blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
2ea23abd8086888898e9990be20ba11ebadd02e2 | rostam/Experiments | /python/python-code-samples/TestingEvaluationML/anotherTest.py | 5,977 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
# ### Diabetes Case Study
#
# You now have had the opportunity to work with a range of supervised machine learning techniques for both classification and regression. Before you apply these in the project, let's do one more example to see how the machine learning process works from beginning to end with another popular dataset.
#
# We will start out by reading in the dataset and our necessary libraries. You will then gain an understanding of how to optimize a number of models using grid searching as you work through the notebook.
# Import our libraries
import pandas as pd
import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split, RandomizedSearchCV
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
import matplotlib.pyplot as plt
from sklearn.svm import SVC
import seaborn as sns
sns.set(style="ticks")
# Read in our dataset
diabetes = pd.read_csv('diabetes.csv')
# Take a look at the first few rows of the dataset
diabetes.head()
# Because this course has been aimed at understanding machine learning techniques, we have largely ignored items related to parts of the data analysis process that come before building machine learning models - exploratory data analysis, feature engineering, data cleaning, and data wrangling.
#
# > **Step 1:** Let's do a few steps here. Take a look at some of usual summary statistics calculated to accurately match the values to the appropriate key in the dictionary below.
# In[2]:
# Cells for work
diabetes.describe()
# In[3]:
sns.pairplot(diabetes, hue="Outcome");
# In[4]:
sns.heatmap(diabetes.corr(), annot=True, cmap="YlGnBu");
# In[5]:
diabetes.hist();
# In[6]:
# Possible keys for the dictionary
a = '0.65'
b = '0'
c = 'Age'
d = '0.35'
e = 'Glucose'
f = '0.5'
g = "More than zero"
# Fill in the dictionary with the correct values here
answers_one = {
'The proportion of diabetes outcomes in the dataset': d,
'The number of missing data points in the dataset': b,
'A dataset with a symmetric distribution': e,
'A dataset with a right-skewed distribution': c,
'This variable has the strongest correlation with the outcome': e
}
y = diabetes['Outcome']
X = diabetes[['Pregnancies','Glucose', 'BloodPressure', 'SkinThickness','Insulin', 'BMI', 'DiabetesPedigreeFunction', 'Age']]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# build a classifier
clf_rf = RandomForestClassifier()
# Set up the hyperparameter search
param_dist = {"max_depth": [3, None],
"n_estimators": list(range(10, 200)),
"max_features": list(range(1, X_test.shape[1]+1)),
"min_samples_split": list(range(2, 11)),
"min_samples_leaf": list(range(1, 11)),
"bootstrap": [True, False],
"criterion": ["gini", "entropy"]}
# Run a randomized search over the hyperparameters
random_search = RandomizedSearchCV(clf_rf, param_distributions=param_dist)
# Fit the model on the training data
random_search.fit(X_train, y_train)
# Make predictions on the test data
rf_preds = random_search.best_estimator_.predict(X_test)
# build a classifier for ada boost
clf_ada = AdaBoostClassifier()
# Set up the hyperparameter search
# look at setting up your search for n_estimators, learning_rate
# http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.AdaBoostClassifier.html
param_dist = {"n_estimators": [10, 100, 200, 400],
"learning_rate": [0.001, 0.005, .01, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 1, 2, 10, 20]}
# Run a randomized search over the hyperparameters
ada_search = RandomizedSearchCV(clf_ada, param_distributions=param_dist)
# Fit the model on the training data
ada_search.fit(X_train, y_train)
# Make predictions on the test data
ada_preds = ada_search.best_estimator_.predict(X_test)
ch.print_metrics(y_test, ada_preds, 'adaboost')
# In[10]:
# build a classifier for support vector machines
clf_svc = SVC()
# Set up the hyperparameter search
# look at setting up your search for C (recommend 0-10 range),
# kernel, and degree
# http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html
param_dist = {"C": [0.1, 0.5, 1, 3, 5],
"kernel": ['linear','rbf']
}
# Run a randomized search over the hyperparameters
svc_search = RandomizedSearchCV(clf_svc, param_distributions=param_dist)
# Fit the model on the training data
svc_search.fit(X_train, y_train)
# Make predictions on the test data
svc_preds = svc_search.best_estimator_.predict(X_test)
ch.print_metrics(y_test, svc_preds, 'svc')
# > **Step 5**: Use the test below to see if your best model matched, what we found after running the grid search.
# In[11]:
a = 'randomforest'
b = 'adaboost'
c = 'supportvector'
best_model = b # put your best model here as a string or variable
# Show your work here - the plot below was helpful for me
# https://stackoverflow.com/questions/44101458/random-forest-feature-importance-chart-using-python
features = diabetes.columns[:diabetes.shape[1]]
importances = random_search.best_estimator_.feature_importances_
indices = np.argsort(importances)
plt.title('Feature Importances')
plt.barh(range(len(indices)), importances[indices], color='b', align='center')
plt.yticks(range(len(indices)), features[indices])
plt.xlabel('Relative Importance');
# and running this cell
a = 'Age'
b = 'BloodPressure'
c = 'BMI'
d = 'DiabetesPedigreeFunction'
e = 'Insulin'
f = 'Glucose'
g = 'Pregnancy'
h = 'SkinThickness'
sol_seven = {
'The variable that is most related to the outcome of diabetes' : f,
'The second most related variable to the outcome of diabetes' : c,
'The third most related variable to the outcome of diabetes' : a,
'The fourth most related variable to the outcome of diabetes' : d
}
|
4d09c4c6782c12470c7ad19b72fb89443acdd978 | QinmengLUAN/Daily_Python_Coding | /wk11_HT_uniqueOccurrences_LC1207.py | 1,056 | 3.953125 | 4 | """
1207. Unique Number of Occurrences
Easy: Hash Table
Given an array of integers arr, write a function that returns true if and only if the number of occurrences of each value in the array is unique.
Example 1:
Input: arr = [1,2,2,1,1,3]
Output: true
Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.
Example 2:
Input: arr = [1,2]
Output: false
Example 3:
Input: arr = [-3,0,1,-3,1,1,1,-3,10,0]
Output: true
"""
class Solution:
def uniqueOccurrences(self, arr: List[int]) -> bool:
arr_counter = Counter(arr)
arr_unique = set(arr_counter.values())
return len(arr_counter) == len(arr_unique)
def uniqueOccurrences1(self, arr: List[int]) -> bool:
arr_counter = Counter(arr)
# print(arr_counter)
appeared_occur = set()
for item in set(arr):
if arr_counter[item] in appeared_occur:
return False
else:
appeared_occur.add(arr_counter[item])
return True |
0209d97e93a70d10bdb739783605bba86104327d | marioleonardo/informatica_1_lab | /laib3/es6.py | 321 | 3.71875 | 4 | import math
num = float(input("Qual è il numero?\n"))
num = math.ceil(num)
if (num <= 4 and num >= 0):
print("A" if num == 4 else "", end="")
print("B" if num == 3 else "", end="")
print("C" if num == 2 else "", end="")
print("D" if num == 1 else "", end="")
print("F" if num == 0 else "", end="")
|
9006f0371809f41105ebb23c3ca395ee86772882 | qzying/leetcode-private | /python/best-time-to-buy-and-sell-stock-iii.py | 1,870 | 3.75 | 4 | r"""
给定一个数组,它的第i个元素是一支给定的股票在第i天的价格。
设计一个算法来计算你所能获取的最大利润,你最多可以完成两笔交易。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
示例 1:
输入:prices = [3,3,5,0,0,3,1,4]
输出:6
解释:在第4天(股票价格 = 0)的时候买入,在第6天(股票价格 = 3)的时候卖出,这笔交易所能获得利润 = 3-0 = 3。
随后,在第7天(股票价格 = 1)的时候买入,在第8天(股票价格 = 4)的时候卖出,这笔交易所能获得利润 = 4-1 = 3。
示例 2:
输入:prices = [1,2,3,4,5]
输出:4
解释:在第1天(股票价格 = 1)的时候买入,在第5天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4。
注意你不能在第1天和第2天接连购买股票,之后再将它们卖出。因为这样属于同时参与了多笔交易,你必须在再次购买前出售掉之前的股票。
示例 3:
输入:prices = [7,6,4,3,1]
输出:0
解释:在这个情况下, 没有交易完成, 所以最大利润为0。
示例 4:
输入:prices = [1]
输出:0
提示:
(1) 1 <= prices.length <= 105
(2) 0 <= prices[i] <= 105
"""
import numpy as np
class Solution:
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
dp = np.zeros((n + 1, 2 + 1, 2))
dp[0, :, 0] = 0
dp[0, :, 1] = -sys.maxsize
dp[:, 0, 0] = 0
dp[:, 0, 1] = -sys.maxsize
for i in range(1, n + 1):
for j in range(2, 0, -1):
dp[i][j][0] = max(dp[i - 1][j][0], dp[i - 1][j][1] + prices[i - 1])
dp[i][j][1] = max(dp[i - 1][j][1], dp[i - 1][j - 1][0] - prices[i - 1])
return int(dp[n][2][0])
|
edcf8b46cb6b094d6bb14c1f55a68230c42a7aaa | BackupTheBerlios/elisa-svn | /trunk/elisa/utils/misc.py | 438 | 3.515625 | 4 | import os
def file_extension_matches(filename, pattern_list):
path, extension = os.path.splitext(filename)
# strip ext separator
extension = extension[1:]
extension = extension.lower()
return extension in pattern_list
def file_is_picture(filename):
return file_extension_matches(filename,('jpg', 'png', 'jpeg', 'gif'))
def file_is_movie(filename):
return file_extension_matches(filename,('avi','mov'))
|
670a71dd45009dd3cc1b73174c4b093c0a90805a | tcandzq/LeetCode | /Stack/ReverseSubstringsBetweenEachPairOfParentheses.py | 1,202 | 3.609375 | 4 | # -*- coding: utf-8 -*-
# @File : ReverseSubstringsBetweenEachPairOfParentheses.py
# @Date : 2020-02-25
# @Author : tc
"""
题号 1190. 反转每对括号间的子串
给出一个字符串 s(仅含有小写英文字母和括号)。
请你按照从括号内到外的顺序,逐层反转每对匹配括号中的字符串,并返回最终的结果。
注意,您的结果中 不应 包含任何括号。
示例 1:
输入:s = "(abcd)"
输出:"dcba"
示例 2:
输入:s = "(u(love)i)"
输出:"iloveu"
示例 3:
输入:s = "(ed(et(oc))el)"
输出:"leetcode"
示例 4:
输入:s = "a(bcdefghijkl(mno)p)q"
输出:"apmnolkjihgfedcbq"
"""
class Solution:
def reverseParentheses(self, s: str) -> str:
s = list(s)
stack = []
n = len(s)
for i in range(n):
if s[i] == '(':
stack.append(i)
s[i] = ''
if s[i] == ')' and stack:
s[i] = ''
start = stack.pop()
s[start:i] = s[start:i][::-1]
return ''.join(s)
if __name__ == '__main__':
s = "(ed(et(oc))el)"
solution = Solution()
print(solution.reverseParentheses(s)) |
b1928474f0b8fca4f0cb0ac1705b8c58c8b09e6c | gohst9/misc | /my_queue.py | 1,412 | 4.21875 | 4 | class Queue_item:
#キュー内の要素にはそれ自体の値と次の値へのリンクがある
def __init__(self,v,next=None):
self.value = v
self.next = next
class Queue:
def __init__(self,v=0):
self.first = None
self.last = None
def push(self,v):
#キューの一番後ろに値を付け足す
if self.first == None:
self.first = Queue_item(v)
self.last = self.first
else:
#キューの一番最後の要素に新しい要素へのリンクを追加した後、
#一番最後を新しい要素に変える
self.last.next = Queue_item(v)
self.last = self.last.next
def pop(self):
if self.first == None:
return None
#一番最初の要素を取り出した後、
#Queue_Item内の次の要素へのリンク(next)をつかって
#一番最初の要素を次の要素に変える
temp = self.first.value
if self.first.next != None:
self.first = self.first.next
else:
self.first = None
self.last = None
return temp
def main():
q = Queue()
for i in [1,2,3]:
q.push(i)
for i in range(3):
print(q.pop())
#先入れ先出しで「1,2,3」の順番で出力される
if __name__ == '__main__':
main()
|
ac5d146845124c159ccee1090552add807fd87eb | jmaitoza/ECE256_Lab2 | /Lab2/caesar_encrypt.py | 1,248 | 4.09375 | 4 | #!/usr/bin/env python3
import os
import sys
shift = int(sys.argv[1])
plaintext = open("plaintext.txt", "r") #opens plaintext file
plntxt = plaintext.read().strip()
encrypted = ""
for c in plntxt:
# if not c.isalpha():
# pass
# continue
#if c.isupper(): # checks if plain text is capital letters
c_uni = ord(c) #turns char into unicode
c_index = ord(c) - ord(" ") #creates new index
new_index = (c_index + shift) % 94 #shifts each char based on shift value
new_uni = new_index + ord(" ") #converts unicode back to char
new_char = chr(new_uni)
encrypted = encrypted + new_char # creates new string based on encrypted characters
# else:
# c_uni = ord(c)
# c_index = ord(c) - ord("a")
# new_index = (c_index + shift) % 26
#
# new_uni = new_index + ord("a")
# new_char = chr(new_uni)
#
# encrypted = encrypted + new_char
print("Plain text: ", plntxt)
print("Encrypted text: ", encrypted)
ciptext = open("ciphertext_file.txt", "r+") #opens ciphertext file
contents = ciptext.read().split("\n") #following code checks if file is empty and if not empties the file to write new text to it
ciptext.seek(0)
ciptext.truncate()
ciptext.write(encrypted) #writes encryped text to file
plaintext.close() #closes files
ciptext.close()
|
70167c3c529371165544332fd791aa5ddf66cec0 | plenari/omfPython | /mpy0.0/fit_circle.py | 2,952 | 3.796875 | 4 | # -*- coding: utf-8 -*-
'''
计算excel文件里铁磁斯格明子的直径,只能含有一个斯格明子
>>>main(path,length=[0,1000],step=2e-9,name='M%d.xlsx',dname=3):
>>>length[start,stop],
>>>这个只能处理方格的情况,每隔格子的长度为step
>>>dname:希望用输入路径中倒数第几个来命名结果,比如:
>>>D:\\relax700\\relax250Hz700\\txt\\excel,倒数第三个,所以dname=3
>>>step,保存到excel的直径将乘以这个数字
>>>name,文件的格式,数字用%d代替。
'''
import pandas as pd
import numpy as np
import math
import os
def circle(x,y):#拟合圆形,最小二乘法
if len(x)==0:
return 0,0,0
x1,x2,x3,y1,y2,y3=0.,0.,0.,0.,0.,0.
x1y1,x1y2,x2y1=0.,0.,0.
N=len(x)
for i in range(N):
x1=x1+x[i]
x2=x2+x[i]**2
x3=x3+x[i]**3
y1=y1+y[i]
y2=y2+y[i]**2
y3=y3+y[i]**3
x1y1=x1y1+x[i]*y[i]
x1y2=x1y2+x[i]*y[i]*y[i]
x2y1=x2y1+x[i]*x[i]*y[i]
C=N*x2-x1**2
D=N*x1y1-x1*y1
E=N*x3+N*x1y2-(x2+y2)*x1
G=N*y2-y1**2
H=N*x2y1+N*y3-(x2+y2)*y1
a=(H*D-E*G)/(C*G-D*D)
b=(H*C-E*D)/(D*D-G*C)
c=-(a*x1+b*y1+x2+y2)/N
A=-a/2
B=-b/2
D=math.sqrt(a**2+b**2-4*c)
return D,A,B
def main(pdir,pfiles,step=2e-9,dname=3,save=True,save_path=None):
indexs,D,A,B=[],[],[],[]
for i in pfiles:
x,y=getxy(os.path.join(pdir,i))
d,a,b=circle(x,y)
D.append(d*step)
A.append(a*step)
B.append(b*step)
indexs.append(i)
print(i,d)
re=np.array([D,A,B])
name=pdir.split(os.sep)[-dname]
result1=pd.DataFrame(re.T,columns=['Dia','X','Y'],index=indexs)
if save==True:
result1.to_excel(os.path.join(save_path,'Position-%s.xlsx'%name))
return result1
def getxy(path):
'''
输入数据的列是x轴,行是y轴.
'''
data=np.array(pd.read_excel(path))
data_mul=data[:,:-1]*data[:,1:]
loc=np.where(data_mul<0)
locx,locy=loc[1],loc[0]#分别是第几列x,第几行y
m0,m1=data[loc],data[locy,locx+1]#
calx=(-m0)/(m1-m0)+locx
return calx,locy
if __name__=='__main__':
#如果需要更改数据,都在下边这行更改,在上边更改无效。
step=2e-9 #cellsize
dname=1 #用倒数第三个名字命名新的excel
pdir=input(r'请输入计算直径excel所在的文件夹:')
pfiles=[i for i in os.listdir(pdir) if i.split('.')[-1]=='xlsx']
pfiles=sorted(pfiles)
###########以下不需要更改
name=pdir.split(os.sep)[-dname]#
save_path=pdir.split(pdir.split(os.sep)[-dname])[0]
print('''当前使用的参数如下:\n1,计算文件夹:{}
\n2,cellsize:{}\n3,excel名字:{}\n4,保存路径:{}'''.format(pdir,step,name,save_path))
main(pdir,pfiles,step=step,dname=dname,save_path=save_path)
|
0a25cecdfdf8f6eae74ce90af5971649d0da15d0 | SalahCoder/Rock-Paper-Scissors | /main.py | 1,488 | 4.09375 | 4 | import random
option_choosen = int(input("what do u choose \n type\n 0 for Rock ⚫️ \n 1 for paper 📄\n 2 for scissors ✂️ : "))
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
if option_choosen == 0:
print(rock)
elif option_choosen == 1:
print(paper)
elif option_choosen == 2:
print (scissors)
else:
print("invalid entry")
computer_choice = random.randint(0 , 2)
print("computer chose: \n")
if computer_choice == 0:
print(rock)
elif computer_choice == 1:
print(paper)
elif computer_choice == 2:
print (scissors)
else:
print("ops the Computer is cheater")
if computer_choice == option_choosen :
print("Drow")
elif option_choosen == 0 and computer_choice == 1:
print("computer win😂 .. You loss🥺")
elif option_choosen == 1 and computer_choice == 2:
print("computer win😂 .. You loss🥺")
elif option_choosen == 2 and computer_choice == 0:
print("computer win😂 .. You loss🥺")
elif option_choosen == 0 and computer_choice == 2:
print("You win 😍 .. computer loss🥺")
elif option_choosen == 1 and computer_choice == 0:
print("You win 😍 .. computer loss🥺")
elif option_choosen == 2 and computer_choice == 1:
print("You win 😍 .. computer loss🥺")
|
7d39b12fb86bfcf572329dca9ae91c83da28c75e | ElshadaiK/Competitive-Programming | /red_and_blue.py | 687 | 3.65625 | 4 | def maximizer(reds, blues):
red_sum = 0
blue_sum = 0
max_red = 0
max_blue = 0
for red in reds:
red_sum += int(red)
max_red = max(max_red, red_sum)
for blue in blues:
blue_sum += int(blue)
max_blue = max(max_blue, blue_sum)
return max_blue+max_red
if __name__ == '__main__':
t = int(input().rstrip())
temp = []
for i in range(t):
red_count = int(input().rstrip())
reds = input().rstrip().split()
blue_count = int(input().rstrip())
blues = input().rstrip().split()
temp.append([reds, blues])
for inputs in temp:
print(maximizer(inputs[0], inputs[1])) |
d4e5b77c4a5c8e22ed20ca0e6c80a74e1dbf0780 | jjlicky/python-basic | /파이썬 기초(조건문,반복문,복합자료형,함수)/함수예제 sumAll3.py | 157 | 3.5 | 4 | def sumAll(*values):
sum=0
for i in values:
sum+=i
print("1부터 10까지의 합은 %d 입니다."%(sum))
sumAll(1,2,3,4,5,6,7,8,9,10)
|
e4ed7b98a241eedea5d0dc9420c788c52419a833 | Prakashchater/Daily-Practice-questions | /largest.py | 1,167 | 3.859375 | 4 | # def large1(arr):
# mx = arr[0]
# for i in range(len(arr)):
# if arr[i] > mx:
# mx = arr[i]
# return mx
#
# if __name__ == '__main__':
# arr = [70, 11, 20, 4, 100]
# print(large1(arr))
# def large2(arr):
# mx = max(arr[0], arr[1])
# secmx = min(arr[0],arr[1])
#
# for i in range(2,len(arr)):
# if arr[i]>mx:
# secmx = mx
# mx = arr[i]
# elif arr[i] > secmx and mx != arr:
# secmx = arr[i]
# return secmx
#
# if __name__ == '__main__':
# arr = [70, 11, 20, 4, 100]
# print(large2(arr))
import sys
def large3(arr):
if len(arr) < 3:
print("Invalid")
return
first = arr[0]
for i in range(1,len(arr)):
if arr[i] > first:
first = arr[i]
second = -sys.maxsize
for i in range(0,len(arr)):
if arr[i] > second and arr[i] < first:
second = arr[i]
third = -sys.maxsize
for i in range(0,len(arr)):
if arr[i] > third and arr[i] < second:
third = arr[i]
return third
if __name__ == '__main__':
arr = [70, 11, 20, 4, 90,100]
print(large3(arr))
|
3c313bd2c0d10b1ffa8686c3c9fe523b28a43a75 | aswaniramachandran/programming-lab-aswani | /CO1 PG 13.py | 176 | 3.65625 | 4 | n=int(input("Enter a limit:"))
print(f"Enter {n} colour names:")
c=[]
for i in range(0,n):
c.append(input())
for i in range(0, n):
print(c[0],c[n-1])
break
|
a9f37012ed908abdc5db839bc1d9a2ea4156dcd2 | ahatzz11/advent-of-code | /2019/02/two.py | 1,477 | 3.59375 | 4 | #!/usr/bin/env python
# part one: 3402634
# part two: 5101069
import sys
def main(args):
f = open("input.txt","r")
instructions = f.read().split(",")
i = 0
for instruction in instructions:
instructions[i] = int(instruction)
i += 1
current_index_offset = 0
while(instructions[current_index_offset]):
if(instructions[0 + current_index_offset] == 1):
print('adding!')
noun = instructions[instructions[1 + current_index_offset]]
verb = instructions[instructions[2 + current_index_offset]]
new_position = instructions[3 + current_index_offset]
instructions[new_position] = noun + verb
elif(instructions[0 + current_index_offset] == 2):
print('multiplying!')
noun = instructions[instructions[1 + current_index_offset]]
verb = instructions[instructions[2 + current_index_offset]]
new_position = instructions[3 + current_index_offset]
instructions[new_position] = noun * verb
elif(instructions[0 + current_index_offset] == 99):
print('dead!')
sys.exit(0)
current_index_offset += 4
print(instructions)
print(instructions)
def part2(data):
for noun in range(100):
for verb in range(100):
if part1(data, noun, verb) == 19690720:
return 100 * noun + verb
if __name__ == '__main__':
main(sys.argv)
|
cf912e0a6b85487110eca93a0be942a8185c33a4 | LucasMaiale/Libro1-python | /Cap3/Programa 3_29.py | 1,329 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
@author: guardati
Solución del problema 3.29
Calcula e imprime el costo de un paquete turístico de acuerdo
con el destino, el nivel y la cantidad de días de duración.
"""
destino = input('Ingrese el tipo de destino (playa/colonial/arqueológica): ')
nivel_paquete = input('Ingrese nivel de paquete (exclusivo/lujo/estándar): ')
numero_dias = int(input('Ingrese los días de duración del viaje: '))
''' Se asigna el valor del costo diario de acuerdo con el destino. Observe
que,si el usuario se equivoca e ingresa un destino diferente a los 3
previstos, el programa asignará el valor de $900, y calculará e imprimirá
un resultado inconsistente. A pesar de que existen maneras de evitar
este tipo de errores, en esta solución no se hace. '''
if destino == 'playa':
costo_dia = 1200
elif destino == 'colonial':
costo_dia = 1000
else:
costo_dia = 900
costo_paquete = costo_dia * numero_dias
# Se aplica un recargo si el nivel es exxclusivo o lujo.
if nivel_paquete == 'exclusivo':
costo_paquete *= 1.3
elif nivel_paquete == 'lujo':
costo_paquete *= 1.1
if numero_dias > 10:
costo_paquete *= 0.92 # Se aplica el descuento del 8% para estadías > 10 días.
print(f'\nEl costo del paquete elegido es ${costo_paquete:.2f}')
|
d379cfc6f12a7bfe6edc398c146dbf16fc86c578 | katesem/sololearn | /us_date_to_eu.py | 461 | 3.78125 | 4 | s = input()
if '/' in s:
s = s.split('/')
print(('/').join([s[1],s[0],s[2]]))
else:
d = {
"January": 1,
"February": 2,
"March": 3,
"April": 4,
"May": 5,
"June": 6,
"July": 7,
"August": 8,
"September": 9,
"October": 10,
"November": 11,
"December": 12
}
s = s.replace(',','').split(' ')
print(('/').join([s[1], str(d[s[0]]), s[2]]))
|
042d46b3933a28a92448696bf6fffe96a648d9a1 | BurlaSaiTeja/Python-Codes | /Lists/Lists06.py | 228 | 4.28125 | 4 | """
Write a Python program to generate all permutations of a list in Python.
"""
import itertools
print(list(itertools.permutations([1,2,3])))
"""
Output:
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
"""
|
a1dcfdcf71ead60e6957be78bf81baeecd27b3a9 | Abhijit2505/Survival-Analysis | /Abhijit/Nelson Aalen Estimator/NA_estimator.py | 2,684 | 3.609375 | 4 | # importing the required python libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from lifelines import NelsonAalenFitter
# reading the data into python dataframe
telco_data = pd.read_csv('telco_customer.csv')
# filtering and preparing the data to the required format
telco_data['TotalCharges']=pd.to_numeric(telco_data['TotalCharges'],errors='coerce')
telco_data['Churn']=telco_data['Churn'].apply(lambda x: 1 if x == 'Yes' else 0 )
# the duration varaiable column
T = telco_data['tenure']
# the target event(occures/not occured) column
E = telco_data['Churn']
# creating a NelsonAalenFitter object and fitting the duration and event colum data to it
naf = NelsonAalenFitter()
naf.fit(T,event_observed=E)
# printing out the NA Estimations (cummulative hazard rates)
print(naf.cumulative_hazard_.head())
print(naf.cumulative_hazard_.tail())
# utility function to plot the NA Estimator
def plot_estimator():
naf.plot(figsize=(12,10),label="NA Estimator")
plt.xlabel('Tenure',size=15)
plt.ylabel('NA Estimate(Commulative Hazard Function Estimator)',size=13)
plt.title('Plotting NA Estimate against the churning tenure of a customer',size=15)
plt.legend(prop={'size': 16})
# utility function to smoothen the curve and compare between the plots
def plot_function(category1,category2,bandwidth,column_name):
small_ans = (telco_data[column_name] == category1)
naf.fit(T[small_ans], event_observed=E[small_ans], label= category1)
ax = naf.plot_hazard(bandwidth=bandwidth,figsize=(10,8))
naf.fit(T[~small_ans], event_observed=E[~small_ans], label= category2)
naf.plot_hazard(ax=ax, bandwidth=bandwidth,figsize=(10,8))
plt.legend(title = column_name,prop={'size': 12})
plt.title('Curve Smoothening and Comparing({})'.format(column_name),size=12)
# utility function for a plot generation to explain the smoothness and bandwidth factor visually
def smooth_analysis():
n = 10
while(n<=100):
naf.plot_hazard(bandwidth=n,figsize=(15,13),label=n)
n+=10
plt.tight_layout()
plt.legend(title= 'Bandwidth',prop={'size': 12})
# plotting the NA Estimator
plot_estimator()
# getting a visualization of bandwidth and smoothness of the NA Estimator
smooth_analysis()
# smoothing the NA Estimator
naf.plot_hazard(bandwidth=10,figsize=(12,10),title="Smoother NA Estimator",label="NA Estimator")
# smoothing and comparing according to the column's entry
plot_function('Male','Female',3,'gender')
plot_function('Yes','No',3,'PhoneService')
plot_function('Yes','No',3,'Partner')
plot_function('Yes','No',3,'Dependents')
plot_function('Yes','No',3,'PaperlessBilling')
|
bfb6ba4f9b944beee17cf3609107882c7a3c1c96 | ataylor89/leetcode | /problem0110.py | 1,476 | 3.546875 | 4 | class Solution(object):
def isBalanced(self, root):
if root == None:
return True
self.assignHeight(root)
if root.left == None and root.right == None:
return True
elif root.left != None and root.right == None:
return root.left.height == 0
elif root.right != None and root.left == None:
return root.right.height == 0
else:
lh = root.left.height
rh = root.right.height
bl = self.isBalanced(root.left)
br = self.isBalanced(root.right)
return abs(lh - rh) <= 1 and bl and br
def assignHeight(self, node):
if node == None:
return
node.height = None
if node.left == None and node.right == None:
node.height = 0
if node.left != None and node.right == None:
self.assignHeight(node.left)
node.height = 1 + node.left.height
elif node.right != None and node.left == None:
self.assignHeight(node.right)
node.height = 1 + node.right.height
elif node.left != None and node.right != None:
self.assignHeight(node.left)
self.assignHeight(node.right)
node.height = 1 + max(node.left.height, node.right.height)
|
c157ab69c10a9d670ff2a28653ad592e22d00fa7 | avinash-mishra/codeInPython | /pythonConcepts/os_module.py | 1,361 | 4.46875 | 4 | # Creating and removing files and directories with Python os module
"""This is done with the os module, which has lots of methods for handling files and dirs"""
import os # this line will import os module
# Make a new file.
# Simply opening a file in write mode will create it at specified location, if it doesn't exist. ( If file does exist,
# the act of opening
# it in write mode will completely overwrite its contents.)
try:
f = open("file.txt", "w") # It will create file.txt in current location
except IOError as e:
print(e.errno)
print(e)
# Remove a file
try:
os.remove("file.txt")
except os.error as e:
print(e.errno)
print(e)
# Make a directory
os.mkdir('dirname')
# Recursive directory creation: creates die_c and if necessary dir_b and dir_a
os.mkdir('dir_a/dir_b/dir_c')
# Remove an empty directory
os.rmdir('dirname')
os.rmdir('dir_a/dir_b/dir_c') # Removes dir_c only
######################################################################################################33
# Create a directory and set user:group with python's os module
import pwd
file_path = 'example'
if not os.path.exists(file_path):
os.makedirs(file_path) # Creates with default permission of 0777
uid, gid = pwd.getpwnam('root').pw_uid, pwd.getpwnam('avi').pw_uid
os.chown(file_path, uid, gid) # set user:group as root:avi
|
659fca32acee07d20c8ef117512d6f06d238fe16 | BROjohnny/Python-A-Z-and-BasicPrograms- | /10 Dictionary/dictionary.py | 515 | 4.15625 | 4 | #this is how to define dictionary in python
pythonDic = {}
#this is how add values for dictionary
pythonDic = {'janidu' : 'most kind person i ever met' , 'yoshini' : 'most angryful girl i ever met'}
print(pythonDic.items())
print(pythonDic.keys())
print(pythonDic.values())
pythonDic['hansika'] = 'she is pretty but high class,cant reach from in my level'
print(pythonDic.items())
#delete items from the dictionary
del(pythonDic['hansika'])
print(pythonDic.items())
pythonDic.clear()
print(pythonDic.items())
|
21a1707916b1019e4d08fa2d0c028edb7a6fed00 | jasonlingo/RoadSafety | /Map/Shapefile.py | 879 | 3.71875 | 4 | import shapefile as shp
def ParseShapefile(filename):
"""
Extract GPS points from a shapefile.
Args;
(String) filename: the address of a shapefile.
Return:
(list) shapePoint: a list of GPS point in the given shapefile.
"""
# Read the shapefile and get its shape records.
ctr = shp.Reader(filename)
ShapeRecords = ctr.iterShapeRecords()
# For storing GPS data of roads.
shapePoint = []
# Extract GPS data of major roads that are the types of
# 'trunk' and 'primary'.
for sr in ShapeRecords:
if sr.record[0] in ['trunk', 'primary']:
shapePoint.append([])
for point in sr.shape.points:
shapePoint[-1].append((point[1], point[0]))
return shapePoint
#ParseShapefile("/Users/Jason/GitHub/RoadSeftey/RoadSafety/Data/shapefile/delhi_highway/delhi_highway.shp")
|
2b079fa9f884419fba9061341f0e8200390dbcdd | jack-x/HackerEarthCode | /E_NotInRange.py | 2,388 | 3.625 | 4 | '''
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
'''
# Write your code here
def sumNatural(num):
return int(num*(num+1)/2)
def main():
x = 1000000
sum = int(x*(x+1)/2)
#print(sum)
N = int(input())
for case in range(0,N):
i = input().split(' ')
l = int(i[0])
r = int(i[1])
#print("L: {} and R: {}".format(l,r))
addition = sumNatural(r) - sumNatural(l-1)
#print("Sum of numbers from L to R: {}".format(addition))
sum -= addition
#print("Sum Remaining: {}".format(sum))
print(sum)
def findPosition(arr,x):
a = 0
b = len(arr)
while a!=b and (b-a) > 1:
mid = int((a+b)/2)
if arr[mid] == x:
return mid
else:
if arr[mid] > x:
b = mid
elif arr[mid] < x:
a = mid
return a
def main2():
x = 1000000
sum = int(x*(x+1)/2)
removekey = [0] * 1000001
N = int(input())
if N == 0:
print(sum)
return
ranges = []
#initializing case 1
i = input().split(' ')
l = int(i[0])
r = int(i[1])
LRarray = [[l,r]]
Larray = [l]
for case in range(1,N):
i = input().split(' ')
l = int(i[0])
r = int(i[1])
#find position
index = findPosition(Larray,l) #binarySearch
for x in range(index,index-1,-1):
LR = LRarray[x]
#print(LRarray)
#print(Larray)
#print(x)
if l <= LR[0] and r>= LR[1]:
LRarray[x] = [l,r]
Larray[x] = l
break
if ( l >=LR[0] and l<=LR[1] ) and r>= LR[1]:
LRarray[x][1] = r
break
if l == LR[1] :
LRarray[x][1] = r
break
if l>LR[1]:
LRarray.insert(x+1,[l,r])
Larray.insert(x+1,l)
break
for y in LRarray:
for x in range(y[0],y[1]+1):
removekey[x] = x
removekey.pop(0)
for x in removekey:
sum -= x
print(sum)
main2()
|
13fbaa6dc28208e99f2c170776df929d28a40ede | jineshpaloor/ProjectEuler | /p07.py | 841 | 3.953125 | 4 | """
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
"""
def main():
# n = 6
# p = 13
# while n < 10001:
# p = p + 2
# is_prime = True
# for i in range(2,p/2 + 1):
# if p % i == 0:
# is_prime = False
# break
# if is_prime:
# n = n + 1
#
# print p
MAX = 105000
numbers = [True] * MAX
numbers[0] = numbers[1] = False
primes = []
for number,is_prime in enumerate(numbers):
if is_prime:
primes.append(number)
if len(primes) == 10001:
break
for i in range(number+number, MAX, number):
numbers[i] = False
print primes[10000]
if __name__ == "__main__":
main()
|
6b3820b099a6d33c188d8441145dbdf2a7d52bec | liorbraun/wordplay | /Functions_Logic.py | 2,040 | 3.625 | 4 | import random
import pandas as pd
from player import add_player
from wordgame import listofplayers
def add_player_func(playername, word, opponent):
try:
add_player(playername, word, opponent)
except:
pass
def get_random_word():
try:
for player_word in listofplayers:
listofwords = pd.read_csv("word.csv")
player_word.word = listofwords["word"][random.randint(1, 10)]
except:
pass
def print_list():
for print_player in listofplayers:
print("player name: " + print_player.name + " player opponent : " +
print_player.opponent_name + " word :" + print_player.word + "\n")
def get_opponent():
try:
list_op = []
for player in listofplayers:
list_op.append(player)
for player in listofplayers:
while list_op:
player_op = random.choice(list_op)
if player != player_op:
player.opponent_name = player_op.name
list_op.remove(player_op)
break
except:
pass
def kill_opponent():
try:
print("kill opponent")
player_name = input("Enter your name : ")
for player in listofplayers:
if player.name == player_name:
ans = input("Are you really {} ? y/n ".format(player_name))
if str.lower(ans) == "y":
kill_ans = input(
"Did you kill {} : y/n ".format(player.opponent_name))
if kill_ans == "y":
for opponent in listofplayers:
if opponent.name == player.opponent_name:
player.opponent_name = opponent.opponent_name
player.word = opponent.word
listofplayers.remove(opponent)
break
else:
print("So go kill him!")
except:
pass
|
1a6dd83c2de641d61f367260cbd1e381956f5034 | jgarte/Python | /Chapter 03/substitutecrypt.py | 263 | 3.8125 | 4 | def substitutionEncrypt(plainText,key):
alphabet = "abcdefghijklmnopqrstuvwxyz "
plainText = plainText.lower()
cipherText = ""
for ch in plainText:
idx = alphabet.find(ch)
chipherText = cipherText + key[idx]
return cipherText
|
458aa7b7e8015db201c1c8563d93c48d849cd634 | moodycam/MARS-5470-4470 | /Hopkins/Homeworks/Week 3/Hopkins_Exercises_WK3.py | 4,235 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 4 14:52:51 2019
@author: srv_veralab
"""
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
person = input('Enter your name:')
#%%
"""
Exercise 1
"""
def scary():
person = input('Enter your name: ')
# Creates an input to place your name.
age = input('Enter your age: ')
# Creates an input to place your age.
old = 2019 - int(age) + 100
# Gives the ouput of the current year minus input age plus 100 years.
old = str(old)
# Converts the variable of 'old' to a string so it can be concatenated
return('Hello ' + person + ". " + "In " + old + " you will be 100 years old.")
# Returns the ouput: Hello [inputted name]. In [outputted year] you will
# be 100 years old.
scary()
#%%
"""
Exercise 2
"""
def divide():
number = input('Enter your number: ')
# Creates a prompt to enter a number
number = int(number)
# Turns the number into an integer
m = number % 2
# Returns the remainder after dividing number by 2
if m > 0:
print("Odd.")
# If "m" is greater than 0 than the number is odd, otherwise it is even.
else:
print("Even.")
divide()
#%%
"""
Exercise 9
"""
def guess():
import random
a = random.randint(1,9)
# Chooses a random number between (and including) 1 and 9
number = int(input('Give me a number between 1 and 9: '))
# Asks the user to input a number between 1 and 9 as an attempted guess
# for the random number chosen by the program
if a > number:
print("Too Low!")
# If the generated number is greater than the chosen number.
elif a < number:
print("Too High!")
# If the generated number is lower than the chosen number.
else:
print("Perfect!")
# If you're exactly right.
guess()
#%%
"""
Exercies 13
"""
def gen_fib():
count = int(input("How many fibonacci numbers would you like to generate?"))
i = 1
if count == 0:
fib = []
# If the input is '0' print nothing
elif count == 1:
fib = [1]
# Otherwise, if the input is '1' print '1'
elif count == 2:
fib = [1,1]
# If the input is '2' print '1, 1'
elif count > 2:
fib = [1,1]
while i < (count - 1):
fib.append(fib[i] + fib[i-1])
i += 1
# Else if the input is greater than '2', first print '1,1' to get
# started, then take the count and count-1 and add them
# together to create a new variable 'i'
# Eventual return is 'fib', which is the final elif return if the
# input is greater than '2'
return fib
gen_fib()
#%%
"""
Dr. Harrison's Answer for Exercise 13
"""
fib1 = 0; fib2 = 1;
counter = 5
print(fib2)
while counter>1:
print(fib2+fib1)
temp = fib2 + fib1
fib1 = fib2
fib2 = temp
counter -= 1
"""
Changing Dr. Harrison's code into a function
"""
def gen_fib2():
count = int(input("How many fibonacci numbers would you like to generate?"))
fib1 = 0; fib2 = 1
while count>1:
print(fib2+fib1)
temp = fib2 + fib1
fib1 = fib2
fib2 = temp
count -= 1
return
gen_fib2()
#%%
"""
Exercise 25
"""
import random
def guess1():
ans2 = input("Is your answer 50? ")
ans3 = 0
guess = 50
count = 1
while ans2 != "yes":
count += 1
# If yes => done
if ans2 == "yes":
print("Great! I solved it in "+str(count)+"tries!")
# If no
else:
# Is it high or low?
ans3 = input("higher or lower? ")
# If High
if ans3 == "higher":
guess += random.randint(1, 5)
ans2 = input("Ok. Is it " + str(guess) + "? ")
# If Low
elif ans3 == "lower":
guess -= random.randint(1, 5)
ans2 = input("Ok. Is it " + str(guess) + "? ")
return print("Great! I solved it in "+str(count)+" tries!")
guess1()
|
9bb843ef70a895d700911c9e0bddb50f661e8af4 | laxur1312/py4e | /ex_07_01.py | 244 | 3.765625 | 4 | print('python shout.py')
fname=input('Enter a file name: ')
try:
fhandle=open(fname)
except:
print('Archivo no encontrado')
exit()
for line in fhandle:
rline=line.rstrip()
rline=rline.upper()
print(rline)
|
f71986ca7dd932abde2d6f7f95646ee246375328 | shehryarbajwa/Algorithms--Datastructures | /Algorithms-Project 1/Task3.py | 2,893 | 4.1875 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('/Users/shehryarbajwa/algorithms-challenges/texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('/Users/shehryarbajwa/algorithms-challenges/calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 3:
(080) is the area code for fixed line telephones in Bangalore.
Fixed line numbers include parentheses, so Bangalore numbers
have the form (080)xxxxxxx.)
Part A: Find all of the area codes and mobile prefixes called by people
in Bangalore.
- Fixed lines start with an area code enclosed in brackets. The area
codes vary in length but always begin with 0.
- Mobile numbers have no parentheses, but have a space in the middle
of the number to help readability. The prefix of a mobile number
is its first four digits, and they always start with 7, 8 or 9.
- Telemarketers' numbers have no parentheses or space, but they start
with the area code 140.
Print the answer as part of a message:
"The numbers called by people in Bangalore have codes:"
<list of codes>
The list of codes should be print out one per line in lexicographic order with no duplicates.
Part B: What percentage of calls from fixed lines in Bangalore are made
to fixed lines also in Bangalore? In other words, of all the calls made
from a number starting with "(080)", what percentage of these calls
were made to a number also starting with "(080)"?
Print the answer as a part of a message::
"<percentage> percent of calls from fixed lines in Bangalore are calls
to other fixed lines in Bangalore."
The percentage should have 2 decimal digits
"""
"""Check if the number belongs to Bangalore"""
def numberFromBangalore(num):
isFromBangalore = num.startswith('(080)')
return isFromBangalore
"""Check area codes"""
def checkAreacodes(num):
if num.startswith('('):
fixedLine = num.split(')')[0].strip('()')
return fixedLine
if num.find(' ') and num[0] == '7' or num[0] == '8' or num[0] == '9':
return num[0:4]
if num.startswith('140'):
return num.startswith('140')
"""Keep track of local calls to Bangalore numbers and all other calls"""
count_bangalore_calls = 0
count_all_calls = 0
areaCodesList = []
for call in calls:
if numberFromBangalore(call[0]):
count_all_calls += 1
get_area_codes = checkAreacodes(call[1])
if get_area_codes not in areaCodesList:
areaCodesList.append(get_area_codes)
if numberFromBangalore(call[1]):
count_bangalore_calls += 1
areaCodesList.sort()
print('The numbers called by people in Bangalore have codes:')
for code in areaCodesList:
print(code)
percentage = ((count_bangalore_calls / count_all_calls) * 100)
print(f"{round(percentage,2)} percent of calls from fixed lines in Bangalore are calls to other fixed lines in Bangalore.")
|
2cfa7b3b6a9288d3b6ce7f68943ddc1ec0d38b10 | abhicse32/SPOJ_codes | /DIVCHK.py | 280 | 3.96875 | 4 | num= input()
for i in range(num):
str_=raw_input()
div=input();
len_=len(str_)-1;
two=1;
num_=0;
while len_ >=0:
num_+=int(str_[len_])*two;
two*=2;
len_-=1
#print (num_)
if num_%div==0:
print ("\nDivisible By %d"%div)
else:
print ("\nNot Divisible By %d"%div)
|
6ff46cb8e308a6981806070bae61917799e420b2 | Anirban2404/LeetCodePractice | /621_leastInterval.py | 2,048 | 3.9375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 21 14:38:35 2019
@author: anirban-mac
"""
"""
Given a char array representing tasks CPU need to do. It contains capital
letters A to Z where different letters represent different tasks. Tasks could
be done without original order. Each task could be done in one interval.
For each interval, CPU could finish one task or just be idle.
However, there is a non-negative cooling interval n that means between
two same tasks, there must be at least n intervals that CPU are doing different
tasks or just be idle.
You need to return the least number of intervals the CPU will take to finish
all the given tasks.
Example:
Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.
Note:
The number of tasks is in the range [1, 10000].
The integer n is in the range [0, 100].
"""
import collections
class Solution:
def leastInterval(self, tasks, n):
"""
:type tasks: List[str]
:type n: int
:rtype: int
"""
d = collections.Counter(tasks)
counts = d.values()
longest = max(counts)
interval = (longest - 1) * (n + 1)
for count in counts:
interval += count == longest and 1 or 0
return max(len(tasks), interval)
"""
n += 1
ans = 0
d = collections.Counter(tasks)
heap = [-c for c in d.values()]
heapq.heapify(heap)
while heap:
stack = []
cnt = 0
for _ in range(n):
if heap:
c = heapq.heappop(heap)
cnt += 1
if c < -1:
stack.append(c + 1)
for item in stack:
heapq.heappush(heap, item)
ans += heap and n or cnt # == if heap then n else cnt
return ans
"""
tasks = ["A","A","A","B","B","B"]
n = 2
print(Solution().leastInterval(tasks,n)) |
6b54d7ae0e3df857db649e5616523be341eefd2e | fabiovpcaumo/curso-de-python | /semana04/aula02/exercicio_10.py | 3,384 | 3.796875 | 4 | """
Classe Bomba de Combustível: Faça um programa completo utilizando classes e métodos que:
Possua uma classe chamada bombaCombustível, com no mínimo esses atributos:
tipoCombustivel.
valorLitro
quantidadeCombustivel
Possua no mínimo esses métodos:
abastecerPorValor( ) – método onde é informado o valor a ser abastecido e mostra a quantidade de litros que foi colocada no veículo
abastecerPorLitro( ) – método onde é informado a quantidade em litros de combustível e mostra o valor a ser pago pelo cliente.
alterarValor( ) – altera o valor do litro do combustível.
alterarCombustivel( ) – altera o tipo do combustível.
alterarQuantidadeCombustivel( ) – altera a quantidade de combustível restante na bomba.
OBS: Sempre que acontecer um abastecimento é necessário atualizar a quantidade de combustível total na bomba.
"""
class BombaDeCombustivel:
def __init__(self, tipo_combustivel: str, valor_litro: int, quantidade_combustivel: int):
self.tipo_combustivel = tipo_combustivel
self.valor_litro = valor_litro
self.quantidade_combustivel = quantidade_combustivel
def abastecerPorValor(self, valor_a_abastecer):
total_litros = valor_a_abastecer/self.valor_litro
if total_litros <= self.quantidade_combustivel:
print(f'Abastecidos {total_litros} com R$ {valor_a_abastecer}')
self.alterarQuantidadeCombustivel(-total_litros)
self.mostrarQuantidadeNaBomba()
else:
print(f'Foram abastecidos apenas {self.quantidade_combustivel} litros pois não há mais combustível na bomba. \
\nTotal: R$ {self.quantidade_combustivel * self.valor_litro} \
\nFaltaram: {total_litros - self.quantidade_combustivel}L de {self.tipo_combustivel}.')
self.alterarQuantidadeCombustivel(-self.quantidade_combustivel)
self.mostrarQuantidadeNaBomba()
def abastecerPorLitro(self, quantidade_de_litros):
valor_total = quantidade_de_litros * self.valor_litro
if valor_total <= self.quantidade_combustivel:
print(f'Abastecidos {quantidade_de_litros} a R$ {valor_total}')
self.alterarQuantidadeCombustivel(-quantidade_de_litros)
print(f'Total de combustível na bomba: {self.quantidade_combustivel}')
self.mostrarQuantidadeNaBomba()
else:
print(f'Foram abastecidos apenas {self.quantidade_combustivel} litros pois não há mais combustível na bomba. \
\nTotal: R$ {self.quantidade_combustivel * self.valor_litro} \
\nFaltaram: {quantidade_de_litros - self.quantidade_combustivel}L de {self.tipo_combustivel}.')
self.alterarQuantidadeCombustivel(-self.quantidade_combustivel)
self.mostrarQuantidadeNaBomba()
def alterarValor(self, novo_valor):
self.valor_litro = novo_valor
def alterarCombustivel(self, novo_combustivel):
self.tipo_combustivel = novo_combustivel
def alterarQuantidadeCombustivel(self, qtde_combustivel):
self.quantidade_combustivel += qtde_combustivel
def mostrarQuantidadeNaBomba(self):
print (f'Quantidade de {self.tipo_combustivel} na bomba: {self.quantidade_combustivel}')
if __name__ == "__main__":
b1 = BombaDeCombustivel("gasolina", 3.75, 100)
b1.abastecerPorLitro(101)
|
d0cb8cf48b393d29401b23dd7a098329029e64bb | Sewez/projecteulersol | /prob4.py | 1,327 | 3.953125 | 4 | # Problem 4
# Find the largest palindrome made from the product of two 3-digit numbers.
# Function to check palindomic numbers
def check_palin(int_list):
j = 0
# Simple loops to compare the current value for it's mirror in the list
for i, x in enumerate(int_list):
if i == (len(int_list) - 1 - i):
break
if x == int_list[len(int_list) - 1 - i]:
continue
else:
return False
# return T or F
return True
# Breaks down a number into a list of it's digitsy
def breakdown_int(num):
i = 1
y = []
# extract matching factors
while i <= num:
y.insert(0, i)
i *= 10
# extract division values
div = [num / i for i in y]
# create a copy to update with extractions from factors
copy = [i for i in div]
# loop and extract each number indvidually in a list
for i, v in enumerate(div):
if i > 0:
copy[i] = v - (div[i-1] * 10)
return copy
def run_test(rev_list):
for x in rev_list_gen:
for y in rev_list_gen:
check_list = breakdown_int(x * y)
if check_palin(check_list):
return x, y, x * y
# Creat reversed list of all 3 digit number
rev_list_gen = range(999,99, -1)
print run_test(rev_list_gen)
|
64bdffc88dd3b3fc3ea5f967d016477141ee9643 | abrosen/classroom | /itp/spring2021/gobbler.py | 4,489 | 3.921875 | 4 | class Player:
def __init__(self, color):
self.color = color
self.pieces = []
self.pieces.append(Piece(color,3))
self.pieces.append(Piece(color,3))
self.pieces.append(Piece(color,2))
self.pieces.append(Piece(color,2))
self.pieces.append(Piece(color,1))
self.pieces.append(Piece(color,1))
def __str__(self) -> str:
output = str(self.color) + " Player has "
for index,piece in enumerate(self.pieces):
output = output + str(index)+": " +str(piece) + ", "
return output[:-2] +"]"
#output = str(self.color) + " Player has ["
#for piece in self.pieces:
# output = output + str(piece) + ", "
#return output[:-2] +"]"
class Piece:
def __init__(self,color,size):
self.color= color # blue or orange
self.size = size # size is int, either 1 2 or 3
self.eaten = None
def can_gobble(self, other):
if self.size > other.size:
return True
else:
return False
def gobble(self, other):
self.eaten = other
def __str__(self):
return str(self.color).lower()[0]+str(self.size)
#return str(self.color) + " " + str(self.size)
class Board:
def __init__(self):
self.grid = [[None,None,None],[None,None,None],[None,None,None]]
# player places a piece
def place(self, piece, row, col):
piece.gobble(self.grid[row][col])
self.grid[row][col] = piece
# player moves a piece
def move(self, piece, oldRow, oldCol, row, col):
self.grid[oldRow][oldCol] = piece.eaten
self.place(piece, row, col)
# check for winner
def is_winner(self):
return self.winner_in_rows() or self.winner_in_cols() or self.winner_in_diagonal()
def winner_in_rows(self):
for row in self.grid:
if None not in row and row[0].color == row[1].color == row[2].color:
return True
return False
# col 0 1 2
# row 0 #
# row 1 #
# row 2 #
def winner_in_cols(self):
for colNum in range(3):
if self.grid[0][colNum] != None and self.grid[1][colNum] != None and self.grid[2][colNum] != None:
if self.grid[0][colNum].color == self.grid[1][colNum] == self.grid[2][colNum]:
return True
return False
def winner_in_diagonal(self):
if self.grid[0][0] != None and self.grid[1][1] != None and self.grid[2][2] != None:
if self.grid[0][0].color == self.grid[1][1].color == self.grid[2][2].color:
return True
if self.grid[0][2] != None and self.grid[1][1] != None and self.grid[2][0] != None:
if self.grid[0][2].color == self.grid[1][1].color == self.grid[2][0].color:
return True
return False
# check if proposed move is valid
def is_valid_place(self, piece, row,col):
if row < 0 or row > 2 :
return False
if col <0 or col > 2:
return False
if self.grid[row][col] == None:
return True
else:
return piece.can_gobble(self.grid[row][col])
# print board status
def printBoard(self):
for row in self.grid:
output = ""
for piece in row:
output += str(piece) + "\t"
print(output)
def getInput(self, player):
choice = ""
if len(player.pieces) == 0:
choice == "move"
while "m" not in choice and "p" not in choice:
choice = input("Please whether you want to place or move")
# place
if "p" in choice:
index = -54892789
while not 0 <= index < len(player.pieces):
print(player)
index = int(input("Please enter the number of the piece you want to play"))
piece = player.pieces[index]
player.pieces.remove(piece)
row = 70
col = 100
while not self.is_valid_place(piece,row,col):
row = int(input("Enter a row: "))
col = int(input("Enter a col: "))
self.place(piece,row,col)
else:
pass
o = Player("Orange")
b = Player("Blue")
board = Board()
board.getInput(o)
board.printBoard()
board.getInput(b)
board.printBoard()
board.getInput(o)
board.printBoard() |
18bff0d9c0ee4fb8b6609bdddac547a8d5172fbc | Rajan-Chaurasiya/Python-Practice | /splitex.py | 116 | 3.703125 | 4 | filename = input("enter a file name: ")
f_exten = filename.split(".")
print("the extension is: " +repr(f_exten[-1])) |
653545660ac6e8f2707ac4d1c913812c19626edd | aymane081/python_algo | /arrays/contains_duplicates.py | 531 | 3.640625 | 4 | class Solution(object):
def contains_duplicates(self, numbers):
number_set = set(numbers)
return len(numbers) != len(number_set)
def contains_duplicates2(self, numbers):
"""
:type numbers: list
:rtype : Boolean
"""
numbers.sort()
for i in range(1, len(numbers)):
if numbers[i] == numbers[i - 1]:
return True
return False
numbers = [1, 2, 1, 4]
solution = Solution()
print(solution.contains_duplicates(numbers))
|
deed9b7d5cb6bdb260cfba2165767bd8f0061878 | shangjiadong/algorithm | /numBitStrings/bitstrings.py | 896 | 3.96875 | 4 | """
3. Number of bit strings of length n that has
1) no two consecutive 0s.
2) two consecutive 0s.
>>> num_no(3)
5
>>> num_yes(3)
3
[HINT] There are three 3-bit 0/1-strings that have two consecutive 0s.
001 100 000
The other five 3-bit 0/1-strings have no two consecutive 0s:
010 011 101 110 111
Feel free to choose any implementation style.
Filename: bitstrings.py
"""
def num_no(n):
no = {1: 2, 2: 3}
if n in no:
return no[n]
else:
no[n] = num_no(n-1) + num_no(n-2)
return no[n]
def num_yes(n):
yes = {1: 0, 2: 1, 3: 3}
if n in yes:
return yes[n]
else:
yes[n] = 2**(n-2) + num_yes(n-2) + num_yes(n-1)
return yes[n]
def main():
print(num_yes(10))
print(num_no(10))
if __name__ == '__main__':
main() |
421053db4de77630c3aeb7309ae830896bf46deb | vishalagrawalit/Competitive-Programming | /Codechef-June_Challange-2017/Triplets.py | 1,716 | 3.546875 | 4 | def binarySearch(arr, l, r, x):
if l>r:
return -1
if x>=arr[r]:
return r
mid = (l+r)//2
if arr[mid]==x:
return mid
if mid>0 and arr[mid-1]<= x and x<arr[mid]:
return mid-1
if x<arr[mid]:
return binarySearch(arr, l, mid-1, x)
return binarySearch(arr, mid+1, r, x)
M = 10**9 + 7
for _ in range(int(input())):
array = list(map(int,input().split()))
s_one,s_three = [],[]
p = list(map(int,input().split()))
p.sort()
add = 0
for x in range(array[0]):
add = (add+p[x])%M
s_one.append(add)
q = list(map(int,input().split()))
q.sort()
r = list(map(int,input().split()))
r.sort()
add = 0
for x in range(array[2]):
add = (add+r[x])%M
s_three.append(add)
ans = 0
for i in range(array[1]):
index_p = binarySearch(p,0, array[0]-1, q[i])
index_r = binarySearch(r,0, array[2]-1, q[i])
if index_p < array[0] and index_p!=-1 and p[index_p+1]==q[i]:
for j in range(index_p+1,array[0]-1):
if p[j]==q[i]:
index_p+=1
else:
break
if index_r < array[2] and index_r!=-1 and r[index_r+1]==q[i]:
for k in range(index_r+1,array[2]-1):
if r[k]==q[i]:
index_r+=1
else:
break
if index_p!=-1 and index_r!=-1:
res = (q[i] * q[i] * (index_p+1) * (index_r+1)) + (s_one[index_p] * s_three[index_r]) + (s_one[index_p] * (index_r+1) + s_three[index_r] * (index_p+1)) * q[i]
ans = (ans + (res%M))%M
print(ans)
|
ac1350ea905e0fd409f24e4542cd661bf014fb6d | kayvera/random_python_files | /name_cases.py | 601 | 3.765625 | 4 | full_name = "Mikayla Rivera"
message = "Hello " + full_name + "," + " is the coolest ever!"
print(message)
print(full_name.title())
print(full_name.upper())
print(full_name.lower())
print('\tWarren Buffett once said,"Price is what you pay.\n\tValue is what you get."')
famous_person = "Warren Buffett"
message = "\t" + famous_person + ' once said,"Price is what you pay.\n\tValue is what you get."'
print(message)
persons_name = " Kelly Green "
print(persons_name)
print('\n' + persons_name)
print('\t' + persons_name)
print(persons_name.lstrip())
print(persons_name.rstrip())
print(persons_name.strip())
|
aebcdc6d32100c50f30dc123668b20850e6559b3 | MrHamdulay/csc3-capstone | /examples/data/Assignment_1/shmken002/question2.py | 414 | 4.1875 | 4 | # program to check the validity of a time entered by the user as a set of three integers
#shimabukuro kenneth
#28 february 2014
hours = eval(input("Enter the hours:""\n"))
minutes = eval(input("Enter the minutes:""\n"))
seconds = eval(input("Enter the seconds:""\n"))
if (0 <= hours <= 23) and (0 <= minutes <= 59) and (0 <= seconds <= 59):
print ("Your time is valid.")
else:
print ("Your time is invalid.") |
2528eef32d526d21201252ed2256a842c5f2216c | NikheelP/Spark_ | /spark/widget/sample/sample_color_variable.py | 9,494 | 3.625 | 4 |
class COLOR_VARIABLE_CHILD():
def __init__(self, value):
self._color_value = value
@property
def set_value(self):
'''
return the color value
'''
return self._color_value
def get_value(self):
'''
return the color value
'''
return self._color_value
@set_value.setter
def set_value(self, value):
'''
setting up the new value
@param value: list value
@type value: list
'''
if not isinstance(value, list):
raise Exception('value is not a list please Define the List')
self._color_value = value
return self._color_value
class COLOR_VARIABLE():
'''
this is the color variable which will be include all the related to color in the widget
can be get and set new value to change the widget color
'''
def __init__(self):
# 18color
self.red_color = COLOR_VARIABLE_CHILD(value=[254, 0, 2])
self.blue_color = COLOR_VARIABLE_CHILD(value=[1, 0, 254])
self.green_color = COLOR_VARIABLE_CHILD(value=[1, 154, 1])
self.orange_color = COLOR_VARIABLE_CHILD(value=[255, 154, 0])
self.yellow_color = COLOR_VARIABLE_CHILD(value=[255, 255, 1])
self.pink_color = COLOR_VARIABLE_CHILD(value=[255, 205, 208])
self.purple_color = COLOR_VARIABLE_CHILD(value=[152, 0, 134])
self.violet_color = COLOR_VARIABLE_CHILD(value=[255, 131, 243])
self.turquoise_color = COLOR_VARIABLE_CHILD(value=[0, 225, 209])
self.gold_color = COLOR_VARIABLE_CHILD(value=[255, 216, 1])
self.lime_color = COLOR_VARIABLE_CHILD(value=[1, 255, 1])
self.aqua_color = COLOR_VARIABLE_CHILD(value=[99, 255, 255])
self.navy_color = COLOR_VARIABLE_CHILD(value=[2, 0, 133])
self.coral_color = COLOR_VARIABLE_CHILD(value=[255, 128, 77])
self.teal_color = COLOR_VARIABLE_CHILD(value=[1, 129, 132])
self.brown_color = COLOR_VARIABLE_CHILD(value=[193, 37, 40])
self.white_color = COLOR_VARIABLE_CHILD(value=[255, 255, 255])
self.black_color = COLOR_VARIABLE_CHILD(value=[80, 80, 80])
basic_font_radius_size = 10
basic_font_weight = 'bold'
#make a object color
self.nurbsCurve_color = self.orange_color
self.dynamicConstraint_color = self.green_color
self.transform_color = self.blue_color
self.mesh_color = self.yellow_color
self.ncloth_color = self.pink_color
self.locator_color = self.pink_color
self.camera_color = self.violet_color
self.nucleus_color = self.red_color
self.clusterHandle_color = self.lime_color
self.light_color = self.brown_color
#CFX COLOR
self.nCloth_color = self.lime_color
self.nRigit_color = self.orange_color
self.nConstraint_color = self.yellow_color
self.nHair_color = self.red_color
self.folical_color = self.gold_color
# PUSHBUTTON BASIC 1 COLOR
self.pushbutton_basic_1_background_color = COLOR_VARIABLE_CHILD(value=[117, 138, 255])
self.pushbutton_basic_1_color = COLOR_VARIABLE_CHILD(value=[255, 255, 255])
self.pushbutton_basic_1_font_size = COLOR_VARIABLE_CHILD(value=basic_font_radius_size)
self.pushbutton_basic_1_font_weight = COLOR_VARIABLE_CHILD(value=basic_font_weight)
self.pushbutton_basic_1_font_radius = COLOR_VARIABLE_CHILD(value=basic_font_radius_size)
self.pushbutton_basic_1_background_hover_color = COLOR_VARIABLE_CHILD(value=[0, 145, 80])
# PUSHBUTTON BASIC 2 COLOR
self.pushbutton_basic_2_background_color = COLOR_VARIABLE_CHILD(value=[254, 82, 147])
self.pushbutton_basic_2_color = COLOR_VARIABLE_CHILD(value=[255, 255, 255])
self.pushbutton_basic_2_font_size = COLOR_VARIABLE_CHILD(value=basic_font_radius_size)
self.pushbutton_basic_2_font_weight = COLOR_VARIABLE_CHILD(value=basic_font_weight)
self.pushbutton_basic_2_font_radius = COLOR_VARIABLE_CHILD(value=basic_font_radius_size)
self.pushbutton_basic_2_background_hover_color = COLOR_VARIABLE_CHILD(value=[189, 61, 110])
# PUSHBUTTON BASIC 3 COLOR
self.pushbutton_basic_3_background_color = COLOR_VARIABLE_CHILD(value=[250, 37, 71])
self.pushbutton_basic_3_color = COLOR_VARIABLE_CHILD(value=[255, 255, 255])
self.pushbutton_basic_3_font_size = COLOR_VARIABLE_CHILD(value=basic_font_radius_size)
self.pushbutton_basic_3_font_weight = COLOR_VARIABLE_CHILD(value=basic_font_weight)
self.pushbutton_basic_3_font_radius = COLOR_VARIABLE_CHILD(value=basic_font_radius_size)
self.pushbutton_basic_3_background_hover_color = COLOR_VARIABLE_CHILD(value=[198, 28, 57])
# PUSHBUTTON BASIC 4 COLOR
self.pushbutton_basic_4_background_color = COLOR_VARIABLE_CHILD(value=[255, 132, 61])
self.pushbutton_basic_4_color = COLOR_VARIABLE_CHILD(value=[255, 255, 255])
self.pushbutton_basic_4_font_size = COLOR_VARIABLE_CHILD(value=basic_font_radius_size)
self.pushbutton_basic_4_font_weight = COLOR_VARIABLE_CHILD(value=basic_font_weight)
self.pushbutton_basic_4_font_radius = COLOR_VARIABLE_CHILD(value=basic_font_radius_size)
self.pushbutton_basic_4_background_hover_color = COLOR_VARIABLE_CHILD(value=[202, 102, 48])
# PUSHBUTTON BASIC 5 COLOR
self.pushbutton_basic_5_background_color = COLOR_VARIABLE_CHILD(value=[104, 99, 160])
self.pushbutton_basic_5_color = COLOR_VARIABLE_CHILD(value=[255, 255, 255])
self.pushbutton_basic_5_font_size = COLOR_VARIABLE_CHILD(value=basic_font_radius_size)
self.pushbutton_basic_5_font_weight = COLOR_VARIABLE_CHILD(value=basic_font_weight)
self.pushbutton_basic_5_font_radius = COLOR_VARIABLE_CHILD(value=basic_font_radius_size)
self.pushbutton_basic_5_background_hover_color = COLOR_VARIABLE_CHILD(value=[136, 131, 211])
# PUSHBUTTON BASIC 6 COLOR
self.pushbutton_basic_6_background_color = COLOR_VARIABLE_CHILD(value=[0, 143, 254])
self.pushbutton_basic_6_color = COLOR_VARIABLE_CHILD(value=[255, 255, 255])
self.pushbutton_basic_6_font_size = COLOR_VARIABLE_CHILD(value=basic_font_radius_size)
self.pushbutton_basic_6_font_weight = COLOR_VARIABLE_CHILD(value=basic_font_weight)
self.pushbutton_basic_6_font_radius = COLOR_VARIABLE_CHILD(value=basic_font_radius_size)
self.pushbutton_basic_6_background_hover_color = COLOR_VARIABLE_CHILD(value=[0, 105, 186])
# PUSHBUTTON BASIC 7 COLOR
self.pushbutton_basic_7_background_color = COLOR_VARIABLE_CHILD(value=[188, 188, 188])
self.pushbutton_basic_7_color = COLOR_VARIABLE_CHILD(value=[255, 255, 255])
self.pushbutton_basic_7_font_size = COLOR_VARIABLE_CHILD(value=basic_font_radius_size)
self.pushbutton_basic_7_font_weight = COLOR_VARIABLE_CHILD(value=basic_font_weight)
self.pushbutton_basic_7_font_radius = COLOR_VARIABLE_CHILD(value=basic_font_radius_size)
self.pushbutton_basic_7_background_hover_color = COLOR_VARIABLE_CHILD(value=[220, 220, 220])
self.background_color = COLOR_VARIABLE_CHILD(value=[0, 255, 132])
self.new_background_color = COLOR_VARIABLE_CHILD(value=[0, 39, 46])
self.background_another_color = COLOR_VARIABLE_CHILD(value=[43, 82, 112])
self.color = COLOR_VARIABLE_CHILD(value=[0, 255, 0])
# TITLE LABEL
self.title_label = COLOR_VARIABLE_CHILD(value=[0, 255, 0])
# MINIMIZE COLOR
self.minimize_color = COLOR_VARIABLE_CHILD(value=[0, 255, 0])
self.minimize_hover_color = COLOR_VARIABLE_CHILD(value=[20, 145, 1])
# MAXIMIZE COLOR
self.maximize_color = COLOR_VARIABLE_CHILD(value=[255, 255, 0])
self.maximize_hover_color = COLOR_VARIABLE_CHILD(value=[166, 166, 0])
# CLOSE COLOR
self.close_color = COLOR_VARIABLE_CHILD(value=[255, 0, 0])
self.close_hover_color = COLOR_VARIABLE_CHILD(value=[171, 0, 0])
# DOCK WIDGET COLOR
self.dockwidget_color = COLOR_VARIABLE_CHILD(value=[0, 255, 0])
self.dockwidget_hover_color = COLOR_VARIABLE_CHILD(value=[255, 85, 0])
self.splitter_background_color = COLOR_VARIABLE_CHILD(value=[255, 85, 0])
# USER TOOL COLOR
self.user_tool_color = COLOR_VARIABLE_CHILD(value=[74, 74, 74])
self.user_help_color = COLOR_VARIABLE_CHILD(value=[74, 74, 74])
def color_list(self):
color_list = [[255, 0, 0], (0,255,0), (0,0,255), (255,255,0), (0,255,255), (255,0,255), (192,192,192),
(128,128,128), (128,0,0), (128,128,0), (0,128,0), (128,0,128), (0,128,128), (0,0,128),
(128,0,0), (139,0,0), (165,42,42), (178,34,34), (220,20,60), (255,0,0), (255,99,71), (255,127,80),
(205,92,92), (240,128,128), (233,150,122), (250,128,114), (255,160,122), (255,69,0), (255,140,0),
(255,165,0), (255,215,0)]
return color_list
def bright_color(self):
return [self.red_color, self.blue_color, self.green_color, self.orange_color,
self.yellow_color, self.pink_color, self.purple_color, self.violet_color,
self.turquoise_color, self.gold_color, self.lime_color, self.aqua_color, self.navy_color,
self.coral_color, self.teal_color, self.brown_color, self.white_color, self.black_color]
|
96729bbbf26ddbb2c41a592e8bd426523f3d4b9b | Arthurmf01/PROGRAMING-WITH-PYTHON- | /Exercices | 347 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 26 14:35:38 2018
@author: arthurmaroquenefroissart
"""
#%%
def linear(number, lst):
for i in range(len(lst)):
if number == lst[i]:
return i
return None
def hello():
name = input("What's your name ? ")
print("Hello " + name)
#%% |
e20ca2cb2b36e99f94bb9ef206851cd49793915c | vilaron/Complejidad2020II | /clase_2/bfs.py | 779 | 3.625 | 4 | #cada posicion de la lista representa a un nodo y lo que hay en esa posicion representa los nodos adyacentes a ese nodo
#lista de adj, visitados y cola o queue
#grafo no dirigido
adj = [
[1,2],
[0, 3 , 4],
[0 ,4 , 5],
[1, 6],
[1 , 2 , 6 ],
[2 ,6],
[3 , 4 , 5]
]
visitados = [False] * len(adj)
#FiFo (First in , First out)
#se comporta como cola
queue = []
#punto de inicio
start = 0
#se lee por niveles
def bfs():
visitados[start] = True
queue.append(start)
while queue:
#se borra el elemento del principio y lo guardas a la misma vez en v
v = queue.pop(0)
print(v)
for u in adj[v]:
if visitados[u] == False:
visitados[u] = True
queue.append(u)
bfs()
|
27c7733ac3ab2c6ee367eb537c65b76ffb73a5c3 | ryzzhov-al/TaskStepik | /Taskstepik.py | 3,122 | 4.09375 | 4 | """
Напишите программу, которая выводит часть последовательности 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 ...
(число повторяется столько раз, чему равно). На вход программе передаётся неотрицательное
целое число n — столько элементов последовательности должна отобразить программа.
На выходе ожидается последовательность чисел, записанных через пробел в одну строку.
Например, если n = 7, то программа должна вывести 1 2 2 3 3 3 4.
n = int(input())
a = []
i = 0
while len(a) < n:
a += [i] * i
print("Выводим а:",a)
i += 1
print('Выводим i:',i)
print("Выводим итог",*a[:n])
'''
L = [1, 2, 3, 4, 5] -- *выыодит все элементы списка через пробел
print(*L)
print(*L, sep=', ')
print(*L, sep=' -> ')
'''
"""
#-----------------------#
"""
Напишите функцию modify_list(l), которая принимает на вход список целых чисел, удаляет из него все нечётные значения,
а чётные нацело делит на два. Функция не должна ничего возвращать, требуется только изменение переданного списка,
например:
lst = [1, 2, 3, 4, 5, 6]
print(modify_list(lst)) # None
print(lst) # [1, 2, 3]
modify_list(lst)
print(lst) # [1]
lst = [10, 5, 8, 3]
modify_list(lst)
print(lst) # [5, 4]
Также функция не должна осуществлять ввод/вывод информации.
"""
"""
def modify_list(l):
i = 0
while i < len(l):
if l[i]%2 != 0:
l.remove(l[i])
else:
l[i] = l[i]//2
i += 1
return (l)
lst = [0, 1, 2,7,8]
print(modify_list(lst))
"""
"""
Напишите программу, которая принимает на вход список чисел и число, после чего выводит все позиции,
на которых это число встречается в переданном списке.
Позиции в списке нумеруются с нуля.
Если число x не найдено в списке, нужно вывести строку "None" (без кавычек, с большой буквы).
"""
"""
a = input().split() #пользовательски ввод разбиваем методом split(разбивает строку с помощью указанного спецсимвола и возвращает список подстрок)
b = input()
if b not in a:
print("None")
else:
for i in range(len(a)): #проверям число по позиции в списке
if a[i] == b:
print(i)
"""
|
26116f1b8924c50c70a09e215e4386f5fc81edb3 | scrypti/Udacity | /ArtificialIntelligence/Localization/kalman_filters.py | 1,931 | 3.703125 | 4 | from math import *
import warnings
# make predictions about future positions
# measurement meant updating our belief (and renormalizing our distribution).
# motion meant keeping track of where all of our probability "went" when we moved
# Kalman Filter:
# measurement update: bayes rule (multiplication)
# motion update prediction: total probability (addition)
def f(m, v, x):
"""
gaussian computation (deprecated)
:param m: mean (mu)
:param v: variance (sigma squared)
:param x: x
"""
return 1 / sqrt(2.0 * pi * v) * exp(-0.5 * (x - m)**2 / v)
def update(m1, v1, m2, v2):
"""
measurement update step (kalman filter)
updates mean and variance based on previous measurement and new observation
:param m1: previous mean (mu)
:param v1: previous variance (sigma^2)
:param m2: observed mean (mu)
:param v2: observed variance (sigma^2)
:return: new mean and variance [m, v]
"""
m = (v1 * m2 + v2 * m1) / (v1 + v2)
v = 1. / (1. / v1 + 1. / v2)
return [m, v]
def predict(m1, v1, m2, v2):
"""
predicts mean and variance based on movement
:param m1: previous mean (mu)
:param v1: previous variance (sigma^2)
:param m2: observed mean (mu)
:param v2: observed variance (sigma^2)
:return: new mean and variance [m, v]
"""
m = m1 + m2
v = v1 + v2
return [m, v]
def main():
measurements = [5., 6., 7., 9., 10.]
motion = [1., 1., 2., 1., 1.]
measurement_sig = 4.
motion_sig = 2.
mu = 0.
sig = 10000.
result = [mu, sig]
for i in range(len(measurements)):
# sense
result = update(result[0], result[1], measurements[i], measurement_sig)
print('update: ', result)
# move
result = predict(result[0], result[1], motion[i], motion_sig)
print('predict: ', result)
# print(update(10, 4, 12, 4))
if __name__ == "__main__":
main()
|
2bab9a82b515cff5eaa7f1e179987b026f2f3d09 | Liza333/Python | /laba 1/Task9.py | 1,508 | 3.625 | 4 | # Напишите программу, имитирующую работу банкомата. Выберите
# структуру данных для хранения купюр разного достоинства в заданном
# количестве. При вводе пользователем запрашиваемой суммы денег,
# скрипт должен вывести на консоль количество купюр подходящего
# достоинства. Если имеющихся денег не хватает, то необходимо
# напечатать сообщение «Операция не может быть выполнена!».
# Например, при сумме 5370 рублей на консоль должно быть выведено
# «5*1000 + 3*100 + 1*50 + 2*10».
import os
os.startfile(r'say_hi.jpg')
money_in_stock = {1000: 2, 500: 2, 200: 10, 100: 5, 50: 5, 10: 20}
result = {1000: 0, 500: 0, 200: 0, 100: 0, 50: 0, 10: 0}
money = int(input('Введите сумму, которую хотите снять: '))
for key in money_in_stock.keys():
current = money // key # деление без остатка
if current > money_in_stock[key]:
money = money - (money_in_stock[key] * key)
result[key] = money_in_stock[key]
else:
money = money % key
result[key] = current
print("Your money : " + str(sum([k * v for k, v in zip(result.keys(), result.values())])))
print(result)
|
1110db582484a26a41aa336f6dfb3d0b3f912b3d | sross1418/PythonExamples | /Turtle Example.py | 3,579 | 4.625 | 5 | # turtle documentation: https://docs.python.org/3/library/turtle.html
# Challenges: add a command to make the turtle draw a circle of a specified diameter
# add a command to change the turtle's color
# add a command to tell the turtle to move to a certain set of coordinates
import turtle
t = turtle.Turtle()
def turtleStar(size):
for i in range(5):
t.forward(size)
t.right(144)
def turtleSquare(sideLength):
for i in range(4):
t.forward(sideLength)
t.right(90)
def turtleCircle(radius):
circleConstant = 0.00873438728
t.speed(0)
for i in range(360):
t.forward(radius * circleConstant)
t.right(1)
if i == 180:
print(t.position())
t.speed(6)
def askInput():
# Keep asking for input until they give us valid input
# we exit the function when we return some value, which will only happen when the input is validated.
while True:
print("What should the turtle do?: ")
# Ask for user input, change it to all lowercase, and split wherever there's a space, leaving us with a list
# of the words or numbers that the user entered
userInput = input().lower().split()
# limit them to only 2 words, a command and an argument
if len(userInput) > 2:
print("Too many arguments. Please type a command and a number")
else:
# if they only say exit, provide a blank argument and return the pair
if len(userInput) == 1:
return (userInput[0], "")
# otherwise save the first element of their input as the command and the second as the argument
else:
# we need to try to convert the argument from a string to a float.
# if we don't, we will get an error if we try something like t.forward("apple") down the line
try:
return (userInput[0], float(userInput[1]))
# this happens if the above 'try' block fails
# meaning they put an argument that could not be converted properly to a float.
# if we don't do this and they enter something that can't be converted, the program will crash
except:
print("Please enter a number after the command.")
# call the appropriate function based on the user's command, using the argument that they gave us as well
def doCommand(command, argument):
if command == "exit" or command == "quit":
exit()
elif command == "left" or command == "l":
t.left(int(argument))
elif command == "right" or command == "r":
t.right(int(argument))
elif command == "forward" or command == "f":
t.forward(int(argument))
elif command == "star" or command == "s":
turtleStar(int(argument))
elif command == "circle":
t.circle(int(argument))
elif command == "square":
turtleSquare(int(argument))
else:
print("Please say 'forward', 'left', 'right', or 'star' in addition to a number. Or say 'exit' to quit.")
def welcome():
print("""Welcome to the interactive turtle program!
Please give the turtle instructions
You can tell the turtle to move forward, turn left or right, or draw a star of a certain size
For example, you can say 'forward 15'
'left 90' or 'star 50'""")
welcome()
# repeat the input -> command loop until they quit
while True:
userInput = askInput()
# pass the command and argument we got to the doCommand function
doCommand(userInput[0], userInput[1]) |
9870fde109c97a853ccb0268a165038bf2e6cc3c | evad37/python-bits-and-pieces | /Calculator.py | 3,415 | 3.8125 | 4 | """
Calculator.py
A calculator that takes input as a string from the user, and recursively solves
the given problem. Reports "divide by zero" errors and bracket mismatch errors.
"""
def add(a,b):
if a is None or b is None:
return None
return a + b
def minus(a,b):
if a is None or b is None:
return None
return a - b
def times(a,b):
if a is None or b is None:
return None
return a * b
def divide(a,b):
if b == 0:
print("Divide by zero error!")
return None
elif a is None or b is None:
return None
return a / b
def power(a,b):
if a is None or b is None:
return None
return pow(a, b)
def calculator(problem):
if problem.count("(") != problem.count(")"):
print("Bracket count mismatch error!")
return None
elif "(" in problem:
lastOpenBracket = problem.rindex("(")
nextCloseBracket = problem.find(")", lastOpenBracket)
if nextCloseBracket == -1:
print("Bracket order mismatch error!")
return None
innerTotal = calculator(problem[lastOpenBracket+1:nextCloseBracket])
if innerTotal is None:
return None
# Convert to string as a float (not exponential for small numbers)
innerPart = format(innerTotal, 'f')
leftPart = problem[0:lastOpenBracket]
if len(leftPart) > 0 and not leftPart[-1] in "+-*/^(":
leftPart += "*"
rightPart = problem[nextCloseBracket+1:]
if len(rightPart) > 0 and not rightPart[0] in "+-*/^)":
rightPart = "*" + rightPart
return calculator(leftPart+innerPart+rightPart)
elif "+" in problem:
parts = problem.split("+")
subtotal = calculator(parts[0])
for i in range(1, len(parts)):
subtotal = add(subtotal, calculator(parts[i]))
return subtotal
elif "-" in problem:
parts = problem.split("-")
subtotal = calculator(parts[0])
for i in range(1, len(parts)):
subtotal = minus(subtotal, calculator(parts[i]))
return subtotal
elif "*" in problem:
parts = problem.split("*")
subtotal = calculator(parts[0])
for i in range(1, len(parts)):
subtotal = times(subtotal, calculator(parts[i]))
return subtotal
elif "/" in problem:
parts = problem.split("/")
subtotal = calculator(parts[0])
for i in range(1, len(parts)):
subtotal = divide(subtotal, calculator(parts[i]))
return subtotal
elif "^" in problem:
parts = problem.split("^")
subtotal = calculator(parts[0])
for i in range(1, len(parts)):
subtotal = power(subtotal, calculator(parts[i]))
return subtotal
elif problem == "":
print("Error! Operators must be used between numbers.")
else:
return float(problem)
result = None
print("Enter problem(s), or 'Q' to quit. Use numbers and the symbols + - * / ^ ( ) only.")
while True:
calculation = input("> ")
if calculation.upper() == 'Q':
break
if not(result is None) and calculation[0] in "+-*/^":
calculation = format(result, 'f') + calculation
result = calculator(calculation)
if not(result is None):
print("=", result)
|
a0a054eee73c04771deffdad9b789a80883b2bac | RavikrianGoru/py_durga | /telsuko_one/py_basics/10_prime_check.py | 206 | 3.96875 | 4 | # num = int(input("Enter positive number: "))
num = 83
num = int(num/2)
for i in range(2, num):
if num % i == 0:
print("Not prime")
break
else:
print("Prime")
print("Bye")
|
ca7f48d6367d4eabc5706b88f3b30b12852a8921 | apitman91/problem-solving | /project-euler/p1.py | 160 | 3.859375 | 4 | def p1(n):
"""Sums all multiples of 3 and 5 less than n"""
set = [i for i in range(1, n) if i % 3 == 0 or i% 5 ==0]
return sum(set)
print(p1(1000)) |
419b22f3679fcda55083a82c19a35b034b235352 | hyphenliu/TensorFlow_Google_Practice | /Deep_Learning_with_TensorFlow/1.4.0/Chapter04/2. 学习率的设置.py | 3,524 | 3.734375 | 4 | # #### 假设我们要最小化函数 $y=x^2$, 选择初始点 $x_0=5$
# #### 1. 学习率为1的时候,x在5和-5之间震荡。
import tensorflow as tf
TRAINING_STEPS = 10
LEARNING_RATE = 1
x = tf.Variable(tf.constant(5, dtype=tf.float32), name="x")
y = tf.square(x)
train_op = tf.train.GradientDescentOptimizer(LEARNING_RATE).minimize(y)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(TRAINING_STEPS):
sess.run(train_op)
x_value = sess.run(x)
print("After %s iteration(s): x%s is %f."% (i+1, i+1, x_value))
# #### 2. 学习率为0.001的时候,下降速度过慢,在901轮时才收敛到0.823355。
TRAINING_STEPS = 1000
LEARNING_RATE = 0.001
x = tf.Variable(tf.constant(5, dtype=tf.float32), name="x")
y = tf.square(x)
train_op = tf.train.GradientDescentOptimizer(LEARNING_RATE).minimize(y)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(TRAINING_STEPS):
sess.run(train_op)
if i % 100 == 0:
x_value = sess.run(x)
print("After %s iteration(s): x%s is %f."% (i+1, i+1, x_value))
# #### 3. 使用指数衰减的学习率,在迭代初期得到较高的下降速度,可以在较小的训练轮数下取得不错的收敛程度。
TRAINING_STEPS = 100
global_step = tf.Variable(0)
LEARNING_RATE = tf.train.exponential_decay(0.1, global_step, 1, 0.96, staircase=True)
x = tf.Variable(tf.constant(5, dtype=tf.float32), name="x")
y = tf.square(x)
train_op = tf.train.GradientDescentOptimizer(LEARNING_RATE).minimize(y, global_step=global_step)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(TRAINING_STEPS):
sess.run(train_op)
if i % 10 == 0:
LEARNING_RATE_value = sess.run(LEARNING_RATE)
x_value = sess.run(x)
print("After %s iteration(s): x%s is %f, learning rate is %f."% (i+1, i+1, x_value, LEARNING_RATE_value))
# After 1 iteration(s): x1 is -5.000000.
# After 2 iteration(s): x2 is 5.000000.
# After 3 iteration(s): x3 is -5.000000.
# After 4 iteration(s): x4 is 5.000000.
# After 5 iteration(s): x5 is -5.000000.
# After 6 iteration(s): x6 is 5.000000.
# After 7 iteration(s): x7 is -5.000000.
# After 8 iteration(s): x8 is 5.000000.
# After 9 iteration(s): x9 is -5.000000.
# After 10 iteration(s): x10 is 5.000000.
# After 1 iteration(s): x1 is 4.990000.
# After 101 iteration(s): x101 is 4.084646.
# After 201 iteration(s): x201 is 3.343555.
# After 301 iteration(s): x301 is 2.736923.
# After 401 iteration(s): x401 is 2.240355.
# After 501 iteration(s): x501 is 1.833880.
# After 601 iteration(s): x601 is 1.501153.
# After 701 iteration(s): x701 is 1.228794.
# After 801 iteration(s): x801 is 1.005850.
# After 901 iteration(s): x901 is 0.823355.
# After 1 iteration(s): x1 is 4.000000, learning rate is 0.096000.
# After 11 iteration(s): x11 is 0.690561, learning rate is 0.063824.
# After 21 iteration(s): x21 is 0.222583, learning rate is 0.042432.
# After 31 iteration(s): x31 is 0.106405, learning rate is 0.028210.
# After 41 iteration(s): x41 is 0.065548, learning rate is 0.018755.
# After 51 iteration(s): x51 is 0.047625, learning rate is 0.012469.
# After 61 iteration(s): x61 is 0.038558, learning rate is 0.008290.
# After 71 iteration(s): x71 is 0.033523, learning rate is 0.005511.
# After 81 iteration(s): x81 is 0.030553, learning rate is 0.003664.
# After 91 iteration(s): x91 is 0.028727, learning rate is 0.002436. |
a9306f484cad43c8ea224c51a8811fbbc336f0a2 | hshafy/semtest | /src/main.py | 2,463 | 3.75 | 4 | """Main"""
import csv
import sys
def read_csv(filename):
"""
Read CSV data and return a list with reocrds
"""
# TODO: get filename from script argument and check path and validate
data = []
with open(filename, newline='') as file:
reader = csv.DictReader(file)
try:
for row in reader:
data.append(process_one_record(row))
except csv.Error as exp:
sys.exit('file {}, line {}: {}'.format(filename, reader.line_num, exp))
return data
def process_one_record(record):
"""
Process each record to update data in one take while reading
"""
# TODO: check safety of this conversion
cost = float(record['Cost'])
if cost != 0:
record['ROI'] = (float(record['Revenue']) - cost) / cost
else:
record['ROI'] = float(record['Revenue'])
return record
def filter_by_key_value(data, key, value):
"""
Filter data by key value
"""
return list(filter(lambda d: d[key] == value, data))
def print_top_kewyord_by_roi(data, company_name, limit):
"""
Prints the top number of keywords for a company
"""
print('')
filtered_data = filter_by_key_value(data, 'Company', company_name)
if filtered_data is not None:
print('Found {} {} records.'.format(len(filtered_data), company_name))
else:
print('No data found for {}.'.format(company_name))
sorted_by_roi = sorted(filtered_data, key=lambda k: k["ROI"], reverse=True)
print('Top {} keywords by ROI for {}'.format(limit, company_name))
top_10 = sorted_by_roi[0:limit-1]
for item in top_10:
print('Keyword: {0}, ROI: {1:.2f}'.format(item['Search keyword'], item['ROI']))
def main():
"""
main
"""
if len(sys.argv) < 2:
print('Please provide filename as a first argument')
return
provided_filename = sys.argv[1]
data = read_csv(provided_filename)
if not data:
print('No data found')
return
print('Found {} records.'.format(len(data)))
print_top_kewyord_by_roi(data, 'GetYourGuide', 10)
# TODO: get list or remanining company names from data
print_top_kewyord_by_roi(data, 'Company A', 10)
print_top_kewyord_by_roi(data, 'Company B', 10)
print_top_kewyord_by_roi(data, 'Company C', 10)
print_top_kewyord_by_roi(data, 'Company D', 10)
print_top_kewyord_by_roi(data, 'Company E', 10)
if __name__ == '__main__':
main()
|
6fcec8ce9310565eada36790a1726d9784f76416 | rewonderful/MLC | /src/归并排序.py | 1,290 | 4 | 4 | #!/usr/bin/env python
# _*_ coding:utf-8 _*_
def merge(nums):
if len(nums) < 2:
return nums
mid = len(nums)//2
leftpart = merge(nums[:mid])
rightpart = merge(nums[mid:])
return mergesort(leftpart,rightpart)
def mergesort(left,right):
result = []
i = 0
j = 0
while i<len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
if i < len(left):
result.extend(left[i:])
if j < len(right):
result.extend(right[j:])
return result
def merge7(nums):
if len(nums) < 2:
return nums
mid = len(nums)//2
left = merge7(nums[:mid])
right = merge7(nums[mid:])
return merge_sort7(left,right)
def merge_sort7(left,right):
dummy = []
i,j = 0,0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
dummy.append(left[i])
i += 1
else:
dummy.append(right[j])
j += 1
if i < len(left):
dummy.extend(left[i:])
if j < len(right):
dummy.extend(right[j:])
return dummy
if __name__ == '__main__':
print(merge7([9,8,7,6,5,4,3,2,1,0]))
#print(mergesort([1,5,7],[2,4,6])) |
3079ae52457f06417737d1a195c4e110e8142cc7 | Endlex-net/Demo_of_design_patterns_by_python | /proxy_pattern/demo.py | 1,318 | 3.578125 | 4 | from abc import ABC, abstractmethod
class Subject(ABC):
"""主题类"""
@abstractmethod
def request(self):
pass
class RealSubject(Subject):
def request(self):
raise NotImplementedError
class ProxySubject(Subject):
def request(self):
raise NotImplementedError
class TonyReception(RealSubject):
def __init__(self, name, phone_number):
self.phone_number = phone_number
self.name = name
def request(self, parcel_content):
print(f"货物主任:{self.name}, 手机号: {self.phone_number}")
print(f"接收到一个包裹,包裹内容是: {parcel_content}")
class WendyReception(ProxySubject):
"""Wendy代收"""
def __init__(self, name, receiver: TonyReception):
self.name = name
self.receiver: TonyReception = receiver
def request(self, parcel_content):
print(f"我是{self.receiver.name} 的朋友, 我来帮他代收快递!")
if self.receiver:
self.receiver.request(parcel_content)
print(f"代收人: {self.name}")
if __name__ == "__main__":
tony = TonyReception("Tony", "123424")
print("Tony接收:")
tony.request("雪地靴")
print()
print("Wendy代收:")
wendy = WendyReception("Wendy", tony)
wendy.request("雪地靴")
|
82c722a169742a41e145c7c53dacd7a25011503e | jmshih/clothes_detector | /download_images.py | 862 | 3.5 | 4 | import argparse
import csv
import os
import sys
from urllib import request
def parse_args():
parser = argparse.ArgumentParser(description='script to download images')
parser.add_argument('--file', help='file containing image urls')
parser.add_argument('--output', help='directory to which to write images')
return parser.parse_args()
def main():
args = parse_args()
if not os.path.exists(args.output):
os.makedirs(args.output)
with open(args.file, newline='') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
url = row[0]
outfn = os.path.join(args.output, os.path.basename(url))
if not os.path.exists(outfn):
print(outfn)
request.urlretrieve(url, filename=outfn)
if __name__ == '__main__':
sys.exit(main())
|
1e970fb7e9f38b4a869ebe187a606e93b829d97a | lovepreetbegu/lovepreetbegu | /3rd programme interchang2.py | 138 | 4 | 4 | X = input("enter value of x ")
Y = input("enter value of y")
temp = X
X=Y
Y = temp
print("value of X",X)
print("value of Y",Y)
|
24ce85ab2f75d6744e9226d214a21d06c0d95346 | zhumike/python_test | /算法/冒泡排序.py | 1,500 | 3.796875 | 4 | class solutionMethod:
def bubble_sort(self,arr):
n = len(arr)
# 遍历所有数组元素
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
#改良版本
"""
因为冒泡排序必须要在最终位置找到之前不断
交换数据项,所以它经常被认为是最低效的排
序方法。这些 “浪费式” 的交换操作消耗了
许多时间。但是,由于冒泡排序要遍历整个
未排好的 部分,它可以做一些大多数排序方
法做不到的事。尤其是如果在整个排序过程中
没有交换,我们就可断定列表已经排好。因此
可改良冒泡排序,使其在已知列表排好的情况
下提前结束。这就是说,如果一个列表只需要几次遍
历就可排好,冒泡排序就占有优势:它可以在
发现列表已排好时立刻结束。
"""
# 冒泡排序改良版本
def bubbleSort(alist):
n = len(alist)
exchange = False
for i in range(n-1, 0, -1):
for j in range(0, i):
if alist[j] > alist[j+1]:
alist[j], alist[j+1] = alist[j+1], alist[j]
exchange = True
# 如果发现整个排序过程中没有交换,提前结束
if not exchange:
break
return alist
if __name__=="__main__":
demo = solutionMethod()
arr = [3, 2, 0, 7, 4]
demo.bubble_sort(arr)
print(arr) |
73b0560c33f081fd72ea3cf7ba6561b4f343b544 | elaneyc/wallbreakers | /week4/stacks/valid_parens.py | 717 | 3.59375 | 4 | class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
# Helper method to return opening brace
def getOpen(p):
if p == ")":
return "("
elif p == "]":
return "["
elif p == "}":
return "{"
for p in s:
if p == "(" or p == "{" or p == "[":
stack.append(p)
else:
try:
open = stack.pop()
if open != getOpen(p):
return False
except:
return False
return len(stack) == 0
|
741d61f62f7d1cc625916bff1706af794780c984 | tope628/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 702 | 4.53125 | 5 | #!/usr/bin/python3
"""Add Integer Module
This module takes 2 integers and/ or floats, and adds them.
otherwise raise a TypeError exception with the message a must be an
integer or b must be an integer. Floats must be casted into integers.
"""
def add_integer(a, b):
"""
Args:
a (int): The first parameter.
b (int): The second parameter.
Returns:
int: Addition of a and b. TypeError otherwise.
"""
if type(a) is float:
a = int(a)
if type(b) is float:
b = int(b)
if type(a) is not int:
raise TypeError("a must be an integer")
if type(b) is not int:
raise TypeError("b must be an integer")
return a + b
|
c30ef439685a615c30d4514accf822512a3bab8e | javvidd/gitProject | /Sep_03_files_execption_summary/exception_handling.py | 793 | 3.59375 | 4 | # exception (errors) handling
# 03-Sep - Done
def division(a, b):
try:
print(a/b)
except ZeroDivisionError as zerodv:
print(f"u cant divide by ZERO - err: {zerodv}")
except (TypeError, NameError) as errmsg:
print(f"check yur input - err: {errmsg}")
# raise errmsg # will show regular error message
finally: # will always be executed in either try or except block
print("finally block is executed")
division(45, 15)
division(45, 10)
division(45, 0)
division(100, "a")
division(100, 2)
filename = "dat/inputData.txt"
try:
with open(filename) as input_data:
contents = input_data.read() # it will read line by line
print(contents)
except FileNotFoundError as noFile:
print(f"filename compromised - {noFile}")
|
bfb046b84c0848b3bda806e96502410ad6511851 | zarix908/Crossword | /model/file_reader.py | 770 | 3.53125 | 4 | import sys
class FileReader:
def read(self, file_name):
try:
with open(file_name, 'r') as file:
return list(map(lambda el: el.strip(), file.readlines()))
except FileExistsError:
self.error(file_name, is_exist_error=True)
except FileNotFoundError:
self.error(file_name, is_exist_error=False)
except UnicodeDecodeError:
print("File content should be utf-8 encoded.", file=sys.stderr)
exit(1)
def error(self, file_name, is_exist_error):
print(
"File " + '\"' + file_name + '\"' + " not" +
(" exist." if is_exist_error else " found.") +
" Try main.py -h or --help",
file=sys.stderr)
exit(1)
|
1bfa2109139b1671a1e60e39e3f05f1c92c6d2b1 | lucnortiz/pooej2 | /modulo_helado.py | 932 | 3.53125 | 4 | class Helado:
__gramos= 0
__sabores= []
def __init__(self,gr,sbr):
self.__gramos= gr
self.__sabores= sbr
def __str__(self):
cadenaHelado = 'Gramos: '+ str(self.__gramos)
for i in range(len(self.__sabores)):
cadenaHelado += '\nGusto: '+ self.__sabores[i].get_nombre()
return cadenaHelado
def get_gramos(self):
return self.__gramos
def get_cant_sabores(self):
return len(self.__sabores)
def cargar_lista_codigos(self):
lista_aux= []
for i in range(len(self.__sabores)):
lista_aux.append(self.__sabores[i].get_numero())
return lista_aux
def cargar_lista_nombres(self):
lista_aux= []
for i in range(len(self.__sabores)):
lista_aux.append(self.__sabores[i].get_nombre())
return lista_aux
|
9b1a4963f5ca7054de39a09508e8b2685b0e1b81 | akhilakr06/pythonluminar | /data_collections/list/nexting.py | 150 | 3.71875 | 4 | #nexting possible
# l=[1,2,3,[5,6,[8,9]]]
# print(l)
lst=[1,2,3]
lst.append(9)
print(lst)
lst.remove(2)
print(lst)
lst.clear()
# del lst
print(lst)
|
2d7e71b8f051faf614840e65225548eb31f5de9b | MiguelMontoya-R/holbertonschool-higher_level_programming | /0x0B-python-input_output/2-read_lines.py | 567 | 3.59375 | 4 | #!/usr/bin/python3
"""[summary]
"""
def read_lines(filename="", nb_lines=0):
"""[summary]
Keyword Arguments:
filename {str} -- [description] (default: {""})
nb_lines {int} -- [description] (default: {0})
"""
counter = 0
if nb_lines <= 0:
with open(filename, 'r') as f:
for line in f:
print(line, end="")
else:
with open(filename, 'r') as f:
for line in f:
if counter < nb_lines:
print(line, end="")
counter += 1
|
858659c6e38706fd893a5b6eadff40ce2aaa7cf2 | alexagrchkva/for_reference | /theory/14th_sprint/B.in_place_quick_sort.py | 2,697 | 4.03125 | 4 | # success try: 49534211, 16 мар 2021, 21:55:36, 1.532s, 29.95Mb
def in_place_quick_sort(array, compare_func=None) -> None:
"""
Just one more version of in place quick sort algorithm. Array is
sorted on place, without extra memory usage. Default sorting is ascending.
@param array: Any iterable of objects with defined comparison methods
@param compare_func: function of x,y returning True if x > y, esle False
@return: None
"""
if compare_func is None:
compare_func = lambda x, y: x > y
def run_compare_around_pivot(from_index, to_index):
pivot = array[from_index]
left, right = from_index, to_index
while True:
while compare_func(pivot, array[left]):
left += 1
while compare_func(array[right], pivot):
right -= 1
if left >= right:
return right
array[left], array[right] = array[right], array[left]
left += 1
right -= 1
def inner_in_place_quick_sort(array, from_index, to_index, compare_func):
if from_index < to_index:
pivot_index = run_compare_around_pivot(from_index, to_index)
inner_in_place_quick_sort(array, from_index, pivot_index,
compare_func=compare_func)
inner_in_place_quick_sort(array, pivot_index+1, to_index,
compare_func=compare_func)
inner_in_place_quick_sort(array, 0, len(array) - 1, compare_func)
if __name__ == '__main__':
from collections import namedtuple
Participant = namedtuple('Participant', ['name', 'tasks', 'penalty'])
with open('input.txt') as in_file:
participants_count = int(in_file.readline())
participants = [None] * participants_count
data = in_file.read().split('\n')
for index in range(participants_count):
line = data[index].split()
participants[index] = Participant(
name=line[0], tasks=int(line[1]), penalty=int(line[2]))
def participants_compare(participant_x, participant_y):
if participant_x.tasks < participant_y.tasks:
return True
if participant_x.tasks > participant_y.tasks:
return False
if participant_x.penalty > participant_y.penalty:
return True
if participant_x.penalty < participant_y.penalty:
return False
return participant_x.name > participant_y.name
in_place_quick_sort(participants, compare_func=participants_compare)
with open('output.txt', 'w') as out_file:
out_file.write('\n'.join(x.name for x in participants))
|
62b72c00290591f7171927252c435f3bcb727e8c | wjpe/EjemplosPython-Cisco | /ej13.py | 134 | 3.640625 | 4 | #ciclo for que imprime 2 a la X potencia
pow = 1
for exp in range(16):
print("2 a la potencia de ", exp, "es", pow)
pow *= 2 |
4d50463042048bdde3cd25963ebd94a6bdd28e6a | anrl-utd/clearShallowAtEase | /Experiment/mlp_Vanilla_camera.py | 3,997 | 3.53125 | 4 | from keras.models import Sequential
from keras.layers import Dense,Input,Lambda, Activation, add, Flatten
from keras.models import Model
import keras.layers as layers
def define_vanilla_model_MLP(input_shape,
num_classes,
hidden_units = 32):
"""Define a normal neural network.
### Naming Convention
ex: f2f1 = connection between fog node 2 and fog node 1
### Arguments
num_vars (int): specifies number of variables from the data, used to determine input size.
num_classes (int): specifies number of classes to be outputted by the model
hidden_units (int): specifies number of hidden units per layer in network
### Returns
Keras Model object
"""
# IoT Node (input image)
img_input_1 = Input(shape = input_shape)
img_input_2 = Input(shape = input_shape)
img_input_3 = Input(shape = input_shape)
img_input_4 = Input(shape = input_shape)
img_input_5 = Input(shape = input_shape)
img_input_6 = Input(shape = input_shape)
input_edge1 = add([img_input_1,img_input_2])
input_edge2 = img_input_3
input_edge3 = add([img_input_4,img_input_5])
input_edge4 = img_input_6
# edge nodes
edge1 = define_MLP_architecture_edge(input_edge1, hidden_units, "edge1_output_layer")
edge2 = define_MLP_architecture_edge(input_edge2, hidden_units, "edge2_output_layer")
edge3 = define_MLP_architecture_edge(input_edge3, hidden_units, "edge3_output_layer")
edge4 = define_MLP_architecture_edge(input_edge4, hidden_units, "edge4_output_layer")
# fog node 4
fog4_input = layers.add([edge2,edge3, edge4], name = "node5_input")
fog4 = define_MLP_architecture_fog_with_two_layers(fog4_input, hidden_units,"fog4_output_layer","fog4_input_layer")
# fog node 3
fog3 = Lambda(lambda x: x * 1,name="node4_input")(edge1)
fog3 = define_MLP_architecture_fog_with_one_layer(fog3, hidden_units, "fog3_output_layer")
# fog node 2
fog2_input = layers.add([fog3, fog4], name = "node3_input")
fog2 = define_MLP_architecture_fog_with_two_layers(fog2_input, hidden_units, "fog2_output_layer", "fog2_input_layer")
# fog node 1
fog1 = Lambda(lambda x: x * 1,name="node2_input")(fog2)
fog1 = define_MLP_architecture_fog_with_two_layers(fog1, hidden_units, "fog1_output_layer", "fog1_input_layer")
# cloud node
cloud = Lambda(lambda x: x * 1,name="node1_input")(fog1)
cloud = define_MLP_architecture_cloud(cloud, hidden_units, num_classes)
model = Model(inputs=[img_input_1,img_input_2,img_input_3,img_input_4,img_input_5,img_input_6], outputs=cloud)
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
def define_MLP_architecture_edge(edge_input, hidden_units, output_layer_name):
edge_output = Dense(units=hidden_units, name=output_layer_name, activation='relu')(edge_input)
return edge_output
def define_MLP_architecture_fog_with_two_layers(fog_input, hidden_units, output_layer_name, input_layer_name):
fog = Dense(units=hidden_units,name=input_layer_name ,activation='relu')(fog_input)
fog_output = Dense(units=hidden_units,name=output_layer_name, activation='relu')(fog)
return fog_output
def define_MLP_architecture_fog_with_one_layer(fog_input, hidden_units, output_layer_name):
fog_output = Dense(units=hidden_units,name=output_layer_name ,activation='relu')(fog_input)
return fog_output
def define_MLP_architecture_cloud(cloud_input, hidden_units, num_classes):
cloud = Dense(units=hidden_units,name="cloud_input_layer",activation='relu')(cloud_input)
cloud = Dense(units=hidden_units,name="cloud_layer_1",activation='relu')(cloud)
cloud = Dense(units=hidden_units,name="cloud_layer_2",activation='relu')(cloud)
cloud = Flatten()(cloud)
cloud_output = Dense(units=num_classes,activation='softmax',name = "output")(cloud)
return cloud_output |
af113d96ad81c4c5245dee8e7cabb533fd8879c5 | xxNB/sword-offer | /leetcode/heapqqq/find_median_from_data_stream.py | 2,190 | 3.828125 | 4 | class Heap:
def __init__(self, cmp):
self.cmp = cmp
self.heap = [None]
def __swap__(self, x, y, a):
a[x], a[y] = a[y], a[x]
def size(self):
return len(self.heap) - 1
def top(self):
return self.heap[1] if self.size() else None
def append(self, num):
self.heap.append(num)
self.siftUp(self.size())
def pop(self):
top, last = self.heap[1], self.heap.pop()
if self.size():
self.heap[1] = last
self.siftDown(1)
return top
def siftUp(self, idx):
while idx > 1 and self.cmp(idx, idx / 2, self.heap):
self.__swap__(idx / 2, idx, self.heap)
idx /= 2
def siftDown(self, idx):
while idx * 2 <= self.size():
nidx = idx * 2
if nidx + 1 <= self.size() and self.cmp(nidx + 1, nidx, self.heap):
nidx += 1
if self.cmp(nidx, idx, self.heap):
self.__swap__(nidx, idx, self.heap)
idx = nidx
else:
break
class MedianFinder:
def __init__(self):
"""
Initialize your data structure here.
"""
self.minHeap = Heap(cmp=lambda x, y, a: a[x] < a[y])
self.maxHeap = Heap(cmp=lambda x, y, a: a[x] > a[y])
def addNum(self, num):
"""
Adds a num into the data structure.
:type num: int
:rtype: void
"""
if not self.maxHeap or num > -self.maxHeap.top():
self.minHeap.append(num)
if self.minHeap.size() > self.maxHeap.size() + 1:
self.maxHeap.append(self.minHeap.pop())
else:
self.maxHeap.append( -num)
if self.maxHeap.size() > self.minHeap.size():
self.minHeap.append(self.maxHeap.pop())
def findMedian(self):
"""
Returns the median of current data stream
:rtype: float
"""
if self.minHeap.size() < self.maxHeap.size():
return self.maxHeap.top()
else:
return (self.minHeap.top() + self.maxHeap.top()) / 2.0
c = MedianFinder()
c.addNum(1)
c.addNum(2)
c.findMedian() |
08c8f99dba6fcfce683e9e49eba1e3aff7781c7d | Conanjun/Leetcode_Practice | /leetcode_543.py | 2,329 | 4.375 | 4 | # -*- coding: utf-8 -*-
# Author: Conan0xff
# Mail : [email protected]
# Func : leetcode_543
from utils.BinaryTree import TreeNode
'''
Diameter of Binary Tree
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
Example:
Given a binary tree
1
/ \
2 3
/ \
4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
'''
# ***********************************************************************************************************************
class Solution(object):
'''
思路:
递归遍历每个节点,记录当前最大长度(通过某个节点的最大长度为depth of node.left + depth of node.right + 1)
'''
def diameterOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
max_diameter = 0 # 0为最小直径(只有一个结点)
def depth(root):
if root is None: return 0
ldep = depth(root.left)
rdep = depth(root.right)
nonlocal max_diameter
max_diameter = max(max_diameter, ldep + rdep)
return 1 + max(ldep, rdep)
depth(root)
return max_diameter
import unittest
class SolutionTest(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_solution(self):
solution = Solution()
'''
1
/ \
2 3
/ \
4 5
'''
node1 = TreeNode(1)
node2 = TreeNode(2)
node3 = TreeNode(3)
node4 = TreeNode(4)
node5 = TreeNode(5)
node1.left = node2
node1.right = node3
node2.left = node4
node2.right = node5
self.assertTrue(solution.diameterOfBinaryTree(node1) == 3)
'''
1
/ \
2 3
/ \
4 5
/ \
6 7
/ \
8 9
'''
node1 = TreeNode(1)
node2 = TreeNode(2)
node3 = TreeNode(3)
node4 = TreeNode(4)
node5 = TreeNode(5)
node6 = TreeNode(6)
node7 = TreeNode(7)
node8 = TreeNode(8)
node9 = TreeNode(9)
node1.left = node2
node1.right = node3
node2.left = node4
node2.right = node5
node4.left = node6
node6.left = node8
node5.right = node7
node7.right = node9
self.assertTrue(solution.diameterOfBinaryTree(node1) == 6)
if __name__ == "__main__":
unittest.main()
|
3b561c5a7281736458316a16aaf5fc5db9526646 | Inkatha/PythonPluralsight | /python-scripts/phoneEmailScraper.py | 663 | 3.578125 | 4 | #! python3
import re, pyperclip
# TODO: Create a regex for phone numbers
re.compile(r'''
# 415-555-0000, 555-0000, (415) 555-0000, 555-000 ext 12345, ext.12345, x.12345
((\d\d\d)|(\(\d\d\d)))? #area code (optional)
(\s|-) # first separator
\d\d\d # first 3 digits
- # separator
\d\d\d\d # last 4 digits
(((ext(\.)?\s|x) # extension (optional
(\d{2,5})))? # Extension number (optional)
''', re.VERBOSE)
# TODO: Create a regex object for email addresses
emailRegex = re.compile(r'''
''')
# TODO: Get the text off the clipboard
# TODO: Extract the email/phone from this text
# TODO: Copy the extracted email/phone to the clipboard
|
aae92bf397af6734a10f169bcde2e12c7bf4a4e5 | malaggang2/project_euler | /problem_41~80/problem_41.py | 959 | 3.765625 | 4 | # Problem_41
# Pandigital prime
# We shall say that an n-digit number is pandigital if it makes use of all the
# digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime.
#
# What is the largest n-digit pandigital prime that exists?
import time
def is_prime(n):
if n == 1:
return False
for d in range(2, int(n**0.5) + 1):
if n % d == 0:
return False
return True
def is_pandigital(n):
for d in range(1, len(str(n))+1):
if str(n).count(str(d)) != 1:
return False
return True
start_time = time.time()
for i in range(7654321, 7123456, -1):
if is_prime(i) and is_pandigital(i):
print(i)
break
print("%.6f seconds" % (time.time() - start_time))
# from itertools import permutations
# t1 = time.time()
# print(max([int(''.join(i)) for i in permutations('1234567') if is_prime(int(''.join(i)))]))
# print("%.6f seconds" % (time.time() - t1))
|
a50434d826bd01b70c10f90b62abc04b676d3f44 | Angelpacman/codecademy-py3 | /Unit 02 Strings and Console Output/02 Date and Time/3-Extracting Information.py | 177 | 4.0625 | 4 | from datetime import datetime
now = datetime.now()
current_year = now.year
current_month = now.month
current_day = now.day
print (now.year)
print (now.month)
print (now.day)
|
bb4566515aecfe1ef4ade3a15396a6b5009f400b | yasuo-/python_lesson | /chapter01/range_function.py | 539 | 4.1875 | 4 | """
range関数
"""
num_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# for なら
for i in num_list:
print(i)
# めんどくさい...
for j in range(10): # 0から9まで表示される
print(j)
for k in range(2, 10): # 2からスタート
print(k)
for l in range(2, 10, 3): # 3飛ばし
print(l)
# 10回処理する
for h in range(10):
print('hello')
for _ in range(10):
print('Hello')
# indexに _ で書くと、rangeから入ってくるindexはループでは使われないと理解できる
|
370f72a8b93b9db6908c3335c0eb50fd190832ae | tanshinjie/FoundationOfCyberSecurity | /cyber_lab6/primes_template.py | 1,484 | 3.609375 | 4 | # 50.042 FCS Lab 6 template
# Year 2019
"""
Tan Shin Jie
1003715
"""
import random
MR_ROUND = 40
def square_multiply(a, x, n):
res = 1
for i in bin(x)[2:]:
res = res * res % n
if i == "1":
res = res * a % n
return res
def miller_rabin(n, a):
# Check is n is 2 or 3
if n == 2 or n == 3:
return True
# Check if n is not even.
if n <= 1 or n % 2 == 0:
return False
s = 0
r = n - 1
while r & 1 == 0:
s += 1
r >>= 1
for _ in range(a):
a = random.randrange(2, n - 1)
x = pow(a, r, n)
if x != 1 and x != n - 1:
j = 1
while j < s and x != n - 1:
x = pow(x, 2, n)
if x == 1:
return False
j += 1
if x != n - 1:
return False
return True
def gen_prime_nbits(n):
p = 0
while not miller_rabin(p, MR_ROUND):
p = generate_prime_candidate(n)
return p
def generate_prime_candidate(n):
p = random.getrandbits(n)
p |= (1 << n - 1) | 1
return p
if __name__ == "__main__":
print("Is 561 a prime?")
print(miller_rabin(561, MR_ROUND))
print("Is 27 a prime?")
print(miller_rabin(27, MR_ROUND))
print("Is 61 a prime?")
print(miller_rabin(61, MR_ROUND))
print("Random number (100 bits):")
print(gen_prime_nbits(100))
print("Random number (80 bits):")
print(gen_prime_nbits(80))
|
e714929c319460b65728ef23e6858f1c34f80aac | CloudChaoszero/Data-Analyst-Track-Dataquest.io-Projects | /Python-Programming-Beginner/Python Basics-1.py | 2,159 | 4.625 | 5 | ## 1. Programming And Data Science ##
england = 135
china=123
india=124
united_states=134
## 2. Display Values Using The Print Function ##
china = 123
india = 124
united_states = 134
print(china)
print(india)
print(united_states)
## 3. Data Types ##
china_name = "China"
china_rounded = 123
china_exact = 122.5
print(china_name, '\n', china_rounded, '\n',china_exact)
## 4. The Type Function ##
china_name = "China"
china_exact = 122.5
print(type(china_exact))
## 5. Converting Types ##
china_rounded = 123
int_to_str = str(china_rounded)
str_to_int = int(int_to_str)
## 6. Comments ##
#China is
china = 123
#Hey
india = 124
#wha
united_states = 134
## 7. Arithmetic Operators ##
china_plus_10 = 10+china
us_times_100 = united_states*100
print(china_plus_10,"\n",us_times_100)
## 8. Order Of Operations ##
china = 123
india = 124
united_states = 134
china_celsius = (china-32)*.56
india_celsius=(india-32)*0.56
us_celsius=(united_states-32)*0.56
## 9. Console ##
5/10
indonesia =103
print(indonesia )
## 10. Using A List To Store Multiple Values ##
countries=[]
temperatures=[]
countries.append("China")
countries.append("India")
countries.append("United States")
temperatures = [122.5,124.0,134.1]
print(countries,"\n",temperatures)
## 11. Creating Lists With Values ##
temps = ["China",122.5,"India",124.0,"United States",134.1]
## 12. Accessing Elements In A List ##
countries = []
temperatures = []
countries.append("China")
countries.append("India")
countries.append("United States")
temperatures.append(122.5)
temperatures.append(124.0)
temperatures.append(134.1)
china=countries[0]
china_temperature=temperatures[0]
# Add your code here.
## 13. Retrieving The Length Of A List ##
countries = ["China", "India", "United States", "Indonesia", "Brazil", "Pakistan"]
temperatures = [122.5, 124.0, 134.1, 103.1, 112.5, 128.3]
a=len(countries)
b=len(temperatures)
two_sum=a+b
print(two_sum)
## 14. Slicing Lists ##
countries = ["China", "India", "United States", "Indonesia", "Brazil", "Pakistan"]
temperatures = [122.5, 124.0, 134.1, 103.1, 112.5, 128.3]
countries_slice = countries[1:4]
temperatures_slice = temperatures[-3:] |
b4f3fbffbf8940cbb1adbcf83122c3c98421891b | Bhartendu-Kumar/Computer-Pointer-Controller | /src/input_feeder.py | 1,754 | 3.609375 | 4 | '''
This class can be used to feed input from an image, webcam, or video to your model.
Sample usage:
feed=InputFeeder(input_type='video', input_file='video.mp4')
feed.load_data()
for batch in feed.next_batch():
do_something(batch)
feed.close()
'''
import cv2
from numpy import ndarray
class InputFeeder:
def __init__(self, input_type, input_file=None):
'''
input_type: str, The type of input. Can be 'video' for video file, 'image' for image file,
or 'cam' to use webcam feed.
input_file: str, The file that contains the input image or video file. Leave empty for cam input_type.
'''
self.input_type=input_type
if input_type=='video' or input_type=='image':
self.input_file=input_file
def load_data(self):
if self.input_type=='video':
self.cap=cv2.VideoCapture(self.input_file)
elif self.input_type=='cam':
self.cap=cv2.VideoCapture(0)
else:
self.cap=cv2.imread(self.input_file)
def next_batch(self):
'''
Returns the next image from either a video file or webcam.
If input_type is 'image', then it returns the same image.
'''
if isinstance(self.cap, ndarray):
while True:
yield self.cap
else:
while True:
#self.cap.set(3, 672)
#self.cap.set(4, 384)
_, frame=self.cap.read()
self.cap.release()
yield frame
self.cap=cv2.VideoCapture(0)
def close(self):
'''
Closes the VideoCapture.
'''
if not self.input_type=='image':
self.cap.release()
|
14f235d471e3a4024cc183afb1d1389fcce0addb | samueljml/URI-Online-Judge | /Strings/1237/1237.py | 637 | 3.5 | 4 | while 1:
try:
fra1 = input()
fra2 = input()
if len(fra1) <= len(fra2):
menor = fra1
maior = fra2
else:
menor = fra2
maior = fra1
idf = 0
for i in range(len(menor), 0, -1):
cont = 0
j = i
if idf:
break
for j in range(j, len(menor) + 1, 1):
if menor[cont:j] in maior:
print(i)
idf = 1
break
cont += 1
if idf == 0:
print('0')
except EOFError:
break
|
eedb392a74a3fdec7c66c516369b97b81dbe7d37 | parrot125/myPy | /16_vote_eligibility.py | 314 | 4.125 | 4 | loop = 0
while loop == 0:
try:
age = int(input("Enter the age of the candidate:"))
loop = 1
except:
print("Invalid input")
loop = 0
if age > 18:
print("Eligible to vote.")
elif age < 0:
print("Please enter a positive age.")
else:
print("Not eligible to vote.")
|
a002fec1ed9442782a735ce6bd3ec37b67c873e4 | carlosbognar/Estudos | /Conjuntos.py | 866 | 4.375 | 4 | # Conjuntos são estruturas de dados que não possuem elementos duplicados.
# Podemos aplicar operações matemáticas aos conjuntos.
a = set('abcdefghijkla')
b = set('abcdefx')
print(type(a))
print(a) # imprime todas as letras do conjunto a, sem duplicidade
print(a - b) # imprime o conjunto de letras em a que não estejam não em b
print(a | b) # imprime o conjunto de letras em a OU em b
print(a & b) # imprime o conjunto de letras em a E em b
print(a ^ b) # imprime o conjunto de letras em a OU em b, mas NÃO em AMBOSˆ
########################################################
# Pode-se executar as operações ADD ou POP em conjuntos
#######################################################
a.add('w') # adiciona o elemento "w" ao conjunto a
print(a)
a.pop() # Retira o primeiro elemento do conjunto a
print(a)
|
7a22c700bfe0a61f8142bebcb3c19c51218e87c2 | gutierrecunha/urionlinejudge_python | /URI_1329 - (8672793) - Accepted.py | 226 | 3.6875 | 4 | # -*- coding: utf-8 -*-
while True:
quant = int(input())
if quant == 0:
break
num = list(map(int,input().split()))
print("Mary won",num.count(0),"times and John won",num.count(1),"times") |
081cd0007e071af17efeb5a363cfa75afcfd0417 | jiankangliu/baseOfPython | /PycharmProjects/untitled1/demo.py | 312 | 3.703125 | 4 | # 复数,输入
n = 1
n1 = 2
print(n+n1)
# n2=int(input("请输入第一个数:"))
# n3=int(input("请输入第二个数:"))
# print(n2+n3)
a,b,c=1,[1,2,3],"liu" #多个变量赋值
print(a)
print(b)
print(c)
b1=1
b2=2
print(b2<b1)
c=complex(1,2)
print(c.real)
print(c.imag)
print(c) |
46e080c36913598ce5278f6b29c65b396e80cf18 | salfaris/CS50 | /pset7/houses/roster.py | 786 | 3.625 | 4 | from sys import argv, exit
from cs50 import SQL
# Check len of CLI
if len(argv) != 2:
print("Usage: roster.py house_name")
exit(1)
# Get house name
house = argv[1]
# Get access to sqlite database students.db
db = SQL("sqlite:///students.db")
# Query for student roster
roster = db.execute("SELECT * FROM students WHERE house = ? ORDER BY last, first", house)
# Iterate over each student (is dictionary)
for student in roster:
if student['middle'] is None:
names = [student['first'], student['last']]
else:
names = [student['first'], student['middle'], student['last']]
# Get full name
full_name = " ".join(names)
# Get birth date
birth = student['birth']
# Print the name and birth date
print(f"{full_name}, born {birth}")
|
e15ab2773d71e7e77f6d9942e1712d7bc06db6ca | GalinaR/hailstone_sequence | /main.py | 805 | 4.34375 | 4 | """
Pick some positive integer and call it n.
If n is even, divide it by two.
If n is odd, multiply it by three and add one.
Continue this process until n is equal to one.
"""
def main():
num = int(input("Enter a number: "))
result = 0 # variable that will be the result of the action and then the original value
i = 0 # variable to count steps until num is equal to one
while result != 1:
if num % 2 == 0:
result = num // 2
print(num, "is even, so I take half:", result)
num = result
i += 1
else:
result = num * 3 + 1
print(num, "is odd, so I make 3n+1:", result)
num = result
i += 1
print("The process took", i, "steps to reach 1")
if __name__ == "__main__":
main() |
9d0533e0383cc2762e0b9f22f99a795f3c1f463d | hanmeimei222/CorePythonEx | /for.py | 146 | 3.640625 | 4 | squared = [x**2 for x in range(4)]
for i in squared:
print i,
sqdEvens = [x**2 for x in range(8) if not x%2]
for i in sqdEvens:
print i,
|
a6b749265854050a22e63036bc09748b8fe70ee6 | bvchand/algorithmic-toolbox | /Week-4/4.1_Binary_Search.py | 999 | 3.8125 | 4 | # python3
import math
def binary_search(a, low, high, key):
if high < low:
return -1
mid = low + math.floor((high - low) / 2)
# print("mid, a[mid]:", mid, a[mid])
if key == a[mid]:
return mid
elif key < a[mid]:
return binary_search(a, low, mid-1, key)
else:
return binary_search(a, mid+1, high, key)
def compute_result(a, b):
# prepare the arrays
n = a[0]
a.remove(a[0])
k = b[0]
b.remove(b[0])
# traverse through array 'b'
result = []
i = 0
while i < k:
key = b[i]
# print("key:", key)
low = 0
high = n-1
# print("result value:", binary_search(a, low, high, key))
result.append(binary_search(a, low, high, key))
i += 1
for x in result:
print(x, end=' ')
if __name__ == '__main__':
A = [int(x) for x in input().split()]
B = [int(x) for x in input().split()]
A_terms = A[0]
B_terms = B[0]
compute_result(A, B)
|
0683e12c6d8a59f033694d9f6d703362b7f6e1f0 | dhpn3/Atividades_MetodosNumericos | /Aulas/06-17/Numpy/06-17_intro_NumPy.py | 2,711 | 4.09375 | 4 | import numpy as np #para dar um apelido e n ter que digitar numpy sempre
# www.numpy.org
#python padrão:
v = [1, 2, 3, 4]
#v.append(5) coloca 5 no final do vetor/da lista
print(v)
print(type(v))
print(type(v[0]))
vet = np.array(v) #criando vetor no numpy
#1 jeito de criar vetor no numpy é passando uma lista do python padrao
print(vet)
print(type(vet))
print(vet.dtype)
print(type(vet[0])) #tipo do elemento 1 da lista
print(vet.dtype.name)
print(vet.itemsize) #tamanho de cada elemento do vetor
print(vet.shape) #retorna dimensao, uma tupla
print(vet.ndim) #vetor de dimensao 1, unidimensional
print(vet.size) #tamanho do vetor inteiro, 4 elementos
m = [[1,2,3], [4, 5, 6]]
print(m)
print(m[0])
print(m[0][1])
print(type(m)) #matriz = lista de listas
mat = np.array(m) #array específico para processamento matemático da biblioteca, q transforma a lista pro array do numpy
print(mat)
print(type(mat))
print(mat.shape) #dimensões do array, devolve uma tupla (2,3), q é uma matriz 2x3
print(mat.ndim) # numero de dimensões: 2, pois é bidimensional (2x3)
print(mat.size) #quantos elementos tem na matriz/lista
vp = list(range(1, 6, 1)) #vetor do python original, que cria e printa uma lista com valores separados por vírgula e n aceita passo float, só inteiro
print(vp)
vnp = np.arange(1, 6, 1) #vetor do numpy (vnp), range do numpy q substitui o do python= arange
print(vnp)
print(vnp.shape)
vnp2 = np.arange(0, 4.1, 0.5) # inicio, fim-, passo
#cria a lista com passo de 0.5, e vai até menos que 4.1 (4.0). O numpy tem essa precisão e possibilidade
print(vnp2)
vnp3 = np.linspace(0, 4, 20) #inicio, fim, qtde de elementos (fim fechado, conta até o número que colocou no linspace, no caso até o 4)
#nao fala o passo, fala quanto de elemento que quer
print(vnp3)
mnp = np.arange(15).reshape(3, 5) #arange cria lista com 15 elementos. Já o reshape = 3x5, dimensao que quer
print(mnp)
lp = list(range(200)) #lista padrao python sem os valores default, sem o 0 q é o inicio, sem o passo (1 é o default), e usando só o 200 que é qtde de elementos
print(lp)
mnp2 = np.array(lp).reshape(5, 40) #reshape cria a matriz com o array e atribui a mnp2, q é a matriz em numpy com o comando do numpy reshape
print(mnp2)
mnp3 = np.zeros((3, 3)) #cria matriz no numpy de dim 3x3 preenchida de zeros
print(mnp3)
print(mnp3.shape) #(3,3)
print(mnp3.dtype.name) # dtype.name nesse caso = float 64 bits
mnp4 = np.ones((3, 2, 6), dtype=np.int16) #matriz tridimensional preenchida de um's, 3x2x6, 3 faces de 2 linhas e 6 colunas
print(mnp4)
print(mnp4.dtype.name)
mnp5 = np.empty((4, 8), dtype=np.int64) #preenchida com sujeira de memória, valores qualquer = empty
print(mnp5)
print(mnp5.dtype.name) |
e58b699c1bb83fc953cd6996b446a4c9bfea7dce | ktny/atcoder | /ABC084/d.py | 596 | 3.625 | 4 | Q = int(input())
from functools import lru_cache
@lru_cache(maxsize=None)
def is_prime(n: int):
if n == 2:
return True
if n == 1 or n % 2 == 0:
return False
for p in range(3, int(n**0.5)+1, 2):
if n % p == 0:
return False
return True
like_2017s = []
for i in range(3, 10**5, 2):
if is_prime(i) and is_prime((i+1)//2):
like_2017s.append(i)
from bisect import bisect_left, bisect_right
for _ in range(Q):
l, r = map(int, input().split())
li = bisect_left(like_2017s, l)
ri = bisect_right(like_2017s, r)
print(ri-li) |
7e8583b9565658deba77d10efb8cd14ab8e25d42 | rafaelperazzo/programacao-web | /moodledata/vpl_data/34/usersdata/130/12894/submittedfiles/moedas.py | 682 | 3.828125 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
a=input('Digite o valor de a:')
b=input('Digite o valor de b:')
c=input('Digite o valor de c:')
if a>=b:
qa=0
qb=0
if c%a==0:
qa=c//a
print(qa)
print(qb)
else:
qa=c//a
d=c%a
if d%b==0:
qb=d//b
print(qa)
print(qb)
else:
print('N')
else:
qb=0
qa=0
if c%b==0:
qb=c//b
print(qb)
print(qa)
else:
qb=c//b
d=c%b
if d%a==0:
qa=d//a
print(qb)
print(qa)
else:
print('N')
|
bc4c830f0313ae511cee21d9af0f64d8bb09be4c | Erkebulannn/seminar3 | /exercise1.py | 166 | 3.859375 | 4 | a= input('Введите числа: ')
b= input('Введите числа: ')
c= input('Введите числа: ')
if((a==b)or(a==c)or(b==c)):
print('yes')
|
362652fd22d05e1301fe42717101ba8cf3cc338d | viniciu-sena/Python-Logica | /lista05/L5E08.py | 145 | 3.890625 | 4 | # Feito por Kelvin Schneider
#08
num = int(input("Digite um numero: "))
def contar(num):
print("Quantidade de digitos: ", len(str(num)))
contar(num)
|
2548004dff28e2db89afae83b3c1f3ad2c6c2cd6 | adichouhan14/python-assignment | /py assignments/module 7/car.py | 249 | 3.84375 | 4 | #The __str__ method
class Car:
def __init__(self,color,mileage):
self.color=color
self.mileage=mileage
def __str__(self):
return f'A {self.color} car with mileage {self.mileage}'
car=Car('RED',20)
print(car)
|
e014caf6f868c367460df9d8fea9bb2b363ad255 | danapplegate/AdventOfCode2020 | /src/aoc2020/9/solution.py | 1,638 | 3.921875 | 4 | #!/usr/bin/env python3
import argparse
import sys
def is_valid(numbers, target_index, preamble_size):
preamble = numbers[target_index - preamble_size : target_index]
target = numbers[target_index]
complements = set()
for n in preamble:
if n in complements:
return True
complements.add(target - n)
return False
def find_contiguous_range(numbers, target):
for i in range(len(numbers)):
for j in range(i + 1, len(numbers)):
contiguous = numbers[i : j + 1]
contiguous_sum = sum(contiguous)
if contiguous_sum == target:
return contiguous
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Advent of Code Day 9: Encoding Error")
parser.add_argument(
"filename", nargs="?", type=argparse.FileType("r"), default=sys.stdin
)
parser.add_argument("part", nargs="?", type=int, default=1)
parser.add_argument(
"-s",
dest="preamble_size",
type=int,
default=25,
help="The number of previous numbers to consider (default 25)",
)
args = parser.parse_args()
numbers = [int(n) for n in args.filename.read().split("\n")]
first_invalid = None
for i in range(args.preamble_size, len(numbers)):
if not is_valid(numbers, i, args.preamble_size):
first_invalid = numbers[i]
if args.part == 1:
print(first_invalid)
exit
break
contiguous_range = find_contiguous_range(numbers, first_invalid)
print(sum([min(contiguous_range), max(contiguous_range)]))
|
bdaf2c1f20b1bcea4d5820f613d8c3696d692917 | giancarlo-garbagnati/dsp | /python/q8_parsing.py | 1,473 | 4.40625 | 4 | # The football.csv file contains the results from the English Premier League.
# The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of
# goals scored for and against each team in that season (so Arsenal scored 79
# goals against opponents, and had 36 goals scored against them). Write a
# program to read the file, then print the name of the team with the smallest
# difference in ‘for’ and ‘against’ goals.
import csv
# open the file, convert it to first a csv reader object, then a list
f = open('football.csv', 'r')
r = csv.reader(f)
l = list(r)
# remove the header entry
header = l.pop(0)
# goals are in index 5 and goals allowed are in index 6 in the original csv,
# but let's see if we find it without prior knowledge of which rows they're
# in
for col in range(len(header)):
if header[col] == 'Team':
teamname = col
next
if header[col] == 'Goals':
goals = col
next
if header[col] == 'Goals Allowed':
goals_allowed = col
# makes a list of two element lists by parsing out each team name followed by
# that team's goals-goals allowed
goal_diff_list = []
for team in l:
goal_diff_list.append( [ team[teamname],
int(team[goals])-int(team[goals_allowed]) ] )
# now to sort by goal difference (lowest goal difference should be element 0)
sorted_goal_diff = sorted(goal_diff_list, key = lambda x: x[-1])
print(sorted_goal_diff[0][0])
# poor Leicester, at least they got their title in the 15-16 season
|
24b5f5a4125c5d2040ff6f7868421cd822b1bd0f | andersonbispos/secPython | /wordlist.py | 150 | 3.578125 | 4 | import itertools
import string
resultado = itertools.permutations(string.ascii_letters + string.digits, 5)
for i in resultado:
print(''.join(i)) |
671b1459dd44a026bdfb7732310467ffda43a19b | cocvu99/head-first-python | /chapter1/page18to22.py | 717 | 4.25 | 4 |
movies = [
"The Holy Grail", 1975, "Terry Jone @ Terry Gilliam", 91,
["Graham Chapman",
["Michael Palin", "John Cleese", "Terry Gilliam", "Eric Idle", "Terry Jones"]]
]
print(movies[4][1][3]) ## Result: Eric Idle
print("----------")
print(movies)
print("----------")
for each_item in movies:
print(each_item)
print("----------")
names = ['Michael', 'Terry']
print(isinstance(names, list))
# isinstance() BIF = check if a specific identifier holds data of a specific type
#True
print("----------")
num_names = len(names)
print(isinstance(num_names, list))
print("----------")
for each_item in movies:
if isinstance(each_item, list):
for nested_item in each_item:
print(nested_item)
else:
print(each_item)
|
842527b86d081d90eed10f15ac1fece49005627e | jadenpadua/Data-Structures-and-Algorithms | /bruteforce/box_volume.py | 415 | 3.625 | 4 | #Create a function that gets an object arguments with height, width and length of a box and returns the volume of the box.
#Examples
#volume_of_box({ "width": 2, "length": 5, "height": 1 }) ➞ 10
#volume_of_box({ "width": 4, "length": 2, "height": 2 }) ➞ 16
#volume_of_box({ "width": 2, "length": 3, "height": 5 }) ➞ 30
def volume_of_box(sizes):
return sizes['width'] * sizes['length'] * sizes['height']
|
f15339cb6d1b7353c66a4be054f11a5c19aea223 | gabqueiroz/roaming | /PacoteFuncoes.py | 1,472 | 3.546875 | 4 | import os
import zipfile
from TransformacaoRomming import TrasformarRomming
class PacoteFuncoes():
@staticmethod
def descompactar(dir_name, extension):
# change directory from working dir to dir with files
os.chdir(dir_name)
for item in os.listdir(dir_name): # loop through items in dir
if item.endswith(extension): # check for ".zip" extension
file_name = os.path.abspath(item) # get full path of files
# create zipfile object
zip_ref = zipfile.ZipFile(file_name)
zip_ref.extractall(dir_name) # extract file to dir
zip_ref.close() # close file
os.remove(file_name) # delete zipped
@staticmethod
def converter(extension, dir_name):
os.chdir(dir_name) # muda para o diretorio ques esta os arquivos
# olha os arquivos que estao no diretorio
for item in os.listdir(dir_name):
# procura os arquivos q terminam com a extencao passada
if item.endswith(extension) and extension=='.GS3':
# pega o caminho td do arquivo
file_name = os.path.abspath(item)
TrasformarRomming.transformarGS3(file_name, item)
os.remove(file_name)
|
93301089a2a4a8689dbf71ab6c03d55b60cb4ba0 | mullevik/advent-of-code-2019 | /day_06.py | 1,752 | 3.90625 | 4 | from typing import Dict, List
def bfs(start: str, end: str, graph: Dict[str, List[str]]) -> int:
queue: List[str] = [start]
visited = set()
distances = {}
for node in graph.keys():
distances[node] = 0
while queue:
current = queue.pop(0)
for child in graph[current]:
if child not in visited:
visited.add(child)
queue.append(child)
distances[child] = distances[current] + 1
if child == end:
return distances[end]
raise ValueError("End not found")
def count_orbits_for_planet(node: str, graph: Dict[str, List[str]]) -> int:
stack: List[str] = [node]
visited = set()
orbits = 0
while stack:
current = stack.pop()
for child in graph[current]:
# if child not in visited:
orbits += 1
stack.append(child)
return orbits
def count_orbits(graph: Dict[str, List[str]]) -> int:
total_number_of_orbits = 0
for node in graph.keys():
total_number_of_orbits += count_orbits_for_planet(node, graph)
return total_number_of_orbits
def main():
graph = {}
while True:
input_string = input()
if input_string == "":
break
input_list = input_string.split(")")
parent = input_list[0]
child = input_list[1]
if child not in graph:
graph[child] = []
if parent not in graph:
graph[parent] = []
# make undirected edge
graph[parent].append(child)
graph[child].append(parent)
number_of_jumps = bfs("YOU", "SAN", graph) - 2
print(number_of_jumps)
if __name__ == "__main__":
main()
|
236d2b467e39c74e657d7250ffdfa0230f69f63d | tordjoha/kattis-problems | /python/cetvrta.py | 336 | 3.6875 | 4 | points = []
x = []
y = []
for __ in range(0, 3):
points.append(list(input().split()))
for i in points:
x.append(i[0])
y.append(i[1])
points = [0, 0]
for i in range(0, 3):
if x.count(x[i]) == 1:
points[0] = x[i]
if y.count(y[i]) == 1:
points[1] = y[i]
print('{} {}'.format(points[0], points[1]))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.