blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
5165e39c4ff20f645ed4d1d725a3a6becd002778 | ashishbansal27/DSA-Treehouse | /BinarySearch.py | 740 | 4.125 | 4 | #primary assumption for this binary search is that the
#list should be sorted already.
def binary_search (list, target):
first = 0
last = len(list)-1
while first <= last:
midpoint = (first + last)//2
if list[midpoint]== target:
return midpoint
elif list[midpoint] < target :
first = midpoint + 1
else :
last = midpoint - 1
return None
#summary of above code :
#two variables named first and last to indicate the starting and ending point
#of the list.
# the while loop would run till the first value is less than or equal to last
# then we update the values of first and last.
a= [x for x in range(1,11)]
print(a)
print(binary_search(a,1))
|
b99316dcaf95db6d42f80537e0c6cb57acb2e107 | lgaultie/BT_Machine_learning | /Day02/ex01/main.py | 1,507 | 3.921875 | 4 | #!/usr/bin/env python
'''Implement the what_are_the_vars function that returns an object with the
right attributes. You will have to modify the "instance" ObjectC, NOT THE CLASS.
Have a look to getattr, setattr.'''
class ObjectC(object):
def __init__(self):
pass
def what_are_the_vars(*args, **kwargs):
"""Your code"""
obj = ObjectC()
for i in range(len(args)):
# creating a new attribute in the instance of obj: var_i
setattr(obj, "var_{}".format(i), args[i])
for x in kwargs:
# dir() gets all attributes/methods/fields/etc of an object
if x in dir(obj):
return
setattr(obj, x, kwargs[x])
return (obj)
def doom_printer(obj):
if obj is None:
print("ERROR")
print("end")
return
# dir() gets all attributes/methods/fields/etc of an object
for attr in dir(obj):
if attr[0] != '_':
# The getattr() method returns the value of the named attribute of an object.
# class Person:
# age = 23
# name = "Adam"
# person = Person()
# print('The age is:', getattr(person, "age"))
# print('The age is:', person.age)
# >> The age is: 23
# >> The age is: 23
value = getattr(obj, attr)
print("{}: {}".format(attr, value))
print("end")
if __name__ == "__main__":
obj = what_are_the_vars(7)
doom_printer(obj)
obj = what_are_the_vars("ft_lol", "Hi")
doom_printer(obj)
obj = what_are_the_vars()
doom_printer(obj)
obj = what_are_the_vars(12, "Yes", [0, 0, 0], a=10, hello="world")
doom_printer(obj)
obj = what_are_the_vars(42, a=10, var_0="world")
doom_printer(obj)
|
f3607d3692bbe899356d1cf3b053468de24bcbd5 | lgaultie/BT_Machine_learning | /Day02/ex00/ft_map.py | 374 | 3.90625 | 4 | #!/usr/bin/env python
def addition(n):
return n + n
def ft_map(function_to_apply, list_of_inputs):
result = []
for i in list_of_inputs:
result.append(function_to_apply(i))
return result
numbers = [1, 2, 3, 4]
res = ft_map(addition, numbers)
print (res)
chars = ['s', 'k', 'k', 'a', 'v']
converted = list(ft_map(lambda s: str(s).upper(), chars))
print(converted)
|
b0f1ac0ab7122c36d4a2fb94e42bf018228827c3 | cugis2019nyc/cugis2019nyc-jadabaeda | /day1code.py | 1,007 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
print("hello world")
print("my name is jada")
print("1226")
5*2
5/2
5-2
5**2
8/9*3
def add(a,b):
add = a+b
print(add)
add(2,3)
print("the sum of 23,70,and 97 is")
def add(a,b,c):
add = a+b+c
print("the sum is ", add)
add(23,70,97)
def aqua(a,b,c):
aqua = a*b*c
print("the product of" ,a,b, "and" ,c, "is" ,aqua)
aqua(5,5,5)
1/2*2*1
1/2*11*19
def area(b,h):
area = 1/2*b*h
print(area)
print("the area of a triangle with base", b, "and height", h, "is volume", area)
area(11, 19)
print("cwhite chocolate")
print("milk chocolate")
chocolate1="milk"
chocolate2="dark"
chocolate3="white"
milk=5
dark=6
white=8
milk = milk+3
milk
milk = milk-3
milk
print(milk+2)
import math
dir(math)
math.factorial(7)
math.sqrt(350)
math.exp(1)
math.pow(2.718281828459045,2)
|
343570c2210214071c5e400f4cce9820346e7ace | SergioO21/intermediate_python | /list_and_dicts.py | 778 | 3.765625 | 4 | def run():
my_list = {1, "Hello", True, 4.5}
my_dict = {"firstname": "Sergio", "lastname": "Orejarena"}
super_list = [
{"firstname": "Sergio", "lastname": "Orejarena"},
{"firstname": "Alberto", "lastname": "Casas"},
{"firstname": "Maria", "lastname": "Castillo"},
{"firstname": "Alan", "lastname": "Contreras"},
{"firstname": "Sara", "lastname": "Roman"}
]
super_dict = {
"natural_nums": [1, 2, 3, 4, 5],
"integer_nums": [-1, -2, 0, 1, 2],
"floating_nums": [1.1, 4.5, 6.43]
}
for key, value in super_dict.items():
print(key, "-", value)
# for key, value in super_list:
# print(key, "-", value)
if __name__ == "__main__":
run()
|
23ead3ddd7505cecc2cef56fd2e793407481e32d | AnshulPatni/CMPE255 | /Activity-classification-1.py | 10,622 | 3.578125 | 4 |
# coding: utf-8
# # kNN Classification using k-mer frequency representation of text
#
# In this project, we will create a program to transform text into vectors using a slightly different technique than previously learned, and then perform kNN based classification on the resulting vectors. We will be using the badges UCI dataset (https://archive.ics.uci.edu/ml/machine-learning-databases/badges/badges.data), which contains names of some conference attendees along with a "+" or "-" class for each name. We will first make the text lowercase and separate the class from the badge name for each object, e.g., "+ Naoki Abe" should be turned into the object "naoki abe" with class "+". We will keep track of the original name ("Naoki Abe") associated with the vector.
#
# Our program will have two input parameters, c and k. Given the input parameter c, for each name, it will construct a vector of c-mer terms (usually called k-mers, but I am calling them c-mers since the input variable k is being used for kNN) of the required c length, by enumerating all subsequences of length c within the name. For example, if c=3, “naoki abe” becomes < “nao”, “aok”, “oki”, “ki “, “i a”, “ ab”, “abe” >. Finally, we will use the same technique we learned for word-based terms to construct sparse term-frequency vectors for each of the objects.
#
# Using the constructed vectors and their associated classes, given the input parameter k, we will construct a program that should perform kNN based classification using cosine similarity and 10-fold cross-validation and report the average classification accuracy among all tests. The class of the test sample should be chosen by majority vote, with ties broken in favor of the class with the highest average similarity. In the rare case that the test sample does not have any neighbors (no features in common with any training samples), we will assign a predicted class label by drawing a random value from a uniform distribution over [0,1) and classifying the test sample as “+” if the value is greater than 0.5 and “-“ otherwise.
#
# In[1]:
import numpy as np
import pandas as pd
import scipy.sparse as sp
from numpy.linalg import norm
from collections import Counter, defaultdict
from scipy.sparse import csr_matrix
# The code below reads the badges dataset into the variable `df` and extracts the string data associated with each person in the `vals` variable. Write code to split the strings in vals into their component names and classes. The `names` and `cls` lists should hold those components such that the $i$th person's name will be in `names[i]` and their associated class in `cls[i]`.
# In[2]:
# read in the dataset
df = pd.read_csv(
filepath_or_buffer='https://archive.ics.uci.edu/ml/machine-learning-databases/badges/badges.data',
header=None,
sep=',')
# separate names from classes
vals = df.iloc[:,:].values
vals_list = vals.tolist()
cls = []
names = []
for x in vals_list:
cls.append(x[0].split(' ', 1)[0])
names.append(x[0].split(' ', 1)[1])
### FILL IN THE BLANKS ###
# Write a function that, given a name and a `c-mer` length parameter `c`, will create the list of `c-mers` for the name.
# In[3]:
def cmer(name, c=3):
r""" Given a name and parameter c, return the vector of c-mers associated with the name
"""
name = name.lower()
### FILL IN THE BLANKS ###
v = []
for x in range(0, len(name)-c+1):
v.append(name[x:x+c])
return v
# The following functions will be useful in later tasks. Study them carefully.
# In[4]:
def build_matrix(docs):
r""" Build sparse matrix from a list of documents,
each of which is a list of word/terms in the document.
"""
nrows = len(docs)
idx = {}
tid = 0
nnz = 0
for d in docs:
nnz += len(set(d))
for w in d:
if w not in idx:
idx[w] = tid
tid += 1
ncols = len(idx)
# set up memory
ind = np.zeros(nnz, dtype=np.int)
val = np.zeros(nnz, dtype=np.double)
ptr = np.zeros(nrows+1, dtype=np.int)
i = 0 # document ID / row counter
n = 0 # non-zero counter
# transfer values
for d in docs:
cnt = Counter(d)
keys = list(k for k,_ in cnt.most_common())
l = len(keys)
for j,k in enumerate(keys):
ind[j+n] = idx[k]
val[j+n] = cnt[k]
ptr[i+1] = ptr[i] + l
n += l
i += 1
mat = csr_matrix((val, ind, ptr), shape=(nrows, ncols), dtype=np.double)
mat.sort_indices()
return mat
def csr_info(mat, name="", non_empy=False):
r""" Print out info about this CSR matrix. If non_empy,
report number of non-empty rows and cols as well
"""
if non_empy:
print("%s [nrows %d (%d non-empty), ncols %d (%d non-empty), nnz %d]" % (
name, mat.shape[0],
sum(1 if mat.indptr[i+1] > mat.indptr[i] else 0
for i in range(mat.shape[0])),
mat.shape[1], len(np.unique(mat.indices)),
len(mat.data)))
else:
print( "%s [nrows %d, ncols %d, nnz %d]" % (name,
mat.shape[0], mat.shape[1], len(mat.data)) )
def csr_l2normalize(mat, copy=False, **kargs):
r""" Normalize the rows of a CSR matrix by their L-2 norm.
If copy is True, returns a copy of the normalized matrix.
"""
if copy is True:
mat = mat.copy()
nrows = mat.shape[0]
nnz = mat.nnz
ind, val, ptr = mat.indices, mat.data, mat.indptr
# normalize
for i in range(nrows):
rsum = 0.0
for j in range(ptr[i], ptr[i+1]):
rsum += val[j]**2
if rsum == 0.0:
continue # do not normalize empty rows
rsum = 1.0/np.sqrt(rsum)
for j in range(ptr[i], ptr[i+1]):
val[j] *= rsum
if copy is True:
return mat
def namesToMatrix(names, c):
docs = [cmer(n, c) for n in names]
return build_matrix(docs)
# Compare the sparse matrix statistics (via `csr_info`) for c-mer representations of the names given $c\in\{1,2,3\}$.
# In[12]:
for c in range(1, 4):
mat = namesToMatrix(names, c)
csr_info(mat)
# We'll now define a function to search for the top-$k$ neighbors for a given name (one of the objects the dataset), where proximity is computed via cosine similarity.
# In[13]:
def findNeighborsForName(name, c=1, k=1):
# first, find the document for the given name
id = -1
for i in range(len(names)):
if names[i] == name:
id = i
break
if id == -1:
print("Name %s not found." % name)
return []
# now, compute similarities of name's vector against all other name vectors
mat = namesToMatrix(names, c)
csr_l2normalize(mat)
x = mat[id,:]
dots = x.dot(mat.T)
dots[0,id] = -1 # invalidate self-similarity
sims = list(zip(dots.indices, dots.data))
sims.sort(key=lambda x: x[1], reverse=True)
return [names[s[0]] for s in sims[:k] if s[1] > 0 ]
# Let c=2 and k=5. Which are the closest neighbors for “Michael Kearns”, in decreasing order of similarity?
# In[14]:
findNeighborsForName("Michael Kearns", c=2, k=5)
# Finally, we'll define a couple functions to perform $d$-fold cross-validation, defaulting to $d=10$. Double-check the code for errors. What does the line
# ```python
# tc = Counter(clstr[s[0]] for s in sims[:k]).most_common(2)
# ```
# do?
# In[15]:
def splitData(mat, cls, fold=1, d=10):
r""" Split the matrix and class info into train and test data using d-fold hold-out
"""
n = mat.shape[0]
r = int(np.ceil(n*1.0/d))
mattr = []
clstr = []
# split mat and cls into d folds
for f in range(d):
if f+1 != fold:
mattr.append( mat[f*r: min((f+1)*r, n)] )
clstr.extend( cls[f*r: min((f+1)*r, n)] )
# join all fold matrices that are not the test matrix
train = sp.vstack(mattr, format='csr')
# extract the test matrix and class values associated with the test rows
test = mat[(fold-1)*r: min(fold*r, n), :]
clste = cls[(fold-1)*r: min(fold*r, n)]
return train, clstr, test, clste
def classifyNames(names, cls, c=3, k=3, d=10):
r""" Classify names using c-mer frequency vector representations of the names and kNN classification with
cosine similarity and 10-fold cross validation
"""
docs = [cmer(n, c) for n in names]
mat = build_matrix(docs)
# since we're using cosine similarity, normalize the vectors
csr_l2normalize(mat)
def classify(x, train, clstr):
r""" Classify vector x using kNN and majority vote rule given training data and associated classes
"""
# find nearest neighbors for x
dots = x.dot(train.T)
sims = list(zip(dots.indices, dots.data))
if len(sims) == 0:
# could not find any neighbors
return '+' if np.random.rand() > 0.5 else '-'
sims.sort(key=lambda x: x[1], reverse=True)
tc = Counter(clstr[s[0]] for s in sims[:k]).most_common(2)
if len(tc) < 2 or tc[0][1] > tc[1][1]:
# majority vote
return tc[0][0]
# tie break
tc = defaultdict(float)
for s in sims[:k]:
tc[clstr[s[0]]] += s[1]
return sorted(tc.items(), key=lambda x: x[1], reverse=True)[0][0]
macc = 0.0
for f in range(d):
# split data into training and testing
train, clstr, test, clste = splitData(mat, cls, f+1, d)
# predict the class of each test sample
clspr = [ classify(test[i,:], train, clstr) for i in range(test.shape[0]) ]
# compute the accuracy of the prediction
acc = 0.0
for i in range(len(clste)):
if clste[i] == clspr[i]:
acc += 1
acc /= len(clste)
macc += acc
return macc/d
# Given $c \in \{1,\ldots,4\}$ and $k \in \{1,\ldots,6\}$, which meta-parameters result in the highest accuracy?
# In[28]:
c = [1, 2, 3, 4]
k = [1, 2, 3, 4, 5, 6]
list_accuracy = []
for x in range(0, len(c)):
for y in range(0, len(k)):
temp = classifyNames(names, cls, c[x], k[y], d=10)
if(list_accuracy):
if(temp > max(list_accuracy)):
c_max = c[x]
k_max = k[y]
list_accuracy.append(temp)
print(list_accuracy)
print("\n")
print("Highest accuracy is " + str(max(list_accuracy)) + " for c = " + str(c_max) + " and k = " + str(k_max))
|
b0d01c99a84369fd367d3116a6b4f978b20851d6 | cdew888/Documents | /Average rainfall.py | 327 | 4.03125 | 4 | #Corey Dew
#cs21
#question 5
total = 0
n = int(input("Enter number of years: "))
for x in range(1, n + 1):
print("for year" ,x,)
for months in range(1,13):
rainfall = float(input("Enter rainfall amount for month in inches: "))
total += rainfall
print(total)
print("average rainfall: ",total / (12 * n))
|
c134eb7a7374a36f8bfc00605f59f69c14bbddc2 | cdew888/Documents | /Test Average and Grade.py | 1,298 | 4 | 4 | #Corey Dew
#cs21
#chp.5 question 15
def main():
score1 = float(input("Enter score 1: "))
score2 = float(input("Enter score 2: "))
score3 = float(input("Enter score 3: "))
score4 = float(input("Enter score 4: "))
score5 = float(input("Enter score 5: "))
average = calc_average(score1, score2, score3, score4, score5)
print("score\t\tnumeric grade\tletter grade")
print("-------------------------------------------")
print("score 1:\t\t", score1, "\t\t", determine_grade(score1))
print("score 2:\t\t", score2, "\t\t", determine_grade(score2))
print("score 3:\t\t", score3, "\t\t", determine_grade(score3))
print("score 4:\t\t", score4, "\t\t", determine_grade(score4))
print("score 5:\t\t", score5, "\t\t", determine_grade(score5))
print("------------------------------------------------------")
print("Average score:\t", average, "\t\t", determine_grade(average))
def calc_average(s1, s2, s3, s4, s5):
return (s1 + s2 + s3 +s4 + s5) / 5.0
def determine_grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"
main()
|
f70cc10b2c5b38a1e8efb4b2aeb92eb8e4ab72d5 | cdew888/Documents | /paint_job.py | 586 | 3.875 | 4 | #Corey Dew
#cs21
#exercise 8
def main():
wall_space = int(input("Enter wall space in square feet: "))
paint_price = int(input("Enter paint price per gallon: "))
paint_gallon = int(input("Gallons of paint: "))
labor_hours = paint_gallon * 8
paint_charges = paint_price * paint_gallon
print("Paint charges: $", format(paint_charges, '.2f'))
labor_charges = paint_gallon * labor_hours
print("Labor charges: $", format(labor126_charges, '.2f'))
total_cost = paint_charges + labor_charges
print("Total cost: $", format(total_cost, '.2f'))
main()
|
744ebbfbc67fb3e79d08e00a6e6d0ff2535d40e7 | cdew888/Documents | /driver_test.py | 2,212 | 3.734375 | 4 | #Corey Dew
#cs21
#Exercise 7
def main():
tot_score = 0
tot_correct = 0
tot_wrong = 0
wrong_list = []
try:
answer_sheet = ['A', 'C', 'A', 'A', 'D', 'B', 'C', 'A', 'C', 'B', 'A', 'D', 'C', 'A', 'D', 'C', 'B', 'B', 'D', 'A']
student_answers = open("student_solution.txt", 'r')
student_answer_list = []
wrong_list = []
for line in student_answers:
line = line.rstrip("\n")
student_answer_list.append(line)
print("Your answer sheet: ", student_answer_list)
for i in range(len(answer_sheet)):
if answer_sheet[i] == student_answer_list[i]:
tot_correct += 1
else:
tot_wrong += 1
wrong_list.append(i + 1)
if tot_correct >= 15:
print("You have passed the test.")
else:
print("You have failed the test.")
print("You have", tot_correct, "questions correct")
print("You have", tot_wrong, "questions correct")
print("These are the questions you have wrong: ", wrong_list)
except:
print()
##
##
## for line in student_answers:
## line = student_answers.rstrip("\n")
## student_answers.append(line)
##
## while tot_score < len(answer_sheet):
## if answer_sheet[tot_score] == student_answers:
## tot_correct += 1
## tot_score += 1
## else:
## tot_wrong += 1
## wrong_list.append(tot_score)
## tot_score += 1
##
## if tot_score >= 15:
## print("You have passed the test")
## print("You have", tot_correct, "correct answers")
## print("You have", tot_wrong, "wrong answers")
## else:
## print("You have failed the test")
## print("You have", tot_correct, "correct answers")
## print("You have", tot_wrong, "wrong answers")
##
## student_answers.close()
## except IOError:
## print("Error: File does not exist")
##
main()
|
8c3ac2c382b67088973a4f8eb276bfebe63068e6 | cdew888/Documents | /baseball2.py | 1,652 | 3.6875 | 4 | #Corey Dew
#cs21
#Baseball question
#Global constant for the base year
BASE_YEAR = 1903
SKIP_YEAR1 = 1904
SKIP_YEAR2 = 1994
def main():
#Local dictionary variables
year_dict = {}
count_dict = {}
#Open the file for reading
input_file = open('WorldSeriesWinners.txt', 'r')
#Read all the lines in the file into a list
winners = input_file.readlines()
#Fill the dictionaries with the team information.
for i in range(len(winners)):
team = winners[i].rstrip('\n')
#Figure out in which year the team won
#(take into account skipped years)
year = BASE_YEAR + i
#print(year,end=' ')
if year >= SKIP_YEAR1:
year += 1
if year >= SKIP_YEAR2:
year += 1
#print(year)
# Add information to year dictionary
year_dict[str(year)] = team
#Update counting dictionary
if team in count_dict:
count_dict[team] += 1
else:
count_dict[team] = 1
#Recieve user input
year = input("Enter a year in the range 1903-2009: ")
#print results
if year == '1904' or year == '1994':
print("The world series wasn't played in the year", year)
elif year < '1903' or year > '2009':
print("The data for the year", year, "is not included in out database.")
else:
winner = year_dict[year]
wins = count_dict[winner]
print("The team that won the world series in ", year, "is the ", winner, '.', sep='')
print("They won the world series", wins, "times.")
#Call the main function.
main()
|
71ffb03026b7ab5725616862d8b0818c1c099e79 | cdew888/Documents | /temps.py | 1,924 | 3.703125 | 4 | #Corey Dew
#cs21
#Question 4 on pg 562
import tkinter
class MyGUI:
def __init__(self):
self.main_window = tkinter.Tk()
self.left_frame = tkinter.Frame(self.main_window)
self.mid_frame = tkinter.Frame(self.main_window)
self.right_frame = tkinter.Frame(self.main_window)
self.label1 = tkinter.Label(self.left_frame, \
text="Enter the Celsius temperature: ")
self.celsius_entry = tkinter.Entry(self.left_frame, \
width=10)
self.label2 = tkinter.Label(self.mid_frame, \
text="Fahrenheit temperature: ")
self.convert_button = tkinter.Button(self.right_frame, \
text="Convert to Fahrenheit", \
command=self.convert)
self.quit_button = tkinter.Button(self.right_frame, \
text="Quit", \
command=self.main_window.destroy)
self.label1.pack(side='top')
self.label2.pack(side='top')
self.celsius_entry.pack(side='bottom')
self.value = tkinter.StringVar()
self.faren_heit_label = tkinter.Label(self.mid_frame, \
textvariable=self.value)
self.faren_heit_label.pack(side='bottom')
self.left_frame.pack(side='left')
self.mid_frame.pack(side='left')
self.right_frame.pack(side='left')
self.convert_button.pack(side='top')
self.quit_button.pack(side='bottom')
tkinter.mainloop()
def convert(self):
try:
c = float(self.celsius_entry.get())
f = (9 / 5) * c + 32
self.value.set(format(f,'.2f'))
except:
self.value.set("Invalid input")
my_gui = MyGUI()
|
40db8a974a3ce0c6592897f13469565275f98439 | mariomanalu/singular-value-decomposition | /svd-test.py | 1,376 | 3.609375 | 4 | import os
import numpy as np
from PIL import Image
from svd import svd
import matplotlib.pyplot as plt
#%matplotlib inline
# Test file for image reduction
#Load image of Waldo the dog
path = 'WaldoasWaldo.jpg'
img = Image.open(path)
s = float(os.path.getsize(path))/1000
#Print the size of the image
print("Size(dimension): ",img.size)
#plt.title("Original Image (%0.2f Kb):" %s)
#Show the image
#plt.imshow(img)
#Convert the image into matrix
imggray = img.convert('LA')
imgmat = np.array( list(imggray.getdata(band = 0)), float)
imgmat.shape = (imggray.size[1], imggray.size[0])
imgmat = np.matrix(imgmat)
plt.figure()
#plt.imshow(imgmat, cmap = 'gray')
#plt.title("Image after converting it into the Grayscale pattern")
#plt.show()
print("After compression: ")
#Execute the Singular Value Decomposition process
U, S, Vt = np.linalg.svd(imgmat)
#NOTE: One can change the numberOfSingularValues as one wish. Greater number means greater quality.
numberOfSingularValues = 5
cmpimg = np.matrix(U[:, :numberOfSingularValues]) * np.diag(S[:numberOfSingularValues]) * np.matrix(Vt[:numberOfSingularValues,:])
plt.imshow(cmpimg, cmap = 'gray')
plt.show()
result = Image.fromarray((cmpimg ).astype(np.uint8))
imgmat = np.array( list(img.getdata(band = 0)), float)
imgmat.shape = (img.size[1], img.size[0])
imgmat = np.matrix(imgmat)
plt.figure()
plt.imshow(imgmat)
plt.show()
|
62d58103b04775afc2075d0cb84721ebc50dff59 | rohezal/buildings | /converter.py | 1,139 | 3.546875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 25 00:06:57 2020
@author: rohezal
"""
import csv
import sys
number_of_arguments = len(sys.argv)
if(number_of_arguments == 2):
filename = sys.argv[1]
else:
print("usage: converter.py name_of_the_file.csv. Using now converted_BRICS.csv as a default file")
filename = 'BRICS_orignal_.csv'
outfile = open('converted_'+filename, 'w', newline="")
csvwriter = csv.writer(outfile )
with open(filename, newline="", encoding='ISO-8859-1') as csv_file_brics:
csv_reader_brics = csv.reader(csv_file_brics, delimiter=';')
for row in csv_reader_brics:
newrow = []
if(len(row) > 0):
if((row[0][0]).isnumeric()):
for element in row:
if (element == "" or element == "MV"):
element="NaN"
elif(":" not in element):
try:
element = float(element.replace(',', '.'))
except Exception as e:
print("Element: " + element)
print(e)
sys.exit(1)
else:
element = "\"" + element + "\""
newrow.append(element)
if(len(newrow) > 0):
csvwriter.writerow(newrow)
outfile.close
|
568ff4916ba0f33b5d07db164aad2caa0f74cb2a | JediChou/Jedi-Py3Promming | /Piy0102/Piy010202_Ref1.py | 485 | 3.578125 | 4 | # coding: utf-8
if __name__ == '__main__':
"""演示对象引用操作: 赋值"""
# 初始化
x = "blue"
y = "red"
z = x
# 步骤1
print("step 1: initialize")
print("x", x)
print("y", y)
print("z", z)
# 步骤2
z = y
print("step 2: z = y")
print("x", x)
print("y", y)
print("z", z)
# 步骤3
x = z
print("step 3: x = z")
print("x", x)
print("y", y)
print("z", z)
|
d9116da4e1b3116f73b714ea06e1338b3e001d42 | R-Saxena/Hackerearth | /Practice Problems/Basic Programming/Basics of Input-Output/cipher.py | 741 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat May 9 17:20:44 2020
@author: rishabhsaxena01
"""
small = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
cap = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
num = ['0', '1', '2', '3','4','5','6','7','8','9']
# Write your code here
text = input()
ans = ''
number = int(input())
for i in text:
if i in cap:
ans += cap[(cap.index(i)+number)%26]
elif i in small:
ans += small[(small.index(i)+number)%26]
elif i in num:
ans += num[(num.index(i)+number)%10]
else:
ans+=i
print(ans) |
643a5249e39344f8b47d65d96c0ee1e2d8af2bbd | R-Saxena/Hackerearth | /Practice Problems/Basic Programming/Basics of Input-Output/seven segment.py | 520 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat May 9 17:21:55 2020
@author: rishabhsaxena01
"""
matchsticks = [6,2,5,5,4,5,6,3,7,6]
def get_machis(x):
su = 0
for i in x:
su+=matchsticks[int(i)]
return su
# Write your code here
for _ in range(int(input())):
x = input()
machis = get_machis(x)
no = ''
if machis%2==0:
for i in range(int(machis/2)):
no += '1'
else:
no+='7'
for i in range(int(machis/2-1)):
no += '1'
print(no) |
f3358fdeb73065519eafe11fd2755677ddaa5ba3 | R-Saxena/Hackerearth | /Practice Problems/Basic Programming/Basics of Input-Output/Motu_patlu.py | 301 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri May 8 06:48:11 2020
@author: rishabhsaxena01
"""
n = int(input())
i=1
while True:
if i >= n:
print('Patlu')
break
else:
n=n-i
if 2*i >= n:
print('Motu')
break
else:
n=n-2*i
i+=1 |
dc7d32b8b45e63f775fa3641108037e4d240641a | thehellz/Programming | /Py/sum.py | 124 | 4.125 | 4 | number = input("Please eneter a number: ")
sum = 0
for i in range(1, number+1):
sum = sum + i
print 'The sum is', sum
|
9550275c4642ff6209cd2261f06d215b34740c48 | huzhiwen/Graybar_Jobsite_Automation | /lib/notification.py | 1,008 | 3.53125 | 4 | #This code sends the email notification whenever sendmail() function is called
import smtplib
from lib.weight import getWeight
def sendmail(product, jobsite_no):
content = "Hi there, \n"
#content += getWeight(product)
content =content + product + " is running below threshold at jobsite no. " + str(jobsite_no)
#content = "hello"
mail = smtplib.SMTP('smtp.gmail.com', port = 587) #Set up the smtp mail server port
mail.ehlo() #Identify yourself to the server
mail.starttls() #Put the SMTP connection in TLS (Transport Layer Security) mode. All SMTP commands that follow will be encrypted
mail.login('autonotif2017@gmail.com', 'ilab2017') #Login with your email id and password
mail.sendmail('autonotif2017@gmail.com' , 'autonotif2017@gmail.com', content) #This sends the mail. First parameter is from, second is to, and third is the content of the mail
mail.close() #Close the server
|
13aa25d7b7180ab8801be99ee71fcc216c6a1e6b | adamchipmanpenton/BlackJack | /db.py | 406 | 3.5 | 4 | db = "money.txt"
import sys
def openWallet():
try:
wallet = open(db)
wallet = round(float(wallet.readline()),)
return wallet
except FileNotFoundError:
print("count not find money.txt")
print("Exiting program. Bye!")
sys.exit()
def changeAmount(winnings):
with open(db, "w") as file:
for item in winnings:
file.write(item)
|
aa7282b1a04d086834b1f734014eb3747128ccbd | aggy07/Leetcode | /1-100q/67.py | 1,162 | 3.78125 | 4 | '''
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
'''
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
result = ""
carry = 0
index_a, index_b = len(a)-1, len(b)-1
while index_a >= 0 and index_b >= 0:
result = (int(a[index_a]) + int(b[index_b]) + carry)%2 + result
carry = (int(a[index_a]) + int(b[index_b]) + carry)%2
index_a -= 1
index_b -= 1
if index_a >= 0:
while index_a >= 0:
result = (int(a[index_a]) + carry)%2 + result
carry = (int(a[index_a]) + carry)%2
index_a -= 1
elif index_b >= 0:
while index_b >= 0:
result = (int(b[index_b]) + carry)%2 + result
carry = (int(b[index_b]) + carry)%2
index_b -= 1
else:
if carry == 1:
result = str(carry) + result
return result |
15f0f2b2686291cbd5c8be606a95e25517f3abaa | aggy07/Leetcode | /300-400q/317.py | 2,355 | 3.96875 | 4 | '''
You want to build a house on an empty land which reaches all buildings in the shortest amount of distance. You can only move up, down, left and right. You are given a 2D grid of values 0, 1 or 2, where:
Each 0 marks an empty land which you can pass by freely.
Each 1 marks a building which you cannot pass through.
Each 2 marks an obstacle which you cannot pass through.
For example, given three buildings at (0,0), (0,4), (2,2), and an obstacle at (0,2):
1 - 0 - 2 - 0 - 1
| | | | |
0 - 0 - 0 - 0 - 0
| | | | |
0 - 0 - 1 - 0 - 0
The point (1,2) is an ideal empty land to build a house, as the total travel distance of 3+3+1=7 is minimal. So return 7.
Note:
There will be at least one building. If it is not possible to build such house according to the above rules, return -1.
'''
class Solution(object):
def shortestDistance(self, grid):
if not grid:
return -1
def bfs(grid, distance_reach_map, row, col):
if(row < 0 or row > len(grid) or col < 0 or col > len(grid[0])):
return
queue = [[row, col]]
qdist = [1]
direction = [[-1, 0], [0, 1], [1, 0], [0, -1]]
while queue:
x, y = queue.pop(0)
curr_dist = qdist.pop(0)
for dx, dy in direction:
new_x, new_y = x+dx, y+dy
if((0 <= new_x < len(grid)) and (0 <= new_y < len(grid[0])) and grid[new_x][new_y] == 0):
grid[new_x][new_y] = -1
queue.append([new_x, new_y])
temp = distance_reach_map[new_x][new_y]
dist, reach = temp[0], temp[1]
dist += curr_dist
reach += 1
distance_reach_map[new_x][new_y] = [dist, reach]
qdist.append(curr_dist+1)
for row in range(len(grid)):
for col in range(len(grid[0])):
if grid[row][col] == -1:
grid[row][col] =0
r_len, c_len = len(grid), len(grid[0])
distance_reach_map = [[[0, 0]]*c_len for _ in range(r_len)]
buildings = 0
for row in range(len(grid)):
for col in range(len(grid[0])):
if grid[row][col] == 1:
bfs(grid, distance_reach_map, row, col)
buildings += 1
result = float('inf')
for row in range(r_len):
for col in range(c_len):
dist, reach = distance_reach_map[row][col]
if reach == buildings:
result = min(result, dist)
return result
solution = Solution()
grid = [[1, 0, 2, 0, 1],
[0, 0, 0, 0, 0],
[0, 0, 1, 0 ,0]]
print solution.shortestDistance(grid)
|
33c960afb411983482d2b30ed9037ee6017fbd34 | aggy07/Leetcode | /600-700q/673.py | 1,189 | 4.125 | 4 | '''
Given an unsorted array of integers, find the number of longest increasing subsequence.
Example 1:
Input: [1,3,5,4,7]
Output: 2
Explanation: The two longest increasing subsequence are [1, 3, 4, 7] and [1, 3, 5, 7].
Example 2:
Input: [2,2,2,2,2]
Output: 5
Explanation: The length of longest continuous increasing subsequence is 1, and there are 5 subsequences' length is 1, so output 5.
Note: Length of the given array will be not exceed 2000 and the answer is guaranteed to be fit in 32-bit signed int.
'''
class Solution(object):
def findNumberOfLIS(self, nums):
length = [1]*len(nums)
count = [1]*len(nums)
result = 0
for end, num in enumerate(nums):
for start in range(end):
if num > nums[start]:
if length[start] >= length[end]:
length[end] = 1+length[start]
count[end] = count[start]
elif length[start] + 1 == length[end]:
count[end] += count[start]
for index, max_subs in enumerate(count):
if length[index] == max(length):
result += max_subs
return result
|
9ee533969bbce8aec40f6230d3bc01f1f83b5e96 | aggy07/Leetcode | /1000-1100q/1007.py | 1,391 | 4.125 | 4 | '''
In a row of dominoes, A[i] and B[i] represent the top and bottom halves of the i-th domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the i-th domino, so that A[i] and B[i] swap values.
Return the minimum number of rotations so that all the values in A are the same, or all the values in B are the same.
If it cannot be done, return -1.
Input: A = [2,1,2,4,2,2], B = [5,2,6,2,3,2]
Output: 2
Explanation:
The first figure represents the dominoes as given by A and B: before we do any rotations.
If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.
'''
class Solution(object):
def minDominoRotations(self, A, B):
"""
:type A: List[int]
:type B: List[int]
:rtype: int
"""
if len(A) != len(B):
return -1
if len(A) == 0:
return 0
for possibility in set([A[0], B[0]]):
top_rotation, bottom_rotation =0, 0
for a_num, b_num in zip(A, B):
if possibility not in [a_num, b_num]:
break
top_rotation += int(b_num != possibility)
bottom_rotation += int(a_num != possibility)
else:
return min(top_rotation, bottom_rotation)
return -1
|
8bdf3154382cf8cc63599d18b20372d16adbe403 | aggy07/Leetcode | /200-300q/210.py | 1,737 | 4.125 | 4 | '''
There are a total of n courses you have to take, labeled from 0 to n-1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.
There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.
Example 1:
Input: 2, [[1,0]]
Output: [0,1]
Explanation: There are a total of 2 courses to take. To take course 1 you should have finished
course 0. So the correct course order is [0,1] .
'''
class Solution(object):
def findOrder(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: List[int]
"""
graph = [[] for _ in range(numCourses)]
visited = [False for _ in range(numCourses)]
stack = [False for _ in range(numCourses)]
for pair in prerequisites:
x, y = pair
graph[x].append(y)
result = []
for course in range(numCourses):
if visited[course] == False:
if self.dfs(graph, visited, stack, course, result):
return []
return result
def dfs(self, graph, visited, stack, course, result):
visited[course] = True
stack[course] = True
for neigh in graph[course]:
if visited[neigh] == False:
if self.dfs(graph, visited, stack, neigh, result):
return True
elif stack[neigh]:
return True
stack[course] = False
result.append(course)
return False |
4705b012a25fe956c96fc78cc949a305c9e6ad0f | aggy07/Leetcode | /900-1000q/999.py | 3,053 | 4.125 | 4 | '''
On an 8 x 8 chessboard, there is one white rook. There also may be empty squares, white bishops, and black pawns. These are given as characters 'R', '.', 'B', and 'p' respectively. Uppercase characters represent white pieces, and lowercase characters represent black pieces.
The rook moves as in the rules of Chess: it chooses one of four cardinal directions (north, east, west, and south), then moves in that direction until it chooses to stop, reaches the edge of the board, or captures an opposite colored pawn by moving to the same square it occupies. Also, rooks cannot move into the same square as other friendly bishops.
Return the number of pawns the rook can capture in one move.
Input: [[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","R",".",".",".","p"],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]]
Output: 3
Explanation:
In this example the rook is able to capture all the pawns.
'''
class Solution(object):
def numRookCaptures(self, board):
"""
:type board: List[List[str]]
:rtype: int
"""
result = 0
rook_index = (0, 0)
for row in range(len(board)):
for col in range(len(board[0])):
if board[row][col] == 'R':
rook_index = (row, col)
break
flag = True
col = rook_index[1]-1
pawn = 0
while col >= 0:
if board[rook_index[0]][col] == 'B':
flag = False
break
if board[rook_index[0]][col] == 'p':
pawn += 1
break
col -= 1
if flag and pawn != 0:
result += 1
flag = True
col = rook_index[1]+1
pawn = 0
while col < len(board[0]):
if board[rook_index[0]][col] == 'B':
flag = False
break
if board[rook_index[0]][col] == 'p':
pawn += 1
break
col += 1
if flag and pawn != 0:
result += 1
flag = True
row = rook_index[0]+1
pawn = 0
while row < len(board):
if board[row][rook_index[1]] == 'B':
flag = False
break
if board[row][rook_index[1]] == 'p':
pawn += 1
break
row += 1
if flag and pawn != 0:
result += 1
pawn = 0
flag = True
row = rook_index[0]-1
while row >= 0:
if board[row][rook_index[1]] == 'B':
flag = False
break
if board[row][rook_index[1]] == 'p':
pawn += 1
break
row -= 1
if flag and pawn != 0:
result += 1
return result |
fe6472a92a73038fff7fd05feb100394b18805a8 | aggy07/Leetcode | /1000-1100q/1026.py | 1,766 | 3.90625 | 4 | '''
Given the root of a binary tree, find the maximum value V for which there exists different nodes A and B where V = |A.val - B.val| and A is an ancestor of B.
(A node A is an ancestor of B if either: any child of A is equal to B, or any child of A is an ancestor of B.)
Example 1:
8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13
Input: [8,3,10,1,6,null,14,null,null,4,7,13]
Output: 7
Explanation:
We have various ancestor-node differences, some of which are given below :
|8 - 3| = 5
|3 - 7| = 4
|8 - 1| = 7
|10 - 13| = 3
Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.
Note:
The number of nodes in the tree is between 2 and 5000.
Each node will have value between 0 and 100000.
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maxAncestorDiff(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def utility_fun(root, res):
if not root:
return 2147483648, -2147483648, res
if not root.left and not root.right:
return root.val, root.val, res
left_t, lmax_t, res = utility_fun(root.left, res)
right_t, rmax_t, res = utility_fun(root.right, res)
m_val = min(left_t, right_t)
max_val = max(lmax_t, rmax_t)
res = max(res, max(abs(root.val-m_val), abs(root.val-max_val)))
# print res
return min(m_val, root.val), max(max_val, root.val), res
x, x2, res = utility_fun(root, -2147483648)
return abs(res)
|
c1e4eb821ec69861f1ff694e6f7c4cf2e9d68ca8 | aggy07/Leetcode | /100-200q/118.py | 655 | 3.984375 | 4 | '''
Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
Example:
Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
'''
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
triangle = []
for row in range(numRows):
new_row = [0 for _ in range(row+1)]
new_row[0], new_row[-1] = 1, 1
for col in range(1, len(new_row)-1):
new_row[col] = triangle[row-1][col-1] + triangle[row-1][col]
triangle.append(new_row)
return triangle |
e9d57ebf9fe9beec2deb9654248f77541719e780 | aggy07/Leetcode | /100-200q/150.py | 1,602 | 4.21875 | 4 | '''
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Note:
Division between two integers should truncate toward zero.
The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation.
Example 1:
Input: ["2", "1", "+", "3", "*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Example 2:
Input: ["4", "13", "5", "/", "+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6
'''
class Solution(object):
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
if not tokens:
return 0
stack = []
for val in tokens:
if val == '+':
val1 = stack.pop()
val2 = stack.pop()
stack.append(val1 + val2)
elif val == '-':
val1 = stack.pop()
val2 = stack.pop()
stack.append(val2-val1)
elif val == '*':
val1 = stack.pop()
val2 = stack.pop()
stack.append(val2*val1)
elif val == '/':
val1 = stack.pop()
val2 = stack.pop()
if val1*val2 < 0:
stack.append(-(-val2/val1))
else:
stack.append(val2/val1)
else:
stack.append(int(val))
return stack[0] |
f33a0bed8cf001db76705264cf5e73f91233c69b | aggy07/Leetcode | /300-400q/347.py | 749 | 3.875 | 4 | '''
Given a non-empty array of integers, return the k most frequent elements.
For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2]
'''
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
if not nums:
return []
frequency = {}
for num in nums:
if num in frequency:
frequency[num] += 1
else:
frequency[num] = 1
result = []
import heapq
heap = []
for key, value in frequency.iteritems():
heapq.heappush(heap, (-value, key))
for _ in range(k):
result.append(heapq.heappop(heap)[1])
return result |
8f83262573f48ba2f847993cc9ba7ffeb5fc1b17 | aggy07/Leetcode | /1000-1100q/1035.py | 1,872 | 4.15625 | 4 | '''
We write the integers of A and B (in the order they are given) on two separate horizontal lines.
Now, we may draw a straight line connecting two numbers A[i] and B[j] as long as A[i] == B[j], and the line we draw does not intersect any other connecting (non-horizontal) line.
Return the maximum number of connecting lines we can draw in this way.
Example 1:
Input: A = [1,4,2], B = [1,2,4]
Output: 2
Explanation: We can draw 2 uncrossed lines as in the diagram.
We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2.
Example 2:
Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2]
Output: 3
Example 3:
Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1]
Output: 2
Note:
1 <= A.length <= 500
1 <= B.length <= 500
1 <= A[i], B[i] <= 2000
'''
class Solution(object):
def maxUncrossedLines(self, A, B):
"""
:type A: List[int]
:type B: List[int]
:rtype: int
"""
dp = [[0]*len(A) for _ in range(len(B))]
dp[0][0] = 1 if A[0] == B[0] else 0
for index_i in range(1, len(dp)):
dp[index_i][0] = dp[index_i-1][0]
if A[0] == B[index_i]:
dp[index_i][0] = 1
for index_j in range(1, len(dp[0])):
dp[0][index_j] = dp[0][index_j-1]
if B[0] == A[index_j]:
dp[0][index_j] = 1
for index_i in range(1, len(dp)):
for index_j in range(1, len(dp[0])):
if A[index_j] == B[index_i]:
dp[index_i][index_j] = max(dp[index_i-1][index_j-1] + 1, max(dp[index_i-1][index_j], dp[index_i][index_j-1]))
else:
dp[index_i][index_j] = max(dp[index_i-1][index_j-1], max(dp[index_i-1][index_j], dp[index_i][index_j-1]))
return dp[len(B)-1][len(A)-1]
|
d16eafea8552970b70b46db21f3a8db069814a0c | aggy07/Leetcode | /300-400q/395.py | 1,141 | 4.0625 | 4 | '''
Find the length of the longest substring T of a given string (consists of lowercase letters only) such that every character in T appears no less than k times.
Example 1:
Input:
s = "aaabb", k = 3
Output:
3
The longest substring is "aaa", as 'a' is repeated 3 times.
Example 2:
Input:
s = "ababbc", k = 2
Output:
5
The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times.
'''
class Solution(object):
def longestSubstring(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
dict = {}
for c in s:
if c not in dict:
dict[c] = 0
dict[c] += 1
if all(dict[i] >= k for i in dict):
return len(s)
longest = 0
start = 0
for i in range(len(s)):
c = s[i]
if dict[c] < k:
longest = max(longest, self.longestSubstring(s[start:i], k))
start = i + 1
return max(longest, self.longestSubstring(s[start:], k))
|
781daf201b2e2f04d1ad4b398e958355afeca707 | aggy07/Leetcode | /100-200q/159.py | 953 | 3.90625 | 4 | '''
Given a string, find the longest substring that contains only two unique characters. For example, given "abcbbbbcccbdddadacb", the longest substring that contains 2 unique character is "bcbbbbcccb".
'''
class Solution(object):
def lengthOfLongestSubstringTwoDistinct(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
unique_char, start, result = {}, 0, 0
for index, char in enumerate(s):
if char in unique_char:
unique_char[s] += 1
else:
unique_char[s] = 1
if len(unique_char) <= 2:
result = max(result, index-start+1)
else:
while len(unique_char) > 2:
char_index = s[start]
count = unique_char[char_index]
if count == 1:
del unique_char[char_index]
else:
unique_char[char_index] -= 1
start += 1
return result
|
8f212585e03771a5123c4b00aabe2edddff3c9ef | aggy07/Leetcode | /900-1000q/926.py | 1,105 | 3.90625 | 4 | '''
A string of '0's and '1's is monotone increasing if it consists of some number of '0's (possibly 0), followed by some number of '1's (also possibly 0.)
We are given a string S of '0's and '1's, and we may flip any '0' to a '1' or a '1' to a '0'.
Return the minimum number of flips to make S monotone increasing.
Example 1:
Input: "00110"
Output: 1
Explanation: We flip the last digit to get 00111.
Example 2:
Input: "010110"
Output: 2
Explanation: We flip to get 011111, or alternatively 000111.
Example 3:
Input: "00011000"
Output: 2
Explanation: We flip to get 00000000.
Note:
1 <= S.length <= 20000
S only consists of '0' and '1' characters.
'''
class Solution(object):
def minFlipsMonoIncr(self, S):
"""
:type S: str
:rtype: int
"""
ones = [0]
for char in S:
ones.append(ones[-1] + int(char))
# print ones
result = float('inf')
for index in range(len(ones)):
zeroes = len(S) - index - (ones[-1]-ones[index])
result = min(zeroes+ones[index], result)
return result
|
0d8b2738c5025a35f5144557f8645fe358ae3f0e | aggy07/Leetcode | /1000-1100q/1015.py | 829 | 3.921875 | 4 | '''
Given a positive integer K, you need find the smallest positive integer N such that N is divisible by K, and N only contains the digit 1.
Return the length of N. If there is no such N, return -1.
Example 1:
Input: 1
Output: 1
Explanation: The smallest answer is N = 1, which has length 1.
Example 2:
Input: 2
Output: -1
Explanation: There is no such positive integer N divisible by 2.
Example 3:
Input: 3
Output: 3
Explanation: The smallest answer is N = 111, which has length 3.
'''
class Solution(object):
def smallestRepunitDivByK(self, K):
"""
:type K: int
:rtype: int
"""
length, value = 0, 0
for no_one in range(100000):
value = (10*value + 1)%K
length += 1
if value == 0:
return length
return -1
|
d8709a64545e1b7a7171225cb9ea1fa5bf1693c0 | aggy07/Leetcode | /1000-1100q/1054.py | 1,207 | 3.890625 | 4 | '''
In a warehouse, there is a row of barcodes, where the i-th barcode is barcodes[i].
Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists.
Example 1:
Input: [1,1,1,2,2,2]
Output: [2,1,2,1,2,1]
Example 2:
Input: [1,1,1,1,2,2,3,3]
Output: [1,3,1,3,2,1,2,1]
Note:
1 <= barcodes.length <= 10000
1 <= barcodes[i] <= 10000
'''
class Solution(object):
def rearrangeBarcodes(self, barcodes):
"""
:type barcodes: List[int]
:rtype: List[int]
"""
import heapq
di = collections.Counter(barcodes)
pq = [(-value, key) for key, value in di.items()]
heapq.heapify(pq)
# print pq
result = []
while len(pq) >= 2:
freq1, barcode1 = heapq.heappop(pq)
freq2, barcode2 = heapq.heappop(pq)
result.extend([barcode1, barcode2])
if freq1 + 1:
heapq.heappush(pq, (freq1 + 1, barcode1))
if freq2 + 1:
heapq.heappush(pq, (freq2 + 1, barcode2))
if pq:
result.append(pq[0][1])
return result
|
6d9a6317730a7a5ec42a2ad70a17fec62a525d9e | aggy07/Leetcode | /1000-1100q/1004.py | 1,007 | 4 | 4 | '''
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Note:
1 <= A.length <= 20000
0 <= K <= A.length
A[i] is 0 or 1
'''
class Solution(object):
def longestOnes(self, A, K):
"""
:type A: List[int]
:type K: int
:rtype: int
"""
start_index = 0
for end_index in range(0, len(A)):
K -= 1-A[end_index]
if K < 0:
K += 1-A[start_index]
start_index += 1
return end_index-start_index+1
|
52a4191848017bfeff5304299b2c8f27b559ae0f | Amohammadi2/python-pluginsystem-tutorial | /src/main.py | 708 | 3.65625 | 4 | from jsonDB import DBConnection
import os
class Program:
def main(self):
self.db = DBConnection(f"../JSON/{input('enter your class name: ')}.json")
try:
while True:
self.db.insertData(self.getInput())
except KeyboardInterrupt:
print ("opening json file ...")
os.system(f"{'notepad' if os.name=='nt' else 'nano'} {self.db.db_file}")
def getInput(self):
return {
"first-name": input("enter your first name: "),
"last-name": input("enter your last name: "),
"grade": int(input("which grade are you at? (enter a number) : "))
}
if __name__ == "__main__": Program().main() |
b47cc4edb6b26bc8d86fc960a19c521e7896d19b | IrsalievaN/Homework | /1.py | 697 | 3.796875 | 4 | '''
import random
while True:
command = input(">>> ")
phrases = ["Никто не ценит того, чего слишком много.","Где нет опасности, не может быть и славы.","Сердце можно лечить только сердцем.","Красотой спасётся мир","Каждый день имеет своё чудо."]
if command == "Скажи мудрость":
print(random.choice(phrases))
elif command == "Знать ничего не хочу":
print("Okay(((")
continue
elif command == "Выход":
print("До свидания")
break
else:
print("Неверный ввод")
'''
print(eval("1+1+1+2"))
|
fe6681006dca45b41fd2ce1a4715decda8b4ce76 | IrsalievaN/Homework | /homework5.py | 578 | 4.125 | 4 | from abc import ABC, abstractmethod
from math import pi
class Figure(ABC):
@abstractmethod
def draw (self):
print("Квадрат нарисован")
class Round(Figure):
def draw(self):
print("Круг нарисован")
def __square(a):
return S = a ** 2 * pi
class Square(Figure):
def draw(self):
super().draw()
@staticmethod
def square(a):
return S = a ** 2
a = int(input("Введите а:\n"))
r = Round()
s = Square()
print()
r.draw()
print()
s.draw()
print()
print(s.square(a))
print(r._Round__square())
|
6b886ad93e6e9e5d05a2c5503f4b2cade76cfe49 | swapnadeepmohapatra/mit-dsa | /Stack/stack.py | 379 | 3.96875 | 4 | # Self Implementation
class Stack:
def __init__(self):
self.items = []
def push(self, data):
self.items.append(data)
def pop(self):
if len(self.items) == 0:
print("Stack is Empty")
else:
self.items.pop()
s = Stack()
s.push(5)
s.push(6)
s.push(7)
print(s.items)
s.pop()
print(s.items)
s.pop()
print(s.items)
|
8d95c66ede3e8c525ad625c63383723517437852 | swapnadeepmohapatra/mit-dsa | /ins.py | 302 | 3.96875 | 4 | def sort(arr):
for right in range(1, len(arr)):
left = right - 1
elem = arr[right]
while left >= 0 and arr[left] > elem:
arr[left + 1] = arr[left]
left -= 1
arr[left + 1] = elem
return arr
arr = [1, 2, 6, 3, 7, 5, 9]
print(sort(arr))
|
64f7eb0fbb07236f5420f9005aedcbfefa25a457 | JATIN-RATHI/7am-nit-python-6thDec2018 | /variables.py | 730 | 4.15625 | 4 | #!/usr/bin/python
'''
Comments :
1. Single Comments : '', "", ''' ''', """ """ and #
2. Multiline Comments : ''' ''', and """ """
'''
# Creating Variables in Python
'Rule of Creating Variables in python'
"""
1. A-Z
2. a-z
3. A-Za-z
4. _
5. 0-9
6. Note : We can not create a variable name with numeric Value as a prefix
"""
'''left operand = right operand
left operand : Name of the Variable
right operand : Value of the Variable'''
"Creating variables in Python"
FIRSTNAME = 'Guido'
middlename = "Van"
LASTname = '''Rossum'''
_python_lang = """Python Programming Language"""
"Accessing Variables in Python"
print(FIRSTNAME)
print("")
print(middlename)
print("")
print(LASTname)
print("")
print(_python_lang)
|
356b0255a23c0a845df9c05b512ca7ccc681aa12 | JATIN-RATHI/7am-nit-python-6thDec2018 | /datatypes/list/List_pop.py | 781 | 4.21875 | 4 | #!/usr/bin/python
aCoolList = ["superman", "spiderman", 1947,1987,"Spiderman"]
oneMoreList = [22, 34, 56,34, 34, 78, 98]
print(aCoolList,list(enumerate(aCoolList)))
# deleting values
aCoolList.pop(2)
print("")
print(aCoolList,list(enumerate(aCoolList)))
# Without index using pop method:
aCoolList.pop()
print("")
print(aCoolList,list(enumerate(aCoolList)))
'''
5. list.pop([i]) : list.pop()
Remove the item at the given position in the list, and return it.
If no index is specified, a.pop() removes and returns the last item in the list.
(The square brackets around the i in the method signature denote that the
parameter is optional,
not that you should type square brackets at that position.
You will see this notation frequently in the Python Library Reference.)
'''
|
29d770237ec753148074d79ef96ef25287fde94a | JATIN-RATHI/7am-nit-python-6thDec2018 | /loops/for_decisionMaking.py | 853 | 4.375 | 4 |
"""
for variable_expression operator variable_name suit
statements
for i in technologies:
print(i)
if i == "AI":
print("Welcome to AI World")
for i in range(1,10): #start element and end element-1 : 10-1 = 9
print(i)
# Loop Controls : break and continue
for i in technologies:
print(i)
if i == "Bigdata":
continue
#break
for i in range(6): # start index 0 1 2 3 4 5 range(6) end-1 = 5
print(i)
else:
print("Completed")
"""
# Neasted For Loop:
"""
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the "outer loop"
"""
technologies = ['Cloud','Bigdata','AI','DevOps']
cloud_vendors = ['AWS','Azure','GCP']
for i in technologies: # Outer loop
for var in cloud_vendors: # Inner Loop
print(i,var)
|
e23ca223aef575db942920729a53e52b1df2ed4d | JATIN-RATHI/7am-nit-python-6thDec2018 | /DecisionMaking/ConditionalStatements.py | 516 | 4.21875 | 4 | """
Decision Making
1. if
2. if else
3. elif
4. neasted elif
# Simple if statement
if "expression" :
statements
"""
course_name = "Python"
if course_name:
print("1 - Got a True Expression Value")
print("Course Name : Python")
print(course_name,type(course_name),id(course_name))
print("I am outside of if condition")
var = 100
var1 = 50
if var == var1:
print("Yes, Condition is met")
print("Goodbye!")
if (var == var1):
print("Yes, Condition is met")
print("Goodbye!")
|
07f477c82976a39cd4ac94ac95acc6b5f96c7d7d | JATIN-RATHI/7am-nit-python-6thDec2018 | /Date_Time/UserInput.py | 396 | 3.984375 | 4 | import datetime
currentDate = datetime.datetime.today()
print(currentDate.minute)
print(currentDate)
print(currentDate.month)
print(currentDate.year)
print(currentDate.strftime('%d %b, %Y'))
print(currentDate.strftime('%d %b %y'))
userInput = input('Please enter your birthday (mm/dd/yyyy):')
birthday = datetime.datetime.strptime(userInput, '%m/%d/%Y').date()
print("Your DOB is ",birthday)
|
71fb2e89c852750f33e2512e2f83ab1f9a021b68 | JATIN-RATHI/7am-nit-python-6thDec2018 | /datatypes/basics/built-in-functions.py | 2,190 | 4.375 | 4 | # Creating Variables in Python :
#firstname = 'Guido'
middlename = 'Van'
lastname = "Rossum"
# Accesing Variables in Python :
#print(firstname)
#print("Calling a Variable i.e. FirstName : ", firstname)
#print(firstname,"We have called a Variable call Firstname")
#print("Calling Variable",firstname,"Using Print Function")
# String Special Operators :
'''
1. + : Concatenation
2. * : Repetition
3. []: Slice
4. [:]: Range Slice
5. [::] : Zero Based Indexing
6. % : Format
7. .format()
'''
#names = firstname + lastname
#print(names)
'''
Indexing
Left to Right
0 1 2 3 4 5 nth
Right to Left
-nth -5 -4 -3 -2 -1
'''
# 0 1 2 3 4 Left to Right Indexing
# -5 -4 -3 -2 -1 Right to Left Indexing
#firstname=' G u i d o'
firstname = 'Guido Van Rossum'
print('Left to Right Indexing : ',firstname[0])
print('Right to Left Indexing : ',firstname[-5])
# print('Range Slice[:]',firstname[Start index: end index]) end index -1 :
print('Range Slice[:]',firstname[2:5])
print('Range Slice[:]',firstname[1:]) # endindex-1 = 3 (0123)
# 012121212121212121
numValues = '102030405060708090'
print("Zero Based Indexing",numValues[2::4])
"""
Below are the list of complete set of symbols which can be used along with % :
Format Symbol Conversion
%c character
%s string conversion via str()
prior to formatting
%i signed decimal integer
%d signed decimal integer
%u unsigned decimal integer
%o octal integer
%x hexadecimal integer (lowercase letters)
%X hexadecimal integer (UPPERcase letters)
%e exponential notation (with lowercase 'e')
%E exponential notation (with UPPERcase 'E')
%f floating point real number
%g the shorter of %f and %e
%G the shorter of %f and %E
"""
print("FirstName : %s MiddleName : %s LastName: %s " %(firstname,middlename,lastname))
print("FirstName :",firstname,"MiddleName : ",middlename,"LastName:",lastname)
print("FirstName : {} MiddleName : {} LastName: {} ".format(firstname,middlename,lastname))
# raw sring : r/R r'expression' or R'expression'
print(r'c:\\users\\keshavkummari\\')
print(R'c:\\users\\keshavkummari\\')
|
47d9ba9ec790f0b9fde1a350cf8b240e5b8c886a | JATIN-RATHI/7am-nit-python-6thDec2018 | /OOPS/Encapsulation.py | 1,035 | 4.65625 | 5 | # Encapsulation :
"""
Using OOP in Python, we can restrict access to methods and variables.
This prevent data from direct modification which is called encapsulation.
In Python, we denote private attribute using underscore as prefix i.e single
“ _ “ or double “ __“.
"""
# Example-4: Data Encapsulation in Python
class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
def setMaxPrice(self, price):
self.__maxprice = price
c = Computer()
c.sell()
# change the price
c.__maxprice = 1000
c.sell()
# using setter function
c.setMaxPrice(1000)
c.sell()
"""
In the above program, we defined a class Computer.
We use __init__() method to store the maximum selling price of computer.
We tried to modify the price.
However, we can’t change it because Python treats the __maxprice as private attributes.
To change the value, we used a setter function i.e setMaxPrice() which takes price as parameter.
""" |
9f6536e8d1970c519e84be0e7256f5b415e0cf3e | JATIN-RATHI/7am-nit-python-6thDec2018 | /loops/Password.py | 406 | 4.1875 | 4 |
passWord = ""
while passWord != "redhat":
passWord = input("Please enter the password: ")
if passWord == "redhat":
print("Correct password!")
elif passWord == "admin@123":
print("It was previously used password")
elif passWord == "Redhat@123":
print(f"{passWord} is your recent changed password")
else:
print("Incorrect Password- try again!")
|
36f0a7f05fba28b2feddb9e1ec0195c252dd1a53 | storrellas/pygame_ws_server | /snake.py | 4,783 | 3.671875 | 4 | """
Sencillo ejemplo de serpiente
Sample Python/Pygame Programs
Simpson College Computer Science
http://programarcadegames.com/
http://simpson.edu/computer-science/
"""
import pygame
from flask import Flask, jsonify, request, render_template
from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler
# --- Globales ---
# Colores
NEGRO = (0, 0, 0)
BLANCO = (255, 255, 255)
# Establecemos el largo y alto de cada segmento de la serpiente
largodel_segmento = 15
altodel_segmento = 15
# Margen entre cada segmento
margendel_segmento = 3
#Velocidad inicial
cambio_x = largodel_segmento + margendel_segmento
cambio_y = 0
## FLASK application
# See: https://stackoverflow.com/questions/18409464/how-to-send-a-pygame-image-over-websockets
app = Flask(__name__)
@app.route('/')
def index():
print("Request index")
test= render_template('index.html')
print(test)
return "Returning"
## Pygame application
class Segmento(pygame.sprite.Sprite):
""" Clase que representa un segmento de la serpiente. """
# -- Métodos
# Función constructor
def __init__(self, x, y):
# Llamada al constructor padre
super().__init__()
# Establecemos el alto y largo
self.image = pygame.Surface([largodel_segmento, altodel_segmento])
self.image.fill(BLANCO)
# Establecemos como punto de partida la esquina superior izquierda.
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
def websocket_app(environ, start_response):
print("app")
# if environ["PATH_INFO"] == '/echo':
# ws = environ["wsgi.websocket"]
# message = ws.receive()
# ws.send(message)
ws = environ["wsgi.websocket"]
message = ws.receive()
ws.send(message)
if __name__ == '__main__':
server = pywsgi.WSGIServer(("", 7070), websocket_app, handler_class=WebSocketHandler)
server.serve_forever()
"""
# Inicializamos Pygame
pygame.init()
# Creamos una pantalla de 800x600
pantalla = pygame.display.set_mode([800, 600])
# Creamos un título para la ventana
pygame.display.set_caption('Serpiente')
listade_todoslos_sprites = pygame.sprite.Group()
# Creamos la serpiente inicial.
segementos_dela_serpiente = []
for i in range(15):
x = 250 - (largodel_segmento + margendel_segmento) * i
y = 30
segmento = Segmento(x, y)
segementos_dela_serpiente.append(segmento)
listade_todoslos_sprites.add(segmento)
reloj = pygame.time.Clock()
hecho = False
while not hecho:
for evento in pygame.event.get():
if evento.type == pygame.QUIT:
hecho = True
# Establecemos la velocidad basándonos en la tecla presionada
# Queremos que la velocidad sea la suficiente para mover un segmento
# más el margen.
if evento.type == pygame.KEYDOWN:
if evento.key == pygame.K_LEFT:
cambio_x = (largodel_segmento + margendel_segmento) * -1
cambio_y = 0
if evento.key == pygame.K_RIGHT:
cambio_x = (largodel_segmento + margendel_segmento)
cambio_y = 0
if evento.key == pygame.K_UP:
cambio_x = 0
cambio_y = (altodel_segmento + margendel_segmento) * -1
if evento.key == pygame.K_DOWN:
cambio_x = 0
cambio_y = (altodel_segmento + margendel_segmento)
# Eliminamos el último segmento de la serpiente
# .pop() este comando elimina el último objeto de una lista.
segmento_viejo = segementos_dela_serpiente.pop()
listade_todoslos_sprites.remove(segmento_viejo)
# Determinamos dónde aparecerá el nuevo segmento
x = segementos_dela_serpiente[0].rect.x + cambio_x
y = segementos_dela_serpiente[0].rect.y + cambio_y
segmento = Segmento(x, y)
# Insertamos un nuevo segmento en la lista
segementos_dela_serpiente.insert(0, segmento)
listade_todoslos_sprites.add(segmento)
# -- Dibujamos todo
# Limpiamos la pantalla
pantalla.fill(NEGRO)
listade_todoslos_sprites.draw(pantalla)
# Actualizamos la pantalla
pygame.display.flip()
# Pausa
reloj.tick(5)
pygame.quit()
"""
# FLASK SERVER |
27663a08442eadf6741dec65943edb03782f4963 | CS-Developers/Python | /Tip-Calculator/tipCalculator.py | 665 | 4.09375 | 4 | # Basic Printing Function
print("Welcome to the tip calculator.")
totalBill = input("What was the total bill? $")
totalPeople = input("How many people to split the bill? ")
percentChoice = input(
"What percentage tip would you like to give? 10, 12, or 15? ")
total = 0
def allInAll():
global total
total += float(totalBill)
total /= float(totalPeople)
if percentChoice == "12":
total = float(totalBill) * 0.12
allInAll()
elif percentChoice == "10":
total = float(totalBill) * 0.10
allInAll()
elif percentChoice == "15":
total = float(totalBill) * 0.15
allInAll()
print("Each person should pay: ${:.2f}".format(total))
|
216bdcda887541ba32eb1e8b656b8bb00c7f3a5c | Saianisha2001/pythonletsupgrade | /day2/day2 assignment.py | 1,123 | 3.8125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
List = [1,2,3,4]
List.append(5)
print(List)
List.insert(2,6)
print(List)
print(sum(List))
print(len(List))
print(List.pop())
# In[7]:
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print(squares.get(3))
print(squares.items())
element=squares.pop(4)
print('deleted element=',element)
print(squares)
squares.update(name=36,age=49)
print(squares)
squares.setdefault('new')
print(squares)
# In[8]:
newset={1,2,6}
newset.add(3)
print(newset)
newset.update([2, 3, 4])
print(newset)
newset.discard(4)
print(newset)
newset.remove(6)
print(newset)
otherset={2,3,4,7,9}
print(newset.union(otherset))
print(newset.clear())
# In[11]:
tup1 = (1, 2, 3, 4, 5, 6, 7 )
print ("tup1[1:5]: ", tup1[1:5])
tup2 = (12, 34.56)
tup3=tup1+tup2
print('tup3=',tup3)
print('length=',len(tup3))
print (cmp(tup1, tup2))
print('minimum val=',min(tup1))
print('maximum val=',max(tup1))
#
# In[14]:
s1='artificial'
s2='INTELLIGENCE'
print(s1.count('i'))
print(s1.islower())
print(s2.lower())
print(s1.endswith("al"))
s3='-->'
print(s3.join(s1))
print(s1.swapcase())
# In[ ]:
|
d0fc6d4c351f801b5f15ee2d9824c90f0cdd6206 | guifurtado/cursopython | /Fluxo/0-if.py | 258 | 4.03125 | 4 | #A = int(input())
txt = input()
A = float (txt)
if A == 20:
print("= 20")
if A > 5 and A < 15:
print ("5 < A < 15")
if A > 20:
print("A > 20")
else:
print("A < 20")
if A == 10:
print("A = 10")
elif A == 20:
print("A = 20")
print( 5 < A < 15)
|
e1c9995fbac0c7c7e792959b8351894e77626a1b | Nesterenko-Andrii/pr2 | /pr2_1.py | 169 | 4 | 4 | print('enter the number')
num1 = float(input())
print('enter another number')
num2 = float(input())
if num1 > num2:
print('True')
else:
print('False') |
917e4eb5d5a629a581b6f952275d69ba61016ee6 | idubey-code/Data-Structures-and-Algorithms | /SelectionSort.py | 272 | 3.828125 | 4 | def selectionSort(array):
for i in range(0,len(array)):
minimum=array[i]
for j in range(i+1,len(array)):
if array[j] < minimum:
minimum=array[j]
array.remove(minimum)
array.insert(i,minimum)
return array
|
436120f034d541d70e2373de9c3a0c968b47f7ad | idubey-code/Data-Structures-and-Algorithms | /InsertionSort.py | 489 | 4.125 | 4 | def insertionSort(array):
for i in range(0,len(array)):
if array[i] < array[0]:
temp=array[i]
array.remove(array[i])
array.insert(0,temp)
else:
if array[i] < array[i-1]:
for j in range(1,i):
if array[i]>=array[j-1] and array[i]<array[j]:
temp=array[i]
array.remove(array[i])
array.insert(j,temp)
return array
|
ef7beb682047faded1e6e4c8e323387c7bf68ff1 | BonIlcer/Daily-Coding-Problem | /m07y20/day19.py | 1,096 | 3.875 | 4 | # Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
# For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
# Bonus: Can you do this in one pass?
def subList(sourceList, num):
subList = []
for elem in sourceList:
subList.append(num - elem)
return subList
def checkDuplicates(listOfElems):
setOfElems = set()
for elem in listOfElems:
if elem in setOfElems:
return True
else:
setOfElems.add(elem)
return False
def bonus(sourceList, num):
difList = []
for elem in sourceList:
print(difList)
for dif in difList:
print("dif: ", dif, " elem: ", elem)
if dif == elem:
return True
difList.append(num - elem)
return False
sourceList = [15, 10, 7, 3]
number = 17
subList = subList(sourceList, number)
print("sourceList: ", sourceList)
print("number: ", number)
print("subList: ", subList)
# print("expandedList: ", sourceList + subList)
# print(checkDuplicates(sourceList + subList))
print(bonus(sourceList, number)) |
35a424ef1171e034d6b0092e9fceb9802c3baf73 | diogofernandesc/ctci-answers | /linked_lists/remove_duplicate.py | 691 | 3.671875 | 4 | def remove_duplicates(node):
seen = set()
previous_node = None
while (node is not None):
if node.data in seen:
previous_node.next = node.next
else:
seen.add(node.data)
previous_node = node
node = node.next
# No buffer solution
def remove_duplicates(head):
current_node = head
while (current_node is not None):
runner_node = current_node.next
while(runner_node is not None):
if (current_node.data == runner_node.data):
runner_node.next = runner_node.next.next
else:
runner_node = runner_node.next
current_node = current_node.next |
190b073ac866811194433c3dc043b9320b949ec7 | HerrDerNasn/AdventOfCode | /TwentyNineteen/Day10/monitoring-station-part-two.py | 1,702 | 3.53125 | 4 | import math
def calc_angle(orig_coord, target_coord):
return math.atan2(target_coord[1] - orig_coord[1], target_coord[0] - orig_coord[0])
def sort_by_dist(val):
return math.sqrt(val[0]*val[0]+val[1]*val[1])
def sort_angles(val):
return val if val >= calc_angle((0, 0), (0, -1)) else val + 2 * math.pi
with open('input.txt', 'r') as file:
asteroids = file.readlines()
angle_mapping = {}
station = (20, 19)
# print("(1, 0) || 90", calc_angle((0, 0), (1, 0)))
# print("(0, 1) || 180", calc_angle((0, 0), (0, 1)))
# print("(-1, 0) || 270", calc_angle((0, 0), (-1, 0)))
# print("(0, -1) || 0", calc_angle((0, 0), (0, -1)))
for x in range(0, 26):
for y in range(0, 26):
if not station == (x, y):
angle = calc_angle(station, (x, y))
if asteroids[y][x] == "#":
if angle not in angle_mapping.keys():
angle_mapping[angle] = []
angle_mapping[angle].append((x-station[0], y-station[1]))
angle_mapping[angle].sort(key=sort_by_dist)
angles = list(angle_mapping.keys())
angles.sort(key=sort_angles)
curr_ast = 0
curr_angle_ind = 0
while any(len(targets) > 0 for targets in angle_mapping.values()):
targets = angle_mapping[angles[curr_angle_ind]]
if len(targets) > 0:
curr_ast += 1
print(str(curr_ast) + ": Deleting " + str((station[0]+targets[0][0], station[1]+targets[0][1])))
targets = targets[1:]
angle_mapping[angles[curr_angle_ind]] = targets
curr_angle_ind = curr_angle_ind + 1 if curr_angle_ind + 1 in range(0, len(angles)) else 0 |
a5bd02624e4a4a500dae264b4ff7ebedf2e040c0 | ishine/tacotron_gmm | /tacotron/utils/num2cn.py | 3,985 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def num2cn(number, traditional=False):
'''数字转化为中文
参数:
number: 数字
traditional: 是否使用繁体
'''
chinese_num = {
'Simplified': ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'],
'Traditional': ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
}
chinese_unit = {
'Simplified': ['个', '十', '百', '千'],
'Traditional': ['个', '拾', '佰', '仟']
}
extra_unit = ['', '万', '亿']
if traditional:
chinese_num = chinese_num['Traditional']
chinese_unit = chinese_unit['Traditional']
else:
chinese_num = chinese_num['Simplified']
chinese_unit = chinese_unit['Simplified']
num_cn = []
# 数字转换成字符列表
num_list = list(str(number))
# 反转列表,个位在前
num_list.reverse()
# 数字替换成汉字
for num in num_list:
num_list[num_list.index(num)] = chinese_num[int(num)]
# 每四位进行拆分,第二个四位加“万”,第三个四位加“亿”
for loop in range(len(num_list)//4+1):
sub_num = num_list[(loop * 4):((loop + 1) * 4)]
if not sub_num:
continue
# 是否增加额外单位“万”、“亿”
if loop > 0 and 4 == len(sub_num) and chinese_num[0] == sub_num[0] == sub_num[1] == sub_num[2] == sub_num[3]:
use_unit = False
else:
use_unit = True
# 合并数字和单位,单位在每个数字之后
# from itertools import chain
# sub_num = list(chain.from_iterable(zip(chinese_unit, sub_num)))
sub_num = [j for i in zip(chinese_unit, sub_num) for j in i]
# 删除第一个单位 '个'
del sub_num[0]
# “万”、“亿”中如果第一位为0则需加“零”: 101000,十万零一千
use_zero = True if loop > 0 and chinese_num[0] == sub_num[0] else False
if len(sub_num) >= 7 and chinese_num[0] == sub_num[6]:
del sub_num[5] # 零千 -> 零
if len(sub_num) >= 5 and chinese_num[0] == sub_num[4]:
del sub_num[3] # 零百 -> 零
if len(sub_num) >= 3 and chinese_num[0] == sub_num[2]:
del sub_num[1] # 零十 -> 零
if len(sub_num) == 3 and chinese_num[1] == sub_num[2]:
del sub_num[2] # 一十开头的数 -> 十
# 删除末位的零
while len(num_list) > 1 and len(sub_num) and chinese_num[0] == sub_num[0]:
del sub_num[0]
# 增加额外的“零”
if use_zero and len(sub_num) > 0:
num_cn.append(chinese_num[0])
# 增加额外单位“万”、“亿”
if use_unit:
num_cn.append(extra_unit[loop])
num_cn += sub_num
# 删除连续重复数据:零,只有零会重复
num_cn = [j for i, j in enumerate(num_cn) if i == 0 or j != num_cn[i-1]]
# 删除末位的零,最后一位为 extra_unit 的 ''
if len(num_list) > 1 and len(num_cn) > 1 and chinese_num[0] == num_cn[1]:
del num_cn[1]
# 反转并连接成字符串
num_cn.reverse()
num_cn = ''.join(num_cn)
return(num_cn)
if '__main__' == __name__:
for num in [0, 5, 100020034005, 10020000, 123456789, 1000000000, 10, 110000, 10000000000, 100000000000]:
print('%d: %s, %s' % (num, num2cn(num, False), num2cn(num, True)))
"""
from itertools import permutations
import copy
test = ['1', '1', '1', '1', '1', '1', '1', '1']
num_list = []
for vid in range(len(test)):
for nid in permutations(range(len(test)), vid):
tmp = copy.copy(test)
for index in nid:
tmp[index] = '0'
num_list.append(int(''.join(tmp)))
num_list = list(set(num_list))
for number in num_list:
print('%d: %s' % (number, num2cn(number, False)))
"""
|
e78ce73faa96ebdc50f1071613253e221a024f33 | rahmanifebrihana/Rahmani-Febrihana_I0320082_Aditya-Mahendra-_Tugas7 | /I0320082_Soal1_Tugas7.py | 538 | 4 | 4 | str = "Program Menghitung Jumlah Pesanan Makanan"
s = str.center(61,'*')
print(s)
nama_pemesan = input("Nama pemesan :")
print("Selamat datang", nama_pemesan)
print("\nMenu makanan : NASI GORENG , BAKSO, SATE")
str = input("Masukkan menu makanan yang dipesan dengan menuliskan menu sebanyak jumlah yang dipesan :")
pesanan =str.upper()
print("Pesanan: ", pesanan)
str = pesanan
a = str.count('NASI GORENG')
b = str.count('BAKSO')
c = str.count('SATE')
print("JUMLAH BAKSO: ", a)
print("JUMLAH MIE AYAM: ", b)
print("JUMLAH SOTO: ", c)
|
92221bfa79730508918f7774fe24cffd71627150 | rhutuja3010/json | /meraki Q1.py | 494 | 3.734375 | 4 | # Q.1 Json data ko python object main convert karne ka program likho?. Example: Input :- Output :
import json
x='{"a":"sinu","b":"sffhj","c":"frjkjs","d":"wqiugd"}'
# a=json.loads(x)
# print(type(a))
# print(a)
a=open("question6.json","w")
json.loads(x,a,indent=4)
a.close()
# with open("question1.json","r") as f:
# y=json.load(f)
# print(y)
# # x='{"a":"sinu","b":"sffhj","c":"frjkjs","d":"wqiugd"}'
# y=json.loads(x)
# # print(y)
# for i in y:
# print(i,y[i]) |
9441cb892e44c9edd6371914b227a48f00f5d169 | hospogh/exam | /source_code.py | 1,956 | 4.21875 | 4 | #An alternade is a word in which its letters, taken alternatively in a strict sequence, and used in the same order as the original word, make up at least two other words. All letters must be used, but the smaller words are not necessarily of the same length. For example, a word with seven letters where every second letter is used will produce a four-letter word and a three-letter word. Here are two examples:
# "board": makes "bad" and "or".
# "waists": makes "wit" and "ass".
#
#
#Using the word list at unixdict.txt, write a program that goes through each word in the list and tries to make two smaller words using every second letter. The smaller words must also be members of the list. Print the words to the screen in the above fashion.
#max_leng_of_word = 14
with open("unixdict.txt", "r") as f:
words = f.readlines()
f.closed
words = [s.strip("\n") for s in words]
#creating a dict with a member after each word which contains an empty list
potential_words = {str(word): ["evennumberword", "oddnumberword"] for word in words}
#adding to the dict member of each word it's even number and odd number chars made words, in total: 2 words as
for word in words:
even_number_word = ""
odd_number_word = ""
try:
for i in range(14):
if i % 2 == 0:
even_number_word = "".join([even_number_word, word[i]])
elif not i % 2 == 0:
odd_number_word = "".join([odd_number_word, word[i]])
except IndexError:
potential_words[str(word)][0] = even_number_word
potential_words[str(word)][0] = odd_number_word
print(word, "evennumber is", even_number_word, "and oddnumber is", odd_number_word)
if even_number_word in set(words) and odd_number_word in set(words):
print(word, "is an alternade")
else:
print(word, "is not an alternade")
#didn't take out dict creation part cause it might be used to write this info in another file
|
0d59e175ec5a00df9c3349909782dce3720c63ee | andrehoejmark/Classify-paying-customers | /data_cleaning_functions.py | 5,107 | 3.609375 | 4 | # -*- coding: utf-8 -*-
import pandas as pd
import sklearn
from sklearn import preprocessing
# for data visualizations
import matplotlib.pyplot as plt
import seaborn as sns
categorical_labels = ["Month", "Weekend", "Revenue", "VisitorType"]
def get_data_cleaned():
data_frame = read_data()
data_size = len(data_frame)
encode_label(data_frame)
data_frame_scaled = standardize(data_frame)
remove_outliers(data_frame_scaled)
draw_correlation(data_frame_scaled)
data_size_2 = len(data_frame_scaled)
size_difference = data_size - data_size_2
return data_frame_scaled
def read_data(file_name='online_shoppers_intention.csv'):
data_frame = pd.read_csv(file_name)
# data.isnull().sum().values
# remove any nulls
data_frame = data_frame.dropna()
# Dropping the negative Durations
data_frame = data_frame.drop(data_frame[data_frame['Administrative_Duration'] < 0].index)
data_frame = data_frame.drop(data_frame[data_frame['Informational_Duration'] < 0].index)
data_frame = data_frame.drop(data_frame[data_frame['ProductRelated_Duration'] < 0].index)
# Checking , no negative values
data_frame.describe()
return data_frame
def encode_label(data_frame):
label_encode = sklearn.preprocessing.LabelEncoder()
for label in categorical_labels:
data_frame[label] = label_encode.fit_transform(data_frame[label])
data_frame[categorical_labels].head(11)
def standardize(data_frame):
# Standardization Standardization involves centering the variable at zero, and standardizing the variance to 1.
# The procedure involves subtracting the mean of each observation and then dividing by the standard deviation: z
# = (x - x_mean) / std
# the scaler - for standardization
# standardisation: with the StandardScaler from sklearn
# set up the scaler
scaler = sklearn.preprocessing.StandardScaler()
# fit the scaler to the train set, it will learn the parameters
scaler.fit(data_frame)
_data_scaled = scaler.transform(data_frame)
data_scaled = pd.DataFrame(_data_scaled, columns=data_frame.columns)
# data_scaled[categorical_labels + ["Administrative_Duration"]].head(11)
# restore the categorical values because we do not standardize these
for label in categorical_labels:
data_scaled[label] = data_frame[label].to_numpy()
#data_scaled[categorical_labels + ["Administrative_Duration"]].head(11)
# test if is a bug in the library
var = data_scaled.isna().sum().values
return data_scaled
def compare_scaling(data_frame, data_frame_scaled):
# let's compare the variable distributions before and after scaling
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(22, 5))
ax1.set_xlim([-120, 600])
ax1.set_ylim([0, 0.017])
ax2.set_xlim([-1.2, 8])
ax2.set_ylim([0, 2.5])
# before scaling
ax1.set_title('Before Scaling')
sns.kdeplot(data_frame['Administrative_Duration'], ax=ax1)
sns.kdeplot(data_frame['Informational_Duration'], ax=ax1)
sns.kdeplot(data_frame['ProductRelated_Duration'], ax=ax1)
# after scaling
ax2.set_title('After Standard Scaling')
sns.kdeplot(data_frame_scaled['Administrative_Duration'], ax=ax2)
sns.kdeplot(data_frame_scaled['Informational_Duration'], ax=ax2)
sns.kdeplot(data_frame_scaled['ProductRelated_Duration'], ax=ax2)
def draw_boxplots(data_frame_scaled):
plt.rcParams['figure.figsize'] = (40, 35)
plt.subplot(3, 3, 1)
sns.set_theme(style="whitegrid")
# sns.boxplot(data = data_scaled,palette="Set3", linewidth=2.5)
sns.boxenplot(data=data_frame_scaled, orient="h", palette="Set3")
# sns.stripplot(data=data,orient="h",size=4, color=".26")
plt.title('box plots types', fontsize=10)
# ------------------------------------------------------------------------------
# accept a dataframe, remove outliers, return cleaned data in a new dataframe
# see http://www.itl.nist.gov/div898/handbook/prc/section1/prc16.htm
# ------------------------------------------------------------------------------
def remove_outlier(df_in, col_name):
q1 = df_in[col_name].quantile(0.25)
q3 = df_in[col_name].quantile(0.75)
iqr = q3 - q1 # Interquartile range
fence_low = q1 - 1.5 * iqr
fence_high = q3 + 1.5 * iqr
df_out = df_in.loc[(df_in[col_name] > fence_low) & (df_in[col_name] < fence_high)]
return df_out
def remove_outliers(data_frame_scaled):
for col in data_frame_scaled.columns:
Q1 = data_frame_scaled[col].quantile(0.25)
Q3 = data_frame_scaled[col].quantile(0.75)
IQR = Q3 - Q1 # IQR is interquartile range.
#print(IQR)
filter = (data_frame_scaled[col] > Q1 - 1.5 * IQR) & (data_frame_scaled[col] < Q3 + 1.5 * IQR)
data_frame_scaled = data_frame_scaled.loc[filter]
def draw_correlation(data_frame_scaled):
plt.figure(figsize=(20, 15))
ax = sns.heatmap(data_frame_scaled.corr(), cmap='Blues', linecolor='Black', linewidths=.3, annot=True, fmt=".3")
ax.set_title('The Correlation Heatmap')
bottom, top = ax.get_ylim()
|
24568901f1ad26e90a52c2fc1c74449d17c0b9bc | kms121999/homework12_13 | /12C/ks_assignment_12C.py | 709 | 3.84375 | 4 |
def main():
myFunc(5, True)
def myFunc(myInt, increasing):
if increasing:
for n in range(1, myInt + 1):
print("*" * n)
myFunc(myInt, False)
else:
for n in range(myInt - 1, 0, -1):
print("*" * n)
'''
if increasing:
if myInt > 1:
myFunc(myInt - 1, True)
print("*" * myInt)
if not increasing:
print("*" * (myInt - 1))
if myInt > 1:
myFunc(myInt - 1, False)
def func2(n, y):
if y:
if n > 1:
func2(n-1, True)
print("*" * n)
if not y:
print("*" * (n-1))
if n > 2:
func2(n-1, False)
'''
|
8ed6ce79985a8de478c66c068e96e9637d0124e8 | shivam5750/DSA-in-py-js | /DSA-python/4.Stacks/stackswitharray.py | 508 | 3.53125 | 4 | class Stacks:
def __init__(self):
self.array = []
def __str__(self):
return str(self.__dict__)
def peek(self):
return self.array[len(self.array)-1];
def push(self,value):
self.array.append(value)
return self.array
def pop(self):
self.array.pop()
return self.array
mystacks = Stacks()
mystacks.push('google')
mystacks.push('udemy')
mystacks.push('discord')
print(mystacks.push('youtube'))
mystacks.pop()
print(mystacks.pop())
# //Discord
# //Udemy
# //google |
c386b02127f2cde6e4f5a7c97b946b0a48f2284b | Awerito/data-structures | /sequences/feigenbaum.py | 493 | 3.578125 | 4 | import matplotlib.pyplot as plt
import numpy as np
from random import random as rnd
logistic = lambda x, r: r*x*(1 - x)
def conv(x0, r, niter):
x = x0
for i in range(niter):
x = logistic(x, r)
return x
if __name__=="__main__":
iterations = 100
r_range = np.linspace(2.9, 4, 10**6)
x = []
for r in r_range:
print(int((r - 2.9)/4*100), "%")
x.append(conv(rnd(), r, iterations))
plt.plot(r_range, x, ls='', marker=',')
plt.show()
|
ad9508df76aa677a1a83c411022c98de253861f2 | Awerito/data-structures | /probability/angle.py | 582 | 3.640625 | 4 | import random, math
def distance(point1, point2):
""" Return the distances between point1 and point2 """
return math.sqrt((point1[0]-point2[0])**2 + (point1[1]-point2[1])**2)
# Estimate of the probability of P(x>pi/2)
obtuse = 0
total = 100000
points = [[0, 0],[1, 0]]
for i in range(total + 1):
a, b = 0, 0
randpoint = [random.random(), random.random()]
a, b = distance(points[0], randpoint), distance(points[1], randpoint)
angle = math.acos((a**2 + b**2 - 1) / (2*a*b))
if angle > math.pi/2:
obtuse += 1
print("P(x>pi/2) = ", obtuse / total)
|
0700ad8689cf66bd15fb59efd286cb3266ea8d35 | Awerito/data-structures | /sequences/primes.py | 392 | 3.921875 | 4 | def prime(n):
"""Return True if n is primes, False otherwise"""
if n == 2:
return True
if n <= 1 or n % 2 == 0:
return False
maxdiv = int(n ** (0.5)) + 1
for i in range(3, maxdiv, 2):
if n % i == 0:
return False
return True
if __name__=="__main__":
total = 100
for i in range(1, total + 1):
print(i, ":", prime(i))
|
4ddb35db33cb67aa252449224265e0d0472a70fa | TiesHogenboom/PythonAchievements | /PYTB1L3SchoolTool/tool.py | 409 | 3.953125 | 4 | Weekdag = "Woensdag"
dag1 = "Je moet vandaag naar school toe. " + "Mis je bus niet.."
dag2 = "Online les! " + "probeer wakker te blijven.."
dag3 = "Een vrije dag!"
if Weekdag == "Maandag":
print(dag1)
elif Weekdag == "Dinsdag":
print(dag2)
elif Weekdag == "Woensdag":
print(dag1)
elif Weekdag == "Donderdag":
print(dag2)
elif Weekdag == "Vrijdag":
print(dag2)
else:
print(dag3)
|
2986fc6e6a795c6fcb19424cebd0a611e883ced5 | TiesHogenboom/PythonAchievements | /PYTB1L5ShuffleAndReturn/shuff.py | 271 | 3.75 | 4 | import random
def original(word):
randomised = ''.join(random.sample(word, len(word)))
return original
print(original(input("Voer je eerste woord in: ")))
print(original(input("Voer je tweede woord in: ")))
print(original(input("Voer je derde woord in: "))) |
3be4ac78c65418caaebfd653f0ce58575ca2c7de | gokcelb/xox | /tictactoe.py | 2,331 | 3.75 | 4 | X = 'x'
O = 'o'
EMPTY = ' '
class NotEmptyCellException(Exception):
pass
board = [[EMPTY for _ in range(3)] for _ in range(3)]
def is_full(board):
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] == EMPTY:
return False
return True
def place_input(arr, position, turn):
i, j = map(int, position.split())
if arr[i][j] != EMPTY:
raise NotEmptyCellException
arr[i][j] = turn
def next_turn(turn):
if turn == X:
return O
return X
def check_horizontal_win(arr, turn):
for i in range(len(arr)):
result = 0
for j in range(len(arr)):
if arr[i][j] == turn:
result += 1
if result == len(arr):
return True
return False
def check_vertical_win(arr, turn):
for j in range(len(arr)):
result = 0
for i in range(len(arr)):
if arr[i][j] == turn:
result += 1
if result == len(arr):
return True
return False
def check_left_diagonal_win(arr, turn):
result = 0
for i in range(len(arr)):
if arr[i][i] == turn:
result += 1
return result == len(arr)
def check_right_diagonal_win(arr, turn):
result = 0
for i in range(len(arr)):
j = len(arr)-i-1
if arr[i][j] == turn:
result += 1
return result == len(arr)
def check_win(arr, turn):
return check_horizontal_win(arr, turn) or check_vertical_win(
arr, turn) or check_left_diagonal_win(arr, turn) or check_right_diagonal_win(arr, turn)
def print_board(arr):
for i in range(len(arr)):
for j in range(len(arr)-1):
print(arr[i][j], end=" | ")
print(arr[i][len(arr)-1], end="")
if i != (len(arr)-1):
print("\n---------")
print()
print("sample input: 0 0")
print_board(board)
turn = X
while not is_full(board):
position = input()
try:
place_input(board, position, turn)
print_board(board)
if check_win(board, turn):
print("%s wins" % turn)
break
turn = next_turn(turn)
except NotEmptyCellException as e:
print("position full")
print_board(board)
except:
print("wrong input")
print_board(board) |
0138f9431c2c80332feeacd67c1c015d1abe9245 | ishandutta2007/corporateZ | /model/post.py | 7,721 | 3.859375 | 4 | #!/usr/bin/python3
from __future__ import annotations
from typing import List, Dict
from csv import reader as csvReader
from functools import reduce
'''
Holds an instance of a certain PostOffice of a certain category
Possible categories : {'H.O', 'S.O', 'B.O', 'B.O directly a/w Head Office'}
Now there's a hierarchy that exists among these different kinds
of PostOffice, which is as follows
A certain general B.O reports to a certain S.O
A certain S.O reports to a certain H.O
A special B.O reports directly to a H.O
So for a PostOffice of `H.O` type, we store
references to all `S.O`(s), which are supposed to be
reporting to `H.O` & all `special B.O`(s), which directly
reports to this `H.O`, in a Linked List ( in its children property )
'''
class PostOffice(object):
def __init__(self, officeName: str, pincode: str, officeType: str, deliveryStatus: str, divisionName: str, regionName: str, circleName: str, taluk: str, districtName: str, stateName: str, children: List[PostOffice]):
self.officeName = officeName
self.pincode = pincode
self.officeType = officeType
self.deliveryStatus = deliveryStatus
self.divisionName = divisionName
self.regionName = regionName
self.circleName = circleName
self.taluk = taluk
self.districtName = districtName
self.stateName = stateName
self.children = children
'''
A string representation of a certain PostOffice object
'''
def __str__(self):
super().__str__()
return '{} -- {} -- {} -- {}'.format(self.officeName, self.pincode, self.officeType, self.stateName)
'''
Following one holds an List of all `H.O`(s)
present in India
Well that doesn't really let us find other kind
of P.O.(s) i.e. S.O, B.O or special B.O ?
So we keep a reference of all those `S.O`(s)
which are supposed to be reporting to this `H.O`
& also all those `special B.O`(s), which directly reports
to this `H.O`
And in a PostOffice object for a certain `S.O`,
we keep reference to all those `B.O`(s),
which are supposed to be reporting to this `S.O`
In a PostOffice object of `B.O` type, we don't keep any
reference to any other object(s), because no other
PostOffice is reporting to it
That's how we have a Graph ( well I'll try optimizing it ) of all PostOffices
'''
class PostOfficeGraph(object):
def __init__(self, headPOs: List[PostOffice]):
self.headPostOffices = headPOs
'''
Finds a postoffice by its pincode
If found returns an instance of PostOffice else returns None
Searches all S.O.s under all H.O.s iteratively,
as soon as a result is found, search is aborted
'''
def findPostOfficeUsingPin(self, pincode: str) -> PostOffice:
def __searchHandler__(searchHere):
return reduce(lambda acc, cur: cur if not acc and cur.pincode ==
pincode else acc, searchHere.children, None)
found = None
for i in self.headPostOffices:
found = __searchHandler__(i)
if found:
break
return found
@staticmethod
def importFromCSV(targetPath: str) -> PostOfficeGraph:
'''
We just update a list of records, which we've
for a certain `PostOffice category`, with second
argument passed to this closure
Returns a Dict[str, List[List[str]]]
'''
def __updateRecordHolderDict__(holder: Dict[str, List[List[str]]], record: List[str]) -> Dict[str, List[List[str]]]:
holder.update(
{record[2]: [record] + holder.get(record[2], [])})
return holder
'''
Given an instance of PostOffice, holding
details about a certain `H.O`,
we try to find out a PostOffice object
which is a `S.O` & of given name ( passed as second argument )
'''
def __findSO__(currentHO: PostOffice, SOName: str) -> PostOffice:
if not SOName:
return currentHO
pointer = None
for i in currentHO.children:
if i.officeName == SOName:
pointer = i
break
return pointer
'''
Given the whole PostOfficeGraph, which is still under construction,
we're asked to find out an instance of PostOffice, which is a `H.O`,
if & only if `SOName` argument is `None`
But there may be a situation when we've to find out a `S.O`
using `SOName` argument, when we'll simply call closure which is written just
above this one, with requested `SOName` & found `H.O` ( PostOffice object )
'''
def __findHO__(graph: PostOfficeGraph, HOName: str, SOName: str = None) -> PostOffice:
pointer = None
for i in graph.headPostOffices:
if i.officeName == HOName:
pointer = __findSO__(i, SOName)
break
return pointer
'''
We first find out `H.O` for this `S.O`,
and a newly created instance of PostOffice ( of type `S.O` )
and append this instance to children list of `H.O`
'''
def __linkSOWithHO__(graph: PostOfficeGraph, currentSO: List[str]) -> PostOfficeGraph:
__findHO__(graph, currentSO[12]).children.append(
PostOffice(*currentSO[:10], []))
return graph
'''
First finding out target `S.O`, then newly created instance of PostOffice ( of type `B.O` )
is linked up with this `S.O`
'''
def __linkBOWithSO__(graph: PostOfficeGraph, currentBO: List[str]) -> PostOfficeGraph:
__findHO__(graph, currentBO[12], SOName=currentBO[11]).children.append(
PostOffice(*currentBO[:10], None)
)
return graph
'''
Finds out target `H.O`, where this `special B.O` reports
& they're linked up
'''
def __linkSpecialBOWithHO__(graph: PostOfficeGraph, currentSpecialBO: List[str]) -> PostOfficeGraph:
__findHO__(graph, currentSpecialBO[12]).children.append(
PostOffice(*currentSpecialBO[:10], None)
)
return graph
graph = None
try:
poList = []
with open(targetPath, mode='r', encoding='ISO-8859-1') as fd:
poList = csvReader(fd.readlines()[1:])
holder = reduce(lambda acc, cur: __updateRecordHolderDict__(
acc, cur), poList, {})
graph = reduce(lambda acc, cur:
__linkSpecialBOWithHO__(acc, cur),
holder['B.O directly a/w Head Office'],
reduce(lambda acc, cur:
__linkBOWithSO__(
acc, cur),
holder['B.O'],
reduce(lambda acc, cur:
__linkSOWithHO__(
acc, cur),
holder['S.O'],
PostOfficeGraph([PostOffice(*i[:10], [])
for i in holder['H.O']]))))
except Exception:
graph = None
finally:
return graph
if __name__ == '__main__':
print('[!]This module is expected to be used as a backend handler')
exit(0)
|
5a41308a38717b1b1add0dc4ad40116ca4ca8c07 | spriteirene/BC-homework | /BC Homework 4 Heros.py | 6,800 | 3.5 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
from collections import Counter
# In[2]:
heros = pd.read_csv("/Users/wuyanxu/Desktop/CWCL201901DATA4/04-Pandas/Homework/Instructions/HeroesOfPymoli/Resources/purchase_data.csv")
# In[3]:
heros.head()
# In[4]:
#Total number of players
counts = heros["SN"].unique()
print(len(counts))
# In[5]:
#Number of unqiue purchase item is 179
unique_item = heros["Item Name"].unique()
print(len(unique_item))
#Average purchase price
price = heros["Price"].describe()
print(price["mean"])
# Total number of purchase
print(price["count"])
#Total Revene
revene = heros["Price"].sum()
print(revene)
#dataframe
unique = pd.DataFrame({"Number of unique item": ["179"],
"Average purchase price": ["3.05"],
"Total number of purchase": ["780"],
"Total Revene": ["2379.77"]
}
)
print(unique)
# In[6]:
#Percentage and Count of Male Players & Percentage and Count of Female Players & Percentage and Count of Other / Non-Disclosed
hero_unique = heros.drop_duplicates(subset="SN", keep='first', inplace=False)
hero_unique
tc = hero_unique["Gender"].value_counts()
print(tc)
percent_male = 484/576
percent_female = 81/576
percent_other = 11/576
print(percent_male)
print(percent_female)
print(percent_other)
#dataframe
malefemale = pd.DataFrame({"Gender": ["Male", "Female", "Other"],
"Total Count": ["484", "81", "11"],
"Percentage": ["84%", "14%", "1.9%"]
}
)
print(malefemale)
# In[7]:
#Purchasing Analysis(Gender)
hero_price = heros[["Gender", "Price"]]
male_price = heros.loc[heros["Gender"] == "Male", :]
male_total_purchase_value = male_price["Price"].sum()
male_total_purchase_count = male_price["Price"].count()
male_total_purchase_average = male_price["Price"].mean()
ave_total_purchase_per_male = male_total_purchase_value/484
print(male_total_purchase_value)
print(male_total_purchase_count)
print(male_total_purchase_average)
print(ave_total_purchase_per_male)
female_price = heros.loc[heros["Gender"] == "Female", :]
female_total_purchase_value = female_price["Price"].sum()
female_total_purchase_count = female_price["Price"].count()
female_total_purchase_average = female_price["Price"].mean()
ave_total_purchase_per_female = female_total_purchase_value/81
print(female_total_purchase_value)
print(female_total_purchase_count)
print(female_total_purchase_average)
print(ave_total_purchase_per_female)
other_price = heros.loc[heros["Gender"] == "Other / Non-Disclosed", :]
other_total_purchase_value = other_price["Price"].sum()
other_total_purchase_count = other_price["Price"].count()
other_total_purchase_average = other_price["Price"].mean()
ave_total_purchase_per_other = other_total_purchase_value/15
print(other_total_purchase_value)
print(other_total_purchase_count)
print(other_total_purchase_average)
print(ave_total_purchase_per_other)
#dataframe
pag = pd.DataFrame({"Gender": ["Male", "Female", "Other"],
"Purchase Value": ["1967.64", "361.94", "50.19"],
"Purchase Count": ["652", "113", "15"],
"Average": ["3.02", "3.20", "3.35"],
"Per one": ["4.07", "4.47", "3.35"]
}
)
print(pag)
# In[8]:
bins = [0, 9, 14, 19, 24, 29, 34, 39, 100]
group_name = ["<10", "10-14", "15-19","20-24", "25-29", "30-34", "35-39","40+"]
heros["Age summary"] = pd.cut(heros["Age"], bins, labels=group_name)
hero_unique = heros.drop_duplicates(subset="SN", keep='first', inplace=False)
hero_unique.head()
hero_unique_= hero_unique.loc[hero_unique["Age summary"] == "<10", :]
print(hero_unique_.count()["SN"])
hero_unique_1014 = hero_unique.loc[hero_unique["Age summary"] == "10-14", :]
print(hero_unique_1014.count()["SN"])
hero_unique_1519 = hero_unique.loc[hero_unique["Age summary"] == "15-19", :]
print(hero_unique_1519.count()["SN"])
hero_unique_2024 = hero_unique.loc[hero_unique["Age summary"] == "20-24", :]
print(hero_unique_2024.count()["SN"])
hero_unique_2529 = hero_unique.loc[hero_unique["Age summary"] == "25-29", :]
print(hero_unique_2529.count()["SN"])
hero_unique_3034 = hero_unique.loc[hero_unique["Age summary"] == "30-34", :]
print(hero_unique_3034.count()["SN"])
hero_unique_3539 = hero_unique.loc[hero_unique["Age summary"] == "35-39", :]
print(hero_unique_3539.count()["SN"])
hero_unique_40 = hero_unique.loc[hero_unique["Age summary"] == "40+", :]
print(hero_unique_40.count()["SN"])
percentage_ = 17/576
print(percentage_)
percentage_1014 = 22/576
print(percentage_1014)
percentage_1519 = 107/576
print(percentage_1519)
percentage_2024 = 258/576
print(percentage_2024)
percentage_2529 = 77/576
print(percentage_2529)
percentage_3034 = 52/576
print(percentage_3034)
percentage_3539 = 31/576
print(percentage_3539)
percentage_40 = 12/576
print(percentage_40)
#dataframe
agedata = pd.DataFrame({"Age summary": ["<10","10-14","15-19","20-24", "25-29", "30-34", "35-39","40+"],
"Count": ["17", "22", "107", "258", "77", "52", "31", "12"],
"percentage": ["2.95%", "3.82%", "18.58%", "44.79%", "13.37%", "9.03%", "5.38%", "2.08%"]
}
)
print(agedata)
# In[9]:
#Top spender
hero_sn = heros.groupby(['SN'])
purchase_value = hero_sn["Price"].sum()
print(purchase_value)
#purchase value sort
pvs = purchase_value.sort_values(ascending=False).head(5)
print(pvs)
#purchase count
hero_sn_ = pd.DataFrame(hero_sn["SN"].count(), columns = ["SN"])
hero_sn_.loc["Lisosia93", :]
hero_sn_.loc["Idastidru52", :]
hero_sn_.loc["Chamjask73", :]
hero_sn_.loc["Iral74", :]
hero_sn_.loc["Iskadarya95", :]
#averager purchase value
lisosia = 18.96/5
idastidru = 15.45/4
chamjask = 13.83/3
iral = 13.62/4
iskadarya = 13.10/3
print(lisosia)
print(idastidru)
print(chamjask)
print(iral)
print(iskadarya)
#dataframe
sorting_by_purchase_value = pd.DataFrame({"SN":["Lisosia93", "Idastidru52", "Chamjask73", "Iral74", "Iskadarya95"],
"Purchase Count": ["5", "4", "3", "4", "3"],
"Total Purchase Value": ["18.96", "15.45", "13.83", "13.62", "13.10"],
"Average Purchase Value": ["3.792", "3.8625", "4.61", "3.405", "4.367"]
}
)
print(sorting_by_purchase_value)
# In[10]:
#most pupular item
hero_popular_item = heros.groupby(['Item Name'])
hero_popular_item_ = hero_popular_item.count()
hero_popular_item_["SN"].sort_values(ascending = False).head(5)
# In[11]:
#most profitted item
hero_profitted_item = heros.groupby(['Price'])
hero_profitted_item_ = hero_profitted_item.count()
hero_profitted_item_["SN"].sort_values(ascending = False).head(5)
# In[ ]:
# In[ ]:
|
16e862e17eb3115db1e308a19c34ea1ac5981f57 | tamirYaffe/ShortestPath | /aStar.py | 4,451 | 3.609375 | 4 | import math
from heapq import heappush, heappop
from pyvisgraph.shortest_path import priority_dict
import queue as Q
from ass1 import print_maze, a_star
def euclidean_distance(start, end):
return math.sqrt((start[0] - end[0]) ** 2 + (start[1] - end[1]) ** 2)
class Node:
def __init__(self, parent=None, position=None):
self.parent = parent
self.position = position
self.g = 0
self.h = 0
self.f = 0
def __eq__(self, other):
return self.position == other.position
def __lt__(self, other):
if self.f == other.f:
return self.h < other.h
else:
return self.f < other.f
def __hash__(self):
return hash(self.position)
def get_neighbors(self, end_node, graph):
children = []
for edge in graph[self.position]:
node_position = edge
# Create new node
new_node = Node(self, node_position)
new_node.g = self.g + graph[self.position][node_position]['weight']
new_node.h = euclidean_distance(node_position, end_node.position)
new_node.f = new_node.g + new_node.h
children.append(new_node)
return children
def solution_path(current_node, maze, graph):
path_cost = current_node.g
path = []
current = current_node
while current is not None:
path.append((current.position[0], current.position[1]))
if maze is not None:
maze[current.position[1]][current.position[0]] = 2
if current.parent is not None:
sub_path = graph[current.parent.position][current.position]['path'][1:-1][::-1]
for point in sub_path:
path.append(point)
current = current.parent
if maze is not None:
for point in path:
maze[point[1]][point[0]] = 2
print(path_cost)
return path[::-1] # Return reversed path
# return path_cost
def aStar(maze, start, end, graph):
# Create start and end node
# start_node = Node(None, start)
# start_node.h = euclidean_distance(start, end)
# start_node.f = start_node.g + start_node.h
# end_node = Node(None, end)
# Initialize both open and closed list
open_list_queue = Q.PriorityQueue()
open_list = []
closed_list = []
# Add the start node
# heappush(open_list, start_node)
open_list_queue.put(start)
open_list.append(start)
# Loop until you find the end
while len(open_list) > 0:
# Get the current node
current_node = open_list_queue.get()
if current_node not in open_list:
continue
open_list.remove(current_node)
# Pop current off open list, add to closed list
closed_list.append(current_node)
# Found the goal
if current_node.position == end.position:
return solution_path(current_node, maze, graph)
# Generate children
children = current_node.get_neighbors(end, graph)
# Loop through children
for child in children:
# Child is on the closed list
if child in closed_list:
continue
# Child is already in the open list
if child in open_list:
dup_child = open_list[open_list.index(child)]
if child.g < dup_child.g:
open_list.remove(dup_child)
open_list_queue.put(child)
# Add the child to the open list
else:
open_list_queue.put(child)
open_list.append(child)
def dijkstra(graph, origin, destination, maze):
D = {}
P = {}
Q = priority_dict()
Q[origin] = 0
for v in Q:
D[v] = Q[v]
if v == destination: break
edges = graph[v]
for e in edges:
w = e.get_adjacent(v)
elength = D[v] + euclidean_distance(v, w)
# aster_path_cost = a_star(maze, (int(v.x), int(v.y)), (int(w.x), int(w.y)), False)
# elength = D[v] + aster_path_cost
if w in D:
if elength < D[w]:
raise ValueError
elif w not in Q or elength < Q[w]:
Q[w] = elength
P[w] = v
path = []
while 1:
path.append(destination)
if destination == origin: break
destination = P[destination]
path.reverse()
return path
|
aa81c49b435383d4971f67d96e379c026876504f | RexTremendae/AdventOfCode | /archive/Source/2020/Day23_1.py | 1,365 | 3.640625 | 4 | exampleInput = [3,8,9,1,2,5,4,6,7]
puzzleInput = [6,4,3,7,1,9,2,5,8]
inputData = puzzleInput
class Node:
def __init__(self, label):
self.label = label
self.next = None
def assignNext(self, nextNode):
self.next = nextNode
def printList(node, separator = " "):
first = node
it = first
while True:
print(f"{it.label}", end=separator)
it = it.next
if (it == None or it.label == first.label): break
print()
def findInList(node, value):
first = node
it = first
while True:
if it.label == value: return it
it = it.next
if (it == None or it.label == first.label): break
return None
n = Node(inputData[0])
nn = n
for d in inputData[1:]:
nn.assignNext(Node(d))
nn = nn.next
nn.next = n
for i in range(100):
label = n.label
n1 = n.next
n2 = n1.next
n3 = n2.next
nn = n3.next
nextN = nn
n.assignNext(nn)
n3.assignNext(None)
labelToFind = label-1
if labelToFind < 1: labelToFind = 9
while findInList(n1, labelToFind) != None:
labelToFind -= 1
if labelToFind < 1: labelToFind = 9
n = findInList(n, labelToFind)
n3.assignNext(n.next)
n.assignNext(n1)
n = nn
while (n.next.label != 1):
n = n.next
n.assignNext(n.next.next)
n = n.next
print()
printList(n, "")
print()
|
56f5058e466751de997a9b4c8a63cc42848a3522 | RexTremendae/AdventOfCode | /archive/Source/2021/Day8_2.py | 1,698 | 3.71875 | 4 | def tostring(arr):
return "".join(sorted(arr))
def get_output(line):
parts = line.rstrip().split('|')
inputs = [tostring(s) for s in parts[0].split(' ')]
outputs = [tostring(s) for s in parts[1].split(' ')]
all = inputs + outputs
digit_by_segments = {}
oneseg = ""
threeseg = ""
sixseg = ""
# 4
segments = [s for s in all if len(s) == 4][0]
digit_by_segments[segments] = 4
# 8
digit_by_segments["abcdefg"] = 8
# 1
segments = [s for s in all if len(s) == 2][0]
digit_by_segments[segments] = 1
oneseg = segments
# 7
segments = [s for s in all if len(s) == 3][0]
digit_by_segments[segments] = 7
# 6
for segments in [s for s in all if len(s) == 6]:
if tostring(set(segments) & set(oneseg)) != oneseg:
digit_by_segments[segments] = 6
sixseg = segments
# 2, 3, 5
for segments in [s for s in all if len(s) == 5]:
if tostring(set(segments) & set(oneseg)) == oneseg:
digit_by_segments[segments] = 3
threeseg = segments
elif len(set(segments) & set(sixseg)) == 5:
digit_by_segments[segments] = 5
else:
digit_by_segments[segments] = 2
# 0, 9
for segments in [s for s in all if len(s) == 6]:
if tostring(set(segments) & set(oneseg)) == oneseg:
if tostring(set(segments) & set(threeseg)) == threeseg:
digit_by_segments[segments] = 9
else:
digit_by_segments[segments] = 0
numbers = []
for seg in [o for o in outputs if o != '']:
numbers.append(digit_by_segments[seg])
sum = 0
d = 1
for n in numbers[::-1]:
sum += d*n
d*=10
return sum
file = open("Day8.txt", "r")
print (sum([get_output(line.rstrip()) for line in file.readlines()]))
|
f4bc5176e017297ab06cf67186f73809232b04d2 | rsd1244/hello-world | /newfile.py | 142 | 4 | 4 | #!/usr/bin/env python3
print("Hello World")
for x in range(10):
print(x)
greeting = "Hey There"
for ch in greeting:
print(ch, end="")
|
ac4983b74f137778773f150040b42b6b2d00fa92 | ustcchenjingfei/ProgrammingOnline | /Python100例(菜鸟教程)/4.py | 703 | 3.703125 | 4 | """
题目:输入某年某月某日,判断这一天是这一年的第几天?
程序分析:以3月5日为例,应该先把前两个月的加起来,然后再加上5天即本年的第几天,特殊情况,闰年且输入月份大于2时需考虑多加一天:
"""
year = int(input('year:'))
month = int(input('month:'))
day = int(input('day:'))
months = (0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334)
# 平年2月28天
# 闰年2月29天
# 四年一闰
if 0 < month <= 12:
sum = months[month - 1]
sum += day
if ((year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0))) and (month > 2):
sum += 1
print('{0}年{1}月{2}日是第{3}天'.format(year, month, day, sum))
|
ae12b7429e9f6146850eff57798aaa54a65021f3 | ustcchenjingfei/ProgrammingOnline | /Python100例(菜鸟教程)/17.py | 681 | 3.859375 | 4 | """
题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
程序分析:利用 for 语句,条件为输入的字符不为 '\n'。
"""
def cnt(string):
letters = 0
space = 0
digit = 0
others = 0
for i in string:
if i.isalpha():
letters += 1
elif i.isspace():
space += 1
elif i.isdigit():
digit += 1
else:
others += 1
return letters, space, digit, others
s = '123runoobc kdf235*(dfl'
letters, space, digit, others = cnt(s)
print('letters={0}, space={1}, digit={2}, others={3}'.format(letters, space, digit, others))
|
ddc33ee98f6925d8f980808d417e02d593b5b0f6 | danielhones/context | /python/tests/test_pycontext.py | 738 | 3.671875 | 4 | import os
import sys
import unittest
from helpers import *
from context import BLUE, END_COLOR, insert_term_color
class TestInsertTermColor(unittest.TestCase):
def test_color_whole_string(self):
teststr = "some example test string\nwith some new lines\tand tabs."
colored = insert_term_color(teststr, 0, len(teststr), BLUE)
expected = BLUE + teststr + END_COLOR
self.assertEqual(colored, expected)
def test_color_substring(self):
teststr = "only color THIS word"
colored = insert_term_color(teststr, 11, 15, BLUE)
expected = "only color " + BLUE + "THIS" + END_COLOR + " word"
self.assertEqual(colored, expected)
if __name__ == "__main__":
unittest.main()
|
0aaa4ee638da2375395796a927cdb2526ca23afa | msharsh/skyscrapers | /skycrapers.py | 5,331 | 4.03125 | 4 | """
This module works with skyscrapers game.
Git repository: https://github.com/msharsh/skyscrapers.git
"""
def read_input(path: str) -> list:
"""
Read game board file from path.
Return list of str.
"""
with open(path) as board_file:
board = board_file.readlines()
for i in range(len(board)):
board[i] = board[i].strip()
return board
def left_to_right_check(input_line: str, pivot: int) -> bool:
"""
Check row-wise visibility from left to right.
Return True if number of building from the left-most hint is visible looking to the right,
False otherwise.
input_line - representing board row.
pivot - number on the left-most hint of the input_line.
>>> left_to_right_check("412453*", 4)
True
>>> left_to_right_check("452453*", 5)
False
"""
visible_buildings = 1
max_height = input_line[1]
for i in range(2, len(input_line)-1):
if int(input_line[i]) > int(max_height):
visible_buildings += 1
max_height = int(input_line[i])
if visible_buildings == pivot:
return True
return False
def check_not_finished_board(board: list) -> bool:
"""
Check if skyscraper board is not finished, i.e., '?' present on the game board.
Return True if finished, False otherwise.
>>> check_not_finished_board(['***21**', '4?????*', '4?????*', '*?????5', '*?????*', '*?????*', '*2*1***'])
False
>>> check_not_finished_board(['***21**', '412453*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***'])
True
>>> check_not_finished_board(['***21**', '412453*', '423145*', '*5?3215', '*35214*', '*41532*', '*2*1***'])
False
"""
for line in board:
if '?' in line:
return False
return True
def check_uniqueness_in_rows(board: list) -> bool:
"""
Check buildings of unique height in each row.
Return True if buildings in a row have unique length, False otherwise.
>>> check_uniqueness_in_rows(['***21**', '412453*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***'])
True
>>> check_uniqueness_in_rows(['***21**', '452453*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***'])
False
>>> check_uniqueness_in_rows(['***21**', '412453*', '423145*', '*553215', '*35214*', '*41532*', '*2*1***'])
False
"""
for i in range(1, len(board)-1):
line_temp = []
for j in range(1, len(board[i])-1):
if board[i][j] in line_temp:
return False
line_temp.append(board[i][j])
return True
def check_horizontal_visibility(board: list) -> bool:
"""
Check row-wise visibility (left-right and vice versa)
Return True if all horizontal hints are satisfiable,
i.e., for line 412453* , hint is 4, and 1245 are the four buildings
that could be observed from the hint looking to the right.
>>> check_horizontal_visibility(['***21**', '412453*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***'])
True
>>> check_horizontal_visibility(['***21**', '452453*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***'])
False
>>> check_horizontal_visibility(['***21**', '452413*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***'])
False
"""
check = True
for i in range(1, len(board)-1):
if board[i][0] != '*' and board[i][-1] != '*':
check = left_to_right_check(board[i], int(board[i][0])) &\
left_to_right_check(board[i][::-1], int(board[i][-1]))
elif board[i][0] != '*':
check = left_to_right_check(board[i], int(board[i][0]))
elif board[i][-1] != '*':
check = left_to_right_check(board[i][::-1], int(board[i][-1]))
if not check:
return False
return True
def check_columns(board: list) -> bool:
"""
Check column-wise compliance of the board for uniqueness (buildings of unique height) and visibility (top-bottom and vice versa).
Same as for horizontal cases, but aggregated in one function for vertical case, i.e. columns.
>>> check_columns(['***21**', '412453*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***'])
True
>>> check_columns(['***21**', '412453*', '423145*', '*543215', '*35214*', '*41232*', '*2*1***'])
False
>>> check_columns(['***21**', '412553*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***'])
False
"""
board_turned = []
for i in range(len(board[0])):
new_row = ''
for j in range(len(board)):
new_row += board[j][i]
board_turned.append(new_row)
check_uniqueness = check_uniqueness_in_rows(board_turned)
check_visibility = check_horizontal_visibility(board_turned)
return check_uniqueness & check_visibility
def check_skyscrapers(input_path: str) -> bool:
"""
Main function to check the status of skyscraper game board.
Return True if the board status is compliant with the rules,
False otherwise.
"""
board = read_input(input_path)
if check_not_finished_board(board) and\
check_uniqueness_in_rows(board) and\
check_horizontal_visibility(board) and\
check_columns(board):
return True
return False
if __name__ == "__main__":
print(check_skyscrapers("check.txt"))
|
01b36affb80f458190d9f1f61c2ce4d98db1c807 | ly2/codeBackup | /FifthPythonProject/environment.py | 6,696 | 3.890625 | 4 | # COMP3620/6320 Artificial Intelligence
# The Australian National University - 2014
# COMP3620 and COMP6320 - Assignment 4
""" This file implements the following environments for use in Assignment 4.
You should familarise yourself with the environments contained within,
but you do not need to change anything in this file.
WindyGrid - This is a grid world with deterministic upward-blowing
wind with varying strength in different columns of squares.
WindyGridWater - This is a grid world with wind that randomly blows
in a random direction each move. A set of squares are specified
as water and there is a specified penalty for an agent falling
in the water.
"""
import random, abc
class Environment(object):
""" The class Environment will be inherited by all of the types of
envroment in which we will run experiments.
"""
@abc.abstractmethod
def __init__(self, width, height, init_pos, goal_pos):
""" All Environments share these common features.
(Environment, int, int, (int, int), (int, int)) -> None
"""
self.width = width
self.height = height
self.init_pos = init_pos
self.goal_pos = goal_pos
self.num_states = width * height
self.init_state = self.pos_to_state(init_pos)
self.current_pos = init_pos
self.num_actions = 4
self.actions = ["up", "down", "left", "right"]
self.action_dirs = {"up" : (0, -1),
"down" : (0, 1),
"left" : (-1, 0),
"right" : (1, 0) }
@abc.abstractmethod
def generate(self, action):
""" Apply the given action to the current state and return
an (observation, reward) pair.
(Environment, str) -> ((int, int), float)
"""
def end_of_episode(self):
""" Return iff it is the end of the episode. If so, reset the
environment to the initial state.
(Environment) -> bool
"""
if self.current_pos == self.goal_pos:
self.current_pos = self.init_pos
self.init_state = self.pos_to_state(self.init_pos)
return True
return False
def pos_to_state(self, pos):
""" Return the index (representing the state) of the current position.
(Environment, (int, int)) -> int
"""
return pos[1]*self.width + pos[0]
class WindyGrid(Environment):
""" WindyGrid has deterministic upward-blowing wind with the given
strength in the specified columns.
"""
def __init__(self, width, height, init_pos, goal_pos, wind):
""" Make a new WindyGrid environment.
The wind should be a list with width elements indicating
the upwards wind in each column.
(WindyGrid, int, int, (int, int), (int, int), [int, ...]) -> int
"""
super(WindyGrid, self).__init__(width, height, init_pos, goal_pos)
self.wind = wind
def generate(self, action):
""" Apply the given action to the current state and return
an (observation, reward) pair.
(WindyGrid, str) -> ((int, int), float)
"""
#Clever min-max bounds checking
a_dir = self.action_dirs[action]
pos = self.current_pos
pos = (min(max(pos[0] + a_dir[0], 0), self.width-1),
min(max(pos[1] + a_dir[1] - self.wind[pos[0]], 0), self.height-1))
self.current_pos = pos
if pos == self.goal_pos:
r = 1.0
else:
r = -1.0
return (self.pos_to_state(pos), r)
def print_map(self):
""" Print an ASCII map of the simulation.
(WindyGrid) -> None
"""
for y in xrange(self.height):
for x in xrange(self.width):
pos = (x, y)
if pos == self.current_pos:
print "A",
elif pos == self.init_pos:
print "S",
elif pos == self.goal_pos:
print "G",
else:
print "*",
print
class WindyGridWater(Environment):
""" An environment where every time the agent moves, with probability
delta, they get blown in a random direction. There is water and
a specified penalty for falling into it.
"""
def __init__(self, width, height, init_pos, goal_pos, water, delta, water_reward):
""" Make a new WindyGridWater environment.
Water is a list of positions that are filled with water.
Delta is the probability of the wind blowing the agent
in a random direction each move.
The agent gets water_reward reward when it falls into the water.
(WindyGrid, int, int, (int, int), (int, int), [(int, int), ...],
float, float) -> int
"""
super(WindyGridWater, self).__init__(width, height, init_pos, goal_pos)
self.water = water
self.delta = delta
self.water_reward = water_reward
def generate(self, action):
""" Apply the given action to the current state and return
an (observation, reward) pair.
(WindyGridWater, str) -> ((int, int), float)
"""
if random.random() < self.delta:
wind_dir = self.action_dirs[random.choice(self.actions)]
else:
wind_dir = (0, 0)
a_dir = self.action_dirs[action]
pos = self.current_pos
pos = (min(max(pos[0] + a_dir[0] + wind_dir[0], 0), self.width-1),
min(max(pos[1] + a_dir[1] + wind_dir[1], 0), self.height-1))
self.current_pos = pos
if self.current_pos in self.water:
r = self.water_reward
elif self.current_pos == self.goal_pos:
r = 1
else:
r = -1
return (self.pos_to_state(self.current_pos), r)
def print_map(self):
""" Print an ASCII map of the simulation.
(WindyGrid) -> None
"""
for y in xrange(self.height):
for x in xrange(self.width):
pos = (x, y)
if pos == self.current_pos:
print "A",
elif pos == self.init_pos:
print "S",
elif pos == self.goal_pos:
print "G",
elif pos in self.water:
print "W",
else:
print "*",
print
|
ebefa282a41ac08aeb4ef5a54c675c44da5a907c | ly2/codeBackup | /FifthPythonProject/visualisation.py | 14,513 | 3.53125 | 4 | # COMP3620/6320 Artificial Intelligence
# The Australian National University - 2014
# COMP3620 and COMP6320 - Assignment 4
"""
This file defines a Visualisation which can be imported and used
in experiments.py to help visualise the progress of your RL algorithms.
It should be used in the following way:
> import visualisation, time
> vis = visualisation.Visualisation(env, 800, 600, min_reward, max_reward)
Here, sensible values for min_reward and max_reward should be determined
by looking at the Q as your algorithm runs
(-15 and 1 should be about right for Q2)
Next, the current Q values, the current greedy policy and a trace of an episode
can be shown by calling:
vis.show_Q(agent, show_greedy_policy, trace)
Here, show_greedy_policy is a bool - the greedy policy will be shown in black.
The trace is a list [(int, str)] of state, action pairs which will be shown
coloured from white to green starting at the beginning of the list.
Pass an empty list if you don't want this to be displayed.
The Q values themselves will be shown as the colour of the triangle with the
base on the relevant edge of each grid square. The colour blue indicates low
reward, while red indicates high reward.
Finally, vis.pause() will block until the visualisation is closed.
"""
import Tkinter, sys
from environment import WindyGrid
Q_TRIANGLE_PERCENT = 0.9
Q_TRIANGLE_BORDER = 2
LINE_COLOR = "black"
MIN_Q_COLOR = (255, 0, 0)
MAX_Q_COLOR = (0, 0, 255)
G_INNER_PERCENT = 0.7
G_OUTER_PERCENT = 0.95
G_COLOR = "black"
T_INNER_PERCENT = 0.9
T_OUTER_PERCENT = 0.98
T_TRIANGLE_COLOR = "green"
MIN_T_COLOR = (255, 255, 255)
MAX_T_COLOR = (0, 255, 0)
def lerp_color(min_val, max_val, val, min_col, max_col):
""" Interpolate between two colours specified as (r, g, b) values.
(float, float, float, (int, int, int), (int, int, int)) -> (int, int, int)
"""
s1 = float(val-min_val) / (max_val-min_val)
s2 = 1.0 - s1
return [int(s1*i+s2*j) for i,j in zip(min_col, max_col)]
class Visualisation(object):
def __init__(self, env, width, height, min_reward, max_reward):
""" Initialise the visualisation with the given parameters.
env is an Environment.
width and height are the dimensions of the visualisation in pixels
min_reward is the minimum reward for coloring (this will be blue)
max_reward is the maximum reward for coloring (this will be red)
(Environment, int, int, float, float) -> None
"""
self.env = env
self.width = width
self.height = height
self.min_reward = min_reward
self.max_reward = max_reward
self.root_window = Tkinter.Tk()
self.root_window.title("Gridworld Visualisation")
self.root_window.geometry(str(width)+"x"+str(height)+"+200+200")
self.root_window.resizable(0, 0)
self.canvas = Tkinter.Canvas(self.root_window, width=width, height=height)
self.canvas.pack(fill=Tkinter.BOTH, expand=1)
self.grid_x_inc = float(self.width) / self.env.width
self.half_grid_x_inc = self.grid_x_inc / 2.0
self.grid_y_inc = float(self.height) / self.env.height
self.half_grid_y_inc = self.grid_y_inc / 2.0
self.h_lines = []
for l in xrange(self.env.height):
pos = l * self.grid_y_inc
self.h_lines.append(self.canvas.create_line(0, pos, self.width, pos,
fill=LINE_COLOR))
self.v_lines = []
for l in xrange(self.env.width):
pos = l * self.grid_x_inc
self.v_lines.append(self.canvas.create_line(pos, 0, pos, self.height,
fill=LINE_COLOR))
self.Q_values = {}
for state in xrange(self.env.num_states):
x, y = self.state_to_pos(state)
x_pos = x * self.grid_x_inc
y_pos = y * self.grid_y_inc
#up
self.Q_values[(state, "up")] = self.canvas.create_polygon(\
x_pos+Q_TRIANGLE_BORDER,
y_pos+Q_TRIANGLE_BORDER,
x_pos+self.grid_x_inc-Q_TRIANGLE_BORDER+1,
y_pos+Q_TRIANGLE_BORDER,
x_pos+self.half_grid_x_inc,
y_pos+Q_TRIANGLE_PERCENT*self.half_grid_y_inc,
fill="blue")
#down
self.Q_values[(state, "down")] = self.canvas.create_polygon(\
x_pos+Q_TRIANGLE_BORDER,
y_pos+self.grid_y_inc-Q_TRIANGLE_BORDER+1,
x_pos+self.grid_x_inc-Q_TRIANGLE_BORDER+1,
y_pos+self.grid_y_inc-Q_TRIANGLE_BORDER+1,
x_pos+self.half_grid_x_inc,
y_pos+self.grid_y_inc-Q_TRIANGLE_PERCENT*self.half_grid_y_inc,
fill="blue")
#left
self.Q_values[(state, "left")] = self.canvas.create_polygon(\
x_pos+Q_TRIANGLE_BORDER,
y_pos+Q_TRIANGLE_BORDER,
x_pos+Q_TRIANGLE_BORDER,
y_pos+self.grid_y_inc-Q_TRIANGLE_BORDER+1,
x_pos+Q_TRIANGLE_PERCENT*self.half_grid_x_inc,
y_pos+self.half_grid_y_inc,
fill="blue")
#right
self.Q_values[(state, "right")] = self.canvas.create_polygon(\
x_pos+self.grid_x_inc-Q_TRIANGLE_BORDER+1,
y_pos+Q_TRIANGLE_BORDER,
x_pos+self.grid_x_inc-Q_TRIANGLE_BORDER+1,
y_pos+self.grid_y_inc-Q_TRIANGLE_BORDER+1,
x_pos+self.grid_x_inc-Q_TRIANGLE_PERCENT*self.half_grid_x_inc,
y_pos+self.half_grid_y_inc,
fill="blue")
self.greedy_policy = {}
for state in xrange(self.env.num_states):
x, y = self.state_to_pos(state)
x_pos = x * self.grid_x_inc
y_pos = y * self.grid_y_inc
#up
self.greedy_policy[(state, "up")] = self.canvas.create_polygon(\
x_pos+Q_TRIANGLE_BORDER+self.half_grid_x_inc*G_OUTER_PERCENT,
y_pos+Q_TRIANGLE_BORDER,
x_pos+self.grid_x_inc-Q_TRIANGLE_BORDER+1-self.half_grid_x_inc*G_OUTER_PERCENT,
y_pos+Q_TRIANGLE_BORDER,
x_pos+self.grid_x_inc-Q_TRIANGLE_BORDER+1-self.half_grid_x_inc*G_INNER_PERCENT,
y_pos+Q_TRIANGLE_BORDER+self.half_grid_y_inc,
x_pos+Q_TRIANGLE_BORDER+self.half_grid_x_inc*G_INNER_PERCENT,
y_pos+Q_TRIANGLE_BORDER+self.half_grid_y_inc,
fill=G_COLOR, state=Tkinter.HIDDEN)
#down
self.greedy_policy[(state, "down")] = self.canvas.create_polygon(\
x_pos+Q_TRIANGLE_BORDER+self.half_grid_x_inc*G_OUTER_PERCENT,
y_pos+self.grid_y_inc-Q_TRIANGLE_BORDER+1,
x_pos+self.grid_x_inc-Q_TRIANGLE_BORDER+1-self.half_grid_x_inc*G_OUTER_PERCENT,
y_pos+self.grid_y_inc-Q_TRIANGLE_BORDER+1,
x_pos+self.grid_x_inc-Q_TRIANGLE_BORDER+1-self.half_grid_x_inc*G_INNER_PERCENT,
y_pos+Q_TRIANGLE_BORDER+self.half_grid_y_inc,
x_pos+Q_TRIANGLE_BORDER+self.half_grid_x_inc*G_INNER_PERCENT,
y_pos+Q_TRIANGLE_BORDER+self.half_grid_y_inc,
fill=G_COLOR, state=Tkinter.HIDDEN)
#left
self.greedy_policy[(state, "left")] = self.canvas.create_polygon(\
x_pos+Q_TRIANGLE_BORDER,
y_pos+Q_TRIANGLE_BORDER+self.half_grid_y_inc*G_OUTER_PERCENT,
x_pos+Q_TRIANGLE_BORDER,
y_pos+self.grid_y_inc-Q_TRIANGLE_BORDER+1-self.half_grid_y_inc*G_OUTER_PERCENT,
x_pos+Q_TRIANGLE_PERCENT*self.half_grid_x_inc,
y_pos+self.grid_y_inc-Q_TRIANGLE_BORDER+1-self.half_grid_y_inc*G_INNER_PERCENT,
x_pos+Q_TRIANGLE_PERCENT*self.half_grid_x_inc,
y_pos+Q_TRIANGLE_BORDER+self.half_grid_y_inc*G_INNER_PERCENT,
fill=G_COLOR, state=Tkinter.HIDDEN)
#right
self.greedy_policy[(state, "right")] = self.canvas.create_polygon(\
x_pos+self.grid_x_inc-Q_TRIANGLE_BORDER+1,
y_pos+Q_TRIANGLE_BORDER+self.half_grid_y_inc*G_OUTER_PERCENT,
x_pos+self.grid_x_inc-Q_TRIANGLE_BORDER+1,
y_pos+self.grid_y_inc-Q_TRIANGLE_BORDER+1-self.half_grid_y_inc*G_OUTER_PERCENT,
x_pos+Q_TRIANGLE_PERCENT*self.half_grid_x_inc,
y_pos+self.grid_y_inc-Q_TRIANGLE_BORDER+1-self.half_grid_y_inc*G_INNER_PERCENT,
x_pos+Q_TRIANGLE_PERCENT*self.half_grid_x_inc,
y_pos+Q_TRIANGLE_BORDER+self.half_grid_y_inc*G_INNER_PERCENT,
fill=G_COLOR, state=Tkinter.HIDDEN)
self.actions_taken = {}
for state in xrange(self.env.num_states):
x, y = self.state_to_pos(state)
x_pos = x * self.grid_x_inc
y_pos = y * self.grid_y_inc
#up
self.actions_taken[(state, "up")] = self.canvas.create_polygon(\
x_pos+Q_TRIANGLE_BORDER+self.half_grid_x_inc*T_OUTER_PERCENT,
y_pos+Q_TRIANGLE_BORDER,
x_pos+self.grid_x_inc-Q_TRIANGLE_BORDER+1-self.half_grid_x_inc*T_OUTER_PERCENT,
y_pos+Q_TRIANGLE_BORDER,
x_pos+self.grid_x_inc-Q_TRIANGLE_BORDER+1-self.half_grid_x_inc*T_INNER_PERCENT,
y_pos+Q_TRIANGLE_BORDER+self.half_grid_y_inc,
x_pos+Q_TRIANGLE_BORDER+self.half_grid_x_inc*T_INNER_PERCENT,
y_pos+Q_TRIANGLE_BORDER+self.half_grid_y_inc,
fill=T_TRIANGLE_COLOR, state=Tkinter.HIDDEN)
#down
self.actions_taken[(state, "down")] = self.canvas.create_polygon(\
x_pos+Q_TRIANGLE_BORDER+self.half_grid_x_inc*T_OUTER_PERCENT,
y_pos+self.grid_y_inc-Q_TRIANGLE_BORDER+1,
x_pos+self.grid_x_inc-Q_TRIANGLE_BORDER+1-self.half_grid_x_inc*T_OUTER_PERCENT,
y_pos+self.grid_y_inc-Q_TRIANGLE_BORDER+1,
x_pos+self.grid_x_inc-Q_TRIANGLE_BORDER+1-self.half_grid_x_inc*T_INNER_PERCENT,
y_pos+Q_TRIANGLE_BORDER+self.half_grid_y_inc,
x_pos+Q_TRIANGLE_BORDER+self.half_grid_x_inc*T_INNER_PERCENT,
y_pos+Q_TRIANGLE_BORDER+self.half_grid_y_inc,
fill=T_TRIANGLE_COLOR, state=Tkinter.HIDDEN)
#left
self.actions_taken[(state, "left")] = self.canvas.create_polygon(\
x_pos+Q_TRIANGLE_BORDER,
y_pos+Q_TRIANGLE_BORDER+self.half_grid_y_inc*T_OUTER_PERCENT,
x_pos+Q_TRIANGLE_BORDER,
y_pos+self.grid_y_inc-Q_TRIANGLE_BORDER+1-self.half_grid_y_inc*T_OUTER_PERCENT,
x_pos+Q_TRIANGLE_PERCENT*self.half_grid_x_inc,
y_pos+self.grid_y_inc-Q_TRIANGLE_BORDER+1-self.half_grid_y_inc*T_INNER_PERCENT,
x_pos+Q_TRIANGLE_PERCENT*self.half_grid_x_inc,
y_pos+Q_TRIANGLE_BORDER+self.half_grid_y_inc*T_INNER_PERCENT,
fill=T_TRIANGLE_COLOR, state=Tkinter.HIDDEN)
#right
self.actions_taken[(state, "right")] = self.canvas.create_polygon(\
x_pos+self.grid_x_inc-Q_TRIANGLE_BORDER+1,
y_pos+Q_TRIANGLE_BORDER+self.half_grid_y_inc*T_OUTER_PERCENT,
x_pos+self.grid_x_inc-Q_TRIANGLE_BORDER+1,
y_pos+self.grid_y_inc-Q_TRIANGLE_BORDER+1-self.half_grid_y_inc*T_OUTER_PERCENT,
x_pos+Q_TRIANGLE_PERCENT*self.half_grid_x_inc,
y_pos+self.grid_y_inc-Q_TRIANGLE_BORDER+1-self.half_grid_y_inc*T_INNER_PERCENT,
x_pos+Q_TRIANGLE_PERCENT*self.half_grid_x_inc,
y_pos+Q_TRIANGLE_BORDER+self.half_grid_y_inc*T_INNER_PERCENT,
fill=T_TRIANGLE_COLOR, state=Tkinter.HIDDEN)
def state_to_pos(self, state):
""" Convert a state number to a grid position.
(Visualisation, int) -> (int, int)
"""
return (state % self.env.width, state / self.env.width)
def show_Q(self, agent, show_greedy_policy, trace):
""" Update the display to show the Q values of the given agent.
This will also show the current greedy policy computed from these
Q values.
trace is a list of state action pairs (int, str) which will also
be displayed. This can be built from each episode
(RLAgent, bool, [(state, action)]) -> None
"""
try:
state_max = {}
state_max_action = {}
for sa, q in agent.Q.iteritems():
color = lerp_color(self.min_reward, self.max_reward,
max(self.min_reward, min(self.max_reward, q)),
MIN_Q_COLOR, MAX_Q_COLOR)
color ="#%02x%02x%02x"%tuple(color)
self.canvas.itemconfigure(self.Q_values[sa], fill=color)
state, action = sa
if state not in state_max or state_max[state] < q:
state_max[state] = q
state_max_action[state] = action
self.canvas.itemconfigure(self.actions_taken[sa], state=Tkinter.HIDDEN)
self.canvas.itemconfigure(self.greedy_policy[sa], state=Tkinter.HIDDEN)
if show_greedy_policy:
for state, max_action in state_max_action.iteritems():
self.canvas.itemconfigure(self.greedy_policy[(state, max_action)],
state=Tkinter.NORMAL)
for tid, (state, action) in enumerate(trace):
if action is None: continue
lerp_pos = float(tid) / len(trace)
color = lerp_color(0.0, 1.0, lerp_pos, MIN_T_COLOR, MAX_T_COLOR)
color ="#%02x%02x%02x"%tuple(color)
self.canvas.itemconfigure(self.actions_taken[(state, action)],
state=Tkinter.NORMAL, fill=color)
self.root_window.update()
except Tkinter.TclError:
pass
def pause(self):
""" Wait here for the window to close!
(Visualisation) -> None
"""
self.root_window.mainloop()
|
a387177160524693b15dbcca98ee463c02d24a90 | ly2/codeBackup | /FifthPythonProject/experiments.py | 18,408 | 3.796875 | 4 | # COMP3620/6320 Artificial Intelligence
# The Australian National University - 2014
# COMP3620 and COMP6320 - Assignment 4
""" Student Details
Student Name: Sai Ma
Student number: u5224340
Date: 25/05/2014
"""
""" In this file you should write code to generate the graphs that
you include in your report in answers.pdf.
We have provided the skeletons of functions which you can use to
run Sarsa and Q-learning if you choose.
We suggest using Matplotlib to make plots. Example code to make a
plot is included below. Matplotlib is installed on the lab computers.
On Ubuntu and other Debian based distributions of linux, you can install it
with "sudo apt-get install python-matplotlib".
Please put the code to generate different plotsinto different functions and
at the bottom of this file put clearly labelled calls to these
functions, to make it easier to test your generation code.
"""
from environment import WindyGrid, WindyGridWater
from agents import Sarsa, QLearn
def get_windy_grid():
""" This function simplifies making a WindyGrid environment.
You should call this function to get the environment with the desired
wind probability (delta) and water penalty.
For Q3 you should call this function to get the environment for Q2.
(float, float) -> GridWater
"""
return WindyGrid(10, 7, (0, 3), (7, 3), [0, 0, 0, 1, 1, 1, 2, 2, 1, 0])
def get_windy_grid_water(delta, water_reward):
""" This function simplifies making a WindyGridWater environment.
You should call this function to get the environment with the desired
wind probability (delta) and water penalty.
For Q3 you should call this function with water_reward=-10 and varying delta.
For Q4 and Q5 you should call this function with delta=0 and water_reward=-100.
(float, float) -> WindyGridWater
"""
return WindyGridWater(10, 7, (0, 1), (7, 1),
[[0, 3], [0, 4], [2, 3], [2, 4], [3, 3], [3, 4]], delta, water_reward)
###############################################################################
# Write your code below #
###############################################################################
##############################################
## Q4 Answer: algorithm part: with epsilon ##
##############################################
'''this part is Q-learn with epsilon to collected data
'''
##get a loop to form epsilon number
epsilon = 0.1
##create lists and int to save result
q_epis_list = []
q_epis_r_list = []
q_epis_l_list = []
total_reward = 0.0
while epsilon <= 0.7:
env = get_windy_grid_water(0, -100)
agent = QLearn(0.1, 0.99, epsilon, env.num_states, env.actions)
##first of all, when Q-Learning algorithm is not convergence
while not agent.convergence:
##create a count number to update episode length in batch
count = 0
##used to save episode lengths in 200 times
patch_lengths = 0.0
while count < 200:
count = count + 1
##create time_step to save episode length
time_step = 0
##initialize s
state = env.pos_to_state(env.init_pos)
##repeat until achieve the goal pos
while not env.end_of_episode():
##choose an action from Q based on state
action = agent.select_action(state)
##take action, and get reward, new state, new position, add one time_step
result = env.generate(action)
reward = result[-1]
new_state = result[0]
##update Q
agent.update_Q(state, action, new_state, reward)
##assign new_stae to state
state = int(new_state)
##add the time_step
time_step = time_step + 1
##test the algorithm is convergence or not
patch_lengths = patch_lengths + time_step
##get the average episode lengths in patch
patch_lengths = float(patch_lengths / 200)
##test the algorithm is convergence or not
agent.test_convergence(patch_lengths)
##if not convergence, make the current patch_length to past_episode
if not agent.convergence:
agent.past_episode = float(patch_lengths)
##when the algorithm convergence collected data
if agent.convergence:
##create episode to act as count to 500
episode = 0
##create sum_time to save total time size of 500 times episodes
sum_time = 0.0
while episode < 500:
episode = episode + 1
time_step = 0
state = env.pos_to_state(env.init_pos)
##there is no need to update Q, because algorithm is convergence
while not env.end_of_episode():
action = agent.select_action(state)
result = env.generate(action)
new_state = result[0]
total_reward = total_reward + result[1]
state = int(new_state)
time_step = time_step + 1
sum_time = sum_time + time_step
##get the average of 500 episodes
episode_length = sum_time / 500
total_reward = total_reward / 500
##add these delta and averge_episode_length information into former list
q_epis_list.append(epsilon)
##save the average reward and episode_length
average_reward = total_reward / episode_length
print average_reward
q_epis_r_list.append(average_reward)
q_epis_l_list.append(episode_length)
print epsilon
##when finish collecting data with 500 times episodes, add 0.1 to epsilon
epsilon = epsilon + 0.1
'''this part is perform Sarsa, with epsilon to collect data, majority code
is same when compare with Q3, then I decide to delete some comments to save
reading time.
'''
epsilon = 0.1
s_epis_list = []
s_epis_r_list = []
s_epis_l_list = []
total_reward = 0.0
while epsilon <= 0.7:
env = get_windy_grid_water(0, -100)
agent = Sarsa(0.1, 0.99, epsilon, env.num_states, env.actions)
while not agent.convergence:
count = 0
patch_lengths = 0.0
while count < 200:
count = count + 1
time_step = 0
state = env.pos_to_state(env.init_pos)
action = agent.select_action(state)
while not env.end_of_episode():
result = env.generate(action)
reward = result[-1]
new_state = result[0]
new_action = agent.select_action(new_state)
agent.update_Q(state, action, new_state, new_action, reward)
action = str(new_action)
state = int(new_state)
time_step = time_step + 1
patch_lengths = patch_lengths + time_step
patch_lengths = float(patch_lengths / 200)
agent.test_convergence(patch_lengths)
if not agent.convergence:
agent.past_episode = float(patch_lengths)
##when the algorithm convergence
if agent.convergence:
episode = 0
sum_time = 0.0
while episode < 500:
episode = episode + 1
time_step = 0
state = env.pos_to_state(env.init_pos)
while not env.end_of_episode():
action = agent.select_action(state)
result = env.generate(action)
new_state = result[0]
total_reward = total_reward + result[1]
state = int(new_state)
time_step = time_step + 1
sum_time = sum_time + time_step
episode_length = sum_time / 500
total_reward = total_reward / 500
s_epis_list.append(epsilon)
average_reward = total_reward / episode_length
s_epis_r_list.append(average_reward)
s_epis_l_list.append(episode_length)
print epsilon
epsilon = epsilon + 0.1
###############################################################
## Q4 Answer: graph display part: with epsilon (y is reward) ##
###############################################################
import matplotlib.pyplot as plt4
plt4.title("Q4 Graphic with epsilon")
plt4.ylabel("Average Reward")
plt4.xlabel("Epsilon")
##add the information into x-label and y-label, and show
plt4.plot(q_epis_list,q_epis_r_list, label="Q-Learning: Epsilon' function of Reward")
plt4.plot(s_epis_list,s_epis_r_list, label="Sarsa: Epsilon' function of Reward")
plt4.legend(loc='lower right')
plt4.show()
################################################
## Q4 Answer: algorithm part: without epsilon ##
################################################
'''this part is Q-learn without epsilon to collected data (y is reward)
'''
##get a loop to form epsilon number
epsilon = 0.1
##create lists and int to save result
q_epis_list_without = []
q_epis_r_list_without = []
q_epis_l_list_without = []
total_reward = 0.0
while epsilon <= 0.7:
env = get_windy_grid_water(0, -100)
agent = QLearn(0.1, 0.99, epsilon, env.num_states, env.actions)
while not agent.convergence:
count = 0
patch_lengths = 0.0
while count < 200:
count = count + 1
time_step = 0
state = env.pos_to_state(env.init_pos)
while not env.end_of_episode():
action = agent.select_action(state)
result = env.generate(action)
reward = result[-1]
new_state = result[0]
agent.update_Q(state, action, new_state, reward)
state = int(new_state)
time_step = time_step + 1
patch_lengths = patch_lengths + time_step
patch_lengths = float(patch_lengths / 200)
agent.test_convergence(patch_lengths)
if not agent.convergence:
agent.past_episode = float(patch_lengths)
if agent.convergence:
agent.epsilon = 0
episode = 0
sum_time = 0.0
while episode < 500:
episode = episode + 1
time_step = 0
state = env.pos_to_state(env.init_pos)
while not env.end_of_episode():
action = agent.select_action(state)
result = env.generate(action)
new_state = result[0]
total_reward = total_reward + result[1]
state = int(new_state)
time_step = time_step + 1
sum_time = sum_time + time_step
episode_length = sum_time / 500
total_reward = total_reward / 500
q_epis_list_without.append(epsilon)
average_reward = total_reward / episode_length
q_epis_r_list_without.append(average_reward)
q_epis_l_list_without.append(episode_length)
epsilon = epsilon + 0.1
'''this part is perform Sarsa, without epsilon to collect data
'''
epsilon = 0.1
s_epis_list_without = []
s_epis_r_list_without = []
s_epis_l_list_without = []
total_reward = 0.0
while epsilon <= 0.7:
env = get_windy_grid_water(0, -100)
agent = Sarsa(0.1, 0.99, epsilon, env.num_states, env.actions)
while not agent.convergence:
count = 0
patch_lengths = 0.0
while count < 200:
count = count + 1
time_step = 0
state = env.pos_to_state(env.init_pos)
action = agent.select_action(state)
while not env.end_of_episode():
result = env.generate(action)
reward = result[-1]
new_state = result[0]
new_action = agent.select_action(new_state)
agent.update_Q(state, action, new_state, new_action, reward)
action = str(new_action)
state = int(new_state)
time_step = time_step + 1
patch_lengths = patch_lengths + time_step
patch_lengths = float(patch_lengths / 200)
agent.test_convergence(patch_lengths)
if not agent.convergence:
agent.past_episode = float(patch_lengths)
##when the algorithm convergence
if agent.convergence:
agent.epsilon = 0
episode = 0
sum_time = 0.0
while episode < 500:
episode = episode + 1
time_step = 0
state = env.pos_to_state(env.init_pos)
while not env.end_of_episode():
action = agent.select_action(state)
result = env.generate(action)
new_state = result[0]
total_reward = total_reward + result[1]
state = int(new_state)
time_step = time_step + 1
sum_time = sum_time + time_step
episode_length = sum_time / 500
total_reward = total_reward / 500
s_epis_list_without.append(epsilon)
average_reward = total_reward / episode_length
s_epis_r_list_without.append(average_reward)
s_epis_l_list_without.append(episode_length)
epsilon = epsilon + 0.1
##################################################################
## Q4 Answer: graph display part: without epsilon (y is reward) ##
##################################################################
import matplotlib.pyplot as plt5
plt5.title("Q4 Graphic without epsilon")
plt5.ylabel("Average Reward")
plt5.xlabel("Epsilon")
##add the information into x-label and y-label, and show
plt5.plot(q_epis_list_without,q_epis_r_list_without, label="Q-Learning: Epsilon' function of Reward")
plt5.plot(s_epis_list_without,s_epis_r_list_without, label="Sarsa: Epsilon' function of Reward")
plt5.legend(loc='lower right')
plt5.show()
#######################################################################
## Q4 Answer: graph display part: with epsilon (y is Episode Length) ##
#######################################################################
import matplotlib.pyplot as plt6
plt6.title("Q4 Graphic with epsilon")
plt6.ylabel("Average Episode Length")
plt6.xlabel("Epsilon")
##add the information into x-label and y-label, and show
plt6.plot(q_epis_list,q_epis_l_list, label="Q-Learning: Epsilon' function of Episode Length")
plt6.plot(s_epis_list,s_epis_l_list, label="Sarsa: Epsilon' function of Episode Length")
plt6.legend(loc='lower right')
plt6.show()
##########################################################################
## Q4 Answer: graph display part: without epsilon (y is episode length) ##
##########################################################################
import matplotlib.pyplot as plt7
plt7.title("Q4 Graphic without epsilon")
plt7.ylabel("Average Episode Length")
plt7.xlabel("Epsilon")
##add the information into x-label and y-label, and show
plt7.plot(q_epis_list_without,q_epis_l_list_without, label="Q-Learning: Epsilon' function of Episode Length")
plt7.plot(s_epis_list_without,s_epis_l_list_without, label="Sarsa: Epsilon' function of Episode Length")
plt7.legend(loc='lower right')
plt7.show()
#####################
## Q5 Testing Code ##
#####################
'''this part is perform Sarsa, to get data for initi_Q value from -100 to 0.0
'''
##create lists to save information
finish_lengths = []
give_nums = []
env = get_windy_grid_water(0, -100)
agent = Sarsa(0.1, 0.99, 0.0, env.num_states, env.actions)
give_num = 0.0
while give_num >= -100:
##initial the Q values to the give_num (from -100 to 0)
agent.initial_Q(give_num)
##collected 500 times to reduce the fluctuate of result line
count = 0
patch_lengths = 0.0
while count < 500:
count = count + 1
time_step = 0
state = env.pos_to_state(env.init_pos)
action = agent.select_action(state)
while not env.end_of_episode():
result = env.generate(action)
reward = result[-1]
new_state = result[0]
new_action = agent.select_action(new_state)
agent.update_Q(state, action, new_state, new_action, reward)
action = str(new_action)
state = int(new_state)
time_step = time_step + 1
patch_lengths = patch_lengths + time_step
##save the collected data
finish_lengths.append(patch_lengths / 500.0)
give_nums.append(give_num)
give_num = give_num - 0.1
import matplotlib.pyplot as plt8
##set graphic name and x, y label's name
plt8.title("Q5 Graphic (Test Lowest Initi_Num)")
plt8.ylabel("Finish_Length")
plt8.xlabel("Give_Nums")
plt8.plot(give_nums, finish_lengths, label = 'Relation between Finish_Length and Init_Nums' )
plt8.legend(loc='lower right')
plt8.show()
#Here is how to make the environment and agent for Q2 and Q4
#env = get_windy_grid()
#agent = Sarsa(alpha, gamma, epsilon, env.num_states, env.actions)
#Here is how to make the environment and agent for Q3, Q4, Q5
#env = get_windy_grid_water(delta, water_reward)
#agent = qlearn(alpha, gamma, epsilon, env.num_states, env.actions)
#Here is how to plot with matplotlib
#import matplotlib.pyplot as plt
#plt.title("A test plot")
#plt.xlabel("x label")
#plt.ylabel("y label")
#plt.plot([1,2, 3, 4, 5], [1, 2, 3, 4, 5], label="line1")
#plt.plot([1, 2, 3, 4, 5], [5, 4, 3, 2, 1], label="line2")
#plt.yscale('linear')
#plt.legend(loc='upper left')
#plt.show()
#To use the graphical visualisation system, read the comments in visualisation.py
#This is totally optional and only exists to help you understand what your
#algorithms are doing
#Above your main loop
#import visualisation, time
#vis = visualisation.Visualisation(env, 800, 600, min_reward, max_reward)
#During an episode build up trace [(state, action)]
#At the ends of an episode do
#vis.show_Q(agent, show_greedy_policy, trace)
#time.sleep(0.1)
#At the end block until the visualisation is closed.
#vis.pause()
|
ec1702cf85a90917a4a41d498ef06d5bb2c13a28 | purohitprachi72/Encrypt-Decrypt | /encrypt-decrypt.py | 2,761 | 3.578125 | 4 | import random
import tkinter
from tkinter import *
from tkinter import messagebox
MAX_KEY_SIZE = random.randrange(1,26)
# def getMessage():
# print('Enter your message:')
# return input()
def getKey():
key = MAX_KEY_SIZE
while True:
if (key >= 1 and key <= MAX_KEY_SIZE):
return key
def getTranslatedMessage(mode, message, key):
if mode[0] == 'd':
key = -key
translated = ''
for symbol in message:
if symbol.isalpha():
num = ord(symbol)
num += key
if symbol.isupper():
if num > ord('Z'):
num -= 26
elif num < ord('A'):
num += 26
elif symbol.islower():
if num > ord('z'):
num -= 26
elif num < ord('a'):
num += 26
translated += chr(num)
else:
translated += symbol
return translated
def decrypt():
mode = 'decrypt'
message = e1.get()
key = getKey()
ans = getTranslatedMessage(mode, message, key)
output.config(text=ans)
def encrypt():
mode = 'encrypt'
message = e1.get()
key = getKey()
ans = getTranslatedMessage(mode, message, key)
output.config(text=ans)
def reset():
global MAX_KEY_SIZE
e1.delete(0, END)
MAX_KEY_SIZE = random.randrange(1,26)
output.config(text='output')
root = tkinter.Tk()
root.geometry("550x600+420+50")
root.title("Encrypt/Decrypt")
root.configure(background = "#000080")
lbl = Label(
root,
text = "Enter Your Message Here",
font = ("Verdana", 18),
bg = "#ffa500", #eed202
fg = "#000000",
)
lbl.pack(pady = 30,ipady=10,ipadx=10)
ans1 = StringVar()
e1 = Entry(
root,
font = ("Verdana", 16),
textvariable = ans1,
)
e1.pack(ipady=5,ipadx=5)
btncheck = Button(
root,
text = "ENCRYPT",
font = ("Verdana", 16),
width = 16,
bg = "#ffa500",
fg = "#1d4e89",
relief = GROOVE,
command = encrypt,
)
btncheck.pack(pady = 40)
btnreset = Button(
root,
text = "DECRYPT",
font = ("Verdana", 16),
width = 16,
bg = "#ffa500",
fg = "#1d4e89",
relief = GROOVE,
command = decrypt,
)
btnreset.pack()
output = Label(
root,
text = "Output",
font = ("Verdana", 18),
bg = "#000000",
fg = "#FFFFFF",
)
output.configure(state="active")
output.pack(pady = 30,ipady=10,ipadx=10)
reset = Button(
root,
text = "RESET",
font = ("Verdana", 16),
width = 16,
bg = "#ffa500",
fg = "#660000",
relief = GROOVE,
command = reset,
)
reset.pack()
root.mainloop()
|
b3ebf46f74f88ddfa8a4a688de107dd6af5ead70 | naiera-magdy/Abbreviation-Coding | /abbrev_utility.py | 6,484 | 3.828125 | 4 | import bitstring
import math as math
# Node class
class Node:
# Constructor magic
#
# Arguments:
# symbol {str} -- The node's key
# freq {int} -- The number of occurences
#
def __init__(self, symbol, freq):
self.symbol = symbol
self.freq = freq
self.left = None
self.right = None
# Comparison magic
def __lt__(self, other):
return self.freq < other.freq
#
# Combines two nodes into a new node
# (no value)
#
# Arguments:
# left {Node} -- The first node
# right {Node} -- The second node
#
# Returns:
# Node -- The combined node
#
def combine_nodes(left, right):
parent = Node(None, left.freq + right.freq)
parent.left = left
parent.right = right
return parent
#
# Populates the encoding dictionary
#
# Arguments:
# node {Node} -- The current node being processed
# code {str} -- The current code being accumulated
# sampleCode {dict} -- The encoding dictionary
#
def encode_tree(node, code, sampleCode):
# If the node doesn't exist, return
if node is None:
return
# If the node is a leaf, store the code
if node.symbol is not None:
sampleCode[node.symbol] = code
return
# Process left and right subtrees
encode_tree(node.left, code + '0', sampleCode)
encode_tree(node.right, code + '1', sampleCode)
return
#
# Encodes a string given an encoding dictionary
#
# Arguments:
# sample {str} -- The string that will be encoded
# sampleCode {dict} -- The encoding dictionary
#
# Returns:
# str -- The encoded string
#
def encode_sample(sample, sampleCode):
encodedSample = ''
for symbol in sample:
encodedSample += sampleCode[symbol]
return encodedSample
#
# Turns a string of binary digits into a bytearray
# (zero-padded)
#
# Arguments:
# sample {string} -- A string of binary digits
#
# Returns:
# bytearray -- The corresponding bytearray
#
def string_to_bytes(sample):
idx = 0
resultBytes = bytearray()
while idx + 8 <= len(sample):
b = sample[idx:idx + 8]
b = int(b, 2)
resultBytes.append(b & 0xff)
idx += 8
remainingLength = len(sample) - idx
if remainingLength == 0:
return resultBytes
b = sample[idx:]
b += '0' * (8 - remainingLength)
b = int(b, 2)
resultBytes.append(b & 0xff)
return resultBytes
#
# Decodes a bitstring given an encoding dictionary
#
# Arguments:
# sample {bitstring} -- The encoded bitstring
# sampleCode {dict} -- The encoding dictionary
#
# Returns:
# string -- The decoded string
#
def decode_sample(sample, sampleCode):
decodedSample = ''
# Swap keys and values for the encoding dictionary
swappedCode = { value: key for key, value in sampleCode.items() }
# Read bit-by-bit
# Accumulate key bitstring
# Once a key is located,
# append the value and reset the key
currentBits = ''
for b in sample:
currentBits += '1' if b else '0'
if currentBits in swappedCode:
# Halt on a null terminator
if swappedCode[currentBits] == '\0':
return decodedSample
decodedSample += swappedCode[currentBits]
currentBits = ''
return decodedSample
#
# Encode Given sample and save the encoded in file and its dictionary in file
#
# Arguments:
# sample {string} -- A string to be encoded
#
def abbriv_encode(sample):
# Split Sample to individual words
sample = sample.split(" ")
encodedSample = ""
encodingDic = {}
code = ""
i = 0
j = 1
while i < len(sample):
# Check if this word is a single character
if len(sample[i]) == 1:
encodedSample += sample[i] + " "
i+=1
j = i+1
continue
# Check if this word or its statement is already stored in the dictionary
skip = False
for key in encodingDic:
if encodingDic[key].find(sample[i]) == 0:
match = True
n = i
dic = encodingDic[key].split(" ")
for word in dic:
if word != sample[n]:
match = False
n += 1
if n >= len(sample):
if word != dic[len(dic)-1]:
match = False
break
if match == True:
skip = True
i += len(encodingDic[key].split(" "))
encodedSample += key + " "
break
# Search for matching words or statements
if skip == False:
found = False
while j < len(sample):
if sample[j] == sample[i]:
found = True
code = sample[i][0].upper()
count = 1
while (i+count < j and j+count < len(sample)):
if sample[j+count] != sample[i+count]:
break
code += sample[i+count][0].upper()
count += 1
k = 1
putasit = False
same = True
# Make sure that this code is unique. If not so, make it unique
while k < len(sample[i+count-1]) and same == True:
same = False
for key in encodingDic:
if key == code and encodingDic[key] != " ".join(sample[i : i+count]):
code = sample[i+count-1][k].upper()
k +=1
same = True
break
if k >= len(sample[i+count-1] ):
putasit = True
if(putasit == False):
encodingDic[code] = " ".join(sample[i : i+count])
encodedSample += code + " "
else:
# If can't make it unique so put it as it is
encodedSample += " ".join(sample[i : i+count]) + " "
i += count
break
else:
j += 1
# If this word isn't repeated put it as it is
if found == False:
encodedSample += sample[i] + " "
i+=1
j = i+1
# Save Encoded text and the dictionary in files
with open('abbrevEncoded.txt', 'w+') as file:
file.write(encodedSample)
with open('encodingDic', 'w+') as file:
file.write(str(encodingDic))
#
# Decode a given sample to its original form
#
# Arguments:
# sample {string} -- A string to be decoded
# encodingDic {dict} -- dictionary of codes
#
# Returns:
# string -- the decoded string
#
def abbriv_decode(sample,encodingDic):
sample = sample.split(" ")
i = 0
decodedSample = ""
while i < len(sample):
founded = False
for key in encodingDic:
if key == sample[i]:
decodedSample += encodingDic[key] + " "
founded = True
if founded == False:
decodedSample += sample[i] + " "
i += 1
return decodedSample.strip()
#
# Calculate the entropy of a given text
#
# Arguments:
# inputText {string} -- A string to calculate its entropy
#
# Returns:
# float -- The entropy
#
def calculate_entropy(inputText):
frequency = [0.0] * 0xFF
for symbol in inputText:
frequency[ord(symbol)] += 1
entropy = 0
for i in range(0,len(frequency)-1):
if frequency[i] == 0:
continue
frequency[i] /= len(inputText)
frequency[i] *= math.log2(1.0/float(frequency[i]))
entropy += frequency[i]
return entropy |
97f8d21ba55780327cf92909b1a73be2f26359f1 | shubhampurohit1998/test | /Problem51.py | 171 | 3.703125 | 4 | class American:
class NewYorker:
def City(self):
print("I used to live Queens but now it is New york city")
obj = American.NewYorker()
obj.City() |
725034f34dd558fd0fd870ab324ba15379dc4dff | lyse0000/Leecode2021 | /420. Strong Password Checker.py | 1,655 | 3.609375 | 4 | class Solution:
def strongPasswordChecker(self, password: str) -> int:
missing = 3
if any('a'<=char<='z' for char in password): missing -= 1
if any('A'<=char<='Z' for char in password): missing -= 1
if any(char.isdigit() for char in password): missing -= 1
one, two = 0, 0
i = 1
fix = 0 # number to fix for aaa
while i < len(password):
if password[i] == password[i-1]:
count = 1
while i < len(password) and password[i] == password[i-1]:
count+=1
i+=1
fix += count//3
if count%3 == 0: one+=1
elif count%3 == 1: two+=1
else:
i+=1
"""
aaabbb aaaBBB 111111 0
"""
if len(password)<=6:
return max(6-len(password), missing, fix)
"""
aaaababaa aaaaabbbbb aaaaaaaaaBbbbabaa
"""
if len(password)<=20:
return max(missing, fix)
"""
比如limit是12
[333 555 55777 777 7Bb]bbbabaa
333555557777777babababababavaadsada change = 4, missing type
11111111111111111111222222222222222 delete 15 - 1 3 5
"""
toomuch = len(password)-20
fix -= min(toomuch, one)
delete = max(0, toomuch-one)
fix -= min(delete, two*2)//2
delete = max(0, delete-two*2)
fix -= min(delete, fix*3)//3
return toomuch + max(fix, missing)
|
848b371cef43494f37540513995bcc39f15b984a | lyse0000/Leecode2021 | /74.240. Search a 2D Matrix I II.py | 1,311 | 3.609375 | 4 | # 240. Search a 2D Matrix II
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
M, N = len(matrix), len(matrix[0]) if matrix else 0
y, x = 0, N-1
while y<M and x>=0:
if matrix[y][x] == target:
return True
if matrix[y][x] > target:
x-=1
else:
y+=1
return False
# 74. Search a 2D Matrix I
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
"""
# SLOW
M, N = len(matrix), len(matrix[0])
lo, hi = 0, M*N-1
while lo<hi:
m = (lo+hi)//2
if matrix[m//N][m%N]==target:
return True
if matrix[m//N][m%N]<target:
lo = m+1
else:
hi = m-1
return matrix[lo//N][lo%N] == target
"""
M, N = len(matrix), len(matrix[0])
y, x = 0, N-1
while x>=0 and y<M:
if matrix[y][x] == target:
return True
if matrix[y][x] < target:
y+=1
else:
x-=1
return False
|
4320b576cef32f3e9cd9ad9ed8da31e16c5a20cb | lyse0000/Leecode2021 | /616. Add Bold Tag in String.py | 1,313 | 3.796875 | 4 | class TrieNode():
def __init__(self):
self.next = {}
self.word = None
class Trie():
def __init__(self):
self.root = TrieNode()
def insert(self, w):
node = self.root
for c in w:
if c not in node.next:
node.next[c] = TrieNode()
node = node.next[c]
node.word = w
class Solution:
def addBoldTag(self, s: str, words: List[str]) -> str:
tree = Trie()
for w in words:
tree.insert(w)
nodes = []
boolean = [False]*len(s)
for i in range(len(s)):
temp = []
nodes.append(tree.root)
for node in nodes:
if s[i] in node.next:
node = node.next[s[i]]
temp.append(node)
if node.word:
boolean[i+1-len(node.word):i+1] = [True]*len(node.word)
nodes = temp
ret, i = "", 0
while i < len(s):
if boolean[i]:
ret+="<b>"
while(i < len(s) and boolean[i]):
ret+=s[i]
i+=1
ret+="</b>"
if i<len(s): ret+=s[i]
i+=1
return ret
|
23a8b778535be8bae4377a991f703457267ee32b | acjensen/project-euler | /0027_QuadraticPrimes.py | 470 | 3.90625 | 4 | import math
def isPrime(n):
if n < 0:
return False
if n % 2 == 0 and n > 2:
return False
return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
nMax = 0
a_ = range(-999, 999)
b_ = range(-1000, 1000)
for a in a_:
for b in b_:
n = 0
while isPrime(n**2 + a*n + b):
n += 1
if n > nMax:
nMax = n
ans_a = a
ans_b = b
#print (a,b,n)
print(ans_a*ans_b)
|
d1a86520bb97baeca04fde56f66330bce4265de8 | acjensen/project-euler | /0037_TruncatablePrimes.py | 1,388 | 3.859375 | 4 | import primetools as pt
import timeit
def problem():
primes = pt.getPrimes(1000000)
def truncate(p: int, from_left=True):
''' Repeatedly truncate the number. Return false if any truncated number is not prime. '''
digits = [c for c in str(p)]
while len(digits) != 0:
if int(''.join(digits)) not in primes:
return False
else:
if from_left==True:
digits = digits[:-1]
else:
digits = digits[1:]
return True
def is_truncatable(p: int):
''' Returns whether the prime `p` is truncatable from the left and the right. '''
return truncate(p, True) and truncate(p, False)
def get_first_11_truncatable_primes():
''' First, generate a bunch of prime numbers. Go through each one in order and determine if it is truncatable until we hit 11. '''
truncatable_primes = []
num_truncatable_primes_found = 0
for p in primes:
if num_truncatable_primes_found == 11:
return truncatable_primes
if is_truncatable(p) and p not in [2, 3, 5, 7]:
num_truncatable_primes_found += 1
truncatable_primes.append(p)
print(p)
return []
print(get_first_11_truncatable_primes())
print(timeit.timeit(problem())) |
9530947bdcad6104ba7c5ce7a0fd544a2dde2a34 | JuanTovar00/Aprendiendo-con-Python | /Tablas.py | 390 | 3.65625 | 4 | #Tablas.py
#Autor: Juan Tovar
#Fecha: sabado 14 de septiembre de 2019
for i in range(1,11):
encabezado="Tabla del {}"
print(encabezado.format(i))
print()
#print sin agurmentaos se utiiza para dar un salto de linea
for j in range(1,11):
#Dentro de for se agrega otro for
salida="{} x {} ={}"
print(salida.format(i,j,i*j))
else:
print () |
ea68edbe1b2025798079fc03ff4376c3282f9c9f | RFenolio/leetcode | /61_rotate_list.py | 1,099 | 3.859375 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
if k == 0 or head is None:
return head
end = head
newEnd = head
distance = 0
while distance < k:
distance += 1
if end.next is None and distance > 0:
k = k % distance
return self.rotateRight(head, k)
end = end.next
# distance += 1
while end.next is not None:
end = end.next
newEnd = newEnd.next
end.next = head
newHead = newEnd.next
newEnd.next = None
return newHead
one = ListNode(1)
two = ListNode(2)
three = ListNode(3)
four = ListNode(4)
five = ListNode(5)
one.next = two
two.next = three
three.next = four
four.next = five
s = Solution()
res = s.rotateRight(one, 2)
assert res.val == 4
zero = ListNode(0)
one = ListNode(1)
two = ListNode(2)
zero.next = one
one.next = two
res2 = s.rotateRight(zero, 4)
assert res2.val == 2 |
8a55ad8adca4388d396e7ad73ab121f190dcc082 | krniraula/Python-2019-Fall | /Exams/exercise_3.py | 641 | 3.890625 | 4 | #Homework 4
odd_numbers = [x for x in range(1,50,2)]
for number in range(0,8):
print(odd_numbers[number])
#Homework 3
grocery_items = ['Chicken', 'Steak', 'Fish', 'Apple']
grocery_items_prices = [10, 15, 25, 2]
print("Items: " + grocery_items[2] + " Price: " + grocery_items_prices[2])
prnt("Items: " + grocery_items[3] + " Price: " + grocery_items_price[3])
grocery_items.append("Pineapple")
grocery_items_prices.append(3)
print(grocery_items)
print(grocery_items_prices)
del grocery_items[0]
del grocery_items_prices[0]
grocery_items_prices[1] = grocery_items_prices[2] * 2.0
print(grocery_items)
print(grocery_item_prices) |
3953866e18727048006993f01cef67059b622cbf | krniraula/Python-2019-Fall | /Attendance/check_string_numbers.py | 433 | 3.921875 | 4 | #Name: Khem Niraula
#Student ID: 0644115
#Due Date: November 10, 2019
#MSITM 6341
# Problem of the day
def check_num(num1,num2):
#first_num = str(input("enter First No.:"))
#Second_num = str(input("enter Second No.:"))
if int(num1)==int(num2):
print("The Numbers are equal..")
else:
print("The Numbers are not equal..")
num1=input("Enter first num: ")
num2=input("Enter Second num: ")
check_num(num1,num2) |
9cca97a531a76aad89d5300c6a331ab85afc1149 | krniraula/Python-2019-Fall | /Assignments/homework_assignment_8/menu_builder.py | 1,628 | 4.09375 | 4 | #Name: Khem Niraula
#Student ID: 0644115
#Due Date: November 3, 2019
#MSITM 6341
menu_item_name = []
def ask_user_for_menu_item_name():
continue_or_not = True
while continue_or_not == True:
item_name = input('Item name: ')
item_name.lower()
if item_name.lower() in menu_item_name:
print("WARNING: ITEM ALREADY EXISTS")
else:
menu_item_name.append(item_name)
want_to_continue = input("You want to continue? Y/N: ")
want_to_continue.lower()
if want_to_continue == "n":
continue_or_not = False
print(menu_item_name)
elif want_to_continue == "y":
continue_or_not = True
else:
return want_to_continue
menu_item_cost = []
loop_count = len(menu_item_name)
def ask_user_for_menu_item_cost():
loop_count = len(menu_item_name)
for loop_count in range(0,loop_count):
#print("Works Works Works \n")
item_cost = input("Item price: ")
menu_item_cost.append(item_cost)
def add_menu_item():
ask_user_for_menu_item_name()
ask_user_for_menu_item_cost()
print("\n......................... ")
print("Please enter the menu items for the Restaurant")
print(".........................")
add_menu_item()
menu_item_add = dict(zip(menu_item_name, menu_item_cost))
#print(menu_item_add)
print(".........................")
print("Restaurant Menu")
print(".........................")
for item in menu_item_add:
print("Item:",item + " Cost:",menu_item_add[item])
print(".........................") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.