blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
af4779e613ae4ea2c34a0d4a89d5bfc03e69cc18 | kmutya/Nonlinear-Optimization | /unconstrained_optimization.py | 7,640 | 3.578125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 29 13:57:51 2019
@author: Kartik
"""
import numpy as np #arrays
from numpy import linalg as LA #Linear Algebra
import matplotlib.pyplot as plt #plotting
import sympy #symbolic computing package
from sympy.utilities.lambdify import lambdify #convert sympy objects to python interpretable
##################################################
# CREATING FUNCTIONS USING SYMPY
##################################################
#Create functions using SymPy
v = sympy.Matrix(sympy.symbols('x[0] x[1]')) #import SymPy objects
#create a function as a SymPy expression
f_sympy1 = v[0]**2 - 2.0 * v[0] * v[1] + 4 * v[1]**2 #first function
print('This is what the function looks like: ', f_sympy1)
f_sympy2 = 0.5*v[0]**2 + 2.5*v[1]**2 #second function
f_sympy3 = 4*v[0]**2 + 2*v[1]**2 + 4*v[0]*v[1] - 3*v[0] #third function
##################################################
# CONVERTING SYMPY EXPRESSIONS INTO REGULAR EXPRESSIONS
##################################################
#Extract Main function
def f_x(f_expression, values):
'''Takes in SymPy function expression along with values of dim 1x2 and return output of the function'''
f = lambdify((v[0],v[1]), f_expression) #convert to function using lambdify
return f(values[0],values[1]) #Evaluate the function at the given value
#Extract gradients
def df_x(f_expression, values):
'''Takes in SymPy function expression along with values of dim 1x2 and returns gradients of the original function'''
df1_sympy = np.array([sympy.diff(f_expression, i) for i in v]) #first order derivatives
dfx_0 = lambdify((v[0],v[1]), df1_sympy[0]) #derivative w.r.t x_0
dfx_1 = lambdify((v[0],v[1]), df1_sympy[1]) #derivative w.r.t x_1
evx_0 = dfx_0(values[0], values[1]) #evaluating the gradient at given values
evx_1 = dfx_1(values[0], values[1])
return(np.array([evx_0,evx_1]))
#Extract Hessian
def hessian(f_expression):
'''Takes in a SymPy expression and returns a Hessian'''
df1_sympy = np.array([sympy.diff(f_expression, i) for i in v]) #first order derivatives
hessian = np.array([sympy.diff(df1_sympy, i) for i in v]).astype(np.float) #hessian
return(hessian)
##################################################
# FUNCTIONS TO VISUALIZE
##################################################
#Function to create a 3-D plot of the loss surface
def loss_surface(sympy_function):
'''Plots the loss surface for the given function'''
#x = sympy.symbols('x')
return(sympy.plotting.plot3d(sympy_function, adaptive=False, nb_of_points=400))
#Function to create a countour plot
def contour(sympy_function):
'''Takes in SymPy expression and plots the contour'''
x = np.linspace(-3, 3, 100) #x-axis
y = np.linspace(-3, 3, 100) #y-axis
x, y = np.meshgrid(x, y) #creating a grid using x & y
func = f_x(sympy_function, np.array([x,y]))
plt.axis("equal")
return plt.contour(x, y, func)
#Function to plot contour along with the travel path of the algorithm
def contour_travel(x_array, sympy_function):
'''Takes in an array of output points and the corresponding SymPy expression to return travel contour plot '''
x = np.linspace(-2, 2, 100) #x-axis
y = np.linspace(-2, 2, 100) #y-axis
x, y = np.meshgrid(x, y) #creating a grid using x & y
func = f_x(sympy_function, np.array([x,y]))
plt.axis("equal")
plt.contour(x, y, func)
plot = plt.plot(x_array[:,0],x_array[:,1],'x-')
return (plot)
##################################################
#ALGORITHMS
##################################################
####Newton Method
def Newton(sympy_function, max_iter, start, step_size = 1, epsilon = 10**-2):
i = 0
x_values = np.zeros((max_iter+1,2))
x_values[0] = start
norm_values = []
while i < max_iter:
norm = LA.norm(df_x(sympy_function, x_values[i]))
if norm < epsilon:
break
else:
grad = df_x(sympy_function, x_values[i])
hessian_inv = LA.inv(hessian(sympy_function))
p = -np.dot(grad, hessian_inv)
x_values[i+1] = x_values[i] + step_size*p
norm_values.append(norm)
i+=1
print('No. of steps Newton takes to converge: ', len(norm_values))
return(x_values, norm_values)
####Steepest Descent Method
def SDM(sympy_function, max_iter, start, step_size, epsilon = 10**-2):
i = 0
x_values = np.zeros((max_iter+1,2))
x_values[0] = start
norm_values = []
while i < max_iter:
norm = LA.norm(df_x(sympy_function, x_values[i]))
if norm < epsilon:
break
else:
p = -df_x(sympy_function, x_values[i]) #updated direction to move in
x_values[i+1] = x_values[i] + step_size*p #new x-value
norm_values.append(norm)
i+=1
print('No. of steps SDM takes to converge: ', len(norm_values))
return(x_values, norm_values)
#### Conjugate Gradient Method
def CGM(sympy_function, max_iter, start, step_size, epsilon = 10**-2):
i = 0
x_values = np.zeros((max_iter+1,2))
x_values[0] = start
grad_fx = np.zeros((max_iter+1,2))
p = np.zeros((max_iter+1,2))
norm_values = []
while i < max_iter:
grad_fx[i] = df_x(sympy_function, x_values[i])
norm = LA.norm(df_x(sympy_function, x_values[i]))
if norm < epsilon:
break
else:
if i == 0:
beta = 0
p[i] = - np.dot(step_size,df_x(sympy_function, x_values[i]))
else:
beta = np.dot(grad_fx[i],grad_fx[i]) / np.dot(grad_fx[i-1],grad_fx[i-1])
p[i] = -df_x(sympy_function, x_values[i]) + beta * p[i-1]
x_values[i+1] = x_values[i] + step_size*p[i]
norm_values.append(norm)
i += 1
print('No. of steps CDM takes to converge: ', len(norm_values))
return(x_values, norm_values)
##################################################
#IMPLEMENTATION
##################################################
#Case 1
loss_surface(f_sympy1)
contour(f_sympy1)
#Newton
newton_values1, newton_norm1 = Newton(f_sympy1, 9, [-3.0,2.0])
contour_travel(newton_values1, f_sympy1)
#SDM
sdm_values1, sdm_norm1 = SDM(f_sympy1, 40, [-3.0,2.0], 0.15)
contour_travel(sdm_values1, f_sympy1)
#CGM
cgm_values1, cgm_norm1 = CGM(f_sympy1, 50, [-3.0,2.0], 0.15)
contour_travel(cgm_values1, f_sympy1)
#Case2
loss_surface(f_sympy2)
contour(f_sympy2)
#Newton
newton_values2, newton_norm2 = Newton(f_sympy2, 9, [-3.0,2.0])
contour_travel(newton_values2, f_sympy2)
#SDM
sdm_values2, sdm_norm2 = SDM(f_sympy2, 50, [-3.0,2.0], 0.15)
contour_travel(sdm_values2, f_sympy2)
#CGM
cgm_values2, cgm_norm2 = CGM(f_sympy2, 50, [-3.0,2.0], 0.15)
contour_travel(cgm_values2, f_sympy2)
#Case3
loss_surface(f_sympy3)
contour(f_sympy3)
#Newton
newton_values3, newton_norm3 = Newton(f_sympy3, 9, [-3.0,2.0])
contour_travel(newton_values3, f_sympy3)
#SDM
sdm_values3, sdm_norm3 = SDM(f_sympy3, 50, [-3.0,2.0], 0.15)
contour_travel(sdm_values3, f_sympy3)
#CGM
cgm_values3, cgm_norm3 = CGM(f_sympy3, 50, [-3.0,2.0], 0.15)
contour_travel(cgm_values3, f_sympy3)
|
8d8c6d7bf7cd63ece8498ad8a5e7653dfb9d008a | rondemora/lstm_predictor | /trader_simulator.py | 7,411 | 4 | 4 | """
Simulates a trader in the stock market during the test dataset for different models:
1. LSTM
2. Prophet
3. Other implemented trading strategies
"""
from keras.models import load_model
import lstm
import data_preprocessor
import prophet
import random
import numpy as np
import pandas as pd
from sklearn.metrics import mean_squared_error
from math import sqrt
class Colors:
BLUE = '\033[94m'
GREEN = '\033[92m'
ENDC = '\033[0m'
class Trader:
def __init__(self, initial_capital):
self.capital = initial_capital
self.stock = 0
def buy_or_hold_order(self, current_price):
"""
Simulates a buy in the market. The maximum number of shares are bought.
"""
if self.capital >= current_price:
# Both options are considered: stock was previously zero or different than zero:
stock_to_buy = self.capital // current_price
self.capital -= stock_to_buy * current_price
self.stock += stock_to_buy
# print(Colors.GREEN+'REAL BUY ++++++++++++++++'+Colors.ENDC)
# else:
# print(Colors.GREEN+'+++'+Colors.ENDC)
def sell_order(self, current_price):
"""
Simulates a sell order in case the trader holds any stock.
"""
if self.stock > 0:
self.capital += self.stock * current_price
self.stock = 0
# print(Colors.BLUE+'REAL SELL --------------------------------'+Colors.ENDC)
# else:
# print(Colors.BLUE+'---'+Colors.ENDC)
def calculate_roi(current_value, cost):
return (current_value - cost) / cost
def simulate_trade(real_values, predictions, initial_capital):
"""
Simulates any trading entity, given an array of real prices and predictions
"""
trader = Trader(initial_capital)
for day in range(len(predictions)):
if predictions[day] > real_values[day]:
trader.buy_or_hold_order(real_values[day])
else:
trader.sell_order(real_values[day])
# At the end of the dataset, a sell order is placed to convert all stocks to liquid with the price of the last
# observation:
trader.sell_order(real_values[len(predictions) - 1])
return calculate_roi(trader.capital, initial_capital)
def simulate_trade_buy_hold(real_prices, initial_capital):
"""
Simulates a trading entity which follows a simple buy and hold strategy
"""
trader = Trader(initial_capital)
trader.buy_or_hold_order(real_prices[0])
trader.sell_order(real_prices[len(real_prices) - 1])
return calculate_roi(trader.capital, initial_capital)
def simulate_trade_random(real_prices, initial_capital):
"""
Simulates trading entity following a random behaviour
"""
trader = Trader(initial_capital)
for day in range(len(real_prices)):
if random.choice([True, False]):
trader.buy_or_hold_order(real_prices[day])
else:
trader.sell_order(real_prices[day])
return calculate_roi(trader.capital, initial_capital)
def predict_average_method(real_prices, days_window):
"""
Makes the predictions for the SMA method
"""
predictions = []
for day in range(len(real_prices)):
predictions.append(calculate_mean(day, days_window, real_prices))
return np.array(predictions)
def calculate_mean(index, elems_before, array):
min_index = max(0, index - elems_before)
max_index = index
sum = 0
# max_index + 1 since the current day is also included in the calculation
for elem in range(min_index, max_index + 1):
sum += array[elem]
return sum / len(range(min_index, max_index + 1))
if __name__ == "__main__":
initial_capital = 10000
input_seq_length = 5 # Timesteps: must be changed depending on the model.
# LSTM and Prophet models to execute
lstm_model = 'model_5_500_8_96.h5'
prophet_model = 'prophet_predictions_9000_5_0.13_25.csv'
# Since the Prophet prediction DataFrame contains all the predictions and not only the ones in the test dataset,
# it will be needed to extract only the ones used for the rest of the model:
initial_date_prophet = 11671
# Prepares the test and train dataser for several models to use
X_train, y_train, X_test, y_test = data_preprocessor.prepare_data_lstm(input_seq_length, lstm.SCALER,
lstm.N_FEATURES)
# LSTM MODEL ========================================================================
model = load_model(lstm.MODELS_FOLDER + lstm_model)
rmse, y_test_scaled, predictions_lstm = lstm.predict_model(model, X_test, y_test, lstm.SCALER)
roi_lstm = simulate_trade(y_test_scaled, predictions_lstm, initial_capital)
print('ROI(LSTM) = ' + str(roi_lstm))
# PROPHET MODEL =======================================================================
df_predictions_prophet = pd.read_csv(
prophet.BASE_FOLDER + prophet.RAW_FOLDER + prophet_model)
# We select only from 2008-05-14 to 2019-12-05, which are the dates tested with the LSTM
predictions_prophet = df_predictions_prophet[initial_date_prophet:]
predictions_prophet = np.array(predictions_prophet[['yhat']])
roi_prophet = simulate_trade(y_test_scaled, predictions_prophet, initial_capital)
print('ROI(Facebook Prophet) = ' + str(roi_prophet))
# AVERAGE MODEL ======================================================================
sliding_window = 20 # Days to include in the average (current day also included)
predictions_average = predict_average_method(y_test_scaled, sliding_window)
roi_average = simulate_trade(y_test_scaled, predictions_average, initial_capital)
print('ROI(SMA ' + str(sliding_window) + ' DAYS) = ' + str(roi_average))
# AVERAGE MODEL ======================================================================
sliding_window = 60 # Days to include in the average (current day also included)
predictions_average_2 = predict_average_method(y_test_scaled, sliding_window)
roi_average_2 = simulate_trade(y_test_scaled, predictions_average_2, initial_capital)
print('ROI(SMA ' + str(sliding_window) + ' days) = ' + str(roi_average_2))
# BUY AND HOLD MODEL ==================================================================
roi_bh = simulate_trade_buy_hold(y_test_scaled, initial_capital)
print('ROI(Buy&Hold) = ' + str(roi_bh))
# RANDOM MODEL (mean of several simulations) ===========================================
simulations = 1000
roi_random = 0
for i in range(simulations):
roi_random += simulate_trade_random(y_test_scaled, initial_capital)
print('ROI(random) = ' + str(roi_random / simulations))
# LAST VALUE MODEL =====================================================================
# In this model, the prediction for the next day is the Nth-previous day closing price
shift_observations = 5
predictions_last_value = np.roll(y_test_scaled, shift_observations)
roi_last_value = simulate_trade(y_test_scaled, predictions_last_value, initial_capital)
print('ROI(last value) = ' + str(roi_last_value))
# RMSE between the predictions and a shif of N observations
# print('\tRMSE(predictions, predictions-'+str(shift_observations)+') = '+str(sqrt(mean_squared_error(y_test_scaled, predictions_last_value))))
|
ba9c0bcd80f26936d0fc42729056ed59291603b6 | Adrian0207/-LetsGo_Python | /Ejercicios_POO/ejercicio1.py | 1,317 | 3.875 | 4 | '''
Crear una clase Persona que tenga como atributo Nombre, Edad y DNI.
Aplique el uso de decoradores.
Crear una funcion que permita verificar si es mayor a 18 años
Usar la funcion __str__ para imprimir el nombre y la edad
'''
class Persona():
def __init__(self,nombre="",edad=0,dni=""):
self.__nombre=nombre
self.__edad=edad
self.__dni=dni
'''Decorador de nombre'''
@property
def nombre(self):
return self.__nombre
@nombre.setter
def nombre(self,nombre):
self.__nombre=nombre
'''Decorador de edad'''
@property
def edad(self):
return self.__edad
@edad.setter
def edad(self,edad):
self.__edad=edad
'''Decorador de DNI'''
@property
def dni(self):
return self.__dni
@dni.setter
def dni(self,dni):
self.__dni=dni
def esMayorDeEdad(self):
if self.edad >= 18:
print('Es mayor de edad')
else:
print('Es menor de edad')
def __str__(self):
return 'Nombre: {} Edad: {}'.format(self.nombre, self.edad)
p1 = Persona()
print(p1)
p2 = Persona('Pepe', 5); print(p2); p2.esMayorDeEdad()
p3 = Persona('Jorge', 18); print(p3); p3.esMayorDeEdad()
p4 = Persona('Maria', 30); print(p4); p4.esMayorDeEdad()
|
7208bf6250ee0f0e34ebfbff44bfe9d4e38ca59c | Parkyunhwan/Programmers | /Level_1/최대공약수와최소공배수.py | 746 | 3.59375 | 4 | # version1
# 유클리드 호제법을 이용한 최소공배수 최대공약수 구하기
# 작은 값은 big으로 간다. 서로의 나머지는 small로 간다. small이 0이 될 때까지 계속한다.
def gcd(a, b):
while b != 0:
tmp = a % b
a = b
b = tmp
return a
def solution(n, m):
answer = []
if (n < m):
tmp = n # 3
n = m # 12
m = tmp # 3
temp = gcd(n, m)
answer.append(temp)
answer.append((n * m) / temp)
return answer
# version2
# 파이썬의 특성을 이용해서 한번에 계산해본 버전
def gcdlcd(n, m):
n , m = max(n, m), min(n, m)
a , b = n , m
while m != 0:
tmp , n = n%m , m
m = tmp
return [n,(a*b)/n] |
4628cb33312da7e7024301c5fdef2c367470c542 | marcos-mpc/CursoEmVideo-Mundo-2 | /ex061.py | 146 | 3.78125 | 4 | termo = int(input('TERMO: '))
razao = int(input('RAZÃO: '))
cont = 0
while cont < 10:
print(termo, end=' ')
termo += razao
cont += 1
|
8d80b107dde8aad1ccc9cc9f4e81c8ebd264230b | Neela25/python-75-hackathon | /dict.py | 709 | 4.0625 | 4 | #Creating 3 dictionaries consisting of student details
student1=dict(name="Neela",regno="16C050",sem=5)
student2={"name":"Meena","regno":"16C040","sem":5}
student3=dict(name="Abi",regno="16C003",sem=5)
#Using setdefault() method,the value for key roll is obtained in n
#Since key roll is not in the dictionary,it is set
n=student2.setdefault("roll",59057)
#Printing the dictionaries
for i in student1 and student2 and student3:
print(student1[i],student2[i],student3[i])
#Since roll is only in student2, the loop doesn't print it and it is printed separately
print(student2)
#Output
'''Neela Meena Abi
16C050 16C040 16C003
5 5 5
{'name': 'Meena', 'regno': '16C040', 'sem': 5, 'roll': 59057}'''
|
f5eccea0d481a56b3b13b3738ec4880d41c466cf | huyuexin/helloworld | /list2.py | 285 | 4.09375 | 4 | squares=[]
for values in range(1,11):
square = values ** 2
squares.append(square)
print(squares)
squares=[]
for values in range(1,31,3):
squares.append(values)
print(squares)
print(squares[0:3])
print(squares[2:5])
print(squares[2:])
print(squares[-3:])
|
5d73b593bf3f45a06eb22909a01e86cf8babdf6b | deepak1214/CompetitiveCode | /LeetCode_problems/Spiral Matrix/solution.py | 1,916 | 3.5 | 4 | #Logic:
#First, four variables containing the indices for the corner points of the array are initialized.
#The algorithm starts from the top left corner of the array, and traverses the first row from left to right.
#Once it traverses the whole row it does not need to revisit it, thus, it increments the top corner index.
#Once complete, it traverses the rightmost column top to bottom. Again, once this completes,
#there is no need to revisit the rightmost column, thus, it decrements the right corner index.
#Next, the algorithm traverses the bottommost row and decrements the bottom corner index afterward.
#Lastly, the algorithm traverses the leftmost column, incrementing the left corner index once it’s done.
#This continues until the left index is greater than the right index, and the top index is greater than the bottom index.
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix:
return []
start_row = 0
start_col = 0
end_row = len(matrix)
end_col = len(matrix[0])
output = []
while(start_row<end_row and start_col<end_col):
for i in range(start_col,end_col):
output.append(matrix[start_row][i])
start_row+=1
for j in range(start_row,end_row):
output.append(matrix[j][end_col-1])
end_col-=1
if(end_row<=start_row):
break
for k in range(end_col-1,start_col-1,-1):
output.append(matrix[end_row-1][k])
end_row-=1
if(end_col<=start_col):
break
for l in range(end_row-1,start_row-1,-1):
output.append(matrix[l][start_col])
start_col+=1
return output |
0bcbeadeba532d6056209f34202662c855cadfe0 | chrhck/pyABC | /pyabc/pyabc_rand_choice.py | 436 | 3.546875 | 4 | import numpy as np
def fast_random_choice(weights):
"""
this is at least for small arrays much faster
than numpy.random.choice.
For the Gillespie overall this brings for 3 reaction a speedup
of a factor of 2
"""
cs = 0
u = np.random.rand()
for k in range(weights.size):
cs += weights[k]
if u <= cs:
return k
raise Exception("Random choice error {}".format(weights))
|
275f18aa119f11353e1c0be3ea3fe1f2d2116eb3 | rwalroth/roboto_gui | /roboto_gui/CommandLine.py | 2,392 | 3.5 | 4 | from PyQt5.QtWidgets import QLineEdit, QWidget, QHBoxLayout, QPushButton
from PyQt5 import QtCore
class CommandLine(QLineEdit):
"""Widget to simulate a command line interface. Stores past
commands, support enter to send and up and down arrow navigation.
attributes:
current: int, index of current command
commands: list, list of previous commands
"""
sendCommand = QtCore.pyqtSignal(str)
def __init__(self, parent=None):
super().__init__(parent)
self.current = -1
self.commands = ['']
def keyPressEvent(self, QKeyEvent):
"""Handles return, up, and down arrow key presses.
"""
key = QKeyEvent.key()
if key == QtCore.Qt.Key_Return or key == QtCore.Qt.Key_Enter:
self.send_command()
elif key == QtCore.Qt.Key_Up:
self.current -= 1
if self.current < -len(self.commands):
self.current = -len(self.commands)
self.setText(self.commands[self.current])
elif key == QtCore.Qt.Key_Down:
self.current += 1
if self.current > -1:
self.current = -1
self.setText(self.commands[self.current])
else:
super().keyPressEvent(QKeyEvent)
def send_command(self, q=None):
"""Adds the current text to list of commands, clears the
command line, and moves current index to -1. Subclasses should
overwrite this to actually send the command, and call this
method after to handle command storage.
"""
command = self.text()
if not (command.isspace() or command == ''):
self.commands.insert(-1, command)
self.setText('')
self.current = -1
self.sendCommand.emit(command)
class CommandLineWidget(QWidget):
sendCommand = QtCore.pyqtSignal(str)
def __init__(self, parent=None):
super(CommandLineWidget, self).__init__(parent)
self.layout = QHBoxLayout()
self.setLayout(self.layout)
self.commandLine = CommandLine(self)
self.layout.addWidget(self.commandLine)
self.sendButton = QPushButton(self)
self.sendButton.setText("Send")
self.layout.addWidget(self.sendButton)
self.sendButton.clicked.connect(self.commandLine.send_command)
self.commandLine.sendCommand.connect(self.sendCommand)
|
020d405a5555b920cbf6c1e4c38f4fe95ab1f086 | akashlahane33/AkashPythonCodes | /FilterMapreduce.py | 246 | 3.59375 | 4 |
from functools import reduce
nums = [2,3,4,5,6,7,8,9,5,4,33,55,33,654,54]
evens = list(filter(lambda n : n%2==0,nums))
doubles = list(map(lambda n : n*2,evens))
sum = reduce(lambda a,b : a + b,doubles)
print(evens)
print(doubles)
print(sum) |
0b45c3d7ba91c51e821d2d7435d268a48b67f44d | mfa1980/python-012021 | /Lekce 3/Ukoly/priklad15.py | 1,715 | 3.5 | 4 | """
Prodej vstupenek
Vytvoř program na prodej vstupenek do letního kina. Ceny vstupenek jsou v tabulce níže.
Datum Cena
1. 7. 2021 - 10. 8. 2021 250 Kč
11. 8. 2021 - 31. 8. 2021 180 Kč
Mimo tato data je středisko zavřené.
Tvůj program se nejprve zeptá uživatele na datum a počet osob, pro které uživatel chce vstupenky koupit.
Uživatel zadá datum ve středoevropském formátu. Převeď řetězec zadaný uživatelem na datum pomocí funkce
datetime.strptime().
Pokud by uživatel zadal příjezd mimo otevírací dobu, vypiš, že letní kino je v té době uzavřené.
Pokud je letní kino otevřené, spočítej a vypiš cenu za ubytování.
Data lze porovnávat pomocí známých operátorů <, >, <=, >=, ==, !=. Tyto operátory můžeš použít v podmínce if.
Níže vidíš příklad porovnání dvou dat. Program vypíše text "První datum je dřívější než druhé datum.".
prvni_udalost = datetime(2021, 7, 1)
druha_udalost = datetime(2021, 7, 3)
if prvni_datum < druhe_datum:
print("Druhá událost se stala po první události")
"""
from datetime import datetime, timedelta
datum = input("Zadej datum představení ve formátu DD.MM.RRRR: ")
datum = datetime.strptime(datum,"%d.%m.%Y")
#print(datum)
pocet = int(input("Zadej počet vstupenek: "))
zacatek_prvni = datetime(2021,7,1)
konec_prvni = datetime(2021,8,10)
zacatek_druha = datetime(2021,8,11)
konec_druha = datetime(2021,8,31)
cena = 0
if datum >= zacatek_prvni and datum <= konec_prvni:
cena = pocet * 250
print (f"Cena za vstupenky je {cena} Kč.")
elif datum >= zacatek_druha and datum <= konec_druha:
cena = pocet * 180
print (f"Cena za vstupenky je {cena} Kč.")
else:
print("Letní kino je uzavřené.") |
32927fa81e1f43cca294874da6a9ee96de4453bf | neizod/problems | /codejam/18/2/falling-balls.py | 1,560 | 3.546875 | 4 | #!/usr/bin/env python3
def get_destination(last_row):
nudge = 0
destination = [None for _ in last_row]
for index, size in enumerate(last_row):
destination[nudge:nudge+size] = [index] * size
nudge += size
return destination
def get_table(last_row):
if last_row[0] == 0 or last_row[-1] == 0:
return []
table = []
destination = get_destination(last_row)
count = [1 for _ in last_row]
while count != last_row:
next_destination = [None for _ in last_row]
row = ''
for index, dest in enumerate(destination):
if dest is not None and index > dest:
count[index] -= 1
count[index-1] += 1
next_destination[index-1] = dest
row += '/'
elif dest is not None and index < dest:
count[index] -= 1
count[index+1] += 1
next_destination[index+1] = dest
row += '\\'
else:
next_destination[index] = dest
row += '.'
destination = next_destination
table += [row]
table += ['.'*len(last_row)]
return table
def main():
for case in range(int(input())):
input()
last_row = [int(n) for n in input().split()]
answer = get_table(last_row)
feasible = 'IMPOSSIBLE' if not answer else len(answer)
print('Case #{}: {}'.format(case+1, feasible))
for line in answer:
print(line)
if __name__ == '__main__':
main()
|
ff3e3d679882abb9b0ab87c0ed7a5c790cd3f289 | sdmgill/python | /Learning/Chapter10/FindStringInFiles.py | 1,618 | 3.53125 | 4 | def get_lines_with(input_str, substr):
"""
Get all lines containing a substring.
Args:
input_str (str): String to get lines from.
substr (str): Substring to look for in lines.
Returns:
list[str]: List of lines containing substr.
"""
lines = []
for line in input_str.strip().split('\n'):
if substr.upper() in line:
#lines.append(line)
print(line)
#print(lines)
def txt_lines_with(fname, substr):
"""
Get all lines in a .txt file containing a substring.
Args:
fname (str): File name to open.
substr (str): Substring to look for in lines.
Returns:
list[str]: List of lines containing substr.
"""
f_contents = open(fname, 'r').read()
return get_lines_with(f_contents, substr)
#path = r'C:\Users\seangi\OneDrive - Ports America\_Projects\EDW\Claims\DocsAndNotes\4-20 Release DB Scripts\DB scripts\1-JDICM_Upgrade_From_2016.20_To_Latest.sql'
#path = r'C:\Users\seangi\OneDrive - Ports America\_Projects\EDW\Claims\DocsAndNotes\4-20 Release DB Scripts\DB scripts\2-JDICM_AllProcs.sql'
#path = r'C:\Users\seangi\OneDrive - Ports America\_Projects\EDW\Claims\DocsAndNotes\4-20 Release DB Scripts\DB scripts\3-JDICM_Maintenance.sql'
#path = r'C:\Users\seangi\OneDrive - Ports America\_Projects\EDW\Claims\DocsAndNotes\4-20 Release DB Scripts\DB scripts\4-Ports CM-6123 Incidents display as claims-24611.sql'
path = r'C:\Users\seangi\OneDrive - Ports America\_Projects\EDW\Claims\DocsAndNotes\4-20 Release DB Scripts\DB scripts\PythonTestFile.sql'
txt_lines_with(path,"DROP TABLE") |
2ea7e3e8fd4f05be82bbee822a99d8cba6b5d5ce | gabriellaec/desoft-analise-exercicios | /backup/user_222/ch47_2019_03_28_12_22_57_662078.py | 175 | 3.859375 | 4 | mes=int(input('numero do mes'))
lista=['janeiro','fevereiro','março','abril','maio','junho','julho','agosto','setembro','outubro','novembro','dezembro']
print(lista[mes-1])
|
a657f0ae35e6f4bd6430d74f546c410e65b9b812 | susunini/leetcode | /281.zigzag-iterator.py | 2,477 | 4 | 4 | #
# [281] Zigzag Iterator
#
# https://leetcode.com/problems/zigzag-iterator
#
# Medium (50.16%)
# Total Accepted:
# Total Submissions:
# Testcase Example: '[1,2]\n[3,4,5,6]'
#
#
# Given two 1d vectors, implement an iterator to return their elements
# alternately.
#
#
# For example, given two 1d vectors:
#
# v1 = [1, 2]
# v2 = [3, 4, 5, 6]
#
#
#
# By calling next repeatedly until hasNext returns false, the order of elements
# returned by next should be: [1, 3, 2, 4, 5, 6].
#
#
#
# Follow up: What if you are given k 1d vectors? How well can your code be
# extended to such cases?
#
#
# Clarification for the follow up question - Update (2015-09-18):
# The "Zigzag" order is not clearly defined and is ambiguous for k > 2 cases.
# If "Zigzag" does not look right to you, replace "Zigzag" with "Cyclic". For
# example, given the following input:
#
# [1,2,3]
# [4,5,6,7]
# [8,9]
#
# It should return [1,4,8,2,5,9,3,6,7].
#
#
class ZigzagIterator(object):
""" Google. Design. 21%. """
def __init__(self, v1, v2):
"""
Initialize your data structure here.
:type v1: List[int]
:type v2: List[int]
"""
self.lists = [v1, v2]
self.pointers = [0 if li else sys.maxint for li in self.lists]
def next(self):
"""
:rtype: int
"""
pointer = min(self.pointers)
list_index = self.pointers.index(pointer)
list = self.lists[list_index]
res = list[pointer]
self.pointers[list_index] += 1
if self.pointers[list_index] >= len(list):
self.pointers[list_index] = sys.maxint
return res
def hasNext(self):
"""
:rtype: bool
"""
return any([self.pointers[i] != sys.maxint for i in range(len(self.pointers))])
class ZigzagIterator(object):
""" queue. 50%. """
def __init__(self, v1, v2):
"""
Initialize your data structure here.
:type v1: List[int]
:type v2: List[int]
"""
self.queue = [v for v in (v1, v2) if v]
def next(self):
"""
:rtype: int
"""
v = self.queue.pop(0)
res = v.pop(0)
if v:
self.queue.append(v)
return res
def hasNext(self):
"""
:rtype: bool
"""
return bool(self.queue)
# Your ZigzagIterator object will be instantiated and called as such:
# i, v = ZigzagIterator(v1, v2), []
# while i.hasNext(): v.append(i.next())
|
c2cb3276c020e883219a49a70291127bc3f11f6f | gtshepard/TechnicalInterviewPrep2020 | /assignments/week1/day3/garrison_shepard_lc/find_all_anagrams/garrison_shepard_LC_438.py | 577 | 3.640625 | 4 | def findAnagrams(s, p):
result = []
p = sorted(p)
#generate all substrings
for i in range(len(s)):
j = i + 1
for j in range(len(s)+1):
if len(s[i:j]) is len(p):
#sort string of same length
sub_str = sorted(s[i:j])
# should be same if anagram
if sub_str == p:
result.append(i)
return result
# run time is O(N^2*N log N) space O(1)
# passes 22 of 36 test cases exceeds time limit on 23rd test case
# see image in folder for leetcode results |
1aa18a01c26f4d9b5af8bf5fc22e01039ff57813 | ronak-kachalia/python-tutorial | /Python Lectures/28- if __name__ == '__main__'/first_module.py | 631 | 3.859375 | 4 | # =============================================================================
# __name__ is a python reserved variable that stores name of the current module.
# if the current module is the one which is run directly by Python then __name__ = '__main__'
# else, if it is not run directly by python, then __name__ = '{Name of the Module}'
# =============================================================================
# print(f'First module\'s name: {__name__}')
print('This is always going to run')
#%%
def main():
print(f'First module\'s name: {__name__}')
if __name__ == '__main__':
main()
else:
print(__name__) |
e1b652e525c423db8e42b9dcd2da24561b057c85 | ParthDeshpande27/PH-354-2019-IISc-Assignment-Problems | /hw5/01/1.py | 622 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 9 12:02:37 2019
@author: alankar
"""
import numpy as np
np.random.seed(500)
dice1 = np.random.randint(low=1,high=6)
dice2 = np.random.randint(low=1,high=6)
print('Dice 1: %d'%dice1)
print('Dice 2: %d'%dice2)
N = int(1.e6)
dice1 = np.random.randint(low=1,high=7,size=N)
dice2 = np.random.randint(low=1,high=7,size=N)
counter = 0
for i in range(N):
if(dice1[i]==6 and dice2[i]==6): counter+=1
print('Probability of getting a double six: %f'%(counter/N))
"""
Output:
Dice 1: 3
Dice 2: 2
Probability of getting a double six: 0.027814
""" |
3f2573a4d86c6c02c0041404f362c0106251b9e1 | vcatafesta/chili | /python/decorators.py | 6,665 | 4.125 | 4 | def outer_function():
message = 'Hi'
def inner_function():
print(message)
return inner_function()
outer_function()
hi_func = outer_function()
#################################################################################
def outer_function(msg):
message = msg
def inner_function():
print(message)
return inner_function()
hi_func = outer_function('Hi')
by_func = outer_function('Bye')
#################################################################################
def cumprimentar(nome):
return 'Hello ' + nome
greet_someone = cumprimentar
print(greet_someone('Vilmar'))
#################################################################################
def greet(name):
def get_message():
return "Hello "
result = get_message() + name
return result
print(greet('Vilmar'))
#################################################################################
def hello(nome):
return 'Alo ' + nome
def call_func(func):
other_name = 'Evili'
return func(other_name)
print(call_func(hello))
#################################################################################
def compose_greet_func():
def get_message():
return "Hello there!"
return get_message
greet = compose_greet_func()
print(greet())
#################################################################################
def compose_greet_func(nome):
def get_message():
return "Ola " + nome + "!"
return get_message
greet = compose_greet_func("John")
print(greet())
#################################################################################
def get_text(name):
return "lorem ipsum, {0} dolor sit amet".format(name)
def p_decorate(func):
def func_wrapper(name):
return "<p>{0}</p>".format(func(name))
return func_wrapper
my_get_text = p_decorate(get_text)
print(my_get_text("John"))
#################################################################################
def p_decorate(func):
def func_wrapper(name):
return "<p>{0}</p>".format(func(name))
return func_wrapper
@p_decorate
def get_text(name):
return "lorem ipsum, {0} dolor sit amet".format(name)
print(get_text("John"))
#################################################################################
def p_decorate(func):
def func_wrapper(name):
return "<p>{0}</p>".format(func(name))
return func_wrapper
def strong_decorate(func):
def func_wrapper(name):
return "<strong>{0}</strong>".format(func(name))
return func_wrapper
def div_decorate(func):
def func_wrapper(name):
return "<div>{0}</div>".format(func(name))
return func_wrapper
get_text = div_decorate(p_decorate(strong_decorate(get_text)))
@div_decorate
@p_decorate
@strong_decorate
def get_text(name):
return "lorem ipsum, {0} dolor sit amet".format(name)
print(get_text("John"))
#################################################################################
def p_decorate(func):
def func_wrapper(self):
return "<p>{0}</p>".format(func(self))
return func_wrapper
class Person(object):
def __init__(self):
self.name = "John"
self.family = "Doe"
@p_decorate
def get_fullname(self):
return self.name + " " + self.family
my_person = Person()
print(my_person.get_fullname())
#################################################################################
def p_decorate(func):
def func_wrapper(*args, **kwargs):
return "<p>{0}</p>".format(func(*args, **kwargs))
return func_wrapper
class Person(object):
def __init__(self):
self.name = "John"
self.family = "Doe"
@p_decorate
def get_fullname(self):
return self.name + " " + self.family
my_person = Person()
print(my_person.get_fullname())
#################################################################################
def tags(tag_name):
def tags_decorator(func):
def func_wrapper(name):
return "<{0}>{1}</{0}>".format(tag_name, func(name))
return func_wrapper
return tags_decorator
@tags("p")
def get_text(name):
return "Hello " + name
print(get_text("John"))
#################################################################################
from functools import wraps
def tags(tag_name):
def tags_decorator(func):
@wraps(func)
def func_wrapper(name):
return "<{0}>{1}</{0}>".format(tag_name, func(name))
return func_wrapper
return tags_decorator
@tags("p")
def get_text(name):
"""returns some text"""
return "Hello " + name
print(get_text.__name__) # get_text
print(get_text.__doc__) # returns some text
print(get_text.__module__) # __main__
#################################################################################
import time
def timing_function(some_function):
"""
Outputs the time a function takes
to execute.
"""
def wrapper():
t1 = time.time()
some_function()
t2 = time.time()
return "Time it took to run the function: " + str((t2 - t1)) + "\n"
return wrapper
@timing_function
def my_function():
num_list = []
for num in (range(0, 10000)):
num_list.append(num)
print("\nSum of all the numbers: " + str((sum(num_list))))
print(my_function())
#################################################################################
def decorator_function(original_function):
def wrapper_function(*args, **kwargs):
print('wrapper executado antes de {}'.format(
original_function.__name__))
return original_function(*args, **kwargs)
return wrapper_function
@decorator_function
def display():
print('Display function ran')
@decorator_function
def display_info(name, age):
print("display_info ran with arguments ({},{})".format(name, age))
display_info('Vilmar', 50)
display()
#################################################################################
from funcoes import sci_logger
@sci_logger
def display_info_log(name, age):
print("display_info ran with arguments ({},{})".format(name, age))
display_info_log('Vilmar', 50)
display_info_log('Vilmar', 150)
display_info_log('Vilmar', 250)
display_info_log('Vilmar', 350)
|
f9212a3a72f965cad9c72387e1669cea7bb7353a | Troy-Wang/LeetCode | /201611_Week2/20161108_2.py | 507 | 3.859375 | 4 | """
Count Numbers with Unique Digits
Given a non-negative integer n, count all numbers with unique digits, x, where 0 <= x < 10n.
"""
class Solution(object):
def countNumbersWithUniqueDigits(self, n):
"""
:type n: int
:rtype: int
"""
if n == 0:
return 1
if n > 10:
n = 10
count = 0
current = 1
for i in range(n - 1):
current *= 9 - i
count += current
return count * 9 + 10
|
889809ecfa1525b20408b3e63edcb25409273c9a | gcctryg/cs362_hw4 | /q2.py | 694 | 3.734375 | 4 | import unittest
def calc_avg(num):
sumNum = 0
for i in num:
sumNum = sumNum + i
length = len(num)
avg = ( sumNum / length) if length != 0 else 0
return avg
class testCase(unittest.TestCase):
def test_func(self):
self.assertEqual(calc_avg([1,3,5,7,9]), 5)
self.assertEqual(calc_avg([1,3,5,7,9]), 25)
def test_emptyList(self):
self.assertTrue(calc_avg([1,2,3,4,5]))
self.assertTrue(calc_avg([]))
def test_divZero(self):
with self.assertRaises(ValueError):
calc_avg([])
with self.assertRaises(ValueError):
calc_avg([1,2,3,4])
if __name__ == '__main__':
unittest.main()
|
c28faf8c80a3b738e80aaebfce38ecd275b67972 | shantanu-python/Python | /prime.py | 428 | 4.125 | 4 | import math
def is_prime(a):
n = abs(a)
if (n<2):
return False
elif (n%2==0):
return False
n1 = int(math.sqrt(n))+ 1
return all(n%i for i in range(3,n1,2))
q = None
while(q!= "q"):
x = int(input("Enter the number :"))
p = is_prime(x)
s = "is prime." if p else "is not prime."
print(x,s)
q = input("Press q to exit , any other key to continue :")
|
a22d626df17fcca840d974e601e4169f4cce5de3 | rescenic/Softuni-Python-v2 | /python-fundamentals/09 RegEx - Excercise/01. Capture the Numbers.py | 159 | 3.5625 | 4 | import re
pattern = r'\d+'
numbers = []
line = input()
while line:
numbers.extend(re.findall(pattern, line))
line = input()
print(' '.join(numbers)) |
65ea595058056595299b2c9d3df6279623e0868f | bssrdf/pyleet | /F/FindLatestGroupofSizeM.py | 2,006 | 3.578125 | 4 | '''
-Medium-
Given an array arr that represents a permutation of numbers from 1 to n. You have a binary
string of size n that initially has all its bits set to zero.
At each step i (assuming both the binary string and arr are 1-indexed) from 1 to n,
the bit at position arr[i] is set to 1. You are given an integer m and you need to
find the latest step at which there exists a group of ones of length m. A group of ones
is a contiguous substring of 1s such that it cannot be extended in either direction.
Return the latest step at which there exists a group of ones of length exactly m. If no
such group exists, return -1.
Example 1:
Input: arr = [3,5,1,2,4], m = 1
Output: 4
Explanation:
Step 1: "00100", groups: ["1"]
Step 2: "00101", groups: ["1", "1"]
Step 3: "10101", groups: ["1", "1", "1"]
Step 4: "11101", groups: ["111", "1"]
Step 5: "11111", groups: ["11111"]
The latest step at which there exists a group of size 1 is step 4.
Example 2:
Input: arr = [3,1,5,4,2], m = 2
Output: -1
Explanation:
Step 1: "00100", groups: ["1"]
Step 2: "10100", groups: ["1", "1"]
Step 3: "10101", groups: ["1", "1", "1"]
Step 4: "10111", groups: ["1", "111"]
Step 5: "11111", groups: ["11111"]
No group of size 2 exists during any step.
Example 3:
Input: arr = [1], m = 1
Output: 1
Example 4:
Input: arr = [2,1], m = 2
Output: 2
Constraints:
n == arr.length
1 <= n <= 10^5
1 <= arr[i] <= n
All integers in arr are distinct.
1 <= m <= arr.length
'''
from typing import List
class Solution:
def findLatestStep(self, arr: List[int], m: int) -> int:
A = arr
if m == len(A): return m
length = [0] * (len(A) + 2)
res = -1
for i, a in enumerate(A):
left, right = length[a - 1], length[a + 1]
if left == m or right == m:
res = i
length[a - left] = length[a + right] = left + right + 1
return res
if __name__ == "__main__":
print(Solution().findLatestStep(arr = [3,5,1,2,4], m = 1)) |
f8e91d79531c94dd1c38e90a513aacc7af7a21f4 | edutilos6666/PythonExamples | /NumberExample.py | 1,885 | 3.96875 | 4 | import math
import random
def example2():
'random methods'
print('random.random() = ', random.random())
print('random.randint(10, 1000) =', random.randint(10, 1000))
print('random.randrange(10, 1000) =', random.randrange(10, 1000))
print('random.randrange(10, 1000, 2) = ', random.randrange(10, 1000, 2))
print('random.randrange(10, 1000, 3) = ', random.randrange(10, 1000, 3))
numbers = [1, 2,3, 4, 5, 6, 7, 8, 9]
names = ["foo", "bar", "bim", "pako", "edu"]
print('numbers = ', numbers)
print('names = ', names)
print('random.choice(numbers) = ', random.choice(numbers))
print('random.choice(names) = ', random.choice(names))
print('random.uniform(10, 1000) = ', random.uniform(10, 1000))
random.shuffle(numbers)
random.shuffle(names)
print('numbers after shuffle = ', numbers)
print('names after shuffle = ', names)
print()
def example1():
'math methods'
str = '100'
n = int(str)
f = float(str)
print('int(str) = ',n)
print('float(str) = ', f)
print('math.pi = ', math.pi)
print('math.e = ', math.e)
print('math.sin(math.pi/3) = ', math.sin(math.pi/3))
print('math.cos(math.pi/3) = ', math.cos(math.pi/3))
print('math.tan(math.pi/3) = ', math.tan(math.pi/3))
print('math.asin(0.5) = ', math.asin(0.5))
print('math.acos(0.5) = ', math.acos(0.5))
print('math.atan(0.5) = ', math.atan(0.5))
print('math.ceil(0.6) = ', math.ceil(0.6))
print('math.floor(0.6) = ', math.floor(0.6))
print('math.fabs(-0.5) = ', math.fabs(-0.5))
print('math.factorial(10) = ', math.factorial(10))
print('math.log(64, 2) = ', math.log(64, 2))
print('math.log2(64) = ', math.log2(64))
print('math.log10(1000) = ', math.log10(1000))
print('math.log1p(e**4) = ', math.log1p(math.e**4))
print('math.pow(10, 3) = ', math.pow(10, 3))
print()
|
a08ace17e89a52ed82d2467cb7dea5823fac6923 | RansomBroker/self-python | /Recursive/binarySearchTree.py | 1,101 | 4.15625 | 4 | class Node:
#make constructor for insert data
def __init__(self, key):
self.left = None
self.right = None
self.value = key
#insert item based on root
def insertTree(self, root, node):
if root is None:
root = node
else:
#insert value to right
if root.value < node.value:
if root.right is None:
root.right = node
else:
self.insertTree(root.right, node)
if root.value > node.value:
if root.left is None:
root.left = node
else:
self.insertTree(root.left, node)
# will print tree
def tree(self, root):
if root:
self.tree(root.left)
print(root.value)
self.tree(root.right)
root = Node(40)
root.insertTree(root, Node(10))
root.insertTree(root, Node(15))
root.insertTree(root, Node(9))
root.insertTree(root, Node(6))
root.insertTree(root, Node(24))
root.insertTree(root, Node(32))
root.tree(root) |
0bd84834e8d43615e9a21b3b7544af06ebb1983f | priscilasvn10/Python_Desafios | /Desafio081.py | 568 | 3.984375 | 4 | '''ler vários números e colocar na lista
a) quantos números foram digitados
b)ordem decrescente
c)se o valor 5 foi digitado e está ou não
na lista'''
num = []
i = 0
while True:
num.append(int(input('Digite um número: ')))
c = str(input('Deseja continuar? [S/N] ')).upper().strip()[0]
if c == 'N':
break
print('='*30)
print(f'Foram digitados {len(num)} números.')
num.sort(reverse=True)
print(f'A ordem decrescente é: {num}')
if 5 in num:
print('O valor 5 foi digitado na lista.')
else:
print('O valor 5 não foi digitado na lista.') |
d2c2746a4575cfbcadcc42469929b9e316a4b8f5 | github-markdown-ui/github-markdown-ui | /test/helpers.py | 414 | 3.828125 | 4 | from re import sub
def remove_whitespace(text: str) -> str:
"""Removes all whitespace from a string (including newline characters) after a > or before a <.
This function allows us to write the expected HTML syntax outputs of the test cases in a more readable form, as long as
we don't put whitespace around < or > characters within HTML tags.
"""
return sub(r'(?<=>)\s+|\s+(?=<)', '', text)
|
a1768e5e3122e215c586a96248f962d1713ca816 | geislor/python-tdd-exercises | /count_num_vowels.py | 233 | 3.984375 | 4 | """
Exercise 4
"""
VOWELS = ['a', 'e', 'i', 'o', 'u', 'y']
def count_num_vowels(s):
"""
Returns the number of vowels in a string s.
whit listcomprehension
"""
return len([i for i in s if i.lower() in VOWELS ])
|
1cd259421166313dd885b7ec7c09362b2a5e0c5b | qmnguyenw/python_py4e | /geeksforgeeks/python/python_all/121_14.py | 3,246 | 4.25 | 4 | Python | Group and count similar records
Sometimes, while working with records, we can have a problem in which we need
to collect and maintain the counter value inside records. This kind of
application is important in web development domain. Let’s discuss certain ways
in which this task can be performed.
**Method #1 : Using loop +Counter() + set()**
The combination of above functionalities can be employed to achieve this task.
In this, we run a loop to capture each tuple and add to set and check if it’s
already existing, then increase and add a counter value to it. The cumulative
count is achieved by using Counter().
__
__
__
__
__
__
__
# Python3 code to demonstrate working of
# Group and count similar records
# using Counter() + loop + set()
from collections import Counter
# initialize list
test_list = [('gfg', ), ('is', ), ('best', ), ('gfg', ),
('is', ), ('for', ), ('geeks', )]
# printing original list
print("The original list : " + str(test_list))
# Group and count similar records
# using Counter() + loop + set()
res = []
temp = set()
counter = Counter(test_list)
for sub in test_list:
if sub not in temp:
res.append((counter[sub], ) + sub)
temp.add(sub)
# printing result
print("Grouped and counted list is : " + str(res))
---
__
__
**Output :**
> The original list : [(‘gfg’, ), (‘is’, ), (‘best’, ), (‘gfg’, ), (‘is’, ),
> (‘for’, ), (‘geeks’, )]
> Grouped and counted list is : [(2, ‘gfg’), (2, ‘is’), (1, ‘best’), (1,
> ‘for’), (1, ‘geeks’)]
**Method #2 : UsingCounter() + list comprehension + items()**
This is one liner approach and recommended to use for programming. The task of
loops is handled by list comprehension and items() is used to access all the
elements of Counter converted dictionary to allow computations.
__
__
__
__
__
__
__
# Python3 code to demonstrate working of
# Group and count similar records
# using Counter() + list comprehension + items()
from collections import Counter
# initialize list
test_list = [('gfg', ), ('is', ), ('best', ), ('gfg', ),
('is', ), ('for', ), ('geeks', )]
# printing original list
print("The original list : " + str(test_list))
# Group and count similar records
# using Counter() + list comprehension + items()
res = [(counter, ) + ele for ele, counter in
Counter(test_list).items()]
# printing result
print("Grouped and counted list is : " + str(res))
---
__
__
**Output :**
> The original list : [(‘gfg’, ), (‘is’, ), (‘best’, ), (‘gfg’, ), (‘is’, ),
> (‘for’, ), (‘geeks’, )]
> Grouped and counted list is : [(2, ‘gfg’), (2, ‘is’), (1, ‘best’), (1,
> ‘for’), (1, ‘geeks’)]
Attention geek! Strengthen your foundations with the **Python Programming
Foundation** Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures
concepts with the **Python DS** Course.
My Personal Notes _arrow_drop_up_
Save
|
4c8b05377b1b43858fc1cdc43c2828636fd21f4e | Praneta-Paithankar/CSCI-B505-Applied-Algorithm | /Assignment 1/Sorting.py | 6,066 | 4.1875 | 4 | import time,FileOperations
#Sort numbers using bubble sort
def bubble_sort(numbers):
for i in xrange(0, len(numbers)-1):
for j in xrange(len(numbers)-1, i, -1):
if numbers[j] < numbers[j-1]:
numbers[j], numbers[j-1] = numbers[j-1], numbers[j]
return numbers
#sort numbers using insertion sort
def insertion_sort(numbers):
for j in xrange(1,len(numbers)-1):
key = numbers[j]
i = j-1
while i >= 0 and numbers[i]>key:
numbers[i+1] = numbers[i]
i=i-1
numbers[i+1] = key
return numbers
#get input
def get_input(file_name):
input_list = []
with open(file_name) as f:
for line in f:
numbers = map(int, line[1:-2].split(","))
input_list.append(numbers)
return input_list
#Read data from file and use bubble sort for sorting random numbers
def run_bubblesort():
with open("Output/bubblesortOutput.csv", "w") as csvfile:
#f.write("Number of input : average time \n")
for x in xrange(400, 10000, 400):
print "No of inputs:{0}\n".format(x)
time_list=[]
file_name = "Input/{0}random.txt".format(x)
input = get_input(file_name)
for numbers in input:
start_time = time.time()
sorted_numbers= bubble_sort(numbers)
end_time=time.time()
time_list.append(end_time-start_time)
#print sorted_numbers
print time_list
avg_time=sum(time_list)/len(time_list)
print avg_time
csvfile.write("{0},{1}\n".format(x, avg_time))
return
#Read data from file and use insertion sort for sorting random numbers
def run_insertionsort():
with open("Output/insertionsortOutput.csv", "w") as f:
#f.write("Number of input :average time\n")
for x in xrange(400, 10000, 400):
print "No of inputs:{0}\n".format(x)
time_list=[]
file_name = "Input/{0}random.txt".format(x)
input = get_input(file_name)
for numbers in input:
start_time = time.time()
sorted_numbers= insertion_sort(numbers)
end_time=time.time()
time_list.append(end_time-start_time)
#print sorted_numbers
print time_list
avg_time = sum(time_list) / len(time_list)
print avg_time
f.write("{0},{1}\n".format(x, avg_time))
#Read data from file and use bubble sort for sorting non-decreasing random numbers
def run_non_decreasing_bubblesort():
with open("Output/NonDecreasingBubbleSort.csv","w") as f:
#f.write("Number of input : time\n")
for x in xrange(400, 10000, 400):
print "No of inputs:{0}\n".format(x)
file_name = "Input/{0}nondecreasing.txt".format(x)
input = get_input(file_name)
numbers= input[0]
start_time = time.time()
sorted_numbers = bubble_sort(numbers)
end_time = time.time()
runtime = end_time - start_time
#print sorted_numbers
print runtime
f.write("{0},{1}\n".format(x, runtime))
return
#Read data from file and use bubble sort for sorting non-increasing random numbers
def run_non_increasing_bubblesort():
with open("Output/NonIncreasingBubbleSort.csv","w") as f:
#f.write("Number of input : time \n ")
for x in xrange(400, 10000, 400):
print "No of inputs:{0}\n".format(x)
file_name = "Input/{0}nonincreasing.txt".format(x)
input = get_input(file_name)
numbers = input[0]
start_time = time.time()
sorted_numbers = bubble_sort(numbers)
end_time = time.time()
runtime = end_time - start_time
#print sorted_numbers
print runtime
f.write("{0},{1}\n".format(x, runtime))
return
#Read data from file and use insertion sort for sorting non-decreasing random numbers
def run_non_decreasing_insertionsort():
with open("Output/NonDecreasingInsertionSort.csv", "w") as f:
#f.write("Number of input : time\n")
for x in xrange(400, 10000, 400):
print "No of inputs:{0}\n".format(x)
file_name = "Input/{0}nondecreasing.txt".format(x)
input = get_input(file_name)
numbers = input[0]
start_time = time.time()
sorted_numbers = insertion_sort(numbers)
end_time = time.time()
runtime = end_time - start_time
#print sorted_numbers
print runtime
f.write("{0},{1}\n".format(x, runtime))
return
#Read data from file and use insertion sort for sorting non-increasing random numbers
def run_non_increasing_insertionsort():
with open("Output/NonIncreasingInsertionSort.csv", "w") as f:
#f.write("Number of input :time \n")
for x in xrange(400, 10000, 400):
print "No of inputs:{0}\n".format(x)
file_name = "Input/{0}nonincreasing.txt".format(x)
input = get_input(file_name)
numbers = input[0]
start_time = time.time()
sorted_numbers = insertion_sort(numbers)
end_time = time.time()
runtime = end_time - start_time
#print sorted_numbers
print runtime
f.write("{0},{1}\n".format(x, runtime))
return
def main():
FileOperations.create_folder("Output")
print "random bubble sort"
run_bubblesort()
print "random insertion sort"
run_insertionsort()
print "non-decreasing bubble sort"
run_non_decreasing_bubblesort()
print "non-increasing insertion sort"
run_non_decreasing_insertionsort()
print "non-decreasing bubble sort"
run_non_increasing_bubblesort()
print "non-increasing insertion sort"
run_non_increasing_insertionsort()
print "Operations completed"
if __name__ == '__main__':
main()
|
d71625a6eff62580a14c614696ac4b2b2a0f9836 | Deiv101/functions_tutorial | /functions_tutorial.py | 7,807 | 3.84375 | 4 | # Creating a function
def my_function():
print("Hello from a function")
# Calling a Function
my_function()
####################################################################################################################################################################
# Arguments
def my_function(fname):
print(fname + " Rakojoana")
my_function("David")
my_function("Lilly")
my_function("Amo")
####################################################################################################################################################################
# Number of Parameters
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Deiv", "Rakojoana")
####################################################################################################################################################################
# Arbitrary Arguments, *args
"""
If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition.
This way the function will receive a tuple of arguments, and can access the items accordingly:
"""
def my_function(*cities):
print("The capital city is " + cities[2])
my_function("Mafeteng", "Mohale's Hoek", "Maseru", "Quthing", "Mokhotlong", "Thaba-Tseka", "Berea", "Qacha's Nek", "Leribe")
####################################################################################################################################################################
# Keyword Arguments
"""You can also send arguments with the key = value syntax.
This way the order of the arguments does not matter."""
def my_function(city3, city2, city1):
print("The 3rd city is " + city3)
my_function(city1="Mafeteng", city2="Berea", city3="Maseru")
####################################################################################################################################################################
# Passing a list as an argument
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
####################################################################################################################################################################
# Return values
def my_function(x):
return 5 * x
print(my_function(10000))
print(my_function(4))
print("\t", my_function("Deiv"))
####################################################################################################################################################################
# Recursion
def tri_recursion(k):
if k > 0:
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
print("\n\nRecursion Example Results")
tri_recursion(6)
####################################################################################################################################################################
def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning")
greet("Amo")
####################################################################################################################################################################
# Example of return
def abs_value(num):
"""This function returns the absolute value of the entered number"""
if num >= 0:
return num
else:
return -num
print(abs_value(-5)); print(abs_value(3))
###########################################################################################################################
print("\t")
def greet(name, msg):
"""This function greets the person with the provided message"""
print("Hello" + name + ", " + msg)
greet("Amo", "Top of the morning to you!")
###########################################################################################################################
# Default arguments
def greet(name, msg = "Good morning!"):
"""This function greets the person with the provided message"""
"""If the message is not provided, it defaults to 'Good morning!'"""
print("Hello, ", name,'' + msg)
greet("Amo,")
greet("Amo,", "How are you this morning?")
###########################################################################################################################
print("\n")
# Recursive function
def factorial(x):
"""This is a recursive function to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 7
print("The factorial of num", num, "is", factorial(num))
###########################################################################################################################
print("\n")
def calc(num1, num2):
add = num1 + num2
print("The Sum of ", num1, "&", num2, "is", add)
calc(2, 4)
###########################################################################################################################
print("\n")
def func(a, b, c):
lis = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
if num in lis:
print("The fifth number is", lis[5])
else:
return num
func(2, 4, 6)
###########################################################################################################################
print("\n")
def iter(a):
x = int(input("Enter a number: "))
while x <= 0:
print("The number you entered is: ", x)
break
else:
return x
iter(2)
###########################################################################################################################
print("\n")
def lumelisa(name):
print("Lumela " + name)
lumelisa("Amo")
####################################################################################################################################################################
18/11/2021
def square(number):
"""Calculate the square of number."""
return number ** 2
square(5)
####################################################################################################################################################################
def maximum(a, b, c):
"""Return the maximum of three values."""
max_value = a
if b > max_value:
max_value = b
if c > max_value:
max_value = c
return max_value
####################################################################################################################################################################
def func(a):
num = int(input("Enter a number: "))
if num != 0:
print("You entered a number that's not a zero")
else:
print("You hit a zero")
return num
func(1)
####################################################################################################################################################################
def factorial(number):
"""Return factorial of a number."""
if number <= 1:
return 1
return number * factorial(number - 1) # recursive call
for i in range(11):
print(f'{i}! = {factorial(i)}')
####################################################################################################################################################################
# Lists and Tuples
a_list = []
for number in range(1, 6):
a_list +=[number]
####################################################################################################################################################################
numbers = [3, 7, 1, 4, 2, 8, 5, 6]
key = 1000
if key in numbers:
print(f'found {key} at index {numbers.index(search_key)}')
else:
print(f'{key} not found')
####################################################################################################################################################################
|
8e72fb71eeaec9570b6721e89afeb3c783af2aac | GiovanniCassani/discriminative_learning | /nonwords/neighbors.py | 6,763 | 3.515625 | 4 | __author__ = 'GCassani'
import helpers as help
from collections import defaultdict, Counter
def map_neighbours_to_pos(neighbours_file, wordform2pos, ids2words):
"""
:param neighbours_file: the file with the neighbours retrieved for each test item: each item is on a different
column, with neighbours retrieved for it in the same column
:param wordform2pos: a dictionary mapping wordforms to the set of pos tags with which the wordform was found in
the input corpus
:param ids2words: a dictionary mapping column indices to test items
:return neighbours: a dictionary mapping each test item to the list of pos tags of the words retrieved as
neighbours. in case a neighbour is ambiguous with respect to the category, all categories
with which it was retrieved are considered
"""
neighbours = defaultdict(list)
with open(neighbours_file, "r") as f:
for line in f:
words = line.strip().split('\t')
for col_id, word in enumerate(words):
if not word in ids2words.values():
if ':' in word:
neighbours[ids2words[col_id]].append(word.split(':')[1])
else:
target_tags = wordform2pos[word]
for tag in target_tags:
neighbours[ids2words[col_id]].append(tag)
return neighbours
########################################################################################################################
def get_tag_distribution(neighbours):
"""
:param neighbours: a dictionary mapping words to the list of pos tags of the neighbors
:return neighbours_distr: a dictionary mapping each test word to each category which appears in the neighborhood
and its frequency of occurrence
:return pos_set: a set containing the unique pos tags found in the neighbours list
"""
neighbours_distr = defaultdict(dict)
pos_set = set()
for word in neighbours:
neighbours_list = neighbours[word]
distr = Counter(neighbours_list)
for pos in distr:
neighbours_distr[word][pos] = distr[pos]
pos_set.add(pos)
return neighbours_distr, pos_set
########################################################################################################################
def write_neighbor_summary(output_file, neighbours_distr, pos_set, table_format="long", cond="minimalist"):
"""
:param output_file: the path where the summary will be written to
:param neighbours_distr: a dictionary mapping words to the pos tags of its neighboring vectors and their
frequency count in the neighbor list
:param pos_set: an iterable of strings, indicating the pos tags encountered across the neighbors
:param cond: a string indicating the input used for the experiment
:param table_format: a string indicating how to print data to table, either 'long' or 'wide'. In the long
format, five columns are created, first the nonword followed by its intended pos tag,
then the condition, then the category, then the frequency. In the wide format, each
category is a different column, with each nonword-category cell indicating how many
neighbors tagged with the category were found in the neighborhood of the nonword.
An extra column indicates the condition.
"""
pos_tags = sorted(pos_set)
with open(output_file, "w") as f:
if table_format == "wide":
f.write("\t".join(["Nonword", "Target", "Condition", "\t".join(pos_tags)]))
f.write('\n')
for word in neighbours_distr:
baseform, target = word.split("|")
counts = []
for tag in pos_tags:
try:
counts.append(str(neighbours_distr[word][tag]))
except KeyError:
counts.append("0")
f.write('\t'.join([baseform, target, cond, '\t'.join(counts)]))
f.write('\n')
elif table_format == "long":
f.write("\t".join(["Nonword", "Target", "Condition", "Category", "Count"]))
f.write('\n')
for word in neighbours_distr:
baseform, target = word.split("|")
for tag in pos_tags:
try:
f.write('\t'.join([baseform, target, cond, tag, str(neighbours_distr[word][tag])]))
except KeyError:
f.write('\t'.join([baseform, target, cond, tag, '0']))
f.write('\n')
else:
raise ValueError("unrecognized format %s!" % table_format)
########################################################################################################################
def nn_analysis(neighbours_file, tokens_file, output_file, cond="minimalist", table_format="long"):
"""
:param neighbours_file: the path to the file containing neighbours for the target words
:param tokens_file: the path to the file containing summary information about tokens, lemmas, pos tags, and
triphones
:param output_file: the path where the summary will be written to
:param cond: a string indicating the input used for the experiment
:param table_format: a string indicating how to print data to table, either 'long' or 'wide'. In the long
format, five columns are created, first the nonword followed by its intended pos tag,
then the condition, then the category, then the frequency. In the wide format, each
category is a different column, with each nonword-category cell indicating how many
neighbors tagged with the category were found in the neighborhood of the nonword.
An extra column indicates the condition.
"""
ids2words = help.map_indices_to_test_words(neighbours_file)
words2pos = help.map_words_to_pos(tokens_file)
neighbors2pos = map_neighbours_to_pos(neighbours_file, words2pos, ids2words)
neighbors_distr, pos_set = get_tag_distribution(neighbors2pos)
write_neighbor_summary(output_file, neighbors_distr, pos_set, cond=cond, table_format=table_format)
|
95a5575a9d0d210d3b7be2c99aeb587c9f0a2c40 | aowenb/Purwadhika-Excercise | /soal 5.py | 521 | 3.640625 | 4 | x = input('masukkan sebuah kalimat : ')
print('kalimat original : ',x)
def counter(x):
up = []
low = []
for i in x[::1]:
if i.isupper() == True:
up.append(i)
else:
low.append(i)
for i in low:
if i == ' ':
low.remove(' ')
return len(up), len(low)
# 0 adalah Kapital dan 1 adalah non kapital
print('banyaknya Jumlah Huruf Kapital Di Kalimat adalah ', counter(x)[0])
print('banyaknya Jumlah Huruf Kapital Di Kalimat adalah ', counter(x)[1])
|
753aa4778234c296d70b2cfc2b01673aa93f58b5 | parolaraul/itChallengeML2017 | /Peru - Buscando Numeros - 60 pts/peru.py | 806 | 3.796875 | 4 | # Peru
pi = open('pi', 'r').read()
def is_prime(n):
if n == 2 or n == 3: return True
if n < 2 or n%2 == 0: return False
if n < 9: return True
if n%3 == 0: return False
r = int(n**0.5)
f = 5
while f <= r:
if n%f == 0: return False
if n%(f+2) == 0: return False
f +=6
return True
#number as string
def is_Capicua(given_str):
if (len(given_str) % 2 == 0):
a,b = given_str[:len(given_str)/2], given_str[len(given_str)/2:][::-1]
else:
a,b = given_str[:(len(given_str)-1)/2], given_str[(len(given_str)+1)/2:][::-1]
return a==b
counter = 0
for i in range(0,len(pi)):
numero = pi[i]+pi[i+1]+pi[i+2]+pi[i+3]+pi[i+4]+pi[i+5]+pi[i+6]
if is_prime(int(numero)) and is_Capicua(numero):
counter+=1
print numero
if counter == 7:
print numero,i
break |
8b47a892df850416f780588f2791e63fd00f3d32 | LachubCz/VUT-FIT-MIT | /6_semestr/DIP/src/pero/src/arabic_helper.py | 572 | 3.609375 | 4 | import arabic_reshaper
import re
def normalize_text(text):
text = reverse_transcription(text)
text = arabic_reshaper.reshape(text)
text = reverse_transcription(text)
return text
def reverse_transcription(transcription):
transcription = transcription[::-1]
number_patter = r"[0-9]+"
matches = re.findall(number_patter, transcription)
if matches:
for match in matches:
i = transcription.index(match)
transcription = transcription[:i] + match[::-1] + transcription[i+len(match):]
return transcription
|
af18dd3717966e3b12ca843ec77ce44b9472110e | Rifat951/PythonExercises | /Lists/exercises.py | 3,331 | 4.53125 | 5 | # 3-4. Guest List: If you could invite anyone, living or deceased, to dinner, who
# would you invite? Make a list that includes at least three people you’d like to
# invite to dinner. Then use your list to print a message to each person, inviting
# them to dinner
print("\n\n##########################################")
guest = []
guest.append('rafi')
guest.append('pafi')
guest.append('tafi')
for x in guest:
print("{} is invited ".format(x))
# 3-5. Changing Guest List: You just heard that one of your guests can’t make the
# dinner, so you need to send out a new set of invitations. You’ll have to think of
# someone else to invite.
# • Start with your program from Exercise 3-4. Add a print statement at the
# end of your program stating the name of the guest who can’t make it.
# • Modify your list, replacing the name of the guest who can’t make it with
# the name of the new person you are inviting.
# • Print a second set of invitation messages, one for each person who is still
# in your list.
print("\n\n##########################################")
a=guest.pop() # pop needs to be integer
print("{} cannot come".format(a))
print('\nAdd new Guest')
guest.insert(2,'new_guest')
for x in guest:
print("{} is invited ".format(x))
# 3-6. More Guests: You just found a bigger dinner table, so now more space is
# available. Think of three more guests to invite to dinner.
# • Start with your program from Exercise 3-4 or Exercise 3-5. Add a print
# statement to the end of your program informing people that you found a
# bigger dinner table.
# • Use insert() to add one new guest to the beginning of your list.
# • Use insert() to add one new guest to the middle of your list.
# • Use append() to add one new guest to the end of your list.
# • Print a new set of invitation messages, one for each person in your list.
print("\n\n##########################################")
guest.insert(0,'rifat')
guest.insert(2,'sifat')
guest.insert(5,'tifat')
print(guest)
# 3-7. Shrinking Guest List: You just found out that your new dinner table won’t
# arrive in time for the dinner, and you have space for only two guests.
# • Start with your program from Exercise 3-6. Add a new line that prints a
# message saying that you can invite only two people for dinner.
# • Use pop() to remove guests from your list one at a time until only two
# names remain in your list. Each time you pop a name from your list, print
# a message to that person letting them know you’re sorry you can’t invite
# them to dinner.
# • Print a message to each of the two people still on your list, letting them
# know they’re still invited.
# • Use del to remove the last two names from your list, so you have an empty
# list. Print your list to make sure you actually have an empty list at the end
# of your program.
print("\n\n##########################################")
for x in range(len(guest)):
if x ==4:
break
else:
print("{} they cannot come ".format(guest.pop()))
print("\n\n{} are Remaining and Invited for dinner".format(guest))
# for x in range(len(guest)):
# del x
# # print("{} list".x)
# print(guest)
del guest[0]
print(guest)
del guest[0]
print(guest)
|
7b6dc37fb7010ad5636b9abafa56503ca1312f6e | opensourcex123/Data_Analysis | /demo1 pyplot的中文显示.py | 309 | 3.625 | 4 | # 作者:宁方笑
# 开发时间:2021/5/27 21:38
import numpy as np
import matplotlib.pyplot as plt
a=np.arange(0.0,5.0,0.02)
plt.xlabel('横轴:时间',fontproperties='kaiti',fontsize=20)
plt.ylabel('纵轴:振幅',fontproperties='kaiti',fontsize=20)
plt.plot(a,np.cos(2*np.pi*a),'r--')
plt.show() |
fd0ab39f0ab8d3065121cf5dfa9b65b83fc36bf9 | curieux/ProgMathSci | /matrix.py | 5,940 | 4.125 | 4 | #!/usr/bin/env python
""" A sample python module for working with matrices.
Abraham D. Smith """
import numbers
class Matrix:
def __init__(self, listOfLists):
""" Construct a Matrix object from a list-of-lists, packed by row.
Some minimal sanity checks are in place. """
if not isinstance(listOfLists,list):
raise ValueError("listOfLists must be a list of lists")
if not all([ isinstance(row,list) for row in listOfLists]):
raise ValueError("listOfLists must be a list of lists")
nRows = len(listOfLists)
nCols = len(listOfLists[0])
if not all( [ len(row) == nCols for row in listOfLists ] ):
raise ValueError("List-of-lists has mismatched rows, so it cannot be a Matrix.")
if not all( [ all([ isinstance(elem,numbers.Number) for elem in row ])
for row in listOfLists ]):
raise(ValueError("A Matrix must contain Numbers"))
## give ourselves some attributes.
self._nRows=nRows
self._nCols=nCols
self._dict = dict()
for i in range(self._nRows):
for j in range(self._nCols):
self._dict[(i,j)]=listOfLists[i][j]
def __getitem__(self,key):
rowKey,colKey=key
""" Get row or element """
if not (rowKey,colKey) in self:
raise IndexError("Row or Column out of range for a {r} by {c} Matrix".format(r=self._nRows,c=self._nCols))
return self._dict[(rowKey,colKey)]
def __setitem__(self,key,value):
rowKey,colKey=key
if not (rowKey,colKey) in self:
raise IndexError("Row or Column out of range for a {r} by {c} Matrix".format(r=self._nRows,c=self._nCols))
if not isinstance(value,numbers.Number):
raise ValueError("Matrix entry must be a Number")
self._dict[(rowKey,colKey)]=value
def __iter__(self):
return ( keypair for keypair in sorted(self._dict) )
def __contains__(self,(rowKey,colKey)):
return (rowKey,colKey) in self._dict.keys()
def dimension(self):
""" compute the dimension of a Matrix, with minimal error correction.
To us, matrices are lists-of-lists, packed row-by-row """
return (self._nRows,self._nCols) ## note, this is a tuple
def __add__(self,other):
""" compute the element-by-element sum of two matrices. """
if not other.dimension() == self.dimension():
raise ValueError("Cannot add matrices of different dimensions.")
nRows,nCols=self.dimension()
newMatrix=Matrix( [ [0]*nCols ]*nRows )
for i,j in newMatrix:
newMatrix[i,j] = self[i,j] + other[i,j]
return newMatrix
def __rmul__(self,num):
""" scalar multplication of a matrix """
nRows,nCols=self.dimension()
newMatrix=Matrix( [ [0]*nCols ]*nRows )
for i,j in newMatrix:
newMatrix[i,j] = num*self[i,j]
return newMatrix
def __equals__(self,other):
if not other.dimension() == self.dimension():
return False
return all( [ self[i,j] == other[i,j] for (i,j) in self ])
def __mul__(self, other):
""" compute the matrix product """
nRows,nInner=self.dimension()
nInnerB,nCols=other.dimension()
if not nInner == nInnerB:
raise ValueError("Dimension mismatch for matrix multiplication.")
newMatrix=Matrix( [ [0]*nCols ]*nRows )
for i,j in newMatrix:
products=[self[i,k]*other[k,j] for k in range(nInner)]
newMatrix[i,j] = sum(products)
return newMatrix
def transpose(self):
""" construct the transpose of a matrix. This could be cleverer. """
nCols,nRows=self.dimension() ## SWAPPED!
newMatrix=Matrix( [ [0]*nCols ]*nRows )
for i,j in newMatrix:
newMatrix[i,j] = self[j,i]
return newMatrix
def __pow__(self,num):
""" scalar multplication of a matrix """
nRows,nCols=self.dimension()
if not nRows==nCols:
raise ValueError("Cannot take a power of a non-square matrix.")
if not type(num) == int and num >= 1:
raise ValueError("Can only take positive integer powers.")
if num==1:
return self
#print "... descending to {nn}".format(nn=num-1)
return self.__pow__(num-1)*self
def __str__(self):
""" pretty-print the matrix """
nRows,nCols=self.dimension()
string=""
for i in range(nRows):
string+="|"
for j in range(nCols):
string+="\t{}\t".format(self[i,j])
string+="|\n"
string+="\n"
return string
if __name__ == "__main__":
# This is called if we run as "./test.py"
print "Running example tests for Matrix class."
A = Matrix([[ 12, 45, 167], [3, 6, 2]])
try:
A1= Matrix("abcdef")
A2= Matrix( [["a", "b", "c"], ["d", "e", "f"]] )
A3= Matrix( [["a", "b", "c"], ["d", "e"]] )
except Exception as e:
print e
pass
B=Matrix([[ 4, 3, 1], [6, 7, 3] ])
C=Matrix([[ 1, 2, 3, 4], [9, 2, 2, 1], [ 5, 4, 3, 2]])
D=Matrix([[ 1,0],[0,2]])
print A.dimension()
print "A"
print A
print "B"
print B
print "A+B"
print A+B
#print add_matrix(A1,B1) ## I find this hillarious,too
#print add_matrix(A2,B2) ## I find this hillarious
#print mult_matrix(A,B) ## throws exception
#print mult_matrix(A,C)
#print mult_matrix(A2,C) ## throws exception
print "3A"
print 3*A
print "At"
print A.transpose()
print "C"
print C
print "AC"
print A*C
#print_matrix(transpose(A))
print "D"
print D
print "D**10"
print D**10
|
01f6cf366b6bda4a6f30d97aa2988b9ee21f284e | david-luk4s/sock | /Sock.py | 951 | 3.703125 | 4 | from turtle import Screen, Turtle, mainloop
def main():
space = Screen()
space.setup(450, 450), space.title('Sock')
space.bgcolor('green')
pen = Turtle(shape='circle')
pen.shapesize(0.3), pen.width(5)
create_sock(pen)
pen.ht()
def create_sock(pen):
pen.color('black', 'red'), pen.speed(9)
pen.seth(90)
pen.pu(), pen.goto(100, -100), pen.pd()
pen.begin_fill()
pen.fd(140), pen.circle(20, 60), pen.fd(140)
pen.circle(20, 90), pen.fd(70), pen.circle(20, 90)
pen.fd(70), pen.circle(-20, 60), pen.fd(79.74)
pen.circle(50, 90), pen.fd(15.62), pen.circle(50, 90)
pen.end_fill()
pen.color('black', 'white'), pen.speed(9)
pen.seth(60)
pen.pu(), pen.goto(3.40, 107.32), pen.pd()
pen.begin_fill()
for i in range(2):
pen.circle(20, 90), pen.fd(50)
pen.circle(20, 90), pen.fd(110)
pen.end_fill()
if __name__ == "__main__":
main()
mainloop() |
c0211a75f578b1abe7b728a92778887eaa691b3f | daniel-reich/turbo-robot | /ZdnwC3PsXPQTdTiKf_17.py | 653 | 4.34375 | 4 | """
Create a function that takes two numbers and a mathematical operator `+ - / *`
and will perform a calculation with the given numbers.
### Examples
calculator(2, "+", 2) ➞ 4
calculator(2, "*", 2) ➞ 4
calculator(4, "/", 2) ➞ 2
### Notes
If the input tries to divide by 0, return: `"Can't divide by 0!"`
"""
def calculator(num_1: int, operator: str, num_2: int) -> int:
if num_2 == 0 and operator == "/":
return"Can't divide by 0!"
funcs = {
"+": int.__add__,
"-": int.__sub__,
"*": int.__mul__,
"/": int.__floordiv__
}
return funcs[operator](num_1, num_2)
|
139dd916ecf9a6189f5febc55171bf4fcb5452b1 | hwankyusong/Prime_Factorizer | /prime_factorizer_v2.py | 328 | 3.53125 | 4 | #returns prime factorization in list form
#fixed emptying list issue
from math import *
L=[]
def prime(n):
if len(L) != 0:
del L[:]
return helper(n)
return helper(n)
def helper(n):
for i in range(2,round(sqrt(n))+1):
if n % i == 0:
L.append(i)
return helper(n/i)
L.append(n)
return L
|
735097a9a3df21715ca85f19a381d29b3840c887 | kyoz/learn | /languages/python/1.learn_py_the_hard_way/ex15.py | 251 | 3.71875 | 4 | from sys import argv
script, filename = argv
txt = open(filename)
print(f"Here's your file {filename} content:")
print(txt.read())
print("Type the filename again:")
new_file_name = input("> ")
new_txt = open(new_file_name)
print(new_txt.read())
|
fd101c8e4759db09b4434d728a23870f0d24bc6a | Rohan07Singh/264789_Daily_Commit | /Word_check.py | 249 | 4.09375 | 4 | def is_word_present(sentence, word):
s=sentence.split(" ")
for i in s:
if(i==word):
print("True")
print("False")
s=input("Enter a sentence")
word=input("Enter the word to be searched")
is_word_present(s,word) |
4941aeb787364f333c38e187ef47f60caa619cbd | Worcester-Preparatory-School-Comp-Sci/python-1-FrankTheTank87 | /Great Lakes .py | 480 | 4.125 | 4 | #Frank Carter, 9-16-19
water = float(input("How many milliliters of water are in the Great Lakes? "))
usa = float(input("What is the surface area in centimeters of the 48 contiguous US states? "))
def depth(x):
x = water/usa
return(x)
print("If all the water in the Great Lakes covered the USA, the water would be ",depth(water)," centimeters deep.")
#typically, you would not want your user research and put in these values which are generally constant
# good work otherwise
|
90a86804d1f7eec8c3af0eda8be0703d517f1ab4 | AnotherContinent/thinkful | /FizzBuzz.py | 368 | 4.0625 | 4 | import sys
num_input = raw_input("Please enter a number: ")
try:
num_input = int(num_input)
except ValueError:
print("That is not a valid integer.")
else:
for n in range(1,num_input):
if n % 5 == 0 and n % 3 == 0:
print("FizzBuzz")
elif n % 5 == 0:
print("Buzz")
elif n % 3 == 0:
print("Fizz")
else:
print(n)
|
c2676db89b7aa05a499bf1b0af4db1b39a934651 | jvfiel/pythonbasic1 | /level2_list.py | 407 | 3.984375 | 4 | #LISTS
bags = ['Hand Bag','Shoulder Bag']
print(bags)
print("---------------------")
for bag in (bags):
print(bag)
print("--------------------")
#Looping through the list and enumerate
for i,bag in enumerate(bags):
print(i, bag)
#In principle index always starts at 0
print("--------------------")
#split by comma to list/array
bags = 'Hand Bag,Shoulder Bag'
bags = bags.split(',')
print(bags) |
73f670325e65f119cb956b2f8a51ec64ee788f95 | kyungtae92/python-basic | /day1015/function14.py | 722 | 3.890625 | 4 | # 원의 넓이 : 반지름 * 반지름 * 3.14
# 원의 둘레 : 원의 넓이 * 높이
def circleArea(radius):
print('radius: ', id(radius))
area = radius * radius * 3.14
return area
def circleVolume(radius, height):
vol = circleArea(radius) * height
return vol
def printCircle(area, vol, radius):
print('반지름 %d인 원의 넓이 %.2f !' % (radius, area))
print('반지름 %d인 원의 둘레 %.2f !' % (radius, vol))
def main():
radius = int(input('반지름 : '))
height = int(input('원의 높이 : '))
area = circleArea(radius)
vol = circleVolume(radius, height)
printCircle(area, vol ,radius)
print('radius: ', id(radius))
main()
|
3d601056471a4541d63b99266c8b698207489e49 | hakan7822/Projet3Macgyver | /class_Square.py | 1,219 | 3.890625 | 4 | import pygame
from pygame.locals import *
from class_Coordinates import *
from class_Item import *
class Square:
"""
Description.
A class that will define the squares of the laby.
"""
def __init__(self, coord, is_wall):
"""Use Coordinates and is_Wall boolean as arguments.
Starts with no item on it."""
self.is_wall = is_wall
self.coord = coord
self.has_item = False
self.item = Item(None, 'ressource/empty.png')
def get_is_wall(self):
"""Return a boolean to know if the square is a wall."""
return self.is_wall
def get_has_item(self):
"""Return a boolean to know if there's an item on the square."""
return self.has_item
def set_has_item(self, state):
"""Set the state of the has_item boolean."""
self.has_item = state
def get_coord(self):
"""Return the square's position as a Coordinate type object."""
return self.coord
def set_item(self, item):
"""Change the Item attribute of the square.
Uses an Item type object."""
self.item = item
def get_item(self):
"""Return the item on the square."""
return self.item
|
cca8e76be7a8651b3dfe346d7975d0900d8af01a | gitForKrish/PythonInPractice | /PythonCrashCourse/Theories/p07_Functions.py | 1,696 | 3.78125 | 4 | def greet_user():
""" Message for greeting """
print('hello')
greet_user()
def greet_user(name):
""" Message for greeting """
print(f'hello, {name.title()}')
greet_user('jack')
# greet_user() # TypeError: greet_user() missing 1 required positional argument: 'name'
def describe_animal(animal_type, pet_name):
''' Method will describe an animal '''
print(f"I have a {animal_type.title()}")
print(f"My {animal_type.title()} name is {pet_name.title()}")
# Positional Arguments
describe_animal('dog', 'jack')
# Keywords Arguments
describe_animal(animal_type='cat', pet_name='buli')
describe_animal(pet_name='tommy', animal_type='dog')
# default value
def describe_animal(pet_name, animal_type = 'dog'):
''' Method with default arguments '''
print(f"I have a {animal_type.title()}")
print(f"My {animal_type.title()} name is {pet_name.title()}")
describe_animal('kalu')
describe_animal('supert', 'tiger')
describe_animal(animal_type='cat',pet_name='lione')
# Function returning value
def get_formatted_name(first_name, last_name):
''' Get Formatted Name '''
return f"{first_name.title()} {last_name.title()}"
my_name = get_formatted_name('krishnendu', 'mandal')
print(my_name)
def get_formatted_name(first_name, last_name, middle_name=''):
''' Get Formatted Name '''
full_name = ''
if middle_name:
full_name = f"{first_name.title()} {middle_name.title()} {last_name.title()}"
else:
full_name = f"{first_name.title()} {last_name.title()}"
return full_name
my_name = get_formatted_name('krishnendu', 'mandal')
print(my_name)
father_name = get_formatted_name('tarun','mondal','kumar')
print(father_name) |
2e9e54bdf97bbd79c74085a86a401ebe65936270 | ebbitten/ScratchEtc | /Challenges/ZombitPath v 2.1a.py | 2,337 | 3.609375 | 4 | import operator
def answer(food,grid):
#initialize the input that we'll get all of the permutations of paths from
N=len(grid)
#if N>=20:
# return -1
bestFood=201
directions=[[0,1,0],[0,0,1]]
growingBranch=[[food,0,0]] #paths that need to have branches added
found=False
while not found:
branch=findNextBranch(growingBranch)
if atEnd(branch,N):
if branch[0]<bestFood:
bestFood=branch[0]
else:
spawnBranch(branch,directions,growingBranch,grid,N)
#liveBranch=list(growingBranch)
#growingBranch=[]
growingBranch.remove(branch)
found=checkIfDone(growingBranch,bestFood)
if bestFood==201:
bestFood=-1
return bestFood
def spawnBranch(branch,directions,growingBranch,grid,N):
#figure out a way to create new growingBranches from the current live branch
for move in directions:
#check for both edge of grid, as well as foodLeft
attmptMove=[branch[0]+move[0],branch[1]+move[1],branch[2]+move[2]]
#try evaluating all on one line and just have food at end to avoid indexError
if attmptMove[1]<N and attmptMove[2]<N:
attmptMove[0]=attmptMove[0]-grid[attmptMove[1]][attmptMove[2]]
if attmptMove[0]>=0:
growingBranch.append(attmptMove)
def atEnd(branch,N):
#check to see if a branch is at the end of the grid
if (branch[1]!=(N-1) or branch[2]!=(N-1)):
return False
else:
return True
def checkIfDone(liveBranch,bestFood):
if not liveBranch:
found=True
elif bestFood==0:
found=True
else:
found=False
return found
def findNextBranch(growingBranch):
#lets start by just trying to find branches with the least food left
return min(growingBranch)
grid=[[0, 8, 6, 8, 7, 8, 7],
[10, 2, 8, 3, 3, 2, 8],
[2, 9, 1, 6, 9, 9, 2],
[3, 8, 10, 2, 7, 8, 1],
[4, 4, 9, 7, 6, 10, 8],
[6, 10, 7, 8, 6, 1, 1],
[10, 1, 3, 2, 9, 2, 5]]
food=150
import random
def genGrid(N):
grid=[]
for i in range(N):
rowval=[]
for j in range(N):
cellval=random.randint(1,10)
rowval.append(cellval)
grid.append(rowval)
grid[0][0]=0
return grid
def genFood():
return random.randint(1,200) |
34eca39f58c01591a82ba1bec326b21d55110c85 | nsa18685/my_first_python | /4장/쳌4.22.py | 104 | 3.703125 | 4 | num = eval(input("수를 입력하세요: "))
num = True if num>0 and num <= 100 else False
print(num)
|
8846dbb60c1199a399b6db4832c3ddcc4c2d7ea8 | victor12416/Elam_Cabrera | /The Dealer ;).py | 7,111 | 4.125 | 4 | Inventory_list = ['Infiniti, Subaru, Lexus, GMC, Toyota, BMW, Honda, Lincoln' ]
#individual list of cars
Infiniti = ['Q50,QX80,QX30']
Subaru= ['Impreza,Legacy,Forester']
Lexus = ['Rx,IS,Ls']
GMC = ['Acadia,Yukon,Canyon']
Toyota = ['Corolla,Land Crusier,C-HR']
BMW = ['3 Series,X5,5 Series']
Honda = ['Accord,Civic,CR-V']
Lincoln = ['Continential,Navigator,MKZ']
#Dialoge
print('Hi welcome to elam autoshop,')
print('if your new i got just the thing for you.')
print('Just pick one of your favorite car brands and well start from there.')
print('Here are some of the top leading Brands')
print('~~>If the Brand is not listed amagon the intial inventory')
print('please enter (N/A)')
print('')
#user Input
print(Inventory_list)
UI = input()
print('')
#adds Brands and 3 cars into it
if UI == 'N/A':
print('Please Enter the name of the brand you')
print('want to add to the selection')
new_brand = input()
print('Now we need to add three cars to add to the suggested Brand')
new_car1 = input("1. ")
new_car2 = input("2. ")
new_car3 = input("3. ")
new_brand_car_list = [new_car1, new_car2, new_car3]
Inventory_list.append(new_brand)
print("You added a new " + new_brand + " list to the database " + "with these models " + str(new_brand_car_list))
print('')
NUI = input('Do you want to go ahead and pick the brand you suggested(Y/N)')
if NUI == 'Y':
print('')
print('Here are the cars you picked from ' + new_brand)
print(new_brand_car_list)
print('')
import random
car_price = (random.randint(40,100))
User_car_selection = input('What car are you going to go for:')
if User_car_selection == new_car1:
print('The cuurent going price for ' + User_car_selection + ' is ' + str(car_price) + ',000')
if User_car_selection == new_car2:
print('The cuurent going price for ' + User_car_selection + ' is ' + str(car_price) + ',000')
if User_car_selection == new_car3:
print('The cuurent going price for ' + User_car_selection + ' is ' + str(car_price) + ',000')
else:
print('')
print(Inventory_list)
print('What brand are you going to go for')
UI = input()
#Randomiser
import random
car_price = (random.randint(50,100))
#scans for UI input and prints accordingly
if UI == 'Infiniti':
print('Here are the top cars from ' + UI)
print(Infiniti)
User_car_selection = input('What car are you going to go for:')
if User_car_selection == 'Q50':
print('The cuurent going price for ' + User_car_selection + ' is ' + str(car_price) + ',000')
if User_car_selection == 'QX80':
print('The cuurent going price for ' + User_car_selection + ' is ' + str(car_price) + ',000')
if User_car_selection == 'QX30':
print('The cuurent going price for ' + User_car_selection + ' is ' + str(car_price) + ',000')
if UI == 'Subaru':
print('Here are the top cars from ' + UI)
print(Subaru)
User_car_selection = input('What car are you going to go for:')
if User_car_selection == 'Impreza':
print('The cuurent going price for ' + User_car_selection + ' is ' + str(car_price) + ',000')
if User_car_selection == 'Legacy':
print('The cuurent going price for ' + User_car_selection + ' is ' + str(car_price) + ',000')
if User_car_selection == 'Forester':
print('The cuurent going price for ' + User_car_selection + ' is ' + str(car_price) + ',000')
if UI == 'Lexus':
print('Here are the top cars from ' + UI)
print(Lexus)
User_car_selection = input('What car are you going to go for:')
if User_car_selection == 'Rx':
print('The cuurent going price for ' + User_car_selection + ' is ' + str(car_price) + ',000')
if User_car_selection == 'IS':
print('The cuurent going price for ' + User_car_selection + ' is ' + str(car_price) + ',000')
if User_car_selection == 'Ls':
print('The cuurent going price for ' + User_car_selection + ' is ' + str(car_price) + ',000')
if UI == 'GMC':
print('Here are the top cars from ' + UI)
print(GMC)
User_car_selection = input('What car are you going to go for:')
if User_car_selection == 'Acadia':
print('The cuurent going price for ' + User_car_selection + ' is ' + str(car_price) + ',000')
if User_car_selection == 'Yukon':
print('The cuurent going price for ' + User_car_selection + ' is ' + str(car_price) + ',000')
if User_car_selection == 'Canyon':
print('The cuurent going price for ' + User_car_selection + ' is ' + str(car_price) + ',000')
if UI == 'Toyota':
print('Here are the top cars from ' + UI)
print(Toyota)
User_car_selection = input('What car are you going to go for:')
if User_car_selection == 'Corolla':
print('The cuurent going price for ' + User_car_selection + ' is ' + str(car_price) + ',000')
if User_car_selection == 'Land Crusier':
print('The cuurent going price for ' + User_car_selection + ' is ' + str(car_price) + ',000')
if User_car_selection == 'C-HR':
print('The cuurent going price for ' + User_car_selection + ' is ' + str(car_price) + ',000')
if UI == 'BMW':
print('Here are the top cars from ' + UI)
print(BMW)
User_car_selection = input('What car are you going to go for:')
if User_car_selection == '3 Series':
print('The cuurent going price for ' + User_car_selection + ' is ' + str(car_price) + ',000')
if User_car_selection == 'X5':
print('The cuurent going price for ' + User_car_selection + ' is ' + str(car_price) + ',000')
if User_car_selection == '5 Series':
print('The cuurent going price for ' + User_car_selection + ' is ' + str(car_price) + ',000')
if UI == 'Honda':
print('Here are the top cars from ' + UI)
print(Honda)
User_car_selection = input('What car are you going to go for:')
if User_car_selection == 'Accord':
print('The cuurent going price for ' + User_car_selection + ' is ' + str(car_price) + ',000')
if User_car_selection == 'Civic':
print('The cuurent going price for ' + User_car_selection + ' is ' + str(car_price) + ',000')
if User_car_selection == 'CR-V':
print('The cuurent going price for ' + User_car_selection + ' is ' + str(car_price) + ',000')
if UI == 'Lincoln':
print('Here are the top cars from' + UI)
print(Lincoln)
User_car_selection = input('What car are you going to go for:')
if User_car_selection == 'Continential':
print('The cuurent going price for ' + User_car_selection + ' is ' + str(car_price) + ',000')
if User_car_selection == 'Navigator':
print('The cuurent going price for ' + User_car_selection + ' is ' + str(car_price) + ',000')
if User_car_selection == 'MKZ':
print('The cuurent going price for ' + User_car_selection + ' is ' + str(car_price) + ',000')
|
a2547f366d7f74fb83b1fdf7dc6b0a5c92923d84 | nguyenkims/projecteuler-python | /src/p25.py | 366 | 3.65625 | 4 | def fib_gen(n):
'''generate n first Fibonacci numbers'''
a,b,i=0,1,1
yield a,0
yield b,1
while i < n:
i += 1
if a > b:
b = a+b
yield b,i
else:
a = b +a
yield a,i
def test() :
t = fib_gen(10)
for i in t:
print i
# test()
def final():
k = 1000
t = fib_gen(6*k)
for i,j in t:
if len(str(i)) > k:
print k,j
return
final() |
3253b5f418d1c40fc7a3590828fb1367e9632bfe | Juan-Tena/Codigo_VBA | /Trabajo_Serializacion.py | 396 | 3.53125 | 4 | import pickle
lista_nombres=["Pedro", "Ana", "Maria","Isabel"]
fichero_binario=open("lista_nombre","wb") #Escritura binaria
pickle.dump(lista_nombres, fichero_binario)
fichero_binario.close()
del(fichero_binario)
#Ahora, una vez creado el fichero binario, vamos a rescatar la información que contiene
import pickle
fichero=open("lista_nombre", "rb")
lista=pickle.load(fichero)
print(lista) |
40a5b2ef1a707beeca6fbcce913af48d670dca79 | bendell02/nowCoder | /01_code/prj188_median.py | 380 | 3.84375 | 4 | #!/usr/bin/python
#-*- coding:utf-8 -*-
#Author: Ben
def median(nums1, nums2):
nums = nums1+nums2
nums.sort()
l = len(nums)
return nums[(l-1)/2]
while True:
try:
nums1 = map(int, raw_input().split())
nums1.pop(0)
nums2 = map(int, raw_input().split())
nums2.pop(0)
print median(nums1, nums2)
except:
break
|
467d5a3efb104f4a98fd54bc1975c8cf1186c732 | serenascalzi/python-specialization | /exercises/chapter01-exercises.py | 854 | 3.859375 | 4 | # chapter 1
# why should you learn to write programs?
# secondary memory - stores information for the long term, even beyond a power cycle
# program - set of instructions that specifies a computation
# compiler - translates a program written in a high-level language into a low-level language all at once, in preparation for later execution
# interpreter - executes a program in a high-level language by translating it one line at a time
# machine code - python source file
# primt 'Hello world!' - invalid syntax, print misspelled
# x = 123 - variable stored in main memory
x = 43
x = x + 1
print(x) # 44
# central processing unit - brain
# main memory - short-term memory
# secondary memory - long-term memory
# input device - headphones
# output device - microphone
# syntax error - fix grammar thru reading, running, ruminating & retreating
|
1cc01064b5ed36b656b4e96809279d6a8eca04b0 | shohruh-abduakhatov-portfolio/go-apteka-py | /web/ui_methods.py | 761 | 3.78125 | 4 | def has_access(self, roles):
user = self.current_user
"""
user_roles = user["roles"]
has_access = False
for role in user_roles:
if _checkRole(role, roles) == True:
has_access = True
break
return has_access
"""
return True
def _checkRole(role, roles):
''' Check given role is inside or equals to roles '''
# Roles is a list not a single element
if isinstance(roles, list):
found = False
for r in roles:
if r.value == role["value"]:
found = True
break
if found == True:
return True
# Role is a single string
else:
if roles.value == role:
return True
return False
|
a36a06e81672816e45fd24bee6066bc28188420a | mcxu/code-sandbox | /PythonSandbox/src/sorting/merge_sort.py | 1,974 | 3.796875 | 4 | '''
Merge Sort
'''
from utils.number_utils import NumberUtils
class Prob:
def mergeSort(self, array):
if not array or len(array)==1:
return array
median = int(len(array)/2)
left = array[:median]
right = array[median:]
#print("mergeSort: median:{}, l:{}, r:{}".format(median,left,right))
sl = self.mergeSort(left)
sr = self.mergeSort(right)
return Prob.mergeArrays(sl,sr)
# merge pre-sorted arrays
def mergeArrays(self, l,r):
print("merging arrays: l:{}, r:{}".format(l,r))
out = []
i = 0
j = 0
while(i<len(l) and j<len(r)):
lv = l[i]; rv = r[j]
#print("=====\ni={}, j={}".format(i,j))
#print("l:{}, r:{}, lv:{}, rv:{}".format(l,r, lv, rv))
if lv <= rv:
out.append(lv)
i += 1
else:
out.append(rv)
j += 1
if i < len(l):
# handle remaining left
out += l[i:]
elif j < len(r):
# handle remaining right
out += r[j:]
return out
@staticmethod
def test_mergeArrays():
a = [1,4,7,128,129,130]
b = [2,5,6,12,56,102,103,104,105,106,110,120,130]
out = Prob.mergeArrays(a,b)
print(out)
@staticmethod
def test_mergeSort():
a= [1,5,4,2,3]
s = Prob.mergeSort(a)
print("s: ", s)
@staticmethod
def test_mergeSort2():
a = []
s = Prob.mergeSort(a)
print("sorting empty: ", s)
@staticmethod
def test_mergeSort3():
a = NumberUtils.generateRandomNumbers(0, 10000, 100, allowDuplicates=False)
s = Prob.mergeSort(a)
print("sorted: ", s)
#Prob.test_countingSort()
#Prob.test_mergeArrays()
#Prob.test_mergeSort()
#Prob.test_mergeSort2()
#Prob.test_mergeSort3()
|
1b6790391e5b6903372f0c9ff5bf76b3c396b2d2 | B14nk/Sorting_Algorithms | /Mergesort/Mergesort.py | 723 | 3.671875 | 4 | arr = [1,4,324,56,7,456, 45, 34, 3267,768, 100]
def mergesort(arr):
if len(arr) <= 1:
return arr
else:
l = mergesort(arr[0:len(arr)/2])
r = mergesort(arr[len(arr)/2:len(arr)])
return merge(l, r)
def merge(l, r):
if len(l) == 0:
return r
if len(r) == 0:
return l
i, j = 0, 0
run = True
output = []
while run:
if l[i] < r[j]:
output.append(l[i])
i += 1
else:
output.append(r[j])
j += 1
if i == len(l):
output += r[j:]
run = False
if j == len(r):
output += l[i:]
run = False
return output
print(mergesort(arr)) |
d4ccf81e659edef409ce7f6b7c4ca621d90cee51 | Crasti/Homework | /Lesson4/Task4.6.py | 782 | 4.21875 | 4 | """
Реализовать два небольших скрипта:
а) бесконечный итератор, генерирующий целые числа, начиная с указанного,
б) бесконечный итератор, повторяющий элементы некоторого списка, определенного заранее.
Подсказка: использовать функцию count() и cycle() модуля itertools.
"""
from itertools import count
from itertools import cycle
# Часть задания А
for el in count(int(input("Enter start integer: "))):
print(el)
# Часть задания Б
string = "String"
iterat = cycle(string)
print(next(iterat))
print(next(iterat))
print(next(iterat))
print(next(iterat))
|
59bf9e3eddbd3e50a5b0e787c1fa14e71ac55632 | macasubo/python_bootcamp | /python01/ex03/matrix.py | 2,448 | 3.703125 | 4 | class Matrix:
def __init__(self, data=[], shape=()):
if type(data) == type(list()):
self.data = data
if len(shape) == 0:
self.shape = (len(self.data), len(self.data[0]))
else:
self.shape = shape
elif type(data) == type(tuple()):
self.data = list()
self.data = [[0 for item in range(data[1])]
for row in range(data[0])]
self.shape = data
def __repr__(self):
return f'Object: shape: {self.shape}, data: {self.data}'
def __str__(self):
return ', '.join([f'{key}: {value}' for key, value
in self.__dict__.items()])
def __add__(self, other):
if type(other) == Matrix:
return [[self.data[y][x] + other.data[y][x]
for x in range(other.shape[1])]
for y in range(self.shape[0])]
elif type(other) == type(list()):
return [[self.data[y][x] + other[y]
for x in range(self.shape[1])]
for y in range(self.shape[0])]
else:
print("Error: invalid type")
def __radd__(self, other):
return self.__add__(other)
def __sub__(self, other):
if type(other) == Matrix:
return [[self.data[y][x] - other.data[y][x]
for x in range(other.shape[1])]
for y in range(self.shape[0])]
elif type(other) == type(list()):
return [[self.data[y][x] - other[y]
for x in range(self.shape[1])]
for y in range(self.shape[0])]
else:
print("Error: invalid type")
def __rsub__(self, other):
if type(other) == Matrix:
return [[other.data[y][x] - self.data[y][x]
for x in range(other.shape[1])]
for y in range(self.shape[0])]
elif type(other) == type(list()):
return [[other[y] - self.data[y][x]
for x in range(self.shape[1])]
for y in range(self.shape[0])]
else:
print("Error: invalid type")
def __mul__(self, other):
if type(other) == type(list()):
other = Matrix([other])
if type(other) == Matrix:
res = Matrix((self.shape[0], other.shape[1]))
for y in range(self.shape[0]):
for x in range(other.shape[1]):
for z in range(self.shape[1]):
res.data[y][x] += self.data[y][z] * other.data[z][x]
return res
# elif type(other) in [type(int()), type(float())]:
else:
print("Error: invalid type")
# def __rmul__(self, other):
# if type(other) == Matrix:
# res = Matrix((self.shape[0], other.shape[1]))
# for y in range(self.shape[0]):
# for x in range(other.shape[1]):
# for z in range(self.shape[1]):
# res.data[y][x] += self.data[y][z] * other.data[z][x]
# return res
|
43059fbcd356ec0f13831956367ede3368efeeff | marcus255/coding | /euler/37/37.py | 740 | 3.875 | 4 | def isPrime2(Number):
return 2 in [Number,2**Number%Number]
def isPrime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
num = 11
primes_sum = 0
primes_count = 0;
while(primes_count < 11):
if isPrime(num):
temp_num = num
temp_num_2 = num
while temp_num > 9 and temp_num_2 > 9:
temp_num = temp_num // 10
temp_num_2 = temp_num_2 - int(str(temp_num_2)[0] + '0' * (len(str(temp_num_2)) - 1))
if not (isPrime(temp_num) and isPrime(temp_num_2)):
break
if temp_num in [2, 3, 5, 7] and temp_num_2 in [2, 3, 5, 7]:
primes_count += 1
primes_sum += num
print('{}: {}'.format(primes_count, num))
num += 1
print('The sum of these primes is ' + str(primes_sum))
|
32be62f0179a2b2e07235c3da0cea65355b6326b | SEugene/python | /task_1_3.py | 1,304 | 3.640625 | 4 | num_list = []
for num in range(21):
num_list.append(num)
for ind in range(len(num_list)):
last_num_hun = num_list[ind] % 100
last_num_ten = num_list[ind] % 10
if 10 < last_num_hun < 15:
print('{} процентов'.format(num_list[ind]))
elif 1 < last_num_ten < 5:
print('{} процента'.format(num_list[ind]))
elif last_num_ten == 1:
print('{} процент'.format(num_list[ind]))
else:
print('{} процентов'.format(num_list[ind]))
# алгоритм решения получился универсальным - не зависящим от диапазона, ниже добавил код, который определяет
# склонение слова "процент" при вводе любого целого числа
rand_num = int(input('Введите любое целое число для проверки склонения слова "процент": '))
last_num_hun = rand_num % 100
last_num_ten = rand_num % 10
if 10 < last_num_hun < 15:
print('{} процентов'.format(rand_num))
elif 1 < last_num_ten < 5:
print('{} процента'.format(rand_num))
elif last_num_ten == 1:
print('{} процент'.format(rand_num))
else:
print('{} процентов'.format(rand_num))
|
e8852066638f03d2fe567ce9b75ed686de97e3ef | shonihei/road-to-mastery | /algorithms/sorting-algorithms/insertionsort.py | 1,288 | 3.5625 | 4 | import random, sys
m = 0 # keeps track of number of comparisons
def wrapper(l):
lst = l[:]
insertion_sort(lst)
return lst
def insertion_sort(lst):
global m
for i in range(1, len(lst)):
cur = i
for j in range(i - 1, -1, -1):
m += 1
if lst[cur] < lst[j]:
lst[cur], lst[j] = lst[j], lst[cur]
cur -= 1
else:
break
def percent_sorted(u, s):
c = 0
for i in range(len(u)):
j = s.index(u[i])
if i <= j:
c += 1
return c / len(u)
def test(lo, hi, n, test_size):
global buckets
global m
buckets = dict()
worst_case = n**2
for test in range(test_size):
l = random.sample(range(lo, hi), n)
sorted_lst = wrapper(l)
percent_same = m / worst_case
buckets[percent_same] = buckets.get(percent_same, []) + [m]
m = 0
for k, v in sorted(buckets.items()):
avg = sum(v) / len(v)
print("{:.2f}% sorted: {:.2f} comparisons".format(k * 100, avg))
#lo, hi, n = int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3])
#l = random.sample(range(lo, hi), n)
#insertion_sort(l)
#print("random list of {} elements sorted with {} comparisons".format(n, m))
#print(l)
|
3f2b3fb132ef8cfab2063dee8d8a87570a60d4e3 | blidt/metodosNumericos | /newton/newton.py | 490 | 3.96875 | 4 | from math import *
def newtonIterationFunction(x):
return x - (((-8*exp(1-x)+7/x)) / (8*exp(1-x)-7/x**2))
def function(x):
return -8*exp(1-x)+7/x
x = 1.6
c = 1
xold = 0
fc = 1
for i in range(1000):
print "Iteraciones: ",str(i),"Valor aproximado: ", str(x), "Intervalo", str(c), "f(c)", str(fc)
c = abs(x - xold)
fc = function(x)
xold = x
x = newtonIterationFunction(x)
if (abs(c) < 0.000000005) :
print ("Solucion encontrada!")
break |
61c1ed60d436e5cb70c3cc74cf375bf20baf8a76 | cikent/Python-Projects | /Automate-The-Boring-Stuff-With-Python/Section_03_Functions/Lesson_10_Global_&_Local_Scope/Local_Variable_Execution_Error_example.py | 276 | 3.890625 | 4 | """
Upon execution, the function 'spam()' throws an exception because eggs is utilized as a Local variable before assignment
"""
def spam():
print(eggs) # ERROR! -- can't use a local variable before it is assigned a value
eggs = 'spam local'
eggs = 'global'
spam() |
ca469bd9acb7c2fdba8ec887fc1e1eb531140dfb | PascalUlor/code-challenges | /python/linked_list_1.py | 6,447 | 4.25 | 4 | # Create Node constructror
class ListNode(object):
def __init__(self, value=None):
self.data = value
self.next_node = None #address to next node
# def __str__(self):
# return f"{self.data} → {self.next_node}"
# node = ListNode(5)
# node.next_node = 2
# print(node)
# create List Constructor that takes a value
class Linked_List(object):
# # set node as None
# # set head for linked list and
# # set a temp/pointer variable to track address of linked lists
def __init__(self):
self.head = None
self.pointer = None
self.list_size = 0
# def __str__(self):
# return f"Head→{self.head}"
def insert_node(self, data): #add a new node to linked list
self.list_size += 1 #increment list size
new_node = ListNode(data) # initialize new node
if self.head is None:
# at start of linked list the head is also the pointer
self.head = new_node
self.pointer = self.head
else:
# if linked list already exists
self.pointer.next_node = new_node # pointer will hold address to new node
self.pointer = new_node # newly added node becomes new pointer
def get_size(self): # optimal approach with (O)1
return self.list_size
def get_size_traver(self): # (O)n works if we did not have size increment on inserting node
actual_node = self.head
size = 0
while actual_node is not None:
size += 1
actual_node = actual_node.next_node
return size
def insert_at_start(self, data):
self.list_size += 1 # increment size of array
new_node = ListNode(data)
if self.head is None: #if there is no head it means linked list is empty
self.head = new_node # set head to new node if linked list is empty
else:
#if linked list is not empty set the address ref of new node to head
new_node.next_node = self.head
# now make the new node the head
self.head = new_node
def remove_node(self, data):
# base case to ensure list in not empty
if self.head is None:
return
# decrement size of list
self.list_size -= 1
# set head node to a variable
current_node = self.head
prev_node = None # since head node has no previous
# traverse list
while current_node.data != data:
prev_node = current_node
current_node = current_node.next_node
# if specified node to be deleted is the head then it wont have a previous
if prev_node is None:
self.head = current_node.next_node
else:
prev_node.next_node = current_node.next_node
def traverse_node(self):
actual_node = self.head
linked_list_string = ""
# traverse list
while actual_node is not None:
# print(f"{actual_node.data}")
linked_list_string += f"{actual_node.data} → "
actual_node = actual_node.next_node
linked_list_string += 'None'
if self.head is None:
print('list is empty')
print(linked_list_string)
def insert_at_end(self, data):
self.list_size += 1
new_node = ListNode(data)
actual_node = self.pointer
# traverse to find the last node
while actual_node.next_node is not None:
actual_node = actual_node.next_node
actual_node.next_node = new_node
def insert_at_pos(self, pos, data):
if pos > self.list_size:
print('invalid position')
else:
self.list_size += 1
new_node = ListNode(data)
current_node = self.head
i = 0
while i < pos:
current_node = current_node.next_node
i += 1
new_node.next_node = current_node.next_node
current_node.next_node = new_node
def remove_from_pos(self, pos):
if pos > self.list_size:
print('invalid position')
else:
self.list_size -= 1
current_node = self.head
i = 0
while i < pos-1:
current_node = current_node.next_node
i += 1
pos_next = current_node.next_node
current_node.next_node = pos_next.next_node
def remove_from_end(self): #(O)n
# base case to ensure list in not empty
if self.head is None:
return
# decrement size of list
self.list_size -= 1
# set head node to a variable
current_node = self.head
prev_node = None # since head node has no previous
# traverse list
while current_node.next_node is not None:
prev_node = current_node
current_node = current_node.next_node
# if specified node to be deleted is the head then it wont have a previous
if prev_node is None:
self.head = current_node.next_node
else:
prev_node.next_node = current_node.next_node
def remove_start(self): #(O)1
# base case to ensure list in not empty
if self.head is None:
return
# decrement size of list
self.list_size -= 1
# set head node to a variable
current_node = self.head
self.head = current_node.next_node
def reverse_list(self):
# to reverse a llist we need 3 pointers
# prev, current and nextnode
current_node = self.head
temp_next_node = self.head
prev_node = None
while temp_next_node is not None:
temp_next_node = temp_next_node.next_node
current_node.next_node = prev_node
prev_node = current_node
current_node = temp_next_node
self.head = prev_node
list_node = Linked_List()
list_node.insert_node(23)
list_node.insert_node(3)
list_node.insert_node(1)
# list_node.insert_at_start(0)
# list_node.remove_node(0)
list_node.insert_at_end(100)
list_node.insert_at_pos(10, 4)
# list_node.insert_at_pos(4, 4)
list_node.traverse_node()
# print('after deletion')
# list_node.remove_from_end()
# list_node.remove_start()
# list_node.remove_from_pos(1)
list_node.traverse_node()
list_node.reverse_list()
print('after reversal')
list_node.traverse_node()
# print(list_node)
|
15c5346462fcc619d7b98b02513d02c1a6f904b1 | superdun/9BillionNames | /9billion.py | 1,040 | 3.546875 | 4 | #! usr/bin/python #coding=utf-8 /
import time
from itertools import groupby,count
#打印神的一个名字
def printGodsName(words):
godsName = ""
#神没有带有三个连续字母的名字
if max(len(list(g)) for k, g in groupby(words) )>=3:
return
for singleWord in words[::-1]:
godsName+=chr(65+singleWord)
print godsName
#26进制
def twentySixDecimal(words,i=0):
if words[i]==26:
words[i] = 0
if i == len(words)-1:
words.append(0)
else:
words[i+1]+=1
i+=1
twentySixDecimal(words,i)
return words
#启动V型电脑
def RunMarkV(bitCount):
words = [-1]
for i in count():
if i==(26**bitCount+26*(1-26**(bitCount-1))/(-25)):
break
words[0] += 1
words = twentySixDecimal(words)
printGodsName(words)
#如果运行到这里世界还没有毁灭的话.....呼一口气,乘坐DC-3离开
time.sleep(1)
print u"神是脆弱的东西,他们闻点儿科学的气味或者喝点常识的药水都会死掉"
def main():
bitCount = 9
RunMarkV(bitCount)
if __name__ == '__main__':
main()
|
8c03e411ea674d15b2520c39b15478f7abf37ad1 | sejal-varu/bigdata | /python/exception/play_input.py | 264 | 3.890625 | 4 | print 'Program starts'
n = raw_input('Enter n : ')
try :
i = int(n)
except ValueError:
#Executes when error
print 'Hey! Please enter numerals only'
else:
#Executes when no error raised in corresponding try block
print 'The number is ', i
print 'Program ends' |
2cf6cfffa8082ad0ef28188e2c5eaf74cb952a61 | shaileshr/leetcode | /binaryTrees/create_list_from_tree.py | 907 | 4 | 4 | from typing import List
class BinaryTreeNode:
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
def create_list_of_leaves(tree: BinaryTreeNode) -> List[BinaryTreeNode]:
# TODO - you fill in here.
#result = []
#def create_list_of_leaves_helper(node):
# if not node:
# return
#
# if not node.left and not node.right:
# result.append(node)
#
# if node.left:
# create_list_of_leaves_helper(node.left)
# if node.right:
# create_list_of_leaves_helper(node.right)
#
# create_list_of_leaves_helper(tree)
# return result
if not tree:
return []
elif not tree.left and not tree.right:
return [tree]
else:
return create_list_of_leaves(tree.left) + create_list_of_leaves(tree.right)
|
3f2430fdf31e1e51064473a1a1de043e7299de17 | MotherTeresaHS/ICS3U-2019-Group22 | /docs/readthedocs_examples/egg+bomb_function_example.py | 1,335 | 3.5625 | 4 | #!/usr/bin/env python3
# Created by: Douglass Jeffrey
# Created on: Dec 2019
# This file is the contains the egg and bomb moving functions for Egg collector
def game_scene():
# Function to make eggs reappear at the top of the screen
def show_egg():
for egg_number in range(len(eggs)):
if eggs[egg_number].x < 0: # meaning it is off the screen,
eggs[egg_number].move(random.randint(0 + constants.SPRITE_SIZE,
constants.SCREEN_X -
constants.SPRITE_SIZE),
constants.OFF_TOP_SCREEN)
break
# Function to make bombs reappear at the top of the screen
def show_bomb():
for bomb_number in range(len(bombs)):
if bombs[bomb_number].x < 0: # meaning it is off the screen
bombs[bomb_number].move(random.randint
(0 + constants.SPRITE_SIZE,
constants.SCREEN_X -
constants.SPRITE_SIZE),
constants.OFF_TOP_SCREEN
- random.randint(0, 50))
break
if __name__ == "__main__":
game_scene()
|
886597afcc7737a15d17249d495c02b420d8f12c | IHAGI-c/GIS_class_2 | /decorator2.py | 326 | 3.796875 | 4 | def decorator(func):
def decorated(a, b):
if a > 0 and b > 0:
func(a, b)
else:
print('err')
return decorated
@decorator
def area(a, b):
T_A = a * b * 1/2
S_A = a * b
print('삼각형의 넓이 :', T_A)
print('사각형의 넓이 :', S_A)
area(2,8)
area(-2,4) |
dff38823f0c0b8932ac6f4ae4362bec85c9fc3fd | Cathryne/Python | /ex31.py | 2,723 | 4.40625 | 4 | # Exercise 31: Making Decisions
# http://learnpythonthehardway.org/book/ex31.html
# enables restarting of program
import sys
import os
def restart_program():
"""Restarts the current program, without returning anything before-hand
Hence, clean-up and save data before calling."""
python = sys.executable
os.execl(python, python, * sys.argv)
door = raw_input("\nYou enter a dark room with three doors. Do you go through the door to your _front_, _left_ or _right_? ")
# while loop to prevent invalid responses
# strange problem: only 1st answer was accepted by (logical) code "while door != ("1st" or "2nd" or "3rd")
# strange problem: only 3rd answer was accepted by (logical) code "while door != ("1st" and "2nd" and "3rd")
# possible explanation: while & if blocks execute only if statement is true.
# truth terms need "" here, because numbers haven't been converted by int() and are thus still strings
while door != "left" and door != "right" and door != "front":
door = raw_input("Please pick a door: front, left or right. ")
# Study Drill 1: New game part with input check and restart function
if door == "front":
gold = int(raw_input("\nYou find three chests of gold. How many do you take for your self? "))
if gold == 0:
raw_input("\nYou found the easter-egg and get to play again, after pressing any key.")
restart_program()
# numbers converted to integers here, thus no "" necessary
while gold != 1 and gold != 2 and gold != 3:
gold = raw_input("How many gold chests do you take? 1, 2 or 3? ")
if gold <= 2:
print "\nOK, that's reasonable. A ladder appears from above and ceiling cat helps you get out into the fresh air.\n"
elif gold == 3:
print "\nYou're a greedy one! The weight of the gold breaks your back and the floor. You fall into the darkness.\n"
elif door == "left":
print """\nThere's a giant bear here eating a cheese cake.
1. Take the cake.
2. Scream at the bear."""
bear = raw_input("What do you do? ")
if bear == "1":
print "The bear eats your face off. Good job!"
elif bear == "2":
print "The bear eats your legs off. Good job!"
else:
raw_input("\nYour answer doesn't fit to the options. Press anything to start the game now. ")
restart_program()
elif door == "right":
print """\nYou stare into the endless abyss at Cthulhu's retina."
1. Blueberries.
2. Yellow jacket clothespins.
3. Understanding revolvers yelling melodies."""
insanity = raw_input("What will it be? ")
if insanity == "1" or insanity == "2":
print "\nYour body survives powered by a mind of jello. Good job!\n"
else:
print "\nThe insanity rots your eyes into a pool of muck. Good job!\n"
|
b116cdb1760778af80afabb2e367dfd1e982aef3 | EdikCarlos/Exercicios_Python_basico | /ex_Aumento_multiplo.py | 346 | 3.78125 | 4 | sal = float(input('Qual o valor do salário atual do funcionário?: '))
sal1 = sal + (sal * 10/100)
sal2 = sal + (sal * 15/100)
if sal <= 1250 :
print('O salário do funcionário terá um aumento de 15%, indo para R${:.2f}.'.format(sal2))
else:
print('O salário do funcionário terá um aumento de 10%, indo para R${:.2f}.'.format(sal1)) |
fcc607412cf4bc6fe9cc73bc32504498b6ca47b1 | udayreddy026/pdemo_Python | /logical_aptitude/08-04-2021/Armstrong.py | 562 | 4.0625 | 4 | # # Armstrong Number means number ex:153 = 1cub+5cub+3cub = same as give number is called armstrong
#
# num = 153
# temp = num
# arm_total = 0
# while num > 0:
# l_num = num % 10
# num = num // 10
# arm_total = arm_total+(l_num**3)
# # print(arm_total)
#
# if arm_total == temp:
# print(arm_total, "is armstrong")
# else:
# print(arm_total, "is not armstrong")
#
x = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
# for i in x:
# print(i)
for i in range(len(x)-1, -1, -1):
print(x[i])
print()
for i in range(0, len(x), 2):
print(x[i]) |
d1bd4b8f9483d961a0bc151fa10d5299ef3befeb | shikhalakra/python-code | /python_code1/candidate_code_1488906186.py | 486 | 3.671875 | 4 |
''' Read inputSTDIN. Print your output to STDOUT '''
#Use input() to read inputSTDIN and use print to write your output to STDOUT
def main():
n=int(raw_input())
for i in xrange(0,n):
for j in xrange(0,i):
print " ",
for k in xrange(0,n-i):
print "*",
for l in xrange(0,n-i-1):
if l!=(n-i-2):
print "*",
else:
print "*"
# Write code here
main() |
d8e56d189545c8e3269f4727da34e595866353b8 | leorossa/first_platformer | /player.py | 1,934 | 3.734375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from pygame import *
MOVE_SPEED = 7
WIDTH = 22
HEIGHT = 26.5
COLOR = "#7cdbef"
JUMP_POWER = 10
GRAVITY = 0.35 # Сила которая удет тянуть наш прямоугольник
class Player(sprite.Sprite):
"""класс нашего прямоугольника"""
def __init__(self, x, y):
sprite.Sprite.__init__(self)
self.xvel = 0 #скорость нашего прямоугольника, 0 стояние на месте
self.startX = x #начальная позиция
self.startY = y
self.image = Surface((WIDTH, HEIGHT)) #его изображение
self.image.fill(Color(COLOR)) #заливка цветом
self.rect = Rect(x, y, WIDTH, HEIGHT) #прямоугольные объект
self.yvel = 0 # скорость вертикального перемещения
self.onGround = False # на земле ли я?
def update(self, left, right, up):
if up:
if self.onGround: # прыгаем только тогда когда можно оттолкнуться от земли
self.yvel = -JUMP_POWER
if left:
self.xvel = -MOVE_SPEED # Лево = x - n
if right:
self.xvel = MOVE_SPEED # Право = x + n
if not(left or right): # Стоим когда нет указаний идти
self.xvel = 0
if not self.onGround:
self.yvel += GRAVITY
self.onGround = False; # мы не знаем когда мы на земле
self.rect.y += self.yvel # переносим положение на yvel
self.rect.x += self.xvel # переносим свое положение на xvel
def draw(self, screen): # Выводим себя на экран
screen.blit(self.image, (self.rect.x,self.rect.y))
|
026a1a25d52e9fb46ad80ea9c7208b2d43981f27 | LexLau/dev-sprint2 | /chap7.py | 451 | 3.90625 | 4 | # Enter your answrs for chapter 7 here
# Name: Alex
# Ex. 7.5
def estimate_pi():
total = 0
k = 0
factor = 2 * math.sqrt(2) / 9801
while True:
num = factorial(4*k) * (1103 + 26390*k)
den = factorial(k)**4 * 396**(4*k)
term = factor * num /den
total += term
if abs(term) < 1e-15: break
k += 1
return 1 / total
print estimate_pi()
# How many iterations does it take to converge?
# I definitely could not figure this out on my own. |
7271b4f9cae55ed3257ea33a8d77ea7b7979499c | 3salaz/python-Devops | /scripts/scriptThree.py | 196 | 4.21875 | 4 | # Given a word
# Have the program remove the given suffix
# Use the strip method
# Strip Method
def suffixStrip(suffix, word):
return print(word.rstrip(suffix))
suffixStrip('ed',"murdered")
|
d30565c4578a12deb775c04d6f42c8cd27420934 | RJBrooker/insult.ai | /insultAI.py | 1,141 | 3.6875 | 4 | """
Insult.AI is an API for predicting the offensiveness of insults. It takes a piece of text and returns a prediction of how insulting it is.
Its built using hug, gunicorn and pyTorch. The model is trained on top of torchMoji [1] using transfer learning and the “Detecting Insults In Social Commentary” dataset [2].
[1] https://github.com/huggingface/torchMoji
[2] https://www.kaggle.com/c/detecting-insults-in-social-commentary/data
"""
import hug
import insultModel as m
import numpy as np
@hug.post('/insult', output=hug.output_format.json )
def sentimentEndpoint(
text:hug.types.text,
language:hug.types.one_of([ 'en' ])='en',
docType:hug.types.one_of(['PLAIN_TEXT'])='PLAIN_TEXT',
):
"""Analyzes comments and predicts their offensiveness."""
scores = m.score(text)
return {
"language": language ,
"sentences": scores
}
# test the endpoint
api = hug.API(__name__)
response = hug.test.post(api, '/insult', { "text": "You're so fake, Barbie is jealous. I like you. You are the worst" } )
print(response.data)
assert (response.status=='200 OK' and response.data is not None)
print( "SUCCESS" )
|
f168c90dd32996fca9d37991aad6938260189345 | EDG-UPF-ADS/Python-1 | /Todas/somatorio Z.py | 214 | 3.796875 | 4 | # FUAQ ler valor para Z. calcular e mostrar o somatório
# dos valores pares entre 1 e z.
z=int(input('Insira um Numero p/ Somatório: '))
acum=0
for i in range(2,z):
if(i%2==0):
acum=acum+i
print(acum) |
8612554ef86f3e5cb07a58fefea7d570f5ef115a | martsavy/stepik-basic-python | /exercises/func13_13.5.2.py | 1,139 | 4.34375 | 4 | """ Змеиный регистр
Напишите функцию convert_to_python_case(text), которая принимает в качестве аргумента строку
в «верблюжьем регистре» и преобразует его в «змеиный регистр».
Примечание 1. Почитать подробнее о стилях именования можно тут.
Примечание 2. Следующий программный код:
print(convert_to_python_case('ThisIsCamelCased'))
print(convert_to_python_case('IsPrimeNumber'))
должен выводить:
this_is_camel_cased
is_prime_number """
# объявление функции
def convert_to_python_case(text):
res = text[0:1].lower()
for c in text[1:]:
if c.isupper():
res = res + '_' + c.lower()
else:
res += c
return res
# проверка
print(convert_to_python_case('ThisIsCamelCased'))
print(convert_to_python_case('IsPrimeNumber'))
# считываем данные
txt = input()
# вызываем функцию
print(convert_to_python_case(txt)) |
95907c6f1fb8ae387bbdb1303443b43116d40baf | tonyzhangqi2000/learning | /day02/exercise05.py | 232 | 3.59375 | 4 | """
练习:判断闰年
四年一润,百年不润
四百年再润
"""
import day01.helloworld as hw
year = int(input("输入年:"))
print((year % 400) == 0 or ((year % 4) == 0 and (year % 100) != 0))
hw.HW() |
12e1b6c65dfed071739226aee435641b5021b25a | dolomaniuk/python_project | /cours/week_1/KMperDay/solution.py | 124 | 3.734375 | 4 | N = int(input()) # km per day
M = int(input()) # count of day
days = M // N
if M % N > 0:
days += 1
print(days)
|
528b8ac11e24dc3a672293e151fa8f4d307bb4b6 | ozmaws/Chapter-2-Projects | /Project2.9.py | 414 | 4.1875 | 4 | #math notes
#10,000km between npole and equator
#90 degrees between npole and equator
#1 degree = 60 min
#1 min = 1 mile
#Request the inputs
kilometer = int(input("Enter the number of kilometers: "))
# Compute the nautical miles
nauticalMiles = ( kilometer / 10000 ) * 90 * 60
# Display the corresponding nautical miles
print("The corresponding number of nautical miles is " + str(nauticalMiles))
|
9f515d876147d885018c5b8f4b7728db9e10b206 | diegomonroy/Platzi-Curso-de-Python-y-Django | /clases.py | 598 | 3.59375 | 4 | class Persona:
def saludo_general(self):
return "Hola Persona"
class Estudiante(Persona): #Hereda de object, siempre se nombra con mayuscula
def __init__(self, nombre, edad): #Es el cosntructor, self se usa siempre en clases
self.nombre = nombre
self.edad = edad
def hola(self): #Es la funcion que contiene nuestra clase Estudiante
return "Mi nombre es %s\n" % self.nombre
e = Estudiante("Arturo",21) #Asi creamos un objeto de la clase Estudiante
print e.saludo_general()
e1 = Estudiante("Fabian",21)
e2 = Estudiante("Pablo",21)
print e.hola(), e1.hola(), e2.hola(); |
893f0d34e8e792f675420b6e24fef7f9190495f3 | rachelkelly/game | /main.py | 2,383 | 3.84375 | 4 | # first game maybe
class Room(object):
def __init__(self):
#self.name = name
### doooon't get it here
#self.foo = thing1
#self.bar = thing2
# these are placeholdery, I feel like putting "pass"
# in the __init__ fn would be a bad time at this juncstuah
# zed did also say to not put too much in the __init__
# ... so what DO I put into it
pass
class Inventory(Room):
#why am I calling Room? hmmm bc you have to be IN the room
#to instantiate the Inventory class, maybe?
#ok but all in all this class is looking better, if
#only I could just GET to it, esp now that I've got the
#invlist as part of the megafauna!
def inventorycheck(self):
print "inventory:\n %s" % invlist
def inventoryadd(self, addnew):
#don't know if putting var addnew in here is necessary right now
if addnew in invlist:
print "can't have more than one, homes"
elif addnew not in invlist:
print "cool! now the %s is in your inventory." %addnew
invlist.append(addnew)
print "want to see what's in the bag now?"
invchk = raw_input("> ")
if 'y' in invchk:
self.inventorycheck()
elif 'n' in invchk:
print "ok you don't have to, anyway it's over now"
exit(0)
else:
print "error in adding item to inventory"
class BookRoomHaHa(Room):
def book(self):
print "ok, you ate the book."
exit(0)
def bookviewing(self):
print "you're in a room. who knows what kind yet?"
print "so what do you do?"
get_it_done = raw_input("> ")
if "book" in get_it_done:
# want to make this more abstractly, like, if VAR in get_it_done
# then do some kind of "do you or don't you" inv taking action
print "ok booktest go"
self.book()
#from stackoverflow
# http://stackoverflow.com/questions/5615648/python-call-function-within-class
elif "shelf" in get_it_done:
print "you see a few books I guess, I don't know, man!"
elif "thing2" in get_it_done:
print "thing 2"
elif "get" in get_it_done:
print "buddy, you got it."
print "for now, just tell me what you got, again: "
addnew = raw_input("> ")
#print "oktest!"
# ok this piece is fine, now how to jump from one class
# to another
# why not just:
#Inventory.inventoryadd()
# doesn't work woh wohhhh
else:
print "try again doof"
self.bookviewing()
class DontDoIt(Room):
pass
invlist = []
crum = BookRoomHaHa()
crum.bookviewing()
|
221c6092a536825b8275a329c5118b1bccbccc11 | kensenwangka/UJIAN_1 | /KENSEN_20DESEMBER2019_UJIAN_1.py | 1,220 | 3.703125 | 4 | # Soal 1
def hashtag(string):
hashtag = "".join(string.title().split())
return [False, f"#{hashtag}"][bool(string and 0 < len(hashtag) <= 140)]
# print(hashtag("Helo there how are you doing"))
# print(hashtag(" "))
# Soal 2
def create_phone_number(n):
return "({}{}{}) {}{}{}-{}{}{}{}".format(*n)
# print(create_phone_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]))
# Soal 3
def sort_odd_even(num):
even = sorted(x for x in num if x % 2 == 0)
odd = sorted((x for x in num if x % 2 != 0), reverse=True)
return [(even if x % 2 == 0 else odd).pop() for x in num]
# print(sort_odd_even([5, 3, 2, 8, 1, 4]))
# Soal 4
# "Height" nya di ganti N aja ya biar cepet
def hollowTriangle(n):
return ['_' * (n - i - 1) + '#' + '_' * (2 * i - 1) + '#' * (i >= 1) + '_' * (n - i - 1) \
for i in range(n - 1)] + ['#' * (2 * n - 1)]
# print(hollowTriangle(6))
# gak ngerti gw wkwkwk jadi yaudah seadanya hehe
# selamat natal dan tahun baru 2020. semoga liburannya menyenangkan di Jogja. see you!
# nyari apaan? |
a064fa90bb4314027b4814da9a7d66ede0152171 | deepsinghsodhi/python-OOPS-assignments | /inheritance task/RBI bakn_inheritance.py | 3,830 | 4.1875 | 4 | '''
All the banks operating in India are controlled by RBI. RBI has set a well defined guideline
(e.g. minimum interest rate, minimum balance allowed, maximum withdrawal limit etc)
which all banks must follow. For example, suppose RBI has set minimum interest rate
applicable to a saving bank account to be 4% annually; however, banks are free to use
4% interest rate or to set any rates above it.
Write a program to implement bank functionality in the above scenario and demonstrate
the dynamic polymorphism concept. Note: Create few classes namely Customer, Account,
RBI (Base Class) and few derived classes (SBI, ICICI, PNB etc).
Assume and implement required instance variables and methods in each class.
'''
class RBI: #<<<< RBI >>>>>
def __init__(self, min_bal = 5000 , min_rate = 4, max_wdr = 50000 ):
self.min_bal = min_bal
self.min_rate = min_rate
self.max_wdr = max_wdr
print("init by RBI class by super")
def getRBI(self):
print("*************RBI Rules*************")
print("Minimum Balance allowed:", self.min_bal)
print("Minimum Rate of Intrest:", self.min_rate)
print("Maximum Withdrawl Limit:", self.max_wdr)
class Account:
def __init__(self):
self.acno = acno
self.actype = 'Saving'
self.bal = 0.00
print("init by Account class by super")
super().__init__()
def getAccount(self):
print("********Account Details**************")
print("AC Number:", self.acno)
print("Bank Balance:", self.bal)
print("Account Type:", self.actype)
super().getRBI()
'''
def deposit(self):
# amount = int(input("Enter amount to be deposited: "))
# self.bal = self.bal + amount
print("\n Amount Deposited:", self.bal)
def withdraw(self):
amount = int(input("Enter amount to be withdrawn: "))
if self.bal >= amount and amount <= self.max_wdr:
self.bal -= amount
print("\n You Withdrew:", amount)
print("Availabel Balance:", self.bal)
else:
print("Insuficiant Balance!")
'''
class Customer: #<<<<< Customer >>>>>>>
def __init__(self):
self.cname = cname
self.add = add
self.mob = mob
self.dob = dob
super().__init__() # calling Account class constructor..
def getCustomer(self):
print("***************Customer Details***************")
print("Name :", self.cname)
print("Address :", self.add)
print("Mobile :", self.mob)
print("DOB :", self.dob)
super().getAccount()
# Calling 'getAccount' of 'Account' Class
class SBI(Customer, Account, RBI):
def __init__(self, minbal, minrate, maxwdr):
self.minbal = minbal
self.minrate = minrate
self.maxwdr = maxwdr
super().__init__()
super().getCustomer()
def check(self):
if self.minbal >= self.min_bal:
print("Minimum balance is:", self.minbal)
else:
print("Minimum balance is lower than RBI Minimum balance", )
if self.minrate < self.min_rate:
print('Minimum rate of Interest is lower than RBI')
else:
print('Minimum rate is:', self.minrate)
sbi = SBI()
sbi.getCustomer()
sbi.check(5000, 5, 2000)
'''
class BOI(RBI, Customer, Account):
def __init__(self, min_bal, min_rate, max_wdr):
self.min_bal = 10000
self.min_rate = 5
self.max_wdr = 40000
class PNB(RBI, Account):
def __init__(self, min_bal, min_rate, max_wdr):
self.min_bal = 10000
self.min_rate = 5
self.max_wdr = 40000
''' |
120432dd70141685477c73483f0d741830505204 | gbaghdasaryan94/Kapan | /Garnik/Python 3/Loops/2.py | 450 | 4.28125 | 4 | # 2. Write a Python program to convert temperatures to and from celsius, fahrenheit.
temp = input("Enter temperature: ")
if temp[-1] == 'C' and temp[:-1].isdigit():
print("The temperature in farenheit is", (int(temp[:-1]) * 9/5 + 32))
elif temp[-1] == 'F' and temp[:-1].isdigit():
print("The temperature in celsius is", (float(temp[:-1]) * 5/9))
else:
print("Please use valid imput format: Should be number + C/F (20C or 68F)")
|
2a0a4994e7174f9d0a0573030e1a86fb353a13be | ruinanzhang/Leetcode_Solution | /6-Largest Number Smaller In Binary Search Tree.py | 2,471 | 3.796875 | 4 | # Tag : Binary Search Tree
# 136.Largest Number Smaller In Binary Search Tree
# -----------------------------------------------------------------------------------
# Description:
# In a binary search tree, find the node containing
# the largest number smaller than the given target number.
# If there is no such number, return -2^31.
# -----------------------------------------------------------------------------------
# Assumptions:
# The given root is not null.
# There are no duplicate keys in the binary search tree.
# -----------------------------------------------------------------------------------
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# *************************************************************************************
# Solution:
# !!!! Similar to find the cloest
# !!!! The condition to update helper node is different
# !!!! Might have better solution, this is hacky
def largestSmaller(self, root, target):
"""
input: TreeNode root, int target
return: int
"""
r_val = root.val
node = root
# If root is the node we re looking for:
if root.val < target and root.right is None:
return root.val
res = find_node(node, root,target)
# if we can't find such node, we will return the root node value and if it's larger than the target,
# we can't find target
# else it might be our target is the root
if res >= target:
return -2147483648
else:
return res
def find_node(node, root,target):
# If reach a leaf node, return the node with smallest difference
if root is None:
return node.val
# If helper node's value is ever be the target, update it
if get_dif(node,target) == 0:
node.val = root.val
# If curr node smaller than target:
if root.val < target:
# If value in hepler node larger than target, update anyway
if node.val >= target:
node.val = root.val
else:
# If value in hepler node is already smaller, update when have smaller difference
if get_dif(root, target) < get_dif(node, target):
node.val = root.val
# Do regular search:
if root.val >= target :
return find_node(node,root.left,target)
if root.val < target :
return find_node(node,root.right,target)
def get_dif(node,target):
return abs(node.val - target) |
764f4d3a884ea043de7ebc0e70e80e0461e1aeb2 | Tammyqian/Python | /works/test/demo2.py | 701 | 3.78125 | 4 | import pandas as pd
df1 = pd.DataFrame({'HPI':[80,85,88,85],
'Int_rate':[2, 3, 2, 2],
'US_GDP_Thousands':[50, 55, 65, 55]},
index = [2001, 2002, 2003, 2004])
print df1['HPI']
print '--------------------'
# if df1['HPI'] >= 80 :
# print df1['HPI'][0]
# if df1.HPI>=80:
# print df1['HPI'][0]
print df1[df1['HPI']==75 | 85].count()
print '--------------------'
print df1[(df1['HPI']==75) | (df1['HPI']==85)]
print df1[(df1['HPI']== 75) | (df1['HPI']== 85)].count().to_dict()
print '---------------------'
print df1[df1['Int_rate']==1 | 3].count().to_dict()
print df1[(df1['Int_rate']== 1) | (df1['Int_rate']== 3)].count().to_dict()
|
89268608f88608bc648a807a48fc36c634ac18b4 | nchanay/night-class | /python labs/contactoop.py | 1,205 | 4 | 4 | # contact list with OOP
class ContactList:
"""
Contact list with class objects
"""
def __init__(self, csv=None, props=None):
if csv is None:
self.props = props
self.contacts = {}
else:
self.load(csv)
def load(self, csv):
"""
reads csv file and parses it into a dictionary of dictionaries
"""
with open(csv) as f:
lines = f.read().split('\n')
contact_list = {}
props = lines[0].split(',')
for i in range(1, len(lines)):
row = lines[i].split(',')
contact = dict(zip(props, row))
contact_list[contact['name']] = contact
self.contacts = contact_list
self.props = props
def save(self, csv):
contacts = [','.join(self.props)]
for name in self.contacts:
contact = self.contacts[name]
contacts.append(','.join(contact.values()))
with open(csv, 'w')as f:
f.write('\n'.join(contacts))
return f'your file has saved'
if __name__ == '__main__':
contacts = ContactList('contacts.csv')
print(contacts.contacts)
print(contacts.props)
|
edc76bb95787df715aaad8814b7494b9626f516d | nsdeo12/thinkPython | /Data/5_Execption Handling/3_Exception_finally.py | 810 | 3.609375 | 4 | try:
testfile = open('data.txt')
try:
txns = testfile.readlines()
print ("File data = ",txns)
finally:
print ("In Inner finally")
except IOError:
print ('unable to access test file\n')
finally:
print ("In Outer finally")
#testfile.close()
print ("In END!!!!")
"""
1)
open('data11111.txt')
this file does not exists
>>>
unable to access test file
In Outer finally
In END!!!!
2)
testfile = open('data.txt')
>>>
File data = ['datalitics\n', 'Welcome to datalitics\n', 'Pune\n', '2015 BYE!!!!']
In Inner finally
In Outer finally
In END!!!!
3)
testfile = open('data.txt')
try:
txns = testfile.readlines()
print "File data = ",tx
NameError
"""
"""
if testfile <> None
testfile.close()
"""
|
e186e1228ac647348157f1cc7fbd633399a577ea | t4d-classes/python_03222021_afternoon | /language_demos/dictionary2_demo.py | 347 | 3.921875 | 4 | person = {
"first_name": "Bob",
"last_name": "Smith"
}
# print(person["age"])
# print(person.get("age"))
# print(person.get("first_name"))
# if "age" not in person:
# person["age"] = 34
# print(person["age"])
print(person.setdefault("age", 34))
print(person.popitem())
print(person.pop("address", "123 Oak Lane"))
print(person)
|
6c46cddf38030d28f463267c8772ff3d1512c32c | ojhermann-ucd/comp10280 | /p19p3.py | 4,686 | 3.8125 | 4 | """
Pseudocode
create list of items we want to find, count, and compare
create associated index list
on each line:
- count each bracket and associated partner
- keep a running tally
compare the counts and report accordingly
"""
import sys
import os
import datetime
#list of strings to find in the document
sList = ["(", ")", "[", "]", "{", "}", "<", ">"]
countList = [] #i would have liked ot use a dictionary
for i in sList:
countList.append(0)
#files
readFile = "p19p3read.txt"
recordFile = "p19p3record.txt"
#existence variables
readExist = os.path.isfile(readFile)
recordExist = os.path.isfile(recordFile)
#existence checks
if not readExist:
print(readFile, "does not exists.")
sys.exit()
if not recordExist:
recordFile = open(recordFile, "w")
recordFile.close()
#program
with open(readFile, "r") as reader:
with open(recordFile, "a+") as writer:
writer.write("in file ")
writer.write(readFile) #identify the file
writer.write("\n") #add a line after
writer.write("at ")
writer.write(str(datetime.datetime.now())) #add the datetime
writer.write("\n") #add a line
#count the shit
for line in reader:
for i in sList:
countList[sList.index(i)] += line.count(i)
#not necessary, but keeping for kicks
with open(recordFile, "a+") as writer:
for i in range(0, len(sList), 1):
writer.write(str(sList[i])) #show character of interest; using str() in case future list contains non-string characters
writer.write(" occurs ")
writer.write(str(countList[i])) #show count of character of interest
writer.write(" times.")
writer.write("\n")
writer.write("\n")
#total count section
print("")
print("This section reports on the total occurances of the relevant brackets")
for i in range(0, len(sList), 2): #compare each even indexed object with the next time, which by construction is its pair
print(sList[i], "occurs", countList[i], "and", sList[i + 1], "occurs", countList[i + 1], end = "")
if countList[i] == countList[i + 1]:
print(", so they are balanced")
else:
print(", so they are not balanced", end = "")
if countList[i] > countList[i + 1]:
print("there are ", countList[i] - countList[i + 1], "more", sList[i], "than", sList[i + 1])
else:
print("; there are ", countList[i + 1] - countList[i], "more", sList[i + 1], "than", sList[i])
print("")
#(
lb0 = []
#)
rb0 = []
#[
lb1 = []
#]
rb1 = []
#{
lb2 = []
#}
rb2 = []
#<
lb3 = []
#>
rb3 = []
#collectionList
collectionList = [lb0, rb0, lb1, rb1, lb2, rb2, lb3, rb3]
with open(readFile, "r") as reader:
lineCount = -1
for line in reader:
lineCount += 1 #count each line for indexing
cCount = -1
for c in line:
cCount += 1 #count each character for indexing
for i in range(0, len(sList), 1):
if c == sList[i]:
collectionList[i].append(str(lineCount) + str(cCount)) #index each occurance with a UID
#Overview of balance
print("This section gives an overview of the balance of brackets in", readFile)
for r in range(0, len(sList), 2):
leftLength = len(collectionList[r])
rightLength = len(collectionList[r + 1])
print("There are", str(leftLength), sList[r], "and", str(rightLength) , sList[r], end = ", so ")
if leftLength < rightLength:
print("there are", str(rightLength - leftLength), "more", sList[r + 1], "than", sList[r])
else:
print("there are", str(leftLength - rightLength), "more", sList[r], "than", sList[r + 1])
print("")
#location of bad guys
print("This section identifies the position of illegal brackets in", readFile, "(it will be empty if there are no illegal brackets)")
for r in range(1, len(sList), 2):
rightLocation = 0
leftLocation = 0
rightList = collectionList[r]
leftList = collectionList[r - 1]
rightLength = len(rightList)
leftLength = len(leftList)
if rightLength == 0:
for i in leftList:
print("Illegal", sList[r - 1], "at line", str(i[0]), ", position", str(i[1::]))
elif leftLength == 0:
for i in rightList:
print("Illegal", sList[r], "at line", str(i[0]), ", position", str(i[1::]))
else:
while leftLocation < len(leftList) and rightLocation < len(rightList):
if leftList[leftLocation] < rightList[rightLocation]:
leftLocation += 1
rightLocation += 1
else:
print("Illegal", sList[r], "at line", str(rightList[rightLocation][0]), ", position", str(rightList[rightLocation][1::]))
rightLocation += 1
for i in range(leftLocation, len(leftList), 1):
print("Illegal", sList[r - 1], "at line", str(leftList[leftLocation][0]), ", position", str(leftList[leftLocation][1::]))
for i in range(rightLocation, len(rightList), 1):
print("Illegal", sList[r], "at line", str(rightList[rightLocation][0]), ", position", str(rightList[rightLocation][1::]))
print("") |
4494c79f8b28b0d03b657746752ad6b2f62e77a7 | fabinhosp2/lista-exercicios-python | /aula001_Exe003/calcula.py | 970 | 4.15625 | 4 | class Calculadora:
def soma(self, num1, num2):
return num1 + num2
def sub(self, num1, num2):
return num1 - num2
def multi(self, num1, num2):
return num1 * num2
def divi(self, num1, num2):
return num1 / num2
def calcula_todos(self, num1, num2):
print(f'As operações de {num1} e {num2}:')
print(f'de soma é: {str(self.soma(num1, num2))}')
print(f'de subtração é: {str(self.sub(num1, num2))}')
print(f'de multiplicação é: {str(self.multi(num1, num2))}')
print(f'de divisão é: {str(self.divi(num1, num2))}')
print('=-' * 30)
print(f'As operações de {num1} e {num2} + 1:')
print(f'de soma é: {str(self.soma(num1, num2) + 1)}')
print(f'de subtração é: {str(self.sub(num1, num2) + 1)}')
print(f'de multiplicação é: {str(self.multi(num1, num2) + 1)}')
print(f'de divisão é: {str(self.divi(num1, num2) + 1)}') |
7835e3bfdbaaa90472e8c155bef216d9a0af7d20 | Aasthaengg/IBMdataset | /Python_codes/p02594/s904973923.py | 94 | 3.890625 | 4 | import math
X = int(input())
if X>=30:
aircon='Yes'
else:
aircon='No'
print(aircon) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.