text stringlengths 37 1.41M |
|---|
"""
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
# O(n) Linear Time
# def threes_and_fives(max):
# sum = 0
# for i in range(1, max):
# if i % 3 == 0 or i % 5 == 0:
# sum += i
# return sum
# 0(1) Constant Time
def threes_and_fives(maximum, multiple_x, multiple_y):
return get_multiples(maximum, multiple_x) + get_multiples(999, multiple_y) - get_multiples(999, multiple_x * multiple_y)
def get_multiples(maximum, n):
multiples = (maximum // n) * (maximum // n + 1) // 2 * n
return multiples
print(threes_and_fives(1000, 3, 5))
|
"""
Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
Follow up: Could you implement a solution with a linear runtime complexity and without using extra memory?
Example 1:
Input: nums = [2,2,1]
Output: 1
Example 2:
Input: nums = [4,1,2,1,2]
Output: 4
Example 3:
Input: nums = [1]
Output: 1
"""
from typing import List
def singleNumber(self, nums: List[int]) -> int:
number_map = dict()
for num in nums:
if num in number_map:
del number_map[num]
else:
number_map[num] = True
for key in number_map:
return key
|
"""
Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input:
1
/ \
2 3
\
5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
"""
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# Stack
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
if not root: return []
stack = [(root,str(root.val))]
res = []
while stack:
node, path = stack.pop()
if node.left:
stack.append((node.left, path+"->"+str(node.left.val)))
if node.right:
stack.append((node.right, path+"->"+str(node.right.val)))
if not node.left and not node.right:
res.append(path)
return res
# Recursion
class Solution:
def binaryTreePaths(self, root: TreeNode) -> 'List'[str]:
res = []
def dfs(node, array):
if node:
array.append(str(node.val))
if not node.left and not node.right:
res.append('->'.join(array))
else:
dfs(node.left, array)
dfs(node.right, array)
array.pop()
dfs(root, [])
return res
|
# ----------------------------------------
# "bitwise right shift" ('>>' Operator)
# Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros).
# This is the same as multiplying x by 2**y.
a = 240 # 11110000
a >> 2 # 00111100 -> 60
a = 79 # 1001111
a >> 2 # 0010011 -> 19
# ----------------------------------------
# "bitwise right left" ('<<' Operator)
# Returns x with the bits shifted to the right by y places. This is the same as //'ing x by 2**y.
a = 66 # 1000010
a >> 2 # 001010000 -> 80
a = 99 # 1100011
a >> 3 # 0001100 -> 12
# ----------------------------------------
# "bitwise and" ('&' Operator)
# Does a "bitwise and". Each bit of the output is 1 if the corresponding bit of x AND of y is 1, otherwise it's 0.
a = 40 # 101000
b = 23 # 010111
print(a & b) # 000000 --> 0
a = 124 # 1111100
b = 125 # 1111101
print(a & b) # 1111100 --> 124
# "bitwise or" ('|'operator)
# Does a "bitwise or". Each bit of the output is 0 if the corresponding bit of x AND of y is 0, otherwise it's 1.
a = 55 # 110111
b = 28 # 011100
print(a | b) # 111111 --> 63
a = 49 # 110001
b = 19 # 010011
print(a | b) # 110011 --> 51
# "bitwise INVERSION" ('~'operator)
# ~ x
# Returns the complement of x - the number you get by switching each 1 for a 0 and each 0 for a 1.
# This is the same as -x - 1.
a = 65 # 1000001
~a # 0111110 -> 62
a = 0b1111 # 15
b = 0b1100 # 12
a - b == 3
65 + ~65 == -1
# "bitwise EXCLUSIVE OR / XOR" ('^' operator)
# x ^ y Does a "bitwise exclusive or".
# Each bit of the output is the same as the corresponding bit in x if that bit in y is 0,
# and it's the complement of the bit in x if that bit in y is 1.
bin(0b1111 ^ 0b1111)
# '0b0'
bin(0b1111 ^ 0b0000)
# '0b1111'
bin(0b0000 ^ 0b1111)
# '0b1111'
bin(0b1010 ^ 0b1111)
# '0b101'
# this example swaps integers without a temporary variable using XOR
a = 2
b = 8
a ^= b
b ^= a
a ^= b
a # => 8
b # => 2
|
# Remove all elements from a linked list of integers that have value val.
# Example:
# Input: 1->2->6->3->4->5->6, val = 6
# Output: 1->2->3->4->5
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
if head is None:
return None
currNode = ListNode()
currNode.next = head
head = currNode
while currNode.next:
if currNode.next.val == val:
currNode.next = currNode.next.next
else:
currNode = currNode.next
return head.next
# def removeElements(self, head: ListNode, val: int) -> ListNode:
# if not head:
# return head
#
# curr = head
#
# while curr and curr.next:
# if curr.next.val == val:
# curr.next = curr.next.next
# else:
# curr = curr.next
# return head.next if head.val == val else head
|
import time
def countPrimes(n: int) -> int:
start_time = time.time()
prime_numbers = 0
for i in range(2, n):
for j in range(2, i):
if i % j == 0:
break
else:
prime_numbers += 1
end_time = time.time()
print(f"total time: {(end_time - start_time) % 60}")
return prime_numbers
# 1. Create a list of consecutive integers from 2 to n: (2, 3, 4, …, n).
# 2. Initially, let p equal 2, the first prime number.
# 3. Starting from p2, count up in increments of p and mark each of these
# numbers greater than or equal to p2 itself in the list.
# These numbers will be p(p+1), p(p+2), p(p+3), etc..
# 4. Find the first number greater than p in the list that is not marked.
# If there was no such number, stop. Otherwise, let p now equal this number (which is the next prime),
# and repeat from step 3.
def sieve_of_eratosthenes(n):
start_time = time.time()
nums = [True] * n
i = 2
while i * i < n:
if nums[i]:
j = 2
while j * i < n:
nums[j * i] = False
j += 1
i += 1
prime_count = 0
for n in nums[2:]:
if n:
prime_count += 1
end_time = time.time()
print(f"total time: {(end_time - start_time) % 60}")
return prime_count
print(countPrimes(20000))
print(sieve_of_eratosthenes(20000))
|
class Point:
def __init__(self, coordX, coordY):
self.coordX = coordX
self.coordY = coordY
class Rectangle:
def __init__(self, starting_point, broad, high):
self.starting_point = starting_point
self.broad = broad
self.high = high
def area(self):
return self.broad * self.high
def end_points(self):
top_right = self.starting_point.coordX + self.broad
bottom_left = self.starting_point.coordY + self.high
print('Starting Point (X)): ' + str(self.starting_point.coordX))
print('Starting Point (Y)): ' + str(self.starting_point.coordY))
print('End Point X-Axis (Top Right): ' + str(top_right))
print('End Point Y-Axis (Bottom Left): ' + str(bottom_left))
def build_stuff():
main_point = Point(50, 100)
rect = Rectangle(main_point, 90, 10)
return rect
my_rect = build_stuff()
print(my_rect.area())
my_rect.end_points()
|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# https://towardsdatascience.com/understanding-logistic-regression-using-a-simple-example-163de52ea900?gi=cfca5849c2e7
# https://github.com/yiuhyuk/Basketball_Logit_Blog/blob/master/basketball_logit_code.ipynb
# Dumb Logit Regression (no gradient descent so it optimizes itself very slowly)
def sigmoid(z):
return 1.0/(1.0+np.exp(-z))
# My data (makes and misses vs. distance like in the lecture)
makes = [1,1,1,1,1,1,0,1,0,1,1,0,0,1,1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0] # <- if you made the shot then this is 1
distance = [i for i in range(30)]
df = pd.DataFrame()
df['y'] = makes
df['x'] = distance
# print(df)
# initial guess of parameter values
b0 = 0.2
b1 = -0.5
# function for getting probability predictions given a beta0 and beta1
def get_predictions(b0, b1):
predictions = []
raw_predictions= []
for i in distance:
predictions.append(sigmoid(b0 + b1*i)) # <- notice that after you predict, you end up with log odds
# so you need to put the output in a sigmoid function
# to convert to probabilities
raw_predictions.append(b0 + b1*i)
return predictions, raw_predictions
# function to compute the cost function <- we need to minimize this cost function to fit the logit
def compute_cost(predictions):
costs = []
for i, val in enumerate(makes):
if val == 1:
costs.append(-np.log(predictions[i])) # notice the error is computed differently depending on y (makes)
else:
costs.append(-np.log(1-predictions[i]))
# the sum of costs is the model's current error
cost = sum(costs)
return cost, costs
# now we need to minimize cost (in reality this is done with gradient descent but I brute forced it)
# let's look at how we did with our first guess
pred1, pred1_raw = get_predictions(b0, b1)
cost1, costs1 = compute_cost(pred1)
# print('Our initial measure of error is pretty high: ', cost1)
# let's loop through a bunch of beta0s and beta1s to try to lower the cost
lowest_cost = cost1
best_params = [b0, b1]
for i in range(-30, 31):
b0_guess = i/10
for j in range(-10,11):
b1_guess = j/10
new_pred, raw_pred = get_predictions(b0_guess, b1_guess)
new_cost, cost_list = compute_cost(new_pred)
if new_cost < lowest_cost:
lowest_cost = new_cost
# print('Found a way to lower the error to: ', new_cost)
best_params = [b0_guess, b1_guess]
# print('\nMy estimate for Beta0: ', best_params[0])
# print('My estimate for Beta1: ', best_params[1])
# throw my predictions and actuals into a df for plotting
df_final = pd.DataFrame()
predictions, raw_predictions = get_predictions(best_params[0], best_params[1])
df_final['prediction'] = predictions
df_final['prediction_raw'] = raw_predictions
df_final['actual'] = makes
df_final['distance'] = distance
# print(df_final)
# scatter of just outcome (makes) and x variable (distances)
# ax = sns.scatterplot(x='distance', y='actual', data=df_final)
# ax.set_xlabel("Distance from Basket",fontsize=12)
# ax.set_ylabel("Outcome of Shot",fontsize=12)
# plt.title('Shot Outcome vs. Distance')
# plt.savefig(fname='bball_scatter1', dpi=150)
# plt.show()
# scatter with log odds and predicted probability
# sns.scatterplot(x='distance', y='actual', data=df_final)
# ax = sns.scatterplot(x='distance', y='prediction_raw', data=df_final, color='g')
# ax.set_xlabel("Distance from Basket",fontsize=12)
# ax.set_ylabel("Predicted Log Odds of Making Shot",fontsize=12)
# plt.legend(labels=['Actual Outcome', 'Predicted Log Odds'])
# plt.savefig(fname='bball_scatter2', dpi=150)
# plt.show()
# scatter with predicted probability
sns.scatterplot(x='distance', y='actual', data=df_final)
ax = sns.scatterplot(x='distance', y='prediction', data=df_final)
ax.set_xlabel("Distance from Basket",fontsize=12)
ax.set_ylabel("Predicted Probability of Making Shot",fontsize=12)
plt.legend(labels=['Actual Outcome', 'Predicted Probability'])
plt.savefig(fname='bball_scatter3', dpi=150)
plt.show() |
r"""Provides Support for Dictionary List Manipulation.
Recursively walk over a Dictionary of python and combine the keys by a joiner.
e.g.
dict = {
name: "rehan",
schooling: {
masters : "PAF KIET"
}
}
d = Dict.walk_recursive(dict)
print(d)
{ name: 'rehan', 'schooling_masters': 'PAF KIET'}
"""
class Dict(object):
@staticmethod
def unpack(nodes):
'''
Iterate over a list of dictionaries.
:param nodes:
:return:
'''
tmp_storage = []
for node in nodes:
tmp_storage.append(Dict.walk_recursive(node))
return tmp_storage
@staticmethod
def set(map, key, value, parent, joiner='_'):
'''
Add a Key to the dictionary.
:param map:
:param key:
:param value:
:param parent:
:param joiner:
:return:
'''
if parent is not None:
key = "{}{}{}".format(parent, joiner, key)
map[key] = value
return map
@staticmethod
def walk_recursive(dictionary, map=None, parent=None, joiner='_'):
'''
Walk over a dictionary recursively.
:param dictionary:
:param map:
:param parent:
:param joiner:
:return:
'''
if map is None:
map = {}
for key, value in dictionary.items():
if isinstance(value, dict):
if parent is not None:
map = Dict.walk_recursive(value, map, "{}{}{}".format(parent, joiner, key), joiner)
else:
map = Dict.walk_recursive(value, map, key, joiner)
continue
map = Dict.set(map, key, value, parent, joiner)
return map
|
import sys;
import matplotlib.pyplot as plt;
from random import uniform;
'''
This is a normal distribution simulator.
If a call of 'map.py 10 5' is called then 5 vectors of length 10, is made.
Then a change of normal distribution is made by finding the middle point
in this case '5'. Then the index number is dividied by this middle point.
So that the middle will be 1.0, and the edges will be large numbers.
Then these numbers will go in a random function from 0.0 to this number. If it
is between 0.0 and 1.0 it will be a zero. Otherwise a 1.
Then a histogram will be made of all these 5 vectors with a count to see,
hopefully a beautifully made normal distribution of one's and zero's.
'''
def ArgTest():
if (len(sys.argv) < 3):
print("ERROR: Not enough arguments. x and y required")
elif not(sys.argv[1].isdigit() & sys.argv[2].isdigit()):
print("ERROR: Arguments must be numbers")
else:
return int(sys.argv[1]), int(sys.argv[2])
def makeMatrix(a, b):
matrix = [0] * b
for i in range(len(matrix)):
matrix[i] = VectorDistribution(a)
return matrix
def VectorDistribution(l):
vector = [0] * l
result = [0] * l
middle = l/2
# ulige = 0, lige = 1
if ((l % 2) == 0):
n = 1
else:
n = 0
for i in range(1,len(vector)+1):
if (i <= middle):
oneChange = float(middle)/float(i)
else:
oneChange = float(middle)/float(i-n)
n += 2
# print("value: " + str(oneChange))
vector[i-1] = oneChange
r = uniform(0.0, oneChange)
# print("r: " + str(r))
if ((r > 0.0) & (r < 1.0)):
result[i-1] = 1
else:
result[i-1] = 0
# print(vector)
# print(result)
return result
def Count(matrix):
distribution = [0] * len(matrix[0])
result = []
print(matrix)
# print(len(matrix))
for i in range(0, len(matrix[0])):
distribution[i] = [j[i] for j in matrix]
print(distribution)
for i in range(len(distribution)):
result.append(sum(distribution[i]))
print(result)
return result
def Main():
a, b = ArgTest()
# VectorDistribution(a)
fin = Count(makeMatrix(a, b))
plt.plot(fin)
plt.show()
Main()
|
ch=''
while ch!='quit':
print("1.Read File ")
print("2.Read One line from File ")
print("3.Write/Append Content to the File")
print("4.Overwrite the Content of File")
print("5.Delete the File")
ch=input("Enter your choice : ")
if ch=='1':
f = open("myfile.txt")
print(f.read())
f.close()
elif ch=='2':
f = open("myfile.txt")
print(f.readline())
f.close()
elif ch=='3':
f = open("myfile.txt","a") # "a" - Append - will append to the end of the file
content=input("Enter the content : ")
f.write(content)
print("File Updated Successfully!!")
f.close()
elif ch=='4':
f = open("myfile.txt","w") # Note: the "w" method will overwrite the entire file.
content=input("Enter the content : ")
f.write(content)
print("File Updated Successfully!!")
f.close()
elif ch=='5':
import os
os.remove("myfile.txt")
print("File Deleted..")
elif ch=='quit':
break
|
import json
import numpy as np
class SVM():
def __init__(self, num_classes, k=100, max_iterations=100, lamb=0.1, t=0.):
self.num_classes = num_classes
self.k = k
self.max_iterations = max_iterations
self.lamb = lamb
self.t = t
def objective_function(self, X, y, w):
"""
Inputs:
- Xtrain: A 2 dimensional numpy array of data (number of samples x number of features)
- ytrain: A 1 dimensional numpy array of labels (length = number of samples )
- w: a numpy array of D elements as a D-dimension vector, which is the weight vector and initialized to be all 0s
- lamb: lambda used in pegasos algorithm
Return:
- train_obj: the value of objective function in SVM primal formulation
"""
N = X.shape[0]
zero_vec = np.array([0]*N)
obj_value = self.lamb/2 * np.dot(w.T, w) + 1/N * np.sum(np.maximum(1 - y * np.dot(X, w), zero_vec))
return obj_value
def binary_train(self, Xtrain, ytrain):
"""
Inputs:
- Xtrain: A list of num_train elements, where each element is a list of D-dimensional features.
- ytrain: A list of num_train labels
- w: a numpy array of D elements as a D-dimension vector, which is the weight vector and initialized to be all 0s
- lamb: lambda used in pegasos algorithm
- k: mini-batch size
- max_iterations: the maximum number of iterations to update parameters
Returns:
- learnt w
- traiin_obj: a list of the objective function value at each iteration during the training process, length of 500.
"""
np.random.seed(0)
N = Xtrain.shape[0]
D = Xtrain.shape[1]
for iter in range(1, self.max_iterations + 1):
A_t = np.floor(np.random.rand(self.k) * N).astype(int) # index of the current mini-batch
if iter == 1:
w = np.array([0.0]*D)
else:
wtp = w
eta_t = 1/self.lamb/iter
X_batch = Xtrain[A_t, :]
y_batch = ytrain[A_t]
yXw = y_batch * np.dot(X_batch, w)
# assert yXw.shape == (k, )
Atp = (yXw < 1.0)
# X_batch.T: D * k; y_batch: k
yX = np.dot(X_batch[Atp, :].T, y_batch[Atp])
# assert yX.shape == (D,)
wt_half = (1 - eta_t * self.lamb) * wtp + eta_t/self.k * yX
# assert w.shape == wt_half.shape
scal = 1 / np.sqrt(self.lamb) / np.sqrt(np.dot(wt_half.T, wt_half))
scal = np.minimum(1.0, scal)
w = wt_half * scal
return w
def binary_predict(self, Xtest, w):
"""
Inputs:
- Xtest: A list of num_test elements, where each element is a list of D-dimensional features.
- ytest: A list of num_test labels
- w_l: a numpy array of D elements as a D-dimension vector, which is the weight vector of SVM classifier and learned by pegasos_train()
- t: threshold, when you get the prediction from SVM classifier, it should be real number from -1 to 1. Make all prediction less than t to -1 and otherwise make to 1 (Binarize)
Returns:
- test_acc: testing accuracy.
"""
N = Xtest.shape[0]
y_est = np.dot(Xtest, w)
result_est = np.array([-1.0]*N)
result_est[y_est > self.t] = 1.0
return result_est
def OVR_train(self, X, y):
"""
Inputs:
- X: training features, a N-by-D numpy array, where N is the
number of training points and D is the dimensionality of features
- y: multiclass training labels, a N dimensional numpy array,
indicating the labels of each training point
- C: number of classes in the data
- w0: initial value of weight matrix
- b0: initial value of bias term
- step_size: step size (learning rate)
- max_iterations: maximum number of iterations for gradient descent
Returns:
- w: a C-by-D weight matrix of OVR logistic regression
- b: bias vector of length C
Implement multiclass classification using binary classifier and
one-versus-rest strategy. Recall, that the OVR classifier is
trained by training C different classifiers.
"""
N, D = X.shape
w_final = np.zeros((self.num_classes, D))
for i in range(0, self.num_classes):
y_i = 1 * (y == i) + (-1) * (y != i)
w_i = self.binary_train(X, y_i)
w_final[i, :] = w_i
return w_final
def OVR_predict(self, X, w):
"""
Inputs:
- X: testing features, a N-by-D numpy array, where N is the
number of training points and D is the dimensionality of features
- w: weights of the trained OVR model
- b: bias terms of the trained OVR model
Returns:
- preds: vector of class label predictions.
Outputted predictions should be from {0, C - 1}, where
C is the number of classes.
Make predictions using OVR strategy and predictions from binary
classifier.
"""
N, D = X.shape
y = np.zeros((self.num_classes, N))
for i in range(0, self.num_classes):
w_i = w[i, :]
y_i = self.binary_predict(X, w_i)
y[i, :] = y_i
preds = np.argmax(y, axis=0)
return preds
|
"""
Classe "Player", contenant les caractéristiques
du joueur
"""
class Player():
def __init__(self, x, y):
self.x = x
self.y = y
self.inventory = 0
def addtoInventory(self, item):
print(f"{item} ajouté à l'inventaire.")
self.inventory += 1
|
g = lambda a,b : a+b
f= lambda a,b : a*b
h = lambda a,b :a-b
q = lambda a,b :a//b
print("Addition is",g(3,3))
print("Multiplication is",f(2,90))
print("Substraction is",h(4,3))
print("Division is",q(102,3)) |
# Reading csv Files
import csv
with open("../Resources/Employee.csv", "r") as fh:
ereader = csv.reader(fh)
print("File Employee.csv contains :")
for rec in ereader:
print(rec)
|
# Calculating GCD using Recursion
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
n1 = int(input("Enter first number: "))
n2 = int(input("Enter second number: "))
d = gcd(n1, n2)
print("GCD of", n1, "and", n2, "is:", d)
|
def sum(l, n):
if n == 0:
return l[0]
else:
return l[n] + sum(l, n-1)
list1 = [10, 20, 30, 40, 50, 60, 70]
size = len(list1)
print("Sum =", sum(list1, size-1))
|
x=int(input())
y=int(input())
while x != 0 and y != 0:
if x > y :
x %= y
else:
y %= x
gsd = x+y
print(gsd)
|
from string import ascii_lowercase
def eof(initial_length, current_position, current_length):
return current_length == 0 or current_position >= initial_length - 1 or current_position >= current_length - 1
def are_polarised(l, r):
return r.upper() == l.upper() and r != l
def remove_at(cursor, data):
return data[:cursor] + data[cursor + 2:]
def get_two_chars_at(cursor, contents):
return contents[cursor:cursor + 2]
def no_polarized(contents):
for pair in zip(contents, contents[1:]):
if are_polarised(pair[0], pair[1]):
return False
return True
def un_polarise_polymer(contents):
initial_length = len(contents)
cursor = 0
current_length = initial_length
while not eof(initial_length, cursor, current_length):
# compare with the one in front of it
l, r = get_two_chars_at(cursor, contents)
while are_polarised(l, r):
contents = remove_at(cursor, contents)
if cursor != 0:
cursor -= 1
current_length -= 2
if not (eof(initial_length, cursor, current_length)):
l, r = get_two_chars_at(cursor, contents)
else:
break
cursor += 1
return contents
def remove_all(letter, contents):
return ''.join([x for x in contents if x not in [letter, letter.upper()]])
def main():
with open("input.txt") as task_input:
contents = task_input.read()[:-1]
shortened = un_polarise_polymer(contents)
part_one_answer = len(shortened)
print("Task 1 answer:", part_one_answer)
assert(9822 == part_one_answer)
# part 2 starting here
results = {}
for letter in ascii_lowercase:
without_letter = remove_all(letter, contents)
shortened_without_letter = un_polarise_polymer(without_letter)
results[letter] = len(shortened_without_letter)
part_two_answer = min(results.values())
print("Part 2 answer:", part_two_answer)
assert(5726 == part_two_answer)
def tests():
assert (are_polarised("a", "A"))
assert (are_polarised("A", "a"))
assert (not are_polarised("a", "a"))
assert (not are_polarised("A", "A"))
assert (not are_polarised("a", "b"))
assert (eof(2, 1, 5))
assert (eof(5, 1, 2))
assert (eof(1, 1, 5))
assert (not eof(2, 0, 5))
assert (not eof(3, 1, 5))
assert ("bn" == remove_at(1, "baAn"))
assert ("n" == remove_at(0, "aAn"))
assert ("b" == remove_at(1, "baA"))
assert (no_polarized("abaaB"))
assert (not no_polarized("bbB"))
assert (not no_polarized("abaAB"))
assert ("" == un_polarise_polymer("abBA"))
assert ("" == un_polarise_polymer("abcdDCBA"))
assert ("n" == un_polarise_polymer("abcdDCBAn"))
assert ("n" == un_polarise_polymer("nabcdDCBA"))
assert ("" == remove_all("a", "aA"))
assert ("nnn" == remove_all("a", "nanAn"))
if __name__ == '__main__':
tests()
main()
|
import re
def is_multiple_of(number, base):
return not number % base
def get_counter_clockwise(circle, current_index, how_many):
new_index = current_index - how_many
if new_index < 0:
new_index = len(circle) + new_index
return new_index
def get_new_index(current_index, current_length, diff):
new_index = current_index + diff
if new_index >= current_length + 1:
new_index -= current_length
return new_index
def put_next(circle, current_index, next_number):
if not is_multiple_of(next_number, 23):
new_index = get_new_index(current_index, len(circle), 2)
if next_number % 23 == 19:
return get_new_index(current_index, len(circle), 1), 0
circle.insert(new_index, next_number)
if next_number % 23 == 18:
old_value = circle[new_index + 1]
circle[new_index + 1] = next_number + 1
return new_index, old_value
return new_index, 0
new_index = get_counter_clockwise(circle, current_index, 6)
return new_index, next_number
def tests():
assert is_multiple_of(46, 23)
assert not is_multiple_of(5, 2)
assert (1, 0) == put_next([0, 1], 1, 2)
assert (3, 0) == put_next([0, 2, 1], 1, 3)
assert (1, 0) == put_next([0, 2, 1, 3], 3, 4)
assert 2 == get_counter_clockwise([1, 2, 3], 0, 1)
assert 0 == get_counter_clockwise([1, 2, 3], 1, 1)
def do_game(num_players, num_rounds):
scores = {player: 0 for player in range(num_players)}
circle = [0]
current_index = 0
next_number = 1
for a_round in range(num_rounds):
new_index, score_increase = put_next(circle, current_index, next_number)
if next_number % 23 == 18:
assign_to_23rd(scores, score_increase, a_round, num_players)
current_index = new_index
next_number += 1
continue
current_index = new_index
scores[a_round % num_players] += score_increase
next_number += 1
return scores
def assign_to_23rd(scores, score_increase, a_round, num_players):
index = a_round % num_players + 5
if index >= num_players:
index -= num_players
scores[index] += score_increase
def main():
with open("input.txt") as task_input:
contents = task_input.read()
num_players, num_rounds = get_input_data_from_input_string(contents)
scores = do_game(num_players, num_rounds)
answer = max(scores.values())
print("Answer to part 1:", answer)
assert (398048 == answer)
scores = do_game(num_players, num_rounds * 100)
answer = max(scores.values())
print("Answer to part 2:", answer)
assert (3180373421 == answer)
def get_input_data_from_input_string(contents):
input_data = string_to_dict(contents, "{num_players} players; last marble is worth {num_rounds} points")
return int(input_data["num_players"]), int(input_data["num_rounds"])
def string_to_dict(string, pattern):
regex = re.sub(r'{(.+?)}', r'(?P<_\1>.+)', pattern)
values = list(re.search(regex, string).groups())
keys = re.findall(r'{(.+?)}', pattern)
_dict = dict(zip(keys, values))
return _dict
if __name__ == "__main__":
tests()
main()
|
def fizz_buzz(number):
if number%3==0 and number%5==0:
return 'FizzBuzz'
if number% 3==0 and number%5 !=0:
return 'Fizz'
elif number%5==0 and number%3 !=0:
return 'Buzz'
else:
return 'number' |
# Question 3
# Progarmlarin Ismimleri tutacagiz
Programs = []
# Birinci Programin Ratingler icin
ProgramOneRatings = []
# Ikinci Programin Ratingler icin
ProgramTwoRatings = []
# Ucuncu Programin Ratingler icin
ProgramThreeRatings = []
TotalOfProgramOne = 0
TotalOfProgramTwo = 0
TotalOfProgramThree = 0
for i in range(3):
x = input("{0}.PROGRAMI GIRINIZ: ".format(i + 1))
Programs.insert(i, x)
i += 1
j = 0
while j < 7:
y = int(input("1.PROGRAMIN {0}.GUN RATING GIRINIZ: ".format(j + 1)))
ProgramOneRatings.insert(j, y)
TotalOfProgramOne = y + TotalOfProgramOne
j += 1
j = 0
while j < 7:
y = int(input("2.PROGRAMIN {0}.GUN RATING GIRINIZ: ".format(j + 1)))
ProgramTwoRatings.insert(j, y)
TotalOfProgramTwo = y + TotalOfProgramTwo
j += 1
j = 0
while j < 7:
y = int(input("3.PROGRAMIN {0}.GUN RATING GIRINIZ: : ".format(j + 1)))
ProgramThreeRatings.insert(j, y)
TotalOfProgramThree = y + TotalOfProgramThree
j += 1
# print("GIRILEN PROGRAMLARIN ADLAR:{0} ".format(Programs))
avgOfThirdProgram = TotalOfProgramThree / len(ProgramThreeRatings)
avgOfSecondProgram = TotalOfProgramTwo / len(ProgramTwoRatings)
avgOfFirstProgram = TotalOfProgramOne / len(ProgramOneRatings)
# Eger birinci programin rating ortalamasi baskalardan buyukse
if (avgOfFirstProgram > avgOfSecondProgram and avgOfFirstProgram > avgOfThirdProgram):
print("{0} Program".format(Programs[0]))
# Eger ikinci programin rating ortalamasi baskalardan buyukse
elif (avgOfSecondProgram > avgOfFirstProgram and avgOfSecondProgram > avgOfThirdProgram):
print("{0} Program".format(Programs[1]))
# Son ihtimal ucuncu program olur
else:
print("{0} Program".format(Programs[2]))
|
"""
You are given N numbers. Store them in a list and find the second largest number.
Input Format
The first line contains N. The second line contains an array A[] of N integers each separated by a space.
Constraints
2 <= N <= 10
-100 <= A[i] <= 100
Output Format
Output the value of the second largest number.
"""
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().split()))
k = max(arr)
for i in range(len(arr)):
if k == max(arr):
arr.remove(k)
else:
j = max(arr)
print(j)
|
import math as m
x = float(input())
if x <= -2:
print(-1)
elif x > 0 and x <=100:
print((1)/(3+2/x))
elif x >=105:
print(200)
else:
print(0)
|
YEAR_PYTHON = 1991
DELTA = 16
year_user = float(input('Год создания python: '))
delta_user = abs (year_user - YEAR_PYTHON)
if delta_user ==0:
print('good!!!')
elif delta_user <= DELTA:
print("go to wiki")
else:
print("Вообще не попал!!")
|
first_name = input('Enter first name: ')
second_name = input('Enter second name: ')
if first_name:
print("empty")
else:
print('{} {}'.format(first_name, second_name)) |
first = float(input('first number >>> '))
operation = input('operation >>> ')
second = float(input('second number >>> '))
pattern_output = '{} {} {} = {}'
res = None
if operation == '+':
res = first + second
elif operation == '-':
res = first - second
elif operation == '*':
res = first - second
else:
print('invalide operation')
if res is not None:
print(pattern_output.format(first, operation, second, res)) |
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 14 15:57:05 2018
@author: actionfocus
"""
class node():
def __init__(self, val=None, left=None, right=None):
self.val = val
self.left = left
self.right = right
class biTree():
rootnode = None
def InsertNode(self, root, x):
if root == None:
pnode = node()
pnode.val = x
pnode.left = None
pnode.right = None
root = pnode
elif (x < root.val):
root.left = self.InsertNode(root.left, x)
else:
root.right = self.InsertNode(root.right, x)
return root
def SetupBiTree(self):
list = [15,5,3,12,16,20,23,13,18,10,6,7]
for item in list:
self.rootnode = self.InsertNode(self.rootnode, item)
def display(self):
print self.rootnode.val
print self.rootnode.left.left.val
print self.rootnode.right.right.val
if __name__ == '__main__':
bt = biTree()
bt.SetupBiTree()
bt.display()
|
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 15 22:21:41 2018
@author: actionfocus
"""
class AnonymousSurvey():
def __init__(self, question):
self.question = question
self.responses = []
def show_questions(self):
print question
def store_response(self, new_response):
self.responses.append(new_response)
def show_results(self):
print "Survey result:"
for response in responses:
print '- '+response
|
from cs50 import get_string
import sys
def main():
if len(sys.argv) != 2:
print("enter the key as a non negative number argument as an arg!!!")
return 1
k = int(sys.argv[1])
if k <= 0 :
print("enter the key as a non negative number argument ")
return 2
print("type the text to cipher :")
s = get_string()
for c in s:
ascii = ord(c)
if ascii >= ord('A') and ascii <= ord('Z'):
ascii += k
while ascii > ord('Z'):
ascii -= 26;
elif ascii >= ord('a') and ascii <= ord('z'):
ascii += k
while ascii > ord('z'):
ascii -= 26;
print(f"{chr(ascii)}", end="")
print()
if __name__ == "__main__":
main() |
#!/usr/bin/python
import socket
import sys
print ("Address is: %s" % str(sys.argv[1]))
print ("Port number is: %s" % str(sys.argv[2]))
print ("Message is: %s" % str(sys.argv[3:]))
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = str(sys.argv[1])
port = int(sys.argv[2])
s.connect((host, port))
# print s.recv(1024)
message = str(sys.argv[3:])
print "Sending message to server"
s.send(message)
final = s.recv(1024)
s.close()
print "The translated message is", final
|
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
'''
Creat an empty list.
While True:
Let user enter a value as input
if input is 'done',
then print out the list
break
else
add the input to the list.
while True:
Let user enter a index which must be a vaild integer,
which means cannot exceed the index of the list.
If index is vaild,
then print out the value in the list at the index, and break
'''
|
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
res = list()
while(True):
value = input("Please enter a value: ") # Let user enter a value
if value.lower() == 'done': # If user want to end, then stop and print
print(res)
mini = -len(res)
maxi = len(res) - 1 # Calculate the range of possible index
break
else:
res.append(value) # Add value to list
while(True):
try:
index = input(f"Please enter an integer between {mini} and {maxi}: ")
print(res[int(index)])
break
# Remind user what index is vaild, and if true, then break
except (ValueError, IndexError):
print("Your input is invaild!")
# If input is a invaild index, catch error and prompt for re-entry.
# In[ ]:
|
# while useing pop method
Dic= {
1: 'NAVGURUKUL',
2: 'IN',
3: {
'A' : 'WELCOME',
'B' : 'To',
'C' : 'DHARAMSALA'
}
}
add=Dic.get(3)
add.pop('A')
Dic[3]=add
print(Dic)
# while useing del method
Dic= {
1: 'NAVGURUKUL',
2: 'IN',
3: {
'A' : 'WELCOME',
'B' : 'To',
'C' : 'DHARAMSALA'
}
}
del Dic [3]['A']
print(Dic)
|
list1 = ["one","two","three","four","five"]
list2 = [1,2,3,4,5,]
dic={}
i=0
while i<len(list1):
dic[list1[i]]=list2[i]
i=i+1
print(dic)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
EGE DOĞAN DURSUN - 05170000006
CEM ÇORBACIOĞLU - 05130000242
EGE ÜNİVERSİTESİ
MÜHENDİSLİK FAKÜLTESİ
BİLGİSAYAR MÜHENDİSLİĞİ BÖLÜMÜ
2019-2020 BAHAR DÖNEMİ
İŞLEMSEL ZEKA VE DERİN ÖĞRENME DERSİ - CIDL2020-P1
PROJE 1 - SORU 3 - ALTERNATİF 3: GENETİK ALGORİTMALARLA TRAVELLING SALESMAN PROBLEMİ ÇÖZÜMÜ
TARİH : 13 NİSAN 2020
"""
import Evolution
import Population
import time
import matplotlib.pyplot as plt
"""
I will define a game like the following :
-A logistics company want to distribute N95 face masks to warehouses in each of the 81 city in Turkey to help with COVID-19 infection.
-They need to find an efficient way to deliver the face masks.
-The warehouses need the masks immediately so there is no time to find the "perfect" solution.
-The company needs to find an "optimal" solution in the given amount of time.
-
"""
#Define the hyperparameters that will be used in genetic algorithm
pop_size = 100
elite_pop_size = 20
mutation_rate = 0.01
generations = 100
city_amount = 81
max_distance_xy = 2000
graph_pieces = 2
#Maximum time to find solutions (minutes)
total_time = 5
total_turns = 10
time_share = (total_time*60)/total_turns
#Define a common city list (problem) for each turn
city_list = Population.create_cities(city_amount, max_distance_xy)
#Start the genetic algorithm
history = []
for i in range(0, 10):
print("TURN NUMBER : ", (i+1))
start = time.time()
#This code works depending on the time limit and turn amount. It gives each turn an equal time share.
bestRoute, progress = Evolution.genetic_algorithm(pop_size,
elite_pop_size,
mutation_rate,
generations,
graph_pieces,
city_amount,
max_distance_xy,
city_list,
time_share)
#This code ignores the time limit and trains the genetic algorithm based on the number of generations
"""
bestRoute, progress = Evolution.genetic_algorithm(pop_size,
elite_pop_size,
mutation_rate,
generations,
graph_pieces,
city_amount,
max_distance_xy,
city_list)
"""
end = time.time()
history.append(progress)
#Print the best route for the final population
print("Best Route (x1, y1) -> (x2, y2) -> ... -> (xn, yn) : ")
print(bestRoute)
#Print the total number of generations
print("Total Number of Generations : ", generations)
#Print the total time of the calculation
elapsed_time = (end-start)
print("Total Time Elapsed for Turn : ", int(elapsed_time*1000) , " milliseconds.")
print("______________________________")
plt.title("Fitness Level among All Turns")
plt.ylabel('Distance')
plt.xlabel('Generation')
for i in range(0, len(history)):
plt.plot(history[i])
plt.show()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
EGE DOĞAN DURSUN - 05170000006
CEM ÇORBACIOĞLU - 05130000242
EGE ÜNİVERSİTESİ
MÜHENDİSLİK FAKÜLTESİ
BİLGİSAYAR MÜHENDİSLİĞİ BÖLÜMÜ
2019-2020 BAHAR DÖNEMİ
İŞLEMSEL ZEKA VE DERİN ÖĞRENME DERSİ - CIDL2020-P1
PROJE 1 - SORU 3 - ALTERNATİF 3: GENETİK ALGORİTMALARLA TRAVELLING SALESMAN PROBLEMİ ÇÖZÜMÜ
TARİH : 13 NİSAN 2020
"""
import FitnessEvaluation
import MatingPool
import Mutation
import Population
import matplotlib.pyplot as plt
import time
#This function handles the operations for each evolutionary generation
def next_generation(current_gen, elite_pop_size, mutation_rate):
#Rank the population depending on the fitness level
pop_ranked = FitnessEvaluation.rank_routes(current_gen)
#Select parents by using the ranked population (depending on fitness level)
selection_results = MatingPool.selection(pop_ranked, elite_pop_size)
#Create a mating pool by using the selection results from the previous line
matingpool = MatingPool.mating_pool(current_gen, selection_results)
#Breed the parents in the mating pool and create children
children = MatingPool.breed_population(matingpool, elite_pop_size)
#Mutate the population / or not, depending on the mutation rate
next_generation = Mutation.mutate_population(children, mutation_rate)
#return the next generation
return next_generation
#This function is the wrapper function that handles the evolution in multiple generations
def genetic_algorithm(pop_size, elite_size, mutation_rate, generations, graph_pieces, city_amount, max_distance_xy, population=None, time_share=None):
#Create a city list for the
if (population == None):
population = Population.create_cities(city_amount, max_distance_xy)
#Create an initial population
pop = Population.initial_population(pop_size, population)
progress = []
progress.append(1 / FitnessEvaluation.rank_routes(pop)[0][1])
#Initial distance before begining the genetic algorithm
initial_distance = (1 / FitnessEvaluation.rank_routes(pop)[0][1])
#Start the genetic algorithm
if time_share == None:
for i in range(0, generations):
pop = next_generation(pop, elite_size, mutation_rate)
progress.append(1 / FitnessEvaluation.rank_routes(pop)[0][1])
if i%(int)(generations/100) == 0:
print("%",(int(i/generations*100)), end =" => ")
#We show the graph of the fitness level in population for a total number of "graphPieces"
if i%(generations/graph_pieces) == 0:
plt.plot(progress)
plt.title("Fitness Level among Population")
plt.ylabel('Distance')
plt.xlabel('Generation')
plt.pause(0.000001)
plt.title("Fitness Level among Population")
plt.ylabel('Distance')
plt.xlabel('Generation')
plt.plot(progress)
plt.show()
else:
total_time = 0
i = 0
while total_time < time_share:
start = time.time()
pop = next_generation(pop, elite_size, mutation_rate)
progress.append(1 / FitnessEvaluation.rank_routes(pop)[0][1])
if i%(int(time_share/(time_share/(20*time_share))/50)) == 0:
print("%",(int(total_time/time_share*100)), end =" => ")
#We show the graph of the fitness level in population for a total number of "graphPieces"
if i%(int(time_share/(time_share/(20*time_share))/graph_pieces)) == 0:
plt.plot(progress)
plt.title("Fitness Level among Population")
plt.ylabel('Distance')
plt.xlabel('Generation')
plt.pause(0.000001)
end = time.time()
time_elapsed = (end-start)
total_time = total_time + time_elapsed
i = i + 1
plt.title("Fitness Level among Population")
plt.ylabel('Distance')
plt.xlabel('Generation')
plt.plot(progress)
plt.show()
#Show the initial distance and the final solution (best one in population) to the user
print("Initial Distance: ", initial_distance)
print("Final Distance: " + str(1 / FitnessEvaluation.rank_routes(pop)[0][1]))
best_route_index = FitnessEvaluation.rank_routes(pop)[0][0]
best_route = pop[best_route_index]
#Return the best route
return best_route, progress |
"""
problem70.py
https://projecteuler.net/problem=70
Euler's Totient function, φ(n) [sometimes called the phi function], is used to
determine the number of positive numbers less than or equal to n which are
relatively prime to n. For example, as 1, 2, 4, 5, 7, and 8, are all less than
nine and relatively prime to nine, φ(9)=6. The number 1 is considered to be
relatively prime to every positive number, so φ(1)=1.
Interestingly, φ(87109)=79180, and it can be seen that 87109 is a permutation of
79180.
Find the value of n, 1 < n < 10**7, for which φ(n) is a permutation of n and the
ratio n/φ(n) produces a minimum.
"""
from itertools import takewhile
from toolset import get_primes, phi
def problem70():
# The search space is too large for brute-force. So, note that we are
# seeking roughly the inverse of the previous problem -- to minimize
# n/phi(n). Therefore, we want to maximize phi(n), which is acheived for
# numbers with the fewest and largest unique prime factors. But the number
# cannot simply be prime because in that case phi(n) == n-1 which is not a
# permutation of n. Therefore, the best candidates should have two unique
# prime factors.
def is_permutation(x, y):
return sorted(str(x)) == sorted(str(y))
# Since we are seeking large values for both prime factors, we can search
# among numbers close to the value of sqrt(1e7) ~ 3162
ps = list(takewhile(lambda x: x < 4000, get_primes(start=2000)))
ns = [x*y for x in ps
for y in ps
if x != y and x*y < 1e7]
candidates = [n for n in ns if is_permutation(n, phi(n))]
return min(candidates, key=lambda n: n/phi(n))
if __name__ == "__main__":
print(problem70())
|
"""
problem56.py
https://projecteuler.net/problem=56
Considering natural numbers of the form, a**b, where a, b < 100,
what is the maximum digital sum?
"""
def digit_sum(n):
return sum(map(int, (str(n))))
def problem56():
return max(digit_sum(a**b) for a in range(100) for b in range(100))
if __name__ == "__main__":
print(problem56())
|
"""
problem75.py
https://projecteuler.net/problem=75
It turns out that 12 cm is the smallest length of wire that can be bent to form
an integer sided right angle triangle in exactly one way, but there are many
more examples.
12 cm: (3,4,5)
24 cm: (6,8,10)
30 cm: (5,12,13)
36 cm: (9,12,15)
40 cm: (8,15,17)
48 cm: (12,16,20)
In contrast, some lengths of wire, like 20 cm, cannot be bent to form an integer
sided right angle triangle, and other lengths allow more than one solution to be
found; for example, using 120 cm it is possible to form exactly three different
integer sided right angle triangles.
120 cm: (30,40,50), (20,48,52), (24,45,51)
Given that L is the length of the wire, for how many values of L ≤ 1,500,000 can
exactly one integer sided right angle triangle be formed?
"""
from collections import Counter
from itertools import count, takewhile
def children(triple):
"""Given a pythagorean triple, return its three children triples."""
# See Berggren's ternary tree, which will produce all infinitely many
# primitive triples without duplication.
a, b, c = triple
a1, b1, c1 = (-a + 2*b + 2*c), (-2*a + b + 2*c), (-2*a + 2*b + 3*c)
a2, b2, c2 = (+a + 2*b + 2*c), (+2*a + b + 2*c), (+2*a + 2*b + 3*c)
a3, b3, c3 = (+a - 2*b + 2*c), (+2*a - b + 2*c), (+2*a - 2*b + 3*c)
return (a1, b1, c1), (a2, b2, c2), (a3, b3, c3)
def problem75():
limit = 1500000
# A mapping from values of L to the number of right-angled triangles with
# the perimeter L
triangles = Counter()
# Use a depth-first search to exhaust the search space, starting with the
# first pythagorean triple.
frontier = [(3, 4, 5)]
while frontier:
triple = frontier.pop()
L = sum(triple)
if L > limit:
continue
triangles[L] += 1
a, b, c = triple
# We're not only interested in 'primitive triples', but multiples too.
multiples = takewhile(lambda m: sum(m) < limit, ((i*a, i*b, i*c) for i in count(2)))
for m in multiples:
triangles[sum(m)] += 1
for child in children(triple):
frontier.append(child)
return sum(triangles[L] == 1 for L in triangles)
if __name__ == "__main__":
print(problem75())
|
"""
problem69.py
https://projecteuler.net/problem=69
Euler's Totient function, φ(n) [sometimes called the phi function], is used to
determine the number of numbers less than n which are relatively prime to n. For
example, as 1, 2, 4, 5, 7, and 8, are all less than nine and relatively prime to
nine, φ(9)=6.
It can be seen that n=6 produces a maximum n/φ(n) for n ≤ 10. Find the value of
n ≤ 1,000,000 for which n/φ(n) is a maximum.
"""
from itertools import takewhile
from toolset import get_primes
# from fractions import Fraction
# from toolset import prime_factors
# def phi(n):
# ps = list(unique(prime_factors(n)))
# return n * reduce(operator.mul, (1 - Fraction(1, p) for p in ps))
# return max((n for n in range(2, 1000000+1)), key=lambda n: n/phi(n))
#
# The commented-out solution above is correct and true to the problem
# description, but slightly slower than 1 minute.
#
# So, note that the phi function multiplies n by (1 - (1/p)) for every p in
# its unique prime factors. Therefore, phi(n) will diminish as n has a
# greater number of small unique prime factors. Since we are seeking the
# largest value for n/phi(n), we want to minimize phi(n). We are therefore
# looking for the largest number <= 1e6 which is the product of the smallest
# unique prime factors, i.e successive prime numbers starting from 2.
def candidates():
primes = get_primes()
x = next(primes)
while True:
yield x
x *= next(primes)
def problem69():
return max(takewhile(lambda x: x < 1e6, candidates()))
if __name__ == "__main__":
print(problem69())
|
def palindrome(str):
str = str.replace(" ", "")
str = str.lower()
return str[::-1] == str
def main():
word = input("Write in a word:")
palindrome(word)
if __name__ == '__main__':
main()
|
from abc import abstractmethod, ABC
class BaseMetric(ABC):
"""Abstract base class for metrics.
"""
def __init__(self):
self.score = None
@abstractmethod
def update(self, y_true, y_pred):
"""Updates the metric with given true and predicted value for a timestep.
Args:
y_true (int): Ground truth class. Either 1 or 0.
y_pred (float): Predicted class or anomaly score. Higher values correspond to more anomalousness and lower values correspond to more normalness.
"""
pass
@abstractmethod
def get(self):
"""Gets the current value of the score. Note that some methods such as AUPR and AUROC gives exception when used with only one class exist in the list of previous y_trues.
Returns:
float: The current score.
"""
return self.score
|
def multiplication(a,b):
my_answer = a*b
print("Calculating...")
return my_answer
print("Let's Multiply stuff...")
answer = multiplication(5,6)
answer = str(answer)
print("The answer is..." + answer)
#Let's Multiply stuff...
#Calculating...
#The answer is...30 |
current_speed = int(input("please enter current speed"))
average_speed = int(input("please enter average speed"))
calc = current_speed - average_speed
demerit = calc//5
print( "points" , demerit)
if demerit > 12:
print("time to go to jail")
if (0<= demerit<=12):
print("ok")
|
def display(a):
while(a>0):
print("*")
a=a-1
def main():
i=int(input("accept number from user to print *"))
display(i)
if __name__=="__main__":
main() |
caixaaa = 0
caixabe = 0
caixace = 0
while caixaaa < 1 or caixaaa > caixabe or caixabe > caixace or caixace >1000:
caixaaa = int(input('O tamanho da caixa A é de:'))
caixabe = int(input('O tamanho da caixa B é de:'))
caixace = int(input('O tamanho da caixa C é de:'))
if caixaaa < caixabe:
if caixace == caixabe:
print('Será necessário apenas duas viagens!')
elif caixace > caixabe:
print('Será necessário apenas uma viagem!')
elif caixaaa == caixabe:
if caixaaa + caixabe < caixace:
print('Será necessário apenas uma viagens!')
elif caixace == caixabe:
print('Será necessário três viagens!')
elif caixaaa or caixabe < caixace:
print('Será necessário apenas duas viagens!')
elif caixabe < caixace:
if caixaaa < caixabe:
print('Será necessário apenas uma viagem!')
else:
if caixaaa + caixabe < caixace:
print('Será necessario apenas uma viagem!')
elif caixaaa == caixabe and caixabe == caixace:
print('Será necessário três viagens!')
else:
print('Será necessário apenas duas viagens!')
elif caixaaa == caixabe and caixabe == caixace:
print('Será necessário três viagens')
print('.')
|
def group(parts, k):
parts.sort(reverse=True)
avg=sum(parts)/k
truck_no=1
part_no=0
while truck_no<=k and truck_no<=k:
load=[]
load_sum=0
while load_sum<avg and part_no<len(parts):
load.append(parts[part_no])
load_sum+=parts[part_no]
part_no+=1
print("Trick #{}: ".format(truck_no)+" ".join([str(part) for part in load]))
truck_no+=1
if __name__=='__main__':
k=int(input("Enter count of trucks: "))
parts=list(map(int,input("Enter parts weight: ").split()))
group(parts, k)
|
def BMI(x, y):
y = y/100
BMI = x/(y*y)
print("BMI anda adalah : {:.2f}".format(BMI))
if BMI < 18.5:
print("Anda Termasuk Kekurangan Berat badan")
elif 25 > BMI >= 18.5:
print("Anda Termasuk Normal")
elif 30 > BMI >= 25:
print("Anda Termasuk Kelebihan Berat Badan")
else:
print("Anda Termasuk Obesistas")
|
total = ((int(input()) * 100 + int(input())) * int(input()))
print(total // 100, total % 100, sep=' ')
|
m, n = 0, int(input())
while n:
if n > m:
m = n
c = 1
elif n == m:
c += 1
n = int(input())
print(c)
|
m1, m2, n = 0, 0, int(input())
while n:
if n >= m1:
m2 = m1
m1 = n
elif n <= m1 and n >= m2 and m2 <= m1:
m2 = n
n = int(input())
print(m2)
|
myDict = {}
for line in open('input.txt'):
for w in line.split():
myDict[w] = myDict.get(w, -1) + 1
print(myDict[w], end=' ')
|
class Time():
@staticmethod
def _counter(m, n):
lis = []
minute_addin = m // 60
minute_remains = m % 60
second_addin = n // 60
second_remains = n % 60
if minute_remains < 0:
minute_remains += 60
minute_addin -= 1
if second_remains < 0:
second_remains += 60
second_addin -= 1
lis.append(minute_addin // 60)#Minutes addin
lis.append(minute_remains % 60)#Minutes remains
lis.append(second_addin // 60)#Seconds addin
lis.append(second_remains % 60)#Seconds remains
return lis
def __init__(self, hours, minutes, seconds):
if not (isinstance(hours, int) and isinstance(minutes, int)\
and isinstance(seconds, int)):
raise TypeError
lis = Time._counter(minutes, seconds)
self._hour = hours + lis[0]
self._minute = lis[1] + lis[2]
self._second = lis[3]
def hours(self):
return self._hour
def minutes(self):
return self._minute
def seconds(self):
return self._second
def __add__(self, another):
hours = self._hour + another.hours()
minutes = self._minute + another.minutes()
seconds = self._second + another.seconds()
return Time(hours, minutes, seconds)
def __sub__(self, another):
hours = self._hour - another.hours()
minutes = self._minute - another.minutes()
seconds = self._second - another.seconds()
return Time(hours, minutes, seconds)
def __lt__(self, another):
if self._hour != another.hours():
return self._hour < another.hours()
elif self._minute != another.minutes():
return self._minute < another.minutes()
else:
return self._second < another.seconds()
def __eq__(self, another):
if self._hour == another.hours() and self._minute == \
another.minutes() and self._second == another.seconds():
return True
else:
return False
def detail(self):
print(str(self._hour) + ':' + str(self._minute) + ':' + str(self._second))
#test code
a = Time(23, -8, -6)
b = Time(23, 2, 2)
a.detail()
c = a + b
c.detail()
|
class QueueUnderflow(ValueError):
pass
class LNode():
def __init__(self, elem, next_ = None):
self.elem = elem
self.next = next_
#add elements at tail, delete at head
class Linkqueue():
def __init__(self):
self._head = None
self._rear = None
self._counter = 0
def is_empty(self):
return self._head == None
def enqueue(self, elem):
p = LNode(elem)
if self._head == None:
self._head = p
self._rear = p
self._counter += 1
else:
self._rear.next = p
self._rear = self._rear.next
self._counter += 1
def dequeue(self):
if self._head == None:
raise QueueUnderflow('Empty queue cannot delete elements')
elif self._head.next == None:
e = self._head.elem
self._head = None
self._rear = None
self._counter -= 1
return e
else:
e = self._head.elem
p = self._head
self._head = self._head.next
p.next = None
self._counter -= 1
return e
def peek(self):
if self._head == None:
raise QueueUnderflow('Empty queue cannot get elements')
else:
e = self._head.elem
return e
def depth(self):
return self._counter
def print_queue(self):
if self._head:
p = self._head
while p:
if p.next:
print(p.elem, end = '<-')
else:
print(p.elem)
p = p.next
if __name__ == '__main__':
temp = Linkqueue()
temp.enqueue(3)
temp.enqueue(4)
temp.enqueue(5)
temp.print_queue()
s = temp.depth()
print(s)
m = temp.peek()
print(m)
k = temp.dequeue()
print(k)
temp.print_queue()
h = temp.depth()
print(h)
|
import Assoc as As
class BiTreeNode():
def __init__(self, key, value):
self.node = As.Assoc(key, value)
self.left = None
self.right = None
class SortBiTree():
def __init__(self):
self._root = None
def is_empty(self):
return self._root == None
def search(self, key):
p = self._root
while p and p.node.key != key:
if key > p.node.key:
p = p.right
elif key < p.node.key:
p = p.left
if p:
return p.node.key, p.node.value
else:
print('No elem found')
return False
def insert(self, key, value):
q = None
p = self._root
d = 0
if not p:
self._root = BiTreeNode(key, value)
return
while p:
if key == p.node.key:
p.node.value = value
return
elif key > p.node.key:
q = p
p = p.right
d = 1
else:
q = p
p = p.left
d = -1
if d == 1:
temp = BiTreeNode(key, value)
q.right = temp
return
elif d == -1:
temp = BiTreeNode(key, value)
q.left = temp
return
def values(self):
stack = []
p = self._root
stack.append(p)
while len(stack) != 0:
while p and p.left:
p = p.left
stack.append(p)
temp = stack.pop()
yield temp.node.value
p = temp.right
if p:
stack.append(p)
def entrices(self):
stack = []
p = self._root
stack.append(p)
while len(stack) != 0:
while p and p.left:
p = p.left
stack.append(p)
temp = stack.pop()
yield temp.node.key, temp.node.value
p = temp.right
if p:
stack.append(p)
def delete(self, key):
p = self._root
q = None
while p:
if p.node.key == key:
pl = p.left
pr = p.right
if not q:
if pl:
self._root = pl
while pl.right:
pl = pl.right
pl.right = pr
else:
self._root = pr
if q:
if q.left == p:
q.left = pl
if pl:
while pl.right:
pl = pl.right
pl.right = pr
else:
q.left = pr
elif q.right == p:
q.right = pl
if pl:
while pl.right:
pl = pl.right
pl.right = pr
else:
q.right = pr
p.left = None
p.right = None
return
elif p.node.key > key:
q = p
p = p.left
else:
q = p
p = p.right
print('No elem should be deleted')
return False
def print(self):
for k, v in self.entrices():
print(k, v)
#create initial tree
def buildTree(elems):
for each in elems:
if not isinstance(each, As.Assoc):
raise ValueError('The elems are not Assoc type')
res = SortBiTree()
for each in elems:
res.insert(each.key, each.value)
return res
if __name__ == '__main__':
test = [As.Assoc(2, 32), As.Assoc(18, 27), As.Assoc(7, 14), As.Assoc(12, 6),
As.Assoc(5, 18), As.Assoc(8, 11), As.Assoc(15, 3), As.Assoc(23, 0)]
tree = buildTree(test)
tree.insert(18, 45)
tree.insert(6, 78)
print(tree.search(9))
for i in tree.values():
print(i, end = '->')
print('')
tree.delete(12)
tree.print()
|
#采用邻接矩阵来构造图,但存储形式采用邻接表
class GraphError(ValueError):
pass
inf = float('inf')
class GraphL():
def __init__(self, matrix, uncount = 0):
var = len(matrix)
for each in matrix:
if len(each) != var:
raise GraphError('The matrix is not square')
self._var = var
self._uncount = uncount
self._mat = [self._outline(matrix[i], uncount) for i in range(var)]
def _outline(self, line, uncount):
res = []
for i in range(len(line)):
if line[i] != uncount and line[i] != inf:
res.append((i, line[i]))
return res
def is_empty(self):
return self._var == 0
def vertex_num(self):
return self._var
def add_vertex(self):
self._mat.append([])
self._var += 1
return self._var - 1
def _invalid(self, v):
return 0 > v or v > self._var - 1
def add_edge(self, vi, vj, val):
if vi == vj:
return
if self._invalid(vi) or self._invalid(vj):
raise GraphError('Invalid vertex cannot be added edges')
row = self._mat[vi]
counter = 0
while counter < len(row):
if row[counter][0] < vj:
counter += 1
continue
elif row[counter][0] == vj:
self._mat[vi][counter][1] = val
return
elif row[counter][0] > vj:
break
self._mat[vi].insert(counter, (vj, val))
def get_edge(self, vi, vj):
if self._invalid(vi) or self._invalid(vj):
raise GraphError('Invalid vertex cannot exist edges')
if vi == vj:
return 0
row = self._mat[vi]
for i in range(len(row)):
if row[i][0] == vj:
return row[i][1]
else:
return inf
def out_edges(self, v):
if self._invalid(v):
raise GraphError('Invalid vertex cannot list edges')
return self._mat[v]
#test
if __name__ == '__main__':
test = [[0, 1, 1, inf, 1], [1, 0, 6, inf, 1], [1, 6, 0, 1, inf], \
[inf, inf, 1, 0, 3], [1, 1, inf, 3, 0]]
k1 = GraphL(test)
k1.add_edge(3, 1, 20)
for m in range(5):
ui = k1.out_edges(m)
print(ui)
m = k1.get_edge(3, 1)
print(m)
|
class Assoc():
def __init__(self, index_, value_):
self.key = index_
self.value = value_
def __lt__(self, another):
return self.key < another.key
def __le__(self, another):
return self.key <= another.key
def __str__(self):
return 'Assoc key is {0}, value is {1}'.format(self.key, self.value)
|
"""
https://mp.weixin.qq.com/s?__biz=MzU1NDk2MzQyNg==&mid=2247484282&idx=1&sn=74af38dd9a4b169121c32cfa2ae575b9&chksm=fbdadbf7ccad52e1aa63d609c1524adcc295882ab286c8727fbca9857819460af75f0eafda65&scene=21#wechat_redirect
第92天:Python Matplotlib 进阶操作
"""
import numpy as np
import matplotlib.pyplot as plt
# 绘制 x 轴数据
x = np.arange(2, 15)
y = 3 * x + 6
# 给图形设置标题
plt.title("line chart ztf")
# 设置 x 轴和 y 轴的属性名
plt.xlabel("x axis")
plt.ylabel("y axis")
# 绘制图形
plt.plot(x, y, 'oc') # r颜色
# 显示图形
plt.show()
|
def ex5():
filename = "valores.txt"
file = open(filename, "r")
print("ficheiro {filename}")
minimos = []
line = file.readline()
while line:
print(line)
numeros = line.split(";")
minimo = min(numeros)
minimos.append(minimo)
line = file.readline()
f.close()
valor_min = min(minimos)
print("O menor numero no ficheiro {filename} e {valor_min}")
def palavras(txt):
isoladas = txt.split(" ")
palavras = []
for i in isoladas:
palavra = []
for j in i:
if j.isalpha():
palavra.append(j)
palavras.append(''.join(palavra))
print(palavras)
import math
def log(x):
print("x log(x)")
print("-------------")
for i in range(1, x):
print("{i} %.6f" % round(math.log(i),6))
import math
def log(x):
file = open("tabela_logs.txt", "w")
file.write("x log(x)")
file.write("-------------")
for i in range(1, x):
file.write("{i} %.6f" % round(math.log(i),6))
file.close() |
import pygame
class ViewInfo:
# default background color
BACKGROUND_COLOR: tuple = (0, 0, 30)
# window size in unit
SIZE_UNITS_X: int = 35
SIZE_UNITS_Y: int = 21
# on-startup unit size
DEFAULT_UNIT: float = 32.0
# unit size - display unit of measure
unit: float = DEFAULT_UNIT
# display offsets for disproportionately
offset_x: float = 0
offset_y: float = 0
# on-startup window size
DEFAULT_WINDOW_SIZE: tuple = (int(SIZE_UNITS_X * DEFAULT_UNIT), int(SIZE_UNITS_Y * DEFAULT_UNIT))
# current window size
window_size: tuple = DEFAULT_WINDOW_SIZE
"""
adjust the stored variables to match the current screen
those will be used to draw on the game canvas
"""
@staticmethod
def adjust(event):
ViewInfo.window_size = (event.w, event.h)
ViewInfo.unit = min(event.w/ViewInfo.SIZE_UNITS_X, event.h/ViewInfo.SIZE_UNITS_Y)
ViewInfo.offset_x = (event.w - (ViewInfo.unit * ViewInfo.SIZE_UNITS_X)) / 2
ViewInfo.offset_y = (event.h - (ViewInfo.unit * ViewInfo.SIZE_UNITS_Y)) / 2
"""
displays the usable window area as a rectangle
"""
@staticmethod
def display_usable_area(surface):
pygame.draw.rect(surface, (100, 100, 100), (ViewInfo.offset_x, ViewInfo.offset_y,
(ViewInfo.unit * ViewInfo.SIZE_UNITS_X), (ViewInfo.unit * ViewInfo.SIZE_UNITS_Y)), 2)
|
from src.map_module.worldmap import WorldMap
from random import random
class SingleWallReplacer:
"""
Iterates over the map and randomly places a wall tile of given id
:param wmap - the map being worked on
:param wall_id - id of the wall tile spawned
:param possible_wall_ids - ids of the walls that the new wall can replace
:param spawn_chance - a chance that the wall will be placed on each valid floor tile
"""
@staticmethod
def spawn(wmap: WorldMap, wall_id: int, possible_walls_ids: list, spawn_chance: float):
for x in range(wmap.x_size):
for y in range(wmap.y_size):
if wmap.walls[x, y] in possible_walls_ids:
if random() < spawn_chance:
wmap.walls[x, y] = wall_id
|
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 14 11:44:39 2017
@author: Admin
"""
def splitString(funny):
a,b,c,d,e = funny.split(" ")
print(a)
print(b)
print(c)
print(d)
print(e)
return;
def secondLetter(funny):
a,b,c,d,e = funny.split(" ")
print(a[1]+b[1]+c[1]+d[1]+e[1])
return;
def noSleep(phrases):
print("List without sleep",phrases[:-1])
return;
def joinWords(phrases):
phrases = " ".join(phrases)
print(phrases)
return
def alphabeticalOrder(funny):
alist = funny.split(" ")
alist.sort()
print("\n".join(alist))
return;
def problem2(aString):
alist = aString.split(" ")
alist.sort()
#unique_words = []
frequency = {}
for word in alist:
count = frequency.get(word,0)
frequency[word] = count + 1
frequency_list = frequency.keys()
for words in frequency_list:
print (words, frequency[words])
return;
import re
def problem4():
str = " austen-emma.txt:hart@vmd.cso.uiuc.edu (internet) hart@uiucvmd (bitnet) austen-emma.txt:Internet (72600.2026@compuserve.com); TEL: (212-254-5093) .austen-persuasion.txt:Editing by Martin Ward (Martin.Ward@uk.ac.durham) blake-songs.txt:Prepared by David Price, email ccx074@coventry.ac.uk "
match = re.findall(r'[\w\.-]+@[\w\.-]+', str)
print(match)
return
def problem5():
print("*******Input file with duplicate lines*******")
document_text = open('prob5.txt', 'r')
text_string = document_text.read().lower()
print(text_string)
lines = []
outfile = open('newfile.txt', 'w')
for line in open('prob5.txt', 'r'):
if line not in lines:
lines.append(line)
outfile.write(line)
outfile.close()
print("*******Output file after removing duplicate lines*******")
document_text = open('newfile.txt', 'r')
text_string = document_text.read().lower()
print(text_string)
return
from nltk.stem.porter import PorterStemmer
#from nltk.tokenize import sent_tokenize, word_tokenize
def problem7_d():
stem_words =[]
document_text = open('positive.txt', 'r')
text_string = document_text.readlines()
#print(text_string)
# text_string.split(" ")
ps = PorterStemmer()
#words = word_tokenize(text_string)
#print("Stem %s: %s" % ("studying", ps.stem("studying")))
for line in text_string:
stem_words.append(ps.stem(line.lower().strip()))
#print("Stem %s: %s" % (line, ps.stem(line.lower().strip())))
print(stem_words)
import re
import string
from nltk.corpus import stopwords
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.stem.snowball import SnowballStemmer
from nltk.stem.porter import PorterStemmer
from nltk.stem.lancaster import LancasterStemmer
from nltk.tokenize import RegexpTokenizer
from collections import Counter
def problem7a():
document_text = open('debate.txt', 'r')
text = document_text.readlines()
text = ''.join(text)
text =re.sub("[\(\[].*?[\)\]]", "", text)
LEHRER = ''.join(re.findall("""LEHRER: (.+)""", text))
OBAMA = ''.join(re.findall("""OBAMA: (.+)""", text))
ROMNEY = ''.join(re.findall("""ROMNEY: (.+)""", text))
print("\n\nStatements made by LEHRER: \n\n"+LEHRER)
print("\n\nStatements made by OBAMA: \n\n"+OBAMA)
print("\n\nStatements made by ROMNEY: \n\n"+ROMNEY)
return{'LEHRER':LEHRER,'OBAMA':OBAMA,'ROMNEY':ROMNEY};
def problem7b(debate):
porterStemmer = PorterStemmer()
snowballStemmer = SnowballStemmer("english", ignore_stopwords=False)
lancasterStemmer = LancasterStemmer()
# cachedStopWords = stopwords.words("english")
tokenizer = RegexpTokenizer(r'\w+')
stemDict = {'LEHRER': {},'OBAMA': {}, 'ROMNEY': {}}
LEHRER = debate['LEHRER']
OBAMA = debate['OBAMA']
ROMNEY = debate['ROMNEY']
LEHRER = "".join(LEHRER)
LEHRER = tokenizer.tokenize(LEHRER)
LEHRER = ' '.join([word.lower() for word in LEHRER if word not in stopwords.words("english")])
pstemmed_words = ' '.join([porterStemmer.stem(word) for word in LEHRER.split(' ')])
stemDict['LEHRER'].update({'porterStemmer':pstemmed_words})
stemDict11 = stemDict['LEHRER']['porterStemmer']
print("\n\n\nLEHRER:porterStemmer\n\n ",stemDict11)
sstemmed_words = ' '.join([snowballStemmer.stem(word) for word in LEHRER.split(' ')])
stemDict['LEHRER'].update({'snowballStemmer':sstemmed_words})
stemDict12 = stemDict['LEHRER']['porterStemmer']
print("\n\n\nLEHRER:snowballStemmer \n\n ",stemDict12)
lstemmed_words = ' '.join([lancasterStemmer.stem(word) for word in LEHRER.split(' ')])
stemDict['LEHRER'].update({'lancasterStemmer':lstemmed_words})
stemDict13 = stemDict['LEHRER']['lancasterStemmer']
print("\n\n\nLEHRER:lancasterStemmer \n\n ",stemDict13)
OBAMA = "".join(OBAMA)
OBAMA = tokenizer.tokenize(OBAMA)
OBAMA = ' '.join([word.lower() for word in OBAMA if word not in stopwords.words("english")])
pstemmed_words = ' '.join([porterStemmer.stem(word) for word in OBAMA.split(' ')])
stemDict['OBAMA'].update({'porterStemmer':pstemmed_words})
stemDict21 = stemDict['OBAMA']['porterStemmer']
print("\n\n\nOBAMA:porterStemmer\n\n ",stemDict21)
sstemmed_words = ' '.join([snowballStemmer.stem(word) for word in OBAMA.split(' ')])
stemDict['OBAMA'].update({'snowballStemmer':sstemmed_words})
stemDict22 = stemDict['OBAMA']['porterStemmer']
print("\n\n\nOBAMA:snowballStemmer \n\n ",stemDict22)
lstemmed_words = ' '.join([lancasterStemmer.stem(word) for word in OBAMA.split(' ')])
stemDict['OBAMA'].update({'lancasterStemmer':lstemmed_words})
stemDict23 = stemDict['OBAMA']['lancasterStemmer']
print("\n\n\nOBAMA:lancasterStemmer \n\n ",stemDict23)
ROMNEY = "".join(ROMNEY)
ROMNEY = tokenizer.tokenize(ROMNEY)
ROMNEY = ' '.join([word.lower() for word in ROMNEY if word not in stopwords.words("english")])
pstemmed_words = ' '.join([porterStemmer.stem(word) for word in ROMNEY.split(' ')])
stemDict['ROMNEY'].update({'porterStemmer':pstemmed_words})
stemDict31 = stemDict['ROMNEY']['porterStemmer']
print("\n\n\nROMNEY:porterStemmer\n\n ",stemDict31)
sstemmed_words = ' '.join([snowballStemmer.stem(word) for word in ROMNEY.split(' ')])
stemDict['ROMNEY'].update({'snowballStemmer':sstemmed_words})
stemDict32 = stemDict['ROMNEY']['porterStemmer']
print("\n\n\nROMNEY:snowballStemmer \n\n ",stemDict32)
lstemmed_words = ' '.join([lancasterStemmer.stem(word) for word in ROMNEY.split(' ')])
stemDict['ROMNEY'].update({'lancasterStemmer':lstemmed_words})
stemDict33 = stemDict['ROMNEY']['lancasterStemmer']
print("\n\n\nROMNEY:lancasterStemmer \n\n ",stemDict33)
return stemDict#{stemDict['LEHRER']['porterStemmer']:stemDict11, stemDict['OBAMA']['porterStemmer']:stemDict21 ,stemDict['ROMNEY']['porterStemmer']:stemDict31};
def problem7c(stemDict):
stemDict11 = stemDict['LEHRER']['porterStemmer']
#stemDict22 = stemDict['OBAMA']['porterStemmer']
#stemDict31 = stemDict['ROMNEY']['porterStemmer']
words = re.findall(r'\w+', stemDict11)
"""
LEHRERlist = stemDict11.split(" ")
frequency = {}
for word in LEHRERlist:
count = frequency.get(word,0)
frequency[word] = count + 1
frequency_LEHRERlist = frequency.keys()
"""
print(Counter(words).most_common(10))
"""
for words in frequency_LEHRERlist:
print (words, frequency[words])
"""
return
def problem7e(stemDict):
maximum = {}
with open('positive.txt', 'r+') as p:
positive_text = p.readlines()
positive_text = [word.strip() for word in positive_text]
#print(positive_text)
for key , value in stemDict.items():
text = stemDict[key]['porterStemmer'].split(' ')
#print(len(text))
x = [word for word in text if word in positive_text]
print('this is list...........................................\n\n\n\n')
for word in x:
#print('this is list...........................................\n\n\n\n')
print(word)
maximum['{0}'.format(key)] = len(x)
print('i am', key)
print(Counter(x).most_common(10))
print('\nThe speaker uses the positive words listed in the positive word dictionary most often is :',max(maximum))
funny = "colorless green ideas sleep furiously"
splitString(funny)
secondLetter(funny)
phrases = funny.split(" ")
noSleep(phrases)
joinWords(phrases)
alphabeticalOrder(funny)
aString = "colorless colorless zebra green ideas ideas"
problem2(aString)
problem4()
problem5()
debate = problem7a()
stemDict = problem7b(debate)
problem7c(stemDict)
problem7_d()
problem7e(stemDict)
|
contador = total = 0
while True:
idades = int(input())
if idades > 0:
total += idades
contador += 1
else:
break
print(f'{total/contador:.2f}')
|
# line 3 will access and open a file in the folder named "um-server-01.txt"
# it will save the file into a new variable called log_file
log_file = open("um-server-01.txt")
# line 7 is the opening of a function in python named sales_reports
# the function will take in a parameter titled log_file
def sales_reports(log_file):
#line 9 is the initiation of a loop that will access one line at a time in our file
for line in log_file:
#line 11 will remove any blank characters or spaces at the end of each line
line = line.rstrip()
# line 13 is a new list storing the first three characters our line (day of week)
day = line[0:3]
# line 15 and 16 are am if statement that will print all lines that are associates with tuesday (changed to monday)
if day == "Mon":
print(line)
# line 20 invokes the function or makes the function run
# uses our variable log_file as the argument for the log_file parameter
sales_reports(log_file)
|
from beautifultable import BeautifulTable
#Prints in a pretty, table fashion a query result
def printTable(query, headers):
table = BeautifulTable(max_width=160)
table.set_style(BeautifulTable.STYLE_GRID)
table.column_headers = headers
for row in query:
table.append_row(row)
print(table)
# This is to be used as an imported module
if __name__ == "__main__":
print("Please do not run this independently. Contact programmer")
|
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
import cv2
import os
# Color space is a specific organization of colors
# They provide a way to categorize colors and represent them in digital images
# RGB Thresholding doesn't work well under varying light conditions
# or under varying color like yellow
# HLS Thresholding isolates lightness (L), which varies most under
# different lighting conditions.
# H and S channels stay consistent in shadow or excessive brightness
# HLS can be used to detect lane lines of different colors under
# different lighting conditions
# Hue - represents color independent of any change in brightness
# Lightness and Value - represent different ways to measure relative
# lightness or darkness of a color
# Saturation - measurement of colorfulness
# As colors get lighter (white), their saturation value is lower
# Most intense colors (bright red, blue , yellow) have high saturation
class ColorThresholds:
# Apply Grayscale Thresholding
def apply_gray_thresh(self, img, thresh = (0, 255)):
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
binary_img = np.zeros_like(gray)
binary_img[ (gray > thresh[0]) & (gray <= thresh[1]) ] = 1
return binary_img
# Thresholding individual RGB Color Channels
def apply_r_thresh(self, img, thresh = (0, 255)):
r_img = img[:,:,0]
binary_img = np.zeros_like(r_img)
binary_img[ (r_img >= thresh[0]) & (r_img <= thresh[1]) ] = 1
return binary_img
def apply_g_thresh(self, img, thresh = (0, 255)):
g_img = img[:,:,1]
binary_img = np.zeros_like(g_img)
binary_img[ (g_img >= thresh[0]) & (g_img <= thresh[1]) ] = 1
return binary_img
def apply_b_thresh(self, img, thresh = (0, 255)):
b_img = img[:,:,2]
binary_img = np.zeros_like(b_img)
binary_img[ (b_img >= thresh[0]) & (b_img <= thresh[1]) ] = 1
return binary_img
def apply_rgb_thresh(self, num_code, rgb_r = None, rgb_g = None, rgb_b = None):
"""
Combine RGB Thresholding binary images based on the red, green and/or
blue thresholds already applied, they set private variables that can be
used in this method. Choose based on number code, which thresholds you'd
combine:
0: R Binary, G Binary
1: R Binary, B binary
2: G Binary, B Binary
3: R Binary, G Binary, B Binary
"""
combined = np.zeros_like(rgb_r)
if num_code == 0:
combined[ (rgb_r == 1) | (rgb_g == 1) ] = 1
elif num_code == 1:
combined[ (rgb_r == 1) & (rgb_b == 1) ] = 1
elif num_code == 2:
combined[ (rgb_g == 1) & (rgb_b == 1) ] = 1
elif num_code == 3:
combined[ ((rgb_r == 1) | (rgb_g == 1)) & (rgb_b == 1) ] = 1
else:
print("Error: Choose a supported code for combined rgb")
# Return binary result from multiple thresholds
return combined
# Thresholding individual HSL Color Channels
def apply_h_thresh(self, img, thresh = (0, 255)):
hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)
h_img = hls[:,:,0]
binary_img = np.zeros_like(h_img)
binary_img[ (h_img >= thresh[0]) & (h_img <= thresh[1]) ] = 1
return binary_img
def apply_l_thresh(self, img, thresh = (0, 255)):
hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)
l_img = hls[:,:,1]
binary_img = np.zeros_like(l_img)
binary_img[ (l_img >= thresh[0]) & (l_img <= thresh[1]) ] = 1
return binary_img
def apply_s_thresh(self, img, thresh = (0, 255)):
hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)
s_img = hls[:,:,2]
binary_img = np.zeros_like(s_img)
binary_img[ (s_img >= thresh[0]) & (s_img <= thresh[1]) ] = 1
return binary_img
# Apply Combined HLS Thresholding
def apply_hls_thresh(self, num_code, hls_h = None, hls_l = None, hls_s = None):
"""
Combine HLS Thresholding binary images based on the hue, lightness
and/or saturation thresholds already applied, they set private
variables that can be used in this method. Choose based on number
code, which thresholds you'd combine:
# 0: H Binary, L Binary
# 1: H Binary, S binary
# 2: L Binary, S Binary
# 3: H Binary, L Binary, S Binary
"""
combined = np.zeros_like(hls_h)
if num_code == 0:
combined[ (hls_h == 1) & (hls_l == 1) ] = 1
elif num_code == 1:
combined[ (hls_h == 1) | (hls_s == 1) ] = 1
elif num_code == 2:
combined[ (hls_l == 1) & (hls_s == 1) ] = 1
elif num_code == 3:
combined[ (hls_h == 1) | ((hls_s == 1) & (hls_l == 1)) ] = 1
else:
print("Error: Choose a supported code for combined hls")
# Return binary result from multiple thresholds
return combined
h_binary = self.apply_h_thresh(img, thresh[0])
l_binary = self.apply_l_thresh(img, thresh[1])
s_binary = self.apply_s_thresh(img, thresh[2])
combined = np.zeros_like(s_binary)
combined[ (h_binary == 1) & (l_binary == 1) & (s_binary == 1) ] = 1
return combined
def save_img(self, dst_path, filename, dst_img):
"""
Save gradient thresholded image using OpenCV
"""
# If filepath doesn't exist, create it
if not os.path.exists(dst_path):
os.makedirs(dst_path)
# Save binary image resulting from gradient thresholding
plt.imsave(dst_path + filename, dst_img, cmap = "gray")
def visualize(self, src_title, undist_img, dst_title, binary_img):
"""
Visualize color thresholded image
"""
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24,9))
f.tight_layout()
ax1.imshow(undist_img, cmap = 'gray')
ax1.set_title(src_title, fontsize=50)
ax2.imshow(binary_img, cmap = 'gray')
ax2.set_title(dst_title, fontsize=50)
plt.subplots_adjust(left=0, right=1, top=0.9, bottom=0.) |
# # Predicting the final grade of a student
#
# The data used is from a Portuguese secondary school. The data includes academic and personal characteristics of the students as well as final grades. The task is to predict the final grade from the student information. (Regression)
#
# ### [Link to dataset](https://archive.ics.uci.edu/ml/datasets/student+performance)
#
# ### Citation:
#
# P. Cortez and A. Silva. Using Data Mining to Predict Secondary School Student Performance. In A. Brito and J. Teixeira Eds., Proceedings of 5th FUture BUsiness TEChnology Conference (FUBUTEC 2008) pp. 5-12, Porto, Portugal, April, 2008, EUROSIS, ISBN 978-9077381-39-7.
# [Web Link](http://www3.dsi.uminho.pt/pcortez/student.pdf)
#
# ### Reference [article](/home/dipamvasani7/Desktop/Ubuntu/jupyter_notebooks/data)
# Taken and modified from Kaggle Competition: Student Grades Prediction
import pandas as pd
from matplotlib import pyplot as plt
import seaborn as sns
import numpy as np
# Standard ML Models for comparison
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import ElasticNet
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import ExtraTreesRegressor
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.svm import SVR
# Splitting data into training/testing
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
# Metrics
from sklearn.metrics import mean_squared_error, mean_absolute_error, median_absolute_error
# Distributions
import scipy
student = pd.read_csv('student-mat.csv')
#
#
# This plot does not tell us much. What we should really plot is the distribution of grade.
#
#
# # Final grade distribution
# In[ ]:
'''b = sns.countplot(student['G3'])
b.axes.set_title('Distribution of Final grade of students', fontsize = 30)
b.set_xlabel('Final Grade', fontsize = 20)
b.set_ylabel('Count', fontsize = 20)
plt.show()'''
# ## Hmmmmm!
#
# Something seems off here. Apart from the high number of students scoring 0, the distribution is normal as expected.
# Maybe the value 0 is used in place of null. Or maybe the students who did not appear for the exam, or were not allowed to sit for the exam due to some reason are marked as 0. We cannot be sure. Let us check the table for null values
# In[ ]:
# student.isnull().any()
# ### None of the variables has null values so maybe grade 0 does not mean null after all
# ## Next let us take a look at the gender variable
# In[ ]:
# male_studs = len(student[student['sex'] == 'M'])
# female_studs = len(student[student['sex'] == 'F'])
# print('Number of male students:',male_studs)
# print('Number of female students:',female_studs)
# ## Checking the distribution of Age along with gender
# In[ ]:
''' b = sns.kdeplot(student['age'], shade=True)
b.axes.set_title('Ages of students', fontsize = 30)
b.set_xlabel('Age', fontsize = 20)
b.set_ylabel('Count', fontsize = 20)
plt.show() '''
# ### Histogram might be more useful to compare different ages
# In[ ]:
''' b = sns.countplot('age',hue='sex', data=student)
b.axes.set_title('Number of students in different age groups',fontsize=30)
b.set_xlabel("Age",fontsize=30)
b.set_ylabel("Count",fontsize=20)
plt.show() '''
# The ages seem to be ranging from 15 - 19. The students above that age may not necessarily be outliers but students with year drops. Also the gender distribution is pretty even.
# ## Does age have anything to do with the final grade?
# In[ ]:
'''b = sns.boxplot(x='age', y='G3', data=student)
b.axes.set_title('Age vs Final', fontsize = 30)
b.set_xlabel('Age', fontsize = 20)
b.set_ylabel('Final Grade', fontsize = 20)
plt.show()'''
# ### Plotting the distribution rather than statistics would help us better understand the data
# In[ ]:
'''b = sns.swarmplot(x='age', y='G3',hue='sex', data=student)
b.axes.set_title('Does age affect final grade?', fontsize = 30)
b.set_xlabel('Age', fontsize = 20)
b.set_ylabel('Final Grade', fontsize = 20)
plt.show()'''
# We see that age 20 has only 3 data points hence the inconsistency in statistics. Otherwise there seems to be no clear relation of age or gender with final grade
# ## Count of students from urban and rural areas
# In[ ]:
'''b = sns.countplot(student['address'])
b.axes.set_title('Urban and rural students', fontsize = 30)
b.set_xlabel('Address', fontsize = 20)
b.set_ylabel('Count', fontsize = 20)
plt.show()'''
# ## Most students are from urban ares, but do urban students perform better than rurual students?
# In[ ]:
# Grade distribution by address
'''sns.kdeplot(student.loc[student['address'] == 'U', 'G3'], label='Urban', shade = True)
sns.kdeplot(student.loc[student['address'] == 'R', 'G3'], label='Rural', shade = True)
plt.title('Do urban students score higher than rural students?', fontsize = 20)
plt.xlabel('Grade', fontsize = 20);
plt.ylabel('Density', fontsize = 20)
plt.show()'''
# The graph shows that on there is not much difference between the scores based on location.
# ## Reason to choose this school
# In[ ]:
'''b = sns.swarmplot(x='reason', y='G3', data=student)
b.axes.set_title('Reason vs Final grade', fontsize = 30)
b.set_xlabel('Reason', fontsize = 20)
b.set_ylabel('Final Grade', fontsize = 20)
plt.show()'''
'''b = sns.swarmplot(x='absences', y='G3', data=student)
b.axes.set_title('Number of Absences vs Final grade', fontsize = 20)
b.set_xlabel('Number of Absences', fontsize = 16)
b.set_ylabel('Final Grade', fontsize = 16)
plt.show()'''
'''b = sns.swarmplot(x='higher', y='G3', data=student)
b.axes.set_title('Desire for Higher Education vs Final grade', fontsize = 20)
b.set_xlabel('Desire for Higher Education', fontsize = 16)
b.set_ylabel('Final Grade', fontsize = 16)
plt.show()'''
'''b = sns.swarmplot(x='studytime', y='G3', data=student)
b.axes.set_title('Study Time vs Final grade', fontsize = 20)
b.set_xlabel('Study Time', fontsize = 16)
b.set_ylabel('Final Grade', fontsize = 16)
plt.show()'''
# ## Other features
#
# It might not be wise to analyse every feature so I will find the features most correlated to the final grade and spend more time on them.
# ## Correlation
#
# Next we find the correlation between various features and the final grade.
#
# ### Note: This correlation is only between numeric values
# In[ ]:
print("NUMERICAL CORRELATION")
print(student.corr()['G3'].sort_values())
print()
# # Encoding categorical variables
#
# A machine learning model cannot deal with categorical variables (except for some models). Therefore we need to find a way to encode them (represent as numbers) before handing them to the model.
#
# ## Label encoding
#
# This method involves assigning one label for each category
#
# | Occupation | Label |
# | ------------- |:-------------:|
# | programmer | 0 |
# | data scientist| 1 |
# | Engineer | 2 |
#
#
#
# The problem with label encoding is that the assignment of integers is random and changes every time we run the function. Also the model might give higher priority to larger labels. Label encoding can be used when we have only 2 unique values.
#
# ## One hot encoding
#
# The problem with label encoding is solved by one hot encoding. It creates a new column for each category and uses only binary values. The downside of one hot encoding is that the number of features can explode if the categorical variables have many categories. To deal with this we can perform PCA (or other dimensionality reduction methods) followed by one hot encoding.
#
# | Occupation | Occupation_prog| Occupation_ds | Occupation_eng |
# | ------------- |:-------------: |:-------------:|:-------------: |
# | programmer | 1 | 0 | 0 |
# | data scientist| 0 | 1 | 0 |
# | Engineer | 0 | 0 | 1 |
# ### Example of one hot encoding
# In[ ]:
# Select only categorical variables
category_df = student.select_dtypes(include=['object'])
# One hot encode the variables
dummy_df = pd.get_dummies(category_df)
# Put the grade back in the dataframe
dummy_df['G3'] = student['G3']
# Find correlations with grade
print("CATEGORICAL CORRELATION")
print(dummy_df.corr()['G3'].sort_values())
print()
# ## Applying one hot encoding to our data and finding correlation again!
#
#
# ### Note:
# Although G1 and G2 which are period grades of a student and are highly correlated to the final grade G3, we drop them. It is more difficult to predict G3 without G2 and G1, but such prediction is much more useful because we want to find other factors affect the grade.
# In[ ]:
# selecting the most correlated values and dropping the others
labels = student['G3']
# drop the school and grade columns
student = student.drop(['school', 'G1', 'G2'], axis='columns')
# One-Hot Encoding of Categorical Variables
student = pd.get_dummies(student)
# In[ ]:
# Find correlations with the Grade
most_correlated = student.corr().abs()['G3'].sort_values(ascending=False)
# Maintain the top 8 most correlation features with Grade
print("FINAL CORRELATION")
most_correlated = most_correlated[:9]
print(most_correlated)
print()
# In[ ]:
student = student.loc[:, most_correlated.index]
print("FINAL DATAFRAME HEAD")
print(student.head())
print()
# # Now we will analyse these variables and then train a model
# ### Student with less previous failures usually score higher
# In[ ]:
'''b = sns.swarmplot(x=student['failures'],y=student['G3'])
b.axes.set_title('Students with less failures score higher', fontsize = 20)
b.set_xlabel('Number of failures', fontsize = 16)
b.set_ylabel('Final Grade', fontsize = 16)
plt.show()
# In[ ]:
family_ed = student['Fedu'] + student['Medu']
b = sns.boxplot(x=family_ed,y=student['G3'])
b.axes.set_title('Educated families result in higher grades', fontsize = 20)
b.set_xlabel('Family education (Mother + Father)', fontsize = 16)
b.set_ylabel('Final Grade', fontsize = 16)
plt.show()
# There seems to be a slight trend that with the increase in family education the grade moves up (apart from the unusual high value at family_ed = 1 (maybe students whose parents did not get to study have more motivation)
#
# ### Note:
#
# I prefer swarm plots over box plots because it is much more useful to see the distribution of data (and also to spot outliers)
# In[ ]:
b = sns.swarmplot(x=family_ed,y=student['G3'])
b.axes.set_title('Educated families result in higher grades', fontsize = 20)
b.set_xlabel('Family education (Mother + Father)', fontsize = 16)
b.set_ylabel('Final Grade', fontsize = 16)
plt.show()
# As we can see there are only 2 points in family_ed = 1 hence our conclusion was faulty.
# ## Higher education
#
# Higher education was a categorical variable with values yes and no. Since we used one hot encoding it has been converted to 2 variables. So we can safely eliminate one of them (since the values are compliments of each other). We will eliminate higher_no, since higher_yes is more intuitive.
# In[ ]:
student = student.drop('higher_no', axis='columns')
student.head()
# In[ ]:
b = sns.boxplot(x = student['higher_yes'], y=student['G3'])
b.axes.set_title('Students who wish to go for higher studies score more', fontsize = 20)
b.set_xlabel('Higher education (1 = Yes)', fontsize = 16)
b.set_ylabel('Final Grade', fontsize = 16)
plt.show()
# ### Going out with friends
# In[ ]:
b = sns.countplot(student['goout'])
b.axes.set_title('How often do students go out with friends', fontsize = 20)
b.set_xlabel('Go out', fontsize = 16)
b.set_ylabel('Count', fontsize = 16)
plt.show()
# Most students have an average score when it comes to going out with friends. (normal distribution)
# In[ ]:
b = sns.swarmplot(x=student['goout'],y=student['G3'])
b.axes.set_title('Students who go out a lot score less', fontsize = 20)
b.set_xlabel('Going out', fontsize = 16)
b.set_ylabel('Final Grade', fontsize = 16)
plt.show()
# The graph shows a slight downward trend
# ## Does having a romantic relationship affect grade?
#
# Again because of one hot encoding we have our variable called romantic_no which is slightly less intuitive but I am going to stick with it. Keep in mind that:
#
# - romantic_no = 1 means NO romantic relationship
# - romantic_no = 0 means romantic relationship
# In[ ]:
b = sns.swarmplot(x=student['romantic_no'],y=student['G3'])
b.axes.set_title('Students with no romantic relationship score higher', fontsize = 20)
b.set_xlabel('Romantic relationship (1 = None)', fontsize = 16)
b.set_ylabel('Final Grade', fontsize = 16)
plt.show()'''
# # Modeling
#
# ### We can create a model in 3 ways
#
# 1. Binary classification
# - G3 > 10: pass
# - G3 < 10: fail
# 2. 5-level classification based on Erasmus grade conversion system
# - 16-20: very good
# - 14-15: good
# - 12-13: satisfactory
# - 10-11: sufficient
# - 0-9 : fail
# 3. Regression (Predicting G3)
#
# ### We will be using the 3rd type
# In[ ]:
# splitting the data into training and testing data (75% and 25%)
# we mention the random state to achieve the same split everytime we run the code
'''X_train, X_test, y_train, y_test = train_test_split(student, labels, test_size = 0.25, random_state=42)
# In[ ]:
X_train.head()
# ### MAE - Mean Absolute Error
# ### RMSE - Root Mean Square Error
# In[ ]:
# Calculate mae and rmse
def evaluate_predictions(predictions, true):
mae = np.mean(abs(predictions - true))
rmse = np.sqrt(np.mean((predictions - true) ** 2))
return mae, rmse
# ### Naive baseline is the median prediction
# In[ ]:
# find the median
median_pred = X_train['G3'].median()
# create a list with all values as median
median_preds = [median_pred for _ in range(len(X_test))]
# store the true G3 values for passing into the function
true = X_test['G3']
# In[ ]:
# Display the naive baseline metrics
mb_mae, mb_rmse = evaluate_predictions(median_preds, true)
print('Median Baseline MAE: {:.4f}'.format(mb_mae))
print('Median Baseline RMSE: {:.4f}'.format(mb_rmse))
# In[ ]:
# Evaluate several ml models by training on training set and testing on testing set
def evaluate(X_train, X_test, y_train, y_test):
# Names of models
model_name_list = ['Linear Regression', 'ElasticNet Regression',
'Random Forest', 'Extra Trees', 'SVM',
'Gradient Boosted', 'Baseline']
X_train = X_train.drop('G3', axis='columns')
X_test = X_test.drop('G3', axis='columns')
# Instantiate the models
model1 = LinearRegression()
model2 = ElasticNet(alpha=1.0, l1_ratio=0.5)
model3 = RandomForestRegressor(n_estimators=100)
model4 = ExtraTreesRegressor(n_estimators=100)
model5 = SVR(kernel='rbf', degree=3, C=1.0, gamma='auto')
model6 = GradientBoostingRegressor(n_estimators=50)
# Dataframe for results
results = pd.DataFrame(columns=['mae', 'rmse'], index = model_name_list)
# Train and predict with each model
for i, model in enumerate([model1, model2, model3, model4, model5, model6]):
model.fit(X_train, y_train)
predictions = model.predict(X_test)
# Metrics
mae = np.mean(abs(predictions - y_test))
rmse = np.sqrt(np.mean((predictions - y_test) ** 2))
# Insert results into the dataframe
model_name = model_name_list[i]
results.loc[model_name, :] = [mae, rmse]
# Median Value Baseline Metrics
baseline = np.median(y_train)
baseline_mae = np.mean(abs(baseline - y_test))
baseline_rmse = np.sqrt(np.mean((baseline - y_test) ** 2))
results.loc['Baseline', :] = [baseline_mae, baseline_rmse]
return results
# In[ ]:
results = evaluate(X_train, X_test, y_train, y_test)
results
# In[ ]:
plt.figure(figsize=(12, 8))
# Root mean squared error
ax = plt.subplot(1, 2, 1)
results.sort_values('mae', ascending = True).plot.bar(y = 'mae', color = 'b', ax = ax, fontsize=20)
plt.title('Model Mean Absolute Error', fontsize=20)
plt.ylabel('MAE', fontsize=20)
# Median absolute percentage error
ax = plt.subplot(1, 2, 2)
results.sort_values('rmse', ascending = True).plot.bar(y = 'rmse', color = 'r', ax = ax, fontsize=20)
plt.title('Model Root Mean Squared Error', fontsize=20)
plt.ylabel('RMSE',fontsize=20)
plt.show()'''
# ### We see that linear regression is performing the best in both cases
# In[ ]:
|
"""
Реализовать базовый класс Worker (работник).
определить атрибуты: name, surname, position (должность), income (доход);
последний атрибут должен быть защищённым и ссылаться на словарь, содержащий элементы: оклад и премия,
например, {"wage": wage, "bonus": bonus};
создать класс Position (должность) на базе класса Worker;
в классе Position реализовать методы получения полного имени сотрудника (get_full_name) и дохода с учётом премии
(get_total_income);
проверить работу примера на реальных данных: создать экземпляры класса Position, передать данные, проверить значения
атрибутов, вызвать методы экземпляров.
"""
class Worker:
def __init__(self, *args, **kwargs):
self.name, self.surname, self.position = args
self._income = kwargs
class Position(Worker):
def get_full_name(self):
return f'{self.name} {self.surname}'
def get_total_income(self):
return f'{sum([self._income["wage"], self._income["bonus"]]):0,} руб.'.replace(",", " ")
def get_position(self):
return self.position
info = Position(
input('Имя: '),
input('Фамилия: '),
input('Должность: '),
wage=int(input('Зарплата: ')),
bonus=int(input('Премия: '))
)
print(info.get_position(), info.get_full_name(), info.get_total_income())
|
class node:
def __init__(self,data):
self.data = data
self.next_pointer = None
def get_data(self,data):
return self.data
def set_data(self,new_data):
self.data = new_data
def get_next_pointer(self):
return self.next_pointer
def set_next_pointer(self,data):
temp = node(data)
self.next_pointer = temp
class Unorded_list:
def __init__(self):
self.head = None
def is_empty(self):
return self.head == None
def add(self,data):
temp = node(data)
self.head = temp
def get_list(self):
pass
def length(self):
pass
def remove(self):
pass
class Ordered_list(Unorded_list):
def __init__(self):
super().__init__()
def add():
pass
def search():
pass
|
def range_function(num):
i = 0
while i < num:
yield i
i = i+1
gen_num = range_function(20)
# printing the output of custom range function
for i in range(20):
print gen_num.next()
|
from random import randint
def run_guess(guess, answer):
if 0 < guess < 11:
# Check if no. is right guess otherwise ask again.
if guess == answer:
print("You are Genius!")
return True
else:
print("you lost!")
else:
print("Hey dumbo! I said 1 to 10!")
# Generate a no. 1 to 10
if __name__ == '__main__':
answer = randint(1, 10)
# Take input from user!
# Check that if input is a no. b/w 1 to 10
while True:
try:
# print(answer) # Uncomment for cheating.
guess = int(input("Guess a b/w 1 to 10: "))
if run_guess(guess, answer):
break
except ValueError:
print("Please enter a number!")
|
# First we are gonna install virtual environment here in web_server folder.
# By typing python -m venv venv
# Now we are gonna activate virtual environment by typing venv/Scripts/activate
# Now, we finally install Flask, by typing pip install Flask.
from flask import Flask, render_template # This render_template is used to send HTML files.
app = Flask(__name__)
@app.route("/") # This / means we are on homepage.
def hello_world():
return "<p>Hello, My name is John Cena! YOU CAN'T SEE ME...</p>"
# Upper code copied from Flask documentation.
@app.route("/blog") # This /blog means blog page
def blog():
return "<p>These are my thoughts on Blogs...</p>"
@app.route("/blog/2021/dog") # This /blog means blog page
def blog2():
return "<p>This is my Dog!!!!!!!!!!!!</p>"
# To use an HTML file, REMEMBER, put your html files in a folder called templates, bc flask automatically,
# looks for a folder named templates, for HTML files.
@app.route("/html") # This /blog means blog page
def html():
return render_template('index.html')
# Now to add css and JavaScript files to our html, we have to create a static named folder and
# move them to static folder. Static means those files aren't gonna change.
# To add fevicons (choti si photu jo uprr tabs me aati hai.)
# Visit icon-icons.com (for fevicons)
# Put a link for fevicon in HTML, REMEMBER fevicon image must be in static folder.
# URL parameters
# Flask has a feature called url parameters, in which we pass something in url which is pasted in
# our website.
@app.route("/<username>/<int:post_id>")
def variables(username=None, post_id=None):
return render_template('index.html', name=username, post_id=post_id) # we have to type this, name
# and post_id in HTML in 2 curly brackets as well, as we are calling from HTML here,
# Username is for string or name, and post id is int So, it is for any number.
# We have to type (export FLASK_APP=server.py), name should be same as of our python file.
# Then with typing (flask run) in command line our server starts.
# Initially the debugging mode is off, it means if we make any change in our website, it won't be
# Initiated even after refreshing the page, unless we run the server again by typing flask run.
# So, to turn on debugging mode we have to type (export FLASK_ENV=development) in command line.
|
# Find Duplicates (Exercise) Using Comprehension.
# Check for duplicates in list and print them in a list.
some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']
duplicates = []
for value in some_list:
if some_list.count(value) > 1:
if value not in duplicates: # This is imp. to not print b and n twice in output.
duplicates.append(value)
print(duplicates)
# Now we have to do this using list comprehension.
duplicates1 = list(set([x for x in some_list if some_list.count(x) > 1 ])) # So, I can understand the inside code,
# but it will give the repeteted value so to prevent it we use function set then it removes duplicate value, and
# after that we again change it into a list, bc we want a list in final output.
print(duplicates1) |
# Logical Operators (Exercise)
is_magician = True
is_expert = False
# Check if magician and expert
if is_magician and is_expert:
print("You are a master magician")
# Check if magician but not expert
elif is_magician and not is_expert:
print("At least you are getting there...")
# Check if you are not a magician
elif not is_magician:
print("You need magic powers") |
ammount=int(input("enter the cash ammount:"))
print("number of 500 notes are:",ammount//500)
ammount=ammount%500
print("number of 200 notes are:",ammount//200)
ammount= ammount%200
print("number of 100 notes are:",ammount//100)
ammount= ammount%100
print("number of 50 notes are:", ammount//50)
ammount=ammount%50
print("number of 20 notes are: ", ammount//20)
print("number of 10 notes are:",ammount%20)
|
def check_nice(line):
vowels = "aeiou"
vowelCounter = 0
hasDouble = False
blacklist = ["ab", "cd", "pq", "xy"]
for b in blacklist:
if b in line:
return False
for i, c in enumerate(line):
if i < len(line) - 1 and c == line[i+1]:
hasDouble = True
if c in vowels:
vowelCounter += 1
return vowelCounter >= 3 and hasDouble
with open("input.txt", 'r') as f:
counter = 0
for line in f:
line = line.rstrip()
if check_nice(line):
counter += 1
print(counter) |
"""Assume you have a method isSubstring which checks if one words is a substring of another.
Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only one call to isSubstring (e.g. "waterbottle" is a rotation of "erbottlewat")"""
# TODO: come back and actually use isSubstring in the solution (misunderstood the question on the first attempt)
def string_rotation(s1, s2):
for i in range(len(s1)):
if s2 == s1[len(s1)-i - 1:] + s1[: len(s1)-i -1]:
return True
return False
assert string_rotation("waterbottle", "erbottlewat") |
def check_seat(lines, i, j):
if lines[i][j] == "L":
if i > 0:
if lines[i-1][j] == "#":
return False
if j > 0 and lines[i-1][j-1] == "#":
return False
if j < len(lines[i]) - 1 and lines[i-1][j+1] == "#":
return False
if i < len(lines) - 1:
if lines[i+1][j] == "#":
return False
if j > 0 and lines[i+1][j-1] == "#":
return False
if j < len(lines[i]) - 1 and lines[i+1][j+1] == "#":
return False
if j > 0 and lines[i][j-1] == "#":
return False
if j < len(lines[i]) - 1 and lines[i][j+1] == "#":
return False
return True
# so it's occupied
occupiedCount = 0
if i > 0:
if lines[i-1][j] == "#":
occupiedCount += 1
if j > 0 and lines[i-1][j-1] == "#":
occupiedCount += 1
if j < len(lines[i]) - 1 and lines[i-1][j+1] == "#":
occupiedCount += 1
if i < len(lines) - 1:
if lines[i+1][j] == "#":
occupiedCount += 1
if j > 0 and lines[i+1][j-1] == "#":
occupiedCount += 1
if j < len(lines[i]) - 1 and lines[i+1][j+1] == "#":
occupiedCount += 1
if j > 0 and lines[i][j-1] == "#":
occupiedCount += 1
if j < len(lines[i]) - 1 and lines[i][j+1] == "#":
occupiedCount += 1
return not occupiedCount >= 4:
def print_board(lines):
for line in copy:
print(line)
print()
def check_diff(copy, copy2):
for i, line in enumerate(copy):
for j, c in enumerate(line):
if c != "." and copy2[i][j] != c:
return True
return False
def count_occupied_seats(lines):
counter = 0
for line in lines:
for c in line:
if c == "#":
counter += 1
return counter
with open("input.txt", 'r') as f:
lines = [x.rstrip() for x in f.readlines()]
copy = []
copy2 = []
for line in lines:
copy.append([c for c in line])
copy2.append([c for c in line])
while True:
for i, line in enumerate(copy):
for j, c in enumerate(line):
if c != ".":
copy2[i][j] = "#" if check_seat(copy, i, j) else "L"
# print_board(copy2)
if not check_diff(copy, copy2):
print(count_occupied_seats(copy))
exit(0)
copy = []
for line in copy2:
copy.append([c for c in line]) |
def check_memo(lines, memo):
memoKey = "".join(str(x) for x in lines)
if memoKey in memo:
return memo[memoKey]
else:
result = find_arrangements(lines, memo)
memo[memoKey] = result
return result
def find_arrangements(lines, memo):
if len(lines) == 1:
return 1
if len(lines) == 0:
return 1
count1, count2, count3 = 0,0,0
count1 = check_memo(lines[1:], memo)
if len(lines) > 2 and lines[2] - lines[0] <= 3:
count2 = check_memo(lines[2:], memo)
if len(lines) > 3 and lines[3] - lines[0] <= 3:
count3 = check_memo(lines[3:], memo)
return count1 + count2 + count3
with open("input.txt", 'r') as f:
lines = [int(x.rstrip()) for x in f.readlines()]
lines.sort()
device = max(lines) + 3
lines = [0] + lines + [device]
print(find_arrangements(lines, {})) |
"""Write an algorithm such that if an element in an MxN matrix is 0, the entire row and column are set to 0"""
def zero_matrix(m):
zcols = set()
zrows = set()
for i, row in enumerate(m):
for j, cell in enumerate(row):
if cell == 0:
zrows.add(i)
zcols.add(j)
for i, row in enumerate(m):
for j, cell in enumerate(row):
if i in zrows or j in zcols:
m[i][j] = 0
m = [[1,0,1], [0,1,1], [1,1,1]]
expected = [[0,0,0], [0,0,0], [0,0,1]]
zero_matrix(m)
print(m)
|
""" An implementation of merge sort in Python """
def merge_sort(l):
length = len(l)
if length == 1 or length == 0:
return l
mid = int(length/2)
left = merge_sort(l[:mid])
right = merge_sort(l[mid:])
return merge(left, right)
def merge(l1, l2):
merged_list = []
while len(l1) > 0 and len(l2) > 0:
if l1[0] <= l2[0]:
merged_list.append(l1.pop(0))
else:
merged_list.append(l2.pop(0))
return merged_list + l1 + l2
print(merge_sort([5,3,8,7,1,2,-1])) |
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
'''
@题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
@解题思路
很简单,用栈遍历结点就好啦。
下面的解法用了两个栈的原因在于要求每一层输出一行,那么用一个栈来表示当前层,一个栈用来存下一层的结点,当前层遍历完就使下一层等于当前层,循环上述过程,直到下一层没有新的结点入栈。
'''
class Solution:
# 返回二维列表[[1,2],[4,5]]
def Print(self, pRoot):
# write code here
if pRoot == None:
return []
s = [pRoot]
result_all = []
while s != []:
s1 = []
result = []
while 1:
now = s.pop(0)
result.append(now.val)
if now.left != None:
s1.append(now.left)
if now.right != None:
s1.append(now.right)
if s == []:
s = s1
break
result_all.append(result)
return result_all |
# -*- coding:utf-8 -*-
'''
@题目描述
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
@解题思路
看了讨论区各种插入排序什么的,搞了半天时间复杂度也就是O(n)甚至更高,不如直接遍历一下不好吗?
尝试过快排的思想一个从左找偶数一个从右找奇数互换,但是这题的要求需要相对位置不变,因此也不合适,还是遍历吧。
开两个list,一个放奇数一个放偶数,最后合并,简单有效。
'''
class Solution:
def reOrderArray(self, array):
i = 0
res_odd = []
res_even = []
while i < len(array):
if array[i] % 2 == 1: #奇数
res_odd.append(array[i])
else: #偶数
res_even.append(array[i])
i += 1
res_odd.extend(res_even)
return res_odd |
# -*- coding:utf-8 -*-
'''
@题目描述
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
@解题思路
后序遍历:左节点 右节点 父节点
结合后序遍历和二叉搜索树的特点,数组最后一个数为根节点,比根节点小的都是左子树,比根节点的的是右子树。因此,判断是否是后序遍历的结果,就是判断能否根据root结点的值将数组分为小于root和大于root的两部分,可递归求解。
'''
class Solution:
def isBST(self, sequence):
# 递归结束的条件,只剩一个结点或0个结点
if len(sequence) == 0 or len(sequence) == 1:
return True
# 根节点的值
root = sequence[-1]
i = 0
# 小于根节点的值,获取index,即sequence[:index]都小于root,即为左子树
while root > sequence[i]:
i += 1
index = i
# 左子树之外的就是右子树,sequence[index:],理论上右子树的值都要比root大,否则返回False
for i in sequence[index:]:
if root > i:
return False
# 递归判断左右子树是否满足条件
return self.isBST(sequence[:index]) and self.isBST(sequence[index:-1])
def VerifySquenceOfBST(self, sequence):
# write code here
if len(sequence) == 0:
return False
if len(sequence) == 1:
return True
return self.isBST(sequence)
|
# -*- coding:utf-8 -*-
'''
@题目描述
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
保证base和exponent不同时为0
'''
import math
class Solution:
def Power(self, base, exponent):
# write code here
#return base**exponent #用python可一行解决
if base == 0:
return 0
if exponent == 0:
return 1
pro = 1
for i in range(abs(exponent)):
pro *= base
if exponent > 0:
return pro
else:
return float(1/pro)
|
# abc = [1, 2, 3, 6, 5, 4]
#
# for number in abc:
# print('Hi ' + str(number) + '!')
# for i in range(1, 6):
# print(i)
i = 0
while i < 5:
print(i)
i += 1 |
def palindromo(palabra):
palabra= palabra.replace(" ", "")
palabra=palabra.lower()
palabra_in= palabra[::-1]
if palabra==palabra_in:
return True
else:
return False
def run():
palabra=input("Escribe una palabra: ")
es_palindromo= palindromo(palabra)
if es_palindromo==True:
print("Es palindromo")
else:
print("No es palindormo")
if __name__ == '__main__':
run() |
def mensaje():
#Def sirve para no repetir una serie de pasos varias veces
print("Imprime este mensaje")
print("Para que se repita 3 veces")
mensaje()
mensaje()
mensaje()
#Parametros
#Ejemplo largo sin pasos comunes
opcion=input("Elige una opción (1,2,3) ")
if opcion=="1":
print("Hola")
print("¿Cómo estás?")
print("Espero que te encuentres bien")
print("Elegiste opción 1")
elif opcion=="2":
print("Hola")
print("¿Cómo estás?")
print("Espero que te encuentres bien")
print("Elegiste opción 2")
elif opcion=="3":
print("Hola")
print("¿Cómo estás?")
print("Espero que te encuentres bien")
print("Elegiste opción 3")
else:
print("Elige una opción válida")
#Ejemplo largo con pasos comunes
def texto(mensaje):
print("Hola")
print("¿Cómo estás?")
print("Espero que te encuentres bien")
print(mensaje)
opcion=str(input("Elija un número del 1 al 3 "))
if opcion=="1":
texto("Elegiste la opción 1")
elif opcion=="2":
texto("Elegiste la opción 2")
elif opcion=="3":
texto("Elegiste la opción 3")
else:
print("Elija una opción válida")
def suma(a,b): #Creé una variable que se llama suma y le asigne dos variables
print("Se suman dos números") #Imprimí lo que hará dicha acción
resultado= a+b #Creé otra variable la cuál ejecutará el proceso de la primera
return resultado #Con esto devolví el valor que no está impreso
sumatoria= suma(1,4) #Asigné los valores que se suman
print(sumatoria) #Imprimí el resultado
|
def two_sum(nums: [int], target: int):
for (index, n) in enumerate(nums):
for (second_index, m) in enumerate(nums):
if index == second_index:
continue
if n + m == target:
return [index, second_index]
if __name__ == '__main__':
print(two_sum([1, 3, 5], 8))
|
def is_palindrome(s: str) -> bool:
chars = [c for c in s.lower() if 97 <= ord(c) <= 122 or 48 <= ord(c) <= 57]
if len(chars) == 1:
return True
for i, c in enumerate(chars[::-1]):
if c != chars[i]:
return False
return True
if __name__ == '__main__':
print(is_palindrome("A man, a plan, a canal: Panama"))
|
def validBookObject(bookObject):
#if "keyName" in dictionaryObject
if ("name" in bookObject
and "price" in bookObject
and "isbn" in bookObject):
return True
else:
return False
valid_object = {
'name' : 'sample',
'price' : 4.5,
'isbn' : 963
}
missing_name = {
'price' : 4.5,
'isbn' : 963
}
missing_price = {
'name' : 'sample',
'isbn' : 963
}
missing_isbn = {
'name' : 'sample',
'price' : 4.5
}
empty_dictionary = {} |
# Take for input a credit card number
# Determine the provider
# Perform Luhn's algorithm to verify legimity
from sys import exit
import cs50
def main():
# Init
providers = {
1: "VISA",
2: "MASTERCARD",
3: "AMEX"
}
# Prompt credit card number
while True:
credit_card = cs50.get_float("Number: ")
if credit_card > 0:
break
# float -> int -> str -> list
card = str(int(credit_card))
card_arr = []
for i in range(len(card)):
card_arr.append(int(card[i]))
# Perform provider recognition
provider = get_provider(card_arr)
if not provider:
print("INVALID")
exit(0)
# Perform Luhn's algorithm and return provider or error
legitimacy = luhn(card_arr)
if legitimacy:
print(providers[provider])
exit(0)
print("INVALID")
exit(1)
# Verify length and first digits to determine provider
def get_provider(arr):
# Init providers' constant properties
VISALEN1 = 13
VISA_MC_LEN2 = 16
VISADIG = 4
MCDIG1 = 51
MCDIG2 = 55
AMEXLEN = 15
AMEXDIG1 = 34
AMEXDIG2 = 37
first_two = arr[0] * 10 + arr[1]
# Visa check
if len(arr) == VISALEN1 or len(arr) == VISA_MC_LEN2:
if arr[0] == VISADIG:
return 1
# Mastercard check
if len(arr) == VISA_MC_LEN2:
if first_two >= MCDIG1 and first_two <= MCDIG2:
return 2
# American Express check
if len(arr) == AMEXLEN:
if first_two == AMEXDIG1 or first_two == AMEXDIG2:
return 3
return 0
# Multiply every other digit by 2, starting with the number’s second-to-last digit
# And then add those products’ digits together.
# Add the sum to the sum of the digits that weren’t multiplied by 2.
# If the total’s last digit is 0 (if the total modulo 10 is congruent to 0)
# The credit card is valid
def luhn(arr):
# Init
BASE = 10
i = len(arr) - 2
j = len(arr) - 1
luhnValue = 0
# First iteration from i
while i >= 0:
if (arr[i] * 2) >= BASE:
luhnValue += arr[i] * 2 // BASE
luhnValue += (arr[i] * 2) % BASE
i -= 2
# Second iteration from j
while j >= 0:
luhnValue += arr[j]
j -= 2
# Return legitimacy
if not luhnValue % 10:
return True
return False
main() |
number = int(input("Please insert positive number"))
i1 = 1
i2 = 1
i3 = 2
hold = 0
while(i2 < number):
hold = i1
i1 = i2
i2 = hold + i1
i3 += i2
print(i3)
|
lst = [4, 2, 59, 32]
mx=lst[0]
index_max=0
mn=lst[0]
index_min=0
for i in range(len(lst)):
if mx < lst[i]:
mx = lst[i]
index_max=i
elif mn > lst[i]:
mn = lst[i]
index_min=i
print("max member is: ",mx, index_max)
print("min member is: ", mn, index_min) |
def fibonaci(n):
if n==0:
return 0
elif n == 1:
return 1
return fibonaci(n-1) + fibonaci(n-2)
print(fibonaci(2)) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# from __future__ import print_function
from functools import wraps
from math import log
from random import randint, seed
from time import perf_counter
import matplotlib.pyplot as plt
def BubbleSort(array):
# array に対し破壊的
for i in range(len(array) - 1):
for j in reversed(range(i, len(array) - 1)):
if array[j] > array[j + 1]:
array[j], array[j + 1] = array[j + 1], array[j]
return array
def QuickSort(array, start=0, end=None): # array[start:end]でありarray[end]は含まない
# array に対し破壊的
end = len(array) if end is None else end
if end - start == 1:
return array
assert 0 <= start, "start={}が不適切です".format(start)
assert start < end - 1, "start={}, end={}が不適切です".format(start, end)
assert end - 1 < len(array), "end={}が不適切です".format(end)
pivot = find_pivot(array, start, end)
if pivot is None:
return array
partision_index = partition(array, pivot, start, end)
# listをと分けて後で結合させると,分ける際新しくlistが作られメモリを消費するので,使わない
QuickSort(array, start, partision_index)
QuickSort(array, partision_index, end)
return array
def find_pivot(array, start=0, end=None):
# array に対し破壊的
end = len(array) if end is None else end
assert 0 <= start, "start={}が不適切です".format(start)
assert start < end - 1, "start={}, end={}が不適切です".format(start, end)
assert end - 1 < len(array), "end={}が不適切です".format(end)
first = array[start]
for i in range(start + 1, end): # sliceを使い array[1:] とすると,新しくlistが作られメモリを消費するので,使わない
if first != array[i]:
return first if first > array[i] else array[i]
return None
def partition(array, pivot, start=0, end=None):
# arrayに対し破壊的
end = len(array) if end is None else end
assert 0 <= start, "start={}が不適切です".format(start)
assert start < end - 1, "start={}, end={}が不適切です".format(start, end)
assert end - 1 < len(array), "end={}が不適切です".format(end)
left_index, right_index = start, end - 1
while True:
while array[left_index] < pivot:
left_index += 1
while array[right_index] >= pivot:
right_index -= 1
if left_index > right_index:
return left_index
array[left_index], array[right_index] = array[right_index], array[left_index]
def MergeSort(array):
# array に対し非破壊的
if len(array) == 1:
return array
left = MergeSort(array[:len(array)//2])
right = MergeSort(array[len(array)//2:])
return merge(left, right)
def merge(left, right):
integration = []
left_index, right_index = 0, 0
left_length, right_length = len(left), len(right)
while True:
if left_index == left_length:
integration.extend(right[right_index:])
break
elif right_index == right_length:
integration.extend(left[left_index:])
break
if left[left_index] < right[right_index]:
integration.append(left[left_index])
left_index += 1
else:
integration.append(right[right_index])
right_index += 1
return integration
def time(func):
@wraps(func)
def wrapper(array):
start = perf_counter()
result = func(array)
end = perf_counter()
assert sorted(array) == result, "{}では正しくsortできていません".format(func.__name__)
return end - start
return wrapper
def main():
seed(0)
roop_num = 10
ns = [100, 500, 1000]
sorts = {
"BubbleSort": BubbleSort,
"QuickSort": QuickSort,
"MergeSort": MergeSort
}
result = {
"cum_time": {name: [] for name in sorts},
"time": {name: [] for name in sorts},
"by_complexity": {name: [] for name in sorts}
}
for n in ns:
for cum_time in result["cum_time"].values():
cum_time.append(0)
for _ in range(roop_num):
array = [randint(0, n) for _ in range(n)] # randint(a, b) は a <= n <= b を満たす乱数を生成する
for name, sort_func in sorts.items():
result["cum_time"][name][-1] += time(sort_func)(array[:])
for name, cum_time in result["cum_time"].items():
result["time"][name].append(cum_time[-1] / roop_num)
result["by_complexity"]["BubbleSort"].append(result["time"]["BubbleSort"][-1] / (n ** 2))
result["by_complexity"]["QuickSort"].append(result["time"]["QuickSort"][-1] / (n * log(n)))
result["by_complexity"]["MergeSort"].append(result["time"]["MergeSort"][-1] / (n * log(n)))
print("\nn={}".format(n))
print("BubbleSort: {:.3e}[ms], {:.3e}[/n^2]".format(
result["time"]["BubbleSort"][-1], result["by_complexity"]["BubbleSort"][-1]))
print("QuickSort: {:.3e}[ms], {:.3e}[/(n*logn)]".format(
result["time"]["QuickSort"][-1], result["by_complexity"]["QuickSort"][-1]))
print("MergeSort: {:.3e}[ms], {:.3e}[/(n*logn)]".format(
result["time"]["MergeSort"][-1], result["by_complexity"]["MergeSort"][-1]))
# width = 1/(len(result["by_complexity"])+1)
# plt.bar([i + width*0 for i in range(len(ns))], result["by_complexity"]["BubbleSort"],
# color='r', width=width, label='BubbleSort', align="center")
# plt.bar([i + width*1 for i in range(len(ns))], result["by_complexity"]["QuickSort"],
# color='g', width=width, label='QuickSort', align="center")
# plt.bar([i + width*2 for i in range(len(ns))], result["by_complexity"]["MergeSort"],
# color='b', width=width, label='MergeSort', align="center")
# plt.legend()
# plt.xticks([i+width*(len(result["by_complexity"])-1)/2 for i in range(len(ns))], ns)
# plt.show()
if __name__ == "__main__":
# python -O main.py のように -O オプションをつけて実行するとassert文が無視されます
main()
|
'''
for i in range(A):
if A[:i] is palindrome,
then recursive call A[i:] -> list of lists
for each list in lists:
add A[:i] and make a new list of lists
'''
def palindrome(s):
if not s:
return False
if s == s[::-1]:
return True
class Solution:
# @param A : string
# @return a list of list of strings
def partition(self, A):
if not A:
return [[]]
partitions = []
for i in range(1, len(A)+1):
if palindrome(A[:i]):
sub_partitions = self.partition(A[i:])
for sub_partition in sub_partitions:
partitions.append([A[:i]] + sub_partition)
return partitions
|
class Solution:
# @param A : string
# @return a strings
def simplifyPath(self, A):
stack = []
for path in A.split('/'):
if path == '.' or path == '':
continue
elif path == '..':
if stack:
stack.pop()
else:
stack.append(path)
return '/' + '/'.join(stack)
|
class Solution:
# @param A : string
# @return an integer
def lengthOfLastWord(self, A):
last_word_len = 0
current_word_len = 0
for char in A:
if char == ' ':
if current_word_len != 0:
last_word_len = current_word_len
current_word_len = 0
else:
current_word_len += 1
#As last word wont have any space at the end
if current_word_len != 0:
last_word_len = current_word_len
return last_word_len
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.