blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
14b2dc30e84b1e23c9d4f70f4be50c093d8a4a03
|
dizidoro/pep8-conformant-util
|
/remove_bad_spaces.py
| 1,461 | 3.890625 | 4 |
#!/usr/bin/env python
"""A script to remove spaces before new lines in files as pep8 warns"""
import sys
import os
import re
__author__ = "Diego Izidoro"
def usage(argv):
"""Checks if script call usage was correct"""
assert argv.__class__ == list
if len(argv) < 2:
sys.exit('Usage: %s text_file_name' % argv[0])
for file_path in argv[1:]:
if not os.path.exists(file_path):
sys.exit('ERROR: file %s was not found!' % argv[1])
def read_file(file_path):
"""reads the file
Args:
file_name: name of the file
Returns: string
string of the file
"""
fin = open(file_path)
string = fin.read()
fin.close()
return string
def overwrite_file(file_path, string):
"""overwrites the file
Args:
file_name: name of the file
string: string to be written in the file
Returns: None
"""
fout = open(file_path, 'w')
fout.write(string)
fout.close()
def correct_files(files_paths):
"""removes spaces before new lines
Args:
files_paths: paths to the files to be corrected
Returns: None
"""
for file_path in files_paths:
string = read_file(file_path)
corrected_string = re.sub(r" +\n", "\n", string)
overwrite_file(file_path, corrected_string)
def main(argv):
"""main"""
usage(argv)
files_paths = argv[1:]
correct_files(files_paths)
if __name__ == "__main__":
main(sys.argv)
|
e614c9e46531ec79bfcdb39eaf925db54f5a203b
|
cartido/conversion_web
|
/conversion/util.py
| 1,097 | 3.71875 | 4 |
class SourceIterator(object):
"""Iterator to facilitate reading the definition files.
Accepts any sequence (like a list of lines, a file or another SourceIterator)
The iterator yields the line number and line (skipping comments and empty lines)
and stripping white spaces.
for lineno, line in SourceIterator(sequence):
# do something here
"""
def __new__(cls, sequence):
if isinstance(sequence, SourceIterator):
return sequence
obj = object.__new__(cls)
if sequence is not None:
obj.internal = enumerate(sequence, 1)
obj.last = (None, None)
return obj
def __iter__(self):
return self
def __next__(self):
line = ''
while not line or line.startswith('#'):
lineno, line = next(self.internal)
line = line.split('#', 1)[0].strip()
self.last = lineno, line
return lineno, line
next = __next__
def block_iter(self):
"""Iterate block including header.
"""
return BlockIterator(self)
|
cd3fd69ab3637a005b7121e9d6aa879b31af8feb
|
itsdivik/Money-Manager
|
/moneymanager.py
| 4,695 | 3.859375 | 4 |
class MoneyManager():
def __init__(self):
'''Constructor to set username to '', pin_number to an empty string,
balance to 0.0, and transaction_list to an empty list.'''
self.u_num = ''
self.pin_number = ''
self.balance = ''
self.i_rate = ''
self.transaction_list = []
self.amt = 0.0
self.type = ''
def user_details(self, unum, pinnum, bal, irate, transaction):
'''Function to get the details about the user such as account_number, pin_number, balance, transaction_list'''
self.u_num = unum
self.pin_number = pinnum
self.balance = bal
self.i_rate = irate
self.transaction_list = transaction
def add_entry(self, amount, entry_type):
'''Function to add and entry an amount to the tool. Raises an
exception if it receives a value for amount that cannot be cast to float. Raises an exception
if the entry_type is not valid - i.e. not food, rent, bills, entertainment or other'''
try:
float(amount)
self.type = entry_type
# if the value is successfully casted to float then passing it to the respective functions
if self.type == "Deposit":
self.deposit_funds(amount)
elif self.type == "Withdraw":
self.withdraw_funds(amount)
except ValueError as e:
raise e
def deposit_funds(self, amount):
'''Function to deposit an amount to the user balance. Raises an
exception if it receives a value that cannot be cast to float. '''
# casting self.balance type <class 'str'> to <class 'float'> to add the amount retrieved into the balance
bal = float(self.balance)
try:
self.amt = float(amount)
bal += self.amt
# casting bal type <class 'float'> to <class 'str'> to save it to the account file
self.balance = str(bal)
except ValueError as e:
raise e
def withdraw_funds(self, amount):
'''Function to withdraw an amount to the user balance. Raises an
exception if it receives a value that cannot be cast to float. '''
# casting self.balance type <class 'str'> to <class 'float'> to add the amount retrieved into the balance
bal = float(self.balance)
try:
self.amt = float(amount)
if amount <= bal:
bal -= self.amt
else:
raise ValueError("Overdraft!!!")
# casting bal type <class 'float'> to <class 'str'> to save it to the account file
self.balance = str(bal)
except ValueError as e:
raise e
def get_transaction_string(self):
'''Function to create and return a string of the transaction list. Each transaction
consists of two lines - either the word "Deposit" or the entry type - food etc - on
the first line, and then the amount deposited or entry amount on the next line.'''
# casting self.amt type <class 'float'> to <class 'str'> for appending in the transaction_list
self.amt = str(self.amt)
# Appending the tuple to the transaction_list
self.transaction_list.append((self.type, self.amt))
return self.transaction_list
def save_to_file(self):
'''Function to overwrite the user text file with the current user
details. user number, pin number, and balance (in that
precise order) are the first four lines - there are then two lines
per transaction as outlined in the above 'get_transaction_string'
function.'''
# Creating the file name with .txt extension with the current users account_id
file = self.u_num + ".txt"
# Trying to open the file and raising an exception if it's not found
try:
with open(file, "w") as user_file:
# Writing the Object's data to the File in the exact Order
# Writing the account_id
user_file.write(self.u_num + "\n")
# Writing the pin_number
user_file.write(self.pin_number + "\n")
# Writing the current balance
user_file.write(self.balance + "\n")
# Writing the interest_rate
user_file.write(self.i_rate + "\n")
# Writing the Updated transaction history into the File
for t_type, amt in self.transaction_list:
user_file.write(t_type + "\n" + amt + "\n")
except IOError as e:
raise e
|
2c783cdc9fe10a12c9ef7f3a5a84241bdf2e2ce9
|
aa2841916/python-study
|
/first/8.1-15.py
| 2,232 | 3.84375 | 4 |
# class apple:
# def __init__(self,w,c,h,l):
# self.weight = w
# self.color = c
# self.high = h
# self.long = l
# print('cread')
#
# app1 = apple(10,'red','12cm','5cm')
# print(app1)
# import math
#
# class circle:
# def __init__(self,r):
# self.radius = r
#
# def area(self):
# return math.pi * self.radius ** 2
#
#
# cir1 = circle(3)
# print(cir1.area())
#
#
# class Triangle:
# def __init__(self,l,h):
# self.high = h
# self.long = l
#
# def area(self):
# return self.high * self.long
#
# def change_size(self,l,h):
# self.high = h
# self.long = l
#
#
# Tri = Triangle(10,20)
# Tri.change_size(20,30)
# area1 = Tri.area()
#
# print(area1)
#
#
# class Hexagon:
# def __init__(self,r):
# self.radiox = r
#
# def cacculate_perimeter(self):
# return self.radiox * 6
#
# hex = Hexagon(10)
# long = hex.cacculate_perimeter()
# print(long)
# class Shape:
# def what_am_i(self):
# print('I am s shape')
#
# class Rectangle(Shape):
# def __init__(self,l,h):
# self.long = l
# self.hight = h
#
# def calculate_perimeter(self):
# return 2 * self.long + 2 * self.hight
#
# class Square(Rectangle):
# def change_size(self,s):
# st = self.long + s
# sy = self.hight + s
# return st,sy
#
#
# Rectangle(10, 3).what_am_i()
# print(Square(10,3).change_size(3))
# Square(10,3).what_am_i()
# class Horse():
# def __init__(self,name,breed,owner):
# self.name = name
# self.breed = breed
# self.owner = owner
#
# class Rider():
# def __init__(self,name):
# self.name = name
#
# mick = Rider('hudi')
# stan = Horse('yao','ming',mick)
# ddd = stan.owner.name
#
# print(ddd)
# class Square:
# list = []
#
# def __init__(self,c,d):
# self.css = c
# self.ddd = d
# self.list.append((self.css,self.ddd))
#
# def print_size(self):
# print("{} by {} by {} by {}".format(self.css,self.ddd,self.css,self.ddd))
#
# cd = Square(10,12)
# dddd = Square(22,22)
#
# print(Square.list)
# Square(29,28).print_size()
# def f(x,y):
# print(x is y)
#
# f(2,2)
|
a8b5b68e372d29d174e0175dfebce29e1b957c51
|
andregutierrez3/calc
|
/calc.py
| 375 | 3.546875 | 4 |
class Calc:
def __init__(self, a=0, b=0):
self.X = a
self.Y = b
return
def soma(self):
r = self.X + self.Y
return r
def sub(self):
r = self.X - self.Y
return r
def multiplicacao(self):
r = self.X * self.Y
return r
def divisao(self):
r = self.X / self.Y
return r
|
e98da80b811178884c8eeb46d415c33ff6d1e7af
|
Aasthaengg/IBMdataset
|
/Python_codes/p02993/s800339520.py
| 443 | 3.734375 | 4 |
a = input()
if a.count("00") > 0:
print("Bad")
elif a.count("11") > 0:
print("Bad")
elif a.count("22") > 0:
print("Bad")
elif a.count("33") > 0:
print("Bad")
elif a.count("44") > 0:
print("Bad")
elif a.count("55") > 0:
print("Bad")
elif a.count("66") > 0:
print("Bad")
elif a.count("77") > 0:
print("Bad")
elif a.count("88") > 0:
print("Bad")
elif a.count("99") > 0:
print("Bad")
else:
print("Good")
|
cd3240400abd6d783a7377121c5cd74b178a0ead
|
Amory0709/Python
|
/Data-Structure-and-Algorithm/NarcissisticNumber.py
| 569 | 3.625 | 4 |
class Solution:
"""
@param n: The number of digits
@return: All narcissistic numbers with n digits
"""
def getNarcissisticNumbers(self, n):
if n == 1:
return [0,1,2,3,4,5,6,7,8,9]
ans = []
for i in range(10**(n-1), 10**n):
sum, num = 0, i
while num != 0:
sum += (num % 10) ** n
num = num // 10
# ERROR: compared sum with num, but num is now 0
if sum == i:
ans.append(sum)
return ans
|
6618b22c20067475aee2f65aa213cdd94e068d47
|
divyashree-dal/PythonExercises
|
/Exercise3.py
| 97 | 3.953125 | 4 |
n = int(input("Enter a number"))
dict1 = {}
for i in range(1,n+1):
dict1[i] = i*i
print dict1
|
8c2003d8aee3d3cb24a29f1e223f1a1ac746388f
|
borntoshine1/py_course_nechaeva_olga
|
/homework/hw7/task_1.py
| 168 | 4.34375 | 4 |
string = input("Enter your string: ")
symbol = input("Enter symbol: ")
new_string = ""
for i in string:
new_string = string.replace(symbol, "")
print(new_string)
|
5bebcea5617b73bb2eb5eef1246d159889177eec
|
mylgood/myl_good_demo
|
/code/chapter04/07_变量作用域.py
| 1,004 | 3.703125 | 4 |
# 全局变量
# 内置模块
"""
import builtins
print("内置模块:",dir(builtins))
b = 100
# 函数的嵌套定义
def fun_a(x,y):
# 形式参数x,y 也是属于本地变量
# 本地变量
a = 100
print("fun_a中访问:",sum)
def fun_b():
# a对于函数b来说是非本地变量
c = 100
print("访问本地变量:", b)
fun_b()
fun_a()
#fun_b()
访问规则: ① 现在本地作用域 > ② 全局作用域(global) > ③ 内置作用域> ④ 报错 没有定义
"""
a = 100
def fun_a():
# 在函数中修改全局变量 global
# 声明变量a 为全局变量,如果外面没有,则会创建全局变量
# global a
# 本地变量
a = 200
def fun_b():
# global a
# 声明为非本地变量 需要注意的是外面的函数必须存在变量a
nonlocal a
a = 300
print("函数fun_c中的值",a)
fun_b()
print("函数fun_a中的值",a)
fun_a()
print("全局中fun_a的值",a)
|
bb660408e43f5a9cf7b3d9955d886c808bd529df
|
Steven79203/sorting_collection-
|
/selection
| 413 | 3.703125 | 4 |
#!/usr/bin/env python
# Selection Sort
from random import sample
def selection(lst):
n = len(lst)
for i in range(0, n - 1):
tmp = lst[i]
for j in range(i + 1, n):
if lst[j] < tmp:
idx = j
tmp = lst[j]
lst[idx] = lst[i]
lst[i] = tmp
return lst
lista = sample(range(200),200)
print(lista)
print(selection(lista))
|
c79ca1a85831596f7d108b41b73f0d01ea078a7f
|
arayush841/medical-insurance
|
/prediction.py
| 1,720 | 3.53125 | 4 |
from os import write
from matplotlib.pyplot import step
import streamlit as st
import numpy as np
import sklearn
import pickle
st.set_page_config(page_title='Medical Insurance Cost Prediction', page_icon="🏥")
@st.cache
def load_model(file):
model = pickle.load(open(file, "rb"))
return model
mymodel = load_model('model_new.pkl')
st.title('Medical Insurance Cost Prediction')
#st.write('Summer Internship Project by Ayush Raj, B.Tech(CSE)-5th Semester')
age = st.number_input("Enter your Age.", min_value = 18, max_value= 100, step = 1)
sex = st.selectbox('Enter your Gender. ( Male : 1 , Female : 0 )', (0, 1))
bmi = st.number_input("Enter your BMI. ( Body Mass Index ( BMI = weight(kg) / height*height(m^2) )", min_value=10.0, max_value=50.0, step=0.1)
children = st.number_input("Do you have any childrens? If yes tell us the no. of children you have else select 0", min_value=0, max_value=10, step=1)
smoker = st.selectbox("Are you a smoker? ( Yes : 1 , No : 0)", (0,1))
region = st.selectbox("Select your region. ( Southeast : 0 , Southwest : 1, Northeast : 2, Northwest : 3)", (0,1,2,3))
prediction = mymodel.predict([[age,sex,bmi,children,smoker,region]])
cost = np.round(prediction[0], 2)
cost_in_inr = cost*73
status = st.button("Click to check your expected Medical Insurance Cost")
if status:
if (cost<0 and cost_in_inr<0):
st.write("Sorry! We don't have much data which matches your entries for predicting the cost of medical insurance.")
else:
st.write("Predicted Medical Insurance Cost for you in USD is : " + str(cost))
st.write("Predicted Medical Insurance Cost for you in INR is : " + str(round(cost_in_inr,2)))
|
cb5cb58d3b32af55a7a5f8121dffdff1307bfe71
|
swain-s/lc
|
/-排序-0冒泡排序.py
| 352 | 3.796875 | 4 |
import random
a = [random.randint(0, 10) for i in range(10)]
print(a)
def bubble_sort(a):
for j in range(0, len(a)):
last = (len(a)-1) - j
for i in range(0, last):
if a[i] > a[i+1]:
temp = a[i]
a[i] = a[i+1]
a[i+1] = temp
print("1-bubble_sort: ", a)
bubble_sort(a)
|
11930043424f9bd57657bbaa308adbef173fac51
|
xhwupup/xhw_project
|
/3_Longest Substring Without Repeating Characters.py
| 841 | 3.625 | 4 |
# 时间:20190427
# Example:
#Example 1:
#Input: "abcabcbb"
#Output: 3
#Explanation: The answer is "abc", with the length of 3.
#Example 2:
#Input: "bbbbb"
#Output: 1
#Explanation: The answer is "b", with the length of 1.
# 难度:Medium(0.5)
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
if s== None or len(s) ==0:
return 0
max_len = 0 #最大的字符串长度
position={} #保存非重复字符最后的位置
start=0 #保存非重复字符穿开始的位置
for i in range(len(s)):
if s[i] in position and position[s[i]] >= start:
start = position[s[i]]+1
position[s[i]] = i
position[s[i]] = i
current_len=i-start+1
max_len=max(max_len,current_len)
return max_len
|
1832d66327024e4d3f48730476edc27e8f9ed781
|
kausthu/kausthub
|
/add.py
| 343 | 4.1875 | 4 |
#write a program to take 2 numbers from the user,
#then take option to add/subtract/mutiple/divide
#and perform that operation
a=int(input("value of a:"))
b=int(input("value of b:"))
c=a+b
print("addition of a and b:",c)
d=a-b
print("substaction of a and b:",d)
e=a*b
print("multiplication of a and b:",e)
f=a/b
print("division of a and b:",f)
|
2c65cc63493e4b366643c6f78becdea40d63ecb4
|
comingback2life/LearningPython
|
/FirstPythonProject/ex3.py
| 483 | 4.4375 | 4 |
#The code is an extract from Learn Python the Hard way Ex3.
print "I will now count my chickens"
print "Hens",25+30/6
print "Rosters",100-25*3%4
print "Now I will count the eggs"
print 3+2+1-5+4%2-1/4+6
print "Is it true that 3+2<5-7"
print 3+2<5-7
print "What is 3+2",3+2
print "What is 5-7", 5-7
print "Oh this is why it is false"
print "How about some more ?"
print "Is it greater ? 5>-2", 5>-2
print "Is this greater or equal?",5>=-2
print "Is this less or equal?",5<=-2
|
81a6d267d59336eac6993de2660dd1c3703d0328
|
bensalmontree/03_Quiz
|
/03_rounds_mechanics_v1.py
| 1,845 | 4.09375 | 4 |
# Quiz component 3 - Rounds Mechanic
# Functions go here
# Check if response to question is valid
def choice_checker(question, valid_list, error):
valid = False
while not valid:
# Ask user for choice (and put choice in lowercase)
response = input(question).lower()
# iterates through list and if response is an item
# in the list ( or the first letter of an item), the
# full item name is returned
for item in valid_list:
if response == item[0] or response == item:
return item
# output error if item is not in list
print(error)
print()
# Main Routine
rounds_played = 0
# List of valid responses
select_difficulty_list = ["easy", "normal", "hard", "xxx"]
select_difficulty = ""
# Ask question
choose_instruction = "'Math Statement' - Is this True or False? "
# Ask user for selected difficulty
select_difficulty = choice_checker("Select between a 'Easy', 'Normal' or 'Hard' quiz... ", select_difficulty_list, "Please enter 'Easy', 'Normal' or 'Hard'.")
# Print out difficulty heading
print()
if select_difficulty == "easy":
rounds = 10
heading = "--- 10 Easy Math Questions ---\n"
elif select_difficulty == "normal":
rounds = 15
heading = "--- 15 Normal Math Questions ---\n"
elif select_difficulty == "hard":
rounds = 25
heading = "--- 25 Hard Math Quiz ---\n"
print(heading)
end_game = "no"
while end_game == "no":
# Start of Quiz Play Loop
# Question Heading
print("Question {}".format(rounds_played +1, rounds))
choose = input(choose_instruction)
# Rest of Quiz
print("You chose {}\n".format(choose))
rounds_played += 1
# End quiz if # of rounds has been played
if rounds_played == rounds:
break
print("Thank you for using your big brain :)")
|
ff01593e573df82365da1b1a95a279a3469eb6bc
|
tejrajendran/Playground
|
/Inheritance/inheritance.py
| 760 | 4.09375 | 4 |
class Parent():
def __init__(self, last_name, eye_color):
self.last_name = last_name
self.eye_color = eye_color
def show_info(self):
print("last name: " + self.last_name)
print("eye color: " + self.eye_color)
class Child(Parent) :
def __init__(self,last_name,eye_color,num_toys):
Parent.__init__(self,last_name,eye_color)
self.num_toys = num_toys
def show_info(self):
print("last name: " + self.last_name)
print("eye color: " + self.eye_color)
print("num toys: " + str(self.num_toys))
billy_cyrus = Parent("Cyrus","blue")
billy_cyrus.show_info()
miley_cyrus = Child("Cyrus", "Blue", 5)
miley_cyrus.show_info()
# print miley_cyrus.num_toys
# print miley_cyrus.last_name
|
c0f43e8c66d80174c39a9b8fca8c5d2e3e8e16aa
|
hunnurjirao/Simple-Linear-Regression-Application
|
/run.py
| 732 | 3.734375 | 4 |
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
w = int(input("Enter weight in Kgs: "))
p = int(input("Enter price for the given weight: "))
weights = []
price = []
w = w * 10 ** 10
while w > 0:
w = w // 1.1
wp = (p * w)
weights.append(w)
price.append(wp)
X = np.array(weights)
y = np.array(price)
X = X.reshape(X.shape[0],1)
Y = Y.reshape(Y.shape[0],1)
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.33,random_state=3)
model = LinearRegression()
model.fit(X_train,y_train)
pred = float(input('Enter the weight to know the price: '))
a = np.array([[pred]])
print("Amoutn to be paid: " + str(np.round(model.predict(a))))
|
0ed6433e057a7da3e08ad897e0a52f354eb5b612
|
Shaonianlan/Python_exercise
|
/login.py
| 1,545 | 3.78125 | 4 |
user_data={}
def old_user():
prompt='请输入用户名:'
panduan=True
while panduan:
name=input(prompt)
if name not in user_data:
if name=='esc' or name=='ESC':
break
else:
prompt='用户名不存在,请重新输入:'
continue
else:
panduan=False
else:
password=input('请输入密码:')
pwd=user_data.get(name)
if password==pwd:
print('欢迎进入***系统!')
else:
print('密码错误!')
def new_user():
prompt='请输入注册的用户名:'
while True:
name=input(prompt)
if name in user_data:
prompt='用户名已存在,请重新输入:'
continue
else:
if name=='esc' or name=='ESC':
break
else:
password1=input('请输入密码:')
password2=input('确认密码:')
if password1==password2:
user_data.setdefault(name,password1)
print('注册成功!')
break
else:
print('请确保两次输入的密码相同!')
continue
def showmenu():
prompt='''
|---新建用户:N/n---|
|---登陆账户:E/e---|
|---退出程序:Q/q---|
|---请输入指令代码---
'''
while True:
chosen=False
while not chosen:
choice=input(prompt)
if choice not in 'NnEeQq':
print('输入的指令代码错误,请重新输入:')
else:
chosen= True
if choice=='q' or choice=='Q':
break
elif choice=='N' or choice=='n':
print('|---输入esc/ESC返回---|')
new_user()
elif choice=='E' or choice=='e':
print('|---输入esc/ESC返回---|')
old_user()
showmenu()
|
5ecad1aef5e6380c372fdca69217df2fc4d1579b
|
YutingPang/leetcode
|
/293_filp_game.py
| 227 | 3.546875 | 4 |
class Solution(object):
def generatePossibleNextMoves(self, s):
return [s[:i] + '--' + s[i+2:] for i in range(len(s) - 1) if s[i:i+2] == '++']
test = Solution()
s = '+++++'
print(test.generatePossibleNextMoves(s))
|
4cdf5c348221ce85f8c861ea3094fd706ccaf271
|
binnev/project-euler
|
/python/puzzles/euler22.py
| 968 | 3.875 | 4 |
# -*- coding: utf-8 -*-
"""
Names scores
Problem 22
Using names.txt (right click and 'Save Link/Target As...'), a 46K text file
containing over five-thousand first names, begin by sorting it into
alphabetical order. Then working out the alphabetical value for each name,
multiply this value by its alphabetical position in the list to obtain a name
score.
For example, when the list is sorted into alphabetical order, COLIN, which is
worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would
obtain a score of 938 × 53 = 49714.
What is the total of all the name scores in the file?
"""
from python.tools import utils, profile
@profile.function
def euler22():
raw = utils.load_puzzle_input("euler22")
f = sorted(raw.replace('"', "").split(","))
scores = [sum(ord(c) - 64 for c in s) for s in f]
return sum([w * p for w, p in zip(scores, range(1, len(f) + 1))])
if __name__ == "__main__":
assert euler22() == 871198282
|
70b0a41da2cdaaf0b21ea4592f4c8eec6b0103d8
|
sumanth-lingappa/prayathna
|
/linkedlist/testnode.py
| 337 | 3.578125 | 4 |
'''
6->3->4->2->1
'''
import node
nodeA = node.Node(6) #head
nodeB = node.Node(3)
nodeC = node.Node(4)
nodeD = node.Node(2)
nodeE = node.Node(1)
nodeA.next = nodeB
nodeB.next = nodeC
nodeC.next = nodeD
nodeD.next = nodeE
numberOfNodes = node.countNodes(nodeA)
print "Number of nodes is {}".format(numberOfNodes)
|
616d598d870548d49ad6dd77aa50e9739e4e2115
|
rghf/Twoc_Problem
|
/Day 6/8.py
| 753 | 3.65625 | 4 |
def spiral(nform, r, c):
rowStartIndex, colStartIndex = 0,0
while (rowStartIndex<r) and (colStartIndex<c):
for i in range(rowStartIndex,c):
print(nform[rowStartIndex][i],end=" ")
rowStartIndex+=1
for i in range(rowStartIndex,r):
print(nform[i][c-1],end=" ")
c-=1
if rowStartIndex<r:
for i in range(c-1,(colStartIndex-1),-1):
print(nform[r-1][i],end=" ")
r-=1
if colStartIndex<c:
for i in range(r-1,(rowStartIndex-1),-1):
print(nform[i][colStartIndex],end=" ")
colStartIndex+=1
nform = [[1,2,3,4,5],
[6,7,8,9,10],
[11,12,13,14,15]]
r = 3
c = 5
spiral(nform, r, c)
|
7bf5a6e56e39d4da88ba10fc4503f40064e731fa
|
EricL0wry/algorithm-practice
|
/python-arcade/first-reverse-try.py
| 633 | 4.46875 | 4 |
# Reversing an array can be a tough task, especially for a novice programmer. Mary just started coding, so she would like to start with something basic at first. Instead of reversing the array entirely, she wants to swap just its first and last elements.
# Given an array arr, swap its first and last elements and return the resulting array.
# Example
# For arr = [1, 2, 3, 4, 5], the output should be
# firstReverseTry(arr) = [5, 2, 3, 4, 1].
def firstReverseTry(arr):
if len(arr):
endBits = [arr[len(arr) - 1], arr[0]]
arr[0] = endBits[0]
arr[len(arr) - 1] = endBits[1]
return arr
print(firstReverseTry([]))
|
ece3e9e6e0f945ab13829d8170752b7f5f97d1b2
|
moaazelsayed1/CS50x-psets
|
/week_7/pset7/houses/roster.py
| 878 | 4.15625 | 4 |
from cs50 import SQL
from sys import argv
import sys
# terminates the programs if the args not equals 2
if len(argv) != 2:
sys.exit("Error")
db = SQL("sqlite:///students.db")
# reading the required data from the students table ordered by last name and the first name
# db.execute retruns a lists of dictionaries
TableList = db.execute("SELECT DISTINCT first, middle, last, birth FROM students WHERE students.house = ? ORDER BY last, first", argv[1])
# iterates over every dictionary in the list
for dic in TableList:
first = dic["first"]
middle = dic["middle"]
last = dic["last"]
birth = dic["birth"]
# checks if the person has a middle name or not to display the correct output without (null) value
if middle == None:
print(f"{first} {last}, born {birth}")
else:
print(f"{first} {middle} {last}, born {birth}")
|
b480150d33fae3cac8b3d56fa1550e1480a0fcbe
|
Evertcolombia/holbertonschool-higher_level_programming
|
/0x01-python-if_else_loops_functions/2-print_alphabet.py
| 89 | 3.6875 | 4 |
#!/usr/bin/python3
i = 97
for i in range(i, 123):
print("{}".format(chr(i)), end='')
|
a5ca6d9264f75943b97f5a4c60a831c8fbac4685
|
mesomagik/python_tetris_game
|
/map.py
| 3,434 | 3.609375 | 4 |
class Map(object):
def __init__(self, height, width, squareSize):
self.squareSize = squareSize
self.height = height
self.width = width
self.mapMatrix = [[0 for i in range(width)] for j in range(height)]
self.connectedBricks = [[0 for i in range(width)] for j in range(height)]
self.points = 0
def ClearMap(self):
print("\n" * 25)
self.mapMatrix = [[0 for i in range(self.width)] for j in range(self.height)]
for i in range(self.height):
for j in range(self.width):
if self.connectedBricks[i][j] == 1:
self.mapMatrix[i][j] = 1
def PrintMap(self):
for j in range(self.width):
print("XX", end='')
print()
scoreString = "SCORE: " + str(self.points)
print("XX ", end='')
print(scoreString, end='')
for iter in range(self.width - 4):
print(" ", end='')
print("XX")
for j in range(self.width):
print("XX", end='')
print()
for i in range(self.height):
for j in range(self.width):
if self.mapMatrix[i][j] == 0:
print(" ", end='')
else:
print("XX", end='')
print("|")
def AddBrick(self, brick):
for lines in range(len(brick.shape)):
for itemInLine in range(len(brick.shape[lines])):
self.mapMatrix[brick.posWidth + lines][brick.posHeight + itemInLine] = brick.shape[lines][itemInLine]
def AddConnectedBrick(self, brick):
for lines in range(len(brick.shape)):
for itemInLine in range(len(brick.shape[lines])):
if brick.shape[lines][itemInLine] == 1:
self.connectedBricks[brick.posWidth + lines][brick.posHeight + itemInLine] = 1
self.CheckIfLineIsFull()
def CheckCollision(self, brick):
for lines in range(len(brick.shape)):
for itemInLine in range(len(brick.shape[lines])):
if brick.posWidth + len(brick.shape) >= self.height:
return True
elif brick.shape[lines][itemInLine] == 1 and self.mapMatrix[brick.posWidth + lines][brick.posHeight + itemInLine] == 1:
self.UpBrick(brick)
return True
return False
def DropBrick(self, brick):
brick.posWidth += 1
def MoveLeft(self, brick):
if brick.posHeight > 0:
brick.posHeight -= 1
def MoveRight(self, brick):
if brick.posHeight + len(brick.shape[0]) < self.width:
brick.posHeight += 1
def UpBrick(self, brick):
brick.posWidth -= 1
def CheckIfLineIsFull(self):
for line in range(self.height):
counter = 0
for itemInLine in range(self.width):
if self.connectedBricks[line][itemInLine] == 0:
break
counter += 1
if counter == self.width:
self.DeleteLineAndAddPoint(line)
def DeleteLineAndAddPoint(self, lineNumber):
print(len(self.connectedBricks))
del self.connectedBricks[lineNumber]
newList = [[0 for i in range(self.width)]]
newList = newList + self.connectedBricks
self.connectedBricks = newList
print(str(len(self.connectedBricks)))
self.points += 1
|
63194d857612064f640f42654d90983c6447b423
|
JuniorCardoso-py/PythonCourse
|
/Aula6/Aula6.0/Aula6.1.py
| 1,223 | 4 | 4 |
#Aula 6 - p2 - 13-11-2019
#Estruturas de repetição - FOR
#--- for simples usando range com incremento padrão de 1
# for i in range(0,10):
# print(f'{i} -Padawans HBSIS')
# for i in range(0,10,2):
# print(f'{i} -Padawans HBSIS')
# #--- for simples usando range com incremento padrão de 2
# for i in range(0,100,2):
# print(f'{i} -Pares')
# lista = ['Mateus','Matheus','Marcela','Nicole','Antonio','Pablo']
# for i in range (0,6):
# print(lista[i])
# lista.append('Natan')
# for sortudo in lista:
# print(sortudo)
# numero = 10
# for i in range(0,10+1):
# print(f'{i} x {numero} = {i*numero} ')
# ---- EXERCICIO ------ LISTAS, FOR E FOREACH
# EXERCICIO 1 - LISTAS
# Escreva programa que leia o nome de 10 alunos
# Armazene os nomes em uma lista
# Imprima a lista
# EXERCICIO 2 - For
# Escreva programa que leia o numero inteiro
# Calcule a tabuada do numero informado
# Imprima a tabuada com a conta
# EXERCICIO 3 - Foreach
# Escreva programa que leia as notas de um aluno
# Armazene as notas e nomes em listas
# Imprima:
# 1 - O nome dos alunos e suas respectivas médias e resultados (Aprovado >= 7.0)
# 2 - Média do aluno
# 3 - Resultado (Aprovado >=7.0)
|
a1105af7b0f972649bd7620771bec05b7397e88e
|
zlxl00917/LIKE_LION-
|
/input.py
| 700 | 3.875 | 4 |
# 파이썬에서 입력을 받는 함수가 있습니다~~ 구글링해서 찾아보세요!
print('문제 1. 전화번호 받기')
print('조건 1. 저장할 때는 공백 문자 없이')
print('조건 2. -, ., , 등이 들어올 때 전부 제외 하고 숫자만 저장!')
phone_number=input('전화번호를 입력하세요: ')
print('문제 2. 영어 이름 받기')
print('choi juwon 을 입력 받으면,')
print('first name : Choi, last name: Juwon 이 출력되게 만들기')
first_name, last_name=input('영어이름을 입력하세요: ').split()
firstname=first_name.capitalize()
lastname=last_name.capitalize()
print("first name : %s" %firstname)
print("last name : %s" %lastname)
|
910e7bbf5d50ec20460e0b87cbe12800446b5bb5
|
christabella/code-busters
|
/store_credit_sort.py
| 719 | 3.71875 | 4 |
#!/usr/bin/env python3
def get_items_to_buy(items, credit):
indices, items = zip(*sorted(enumerate(items), key=lambda x: x[1]))
i = 0
j = len(items) - 1
current_sum = items[i] + items[j]
while current_sum != credit:
if current_sum < credit:
i += 1
elif current_sum > credit:
j -= 1
current_sum = items[i] + items[j]
return sorted([indices[i]+1, indices[j]+1])
if __name__ == "__main__":
cases = int(input())
for case in range(1, cases+1):
credit = int(input())
num_items = int(input())
items = [int(x) for x in input().split()]
print("Case #{}: {} {}".format(case, *get_items_to_buy(items, credit)))
|
498d646039a18008e69b4f7020c5b61c487f6112
|
maoyalu/leetcode
|
/Python/1-99/5_Longest_Palindromic_Substring.py
| 1,432 | 3.59375 | 4 |
import unittest
def solution(s):
# ********** Attempt 2 - 2019/10/08 **********
'''Dynamic Programming'''
if len(s) < 2:
return s
size = len(s)
dp = [[False for _ in range(size)] for _ in range(size)]
max_length = 0
result = ''
for i in range(size):
max_length = 1
dp[i][i] = True
result = s[i]
for i in range(size - 1):
if s[i] == s[i+1]:
max_length = 2
dp[i][i+1] = True
result = s[i:i+2]
for length in range(2, size):
for i in range(size - length):
j = i + length
if s[i] == s[j] and dp[i+1][j-1]:
dp[i][j] = True
if length + 1 > max_length:
max_length = length + 1
result = s[i: j+1]
return result
# ********** Attempt 1 - 2019/10/08 **********
# result = ''
# for i in range(len(s)):
# for j in range(len(s), i, -1):
# sub_s = s[i:j]
# if sub_s == sub_s[::-1] and len(sub_s) > len(result):
# result = sub_s
# return result
class TestSolution(unittest.TestCase):
def test1(self):
s = "babad"
out = "bab"
self.assertEqual(solution(s), out)
def test2(self):
s = "cbbd"
out = "bb"
self.assertEqual(solution(s), out)
if __name__ == "__main__":
unittest.main()
|
6451ffdf05cde5516d7f885a0daad77e25f208a7
|
hverlin/algo
|
/hello_world/hello_world.py
| 672 | 4.0625 | 4 |
# coding: utf-8
import sys
# coding: utf-8
def hello_world(n):
"""Prints 'Hello World!' n times to stdout.
To run doctests:
python3 -m doctest -v solution.py
>>> hello_world(3)
Hello World!
Hello World!
Hello World!
Parameters
----------
n : integer
number of times to repeat 'Hello World!' to stdout
Returns
-------
N/A (no return value)
"""
for i in range(n):
print("Hello World!")
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: .py <int>")
sys.exit(1)
n = int(sys.argv[1])
# Call the function
hello_world(n)
|
835ee3a673d0639df597312dc4c746e9f2cbf0d3
|
bgorsi/PFB_problemsets
|
/python_problem2.8.py
| 493 | 4.25 | 4 |
#!/usr/bin/env python3
import sys
number = int(sys.argv[1])
if number > 0:
print ("positive")
if number < 50:
print ("smaller than 50")
if number %2 ==0:
print ("it is an even number that is smaller than 50")
elif number > 50:
print("greater than 50")
if number %3 ==0:
print ("it is larger than 50 and divisible by 3")
elif number == 0:
print ("zero")
else:
print ("negative")
print("you're doing awesome!")
|
13a3fd4f993b399dc66107989b62a14bacada343
|
jan25/code_sorted
|
/leetcode/weekly181/2_4_divisors.py
| 666 | 3.5 | 4 |
'''
https://leetcode.com/contest/weekly-contest-181/problems/four-divisors/
'''
class Solution:
def sumFourDivisors(self, nums: List[int]) -> int:
def numDivs(a):
d, s = 0, 0
for i in range(1, max(nums)):
if i*i > a: break
if a % i == 0:
d += 1
s += i
if i * i != a:
d += 1
s += a // i
return d, s
sumDivs = 0
for a in nums:
d, s = numDivs(a)
if d == 4:
sumDivs += s
return sumDivs
|
033ffa55bb1fbc0a0df3e2ca6145e65a93522d99
|
faizalmuzakki/Risop
|
/least_cost.py
| 2,828 | 3.828125 | 4 |
def create_table(row, column):
array2d = []
for i in range(row):
array = []
for j in range(column):
val = int(input("value: "))
array.append(val)
array2d.append(array)
for i in range(row):
val = int(input("supply: "))
array2d[i].append(val)
demand = []
for i in range(column):
val = int(input("demand: "))
demand.append(val)
array2d.append(demand)
return array2d
def print_table(row, column, table):
for i in range(row+1):
for j in range(column):
print(table[i][j], end="\t")
if(j+1 == column):
if(i == row):
print()
else:
print(table[i][column])
#print()
def least_cost(row, column, table):
array2d = []
sort = []
for i in range(row):
array = []
sort += sorted(table[i][:column])
for j in range(column):
array.append(0)
array2d.append(array)
sort = sorted(sort)
i = 0
cost_idx = 0
hehe = 0
j = 0
while(1):
array = []
while(1):
if(table[i][j] == sort[cost_idx]):
hehe = 0
if(table[row][j] == 0):
cost_idx = cost_idx + 1
elif(table[i][column] >= table[row][j]):
array2d[i][j] = table[row][j]
table[i][column] -= table[row][j]
table[row][j] = 0
cost_idx = cost_idx + 1
if(table[i][column] == 0):
j = j + 1
break
elif(table[i][column] < table[row][j]):
array2d[i][j] = table[i][column]
table[row][j] -= table[i][column]
table[i][column] = 0
cost_idx = cost_idx + 1
j = j + 1
break
if(j+1 >= column):
j = 0
i = i + 1
if(i == row):
i = 0
else:
j = j+1
hehe = hehe + 1
total = 0
for k in range(column):
total += table[row][k]
if(total == 0):
break
print("result: ", array2d)
tot = 0
for i in range(row-1):
for j in range(column):
tot += array2d[i][j]*table[i][j]
print("total cost: ", tot)
#row = int(input("Jumlah baris: "))
#column = int(input("Jumlah kolom: "))
row = 3
column = 4
#table = create_table(row, column)
table = [[10,0,20,11,15], [12,7,9,20,25], [0,14,16,18,5], [5,15,15,10]]
minim = min(table)
print("min: ", min(minim))
print_table(row, column, table)
print()
lcm = least_cost(row, column, table)
|
c2fae5e17427fc6fb8e5064437d35013c3323222
|
SauravShoaeib/College
|
/CS_127/Python/countin_stars.py
| 197 | 4.0625 | 4 |
#Saurav Hossain
#09/04/18
#A program that prints an opening statement and then asks the user for a number and prints that many stars, one per line
for i in range(int(input("Input was \n"))):
print("*")
|
44ea283b16276460d75d47a25a02305f98c2342e
|
Ilnur92/skillfactory-module5
|
/script.py
| 1,479 | 3.75 | 4 |
field = [[" ", "0", "1", "2"],
["0", "-", "-", "-"],
["1", "-", "-", "-"],
["2", "-", "-", "-"]]
def show_field():
for x in field:
print(x[0], x[1], x[2], x[3])
def ask_field():
i = input("Введите строку: ")
i = int(i)
j = input("Введите столбец: ")
j = int(j)
return i, j
for i in range(5):
show_field()
print("Ходи X!")
i, j = ask_field()
field[i + 1][j + 1] = "x"
show_field()
print("Ходи 0!")
i, j = ask_field()
field[i + 1][j + 1] = "0"
wins = [((1, 1), (1, 2), (1, 3)), ((2, 1), (2, 2), (2, 3)), ((3, 1), (3, 2), (3, 3)), ((1, 1), (2, 2), (3, 3)),
((1, 3), (2, 2), 3, 1)]
def check_win():
for user in ['x', '0']:
for i in range(3):
if f'{field[i][0]}{field[i][1]}{field[i][2]}' == user * 3:
print(f"Win - {user}")
return
elif f'{field[0][i]}{field[1][i]}{field[2][i]}' == user * 3:
print(f"Win - {user}")
return
if f'{field[0][0]}{field[1][1]}{field[2][2]}' == user * 3:
print(f"Win - {user}")
return
elif f'{field[0][2]}{field[1][1]}{field[2][0]}' == user * 3:
print(f"Win - {user}")
return
for j in range(3):
if field[i + 1][j + 1] not in field[j] and '_' not in field[j]:
return True
|
0479f1472d7399bcb4668d790dc5477a4ddbdb7e
|
Randyedu/python
|
/知识点/04-LiaoXueFeng-master/32-MetaClass.py
| 7,559 | 4.625 | 5 |
'''
type()
动态语言和静态语言最大的不同,就是函数和类的定义,不是编译时定义的,而是运行时动态创建的。
'''
class Hello(object):
def hello(self, name = 'world'):
print('Hello, %s' % name)
h = Hello()
h.hello()
print(type(Hello))
print(type(h))
print('--------------------------')
'''
我们说class的定义是运行时动态创建的,而创建class的方法就是使用type()函数。
type()函数既可以返回一个对象的类型,又可以创建出新的类型
比如,我们可以通过type()函数创建出Hello类,而无需通过class Hello(object)...的定义:
要创建一个class对象,type()函数依次传入3个参数:
1、class的名称;
2、继承的父类集合,注意Python支持多重继承,如果只有一个父类,别忘了tuple的单元素写法;
3、class的方法名称与函数绑定,这里我们把函数fn绑定到方法名hello上。
通过type()函数创建的类和直接写class是完全一样的,因为Python解释器遇到class定义时,仅仅是扫描一下class定义的语法,然后调用type()函数创建出class。
'''
def fn(self,name = 'world'):
print('Hello,%s' % name)
Hello = type('Hello',(object,),dict(hello = fn))
h = Hello()
h.hello()
print(type(Hello))
print(type(h))
'''
使用元类
阅读: 95912
type()
动态语言和静态语言最大的不同,就是函数和类的定义,不是编译时定义的,而是运行时动态创建的。
比方说我们要定义一个Hello的class,就写一个hello.py模块:
class Hello(object):
def hello(self, name='world'):
print('Hello, %s.' % name)
当Python解释器载入hello模块时,就会依次执行该模块的所有语句,执行结果就是动态创建出一个Hello的class对象,测试如下:
>>> from hello import Hello
>>> h = Hello()
>>> h.hello()
Hello, world.
>>> print(type(Hello))
<class 'type'>
>>> print(type(h))
<class 'hello.Hello'>
type()函数可以查看一个类型或变量的类型,Hello是一个class,它的类型就是type,而h是一个实例,它的类型就是class Hello。
我们说class的定义是运行时动态创建的,而创建class的方法就是使用type()函数。
type()函数既可以返回一个对象的类型,又可以创建出新的类型,比如,我们可以通过type()函数创建出Hello类,而无需通过class Hello(object)...的定义:
>>> def fn(self, name='world'): # 先定义函数
... print('Hello, %s.' % name)
...
>>> Hello = type('Hello', (object,), dict(hello=fn)) # 创建Hello class
>>> h = Hello()
>>> h.hello()
Hello, world.
>>> print(type(Hello))
<class 'type'>
>>> print(type(h))
<class '__main__.Hello'>
要创建一个class对象,type()函数依次传入3个参数:
class的名称;
继承的父类集合,注意Python支持多重继承,如果只有一个父类,别忘了tuple的单元素写法;
class的方法名称与函数绑定,这里我们把函数fn绑定到方法名hello上。
通过type()函数创建的类和直接写class是完全一样的,因为Python解释器遇到class定义时,仅仅是扫描一下class定义的语法,然后调用type()函数创建出class。
正常情况下,我们都用class Xxx...来定义类,但是,type()函数也允许我们动态创建出类来,也就是说,动态语言本身支持运行期动态创建类,这和静态语言有非常大的不同,要在静态语言运行期创建类,必须构造源代码字符串再调用编译器,或者借助一些工具生成字节码实现,本质上都是动态编译,会非常复杂。
metaclass
除了使用type()动态创建类以外,要控制类的创建行为,还可以使用metaclass。
metaclass,直译为元类,简单的解释就是:
当我们定义了类以后,就可以根据这个类创建出实例,所以:先定义类,然后创建实例。
但是如果我们想创建出类呢?那就必须根据metaclass创建出类,所以:先定义metaclass,然后创建类。
连接起来就是:先定义metaclass,就可以创建类,最后创建实例。
__new__()方法接收到的参数依次是:
1、当前准备创建的类的对象;
2、类的名字;
3、类继承的父类集合;
4、类的方法集合。
'''
# metaclass是类的模板,所以必须从`type`类型派生:
class ListMetaclass(type):
"""docstring for ListMetaclass"""
def __new__(cls,name,bases,attrs):
attrs['add'] = lambda self,value : self.append(value)
return type.__new__(cls,name,bases,attrs)
# 有了ListMetaclass,我们在定义类的时候还要指示使用ListMetaclass来定制类,传入关键字参数metaclass:
class MyList(list, metaclass = ListMetaclass):
pass
L = MyList()
L.add(1)
print(L)
'''
ORM全称“Object Relational Mapping”,即对象-关系映射,就是把关系数据库的一行映射为一个对象,也就是一个类对应一个表,这样,写代码更简单,不用直接操作SQL语句。
要编写一个ORM框架,所有的类都只能动态定义,因为只有使用者才能根据表的结构定义出对应的类来。
让我们来尝试编写一个ORM框架。
'''
class Field(object):
def __init__(self, name, column_type):
self.name = name
self.column_type = column_type
def __str__(self):
return '<%s:%s>' % (self.__class__.__name__, self.name)
class StringField(Field):
def __init__(self, name):
super(StringField, self).__init__(name,'varchar(100)')
class IntegerField(Field):
def __init__(self, name):
super(IntegerField, self).__init__(name,'bigint')
'''
在ModelMetaclass中,一共做了几件事情:
1、排除掉对Model类的修改;
2、在当前类(比如User)中查找定义的类的所有属性,如果找到一个Field属性,就把它保存到一个__mappings__的dict中,同时从类属性中删除该Field属性,否则,容易造成运行时错误(实例的属性会遮盖类的同名属性);
3、把表名保存到__table__中,这里简化为表名默认为类名。
'''
class ModelMetaclass(type):
def __new__(cls,name,bases,attrs):
if name == 'Model':
return type.__new__(cls,name,bases,attrs)
print('Found model:%s' % name)
mappings = dict()
for k,v in attrs.items():
if isinstance(v,Field):
print('Found mappings:%s ==> %s' % (k,v))
mappings[k] = v
for k in mappings.keys():
attrs.pop(k)
attrs['__mappings__'] = mappings
attrs['__table__'] = name
return type.__new__(cls,name,bases,attrs)
# 在Model类中,就可以定义各种操作数据库的方法,比如save(),delete(),find(),update等等。
class Model(dict,metaclass=ModelMetaclass):
def __init__(self, **kw):
super(Model, self).__init__(**kw)
def __getattr__(self,key):
try:
return self[key]
except KeyError:
raise AttributeError(r"'Model' object has no attribute '%s'" % key)
def __setattr__(self,key,value):
self[key] = value
def save(self):
fields = []
params = []
args = []
for k,v in self.__mappings__.items():
fields.append(v.name)
params.append('?')
args.append(getattr(self,k,None))
sql = 'indert into %s (%s) values (%s)' % (self.__table__,','.join(fields),','.join(params))
print('SQL:%s' % sql)
print('ARGS:%s'% str(args))
class User(Model):
# 定义类的属性到列的映射:
id = IntegerField('id')
name = StringField('username')
email = StringField('email')
password = StringField('password')
u = User(id=12345,name='Michael',email='[email protected]',password='my-pwd')
u.save()
|
5ab15fae83e1322eb46e0c0d2b1306554437794e
|
lightionight/LearnPython
|
/SourceCode/BuildInModules/datetime.py
| 361 | 3.796875 | 4 |
# datatime is python deal with time and date standard lib
# important datatime modules
# first datetime is modules name, second datetime is class name
from datetime import datetime
# get current time from system
now = datetime.now()
print(now)
# using order time to create datetime object
dt = datetime(2020, 11, 13, 15, 31)
print(dt)
print(dt.timestamp())
|
ef8cc271c0fa8304666d97ec0c962a9597546e36
|
viviannevilar/pyhton-tasks
|
/functionsQ2.py
| 306 | 4.3125 | 4 |
number = []
new_number_string = input("Type a number to add: ")
while len(new_number_string) > 0:
new_number = int(new_number_string)
number.append(new_number)
new_number_string = input("Type a number to add: ")
mean = sum(number)/len(number)
print("The average of the numbers is {mean}")
|
5f93df695fb0118e939018c8b7109b58e2ed5af6
|
MahmoudHassan/hacker-rank
|
/30DaysOfCode/Day11.py
| 1,341 | 4 | 4 |
"""
Context
Given a 6*6 2D Array, A:
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
We define an hourglass in A to be a subset of values with indices falling in this pattern in A's graphical representation:
a b c
d
e f g
There are 16 hourglasses in A, and an hourglass sum is the sum of an hourglass' values.
Task
Calculate the hourglass sum for every hourglass in A, then print the maximum hourglass sum.
Input Format
There are 6 lines of input, where each line contains 6 space-separated integers describing 2D Array ;
A every value in A will be in the inclusive range of -9 to 9.
Constraints
-9=< A[i][j] <=9
0=< i,j <=5
Output Format
Print the largest (maximum) hourglass sum found in A.
Sample Input
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 2 4 4 0
0 0 0 2 0 0
0 0 1 2 4 0
Sample Output
19
"""
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
arr = []
hourglass = []
hourglass_list = []
for _ in range(6):
arr.append(list(map(int, input().rstrip().split())))
for row in range(4):
for col in range(4):
hourglass = [x[col:col+3] for x in arr[row:row+3]]
hourglass[1][0:3:2] = [0, 0]
hourglass_list.append(sum([sum(l) for l in hourglass]))
print(max(hourglass_list))
|
050c5774e4dc36741ed87008ee252aab5b3bd711
|
ashutoshkrris/Data-Structures-and-Algorithms-in-Python
|
/Recursion/flatten.py
| 457 | 4.0625 | 4 |
# Write a recursive function called flatten which accepts an array and returns new array with all values flattened
def flatten(arr):
result = []
for item in arr:
if type(item) is list:
result.extend(flatten(item))
else:
result.append(item)
return result
print(flatten([1, 2, 3, [4, 5]]))
print(flatten([1, [2, [3, 4], [[5]]]]))
print(flatten([[1], [2], [3]]))
print(flatten([[[1], [[[2]]], [[[3]]]]]))
|
8694362beeb11f7451b7232b226888c28b54dc7b
|
germandouce/AyP-1
|
/Clases_y_ejercicios/Ejs_RPL/4_Decisiones.py
| 2,432 | 3.84375 | 4 |
#UNIDAD 4: Decisiones
#ej 4.1
# a) - Es par
'''Escribir una función indique si un determinado número entero es par o no'''
'''
n=4
def es_par(n):
"""
dice si es par o no
"""
# if n%2 == 0:
# return (n%2 + 1)
# else:
# return (n%2 - 1)
return (n%2 == 0)
print(es_par(n))
'''
#4.1
# b) - Es primo
'''Escribir una función que indique si un número natural es primo.
Recordar: Un número es primo cuándo tiene exactamente dos divisores (sólo se puede dividir por 1 y
por sí mismo).'''
'''
def es_primo(n):
"""
dice si es primo o no
"""
es_primo = True
divisor = n-1
while divisor >1:
if n % divisor == 0:
es_primo = False
divisor -=1
return es_primo
print( es_primo( int (input('n:') ) ) )
'''
#4.2 - Abs
'''
Escribir una implementación propia de la función abs, que devuelva el valor absoluto de
cualquier valor que reciba.'''
'''
def mi_abs(x):
"""
devuelve el valor absoluto
"""
if x<0:
x = -x
return x
print(mi_abs(int(input('n: '))))
'''
#4.3 - Matrzi matriz identidad
'''
Escribir una función que reciba por parámetro una dimensión n, e imprima la matriz identidad
correspondiente a esa dimensión.'''
'''
def matriz_identidad(n) -> None:
"""
DOC: Completar.
"""
for i in range(n):
fila = list()
for j in range(n):
if i ==j:
print(1, end = ' ')
#fila.append(1)
else:
print(0, end = ' ')
#fila.append(0)
print()
matriz_identidad(int(input('n:')))
'''
#4.4 a) - Extremos de un polinomio
'''
Escribir una función que permita encontrar el máximo o mínimo de un polinomio de segundo grado.
La función deberá devolver la posición del extremo y un booleano indicando si es un máximo.
El polinomio estará representado por sus coeficientes en la forma a x² + b x + c. Por ejemplo,
para el polinomio 2 x² + 3 x + 4 los coeficientes serían a = 2, b = 3, c = 4.
Se deberá validar que el polinomio sea de segundo grado (a != 0). Si la validación falla, la
función deberá devolver None.
'''
#FIACA
#maximo o minimo es el vertice -b/2a
'''
def buscar_extremo(a, b, c) -> tuple:
"""
max y min de p(x)
"""
if a == 0:
maxi_mini = None
else:
maxi_mini = -b/(2*a)
return maxi_mini
'''
|
1bed4e2666c699ebf25b0a1035b23491dec84666
|
woobaik/python200
|
/qestion.py
| 398 | 3.796875 | 4 |
def delete_from_dict(a, *b):
if not isinstance(a, dict):
print(f"You need to send a dictionary. You sent: {type(a)}")
return
if len(b) != 1:
print("You need to specify a word to delete.")
else:
if b[0] in a:
del a[b[0]]
print(f"{b[0]} has been deleted.")
else:
print(f"{b[0]} is not in dict. Won't delete.")
|
252e89a41bc1023e2806f58c5eea6c81cc6b4c7c
|
purusoth-lw/my-work
|
/6.Bitwise operator.py
| 422 | 3.953125 | 4 |
a=int(input("Enter value 1 : "))
b=int(input("Enter value 2 : "))
c=a&b
print("a&b : ",c)
c=a|b
print("a|b : ",c)
c=a^b
print("a^b : ",c)
c=~a
print("~a : ",c)
c=a<<1
print("a<<1 : ",c)
c=a<<2
print("a<<2 : ",c)
c=a>>1
print("a>>1 : ",c)
c=a>>2
print("a>>2 : ",c)
c=b<<1
print("b<<1 : ",c)
c=b<<2
print("b<<2 : ",c)
c=b>>1
print("b>>1 : ",c)
c=b>>2
print("b>>2 : ",c)
|
ac27deacfacab6a8e85e0141a42c61ee07aa29f6
|
mcvholloway/reinforcement_tic_tac_toe
|
/draw_board.py
| 1,130 | 3.75 | 4 |
import matplotlib.pyplot as plt
import numpy as np
def setup_grid():
fig = plt.figure()
plt.xlim(0,3)
plt.ylim(0,3)
for x in [1,2]:
plt.vlines(x = x, ymin = 0, ymax = 3)
for y in [1,2]:
plt.hlines(y = y, xmin = 0, xmax = 3)
plt.axis('off')
def add_elements(board):
for i in range(3):
for j in range(3):
if board[j][i] == 1:
plt.plot([i + 0.5 - 0.4, i + 0.5 + 0.4],
[2 - j + 0.5 + 0.4, 2 - j + 0.5 - 0.4], color = 'black')
plt.plot([i + 0.5 - 0.4, i + 0.5 + 0.4],
[2 - j + 0.5 - 0.4, 2 - j + 0.5 + 0.4], color = 'black')
if board[j][i] == -1:
theta = np.linspace(0,1,200)
x = 0.4*np.cos(2*np.pi*theta) + i + 0.5
y = 0.4*np.sin(2*np.pi*theta) + 2 - j + 0.5
plt.plot(x,y, color = 'black')
def draw_board(board):
setup_grid()
add_elements(board)
plt.show(block = False)
if __name__ == '__main__':
draw_board([[0,-1,0],[1,1,0],[0,0,0]])
input('Press Enter to close plot.')
|
fa405f4b4f479c4c2d9896e8ce632893a7048a50
|
curtislb/ProjectEuler
|
/py/problem_009.py
| 1,392 | 4.53125 | 5 |
#!/usr/bin/env python3
"""problem_009.py
Problem 9: Special Pythagorean triplet
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = S.
Find the product a*b*c.
"""
__author__ = 'Curtis Belmonte'
import math
from typing import Optional
# PARAMETERS ##################################################################
S = 1000 # default: 1000
# SOLUTION ####################################################################
def solve() -> Optional[int]:
# no triplet exists if S is not even
if S % 2 != 0:
return None
# let a = 2*m*n, b = m^2 - n^2, c = m^2 + n^2. Then, m^2 + m*n = S/2
s_div_2 = S / 2
m_limit = int(math.ceil(math.sqrt(s_div_2)))
# search for m and n under conditions m > n and m % 2 != n % 2
for m in range(2, m_limit):
if S % m == 0:
s_div_2m = s_div_2 / m
for n in range(1 if m % 2 == 0 else 2, m, 2):
if m + n == s_div_2m:
# compute a, b, and c from the definitions of m and n
m_sq = m * m
n_sq = n * n
return (2 * m * n) * (m_sq - n_sq) * (m_sq + n_sq)
# no triplet found
return None
if __name__ == '__main__':
print(solve())
|
dd9bfdff870560655783b59ed35c51f620045ff6
|
gslandtreter/pyNeuralClassifier
|
/gradient_tester.py
| 1,919 | 3.78125 | 4 |
import neural_classifier
from neuralnetwork.activation_function import ActivationFunction
from neuralnetwork.neural_network import NeuralNetwork
if __name__ == '__main__':
activation_function = ActivationFunction(neural_classifier.sigmoid, neural_classifier.derivative_sigmoid)
#Topologia simples, 1 neuronio entrada, 1 de saida e 1 na camada oculta
topology = [1, 1, 1]
#Inicializa rede neural sem neuronios de bias (para facilitar a verificacao do gradiente)
neural_network = NeuralNetwork(topology, activation_function, alpha=0.15, has_bias_neurons=False)
inputs = [1.5]
expected_output = [1]
##########################################
# Shumbay os valores dos pesos para bater com o exemplo dado. Por padrao, a rede inicializaria em random
# Comentar para inicializacao randomica
neural_network.layers[0].neurons[0].output_synapses[0].weight = 0.39
neural_network.layers[1].neurons[0].output_synapses[0].weight = 0.94
##########################################
print "Testing gradient calculation. Inputs:"
print inputs
print "Expected output:"
print expected_output
print "Topology:"
print topology
print "Evaluating... Weights:"
weights = neural_network.get_weights()
print weights
print "Network output:"
real_output = neural_network.evaluate(inputs)
print real_output
print "Network Cost (J):"
cost = neural_network.get_cost(expected_output)
print cost
print "Running backpropagation..."
neural_network.backpropagate(expected_output)
print "Gradients:"
gradients = neural_network.get_weight_gradients()
print gradients
epsilon = 0.000005
print "Estimating gradients using epsilon = " + str(epsilon)
gradient_estimates = neural_network.estimate_gradients(epsilon, inputs, expected_output)
print "Estimated gradients:"
print gradient_estimates
|
3932dd0a0cb7d95fac248801590ad028896de2ef
|
masterfung/LPTHW
|
/ex31.py
| 1,248 | 4.3125 | 4 |
print 'You are at crossroad and you have to choose from three paths. What do you choose (left, middle, or right)?'
userChoice = raw_input('Please enter your choice: ')
if userChoice.lower() == 'left':
print 'The giant zebra grabbed you and ate you like an eggplant. But all hope is not lost. You have two possible actions to try.'
action = raw_input('Will you scream or will you cry? ')
if action.lower() == 'scream':
print 'The giant zebra got pissed and decided not to spare you anymore. Doom! Your end is now! Num NUM NOM'
else:
print 'The giant zebra saw you are sad and decided to let you go. He came back and licked you while he apologizes. You are free, he said.'
elif userChoice.lower() == 'center':
print 'You came across three more choices, you have to eat either the berry, the cheese, or orange.'
food = raw_input('What will you eat? (berry, cheese, or orange) ')
if food.lower() == 'berry':
print 'The berry turned into a frog and choked you to death. Game Over!'
elif food.lower() == 'cheese':
print 'You are safe and you continue to walk. Freedom ahead. :)'
else:
print 'That was not an orange but a tranformation potion. You are now a chili pepper. Good luck.'
else:
print 'You are lost. Who knows. Who will?'
|
9fd2aea905257e82dd5c8fe9eba12b89dbfb6114
|
enisnazif/battleships
|
/bots/Notorious_B_O_T.py
| 4,933 | 3.734375 | 4 |
import random
from typing import List, Dict, Union, Tuple
from config import BOARD_SIZE
from game_types import Bot, Board, Point, Ship, ShipType, Orientation
class Notorious_B_O_T(Bot):
""" Hello! I am a dumb sample bot who places its ships randomly and shoots randomly! """
def __init__(self):
super().__init__()
self.my_shots = []
self.map = [[''] * 10 for i in range(10)]
self.seenX = [0] * 10
self.seenY = [0] * 10
def get_ship_placements(self, ships: List[Ship]) -> List[Tuple[Ship, Point, Orientation]]:
"""
Returns a set of point at which a ship will be placed. For each ship, you must return a tuple of [Ship, Point, Orientation],
where Point corresponds to the bottom left corner of the Ship, e.g:
-
x - - - or -
-
x
and Orientation is one of Orientation.Vertical and Orientation.Horizontal
:param ships: A List of Ship which your bot should return placements for
:return: A list of placements for each ship in 'ships'
"""
ships = sorted(ships, key=lambda x: len(x.horizontal_offsets))
placed = [
(ships[0], Point(0, 6), Orientation.Horizontal),
(ships[1], Point(1, 1), Orientation.Vertical),
(ships[2], Point(6, 2), Orientation.Horizontal),
(ships[3], Point(3, 8), Orientation.Horizontal),
(ships[4], Point(1, 5), Orientation.Horizontal),
]
return placed
# # Perform random ship placement
# while True:
# placements = []
# for ship in ships:
# random_orientation = random.choice(list(Orientation))
# random_point = Point(
# random.randrange(0, BOARD_SIZE), random.randrange(0, BOARD_SIZE)
# )
#
# placements.append((ship, random_point, random_orientation))
#
# if Board.is_valid_ship_placement(placements):
# break
#
# return placements
def get_best_shot(self):
squares = [] # tuple of (x, y, score)
bestScore = -999999
best = []
for x in range(10):
for y in range(10):
score = 0
if self.map[x][y]: # if we've already fired at this square, skip
continue
if x > 0 and self.map[x-1][y] == 'H':
score += 10
if x > 1 and self.map[x-2][y] == 'H':
score += 10
elif x > 1 and self.map[x-2][y] == 'H':
score += 10
if x < 9 and self.map[x+1][y] == 'H':
score += 10
if x < 8 and self.map[x+2][y] == 'H':
score += 10
if y > 0 and self.map[x][y-1] == 'H':
score += 10
if y > 1 and self.map[x][y-2] == 'H':
score += 10
if y < 9 and self.map[x][y+1] == 'H':
score += 10
if y < 8 and self.map[x][y+2] == 'H':
score += 10
score -= self.seenX[x]
score -= self.seenY[y]
if ((x == 0 or self.map[x-1][y] == 'M') and
(x == 9 or self.map[x+1][y] == 'M') and
(y == 0 or self.map[x][y-1] == 'M') and
(y == 9 or self.map[x][y+1] == 'M')):
score -= 10
if score == bestScore:
best.append(Point(x, y))
if score > bestScore:
bestScore = score
best = [Point(x, y)]
return random.sample(best, 1)[0]
def get_shot(self) -> Point:
"""
Called each round by the game engine to get the next point to shoot on the opponents board.
:return: The next point to shoot on the opponents board
"""
# Get the status of your last shot - could be useful in planning your next move!
last_shot_status = self.last_shot_status
# Example response:
# {
# 'shot': Point(4, 5), # type: Point
# 'is_hit': True, # type: bool
# 'is_sunk' True, # type: bool
# 'ship_sunk': <ShipType.Battleship: 'Battleship'>, # type: ShipType
# 'error': None # type: Union[None, Exception]
# }
if last_shot_status['shot'] is not None:
lastp = last_shot_status['shot']
if last_shot_status['is_sunk']:
self.map[lastp.x][lastp.y] = 'S'
elif last_shot_status['is_hit']:
self.map[lastp.x][lastp.y] = 'H'
else:
self.map[lastp.x][lastp.y] = 'M'
p = self.get_best_shot()
self.my_shots.append(p)
self.seenX[p.x] += 1
self.seenY[p.y] += 1
return p
|
41474e9e57bfc3ad78f908f587b448a6c7fded13
|
euni-brownie/python-workbook
|
/average.py
| 454 | 3.765625 | 4 |
from Student import Student
continued = ""
student_list = []
student_info = 0
while(student_info != "1") :
student_info = input("학생정보입력(그만두기:1) >")
if(student_info == "1") : break
student_list.append(Student(student_info[0],student_info[1],student_info[2],student_info[3]))
print("이름 총점 평균 석차")
for std in student_list:
print (std.name, std.get_total_score(), std.get_average(),end=" ")
|
fb96da73cb49f829f9d4038cb8dddcd2330e9a9e
|
alexoah/PythonPlayground
|
/W3School-PyExercises/PY-IfElse/pyIfElseE8.py
| 310 | 3.578125 | 4 |
"""
from PYTHON If...Else: Exercise 8 ( https://www.w3schools.com/python/exercise.asp?filename=exercise_ifelse8 )
question:
Use the correct short hand syntax to put the following statement on one line:
if 5 > 2:
print("Five is greater than two!")
"""
if 5 > 2: print("Five is greater than two!")
|
2d1e6490abb63d6d47de12d5972fcf7c52a24e21
|
SafonovMikhail/python_000577
|
/001132StepikITclassPy/Stepik001132ITclassPyсh05p03st03TASK02_20210216_quadrant.py
| 1,448 | 4.5625 | 5 |
'''
В теории к уроку есть задача про определение четверти по введенным координатам x и y. Тебе необходимо исправить и дополнить программу, так, чтобы она не только определяла четверти, но и писала бы другие ответы: Положительная абсцисса, Отрицательная ордината, Начало координат и т.д.
Sample Input 1:
0
0
Sample Output 1:
Начало координат
Sample Input 2:
-10
0
Sample Output 2:
Отрицательная абсцисса
Sample Input 3:
10.12
190
Sample Output 3:
Первая четверть
'''
x = float(input())
y = float(input())
if x == 0 and y == 0:
print('Начало координат')
elif x == 0 and y != 0:
if y > 0:
print('Положительная ордината')
else:
print('Отрицательная ордината')
elif y == 0 and x != 0:
if x > 0:
print('Положительная абсцисса')
else:
print('Отрицательная абсцисса')
elif x > 0 and y > 0:
print('Первая четверть')
elif x < 0 and y > 0:
print('Вторая четверть')
elif x < 0 and y < 0:
print('Третья четверть')
else:
print('Четвертая четверть')
|
2bfebb797ff74ce393f29cada7ae4b76a5436c9e
|
noserider/school_files
|
/Python-Next-steps/Python Next steps/L2 Loops/guessGame.py
| 356 | 4.28125 | 4 |
answer = "8"
guess = input("Guess a number: ")
# while() loop code goes here
# while() loop code ends
print("\nWell done, that's right!")
input("\nPress ENTER to exit program")
# EXTENSION ACTIVITY
# 1. Let the user put in the answer first (so it's not always 8)
# 2. Use a counter to count how many guesses it took to get the right answer
|
02bbd4a0586531b083c7f17effb451eb69af936a
|
utsadev/ProgEngIIHW
|
/Week4_py/if-elif-example.py
| 931 | 3.90625 | 4 |
print "Welcome to Hotel ABC"
print "How many rooms do you want to reserve?"
roomNo=int(raw_input())
print "How many nights do you want to stay?"
nightNo=int(raw_input())
print "We have King Room ($100/night), and Queen Room ($80/night)"
print "Press 1 to select King Room, and 2 to select Queen Room"
roomType=int(raw_input())
King=100
Queen=80
total=0.0
if (roomType==1):
total=roomNo*nightNo*King
if (roomNo>3 and nightNo<=3):
total=total*0.9
elif (roomNo<=3 and nightNo>3):
total = total * 0.9
elif (roomNo>3 and nightNo>3):
total = total * 0.8
else:
pass
elif(roomType==2):
total = roomNo * nightNo * Queen
if (roomNo > 3 and nightNo <= 3):
total = total * 0.9
elif (roomNo <= 3 and nightNo > 3):
total = total * 0.9
elif (roomNo > 3 and nightNo > 3):
total = total * 0.8
else:
pass
print "Your total Bill is: %.2f"%total
|
c5ec33c64182ef2ccc89813e29753caffc8898ba
|
liuyonggg/youngcoders
|
/week1.py
| 180 | 3.5625 | 4 |
print ("Hello", "World!")
print ("Hello " + "World")
print ("Hello %s" % "World")
print ("2 + 3 =", 2+3)
print ("I'd much rather you 'not'.")
print ('I "said" do not touch this.')
|
faabb8972230daae0d2348a84a0a7050b8862ba6
|
galayko/euler-python
|
/problem14.py
| 945 | 4.125 | 4 |
#!/usr/bin/env python
# The following iterative sequence is defined for the set of positive
# integers:
# n = n/2 (n is even)
# n = 3n + 1 (n is odd)
# Using the rule above and starting with 13, we generate the
# following sequence:
# 13 40 20 10 5 16 8 4 2 1
# It can be seen that this sequence (starting at 13 and finishing at 1)
# contains 10 terms. Although it has not been proved yet (Collatz
# Problem), it is thought that all starting numbers finish at 1.
# Which starting number, under one million, produces the longest chain?
# NOTE: Once the chain starts the terms are allowed to go above one million.
def Collatz(num):
res = []
while num!=1:
res.append(num)
if num%2==0:
num = num/2
else:
num = 3*num+1
res.append(1)
return res
cnt = 0
res = 0
for i in range(1,1000000):
l = len(Collatz(i))
if cnt<l:
cnt = l
res = i
print "Res=", res
|
d8c0929193adf3aee997b4252a895237c2f97b3c
|
LarisaOvchinnikova/Python
|
/1 - Python-2/19 - datetime/HW19/3a - Get weekdays.py
| 227 | 4.25 | 4 |
# Print a full weekday's name of the first day of every month
from datetime import date
month = 1
first_weekday = [date(2020, month, 1) for month in range(1,13)]
for day in first_weekday:
print(day.strftime("%B %d: %A"))
|
fe6e5ba36bc8b2339d7a27f351d65cebd18a0c6d
|
stephanieeechang/PythonGameProg
|
/PyCharmProj/CupcakeMachine.py
| 1,897 | 3.984375 | 4 |
'''
The program runs a cupcake machine
'''
import time
from threading import Thread
import signal
chocolate = 50
vanilla = 30
redVelvet = 45
cherryP = 5
frostingP = 10
cTime = 10
vTime = 6
rTime = 8
cherry = False
frosting = False
productTime = 0
productPrice = 0
start = False
TIMEOUT = 10
def menu():
#flavor
print('Choose a product: ')
flavor = input('1-Red Velvet 2-Chocolate 3-Vanilla\n')
#cherry
cherryYN = raw_input('Cherry? (Y/N): ')
if(cherryYN == 'Y'):
cherry = True
elif(cherryYN == 'N'):
cherry = False
else:
print('Invalid input!')
restart()
#frosting
frostingYN = raw_input('Frosting? (Y/N): ')
if(frostingYN == 'Y'):
frosting = True
elif(frostingYN == 'N'):
frosting = False
else:
print('Invalid input!')
restart()
#price
if(flavor == 1):
price = redVelvet
time = rTime
elif(flavor == 2):
price = chocolate
time = cTime
elif(flavor == 3):
price = vanilla
time = vTime
else:
print('Invalid input!')
restart()
if(cherry):
price += cherryP
if(frosting):
price += frostingP
return price, time
def check():
print('START or CANCEL? You have 10 seconds to input...')
signal.alarm(TIMEOUT)
answer = raw_input()
signal.alarm(0)
if answer == 'START':
start = True
countdown()
print('Your cupcake is ready!')
return start
else:
print('Restarting...')
restart()
def countdown():
for t in range(productTime, 0, -1):
print(str(t) + 'seconds left till your cupcake ready...')
time.sleep(1)
def restart():
productPrice, productTime = menu()
print('The price of your cupcake is ' + str(productPrice) + ' NTD.')
Thread(target=check).start()
restart()
|
2db9f4c84c86fe945dad05166a20d021abb73e03
|
adrianadames/GraphsRedo
|
/GraphsRedo/projects/graph/src/draw1.py
| 15,010 | 3.546875 | 4 |
# In draw.py, implement the BokehGraph class. The constructor should accept a
# Graph object (as you implemented in part 1), and optionally other parameters
# configuring e.g. graphical settings. The show method should use Bokeh to
# generate and display HTML that draws the graph - the included Pipfile will
# install Bokeh and necessarily dependencies.This is purposefully open-ended,
# so feel free to get creative. But also, ask questions to avoid being blocked,
# and generally discuss and work from lecture examples.
"""
General drawing methods for graphs using Bokeh.
"""
import math
from bokeh.io import show, output_file
from bokeh.plotting import figure
from bokeh.models import GraphRenderer, StaticLayoutProvider, Circle, LabelSet, ColumnDataSource
from bokeh.palettes import Spectral8
from graph1 import Graph
############## Attempt 2 (code heavily based on BokehGraph implementation in graphs day) ########################
# NOTE: I didn't finish this first attempt at the BokehGraph class. In interest of time
# I decided to pause and implement the solution code from graph lecture day 3/4.
class BokehGraph:
"""Class that takes a graph and exposes drawing methods."""
def __init__(self, graph):
self.graph = graph
def drawGraph(self):
graph = self.graph
N = len(graph.vertices)
node_indices = list(graph.vertices)
plot = figure(title= "Graph Layout Demonstration", x_range= (-1.1,10.1), y_range=(-1.1,10.1), tools = '', toolbar_location = None )
graph_renderer = GraphRenderer()
graph_renderer.node_renderer.data_source.add(node_indices, 'index')
graph_renderer.node_renderer.data_source.add([graph.vertices[vertex_id].color for vertex_id in graph.vertices], 'color')
graph_renderer.node_renderer.glyph = Circle(radius = 0.5, fill_color = 'color')
start_indices = []
end_indices = []
for vertex_id in graph.vertices: #here we're looking at the keys of our vertex dictionary
for edge_end in graph.vertices[vertex_id].edges:
start_indices.append(vertex_id)
end_indices.append(edge_end)
graph_renderer.edge_renderer.data_source.data = dict(
start = start_indices,
end = end_indices
)
### start of layout code
x = [graph.vertices[vertex_id].x for vertex_id in graph.vertices]
y = [graph.vertices[vertex_id].y for vertex_id in graph.vertices]
graph_layout = dict(zip(node_indices, zip(x,y)))
graph_renderer.layout_provider = StaticLayoutProvider(graph_layout = graph_layout)
plot.renderers.append(graph_renderer)
labelSource = ColumnDataSource(data = dict(x=x, y=y, names = [graph.vertices[vertex_id].value for vertex_id in graph.vertices]))
labels = LabelSet(x= 'x', y = 'y', text = 'names', level = 'glyph',
text_align= 'center', text_baseline = 'middle', source = labelSource, render_mode = 'canvas' )
plot.add_layout(labels)
output_file('graph1.html')
show(plot)
# class BokehGraph:
# """Class that takes a graph and exposes drawing methods."""
# def __init__(self, graph):
# self.graph = graph
# def drawGraph(self):
# pass
# #test
# graph1 = Graph() # Instantiate your graph
# graph1.add_vertex(0)
# graph1.add_vertex(1)
# graph1.add_vertex(2)
# graph1.add_vertex(3)
# graph1.add_edge(0, 1)
# graph1.add_edge(0, 3)
# bokehGraph1 = BokehGraph(graph1)
# bokehGraph1.drawGraph()
# ###### Bookeh example for Visualizing Network Graphs (https://bokeh.pydata.org/en/latest/docs/user_guide/graph.html) ##########
# import math
# from bokeh.io import show, output_file
# from bokeh.plotting import figure
# # "Bokeh uses a separate LayoutProvider model in order to supply the coordinates of a graph in Cartesian space. Currently the only built-in provider is the StaticLayoutProvider model, which contains a dictionary of (x,y) coordinates for the nodes.""
# from bokeh.models import GraphRenderer, StaticLayoutProvider, Oval
# from bokeh.palettes import Spectral8
# N = 8
# node_indices = list(range(N))
# # figure class (imported above) creates a new Figure for plotting. class Figure(*ark, **kw) is a subclass of Plot that simplifies plot creation with default axes, grids, tools, etc.
# plot = figure(title='Graph Layout Demonstration', x_range=(-1.1,1.1), y_range=(-1.1,1.1),
# tools='', toolbar_location=None)
# # GraphRenderer class: maintains separate sub-GlyphRenderers for the graph nodes and the graph edges. This allows for customizing the nodes by modifying the GraphRenderer’s node_renderer property.
# # -edge_renderer attribute: Instance of GlyphRenderer class containing an MultiLine Glyph that will be rendered as the graph edges.
# # -node_renderer attribute: Instance of GlyphRenderer class containing an XYGlyph (point-like Glyph) that will be rendered as the graph nodes.
# graph = GraphRenderer()
# # data_source attribute of Glyphrenderer: Local data source to use when rendering glyphs on the plot. Instance of the DataSource class. The DataSource class is a an abstract base class used to help organize the hierarchy of Bokeh model types. It is not useful to instantiate on its own.
# # Two requirements for data sources belonging to node_renderer and edge_renderer
# # -The ColumnDataSource (i.e. a JSON dict that maps names to arrays of values) associated with the node sub-renderer must have a column named "index" that contains the unique indices of the nodes.
# # -The ColumnDataSource associated with the edge sub-renderer has two required columns: "start" and "end". These columns contain the node indices of for the start and end of the edges.
# # ColumnDataSource is a bokeh class that maps names of columns to sequences or arrays. It's a fundamental data structure of Bokeh. Most plots, data tables, etc. will be driven by a ColumnDataSource.
# graph.node_renderer.data_source.add(node_indices, 'index')
# # spectral8 (a color palette) specifies the range of colors used for the plot markers
# graph.node_renderer.data_source.add(Spectral8, 'color')
# # specifies the shape and style of the plot markers (i.e. graph nodes in our case)
# # GlyphRenderer class attr glyph: Instance of Glyph class. Specifies glyph to render, in conjunction with the supplied data source and ranges.
# graph.node_renderer.glyph = Oval(height=0.1, width=0.2, fill_color='color')
# # The ColumnDataSource associated with the edge sub-renderer has two required columns: "start" and "end". These columns contain the node indices of for the start and end of the edges.
# # data attribute of ColumnDataSource class : Mapping of column names to sequences of data. The data can be, e.g, Python lists or tuples, NumPy arrays, etc.
# graph.edge_renderer.data_source.data = dict(
# start=[0]*N,
# end=node_indices)
# ### start of layout code
# # circ here is a list populated with the different angles of a circle (i.e. 0 to 2*pi)
# circ = [i*2*math.pi/8 for i in node_indices]
# x = [math.cos(i) for i in circ]
# y = [math.sin(i) for i in circ]
# # the zip() method: The purpose of zip() is to map the similar index of multiple containers so that they can be used just using as single entity.
# graph_layout = dict(zip(node_indices, zip(x, y)))
# # StaticLayoutProvider base class: bokeh.models.graphs.LayoutProvider (abstract data type. not useful on its own.)
# # graph_layout attribute of StaticLayoutProvider: The coordinates of the graph nodes in cartesian space. The dictionary keys correspond to a node index and the values are a two element sequence containing the x and y coordinates of the node. (property type: Dict ( Either ( String , Int ), Seq ( Any ) ))
# # By default the StaticLayoutProvider will draw straight-line paths between the supplied node positions. In order to supply explicit edge paths you may also supply lists of paths to the edge_renderer bokeh.models.sources.ColumnDataSource. The StaticLayoutProvider will look for these paths on the "xs" and "ys" columns of the data source. Note that these paths should be in the same order as the "start" and "end" points.
# graph.layout_provider = StaticLayoutProvider(graph_layout=graph_layout)
# # plot here is an instantiation of the Figure class (A subclass of Plot that simplifies plot creation with default axes, grids, tools, etc.)
# # renderers is an attribute of Plot. Description:A list of all renderers for this plot, including guides and annotations in addition to glyphs and markers. property type: List ( Instance ( Renderer ) ). Recall that Renderer is an abstract base class used to help organize the hierarchy of Bokeh model types. It is not useful to instantiate on its own.
# plot.renderers.append(graph)
# # output_file(): Configures the default output state to generate output saved to a file when show() is called. (https://bokeh.pydata.org/en/latest/docs/reference/io.html#bokeh.io.output_file)
# output_file('graphEx1.html')
# # show(): Immediately displays a Bokeh object or application. (https://bokeh.pydata.org/en/latest/docs/reference/io.html#bokeh.io.show)
# show(plot)
# ############## Attempt 1 ########################
# # NOTE: I didn't finish this first attempt at the BokehGraph class. In interest of time
# # I decided to pause and implement the solution code from graph lecture day 2.
# class BokehGraph:
# """Class that takes a graph and exposes drawing methods."""
# def __init__(self, graph):
# self.graph = graph
# def drawGraph(self):
# graph = self.graph
# N = len(graph.vertices)
# node_indices = list()
# for i in graph.vertices:
# node_indices.append(i.value)
# # figure class (imported above) creates a new Figure for plotting. class Figure(*ark, **kw) is a subclass of Plot that simplifies plot creation with default axes, grids, tools, etc.
# plot = figure(title = 'Adrian\'s Graph Demo', x_range = (-10,10), y_range = (-10,10))
# # GraphRenderer class: maintains separate sub-GlyphRenderers for the graph nodes and the graph edges. This allows for customizing the nodes by modifying the GraphRenderer’s node_renderer property.
# # -edge_renderer attribute: Instance of GlyphRenderer class containing an MultiLine Glyph that will be rendered as the graph edges.
# # -node_renderer attribute: Instance of GlyphRenderer class containing an XYGlyph (point-like Glyph) that will be rendered as the graph nodes.
# graphRenderer = GraphRenderer()
# # data_source attribute of Glyphrenderer: Local data source to use when rendering glyphs on the plot. Instance of the DataSource class. The DataSource class is a an abstract base class used to help organize the hierarchy of Bokeh model types. It is not useful to instantiate on its own.
# # Two requirements for data sources belonging to node_renderer and edge_renderer
# # -The ColumnDataSource (i.e. a JSON dict that maps names to arrays of values) associated with the node sub-renderer must have a column named "index" that contains the unique indices of the nodes.
# # -The ColumnDataSource associated with the edge sub-renderer has two required columns: "start" and "end". These columns contain the node indices of for the start and end of the edges.
# # ColumnDataSource is a bokeh class that maps names of columns to sequences or arrays. It's a fundamental data structure of Bokeh. Most plots, data tables, etc. will be driven by a ColumnDataSource.
# graphRenderer.node_renderer.data_source.add(node_indices, 'index')
# # # spectral8 (a color palette) specifies the range of colors used for the plot markers
# # graphRenderer.node_renderer.data_source.add(Spectral8, 'color')
# # specifies the shape and style of the plot markers (i.e. graph nodes in our case)
# # GlyphRenderer class attr glyph: Instance of Glyph class. Specifies glyph to render, in conjunction with the supplied data source and ranges.
# graphRenderer.node_renderer.glyph = Circle(radius=0.2)
# # The ColumnDataSource associated with the edge sub-renderer has two required columns: "start" and "end". These columns contain the node indices of for the start and end of the edges.
# # data attribute of ColumnDataSource class : Mapping of column names to sequences of data. The data can be, e.g, Python lists or tuples, NumPy arrays, etc.
# start_indices = []
# end_indices = []
# for vertex in graph.vertices:
# for edge_end in graph.vertices[vertex].adjVertices:
# start_indices.append(vertex.value)
# end_indices.append(edge_end.value)
# # print(start_indices)
# # print(end_indices)
# # print(start_indices)
# # print(end_indices)
# graphRenderer.edge_renderer.data_source.data = dict(
# start=start_indices,
# end=end_indices)
# ### start of layout code
# x = [graph.vertices[vertex].x for vertex in graph.vertices]
# y = [graph.vertices[vertex].y for vertex in graph.vertices]
# x = []
# y = []
# for vertex in graph.vertices:
# x.append(vertex.x)
# y.append(vertex.y)
# # the zip() method: The purpose of zip() is to map the similar index of multiple containers so that they can be used just using as single entity.
# graph_layout = dict(zip(node_indices, zip(x, y)))
# # StaticLayoutProvider base class: bokeh.models.graphs.LayoutProvider (abstract data type. not useful on its own.)
# # graph_layout attribute of StaticLayoutProvider: The coordinates of the graph nodes in cartesian space. The dictionary keys correspond to a node index and the values are a two element sequence containing the x and y coordinates of the node. (property type: Dict ( Either ( String , Int ), Seq ( Any ) ))
# # By default the StaticLayoutProvider will draw straight-line paths between the supplied node positions. In order to supply explicit edge paths you may also supply lists of paths to the edge_renderer bokeh.models.sources.ColumnDataSource. The StaticLayoutProvider will look for these paths on the "xs" and "ys" columns of the data source. Note that these paths should be in the same order as the "start" and "end" points.
# graph.layout_provider = StaticLayoutProvider(graph_layout=graph_layout)
# plot.renderers.append(graphRenderer)
# output_file('graphEx1.html')
# show(plot)
|
ead984afdc6d3600f684e4f87796df11646eadd8
|
angel-becerra/trabajo10-Becerra_Chancafe
|
/app2.py
| 885 | 3.5625 | 4 |
import libreria
#aplicacion para guardar
def agregar_curso():
curso=libreria.pedir_nombre("ingrese curso:")
nota=libreria.pedir_numero("ingrese nota:",1,100)
contenido=curso + "-" + str(nota)+ "\n"
libreria.guardar_datos("notas.txt", contenido,"a")
print("datos guardados con exito")
def dar_informacion():
datos=libreria.obtener_datos("notas.txt")
if(datos!= ""):
print(datos)
else:
print("archivo sin datos")
opc=0
max=3
while(opc != max):
print("########### MENU ##########")
print("1.agregar curso #")
print("2.dar informacion #")
print("3.salir #")
print("##############################")
opc=libreria.pedir_numero("ingrese opcion:",1,3)
if( opc==1 ):
agregar_curso()
if (opc==2):
dar_informacion()
#fin_menu
print("fin del programa")
|
b107bbcb4242f3239ba8a3bdf07241208edc56e4
|
ATJUstudent/DataManagePlatForm
|
/server/importdatafile.py
| 11,673 | 3.53125 | 4 |
"""
Interface for import data into database by excel file <.xlsx> and csv file <.csv>
Please look forward to more features
"""
# Author: Wang Chuhan([email protected])
# Time: 2021.03.14
# for Data Manage Platform(TJU CS2018-3)
from openpyxl import load_workbook
from sqlcreator import SqlCreator
import csv
import pymysql
import datetime
import json
class FileImportTool(SqlCreator):
""" Import data in excel file <.xlsx> and csv file <.csv>
Interface for creating database according to excel file
Interface for creating table in an existed database according to excel file
Interface for inserting data into an existed table according to excel file
Interface for inserting data into an existed table according to csv file
Interface for rollback the new database
Interface for rollback the new table
"""
def deal_excel_1(self, excel, key_number=0):
""" create database according to excel file
Function will automatically generate database and import data according to excel data
Parameters
----------
excel: str
path of excel file <.xlsx>
key_number: int
be able to specify the number of the first column as the primary key, which is the first column by default
Notes
-----
Excel file name cannot be consistent with the existing database.
You can specify which column as the primary key column, but in each workbook this number must be same.
(The default is 0)
"""
database = excel.split('.')[0]
json_template = """
{
"database": "%s",
"charset": "utf8mb4"
}
"""
json_create_database = json_template % database
self.create_database_sql(json_create_database)
print("Database '%s' Create Status Code:" % database, self.commit_all())
try:
self.deal_excel_2(excel, database, key_number)
except ReferenceError:
self.rollback_database_import(database)
def deal_excel_2(self, excel, database_name, key_number=0):
""" create table according to excel file
Function creates the data table automatically
Parameters
----------
excel: str
path of excel file <.xlsx>
database_name: str
name of an existed database
key_number: int
be able to specify the number of the first column as the primary key, which is the first column by default
Notes
-----
You can specify which column as the primary key column, but in each workbook this number must be same.
(The default is 0)
"""
workbook = load_workbook(excel, data_only=True)
sheets = workbook.sheetnames
for sheet in sheets:
field_template = {}
json_template = {sheet: field_template}
work_sheet = workbook[sheet]
value_row = []
for row in work_sheet.rows:
value = [cell.value for cell in row]
value_row.append(value)
num = 0
for v in value_row[1]:
if num == key_number:
e = 'PRI'
else:
e = ''
if type(v) == int:
field_template[num] = {'Field': value_row[0][num], 'Type': 'INT', 'Key': e}
elif type(v) == float:
field_template[num] = {'Field': value_row[0][num], 'Type': 'FLOAT', 'Key': e}
elif type(v) == str:
field_template[num] = {'Field': value_row[0][num], 'Type': 'VARCHAR(255)', 'Key': e}
elif type(v) == datetime.datetime:
field_template[num] = {'Field': value_row[0][num], 'Type': 'DATETIME', 'Key': e}
elif type(v) == datetime.date:
field_template[num] = {'Field': value_row[0][num], 'Type': 'DATE', 'Key': e}
elif type(v) == datetime.time:
field_template[num] = {'Field': value_row[0][num], 'Type': 'TIME', 'Key': e}
else:
raise TypeError('不支持的数据类型!')
num = num + 1
json_create_table = json.dumps(json_template)
self.create_table_sql(json_create_table, database_name)
print("Table '%s' Create Status Code:" % sheet, self.commit_all())
num = 0
json_template = {}
for values in value_row[1:]:
value = [v for v in values]
value_num = len(value)
value_d = {}
for i in range(value_num):
if value[i] is None:
self.rollback_table_import(database_name, sheet)
raise ReferenceError('表中数据存在空存档,请修改后重试')
if type(value[i]) == datetime.datetime or type(value[i]) == datetime.date \
or type(value[i]) == datetime.time:
value_d[value_row[0][i]] = str(value[i]).split('.')[0]
else:
value_d[value_row[0][i]] = value[i]
json_template['%d' % num] = value_d
num = num + 1
json_insert_table = json.dumps(json_template, ensure_ascii=False)
self.create_object_sql(json_insert_table, database_name, sheet)
print("Insert Into Table '%s' Status Code:" % sheet, self.commit_all())
def deal_excel_3(self, excel, database_name, table_name, sheet_seq=0):
""" insert data into table according to excel file <.xlsx>
Function automatically matches column and database properties by name
Parameters
----------
excel: str
path of excel file <.xlsx>
database_name: str
name of an existed database
table_name: str
name of an existed table
sheet_seq: int
the serial number of the imported workbook
Notes
-----
if not specify the serial number of imported workbook, it will be defaulted by 0 (the first work sheet)
"""
workbook = load_workbook(excel, data_only=True)
sheets = workbook.sheetnames
sheet = workbook[sheets[sheet_seq]]
value_row = []
for row in sheet.rows:
value = [cell.value for cell in row]
value_row.append(value)
self.insert_value_row(value_row, database_name, table_name)
def deal_csv(self, csv_file, database_name, table_name):
""" insert data into table according to csv file <.csv>
Function automatically matches column and database properties by name
Parameters
----------
csv_file: str
path of csv file <.csv>
database_name: str
name of an existed database
table_name: str
name of an existed table
"""
with open(csv_file) as f_csv:
file = csv.reader(f_csv)
value_row = []
for row in file:
value = [v.replace(' ', '') for v in row]
value_row.append(value)
f_csv.close()
self.insert_value_row(value_row, database_name, table_name)
def insert_value_row(self, value_row, database_name, table_name):
""" inserts the input data into the specified table
Parameters
----------
value_row: list
the input data
database_name: str
name of an existed database
table_name: str
name of an existed table
Notes
-----
the value of value_row[0] must be the name of column
"""
input_name = []
for value in value_row[0]:
input_name.append(value)
accept_name = []
for key in self.table_columns(database_name, table_name).fetchall():
accept_name.append(key['Field'])
try:
auto_map = my_match_list(input_name, accept_name) # <input -> accept>
except ValueError:
raise ReferenceError('两张表所含数据名称不一一对应!')
except KeyError:
raise ReferenceError('两张表所含数据名称不一一对应!')
except ReferenceError:
raise Warning('输入数据不能对所有数据库属性赋值,可能会产生意想不到的错误!')
num = 0
json_template = {}
for values in value_row[1:]:
value = [v for v in values]
value_num = len(value)
value_d = {}
for i in range(value_num):
if value[i] is None:
raise ReferenceError('表中数据存在空存档,请修改后重试')
if type(value[i]) == datetime.datetime or type(value[i]) == datetime.date \
or type(value[i]) == datetime.time:
value_d[value_row[0][auto_map[i]]] = str(value[i]).split('.')[0]
else:
value_d[value_row[0][auto_map[i]]] = value[i]
json_template['%d' % num] = value_d
num = num + 1
json_insert_table = json.dumps(json_template, ensure_ascii=False)
self.create_object_sql(json_insert_table, database_name, table_name)
print(json_insert_table)
print("Insert Into Table '%s' Status Code:" % table_name, self.commit_all())
def rollback_database_import(self, database_name):
try:
self.commit_sql('DROP DATABASE %s;' % database_name)
except pymysql.err.Error:
print('表中数据存在空存档,请修改后重试')
raise ReferenceError('Rollback Import Error: Cannot drop database.')
def rollback_table_import(self, database_name, table_name):
try:
self.commit_sql('DROP TABLE %s.%s;') % (database_name, table_name)
except pymysql.err.Error:
print('表中数据存在空存档,请修改后重试')
raise ReferenceError('Rollback Import Error: Cannot drop table.')
def my_match_list(list1, list2):
list2_stack = {}
i = 0
for el in list2:
try:
list2_stack[el].append(list2.index(el, i, len(list2)))
i = i + 1
except KeyError:
list2_stack[el] = []
list2_stack[el].append(list2.index(el, i, len(list2)))
i = i + 1
result = {}
i = 0
for el in list1:
try:
result[i] = list2_stack[el].pop(0)
i = i + 1
except ValueError:
raise ValueError('Value Error: The number of elements in LIST1 and List2 is not equal!')
except KeyError:
raise ValueError('Key Error: There is no such element in List2!')
for key in list2_stack:
if list2_stack[key]:
raise ReferenceError('Reference Error: The two lists are not equal in length!')
return result
# # 测试用代码,取消注释使用
# if __name__ == '__main__':
# dict1 = {
# "ip": "127.0.0.1",
# "port": 3306,
# "database": "test",
# "username": "root",
# "password": "123456"
# }
# FileImportTool.init_config(dict1)
# it = FileImportTool()
# it.connect_db()
# # print(it.deal_excel_1(u'TotalData.xlsx'))
# it.rollback_database_import('totaldata')
# # print(it.deal_excel_2(u'TotalData.xlsx', 'totaldata'))
# # it.deal_excel_3(u'TotalData.xlsx', 'totaldata', 'sheet1', sheet_seq=2)
# # it.deal_csv('TotalData.csv', 'totaldata', 'sheet3')
|
b564685c9f5f899cd3562a8cdbe89415b006244c
|
Rimesh/Python-LPTHW
|
/ex13.py
| 390 | 3.703125 | 4 |
# Title: Exercise 13 - Parameters, Unpacking, Variables
# from Learn Python the hard way
# Date: 1st March 2017
# by Rimesh Jotaniya
# Description: taking command line arguments
from sys import argv
script, first, second, third = argv
print "The script is called: ", script
print "Your first variable is: ", first
print "Your second variable is: ", second
print "Your third variable is: ", third
|
9d0c2dc40b8d6b7c61825bcf62f9ddcedbd771e5
|
adstr123/ds-a-in-python-goodrich
|
/chapter-1/c22_dot_product.py
| 632 | 4.3125 | 4 |
def dot_product(list_a, list_b):
"""Performs dot product on two lists
:param list list_a: dot product left-hand side
:param list list_b: dot product right-hand side
:return int: dot product of input lists
"""
return sum([i * j for (i, j) in zip(list_a, list_b)])
print(dot_product([1, 2, 3], [1, 3, 3]))
"""
Time: O(n)
- zip does one calculation per pairs of elements in inputs
- loop does one calculation per pairs of elements in inputs
- sum does one calculation per pairs of elements in inputs
Space: O(n)
- n units of space for zip result
- n units of space for loop result
- n units of space for sum result
"""
|
38c12b3bd8c3b175ce68dd2e06eea42ea4fa7e4b
|
kobrv/projekt
|
/minigames.py
| 13,316 | 3.703125 | 4 |
import random
class Quest:
def __init__(self, mainloop):
self.mainloop = mainloop
self.completed = False
def run(self):
self.completed = self.mainloop()
def guess_number():
print("Twoim zadaniem będzie zgadnięcie, jaką liczbę mam na myśli.\nJest to liczba z zakresu od 1 do 100. \nGotowy?")
number = random.randint(1, 100)
i = 0
while int(i) < 10:
guess = int(input("Podaj liczbę od 1 do 100. "))
i += 1
if guess < number:
print("Podana liczba jest za mała!")
elif guess > number:
print("Podana liczba jest za duża!")
else:
print("Brawo! moja liczba to", number, "!")
return True
break
print("Ilość ruchów: ", 10 - i)
if i > 10:
print("Przegrałeś...")
return False
def hangman():
HANGMAN = (
"""
_________
|/ |
|
|
|
|
|
_|___
""",
"""
_________
|/ |
| (_)
|
|
|
|
_|___
""",
"""
_________
|/ |
| (_)
| |
|
|
|
_|___
""",
"""
_________
|/ |
| (_)
| \|
|
|
|
_|___
""",
"""
_________
|/ |
| (_)
| \|/
|
|
|
_|___
""",
"""
_________
|/ |
| (_)
| \|/
| |
|
|
_|___
""",
"""
_________
|/ |
| (_)
| \|/
| |
| _/
|
_|___
""",
"""
_________
|/ |
| (_)
| \|/
| |
| _/ \_
|
_|___
""")
loss = len(HANGMAN) - 1
WORDS = ("ATLANTYDA", "OCEAN", "SKARB", "TAJEMNICA", "ABRAKADABRA")
word = random.choice(WORDS)
so_far = "-" * len(word)
wrong = 0
used = []
print("Witaj w grze 'Wisielec'. Powodzenia!")
while wrong < loss and so_far != word:
print(HANGMAN[wrong])
print("\nWykorzystane litery:\n", used)
print("\nZagadka:\n", so_far)
guess = input("\n\nWprowadź literę: ")
guess = guess.upper()
while guess in used:
print("Już wykorzystałeś literę", guess)
guess = input("Wprowadź literę: ")
guess = guess.upper()
used.append(guess)
if guess in word:
print("\nBrawo!", guess, "znajduje się w moim słowie!")
new = ""
for i in range(len(word)):
if guess == word[i]:
new += guess
else:
new += so_far[i]
so_far = new
else:
print("\nNiestety,", guess, "nie występuje w moim słowie.")
wrong += 1
if wrong == loss:
print(HANGMAN[wrong])
print("\nPrzegrałeś...")
return False
else:
print("\nOdgadłeś moje słowo!")
return True
print("\nMoje słowo to", word)
def tic_tac_toe():
board = [1, 2, 3, 4, 5, 6, 7, 8, 9]
end = False
used = []
win_commbinations = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6))
def draw():
print(board[0], "|", board[1], "|", board[2])
print("---------")
print(board[3], "|", board[4], "|", board[5])
print("---------")
print(board[6], "|", board[7], "|", board[8])
print()
draw()
def player():
n = choose_number()
board[n] = "O"
used.append(n)
def computer():
n = random.randint(0,8)
board[n] = "X"
used.append(n)
def choose_number():
while True:
while True:
a = input("Gdzie chcesz postawić kółko? ")
try:
a = int(a)
a -= 1
if a in range(0, 9):
return a
else:
print("Podano miejsce poza planszą...")
continue
except ValueError:
print("\n To nie jest liczba! Spróbuj jeszcze raz. ")
continue
def check_board():
count = 0
for a in win_commbinations:
if board[a[0]] == board[a[1]] == board[a[2]] == "O":
print("Wygrałeś!")
return True
if board[a[0]] == board[a[1]] == board[a[2]] == "X":
print("Przegrałeś :(")
return False
for a in range(9):
if board[a] == "X" or board[a] == "O":
count += 1
if count == 9:
print("Remis...")
return False
while not end:
player()
draw()
end = check_board()
if end == True:
break
print("Ruch komputera:")
computer()
draw()
end == check_board()
if end == True:
break
print()
def rock_paper_scissors():
print("\n\nGra polega na zdobyciu 3 punktow w grze w papier/kamień/nożyce.")
print("ZASADY: Kamień bije nożyce, papier bije kamień, nożyce biją papier.")
MOVES = ("papier", "kamień", "nożyce")
score = 0
while score != 3 and score >= 0:
choice = input("Twoj ruch: ")
tries = 0
for move in MOVES:
if choice.lower() != move:
tries += 1
computer = MOVES[random.randint(0,2)]
print("Ruch przeciwnika: " + computer)
if choice.lower() == computer:
print("Remis!")
if choice.lower() == "kamień":
if computer.lower() == "papier":
print("Tracisz punkt :(")
score -= 1
elif computer.lower() == "nożyce":
print("Zdobywasz punkt!\n")
score += 1
if choice.lower() == "papier":
if computer.lower() == "nożyce":
print("Tracisz punkt :(")
score -= 1
elif computer.lower() == "kamień":
print("Zdobywasz punkt!\n")
score += 1
if choice.lower() == "nożyce":
if computer.lower() == "kamień":
print("Tracisz punkt :(")
score -= 1
elif computer.lower() == "papier":
print("Zdobywasz punkt!\n")
score += 1
print("Twoj wynik:", score,"\n")
if score == 3:
print("Wygrywasz!")
return True
else:
print("Przegrywasz...")
return False
def what_is_it():
ananas = ["""
\||/
\||/
.<><><>.
.<><><><>.
'<><><><>'
jgs '<><><>'""" , "ananas"]
carrot = [""" \/_
_/
(,;)
(,.)
(,/
|/""", "marchewka"]
spongebob = [
"""
.--..--..--..--..--..--.
.' \ (`._ (_) _ |
.' | '._) (_) |
\ _.')\ .----..---. /
|(_.' | / .-\-. \ |
\ 0| | ( O| O) | o|
| _ | .--.____.'._.-. |
\ (_) | o -` .-` |
| \ |`-._ _ _ _ _\ /
\ | | `. |_||_| |
| o | \_ \ | -. .-.
|.-. \ `--..-' O | `.`-' .'
_.' .' | `-.-' /-.__ ' .-'
.' `-.` '.|='=.='=.='=.='=|._/_ `-'.'
`-._ `. |________/\_____| `-.'
.' ).| '=' '='\/ '=' |
`._.` '---------------'
//___\ //___\
|| ||
LGB ||_.-. ||_.-.
(_.--__) (_.--__)""", "spongebob"]
mickey = [
"""
_..-----._
.' '.
/ \
| ;
| |
\ |
\ ;
_..----' /
.`-. .-'``'-. .-'
.'_ ` _ '. `'.
/ _` _ ` \ \ _...._
_ | / \ / \ | | .-' `'.
/ \ | | /| | /| | ;' \
| |_\ \_|/ \_|/ / ;
.\_/ `'-. /_...._ |
/ ` `\ |
| __ | /
\ / ` //'. .'
'._ .' .' `'-...-'`
`"'-.,__ ___.-' .-'
jgs `-._```` __..--'`
``````""", "myszka miki"]
words = [ananas, carrot, spongebob, mickey]
used = []
#counter = 0
points = 0
while True:
random_num = random.randint(0, 3)
word = words[random_num][0]
while word not in used:
input("Wcisnij enter, by wyswietlic obrazek!")
print("Twoj obrazek:")
print(word)
guess = input("\nCo to jest?: ")
if guess == words[random_num][1]:
print("Dobrze! Otrzymujesz punkt!")
points += 1
else:
print("Niestety nie, prawidlowa odpowiedz to " + words[random_num][1] + ".")
used.append(words[random_num][0])
#counter += 1
if points == 3:
return True
else:
return False
def quiz():
file = open("quiz.txt", "r")
questions = []
for line in file:
x = [file.readline().replace("\n", ""), file.readline().replace("\n", ""), file.readline().replace("\n", ""),
file.readline().replace("\n", ""), file.readline().replace("\n", ""), file.readline().replace("\n", "")]
questions.append(x)
print("Odpowiedz dobrze na wszystkie pytania, aby przejść dalej!")
number = 0
n = 0
input("Gotowy? Naciśnij ENTER.")
while True:
print("\nPytanie " + "#" + str(number + 1))
print(questions[n][0])
print("A. " + questions[n][1])
print("B. " + questions[n][2])
print("C. " + questions[n][3])
print("D. " + questions[n][4])
while True:
guess = input("Prawidłowa odpowiedź: ")
if guess.upper() == questions[n][5]:
print("\nDobra odpowiedz!")
number += 1
n += 1
break
else:
print("Zła odpowiedź. Spróbuj jeszcze raz.")
def cowsBulls():
print("\n\nZacznijmy od wyjasnienia zasad. W grze generowana jest 4-cyfrowa liczba. Twoim zadaniem jest ja zgadnac!")
print("Po kazdej rundzie zgadywania dowiadujesz sie, ile masz krowek, a ile bykow. Dostajesz byka za kazda liczbe")
print("we wlasciwym miejscu, a kazda krowe za blad. Przyjmujac, ze wylosowana liczba to 4176, przy zgadnieciu")
print("2186 dostaniesz dwie krowy i dwa byki, a przy 4186 jedna krowe i 3 byki. Jasne? To lecimy!\n")
number = str(random.randint(1000,9999))
while True:
cowsandbulls = [0,0]
playerGuess = input("Podaj zgadywana liczbe: ")
if len(playerGuess) != 4:
print("Liczba musi miec 4 cyfry!")
continue
try:
for i in range(len(number)):
if number[i] == playerGuess[i]:
cowsandbulls[1] += 1
else:
cowsandbulls[0] += 1
except ValueError:
print("Nalezy podac liczbe!")
continue
print("Krowki:", cowsandbulls[0], "| Byki:", cowsandbulls[1])
if cowsandbulls[1] == 4:
return True
def spelling_bee():
word_1 = ["rzeżucha", "Rzerzucha, żerzuha, rzeżucha, a może żeżucha???"]
word_2 = ["chihuahua", "cuachua, ciułała, chichuaua, chihuahua...?"]
word_3 = ["hipochondryk", "chipohondyk? hipochondryk? chipochondyk? hipohondryk?"]
word_4 = ["sufrażystka", "surfażystka, sufrażystka, surfarzystka, sufrarzystka?"]
word_5 = ["nowo narodzony", "nowonarodzony, nowo-narodzony, a może nowo narodzony?"]
word_6 = ["ponaddwuipółmiesięczny", "'ponad dwu i pół miesięczny', 'ponaddwu i pół miesięczny', ponad dwuipółmiesięczny, ponaddwuipółmiesięczny??"]
words_to_guess = [word_1, word_2, word_3, word_4, word_5, word_6]
used = []
points = 0
while points <=3 :
random_num = random.randint(0, 5)
to_guess = words_to_guess[random_num][0]
while to_guess not in used:
input("Wcisnij enter, by wyswietlic zagadkę!")
print("Jak to się pisze?:")
print(words_to_guess[random_num][1])
guess = input("\nPrawidłowy zapis: ")
if guess == words_to_guess[random_num][0]:
print("Dobrze! Otrzymujesz punkt!")
points += 1
else:
print("Niestety nie, prawidlowa odpowiedz to " + words_to_guess[random_num][0] + ".")
used.append(words_to_guess[random_num][0])
if points == 3:
return True
else:
return False
|
04170aa4019650ddd2c1ed83a81c6de94b874e90
|
keepsoftware/words2num
|
/tests/__init__.py
| 1,069 | 3.671875 | 4 |
import unittest
import words2num
class TestITN(unittest.TestCase):
"""Test inverse text normalization for numbers.
"""
def test_lang(self):
"""Test multi-lang handling of words2num.
"""
try:
words2num.w2n(None, lang='123')
assert False, "exception not raised for invalid language"
except NotImplementedError:
pass
try:
words2num.w2n("ninety", lang='en_TEST')
except NotImplementedError:
assert False, "no default fallback for region-specified language"
def test_failure(self):
"""Test error handling of words2num.
Make sure that invalid strings raise value errors.
"""
test_trials = ("1", "frogess", "telepromptx", "**", "-", "0", "sixes")
for trial in test_trials:
try:
words2num.w2n(trial)
assert False, "exception not raised for: {0}".format(trial)
except ValueError:
pass
if __name__ == '__main__':
unittest.main()
|
2e2a77e3902d91960f578fbc5711ca57b39bc897
|
mieva/DATASCIENCE
|
/APPLICATIONS/TUBULAR/AlgoSolution_EngCodingTest_trains.py
| 2,327 | 4.125 | 4 |
####### A possible algorithm to solve the coding test about train stations
####### PSEUDO CODE!
# Main function that read inputs and call the recursive function to find the required time
def FindPath():
import sys
data = sys.stdin.readlines()
# Parsing the first table that contains the travel time between connected stations
# Create a list(dimension N) named Timetable, of arrays(dimension 3) for each line in the input
Timetable = [array([start_station_1, arrival_station_1, travel_time_1]),
array([start_station_2, arrival_station_2, travel_time_2]),
# ...
]
# Parsing the second table containing the pairs of stations among with we will calculate the integrated travel time
# Create a list(dimension M) named MyTrip, of arrays(dimension 2) for each pair of stations
MyTrip = [array([departure_station_1, destination_station_1]),
array([departure_station_2, destination_station_2]),
# ...
]
for (departure_station, destination_station) in MyTrip:
cumulative_travel_time = 0
last_station = null
return TimePath(Timetable,
departure_station,
destination_station,
last_station,
cumulative_travel_time)
### This function is the recursive function that calculates the travel time ###
def TimePath(Timetable, departure_station, destination_station, last_station, cumulative_travel_time=0):
## Check if exist a direct connection between dep and dest or find in the timetable all possible
## connection with my departure point
for (start_station, arrival_station, travel_time) in Timetable:
if start_station == departure_station:
if arrival_station == destination_station:
return cumulative_travel_time + travel_time
elif arrival_station == last_station:
return 0
else:
new_departure = arrival_station
cumulative_travel_time += travel_time
# save the last station where you are in order not to move back
last_station = start_station
#Call same func (recursive) with as new departure point, the arrival of previous step
return TimePath(Timetable,
departure_station=new_departure,
destination_station=destination_station,
last_station=last_station,
cumulative_travel_time=cumulative_travel_time)
|
eb00e6d2dc615f1022097b924c89cc144aab61b5
|
OneOneFour/NeuralSnake
|
/neuralnetwork.py
| 9,133 | 3.609375 | 4 |
import numpy as np
import names
import time
import snake
from tensorflow.examples.tutorials.mnist import input_data
import matplotlib.pyplot as plt
class NeuralNetwork:
def __init__(self, layer_setup, name, family, bias=None, weights=None):
'''
Create neural network with blank parameters for snake
'''
self.first_name = name
self.family = family
self.layer_count = len(layer_setup)
self.layer_setup = layer_setup
if weights is None:
self.weights = [np.random.randn(y, x) for x, y in zip(layer_setup[:-1], layer_setup[
1:])] # i think you can use zip() here but this is easier to understand
else:
self.weights = weights
if bias is None:
self.bias = [np.random.randn(y) for y in layer_setup[1:]]
else:
self.bias = bias
def get_weight_size(self):
return np.sum([np.size(x) for x in self.weights])
def get_bias_size(self):
return np.sum([np.size(x) for x in self.weights])
def out(self, input):
'''
Get output result from neural network
:param input:Vector of
input neurons
:return: Vector of output neurons
'''
if len(input) != self.layer_setup[0]:
raise Exception("Input dimens much match network input dimens")
current_layer = input
for i in range(self.layer_count - 1):
current_layer = self.sigmoid(np.dot(self.weights[i], current_layer) + self.bias[i])
return current_layer
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
# class CalclusClass:
# def __init__(self):
# self.bot = NeuralNetwork([20**2, 16, 16, 10], names.get_first_name(),names.get_last_name())
# self.mnist = input_data.read_data_sets("MNIST_data", one_hot=True)
#
# def test_set(self, start, size):
# average_cost = 0
#
# score = 0
# for i in range(size):
# result = self.bot.out(self.mnist.train.images[i])
# true = self.mnist.train.labels[i]
# if np.argmax(result) == np.argmax(true):
# score += 1
# cost = np.sum((result - true) ** 2)
# average_cost += cost
# # Calculate gradient
#
class Classroom:
def __init__(self):
# Load training images
self.mixing = 0.5
self.mutation = 0.05
self.population = 20
self.gen = 0
#self.mnist = input_data.read_data_sets("MNIST_data", one_hot=True)
self.brains = [NeuralNetwork([20 ** 2, 6, 3], names.get_first_name(), names.get_last_name()) for i in
range(self.population)]
plt.ion()
plt.show()
self.fig = plt.figure()
self.bestAI = self.brains[0], 0
self.best = []
self.avg = []
self.ax1 = plt.gca()
self.ax1.set_ylim(0, 100)
self.line, = self.ax1.plot([], self.best, 'b-')
self.line2, = self.ax1.plot([], self.avg, 'r-')
time.sleep(0.5)
self.trial_all()
def trial_all(self):
while self.bestAI[1] < 50:
scores = []
for network in self.brains:
scores.append((network, self.trial_snake(network)))
scores.sort(key=lambda x: x[1], reverse=True)
self.print_scoreboard(scores)
if scores[0][1] > self.bestAI[1]:
self.bestAI = scores[0]
self.brains = []
while len(self.brains) < self.population:
a = self.tournament_selection(scores,2)
b = self.tournament_selection(scores,2)
if a is b: continue
ab_weights, ab_bias, ba_weights, ba_bias = self.swap_genome(a[0], b[0])
family_name = a[0].family if a[1] > b[1] else b[0].family
self.brains.append(
NeuralNetwork(a[0].layer_setup, names.get_first_name(), family_name, ab_bias, ab_weights))
self.brains.append(
NeuralNetwork(b[0].layer_setup, names.get_first_name(), family_name, ba_bias, ba_weights))
self.gen += 1
def swap_genome(self, a, b):
# unpack
a_chromosone = np.concatenate(np.append([x.flatten() for x in a.weights], [x.flatten() for x in a.bias]))
b_chromosone = np.concatenate(np.append([x.flatten() for x in b.weights], [x.flatten() for x in b.bias]))
ab_chromosone, ba_chromosone = [], []
for i in range(len(a_chromosone)):
if np.random.uniform() > self.mixing:
ba_chromosone.append(a_chromosone[i])
ab_chromosone.append(b_chromosone[i])
else:
ba_chromosone.append(b_chromosone[i])
ab_chromosone.append(a_chromosone[i])
total = [a_chromosone, ab_chromosone, ba_chromosone, b_chromosone]
for chromo in total:
for i in range(len(chromo)):
if np.random.uniform() < self.mutation:
chromo[i] = np.random.randn()
aa_weights, aa_bias = a_chromosone[:a.get_weight_size()], a_chromosone[a.get_weight_size():]
ab_weights, ab_bias = ab_chromosone[:a.get_weight_size()], ab_chromosone[a.get_weight_size():]
ba_weights, ba_bias = ba_chromosone[:b.get_weight_size()], ba_chromosone[b.get_weight_size():]
bb_weights, bb_bias = b_chromosone[:b.get_weight_size()], b_chromosone[b.get_weight_size():]
aa_weights = self.reform_chromosone_weight(aa_weights, a.layer_setup)
bb_weights = self.reform_chromosone_weight(bb_weights, b.layer_setup)
ab_weights = self.reform_chromosone_weight(ab_weights, a.layer_setup)
ba_weights = self.reform_chromosone_weight(ba_weights, b.layer_setup)
aa_bias = self.reform_chromosone_bias(aa_bias, a.layer_setup)
ab_bias = self.reform_chromosone_bias(ab_bias, a.layer_setup)
ba_bias = self.reform_chromosone_bias(ba_bias, b.layer_setup)
bb_bias = self.reform_chromosone_bias(bb_bias, b.layer_setup)
return ab_weights, ab_bias, ba_weights, ba_bias
def reform_chromosone_bias(self, bias, network_setup):
values = network_setup[1:]
end_bias = []
for v in range(len(values)):
end_bias.append(np.reshape(bias[int(np.sum(values[:v])):int(np.sum(values[:v + 1]))], (values[v],)))
return end_bias
def reform_chromosone_weight(self, weight, network_setup):
values = [a * b for a, b in zip(network_setup, network_setup[1:])]
end_weight = []
for v in range(len(values)):
end_weight.append(np.reshape(weight[int(np.sum(values[:v])):int(np.sum(values[:v + 1]))],
list(zip(network_setup[1:], network_setup))[v]))
return end_weight
def print_scoreboard(self, scores):
names = ["{0} {1}".format(k[0].first_name,k[0].family) for k in scores]
scores = [s[1] for s in scores]
self.best.append(scores[0])
self.avg.append(np.mean(scores))
print("------------------GENERATION {0} results---------------".format(self.gen))
for i in range(len(scores)):
print("{0} Score: {1} %".format(names[i], scores[i]))
print("------------------------------------------------------\n"
"Average Score: {0} % \n"
"------------------------------------------------------".format(np.mean(scores)))
self.line.set_ydata(self.best)
self.line.set_xdata(np.arange(0, self.gen + 1, 1))
self.line2.set_ydata(self.avg)
self.line2.set_xdata(np.arange(0, self.gen + 1, 1))
self.ax1.set_xlim(0, self.gen + 1)
self.ax1.set_ylim(0,np.max(scores) + 10)
plt.draw()
plt.pause(1e-17)
time.sleep(0.001)
# def trial_images(self, network):
# score = 0
# for i in range(self.num):
# result = network.out(self.mnist.test.images[i].reshape((28 ** 2,)))
# true = self.mnist.test.labels[i]
# if np.argmax(result) == np.argmax(true):
# score += 1
# return score
def trial_snake(self,network):
score = []
snake.Game(network,score)
return score[0]
def tournament_selection(self, scores, k):
current_winner = None
for i in range(k):
challenger = scores[np.random.randint(0, len(scores))]
if current_winner is None or challenger[1] > current_winner[1]:
current_winner = challenger
return current_winner
c = Classroom()
# plt.ioff()
# while True:
# i = np.random.randint(0, 10000)
# result = c.bestAI[0].out(c.mnist.test.images[i].reshape((28 ** 2,)))
# true = c.mnist.test.labels[i]
# fig = plt.figure()
# print(result)
# plt.title("Value is {0}, my guess was {1}".format(np.argmax(true), np.argmax(result)))
# plt.imshow(c.mnist.test.images[i].reshape((28, 28)), cmap='gray')
# plt.show()
|
12f14d96f18b14f62b29217362257d0ae7530d8e
|
jpsalviano/uri-online-judge
|
/2147.py
| 78 | 3.5 | 4 |
for _ in range(int(input())):
print('{:.2f}'.format(len(input()) * 0.01))
|
c5e262d0df628a6a2badbd9a68b2550edcf1c88b
|
AhmadMWaddah/AMW_Functions
|
/AMW SLR Package.py
| 4,342 | 3.640625 | 4 |
class MeanSquaredError:
def __init__(self, actual_data, predicted_data):
self.
# Mean Squared Error.
def mean_square_error(self):
"""
Function Takes 2 Parameters lists of data, making counter and add to it and zipping lists.
:param actual_data:
:param predicted_data:
:return: Mean Squared Error Of Both Data Actual and Predicted.
"""
# Starter Counter.
counter = 0
# Combining BOth List With Zipping Function.
data_combined = zip(actual_data, predicted_data)
# Loop For Each cell in both data.
for (each_actual, each_predicted) in data_combined:
# Adding Results To Starter Counter.
counter += (each_actual - each_predicted) ** 2
return counter / len(actual_data)
# -------------------- #
def data_mean(data_values):
"""
Getting The Mean Number For Data.
:param data_values: Set Of Data
:return: Mean Of Data Values.
"""
mean_of_data = sum(data_values) / len(data_values)
return mean_of_data
# -------------------- #
def data_variance(data_values, mean_of_data):
"""
Getting The Variance Number For Data.
:param data_values: Set Of Data
:param mean_of_data: Mean Of Data From Previous Function.
:return: Variance Of Data.
"""
starter_counter = 0
for data_cells in data_values:
starter_counter += (data_cells - mean_of_data) ** 2
variance_of_data = starter_counter / len(data_values)
return variance_of_data
# -------------------- #
def data_covariance(features_values, labels_values, features_mean, labels_mean):
"""
It measures the degree of change in the variables, i.e. when one variable changes, will there be the same/a similar change in the other variable.
:param features_values: (X) Weights and Features Of Data
:param labels_values: (Y) Predictions and Labels Of Data
:param features_mean: Measured Mean Of Features For Data
:param labels_mean: Measured Mean Of Labels For Data
:return: Measure of relationship between 2 variables.
"""
# Labels and Features Added and Multiplied.
features_labels_sum_multiply = 0
# Combine Both Features and Labels In One Object.
feature_label_combined = zip(features_values, labels_values)
for (features_values, labels_values) in feature_label_combined:
features_labels_sum_multiply += ((features_values - features_mean) * (labels_values - labels_mean))
covariance_of_data = features_labels_sum_multiply / len(features_values)
return covariance_of_data
# -------------------- #
def data_coefficient(features_values, labels_values):
"""
Measure of correlation overcomes the scale dependency of covariance by standardizing the measures.
:param features_values: (X) Weights and Features Of Data
:param labels_values: (Y) Predictions and Labels Of Data
:return: Beta One And Beta Zero.
"""
features_mean = data_mean(features_values)
labels_values = data_mean(labels_values)
features_variance = data_variance(features_values, features_mean)
labels_variance = data_variance(labels_values, labels_values)
print(features_variance)
beta_one = data_covariance(features_values, labels_values, features_mean, labels_values) / features_variance
beta_zero = labels_values - (beta_one * features_mean)
return beta_one, beta_zero
# -------------------- #
def simple_linear_regression(features_train, labels_train, features_test):
"""
Using a linear regression model will allow you to discover whether a relationship between variables exists at all.
:param features_train:
:param labels_train:
:param features_test:
:return: prediction_of_data
"""
beta_one_train, beta_zero_train = data_coefficient(features_train, labels_train)
prediction_of_data = beta_one_train * features_test + beta_zero_train
return prediction_of_data
# -------------------- #
def evaluate_model(features_train, labels_train, features_test, labels_test):
"""
Evaluate Model anc Compare Train Data With Test Data.
:param features_train:
:param labels_train:
:param features_test:
:param labels_test:
:return: mean_square_error
"""
prediction_data = simple_linear_regression(features_train, labels_train, features_test)
return mean_square_error(prediction_data, labels_test)
|
5a5f041391049d4e7fa05338ae258462dcbf3e12
|
iulidev/dictionary_search
|
/search_dictionary.py
| 2,798 | 4.21875 | 4 |
"""
Implementarea unui dictionar roman englez si a functionalitatii de cautare in
acesta, pe baza unui cuvant
In cazul in care nu este gasit cuvantul in dictionar se va ridica o eroare
definita de utilizator WordNotFoundError
"""
class Error(Exception):
"""Clasa de baza pentru exceptii definite de utilizator"""
pass
class WordNotFoundError(Error):
"""Clasa pentru exceptii la cautare fara succes in dictionar"""
class Dict:
"""Clasa pentru instante de tip dictionar, perechi cuvant: traducere
Atribute:
name (str): numele dictionarului
words (dict): dictionarul de cuvinte, perechi de stringuri
word: translation
total (int): numarul total de definitii (cuvinte)
Metode:
__init__(self, name='Dictionar En-Ro', initial_words=None)
- constructor pe baza nume (string) si dictionar de start (dict)
add(self, word, translation)
- adauga un cuvant word cu traducerea translation la dictionar
display(self)
- afiseaza perechile cuvant: traducere (valorile din dictionar)
search(self, word)
- cauta cuvantul word in dictionar
- afiseaza traducerea daca este gasit
- altfel, ridica exceptia WordNotFoundError
count():
- afiseaza numarul de cuvinte din dictionar (total)
"""
total = 0
def __init__(self, name='Dictionar Ro-En', initial_words=None):
self.name = name
if initial_words is None:
self.words = {}
else:
self.words = initial_words.copy()
Dict.total += len(initial_words)
def add(self, word, translation):
self.words[word] = translation
Dict.total += 1
def display(self):
for word, translation in self.words.items():
print(f'{word} = {translation}')
def search(self, word):
try:
translation = self.words.get(word)
if translation is None:
raise WordNotFoundError(
f'Cuvantul {word} nu este in dictionar')
except WordNotFoundError as e:
return f'>>> {e.__class__.__name__}: {e}'
else:
return f'Rezultat cautare: {word} = {translation}'
@staticmethod
def count():
return f'Dictionarul are {Dict.total} cuvinte'
def main():
d = Dict('Dictionar Roman Englez',
{'mare': 'sea', 'calculator': 'computer'})
d.add('zi', 'day')
d.add('ora', 'hour')
d.add('soare', 'sun')
d.add('apa', 'water')
d.display()
print(d.search('zi'))
print(d.search('eveniment')) # ridica o exceptie WordNotFoundError
print(d.search('soare'))
print(Dict.count())
if __name__ == '__main__':
main()
|
8af974cf30f71656110ff8ea3510219cad025632
|
jacquerie/leetcode
|
/leetcode/1374_generate_a_string_with_characters_that_have_odd_counts.py
| 380 | 3.671875 | 4 |
# -*- coding: utf-8 -*-
class Solution:
def generateTheString(self, n: int) -> str:
if n % 2:
return "a" * n
return "a" * (n - 1) + "b"
if __name__ == "__main__":
solution = Solution()
assert "aaab" == solution.generateTheString(4)
assert "ab" == solution.generateTheString(2)
assert "aaaaaaa" == solution.generateTheString(7)
|
caf0761b7ad526e99b283a1759adfab82ef03ddd
|
guydav/minerva
|
/stuff/peculiar_balance.py
| 1,280 | 4.15625 | 4 |
def answer(x):
'''
x: the weight on the left side to be balanced
return: a list of where to place each weight - "L" / "-" / "R"
'''
# create a list of all weights to be used:
if x <= 0:
return
current_weight = 1
weights = [current_weight]
while sum(weights) < x:
current_weight *= 3
weights.append(current_weight)
solution_weight = 0
target_weight = x
solution = []
while solution_weight != target_weight:
current_weight = weights.pop()
diff = abs(target_weight - solution_weight)
if weights and diff <= sum(weights):
solution.append('-')
continue
diff_weight_on_right = abs(target_weight - solution_weight - current_weight)
if diff_weight_on_right < diff:
# weight should go on the right
solution.append('R')
solution_weight += current_weight
else:
# weight goes on left
solution.append('L')
target_weight += current_weight
for remaining_weight in weights:
# handle the remaining weights well
solution.append('-')
solution.reverse()
return solution
if __name__ == '__main__':
for x in xrange(1000):
answer(x)
|
9ccd3916c23a263cdd909fe8b273698c706d4daa
|
taeyoung02/Algorithm
|
/최대힙.py
| 1,807 | 3.609375 | 4 |
import sys
class heap:
def __init__(self):
self.n = int(input())
self.arr = [0]*(self.n+2)
self.count=0
self.start()
def heapmax(self):
if self.count==0:
print(0)
else:
print(self.arr[1])
self.arr[1]=self.arr[self.count]
temp=self.arr[1]
self.count-=1
cur=1
child=2
while child<=self.count:
if child+1<=self.count: # 순서가 꼬였어도 자식중에 큰놈이랑
# 바꾸기 때문에 자연스럽게 맞춰짐
# 루트노드가 오른쪽을 선택하면 왼쪽전체는 무조건 다음루트노드보다
# 작은숫자고, 오른쪽의 가장큰숫자가 루트노드 오른쪽으로 온다
if self.arr[child+1]>self.arr[child]:
child+=1
if temp>=self.arr[child]:
break
else:
self.arr[cur]=self.arr[child]
cur=child
child*=2
self.arr[cur] = temp
# 그냥 부모보다 작으면 자식으로 박는다
def insert(self,num):
self.count+=1
i=self.count
while i//2>0:
if self.arr[i//2]<num:
self.arr[i] = self.arr[i//2]
i//=2
else:
break
self.arr[i]=num
def start(self):
for k in range(self.n):
a=int(sys.stdin.readline())
if a==0:
self.heapmax()
else:
self.insert(a)
print(self.arr)
if __name__ == "__main__":
h=heap()
|
d4d3857ea80ae8f790e55834cd171d4332d6d832
|
eulestadt/MIS-304
|
/Final Project/cupcakes.py
| 3,356 | 4.4375 | 4 |
# Name: Phoenix Wang
# Assignment Number: Final Project
# Date: 12/5/19
# Section: 9:30-11
# Description: The cupcake class for the cupcake object
# that is sold at the cupcake shop. Allows the user to access
# the price, flavor, inventory, and topping attributes of the
# cupcake, while also checking each part.
#cupcake class for cupcakes that are sold at the cupcake shop
class Cupcake:
#receives the arguments of price, flavor, and inventory
#assigns to the price, flavor, and inventory attributes
def __init__(self, price, flavor, inventory):
#assigns the price argument to the price attribute
self.__price = price
#assigns the flavor argument to the flavor attribute
self.__flavor = flavor
#assigns the inventory argument to the inventory attribute
self.__inventory = inventory
#methods to "get" each of the attributes
#gets the price for the cupcake
#get_price method receives the cupcake object and returns the price
def get_price(self):
return self.__price
#gets the flavor for the cupcake
#get_flavor method receives the cupcake object and returns the flavor
def get_flavor(self):
return self.__flavor
#gets the inventory for the cupcake
#get_inventory method receives the cupcake object and returns the inventory
def get_inventory(self):
return self.__inventory
#methods to set each of the attributes
#set_price method receives the cupcake object and price
#sets the price attribute of the cupcake
def set_price(self, price):
#checks if price is positive
if price < 0:
print('Invalid price! Price must be positive!')
else:
self.__price = price
#set_flavor method receives the cupcake object and flavor
#sets the flavor attribute of the cupcake
def set_flavor(self, flavor):
self.__flavor = flavor
#set_inventory method
def set_inventory(self, inventory):
# check if inventory is <= 0 or > 100
if inventory <= 0 or inventory > 100:
print('Invalid inventory quantity! Please enter a value between 0 and 100')
#sets the inventory of the bread
else:
self.__inventory = inventory
#__str__ method returns a string with all the attributes of the cupcake
def __str__(self):
#creates a string with the value of all the attributes
selfString = 'The cupcake price is $' + str(format(self.__price, '.2f')) + '\n' + 'The cupcake flavor is ' + self.__flavor + '\n' + 'The cupcake inventory is ' + str(self.__inventory) + '\n'
#returns the value of all outputs
return selfString
#class for the cupcake with topping
class CupcakeWithTopping(Cupcake):
#inherits all attributes from cupcake with the additional topping attribute
def __init__(self, price, flavor, inventory, topping):
Cupcake.__init__(self, price, flavor, inventory)
self.__topping = topping
#gets the topping of the cupcake
def get_topping(self):
return self.__topping
#set the topping of the cupcake
def set_topping(self, topping):
self.__topping = topping
def __str__(self):
return Cupcake.__str__(self) + 'The cupcake topping is ' + self.__topping + '\n'
|
a809edf288895b01433542db8ac8e623d264ca51
|
HarshKhaiwal/Python-Assignment
|
/duplicate.py
| 380 | 3.984375 | 4 |
list1 = []
list2 = []
n = int(input('Enter no. of elements you want to enter in a list : '))
for i in range(0, n):
x = int(input())
list1.append(x)
print('Original list {}'.format(list1))
list1.sort()
for i in range(len(list1) - 1):
if list1[i] == list1[i + 1]:
list2.append(list1[i])
print("list containing duplicate elements {}".format(list2))
|
1bad39d26c85c4368c5a8964bf242bc0340040b2
|
smilezjw/LeetCode
|
/P142_Linked List Cycle II/Linked List Cycle II.py
| 1,887 | 3.5625 | 4 |
# coding=utf8
__author__ = 'smilezjw'
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def detectCycle(self, head):
if head is None or head.next is None:
return None
fast = slow = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if fast == slow: # 判断有环
break
if fast == slow:
slow = head
while slow != fast: # 找到环的起点
slow = slow.next
fast = fast.next
return slow.val
return None
if __name__ == '__main__':
s = Solution()
head = ListNode(3)
p = head
for i in [2, 0, 4]:
p.next = ListNode(i)
p = p.next
p.next = head.next
head2 = ListNode(0)
head2.next = head2
print s.detectCycle(head)
############################################################################################
# 对于这道题目,我只能说奥数题目大概就是这样计算的。
# 具体示意图参考:http://www.cnblogs.com/zuoyuan/p/3701877.html
# 从head到环路起点距离为K,起点到fast和slow的相遇点距离为M,整个环路周长为L。假设当fast和
# slow相遇时,fast走过了Lfast,slow走过了Lslow,根据题意可知:
# Lslow = K + M
# Lfast = K + M + n * L
# Lfast = 2 * Lslow
# 根据上面三个式子可以得出: K = n * L - M = (n - 1) * L + L - M
# 将slow重新从head开始,fast从相遇点开始走,每次都只走一步,slow走了K步到达环的起点,此时fast
# 绕着环走了n-1圈,并且也到达了环的起点。于是,环的起点通过再次判断fast == slow就找到了。
# 这样不需要具体计算K、L、M距离的值,通过两次判断slow == fast即可判断是否有环以及环的起点。
#
|
4ec3cae997290213c5a5d074a2446bf5c677defb
|
TheRea1AB/Python
|
/Conditional.py
| 1,129 | 4.34375 | 4 |
#Conditional Statements
#if statement
grade = 95
if grade > 90:
print("You got an A!")
#if-else statement
grade = 75
if grade > 90:
print('You got an A')
else:
print('You did not get an A')
#if-elif statement
grade = 85
if grade > 90:
print("A")
elif grade > 80:
print("B")
else:
print("Youg did not get an A or B")
#nested statement
grade = 100
if grade > 90:
if grade == 100:
print("Perfect!")
#Operations
#AND
grade = 85
if grade < 90 and grade >= 80:
print('You get a B')
else:
print('You did not get a B')
#OR
sport = 'Baseball'
if sport is 'Football' or sport is 'Baseball':
print("The Greatest Game in the World!")
#Excercices
#Write a program that checks to see if a number is less than 10
number = 5
if number < 10:
print("Number is less than 10")
number = 87
if number % 2 == 0:
print("The number is even")
else:
print("The number is odd")
number = 200
if number % 50 == 0 and number % 10 == 0:
if number % 30 == 0:
print('Number is divisible by 10, 30, and 50')
else:
print('Number is divisible by 10 and 50 but not 30')
|
7b1d132e85f8c478ae3c778ce465f10672bcc08b
|
mdeng1110/Computing_Talent_Initiative
|
/12_P2_Add_Node_to_BST.py
| 1,410 | 4 | 4 |
class Node:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
class Tree:
def __init__(self):
self.root = None
def print_bfs(self):
if not self.root:
return
queue = [self.root]
while len(queue) > 0:
current_node = queue.pop(0)
print(current_node.data)
if current_node.left:
queue.append(current_node.left)
if current_node.right:
queue.append(current_node.right)
def in_order_traversal(self):
nodes = []
def dfs(node):
if node:
dfs(node.left)
nodes.append(node.data)
dfs(node.right)
dfs(self.root)
return nodes
def add(self,node):
if self.root is None:
self.root = node
else:
def insert(root, node):
if node.data < root.data:
if root.left is None:
root.left = node
else:
insert(root.left, node)
else:
if root.right is None:
root.right = node
else:
insert(root.right,node)
root = self.root
insert(root, node)
tree = Tree()
tree.root = Node(55)
tree.root.left = Node(20)
tree.root.right = Node(100)
tree.root.left.left = Node(15)
tree.root.left.right = Node(30)
tree.root.right.left = Node(60)
tree.root.right.right = Node(200)
print(tree.add(Node(7)))
print(tree.in_order_traversal())
|
8c034bc5367ed40c4bae0b818a943384936b391e
|
iamNargiz/Py_concepts_RegEx
|
/RegEx.py
| 775 | 4.125 | 4 |
#!/usr/bin/env python
# coding: utf-8
# In[11]:
#search() function
import re
text = "The match in Azerbaijan"
x = re.search('^The.*Azerbaijan$',text)
print(x)
# In[12]:
if x:
print("Yes! We have a match!")
else:
print("No match")
# In[13]:
#findall() function
txt = "The rain in Azerbaijan"
x = re.findall("ai", txt)
print(x)
# In[14]:
#No match
x = re.findall("Brazil", txt)
print(x)
if (x):
print("Yes, there is at least one match!")
else:
print("No match")
# In[15]:
#split() function
x = re.split("\s", txt)
print(x)
# In[16]:
#split() with count
x = re.split("\s", txt, 1)
print(x)
# In[17]:
#sub() function
x = re.sub("\s", "%", txt)
print(x)
# In[10]:
#sub() with count
x = re.sub("\s", "%", txt, 2)
print(x)
# In[ ]:
|
6f4fe239759e2bb1f8ca01b7a61a102cd2c82ed5
|
guptaarchit/movie-recommendation-system
|
/Movie-Recommendation-Algorithm-master/runMe.py
| 3,137 | 3.515625 | 4 |
import networkx as nx
import matplotlib.pyplot as plt
def neighborList(G, node, props):
neigh = G.neighbors(node)
neigh.remove('Weight')
for prop in props:
neigh.remove(prop)
return neigh
#print "\n "
props = ['Actor','Director','Producer','Genre']
G = nx.Graph()
#Constructing a graph from the JSON file
fin = open("testFile.txt")
JSONarr = fin.readlines()
#creating nodes. Each movie is a node.
for line in JSONarr:
JSONobj = eval(line)
nodes = G.nodes()
#print nodes
G.add_node(JSONobj['Name'])
G[JSONobj['Name']]['Weight'] = 0
G[JSONobj['Name']]['Director'] = JSONobj['Director'] #this is a list
G[JSONobj['Name']]['Actor'] = JSONobj['Actor']
G[JSONobj['Name']]['Producer'] = JSONobj['Producer']
G[JSONobj['Name']]['Genre'] = JSONobj['Genre']
#print G[JSONobj['Name']]
#creating edges between nodes. Each edge is associated with a list that specifies how those two entities are related.
for node in nodes:
for key in props:
#print G[JSONobj['Name']][key]
#print G[node][key]
#print set(G[JSONobj['Name']][key]).isdisjoint(set(G[node][key]))
if not set(G[JSONobj['Name']][key]).isdisjoint(set(G[node][key])):
if G.has_edge(JSONobj['Name'], node): #if the edge is being added for the first time, then initialize its value with the key, else append the key to the existing relation.
CurrAssoc = G[JSONobj['Name']][node]['Associations']
CurrAssoc.append(key)
G.add_edge(JSONobj['Name'], node, Associations = CurrAssoc)
else:
G.add_edge(JSONobj['Name'], node, Associations = [key])
#print G[JSONobj['Name']]
#print "\n"
'''
for node in G.nodes():
print "\n" + node
print neighborList(G, node, props)
'''
#nx.draw(G)
#plt.show()
'''configuration'''
weightVector = [1,1,1,1] #This is the weights associated with every movie
inputSeq = ["MovieName1","MovieName2","MovieName2"] #This is the sequence in which the user has watched a movie
#normalizing the weight vector
s = float(sum(weightVector))
for i in range(len(weightVector)):
weightVector[i] = weightVector[i] / s
#propWeight is a dictionary that has a weight associated with every property. Ex: {"Director": 0.3}
propWeight = {}
for i in range(len(props)):
propWeight[props[i]] = weightVector[i]
for node in inputSeq: #traverse every node in the inputsequence of the reader
neighbors = neighborList(G, node, props) #get the neighbors of the those nodes
for neighbor in neighbors: #for each neighbor, get the information on how it is connected to this node
#print "\n"
#print (node, neighbor)
Associations = G[node][neighbor]['Associations']
for assocs in Associations:
G[neighbor]['Weight'] += propWeight[assocs] #increase the weight of the neighbor based on its associations with the current node.
#Sort the movie names according to their Weights gained.
FinalValue = {}
for node in G.nodes():
FinalValue[node] = G[node]['Weight']
FinalValue = FinalValue.items()
FinalValue = [(rating, name) for name,rating in FinalValue]
FinalValue.sort(reverse = True)
FinalValue = [name for rating, name in FinalValue]
print "Movies watched:" + str(inputSeq)
print "Recommendation:" + str(FinalValue)
|
19b0ea7d89396b790baee3f1265cd2f700105a21
|
NCavaliere1991/space-invaders
|
/turret.py
| 1,057 | 3.5625 | 4 |
from turtle import Turtle
class Turret(Turtle):
def __init__(self):
super().__init__()
self.shape("sprites/ship.gif")
self.penup()
self.goto(0, -225)
self.bullet = None
self.bullet_list = []
def move_right(self):
if self.xcor() < 270:
self.forward(10)
def move_left(self):
if self.xcor() > -275:
self.backward(10)
def shoot(self):
if not self.bullet_list:
self.bullet = Turtle(shape='square')
self.bullet.color('yellow')
self.bullet.shapesize(stretch_len=.5, stretch_wid=.1)
self.bullet.setheading(90)
self.bullet.penup()
self.bullet.goto(self.xcor(), self.ycor())
self.bullet_list.append(self.bullet)
def player_bullet_move(self):
self.bullet.forward(15)
def destroy(self):
self.bullet_list.remove(self.bullet)
self.bullet.hideturtle()
self.bullet = None
def reset_position(self):
self.goto(0, -225)
|
7f09b95f67b37362db89cf2b26951499901f930e
|
wongahee/python3
|
/ex15.py
| 1,006 | 3.75 | 4 |
# 혈액 보관 시스템
A = []
B = []
AB = []
O = []
num = 0
for i in range(10):
blood = input('헌혈해 주셔서 감사합니다. 혈액형을 선택하세요 \n'
'A, B, AB, O : ')
if blood == 'A' or blood == 'a' : A.append(blood)
elif blood == 'B' or blood == 'b' : B.append(blood)
elif blood == 'AB' or blood == 'ab' : AB.append(blood)
elif blood == 'O' or blood == 'o' : O.append(blood)
print(f'혈액형별 수급 현황 :')
print('-------------')
print(f'A형 : {len(A)}명, B형 : {len(B)}명, AB형 : {len(AB)}명, O형 : {len(O)}명')
# 풀이 2
bloods = []
for i in range(10):
blood = input('헌혈해 주셔서 감사합니다. 혈액형을 선택하세요 \n'
'A, B, AB, O : ')
bloods.append(blood)
print('-'*30)
print('혈액형 수급 현황')
print('-'*30)
print(f'A형 : {bloods.count("A")}명, B형 : {bloods.count("B")}명 '
f'AB형 : {bloods.count("AB")}명, O형 : {bloods.count("O")}명')
print('-'*30)
|
5beb8e7970a2e8b1bb5cbf73f0c9717d6da7d2b6
|
black40/helper_code
|
/balance_brackets.py
| 1,084 | 3.6875 | 4 |
''' Balance of opening and closing brackets '''
def find_balance(data, left='[{(', right=']})'):
res = []
for i in data:
if i in left:
res.append(i)
elif i in right:
if len(res) == 0:
return False
elif right.index(i) == left.index(res[-1]):
res = res[:-1]
else:
return False
return len(res) == 0
## -----------------testing----------------------
def find_name(x, g=globals()):
return ([n for n in g if id(g[n]) == id(x)])
test_string_1 = '[{()}]'
test_string_2 = '[[]{()[]}(){}]'
test_string_3 = '[w[23]f,.g0{()[qwer,ty]12}()<{}0]'
test_string_4 = ']({[]})[])}'
test_string_5 = '[adsf{3g(fe(3cfa)rt )4 }45'
test_list = [test_string_1, test_string_2, test_string_3, test_string_4, test_string_5]
for test in test_list:
print('{name}: {func}.'.format(name=find_name(test)[0], func=find_balance(test)))
# Will be displayed
# Test_String_1: True.
# Test_String_2: True.
# Test_String_3: True.
# Test_String_4: False.
# Test_String_5: False.
|
630836444b51ed83dcc7707b0df0cc086c29e767
|
think-differentt/Final-Python-Project
|
/main.py
| 2,640 | 4.53125 | 5 |
# <Author> Think-differentt
# <Date> 11OCT20
# Program - This is a program that is used to get weather information from openweathermap
# and display it to the user.
#
# Some printing information taken from https://www.youtube.com/watch?v=PWZKTWJ9bJE REQ 1 - Asks the user for their
# zip code or city. REQ 2 - Use the zip code or city name in order to obtain weather forecast data from:
# http://openweathermap.org/ REQ 3 - Display the weather forecast in a readable format to the user. REQ 4 - Use
# comments within the application where appropriate in order to document what the program is doing. REQ 5 - Use
# functions including a main function. REQ 6 - Allow the user to run the program multiple times. REQ 7 - Use the
# Requests library in order to request data from the webservice. REQ 8 - Use Python 3. REQ 9 - Use try blocks when
# establishing connections to the webservice. You must print a message to the user indicating whether or not the
# connection was successful.
import requests
import json
from pprint import pprint
print("------------------Welcome to my weather application---------------------")
def weather_query():
# Asks the user for their zip code or city
city_name = input("Please enter your the city name:")
# Use the zip code or city name in order to obtain weather forecast data from: http://openweathermap.org/
url = 'http://api.openweathermap.org/data/2.5/weather?q=%s&appid=b15c469fd15ac99f42fd131c12433903&units=imperial' % city_name
current_weather = requests.get(url)
# DISPLAY THE WEATHER FORECAST-
data = current_weather.json()
# Display the weather forecast in a readable format to the user.
# Use try blocks when establishing connections.
try:
temp = data['main']['temp']
wind_speed = data['wind']['speed']
latitude = data['coord']['lat']
longitude = data['coord']['lon']
description = data['weather'][0]['description']
print('Temperature : {} degree F'.format(temp))
print('Wind Speed : {} m/s'.format(wind_speed))
print('Latitude : {}'.format(latitude))
print('Longitude : {}'.format(longitude))
print('Description : {}'.format(description))
except KeyError:
print("Invalid Entry, try again.")
# Allow the user to run the program multiple times.
x = input('Press a letter or number then ENTER to exit, otherwise press ENTER to continue:')
if x:
exit(0)
else:
weather_query()
# Use functions including a main function.
def main():
weather_query()
main()
|
0480316d6fbf3dc3841ac9970687e470839c5816
|
masoom-A/Python-codes-for-Beginners
|
/list_index.py
| 178 | 3.796875 | 4 |
def list(nums):
count=0
for num in nums:
if num==4:
count=count+1
return count
print(list([1,4,3,5,4]))
print(list([4,5,4,6,4,3]))
|
df3dc4f30b3d81c5c0ad4ac5114cbefb5d060ff1
|
rodrigobmedeiros/Coursera-Introdution-To-Scientific-Computing-With-Python
|
/Exercises/soma_elementos.py
| 444 | 3.9375 | 4 |
#Introduction to Computer Science
#Function: soma_elementos
#Date: 18/02/2020
#Developed by: Rodrigo Bernardo Medeiros
#================================================================
#The program will receive a list with integer numbers and will
#sum all elements.
#================================================================
def soma_elementos(lista):
sum = 0
for i in range(len(lista)):
sum = sum + lista[i]
return sum
|
8b73cec23cf79ff10b91e7259e54d8b8f84bc949
|
theref/Computing-For-Mathematics
|
/Lab Sheet 2/#3.py
| 148 | 4.1875 | 4 |
mylist = []
for i in range(1301):
if i % 3 == 0: #computes all the numbers in range divisible by 3
mylist.append(i)
print mylist
print mylist[-1]
|
4ef22b0642da92e7839a0f71f2a7dae4482b7466
|
jspahn/Python-Code
|
/Project-Euler/Finished Problems 1-25/04-PalindromeProject.py
| 1,831 | 4.03125 | 4 |
# Project Euler
# Problem 4: Largest Palindrome Product
# Problem Details:
# A Palindromic number reads the same both ways. The largest
# palindrome made from the product of two 2-digit numbers is
# 9009 = 91 * 99
# Find the largest palindrome made from the product of two
# 3-digit numbers.
#
# Jeffrey Spahn
# created for Python 3.x
import time
def isPalindrome(n):
""" Tests to see if n is a palindrome
Returns boolean"""
s = str(n)
b_isP = True
for i in range(len(s)):
if s[i] != s[-i-1]:
b_isP = False
return b_isP
def findLargest_inRange(low_i,high_i, low_j, high_j):
""" Searches for two natural numbers between the low and the high
that when multiplied give a palindrome.
returns a tuple of those two numbers"""
result = (-1,-1)
for i in range(low_i,high_i+1):
for j in range(low_j,high_j+1):
if isPalindrome(i*j) and i*j > result[0]*result[1]:
result = (i,j)
return result
#------------------------------------------------------------
# Main
#------------------------------------------------------------
if __name__ == "__main__":
start_time = time.time()
# Brute Force method:
multipliers = findLargest_inRange(100,999, 100, 999)
solution = multipliers[0] * multipliers[1]
print("The Largest Palindrome made from the product of the two 3-digit numbers is: {}".format(solution))
print("The two 3-digit numbers are: {} and {}".format(multipliers[0], multipliers[1]))
print("Completion time: {}".format(time.time() - start_time))
# Output:
# The Largest Palindrome made from the product of the two 3-digit numbers is: 906609
# The two 3-digit numbers are: 913 and 993
# Completion time: 1.4271514415740967
|
80502b084e3959c1a551e29d09ffa2432c9d81de
|
kristiangyene/IN1000
|
/oblig4/regnelokke.py
| 817 | 3.859375 | 4 |
"""
Programmet skal la brukeren skrive inn tall helt til brukeren skriver "0" og
legger det i en liste. Alle elemter blir skrevet ut hver for seg. Summen av
tallene, det største tallet, og det minste blir også skrevet ut ved hjelp av
for-løkker.
"""
liste = []
tall = 1
while tall != 0:
tall = int(input("Skriv inn tall:\n>"))
if tall == 0:
break
liste.append(tall)
for e in liste:
print("Tall i liste:", e)
minSum = 0
if tall == 0:
for e in liste:
minSum += e
print("Summen i listen:", minSum)
minst = liste[0]
for e in liste:
if e < minst:
minst = e
print("Det minste tallet i listen er:", minst)
størst = liste[0]
for e in liste:
if e > størst:
størst = e
print("Det største tallet i listen er:", størst)
print("Programmet avsluttes")
|
d5efc06c6703a1691cb8e48011fc78d69c28b16d
|
cassianasb/python_studies
|
/fiap-on/6-7 - Login.py
| 219 | 3.5625 | 4 |
import getpass
user = input("Digite o usuário: ").upper()
password = getpass.getpass("Digite a senha: ")
if user == "USERADM" and password == "OutTime":
print("Usuário logado")
else:
print("Login Negado")
|
f454abf3c65d5508df03bbc74e0e5a8c6fd650d0
|
emas89/Project-5_OpenFoodFacts_Advisor
|
/Scripts/5_substitute_finder.py
| 4,943 | 3.9375 | 4 |
#! /usr/bin/env python3
# -*- coding: utf8 -*-
"""
Open Food Facts Advisor.
Program which finds a healthier food alternative than the one chosen by
the user. The comparison is based on the nutition score: a better dish will
have a higher score than a worse one.
Furthermore, the program indicates where to buy the specified food, if
the information is available in the database.
The user can save his substituted meals in his own database if desired,
or looks at his previous saved meals for a faster choice.
"""
# Original file: OpenFoodFacts database (URL https://world.openfoodfacts.org/data)
from classes import *
def main():
# Welcome message and starting menu
print("\nHi, welcome to the OpenFood Facts Advisor!\nI hope you will find me useful.\n")
print('Please choose one of the following options by typing 1 or 2 on your keyboard: \n')
option = input('1 - You want to find a substitute and healthier aliment.\
\n2 - Look at your saved meals.\n')
while option != '1' and option != '2':
option = input("You have to type '1' or '2' on your keyboard.\n")
# Option 1: find a better food alternative
if option == '1':
# Display all the categories
print ('Categories in Database:\n'\
'(n°, name)\n')
Mysql_queries.show_category()
# Manage exceptions
while 1:
num_cat = input('\nSelect a food category '\
'(enter a number from 1 to 10): \n')
try:
if int(num_cat) in range(1,11):
break
except ValueError:
pass
# Search for correspondances between user's chosen nb and category id
cat_nb = List.category_list_id()[int(num_cat)-1]
# Show to user the meals from the selected category
print ('\nHere are the meals from selected category:\n'\
'(n°, name, brand)\n')
# Show up the products of the selected category (20 in every page)
page_nb = 0
Mysql_queries.show_dish(cat_nb, page_nb)
# User interaction with the list
while 1:
selected_meal = input("\nSelect your meal by entering his number"\
" or turn the page by clicking 'n' on your keyboard:\n") # 'n' for 'next'
min_nb = 1 + 20 * page_nb
max_nb = min_nb + 20
try:
if selected_meal == 'n':
page_nb += 1
Mysql_queries.show_dish(cat_nb, page_nb)
elif int(selected_meal) in range(min_nb, max_nb):
break
except ValueError:
pass
# Searching for correspondances between user's chosen nb and dish id
selected_dish = List.dish_list_id(cat_nb)[int(selected_meal)-1]
# Show up the selected products
Mysql_queries.show_selected_dish(selected_dish)
# Suggest a healthier food alternative
chosen_nb = 0
# Show up 1 product in every page with its properties
# User interaction with the list
Mysql_queries.show_alternative(cat_nb, selected_dish, chosen_nb)
while 1:
ok_choice = input ("\nThis product is recommended. Click 'y' to choose it"\
" or 'o' to see another one\n") # ('y' for 'yes'); ('o' for 'other')
try:
if ok_choice == 'o':
chosen_nb += 1
Mysql_queries.show_alternative(cat_nb, selected_dish, chosen_nb)
elif ok_choice == 'y':
alternative_dish = List.substitute_list_id(cat_nb, selected_dish)\
[int(chosen_nb)]
break
except ValueError:
pass
# Show up the store where to buy the suggested meal
Mysql_queries.show_stores(alternative_dish)
# Suggestion to save the healthier meal in the 'Healthier_Substitute' table
db_save = input("\nDo you want to save this meal for later?"\
" Tap 's' to confirm or any other key to exit.\n") # ('s' for 'save')
if db_save == 's':
Mysql_queries.alternative_save(selected_dish, alternative_dish)
print("\nMeal saved. You are a little bit healthier now!\nSee you soon. Bye bye!")
else:
print("\nSee you soon. Bye bye!")
# Option 2: find a meal saved in the 'Healthier_Substitute' table
elif option == '2':
print('\nHere are the saved meals in your database:\n'\
'(n°id, name, brand, nutritional level)\n')
# Display the meals, 10 in every page.
returned_page = 0
Mysql_queries.origin_dish_db(returned_page)
# User interaction with the list
broken = 1
while broken:
id_origin = input("\nSelect a meal by entering his id) "\
"or type 'n' to see the next page):\n")
# Check user input
try:
if id_origin == 'n':
returned_page += 1
Mysql_queries.origin_dish_db(returned_page)
# Check if the chosen id is on the principal list in the 'Healthier_Substitute' table
elif id_origin != 'n':
for j in List.origin_list_id():
if j == int(id_origin):
broken = 0
except ValueError:
pass
## Display the selected substitute meal with its properties
Mysql_queries.alternative_dish_db(id_origin)
# Goodbye message
print("\nSee you next time!\n")
# To be standalone
if __name__ == "__main__":
main()
|
d9ae7392ce1848620afbea4b57c6aed0bccafc20
|
Hiromitsu4676/algorithm
|
/connected_component.py
| 1,637 | 3.859375 | 4 |
class Queue():
'''
キュー(先入れ先出し)
'''
def __init__(self,size=100):
self.queue =[]
self.size=size
def enqueue(self,x):
self.queue.append(x)
return self.queue
def dequeue(self):
rslt=self.queue[0]
del self.queue[0]
return rslt
def is_empty(self):
return len(self.queue)==0
def bfs_check(alist,start,end):
color=['White']*len(alist)
Q=Queue()
Q.enqueue(start)
while Q.is_empty()!=True:
u = Q.dequeue()
color[u-1] = 'Black'
for n in alist[u]:
if color[n-1]=='White':
Q.enqueue(n)
if n == end:
return True
return False
if __name__=='__main__':
input_data=[]
input_data.append('10 9')
input_data.append('0 1')
input_data.append('0 2')
input_data.append('3 4')
input_data.append('5 7')
input_data.append('5 6')
input_data.append('6 7')
input_data.append('6 8')
input_data.append('7 8')
input_data.append('8 9')
input_data.append('3')
input_data.append('0 1')
input_data.append('5 9')
input_data.append('1 3')
N,E=map(int,input_data.pop(0).split())
adjacent_list=[[] for i in range(E)]
for i in range(E):
u,v = map(int,input_data.pop(0).split())
adjacent_list[u].append(v)
q_number=int(input_data.pop(0))
for j in range(q_number):
start,end=map(int,input_data.pop(0).split())
rslt=bfs_check(adjacent_list,start,end)
if rslt==True:
print('Yes')
else:
print('No')
|
972f5f57d97ffed00089beac68d409e691615f05
|
marmara-technology/SIKAR-HA
|
/SIKAR-HA Control Panel/Programlar/konumgonder.py
| 2,524 | 3.578125 | 4 |
import tkinter.font
from tkinter import *
from tkinter import messagebox
from tkinter import Menu
import RPi.GPIO as GPIO
import os
wait=None
rec=None
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD) #Numbers GPIOs by physical location
def SetAngle(angle): # Angle paramater will be got from user
print('go')
def SetAngle2(angle): # Angle paramater will be got from user
print('go')
def SetAngle3(angle): # Angle paramater will be got from user
print('go')
#MOTOR ANGLES
def ServoOn():
x=int(str(angle1.get()))
y=int(str(angle2.get()))
if x>180 or y>180:
messagebox.showerror('TEKİLLİK HATASI', 'Verilebilecek en büyük açı 180 derecedir.')
return None
SetAngle(x)
SetAngle2(y)
global grp
grp=150
def GrOn():
global grp
grp+=1
SetAngle3(155)
grinfo=Label(konum,text='Gripper Pozisyonu:'+str(grp)).grid(column=22,row=72)
def GrOff():
global grp
grp-=1
if grp<150 or grp>170:
messagebox.showerror('TEKİLLİK HATASI','Gripper Konum Sınırlarına ulaşılmıştır.')
return None
SetAngle3(176)
grinfo2=Label(konum,text='Gripper Pozisyonu:'+str(grp)).grid(column=22,row=72)
def Gripper():
z=int(str(gripper.get()))
SetAngle3(z)
##Kayit fonk sonu
def konumsal():
global angle1
global angle2
global gripper
global konum
konum=Tk()
konum.geometry('900x300')
konum.title('KONUM BİLGİSİNE GÖRE HAREKET')
lbl = Label(konum, text="MOTOR 1",fg='blue',bg='yellow',font=("Arial Bold",24),width='10')
lbl.grid(column=20, row=0)
lbl = Label(konum, text="MOTOR 2",fg='blue',bg='yellow',font=("Arial Bold",24),width='10')
lbl.grid(column=21, row=0)
lbl = Label(konum, text="GRIPPER",fg='blue',bg='yellow',font=("Arial Bold",24),width='10')
lbl.grid(column=23, row=0)
angle1 = Entry(konum,width=5)
angle1.grid(column=20, row=40)
angle2 = Entry(konum,width=5)
angle2.grid(column=21, row=40)
btn2= Button(konum,text='Onayla', command=ServoOn,height='2',width='5')
btn2.grid(column=21,row=41,sticky=W)
gon= Button(konum,text='Gripper Aç', command=GrOn)
gon.grid(column=22,row=41)
goff= Button(konum,text='Gripper Kapat', command=GrOff)
goff.grid(column=30,row=41,sticky=W)
gripper=Scale(konum,from_=150,to=180,orient=HORIZONTAL)
gripper.grid(column=23,row=100)
grpbutton=Button(konum,text='Move',command=Gripper)
grpbutton.grid(column=23,row=181)
konum.mainloop()
konumsal()
|
7940f16bbb51967bcccd2e40f54eb32178263453
|
raghav581/DSA-Solutions
|
/Recursion/Day1/problem1/main.py
| 218 | 4.125 | 4 |
def fibonacci(n):
if n == 1:
return 0
elif n == 2:
return 1
return fibonacci(n - 1) + fibonacci(n - 2)
if __name__ == "__main__":
n = int(input())
res = fibonacci(n)
print(res)
|
f4a4ed772b1fbce140eee1bc6d391472ca05de26
|
mahsa-ashna/python-project
|
/project_phase2_mahsa ashna/login.py
| 1,893 | 3.734375 | 4 |
import pandas as pd
import hashlib
import csv
class User:
def __init__(self, username, password,varity):
self.username = username
self.password = password
self.kind = varity
@staticmethod
def register():
file_path = "account.csv"
df_account = pd.read_csv(file_path)
lst_username = list(df_account["username"])
varities = ["normal", "student", "employee", "admin"]
username = input("enter your username:")
if username in lst_username:
print("invalid username")
return
password = input("enter your password:")
hash_password = hashlib.sha256(password.encode("utf8")).hexdigest()
for v in varities:
print(str(varities.index(v)) + "." + v)
v = int(input("please enter your varity number: "))
if(v < 0 or v > 3):
print("no such varity")
return
obj_user = User(username, hash_password,varities[v])
row_account = [[obj_user.username, obj_user.password, varities[v]]]
with open(file_path, 'a', newline='') as csv_account:
csv_writer = csv.writer(csv_account)
# writing the data row
csv_writer.writerows(row_account)
def showEvents(self):
#showing events based on is she admin or not
pass
def buy(self):
#buying events
pass
def addEvent(self):
#addingEvents
pass
class Event:
def __init__(self, date, location, capacity, cost):
self.date = date
self.location = location
self.capacity = capacity
self.cost = cost
with open("event.csv" ,'a', newline='') as csv_account:
csv_writer = csv.writer(csv_account)
csv_writer.writerows([date,location,capacity,cost])
|
43eb11b51339147fd49d99ea39b1e6d2d03ff0ea
|
alanniu99/codebyte
|
/letterChanages.py
| 433 | 4.1875 | 4 |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
def LetterChanges(str):
newStr = ""
for char in str:
if char.isalpha():
if char.lower() == 'z':
char = 'a'
else:
char = chr( ord(char) + 1 )
if char in "aeiou":
char = char.upper()
newStr = newStr + char
return newStr
print( LetterChanges( input("please input letters\n") ) )
|
83ff9347d8b13168ab53aceada5da6a7d491d857
|
knuu/competitive-programming
|
/aoj/24/aoj2441.py
| 1,029 | 3.65625 | 4 |
def count_div(start, end, div):
# [start, end)
return (end - 1) // div - (start - 1) // div
def calc_start(mid):
cnt, i = 0, 1
while 10 ** i < mid:
d, p = 10 ** i, 10 ** (i - 1)
fif, three, five = count_div(p, d, 15), count_div(p, d, 3), count_div(p, d, 5)
cnt += i * (d - p) + (three + five) * 4 - (three + five - fif) * i
i += 1
d = 10 ** (i - 1)
fif, three, five = count_div(d, mid, 15), count_div(d, mid, 3), count_div(d, mid, 5)
cnt += i * (mid - d) + (three + five) * 4 - (three + five - fif) * i
return cnt
N = int(input()) - 1
left, right = 1, 10 ** 18
while left + 1 < right:
mid = (left + right) // 2
start = calc_start(mid)
if start <= N:
left = mid
else:
right = mid
ans = ''
for i in range(left, left + 9):
tmp = ''
if i % 3 == 0:
tmp += "Fizz"
if i % 5 == 0:
tmp += "Buzz"
if not tmp:
tmp = str(i)
ans += tmp
start = calc_start(left)
print(ans[N - start:N - start + 20])
|
7694c5fb666041e14760f5a0200bb09225f8be84
|
alex99q/python3-lab-exercises
|
/Lab2/Exercise4.py
| 366 | 3.9375 | 4 |
leap_years = []
current_year = 2018
while len(leap_years) < 20:
current_year += 1
if current_year % 4 != 0:
continue
elif current_year % 100 != 0:
leap_years.append(current_year)
elif current_year % 400 != 0:
continue
else:
leap_years.append(current_year)
for year in leap_years:
print(year)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.