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
|
---|---|---|---|---|---|---|
1ce1a82e5295e4bbe129a95b7ec3c6b252b87f45 | guilhermebap/Data-science-personal-study | /Udacity/Foundation AWS/5 - Software Engineering Practices Part 2/Exercise 01 - Unit test/compute_launch.py | 378 | 4.25 | 4 | def days_until_launch(current_day, launch_day):
""""Returns the days left before launch.
current_day (int) - current day in integer
launch_day (int) - launch day in integer
"""
#if launch_day > current_day:
# result = launch_day - current_day
#else:
# result = 0
return launch_day - current_day if launch_day > current_day else 0
|
ffb9898fac43592cc29642c5652a2f4913130dc9 | MrHamdulay/csc3-capstone | /examples/data/Assignment_3/mtttaf002/question2.py | 292 | 4.28125 | 4 | #creating a triangle with height n
#created by tafara mtutu
#23 march 2013
def isosceles(n):
s = "*"
for i in range(1,n+1,1):
print(" "*(n-i), s, sep = "")
s+="**"
height = eval(input("Enter the height of the triangle:\n"))
isosceles(height) |
e764cc9e3a5ecbba5720d730f9b8a13421f64b56 | 17764591637/jianzhi_offer | /剑指offer/62_KthNode.py | 1,637 | 3.765625 | 4 | '''
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8)
中,按结点数值大小顺序第三小结点的值为4。
'''
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# 方法一:
# class Solution:
# # 返回对应节点TreeNode
# def KthNode(self, pRoot, k):
# # write code here
# list_node = []
# if pRoot == None or k <= 0:
# return None
# currentStack = [pRoot]
# while len(currentStack):
# t = currentStack.pop(0)
# list_node.append(t)
# if t.left:
# currentStack.append(t.left)
# if t.right:
# currentStack.append(t.right)
# list_node = sorted(list_node,key = lambda x:x.val)
# if k>len(list_node):
# return None
# return list_node[k-1]
#方法二:
class Solution:
# 返回对应节点TreeNode
def KthNode(self, pRoot, k):
# write code here
#第三个节点是4
#前序遍历5324768
#中序遍历2345678
#后序遍历2436875
#所以是中序遍历,左->根->右
global result
result=[]
self.midnode(pRoot)
if k<=0 or len(result)<k:
return None
else:
return result[k-1]
def midnode(self,root):
if not root:
return None
self.midnode(root.left)
result.append(root)
self.midnode(root.right) |
d04ed393c87ee05b9f33da5b941da47a1bb4eb02 | tyanbz/Algo-courses | /ps/2. simple paint/paint.py | 944 | 3.765625 | 4 | from turtle import *
v = 100 #скорость черепашки
step = 15 #шаг
t = Turtle()
t.color('blue')
t.width(5)
t.shape('circle')
t.pendown()
t.speed(v)
def draw(x, y):
t.goto(x, y)
def move(x, y):
t.penup()
t.goto(x, y)
t.pendown()
def setRed():
t.color('red')
def setGreen():
t.color('green')
def setBlue():
t.color('blue')
def stepUp():
t.goto(t.xcor(), t.ycor() + step)
def stepDown():
t.goto(t.xcor(), t.ycor() - step)
def stepLeft():
t.goto(t.xcor() - step, t.ycor())
def stepRight():
t.goto(t.xcor() + step, t.ycor())
def startFill():
t.begin_fill()
def endFill():
t.end_fill()
t.ondrag(draw)
scr = t.getscreen()
scr.onscreenclick(move)
scr.onkey(setRed,'r')
scr.onkey(setGreen,'g')
scr.onkey(setBlue,'b')
scr.onkey(stepUp,'Up')
scr.onkey(stepDown,'Down')
scr.onkey(stepLeft,'Left')
scr.onkey(stepRight,'Right')
scr.onkey(startFill,'f')
scr.onkey(endFill,'e')
scr.listen()
exitonclick()
|
27b22e7cd140f72febe4364107e2fed57d4927b0 | justin-crabtree/Practice-Python | /Repfields.py | 557 | 4.28125 | 4 | age = 28
print("My age is {0} years".format(age)) # The {0} is replaced with the first format value in the list (age)
print("There are {0} days in {1}, {2}, {3}, {4}, {5}, {6} and {7}"
.format(31, "Jan", "Mar", "May", "Jul", "Aug", "Oct", "Dec"))
print("Jan: {2}, Feb: {0}, Mar: {2}, Apr: {1}, May: {2}, June: {1}, Jul: {2}, Aug: {1}, Sep: {2}, Oct: {1}, Nov: {2}, Dec: {1}"
.format(28, 30, 31))
print()
print("""Jan: {2}
Feb: {0}
Mar: {2}
Apr: {1}
May: {2}
Jun: {1}
Jul: {2}
Aug: {1}
Sep: {2}
Oct: {1}
Nov: {2}
Dec: {1}""".format(28, 30, 31))
|
78cb8cf7efeb151a58d882cd018d2ad3d5850349 | kfrankc/code | /python/coin_change.py | 547 | 3.84375 | 4 | # Coin Change - Dynamic Programming
class Solution:
# vals: array containing value of the coins
# total: total to give back
# returns: minimal number of coins to make a total of t
def coinChange(self, vals, t):
tmparr = [0 for i in range(0, t+1)]
n = len(vals)
for i in range(1, t+1):
minimum = float("inf")
for j in range(0, n):
if (vals[j] <= i):
minimum = min(minimum, tmparr[i-vals[j]])
tmparr[i] = 1 + minimum
return tmparr[t]
# TEST
s = Solution()
vals = [1, 3, 4]
t = 20
print s.coinChange(vals, t) # print 5 |
4a310c9cf89d17dcce1ce0f57d39ada19f367797 | rsquir/learning-ai-python | /old_projects/not_ai/music_tree.py | 666 | 4 | 4 | class Node(object):
def __init__(self, data):
self.data = data
self.children = []
def add_child(self, obj):
self.children.append(obj)
m_i = Node('c')
m_i_i = Node('c')
m_i.add_child(m_i_i)
m_i_i_i = Node('c')
m_i_i.add_child(m_i_i_i)
m_i_i_ii = Node('d')
m_i_i.add_child(m_i_i_ii)
m_i_i_iii = Node('e')
m_i_i.add_child(m_i_i_iii)
m_i_ii = Node('d')
m_i.add_child(m_i_ii)
m_i_ii_i = Node('c')
m_i_ii.add_child(m_i_ii_i)
m_i_ii_ii = Node('d')
m_i_ii.add_child(m_i_ii_ii)
m_i_ii_iii = Node('e')
m_i_ii.add_child(m_i_ii_iii)
for n in m_i.children:
print n.data
value = raw_input("first note (c):\n")
print("note is: ", value) |
176f8a3571be6c9be27b34a6b1d91cf4d79846a2 | irshadkhan248/JavaPythonAndroidMysqlCode | /irshad dir/kamal/demo_python/python/L3/patteren2.py | 313 | 3.703125 | 4 | # wapp to generae:
# A
# B B
# C C C
# D D D D
num=int(input("enter number of line "))
c=65
for i in range(num):
for j in range(i+1):
print(chr(c),end="\t")
print()
c+=1
num1=int(input("enter number of line "))
for k in range(num):
for l in range(k+1):
print("+",end ="\t")
print()
|
15099296ed6f58b0390c6678d2498df44d305a68 | GZHOUW/Algorithm | /LeetCode Problems/DFS/Flood Fill.py | 1,714 | 4.125 | 4 | '''
An image is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535).
Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor, "flood fill" the image.
To perform a "flood fill", consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color as the starting pixel), and so on.
Replace the color of all of the aforementioned pixels with the newColor.
At the end, return the modified image.
Example 1:
Input:
image = [[1,1,1],[1,1,0],[1,0,1]]
sr = 1, sc = 1, newColor = 2
Output: [[2,2,2],[2,2,0],[2,0,1]]
Explanation:
From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected
by a path of the same color as the starting pixel are colored with the new color.
Note the bottom corner is not colored 2, because it is not 4-directionally connected
to the starting pixel.
'''
class Solution:
def floodFill(self, image, sr, sc, newColor):
oldColor = image[sr][sc]
if oldColor != newColor:
self.modifyImage(image, sr, sc, oldColor, newColor)
return image
def modifyImage(self, image, r, c, oldColor, newColor):
image[r][c] = newColor
for x, y in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)): # set faster than list
if 0 <= x < len(image) and 0 <= y < len(image[0]) and image[x][y] == oldColor:
self.modifyImage(image, x, y, oldColor, newColor)
|
eb39189cfa24c993d684331eb6d10720bb04b850 | soeirosantos/python-basico | /00-cadastro_funcionarios.py | 2,051 | 3.59375 | 4 | # -*- coding: utf-8 -*-
def aplicacao():
'''
Programa que controla o cadastro de
funcionários com as funcionalidades de
-- Inclusão
-- Alteração
-- Exclusão
-- Listagem de todos os Funcionários
-- Exibição dos dados de um Funcionário
'''
print "\n:: SISTEMA DE CONTROLE DE FUNCIONÁRIOS ::\n"
cadastrando_funcionarios = True
while cadastrando_funcionarios:
print "O que você deseja fazer?"
print "1 - Incluir um funcionário"
print "2 - Alterar um funcionário"
print "3 - Remover um funcionário"
print "4 - Exbir dados de um funcionário"
print "5 - Listar todos os funcionários"
print "6 - Sair"
opcao = raw_input("Escolha uma opção:")
if opcao == "1":
'''
Inclui um funcionário com os seguintes dados:
cpf, nome, telefone, salario, data_de_admissao
'''
pass
elif opcao == "2":
'''
Altera as informações de um funcionário
específico a partir do CPF informado
'''
pass
elif opcao == "3":
'''
Remove um funcionario específico
a partir do CPF informado
'''
pass
elif opcao == "4":
'''
Exibe os dados de um funcionário
específico a partir do CPF informado
'''
pass
elif opcao == "5":
'''
Exibe os dados de todos os funcionários
'''
pass
elif opcao == "6":
'''
Finaliza o programa
'''
cadastrando_funcionarios = False
else:
print "\nOpção não encontrada, por favor selecione um valor de 1 a 6.\n"
print "\n:: CONTROLE DE FUNCIONARIOS FINALIZADO ::\n"
if __name__ == "__main__":
aplicacao() |
98a9a10a622cb9513ec55ab0ea2263e46966a61c | mishra-ankit-dev/raspberrypi-backup | /code/test/parent.py | 437 | 3.921875 | 4 | class parent():
global parent1,parent2
parent1 = 'father'
#parent2 = 'mother'
def print_parent(self):
global parent2
parent2 = 'mother'
print("your parents are {} and {}".format(parent1,parent2))
class mother(parent):
def print_mother(self):
print("your mother's name is {}".format(parent2))
ankit = parent()
ankit_mother = mother()
ankit.print_parent()
ankit_mother.print_mother()
|
dc9cb123fc583362bdfbe8a629ca062d90a2ad20 | gabriellaec/desoft-analise-exercicios | /backup/user_310/ch32_2019_03_12_18_57_47_179091.py | 116 | 3.828125 | 4 | duvida=input("Tem duvidas? ")
while duvidas!= "não":
print("Pratique mais")
duvidas=input("Tem duvidas? ") |
6a48f4ecf5cd6062e9ac5000d683a347bcea9aff | charlie1kimo/leetcode_judge | /126_word_ladder_2.py | 2,977 | 3.765625 | 4 | """
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the dictionary
For example,
Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
Return
[
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]
Note:
All words have the same length.
All words contain only lowercase alphabetic characters.
"""
class Solution(object):
def findLadders(self, start, end, dict):
"""
:type start: str
:type end: str
:type dict: Set[str]
:rtype: List[List[int]]
idea:
1. BFS: (stop @ end, shortest path)
- build word distance from start (keep out the loop)
- build word's neighbor words list
2. DFS:
- drill down from start. go through neighbor list
- save the path and return
"""
if dict == None or len(dict) == 0:
return []
if not start in dict or not end in dict:
return []
words_map, dist_map = self.bfs(start, end, dict)
ret = []
self.dfs(ret, [], start, end, words_map, dist_map)
return ret
def bfs(self, start, end, dict):
done = False
distance = 0
words_map = {}
dist_map = {}
queue = [start]
while len(queue) > 0 and not done:
size = len(queue)
for i in range(size):
word = queue.pop(0)
if word == end:
done = True
neighbors = self.expand(word, dict)
words_map[word] = neighbors
dist_map[word] = distance
queue += neighbors
distance += 1
return words_map, dist_map
def expand(self, word, dict):
neighbors = []
chars = 'abcdefghijklmnopqrstwvxyz'
for index in range(len(word)):
for c in chars:
if word[index] != c:
new_word = word[:index] + c + word[index+1:]
if new_word in dict:
neighbors.append(new_word)
return neighbors
def dfs(self, ret, path, word, end, words_map, dist_map):
if word == end:
path.append(word)
ret.append(list(path))
path.pop()
return
word_distance = dist_map[word]
for neighbor in words_map[word]:
neighbor_distance = dist_map[neighbor]
if word_distance + 1 == neighbor_distance:
path.append(word)
self.dfs(ret, path, neighbor, end, words_map, dist_map)
path.pop()
if __name__ == "__main__":
start = "a"
end = "c"
dict = set(["a", "b", "c"])
sol = Solution()
print sol.findLadders(start, end, dict)
|
dff2ec9b4ea4d19ba8d6ef400526a6c91e25d74c | yadelab/API_challenge | /step3.py | 1,238 | 3.765625 | 4 | # step3.py
# -------
# Challenge: Locate the needle in the haystack array. You are going to send
# back the position, or index, of the needle string. The API expects indexes
# to start counting at 0.
# Implementation
import requests
import json
__author__ = "Yadel Abraham"
# Fire initial HTTP POST request to API
url ='http://challenge.code2040.org/api/haystack'
init_json = {"token" : "c7ab03d52031cf3b84510fdae8af5689"}
r = requests.post(url, data=init_json)
#convert response to dictionary
dictionary = r.content #dict contains needle & haystack
d = json.loads(dictionary)
needle = d["needle"] #string
haystack_arr = d["haystack"] #array
# Helper to find the 'needle' in the array
def findNeedle(_arr):
""" Takes in the haystack and finds the position of the needle string if
needle is in the array
:param _arr: the haystack array
:return: The position, or "index"
"""
if needle not in _arr:
return None
index = 0
for haystack in haystack_arr:
if haystack == needle:
return index
index+=1
# Send index of needle via HTTP POST
index = str(findNeedle(haystack_arr)) #convert back to string
url2 ='http://challenge.code2040.org/api/haystack/validate'
final_json = {"token" : "c7ab03d52031cf3b84510fdae8af5689", "needle" : index}
req = requests.post(url2, data=final_json) |
188d9bb0ce9e94064337061d10485754284a03d0 | AnthonySimmons/EulerProject | /ProjectEuler/ProjectEuler/Problems/Problem2.py | 739 | 4.03125 | 4 | #Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
#1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
def FibonacciEvenSum(start1, start2, maxValue):
x = start1
y = start2
evenSum = 0
val = 0
while(val <= maxValue):
val = x + y
x = y
y = val
if(val < 100):
print (str(val))
if(val % 2 == 0):
evenSum += val
return evenSum
def Solve():
fibEvenSum = FibonacciEvenSum(0, 1, 4000000)
print ("Sum of Even Fibonnaci Numbers less than 4,000,000: \n" + str(fibEvenSum))
return fibEvenSum |
16d4050c6a2721ed96f1dc8ecf6b1d9a411e4a6e | RoscoBoscovich/cp1404practicals | /prac_06/guitars.py | 830 | 3.53125 | 4 | """Guitar collection program"""
from prac_06.guitar_class import Guitars
def main():
guitar_list = []
print("My Guitars!")
name = " "
while name != "":
name = input("Name: ")
if name == "":
break
year = int(input("Year: "))
cost = int(input("Cost: "))
guitar = Guitars(name, year, cost)
guitar_list.append(guitar)
print("Guitar {} ({}), worth ${} added.".format(guitar.name, guitar.year, guitar.cost))
guitar_list.append(Guitars("Gibson L-5 CES", 1922, 16035.40))
guitar_list.append(Guitars("Line 6 JTV-59", 2010, 1512.9))
print("These are my guitars")
for i, guitar in enumerate(guitar_list):
print("Guitar {}: {} ({}), worth ${} {}".format(i, guitar.name, guitar.year, guitar.cost, guitar.is_vintage()))
main() |
78faf3426912d68396bd3825547bdeb1661c69cc | Clem-Jos/CellScanner | /CellScanner_1.1.0/db_script.py | 19,151 | 3.515625 | 4 | from sqlite3 import *
from shutil import copyfile
import os
"""This file contains all functions linking the program and the database """
def execute(phrase):
"""This function create a connection to the database and execute a command.
:param phrase: str SQL sentence to execute
:return: list of str received from the database after command execution.
"""
conn = connect('bd.db')
res = []
cursor = conn.cursor()
cursor.execute(phrase)
conn.commit()
for row in cursor:
res.append(row)
conn.close()
return res
def getClassNames(isapred=False):
"""This function extract class name from database, if it's for a prediction purpose the class should not be empty.
:param isapred: Boolean, if True only class with at least 2 records with references will be selected. Because
necessary for a prediction.
:return: List of class Names
"""
classes = []
if not isapred:
phrase = """SELECT NAME FROM CLASS"""
else:
phrase = "select name from class inner join (select ID_CLASS,count(ID_RECORD)AS c from CLASS_RECORD where " \
"id_record in(select ID_RECORD from RECORD_REFERENCE) GROUP BY ID_CLASS)as T on class.ID = " \
"T.ID_CLASS where c>=2 "
res = execute(phrase)
for row in res:
classes = classes + list(row)
return classes
def getRecordNames(aClass, isapred=False):
""" This function extract record names from the database for a specific class. If it is a prediction, only record
with a reference will be extracted
:param aClass: str class name
:param isapred: boolean if True, only record from specified class with a reference will be selected.
:return: List of record names
"""
records = []
if not isapred:
phrase = "Select NAME FROM RECORD INNER JOIN (SELECT ID_RECORD FROM CLASS_RECORD INNER JOIN (SELECT ID FROM " \
"CLASS WHERE NAME ='" + aClass + "') AS X ON CLASS_RECORD.ID_CLASS = X.ID) AS Y ON RECORD.ID = " \
"Y.ID_RECORD ORDER BY NAME "
else:
phrase = "select Name from RECORD inner join (select * from RECORD_REFERENCE INNER JOIN CLASS_RECORD ON " \
"RECORD_REFERENCE.ID_RECORD = CLASS_RECORD.ID_RECORD WHERE CLASS_RECORD.ID_CLASS =(SELECT ID FROM " \
"CLASS WHERE NAME = '" + aClass + "') AND IS_A_REF ='T') as T on record.ID = T.ID_RECORD group by " \
"NAME ORDER BY NAME"
res = execute(phrase)
for row in res:
records = records + list(row)
return records
def getReferenceNames(aRecord, aClass):
"""This function extract reference name from database for a specific record :
used to show reference in the update data function
:param aClass:
:param aRecord: str record name
:return: List of reference names
"""
references = []
isARef = []
phrase = "Select NAME,IS_A_REF FROM REFERENCE INNER JOIN (SELECT ID_REFERENCE,IS_A_REF FROM RECORD_REFERENCE " \
"WHERE ID_RECORD IN (SELECT ID FROM RECORD WHERE NAME='" + aRecord + "') AND ID_CLASS =(SELECT ID FROM " \
"CLASS WHERE NAME ='" + aClass + \
"')ORDER BY IS_A_REF DESC) AS Y ON REFERENCE.ID = Y.ID_REFERENCE "
res = execute(phrase)
for row in res:
a = list(row)
references.append(a[0])
isARef.append(a[1])
return references, isARef
def changeReferences(aRecord, newRefs):
"""This function update the active references for a specific record.
:param aRecord: str record name
:param newRefs: List of references to set as active.
:return: Only change db content so nothing is return
"""
phrase = "UPDATE RECORD_REFERENCE SET IS_A_REF='F' WHERE ID_RECORD =(SELECT ID FROM RECORD WHERE NAME ='" + \
aRecord + "')"
execute(phrase)
for aRef in newRefs:
phrase2 = "UPDATE RECORD_REFERENCE SET IS_A_REF='T' WHERE ID_REFERENCE =(SELECT ID FROM REFERENCE WHERE " \
"NAME ='" + aRef + "'); "
execute(phrase2)
def addClass(className):
"""Create a new class in the database if not exist
:param className: str for class name
:return: boolean if it exist or not
"""
if doesntExsist('CLASS', className):
phrase = "INSERT INTO CLASS(NAME) VALUES ('" + className + "')"
execute(phrase)
return False
else:
return True
def addFc(fcName):
if doesntExsist('FLOWCYTOMETER', fcName):
phrase = "INSERT INTO FLOWCYTOMETER(NAME) VALUES ('" + fcName + "')"
execute(phrase)
return False
else:
return True
def addRecord(aClass, recordName):
"""Add a new record from a specific class in the database if it doesn't exist in the database
:param aClass: str for class name
:param recordName: str for record name
:return: boolean if it exist or not
"""
if doesntExsist('RECORD', recordName): # or if class_record doesn't exist
phrase = "INSERT INTO RECORD(NAME) VALUES ('" + recordName + "'); "
execute(phrase)
exist = execute('SELECT * FROM CLASS_RECORD WHERE ID_CLASS =(SELECT ID FROM CLASS WHERE NAME ="' + aClass +
'") AND ID_RECORD =(SELECT ID FROM RECORD WHERE NAME="' + recordName + '")')
if not exist:
phrase = "INSERT INTO CLASS_RECORD(ID_CLASS,ID_RECORD) VALUES ((SELECT ID FROM CLASS WHERE NAME ='" + aClass + \
"' ),(SELECT ID FROM RECORD WHERE NAME ='" + recordName + "')) "
execute(phrase)
return False
return True
def addReference(aRecord, fileName, aClass): # don't add a link if exist already #class
""" Add a reference to a record, if already in the database, add only a link to the record. If already exist only a
link with the record is created. If link already exist, ??? does it add the red or not???? #
:param aClass:
:param aRecord:
:param fileName:
:return:
"""
fileName = fileName.replace('\\', '/')
referenceName = fileName.split('/')[-1]
referenceName = referenceName.replace(' ', '_')
# give an option to chose the name of the reference popup
if doesntExsist('REFERENCE', referenceName):
if not os.path.exists('references/' + referenceName):
copyfile(fileName, 'references/' + referenceName) #
phrase = "INSERT INTO REFERENCE(NAME) VALUES ('" + referenceName + "'); "
execute(phrase)
exist = execute(
"SELECT * FROM RECORD_REFERENCE WHERE ID_RECORD IN (SELECT ID FROM RECORD WHERE NAME ='" + aRecord +
"') AND ID_REFERENCE =(SELECT ID FROM REFERENCE WHERE NAME='" + referenceName +
"') AND ID_CLASS =(SELECT ID FROM CLASS WHERE NAME='" + aClass + "')")
if not exist:
phrase = "INSERT INTO RECORD_REFERENCE(ID_RECORD,ID_CLASS,ID_REFERENCE,IS_A_REF) VALUES ((SELECT ID_RECORD " \
"FROM CLASS_RECORD WHERE ID_RECORD IN (SELECT ID FROM RECORD WHERE NAME ='" + aRecord + "' ) AND " \
"ID_CLASS=(SELECT ID FROM CLASS WHERE NAME ='" + aClass + "')),(SELECT ID FROM CLASS WHERE NAME ='" + \
aClass + "'),(SELECT ID FROM REFERENCE WHERE NAME ='" + referenceName + "'),'F') "
execute(phrase)
return False
return True
def addChannels(fc,channels,ref, update):
# get fc id from fc name
phrase = "SELECT ID FROM FLOWCYTOMETER WHERE NAME='"+fc+"'"
res = execute(phrase)
fcid = res[0][0]
if update:
# del all values from table channels where fc id = fc id
phrase = "DELETE FROM CHANNELS WHERE ID_FC ="+str(fcid)
res = execute(phrase)
#for each channels name
for i in range(len(channels)):
if ref[i] != '':
#get the id from the ref name
# crete the phrase
phrase = "INSERT INTO CHANNELS (NAME,ID_FC,ID_REF_CN) VALUES ('"+channels[i]+"',"+str(fcid)+",(SELECT ID FROM REF_CHANNELS WHERE NAME='"+str(ref[i])+"'))"
print(phrase)
else:
phrase = "INSERT INTO CHANNELS (NAME,ID_FC) VALUES ('" + channels[i] + "'," + str(fcid) + ")"
print(phrase)
#create the phrase
res = execute(phrase)
def updateFc():
phrase = "DELETE FROM FLOWCYTOMETER WHERE ID NOT IN (SELECT ID_FC FROM CHANNELS INNER JOIN FLOWCYTOMETER WHERE FLOWCYTOMETER.ID=CHANNELS.ID_FC GROUP BY ID_FC)"
execute(phrase)
return
def doesntExsist(table, name):
"""Ask the database if an item is in a specific table or not
:param table: str for tale name
:param name: str for item name
:return: Bollean, True if the item doesn't exsist
"""
phrase = "SELECT NAME FROM " + table + " WHERE NAME ='" + name + "'"
res = execute(phrase)
a = []
for val in res:
a = a + list(val)
if not a:
return True
else:
return False
def delClass(aClass):
"""Delete a class from the database, delete all link with record, delete record if the record is not liked to
another class. Delete references, if not linked to any record.
:param aClass: str class name
:return: Changes done in the database, nothing to return
"""
phrase = "DELETE FROM CLASS_RECORD WHERE ID_CLASS =(SELECT ID FROM CLASS WHERE NAME = '" + aClass + "'); "
execute(phrase)
phrase = "DELETE FROM CLASS WHERE NAME = '" + aClass + "'; "
execute(phrase)
phrase = "DELETE FROM RECORD WHERE ID IN (SELECT ID FROM RECORD LEFT JOIN CLASS_RECORD ON RECORD.ID = " \
"CLASS_RECORD.ID_RECORD WHERE CLASS_RECORD.ID_RECORD IS NULL); "
execute(phrase)
phrase = "DELETE FROM RECORD_REFERENCE WHERE ID_RECORD IN (SELECT RECORD_REFERENCE.ID_RECORD FROM RECORD_" \
"REFERENCE LEFT JOIN RECORD ON RECORD_REFERENCE.ID_RECORD = RECORD.ID WHERE RECORD.ID IS NULL); "
execute(phrase)
phrase = "DELETE FROM REFERENCE WHERE ID IN (SELECT ID FROM REFERENCE LEFT JOIN RECORD_REFERENCE ON " \
"REFERENCE.ID = RECORD_REFERENCE.ID_REFERENCE WHERE RECORD_REFERENCE.ID_REFERENCE IS NULL); "
execute(phrase)
delRefFile()
def delRecord(aClass, aRecord):
""" Delete a record from a class, delete reference from the deleted record if not liked to other records or if the
record is not liked to another class
:param aClass: str for class name
:param aRecord: str for record name
:return: Changes done in the database, nothing to return
"""
phrase = "DELETE FROM CLASS_RECORD WHERE ID_RECORD =(SELECT ID FROM RECORD WHERE NAME = '" + aRecord + \
"')AND ID_CLASS =(SELECT ID FROM CLASS WHERE NAME ='" + aClass + "');" # for a specific class ?
execute(phrase)
phrase = "DELETE FROM RECORD WHERE ID IN (SELECT ID FROM RECORD LEFT JOIN CLASS_RECORD ON " \
"RECORD.ID = CLASS_RECORD.ID_RECORD WHERE CLASS_RECORD.ID_RECORD IS NULL); "
execute(phrase)
phrase = "DELETE FROM RECORD_REFERENCE WHERE ID_RECORD IN (SELECT RECORD_REFERENCE.ID_RECORD FROM " \
"RECORD_REFERENCE LEFT JOIN RECORD ON RECORD_REFERENCE.ID_RECORD = RECORD.ID WHERE RECORD.ID IS NULL); "
execute(phrase)
phrase = "DELETE FROM REFERENCE WHERE ID IN (SELECT ID FROM REFERENCE LEFT JOIN RECORD_REFERENCE ON " \
"REFERENCE.ID = RECORD_REFERENCE.ID_REFERENCE WHERE RECORD_REFERENCE.ID_REFERENCE IS NULL); "
execute(phrase)
delRefFile()
def delRefFile():
phrase = 'SELECT NAME FROM REFERENCE'
filesdb = execute(phrase)
filedb=[]
files = os.listdir('./References/')
for row in filesdb:
a = list(row)
filedb = filedb + a
for f in files:
if f not in filedb:
os.remove('./References/'+f)
def delReference(aRecord, aReference, aClass):
"""From a record name, delete the reference associated to the record, and delete the reference from the database if
not liked to another record.
:param aClass:
:param aRecord: str name of the record
:param aReference: str name for a reference
:return: Changes done in the database, nothing to return
"""
phrase = "DELETE FROM RECORD_REFERENCE WHERE ID_REFERENCE =(SELECT ID FROM REFERENCE WHERE NAME = '" + aReference +\
"') AND ID_RECORD IN (SELECT ID FROM RECORD WHERE NAME ='" + aRecord + \
"') AND ID_CLASS=(SELECT ID FROM CLASS WHERE NAME='" + aClass + "');"
execute(phrase)
phrase = "DELETE FROM REFERENCE WHERE ID IN (SELECT ID FROM REFERENCE LEFT JOIN RECORD_REFERENCE ON " \
"REFERENCE.ID = RECORD_REFERENCE.ID_REFERENCE WHERE RECORD_REFERENCE.ID_REFERENCE IS NULL); "
execute(phrase)
if not execute('SELECT * FROM REFERENCE WHERE NAME ="' + aReference + '"'):
os.remove('References/' + aReference)
def getCnFromRef(refName,fcName):
phrase ="SELECT NAME from CHANNELS WHERE ID_FC =(SELECT ID FROM FLOWCYTOMETER WHERE NAME ='"+fcName+"') AND ID_REF_CN =(SELECT ID FROM REF_CHANNELS WHERE NAME ='"+refName+"')"
res = execute(phrase)
if res == []:
return res
else :
return res[0][0]
def getReferences(aRecord, aClass):
"""This function extract active references (checked in the 'update data' window) from a record name.
:param aClass:
:param aRecord: str record name
:return: list of reference names
"""
references = []
phrase = "Select NAME FROM REFERENCE INNER JOIN (Select ID_REFERENCE, IS_A_REF FROM RECORD_REFERENCE where " \
"ID_CLASS =(select id from class where name ='" + aClass + "') and ID_RECORD=(select id from record " \
"where name ='" + aRecord + "'))AS Y ON REFERENCE.ID = Y.ID_REFERENCE WHERE IS_A_REF='T' "
res = execute(phrase)
for row in res:
a = list(row)
references = references + a
return references
def getChannels():
"""This function extract the channels list from the database according to the active flowcytometer."""
# get the flowcytometer number active
channels=[]
toreplace=[]
replaced=[]
dict={}
phrase = "SELECT VALUE FROM PARAMETER WHERE ID ='fc' AND ACTIVE=1"
res = execute(phrase)
if res == []:
channels=[]
replaced = []
dict = {}
else :
fc = res[0][0]
# get the list of param + the list changed channels
phrase2 = "SELECT NAME,ID_REF_CN FROM CHANNELS WHERE ID_FC ="+fc
res2 = execute(phrase2)
for row in res2:
a = list(row)
channels.append(a[0])
toreplace.append(a[1])
phrase3 = "SELECT NAME,ID FROM REF_CHANNELS "
res3 = execute(phrase3)
Lname = []
Lid = []
replaced=channels.copy()
for row in res3:
a = list(row)
Lname.append(a[0])
Lid.append(a[1])
for i in range(len(Lid)):
dict[channels[toreplace.index(Lid[i])]] = Lname[i]
for key,value in dict.items():
replaced = [value if x == key else x for x in replaced]
return channels,replaced, dict
def getFlowcytometerList():
phrase = "SELECT NAME FROM FLOWCYTOMETER"
res = execute(phrase)
fc = []
for row in res:
a = list(row)
fc.append(a[0])
return fc
def getRefChannels():
phrase = "SELECT NAME,DESC FROM REF_CHANNELS"
res = execute(phrase)
channels = []
desc = []
for row in res:
a = list(row)
channels.append(a[0])
desc.append(a[1])
return channels, desc
def getSpecies():
"""Ask in the database all species name referenced for the species auto-completer.
:return: List of bacterial species names
"""
phrase = "SELECT NAME FROM REF_SPECIES WHERE ID_RECORD IS NULL"
res = execute(phrase)
classes = []
for row in res:
classes = classes + list(row)
return classes
def getParamValue(param):
"""Get a parameter value from the database.
:param param: Parameter name
:return: string parameter value
"""
phrase = "SELECT VALUE FROM PARAMETER WHERE ACTIVE =1 AND ID ='" + param + "'"
res = execute(phrase)
if res==[]:
return 'NULL'
return res[0][0]
def getFcValue():
v = getParamValue('fc')
phrase = "SELECT NAME FROM FLOWCYTOMETER WHERE ID ="+v
res = execute(phrase)
if res == []:
return []
else:
return res[0][0]
def activeDefaultParam():
"""Set all default parameter as active in the database
:return: Changes done in the database, nothing to return
"""
phrase = "UPDATE PARAMETER SET ACTIVE = 1 WHERE STANDARD=1;"
execute(phrase)
phrase = "UPDATE PARAMETER SET ACTIVE = 0 WHERE STANDARD=0 "
execute(phrase)
def desactivateParam():
"""Desactivate in the database all parameters that are set active.
:return: Changes done in the database, nothing to return
"""
phrase = "UPDATE PARAMETER SET ACTIVE = 0 WHERE ACTIVE = 1 AND ID NOT IN ('fc')"
execute(phrase)
def desactivateFc():
phrase = "UPDATE PARAMETER SET ACTIVE = 0 WHERE ACTIVE = 1 AND ID ='fc'"
execute(phrase)
def removeUnusedParam():
"""Delete from the database all parameter values that are not used and not initial parameters
:return: Changes done in the database, nothing to return
"""
phrase = "DELETE FROM PARAMETER WHERE ACTIVE = 0 AND STANDARD = 0"
execute(phrase)
def updateReferenceInfo():
# select reference from ref directory
refFiles = [a for a in os.listdir('./references') if os.path.isfile(os.path.join('./references', a))]
refFilesStr = '("'+'","'.join(refFiles)+'")'
phrase = 'DELETE FROM REFERENCE WHERE NAME NOT IN '+refFilesStr
execute(phrase)
# remove all line in db that are not in the ref file list.
def saveParam(paramName, paramValue):
"""Update a parameter in the parameter table in the database
:param paramName: Name of the parameter
:param paramValue: new value of the parameter
:return: Changes done in the database, nothing to return
"""
phrase = "INSERT INTO PARAMETER VALUES('" + paramName + "','" + str(paramValue) + "',1,0)"
execute(phrase)
def saveFc(value):
phrase = "SELECT ID FROM FLOWCYTOMETER WHERE NAME ='"+value+"'"
res = execute(phrase)
if res:
saveParam('fc',res[0][0])
def delFc(fcName):
phrase = "DELETE FROM CHANNELS WHERE ID_FC =(SELECT ID FROM FLOWCYTOMETER WHERE NAME ='"+fcName+"')"
execute(phrase)
phrase = "DELETE FROM FLOWCYTOMETER WHERE NAME ='"+fcName+"'"
execute(phrase) |
3521cd212a88ebb7eac8e34f68cb6928d850d907 | aaaaaaason/codeforces | /BusToUdayland.py | 466 | 3.75 | 4 |
n = int(input())
rows = [input() for _ in range(n)]
def check(rows: list, r: int, c: int) -> bool:
if rows[r][c] == rows[r][c+1] and rows[r][c] == 'O':
rows[r] = rows[r][:c] + '++' + rows[r][c+2:]
return True
return False
found = False
for i, row in enumerate(rows):
if check(rows, i, 0) or check(rows, i, 3):
found = True
break
if found:
print('YES')
for row in rows:
print(row)
else:
print('NO')
|
6a00f0ca9fa632aab7f9c362b3f647c6682c5507 | swadhikar/python_and_selenium | /python_practise/Interview/threads/images/thread_locker.py | 1,269 | 3.765625 | 4 | from contextlib import contextmanager
from threading import Lock, Thread, current_thread
from time import sleep
# Run a function
# The function must be protected by thread lock
# After the function gets executed, the lock should be released
sum_of_values = 0
@contextmanager
def acquire_thread_lock():
lock = Lock()
try:
lock.acquire()
yield
finally:
lock.release()
def value_incrementer(num_times):
with acquire_thread_lock():
global sum_of_values
for _ in range(num_times):
sum_of_values += 1
if __name__ == '__main__':
list_times = [4543, 3423, 2422, 1253, 6233, 5231]
list_threads = list()
print('Creating "{}" thread instances ...'.format(len(list_times)))
for times in list_times:
_thread = Thread(target=value_incrementer, args=(times,), name=str(times))
list_threads.append(_thread)
print('Starting thread instances ...')
for _thread in list_threads:
_thread.start()
print('Started jobs. Waiting for completion ...')
for _thread in list_threads:
_thread.join()
print('All threads has been completed!')
print('Final sum:', sum_of_values)
"""
Final sum: 45964493
Final sum: 45964493
""" |
d1eab49e66cd7578e0dc835d8cee113a94e661b7 | zeelp741/Data-Strucutures | /PriorityQueue_linked.py | 5,647 | 3.5 | 4 | # Imports
from copy import deepcopy
class PQNode:
def __init__(self, element):
"""
-------------------------------------------------------
Initializes a priority queue node that contains a copy of
the given element and a link pointing to None.
Use: node = PQNode(element)
-------------------------------------------------------
Parameters:
element - data element for node (?)
Returns:
a new PriorityQueue object (PQNode)
-------------------------------------------------------
"""
self._next = None
self._value = deepcopy(element)
class PriorityQueue:
def __init__(self):
"""
-------------------------------------------------------
Initializes an empty priority queue.
Use: pq = PriorityQueue()
-------------------------------------------------------
Returns:
a new PriorityQueue object (PriorityQueue)
-------------------------------------------------------
"""
self._front = None
self._rear = None
self._count = 0
def isEmpty(self):
"""
-------------------------------------------------------
Determines if the priority queue is empty.
Use: b = pq.isEmpty()
-------------------------------------------------------
Returns:
True if priority queue is empty, False otherwise.
-------------------------------------------------------
"""
return self._count == 0
def __len__(self):
"""
-------------------------------------------------------
Returns the length of the priority queue.
Use: n = len(pq)
-------------------------------------------------------
Returns:
the number of elements in the priority queue.
-------------------------------------------------------
"""
return self._count
def insert(self, element):
"""
-------------------------------------------------------
A copy of element is inserted into the priority queue.
Elements are stored in priority order. The minimum element
has the highest priority.
Use: pq.insert(element)
-------------------------------------------------------
Parameters:
element - a data element (?)
Returns:
None
-------------------------------------------------------
"""
current = self._front
previous = None
while current is not None and current._value < element:
previous = current
current = current._next
if current is None:
# Reached end of Queue or Queue empty
new_node = PQNode(element)
if self._count == 0:
self._rear = new_node
self._front = new_node
else:
# Reached end of Queue
self._rear._next = new_node
self._rear = new_node
self._count += 1
else:
# Somewhere in Queue
new_node = PQNode(element)
if previous is None:
# Beginning of Queue
self._front = new_node
else:
# Not beginning, update references
previous._next = new_node
self._count += 1
return
def remove(self):
"""
-------------------------------------------------------
Removes and returns the highest priority element from the
priority queue.
Use: element = pq.remove()
-------------------------------------------------------
Returns:
element - the highest priority element in the priority queue -
the element is removed from the priority queue. (?)
-------------------------------------------------------
"""
assert self._count > 0, "Cannot remove from an empty priority queue"
element = self._front._value
self._front = self._front._next
self._count -= 1
if self._count == 0:
self._rear = None
return deepcopy(element)
def peek(self):
"""
-------------------------------------------------------
Peeks at the highest priority element of the priority queue.
Use: v = pq.peek()
-------------------------------------------------------
Returns:
a copy of the highest priority element in the priority queue -
the element is not removed from the priority queue. (?)
-------------------------------------------------------
"""
assert self._count > 0, "Cannot peek at an empty priority queue"
return deepcopy(self._front._value)
def __iter__(self):
"""
USE FOR TESTING ONLY
-------------------------------------------------------
Generates a Python iterator. Iterates through the queue
from front to rear.
Use: for value in pq:
-------------------------------------------------------
Returns:
value - the next value in the priority queue (?)
-------------------------------------------------------
"""
curr = self._front
while curr is not None:
yield curr._value
curr = curr._next
|
adffbd365423fb9421921d4ca7c0f5765fe0ac60 | denvinnpaolo/AlgoExpert-Road-to-Cerification-Questions | /Arrays/ThreeNumSum.py | 1,745 | 4.34375 | 4 | # ThreeNumSum
# Difficulty: Easy
# Instruction:
# Write a function that takes in a non-empty array of distinct integers and an
# integer representing a target sum. The function should find all triplets in
# the array that sum up to the target sum and return a two-dimensional array of
# all these triplets. The numbers in each triplet should be ordered in ascending
# order, and the triplets themselves should be ordered in ascending order with
# respect to the numbers they hold.
# If no three numbers sum up to the target sum, the function should return an
# empty array.
# Solution 1:
def threeNumberSum(array, targetSum):
# Write your code here.
array.sort()
ans = []
for i in range(len(array)):
left = i + 1
right = len(array) - 1
while left < right:
curSum = array[i] + array[left] + array[right]
if curSum == targetSum:
ans.append([array[i], array[left], array[right]])
left += 1
right -= 1
elif curSum < targetSum:
left += 1
elif curSum > targetSum:
right -= 1
return ans
# Solution 2:
ans = []
d ={}
for i in range(len(array)):
for j in range(len(array)):
if i == j:
continue
num = targetSum - (array[i] + array[j])
if num in d:
d[num].append([array[i], array[j]])
else:
d[num] = [[array[i], array[j]]]
for i in range(len(array)):
if array[i] in d:
for j in range(len(d[array[i]])):
if array[i] in d[array[i]][j]:
continue
possible_ans = d[array[i]][j][0] + d[array[i]][j][1] + array[i]
if possible_ans == targetSum:
d[array[i]][j].append(array[i])
d[array[i]][j].sort()
if d[array[i]][j] not in ans:
ans.append(d[array[i]][j])
ans.sort()
return ans
|
4393bf305299eea380c630b0486e73aed1c29102 | RegisSchulze/challenge-card-game-becode | /utils/game.py | 3,941 | 3.78125 | 4 | from utils.card import Deck
from math import floor
class Board:
"""
Class Board, that represents the status of the game
containing four attributes
-attribute players that is a list of Player containing all the players
-attribute turn_count that is an int and keeps record of how many rounds have been played
a round is done when all players have played one card
-attribute active_cards is a list of Card containing the last card played by each player
-attribute history_cards is a list of Card containing all cards that have been played up to this point
with the exception of the cards in attribute active_cards
"""
def __init__(self, players):
self.players = players
self.turn_count = 0
self.active_cards = []
self.history_cards = []
def start_game(self):
card_deck = Deck() # creating an object of type Deck after importing from card.py
card_deck.fill_deck() # fill the deck using method fill_deck of Deck
card_deck.shuffle() # shuffle the deck using method shuffle of Deck
card_deck.distribute(self.players) # distribute the deck among the players, each player gets same amouts
# of cards
number_of_players = len(self.players)
number_of_rounds = floor(52 / number_of_players)
for i in range(number_of_rounds): # iterate over the number of rounds
highest_value = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
highest_value_index = 0
icon = ['♥', '♦', '♣', '♠']
icon_index = 0
player = 0
for j in range(number_of_players): # iterate over the number of players
active_card = self.players[j].play() # method play of Player is called upon
if highest_value.index(active_card.value) >= highest_value_index: # NICE TO HAVE FEATURES
highest_value_index = highest_value.index(active_card.value)
if icon.index(active_card.icon) >= icon_index:
icon_index = icon.index(active_card.icon)
winner = player # winner of the round
if self.turn_count != 0: # in the first round no history cards allowed
self.history_cards.append(self.active_cards.pop(0))
self.active_cards.append(active_card) # the cards that have been played in this round are added to
# active_cards
player += 1
self.players[winner].count += 1 # increase score of winner of the round
print(f'Player {self.players[winner].name} has won this round')
self.turn_count += 1
print(f'The turn count is {self.turn_count}' #print turn_count
f'\nThe list of active cards is')
for l in range(len(self.active_cards)): # print the cards in active_cards
print(f'{self.active_cards[l].value} {self.active_cards[l].icon}')
print(f'The number of cards in the history_cards is {len(self.history_cards)}') #print number of cards in
print("=====================================================================================") # history_cards
end_winner = 0 # retrieving winner with highest score
current_winner = 0
highest_score = 0
for i in self.players:
if i.count >= highest_score:
highest_score = i.count
end_winner = current_winner
current_winner += 1
print(f'Player {i.name} has a score of {i.count}')
print(f'Player {self.players[end_winner].name} has won the game!')
print('Well done, the game is finished. Hope you enjoyed it!!!')
|
1d58d17040b4e94522bbd9256cacc9b2a9c39680 | lvyu-imech/PyVT | /pyvt/myio/binarytecplot/binary2asciifile.py | 2,479 | 3.9375 | 4 | import struct
class Binary2AsciiFile(object):
"""
Binary2AsciiFile:
this class is a helpfull class to read a binary file characters.
Mainly, converts bytes to char, long integers, float, double, text
Binary2AsciiFile( filename )
"""
def __init__(self, filename):
"""
Arguments:
** filename = str() # the name of the binary file.
"""
self.filename = filename
try:
self.binaryfile = open(filename,'rb')
except IOError:
print("file is open")
def _readLine (self, size = 4):
"""
This is the Kernel of the class that read
some bytes from the file.
The default size is 4 bytes.
** size = int() # the number of bytes
"""
return self.binaryfile.read(size)
def _readChar (self, size = 4):
"""
This method reads a sequence of the bytes from
the file and converts to utf-8 format.
"""
return self._readLine(size).decode("utf-8")
def _readLongInteger (self):
"""
read struct module for more information.
This function reads a long integer.
"""
return struct.unpack('l', self._readLine(4)) [0]
def _readInteger (self):
"""
This function reads 4 bytes from the file and
convert to an integer.
"""
return struct.unpack('i', self._readLine(4)) [0]
def _readFloat (self):
"""
This function reads 4 bytes from the file and
convert to a float number.
"""
return struct.unpack('f', self._readLine(4)) [0]
def _readDouble (self):
"""
This function reads 4 bytes from the file and
convert to a float number.
"""
return struct.unpack('d', self._readLine(8)) [0]
def _read_ListOfIntegers(self, n):
return [self._readInteger() for _ in range(n)]
def _Binary2Ascii (self):
"""
This method reads a string from a file.
The method continuously reads the file untile the null char
is read.
"""
title = ""
while True:
ascii = self._readLine().decode('utf-8').replace(chr(0),"")
if ascii=="": break
title += ascii
return title
|
bbcd56895dff583787c16e847b17c5f462da48e1 | cyclony/pythonTrainingProject | /dataModel.py | 729 | 3.609375 | 4 | import random
class Factor:
def __init__(self, n):
self.i = 1
self.total = 1
self.n = n
def __iter__(self):#python解释器一旦碰到的类有这个方法,则该类对象是iterable的
return self
def __next__(self): #for循环执行的时候会内部调用该方法来实现迭代。
if self.i == self.n:
raise StopIteration
self.total = self.total * self.i
self.i += 1
return self.total
factor = Factor(10)
for i in factor:
print(i)
l = [x*y for x in range(5)
for y in range(10)
if x>0 and y>0]
odds = [x for x in range(100)
if x%2 != 0]
print("this is odds:")
print(odds)
l += [123,456,789]
|
e28449c4c08c2aa8a3dd63a4e8f83a9ac2701083 | EdwardLijunyu/first-room | /数据结构/16链表中环的入口节点.py | 1,253 | 3.84375 | 4 | # 给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
'''
思路:
1.先确定链表是否含有环,通过快慢两个指针一次移动,如果没有快指针能追上慢指针就说明有环
2.确定有环之后,当快慢指针重合的时候,再让一个指针成从头指针开始,两个同时移动,直到两个指针重合时就是环的入口节点
'''
# -*- coding:utf-8 -*-
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def EntryNodeOfLoop(self, pHead):
#先判断是否有环
slow_node=pHead
fast_node = pHead
while fast_node.next!=None and fast_node.next.next!=None:
fast_node=fast_node.next.next
slow_node=slow_node.next
if fast_node==slow_node:
break
if fast_node.next==None or fast_node.next.next==None:
return None #无环返回None
# 执行2
if fast_node==slow_node:
slow_node=pHead
while fast_node!=slow_node:
fast_node=fast_node.next
slow_node=slow_node.next
return slow_node
#提交成功
|
d4ec950993dd2edf31ab707dceef429c71fbf118 | mtpatil10/MechITgr8 | /Lecture 3 and 4-Variables in python.py | 443 | 3.8125 | 4 | print('navin\'s "laptop"') # \ directs to ignore '
print('navin'+ ' navin')
print(r'docs\navin') # r which is a row string directs to ignore special meaning of \n
print() # for empty line
name='youtube' # y o u t u b e
# 0 1 2 3 4 5 6
#-7 -6 -5 -4 -3 -2 -1
print(name)
print(name[0])
print(name[-1])
print(name[1:])
print(name[:4])
print('my'+name[3:7])
print(len(name))
|
6580df6e197ac3be075cd2aeb5f3c48a1b4cb37f | Dqvvidq/Nauka | /Operacje na plikach/main.py | 809 | 3.640625 | 4 | import os
import csv
# tworzenie ścieżki dostępu do pliku
os.path.join("czesc.txt")
# tworzenie pliku i zapisywanie coś na nim
st = open("czesc.txt", "w")
st.write("czesc")
st.close()
# otwieranie pliku i jego zawartości
with open("czesc.txt", "r") as f:
print(f.read())
# umieszanie zmian w koontenerze w celu otwierania pliku w programie
my_list = list()
with open("st.txt", "r") as f:
my_list.append(f.read())
print(my_list)
print(my_list)
#pliki csv
with open("st.csv", "w", newline='') as v:
write = csv.writer(v, delimiter=",")
write.writerow(["jeden", "dwa", "trzy"])
write.writerow(["cztery", "piec", "szesc"])
with open("st.csv", "r") as v:
r = csv.reader(v, delimiter=",")
for row in r:
print(",".join(row)) |
dac9f9ce7a485fa8fb7787e227ce88422b7b4060 | JHPolarBear/TensorFlow_Practice | /03.Classification/04-1_Logistic_Classification_Logit_zoo.py | 2,780 | 3.546875 | 4 | ## 소스 출처 : https://hunkim.github.io/ml/
## 아래 코드는 위 링크에서 학습한 머신 러닝 코드를 실습한 내용을 정리해 놓은 것으로,
## 관련된 모든 내용은 원 링크를 참고해주시가 바랍니다
## Source Originated from : https://hunkim.github.io/ml/
## The following code is a summary of the machine learning code learned from the link above.
## Please refer to the original link for all related contents.
# import module
import tensorflow as tf
import matplotlib as plt
import numpy as np
# Load data
xy = np.loadtxt('data-04-zoo.csv', delimiter = ',', dtype = np.float32)
x_data = xy[:, 0:-1]
y_data = xy[:, [-1]]
x_len = len(x_data[1])
nb_classes = 7
print(x_len, nb_classes)
# X && Y Data
# Data가 행렬인 경우 shape에 유의하자
X = tf.placeholder(tf.float32, shape=[None, x_len])
Y = tf.placeholder(tf.int32, shape=[None, 1]) #0~6 사이 하나의 값을 갖게 됨 shape(?,1)
Y_one_hot = tf.one_hot(Y, nb_classes) #클래스(레이블) 갯수만큼의 one_hot 행렬을 생성 shape(?,1,7)
Y_one_hot = tf.reshape(Y_one_hot, [-1, nb_classes]) #one_hot 함수가 불필요한 axis를 추가로 만들어 이를 제거 shape(?,7)
# 각 x_Data에 대응하는 W var
W = tf.Variable(tf.random_normal([x_len, nb_classes]), name = 'weight')
b = tf.Variable(tf.random_normal([nb_classes]), name = 'bias')
# H(x) 방정식 선언
logits = tf.matmul(X,W) + b
hypothesis =tf.nn.softmax(logits)
# Cost 방정식(Cross entropy) - tf에서 제공되는 버전
# logit과 one hot(위 식의 Y)를 받아 -tf.reduce_sum(Y*tf.log(hypothesis), axis=1) 를 실행
cost_i = tf.nn.softmax_cross_entropy_with_logits_v2(logits = logits, labels = Y_one_hot)
cost = tf.reduce_mean(cost_i)
#위의 cost minimization을 해주는 optimizer
optimizer = tf.train.GradientDescentOptimizer(learning_rate = 0.1).minimize(cost)
# 정확도 체크
prediction = tf.argmax(hypothesis, 1) #현재 hypohtesis에서 나온 값의 클래스 인덱스
correct_prediction = tf.equal(prediction, tf.argmax(Y_one_hot, 1)) # 실제 인덱스
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # 위 2개를 비교하여 일치하는 확률 구함
# Create session
with tf.Session() as sess:
# variable 초기화
sess.run(tf.global_variables_initializer())
feed = {X: x_data, Y: y_data}
# 학습 진행
for step in range(2001):
sess.run(optimizer, feed_dict = feed)
if step%100 == 0:
loss, acc = sess.run([cost, accuracy], feed_dict=feed)
print("stdp: {:5}\tLoss: {:.3f}\tAcc: {:.2%}".format(step, loss, acc))
pred = sess.run(prediction, feed_dict = {X: x_data})
for p, y in zip(pred, y_data.flatten()):
print("[{}] Prediction: {} True Y: {}".format(p == int(y), p, int(y)))
|
7b45382df7bdf9351d1237b42375a5a90a25abf2 | palmeida7/dayfive-python | /func_exercises.py | 4,287 | 4.59375 | 5 | """ #1. Madlib function
Write a function that accepts two arguments: a name and a subject.
The function should return a String with the name and subject interpolated in.
For example:
madlib("Jenn", "science")
# "Jenn's favorite subject is science."
madlib("Jeff", "history") """
# "Jeff's favorite subject is history."
#Provide default arguments in case one or both are omitted.
""" def favorite(name, subject):
return (f"{name}'s favorite subject is {subject}.")
print(favorite("Jenn", "science"))
print(favorite("Jeff", "history")) """
########
#2. Celsius to Fahrenheit conversion
#The formula to convert a temperature from Celsius to Fahrenheit is:
#F = (C * 9/5) + 32
#Write a function that takes a temperature in Celsius, converts it Fahrenheit, and returns the value
#import math
""" F= 0
def conversion(C, F):
return (C * 9/5) + 32
print(conversion(20, F)) """
#3. Fahrenheit to Celsius conversion
""" The formula to convert a temperature from Fahrenheit to Celsius is:
C = (F - 32) * 5/9
Write a function that takes a temperature in Fahrenheit, converts it to Celsius, and returns the value. """
#import math
""" C = 0
def conversion(F, C):
return (F - 32) * 5/9
print(conversion(70, C)) """
#4. is_even function
#Write a function that accepts a number as an argument and returns a Boolean value.
#Return True if the number is even; return False if it is not even.
""" x = int(input("Please give a number:\n"))
def even(x):
if x % 2 == 0:
print("This is even.")
return True
else:
print("This is odd.")
return False
print(even(x))
"""
#OR
""" def even(num):
res = False
if num % 2 ==0:
res = True
return res
print(even(2))
print(even(3)) """
#5. is_odd function
#Write an is_odd function that uses your is_even function to determine if a number is odd.
#(That is, do not do the calculation - call a function that does the calculation.)
#Hint: You'll use the not keyword
""" x = int(input("Please give a number:\n"))
def even(x):
if not x % 2 == 0:
print("This is odd.")
return True
else:
print("This is even.")
return False
print(even(x)) """
#########
#6. only_evens function
#Write a function that accepts a List of numbers as an argument.
#Return a new List that includes the only the even numbers.
#only_evens([11, 20, 42, 97, 23, 10])
# Returns [20, 42, 10]
#Hint: use your is_even() function to determine which numbers to include in your new List
""" def is_evens(list):
even_list = []
for i in list:
if i % 2 ==0:
even_list.append(i)
return even_list
print(is_evens([11, 20, 42, 97, 23, 10])) """
#7. only_odds function
#Write a function that accepts a List of numbers as an argument.
#Return a new List that includes the only the odd numbers.
""" def odd(list):
odd_list = []
for i in list:
if i % 2 !=0:
odd_list.append(i)
return odd_list
print(odd([11, 20, 42, 97, 23, 10])) """
#1 medium
#1. Find the smallest number
#Write a function smallest that accepts a List of numbers as an argument.
#It should return the smallest number in the List
""" list = [11, 20, 42, 97, 23, 10]
def small(list):
return min(list)
print(small(list)) """
#2. Find the largest number
#Write a function largest that accepts a List of numbers as an argument.
#It should return the largest number in the List.
""" list = [11, 20, 42, 97, 23, 10]
def large(list):
return max(list)
print(large(list)) """
######################
##3. Find the shortest String
#Write a function shortest that accepts a List of Strings as an argument.
#It should return the shortest String in the List.
""" strings = ["Hello world", "Is anyone out there", "Guess I am alone"]
calc = min(strings, key = len)
def shortest(strings):
for i in strings:
return calc
print(shortest(strings)) """
##2. Find the largest number
#Write a function largest that accepts a List of numbers as an argument.
#It should return the largest number in the List.
""" strings = ["Hello world", "Is anyone out there", "Guess I am alone"]
calc = max(strings, key = len)
def largest(strings):
for i in strings:
return calc
print(largest(strings)) """
####### |
abb5302ab8fca5d1cb9e91b85630b47ffb4aca26 | YiddishKop/python_simple_study | /MultiThread2_asyncWriter.py | 1,696 | 4.4375 | 4 | # MultiThreading - 2
# Asynchronous Tasks
# Some tasks can take a long time. Input and output for example can take a long time.
# Some programs are required to be real time. So we can setup Threads to run in the background to write a file or search for items while the user can still interact with the interface or commandline.
# Custom Threads
# We can make our own thread subclasses.
# These are useful for making task specific threads that we can simply reuse as well as add features to the thread.
# Can make managing harder or more simple depending on how advanced we make our threading.
# AsyncWrite Program
# A basic threading program that writes a file in the background.
# A custom thread class will be created to take a string and save it to a file in the background.
# We will make it sleep for a second so we can see it working.
import threading
import time
class AsyncWriter(threading.Thread):
def __init__(self, text, out):
threading.Thread.__init__(self)
self.text = text
self.out = out
def run(self):
f = open(self.out, "a")
f.write(self.text + '\n')
f.close()
# 2 second
time.sleep(2)
print("Finished Backgroud File Write to " + self.out)
def Main():
message = input("Enter a string to store:")
background = AsyncWriter(message, 'out.txt')
background.start()
print("The program can continue while it write in another thread")
print("100 + 400 = ", 100+400)
# it will still waiting until background thread i done
# when background is done, it will continue
background.join()
print("waited until thread was complete")
if __name__ =="__main__":
Main()
|
66268e7b91c1312a0b5ee11d3352ec38f6f8eb80 | RotcehOdraude/horario-fi | /Python Scrapping/HorarioFIScrapping.py | 553 | 3.640625 | 4 | ##Hola paco rodri :D, por si querias scrapear la pagina de horarias de la facultad :o
import pandas as pd
listaDeMaterias = ['1645','1644','1562','1686','1413']
Materias = pd.DataFrame()
for materia in listaDeMaterias:
website = "http://ssa.ingenieria.unam.mx/hrsHtml/{}.html?".format(materia)
datalist = pd.read_html(website,attrs={"class":"table"})
Materias = Materias.append(datalist,ignore_index=True)
Materias.set_axis(['clave', 'gpo','profesor','tipo','horario','dias','cupo'], axis='columns', inplace=True)
print(Materias.tail(10)) |
0df8b4c11794dfa7efc67ac9d88951da88a1facc | anshu3769/KeplerProject | /Backend/data/database.py | 3,055 | 3.578125 | 4 | """
This module creates SQLAlchemy engine
and contains a method to initialize the
database which will be called upon running the
application.
"""
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.pool import SingletonThreadPool
from .utils import generateWords
# create an engine.
# NOTE: An sqlalchemy engine manages two things
# 1. Connection pools (max 5 by default)
# 2. Dialects which tell the sqlalchemy ORM about
# which database dialect to use. e.g. sqlite3,
#postgres etc
ENGINE = create_engine(
"sqlite:///database.sqlite3",
convert_unicode=True,
connect_args={'check_same_thread': False}
)
# Sessions are created to ensure consistency in the database
# sessionmaker creates a Session class that is used to create a session
db_session = scoped_session(
sessionmaker(autocommit=False, autoflush=False, bind=ENGINE)
)
# Base class for our class definitions
# Meaning not much clear of the declarative class??
Base = declarative_base()
Base.query = db_session.query_property()
# Create the utillity function to initialize database on startup
def init_db():
"""
Create few entries in the database
on startup
"""
from .models import Player, Score, Word, TopFiveScore
Base.metadata.drop_all(bind=ENGINE)
Base.metadata.create_all(bind=ENGINE)
# Add players
player_1 = Player(
first_name="Anshu",
last_name="Tomar",
user_name="Anshu"
)
db_session.add(player_1)
player_2 = Player(
first_name="Bunny",
last_name="Tomar",
user_name="Bunny"
)
db_session.add(player_2)
# Add scores
score_1 = Score(
value=10,
player=player_1
)
db_session.add(score_1)
score_2 = Score(
value=20,
player=player_1
)
db_session.add(score_2)
score_3 = Score(
value=30,
player=player_2
)
db_session.add(score_3)
score_4 = Score(
value=40,
player=player_2
)
db_session.add(score_4)
score_5 = Score(
value=50,
player=player_2
)
db_session.add(score_5)
score_6 = Score(
value=60,
player=player_2
)
db_session.add(score_6)
# Add words
words = generateWords()
for w in words:
word = Word(word=w)
db_session.add(word)
# Add top scores
top_score_1 = TopFiveScore(
value=60,
player=player_2
)
db_session.add(top_score_1)
top_score_2 = TopFiveScore(
value=50,
player=player_2
)
db_session.add(top_score_2)
top_score_3 = TopFiveScore(
value=40,
player=player_2
)
db_session.add(top_score_3)
top_score_4 = TopFiveScore(
value=30,
player=player_2
)
db_session.add(top_score_4)
top_score_5 = TopFiveScore(
value=20,
player=player_1
)
db_session.add(top_score_5)
db_session.commit()
|
fffe6c2a0ea5678450a1e8304755b358c1ef9d9e | prabhupant/python-ds | /algorithms/dynamic_programming/longest_subarray_with_no_pairsum_divisible_by_k.py | 1,466 | 3.953125 | 4 | """
Find the longest subarray in the input array such that the pairwise sum of
the elements of this subarray is not divisible by K
The idea is -
How can we tell that two numbers x and y will make a pairsum that will be
divisible by K just by looking at their remainders? There can be two conditions
1. It will be only possible if the sum of the remainders when x and y are
divided by K is equal to K. As the sum of the remainders cannot exceed K
so if it reaches K then it means that the sum of those numbers will also be
divisible by K
0 < (X%K) + (Y%K) <= K
2. If arr[i] % k == 0 and there is also an element j such that arr[j] % k == 0
and 0 exists in the hash (i.e hash[j] = True)
"""
def find_subarray(arr, k):
"""
True means divisible by k
"""
start, end = 0, 0
max_start, max_end = 0, 0
n = len(arr)
mod_arr = [0] * n
mod_arr[arr[0] % k] = mod_arr[arr[0] % k] + 1
for i in range(1, n):
mod = arr[i] % k
while (mod_arr[k - mod] != 0) or (mod == 0 and mod_arr[mod] != 0):
mod_arr[arr[start] % k] = mod_arr[arr[start] % k] - 1
start += 1
mod_arr[mod] = mod_arr[mod] + 1
end += 1
if (end - start) > (max_end - max_start):
max_end = end
max_start = start
print(f'Max size is {max_end - max_start}')
for i in (max_start, max_end + 1):
print(arr[i], end=" ")
arr = [3, 7, 1, 9, 2]
k = 3
find_subarray(arr, k)
|
803fa874360ac82951c3f7949b55178c3746169f | StampedPassp0rt/courses | /lphw/ex8.py | 572 | 3.75 | 4 | #Exercise 8
#variable that force prints four inputs with %r, kind of a debugger too.
formatter = "%r %r %r %r"
#printing out 1 through 4
print formatter % (1,2,3,4)
#printing out one through four as strings.
print formatter % ("one", "two", "three", "four")
#forcing the print of Boolean values
print formatter % (True, False, True, False)
# Will just print the string with the %r's.
print formatter % (formatter, formatter, formatter, formatter)
print formatter % ("I had this thing.", "That you could type up right.",\
"But it didn't sing.", "So I said goodnight.")
|
c6c142a9e6525d7307b9ccaf27f636e0d65da2ae | Ibunao/pythontest | /test1/yanglao.py | 1,181 | 3.515625 | 4 | import math
# 每月计划投入多少钱
plan = 5000
# 现在几岁
now_age = 27
# 多少岁可以取
plan_age = 40
# 目标活到多少岁
target_age = 80
# 周期,按月则是12,按周52,按天356
cycle = 12
# 分红,分红先不计算利率
profit = 129060
# 到期后每月返还多少
get_plan = 1029.5
# 预期利率
plan_rate = 0.10
def getWorthy():
'''
计算利息
:return:
'''
global plan, plan_age, now_age, target_age, cycle, plan_rate
# 计算支付的
pay_year = plan_age - now_age
pay_total = 0
while pay_year > 0:
pay_total += math.pow(1 + plan_rate, pay_year)
pay_year -= 1
pay_total = pay_total * plan * cycle
# 计算收益
get_total = 0
get_year = target_age - plan_age
# 计算投入的钱到死的时候的雪球
pay_total = pay_total * math.pow(1 + plan_rate, get_year)
while get_year > 0:
get_total += math.pow(1 + plan_rate, get_year)
get_year -= 1
# 计算能得到的
get_total = get_total * get_plan * cycle + profit
print(pay_total, get_total)
return "不值" if pay_total > get_total else "值"
print(getWorthy())
|
20e4664b280eaa2a93738524400c58ed384a34cb | petercheng00/adventOfCode | /2022/python/day12.py | 2,918 | 3.625 | 4 | import sys
from typing import Dict, List, Tuple
def load_heightmap() -> Tuple[List[str], Tuple[int, int], Tuple[int, int]]:
with open(sys.argv[1]) as f:
heightmap = f.read().splitlines()
start_pos = (-1, -1)
end_pos = (-1, -1)
for i in range(len(heightmap)):
if (start_j:=heightmap[i].find("S")) != -1:
start_pos = (i, start_j)
heightmap[i] = heightmap[i].replace("S", "a")
if (end_j:=heightmap[i].find("E")) != -1:
end_pos = (i, end_j)
heightmap[i] = heightmap[i].replace("E", "z")
return heightmap, start_pos, end_pos
def part1():
heightmap, start_pos, end_pos = load_heightmap()
dist_from_start = {start_pos: 0}
to_explore = [start_pos]
while to_explore:
pos = to_explore.pop(0)
dist_to_pos = dist_from_start[pos]
if pos == end_pos:
print(dist_to_pos)
return
my_height = heightmap[pos[0]][pos[1]]
for neighbor_step in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
neighbor_pos = (pos[0] + neighbor_step[0], pos[1] + neighbor_step[1])
if neighbor_pos[0] < 0 or neighbor_pos[0] >= len(heightmap) or neighbor_pos[1] < 0 or neighbor_pos[1] >= len(heightmap[0]):
# Off the map!
continue
if neighbor_pos in dist_from_start:
# Already visited before.
continue
neighbor_height = heightmap[neighbor_pos[0]][neighbor_pos[1]]
if ord(neighbor_height) - ord(my_height) > 1:
# Too high.
continue
dist_from_start[neighbor_pos] = dist_to_pos + 1
to_explore.append(neighbor_pos)
print("Finished without finding the end?")
def part2():
heightmap, _, end_pos = load_heightmap()
dist_from_end = {end_pos: 0}
to_explore = [end_pos]
while to_explore:
pos = to_explore.pop(0)
dist_to_pos = dist_from_end[pos]
my_height = heightmap[pos[0]][pos[1]]
if my_height == "a":
print(dist_to_pos)
return
for neighbor_step in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
neighbor_pos = (pos[0] + neighbor_step[0], pos[1] + neighbor_step[1])
if neighbor_pos[0] < 0 or neighbor_pos[0] >= len(heightmap) or neighbor_pos[1] < 0 or neighbor_pos[1] >= len(heightmap[0]):
# Off the map!
continue
if neighbor_pos in dist_from_end:
# Already visited before.
continue
neighbor_height = heightmap[neighbor_pos[0]][neighbor_pos[1]]
if ord(my_height) - ord(neighbor_height) > 1:
# Too high.
continue
dist_from_end[neighbor_pos] = dist_to_pos + 1
to_explore.append(neighbor_pos)
print("Finished without finding the end?")
part1()
part2()
|
9f97b14927e5e15a283922a106c4614d72133f4f | hector81/Aprendiendo_Python | /CursoPython/Unidad8/Soluciones/moulo_II_.py | 1,333 | 4.125 | 4 | """paquete del moulo principal del descuento"""
import random
def sorteo(valor):
x = random.choice([0,10,20,25,50])
bolas = {0:"BOLA BLANCA", 10:"BOLA ROJA", 20:"BOLA AZUL", 25:"BOLA VERDE", 50:"BOLA AMARILLA"}
if x == 0:
print("Lo siento no tienes descuento, te salió la bola blanca")
else:
la_bola = bolas[x]
a_pagar = float (valor -(float(valor * x)/100))
print(f"Has sacado una bola {la_bola}")
print(f"Felicidades tienes un {x}% de descuento")
print(f"Debes pagar: {a_pagar}")
def promocion(): #Información del descuento
print ("")
print ("Has gastado al menos 100.00€, Ahora participa en el sorteo para la promoción.")
print ("")
print (" COLOR DESCUENTO")
print ("")
print (" BOLA BLANCA NO TIENE DESCUENTO")
print (" BOLA ROJA 10 POR CIENTO")
print (" BOLA AZUL 20 POR CIENTO")
print (" BOLA VERDE 25 POR CIENTO")
print (" BOLA AMARILLA 50 POR CIENTO")
print ("")
def cobro():
cobra = float(input("Cuanto ha gastado el cliente?? "))
if cobra < 100.00:
print("Lo siento pero no se te aplica el descuento")
else:
print("Se te aplicará un descuento dependiendo del sorteo")
promocion()
input("Para ejecutarlo pulsa en intro...")
sorteo(cobra) |
af4080f51de0369622e20069a6a1310ce8eadc7a | JackelyneTriana/EVIDENCIA-3 | /EVIDENCIA3.py | 7,665 | 3.71875 | 4 | separador = ("*" * 40)
import sys
import sqlite3
from sqlite3 import Error
with sqlite3.connect("CURSO.db") as conn:
c = conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS materias (idmateria INTEGER PRIMARY KEY, nombre TEXT NOT NULL);")
c.execute("CREATE TABLE IF NOT EXISTS alumnos (idalumno INTEGER PRIMARY KEY, nombre TEXT NOT NULL);")
c.execute("CREATE TABLE IF NOT EXISTS calificaciones (idalumno INTEGER NOT NULL, idmateria INTEGER NOT NULL, calificacion INTEGER NOT NULL, FOREIGN KEY(idalumno) REFERENCES alumnos(idalumno), FOREIGN KEY(idmateria) REFERENCES materias(idmateria));")
c.execute("INSERT INTO materias(idmateria, nombre) SELECT 1, 'PROGRAMACION' WHERE NOT EXISTS(SELECT idmateria FROM materias WHERE idmateria = 1)")
c.execute("INSERT INTO materias(idmateria, nombre) SELECT 2, 'BASE DE DATOS' WHERE NOT EXISTS(SELECT idmateria FROM materias WHERE idmateria = 2)")
c.execute("INSERT INTO materias(idmateria, nombre) SELECT 3, 'MACROECONOMIA' WHERE NOT EXISTS(SELECT idmateria FROM materias WHERE idmateria = 3)")
c.execute("INSERT INTO materias(idmateria, nombre) SELECT 4, 'ESTADISTICAS' WHERE NOT EXISTS(SELECT idmateria FROM materias WHERE idmateria = 4)")
c.execute("INSERT INTO materias(idmateria, nombre) SELECT 5, 'CONTABILIDAD' WHERE NOT EXISTS(SELECT idmateria FROM materias WHERE idmateria = 5)")
conn.commit()
def menu():
print("1) Capturar 30 estudiantes")
print("2) Capturar las calificaciones de los 30 estudiantes")
print("3) Consultar calificaciones por alumno determinado")
print("4) Consultar reporte por estudiantes")
print("5) Consultar reporte por materias")
alumnos = conn.cursor()
alumnos.execute("SELECT * FROM alumnos")
alumnos1 = alumnos.fetchall()
materias = conn.cursor()
materias.execute("SELECT * FROM materias")
materias = materias.fetchall()
respuesta = int(input("Elige la opcion del menu que desees:"))
print(separador)
while (respuesta != 1) and (respuesta != 2) and (respuesta != 3) and (respuesta != 4) and (respuesta != 5) and (respuesta != 6) :
respuesta = int(input("Opcion invalida, teclea una opcion del menu"))
if respuesta == 1:
Opcion_1()
elif respuesta == 2:
Opcion_2()
elif respuesta == 3:
Opcion_3()
elif respuesta == 4:
Opcion_4()
else:
Opcion_5()
def Opcion_1():
print("Ingrese los datos de los 30 alumno (matricula y nombre)")
registros_cant = 1
while registros_cant <= 2:
idalumno = int(input("Matricula del alumno: "))
nombre = input("Nombre del alumno: ")
insertaralumnos = conn.cursor()
valores = {"idalumno":idalumno, "nombre": nombre}
insertaralumnos.execute("INSERT INTO alumnos VALUES(:idalumno,:nombre)", valores)
registros_cant = registros_cant + 1
print("ALUMNOS REGISTRADOS CORRECTAMENTE")
conn.commit()
menu()
def Opcion_2():
alumnos = conn.cursor()
alumnos.execute("SELECT * FROM alumnos")
registros = alumnos.fetchall()
if registros:
for idalumno,nombre in registros:
print(f"INGRESA LAS CALIFICACIONES DE {nombre}: ")
progra = int(input("Programacion: "))
cal1 = conn.cursor()
valores = {"idalumno":idalumno, "idmateria":1, "calificacion":progra}
cal1.execute("INSERT INTO calificaciones VALUES(:idalumno,:idmateria,:calificacion)", valores)
base = int(input("Base de datos: "))
cal2 = conn.cursor()
valores = {"idalumno":idalumno, "idmateria":2, "calificacion":base}
cal2.execute("INSERT INTO calificaciones VALUES(:idalumno,:idmateria,:calificacion)", valores)
macro = int(input("Macroeconomia: "))
cal3 = conn.cursor()
valores = {"idalumno":idalumno, "idmateria":3, "calificacion":macro}
cal3.execute("INSERT INTO calificaciones VALUES(:idalumno,:idmateria,:calificacion)", valores)
est = int(input("Estadistica: "))
cal4 = conn.cursor()
valores = {"idalumno":idalumno, "idmateria":4, "calificacion":est}
cal4.execute("INSERT INTO calificaciones VALUES(:idalumno,:idmateria,:calificacion)", valores)
conta = int(input("Contabilidad: "))
cal5 = conn.cursor()
valores = {"idalumno":idalumno, "idmateria":5, "calificacion":macro}
cal5.execute("INSERT INTO calificaciones VALUES(:idalumno,:idmateria,:calificacion)", valores)
else:
print("Debe capturar los datos de los alumnos en la opcion 1 del menu")
menu()
conn.commit()
print("CALIFICACIONES AGREGADAS CORRECTAMENTE")
print(separador)
menu()
def Opcion_3():
idalumno = int(input("Ingresa la matricula del alumno para ver sus calificaciones: "))
cal_alumno = conn.cursor()
valores = {"idalumno":idalumno}
cal_alumno.execute("SELECT nombre, calificacion FROM calificaciones JOIN materias ON calificaciones.idmateria = materias.idmateria WHERE idalumno=:idalumno", valores)
calificaciones = cal_alumno.fetchall()
nom_alumno = conn.cursor()
nom_alumno.execute("SELECT nombre FROM alumnos WHERE idalumno=:idalumno", valores)
nombre = nom_alumno.fetchall()
nom = nombre[0]
n = str(nom[0])
if calificaciones:
print(f"Calificaciones de {n}")
for nombre,calificacion in calificaciones:
print(f"{nombre}\t",end="")
print(calificacion)
else:
print(f"No existe un alumno con la matricula {idalumno}, intenta con otra")
Opcion_3()
print(separador)
menu()
def Opcion_4():
idmateria = conn.cursor()
idmateria.execute("SELECT idmateria FROM materias GROUP BY idmateria")
materias = idmateria.fetchall()
for claves in materias:
clave = int(claves[0])
valores = {"idmateria":clave}
nom_mat = conn.cursor()
nom_mat.execute("SELECT nombre FROM materias WHERE idmateria=:idmateria", valores)
nom_materia = nom_mat.fetchall()
n = nom_materia[0]
nom = str(n[0])
print(f"{nom}\n")
calif = conn.cursor()
calif.execute("SELECT nombre, calificacion FROM calificaciones JOIN alumnos ON alumnos.idalumno = calificaciones.idalumno WHERE idmateria=:idmateria", valores)
calificaciones = calif.fetchall()
for nombre, calificacion in calificaciones:
print(f"{nombre}\t", end="")
print(calificacion)
print("\n")
print(separador)
menu()
def Opcion_5():
idalumno = conn.cursor()
idalumno.execute("SELECT idalumno FROM alumnos GROUP BY idalumno")
alumnos = idalumno.fetchall()
for claves in alumnos:
clave = int(claves[0])
valores = {"idalumno":clave}
nom_alum = conn.cursor()
nom_alum.execute("SELECT nombre FROM alumnos WHERE idalumno=:idalumno", valores)
nom_alumno = nom_alum.fetchall()
n = nom_alumno[0]
nom = str(n[0])
print(f"{nom}\n")
calif = conn.cursor()
calif.execute("SELECT nombre, calificacion FROM calificaciones JOIN materias ON materias.idmateria = calificaciones.idmateria WHERE idalumno=:idalumno", valores)
calificaciones = calif.fetchall()
for nombre, calificacion in calificaciones:
print(f"{nombre}\t", end="")
print(calificacion)
print("\n")
print(separador)
menu()
menu()
|
87ab05696a47a263f53a4d5db264c0e844a62a1c | dipro007/Python-all-in-one | /area.py | 253 | 3.96875 | 4 | b = float(input("Enter the value of base: "))
h = float(input("Enter the value of height: "))
r = float(input("Enter the value of radius: "))
at= 0.5 * b * h
ac = 3.1416 * r * r
print("Area of Triangle = ",at)
print("Area of Circle = ",ac)
|
0758c7bdd7f377f4aed1159cbcce20398de79693 | emkramer/homework_python | /13.09/15.09.py | 124 | 3.875 | 4 | def generator_():
number = 0
while number<1000000:
yield number
number += 3
for i in generator_():
print(i, end=" ")
|
581eb4f8342ca1603abb22b42b2b710f4ff33951 | aleshkoa/python_exercise | /question2.py | 156 | 3.734375 | 4 | celsius = float(raw_input('Enter Temperature in Celsius '))
fahrenheit = 9.0/5.0 * celsius + 32
print 'Temperature in Fahrehnheit is: ' + str(fahrenheit)
|
d2eeb7908498328e2e25037d713d53fad9464f20 | dyedefRa/python_bastan_sona_sadik_turan | /13_Python_Generators/01_generators.py | 568 | 4.0625 | 4 | # def cube():
# result = []
# for i in range(5):
# result.append(i**3)
# return result
# print(cube())
def cube():
for i in range(5):
yield i ** 3
# generator = cube()
# iterator = iter(generator)
# print(next(generator))
# print(next(generator))
# print(next(generator))
# print(next(generator))
# print(next(generator))
for i in cube():
print(i)
# liste = [i**3 for i in range(5)]
generator = (i**3 for i in range(5))
print(next(generator))
print(next(generator))
print(next(generator))
for i in generator:
print(i) |
24522bbc843ddf43e6505c3196c572b3be06d614 | manixaist/pyclimber | /src/particle_generator.py | 3,772 | 3.765625 | 4 | """Particle generator for Py-Climber"""
from src.particle import Particle
import random
class ParticleGenerator():
"""The ParticleGenerator class is responsible for creating and tracking Particle
objects which are just 2D rects of a given color. A calling object may specify
a callback to customize the particles generated, e.g. their velocities and color
"""
def __init__(self, screen, settings, color, x, y, generator_callback=None):
"""Init the position and color"""
self.screen = screen
self.screen_rect = self.screen.get_rect()
self.settings = settings
self.x = x
self.y = y
self.color = color
self.particles = []
self.active = False
self.active_frames = 0
self.frames_to_generate = 0
self.callback = generator_callback
def start(self, frames_to_generate):
"""Tells the generator to start generating particles"""
self.active = True
self.active_frames = 0
self.frames_to_generate = frames_to_generate
def stop(self):
"""Tells the generator to stop generating particles"""
self.active = False
self.active_frames = 0
# start() dictates the duration
self.frames_to_generate = 0
def update(self):
"""Update the position of all alive particles"""
# We always want to draw the particles, so unlike other sprites,
# the 'active' or 'on' property will control the generation instead
# This way when the generator stops, the existing particles will
# finish out their lives. If it controlled the drawing, particles
# in-flight would just vanish (or you would need additional logic
# in the drawing code)
if self.active:
self.generate_particles(self.settings.particle_gen_per_frame)
self.active_frames += 1
if self.active_frames > self.frames_to_generate:
self.stop()
# For any particles still alive, we need to update them, even if the
# generator is stopped. Once a particle is 'dead', remove it
for particle in self.particles:
particle.update()
if not particle.alive():
self.particles.remove(particle)
def generate_particles(self, number_of_new_particles):
"""Create a new particle at the generator's location and give it an initial velocity"""
# In the callback case the implementer controls it all, including the number
# create an empty list to hold the data
particle_data = []
if self.callback:
# We have a callback, so delegate all of the work....
particle_data = self.callback()
else:
# No callback, so make some random ones by default
for particle_index in range(0, number_of_new_particles):
new_data = (random.randint(-2, 2), random.randint(5, 20) * -1, (random.randint(0,255), random.randint(0,255), random.randint(0,255)))
particle_data.append(new_data)
# Callback or not, at this point we should have a list of particle data
for particle_info in particle_data:
# Create a new particle object
new_particle = Particle(self.screen, self.settings, self.x, self.y, particle_info[0], particle_info[1], random.randint(1, 4), particle_info[2])
# Add it to the list to track/draw
self.particles.append(new_particle)
def draw(self):
"""Draw all of the particles"""
# Since the are not pygame.sprites, can't just use the Group as with the blobs
# Just another way to do things
for particle in self.particles:
particle.draw()
|
42a3528872a1f3cde35e0f8cbd16cce415395fa4 | palhiman/Lab-Practices | /ml/dfm1.py | 852 | 4.1875 | 4 | #!/usr/bin/python
# Implementation of Diffie-Hellman-Merkel key exchange algorithm
# Author: Himanshu Shekhar
import math
def power(a, b , P):
if b == 1:
return a
else:
return (math.pow(a, b) % P)
if __name__ == "__main__":
p = int(input("Enter the comman prime number:"))
g = int(input("Enter a base(primitive root of p):"))
a = int(input("Enter the private key for Alice:"))
b = int(input("Enter the private key of Bob:"))
# Generating a key by Alice and to be sent to Bob
print("Key from Alice to Bob:")
x = power(g, a, p)
# Generating a key by Bob and to be sent to Alice
print("Key from Bob to Alice:")
y = power(g, b, p)
print("The secret exchange between them....")
ka = power(y, a, p)
print(f"key for Alice:{ka}")
kb = power(x, b, p)
print(f"key for Bob:{kb}")
|
8e189741b544ba01abf8a99179ffbd1128bdbc22 | Pharaoh00/My-Experiments | /Pygame/test_maps/test_map_v5.py | 6,945 | 3.625 | 4 | #-*- coding:utf-8 -*-
#test_map_v5.py
import pygame
from pygame.locals import *
from pygame.math import Vector2
pygame.init()
#pygame.key.set_repeat(250, 25)
s_width = 600
s_height = 600
clock = pygame.time.Clock()
fps = 30
running = True
game_screen = pygame.display.set_mode((s_width, s_height), pygame.DOUBLEBUF)
class Maps:
def __init__(self, objects, m):
self.maps = m
self.current_map = self.maps[1][1]
self.objects = objects
self.image = pygame.Surface(game_screen.get_size())
self.rect = self.image.get_rect()
def update(self):
#print("current map: ",self.current_map)
game_screen.blit(self.image, (0,0))
self.objects.update()
"""
self.object.update(), objects sendo o grupo com todas as sprites,
funciona da seguinte forma:
Tudo na tela será "autalizado", posição dos objetos do grupo.
"""
self.image.fill(self.current_map)
self.objects.draw(self.image)
"""
self.objects.draw(self.image), objects sendo o grupo com todas as sprites
self.image, sendo a onde os objetos serão desenhados, no caso, no mapa
atual. Funciona da seguinte forma:
Todos os objetos do grupo serão desenhados na tela, mas não diz respeito,
aos calculos como posição por exemplos.
So diz respeito a desenha os objetos na tela.
"""
self.next_map(player)
"""
A FAZER:
Adicionar mais "mapas" na lista.
Usar as index´s da lista da coordenadas, (0,0) para andar pelos mapas.
(0,0) sendo (x,y), x cima/baixo, y(esquerda/direita)
Se o player for para cima, (-1,0), se o player for para baixo, (0,0)
Se o player for para esquerda, (0, -1), se o player for
para direita (0,0).
self.current_map = self.map[1]
Observações:
Se self.object.update() estiver "ativo", e self.objects.draw(), estiver
"desligado", os objetos na tela não seram mostrados, mas a posição será
atualizada.
Se self.object.draw() estiver "ativo", e self.objects.update(), estiver
"desligado", os objetos na tela serão desenhados, mas ficaram estaticos
na tela. Não iram ser atualizados.
Meus pensamentos sobre isso:
No conceito dos mapas, se REALMENTE o player estiver no mapa, os objetos
(do mapa), serão desenhados. Mas, pode ter outra boolean que irá manter
track dos outros mapas, os mapas em volta do player por exemplo, podem
continuar sendo atualizados (suas posições/mecanicas), em um framerate
menor, e quando o player for nesses mapas, é como se o "mundo" estivesse
ativo em sua ausencia, dando a iluzação que o "mundo está vivo".
Com update() eu posso monter track desses mapas, e continuar os
atualizando, e com draw(), eu posso manter track a onde o player
realmente está e desenhar os objetos do mapa.
Talvez a melhor forma de se atingir esse objetivo é usar os
sprite.Group() de forma inteligente.
Ter sprite.Group() para os mapas, para os objetos animados, e assim
atualizando e denhando de forma eficiente.
Problemas futuros:
Como os objetos estarão sendo atualizados na mesma surface, eles vão
estar se "esbarrando", se ouver alguma mecanica de colisão, ela será
aplicada da mesma forma sem os objetos estarem sendo mostrados na tela.
Talvez colocar os objetos de mapas diferentes em grupos diferentes,
sendo assim cada mapa terá o seu proprio grupo?
Cabe so testar para saber.
"""
self.test_current_map = 1
self.test = self.maps[self.test_current_map][0]
self.test_map_x = 0
self.test_map_y = 0
if self.test[0] == self.test_map_x and self.test[1] == self.test_map_y:
print(self.test)
def next_map(self, p):
self.p = p
if self.p.pos[0] < 0:
self.current_map = self.maps[0][1]
self.p.pos[0] = s_width
self.image.fill(self.current_map)
if self.p.pos[0] > s_width:
self.current_map = self.maps[1][1]
self.p.pos[0] = 0
self.image.fill(self.current_map)
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self) # Inicializando a Herança
#self.image = pygame.image.load("poo1.png") # Imagem aleatoria
self.image = pygame.Surface((50,50)) # Criando uma nova Surface
self.rect = self.image.get_rect()
self.rect = pygame.draw.rect(self.image, (0,255,0), self.rect)
self.pos = Vector2(0,0)
self.speed_x = 0
self.speed_y = 0
def start_move_left(self):
self.speed_x = -10
def stop_move_left(self):
self.speed_x = 0
def start_move_right(self):
self.speed_x = 10
def stop_move_right(self):
self.speed_x = 0
def start_move_up(self):
self.speed_y = -10
def stop_move_up(self):
self.speed_y = 0
def start_move_down(self):
self.speed_y = 10
def stop_move_down(self):
self.speed_y = 0
def update(self):
self.moving = Vector2(self.speed_x, self.speed_y) #Mistake?
#print(self.rect)
#print(self.speed_x)
#print(self.speed_y)
if self.moving:
self.pos += self.moving
self.rect.x, self.rect.y = self.pos
#print(self.pos)
#print(self.moving)
player = Player()
maps = (
((-1,-1), (255,255,0)),
((0,0), (255,0,0))
)
allsprites = pygame.sprite.Group()
allsprites.add(player)
m1 = Maps(allsprites, maps)
while(running):
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.start_move_left()
if event.key == pygame.K_RIGHT:
player.start_move_right()
if event.key == pygame.K_UP:
player.start_move_up()
if event.key == pygame.K_DOWN:
player.start_move_down()
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
player.stop_move_left()
if event.key == pygame.K_RIGHT:
player.stop_move_right()
if event.key == pygame.K_UP:
player.stop_move_up()
if event.key == pygame.K_DOWN:
player.stop_move_down()
m1.update()
pygame.display.update()
clock.tick(fps)
#print(clock.get_fps())
pygame.quit()
|
e485bec3fab28d61253218a3a00387fa16915781 | kiranani/playground | /Python3/0124_Binary_Tree_Max_Path_Sum.py | 618 | 3.515625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
def helper(root):
if not root:
return 0
nonlocal maxSum
leftSum, rightSum = max(0, helper(root.left)), max(0, helper(root.right))
maxSum = max(maxSum, leftSum + root.val + rightSum)
return root.val + max(rightSum, leftSum)
maxSum = -float("inf")
helper(root)
return maxSum
|
283290e663ae6e345e9f03357f22a0549ec1fc30 | Jp9910/Projeto-e-Analise-de-Algoritmos | /nQueens.py | 1,712 | 3.6875 | 4 | def posicaoValida(X,r,col) -> bool:
#checa se a coluna col já foi utilizada por uma rainha de índice anterior a r
#e também se a rainha k não ataca em diagonal a rainha r
for k in range(1,r):
if (X[k] == col) or (abs(X[k]-col) == abs(k-r)):
return False
return True
def NQ(i,n,X):
#Entrada: rainha i, tamanho do tabuleiro n, solução X
#Saída: X[0] indicando se tem solução (1) ou não (0). Caso sim, X[1..n] a armazena.
for j in range(1,n+1):
#verifica se pode alocar a rainha i na coluna j
if(posicaoValida(X,i,j)):
#colocar rainha i na coluna j
X[i] = j
#checar se já posicionou todas as rainhas ou se precisa continuar a busca
if(i==n):
X[0] = 1
print(X)
#para encontrar apenas a primeira solução, basta incluir
#uma condiçao para parar (break no for) todas as recursoes caso X[0] == 1
else:
NQ(i+1,n,X) #prosseguir para alocar a proxima rainha
def nQueens(n):
#Entrada: Tamanho do tabuleiro n
#Saída: Solução armazenada em X[1..n] impressa, se existir alguma.
#Posição 0 do vetor X indica se existe solução (1) ou não (0)
X = [0]*(n+1)
for i in range(0,n+1):
X[i] = 0
#NQ aplica backtracking para encontrar uma solução
NQ(1,n,X)
"""
if(X[0] == 1):
print("Solução de ordem",n,":")
for i in range(1,n+1):
print(X[i],end='-')
else:
print("Não existe solução para um tabuleiro de ordem",n)
"""
if(X[0]==0):
print("Não existe solução para um tabuleiro de ordem",n)
nQueens(4) |
d0362c81ac4651f60c95b1ae9a6e769335a978c9 | Fuseken/code | /python/if.py | 99 | 3.859375 | 4 | door = input("> ")
if door == "a":
print("you have typed ",door, "right?")
else:
print("okay")
|
f9fb49141c26304f264b8eb7c7d8425668c6cc50 | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day07/exercise08.py | 637 | 4.09375 | 4 | """
list01 = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]
练习1:打印第二行第三个元素
练习2:打印第三行第每个元素
练习3:打印第一列每个元素
"""
list01 = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]
# 练习1:打印第二行第三个元素
print(list01[1][2])
# 练习2:打印第三行第每个元素
for item in list01[2]:
print(item, end=" ")
print()
# 练习3:打印第一列每个元素
for row in range(len(list01)):
print(list01[row][0], end=" ")
|
10a000bafbc19d46e623dac5cbb1f76eacfae7ed | michlee1337/practice | /CTCI/c4_treesAndGraphs/firstCommonAncestor.py | 2,124 | 3.796875 | 4 | from queue import *
# O(n) time: finding the nodes takes O(n) time,
# and the rest takes O(h) time where h is height of the tree
# O(lgn) space: search queue will be O(lgn) (at least the root will be on a diff level)
# and the rest are constant space pointers
def firstCommonAncestor(root, node1, node2):
# find the nodes and their depths in the tree
pointer_1, pointer_2 = findNodeLevels(root, [node1,node2])
# make their depths equal
while (pointer_2[1] - pointer_1[1]) > 0:
pointer_2 = (pointer_2[0].parent, pointer_2[1]-1)
while (pointer_1[1] - pointer_2[1]) > 0:
pointer_1 = (pointer_1[0].parent, pointer_1[1]-1)
pointer_1 = pointer_1[0] # getting rid of level counts for cleaner code
pointer_2 = pointer_2[0]
# traverse up ancestor paths until common
while pointer_1 != pointer_2: # no need for a out of bounds check because root must be a common ancestor
pointer_1 = pointer_1.parent
pointer_2 = pointer_2.parent
return(pointer_1)
def findNodeLevels(root, nodes):
pointers = [None for _ in nodes]
searchQueue = Queue()
searchQueue.put((root,0))
while None in pointers:
if searchQueue.empty():
raise ValueError("Nodes given are not in tree!")
else:
node, level = searchQueue.get()
for child in node.children:
for node_ind, node in enumerate(nodes):
if child == node:
pointers[node_ind] = (child, level)
searchQueue.put((child,level+1))
return(pointers)
class Node():
def __init__(self,val):
self.val = val
self.children = []
self.parent = None
def addChildren(self,children):
self.children = children
for node in self.children:
node.parent = self
if __name__ == "__main__":
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
n4 = Node(4)
n5 = Node(5)
n6 = Node(6)
n7 = Node(7)
n1.addChildren([n2,n3,n4])
n2.addChildren([n5])
n4.addChildren([n6,n7])
print(firstCommonAncestor(n1,n6,n7).val)
|
ed952f6a95f21f5d549e209705fcaabc6bc64271 | PierreKimbanziR/belgium_housing_price_predictor | /app.py | 4,433 | 3.5 | 4 | import streamlit as st
import pickle
import pandas as pd
import numpy as np
import os
import webbrowser
from bokeh.models.widgets import Div
cwd = os.getcwd() # Get the current working directory (cwd)
model = pickle.load(open(cwd + "/estimator.pkl", "rb"))
data = pd.read_csv(
"https://raw.githubusercontent.com/SamuelD005/challenge-regression/development/Data8.csv",
sep=",",
)
x = data.drop(["Price", "PriceperMeter", "Unnamed: 0"], axis=1)
columns = x.columns
st.title("Estimate the price of your property")
st.subheader("Artificial intelligence powered price estimation.")
def main():
st.write(
"""
#### To evaluate the price of your property we will need a few infomations.
"""
)
type_of_property = st.selectbox(
"What type of property do you want to estimate ? ", ("--", "house", "apartment")
)
locality = st.number_input(
"Please enter the property's postal code.", min_value=1000, max_value=9999
)
region = st.selectbox(
"Select the region of the property", ("Flanders", "Wallonia", "Brussel")
)
province = st.selectbox(
"Select the province of the property",
options=[
"------",
"Flandre Occidental",
"Flandre Oriental",
"Hainaut",
"Brussel",
"Anvers",
"Liège",
"Brabant Flamand",
"Brabant Wallon",
"Limbourg",
"Namur",
"Luxembourg",
],
)
area = st.number_input(
"Enter the size (in m²) of the property.", min_value=0, max_value=1000
)
number_of_room = st.select_slider(
"How many rooms are there in the house ?",
options=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
)
state_of_building = st.select_slider(
"What is the condition of the property ? ",
options=["to renovate", "medium", "good", "new"],
)
st.write("_____________________________________________________")
fully_equipped_kitchen = st.selectbox(
"Is the kitchen fully equipped ?", ["No", "Yes"]
)
furnished = st.selectbox("Is the house is sell furnished ?", ["No", "Yes"])
open_fire = st.selectbox("Does the house have an open fire ?", ["No", "Yes"])
st.write("_____________________________________________________")
terrace_area = st.number_input(
"Enter the size of the terrace (in m²).", min_value=0, max_value=1000
)
garden_area = st.number_input(
"Enter the area of your garden", min_value=0, max_value=100000000
)
number_of_facades = st.selectbox("How many facades does the property have ?", [2, 3, 4])
swimming_pool = st.selectbox("Does the property have a swimming pool ?", ["No", "Yes"])
surface_of_the_land = area + terrace_area + garden_area
fully_equipped_kitchen = 1 if fully_equipped_kitchen == "Yes" else 0
furnished = 1 if furnished == "Yes" else 0
open_fire = 1 if open_fire == "Yes" else 0
swimming_pool = 1 if swimming_pool == "Yes" else 0
df = pd.DataFrame(
[
[
locality,
type_of_property,
number_of_room,
area,
fully_equipped_kitchen,
furnished,
open_fire,
terrace_area,
garden_area,
surface_of_the_land,
number_of_facades,
swimming_pool,
state_of_building,
province,
region,
]
],
columns=columns,
)
linkedin = "[Find me on Linkedin](https://www.linkedin.com/in/pierre-kimbanzi-ruganda/)"
github = "[Find me on Github](https://github.com/PierreKimbanziR)"
github_project = "[Take a look at the code behind this project](https://github.com/PierreKimbanziR/belgium_housing_price_predictor)"
side_text = st.sidebar.write(
"""
# Get in touch
""")
link_1 = st.sidebar.markdown(linkedin, unsafe_allow_html=True)
link_2 = st.sidebar.markdown(github, unsafe_allow_html=True)
link_3 = st.sidebar.markdown(github_project, unsafe_allow_html=True)
if st.button("Estimate the price"):
result = model.predict(df)
st.success(f"The estimated price of the property is {round(result[0])} euros")
if __name__ == "__main__":
main()
|
2336fdef1f7c65c453ce50f31bc57cdd659ce96a | pawelptak/FaceRecognizer | /classes/screen_stack.py | 597 | 3.6875 | 4 | class ScreenStack:
def __init__(self):
self.stack = []
def add_screen(self, screen_name):
if len(self.stack) > 0:
if self.stack[-1] != screen_name:
self.stack.append(screen_name)
else:
self.stack.append(screen_name)
def previous_screen(self):
if len(self.stack) > 1:
self.stack.pop()
else:
print("nothing to go back to")
return self.stack[-1]
def get_top(self):
if len(self.stack) > 1:
return self.stack[-1]
else:
return None
|
eca678dc8091cdc00b987c2733c163a32996e0dc | paalso/learning_with_python | /ADDENDUM. Think Python/10 Lists/10-5.py | 510 | 4.09375 | 4 | '''
Exercise 10.5. Write a function called is_sorted that takes a list as
a parameter and returns True if the list is sorted in ascending order and
False otherwise.
'''
def is_sorted(L):
for i in range(1, len(L)):
if L[i] < L[i - 1]:
return False
return True
t1 = []
t2 = [1]
t3 = [1, 2, 3, 4, 5, 6, 7]
t4 = [10, 2, 3, 4, 5, 6, 7]
print(is_sorted(t1)) # True
print(is_sorted(t2)) # True
print(is_sorted(t3)) # True
print(is_sorted(t4)) # False
|
2fb3cf465ce2c1fa829e5805ed6799196c2811fd | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/word-count/51375a5af58746209b9db60b7d392b3c.py | 285 | 3.796875 | 4 | from collections import Counter
def word_count(phrase):
cleaned_phrase = ""
# Remove anything not alphanumeric or a space
for c in phrase:
if (c.isalnum() or c == " "):
cleaned_phrase += c.lower()
return Counter(cleaned_phrase.split())
|
a68b92849ffb44f9cc611e2a7399248a6c525f33 | relsqui/joculators | /bot/cryptograms.py | 3,272 | 4.21875 | 4 | #!/usr/bin/python3
"""
Cryptogram finder.
(c) 2017 Finn Ellis.
A "cryptogram" for the purpose of this module is a string which can be
transformed into a target string by consistently replacing each letter 1:1
with another letter (or with itself).
"""
import logging
import random
logger = logging.getLogger(__name__)
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.DEBUG)
def clean_words():
"""
Filter /usr/share/dict words for lines which only contain lowercase ASCII.
Returns:
A list of such strings.
"""
logger.info("Getting word list and filtering ...")
words = []
with open("/usr/share/dict/words") as f:
for word in f:
word = word[:-1]
if (word.isalpha() and word == word.lower() and
all(ord(c) < 128 for c in word)):
words.append(word)
logger.info("Loaded %s words.", len(words))
return words
def normalize(string):
"""
Convert a string into a normalized cryptogram form, in which each letter is
consistently replaced by the first position at which that letter appears in
the string. That is, the first letter is replaced by 1, the second is
replaced by 2 (unless it's the same as the first, in which case it's also
1), the third is replaced by 3 (unless it's the same as a previous letter),
and so on. The output of this process for two different strings is
identical if and only if the strings are cryptograms of each other.
Args:
A string.
Returns:
A list of integers, the normal form of the string.
"""
ords = list(map(ord, string))
cipher = {}
for i in range(len(string)):
if ords[i] not in cipher:
cipher[ords[i]] = i
ords[i] = cipher[ords[i]]
return ords
def find_cryptograms(target):
"""
Find cryptograms of a target string in the sanitized wordlist provided
by clean_words (lowercase ASCII only from /usr/share/dict/words).
Args:
One target word.
Returns:
A list of cryptograms of that word.
"""
matches = []
logger.info("Looking for cryptograms of %s.", target)
normal_target = normalize(target)
for w in clean_words():
if normalize(w) == normal_target:
matches.append(w)
logger.info("Found %s cryptograms.", len(matches))
return matches
def make_cryptogram(cleartext):
"""
Make a cryptogram by replacing every instance of one letter in a string with
a different letter.
Args:
Source string.
Returns:
Encoded string.
"""
cleartext = cleartext.upper()
ciphertext = ""
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
shuffled = list(alphabet)
random.shuffle(shuffled)
mapping = {}
for letter in alphabet:
mapping[letter] = shuffled.pop()
for letter in cleartext:
if letter in mapping.keys():
ciphertext += mapping[letter]
else:
ciphertext += letter
return ciphertext
if __name__ == "__main__":
"""
Take a word on the command line and return any cryptograms of it which are
in the cleaned-up version of /usr/share/dict/words.
"""
import sys
print("\n".join(find_cryptograms(sys.argv[1])))
|
0af70927a3788c82e9dad253df2b05d35eb1b1e7 | Python-x/Python-x | /面向对象/单例.py | 1,101 | 3.71875 | 4 | class Person(object):
def __init__(self, name):
self.name = name
def read(self):
print(self.name +"正在读书")
def watch_TV(self):
print(self.name+"在看电视")
class Woman(Person):
def maoyi(self):
print(self.name+"在逛街")
mama = Woman("妈妈")
mama.maoyi()
mama.watch_TV()
class Man(Person):
def football(self):
print(self.name+"在看球赛")
baba = Man("爸爸")
baba.football()
baba.read()
class Son(Person):
instance = None
init_flag = False
def __new__(cls,*w,**q):
if cls.instance is None:
cls.instance = super().__new__(cls)
instance = True
return cls.instance
def __init__(self,name):
if not Son.init_flag:
self.name = name
print("我叫"+self.name+"我是爸爸妈妈唯一的一个孩子")
Son.init_flag = True
def go_to_play(self,father,mother):
print("%s和%s%s出去玩了"%(self.name,father.name,mother.name))
xiaoming = Son("小明")
print(id(xiaoming))
xiaoming.go_to_play(baba,mama)
xiaogang = Son("hahaha")
print(id(xiaogang))
xiaogang.go_to_play(baba, mama)
xiaoli = Son("lllll")
xiaoli.go_to_play(baba, mama) |
5e12a1a8358669ec2b3f7569986fd1457a95e091 | melottii/notas | /MergeSort.py | 2,715 | 3.96875 | 4 | import pickle
def student(notas, alunos): #Função para somar a nota de cada aluno e chamar as ordenações das notas.
overall_grade, term = [], 0
for i in notas:
sum_of_assessments = notas[term][1] + notas[term][2] + notas[term][3] + notas[term][4]
overall_grade.append((term+1, sum_of_assessments, notas[term][2], notas[term][5], alunos[term+1]))
term += 1
merge_sort(overall_grade), out_formatting(overall_grade)
def merge_sort(overall_grade): #Função para definir os lados e separar os termos para serem comparados.
if len(overall_grade) > 1:
middle = len(overall_grade) // 2
left = overall_grade[:middle]
right = overall_grade[middle:]
merge_sort(left)
merge_sort(right)
merge(overall_grade, left, right)
def merge(overall_grade, left, right): #Função para comparar e organizar os termos.
i, j, k = 0, 0, 0
while (i<len(left)) and (j < len(right)):
if previous(left[i], right[j]):
overall_grade[k] = left[i]
i += 1
else:
overall_grade[k] = right[j]
j += 1
k += 1
while i < len(left):
overall_grade[k] = left[i]
i += 1
k += 1
while j < len(right):
overall_grade[k] = right[j]
j += 1
k += 1
def previous(left, right): #Função para definir qual termo é maior (define se o termo vai mudar de lugar ou não na merge).
if left[1] > right[1]:
return True
if left[1] < right[1]:
return False
if left[2] > right[2]:
return True
if left[2] < right[2]:
return False
if left[3] < right[3]:
return True
if left[3] > right[3]:
return False
if left[4] < right[4]:
return True
return False
def out_formatting(overall_grade): #Função para definir as maiores notas (5º) e recompensa-los com 2 pontos, além de printar o ranking atualizado.
ranking = overall_grade[:5]
for i in range(5, len(overall_grade)):
if overall_grade[i][1] >= ranking[len(ranking)-1][1] and overall_grade[i][2] >= ranking[len(ranking)-1][2] and overall_grade[i][3] <= ranking[len(ranking)-1][3]:
ranking.append(overall_grade[i])
for t in range(len(ranking)):
t1, t2, t3, t4, t5 = overall_grade[t]
overall_grade[t] = t1, t2+2, t3, t4, t5
for m in range(len(overall_grade)):
print (f'{overall_grade[m][4]} {overall_grade[m][1]}')
def main():
with open('entrada2.bin', 'rb') as file:
alunos, notas = pickle.load(file), pickle.load(file)
student(notas, alunos)
main() |
68cfe6a531368bda768d91b4c4885d3943a134e6 | gauthampaimk/Hangman | /Hangman.py | 6,196 | 4.21875 | 4 | import random
import string
WORDLIST_FILENAME = "words.txt" # Extracts the contents of 'words.txt' and stores it in the variable 'WORDLIST_FILENAME'.
# 'words.txt' contains a big number of words that are to be guessed in the game.
def loadWords():
"""
Function significance :
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..." # This prints the message telling that loading may take some time.
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0) # opens the file in read mode and returns file handle to the variable 'inFile'
# line: string
line = inFile.readline() # A string of the contents of the file is returned and stored in variable 'line'
# wordlist: list of strings
wordlist = string.split(line) # a list of words is formed using split() method of string class
print len(wordlist), "words loaded." # Number of words is printed in the screen
return wordlist # The list of words is returned
def chooseWord(wordlist):
"""
Function significance:
wordlist (list): list of words (strings)
Returns a word from wordlist at random
"""
# a word at random is chosen from the wordlist using choice() method of random class
return random.choice(wordlist)
def getAvailableLetters(lettersGuessed):
"""
Function significance :
Takes in one parameter - a list of letters, lettersGuessed.
This function returns a string that is comprised of lowercase English letters
- all lowercase English letters that are not in lettersGuessed.
"""
alp='abcdefghijklmnopqrstuvwxyz' # 'alp' is a string of letters of English alphabet
a='' # an empty string is created
for i in alp: # Iterates through all letters of alp
if i not in lettersGuessed:
a+=i # The string is appended with letters that are not guessed by player
# i.e. 'a' is a string of letters available to the player
return a
def getGuessedWord(secretWord, lettersGuessed):
"""
Function significance :
Takes in two parameters - a string, secretWord,
and a list of letters, lettersGuessed.
This function returns a string that is comprised of letters and underscores,
based on what letters in lettersGuessed are in secretWord.
"""
a=' ' # an empty string is created
for i in secretWord: # Iterates through the secret word generated in chooseWord
n=0 # set n=0 for every iteration
for j in lettersGuessed: # Iterates through 'lettersGuessed'
if j==i: # if letter guessed is in the secretWord,
n+=1 # increment the variable n
break # breaks on finding letter guessed in secretWord
if n!=0:
a+=i # The letter found in secret word is filled in Guessed Word 'a'
a+=' '
else:
a+='_' # an underscore is filled in Guessed word 'a' if letter is not guessed
a+=' '
return a # the (partial) Guessed word 'a' is returned
def isWordGuessed(secretWord, lettersGuessed):
"""
Function significance :
Takes in two parameters - a string, secretWord, and a list of letters, lettersGuessed.
This function returns a boolean - True if secretWord has been guessed
(ie, all the letters of secretWord are in lettersGuessed) and False otherwise.
"""
n=0
for i in secretWord: # Iterates through the secret word
if i in lettersGuessed: # if the letter in the iteration is in the list of guessed letters,
n+=1 # increment a variable 'n'
if n==len(secretWord): # if the value n is equal to length of secret word,
return True # Returns True as the player has guessed the word
else:
return False # else returns False as the player has failed in guessing
def hangman(secretWord):
"""
Function significance :
Takes a parameter - a string secret word
This is the method that starts the game and calls the above functions
"""
print 'Welcome to the game, Hangman!'
print 'I am thinking of a word that is',len(secretWord),'letters long.'
# Welcomes the player and tells him the number of letters in the word he has to guess
print '-------------'
lettersGuessed=list() # creates an empty list on a new game to fill the letters, the player has guessed
g=9 # 'g' is the variable to keep track of number of guesses player has used
while g!=0: # checks if player has run out of the number of guesses
g-=1 # decrements number of guesses on a guess
if g==0:
break
print 'You have',g,'guesses left.'
a=getAvailableLetters(lettersGuessed) # 'a' is a variable that has the letters available for player to guess
print 'Available letters:',a
b=raw_input('Please guess a letter:')
b=b.lower() # a guess is taken from player and it is converted to lowercase
lettersGuessed.append(b) # guessed letter is appended to list of guessed letters
c=getGuessedWord(secretWord,lettersGuessed) # 'c' is the guessed word (partial)
if b not in a: # checks if player tried to guess a letter he/she has already guessed
print 'Oops! You\'ve already guessed that letter:',c
g+=1
print '------------'
continue
if b not in secretWord: # checks if guessed letter is in secret word
print 'Oops! That letter is not in my word:',c
if b in secretWord: # if letter guessed is in secret word (an else can also be used here)
print 'Good guess:',c
g+=1 # the number of remaining guesses is incremented,
# giving a bonus to player on correct guess
n=isWordGuessed(secretWord,lettersGuessed) # 'n' is a boolean variable returned by isWordGuessed,
# to tell whether player is successful in guessing the secret word
print '------------'
if n==True:
break
if n==True: # Player has guessed the correct word
print 'Congratulations, you won!'
else: # Player failed in guessing the secret word
print 'Sorry, you ran out of guesses. The word was',secretWord
wordlist=loadWords() # a list of words is generated
secretWord = chooseWord(wordlist).lower() # a secret word is chosen at random
hangman(secretWord) # The game begins calling this function
|
88d90ac4e1efc3df9d71d3a333bf634918f67f32 | ayushgarg2702/Intern-Management-API | /common/common_filters.py | 152 | 3.515625 | 4 | import re
def CheckMobileNumber(param: str) -> bool:
if re.search(r"^[6-9]\d{9}$", str(param)):
return True
else:
return False |
aea9f514df21bf317438340e645f2a8d09438f2b | liviaasantos/curso-em-video-python3 | /mundo-1/ex024.py | 210 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 3 20:01:18 2021
@author: Livia Alves
"""
city = input('Em que cidade você nasceu: ')
city = city.upper().strip()
corte = city.split(' ')
print(corte[0] == 'SANTO')
|
b7e85a91199225c2ac3c1a41a3aa6648cfa6f28c | Oumar96/travelingstrategy-1 | /server/data/helper_class/wiki_weather_parser.py | 2,033 | 3.609375 | 4 | from bs4 import BeautifulSoup
class wiki_weather_parser:
def __init__(self, url, driver):
self.url = url
self.driver = driver
#This is the parser for the main tables which include
def visa_parser_table(self):
info ={}
self.driver.get(self.url)
#Selenium hands the page source to Beautiful Soup
soup = BeautifulSoup(self.driver.page_source, 'lxml')
visa = " "
all_tables = soup.findAll('table', {"class": "wikitable"})[0:6]
for table in all_tables:
table_body = table.find('tbody')
table_rows = table_body.find_all('tr')
x = 0
for tr in table_rows:
# x = x+1
cols = tr.find_all('td')
cols = [ele.text.strip() for ele in cols]
if(len(cols) > 0): #To avoid parsing table headers and antartica
country_name = cols[0]
city_name = cols[1]
january_temp = cols[2].split('(')[0]
february_temp = cols[3].split('(')[0]
march_temp = cols[4].split('(')[0]
april_temp = cols[5].split('(')[0]
may_temp = cols[6].split('(')[0]
june_temp = cols[7].split('(')[0]
july_temp = cols[8].split('(')[0]
august_temp = cols[9].split('(')[0]
septembre_temp = cols[10].split('(')[0]
octobre_temp = cols[11].split('(')[0]
novembre_temp = cols[12].split('(')[0]
decembre_temp = cols[13].split('(')[0]
info[city_name] = {"january":january_temp, "february":february_temp, "march":march_temp, "april":april_temp, "may":may_temp, "june":june_temp, "july":july_temp, "august":august_temp, "septembre":septembre_temp, "octobre":octobre_temp, "novembre":novembre_temp, "decembre":decembre_temp }
return info
def set_url(self, url):
self.url = url
|
3f63dc60b0fd95bcc0b7ee34e28cc5983fd2ec8a | BenRauzi/159.172 | /Tutorial 8/text_therapist.py | 2,912 | 3.875 | 4 | import random
hedges = ( "Please, tell me a little more.",
"Many of my patients tell me the same thing.",
"Please, carry on talking." ,
"What is your point?")
qualifiers = ("Why do you say that ",
"You seem to think that ",
"Can you explain why ")
#I have also changed all functions to use word.lower() so that capitalisation does not lead to the words not being changed.
replacements = {"I":"you", "me":"you", "my":"your","we":"you", "us":"you", "mine":"yours", "am":"are", "you": "I", "are": "am", "you're": "I'm"}
#really don't know any more single-word abbreviations
text_replacements = {
"you": "u",
"are": "r",
"your": "ur",
"you're": "ur"
}
#dict is inefficient for this but instructions say to use - and this is a tutorial on dicts so I guess I will
vowels = {
"a": "",
"e": "",
"i": "",
"o": "",
"u": ""
}
history = []
def removeVowels(word):
new_word = ""
for char in word:
new_word += vowels.get(char.lower(), char)
return new_word
def changetoText(sentence):
words = sentence.split()
processed_words = []
for word in words:
new_word = text_replacements.get(word.lower(), word)
#some 4 character words are really hard to read with vowels removed. Oh well, instructions haha.
if len(new_word) > 3:
processed_words.append(removeVowels(new_word))
else:
processed_words.append(new_word)
return " ".join(processed_words)
def reply(sentence):
"""Builds and returns a reply to the sentence."""
probability = random.randint(1, 20)
#print(probability) #not getting caught out on this again like in the test where I lost marks for fully removing the print statement, even though it wasn't needed after testing haha.
history.append(sentence)
if probability <= 5:
return random.choice(hedges)
elif probability >= 18 and len(history) > 5:
#'Earlier' gets hit really hard by the abbreviations... 'rlr'
return f"Earlier, you said that {changePerson(random.choice(history))}"
else:
return random.choice(qualifiers) + changePerson(sentence) + " ?"
def changePerson(sentence):
"""Replaces first person pronouns with second person pronouns."""
words = sentence.split()
replyWords = []
for word in words:
replyWords.append(replacements.get(word.lower(),word))
return " ".join(replyWords)
def main():
"""Handles the interaction between patient and doctor."""
print(changetoText("Good morning, I hope that you are well today ?"))
print(changetoText("What can I do for you ?"))
while True:
sentence = input("\n>> ")
if sentence.upper() == "QUIT":
print(changetoText("Have a nice day"))
break
print(changetoText(reply(sentence)))
main()
|
fbd4ee6e35f6905e3c4dbeea7ef8ec5a9dfd8c43 | shahbagdadi/py-algo-n-ds | /sortSearch/searchSuggestionSystem/Solution.py | 551 | 3.53125 | 4 | from bisect import bisect_left
from typing import List
class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
products.sort()
i , prefix , res = 0 , '' , []
for c in searchWord:
prefix += c
i = bisect_left(products,prefix,i)
res.append([x for x in products[i:i+3] if x.startswith(prefix) ])
return res
s = Solution()
ip = ["bags","baggage","banner","box","cloths"]
word = 'bags'
ans = s.suggestedProducts(ip,word)
print(ans) |
86b703d029d254e88c938b08d413f0a844143779 | ragulkesavan/python-75-hackathon | /WRITE FILE/line_by_line.py | 469 | 3.546875 | 4 | #WRITING INTO FILE LINE BY LINE
#opening file in w mode
f=open("lyrics.txt","w")
''' USING write() FUNCTION WE CAN WRITE LINE BY LINE INTO FILES ,EACH ATTRIBUTE OF write() IS A LINE STRING AND SHOULD END WITH "\n" OR EOL '''
f.write("Spent 24 hours\n")
f.write("I need more hours with you\n")
f.write("You spend the week end\n")
f.close()
f=open("lyrics.txt","r")
print f.read()
f.close()
'''
OUTPUT
Spent 24 hours
I need more hours with you
You spend the week end
'''
|
f5bb794391c32a84d05a80a2fd595437b3eabb92 | vmred/Coursera | /coursera/python-basic-programming/week1/hw18.py | 733 | 4.03125 | 4 | # Электронные часы показывают время в формате h:mm:ss,
# то есть сначала записывается количество часов (число от 0 до 23),
# потом обязательно двузначное количество минут, затем обязательно двузначное количество секунд.
# Количество минут и секунд при необходимости дополняются до двузначного числа нулями.
value = int(input())
m = value // 60 % 60
if m < 10:
m = '0{}'.format(m)
s = value % 60
if s < 10:
s = '0{}'.format(s)
print('{}:{}:{}'.format(value // 3600 % 24, m, s))
|
e61883b63f0ff3c5308dea1a7f6522cf7219866a | statho7/PythonExamples | /export_csv_from_multiple_csv_files.py | 2,184 | 3.71875 | 4 | import sys
import pandas as pd
import os
def Run(action, *args):
if action == 'merge':
Merge(args)
elif action == 'concatenate':
Create_the_combined_csv_file(args)
def Create_the_combined_csv_file(export_filename, *args):
# CSV to Pandas DataFrame the first 2 CSV files
csv_1 = pd.read_csv(f'{args[0][0]}')
csv_2 = pd.read_csv(f'{args[0][1]}')
# Append the first csv to the other
export_csv = csv_1.append(csv_2, ignore_index=True)
# If more than 2 CSV files have been mentioned in command line this will run
try:
# For every extra csv file we are creating a Pandas DataFrame and then append it to the existing one to export
for arg in args[0][2:]:
csv_2 = pd.read_csv(f'{arg}')
export_csv = export_csv.append(csv_2, ignore_index=True)
except:
pass
# After appending all the Pandas DataFrame to the export_csv DataFrame we are exporting it to a CSV file with the name mentioned in the command line
export_csv.to_csv(f'{export_filename}', index=False)
def Merge(export_filename, column, join, *args):
# CSV to Pandas DataFrame the first 2 CSV files
csv_1 = pd.read_csv(f'{args[0][0]}')
csv_2 = pd.read_csv(f'{args[0][1]}')
# Append the first csv to the other
export_csv = csv_1.merge(csv_2, on=column, how=join)
# If more than 2 CSV files have been mentioned in command line this will run
try:
# For every extra csv file we are creating a Pandas DataFrame and then append it to the existing one to export
for arg in args[0][2:]:
csv_2 = pd.read_csv(f'{arg}')
export_csv = export_csv.merge(csv_2, on=column, how=join)
except:
pass
# After appending all the Pandas DataFrame to the export_csv DataFrame we are exporting it to a CSV file with the name mentioned in the command line
export_csv.to_csv(f'{export_filename}', index=False)
if __name__ == '__main__':
# Install pandas if you do not have already
os.system("pip install pandas")
try:
Run(str(sys.argv[1]),str(sys.argv[2]),sys.argv[3:])
except:
print('You should state more arguments') |
881afdd855296901476e045d44b15d8a6730a82e | acunaMatata22/Jump-Chess | /utils.py | 632 | 3.734375 | 4 | # generally helpful functions used throughout the application
def squarePos(num):
# returns the XY coordinates of the squares for initialization render
# NOTE: for drawing only, not for indexing
return (num % 8 - 3.5, (num % 64) // 8, (num // 64) * 1.13)
def indexToTuple(num):
# used to reference the coordinate of a specific 0-127 indexed square
return (num // 64, (num % 64) // 8, (num % 64) % 8)
def tupleToIndex(coordinates):
# used to get square index from a coordinate tuple
total = 0
total += coordinates[0] * 64
total += coordinates[1] * 8
total += coordinates[2]
return total |
90e552006875ac9ab9d1b7740130ec8128022562 | NathanKinney/class_ocelot | /Code/jon/lab14_bogosort.py | 673 | 3.609375 | 4 | import random
def random_list(n):
lst = []
for i in range(n - 1):
lst.append(random.randrange(0, 20))
return lst
def shuffle(lst):
for i in range(len(lst)):
s = random.randrange(len(lst))
t = lst[i]
lst[i] = lst[s]
lst[s] = t
def is_sorted(lst):
for i in range(1, len(lst)):
#print(lst[i - 1], lst[i])
if lst[i - 1] > lst[i]:
return False
return True
lst = random_list(20)
saved_list = lst.copy()
shuffle(lst)
print(saved_list)
print(lst)
i = 0
while not is_sorted(lst):
i += 1
shuffle(lst)
if i%100 == 0:
print(i)
print(f' That took {i} tries')
|
0ac9c1e00bf08f0f3abcbcdfd9a72cc05041f91f | jbp4444/PyGenAlg | /nc_dist12/check_files.py | 1,932 | 3.5 | 4 |
import csv
def main():
zip_to_congr = {}
with open('zip_to_congr.csv','r') as fp:
readCSV = csv.reader( fp, delimiter=',' )
# skip 2 headers
next( readCSV, None )
next( readCSV, None )
# now read all the actual data
for row in readCSV:
zip_to_congr[row[1]] = 1
nc_zips = {}
with open('nc_data.zip.txt','r') as fp:
readCSV = csv.reader( fp, delimiter=',' )
# skip 2 headers
next( readCSV, None )
next( readCSV, None )
# now read all the actual data
for row in readCSV:
nc_zips[row[1]] = 1
all_zips = {}
with open('gaz2015zcta5centroid.csv','r') as fp:
readCSV = csv.reader( fp, delimiter=',' )
# skip 1 header
next( readCSV, None )
# now read all the actual data
for row in readCSV:
all_zips[row[2]] = 1
nc_zips2 = {}
with open('pop_per_zip.csv','r') as fp:
readCSV = csv.reader( fp, delimiter=',' )
# skip 2 headers
next( readCSV, None )
next( readCSV, None )
# now read all the actual data
for row in readCSV:
nc_zips2[row[1]] = 1
print( 'scanning nc_data.zip.txt to zip_to_congr.csv ...' )
for zip in nc_zips.keys():
if( not zip in zip_to_congr ):
print( 'NOT found: '+zip )
print( '\nscanning zip_to_congr.csv to nc_data.zip.txt ...' )
for zip in zip_to_congr.keys():
if( not zip in nc_zips ):
print( 'NOT found: '+zip )
print( '\nscanning nc_data.zip.txt to all_zips ...' )
for zip in nc_zips.keys():
if( not zip in all_zips ):
print( 'NOT found: '+zip )
print( '\nscanning zip_to_congr.csv to all_zips ...' )
for zip in zip_to_congr.keys():
if( not zip in all_zips ):
print( 'NOT found: '+zip )
print( '\nscanning pop_per_zip to all_zips ...' )
for zip in nc_zips2.keys():
if( not zip in all_zips ):
print( 'NOT found: '+zip )
print( '\nscanning pop_per_zip to zip_to_congr.csv ...' )
for zip in nc_zips2.keys():
if( not zip in zip_to_congr ):
print( 'NOT found: '+zip )
if __name__ == '__main__':
main()
|
970e66a9151074cbbe3c5226f9fb5083ceab437b | kennycaiguo/Heima-Python-2018 | /15期/00Python基础/1-3 面向对象/02-面向对象练习/01-小明爱跑步.py | 476 | 3.5625 | 4 | class Personal:
def __init__(self, name, weight):
self.name = name
self.weight = weight
def __str__(self):
return "我的名字叫%s,体重是%.2f公斤" % (self.name, self.weight)
def run(self):
print("%s可以跑步"%self.name)
self.weight -=0.5
def eat(self):
print("%s可以吃东西"%self.weight)
self.weight +=0.5
xiaoming = Personal("小明",75.0)
xiaoming.run()
xiaoming.eat()
print(xiaoming) |
1a08e6c80c0e72e886a3b4a393be45d017c260bd | adiG48/voice_assistant_app | /document.py | 18,215 | 3.8125 | 4 | '''Voice_assistant_app:
I was inspired by following things(voice assistants like Alexa, Siri,Google,Jarvis etc.) and it made me to search more about it and make a one for me. I made my Voice Assistant(@diG48)using Python. The query for the assistant can be manipulated as per the user’s need.
Speech recognition is the process of converting audio into text. Python provides an API called Speech_Recognition to allow us to convert audio into text for further processing. In this article, we will look at converting large or long audio files into text using the SpeechRecognition API in python.To make the voice_assistant_app more interactive and do more functions,I used many built in modules such as
pyttsx3, datetime, speech_recognition, pywhatkit, Wikipedia, smtplib, pyjokes.
I explained about every madule and whole code line by line as follows….
*IMPORTING ALL NEEDED MODULES:
I used pip to install all the commands in the terminal of pycharm. So we can use all the modules whenever needed without any errors, the command to install the modules are listed below.
Import all the following modules:'''
from tkinter import *
import pyttsx3
import datetime
import speech_recognition as sr
import pywhatkit
import wikipedia
import smtplib
import pyjokes
from email.message import EmailMessage
''' *pip install tkinter
*pip install pyttsx3
*pip install speech_recognition
*pip install pywhatkit
*pip install wikipedia
*pip install smtplib
*pip install emails
*pip install pyjokes '''
'''*FRONT_END_PART:
I had made the frontend part for my voice_assistant_app using Tkinter in python. I used this because it is easy to make window and buttons and we can display the content whenever needed easily and can update the screen while running easyly.
*pip install tkinter'''
Code:
from tkinter import * #importing everything from the module.
window = Tk() #creting the tkinter window.
global var # declaring 2 global variables to access it any where.
global var1
var = StringVar() # stringVar() is a tkinter module that holds the string values, by default it holds “” empty string.
var1 = StringVar() # to hold the values that user says we are assigning it the variable which can be updated while running.
label2 = Label(window, textvariable=var1, bg='#FAB60C')# labling the window using label(), ‘text variable’ is the value that we want to display so I’m assigning it to the variable ‘var1’ so it can be updated when the value changes, finally passing the third argument as background color, we can use any color code as a background.
label2.config(font=("Courier", 20)) # configuring our text such as font and size using ‘.config()’.
var1.set('User Said:') # initially setting the value that to be displayed which is an optional one
label2.pack() # it is used to update the widjet we made with minimal space and block of allocation.
label1 = Label(window, textvariable=var, bg='#ADD8E6') # same as above setting another variable
label1.config(font=("Courier", 20))
var.set('Welcome')
label1.pack()
frames = [PhotoImage(file='Assistant3.gif', format='gif -index %i' % i) for i in range(100)] #Tkinter Photoimage is one of the built-in methods which has been used to add the user-defined images in the application. Iterating it over a for loop since to animate the gif.
window.title('@diG48') # giving title to our window using ‘.title()’
label = Label(window, width=1000, height=500) # labling the window dimensions
label.pack()
window.after(0, update, 0)# This method calls the function FuncName after the given delay in milisecond
btn1 = Button(text='START', width=23, command=play, bg='#5C85FB') # creating the buttons on the window using button(),which takes arguments such as text and font size, if the buuton is pressed taking the command varible to operate some functions
btn1.config(font=("Courier", 12)) # configuring the buttons
btn1.pack()
btn2 = Button(text='EXIT', width=25, command=window.destroy, bg='#12cee3') # adding another button named exit and using a built in module to destroythe window created.
btn2.config(font=("Courier", 12))
btn2.pack()
window.mainloop() # window.mainloop() tells Python to run the Tkinter event loop. This method listens for events, such as button clicks or keypresses, and blocks any code that comes after it from running until the window it’s called on is closed.
'''* UPDATE MODULE:
Used to update the gif on the screen after the specified amount of time.
def update(ind): # used to update the gif. '''
frame = frames[ind % 100]
ind += 2
label.configure(image=frame)
window.after(100, update, ind) # updating the gif after specified time of intervals.
'''*PYTTSX3 MODULE:
First to make the app interactive with the user I made use of pyttsx3(python text to speech module) which speaks the text what we have typed.
*pip install pyttsx3 '''
Code:
import pyttsx3 #importing the module
engine = pyttsx3.init() #initializing speech-text in var engine
voices = engine.getProperty('voices') #from pyttsx3 getting property as voices and assigning it to voices
engine.setProperty('voice', voices[1].id) #from built in voices we are setting it to a female voice using “voice[1]”, to use a male voice we can use “voice[0]”
#To speak what we have typed I defined a function as follows:
Code:
def speak(audio):
engine.say(audio) # say is a module that speaks what we send as input.
engine.runAndWait() # to make it wait wait for the users response.
When we call this function with an argument with strings it will speak it.
'''*SPEECH_RECOGINITION MODULE:
To get the voice from user and convert it into text this module is used.
*pip install speech_recoginition
I put everything inside a function named “take_command():”'''
Code:
import speech_recognition as sr # importing the module as sr to call it with easy way.
def takecommand(): # function to take command from user
r = sr.Recognizer() #initializing r as recognizer of our voice.
with sr.Microphone() as source: # making our microphone as source to take voice.
var.set("Listening...") #used in app to diplay
window.update() #updating the window of the app to make the changes what we did.
print("Listening...")
r.pause_threshold = 1 # making the pause threshold of our voice as 1
r.energy_threshold = 400 # if our voice is over the threshold of 400 it will recognize it
audio = r.listen(source) #listening the voice using listen() and assigning it to audio.
try:
var.set("Recognizing...")
window.update()
print("Recognizing")
query = r.recognize_google(audio, language='en-in') # recognizing the audio with google with language as Indian English.
except Exception as e: #exception block to avoid errors if nothing is said.
return "None"
var1.set(query)
window.update()
return query # finally retuning the value of query which we use later in the app.
'''*EMAIL_SENDER_MODULE:
Simple Mail Transfer Protocol (SMTP) is a protocol, which handles sending e-mail and routing e-mail between mail servers.
Python provides smtplib module, which defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon.
Here is a simple syntax to create one SMTP object, which can later be used to send an e-mail :
Code:
import smtplib
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )'''
def send(msg):
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: # logging into the smtp server.
smtp.login('Enter the mail id', 'password') #login into your email id from where u want send messages. “# Make sure to give app access in your Google account” to do so follow go to the mail settings security less secure app access turn it on.
smtp.send_message(msg) # sending the message using the builtin sen_message().
try: # Trying this block of code if user wants to send an email.
msg = EmailMessage() #used to pass the values to a variable as in E-Mail format like from,to and subject.
c = {'name1': 'mail id', name2': mail id'} # giving the name as key and assigning it with the respected mail id’s.
speak('To Whom You Want To Send Email') # Speaks what is inside the quotes.
b = takecommand() # from user taking command as voice and assigning it to a variable.
d = c[b] # checking wether the key is present what user command.
msg['To'] = d # assigning TO message of the E-mail
speak('Tell Me The Subject In Your Email')
a = takecommand() # Taking command from user for subject
msg['Subject'] = a # assigning SUBJECT of the E-Mail
msg['From'] = '[email protected]' # assigning FROM of the E-Mail.
speak('Tell Me The Content Of The Email')
e = takecommand()
msg.set_content(e) # setting the content of the E-Mail.
send(msg) # send() is used to send the message to the desired one and it is passed to the function that we have decleared earlier.
var.set('Your Email Has Been Sent Sir!!') # to display on the screen
speak('Your Email Has Been Sent Sir!!') # confirmation message said by our voice_assistant.
except Exception as e: # excepting the errors as e, to make exception hanling while running.
print(e)
var.set("Sorry Sir! I was not able to send this email")
window.update()
speak('Sorry Sir! I was not able to send this email') # say’s this when an exception occurs or the E-mail is not sent.
'''*WISH_MODULE:
I made this function to greet the user whenever he presses the play button, my voice_Assistant will greet the user according to the current time in their system. This function can later called when we are inquiring our command from the user.'''
Code:
def wishme():
hour = int(datetime.datetime.now().hour) # from datetime module we are getting the current time of the system in hours.
if (hour >= 0) and (hour <= 12): # it will check the hour and greet us according to the time hour condition we mentioned
var.set("Good Morning Sir")
window.update()
speak("Good Morning Sir!")
elif (hour >= 12) and (hour <= 18):
var.set("Good Afternoon Sir!")
window.update()
speak("Good Afternoon Sir!")
else:
var.set("Good Evening Sir")
window.update()
speak("Good Evening Sir!")
speak("Myself @diG48! How may I help you sir") # after greeting us it will say it’s name and ask us how it could help us.
'''*PLAY_MODULE:
I had put everything that is to be done when the play button is pressed. I used simple ‘if elif else’ condition statements to check wether the user said is present in there are not using ‘in’ statement. I put like playing musics, asking who is that person,greet, time, date, name of the bot, by whom it created, saying hello to everyone, sending E-Mail, sending whatsapp messages and giving some inbuilt jokes etc… we can make more tasks to be done if we want.'''
Code:
def play(): # this module is called when the play button on the screen is pressed.
btn2['state'] = 'disabled' # then I made the exit button disabled.
btn1.configure(bg='orange') # changing the color of the buttons after the play button is pressed.
btn2.configure(bg='#5C85FB') # changing the color of the buttons after the play button is pressed.
wishme() # calling the wishme() module to greet the user.
while True: # until the exit button is enabled it will execute repeatedly.
btn1.configure(bg='orange') # changing the button color.
query = takecommand().lower() # converting everything from takecommand() to lower case which is said by the user to execute further.
if 'exit' in query: # if the user asks or says exit in takecommand() this block will be executed.
var.set("Bye sir")
btn1.configure(bg='#5C85FB') # changing the color of the buttons back to intial stage.
btn2['state'] = 'normal' # enabling the exit button to quit the program.
btn2.configure(bg='#12cee3')
window.update()
speak("Bye sir") # saying bye to the user
break # breaking the looping statement.
elif 'play' in query: # if user asks to play something it will be played in youtube.
song = query.replace('play', '') # removing the play statement said by the user and searching the other in YT.
speak('Playing' + song) # says palyin the song which u said.
pywhatkit.playonyt(song) # pywhatkit’s inbuilt module to paly anything on YT.
window.update() # updating the window
takecommand()
window.update() # updating the window after exit from YT.
elif 'who is' in query: # if user asks who is this/that person is this block will be executed.
person = query.replace('who is', '') # replacing or removing who is and taking only the name of the person.
info = wikipedia.summary(person, 1) # wikipedia’s inbuilt module to search about a person in google and taking only the 1 statement.
speak(info) # this will call the speak module and speak the information what it got from Wikipedia.
elif 'greet' in query: # if user says gteet it will wish what we said in the speak module and displays it as its value is assigned to a global variable ‘var’.
var.set('Hello Sir, have a nice day')
window.update()
speak("Hello Sir, have a nice day")
elif 'the time' in query: # if user asks for time this block will be executed.
strtime =datetime.datetime.now().strftime("%H:%M:%S") #this statement will fetch the correct time in our system using the builtin module datetime() and give us the format in which we want.
var.set("Sir the time is %s" % strtime)
window.update()
speak("Sir the time is %s" % strtime)
elif 'the date' in query: # if user asks for the date today it will fetch the current date in which format we specified.
strdate = datetime.datetime.today().strftime("%d %m %y") # using datetime() method we can refer the date.
var.set("Sir today's date is %s" % strdate)
window.update()
speak("Sir today's date is %s" % strdate)
elif 'thank you' in query: # if user says thank you this block will be executed and speaks whatever given in speak().
var.set("Welcome Sir")
window.update()
speak("Welcome Sir")
elif 'your name' in query: # if user asks for the robots name it will say the following which is specified inside this block.
var.set("Hi, Im @diG48 the Robot. Speed 1 terahertz, memory 1 zigabyte ")
window.update()
speak('Hi, Im @diG48 the Robot. Speed 1 terahertz, memory 1 zigabyte ')
elif 'who created you' in query: # if user asks for who created the robot the following statements will be executed.
var.set('I was created by AdithyaaG48')
window.update()
speak('I was created by AdithyaaG48')
elif 'say hello' in query: # if user asks say hello the following statement will be executed.
var.set('Hello Everyone! My self @diG48')
window.update()
speak('Hello Everyone! My self @diG48')
elif 'email' in query: # if user wants to send an email this E-Mail module which I mentioned above will be executed.
try:
msg = EmailMessage()
c = {'black': '[email protected]', 'Shiny mam': '[email protected]'}
speak('To Whom You Want To Send Email')
b = takecommand()
d = c[b]
msg['To'] = d
speak('Tell Me The Subject In Your Email')
a = takecommand()
msg['Subject'] = a
msg['From'] = '[email protected]'
speak('Tell Me The Content Of The Email')
e = takecommand()
msg.set_content(e)
send(msg)
var.set('Your Email Has Been Sent Sir!!')
speak('Your Email Has Been Sent Sir!!')
except Exception as e:
print(e)
var.set("Sorry Sir! I was not able to send this email")
window.update()
speak('Sorry Sir! I was not able to send this email')
elif 'joke' in query: # if user asks for a joke this will be executed.
speak(pyjokes.get_joke()) # pyjokes module has builtin function to get some of the builtin jokes inside it’s module and gives us a random joke whenever executed.
'''To make the app more beautiful, I added more images and made them to display on the window when the respected block is executing. I added it by a simple way as follows
Created more frames and called it whenever needed'''
Code:
frames0 = [PhotoImage(file='name.png')] # initializing the frames with desired images using ‘PhotoImage() method’.
frames1 = [PhotoImage(file='creator.png')]
frames2 = [PhotoImage(file='time.png')]
frames3 = [PhotoImage(file='MAIL.png')]
frames4 = [PhotoImage(file='date.png')]
frames5 = [PhotoImage(file='WA.png')]
frames6 = [PhotoImage(file='hello.png')]
frames7 = [PhotoImage(file='joker.png')]
frames8 = [PhotoImage(file='YT.png')]
frames9 = [PhotoImage(file='creator.png')]
frames10 = [PhotoImage(file='bye.png')]
frames11 = [PhotoImage(file='who.png')]
frames12 = [PhotoImage(file='welcome.png')]
Calling the frames whenever needed as follows and updating the window then and there.
Code:
label.configure(image=frames0) # configuring the window with the respected image.
window.update() # updating the window to view the updated image.
|
cd7f67f8c7cf41654e6b6357eb25c100583ee88b | yddong/Py3L | /src/Week2/s2-dict-1.py | 264 | 3.71875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
German = 0
English = 1
Polish = 2
mydict = {}
mydict["krava"] = [ "Kuh", "cow", "krowa" ]
mydict["pas"] = [ "Hund", "dog", "pies" ]
mydict["konj"] = [ "Pferd", "horse", "koń", "使" ]
print( mydict["konj"] )
|
c09a012d002dd7b15e8b4396965333555f8b5ce1 | ShimpeiARK/python-for-trainig | /a.py | 3,603 | 3.703125 | 4 | #!/usr/bin/python
# -*- Coding: utf-8 -*-
array = list(map(int, input(),split(' ')))
2転換距離
'''
=============================
import random
def randomlist(size):
list=[]
for i in range(1,size+1):
list.append(random.randint(0,100)):
return list
print (list)
=============================
list=["A","B","C"]
list.append("D")
print(list)
============================
a=input()
for i in range(int(a)):
print('Hello!')
=============================
import sys
m=0
for i in range (30):
if m%15==0:
print('fizzbuzz')
m+=1
elif m%3==0:
print('fizz')
m+=1
elif m%5==0:
print('buzz')
m+=1
else:
print(m)
m+=1
=============================
sum=0
for x in range (1,51):
sum += x
print (sum)
=============================
def checkio(number):
if number%5 ==0 and number%3 ==0:
print("Fizz Buzz")
elif number%5 ==0:
print("Buzz")
elif number%3 ==0:
print("Fizz")
else:
print(str(number))
=============================
max=int(10)
x,y=int(1),int(1)
for i in range(max):
print (x,y)
x=x+y
y=x+y
=============================
int(input())
if sei%100==0 and sei%400 !=0:
print('heinenn')
elif sei%4 ==0:
print('uruudosi')
else:
print('heinenn')
=============================
s=0
for i in range(1,50):
s= s+i
print(s)
=============================
#!/usr/bin/python
# coding: utf-8
def keisan(a,b):
if a > b:
while b != 0:
r = a
a = b
b = r % b
return a
else:
print ("AにはBより大きい数字を入れて下さい。")
exit()
a = int(input())
b = int(input())
c = keisan(a,b)
print (a,"と",b,"の最大公約数は",c,"です。")
=============================
import math
a =input()
b=math.sqrt(int(a))
print ("%.5f"% (b))
=============================
N=int(input())
c=int(input())
a=[0]
for N in set(c):
a.append(c.count(N))
print(max(a),min(a))
=============================
N=int(input())
c=list(int(input()))
ans=[0,0,0,0]
for i in range(N):
if c[i]==1:
ans[0]+=1
elif c[i]==2:
ans[1]+=1
elif c[i]==3:
ans[2]+=1
else:
ans[3]+=1
ans.sort()
print(str(ans[3])+""+str(ans[0]))
=============================
N=int(input())
c=input()
ans_max=0
ans_min=N
for i in range(1,5):
tmp=c.count(str(i))
ans_max=max(ans_max,tmp)
ans_min=min(ans_min,tmp)
print(ans_max,ans_min)
=============================
A,B = map(int, input().split())
C=abs(A-B)
co=int(0)
while C>=8:
co+=1
C-=10
while 3<=C<8:
co+=1
C-=5
C=abs(C)
print(C+co)
=============================
N=int(input())
c=input()
GPA=int(0)
for i in c:
if i=="A":
GPA+=4
elif i=="B":
GPA+=3
elif i=="C":
GPA+=2
elif i=="D":
GPA+=1
elif i=="F":
GPA+=0
GPA=GPA/N
print(GPA)
=============================
A,B=map(int,input().split(" "))
if A>=B:
print(A)
else:
print(B)
'''
if A[0]>=A[1]:
print(A[0])
else:
print(A[1])
'''
A=input().split(" ")
if int(A[0])>=int(A[1]):
print(A[0])
else:
print(A[1])
=============================
N=int(input())
s=0
for i in range(1,N+1):
s+=10000*i*(1/N)
print(s)
=============================
N=int(input())
if N%100==0 and N%400 !=0:
print('NO')
elif N%4 ==0:
print('YES')
else:
print('NO')
=============================
a,b = input(), input()
def gcd(a,b):
if b==0:
return a
else:
return gcd(b,a%b)
print (gcd(int(a),int(b)))
=============================
'''
|
10483d09762a412329daf776194a3713fe1176fd | sinystr/hackbulgaria | /week11/task_2_laptop_bg.py | 1,978 | 3.71875 | 4 | class Product:
def __init__(self, name, stock_price, final_price):
self.name = name
self.stock_price = stock_price
self.final_price = final_price
def profit(self):
return self.final_price - self.stock_price
class Laptop(Product):
def __init__(self, name, stock_price, final_price, diskspace, RAM):
super().__init__(name, stock_price, final_price)
self.diskspace, self.RAM = diskspace, RAM
class Smartphone(Product):
def __init__(self, name, stock_price, final_price, display_size, mega_pixels):
super().__init__(name, stock_price, final_price)
self.display_size, self.mega_pixels = display_size, mega_pixels
class Store:
def __init__(self, name):
self.name = name
self.products = {}
self.income = 0
# helps us to find if we have added the product before
def _exists_in_store_(self, product):
for key in self.products:
if key == product:
return True
return False
def _store_has_it_(self, product):
if self._exists_in_store_(product) and self.products[product] > 0:
return True
return False
def _execute_sell_(self, product):
self.income += product.profit()
self.products[product] -= 1
def load_new_products(self, product, count):
if isinstance(product, Product):
if self._exists_in_store_(product):
self.products[product] += count
else:
self.products[product] = count
def list_products(self, type_product):
for key in self.products:
if isinstance(key, type_product):
print("{} - {}".format(key.name, self.products[key]))
def total_income(self):
print(self.income)
def sell_product(self, product):
if self._store_has_it_(product):
self._execute_sell_(product)
return True
return False
|
f90a5a51eaaec5fb56d2aeee0120fc59315d28cc | MahrukhKhaan/IDLE-based-LMS | /win2.py | 1,722 | 3.59375 | 4 | from tkinter import *
class MainMenu(Frame):
def __init__(self,parent):
Frame.__init__(self, parent)
Frame.config(self, width=500,height=500,bg='misty rose')
Frame.pack(self, side=LEFT)
self.parent=parent
labelmain= Label(self,text="MAIN MENU",font=("bold",18),bg='misty rose')
labelmain.place(x=150,y=30)
button1= Button(self,text="1.Borrow Books",font=("bold",10),command= lambda: self.BorrowBooks())
button1.place(x=120,y=100)
button2= Button(self,text="2.Available Books",font=("bold",10),command= lambda: self.AvailableBooks())
button2.place(x=120,y=140)
button3= Button(self,text="3.Return Books",font=("bold",10),command= lambda: self.ReturnBooks())
button3.place(x=120,y=180)
backbutton = Button(self, text="LOG OUT",command= lambda: self.back())
backbutton.place(x=430, y=10)
nextbutton= Button(self,text='NEXT',width=20,font=("bold",10),bg='floral white')
nextbutton.place(x=180,y=280)
def back(self):
import win0_1
self.parent.CurrentPage=win0_1.UserLogin(self)
self.parent.CurrentPage.tkraise()
def BorrowBooks(self):
import win2_0
self.parent.CurrentPage=win2_0.BorrowBooks(self)
self.parent.CurrentPage.tkraise()
def AvailableBooks(self):
import win2_1
self.parent.CurrentPage=win2_1.AvailableBooks(self)
self.parent.CurrentPage.tkraise()
def ReturnBooks(self):
import win2_2
self.parent.CurrentPage=win2_2.ReturnBooks(self)
self.parent.CurrentPage.tkraise()
|
a9faf34499ef85ad3a0ad07db3fdbb0894ef0afe | celeist666/ProgrammersAlgo | /전화번호 목록.py | 374 | 3.65625 | 4 | # 문자열을 정리해두면 접두사인 번호가 앞에 나오고 그 바로 뒤에 해당 번호를 접두사로 두는 번호가
# 나온다. 그렇기에 n번씩만 비교하면된다.
def solution(phoneBook):
phoneBook = sorted(phoneBook)
for p1, p2 in zip(phoneBook, phoneBook[1:]):
if p2.startswith(p1):
return False
return True
|
b43f9be62b3f456075051fd48bbeae47a80e7832 | Taving40/Python_Design_Patterns | /Strategy_pattern/Strategy_pattern_solution.py | 1,943 | 4.1875 | 4 | from __future__ import annotations
from abc import ABC #abstract base class (deriving from this results in an abstract class)
from abc import abstractmethod
"""The solution is to turn the fly method into an interface in the base class
to ensure that every child Duck class implements it (since all Ducks should have something to do with flying)
but we create a separate interface for every type of behaviour that the fly interface can take
and each child implements one of those."""
class IFlyStrategy(ABC):
"""Interface for Strategy type classes that model the flying behavior"""
@abstractmethod
def fly(self):
pass
class ConcreteStrategyFlyCannot(IFlyStrategy):
def fly(self):
print("I can't fly!!!")
class ConcreteFlyStrategyCan(IFlyStrategy):
def fly(self):
print("I can fly!!!")
class Duck:
def __init__(self, fly_strategy):
self._fly_strategy = fly_strategy
def quack(self):
print("All ducks can quack!")
def display(self):
print("I'm a generic duck!")
def fly(self):
self._fly_strategy.fly()
class WildDuck(Duck):
def __init__(self, fly_strategy):
self._fly = fly_strategy
def display(self):
print("I'm a wild duck!")
class CityDuck(Duck):
def __init__(self, fly_strategy):
self._fly = fly_strategy
def display(self):
print("I'm a city duck!")
class RubberDuck(Duck):
def __init__(self, fly_strategy):
self._fly = fly_strategy
def display(self):
print("I'm a rubber duck!")
class PenguinDuck(Duck):
def __init__(self, fly_strategy):
self._fly = fly_strategy
def display(self):
print("I'm a rubber duck!")
def main():
simple_duck = Duck(ConcreteFlyStrategyCan())
simple_duck.fly()
rubber_duck = Duck(ConcreteStrategyFlyCannot())
rubber_duck.fly()
if __name__ == "__main__":
main()
|
986bfa374e8bf0e454af9778c76251408ec77c5a | madtyn/pythonHeadFirst | /pythonDesignPatterns/src/composite/menuiterator/menu.py | 2,826 | 3.6875 | 4 | from abc import ABCMeta, abstractmethod
from pythonDesignPatterns.src.composite.menuiterator.iterator import NullIterator, CompositeIterator, Iterator
class MenuComponent(metaclass=ABCMeta):
"""
A class which allowes to contain another instances of the same class
"""
def add(self, menuComponent):
"""
Adds a menuComponent instance to this menuComponent
:param menuComponent: the menuComponent instance to add
:return: not implemented, must be overriden, should be None or a boolean
"""
return NotImplemented
def remove(self, menuComponent):
"""
:param menuComponent: the menuComponent instance to remove
:return: not implemented, must be overriden, it should return the removed element
"""
return NotImplemented
def getChild(self, i):
"""
Retrieves the i-th menuComponent contained within this class
:param i: the index where the retrieved element is
:return: the i-th child element
"""
return NotImplemented
@abstractmethod
def createIterator(self):
pass
def print(self):
return NotImplemented
class Menu(MenuComponent):
"""
A concrete instantiation of MenuComponent, which can hold other MenuComponent instances
as instance of Menu itself and MenuItem
"""
def __init__(self, name, description):
super().__init__()
self.name = name
self.description = description
self.menuComponents = []
def add(self, menuComponent):
self.menuComponents.append(menuComponent)
def remove(self, menuComponent):
self.menuComponents.remove(menuComponent)
def getChild(self, i):
return self.menuComponents[i]
def createIterator(self):
return CompositeIterator(Iterator.createIterator(self.menuComponents))
def print(self):
print("\n{}".format(self.name),)
print(", {}".format(self.description))
print("---------------------")
iterator = Iterator.createIterator(self.menuComponents)
while iterator.hasNext():
menuComponent = iterator.getNext()
menuComponent.print()
class MenuItem(MenuComponent):
def __init__(self, name, description, vegetarian, price) -> None:
super().__init__()
self.name = name
self.description = description
self.vegetarian = vegetarian
self.price = price
def createIterator(self):
return NullIterator()
def print(self):
print(" {}".format(self.name),)
if self.vegetarian:
print("(v)",)
print(", {}".format(self.price))
print(" -- {}".format(self.description))
#vv MenuItemCompositeV2Main
#^^ MenuItemCompositeV2Main
#^^ MenuItemCompositeV2
|
43d7e9182242b6040a77407126643db1fa963edb | klich1984/holberton-system_engineering-devops | /0x16-api_advanced/2-recurse.py | 1,138 | 3.65625 | 4 | #!/usr/bin/python3
"""
Write a recursive function that queries the Reddit API and returns a list
containing the titles of all hot articles for a given subreddit. If no results
are found for the given subreddit, the function should return None.
"""
from requests import get
def recurse(subreddit, hot_list=[], after=None):
"""function that queries the Reddit API"""
res = get("https://www.reddit.com/r/{}/hot.json".format(subreddit),
headers={"User-Agent": "Klich from Holberton"},
allow_redirects=False,
params={"after": after, "limit": 10})
# print(res, hot_list, after)
if res.status_code == 200:
search = res.json().get('data').get('children')
# print(hot)
if search:
hot_list += search
after = res.json().get('data').get('after')
# print("hot_list =", hot_list)
# print("*"*100)
# print("after =", after)
if after is None:
return hot_list
return recurse(subreddit, hot_list, after)
else:
return None
else:
return None
|
6fd446499ca33c7865ef1c6b292c5b224708b1eb | Hasib404/Python-problems | /palindrome.py | 917 | 4.3125 | 4 | """
#PROBLEM
A palindrome is a word that reads the same backward or forward.
Write a function that checks if a given word is a palindrome. Character case should be ignored.
def is_palindrome(word)
For example, isPalindrome("Deleveled") should return true as character case should be ignored, resulting in "deleveled", which is a palindrome since it reads the same backward and forward.
#INPUT
Deleveled
adam
"""
#ANSWER
# function which return reverse of a string
def reverse(s):
return s[::-1]
def isPalindrome(s):
# Calling reverse function
rev = reverse(s)
# Checking if both string are equal or not
if (s == rev):
return True
return False
# Driver code
s = "Deleveled".lower()
ans = isPalindrome(s)
if ans == 1:
print("Yes")
else:
print("No")
s = "adam"
ans = isPalindrome(s)
if ans == 1:
print("Yes")
else:
print("No")
|
5d6d7106c67e09ab44afd18cb8bf0ac548e8b1f8 | Pythonyte/Algorithms | /binray_tree_mirror_image.py | 549 | 4.03125 | 4 | '''
Mirror(Tree)
(1) Call Mirror for left-subtree i.e., Mirror(left-subtree)
(2) Call Mirror for right-subtree i.e., Mirror(right-subtree)
(3) Swap left and right subtrees.
temp = left-subtree
left-subtree = right-subtree
right-subtree = temp
'''
def mirror_Tree(self,root):
if root.left:
self.mirror_Tree(root.left)
if root.right:
self.mirror_Tree(root.right)
if root.left or root.right:
temp=root.left
root.left=root.right
root.right=temp
return root
|
944545e661dd563e223f9415ee23817b146cc222 | davemccann4130/UCDPA_davidmccann | /numpy_happy_life_expect.py | 1,623 | 3.546875 | 4 | import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
# https://www.kaggle.com/unsdsn/world-happiness
happydata = pd.read_csv('world-happiness-report-2021.csv')
#print(happydata.columns)
# Set variables to hold data to join into 2d numpy array
np_happyscore = happydata['Ladder score']
np_lifeexpect = happydata['Healthy life expectancy']
# Join the two sets of data into a numpy array
happyarray = np.column_stack([np_happyscore, np_lifeexpect])
#print(happyarray.shape)
#print(happyarray.ndim)
#print(happyarray[:,0])
print("The average happiness score in the 149 countries included was",np.mean(happyarray[:,0]))
print("The average life expectancy in the 149 countries included was",np.mean(happyarray[:,1]))
print("The median happiness score in the 149 countries included was",np.median(happyarray[:,0]))
print("The median life expectancy in the 149 countries included was",np.median(happyarray[:,1]))
print("The std.dev in happiness score in the 149 countries included was",np.std(happyarray[:,0]))
print("The std.dev in life expectancy in the 149 countries included was",np.std(happyarray[:,1]))
print("Pearson Correlation Coefficient between Happiness and Life Expectancy is", np.corrcoef(happyarray[:,0],happyarray[:,1]))
matplotlib.style.use('ggplot')
x= happyarray[:,0]
y= happyarray[:,1]
plt.scatter(x, y)
plt.xticks(fontsize=8)
plt.xlabel('Happy Score', fontsize=10)
plt.ylabel('Life Expectancy', fontsize=10)
plt.xticks(rotation=40)
plt.title('Correlation between Happiness and Life Expectancy')
plt.show()
|
b7f91697352f0f4fa12e6dbf9ef7525d9a6a4553 | grk44/host_scripting | /Python/chapter4_project_flips.py | 762 | 3.5 | 4 | import random
numberOfStreaks = 0
for experimentNumber in range(10000):
flips = []
#creates array/list of 100 flips, 0 or 1
for x in range(100):
rnum = random.randint(0,1)
flips.append(rnum)
#sets counts of streak to 0
headcount = 0
tailcount = 0
#iterates through the array/list of 0 and 1
for y in flips:
ht = flips[y]
#if the flip is "heads" 1
if ht == 1:
headcount = headcount+1
if headcount == 6:
numberOfStreaks = numberOfStreaks + 1
headcount = 0
tailcount = 0
elif ht == 0:
tailcount = tailcount+1
if tailcount == 6:
numberOfStreaks = numberOfStreaks + 1
tailcount = 0
headcount = 0
print('Chance of streak: %s%%' % (numberOfStreaks / 100))
|
0131cab8dc79656f0d3f0ec383755c26e4143306 | nuga99/daily-coding-problem | /Problem 15/solve.py | 1,259 | 4.125 | 4 | #!/usr/bin/python
'''
Good morning! Here's your coding interview problem for today.
This problem was asked by Facebook.
Given a stream of elements too large to store in memory,
pick a random element from the stream with uniform probability.
Upgrade to premium and get in-depth solutions to every problem.
Since you were referred by one of our affiliates, you'll get a 10% discount on checkout!
If you liked this problem, feel free to forward it along so they can subscribe here!
As always, shoot us an email if there's anything we can help with!
'''
import random
# using uniform probability
# Credits : https://www.dailycodingproblem.com/blog/how-to-pick-a-random-element-from-an-infinite-stream/
def solve(streamElements):
random_element = None
line = 0
# enumerate each line so with number
for strings in streamElements:
line+=1
if line == 0 :
random_element = strings
elif random.randint(1, line+1) == 1:
random_element = strings
return random_element
if __name__ == "__main__":
# some stream data like file.txt or using terminal input
streamInput = open('file.txt','r')
try:
#solver
print(solve(streamInput))
except:
"No stream data"
|
195b4955345859075d9a736281f5399680a37557 | mikolajf/sailing-tdd | /sailboat.py | 655 | 3.609375 | 4 | from utils import sides
class Sailboat(object):
def __init__(self, initial_heading):
self._heading = initial_heading
def get_heading(self):
return self._heading
def change_course(self, course_diff):
self._heading = (self._heading + course_diff) % 360.0
def set_sail(self, sea):
self.sea = sea
def get_wind_direction(self):
try:
return self.sea.wind_direction
except:
raise ValueError("Boat has not been launched.")
def get_tack(self):
return sides[int((self._heading - self.get_wind_direction()) // 180.0)] |
13798e11dfe409bdda7f6018e106c1ca4031400b | imji0319/checkio | /Checkio/scientific_expedition/common_word.py | 570 | 3.734375 | 4 | '''
Created on 2018. 1. 21.
@author: jihye
'''
def checkio(first, second):
first=first.split(',')
second=second.split(',')
common=[]
for i in range(len(first)):
for j in range(len(second)):
if first[i]==second[j]:
common.append(second[j])
common=sorted(common) # sorted : 원소 정렬
common=",".join(common) # join : 리스트 원소 -> 문자열로 결합
print( common )
checkio("hello,world", "hello,earth")
checkio("one,two,three", "four,five,one,two,six,three")
|
c3a978dd68c9b31ad35cbaf1b488ded089be48cc | cedwardsmedia/compare | /compare.py | 1,210 | 3.625 | 4 | #!/usr/bin/python3
import sys
import hashlib
try:
file1 = sys.argv[1]
file2 = sys.argv[2]
except:
print("I need two files you idiot!")
exit()
try:
open(file1, 'r')
except FileNotFoundError:
print("Cannot open " + file1)
exit()
try:
open(file2, 'r')
except FileNotFoundError:
print("Cannot open " + file2)
exit()
print("Comparing...")
try:
hasher1 = hashlib.sha256()
with open(file1, 'rb') as filea:
buf1 = filea.read()
hasher1.update(buf1)
buf1 = None
filea.close()
file1hash = (hasher1.hexdigest())
except:
print("An error occured with the first file.")
exit()
try:
hasher2 = hashlib.sha256()
with open(file2, 'rb') as fileb:
buf2 = fileb.read()
hasher2.update(buf2)
buf2 = None
fileb.close()
file2hash = (hasher2.hexdigest())
except:
print("An error occured with the second file.")
exit()
if (file1hash == file2hash):
print("🗹 Files match.\n")
print(file1 + ": " + file1hash)
print(file2 + ": " + file2hash)
else:
print("🗷 Files do not match.\n")
print(file1 + ": " + file1hash)
print(file2 + ": " + file2hash)
exit()
|
1b97becd5535df33e0232d4e1eb3892b6f03ed9f | liucheng2912/py | /leecode/study/树的非递归先序遍历.py | 648 | 3.859375 | 4 | #使用栈来实现
#若是右子节点存在,入栈
#若是左子节点存在,入栈
#最后出栈
def preorder(node):
stack=[node]
while len(stack)>0:
print(node.val)
if node.right is not None:
stack.append(node.right)
if node.left is not None:
stack.append(node.left)
stack.pop()
def midorder(node):
stack=[]
pos=node
while pos is not None or len(stack)>0:
if pos is not None:
stack.append(pos)
pos=pos.left
else:
pos=stack.pop()
print(pos.val)
pos=pos.right
|
d36fba4bdff5dc3778c1210d843fa564e614bcfd | wikipycoder/ds-algo-in-py | /maze_runner.py | 1,239 | 3.984375 | 4 | #this script is a simple version of maze runner in python
maze = [[1, 0, 0, 0], [1, 1, 0, 1], [0, 1, 0, 0], [0, 1, 0, 0 ],
[1, 1, 1, 0], [0, 0, 1, 0], [1, 0, 1, 1], [0, 0, 1, "End"]
]
maze_runner = "*" #maze runner character
def display_maze():
for d1 in maze:
for row in d1:
print(row, end=" ")
print("\n")
def did_maze_runner_win(row, col):
if (row == len(maze)-1 and col == len(maze[row])-1) and maze[row][col] == "*":
return True
def backtracking():
row = 0
col = 0
while True:
try:
if maze[row][col+1]:
maze[row][col+1] = maze_runner
col += 1
except IndexError:
pass
try:
if maze[row+1][col]:
maze[row+1][col] = maze_runner
row += 1
except IndexError:
pass
display_maze()
if did_maze_runner_win(row, col):
print("maze_runner won")
break
def main():
display_maze()
print("\n\n")
backtracking()
if __name__ == "__main__":
main() |
09592e3943bb7f52d0dd2db30a1d88b3b6dfc8fe | yujin0719/Problem-Solving | /프로그래머스/2019 KAKAO BLIND RECRUITMENT/오픈채팅방.py | 511 | 3.609375 | 4 | # 오픈채팅방
from collections import defaultdict
def solution(record):
answer = []
dict = defaultdict(list)
for r in record:
r = r.split(" ")
if r[0] != 'Leave':
dict[r[1]] = r[2]
for r in record:
r = r.split(" ")
if r[0] == 'Change':
continue
if r[0] == 'Enter':
answer.append(dict[r[1]]+'님이 들어왔습니다.')
else:
answer.append(dict[r[1]]+'님이 나갔습니다.')
return answer |
8411166d3b4014fc9e41599512aa1b964e53cc0b | Vitalius1/Python_OOP_Assignments | /Hospital/register.py | 1,148 | 3.734375 | 4 | from hospital import Hospital
from patient import Patient
# creating 6 instances of Patient class
p1 = Patient("Vitalie", "No allergies")
p2 = Patient("Diana", "No allergies")
p3 = Patient("Galina", "Yes")
p4 = Patient("Nicolae", "Yes")
p5 = Patient("Ion", "No allergies")
p6 = Patient("Olivia", "Yes")
# Create the hospital giving it a name and a capacity
hospital1 = Hospital("Braga", 5)
# Admiting the patients into the hospital
hospital1.admit(p1)
hospital1.admit(p2)
hospital1.admit(p3)
hospital1.admit(p4)
hospital1.admit(p5)
hospital1.admit(p6) # this patient will receive a message that hospital is full (capacity = 5) and will not be admited to it.
print
# Discharge a patient by his name and setting it's bed attribute to None, but he still keeps his ID in case he returns.
hospital1.discharge("Galina")
print # When the patient is discharged he gives the bed back to be reused by new patients.
hospital1.discharge("Nicolae")
print
hospital1.admit(p3) # Testing the admition of 2 previous patients in case they come back they still have the same ID
hospital1.admit(p4) # but reusing beds left by other users |
81d3794dc323a6b7047135e301a2b1194b4b9470 | EgorZamotaev/PythonLabs | /Lab1/4.py | 106 | 3.671875 | 4 | N=int(input("Введите N "))
C=12
D=100
P=(N/C*1/3)**D
print('Вероятность равна: ',P) |
35f86cb70aad5a8b2af72b819feea93688e112f9 | MattB17/googleMemoryAutoScaling | /MemoryAutoScaling/Models/Sequential/TraceExponentialSmoothing.py | 4,849 | 3.71875 | 4 | """The `TraceExponentialSmoothing` class is used to construct a predictive
model based on exponential smoothing. For exponential smoothing, the
prediction at time `t` is `p_t = alpha * x_t-1 + (1 - alpha) * p_t-1` where
`alpha` is a configurable weight constant between 0 and 1, `x_t-1` is the
actual data observation at time `t-1` and `p_t` and `p_t-1` are the
predictions at times `t` and `t-1` respectively.
"""
import numpy as np
import matplotlib.pyplot as plt
from MemoryAutoScaling.Models.Sequential import SequentialModel
class TraceExponentialSmoothing(SequentialModel):
"""Builds an Exponential Smoothing model for a data trace.
Parameters
----------
alpha: float
The alpha value for the model. It is a number between 0 and 1
representing the weight of new observations versus past predictions.
initial_pred: float
A float representing the initial prediction. This is used as the
prediction for a new trace before seeing any data for that trace.
train_prop: float
A float in the range [0, 1], representing the proportion of data
in the training set. The default is 0.6.
val_prop: float
A float in the range [0, 1] representing the proportion of data in
the validation set. The default value is 0.2.
max_mem: bool
A boolean indicating if the target value is maximum memory. The
default value is True, indicating that maximum memory usage is
the target variable. Otherwise, maximum CPU usage is used.
Attributes
----------
_alpha: float
The alpha value for the model.
_initial_pred: float
The initial prediction for a new, unseen trace.
_train_prop: float
The proportion of data in the training set.
_val_prop: float
The proportion of data in the validation set.
_max_mem: bool
A boolean indicating the target variable. True indicates that maximum
memory usage is the target variable. Otherwise, maximum CPU usage is
used as the target.
"""
def __init__(self, alpha, initial_pred, train_prop=0.6,
val_prop=0.2, max_mem=True):
self._alpha = alpha
super().__init__(initial_pred, train_prop, val_prop, max_mem)
def get_params(self):
"""The parameters of the model.
The model parameters are the initial prediction and the alpha value.
Returns
-------
tuple
A two element tuple containing the parameters of the model,
corresponding to the initial prediction and the alpha value.
"""
return {'alpha': self._alpha, 'initial_pred': self._initial_pred}
def get_model_title(self):
"""A title describing the model.
Returns
-------
str
A string representing the title for the model.
"""
return "{}-ExponentialSmoothing".format(self._alpha)
def get_next_prediction(self, past_obs, past_pred):
"""Calculates the current exponential smoothing model prediction.
Parameters
----------
past_obs: float
A float representing the past observation.
past_pred: float
A float representing the past prediction.
Returns
-------
float
A float representing the current exponential smoothing model
prediction.
"""
return (self._alpha * past_obs) + ((1 - self._alpha) * past_pred)
def _get_predictions(self, trace_ts, tuning=True):
"""Calculates all predictions for `trace_ts`.
For each time point in `trace_ts` the exponential smoothing
prediction is calculated. The first prediction is `_initial_pred` and
the second prediction is the first observation as no past data exists.
All subsequent predictions are based on the exponential smoothing
formula.
Parameters
----------
trace_ts: np.array
A numpy array representing the data trace for which the
exponential smoothing predictions are calculated.
tuning: bool
A boolean value indicating whether the predictions are for the
validation set or the test set.
Returns
-------
np.array, np.array
Two numpy arrays that represent the predictions for `trace_ts`
on the training and testing sets, respectively.
"""
time_points = len(trace_ts)
preds = np.array([self._initial_pred for _ in range(time_points)])
if time_points >= 2:
preds[1] = trace_ts[0]
for idx in range(2, time_points):
preds[idx] = self.get_next_prediction(
trace_ts[idx - 1], preds[idx - 1])
return self.split_data(preds, tuning)
|
6d501e12d7d8c7ce59a5d52fea2b3f1de0a848c7 | melany202/programaci-n-2020 | /talleres/tallerquiz2.py | 2,769 | 3.625 | 4 | #ENTRADAS
Temperatura_Corporal = [36,37,38,35,36,38,37.5,38.2,41,37.4,38.6,39.1,40.3,33]
#Preguntas
preguntaMenu = '''
Por favor igrese alguna de estas opciones
1-Convertir temperaturas
2-Estado de salud de c/u de las temperaturas
3-Ver maximo y minimo de temperaturas
4-Para salir del programa
: '''
preguntaConversionTemperatura = '''
F-Convertir temperaturas Fahrenheit
K-Covertir temperaturas kelvin
C-Convertir temperaturas Celsius
: '''
#---Mensaje Error---#
mensajeEntradaNoValidaN ='Recuerde ingresar una opcion valida 1,2,3,4'
mensajeEntradaNoValidaT ='Recuerde ingresar una opcion valida F,K,C'
#---Mensajes Informativos---#
mensajeOpcion = 'Usted escogio la opcion {}'
mensajeSalida ='Gracias por usar el programa'
mensajeCelsius ='No es necesario la conversión, pero se muestra la lista'
mensajeMaxima ='La temperatura maxima es'
mensajeMinima ='La temperatura minima fue'
mensajefrecuencia ='La temperatura fue tomada con una frecuencia de'
#Inicio codigo
opcion =int(input(preguntaMenu))
#Calculos preliminares
listaGradosKelvin =[]
listaGradosFa=[]
listaGradosC =Temperatura_Corporal
ListaEstadosSalud =[]
#---Pasando a kelvin xC + 273.15---#
for elemento in listaGradosC:
kelvin = elemento + 273.15
listaGradosKelvin.append(kelvin)
#---Pasando a Fa=(xC*1.8)+32 ---#
for elemento in listaGradosC:
Fahrenheit = (elemento*1.8)+32
listaGradosFa.append(Fahrenheit)
#---detectando los estados de salud---#
for elemento in listaGradosC:
estado =''
if (elemento < 36):
estado= 'Hipotermia'
elif(elemento >= 36 and elemento <37.6 ):
estado ='Normal'
else:
estado ='Fiebre'
ListaEstadosSalud.append(estado)
#---Calcular maximo & minimo---#
mayor = max (listaGradosC)
menor =min (listaGradosC)
frecuencia =len(listaGradosC)/24
#Menu
while (opcion != 4) :
if (opcion == 1):
print(mensajeOpcion.format(1))
#pregunta conversion
conversion =input(preguntaConversionTemperatura)
if(conversion =='K'):
print(listaGradosKelvin)
elif (conversion =='F'):
print(listaGradosFa)
elif(conversion =='C'):
print(listaGradosC)
else :
print(mensajeEntradaNoValidaT)
elif(opcion ==2):
print(mensajeOpcion.format(2))
print(ListaEstadosSalud)
elif(opcion ==3):
print(mensajeOpcion.format(3))
print(mensajeMaxima,mayor)
print(mensajeMinima,menor)
print(mensajefrecuencia,frecuencia)
else:
print(mensajeEntradaNoValidaN)
#Entrada de la variable de opcion
opcion =int(input(preguntaMenu))
#Salida del programa
print(mensajeSalida)
|
c9cb4c5b9a35df7b5a72fec175bd0ac61324ebc0 | malaika-chandler/triple-triad-python | /agents.py | 7,074 | 3.65625 | 4 | from textdisplay import TripleTriadColors
from abc import ABCMeta, abstractmethod
class Agent:
"""Base class for implementing a game player
Attributes:
index (int): The index of the player
Methods:
initialize: Prepares agent for a new game
get_action: Throws NotImplemented error; should be implemented by subclass
increment_score: Increments player score by 1
decrement_score: Decrements player score by 1
place_card_in_hand: Places a given card in the player's hand
set_hand: Deals a full hand of cards to the player
play_card: Removes a card from the player's hand
"""
__metaclass__ = ABCMeta
def __init__(self, index):
self._hand = []
self._index = index
self._name = "Player {}".format(index + 1)
self._score = 0
def __deepcopy__(self, memo_dict={}):
copy_agent = Agent(self._index)
copy_agent._hand = list(self._hand)
copy_agent._name = self._name
copy_agent._score = self._score
return copy_agent
def initialize(self):
self._hand = []
self._score = 0
@abstractmethod
def get_action(self, game_state):
raise NotImplemented("Method needs to be implemented in sub class")
@property
def name(self):
return self._name
@property
def score(self):
return self._score
@property
def index(self):
return self._index
@property
def hand(self):
return self._hand
def increment_score(self):
self._score += 1
def decrement_score(self):
self._score -= 1
def place_card_in_hand(self, card):
self._hand.append(card)
def set_hand(self, dealt_cards):
self._hand.clear()
self._hand.extend(dealt_cards)
self._score = len(dealt_cards)
def play_card(self, selected_card):
if selected_card in self._hand:
# Remove card from hand and return
self._hand.remove(selected_card)
return selected_card
# Card not in player's hand
return None
def __eq__(self, other):
return self.score == other.score
def __ge__(self, other):
return self.score >= other.score
def __le__(self, other):
return self.score <= other.score
def __lt__(self, other):
return self.score < other.score
def __gt__(self, other):
return self.score > other.score
def __ne__(self, other):
return self.score != other.score
class FirstAvailableAgent(Agent):
def __init__(self, index):
super().__init__(index)
"""For Testing: Uses first available card in first available space"""
def get_action(self, game_state):
legal_cards, legal_grid_spaces = game_state.get_legal_agent_actions(self)
return 0, list(legal_grid_spaces.values())[0].get_coordinates()
class MinMaxAgent(Agent):
def __init__(self, index):
super().__init__(index)
def __deepcopy__(self, memo_dict={}):
new_agent = MinMaxAgent(self._index)
new_agent._index = self._index
new_agent._hand = list(self._hand)
new_agent._name = self.name
new_agent._score = self.score
return new_agent
def get_action(self, game_state):
legal_cards, legal_grid_spaces = game_state.get_legal_agent_actions(self)
max_action = 0, list(legal_grid_spaces.values())[0].get_coordinates()
value = float('-inf')
depth = 9 % game_state.get_count_turns_remaining()
print("Thinking...")
# Go through each available card
for card_index in range(len(legal_cards)):
# Go through each available space on the board
for coordinates, grid_space in legal_grid_spaces.items():
# Generate possible game state successor
result = self.dive_down(
game_state.generate_successor(self._index, (card_index, coordinates)),
depth
)
if value < result:
value = result
max_action = card_index, coordinates
return max_action
def dive_down(self, game_state, depth):
game_state.increment_player_turn()
current_agent = game_state.get_current_player()
agents = game_state.get_agents()
other_player_index = (self._index + 1) % len(agents)
current_result = 100 * (agents[self._index].score - agents[other_player_index].score)
if depth == 0:
return current_result
legal_cards, legal_grid_spaces = game_state.get_legal_agent_actions(current_agent)
if current_agent.index == self._index:
# Maximize own interests
value = float('-inf')
for card_index in range(len(legal_cards)):
# Go through each available space on the board
for coordinates, grid_space in legal_grid_spaces.items():
result = self.dive_down(
game_state.generate_successor(self._index, (card_index, coordinates)),
depth - 1
)
value = max(value, result + current_result)
return value
else:
# Minimize opponent interests
# TODO Can only check cards if open rule is in play
value = float('-inf')
for card_index in range(len(legal_cards)):
# Go through each available space on the board
for coordinates, grid_space in legal_grid_spaces.items():
result = self.dive_down(
game_state.generate_successor(self._index, (card_index, coordinates)),
depth - 1
)
value = max(value, result + current_result)
return value
class KeyBoardAgent(Agent):
def __init__(self, index):
super().__init__(index)
self.self_color = TripleTriadColors.AGENT_COLORS[index]
def __deepcopy__(self, memo_dict={}):
new_agent = KeyBoardAgent(self._index)
new_agent._index = self._index
new_agent._hand = list(self._hand)
new_agent._name = self._name
new_agent._score = self._score
return new_agent
def get_action(self, game_state):
# Get legal cards/spaces
legal_cards, legal_grid_spaces = game_state.get_legal_agent_actions(self)
# Get player move
card_index, coordinates = -1, None
while not (0 <= card_index < len(legal_cards) and coordinates in legal_grid_spaces):
player_input = input("{}'s turn: ".format(
self.self_color + self._name + TripleTriadColors.COLOR_RESET))
result = player_input.split(' ')
card_index, coordinates = int(result[0]) - 1, (int(result[1]), int(result[2]))
return card_index, coordinates
class MouseAgent(Agent):
def get_action(self, game_state):
pass
pass
|
5b07a1e623816033a157a27316d095177154ee4e | Ahmedrajiv/hello-world | /defcalculatorS9.py | 331 | 3.921875 | 4 | #def function
def add (a,b):
return (a+b)
def sub (a,b):
return (a-b)
def mul (a,b):
return (a*b)
def div (a,b):
return (a/b)
x= int(input("Enter X value"))
y= int(input("Enter Y value"))
print (add(x,y), "Addition")
print (sub(x,y),"Subtraction")
print (mul(x,y),"Multiplication")
print (div(x,y),"Divsion")
|
b464a61efab059d53cd9e0e5a5028cd4a653c23b | kelr/practice-stuff | /leetcode/83-removeduplicatessorted.py | 988 | 3.921875 | 4 | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# Use two pointers, if fast is the same as slow, increment fast until it no longer is.
# Then set the next node on slow to the different value on fast, which skips duplicate values.
# O(N) time, fast iterates N times
# O(1) space, no extra space is used
def deleteDuplicates(head: ListNode) -> ListNode:
if not head or not head.next:
return head
slow = head
fast = head.next
while fast:
if fast.val == slow.val:
fast = fast.next
else:
slow.next = fast
slow = slow.next
fast = fast.next
# If there were duplicates at the end of the list, fast would be None, so manually set slow.next once more
slow.next = fast
return head
test = ListNode(1, ListNode(1, ListNode(2, ListNode(3, ListNode(3)))))
res = deleteDuplicates(test)
while res:
print(res.val)
res = res.next
|
49f2d9674b356ec1fa8e1b9d6cdeabdc93804163 | GohJC/DPL5211Tri2110 | /Lab 2 Q3.py | 254 | 4.125 | 4 | #student ID: 1201201564
#student Name: Goh Jia Chen
FT = -17.2222
celcius = float(input("Please enter your Celcius temperature : "))
fahrenheit = FT * celcius
print("For {:.2f} Celcius is equivalent to {:.2f} Fahrenheit".format(celcius, fahrenheit)) |
a2d78e2e6b4c3c000c0ccf91a45742e570cca30c | jieye-ericx/learn-python | /22/my/04.py | 901 | 3.53125 | 4 | import tensorflow as tf
# 线性回归
def myregression():
x = tf.random_normal([100, 1], mean=1.75, stddev=0.5, name="x_data")
y_true = tf.matmul(x, [[0.7]]) + 0.8
weight = tf.Variable(tf.random_normal([1, 1], mean=0.0, stddev=1.0, name="w"))
bias = tf.Variable(0.0, name="b")
y_predict = tf.matmul(x, weight) + bias
loss = tf.reduce_mean(tf.square(y_true - y_predict))
train_op = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init_op)
print("随即初始化参数权重:%f,偏置:%f" % (weight.eval(), bias.eval()))
for i in range(100):
sess.run(train_op)
print("第%d次优化参数权重为:%f,偏置为:%f" % (i, weight.eval(), bias.eval()))
return None
if __name__ == "__main__":
myregression()
|
0aa27946dbe9f13346f86c95408c03d40650a319 | nyghtowl/HB_Wk4_LAMP | /model.py | 3,261 | 3.578125 | 4 | """
model.py
"""
import sqlite3
import datetime
def connect_db():
return sqlite3.connect("tipsy.db")
def new_user(db, email, password, fname, lname):
c = db.cursor()
query = """INSERT INTO Users VALUES (NULL, ?, ?, ?, ?)"""
result = c.execute(query, (email, password, fname, lname))
if result:
db.commit()
return result.lastrowid
def make_user(row):
fields = ["id", "email", "password", "first_name", "last_name"]
return dict(zip(fields, row))
def authenticate(db, email, password):
#open a connection to the database and assign to variable c
c = db.cursor()
#sets the query to run by pulling all information based on email and password
query = """SELECT * from Users where email = ? and password = ?"""
#executes the query on the database with the passed parameters
c.execute(query, (email, password))
# should only assign one result from the database query to result var
result = c.fetchone()
# If result exists, create a dictionary
if result:
return make_user(result)
#Else return none
return None
def new_task(db, title, user_id):
c = db.cursor()
#Insert new task into db
query = """INSERT INTO Tasks VALUES (NULL, ?, DATETIME('now'), NULL, NULL, ?)"""
#run query
result = c.execute(query, (title, user_id))
#commit query
db.commit()
#return task
return result.lastrowid
def get_user(db, id):
#Fetch a user's record based on his id. Return a user as a dictionary, like authenticate method
c = db.cursor()
query = """SELECT * from Users where id = ?"""
c.execute(query, (id,))
result = c.fetchone()
if result:
return make_user(result)
return None
def complete_task(db, task_id):
# find task id
c = db.cursor()
now = datetime.datetime.now()
query = """UPDATE Tasks
SET completed_at = ?
WHERE id = ?"""
c.execute(query, (now, task_id))
result = c.fetchone()
db.commit()
def get_tasks(db, user_id=None):
# gets all the tasks for the given user id.
c = db.cursor()
tasks_list = []
#check if user id is NONE
if user_id == None:
#query all tasks
query = """SELECT * from Tasks"""
c.execute(query,)
#if there is a user id, run query for that user
else:
query = """SELECT * from Tasks where user_id = ?"""
c.execute(query,(user_id,))
results = c.fetchall()
#loop through results and create a dictionary of the results
for result in results:
holder_dict = {}
holder_dict['id'] = result[0]
holder_dict['title'] = result[1]
holder_dict['create_at'] =result[2]
holder_dict['due_date'] =result[3]
holder_dict['completed_at'] =result[4]
holder_dict['user_id'] =result[5]
tasks_list.append(holder_dict)
return tasks_list
def get_task(db, task_id):
c = db.cursor()
query = """SELECT * FROM Tasks WHERE id = ?"""
c.execute(query, (task_id,))
result = c.fetchone()
if result:
fields = ["id", "title", "created_at", "due_date", "completed_at", "user_id"]
return dict(zip(fields, result))
#Else return none
return None
# def get_taske(db, task_id):
# CREATE TABLE Users (
# id INTEGER PRIMARY KEY,
# email varchar(64),
# password varchar(64),
# fname varchar(64),
# lname varchar(64)
# );
# CREATE TABLE Tasks (
# id INTEGER PRIMARY KEY,
# title varchar(128),
# created_at DATETIME,
# due_date DATETIME,
# completed_at DATETIME,
# user_id INT
# );
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.