blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
6a5a673128ffdcedf4ddf30e621b103ef5b22bff
|
supermitch/Advent-of-Code
|
/2017/05/five.py
| 555 | 3.671875 | 4 |
def exit_count(jumps, incrementor):
count = 0
i = 0
while True:
try:
move = jumps[i]
jumps[i] += incrementor(move)
i += move
count += 1
except IndexError:
return count
def main():
with open('input.txt', 'r') as f:
jumps = [int(x.strip()) for x in f.readlines()]
print('Part A: {}'.format(exit_count(jumps[:], lambda x: 1)))
print('Part B: {}'.format(exit_count(jumps[:], lambda x: -1 if x >= 3 else 1)))
if __name__ == '__main__':
main()
|
2ce379c0d27879cfc873f323da7c6de85dcdd867
|
vivekaxl/LexisNexis
|
/ExtractFeatures/Data/sohamchakravarty/005.py
| 548 | 3.515625 | 4 |
from helperFunctions import *
def findSmallestMultiple(startValue,endValue):
if startValue==1: startValue+=1
numList = range(startValue,endValue+1)
primeList = SOE(endValue)
for i in primeList:
numList.remove(i)
num = product = reduce(lambda x,y:x*y, primeList)
while True:
flag=1
for i in numList:
if num%i:
flag=0
break
if flag==0:
num+=product
else:
return num
print findSmallestMultiple(1,20)
|
c44540b6382062abdb6609363c07fc4b31513a33
|
freezees/wxpython
|
/practice/class/super.py
| 411 | 3.875 | 4 |
class A():
def __init__(self):
self.n=2
def add(self,m):
print('A')
self.n=self.n+2*m
class B(A):
def __init__(self):
self.n=3
def add(self,m):
print('B')
self.n=self.n+1
class C(B):
def __init__(self):
self.n=3
def add(self,m):
super(B,self).add(m)
print('C')
self.n=self.n+4
x=C()
x.add(3)
print(x.n)
|
35ac517024a1935a74b3e49b4a05ed81e96a8bc2
|
nischal-sudo/Flask-repo
|
/Desktop/code/models/store.py
| 959 | 3.546875 | 4 |
from db import db
class StoreModel(db.Model):#creates an object which is having name and price properties #"query"
__tablename__ = "stores"
id = db.Column(db.Integer,primary_key = True)
name = db.Column(db.String(80))#'sqlalchemy.sql.column()'
items = db.relationship("ItemModel",lazy="dynamic")
def __init__(self,name):#name=row[0],price=row[1]
self.name=name
def json(self):
return {"name":self.name,"items":[item.json() for item in self.items]}
@classmethod
def find_by_name(cls,name):
return cls.query.filter_by(name=name).first()#that db name=this name what we have given
#"query" is not something we defibne ,that comes from "db.Model"
#classmethodbecause self.insert(item) is used above
def save_to_db(self):
db.session.add(self)#INSERT INTO items VALUES
db.session.commit()
def delete_from_db(self):
db.session.delete(self)
db.session.commit()
|
f5a71aec645268beeddf0cedc22772ba11702855
|
Niyuhang/read_books
|
/fluent_python/chapter_2/tuple_sample.py
| 813 | 3.53125 | 4 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable = line-too-long
"""
@FIle:tuple.py
~~~~~~~~~~~
:copyright: (c) 2017 by the eigen.
:license: BSD, see LICENSE for more details.
"""
# 元祖可以用来记录数据
# 可以用来进行嵌套数据的拆包
name, cc, pop, (x, y) = ('Tokyo', 'JP', 36.933, (35.689722, 139.691667))
print(x)
"""
具名元祖
"""
from collections import namedtuple
City = namedtuple("city", "name cc pop")
dudu_city = City("dudu", "dupi", 303)
print(dudu_city._asdict()) # 利用asdict 可以返回一个 OrderDict
"""
不可变的tuple存了可变类型
"""
# 虽然会报错,但是因为 += 先执行了 + 然后在执行 = 所以可变类型还是改变了
t_a = (1, 2, [3, 4])
try:
t_a[2] += [3]
except TypeError:
print(t_a)
|
9b3cc541575097b59d98cf057bf95cf23abdd18a
|
EAGLE50/LearnLeetCode
|
/2020-07/Q209-min-sub-array-len.py
| 2,364 | 3.578125 | 4 |
# -*- coding:utf-8 -*-
# @Time : 2020/7/7 22:35
# @Author : bendan50
# @File : Q209-min-sub-array-len.py
# @Function : 长度最小的子数组
# 给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的子数组,
# 并返回其长度。如果不存在符合条件的子数组,返回 0。
#
# 输入:s = 7, nums = [2,3,1,2,4,3]
# 输出:2
# 解释:子数组 [4,3] 是该条件下的长度最小的子数组。
# 输入 s = 213 nums = [12, 28, 83, 4, 25, 26, 25, 2, 25, 25, 25, 12]
# 输出 8
# 解释:子数组[83, 4, 25, 26, 25, 2, 25, 25]是该条件下长度最小的子数组
# @Software: PyCharm
class Solution:
def minSubArrayLen(self, s: int, nums) -> int:
"""
思路:注意子数组的定义,因此不能排序!
暴力法:从第一个结点开始,往后累加,满足大于等于s后,记录长度,然后继续从第二个结点开始。
循环到数组尾,时间复杂度O(n^2)
改进:前后两个指针构建的滑动窗口。sum=nums[head]+...+nums[tail],个数为tail-head+1
:param s:
:param nums:
:return:
"""
#第一步:一直往里加(头结点不变,尾结点往后移),直到满足大于等于s,
head = tail = 0
nums_len = len(nums)
if nums_len == 0:
return 0
sum = 0
ret = nums_len + 1 #子数组的长度,因为寻找最小长度,所以比数组长度大1,当结束时,小于等于数组长度说明有解。
while tail < nums_len:
if nums[tail] >= s:
return 1
sum += nums[tail]
if sum >= s:
#后移前指针
while sum >= s and head <= tail:
sum -= nums[head]
head += 1
ret = min(ret,tail-head+2) # +2是因为tail-head之间应该+1,但此时sum<s了,刚才的头节点应该算上,所以+2
pass
tail += 1
if ret <= nums_len:
return ret
else:
return 0
if __name__ == "__main__":
s = 213
nums = [12, 28, 83, 4, 25, 26, 25, 2, 25, 25, 25, 12]
# s = 7
# nums = [2, 3, 1, 2, 4, 3]
ret = Solution().minSubArrayLen(s,nums)
print(ret)
|
78f5874ca83b11a889034de3d07901f92a40f9bd
|
a2606844292/vs-code
|
/test2/集合和列表去重/1.py
| 463 | 3.9375 | 4 |
#集合和列表去重
#使用set的方法去重复
place=['Beijing','Shanghai','Hangzhou','Guangdong''Beijing','Hangzhou']
print(len(place))
unique_place=set(place)
print(unique_place)
#判断值是否在列表里面
print('London' in unique_place)
print('Shanghai' in unique_place)
place.append('London')
print(place)
#集合add()pop()
#集合添加
number={1,2,3,4,5,6}
number.add(9)
print(number)
#集合为空默认取出1
number.pop()
|
fd9169db18d3b5480aa56cab46eb809755762c4c
|
vincy0320/School_Intro_to_ML
|
/Project1/house-vote-84.py
| 6,880 | 3.90625 | 4 |
#!/usr/bin/python3
import numpy as np
import pandas as pd
import statistics as st
import naivebayes as nb
import winnow as winnow
import util as util
def normalize(column):
"""
Normalize the input feature value if it's in the range of lower bound and
upper bound.
@param feature: the feature value
@param lower_bound: the lower bound
@param upper_bound: the upper bound
@return 1 if the feature value is inbound. Otherwise 0.
"""
value_set = set(column)
unique_count = len(value_set)
if unique_count == 1:
# skip everything in this column.
return []
elif unique_count == 2:
zero = list(value_set)[0]
one = list(value_set)[1]
normalized_column = []
for value in column:
normalized_column.append(1 if value == one else 0)
return [normalized_column]
else:
all_values = list(value_set)
normalized_column = []
# expand into multiple columns
for index in range(len(all_values)):
normalized_column.append([])
for value in column:
for index in range(len(all_values)):
normalized_column[index].append(1 if value == all_values[index] else 0)
return normalized_column
def normalize_data(data, class_name):
"""
Convert the entire data table into 0s and 1s based on the given range and
class name. The range is used to tell which rows' values should be used
to calculate means and standard deviation. The calculated value will be
used to normalize the original values to 0s or 1s.
The class name is used to normalize the class name colum. If the name is
a match, then it's normalized to 1, otherwise, 0.
NOTE: This function implicitly assumes that the rows in the range matches
the given class name.
@param data: The unnormalized data read from csv using panda.
@param range_lower: the lower range for the section of data to be used.
@param range_upper: the uppper range for the section of data to be used.
@param class_name: the name of the classes in this dataset.
@return normalized dataset.
"""
row_count = len(data.index)
col_count = len(data.columns)
normalized_data = []
normalized_class_list = []
class_list = data.iloc[(range(row_count)), 0].values
for value in class_list:
normalized_class_list.append(1 if value == class_name else 0)
normalized_data.append(normalized_class_list)
for index in range(1, col_count):
feature_list = data.iloc[(range(row_count)), index].values
normalized_data += normalize(feature_list)
return normalized_data
def get_training_index():
"""
@return The indexes of the training data used in this dataset. The indices
corresponds to rows.
"""
return list(range(0, 305))
def get_test_index():
"""
@return The indexes of the test data used in this dataset. The indices
corresponds to rows.
"""
return list(range(305, 435))
def train_with_winnow(normalized_data, weights, alpha, theta):
"""
Train the given normalized dataset using winnow algorithm.
@param normalized_data
@param weights for the model.
@param alpha used to tune the model
@param theta used as a threshold for the model.
@return the trained weights.
"""
training_table = util.get_training_table(normalized_data, 0, get_training_index())
return winnow.train(training_table[0], training_table[1], weights, alpha, theta)
def train_and_test_with_winnow(data, class_names):
"""
Train data to classify the given class names using winnow algorithm.
Then run tests on the test data and print the weights and the results.
@param data unnormalized ata used for training and testing/
@param class_names the name of the classes.
"""
alpha = 2
# Train Class
class_theta = 0.5
class_normalized_data = normalize_data(data, class_names[0])
init_weights = [1] * (len(class_normalized_data) - 1)
class_weights = train_with_winnow(class_normalized_data, init_weights.copy(), alpha, class_theta)
# Get Class Test Data
class_index = 0
class_test_feature_table = util.get_test_table(class_normalized_data, class_index, get_test_index())[0]
class_test_classes = util.get_test_table(class_normalized_data, class_index, get_test_index())[1]
original_indices = get_test_index()
# Go through each line of test data and compare results.
for index in range(len(class_test_classes)):
class_features = util.get_test_features(class_test_feature_table, index)
result_class = winnow.get_classification(class_features, class_weights, class_theta)
expected_class = class_test_classes[index]
matched = result_class == expected_class
util.print_test_result(original_indices[index], matched, [result_class], expected_class, class_names)
util.print_all_weights([class_weights, class_weights], class_names)
def train_and_test_with_naive_bayes(data, class_names):
"""
Train data to classify the given class names using naive bayes algorithm.
Then run tests on the test data and print the results.
@param data unnormalized ata used for training and testing/
@param class_names the name of the classes.
"""
# Train data
class_normalized_data = normalize_data(data, class_names[0])
class_training_table = util.get_training_table(class_normalized_data, 0, get_training_index())
class_model = nb.train(class_training_table[0], class_training_table[1])
# Get Class Test Data
class_index = 0
class_test_feature_table = util.get_test_table(class_normalized_data, class_index, get_test_index())[0]
class_test_classes = util.get_test_table(class_normalized_data, class_index, get_test_index())[1]
original_indices = get_test_index()
# Go through each line of test data and compare results.
for index in range(len(class_test_classes)):
class_features = util.get_test_features(class_test_feature_table, index)
result_class = nb.get_classification(class_features, class_model)
expected_class = class_test_classes[index]
matched = result_class == expected_class
util.print_test_result(original_indices[index], matched, [result_class], expected_class, class_names)
def main():
"""
Main function to kick off the trianing and testing
"""
data = pd.read_csv('./house-votes-84.data', header = None)
class_names = ["republican", "democrat"]
print("\n-- Train and Test with Winnow --\n")
train_and_test_with_winnow(data, class_names)
print("\n-- Train and Test with Naive Bayes --\n")
train_and_test_with_naive_bayes(data, class_names)
if __name__ == '__main__':
main()
|
6c389d3548e6fdbce7aeb6bafc979ed014ce5ff6
|
govindak-umd/HackerRank_Python
|
/text_wrap.py
| 292 | 3.78125 | 4 |
import textwrap
def wrap(string, max_width):
i = ""
for c in range(0, len(string), max_width):
i += string[c:c + max_width] + "\n"
return i
if __name__ == '__main__':
string, max_width = input(), int(input())
result = wrap(string, max_width)
print(result)
|
0092c7ace7c54301d4ea68c04771058d752930dc
|
betty29/code-1
|
/recipes/Python/579024_Simple_FIFO_trading_model/recipe-579024.py
| 3,458 | 3.546875 | 4 |
from collections import deque
import random
'''
Example below replicates
+75 MSFT 25.10
+50 MSFT 25.12
-100 MSFT 25.22
Realized P&L = 75 * (25.22 - 25.10) + 25 * (25.22 - 25.12) = $ 11.50
A Trade is split into a set of unit positions that are then dequeued on FIFO basis as part of Sell.
'''
number_of_sell_trades = 1000
max_sell_quentity = 5
min_sell_price = 23.00
max_sell_price = 27.00
class TradeManager():
def __init__(self):
# FIFO queue that we can use to enqueue unit buys and
# dequeue unit sells.
self.fifo = deque()
self.profit = []
def __repr__(self):
return 'position size: %d'%(len(self.fifo))
def execute_with_total_pnl(self, direction, quantity, price):
#print direction, quantity, price, 'position size', len(self.fifo)
if len(self.fifo) == 0:
return 0
if 'Sell' in (direction):
if len(self.fifo) >= quantity:
return sum([(price - fill.price) for fill in tm.execute(direction, quantity, price)])
else:
return 0
else:
return [tm.execute(direction, quantity, price)]
def execute(self, direction, quantity, price):
#print direction, quantity, price, 'position size', len(self.fifo)
if direction in ('Buy'):
for i, fill in Trade(direction, quantity, price):
self.fifo.appendleft(fill)
yield fill
elif direction in ('Sell'):
for i, fill in Trade(direction, quantity, price):
yield self.fifo.pop()
class Fill():
def __init__(self, price):
self.price = price
self.quantity = 1
class Trade():
def __init__(self, direction, quantity, price):
self.direction = direction
self.quantity = quantity
self.price = price
self.i = 0
def __iter__(self):
return self
def next(self):
if self.i < self.quantity:
i = self.i
self.i += 1
return i, Fill(self.price)
else:
raise StopIteration()
# create a TradeManager
tm = TradeManager()
# generate some buys
a = [i for i in tm.execute('Buy', 75, 25.10)]
a = [i for i in tm.execute('Buy', 50, 25.12)]
# generate sell
pnl = np.cumsum(tm.execute_with_total_pnl('Sell', 100, 25.22))
# how much did we make
print 'total pnl', pnl[-1:]
# try something more involved.
tm = TradeManager()
pnl_ending = []
# run n simulations
for step in range(0,50):
a = [i for i in tm.execute('Buy', 75000, 25)]
pnl = np.cumsum([tm.execute_with_total_pnl('Sell', quantity, random.uniform(min_sell_price, max_sell_price)) \
for quantity in [random.randint(0,max_sell_quentity) \
for i in range(0,number_of_sell_trades,1)]])
plot(pnl)
pnl_ending.append(pnl[-1:][0])
print 'step', step, 'pnl', pnl[-1:][0], 'avg. pnl', np.mean(pnl_ending), 'diff to mean', pnl[-1:][0]-np.mean(pnl_ending)
print 'avg, total pnl', np.mean(pnl_ending) #pnl[-1:][0]
show()
# bin the results
hist(pnl_ending, 25)
grid(True)
show()
# could lookat fitting and var.
|
ab44c0f0d73bd0b2a5c03ae8afd6048225119c16
|
jaimeMontea/Text-Analysis
|
/tSNE.py
| 6,984 | 3.53125 | 4 |
'''The following code produces a t-Distributed Stochastic Neighbor Embedding (t-SNE)
technique, which is a dimensionality reduction model used to represent high-dimensional
dataset in a low-dimensional space of two or three dimensions so that we can
visualize it. This code is based on the t-SNE source code fromm scikit-learn library.'''
import numpy as np
from sklearn.datasets import load_digits
from scipy.spatial.distance import pdist
#from sklearn.manifold.TSNE import _joint_probabilities_nn
from scipy import linalg
from sklearn.metrics import pairwise_distances
from scipy.spatial.distance import squareform
from sklearn.manifold import TSNE
from matplotlib import pyplot as plt
import seaborn as sns
from time import time
import pyximport
pyximport.install()
import _utils
sns.set(rc={'figure.figsize':(11.7,8.27)})
palette = sns.color_palette("bright", 10)
MACHINE_EPSILON = np.finfo(np.double).eps
n_components = 2 #Number of components could be rather 2 or 3 given that t-SNE is strictly
#used for visualization and we can only see things in up to 3 dimensinos.
perplexity = 30 #TPerplexity is related with the number of nearest neighbors used in the
#algorithm.
def fit(X):
'''This function transforms the dataset with the t-SNE technique.'''
n_samples = X.shape[0]
# Compute euclidean distance
distances = pairwise_distances(X, metric='euclidean', squared=True)
# Compute joint probabilities p_ij from distances.
P = _joint_probabilities_nn(distances=distances, desired_perplexity=perplexity, verbose=False)
# The embedding is initialized with iid samples from Gaussians with standard deviation 1e-4.
X_embedded = 1e-4 * np.random.mtrand._rand.randn(n_samples, n_components).astype(np.float32)
# degrees_of_freedom = n_components - 1 comes from
# "Learning a Parametric Embedding by Preserving Local Structure"
# Laurens van der Maaten, 2009.
degrees_of_freedom = max(n_components - 1, 1)
return _tsne(P, degrees_of_freedom, n_samples, X_embedded=X_embedded)
def _tsne(P, degrees_of_freedom, n_samples, X_embedded):
'''The embedding is transformed and the KL divergence is used.'''
#The vector is flatten into a 1-D array.
params = X_embedded.ravel()
#The gradient descent is used to minimize the KL (Kullback-Leiber) divergence.
obj_func = _kl_divergence
params = _gradient_descent(obj_func, params, [P, degrees_of_freedom, n_samples, n_components])
#The embedding is back to 2D
X_embedded = params.reshape(n_samples, n_components)
return X_embedded
def _kl_divergence(params, P, degrees_of_freedom, n_samples, n_components):
'''The following function computes the error in the form of the KL divergence and the
gradient.'''
#Calculation of the probability distribution over the points in the low-dimensional map.
X_embedded = params.reshape(n_samples, n_components)
dist = pdist(X_embedded, "sqeuclidean")
dist /= degrees_of_freedom
dist += 1.
dist **= (degrees_of_freedom + 1.0) / -2.0
Q = np.maximum(dist / (2.0 * np.sum(dist)), MACHINE_EPSILON)
# Kullback-Leibler divergence of P and Q
kl_divergence = 2.0 * np.dot(P, np.log(np.maximum(P, MACHINE_EPSILON) / Q))
# Gradient: dC/dY
grad = np.ndarray((n_samples, n_components), dtype=params.dtype)
PQd = squareform((P - Q) * dist)
for i in range(n_samples):
grad[i] = np.dot(np.ravel(PQd[i], order='K'),
X_embedded[i] - X_embedded)
grad = grad.ravel()
c = 2.0 * (degrees_of_freedom + 1.0) / degrees_of_freedom
grad *= c
return kl_divergence, grad
def _gradient_descent(obj_func, p0, args, it=0, n_iter=1000,
n_iter_check=1, n_iter_without_progress=300,
momentum=0.8, learning_rate=200.0, min_gain=0.01,
min_grad_norm=1e-7):
p = p0.copy().ravel()
update = np.zeros_like(p)
gains = np.ones_like(p)
error = np.finfo(np.float).max
best_error = np.finfo(np.float).max
best_iter = i = it
for i in range(it, n_iter):
error, grad = obj_func(p, *args)
grad_norm = linalg.norm(grad)
inc = update * grad < 0.0
dec = np.invert(inc)
gains[inc] += 0.2
gains[dec] *= 0.8
np.clip(gains, min_gain, np.inf, out=gains)
grad *= gains
update = momentum * update - learning_rate * grad
p += update
print("[t-SNE] Iteration %d: error = %.7f,"
" gradient norm = %.7f"
% (i + 1, error, grad_norm))
if error < best_error:
best_error = error
best_iter = i
elif i - best_iter > n_iter_without_progress:
break
if grad_norm <= min_grad_norm:
break
return p
def _joint_probabilities_nn(distances, desired_perplexity, verbose):
"""Compute joint probabilities p_ij from distances using just nearest
neighbors.
This method is approximately equal to _joint_probabilities. The latter
is O(N), but limiting the joint probability to nearest neighbors improves
this substantially to O(uN).
Parameters
----------
distances : sparse matrix of shape (n_samples, n_samples)
Distances of samples to its n_neighbors nearest neighbors. All other
distances are left to zero (and are not materialized in memory).
Matrix should be of CSR format.
desired_perplexity : float
Desired perplexity of the joint probability distributions.
verbose : int
Verbosity level.
Returns
-------
P : sparse matrix of shape (n_samples, n_samples)
Condensed joint probability matrix with only nearest neighbors. Matrix
will be of CSR format.
"""
t0 = time()
# Compute conditional probabilities such that they approximately match
# the desired perplexity
# distances.sort_indices()
n_samples = distances.shape[0]
distances_data = distances.reshape(n_samples, -1)
distances_data = distances_data.astype(np.float32, copy=False)
conditional_P = _utils._binary_search_perplexity(
distances_data, desired_perplexity, verbose)
assert np.all(np.isfinite(conditional_P)), \
"All probabilities should be finite"
# Symmetrize the joint probability distribution using sparse operations
P = csr_matrix((conditional_P.ravel(), distances.indices,
distances.indptr),
shape=(n_samples, n_samples))
P = P + P.T
# Normalize the joint probability distribution
sum_P = np.maximum(P.sum(), MACHINE_EPSILON)
P /= sum_P
assert np.all(np.abs(P.data) <= 1.0)
if verbose >= 2:
duration = time() - t0
print("[t-SNE] Computed conditional probabilities in {:.3f}s"
.format(duration))
return P
|
a5df18ff781e1578cba587e0757865aa92aec2e3
|
sincerehwh/Python
|
/Grammer/3.Container/generator.py
| 666 | 3.859375 | 4 |
''' 生成器
- 节省内存
- 通过推倒获取对应的值
- 用到了再计算
'''
# 生成
squares = []
for i in range(1000):
squares.append(i * i)
for i in range(10):
print(squares[i])
print(squares)
squares_generator = (x*x for x in range(200))
for i in range(100):
print(next(squares_generator))
def fib(max):
n,a,b = 0,0,1
while n<max:
yield b
a,b = b,a+b
n += 1
return 'Finished'
f = fib(100)
import traceback
print(next(f))
print(next(f))
print(next(f))
print(next(f))
print(next(f))
print(next(f))
print(next(f))
try:
print(next(f))
except StopIteration:
print("Interation stoped!")
for i in fib(100):
print(i)
# 遍历
|
34fe1c95fd0cde597bb3ab0950a89538d14e1b98
|
Anarcroth/daily-code-challenges
|
/py/a_zero_sum_game_of_threes.py
| 1,568 | 3.875 | 4 |
#!bin/python3
# Description
#
# Let's pursue Monday's Game of Threes further!
#
# To make it more fun (and make it a 1-player instead of a 0-player game), let's change the rules a bit: You can now add any of [-2, -1, 1, 2] to reach a multiple of 3. This gives you two options at each step, instead of the original single option.
#
# With this modified rule, find a Threes sequence to get to 1, with this extra condition: The sum of all the numbers that were added must equal 0. If there is no possible correct solution, print Impossible.
# Sample Input:
#
# 929
#
# Sample Output:
#
# 929 1
# 310 -1
# 103 -1
# 34 2
# 12 0
# 4 -1
# 1
#
# Since 1 - 1 - 1 + 2 - 1 == 0, this is a correct solution.
# Bonus points
#
# Make your solution work (and run reasonably fast) for numbers up to your operating system's maximum long int value, or its equivalent. For some concrete test cases, try:
#
# 18446744073709551615
# 18446744073709551614
n = int(input("Enter a number: "));
sum_of_all_adds = 0;
while n > 1:
if n % 3 == 0:
print(int(n), "0");
n /= 3;
elif (n - 2) % 3 == 0:
print (int(n), " -2");
n = (n - 2) / 3;
sum_of_all_adds -= 2;
elif (n + 2) % 3 == 0:
print (int(n), " +2");
n = (n + 2) / 3;
sum_of_all_adds += 2;
elif (n - 1) % 3 == 0:
print (int(n), " -1");
n = (n - 1) / 3;
sum_of_all_adds -= 1;
elif (n + 1) % 3 == 0:
print(int(n), " +1");
n = (n + 1) / 3;
sum_of_all_adds += 1;
print(int(n));
print(sum_of_all_adds);
|
65a1c8a95efc8e936fe8ef518f78068619a93aa4
|
eldss-classwork/MITx
|
/6.00.1x Intro to Comp Sci/CreditCardDebt2.py
| 974 | 4.28125 | 4 |
# Evan Douglass
# This program calculates the minimum fixed monthly payment
# (as a multiple of ten) that will pay off a given debt in
# less than one year.
# initialize values
balance = 3926
annualInterestRate = 0.2
# monthly interest rate
monthlyRate = annualInterestRate / 12.0
def findEndBalance(balance, monthlyRate, payment):
'''
balance (float or int): Original balance in account.
monthlyRate (float): Monthly interest rate.
payment (int): Monthly payment. Assumes multiples of 10.
returns the ending balance after 12 months as a float or int.
'''
test_balance = balance
for month in range(12):
test_balance -= payment
test_balance += (test_balance * monthlyRate)
return test_balance
# increment test values for payment until findEndBalance returns negative
test = 0
while round(findEndBalance(balance, monthlyRate, test), 2) > 0:
test += 10
print('Lowest Payment:', test)
|
361e0f993770178c79807c6541cf7f369dbeb7d7
|
jfdiel/programming
|
/python/exercicios/area.py
| 308 | 3.9375 | 4 |
#calculo de area
a = float(input())
b = float(input())
c = float(input())
pi = 3.14159
print("TRIANGULO:"+str(round(((a*c)/2),3)))
print("CIRCULO:"+str(round((c*c)*pi,3)))
print("TRAPEZIO:"+str(round((((a+b)*c)/2),3)))
print("QUADRADO:"+str(round((b*b),3)))
print("RETANGULO:"+str(round((a*b),3)))
|
d01c53f51ed7b1c9fc039566c7dd4715fe8fad27
|
ahmedsalah52/Self_Driving_Car_Course
|
/Python/q3.py
| 214 | 4.0625 | 4 |
num = int(input("Please enter any number to build a pyramid\n"))
for i in range(num+1):
for j in range(num-i):
print(" ",end ="")
for k in range((i*2)-1):
print("*",end ="")
print("\n")
|
e8d73a23d38a55c9bf7ec46228666bb546e5ec68
|
microease/Python-Cookbook-Note
|
/Chapter_3/3.3.py
| 165 | 3.765625 | 4 |
# 你需要将数字格式化后输出,并控制数字的位数、对齐、千位分隔符和其他的细节。
x = 1234.56789
res = format(x, '0.2f')
print(res)
|
dbc14e2a8ccf129c0973caa5dc74e7cf1d355d2f
|
farochocolom/Core-Data-Structures
|
/source/set_test.py
| 5,217 | 3.59375 | 4 |
#!python
from hashset import Set
import unittest
class SetTest(unittest.TestCase):
def test_init(self):
s = Set()
assert s.size == 0
assert s.table.length() == 0
def test_init_with_list(self):
s = Set(['A', 'B', 'C'])
assert s.size == 3
assert s.table.length() == 3
assert s.is_empty() is False
def test_contains(self):
s = Set(['A', 'B', 'C', 'D', 'X'])
assert s.contains('C') == True
assert s.contains('A') == True
s.add('Y')
assert s.contains('Y') == True
assert s.contains('Z') == False
s.add('Z')
assert s.contains('Z') == True
s.remove('Y')
assert s.contains('Y') == False
def test_add(self):
s = Set()
assert s.size == 0
s.add('Y')
assert s.contains('Y') == True
assert s.size == 1
s.add('Y')
assert s.size == 1
assert s.contains('Z') == False
s.add('Z')
assert s.contains('Z') == True
assert s.size == 2
def test_remove(self):
s = Set(['A', 'B', 'C', 'D', 'X'])
assert s.size == 5
s.remove('A')
assert s.contains('A') == False
assert s.size == 4
with self.assertRaises(KeyError):
s.remove('Z') # item not in set
assert s.size == 4
s.remove('B')
assert s.contains('B') == False
assert s.size == 3
s.remove('C')
assert s.size == 2
s.remove('D')
assert s.size == 1
s.remove('X')
assert s.size == 0
def test_union(self):
sA = Set(['A', 'B', 'C', 'D', 'X'])
sB = Set(['M', 'N', 'O', 'A', 'P'])
psA = set(['A', 'B', 'C', 'D', 'X'])
psB = set(['M', 'N', 'O', 'A', 'P'])
assert sA.union(sB).sort() == ['A', 'B', 'C', 'D', 'X', 'M', 'N', 'O', 'P'].sort()
assert sB.union(sA).sort() == ['A', 'B', 'C', 'D', 'X', 'M', 'N', 'O', 'P'].sort()
assert sA.table.keys().sort() == Set(['A', 'B', 'C', 'D', 'X']).table.keys().sort()
sA = Set(['A', 'B', 'C', 'D', 'X'])
sB = Set()
assert sA.union(sB).sort() == ['A', 'B', 'C', 'D', 'X'].sort()
assert sB.union(sA).sort() == ['A', 'B', 'C', 'D', 'X'].sort()
sA = Set()
sB = Set()
assert sA.union(sB) == []
assert sB.union(sA) == []
def test_intersection(self):
sA = Set(['A', 'B', 'C', 'D', 'X'])
sB = Set(['A', 'B', 'C', 'D', 'X'])
assert sA.intersection(sB).sort() == ['A', 'B', 'C', 'D', 'X'].sort()
assert sB.intersection(sA).sort() == ['A', 'B', 'C', 'D', 'X'].sort()
sA = Set(['A', 'B', 'C', 'D', 'X'])
sB = Set(['A', 'B', 'M', 'P', 'Z'])
assert sA.intersection(sB).sort() == ['A', 'B', 'C', 'D', 'X'].sort()
assert sB.intersection(sA).sort() == ['A', 'B'].sort()
sA = Set(['A', 'B', 'C', 'D', 'X'])
sB = Set(['M', 'N', 'O', 'A', 'P'])
assert sA.intersection(sB).sort() == ['A'].sort()
assert sB.intersection(sA).sort() == ['A'].sort()
sA = Set(['A', 'B', 'C', 'D', 'X'])
sB = Set()
assert sA.intersection(sB).sort() == [].sort()
assert sB.intersection(sA).sort() == [].sort()
#
sA = Set()
sB = Set()
assert sA.intersection(sB) == []
assert sB.intersection(sA) == []
def test_difference(self):
sA = Set(['A', 'B', 'C', 'D', 'X'])
sB = Set(['A', 'B', 'C', 'D', 'X'])
assert sA.difference(sB).sort() == [].sort()
assert sB.difference(sA).sort() == [].sort()
sA = Set(['A', 'B', 'C', 'D', 'X'])
sB = Set(['A', 'B', 'M', 'P', 'Z'])
assert sA.difference(sB).sort() == ['C', 'D', 'X'].sort()
assert sB.difference(sA).sort() == ['M', 'P', 'Z'].sort()
sA = Set(['A', 'B', 'C', 'D', 'X'])
sB = Set(['M', 'N', 'O', 'A', 'P'])
assert sA.difference(sB).sort() == ['D'].sort()
assert sB.difference(sA).sort() == ['M', 'N', 'O', 'P'].sort()
sA = Set(['A', 'B', 'C', 'D', 'X'])
sB = Set()
assert sA.difference(sB).sort() == ['A', 'B', 'C', 'D', 'X'].sort()
assert sB.difference(sA).sort() == [].sort()
sA = Set()
sB = Set()
assert sA.difference(sB) == []
assert sB.difference(sA) == []
def test_is_subset(self):
sA = Set(['A', 'B', 'C', 'D', 'X'])
sB = Set(['A', 'B', 'C', 'D', 'X'])
assert sA.is_subset(sB) == True
assert sB.is_subset(sA) == True
sA = Set(['A', 'B', 'C', 'D', 'X'])
sB = Set(['A', 'B'])
assert sA.is_subset(sB) == False
assert sB.is_subset(sA) == True
sA = Set(['A', 'B', 'C', 'D', 'X'])
sB = Set(['A', 'B', 'M'])
assert sA.is_subset(sB) == False
assert sB.is_subset(sA) == False
sA = Set(['A', 'B', 'C', 'D', 'X'])
sB = Set()
assert sA.is_subset(sB) == False
assert sB.is_subset(sA) == True
sA = Set()
sB = Set()
assert sA.is_subset(sB) == True
assert sB.is_subset(sA) == True
if __name__ == '__main__':
unittest.main()
|
591fbcaa20fca0a66edeff2a4b54efc47d7fc68a
|
asiacanady/s18-a05
|
/q5.py
| 738 | 3.90625 | 4 |
import pandas as pd
df = pd.read_csv('crimes.csv')
'''
#5. What is the number of the community area with the most homicides in 2017?
How many were there? What is the community area's name? (You can find a mapping
of community area numbers to names online.)
'''
homicides = df[df['Primary Type'] == 'HOMICIDE']
communityarea = homicides['Community Area'].value_counts()
sorted_homicides = communityarea.sort_values()
top_homicide = sorted_homicides.tail(1)
print('The community with the Most Homicides is Austin (community number# then homicide count):', top_homicide)
#The number of the community area with the most homicides is number #25
#There were 81 homicides in neighborhood 25.
#Austin is the neighborhood with the most crimes.
|
4a68705438d1658953af47ad0d8c433353761fd0
|
jasminegrewal/algos
|
/ctci/arrays_strings/nullify.py
| 822 | 3.6875 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 29 18:52:48 2017
@author: jasmine
"""
def nullify(m):
row=[False]*len(m)
col=[False]*len(m[0])
# store which column and rows have zeroes
for i in range(0,len(m)):
for j in range(0,len(m[0])):
if (m[i][j]==0):
row[i]=True
col[j]=True
# make the rows zero
for b in range(0,len(row)):
if (row[b]==True):
for j in range(0,len(m[0])):
m[b][j]=0
# make the columns zero
for b in range(0,len(col)):
if (col[b]==True):
for j in range(0,len(m)):
m[j][b]=0
return m
m=[[1,2,0,4,7,8],[5,6,7,8,7,9],[2,4,3,0,9,7]]
print(nullify(m))
|
3654a947f7bec54a6965fbc5e134e50262871a8c
|
MicherlaneSilva/ifpi-ads-algoritmos2020
|
/fabio_2/fabio_2_p2/f2_p2_q6.py
| 551 | 3.828125 | 4 |
#Leia o turno em que um aluno estuda
# sendo M para matutino, V para Vespertino ou N para Noturno e
#escreva a mensagem "Bom Dia!", "Boa Tarde!"
# ou "Boa Noite!" ou "Valor Inválido!", conforme o caso.
def main():
print('Saudação\n')
turno = input('Turno (M/V/N): ').upper()
print(saudacao(turno))
def saudacao(turno):
if turno == 'M':
return 'Bom dia!'
elif turno == 'V':
return 'Boa tarde!'
elif turno == 'N':
return 'Boa Noite!'
else:
return 'Turno inválido'
main()
|
32cf78294d58e82313cadc8f1b8a33533cc55c07
|
Jabba1988/Python_Examples
|
/m9_1в.py
| 362 | 3.765625 | 4 |
# Пример 1
from random import *
# Генерация списка
m = [randint(-5,6) for i in range(5)]
# Вывод списка в целом
print(m)
# Вывод списка поэлементно
a,b = 0,0
for i in m:
if i>=0: a += i
else: b += i
print('Сумма положительных: %d, отрицательных: %d' % (a,b))
|
7f2c7152c1e7bfe30b1861258408f1728ffcba49
|
LinearPi/tanzhou_work_file
|
/lession/minmax.py
| 318 | 3.5 | 4 |
def minmax(test, *args):
res = args[0]
for arg in args[1:]:
if test(arg, res):
res = arg
return res
def lessthan(x, y): return x < y
def grtrthan(x, y): return x > y
print(minmax(lessthan, 4, 2, 3, 1, 6 ,5))
print(minmax(grtrthan, 4, 2, 3, 1, 6 ,5))
def func(a, b, c=2, d=4):
print(a,b,c,d)
func(1, *(5,6))
|
89ffeb17f800ab821ad5e8488f9ca081bb993412
|
vacous/Coursera-Python-Specilization
|
/Principles of Computing/Puzzle15.py
| 13,524 | 3.515625 | 4 |
"""
Loyd's Fifteen puzzle - solver and visualizer
Note that solved configuration has the blank (zero) tile in upper left
Use the arrows key to swap this tile with its neighbors
"""
import poc_fifteen_gui
# helper function
def unroll(list1):
'''
return the unroll list
'''
output = []
for ele in list1:
output.extend(ele)
return output
def find(list1,ele):
'''
find the idx and jdx for a target ele
'''
for idx in range( len(list1) ):
for jdx in range(len(list1[idx])):
if list1[idx][jdx] == ele:
result = [idx,jdx]
return result
class Puzzle:
"""
Class representation for the Fifteen puzzle
"""
def __init__(self, puzzle_height, puzzle_width, initial_grid=None):
"""
Initialize puzzle with default height and width
Returns a Puzzle object
"""
self._height = puzzle_height
self._width = puzzle_width
self._grid = [[col + puzzle_width * row
for col in range(self._width)]
for row in range(self._height)]
if initial_grid != None:
for row in range(puzzle_height):
for col in range(puzzle_width):
self._grid[row][col] = initial_grid[row][col]
# the solved array
self._solve = [ [[] for _ in range(self._width)] for _ in range(self._height) ]
for num in range(self._height * self._width):
self._solve[num // self._width][num % self._width] = num
def __str__(self):
"""
Generate string representaion for puzzle
Returns a string
"""
ans = ""
for row in range(self._height):
ans += str(self._grid[row])
ans += "\n"
return ans
#####################################
# GUI methods
def get_height(self):
"""
Getter for puzzle height
Returns an integer
"""
return self._height
def get_width(self):
"""
Getter for puzzle width
Returns an integer
"""
return self._width
def get_number(self, row, col):
"""
Getter for the number at tile position pos
Returns an integer
"""
return self._grid[row][col]
def get_solve(self, row, col):
"""
Getter for the number at tile position pos
Returns an integer
"""
return self._solve[row][col]
def set_number(self, row, col, value):
"""
Setter for the number at tile position pos
"""
self._grid[row][col] = value
def set_solve(self, row, col, value):
"""
Setter for the number at tile position pos
"""
self._solve[row][col] = value
def clone(self):
"""
Make a copy of the puzzle to update during solving
Returns a Puzzle object
"""
new_puzzle = Puzzle(self._height, self._width, self._grid)
return new_puzzle
########################################################
# Core puzzle methods
def current_position(self, solved_row, solved_col):
"""
Locate the current position of the tile that will be at
position (solved_row, solved_col) when the puzzle is solved
Returns a tuple of two integers
"""
solved_value = (solved_col + self._width * solved_row)
for row in range(self._height):
for col in range(self._width):
if self._grid[row][col] == solved_value:
return (row, col)
assert False, "Value " + str(solved_value) + " not found"
def update_puzzle(self, move_string):
"""
Updates the puzzle state based on the provided move string
"""
zero_row, zero_col = self.current_position(0, 0)
for direction in move_string:
if direction == "l":
assert zero_col > 0, "move off grid: " + direction
self._grid[zero_row][zero_col] = self._grid[zero_row][zero_col - 1]
self._grid[zero_row][zero_col - 1] = 0
zero_col -= 1
elif direction == "r":
assert zero_col < self._width - 1, "move off grid: " + direction
self._grid[zero_row][zero_col] = self._grid[zero_row][zero_col + 1]
self._grid[zero_row][zero_col + 1] = 0
zero_col += 1
elif direction == "u":
assert zero_row > 0, "move off grid: " + direction
self._grid[zero_row][zero_col] = self._grid[zero_row - 1][zero_col]
self._grid[zero_row - 1][zero_col] = 0
zero_row -= 1
elif direction == "d":
assert zero_row < self._height - 1, "move off grid: " + direction
self._grid[zero_row][zero_col] = self._grid[zero_row + 1][zero_col]
self._grid[zero_row + 1][zero_col] = 0
zero_row += 1
else:
assert False, "invalid direction: " + direction
##################################################################
# Phase one methods
def lower_row_invariant(self, target_row, target_col):
"""
Check whether the puzzle satisfies the specified invariant
at the given position in the bottom rows of the puzzle (target_row > 1)
Returns a boolean
"""
if self._grid[target_row][target_col] == 0:
for idx in range(target_row * self._width + target_col + 1, self._height * self._width):
if unroll(self._grid)[idx] != unroll(self._solve)[idx]:
return False
else:
return False
return True
def solve_interior_tile(self, target_row, target_col):
"""
Place correct tile at target position
Updates puzzle and returns a move string
"""
move_made = ''
move_value = self._solve[target_row][target_col]
pos_value = find(self._grid,move_value)
# move the tile to the target value position
for _ in range(target_row - pos_value[0]):
self.update_puzzle('u')
move_made += 'u'
if pos_value[1] - target_col < 0:
for _ in range(target_col - pos_value[1]):
self.update_puzzle('l')
move_made += 'l'
for _ in range(target_col - pos_value[1] - 1):
if pos_value[0] > 0:
self.update_puzzle('urrdl')
move_made += 'urrdl'
else:
self.update_puzzle('drrul')
move_made += 'drrul'
for idx in range(target_row - pos_value[0]):
if idx == 0:
self.update_puzzle('dru')
move_made += 'dru'
else:
self.update_puzzle('lddru')
move_made += 'lddru'
elif pos_value[1] - target_col > 0:
for _ in range(pos_value[1] - target_col):
self.update_puzzle('r')
move_made += 'r'
for _ in range(pos_value[1] - target_col - 1):
if pos_value[0] > 0:
self.update_puzzle('ulldr')
move_made += 'ulldr'
else:
self.update_puzzle('dllur')
move_made += 'dllur'
for idx in range(target_row - pos_value[0]):
if idx == 0:
if pos_value[0] > 0:
self.update_puzzle('ullddru')
move_made += 'ullddru'
else:
self.update_puzzle('dlu')
move_made += 'dlu'
else:
self.update_puzzle('lddru')
move_made += 'lddru'
else:
for _ in range(target_row - pos_value[0] -1):
self.update_puzzle('lddru')
move_made += 'lddru'
# move the tile back to position
if self.lower_row_invariant(target_row, target_col-1) == False:
self.update_puzzle('ld')
move_made += 'ld'
return move_made
def solve_col0_tile(self, target_row):
"""
Solve tile in column zero on specified row (> 1)
Updates puzzle and returns a move string
# """
move_made = ''
self.update_puzzle('u')
move_made += 'u'
if self._solve[target_row][0] != self._grid[target_row][0]:
if self._solve[target_row][0] != self._grid[target_row-1][1]:
self.update_puzzle('r')
move_made += 'r'
temp_board = self.clone()
temp_board.set_solve(target_row - 1 ,1, temp_board.get_solve(target_row,0) )
temp_move = temp_board.solve_interior_tile(target_row - 1, 1)
self.update_puzzle(temp_move)
move_made += temp_move
print move_made
self.update_puzzle('ruldrdlurdluurddlur')
move_made += 'ruldrdlurdluurddlur'
for _ in range(self._width - 2):
self.update_puzzle('r')
move_made += 'r'
return move_made
else:
for _ in range(self._width - 1):
self.update_puzzle('r')
move_made += 'r'
return move_made
#############################################################
# Phase two methods
def row0_invariant(self, target_col):
"""
Check whether the puzzle satisfies the row zero invariant
at the given column (col > 1)
Returns a boolean
"""
if self._grid[0][target_col] == 0:
temp_board = self.clone()
if target_col > 0:
invariant_pos = [1,target_col-1]
else:
invariant_pos =[0,temp_board.get_width()-1]
temp_board.set_number(invariant_pos[0],invariant_pos[1],0)
return temp_board.lower_row_invariant(invariant_pos[0],invariant_pos[1])
else:
return False
def row1_invariant(self, target_col):
"""
Check whether the puzzle satisfies the row one invariant
at the given column (col > 1)
Returns a boolean
"""
return self.lower_row_invariant(1, target_col)
def solve_row0_tile(self, target_col):
"""
Solve the tile in row zero at the specified column
Updates puzzle and returns a move string
"""
move_made = ''
self.update_puzzle('ld')
move_made += 'ld'
if self._grid[0][target_col] != self._solve[0][target_col] :
temp_board = self.clone()
temp_board.set_solve(1,target_col - 1, temp_board.get_solve(0,target_col))
temp_move = temp_board.solve_interior_tile(1, target_col - 1)
self.update_puzzle(temp_move)
move_made += temp_move
self.update_puzzle('urdlurrdluldrruld')
move_made += 'urdlurrdluldrruld'
return move_made
def solve_row1_tile(self, target_col):
"""
Solve the tile in row one at the specified column
Updates puzzle and returns a move string
"""
move_made = ''
move_made += self.solve_interior_tile(1, target_col)
self.update_puzzle('ur')
move_made += 'ur'
return move_made
###########################################################
# Phase 3 methods
def solve_2x2(self):
"""
Solve the upper left 2x2 part of the puzzle
Updates the puzzle and returns a move string
"""
move_made = ''
while self._grid[1][0] != self._width:
self.update_puzzle('lurd')
move_made += 'lurd'
self.update_puzzle('ul')
move_made += 'ul'
return move_made
def solve_puzzle(self):
"""
Generate a solution string for a puzzle
Updates the puzzle and returns a move string
"""
if self._grid == self._solve:
return ''
move_made = ''
ini_pos = find(self._grid,0)
for _ in range(self._height - ini_pos[0] - 1):
self.update_puzzle('d')
move_made += 'd'
for _ in range(self._width - ini_pos[1] - 1):
self.update_puzzle('r')
move_made += 'r'
for jdx in range(self._height - 1 , 1 ,-1):
for idx in range(self._width - 1,-1,-1):
if idx > 0:
move_made += self.solve_interior_tile(jdx,idx)
else:
move_made += self.solve_col0_tile(jdx)
print self._grid
tile_pos = self._width-1
for _ in range(self._width-2):
move_made += self.solve_row1_tile(tile_pos)
move_made += self.solve_row0_tile(tile_pos)
tile_pos -= 1
move_made += self.solve_2x2()
return move_made
|
5193f7e839ced93442309649c21311d6cc3d761a
|
dubesar/My-Machine-Learning-Course-Projects
|
/NeuralNetwork.py
| 1,911 | 3.5625 | 4 |
import numpy as np
import pandas as pd
dataset=pd.read_csv("train (1).csv")
del dataset['Cabin']
del dataset['Ticket']
del dataset['PassengerId']
del dataset['Name']
del dataset['Embarked']
del dataset['Age']
# creating a dict file
Sex = {'male': 1,'female': 0}
# traversing through dataframe
# Gender column and writing
# values where key matches
dataset.Sex = [Sex[item] for item in dataset.Sex]
dataset=np.array(dataset)
X_act=dataset[:,1:]
Y_act=dataset[:,0]
Y_act=Y_act.T
def sigmoid(x):
return 1.0/(1+ np.exp(-x))
def sigmoid_derivative(x):
return x * (1.0 - x)
class NeuralNets:
def __init__(self,x,y):
self.input = x
self.weights1=np.random.rand(self.input.shape[1],4)
self.weights2=np.random.rand(4,1)
self.y=y
self.output=np.zeros(self.y.shape)
def feedforward(self):
self.layer1 = sigmoid(np.dot(self.input, self.weights1))
self.output = sigmoid(np.dot(self.layer1, self.weights2))
def backprop(self):
# application of the chain rule to find derivative of the loss function with respect to weights2 and weights1
d_weights2 = np.dot(self.layer1.T, (2*(self.y - self.output) * sigmoid_derivative(self.output)))
d_weights1 = np.dot(self.input.T, (np.dot(2*(self.y - self.output) * sigmoid_derivative(self.output), self.weights2.T) * sigmoid_derivative(self.layer1)))
# update the weights with the derivative (slope) of the loss function
self.weights1 += d_weights1
self.weights2 += d_weights2
if __name__ == "__main__":
Y_act=dataset[:,1]
X_act=dataset[:,2:]
X = np.array([[0,0,1],
[0,1,1],
[1,0,1],
[1,1,1]])
y = np.array([[0],[1],[1],[0]])
struct=NeuralNets(X,y)
for i in range(1500):
struct.feedforward()
struct.backprop()
print(struct.output)
|
b403a3e00834ab2ed795fcbe090982353b777c69
|
kramerProject/trybe_exercises
|
/Computer_Science/34_python/34_1/exercises.py
| 1,286 | 3.890625 | 4 |
import math
def max(x,y):
if (x > y):
return x
elif (x < y):
return y
else:
return "Numbers are equal"
def meanNumber(lst):
return sum(lst) / len(lst)
def square(x):
n = 0
if (x > 1):
while (n < x):
print(x * "*")
n += 1
else:
return ""
def biggestName(names):
biggest = ""
for i in range(0, len(names)):
if (i == 0):
biggest = names[i]
elif (len(names[i]) > len(biggest)):
biggest = names[i]
return biggest
def painting(meters):
liters = meters / 3
cans = liters / 18
totalPrice = math.ceil(cans) * 80
res = (math.ceil(cans), totalPrice)
return res
def triangle(x, y, z):
isTriangle = ((x + y) > z) and ((x + z) > y) and ((y + z) > x)
if isTriangle:
if ( x == y == z):
return "Equilatero"
elif (x == y or x == z or y == z):
return "Isósceles"
else:
return "Escaleno"
return "not a triangle"
#ex1
print('ex1 ----')
print(max(3,2))
#ex2
print('ex2 ----')
numbers = [1, 3]
print(meanNumber(numbers))
#ex3
print('ex3 ----')
print(square(5))
#ex4
print('ex4 ----')
names = ["José", "Lucas", "Nádia", "Fernanda", "Cairo", "Joana"]
print(biggestName(names))
#ex5
print('ex5 ----')
print(painting(108))
#ex6
print('ex5 ----')
print(triangle(3,4,5))
|
304d7b315810f388c1b4a6512ff4f6d55fc848e5
|
ee1tbg/elanFirstPyProj
|
/dictionaries/dictionaryChallenges.py
| 3,322 | 4.03125 | 4 |
'''
Created on Feb 1, 2019
@author: Winterberger
'''
# Write your values_that_are_keys function here:
import dictionaryBasics
def values_that_are_keys(my_dictionary):
return [my_dictionary[key] for key in my_dictionary if my_dictionary[key] in my_dictionary.keys()]
'''
for key in my_dictionary:
if my_dictionary[key] in my_dictionary.keys():
valkeys.append(my_dictionary[key])
return valkeys
'''
# Uncomment these function calls to test your function:
print(values_that_are_keys({1:100, 2:1, 3:4, 4:10}))
# should print [1, 4]
print(values_that_are_keys({"a":"apple", "b":"a", "c":100}))
# should print ["a"]
'''
Determine frequency of each entry in a list. return a dictionary with key = entry and value = frequency
'''
# Write your frequency_dictionary function here:
def frequency_dictionary(words):
freq_dict = {}
for i in range(len(words)):
if words[i] not in words[i+1:]:
key_count = 0
key = words[i]
#print(key)
for j in words:
#print(j)
if key == j:
key_count += 1
#print(key_count)
freq_dict.update({key:key_count})
#print(freq_dict)
return freq_dict
'''
keys = [words[index] for index in range(len(words)) if words[index] not in words[index+1:]]
print(keys)
frequency = []
'''
# Uncomment these function calls to test your function:
print(frequency_dictionary(["apple", "apple", "cat", 1]))
# should print {"apple":2, "cat":1, 1:1}
print(frequency_dictionary([0,0,0,0,0]))
# should print {0:5}
'''
Count number of unique values in a dictionary
'''
# Write your unique_values function here:
def unique_values(my_dictionary):
val_list = [lVal for lVal in my_dictionary.values()]
print(val_list)
unique_vals = [val_list[i] for i in range(len(val_list)) if val_list[i] not in val_list[i+1:]]
print(unique_vals)
num_unique_vals = len(unique_vals)
return num_unique_vals
# Uncomment these function calls to test your function:
print(unique_values({0:3, 1:1, 4:1, 5:3}))
# should print 2
print(unique_values({0:3, 1:3, 4:3, 5:3}))
# should print 1
'''
Last name nightmare...
'''
# Write your count_first_letter function here:
def count_first_letter(names):
last_names = [i for i in names]
first_names = [names[i] for i in last_names]
print(last_names)
print(first_names)
last_letters = [last_name[0] for last_name in last_names]
print(last_letters)
for i in range(len(last_names)):
if last_letters[i] in last_letters[:i]:
index = last_letters.index(last_letters[i])
first_names[i] += first_names[index]
last_letters.pop(index)
first_names.pop(index)
print(last_letters)
print(first_names)
new_names = {last_letter:names for last_letter,names in zip(last_letters,first_names)}
return new_names
# Uncomment these function calls to test your function:
#print(count_first_letter({"Stark": ["Ned", "Robb", "Sansa"], "Snow" : ["Jon"], "Lannister": ["Jaime", "Cersei", "Tywin"]}))
# should print {"S": 4, "L": 3}
print(count_first_letter({"Stark": ["Ned", "Robb", "Sansa"], "Snow" : ["Jon"], "Sannister": ["Jaime", "Cersei", "Tywin"]}))
# should print {"S": 7}
|
23ecedd3b431e13c9c9f1048e32db3c55fe86820
|
jaford/thissrocks
|
/jim_python_practice_programs/29.60_print_user_input_fibonacci_numbers.py
| 440 | 4.34375 | 4 |
# Write a program that will list the Fibonacci sequence less than n
def fib_num_user():
n = int(input('Enter a number: '))
t1 = 1
t2 = 1
result = 0
# loop as long as t1 is less than n
while t1 < n:
# print t1
print(t1)
# assign sum of t1 and t2 to result
result = t1 + t2
# assign t2 to t1
t1 = t2
# assign result to t2
t2 = result
fib_num_user()
|
9beca6071b7647792e0fb5c50cd28bd225fbe7db
|
nidhigup01/Binary_search_in-Python
|
/binary_search.py
| 3,249 | 3.59375 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Tue May 22 07:03:10 2018
@author: nidhi
learned from : https://www.youtube.com/watch?v=zeULw-a7Mw8
"""
list1 = [0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
value = 6
def binary_search_linear(list1, value):
for i in range (len(list1)):
if list1[i] == value:
print('value is in the list')
return True
print('value not in the list')
return
def binary_search_iterative (list1, value):
l = len(list1)
while l > 0 :
mid_index = (l-1)//2
if len(list1) ==0 or (len(list1)==1 and list1[0]!= value):
print ('value not in the list')
return -1
elif list1[mid_index] == value or list1[0]==value:
print ('value is in the list')
return True
elif list1[mid_index] < value:
list1 = list1[mid_index+1:]
print ('first mid_index', mid_index)
print('truncated first list1', list1)
l = len(list1)
elif list1[mid_index] > value:
list1 = list1[:mid_index-1]
print ('second mid_index', mid_index)
print('truncated second list1', list1)
l = len(list1)
return False
def binary_searchiterativeindex(list1, value):
low = 0
high = len(list1)-1
while low <= high:
mid_index = (low + high)//2
if len(list1) ==0 or (len(list1)==1 and list1[0]!= value):
return -1
elif list1[mid_index] ==value:
print(mid_index)
return True
elif list1[mid_index] < value:
low = mid_index + 1
elif list1[mid_index] > value:
high = mid_index-1
return -1
def binary_search_recursive(list1, value):
l= len(list1)
mid_index = (l-1)//2
if len(list1) ==0 or (len(list1)==1 and list1[0]!= value):
print ('value not in the list')
return -1
elif list1[mid_index] == value or list1[0]==value:
print('value is in the list')
return True
elif list1[mid_index] < value:
list1 = list1[mid_index+1:]
binary_search_recursive(list1, value)
elif list1[mid_index] > value:
list1 = list1[:mid_index-1]
binary_search_recursive(list1, value)
return False
def bsrec_ind(arr, value, low, high):
if len(arr) == 0 or (len(arr)==1 and arr[0]!= value) or low> high:
print ('value not in the list')
return False
else:
mid = (low + high)//2
if arr[mid] == value:
print ('index at which value found = ', mid)
return mid
elif value > arr[mid]:
low = mid+1
bsrec_ind(arr, value, low, high)
elif value < arr[mid]:
high = mid-1
bsrec_ind(arr, value, low, high)
return False
bsrec_ind(list1, 31, 0, 6)
def binary_search_iteration (list1, value):
binary_search_linear(list1, 5)
binary_search_iterative(list1, 16)
binary_search_recursive(list1, 1)
|
f432cf794ed99c15a98410600baa2f1072207f56
|
JosephLevinthal/Research-projects
|
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/4488/codes/1590_842.py
| 283 | 3.546875 | 4 |
# Teste seu codigo aos poucos.
# Nao teste tudo no final, pois fica mais dificil de identificar erros.
# Nao se intimide com as mensagens de erro. Elas ajudam a corri
num =int(input("Digite um numero:"))
d1= num//1000
d2=(num//100)%10
d3=(num//10)%10
d4=num%10
print(d1+d2+d3+d4)
|
6efd0b4c730e65f7cce22f1abdbd55af7cc12f6f
|
Philip-Owen/algorithms
|
/python/bubble-sort.py
| 536 | 3.8125 | 4 |
import time
start_time = time.time()
arr = [77, 32, 99, 17, 2, 95]
def bubble_sort(arr):
swapped = True
passes = 0
while swapped:
swapped = False
passes = passes + 1
for i in range(len(arr) - passes):
if i != (len(arr) - 1):
if arr[i] > arr[i + 1]:
arr.insert(i, arr.pop(i + 1))
swapped = True
print(arr)
print(f"Bubble sort took {time.time() - start_time} seconds to complete with {passes} passes.")
bubble_sort(arr)
|
887e0b57d0e2b4eaea5d3b93d39ced5776616cc1
|
shaikhAbuzar/basicprograms
|
/curry.py
| 254 | 3.625 | 4 |
def add_a(a):
def add_a_b(b):
def add_a_b_c(c):
return a++b+c
return add_a_b_c
return add_a_b
ans=add_a(1)(2)(3)
print('Sum: ',ans)
ans1=add_a(1)
ans12=ans1(2)
ans123=ans12(3)
print('SUM: ',ans123)
|
b3737ba7b65cf239791970f9fbf709a6c48f9c11
|
anakarlasantana/Exercicios-Python
|
/Exercício 3.py
| 415 | 4.15625 | 4 |
# -*- coding: utf-8 -*-
"""
Exercício 3 - Nessa aula, vamos aprender como funcionam os tipos primitivos no Python e as peculiaridades do int() float() bool() e str(). Além disso, veremos como fazer as primeiras operações com a função print() do Python.
"""
n1 = int(input ('Digite o primeiro numero:'))
n2 = int(input('Digite o segundo numero: '))
s = int(n1 + n2)
print('A soma entre', n1,'e', n2,'vale:',s)
|
c0d254cebd98fca0208a96d235ed21bd6f314b5b
|
lianggangscu/pylearn
|
/funpar.py
| 159 | 3.609375 | 4 |
#!/usr/bin/env python
#Filename:funwithpar.py
def maximum(a,b):
if a>b:
print("%d is maximum" %a)
else:
print("%d is maximum" %b)
a=7
b=5
maximum(a,b)
|
4b946226ee7195017b43b231827f57f837fee95e
|
lutolita/python
|
/taller3/t6.py
| 535 | 3.875 | 4 |
valores = []
def fibonacci(actual, cantidad):
index = actual
while (index < cantidad):
if index == 0:
valores.append(0)
elif index == 1:
valores.append(1)
else:
valores.append(valores[actual - 1] + valores[index - 2])
index += 1
def imprimir(lista):
for i in lista:
print(i)
cantidad = input("Cuantos valores desea generar?\n")
fibonacci(0, int(cantidad))
imprimir(valores)
|
80df7cd086497063e9f7e132e935d7321eb53a44
|
arifaulakh/Competitive-Programming
|
/DMOJ/hailstone/hailstone.py
| 184 | 3.609375 | 4 |
n = int(input())
total = 0
while (n !=1):
if n%2 == 0:
n = n/2
total += 1
else:
n = n*3 + 1
total += 1
if n == 1:
break
print(total)
|
0a8fb243e4fb328b4d0795b9af73d57fd879a858
|
Vampir007one/Python
|
/Kalmykov_Practical_9/quest10.py
| 347 | 3.65625 | 4 |
mass = [int(s) for s in input("Введите информацию: ").split()]
indexMin = 0
indexMax = 0
for i in range(1, len(mass)):
if mass[i] > mass[indexMax]:
indexMax = i
if mass[i] < mass[indexMin]:
indexMin = i
mass[indexMin], mass[indexMax] = mass[indexMax], mass[indexMin]
print(' '.join([str(i) for i in mass]))
|
5f422e651695dcc8c1e16e768c53a6805ee42ed1
|
adamcfro/practice-python-solutions
|
/password_generator.py
| 559 | 3.984375 | 4 |
import string
from random import choice
def password_generator():
strength = int(input("How strong would you like your password? "))
password = ''
for item in range(1, strength + 1):
alphanum = string.ascii_letters + string.digits
rand_alphanum = choice(alphanum)
password += rand_alphanum
return password
print(password_generator())
##########
import random
import string
s = string.ascii_letters + string.digits
passlen = int(input("How strong of a password? "))
p = ''.join(random.sample(s, passlen))
print(p)
|
5d7d46c5e2a994df49516bf1b3c94c095823bf42
|
AnatolyDomrachev/karantin
|
/is28/fedin28/4/4_4.py
| 168 | 3.5 | 4 |
def func(n):
if ((n%4 == 0) and (n%100 != 0)) or (n%400 == 0):
print(True)
else:
print(False)
n=int(input("Nomer goda: "))
func(n)
|
5402cddf875a574d62350cd820de1fc5a61b405f
|
oelbarmawi/Ehab
|
/Session3/UserInput.py
| 413 | 4.25 | 4 |
def getName():
name = input('What is your name? ')
print("Your name is {}.".format(name))
# getName()
"""
The function input always returns a string.
"""
def getAge():
age = input("What is your age? ")
# To convert a string to an integer [whole numbers]
my_age = int(age) + 10
# To convert a string to a float [decimals]
my_age = float(age) + 10
print("My age is {}".format(my_age))
getAge()
|
49f5154f43739fb689857e9afe54972c4058a24e
|
Meirelesg/Codigos-Python
|
/Atividade 5/Atividade2.py
| 347 | 3.75 | 4 |
valores = list()
pares = []
for cont in range(0,5):
valores.append(int(input(f"Isnira o {cont+1}º valor: ")))
if valores[cont] % 2 == 0:
pares.append(valores[cont])
for cont in range(0,len(pares)):
if pares[cont] in valores:
valores.remove(pares[cont])
del(pares)
print(f"Lista sem os valores pares: {valores}")
|
9bad3f9582f4a8a85af82d0e0e6b3a7be9ca02ca
|
thhuynh91/Python_Practice
|
/Even_Fibonacci_numbers.py
| 478 | 4.46875 | 4 |
#The Fibonacci number is generated by adding the previous two terms.
#For example: below is list of Fibonacci numbers:
#1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#Find the sum of the even-valued terms by considering the terms in Fibonacci sequence whose value do not exceed a given "n"
def Fibo(n):
total = 0
f1 = 0
f2 = 1
for i in range(n):
while f2 < n:
if f2%2 == 0:
total += f2
f1, f2 = f2, f1 + f2
return(total)
|
f0ad2a42b0cbf0bfcb2885deabd9fa506bd15b80
|
RyanWaltersDev/NSPython_Chapter7
|
/sandwich_orders.py
| 823 | 4.15625 | 4 |
#!/usr/bin/env python3
# RyanWaltersDev Jun 16 2021 -- TIY 7-8 and 7-9
# Initial list
sandwich_orders = [
'pastrami', 'italian', 'ham', 'capricolla',
'pastrami', 'meatball', 'grilled chicken', 'pastrami',
]
finished_sandwiches = []
# Remove pastrami 7-9
print("My apologies, we are out of pastrami! But the other sandiwches "
"will be ready shortly.")
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
# While loop
while sandwich_orders:
finished_sandwich = sandwich_orders.pop()
print(f"We finished making your {finished_sandwich.title()} Sandwich!")
finished_sandwiches.append(finished_sandwich)
# Print List
print("\nHere is the full order of sandwiches that we made for you.")
for sandwich in finished_sandwiches:
print(sandwich.title())
# END OF PROGRAM
|
1d8a50fe96a7d502f058813eb1b471fbea834eac
|
MaliciousMatrix/SAPySap
|
/SAP1/ScheduleGeneration.Core/duration.py
| 2,940 | 3.75 | 4 |
class Duration:
def __init__(self, start_date_time, end_date_time, *args, **kwargs):
self._is_init = True
self.start_time = start_date_time
self.end_time = end_date_time
self._is_init = False
assert self.start_time < self.end_time, 'start time must be before end time'
return super().__init__(*args, **kwargs)
def can_happen_inside_of(self, date_time_span):
'''
checks to see if this object can happen inside of the given object.
[6 am to 10 am].can_happen_inside_of([6am to 10 am]) => true
[7 am to 9 am].can_happen_inside_of([6am to 10 am]) => true
[6 am to 10 am].can_happen_inside_of([7am to 10 am]) => false
'''
return self.can_end_inside_of(date_time_span) and self.can_start_inside_of(date_time_span)
def can_start_inside_of(self, start_time):
other_start_date = start_time.start_time
other_end_date = start_time.end_time
return self.start_time >= other_start_date and self.start_time <= other_end_date
def can_end_inside_of(self, end_time):
other_start_date = end_time.start_time
other_end_date = end_time.end_time
return self.end_time <= other_end_date and self.end_time >= other_start_date
def conflicts_with(self, other_time):
if self.can_end_inside_of(other_time) \
or self.can_start_inside_of(other_time) \
or other_time.can_start_inside_of(self) \
or other_time.can_start_inside_of(self):
# In this case a DateTimeSpan that ends at 10 does not conflict with one that starts at 10.
if self.start_time == other_time.end_time or self.end_time == other_time.start_time:
return False
return True
def __str__(self):
return '%s to %s' % (self.start_time, self.end_time)
def set_start_time(self, value):
assert self._is_init or value < self.end_time, 'start time must be before end time'
self._start_time = value
def get_start_time(self):
return self._start_time
def set_end_time(self, value):
assert self._is_init or value > self.start_time, 'start time must be before end time'
self._end_time = value
def get_end_time(self):
return self._end_time
def get_length_in_hours(self):
elapsed_time = self.end_time - self.start_time
return elapsed_time.total_seconds() / 60.0 / 60.0
def is_on_date(self, date):
return self.start_time.year == date.year and \
self.start_time.month == date.month and \
self.start_time.day == date.day
start_time = property(get_start_time, set_start_time)
end_time = property(get_end_time, set_end_time)
def __eq__(self, value):
return isinstance(value, Duration) and \
value.start_time == self.start_time and \
value.end_time == self.end_time
|
aa7c2aaf64588e63ba783483e36a663dd048d53f
|
joshua-morris/chess3d
|
/Chess/Model.py
| 4,333 | 3.765625 | 4 |
from enum import Enum
class Game:
"""A chess game with game state information."""
def __init__(self, positions=None):
"""Create a new game with default starting positions."""
if positions is None:
self._positions = self._init_positions()
else:
self._position = positions
# true if white's turn
self.turn = True
self.playing = True
self.focused = None
def is_playing(self):
return self.playing
def move(self, rank, file):
print(rank, file)
return self.focused.move(Position(rank, file))
def get_focused(self):
return self.focused
def get_focused_position(self):
return self.focused.get_position().get_rank(), self.focused.get_position().get_file()
def get_model(self):
return self.focused.get_model_idx()
def set_focused(self, position):
for piece in self._positions:
if piece.get_position().get_rank() == position[0] and piece.get_position().get_file() == position[1]:
self.focused = piece
return
def unfocus(self):
self.focused = None
def _init_positions(self):
"""Default starting positions."""
result = []
for file in range(8):
result.append(Pawn(Position(7-file, 1), Colour.BLACK, False, "blackPawnModels", file))
result.append(Pawn(Position(7-file, 6), Colour.WHITE, False, "whitePawnModels", file))
result.append(Rook(Position(0, 0), Colour.BLACK, "blackRookModels", 0))
result.append(Rook(Position(7, 0), Colour.BLACK, "blackRookModels", 1))
result.append(Rook(Position(0, 7), Colour.WHITE, "whiteRookModels", 0))
result.append(Rook(Position(7, 7), Colour.WHITE, "whiteRookModels", 1))
result.append(Knight(Position(1, 0), Colour.BLACK, "blackKnightModels", 0))
result.append(Knight(Position(6, 0), Colour.BLACK, "blackKnightModels", 1))
result.append(Knight(Position(1, 7), Colour.WHITE, "whiteKnightModels", 0))
result.append(Knight(Position(6, 7), Colour.WHITE, "whiteKnightModels",1))
result.append(Bishop(Position(2, 0), Colour.BLACK, "blackBishopModels", 0))
result.append(Bishop(Position(5, 0), Colour.BLACK, "blackBishopModels", 1))
result.append(Bishop(Position(2, 7), Colour.WHITE, "whiteBishopModels", 0))
result.append(Bishop(Position(5, 7), Colour.WHITE, "whiteBishopModels",1))
result.append(Queen(Position(3, 0), Colour.BLACK, "blackQueenModel"))
result.append(Queen(Position(3, 7), Colour.WHITE, "whiteQueenModel"))
result.append(King(Position(4, 0), Colour.BLACK, "blackKingModel"))
result.append(King(Position(4, 7), Colour.WHITE, "whiteKingModel"))
return result
class Position:
"""Represent a position on the board."""
def __init__(self, rank, file):
"""Create a new position with the given rank and file."""
self._rank = rank
self._file = file
def get_rank(self):
"""Return this position's rank."""
return self._rank
def get_file(self):
"""Return this position's file."""
return self._file
class Piece:
"""Represent a piece on the board."""
def __init__(self, position, colour, model, idx=None):
"""Initialise a new piece with the given position."""
self._position = position
self._colour = colour
self._model = model
self._idx = idx
def get_model_idx(self):
return self._model, self._idx
def get_position(self):
return self._position
def move(self, position: Position):
"""(Abstract) move the piece to the new position.
Parameters:
position: the position to move to
Return True if a valid move and False otherwise.
"""
pass
class Pawn(Piece):
"""A pawn piece."""
def __init__(self, position: Position, colour, en_passant: bool, model, idx):
"""Initialise a new pawn piece."""
super().__init__(position, colour, model, idx)
self._en_passant = en_passant
def move(self, position):
# Check the given move is valid
mult = 1 if self._colour == Colour.WHITE else -1
if mult * (self._position.get_file() - position.get_file()) not in [1, 2]:
return False # too far vertically
# TODO
self._position = position
return True
class Rook(Piece):
pass
class Knight(Piece):
pass
class Bishop(Piece):
pass
class Queen(Piece):
pass
class King(Piece):
pass
class Colour(Enum):
WHITE = 0
BLACK = 1
|
2d6aa76070e4cb2534bcf595ab4bbe30ddd1516d
|
baewonje/iot_bigdata_-
|
/python_workspace/01_jump_to_python/5_APP/1_Class/188_4_cal_class5.py
| 1,011 | 3.828125 | 4 |
class FourCal:
def setdata(self,first, second):
self.first = first # 멤버 변수가 없음에도 객체생성이후에
self.second = second
def add(self):
result = self.first + self.second
return result
def print_number(self):
print("first: %d, second: %d"%(self.first,self.second))
a= FourCal()
a.setdata(1,2) # 객채 생성이후의 멤버 변수 값을 설정할 때 사용한다.
a.print_number()
print(a.add())
print("first: %d, second: %d"%(a.first,a.second))
print(a.first+a.second)
# 위와 같이 python의 모든 클래스의 멤버 변수, 함수는 속성이 public,이라
# 외부에서 모두 접근이 가능하다.
# 하지만 클래스의 멤버 변수에 대해서 설정하는 것은
# 클래스 정의시 멤버변수 정의, 생성자, setxxx()함수로 정의 및 수정을 하는 것이
# 객체지향 프로그래밍에 가깝다.
temp = [1,2,3,4]
temp.__class__
# 객체지향언어에서의 private 개념은 __멤버변수__.
|
4c2bcf20c71c2b536281c7a330705ecc57794ff8
|
UdhaikumarMohan/Strings-and-Pattern
|
/length/longest.py
| 331 | 4.1875 | 4 |
# Write a function that takes a list of words and returns the length of the longest word
def longest(Array):
length = 0
for a in Array:
if len(a)>length:
length = len(a)
return length
Array = ['Bishop','Heber','College','Tiruchirappalli','udhai','abcdefghijklmnopqrstuvwxyz1234567890']
print(longest(Array))
|
f9945addf9236f79da3c4a08621e0f6a3e42773a
|
MaartenAmbergen/MiniProjectGroep5
|
/AlarmV2.py
| 653 | 3.515625 | 4 |
from gpiozero import LED, Button
from time import sleep
led1 = LED(17)
led2 = LED(27)
led3 = LED(13)
button = Button(2)
alarm_aan = False
while True:
if button.is_pressed and alarm_aan == False:
alarm_aan = True
led2.on()
sleep(5)
if alarm_aan:
led3.on()
print("er moet nu een alarm naar de server worden gestuurd")
elif button.is_pressed and alarm_aan:
alarm_aan == False
led2.off()
led3.off()
led1.on()
sleep(1)
led1.off()
sleep(1)
led1.on()
sleep(1)
led1.off()
print("het alarm is gereset")
|
987b846c4b84893c318b17f519790cce262c5108
|
ltlongzhu/MLCode
|
/gradient-descent/gradient-descent-linear-regression.py
| 2,197 | 4 | 4 |
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
#This is a simple implementation of gradient descent for linera regression on a simle two dimensional data stored in data.csv
from numpy import *
from matplotlib import pyplot as plt
def run():
points = genfromtxt("/home/mirk/ML/mycode/gradient-descent/data.csv", delimiter=",")
learning_rate = 0.0001
# y = mx+b
initial_b = 0
initial_m = 0
num_iterations = 2000
print "Starting gradient descent at b = {0}, m = {1}, error = {2}".format(initial_b, initial_m, compute_error(initial_b, initial_m, points))
print "********************************************************"
[b, m] = gradient_descent(points, initial_b, initial_m, learning_rate, num_iterations)
print "After {0} iterations b = {1}, m = {2}, error = {3}".format(num_iterations, b, m, compute_error(b, m, points))
x = points[:,0]
y = points[:,1]
plt.scatter(x,y)
plt.plot(x,(m * x) + b)
plt.show()
#function for calculating total error for candidate line 'y' value
def compute_error(b, m, points):
total_error = 0
for i in range(0, len(points)):
x = points[i, 0]
y = points[i, 1]
total_error += (y - (m * x + b)) ** 2
return total_error/float(len(points))
#function for step gradient, finding minima for the b,m
def step_gradient(b_current, m_current, points, learning_rate):
b_gradient = 0
m_gradient = 0
N = float(len(points))
for i in range(0, len(points)):
x = points[i, 0]
y = points[i, 1]
b_gradient += -(2/N) * (y - ((m_current * x) + b_current))
m_gradient += -(2/N) * x * (y -((m_current * x) + b_current))
new_b = b_current - (learning_rate * b_gradient)
new_m = m_current - (learning_rate * m_gradient)
return [new_b, new_m]
#function for running descent, iterating for finding best fit
def gradient_descent(points, starting_b, starting_m, learning_rate, num_iterations):
b = starting_b
m = starting_m
image = []
for i in range(num_iterations):
b, m = step_gradient(b, m, array(points), learning_rate)
return [b, m]
if __name__ == '__main__':
run()
|
80b1c005f340398f8124089d25374cc48e1f3b1c
|
xsoer/pytools
|
/learn-numpy/src/1.Tutorial/1.4.LessBasic.py
| 807 | 3.515625 | 4 |
import numpy as np
#%%
"""
Broadcasting allows universal functions to deal in a meaningful way with inputs that do not have exactly the same shape.
The first rule of broadcasting is that if all input arrays do not have the same number of dimensions, a “1” will be repeatedly prepended to the shapes of the smaller arrays until all the arrays have the same number of dimensions.
The second rule of broadcasting ensures that arrays with a size of 1 along a particular dimension act as if they had the size of the array with the largest shape along that dimension. The value of the array element is assumed to be the same along that dimension for the “broadcast” array.
After application of the broadcasting rules, the sizes of all arrays must match. More details can be found in Broadcasting.
"""
|
0f9c5818d270deb7ac1d18e8538656c23d57f76d
|
jfxugithub/python
|
/面向对象的高级编程/多重继承.py
| 559 | 3.953125 | 4 |
#!/usr/bin/evn python3.5
# -*- coding: utf-8 -*-
#################################
#和java不同的是Python是可以多重继承的
#################################
class Animal(object):
type = 'animal'
class Runable(object):
def run(self):
print('I can run...')
class Dog(Animal,Runable):
def __init__(self):
self.type = 'dog'
dog = Dog()
print("I am a",dog.type)
dog.run()
'''
小结:
我们不需要复杂而庞大的继承链,只要选择组合不同的类的功能,就可以快速构造出所需的子类
'''
|
9b6d49ba6374688c59eb99d0056afdf7a2388878
|
korabelus/python_step
|
/functions/recursion.py
| 4,088 | 4.4375 | 4 |
"""factorial"""
def factorial(n: int):
if n == 0:
return 1
if n == 1:
return 1
else:
return n * factorial(n-1)
print('factorial')
print(factorial(0))
print(factorial(1))
print(factorial(2))
print(factorial(5))
"""возведение числа а в степень n"""
def my_pow(n: int, a: int):
if n == 0:
return 1
if n == 1:
return a
else:
return a * my_pow(n-1, a)
print('возведение в степень')
print(my_pow(2, 5))
print(my_pow(3, 10))
print(my_pow(0, 4))
print(my_pow(1, 6))
""""сумма цифр натурального числа"""
def sum_of_digits(n: int):
if n < 10:
return n
else:
return n % 10 + sum_of_digits((n - n % 10) / 10)
print('сумма цифр натурального числа')
print(sum_of_digits(100))
print(sum_of_digits(1))
print(sum_of_digits(120516))
print(sum_of_digits(99999))
""""количество цифр натурального числа"""
def number_of_digits(n: int):
if n < 10:
return 1
else:
return 1 + number_of_digits(n / 10)
print('число цифр натурального числа')
print(number_of_digits(100))
print(number_of_digits(1))
print(number_of_digits(120516))
print(number_of_digits(99999))
""""цифровой корень натурального числа"""
def super_digit(n: int):
if n < 10:
return n
else:
return super_digit(sum_of_digits(n))
print('цифровой корень')
print(super_digit(100))
print(super_digit(1))
print(super_digit(120516))
print(super_digit(99999))
print(super_digit(999999999999))
""""арифметическая прогрессия"""
def arithmetic_progression(first_a: int, step: int, n: int):
if n == 1:
return first_a
else:
return step + arithmetic_progression(first_a, step, n-1)
print('арифметическая прогрессия')
print(arithmetic_progression(5, 5, 5))
print(arithmetic_progression(5, 2, 1))
print(arithmetic_progression(5, 10, 3))
""""сумма арифметической прогрессии"""
def sum_arithmetic_progression(first_a: int, step: int, n: int):
if n == 1:
return first_a
else:
return arithmetic_progression(first_a, step, n) + sum_arithmetic_progression(first_a, step, n-1)
print('сцмма арифметической прогрессии')
print(sum_arithmetic_progression(5, 5, 5))
print(sum_arithmetic_progression(5, 2, 1))
print(sum_arithmetic_progression(5, 10, 3))
""""геометрическая прогрессия"""
def geometric_progression(first_b: int, step: int, n: int):
if n == 1:
return first_b
else:
return step * geometric_progression(first_b, step, n-1)
print('геометрическая прогрессия')
print(geometric_progression(5, 2, 5))
print(geometric_progression(5, 2, 1))
print(geometric_progression(7, 2, 3))
""""сцмма геометрической прогрессии"""
def sum_geometric_progression(first_b: int, step: int, n: int):
if n == 1:
return first_b
else:
return geometric_progression(first_b, step, n) + sum_geometric_progression(first_b, step, n-1)
print('сцмма геометрической прогрессии')
print(sum_geometric_progression(5, 2, 5))
print(sum_geometric_progression(5, 2, 1))
print(sum_geometric_progression(7, 2, 3))
""""fibonachi"""
def my_fibo(n: int):
if n == 0:
return 0
elif n == 1:
return 1
else:
return my_fibo(n - 1) + my_fibo(n - 2)
print('fibonachi')
print(my_fibo(0))
print(my_fibo(1))
print(my_fibo(2))
print(my_fibo(3))
print(my_fibo(4))
print(my_fibo(5))
"max element of list"
def max_list(arr):
if arr.length == 1:
return arr[0]
else:
return max_list(arr.pop)
|
75aa4af10cac0093c7ee561771d136f89b659c95
|
QMRonline/Tools-I-Use
|
/PythonTools/qmark-show-pass.py
| 4,308 | 3.71875 | 4 |
# Import subprocess so we can use system commands
import subprocess
# Import the re module so that we can make use of regular expressions.
import re
# Python allows us to run system commands by using a function provided by the subprocess module
# (subprocess.run(<list of command line arguments goes here>, <specify the second argument if you want to capture the output>))
# The script is a parent process and creates a child process which runs the system command,
# and will only continue once the child process has completed.
# To save the contents that gets sent to the standard output stream (the terminal)
# we have to specify that we want to capture the output,
# so we specify the second argument as capture_output = True.
# This information gets stored in the stdout attribute.
# The information is stored in bytes and we need to decode it to Unicode
# before we use it as a String in Python.
print(r"""
****************************************************************
/$$$$$$ /$$
/$$__ $$ | $$
| $$ \ $$ /$$$$$$/$$$$ /$$$$$$ /$$$$$$ | $$ /$$
| $$ | $$| $$_ $$_ $$ |____ $$ /$$__ $$| $$ /$$/
| $$ | $$| $$ \ $$ \ $$ /$$$$$$$| $$ \__/| $$$$$$/
| $$/$$ $$| $$ | $$ | $$ /$$__ $$| $$ | $$_ $$
| $$$$$$/| $$ | $$ | $$| $$$$$$$| $$ | $$ \ $$
\____ $$$|__/ |__/ |__/ \_______/|__/ |__/ \__/
\__/
""")
print("*****************************************************************")
print("\n* Copyright of Ranjith, 2021 *")
print("\n* https://www.qmarkonline.com *")
print("\n* qucik shoutout *")
print("\n*****************************************************************\n")
command_output = subprocess.run(["netsh", "wlan", "show", "profiles"], capture_output = True).stdout.decode()
# We imported the re module so that we can make use of regular expressions.
# We want to find all the Wifi names which is always listed after "ALL User Profile :".
# In the regular expression we create a group of all characters until the return escape sequence (\r) appears.
profile_names = (re.findall("All User Profile : (.*)\r", command_output))
# We create an empty list outside of the loop where dictionaries with all the wifi
# username and passwords will be saved.
wifi_list = list()
# If we didn't find profile names we didn't have any wifi connections,
# so we only run the part to check for the details of the wifi and
# whether we can get their passwords in this part.
if len(profile_names) != 0:
for name in profile_names:
# Every wifi connection will need its own dictionary which will be appended to the wifi_list
wifi_profile = dict()
# We now run a more specific command to see the information about the specific wifi connection
# and if the Security key is not absent we can possibly get the password.
profile_info = subprocess.run(["netsh", "wlan", "show", "profile", name], capture_output = True).stdout.decode()
# We use a regular expression to only look for the absent cases so we can ignore them.
if re.search("Security key : Absent", profile_info):
continue
else:
# Assign the ssid of the wifi profile to the dictionary
wifi_profile["ssid"] = name
# These cases aren't absent and we should run them "key=clear" command part to get the password
profile_info_pass = subprocess.run(["netsh", "wlan", "show", "profile", name, "key=clear"], capture_output = True).stdout.decode()
# Again run the regular expressions to capture the group after the : which is the password
password = re.search("Key Content : (.*)\r", profile_info_pass)
# Check if we found a password in the regular expression. All wifi connections will not have passwords.
if password == None:
wifi_profile["password"] = None
else:
# We assign the grouping (Where the password is contained) we are interested to the password key in the dictionary.
wifi_profile["password"] = password[1]
# We append the wifi information to the wifi_list
wifi_list.append(wifi_profile)
for x in range(len(wifi_list)):
print(wifi_list[x])
|
2ffc683a793d402991525d16542e0441c7652758
|
AwesomeZaidi/Problem-Solving
|
/Python-Problems/medium/prime.py
| 840 | 4.125 | 4 |
def get_number(prompt):
'''Returns integer value for input. Prompt is displayed text'''
return int(input(prompt))
def is_prime(number):
'''Returns True for prime numbers, False otherwise'''
#Edge Cases
if number == 1:
prime = False
elif number == 2:
prime = True
#All other primes
else:
prime = True
for check_number in range(2, (number / 2)+1):
if number % check_number == 0:
prime = False
break
return prime
def print_prime(number):
prime = is_prime(number)
if prime:
descriptor = ""
else:
descriptor = "not "
print(number," is ", descriptor, "prime.", sep = "", end = "\n\n")
#never ending loop
while 1 == 1:
print_prime(get_number("Enter a number to check. Ctl-C to exit."))
|
24e41c4c5e7de5d2f2c20d592792f2f64fbf56fa
|
gloomysun/pythonLearning
|
/7-面向对象高级编程/4_定制类.py
| 828 | 3.671875 | 4 |
class Student():
def __init__(self, name):
self.name = name
def __str__(self):
return 'Student object[name:%s]' % self.name
__repr__ = __str__
s = Student('ly')
print(s)
print('===========================练习===================')
class Chain():
def __init__(self, path=''):
self.path = path
def __getattr__(self, item):
if item == 'users':
return lambda x: Chain('%s/%s/:%s' % (self.path, item, x))
return Chain('%s/%s' % (self.path, item))
def __str__(self):
return self.path
__repr__ = __str__
c = Chain()
print(c.user.list)
print(c.users('xiaoli').index)
class Student(object):
def __init__(self, name):
self.name = name
def __call__(self,item):
return Student()
s = Student('xx')
print(s('ddd'))
|
d58c8e67567ee391c91ebf416adfbed0d51d922c
|
xzlukeholo/range
|
/range.py
| 517 | 3.71875 | 4 |
import random
num = input('你想產生幾個隨機數:')
min1 = input('隨機數的最小值:')
max1 = input('隨機數的最大值:')
min1 = int(min1)
max1 =int(max1)
num = int(num)
for i in range(num):
r = random.randint(min1, max1)
print('第', i+1, '個隨機數:', r)
'你想計算多少加到多少的數值呢?'
start = input( '請輸入開始加總的數字:')
end = input( '請輸入結束加總的數字:')
start = int(start)
end = int(end)
sum = 0
for i in range(start, end+1):
sum += i
print(sum)
|
1e0c41fe3ffabc8e270bec6ec4090b96f00dc188
|
SoullessStone/mancalaMaster
|
/gamemodel.py
| 1,124 | 3.546875 | 4 |
class GameModel:
# Indices for fields
PLAYER1_1 = 0;
PLAYER1_2 = 1;
PLAYER1_3 = 2;
PLAYER1_4 = 3;
PLAYER1_5 = 4;
PLAYER1_6 = 5;
PLAYER1_BASE = 6;
PLAYER2_1 = 7;
PLAYER2_2 = 8;
PLAYER2_3 = 9;
PLAYER2_4 = 10;
PLAYER2_5 = 11;
PLAYER2_6 = 12;
PLAYER2_BASE = 13;
__gamefield=[]
__turn = 0;
def __init__(self):
print("New Gamemodel created");
self.resetGamefield();
def resetGamefield(self):
self.__gamefield=[4,4,4,4,4,4,
0,
4,4,4,4,4,4,
0];
def getTurn(self):
return self.__turn;
def switchTurn(self):
if self.__turn == 1:
self.__turn = 0;
else:
self.__turn = 1;
def getFieldValue(self,position):
return self.__gamefield[position];
def changeFieldValue(self,position,newValue):
self.__gamefield[position] = newValue;
def getGamefield(self):
return self.__gamefield;
def printGamefield(self):
print("gamefield=" + str(self.__gamefield));
|
fe4c4fcdd6b6e7e5ba57ad9f52deef86e9f1c81c
|
helen-research/NNETs_and_Deep_Learning
|
/Coursera/0-Notes/Python/1-Vectorization.py
| 683 | 3.796875 | 4 |
"""------------------------------------------------ Vectorization.py -----
| Purpose: First Vectorization approach, compares it to traditional
| methods.
|
| Developer:
| Carlos García - https://github.com/cxrlos
|
*------------------------------------------------------------------"""
import numpy as np
import time
a = np.random.rand(1000000)
b = np.random.rand(1000000)
tic = time.time()
c = np.dot(a,b)
toc = time.time()
print(c)
print("Vectorized time in ms " + str(1000*(toc-tic)))
c = 0
tic = time.time()
for i in range(1000000):
c += a[i]*b[i]
toc = time.time()
print(c)
print("For looped time in ms " + str(1000*(toc-tic)))
|
e71c4fe3adf79e6ab8af42bd97d3ac5e694b542b
|
chandrap08/leetcode
|
/maximum_product.py
| 582 | 3.734375 | 4 |
class Solution(object):
def maximumProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums = sorted(nums)
max_list = []
max_list.append(int(nums[-1]) * int(nums[-2]) * int(nums[-3]))
max_list.append(int(nums[0]) * int(nums[1]) * int(nums[2]))
max_list.append(int(nums[0]) * int(nums[1]) * int(nums[-1]))
max_list.append(int(nums[0]) * int(nums[-1]) * int(nums[-2]))
return max(max_list)
if __name__ == "__main__":
s = Solution()
print(s.maximumProduct([9,1,5,6,7,2]))
|
8e603d6f9037dfd392aaa1908c0129457dd2d4f7
|
vbraguimcanto/pesquisa-operacional-2
|
/buscaFibonacci.py
| 1,069 | 4.15625 | 4 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# CÁLCULO DA FUNÇÃO NO PONTO X
f = (lambda x: x**2 + 2*x)
# CÁLCULO DO NÚMERO DE ITERAÇÕES
w = (lambda a, b, e: (b-a)/e)
# LISTA DE FIBONACCI
def fibonacci(iteracoes):
fib = []
i = 0
while True:
if i == 0:
fib.append(1)
elif i == 1:
fib.append(1)
else:
fib.append(fib[len(fib) - 1] + fib[len(fib) - 2])
if(fib[len(fib) - 1]>iteracoes):
return fib
i+=1
def buscaFibonacci(a, b, fib, n):
print("=" * 100)
print("\nINÍCIO DA RESOLUÇÃO - BUSCA FIBONACCI\n")
print("=" * 100)
print("\n")
k = 0
while(k<(n-1)):
p = a + (fib[n - k - 2])/(fib[n - k])*(b - a)
q = a + ((fib[n - k - 1])/(fib[n - k]))*(b - a)
print(k,'|', a,'|', b,'|', p,'|', f(p),'|', q,'|', f(q),'|')
if f(p)>f(q):
a = p
else:
b = q
k+=1
def main():
a = float(input("Digite o valor de A: "))
b = float(input("Digite o valor de B: "))
precisao = float(input("Digite o valor da precisao: "))
iteracoes = w(a, b, precisao)
fib = fibonacci(iteracoes)
buscaFibonacci(a, b, fib, len(fib) - 1)
main()
|
9cd867ec71ff02fd0b4d67d2b9b67545f78a5774
|
audoreven/IntroToPython
|
/Exercises/count-keywords.py
| 803 | 3.734375 | 4 |
import keyword
# getting list of keywords
key_words = keyword.kwlist
# initializing dictionary
count = {}
# getting file name
source = input("Enter a filename: ")
while True:
try:
file = open(source, "r")
break
except FileNotFoundError:
print('File does not exist. Please try again. \n')
source = input("Enter a filename: ")
# reading the file
lines = file.readlines()
# counting occurrences of keywords
for l in lines:
words = l.split()
for word in words:
if word in key_words:
if word in count:
count[word] += 1
else:
count[word] = 1
# print results
print("Key Words \t Occurrences")
for kw in count.keys():
if count[kw] > 0:
print("{:12} {:<7}".format(kw, count[kw]))
|
2a8f87438f6c74b32e6ad8982da7ee94671f1665
|
MicahJank/Intro-Python-I
|
/src/14_cal.py
| 4,160 | 4.53125 | 5 |
"""
The Python standard library's 'calendar' module allows you to
render a calendar to your terminal.
https://docs.python.org/3.6/library/calendar.html
Write a program that accepts user input of the form
`14_cal.py [month] [year]`
and does the following:
- If the user doesn't specify any input, your program should
print the calendar for the current month. The 'datetime'
module may be helpful for this.
- If the user specifies one argument, assume they passed in a
month and render the calendar for that month of the current year.
- If the user specifies two arguments, assume they passed in
both the month and the year. Render the calendar for that
month and year.
- Otherwise, print a usage statement to the terminal indicating
the format that your program expects arguments to be given.
Then exit the program.
Note: the user should provide argument input (in the initial call to run the file) and not
prompted input. Also, the brackets around year are to denote that the argument is
optional, as this is a common convention in documentation.
This would mean that from the command line you would call `python3 14_cal.py 4 2015` to
print out a calendar for April in 2015, but if you omit either the year or both values,
it should use today’s date to get the month and year.
"""
import sys
import calendar
from datetime import datetime
# Things i dont know
# - How do i get values from the command line? - I need to be able to do this in order to grab the month and day the user inputs when running the start command
# print(sys.argv) will print me the command line input with everything put inside a list for me all i would need to do is remove the first item from the list and then i would be left with
# a list that just hast he 2 arguments i want - the month and year
#
# - How do i print a calendar using the calendar and/or datetime module i imported?
# print(datetime.today().month) - gives me the current month
# print(datetime.today().year) - gives me the current year
# print(calendar.month(2020, 5)) - prints out the calendar with the specified year and month
# First i need to get the arguments from the command line
# Next i need to use the calendar module to print out the calendar with that month and year the user specified
# if the user doesnt put in a month or year - i need to use the datetime module to find the systems current month and year and use those values instead when printing the calendar
# if the user passes only 1 argument - i need to assume that is the month and print the calendar using that month and the systems current year
inputs = sys.argv
def check_month_input(monthNum):
# there is a chance a user will put in a letter for the month instead of a number - in this case the casting will throw an error
# so it is better that i catch it here then have the program error out
try:
monthNum = int(monthNum)
except:
print("Invalid string type for month input - please make sure your month input is a number between 1 and 12")
return
else:
if monthNum < 1 or monthNum > 12:
print("Invalid month input - please make sure your month input is a number between 1 and 12")
return
else:
return monthNum
def check_year_input(yearNum):
try:
yearNum = int(yearNum)
except:
print("Invalid string type for year input - please only use numbers for year(in format YYYY).")
return
else:
if yearNum < 0:
print('Invalid year input - please dont use negative numbers for years.')
return
else:
return yearNum
if len(inputs) == 1:
month = datetime.today().month
year = datetime.today().year
print(calendar.month(year, month))
elif len(inputs) == 2:
month = check_month_input(inputs[1])
year = datetime.today().year
if type(month) == int:
print(calendar.month(year, month))
elif len(inputs) == 3:
month = check_month_input(inputs[1])
year = check_year_input(inputs[2])
if type(year) == int and type(month) == int:
print(calendar.month(year, month))
|
cd33aa67fa461655557e2cb565841da0051234c8
|
HigorSenna/python-study
|
/guppe/leitura_e_escrita_de_arquivos/sistema_de_arquivos.py
| 1,196 | 3.53125 | 4 |
"""
Sistema de Arquivos e Navegação
Para fazer uso de manipulação de arquivos do sistema operacional, precisamos usar o modulo "os"
"""
import os
# Pega o diretorio atual (current work directory) -> caminho absoluto
print(os.getcwd())
# Mudar o diretório
os.chdir("../")
print(os.getcwd())
# Podemos checar se um diretorio é absoluto ou relativo
print(os.path.isabs('/home/geek/')) # True
print(os.path.isabs('/home/geek/')) # True
print(os.path.isabs('home/geek/')) # False
# OBS PARA WINDOWS:
print(os.path.isabs('C:\\Users'))
# Identificando o sistema operacional
print(os.name) # posix(Linux e Mac), nt (Windows)
# Identificando mais detalhes do sistema operacional
print(os.uname()) # No windows nao temos essa funcao
# Join para diretorios
print(os.getcwd())
res = os.path.join(os.getcwd(), 'OutroDir', 'OutroOutroDir')
print(res)
# Listando arquivos e diretorios
print(os.listdir())
print(os.listdir('/etc'))
# Listando arquivos e diretorios com mais detalhes
scanner = os.scandir('/etc')
arquivos = list(scanner)
print(arquivos[0].name)
print(dir(arquivos[0]))
# OBS: Após utilizar o scandir(), devemos fechar
scanner.close()
import sys
print(sys.platform)
|
5315567d08092c7a79631a0f3cecee4d3c5d1861
|
silvioedu/TechSeries-Daily-Interview
|
/day21/Solution.py
| 228 | 3.765625 | 4 |
def num_ways(n, m):
if m == 1 or n == 1 :
return 1
return (num_ways(m - 1, n) +
num_ways(m, n - 1))
if __name__ == '__main__' :
print(num_ways(2, 2))
# 2
print(num_ways(5, 5))
# 70
|
20cf5ea0fcce629803a1b3945d1008a885a95dc6
|
vishrutkmr7/DailyPracticeProblemsDIP
|
/2022/12 December/db12062022.py
| 780 | 4.1875 | 4 |
"""
Given a sorted array of integers, nums, and a target, return the index of the target within nums.
If it does not exist, return the index of where target should be inserted.
Ex: Given the following nums and target...
nums = [1, 5, 8, 12], target = 12, return 3.
Ex: Given the following nums and target...
nums = [3, 4, 7, 12, 29], target = 5, return 2.
"""
class Solution:
def searchInsert(self, nums: list[int], target: int) -> int:
if target not in nums:
nums.append(target)
nums.sort()
return nums.index(target)
if __name__ == "__main__":
nums = [1, 5, 8, 12]
target = 12
print(Solution().searchInsert(nums, target))
nums = [3, 4, 7, 12, 29]
target = 5
print(Solution().searchInsert(nums, target))
|
417e5d1633b28c942b66de94a63bbc33c156b9b9
|
deltonmyalil/dataSciencePrerequisiteStack
|
/src/2_pandasTrials/10_joins.py
| 549 | 3.609375 | 4 |
import pandas as pd
# This uses table1.csv and table2.csv
t1 = pd.read_csv("table1.csv")
t2 = pd.read_csv("table2.csv")
print("Printing both tables separately")
print("Table 1")
print(t1)
print()
print("Table 2")
print(t2)
print()
# Let us join the two tables with respect to user_id attribute. Like natural join.
m = pd.merge(t1, t2, on="user_id") # join operation of t1 and t2 on the attribute user_id,
# you can also join on more than one attribute
# you can also do t1.merge(t2, on="user_id")
print()
print("Printing joined table")
print(m)
|
2fb9851a0aa96fcfdf96f4f1cef717d584a6fc21
|
kdogyun/algorithm_study
|
/1920.수찾기.py
| 1,018 | 3.625 | 4 |
import sys
input = sys.stdin.readline
class binary():
def __init__(self):
self.array = []
def search(self, start, end, num):
mid = int((start + end) / 2)
if start > len(self.array) or end < 0 or start > end:
return False, start
if self.array[mid] == num:
return True, mid
elif start == end:
if self.array[mid] > num:
return False, start
else:
return False, start + 1
elif self.array[mid] > num:
return self.search(start, mid-1, num)
else:
return self.search(mid+1, end, num)
def insert(self, num):
_, pos = self.search(0, len(self.array)-1, num)
self.array.insert(pos, num)
bi = binary()
n = int(input())
for i in list(input().rstrip().split()):
bi.insert(int(i))
_ = input()
for i in list(input().rstrip().split()):
re, pos = bi.search(0, n-1, int(i))
if re:
print(1)
else:
print(0)
|
ccb88188ae1505cc7261bd63a9d7d2b0f573b4e7
|
Vestenar/PythonProjects
|
/venv/02_Codesignal/02_The Core/030_appleBoxes.py
| 886 | 3.796875 | 4 |
def appleBoxes(k):
# diff = 0
# for i in range(1, k+1):
# if i % 2 == 0:
# diff += i * i
# else: diff -= i * i
return sum((i*i) * (-1)**i for i in range(1, k+1))
print(appleBoxes(36))
'''
You have k apple boxes full of apples.
Each square box of size m contains m × m apples.
You just noticed two interesting properties about the boxes:
The smallest box is size 1, the next one is size 2,..., all the way up to size k.
Boxes that have an odd size contain only yellow apples. Boxes that have an even size contain only red apples.
Your task is to calculate the difference between the number of red apples and the number of yellow apples.
Example
For k = 5, the output should be
appleBoxes(k) = -15.
There are 1 + 3 * 3 + 5 * 5 = 35 yellow apples
and 2 * 2 + 4 * 4 = 20 red apples,
making the answer 20 - 35 = -15.
'''
|
f773a1bed7392592f256568c51791d24430d3c54
|
UdayQxf2/tsqa-basic
|
/employee-salary-calculation/01_employee_salary_calculation.py
| 1,245 | 4.34375 | 4 |
"""
We will use this script to teach Python to absolute beginners
The script is an example of salary calculation implemented in Python
The salary calculator:
Net_Income = Gross_Income - Taxable_Due
Taxable_Due = Federal_tax + Social_security + Medicare_tax
Taxable_Income = Gross_Income -120,00
Social_security = 6.2% of Gross_Income
Medicare_Tax = 1.45 % of Gross_Income
"""
# Enter the gross income
print("Enter the gross income")
# raw_input gets the input from the keyboard through user
gross_income = float(raw_input())
# Enter the federal tax
print("Enter the federal_tax")
# Getting the federal tax from the user
fedral_tax = float(raw_input())
# Taxable income will be reduced from gross income.This is the fixed dedutable income
taxable_deduction = 12000
# 6.2% of gross income is social security
social_security = gross_income *(6.2/100)
print("The employee social_security is",social_security)
# 1.45% of gross income is medicare tax
medicare_tax = gross_income *(1.45/100)
print("The employee medicare tax is",medicare_tax)
# Taxable due
taxable_due = fedral_tax + social_security + medicare_tax
# Net income
net_income = gross_income - taxable_due
print("The employee take home salary is",net_income)
|
336840a0a10dd44ceb9f52e8c8fea64d52b3c1a0
|
Mahalinoro/python-program
|
/Omondi/Omondi v2/moto_class_file.py
| 3,463 | 4.03125 | 4 |
# This is the file containing the moto class
# importing the Vehicle class
# importing numpy to perform mathematic calculation
from vehicle_file import Vehicle
import numpy as np
# This is the moto class
class Moto(Vehicle):
# This is the method __init__ that will create instances automatically
def __init__(self, model, year_released, year_acquired, rent_time, plate_number, revenue, helmet_number, miles,
gallons, carbon, carbon_footprint):
super().__init__(model, year_released, year_acquired, rent_time, plate_number, revenue)
self.helmet_number = helmet_number
self.miles = miles
self.gallons = gallons
self.carbon = carbon
self.carbon_footprint = carbon_footprint
def info(self):
# This method will display the information about model and plate number for the moto
return self.model + " - " + "Plate Number: " + self.plate_number
def info_details(self):
# This method will display detailed information about the moto
return "Moto Model: " + self.model + "\n" + "Revenue: " + str(
self.revenue) + "\n" + "Yearly Miles: " + str(
self.miles) + "\n" + "Gallons consumed: " + str(self.gallons) + "\n" + \
"Carbon emmited: " + str(self.carbon) \
+ "\n" + "Helmets Available: " + str(self.helmet_number) + "\n"
def update_helmet_number(self):
# This method will ask the user the number of available helmet and update the information to the instance
number_helmet = int(input("Insert the number of helmet available: "))
self.helmet_number = number_helmet + self.helmet_number
return self.helmet_number
def update_miles(self):
# This method will ask the user the miles made yearly and will update the information
self.miles = int(input("Insert the miles made yearly [number]: "))
return self.miles
def update_gallons(self):
# This method will ask the user the gallons consumed
self.gallons = int(input("Insert the gallons volume consumed [number]: "))
return self.gallons
def update_carbon(self):
# This method will ask the user the carbon emitted
self.carbon = int(input("Insert the grams of CO2 emitted [number]: "))
return self.carbon
def get_carbon_footprint(self):
# This method will calculate the carbon footprint of a moto
# First, getting the number of year released
# Then, the average mile made yearly
# After, the gallons per mile made
# Last, the carbon per gallon made
# With the formula of carbon footprint, we get the value of the carbon footprint
number_year_released = 2019 - self.year_released
average_mile = np.mean(self.miles)
gallons_mile = self.gallons / self.miles
carbon_gallon = self.carbon / self.gallons
self.carbon_footprint = round(number_year_released * (10000 * average_mile) *
(2 * gallons_mile) * (9 * carbon_gallon))
return self.carbon_footprint
def report(self):
# This method will give the user the report about the revenue, number of times the moto has been rented and
# the carbon footprint
return "Revenue: " + str(self.revenue) + "\n" + "Number of rented times: " + str(self.rent_time) + \
"\n" + "Carbon Footprint: " + str(self.carbon_footprint)
|
23ed044e85ac279b7dc3f127adab1318a227882e
|
Connor-Mooney/Clifford-T-Synthesis-Project
|
/Ops/operator.py
| 2,327 | 3.53125 | 4 |
import numpy as np
class Operator:
"""This class represents a matrix in SO6(Z[1/sqrt(2)]), storing the name of the operator, i.e. a string of T operators, its actual matrix, its residue,
and its column-permutation-invariant class"""
def __init__(self, LDE, mat,name):
self.matrix = mat
self.LDE = LDE
self.name = name
self.residue = self.gen_res()
self.permclass = self.column_perm_class()
def gen_res(self):
"""Generates the residue of this operator"""
return [self.matrix[0] % 2, self.matrix[1] % 2]
def transpose(self, mat):
"""returns the transpose of a matrix"""
vOut = []
for i in range(len(mat[0])):
vOut.append([mat[j][i] for j in range(len(mat))])
return vOut
def display(self):
"""Displays the matrix as a string"""
s = ""
s + = "1/√2^{}".format(self.LDE)
for i in range(6):
s += "["
for j in range(6):
s + = "{} + {}√2".format(self.mat[0][i,j], self.mat[1][i,j])
s += "] \n"
return s
def column_perm_class(self):
"""Generates the permutation class of this operator"""
permclass = [[None, None, None, None, None, None], [None, None, None, None, None, None], \
[None, None, None, None, None, None], [None, None, None, None, None, None],\
[None, None, None, None, None, None], [None, None, None, None, None, None]]
for i in range(self.matrix[0].shape[0]):
for j in range(self.matrix[0].shape[1]):
permclass[i][j] = (self.matrix[0][i,j], self.matrix[1][i,j])
return [self.LDE, self.transpose(sorted(self.transpose(permclass)))]
def dot(self, op2):
"""multiplies this operator with another"""
LDENew = self.LDE + op2.LDE
mat0 = np.matmul(self.matrix[0],op2.matrix[0]) + 2*np.matmul(self.matrix[1],op2.matrix[1])
mat1 = np.matmul(self.matrix[0],op2.matrix[1]) + np.matmul(self.matrix[1],op2.matrix[0])
newmat = [mat0, mat1]
newname = self.name + " " + op2.name
while np.all(newmat[0] % 2 == 0):
# NEED TO REDUCE THIS DOWN TO MOST SIMPLIFIED MATRIX
mat0 = np.copy(newmat[1])
mat1 = np.copy(newmat[0])/2
newmat = [mat0, mat1]
LDENew = LDENew - 1
return Operator(LDENew, newmat, newname)
|
fbe88e24f6adb88c82fef8e9d0c52baf3edafc37
|
franchescaleung/ICS31
|
/restaurants6.py
| 7,109 | 4.3125 | 4 |
#RESTAURANT COLLECTION PROGRAM
# ICS 31, UCI, Winter 2018
# Implement Restaurant as a namedtuple, collection as a list
##### MAIN PROGRAM (CONTROLLER)
from collections import namedtuple
Dish = namedtuple ("Dish", "name price calories") #using to test
#d1 = Dish('noodles', 4.00)
def restaurants(): # nothing -> interaction
""" Main program
"""
print("Welcome to the restaurants program!")
our_rests = collection_new()
our_rests = handle_commands(our_rests)
print("\nThank you. Good-bye.")
return
MENU = """
Restaurant Collection Program --- Choose one
n: Add a new restaurant to the collection
r: Remove a restaurant from the collection
s: Search the collection for selected restaurants
p: Print all the restaurants
q: Quit
e: Remove (erase) all the restaurants from the collection
c: Change prices for the dishes served
m: Search for specific cuisine
w: Search for specific word or phrase
"""
def dish_change_price(d: "list of dishes", b: float) -> "list of dishes":
dishlist = []
for i in d:
i = i._replace(price = i.price * (1 + (b/100)))
dishlist.append(i)
return dishlist
def handle_commands(diners: list) -> list:
""" Display menu, accept and process commands.
"""
done = False
while not done:
response = input(MENU)
if response=="q":
done = True
return diners
elif response=='n':
r = restaurant_get_info()
diners = collection_add(diners, r)
elif response=='r':
n = input("Please enter the name of the restaurant to remove: ")
diners = collection_remove_by_name(diners, n)
elif response=='p':
print(collection_str(diners))
elif response=='s':
n = input("Please enter the name of the restaurant to search for: ")
for r in collection_search_by_name(diners, n):
print(restaurant_str(r))
elif response == 'e':
diners = []
elif response == 'c':
percent = float(input("How big of a change?"))
diners = collection_change_prices(diners, percent)
elif response == 'm':
c = input("Please enter cuisine: ")
d = collection_search_by_cuisine(diners, c)
for rest in d:
print(restaurant_str(rest))
elif response == 'w':
g = input("Please enter a word or phrase: ")
e = collection_search_by_word(diners, g)
print(diners)
for item in e:
print(restaurant_str(item))
else:
invalid_command(response)
def invalid_command(response): # string -> interaction
""" Print message for invalid menu command.
"""
print("Sorry; '" + response + "' isn't a valid command. Please try again.")
##### Restaurant
from collections import namedtuple
Restaurant = namedtuple('Restaurant', 'name cuisine phone menu')
# Constructor: r1 = Restaurant('Taillevent', 'French', '01-11-22-33-44', 'Escargots', 23.50)
def restaurant_str(self: Restaurant) -> str:
return (
"Name: " + self.name + "\n" +
"Cuisine: " + self.cuisine + "\n" +
"Phone: " + self.phone + "\n" +
"Menu: " + menu_display(self.menu) + "\n" +
"Average Price: $" + str(avg_price(self.menu)) + "\n" +
"Average Calories: " + str(avg_calories(self.menu)) + "\n\n")
def restaurant_get_info() -> Restaurant:
""" Prompt user for fields of Restaurant; create and return.
"""
a = input("Please enter the restaurant's name: ")
b = input("Please enter the kind of food served: ")
c = input("Please enter the phone number: ")
return Restaurant(a, b, c, menu_enter())
def restaurant_change_price(a: Restaurant, b: float) -> "list of restaurants":
'''change restaurant price'''
new = []
for i in range(len(a.menu)):
new.append(dish_change_price(a.menu[i], b))
return new
#### COLLECTION
# A collection is a list of restaurants
def collection_new() -> list:
''' Return a new, empty collection
'''
return [ ]
def collection_str(diner_collection: list) -> str:
''' Return a string representing the collection
'''
s = ""
for r in diner_collection:
s = s + restaurant_str(r)
return s;
def collection_search_by_name(diner_list: list, diner_name: str) -> list:
""" Return list of Restaurants in input list whose name matches input string.
"""
result = [ ]
for r in diner_list:
if r.name == diner_name:
result.append(r)
return result
def collection_add(diner_list: list, diner: Restaurant) -> list:
""" Return list of Restaurants with input Restaurant added at end.
"""
diner_list.append(diner)
return diner_list
def collection_remove_by_name(diners: list, diner_name: str) -> list:
""" Given name, remove all Restaurants with that name from collection.
"""
result = [ ]
for r in diners:
if r.name != diner_name:
result.append(r)
return result
def collection_change_prices(diners: list, n: float) -> list:
'''changes price of whole collection'''
newprices = []
for i in diners:
i = i._replace(price = i.price * (1 + (n/100)))
newprices.append(i)
return newprices
def collection_search_by_cuisine(m: list, cuisine: str) -> list:
'''returns list of restaurant that matches cuisine'''
match = []
for rest in m:
if rest.cuisine == cuisine:
match.append(rest)
return match
def collection_search_by_word(m: list, word: str) -> list:
woo = []
for rest in m:
for i in rest.menu:
if word in i.name:
woo.append(rest)
return woo
###DISHES
def dish_str(a: Dish) -> str:
'''return string of name, price, and calories'''
return a.name + ' ($' + str(a.price) + '): '+ str(a.calories) + ' cal'
def dish_get_info() -> Dish:
""" Prompt user for fields of Dish; create and return.
"""
return Dish(
input("Please enter the dish's name: "),
float(input("Please enter the price of the dish: ")),
int(input("Please enter the amount of calories:")))
###MENUS
def menu_enter() -> Dish:
'''asks user if he or she wants to make new dish'''
menu = []
working = True
while True:
user = input("Do you want to create a dish?")
if user == 'yes':
new_dish = dish_get_info()
menu.append(new_dish)
elif user == 'no':
return menu
def avg_price(m: list) -> float:
'''returns avg price of dishes in menu'''
p = []
for i in m:
p.append(i.price)
return sum(p)/len(p)
def avg_calories(m:list) -> int:
p = []
for i in m:
p.append(i.calories)
return sum(p)/len(p)
def menu_display(diners: list) -> str:
'''returns menu'''
m = ""
for i in diners:
m += dish_str(i) + "\n"
return m
restaurants()
|
940d0f9da2f3f1b9f5601ef88e23fcfca49d1f3d
|
dr-dos-ok/Code_Jam_Webscraper
|
/solutions_python/Problem_145/518.py
| 768 | 3.703125 | 4 |
#!/usr/bin/python
import fractions
num_tests = int(raw_input())
def solve(p, q):
gcd = fractions.gcd(p, q)
if gcd != 0:
p /= gcd
q /= gcd
if p == 1:
return power(q)
if 2*p < q:
return solve(p-1, q/2) + 1
else:
return 1
def power(num):
pow = 0
while num > 1:
num /= 2
pow += 1
return pow
if __name__ == '__main__':
for test_num in range(num_tests):
p, q = raw_input().strip().split('/')
p = int(p)
q = int(q)
result = 'impossible'
gcd = fractions.gcd(p, q)
if gcd != 0:
p /= gcd
q /= gcd
if bin(q)[2:].count('1') == 1:
result = solve(p, q)
if result > 40:
result = 'impossible'
print "Case #%d: %s" % (test_num+1, str(result))
|
0c0d82877422407c6212ee0d5681b9cfe888343c
|
kussy-tessy/atcoder
|
/abc191/d/main.py
| 1,361 | 4.0625 | 4 |
#!/usr/bin/env python3
# 努力した記念提出
import math
X, Y, R = map(float,(input().split()))
def is_in_circle(x, y):
return (x-X)**2 + (y-Y)**2 <= R**2
# https://twitter.com/meguru_comp/status/697008509376835584/photo/3
def count_lat_p(k):
count = 0
# left(円に初めて入る点)
ok = math.floor(X - R)
ng = math.floor(X) + 1
print(k, 'l', ok, ng)
while abs(ok - ng) > 1:
mid = math.floor((ok + ng) / 2)
if is_in_circle(mid, k):
ok = mid
else:
ng = mid
if not is_in_circle(mid, k):
pts = 0
else:
pts = math.floor(X) + 1 - mid
print(k, 'left', 'mid', mid)
print(k, 'left', 'pts', pts)
count += pts
# right(円から初めて出る点)
ok = math.ceil(X)
ng = math.ceil(X + R) + 1
print(k, 'r', ok, ng)
while abs(ok - ng) > 1:
mid = math.floor((ok + ng) / 2)
if not is_in_circle(mid, k):
ok = mid
else:
ng = mid
if not is_in_circle(math.ceil(X), k):
pts = 0
else:
pts = mid - math.ceil(X)
print(k, 'right', 'mid', mid)
print(k, 'right', 'pts', pts)
count += pts
return count
ans = 0
for k in range(math.floor(X-R), math.ceil(Y+R)):
ans += count_lat_p(k)
print(ans)
|
3cd69b04bdb1507352e919350948402641c88ee4
|
SayanNL1996/Cab_Booking_System
|
/schema.py
| 4,332 | 3.546875 | 4 |
""" Create all necessary tables required in the project."""
class Schema:
def __init__(self, connection):
self.conn = connection
def setup_admin(self):
"""
Create table employees & users if not exists and insert one row with given pre-details of admin.
:return: True/False
"""
try:
c = self.conn.cursor()
c.execute("SELECT count(*) FROM information_schema.tables WHERE table_name ='employees';")
# if the count is not 1, then create table employees, users and add 1st Admin
if c.fetchone()[0] != 1:
c.execute('''CREATE TABLE employees
(ID INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
FNAME VARCHAR(20) NOT NULL,
LNAME VARCHAR(20) NOT NULL,
EMAIL VARCHAR(50) UNIQUE NOT NULL,
PHONE VARCHAR(10) NOT NULL);''')
c.execute("INSERT INTO employees(ID, FNAME, LNAME, EMAIL, PHONE) \
VALUES(1211, 'sayan', 'mandal', '[email protected]', '7001621385 ')")
c.execute('''CREATE TABLE users
(EMAIL VARCHAR(50) UNIQUE NOT NULL,
PASSWORD VARCHAR(16) NOT NULL,
ROLE INTEGER NOT NULL,
FOREIGN KEY(EMAIL) REFERENCES employees(EMAIL));''')
c.execute("INSERT INTO users(EMAIL, PASSWORD, ROLE) \
VALUES('[email protected]', 'Sayan@1', 11)")
self.conn.commit()
return True
except Exception as e:
print(type(e), ": ", e)
return False
def create_tables(self):
"""
Create tables only if they don't exist in database.
:return: True/False
"""
try:
c = self.conn.cursor()
# create table cabs if not exist
c.execute('''CREATE TABLE if not exists cabs
(ID INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
CAB_NO VARCHAR(15) UNIQUE NOT NULL,
RIDER_NAME VARCHAR(50) NOT NULL,
RIDER_NO VARCHAR(10) NOT NULL,
CAPACITY INTEGER NOT NULL);''')
c.execute("ALTER TABLE cabs AUTO_INCREMENT = 111;")
# create table routes if not exist
c.execute('''CREATE TABLE if not exists routes
(ID INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
CAB_ID INTEGER NOT NULL REFERENCES cabs(ID),
SOURCE VARCHAR(20) NOT NULL,
DESTINATION VARCHAR(20) NOT NULL,
TIMING TIME NOT NULL,
SEATS_AVAILABLE INTEGER NOT NULL);''')
c.execute("ALTER TABLE routes AUTO_INCREMENT = 1510;")
# create table bookings if not exist
c.execute('''CREATE TABLE if not exists bookings
(ID INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
EMP_ID INTEGER NOT NULL REFERENCES employees(ID),
ROUTE_ID INTEGER NOT NULL REFERENCES routes(ID),
DATE DATE NOT NULL,
TIME TIME NOT NULL,
OCCUPANCY INTEGER NOT NULL,
STATUS INTEGER NOT NULL);''')
c.execute("ALTER TABLE bookings AUTO_INCREMENT = 1021;")
self.conn.commit()
return True
except Exception as e:
print(type(e), ": ", e)
return False
|
075025805c30115c4518dbdcbe8fcf1198a5d0a3
|
Mamatemenrs/Programming-for-Everyone
|
/Assignment4.6.py
| 569 | 3.90625 | 4 |
'''def computepay(h,r):
if hrs > 40:
ot = hrs - 40
ot_rate = rate * 1.5
ot_pay = ot_rate * ot
full_pay = pay + ot_pay
else:
print hrs *rate
return full_pay'''
def computepay(h,r):
if hrs > 40:
pay = 40 * rate
ot = hrs -40
ot_rate = rate * 1.5
full_pay = ot_rate *ot + pay
else:
full_pay = hrs * rate
return full_pay
hrs = float(raw_input("Enter Hours:"))
rate = float(raw_input("Enter Pay Rate:"))
#pay = hrs * rate
print hrs,rate
p = computepay(5,3)
print p
|
dfe50cafce4caecf017c9bf35bda237a3196dd16
|
morgante/learn-a-little
|
/3_sum/index.py
| 777 | 4 | 4 |
'''
Given a list of numbers and a target N,
return a combination of 3 numbers from the list which sums to N.
This solution is O(n^2)
O(n log n + n*n) = O(n*(log n + n)) = O(n^2)
'''
def get_combination_sum(numbers, n):
numbers = sorted(numbers)
for i, num1 in enumerate(numbers[0:-2]):
left_j = i + 1
right_k = len(numbers) - 1
while left_j < right_k:
num2 = numbers[left_j]
num3 = numbers[right_k]
my_sum = num1 + num2 + num3
if my_sum == n:
return (num1, num2, num3)
elif my_sum >= n:
right_k -= 1
else:
left_j += 1
return None
print('solution', get_combination_sum([2, 5, 9, 11, 17, 3, 9, 88], 19), '5, 11, 3')
|
52581a14a9bb8f5574020a185de2f1ea50fe075b
|
MeinAccount/ea-snake
|
/game/direction.py
| 2,630 | 3.734375 | 4 |
import math
from typing import Tuple, List
GRID_WIDTH = 50
GRID_HEIGHT = 50
class Directions:
RIGHT = 0
UP = 1
LEFT = 2
DOWN = 3
@staticmethod
def to_left(direction: int) -> int:
return (direction + 1) % 4
@staticmethod
def to_right(direction: int) -> int:
return (direction - 1) % 4
@staticmethod
def apply(direction: int, pos: Tuple[int, int]):
(x, y) = pos
if direction == Directions.RIGHT:
return x + 1, y
if direction == Directions.UP:
return x, y - 1
if direction == Directions.LEFT:
return x - 1, y
if direction == Directions.DOWN:
return x, y + 1
class Board:
@staticmethod
def neighbours_free(direction: int, positions: List[Tuple[int, int]]) -> List[bool]:
"""
:param direction: direction to check
:param positions: list of positions - with list head assumed as head
:return: list of three bools: [left is free, forward is free, right is free]
"""
free = [True, True, True]
neighbours = [Directions.apply(Directions.to_left(direction), positions[0]),
Directions.apply(direction, positions[0]),
Directions.apply(Directions.to_right(direction), positions[0])]
# check if neighbour is one of the positions
for pos in positions:
for i in range(0, 3):
if pos == neighbours[i]:
free[i] = False
# handle edges
for i in range(0, 3):
if neighbours[i][0] == -1 or neighbours[i][0] == GRID_WIDTH or \
neighbours[i][1] == -1 or neighbours[i][1] == GRID_HEIGHT:
free[i] = False
return free
@staticmethod
def compute_normalized_angle(direction: int, snake: Tuple[int, int], apple: Tuple[int, int]) -> float:
""" Computes the angle to the apple
The angle is relative to the current movement direction and normalized to [-1, 1]
"""
# compute atan2 with apple rotated around snake for down direction
if direction == Directions.RIGHT:
angle = math.atan2(snake[1] - apple[1], apple[0] - snake[0])
elif direction == Directions.UP:
angle = math.atan2(snake[0] - apple[0], snake[1] - apple[1])
elif direction == Directions.LEFT:
angle = math.atan2(apple[1] - snake[1], snake[0] - apple[0])
elif direction == Directions.DOWN:
angle = math.atan2(apple[0] - snake[0], apple[1] - snake[1])
return angle / math.pi
|
6c1319d015f95a7a17d0d8d30feaf7db00243357
|
DukhDmytro/py_point
|
/point.py
| 1,254 | 4.375 | 4 |
"""sqrt func used in calculations"""
from math import sqrt
class Point:
"""Class representing point in 2D space"""
def __init__(self, x_coord: int, y_coord: int):
self.x_coord = x_coord
self.y_coord = y_coord
def find_distance(self, other_point):
"""
Calculate distance between two points in 2D space
:param other_point:
:return: distance
"""
return sqrt((other_point.x_coord - self.x_coord) ** 2 +
(other_point.y_coord - self.y_coord) ** 2)
def __repr__(self):
"""
:return: the Point object representation
"""
return f"Point({self.x_coord}, {self.y_coord})"
def __str__(self):
"""
:return:the string representation of the Point object
"""
return f"({self.x_coord}, {self.y_coord})"
def __hash__(self):
"""
:return: return hash for Point object
"""
return hash((self.x_coord, self.y_coord))
def __eq__(self, other_point):
"""
Check equality of two points in 2D space
:param other_point:
:return: boolean
"""
return self.x_coord == other_point.x_coord and self.y_coord == other_point.y_coord
|
1de8ebca56bb0e75e55a70634c62d5aef7311693
|
vaishnavav99/funproject
|
/weather.py
| 662 | 3.578125 | 4 |
import json
from urllib.request import urlopen
x="n"
while(x!='y'and x!='Y'):
city = input("City/State \t")
print("")
key = "<your api key>"
url = "http://api.openweathermap.org/"
url = url+"data/2.5/weather?appid="+key+f"&q={city}&units=metric"
response = urlopen(url)
decoded = response.read().decode('utf-8')
data = json.loads(decoded)
for key,value in data.items():
print(key," ",value)
t=data['main']
print("\n Temperature:",t['temp']," C","\n Pressure",t['pressure'],"\n Humidity:",t['humidity'],)
print(t['temp_min'],t['temp_max'])
x=input("Do u want to exit y/n ?\t")
|
d1d4f91fe596a71e6ecea00ee7daeaffc9fc31b7
|
ibourzgui/week3_work
|
/pyPoll/main_IB.py
| 1,810 | 3.53125 | 4 |
import os
import csv
total_votes = 0
candidates_names = ''
Dictionary= {}
vote_count = 0
vote_count_cand=0
election_file = os.path.join("","Resources","election_data.csv")
highest_votes = 0
winner = ''
with open(election_file, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
csv_header = next(csvreader)
for row in csvreader:
total_votes += 1
candidates_names = row[2]
if not candidates_names in Dictionary:
Dictionary.update({candidates_names : 1})
else:
Dictionary[candidates_names] += 1
print("Election Results")
print("--------------------------------------")
print(" total votes : " + str(total_votes))
print("--------------------------------------")
votestring="Individual Votes\n"
for key,v in Dictionary.items():
votestring+=((( key) + " : " + "{0:.0f}%".format ((v/total_votes)*100)) + " (" + str(v) + ")" + "\n" )
print((( key) + " : " + "{0:.0f}%".format ((v/total_votes)*100)) + " (" + str(v) + ")" )
if v > highest_votes:
highest_votes = v
winner = key
print("--------------------------------------")
print("winner : " + winner)
output_path = os.path.join("", "election_results.txt")
with open(output_path, 'w', newline='') as out:
out = open(output_path,"w")
out.write("Election Results\n")
out.write("--------------------------------------\n")
out.write(" total votes : " + str(total_votes) + "\n")
out.write(votestring)
out.write("--------------------------------------\n")
out.write("--------------------------------------\n")
out.write("winner : " + winner + "\n")
out.close()
print("Done writing to result file: " + output_path)
|
35622c96459eebf0b242d7b51d9dc88fc5f197a1
|
msoucy/fuf
|
/fuf/dispatchdict.py
| 2,588 | 3.75 | 4 |
#!/usr/bin/env python
"""
Dispatching Dictionary
Matt Soucy
This class provides a way to forward dictionary lookups to a second dictionary
transparently, such that users cannot tell which dictionary the item is in.
This is useful in situations where a form of "inheritance" is needed,
to provide a convenient interface for situations where a core dictionary needs
to be updated, but other "derived" dictionaries need to look up items from it.
"""
from itertools import chain
class DispatchDict(dict):
'''
Behaves as a dictionary, but looks up nonexistant keys in another place
'''
def __init__(self, *args, **kwargs):
'''
Construct the internal dictionary like a builtin dictionary
Specify the `dispatch` keyword argument to provide an alias
'''
super(DispatchDict, self).__init__()
self._alias = kwargs.pop("dispatch", None)
self._dict = dict(*args, **kwargs)
def dispatch(self, alias=None):
''' Choose a new item to lookup items in '''
self._alias = alias
def get_dispatch(self):
''' Get the item being dispatched to '''
return self._alias
def __getitem__(self, key):
'''
Get the item with the given key
Uses the builtin dictionary, or the aliased one if possible
'''
if key in self._dict:
return self._dict[key]
elif self._alias:
return self._alias[key]
else:
raise KeyError(key)
def __setitem__(self, key, value):
'''
Set an item to a particular value
Always assigns to the builtin, never the alias
'''
self._dict[key] = value
return value
def __delitem__(self, key):
'''
Remove an item from the dictionary
May remove from the aliased dictionary
'''
if key in self._dict:
del self._dict[key]
elif self._alias:
del self._alias[key]
else:
raise KeyError(key)
def keys(self):
''' List the keys in the dictionary and dispatch object '''
return set(self._dict.keys()) | set((self._alias or {}).keys())
def __iter__(self):
''' Iterates over the builtin dictionary, then the dispatch object '''
if self._alias:
return chain(self._dict, self._alias)
else:
return iter(self._dict)
def __contains__(self, key):
''' Test to see if the key exists in the dispatch object '''
return key in self._dict or (self._alias and key in self._alias)
|
99e02fa63b997cb3156d5427da3833584a99d3c3
|
stogaja/python-by-mosh
|
/12logicalOperators.py
| 534 | 4.15625 | 4 |
# logical and operator
has_high_income = True
has_good_credit = True
if has_high_income and has_good_credit:
print('Eligible for loan.')
# logical or operator
high_income = False
good_credit = True
if high_income or good_credit:
print('Eligible for a loan.')
# logical NOT operator
is_good_credit = True
criminal_record = False
if is_good_credit and not criminal_record:
print('Eligible for a loan.')
# AND both conditions must be true
# OR at least one condition is true
# NOT reverses any boolean value given
|
fcc1ea0874b8f5b66f42214be26261314af0ad91
|
tsunoda416/KHDKLAB-NLP
|
/100pon-knock/c1/02.py
| 562 | 4.21875 | 4 |
# -*- coding: utf-8 -*-
#!/usr/bin/python
import sys
def merge_string(string,string2):
mergestring = ''
for i in range(len(string)):
mergestring += string[i]
mergestring += string2[i]
return mergestring
if __name__ == "__main__":
'''
print result of merge char from string given as a arguments
this only support 1 arguments
original param should be "パトカー" + "タクシー"
'''
string = sys.argv[1]
string2 = sys.argv[2]
mergestring = merge_string(string,string2)
print(mergestring)
|
2ab544066215b185af0df9a551a99258b1954d26
|
Akhil-64/Data-structures-using-Python
|
/6.py
| 1,464 | 3.953125 | 4 |
'''
The given binary tree is not a Binary Search Tree (BST) then print the location of 1 st violation.
'''
class Node:
def __init__(self,key):
self.key=key
self.right=None
self.left=None
def isBSTUtil(node,min1,max1):
if node is None:
return True
if node.key<min1 or node.key>max1:
print("Location of 1st Violation: Level",getLevel(root,node.key))
return False
return (isBSTUtil(node.left,min1,node.key-1)and isBSTUtil(node.right,node.key+1,max1))
int_min=-4294967296
int_max=4294967296
def isBST(node):
return (isBSTUtil(node,int_min,int_max))
def getLevelUtil(node,key,level):
if node is None:
return 0
if node.key==key:
return level
downlevel=getLevelUtil(node.left,key,level+1)
if (downlevel!=0):
return downlevel
downlevel=getLevelUtil(node.right,key,level+1)
return downlevel
def getLevel(root,key):
return getLevelUtil(root,key,1)#level start from 1
root=Node(12)
root.right=Node(15)
root.left=Node(8)
root.left.right=Node(6)
root.left.left=Node(10)
root.right.left=Node(14)
root.right.right=Node(16)
'''
12 ------------- Level 1
/ \
8 15 ------- Level 2
/ \ / \
10 6 14 16 -- Level 3
'''
if (isBST(root)):
print("is BST")
else:
print("Not a BST")
|
0db86d8bfba1814b20e26db120a79ad22e34da40
|
jenkin-du/Python
|
/pyhon36_study/str2float.py
| 681 | 3.515625 | 4 |
# 将字符串转化成float型数字
# 这是改过的版本
from functools import reduce
NumMap = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '.': '.'}
def fn(x, y):
return x * 10 + y
def char2num(char):
return NumMap[char]
def str2float(string):
numList = list(map(char2num, string))
n = 0 # 记录小数位数
for i in numList:
if i != '.':
n += 1
else:
break
lens = len(numList) - n - 1
numList.remove('.')
i = 1
m = 1
while i <= lens:
m *= 10
i += 1
return reduce(fn, numList) / m
result = str2float('2234.456')
print(result)
|
d4b8d25390666f419b129fafd5a395a5cefb14c8
|
OlgaDrach/kolokviym-
|
/44.py
| 534 | 3.796875 | 4 |
#Підрахуйте кількість елементів одновимірного масиву, які збігаються зі
#своїм номером і при цьому кратні 3.
#Драч Ольга Олескандрівна, 122Д
import numpy as np
from random import randint
m = []
n = 0
for j in range(10):
m.append(int(input('Введіть числа: ')))
for i in range(10):
if m[j] == j and m[j] / 3 == 0:
n += 1
print("Збігаються зі своїм номером і при цьому кратні 3", n)
|
a61ae77132528c63366687f13b39dc949a036b98
|
jpelaezClub/pyowm
|
/scripts/generate_city_id_files.py
| 6,988 | 3.5 | 4 |
#!/usr/bin/env python
import requests, sys, os, codecs, json, gzip, collections, csv
city_list_url = 'http://bulk.openweathermap.org/sample/city.list.json.gz'
us_city_list_url = 'http://bulk.openweathermap.org/sample/city.list.us.json.gz'
city_list_gz = "city.list.json.gz"
us_city_list_gz = "city.list.us.json.gz"
csv_city_list = "city_list.csv"
us_csv_city_list = "us_city_list.csv"
ordered_csv_city_list = "city_list.ordered.csv"
"""
This script is used to retrieve the city IDs list from the OWM web 2.5 API
and then to divide the list into smaller chunks: each chunk is ordered by
city ID and written to a separate file
URLs of source files:
http://bulk.openweathermap.org/sample/city.list.json.gz
http://bulk.openweathermap.org/sample/city.list.us.json.gz
"""
def download_the_files():
print 'Downloading file '+city_list_url+' ...'
with open(city_list_gz, 'wb') as h:
response = requests.get(city_list_url, stream=True)
for block in response.iter_content(1024):
h.write(block)
print 'Downloading file '+us_city_list_url+' ...'
with open(us_city_list_gz, 'wb') as g:
response = requests.get(us_city_list_url, stream=True)
for block in response.iter_content(1024):
g.write(block)
print ' ... done'
def read_all_cities_into_dict():
print 'Reading city data from files ...'
all_cities = dict()
# All cities
with gzip.open(city_list_gz, "rb", "utf-8") as i:
cities = json.loads(i.read())
for city_dict in cities:
# eg. {"id":707860,"name":"Hurzuf","country":"UA","coord":{"lon":34.283333,"lat":44.549999}}
if city_dict['id'] in all_cities:
print 'Warning: city ID %d was already processed! Data chunk is: %s' % (city_dict['id'], city_dict)
continue
else:
all_cities[city_dict['id']] = dict(name=city_dict['name'],
country=city_dict['country'],
lon=city_dict['coord']['lon'],
lat=city_dict['coord']['lat'])
# US cities
with gzip.open(us_city_list_gz, "rb", "utf-8") as f:
try:
cities = json.loads(f.read())
for city_dict in cities:
# eg. {"id":707860,"name":"Hurzuf","country":"UA","coord":{"lon":34.283333,"lat":44.549999}}
if city_dict['id'] in all_cities:
print 'Warning: city ID %d was already processed! Data chunk is: %s' % (city_dict['id'], city_dict)
continue
else:
all_cities[city_dict['id']] = dict(name=city_dict['name'],
country=city_dict['country'],
lon=city_dict['coord']['lon'],
lat=city_dict['coord']['lat'])
except Exception as e:
print 'Impossible to read US cities: {}'.format(e)
print '... done'
return all_cities
def order_dict_by_city_id(all_cities):
print 'Ordering city dict by city ID ...'
all_cities_ordered = collections.OrderedDict(sorted(all_cities.items()))
print '... done'
return all_cities_ordered
def city_to_string(city_id, city_dict):
return ','.join([city_dict['name'], str(city_id), str(city_dict['lat']), str(city_dict['lon']),
city_dict['country']])
def split_keyset(cities_dict):
print 'Splitting keyset of %d city names into 4 subsets based on the initial letter:' % (len(cities_dict),)
print '-> from "a" = ASCII 97 to "f" = ASCII 102'
print '-> from "g" = ASCII 103 to "l" = ASCII 108'
print '-> from "m" = ASCII 109 to "r" = ASCII 114'
print '-> from "s" = ASCII 115 to "z" = ASCII 122'
ss = [list(), list(), list(), list()]
for city_id in cities_dict:
name = cities_dict[city_id]['name'].lower()
if not name:
continue
c = ord(name[0])
if c < 97: # not a letter
continue
elif c in range(97, 103): # from a to f
ss[0].append(city_to_string(city_id, cities_dict[city_id]))
continue
elif c in range(103, 109): # from g to l
ss[1].append(city_to_string(city_id, cities_dict[city_id]))
continue
elif c in range(109, 115): # from m to r
ss[2].append(city_to_string(city_id, cities_dict[city_id]))
continue
elif c in range (115, 123): # from s to z
ss[3].append(city_to_string(city_id, cities_dict[city_id]))
continue
else:
continue # not a letter
print '... done'
return ss
def write_subsets_to_files(ssets, outdir):
print 'Writing subsets to files ...'
with codecs.open("%s%s097-102.txt" % (outdir, os.sep),
"w", "utf-8") as f:
for city_string in sorted(ssets[0]):
f.write(city_string+"\n")
with codecs.open("%s%s103-108.txt" % (outdir, os.sep),
"w", "utf-8") as f:
for city_string in sorted(ssets[1]):
f.write(city_string+"\n")
with codecs.open("%s%s109-114.txt" % (outdir, os.sep),
"w", "utf-8") as f:
for city_string in sorted(ssets[2]):
f.write(city_string+"\n")
with codecs.open("%s%s115-122.txt" % (outdir, os.sep),
"w", "utf-8") as f:
for city_string in sorted(ssets[3]):
f.write(city_string+"\n")
print '... done'
def gzip_csv_compress(plaintext_csv, target_gzip):
print 'G-zipping: %s -> %s ...' % (plaintext_csv, target_gzip)
with open(plaintext_csv, 'r') as source:
source_rows = csv.reader(source)
with gzip.open(target_gzip, "wt") as file:
writer = csv.writer(file)
for row in source_rows:
writer.writerow(row)
print '... done'
def gzip_all(outdir):
gzip_csv_compress('%s%s097-102.txt' % (outdir, os.sep),
'%s%s097-102.txt.gz' % (outdir, os.sep))
gzip_csv_compress('%s%s103-108.txt' % (outdir, os.sep),
'%s%s103-108.txt.gz' % (outdir, os.sep))
gzip_csv_compress('%s%s109-114.txt' % (outdir, os.sep),
'%s%s109-114.txt.gz' % (outdir, os.sep))
gzip_csv_compress('%s%s115-122.txt' % (outdir, os.sep),
'%s%s115-122.txt.gz' % (outdir, os.sep))
if __name__ == '__main__':
target_folder = os.path.abspath(sys.argv[1])
print 'Will save output files to folder: %s' % (target_folder,)
print 'Job started'
download_the_files()
cities = read_all_cities_into_dict()
ordered_cities = order_dict_by_city_id(cities)
ssets = split_keyset(ordered_cities)
write_subsets_to_files(ssets, target_folder)
gzip_all(target_folder)
print 'Job finished'
|
9404aec42de685e10361d5edcefade3f3bb7efd4
|
Weeeendi/Python
|
/car.py
| 1,251 | 4.1875 | 4 |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
class Car():
"""一次模拟汽车的简单测试"""
def __init__(self,make,model,year):
"""初始化描述汽车的属性"""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_desciptive_name(self):
"""return the clearly desciptive message"""
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
"""打印一条指出汽车里程的信息"""
print("This car has " + str(self.odometer_reading) + " mile on it.")
def update_odometer(self,milage):
"""将里程表读数设置为指定的值"""
"""禁止将里程表读数进行回调"""
if milage >= self.odometer_reading:
self.odometer_reading = milage
else:
print("You can't roll back the odometer!")
def increment_odometer(self,miles):
if miles < 0:
print("You can't roll back the odometer!")
else:
self.odometer_reading += miles
def fill_gas_tank(self):
print("This car's gas tank is full.")
|
2d706e8327c739f9af20ef85cc13840dd4b8bfe3
|
CarolinaRivera/Python
|
/Operaciones Matematicas/Operaciones.py
| 1,048 | 4.15625 | 4 |
# Entrada de Datos
print("Escribe el numero1: ")
number1 = int(input())
print("Escribe numero2: ")
number2 = int(input())
# Operaciones o Calculos Matematicos
suma = number1 + number2
resta = number1 - number2
potencia1 = pow(number1, number2)
potencia2 = pow(number1, number2)
raiz_cuadrada = pow(number1, 0.5)
raiz_cubica = pow(number1, 1/3)
modulo = number1 % number2
# Impresion o mostrar pantalla
#suma
print("la suma es igual a " + str(suma))
print(f"la suma = {suma}")
#resta
print("la resta es igual a " + str(resta))
print(f"La resta = {resta}")
#multiplicacion
print(f"la multiplicaion de " + str(number1 * number2))
#division
print(f"la division de " + str(number1 / number2))
#potencias
print(f"La potencia de " + str(number1))
print(f"La potencia de " + str(number2))
#raices
print(f"La raiz cuadrada de " + str(raiz_cuadrada))
print(f"La raiz cubica de " + str(raiz_cubica))
print(f"La raiz cubica de ", str(raiz_cubica))
#modulo
print(f"El modulo o residuo es " + str(modulo))
print(f"El modulo o residuo = {modulo}")
|
f6d17ecc473467bff0768727c42c7201ab7c6921
|
sujan-thapa/Invoice-In-Python
|
/Invoice/main.py
| 2,533 | 4.0625 | 4 |
import first
sujan = first.dict1()
# print(sujan)
sss = sujan.items()
customerName = input("What is your name?: \n")
customer = input("Which prodcut do you want to buy from available products???: ")
# print(customer)
amount = 0
def inside():
for gadgets, prQty in sss: #for loop for nested dictionary
if customer in gadgets: #check if product is available
print("\nProduct: ", gadgets)
priceQty = [] #empty list
for vg in prQty: #adding stock amount and price of product in list
print(vg + ":", prQty[vg]) #displays the nested dictionary keys and values
priceQty.append(prQty[vg]) #add the information at the end of list
else:
desire = int(input("How many piece do your want??: ")) #user input for desired piece
strInt = int(priceQty[0])
avail = int(priceQty[1])
if avail >= desire:
global amount
amount = strInt * desire
# print(f"The total price is {amount}")
avail -= desire
# print(avail)
return avail
# rough = ""
# reading = open("vg.txt","r")
# for line in reading:
# stripLine = line.strip()
# newLine = stripLine.replace(sujan[customer]["stock"],str(avail))
# rough += newLine +"\n"
# reading.close()
# print(rough)
# writing = open("vg.txt","w")
# writing.write(rough)
# writing.close()
else:
# print("The stock of product is limited.")
return "The stock of product is limited."
break
else:
continue
else:
# print("Sorry! The product is not available")
return "The product is not available" #returns the sorry message
# print(inside())
# inside()
# print("The total amount is " + amount) #This ways is wrong because print can only concatenate str (not "int") to str
# print(amount) #This gives the result
#Displays the message with proper message
# amt = str(amount) #Convert integer to string
# print("The total amount of product is "+ amt) #prints the message in appropriate way
# print(type(amount))
|
50bd565caffb972a8d3c2a5e0eb611becc7dbfab
|
cliffpham/algos_data_structures
|
/algos/loops/K_closets_points_to_origin.py
| 1,539 | 3.546875 | 4 |
# space efficient solution
import math
def closet(points, K):
output = []
points = merge_sort(points)
while len(output) < K:
output.append(points.pop())
return output
def compare(points, index):
cur = points[index]
return math.trunc(math.pow(cur[0],2) + math.pow(cur[1], 2))
#descending order merge sort
def merge_sort(arr):
left_index = 0
right_index = 0
if len(arr) < 2:
return arr
left = arr[0:(len(arr)//2)]
right = arr[len(arr)//2:len(arr)]
left = merge_sort(left)
right = merge_sort(right)
return merge(left, right, left_index, right_index)
def merge(left, right, left_index, right_index):
results = []
while len(left) > left_index and len(right) > right_index:
if compare(left, left_index) < compare(right, right_index):
results.append(right[right_index])
right_index += 1
else:
results.append(left[left_index])
left_index += 1
while len(left) > left_index:
results.append(left[left_index])
left_index += 1
while len(right) > right_index:
results.append(right[right_index])
right_index += 1
return results
# print(closet(points = [[-5,4],[-6,-5],[4,6]], K=2))
# print(closet(points = [[3,3],[5,-1],[-2,4]], K=2))
# print(closet(points = [[-2,10],[-4,-8],[10,7],[-4,-7]], K=3))
# time efficient solution
def kClosest(points, K):
points.sort(reverse = False, key = lambda p: p[0]**2 + p[1]**2)
return points[:K]
|
a55758428419de0dcef952e13dd006d0d27a410b
|
SaitoTsutomu/leetcode
|
/codes_/0022_Generate_Parentheses.py
| 565 | 3.578125 | 4 |
# %% [22. **Generate Parentheses](https://leetcode.com/problems/generate-parentheses/)
# 問題:有効な「n個の括弧からなる文字」を列挙
# 解法:左括弧と右括弧について再帰
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
return list(search("(" * n, "", ""))
def search(left, right, cur):
if left:
yield from search(left[:-1], right + left[-1], cur + left[-1])
if right:
yield from search(left, right[:-1], cur + chr(81 - ord(right[-1])))
elif not left:
yield cur
|
d89d6e24f1a063a2b3a3cddf84882d4125c4ccf3
|
lucassing/SportLeague
|
/team.py
| 343 | 3.515625 | 4 |
class Team:
"""
Tournament object
:param name: the team name
foundation: the foundation's year of the team
"""
def __init__(self, name, *args, **kwargs):
self.team_name = name
self.foundation = kwargs.get('foundation')
def __str__(self):
return str(self.team_name)
|
32d89207a300b41d758daabcddfd9704c2de3c95
|
bmandiya308/python_trunk
|
/oracle.py
| 1,524 | 3.578125 | 4 |
list_input = ["may", "student", "students", "dog","studentssess", "god","god","cat", "act","tab", "bat", "flow", "wolf", "lambs","amy", "yam", "balms", "looped", "poodle"]
'''
list_matched =list()
list_not_matched =list()
for word in list_input:
length_match = [itm for itm in list_input if len(word) == len(itm) and word != itm]
#print(length_match)
if(len(length_match) <= 0):
next
else:
for word1 in length_match:
count = 0
for char in word:
if(char in word1):
count += 1
if(len(word1) == count):
if(not word in list_matched):
list_matched.append(word)
print(list_matched)
print(list_not_matched)
dict_a = dict()
for word in list_input:
if(not dict_a.get(word)):
dict_a[word] = {'value' : ''.join(sorted(list(word))), 'count' : 1}
else:
dict_a[word] = {'value': ''.join(sorted(list(word))), 'count': dict_a[word]['count'] + 1}
print(dict_a)
for key,value in sorted(dict_a.items(),key=lambda x:x[1]):
dict_bk = dict_a.copy()
del dict_bk[key]
if(value in dict_bk.values()):
print("Matched : ",key)
else:
print("Not Matched : ",key)
'''
dict_a = dict()
for word in list_input:
if(not dict_a.get(''.join(sorted(list(word))))):
dict_a[''.join(sorted(list(word)))] = [word]
else:
dict_a[''.join(sorted(list(word)))].append(word)
for key,value in dict_a.items():
print(key,' : ',value)
|
9ee6b7631c5fbe8a124ee2364356d3e5f84faece
|
maia13/aoc-2020
|
/day23a/program_lib.py
| 919 | 3.796875 | 4 |
import re
def calculate(cups, count):
for _ in range(count):
cups = move(cups)
ix1 = cups.index('1')
result = cups[ix1+1:] + cups[0:ix1]
return ''.join(result)
# (3) [8 9 1] 5 4 6 7 {2}
# (3) [8 9 1] {2} 5 4 6 7
# (3) [8 9 1] 5 4 {2} 6 7
def move(cups):
current_cup_label = cups[0]
three_cups = cups[1:4]
destination_cup_label = int(current_cup_label) - 1
while str(destination_cup_label) in three_cups or destination_cup_label == 0:
if destination_cup_label < 0:
raise Exception(f'destination_cup_label = {destination_cup_label}')
if destination_cup_label == 0:
destination_cup_label = 9
else:
destination_cup_label -= 1
destination_cup_ix = cups.index(str(destination_cup_label))
result_cups = cups[4:destination_cup_ix+1] + three_cups + cups[destination_cup_ix+1:] + current_cup_label
return result_cups
|
ea072f8d767eef8a180818eb41960aed645b2079
|
patels20/APC-Hub
|
/CURSE/code/Classes/user_c.py
| 552 | 3.6875 | 4 |
class User:
# Base Class that all classes are built off of
def __init__(self, user_id="7", first_name="7", last_name="7", passcode="7"):
# This is the initialization function
# if no paramaters are passed into it, the default listed will be used
self.user_id = user_id # User ID - It must be UNIQUE
self.first_name = first_name # User's First Name
self.last_name = last_name # User's Last Name
self.passcode = passcode # Passcode is used for initial Login
|
7409c7ee4377af3be4e3cc14ebdd6291cff2306b
|
ahmedyoko/python-course-Elzero
|
/DB_fetch_data80.py
| 1,415 | 3.875 | 4 |
#................................................
# DB => sqlite => retrive data from data base
#................................................
# fetchone => return single record or non if no more rows are available
# fetchall => fetch all rows of the query result.It returns all the rows as a list of tuple
# & an empty list will be returned if no record to fetch
# fetchmany(size) => number of rows
#................................................
# import sqlite3 module
import sqlite3
# create database and connect
db = sqlite3.connect("app.db")
# setting up the cursor
cr = db.cursor()
# execute the tables and fields
cr.execute("CREATE TABLE if not exists users(user_id INTEGER,name TEXT)")
cr.execute("CREATE TABLE if not exists skills(name TEXT,progress INTEGER,user_id INTEGER)")
# insert data
cr.execute("insert into users(user_id,name)values(1,'Ahmed')")
cr.execute("insert into users(user_id,name)values(2,'Nagib')")
cr.execute("insert into users(user_id,name)values(3,'Osama')")
# fetch data
# cr.execute("select name from users")
# cr.execute("select user_id,name from users")
# cr.execute("select * from users")
# print(cr.fetchone())
# print(cr.fetchone())
# print(cr.fetchone())
# print(cr.fetchone())
# print(cr.fetchall())
# print(cr.fetchmany(2))
# save(commit)changes => to transmit to data base and appear in browser
db.commit()
# close the db
db.close()
print('*'*50)
|
41a948615ca54ff0acccf40d8dbd3a13f49d29dc
|
atulmishra/try_git
|
/day2/statisticsDemo.py
| 796 | 3.546875 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 12 09:59:59 2018
@author: Administrator
"""
import statistics
print (statistics.mean([1,2,3,4,4]))
print (statistics.mean([-1.0,2.5,3.25,5.75]))
from fractions import Fraction as F
print(statistics.mean([F(3,7),F(1,21),F(5,3),F(1,3)]))
print (F(3,67))
from decimal import Decimal as D
print(statistics.mean([D("0.5"), D("0.75"), D("0.58")]))
print(statistics.harmonic_mean([2.5,3,10]))
print(statistics.median([1,3,4,5]))
print(statistics.median_high([1,3,5,7]))
print(statistics.median_low([1,3,5,7]))
#used in frequency table
print(statistics.median_grouped([52,52,53,54]))
#mode
print(statistics.mode(["red","blue","blue","red","green","red","red"]))
print(statistics.mode([1,1,2,2,2]))
|
8230479d2659a733c178413664ea18b695925711
|
perennialAutodidact/PDXCodeGuild_Projects
|
/Python/lists_practice/problem10.py
| 237 | 4 | 4 |
def merge(a,b):
pairs = []
[pairs.append([a[i], b[i]]) for i in range(len(a))]
return pairs
def main():
list1 = ["a", "b", "c"]
list2 = [1,2,3]
print(f"{list1}, {list2}. Merged: {merge(list1, list2)}")
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.