blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
95ae69a68f37ef7311380514541995a36f7c8686 | golan1202/verilog-parser | /data_from_csv.py | 768 | 3.5 | 4 | import csv
import os
import sys
def parse_from_csv(fname):
if os.path.exists(fname) and os.stat(fname).st_size != 0 and fname.endswith('.csv'):
with open(fname) as f:
data = dict()
try:
reader = csv.reader(f, delimiter=',')
next(reader) # skip the header row
for line in reader:
data[line[0]] = [line[1], line[2]]
return data
except IndexError:
print("\nError in File: '%s'" % fname)
sys.exit("IndexError: Must be in this pattern: port name,port mode,port data_type")
else:
print("\nError in File: '%s'" % fname)
sys.exit("File does not exist OR is empty OR wrong extension")
|
b0a07c7c13f8973b1406df6a06b86710ead5581d | rebetli6/first_project | /data_structures.py | 146 | 3.640625 | 4 | name = ["John Doe", "Jack Doe"]
print(len(name))
print(name[1])
numbers= [11, 24, 55, 12, 21]
s=0
for c in numbers:
s += c
print(c)
print(s) |
67dd8f9a9ace275c3abbe429744e82e558918189 | CesarNaranjo14/selenium_from_scratch | /create_pickles.py | 1,111 | 3.578125 | 4 | """
DESCRIPTION
Create a set of pickle files of neighborhoods.
These files are for the use of giving the crawlers a "memory",
that is, we remove a neighborhood every time a crawler finishes
to scrap it in order to not iterate again.
HOW TO RUN
You have to run inside this directory:
python create_pickle start
"""
# Built-in libraries
import pickle
import os
# Third-party libraries
from flask import Blueprint
# Modules
from src.base.constants import MEMORY_PATH, CRAWLERS_PATH
create_pickles = Blueprint('create_pickles', __name__)
pages = [
"inmuebles24",
"icasas",
"vivanuncios",
"propiedades",
"lamudi",
]
@create_pickles.cli.command('start')
def pickles():
"""Create a set of pickles for every website."""
if not os.path.exists(MEMORY_PATH):
os.makedirs(MEMORY_PATH)
for page in pages:
with open(f"{CRAWLERS_PATH}colonias.txt", "r") as myfile:
colonias = [colonia.lower().strip() for colonia in myfile]
with open(f"{MEMORY_PATH}colonias-{page}.pickle", "wb") as pickle_file:
pickle.dump(colonias, pickle_file)
|
f1579f18820ec92be33bbf194db207d4b8678b89 | nonelikeanyone/Robotics-Automation-QSTP-2021 | /Week_1/exercise.py | 717 | 4.1875 | 4 | import math
def polar2cart(R,theta):
#function for coonverting polar coordinates to cartesian
print('New Coordinates: ', R*math.cos(theta), R*math.sin(theta))
def cart2polar(x,y):
#function for coonverting cartesian coordinates to polar
print('New Coordinates: ', (x**2+y**2)**(0.5), math.atan(y/x))
print('Convert Coordinates')
print('Polar to Cartesian? Put 1. Cartesian to Polar? Put 2.')
ip=int(input('Your wish: ')) #prompt user for input
if ip==1:
#if user enters 1, execute this block
R=int(input('Enter R= '))
theta=(input('Enter theta in radians= '))
polar2cart(R,theta)
else:
#if user does not enter 1, execute this block
x=int(input('Enter x= '))
y=int(input('Enter y= '))
cart2polar(x,y)
|
6c3a9013ec4b575035995144a1239ebc2f2d97ff | yuhaitao10/Language | /python/first-class/first_class_fun.py | 288 | 4.03125 | 4 | #!/usr/bin/python
def square(x):
return x*x
def cube(x):
return x*x*x
def my_map(func,arg_list):
result = []
for i in arg_list:
result.append(func(i))
return result
squares = my_map(square, [1,2,3,4,5,6])
print(squares)
cubes = my_map(cube, [1,2,3,4,5,6])
print(cubes)
|
4f4fddc6e1b35d24a52d7cbf4e3468aab4bca6d2 | yuhaitao10/Language | /python/scripts/data_types.py | 1,486 | 3.984375 | 4 | #!/usr/bin/python
#working on dictionary
print "\nWorking on dictionary"
hosts = {}
hosts['h1'] = '1.2.3.4'
hosts['h2'] = '2.3.4.5'
hosts['h3'] = '3.4.5.6'
for server,ip in hosts.items():
print server, ip
for server,ip in hosts.items():
print ('serer: {} ip: {}'.format(server, ip))
hosts2 = {'h1':'1.2.3.4','h2':'2,3,4,5', 'h3':'3.4.5.6'}
for server,ip in hosts2.items():
print "server: %s" % ip
mylist = []
mytuple = ()
mydictionary = {}
#the only thing we can do to a tuple is to add an element
a = (1,2,3)
a = a + (4,)
book={'Dad':'Bob','Mom':'Lisa','Bro':'Joe'}
book['Dad']
p=book.clear()
print "Dictionary clear() function: %s" % p
#del an dictionary element
del['Dad']
#add a dictionary element
book['Grace'] = 'Sis'
ages={'Dad':'42','Mom':'87'}
tuna=ages.copy()
p = 'Mom' in tuna
print "Dictionary in function: %s" % p
#working on string
print "\nWorking on string:"
seperator='hoss'
sequence=['hey','there', 'bessie','hoss']
glue='hoss'
p=glue.join(sequence)
print "string join() function: %s" % p
randstr="I wich I Had No Sausage"
randstr
p = randstr.lower()
print "string lower() function: %s" % p
truth="I love old women"
p = truth.replace('women', 'men')
print "String replace() function: %s" % p
example="Hey now bessie nice chops"
p = example.find('bessie')
print "String find() function: %s" % p
ratio = '68%'
amt = int(ratio.rstrip('%'))
print "String rstrip() function: %s" % amt
|
eb2fa02366ac7da73b69491e146e50dc6c4f9072 | zhngfrank/notes | /pynotes.py | 3,222 | 4.40625 | 4 | #division normally operates in floating point, to truncate and get integer division use
#// e.g.
print ("3//5 = ", 3//5, "whereas\n3/5 =", 3/5)
#when python is used as a calculator, e.g. through python3 command terminal, the last saved answer
#is stored in the variable "_" (underscore). same as 2nd ans on TI calculator
print('\n','_'*200,'\n')
##round(number, decimalplaces)
print ("round(75.0386, 2)= ", round(75.0386, 2))
#single and double quotes are interchangable, used them as needed to make text readable, e.g.
#if you need quotes in a print statement.
#you can also use \ as an escape sequence to the same effect, this means that the following
#is a character and not something else, e.g. \" will be printed, and will not terminate a print
#statement
print('\n', '_'*200,'\n')
print ("the dog said \"hello\"")
#use r before quotations to force the string to be raw characters. \will be ignored
print('\n', '_'*200,'\n')
print (r"the directory is \user\new, see, no newline")
#make multiline strings with triple quotes. no need to repeat print statements, or use new lines(\n)
#most of the time. python automatically adds a newline, but you can circumvent this by putting a \
#at the end of the line to prevent the EOL"
print('\n', '_'*200,'\n')
print ("""my name is frank\
nice to meet you
this is on the next line
and this is on the third line\
but this isn't""")
#strings can be glued together using the "+" sign or repeated using "*"
print('\n', '_'*200,'\n')
print("my name is frank" + ", nice to meet you" *3)
#side by side string literals can glued together without a + sign, just put em together
#print("yo", " fam")
print('\n', '_'*200,'\n')
#strings are stored c style, e.g. an array of characters. can be accessed via indices
var = "word"
print("word[0] =", var[0],"\nand word[-3] =", var[-3], " (reads from the right)")
print('\n', '_'*200,'\n')
#can slice indices, basically a to statement within the array
print("word[:2] hi word[2:] = " , var[:2], " hi ", var[2:])
print("notice that the first is included and end excluded")
#despite being c string they are immutable, you can't set var[4] = 'j'
print('\n', '_'*200,'\n')
print("len(var)= ", len(var))
#lists in python are like typename vectors, can store any data type and can be added to the end
#format is same as array
print('\n', '_'*200,'\n')
squares = [1, 4, 9, 16]
print("squares[0] = ", squares[0])
#can add to the end using squares.append(literal)
#can be sliced as well. makes it a hell of a lot easier to iterate through them
#creates a shallow copy >> ram usage issues?
print('\n', '_'*200,'\n')
if 3<5 :
print ("do, elif or else won't print")
elif 4>3:
print("this is the same as else if")
else:
print ('this is else')
test_boolean_logic1 = 0;
test_boolean_logic2 = 1;
if test_boolean_logic1:
print("this is 0, should not have printed")
elif test_boolean_logic2:
print("this should have printed, elif with 1 works!")
print('\n', '_'*200,'\n')
#for loop is significantly less explicit
for w in var:
print(w, len(var))
print("so the control variable w, once printed, corresponds to var[i], where i is internal and not",
"explicit")
####
print('\n', '_'*200,'\n', sep='')
|
07fa76c6a9fcbc33d34229f1e62c27e22ec93365 | juanperdomolol/Dominio-python | /ejercicio15.py | 595 | 4.1875 | 4 | #Capitalización compuesta
#Crear una aplicación que trabaje con la ley de capitalización compuesta.
#La capitalización compuesta es una operación financiera que proyecta un capital a un período futuro,
# donde los intereses se van acumulando al capital para los períodos subsiguientes.
capitalInicial= float(input("Cual es el capital dispuesto a Capitalización compuesta "))
interes = float(input("Cual es el interes anual? "))
años = int(input("A cuantos años se proyecta el capital "))
porcentaje= interes/100
resultado = capitalInicial*((1+porcentaje)**años)
print(resultado) |
70d854315f7ccfd8d4a3f46d604991b7a41f82d6 | juanperdomolol/Dominio-python | /ejercicio3.py | 630 | 3.890625 | 4 | #Intervalos
#Generar un número aleatorio entre 1 y 120.
#Decir si se encuentra en el intervalo entre 10 y 50, o bien si es mayor de 50 hasta 100,
# o bien si es mayor de 100, o bien si es menor de 10.
import random
Aleatorio = random.randrange(1, 120)
if (Aleatorio>10 and Aleatorio<50):
print("se encuentra en el intervalo entre 10 y 50")
elif (Aleatorio>50 and Aleatorio<100):
print("se encuentra en el intervalo entre 50 y 100")
elif (Aleatorio>100 and Aleatorio<=120):
print("se encuentra en el intervalo entre 100 y 120")
else:
print("El numero es menor de 10")
print("El numero es: ",Aleatorio) |
3c82383327e8e17cb8b22247916cb89861c50d46 | thouis/plate_normalization | /welltools.py | 377 | 3.5625 | 4 | import re
def extract_row(well):
well = well.upper().strip()
if len(well) > 0 and 'A' <= well[0] <= 'P':
return well[0]
return '(could not parse row from %s)'%(well)
def extract_col(well):
# find the first block of numbers
m = re.match('[^0-9]*([0-9]+)', well)
if m:
return m.group(1)
return '(could not parse col from %s)'%(well)
|
865f27d25b6f07ac8fb8ff2564ad663641104943 | michael-deprospo/OptionsTradingProject | /MultiRegression.py | 1,999 | 3.625 | 4 | from yahoo_fin import stock_info as si
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model
from sklearn.model_selection import train_test_split
#This class pertains to multiple linear regression modeling, with ordinary least squares as the loss function. This class will handle
#data preprocessing, cross validation, train-test split, building loss visualizations, feature engineering. We will be experimenting with L1 and L2
#loss, aka ridge and lasso regression. The final output will be train and test accuracy on the model, as well as inputting a stock and predicting it's
#price daily, weekly, and monthly
class MultiLinearRegression:
def __init__(self, ticker, startdate, enddate):
self.ticker = ticker
self.startdate = startdate
self.enddate = enddate
self.liveprice = None
self.X_train = None
self.Y_train = None
self.X_test = None
self.Y_test = None
self.data = None
def get_curr_price(self):
self.live_price = si.get_live_price(self.ticker)
return self.live_price
def get_historic_data(ticker):
self.data = si.get_data(ticker, start_date=self.startdate, end_date=self.enddate, index_as_date = False)
return self.data
def crossValidation(self):
return 0
def train_test_split(self):
X = get_historic_data(self.ticker)
temp = X
X = X.drop('adjclose')
Y = pd.Series(temp['adjclose'])
self.X_train, self.X_test, self.Y_train, self.Y_test = train_test_split(X, Y, train_size = .9)
return self.X_train, self.X_test, self.Y_train, self.Y_test
def rmse(self, actual_y, predicted_y):
return np.sqrt(np.mean((actual_y - predicted_y) ** 2))
def customFeatureEngineering(self, self.X):
df =
def buildMultiRegModel(self, ticker):
df = get_historic_data(ticker)
regressor = linear_model.LinearRegression()
|
c8bf6025d729849c121bd1b9ad4702dfae8a3a13 | brobinson124/ai3202 | /Assignment5/assignment5.py | 6,478 | 3.5 | 4 | #Brooke Robinson
#Assignment 5
#Used Assignment 2 as a base
#Worked with Mario Alanis
import sys
class Node:#node represent a grid squard
def __init__(self, locationx, locationy, type_val):
self.x = locationx
self.y = locationy
self.p = None
self.typeN = type_val #0 is free, 1 is mountain, 2 is wall, 3 is a snake, 4 is a barn
if type_val == 0:#awards associated with each type value
self.reward = 0
elif type_val == 1: #Mountain
self.reward = -1
elif type_val == 3: #Snake
self.reward = -2
elif type_val == 4: #Barn
self.reward = 1
elif type_val == 50: #the Apple!
self.reward = 50
else:
self.reward = 0
def setParent(self, parent): #setting the parent
self.p = parent
def getMap(arg):
mymap = []
with open(arg, 'r') as f:
for line in f:
line = line.strip()
if len(line) > 0:
mymap.append(map(int, line.split()))
for x in (range(0,len(mymap))):
for y in range(0,len(mymap[x])):
mymap[x][y] = Node(x,y,int(mymap[x][y]))
#print mymap[x][y].x,mymap[x][y].y, mymap[x][y].reward
return mymap
class MDP:
def __init__(self, mymap):
self.Open = {}
self.Close = {}
self.mymap = mymap
self.length = len(mymap)
self.goal = mymap[0][9]
self.start = mymap[7][0]
self.util_list = {} #a list that stores the utilities for the current
self.prev_util = {} #a list that stores the utilities for the previous
def getAdj(self, n):
#Added for MDP: No cornors
adj_matrix = []
for x in range(n.x-1, n.x+2): #we add +2 because the range does not include the final value
for y in range(n.y-1, n.y+2):
if(x>= 0 and y>=0 and x<len(self.mymap) and y<len(self.mymap[x]) and not (x== n.x and y==n.y)):
if not((x == n.x-1 and y == n.y-1) or (x==n.x+1 and y==n.y+1) or (x==n.x-1 and y ==n.y+1) or (n==n.x+1 and y==n.y-1)):
#we have to make sure it is within bounds(No corners!)
#we also have to make sure we do not add the same node
if(self.mymap[x][y].reward != 2):
adj = mymap[x][y]
adj_matrix.append(adj)
self.u = 0
return adj_matrix
def expect_u(self, e):#e=epsilon, our parameter
#let's initialize all of our map to 0.0 reward
for x in range(0,len(self.mymap)):
for n in self.mymap[x]:
self.util_list[n] = 0.0
self.prev_util[n] = 0.0
d = 1.0#d=delta, a way to measure our parameter
while(d>(e*(1.0-0.9)/0.9)): #our parameters
for x in range(0,len(self.mymap)):
for node in self.mymap[x]:
self.prev_util[node] = self.util_list[node] #add it to our previous to remember value for next loop
max_val = self.MDPfunc(node) #find the policy with the max reward
self.util_list[node] = node.reward +0.9*max_val #0.9 is our living reward
if node.typeN == 2: #cannot be a wall
self.util_list[node] = 0.0
d = 0.0 #reset delta
#we want to loop through the map in order to find if any of the nodes are greater than delta(our parameter tester)
for x in range(0,len(self.mymap)):
for node in self.mymap[x]:
if abs(self.util_list[node] - self.prev_util[node]) > d:
d = abs(self.util_list[node] - self.prev_util[node]) #update our parameters
#print('\n'.join([' '.join(['{0:.2f}'.format(self.util_list[item]) for item in row]) for row in self.mymap]))
#prints the grid of our utilities: I got this specifically from Mario in order to test my code
def MDPfunc(self, n):
#Our policy-finding function
adj = self.getAdj(n)
stored_vals = []
for val in adj:
if val.x == n.x: #have to check up option and down option
if val.y >= 0 and val.y < (len(self.mymap[0])-1):
if self.mymap[val.x][val.y+1] in adj:
node1 = self.mymap[n.x][n.y+1]
else:
node1 = 0.0
if self.mymap[n.x][n.y-1] in adj:
node2 = self.mymap[n.x][n.y-1]
else:
node2 = 0.0
if node1 == 0.0 and node2 == 0.0:
stored_vals.append(0.8*self.prev_util[val])
elif node1 == 0.0:
stored_vals.append(0.8*self.prev_util[val]+0.1*(self.prev_util[node2]))
elif node2 == 0.0:
stored_vals.append(0.8*self.prev_util[val]+0.1*(self.prev_util[node1]))
else:
stored_vals.append(0.8*self.prev_util[val]+0.1*self.prev_util[node1]+0.1*self.prev_util[node2])
elif val.y == n.y: #check left option and right option
if val.x >= 0 and val.x < (len(self.mymap)-1):
if self.mymap[val.x+1][val.y] in adj:
node1 = self.mymap[n.x+1][n.y]
else:
node1 = 0.0
if self.mymap[n.x-1][n.y] in adj:
node2 = self.mymap[n.x-1][n.y]
else:
node2 = 0.0
if node1 == 0.0 and node2 == 0.0:
stored_vals.append(0.8*self.prev_util[val])
elif node1 == 0.0:
stored_vals.append(0.8*self.prev_util[val]+0.1*self.prev_util[node2])
elif node2 == 0.0:
stored_vals.append(0.8*self.prev_util[val]+0.1*self.prev_util[node1])
else:
stored_vals.append(0.8*self.prev_util[val]+0.1*self.prev_util[node1]+0.1*self.prev_util[node2])
return max(stored_vals) #return the best policy
#A* search (Modified)
def starsearch(self):
self.Open[self.start] = self.util_list[self.start] #start our Open list with the reward value stored in util_list
while self.Open != {}:
#find reward that is the LARGEST
max_val_find = max(self.Open, key=self.Open.get)#we want the largest reward, so I changed MIN to MAX
max_val = self.Open[max_val_find]
for value in self.Open:
if self.Open[value] == max_val:
node = value
break
del self.Open[node]
if node.x == self.goal.x and node.y == self.goal.y:
self.time_to_print(node)
break
self.Close[node] = self.util_list[node]
node_adj = self.getAdj(node)
for n in node_adj:
if (n.typeN != 2 and not(n in self.Close)):
if not(n in self.Open) or (self.util_list[n] > self.util_list[node]):
n.setParent(node)
if not(n in self.Open):
self.Open[n] = self.util_list[n]
def time_to_print(self, nextNode):
print "This is my path: "
cost = 0
stringArr = []
while not(nextNode.x == self.start.x and nextNode.y == self.start.y):
stringArr.append(["(", nextNode.x, ",", nextNode.y, ")","Utility: ",self.util_list[nextNode]])
nextNode = nextNode.p
stringArr.append(["(", nextNode.x, ",", nextNode.y, ")", "Utility: ",self.util_list[nextNode]])
for lis in reversed(stringArr):
print lis[0],lis[1],lis[2],lis[3],lis[4],lis[5],lis[6]
mymap = getMap(sys.argv[1])
searched = MDP(mymap)
searched.expect_u(float(sys.argv[2]))
searched.starsearch()
|
baf478cdd62e5bd29bfaaa725f32fa2d041ae191 | louissock/Python-PPA | /ccipher.py | 6,844 | 3.84375 | 4 | """
Filename: ccipher.py
Author: Sang Shin
Date: 09/05/2012
"""
#!/bin/env python
import sys
CONST_ALBET = 'abcdefghijklmnopqrstuvwxyz'
MOD_ALBET = ''
def exit_program():
# Prompt the user with a exiting greet and terminate.
print "Thank you for using the Caesar Cipher Program."
print "Have a nice day."
sys.exit()
def rotate_alphabet(rot, direc):
rot = int(rot)
# For left rotations, we need to adapt for numbers greater than 26
# Rotate the alphabet to the left
if (str(direc).lower() == 'l') or (str(direc).lower() == "left"):
while rot == len(CONST_ALBET) or rot > len(CONST_ALBET):
rot = rot - len(CONST_ALBET)
lowEnd = [CONST_ALBET[i] for i in range(0, rot)]
highEnd = [CONST_ALBET[i] for i in range(rot, len(CONST_ALBET))]
modAlphabetList = highEnd + lowEnd
modAlphabet = "".join(modAlphabetList)
return modAlphabet
# For right rotations, we need to adapt for numbers greater than 26
# Rotate the alpabet to the right
elif (str(direc).lower() == 'r') or (str(direc).lower() == "right"):
while rot == len(CONST_ALBET) or rot > len(CONST_ALBET):
rot = rot - len(CONST_ALBET)
lowEnd = [CONST_ALBET[i] for i in range(len(CONST_ALBET) - rot, len(CONST_ALBET))]
highEnd = [CONST_ALBET[i] for i in range(0, (len(CONST_ALBET) - rot))]
modAlphabetList = lowEnd + highEnd
modAlphabet = "".join(modAlphabetList)
return modAlphabet
else:
print "An error occurred. Exiting."
sys.exit()
def encode_string(userString):
(encodedString, encodedSplitString) = ([],[])
# Check to see if the letter is in the alphabet. If not, add it to the array.
# If the letter is in the alphabet, we need to find the index of it in the
# original alphabet, and find the corresponding letter in the modified alphabet.
for lett in str(userString).lower():
if lett in str(CONST_ALBET):
idx = str(CONST_ALBET).index(lett.lower())
count = 0
for lett_mod in str(MOD_ALBET):
if int(idx) == count:
encodedString.append(lett_mod)
break
else:
count += 1
else:
encodedString.append(lett)
# We have a list that contains only letters. We are going to combine the letters
# to create the word and add it to a list.
encodedString = ''.join(encodedString)
encodedSplitString = encodedString.split()
return encodedSplitString
def encode_procedure():
global MOD_ALBET
userString = raw_input("Enter a string to encode: ")
userRotation = raw_input("Enter a rotation: ")
while True:
userDirection = raw_input("Enter a direction (L or R): ")
# Check for correction direction
if (str(userDirection).lower() == 'l') or \
(str(userDirection).lower() == 'left') or \
(str(userDirection).lower() == 'r') or \
(str(userDirection).lower() == 'right'):
break
else:
print "Invalid input. Try again."
MOD_ALBET = rotate_alphabet(userRotation, userDirection)
encodedUserString = encode_string(userString)
encodedUserString = ' '.join(encodedUserString)
print
print "Encoded String: %s" % encodedUserString
def check_decode_procedure(userString, userWord):
# We want to loop through every possible combination of
# rotations of the alphabet and see if the word provided
# by the user is in the decoded string.
#
# There are two possible outcomes for every decoding method
# for left and right rotations. Since these rotations overlap
# somewhere, we need to find both.
global MOD_ALBET
decodedData = {}
for i in range(1, len(CONST_ALBET) + 1):
MOD_ALBET = rotate_alphabet(i, 'l')
decodedUserString = decode_string(userString)
if userWord in decodedUserString:
decodedData["Left"] = i
break
for i in range(1, len(CONST_ALBET) + 1):
MOD_ALBET = rotate_alphabet(i, 'r')
decodedUserString = decode_string(userString)
if userWord in decodedUserString:
decodedData["Right"] = i
break
return (decodedUserString, decodedData)
def decode_string(userString):
(decodedString, decodedSplitString) = ([],[])
# Check to see if the letter is in the MOD_Alphabet. If not, add it to the array.
# If the letter is in the MOD_Alphabet, we need to find the index of it in the
# MOD_Alphabet, and find the corresponding letter in the original alphabet.
for lett_mod in str(userString).lower():
if lett_mod in str(MOD_ALBET):
idx = str(MOD_ALBET).index(lett_mod.lower())
count = 0
for lett in str(CONST_ALBET):
if int(idx) == count:
decodedString.append(lett)
break
else:
count += 1
else:
decodedString.append(lett_mod)
# We have a list that contains only letters. We are going to combine the letters
# to create the word and add it to a list.
decodedString = ''.join(decodedString)
decodedSplitString = decodedString.split()
return decodedSplitString
def decode_procedure():
global MOD_ALBET
userString = raw_input("Enter a string to decode: ")
userWord = raw_input("Enter a word in the string: ")
(decodedUserString, decodeData) = check_decode_procedure(userString, userWord)
decodedUserString = ' '.join(decodedUserString)
print
print "Decoded String: %s" % decodedUserString
print "Possible Combinations: "
if "Left" in decodeData:
print "\t Direction: Left \t Rotation: %s" % decodeData["Left"]
if "Right" in decodeData:
print "\t Direction: Right \t Rotation: %s" % decodeData["Right"]
else:
print "\t None. Decoding procedure failed."
def main():
print "This is the Caesar Cipher Program."
print "This will either encode or decode a string with the Caesar Algorithm."
while True:
print
print "\t 'e' to ENCODE"
print "\t 'd' to DECODE"
print "\t 'q' to QUIT"
print
userInput = raw_input("\t ---> ")
if (str(userInput).lower() == 'e') or (str(userInput).lower() == 'encode'):
encode_procedure()
elif (str(userInput).lower() == 'd') or (str(userInput).lower() == 'decode'):
decode_procedure()
elif (str(userInput).lower() == 'q') or (str(userInput).lower() == 'quit'):
exit_program()
else:
print "Invalid Input. Try again."
if __name__ == "__main__":
main()
|
fcd42737dc107cd0ddda3a5ea2963abbca0bff55 | louissock/Python-PPA | /gasoline.py | 1,469 | 3.671875 | 4 | """
Filename: gasoline.py
Author: Sang Shin
Date: 08/09/2012
"""
#!/bin/env python
from __future__ import division
CONVERSION_GAL_LITER = 3.7854
CONVERSION_GAL_BARREL = 19.5
CONVERSION_GAL_POUND = 20
CONVERSION_GAL_ENERGY = 115000
CONVERSION_GAL_ENERGY_ETH = 75700
CONVERSION_GAL_DOLLAR = 4.00
def main():
user_input = raw_input("Please enter the number of gallons of gasoline: ")
input_fl = float(user_input)
print "Original number of gallons is: %.2f" % input_fl
print "%.2f gallons is the equivalent of %.2f liters" % (input_fl, \
input_fl * CONVERSION_GAL_LITER)
print "%.2f gallons of gasoline requires %f barrels of oil" % (input_fl, \
input_fl / CONVERSION_GAL_BARREL)
print "%.2f gallons of gasoline produces %.2f pounds of C02" % (input_fl, \
input_fl * CONVERSION_GAL_POUND)
print "%.2f gallons of gasoline is energy equivalent to %.2f gallons of ethanol" % (input_fl, \
(input_fl * CONVERSION_GAL_ENERGY_ETH)/CONVERSION_GAL_ENERGY)
print "%.2f gallons of gasoline requires $%.2f U.S. Dollars" % (input_fl, input_fl * CONVERSION_GAL_DOLLAR)
print
print "Thank you for playing"
if __name__ == "__main__":
main()
|
ff69e17bc700225f4eb40e087d613599d79aedfa | louissock/Python-PPA | /digicount.py | 847 | 3.734375 | 4 | """
Filename: digicount.py
Author: Sang Shin
Date: 08/10/2012
"""
#!/bin/env python
def userInputChecker(diag):
check = 1
while check == 1:
try:
inp_str = raw_input(diag)
inp_int = int(inp_str)
check = 0
except ValueError:
check = 1
print "Please enter a valid number."
return inp_int
def main():
inp_int = userInputChecker("Enter a number: ")
print "The number entered is %d" % inp_int
print
inp_int_digi = userInputChecker("Enter a digit: ")
print "The digit entered is %d" % inp_int_digi
print
digi_arr = [digi for digi in str(inp_int)]
count = digi_arr.count(str(inp_int_digi))
print "The number of %s's in %s is %d" % (str(inp_int_digi), str(inp_int), count)
if __name__ == "__main__":
main()
|
a57504d5e5dd34e53a3e30b2e0987ae6314d6077 | MattCoston/Python | /shoppinglist.py | 298 | 4.15625 | 4 | shopping_list = []
print ("What do you need to get at the store?")
print ("Enter 'DONE' to end the program")
while True:
new_item = input("> ")
shopping_list.append(new_item)
if new_item == 'DONE':
break
print("Here's the list:")
for item in shopping_list:
print(item)
|
5682494536ebd893e233685b4395290391c6c2b2 | VanSC/Lab7 | /Problema6.py | 575 | 3.875 | 4 | pares=0
impares=0
neutro=0
negativos=0
positivos=0
limite=5
for x in range(limite):
number=int(input("ingres el numero "))
if number % 2 == 0:
pares+=1
else:
impares+=1
if x<0:
negativos+=1
else:
positivos+=1
if number == 0:
neutro = 0
print("La cantidad de numeros pares es: ",pares)
print("La cantidad de numeros impares es: ",impares)
print("La cantidad de numeros negativos es: ",negativos)
print("La cantidad de numeros positivos es: ",positivos)
print("El numero neutro es: ",neutro) |
edea61d2217ce4cb2beceb5211bfbd0a844b4a1a | dennisliuu/Coding-365 | /102/003.py | 795 | 3.828125 | 4 | import math
triType = input()
triHeight = int(input())
if triType == '1':
for i in range(1, (triHeight + 1) // 2 + 1):
for j in range(1, i + 1):
print(j, end='')
print()
for i in range(1, (triHeight + 1) // 2):
for j in range(1, (triHeight + 1) // 2 - i + 1):
print(j, end='')
print()
elif triType == '2':
for i in range(1, (triHeight + 1) // 2 + 1):
for j in range(1, (triHeight + 1) // 2 - i + 1):
print('.', end='')
for j in range(i, 0, -1):
print(j, end='')
print()
for i in range(1, (triHeight + 1) // 2):
for j in range(0, i):
print('.', end='')
for j in range((triHeight + 1) // 2 - i, 0, -1):
print(j,end='')
print()
|
5635f384336ab7a9cda34f2217deb0b2aede9388 | dennisliuu/Coding-365 | /101/001.py | 337 | 3.765625 | 4 | name = input("姓名:")
std_id = input("學號:")
score1 = int(input("第一科成績:"))
score2 = int(input("第二科成績:"))
score3 = int(input("第三科成績:"))
total = score1 + score2 + score3
print("Name:" + name + '\n' + "Id:" + std_id + '\n' +
"Total:" + str(total) + '\n' + "Average:" + str(int(total/3))) |
f174320582815cb1397828890720288b72bab536 | dennisliuu/Coding-365 | /103/003.py | 2,800 | 3.75 | 4 | # class poly:
# __a = [0]*20 #存放第一个输入的多项式和运算结果
# __b = [0]*20#存放输入的多项式
# __result = [0]*20#结果
# def __Input(self,f):
# n = input('依序输入二项式的系数和指数(指数小于10):').split()
# for i in range(int(len(n)/2)):
# f[ int(n[2*i+1])] = int(n[2*i])
# print(f, n)
# self.__output(f)
# def __add(self,a,b): #加法函数
# return [a[i]+b[i] for i in range(20)]
# def __minus(self,a,b): #减法函数
# return [a[i]-b[i] for i in range(20)]
# def __mul(self,a,b):
# self.__result = [0]*20
# for i in range(10):#第一个循环:b分别于a[0]到a[9]相乘
# for j in range(10): #第二个循环:b[j]*a[i]
# self.__result[i+j] = int(self.__result[i+j]) + int(a[i]*b[j])
# return self.__result
# def __output(self,a):#输出多项式
# b = ''
# for i in range(20):
# if a[i]> 0:
# b = b+'+'+str(a[i])+'X^'+str(i)
# if a[i]<0:
# b = b+"-"+str(-a[i])+'X^'+str(i)
# print(b[1::])
# def control(self):
# print ("二项式运算:\n")
# self.__Input(self.__a)
# while True:
# operator = input('请输入运算符(结束运算请输入‘#’)')#self.Input(self.a)
# if operator =='#':
# return 0
# else:
# self.__b = [0]*20
# self.__Input(self.__b)
# self.__a = {'+':self.__add(self.__a,self.__b),'-':self.__minus(self.__a,self.__b),'*':self.__mul(self.__a,self.__b)}.get(operator)
# print ('计算结果:',end='')
# self.__output(self.__a)
# POLY = poly() #初始化类
# POLY.control() #通过选取操作符选择相应的运算
# import numpy as np
# # sym = input()
# # 4x^3 - 2x + 3
list1 = []
p1 = input().split(' ')
for i in p1:
list1.append(i)
print(list1)
t = len(list1)
for i in range(len(list1)):
if i == t:
break
if list1[i] == '-':
list1[i:i+2] = [''.join(list1[i:i+2])]
t -= 1
print(list1)
x_times = [s for s in list1 if "x" in s]
print(x_times)
print(
list(set(list1) - set(x_times)).remove('+')
)
coef = []
for i in range(len(x_times)):
coef.append(x_times[i].split('x')[0])
coef.append((x_times[i].split('x')[1]))
for i in range(len(coef)):
if coef[i] == '':
coef[i] = 1
elif coef[i] == '-':
coef[i] = -1
print(coef)
# # p1 = np.poly1d([4, 0, -2, 3])
# # p2 = np.poly1d([-2, 0, -1, 3, -1, -1])
# # if sym == '+':
# # print(p1 + p2)
# # elif sym == '-':
# # print(p1 - p2)
# # elif sym == '*':
# # print(p1 * p2)
|
b33e6d93be650bfcfe25852ffd17b411915c7d4f | ghmkt/3th_EDU | /Session03_Python_element_3/Session03_Quest_answer_3.py | 1,838 | 3.609375 | 4 | # 클래스 연습문제
class stock_analysis:
def __init__(self, code):
try:
with open("c:\\Users\\LYJ\\Desktop\\파이썬세션데이터\\{0}.csv".format(code)) as f:
self.lines = f.readlines()
except FileNotFoundError:
print("{0} 파일을 로드하는데 실패했습니다".format(code))
else:
self.len = len(self.lines)
self.latest_close = int(self.lines[-1].split(',')[4])
self.latest_open = int(self.lines[-1].split(',')[1])
self.latest_low = int(self.lines[-1].split(',')[2])
self.latest_high = int(self.lines[-1].split(',')[3])
def close_mean(self):
close = [int(line.split(',')[4]) for line in self.lines[1:]]
return (sum(close) // len(close))
def close_variance(self):
return sum([(int(line.split(',')[4]) - self.close_mean())**2 for line in self.lines[1:]]) / len(self.lines[1:])
def close_std(self):
return self.close_variance()**0.5
def volume_mean(self):
volume = [int(line.split(',')[5].strip()) for line in self.lines[1:]]
return (sum(volume) // len(volume))
def MA5(self):
MA5_dict = {}
for i in range(5,self.len):
MA5_dict[self.lines[i].split(',')[0]] = sum([int(self.lines[i].split(',')[4]) for i in range(i-4,i+1)]) / 5
return MA5_dict
# 판다스 연습문제
import pandas as pd
df = pd.read_csv("c:\\Users\\LYJ\\Desktop\\파이썬세션데이터\\네이버_new.csv", engine='python')
# 1번
df["종가"] = df["종가"].apply(lambda x: x*(-1))
# 2번
df['상승폭'] = ((df['종가'] - df['시가'])/df['시가']) * 100
# 3번
# 범위에 맞게 적절히 수정
print(df['종가'][30:60])
# 4번
vol_mean = df['거래량'].mean()
print(df[df['거래량'] > vol_mean * 1.5]['종가'].mean())
|
5c9da03dc72008401f422d092f27b27bedd28177 | AspenH/K-Nearest-Neighbor-Algorithm | /knn.py | 3,625 | 3.78125 | 4 | # Programmed by Aspen Henry
# This program uses two .csv files within its directory (trainging data and test sample data)
# to classify test samples using the K Nearest Neighbor algorithm.
import math
#This function is used to preformat the csv files for use
#It assumes that the csv is in the form [class_label, a1, a2, ..., an]
#with the first row of data in the csv being lables for columns
def preformat(fileName):
with open(fileName) as file:
contents = file.readlines()
for i in range(len(contents)):
contents[i] = contents[i][:-1]
contents[i] = contents[i].split(',')
for i in range(1, len(contents)):
for j in range(len(contents[i])):
contents[i][j] = int(contents[i][j])
return contents
#Function for calculating the Euclidean Distance
def getDistance(x1, x2):
distance = 0
for i in range(1, len(x1)):
distance += math.pow((x1[i] - x2[i]), 2)
return math.sqrt(distance)
#Function for getting the output class of the test sample with KNN
def KNN(trainingData, tup, k):
neighborDistances = [20000]*k
neighborClasses = [None]*k
#Calculating the k closest distances and storing the corresponding classes
for data in trainingData:
if(isinstance(data[0], str)):
continue
distance = getDistance(tup, data)
if(all(i < distance for i in neighborDistances)):
continue
else:
del neighborClasses[neighborDistances.index(max(neighborDistances))]
neighborClasses.append(data[0])
neighborDistances.remove(max(neighborDistances))
neighborDistances.append(distance)
#Calculating the votes (weights) for each class by using a summation of (1 / distance)
classVotes = {}
for i in range(len(neighborClasses)):
if (neighborClasses[i] not in classVotes.keys()):
classVotes[neighborClasses[i]] = (1 / neighborDistances[i])
else:
classVotes[neighborClasses[i]] += (1 / neighborDistances[i])
for cj, weight in classVotes.items():
if (weight == max(classVotes.values())):
return cj
#Driver function for performing the analysis and classification
def main():
trainingFileName = "MNIST_train.csv"
trainingData = preformat(trainingFileName)
testFileName = "MNIST_test.csv"
testData = preformat(testFileName)
k = 7
#Classifying test data and finding statistics for analysis
desiredClasses = []
computedClasses = []
for test in testData:
if(isinstance(test[0], str)):
continue
desiredClasses.append(test[0])
computedClasses.append(KNN(trainingData, test, k))
correctClassifications = 0;
totalClassifications = 0;
for i in range(len(desiredClasses)):
totalClassifications += 1
if (desiredClasses[i] == computedClasses[i]):
correctClassifications += 1
accuracy = (correctClassifications / totalClassifications) * 100
missedClassifications = totalClassifications - correctClassifications
#Printing the output
print("\nK = " + str(k) + '\n')
for i in range(len(desiredClasses)):
print("Desired class: " + str(desiredClasses[i]) +
" computed class: " + str(computedClasses[i]))
print("\nAccuracy rate: " + str(accuracy) + "%" +'\n')
print("Number of misclassified test samples: " + str(missedClassifications) + '\n')
print("total number of test samples: " + str(totalClassifications))
#print(KNN(trainingData, testData[34], k))
if __name__ == "__main__":
main()
|
df3157fb21a7d9d35fdd8ce4550733a859f3a64c | Potrik98/plab2 | /proj5/fsm/utils.py | 166 | 3.625 | 4 |
#
# Check if a string is an integer
#
def is_int(string: str) -> bool:
try:
int(string)
return True
except ValueError:
return False
|
c259e8f8f0be2ae221e13062855d370df14d9691 | Potrik98/plab2 | /proj3/crypto/AffineCipher.py | 1,281 | 3.5 | 4 | from crypto.SimpleCipher import SimpleCipher
from crypto.Cipher import Cipher, alphabet, alphabet_length
from crypto.MultiplicationCipher import MultiplicationCipher
from crypto.CaesarCipher import CaesarCipher
class AffineCipher(SimpleCipher):
class Key(Cipher.Key):
def __init__(self,
caesar_key: CaesarCipher.Key,
multiplication_key: MultiplicationCipher.Key):
self._caesar_key = caesar_key
self._multiplication_key = multiplication_key
def __str__(self):
return "Affine key: %s %s" % (str(self._caesar_key), str(self._multiplication_key))
def __init__(self):
super().__init__()
self._caesar_cipher = CaesarCipher()
self._multiplication_cipher = MultiplicationCipher()
def set_key(self, key: Key):
self._caesar_cipher.set_key(key._caesar_key)
self._multiplication_cipher.set_key(key._multiplication_key)
def _encrypt_character(self, char):
return self._caesar_cipher._encrypt_character(
self._multiplication_cipher._encrypt_character(char))
def _decrypt_character(self, char):
return self._multiplication_cipher._decrypt_character(
self._caesar_cipher._decrypt_character(char))
|
ec44a59c2bfda5f812b86363dd4ad98c114361a1 | yashmalik23/python-domain-hackerrank | /the minion game.py | 339 | 3.515625 | 4 | def minion_game(s):
vowels = 'AEIOU'
kev = 0
stu = 0
for i in range(len(s)):
if s[i] in vowels:
kev += (len(s)-i)
else:
stu += (len(s)-i)
if kev > stu:
print ("Kevin", kev)
elif kev < stu:
print ("Stuart", stu)
else:
print ("Draw") |
7ebd2319068650b767db0961f553832b4af556b1 | PythonHacker199/Bargraph-3d- | /main.py | 541 | 4.09375 | 4 | # Hi gus
#welcome to hacker python channel
# today we will learn how to make bar graph
#we need to install matplotlib package
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig=plt.figure()
ax1=fig.add_subplot(111,projection='3d')
xpos=[1,2,3,4,5,6,7,8,9,10]
ypos=[1,2,3,4,5,1,6,8,2,1]
zpos=[0,0,0,0,0,0,0,0,0,0]
num_elements=len(xpos)
dx=np.ones(10)
dy=np.ones(10)
dz=[2,4,1,6,4,8,0,2,3,2]
ax1.bar3d(xpos,ypos,zpos,dx,dy,dz,color='#26ffe6')
plt.show()
# so guys thank you and have a great day |
2b908cba6c3ff6eea86011228e03224a22bec643 | Kenneth-Fries/Kenneth_Fries | /Pairs 2-25-19 best path.py | 5,195 | 4.25 | 4 | """The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess.
The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately.
Some of the rooms are guarded by demons, so the knight loses health (negative integers) upon entering these rooms; other rooms are either empty (0's) or contain magic orbs that increase the knight's health (positive integers).
In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.
Write a function to determine the knight's minimum initial health so that he is able to rescue the princess.
For example, given the dungeon below, the initial health of the knight must be at least 7 if he follows the optimal path RIGHT-> RIGHT -> DOWN -> DOWN.
-2 (K) -3 3
-5 -10 1
10 30 -5 (P)
Note:
The knight's health has no upper bound.
Any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.
"""
import itertools
import time
dungeon1 = [[-2,-3,3],[-5,-10,1],[10,30,-5]]
dungeon2 = [[1,-4,5,-99],[2,-2,-2,-1]]
dungeon4 = [[-2,-3,3,-4],[-5,-10,1,2],[10,30,-5,-3]]
dungeon5 = [[-2,-3,3,3,5],[-5,-10,1,-3,-2],[10,30,-5,5,3],[10,30,-5,5,3],[10,30,-5,5,3]]
dungeon6 = [[-2,-3,3,3,5,6],[-5,-10,1,-3,-2,3],[10,30,-5,5,3,-1],[10,30,-5,5,3,-4],[10,30,-5,5,3,-19],[11,20,-5,5,3,-19]]
dungeon7 = [[-2,-3,3,3,5,6,5],[-5,-10,1,-3,-2,3,84,-6],[10,30,-5,5,3,-1,-11,-10],[10,30,-5,5,3,-4,10,-3],[10,30,-5,5,3,-19,5,-5],[-12,7,11,20,-5,5,3,-19],[-4,7,11,20,-5,5,3,-19]]
dungeon8 = [[0,-74,-47,-20,-23,-39,-48],[37,-30,37,-65,-82,28,-27],[-76,-33,7,42,3,49,-93],[37,-41,35,-16,-96,-56,38],[-52,19,-37,14,-65,-42,9],[5,-26,-30,-65,11,5,16],[-60,9,36,-36,41,-47,-86],[-22,19,-5,-41,-8,-96,-95]]
"""This is the slow brute force method. Faster method below."""
def calculateMinimumHP(dungeon):
start = time.time() #so slow I was timing it
width = len(dungeon)-1
height = len(dungeon[0])-1
direction_instructions = str() #producing a list of binary instructions
for _ in range (width):
direction_instructions += '1' #1 will mean go right
for _ in range (height):
direction_instructions += '0' #0 will mean go down
direction = set() #get rid of duplicates using a set
[direction.add(i) for i in itertools.permutations(direction_instructions, height + width)]
direction = list(direction) #Make it iterable
#the following goes through every path and calculates the life hit
result_set = set()
counter = 0
for x in direction:
i = 0
j = 0
life = 0
trial = set()
life += dungeon[i][j] #starting Square
trial.add(life) #each amount of life gets updated to the trial list
for y in x:
counter += 1 #just to keep track of how many iterations for curiosity
print(counter)
if y == '1': # if the instruction is a 1 we go down
i+= 1
else: #if the instruction is 0 we go right
j += 1
#life starts at zero, and is
life += dungeon[i][j] #updated every step
trial.add(life) #trial value is added to a list or set
result_set.add(min(trial)) #The min value is key to remember
if max(result_set) > 0: #If you won't die going through maze
print( 1) #The min start value would be 1
print(1-max(result_set)) #Otherwise it's this value.
end = time.time()
print("time = ",end - start) #This is for curiosity
#calculateMinimumHP(dungeon1) #This take forever for large dungeons
"""The following second take at this challange produced a faster algorithm.
I learned a better way of looking at his type of problem. """
def calculateMinimumHP2(dungeon):
start = time.time()
width = len(dungeon[0])-1
height = len(dungeon)-1
for i in range(height,-1,-1):
for j in range(width,-1,-1):
print('i',i,'j',j,'width',width,'height',height)
[print(x) for x in dungeon]
print('dungeon[i][j] = ',dungeon[i][j])
if i == height and j == width:
dungeon[i][j] = max([1,1-dungeon[i][j]])
elif i == height:
dungeon[i][j] = max([1,dungeon[i][j+1] - dungeon[i][j]])
elif j == width:
dungeon[i][j] = max([1,dungeon[i+1][j] - dungeon[i][j]])
else:
tempi = dungeon[i][j+1] - dungeon[i][j]
tempj = dungeon[i+1][j] - dungeon[i][j]
dungeon[i][j] = max(1,min([tempi,tempj]))
end = time.time()
print("time = ",end - start) #This is for curiosity
return dungeon[0][0]
calculateMinimumHP2(dungeon8)
|
27fd01141cf75a31a087b5fa5b47e7b203b0bdbd | FuelRats/pipsqueak3 | /src/packages/utils/autocorrect.py | 1,450 | 3.578125 | 4 | """
autocorrect.py - Methodology to attempt auto-correcting a typo'd system name.
Copyright (c) 2019 The Fuel Rat Mischief,
All rights reserved.
Licensed under the BSD 3-Clause License.
See LICENSE.md
This module is built on top of the Pydle system.
"""
import re
def correct_system_name(system: str) -> str:
"""
Take a system name and attempt to correct common mistakes to get the true system name.
Args:
system (str): The system name to check for corrections.
Returns:
str: The system name with any corrections applied, uppercased.
"""
system = system.upper()
match_regex = re.compile(r"(.*)\b([A-Z01258]{2}-[A-Z01258])\s+"
r"([A-Z01258])\s*([0-9OIZSB]+(-[0-9OIZSB]+)?)\b")
replacements = {k: v for k, v in zip('01258', 'OIZSB')}
# Check to see if the provided system name follows the procedural format.
matched = match_regex.match(system)
if matched:
sector = matched.group(1).strip()
letters = f"{matched.group(2)} {matched.group(3)}"
numbers = matched.group(4)
for letter, number in replacements.items():
letters = letters.replace(letter, number)
numbers = numbers.replace(number, letter)
# Re-format the string to ensure no extraneous spaces are included.
return f"{sector} {letters}{numbers}"
# Don't try and correct a system that isn't procedurally named.
return system
|
7c967ec0e9a7286ab5569133662f8966efcfd80b | coder-kiran/pythonCalculator | /pythonCalculatorByKK.py | 10,311 | 3.625 | 4 | # Python Calculator by Kiran K K
from tkinter import *
from tkinter.messagebox import *
import math
window = Tk()
window.geometry("230x350")
window.title("I Calculate")
window.configure(bg='#000066')
window.resizable(0,0)
s0 = s1 = s2 = ""
famous=""
equalClickedOn = False
font=('verdana',10)
#------------------ function definitions------------------
def num0Clicked():
global famous
global val
global s0, s2, s1
if s1 != "":
s2=""
s2 = s2 + "0"
famous=famous+s2
else:
s0=""
s0 = s0 + "0"
famous=famous+s0
labelid.set(famous)
def num1Clicked():
global famous
global s0,s2,s1
if s1 != "":
s2 = ""
s2 = s2 + "1"
famous = famous + s2
else:
s0 = ""
s0 = s0 + "1"
famous = famous + s0
labelid.set(famous)
def num2Clicked():
global famous
global s0, s2, s1
if s1 != "":
s2 = ""
s2 = s2 + "2"
famous = famous + s2
else:
s0 = ""
s0 = s0 + "2"
famous = famous + s0
labelid.set(famous)
def num3Clicked():
global famous
global s0, s2, s1
if s1 != "":
s2 = ""
s2 = s2 + "3"
famous = famous + s2
else:
s0 = ""
s0 = s0 + "3"
famous = famous + s0
labelid.set(famous)
def num4Clicked():
global famous
global s0, s2, s1
if s1 != "":
s2 = ""
s2 = s2 + "4"
famous = famous + s2
else:
s0 = ""
s0 = s0 + "4"
famous = famous + s0
labelid.set(famous)
def num5Clicked():
global famous
global s0, s2, s1
if s1 != "":
s2 = ""
s2 = s2 + "5"
famous = famous + s2
else:
s0 = ""
s0 = s0 + "5"
famous = famous + s0
labelid.set(famous)
def num6Clicked():
global famous
global s0, s2, s1
if s1 != "":
s2 = ""
s2 = s2 + "6"
famous = famous + s2
else:
s0 = ""
s0 = s0 + "6"
famous = famous + s0
labelid.set(famous)
def num7Clicked():
global famous
global s0, s2, s1
if s1 != "":
s2 = ""
s2 = s2 + "7"
famous = famous + s2
else:
s0 = ""
s0 = s0 + "7"
famous = famous + s0
labelid.set(famous)
def num8Clicked():
global famous
global s0, s2, s1
if s1 != "":
s2 = ""
s2 = s2 + "8"
famous = famous + s2
else:
s0 = ""
s0 = s0 + "8"
famous = famous + s0
labelid.set(famous)
def num9Clicked():
global famous
global s0, s2, s1
if s1 != "":
s2 = ""
s2 = s2 + "9"
famous = famous + s2
else:
s0 = ""
s0 = s0 + "9"
famous = famous + s0
labelid.set(famous)
def dotClicked():
global famous
global s0, s2, s1
if s1 != "":
s2=""
s2 = s2 + "."
famous = famous + s2
else:
s0=""
s0 = s0 + "."
famous = famous + s0
labelid.set(famous)
def addClicked():
global famous
global s1
s1 = "+"
famous=famous+s1
labelid.set(famous)
def minusClicked():
global famous
global s1
s1 = "-"
famous = famous + s1
labelid.set(famous)
def multClicked():
global famous
global s1
s1 = "*"
famous = famous + s1
labelid.set(famous)
def divClicked():
global famous
global s1
s1 = "/"
famous = famous + s1
labelid.set(famous)
def powerClicked():
global famous
global s1
s1 = "^"
famous=famous+s1
labelid.set(famous)
def equalClicked():
try:
global s0,s2
if s1 == "^":
labelid.set(pow(int(s0),int(s2)))
s0=s2=""
else:
global equalClickedOn
answer=eval(famous)
labelid.set("")
labelid.set(answer)
equalClickedOn = True
except Exception as e:
showerror("Error",e)
def clearClicked():
global famous,s0,s1,s2
s0=s1=s2=famous=""
labelid.set(famous)
def backSpaceClicked():
global famous
if equalClickedOn == False:
lengthOfFamous = len(famous) - 1
newfamous = famous[0:lengthOfFamous]
famous = newfamous
labelid.set(famous)
else:
famous = ""
labelid.set(famous)
def squareRoot():
labelid.set(math.sqrt(int(labelid.get())))
def darkClicked():
window.config(bg="#000000")
b0.config(bg='#663300')
b1.config(bg='#000000')
b2.config(bg='#000000')
b3.config(bg='#000000')
b4.config(bg='#000000')
b5.config(bg='#000000')
b6.config(bg='#000000')
b7.config(bg='#000000')
b8.config(bg='#000000')
b9.config(bg='#000000')
ba.config(bg='#333')
bs.config(bg='#333')
bd.config(bg='#333')
bm.config(bg='#333')
beq.config(bg='#006600')
bc.config(bg='#660000')
bdot.config(bg='#000000')
bback.config(bg='#660000')
bdark.config(bg='#000000')
blight.config(bg='#000000')
bsqrt.config(bg='#660000')
bpower.config(bg='#000000')
label.config(bg='#fff',fg='#333333')
def lightClicked():
window.config(bg='#000066')
b0.config(bg='#cc3300')
b1.config(bg='#000066')
b2.config(bg='#000066')
b3.config(bg='#000066')
b4.config(bg='#000066')
b5.config(bg='#000066')
b6.config(bg='#000066')
b7.config(bg='#000066')
b8.config(bg='#000066')
b9.config(bg='#000066')
ba.config(bg='#0066ff')
bs.config(bg='#0066ff')
bd.config(bg='#0066ff')
bm.config(bg='#0066ff')
beq.config(bg='#009900')
bc.config(bg='#003399')
bdot.config(bg='#000066')
bback.config(bg='#003399')
bdark.config(bg='#000066')
blight.config(bg='#000066')
bsqrt.config(bg='#003399')
bpower.config(bg='#000066')
label.config(bg='#fff')
#------------------creating a text field------------------
labelid = StringVar()
label = Label(window, text="", width=20, height=2,textvariable=labelid,padx=5,pady=10,anchor='e',font='verdana 12 ',fg='#000066')
# ------------------creating buttons------------------
b0 = Button(window, text="0", width=5, height=2, command=num0Clicked,activebackground='#0000ff',
activeforeground='#000000',bg='#cc3300',borderwidth=0,foreground='#fff',font=font)
b1 = Button(window, text="1", width=5, height=2, command=num1Clicked,bg='#000066',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff')
b2 = Button(window, text="2", width=5, height=2, command=num2Clicked,bg='#000066',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff')
b3 = Button(window, text="3", width=5, height=2, command=num3Clicked,bg='#000066',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff')
b4 = Button(window, text="4", width=5, height=2, command=num4Clicked,bg='#000066',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff')
b5 = Button(window, text="5", width=5, height=2, command=num5Clicked,bg='#000066',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff')
b6 = Button(window, text="6", width=5, height=2, command=num6Clicked,bg='#000066',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff')
b7 = Button(window, text="7", width=5, height=2, command=num7Clicked,bg='#000066',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff')
b8 = Button(window, text="8", width=5, height=2, command=num8Clicked,bg='#000066',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff')
b9 = Button(window, text="9", width=5, height=2, command=num9Clicked,bg='#000066',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff')
bd = Button(window, text="/", width=5, height=2,command=divClicked,bg='#0066ff',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff')
bm = Button(window, text="x", width=5, height=2,command=multClicked,bg='#0066ff',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff')
ba = Button(window, text="+", width=5, height=2, command=addClicked,bg='#0066ff',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff')
bs = Button(window, text="-", width=5, height=2,command=minusClicked,bg='#0066ff',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff')
beq = Button(window, text="=", width=5, height=2, command=equalClicked,bg='#009900',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff')
bc = Button(window, text="C", width=5, height=2,command=clearClicked,bg='#003399',borderwidth=0,foreground='#fff',font=font ,activebackground='#0033ff')
bdot = Button(window, text=".", width=5, height=2, command=dotClicked,bg='#000066',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff')
bback = Button(window,text="back",width=5, height=2, command=backSpaceClicked,bg='#003399',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff')
bpower = Button(window,text="^",width=5, height=2, command=powerClicked,bg='#000066',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff')
bsqrt = Button(window,text="√",width=5, height=2, command=squareRoot,bg='#003399',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff')
bdark = Button(window,text="DARK",width=11, height=2, command=darkClicked,bg='#000066',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff')
blight = Button(window,text="LIGHT",width=11, height=2, command=lightClicked,bg='#000066',borderwidth=0,foreground='#fff',font=font,activebackground='#0033ff')
#------------------ applying grid system to all elements------------------
label.grid(row=2, columnspan=4,pady=30,padx=7)
bc.grid(row=4,column=0)
bback.grid(row=4,column=1,)
bsqrt.grid(row=4,column=2)
bd.grid(row=4, column=3)
b7.grid(row=5, column=0)
b8.grid(row=5, column=1)
b9.grid(row=5, column=2)
bm.grid(row=5, column=3)
b4.grid(row=6, column=0)
b5.grid(row=6, column=1)
b6.grid(row=6, column=2)
bs.grid(row=6, column=3)
b1.grid(row=7, column=0)
b2.grid(row=7, column=1)
b3.grid(row=7, column=2)
ba.grid(row=7, column=3)
b0.grid(row=8, column=1)
bdot.grid(row=8, column=0)
bpower.grid(row=8,column=2)
beq.grid(row=8, column=3)
bdark.grid(row=9,column=0,columnspan=2)
blight.grid(row=9,column=2,columnspan=2)
#------------------ execution of calculator ends here------------------
window.mainloop()
|
331ea7efc532c4d9f09da6b6497be679c91de9ff | layanabushaweesh/math-series | /tests/serises_test.py | 1,828 | 3.65625 | 4 | # testing fibonacci function :)
from math_serises.serise import fibonacci
def test_fib_0():
expected=0
actual=fibonacci(0)
assert actual == expected
def test_fib_1():
expected=1
actual=fibonacci(1)
assert actual == expected
def test_fib_2():
expected=1
actual=fibonacci(2)
assert actual == expected
def test_fib_3():
expected=2
actual=fibonacci(3)
assert actual == expected
# testing lucas function
from math_serises.serise import lucas
def test_luc_0():
excepted=2
actual=lucas(0)
assert actual==excepted
def test_luc_1():
excepted=1
actual=lucas(1)
assert actual==excepted
def test_luc_2():
excepted=3
actual=lucas(2)
assert actual==excepted
def test_luc_3():
excepted=4
actual=lucas(3)
assert actual==excepted
def test_luc_4():
excepted=7
actual=lucas(4)
assert actual==excepted
# testing sum function
from math_serises.serise import sum_series
# 1- Calling this function with no optional parameters will produce numbers from the fibonacci series.
def test_sum_0():
excepted=0
actual=sum_series(0)
assert actual == excepted
def test_sum_1():
excepted=1
actual=sum_series(1)
assert actual == excepted
def test_sum_2():
excepted=1
actual=sum_series(2)
assert actual == excepted
# 2- Calling it with the optional arguments 2 and 1 will produce values from the lucas.
def test_sum_lucas_0():
excepted=2
actual=sum_series(0,2,1)
assert actual == excepted
def test_sum_lucas_1():
excepted=1
actual=sum_series(1,2,1)
assert actual == excepted
def test_sum_lucas_2():
excepted=3
actual=sum_series(2,2,1)
assert actual == excepted
# 3- Other values for the optional parameters will produce other series.
def test_sum_other_2():
actual=sum_series(2,2,3)
excepted=5 # i gess
assert actual == excepted |
b6a2e295b45e45114c947f339cfae96b8faa8229 | rompe/adventofcode2020 | /src/day02.py | 503 | 3.71875 | 4 | #!/usr/bin/env python
import itertools
import sys
def solution(input_file):
"""Solve today's riddle."""
lines = open(input_file).read().splitlines()
valids = 0
for line in lines:
count, char, password = line.split()
char = char[0]
lowest, highest = count.split('-')
if (password[int(lowest) - 1] == char) ^ (password[int(highest) - 1] == char):
valids += 1
print(valids)
if __name__ == "__main__":
sys.exit(solution(sys.argv[1]))
|
d0bca1738a9a21e3888084c65786e73bff22fe7d | CodecoolBP20161/python-pair-programming-exercises-4th-tw-miki_gyuri | /3-phone-numbers/main.py | 1,266 | 3.796875 | 4 | import csv
import sys
from person import Person
def open_csv(file_name):
with open(file_name, 'r') as phone_number:
names_n_numbers = [line.split(",") for line in names_n_numbers.readlines()]
numbers = []
numbers = numbers.digits
for element in names_n_numbers:
for i in element[1]:
# get phone numbers from list elements
# remove every non-digit characters
return names_n_numbers
def get_csv_file_name(argv_list):
to_return = argv_list[1] # might need to tell that it's a string
return to_return
def format_output(person):
# implent this function
pass # delete this
def get_person_by_phone_number(person_list, user_input_phone_number):
for element in person_list:
if user_input_phone_number == element[1]:
return element[0]
def main():
file_name = get_csv_file_name(sys.argv)
if file_name is None:
print('No database file was given.')
sys.exit(0)
person_list = open_csv(file_name)
user_input_phone_number = input('Please enter the phone number: ')
match_person = get_person_by_phone_number(person_list, user_input_phone_number)
print(format_output(match_person))
if __name__ == '__main__':
main()
|
f62b64433ab03f57cc107b63c7c853590be44a9f | koiku/nickname-generator | /main.py | 1,028 | 3.640625 | 4 | """
* 0 - Vowel letter
*
* 1 - Consonant letter
"""
import random
VOWELS = ['a', 'e', 'i', 'o', 'u', 'y']
CONSONANTS = [
'b', 'c', 'd', 'f', 'g',
'h', 'j', 'k', 'l', 'm',
'n', 'p', 'q', 'r', 's',
't', 'v', 'w', 'x', 'z'
]
MIN_LEN = 3
MAX_LEN = 8
def main():
length = random.randint(MIN_LEN, MAX_LEN)
nickname = ""
prev_letter = -1
two_vowels = False
for letter in range(length):
if letter == 0:
letter_type = random.randint(0, 1)
prev_letter = letter_type
if letter_type == 0:
nickname += random.choice(VOWELS)
two_vowels = False
else:
nickname += random.choice(CONSONANTS)
two_vowels = False
continue
if prev_letter == 1:
nickname += random.choice(VOWELS)
prev_letter = 0
elif prev_letter == 0:
letter_type = random.randint(0, 1)
if letter_type == 0 and not two_vowels:
nickname += random.choice(VOWELS)
two_vowels = True
else:
nickname += random.choice(CONSONANTS)
two_vowels = False
print(nickname)
if __name__ == "__main__":
main()
|
d924bcfa89f8453db0f96e452469e2bbd15c21d3 | ScottRWilson11/WebScrapingHW | /webscraping.py | 889 | 3.546875 | 4 | import pandas as pd
from bs4 import BeautifulSoup
import requests
url1="https://www.nasa.gov/feature/jpl/nasas-next-mars-mission-to-investigate-interior-of-red-planet"
r = requests.get(url1)
data = r.text
soup = BeautifulSoup(data, features="html.parser")
news_title = soup.title.text
print(news_title)
tags = soup.find(attrs={"name":"dc.description"})
news_p = tags.get('content')
print(news_p)
url1 = "https://space-facts.com/mars/"
page = requests.get(url1)
data = page.text
soup = BeautifulSoup(data, 'html.parser')
table = soup.find_all("table")
for mytable in table:
table_body = mytable.find('tbody')
rows = table_body.find_all('tr')
for tr in rows:
print ("<tr>")
cols = tr.find_all('td')
for td in cols:
print ("<td>",td.text, "</td>")
print ("</tr>")
#df = pd.read_html(str(table))
|
64b86298ac0017b88bf25e6d658a6bc9b4c22d0a | panwuying/homework5 | /work6.py | 203 | 3.53125 | 4 | a="4 4 213 123 124 1 123 "
a=a.split()
a=[int(x) for x in a]
def all_list(b):
c = min(b)
for i in range(len(b)):
if c==b[i]:
print(i)
break
all_list(a)
|
96aa4c549c9a5341a565699832cdbbf30ff406e7 | liweinan/hands_on_ml | /sort_class.py | 982 | 4.125 | 4 | from collections import OrderedDict
class Student:
def __init__(self, name, order):
self.name = name
self.order = order
tom = Student("Tom", 0)
jack = Student("Jack", 0)
rose = Student("Rose", 1)
lucy = Student("Lucy", 2)
users = OrderedDict()
users[rose.name] = rose
users[lucy.name] = lucy
users[jack.name] = jack
users[tom.name] = tom
# 接下来是转化users,让order变成key,然后让value是student数组
users2 = OrderedDict()
for k, v in users.items():
if v.order not in users2.keys():
users2[v.order] = []
users2[v.order].append(v)
# 然后是sort这个数组,生成一个新的dict:
sorted_users = OrderedDict()
sorted_keys = sorted(users2)
for k in sorted_keys:
for v in users2[k]:
print(str(v.order) + ", " + v.name)
sorted_users[v.name] = v
# 这样,我们就得到了sorted_users:
print("-=-=-=-=-=-=-=-=-=-=-=-=-=-")
for k, v in sorted_users.items():
print(str(v.order) + ", " + k)
|
6c112be7a3443ebd31b68bfe73f424af50ca34af | abhishekshrestha008/Binary-and-Linear-Search-Algorithms | /searchMain.py | 1,242 | 3.84375 | 4 | import random
from search import linear_search, binary_search
from time import time
import matplotlib.pyplot as plt
elapsed_linear = []
elapsed_binary = []
x = []
for i in range(10000, 100000, 10000):
#Data
data = random.sample(range(i), i)
sorted_data = sorted(data)
random_number = random.randint(0,len(data)-1)
#For Linear Search
start_linear = time()
index_linear = linear_search(data, random_number)
end_linear = time()
elapsed_linear.append((end_linear - start_linear))
#For Binary Search
start_binary = time()
index_binary = binary_search(sorted_data, 0, len(data)-1, random_number)
end_binary = time()
elapsed_binary.append((end_binary - start_binary))
x.append(i)
plt.plot(x, elapsed_linear, label="linear_search")
plt.plot(x, elapsed_binary, label="binary_search")
plt.xlabel('Input size')
plt.ylabel('Execution time')
plt.title('Input size vs Execution-time graph')
plt.legend()
plt.show()
print("The best case for linear_search is: {} ".format(min(elapsed_linear)))
print("The worst case for linear_search is: {} ".format(max(elapsed_linear)))
print("The best case for binary search is: {} ".format(min(elapsed_binary)))
print("The worst case for binary search is: {} ".format(max(elapsed_binary))) |
ebb33953daccc725fab8383a652c8fd60c181ff1 | ferdirn/hello-python | /python_min.py | 185 | 3.65625 | 4 | #!/usr/bin/env python
list1, list2 = ['xyz', 'abc', 'opq'], [8, 9, 3, 5, 6]
print 'list1', list1
print 'list2', list2
print 'min(list1)', min(list1)
print 'min(list2)', min(list2)
|
be66511c268ce38ea8d4e3ce561894c390bccbc2 | ferdirn/hello-python | /hari.py | 349 | 3.84375 | 4 | #!/usr/bin/env python
nama_hari = raw_input('Masukkan nama hari : ')
if nama_hari == 'sabtu' or nama_hari == 'minggu':
print 'Weekends'
elif nama_hari == 'senin' or nama_hari == 'selasa' or nama_hari == 'rabu' or nama_hari == 'kamis':
print 'Weekdays'
elif nama_hari == "jum'at":
print 'TGIF'
else:
print 'Nama hari tidak dikenal'
|
7937dba17b2af72fcedc087ce51375b73258e3e0 | ferdirn/hello-python | /yourname.py | 195 | 3.875 | 4 | #!/usr/bin/env python
firstname = raw_input('Your first name is ').strip()
lastname = raw_input('Your last name is ').strip()
print "Hello {} {}! Nice to see you...".format(firstname, lastname)
|
4de4ba9a0b6507c01147f52527413bfbf0305982 | ferdirn/hello-python | /ternaryoperator.py | 231 | 4.1875 | 4 | #!/usr/bin/env python
a = 1
b = 2
print 'a = ', a
print 'b = ', b
print '\n'
#ternary operator
print 'Ternary operator #1'
print 'a > b' if (a > b) else 'b > a'
print '\nTernary operator #2'
print (a > b) and 'a > b' or 'b > a'
|
fc7b4eb2b4ffe1f9021b3cf27842600cdc88e098 | ferdirn/hello-python | /bitwiseoperators.py | 337 | 3.796875 | 4 | #!/usr/bin/env python
print 'binary of 5 is', bin(5)[2:]
print 'binary of 12 is', bin(12)[2:]
print '5 and 12 is', bin(5&12)[2:]
print '5 or 12 is', bin(5|12)[2:]
print '5 xor 12 is', bin(5^12)[2:]
print 'not 5 is', bin(~5)
print '2 shift left 5 is', bin(5<<2)[2:], ' or ', 5<<2
print '2 shift right 5 is', bin(5>>2)[2:], ' or ', 5>>2
|
986e29934e3ad5528978247f8eaf1be4173e10e3 | ferdirn/hello-python | /comparison_operators.py | 411 | 3.546875 | 4 | #!/usr/bin/env python
print 'is equal'
print '10 == 20 ' + str(10 == 20)
print '\nis not equal'
print '10 != 20 ' + str(10 != 20)
print '10 <> 20 ' + str(10 <> 20)
print '\ngreater than'
print '10 > 20 ' + str(10 > 20)
print '\nless than'
print '10 < 20 ' + str(10 < 20)
print '\ngreater than or equal to'
print '10 >= 20 '+ str(10 >= 20)
print '\nless than or equal to'
print '10 <= 20 ' + str(10 <= 20)
|
683501e8b36347e0fc89b461d33ca8ade2457895 | ferdirn/hello-python | /kelvintofahrenheit.py | 294 | 3.796875 | 4 | #!/usr/bin/env python
def KelvinToFahrenheit(temperature):
assert (temperature >= 0), "Colder than absolute zero!"
return ((temperature-273)*1.8)+32
try:
print KelvinToFahrenheit(273)
print KelvinToFahrenheit(-5)
except AssertionError, e:
print e.args
print str(e)
|
4da324086fd2415baf3a247e24841560fc29a8b1 | sharpvik/python-libs | /search.py | 2,353 | 3.640625 | 4 | #
# ================================== BBBBBB YY YYY MMMM MMMM RRRRRR VV VVV RRRRRR
# = THE = BBB BB YY YYY MMMMM MMMMM RRR RR VV VVV RRR RR
# ===> Search functions library <=== BBBBBB YYYYY MMM MM MMM RRRRRR VV VVV RRRRRR
# = (25.04.2018) = BBB BBB YYY MMM MMM RRR R VVVVV RRR R
# ================================== BBBBBBBB YYY MMM MMM RRR RR VVV RRR RR
#
# My github --> https://www.github.com/sharpvik <--
#
# functions
## --> binary search
def binary(array, element): # array(list) -- list of numbers; element(int / float) -- number you are searching for;
# --> function returns index of element if found, ohterwise returns -1;
array.sort() # sort the array just in case;
low = 0 # low(int) -- lowest searching limit;
high = len(array) - 1 # high(int) -- highest searching limit;
index = -1 # index(int) -- index of the element if found, otherwise = -1;
position = high // 2 # position(int) -- the index we're testing;
while low < high:
if element == array[position]:
index = position
return index
elif element < array[position]:
high = position - 1
else:
low = position + 1
position = (high - low) // 2 + low
else:
if low == high and element == array[low]:
index = low
return index
## binary search <--
## --> linear search
def linear(array, element, count=1): # array(list) -- any list; element(any type) -- element you are searching for;
# count(int) -- number of indexes saved before returning the answer;
indexes = []
i = 0
while i < len(array) and len(indexes) < count:
if array[i] == element:
indexes.append(i)
i += 1
if len(indexes) == 0:
return -1
elif len(indexes) == 1:
return indexes[0]
else:
return indexes
## linear search <--
|
fb89441290c0ebb8992bbe6ac22ef88da84b0afd | sharpvik/python-libs | /graphD.py | 5,155 | 3.734375 | 4 | #
# =============================== BBBBBB YY YYY MMMM MMMM RRRRRR VV VVV RRRRRR
# = THE = BBB BB YY YYY MMMMM MMMMM RRR RR VV VVV RRR RR
# ===> Graph class <=== BBBBBB YYYYY MMM MM MMM RRRRRR VV VVV RRRRRR
# = (10.05.2018) = BBB BBB YYY MMM MMM RRR R VVVVV RRR R
# =============================== BBBBBBBB YYY MMM MMM RRR RR VVV RRR RR
#
# My github --> https://www.github.com/sharpvik <--
#
from stackD import Stack
from queueD import Queue
class Graph: # undirected graph; no values for the edges;
def __init__(self):
self.nodes_dict = dict()
def node_add(self, name): # name(int / str) -- name of the node;
if name not in self.nodes_dict:
self.nodes_dict.update( { name : list() } )
return name
def node_del(self, name): # name(int / str) -- name of the node;
self.nodes_dict.pop(name, None)
for each in self.nodes_dict:
try:
self.nodes_dict[each].remove(name)
except ValueError:
print( "WARNING: {} does not exist!".format(name) )
return name
def connection_add(self, one, two): # one(int / str) and two(int / str) -- two nodes you want to connect;
if two not in self.nodes_dict[one]:
self.nodes_dict[one].append(two)
if one not in self.nodes_dict[two]:
self.nodes_dict[two].append(one)
return [one, two]
def connection_del(self, one, two): # one(int / str) and two(int / str) -- two nodes you want to disconnect;
try:
self.nodes_dict[one].remove(two)
except ValueError:
print( "WARNING: {} does not have a connection to {}!".format(two, one) )
try:
self.nodes_dict[two].remove(one)
except ValueError:
print( "WARNING: {} does not have a connection to {}!".format(one, two) )
return [one, two]
def nodes_count(self): # --> function returns the number of nodes in the graph;
return len(self.nodes_dict)
def nodes_return(self): # --> function returns the whole dict containing nodes and their connections;
return self.nodes_dict
def node_con_return(self, name): # name(int / str) -- name of the node you're checking;
# --> function returns connections of the given node;
return self.nodes_dict[name]
# search
## --> breadth first search using class Queue
def bfs( self, final, queue=Queue(None), checked=list() ): # final(int / str) -- name of the node you're trying to establish connection with;
# queue(class Queue) -- Queue containing the element you are beginning with (format: element);
# checked(list) -- leave empty *** internal use ***;
# --> function returns True if the two nodes are connected, otherwise it returns False;
_checked = list(checked)
if queue.is_empty():
return False
temp = queue.pop()
if temp == final:
return True
else:
_checked.append(temp)
for child in self.node_con_return(temp):
if child not in _checked and not queue.inside(child):
queue.push(child)
return self.bfs(final, queue, _checked)
## breadth first search using class Queue <--
## --> depth first serach using class Stack
def dfs( self, final, stack=Stack(None), checked=list() ): # final(int / str) -- name of the node you're trying to establish connection with;
# stack(class Stack) -- Stack containing the element you are beginning with (format: element);
# checked(list) -- leave empty *** internal use ***;
# --> function returns True if the two nodes are connected, otherwise it returns False;
_checked = list(checked)
if stack.is_empty():
return False
temp = stack.pop()
if temp == final:
return True
else:
_checked.append(temp)
for child in self.node_con_return(temp):
if child not in _checked and not stack.inside(child):
stack.push(child)
return self.dfs(final, stack, _checked)
## depth first serach using class Stack <--
|
55075c4e6d4561690da93b466a2f1a7c2319be64 | MMahoney6713/cs50 | /pset6-Python/credit.py | 243 | 3.640625 | 4 | card = input('Card Number? ')
var = 0
for i in range(1, length(card), 2):
value = int(card(i)) * 2
if value > 9:
value = str(value)
value = int(value[1]) + int(value([2])
var += value
print(f"{round_1_sum}") |
4b089ecb061076b81df93e125f0b86f259b3197d | bognan/training_python | /guess the random namber/random number from computer.py | 1,121 | 3.703125 | 4 | import random
number = random.randint(1, 100)
users_count = int(input('Введите количество игроков: '))
users_list = []
for i in range(users_count):
user_name = (input(f'Введите имя игрока {i}: '))
users_list.append(user_name)
count = 1
levels = {1: 10, 2: 5, 3: 3}
level = int(input('Выбирете уровень сложности: '))
max_count = levels[level]
is_winner = False
winner_name = None
while not is_winner:
count += 1
if count > max_count:
print('Все игроки проиграли')
break
for user in users_list:
print(f'Ход игрока {user}')
user_number = int(input(f'{user} введите ваше число: ', ))
if number == user_number:
is_winner = True
winner_name = user
break
elif number < user_number:
print('Ваше число больше')
else:
print('Ваше число меньше')
else:
print(f'Вы угадали число c {count} попыток. {winner_name} победил!')
|
2bc2bbc4f60dddbef026efbc41a63ab24182cd25 | bognan/training_python | /HW/HW№2.py | 234 | 4.03125 | 4 | number = int(input('Введите любое число: ',))
while (number > 10) or (number < 0):
number = int(input('Побробуйте еще: ',))
else:
if number <= 10:
print('Результат:', number ** 2) |
4415824dde9566902bf6a7bb9015764785597c02 | mateusPreste/Testing | /Testing/Plot.py | 202 | 3.65625 | 4 | from matplotlib.pyplot import *
import numpy as np
def f(t):
return t**2*np.exp(-t**2)
t = np.linspace(0, 3, 310)
y = np.zeros(len(t))
for i in range(len(t)):
y[i] = f(t[i])
plot(t, y)
show()
|
6b94e8638f16b58df5460af29cb8f13e2a8e53bc | mittalpranjal12/Basic-Python-Codes | /swap_two_numbers.py | 312 | 4.09375 | 4 | #swap two numbers
x = int(input("Enter first number: x= "))
y = int(input("Enter second number: y= "))
print("Value of x and y before swapping is {0} and {1}" .format(x,y))
#swapping using temp
temp = x
x = y
y = temp
print("\nThe value of x and y after swapping is {0} and {1}" .format(x ,y)) |
9392258cba43a64ce272d77ab90b889c020946d9 | LorenBristow/module3 | /ch04_UnitTesting/is_prime.py | 1,237 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 28 10:00:27 2019
@author: loren
"""
#### TASK 1 - PRIME NUMBERS to FAIL & TASK 2 - to PASS ####
def is_prime(number):
'''Return True if number is a prime number'''
if number <= 1:
return False
elif number > 1:#to prevent div by 0 error
for each in range(2,number):
if number % each == 0 and number != each:
print("false")
return False
return True
else:
print("weird")
def print_next_prime(number): ##something still wrong here.
'''If number is prime, provide next prime number'''
next_number = number
while is_prime(number) == True:
next_number += 1
if is_prime(next_number) == True:
print("After {}, the next prime number is {}".format(number, next_number))
return number
### TASK 4 - Count Words ###
def wordcount(text):
wordcount_dictionary = {}
words = text.split()
for word in words:
if word in wordcount_dictionary:
wordcount_dictionary[word] = wordcount_dictionary[word] + 1
else:
wordcount_dictionary[word] = 1
return wordcount_dictionary
wordcount('foo bar foo') |
771b2e1c61a2466875e9b9ed32ba91d9c7625e01 | ChChLance/sc_project | /stancode_project/boggle_game_solver/boggle.py | 3,669 | 3.90625 | 4 | """
File: boggle.py
Name:
----------------------------------------
TODO:
"""
# This is the file name of the dictionary txt file
# we will be checking if a word exists by searching through it
FILE = 'dictionary.txt'
word_lst = []
bog_lst = []
ans_lst = []
legal_edge = []
record_lst = []
look_up_dict = {}
def main():
"""
TODO:
"""
read_dictionary()
legal_edge_setup()
for i in range(1, 5):
row = input(str(i) + " row of letters: ")
row_lst = row.lower().split()
if check_illegal(row_lst) is False:
print('Illegal input')
break
bog_lst.append(row_lst)
if i == 4:
built_dict()
boggle()
def boggle():
for x in range(0, 4): # Start from every point
for y in range(0, 4):
# Take out letter location and append into record_lst
start_point = (y, x)
record_lst.append(start_point)
boggle_helper(y, x)
print("There are " + str(len(ans_lst)) + " words in total.")
def boggle_helper(y, x):
for i in range(-1, 2): # Search toward all direction
for j in range(-1, 2):
if (y+i, x+j) not in record_lst: # Check whether we already passed the location
if legal_edge_check((y+i, x+j)): # Check whether the location excess the edge
record_lst.append((y+i, x+j)) # Append letter into the record list
cur_word = take_record_lst_str(record_lst) # Take out string in the record list
if len(cur_word) >= 4: # Check prefix & ans at the same time only if length of word >= 4
if has_prefix_and_find_ans(cur_word) == 'with_ans':
if cur_word not in ans_lst: # Just keep a unique answer
ans_lst.append(cur_word)
print("Found: ", cur_word)
boggle_helper(y + i, x + j)
else:
# No prefix -> no wat to go -> pop(go back to previous selected point)
record_lst.pop()
else: # Only check prefix when length of word < 4
if has_prefix(cur_word):
boggle_helper(y + i, x + j)
else:
# No prefix -> no wat to go -> pop(go back to previous selected point)
record_lst.pop()
# Completed search for all direction -> no wat to go -> pop(go back to previous selected point)
record_lst.pop()
def check_illegal(row_lst):
for letter in row_lst:
if len(letter) != 1:
return False
def built_dict():
for x in range(0, 4):
for y in range(0, 4):
look_up_dict[(y, x)] = bog_lst[y][x]
def take_record_lst_str(lst):
"""
:param lst: list, the record list
:return: str, the string which is taken from the record list
"""
cur_word = ''
for tpl in lst:
cur_word = cur_word + look_up_dict[tpl]
return cur_word
def legal_edge_setup():
for i in range(0, 4):
for j in range(0, 4):
legal_edge.append((i, j))
def legal_edge_check(cur_point):
if cur_point in legal_edge:
return True
else:
return False
def read_dictionary():
"""
This function reads file "dictionary.txt" stored in FILE
and appends words in each line into a Python list
"""
with open(FILE, 'r') as f:
for line in f:
line = line.split()
if len(line[0]) >= 4:
word_lst.append(line[0])
def has_prefix(sub_s):
"""
:param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid
:return: (bool) If there is any words with prefix stored in sub_s
"""
for i in word_lst:
if i.startswith(sub_s):
return True
return False
def has_prefix_and_find_ans(sub_s):
"""
:param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid
:return: (bool) If there is any words with prefix stored in sub_s
"""
for i in word_lst:
if i.startswith(sub_s):
if sub_s == i:
return "with_ans"
else:
return "no_ans"
return False
if __name__ == '__main__':
main()
|
0d6582833054a0596747ea349f9d714deeb5b355 | fxyan/data-structure | /code/反转链表.py | 214 | 3.859375 | 4 | def reverseList(head):
"""
:type head: ListNode
:rtype: ListNode
"""
q = None
while head is not None:
p = head
head = head.next
p.next = q
q = p
return q
|
9185b85e3286d25f7e59612585b183302cb81b47 | fxyan/data-structure | /queue.py | 813 | 4.0625 | 4 | class Node(object):
def __init__(self, element=None, next=None):
self.element = element
self.next = next
def __repr__(self):
return str(self.element)
class Queue(object):
def __init__(self):
self.head = Node()
self.tail = self.head
def empty(self):
return self.head.next is None
def append(self, element):
node = Node(element)
self.tail.next = node
self.tail = node
def pop(self):
node = self.head.next
if not self.empty():
self.head = self.head.next
return node
def test():
q = Queue()
q.append(1)
q.append(2)
q.append(3)
q.append(4)
print(q.pop())
print(q.pop())
print(q.pop())
print(q.pop())
if __name__ == '__main__':
test()
|
e86aed6b3987db89dd58700410da0a25a030f5f7 | fxyan/data-structure | /code/剑指/删除链表中重复的节点.py | 1,226 | 3.96875 | 4 | """
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留。
样例1
输入:1->2->3->3->4->4->5
输出:1->2->5
样例2
输入:1->1->1->2->3
输出:2->3
这个题是比较绕的,思路有些清奇
首先先设定一个虚拟节点 None 将他的next连到头结点上去
p永远是前一个节点 q是p的下一个节点
while 如果让q等于p.next 直到q的值为一个新的节点的值
然后拿 p的第二个节点对比如果相等那么p直接下移
如果不等那么将p的next指向q
"""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def deleteDuplication(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:
return head
new_head = ListNode(0)
p = new_head
while p.next:
q = p.next
while q and q.val == p.next.val:
q = q.next
if p.next.next == q:
p = p.next
else:
p.next = q
return new_head.next
|
99bad259f692251137282ccf7b168ba6a67d1ac0 | fxyan/data-structure | /code/lookup_array.py | 654 | 3.6875 | 4 | """
二维数组查找数据
首先确定行数和列数
将左下角第一个数设为n
如果这个整数比n大,那么就排除这一行 向上查询
如果这个整数比n小,那么就排除这一列像右查询
"""
class Solution:
# array 二维列表
def Find(self, target, array):
# write code here
rows = len(array) - 1
cols = len(array[0]) - 1
i = rows
j = 0
while j <= cols and i >= 0:
if array[i][j] > target:
i -= 1
elif array[i][j] < target:
j += 1
else:
return True
return False
"""
""" |
97b3f526a267e916bb6ae64e4a1db6b5d5bb372d | fxyan/data-structure | /code/剑指/机器人移动范围.py | 1,394 | 3.578125 | 4 | """
地上有一个 m 行和 n 列的方格,横纵坐标范围分别是 0∼m−1 和 0∼n−1。
一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格。
但是不能进入行坐标和列坐标的数位之和大于 k 的格子。
请问该机器人能够达到多少个格子?
样例1
输入:k=7, m=4, n=5
输出:20
样例2
输入:k=18, m=40, n=40
输出:1484
解释:当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。
但是,它不能进入方格(35,38),因为3+5+3+8 = 19。
这里还是用了深搜
"""
class Solution(object):
def movingCount(self, threshold, rows, cols):
"""
:type threshold: int
:type rows: int
:type cols: int
:rtype: int
"""
self.rows = rows
self.cols = cols
self.dict = set()
self.search(threshold, 0, 0)
return len(self.dict)
def judge(self, threshold, c, r):
return sum(map(int, list(str(c)))) + sum(map(int, list(str(r)))) <= threshold
def search(self, threshold, c, r):
if not self.judge(threshold, c, r) or (c, r) in self.dict:
return
self.dict.add((c, r))
if c < self.cols - 1:
self.search(threshold, c+1, r)
if r < self.rows - 1:
self.search(threshold, c, r+1) |
d926c569be01e185ea52383e988360694ec1809c | fxyan/data-structure | /Array.py | 602 | 3.96875 | 4 | # 定长的列表
class Array(object):
def __init__(self, size=8):
self._size = size
self._item = [None] * size
def __len__(self):
return self._size
def __getitem__(self, index):
return self._item[index]
def __setitem__(self, key, value):
self._item[key] = value
def clear(self, value=None):
for i in range(len(self._item)):
self._item[i] = value
def __iter__(self):
for item in self._item:
yield item
def __repr__(self):
return '列表值: {}'.format(self._item)
print(Array())
|
348fd28791be8033b293c27087b6861ec35b6989 | fxyan/data-structure | /exercise.py | 12,479 | 4.0625 | 4 | """
冒泡排序
首先从第一个数循环到倒数第二个数 n-1 最后一个数已经被安排了
内层循环开始从第一个数开始循环 n-1-i次,因为i也被安排了
边界检测如果为没有数
def bubble_sort(array):
if array is None or len(array) < 2:
return array
for i in range(len(array)-1):
for j in range(len(array)-i-1):
if array[j] > array[j+1]:
array[j], array[j+1] = array[j+1], array[j]
def test_bubble():
array = [4, 2, 1, 7, 5, 3, 2, 4]
array2 = [4, 4, 1]
bubble_sort(array)
bubble_sort(array2)
print(array)
print(array2)
"""
"""
选择排序 就是直接定义第一个数是最小值,然后开始循环找到真正最小值的坐标然后两个交换
不需要检查最后一个因为最后一个会在自动排序完成
def select_sort(array):
if array is None or len(array) < 2:
return array
for i in range(len(array)-1):
index = i
for j in range(i+1, len(array)):
if array[index] > array[j]:
index = j
if index != i:
array[i], array[index] = array[index], array[i]
def test_select():
array = [4, 2, 1, 7, 5, 3, 2, 4]
array2 = [4, 4, 1]
select_sort(array)
select_sort(array2)
print(array)
print(array2)
"""
"""
插入排序
将一个数据插入到已经排好序的数组中
判断他的值是不是最小的如果不是就一直前移
def insert_sort(array):
for i in range(1, len(array)):
index = i
value = array[i]
while index > 0 and value < array[index-1]:
array[index] = array[index-1]
index -= 1
if index != i:
array[index] = value
def test_insert():
array = [4, 2, 1, 7, 5, 3, 2, 4]
array2 = [4, 4, 1]
insert_sort(array)
insert_sort(array2)
print(array)
print(array2)
"""
"""
快排 使用了递归的排序
基本思路就是找到一个中间点,然后将自己的数组分成两部分左部分右部分和中间点,然后递归回去
import random
def quick_sort(array):
if len(array) < 2 or array is None:
return array
return quick(array, 0, len(array)-1)
def quick(array, l, r):
if l < r:
ran = random.randint(l, r)
print(l, r)
print(ran)
array[ran], array[r] = array[r], array[ran]
q = partition(array, l, r)
print(q)
quick(array, l, q[0])
quick(array, q[1], r)
def partition(array, l, r):
left = l-1
right = r
while l < right:
if array[l] < array[r]:
left += 1
array[left], array[l] = array[l], array[left]
l += 1
elif array[l] > array[r]:
right -= 1
array[l], array[right] = array[right], array[l]
else:
l += 1
array[r], array[l] = array[l], array[r]
q = [left, right+1]
return q
def test_quick():
array = [4, 2, 1, 7, 5, 3, 2, 4]
array2 = [4, 4, 1]
quick_sort(array)
quick_sort(array2)
print(array)
print(array2)
"""
"""
归并排序
def merge_sort(array):
if len(array) < 2 or array is None:
return array
return sort_process(array, 0, len(array)-1)
def sort_process(array, l, r):
if l == r:
return None
else:
mid = (l+r)//2
sort_process(array, l, mid)
sort_process(array, mid+1, r)
merge(array, l, mid, r)
def merge(array, l, mid, r):
help = []
left = l
right = mid+1
while left <= mid and right <= r:
if array[left] < array[right]:
help.append(array[left])
left += 1
else:
help.append(array[right])
right += 1
while left <= mid:
help.append(array[left])
left += 1
while right <= r:
help.append(array[right])
right += 1
for i in range(len(help)):
array[l+i] = help[i]
def test_merge():
array = [4, 2, 1, 7, 5, 3, 2, 4]
array2 = [4, 4, 1]
merge_sort(array)
merge_sort(array2)
print(array)
print(array2)
"""
"""
堆排序
def heap_sort(array):
if len(array) < 2 or array is None:
return array
size = len(array)
build_max(array, size)
for i in range(size-1, -1, -1):
array[i], array[0] = array[0], array[i]
heap_insert(array, 0, i)
def build_max(array, size):
for i in range((size-2)//2, -1, -1):
heap_insert(array, i, size)
def heap_insert(array, root, size):
left = root * 2 + 1
while left < size:
largest = left+1 if left+1 < size and array[left+1] > array[left] else left
if array[root] < array[largest]:
array[root], array[largest] = array[largest], array[root]
root = largest
left = root * 2 + 1
else:
return
def test_heap():
array = [4, 2, 1, 7, 5, 3, 2, 4]
array2 = [4, 4, 1]
heap_sort(array)
heap_sort(array2)
print(array)
print(array2)
"""
"""
判断数组中有没有三个数相加等于 你输入的整数
# 三重循环的辣鸡写法
def equal1(seq, n):
if len(seq) < 3:
return False
for i in range(len(seq) - 2):
for j in range(i + 1, len(seq) - 1):
for x in range(j + 1, len(seq)):
print(x)
if seq[i] + seq[j] + seq[x] == n:
return True
return False
# 通过指针优化的写法
def equal(seq, n):
if len(seq) < 3:
return False
for i in range(len(seq) - 2):
j = i + 1
k = len(seq) - 1
while j != k:
if seq[i] + seq[j] + seq[k] < n:
j += 1
elif seq[i] + seq[j] + seq[k] > n:
k -= 1
elif seq[i] + seq[j] + seq[k] == n:
return True
return False
"""
"""
判断排序之后数组的相邻的最大差值,使用非比较排序 时间复杂度为O(N)
def maxgap(array):
if len(array) < 2 or array is None:
return array
smax = max(array)
smin = min(array)
if smax == smin:
return 0
size = len(array)
min_size = [None] * (size + 1)
max_size = [None] * (size + 1)
bool_size = [False] * (size + 1)
for i in range(len(array)):
bid = backsize(array[i], size, smax, smin)
max_size[bid] = array[i] if max_size[bid] is None or max_size[bid] < array[i] else max_size[bid]
min_size[bid] = array[i] if min_size[bid] is None or min_size[bid] > array[i] else min_size[bid]
bool_size[bid] = True
res = 0
print(min_size, max_size)
lastmax = max_size[0]
for i in range(len(min_size)):
if bool_size[i]:
res = max(res, max_size[i] - lastmax)
lastmax = max_size[i]
return res
def backsize(num, size, smax, smin):
return (num - smin) * size // (smax - smin)
def test_max():
array = [4, 2, 1, 7, 5, 3, 2, 4, 17]
array2 = [4, 4, 1]
print(maxgap(array))
print(maxgap(array2))
"""
"""
数组结构实现大小固定的队列和栈
class Stack(object):
def __init__(self, size):
self.stack = [None] * size
self.size = size
self.len = 0
def push(self, value):
if self.len >= self.size:
print('栈已经满了')
else:
self.stack[self.len] = value
self.len += 1
def get_min(self):
if self.len == 0:
return None
return self.stack[self.len-1]
def pop(self):
if self.len < 0:
print('无数据可以出栈')
else:
self.len -= 1
value = self.stack[self.len]
# print(value)
return value
def test_stack():
stack = Stack(3)
stack.push(7)
stack.push(8)
stack.push(6)
stack.push(77)
stack.pop()
stack.pop()
stack.pop()
class Queue(object):
def __init__(self, size):
self.queue = [None] * size
self.size = size
self.end = 0
self.start = 0
self.index = 0
def push(self, value):
if self.index < self.size:
print(self.index)
self.queue[self.end] = value
self.end = 0 if self.end + 1 == self.size else self.end + 1
self.index += 1
else:
print('队列已满')
def pop(self):
if self.index > 0:
print(self.queue[self.start])
self.start = 0 if self.start + 1 == self.size else self.start + 1
self.index -= 1
else:
print('队列无数据')
def test_queue():
queue = Queue(3)
queue.push(5)
queue.push(4)
queue.push(3)
queue.push(2)
queue.pop()
queue.pop()
queue.pop()
queue.pop()
class Steak2():
def __init__(self, size):
self.stack3 = Stack(size)
self.stack4 = Stack(size)
def push(self, value):
self.stack3.push(value)
if self.stack3.get_min() is None or value < self.stack3.get_min() :
self.stack4.push(value)
else:
self.stack4.push(self.stack3.get_min())
def pop(self):
self.stack4.pop()
return self.stack3.pop()
def get_min(self):
return self.stack4.get_min()
def test_steak2():
steak = Steak2(3)
steak.push(5)
steak.push(4)
steak.push(3)
steak.pop()
steak.pop()
print(steak.get_min())
"""
"""
矩阵转圈打印
def order_print(array):
tR = 0
tC = 0
dR = len(array) - 1
dC = len(array[0]) - 1
while tR <= dR and tC <= dC:
print_edge(array, tR, tC, dR, dC)
tR += 1
tC += 1
dR -= 1
dC -= 1
def print_edge(array, tR, tC, dR, dC):
if tC == dC:
while tR <= dR:
print(array[tR][tC], end=' ')
tR += 1
elif tR == dR:
while tC <= dC:
print(array[tR][tC], end=' ')
tC += 1
else:
curR = tR
curC = tC
while tC < dC:
print(array[tR][tC], end=' ')
tC += 1
while tR < dR:
print(array[tR][tC], end=' ')
tR += 1
while dC > curC:
print(array[dR][dC], end=' ')
dC -= 1
while dR > curR:
print(array[dR][dC], end=' ')
dR -= 1
while dC > curC:
print(array[dR][dC], end=' ')
dC -= 1
def test_order():
array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
array2 = [[1, 2, 3, 4]]
array3 = [[1], [2], [3]]
# order_print(array)
order_print(array2)
order_print(array3)
"""
"""
将矩阵的数字转换90度
1 2 4 1
4 5 5 2
def rotate(array):
tR = 0
tC = 0
dR = len(array) - 1
dC = len(array[0]) - 1
while tR < dR or tC < dC:
rotate_edge(array, tR, tC, dR, dC)
tR += 1
tC += 1
dR -= 1
dC -= 1
def rotate_edge(array, tR, tC, dR, dC):
size = dC - tC
for i in range(size):
time = array[tR][tC+i]
print(i)
array[tR][tC+i] = array[dR-i][tC]
array[dR-i][tC] = array[dR][dC-i]
array[dR][dC-i] = array[tR+i][dC]
array[tR+i][dC] = time
def test_rotate():
array = [[1, 2, 3], [3, 4, 5], [6, 7, 8]]
rotate(array)
print(array)
"""
"""
之字形打印矩阵
"""
def print_zhi(array):
tR = 0
tC = 0
dR = 0
dC = 0
endR = len(array) - 1
endC = len(array[0]) - 1
bool_1 = True
while tR <= endR and dC <= endC:
print_level(array, tR, tC, dR, dC, bool_1)
tR = 0 if tC < endC else tR + 1
tC = tC + 1 if tC < endC else tC
dC = 0 if dR < endR else dC + 1
dR = dR + 1 if dR < endR else dR
bool_1 = False if bool_1 is True else True
def print_level(array, tR, tC, dR, dC, bool_1):
if bool_1 is True:
while dR >= tR and dC <= tC:
print(array[dR][dC])
dR -= 1
dC += 1
else:
while tR <= dR and tC >= dC:
print(array[tR][tC])
tR += 1
tC -= 1
def test_level():
array = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
print_zhi(array)
if __name__ == '__main__':
# test_bubble()
# test_select()
# test_insert()
# test_quick()
# test_merge()
# test_heap()
# test_max()
# test_stack()
# test_queue()
# test_steak2()
# test_order()
# test_rotate()
test_level() |
8880877537ac0e945bde820806c56cb008125b9f | leox64/ADT | /Array.py | 1,087 | 3.78125 | 4 | #array
class Array:
def __init__(self,n):
self.data=[]
for i in range(n):
self.__data.append(None)
def get_length(self):
return len(self.__data)
def set_item(self,index,value):
if index >= 0 and index < len(self.__data):
self.__data[index] = value
else:
print("Fuera de rango")
def get_item (self,index):
if index >= 0 and index < len(self.__data):
return self.__data[index]
else:
print("Fuera de rango")
def clearing (self,valor):
for index in range(len(self.__data)):
self.__data[index] = valor
def to_string(self):
print(self.__data)
#main
def main():
arreglo = Array(10)
arreglo.to_string()
print(f"El tamaño es de {arreglo.get_length()}")
arreglo.set_item(1,10)
arreglo.to_string()
arreglo.set_item(12,10)
print (f"El elemento 1 es {arreglo.get_item(1)}")
arreglo.get_item(20)
arreglo.clearing(5)
arreglo.to_string()
main()
|
ffc2780064c17ff9d45e2b817fbd0c4208c330a9 | Anthonywilde1/pythonpractice | /practice.py | 814 | 3.828125 | 4 | # Fibonacci series:
# the sum of two elements defines the next
a, b = 0, 1
while a < 1000:
print(a)
a, b = b, a+b
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
name = letters[0] + letters[13] + letters[19] + letters[7] + letters[14] + letters[13] + letters[-2]
print(name)
x = int(input("Please enter an integer: "))
# input requires user input seems like stating the variable required
#outside the brackets, in this case int for integer.
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
# Measure some strings:
words = ['cat', 'window', 'defenestrate', 'Wowowowowowowow']
for w in words:
print(w, len(w)) |
91764a0218ca3632eac11064e1312c30e1ead470 | SrCarlangas1/Practica7 | /Exercici_06.py | 233 | 3.828125 | 4 | print "Dime un nombre"
prime=raw_input()
pepe=list(prime)
print pepe
print "Dime un caracter"
susti=raw_input()
if susti in pepe:
print "El caracter esta en tu nombre"
else:
print "El caracter no esta en tu nombre"
|
c3bc1f9db4fd2ab9b4ba40ce7e8d69b0da87fd42 | lior20-meet/meet2018y1lab2 | /MEETinTurtle.py | 972 | 4.15625 | 4 |
import turtle
turtle.penup() #Pick up the pen so it doesn’t
#draw
turtle.goto(-200,-100) #Move the turtle to the
#position (-200, -100)
#on the screen
turtle.pendown() #Put the pen down to start
#drawing
#Draw the M:
turtle.goto(-200,-100+200)
turtle.goto(-200+50,-100)
turtle.goto(-200+100,-100+200)
turtle.goto(-200+100,-100)
turtle.penup()
turtle.goto (-50,100)
turtle.pendown()
turtle.goto(-50,-100)
turtle.goto(50,-100)
turtle.penup()
turtle.goto(-50,100)
turtle.pendown()
turtle.goto(50,100)
turtle.penup()
turtle.goto(-50,0)
turtle.pendown()
turtle.goto(50,0)
turtle.penup()
turtle.goto(100,100)
turtle.pendown()
turtle.goto(100,-100)
turtle.goto(200,-100)
turtle.penup()
turtle.goto(100,100)
turtle.pendown()
turtle.goto(200,100)
turtle.penup()
turtle.goto(100,0)
turtle.pendown()
turtle.goto(200,0)
turtle.penup()
turtle.goto(250,100)
turtle.pendown()
turtle.goto(350,100)
turtle.goto(300,100)
turtle.goto(300,-100)
|
7235257c51e5a1af67454306e76c5e58ffd2a31c | VeronikaA/user-signup | /crypto/helpers.py | 1,345 | 4.28125 | 4 | import string
# helper function 1, returns numerical key of letter input by user
def alphabet_position(letter):
""" Creates key by receiving a letter and returning the 0-based numerical position of that letter in the alphabet, regardless of case."""
alphabet = string.ascii_lowercase + string.ascii_uppercase
alphabet1 = string.ascii_lowercase
alphabet2 = string.ascii_uppercase
i = 0
for c in alphabet:
key = 0
c = letter
if c in alphabet1:
ascii_value = ord(c)
c = ascii_value
key = (c - 97) % 26
elif c in alphabet2:
ascii_value = ord(c)
c = ascii_value
key = (c - 65) % 26
elif c not in alphabet:
key = ord(c)
return key
# helper funtion 2
def rotate_character(char, rot):
"""Receives a character 'char', and an integer 'rot'.
Returns a new char, the result of rotating char by rot number of places to the right."""
a = char
a = alphabet_position(a)
rotation = (a + rot) % 26
if char in string.ascii_lowercase:
new_char = rotation + 97
rotation = chr(new_char)
elif char in string.ascii_uppercase:
new_char = rotation + 65
rotation = chr(new_char)
elif char == char:
rotation = char
return rotation
|
ed3c20641bdad8b23f85153994fef6345af81de5 | echibe/Projects | /Python/Scrape.py | 660 | 3.796875 | 4 | #Elliot Chibe
#September 15th, 2016
#Given a YouTube video link this will output the title, description, and user of the video
#Uses BeautifulSoup and requests for Python
import requests
from bs4 import BeautifulSoup
url = raw_input("What is the URL: ")
r = requests.get(url)
soup = BeautifulSoup(r.content, "lxml")
titles = soup.find_all("title")
print("")
print ("-----Title:")
for t in titles:
print t.text
print("")
print ("-----Description:")
desc = soup.find_all("div", {"id": "watch-description-text"})
for d in desc:
print d.text
print("")
print ("-----User:")
user = soup.find_all("div", {"class": "yt-user-info"})
for u in user:
print u.text
|
a87fe2d7477098d5cb41c018fccc47b787b1ff8d | rlazarev/powerunit | /powerunit.py | 1,048 | 3.65625 | 4 | #!/usr/bin/env python
# Import the modules to send commands to the system and access GPIO pins.
from subprocess import call
import RPi.GPIO as GPIO
from time import sleep
# Map PinEleven and PinThirteen on the Power.unit PCB to chosen pins on the Raspberry Pi header.
# The PCB numbering is a legacy with the original design of the board.
PinEleven = 11
PinThirteen = 13
GPIO.setmode(GPIO.BOARD) # Set pin numbering to board numbering.
GPIO.setup(PinEleven, GPIO.IN) # Set up PinEleven as an input.
GPIO.setup(PinThirteen, GPIO.OUT, initial=1) # Setup PinThirteen as output for the LED.
while (GPIO.input(PinEleven) == True): # While button not pressed
GPIO.wait_for_edge(PinEleven, GPIO.RISING) # Wait for a rising edge on PinSeven
sleep(0.1); # Sleep 100ms to avoid triggering a shutdown when a spike occured
if (GPIO.input(PinEleven) == True):
GPIO.output(PinThirteen,0) # Bring down PinThirteen so that the LED will turn off.
call('poweroff', shell=False) # Initiate OS Poweroff
else:
call('reboot', shell=False) # Initiate OS Reboot
|
3f4b48b07ce6785b6a30ab7651d62ab2b730adc3 | MBScott1997-zz/Python_Projects | /Scott_MarvelMart.py | 7,535 | 3.640625 | 4 | '''
Python Project - Marvel Mart Project
Michael Scott
Due: March 10, 2020
'''
import csv
import numpy as np
import pandas as pd
import collections
from collections import defaultdict
pd.set_option('display.float_format', lambda x: '%.3f' % x)
#Part 1: Cleaning the data
#Cleaning ints out of Country
mart = pd.read_csv('DataSamples/Marvel_Mart_Sales_clean.csv', delimiter=',')
for index, row in mart.iterrows():
try:
result = float(row.loc["Country"]) #if it can be converted to a float that's bad
mart.loc[float(index), "Country"] = "NULL" #so change it to null
except:
1==1
#cleaning blanks out of item type & priority
mart["Item Type"].fillna("NULL", inplace=True) #fill blanks with null
mart["Order Priority"].fillna("NULL", inplace=True) #fill blanks with null
#cleaning strings from order id
for index, row in mart.iterrows():
try:
placeholder = row.loc["Order ID"] * 2 #if it can be multiplied by two that's good
except:
mart.loc[int(index), 'Order ID'] = 0 #if it can't change it to zero
# Part 2: General Statistics
#1A
print("\n-2.A-")
print("Countries Most Sales:")
data = mart.groupby(["Country"],sort=True)["Units Sold"].sum().reset_index() #group by country and sum units sold
data = data.sort_values(by = ['Units Sold'], ascending=[False]) #sort units sold sums
topTenSales = data.head(10) #top ten values
print(topTenSales)
print("\nThe country we should build our shipping center is Cape Verde because they are our third biggest customer by Units Sold")
#1B
print("\n-2.1.B-")
offline = collections.Counter() #counter variable
with open('DataSamples/Marvel_Mart_Sales_clean.csv') as input_file:
for row in csv.reader(input_file, delimiter=','):
offline[row[3]] += 1 #everytime "offline" is in row[3] count it
print('Number of offline sales: %s' % offline['Offline'])
online = collections.Counter() #counter variable
with open('DataSamples/Marvel_Mart_Sales_clean.csv') as input_file:
for row in csv.reader(input_file, delimiter=','):
online[row[3]] += 1 #everytime "online" is in row[3] count it
print('Number of online sales: %s' % online['Online'])
if online['Online'] > offline['Offline']: #if more online sales
print("We have more online sales") #print there's more online sales
else:
print("We have more offline sales") #if not, tell us there's more offline sales
#C
print("\n-2.1.C-")
mart['year'] = pd.DatetimeIndex(mart['Order Date']).year #adding a year column to make the rest easier
print("Best Years:")
data = mart.groupby(["year"],sort=True)["Total Profit"].sum().reset_index() #group by year and sum total profits
data = data.sort_values(by = ['Total Profit'], ascending=[False]) #sort total profit desc
data1 = data.head(3) #top 3 values
print(data1)
print("\nWorst Years:")
data = mart.groupby(["year"],sort=True)["Total Profit"].sum().reset_index() #group by year and sum total profits
data = data.sort_values(by = ['Total Profit'], ascending=[True]) #sort total profit asc
data2 = data.head(3) #top (bottom) three values
print(data2)
print("\nWe sold the most in 2011")
with open('DataSamples/Marvel_Mart_Rankings.txt', 'w+') as reader:
reader.write("-2.A-")
reader.write("\nCountries Most Sales: ")
reader.write("\n")
topTenSales.to_string(reader)
reader.write("\n")
reader.write("\nThe country we should build our shipping center is Cape Verde because they are our third biggest customer by Units Sold")
reader.write("\n")
reader.write("\n-2.1.B-")
reader.write("\n")
reader.writelines(str(onlinePrint))
reader.write("\n")
reader.writelines(str(offlinePrint))
reader.write("\n")
reader.write("We have more online sales")
reader.write("\n")
reader.write("\n-2.1.C-")
reader.write("\n")
data1.to_string(reader)
reader.write("\n")
reader.write("\n")
data2.to_string(reader)
reader.write("\n")
reader.write("\nWe sold the most in 2011")
#making a nicely formatted .txt file :)
#2A
print("\n-2.2.A-")
print("Sums:")
totalUnits = mart['Units Sold'].sum() #summing units sold
sum1 = "Units Sold: " + str(totalUnits) #print var
print(sum1)
totalUnits = mart['Unit Cost'].sum()
sum2 = "Unit Cost: " + str(totalUnits)
print(sum2)
totalUnits = mart['Total Revenue'].sum()
sum3 = "Total Revenue: " + str(totalUnits)
print(sum3)
totalUnits = mart['Total Cost'].sum()
sum4 = "Total Cost: " + str(totalUnits)
print(sum4)
totalUnits = mart['Total Profit'].sum()
sum5 = "Total Profit: " + str(totalUnits)
print(sum5)
print("\nAverages:")
totalUnits = mart['Units Sold'].mean() #averaging column
avg1 = "Units Sold: " + str(totalUnits) #print variable
print(avg1)
totalUnits = mart['Unit Cost'].mean()
avg2 = "Unit Cost: " + str(totalUnits)
print(avg2)
totalUnits = mart['Total Revenue'].mean()
avg3 = "Total Revenue: " + str(totalUnits)
print(avg3)
totalUnits = mart['Total Cost'].mean()
avg4 = "Total Cost: " + str(totalUnits)
print(avg4)
totalUnits = mart['Total Profit'].mean()
avg5 = "Total Profit: " + str(totalUnits)
print(avg5)
print("\nMaximums:")
totalUnits = mart['Units Sold'].max() #finding the max value from the column
max1 = "Units Sold: " + str(totalUnits) #print variable
print(max1)
totalUnits = mart['Unit Cost'].max()
max2 = "Unit Cost: " + str(totalUnits)
print(max2)
totalUnits = mart['Total Revenue'].max()
max3 = "Total Revenue: " + str(totalUnits)
print(max3)
totalUnits = mart['Total Cost'].max()
max4 = "Total Cost: " + str(totalUnits)
print(max4)
totalUnits = mart['Total Profit'].max()
max5 = "Total Profit: " + str(totalUnits)
print(max5)
with open('DataSamples/Marvel_Mart_Calc.txt', 'w+') as reader:
reader.write("-3-")
reader.write("\n")
reader.write("Sum: ")
reader.write("\n")
reader.writelines(sum1)
reader.write("\n")
reader.writelines(sum2)
reader.write("\n")
reader.writelines(sum3)
reader.write("\n")
reader.writelines(sum4)
reader.write("\n")
reader.writelines(sum5)
reader.write("\n")
reader.write("Averages: ")
reader.write("\n")
reader.writelines(avg1)
reader.write("\n")
reader.writelines(avg2)
reader.write("\n")
reader.writelines(avg3)
reader.write("\n")
reader.writelines(avg4)
reader.write("\n")
reader.writelines(avg5)
reader.write("\n")
reader.write("Maximums: ")
reader.write("\n")
reader.writelines(max1)
reader.write("\n")
reader.writelines(max2)
reader.write("\n")
reader.writelines(max3)
reader.write("\n")
reader.writelines(max4)
reader.write("\n")
reader.writelines(max5)
# making another nicely formatted .txt for you :)
#Part 3: Cross-Reference Statistics
#1
print("\n-3.1.A")
dictOfLists = {} #empty dict
for i in mart.Region.unique(): #for each unique region
dictOfLists[i] = mart[mart.Region == i].Country.unique().tolist() #put the corresponding unique country into a list and the list as a value to the region key
df=pd.DataFrame.from_dict(dictOfLists,orient='index').transpose() #dict to dataframe
df.to_csv('DataSamples/Countries_By_Region.csv', encoding='utf-8', index=False) #dataframe to csv
for i in dictOfLists: #printing the keys of the dict of lists
print(i) #printing the regions line by line
|
237cbd779d44ac9cdc04edd467647769c4781c97 | andxu282/poker_engine | /models/rank.py | 510 | 3.546875 | 4 | """
The rank of the card (2 through Ace). The rank is represented by a single character string (the number itself for 2-9
and T, J, Q, K, A for 10, Jack, Queen, King, and Ace respectively.
"""
from helpers.constants import rank_dict
class Rank():
def __init__(self, rank_str):
self.rank_str = rank_str
def __str__(self):
return rank_dict[self.rank_str]
def __eq__(self, other):
return self.rank_str == other.rank_str
def get_rank(self):
return self.rank_str |
22f0b036d436b9d8b3021b349c612f7322720db3 | sayalijo/my_prog_solution | /hacker_rank/Algorithms/Warmup/min_max_sum/min_max_sum.py | 243 | 3.796875 | 4 | #!/bin/python3
import sys
def miniMaxSum(arr):
# Complete this function
x = sum(arr)
print (x-(max(arr)), (x-(min(arr))))
if __name__ == "__main__":
arr = list(map(int, input().strip().split(' ')))
miniMaxSum(arr)
|
ff2c1fc5723a4c3309b97226e849bd0c7f824210 | sayalijo/my_prog_solution | /geeks_for_geeks/Algorithms/Searching/binary_search/binary_search.py | 566 | 4.0625 | 4 | def binary_search(arr, x, start_index, end_index):
if end_index >= 1:
mid_index = start_index + (end_index - start_index)//2
if arr[mid_index] == x:
return mid_index
elif arr[mid_index] > x:
return binary_search(arr, x,start_index, mid_index - 1)
else:
return binary_search(arr, x, mid_index+1, end_index)
else:
return -1
x = int(input())
arr = list(map(int, input().split(" ")))
result = binary_search(arr, x, 0, len(arr)-1)
if result != -1:
print("Element found at position", result)
else:
print("Element not present in the given array")
|
c4d7076b3ef58086aa5b0d53c3168d5292e57836 | sayalijo/my_prog_solution | /geeks_for_geeks/Arrays/arrangements/move_all_zeros_end/move_all_zeros_end.py | 368 | 3.78125 | 4 | # arr[] = {1, 2, 0, 0, 0, 3, 6}
# Output : 1 2 3 6 0 0 0
def rearrange(ar):
i,j = -1, 0
for j in range(len(ar)):
if ar[j] > 0:
i += 1
ar[i], ar[j] = ar[j], ar[i]
return ar
array = list(map(int, input("Enter your array:\t").split(" ")))
result = rearrange(array)
print("Now your array is:\n", " ".join(map(str,result)))
|
b5fe57756695c05b2f96eb62de309d88a45fb40f | sayalijo/my_prog_solution | /hacker_rank/Algorithms/Implementation/manasa_and_stones/manasa_and_stones.py | 753 | 3.515625 | 4 | #!/bin/python3
import sys
def stones(n, a, b):
a,b = min(a,b), max(a,b)
diff = b - a
stones = n - 1
current_stone = a * stones
max_stone = b * stones
#result = []
if a == b:
#result.append(current_stone)
yield current_stone
return result
else:
while current_stone <= max_stone:
#result.append(current_stone)
yield current_stone
current_stone += diff
#return result
if __name__ == "__main__":
T = int(input().strip())
for a0 in range(T):
n = int(input().strip())
a = int(input().strip())
b = int(input().strip())
result = stones(n, a, b)
print(" ".join(map(str, result)))
|
4db6f63da2c03590a2765d346707db7667d82d36 | jaykumarvaghela/python-for-fun | /printfunction.py | 138 | 3.640625 | 4 | n = int(input())
list = []
i = 1
while (i <= n):
list.append(i)
i = i + 1
for j in range(n):
print(list[j], end="")
|
c3607404f5ac3cc66c9a3222fd122c7e05789569 | k5tuck/Digital-Crafts-Classes | /end_of_lesson_exercises/lrg_exercises/python/lrg_exercise2.py | 970 | 3.96875 | 4 |
num = int(input("What number would you like to factor?: "))
if num % 2 == 0:
print("%i is a positive number" %num)
even_list = []
p = 1
while p <= num:
if num % p == 0:
q = num / p
even_list.append(p)
even_list.append(int(q))
p += 1
else:
p += 1
print("These are the factors for %i:" %num)
dup_list = set(even_list)
even_sorted = sorted(dup_list)
for i in range(len(even_sorted)):
print(even_sorted[i])
else:
print("%i is a negative number" %num)
odd_list = []
p = 1
while p <= num:
if num % p == 0:
q = num / p
odd_list.append(p)
odd_list.append(int(q))
p += 1
else:
p += 1
print("These are the factors for %i:" %num)
odd_dup_list = set(odd_list)
odd_sorted = sorted(odd_dup_list)
for i in range(len(odd_sorted)):
print(odd_sorted[i]) |
1b658c4f93e2273d593ad60070c170d88b147ce0 | k5tuck/Digital-Crafts-Classes | /python/wk_1/comparisons1.py | 249 | 3.90625 | 4 | my_number = 29
compare1 = 18
compare2 = 7
compare3 = 29
if my_number == compare1:
print(True)
elif my_number == compare2:
print(True)
elif my_number == compare3:
print(True)
else:
print("This number is equal to none of the above") |
bcde179facbf825efb934e779b2257e2e608d211 | k5tuck/Digital-Crafts-Classes | /end_of_lesson_exercises/small_exercises/python/wk2_exercise5.py | 254 | 3.875 | 4 | # Exercise 5
numbers = [-23, -52, 0, -1.6, 56, 231, 86, 20, 11, 17, 9]
for num in numbers:
if num > 0:
print(num)
# Exercise 6
new_numbers = []
for num in numbers:
if num > 0:
new_numbers.append(num)
print(sorted(new_numbers))
|
b775e2235930821da179884ff859d592d3d5ada7 | k5tuck/Digital-Crafts-Classes | /end_of_lesson_exercises/small_exercises/python/wk2_exercise2.py | 246 | 4.09375 | 4 |
numbers = [6,7,8,4,312,109,878]
biggest = 0
for num in numbers:
if biggest < num:
biggest = num
else:
pass
print(biggest)
#Alternative using sort method
numbers.sort()
print(numbers[-1])
#Alternative
print(max(numbers)) |
fe219eb50f78b4c717b8a4a17567073ddb435621 | k5tuck/Digital-Crafts-Classes | /end_of_lesson_exercises/small_exercises/python/exercise3.py | 310 | 3.9375 | 4 | print("Please fill in the blanks below:\n")
print("____(name)____ loves ____(activity)____ whenever possible!\n")
name = input("What is your name? ")
activity = input("What is %s's favorite activity to do whenever they get the opportunity? " %name)
print("%s loves %s whenever possible!" %(name, activity)) |
9bdbbea001d9ddbc0c7330ab7b71fc575ac467ce | sankarmanoj/CTE-Python | /second/rand.py | 743 | 3.78125 | 4 | import random
import copy
randomArray = [random.randint(0,100) for x in range(10)]
print "Random Array =",randomArray
#Sort Array
randomArray.sort()
print "Sorted Array = ",randomArray
#Largest Element
print "Largest Element In Array = ",max(randomArray)
#Smallest Element
print "Smallest Element in Array = ",min(randomArray)
#Create New Array From the Existing Array
newArray = randomArray
anotherArray = newArray[:]
# anotherArray = copy.deepcopy(randomArray)
anotherArray = list(randomArray)
#Update Starting Value
newArray[0]=666
#Print Old Array
print "randomArray =",randomArray," newArray = ",newArray
#Update Starting Value
anotherArray[1]=333
#Print Old Array
print "randomArray =",randomArray," anotherArray = ",anotherArray
|
7ec2ef1c7ecdc53dadc8c11a3a57fd6da40c1920 | sankarmanoj/CTE-Python | /third/third.py | 197 | 3.859375 | 4 | a = range(3)
b = range(10,13)
c = []
for x in a:
for y in b:
c.append((x,y))
print c
c = [(x,y) for x in a for y in b]
print c
import itertools
c = itertools.product(a,b)
print list(c)
|
0d81f91728bed2c804208f94df5311a26d27df1e | sankarmanoj/CTE-Python | /recur.py | 172 | 3.703125 | 4 | def insertion(a):
if len(a)==2:
if a[0]>a[1]:
a[0],a[1] = a[1],a[0]
return a
else:
return a
|
c5366570917b06ef617db8abd9c478cbf2c79628 | JohnVonNeumann/selenium-py | /custom_logger.py | 892 | 3.53125 | 4 | import inspect #allows users to get info from live objects
import logging
# the purpose of this file is to act as something of a module that we can
# call when needed, it sets itself a name, file and other params.
def customLogger(logLevel):
# Gets the name of the class / method from where this method is called
loggerName = inspect.stack()[1][3]
logger = logging.getLogger(loggerName)
# By default, log all messages
logger.setLevel(logging.DEBUG)
fileHandler = logging.FileHandler("{0}.log".format(loggerName), mode='w')
# gives the log file its own named based on method calling it
fileHandler.setLevel(logLevel)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p')
fileHandler.setFormatter(formatter)
logger.addHandler(fileHandler)
return logger
|
01412ba71dea158f097e6da5e831c0c7cea44d50 | iabok/sales-tracker | /web/sales_app/apps/helpers/processProductSales.py | 2,650 | 3.609375 | 4 | '''
Process the product sales fields
'''
from collections import namedtuple
import operator
class ProductSales:
"""
Product process class
"""
def __init__(self, product_name, quantity, price):
'''
constructor
'''
self.product_name = product_name
self.quantity = quantity
self.price = price
self.fields = None
self.productRecord = namedtuple('Product', 'name, quantity, \
unit_price, station_id, sales_date, sales')
def mapFields(self):
"""
process the fields
"""
if not isinstance(self.product_name, list) \
or not isinstance(self.quantity, list) \
or not isinstance(self.price, list):
return False
self.fields = zip(self.product_name, self.quantity, self.price)
def getMapFields(self):
"""
get the fields
"""
return self.fields
def totalProductSales(self):
"""
Returns the total of all product sales
Returns an integer
"""
if not isinstance(self.quantity, list) \
or not isinstance(self.price, list):
return False
quantity = list(map(int, self.quantity))
price = list(map(int, self.price))
return sum(map(lambda x: operator.mul(*x), zip(quantity, price)))
def getProductInsertFields(self, missingFields):
"""
Inserts the missing fields and cleans up the product sales \
ready for insertion
missingFields = [sales_id, station_id, sales_date]
"""
if not isinstance(missingFields, list):
return False
self.mapFields()
if self.getMapFields() is not None:
upackedFields = list(map(list, self.getMapFields()))
return map(lambda field: field + missingFields, upackedFields)
return False
def getProudctInsertData(self, missingFields, model):
"""
returns a namedtuple for database insertion
"""
listOfFields = []
fields = self.getProductInsertFields(missingFields)
for product in map(self.productRecord._make, list(fields)):
listOfFields.append(model['productSales'](
product_id=product.name,
quantity=product.quantity,
unit_price=product.unit_price,
station_id=product.station_id,
sales_date=product.sales_date,
sales=product.sales))
return listOfFields
|
272adc9f1c787a36e7702e6ee2caa36ae8a547d8 | RagingTiger/MontyHallProblem | /montyhall.py | 4,080 | 4.1875 | 4 | #!/usr/bin/env python
# libs
import random
# classes
class MontyHall(object):
"""A class with various methods for simulating the Monty Hall problem."""
def lmad(self):
"""Interactive version of Monty Hall problem (i.e. Lets Make A Deal)."""
# start game
print('Let\'s Make A Deal')
try:
# how many doors
ndoors = int(input('How many doors: '))
# which door would you like
first_choice = int(input('Choose one door out of {}: '.format(ndoors)))
# now the host calculates
results = self.simulate(ndoors, first_choice)
# would you like to switch
switch = input('Would you like to switch doors [y/n]: ')
# converst switch to true/false
switch = True if switch in {'y', 'Y', 'yes', 'Yes', 'YES'} else False
# check switch
final_choice = results['second_choice'] if switch else first_choice
# prepare results
results['final_choice'] = final_choice
# return results
return results
except EOFError or KeyboardInterrupt:
# do nothing but end silently
pass
@staticmethod
def predict(ndoors):
"""Calculate the predicted probabilities of no switch vs. switch.
Args:
ndoors (int): The number of doors to use.
Returns:
ndoors (int): The number of doors used.
noswitch (float): Probability of winning if players does not switch.
switch (float): Probability of winning if player switches.
"""
# calculate probabilities
no_switch = 1.0 / float(ndoors)
switch = 1.0 - no_switch
# return results dictionary
return {
'ndoors': ndoors,
'noswitch': no_switch,
'switch': switch
}
@staticmethod
def simulate(ndoors, first_choice):
"""Non-interactive version of Monty Hall problem.
Args:
ndoors (int): The number of doors to use.
first_choice (int): The first door the player chooses.
Returns:
first_choice (int): The first door the player chooses.
second_choice (int): The second door the player can switch to.
car (int): The door hiding the car.
"""
# get random number in range of ndoors (representing the car to be won)
car = random.randint(1, ndoors)
# get second_choice (i.e. 2nd door to choose from)
if first_choice != car:
second_choice = car
else:
while True:
second_choice = random.randint(1, ndoors)
if second_choice != car:
break
# return results
return {
'first_choice': first_choice,
'second_choice': second_choice,
'car': car
}
def experiment(self, ndoors, first_choice, ngames):
"""Run multiple games of Monty Hall problem.
Args:
ndoors (int): The number of doors to use.
first_choice (int): The first door the player chooses.
ngames (int): The number of games to run.
Returns:
noswitch (float): Experimental percent of winning without switching.
switch (float): Experimental percent of winning with switching.
"""
# setup initial values
switch, noswitch = 0, 0
# setup loop
for _ in range(ngames):
# get results of game
game = self.simulate(ndoors, first_choice)
# update statistics
if game['first_choice'] == game['car']:
noswitch += 1.0
else:
switch += 1.0
# calculate results
return {
'noswitch': noswitch / (switch + noswitch),
'switch': switch / (switch + noswitch)
}
# executable only
if __name__ == '__main__':
# libs
import fire
# bang bang
fire.Fire(MontyHall)
|
802f19a0bbe365b4fba2cb6c6d3fbba1db803066 | qilinchang70/oh-yeah | /028 星座.py | 1,551 | 3.921875 | 4 | n=eval(input())
for i in range(0,n,1):
[month,date]= input().split()
month= eval(month)
date= eval(date)
if month==1 and date >=21:
print("Aquarius")
elif month==2 and date <=19:
print("Aquarius")
elif month==2 and date >19:
print("Pisces")
elif month==3 and date <=20:
print("Pisces")
elif month==3 and date >20:
print("Aries")
elif month==4 and date <=19:
print("Aries")
elif month==4 and date >=20:
print("Taurus")
elif month==5 and date <=20:
print("Taurus")
elif month==5 and date >=21:
print("Gemini")
elif month==6 and date <=21:
print("Gemini")
elif month==6 and date >21:
print("Cancer")
elif month==7 and date <=22:
print("Cancer")
elif month==7 and date >=23:
print("Leo")
elif month==8 and date <=22:
print("Leo")
elif month==8 and date >=23:
print("Virgo")
elif month==9 and date <=22:
print("Virgo")
elif month==9 and date >=23:
print("Libra")
elif month==10 and date <=23:
print("Libra")
elif month==10 and date >=24:
print("Scorpio")
elif month==11 and date <=21:
print("Scorpio")
elif month==11 and date >=22:
print("Sagittarius")
elif month==12 and date <=20:
print("Sagittarius")
elif month==12 and date >=21:
print("Capricorn")
elif month==1 and date <=20:
print("Capricorn")
|
c47734a966d5996428b2ae19beeb8a396a3c734f | Gouenji/Dynamic-Programming | /Weighted Job Scheduling Dynamic Programming.py | 1,699 | 3.625 | 4 | def doNotOverlap(job1,job2):
if job1[0] < job2[0] and job2[1] < job1[1] :
return 0
if job2[0] < job1[0] and job1[1] < job2[1] :
return 0
if job1[1] > job2[0] and job1[0]<job2[0]:
return 0
if job2[1] > job1[0] and job2[0]<job1[0]:
return 0
else:
return 1
from operator import itemgetter
def WeightedJobScheduling(Jobs):
sorted(Jobs,key=itemgetter(1))
temp_array=[]
temp_locator=[]
for k in range(len(Jobs)):
temp_array.append(Jobs[k][2])
temp_locator.append(0)
i=1
j=0
while(i<len(Jobs)):
while(i!=j):
temp_tracker=temp_array[i]
if doNotOverlap(Jobs[i],Jobs[j]):
temp_array[i]=max(temp_array[i],temp_array[j]+Jobs[i][2])
if temp_array[i] != temp_tracker:
temp_locator[i]=j
j+=1
i+=1
j=0
maxCost=max(temp_array)
index=temp_array.index(maxCost)
temp_maxCost=maxCost
jobsindices=[]
jobs=[]
while temp_maxCost>0:
jobsindices.append(index)
temp_maxCost-=Jobs[index][2]
index=temp_locator[index]
jobsindices.reverse()
for itr in range(len(jobsindices)):
jobs.append(Jobs[jobsindices[itr]])
return jobs,maxCost
Jobs=[]
n=int(raw_input("Enter the No of Jobs:\n"))
print "Enter jobs Start-Time End-Time Cost"
for i in range(n):
jobs=map(int,raw_input().strip().split(" "))
Jobs.append(jobs)
jobs,maxCost = WeightedJobScheduling(Jobs)
for itr in range(len(jobs)):
print "Start Time: " + str(jobs[itr][0]) + " End Time: " + str(jobs[itr][1]) + " Cost: "+str(jobs[itr][2])
print "Total Cost: "+str(maxCost)
|
1b775b3d85e54f9c236f1a4ba71409e99a4ab1d3 | Gouenji/Dynamic-Programming | /Maximum Sum Increasing Subsequence Dynamic Programming.py | 1,478 | 3.890625 | 4 | print ("Enter the array to find Maximum Sum Increasing Subsequence (space separated)")
a=map(int,raw_input().strip(' ').split(' '))
from copy import copy
def MaximumSumIncreasingSubsequence(array):
max_sum_array=copy(array)
actual_sequence=[]
for i in range(len(array)):
actual_sequence.append(i)
j=0
i=1
while(i<len(array)):
while(j!=i):
temp=max_sum_array[i]
if array[j]<array[i]:
max_sum_array[i]=max(array[i]+max_sum_array[j],max_sum_array[i])
if max_sum_array[i]!=temp:
actual_sequence[i]=j
j+=1
j=0
i+=1
maxSum=max(max_sum_array)
temp_sum=maxSum
position_max_sum=max_sum_array.index(maxSum)
#print actual_sequence
#print max_sum_array
sequence=[]
while(temp_sum > 0):
sequence.append(array[position_max_sum])
temp_sum-=array[position_max_sum]
position_max_sum=actual_sequence[position_max_sum]
sequence.reverse()
print "1.To print Maximum Sum Increasing Subsequence and Max Sum\n2.Return the values of Max Sum and Maximum Sum Increasing Subsequence "
choice=int(raw_input())
if choice == 1:
print "\nMax Sum: "+str(maxSum)
print "Sequence:"
for i in range (len(sequence)):
print " "+str(sequence[i]),
elif choice == 2:
print "Returned"
return sequence,maxSum
MaximumSumIncreasingSubsequence(a)
|
7b709a867ddc325c7f905dcee39dc8a0001ed6b5 | prajwaldhore/pythonlab | /ams.py | 161 | 3.65625 | 4 | x=int(input(' enter the number ' ))
p=(x//10)
q=(x%10)
s=(p//10)
r=(p%10)
z=(s**3+q**3+r**3)
if x==z:
print('amstrong')
else:
print('not')
|
de07a3442ceabc74bbebe758ac77672f8d8441e0 | RiderBR/Desafios-Concluidos-em-Python | /Python/Desafio 002.py | 250 | 3.78125 | 4 | #RiderBR-TEKUBR
dia = int(input("Qual o dia que você nasceu? "))
mes = str(input("Qual o mês de seu nascimento? "))
ano = int(input("Qual o ano de seu nascimento? "))
print("Você nasceu em {} de {} de {}. Estou correto?".format(dia, mes, ano)) |
01113ddaf86fac3d3c169ce261a1789ee2731516 | RiderBR/Desafios-Concluidos-em-Python | /Python/Desafio 045.py | 843 | 3.84375 | 4 | import random
lista = ['Pedra', 'Papel', 'Tesoura']
print('-='*13)
print('''Escolha uma das opções:
[ 1 ] - Pedra
[ 2 ] - Papel
[ 3 ] - Tesoura''')
print('-='*13)
jogador = int(input('Sua escolha: '))
print('-='*13)
print('Vez do computador.')
pc = random.choice(lista)
print('O computador escolheu {}.'.format(pc))
print('-='*13)
if jogador == 1:
if pc == 'Pedra':
print('EMPATE')
elif pc == 'Tesoura':
print('VOCÊ GANHOU')
else:
print('VOCÊ PERDEU.')
elif jogador == 2:
if pc == 'Pedra':
print('VOCÊ GANHOU')
elif pc == 'Papel':
print('EMPATE')
else:
print('VOCÊ PERDEU')
else:
if pc == 'Pedra':
print('VOCÊ PERDEU')
elif pc == 'Papel':
print('VOCÊ GANHOU')
else:
print('EMPATE') |
e6fa51b5a6851f3536f05d31d4ed14d9394e2e9e | wjdghrl11/repipe | /sbsquiz6.py | 418 | 3.6875 | 4 | # 문제 : 99단 8단을 출력해주세요.
# 조건 : 숫자 1 이외의 값을 사용할 수 없습니다. 소스코드를 수정해주세요.
# 조건 : while문을 사용해주세요.
# """
# 출력 양식
# == 8단 ==
# 8 * 1 = 8
# 8 * 2 = 16
# 8 * 3 = 24
# 8 * 4 = 32
# 8 * 5 = 40
# 8 * 6 = 48
# 8 * 7 = 56
# 8 * 8 = 64
# 8 * 9 = 72
# """
# 수정가능 시작
num = int(input("8을 입력해 주세요"))
|
bc1f578d4254a5a6d336acceeb1e0e90bebcdd3a | wjdghrl11/repipe | /sbsquiz5.py | 107 | 3.640625 | 4 | # 반복문을 이용해 1 ~ 10까지 출력해주세요.
num = 1
while num <= 10:
print(num)
num += 1
|
a2b9d9b20dacdbcf9650b924e27b2be4a55bad61 | wjdghrl11/repipe | /quiz8.py | 676 | 3.65625 | 4 | # 1 ~ 10 까지 수 리스트 선언
list1 = [1,2,3,4,5,6,7,8,9,10]
print(list1)
# 리스트 값 짝수만 가져오기
print(list1[0])
print(list1[1])
print(list1[3])
print(list1[5])
print(list1[7])
print(list1[9])
i = 0
while i < 10 :
if list1[i] % 2 == 0 :
print(list1[i])
i += 1
# 리스트에 11,13,15 추가하기
list1.append(11)
list1.append(13)
list1.append(15)
print(list1)
# 리스트의 짝수번째 값 1증가시키기
list1[0] += 1
list1[2] += 1
list1[4] += 1
list1[6] += 1
list1[8] += 1
list1[8] += 1
print(list1)
i = 0
while i < 13 :
if i % 2 == 0 :
list1[i] += 1
i += 1
# 리스트에서 세번째 값 지우기
del list1[2]
print(list1) |
0e509745b1acc82ae4142d6b2daafdfde2861533 | wjdghrl11/repipe | /4.py | 431 | 3.515625 | 4 | # # 삼자택일, 삼지선다
# a = 0
# if a < 0 :
# print("음수")
# elif a == 0 :
# print("0")
# else : # 위에서 조건을 다 끝내고서 맨 마지막
# print("양수")
b = 15
if b < 1 :
print("1보다 작습니다.")
elif b < 3 :
print("3보다 작습니다.")
elif b < 5 :
print("5보다 작습니다.")
elif b < 10 :
print("10보다 작습니다")
else :
print("10보다 크거나 같습니다.") |
714077f21c473536d8f64b6ba9c1f11c968d172b | wonderfullinux/work | /calculator_challenge2.py | 929 | 3.546875 | 4 | #!/usr/bin/env python3
import sys
def calculator(gz):
yn = gz - 0.165 * gz - 5000
if yn <= 0:
ns = 0
elif yn <= 3000:
ns = yn * 0.03
elif yn <= 12000:
ns = yn * 0.1 - 210
elif yn <= 25000:
ns = yn * 0.2 - 1410
elif yn <= 35000:
ns = yn * 0.25 - 2660
elif yn <= 55000:
ns = yn * 0.3 - 4410
elif yn <= 80000:
ns = yn * 0.35 - 7160
else:
ns = yn * 0.45 - 15160
sh = gz - 0.165 * gz - ns
return sh
if __name__ == '__main__':
if len(sys.argv) == 1:
print("Parameter Error")
exit()
dict1 = {}
for arg in sys.argv[1:]:
key, value = arg.split(':')
try:
dict1[int(key)] = int(float(value))
except ValueError:
print("Parameter Error")
exit()
for gh, gz in dict1.items():
print("{}:{:.2f}".format(gh, calculator(gz)))
|
15d38f06d05b2330c9d0269c4882c701d371eb69 | DiggidyDev/euleriser | /graph.py | 7,852 | 3.671875 | 4 | import random
from interface import Interface
from node import Node
__author__ = "DiggidyDev"
__license__ = "MIT"
__version__ = "1.0.1"
__maintainer__ = "DiggidyDev"
__email__ = "35506546+DiggidyDev@users.noreply.github.com"
__status__ = "Development"
class Graph:
"""
Graph is an object which represents a series of nodes, their
connections and identifiers. It is used for Eulerian-style graphs
and is capable of solving them using a Depth-First Search algorithm
with the hope of implementing a real-time visualisation of said
solution in the future.
It is currently still under development, but is hopefully going to
serve some sort of use in the future.
"""
def __init__(self, nodes: int = None):
"""
Default initialisation function.
:param nodes:
"""
self.current_node = None
self.image = None
self.interface = None
self.nodes = []
self.odd_nodes = []
self.path_count = 0
self.previous_node = None
self.travelled = {k + 1: [] for k in range(nodes)}
@property
def node_count(self):
"""
Returns the number of nodes in the graph, connected or not.
:return:
"""
return len(self.travelled.keys())
@property
def paths(self):
"""
Returns a dict containing all paths as keys, and their
connected nodes (see self.node_links) as the values.
:return:
"""
return {k: c.connections for k, c in enumerate(self.nodes, 1)}
def __len__(self):
"""
Returns the number of paths in a graph.
:return:
"""
return self.path_count
def __str__(self):
"""
Shows graph as an image.
Used to visualise the nodes and paths.
:return:
"""
for count in range(1, self.node_count + 1):
self.image = self.interface.draw_node(self.get_node(count), self.get_node(count).centre, 20)
self.image.show()
return "Graph successfully loaded!"
def _dfs(self, solution):
"""
Performs a depth-first search on the graph from a set
starting position.
Returns a list containing the solution.
:param solution:
:return:
"""
for neighbour in self.paths[self.current_node.identifier]:
if neighbour not in self.travelled[self.current_node.identifier] and not self.paths == self.travelled:
solution.append(self.current_node.identifier)
self.previous_node = self.current_node
self.current_node = self.get_node(neighbour)
self.travelled[self.current_node.identifier].append(self.previous_node.identifier)
self.travelled[self.previous_node.identifier].append(self.current_node.identifier)
self._dfs(solution)
for node in self.travelled.values():
node.sort()
return solution
def add_path(self, start, end):
"""
Creates and draws a path between two defined nodes, start and
end.
:param start:
:param end:
:return:
"""
if not (0 < start <= self.node_count) or not (0 < start <= self.node_count):
raise IndexError(f"Please provide valid values between the lower and upper bounds, inclusively: (1-{self.node_count})")
try:
start_node = self.get_node(start)
end_node = self.get_node(end)
start_node.connect_to(end_node)
self.image = self.interface.draw_path(start_node.centre, end_node.centre, action="add")
self.path_count += 1
except Exception as e:
print(f"{type(e).__name__}: {e}")
def analysis(self):
"""
Analyses the graph for the number of nodes, number of odd, even
nodes, whether it's Eulerian, semi-Eulerian or invalid.
In future will also highlight the path in real-time for the
solution to the graph.
:return:
"""
PAD = 14
self.odd_nodes = [str(node) for node in self.paths.keys() if len([c for c in self.paths[node]]) % 2 == 1]
if len(self.odd_nodes) == 2:
graph_type = "Semi-Eulerian path"
elif len(self.odd_nodes) == 0:
graph_type = "Eulerian cycle"
else:
graph_type = "Invalid graph type"
print(f"\n{'Nodes':{PAD}}: {self.node_count} ({'Even' if self.node_count % 2 == 0 else 'Odd'})")
print(f"{'Odd nodes':{PAD}}: {', '.join(self.odd_nodes)} (Possible starting nodes)")
print(f"{'Graph type':{PAD}}: {graph_type}\n")
def del_path(self, start, end):
"""
Deletes a path between two defined nodes, start and end.
This will both conceptually and visually delete said path.
:param start:
:param end:
:return:
"""
if not (0 < start <= self.node_count) or not (0 < start <= self.node_count):
raise IndexError(f"Please provide valid values between the lower and upper bounds, inclusively: (1-{self.nodes})")
try:
start_node = self.get_node(start)
end_node = self.get_node(end)
start_node.disconnect_from(end_node)
self.image = self.interface.draw_path(start_node.centre, end_node.centre, action="remove")
self.path_count -= 1
except Exception as e:
print(f"{type(e).__name__}: {e}")
def get_node(self, identifier):
"""
Returns the node object from the given identifier.
For when you wish to interact with a node.
:param identifier:
:return:
"""
for node in self.nodes:
if identifier == node.identifier:
return node
def init_gui(self):
"""
Initialises the Interface object, enabling drawing.
:return:
"""
gui = Interface(self.node_count)
self.interface = gui
for i in range(len(self.travelled.keys())):
node = Node(i + 1, self.interface)
node.set_radius(20)
self.nodes.append(node)
self.interface.graph = self
w = self.interface.dimensions[0]
h = self.interface.dimensions[1]
for node in range(1, self.node_count + 1):
radius = self.get_node(node).radius
self.get_node(node).set_position(random.randint(radius, (w - radius)), random.randint(radius, h - radius))
while self.get_node(node).distance_from() < radius * 2.5:
self.get_node(node).set_position(random.randint(radius, (w - radius)), random.randint(radius, h - radius))
return self.interface
def node_links(self, node=None):
"""
Returns the connecting nodes from a given node as a list.
:param node:
:return:
"""
if node is None:
node = self.current_node
print(f"'Node {node}' has {len(self.paths[node])} linked nodes: {', '.join([str(v) for v in self.paths[node]])}")
return self.paths[node]
def search(self, start):
"""
Runs the depth-first search algorithm, returning the validity
of the graph, and route if valid.
:param start:
:return:
"""
if not isinstance(start, Node):
self.current_node = self.get_node(start)
else:
self.current_node = start
solve_order = ' -> '.join([str(node) for node in self._dfs([])])
solve_order += f" -> {self.current_node.identifier}"
for node in self.travelled.values():
node.sort()
if self.travelled == self.paths:
print(f"Solved!\n{solve_order}")
else:
print("Not possible from this position!")
|
d67990ec50f962766c1017b19e5b89f5798fa710 | otmaneattou/OOP_projects | /calories_app/temperature.py | 1,679 | 3.625 | 4 | from selectorlib import Extractor
import requests
class Temperature():
"""
A scraper that uses an yaml file to read the xpath of a value
It needs to extract from timeanddate.com/weather/ url
"""
headers = {
'pragma': 'no-cache',
'cache-control': 'no-cache',
'dnt': '1',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (X11; CrOS x86_64 8172.45.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.64 Safari/537.36',
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',
}
base_url = 'https://www.timeanddate.com/weather/'
yaml_path = 'temperature.yaml'
def __init__(self, country, city):
self.country = country
self.city = city
def _build_url(self):
"""Build the url string adding country and city"""
url = self.base_url + self.country + "/" + self.city
return url
def _scrape(self):
"""Extracts a value as instructed by the yaml file and returns a dictionary"""
r = requests.get(self.base_url(), headers=self.headers)
full_content = r.text
extractor = Extractor.from_yaml_file(self.yaml_path)
raw_content = extractor.extract(full_content)
return raw_content
def get(self):
"""Cleans the output of _scrape"""
scraped_content = self._scrape
return float(scraped_content['temp'].replace("°C","").strip())
if __name__ == "__main__":
temperature = Temperature(country="usa", city="san francisco")
print(temperature.get()) |
ab9343311a6c6d43501b8e2196b1682e3d0398f6 | panoptes/PEAS | /peas/PID.py | 2,683 | 3.546875 | 4 | from datetime import datetime
class PID:
'''
Pseudocode from Wikipedia:
previous_error = 0
integral = 0
start:
error = setpoint - measured_value
integral = integral + error*dt
derivative = (error - previous_error)/dt
output = Kp*error + Ki*integral + Kd*derivative
previous_error = error
wait(dt)
goto start
'''
def __init__(self, Kp=2., Ki=0., Kd=1.,
set_point=None, output_limits=None,
max_age=None):
self.Kp = Kp
self.Ki = Ki
self.Kd = Kd
self.Pval = None
self.Ival = 0.0
self.Dval = 0.0
self.previous_error = None
self.set_point = None
if set_point:
self.set_point = set_point
self.output_limits = output_limits
self.history = []
self.max_age = max_age
self.last_recalc_time = None
self.last_interval = 0.
def recalculate(self, value, interval=None,
reset_integral=False,
new_set_point=None):
if new_set_point:
self.set_point = float(new_set_point)
if reset_integral:
self.history = []
if not interval:
if self.last_recalc_time:
now = datetime.utcnow()
interval = (now - self.last_recalc_time).total_seconds()
else:
interval = 0.0
# Pval
error = self.set_point - value
self.Pval = error
# Ival
for entry in self.history:
entry[2] += interval
for entry in self.history:
if self.max_age:
if entry[2] > self.max_age:
self.history.remove(entry)
self.history.append([error, interval, 0])
new_Ival = 0
for entry in self.history:
new_Ival += entry[0] * entry[1]
self.Ival = new_Ival
# Dval
if self.previous_error:
self.Dval = (error - self.previous_error) / interval
# Output
output = self.Kp * error + self.Ki * self.Ival + self.Kd * self.Dval
if self.output_limits:
if output > max(self.output_limits):
output = max(self.output_limits)
if output < min(self.output_limits):
output = min(self.output_limits)
self.previous_error = error
self.last_recalc_time = datetime.utcnow()
self.last_interval = interval
return output
def tune(self, Kp=None, Ki=None, Kd=None):
if Kp:
self.Kp = Kp
if Ki:
self.Ki = Ki
if Kd:
self.Kd = Kd
|
dd45a9660cfd3f30085b148fbbdc2c57691be9a9 | hpvo37/PyGame-games | /GameEffects/ShadowForText.py | 1,636 | 4 | 4 |
"""
example non-animated entry for the pygame text contest
if you would like to change this for your own entry, modify
the first function that renders the text. you'll also probably
want to change the arguments that your function used. simply
running the script should show some sort of example for your
text rendering
"""
import os, sys, pygame, pygame.font, pygame.image
from pygame.locals import *
def textDropShadow(font, message, offset, fontcolor, shadowcolor):
base = font.render(message, 0, fontcolor)
size = base.get_width() + offset, base.get_height() + offset
img = pygame.Surface(size, 16)
base.set_palette_at(1, shadowcolor)
img.blit(base, (offset, offset))
base.set_palette_at(1, fontcolor)
img.blit(base, (0, 0))
return img
entry_info = 'YASSSSSSSSSSS'
#this code will display our work, if the script is run...
if __name__ == '__main__':
pygame.init()
#create our fancy text
white = 255, 255, 255
grey = 100, 100, 100
bigfont = pygame.font.Font(None, 60)
text = textDropShadow(bigfont, entry_info, 3, white, grey)
#create a window the correct size
win = pygame.display.set_mode(text.get_size())
winrect = win.get_rect()
win.blit(text, (0, 0))
pygame.display.flip()
#wait for the finish
while 1:
event = pygame.event.wait()
if event.type is KEYDOWN and event.key == K_s: #save it
name = os.path.splitext(sys.argv[0])[0] + '.bmp'
print ('Saving image to:', name)
pygame.image.save(win, name)
elif event.type in (QUIT,KEYDOWN,MOUSEBUTTONDOWN):
break
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.