mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-23 21:11:08 +00:00
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:
parent
bcaa88b26c
commit
6acd7fb5ce
|
@ -7,7 +7,7 @@ before_install: pip install --upgrade pip setuptools six
|
|||
install: pip install -r requirements.txt
|
||||
before_script:
|
||||
- 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
|
||||
script:
|
||||
- scripts/validate_filenames.py # no uppercase, no spaces, in a directory
|
||||
|
|
|
@ -14,6 +14,7 @@
|
|||
* [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 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)
|
||||
* [N Queens](https://github.com/TheAlgorithms/Python/blob/master/backtracking/n_queens.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)
|
||||
|
||||
## 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)
|
||||
* [Atbash](https://github.com/TheAlgorithms/Python/blob/master/ciphers/atbash.py)
|
||||
* [Base16](https://github.com/TheAlgorithms/Python/blob/master/ciphers/base16.py)
|
||||
|
@ -138,6 +140,8 @@
|
|||
## Digital Image Processing
|
||||
* [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)
|
||||
* Dithering
|
||||
* [Burkes](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/dithering/burkes.py)
|
||||
* Edge Detection
|
||||
* [Canny](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/edge_detection/canny.py)
|
||||
* Filters
|
||||
|
|
|
@ -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
|
||||
BYTE_SIZE = 256
|
||||
|
@ -92,7 +95,9 @@ def encryptAndWriteToFile(
|
|||
keySize, n, e = readKeyFile(keyFilename)
|
||||
if keySize < blockSize * 8:
|
||||
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)
|
||||
)
|
||||
|
||||
|
@ -117,7 +122,9 @@ def readFromFileAndDecrypt(messageFilename, keyFilename):
|
|||
|
||||
if keySize < blockSize * 8:
|
||||
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)
|
||||
)
|
||||
|
||||
|
|
|
@ -1,5 +1,9 @@
|
|||
import random, sys, os
|
||||
import rabin_miller as rabinMiller, cryptomath_module as cryptoMath
|
||||
import os
|
||||
import random
|
||||
import sys
|
||||
|
||||
import cryptomath_module as cryptoMath
|
||||
import rabin_miller as rabinMiller
|
||||
|
||||
|
||||
def main():
|
||||
|
@ -35,7 +39,8 @@ def makeKeyFiles(name, keySize):
|
|||
):
|
||||
print("\nWARNING:")
|
||||
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)
|
||||
)
|
||||
sys.exit()
|
||||
|
|
|
@ -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.
|
||||
- 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.
|
||||
- Advantages over SLL - IT can be traversed in both forward and backward direction.,Delete operation is more efficient"""
|
||||
- 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.
|
||||
- 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
|
||||
|
@ -13,7 +16,7 @@ class LinkedList: # making main class named linked list
|
|||
|
||||
def insertHead(self, x):
|
||||
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
|
||||
else:
|
||||
self.head.previous = newLink # newLink <-- currenthead(head)
|
||||
|
@ -23,7 +26,9 @@ class LinkedList: # making main class named linked list
|
|||
def deleteHead(self):
|
||||
temp = self.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:
|
||||
self.tail = None # if empty linked list
|
||||
return temp
|
||||
|
|
|
@ -31,12 +31,19 @@ def matrix_subtraction(matrix_a: List, matrix_b: 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]])
|
||||
([[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]])
|
||||
([[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]])
|
||||
>>> 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]
|
||||
... ]) # 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:
|
||||
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:
|
||||
"""
|
||||
Recursive function to calculate the product of two matrices, using the Strassen Algorithm.
|
||||
It only supports even length matrices.
|
||||
Recursive function to calculate the product of two matrices, using the Strassen
|
||||
Algorithm. It only supports even length matrices.
|
||||
"""
|
||||
if matrix_dimensions(matrix_a) == (2, 2):
|
||||
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]:
|
||||
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)
|
||||
dimension2 = matrix_dimensions(matrix2)
|
||||
|
@ -119,7 +127,8 @@ def strassen(matrix1: List, matrix2: List) -> List:
|
|||
new_matrix1 = matrix1
|
||||
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):
|
||||
if i < dimension1[0]:
|
||||
for j in range(dimension1[1], maxim):
|
||||
|
|
|
@ -4,10 +4,9 @@ This is a Python implementation for questions involving task assignments between
|
|||
Here Bitmasking and DP are used for solving this.
|
||||
|
||||
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.
|
||||
|
||||
|
||||
"""
|
||||
from collections import defaultdict
|
||||
|
||||
|
@ -25,7 +24,8 @@ class AssignmentUsingBitmask:
|
|||
|
||||
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
|
||||
|
||||
def CountWaysUtil(self, mask, task_no):
|
||||
|
@ -45,7 +45,8 @@ class AssignmentUsingBitmask:
|
|||
# Number of ways when we don't this task in the arrangement
|
||||
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:
|
||||
for p in self.task[task_no]:
|
||||
|
||||
|
@ -53,7 +54,8 @@ class AssignmentUsingBitmask:
|
|||
if mask & (1 << p):
|
||||
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)
|
||||
|
||||
# save the value.
|
||||
|
@ -85,6 +87,7 @@ if __name__ == "__main__":
|
|||
)
|
||||
"""
|
||||
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
|
||||
"""
|
||||
|
|
|
@ -2,10 +2,12 @@
|
|||
Author : Turfa Auliarachman
|
||||
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 :
|
||||
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.
|
||||
"""
|
||||
|
||||
|
||||
|
|
|
@ -20,15 +20,21 @@ class Decision_Tree:
|
|||
mean_squared_error:
|
||||
@param labels: a one dimensional numpy array
|
||||
@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()
|
||||
>>> test_labels = np.array([1,2,3,4,5,6,7,8,9,10])
|
||||
>>> 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_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:
|
||||
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:
|
||||
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.
|
||||
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)):
|
||||
if len(X[:i]) < self.min_leaf_size:
|
||||
|
@ -136,7 +144,7 @@ class Test_Decision_Tree:
|
|||
helper_mean_squared_error_test:
|
||||
@param labels: a one dimensional numpy array
|
||||
@param prediction: a floating point value
|
||||
return value: helper_mean_squared_error_test calculates the mean squared error
|
||||
return value: helper_mean_squared_error_test calculates the mean squared error
|
||||
"""
|
||||
squared_error_sum = np.float(0)
|
||||
for label in labels:
|
||||
|
@ -147,9 +155,10 @@ class Test_Decision_Tree:
|
|||
|
||||
def main():
|
||||
"""
|
||||
In this demonstration we're generating a sample data set from the sin function in numpy.
|
||||
We then train a decision tree on the data set and use the decision tree to predict the
|
||||
label of 10 different test values. Then the mean squared error over this test is displayed.
|
||||
In this demonstration we're generating a sample data set from the sin function in
|
||||
numpy. We then train a decision tree on the data set and use the decision tree to
|
||||
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)
|
||||
y = np.sin(X)
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
#!/usr/bin/python
|
||||
|
||||
## Logistic Regression from scratch
|
||||
# Logistic Regression from scratch
|
||||
|
||||
# In[62]:
|
||||
|
||||
|
@ -8,8 +8,12 @@
|
|||
|
||||
# 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 matplotlib.pyplot as plt
|
||||
|
@ -21,7 +25,8 @@ from sklearn import datasets
|
|||
|
||||
# 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):
|
||||
|
|
|
@ -3,6 +3,7 @@ from sklearn import svm
|
|||
from sklearn.model_selection import train_test_split
|
||||
import doctest
|
||||
|
||||
|
||||
# different functions implementing different types of SVM's
|
||||
def NuSVC(train_x, train_y):
|
||||
svc_NuSVC = svm.NuSVC()
|
||||
|
@ -17,8 +18,11 @@ def Linearsvc(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)
|
||||
# various parameters like "kernel","gamma","C" can effectively tuned for a given machine learning model.
|
||||
# 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)
|
||||
# various parameters like "kernel","gamma","C" can effectively tuned for a given
|
||||
# machine learning model.
|
||||
SVC = svm.SVC(gamma="auto")
|
||||
SVC.fit(train_x, train_y)
|
||||
return SVC
|
||||
|
@ -27,8 +31,8 @@ def SVC(train_x, train_y):
|
|||
def test(X_new):
|
||||
"""
|
||||
3 test cases to be passed
|
||||
an array containing the sepal length (cm), sepal width (cm),petal length (cm),petal width (cm)
|
||||
based on which the target name will be predicted
|
||||
an array containing the sepal length (cm), sepal width (cm), petal length (cm),
|
||||
petal width (cm) based on which the target name will be predicted
|
||||
>>> test([1,2,1,4])
|
||||
'virginica'
|
||||
>>> test([5, 2, 4, 1])
|
||||
|
|
|
@ -23,9 +23,11 @@ class Point:
|
|||
|
||||
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
|
||||
|
||||
|
@ -33,10 +35,12 @@ def estimate_pi(number_of_simulations: int) -> float:
|
|||
|
||||
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.
|
||||
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
|
||||
"""
|
||||
if number_of_simulations < 1:
|
||||
|
|
|
@ -147,7 +147,10 @@ if __name__ == "__main__":
|
|||
|
||||
doctest.testmod()
|
||||
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(
|
||||
"date_input", type=str, help="Date as a string (mm-dd-yyyy or mm/dd/yyyy)"
|
||||
|
|
|
@ -3,7 +3,8 @@
|
|||
|
||||
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.
|
||||
Common operations and information available.
|
||||
>>> rows = [
|
||||
|
@ -16,13 +17,13 @@ class Matrix:
|
|||
[[1. 2. 3.]
|
||||
[4. 5. 6.]
|
||||
[7. 8. 9.]]
|
||||
|
||||
|
||||
Matrix rows and columns are available as 2D arrays
|
||||
>>> print(matrix.rows)
|
||||
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
|
||||
>>> print(matrix.columns())
|
||||
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
|
||||
|
||||
|
||||
Order is returned as a tuple
|
||||
>>> matrix.order
|
||||
(3, 3)
|
||||
|
@ -33,7 +34,8 @@ class Matrix:
|
|||
>>> matrix.is_invertable()
|
||||
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())
|
||||
[[1. 0. 0.]
|
||||
[0. 1. 0.]
|
||||
|
@ -46,7 +48,8 @@ class Matrix:
|
|||
[[-3. 6. -3.]
|
||||
[6. -12. 6.]
|
||||
[-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.]
|
||||
[6. -12. 6.]
|
||||
[-3. 6. -3.]]
|
||||
|
@ -57,7 +60,8 @@ class Matrix:
|
|||
>>> matrix.determinant()
|
||||
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)
|
||||
[[-1. -2. -3.]
|
||||
[-4. -5. -6.]
|
||||
|
@ -102,8 +106,9 @@ class Matrix:
|
|||
|
||||
def __init__(self, rows):
|
||||
error = TypeError(
|
||||
"Matrices must be formed from a list of zero or more lists containing at least "
|
||||
"one and the same number of values, each of which must be of type int or float."
|
||||
"Matrices must be formed from a list of zero or more lists containing at "
|
||||
"least one and the same number of values, each of which must be of type "
|
||||
"int or float."
|
||||
)
|
||||
if len(rows) != 0:
|
||||
cols = len(rows[0])
|
||||
|
@ -159,10 +164,8 @@ class Matrix:
|
|||
)
|
||||
else:
|
||||
return sum(
|
||||
[
|
||||
self.rows[0][column] * self.cofactors().rows[0][column]
|
||||
for column in range(self.num_columns)
|
||||
]
|
||||
self.rows[0][column] * self.cofactors().rows[0][column]
|
||||
for column in range(self.num_columns)
|
||||
)
|
||||
|
||||
def is_invertable(self):
|
||||
|
@ -346,7 +349,7 @@ class Matrix:
|
|||
|
||||
@classmethod
|
||||
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__":
|
||||
|
|
|
@ -30,7 +30,8 @@ def alternative_password_generator(ctbi, i):
|
|||
i = i - len(ctbi)
|
||||
quotient = int(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 = (
|
||||
ctbi
|
||||
+ random(ascii_letters, quotient + remainder)
|
||||
|
|
|
@ -5,11 +5,14 @@
|
|||
Simple example of Fractal generation using recursive function.
|
||||
|
||||
What is Sierpinski Triangle?
|
||||
>>The Sierpinski triangle (also with the original orthography Sierpinski), also called the Sierpinski gasket or the Sierpinski Sieve,
|
||||
is a fractal and attractive fixed set with the overall shape of an equilateral triangle, subdivided recursively into smaller
|
||||
equilateral triangles. Originally constructed as a curve, this is one of the basic 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.
|
||||
>>The Sierpinski triangle (also with the original orthography Sierpinski), also called
|
||||
the Sierpinski gasket or the Sierpinski Sieve, is a fractal and attractive fixed set
|
||||
with the overall shape of an equilateral triangle, subdivided recursively into smaller
|
||||
equilateral triangles. Originally constructed as a curve, this is one of the basic
|
||||
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):
|
||||
- turtle
|
||||
|
@ -20,7 +23,8 @@ Python:
|
|||
Usage:
|
||||
- $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
|
||||
|
|
|
@ -1,11 +1,14 @@
|
|||
"""
|
||||
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.
|
||||
"""
|
||||
|
|
|
@ -14,15 +14,18 @@ import bisect
|
|||
|
||||
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 item: item to bisect
|
||||
: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])
|
||||
: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:
|
||||
>>> 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.
|
||||
|
||||
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 item: item to bisect
|
||||
: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])
|
||||
: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:
|
||||
>>> 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.
|
||||
|
||||
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 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.
|
||||
|
||||
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 item: item to insert
|
||||
|
|
|
@ -14,5 +14,6 @@ def send_slack_message(message_body: str, slack_url: str) -> None:
|
|||
|
||||
|
||||
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>")
|
||||
|
|
Loading…
Reference in New Issue
Block a user