blob_id
stringlengths 40
40
| repo_name
stringlengths 5
127
| path
stringlengths 2
523
| length_bytes
int64 22
3.06M
| score
float64 3.5
5.34
| int_score
int64 4
5
| text
stringlengths 22
3.06M
|
---|---|---|---|---|---|---|
46b164ad9c3a01ee945fee69cd8ec8676fc2f154 | vthomas1908/yahtzee | /functions.py | 4,616 | 3.828125 | 4 | # Copyright (c) 2014 Thomas Van Klaveren
# create the function for Yahtzee game. This will evaluate dice and
# determine the points eligible for the score card item selected
#function checks the values of dice and returns a list containing the numbers
#of same valued dice (ie dice 6,2,6,6,2 would return [3,2])
def same_val_check(dice_list):
d = {}
l = []
for i in dice_list:
if i not in d:
d[i] = 1
else:
d[i] += 1
for i in d:
if d[i] not in l:
l.append(d[i])
return l
#function adds sum of dice values and returns that value
def dice_sum(dice_list):
x = 0
for i in dice_list:
x += i
return x
# tried to write this function as a module to import into my main file,
# however, tkinter needed this to be in the class where it was called from
# the radiobutton command
"""
def give_val(dice_results, score_card, dictionary, item):
val = 0
dice_vals = same_val_check(dice_results)
if score_card.get() == "ones":
for i in dice_results:
if i == 1:
val += 1
dictionary["ones"] = val
dictionary["total1"] += val
dictionary["total_score"] += val
item.configure(text = dictionary["ones"])
elif score_card.get() == "twos":
for i in dice_results:
if i == 2:
val += 1
dictionary["twos"] = val
dictionary["total1"] += val
dictionary["total_score"] += val
elif score_card.get() == "threes":
for i in dice_results:
if i == 3:
val += 1
dictionary["threes"] = val
dictionary["total1"] += val
dictionary["total_score"] += val
elif score_card.get() == "fours":
for i in dice_results:
if i == 4:
val += 1
dictionary["fours"] = val
dictionary["total1"] += val
dictionary["total_score"] += val
elif score_card.get() == "fives":
for i in dice_results:
if i == 5:
val += 1
dictionary["fives"] = val
dictionary["total1"] += val
dictionary["total_score"] += val
elif score_card.get() == "sixes":
for i in dice_results:
if i == 6:
val += 1
dictionary["sixes"] = val
dictionary["total1"] += val
dictionary["total_score"] += val
elif score_card.get() == "three kind":
for i in range(3,6):
if i in dice_vals:
val = dice_sum(dice_list)
break
dictionary["three_kind"] = val
dictionary["total2"] += val
dictionary["total_score"] += val
elif score_card.get() == "four kind":
for i in range(4,6):
if i in dice_vals:
val = dice_sum(dice_list)
break
dictionary["four_kind"] = val
dictionary["total2"] += val
dictionary["total_score"] += val
elif score_card.get() == "full house":
if 3 in dice_vals and 2 in dice_vals:
val = 25
elif 5 in dice_vals:
val = 25
dictionary["full_house"] = val
dictionary["total2"] += val
dictionary["total_score"] += val
elif score_card.get() == "sm straight":
for i in range(1,7):
if [i, i+1, i+2, i+3] <= sort(dice_results):
val = 30
elif 5 in dice_vals:
val = 30
dictionary["sm_straight"] = val
dictionary["total2"] += val
dictionary["total_score"] += val
elif score_card.get() == "lg straight":
for i in range(1,7):
if [i, i+1, i+2, i+3, i+4] <= sort(dice_results):
val = 40
elif 5 in dice_vals:
val = 40
dictionary["lg_straight"] = val
dictionary["total2"] += val
dictionary["total_score"] += val
elif score_card.get() == "chance":
val = dice_sum(dice_listi)
dictionary["chance"] = val
dictionary["total2"] += val
dictionary["total_score"] += val
elif score_card.get() == "yahtzee":
dice_vals = same_val_check(dice_results)
if 5 in dice_vals:
val = 50
dictionary["yahtzee"] = val
dictionary["total2"] += val
dictionary["total_score"] += val
if dictionary["ones"] + dictionary["twos"] + dictionary["threes"] + \
dictionary["fours"] + dictionary["fives"] + dictionary["sixes"] > 62:
dictionary["bonus"] = 35
dictionary["total1"] += 35
"""
|
96720afe434563414e5a8167964e4759a4696186 | tadteo/nnn | /src/utils.py | 835 | 3.53125 | 4 | #select the best two individuals
def select_best_two(population):
if population[0].score >= population[1].score:
mx=population[0].score
best = population[0]
second_best_value = population[1].score
second_best = population[1]
else:
mx=population[1].score
best = population[1]
second_best_value = population[0].score
second_best = population[0]
for i in range(2,len(population)):
if population[i].score>mx:
second_best_value = mx
second_best = best
mx=population[i].score
best=population[i]
elif population[i].score>second_best_value and mx != population[i].score:
second_best_value=population[i].score
second_best=population[i]
return best, second_best
|
3bcd2fad9fbb8028a7b92da712c3c3f5f13c3f84 | spoofdoof/2018 | /SP/assign3/decrypt.py | 2,302 | 3.96875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import string
from collections import defaultdict, Counter
def read_file(filename):
with open(filename) as lines:
for line in lines:
yield line.strip().decode('hex')
def xor_combinations(data):
"""
Returns all posible combinations of XORs between data entries
TODO: use numpy arrays
>>> list(xor_combinations(["AAA","AAA"]))
[('AAA', 'AAA', '\x00\x00\x00')]
>>> list(xor_combinations(["AAA","BBB", "CCCC"]))
[('AAA', 'BBB', '\x03\x03\x03'), ('AAA', 'CCCC', '\x02\x02\x02'), ('BBB', 'CCCC', '\x01\x01\x01')]
"""
import itertools
for ct1, ct2 in itertools.combinations(data,2):
xorred = []
for char1, char2 in zip(ct1, ct2):
xorred.append(chr(ord(char1) ^ ord(char2)))
yield ct1, ct2, "".join(xorred)
def statistics(data):
"""Returns list of possible values for each byte of key"""
possibilities = defaultdict(list)
for ct1, ct2, xorred in data:
for (i, char) in enumerate(xorred):
# The unlimate hint was given at Question itself:
# Hint: XOR the ciphertexts together, and consider what happens when a space is XORed with a character in [a-zA-Z].
if char in string.letters:
possibilities[i].extend([ord(ct1[i])^32, ord(ct2[i])^32])
return possibilities
def guess_key(possibilities):
"""
Simplest heuristics ever - just return most common value for each dict key
XXX: sic! Because of that output is not 100% correct. We should take into
an account english letter distribution.
"""
return "".join(chr(Counter(item).most_common(1)[0][0]) for item in possibilities.values())
if __name__ == '__main__':
import logging
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-f", type="string", dest="file", default="ciphertexts.txt")
(options, args) = parser.parse_args()
data = list(read_file(options.file))
possibilities = statistics(xor_combinations(data))
key = guess_key(possibilities)
logging.warn("Possible key: {0}".format(key.encode('hex')))
from encrypt import strxor
for target in data:
logging.warning("Partially recovered data: {0}".format(strxor(target, key)))
|
e7caaeace5bfd268d90db767c2d8df6d1539fca6 | JuDePom/algooo | /lda/prettyprinter.py | 2,077 | 3.9375 | 4 | class PrettyPrinter:
"""
Facilitates the making of a properly-indented file.
"""
# must be defined by subclasses
export_method_name = None
def __init__(self):
self.indent = 0
self.strings = []
self.already_indented = False
def put(self, *items):
"""
Append items to the source code at the current indentation level.
If an item is a string, append it right away; otherwise, invoke
`item.<export_method_name>(self)`.
"""
for i in items:
if type(i) is str:
if not self.already_indented:
self.strings.append('\t' * self.indent)
self.already_indented = True
self.strings.append(i)
else:
getattr(i, self.export_method_name)(self)
def indented(self, exportfunc, *args):
"""
Append items to the source code at an increased indentation level.
:param exportfunc: export function. Typically put, putline, or join.
:param args: arguments passed to exportfunc
"""
self.indent += 1
exportfunc(*args)
self.indent -= 1
def newline(self, count=1):
"""
Append line breaks to the source code.
:param count: optional number of line breaks (default: 1)
"""
self.strings.append(count*'\n')
self.already_indented = False
def putline(self, *items):
"""
Append items to the source code, followed by a line break.
"""
self.put(*items)
self.newline()
def join(self, iterable, gluefunc, *args):
"""
Concatenate the elements in the iterable and append them to the source
code. A 'glue' function (typically put()) is called between each
element. Note: This method is similar in purpose to str.join().
:param gluefunc: glue function called between each element
:param args: arguments passed to gluefunc
"""
it = iter(iterable)
try:
self.put(next(it))
except StopIteration:
return
for element in it:
gluefunc(*args)
self.put(element)
def __repr__(self):
"""
Return the source code built so far.
"""
return ''.join(self.strings)
class LDAPrettyPrinter(PrettyPrinter):
export_method_name = "lda"
class JSPrettyPrinter(PrettyPrinter):
export_method_name = "js"
|
5ecae8a199ce0b5e87bb6d57f4386a5c8ba29d31 | Riableo/analisis | /Ejercicios/insercion.py | 396 | 3.921875 | 4 | def Insercion(Vector):
for i in range(1,len(Vector)):
actual = Vector[i]
j = i
#Desplazamiento de los elementos de la matriz }
while j>0 and Vector[j-1]>actual:
Vector[j]=Vector[j-1]
j = j-1
#insertar el elemento en su lugar
Vector[j]=actual
return(Vector)
te = [8, 1, 3, 2]
print(Insercion(te))
|
63d77f48f26c15c1d060ba2f50b82386016a6389 | Riableo/analisis | /Ejercicios/Multiplos.py | 367 | 3.890625 | 4 | tr=0
while tr == 0:
try:
Num=int(input("Ingresar numero: "))
Num_I=int(input("Ingresar numero: "))
N=Num%Num_I
N1=Num_I%Num
if N == 0 or N1 == 0:
print("Sao Multiplos")
else:
print("Nao sao Multiplos")
except ValueError:
print("Solo números por favor")
tr=int(input("Volver a realizar diferencia \n 0: sí !0:No: "))
|
331a82a167fd30e270ec8db699145caba71a80d3 | skyhuge/python-demo | /muti_params.py | 1,204 | 4.0625 | 4 | def calc(nums):
sum = 0
for n in nums:
sum += n
return sum
# 可变参数
def add_nums(*nums):
sum = 0
for n in nums:
sum += n
return sum
# 关键字参数
def print_nums(name, age, **kw):
# kw.clear() # 对kw的操作不会改变extra的值
print('name is %s , age is %s , other is %s' % (name, age, kw))
# 命名关键字参数
def print_info(name, age, *args, addr, job):
print('name is %s , age is %s , addr is %s , job is %s ' % (name, age, addr, job))
print('* is ', args) # args 其实是一个只有一个元素的tuple
# 参数定义的顺序必须是:必选参数、默认参数、可变参数、命名关键字参数和关键字参数
def example(a, b=1, *, c, d, **kw):
print(a, b, c, d, kw)
def exam(*args, **kw):
print(args.__add__((6,)), kw)
if __name__ == '__main__':
l = [1, 2, 4, 3, 5]
print(calc(l))
print(add_nums(*l))
extra = {'job': 'Engineer', 'address': 'Shanghai'}
print_nums('ashin', 24, gender='male')
print_nums('ashin', 24, **extra)
print_info('ashin', 24, extra, addr='China', job='Engineer')
example('hello', c='adc', d='world', **extra)
exam(*l, **extra)
|
f19d3a39693428d4ff85fc65e8cdc734c1b8f5d0 | 6Kwecky6/PyForProggers | /Lecture4/TimeTableDraw.py | 1,224 | 4.0625 | 4 | import turtle
import math
step = 0
def drawCircle(rad, num_points, pen):
# placing the circle down by rad to make the center of it origo
pen.up()
pen.goto(0,-rad)
pen.down()
# Drawing the circle
pen.circle(rad)
pen.up()
#Moves along the circle to yield points
for it in range(num_points):
yield [math.sin(step*it)*rad,math.cos(step*it)*rad] #This yields each point
def drawLine(rad,num_points,cur_point,multiplic,x_pos,y_pos,pen):
to_pos = [math.sin(step*(cur_point*multiplic%num_points))*rad,math.cos(step*(cur_point*multiplic%num_points))*rad]
pen.goto(x_pos,y_pos)
pen.down()
pen.goto(to_pos[0],to_pos[1])
pen.up()
def main():
pen = turtle.Turtle()
num_points = 300
rad = 200
multiplic = 4
window = turtle.Screen()
global step # This is the length between each point on the circle
step = (math.pi * 2) / num_points
pen.speed(10)
#Draws the circle
points = drawCircle(rad,num_points, pen)
# Draws each line
for it in range(num_points):
to_pos = next(points)
drawLine(rad,num_points,it, multiplic,to_pos[0],to_pos[1],pen)
window.exitonclick()
if __name__ == '__main__':
main() |
eac82a0b61c8bee65c15b3078150af5f711c45d5 | pinpin3152/python | /Assignment_cointoss.py | 837 | 3.78125 | 4 | import random
def coin(toss):
if toss == 0:
return "head"
else:
return "tail"
head = 0
tail = 0
i = 1
while i < 5001:
X = random.randint(0,1)
if X == 0:
head += 1
else:
tail += 1
print "Attempt #" + str(i) + ": Throwing a coin... It's a " + coin(X) + "! ... Got " + str(head) + " head(s) so far and " + str(tail) + " tail(s) so far"
i += 1
'''
#answer sheet solution
import random
import math
print 'Starting the program'
head_count = 0
tail_count = 0
for i in range(1,5001):
rand = round(random.random())
if rand == 0:
face = 'tail'
tail_count += 1
else:
face = 'head'
head_count += 1
print "Attempt #"+str(i)+": Throwing a coin...It's a "+face+"!...Got "+str(head_count)+" head(s) and "+str(tail_count)+" tail(s) so far"
print 'Ending the program, thank you!'
''' |
63a21b76e45777b7fa2b333df3bf46b56920c304 | Tornike-Skhulukhia/Principles-of-data-science-book-working-files | /scripts/chapter 10/point_estimates.py | 1,168 | 3.625 | 4 | from import_helpers import (
np,
pd,
plt,
)
from scipy import stats
from scipy.stats import poisson
# why do they use loc > 0 in the book???
long_breaks = poisson.rvs(loc=0, mu=60, size=3000)
short_breaks = poisson.rvs(loc=0, mu=15, size=6000)
breaks = np.concatenate([long_breaks, short_breaks])
# pd.Series(breaks).hist()
parameter = np.mean(breaks)
if __name__ == '__main__':
print(f'Population parameter - Mean = {parameter:.3f}')
sample_breaks = np.random.choice(breaks, size=100)
print(f'Point estimate - Mean based on sample = {np.mean(sample_breaks):.3f}')
# calculate more samples
point_estimates = [np.mean(np.random.choice(breaks, 100)) for _ in range(500)]
estimates_mean = np.mean(point_estimates)
print(f'Mean of 500 point estimates = {estimates_mean:.3f}')
print(f'Difference from parameter {estimates_mean - parameter:.3f} ({(estimates_mean - parameter) / parameter * 100:.3f}%)')
plt.title('Distribution of 500 point estimate means')
pd.Series(point_estimates).hist(bins=50)
plt.show()
|
f4034f05130cfa6c9d6f1af443f1651da5534e28 | stoicswe/CSCI315A-BigData | /HW6_NathanBunch/Boltzman Machine Example/rbm.py | 14,152 | 3.828125 | 4 | from __future__ import print_function
import numpy as np
class RBM:
def __init__(self, num_visible, num_hidden):
self.num_hidden = num_hidden
self.num_visible = num_visible
self.debug_print = True
# Initialize a weight matrix, of dimensions (num_visible x num_hidden), using
# a uniform distribution between -sqrt(6. / (num_hidden + num_visible))
# and sqrt(6. / (num_hidden + num_visible)). One could vary the
# standard deviation by multiplying the interval with appropriate value.
# Here we initialize the weights with mean 0 and standard deviation 0.1.
# Reference: Understanding the difficulty of training deep feedforward
# neural networks by Xavier Glorot and Yoshua Bengio
np_rng = np.random.RandomState(1234)
self.weights = np.asarray(np_rng.uniform(
low=-0.1 * np.sqrt(6. / (num_hidden + num_visible)),
high=0.1 * np.sqrt(6. / (num_hidden + num_visible)),
size=(num_visible, num_hidden)))
print(self.weights)
# Insert weights for the bias units into the first row and first column.
self.weights = np.insert(self.weights, 0, 0, axis = 0)
self.weights = np.insert(self.weights, 0, 0, axis = 1)
print(self.weights)
def train(self, data, max_epochs = 1000, learning_rate = 0.1):
"""
Train the machine.
Parameters
----------
data: A matrix where each row is a training example consisting of the states of visible units.
"""
num_examples = data.shape[0]
#print(data)
#print(num_examples)
# Insert bias units of 1 into the first column.
# here is when the intercept is added
# y = ax + b*1
# that is why 1 is added, since it describes the bias
data = np.insert(data, 0, 1, axis = 1) # intercept like sciklit learn is added into the weights
#print(data)
for epoch in range(max_epochs):
# Clamp to the data and sample from the hidden units.
# (This is the "positive CD phase", aka the reality phase.)
#print("DATA")
#print(data)
pos_hidden_activations = np.dot(data, self.weights)
#print("POS HIDDEN ACTIVATIONS")
#print(pos_hidden_activations)
#print(pos_hidden_activations)
pos_hidden_probs = self._logistic(pos_hidden_activations)
#print("POS HIDDEN PROBS")
#print(pos_hidden_probs)
#print(pos_hidden_probs)
pos_hidden_probs[:,0] = 1 # Fix the bias unit.
#print("POS HIDDEN PROBS FIX")
#print(pos_hidden_probs)
#print(pos_hidden_probs)
pos_hidden_states = pos_hidden_probs > np.random.rand(num_examples, self.num_hidden + 1)
#print("POS HIDDEN STATES")
#print(pos_hidden_states)
#print(">>>>>>>>>>>>>>>>>>>>>>")
#print(pos_hidden_states)
# Note that we're using the activation *probabilities* of the hidden states, not the hidden states
# themselves, when computing associations. We could also use the states; see section 3 of Hinton's
# "A Practical Guide to Training Restricted Boltzmann Machines" for more.
pos_associations = np.dot(data.T, pos_hidden_probs)
#print("POS ASSOCIATIONS")
#print(pos_associations)
#print(pos_associations)
# Reconstruct the visible units and sample again from the hidden units.
# (This is the "negative CD phase", aka the daydreaming phase.)
neg_visible_activations = np.dot(pos_hidden_states, self.weights.T)
# print("NEG VISIBLE ACTIVATIONS")
#print(neg_visible_activations)
#print(neg_visible_activations)
neg_visible_probs = self._logistic(neg_visible_activations)
# print("NEG VISIBLE PROBS LOGISTICS")
#print(neg_visible_probs)
#print(neg_visible_probs)
neg_visible_probs[:,0] = 1 # Fix the bias unit.
# print("NEG VISIBLE PROBS FIX")
# print(neg_visible_probs)
#print(neg_visible_probs)
neg_hidden_activations = np.dot(neg_visible_probs, self.weights)
# print("NEG HIDDEN ACTIVATIONS")
# print(neg_hidden_activations)
#print(neg_hidden_activations)
neg_hidden_probs = self._logistic(neg_hidden_activations)
# print("NEG HIDDEN PROBS LOGISTICS")
# print(neg_hidden_probs)
#print(neg_hidden_probs)
# Note, again, that we're using the activation *probabilities* when computing associations, not the states
# themselves.
neg_associations = np.dot(neg_visible_probs.T, neg_hidden_probs)
# print("NEG ASSOCIATIONS")
# print(neg_associations)
#print(neg_associations)
# Update weights.
self.weights += learning_rate * ((pos_associations - neg_associations) / num_examples)
# print("WEIGHT UPDATE")
# print(self.weights)
#print(self.weights)
error = np.sum((data - neg_visible_probs) ** 2)
#print(error)
if self.debug_print:
print("Epoch %s: error is %s" % (epoch, error))
def run_visible(self, data):
"""
Assuming the RBM has been trained (so that weights for the network have been learned),
run the network on a set of visible units, to get a sample of the hidden units.
Parameters
----------
data: A matrix where each row consists of the states of the visible units.
Returns
-------
hidden_states: A matrix where each row consists of the hidden units activated from the visible
units in the data matrix passed in.
"""
num_examples = data.shape[0]
# Create a matrix, where each row is to be the hidden units (plus a bias unit)
# sampled from a training example.
hidden_states = np.ones((num_examples, self.num_hidden + 1))
# Insert bias units of 1 into the first column of data.
data = np.insert(data, 0, 1, axis = 1)
# Calculate the activations of the hidden units.
hidden_activations = np.dot(data, self.weights)
# Calculate the probabilities of turning the hidden units on.
hidden_probs = self._logistic(hidden_activations)
# Turn the hidden units on with their specified probabilities.
hidden_states[:,:] = hidden_probs > np.random.rand(num_examples, self.num_hidden + 1)
# Always fix the bias unit to 1.
# hidden_states[:,0] = 1
# Ignore the bias units.
hidden_states = hidden_states[:,1:]
return hidden_states
# TODO: Remove the code duplication between this method and `run_visible`?
def run_hidden(self, data):
"""
Assuming the RBM has been trained (so that weights for the network have been learned),
run the network on a set of hidden units, to get a sample of the visible units.
Parameters
----------
data: A matrix where each row consists of the states of the hidden units.
Returns
-------
visible_states: A matrix where each row consists of the visible units activated from the hidden
units in the data matrix passed in.
"""
num_examples = data.shape[0]
# Create a matrix, where each row is to be the visible units (plus a bias unit)
# sampled from a training example.
visible_states = np.ones((num_examples, self.num_visible + 1))
# Insert bias units of 1 into the first column of data.
data = np.insert(data, 0, 1, axis = 1)
# Calculate the activations of the visible units.
visible_activations = np.dot(data, self.weights.T)
# Calculate the probabilities of turning the visible units on.
visible_probs = self._logistic(visible_activations)
# Turn the visible units on with their specified probabilities.
visible_states[:,:] = visible_probs > np.random.rand(num_examples, self.num_visible + 1)
# Always fix the bias unit to 1.
# visible_states[:,0] = 1
# Ignore the bias units.
visible_states = visible_states[:,1:]
return visible_states
def daydream(self, num_samples):
"""
Randomly initialize the visible units once, and start running alternating Gibbs sampling steps
(where each step consists of updating all the hidden units, and then updating all of the visible units),
taking a sample of the visible units at each step.
Note that we only initialize the network *once*, so these samples are correlated.
Returns
-------
samples: A matrix, where each row is a sample of the visible units produced while the network was
daydreaming.
"""
# Create a matrix, where each row is to be a sample of of the visible units
# (with an extra bias unit), initialized to all ones.
samples = np.ones((num_samples, self.num_visible + 1))
# Take the first sample from a uniform distribution.
samples[0,1:] = np.random.rand(self.num_visible)
# Start the alternating Gibbs sampling.
# Note that we keep the hidden units binary states, but leave the
# visible units as real probabilities. See section 3 of Hinton's
# "A Practical Guide to Training Restricted Boltzmann Machines"
# for more on why.
for i in range(1, num_samples):
visible = samples[i-1,:]
# Calculate the activations of the hidden units.
hidden_activations = np.dot(visible, self.weights)
# Calculate the probabilities of turning the hidden units on.
hidden_probs = self._logistic(hidden_activations)
# Turn the hidden units on with their specified probabilities.
hidden_states = hidden_probs > np.random.rand(self.num_hidden + 1)
# Always fix the bias unit to 1.
hidden_states[0] = 1
# Recalculate the probabilities that the visible units are on.
visible_activations = np.dot(hidden_states, self.weights.T)
visible_probs = self._logistic(visible_activations)
visible_states = visible_probs > np.random.rand(self.num_visible + 1)
samples[i,:] = visible_states
# Ignore the bias units (the first column), since they're always set to 1.
return samples[:,1:]
def _logistic(self, x):
return 1.0 / (1 + np.exp(-x))
# Nathan's definitions that have been added
# weights in the sciklit learn is known as components and here it is weights
# create the collowing:
#def fit(self, data, y=None):
# #fix the way the weights are generated....its incorrect size
# n_samples = data.shape[0]
# vis = data.shape[1]
# hid = data.shape[0] * data.shape[1]
# np_rng = np.random.RandomState(1234)
# self.weights = np.asarray(np_rng.uniform(low=-0.1 * np.sqrt(6. / (hid + vis)), high=0.1 * np.sqrt(6. / (hid + vis)),size=(vis, hid)))
# self.weights = np.insert(self.weights, 0, 0, axis = 0)
# self.weights = np.insert(self.weights, 0, 0, axis = 1)
# n_batches = int(np.ceil(float(n_samples) / 4))
#batch_slices = list(gen_even_slices(n_batches * 4,n_batches, n_samples))
# batch_slices = list(data[0:n_batches*4:n_batches])
# for iteration in range(1, 5000 + 1):
# for batch_slice in batch_slices:
# #self._fit(X[batch_slice])
# self._fit(data[batch_slice])
# print("Iteration %d, pseudo-likelihood = %.2f" % (iteration, self.score_samples(X).mean()))
#idk why but this is an error
#def _fit(self, data):
#h_pos = self._mean_hiddens(v_pos)
# v_neg = self._sample_visibles(self.h_samples_, rng)
# h_neg = self._mean_hiddens(v_neg)
# lr = float(self.learning_rate) / v_pos.shape[0]
# update = safe_sparse_dot(v_pos.T, h_pos, dense_output=True).T
# update -= np.dot(h_neg.T, v_neg)
# self.components_ += lr * update
# self.intercept_hidden_ += lr * (h_pos.sum(axis=0) - h_neg.sum(axis=0))
# self.intercept_visible_ += lr * (np.asarray(
# v_pos.sum(axis=0)).squeeze() -
# v_neg.sum(axis=0))
# h_neg[rng.uniform(size=h_neg.shape) < h_neg] = 1.0 # sample binomial
# self.h_samples_ = np.floor(h_neg, h_neg)
#pos_hidden_activations = np.dot(data, self.weights)
#pos_hidden_probs = self._logistic(pos_hidden_activations)
#pos_hidden_probs[:,0] = 1 # Fix the bias unit.
#pos_hidden_states = pos_hidden_probs > np.random.rand(num_examples, self.num_hidden + 1)
# Note that we're using the activation *probabilities* of the hidden states, not the hidden states
# themselves, when computing associations. We could also use the states; see section 3 of Hinton's
# "A Practical Guide to Training Restricted Boltzmann Machines" for more.
#pos_associations = np.dot(data.T, pos_hidden_probs)
# Reconstruct the visible units and sample again from the hidden units.
# (This is the "negative CD phase", aka the daydreaming phase.)
#neg_visible_activations = np.dot(pos_hidden_states, self.weights.T)
#neg_visible_probs = self._logistic(neg_visible_activations)
#neg_visible_probs[:,0] = 1 # Fix the bias unit.
#neg_hidden_activations = np.dot(neg_visible_probs, self.weights)
#neg_hidden_probs = self._logistic(neg_hidden_activations)
# Note, again, that we're using the activation *probabilities* when computing associations, not the states
# themselves.
#neg_associations = np.dot(neg_visible_probs.T, neg_hidden_probs)
# Update weights.
#self.weights += learning_rate * ((pos_associations - neg_associations) / num_examples)
#error = np.sum((data - neg_visible_probs) ** 2)
#if self.debug_print:
# print("Fit Iteration %s: error is %s" % (epoch, error))
#def score_samples():
if __name__ == '__main__':
r = RBM(num_visible = 6, num_hidden = 2)
training_data = np.array([[1,1,1,0,0,0],[1,0,1,0,0,0],[1,1,1,0,0,0],[0,0,1,1,1,0], [0,0,1,1,0,0],[0,0,1,1,1,0]])
#r.train(training_data, max_epochs = 5000) #default
r.train(training_data, max_epochs = 5000)
#r.fit(training_data)
print("Weights:")
print(r.weights)
print()
user = np.array([[0,0,0,1,1,0]])
print("Get the category preference:")
print(r.run_visible(user))
print()
userPref = np.array([[1,0]])
print("Get the movie preference:")
print(r.run_hidden(userPref))
print()
print("Daydream for (5):")
movieWatch = r.daydream(5)
print(movieWatch)
#print(movieWatch[:,3])
#print("Get daydream category preferences:")
#print(r.run_visible(np.array(movieWatch[:,2]))) |
ff66222e7d4764345f053a966e2b0cd81255667f | adhed/shortest-path | /shortest_path.py | 1,002 | 4.0625 | 4 | from point import Point
from algorithm import Algorithm
def ask_for_points():
points = []
points_counter = int(input("Podaj proszę liczbę punktów jaką będziesz chciał przeliczyć: "))
for idx in range(points_counter):
x = int(input("Podaj współrzędną X dla punktu nr {0}: ".format(idx+1)))
y = int(input("Podaj współrzędną Y dla punktu nr {0}: ".format(idx+1)))
point = Point(idx+1, x, y)
points.append(point)
return points
def ask_for_starting_point():
try:
starting_point = int(input("Podaj numer punktu startowego: "))
except:
print("Czy aby na pewno podałeś numer?")
return starting_point
def main():
print("Witaj w algorytmie przeliczania najkrótszej ścieżki!")
points = ask_for_points()
starting_point_number = ask_for_starting_point()
algorithm = Algorithm(points, starting_point_number)
algorithm.calculate_shortest_path()
if __name__ == "__main__":
main() |
0e69f61ef23bc9b2dc698670ed063a51fe8fb2c1 | anoubhav/Codeforces-Atcoder-Codechef-solutions | /Codeforces/653_div_3/b.py | 1,358 | 3.546875 | 4 | from sys import stdin
from collections import defaultdict as dd
from collections import deque as dq
import itertools as it
from math import sqrt, log, log2
from fractions import Fraction
t = int(input())
for _ in range(t):
n = int(input())
nummoves = 0
flag = 0
while n!=1:
if n%3!=0:
flag = 1
break
if n%6 == 0:
n //= 6
else:
n*=2
nummoves += 1
if flag: print(-1)
else: print(nummoves)
## Intended solution
# If the number consists of other primes than 2 and 3 then the answer is -1. Otherwise, let cnt2 be the number of twos in the factorization of n and cnt3 be the number of threes in the factorization of n. If cnt2>cnt3 then the answer is -1 because we can't get rid of all twos. Otherwise, the answer is (cnt3−cnt2)+cnt3.
def editorial():
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
n = int(input())
count3 = 0
while n % 3 == 0:
n //= 3
count3 += 1
count2 = 0
while n % 2 == 0:
n //= 2
count2 += 1
if n != 1 or count2 > count3:
print(-1)
continue
print(count3 + (count3 - count2))
|
9336374508ea58e1706637d9d20636ab94d08b4c | anoubhav/Codeforces-Atcoder-Codechef-solutions | /Codeforces/644 Div 3/C.py | 1,094 | 3.96875 | 4 | # A pair (x, y) is similar if they have same parity, i.e., x%2 == y%2 OR they are consecutive |x-y| = 1
t = int(input())
for _ in range(t):
# n is even (given in question, also a requirement to form pairs)
n = int(input())
arr = list(map(int, input().split()))
# There are only two cases: no.of even (and odd) pairs is even OR no.of even (and odd) pairs is odd. [n is even]
even_pair_count = 0
for num in arr:
if num%2 == 0: even_pair_count += 1
if even_pair_count%2==0: # there are even no. of even pairs and odd pairs
print('YES')
continue
else:
# both (even and odd pairs) are odd.
# If we can find a SINGLE |x-y| consecutive number pair (one will be even, other odd because consecutive), we can exclude (x, y) from the array. This leaves us with even no. of (even and odd) pairs.
arr.sort()
ans = 'NO'
for i in range(1, n):
if arr[i] - arr[i-1] == 1:
ans = 'YES'
break
print(ans)
|
fad5fe4ca3e87197c4d7204999ed5fef4f81220a | anoubhav/Codeforces-Atcoder-Codechef-solutions | /Codechef/ANSLEAK.py | 439 | 3.59375 | 4 | from collections import Counter
def get_most_frequent(solns):
return Counter(solns).most_common()[0][0]
if __name__ == "__main__":
T = int(input())
for _ in range(T):
ans = []
n, m, k = list(map(int, input().split()))
for _ in range(n):
solns = list(map(int, input().split()))
ans.append(get_most_frequent(solns))
print(' '.join([str(i) for i in ans]))
|
9e364b774c5ccd44d3897cd98983a4d7bf072cd7 | anoubhav/Codeforces-Atcoder-Codechef-solutions | /Atcoder/172/d.py | 1,294 | 3.828125 | 4 | n = int(input())
# Check out atcoder editorial for this, beautifully explained. Same as geothermal's but it also shows how this idea was thought
# https://img.atcoder.jp/abc172/editorial.pdf
def sieve(n):
# 1.9 seconds.
# 1 and n are divisors for every n.
is_prime = [2]*(n + 1)
is_prime[0], is_prime[1] = 0, 0
# is_prime holds the number of positive divisors of N. Instead of being a bool of 0/1 for prime/not prime. for example of N=24---> is_prime[24] = 6 (1, 2, 3, 4, 6 ,24)
for num in range(2, n+1//2):
for mult in range(2*num, n+1, num):
is_prime[mult] += 1
ans = 1
# i is N. elem is f(N)
for i, elem in enumerate(is_prime[2:]):
ans += (elem)*(i + 2)
print(ans)
def geothermal(n):
# Source: https://codeforces.com/blog/entry/79438
# Let's reframe the problem by considering the total contribution each divisor makes to the answer. For any given i, i contributes K to the sum for each K from 1 to N such that K is a multiple of i.
ans = 0
for i in range(1, n+1):
mult = n//i
ans += (mult*(mult + 1)*i)//2
print(ans)
# O(N) solution; 170ms
geothermal(n)
# O(N* some log factors) much slower than geo's; 1940ms
sieve(n)
|
a1c657c309fabf23cd2f255e0431ec673c2d8470 | anoubhav/Codeforces-Atcoder-Codechef-solutions | /Codeforces/Educational Round 88/C.py | 1,885 | 3.671875 | 4 | # If there are even number of cups, the attained temperature is always: (h+c)/2. If there are odd number of total cups (let it be 2*x - 1). There are x hot cups and (x-1) cold cups. The attained temperature is given by (h*x + c*(x-1))/2*x-1 = t_attained ---- EQN 1
# In the odd no. of cups case, the no. of hot cups is ALWAYS one more than no. of cold cups, so t_attained > (h+c)/2.
# If t_desired < (h+c)/2 --> the answer is two cups.
# If t_desired > (h+c)/2 --> the answer consists of odd no. of cups. This can be obtained by solving EQN 1 for x by substituting t_attained by t_desired.
# x = (t_desired - c)/ (h + c - 2*t_desired). Solving this we get a fractional value for x.
# The answer will be 2*min(t_desired - t_attained_floor_x, t_desired - t_attained_ceil_x)-1.
# As x, gives us the number of h cups. The answer is total number of cups which is 2*x - 1
# Solve above equation for x (no. of hot cups) by replacing t_attained with t_desired.
## Failing on the test case:
# 1
# 999977 17 499998
# Output = 499979
# Answer = 499981
from sys import stdin, stdout
from decimal import Decimal # tried using decimal module to get more precision.
t = int(input())
for _ in range(t):
h, c, t = map(int, stdin.readline().split())
if (h+c) >= 2*t:
print(2)
else:
x1 = (c-t)//(h+c- 2*t) # floor x
x2 = x1 + 1 # ceil x
# get both average temperature and check which is minimum
t1 = Decimal((h*x1 + c*(x1 - 1))/((2*x1) - 1))
t2 = Decimal((h*x2 + c*(x2 - 1))/((2*x2) - 1))
# print(t1, t2, abs_avg_x1, abs_avg_x2)
t = Decimal(t)
abs_avg_x1 = Decimal(abs(t - t1))
abs_avg_x2 = Decimal(abs(t - t2))
if abs_avg_x1<=abs_avg_x2:
print(2*x1 - 1)
else:
print(2*x2 - 1)
|
f05605470e60d9342fc96dca170bc90e9418cac4 | Mustafa-pnevma-galinis/Basic-Algorithms | /Agorithms.py | 11,412 | 4.34375 | 4 | #بسم اللّه و الصلاة و السلام على جميع الأنبياء و المرسلين و آل بيوتهم الطاهرين المقربين و على من تبعهم بإحسانٍ إلى يوم الدين
# ◙◙ (α) Merge Sort Algorithm
count = 0
lst = [4,6,8,1,3,2,5,7]
sectorA = lst[0:4]
sectorB = lst[4:8]
# ◘◘@Note: to allocate the size of the array before initialisation.
#sortedArray = [][:5]
sortedArray = []
count = 0
# ◘◘@Note: to print the entire array elements without for loop.
'''print(*sectorA,sep ="\n")
print('\n'.join(map(str, sectorA)))'''
'''for i in range(1):
if (sectorA[-1] < sectorA[0] and sectorA[-1] < sectorA[1] and sectorA[-1] < sectorA[2]):
sortedArray.append(sectorA[-1])
if(sectorA[0] < sectorA[1] and sectorA[0] < sectorA[2] ):
sortedArray.append(sectorA[0])
if(sectorA[1] < sectorA[2]):
sortedArray.append(sectorA[1])
sortedArray.append(sectorA[2])
'''
'''for i in sectorA:
if(sectorA[-1] < i):
sortedArray.append(sectorA[-1])
if(sectorA[0] < i):
sortedArray.append(sectorA[0])
if (sectorA[1] < i):
sortedArray.append(sectorA[1])
sortedArray.append(sectorA[2])
'''
# ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
# ◙◙ {Select Sorting Algorithms}
#───────────────────────────────────────────────────────────────────────────────────
#◘◘@Note: to sort a list we need firstly to set the minimum number {declare a new variable} as the first index on the list; either it is the minimum or not,
# then compare that number with the rest numbers on the list, after getting the {real minimum number}, set it to be the first index on the list.
unsortedLst = [7,11,8,1,4,2,3,9,12,10]
for i in range(len(unsortedLst)):
# Find the minimum element in remaining
# unsorted array
min_number = i
for j in range(i+1, len(unsortedLst)):
if unsortedLst[min_number] > unsortedLst[j]:
min_number = j
# Swap the found minimum element with
# the first element
unsortedLst[i], unsortedLst[min_number] = unsortedLst[min_number], unsortedLst[i]
'''print(unsortedLst)'''
# ◘◘Select Sorting Algorithm illustration;
'''
◘ for i in range (11):
min_number = 0
for j in range(1,11):
if (unsortedLst[0] > unsortedLst[1]):
min_number = 1
▬# Then Swapping indices, The min_number will get in-place
of the higher_number; That process will continuosly occured till
the array got arranged.
'''
# ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
# ◙◙ {Bubble Sorting Algorithms}
#───────────────────────────────────────────────────────────────────────────────────
def bubbleSort(array):
n = len(array)
for i in range(n-1): # ◘◘ {n-1} because the last element has the index No. [(len(array)-1)].
for j in range(0,n-i-1):
if (array[j] > array[j+1]):
array[j], array[j+1] = array[j+1], array[j]
return array
'''
# ◘◘Illustration: ▬ On first iteration
for i in range(7):
for j in range(0,6): # On first iteration i = 0
if (array[1] > array[2]): # ▬ if True > then swap the indices values.
array[1], array[2] = array[2],array[1]
'''
'''print(bubbleSort([1,3,4,5,8,6,7,2]))'''
# ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
# ◙◙ {Insertion Sorting Algorithms}
#───────────────────────────────────────────────────────────────────────────────────
L = [4,5,8,9,2,1,3,7,6]
for i in range(1,len(L)):
k = L[i]
j = i - 1
while (j >= 0 and L[j] > k):
L[j+1] = L[j]
j = j - 1
L[j+1] = k
'''Algorithm Analysis'''
'''k = L[0]
j = 0'''
# if {Ture} then looping
'''while (1 >= 0 and 4 > 5):
L[2] = L[1]
j = 0 '''
# if False then keep it in its index.
'''L[j+1] = k ◘◘ As {j+1 = 1}
'''
# ◘ get the integer value of division. » use (//) ▬ for example: {//2}.
'''print(len(L) //2)'''
# ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
# ◙◙ {Merge Sort Algorithm}
#───────────────────────────────────────────────────────────────────────────────────
# ◘ To define this Algorithm we need to pass through some steps:
# ○ α) Divide the main array by its length for sub-arrays.
# ○ ß) Sorting elements.
# ○ Γ) Merging elements in sub-arrays; finally merge sub-arrays to the final form of array.
def mergeSort(array):
if (len(array) > 1):
mid_length = len(array) //2 # ◘ Get the integer number of the length.
# ◙ Dividing the main array to (2) sectors {Right -- Left}..
L = array[:mid_length]
R = array[mid_length:]
# Then Sorting The Right and Left sector Separately.
# ◘◘ The Passed array will be divided till reaching out one element of each array to be compared with.
mergeSort(L)
mergeSort(R)
i = j = k = 0
# ◘ Loop till the reaching the length of both arrays and copying the main array elements
# on both sub-arrays.
# »» On this step: Dividing the main array to {2 arrays}; while one of these arrays
# will contain the smaller valued elements and the other will contain the higher valued elements.
while i < len(L) and j < len(R):
# ○ Comparing with first elements in both arrays.
# » If the left side element is smaller than the right side element.
if (L[i] < R[j]):
# ◘ Replacing the first element in the main arrays with the smaller number.
array[k] = L[i]
i += 1
# » If the Right side element is smaller than the left side element.
else:
array[k] = R[j]
j += 1
k += 1
while i < len(L):
array[k] = L[i]
i += 1
k += 1
while j < len(R):
array[k] = R[j]
j += 1
k += 1
return array
'''print(mergeSort([5,6,1,3,2,7,9,8,4]))'''
#────────────────────────────────────important──────────────────────────────────────
# α)
# ▬▬ Check if a String contains an integer number:
'''x = "asdfas5654asd"
for i in range(len(x)):
try:
if (isinstance(int(x[i]), int)):
print("Integer")
except ValueError:
print("Not Integer")
'''
# ß)
# ▬▬ Inverting string value.
# ◘ Method_1
'''print(string[::-1])'''
# ◘ Method_2
'''x = ""
count = len(string) -1
for i in string:
x += string[count]
count -= 1'''
# Γ)
# ▬▬ getting the absolute number from float value.
'''if int(n) < n:
print(int(n) + 1)
else:
print(n)'''
# Σ)
# ▬▬ using enumerate function; Note that {enumerate} will print a type (list) in a form of dictionary {key and values}.
'''lst = ["GTX 1650","GTX 980","GTX 970","RTX 2070"]
for i,j in enumerate(lst):
print(i,j)
'''
'''
0 GTX 1650
1 GTX 980
2 GTX 970
3 RTX 2070
'''
# σ)
# ▬▬ using {.round()} function that is mainly used to get the nearest decimals according to the past argument.
''' ◘ Note: that while the the parameter passed to this argument is <-number> » That will return the nearest 100 number.
# ╚ For example: x = 5555.456156187 └ print(round(x,-2)) ▬ returns 5600'''
x = -10
y = 5
#print(min(abs(y),abs(x)))
# µ)
# ▬▬ remove an item from a list and add it to an appended new list.
'''
def remove_item(x):
if x == 30:
lst_1.reverse()
lst.append(lst_1)
return False
if x > 30:
lst.remove(x)
lst_1.append(x)
remove_item(x - 1)
return lst
'''
# τ)
# ▬▬ return a key for the specified value in dictionary.
'''def get_required_item(item_1,item_2,item_3):
dictionary = {"GTX 1650":item_1,"RTX 2070":item_2,"RTX 3080":item_3}
for key,value in dictionary.items():
if value:
return key'''
#───────────────────────────────────────────────────────────────────────────────────
# Check your answer
#q6.check()
#print(exactly_one_topping(False,True,False))
'''
l = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]
lst = [x for x in l if x > 4]
print(lst)'''
dic = {"GTX 1650":2900,"GTX 2060":5700,"RTX 3080":2900}
x = 2900
#print(remove_item(40))
#print(lst)
'''
def exactly_one_topping(ketchup, mustard, onion):
"""Return whether the customer wants exactly one of the three available toppings
on their hot dog.
"""
lst = []
topping_dictionary = {"Ketchup":ketchup,"Mustard":mustard,"Onion":onion}
for key, value in topping_dictionary.items():
if value == True:
lst.append(key)
return lst
print(exactly_one_topping(True,True,False))
'''
def select_second(L):
"""Return the second element of the given list. If the list has no second
element, return None.
"""
if len(L) > 2:
return L[1]
else:
return None
|
93981da08850dd74b5752556d1b8f0ede9c75d1d | 6qos/CSE | /notes/venv/Semester 2 Note.py | 346 | 3.921875 | 4 | print("Hello World")
# Cookies
cars = 5
driving = True
print("I have %s cars" % cars)
age = input("How Old Are You?")
print("%s?? Really??"% age)
colors = ["Red", "Blue", "Black", "White"]
colors.append("Cyan")
print(colors)
import string
print(list(string.ascii_letters))
print(string.digits)
print(string.punctuation)
print(string.printable)
|
a284d342205f358abf46a778680e060ac193cc3d | senthilkumarr2212/python | /Day1.py | 876 | 3.96875 | 4 | # Task 1
names = ["john", "jake", "jack", "george", "jenny", "jason"]
for name in names:
if len(name) < 5 and 'e' not in name:
print('Printing Unique Names : ' +name)
# Task 2
str = 'python'
print('c' + str[1:])
# Task 3
dict = {"name": "python", "ext": "py", "creator": "guido"}
print(dict.keys())
print(dict.values())
# Task 4
for i in range(101):
if i % 3 == 0 and i % 5 == 0:
print("fizzbuzz")
elif i % 3 == 0:
print("fizz")
elif i % 5 == 0:
print("buzz")
else:
print("nothing")
# Task 5
guessnum = input("Enter your Guess Number :")
num = 20
if int(guessnum) == num:
print("You guessed correctly")
elif int(guessnum) > num:
print("Your Guess value is greater than the actual number")
else:
print("Your Guess value is less than the actual number")
|
6e12c901e0706b05f3ac67dd2e0c5df3215855bf | gothaur/the_game | /projectile.py | 2,174 | 3.9375 | 4 | import pygame
from pygame.sprite import Sprite
from penguin import Enemy
class Projectile(Sprite):
def __init__(self, settings, penguin, f_img, b_img):
"""
:param penguin: penguin which fired projectile
:param f_img: image faced forward
:param b_img: image faced backward
"""
super().__init__()
self.direction = penguin.move_left
if self.direction:
self.width = b_img.get_width()
self.height = b_img.get_height()
else:
self.width = f_img.get_width()
self.height = f_img.get_height()
if self.direction or type(penguin) == Enemy:
self.x = penguin.x - int(penguin.get_width() * 0.35)
else:
self.x = penguin.x + int(penguin.get_height())
self.y = penguin.y + int(penguin.get_width() * 0.25)
self.penguin = penguin
self.f_img = f_img
self.b_img = b_img
self.settings = settings
self.name = "Projectile"
def draw(self, win):
"""
Draws projectile on the screen
:return: None
"""
if self.direction or type(self.penguin) == Enemy:
image = self.b_img
else:
image = self.f_img
win.blit(image, (self.x, self.y))
def move(self):
"""
Moves projectile on the screen
:return: None
"""
if self.direction or type(self.penguin) == Enemy:
self.x -= (self.penguin.get_vel() + self.settings.bullet_speed)
else:
self.x += self.penguin.get_vel() + 15 + self.settings.bullet_speed
def collide(self, penguin):
"""
Checks if projectile collides with penguin
:param penguin:
:return: True if collided
"""
penguin_mask = penguin.get_mask()
if self.direction or type(penguin) == Enemy:
projectile_mask = pygame.mask.from_surface(self.b_img)
else:
projectile_mask = pygame.mask.from_surface(self.f_img)
offset = (self.x - penguin.get_x(), self.y - penguin.get_y())
return penguin_mask.overlap(projectile_mask, offset)
|
8e4078ae8d366d00cc83fdb60acfed096f252a1e | VINITHAKANDASAMY/python_programming | /hunter/upper.py | 74 | 3.890625 | 4 | list = ['vibi','john','peter']
for item in list:
print(item.upper())
|
90472457e00f25dfca4f589b398a60f47cd311c8 | VINITHAKANDASAMY/python_programming | /player/vowel.py | 151 | 4.03125 | 4 | v1=input("enter an alphabet")
if v1 in ('a','e','i','o','u'):
print("given alphabet is vowel")
else:
print("given alphabet is consonant")
|
ce9090dbbbc2431d045c37550b6704403938a23b | justinchoys/learn_python | /ex43.py | 2,904 | 3.75 | 4 | from sys import exit
from random import randint
from textwrap import dedent
class Scene(object):
def enter(self):
print("This is not a configured scene, use a subclass")
exit(1)
class Engine(object):
def __init__(self, scene_map):
self.scene_map = scene_map
def play(self):
current_scene = self.scene_map.opening_scene()
last_scene = self.scene_map.next_scene('finished')
while current_scene != last_scene: #check if current scene is the ending
next_scene_name = current_scene.enter() #enter current scene and get return value
current_scene = self.scene_map.next_scene(next_scene_name) #use return value to update current scene
class Death(Scene):
def enter(self):
print("You are dead")
exit(1)
pass
class CentralCorridor(Scene):
def enter(self):
n = input("You enter the central corridor, Shoot, Dodge, or Tell Joke:")
if n == "Shoot":
return 'death'
elif n == "Dodge":
return 'death'
elif n == "Tell Joke":
return 'laser_weapon_armory'
else:
print("does not compute")
return 'central_corridor'
class LaserWeaponArmory(Scene):
def enter(self):
print("You enter the laser weapon armory, you have 10 guesses for 3 digit code:")
code = f"{randint(1,9)}{randint(1,9)}{randint(1,9)}"
guess = input("[keypad]> ")
guesses = 0
print(f"The code is actually {code}")
while guess != code and guesses < 10:
print("WRONG")
guesses += 1
guess = input("[keypad]> ")
if guess == code:
print("You got the code correct")
return 'the_bridge'
else:
print("you got the code wrong")
return 'death'
class TheBridge(Scene):
def enter(self):
n = input("You enter the bridge, throw bomb or place bomb")
if n == 'throw bomb':
print("You threw the bomb and died")
return 'death'
elif n == 'place bomb':
print("You place bomb and continue")
return 'escape_pod'
else:
print("does not compute")
return 'the_bridge'
class EscapePod(Scene):
def enter(self):
print("You enter the escape pod room")
x = randint(1, 3) #generate random number 1, 2, or 3
n = int(input("You choose a door from 1-3"))
if n == x:
print("You choose the correct door and escape")
return 'finished'
else:
print("You choose the wrong door...")
return 'death'
class Finished(Scene):
def enter(self):
print("You finish the game")
return 'finished'
class Map(object):
scenes = {
'central_corridor': CentralCorridor(),
'laser_weapon_armory': LaserWeaponArmory(),
'the_bridge' : TheBridge(),
'escape_pod' : EscapePod(),
'death' : Death(),
'finished':Finished(),
}
def __init__(self, start_scene):
self.start_scene = start_scene
def next_scene(self, scene_name):
val = Map.scenes.get(scene_name) #return None if doesn't exist in dict
return val
def opening_scene(self):
return self.next_scene(self.start_scene)
a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play() |
3ff0b5ab4f45e5763fcc28aef525111e513cd5e9 | maisuto/address | /takeaddress.py | 929 | 3.671875 | 4 | # -*- coding: utf-8 -*-
# !/usr/bin/env python
from makeaddress import MakeAddress
class TakeAddress(MakeAddress):
def make_new_csv(self, csvdic):
newcsv = []
top_list = [
'name',
'phone',
'mobile_pyone',
'zip code',
'address'
]
newcsv.append(top_list)
for i in csvdic:
line = []
line.append(" ".join((i['lastname'], i['firstname'])))
line.append(":".join(("TEL", i['phone'])))
line.append(":".join(("MOBILE", i['mobilephone'])))
line.append(":".join(("〒", i['zip code'])))
line.append("".join((i['address1'], i['address2'], i['address3'])))
newcsv.append(line)
return newcsv
if __name__ == '__main__':
test = TakeAddress("addresslist.csv")
test.write_csv("takeaddress_new.csv")
|
edace158002f255b7bbfd8d5708575912ab065d9 | Varsha1230/python-programs | /ch4_list_and_tuples/ch4_lists_and_tuples.py | 352 | 4.1875 | 4 | #create a list using[]---------------------------
a=[1,2,4,56,6]
#print the list using print() function-----------
print(a)
#Access using index using a[0], a[1], a[2]
print(a[2])
#change the value of list using------------------------
a[0]=98
print(a)
#we can also create a list with items of diff. data types
c=[45, "Harry", False, 6.9]
print(c)
|
ccade5b4083c03f67193c304ed68f470f91ec980 | Varsha1230/python-programs | /ch11_inheritance.py/ch11_3_multiple_inheritance.py | 496 | 3.875 | 4 | class Employee:
company = "visa"
eCode = 120
class Freelancer:
company = "fiverr"
level = 0
def upgradeLevel(self):
self.level =self.level + 1
class Programmer(Employee, Freelancer): #multiple inheritance
name = "Rohit"
p = Programmer()
print(p.level)
p.upgradeLevel()
print(p.level)
print(p.company) #what will be printed... due to this line---> ans:--> "visa", bcoz when we define child class then, we inherit employee-class first then freelancer-class
|
a12737d07ea5a4ac4268d50070a09be8018fd499 | Varsha1230/python-programs | /ch2_variables_and_dataType/ch2_prob_04_comparision_operator.py | 138 | 3.796875 | 4 | # use comparision operator to find out whether a given variable 'a' is greater than 'b' or not... take a=34 and b=80
a=34
b=80
print(a>b) |
194b4560ae2532e13e65a0f4b3664149578c3293 | Varsha1230/python-programs | /ch13_advance_python2.py/ch13_3_format.py | 265 | 3.640625 | 4 | name = "Harry"
channel = "Code with harry"
type = "coding"
#a = f"this is {name}"
#a = "this is {}" .format(name)
# a = "this is {} and his channel is {}" .format(name, channel)
a = "this is {0} and his {2} channel is {1}".format(name, channel, type)
print(a) |
360ec7c1039125c324248437f72dc44eb56d59a5 | Varsha1230/python-programs | /ch8_functions_and_recursion.py/ch8_prob_04.py | 580 | 3.953125 | 4 | # n! = (n-1)! * n
# sum(n) = sum(n-1) + n
#-- there is no exit/stop statement in this loop------------------------------------------------
# def sum(n):
# return (sum(n-1) + n)
# num = int(input("please enter a no.: "))
# add = sum(num)
# print("the sum of n natural numbers is: " + str(add))
#--------------------------------------------------------------------
def sum(n):
if n==1 :
return 1
else :
return n + sum(n-1)
m=int(input("Enter a natural number : "))
x=sum(m)
print("The sum of first " + str(m)+ " natural number is "+ str(x)) |
2765a047df4e0eace928604f2d0dd53cafb7e36f | Varsha1230/python-programs | /ch6_conditional_expressions.py/ch6_prob_05.py | 181 | 3.984375 | 4 | l1 = ["varsha", "ankur", "namrata"]
name = input("please enter your name:\n")
if name in l1:
print("your name is in the list")
else:
print("your name is not in the list") |
e05e4075af111c11cfe2b2f55dfc46ae0c13aa3d | Varsha1230/python-programs | /ch11_inheritance.py/ch11_6_class_method.py | 508 | 3.703125 | 4 | class Employee:
company = "camel" # class-attribute
location = "Delhi" # class-attribute
salary = 100 # class-attribute
# def changeSalary(self, sal):
# self.__class__.salary = sal # dunder class (we can use this for same task,but it is related to object, here oue motive is just use the class method only)
@classmethod
def changeSalary(cls, sal):
cls.salary = sal
e = Employee()
print(e.salary)
e.changeSalary(455)
print(e.salary)
print(Employee.salary) |
5e8c0be79943cb840b77adfc98efbb1664d09972 | Varsha1230/python-programs | /ch6_conditional_expressions.py/ch6_5_logical_operator.py | 229 | 3.96875 | 4 | age=int(input("enter your age: "))
if(age>34 and age<56):
print("you can work with us")
else:
print("you can't work with us")
print("Done")
if(age>34 or age<56):
print("you can with us")
else:
print("djvbvjnd") |
c43b35b690a329f582683f9b406a66c826e5cabf | Varsha1230/python-programs | /ch3_strings/ch3_prob_01.py | 435 | 4.3125 | 4 | #display a user entered name followed by Good Afternoon using input() function--------------
greeting="Good Afternoon,"
a=input("enter a name to whom you want to wish:")
print(greeting+a)
# second way------------------------------------------------
name=input("enter your name:")
print("Good Afternoon," +name)
#-----------------------------------------------------
name=input("enter your name:\n")
print("Good Afternoon," +name) |
5b3ef497693bc27e3d5fee58a9a77867b8f18811 | Varsha1230/python-programs | /ch11_inheritance.py/ch11_1_inheritance.py | 731 | 4.125 | 4 | class Employee: #parent/base class
company = "Google"
def showDetails(self):
print("this is an employee")
class Programmer(Employee): #child/derived class
language = "python"
# company = "YouTube"
def getLanguage(self):
print("the language is {self.language}")
def showDetails(self): #overwrite showDetails()-fn of class "Employee"
print("this is an programmer")
e = Employee() # object-creation
e.showDetails() # fn-call by using object of class employee
p = Programmer() # object-creation
p.showDetails() # fn-call by using object of class programmer
print(p.company) # using claas-employee's attribute by using the object of class programmer
|
d6fd821221299ad77efb685c4c82b4b485bec16d | vivek-2000/DSA | /Array/K_sorted_array.py | 401 | 3.53125 | 4 | from heapq import heappop, heappush, heapify
def sort_k(arr,n,k):
heap=arr[:k+1]
heapify(heap)
tar_ind=0
for rem_elmnts_index in range(k+1,n):
arr[tar_ind]=heappop(heap)
heappush(heap, arr[rem_elmnts_index])
tar_ind+=1
while heap:
arr[tar_ind]=heappop(heap)
tar_ind+=1
k=3
arr=[2,6,3,12,56,8]
n=len(arr)
sort_k(arr,n,k)
print(arr)
#time complexity [nlogk] |
4d669245dc188f77447bac45eaa554bba7feab52 | BestNico/Leetcode_answer | /1431/1431.py | 288 | 3.625 | 4 | from typing import List
class Solution(object):
def kidWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
biggestEle = max(candies)
subList = [biggestEle - i for i in candies]
return [True if i <= extraCandies else False for i in subList] |
b4591e299bcaa0f177ab2da26aaa98dd3599321f | AprilLJX/LJX-also-needs-to-earn-big-money | /code-offer/no21reOrderOddEven.py | 1,064 | 3.640625 | 4 | def reOrderOddEven_1(str):
length = len(str)
if length == 0:
return
i = 0
j = length - 1
while i < j:
#前面的为奇数,遇到偶数停止
while i < j and (str[i] & 0x1) != 0:
i += 1
while i < j and (str[j] & 0x1) == 0:
j -= 1
if i < j:
temp = str[j]
str[j] = str[i]
str[i] = temp
return str
# 测试用例
def printArray(str,length):
if length <= 0 :
return
for i in range(0,length):
print(str[i],end='')
print("\t")
def Test(name,str,length):
if len(name) != 0:
print(name+"bagin")
printArray(str,length)
str = reOrderOddEven_1(str)
printArray(str,length)
if __name__ == '__main__':
str1 = [1, 2, 3, 4, 5, 6, 7]
str2 = [2, 4, 6, 1, 3, 5, 7]
str3 = [1, 3, 5, 7, 2, 4, 6]
str4 = [1]
str5 = [2]
str6 = []
Test("test1",str1,7)
Test("test2",str2,7)
Test("test3",str3,7)
Test("test4",str4,1)
Test("test5",str5,1)
Test("test6",str6,0)
|
dff95a393d887cc6f44d3480f02dc8064e71bdc0 | AprilLJX/LJX-also-needs-to-earn-big-money | /code-offer/no40getLeastNumbers.py | 538 | 3.75 | 4 | import maxHeap
def getLeastNumbers(arr,k):
if not k or not arr or k < 1 or len(arr) < k :
return
heap = maxHeap.MaxHeap(arr[:k])
for item in arr[k:]:
if item < heap.data[0]:
heap.extractMax()
heap.insert(item)
for item in heap.data:
print(item)
if __name__ == "__main__":
# arr1 = [4, 5, 1, 6, 2, 7, 3, 8]
# getLeastNumbers(arr1,4)
arr2 = [4, 5, 1, 6, 2, 7, 3, 8]
getLeastNumbers(arr2,None)
# arr3=[4, 5, 1, 6, 2, 7, 2, 8]
# getLeastNumbers(arr2,2) |
40ceb70ecc8460fff034f6bbc53cc7cba2267938 | AprilLJX/LJX-also-needs-to-earn-big-money | /code-offer/no42findGreatestSumOfSubArray.py | 400 | 3.640625 | 4 | def findSubarray(nums):
invalidInput = False
if not nums or len(nums) <= 0:
invalidInput = True
return 0
invalidInput = False
curSum = 0
greastestSum = float('-inf')
for i in nums:
if curSum < 0:
curSum = i
else:
curSum += i
if curSum > greastestSum:
greastestSum = curSum
return greastestSum |
fc39fba8f6f26ad7ed138dd93379482053578c20 | AprilLJX/LJX-also-needs-to-earn-big-money | /code-offer/no53getFirstK.py | 1,411 | 4 | 4 | # 巧用二分查找在排序数组中找一个特定数字
def getNumberOfK(data,length,k):
number = 0
if data and length > 0:
first = getFirstK(data,length,k,0,length-1)
last = getLastK(data,length,k,0,length-1)
if first > -1 and last > -1:
number = last - first +1
return number
def getFirstK(data,length,k,start,end):
if start > end:
return -1
middleIndex = (start+end)//2
middleData = data[middleIndex]
if middleData == k:
if (middleIndex > 0 and data[middleIndex-1] != k) or middleIndex == 0:
return middleIndex
else:
end = middleIndex - 1
elif middleData > k:
end = middleIndex - 1
else:
start = middleIndex + 1
return getFirstK(data,length,k,start,end)
def getLastK(data,length,k,start,end):
if start > end:
return -1
middleIndex = (start+end)//2
middleData = data[middleIndex]
if middleData == k:
p = data[middleIndex+1]
if (middleIndex < length -1 and data[middleIndex+1]!=k) or middleIndex == length-1:
return middleIndex
else:
start = middleIndex + 1
elif middleData > k:
end = middleIndex - 1
else:
start = middleIndex + 1
middleIndex = getLastK(data,length,k,start,end)
return middleIndex
data = [3,3,3,3,4,5]
print(getNumberOfK(data,6,3))
|
29d80bdd038da385e916ebd1a02a0e200f9b7378 | AprilLJX/LJX-also-needs-to-earn-big-money | /code-offer/no7reconstructBiTreev2.py | 4,501 | 3.75 | 4 | class BinaryTree:
def __init__(self,rootObj):
self.key = rootObj
self.rightChild = None
self.leftChild = None
def insertLeftChild(self,newNode):
if self.leftChild == None:
self.leftChild = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
t.leftChild = self.leftChild
self.leftChild = t
def insertRightChild(self,newNode):
if self.rightChild == None:
self.rightChild = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
t.rightChild = self.rightChild
self.rightChild = t
def getRightChild(self):
return self.rightChild
def getLeftChild(self):
return self.leftChild
def setRootVal(self,obj):
self.key = obj
def getRootVal(self):
if self == None:
return -1
return self.key
def printPreTree(self):
if self == None:return
print(self.key,end=' ')
if self.leftChild :
self.leftChild.printPreTree()
if self.rightChild:
self.rightChild.printPreTree()
def printInTree(self):
if self == None: return
if self.leftChild:
self.leftChild.printInTree()
print(self.key, end=' ')
if self.rightChild:
self.rightChild.printInTree()
# def construct(preorder:list,inorder:list,length:int):
# if preorder == None or inorder == None or length <= 0:
# return None
# stratPreorder = 0
# endPreorder = stratPreorder +length -1
# startInorder = 0
# endInorder = startInorder + length -1
# return constructCore(preorder,stratPreorder,endPreorder,inorder,startInorder,endInorder)
#
# def constructCore(preorderList,startPreorder,endPreorder,inorderList,startInorder,endInorder):
#
# #前序遍历的第一个数字是根结点的值
# rootValue = preorderList[startPreorder]
# root = BinaryTree(rootValue)
#
#
# if startPreorder == endPreorder:
# if startInorder == endInorder and preorderList[startPreorder] == inorderList[startInorder]:
# return root
# else:
# print("invalid input")
#
# #在中序遍历序列中找到根结点的值
# rootInorder = startInorder
# while rootInorder <= endInorder and inorderList[rootInorder] != rootValue:
# rootInorder += 1
#
# if rootInorder == endInorder and inorderList[rootInorder] != rootValue:
# print("invalid input")
#
# leftLength = rootInorder - startInorder
# leftPreorderEnd = startPreorder + leftLength
#
# if leftLength > 0:
# #构建左子树
# root.leftChild = constructCore(preorderList,startPreorder+1,leftPreorderEnd,
# inorderList,startInorder,rootInorder-1)
#
# if leftLength < endPreorder - startPreorder:
# #构建右子树
# root.rightChild = constructCore(preorderList,leftPreorderEnd+1,endPreorder,
# inorderList,rootInorder+1,endInorder)
# print('\ntest:')
# root.printPreTree()
# return root
def buildTree(preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
if len(inorder) == 0:
return None
# 前序遍历第一个值为根节点
root = BinaryTree(preorder[0])
# 因为没有重复元素,所以可以直接根据值来查找根节点在中序遍历中的位置
mid = inorder.index(preorder[0])
# 构建左子树
root.leftChild = buildTree(preorder[1:mid + 1], inorder[:mid])
# 构建右子树
root.rightChild = buildTree(preorder[mid + 1:], inorder[mid + 1:])
print("\ntest:")
root.printPreTree()
return root
def test(testName:str,preorder:list,inorder:list,length:int):
print(testName +"begins:")
print("the preorder sequence is:")
for i in preorder:
print(i,end='')
print("\nthe inorder sequence is:")
for i in inorder:
print(i,end='')
#root = construct(preorder,inorder,length)
root = buildTree(preorder,inorder)
print("\npreorder:")
root.printInTree()
print("\ninorder:")
root.printPreTree()
def test1():
length = 8
preorder = [1, 2, 4, 7, 3, 5, 6, 8]
inorder = [4, 7, 2, 1, 5, 3, 8, 6]
test("test1",preorder,inorder,length)
if __name__=="__main__":
test1()
|
a806ec1eaa2bd542dda64e9dfee12847b32771c1 | AprilLJX/LJX-also-needs-to-earn-big-money | /code-offer/no14cutstring.py | 1,020 | 3.609375 | 4 | #大问题->小问题->小问题最优解组合->大问题最优解----->可以用动态规划
def maxProductAfterCutting_DP(length):
if length <2:
return 0
if length == 2:
return 1
if length == 3:
return 2
products = [0,1,2,3]
max = 0
for i in range(4,length+1):
max = 0
products.append(0)
for j in range(1,i//2+1):
product = products[j] * products[i-j]
if max < product:
max = product
products[i] = max
max = products[length]
return max
def maxProductAfterCutting_TX(length):
if length <2:
return 0
if length == 2:
return 1
if length == 3:
return 2
timesOf3 = length//3
if (length - timesOf3 * 3 == 1):
# timesOf3 -= 1
timesOf2 = 2
# timesOf2 = (length - timesOf3 * 3)//2
timesOf2 = 1
return int(pow(3,timesOf3)) * int(pow(2,timesOf2))
print(maxProductAfterCutting_DP(8))
print(maxProductAfterCutting_TX(8)) |
b03562bddb37cc22ce4c2aba658d8c368becb2c0 | AprilLJX/LJX-also-needs-to-earn-big-money | /code-offer/no39moreThanHalfNum_1.py | 499 | 3.546875 | 4 | def MoreThanHalfNum(numbers,length):
# 判断输入符合要求
if not numbers and length<=0:
return 0
result = numbers[0]
times = 1
for i in range(1,length):
if times == 0:
result = numbers[i]
times = 1
elif numbers[i] == result:
times += 1
else:
times -= 1
sum = 0
for item in numbers:
if item == result:
sum += 1
return result if sum*2 > length else 0
#21ms5752k |
266cab3b9773bbca24a1449cd305e27e3b82ab59 | AprilLJX/LJX-also-needs-to-earn-big-money | /code-offer/no55isBalanced2.py | 531 | 3.78125 | 4 | def isBalanced(proot,depth):
if not proot:
depth = 0
return True
leftDepth = rightDepth = -1
# 递归,一步步往下判断左右是否是平衡树,不是就返回,是的话记录当前的深度
if isBalanced(proot.left,leftDepth) and isBalanced(proot.right,rightDepth):
diff = leftDepth - rightDepth
if diff <= 1 and diff >= -1:
depth = max(leftDepth,rightDepth)+1
return True
return False
def isBalanced(proot):
return isBalanced(proot,0)
|
4d834531037456b1cac14a8fb3d72df707764355 | AprilLJX/LJX-also-needs-to-earn-big-money | /code-offer/no17print_n_num_v2.py | 1,616 | 3.625 | 4 | def PrintToMAxDIgits(n):
if n <= 0:
return
number = [0]*(n)
while(not Increment(number)):
PrintNumber(number)
def Increment(number:[int]):
isOverflow = False
nTakeOver = 0
length = len(number)
#每一轮只计一个数,这个循环存在的意义仅在于判断是否有进位,如有进位,高位就可以加nTakeove
# 以isOverflow判断是否最高位进位,最高位进位则溢出,整个结束输出。
for i in range(length-1,-1,-1):
nSum = number[i] + nTakeOver
if i == length -1:
nSum += 1
if nSum >= 10:
if i == 0:
isOverflow = True
else:
nSum -= 10
nTakeOver = 1
number[i] = nSum
else:
number[i] = nSum
break
return isOverflow
def ifIncrement(number):
isOverflow = False
nTakeOver = 0
length = len(number)-1
for i in range(length,-1,-1):
nSum = number[i] + nTakeOver
if i == length:
nSum += 1
if nSum >= 10:
if i == 0:
isOverflow = True
else:
nSum -= 10
number[i] = nSum
nTakeOver = 1
else:
number[i] = nSum
break
return isOverflow
def PrintNumber(number:[int]):
isBegining = True
for i in range(0,len(number)):
if isBegining and number[i] != 0:
isBegining = False
if not isBegining:
print(number[i],end='')
print("\n")
PrintToMAxDIgits(2) |
a2dc98deb96601ebc3b9643d539a31d7835853cc | AprilLJX/LJX-also-needs-to-earn-big-money | /code-offer/no34findPath.py | 1,041 | 3.703125 | 4 | # 找到二叉树中某一值和的路径
def findPath(root,expectedSum):
if not root:
return []
result = []
def findPathCore(root,path,currentSum):
currentSum += root.val
path.append(root)
ifLeaf = not (root.left or root.right)
# 是叶子节点,且和为目标和
if ifLeaf and currentSum==expectedSum:
# result.append(path) 这里要加入节点的值,不能直接加入节点
tempPath = []
for node in path:
tempPath.append(node.val)
result.append(tempPath)
# 是叶子节点,和大于目标和,直接pop,不是叶子节点同理
# 不是叶子节点且和小于目标和,遍历其左右子树
if (not ifLeaf) and currentSum<expectedSum:
if root.left:
findPathCore(root.left,path,currentSum)
if root.right:
findPathCore(root.right,path,currentSum)
path.pop()
findPathCore(root,[],0)
return result
|
f1e92e70cfd8d1757967e5ff3d56883ac269227a | AprilLJX/LJX-also-needs-to-earn-big-money | /code-offer/no16pow.py | 1,535 | 3.796875 | 4 | class Solution:
g_Invalid_input = False
def power(self,base,exponent):
if base == 0 and exponent < 0:
self.g_Invalid_input = True
return 0
absExponent = exponent
if exponent < 0:
absExponent = -exponent
result = self.powerCal_2(base,absExponent)
if exponent < 0:
result = 1 / result
return result
def powerCal(self,base,exponent):
result = 1
for i in range(0,exponent):
result *= base
return result
def powerCal_2(self,base,exponent):
if exponent == 0:
return 1
if exponent == 1:
return base
result = self.powerCal_2(base,exponent>>1)
result *= result
#判断奇偶
if exponent & 0x1 == 1:
result *= base
return result
def Test(self,base,exponent,expected,inputerror):
if self.power(base,exponent) == expected and inputerror == self.g_Invalid_input:
print("passed")
else:
print("failed")
if __name__ == '__main__':
s = Solution()
# 底数、指数都为正数
s.Test(2, 3, 8, False)
#底数为负数、指数为正数
s.Test(-2, 3, -8, False)
#指数为负数
s.Test( 2, -3, 0.125, False)
#指数为0
s.Test(2, 0, 1, False)
#底数、指数都为0
s.Test(0, 0, 1, False)
#底数为0、指数为正数
s.Test(0, 4, 0, False)
#底数为0、指数为负数
s.Test(0, -4, 0, True)
|
1c424c81442732b5b5c2d7616919ac81bc4dfcd2 | mittgaurav/Pietone | /power_a_to_b.py | 637 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 3 13:57:40 2019
@author: gaurav
cache half power results. O(log n)
"""
def power(a, b):
"""power without pow() under O(b)"""
print("getting power of", a, "for", b)
if a == 0:
return 0
if b == 1:
return a
elif b == 0:
return 1
elif b < 0:
return 1 / power(a, -b)
else: # positive >1 integer
half_res = power(a, b // 2)
ret = half_res * half_res
if b % 2: # odd power
ret *= a
return ret
for A, B in [(4, 5), (2, 3), (2, -6), (12, 4)]:
print(A, B, ":", pow(A, B), power(A, B))
|
0042a3255312843743e1e257face5599acc063d8 | mittgaurav/Pietone | /skyline.py | 5,927 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 16 22:56:07 2019
@author: gaurav
"""
# NOT CORRECT
# NOT CORRECT
# NOT CORRECT
# NOT CORRECT
def skyline(arr):
"""A skyline for given
building dimensions"""
now = 0
while now < len(arr):
start, height, end = arr[now]
print(start, height)
nxt = now + 1
while nxt < len(arr): # ignore short and small
n_start, n_height, n_end = arr[nxt]
# next building is far away, so read
if n_start >= end:
break
# next building is big, so we take it
if n_height > height:
now = nxt
if end > n_end: # Add my remains
arr.insert(nxt, (n_end, height, end))
now -= 1
break
# next building is small but longer
# so keep what'll remain after this
if n_end > end:
arr[nxt] = (end, n_height, n_end)
break
nxt += 1
now += 1
now += 1
A = [(1, 10, 4),
(2, 5, 3),
(2.5, 5, 8),
(3, 15, 8),
(6, 9, 11),
(10, 12, 15),
(18, 12, 22),
(20, 8, 25)]
print("====", skyline.__name__)
skyline(A)
def rain_water(arr):
"""collect rain water in
different size building"""
if not arr:
return 0
# for i, max on right and left
left, right = [], []
# collect max on the left side
curr_max = 0
for i in arr:
left.append(curr_max)
curr_max = max(curr_max, i)
# collect max on the right side
curr_max = 0
for i in reversed(arr):
right.insert(0, curr_max)
curr_max = max(curr_max, i)
# for each i, get its difference to min of l/r
res = [max(0, min(_l, _r)-i) for _l, _r, i in
zip(left, right, arr)]
return sum(res)
print("====", rain_water.__name__)
print(rain_water([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]))
def merge_intervals(intervals):
"""merge overlap-
ping intervals"""
out = []
if not intervals:
return out
start, end = intervals[0]
for new_start, new_end in intervals[1:]:
if new_start <= end: # overlapping elements
end = max(end, new_end)
else: # New is after end. There's gap between
# current element end and next start; end
# right now and collect this into result
out.append((start, end))
start, end = new_start, new_end
out.append((start, end))
return out
print("====", merge_intervals.__name__)
print(merge_intervals([[1, 3], [2, 6], [4, 5], [8, 10], [15, 18]]))
print(merge_intervals([[1, 4], [4, 5]]))
def overlapping_intervals(intervals):
"""more than one running"""
out = []
if not intervals:
return out
prev_start, prev_end = 0, 0
for start, end in intervals:
# we have taken care of this later
# by considering all four cases.
start = max(start, prev_start)
if end < start:
# for shorter interval after
continue
if start < prev_end:
if end < prev_end:
out.append((start, end))
prev_start = end
else:
out.append((start, prev_end))
prev_start = prev_end
prev_end = end
else:
prev_start, prev_end = start, end
# we may have some overlapping intervals.
out = merge_intervals(out)
return out
print("====", overlapping_intervals.__name__)
print(overlapping_intervals([[1, 3], [2, 6], [4, 5], [8, 10]]))
print(overlapping_intervals([[1, 7], [2, 6], [4, 5], [8, 10]]))
print(overlapping_intervals([[1, 7], [2, 6], [6, 7], [8, 10]]))
print(overlapping_intervals([[1, 7], [2, 6], [5, 6], [6, 8]]))
print(overlapping_intervals([[1, 6], [2, 8], [3, 10], [5, 8]]))
print(overlapping_intervals([[1, 4], [4, 5]]))
def intersection_intervals(intervals):
"""simple: intersection of all"""
out = []
max_start = min([_[0] for _ in intervals])
min_end = max([_[1] for _ in intervals])
for start, end in intervals:
max_start = max(max_start, start)
min_end = min(min_end, end)
if min_end > max_start:
out.append((max_start, min_end))
return out
print("====", intersection_intervals.__name__)
print(intersection_intervals([[1, 3], [2, 6], [4, 5], [8, 10]]))
print(intersection_intervals([[1, 6], [2, 8], [3, 10], [5, 8]]))
def main(dict_bank_list_of_times):
"""
Bank hours problem
Given a list of banks opening hours, determine
the hours when there is at least one open bank
This is useful to determine when it's possible
to submit an order into a trading system.
Example
JPDL: 8-12 13-17
BARX: 9-13 14-18
Result: 8-18
"""
times = []
for bank_times in dict_bank_list_of_times.values():
times.extend(bank_times)
times.sort(key=lambda x: x[0])
print(merge_intervals(times))
print("==== bank_open_times")
main({"JPDL": [(8, 12), (13, 17)], "BARX": [(9, 13), (14, 18)]})
main({"JPDL": [(8, 12), (13, 17)], "BARX": [(9, 13), (19, 20)]})
main({"JPDL": [(8, 12), (13, 17), (19, 19)], "BARX": [(9, 13)]})
main({"JPDL": [(8, 12), (13, 17), (19, 19)], "BARX": []})
main({})
def total_time(arr):
"""tell total time that user
watched tv, given blocks"""
if not arr:
return 0
arr.sort(key=lambda x: x[0])
max_end = 0
time = 0
for start, end in arr:
assert start <= end
start = max(start, max_end) # start within max_end?
time += max(0, end - start) # end > start but is it > max_end
max_end = max(max_end, end) # for the next
return time
print("====", total_time.__name__)
print(total_time([[10, 20], [15, 25]]))
print(total_time([[10, 20], [22, 25]]))
print(total_time([[10, 20], [1, 25]]))
|
7d4cb2013282e283ff91dd0762490ff962b5eeec | mittgaurav/Pietone | /common_elem_n_arrays.py | 1,938 | 3.921875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 28 02:00:55 2019
@author: gaurav
"""
def common_elem_in_n_sorted_arrays(arrays):
"""find the common elements in
n sorted arrays without using
extra memory"""
if not arrays:
return []
result = []
first = arrays[0]
for i in first: # for each element
are_equal = True
# match first arr's elements
# with each arrays' elements
# and based on whether first
# element is ==, >, or <, we
# take appropriate step. And
# if all match, store elem.
for array in arrays[1:]:
if not array:
# any array has been consumed
return result
if i == array[0]:
array.pop(0)
elif i > array[0]:
# bring array up to level of first
while array and array[0] < i:
array.pop(0)
# somehow array does have that elem
if array and array[0] == i:
array.pop(0)
else:
are_equal = False
else: # first[i] < array[0]
# first is smaller, break
# and take the next first
are_equal = False
break
if are_equal:
result.append(i)
return result
ARR = [
[10, 160, 200, 500, 500],
[4, 150, 160, 170, 500],
[2, 160, 200, 202, 203],
[3, 150, 155, 160, 300],
[3, 150, 155, 160, 301]
]
print(common_elem_in_n_sorted_arrays(ARR))
ARR = [
[23, 24, 34, 67, 89, 123, 566, 1000, 1224],
[11, 22, 23, 24, 33, 37, 185, 566, 987, 1223, 1224, 1234],
[23, 24, 43, 67, 98, 566, 678, 1224],
[1, 4, 5, 23, 24, 34, 76, 87, 132, 566, 665, 1224],
[1, 2, 3, 23, 24, 344, 566, 1224]
]
print(common_elem_in_n_sorted_arrays(ARR))
|
7bad8a4482385e6b355d8cd9bd3e303c6c8e8ed5 | mittgaurav/Pietone | /sudoku.py | 2,787 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun May 10 02:12:35 2020
@author: gaurav
"""
import math
from functools import reduce
from operator import add
board = [
[4, 3, 0, 0],
[1, 2, 3, 0],
[0, 0, 2, 0],
[2, 1, 0, 0]
]
def _check(board, full=False):
N = len(board)
def _inner(r):
vals = [x for x in r if x != 0] # non-zero elements
if full:
# contain all elements up to N
if sorted(vals) != list(range(1, N + 1)):
return False
else:
# no value below 1 and no value above N
if [x for x in vals if x <= 0 or x > N]:
return False
# all unique
if len(vals) != len(set(vals)):
return False
return True
for i in range(N):
# row and column
for r in (board[i], [x[i] for x in board]):
if not _inner(r):
return False
# each sub-matrix is sqrt(N)
sqrt = int(math.sqrt(N))
for i in range(0, N, sqrt):
for j in range(0, N, sqrt):
cells = reduce(add,
[r[j:j+sqrt] for r in board[i:i+sqrt]], [])
if not _inner(cells):
return False
return True
def solve_sudoku(board):
N = len(board)
def _solve(cell):
"""choose - constraint - goal"""
if cell >= N * N: # goal
print('solution')
[print(_) for _ in board]
return True if _check(board, True) else False
r, c = cell // N, cell % N
if board[r][c] != 0:
# cell is already filled. go to next
return _solve(cell + 1)
for i in range(1, len(board) + 1):
# choose
board[r][c] = i
# constraint
if _check(board):
# recurse
_solve(cell + 1)
# undo
board[r][c] = 0
_solve(0)
[print(_) for _ in board]
solve_sudoku(board)
board = [
[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2, 8, 0],
[0, 0, 0, 4, 1, 9, 0, 0, 5],
[0, 0, 0, 0, 8, 0, 0, 7, 9]
]
solve_sudoku(board)
grid = []
grid.append([3, 0, 6, 5, 0, 8, 4, 0, 0])
grid.append([5, 2, 0, 0, 0, 0, 0, 0, 0])
grid.append([0, 8, 7, 0, 0, 0, 0, 3, 1])
grid.append([0, 0, 3, 0, 1, 0, 0, 8, 0])
grid.append([9, 0, 0, 8, 6, 3, 0, 0, 5])
grid.append([0, 5, 0, 0, 9, 0, 6, 0, 0])
grid.append([1, 3, 0, 0, 0, 0, 2, 5, 0])
grid.append([0, 0, 0, 0, 0, 0, 0, 7, 4])
grid.append([0, 0, 5, 2, 0, 6, 3, 0, 0])
solve_sudoku(grid)
|
853936e6f2e717da65ad845d1e7cfef1b52d630d | mittgaurav/Pietone | /wildcard_pattern_matching.py | 2,518 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 8 19:24:26 2018
@author: gaurav
"""
def wildcard_matching_no_dp(string, pat):
"""tell whether pattern represents
string as wildcard. '*' and '?'"""
if not pat:
return not string
if not string:
for i in pat:
if i is not '*':
return False
return True
# Either char matched or any char
if string[0] == pat[0] or pat[0] == '?':
return wildcard_matching_no_dp(string[1:], pat[1:])
# Not a wildcard, and no char match
if pat[0] != '*':
return False
# wildcard (*)
# remove current char or
# remove current char and * or
# remove *
return (wildcard_matching_no_dp(string[1:], pat) or
wildcard_matching_no_dp(string[1:], pat[1:]) or
wildcard_matching_no_dp(string, pat[1:]))
def get(matrix, i, j):
if i >= len(matrix) or i < 0:
return True
if j >= len(matrix[0]) or j < 0:
return True
return matrix[i][j]
def wildcard_matching_dp(string, pat):
"""memoization"""
if not pat:
return not string
if not string:
for i in pat:
if i is not '*':
return False
return True
# fill to prevent out of index
matrix = list()
for i in range(0, len(string)):
matrix.append(list())
for j in range(0, len(pat)):
matrix[i].append(False)
# Fill matrix from end.
for i in range(len(string)-1, -1, -1):
for j in range(len(pat)-1, -1, -1):
if string[i] == pat[j] or pat[j] == '?':
matrix[i][j] = get(matrix, i+1, j+1)
elif pat[j] != '*':
matrix[i][j] = False
else:
matrix[i][j] = (get(matrix, i+1, j) or
get(matrix, i+1, j+1) or
get(matrix, i, j+1))
return matrix[0][0]
wildcard_matching = wildcard_matching_dp
wildcard_matching = wildcard_matching_no_dp
print(wildcard_matching("", ""))
print(wildcard_matching("", "**"))
print(wildcard_matching("a", "")) # False
print(wildcard_matching("a", "a"))
string = "baaabab"
print(wildcard_matching(string, "***"))
print(wildcard_matching(string, "a*ab")) # False
print(wildcard_matching(string, "ba*a?"))
print(wildcard_matching(string, "baaa?ab"))
print(wildcard_matching(string, "*****ba*****ab"))
|
9119084ee6a7f510f481c56f72d6524edbaefe58 | mittgaurav/Pietone | /battleship.py | 1,820 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 22 13:05:37 2020
leetcode.com/discuss/interview-question/538068/
@author: gaurav
"""
def get_tuple(N, this):
"""given row digits and col char
returns the unique tuple number"""
row, col = get_row_col(this)
return get_tuple_2(N, row, col)
def get_row_col(this):
"""return tuple of row and col
from '12A', '1A', etc. strs"""
return int(this[:-1]), ord(this[-1]) - ord('A')
def get_tuple_2(N, row, col):
"""for everything figured out"""
return (N * (row - 1)) + col
def solution(N, S, T):
"""given battleship locations and
hits, get number of ships totally
sunk and only hit but not sunk"""
# determine ships
ships = S.split(',')
# determine hits - for each ship how many hit
hits = T.split(' ')
hits = set([get_tuple(N, h) for h in hits])
ships_sunk = 0
ships_hit = 0
for ship in ships:
# for each ship, figure out ends
this = ship.split(' ')
left_row, left_col = get_row_col(this[0])
right_row, right_col = get_row_col(this[1])
# determine all tuples for this ship
ship_locs = []
for row in range(left_row, right_row + 1):
for col in range(left_col, right_col + 1):
ship_locs.append(get_tuple_2(N, row, col))
# Now, determine if all
# locations in this hit
ship_locs = set(ship_locs)
ship_hits = ship_locs.intersection(hits)
if len(ship_hits) == len(ship_locs):
ships_sunk += 1
elif len(ship_hits) > 0:
ships_hit += 1
return f'{ships_sunk},{ships_hit}'
print(solution(4, '1B 2C,2D 4D', '2B 2D 3D 4D 4A') == '1,1')
print(solution(3, '1A 1B,2C 2C', '1B') == '0,1')
print(solution(12, '1A 2A,12A 12A', '12A') == '1,0')
|
51dcdbe9d528b1c4f5de18838e678b24ccff3a07 | mittgaurav/Pietone | /largest_square_submatrix.py | 4,727 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 9 01:26:49 2018
@author: gaurav
[False, True, False, False],
[True, True, True, True],
[False, True, True, False],
for each elem, collect four values:
* Continuous true horizontally
* Continuous true vertically
* Minimum of continuous true
horizontally, vertically, or
diagonally. This tells exact
size of square matrix that's
ending at this very element.
* The overall maximum square
matrix size till this point.
[[0, 0, 0, 0], [1, 1, 1, 1], [0, 0, 0, 1], [0, 0, 0, 1]]
[[1, 1, 1, 1], [2, 2, 1, 1], [1, 3, 1, 1], [1, 4, 1, 1]]
[[0, 0, 0, 1], [3, 1, 1, 1], [2, 2, 2, 2], [0, 0, 0, 2]]
Though, we can easily remove
4th elems. Instead, maintain
a global max.
"""
matrix = list()
def square_submatrix(input):
"""given a matrix, find the
largest square matrix with
all vals equal to true"""
for i in range(0, len(input) + 1):
matrix.insert(i, list())
matrix[i].insert(0, [0, 0, 0, 0])
for j in range(0, len(input[0]) + 1):
matrix[0].insert(j, [0, 0, 0, 0])
m = 0
for i in range(1, len(input) + 1):
for j in range(1, len(input[0]) + 1):
arr = list()
if input[i-1][j-1]:
"""True"""
# horizontal
arr.append(1 + matrix[i-1][j][0])
# vertical
arr.append(1 + matrix[i][j-1][1])
# Size of matrix
# at this point.
arr.append(min(arr[0], arr[1],
1 + matrix[i-1][j-1][2]))
else:
"""False"""
arr.append(0)
arr.append(0)
arr.append(0)
# The overall maximum size
# of matrix seen till now.
arr.append(max(arr[2], matrix[i-1][j-1][3],
matrix[i-1][j][3], matrix[i][j-1][3]))
# we can have running max
m = max(arr[3], m)
# or keep within memoizer
matrix[i].insert(j, arr)
# both should nonetheless be same
assert(m == matrix[len(input)][len(input[0])][3])
return m
def square_submatrix_short(input):
"""I don't need to keep so
many values. Instead keep
only the maximum.
Quite similar to finding
longest True series in an
array. You maintain local
size and a global max one
"""
matrix = [[0 for _ in range(len(input[0])+1)] for _ in
range(len(input) + 1)]
m = 0
for i in range(1, len(input) + 1):
for j in range(1, len(input[0]) + 1):
if input[i-1][j-1]:
# if current val is True
# then we can add on to
# existing size. Min of
# left, right, and diag
val = 1 + min(matrix[i-1][j],
matrix[i][j-1],
matrix[i-1][j-1])
else:
val = 0
matrix[i][j] = val
m = max(m, val)
return m
matrix = []
print(square_submatrix([
[False, True, False, False],
[True, True, True, True],
[False, True, True, False],
]))
matrix = []
print(square_submatrix_short([
[False, True, False, False],
[True, True, True, True],
[False, True, True, False],
]))
print("-----")
matrix = []
print(square_submatrix([
[True, True, True, True, True],
[True, True, True, True, False],
[True, True, True, True, False],
[True, True, True, True, False],
[True, False, False, False, False]
]))
matrix = []
print(square_submatrix_short([
[True, True, True, True, True],
[True, True, True, True, False],
[True, True, True, True, False],
[True, True, True, True, False],
[True, False, False, False, False]
]))
print("-----")
matrix = []
print(square_submatrix([
[True, True, True, True, True],
[True, True, True, True, False],
[True, False, True, True, False],
[True, True, True, True, False],
[True, False, False, False, False]
]))
matrix = []
print(square_submatrix_short([
[True, True, True, True, True],
[True, True, True, True, False],
[True, False, True, True, False],
[True, True, True, True, False],
[True, False, False, False, False]
]))
print("-----")
|
eb1bf679c48940bbc2bf157675287e9c71f14e7a | mittgaurav/Pietone | /tree.py | 6,327 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
tree.py
- Tree (Binary Tree)
- Bst
"""
class Tree():
"""Binary tree"""
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
def max_level(self):
"""height of tree"""
return max(self.left.max_level() if self.left else 0,
self.right.max_level() if self.right else 0) + 1
@classmethod
def tree(cls):
"""return a demo binary tree"""
return Tree(1,
Tree(2, Tree(4), Tree(3)),
Tree(6, Tree(6, Tree(0), Tree(7))))
@classmethod
def tree2(cls):
"""return another demo binary tree"""
return Tree(2,
Tree(1, Tree(4), Tree(3)),
Tree(5, Tree(6, Tree(0), Tree(7))))
@classmethod
def str_node_internal(cls, nodes, level, levels):
"""internal of prints"""
ret = ''
if len([x for x in nodes if x is not None]) == 0:
return ret
floor = levels - level
endge_lines = int(pow(2, max(floor - 1, 0)))
first_spaces = int(pow(2, floor) - 1)
between_spaces = int(pow(2, floor + 1) - 1)
ret += first_spaces * ' '
new_nodes = list()
for node in nodes:
if node is not None:
ret += str(node.data)
new_nodes.append(node.left)
new_nodes.append(node.right)
else:
ret += ' '
new_nodes.append(None)
new_nodes.append(None)
ret += between_spaces * ' '
ret += '\n'
for i in range(1, endge_lines + 1):
for node in nodes:
ret += (first_spaces - i) * ' '
if node is None:
ret += ((endge_lines * 2) + i + 1) * ' '
continue
if node.left is not None:
ret += '/'
else:
ret += ' '
ret += (i + i - 1) * ' '
if node.right is not None:
ret += '\\'
else:
ret += ' '
ret += ((endge_lines * 2) - i) * ' '
ret += '\n'
ret += cls.str_node_internal(new_nodes, level + 1, levels)
return ret
def __str__(self):
levels = self.max_level()
return self.str_node_internal([self], 1, levels)
def __repr__(self):
return str(self.data)
def __len__(self):
"""num of nodes"""
return ((len(self.left) if self.left else 0) +
(len(self.right) if self.right else 0) + 1)
class Bst(Tree):
"""Binary Search Tree"""
def __init__(self, data=None, left=None, right=None):
Tree.__init__(self, data, left, right)
@classmethod
def bst(cls):
"""return demo BST"""
return Bst(4,
Bst(1, Bst(0), Bst(3)),
Bst(8, Bst(6, Bst(5), Bst(7))))
@classmethod
def bst2(cls):
"""another demo BST"""
return Tree(4,
Tree(3, Tree(0), Tree(3)),
Tree(5, None, Tree(7, Tree(6), Tree(9))))
tree = bst
tree2 = bst2
def insert(self, data):
"""insert into BST"""
if self.data is None:
self.data = data
return
if data > self.data:
if self.right is None:
self.right = Bst(data)
return
return self.right.insert(data)
if data <= self.data:
if self.left is None:
self.left = Bst(data)
return
return self.left.insert(data)
def find(self, data):
"""find node that
got data in BST"""
if self.data == data:
return self
elif self.data > data:
if self.left is not None:
return self.left.find(data)
elif self.data < data:
if self.right is not None:
return self.right.find(data)
return None
def find_node_and_parent(self, data, parent=None):
"""find node and
parent in bst"""
if self.data == data:
return self, parent
elif self.data > data:
if self.left:
return self.left.find_node_and_parent(data, self)
elif self.data < data:
if self.right:
return self.right.find_node_and_parent(data, self)
return None, None
def find_max_and_parent(self, parent=None):
"""max val in BST"""
if self.right:
return self.right.find_max_and_parent(self)
return self, parent
def find_min_and_parent(self, parent=None):
"""min val in BST"""
if self.left:
return self.left.find_min_and_parent(self)
return self, parent
def delete(self, data):
"""delete node from BST"""
node, parent = self.find_node_and_parent(data, None)
if node is None:
return
if node.left:
# replace with just smaller
can, par = node.left.find_max_and_parent(node)
new_data = can.data
if par:
# delete just smaller
par.delete(new_data)
else:
# left itself is just smaller
node.left = None
node.data = new_data
return
if node.right:
can, par = node.right.find_min_and_parent(node)
new_data = can.data
if par:
par.delete(new_data)
else:
node.right = None
node.data = new_data
return
# if no children
if parent is None:
# root. There is nothing
node.data = None
return
# which child exists?
if parent.left is node:
parent.left = None
else: # parent.right is node
parent.right = None
def inorder(self, result=[]):
"""in order traversal"""
self.left.inorder(result) if self.left else None
result.append(self.data)
self.right.inorder(result) if self.right else None
return result
|
e586a1f9e60722c8aa1949a9c1aa9f2404fa683e | PhirayaSripim/Python | /Week2/test2.6.py | 1,019 | 3.765625 | 4 | price=[[25,30,45,55,60],[45,45,75,90,100],[60,70,110,130,140]]
car = [" 4 ล้อ "," 6 ล้อ ","มากกว่า 6 ล้อ "]
print( " โปรแกรมคำนวณค่าผ่านทางมอเตอร์เวย์\n---------------")
print(" รถยนต์ 4 ล้อ กด 1\nรถยนต์ 6 ล้อ กด 2\nรถยนต์มากกว่า 6 ล้อ กด 3\n")
a=int(input("เลือกประเภทยานพหนะ : "))
print(car[a-1])
print("ลาดกระบัง----->บางบ่อ "+str(price[a-1][0])+" บาท")
print("ลาดกระบัง----->บางประกง "+str(price[a-1][1])+" บาท")
print("ลาดกระบัง----->พนัสนิคม "+str(price[a-1][2])+" บาท")
print("ลาดกระบัง----->บ้านบึง "+str(price[a-1][3])+" บาท")
print("ลาดกระบัง----->บางพระ "+str(price[a-1][4])+" บาท") |
2abbde87690a9670e0dd672daa22ae9e4c7afeb7 | PhirayaSripim/Python | /Week2/test2.3.py | 126 | 3.609375 | 4 | friend= ['jan','cream','phu','bam','orm','pee','bas','kong','da','james']
friend[9]="may"
friend[3]="boat"
print (friend[3:8]) |
184bc3285b8669680b305faafcb8099d2464b9cd | renatomayoral/ClickAutomation | /WAtest.py | 1,558 | 3.75 | 4 | #WhatApp Desktop App mensage sender
import pyautogui as pg
import time
print(pg.position())
screenWidth, screenHeight = pg.size() # Get the size of the primary monitor.
currentMouseX, currentMouseY = pg.position() # Get the XY position of the mouse.
pg.moveTo(471, 1063) # Move the mouse to XY coordinates.
pg.click() # Click the mouse.
time.sleep(10) # makes program execution pause for 10 sec
pg.moveTo(38, 244) # Move the mouse to XY coordinates.
pg.click(38, 244) # Move the mouse to XY coordinates and click it. """
time.sleep(3) # makes program execution pause for 3 sec
pg.write('Bom dia Lindinha!!', interval=0.20) # type with quarter-second pause in between each key
pg.press('enter') # Press the enter key. All key names are in pyautogui.KEY_NAMES
""" pyautogui.click('button.png') # Find where button.png appears on the screen and click it.
pyautogui.doubleClick() # Double click the mouse.
pyautogui.moveTo(500, 500, duration=2, tween=pyautogui.easeInOutQuad) # Use tweening/easing function to move mouse over 2 seconds.
pyautogui.press('esc') # Press the Esc key. All key names are in pyautogui.KEY_NAMES
pyautogui.keyDown('shift') # Press the Shift key down and hold it.
pyautogui.press(['left', 'left', 'left', 'left']) # Press the left arrow key 4 times.
pyautogui.keyUp('shift') # Let go of the Shift key.
pyautogui.hotkey('ctrl', 'c') # Press the Ctrl-C hotkey combination.
pyautogui.alert('This is the message to display.') # Make an alert box appear and pause the program until OK is clicked. """ |
e0e4e39fd90e6e7bb8024ff3636229043ae63b40 | eddylongshanks/repl-code | /Week 1 Example Code/_week1-program.py | 1,984 | 4.125 | 4 |
class User:
def __init__(self, name, age):
self.name = name
self.age = age
def details(self):
return "Name: " + self.name + "\nAge: " + str(self.age) +"\n"
def __str__(self):
return "Name: " + self.name + "\nAge: " + str(self.age) +"\n"
def __repr__(self):
return "User(name, age)"
# Inherit from User
class Admin(User):
def details(self):
return "Name: " + self.name + " (Admin)\nAge: " + str(self.age) +"\n"
# __str__ will return this line when calling the class. eg: print(user1)
def __str__(self):
return "Name: " + self.name + " (Admin)\nAge: " + str(self.age) +"\n"
def __repr__(self):
return "Admin(User)"
class Users:
def __init__(self):
self.users = []
def AddUser(self, user):
# Check for the type of the object to determine admin status
if user is type(Admin):
user = Admin(user.name, user.age)
elif user is type(User):
user = User(user.name, user.age)
self.users.append(user)
def GetUsers(self):
print("There are {0} users\n".format(str(len(self.users))))
for user in self.users:
print(user.details())
def __str__(self):
return "There are {0} users\n".format(str(len(self.users)))
def __repr__(self):
return "Users()"
users = Users()
numberOfUsers = int(input("How many users do you want to add?: "))
userCount = 1
while userCount <= numberOfUsers:
name = input("What is the name of user " + str(userCount) + "?: ")
age = input("What is the age of user " + str(userCount) + "?: ")
# Create a new user with the accepted information
currentUser = User(name, age)
# Add new user to the list
users.AddUser(currentUser)
userCount += 1
# Create an admin user and add to the list
admin = Admin("Chris", 30)
users.AddUser(admin)
# List the current users
users.GetUsers()
|
40f6f3affe328fbe149f7766be75a7774acbf709 | careywalker/networkanalysis | /CommunityEvaluation/utilities/calculate_modularity.py | 1,118 | 3.984375 | 4 | """This uses Newman-Girwan method for calculating modularity"""
import math
import networkx as nx
def calculate_modularity(graph, communities):
"""
Loops through each community in the graph
and calculate the modularity using Newman-Girwan method
modularity: identify the set of nodes that intersect with each
other more frequently than expected by random chance
"""
modularity = 0
sum_of_degrees_in_community = 0
number_of_edges_in_community = 0
number_of_edges_in_network = nx.number_of_edges(graph)
for community in communities:
number_of_edges_in_community = len(nx.edges(nx.subgraph(graph, community)))
for key, value in nx.subgraph(graph, community).degree().items():
sum_of_degrees_in_community += value
community_modularity = (
number_of_edges_in_community / number_of_edges_in_network
) - math.pow((sum_of_degrees_in_community/(2*number_of_edges_in_network)), 2)
modularity += community_modularity
sum_of_degrees_in_community = 0
return modularity
|
c174f8baea2ae06e4772c33599bc0de062bef842 | robertvari/pycore-210612-alapok-1 | /07_lists.py | 620 | 4 | 4 | my_name = "Tom"
my_age = 34
# indexes: 0 1 2 3
my_numbers = [23, 56, 12, 46]
# mixed list
my_list = [
"Robert",
"Csaba",
"Christina",
32,
3.14,
my_name,
my_age,
my_numbers
]
# print(my_list[7][-1])
# print(my_list[0])
# add items to list
my_numbers.append("Csilla")
print(my_numbers)
my_numbers.insert(2, "Laci")
print(my_numbers)
# remove item from list
my_numbers.remove(56)
print(my_numbers)
del my_numbers[2]
print(my_numbers)
del my_numbers[my_numbers.index("Csilla")]
print(my_numbers)
print("Csilla" in my_numbers)
# clear
my_numbers.clear()
print(my_numbers) |
c5b88df5ed908065732058806f386d7b9f723d7e | robertvari/pycore-210612-alapok-1 | /12_list_comprehension.py | 190 | 3.5 | 4 | number_list = [1, 2, 3, 4, 5]
# result_list = []
#
# for i in number_list:
# result_list.append(i+100)
result_list = [ i*i for i in number_list ]
print(number_list)
print(result_list) |
2fc3dc75d5a35af8a8890e8b2f7613ef00bcefbd | robertvari/pycore-210612-alapok-1 | /08_sets.py | 405 | 3.828125 | 4 | # cast list into a set
my_list = [1, 2, 3, "csaba", 4, "csaba", 2, 1]
my_set = set(my_list)
# print(my_set)
# add items to set
new_set = {1, 2, 3}
# print(new_set)
new_set.add(4)
# print(new_set)
# add more items to set
new_set.update([5, 6, 7, 8])
# print(new_set)
new_set.remove(5)
new_set.discard(7)
# print(new_set)
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A | B)
print(A & B)
print(A - B) |
d0bad2d90258f1654b588b956d926a2203ea59a3 | dinoivusic/Python-Challenges | /day17.py | 351 | 3.515625 | 4 | class Solution:
def longestCommonPrefix(self, strs):
longest = ""
if len(strs) < 1:
return longest
for index, value in enumerate(strs[0]):
longest += value
for s in strs[1:]:
if not s.startswith(longest):
return longest[:index]
return longest
|
a9f01e9a879b0b939d1a8ec99915cc0ec7999fb9 | dinoivusic/Python-Challenges | /day55.py | 275 | 3.515625 | 4 | def longestCommonPrefix(self, strs: List[str]) -> str:
ans = ""
if len(strs) == 0:
return ans
for i in range(len(min(strs))):
can = [s[i] for s in strs]
if (len(set(can)) != 1):
return ans
ans += can[0]
return ans
|
2d3f6ad78b0fccadc9cb575780e9268d9fa94680 | dinoivusic/Python-Challenges | /day24.py | 597 | 3.578125 | 4 | #One line solution
def cakes(recipe, available):
return min(available.get(k, 0)/recipe[k] for k in recipe)
#Longer way of solving it
def cakes(recipe, available):
new = []
shared = set(recipe.keys() & set(available.keys()))
if not len(shared) == len(recipe.keys()) and len(shared) == len(available.keys()):
print('Not all keys are shared')
if len(recipe.keys()) > len(available.keys()):
return 0
for key in available.keys():
if key in recipe.keys():
res = available[key]//recipe[key]
new.append(res)
return sorted(new)[0] |
03e81f455a5d2bab66078ff4c210da966c8958de | dinoivusic/Python-Challenges | /day35.py | 222 | 3.609375 | 4 | def overlap(arr,num):
count = 0
for i in range(len(arr)):
if arr[i][0] == num or arr[i][1] == num:
count+=1
if num > arr[i][0] and num < arr[i][1]:
count+=1
return count
|
b220260f33cd97cb8f1216bdad813af73adc0137 | dinoivusic/Python-Challenges | /day64.py | 527 | 4.03125 | 4 | #Create a function that return the output of letters multiplied by the int following them
import re
def multi(arr):
chars = re.findall('[A-Z]', arr)
digits = re.findall('[0-9]+', arr)
final= ''.join([chars[i]* int(digits[i]) for i in range(0,len(chars)-1)]) + chars[-1]
return final
print(multi('A4B5C2'))
def chars(arr):
extra =''
for char in arr:
if char.isdigit():
extra += extra[-1]* (int(char)-1)
else:
extra += char
return extra
print(chars('A4B5C2'))
|
1ccb257f02a30bb948940670626b3a713e863934 | dinoivusic/Python-Challenges | /day18.py | 173 | 3.515625 | 4 | class Solution:
def isPalindrome(self, strs):
s = [c.lower() for c in strs if c.isalnum()]
if s == s[::-1]:
return True
return False
|
dd054af1ca07948f20cc5e126da501ad227da02e | aqueed-shaikh/submissions | /7/islam_yaseen/app.py | 741 | 3.5 | 4 |
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return """<h1>This is the home page </h1>
<p><a href="/about">about</a> page</p>
<p><a href="/who">who</a> page</p>
<p><a href="http://www.youtube.com/watch?v=unVQT_AB0mY">something</a> to watch</p>
"""
@app.route("/who")
@app.route("/who/<name>")
def name(name="default"):
page = """
<h1> the page name </h1>
This is a page with someone's name
<hr>
The name is:
"""
page=page+name+"<hr>"
return page
@app.route("/about")
def about():
return """<h1>This is the about page</h1>
<p> go <a href="/who/YASEEN!">here!</a></p>
"""
if __name__=="__main__":
app.debug=True
app.run(host="0.0.0.0",port=5005)
|
c12604df95e476146dd984c1b6ddf7ae3453492d | aqueed-shaikh/submissions | /7/han_jason/HW1.py | 1,130 | 3.53125 | 4 | #!/usr/bin/python
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "<h1>Hello World.</h1>\n<h2>More headings</h2>\n<b>Bold stuff</b>"
@app.route("/about")
def about():
return "<h1>I am cookie monster. Nom nom nom nom.</h1>"
@app.route("/color")
def color():
return """
<body style='background-color:blue;'>
<h1 style='background-color:white;'>White and blue.</h1>
</body>
"""
@app.route("/table")
def table():
return """<table border='2'>
<tr>
<td>Yo this is the story</td>
<td>All about how</td>
<td>My life got flip turned</td>
<td>Upside down</td>
</tr>
<tr>
<td>I forget the rest of this song</td>
<td>Oh well</td>
<td>This is a table</td>
<td>wee</td>
</tr>
</table>"""
@app.route("/link")
def link():
return """<a href="http://www.google.com"></a>"""
@app.route("/list")
def list():
return """The difference between ul and ol\n
<ul>
<li>This is an unordered list</li>
<li>Stuff</li>
<li>more stuff</li>
<li>even more stuff</li>
<li>aight that's about it</li>
</ul>
<ol>
<li>This list has order.</li>
<li>wee</li>
"""
if __name__ == "__main__":
app.run()
|
bdeab1439c982ce0a142980a1bd868a00caac17f | aqueed-shaikh/submissions | /6/lin_jing/HW1.py | 449 | 4.0625 | 4 | #!/usr/bin/python
#Factorization of Input Number
def main():
try:
a = int(raw_input("Enter a number: "))
except ValueError:
print("That is not a number!")
return 0
String = "The Factors of %d are " % (a)
Counter = int(a**.5)
for i in range(2, Counter):
if(a == (a / i) * i):
a = a / i
String += "%d %d" % (a, i)
print(String)
if __name__ == "__main__":
main()
|
362923f31d00353c0ddd2640101ae9d80e427e77 | aqueed-shaikh/submissions | /6/kozak_severyn/3_madlibs/app.py | 871 | 3.609375 | 4 | #!/usr/bin/python
"""
Team: Severyn Kozak (only)
app, a Python Flask application, populates a template .html
file's empty fields with a randomized selection of words.
Think madlibs.
"""
from flask import Flask, render_template
from random import sample
app = Flask(__name__)
#dictionary of word arrays, by type
wordPool = {'Object' : ['greatsword', 'chalice', 'stacks'],
'Verb' : ['pilfer', 'hike', 'dungeoneer'],
'Place' : ['barrio', 'The Wall', 'Sao Tome'],
'Adjective' : ['black', 'svelte', 'gaunt']}
@app.route("/")
#populates template with a shuffled copy of wordPool
def madlib():
words = {'O': sample(wordPool['Object'], 3),
'V': sample(wordPool['Verb'], 3),
'P': sample(wordPool['Place'], 3),
'A': sample(wordPool['Adjective'], 3)}
return render_template("template.html", words = words)
if __name__ == "__main__":
app.run(debug = True)
|
865e77608165c48b254aa4fbbfbcee48e65c79c2 | aqueed-shaikh/submissions | /6/kurtovic_benjamin/stuff.py | 2,061 | 3.9375 | 4 | #! /usr/bin/env python
# I'm not sure how to demonstrate my knowledge best, so here's an example of
# some really esoteric concepts in the form of metaclasses (because I can).
import sys
import time
class CacheMeta(type):
"""Caches the return values of every function in the child class."""
def __new__(cls, name, bases, values):
def use_cache(func):
"""Wraps a function to use the caching system."""
def wrapper(self, *args):
key = (func, args)
if key in self._cache:
return self._cache[key]
result = func(self, *args)
self._cache[key] = result
return result
return wrapper
for key, func in values.iteritems():
if callable(func):
values[key] = use_cache(func)
values["_cache"] = {}
return super(CacheMeta, cls).__new__(cls, name, bases, values)
class WithoutCache(object):
"""Some time-consuming methods that don't use a cache."""
def fib(self, n):
"""Calculates the nth Fibonacci number inefficiently."""
if n <= 2:
return 1
return self.fib(n - 1) + self.fib(n - 2)
class WithCache(object):
"""Some time-consuming methods that use a cache."""
__metaclass__ = CacheMeta
def fib(self, n):
"""Calculates the nth Fibonacci number efficiently."""
if n <= 2:
return 1
return self.fib(n - 1) + self.fib(n - 2)
def test():
n = 35
classes = [(WithoutCache(), "without"), (WithCache(), "with")]
for obj, desc in classes:
print "First %i Fibonacci numbers %s cache:\n\t" % (n, desc),
for i in xrange(1, n + 1):
if i == n:
t1 = time.time()
sys.stdout.write(str(obj.fib(i)) + (" "))
sys.stdout.flush()
if i == n:
t2 = time.time()
print "\n\t%.8f seconds to find %ith number" % (t2 - t1, n)
print
if __name__ == "__main__":
test()
|
66d0e4aed34979127e18bf88bd2010461028acc4 | aqueed-shaikh/submissions | /7/herman_hunter/hermanroar.py | 433 | 3.71875 | 4 | import random
<<<<<<< HEAD
for x in range(0, random.randrange(0, 999)):
print "I AM HERMAN HEAR ME ROAR"
print "meow"
=======
total_fear = 0
for x in range(0, random.randrange(1, 999)):
print "I AM HERMAN NUMBER %i HEAR ME ROAR"%(x*x)
num = random.randrange(100, 450)
print "fear level: %i"%num
total_fear += num
print "meow. total fear: %i"%total_fear
>>>>>>> 995de77d830fc93d8ab5ff0588b1f4956391aa3c
|
2ca884ecd48eb25176d5f0a315371e9464710f89 | aqueed-shaikh/submissions | /7/chung_victoria/test.py | 576 | 3.625 | 4 | #!/usr/bin/python
def problemOne():
sum = 0
i = 1
while i < 1000:
if i % 3 == 0 or i % 5 == 0:
sum += i
i+=1
print sum
def problemTwo():
sum = 2
a = 1
b = 2
term = 2
while term <= 4000000:
term = a + b
a = b
b = term
if term % 2 == 0:
sum += term
print sum
def problemThree():
answer = 0;
for first in range (100, 999):
for second in range (100, 999):
product = first * second
if str(product) == str(product)[::-1]:
if product > answer:
answer = product
print answer
# problemOne()
# problemTwo()
problemThree()
|
34067bf118ee70d6f07d4499db7015d3b4dee808 | aqueed-shaikh/submissions | /6/Luo_Jason/Hello.py | 414 | 3.890625 | 4 | #!/usr/bin/python
def fact (n):
if n == 0:
return 1
else:
return n * fact(n-1)
print fact (5)
def fib (n):
count = 0
if n == 1:
return count + 0
elif n == 2:
return count + 1
else:
return count + fib(n-1) + fib(n-2)
print fib(10)
def isPrime(n):
last = False
if n % 2 == 0:
return not last
return last
print isPrime(3)
|
c25ee297552465456ca50c12ce5df934c9d399bf | IsaacMarovitz/ComputerSciencePython | /MontyHall.py | 2,224 | 4.28125 | 4 | # Python Homework 11/01/20
# In the Monty Hall Problem it is benefical to switch your choice
# This is because, if you switch, you have a rougly 2/3 chance of
# Choosing a door, becuase you know for sure that one of the doors is
# The wrong one, otherwise if you didnt switch you would still have the
# same 1/3 chance you had when you made your inital guess
# On my honour, I have neither given nor received unauthorised aid
# Isaac Marovitz
import random
num_simulations = 5000
no_of_wins_no_switching = 0
no_of_wins_switching = 0
# Runs Monty Hall simulation
def run_sim(switching):
games_won = 0
for _ in range(num_simulations):
# Declare an array of three doors each with a tuple as follows (Has the car, has been selected)
doors = [(False, False), (False, False), (False, False)]
# Get the guess of the user by choosing at random one of the doors
guess = random.randint(0, 2)
# Select a door at random to put the car behind
door_with_car_index = random.randint(0, 2)
# Change the tuple of that door to add the car
doors[door_with_car_index] = (True, False)
# Open the door the user didn't chose that doesn't have the car behind it
for x in range(2):
if x != door_with_car_index and x != guess:
doors[x] = (False, True)
# If switching, get the other door that hasn't been revealed at open it, otherwise check if
# the current door is the correct one
if switching:
for x in range(2):
if x != guess and doors[x][1] != True:
games_won += 1
else:
if guess == door_with_car_index:
games_won += 1
return games_won
# Run sim without switching for first run
no_of_wins_no_switching = run_sim(False)
# Run sim with switching for the next run
no_of_wins_switching = run_sim(True)
print(f"Ran {num_simulations} Simulations")
print(f"Won games with switching: {no_of_wins_switching} ({round((no_of_wins_switching / num_simulations) * 100)}%)")
print(f"Won games without switching: {no_of_wins_no_switching} ({round((no_of_wins_no_switching / num_simulations) * 100)}%)")
|
d5abb3795766226e51caba8f079af04c9c5cb7cf | IsaacMarovitz/ComputerSciencePython | /IfStatements2.py | 1,219 | 3.921875 | 4 | # Python Homework 09/16/2020
import sys
try:
float(sys.argv[1])
except IndexError:
sys.exit("Error: No system arguments given\nProgram exiting")
except ValueError:
sys.exit("Error: First system argument must be a float\nProgram exiting")
user_score = float(sys.argv[1])
if user_score < 0 or user_score > 5:
sys.exit("Error: First system argument must be greater than 0 or less than 5\nProgram exiting")
def get_user_score(user_score):
if user_score <= 1:
return "F"
elif user_score <= 1.33:
return "D-"
elif user_score <= 1.67:
return "D"
elif user_score <= 2:
return "D+"
elif user_score <= 2.33:
return "C-"
elif user_score <= 2.67:
return "C"
elif user_score <= 3:
return "C+"
elif user_score <= 3.33:
return "B-"
elif user_score <= 3.67:
return "B"
elif user_score <= 4:
return "B+"
elif user_score <= 4.33:
return "A-"
elif user_score <= 4.67:
return "A"
else:
return "A+"
print(f"Your score is {get_user_score(user_score)}")
input("Press ENTER to exit")
# On my honour, I have neither given nor received unauthorised aid
# Isaac Marovitz |
155a6195c974de35a6de43dffe7f1d2065d40787 | IsaacMarovitz/ComputerSciencePython | /Conversation2.py | 1,358 | 4.15625 | 4 | # Python Homework 09/09/2020
# Inital grade 2/2
# Inital file Conversation.py
# Modified version after inital submisions, with error handeling and datetime year
# Importing the datetime module so that the value for the year later in the program isn't hardcoded
import datetime
def userAge():
global user_age
user_age = int(input("How old are you? (Please only input numbers) "))
print("\nHey there!", end=" ")
user_name = input("What's your name? ")
print("Nice to meet you " + user_name)
user_age_input_recieved = False
while (user_age_input_recieved == False):
try:
userAge()
user_age_input_recieved = True
except ValueError:
print("Invalid Input")
user_age_input_recieved = False
# I got this datetime solution from StackOverflow
# https://stackoverflow.com/questions/30071886/how-to-get-current-time-in-python-and-break-up-into-year-month-day-hour-minu
print("So, you were born in " + str((datetime.datetime.now().year-user_age)) + "!")
user_colour = input("What's your favourite colour? ")
if user_colour.lower() == "blue":
print("Hey, my favourite is blue too!")
else:
print(user_colour.lower().capitalize() +
"'s a pretty colour! But my favourite is blue")
print("Goodbye!")
input("Press ENTER to exit")
# On my honor, I have neither given nor received unauthorized aid
# Isaac Marovitz
|
bf00b432183b7c83bed5de8f1f78ce59322e1889 | IsaacMarovitz/ComputerSciencePython | /Minesweeper.py | 10,535 | 3.59375 | 4 | # Isaac Marovitz - Python Homework 02/10/20
# Sources: N/A
# Blah blah blah
# On my honour, I have neither given nor received unauthorised aid
import sys, random, os, time
# Declaring needed arrays
mineGrid = []
gameGrid = []
# Clear the terminal
def clear():
if os.name == "nt":
os.system('cls')
else:
os.system("clear")
# Returns all items surrounding an item in a given array
def checkSurrounding(givenArray, x, y):
returnArray = []
height = len(givenArray) - 1
width = len(givenArray[0]) - 1
if y < height and x > 0:
returnArray.append((givenArray[y+1][x-1], y+1, x-1))
if y < height:
returnArray.append((givenArray[y+1][x], y+1, x))
if y < height and x < width:
returnArray.append((givenArray[y+1][x+1], y+1, x+1))
if x > 0:
returnArray.append((givenArray[y][x-1], y, x-1))
if x < width:
returnArray.append((givenArray[y][x+1], y, x+1))
if y > 0 and x > 0:
returnArray.append((givenArray[y-1][x-1], y-1, x-1))
if y > 0:
returnArray.append((givenArray[y-1][x], y-1, x))
if y > 0 and x < width:
returnArray.append((givenArray[y-1][x+1], y-1, x+1))
return returnArray
# Creates the mineGrid, which is the solved version of the grid that the user doesnt see
def createMineGrid(startX, startY):
# Create 2D Array if given width and height
for _ in range(0, height):
tempWidthGrid = [0 for x in range(width)]
mineGrid.append(tempWidthGrid)
# Place mines in the grid until the mine count equals total mine count
totalMineCount = 0
while totalMineCount < mineCount:
xPosition = random.randint(0, width-1)
yPosition = random.randint(0, height-1)
if mineGrid[yPosition][xPosition] != '*':
if startX != xPosition and startY != yPosition:
mineGrid[yPosition][xPosition] = '*'
totalMineCount = totalMineCount + 1
# Sets all the numbers in the grid to the number of mines surrounding that point
for y in range(0, height):
for x in range(0, width):
if mineGrid[y][x] != '*':
surroundingMineCount = 0
checkArray = checkSurrounding(mineGrid, x, y)
for value in checkArray:
if value[0] == '*':
surroundingMineCount += 1
mineGrid[y][x] = surroundingMineCount
createGameGrid(startX, startY)
# Create the gameGrid which stores hidden tiles with 'False', shown tiles with 'True', and flagged tiles with 'f', default it all to 'False'
def createGameGrid(startX, startY):
for _ in range(0, height):
tempWidthGrid = []
for _ in range(0, width):
tempWidthGrid.append(False)
gameGrid.append(tempWidthGrid)
recursiveCheck(startX, startY)
# Checks all tiles around a given tile and starts the check if it isn't already shown
def recursiveCheck(xPos, yPos):
gameGrid[yPos][xPos] = True
if mineGrid[yPos][xPos] != '*':
if int(mineGrid[yPos][xPos]) == 0:
gameGrid[yPos][xPos] = True
checkArray = checkSurrounding(gameGrid, xPos, yPos)
for value in checkArray:
if not value[0]:
gameGrid[value[1]][value[2]] = True
recursiveCheck(value[1], value[2])
# This checks to see if the win conditions have been met yet by checking if there are any unrevealed non-mine tiles
def checkWin():
totalSqauresLeft = 0
for x in range(0, width):
for y in range(0, height):
if mineGrid[y][x] != '*' and gameGrid[y][x] == False:
totalSqauresLeft = totalSqauresLeft + 1
if totalSqauresLeft == 0:
return True
else:
return False
# Parses user input coords for each turn and checks for errors
def parseUserInput(inputMessage):
# Gets input message and splits it into an array
inputMessage = inputMessage.strip().split(" ")
try:
# Gets input coords from input message array
xPos = int(inputMessage[0]) - 1
yPos = int(inputMessage[1]) - 1
# If an 'f' is included, toggle the flag on the given square
try:
if inputMessage[2] == 'f' or inputMessage[2] == 'F':
if gameGrid[yPos][xPos] == False:
gameGrid[yPos][xPos] = 'F'
elif gameGrid[yPos][xPos] == 'F':
gameGrid[yPos][xPos] = False
else:
print("You can't place flags on revealed squares!")
time.sleep(1)
else:
print("Type 'f' to place a flag at the given coordinates!")
time.sleep(1)
# If no flag is included, check if the given square is a mine and either reveal it or end the game
except IndexError:
if gameGrid[yPos][xPos] != 'F':
recursiveCheck(xPos, yPos)
if mineGrid[yPos][xPos] == '*':
print("You died!")
return
else:
print("You cannot reveal sqaures with a flag!")
time.sleep(1)
# Error checking
except ValueError:
print("Only input intergers for coordinates!")
time.sleep(1)
except IndexError:
print("Only input valid coordinates!")
time.sleep(1)
if checkWin():
printGrid()
print("You won!")
else:
printGrid()
parseUserInput(input("Input coords: "))
# Prints the grid with spacing and unicode box-drawing characters for added aesthetics
def printGrid():
clear()
print('┌',end='')
for x in range(0, width):
if x < width-1:
print('───┬', end='')
else:
print('───┐', end='')
print('\n', end='')
for y in range(0, height):
for x in range (0, width):
print('│', end='')
if gameGrid[y][x] == 'F':
print(' ⚑ ', end='')
else:
if gameGrid[y][x] and mineGrid[y][x] != '*':
print(f" {mineGrid[y][x]} ", end='')
else:
print(' ◼ ', end='')
if not (x < width-1):
print('│', end='')
print('\n',end='')
if y < height-1:
print('├', end='')
else:
print('└', end='')
for x in range(0, width):
if y < height-1:
if x < width-1:
print('───┼', end='')
else:
print('───┤', end='')
else:
if x < width-1:
print('───┴', end='')
else:
print('───┘', end='')
print('\n', end='')
# Starts the game, gets the starting coords from the user, checks for errors, keeps track of game time, and asks the user if they want to play again
def startGame():
global mineGrid, gameGrid
clear()
print('Welcome to Minesweeper\n')
startCoordsReceived = False
mineGrid = []
gameGrid = []
# Receive starting coords and check if they're valid
while not startCoordsReceived:
try:
inputMessage = input('Where do you want to start? Input coords (x & y): ')
inputMessage = inputMessage.strip().split(' ')
xCoord = int(inputMessage[0]) - 1
yCoord = int(inputMessage[1]) - 1
if xCoord < width and yCoord < height:
startCoordsReceived = True
else:
print(f"Width and height must be between 0 and {width} and {height} respectively!")
startCoordsReceived = False
time.sleep(1)
clear()
print('Welcome to Minesweeper\n')
except IndexError:
print("Please input an x AND a y coordinate seperated by a space.")
startCoordsReceived = False
time.sleep(1)
clear()
print('Welcome to Minesweeper\n')
except ValueError:
print("Please only input whole intergers.")
startCoordsReceived = False
time.sleep(1)
clear()
print('Welcome to Minesweeper\n')
# Record start time and create mine grid
startTime = time.time()
createMineGrid(xCoord, yCoord)
printGrid()
parseUserInput(input("Input coords: "))
# When the game finishes, display final time
print(f"You played for {round(time.time() - startTime, 2)} seconds!")
playAgainReceived = False
# Ask the user if they want to play again
while not playAgainReceived:
try:
inputMessage = input('Do you want to play again? (y/n): ')
inputMessage = inputMessage.strip().lower()
if inputMessage == 'y' or inputMessage == 'yes':
playAgainReceived = True
startGame()
elif inputMessage == 'n' or inputMessage == 'no':
playAgainReceived = True
input("Press ENTER to exit")
else:
print("Please input yes or no")
time.sleep(1)
clear()
playAgainReceived = False
except ValueError:
print("Please input yes or no")
time.sleep(1)
clear()
playAgainReceived = False
# Get starting command line argument and check for errors
try:
width = int(sys.argv[1])
if width < 1 or width > 30:
sys.exit("Width must be greater than 0 and less than 30!\nProgram exiting.")
except IndexError:
sys.exit("Width not given!\nProgram exiting.")
except ValueError:
sys.exit("Width can only be an interger!\nProgram exiting.")
try:
height = int(sys.argv[2])
if height < 1 or width > 30:
sys.exit("Height must be greater than 0 and less than 30!\nProgram exiting.")
except IndexError:
sys.exit("Height not given!\nProgram exiting.")
except ValueError:
sys.exit("Height can only be an interger!\nProgram exiting.")
try:
mineCount = int(sys.argv[3])
if mineCount < 1 or mineCount > (width * height):
sys.exit("Number of mines must be greater than 0 and less than the number of grid squares!\nProgram exiting.")
except IndexError:
sys.exit("Number of mines not given!\nProgram exiting.")
except ValueError:
sys.exit("Number of mines can only be an interger!\nProgram exiting.")
startGame()
|
6cad478212cb9a345107e33659dd716f49e674a0 | daniromero97/Python | /e025-StringMethods/StringMethods.py | 1,049 | 3.75 | 4 | print("##################### 1 #####################")
sequence = ("This is a ", "")
s = "test"
sentence = s.join(sequence)
print(sentence)
sequence = ("This is a ", " (", ")")
sentence = s.join(sequence)
print(sentence)
"""
output:
This is a test
This is a test (test)
"""
print("##################### 2 #####################")
sentence = "this is a test"
separator = "is a"
tuple = sentence.partition(separator)
print(tuple)
"""
output:
('this ', 'is a', ' test')
"""
print("##################### 3 #####################")
sentence = "this is a test, " * 4
separator = ","
list = sentence.split(separator)
print(sentence)
print(list)
"""
output:
this is a test, this is a test, this is a test, this is a test,
['this is a test', ' this is a test', ' this is a test', ' this is a test', ' ']
"""
print("##################### 4 #####################")
sentence = """line 1
line2
line3"""
print(sentence)
print(sentence.splitlines())
"""
output:
line 1
line2
line3
['line 1', 'line2 ', 'line3']
"""
|
00e97c511c9114dd8cb32f68a3ce3323cfd7ebf4 | daniromero97/Python | /e004-Tuples/Tuples.py | 1,380 | 3.875 | 4 | print("########################### 1 ############################")
my_tuple = ("value 1", "value 2", "value 3", ["value 4.1", "value 4.2"], 5, ("value 6.1", "value 6.2"))
print(my_tuple)
print(my_tuple[0])
print(my_tuple[-1])
print(my_tuple[2:5])
"""
Output:
('value 1', 'value 2', 'value 3', ['value 4.1', 'value 4.2'], 5, ('value 6.1', 'value 6.2'))
value 1
('value 6.1', 'value 6.2')
('value 3', ['value 4.1', 'value 4.2'], 5)
"""
print("########################### 2 ############################")
print(my_tuple.index("value 2"))
print(5 in my_tuple)
"""
Output:
1
True
"""
print("########################### 3 ############################")
print(len(my_tuple))
print(my_tuple.count("value 3"))
"""
Output:
6
1
"""
print("########################### 4 ############################")
my_tuple2 = (1, 4, 5, 21, 2)
print(min(my_tuple2))
print(max(my_tuple2))
"""
Output:
1
21
"""
print("########################### 5 ############################")
print(my_tuple)
l = list (my_tuple)
print(l)
t = tuple (l)
print(t)
"""
Output:
('value 1', 'value 2', 'value 3', ['value 4.1', 'value 4.2'], 5, ('value 6.1', 'value 6.2'))
['value 1', 'value 2', 'value 3', ['value 4.1', 'value 4.2'], 5, ('value 6.1', 'value 6.2')]
('value 1', 'value 2', 'value 3', ['value 4.1', 'value 4.2'], 5, ('value 6.1', 'value 6.2'))
""" |
ddbeef1a26cb8b570434e5e595dd1421a81a5625 | daniromero97/Python | /e013-Encapsulation/OOP.py | 728 | 4.03125 | 4 | class Person(object):
def __init__(self, name, height, weight, age):
self.__name = name
self.__height = height
self.__weight = weight
self.__age = age
def properties(self):
print("Name: %s, height: %.2f m, weight: %.1f kg, age: %d years old" % (self.__name, self.__height, self.__weight, self.__age))
def eat(self):
print("%s is eating" % self.__name)
def drink(self):
print("%s is drinking" % self.__name)
def sleep(self):
print("%s is sleeping" % self.__name)
p1 = Person("Gonzalo", 1.78, 74, 25)
p1.properties()
p1.__name = "Luis"
p1.properties()
print(p1.__name) # Unresolved attribute reference '__name' for class 'Person'
|
a5eaef2210158228b7681822194cb4ae04dfd677 | daniromero97/Python | /e006-ControlFlowStatements/ControlFlowStatements.py | 1,780 | 3.9375 | 4 | print("########################### 1 ############################")
a = 0
while a<5:
print(a)
a+=1
"""
Output:
0
1
2
3
4
"""
print("########################### 2 ############################")
a = 0
while True:
a += 1
print(a)
if a == 3:
break
"""
Output:
1
2
3
"""
print("########################### 3 ############################")
color_list = ['red', 'blue', 'green']
for color in color_list:
print(color)
"""
Output:
red
blue
green
"""
print("########################### 4 ############################")
for num in range(0, 5):
print(num)
"""
Output:
0
1
2
3
4
"""
print("########################### 5 ############################")
sentence = "I just want you to count the letters"
counter = 0
print(len(sentence))
for letter in sentence:
if letter == ' ':
continue
counter+=1
print(counter)
"""
Output:
36
29
"""
print("########################### 6 ############################")
sentence = "I just want you to count the letters"
counter = 0
print(len(sentence))
for letter in sentence:
pass # Incomplete code
print(counter)
"""
Output:
36
0
"""
print("########################### 7 ############################")
sentence = "Count only the length of the first word"
counter = 0
for letter in sentence:
counter += 1
if letter == ' ':
break
else:
counter = 0
print("It was not a sentence, it was a word")
print(counter)
sentence = "Test"
counter = 0
for letter in sentence:
counter += 1
if letter == ' ':
break
else:
counter = 0
print("It was not a sentence, it was a word")
print(counter)
"""
Output:
6
It was not a sentence, it was a word
0
""" |
7dcde1f414b5214079c7516810a9d96094538107 | daniromero97/Python | /e033-Datetime/Main.py | 3,097 | 3.734375 | 4 | import datetime
print("###################### 1 ######################")
print(datetime.MINYEAR)
"""
output:
1
"""
print("###################### 2 ######################")
print(datetime.MAXYEAR)
"""
output:
9999
"""
print("###################### 3 ######################")
print(datetime.date.today())
print("day:", datetime.date.today().day)
print("month:", datetime.date.today().month)
print("year:", datetime.date.today().year)
print("weekday:", datetime.date.today().weekday())
"""
output:
2018-11-28
day: 28
month: 11
year: 2018
weekday: 2
"""
print("###################### 4 ######################")
print(datetime.datetime.now())
print("hour:", datetime.datetime.now().hour)
print("minute:", datetime.datetime.now().minute)
print("second:", datetime.datetime.now().second)
print("microsecond:", datetime.datetime.now().microsecond)
print("timestamp():", datetime.datetime.now().timestamp())
"""
output:
2018-11-28 12:54:24.378262
hour: 12
minute: 54
second: 24
microsecond: 378290
timestamp(): 1543406064.378299
"""
print("###################### 5 ######################")
print("weeks:", datetime.timedelta(weeks=1), "--> total seconds:",datetime.timedelta(weeks=1).total_seconds())
print("days:", datetime.timedelta(days=1), "--> total seconds:",datetime.timedelta(days=1).total_seconds())
print("hours:", datetime.timedelta(hours=1), "--> total seconds:",datetime.timedelta(hours=1).total_seconds())
print("minutes:", datetime.timedelta(minutes=1), "--> total seconds:",datetime.timedelta(minutes=1).total_seconds())
print("seconds:", datetime.timedelta(seconds=1), "--> total seconds:",datetime.timedelta(seconds=1).total_seconds())
print("milliseconds:", datetime.timedelta(milliseconds=1), "--> total seconds:",datetime.timedelta(milliseconds=1).total_seconds())
print("microseconds:", datetime.timedelta(microseconds=1), "--> total seconds:",datetime.timedelta(microseconds=1).total_seconds())
print("total:",
datetime.timedelta(weeks=1, days=1, hours=1, minutes=1, seconds=1, milliseconds=1, microseconds=1),
"--> total seconds:",
datetime.timedelta(weeks=1, days=1, hours=1, minutes=1, seconds=1, milliseconds=1, microseconds=1).total_seconds())
"""
output:
weeks: 7 days, 0:00:00 --> total seconds: 604800.0
days: 1 day, 0:00:00 --> total seconds: 86400.0
hours: 1:00:00 --> total seconds: 3600.0
minutes: 0:01:00 --> total seconds: 60.0
seconds: 0:00:01 --> total seconds: 1.0
milliseconds: 0:00:00.001000 --> total seconds: 0.001
microseconds: 0:00:00.000001 --> total seconds: 1e-06
total: 8 days, 1:01:01.001001 --> total seconds: 694861.001001
"""
print("###################### 6 ######################")
print(datetime.date.today())
print(datetime.datetime.today().strftime('%d, %b %Y'))
print(datetime.datetime.now())
print(datetime.datetime.now().strftime('%d, %b %Y'))
print(datetime.datetime.now().strftime('%d/%b/%Y %H:%M:%S'))
"""
output:
2018-11-28
28, Nov 2018
2018-11-28 13:26:41.492853
28, Nov 2018
28/Nov/2018 13:26:41
""" |
b574c115fc9c68ca068880dfb5b2a247f985d8c2 | xiong-zh/Arithmetic | /sort/radix.py | 685 | 3.84375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2020/6/15
# @Author: zhangxiong.net
# @Desc :
def radix(arr):
digit = 0
max_digit = 1
max_value = max(arr)
# 找出列表中最大的位数
while 10 ** max_digit < max_value:
max_digit = max_digit + 1
while digit < max_digit:
temp = [[] for i in range(10)]
for i in arr:
# 求出每一个元素的个、十、百位的值
t = int((i / 10 ** digit) % 10)
temp[t].append(i)
coll = []
for bucket in temp:
for i in bucket:
coll.append(i)
arr = coll
digit = digit + 1
return arr
|
774ce49dd157eca63ab05d74c0d542dd33b4f14a | Nyame-Wolf/snippets_solution | /codewars/Write a program that finds the summation of every number between 1 and num if no is 3 1 + 2.py | 629 | 4.5 | 4 | Summation
Write a program that finds the summation of every number between 1 and num. The number will always be a positive integer
greater than 0.
For example:
summation(2) -> 3
1 + 2
summation(8) -> 36
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8
tests
test.describe('Summation')
test.it('Should return the correct total')
test.assert_equals(summation(1), 1)
test.assert_equals(summation(8), 36)
others solution:
def summation(num):
return (1+num) * num / 2
or
def summation(num):
return sum(range(1,num+1))
or
def summation(num):
if num > 1:
return num + summation(num - 1)
return 1
|
389b09b0bcc2596b3847791765a47127b4f97f13 | McBonB/text01_lf | /t.py | 1,958 | 3.65625 | 4 | """
最远足迹
莫探险队对地下洞穴探索
会不定期记录自身坐标,在记录的间隙中也会记录其他数据,探索工作结束后,探险队需要获取到某成员在探险过程中,对于探险队总部的最远位置
1.仪器记录坐标时,坐标的数据格式为 x,y
x和y——》0-1000
(01,2)(1,01)
设定总部位置为0,0
计算公式为x*(x+y)*y
"""
import re,math
s = "abcccc(3,10)c5,13d(1$f(6,11)sdf(510,200)adas2d()(011,6)" #原始字符串
#print(re.findall(r'[^()a-z]+', s))
pattern = re.compile(r'\(([0-9]{1,3},[0-9]{1,3})\)') #提取坐标正则表达式对象
result = re.findall(pattern,s) #查询整个字符串,得出坐标列表
f_result={}
#判断是否为合格的十进制整数,且大于0小于500
def isDigit(str1):
if len(str1)==3:
if str1[0]=='0':
return False
else:
return True
if len(str1)==2:
if str1[0]=='0':
return False
else:
return True
if len(str1)==1:
if str1=='0':
return False
else:
return True
#遍历得出的坐标列表,求得他距离总部(0,0)的距离,距离为x^2+y^2,并保存到字典f_result
for i in result:
i=i.split(',')
if isDigit(i[0]) and isDigit(i[1]):
f_result[','.join(i)]=i[0]*(i[1]+i[0])*i[1]
#求得最远距离
a=max(f_result.values())
#最远距离的距离和坐标字典
z_result=[]
for i in f_result:
if f_result[i]==a:
z_result.append(i)
#最远距离下,x+y和与坐标
he_result={}
#如果最远距离相等,判断谁先到达,规则x+y
for i in z_result:
i=i.split(',')
he_result[','.join(i)]=int(i[0])+int(i[1])
#求得和的最小值
b=min(he_result.values())
#遍历,打印出最小和的坐标
for i in he_result:
if he_result[i]==b:
print('('+i+')')
#print(i,i[0],i[1],isDigit(i[0]),isDigit(i[1]),f_result,a,z_result,z_result[0],he_result) |
a1e2cbfe73c8889bca05dd05a02ef1789bb61a68 | Bellroute/python_class | /day0911/example2_6.py | 304 | 4.09375 | 4 | def sumDigits(n):
result = 0
while(n != 0):
result += n % 10
n //= 10
return result
def main():
n = int(input('Enter a number between 0 and 1000 : '))
result = sumDigits(n)
print('The sum of the digits is', result)
if __name__ == "__main__":
main() |
483a180d35ed99b23cd82163b47fe2f78e18148c | Bellroute/python_class | /day1002/example5_19.py | 253 | 3.703125 | 4 | inputValue = int(input("Enter the number of lines: "))
for i in range(1, inputValue + 1):
line = " "
for j in range(i, 0, -1):
line += str(j) + " "
for j in range(2, i + 1):
line += str(j) + " "
print(line.center(60))
|
282434fc39e19a79f8ce6b7ca4b142a9a61aed9d | Bellroute/python_class | /someday/factorize.py | 457 | 3.765625 | 4 | import prime
def factorize(n):
factor = []
while True:
m = prime.isPrime(n)
if m == n:
break
n //= m
return factor
def main():
n = int(input('type any number : '))
result = prime.isPrime(n)
if result:
print(n, '은 소수야!')
else:
print(n, '은 ', result, '로 나눠져!')
result = factorize(n)
print(result)
if __name__ == "__main__":
main()
|
d920f009c5aa6209e9daf681197d9de7ca73a1f5 | acttx/Python | /Comp Fund 2/Lab4/personList.py | 1,811 | 3.59375 | 4 | import csv
from person import Person
from sortable import Sortable
from searchable import Searchable
"""
This class has no instance variables.
The list data is held in the parent list class object.
The constructor must call the list constructor:
See how this was done in the Tower class.
Code a populate method, which reads the CSV file.
It must use: try / except, csv.reader,
and with open code constructs.
Code the sort method: Must accept a function object
and call the function.
Code the search method: Must accept a function object
and a search item Person object and call the function.
Code a __str__ method: Look at the Tower class for help
You may want to code a person_at method for debug purposes.
This takes an index and returns the Person at that location.
"""
class PersonList(Sortable, Searchable, list):
def __init__(self):
super().__init__()
def populate(self, filename):
try:
with open(filename, 'r') as input_file:
lines = csv.reader(input_file)
emp_list = list(lines)
for emp in emp_list:
name = emp[0]
month = int(emp[1])
day = int(emp[2])
year = int(emp[3])
self.append(Person(name, year, month, day))
except IOError:
print("File Not Found. Program Exited.")
exit()
def person_at(self):
for i in range(len(self)):
return self.index(i)
def sort(self, funcs):
funcs(self)
def search(self, func, person_obj):
return func(self, person_obj)
def __str__(self):
x = '[' + '] ['.join(str(d) for d in self)
return x
|
e96466aa5575c4b719780a0c2585c270e6f2fb16 | acttx/Python | /Comp Fund 2/Lab9/road.py | 8,547 | 3.859375 | 4 | import math
from edge import Edge
from comparable import Comparable
"""
Background to Find Direction of Travel:
If you are traveling:
Due East: you are moving in the positive x direction
Due North: you are moving in the positive y direction
Due West: you are moving in the negative x direction
Due South: you are moving in the negative y direction
From any point in a plane one can travel 360 degrees.
The 360 degrees can be divided into 4 quadrants of 90 degrees each.
The angles run from 0-90 degrees in a counter-clockwise direction
through each of the four quadrants defined below:
a) East to North: called Quadrant I
b) North to West: called Quadrant II
c) West to South: called Quadrant III
d) South to East: called Quadrant IV
The possible directions of travel are
Quadrant I: E, ENE, NE, NNE, N
Quadrant II: N, NNW, NW, WNW, W
Quadrant III: W, WSW, SW, SSW, S
Quadrant IV; S, SSE, SE, ESE. E
The angle slices in these quadrants correspond to traveling in
one of 16 directions:
Quadrant I (1): [0.00, 11.25) : 'E'
[11.25, 33.75) : 'ENE'
[33.75, 56.25) : 'NE'
[56.25, 78.75) : 'NNE'
[78.75, 90.0) : 'N'
Quadrant II (2): [0.00, 11.25) : 'N',
[11.25, 33.75) : 'NNW'
[33.75, 56.25) : 'NW'
[56.25, 78.75) : 'WNW'
[78.75, 90.0) : 'W'
Quadrant III (3): [0.00, 11.25) : 'W'
[11.25, 33.75) : 'WSW'
[33.75, 56.25) : 'SW'
[56.25, 78.75) : 'SSW'
[78.75, 90.0) : 'S'
Quadrant IV (4): [0.00, 11.25) : 'S'
[11.25, 33.75) : 'SSE'
[33.75, 56.25) : 'SE'
[56.25, 78.75) : 'ESE'
[78.75, 90.0) : 'E'
To determine the quadrant, you need to know the relative
positions between x1 and x2 and between y1 and y2
a) Quadrant I: (x1 < x2 & y1 <= y2)
b) Quadrant II: (x1 >= x2 & y1 < y2)
c) Quadrant III:(x1 > x2 & y1 >= y2)
d) Quadrant IV: (x1 >= x2 & y1 > y2)
To find the direction of travel, you need to find an angle
between the line from P1 to P2 and either
a) a line parallel to the x-axis OR
b) a line parallel to the y-axis
In order to find the angle A in radians, which is the angle between
the line from P1 to P2, and the line parallel to either the x-axis for
Quadrants I and III or the y-axis for Quadrants II and IV, you need
to use:
angle_A = arctan((y2-y1) / (x2-x1))
The Python math library has a function for this
angle_A = math.atan ((y2-y1) / (x2-x1))
This gives the angle in radians. You must convert the angle to degrees.
Use the Python math library function:
angle_A_deg = math.degrees (angle_A)
If the direction is in Quadrants II or IV, then add 90 degrees.
To compute the distance, use the distance formula
distance = SQRT [(x2-x1)**2 + (y2-y1)**2]
The Python math library has a function for this
distance = math.sqrt ((x2-x1)**2 + (y2-y1)**2)
"""
class Road(Edge, Comparable):
"""
This class represents a Road on a map (Graph)
"""
def __init__(self, from_city, to_city):
"""
Creates a new Road
New Instance variables:
self.direction: str
Set Edge instance variable:
self weight: float
This is the distance stored in miles
Call the method comp_direction to set
the direction and weight (in miles)
"""
super().__init__(from_city, to_city)
direction, distance = self.comp_direction()
self.direction = direction
self.weight = distance
def get_direction(self):
"""
Return the direction set in the constructor
"""
return self.direction
def comp_direction(self):
"""
Compute and return the direction of the Road
and the distance between the City vertices
Note: Do NOT round any values (especially GPS) in this method,
we want them to have their max precision.
Only do rounding when displaying values
This is called in the constructor
"""
# Get the points from the GPS coordinates of each City
# These are in degrees, change to radians
# Point 1
x1 = self.from_vertex.get_X()
y1 = self.from_vertex.get_Y()
# Point 2
x2 = self.to_vertex.get_X()
y2 = self.to_vertex.get_Y()
# Convert from degrees to radian
x1 = math.radians(x1)
y1 = math.radians(y1)
x2 = math.radians(x2)
y2 = math.radians(y2)
# Given the x and y coordinates of P1 and P2,
# find the quadrant in which the angle exists
quadrant = self.find_quadrant(x1, y1, x2, y2)
# Given the x and y coordinates of P1 and P2 and the quadrant,
# find the angle between the x or y axis and the line from P1 to P2.
# Return the angle in degrees
degrees = self.compute_angle(x1, y1, x2, y2, quadrant)
# Using the angle and quadrant, find the direction
# This function must use a dictionary
direction = self.compute_direction(degrees, quadrant)
# Find the distance between the points P1 and P2
# Convert the distance to miles and return it
dist_miles = self.distance(x1, y1, x2, y2) * 3956
return direction, dist_miles
def find_quadrant(self, x1, y1, x2, y2):
"""
a) Quadrant I: when x2 > x1 and y2 >= y1
b) Quadrant II: when x2 <= x1 and y2 > y1
c) Quadrant III: when x2 < x1 and y2 <= y1
d) Quadrant IV: when x2 >= x1 and y2 < y1
"""
quadrant = 0
if x2 > x1 and y2 >= y1:
quadrant = 1
elif x2 <= x1 and y2 > y1:
quadrant = 2
elif x2 < x1 and y2 <= y1:
quadrant = 3
elif x2 >= x1 and y2 < y1:
quadrant = 4
return quadrant
def distance(self, x1, y1, x2, y2):
"""
Use distance formula to find length of line from P1 to P2
"""
dist = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
return dist
def compute_angle(self, x1, y1, x2, y2, quadrant):
"""
Use the trig formula: atan = (y2-y1) / (x2-x1)
Convert radians to degrees
"""
# Radian formula
angle_A = math.atan((y2 - y1) / (x2 - x1))
# Convert to degrees based on quadrant
if quadrant == 2 or quadrant == 4:
angle_A_deg = math.degrees(angle_A) + 90
else:
angle_A_deg = math.degrees(angle_A)
return angle_A_deg
def compute_direction(self, angle, quadrant):
"""
Create a dictionary for each quadrant that holds the angle slices
for each direction. The key is a 2-tuple holding the degrees
(low, high) of the angle slices, and the value is the direction
"""
dict_Q1 = {(00.00, 11.25): 'E', (11.25, 33.75): 'ENE',
(33.75, 56.25): 'NE', (56.25, 78.75): 'NNE',
(78.75, 90.00): 'N'}
dict_Q2 = {(00.00, 11.25): 'N', (11.25, 33.75): 'NNW',
(33.75, 56.25): 'NW', (56.25, 78.75): 'WNW',
(78.75, 90.00): 'W'}
dict_Q3 = {(00.00, 11.25): 'W', (11.25, 33.75): 'WSW',
(33.75, 56.25): 'SW', (56.25, 78.75): 'SSW',
(78.75, 90.00): 'S'}
dict_Q4 = {(00.00, 11.25): 'S', (11.25, 33.75): 'SSE',
(33.75, 56.25): 'SE', (56.25, 78.75): 'ESE',
(78.75, 90.00): 'E'}
if quadrant == 1:
for k, v in dict_Q1.items():
if k[0] <= angle < k[1]:
return v
elif quadrant == 2:
for k, v in dict_Q2.items():
if k[0] <= angle < k[1]:
return v
elif quadrant == 3:
for k, v in dict_Q3.items():
if k[0] <= angle < k[1]:
return v
elif quadrant == 4:
for k, v in dict_Q4.items():
if k[0] <= angle < k[1]:
return v
def __str__(self):
"""
Return road information as a string
"""
return self.from_vertex.get_name() + " to " + self.to_vertex.get_name() + " traveling " + self.direction + " for " + "{0:.2f}".format(
self.weight) + " miles."
|
5fbadcc16da279332b3cf317155a683f3744e93d | acttx/Python | /Comp Fund 2/Lab4/person_main.py | 3,160 | 4.1875 | 4 | from comparable import Comparable
from personList import PersonList
from person import Person
from sort_search_funcs import *
def main():
"""
This main function creates a PersonList object and populates it
with the contents of a data file containing 30 records each
containing the first name and birthdate as month day year
separated by commas: Merli,9,10,1998
Next, a request is made to search for a certain Person.
A Person object is created from the input.
Then a linear search is performed with the Person object
If the Person is located in the list, its index is returned
Otherwise, -1 is returned.
The number of compares for the linear search is displayed
Next, a bubble sort is executed to sort the PersonList.
The sorted list is displayed, along with the number of
compares it took to sort it
Next, a request is made to search for another Person.
A Person object is created from the input.
Then a binary search is performed with the Person object
If the Person is located in the sorted list, its index is returned
Otherwise, -1 is returned.
The number of compares for the binary search is displayed
"""
# Create a PersonList object and add the data
p_list = PersonList()
p_list.populate("persons.csv")
# Request a person to search
print("List searched using linear search")
print()
name = input("Who do you want to search for?")
bdate = input("What is their birthdate? (mm-dd-yyyy)")
print()
# Create a person object from the input
month, day, year = bdate.split('-')
p_obj = Person(name, int(year), int(month), int(day))
# Do a linear search
index = p_list.search(linear_search, p_obj)
if index == -1:
print(name, "is not in the list")
else:
print(name, "is at position", index, "in the list")
# Display the number of compares
print()
print("The number of compares are", Comparable.get_num_compares())
print()
# Reset the compare count
Comparable.clear_compares()
# Sort the list using bubble sort
p_list.sort(bubble_sort)
print("List sorted by bubble sort")
for p in p_list:
print(p)
# Display the number of compares
print()
print("The number of compares are", Comparable.get_num_compares())
print()
# Reset the compare count
Comparable.clear_compares()
# Request a person to search
print("List searched using binary search")
print()
name = input("Who do you want to search for?")
bdate = input("What is their birthdate? (mm-dd-yyyy)")
print()
# Create a person object from the input
month, day, year = bdate.split('-')
p_obj = Person(name, int(year), int(month), int(day))
# Do a binary search
index = p_list.search(binary_search, p_obj)
if index == -1:
print(name, "is not in the list")
else:
print(name, "is at position", index, "in the list")
# Display the number of compares
print()
print("The number of compares are", Comparable.get_num_compares())
main()
|
6b789ec1822bfeef3b0518c2114a51dee2425424 | acttx/Python | /Comp Fund 2/Lab8/charCount.py | 530 | 3.75 | 4 | from comparable import Comparable
class CharCount(Comparable):
def __init__(self, char, count):
self.char = char
self.count = count
def get_char(self):
return self.char
def get_count(self):
return self.count
def compare(self, other_charCount):
if self.char < other_charCount.char:
return -1
if self.char > other_charCount.char:
return 1
return 0
def __str__(self):
return str(self.char) + " : " + str(self.count)
|
62ef143a7d1a7dd420ad2f2f4b8a4ec9dda89f4f | DanielOram/simple-python-functions | /blueberry.py | 2,627 | 4.625 | 5 | #Author: Daniel Oram
#Code club Manurewa intermediate
#This line stores all the words typed from keyboard when you press enter
myString = raw_input()
#Lets print out myString so that we can see proof of our awesome typing skills!
#Try typing myString between the brackets of print() below
print()
#With our string we want to make sure that the first letter of each word is a capital letter
#Try editing myString by calling .title() at the end of myString below - This Will Capitalise Every Word In Our String
myCapitalString = myString
print("My Capitalised String looks like \"" + myCapitalString + "\"")
#Now we want to reverse myString so that it looks backwards!
#Try reversing myString by putting .join(reversed(myCapitalString)) after the empty string below - it will look like this -> ''.join(reversed(myCapitalString))
myBackwardsString = ''
#Lets see how we did!
print(myBackwardsString)
#Whoa that looks weird!
#Lets reverse our string back so that it looks like normal!
#Can you do that just like we did before?
myForwardString = '' #remember to use myBackwardsString instead of myCapitalString !
print("My backwards string = " + "\"" + myBackwardsString + "\"")
#Ok phew! we should be back to normal
#Lets try reverse our string again but this time we want to reverse the word order! NOT the letter order!
#To do this we need to find a way to split our string up into the individual words
#Try adding .split() to the end of myForwardString kind of like we did before
myListOfWords = ["We", "want", "our", "String", "to", "look", "like", "this!"] #replace the [...] with something that looks like line 27!
#Now lets reverse our List so that the words are in reverse order!
myBackwardsListOfWords = reversed(["Replace","this", "list", "with", "the", "correct", "list"]) #put myListOfWords here
#Before we can print it out we must convert our list of words back into a string!
#Our string was split into several different strings and now we need to join them back together
#HINT: we want to use the .join() function that we used earlier but this time we just want to put our list of words inside the brackets and
# NOT reversed(myBackwardsListOfWords) inside of the brackets!
myJoinedString = ''.join(["Replace", "me", "with", "the", "right", "list!"]) # replace the [...] with the right variable!
print(myJoinedString)
#Hmmm our list is now in reverse.. but it's hard to read!
#Go back and fix our issue by adding a space between the '' above. That will add a space character between every word in our list when it joins it together!
#Nice job! You've finished blueberry.py
|
15cc2f889516a57be1129b8cad373084222f2c30 | viniciuschiele/solvedit | /strings/is_permutation.py | 719 | 4.125 | 4 | """
Explanation:
Permutation is all possible arrangements of a set of things, where the order is important.
Question:
Given two strings, write a method to decide if one is a permutation of the other.
"""
from unittest import TestCase
def is_permutation(s1, s2):
if not s1 or not s2:
return False
if len(s1) != len(s2):
return False
return sorted(s1) == sorted(s2)
class Test(TestCase):
def test_valid_permutation(self):
self.assertTrue(is_permutation('abc', 'cab'))
self.assertTrue(is_permutation('159', '915'))
def test_invalid_permutation(self):
self.assertFalse(is_permutation('abc', 'def'))
self.assertFalse(is_permutation('123', '124'))
|
9332ac35cb63d27f65404bb86dfc6370c919c2be | viniciuschiele/solvedit | /strings/is_permutation_of_palindrome.py | 1,117 | 4.125 | 4 | """
Explanation:
Permutation is all possible arrangements of a set of things, where the order is important.
Palindrome is a word or phrase that is the same forwards and backwards.
A string to be a permutation of palindrome, each char must have an even count
and at most one char can have an odd count.
Question:
Given a string, write a function to check if it is a permutation of a palindrome.
"""
from unittest import TestCase
def is_permutation_of_palindrome(s):
counter = [0] * 256
count_odd = 0
for c in s:
char_code = ord(c)
counter[char_code] += 1
if counter[char_code] % 2 == 1:
count_odd += 1
else:
count_odd -= 1
return count_odd <= 1
class Test(TestCase):
def test_valid_permutation_of_palindrome(self):
self.assertTrue(is_permutation_of_palindrome('pali pali'))
self.assertTrue(is_permutation_of_palindrome('abc111cba'))
def test_non_permutation_of_palindrome(self):
self.assertFalse(is_permutation_of_palindrome('pali'))
self.assertFalse(is_permutation_of_palindrome('abc1112cba'))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.