Wrap lines that go beyond GitHub Editor (#1925)

* Wrap lines that go beyond GiHub Editor

* flake8 --count --select=E501 --max-line-length=127

* updating DIRECTORY.md

* Update strassen_matrix_multiplication.py

* fixup! Format Python code with psf/black push

* Update decision_tree.py

Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
This commit is contained in:
Christian Clauss 2020-05-01 23:36:35 +02:00 committed by GitHub
parent bcaa88b26c
commit 6acd7fb5ce
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
19 changed files with 161 additions and 82 deletions

View File

@ -7,7 +7,7 @@ before_install: pip install --upgrade pip setuptools six
install: pip install -r requirements.txt install: pip install -r requirements.txt
before_script: before_script:
- black --check . || true - black --check . || true
- flake8 . --count --select=E101,E722,E9,F4,F63,F7,F82,W191 --show-source --statistics - flake8 . --count --select=E101,E501,E722,E9,F4,F63,F7,F82,W191 --max-line-length=127 --show-source --statistics
- flake8 . --count --exit-zero --max-line-length=127 --statistics - flake8 . --count --exit-zero --max-line-length=127 --statistics
script: script:
- scripts/validate_filenames.py # no uppercase, no spaces, in a directory - scripts/validate_filenames.py # no uppercase, no spaces, in a directory

View File

@ -14,6 +14,7 @@
* [All Combinations](https://github.com/TheAlgorithms/Python/blob/master/backtracking/all_combinations.py) * [All Combinations](https://github.com/TheAlgorithms/Python/blob/master/backtracking/all_combinations.py)
* [All Permutations](https://github.com/TheAlgorithms/Python/blob/master/backtracking/all_permutations.py) * [All Permutations](https://github.com/TheAlgorithms/Python/blob/master/backtracking/all_permutations.py)
* [All Subsequences](https://github.com/TheAlgorithms/Python/blob/master/backtracking/all_subsequences.py) * [All Subsequences](https://github.com/TheAlgorithms/Python/blob/master/backtracking/all_subsequences.py)
* [Coloring](https://github.com/TheAlgorithms/Python/blob/master/backtracking/coloring.py)
* [Minimax](https://github.com/TheAlgorithms/Python/blob/master/backtracking/minimax.py) * [Minimax](https://github.com/TheAlgorithms/Python/blob/master/backtracking/minimax.py)
* [N Queens](https://github.com/TheAlgorithms/Python/blob/master/backtracking/n_queens.py) * [N Queens](https://github.com/TheAlgorithms/Python/blob/master/backtracking/n_queens.py)
* [Sudoku](https://github.com/TheAlgorithms/Python/blob/master/backtracking/sudoku.py) * [Sudoku](https://github.com/TheAlgorithms/Python/blob/master/backtracking/sudoku.py)
@ -31,6 +32,7 @@
* [One Dimensional](https://github.com/TheAlgorithms/Python/blob/master/cellular_automata/one_dimensional.py) * [One Dimensional](https://github.com/TheAlgorithms/Python/blob/master/cellular_automata/one_dimensional.py)
## Ciphers ## Ciphers
* [A1Z26](https://github.com/TheAlgorithms/Python/blob/master/ciphers/a1z26.py)
* [Affine Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/affine_cipher.py) * [Affine Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/affine_cipher.py)
* [Atbash](https://github.com/TheAlgorithms/Python/blob/master/ciphers/atbash.py) * [Atbash](https://github.com/TheAlgorithms/Python/blob/master/ciphers/atbash.py)
* [Base16](https://github.com/TheAlgorithms/Python/blob/master/ciphers/base16.py) * [Base16](https://github.com/TheAlgorithms/Python/blob/master/ciphers/base16.py)
@ -138,6 +140,8 @@
## Digital Image Processing ## Digital Image Processing
* [Change Contrast](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/change_contrast.py) * [Change Contrast](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/change_contrast.py)
* [Convert To Negative](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/convert_to_negative.py) * [Convert To Negative](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/convert_to_negative.py)
* Dithering
* [Burkes](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/dithering/burkes.py)
* Edge Detection * Edge Detection
* [Canny](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/edge_detection/canny.py) * [Canny](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/edge_detection/canny.py)
* Filters * Filters

View File

@ -1,4 +1,7 @@
import sys, rsa_key_generator as rkg, os import os
import sys
import rsa_key_generator as rkg
DEFAULT_BLOCK_SIZE = 128 DEFAULT_BLOCK_SIZE = 128
BYTE_SIZE = 256 BYTE_SIZE = 256
@ -92,7 +95,9 @@ def encryptAndWriteToFile(
keySize, n, e = readKeyFile(keyFilename) keySize, n, e = readKeyFile(keyFilename)
if keySize < blockSize * 8: if keySize < blockSize * 8:
sys.exit( sys.exit(
"ERROR: Block size is %s bits and key size is %s bits. The RSA cipher requires the block size to be equal to or greater than the key size. Either decrease the block size or use different keys." "ERROR: Block size is %s bits and key size is %s bits. The RSA cipher "
"requires the block size to be equal to or greater than the key size. "
"Either decrease the block size or use different keys."
% (blockSize * 8, keySize) % (blockSize * 8, keySize)
) )
@ -117,7 +122,9 @@ def readFromFileAndDecrypt(messageFilename, keyFilename):
if keySize < blockSize * 8: if keySize < blockSize * 8:
sys.exit( sys.exit(
"ERROR: Block size is %s bits and key size is %s bits. The RSA cipher requires the block size to be equal to or greater than the key size. Did you specify the correct key file and encrypted file?" "ERROR: Block size is %s bits and key size is %s bits. The RSA cipher "
"requires the block size to be equal to or greater than the key size. "
"Did you specify the correct key file and encrypted file?"
% (blockSize * 8, keySize) % (blockSize * 8, keySize)
) )

View File

@ -1,5 +1,9 @@
import random, sys, os import os
import rabin_miller as rabinMiller, cryptomath_module as cryptoMath import random
import sys
import cryptomath_module as cryptoMath
import rabin_miller as rabinMiller
def main(): def main():
@ -35,7 +39,8 @@ def makeKeyFiles(name, keySize):
): ):
print("\nWARNING:") print("\nWARNING:")
print( print(
'"%s_pubkey.txt" or "%s_privkey.txt" already exists. \nUse a different name or delete these files and re-run this program.' '"%s_pubkey.txt" or "%s_privkey.txt" already exists. \n'
"Use a different name or delete these files and re-run this program."
% (name, name) % (name, name)
) )
sys.exit() sys.exit()

View File

@ -1,9 +1,12 @@
""" """
- A linked list is similar to an array, it holds values. However, links in a linked list do not have indexes. - A linked list is similar to an array, it holds values. However, links in a linked
list do not have indexes.
- This is an example of a double ended, doubly linked list. - This is an example of a double ended, doubly linked list.
- Each link references the next link and the previous one. - Each link references the next link and the previous one.
- A Doubly Linked List (DLL) contains an extra pointer, typically called previous pointer, together with next pointer and data which are there in singly linked list. - A Doubly Linked List (DLL) contains an extra pointer, typically called previous
- Advantages over SLL - IT can be traversed in both forward and backward direction.,Delete operation is more efficient""" pointer, together with next pointer and data which are there in singly linked list.
- Advantages over SLL - IT can be traversed in both forward and backward direction.,
Delete operation is more efficient"""
class LinkedList: # making main class named linked list class LinkedList: # making main class named linked list
@ -13,7 +16,7 @@ class LinkedList: # making main class named linked list
def insertHead(self, x): def insertHead(self, x):
newLink = Link(x) # Create a new link with a value attached to it newLink = Link(x) # Create a new link with a value attached to it
if self.isEmpty() == True: # Set the first element added to be the tail if self.isEmpty(): # Set the first element added to be the tail
self.tail = newLink self.tail = newLink
else: else:
self.head.previous = newLink # newLink <-- currenthead(head) self.head.previous = newLink # newLink <-- currenthead(head)
@ -23,7 +26,9 @@ class LinkedList: # making main class named linked list
def deleteHead(self): def deleteHead(self):
temp = self.head temp = self.head
self.head = self.head.next # oldHead <--> 2ndElement(head) self.head = self.head.next # oldHead <--> 2ndElement(head)
self.head.previous = None # oldHead --> 2ndElement(head) nothing pointing at it so the old head will be removed # oldHead --> 2ndElement(head) nothing pointing at it so the old head will be
# removed
self.head.previous = None
if self.head is None: if self.head is None:
self.tail = None # if empty linked list self.tail = None # if empty linked list
return temp return temp

View File

@ -31,12 +31,19 @@ def matrix_subtraction(matrix_a: List, matrix_b: List):
def split_matrix(a: List,) -> Tuple[List, List, List, List]: def split_matrix(a: List,) -> Tuple[List, List, List, List]:
""" """
Given an even length matrix, returns the top_left, top_right, bot_left, bot_right quadrant. Given an even length matrix, returns the top_left, top_right, bot_left, bot_right
quadrant.
>>> split_matrix([[4,3,2,4],[2,3,1,1],[6,5,4,3],[8,4,1,6]]) >>> split_matrix([[4,3,2,4],[2,3,1,1],[6,5,4,3],[8,4,1,6]])
([[4, 3], [2, 3]], [[2, 4], [1, 1]], [[6, 5], [8, 4]], [[4, 3], [1, 6]]) ([[4, 3], [2, 3]], [[2, 4], [1, 1]], [[6, 5], [8, 4]], [[4, 3], [1, 6]])
>>> split_matrix([[4,3,2,4,4,3,2,4],[2,3,1,1,2,3,1,1],[6,5,4,3,6,5,4,3],[8,4,1,6,8,4,1,6],[4,3,2,4,4,3,2,4],[2,3,1,1,2,3,1,1],[6,5,4,3,6,5,4,3],[8,4,1,6,8,4,1,6]]) >>> split_matrix([
([[4, 3, 2, 4], [2, 3, 1, 1], [6, 5, 4, 3], [8, 4, 1, 6]], [[4, 3, 2, 4], [2, 3, 1, 1], [6, 5, 4, 3], [8, 4, 1, 6]], [[4, 3, 2, 4], [2, 3, 1, 1], [6, 5, 4, 3], [8, 4, 1, 6]], [[4, 3, 2, 4], [2, 3, 1, 1], [6, 5, 4, 3], [8, 4, 1, 6]]) ... [4,3,2,4,4,3,2,4],[2,3,1,1,2,3,1,1],[6,5,4,3,6,5,4,3],[8,4,1,6,8,4,1,6],
... [4,3,2,4,4,3,2,4],[2,3,1,1,2,3,1,1],[6,5,4,3,6,5,4,3],[8,4,1,6,8,4,1,6]
... ]) # doctest: +NORMALIZE_WHITESPACE
([[4, 3, 2, 4], [2, 3, 1, 1], [6, 5, 4, 3], [8, 4, 1, 6]], [[4, 3, 2, 4],
[2, 3, 1, 1], [6, 5, 4, 3], [8, 4, 1, 6]], [[4, 3, 2, 4], [2, 3, 1, 1],
[6, 5, 4, 3], [8, 4, 1, 6]], [[4, 3, 2, 4], [2, 3, 1, 1], [6, 5, 4, 3],
[8, 4, 1, 6]])
""" """
if len(a) % 2 != 0 or len(a[0]) % 2 != 0: if len(a) % 2 != 0 or len(a[0]) % 2 != 0:
raise Exception("Odd matrices are not supported!") raise Exception("Odd matrices are not supported!")
@ -66,8 +73,8 @@ def print_matrix(matrix: List) -> None:
def actual_strassen(matrix_a: List, matrix_b: List) -> List: def actual_strassen(matrix_a: List, matrix_b: List) -> List:
""" """
Recursive function to calculate the product of two matrices, using the Strassen Algorithm. Recursive function to calculate the product of two matrices, using the Strassen
It only supports even length matrices. Algorithm. It only supports even length matrices.
""" """
if matrix_dimensions(matrix_a) == (2, 2): if matrix_dimensions(matrix_a) == (2, 2):
return default_matrix_multiplication(matrix_a, matrix_b) return default_matrix_multiplication(matrix_a, matrix_b)
@ -106,7 +113,8 @@ def strassen(matrix1: List, matrix2: List) -> List:
""" """
if matrix_dimensions(matrix1)[1] != matrix_dimensions(matrix2)[0]: if matrix_dimensions(matrix1)[1] != matrix_dimensions(matrix2)[0]:
raise Exception( raise Exception(
f"Unable to multiply these matrices, please check the dimensions. \nMatrix A:{matrix1} \nMatrix B:{matrix2}" f"Unable to multiply these matrices, please check the dimensions. \n"
f"Matrix A:{matrix1} \nMatrix B:{matrix2}"
) )
dimension1 = matrix_dimensions(matrix1) dimension1 = matrix_dimensions(matrix1)
dimension2 = matrix_dimensions(matrix2) dimension2 = matrix_dimensions(matrix2)
@ -119,7 +127,8 @@ def strassen(matrix1: List, matrix2: List) -> List:
new_matrix1 = matrix1 new_matrix1 = matrix1
new_matrix2 = matrix2 new_matrix2 = matrix2
# Adding zeros to the matrices so that the arrays dimensions are the same and also power of 2 # Adding zeros to the matrices so that the arrays dimensions are the same and also
# power of 2
for i in range(0, maxim): for i in range(0, maxim):
if i < dimension1[0]: if i < dimension1[0]:
for j in range(dimension1[1], maxim): for j in range(dimension1[1], maxim):

View File

@ -4,10 +4,9 @@ This is a Python implementation for questions involving task assignments between
Here Bitmasking and DP are used for solving this. Here Bitmasking and DP are used for solving this.
Question :- Question :-
We have N tasks and M people. Each person in M can do only certain of these tasks. Also a person can do only one task and a task is performed only by one person. We have N tasks and M people. Each person in M can do only certain of these tasks. Also
a person can do only one task and a task is performed only by one person.
Find the total no of ways in which the tasks can be distributed. Find the total no of ways in which the tasks can be distributed.
""" """
from collections import defaultdict from collections import defaultdict
@ -25,7 +24,8 @@ class AssignmentUsingBitmask:
self.task = defaultdict(list) # stores the list of persons for each task self.task = defaultdict(list) # stores the list of persons for each task
# final_mask is used to check if all persons are included by setting all bits to 1 # final_mask is used to check if all persons are included by setting all bits
# to 1
self.final_mask = (1 << len(task_performed)) - 1 self.final_mask = (1 << len(task_performed)) - 1
def CountWaysUtil(self, mask, task_no): def CountWaysUtil(self, mask, task_no):
@ -45,7 +45,8 @@ class AssignmentUsingBitmask:
# Number of ways when we don't this task in the arrangement # Number of ways when we don't this task in the arrangement
total_ways_util = self.CountWaysUtil(mask, task_no + 1) total_ways_util = self.CountWaysUtil(mask, task_no + 1)
# now assign the tasks one by one to all possible persons and recursively assign for the remaining tasks. # now assign the tasks one by one to all possible persons and recursively
# assign for the remaining tasks.
if task_no in self.task: if task_no in self.task:
for p in self.task[task_no]: for p in self.task[task_no]:
@ -53,7 +54,8 @@ class AssignmentUsingBitmask:
if mask & (1 << p): if mask & (1 << p):
continue continue
# assign this task to p and change the mask value. And recursively assign tasks with the new mask value. # assign this task to p and change the mask value. And recursively
# assign tasks with the new mask value.
total_ways_util += self.CountWaysUtil(mask | (1 << p), task_no + 1) total_ways_util += self.CountWaysUtil(mask | (1 << p), task_no + 1)
# save the value. # save the value.
@ -85,6 +87,7 @@ if __name__ == "__main__":
) )
""" """
For the particular example the tasks can be distributed as For the particular example the tasks can be distributed as
(1,2,3), (1,2,4), (1,5,3), (1,5,4), (3,1,4), (3,2,4), (3,5,4), (4,1,3), (4,2,3), (4,5,3) (1,2,3), (1,2,4), (1,5,3), (1,5,4), (3,1,4),
(3,2,4), (3,5,4), (4,1,3), (4,2,3), (4,5,3)
total 10 total 10
""" """

View File

@ -2,10 +2,12 @@
Author : Turfa Auliarachman Author : Turfa Auliarachman
Date : October 12, 2016 Date : October 12, 2016
This is a pure Python implementation of Dynamic Programming solution to the edit distance problem. This is a pure Python implementation of Dynamic Programming solution to the edit
distance problem.
The problem is : The problem is :
Given two strings A and B. Find the minimum number of operations to string B such that A = B. The permitted operations are removal, insertion, and substitution. Given two strings A and B. Find the minimum number of operations to string B such that
A = B. The permitted operations are removal, insertion, and substitution.
""" """

View File

@ -20,15 +20,21 @@ class Decision_Tree:
mean_squared_error: mean_squared_error:
@param labels: a one dimensional numpy array @param labels: a one dimensional numpy array
@param prediction: a floating point value @param prediction: a floating point value
return value: mean_squared_error calculates the error if prediction is used to estimate the labels return value: mean_squared_error calculates the error if prediction is used to
estimate the labels
>>> tester = Decision_Tree() >>> tester = Decision_Tree()
>>> test_labels = np.array([1,2,3,4,5,6,7,8,9,10]) >>> test_labels = np.array([1,2,3,4,5,6,7,8,9,10])
>>> test_prediction = np.float(6) >>> test_prediction = np.float(6)
>>> assert tester.mean_squared_error(test_labels, test_prediction) == Test_Decision_Tree.helper_mean_squared_error_test(test_labels, test_prediction) >>> tester.mean_squared_error(test_labels, test_prediction) == (
... Test_Decision_Tree.helper_mean_squared_error_test(test_labels,
... test_prediction))
True
>>> test_labels = np.array([1,2,3]) >>> test_labels = np.array([1,2,3])
>>> test_prediction = np.float(2) >>> test_prediction = np.float(2)
>>> assert tester.mean_squared_error(test_labels, test_prediction) == Test_Decision_Tree.helper_mean_squared_error_test(test_labels, test_prediction) >>> tester.mean_squared_error(test_labels, test_prediction) == (
... Test_Decision_Tree.helper_mean_squared_error_test(test_labels,
... test_prediction))
True
""" """
if labels.ndim != 1: if labels.ndim != 1:
print("Error: Input labels must be one dimensional") print("Error: Input labels must be one dimensional")
@ -46,7 +52,8 @@ class Decision_Tree:
""" """
""" """
this section is to check that the inputs conform to our dimensionality constraints this section is to check that the inputs conform to our dimensionality
constraints
""" """
if X.ndim != 1: if X.ndim != 1:
print("Error: Input data set must be one dimensional") print("Error: Input data set must be one dimensional")
@ -72,7 +79,8 @@ class Decision_Tree:
""" """
loop over all possible splits for the decision tree. find the best split. loop over all possible splits for the decision tree. find the best split.
if no split exists that is less than 2 * error for the entire array if no split exists that is less than 2 * error for the entire array
then the data set is not split and the average for the entire array is used as the predictor then the data set is not split and the average for the entire array is used as
the predictor
""" """
for i in range(len(X)): for i in range(len(X)):
if len(X[:i]) < self.min_leaf_size: if len(X[:i]) < self.min_leaf_size:
@ -147,9 +155,10 @@ class Test_Decision_Tree:
def main(): def main():
""" """
In this demonstration we're generating a sample data set from the sin function in numpy. In this demonstration we're generating a sample data set from the sin function in
We then train a decision tree on the data set and use the decision tree to predict the numpy. We then train a decision tree on the data set and use the decision tree to
label of 10 different test values. Then the mean squared error over this test is displayed. predict the label of 10 different test values. Then the mean squared error over
this test is displayed.
""" """
X = np.arange(-1.0, 1.0, 0.005) X = np.arange(-1.0, 1.0, 0.005)
y = np.sin(X) y = np.sin(X)

View File

@ -1,6 +1,6 @@
#!/usr/bin/python #!/usr/bin/python
## Logistic Regression from scratch # Logistic Regression from scratch
# In[62]: # In[62]:
@ -8,8 +8,12 @@
# importing all the required libraries # importing all the required libraries
""" Implementing logistic regression for classification problem """
Helpful resources : 1.Coursera ML course 2.https://medium.com/@martinpella/logistic-regression-from-scratch-in-python-124c5636b8ac""" Implementing logistic regression for classification problem
Helpful resources:
Coursera ML course
https://medium.com/@martinpella/logistic-regression-from-scratch-in-python-124c5636b8ac
"""
import numpy as np import numpy as np
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
@ -21,7 +25,8 @@ from sklearn import datasets
# In[67]: # In[67]:
# sigmoid function or logistic function is used as a hypothesis function in classification problems # sigmoid function or logistic function is used as a hypothesis function in
# classification problems
def sigmoid_function(z): def sigmoid_function(z):

View File

@ -3,6 +3,7 @@ from sklearn import svm
from sklearn.model_selection import train_test_split from sklearn.model_selection import train_test_split
import doctest import doctest
# different functions implementing different types of SVM's # different functions implementing different types of SVM's
def NuSVC(train_x, train_y): def NuSVC(train_x, train_y):
svc_NuSVC = svm.NuSVC() svc_NuSVC = svm.NuSVC()
@ -17,8 +18,11 @@ def Linearsvc(train_x, train_y):
def SVC(train_x, train_y): def SVC(train_x, train_y):
# svm.SVC(C=1.0, kernel='rbf', degree=3, gamma=0.0, coef0=0.0, shrinking=True, probability=False,tol=0.001, cache_size=200, class_weight=None, verbose=False, max_iter=-1, random_state=None) # svm.SVC(C=1.0, kernel='rbf', degree=3, gamma=0.0, coef0=0.0, shrinking=True,
# various parameters like "kernel","gamma","C" can effectively tuned for a given machine learning model. # probability=False,tol=0.001, cache_size=200, class_weight=None, verbose=False,
# max_iter=-1, random_state=None)
# various parameters like "kernel","gamma","C" can effectively tuned for a given
# machine learning model.
SVC = svm.SVC(gamma="auto") SVC = svm.SVC(gamma="auto")
SVC.fit(train_x, train_y) SVC.fit(train_x, train_y)
return SVC return SVC
@ -27,8 +31,8 @@ def SVC(train_x, train_y):
def test(X_new): def test(X_new):
""" """
3 test cases to be passed 3 test cases to be passed
an array containing the sepal length (cm), sepal width (cm),petal length (cm),petal width (cm) an array containing the sepal length (cm), sepal width (cm), petal length (cm),
based on which the target name will be predicted petal width (cm) based on which the target name will be predicted
>>> test([1,2,1,4]) >>> test([1,2,1,4])
'virginica' 'virginica'
>>> test([5, 2, 4, 1]) >>> test([5, 2, 4, 1])

View File

@ -23,9 +23,11 @@ class Point:
def estimate_pi(number_of_simulations: int) -> float: def estimate_pi(number_of_simulations: int) -> float:
""" """
Generates an estimate of the mathematical constant PI (see https://en.wikipedia.org/wiki/Monte_Carlo_method#Overview). Generates an estimate of the mathematical constant PI.
See https://en.wikipedia.org/wiki/Monte_Carlo_method#Overview
The estimate is generated by Monte Carlo simulations. Let U be uniformly drawn from the unit square [0, 1) x [0, 1). The probability that U lies in the unit circle is: The estimate is generated by Monte Carlo simulations. Let U be uniformly drawn from
the unit square [0, 1) x [0, 1). The probability that U lies in the unit circle is:
P[U in unit circle] = 1/4 PI P[U in unit circle] = 1/4 PI
@ -33,10 +35,12 @@ def estimate_pi(number_of_simulations: int) -> float:
PI = 4 * P[U in unit circle] PI = 4 * P[U in unit circle]
We can get an estimate of the probability P[U in unit circle] (see https://en.wikipedia.org/wiki/Empirical_probability) by: We can get an estimate of the probability P[U in unit circle].
See https://en.wikipedia.org/wiki/Empirical_probability by:
1. Draw a point uniformly from the unit square. 1. Draw a point uniformly from the unit square.
2. Repeat the first step n times and count the number of points in the unit circle, which is called m. 2. Repeat the first step n times and count the number of points in the unit
circle, which is called m.
3. An estimate of P[U in unit circle] is m/n 3. An estimate of P[U in unit circle] is m/n
""" """
if number_of_simulations < 1: if number_of_simulations < 1:

View File

@ -147,7 +147,10 @@ if __name__ == "__main__":
doctest.testmod() doctest.testmod()
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
description="Find out what day of the week nearly any date is or was. Enter date as a string in the mm-dd-yyyy or mm/dd/yyyy format" description=(
"Find out what day of the week nearly any date is or was. Enter "
"date as a string in the mm-dd-yyyy or mm/dd/yyyy format"
)
) )
parser.add_argument( parser.add_argument(
"date_input", type=str, help="Date as a string (mm-dd-yyyy or mm/dd/yyyy)" "date_input", type=str, help="Date as a string (mm-dd-yyyy or mm/dd/yyyy)"

View File

@ -3,7 +3,8 @@
class Matrix: class Matrix:
""" """
Matrix object generated from a 2D array where each element is an array representing a row. Matrix object generated from a 2D array where each element is an array representing
a row.
Rows can contain type int or float. Rows can contain type int or float.
Common operations and information available. Common operations and information available.
>>> rows = [ >>> rows = [
@ -33,7 +34,8 @@ class Matrix:
>>> matrix.is_invertable() >>> matrix.is_invertable()
False False
Identity, Minors, Cofactors and Adjugate are returned as Matrices. Inverse can be a Matrix or Nonetype Identity, Minors, Cofactors and Adjugate are returned as Matrices. Inverse can be
a Matrix or Nonetype
>>> print(matrix.identity()) >>> print(matrix.identity())
[[1. 0. 0.] [[1. 0. 0.]
[0. 1. 0.] [0. 1. 0.]
@ -46,7 +48,8 @@ class Matrix:
[[-3. 6. -3.] [[-3. 6. -3.]
[6. -12. 6.] [6. -12. 6.]
[-3. 6. -3.]] [-3. 6. -3.]]
>>> print(matrix.adjugate()) # won't be apparent due to the nature of the cofactor matrix >>> # won't be apparent due to the nature of the cofactor matrix
>>> print(matrix.adjugate())
[[-3. 6. -3.] [[-3. 6. -3.]
[6. -12. 6.] [6. -12. 6.]
[-3. 6. -3.]] [-3. 6. -3.]]
@ -57,7 +60,8 @@ class Matrix:
>>> matrix.determinant() >>> matrix.determinant()
0 0
Negation, scalar multiplication, addition, subtraction, multiplication and exponentiation are available and all return a Matrix Negation, scalar multiplication, addition, subtraction, multiplication and
exponentiation are available and all return a Matrix
>>> print(-matrix) >>> print(-matrix)
[[-1. -2. -3.] [[-1. -2. -3.]
[-4. -5. -6.] [-4. -5. -6.]
@ -102,8 +106,9 @@ class Matrix:
def __init__(self, rows): def __init__(self, rows):
error = TypeError( error = TypeError(
"Matrices must be formed from a list of zero or more lists containing at least " "Matrices must be formed from a list of zero or more lists containing at "
"one and the same number of values, each of which must be of type int or float." "least one and the same number of values, each of which must be of type "
"int or float."
) )
if len(rows) != 0: if len(rows) != 0:
cols = len(rows[0]) cols = len(rows[0])
@ -159,10 +164,8 @@ class Matrix:
) )
else: else:
return sum( return sum(
[ self.rows[0][column] * self.cofactors().rows[0][column]
self.rows[0][column] * self.cofactors().rows[0][column] for column in range(self.num_columns)
for column in range(self.num_columns)
]
) )
def is_invertable(self): def is_invertable(self):
@ -346,7 +349,7 @@ class Matrix:
@classmethod @classmethod
def dot_product(cls, row, column): def dot_product(cls, row, column):
return sum([row[i] * column[i] for i in range(len(row))]) return sum(row[i] * column[i] for i in range(len(row)))
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -30,7 +30,8 @@ def alternative_password_generator(ctbi, i):
i = i - len(ctbi) i = i - len(ctbi)
quotient = int(i / 3) quotient = int(i / 3)
remainder = i % 3 remainder = i % 3
# chars = ctbi + random_letters(ascii_letters, i / 3 + remainder) + random_number(digits, i / 3) + random_characters(punctuation, i / 3) # chars = ctbi + random_letters(ascii_letters, i / 3 + remainder) +
# random_number(digits, i / 3) + random_characters(punctuation, i / 3)
chars = ( chars = (
ctbi ctbi
+ random(ascii_letters, quotient + remainder) + random(ascii_letters, quotient + remainder)

View File

@ -5,11 +5,14 @@
Simple example of Fractal generation using recursive function. Simple example of Fractal generation using recursive function.
What is Sierpinski Triangle? What is Sierpinski Triangle?
>>The Sierpinski triangle (also with the original orthography Sierpinski), also called the Sierpinski gasket or the Sierpinski Sieve, >>The Sierpinski triangle (also with the original orthography Sierpinski), also called
is a fractal and attractive fixed set with the overall shape of an equilateral triangle, subdivided recursively into smaller the Sierpinski gasket or the Sierpinski Sieve, is a fractal and attractive fixed set
equilateral triangles. Originally constructed as a curve, this is one of the basic examples of self-similar sets, i.e., with the overall shape of an equilateral triangle, subdivided recursively into smaller
it is a mathematically generated pattern that can be reproducible at any magnification or reduction. It is named after equilateral triangles. Originally constructed as a curve, this is one of the basic
the Polish mathematician Wacław Sierpinski, but appeared as a decorative pattern many centuries prior to the work of Sierpinski. examples of self-similar sets, i.e., it is a mathematically generated pattern that can
be reproducible at any magnification or reduction. It is named after the Polish
mathematician Wacław Sierpinski, but appeared as a decorative pattern many centuries
prior to the work of Sierpinski.
Requirements(pip): Requirements(pip):
- turtle - turtle
@ -20,7 +23,8 @@ Python:
Usage: Usage:
- $python sierpinski_triangle.py <int:depth_for_fractal> - $python sierpinski_triangle.py <int:depth_for_fractal>
Credits: This code was written by editing the code from http://www.riannetrujillo.com/blog/python-fractal/ Credits: This code was written by editing the code from
http://www.riannetrujillo.com/blog/python-fractal/
""" """
import turtle import turtle

View File

@ -1,11 +1,14 @@
""" """
Problem: Problem:
Comparing two numbers written in index form like 2'11 and 3'7 is not difficult, as any calculator would confirm that 2^11 = 2048 < 3^7 = 2187. Comparing two numbers written in index form like 2'11 and 3'7 is not difficult, as any
calculator would confirm that 2^11 = 2048 < 3^7 = 2187.
However, confirming that 632382^518061 > 519432^525806 would be much more difficult, as both numbers contain over three million digits. However, confirming that 632382^518061 > 519432^525806 would be much more difficult, as
both numbers contain over three million digits.
Using base_exp.txt, a 22K text file containing one thousand lines with a base/exponent pair on each line, determine which line number has the greatest numerical value. Using base_exp.txt, a 22K text file containing one thousand lines with a base/exponent
pair on each line, determine which line number has the greatest numerical value.
NOTE: The first two lines in the file represent the numbers in the example given above. NOTE: The first two lines in the file represent the numbers in the example given above.
""" """

View File

@ -14,15 +14,18 @@ import bisect
def bisect_left(sorted_collection, item, lo=0, hi=None): def bisect_left(sorted_collection, item, lo=0, hi=None):
""" """
Locates the first element in a sorted array that is larger or equal to a given value. Locates the first element in a sorted array that is larger or equal to a given
value.
It has the same interface as https://docs.python.org/3/library/bisect.html#bisect.bisect_left . It has the same interface as
https://docs.python.org/3/library/bisect.html#bisect.bisect_left .
:param sorted_collection: some ascending sorted collection with comparable items :param sorted_collection: some ascending sorted collection with comparable items
:param item: item to bisect :param item: item to bisect
:param lo: lowest index to consider (as in sorted_collection[lo:hi]) :param lo: lowest index to consider (as in sorted_collection[lo:hi])
:param hi: past the highest index to consider (as in sorted_collection[lo:hi]) :param hi: past the highest index to consider (as in sorted_collection[lo:hi])
:return: index i such that all values in sorted_collection[lo:i] are < item and all values in sorted_collection[i:hi] are >= item. :return: index i such that all values in sorted_collection[lo:i] are < item and all
values in sorted_collection[i:hi] are >= item.
Examples: Examples:
>>> bisect_left([0, 5, 7, 10, 15], 0) >>> bisect_left([0, 5, 7, 10, 15], 0)
@ -57,13 +60,15 @@ def bisect_right(sorted_collection, item, lo=0, hi=None):
""" """
Locates the first element in a sorted array that is larger than a given value. Locates the first element in a sorted array that is larger than a given value.
It has the same interface as https://docs.python.org/3/library/bisect.html#bisect.bisect_right . It has the same interface as
https://docs.python.org/3/library/bisect.html#bisect.bisect_right .
:param sorted_collection: some ascending sorted collection with comparable items :param sorted_collection: some ascending sorted collection with comparable items
:param item: item to bisect :param item: item to bisect
:param lo: lowest index to consider (as in sorted_collection[lo:hi]) :param lo: lowest index to consider (as in sorted_collection[lo:hi])
:param hi: past the highest index to consider (as in sorted_collection[lo:hi]) :param hi: past the highest index to consider (as in sorted_collection[lo:hi])
:return: index i such that all values in sorted_collection[lo:i] are <= item and all values in sorted_collection[i:hi] are > item. :return: index i such that all values in sorted_collection[lo:i] are <= item and
all values in sorted_collection[i:hi] are > item.
Examples: Examples:
>>> bisect_right([0, 5, 7, 10, 15], 0) >>> bisect_right([0, 5, 7, 10, 15], 0)
@ -98,7 +103,8 @@ def insort_left(sorted_collection, item, lo=0, hi=None):
""" """
Inserts a given value into a sorted array before other values with the same value. Inserts a given value into a sorted array before other values with the same value.
It has the same interface as https://docs.python.org/3/library/bisect.html#bisect.insort_left . It has the same interface as
https://docs.python.org/3/library/bisect.html#bisect.insort_left .
:param sorted_collection: some ascending sorted collection with comparable items :param sorted_collection: some ascending sorted collection with comparable items
:param item: item to insert :param item: item to insert
@ -138,7 +144,8 @@ def insort_right(sorted_collection, item, lo=0, hi=None):
""" """
Inserts a given value into a sorted array after other values with the same value. Inserts a given value into a sorted array after other values with the same value.
It has the same interface as https://docs.python.org/3/library/bisect.html#bisect.insort_right . It has the same interface as
https://docs.python.org/3/library/bisect.html#bisect.insort_right .
:param sorted_collection: some ascending sorted collection with comparable items :param sorted_collection: some ascending sorted collection with comparable items
:param item: item to insert :param item: item to insert

View File

@ -14,5 +14,6 @@ def send_slack_message(message_body: str, slack_url: str) -> None:
if __name__ == "main": if __name__ == "main":
# Set the slack url to the one provided by Slack when you create the webhook at https://my.slack.com/services/new/incoming-webhook/ # Set the slack url to the one provided by Slack when you create the webhook at
# https://my.slack.com/services/new/incoming-webhook/
send_slack_message("<YOUR MESSAGE BODY>", "<SLACK CHANNEL URL>") send_slack_message("<YOUR MESSAGE BODY>", "<SLACK CHANNEL URL>")