blob_id
stringlengths 40
40
| repo_name
stringlengths 5
127
| path
stringlengths 2
523
| length_bytes
int64 22
3.06M
| score
float64 3.5
5.34
| int_score
int64 4
5
| text
stringlengths 22
3.06M
|
---|---|---|---|---|---|---|
9a171f9585f56bb701ddbf6d88c6437c5123eca2 | hcmMichaelTu/python | /lesson14/tri_color_wheel.py | 1,797 | 3.6875 | 4 | import turtle as t
import time
import math
class TriColorWheel:
def __init__(self, omega, center=(0, 0), radius=100,
colors=("red", "green", "blue"),
up_key=None, down_key=None):
self.center = center
self.radius = radius
self.colors = colors
self.omega = omega # vận tốc góc độ/giây (+, 0, -)
self.angle = 0 # góc điểm chốt A
if up_key: t.onkeypress(self.speed_up, up_key)
if down_key: t.onkeypress(self.speed_down, down_key)
def speed_up(self): self.omega += 2
def speed_down(self): self.omega -= 2
def rotate(self, dt):
self.angle += self.omega * dt
A = self.angle; B = A + 120; C = B + 120
t.up(); t.goto(self.center); t.down()
for angle, color in zip((A, B, C), self.colors):
t.color(color)
t.begin_fill()
t.setheading(angle); t.forward(self.radius); t.left(90)
t.circle(self.radius, 120); t.goto(self.center)
t.end_fill()
def contain(self, point):
return math.dist(point, self.center) <= self.radius
if __name__ == "__main__":
def run():
global tm
t.clear()
tcw1.rotate(time.time() - tm)
tcw2.rotate(time.time() - tm)
t.update()
tm = time.time()
t.ontimer(run, 1000//24) # 24 fps
tcw1 = TriColorWheel(180, center=(100, 0),
up_key="Left", down_key="Right")
tcw2 = TriColorWheel(-180, center=(-100, 0),
colors=("cyan", "magenta", "yellow"),
up_key="a", down_key="d")
t.tracer(False); t.hideturtle(); t.listen()
tm = time.time(); run(); t.exitonclick()
|
db6bca60ff9d43d14f893a5d2afaf0dcb825091b | hcmMichaelTu/python | /lesson08/Newton_sqrt2.py | 166 | 3.75 | 4 | def Newton_sqrt(x):
if x < 0:
return
if x == 0:
return 0
y = x
for i in range(100):
y = y/2 + x/(2*y)
return y
|
a4fbc2deb5430e99feeeafc0af267677f4e957fc | hcmMichaelTu/python | /lesson05/square.py | 192 | 3.71875 | 4 | import turtle as t
t.shape("turtle")
d = int(input("Kích thước hình vuông? "))
t.forward(d); t.left(90)
t.forward(d); t.left(90)
t.forward(d); t.left(90)
t.forward(d); t.left(90)
|
2d17aba920279d5c521fcd5646ef53b844dde294 | hcmMichaelTu/python | /lesson06/exam.py | 191 | 3.65625 | 4 | điểm_thi = float(input("Bạn thi được bao nhiêu điểm? "))
if điểm_thi < 5:
print("Chúc mừng! Bạn đã rớt.")
else:
print("Chia buồn! Bạn đã đậu.")
|
113c8f8c95c6b98f181af8c197305be9729c853e | hcmMichaelTu/python | /lesson15/turtle_escape.py | 552 | 3.65625 | 4 | import turtle as t
import random
t.shape("turtle")
d = 20
try:
while (abs(t.xcor()) < t.window_width()/2
and abs(t.ycor()) < t.window_height()/2):
direction = random.choice("LRUD")
if direction == "L":
t.setheading(180)
elif direction == "R":
t.setheading(0)
elif direction == "U":
t.setheading(90)
else: # direction == "D"
t.setheading(270)
t.forward(d)
print("Congratulations!")
except t.Terminator:
pass
|
30ab7ff7d01d2d2ac154a8a1643169059633d8a8 | hcmMichaelTu/python | /lesson12/turtle_draw2.py | 349 | 3.625 | 4 | import turtle as t
def forward(deg):
def _forward():
t.setheading(deg)
t.forward(d)
return _forward
t.shape("turtle")
d = 20
actions = {"Left": 180, "Right": 0, "Up": 90, "Down": 270}
for act in actions:
t.onkey(forward(actions[act]), act)
t.onkey(t.bye, "Escape")
t.listen()
t.mainloop()
|
f7627d984bb9d995801c88ebe76baffac933ebca | hcmMichaelTu/python | /lesson17/triangle.py | 271 | 3.5 | 4 | import sys
char = input("Nhập kí hiệu vẽ: ")
n = int(input("Nhập chiều cao: "))
stdout = sys.stdout
with open("triangle.txt", "wt") as f:
sys.stdout = f
for i in range(1, n + 1):
print(char * i)
sys.stdout = stdout
print("Done!")
|
5d437d6e804b72f26526c22418c8f2cb719ed1d6 | hcmMichaelTu/python | /lesson18/guess_number2.py | 872 | 3.765625 | 4 | import random
def binary_guess():
if left <= right:
return (left + right) // 2
else:
return None
def hint(n, msg):
global left, right
if msg == "less":
left = n + 1
else:
right = n - 1
max = 1000
print("Trò chơi đoán số!")
print(f"Bạn đoán một con số nguyên trong phạm vi 1-{max}.")
left, right = 1, max
secret = random.randint(1, max)
count = 0
while True:
count += 1
input("Press Enter to guess.")
n = binary_guess()
print(f"Đoán lần {count} số {n}")
if n < secret:
print("Số bạn đoán nhỏ quá!")
hint(n, "less")
elif n > secret:
print("Số bạn đoán lớn quá!")
hint(n, "greater")
else:
print(f"Bạn đoán đúng số {secret} sau {count} lần.")
break
|
4de83b6bff15ac23aa0a775e068a487b51c771e4 | mikemeko/6.01_Tools | /src/core/math/line_segments.py | 2,443 | 3.671875 | 4 | """
Utility for line segments.
(1) Check whether two line segments intersect. Credit to: http://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect
(2) Translate segments.
"""
__author__ = '[email protected] (Michael Mekonnen)'
from core.util.util import overlap
from math import atan2
from math import cos
from math import pi
from math import sin
def _cross(V, W):
"""
Returns the magnitude of the cross product of vectors |V| and |W|.
"""
vx, vy = V
wx, wy = W
return vx * wy - vy * wx
def intersect(segment1, segment2):
"""
If |segment1| or |segment2| has 0 length, returns False.
If |segment1| and |segment2| intersect and are colliniar, returns 'collinear'.
Otherwise, if |segment1| and |segment2| intersect at exactly one point,
returns that point.
Otherwise, returns False.
Segments should be given in the form ((x0, y0), (x1, y1)).
"""
(x00, y00), (x01, y01) = segment1
x00, y00, x01, y01 = float(x00), float(y00), float(x01), float(y01)
R = (x01 - x00, y01 - y00)
if R == (0, 0):
return False
(x10, y10), (x11, y11) = segment2
x10, y10, x11, y11 = float(x10), float(y10), float(x11), float(y11)
S = (x11 - x10, y11 - y10)
if S == (0, 0):
return False
QmP = (x10 - x00, y10 - y00)
RcS = float(_cross(R, S))
QmPcS = _cross(QmP, S)
QmPcR = _cross(QmP, R)
if RcS == 0:
# segments are parallel
if QmPcR == 0:
# segments are collinear
if R[0] == 0:
return 'collinear' if overlap((min(y00, y01), max(y00, y01)), (min(y10,
y11), max(y10, y11))) else False
else:
for (x, vx, xs) in [(x00, R[0], (x10, x11)), (x10, S[0], (x00, x01))]:
for ox in xs:
if 0 <= (ox - x) / vx <= 1:
return 'collinear'
return False
else:
return False
t = QmPcS / RcS
if t < 0 or t > 1:
return False
u = QmPcR / RcS
if u < 0 or u > 1:
return False
return (x00 + t * R[0], y00 + t * R[1])
def translate(segment, d):
"""
Returns a new segment that corresponds to the given |segment| translated
perpendicularly by |d| units.
Segment should be given and is returned in the form ((x1, y1), (x2, y2)).
"""
(x1, y1), (x2, y2) = segment
if x1 > x2:
x1, x2 = x2, x1
y1, y2 = y2, y1
phi = atan2(y2 - y1, x2 - x1)
theta = pi / 2 - phi
dx = d * cos(theta)
dy = d * sin(theta)
return ((x1 - dx, y1 - dy), (x2 - dx, y2 - dy))
|
fe5ece5986e3f29e5f82a7512ea54746f2efa9bc | guimesmo/python-demo | /frase_do_dia_typed.py | 1,260 | 3.578125 | 4 | import random
import typing
class Frase:
def __init__(self, conjunto: str, idioma_padrao: str = "pt"):
self.conjunto = conjunto
self.idioma_padrao = idioma_padrao
self.output = dict()
self.parse()
def __str__(self):
return self.output.get(self.idioma_padrao, "Não definido")
def parse(self) -> None:
conjunto = self.conjunto.split("\n")
for frase in conjunto:
if frase: # previne linha em branco
idioma, frase = frase.split("|")
self.output[idioma] = frase
def gerador_de_frase_i18n(idioma: str = "pt") -> str:
with open("frases-i18n.txt", "r") as arquivo:
conjuntos = arquivo.read().split("\n\n")
frases = []
for conjunto in conjuntos:
frase_instancia = Frase(conjunto)
frases.append(frase_instancia)
frase = random.choice(frases)
return frase.output.get(idioma)
def gerador_de_frase() -> str:
with open("frases.txt", "r") as arquivo:
frases = list(arquivo.readlines())
return random.choice(frases)
if __name__ == '__main__':
import sys
if len(sys.argv) > 1:
idioma = sys.argv[1]
else:
idioma = "pt"
print(gerador_de_frase_i18n(idioma))
|
62bb6e65edf4da3a18f8f681413b99518182631f | lokeki/python | /ZadSrdZaw/wykladI/Zad8EnumerateZip.py | 1,292 | 3.71875 | 4 | #wyk/enumerate/zip
'''
workDays = [19, 21, 22, 21, 20, 22]
print(workDays)
print(workDays[2])
enumerateDays = list(enumerate(workDays))
print(enumerateDays)
#enumerate - numerujemy kazdy element z listy i tworza sie tumple
for pos, value in enumerateDays:
print("Pos:", pos, "Value:", value)
month = ['I', 'II', 'III', 'IV', 'V', 'VI']
#zip - laczymy dwie tablice i tworza sie yumple(pary)
monthDay = list(zip(month,workDays))
print(monthDay)
for mon, day in monthDay:
print('Month:', mon, 'Day:', day)
for pos, (mon, day) in enumerate(zip(month, workDays)):
print('Pos:', pos, 'Month:', mon, 'Day:', day)
print('{} - {} - {}'.format(pos, mon, day)
'''
projects = ['Brexit', 'Nord Stream', 'US Mexico Border']
leaders = ['Theresa May', 'Wladimir Putin', 'Donald Trump and Bill Clinton', 'cosik']
for project, leader in zip(projects, leaders):
print('The leader of {} is {}'.format(project, leader))
print('')
dates = ['2016-06-23', '2016-08-29', '1994-01-01']
for project, data, leader in zip(projects, dates, leaders):
print('The leader of {} started {} is {}'.format(project, data, leader))
print('')
for position, (project, data, leader) in enumerate(zip(projects, dates, leaders)):
print('{} The leader of {} started {} is {}'.format(position + 1, project, data, leader))
|
14547f40099598502bbadfea46a328fb21330128 | lokeki/python | /ZadSrdZaw/wykladI/Zad11Generator.py | 1,645 | 3.671875 | 4 | #generator zazwyczaj się używa kiedy jest duza baza danych
'''
listA = list(range(6))
listaB = list(range(6))
print(listA, listaB)
product = []
for a in listA:
for b in listA:
product.append((a,b))
print(product)
#skrocona wersja z ifem (lista)
product = [(a,b) for a in listA for b in listaB if a % 2 != 0 and b % 2 == 0]
print(product)
#wersja ze slownikiem, zmiana nawiasow kawadratowych na klamrowe, zmiana w zapisie danych
#zamiast (a,b), to a:b
product = { a:b for a in listA for b in listaB if a % 2 != 0 and b % 2 == 0}
#klucz (a) zosal a dane (b) sie zmienialy
print(product)
print('-' * 30)
#generator nie zajmuje pamięci jak lista, nie jest to gotowa np lista, nie przechowuje danych,
# przechowuje raczej metode, sposob na wygenerowanie tych danych
gen = ((a,b) for a in listA for b in listaB if a % 2 != 0 and b % 2 == 0)
print(gen)
print('-' * 30)
#zwraca i usuwa
print(next(gen))
print(next(gen))
print('-' * 30)
for x in gen:
print(x)
print('-' * 30)
gen = ((a,b) for a in listA for b in listaB if a % 2 != 0 and b % 2 == 0)
#wyłapanie konca generatora poprzez try/except
while True:
try:
print(next(gen))
except StopIteration:
print("All values have been generated")
break
'''
ports = ['WAW', 'KRK', 'GDN', 'KTW', 'WMI', 'WRO', 'POZ', 'RZE', 'SZZ',
'LUZ', 'BZG', 'LCJ', 'SZY', 'IEG', 'RDO']
routes = ((port1, port2) for port1 in ports for port2 in ports if port1 < port2)
line = 0
while True:
try:
print(next(routes))
line += 1
except StopIteration:
print("All values have been generated. It have been", line)
break |
a0556b957eaf8394c0277e7830d7b347319bb402 | lokeki/python | /ZadSrdZaw/wykladI/Zad18FunkcjaArgumentemFunkcji.py | 969 | 3.53125 | 4 | # Funkcja jako argument funkcji
'''
def Bake (what):
print("Baking:", what)
def Add (what):
print("Adding:",what)
def Mix (what):
print("Mixing:", what)
cookBook = [(Add, "milk"), (Add, "eggs"), (Add, "flour"), (Add, "sugar"), (Mix, "ingerdients"), (Bake, "cookies")]
for activity, obj in cookBook:
activity(obj)
print("-" * 40)
def Cook(activity, obj):
activity(obj)
for activity, obj in cookBook:
Cook(activity, obj)
'''
def double(x):
return 2 * x
def root(x):
return x ** 2
def negative(x):
return -x
def div2(x):
return x / 2
def generateValues(nameFunctoin, parametrs):
listWithResult = []
for parametr in parametrs:
listWithResult.append(nameFunctoin(parametr))
return listWithResult
x_table = list(range(11))
print(type(x_table))
print(generateValues(double, x_table))
print(generateValues(root, x_table))
print(generateValues(negative, x_table))
print(generateValues(div2, x_table))
|
dc30adb10fb9d8482e0f4febadf412dd4524bc80 | lokeki/python | /ZadSrdZaw/wykladI/Zad24OptymalizacjaFunkcjiCache.py | 737 | 3.5625 | 4 | #Optymalizacja funkcji przez cache# musi byc deterministyczna, miec zawsze takie
# same argumenty i taki rezultat
'''
import time
import functools
@functools.lru_cache()
def Factorial (n):
time.sleep(0.1)
if n == 1:
return 1
else:
return n * Factorial(n - 1)
start = time.time()
for i in range(1,11):
print('{}! = {}'.format(i, Factorial(i)))
stop = time.time()
print("Time:", stop - start)
print(Factorial.cache_info())
'''
import time
import functools
@functools.lru_cache()
def fib(n):
if n <= 2:
result = n
else:
result = fib(n - 1) + fib(n - 2)
return result
start = time.time()
for i in range(1, 33):
print(fib(i))
stop = time.time()
print(stop - start) |
30532ca431def7eaaba8588814e5b22873ff8017 | lokeki/python | /ZadSrdZaw/wykladI/Zad19FunkcjaZwracaFunkcje.py | 1,208 | 3.53125 | 4 | # Zwaracanie funkcji
#
# def Calculate ( kind = "+", *args):
# result = 0
#
# if kind == "+":
#
# for a in args:
# result += a
#
# elif kind == '-':
#
# for a in args:
# result -= a
#
# return result
#
# def CreateFunction(kind = "+"):
# source = '''
# def f(*args):
# result = 0
# for a in args:
# result {}= a
# return result
# '''.format(kind)
# exec(source, globals())
#
# return f
#
# fAdd = CreateFunction("+")
# print(fAdd(1,2,3,4))
# fSubs = CreateFunction("-")
# print(fSubs(1,2,3,4))
import datetime
def TimeFunk(timeF = 'm' ):
if timeF == 'm':
sec = 60
elif timeF == 'h':
sec = 3600
elif timeF == 'd':
sec = 86400
source = '''
def f(start, end):
temp = end - start
tempSec = temp.total_seconds()
return divmod(tempSec, {})[0]
'''.format(sec)
exec(source, globals())
return f
TimeFunk()
f_minutes = TimeFunk('m')
f_hours = TimeFunk('h')
f_days = TimeFunk('d')
start = datetime.datetime(2019, 12, 10, 0, 0, 0)
end = datetime.datetime(2020, 12, 10, 0, 0, 0)
print(f_minutes(start, end))
print(f_hours(start, end))
print(f_days(start, end)) |
8a23940de2d48ab3b767e90e2e3a3e55836daffd | andyreagan/2018-advent-of-code | /2019-mm-month-of-python/13-manselmi/bruteforce.py | 489 | 3.953125 | 4 | import sys
def collatz_f(i: int) -> int:
if i % 2 == 0:
return int(i / 2)
else:
return int(3*i + 1)
def get_path_length(i: int) -> int:
# print(i)
l = 1
while i != 1:
i = collatz_f(i)
l += 1
# print(i, l)
return l
def main(n):
all_path_lengths = [get_path_length(i+1) for i in range(n)]
m = max(all_path_lengths)
print(m, all_path_lengths.index(m)+1)
if __name__ == '__main__':
main(int(sys.argv[1]))
|
8122e6d19531fc76d06288aaf9dfb1590aca10d7 | webclinic017/StockPredictor-1 | /CAP4621_Stock_Prediction_Project.py | 15,684 | 3.59375 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Dhruv's Section
# In[ ]:
get_ipython().system('pip install matplotlib')
get_ipython().system('pip install seaborn')
get_ipython().system('pip install yfinance')
import platform
import yfinance as yf
import datetime
import matplotlib.pyplot as plt
import seaborn
# prints the ticker's close form the most recent, and its change from the day before
def getTickerData(tickerSymbol):
tickerData = yf.Ticker(tickerSymbol)
tickerInfo = tickerData.info
companyName = tickerInfo['shortName']
print('Company Name: ' + companyName)
today = datetime.datetime.today().isoformat()
# tickerOF = tickerData.history(period='1d', start='2020-10-1', end=today[:10])
# tickerOF = tickerData.history(period='1d', start='2018-5-1', end='2018-6-1')
tickerOF = tickerData.history(period='1d', start='2020-10-1', end='2020-10-20')
priceLast = tickerOF['Close'].iloc[-1]
priceYest = tickerOF['Close'].iloc[-2]
change = priceLast - priceYest
print(companyName + ' last price is: ' + str(priceLast))
print('Price change = ' + str(change))
# Gives a chart of the last 10 days
def getChart(tickerSymbol):
tickerData = yf.Ticker(tickerSymbol)
hist = tickerData.history(period="30d", start='2020-9-21', end='2020-10-20')
# hist = tickerData.history(period='1d', start='2020-10-1', end=today[:10])
# Plot everything by leveraging the very powerful matplotlib package
hist['Close'].plot(figsize=(16, 9))
# Calling the functions
getTickerData('MSFT')
getChart('MSFT')
# # Andres's Section
# In[ ]:
pip install quandl
# In[ ]:
import quandl
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.svm import SVR
from sklearn.model_selection import train_test_split
# In[ ]:
# Get stock data
df = quandl.get("WIKI/FB")
# Print Data
print(df.tail())
# In[ ]:
# Get Close Price
df = df[['Adj. Close']]
# Print it
print(df.head())
# In[ ]:
# Var for predicting 'n' days out into the future
forecast_out = 30
# Create another column (the target or dependent variable) shifted 'n' units up
df['Prediction'] = df[['Adj. Close']].shift(-2)
# Print new dataset
print(df.tail())
# In[ ]:
# Create independent Data set (X)
# Convert dataframe to numpy array
X = np.array(df.drop(['Prediction'], 1))
# Remove the last 'n' rows
X = X[:-2]
print(X)
# In[ ]:
# Create dependent data set (y)
# Convert the dataframe to numpy array (All of the values including NaN's)
y = np.array(df['Prediction'])
# Get all of the y values except the last n rows
y = y[:-2]
print(y)
# In[ ]:
# Split the data into 80% training and 20& testing
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
# In[ ]:
# Create and train the Support Vector Machine (Regressor)
svr_rbf = SVR(kernel="rbf", C=1e3, gamma=0.1)
svr_rbf.fit(x_train, y_train)
# In[ ]:
# Test Model: Score returns the coefficient of determination R^2 of the prediction
# The best possible score is 1.0
svm_confidence = svr_rbf.score(x_test, y_test)
print("svm confidence: ", svm_confidence)
# In[ ]:
# Create and train the Linear Regression Model
lr = LinearRegression()
# Train the Model
lr.fit(x_train, y_train)
# In[ ]:
# Test Model: Score returns the coefficient of determination R^2 of the prediction
# The best possible score is 1.0
lr_confidence = lr.score(x_test, y_test)
print("lr confidence: ", lr_confidence)
# In[ ]:
# Set x_forecast equal to the last 2 rows of the original data set from Adj. Close column
x_forecast = np.array(df.drop(['Prediction'],1))[-2:]
print(x_forecast)
# In[ ]:
# Print linear regression model predictions for the next n days
lr_prediction = lr.predict(x_forecast)
print(lr_prediction)
# Print SVR model predictions
svm_prediction = svr_rbf.predict(x_forecast)
print(svm_prediction)
# Backtesting with Zipline
# In[ ]:
get_ipython().system('pip install backtrader')
# In[ ]:
from zipline.api import order_target, record, symbol
import matplotlib.pyplot as plt
def initialize(context):
context.i = 0
context.asset = symbol('AAPL')
def handle_data(context, data):
# Skip first 300 days to get full windows
context.i += 1
if context.i < 300:
return
# Compute averages
# data.history() has to be called with the same params
# from above and returns a pandas dataframe.
short_mavg = data.history(context.asset, 'price', bar_count=100, frequency="1d").mean()
long_mavg = data.history(context.asset, 'price', bar_count=300, frequency="1d").mean()
# Trading logic
if short_mavg > long_mavg:
# order_target orders as many shares as needed to
# achieve the desired number of shares.
order_target(context.asset, 100)
elif short_mavg < long_mavg:
order_target(context.asset, 0)
# Save values for later inspection
record(AAPL=data.current(context.asset, 'price'),
short_mavg=short_mavg,
long_mavg=long_mavg)
def analyze(context, perf):
fig = plt.figure()
ax1 = fig.add_subplot(211)
perf.portfolio_value.plot(ax=ax1)
ax1.set_ylabel('portfolio value in $')
ax2 = fig.add_subplot(212)
perf['AAPL'].plot(ax=ax2)
perf[['short_mavg', 'long_mavg']].plot(ax=ax2)
perf_trans = perf.ix[[t != [] for t in perf.transactions]]
buys = perf_trans.ix[[t[0]['amount'] > 0 for t in perf_trans.transactions]]
sells = perf_trans.ix[
[t[0]['amount'] < 0 for t in perf_trans.transactions]]
ax2.plot(buys.index, perf.short_mavg.ix[buys.index],
'^', markersize=10, color='m')
ax2.plot(sells.index, perf.short_mavg.ix[sells.index],
'v', markersize=10, color='k')
ax2.set_ylabel('price in $')
plt.legend(loc=0)
plt.show()
# # Abhinay's Section
# In[ ]:
get_ipython().system('pip install stocknews')
# In[ ]:
from stocknews import StockNews
# In[ ]:
# In[ ]:
scraper.find('div', {'class', 'My(6px) Pos(r) smartphone_Mt(6px)'}).find('span').text
# In[ ]:
# # John and Dhruv's Section
# In[ ]:
from google.colab import drive
drive.mount('/content/drive')
# In[ ]:
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.svm import SVR
from sklearn.model_selection import train_test_split
import pandas as pd
from sklearn.metrics import mean_squared_error, r2_score
import matplotlib.pyplot as plt
import os
# plt.style.use('fivethirtyeight')
# In[ ]:
# df = pd.read_csv('/content/drive/My Drive/AI Stock Predictor Project Group/data/aapl.csv', sep = ',', header = 0)
df = pd.read_csv('aapl.csv',sep = ',', header = 0)
#print(df.tail())
# In[ ]:
df.shape
plt.figure(figsize=(16,8))
plt.title('Close Price History')
plt.plot(df['Close'])
plt.xlabel('Date', fontsize=18)
plt.ylabel('Close Price USD ($)', fontsize=18)
plt.show()
# In[ ]:
print(df.tail())
# In[ ]:
# Create independent Data set (X)
# Convert dataframe to numpy array
# X = np.array(df)
# X = df['Close']
# converting list to array
X = np.array(df['Close'])
X = np.reshape(X, (-1, 1))
# print(Temp)
# Remove the last 'n' rows
# X = X[:-forecast_out]
print(X)
# In[ ]:
# Create dependent data set (y)
# Convert the dataframe to numpy array (All of the values including NaN's)
y = np.array(df['Prediction'])
# Get all of the y values except the last n rows
# y = y[:-forecast_out]
print(y)
# In[ ]:
# Split the data into 80% training and 20& testing
# x_train, x_test, y_train, y_test = train_test_split(df, y, test_size=0.2)
# x_train1 = np.array(x_train.drop(['Sentiment','Date', 'Prediction'], axis=1))
# x_test1 = np.array(x_test.drop(['Sentiment','Date', 'Prediction'], axis=1))
x_train1 = np.array(df.drop(['Date', 'Prediction'],1))[:-40]
x_test1 = np.array(df.drop(['Date', 'Prediction'],1))[-40:]
# Split the data into training/testing sets
x_train = X[:-40]
x_test = X[-40:]
# Split the targets into training/testing sets
y_train = y[:-40]
y_test = y[-40:]
print(x_train)
print(x_test)
print(y_train)
print(y_test)
# In[ ]:
# # Create and train the Support Vector Machine (Regressor)
# svr_rbf = SVR(kernel="rbf", C=1e3, gamma=0.1)
# svr_rbf.fit(x_train, y_train)
# In[ ]:
# # Test Model: Score returns the coefficient of determination R^2 of the prediction
# # # The best possible score is 1.0
# svm_confidence = svr_rbf.score(x_test, y_test)
# print("svm confidence: ", svm_confidence)
# In[ ]:
# Create and train the Linear Regression Model
lr = LinearRegression()
# Train the Model
lr.fit(x_train1, y_train)
# In[ ]:
# Test Model: Score returns the coefficient of determination R^2 of the prediction
# The best possible score is 1.0
lr_confidence = lr.score(x_test1, y_test)
print("lr confidence: ", lr_confidence)
# In[ ]:
# # Print linear regression model predictions for the next n days
# lr_prediction = lr.predict(x_test)
# print(lr_prediction)
# CODE #####################################################################################
# Make predictions using the testing set
# x_forecast is the last row of the data, which we ant to predict
x_forecast = np.array(df.drop(['Date', 'Prediction'],1))[-1:]
print(x_forecast)
lr_prediction = lr.predict(x_forecast)
print('Prediction for the 1 day out:', lr_prediction)
# Print SVR model predictions
# svm_prediction = svr_rbf.predict(x_forecast)
# print(svm_prediction)
# In[ ]:
lr_prediction = lr.predict(x_test1)
print(lr_prediction)
# lr_prediction = scalar.inverse_transform(lr_prediction)
# train = df[:x_train1]
# valid = df[x_train1:]
train = x_train1
valid = df.drop(['Date', 'Prediction'],1)[-40:]
valid['Predictions'] = lr_prediction
# Visulaize the date
plt.figure(figsize=(16,8))
plt.title('Model')
plt.xlabel('Date', fontsize=18)
plt.ylabel('Close Price USD ($)', fontsize=18)
plt.plot(df['Close'])
plt.plot(valid[['Close', 'Predictions']])
plt.legend(['Train', 'Val', 'Predictions'])
plt.show()
# In[ ]:
lr_prediction = lr.predict(x_test1)
print(lr_prediction)
# The coefficients
print('Coefficients: \n', lr.coef_)
# The mean squared error
print('Mean squared error: %.2f'
% mean_squared_error(y_test, lr_prediction))
# The coefficient of determination: 1 is perfect prediction
print('Coefficient of determination: %.2f'
% r2_score(y_test, lr_prediction))
# Prediction is black line, actual is blue dot
plt.plot(x_test['Date'], lr_prediction, color='black')
plt.plot_date(x_test['Date'], x_test['Close'], color='blue', linewidth=3)
plt.xticks(())
plt.yticks(())
plt.show()
# In[ ]:
# Set x_forecast equal to the last n row of the original data set from Close column
x_forecast = np.array(df.drop(['Sentiment', 'Date', 'Prediction'],1))[-1:]
print(x_forecast)
# # John's Section
# In[ ]:
import urllib.request, json
with urllib.request.urlopen('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=AMZN&apikey=RKHOCKAPF9H87FQQ') as response:
data = json.loads(response.read())
meta=data["Meta Data"]
data=data["Time Series (Daily)"]
print(meta)
print(data)
# In[ ]:
# # Dhruv's Section
# In[ ]:
import math
import pandas_datareader as web
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
# In[ ]:
# Get the stock quote
#df = pd.read_csv('aapl.csv',sep = ',', header = 0)
# print(type(df))
# print(df.tail())
n = 60
#df = web.DataReader('AAPL', data_source='yahoo', start='2012-01-01', end='2019-12-17')
# df
# In[ ]:
# Visualize the data
# df.shape
plt.figure(figsize=(16,8))
plt.title('Close Price History')
plt.plot(df['Close'])
plt.xlabel('Date', fontsize=18)
plt.ylabel('Close Price USD ($)', fontsize=18)
plt.show()
# In[ ]:
#Create a new Dataframe
df = web.DataReader('AAPL', data_source = 'yahoo', start = '2015-01-01', end = '2020-10-01')
data = df[['Close']]
print(data.values)
#print(data.values)
#print(len(data))
# print(type(data))
#Convert to numpy array
dataset = np.array(data.values)
dataset = np.reshape(dataset, (-1, 1))
#print(dataset)
#print(dataset)
#Get the number of rows to train the model
training_data_len = math.ceil(len(data) * .8)
# In[ ]:
#Scale the data
scaler = MinMaxScaler(feature_range=(0,1))
scaled_data = scaler.fit_transform(dataset)
print(scaled_data)
# In[ ]:
#Create the scaled training data set
train_data = scaled_data[0:training_data_len, :]
#Split the data into x_train and y_train
x_train = []
y_train = []
for i in range(n, len(train_data)):
x_train.append(train_data[i-n:i, 0])
y_train.append(train_data[i, 0])
# In[ ]:
#Convert the x_train and y_train to numpy arrays
x_train, y_train = np.array(x_train), np.array(y_train)
#Reshape the data
# (#samples, timesteps, and features)
#x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
#x_train.shape
# In[ ]:
#Build the LSTM model
model = Sequential()
# 50 neurons, (timesteps, features)
model.add(LSTM(50, return_sequences = True, input_shape = (x_train.shape[1], 1)))
model.add(LSTM(50, return_sequences = False))
#model.add(LSTM(50))
model.add(Dense(25))
model.add(Dense(1))
# In[ ]:
model.compile(optimizer = 'adam', loss = 'mean_squared_error')
# In[ ]:
#Train the model
model.fit(x_train, y_train, batch_size = 1, epochs = 5)
# In[ ]:
#Create the testing dataset
#Create a new array containing scaled values from index size-n to size
# [last n values, all the columns]
test_data = scaled_data[training_data_len - n:, :]
#Create the datasets x_test, y_test
x_test = []
# 61st values
y_test = dataset[training_data_len:, :]
for i in range(n, len(test_data)):
# Past n values
x_test.append(test_data[i-n:i, 0])
# In[ ]:
#convert to numpy array
x_test = np.array(x_test)
print(x_test.shape)
# In[ ]:
#Reshape the data for the LSTM model to 3-D
x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))
# In[ ]:
#Get the models predicted price and values
print(x_test[0])
#predictions = model.predict(x_test)
#print(predictions)
# We want predictions to contain the same values as y_test dataset
#predictions = scaler.inverse_transform(predictions)
#print(predictions)
# print(type(predictions))
# In[ ]:
#Get the root mean squred error (RMSE) - lower the better
rmse = np.sqrt(np.mean(predictions - y_test)**2)
print(rmse)
# In[ ]:
#Plot the data
#print(data[:56])
train = data[:training_data_len]
valid = data[training_data_len:]
#train = data.loc[:'2020-09-01']
#valid = data.loc['2020-09-01':]
#print(data.loc[:'2020-09-01'])
valid['Predictions'] = predictions
#print(type(train))
#print(type(valid))
#predictions_series = []
#indices = list(range(162, 202))
#for prediction in predictions:
# predictions_series.append(prediction)
#predictions = pd.Series(predictions_series, index = indices)
# Visulaize the date
plt.figure(figsize=(16,8))
plt.title('Model')
plt.xlabel('Date', fontsize=18)
plt.ylabel('Close Price USD ($)', fontsize=18)
plt.plot(train['Close'])
plt.plot(valid['Close'])
plt.plot(valid['Predictions'])
plt.legend(['Train', 'Val', 'Predictions'], loc='lower right')
plt.show()
# In[ ]:
print(valid[[180]], predictions[[180]])
# In[ ]:
#Get the quote
# apple_quote = web.DataReader('AAPL', data_source="yahoo", start)
stock_quote = pd.read_csv('/content/aapl.csv',sep = ',', header = 0)
new_df = stock_quote.filter(['Close'])
last_n_days = new_df[-n:].values
last_n_days_scaled = scaler.transform(last_n_days)
X_test = []
X_test.append(last_n_days_scaled)
X_test = np.array(X_test)
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
pred_price = model.predict(X_test)
pred_price = scaler.inverse_transform(pred_price)
print(pred_price)
|
02960d761aec2401238739d0c6cee1a6a5b54571 | Wowol/Blackjack-Reinforcement-Learning | /game/card.py | 333 | 3.875 | 4 | from random import randint
class Card:
"""Generate one card and store its number in value field
"""
value = 0
def __init__(self):
number = randint(1, 13)
if number == 1:
self.value = 11
elif number > 10:
self.value = 10
else:
self.value = number
|
d81541f0bfae3d2a5323f517300afa9501bdf685 | ntshcalleia/Listas_AlgGraf_2017_2 | /lista2/questao5.py | 1,868 | 3.734375 | 4 | import math
def troco(T):
moedas = {
1: 0,
5: 0,
10: 0,
25: 0,
50: 0,
100: 0
}
while(T > 0): # Criterio guloso: escolher maior moeda possivel. Colocar quantas der dela
if T >= 100:
moedas[100] = int(math.floor(T/100))
T = T % 100
elif T >= 50:
moedas[50] = int(math.floor(T/50))
T = T % 50
elif T >= 25:
moedas[25] = int(math.floor(T/25))
T = T % 25
elif T >= 10:
moedas[10] = int(math.floor(T/10))
T = T % 10
elif T >= 5:
moedas[5] = int(math.floor(T/5))
T = T % 5
elif T >= 1:
moedas[1] = T
T = 0
return moedas
def main():
T = int(input("T = "))
moedas = troco(T)
print("{} pode ser representado por:".format(T))
if moedas[1] != 0:
if moedas[1] == 1:
print("1 moeda de 1")
else:
print("{} moedas de 1".format(moedas[1]))
if moedas[5] != 0:
if moedas[5] == 1:
print("1 moeda de 5")
else:
print("{} moedas de 5".format(moedas[5]))
if moedas[10] != 0:
if moedas[10] == 1:
print("1 moeda de 10")
else:
print("{} moedas de 10".format(moedas[10]))
if moedas[25] != 0:
if moedas[25] == 1:
print("1 moeda de 25")
else:
print("{} moedas de 25".format(moedas[25]))
if moedas[50] != 0:
if moedas[50] == 1:
print("1 moeda de 50")
else:
print("{} moedas de 50".format(moedas[50]))
if moedas[100] != 0:
if moedas[100] == 1:
print("1 moeda de 100")
else:
print("{} moedas de 100".format(moedas[100]))
if __name__ == '__main__':
main() |
f8576b094f7f0676433b035d8630f2a64477eb85 | Huitzoo/Rosalind_Bioinformatics | /rabbits.py | 299 | 3.671875 | 4 | def main():
months = int(input('Enter the months'))
litters = int(input('Enter the number of litters'))
fibo = [1,1]
if months <= 2:
print('1')
else:
for i in range(2,months):
fibo.append(litters*fibo[i-2]+fibo[i-1])
print(fibo)
main()
|
e9f2417dd3507d88cfb24b12c8c927c259e7fc91 | halesahinn/Searching-Reverse-Complement-of-DNA-Motif | /Project1_150114063_150116841_150114077.py | 2,536 | 3.5625 | 4 | #Büşra YAŞAR-150114063
#Emine Feyza MEMİŞ-150114077
#Hale ŞAHİN-150116841
import operator
import re
import os
import sys
from os import path
#print("Please enter the input file path :")
#path = input()
def reverse(s):
str = ""
for i in s:
str = i + str
return str
def readFile(file_path):
path2 = path.relpath(file_path)
with open(path2) as f:
text = f.read()
printText(text)
def printText(text):
# Extract your code into a function and print header for current kmer
#print("%s\n################################" %name)
kmers = {}
for i in range(len(text) - k + 1):
kmer = text[i:i+k]
if kmer in kmers:
kmers[kmer] += 1
else:
kmers[kmer] = 1
print ('Inputs: k=%d,x=%d' % (k,x))
print ('Outputs:')
print ('%d-mer:\t' % (k))
i = 0
occuredKmers = {}
passAmount = 0
for kmer, count in kmers.items():
if count >= x:
print (kmer)
occuredKmers[i] = kmer
i = i + 1
passAmount = passAmount + 1
if passAmount == 0:
print('There is no such %d-mer which appears more than %d times for the input DNA string.' % (k,x))
print ('Reverse Complement: ')
j = 0
reverseComplement = ""
noReverse = 0
occurence = 0
while j < len(occuredKmers):
kmer = occuredKmers[j]
reverseKmer = reverse(kmer)
for base in reverseKmer:
if base == 'A':
base = 'T'
elif base == 'T':
base = 'A'
elif base == 'G':
base = 'C'
elif base == 'C':
base = 'G'
reverseComplement = reverseComplement + base
for i in range(len(text) - k + 1):
kmer = text[i:i+k]
if reverseComplement == kmer:
occurence = occurence +1
if occurence > 0:
print (reverseComplement + ' appearing' + ' %d times' % (occurence))
noReverse = noReverse + 1
j = j + 1
occurence = 0
reverseComplement=""
if noReverse == 0:
print ('There is no reverse complement %d-mers in DNA string.' % (k))
if __name__ == "__main__":
print("Please enter the k value: ")
k =int(input())
print("Please enter the x value: ")
x =int(input())
print("Please enter the input file path:")
file_path = input()
readFile(file_path)
|
235a6863fd259e561c92567af98b6ccf29a7fee0 | optimizely/pycon2019 | /lambda_calculus_seminar/pylambda1.py | 202 | 4.09375 | 4 | '''
'''
f = lambda x: 3*x + 1
f(2) # eli5 - you replace the x with the 2
f(4)
'''
def f(x):
return x
def f(x):
return x(x)
'''
def f(x):
def g(y):
return x(y)
return g
|
314411a03d4703ed284d6f12d7f1c356eab8a094 | pandast3ph4n/password-generator | /passgen.py | 1,071 | 3.5625 | 4 | import random
import string
import tkinter as tk
pool = string.ascii_letters + string.digits + string.punctuation
def generate_password(length=12, random_length=False):
if random_length:
length = random.randrange(10, 16)
if length < 4:
print('hey din dust.... ikke noe tull')
return False
elif length > 1000:
print('yo, for langt... thats what she said!')
return False
while True:
password = random.choices(pool, k=length)
password = ''.join(password)
if not any(character in string.digits for character in password):
continue
if not any(character in string.punctuation for character in password):
continue
if not any(character in string.ascii_lowercase for character in password):
continue
if not any(character in string.ascii_uppercase for character in password):
continue
break
return password
if __name__ == "__main__":
password = generate_password()
print(generate_password())
|
8a5bb6ad81f3f444da59c72d9c3f3f4dbaf9cfa3 | ccmien/Fundamentals-of-Computing-Projects | /Word Wrangler.py | 4,042 | 4.0625 | 4 | """
Student code for Word Wrangler game
"""
import urllib2
import codeskulptor
import poc_wrangler_provided as provided
WORDFILE = "assets_scrabble_words3.txt"
# Functions to manipulate ordered word lists
def remove_duplicates(list1):
"""
Eliminate duplicates in a sorted list.
Returns a new sorted list with the same elements in list1, but
with no duplicates.
This function can be iterative.
"""
if len(list1) == 0:
return list1
if len(list1) == 1:
return [list1[0]]
elif list1[len(list1)/2 -1] == list1[len(list1)/2]:
return remove_duplicates(list1[:len(list1)/2]) + remove_duplicates(list1[len(list1)/2 + 1:])
else:
return remove_duplicates(list1[:len(list1)/2]) + remove_duplicates(list1[len(list1)/2:])
def intersect(list1, list2):
"""
Compute the intersection of two sorted lists.
Returns a new sorted list containing only elements that are in
both list1 and list2.
This function can be iterative.
"""
if len(list1) == 0 or len(list2) == 0:
return []
index1 = 0
index2 = 0
intersect_list = []
while index1 < len(list1) and index2 < len(list2):
if list1[index1] == list2[index2]:
intersect_list.append(list1[index1])
index1 += 1;
index2 += 1;
elif list1[index1]<list2[index2]:
index1 += 1
else:
index2 += 1
return intersect_list
# Functions to perform merge sort
def merge(list1, list2):
"""
Merge two sorted lists.
Returns a new sorted list containing all of the elements that
are in either list1 and list2.
This function can be iterative.
"""
merged_list = list2
index_add = 0
for (index1, item1) in enumerate(list1):
for index2 in range(index_add, len(list2)):
if index2 == len(list2) - 1 and item1 >= list2[index2]:
merged_list = merged_list + [item1]
if item1 < list2[index2]:
merged_list = merged_list[:(index2+index1)] + [item1] + merged_list[(index2+index1):]
index_add = index2
break
return merged_list
def merge_sort(list1):
"""
Sort the elements of list1.
Return a new sorted list with the same elements as list1.
This function should be recursive.
"""
if len(list1) < 2:
return list1
if len(list1) == 2:
return merge([list1[0]], [list1[1]])
else:
return merge(merge_sort(list1[:len(list1)/2]), merge_sort(list1[len(list1)/2:]))
# Function to generate all strings for the word wrangler game
def gen_all_strings(word):
"""
Generate all strings that can be composed from the letters in word
in any order.
Returns a list of all strings that can be formed from the letters
in word.
This function should be recursive.
"""
if len(word) == 0:
return [""]
if len(word) == 1:
return ["", word]
else:
first = word[0]
rest = word[1:]
rest_strings = gen_all_strings(rest)
new_strings = []
for string in rest_strings:
for index_s in range(len(string) + 1):
new_strings.append(str(string[:index_s]) + first + str(string[index_s:]))
return new_strings + rest_strings
# Function to load words from a file
def load_words(filename):
"""
Load word list from the file named filename.
Returns a list of strings.
"""
res = []
url = codeskulptor.file2url(filename)
netfile = urllib2.urlopen(url)
for line in netfile.readlines():
res.append(line[:-1])
return res
def run():
"""
Run game.
"""
words = load_words(WORDFILE)
wrangler = provided.WordWrangler(words, remove_duplicates,
intersect, merge_sort,
gen_all_strings)
provided.run_game(wrangler)
# Uncomment when you are ready to try the game
run() |
ae97a6da42d85c675d029aacdd0991f18ec08c6c | SofiaDaniela/Mision_02 | /extraGalletas.py | 446 | 3.890625 | 4 | # Autor: Sofía Daniela Méndez Sandoval, A01242259
# Descripción: Cantidad de Ingredientes para # de Galletas
cantidad = int(input("¿Cuántas galletas realizará?: "))
azucar = (cantidad*1.5)/48
mantequilla = cantidad/48
harina = (cantidad*2.75)/48
print("Para realizar el determinado número de galletas, necesitará: ")
print("Azúcar: ", "%.2f" % azucar, "tazas")
print("Mantequilla: ", "%.2f" % mantequilla, "tazas")
print("Harina: ", "%.2f" % harina, "tazas")
|
c4061364eb081676fcaa1c2720decd4187d1eef9 | vamsikvs1994/Web_crawler | /word_counter.py | 3,854 | 4.09375 | 4 | '''
Author: Venkata Sai Vamsi Komaravolu
Date: 30th December 2017
File Name: word_counter.py
Description:
This python program performs the word count in a web-page given the URL. It makes use of certain
methods and packages available in python.
The working of this program classified as mentioned below:
1. Open the given URL
2. Read the web-page and using the utf-8 format decoding
3. Remove the tags in the web page
4. Remove all the non-alphanumeric characters in the word string
5. Count the words and form a dictionary
6. Finally sorting and displaying the top 5 most used words in the web-page
'''
import re #regular expression package
from urllib.request import urlopen #urlopen is used to open the web-page using the given URL
def main(url):
opened_url = urlopen(url) #open the given web-page from the given url
decoded_url = opened_url.read().decode('utf-8') #read the web-page and decode according to utf-8 format
text = remove_tags(decoded_url).lower() #remove the tags in the webpage and lower() makes all case-based characters lowercased
words = remove_non_alp_num(text) #remove all non-alphanumeric characters
dict = word_counter(words) #creates a dictionary with the words and their count
sorted_words = sort_counter(dict) #sorts the dictionary and returns the words and their count in descending order
count=0
for s in sorted_words: #displays the 5 top most used words in the given web-page
if(count<5):
print(str(s))
count+=1
return
def remove_tags(page_info): #method to remove the tags in the the given web-page
start = page_info.find("</a>")
end = page_info.rfind("</li>") #rfind() returns the last index where the substring is found
page_info = page_info[start:end]
ins = 0
word_form = ''
for char in page_info: # creating a word form from the characters
if char == '<': # word string is between the < and > characters
ins = 1
elif (ins == 1 and char == '>'):
ins = 0
elif ins == 1:
continue
else:
word_form += char
return word_form
def remove_non_alp_num(text): #method for removing all non-alphanumeric characters using UNICODE definition
return re.compile(r'\W+', re.UNICODE).split(text) #re.compile() is used to compile a regular expression pattern into a regular expression object, which can be used for matching using its match(), search() and other methods
def word_counter(words): #method for creating a Python dictionary with words and their respective count
wordfreq = [words.count(p) for p in words]
return dict(zip(words,wordfreq))
def sort_counter(dict): #method for sorting and displaying the words with their count in descending order
out = [(dict[key], key) for key in dict]
out.sort()
out.reverse()
return out
|
2aefeb397fb1ea15bc2519fa34be929718bf4a9a | agoldh20/exercism | /python/pangram/pangram.py | 249 | 3.609375 | 4 | import re
def is_pangram(sentence):
sentence = sentence.lower()
sentence = re.sub(r'([^a-z])', "", sentence)
if len(list(set(sentence))) < 26:
return False
elif len(list(set(sentence))) == 26:
return True
pass
|
3eb68789808cd0ae37f3509e941521452b9141f7 | IlkoAng/Python-OOP-Softuni | /exercise1-first-steps-oop/04-cup.py | 407 | 3.59375 | 4 | class Cup:
def __init__(self, size, quantity):
self.size = size
self.quantity = quantity
def fill(self, mil):
if self.size >= self.quantity + mil:
self.quantity += mil
def status(self):
result = self.size - self.quantity
return result
cup = Cup(100, 50)
print(cup.status())
cup.fill(40)
cup.fill(20)
print(cup.status())
|
cbc85235c505b37df1c409b2a9b9a070ae497e42 | liu-creator/python__basic | /Py_mysql/一次插入多条数据.py | 1,135 | 3.59375 | 4 | '''插入100条数据到数据库(一次插入多条)'''
import pymysql
import string,random
#打开数据库连接
conn=pymysql.connect('localhost','root','123456')
conn.select_db('testdb')
#获取游标
cur=conn.cursor()
#创建user表
cur.execute('drop table if exists user')
sql="""CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`age` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=0"""
cur.execute(sql)
#修改前查询所有数据
cur.execute("select * from user;")
print('修改前的数据为:')
for res in cur.fetchall():
print (res)
print ('*'*40)
#循环插入数据
words=list(string.ascii_letters)
sql="insert into user values(%s,%s,%s)"
random.shuffle(words)#打乱顺序
cur.executemany(sql,[(i+1,"".join(words[:5]),random.randint(0,80)) for i in range(100) ])
#插入100条后查询所有数据
cur.execute("select * from user;")
print('修改后的数据为:')
for res in cur.fetchall():
print (res)
print ('*'*40)
cur.close()
conn.commit()
conn.close()
print('sql执行成功')
|
54873a969653a53afa1be805c1c8b96dcd77daa3 | MattBJ/Radar_Object_Detection_System | /Data_Simulations/Sampled_Frequency_Data_out.py | 9,078 | 3.5 | 4 | # Matthew Bailey
# Simulation python code:
# Purpose: Generate 3 sampled frequency data sets that represent a moving ordinance and 2 stationary objects in a 3D Area
# Secondary purpose: Ditch the stationary objects (explain how it would've worked) - Use only x,x',y, and y' and assume stationary Z, as everything would've been stationary
# Vision: We have 1 transmitting radar, and 3 receivers. The receivers are set up in an equilateral triangle configuration, with the transmitter in the center.
# There, hopefully, 2 objects that are stationary (represented as single points), that will contribute constant frequency information
# There will be an ordinance traveling from the near edge of the field to a close point next to the radar dish
# Important information: Bandwidth is 100 MHz, the chirp is 100 microseconds (10 KHz)
# Chirp waveform: Triangulat (so from 0 modulation to 100 MHz is 50uS)
# Delta Frequency = 600 GHz
# Time per freq. change = 1.666 pico seconds
# Arbitrary distance constraint: 6 meters --> Roughly 25KHz difference (there and back = 12 meters)
# Constraints: C (Speed of light) = 3e8
# Arbitrary distance max = 6 meters (from any receiver)
# The distance to any object to any receiver is calculated by the following:
# D_TX = sqrt((TX_x - Obj_x)^2 + (TX_y - Obj_y)^2 + (TX_z - Obj_z)^2)
# D_RXn = sqrt((RX_x - Obj_x)^2 + (RX_y - Obj_y)^2 + (RX_z - Obj_z)^2)
# D_Tot = D_TX + D_RXn
# Converting distance to frequency information:
# (D_tot / c) * 600 GHz = Frequency_Data
# For the stationary objects, this can simply be calculated over the entirety of the large sample set
# For the ordinance, the distance will be dynamically changing
# For each sample in time, a new distance must be calculated and thus the corresponding frequency changes (should steadily get lower)
# Each data set will be represented by a vector of scalars which are set equal to the 3 CURRENT frequency components multiplied by time
# FIRST CHALLENGE: Create a varying frequency dataset (1 HZ to 1KHz, changes once per ____ samples)
# make the sampling extremely high frequency (1 nanosecond)
# figure out how to change frequencies dynamically over time WITHOUT jumping around
# after 1000 samples, change frequency
# np.cos() requires an array of data (time set), then outputs an array of equal size. will always take that last element and append it
import numpy as np
import matplotlib.pyplot as plt
import copy
def freq_data(freq,sampling_freq,sample_num): # Takes the frequency, sampling frequency, and the time instance of the data required
# t = np.arange(0,(sample_num+1)+(1/sampling_freq),(1/sampling_freq))
# print(t)
out = np.cos(2*(np.pi)*(freq)*(sample_num / sampling_freq))
# print(out)
# return out[(sample_num)*(sampling_freq)] # the last element
return out
# THE CODE BELOW WAS ME TESTING DYNAMICALLY CHANGING FREQUENCY OF A SIGNAL AS THE SIGNAL IS BEING SAMPLED
# frequency_jumps = np.arange(50,151)
# print(frequency_jumps.shape)
# print(frequency_jumps)
# print(frequency_jumps[999])
# j = 0
# data_buffer = []
# sampling_freq = 1000 # 1ksps
# N = 2224
# freq_jump_prev = 0
# freq_jump_next = (2/50) * 1000
# print(int(52.6))
# for i in range(N):
# print(i)
# if(freq_jump_next == i):
# j += 1
# freq_jump_prev = freq_jump_next
# freq_jump_next = freq_jump_prev + (2/frequency_jumps[j]) * 1000
# freq_jump_next = int((freq_jump_next + 0.5))
# print(int(freq_jump_next))
# print('Frequency: ',frequency_jumps[j])
# data_buffer.append(freq_data(frequency_jumps[j],1000,i))
# data_buffer = np.array(data_buffer)
# Now display the sinusoids over the time
# fig = plt.figure()
# ax = fig.add_subplot(1, 1, 1)
# plt.plot(np.arange(0,N),data_buffer,'r')
# plt.show()
# First attempt, all 1's...
# Generate the 2 object frequencies for the 3 receivers --> Will probably get rid of it
# For now let's just do the ordinance frequencies
# nf_pos = 0.1
TX_pos = np.array([0,1,0])
RX1_pos = np.array([0,1,0])
RX2_pos = np.array([0,0,((4/3)**(1/2))/2])
RX3_pos = np.array([0,0,-((4/3)**(1/2))/2])
x_0 = 4
x_f = 1
sampling_freq = 100000
samples = int(sampling_freq*.9)
print(samples)
# dt = 0.0000001 # let's make it real as possible --> 10 Msps
dt = 1/sampling_freq
dx_0 = (x_f - x_0)/(dt*samples)
y_0 = 5
y_f = 3
# dt = 1/sampling_freq
dy_0 = 2.18777777777 # per second
def generate_y_data(y_0, v_0, nf_pos, nf_vel,dt,samples): # count is in milliseconds
# time step will be 1 millisecond
a = -9.8 # meters per second
# a = -9.8e-3 # per milisecond
v_0_mili = copy.copy(v_0)
v_0_mili = v_0_mili/1000
# v_0_mili *= 1e-3 # get in velocity per milisecond
count = (-2*v_0)/a # count is in MILISECONDS
count = int(round(count*1000))
# return np.array([np.random.randn()*nf_pos + y_0 + v_0*i/1000 + (1/2)*a*((i/1000)**2) for i in range(count)]), count, np.array([y_0 + v_0*i/1000 + (1/2)*a*((i/1000)**2) for i in range(count)]), np.array([np.random.randn()*nf_vel + v_0 + (a)*(i/1000) for i in range(count)]), np.array([v_0 + (a)*(i/1000) for i in range(count)])
return np.array([y_0 + v_0 * (i*dt) + (1/2)*a*((i*dt)**2) for i in range(samples)])
actual_x = np.array([x_0 + (dx_0)*(i*dt) for i in range(samples)])
actual_y = generate_y_data(y_0,dy_0,0,0,dt,samples)
# actual_x = np.ones(samples) * x_0
# actual_y = np.ones(samples) * y_0 # let's just keep it stationary
# Try and work with the generation using stationary object!
print(actual_x.shape)
print(actual_y.shape)
TX_x = np.ones(samples) * 0
TX_y = np.ones(samples) * 0.5
RX1_x = RX1_pos[0] * np.ones(samples)
RX1_y = RX1_pos[1] * np.ones(samples)
RX2_x = RX2_pos[0] * np.ones(samples)
RX2_y = RX2_pos[1] * np.ones(samples)
RX3_x = RX3_pos[0] * np.ones(samples)
RX3_y = RX3_pos[1] * np.ones(samples)
dist_TX = ((TX_x - actual_x)**2+(TX_y - actual_y)**2)**(1/2)
dist_RX1 = ((RX1_x - actual_x)**2 + (RX1_y - actual_x)**2)**(1/2)
dist_RX2 = ((RX2_x - actual_x)**2 + (RX2_y - actual_x)**2)**(1/2)
dist_RX3 = ((RX3_x - actual_x)**2 + (RX3_y - actual_x)**2)**(1/2)
# Now have all the distance information from the separate RX's
# Now convert the 3 buffers to frequency data! --> Total distance * the frequency rate change
F_1 = (dist_TX + dist_RX1)/(3e8) * 6e11
F_2 = (dist_TX + dist_RX2)/(3e8) * 6e11
F_3 = (dist_TX + dist_RX3)/(3e8) * 6e11
# print(D_1)
# Turn the 3 buffers from frequency data into an actual signal
print(int(1/dt))
k = 0 # Responsible for 'batch programming'
print('total samples: ',samples)
print('sampling freq: ',sampling_freq)
# PROBLEM: running out of RAM space with these 900K - 64-bit (double precision) floating point arrays of frequency information
# Solution: Somehow, call these routines as FUNCTIONS (subroutines), upon return the STACK is cleared (RAM)
# 'Garbage collection doesn't happen in line' --> Need to create a function and call it (kinda like a stack!)
# With this function, return 2 things:
# 1) Return the string to append to the original string
# 2) Return the ITERATION to continue the calculation!
text_file_buf1 = open("RX1_buffer.txt","w")
text_file_buf2 = open("RX2_buffer.txt","w")
text_file_buf3 = open("RX3_buffer.txt","w")
# samples_calc = 100 # just do batches of 100
# s_sampled_1 = 'float32_t sampled_RX1[] = {'
# s_sampled_2 = 'float32_t sampled_RX2[] = {'
# s_sampled_3 = 'float32_t sampled_RX3[] = {'
s_sampled_1 = ''
s_sampled_2 = ''
s_sampled_3 = ''
# text_file_buf1.write(s_sampled_1)
# text_file_buf2.write(s_sampled_2)
# text_file_buf3.write(s_sampled_3)
def calc_write(text_file,freq,sampling_freq,sample_num):
sample_value = freq_data(freq,sampling_freq,sample_num)
s = str(sample_value) + '\n'
text_file.write(s)
for q in range(samples):
print('text_file writing, iteration: ', q, 'Frequency at q: ', F_1[q])
calc_write(text_file_buf1,F_1[q],sampling_freq,q)
calc_write(text_file_buf2,F_2[q],sampling_freq,q)
calc_write(text_file_buf3,F_3[q],sampling_freq,q)
sample_size = 512 # or 2024
true_RX1Dist_fname = "RX1_TruDist.txt"
file_true = open(true_RX1Dist_fname,'w')
for x in range(int(samples/sample_size)):
print(F_1[x*sample_size]/(6e11))
for x in range(samples):
s = str(F_1[x]/(6e11)) + '\n'
file_true.write(s)
file_true.close()
print('final x value of ordinance: ',actual_x[-1])
print('final y value of ordinance: ',actual_y[-1])
# text_file_buf1.close()
# Write a function that does the computation AND creates the string, THEN appends it to the text files
# somehow, for the last 3 files delete the last ',' then write '};' and be done!
# write the large datasets to txt files
# text_file_buf1.write()
text_file_buf1.close()
# text_file_buf2.write()
text_file_buf2.close()
# text_file_buf3.write()
text_file_buf3.close()
print(s_sampled_1)
# {number,number,number,number,....,number,number, + '};'... get rid of LAST ','
|
0a6ff68dfe1aa589b13e7baeddc216e2780ca7ec | ngantonio/DataScience-Analysis | /practicas con bases de datos/coutingDomains.py | 1,457 | 3.59375 | 4 | """ cuenta el número total de dominios de emails
y los almacena en una base de datos
"""
import sqlite3 as sql
# Iniciamos las variables de conexión, y creamos la base de datos.
connection = sql.connect('domaindb.sqlite')
cur = connection.cursor()
# Verificamos si la tabla existe, si no, la creamos.
cur.execute('DROP TABLE IF EXISTS Counts')
cur.execute('CREATE TABLE Counts (org TEXT, count INTEGER)')
file = input('Enter file name: ')
if len(file) < 1:
file = 'mbox.txt'
fh = open(file)
# Por cada linea...
for line in fh:
# Obtenemos solo las lineas que comiencen por "From: "
if not line.startswith('From: '): continue
pieces = line.split()
# Obtenemos el email
email = pieces[1]
# Para obtener el dominio del email, separamos el string por el caracter '@'
# para: [email protected] el dominio se encuentra en la pos. 1
email = email.split('@')
domain = email[1]
# Almacenamos el dominio y Preguntamos si ya existe en la DB,
# si es asi, actualiza el contador
cur.execute('SELECT count FROM Counts WHERE org = ?', (domain,))
row = cur.fetchone()
if row is None:
cur.execute('INSERT INTO Counts (org, count) VALUES(?,1)',(domain,))
else:
cur.execute('UPDATE Counts SET count = count+1 WHERE org = ?',(domain,))
connection.commit()
sqlstr = 'SELECT org, count FROM Counts ORDER BY count DESC LIMIT 10'
for row in cur.execute(sqlstr):
print(str(row[0]),row[1])
cur.close() |
492009c5e453bbcd947240576e7741225109328e | Tachone/PythonCode | /countline0007/countline0007.py | 1,154 | 3.640625 | 4 | #!/usr/bin/env python
#coding=utf-8
# 统计目录下文件的代码行数
import os
def walk_dir(path):
file_path=[]
for root,dirs,files in os.walk(path):
for f in files:
if f.lower().endswith('py'):
file_path.append(os.path.join(root,f))
return file_path
def count_codeline(path):
file_name=os.path.basename(path)
line_num=0
empty_line_num=0
note_num=0
note_flag=False
with open(path) as f:
for line in f.readlines():
line_num+=1
if line.strip().startswith('\"\"\"') and not note_flag:
note_num+=1
note_flag=True
continue
if line.strip().startswith('\"\"\"'):
note_flag=False
note_num+=1
if line.strip().startswith('#') or note_flag:
note_num+=1
if line.strip()=='':
empty_line_num+=1
print u"在%s中,共有%d行代码,其中有%d空行,有%d行注释" %(file_name,line_num,empty_line_num,note_num)
if __name__ =='__main__':
for f in walk_dir('.'):
count_codeline(f)
|
8f2417a4bd242c6372d79c5244b5af3be83ca9a2 | MahadiRahman262523/Python_Code_Part-2 | /formatted string.py | 198 | 3.875 | 4 | '''
num1 = 20
num2 = 30
print("sum is = ",num1 + num2)
'''
'''
num1 = 20
num2 = 30
print(f"{num1} + {num2} = {num1 + num2} ")
'''
print("mahadi rahman", end = " ")
print("01301442265")
|
4ee6c5e0690d7c0302b76dbebff6751bbf507c1e | MahadiRahman262523/Python_Code_Part-2 | /factorial.py | 119 | 3.953125 | 4 | n = int(input("enter any positive number = "))
fact = 1
for i in range(n) :
fact = fact*(i+1)
print(fact) |
67293e2d186feadeafd7db8ea20284a37e3b93bd | MahadiRahman262523/Python_Code_Part-2 | /sum of n number.py | 130 | 3.9375 | 4 |
n = int(input("enter any integer value = "))
sum = 0
i = 1
while i <= n :
sum = sum + i
i = i + 1
print(sum)
|
ad0b647a1611a07369624c42e3cea0484b7afd4c | flaherty-kr/DS2000HW | /conv.py | 247 | 3.96875 | 4 | # Kristen Flaherty
# Sec 01
#key parameters
#input
km = float(input('Please enter the number of kilometers:\n'))
#km to miles conversion
conv = .621
full_miles = int(km * conv)
#print full miles statement
print("The number of full miles is:", full_miles)
|
77019b16ce59e91dc2f26b3a73a6f353873b9b6c | cbstudent/Exercises | /4. Sorting/mergeSort.py | 606 | 4.03125 | 4 | def mergeSort(array):
_mergeSort(array, 0, len(array) - 1)
return array
def _mergeSort(array, lo, hi):
if lo >= hi:
return
mid = (lo + hi) // 2 + 1
_mergeSort(array, lo, mid - 1)
_mergeSort(array, mid, hi)
merge(array, lo, mid, hi)
def merge(array, lo, mid, hi):
copy = array[:]
p1 = lo
p2 = mid
cur = lo
while cur <= hi:
if p1 < mid and p2 <= hi:
if copy[p1] < copy[p2]:
array[cur] = copy[p1]
p1 += 1
else:
array[cur] = copy[p2]
p2 += 1
elif p1 < mid:
array[cur] = copy[p1]
p1 += 1
else:
array[cur] = copy[p2]
p2 += 1
cur += 1
|
837e845a9c83a16b34c9581c2bad17b55eda0102 | cbstudent/Exercises | /3. Arrays/threeNumberSum.py | 599 | 3.96875 | 4 | def threeNumberSum(array, targetSum):
# Sort the array (can be sorted in place, because we don't care about the original indices)
array.sort()
res = []
# Use two pointers, one starting from the left, and one starting from the right
for idx, curr in enumerate(array):
i = idx + 1
j = len(array) - 1
while i < j:
currSum = curr + array[i] + array[j]
if currSum < targetSum:
i += 1
elif currSum > targetSum:
j -= 1
elif currSum == targetSum:
ares = sorted([curr, array[i], array[j]])
res.append(ares)
i += 1
j -= 1
return sorted(res)
|
9c5cd49ac894af1653d42d202d98446ac5814a77 | cbstudent/Exercises | /7. Graphs/hasSingleCycle.py | 441 | 3.71875 | 4 | def hasSingleCycle(array):
# Write your code here.
idx = 0
counter = 0
while counter < len(array):
# If we've jumped more than once and we find ourselves back at the starting index, we haven't visited each element
if counter > 0 and idx == 0:
return False
jump = array[idx]
idx = (idx + jump) % len(array)
if idx < 0:
idx = idx + len(array)
counter += 1
if idx == 0:
return True
else:
return False
|
19dcfff0b8fc4eaa073e604d83e2519e862d5353 | SteventsStuff/ElementaryTasks | /tests/t3_triangles_test.py | 1,728 | 3.578125 | 4 | #!/usr/bin/env python3
import unittest
import tasks.t3_triangles as triang
from tasks.t3_triangles import Triangle
class TestTriangle(unittest.TestCase):
def setUp(self) -> None:
self.triangle_1 = Triangle("tr1", 12, 15, 14)
self.triangle_2 = Triangle("tr2", 10.5, 13.5, 12.5)
self.triangle_3 = Triangle("tr3", 2, 5, 4)
self.triangle_4 = Triangle("test_1", 7, 10.3, 9)
# testing Triangle class
def test_Triangle_constructor(self):
self.assertEqual(("test_1", 7, 10.3, 9),
(self.triangle_4._name, self.triangle_4.a_size,
self.triangle_4.b_size, self.triangle_4.c_size))
def test_validate_triangle_size_perfect_input(self):
self.assertEqual(None, self.triangle_4.validate_triangle_size())
# idk
# def test_validate_triangle_size_incorrect_input(self):
# self.assertRaises(ValueError, Triangle("test_error", 7, 1, 9))
def test_get_area(self):
self.assertEqual(78.92678569408487, self.triangle_1.get_area())
def test_get_name(self):
self.assertEqual("tr3", self.triangle_3.get_name())
# testing print func
def test_print_triangles_empty_list(self):
expected = "There are no triangles in this list!"
self.assertEqual(expected, triang.print_triangles([]))
def test_print_triangles_perfect_list(self):
triangle_list = [self.triangle_1, self.triangle_2,
self.triangle_3, self.triangle_4]
expected = """1. [tr1]: 78.93cm
2. [tr2]: 62.15cm
3. [test_1]: 30.93cm
4. [tr3]: 3.80cm
"""
self.assertEqual(expected, triang.print_triangles(triangle_list))
if __name__ == "__main__":
unittest.main()
|
bb3e8df598c01c38d5982158ec26c99f8e77fb3c | blaise594/PythonPuzzles | /printStatements.py | 687 | 4.09375 | 4 | #The Purpose of this program is to demonstrate print statements
# Print full name
print("My name is Daniel Rogers")
# Print the name of the function that converts a string to a floating point number
print("The float() function can convert strings to a float")
# Print the symbol used to start a Python comment
print("The symbol used to start a comment in Python is the pound symbol \'#\' ")
# Print the name of Python data type for numbers without decimals
print("The Python data type used for numbers is the integer type, whole numbers only")
# Print the purpose of the \t escape character
print ('The backslash-t escape character is used to insert TAB spaces into outputs\tlike\tthis')
|
639d50d4d0579ee239adf72a08d7b4d78d9b91b6 | blaise594/PythonPuzzles | /weightConverter.py | 424 | 4.21875 | 4 | #The purpose of this program is to convert weight in pounds to weight in kilos
#Get user input
#Convert pounds to kilograms
#Display result in kilograms rounded to one decimal place
#Get user weight in pounds
weightInPounds=float(input('Enter your weight in pounds. '))
#One pound equals 2.2046226218 kilograms
weightInKilos=weightInPounds/2.2046226218
print('Your weight in kilograms is: '+format(weightInKilos, '.1f'))
|
2b32c38f8df34e7624b993aba7ba38a88059dcbb | i-djurdjevic/BioinformaticsCourseBook | /poglavlja/9/kodovi/SuffixArrayMultiple.py | 1,715 | 3.8125 | 4 | #Formiranje sufiksnog niza na osnovu niza niski strings
def suffix_array_construction(strings):
suffix_array = []
for s in range(len(strings)):
string = strings[s] + '$'
for i in range(len(string)):
suffix_array.append((string[i:],s, i))
suffix_array.sort()
return suffix_array
#Funkcija vraca pozicije na kojima se niska pattern pojavljuje u svakoj pojedinacnoj niski, u "okolini" pozicije mid
def find_neighborhood(suffix_array, mid, pattern):
up = mid
down = mid
while up >= 0 and len(suffix_array[up][0]) > len(pattern) and suffix_array[up][0][:len(pattern)] == pattern:
up -= 1
while down < len(suffix_array) and len(suffix_array[down][0]) > len(pattern) and suffix_array[down][0][:len(pattern)] == pattern:
down += 1
positions = []
for i in range(up+1, down):
positions.append((suffix_array[i][1], suffix_array[i][2]))
positions.sort()
print(positions)
return positions
#Trazenje pozicija na kojima se pojavljuje niska pattern u svakoj pojedinacnoj niski koja je ucestvovala u formiranju suffix_array-a
def pattern_matching_with_suffix_array(suffix_array, pattern):
top = 0
bottom = len(suffix_array)-1
while top <= bottom:
mid = (top + bottom) // 2
if len(suffix_array[mid][0]) > len(pattern):
if suffix_array[mid][0][:len(pattern)] == pattern:
return find_neighborhood(suffix_array, mid, pattern)
if pattern < suffix_array[mid][0]:
bottom = mid - 1
else:
top = mid + 1
def main():
strings = ['ananas', 'and', 'antenna', 'banana', 'bandana', 'nab', 'nana', 'pan']
suffix_array = suffix_array_construction(strings)
pattern = 'an'
print(pattern_matching_with_suffix_array(suffix_array, pattern))
if __name__ == "__main__":
main()
|
f25285c2cc809eeb16fd3696bbfa60ddc341e9e9 | juliali/ClassicAlgorithms | /undirected_graph/ugraph_circle.py | 1,159 | 3.59375 | 4 | import queue
import os
import csv
def is_undirected_graph_circled(adj_matrix):
n = len(adj_matrix)
degrees = [0] * n
visited = []
q = queue.Queue()
for i in range(0, n):
degrees[i] = sum([int(value) for value in adj_matrix[i]])
if degrees[i] <= 1:
q.put(i)
visited.append(i)
while not q.empty():
i = q.get()
for j in range(0, n):
if int(adj_matrix[i][j]) == 1:
degrees[j] -= 1
if degrees[j] == 1:
q.put(j)
visited.append(j)
if len(visited) == n:
return False
else:
return True
def processFile(file_name):
script_dir = os.path.dirname(__file__)
file_path = os.path.join(script_dir, file_name)
data = list(csv.reader(open(file_path)))
result = is_undirected_graph_circled(data)
if result:
print("YES. It contains circle(s): " + file_path)
else:
print("NO. It doesn't contain circle(s): " + file_path)
return
processFile("graph1.csv")
processFile("graph2.csv") |
9d2a6aa7b90925def161452c31235a27d5af40ca | bushidosds/MeteorTears | /lib/utils/fp.py | 979 | 3.625 | 4 | # -*- coding:utf-8 -*-
import os
def iter_files(path: str, otype='path') -> list:
r"""
Returns a list of all files in the file directory path.
:param path: file path, str object.
:param otype: out params type, str object default path.
:return: files path list.
:rtype: list object
"""
filename = []
def iterate_files(path):
path_rest = path if not isinstance(path, bytes) else path.decode()
abspath = os.path.abspath(path_rest)
try:
all_files = os.listdir(abspath)
for items in all_files:
files = os.path.join(path, items)
if os.path.isfile(files):
filename.append(files) if otype == 'path' else filename.append(items)
else:
iterate_files(files)
except (FileNotFoundError, AttributeError, BytesWarning, IOError, FileExistsError):
pass
iterate_files(path)
return filename
|
b858cea86ba5635c86653bcc25a02aa9319d3104 | rdauncey/CS50_problem_set_solutions | /pset6/credit.py | 2,025 | 4 | 4 | from cs50 import get_string
from sys import exit
def main():
# Get input from user
number = get_string("Number: ")
digits = len(number)
# Check length is valid
if digits < 13 or digits > 16 or digits == 14:
print("INVALID")
exit(1)
# Luhn's algorithm
if luhns(number) is False:
print("INVALID")
exit(1)
# VISA or MASTERCARD
if digits == 13 or digits == 16:
# Use the number at the beginning to determine the type
if number[0] == "4":
print("VISA")
exit(0)
elif (int(number[:2]) > 50) and (int(number[:2]) < 56):
print("MASTERCARD")
exit(0)
else:
print("INVALID")
exit(0)
# AMEX
elif digits == 15:
# Check the beginning of the number is correct
if number[:2] == "34" or number[:2] == "37":
print("AMEX")
exit(0)
else:
print("INVALID")
exit(1)
# Function takes the number (as a string) as an input, and returns a boolean value
# which indicates whether the number is or is not a valid credit card number
def luhns(number):
even_digits = []
odd_digits = []
for i in range(len(number)):
# If even, append digit in int form to odds list
if i % 2 == 0:
odd_digits.append(int(number[len(number) - i - 1]))
# If not, append to evens list
else:
even_digits.append(int(number[len(number) - i - 1]))
# Multiply all entries in even_digits by 2
even_digits = [i * 2 for i in even_digits]
# If we have a two digit number, preemptively sum the digits
for k in range(len(even_digits)):
# Can be at most two digits
if even_digits[k] > 9:
even_digits[k] = 1 + (even_digits[k] - 10)
# Now we can just sum over the two lists
output = sum(even_digits) + sum(odd_digits)
if output % 10 == 0:
return True
else:
return False
main()
|
abe6d35e9add0faca38e2eb800fef850dee91aed | paperbackdragon/python-300 | /project/dbhelper.py | 2,907 | 3.875 | 4 | """
Database Helper
Author: Heather Hoaglund-Biron
"""
import sqlite3
class DatabaseHelper:
"""
A DatabaseHelper reads and writes MP3 metadata to an SQLite database. It is
necessary to close the connection to the database when finished with the
close() method.
"""
def __init__(self):
"""
Initializes the MP3 metadata database.
"""
self.conn = sqlite3.connect('tags.db')
self.c = self.conn.cursor()
#Create table
self.c.execute("""CREATE TABLE IF NOT EXISTS songs
(title TEXT NOT NULL,
album TEXT NOT NULL,
artist TEXT,
track INTEGER,
length TEXT,
PRIMARY KEY (title, album))""")
#Commit changes
self.conn.commit()
def write(self, data):
"""
Takes the given song and writes it to the database, returning the
primary key. Song title and album name are required.
"""
insert_text = "INSERT into songs (title, album"
columns = ['title', 'album', 'artist', 'track', 'length']
used = ['title', 'album']
primary_key = {}
#See which tags are in the dictionary (title and album aren't optional)
for column in columns[2:]:
if column in data:
insert_text += ", " + column
used.append(column)
insert_text += ") values ("
#Prepare values
values = []
for column in used:
if column == "track":
values.append(data[column])
else:
values.append("\"" + data[column] + "\"")
if column == "title" or column == "album":
primary_key[column] = data[column]
insert_text += ", ".join(values)
insert_text += ")"
#Execute command(s) and commit
try:
self.c.execute(insert_text)
self.conn.commit()
print "Writing tag: %s" % data
except sqlite3.IntegrityError:
primary_key = {}
print "Item already exists in database."
return primary_key
def read(self, key):
"""
Reads the information given in the query, grabs the specified data from
the database, and returns it.
"""
select_text = "SELECT * from songs WHERE title is \"%s\" AND album is "\
"\"%s\" ORDER BY artist, album, track" % (key["title"], key["album"])
self.c.execute(select_text)
rows = []
for row in self.c.fetchall():
rows.append(row)
print "Reading tag: %s" % rows
return rows
def close(self):
self.conn.close()
|
3f04d5bef7608689c343a5eddb61c3ac1939a3e8 | boconganh/algorithm | /python/merge-sort.py | 418 | 3.609375 | 4 | def merge(A,p,q,r):
n1=q-p+1
n2=r-q
L=A[p:p+n1]+[float("inf")]
R=A[q+1:q+1+n2]+[float("inf")]
#print A[p:r+1],L,R
i=0
j=0
for k in range(p,r+1):
if L[i]<=R[j]:
A[k]=L[i]
i+=1
else:
A[k]=R[j]
j+=1
def merge_sort(A,p,r):
if p<r:
q=(p+r)//2
merge_sort(A,p,q)
merge_sort(A,q+1,r)
merge(A,p,q,r)
A=[1,2,4,2,4,32,45,6]
print A
merge_sort(A,0,len(A)-1)
print A
|
a2dad7fea5ec6e42767c6ab36c4658c857d5548c | boconganh/algorithm | /python/find-max-subarray.py | 997 | 3.59375 | 4 |
def find_max_cross_subarray(A,low,mid,high):
left_sum=float("-inf")
sum=0
for i in range(mid,low-1,-1):
sum+=A[i]
if sum>left_sum:
left_sum=sum
max_left=i
right_sum=float("-inf")
sum=0
for j in range(mid+1,high+1):
sum+=A[j]
if sum>right_sum:
right_sum=sum
max_right=j
return (max_left,max_right,left_sum+right_sum)
def find_max_subarray(A,low,high):
if low==high:
return (low,high,A[low])
else:
mid=(low+high)//2
left_low,left_high,left_sum=find_max_subarray(A,low,mid)
right_low,right_high,right_sum=find_max_subarray(A,mid+1,high)
cross_low,cross_high,cross_sum=find_max_cross_subarray(A,low,mid,high)
if left_sum>=right_sum and left_sum>=cross_sum:
return (left_low,left_high,left_sum)
elif right_sum>=left_sum and right_sum>=cross_sum:
return (right_low,right_high,right_sum)
else:
return (cross_low,cross_high,cross_sum)
A=[11,-2,-4,3,-4,23,-145,345,23]
print A
print find_max_subarray(A,0,len(A)-1) |
ac8ff352c058b7b1e3885d3bca7611f29437f2b4 | SaeedTaghavi/MonteCarloIntegration | /test.py | 1,391 | 3.640625 | 4 | import numpy as np
import random
def calc_pi(N):
inCircle = 0
for i in range(N):
point = (random.random() , random.random())
r = point[0]*point[0] + point[1]*point[1]
if r < 1.0 :
inCircle = inCircle +1
# plt.plot(point[0], point[1], 'r.')
# else:
# plt.plot(point[0], point[1], 'b.')
res = float(inCircle)/float(N)
res = 4.0*res
return res
def pi_diff(temp_pi):
return np.pi-temp_pi
def calc_pi_array(num_array):
res_array = []
for num in num_array:
res_array = res_array + [calc_pi(num)]
return res_array
Numbers = []
for i in range(2,7):
Numbers = Numbers + [int(10.0**i)]
Numbers = Numbers + [int(3.0 * 10.0 ** i)]
Numbers = Numbers + [int(6.0 * 10.0 ** i)]
import matplotlib.pyplot as plt
for i in range(1,5):
pis = calc_pi_array(Numbers)
pi_diff_array = []
for pi in pis:
pi_diff_array = pi_diff_array + [pi_diff(pi)]
print(Numbers)
print(pis)
print(pi_diff_array)
plt.plot(Numbers,pi_diff_array,'-s')
plt.xscale('log')
plt.xlabel('N')
plt.ylabel('pi_calc - pi')
plt.savefig('PiDeviationFromTheExactValue.png')
plt.show()
#
# def double(x):
# return 2.0*x
#
# def sinSquare(x):
# return np.sin(x)*np.sin(x)
#
# print(double(3.0))
# print(sinSquare(np.pi/6.0))
|
eac27c0231a6e7acfd305620cff56fd69e3f6d3e | apan64/basic-data-structures | /Lab_11.py | 1,194 | 3.703125 | 4 | import math
class AdjMatrixGraph:
def __init__ (self, n):
self.n = n
self.array = []
for x in range(n):
q = []
for y in range(n):
q.append(int(0))
self.array.append(q)
def display (self):
for x in range (self.n):
for y in range (self.n):
print ("{0:2}".format(self.array[x][y]), end=" ")
print( )
print( )
def insert (self, x, y, w):
self.array[x][y] = int(w)
def floyd (self):
for i in range(0, self.n):
for r in range(0, self.n):
for c in range(0, self.n):
self.array[r][c] = min(self.array[r][c], self.array[r][i] + self.array[i][c])
def main( ):
n = eval(input("Enter number of vertices: "))
G = AdjMatrixGraph(n)
G.display( )
k = math.ceil(math.sqrt(n))
for x in range(n):
for y in range(n):
if x!=y:
weight = (x%k-y%k)**2 + (x//k-y//k)**2 + 1
G.insert(x, y, weight)
G.display( )
G.floyd( )
G.display( )
if __name__ == '__main__':
main( )
|
ab96fe2f94f539e7535d8110c3dafcd2f35cf097 | apan64/basic-data-structures | /Lab_6.py | 2,569 | 3.921875 | 4 |
class Node:
def __init__ (self, x, q):
self.data = x
self.next = q
class Stack:
def __init__ (self):
self.top = None
def isEmpty (self):
return self.top == None
def push (self, x):
self.top = Node (x, self.top)
def pop (self):
if self.isEmpty( ):
raise KeyError ("Stack is empty.")
x = self.top.data
self.top = self.top.next
return x
class List:
def __init__ (self):
self.head = None
def build_list (self):
str = input ("Enter strings separated by blanks: ")
for x in str.split (" "):
if self.head == None:
self.head = Node (x, None)
curr = self.head
else:
curr.next = Node (x, None)
curr = curr.next
def display (self):
curr = self.head
while curr != None:
print (curr.data, end=" ")
curr = curr.next
print( )
def reverse_display_1 (self):
st = Stack()
curr = self.head
while curr != None:
st.push(curr.data)
curr = curr.next
while (not(st.isEmpty())):
print(st.pop(), end = " ")
print( )
def recur(self, q):
if q.next != None:
self.recur(q.next)
print(q.data, end = " ")
def reverse_display_2 (self):
self.recur(self.head)
print( )
def reverse_display_3 (self):
w = self.head
curr = self.head
head = self.head
head = head.next
curr.next = None
while head != None:
curr = head
head = head.next
curr.next = w
w = curr
head = curr.next
while curr != None:
print (curr.data, end=" ")
curr = curr.next
print( )
curr = w
curr.next = None
while head != None:
curr = head
head = head.next
curr.next = w
w = curr
def main( ):
L = List( )
L.build_list( )
print ("Forward: ", end="\t")
L.display( )
print ("Backward: ", end="\t")
L.reverse_display_1( )
print ("Backward: ", end="\t")
L.reverse_display_2( )
print ("Backward: ", end="\t")
L.reverse_display_3( )
print ("Forward: ", end="\t")
L.display( )
if __name__ == '__main__':
main( )
|
02856d56ce1a0c1a834220d6e0eb7d259010e53d | naitiknakrani/Machine-Learning-algorithms | /1.3-polynomial-regression.py | 3,466 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jul 11 17:42:30 2021
@author: naitik
"""
import matplotlib.pyplot as plt
import pandas as pd
import pylab as pl
import numpy as np
%matplotlib inline
df = pd.read_csv("FuelConsumptionCo2.csv")
df.head() # show data
df.describe() #summarize data
cdf = df[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB','CO2EMISSIONS']] # select few samples
cdf.iloc[5:7,:] # select specific row and column
cdf.head(9) # give first 9 rows data
# Training starts from here
# Let's split our dataset into train and test sets.
# 80% of the entire dataset will be used for training and 20% for testing.
# We create a mask to select random rows using np.random.rand() function:
msk = np.random.rand(len(df)) < 0.8
train = cdf[msk]
test = cdf[~msk]
# Build a Model of Linear Regression
from sklearn import linear_model
from sklearn.preprocessing import PolynomialFeatures
train_x = np.asanyarray(train[['ENGINESIZE']])
train_y = np.asanyarray(train[['CO2EMISSIONS']])
test_x = np.asanyarray(test[['ENGINESIZE']])
test_y = np.asanyarray(test[['CO2EMISSIONS']])
poly = PolynomialFeatures(degree=2)
train_x_poly = poly.fit_transform(train_x) # convert Train_x into 1 x x^2
train_x_poly
# Now we can use same linear model for polynomial data
regr = linear_model.LinearRegression()
regr.fit (train_x_poly, train_y)
# The coefficients
print ('Coefficients: ', regr.coef_)
print ('Intercept: ',regr.intercept_)
# plot the data and non-linear regression line
plt.scatter(train.ENGINESIZE, train.CO2EMISSIONS, color='blue')
XX = np.arange(0.0, 10.0, 0.1) # generate sample sequence like for XX=0:0.1:10
yy = regr.intercept_[0]+ regr.coef_[0][1]*XX+ regr.coef_[0][2]*np.power(XX, 2)
plt.plot(XX, yy, '-r' )
plt.xlabel("Engine size")
plt.ylabel("Emission")
#Evaluation matrix
from sklearn.metrics import r2_score
test_x_poly=poly.fit_transform(test_x)
test_y_ = regr.predict(test_x_poly)
print("Mean absolute error: %.2f" % np.mean(np.absolute(test_y_ - test_y)))
print("Residual sum of squares (MSE): %.2f" % np.mean((test_y_ - test_y) ** 2))
print("R2-score: %.2f" % r2_score(test_y , test_y_) )
print('Variance score: %.2f' % regr.score(test_x_poly, test_y))
# regression with cubic polynomial
poly = PolynomialFeatures(degree=3)
train_x_poly = poly.fit_transform(train_x) # convert Train_x into 1 x x^2
train_x_poly
# Now we can use same linear model for polynomial data
regr = linear_model.LinearRegression()
regr.fit (train_x_poly, train_y)
# The coefficients
print ('Coefficients: ', regr.coef_)
print ('Intercept: ',regr.intercept_)
# plot the data and non-linear regression line
plt.scatter(train.ENGINESIZE, train.CO2EMISSIONS, color='blue')
XX = np.arange(0.0, 10.0, 0.1) # generate sample sequence like for XX=0:0.1:10
yy = regr.intercept_[0]+ regr.coef_[0][1]*XX+ regr.coef_[0][2]*np.power(XX, 2)+regr.coef_[0][3]*np.power(XX, 3)
plt.plot(XX, yy, '-r' )
plt.xlabel("Engine size")
plt.ylabel("Emission")
#Evaluation matrix
from sklearn.metrics import r2_score
test_x_poly=poly.fit_transform(test_x)
test_y_ = regr.predict(test_x_poly)
print("Mean absolute error: %.2f" % np.mean(np.absolute(test_y_ - test_y)))
print("Residual sum of squares (MSE): %.2f" % np.mean((test_y_ - test_y) ** 2))
print("R2-score: %.2f" % r2_score(test_y , test_y_) )
print('Variance score: %.2f' % regr.score(test_x_poly, test_y)) |
7ebafa063d92a5960289cba76c3043e18990810e | IqbalHadiSubekti/Factorial | /factorial.py | 462 | 4.0625 | 4 | count = 0
while count == 0:
def factorial(n):
if 1 <= n <= 2:
return n
elif 3 <= n <= 5:
return n + 1
elif 6 <= n <= 8:
return n + 2
elif 9 <= n <= 11:
return n + 3
else:
print("Input Salah")
n = int(input("Input: "))
print("Output:",factorial(n))
ulangi = str(input("Hitung ulang? ya/tidak: "))
if ulangi == "ya":
pass
elif ulangi == 'tidak':
break
|
5e238d1bc97635963bcb15b615c9e94fbf7c7b5f | dharanpreethi/Text-Minining_Indian-English-Liteature | /Text_mining/Corpus_tm.py | 2,458 | 3.890625 | 4 | # Corpus of text analysis
# Now, we can mine the corpus of texts using little more advanced methods of Python.
#1.Install glob using pip and import the module
#2. Import other necessary modules which we already installed in our previous analysis
#3. Asterisk mark will import all plain text files in the corpus
#4. Create a corpus of text files and call them using glob
#5. Store the stopwords of nltk in a variable
import nltk
from nltk.tokenize import RegexpTokenizer
from nltk.corpus import stopwords
import glob
corpus = glob.glob("E:\Medium Blog\Text_mining\*.txt")
stop_words = set(stopwords.words('english'))
# Pre-processing and analysis
# We will call the corpus using for loop and then read the texts and convert them into lowercase. We extract the content for analysis, apply stopwords list and tokenization as we did for the single text, but everything should be in the for loop as in the below code.
for i in range(len(corpus)):
text_file = open(corpus[i], "r", encoding = "UTF-8")
lines = []
lines = text_file.read().lower()
extract1 =lines.find("start of this project")
extract2 = lines.rfind("end of this project")
lines = lines[extract1:extract2]
tokenizer = RegexpTokenizer('\w+') # extracting words
tokens = tokenizer.tokenize(lines) # tokenize the text
new_stopwords = ("could", "would", "also", "us") # add few more words to the list of stopwords
stop_words = stopwords.words('english')
for i in new_stopwords:
stop_words.append(i) # adding new stopwords to the list of existing stopwords"""
words_list = [w for w in tokens if not w in stop_words]
filtered_words = []
for w in tokens:
if w not in stop_words:
filtered_words.append(w)
fre_word_list = nltk.FreqDist(filtered_words) #extracting frequently appeared words
print(fre_word_list.most_common(5)) # check the most common frequent words
fre_word_list.plot(25) #create a plot for the output
pos = nltk.pos_tag(filtered_words, tagset = 'universal') # applying parts of speech (pos) tag for further analysis
p = []
y = ['NOUN'] # change the pos here to store them separately
for j in pos:
for l in y:
if l in j:
p.append(j)
noun = nltk.FreqDist(p)# check the frequency of each pos
noun.plot(20)# creating a plot for pos
|
8160b104778db2c44617989b4a58d2f9873fa57c | AYBUcode/CENG113fall2020 | /Week3p.py | 141 | 3.828125 | 4 | a=3.556; b=4; c="abc"
print('{0}+{1}={2}'.format(a,b,a+b))
print("the value of a:%10.0f!!"%(a))
x = int(input("Enter a value: "))
print(x*2) |
24a70d398de181471d15d36d995c8585b1c35ea7 | quentinb28/problem-solving-challenges | /codility/flags.py | 1,694 | 3.6875 | 4 | def solution(A):
# initialize list of peaks indexes in between peaks
peaks = [0] * len(A)
# last item should be index outside of peaks length
next_peak = len(A)
peaks[-1] = next_peak
# stops at 0 because we want to avoid index out of range within if statement
for i in range(len(A) - 2, 0, -1):
# if height greater than point before and after then save peak index
if (A[i] > A[i - 1]) and (A[i] > A[i + 1]):
next_peak = i
# keep saving peak index until next peak occurs
peaks[i] = next_peak
# cannot be within loop for index out of bound reasons
peaks[0] = next_peak
current_guess = 0
next_guess = 0
# iterate through flags counts until it breaks
while can_place_flags(peaks, next_guess):
# saves last working flags count
current_guess = next_guess
next_guess += 1
return current_guess
def can_place_flags(peaks, flags_to_place):
# to land on index 1 after first iteration (cannot land on index 0)
current_position = 1 - flags_to_place
# iterates through each flag and add the relevant number of places to next position
for i in range(flags_to_place):
# if next flag falls outside of peaks index range
if current_position + flags_to_place > len(peaks) - 1:
return False
# current position moves to current position + flags places
current_position = peaks[current_position + flags_to_place]
# if last current position within peaks size then return True
return current_position < len(peaks)
if __name__ == '__main__':
A = [1, 5, 3, 4, 3, 4, 1, 2, 3, 4, 6, 2]
solution(A)
|
4c22ce72238761ce47b68c340174df50866a6a35 | quentinb28/problem-solving-challenges | /sherlock-and-anagrams/sherlock-and-anagrams-exercise.py | 1,063 | 3.890625 | 4 | from collections import Counter
from itertools import combinations
s = 'ifailuhkqq'
def sherlockAndAnagrams(s):
# Variable to store all possible combinations
all_combinations = []
# Iterate through substrings starting points
for i in range(0, len(s) + 1):
# Iterate through substrings ending points
for j in range(1, len(s) + 1):
# Append substring to list of combinations
all_combinations.append(s[i:j])
# Sort all substrings so the anagrams can be counted
all_combinations = [''.join(sorted(c)) for c in all_combinations]
# Filter out all empty strings
all_combinations = list(filter(None, all_combinations))
result = 0
# Get the values from the counter and compute all the possible anagram pairs
# (i.e. if v = 4 then the options are 1-2 1-3 1-4 2-3 2-4 3-4 = 6)
for k, v in Counter(all_combinations).items():
result += len(list(combinations(range(v), 2)))
return result
if __name__ == '__main__':
r = sherlockAndAnagrams(s)
print(r)
|
39347b2b248bd565b8a1df9753681900855e88d0 | quentinb28/problem-solving-challenges | /new-year-chaos/new-year-chaos-exercise.py | 585 | 3.578125 | 4 | q = [2, 1, 5, 3, 4]
def minimumBribes(q):
# Initiate total number of bribes
total_bribes = 0
# Iterate through each runner backward
for i in range(len(q) - 1, -1, -1):
# Stop execution if a runner bribes more than two runners
if q[i] - (i + 1) > 2:
print('Too chaotic')
return
# Add the number of runners behind current runner that were bribed
else:
total_bribes += len(list(filter(lambda x: x < q[i], q[i + 1:])))
print(total_bribes)
if __name__ == '__main__':
minimumBribes(q)
|
79fb67bd7592371aaf3861d4e0f9dc84f3a94fdd | y001003/PythonStudy | /_class/class_overriding_1.py | 2,318 | 3.75 | 4 | #일반 유닛
class Unit: # 부모 class
def __init__(self, name, hp, speed):
self.name = name
self.hp = hp
self.speed = speed
print("{0} 유닛이 생성되었습니다.".format(self.name))
def move(self, location):
print("[지상 유닛 이동")
print("{0} : {1} 방향으로 이동합니다. [속도 {2}]"\
.format(self.name,location,self.speed))
#공격 유닛
class AttackUnit(Unit): # 자식 class
def __init__(self, name, hp, speed, damage):
Unit.__init__(self, name, hp, speed)
self.damage = damage
# method
def attack(self, location):
print("{0} : {1} 방향으로 적군을 공격 합니다. [공격력 {2}]"\
.format(self.name, location, self.damage))
def damaged(self, damage):
print("{0} : {1} 데미지를 입었습니다."\
.format(self.name, damage))
self.hp -= damage
print("{0} : 현재 남은 체력은 {1} 입니다."\
.format(self.name, self.hp))
if self.hp <= 0:
print("{0} : 파괴되었습니다.".format(self.name))
# 드랍쉽 : 수송기, 공격 X, 공중유닛
class Flyable:
def __init__(self, flying_speed):
self.flying_speed = flying_speed
def fly(self, name, location):
print("{0} : {1} 방향으로 날아갑니다. [속도 {2}]"\
.format(name, location, self.flying_speed))
#공중 공격 유닛 클래스
#공격 유닛, 공중유닛 다중 상속
class FlayableAttackUnit(AttackUnit, Flyable):
def __init__(self, name, hp, damage, flying_speed):
AttackUnit.__init__(self, name, hp, 0, damage) # 지상 speed 0
Flyable.__init__(self, flying_speed)
# 메서드 오버라이딩 move로 fly 기동하도록 메서드 move 재정의
def move(self, location):
print("[공중 유닛 이동]")
self.fly(self.name, location)
# 벌쳐 : 지상 유닛, 기동성이 좋음
vulture = AttackUnit("벌쳐",80,10,20)
# 배틀크루저 : 공중 유닛, 체력, 공격력 좋지만 느림
battlecruiser = FlayableAttackUnit("배틀크루저", 500, 25, 3)
vulture.move("11시")
#battlecruiser.fly(battlecruiser.name,"9시")
battlecruiser.move("9시")
|
2c8446bcdebf09395972b1f4fc94eecc00a29fde | y001003/PythonStudy | /_class/class_super_1.py | 2,233 | 3.75 | 4 | #일반 유닛
class Unit: # 부모 class
def __init__(self, name, hp, speed):
self.name = name
self.hp = hp
self.speed = speed
print("{0} 유닛이 생성되었습니다.".format(self.name))
def move(self, location):
print("[지상 유닛 이동")
print("{0} : {1} 방향으로 이동합니다. [속도 {2}]"\
.format(self.name,location,self.speed))
#공격 유닛
class AttackUnit(Unit): # 자식 class
def __init__(self, name, hp, speed, damage):
Unit.__init__(self, name, hp, speed)
self.damage = damage
# method
def attack(self, location):
print("{0} : {1} 방향으로 적군을 공격 합니다. [공격력 {2}]"\
.format(self.name, location, self.damage))
def damaged(self, damage):
print("{0} : {1} 데미지를 입었습니다."\
.format(self.name, damage))
self.hp -= damage
print("{0} : 현재 남은 체력은 {1} 입니다."\
.format(self.name, self.hp))
if self.hp <= 0:
print("{0} : 파괴되었습니다.".format(self.name))
# 드랍쉽 : 수송기, 공격 X, 공중유닛
class Flyable:
def __init__(self, flying_speed):
self.flying_speed = flying_speed
def fly(self, name, location):
print("{0} : {1} 방향으로 날아갑니다. [속도 {2}]"\
.format(name, location, self.flying_speed))
#공중 공격 유닛 클래스
#공격 유닛, 공중유닛 다중 상속
class FlayableAttackUnit(AttackUnit, Flyable):
def __init__(self, name, hp, damage, flying_speed):
AttackUnit.__init__(self, name, hp, 0, damage) # 지상 speed 0
Flyable.__init__(self, flying_speed)
# 메서드 오버라이딩 move로 fly 기동하도록 메서드 move 재정의
def move(self, location):
print("[공중 유닛 이동]")
self.fly(self.name, location)
#건물
class BuildingUnit(Unit):
def __init__(self, name, hp, location):
#Unit.__init__(self, name, hp, 0)
super().__init__(name, hp, 0) # 자신이 상속받는 부모클래스 초기화
self.location = location
|
36b67db6ed6e02eb188301bea8a878aa34166ad6 | y001003/PythonStudy | /_file/input_output_1.py | 856 | 3.765625 | 4 |
# print("Python","Java","JavaScript", sep=" vs ", end="?")
# print("무엇이 더 재미있을까요?")
# import sys
# print("Python","Java", file=sys.stdout)
# print("Python","Java", file=sys.stderr)
# dictionary
# scores = {"수학":0, "영어":50, "코딩":100}
# for subject, score in scores.items():# items() : key와 value 쌍으로 보내줌
# #print(subject,score)
# #왼쪽정렬 8공간 오른쪽 정렬 4개공간
# print(subject.ljust(8), str(score).rjust(4), sep=":")
#은행 대기순번표
# 001, 002, 003, ...
# for num in range(1,21):
# print("대기번호 : " + str(num).zfill(3))
# 표준 입력
answer = input("아무 값이나 입력하세요 : ")
print(type(answer)) # 무조건 String 문자열형태로 기억된다.
# print("입력하신 값은 " + answer + "입니다.")
|
3bdb316174a1c4996567dd5bb66fd25ab8891b57 | y001003/PythonStudy | /_for,while/for_2.py | 519 | 3.671875 | 4 | # 출석번호가 1 2 3 4, 앞에 100을 붙이기로 함 -> 101, 102,103,104.
# students = [1,2,3,4,5]
# print(students)
# students = [i+100 for i in students]#students 값을 i에 대입해서 각 i +100
# print(students)
# 학생 이름을 길이로 변환
# students = ["Iron man", "Thor", "I am groot"]
# students = [len(i) for i in students]
# print(students)
# 학생 이름을 대문자로 변환
students = ["Iron man", "Thor", "I am groot"]
students = [i.upper() for i in students]
print(students) |
c0287f0659be8e9c8b945efbeb98e648caf565a9 | y001003/PythonStudy | /_class/class_heritage_1.py | 1,683 | 3.6875 | 4 | #일반 유닛
class Unit: # 부모 class
def __init__(self, name, hp):
self.name = name
self.hp = hp
print("{0} 유닛이 생성되었습니다.".format(self.name))
#공격 유닛
class AttackUnit(Unit): # 자식 class
def __init__(self, name, hp, damage):
Unit.__init__(self, name, hp)
self.damage = damage
# method
def attack(self, location):
print("{0} : {1} 방향으로 적군을 공격 합니다. [공격력 {2}]"\
.format(self.name, location, self.damage))
def damaged(self, damage):
print("{0} : {1} 데미지를 입었습니다."\
.format(self.name, damage))
self.hp -= damage
print("{0} : 현재 남은 체력은 {1} 입니다."\
.format(self.name, self.hp))
if self.hp <= 0:
print("{0} : 파괴되었습니다.".format(self.name))
# 드랍쉽 : 수송기, 공격 X, 공중유닛
class Flyable:
def __init__(self, flying_speed):
self.flying_speed = flying_speed
def fly(self, name, location):
print("{0} : {1} 방향으로 날아갑니다. [속도 {2}]"\
.format(name, location, self.flying_speed))
#공중 공격 유닛 클래스
#공격 유닛, 공중유닛 다중 상속
class FlayableAttackUnit(AttackUnit, Flyable):
def __init__(self, name, hp, damage, flying_speed):
AttackUnit.__init__(self, name, hp, damage)
Flyable.__init__(self, flying_speed)
# 발키리 : 공중 공격 유닛, 한번에 14발 미사일 발사
valkyrie = FlayableAttackUnit("발키리",200,6,5)
valkyrie.fly(valkyrie.name,"3시")
|
c3a23f4391d29250c7ff9ee4fa0ad9cd133abbe7 | priancho/nlp100 | /05.py | 900 | 4.3125 | 4 | #usage example:
#python3 05.py 2 "This is a pen."
import re
import sys
# extract character n-grams and calculate n-gram frequency
def char_n_gram(n, str):
ngramList = {}
n=int(n)
str = str.lower()
wordList=re.findall("[a-z]+",str)
for word in wordList:
if len(word) >= n:
for i in range(len(word)-n+1):
if word[i:i+n] in ngramList:
ngramList[word[i:i+n]]+=1
else:
ngramList[word[i:i+n]]=1
return ngramList
# extract character n-grams and calculate n-gram frequency
def word_n_gram(n, str):
next
if __name__ == '__main__':
if len(sys.argv) != 3:
print "Usage: %s <n> <sentence>" % (sys.argv[0])
print " <n>: n for n-gram."
print " <sentence>: input sentence to generate n-grams"
print ""
print " e.g., %s 2 \"This is a pen.\"" % (sys.argv[0])
exit(1)
print (char_n_gram(sys.argv[1],sys.argv[2]))
print (word_n_gram(sys.argv[1],sys.argv[2]))
|
af416cceefc1c63424869b66e5fbbaccf9e1f4a5 | silvaniodc/python | /Aulas Python/E_hoje.py | 1,049 | 3.546875 | 4 | # -*- coding: UTF-8 -*-
# O que Silvanio vai fazer no Domingo?
def hoje_e_o_dia():
from datetime import date
hj = date.today()
dias = ('Segunda-feira', 'Terça-feira', 'Quarta-feira', 'Quinta-feira', 'Sexta-feira', 'Sábado', 'Domingo')
dia = int(hj.weekday())
if dia == 3 :
print 'Hoje é %s e Silvânio vai continuar Estudando insanamente...!' % (dias[hj.weekday()])
if dia == 1 :
print 'Hoje é %s e Silvânio vai na Ubercom ver se o HD SSD ja chegou!' % (dias[hj.weekday()])
if dia == 6 :
print 'Hoje é %s e com certeza Silvânio vai pescar :) ' % (dias[hj.weekday()])
if dia == 5 :
print 'Hoje é %s e Silvânio vai levar Janaina pra tomar Açai!' % (dias[hj.weekday()])
if dia == 2 :
print 'Hoje é %s e Silvânio vai estudar Inglês igual um a louco!' % (dias[hj.weekday()])
if dia == 0 :
print 'Hoje é %s e Silvânio vai faze um Churrasco de Picanha au au!' % (dias[hj.weekday()])
if dia == 4 :
print 'Hoje é %s e Silvânio vai assistir Family Guy na Netflix!' % (dias[hj.weekday()])
hoje_e_o_dia() |
fee0f545fe5e9ec8758ef45e2411e1a2e76801c4 | rustikk/OpenCV-Basics | /opencv-getting-setting/gett_setting_code_along.py | 1,990 | 3.546875 | 4 | import argparse
import cv2
#construct the argument parser
ap = argparse.ArgumentParser()
#if no argument is passed, "adrian.png" is used
ap.add_argument("-i", "--image", type=str, default="adrian.png",
help="path to input image")
#vars stores the arguments in a dictionary
args = vars(ap.parse_args())
#load the image, grab it spacial dimensions (width and height),
#and then display the original image to our screen
#reads the image from the argument passed at the command line,
#the input path to the image being manipulated
image = cv2.imread(args["image"])
#grabs the width and height
(h, w) = image.shape[:2]
#shows the image with a title of Original
cv2.imshow("Original", image)
#keeps the image open til a key is pressed, then it closes
#cv2.waitKey(0)
#rgb values at (0, 0)
(b, g, r) = image[0, 0]
print("Pixel at (0, 0) - Red: {}, Green: {}, Blue {}".format(r, g, b))
# access the pixel located at x=50, y=20
(b, g, r) = image[20, 50]
print("Pixel at (50, 20) - Red: {}, Green: {}, Blue: {}".format(r, g, b))
# update the pixel at (50, 20) and set it to red
image[20, 50] = (0, 0, 255)
#y values first then x values as images are numpy arrays
#and you access rows before columns in numpy arrays
(b, g, r) = image[20, 50]
print("Pixel at (50, 20) - Red: {}, Green: {}, Blue: {}".format(r, g, b))
# compute the center of the image, which is simply the width and height
# divided by two
cX, cY = (w // 2, h // 2)
# since we are using NumPy arrays, we can apply array slicing to grab
# large chunks/regions of interest from the image -- here we grab the
# top-left corner of the image
tl = image[0:cY, 0:cX]
tr = image[0:cY, cX:w]
br = image[cY:h, cX:w]
bl = image[cY:h, 0:cX]
cv2.imshow("Top-Left Corner", tl)
cv2.imshow("Top-Right Corner", tr)
cv2.imshow("Bottom-Right Corner", br)
cv2.imshow("Bottom-left Corner", bl)
#set the top left corner of the original image to be green
image[0:cY, 0:cX] = (255, 0, 255)
#show updated image
cv2.imshow("Updated", image)
cv2.waitKey(0) |
bc44e991bdb4525bbca5a93fe4e6db50947fe225 | kerroggu/AtCoderLibrary | /src/UnionFind.py | 1,325 | 3.609375 | 4 | ## Tested by ABC264-E
## https://atcoder.jp/contests/abc264/tasks/abc264_e
## Tested by ABC120-D
## https://atcoder.jp/contests/abc120/tasks/abc120_d
class UnionFind:
def __init__(self,n):
# 負 : 根であることを示す。絶対値はランクを示す
# 非負: 根でないことを示す。値は親を示す
self.parent=[-1]*n
# 連結成分の個数を管理
self._size=[1]*n
def root(self,x):
if self.parent[x]<0:
return x
else:
# 経路の圧縮
self.parent[x]=self.root(self.parent[x])
return self.parent[x]
def same(self,x,y):
return self.root(x)==self.root(y)
def union(self,x,y):
r1=self.root(x)
r2=self.root(y)
if r1==r2:
return
# ランクの取得
d1=self.parent[r1]
d2=self.parent[r2]
if d1<=d2:
self.parent[r2]=r1
self._size[r1]+=self._size[r2]
if d1==d2:
self.parent[r1]-=1
else:
self.parent[r1]=r2
self._size[r2]+=self._size[r1]
def size(self,x):
return self._size[self.root(x)]
def __str__(self):
rt=[i if j<0 else j for i,j in enumerate(self.parent)]
return str(rt)
|
053d941b6d0539e9510961fd68a4a70123ff0cc7 | DouglasCremonese/Uri | /1042.py | 266 | 3.734375 | 4 | # Exercício 1042 Uri Online Judge
# Programador: Douglas Garcia Cremonese
lista = list()
a, b, c = map(int, input().strip().split(" "))
lista.append(a)
lista.append(b)
lista.append(c)
lista.sort()
for i in range(3):
print(lista[i])
print()
print(a)
print(b)
print(c) |
8a56d576c3c6be23f5fdbb3ad70965befbac04f7 | juancebarberis/algo1 | /practica/7-10.py | 898 | 4.3125 | 4 | #Ejercicio 7.10. Matrices.
#a) Escribir una función que reciba dos matrices y devuelva la suma.
#b) Escribir una función que reciba dos matrices y devuelva el producto.
#c) ⋆ Escribir una función que opere sobre una matriz y mediante eliminación gaussiana de-
#vuelva una matriz triangular superior.
#d) ⋆ Escribir una función que indique si un grupo de vectores, recibidos mediante una
#lista, son linealmente independientes o no.
A = [(2,1), (4,1)]
B = [(4,0), (2,8)]
def sumarMatrices(A, B):
""""""
resultado = []
for i in range(len(A)):
nuevaFila = []
for e in range(len(A[i])):
nuevaFila.append(A[i][e] + B[i][e])
resultado.append(nuevaFila)
return resultado
print('A')
for fila in A:
print(fila)
print('B')
for fila in B:
print(fila)
print('Resultado!:')
res = sumarMatrices(A, B)
print(f"{res[0]}")
print(f"{res[1]}")
|
49ff1527a9468412bde79ed0664bdbf5ebbdac99 | juancebarberis/algo1 | /tp2/modulos/input.py | 2,558 | 3.625 | 4 | #Este módulo contiene funciones del tipo input que intervienen en la jugabilidad
#y el movimiento de Snake.
from modulos.terminal import timed_input
def inputJugada(movimiento, variables, _ESPECIALES, snake):
"""
Comprueba lo ingresado por el usuario desde el teclado.
Evalúa si pertenece a un movimiento, un especial, o a un cierre del juego.
"""
entrada = timed_input(float(variables['SPEED']))
#Condicionales de 'salir del juego'.
if entrada.isspace(): #Para salir del juego, presiona <SPACE>
return False, variables, snake, _ESPECIALES
#Condicionales de movimiento
if entrada == 'w' and not movimiento == 's':
return entrada, variables, snake, _ESPECIALES
elif entrada == 'a' and not movimiento == 'd':
return entrada, variables, snake, _ESPECIALES
elif entrada == 's' and not movimiento == 'w':
return entrada, variables, snake, _ESPECIALES
elif entrada == 'd' and not movimiento == 'a':
return entrada, variables, snake, _ESPECIALES
#Condicionales de especiales
especiales = variables['SPECIALS']
if especiales == [] or especiales[0] == '':
return movimiento, variables, snake, _ESPECIALES
for i in range(len(especiales)):
if entrada == _ESPECIALES[especiales[i]]['E_KEY'] and int(_ESPECIALES[especiales[i]]['E_CANT']) > 0:
if _ESPECIALES[especiales[i]]['E_TYPE'] == 'VELOCIDAD':
velocidad = float(variables['SPEED'])
velocidad += float(_ESPECIALES[especiales[i]]['E_VALUE'])
variables['SPEED'] = str(velocidad)
_ESPECIALES[especiales[i]]['E_CANT'] = int(_ESPECIALES[especiales[i]]['E_CANT'])-1
break
if _ESPECIALES[especiales[i]]['E_TYPE'] == 'LARGO':
if len(snake) == 1:
break
if int(_ESPECIALES[especiales[i]]['E_VALUE']) == -1:
snake.pop(-1)
if int(_ESPECIALES[especiales[i]]['E_VALUE']) == 1:
if movimiento == 'w': snake.insert(0, (snake[0][0] - 1, snake[0][1]))
if movimiento == 's': snake.insert(0, (snake[0][0] + 1, snake[0][1]))
if movimiento == 'a': snake.insert(0, (snake[0][0], snake[0][1] - 1))
if movimiento == 'd': snake.insert(0, (snake[0][0], snake[0][1] + 1))
_ESPECIALES[especiales[i]]['E_CANT'] = int(_ESPECIALES[especiales[i]]['E_CANT'])-1
break
return movimiento, variables, snake, _ESPECIALES |
aa85396997537a23bda51f9247ef62426ba564a3 | juancebarberis/algo1 | /practica/mapEnClase.py | 182 | 3.609375 | 4 | def map(seq, funcion):
res = []
for elem in seq:
res.append(funcion(elem))
return res
def por_2(n): return n * 2
seq = [1,2,3,4,5,6,7,8]
print(map(seq, por_2)) |
51956c3e996f59440be71017a4160422f79b320b | juancebarberis/algo1 | /pre-parcialito/parcialito_3.py | 2,155 | 3.734375 | 4 | '''
1. Escribir una funci´on reemplazar que tome una Pila, un valor nuevo y un valor viejo y
reemplace en la Pila todas las ocurrencias de valor viejo por valor nuevo. Considerar que la
Pila tiene las primitivas apilar(dato), desapilar() y esta vacia().
'''
def reemplazar(pila, nuevo, viejo):
pilaAuxiliar = Pila()
#Recorro pila hasta vaciarla
while not pila.esta_vacia():
valor = pila.desapilar()
if valor == viejo:
valor = nuevo
pilaAuxiliar.apilar(valor)
#Muevo los valor de la pila auxiliar a la pila original
while not pilaAuxiliar.esta_vacia():
pila.apilar(pilaAuxiliar.desapilar())
'''
2. Escribir un m´etodo que invierta una ListaEnlazada utilizando una Pila como estructura
auxiliar y considerando que lista solo tiene una referencia al primer nodo.
'''
import enlazadas
import pilas
import colas
def invertir_lista_enlazada(self):
''''''
pila = Pila()
#Apilo todos los elementos en pila
actual = self.prim
while actual:
pila.apilar(actual)
actual = self.prox
#Vuelvo a enlistar los datos en la lista de manera invertida
primero = self.prim
proximo = self.prox
while not pila.esta_vacia():
primero = pila.desapilar()
proximo = None
'''
3. Escribir una funci´on que reciba una pila de n´umeros y elimine de la misma los elementos
consecutivos que est´an repetidos. Se pueden usar estructuras auxiliares. La funci´on no devuelve
nada, simplemente modifica los elementos de la pila que recibe por par´ametro.
Por ejemplo: remover duplicados consecutivos(Pila([2, 8, 8, 8, 3, 3, 2, 3, 3, 3, 1, 7]))
Genera: Pila([2, 8, 3, 2, 3, 1, 7]).
'''
def limpiar_repetidos_pila(pila):
''''''
pilaAuxiliar = Pila()
while not pila.esta_vacia():
valor = pila.desencolar()
if not pila.esta_vacia():
siguiente = pila.ver_tope()
elif valor == siguiente:
continue
pilaAuxiliar.apilar(valor)
while not pilaAuxiliar.esta_vacia():
pila.apilar(pilaAuxiliar.desapilar())
'''
6. Escribir una funci´on que reciba una cola y la cantidad de elementos en la misma,
y devuelva True si los elementos forman un pal´ındromo o False si no.
Por ejemplo:
es palindromo([n, e, u, q, u, e,n], 7) − > True
'''
|
ef2adcd35cf3050024eaad85e20cfa17d87d6132 | juancebarberis/algo1 | /practica/6-1.py | 1,072 | 4.03125 | 4 | #Ejercicio 6.1. Escribir funciones que dada una cadena de caracteres:
#a) Imprima los dos primeros caracteres.
#b) Imprima los tres últimos caracteres.
#c) Imprima dicha cadena cada dos caracteres. Ej.: 'recta' debería imprimir 'rca'
#d) Dicha cadena en sentido inverso. Ej.: 'hola mundo!' debe imprimir '!odnum aloh'
#e) Imprima la cadena en un sentido y en sentido inverso. Ej: 'reflejo' imprime
#'reflejoojelfer' .
def imprimirDosPrimerosCaracteres(s):
print('Primeros dos: ' + s[:2])
def imprimirTresUltimosCaracteres(s):
print('Tres ultimos caracteres: ' + s[-3:])
def imprimirCadaDosCaracteres(s):
print('Cada dos caracteres: ' + s[::2])
def imprimirCadenaInversa(s):
print('Inversa: ' + s[::-1])
def imprimirCadenaEInversa(s):
print('Cadena e Inversa: ' + s + s[::-1])
entrada = input('Ingrese una secuencia: ')
aReturn = imprimirDosPrimerosCaracteres(entrada)
bReturn = imprimirTresUltimosCaracteres(entrada)
cReturn = imprimirCadaDosCaracteres(entrada)
dReturn = imprimirCadenaInversa(entrada)
eReturn = imprimirCadenaEInversa(entrada) |
04dcc88ad0fb461fa9aafe3e290ab9addb03c08e | juancebarberis/algo1 | /practica/5-4.py | 1,135 | 4.125 | 4 | #Ejercicio 5.4. Utilizando la función randrange del módulo random , escribir un programa que
#obtenga un número aleatorio secreto, y luego permita al usuario ingresar números y le indique
#si son menores o mayores que el número a adivinar, hasta que el usuario ingrese el número
#correcto.
from random import randrange
def adivinarNumeroAleatorio():
""""""
numeroSecreto = randrange(start= 0, stop=100)
print('Adivine el número entre 0 y 100.')
while True:
entrada = input('Ingrese el candidato:')
if not entrada.isnumeric():
print('Por favor, ingrese un número válido.')
continue
else:
entrada = int(entrada)
if entrada == numeroSecreto:
break
if entrada > numeroSecreto:
print(f'El número {entrada} es mayor que el número a adivinar.')
continue
if entrada < numeroSecreto:
print(f'El número {entrada} es menor que el número a adivinar.')
continue
print('¡Genial, adivinaste! El número era ' + str(numeroSecreto))
adivinarNumeroAleatorio() |
e08f787de4a2297aa6884dbb013e92f612423cc5 | juancebarberis/algo1 | /practica/7-7.py | 877 | 4.21875 | 4 | #Ejercicio 7.7. Escribir una función que reciba una lista de tuplas (Apellido, Nombre, Ini-
#cial_segundo_nombre) y devuelva una lista de cadenas donde cada una contenga primero el
#nombre, luego la inicial con un punto, y luego el apellido.
data = [
('Viviana', 'Tupac', 'R'),
('Francisco', 'Tupac', 'M'),
('Raquel', 'Barquez', 'H'),
('Mocca', 'Tupac Barquez', 'D'),
('Lara', 'Tupac Barquez', 'P')
]
def tuplaACadena(lista):
"""
Esta función recibe una lista de tuplas con (Nombre, Apellido, Inicial segundo nombre)
y devuelve una lista con cadenas, donde cada una representa "Nombre Inicial. Apellido).
"""
resultante = []
for persona in lista:
cadenaIndividual = ""
cadenaIndividual += f"{persona[1]} {persona[2]}. {persona[0]}"
resultante.append(cadenaIndividual)
return resultante
print(tuplaACadena(data)) |
f9209f14d346695a6956bdc5180624ca6144b176 | juancebarberis/algo1 | /ej1/norma.py | 694 | 3.515625 | 4 | # NOMBRE_Y_APELLIDO = JUAN CELESTINO BARBERIS
# PADRÓN = 105147
# MATERIA = 7540 Algoritmos y Programación 1, curso Essaya
# Ejercicio 1 de entrega obligatoria
def norma(x, y, z):
"""Recibe un vector en R3 y devuelve su norma"""
return (x**2 + y**2 + z**2) ** 0.5
assert norma(-60, -60, -70) == 110.0
assert norma(26, 94, -17) == 99.0
assert norma(34, 18, -69) == 79.0
assert norma(-34, 63, -42) == 83.0
assert norma(0, 35, 84) == 91.0
assert norma(6, -7, 6) == 11.0
assert norma(94, -3, -42) == 103.0
assert norma(0, 42, -40) == 58.0
assert norma(48, -33, 24) == 63.0
assert norma(0, 0, 0) == 0
#Con z = 85, la igualdad de cumple. (Vale también para -85).
z = 85
assert norma(-70, 14, z) == 111.0 |
ce044a40bf93a96235b26cbd956382cbdb23c054 | stavanmehta/image-test | /image_helper/shortest_sequence.py | 458 | 3.75 | 4 |
def solution(N):
# write your code in Python 3.6
commands = list()
L = 0
R = 1
def getL():
return 2 * L - R
def getR():
return 2 * R - L
print L
if N < 0:
L = getL()
commands.append(L)
while L >= N:
L = getL()
if L + R - N == 0:
R = getR()
commands.append(L)
print commands
if __name__ == '__main__':
solution(-11) |
52bd4fcad10f017b48d79ab42a97e75fa9c7b7f4 | AshleySetter/LearningTravis | /UnecessaryMath.py | 139 | 3.71875 | 4 | def multiply(a, b):
"""
multiplies 2 python objects,
a and b and returns the result
"""
result = a*b
return result
|
7926f12749d7c6331283b2b5c7006ecddd3a88e0 | frollo/AdvancedProgramming | /Lab-7/es1.py | 783 | 3.609375 | 4 | import sys
from re import sub
def isMinor(word):
return (word == "the") or (word == "and") or (len(word) <= 2)
if __name__ == '__main__':
kwicindex = list()
counter = 0
titles = dict()
with open(sys.argv[1], "r") as file:
for line in file:
counter += 1
line = sub("[^a-zA-Z0-9\s]", " ", line)
line = sub("\s+", " ", line.strip())
kwicindex += [(x, counter) for x in line.lower().split() if not isMinor(x)]
titles[counter] = line
for (kwic, c ) in sorted(kwicindex, key = lambda x: x[0]):
title = titles[c]
position = title.lower().find(kwic)
print("{0:>5d}\t{1:>33s}{2:<40s}.".format(c, title[0:position if position < 33 else 33], title[position:40 + position:]))
|
d5a5865ba7093b98233327b3f159751422511629 | frollo/AdvancedProgramming | /Lab-4/es2.py | 1,097 | 3.6875 | 4 | class SocialNode(object):
def __init__(self, name):
self.name = name
self.connections = list()
def addConnection(self, tag, other):
self.connections.append((tag, other))
other.connections.append((tag, self))
def __visit__(self, visited=None):
if visited is None: visited = set()
visited.add(self)
toVisit = [x[1] for x in self.connections if x[1] not in visited]
for friend in toVisit:
if friend not in visited:
visited = visited.union(friend.__visit__(visited))
return visited
def __str__(self):
visited = self.__visit__()
string = ""
for v in visited:
friends = ["\t{0} with {1}\n".format(x[0], x[1].name) for x in v.connections]
string = string + v.name + ":\n" + "".join(friends)
return string
if __name__ == '__main__':
lollo = SocialNode("Lorenzo Rossi")
marco = SocialNode("Marco Odore")
luca = SocialNode("Luca Rossi")
lollo.addConnection("works", marco)
lollo.addConnection("friend", luca)
print(lollo)
|
67fcb010226731a071c51b6b0e59f254eaf7a106 | frollo/AdvancedProgramming | /exams/2015-06-16/quickrecursion.py | 903 | 3.875 | 4 | def memoization(fun):
past_values = dict()
def wrapper (*args):
if args in past_values:
print ("### cached value for {0} --> {1}".format(args, past_values[args]))
else:
past_values[args] = fun(*args)
return past_values[args]
return wrapper
@memoization
def fibo(n):
if n < 3:
return 1
return fibo(n - 1) + fibo(n-2)
@memoization
def fact(n):
if n < 2:
return 1
return n * fact(n-1)
@memoization
def sum(n,m):
if n == 0:
return m
return sum(n - 1, m + 1)
if __name__ == '__main__':
print("fibo({0}) --> {1}".format(25, fibo(25)))
for x in range(1,25):
print("fact({0}) --> {1}".format(x, fact(x)))
print("sum({0}, {1}) --> {2}".format(5, 9, sum(5,9)))
print("sum({0}, {1}) --> {2}".format(4, 10, sum(4,10)))
print("sum({0}, {1}) --> {2}".format(13,1, sum(13,1)))
|
97fbde95357d10d54ef0533a0a2ea5b8ac4086e7 | ninnin92/Pyworks | /auto_analysis/days to age.py | 3,286 | 3.78125 | 4 | #!/usr/bin/env
# -*- coding: utf-8 -*-
import pandas as pd
from datetime import date, timedelta, datetime
################################################
# 宣言
################################################
s_data = pd.read_csv("subject_age.csv")
################################################
# 処理関数
################################################
# 年齢の計算(閏日補正含む) :今何歳何ヶ月なのか?
def count_years(b, s):
try:
this_year = b.replace(year=s.year)
except ValueError:
b += timedelta(days=1)
this_year = b.replace(year=s.year)
age = s.year - b.year
if s < this_year:
age -= 1
# 何歳”何ヶ月”を計算
if (s.day - b.day) >= 0:
year_months = (s.year - b.year) * 12 - age * 12 + (s.month - b.month)
else:
year_months = (s.year - b.year) * 12 - age * 12 + (s.month - b.month) - 1 # 誕生日が来るまでは月齢も-1
return age, year_months
# 月齢の計算
def count_months(b, s):
if (s.day - b.day) >= 0:
months = (s.year - b.year) * 12 + (s.month - b.month)
else:
months = (s.year - b.year) * 12 + (s.month - b.month) - 1 # 誕生日が来るまでは月齢も-1
return months
# 月齢および何歳何ヶ月の余り日数(何歳何ヶ月”何日”)
def count_days(b, s):
if (s.day - b.day) >= 0:
days = s.day - b.day
else:
try:
before = s.replace(month=s.month - 1, day=b.day)
days = (s - before).days
except ValueError:
days = s.day
# 2月は1ヶ月バックするとエラーになる時がある(誕生日が29-31日の時)
# なのでそうなった場合は、すでに前月の誕生日を迎えたことにする(setされた日が日数とイコールになる)
return days
################################################
# メイン処理
################################################
if __name__ == '__main__':
a_months = []
a_days = []
a_details = []
for i in range(0, len(s_data)):
try:
base = s_data.iloc[i, :]["days"]
base = datetime.strptime(str(base), "%Y/%m/%d")
base_day = date(base.year, base.month, base.day)
birth = s_data.iloc[i, :]["birthday"]
birth = datetime.strptime(str(birth), "%Y/%m/%d")
bir_day = date(birth.year, birth.month, birth.day)
print(base_day, bir_day)
age = str(count_years(bir_day, base_day)[0])
age_year_months = str(count_years(bir_day, base_day)[1])
age_days = str(count_days(bir_day, base_day))
age_months = str(count_months(bir_day, base_day))
age_in_days = str((base_day - bir_day).days)
age_details = age + "y " + age_year_months + "m " + age_days + "d"
except:
age_months = "NA"
age_in_days = "NA"
age_details = "NA"
a_months.append(age_months)
a_days.append(age_in_days)
a_details.append(age_details)
s_data = s_data.assign(age_days=a_days, age_months=a_months, age_details=a_details)
s_data.to_csv("result_subjects_age.csv", index=False)
|
6d16dd48bab98affcb0df5e64cd1158e846b1e57 | foundjem/COMP551-Applied-Machine-Learning | /Project 3/Code/train_test_LR_SVM_NN_raw_pixels.py | 1,872 | 3.53125 | 4 | # -*- coding: utf-8 -*-
'''
Perform Logistic Regression, SVM and feed-forward neural network
using raw pixel values on the test data
'''
import sklearn
import numpy as np
import scipy.misc # to visualize only
from scipy import stats
from sklearn.decomposition import PCA as sklearnPCA
from sklearn.feature_selection import SelectKBest
from sklearn.neural_network import MLPClassifier
from sklearn.feature_selection import chi2
from sklearn import svm, linear_model, naive_bayes
from sklearn import metrics
import math
x = np.fromfile('train_x.bin', dtype='uint8')
x = x.reshape((100000,60,60))
y = np.genfromtxt("train_y.csv", delimiter=",", dtype= np.float64)
y = y[1:100001,1]
unfolded_data = x.reshape(100000,3600)
test = np.fromfile('test_x.bin', dtype='uint8')
test = test.reshape((20000,60,60))
x_flat = x.reshape(100000,3600)
test_flat = test.reshape(20000,3600)
x_train = unfolded_data
y_train = y
x_test = test_flat
"""
Logistic Regression
"""
logreg = linear_model.LogisticRegression(C=1e5)
print "Training Logistic Regression"
logreg.fit(x_train,y_train)
print "Testing Logistic Regression"
predicted_logreg = logreg.predict(x_test)
np.savetxt("predicted_logreg_raw_pixels.csv",predicted_logreg, delimiter =",")
"""
SVM
"""
sv = svm.SVC()
print "Training SVM"
sv.fit(x_train,y_train)
print "Testing SVM"
predicted_svm = sv.predict(x_test)
np.savetxt("predicted_svm_raw_pixels.csv",predicted_svm, delimiter =",")
"""
Neural Network
"""
print "Training Neural Network"
clf = MLPClassifier(solver='adam', alpha=1e-5,
hidden_layer_sizes=(10,10), random_state=1, tol=0.0000000001, max_iter=100000)
clf.fit(x_train,y_train)
print "Testing Neural Network"
predicted_nn = clf.predict(x_test)
np.savetxt("predicted_nn_raw_pixels.csv",predicted_nn, delimiter =",")
|
e0a5afb486454fc6def28ed6c5bb593528bcd246 | foundjem/COMP551-Applied-Machine-Learning | /Project 3/Code/train_test_LR_SVM_NN_Daisy.py | 2,580 | 3.5 | 4 | # -*- coding: utf-8 -*-
'''
Perform Logistic Regression, SVM and feed-forward neural network
using Daisy features on the test data
'''
import sklearn
import numpy as np
import scipy.misc # to visualize only
from scipy import stats
from sklearn.decomposition import PCA as sklearnPCA
from sklearn.feature_selection import SelectKBest
from sklearn.neural_network import MLPClassifier
from sklearn.feature_selection import chi2
from sklearn import svm, linear_model, naive_bayes
from sklearn import metrics
import math
import matplotlib.pyplot as plt
import skimage
from skimage.feature import hog
from skimage import data, color, exposure
from skimage.feature import daisy
x = np.fromfile('train_x.bin', dtype='uint8')
x = x.reshape((100000,60,60))
y = np.genfromtxt("train_y.csv", delimiter=",", dtype= np.float64)
y = y[1:100001,1]
test = np.fromfile('test_x.bin', dtype='uint8')
test = test.reshape((20000,60,60))
print "Daisy: Saving features' loop for train"
daisy_features_train_set = np.zeros((len(x),104))
for i in range(len(x)):
descs, descs_img = daisy(x[i], step=180, radius=20, rings=2, histograms=6,
orientations=8, visualize=True)
daisy_features_train_set[i] = descs.reshape((1,104))
print "Daisy: Saving features' loop for test"
daisy_features_test_set = np.zeros((len(test),104))
for i in range(len(test)):
descs, descs_img = daisy(test[i], step=180, radius=20, rings=2, histograms=6,
orientations=8, visualize=True)
daisy_features_test_set[i] = descs.reshape((1,104))
x_train = daisy_features_train_set
y_train = y
x_test = daisy_features_test_set
"""
Logistic Regression
"""
logreg = linear_model.LogisticRegression(C=1e5)
print "Training Logistic Regression"
logreg.fit(x_train,y_train)
print "Testing Logistic Regression"
predicted_logreg = logreg.predict(x_test)
np.savetxt("predicted_logreg_daisy.csv",predicted_logreg, delimiter =",")
"""
SVM
"""
sv = svm.SVC()
print "Training SVM"
sv.fit(x_train,y_train)
print "Testing SVM"
predicted_svm = sv.predict(x_test)
savetxt("predicted_logreg_daisy.csv",predicted_svm, delimiter =",")
"""
Neural Network
"""
print "Training Neural Network"
clf = MLPClassifier(solver='adam', alpha=1e-5,
hidden_layer_sizes=(10,10), random_state=1, tol=0.0000000001, max_iter=10000)
clf.fit(x_train,y_train)
print "Testing Neural Network"
predicted_nn = clf.predict(x_test)
savetxt("predicted_logreg_daisy.csv",predicted_nn, delimiter =",")
|
2c4ac0b414a5644612b8c956b253d40c6329b94b | PeterPZhang/CrossRiver | /CrossRiver.py | 6,117 | 3.53125 | 4 | edgeFlag1=True #河岸标识符现在在A岸
edgeFlag2=False#河岸标识符 与上面一样 用这两个就可以表示船
sheep1=[1,1,1]#河岸A的羊
sheep2=[]#河岸B的狼
wolf1=[1,1,1]#河岸A的狼
wolf2=[]#河岸B的狼
GameFlag=True#游戏开始标志
edge1="A"#用来识别A岸
edge2="B"#用来识别B岸
step=0
winner_list=[]
winner={}
def oprate(SheepA, SheepB, WolfA, WolfB,EdgeFlag1,EdgeFlag2):#键入操作进行游戏
global edgeFlag1,edgeFlag2,step
for i in range(2):
op=input("请输入你的操作:")
push(op,SheepA,SheepB,WolfA,WolfB)#对当前操作进行操作
# judge(EdgeFlag1,SheepA,SheepB,WolfA,WolfB)#判断对岸状态
# EdgeFlag1=False #判断完置反 表示船走了
# EdgeFlag2=True
edgeFlag1 = not EdgeFlag1
edgeFlag2 = not EdgeFlag2
step += 1
return
def push (Op,SheepA,SheepB,WolfA,WolfB):
if Op =="S": #输入S进行操作
SheepA.pop() #当前河岸S-1
SheepB.append(1)#对岸+1
return
elif Op=="W":
WolfA.pop()
WolfB.append(1)
return
elif Op=="N":#可以不上元素返回
return
def judge(SheepA,WolfA,SheepB,WolfB):
global GameFlag
if (len(SheepA)<len(WolfA) or len(SheepB)<len(WolfB)) and len(SheepA)!=0 and len(SheepB)!=0 :
print("你输了")
GameFlag=False
elif len(SheepA)==0 and len(WolfA)==0:
print("你赢了")
fo = open("winners.txt", "a", encoding="UTF-8")
winner["姓名:"]=input("请输入你的姓名:")
winner["步数"]=step
fo.write(winner)
fo.close()
fo = open("winners.txt","r+",encoding="UTF-8")
winner_list=fo.readlines()
winner_list.sort(key="步数")
for onewinner in winner_list:
fo.write(onewinner)
fo.close()
GameFlag=False
else:
print("请继续")
return
# def iscontinue(edge,list):
# if edege
# if list.length==0:
# print("此岸已没有可操作的了")
# else:
# return
def show(EdgeFlag1,EdgeFlag2,Edge1,Edge2,Sheep1,Sheep2,Wolf1,Wolf2):
print("当前状态是:")
for wolf in wolf1:
print(""" * *
* *
**
* **
* **
*********** **
****************
******************
* * * * *
* * * * *
* * * *
* * * *
""")
for sheep in sheep1:
print(""" * *
************ ****
******************* ** ***
********************** ** ***
*************************
**********************
******************
* * *********** * *
* * * *
""")
print("河岸%s有%d只羊%d只狼" % (Edge1, len(Sheep1), len(Wolf1)))
print("______________________________________________________")
for wolf in wolf2:
print(""" * *
* *
**
* **
* **
*********** **
****************
******************
* * * * *
* * * * *
* * * *
* * * *
""")
for sheep in sheep2:
print(""" * *
************ ****
******************* ** ***
********************** ** ***
*************************
**********************
******************
* * *********** * *
* * * *
""")
print("河岸%s有%d只羊%d只狼" % (Edge2, len(Sheep2), len(Wolf2)))
if(EdgeFlag1==True):
print("""现在船在 A岸""")
elif (EdgeFlag2==True):
print("""现在船在 B岸""")
def main():
print("""欢迎进入狼羊过河游戏
游戏规则:现在在河岸A有3只羊和3只狼要都过河,但是河岸边只有一艘小船,小船自多只能承载两个单位,且必须至少有一个单位在船上时小船才会开动。
当船两岸任意一岸的羊的数量小于狼的数量时,羊就会被吃掉游戏失败。怎样做才能让所有的羊和狼都过河呢?
操作提示:
S:让此岸的羊上船
W:让此岸的狼上船
N:不上船""")
fo = open("winners.txt", "ab+")
fo.close()
show(edgeFlag1, edgeFlag2, edge1, edge2, sheep1, sheep2, wolf1, wolf2)
while GameFlag == True:
print("步数:%d"%step)
if edgeFlag1==True:
oprate(sheep1, sheep2, wolf1, wolf2,edgeFlag1,edgeFlag2)
judge(sheep1,wolf1,sheep2,wolf2)
elif edgeFlag2==True:
oprate(sheep2, sheep1, wolf2, wolf1,edgeFlag1,edgeFlag2)
judge(sheep1,wolf1,sheep2,wolf2)
show(edgeFlag1,edgeFlag2,edge1, edge2, sheep1, sheep2, wolf1, wolf2)
main()
print(edgeFlag1)
|
b32fa0aa5cf1525a58af1887b5616554f97b767f | atanasbozhinov/simple_2d_array_operations | /core/matrix_operations.py | 480 | 3.546875 | 4 | import numpy as np
def append(input_x, input_y):
try:
output = np.append(input_x, input_y, axis=0)
except ValueError:
return None
return output
def combine(input_x, input_y):
try:
output = np.append(input_x, input_y, axis=1)
except ValueError:
return None
return output
def sum(input_x, input_y):
if not (input_x.shape == input_y.shape):
return None
output = np.add(input_x, input_y)
return output |
dec49accb05722be663a3b935e948db291948826 | lerrigatto/algo2 | /src/lesson7/bfs.py | 1,014 | 3.6875 | 4 | # Implement DFS algorithm
import networkx as nx
import random
def bfs(G,u):
""" Breath First Search """
visited = []
visited_edges = []
walk = []
visited.append(u)
walk.insert(0,u)
while len(walk) > 0:
v = walk.pop()
adj = G.successors(v)
print(f"v:{v}, adj:{list(G.successors(v))}")
if adj:
for w in adj:
if w not in visited:
visited.append(w)
visited_edges.append((v,w))
walk.insert(0,w)
else:
print(f"else")
walk.pop()
return visited_edges
def main():
nodes = [0, 1, 2, 3]
edges = [(0, 1), (1, 0), (0, 2), (2, 1), (3, 0), (3, 1)]
#G = nx.DiGraph(edges)
# Generate random complete graph
G = nx.gn_graph(100)
root = random.randint(0,100)
my_visit = bfs(G, root)
good_visit = list(nx.bfs_edges(G,source=root))
print(f"My visit: {my_visit}")
print(f"Good visit: {good_visit}")
main()
|
77b80551538eb2521a2244e396b166336b6bff7d | lerrigatto/algo2 | /src/es07-bt/es0708.py | 1,277 | 3.75 | 4 | # Dato n, si stampino tutte le matrici di interi n x n tali che
# le righe e le colonne della matrice siano in ordine crescente
def print_matr(M):
for line in M:
print(''.join(str(line)))
print("---")
def stampa_bt(n, M, i=0, j=0, c=0):
if i == n:
print_matr(M)
return
else:
if c>0:
M[i][j] = c
# Controllo se sono a fine riga
if j < n -1:
stampa_bt(n,M,i,j+1)
else:
stampa_bt(n,M,i+1,0)
else:
for x in range(1,n+2):
# Nella posizione 0,0 non ho vicini da controllare
if i==0 and j==0:
stampa_bt(n,M,i,j,x)
order = True
# Controllo prima riga, ogni colonna
if i == 0 and j>0:
order &= M[i][j-1] <= x
# Controllo riga e colonna centrali
if i>0 and j>0:
order &= M[i-1][j] <= x and M[i][j-1] <= x
# Controllo prima colonna
if i>0 and j==0:
order &= M[i-1][j] <= x and M[i][j+1] <= x
if order:
stampa_bt(n,M,i,j,x)
n=2
M = [[0] * n for _ in range(n)]
stampa_bt(n, M)
|
9ce0934bfba140a3fef6e1f11dba2817a7d120f0 | SwapnaSubbagari/python-challenge | /PyBank/main.py | 1,793 | 3.625 | 4 | import os
import csv
import pandas as pd
datapath = os.path.join('Resources','budget_data.csv')
#Opening the file
with open(datapath) as budget_data_file:
df = pd.read_csv(datapath, usecols = ['Date','Profit/Losses'])
#Calculating unique list of Months and count of Months
unique_TotalMonths = df['Date'].unique()
Number_Total_Months= pd.value_counts(unique_TotalMonths).count()
#Calculating Total Amount of Profits/Losses
Net_Total_Amount= df['Profit/Losses'].sum()
PL_Amount = df['Profit/Losses']
#Calculating the difference in Profit and Loss Amount
Change = df['Profit/Losses'].diff()
result={"Date":unique_TotalMonths,"Profit/Losses":PL_Amount, "Difference/Change":Change}
result_df=pd.DataFrame(result)
result_df = result_df.set_index("Difference/Change")
#Calculating values using functions Max,Min,Mean and retreiving the dates using loc.
Max_Change=Change.max().__round__()
Min_Change=Change.min().__round__()
Average_Change=Change.mean().__round__(2)
Greatest_Increase_Month=result_df.loc[Max_Change,"Date"]
Greatest_Decrease_Month=result_df.loc[Min_Change,"Date"]
#Writing Output to text file and terminal
with open("Analysis\PyBank_Output_textfile.txt", 'x') as f:
f.write("Financial Analysis"+'\n')
f.write("----------------------------------"+'\n')
f.write("Total Months: " +str(Number_Total_Months)+'\n')
f.write("Total: $" +str(Net_Total_Amount)+'\n')
f.write("Average Change: $" +str(Average_Change)+'\n')
f.write("Greatest Increase in Profits: " +Greatest_Increase_Month+ " ($"+str(Max_Change)+")"'\n')
f.write("Greatest Decrease in Profits: " +Greatest_Decrease_Month+ " ($"+str(Min_Change)+")"'\n')
f.close()
#Reading Output from text file
with open("Analysis\PyBank_Output_textfile.txt", "r") as f:
print(f.read())
|
fa3cf86e4519a406c8de6544c9acac1c0e6a3813 | tahabroachwala/lists | /DigitsReturn.py | 256 | 4.03125 | 4 | # Write a function that takes a number and returns a list of its digits.
# So for 2342 it should return [2,3,4,2].
def returnDigits(num):
num_string = str(num)
num_list = [int(i) for i in num_string]
return num_list
print(returnDigits(2432))
|
f4890460ff11e22734a6fbd86de168a5c28f5ba9 | tahabroachwala/lists | /BubbleSort.py | 314 | 4.03125 | 4 | def bubbleSort(list1):
for passnum in range(len(list1) - 1, 0, -1):
for i in range(passnum):
if list1[i] > list1[i+1]:
list1[i], list1[i+1] = list1[i+1], list1[i]
else:
continue
list1 = [54,26,93,17,77,31,44,55,20]
bubbleSort(list1)
print(list1) |
e7c0cc03577d1dee49c6618f998312af4d18aa84 | abbeychrystal/CodingDojo_PythonRepo | /pythonFeb2021/python_fundamentals/for_loop_basic1.py | 1,159 | 4.09375 | 4 | # Basic - Print all integers of 5 from 5-1000
for i in range(0, 151, 1):
print(i)
# Multiples of Five - Print all the multiples of 5 from 5 to 1,000
for i in range(5, 1001, 5):
print(i)
# Counting, the Dojo Way - Print integers 1 to 100. If divisible by 5, print "Coding" instead. If divisible by 10, print "Coding Dojo".
for i in range( 1, 101, 1):
if i%5 == 0:
print("Coding")
else:
print(i)
# Whoa. That Sucker's Huge - Add odd integers from 0 to 500,000, and print the final sum.
count = 0
for i in range(1, 500001):
if i%2 != 0:
count = count + i
print(count)
# Countdown by Fours - Print positive numbers starting at 2018, counting down by fours.
for i in range (2018, -1, -4):
print(i)
# Flexible Counter - Set three variables: lowNum, highNum, mult. Starting at lowNum and going through highNum, print only the integers that are a multiple of mult. For example, if lowNum=2, highNum=9, and mult=3, the loop should print 3, 6, 9 (on successive lines)
def flexCount(lowNum, highNum, mult):
for i in range(lowNum, highNum+1):
if i%mult ==0:
print(i)
flexCount(2,9,3)
|
4e1a29434d93da6c303babfbfb477f5cd0ac6ecf | abbeychrystal/CodingDojo_PythonRepo | /_python/OOP/INtroOOPnotes.py | 5,581 | 4.6875 | 5 | # As almost all applications revolve around users, almost all applications define a User class. Say we have been contracted to build a banking application. The information we need about a user for a banking application would be different than what we would need if we were building a social media application. If we allowed each user to decide what information they wanted to provide to us, you can imagine how difficult it would be to sift through and utilize that information. Instead, we design a class on the backend that will dictate what information the user is required to provide. This ensures consistent creation of User instances.
# Here's the syntax for creating a class that we want to call User:
class User:
pass # we'll fill this in shortly
# And here's how we create a new instance of our class:
michael = User()
anna = User()
# We can flesh out the User class with:
# Attributes: Characteristics shared by all instances of the class type.
# Methods: Actions that an object can perform. A user, for example, should be able to make a deposit or a withdrawal, or maybe send money to another user.
# Let's start building our User class by adding attributes. Again, attributes are characteristics of an object. For example, in our banking application, we may be interested in their name, email, and account balance. Attributes are defined in a "magic method" called __init__, which method is called when a new object is instantiated.
class User: # declare a class and give it name User
def __init__(self): #First and required parameter is always 'self'
self.name = "Michael" # add in whatever attributes are required/desired
self.email = "[email protected]"
self.account_balance = 0
# The first parameter of every method within a class will be self, and the class's attribute names are also indicated by self.. We'll talk more about self later, but for now just follow this pattern: self.<<attribute_name_of_your_choosing>>.
# Then to instantiate a couple of new users:
guido = User()
monty = User()
# If we want to access our instance's attributes, we can refer to them from our instances by name:
print(guido.name) # output: Michael
print(monty.name) # output: Michael
# While we definitely want every user to have a name, email, and account balance, we don't want all of our users to have the same name and email address upon creation. How will we know what the name should be?
# With the __init__ method's parameters, we indicate what needs to be provided (i.e. arguments) when the class is instantiated. (self is always passed in implicitly.)
# In our example, even though we have 3 attributes, we only require input for 2 of them. When the User instance is created, we should expect to receive specific values for the name and email address. We'll assume, however, that everyone starts with $0 in their account. Let's adjust our code to allow arguments to be passed in upon instantiation:
class User:
def __init__(self, username, email_address):# now our method has 2 parameters!
self.name = username # and we use the values passed in to set the name attribute
self.email = email_address # and the email attribute
self.account_balance = 0 # the account balance is set to $0, so no need for a third parameter
# Now when we want to create users, we must send in the 2 required arguments:
guido = User("Guido van Rossum", "[email protected]")
monty = User("Monty Python", "[email protected]")
print(guido.name) # output: Guido van Rossum
print(monty.name) # output: Monty Python
# Now it's time to add some functionality to our class. Methods are just functions that belong to a class. This means that we can't call them independently as we have called functions previously; rather, methods must be called from an instance of a class. For example, if a user wanted to make a deposit, we'd want to be able to call the method from the user instance; because a specific user is making a deposit, it should only affect that user's balance. Making such a call would look something like this:
guido.make_deposit(100)
# To be able to call on this method, it needs to exist. Let's make it!
class User: # here's what we have so far
def __init__(self, name, email):
self.name = name
self.email = email
self.account_balance = 0
# adding the deposit method
def make_deposit(self, amount): # takes an argument that is the amount of the deposit
self.account_balance += amount # the specific user's account increases by the amount of the value received
# Don't forget that the first parameter of every method within a class should be self. Notice that, in addition to whatever arguments are passed in as a traditional function, methods also have access to the class's attributes.
# Now that our method is written, we can call it:
guido.make_deposit(100)
guido.make_deposit(200)
monty.make_deposit(50)
print(guido.account_balance) # output: 300
print(monty.account_balance) # output: 50
# Self
# It's probably time to talk about self. The self parameter includes all the information about the individual object that has called the method. But how does it get passed in? Based on the signature for the deposit method or the __init__ method, they require 2 and 3 arguments, respectively. However, when we call on them, we pass in only 1 and 2. What's happening here? Because we are calling on the method from the instance, this is known as implicit passage of self. When we call on a method from an instance, that instance, along with all of its information (name, email, balance), is passed in as self. |
afce4efaa47e3addf871f4a1df08c4f620a292da | willwburdick/Shared_Class_Work | /Assignment_05.py | 3,627 | 4.3125 | 4 | # ----------------------------------------------------------------------------------------------------------------------
# Title: Assignment 05
# Dev: William Burdick
# Date: 04/30/2018
# Description: Read and write a text file
# This project is like to the last one, but this time The To Do file will contain two columns of data (Task, Priority)
# which you store in a Python dictionary. Each Dictionary will represent one row of data and these rows of data
# are added to a Python List to create a table of data.
# ----------------------------------------------------------------------------------------------------------------------
# When the program starts, load each row of data from the To Do.txt text file into a Python dictionary.
# You can use a for loop to read a single line of text from the file and then place the data
# into a new dictionary object.
print("Hello, this program keeps track of the To Do items for your household")
#ToDoList = open("D:\UW_Python_Class\Assignment05\ToDo.txt", "r") # Open the file To Do.txt
#print (ToDoList)
# for line in ToDoList:
# Task1 = ToDoList.readline(0)
# Task2 = ToDoList.readline(1)
# print (Task1)
# print (Task2)
print("Here are the items in your list:")
ToDoRow1 = {"ID": 1, "Task": "Clean House", "Priority": "Low"}
ToDoRow2 = {"ID": 2, "Task": "Pay Bills", "Priority": "High"}
ToDoDictionary = [ToDoRow1, ToDoRow2]
print(ToDoDictionary)
# ToDoList.close()
TableHeader = ["ID", "Task", "Priority"]
NewRow = "\n" # Add the new dictionary row into a Python list object
TaskList = [TableHeader + ToDoDictionary] # Now the data will be managed as a table).
# Allow the user to Add or Remove tasks from the list using numbered choices.
# Menu of Options
Menu1 = "#1 Show current data"
Menu2 = "#2 Add a new item"
Menu3 = "#3 Remove an existing item"
Menu4 = "#4 Save Data to File"
Menu5 = "#5 Exit Program"
print (Menu1)
print (Menu2)
print (Menu3)
print (Menu4)
print (Menu5)
ItemId = 2
UserChoice = 0
while UserChoice != 5: # If boolean is not equal to 5 loop will continue
UserChoice = int(input("Please choose from the Menu:"))
if UserChoice == 1:
print ("Current list:")
print(TaskList)
elif UserChoice == 2:
NewId = (ItemId + 1)
ItemName = raw_input("Please enter the New Item:")
ItemPriority = raw_input("Please enter the Priority:")
NewRow = [NewId, ItemName, ItemPriority]
TaskList.append(NewRow)
ItemId = NewId
print (Menu1)
print (Menu2)
print (Menu3)
print (Menu4)
print (Menu5)
elif UserChoice == 3:
#print(TaskList)
#RowToRemove = int(input("Please enter the ID of the Task to remove:"))
#for line in TaskList:
#TaskList.remove([RowToRemove])
#print (TaskList)
print (Menu1)
print (Menu2)
print (Menu3)
print (Menu4)
print (Menu5)
continue
elif UserChoice == 4:
File = open("D:\UW_Python_Class\Assignment05\ToDo.txt", "w") # Open/write file named To Do.txt
File.write(str(TaskList)) # Write the Dictionary to the file
File.close() # Close the file
print ("File saved")
print (Menu1)
print (Menu2)
print (Menu3)
print (Menu4)
print (Menu5)
continue
elif UserChoice == 5: # User enters n to end loop
break # Close loop
print ("Program Closed")
print("---------------------------------------------------------------------------------------------------------------") |
6575a721c66f1f75f16f6662c2cca21dc3bb03c8 | EricB2745/Data_Analytics_and_Visualizations | /Numpy/CreatingArrays.py | 808 | 3.515625 | 4 | import numpy as np
# Create an array by converting a list
my_list1 = [1,2,3,4]
my_array1 = np.array(my_list1)
print my_array1
my_list2 = [11,22,33,44]
my_lists = [my_list1,my_list2]
my_array2 = np.array(my_lists)
print my_array2
print 'Shape of array: ' + str(my_array2.shape)
print 'Type of array: ' + str(my_array2.dtype)
zero_array = np.zeros(5)
print zero_array
print 'Shape of array: ' + str(zero_array.shape)
print 'Type of array: ' + str(zero_array.dtype)
ones_array = np.ones([5,25])
print ones_array
print 'Shape of array: ' + str(ones_array.shape)
print 'Type of array: ' + str(ones_array.dtype)
identity_array = np.eye(5)
print identity_array
print 'Shape of array: ' + str(identity_array.shape)
print 'Type of array: ' + str(identity_array.dtype)
print np.arange(5)
print np.arange(5,50,2) |
541bd87f9ff8191ea2b7758fad6d4af7206024d2 | BeginnerA234/codewars | /задача_35_7kyu.py | 306 | 3.546875 | 4 | # https://www.codewars.com/kata/5667e8f4e3f572a8f2000039/train/python
def accum(string):
res = ''
for i, s in enumerate(string):
if i == 0:
res = res + s.capitalize()
else:
res = res + '-' + (s * i).capitalize()
return res
print(accum('ZpglnRxqenU'))
|
173c8cb3559bb0b12cb3b93339ab0d69df5b9d8f | BeginnerA234/codewars | /задача_30_6kyu.py | 483 | 3.71875 | 4 | # https://www.codewars.com/kata/54da539698b8a2ad76000228/train/python
def is_valid_walk(walk):
print(walk)
res = 0
random_name = ''
for i in walk:
if i in random_name or len(random_name) == 0:
random_name += i
res += 1
else:
res -= 1
if len(walk) == 10 and res == 0:
return True
else:
return False
print(is_valid_walk(['s', 'e', 's', 's', 'n', 's', 'e', 'n', 'n', 's']))
|
8c93f27cd772c1b1dc179921157c51eb5419b32a | BeginnerA234/codewars | /задача_24_6kyu.py | 301 | 3.75 | 4 | # https://www.codewars.com/kata/54bf1c2cd5b56cc47f0007a1/train/python
def duplicate_count(text):
res = 0
text = text.lower()
for i in text:
if text.count(i)>1:
res+=1
text = text.replace(i,'')
return res
print(duplicate_count("abcdabcd"))
|
83bdc36e4e00b6aa0b7afcd4dee64707c1b3faf1 | mpwesthuizen/eng57_factory | /general_functions.py | 868 | 3.90625 | 4 | # recap function
# define a function
def say_hello(name):
return (f'Hello {name}' )
# #BAD!
# def return_formatted_name(name):
# print(name.title().strip())
def return_formatted_name(name):
return name.title().strip()
# print the return of the function outside - NOT print inside the function. If you do all argument will return none (because return is already set to none)
f_name = (return_formatted_name("marcus "))
print(say_hello((f_name)))
# # Basis of a test
#
# def return_formatted_name(name):
# return name.title().strip()
# test setup
print("Testingfunction return formatted name() with 'filipe '--> Filipe")
know_input = 'filipe '
expected_out = 'Filipe'
#test execution
print("Testingfunction return formatted name() with 'filipe '--> Filipe")
print(return_formatted_name() == expected_out)
# testing say_hello() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.