blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
f3e15424cbabfa65909bb5ecd9be58598d976790
|
matheus-frota/GameRecommendationSystem
|
/gameRecommender/main.py
| 237 | 3.5 | 4 |
from knn import recommender, personalization
def main():
k = int(input("How many games do you want to know? "))
gameName = input("Enter the name of your favorite game: ")
personalization()
recommender(k,gameName)
main()
|
5d6c1a0fddce4304784f333e96e685069a49ad69
|
hollandm/cs441-majestic-eagle
|
/CEEBData/ceebScraper.py
| 2,318 | 3.9375 | 4 |
#
# Description: This python file scrapes CEEB code data from the
# website "sat.collegeboard.org
#
# Input: None.
#
# Output: A .csv file containing every high school's name and CEEB
# number as reported by the SAT Collegeboard.
#
# Based on the data scraping tutorial provided in the book "Visualize
# This" by Nathan Yau.
#
# Requires: Beautiful Soup Python Library.
#
#
import urllib2, re
from bs4 import BeautifulSoup
# Open a file to write .csv data
f = open("ceebcodes.csv", "w");
# Write the headers for the .csv data
f.write("High School Name, Code, State \n");
states = ["AL","AK","AZ","AR","CA","CO","CT","DE","FL","GA","HI","ID","IL","IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MS","MO","MT","NE","NV","NH","NJ","NM","NY","NC","ND","OH","OK","OR","PA","RI","SC","SD","TN","TX","UT","VT","VA","WA","WV","WI","WY"];
urls = []
# Create an array of URLs, one per state
for state in states:
urls.append("http://sat.collegeboard.org/register/sat-code-search-schools?decorator=none&submissionMode=ajax&pageId=registerCodeSearch&codeType=high-school-code&country=US&state="+state);
# Count which iteration of the loop we are in.
j = 0;
# Parse each url and extract a list of high schools.
for page in urls:
# Load the page; This loads all of the HTML that the URL points
# to.
page = urllib2.urlopen(page)
# Use BeautifulSoup to parse the page. The raw HTML is now stored as
# a collection of elements that are much easier to work with.
soup = BeautifulSoup(page)
# Get all of the strong elements; that's where all the school names are.
# Note that the first two strong elements on the page are decorative.
schoolNames = soup.findAll(attrs={"class":"schoolResultCell"});
# Get all of the div elements of the class "top-fs-desc"; that's where
# all the school addresses are.
codes = soup.findAll(attrs={"class":"codeResultCell"})
# Assemble each entry
for i in range(0, len(schoolNames)):
f.write(schoolNames[i].contents[0][:-2] + ",") # The name of the school
f.write(codes[i].contents[0][:-1] + ",") # The code that corresponds to the school
f.write(states[j] ) # The state in which the school resides.
f.write("\n")
j = j + 1;
# Close the file
f.close()
|
d31636b5246aa906e66d8e9a3cca1151102cd73f
|
shennyrs/bash
|
/python/class_objects/constructors.py
| 336 | 3.96875 | 4 |
#constructor is a class function that instantiates an object to predefined values
#defined with a double underscore() it is __init__() method
class user():
name=" "
def __init__(self, name):
self.name=name
def sayhello(self):
print("hello "+self.name)
user1=user("alex")
user1.sayhello()
|
2bff0411f32abb66898beebd7ec43965a1a6b301
|
nazninnahartumpa/python
|
/test2.py
| 747 | 3.921875 | 4 |
# x = "Hello world {}.format('inserted')"
result = 100/777
print('The result is {r:1.3f}'.format(r=result))
print(5+7)
#pring mod
print(15%5)
#printin 2 to the power 3
print(2**3)
#print with new line
print("Hello \n World")
#string indexing
var = "Hello World"
print(var[0])
#print negetive indexing
print(var[-3])
#slicing of the string
print(var[1:])
#slicing of the srting start to index 1 and stop in index 5 and out put is ello
print(var[1:5])
#slice first to next 4 letter
print(var[ :4])
#slice letter from first to 4 step to step
print(var[::4])
#slice start to stop and step
print(var[1:5:2])
#concat variable with the string
print(var+' This is me')
#split the word whene it gets the l letter
var = "Helo World"
print(var.split('l'))
|
0c8113f49b5c8b55319996f2169268cd77a294a6
|
NAMRATHABATHULA/listtupledictionary
|
/listupledict.py
| 786 | 4.25 | 4 |
#1 inputting elements to an empty list
list=[]
n=int(input("enter number of elements of the list"))
for i in range(0,n):
a=int(input("enter the element"))
list.append(a)
list1=list
print(list1)
# addind an element in existing list,let the number be 67
list1.append(67)
print(list1)
# adding more than one element to a list,let the numbers be 34,43
list1.extend([34,43])
print(list1)
#2 accessing elements from a tupple
tuple=("orange","candy","apple","guava","mango","melon")
print(tuple)
# access using index of the element
print(tuple[1])
#access more than one element
print(tuple[1:])
print(tuple[:-1])
print(tuple[2:4])
#deleting different dictionary elements
dictionary={"a":1,"b":2,"c":3,"d":4}
print(dictionary)
del dictionary["b"]
print(dictionary)
|
602387f3423605bfb1e6a3255cc3701144bc5b20
|
ashokpal100/python_written_test
|
/python/number/arm_or_not.py
| 215 | 3.875 | 4 |
num=int(raw_input("enter any no: "))
number = int(num)
orig = number
rev = 0
while number > 0:
rm=number%10
rev=rev+(rm*rm*rm)
number=number/10
print rev
if orig==rev:
print "arm",rev
else:
print "not",rev
|
c595aa711930f30c03fd2561ff6b206d11b87ca2
|
spencerpeters/BackDoorExperiment
|
/src/TakataDSeparator.py
| 1,446 | 3.59375 | 4 |
import networkx
from src.DSeparation import DSeparator
LABEL = 'label'
DETERMINED = 'determined'
DESCENDANT = 'descendant'
START_NODE = "DSeparatorStartNode"
REACHABLE = 'reachable'
__author__ = 'Spencer'
class TakataDSeparator:
# Note! This is for D-separation. So D-separation in the back-door graph gives
@staticmethod
def moralGraph(graph: networkx.DiGraph, X, Y, Z):
moralGraph = graph.copy()
DSeparator.makeDescendants(moralGraph, X.union(Y).union(Z))
for node in moralGraph.nodes():
if not node[DESCENDANT]: # if the node is not an ancestor of any of the nodes in X, Y, Z
moralGraph.remove_node(node)
node[DESCENDANT] = False # clear DESCENDANT markers
DSeparator.makeDescendants(moralGraph, Z)
# not sure if this strategy for moralizing the graph is efficient (I can imagine examples where it is very bad)
# eg, all nodes in set P have edges to all children in set C
# go find an algorithm for moralizing a graph (Koller??)
for node in moralGraph.nodes():
if node[DESCENDANT]: # if the node is an ancestor of a node in Z, or if it is in Z
parents = list(node.parents())
for i in range(len(parents)):
for j in range(i + 1, len(parents)):
graph.add_edge(parents[i], parents[j])
return graph.to_undirected(graph)
|
4db064549cb8ef865478ff942ecddaff29c66a8f
|
r2d2c3po/learntris
|
/imple1
| 1,166 | 3.515625 | 4 |
#!/usr/bin/env python
#Joey Y. Ni
import sys
import pygame
numClear=0
score=0
matrix=[['.' for x in xrange(10)] for e in xrange(22)]
#global game board initialized with .
def main():
pygame.init()
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key==pygame.K_p:
printMatrix() #initialize game
if event.key==pygame.K_q:
sys.exit()
if event.key==pygame.K_g:
reload()
if event.key==pygame.K_c: #clear matrix
matrix=[]
matrix=[['.' for x in xrange(10)] for e in xrange(22)]
printMatrix()
if event.key==pygame.K_s: #display score
print(score)
if event.key==pygame.K_n: #display num lines cleared
print(numClear)
if event.key==pygame.K_SPACE:
#execute one step of the simulation
def reload(): #reload matrix with changes as described by the input in stdin
for line in sys.stdin:
new=line.split()
matrix=[]
printMatrix()
def printMatrix():
for e in matrix: print " ".join(str(x) for x in e)
if __name__== "__main__":
main()
|
2cad4a419625d7ab1802e25546a199c6f1203a95
|
cdr-caique/uri-online-judge
|
/python-3.8/1074.py
| 481 | 3.859375 | 4 |
n = int(input())
message = ""
for i in range(n):
x = int(input())
if(x==0):
message += "NULL\n"
elif(x%2 == 0):
message += "EVEN "
if(x > 0):
message += "POSITIVE\n"
else:
message += "NEGATIVE\n"
else:
message += "ODD "
if(x > 0):
message += "POSITIVE\n"
else:
message += "NEGATIVE\n"
message = message[:-1]
print(message)
|
a26e34a725fcceeceb72891e1fc9c053955a493e
|
suacalis/VeriBilimiPython
|
/Ornek2_1.py
| 245 | 3.8125 | 4 |
'''
Örnek 2.1:
İki sayının toplamını hesaplayan basit matematiksel işlemi yapalım.
'''
A = int (input("1.sayıyı gir:")) #hatalı kullanım: A = input("1.sayıyı gir:")
B = int (input("2.sayıyı gir:"))
T = A + B
print ("Toplam= ", T)
|
303243ad222dcb575390d352f952e7eea2c15fbb
|
rickerje/web-caesar
|
/caesar.py
| 1,182 | 4.0625 | 4 |
import string
def alphabet_position(letter):
alphabet = {'a': 0, 'b': 1, 'c': 2, 'd': 3,
'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8,
'j': 9, 'k': 10, 'l': 11, 'm': 12,
'n': 13, 'o': 14, 'p': 15, 'q': 16,
'r': 17, 's': 18, 't': 19, 'u': 20,
'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
return alphabet.get(letter.lower())
def rotate_character(char, rot):
alphabet = string.ascii_lowercase
if not char.isalpha():
return char
char_value = alphabet_position(char)
char_pos = char_value + rot
if char_pos < 25:
new_char = alphabet[char_pos]
else:
new_char = alphabet[char_pos % 26]
if char.isupper():
return new_char.upper()
else:
return new_char
def encrypt(text, rot):
encrypted_msg = ''
for char in text:
encrypted_msg = encrypted_msg + rotate_character(char, rot)
return encrypted_msg
def main():
message = input("Enter your message to encrypt: ")
rotation = int(input("Enter the character rotation for encrypting: "))
print(encrypt(message, rotation))
if __name__ == "__main__":
main()
|
a10a03597e16bfff920a0d72128630bb9fbd0435
|
gavarito/520_python_fundamentals
|
/fatorial.py
| 204 | 4.1875 | 4 |
#!/usr/bin/python3
def factorial(num):
aux = 1
for x in range(1,num+1):
aux *= x
return aux
# from math import factorial
num = int(input('Digite o número: '))
print(factorial(num))
|
453310fee72d48acd9aa4b119213e95db19b7d5d
|
Badw0lf613/Data-Structure_2
|
/项目代码-1812055-姚施越/P2/Preprocess.py
| 2,337 | 3.546875 | 4 |
#文本预处理,做分词、清洗工作
#首先引入nltk以及re的模块,以便后续使用
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.corpus import stopwords
import re
#python正则表达式
#后续做清洗时会用到
#主要对一些标点符号进行了分割
pattern = r'(\/\w+)|(\d+\-\S+)|(\[)|(\]\S+)|(\])|(\')|(\")|(\.)|(\,)|(\;)|(\!)|(\()|(\))|\$?\d+(\.\d+)?%?| \.\.\.| ([^A-Za-z0-9]\.)+ '
#在这里增加新的语料
mytxt1=open("D:\\Y\\python\\Data_Structure\\dict\\Lincoln1.txt")#打开
sentence_list = mytxt1.readlines(100000)
open("D:\\Y\\python\\Data_Structure\\dict\\Lincoln.txt",'a+').writelines(sentence_list)
#读入准备好的文章(txt文件)
mytxt=open("D:\\Y\\python\\Data_Structure\\dict\\Lincoln.txt")#打开
s=mytxt.read()#读取
mytxt_senttok = sent_tokenize(s)#做分句
#打印利用sent_tokenize做分句后的效果
print("分句:")
print(mytxt_senttok)
#写入新的txt中
open("D:\\Y\\python\\Data_Structure\\dict\\Lincoln(after process).txt",'a+').writelines(mytxt_senttok)
#这里的属性为a+打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
#利用正则表达式删去标点符号
senttok_regexp = re.compile(pattern).sub('',str(mytxt_senttok))#需要转换为字符串
print("分句(正则表达式):")
print(senttok_regexp)
open("D:\\Y\\python\\Data_Structure\\dict\\Lincoln(after regexp).txt",'a+').writelines(senttok_regexp)
#这里使用a+同理
#对此前正则化后的文本做分词
senttok_regexp_wordtok = word_tokenize(senttok_regexp)
print("分词:")
print(senttok_regexp_wordtok)
#设置停止词,做适度清洗
stop_words = set(stopwords.words('english'))
senttok_regexp_wordtok_afterstop = []
for w in senttok_regexp_wordtok:
if w not in stop_words:
#对不在停止词内的词做append操作,以空格分隔
senttok_regexp_wordtok_afterstop.append(w+' ')
print("分词(去除停止词):")
print(senttok_regexp_wordtok_afterstop)
open("D:\\Y\\python\\Data_Structure\\dict\\Lincoln_new.txt",'a+').writelines(senttok_regexp_wordtok_afterstop)
print("文本已被写入D:\\Y\\python\\Data_Structure\\dict\\Lincoln_new.txt")
|
6caddf5e5e599b216c5edfd5a21a5811680b57ca
|
seanlab3/algorithms
|
/algorithms_practice/6.DP/9.DP_longest_increase.py
| 391 | 4.15625 | 4 |
"""
Given an unsorted array of integers, find the length of longest increasing subsequence.
Example:
Input: [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
The time complexity is O(n^2).
"""
from algorithms.dp import longest_increasing_subsequence
a=[10,9,2,5,3,7,101,18]
print(longest_increasing_subsequence(a))
|
c5f2ee7e7ec10a219cf4da141219284a963dea5a
|
Davidnet/Euler-Project-Python
|
/Problem11.py
| 776 | 3.84375 | 4 |
def nthtrianglenum(n):
return (n * (n + 1)) / 2
def numberofdivisors(n):
divisors = 1
count = 0
f = 2
while n % f == 0:
count += 1
n /= f
divisors *= (count + 1)
f = 3
while f <= n:
counter = 0
while n % f == 0:
counter += 1
n /= f
divisors *= (counter + 1)
f += 2
return divisors
def unique_divisors(n):
if n % 2 == 0:
n /= 2
return numberofdivisors(n)
def first_triangle_with_more_than_n_divisor(n):
i = 1
f1 = unique_divisors(n)
f2 = unique_divisors(n + 1)
while f1 * f2 <= n:
f1 = f2
f2 = unique_divisors(i + 2)
i += 1
return i
n = 500
res = first_triangle_with_more_than_n_divisor(n)
print(res)
|
b4e4d1bb0b0fded67373f0662da1ed8a9b9eae82
|
MSuha/Codeforces_Problem_Set
|
/Python/Problem339A_HelpfulMaths.py
| 418 | 3.875 | 4 |
def main():
expression = input()
length = len(expression)
num1 = num2 = num3 = 0
while length > 0:
if expression[length-1] == '1':
num1 += 1
elif expression[length-1] == '2':
num2 += 1
else:
num3 += 1
length -= 2
result = num1 * "1+" + num2 * "2+" + (num3) * "3+"
print(result[:-1])
if __name__ == "__main__":
main()
|
b3b39d33e0a4c52473612d66c29f14fdcd63b553
|
singi2016cn/python-start-programming
|
/7/7.9/vacationland.py
| 286 | 3.625 | 4 |
# 梦想的度假胜地
vacationlands = []
active = True
while active:
vacationland = input('你梦想的度假胜地是哪里?\n')
if vacationland == 'q':
break
vacationlands.append(vacationland)
print('人们梦想的度假胜地有:\n')
print(vacationlands)
|
2b1d5baf4024d283b587d975764592c23c6cc64c
|
NitishPuri/ud120-projects
|
/decision_tree/dt_author_id.py
| 1,472 | 3.75 | 4 |
#!/usr/bin/python
"""
This is the code to accompany the Lesson 3 (decision tree) mini-project.
Use a Decision Tree to identify emails from the Enron corpus by author:
Sara has label 0
Chris has label 1
"""
import sys
from time import time
sys.path.append("../tools/")
from email_preprocess import preprocess
### features_train and features_test are the features for the training
### and testing datasets, respectively
### labels_train and labels_test are the corresponding item labels
features_train, features_test, labels_train, labels_test = preprocess()
outputFile = "output2.txt"
out = open(outputFile, "w")
def logLine(line):
out.write(line)
out.write("\n")
print line
#########################################################
### your code goes here ###
logLine("No of Features = {}".format(len(features_train[0])))
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
clf = DecisionTreeClassifier(min_samples_split=40)
t0 = time()
clf.fit(features_train, labels_train)
t1 = time()
labels_predict = clf.predict(features_test)
t2 = time()
accuracy = accuracy_score(labels_test, labels_predict)
logLine("Training with decision tree default values, min_sample_split = 40")
logLine("Accuracy : {}".format(accuracy))
logLine("Training time : {}".format(t1-t0))
logLine("Prediction time : {}".format(t2-t1))
#########################################################
out.close()
|
c2bb017b404c9dd2f4fb00978b2b23f22d72c5a6
|
ramin153/algebra-university
|
/q4.py
| 2,398 | 3.6875 | 4 |
import sys
from pandas import *
'''
M-> our matrix order to multiplication and vale is theirs size
chain-> our array to save multiplication results
help_chain-> help to track back
n ← M.length − 1
for i ← 1 to n
chain[i, i] ← 0
for size ← 2 to n
; size is length of chain
for i ← 1 to n − size + 1
j ← i + size −1
chain[i, j] ← maxValue
; we put maxValue to sure the value would change
for k ← i to j − 1
min ← chain[i, k] + chain[k+1, j] + M[i-1]*M[k]*M[j]
if min < chain[i, j]
chain[i, j] ← min
help_chain[i, j] ← k
return chain and help_chain
ما دو مارتیس کمکی استفاده می کنیم که به جواب برسیم یکی برای مسیر و یکی برای برای یافتن جواب(یا یک اریه 3 بعدی نیز کار می کند
ما برای محاسبه ضرب اغضای i تا j به روش زیر عمل می کنیم:
ما قبل از به همین روش تمام جواب های که ضبر j تا k و k تا i که k < j و i < k هست را قبل حساب کرده وذخیره کردیم
حال ما مقدار زیر بدست میاریم برای ضرب از عضو i تا جه j قرار می دهیم :
min(chain[i, k] + chain[k+1, j] + M[i-1]*M[k]*M[j])
و همچنین مقدار k حالت منیم بدست میاورد ذخیره می کنیم که بتونیم ترک بک کنیم
این کار ادامه می دهیم که ازز عضو اول تا اخر برسیم.
'''
def chain_matrix(matrix_size:list):
n = len(matrix_size)
help_matrix = [[-1 for i in range(n)] for j in range(n)]
chain = [[0 for i in range(n)] for j in range(n)]
for size in range(2,n):#at lest we need to 2 matrix to do mutltiplicatoin
for i in range(n-size+1):
j = i + size -1
chain[i][j] = sys.maxsize# max value
for k in range( i , j ):
min = chain[i][ k] + chain[k + 1][ j] + matrix_size[i - 1] * matrix_size[k] * matrix_size[j]
if min < chain[i][ j]:
chain[i][ j] = min
help_matrix[i][ j] = k
return (chain,help_matrix)
# 50x40 40x30 30x20 20x10
matrix = [50,40,30,20,10]
chain , help =chain_matrix(matrix)
#print(DataFrame(chain))
print(chain[1][len(matrix)-1])
#ramin rowshan 9732491
|
1cba709c555b7a58394de4e02a3619bb30d5e2fc
|
EricMa206/dsc-object-oriented-shopping-cart-lab-nyc-ds-career-042219
|
/shopping_cart.py
| 756 | 3.53125 | 4 |
class ShoppingCart:
# write your code here
import numpy as np
def __init__(self, total=0, emp_discount=None,
items={'name': [], 'price': []}):
self.total = total
self.employee_discount = emp_discount
self.items = items
def add_item(self, name, price, quantity=1):
self.total += price*quantity
for item in range(quantity):
self.items['name'].append(name)
self.items['price'].append(price)
return self.total
def mean_item_price(self):
return self.items['price'].np.mean()
def median_item_price(self):
return median(self.items['price'])
def apply_discount(self):
pass
def void_last_item(self):
pass
|
15d828e752d90d673260ecc621b7a42660e24ce6
|
Nico34000/API_ong
|
/test_fonction.py
| 2,336 | 3.90625 | 4 |
import unittest
from functions_panda import per_capi, average_year, latest_by_country
class TestMethods(unittest.TestCase):
def test_by_country(self):
"""This function test latest_by_country.
With this function we testing the function
latest_by country.
We test several returns to see if our function
returns the right results. If return is ok the
test return ok
"""
self.assertEqual({'country': 'Albania', 'year': 2017, 'emissions': 4342.011}, latest_by_country('Albania'))
self.assertIsNotNone({2005}, latest_by_country('France'))
self.assertIsNot({1999}, latest_by_country('France'))
self.assertIsInstance(latest_by_country('Belgium'), dict)
def test_average_for_year (self):
"""This function test average_for_year.
With this function we testing the function
average_for_year.
We test several returns to see if our function
returns the right results. If return is ok the
test return ok
"""
self.assertEqual({"total": 217093.22722535214, "year": 2016}, average_year(2016))
self.assertIsNotNone(1985 ,average_year(1985))
self.assertIsNotNone({"year": 1975} ,average_year(1975))
self.assertIsInstance(average_year(1995), dict)
self.assertIsNot({2000}, average_year(1995))
def test_per_capita (self):
""" This function test per_capita.
With this function we testing the function
per_capita.
We test several returns to see if our function
returns the right results. If return is ok the
test return ok
"""
self.assertEqual({1975: 2.562, 1985: 3.191, 1995: 2.058, 2005 : 2.22, 2010: 2.604, 2015: 2.342, 2016: 2.422, 2017: 2.283}, per_capi('Cuba'))
self.assertIsNotNone({2.058}, per_capi('Cuba'))
self.assertIsNotNone({2010}, per_capi('France'))
self.assertIsNot({1999}, per_capi('France'))
self.assertEqual({ 1975: 1.205, 1985: 1.152, 1995: 1.405, 2005: 1.667, 2010: 1.89, 2015: 2.203, 2016: 2.015, 2017: 2.043}, per_capi('Brazil'))
self.assertIsInstance(per_capi('Belgium'), dict)
if __name__ == '__main__':
unittest.main()
|
bcb011e22c3bf4df9e63449955837317e8001496
|
youyuebingchen/Algorithms
|
/paixusuanfa/selectsort.py
| 647 | 3.828125 | 4 |
# def SelectSort(alist):
# n = len(alist)
# for i in range(n-1):
# min = i
# for j in range(n-i):
# if alist[min] > alist[i+j]:
# min = i+j
# alist[i],alist[min] = alist[min],alist[i]
# return alist
# a = [1, 5, 3, 2, 7, 4, 9]
# b = SelectSort(a)
# print(b)
def SelectSort(array):
n = len(array)
for i in range(n):
min = i
for j in range(n-i):
if array[min]> array[i+j]:
min = i+j
array[min],array[i] = array[i],array[min]
return array
if __name__ == '__main__':
a = [1, 5, 3, 2, 7, 4, 9]
print(SelectSort(a))
|
87288e65557091ef27a264a7158554342d3b806e
|
Shari87/Python-Bootcamp
|
/Day-2/Day-2-2/BMI.py
| 273 | 4.28125 | 4 |
height = input("enter your height in m: ")
weight = input("enter your weight in kg: ")
# code below this line
new_height = float(height)
new_weight = int(weight)
# formula to calculate the BMI
BMI = new_weight / (new_height*new_height)
# convert to integer
print(int(BMI))
|
66e9f6540ea0f6d5e3a0f1793ee22cff00cb2de2
|
DOps12/Test_proj
|
/com_ele.py
| 174 | 3.609375 | 4 |
def common_ele(l,n):
e = []
for i in l:
if i in n:
e.append(i)
return e
#Hello######
n = [1,2,3,4,5]
l = [1,3,4,6]
print(common_ele(l,n))
|
151ce8625340edacbd0b3713ee98bafa48db91eb
|
yize11/1808
|
/17day/06-a+=a和a=a+a的不一样.py
| 333 | 4.09375 | 4 |
def test(a):
a+=a
print(a)#[1,1]
x = [1]
test(x)
print(x)#[1,1]
def test1(a):
a=a+a#先算等号右边,然后把值赋值一个新的变量来指向
print(a)#[1,1]
x = [1]
test1(x)
print(x)#[1]
'''
def test2(a):
a+=a
print(a)#[1,1] 如果可变类型数据,是指a指向上的变量上修改
'''
|
444a32fc381b5cdd5860283f1dde45e3049fd217
|
enterpriseih/data-structure-algorithms
|
/P0/P0/Task1.py
| 880 | 4.0625 | 4 |
"""
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 1:
How many different telephone numbers are there in the records?
Print a message:
"There are <count> different telephone numbers in the records."
"""
def check_dict(dict, key):
if key in dict:
dict[key] += 1
else:
dict[key] = 1
number_dict = dict()
for i in range(len(texts)):
for j in range(2):
check_dict(number_dict, texts[i][j])
for i in range(len(calls)):
for j in range(2):
check_dict(number_dict, calls[i][j])
# for key in number_dict:
# print(key)
print('There are', len(number_dict) ,'different telephone numbers in the records.')
|
5619ff192fd0e03945cafa54505ead95f3f79794
|
pytorch-ts/pytorch-ts
|
/lstm/model.py
| 1,226 | 3.53125 | 4 |
"""Pytorch lstm
"""
import torch
import torch.nn as nn
class LSTM(nn.Module):
"""
lstm
"""
def __init__(self, cov_dim, hidden_dim, batch_first=True, output_dim=1, num_layers=2,
dropout=0.):
super(LSTM, self).__init__()
self.cov_dim = cov_dim
self.hidden_dim = hidden_dim
self.num_layers = num_layers
self.batch_first = batch_first
# Define the lstm layer
self.lstm = nn.LSTM(self.cov_dim + 1, self.hidden_dim, self.num_layers,
batch_first=batch_first, dropout=dropout)
# Define the output layer
self.linear = nn.Linear(self.hidden_dim, output_dim)
self.hidden = None
def init_hidden(self, batch_size):
"""
init hidden state
:return:
"""
self.hidden = (torch.zeros(self.num_layers, batch_size, self.hidden_dim),
torch.zeros(self.num_layers, batch_size, self.hidden_dim))
def forward(self, inp):
"""
forward
:param input:
:return:
"""
lstm_out, self.hidden = self.lstm(inp, self.hidden)
out = self.linear(lstm_out[:, -1, :])
return out.view(-1)
|
9542507cd41d2b317fd4539eace498bf765bfaba
|
Abhishek-IOT/Data_Structures
|
/DATA_STRUCTURES/Stacks&Queues/StackPermutations.py
| 767 | 3.71875 | 4 |
from queue import Queue
def stackPermutation(inp,out,n):
input=Queue()
output=Queue()
for i in range(n):
input.put(inp[i])
for i in range(n):
output.put(out[i])
temp=[]
while(not input.empty()):
ele=input.queue[0]
input.get()
if ele==output.queue[0]:
output.get()
while(len(temp)!=0):
if temp[-1]==output.queue[0]:
temp.pop()
output.get()
else:
temp.append(ele)
return len(temp)==0 and input.empty()
if __name__ == '__main__':
input=[1,2,3]
output=[3,1,2]
m=stackPermutation(input,output,2)
if m==True:
print("Yes")
else:
print("no")
|
f713f4d2ae3bf224c8afe5b8308024a539581575
|
wnj00524/CodeAcademy_proj1
|
/main.py
| 1,427 | 3.734375 | 4 |
class room():
def __init__(self, name, description, exits):
self.name = name
self.description = description
self.exits = exits
def __repr__(self):
seen_exits = ""
for exit in self.exits:
seen_exits = seen_exits + exit + "\n"
if seen_exits == "":
seen_exits = "None!"
a = "This is:","\t" + self.name, self.description, "You can see the following exits:", seen_exits
ret = ""
for b in a:
ret = ret + b + "\n"
return ret
class locale():
def __init__(self, rooms):
self.rooms = rooms
def __repr__(self):
a = ""
for new_room in self.rooms:
a = a + new_room.name + "\n"
return a
def fetch_room(self, current_room, new_room):
for room in self.rooms:
if room.name.title() == new_room.title():
return room
return current_room
entrance = room("Entrance", "This is the entrance to the house.",["Sitting Room"])
sitting_room = room("Sitting Room", "This is the sitting room. Nice and cosey.",["Entrace"])
new_loc = locale([entrance, sitting_room])
print(new_loc)
def main(current_room):
print(current_room)
dest = input("Where would you like to go?")
if dest.lower() == "quit":
exit()
new_room = new_loc.fetch_room(current_room,dest.title())
main(new_room)
main(entrance)
|
64404f90301457af47593624ec70395f99871bb8
|
Gurdeep123singh/mca_python
|
/python/practice python/fact_without_recursion.py
| 1,397 | 4.09375 | 4 |
'''
program to find factorial from 1 to given no and from n to 1 using without recursion
used only 2 function and without returning
i/p -> 6
o/p->
1 ! is : 1
2 ! is : 2
3 ! is : 6
4 ! is : 24
5 ! is : 120
6 ! is : 720
reverse order of factorial is :
6 ! is : 720
5 ! is : 120
4 ! is : 24
3 ! is : 6
2 ! is : 2
1 ! is : 1
'''
def main():
n= int(input("enter no upto which you want factorial :\n")) # taking input
a=1
list1=[]
if (n>0): # if greater than 0 it prints this statement
print(f"\nfactorial from 1 to {n} is :\n")
factorial(n,a,list1)
def factorial(n,a,list1):
if(n==0): # if 0 then prints factorial of 0
print("factorial of 0 is:",a)
else:
for i in range(1,n+1): # if greater than 0
a=a*i # its doing factorial
list1.append(a) # appending factorial in the list
print(f"factorial of {i} is : {a}")
if (n>0): # executes when n is greater than 0
print("\nreverse order of factorial is ->>> ")
print(f"\nfactorial from {n} to 1 is :\n")
for i in range(len(list1)-1,-1,-1): # going from length to 0 or say it is in decreasing order
print(f"factorial of { i+1 } is : {list1[i]}") # printing in reverse order
main()
|
8d2945480e6036e83510b23fd4806d7303c3070f
|
carinatze/cscoffeechat_matching
|
/validate.py
| 381 | 3.5 | 4 |
def valid_filename(filename):
"""Check if filename is for a CSV file with no folder names."""
return not "/" in filename and filename.endswith(".csv")
def duplicate_matches(past_matches, matches):
matches_pairs = set(
frozenset(s.email for s in students)
for students in matches.items()
)
return not past_matches.isdisjoint(matches_pairs)
|
eba88be00144b950fe5ded43d38d593898c89ff8
|
Kunal352000/python_adv
|
/17_userDefinedFunction4.py
| 362 | 4.0625 | 4 |
"""
mixing of default and non-default arguments
"""
def add(x=1,y):
z=x+y
print(z)
add(2,2)
"""
we recive syntaxError becoz non default argumnets follows default arguments
we can pass first as a non default and pass the second as default is true
if we can pass first as a default and second one as non-default then we get
syntax error"""
|
d3d540a659ff1160794f22a1a36faabe327f5579
|
Aditya11020/MusicPlayerInPython-tkinter-
|
/Python project/bg.py
| 542 | 3.515625 | 4 |
from tkinter import *
from PIL import ImageTk
master = Tk()
#width, height = Image.open(image.png).size
canvas = Canvas(master, width=900, height=563)
canvas.pack()
image = ImageTk.PhotoImage(file="image.png")
canvas.create_image(0, 0, image=image, anchor=NW)
canvas_id = canvas.create_text(10, 10,fill="white",anchor="nw",)
canvas.itemconfig(canvas_id, text="this is the text "*300, width=780)
canvas.itemconfig(canvas_id, font=("courier", 12))
canvas.insert(canvas_id, 12, "new ")
#canvas.create_text(2, 2, text="Python")
mainloop()
|
8426694ae1a863761505271f336f99b570c59571
|
supperllx/LeetCode
|
/965.py
| 589 | 3.875 | 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 isUnivalTree(self, root: TreeNode) -> bool:
if not root:
return True
else:
l = self.isUnivalTree(root.left)
r = self.isUnivalTree(root.right)
l_val = root.left.val if root.left else root.val
r_val = root.right.val if root.right else root.val
return all([l, r, l_val == root.val, r_val == root.val])
|
e658bdd1c6921872b0fa1743cf8f27efeefdfcfb
|
fzingithub/SwordRefers2Offer
|
/4_LEETCODE/1_DataStructure/3_Stack/单调栈/矩阵中的最大矩形.py
| 959 | 3.578125 | 4 |
class Solution:
def largestRectangleArea(self, heights):
if not heights:
return 0
length = len(heights)
minL = [-1] * length
minR = [-1] * length
Stack = [] # 单调递减栈
for i in range(length):
while Stack and heights[i] <= heights[Stack[-1]]:
Stack.pop()
minL[i] = 0 if not Stack else Stack[-1] + 1
Stack.append(i)
Stack.clear()
for i in range(length-1, -1, -1):
while Stack and heights[i] <= heights[Stack[-1]]:
Stack.pop()
minR[i] = length-1 if not Stack else Stack[-1] - 1
Stack.append(i)
tempL = [-1] * length
for i in range(length):
tempL[i] = (minR[i] - minL[i] + 1) * heights[i]
return max(tempL)
if __name__ == '__main__':
test = Solution()
res = test.largestRectangleArea([2,1,5,6,2,3])
print(res)
|
ea7594aadcef5561f06cd51c3c1ae4b6d4dc3e0e
|
hariprabha92/anand_python-
|
/chapter2/problem17.py
| 604 | 4.5 | 4 |
''' Write a program reverse.py to print lines of a file in reverse order.
$ cat she.txt
She sells seashells on the seashore;
The shells that she sells are seashells I'm sure.
So if she sells seashells on the seashore,
I'm sure that the shells are seashore shells.
$ python reverse.py she.txt
I'm sure that the shells are seashore shells.
So if she sells seashells on the seashore,
The shells that she sells are seashells I'm sure.
She sells seashells on the seashore; '''
def reverse():
f=open('she.txt')
l=[]
[l.append(line) for line in f]
for i in range(-1,-len(l)-1,-1):
print l[i]
reverse()
|
8779ac78ea86004e6b179240b4e79a63dff82b3c
|
Sitarweb/Python_study
|
/pythontutor_2/num_1.py
| 239 | 3.96875 | 4 |
#Даны два целых числа. Выведите значение наименьшего из них.
a = int(input("введите число"))
b = int(input("введите число"))
if b > a:
print(a)
else:
print(b)
|
563f68c333bb5bcfe8a84dfb5d657bbefe38ea5b
|
Sharukkhan777/Python
|
/general/Generators with example.py
| 1,825 | 4.59375 | 5 |
# Generators in python
'''
Generators :
* Definition:
A generator-function is defined like a normal function, but whenever it needs to generate a value,
it does so with the yield keyword rather than return.
If the body of a def contains yield, the function automatically becomes a generator function.
* A generator function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return.
* We should use yield when we want to iterate over a sequence, but don’t want to store the entire sequence in memory.
* Return sends a specified value back to its caller whereas Yield can produce a sequence of values.
WEBSITE:
https://www.geeksforgeeks.org/use-yield-keyword-instead-return-keyword-python/
'''
#``````````````````````````````````````````````````````````````````````````````
# Example code with yield keyword
# A Python program to generate squares from 1
# to 100 using yield and therefore generator
# An infinite generator function that prints
# next square number. It starts with 1
def nextSquare():
i = 1;
# An Infinite loop to generate squares
while True:
yield i*i #!!!!!!!!!!!!!!!! Warning, if we use return here we get error
i += 1 # Next execution resumes
# from this point
# Driver code to test above generator
# function
for num in nextSquare():
if num > 100:
break
print(num)
#``````````````````````````````````````````````````````````````````````````````
# sololearn example
t=(n for n in range(5))
if type(t) == tuple:
print(len(t))
else:
print(next(t))
#``````````````````````````````````````````````````````````````````````````````
|
86ce2fa70be7b7dbb5274b90407610899ca89557
|
luhralive/python
|
/Jaccorot/0012/0012.py
| 646 | 3.796875 | 4 |
#!/usr/bin/python
# coding=utf-8
"""
第 0012 题: 敏感词文本文件 filtered_words.txt,里面的内容 和 0011题一样,
当用户输入敏感词语,则用 星号 * 替换,例如当用户输入「北京是个好城市」,则变成「**是个好城市」。
"""
def trans_to_words():
type_in = raw_input(">")
with open('filtered_words.txt') as f:
text = f.read().decode('utf-8').encode('gbk')
print text.split("\n")
for i in text.split("\n"):
if i in type_in:
type_in = type_in.replace(i, '**')
print type_in
if __name__ == "__main__":
while True:
trans_to_words()
|
27c4e879e277a5d3a344110aafa93dbab422aff2
|
viad00/code_olymp
|
/olymp2017/3.py
| 159 | 3.890625 | 4 |
def IsPrime(n):
for i in range(2, n):
if (n % i == 0) and (i!=1) and (i!=n):
return False
return True
print(IsPrime(int(input())))
|
64736f36afefdadb43b374af179e512fffc650c6
|
Git-hSin/python-challenge
|
/PyBank/main.py
| 2,021 | 3.640625 | 4 |
import os
import csv
import pandas as pd
import numpy as np
from pathlib import Path
file = Path('C:/Users/hahma/OneDrive/Desktop/PythonData/USCLOS201811DATA3/03_python/homework/Instructions/PyBank/Resources/budget_data.csv')
df_pd = pd.read_csv(file)
Total_Months = df_pd["Date"].count()
PLdiff = []
for i in range(Total_Months):
PLdiff.append(df_pd["Profit/Losses"].iloc[i] - df_pd["Profit/Losses"].iloc[i-1])
df_pd.insert(2, "AvgChg", PLdiff)
PLdiff.pop(0)
Average_Change = round(sum(PLdiff)/(Total_Months-1), 2)
greatest_change = df_pd.iloc[df_pd['AvgChg'].idxmax()]
smallest_change = df_pd.iloc[df_pd['AvgChg'].idxmin()]
print(" ")
print("[Financial Analysis]")
print("----------------------")
print(" ", "Total Months in dataset equals: ", Total_Months)
print(" ", "Average Change between months equals: ", Average_Change)
print(" ", greatest_change["Date"], " was the date with the largest increase in profits at $" ,greatest_change["AvgChg"], ". Profits at this time were $", greatest_change["Profit/Losses"])
print(" ", smallest_change["Date"], " was the date with the largest decrease in profits at $" ,smallest_change["AvgChg"], ". Profits at this time were $", smallest_change["Profit/Losses"])
print(" ")
text = open('Financial Analysis.txt', "w")
print(" ",file=text)
print("[Financial Analysis]",file=text)
print("----------------------",file=text)
print(" ", "Total Months in dataset equals: ", Total_Months,file=text)
print(" ", "Average Change between months equals: ", Average_Change,file=text)
print(" ", greatest_change["Date"], " was the date with the largest increase in profits at $" ,greatest_change["AvgChg"], ". Profits at this time were $", greatest_change["Profit/Losses"],file=text)
print(" ", smallest_change["Date"], " was the date with the largest decrease in profits at $" ,smallest_change["AvgChg"], ". Profits at this time were $", smallest_change["Profit/Losses"],file=text)
print(" ",file=text)
|
b9120dfc17cda4537ccac648dc63f950767bdcec
|
URTK/Lab-5
|
/Main.py
| 701 | 3.859375 | 4 |
import math
masX = []
masY = []
n = 1
# Массив X
for i in range(3): # 19
print('Введите элемент массива', n)
masX.append(int(input()))
n += 1
print(' MasX ', masX)
# Массив Y
for i in range(3):
y = 0,5 * math.log(masX[i])
masY.append(y)
print(' MasY ', masY)
# Поиск наибольшего числа, кратного 3 и вывод его индекса
MaxY = masY[0]
for i in range(3):
if masY[i]>MaxY:
MaxY = masY[i]
if int(MaxY[1]) % 3 == 0:
print(' Наивысший элемент ', MaxY.index)
else:
print(' Элеменат удовлетворяющего уловиям нет ')
|
fb7726678dd568dc59501372739ae431648c32d6
|
nikhil2596/phy
|
/1.py
| 132 | 4.09375 | 4 |
a=input("enter the number:")
if a>0:
print"a is positive"
elif a<0:
print"a is negative"
else:
print "a is zero"
|
d31a5b0486c27ded4d68f162dddf7e340789b594
|
sidtsc/algoritmos
|
/coursera/dezenas.py
| 115 | 4.03125 | 4 |
n = int(input("Digite um número inteiro: "))
print(n)
d = (n // 10) % 10
print("O dígito das dezenas é: %d" % d)
|
7df1141e7a4c136ac4329b4abc74bf4a10a135f9
|
amarmulyak/Python-Core-for-TA
|
/hw03/ashep/task5.py
| 265 | 4.09375 | 4 |
day_of_week = ['Monday','Tuesday','Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday' ]
k = int(input("Enter number "))
if 0 < k <= 365:
n = day_of_week[(k % 7)-1]
print("The weekday is {}".format(n))
else:
print("k should be between 1 and 365")
|
824c29f82c254155bd3356dadcbe9fc98590f78d
|
mourakf/Python-FDS-Dataquest
|
/Python II - Intermediate/Working with Dates and Times in Python-353.py
| 2,353 | 3.71875 | 4 |
## 1. Introduction ##
from csv import reader
potus_visitors_2015 = open('potus_visitors_2015.csv')
read_potus_visitors_2015 = reader(potus_visitors_2015)
list_potus_visitors_2015 = list(read_potus_visitors_2015)
potus = list_potus_visitors_2015[1:]
print(potus)
## 3. The Datetime Module ##
import datetime as dt
## 4. The Datetime Class ##
import datetime as dt
ibm_founded = dt.datetime(1911,6,16)
man_on_moon = dt.datetime(1969,7,20,20,17)
#ano, mes e dia, hora minuto, segundo
print(ibm_founded)
print(man_on_moon)
## 5. Using Strptime to Parse Strings as Dates ##
# The `potus` list of lists is available from
# the earlier screen where we created it
import datetime as dt
date_format = "%m/%d/%y %H:%M"
for column in potus:
appt_start_date = column[2]
convert = dt.datetime.strptime(appt_start_date, date_format)
column[2] = convert
print(column[2])
## 6. Using Strftime to format dates ##
import datetime as dt
visitors_per_month = {}
format_date = "%B, %Y"
for row in potus:
appt_start_date = row[2]
appt_start_date = appt_start_date.strftime(format_date)
if appt_start_date not in visitors_per_month:
visitors_per_month[appt_start_date] = 1
else:
visitors_per_month[appt_start_date] +=1
## 7. The Time Class ##
import datetime
appt_times = []
for row in potus:
appt_dt = row[2]
dt_time = appt_dt.time()
appt_times.append(dt_time)
## 8. Comparing time objects ##
min_time = min(appt_times)
max_time = max(appt_times)
print(min_time, max_time)
## 9. Calculations with Dates and Times ##
dt_1 = dt.datetime(1981, 1, 31)
dt_2 = dt.datetime(1984, 6, 28)
dt_3 = dt.datetime(2016, 5, 24)
dt_4 = dt.datetime(2001, 1, 1, 8, 24, 13)
answer_1 = dt_2 - dt_1
answer_2 = dt_3 + dt.timedelta(days=56)
answer_3 = dt_4 - dt.timedelta(seconds=3600)
print(answer_1, answer_2, answer_3)
## 10. Summarizing Appointment Lengths ##
appt_lengths = {}
for row in potus:
end_date = row[3]
end_date = dt.datetime.strptime(end_date, "%m/%d/%y %H:%M")
row[3] = end_date
start_date = row[2]
length = end_date - start_date
if length not in appt_lengths:
appt_lengths[length] = 1
else:
appt_lengths[length] +=1
min_length = min(appt_lengths)
max_length = max(appt_lengths)
print(max_length)
print(min_length)
print(appt_lengths)
|
b3b98595a6e4a25f115c0757846757a1241470b1
|
FMRodrigues97/Lista02-CES22
|
/Questão05.py
| 185 | 3.59375 | 4 |
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def reflect_x(self):
return self.x, -self.y
print(Point(3, 5).reflect_x())
|
e944e8d61a560098603ac2676a1699a7c613523b
|
nnonnoon/beta
|
/Python/word_chain.py
| 401 | 3.765625 | 4 |
len_word = int(input()); ro = int(input()); word = []
for i in range(ro): word.append(input())
def check_word(a, b):
count = 0
for i in range(len_word):
if a[i] != b[i]: count += 1
return True if count >= 3 else False
for i in range(ro):
if i < ro - 2:
if check_word(word[i], word[i+1]):
print(word[i])
break
elif i == ro-1: print(word[i])
|
d2ae3077e65b45be20704d1e0de5915cff234c19
|
pcaa3000/Python_code
|
/reloj.py
| 344 | 3.71875 | 4 |
ms = 0
s = 0
min = 0
hr = 24
while hr < 24:
while min < 60:
while s < 60:
while ms < 1000:
print(f'{hr} hr : {min} min : {s} s : {ms} ms')
ms += 1
s += 1
ms = 0
min += 1
s = 0
hr += 1
min = 0
print(f'{hr} hr : {min} min : {s} s : {ms} ms')
|
4a473785c2f34f76eca6875de6b7c1c460d31d71
|
MrHamdulay/csc3-capstone
|
/examples/data/Assignment_3/mggdac001/question1.py
| 279 | 4.15625 | 4 |
#Rect angle
def rectangle():
y=eval(input('Enter the height of the rectangle:\n'))
l=eval(input('Enter the width of the rectangle:\n'))
x=y-1
while x<y:
x+=1
#print('*'*x,end='')
print(('*'*l+'\n')*x)
rectangle()
|
0d167e02d7e6fc108c9d5c07cf1124bf5f657aaf
|
JosephLevinthal/Research-projects
|
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4432/codes/1721_3067.py
| 397 | 3.984375 | 4 |
a=input("ataque espada ou cauda ")
b=int(input("numero "))
c=int(input("nu "))
d=int(input("dfsdfg "))
e=int(input("fdfgd "))
if(a=="CAUDA")or(a=="ESPADA"):
if(b<=0)or(b>=7)or(c<=0)or(c>=7)or(d<=0)or(d>=7)or(e<=0)or(e>=7):
print("Entrada invalida")
elif(a=="CAUDA"):
z=(b+c+d)*e
print(z)
elif(a=="ESPADA"):
z=(b+6)+(c+6)+(d+6)+(e+6)
print(z)
else:
print("Entrada invalida")
|
b4ae7c03b928a0090221cb219208f78a5689ee51
|
qader1/pathfind-and-sort-visualizer
|
/interface.py
| 8,060 | 3.5 | 4 |
import tkinter as tk
from tkinter import ttk
from list_visualizer import *
from maze import *
import dbs
def v_sort():
# according to the selected item in the listbox, speed, and size, it run the visualize function.
if lst_sort.curselection()[0] == 0:
data = visualize_sort(list_size.get(), v_bubble_sort, sort_delay.get())
elif lst_sort.curselection()[0] == 1:
data = visualize_sort(list_size.get(), v_insertion_sort, sort_delay.get())
else:
data = visualize_sort(list_size.get(), v_quick_sort, sort_delay.get())
if data is not None:
dbs.sort_entry(lst_sort.get(lst_sort.curselection()), list_size.get(), data[0], data[1])
s_tree.insert('', 'end', values=(dbs.datetime.datetime.now(),
lst_sort.get(lst_sort.curselection()),
list_size.get(),
data[0],
data[1]))
def v_maze():
# according to the selected item in the listbox, speed, and size, it run the visualize function.
if path_find.curselection()[0] == 0:
data = breadth_depth_first(generate_maze(matrix(maze_size.get())), maze_delay.get())
elif path_find.curselection()[0] == 1:
data = breadth_depth_first(generate_maze(matrix(maze_size.get())), maze_delay.get(), breadth=False)
else:
data = wall_follower(generate_maze(matrix(maze_size.get())), maze_delay.get())
if data is not None:
dbs.maze_entry(path_find.get(path_find.curselection()), maze_size.get(), data)
m_tree.insert('', 'end', values=(dbs.datetime.datetime.now(),
path_find.get(path_find.curselection()),
maze_size.get(),
data))
def clear_maze_table():
# deletes all rows in the maze table. calls the function from dbs file
dbs.clear_path()
m_tree.delete(*m_tree.get_children())
def clear_sort_table():
# deletes all the rows in the sorting table.
dbs.clear_sort()
s_tree.delete(*s_tree.get_children())
def filter_maze():
if combobox_m.get() == 'All':
result = dbs.get_path()
else:
result = dbs.filter_maze(combobox_m.get())
m_tree.delete(*m_tree.get_children())
for i in result:
m_tree.insert('', 'end', values=tuple(i))
def filter_sort():
if combobox_s.get() == 'All':
result = dbs.get_sort()
else:
result = dbs.filter_sort(combobox_s.get())
s_tree.delete(*s_tree.get_children())
for i in result:
s_tree.insert('', 'end', values=tuple(i))
def on_closing():
dbs.connection.close()
root.destroy()
# tkinter root window, title, and size.
root = tk.Tk()
root.title('algorithm visualizer')
root.geometry('700x500')
root.resizable(0, 0)
# closes the connection with the databases. the connection is made in the dbs file
root.protocol("WM_DELETE_WINDOW", on_closing)
# notebook holds different frames and displays them as tabs
tabs = ttk.Notebook(root)
# first tab for sort visualization
tab1 = ttk.Frame(tabs)
tab1.rowconfigure(0, weight=1)
tab1.columnconfigure(1, weight=1)
# second tab for the maze
tab2 = ttk.Frame(tabs)
tab2.rowconfigure(0, weight=1)
tab2.columnconfigure(1, weight=1)
# name the tabs and make them fill the notebook
tabs.add(tab1, text='sorting visualizer')
tabs.add(tab2, text='path finding visualizer')
tabs.pack(expand=1, fill='both')
# list box for the sorting algorithms options
sorting_alg = ('bubble sort', 'insertion sort', 'quick sort')
lst_sort = tk.Listbox(tab1, height=2)
lst_sort.grid(column=0, row=0, sticky='nws', padx=15, pady=15)
lst_sort.insert(tk.END, *sorting_alg)
# scale to choose the size with a label
list_size_l = tk.Label(tab1, text='size')
list_size_l.grid(column=0, row=2)
list_size = tk.Scale(tab1, from_=1, to=300, orient=tk.HORIZONTAL)
list_size.set(150)
list_size.grid(column=1, columnspan=3, row=2, sticky='ew', padx=10)
# scale to choose the speed of the visualization with a label
sort_delay_l = tk.Label(tab1, text='delay')
sort_delay_l.grid(column=0, row=3)
sort_delay = tk.Scale(tab1, from_=0, to=4, orient=tk.HORIZONTAL)
sort_delay.set(2)
sort_delay.grid(column=1, columnspan=3, row=3, sticky='sew', padx=10, pady=5)
# create a table with the widget treeview. the table displays the runs of sorting visualizations
s_tree_columns = ('Time', 'Algorithm', 'List size', 'Swaps', 'Comparisons')
s_tree = ttk.Treeview(tab1, columns=s_tree_columns, show='headings')
for i in s_tree_columns:
s_tree.heading(i, text=i)
s_tree.column(i, width=80)
s_tree.column('Time', width=110)
s_tree.grid(column=1, row=0, sticky='news', pady=15)
s_data = list(dbs.get_sort())
for i in s_data:
s_tree.insert('', 'end', values=tuple(i))
s_tree_scroll = ttk.Scrollbar(tab1,
orient="vertical",
command=s_tree.yview)
s_tree_scroll.grid(column=2, row=0, sticky='ns', pady=15)
s_tree.configure(yscrollcommand=s_tree_scroll.set)
# 2 buttons to run the visualization and clear the table in the database
v_sort_button = tk.Button(tab1, text='Visualize', command=v_sort, width=20)
v_sort_button.grid(column=1, row=4, pady=10)
clear_sort_h = tk.Button(tab1, text='Clear history', command=clear_sort_table, width=20)
clear_sort_h.grid(column=0, row=4, pady=10, padx=15)
# listbox to choose the path finding algorithms options
maze_algs = ('breath first search', 'depth first search', 'wall follower')
path_find = tk.Listbox(tab2, height=1)
path_find.grid(column=0, row=0, sticky='nws', padx=15, pady=15)
path_find.insert(tk.END, *maze_algs)
# scale for the maze size
maze_size_l = tk.Label(tab2, text='size')
maze_size_l.grid(column=0, row=2)
maze_size = tk.Scale(tab2, from_=5, to=60, orient=tk.HORIZONTAL)
maze_size.set(20)
maze_size.grid(column=1, columnspan=3, row=2, sticky='ew', padx=10)
# scale for the speed of the visualization
maze_delay_l = tk.Label(tab2, text='delay')
maze_delay_l.grid(column=0, row=3)
maze_delay = tk.Scale(tab2, from_=0, to=4, orient=tk.HORIZONTAL)
maze_delay.set(2)
maze_delay.grid(column=1, columnspan=3, row=3, sticky='sew', padx=10, pady=5)
# table for the history of runs of the path finding algorithms
m_tree_columns = ('Time', 'Algorithm', 'maze size', 'cells scanned')
m_tree = ttk.Treeview(tab2, columns=m_tree_columns, show='headings')
for i in m_tree_columns:
m_tree.heading(i, text=i)
m_tree.column(i, width=80)
m_tree.column('Time', width=110)
m_tree.grid(column=1, row=0, sticky='news', pady=15)
m_data = list(dbs.get_path())
for i in m_data:
m_tree.insert('', 'end', values=tuple(i))
m_tree_scroll = ttk.Scrollbar(tab2,
orient="vertical",
command=m_tree.yview)
m_tree_scroll.grid(column=2, row=0, sticky='ns', pady=15)
m_tree.configure(yscrollcommand=m_tree_scroll.set)
# 2 buttons to run the visualization and to clear the table in the database
v_maze_button = tk.Button(tab2, text='Visualize', command=v_maze, width=20)
v_maze_button.grid(column=1, row=4, pady=10)
clear_maze_h = tk.Button(tab2, text='Clear history', command=clear_maze_table, width=20)
clear_maze_h.grid(column=0, row=4, pady=10, padx=15)
combobox_m = ttk.Combobox(tab2, width=15, value=['All', *maze_algs])
combobox_m.grid(column=1, row=1, pady=20)
combobox_m.set('All')
combobox_m_button = tk.Button(tab2, text='Filter history', width=20, command=filter_maze)
combobox_m_button.grid(column=1, row=1, sticky='e')
combobox_s = ttk.Combobox(tab1, width=15, value=['All', *sorting_alg])
combobox_s.grid(column=1, row=1, pady=20)
combobox_s.set('All')
combobox_s_button = tk.Button(tab1, text='Filter history', width=20, command=filter_sort)
combobox_s_button.grid(column=1, row=1, sticky='e')
tk.mainloop()
|
d60314cced05376d396a9e63a89f01784d7ed480
|
sohn0356-git/TIL
|
/PyStudy/day06/p305.py
| 1,325 | 3.625 | 4 |
f = open("live.txt", "wt", encoding='UTF-8')
f.write("""God will make a way
Where there seems to be no way
He works in ways we cannot see
He will make a way for me
He will be my guide
Hold me closely to his side
With love & strength for each new day
He will make a way
He will make a way
God will make a way
Where there seems to be no way
He works in ways we cannot see
He will make a way for me
He will be my guide
Hold me closely to his side
With love & strength for each new day
He will make a way
He will make a way
By a roadway in the wilderness
He'll lead me
Rivers in the desert
Will I see
Heaven & earth will fade
But his word will still remain
& He will do something new today
God will make a way
Where there seems to be no way
He works in ways we cannot see
He will make a way for me
He will be my guide
Hold me closely to his…""")
print(type(f))
f.close()
fr = None
try:
fr = open("liv.txt","rt", encoding="UTF-8")
text = fr.read()
print(text)
except FileNotFoundError:
print("There isn't file")
finally:
if fr != None:
fr.close()
# try:
# f2 = open("live.txt","rt")
# while True:
# text = f2.read(10)
# if len(text)==0:
# break
# print(text, end = '')
# except FileNotFoundError:
# print("There isn't file")
# finally:
# f2.close()
|
9c531073982a38ee4f619ccea7e5c5729923864a
|
plilja/project-euler
|
/problem_32/pandigit.py
| 484 | 3.515625 | 4 |
from math import sqrt
from common.functions import is_pandigital
def pandigital_products():
res = set()
for product in range(1, int(sqrt(123456789))):
for multiplicand in range(2, int(sqrt(product))):
if product % multiplicand == 0:
pandigital_candidate = int(str(product) + str(multiplicand) + str(product / multiplicand))
if is_pandigital(pandigital_candidate, 1, 9):
res |= {product}
return res
|
ded2b1c097117385a34e4f9db7cc455810c1ce07
|
odair-pedroso/Nanodegree-Python
|
/amigo.py
| 195 | 3.609375 | 4 |
def is_friend(name):
if name[0]=="D":
return True
if name[0]=="N":
return True
else:
return False
print is_friend("Damara")
print is_friend("Odair")
|
9e1687562b2d67b36f48fc5170045f84748393dd
|
ziyaad18/LibariesPython
|
/dropdown.py
| 229 | 3.609375 | 4 |
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
Window = Tk()
variable = StringVar(Window)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(Window, variable, *OPTIONS)
w.grid(row=1, column=3)
mainloop()
|
bc4ade117fd8017f2ead0adac5ffb0c7e2c479ce
|
giftnadia/Age-Calculator
|
/hello.py
| 270 | 4.25 | 4 |
year_of_birth=int(input("year_of_birth"))
def age_calc(yearofbirth):
age=(2019-year_of_birth)
if age < 18 :
print("your are a minor")
elif age < 35 :
print("you are a youth")
else :
print("you are an elder")
age_calc(year_of_birth)
|
c51a770a9182d9dba58002659549bc4a1d589cc7
|
yaochie/AdventOfCode2019
|
/6.py
| 1,994 | 3.5625 | 4 |
class Node:
def __init__(self, name):
self.name = name
self.children = set()
self.parent = None
def add_child(self, child):
# child should also be a node
assert isinstance(child, Node)
self.children.add(child)
assert child.parent is None or child.parent == self
child.parent = self
def n_children(self):
return sum([
child.n_children()
for child in self.children
]) + len(self.children)
def __repr__(self):
return self.name
def n_ancestors(node):
n = 0
while node.parent is not None:
n += 1
node = node.parent
return n
def rootpath(node):
path = []
while node.parent is not None:
path.append(node.parent)
node = node.parent
return path
def find_lowest_common_ancestor(node1, node2):
rootpath1 = list(reversed(path_to(node1, None)))
rootpath2 = list(reversed(path_to(node2, None)))
i = 0
while rootpath1[i] == rootpath2[i]:
i += 1
return rootpath1[i-1]
def path_to(src, dest):
if src == dest:
return []
path = []
node = src
while node.parent != dest:
path.append(node.parent)
node = node.parent
return path
orbits = open('../data/input6').readlines()
# orbits = """COM)B
# B)C
# C)D
# D)E
# E)F
# B)G
# G)H
# D)I
# E)J
# J)K
# K)L
# K)YOU
# I)SAN""".split()
# build tree?
nodes = {}
nodes['COM'] = Node('COM')
for orbit in orbits:
source, target = orbit.strip().split(')')
if source not in nodes:
nodes[source] = Node(source)
if target not in nodes:
nodes[target] = Node(target)
# add relation
nodes[source].add_child(nodes[target])
print(sum(n_ancestors(node) for node in nodes.values()))
# part 2
common_anc = find_lowest_common_ancestor(nodes['YOU'], nodes['SAN'])
ans2 = len(path_to(nodes['YOU'], common_anc)) + len(path_to(nodes['SAN'], common_anc))
print(ans2)
|
5966f2ca4298ae1514e8cd061615fc8661d17aed
|
kylejava/InterviewPractice
|
/merge.py
| 619 | 3.984375 | 4 |
def mergesort(data):
if(len(data) == 0 or len(data) == 1):
return data
mid = len(data) // 2
a = data[:mid]
b = data[mid:]
a = mergesort(a)
b = mergesort(b)
return merge(a, b)
def merge(a, b):
c = []
while(len(a) != 0 and len(b) != 0):
if(a[0] > b[0] ):
c.append(b[0])
b.pop(0)
else:
c.append(a[0])
a.pop(0)
for i in range(len(a)):
c.append(a[0])
a.pop(0)
for j in range(len(b)):
c.append(b[0])
b.pop(0)
return (c)
x = [9,4,1,7,3,8,3,1,0]
print(mergesort(x))
|
01240ebbeac9cd0dd912097c8249ca7c6654b73f
|
janedallaway/ThinkStats
|
/Chapter2/pumpkin.py
| 1,975 | 4.25 | 4 |
import thinkstats
import math
'''ThinkStats chapter 2 exercise 1
http://greenteapress.com/thinkstats/html/thinkstats003.html
This is a bit of an overkill solution for the exercise, but as I'm using it as an opportunity to learn python it seemed to make sense'''
class Pumpkin():
def __init__ (self, type, size, number):
self.type = type
self.size = size
self.number = number
def getType(self):
return self.type
def getSize(self):
return self.size
def getNumber(self):
return self.number
class Pumpkins():
def __init__ (self):
self.pumpkins = [] # store complete pumpkin objects
self.weightsOnly = [] # store the weights only, one entry per pumpkin
pass
def addPumpkin (self, myPumpkin):
self.pumpkins.append (myPumpkin)
for i in range (myPumpkin.getNumber()):
self.weightsOnly.append (myPumpkin.getSize())
def writePumpkins(self):
for pumpkin in self.pumpkins:
print "There are",pumpkin.getNumber()," ",pumpkin.getType()," pumpkins which weigh",pumpkin.getSize(),"pound each"
def writeWeights(self):
for weight in self.weightsOnly:
print weight
def meanPumpkin(self):
return thinkstats.Mean(self.weightsOnly)
def variancePumpkin(self):
return thinkstats.Var(self.weightsOnly)
def stdDeviationPumpkin(self):
return math.sqrt(self.variancePumpkin())
myPumpkins = Pumpkins()
myPumpkins.addPumpkin(Pumpkin("Decorative",1,3))
myPumpkins.addPumpkin(Pumpkin("Pie",3,2))
myPumpkins.addPumpkin(Pumpkin("Atlantic Giant",591,1))
print "The mean weight is", myPumpkins.meanPumpkin() # should be 100
print "The variance weight is", myPumpkins.variancePumpkin()
print "The standard deviation is", myPumpkins.stdDeviationPumpkin()
|
be198122a49dcbc18eaefc8a501a18fc76c54cdd
|
KondakovY/Python
|
/Lesson2/Task2.py
| 658 | 4.3125 | 4 |
"""
2. Для списка реализовать обмен значений соседних элементов, т.е.
Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д.
При нечетном количестве элементов последний сохранить на своем месте.
Для заполнения списка элементов необходимо использовать функцию input().
"""
list = input('Значение через пробел: ').split()
for a in range(0, len(list) - 1, 2):
list[a], list[a+1] = list[a+1], list[a]
print(list)
|
1d32952c8bdc4fdbcffa5a37cbaf9181ff35cdb6
|
jajatisahoo/PythonProgram123
|
/DailyProgram/loop.py
| 170 | 3.96875 | 4 |
print("hello world")
i = 1;
while (i <= 2):
print("value of i is" + str(i));
i = i + 1
# j =input("enter a string")
name="jajati"
length=len(name)
print(length)
|
8322d1f4ca5d1365720fa9bc36dac86bdcd67929
|
alex2018hillel/Hillel2020Python
|
/Lesson_2/Task_6.py
| 305 | 3.984375 | 4 |
import re
str = "English = 78 Science = 83 Math = 68 History = 65"
def sum_num(str):
"""Return sum all numbers in string"""
regex_num = re.compile('\d+')
numbers_string = regex_num.findall(str)
numbers = [int(elem) for elem in numbers_string]
return sum(numbers)
print(sum_num(str))
|
5cff738f71bed1e7b605dc20cc1dbfe9865579ce
|
jeongwoohong/iot_python2019
|
/01_Jump_to_python/3_control/3_for/5_144.py
| 248 | 3.8125 | 4 |
#coding: cp949
#step1] ̽ ⺻
a=[1,2,3,4]
result=[]
for num in a:
result.append(num*3)
print(result)
a=[1,2,3,4]
result = [num *3 for num in a]
print(result)
a=[1,2,3,4]
result=[num *3 for num in a if num%2==0]
print(result)
|
7061c403eb80a27bfa101d8eaef35a258f470334
|
rtullybarr/battlesnake-python
|
/app/collisions.py
| 3,629 | 3.546875 | 4 |
from app.movement import UP, DOWN, LEFT, RIGHT, points_equal, move_point, move_towards, distance
# set of weighting fuctions designed to help us avoid collisions.
def avoid_walls(data, weight):
criteria = {"goal": "avoid_walls", "weight": weight}
# walls: places with x, y outside the game area
# where we are
us = data["you"]
board = data["board"]
# first point in list is our head.
our_head = us["body"][0]
# possible directions we can move
directions = [1.0, 1.0, 1.0, 1.0]
if our_head["x"] + 1 >= board["width"]:
directions[RIGHT] = 0.0
if our_head["x"] - 1 < 0:
directions[LEFT] = 0.0
if our_head["y"] + 1 >= board["height"]:
directions[DOWN] = 0.0
if our_head["y"] - 1 < 0:
directions[UP] = 0.0
# normalize weighting matrix
if sum(directions) == 0:
criteria["direction_values"] = [0.0, 0.0, 0.0, 0.0]
else:
criteria["direction_values"] = [x / sum(directions) for x in directions]
return criteria
def avoid_other_snakes(data, weight):
criteria = {"goal": "avoid_other_snakes", "weight": weight}
# walls: places with x, y outside the game area
# where we are
us = data["you"]
# first point in list is our head.
us_points = us["body"]
our_head = us_points[0]
# spots we could move:
moves = [move_point(our_head, UP), move_point(our_head, DOWN),
move_point(our_head, LEFT), move_point(our_head, RIGHT)]
other_snakes = []
# other snakes
for snake in data["board"]["snakes"]:
if snake["health"] > 0:
# If snake is dead, we don't need to avoid it
other_snakes.append(snake)
# possible directions we can move
directions = [1.0, 1.0, 1.0, 1.0]
for snake in other_snakes:
snake_points = snake["body"]
# note: tail is always safe
for index in range(len(snake_points)):
# special handling for enemy snake heads
if index == 0 and not points_equal(our_head, snake_points[index]):
# weight if other snake is bigger than us
weight = 0.1
if len(snake_points) < len(us_points):
# weight if other snake is smaller than us
weight = 2.0
for i in range(4):
for j in range(4):
# be more conservative about enemy snake heads
if distance(moves[i], move_point(snake_points[index], j)) < 2.2:
if weight == 0.1 and points_equal(moves[i], move_point(snake_points[index], j)):
# don't die
directions[i] = 0.0
else:
directions[i] = weight
for i in range(4):
if points_equal(moves[i], snake_points[index]):
directions[i] = 0.0
# normalize and return
if sum(directions) == 0:
criteria["direction_values"] = [0.0, 0.0, 0.0, 0.0]
else:
criteria["direction_values"] = [x / sum(directions) for x in directions]
return criteria
def follow_tail(data, weight):
criteria = {"goal": "follow_our_tail", "weight": weight}
head = data["you"]["body"][0]
tail = data["you"]["body"][-1]
directions = move_towards(head, tail)
# normalize and return
if sum(directions) == 0:
criteria["direction_values"] = [0.0, 0.0, 0.0, 0.0]
else:
criteria["direction_values"] = [x / sum(directions) for x in directions]
return criteria
|
de9dea6f907835b05912b49feb664be1b0ac1d16
|
castilhos90124/E-PRIME-Converter
|
/DataTools_2.0.py
| 407 | 3.515625 | 4 |
import os
error = True
choice = 0
while error:
error = False
print("Que tipo de arquivo sera inserido ?")
print("1: Os do Pedro")
print("2: IAPS / Attractfaces")
choice = input()
if choice == "1":
import parte1
import parte2
elif choice == "2":
import Main
else:
error = True
os.system("CLS")
print("Opcao invalida !")
|
a6f7c25d852c431f22641cc9a4ea54e32b00e29e
|
p4t0p/codewars
|
/chess_exercise.py
| 1,479 | 3.515625 | 4 |
from chess.main import start as StartGame
from chess.helpers import inverse, compare, get_range, to_x_cord, from_x_cord
def pawn(game, from_i, to_i, from_j, to_j):
color = game.queue
is_straight = from_j == to_j
move_to_fig = game.find(to_i, to_j)
max_move = 1
if (color is 'black' and from_i == 2) or (color is 'white' and from_i == 7):
max_move = 2
if is_straight:
return move_to_fig == ' ' and to_i - from_i <= max_move if color is 'black' else from_i - to_i <= max_move
else:
if abs(compare(from_j, to_j)) <= max_move and move_to_fig != ' ' and game.get_color(move_to_fig) != color:
return {
'figure': move_to_fig,
'color': inverse(color),
}
else:
return False
def rook(game, from_i, to_i, from_j, to_j):
color = game.queue
is_horizontal = from_i == to_i
is_vertical = from_j == to_j
move_to_fig = game.find(to_i, to_j)
if is_horizontal:
for x in get_range(to_x_cord(from_j), to_x_cord(to_i)):
if game.find(to_i, from_x_cord(x)) != ' ':
return False
else:
for y in get_range(from_i, to_i):
if game.find(y,to_j) != ' ':
return False
if move_to_fig != ' ':
return game.get_color(move_to_fig) != color
return True
moves = {
'♙': pawn,
'♟': pawn,
'♜': rook,
'♖': rook,
}
game = StartGame(moves)
|
c11d343a9d2cc62bfe2e401a1bcf568638a6e86e
|
coltynw/Sprint-Challenge--Data-Structures-Python
|
/ring_buffer/ring_buffer.py
| 841 | 3.734375 | 4 |
class RingBuffer:
def __init__(self, capacity):
#where it the iterating position is
self.current = 0
#the array
self.store = []
#the max number of things in the array
self.capacity = capacity
def append(self, item):
#check if the length of the array is smaller than the capacity
if len(self.store) < self.capacity:
#if it is then add on next item
self.store.append(item)
#if it isn't then
else:
#get the oldest item
self.store[self.current] = item
#add 1
self.current += 1
#if the position is at capacity
if self.current == self.capacity:
#then go back to the first one, zero index.
self.current = 0
def get(self):
return self.store
|
b7cba9ec47ec9a03d7478a4de7a68f29c2a12014
|
giridhersadineni/pythonexamples
|
/fibonnaci.py
| 212 | 3.625 | 4 |
import sys
def cube(n): #generator function
if(n<0):
return
yield n*n*n
c = cube(9)
while True:
try:
print (next(c), end=" ")
except StopIteration:
sys.exit()
|
ac562896435c8d41ef57f2dad1a9ef240e68ec72
|
busuka/Python_src
|
/Checkio/★digits-multiplication.py
| 850 | 3.65625 | 4 |
import itertools
def checkio1(number):
v = list(str(number))
mv = list(map(lambda x: x.replace('0', '1'), v)) # => ['1','2','3','4','1','5']
nv = list(map(int, mv))
pdt = 1
for i in nv:
pdt = pdt * i
return pdt
def checkio(number):
number_list = [x for x in map(int, list(str(number))) if x != 0] # => [1,2,3,4,5]
return list(itertools.accumulate(number_list, lambda x, y: x * y))[-1]
def checkioNO1(number):
res = 1
for d in str(number):
res *= int(d) if int(d) else 1 # d = 0 のときはbool値がFalseとなる. Pythonは0が偽.
return res
# These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio(123405) == 120
assert checkio(999) == 729
assert checkio(1000) == 1
assert checkio(1111) == 1
|
8129fc331e458127c84d8faece4cf0cd2452507c
|
ksturm/python-challenge
|
/pypoll_nopandas_trial.py
| 1,941 | 3.796875 | 4 |
#GROFIT
# Import Libraries
import os
import csv
# Init Variables/Lists
num_votes = 0
candidates = []
vote_counts = []
# Define Path
poll_data = "Resources/election_data.csv"
poll_path = os.path.join(poll_data)
#Open File
with open(poll_path, newline="") as csvfile:
csvreader = csv.reader(csvfile)
#Skip Header
row = next(csvreader,None)
#count vote total as well as based on candidate/ add candidate to list of candidates if not already in list
for row in csvreader:
num_votes = num_votes + 1
candidate = row[2]
if candidate in candidates:
candidate_index = candidates.index(candidate)
vote_counts[candidate_index] = vote_counts[candidate_index] + 1
else:
candidates.append(candidate)
vote_counts.append(1)
#Variable Init
vote_percents = []
high_votes = vote_counts[0]
max_index = 0
#Compares each candidates vote_count to the total num_votes, output X100 for percent
for count in range(len(candidates)):
percent_votes = vote_counts[count]/num_votes*100
vote_percents.append(percent_votes)
#if an item in the list is greater than the last greatest item saved it replaces it, sets max index to the index of that candidate
if vote_counts[count] > high_votes:
high_votes = vote_counts[count]
print(high_votes)
max_index = count
#prints name of Candidate holding max_index as thier count
winner = candidates[max_index]
sumarry = (
f"\nElection Results\n"
f"--------------\n"
f"Total Votes Cast: {num_votes}\n"
f"Candidates: {candidates}\n"
f"Winner: {winner}\n"
f"Candidate Votes: {vote_counts}\n"
f"Vote Percents: {vote_percents}\n"
)
#print Sumarry
# print(winner)
# print(*candidates)
# print(*vote_counts)
# print(vote_percents)
# print(num_votes)
print(sumarry)
txtOutputPath = os.path.join('Pypoll.txt')
with open(txtOutputPath, "w") as f:
f.write(sumarry)
|
991bf9f915f370cc1cb7a467b3fb7273b926d406
|
YanHengGo/python
|
/19/lesson.py
| 339 | 3.859375 | 4 |
def discounts(price,rate):
final_price=price*rate
old_price=50
print('in function old_price : ',old_price)
return final_price
old_price=float(input('please enter a price :'))
rate=float(input('please enter a rate :'))
new_price=discounts(old_price,rate)
print('global old_price:',old_price)
print('discounts :',new_price)
|
080341b9ac0f1d109c9c1f7de120adfc989e216e
|
mepragati/100_days_of_Python
|
/Day 001/BandNameGenerator.py
| 251 | 4.1875 | 4 |
#Band Name Generator Program
print("Welcome to the Band Name Generator !!")
name=input("What is the name of the city you grew up in?\n")
pet=input("What is the name of the first pet you owned?\n")
print("The name of your Band could be: "+name+" "+pet)
|
a7eb8027dd3973f991318dc08847dec1a43f322e
|
Devanosh/python-projects
|
/list comprehension.py
| 159 | 4.0625 | 4 |
# odd=[]
# for x in range(3,60):
# if(x%3==0):
# x+=8
# odd.append(x)
# print(odd)
a=[x+8 for x in range(3,60) if x%3==0]
print(a)
|
93d9b612bb2a7a93efa7612fbe6f199eb1af4d0e
|
seddon-software/python3
|
/Python3/src/_Exercises/src/Pandas/07_additional_column.py
| 560 | 3.796875 | 4 |
'''
Use Pandas to read the file "../MiniProject/wtk_site_metadata.csv"
Create the same dataframe 'Rhode Island' as in the previous exercise.
Now add an extra column called 'power' that is computed as the product of the
columns 'capacity_factor' and 'wind_speed'.
'''
import pandas as pd
pd.set_option('display.precision', 2)
pd.set_option('display.width', None)
pd.set_option('display.max_rows', None)
df = pd.read_csv("../MiniProject/wtk_site_metadata.csv")
df['power'] = df.apply(lambda row:row.capacity_factor*row.wind_speed, raw=True, axis=1)
print(df)
|
08e34bbdeeed4761a8bd0b85875e8ac64ff7875e
|
marcelofreire1988/python-para-zumbis-resolucao
|
/Lista 1/questão03.py
| 377 | 3.921875 | 4 |
#Escreva um programa que leia a quantidade de dias, horas, minutos e segundos do usuário. Calcule o total em segundos.
dias = int(input("insira um dia: " ))
horas = int(input("insira as horas: "))
minutos = int(input("insira os minutos: "))
segundos = float(input("insira os segundos: "))
total = dias * 24 * 60 * 60 + horas * 60 * 60 + minutos * 60 + segundos
print total
|
a8bb4b1590e9ea71d7589b68283b8b7155adf26f
|
SuchismitaDhal/Solutions-dailyInterviewPro
|
/2020/08-August/08.02.py
| 1,144 | 3.828125 | 4 |
# AMAZON
"""
SOLVED -- LEETCODE#340
You are given a string s, and an integer k.
Return the length of the longest substring in s that contains at most k distinct characters.
For instance, given the string:
aabcdefff and k = 3,
then the longest substring with 3 distinct characters would be defff.
The answer should be 5.
"""
def longest_substring_with_k_distinct_characters(s, k):
# Time: O(n) Space: O(1)
if k == 0:
return 0
hash = dict()
sz = 0
l = r = 0
sol = 0
while r < len(s):
if sz > k:
if hash[s[l]] == 1:
del hash[s[l]]
sz -= 1
else:
hash[s[l]] -= 1
l += 1
else:
sol = max(sol, r - l)
if s[r] in hash:
hash[s[r]] += 1
else:
hash[s[r]] = 1
sz += 1
r += 1
if sz <= k: sol = max(sol, r - l)
return sol
print(longest_substring_with_k_distinct_characters('aabcdefff', 3))
# 5 (because 'defff' has length 5 with 3 characters)
|
1f5af626290f012084e1aafe8e86a1a629835726
|
antomin/GB_Algorithms
|
/lesson_2/task_2_3.py
| 463 | 4.3125 | 4 |
"""
Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран. Например, если введено
число 3486, то надо вывести число 6843.
"""
def revers_func(num):
res = 0
while num > 0:
res = res * 10 + num % 10
num = num // 10
return res
print(revers_func(nt(input('Enter number: '))))
|
e19cc8244e1db0c143ebd921995f1cedbb99a85c
|
thebillington/menu_pyg
|
/menu_pyg/menus.py
| 1,328 | 4.09375 | 4 |
#Class that implements the most basic menu
class Menu(object):
def __init__(self, screen, x, y, width, height, font, aa, colour):
#Store the screen
self.screen = screen
#Setup a list of menu items
self.menu_items = []
#Setup a list to store the renders
self.item_renders = []
#Set the position of the menu
self.x = x
self.y = y
self.width = width
self.height = height
#Store the font and render options
self.font = font
self.aa = aa
self.colour = colour
#Function to render all of the fonts
def render_items(self):
self.item_renders = []
#For each item, render
for item in self.menu_items:
self.item_renders.append(self.font.render(item.text, self.aa, self.colour))
def add_item(self, item):
#Add the item
self.menu_items.append(item)
#Render the fonts
self.render_items()
def list_items(self):
for item in self.menu_items:
print item.text
def render(self):
#Store how much to move the y by for each item
y_increment = 0
for r in self.item_renders:
self.screen.blit(r, (self.x, self.y + y_increment))
y_increment += r.get_height()
|
4b099712f20c917a1e17b58b53e671d49224dd8a
|
Alamin-H-M/photon_theory
|
/photon_theory.py
| 622 | 4.28125 | 4 |
# what is the angular momentum of an electron in 3rd shell? if the radius of the shell 3.6 * (10**-8)cm , determine the velocity of the shell. [mass of an electron = 9.11 * (10**-28 g)]
'''
here, shell no., n = 3
plunk constant, h = 6.626 * (10**-34) Js
constant, pi = 22/7
mass of electron, m = 9.11 * (10**-31) kg
radius of shell, r = 3.6 *(10**-10)
'''
n = 3
h = 6.626 * (10**-34)
pi = 22/7
m = 9.11 * (10**-31)
r = 3.6 *(10**-10)
angular_momentum = (n * h) / (2 * pi)
velocity = angular_momentum / (m * r)
print(f"angular momentum = {angular_momentum} Js\n and the velocity = {velocity} m/s")
|
261d8a1cca6b0e39e5d5535c5a9204b44d207178
|
hussainMansoor876/Python-Work
|
/practice/.idea/practice 9.py
| 658 | 3.65625 | 4 |
from collections import defaultdict
import json
# numbers = [2, 3, 5, 7, 11, 13,15,17]
# filename = 'numbers.json'
# with open(filename,'r+') as f_obj:
# data=json.dump(numbers,f_obj)
# data1=json.load(f_obj)
# print(data1)
# print(data[0])
# username = input("What is your name? ")
username = {'name': 'mans', 'id': 30557, 'address': 'sdh', 'balance': 'Rs 888'}
filename = 'username.json'
with open(filename,'a') as f_obj:
json.dump(str(username)+"\n", f_obj)
# username=json.load(f_obj)
# print("We'll remember you when you come back, " + str(user) + "!")
# print(username)
# if 'Rs 999' in username:
# print(username)
|
12a6321d1692888412cbf0fb4743490727938069
|
oggyoggy448/school_management_system_using_sqlite
|
/db_conn.py
| 1,321 | 4.1875 | 4 |
import sqlite3
from sqlite3 import Error
def create_connection(db_file):
""" create a database connection to the SQLite database
specified by db_file
:param db_file: database file
:return: Connection object or None
"""
conn = None
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
return conn
def create_table(conn, create_table_sql):
""" create a table from the create_table_sql statement
:param conn: Connection object
:param create_table_sql: a CREATE TABLE statement
:return:
"""
try:
c = conn.cursor()
c.execute(create_table_sql)
except Error as e:
print(e)
def insert_student_data(conn, project):
"""
Create a new project into the projects table
:param conn:
:param project:
:return: project id
"""
sql = ''' INSERT INTO students
VALUES(?,?,?,?) '''
cur = conn.cursor()
cur.execute(sql, project)
conn.commit()
print("data has been added")
def select_all_tasks(conn):
"""
Query all rows in the tasks table
:param conn: the Connection object
:return:
"""
cur = conn.cursor()
cur.execute("SELECT * FROM students")
rows = cur.fetchall()
for row in rows:
print(row)
|
56fa7796fa14663c3fc6e9ac960dd9221f394f79
|
j0ker404/flappy-clone
|
/state.py
| 1,439 | 3.5 | 4 |
import colours
import pygame
class State:
def __init__(self, game_area,bird,SCREEN,pipe, pipe_group=None):
"""
game_area: Game_Area instance
pipe_group: Pipe_group instance
bird: bird instance
SCREEN: Display Surface area
"""
self.game_area = game_area
self.bird = bird
self.SCREEN = SCREEN
self.pipe = pipe
self.pipe_group = pipe_group
def draw(self):
"""
draw state on screen
"""
# draw current state on game screen
# add background colour
self.game_area.fill(colours.WHITE)
self.game_area.blit(self.bird.image,self.bird.rect)
self.game_area.blit(self.pipe.image,(self.pipe.get_x(), self.pipe.get_y()))
# draw game screen on APP window
self.SCREEN.blit(self.game_area,self.game_area.get_coords())
def update_state(self):
"""
update current state on game area
"""
# events
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
quit()
elif event.key == pygame.K_SPACE:
# jump
pass
def update_display(self):
"""
Update display
"""
pygame.display.update()
|
f0f35b6d5104853340a6597a3ec70a59e9be6dee
|
qhuydtvt/C4E3
|
/Assignment_Submission/minhdn/Session 4 - Assignment 3/3.1.2. Circle in circle.py
| 112 | 3.59375 | 4 |
from turtle import *
color('green')
i = 0
r = 10
while i < 10:
circle(r)
i = i + 1
r = r + 10
|
7f4ef7d2fa5dd2f331b88f3b604cc19cbfac3389
|
mshibatatt/wcbc_problems
|
/problemsets/chapter11/fird.py
| 439 | 3.625 | 4 |
from utils import WcbcException
def fird(inString):
split = inString.split()
if len(split) != 3:
raise WcbcException("input must be composed of 3 numbers")
M, a, b = int(split[0]), int(split[1]), int(split[2])
if a > b:
raise WcbcException("a must be equal to or smaller than b")
for i in range(max(a, 2), min(b + 1, M)):
if M % i == 0:
return "yes"
return "no"
|
d6f9870c10af1020405d3815d3198062f44cd0db
|
KvinLiu/Udacity
|
/ITCS/Lesson_2/Median.py
| 283 | 3.703125 | 4 |
def bigger(a,b):
result = a
if b > a:
result = b
return result
def biggerst(a,b,c):
return bigger(bigger(a,b),c)
def median(a,b,c):
if a == biggerst(a,b,c):
return bigger(b,c)
if b == biggerst(a,b,c):
return bigger(a,c)
if c == biggerst(a,b,c):
return bigger(a,b)
|
1f2ee8d45634fdcd402042ab92066db0bbe60dd2
|
benfetch/Project-Euler-Python
|
/problem17.py
| 1,804 | 3.75 | 4 |
def spell_number(n):
word = ''
dict_words = {'1': 'one', '2': 'two', '3': 'three', '4': 'four', '5':'five', '6': 'six', '7':'seven', '8': 'eight', '9':'nine'}
dict_teens = {'11': 'eleven', '12': 'twelve', '13': 'thirteen', '14': 'fourteen', '15': 'fifteen', '16': 'sixteen', '17': 'seventeen', '18': 'eighteen', '19': 'nineteen'}
dict_tens = {'2': 'twenty', '3': 'thirty', '4': 'forty', '5': 'fifty', '6': 'sixty', '7': 'seventy', '8': 'eighty', '9': 'ninety'}
x = str(n)
if len(x) == 4:
word = dict_words[x[0]] + 'thousand'
return 'onethousand'
if len(x) >= 3:
word += dict_words[x[-3]] + 'hundred'
if len(x) == 1:
return dict_words[x]
elif len(x) == 2:
if x[-2:] == '00':
return word
elif x[-2:] == '10':
word += 'ten'
return word
elif x[-2] == '1':
word += '' + dict_teens[x[-2:]]
return word
elif x[-2] == '0':
word += '' + dict_words[x[-1]]
return word
elif x[-1] == '0':
word += '' + dict_tens[x[-2]]
return word
else:
word += '' + dict_tens[x[-2]] + dict_words[x[-1]]
return word
if x[-2:] == '00':
return word
elif x[-2:] == '10':
word += 'andten'
return word
elif x[-2] == '1':
word += 'and' + dict_teens[x[-2:]]
return word
elif x[-2] == '0':
word += 'and' + dict_words[x[-1]]
return word
elif x[-1] == '0':
word += 'and' + dict_tens[x[-2]]
return word
else:
word += 'and' + dict_tens[x[-2]] + dict_words[x[-1]]
return word
sum = 0
for i in range(1, 1001):
print(i, spell_number(i))
sum += len(spell_number(i))
print(sum)
|
0ada1809658e1113b361146cb2cfb2988342f9d1
|
xxcocoymlxx/Study-Notes
|
/CSC148/06 Tree(BST)/more tree practice.py
| 2,617 | 3.921875 | 4 |
#没壳的
class BTNode():
def __init__(self, data, left=None, right=None):
self.data, self.left, self.right = data, left, right
def longest_path(self):
""" BTNode -> list of BTNode"""
## 这是下面已经包含了的base case
## if self.left == self.right == None:
## return [self]
if self.left:
l = self.left.longest_path()
else:
l = [] #base case
if self.right:
r = self.right.longest_path()
else:
r = [] #base case
if len(l) > len(r):
l.append(self)#记得要添加上自己!
return l
else:
r.append(self)
return r
def all_longest_paths(self):
""" BTNode -> list of list of BTNode
如果有好几个相同长度的longest path,return a list of list of the paths"""
if self.left:
l = self.left.all_longest_paths()
else:
l = []
if self.right:
r = self.right.all_longest_paths()#此时已经是一个大list里面含有很多个longest path
else:
r = []
#只想当前一层的情况,现在l和r都是已经包含了所有longest paths的list了
if l == []:
longest = r
elif r == []:
longest = l
elif len(l[0]) > len(r[0]):#既然都是longest path那长度应该都是一样的,比较第一个path的长度就好
longest = l
elif len(l[0]) < len(r[0]):
longest = r
else:#l和r里的longest path长度相等
longest = l + r
if longest == []:
return [[self]]#左支右支都没有path,tree里只有他一个
for a_path in longest:#大list里的每一个小path
a_path.append(self)#最后都要加回他自己
return longest
def shortest_path(self):#pretty much the same as the longest one
pass
def all_data_in_level(self, level):
""" (BTNode, int) -> list of BTNode
"""
if level == 0:
return [self]
if self.left:
l = self.left.all_data_in_level(level-1)#除去了root就低了一级level
else:
l = []
if self.right:
r = self.right.all_data_in_level(level-1)
else:
r = []
return l + r
t = BTNode(1,BTNode(2,BTNode(4,BTNode(8),BTNode(9)),BTNode(5,None,BTNode(10))),BTNode(3,BTNode(6),BTNode(7)))
|
de6c43ab4974ced18cb43983528b39c140c491e0
|
Ernest-Sharp/Programming_for_Informatics
|
/Curso_1-4/05week_01.py
| 813 | 4.40625 | 4 |
# 3.1 Write a program to prompt the user for
# hours and rate per hour using raw_input to
# compute gross pay. Pay the hourly rate for
# the hours up to 40 and 1.5 times the hourly
# rate for all hours worked above 40 hours.
# Use 45 hours and a rate of 10.50 per hour
# to test the program (the pay should be 498.75).
# You should use raw_input to read a string and
# float() to convert the string to a number.
# Do not worry about error checking the user
# input - assume the user types numbers properly.
# Desired Output 498.75
# Ask hours and rate
a = raw_input("Number of hours? ")
b = raw_input("Rate? ")
# Convert to float
hours = float(a)
rate = float(b)
# Check if hours > 40 and do the math
if hours > 40:
pay = (40 * rate) + ((hours - 40) * (1.5 * rate))
else:
pay = hours * rate
print pay
|
fb13f8e1038f223d98292846a36846fa93d776e8
|
JATP98/ejercicio_json
|
/ejer5.py
| 420 | 3.515625 | 4 |
#5. Pedir un id pelicula y contar
# cuantos generos tiene.
import json
from pprint import pprint
idd=input("Dime un id: ")
contador=0
with open('peliculas.json') as data_file:
data = json.load(data_file)
for pelicula in data:
if (pelicula["id"]) == idd:
#for genero in pelicula["genres"]:
# contador=contador+1
#print(contador)
print("La pelicula con id", idd, "tiene", len(pelicula["genres"]), "género/s")
|
80259cd8abb51eb33e42c7e0385210b27e35db9c
|
khanabdul16/Full-Python-Course
|
/3. if statements, Loops, Break,Pass,Continue, Prime no.py
| 839 | 4 | 4 |
###### If Statement ######
x=2
y=3
if x<y:
print("greater")
elif x==y:
print("equal")
else:
print("lesser")
print()
###### While Loop ######
x=1
while x<=5:
print(x,end=" ")
x+=1
print()
###### For Loop ######
x=[1,3,34,4,5]
for i in x:
print(i,end=" ")
print()
for i in range(2,10,3): #startpoint, endpoint, difference
print(i,end=" ")
print()
###### Break,Pass, Continue ######
x=6
for i in range(0,x,1):
if i>4:
break
print(i,end="")
print()
for i in range(0, x, 1):
pass
print()
for i in range(0, x, 1):
if i %2== 1:
continue
print(i,end="")
print()
###### Prime Or Not ######
num=9
for i in range(2,num):
if num%i==0:
print("not prime and divisible by ",i)
break
else:
print("prime")
|
32ec25d18eb77688e3c4f4502a479d008f6696b3
|
5oma/acpythonscripts
|
/GUI/hwsophi.py
| 290 | 3.921875 | 4 |
from tkinter import *
import math
root = Tk() # root (main) window
top = Frame(root) # create frame
top.pack(side='top') # pack frame in main window
hwtext = Label(top, text='Hola, Ariel! Me llamo 50πΔ. Vamos a crear un jardín de formas.')
hwtext.pack(side='left')
root.mainloop()
|
2dd350d39109137a8dbb80f2812721d6f4047b03
|
philgineer/Python_projects
|
/Deeplearning_math/Chapter01/python_class2.py
| 498 | 3.6875 | 4 |
class node:
node_cnt = 0 # class variable
def __init__(self, x, y):
self.x, self.y = x, y
self.add = None
self.adder()
node.node_cnt += 1
def adder(self):
self.add = self.x + self.y
node1 = node(10, 20)
print("x: ", node1.x, "\ny: ", node1.y, "\nadd: ", node1.add, "\ncnt: ", node1.node_cnt)
node2 = node(100, 200)
print("\nx: ", node2.x, "\ny: ", node2.y, "\nadd: ", node2.add, "\ncnt: ", node2.node_cnt)
|
d043ff9deea7e05d38c32fb1b2664121f34fc9fc
|
gary391/CWH-PythonBeginner
|
/oopstut2.py
| 853 | 4.28125 | 4 |
# First class
# How to make your own class
# How to make your own object from this class
# What is init method
class Person:
# This constructor method is called each time we make an object of the class
# There we are defining the attribute for our object
# self key word is convention, but you can write your own variable, in that case we will have replace self everywhere
def __init__(self, first_name, last_name, roll_number):
# instance variable
print("Constructor get called!")
self.fname = first_name # fname is the instance variable
self.lname = last_name # lname is the instance variable
self.rollnumber = roll_number
p1 = Person("harry", "jackson", 45000)
p2 = Person("Sumit", "Arora", 55000)
p3 = Person("Amit", "Arora",65000)
print(p3.fname)
# print(p2.lname)
# print(p2.rollnumber)
|
66475394f2ec10a0ffc7fcd1c75322d452a6cdb0
|
Lominelo/infa_2021_Litovchenko
|
/lab_2/упр 8.py
| 127 | 3.78125 | 4 |
import turtle
import math
turtle.shape('turtle')
for i in range (0,1000):
turtle.forward(i*10)
turtle.left(90)
|
865dfc7305a55d66dbcdbcadc1c3c2d18b72ec96
|
mishrasunny174/DataStructuresAndAlgorithms
|
/python/DataStructures/LinkedList/LinkedList.py
| 1,194 | 4.03125 | 4 |
from Node import Node
class LinkedList(object):
def __init__(self):
self.head = None
self.size = 0
# O(1) complexity
def insertBegin(self, data):
if self.head is None:
self.head = Node(data=data)
else:
self.head = Node(data=data, nextNode=self.head)
self.size += 1
# O(n) complexity
def insertEnd(self, data):
if self.head is None:
self.head = Node(data=data)
else:
tempNode = self.head
while tempNode.nextNode is not None:
tempNode = tempNode.nextNode
tempNode.nextNode = Node(data=data)
self.size += 1
# O(n) complexity
def remove(self, data):
if self.head:
if self.head.data == data:
self.head = self.head.nextNode
else:
self.head.nextNode.remove(data, previous_node=self.head)
self.size -= 1
# O(n) complexity
def traverse(self):
tempNode = self.head
while tempNode is not None:
yield tempNode.data
tempNode = tempNode.nextNode
|
28d50188fdd027f54728ce5bd2e5e2a6382d4b2b
|
stoic-plus/codewars_kata
|
/python/descendingOrder.py
| 632 | 4.21875 | 4 |
# Your task is to make a function that can take any non-negative integer as a argument and return it with its digits in descending order. Essentially, rearrange the digits to create the highest possible number.
#
# Examples:
# Input: 21445 Output: 54421
#
# Input: 145263 Output: 654321
#
# Input: 1254859723 Output: 9875543221
def Descending_Order(num):
if len(str(num)) == 1: return num
reversed = sorted(list(str(num)), reverse=True)
return int("".join(reversed), 10)
# test.assert_equals(Descending_Order(0), 0)
# test.assert_equals(Descending_Order(15), 51)
# test.assert_equals(Descending_Order(123456789), 987654321)
|
11b21a9139f6ecc597e0096e560d93abf1be5c9e
|
Zekess/Asignacion_de_Turnos_webapp
|
/Solver_codigos/get_instancias.py
| 12,655 | 3.59375 | 4 |
import pandas as pd
import streamlit as st
import base64
# descarga de archivos
def xldownload(excel, name):
data = open(excel, 'rb').read()
b64 = base64.b64encode(data).decode('UTF-8')
href = f'<a href="data:file/xls;base64,{b64}" download={name}>Download {name}</a>'
return href
def get_col_widths(dataframe):
# First we find the maximum length of the index column
idx_max = max([len(str(s)) for s in dataframe.index.values] + [len(str(dataframe.index.name))])
# Then, we concatenate this to the max of the lengths of column name and its values for each column, left to right
return [idx_max] + [max([len(str(s)) for s in dataframe[col].values] + [len(col)]) for col in dataframe.columns]
def CrearInstancias(xls):
#st.write('Comenzando función: ')
df = pd.read_excel(xls, 'Dotaciones').dropna()
df2 = pd.read_excel(xls, 'Parametros',index_col=0)
df3 = pd.read_excel(xls, 'Feriados').dropna()
puestos = df.index
dia_inicial = df2.loc['FECHA INICIO','VALOR'].date() #strftime("%Y-%m-%d")
dia_final = df2.loc['FECHA TERMINO','VALOR'].date() #strftime("%Y-%m-%d")
dotacion_externa = 4
duracion_turno = dict()
horas_semanales_contrato = int(df2.loc['MAXIMO HORAS POR SEMANA','VALOR'])
UTM = float(df2.loc['UTM','VALOR'])
falta_de_trabajadores = int(df2.loc['FALTA DE TRABAJADORES','VALOR'])
exceso_de_trabajadores = int(df2.loc['EXCESO DE TRABAJADORES','VALOR'])
descanso = float(df2.loc['DESCANSO','VALOR'])
mantener_el_mismo_turno = float(df2.loc['MANTENER EL MISMO TURNO','VALOR'])
maximo_de_minutos_trabajados = float(df2.loc['MAXIMO DE MINUTOS TRABAJADOS','VALOR'])
maximo_de_turnos_seguidos = float(df2.loc['MAXIMO DE DIAS SEGUIDOS','VALOR'])
maximo_horas_extra = int(df2.loc['MAXIMO HORAS EXTRA POR SEMANA','VALOR'])
# if sys.platform == 'linux':
# this_folder = os.popen("pwd").read()[:-1]
# elif platform.system() == 'Windows':
# this_folder = os.popen("echo %cd%").read()[:-1]
#
#
# try:
# os.mkdir('Instancias')
# except FileExistsError:
# pass ## qué hacer en caso de que exista
# out_folder = os.path.join(this_folder,'Instancias')
horas_requeridas = dict()
dias_requeridos = dict()
nro_a_mes = {1:'Enero',2:'Febrero',3:'Marzo',4:'Abril',5:'Mayo',6:'Junio',7:'Julio',
8:'Agosto',9:'Septiembre',10:'Octubre',11:'Noviembre',12:'Diciembre'}
# mes_a_nro = {'Enero':1,'Febrero':2,'Marzo':3,'Abril':4,'Mayo':5,'Junio':6,'Julio':7,
# 'Agosto':8,'Septiembre':9,'Octubre':10,'Noviembre':11,'Diciembre':12}
dict_de_excels = {}
total = len(puestos)*2
contador_avance = 0
with st.spinner('Cargando cargos y turnos...'):
barra_progreso_crearinstancias = st.progress(0)
for turno_corto in [True, False]:
if turno_corto:
tipo_turno = '_turno_corto'
else:
tipo_turno = '_turno_largo'
for index in puestos:
horas_requeridas[index] = dict()
dias_requeridos[index] = dict()
for i in range(12):
horas_requeridas[index][i+1], dias_requeridos[index][i+1] = map(int,df[nro_a_mes[i+1]].loc[index].split("/"))
if horas_requeridas[index][i+1] == 24:
if not turno_corto:
duracion_turno[i+1] = 12
else:
duracion_turno[i+1] = 8
elif horas_requeridas[index][i+1] == 16:
duracion_turno[i+1] = 8
elif horas_requeridas[index][i+1] == 12:
if not turno_corto:
duracion_turno[i+1] = 12
else:
duracion_turno[i+1] = 6
else:
duracion_turno[i+1] = horas_requeridas[index][i+1]
#Instancia Parametros
for index in puestos:
df_param = pd.DataFrame(columns=['PARAMETROS','VALOR', 'UNIDAD'])
dotacion = int(df['Dotacion'].loc[index])
dotacion_turno = int(df['Dotacion turno'].loc[index])
nombre_instancia = '_'.join(df['Cargo'].loc[index].split())+'_contratados_'+str(dotacion)+tipo_turno+'.xlsx'
df_param = df_param.append({'PARAMETROS':'FECHA INICIO', 'VALOR':dia_inicial, 'UNIDAD':''}, ignore_index=True) #1r lunes del mes
df_param = df_param.append({'PARAMETROS':'FECHA TERMINO', 'VALOR':dia_final, 'UNIDAD':''}, ignore_index=True)
df_param = df_param.append({'PARAMETROS':'MAXIMO HORAS POR SEMANA', 'VALOR':horas_semanales_contrato, 'UNIDAD':'HORAS'}, ignore_index=True)
df_param = df_param.append({'PARAMETROS':'MAXIMO HORAS EXTRA POR SEMANA', 'VALOR':maximo_horas_extra, 'UNIDAD':'HORAS'}, ignore_index=True)
df_param = df_param.append({'PARAMETROS':'TRABAJADORES CONTRATADOS EN EL PUESTO', 'VALOR':dotacion, 'UNIDAD':'PERSONAS'}, ignore_index=True)
df_param = df_param.append({'PARAMETROS':'TRABAJADORES EXTERNOS DISPONIBLES', 'VALOR':dotacion_externa, 'UNIDAD':'PERSONAS'}, ignore_index=True)
df_param = df_param.append({'PARAMETROS':'TRABAJADORES NECESARIOS EN EL PUESTO', 'VALOR':dotacion_turno, 'UNIDAD':'PERSONAS'}, ignore_index=True)
#Costos
factor = 1
costo_por_hora_contratado = factor*float(df['Sueldo Mes'].loc[index])/(4*horas_semanales_contrato*UTM)
costo_trabajador_externo = costo_por_hora_contratado * 1.5
costo_extra_50 = factor*float(df['HE al 50%'].loc[index])/UTM
costo_extra_100 = factor*float(df['HE al 100%'].loc[index])/UTM
costo_extra_200 = factor*float(df['HE al 200%*'].loc[index])/UTM
costo_extra_externo = costo_trabajador_externo * 1.5
df_costos = pd.DataFrame(columns=['PESO','VALOR','UNIDAD'])
df_costos = df_costos.append({'PESO':'FALTA DE TRABAJADORES', 'VALOR':falta_de_trabajadores,'UNIDAD':'UTM POR TRABAJADOR (RECOMENDADO 10 VECES EL MAXIMO DE LOS DEMAS)'}, ignore_index=True)
df_costos = df_costos.append({'PESO':'EXCESO DE TRABAJADORES', 'VALOR':exceso_de_trabajadores,'UNIDAD':'UTM POR TRABAJADOR (FICTICIO)'}, ignore_index=True)
df_costos = df_costos.append({'PESO':'DESCANSO', 'VALOR':descanso,'UNIDAD':'UTM POR DIA NO RESPETADO'}, ignore_index=True)
df_costos = df_costos.append({'PESO':'MANTENER EL MISMO TURNO', 'VALOR':mantener_el_mismo_turno,'UNIDAD':'UTM POR SEMANA NO RESPETADA'}, ignore_index=True)
df_costos = df_costos.append({'PESO':'MAXIMO DE MINUTOS TRABAJADOS', 'VALOR':maximo_de_minutos_trabajados,'UNIDAD':'UTM POR SEMANA NO RESPETADA'}, ignore_index=True)
df_costos = df_costos.append({'PESO':'MAXIMO DE DIAS SEGUIDOS', 'VALOR':maximo_de_turnos_seguidos,'UNIDAD':'UTM POR SEMANA NO RESPETADA'}, ignore_index=True)
df_costos = df_costos.append({'PESO':'COSTO TRABAJADOR CONTRATADO', 'VALOR':costo_por_hora_contratado,'UNIDAD':'UTM POR HORA (SALARIO MENSUAL EN UTM/180)'}, ignore_index=True)
df_costos = df_costos.append({'PESO':'COSTO TRABAJADOR EXTERNO', 'VALOR':costo_trabajador_externo,'UNIDAD':'UTM POR HORA'}, ignore_index=True)
df_costos = df_costos.append({'PESO':'COSTO HORA EXTRA 50%', 'VALOR':costo_extra_50,'UNIDAD':'UTM POR HORA'}, ignore_index=True)
df_costos = df_costos.append({'PESO':'COSTO HORA EXTRA 100%', 'VALOR':costo_extra_100,'UNIDAD':'UTM POR HORA'}, ignore_index=True)
df_costos = df_costos.append({'PESO':'COSTO HORA EXTRA 200%', 'VALOR':costo_extra_200,'UNIDAD':'UTM POR HORA'}, ignore_index=True)
df_costos = df_costos.append({'PESO':'COSTO HORA DOMINGO EXTERNO', 'VALOR':costo_extra_externo,'UNIDAD':'UTM POR HORA'}, ignore_index=True)
df_req = pd.DataFrame(columns=['MES','HORAS/DIAS','DURACION TURNO (HORAS)'])
df_req = df_req.append({'MES':'Enero','HORAS/DIAS':str(horas_requeridas[index][1])+'/'+str(dias_requeridos[index][1]),'DURACION TURNO (HORAS)':duracion_turno[1]},ignore_index=True)
df_req = df_req.append({'MES':'Febrero','HORAS/DIAS':str(horas_requeridas[index][2])+'/'+str(dias_requeridos[index][2]),'DURACION TURNO (HORAS)':duracion_turno[2]},ignore_index=True)
df_req = df_req.append({'MES':'Marzo','HORAS/DIAS':str(horas_requeridas[index][3])+'/'+str(dias_requeridos[index][3]),'DURACION TURNO (HORAS)':duracion_turno[3]},ignore_index=True)
df_req = df_req.append({'MES':'Abril','HORAS/DIAS':str(horas_requeridas[index][4])+'/'+str(dias_requeridos[index][4]),'DURACION TURNO (HORAS)':duracion_turno[4]},ignore_index=True)
df_req = df_req.append({'MES':'Mayo','HORAS/DIAS':str(horas_requeridas[index][5])+'/'+str(dias_requeridos[index][5]),'DURACION TURNO (HORAS)':duracion_turno[5]},ignore_index=True)
df_req = df_req.append({'MES':'Junio','HORAS/DIAS':str(horas_requeridas[index][6])+'/'+str(dias_requeridos[index][6]),'DURACION TURNO (HORAS)':duracion_turno[6]},ignore_index=True)
df_req = df_req.append({'MES':'Julio','HORAS/DIAS':str(horas_requeridas[index][7])+'/'+str(dias_requeridos[index][7]),'DURACION TURNO (HORAS)':duracion_turno[7]},ignore_index=True)
df_req = df_req.append({'MES':'Agosto','HORAS/DIAS':str(horas_requeridas[index][8])+'/'+str(dias_requeridos[index][8]),'DURACION TURNO (HORAS)':duracion_turno[8]},ignore_index=True)
df_req = df_req.append({'MES':'Septiembre','HORAS/DIAS':str(horas_requeridas[index][9])+'/'+str(dias_requeridos[index][9]),'DURACION TURNO (HORAS)':duracion_turno[9]},ignore_index=True)
df_req = df_req.append({'MES':'Octubre','HORAS/DIAS':str(horas_requeridas[index][10])+'/'+str(dias_requeridos[index][10]),'DURACION TURNO (HORAS)':duracion_turno[10]},ignore_index=True)
df_req = df_req.append({'MES':'Noviembre','HORAS/DIAS':str(horas_requeridas[index][11])+'/'+str(dias_requeridos[index][11]),'DURACION TURNO (HORAS)':duracion_turno[11]},ignore_index=True)
df_req = df_req.append({'MES':'Diciembre','HORAS/DIAS':str(horas_requeridas[index][12])+'/'+str(dias_requeridos[index][12]),'DURACION TURNO (HORAS)':duracion_turno[12]},ignore_index=True)
# path_instancia = os.path.join(out_folder,nombre_instancia)
with pd.ExcelWriter(f'Instancias/{nombre_instancia}', datetime_format='yyyy-mm-dd', engine='xlsxwriter') as writer:
df_param.to_excel(writer, sheet_name='Parametros', index=False)
df_costos.to_excel(writer, sheet_name='Costos', index=False)
df_req.to_excel(writer, sheet_name='Requerimientos', index=False)
df3.to_excel(writer, sheet_name='Feriados', index=False)
for i, width in enumerate(get_col_widths(df_param)):
j = max(0,i-1)
writer.sheets['Parametros'].set_column(j, j, width+2)
for i, width in enumerate(get_col_widths(df_costos)):
j = max(0,i-1)
writer.sheets['Costos'].set_column(j, j, width+2)
for i, width in enumerate(get_col_widths(df_req)):
j = max(0,i-1)
writer.sheets['Requerimientos'].set_column(j, j, width+2)
for i, width in enumerate(get_col_widths(df3)):
j = max(0,i-1)
writer.sheets['Feriados'].set_column(j, j, width+2)
#print(df_param)
#print(df_costos)
#print(nombre_instancia)
contador_avance += 1
barra_progreso_crearinstancias.progress(contador_avance/total)
#dict_de_excels = dict(dict_de_excels, **{nombre_instancia:xldownload(writer, nombre_instancia)}) # ([xldownload(writer, nombre_instancia), nombre_instancia])
dict_de_excels = dict(dict_de_excels, **{nombre_instancia: writer}) # ([xldownload(writer, nombre_instancia), nombre_instancia])
barra_progreso_crearinstancias.empty()
return dict_de_excels
|
98f94d5512b3fd153ea489a796ccd4a87ca30bd9
|
rundong-zhou/PHY407-Projects
|
/Lab4/Lab04-407-2020-sol/L04-407-2020-Q3c.py
| 2,236 | 3.796875 | 4 |
# Author: Nico Grisouard, University of Toronto Physics
# Answer to questions related to finding roots and extrema
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
import scipy.constants as pc # physical constants
def f(x): return 5*(np.exp(-x) - 1.) + x
def df(x): return 1 - 5*np.exp(-x)
font = {'family': 'normal', 'size': 14} # font size
rc('font', **font)
# Q3c ------------------------------------------------------------------------|
epsilon = 1e-6 # accuracy tolerance
# Binary search --------------------------------------------------------------|
x1 = 0.1 # lower bracket
x2 = 10. # upper bracket
if f(x1)*f(x2) > 0.: # I will assume we will never find the root right away
raise NameError('Fct at brackets is of the same sign. Change brackets.')
i = 0 # iterations counter
while abs(x2-x1) > epsilon:
i += 1
xm = .5*(x1 + x2)
if f(xm)*f(x1) > 0.: # then the middle point is on same side as x1
x1 = xm # bring it closer to that side
else:
x2 = xm
print("Binary search: x = {0:.6f}, converged in {1} iterations"
.format(0.5*(x1+x2), i))
# Newton's method ------------------------------------------------------------|
x1 = 1. # is whatever at this point, just not too close to the guess
x2 = 10. # initial guess
i = 0 # iterations counter
while abs(x2 - x1) > epsilon:
i += 1
x1 = x2
x2 = x1 - f(x1)/df(x1)
print("Newton's method: x = {0:.6f}, converged in {1} iterations".format(
x2, i))
# Secant method --------------------------------------------------------------|
x1 = 0.1 # lower bracket
x2 = 10. # upper bracket
x3 = x2 - f(x2)*(x2-x1)/(f(x2) - f(x1)) # first iteration
i = 1 # iterations counter; I start at 1 because we've done it once before
while abs(x3 - x2) > epsilon:
i += 1
x1 = x2
x2 = x3
x3 = x2 - f(x2)*(x2-x1)/(f(x2) - f(x1))
print("Secant method: x = {0:.6f}, converged in {1} iterations".format(
x2, i))
# Temperature of the Sun -----------------------------------------------------|
b = pc.Planck * pc.c / (pc.Boltzmann * x3)
lmbda = 502e-9 # [m] peak wavelength of Sun's spectrum
print("")
print("In any case, the temperature of the Sun is {0:.6e} K".format(b/lmbda))
|
bafee89a6ac13c21997e7054175e2a4ee2afaa93
|
Mike-droid/ejercicios-python-youtube
|
/Diccionarios/ejercicio4.py
| 458 | 4.09375 | 4 |
meses = {
'1' : 'Enero',
'2' : 'Febrero',
'3' : 'Marzo',
'4' : 'Abril',
'5' : 'Mayo',
'6' : 'Junio',
'7' : 'Julio',
'8' : 'Agosto',
'9' : 'Septiembre',
'10' : 'Octubre',
'11' : 'Noviembre',
'12' : 'Diciembre'
}
fecha = input("Escribe una fecha en formato dd/mmm/aaaa : ")
#* 22/10/2021
fecha = fecha.split("/") #! fecha[dd][mmm][aaaa]
#! fecha[0][1][2]
print(f"{fecha[0]} / {meses[fecha[1]]} / {fecha[2]}")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.