Skip to content

Commit

Permalink
Wrap lines that go beyond GitHub Editor (TheAlgorithms#1925)
Browse files Browse the repository at this point in the history
* 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>
  • Loading branch information
cclauss and github-actions authored May 1, 2020
1 parent bcaa88b commit 6acd7fb
Show file tree
Hide file tree
Showing 19 changed files with 161 additions and 82 deletions.
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -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
Expand Down
13 changes: 10 additions & 3 deletions ciphers/rsa_cipher.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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)
)

Expand All @@ -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)
)

Expand Down
11 changes: 8 additions & 3 deletions ciphers/rsa_key_generator.py
Original file line number Diff line number Diff line change
@@ -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():
Expand Down Expand Up @@ -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()
Expand Down
15 changes: 10 additions & 5 deletions data_structures/linked_list/doubly_linked_list.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -13,7 +16,7 @@ def __init__(self):

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)
Expand All @@ -23,7 +26,9 @@ def insertHead(self, x):
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
Expand Down
23 changes: 16 additions & 7 deletions divide_and_conquer/strassen_matrix_multiplication.py
Original file line number Diff line number Diff line change
Expand Up @@ -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!")
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand All @@ -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):
Expand Down
17 changes: 10 additions & 7 deletions dynamic_programming/bitmask.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@
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

Expand All @@ -25,7 +24,8 @@ def __init__(self, task_performed, total):

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):
Expand All @@ -45,15 +45,17 @@ def CountWaysUtil(self, mask, task_no):
# 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]:

# if p is already given a task
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.
Expand Down Expand Up @@ -85,6 +87,7 @@ def countNoOfWays(self, task_performed):
)
"""
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
"""
6 changes: 4 additions & 2 deletions dynamic_programming/edit_distance.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
"""


Expand Down
29 changes: 19 additions & 10 deletions machine_learning/decision_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,21 @@ def mean_squared_error(self, labels, prediction):
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")
Expand All @@ -46,7 +52,8 @@ def train(self, X, y):
"""

"""
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")
Expand All @@ -72,7 +79,8 @@ def train(self, X, y):
"""
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:
Expand Down Expand Up @@ -136,7 +144,7 @@ def helper_mean_squared_error_test(labels, prediction):
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:
Expand All @@ -147,9 +155,10 @@ def helper_mean_squared_error_test(labels, prediction):

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)
Expand Down
13 changes: 9 additions & 4 deletions machine_learning/logistic_regression.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
#!/usr/bin/python

## Logistic Regression from scratch
# Logistic Regression from scratch

# In[62]:

# In[63]:

# 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
Expand All @@ -21,7 +25,8 @@

# 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):
Expand Down
12 changes: 8 additions & 4 deletions machine_learning/support_vector_machines.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
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()
Expand All @@ -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
Expand All @@ -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])
Expand Down
Loading

0 comments on commit 6acd7fb

Please sign in to comment.