From 5204f2f2b504d446f618d8798745bcae1e343598 Mon Sep 17 00:00:00 2001 From: yedhink Date: Fri, 5 Oct 2018 06:44:02 +0530 Subject: [PATCH 01/88] Added algorithm to find longest substring --- strings/longest_substring.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 strings/longest_substring.py diff --git a/strings/longest_substring.py b/strings/longest_substring.py new file mode 100644 index 0000000..47dffcd --- /dev/null +++ b/strings/longest_substring.py @@ -0,0 +1,34 @@ +# Create an algorithm that prints the longest substring of s in which +# the letters occur in alphabetical order. For example, if +# s = 'azcbobobegghakl', then your program should print: +# Longest substring in alphabetical order is: beggh + +# In the case of ties, print the first substring. +# For example, if s = 'abcbcd', then your program should print: +# Longest substring in alphabetical order is: abc + + +def longest_substr(s): + count = 0 + maxcount = 0 + result = 0 + for char in range(len(s) - 1): + if (s[char] <= s[char + 1]): + count += 1 + if count > maxcount: + maxcount = count + result = char + 1 + else: + count = 0 + startposition = result - maxcount + return startposition, result + + +# parent string +s = 'azbeggaklbeggh' + +# longest substring indexes +start, end = longest_substr(s) + +print('Longest substring in alphabetical order is:', + s[start:end + 1]) From ef24bb6d3d3cce89ac1c022dc91e0da936ebefc4 Mon Sep 17 00:00:00 2001 From: anish03 Date: Thu, 4 Oct 2018 20:28:16 -0700 Subject: [PATCH 02/88] Added python implementation for finding the middle element of a linkedlist --- linkedlist/middle_of_linkedlist.py | 56 ++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 linkedlist/middle_of_linkedlist.py diff --git a/linkedlist/middle_of_linkedlist.py b/linkedlist/middle_of_linkedlist.py new file mode 100644 index 0000000..c0d55df --- /dev/null +++ b/linkedlist/middle_of_linkedlist.py @@ -0,0 +1,56 @@ +class Node: + def __init__(self,data): + self.data = data + self.next = None + +class LinkedList: + def __init__(self): + self.head = None + self.tail = None + self.count = 0 + + def isEmpty(self): + if self.count == 0: + return True + return False + + def add_node(self,data): + new = Node(data) + + if self.isEmpty(): + self.head = new + self.tail = new + self.count += 1 + else: + new.next = self.head + self.head = new + self.count += 1 + + def show(self): + list = '' + ptr = self.head + while ptr: + print ptr.data + print ' -> ' + ptr = ptr.next + print list + + def middle(self): + fast = self.head + slow = self.head + while fast and fast.next: + slow = slow.next + fast = fast.next.next + print slow.data + + +def main(): + L = LinkedList() + L.add_node(2) + L.add_node(32) + L.add_node(21) + L.add_node(67) + L.add_node(89) + L.middle() +if __name__ == '__main__': + main() From 7873d2705693cf9718ab9f291c121cfc324b7161 Mon Sep 17 00:00:00 2001 From: Jay Rajput Date: Mon, 8 Oct 2018 00:54:07 +0530 Subject: [PATCH 03/88] Added check_armstrong in math --- math/check_armstrong.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 math/check_armstrong.py diff --git a/math/check_armstrong.py b/math/check_armstrong.py new file mode 100644 index 0000000..783e8d8 --- /dev/null +++ b/math/check_armstrong.py @@ -0,0 +1,22 @@ +def main(): + print("Enter the the number") + n=int(input()) + for i in range(1,n+1): + b=checkamstrong(i) + if b: + print(str(i)+" is an armstrong number") + +def checkarmstrong(n): + t=n + sum=0 + while t!=0: + r=t%10 + sum=sum+(r*r*r) + t=t//10 + if sum==n: + return True + else: + return False + +if __name__ == '__main__': + main() \ No newline at end of file From 7b887caa1c1079ef9f0c604083b4ed1f051df058 Mon Sep 17 00:00:00 2001 From: Altaf Date: Tue, 9 Oct 2018 14:23:34 +0530 Subject: [PATCH 04/88] Coin change problem using recursive pattern --- recursion/Coin-Change-Problem.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 recursion/Coin-Change-Problem.py diff --git a/recursion/Coin-Change-Problem.py b/recursion/Coin-Change-Problem.py new file mode 100644 index 0000000..c88529f --- /dev/null +++ b/recursion/Coin-Change-Problem.py @@ -0,0 +1,11 @@ +def coin_change(v,items): + ans = 99 + if v <= 0: + return 0; + for item in items: + if v - item >= 0: + update = 1 + coin_change(v - item, items) + ans = min(ans, update); + return ans; + +print(coin_change(4, [1,2,3,5])) \ No newline at end of file From 1c60b68a0c17ff775ec6d64ce642d0a734325be1 Mon Sep 17 00:00:00 2001 From: marvin-michum Date: Tue, 9 Oct 2018 09:59:57 -0400 Subject: [PATCH 05/88] added Zellers Congruence --- math/zellers_birthday.py | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 math/zellers_birthday.py diff --git a/math/zellers_birthday.py b/math/zellers_birthday.py new file mode 100644 index 0000000..450ebc6 --- /dev/null +++ b/math/zellers_birthday.py @@ -0,0 +1,39 @@ +"""Zellers Congruence Birthday Algorithm + Find out what day of the week you were born on + Accepts birthday as a string in mm-dd-yyyy format +""" + +def zeller(bday): + + days = { + '0': 'Sunday', + '1': 'Monday', + '2': 'Tuesday', + '3': 'Wednesday', + '4': 'Thursday', + '5': 'Friday', + '6': 'Saturday' + } + + m = int(bday[0] + bday[1]) + d = int(bday[3] + bday[4]) + y = int(bday[6] + bday[7] + bday[8] + bday[9]) + + if m <= 2: + y = y - 1 + m = m + 12 + c = int(str(y)[:2]) + k = int(str(y)[2:]) + + t = int(2.6*m - 5.39) + u = int(c / 4) + v = int(k / 4) + x = d + k + z = t + u + v + x + w = z - (2 * c) + + f = round(w%7) + + for i in days: + if f == int(i): + print("Your birthday " + bday + ", was a " + days[i] + "!") \ No newline at end of file From 7477846b861ec8e19b6680bc6cd0a1e4f56a90c9 Mon Sep 17 00:00:00 2001 From: jeffmikels Date: Tue, 9 Oct 2018 23:39:16 -0400 Subject: [PATCH 06/88] added bkdr hash --- ciphers/bkdr.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 ciphers/bkdr.py diff --git a/ciphers/bkdr.py b/ciphers/bkdr.py new file mode 100644 index 0000000..bbb89d2 --- /dev/null +++ b/ciphers/bkdr.py @@ -0,0 +1,20 @@ +#!/usr/bin/python + + + + +def BKDRHash(s): + '''BKDR Hash is an algorithm invented by Brian Kernighan, Dennis Ritchie. + The algorithm was presented in/on "The C Programming Language". + The digest (hash generated by this algorithm) is 32 bits (4 Bytes) in length. + refer to: http://www.partow.net/programming/hashfunctions/ + ''' + seed = 131 # can be any combination of 31, like 31 131 1313 13131 131313 + hash = 0 + for i in range(len(s)): + hash = (hash * seed) + ord(s[i]) + return hash + +if __name__ == '__main__': + cleartext = "This is a test string for use with the BKDRHash" + print BKDRHash(cleartext) \ No newline at end of file From a55e8d645324c46b21acc0437312df254ee45d50 Mon Sep 17 00:00:00 2001 From: pramodbharti Date: Wed, 10 Oct 2018 23:36:21 +0530 Subject: [PATCH 07/88] Improved quick_sort implementation --- sorting/quick_sort.py | 39 +++++++++++++-------------------------- 1 file changed, 13 insertions(+), 26 deletions(-) diff --git a/sorting/quick_sort.py b/sorting/quick_sort.py index 5865203..16da17b 100644 --- a/sorting/quick_sort.py +++ b/sorting/quick_sort.py @@ -1,27 +1,14 @@ -#quick sort implementation in Python by Neville Antony +""" +Here is the implementation of quicksort algorithm in python by Pramod Bharti +quick_sort() function takes an unsorted array and prints sorted array +""" +def quick_sort(arr): + if len(arr) <= 1: + return arr + pivot = arr[len(arr) // 2] + left = [x for x in arr if x < pivot] + middle = [x for x in arr if x == pivot] + right = [x for x in arr if x > pivot] + return quick_sort(left) + middle + quick_sort(right) -def partition(arr, down, up): - i = ( down - 1 ) - pivot = arr[up] - - for j in range(down, up): - if arr[j] <= pivot: - i = i+1 - arr[i],arr[j] = arr[j],arr[i] - - arr[i+1],arr[up] = arr[up],arr[i+1] - return ( i+1 ) - -def quickSort(arr, down, up): - if down< up: - pi = partition(arr, down, up) - quickSort(arr, down, pi-1) - quickSort(arr, pi+1, up) - -arr = [91, 72, 68, 23, 37, 55] -n = len(arr) -quickSort(arr,0,n-1) -print("The sorted array is :") -for i in range(n): - print ("%d" %arr[i]), - +print (quick_sort([5,2,8,3,9,12,43])) # This will print [2,3,5,8,9,12,43] From 4bef8cb6f5b3000528392edea10d2cae6fdfd968 Mon Sep 17 00:00:00 2001 From: Jannes Jonkers Date: Wed, 10 Oct 2018 22:29:32 +0200 Subject: [PATCH 08/88] Added the lucky numbers algorithm --- math/lucky_numbers.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 math/lucky_numbers.py diff --git a/math/lucky_numbers.py b/math/lucky_numbers.py new file mode 100644 index 0000000..d37568f --- /dev/null +++ b/math/lucky_numbers.py @@ -0,0 +1,15 @@ +def generate_lucky_number_sequence(end): + + #create a list of all odd numbers up to the final number + sequence = [*range(1, end+1, 2)] + + #remove every xth number from the list where x = the nth element of the sequence + n = 1 + while len(sequence) > sequence[n]: + number_to_delete = sequence[n] + del sequence[number_to_delete-1::number_to_delete] + n = n + 1 + + return sequence + +print(generate_lucky_number_sequence(int(input("Please enter the upper bound of the lucky number sequence: ")))) From 3e8716d7c1fba3349f96e10c9355a7802fdc6400 Mon Sep 17 00:00:00 2001 From: mrvnmchm Date: Wed, 10 Oct 2018 16:51:28 -0400 Subject: [PATCH 09/88] modularized --- math/zellers_birthday.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/math/zellers_birthday.py b/math/zellers_birthday.py index 450ebc6..5233730 100644 --- a/math/zellers_birthday.py +++ b/math/zellers_birthday.py @@ -1,3 +1,4 @@ +import argparse """Zellers Congruence Birthday Algorithm Find out what day of the week you were born on Accepts birthday as a string in mm-dd-yyyy format @@ -36,4 +37,10 @@ def zeller(bday): for i in days: if f == int(i): - print("Your birthday " + bday + ", was a " + days[i] + "!") \ No newline at end of file + print("Your birthday " + bday + ", was a " + days[i] + "!") + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='Find out what day of the week you were born on Accepts birthday as a string in mm-dd-yyyy or mm/dd/yyyy format') + parser.add_argument('bday', type=str, help='Date as a string (mm-dd-yyyy or mm/dd/yyyy)') + args = parser.parse_args() + zeller(args.bday) \ No newline at end of file From e6d9824f2cbe19dba32ad0fe681025904cd558b2 Mon Sep 17 00:00:00 2001 From: Will Adams Date: Thu, 11 Oct 2018 15:52:24 -0700 Subject: [PATCH 10/88] Add bogo sort implementation --- sorting/bogo_sort.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 sorting/bogo_sort.py diff --git a/sorting/bogo_sort.py b/sorting/bogo_sort.py new file mode 100644 index 0000000..bd9f5cd --- /dev/null +++ b/sorting/bogo_sort.py @@ -0,0 +1,13 @@ +# Python implementation of Bogo sort + +from random import shuffle + +def bogo_sort(l): + while not all(l[i] <= l[i+1] for i in xrange(len(l)-1)): + shuffle(l) + return l + +# Tests +if __name__ == '__main__': + print bogo_sort([3, 2, 1]) + print bogo_sort([1000, 100, 10, 1]) From 594a161b708074dc2f9af7781b6cda66677ede65 Mon Sep 17 00:00:00 2001 From: jacknash Date: Tue, 16 Oct 2018 22:56:35 +0900 Subject: [PATCH 11/88] add the calcu_trig_func algorithm --- math/calcu_trig.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 math/calcu_trig.py diff --git a/math/calcu_trig.py b/math/calcu_trig.py new file mode 100644 index 0000000..483a6c5 --- /dev/null +++ b/math/calcu_trig.py @@ -0,0 +1,31 @@ +from math import sqrt + +sign = ["", + "","",'-','-', #sin + "",'-',"-",'', #cos + "",'-','',"-"] #tan + +def trig_func(name,value,quad=1): + if name == 'tan': + cos = sqrt(1 / (value ** 2 + 1)) + sin = abs(value * cos) + print("sin={}{},cos={}{},tan={}".format(sign[quad], + sin,sign[quad+4], + cos,value)) + + elif name == 'sin': + cos = sqrt(1 - value ** 2) + tan = abs(value / cos) + print("sin={},cos={}{},tan={}{}".format(value, + sign[quad+4],cos, + sign[quad+8],tan)) + + elif name == 'cos': + sin = sqrt(1 - value ** 2) + tan = abs(sin / value) + print("sin={}{},cos={},tan={}{}".format(sign[quad],sin, + value, + sign[quad+8],tan)) + + else: + print('not sin,cos,tan') From 0f38e59ffd3ad80806b1bd848f1a41072c012e74 Mon Sep 17 00:00:00 2001 From: Dvontre Coleman Date: Wed, 17 Oct 2018 15:40:49 -0400 Subject: [PATCH 12/88] Add Recursive check for palindrome --- strings/recursivePalindrome.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 strings/recursivePalindrome.py diff --git a/strings/recursivePalindrome.py b/strings/recursivePalindrome.py new file mode 100644 index 0000000..200fe2f --- /dev/null +++ b/strings/recursivePalindrome.py @@ -0,0 +1,10 @@ +def checkString(string): + string = string.lower() + if(len(string) > 2): + if(string[0] == string[-1]): + return checkString(string[1 : -1]) + else: + return False + else: return string[0] == string[-1] + +print(checkString(input("check word for palindrome: "))) \ No newline at end of file From a40cad9dd833e1c549eb3b145ac65f161d20bf4a Mon Sep 17 00:00:00 2001 From: Mauricio Date: Sat, 20 Oct 2018 17:29:46 -0500 Subject: [PATCH 13/88] :octocat: Added stack to data structures and unitary tests --- data-structures/stacks/node.py | 30 +++++++++++++++ data-structures/stacks/stack.py | 56 ++++++++++++++++++++++++++++ data-structures/stacks/test_node.py | 29 ++++++++++++++ data-structures/stacks/test_stack.py | 53 ++++++++++++++++++++++++++ 4 files changed, 168 insertions(+) create mode 100644 data-structures/stacks/node.py create mode 100644 data-structures/stacks/stack.py create mode 100644 data-structures/stacks/test_node.py create mode 100644 data-structures/stacks/test_stack.py diff --git a/data-structures/stacks/node.py b/data-structures/stacks/node.py new file mode 100644 index 0000000..757368c --- /dev/null +++ b/data-structures/stacks/node.py @@ -0,0 +1,30 @@ +class Node: + + def __init__(self,item,next=None): + self.item = item + self.next = next + + def __str__(self): + string = '[' + str(self.item) + ']' + next = self.next + + while next: + if next: + string += ' -> ' + str(next) + next = next.get_next() + + return string + + + def get_item(self): + return self.item + + def get_next(self): + return self.next + + def set_item(self,item): + self.item = item + + def set_next(self,next): + self.next = next + diff --git a/data-structures/stacks/stack.py b/data-structures/stacks/stack.py new file mode 100644 index 0000000..085e7b6 --- /dev/null +++ b/data-structures/stacks/stack.py @@ -0,0 +1,56 @@ +from node import Node + +class Stack: + + def __init__(self): + self.head = None + + def __str__(self): + node = self.head + list = [] + while node: + list.append(node.get_item()) + node = node.get_next() + return str(list) + + def is_empty(self): + return not self.head + + def push(self, item): + if not self.head: + self.head = Node(item) + else: + self.head = Node(item,self.head) + + def pop(self): + if not self.head: + raise EmptyStackException('Cannot pop from a empty stack') + else: + item = self.head.get_item() + + if self.head.get_next(): + self.head = self.head.get_next() + + else: + self.head = None + + return item + + + def peek(self): + if not self.head: + raise EmptyStackException('Cannot peek from an empty stack') + else: + return self.head.get_item() + + def size(self): + count = 0 + node = self.head + while node: + count += 1 + node = node.get_next() + return count + + +class EmptyStackException(Exception): + pass \ No newline at end of file diff --git a/data-structures/stacks/test_node.py b/data-structures/stacks/test_node.py new file mode 100644 index 0000000..7f57f83 --- /dev/null +++ b/data-structures/stacks/test_node.py @@ -0,0 +1,29 @@ +import unittest +from node import Node + +class TestNode(unittest.TestCase): + + def setUp(self): + self.next_node = Node('item 2') + self.node = Node('item 1',self.next_node) + + def test_str(self): + self.assertEqual(str(self.node),'[item 1] -> [item 2]') + + def test_get_item(self): + self.assertEqual(self.node.get_item(),'item 1') + + def test_get_next(self): + self.assertIs(self.node.get_next(),self.next_node) + + def test_set_item(self): + self.node.set_item('another item') + self.assertEqual(self.node.get_item(),'another item') + + def test_set_next(self): + another_node = Node('another item') + self.node.set_next(another_node) + self.assertIs(self.node.get_next(),another_node) + +if __name__ == '__main__': + unittest.main() \ No newline at end of file diff --git a/data-structures/stacks/test_stack.py b/data-structures/stacks/test_stack.py new file mode 100644 index 0000000..bcadbae --- /dev/null +++ b/data-structures/stacks/test_stack.py @@ -0,0 +1,53 @@ +import unittest +from stack import Stack, EmptyStackException + +class TestStack(unittest.TestCase): + + def setUp(self): + self.stack = Stack() + + def test_is_empty(self): + self.assertTrue(self.stack.is_empty()) + + def test_str_and_push(self): + self.stack.push(6) + self.assertEqual(str(self.stack),"[6]") + + def test_push_three_elements(self): + self.stack.push(3) + self.stack.push(2) + self.stack.push(1) + self.assertEqual(str(self.stack),"[1, 2, 3]") + + def test_pop_exception(self): + with self.assertRaises(EmptyStackException): + self.stack.pop() + + def test_pop_with_one_element(self): + self.stack.push("Item") + self.assertEqual(self.stack.pop(),"Item") + self.assertTrue(self.stack.is_empty()) + + def test_pop_with_two_elements(self): + self.stack.push(2) + self.stack.push(1) + self.assertEqual(self.stack.pop(),1) + self.assertEqual(str(self.stack),'[2]') + + def test_peek_exception(self): + with self.assertRaises(EmptyStackException): + self.stack.peek() + + def test_peek(self): + self.stack.push(1) + self.assertEqual(self.stack.peek(),1) + + def test_size(self): + self.assertEqual(self.stack.size(),0) + self.stack.push(1) + self.stack.push(2) + self.stack.push(3) + self.assertEqual(self.stack.size(),3) + +if __name__ == '__main__': + unittest.main() \ No newline at end of file From adb00e95fecf5f6adb5a6e8d3119fda89ab04229 Mon Sep 17 00:00:00 2001 From: Abraham Hernandez Date: Mon, 22 Oct 2018 00:48:33 -0400 Subject: [PATCH 14/88] fix broken images links --- readme.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/readme.md b/readme.md index 43a0f08..acd2372 100644 --- a/readme.md +++ b/readme.md @@ -2,7 +2,7 @@


- +


@@ -15,9 +15,9 @@
- - - + + +


@@ -146,7 +146,7 @@ To the extent possible under law, [Carlos Abraham](https://go.abranhe.com/github -[mit-license]: https://cdn.abraham.gq/projects/algorithms/mit-license.png +[mit-license]: https://cdn.abranhe.com/projects/algorithms/mit-license.png [mit-link]: https://github.com/abranhe/algorithms/blob/master/license From 8c5778982f6b0f493752aff8b4b4892729d20072 Mon Sep 17 00:00:00 2001 From: bhuvanakundumani Date: Wed, 24 Oct 2018 14:44:11 +0530 Subject: [PATCH 15/88] Added the magic square algorithm --- math/magic_square.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 math/magic_square.py diff --git a/math/magic_square.py b/math/magic_square.py new file mode 100644 index 0000000..dca9adf --- /dev/null +++ b/math/magic_square.py @@ -0,0 +1,42 @@ + + + +"""A magic square is an N×N grid of numbers in which the entries in each row, column and main diagonal sum to the same number (equal to N(N2+1)/2)""" + + +import numpy as np + + +print("Hi! Welcome to the magic square algorithm") +print("Please enter the number for which you would want a magic sqaure to be printed. Please enter an odd number") + +# The odd number for which the magic square is created is stored in the variable N + +N = int(input()) + +# create a matrix with values 0 using numpy. The datatype is int for the elements in the matrix +magic_square = np.zeros((N,N), dtype=int) + +n = 1 +i, j = 0, N//2 + +# n iterates from 1 to N**2. The loop exits when n is equal to N**2 + +while n <= N**2: + # Start in the middle of the first row. + # (i = 0 and j = N//2 ) and the element at magic_square[i,j] is the middle in the first row. + # insert n = 1 to begin with at magic_square[i,j] + magic_square[i, j] = n + # increment n by 1 + n += 1 + # Move diagonally up and right, wrapping to the first column or last row if the move leads outside the grid + + new_i, new_j = (i-1) % N, (j+1)% N + + # if the cell is already filled with a number, move vertically down one space. + if magic_square[new_i, new_j]: + i += 1 + else: + i, j = new_i, new_j + +print(magic_square) From 5806a45a5cb66048d766cf2958f5acc782b26137 Mon Sep 17 00:00:00 2001 From: bhuvanakundumani Date: Wed, 24 Oct 2018 15:19:17 +0530 Subject: [PATCH 16/88] Pascla's Traingle implemented --- math/pascals_triangle.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 math/pascals_triangle.py diff --git a/math/pascals_triangle.py b/math/pascals_triangle.py new file mode 100644 index 0000000..ea625d4 --- /dev/null +++ b/math/pascals_triangle.py @@ -0,0 +1,26 @@ + +""" +Pascal's triangle is a triangular array of numbers in which those at the ends of the rows are 1 and each of the others is the sum of the nearest two numbers in the row above (the apex, 1, being at the top). + +""" +print("Welcome to Pascal's traingle:") + + +n=int(input("Enter number of rows for the pascal's traingle: ")) +a=[] +for i in range(n): + a.append([]) + a[i].append(1) + for j in range(1,i): + a[i].append(a[i-1][j-1]+a[i-1][j]) + if(n!=0): + a[i].append(1) + + +# printing pascal's triangle +print( " Your Pascal's traiange for the number {}".format(n)) +for i in range(n): + print(" "*(n-i),end=" ",sep=" ") + for j in range(0,i+1): + print('{0:6}'.format(a[i][j]),end=" ",sep=" ") + print() From 63e79f31e8d4c1c6065cc510c8d49c1360ba5be5 Mon Sep 17 00:00:00 2001 From: LuizGuerra Date: Wed, 31 Oct 2018 18:41:15 -0300 Subject: [PATCH 17/88] added stack data structure --- data-structures/stack/stack.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 data-structures/stack/stack.py diff --git a/data-structures/stack/stack.py b/data-structures/stack/stack.py new file mode 100644 index 0000000..7d0d1a3 --- /dev/null +++ b/data-structures/stack/stack.py @@ -0,0 +1,31 @@ +''' + Created by Luiz Guerra + My github github.com/LuizGuerra +''' + +class Stack { + + def __init__ (.self): + head = null + count = 0 + + def append(.self, e): + n = Node(e) + if count == 0: + head = n + count += 1 + else: + n.next = head.next + head = n + + def pop(.self): + n = head + head = head.next + return n.element + +} + +class Node (e): + __init__ (.self, e): + next = null + element = e From 7a8e9cf476e46578a356f80c26c6a1254850bfcf Mon Sep 17 00:00:00 2001 From: LuizGuerra Date: Wed, 31 Oct 2018 18:43:49 -0300 Subject: [PATCH 18/88] added stack data structure --- data-structures/stack/stack.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/data-structures/stack/stack.py b/data-structures/stack/stack.py index 7d0d1a3..6865245 100644 --- a/data-structures/stack/stack.py +++ b/data-structures/stack/stack.py @@ -3,7 +3,7 @@ My github github.com/LuizGuerra ''' -class Stack { +class Stack: def __init__ (.self): head = null @@ -22,8 +22,7 @@ def pop(.self): n = head head = head.next return n.element - -} + class Node (e): __init__ (.self, e): From 4dae1683048c933a1aea315bad2a246cc87d426d Mon Sep 17 00:00:00 2001 From: Sebastian Sangervasi Date: Tue, 30 Oct 2018 23:34:38 -0700 Subject: [PATCH 19/88] Implemented Conway's Game of Life with classic "glider" example * Module is executable and also importable. * Supports converting a game board to and from a multiline string. --- cellular-automaton/conways_game_of_life.py | 157 +++++++++++++++++++++ 1 file changed, 157 insertions(+) create mode 100644 cellular-automaton/conways_game_of_life.py diff --git a/cellular-automaton/conways_game_of_life.py b/cellular-automaton/conways_game_of_life.py new file mode 100644 index 0000000..21919c3 --- /dev/null +++ b/cellular-automaton/conways_game_of_life.py @@ -0,0 +1,157 @@ +""" +Conway's Game of Life +""" +import itertools + +class GameOfLife: + @classmethod + def dead_grid(cls, *, height=None, width=None): + return [ + [Dead() for _cols in range(width)] + for _rows in range(height) + ] + + @classmethod + def from_str(cls, string): + non_empty_lines = ( + line for line in string.splitlines() + if len(line) > 0 + ) + parsed_grid = [ + [Cell.from_str(char) for char in line] + for line in non_empty_lines + ] + return cls(grid=parsed_grid) + + def __init__(self, grid=None): + self.grid = grid + self.height = len(grid) + self.width = len(grid[0]) + + + def __str__(self): + return '\n'.join( + ''.join(str(cell) for cell in row) + for row in self.grid + ) + + def next_generation(self): + next_grid = [ + [ + cell.next_state(neighbor_count) + for cell, neighbor_count in row + ] + for row in self.grid_with_live_neighbor_counts() + ] + return GameOfLife(grid=next_grid) + + def grid_with_live_neighbor_counts(self): + ''' + Returns an iterator of grid rows in which each element + is a tuple containing the cell and the count of living neighbors + adjacent to that cell. + E.g. [[(Live, 0), (Dead, 3), ...], ...] + ''' + return ( + ( + (cell, self.count_live_neighbors(row, col)) + for (row, col), cell in coordinated_row + ) + for coordinated_row in self.coordinate() + ) + + def coordinate(self): + ''' + Returns an iterator of grid rows in which each element + is a tuple containg the coordinates and the content of the grid + at those coordinates. + E.g. [[((0, 0), Live), ((0, 1), Dead), ...], ...] + ''' + return ( + ( + ((row_index, col_index), cell) + for col_index, cell in enumerate(row) + ) + for row_index, row in enumerate(self.grid) + ) + + def count_live_neighbors(self, row, col): + directions_1D = (-1, 0, 1) + directions_2D = itertools.product(directions_1D, directions_1D) + neighbor_coords = ( + (row + d_row, col + d_col) + for (d_row, d_col) in directions_2D + if (d_row, d_col) != (0, 0) + ) + + def is_coord_alive(coord): + cell = self.get(*coord, default=Dead()) + return int(cell.is_alive) + + return sum(map(is_coord_alive, neighbor_coords)) + + def get(self, row, col, default=None): + is_within_rows = (0 <= row < self.height) + is_within_cols = (0 <= col < self.width) + if is_within_rows and is_within_cols: + return self.grid[row][col] + return default + + +class Cell: + @classmethod + def from_str(cls, string): + if string == Live.string_form: + return Live() + return Dead() + + def __str__(self): + return self.string_form + +class Dead(Cell): + string_form = '·' + is_alive = False + + def next_state(self, neighbor_count): + if neighbor_count == 3: + return Live() + return Dead() + +class Live(Cell): + string_form = '0' + is_alive = True + + def next_state(self, neighbor_count): + if neighbor_count in [2, 3]: + return Live() + return Dead() + + +def glider_example(): + from textwrap import dedent + + glider_string = dedent(''' + ··0···· + 0·0···· + ·00···· + ······· + ······· + ······· + ''') + + glider_game = GameOfLife.from_str(glider_string) + num_gens = 15 + print(dedent(f''' + Conway's Game of Life + Starting with seed: "Glider" + Running for {num_gens} generations. + ''')) + for gen_num in range(1, num_gens + 1 + ): + print(f'Generation {gen_num}:') + print(str(glider_game)) + glider_game = glider_game.next_generation() + print('Done') + +if __name__ == '__main__': + glider_example() From ae241cd2042314c4f596fe1d347a55926389449c Mon Sep 17 00:00:00 2001 From: Sebastian Sangervasi Date: Sun, 4 Nov 2018 12:08:01 -0800 Subject: [PATCH 20/88] Overly fancy formatting string header --- cellular-automaton/conways_game_of_life.py | 58 ++++++++++++++++------ 1 file changed, 43 insertions(+), 15 deletions(-) diff --git a/cellular-automaton/conways_game_of_life.py b/cellular-automaton/conways_game_of_life.py index 21919c3..bf66999 100644 --- a/cellular-automaton/conways_game_of_life.py +++ b/cellular-automaton/conways_game_of_life.py @@ -127,9 +127,33 @@ def next_state(self, neighbor_count): return Dead() -def glider_example(): - from textwrap import dedent +from textwrap import dedent + +def run_string_example( + *, + seed_string=None, + seed_name=None, + num_gens=10 +): + seed_game = GameOfLife.from_str(seed_string) + if seed_name is None: + seed_name = f'A {seed_game.height}x{seed_game.width} grid' + print(dedent(f''' + ========================= + | Conway's Game of Life | + {'':=^50} + | {f'Starting with seed: "{seed_name:.10}"': <46.46} | + | {f'Running for {str(num_gens):1.3} generations.': <46.46} | + {'':=^50} + ''')) + latest_generation = seed_game + for gen_num in range(1, num_gens + 1): + print(f'Generation {gen_num}:') + print(str(latest_generation)) + latest_generation = latest_generation.next_generation() + print('Done') +def glider_example(): glider_string = dedent(''' ··0···· 0·0···· @@ -138,20 +162,24 @@ def glider_example(): ······· ······· ''') + run_string_example( + seed_string=glider_string, + seed_name='Glider', + num_gens=15 + ) - glider_game = GameOfLife.from_str(glider_string) - num_gens = 15 - print(dedent(f''' - Conway's Game of Life - Starting with seed: "Glider" - Running for {num_gens} generations. - ''')) - for gen_num in range(1, num_gens + 1 - ): - print(f'Generation {gen_num}:') - print(str(glider_game)) - glider_game = glider_game.next_generation() - print('Done') +def question_example(): + from textwrap import dedent + + game_string = dedent(''' + ·0· + 0·0 + ''') + run_string_example( + seed_string=game_string, + num_gens=4 + ) if __name__ == '__main__': glider_example() + question_example() From e0f65b2f65f87154cf9091c7a9c4629341a88422 Mon Sep 17 00:00:00 2001 From: Abraham Hernandez Date: Sat, 10 Nov 2018 01:04:03 -0500 Subject: [PATCH 21/88] remove maintainers --- readme.md | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/readme.md b/readme.md index acd2372..d40afb4 100644 --- a/readme.md +++ b/readme.md @@ -125,9 +125,9 @@ See all algorithms and their explanation and categories at [@AllAlgorithms/algor ## Maintainers -| [![M1][m1-i]][m1] | [![M2][m2-i]][m2] | [![M3][m3-i]][m3] | -| :-: | :-: | :-: | -| [Carlos Abraham][m1] | [Pablo Trinidad][m2] | [Martmists][m3] | +| [![M1][m1-i]][m1] | +| :-: | +| [Carlos Abraham][m1] | ## License @@ -152,7 +152,3 @@ To the extent possible under law, [Carlos Abraham](https://go.abranhe.com/github [m1]: https://github.com/abranhe [m1-i]: https://avatars2.githubusercontent.com/u/21347264?s=70 -[m2]: https://github.com/pablotrinidad -[m2-i]: https://avatars1.githubusercontent.com/u/5308050?s=70 -[m3]: https://github.com/martmists -[m3-i]: https://avatars1.githubusercontent.com/u/16361449?s=70 From 3505967f7e73e4faf35986a7b58c770c72f8ae0b Mon Sep 17 00:00:00 2001 From: Abraham Hernandez Date: Sun, 30 Dec 2018 04:00:04 -0500 Subject: [PATCH 22/88] adding dbscan algorithm --- artificial-intelligence/dbscan.py | 84 +++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 artificial-intelligence/dbscan.py diff --git a/artificial-intelligence/dbscan.py b/artificial-intelligence/dbscan.py new file mode 100644 index 0000000..299fd99 --- /dev/null +++ b/artificial-intelligence/dbscan.py @@ -0,0 +1,84 @@ +import numpy as np +import math + +UNCLASSIFIED = False +NOISE = None + +def _dist(p,q): + return math.sqrt(np.power(p-q,2).sum()) + +def _eps_neighborhood(p,q,eps): + return _dist(p,q) < eps + +def _region_query(m, point_id, eps): + n_points = m.shape[1] + seeds = [] + for i in range(0, n_points): + if _eps_neighborhood(m[:,point_id], m[:,i], eps): + seeds.append(i) + return seeds + +def _expand_cluster(m, classifications, point_id, cluster_id, eps, min_points): + seeds = _region_query(m, point_id, eps) + if len(seeds) < min_points: + classifications[point_id] = NOISE + return False + else: + classifications[point_id] = cluster_id + for seed_id in seeds: + classifications[seed_id] = cluster_id + + while len(seeds) > 0: + current_point = seeds[0] + results = _region_query(m, current_point, eps) + if len(results) >= min_points: + for i in range(0, len(results)): + result_point = results[i] + if classifications[result_point] == UNCLASSIFIED or \ + classifications[result_point] == NOISE: + if classifications[result_point] == UNCLASSIFIED: + seeds.append(result_point) + classifications[result_point] = cluster_id + seeds = seeds[1:] + return True + +def dbscan(m, eps, min_points): + """Implementation of Density Based Spatial Clustering of Applications with Noise + See https://en.wikipedia.org/wiki/DBSCAN + + scikit-learn probably has a better implementation + + Uses Euclidean Distance as the measure + + Inputs: + m - A matrix whose columns are feature vectors + eps - Maximum distance two points can be to be regionally related + min_points - The minimum number of points to make a cluster + + Outputs: + An array with either a cluster id number or dbscan.NOISE (None) for each + column vector in m. + """ + cluster_id = 1 + n_points = m.shape[1] + classifications = [UNCLASSIFIED] * n_points + for point_id in range(0, n_points): + point = m[:,point_id] + if classifications[point_id] == UNCLASSIFIED: + if _expand_cluster(m, classifications, point_id, cluster_id, eps, min_points): + cluster_id = cluster_id + 1 + return classifications + +# def test_dbscan(): +# m = np.matrix('1 1.2 0.8 3.7 3.9 3.6 10; 1.1 0.8 1 4 3.9 4.1 10') +# eps = 0.5 +# min_points = 2 +# assert dbscan(m, eps, min_points) == [1, 1, 1, 2, 2, 2, None] + +def main(): + m = np.matrix('-0.99 -0.98 -0.97 -0.96 -0.95 0.95 0.96 0.97 0.98 0.99; 1.1 1.09 1.08 1.07 1.06 1.06 1.07 1.08 1.09 1.1') + eps = 1 + min_points = 3 + print(dbscan(m, eps, min_points)) + +main() From 377dbf1b95047711001e4ef7fc44883d99f1ded8 Mon Sep 17 00:00:00 2001 From: Josh Date: Tue, 1 Oct 2019 18:39:56 +0100 Subject: [PATCH 23/88] Fixed case sensitivity bug Updated the function to convert the string to uppercase before checking whether it's a palindrome. This prevents it from returning an incorrect value if a string is a palindrome but has inconsistent casing. --- strings/palindrome.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/strings/palindrome.py b/strings/palindrome.py index 82cc06e..698983b 100644 --- a/strings/palindrome.py +++ b/strings/palindrome.py @@ -3,12 +3,14 @@ def reverse(s): return s[::-1] def isPalindrome(s): + # Convert s to uppercase to ignore case sensitivity + s = s.upper() # Checking if both string are equal or not if (s == reverse(s)): return True return False # Tests -print(isPalindrome('racecar')) +print(isPalindrome('Racecar')) print(isPalindrome('ferrari')) -print(isPalindrome('civic')) +print(isPalindrome('CiVIc')) From 77e305b91dacbd63b38f0084fa76df9d66cd70b4 Mon Sep 17 00:00:00 2001 From: MacMullen Date: Tue, 1 Oct 2019 15:30:12 -0300 Subject: [PATCH 24/88] Added Counting Sort --- sorting/counting_sort.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 sorting/counting_sort.py diff --git a/sorting/counting_sort.py b/sorting/counting_sort.py new file mode 100644 index 0000000..d6922fe --- /dev/null +++ b/sorting/counting_sort.py @@ -0,0 +1,35 @@ +# +# Python implementation of counting sort. +# +# +# The All ▲lgorithms Project +# +# https://allalgorithms.com/ +# https://github.com/allalgorithms/cpp +# +# Contributed by: Simon Faillace Mullen +# Github: @macmullen +# + + +def counting_sort(arr): + # Create the counting sort array with length equal to the maximum number + # in the list. + count_array = [0] * (max(arr) + 1) + # Count the amount of repetitions for each number. + for number in arr: + count_array[number] += 1 + # Append the amount of repetitions in order. + position = 0 + for index, number in enumerate(count_array): + for amount in range(count_array[index]): + arr[position] = index + position += 1 + + +arr = [8, 5, 8, 4, 3, 3, 2, 1, 5, 5, 5, 9, 7, 7, 8, 1, 9, 3, 2] +print("Unsorted array:") +print(arr) +counting_sort(arr) +print("Sorted array:") +print(arr) From 235ce64a5910f68bfc2e5b11d8feabf670365c05 Mon Sep 17 00:00:00 2001 From: Kush Saini Date: Wed, 2 Oct 2019 01:14:28 +0530 Subject: [PATCH 25/88] Create fibonacci_search --- searches/fibonacci_search | 65 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 searches/fibonacci_search diff --git a/searches/fibonacci_search b/searches/fibonacci_search new file mode 100644 index 0000000..32be35d --- /dev/null +++ b/searches/fibonacci_search @@ -0,0 +1,65 @@ +# Python3 program for Fibonacci search. +from bisect import bisect_left + +# Returns index of x if present, else +# returns -1 +def fibMonaccianSearch(arr, x, n): + + # Initialize fibonacci numbers + fibMMm2 = 0 # (m-2)'th Fibonacci No. + fibMMm1 = 1 # (m-1)'th Fibonacci No. + fibM = fibMMm2 + fibMMm1 # m'th Fibonacci + + # fibM is going to store the smallest + # Fibonacci Number greater than or equal to n + while (fibM < n): + fibMMm2 = fibMMm1 + fibMMm1 = fibM + fibM = fibMMm2 + fibMMm1 + + # Marks the eliminated range from front + offset = -1; + + # while there are elements to be inspected. + # Note that we compare arr[fibMm2] with x. + # When fibM becomes 1, fibMm2 becomes 0 + while (fibM > 1): + + # Check if fibMm2 is a valid location + i = min(offset+fibMMm2, n-1) + + # If x is greater than the value at + # index fibMm2, cut the subarray array + # from offset to i + if (arr[i] < x): + fibM = fibMMm1 + fibMMm1 = fibMMm2 + fibMMm2 = fibM - fibMMm1 + offset = i + + # If x is greater than the value at + # index fibMm2, cut the subarray + # after i+1 + elif (arr[i] > x): + fibM = fibMMm2 + fibMMm1 = fibMMm1 - fibMMm2 + fibMMm2 = fibM - fibMMm1 + + # element found. return index + else : + return i + + # comparing the last element with x */ + if(fibMMm1 and arr[offset+1] == x): + return offset+1; + + # element not found. return -1 + return -1 + +# Driver Code +arr = [10, 22, 35, 40, 45, 50, + 80, 82, 85, 90, 100] +n = len(arr) +x = 85 +print("Found at index:", + fibMonaccianSearch(arr, x, n)) From 3082b83f02384641c0ed700bf17d525880ac7e97 Mon Sep 17 00:00:00 2001 From: Kush Saini Date: Wed, 2 Oct 2019 01:19:31 +0530 Subject: [PATCH 26/88] Rename fibonacci_search to fibonacci_search.py --- searches/{fibonacci_search => fibonacci_search.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename searches/{fibonacci_search => fibonacci_search.py} (100%) diff --git a/searches/fibonacci_search b/searches/fibonacci_search.py similarity index 100% rename from searches/fibonacci_search rename to searches/fibonacci_search.py From d981917206b4855ebf5beb3270c1c9f2caf33ce6 Mon Sep 17 00:00:00 2001 From: Abraham Hernandez Date: Tue, 1 Oct 2019 15:57:40 -0400 Subject: [PATCH 27/88] Rename recursivePalindrome.py to recursive_palindrome.py --- strings/{recursivePalindrome.py => recursive_palindrome.py} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename strings/{recursivePalindrome.py => recursive_palindrome.py} (79%) diff --git a/strings/recursivePalindrome.py b/strings/recursive_palindrome.py similarity index 79% rename from strings/recursivePalindrome.py rename to strings/recursive_palindrome.py index 200fe2f..e216872 100644 --- a/strings/recursivePalindrome.py +++ b/strings/recursive_palindrome.py @@ -7,4 +7,4 @@ def checkString(string): return False else: return string[0] == string[-1] -print(checkString(input("check word for palindrome: "))) \ No newline at end of file +print(checkString(input("check word for palindrome: "))) From 78cd0e16020366b7d36a3097cfdc258920a36a94 Mon Sep 17 00:00:00 2001 From: Saeed Date: Wed, 2 Oct 2019 00:11:54 +0330 Subject: [PATCH 28/88] The Jump Search --- searches/jump_search.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 searches/jump_search.py diff --git a/searches/jump_search.py b/searches/jump_search.py new file mode 100644 index 0000000..b34efc6 --- /dev/null +++ b/searches/jump_search.py @@ -0,0 +1,20 @@ +import math + +def jumoSearch (listA, theGoalValue): + length = len(listA) + jump = int(math.sqrt(length)) + left, right = 0, 0 + while length > left && theGoalValue >= listA[left]: + right = min(length - 1, left + jump) + if listA[left] <= theGoalValue and listA[right] >= theGoalValue: + break + left += jump; + if left >= length or listA[left] > theGoalValue: + return -1 + right = min(length - 1, right) + i = left + while i <= right and listA[i] <= theGoalValue: + if listA[i] == theGoalValue: + return i + i += 1 + return -1 From 2a7d8deb64ec092f9a44878d90d8a379b0231486 Mon Sep 17 00:00:00 2001 From: David Gokimmung <43725247+Davidgokimmung@users.noreply.github.com> Date: Wed, 2 Oct 2019 02:13:15 +0530 Subject: [PATCH 29/88] Create gcd.py --- math/gcd.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 math/gcd.py diff --git a/math/gcd.py b/math/gcd.py new file mode 100644 index 0000000..5eb748b --- /dev/null +++ b/math/gcd.py @@ -0,0 +1,10 @@ +def gcd(A, B): + if B>A: + A, B = B, A + while B!=0: + temp = B + B = A%B + A = temp + return A + +print(gcd(10,20)) From 039ff4a04718d459acb06b29ca74c73c0ab3ba3f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=8E=9B=E2=8E=9D=20L=E2=88=86RBI=20=E2=8E=A0=E2=8E=9E?= <48409226+L4RBI@users.noreply.github.com> Date: Thu, 1 Oct 2020 02:08:07 +0100 Subject: [PATCH 30/88] added a classification algorithms folder --- classification/fcm.py | 57 +++++++++++++++++++++++++++++++++++++++++ classification/tools.py | 20 +++++++++++++++ 2 files changed, 77 insertions(+) create mode 100644 classification/fcm.py create mode 100644 classification/tools.py diff --git a/classification/fcm.py b/classification/fcm.py new file mode 100644 index 0000000..79a3ee9 --- /dev/null +++ b/classification/fcm.py @@ -0,0 +1,57 @@ +from tools import * + +# https://en.wikipedia.org/wiki/Fuzzy_clustering + + +class FuzzyCMeans: + def __init__(self, n_clusters, initial_centers, data, max_iter=250, m=2, error=1e-5): + assert m > 1 + #assert initial_centers.shape[0] == n_clusters + self.U = None + self.centers = initial_centers + self.max_iter = max_iter + self.m = m + self.error = error + self.data = data + + def membership(self, data, centers): + U_temp = cdist(data, centers, 'euclidean') + U_temp = numpy.power(U_temp, 2/(self.m - 1)) + denominator_ = U_temp.reshape( + (data.shape[0], 1, -1)).repeat(U_temp.shape[-1], axis=1) + denominator_ = U_temp[:, :, numpy.newaxis] / denominator_ + return 1 / denominator_.sum(2) + + def Centers(self, data, U): + um = U ** self.m + return (data.T @ um / numpy.sum(um, axis=0)).T + + def newImage(self, U, centers, im): + best = numpy.argmax(self.U, axis=-1) + # print(best) + # numpy.round() + image = im.astype(int) + for i in range(256): + image = numpy.where(image == float(i), centers[best[i]][0], image) + return image + + def compute(self): + self.U = self.membership(self.data, self.centers) + + past_U = numpy.copy(self.U) + begin_time = datetime.datetime.now() + for i in range(self.max_iter): + + self.centers = self.Centers(self.data, self.U) + self.U = self.membership(self.data, self.centers) + + if norm(self.U - past_U) < self.error: + break + past_U = numpy.copy(self.U) + x = datetime.datetime.now() - begin_time + return self.centers, self.U, x + +# that's how you run it, data being your data, and the other parameters being the basic FCM parameters such as numbe rof cluseters, degree of fuzziness and so on +# f = FuzzyCMeans(n_clusters=C, initial_centers=Initial_centers, +# data=data m=2, max_iter=1000, error=1e-5) +# centers, U, time = f.compute() diff --git a/classification/tools.py b/classification/tools.py new file mode 100644 index 0000000..682268a --- /dev/null +++ b/classification/tools.py @@ -0,0 +1,20 @@ +from matplotlib.image import imread +import matplotlib.pyplot as plt +from math import sqrt +import math +import random +import numpy +import operator +from scipy.spatial.distance import cdist +from scipy.linalg import norm +import datetime + + +def Histogram(path): + image = imread(path) + if len(image.shape) != 2: + def gray(rgb): return numpy.dot(rgb[..., :3], [0.2989, 0.5870, 0.1140]) + gray = gray(image) + image = gray + hist, bins = numpy.histogram(image.ravel(), 256, [0, 256]) + return adapt(hist) From cf88e812859915bf260f4a42cfccf016b52b4f32 Mon Sep 17 00:00:00 2001 From: shirogin <42269089+shirogin@users.noreply.github.com> Date: Thu, 1 Oct 2020 03:42:56 +0100 Subject: [PATCH 31/88] some math problems --- math/GCD.py | 14 ++++++++++++++ math/fibonacci-recursive.py | 13 +++++++++++++ math/fibonacci.py | 11 +++++++++++ 3 files changed, 38 insertions(+) create mode 100644 math/GCD.py create mode 100644 math/fibonacci-recursive.py create mode 100644 math/fibonacci.py diff --git a/math/GCD.py b/math/GCD.py new file mode 100644 index 0000000..56e6f20 --- /dev/null +++ b/math/GCD.py @@ -0,0 +1,14 @@ +def gcd (small, large) : + if (small == 0): + return large + else: + return gcd(large % small, small) + + +gcdList = [[6, 9], [6, 12], [12, 18], [7, 14], [7, 13]] + +for Set in gcdList : + small = Set[0] + large = Set[1] + Gcd=gcd(small, large) + print(f"GCD for {small} and {large} is {Gcd}") \ No newline at end of file diff --git a/math/fibonacci-recursive.py b/math/fibonacci-recursive.py new file mode 100644 index 0000000..51b27a9 --- /dev/null +++ b/math/fibonacci-recursive.py @@ -0,0 +1,13 @@ +def fibonacciUn(n,Un_2=None,Un_1=None): + if(n<1): + return Un_2 or n + if (n==1): + return Un_1 or n + return fibonacciUn(n-1,Un_2,Un_1) + fibonacciUn (n-2,Un_2,Un_1) +# Test + +print("The first item of the sequence is:") +print(fibonacciUn(1,10,15)) + +print("The tweleth item of the sequence is:") +print(fibonacciUn(12)) \ No newline at end of file diff --git a/math/fibonacci.py b/math/fibonacci.py new file mode 100644 index 0000000..4420883 --- /dev/null +++ b/math/fibonacci.py @@ -0,0 +1,11 @@ +def fibonacciUn(Un_2,Un_1,n): + if(n<1): + return Un_2 + if (n==1): + return Un_1 + for i in range(n): + fib=Un_1+Un_2 + Un_2=Un_1 + Un_1=fib + return Un_1 +print(fibonacciUn(10,15,2)) \ No newline at end of file From a3c59dbc25e3fc03bdef28797f41dee80184908e Mon Sep 17 00:00:00 2001 From: Ishita Tiwari Date: Thu, 1 Oct 2020 11:22:58 +0530 Subject: [PATCH 32/88] Add files via upload --- math/SieveOfEratosthenes_PrimeNumbers.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 math/SieveOfEratosthenes_PrimeNumbers.py diff --git a/math/SieveOfEratosthenes_PrimeNumbers.py b/math/SieveOfEratosthenes_PrimeNumbers.py new file mode 100644 index 0000000..5285a72 --- /dev/null +++ b/math/SieveOfEratosthenes_PrimeNumbers.py @@ -0,0 +1,22 @@ +#time complexity: O(n log(log n)) + +def Sieve(n): + prime = [True for i in range(n + 1)] + p = 2 + + #Here, we mark all the numbers that are not prime + while(p * p <= n): + if prime[p] == True: + for i in range(p * p, n + 1, p): + prime[i] = False + p += 1 + + #only the numbers that are unmarked, are prime. Hence, we print them + for p in range(2, n): + if prime[p]: + print(p, end = ' ') + +#driver code +n = int(input()) +print("All prime numbers till", n, "are: ") +Sieve(n) From a3563f5788b02b4e3e781f1edf20fcef7eebf6ee Mon Sep 17 00:00:00 2001 From: Abraham Hernandez Date: Fri, 2 Oct 2020 02:09:53 -0400 Subject: [PATCH 33/88] refactofing! --- .github/code-of-conduct.md | 40 ++ .github/contributing.md | 3 + .github/issue-template.md | 1 + .github/pull-request-template.md | 6 + .gitignore | 115 ----- .../artificial-intelligence}/dbscan.py | 0 .../conways_game_of_life.py | 0 {ciphers => algorithms/ciphers}/bkdr.py | 0 .../cryptography}/aes.py | 0 .../cryptography}/caesar_cipher.py | 0 .../cryptography}/playfair.py | 0 .../data-structures}/hashs/hash_table.py | 0 .../linked-lists/linked_list.py | 0 .../data-structures}/trees/avl.py | 0 .../trees/binary_search_tree.py | 0 .../data-structures}/trees/heap.py | 0 .../trees/lowest_common_ancestor.py | 0 .../data-structures}/trees/min_height_bst.py | 0 .../dynamic-programming}/FloydWarshall.py | 0 .../binomial_coefficient.py | 0 .../dynamic-programming}/coin_change.py | 0 .../dynamic-programming}/edit_distance.py | 0 .../dynamic-programming}/knapsack.py | 0 .../dynamic-programming}/lcs.py | 0 .../longest_increasing_subsequence.py | 0 .../dynamic-programming}/rod_cutting.py | 0 .../rod_cutting_problem.py | 0 {graphs => algorithms/graphs}/bellman_ford.py | 0 {graphs => algorithms/graphs}/bfs.py | 0 .../graphs}/breadth_first_search.py | 0 .../graphs}/cycle_in_directed.py | 0 .../graphs}/cycle_in_undirected.py | 0 {graphs => algorithms/graphs}/dfs.py | 0 {graphs => algorithms/graphs}/dijkstra.py | 0 .../graphs}/floyd_warshall.py | 0 .../graphs}/ford_fulkerson.py | 0 {graphs => algorithms/graphs}/kruskals_MST.py | 0 {graphs => algorithms/graphs}/prims_MST.py | 0 .../graphs}/topological_sort.py | 0 {greedy => algorithms/greedy}/coin_change.py | 0 .../greedy}/dijkstra_algo.py | 0 .../greedy}/fractional_knapsack.py | 0 {math => algorithms/math}/calcu_trig.py | 0 {math => algorithms/math}/check_armstrong.py | 0 {math => algorithms/math}/collatz.py | 0 {math => algorithms/math}/ducci.py | 0 .../math}/factorial_iterative.py | 0 .../math}/factorial_recursive.py | 0 {math => algorithms/math}/lucky_numbers.py | 0 {math => algorithms/math}/magic_square.py | 0 .../math}/nth_fibonacci_using_goldenratio.py | 0 {math => algorithms/math}/pascals_triangle.py | 0 {math => algorithms/math}/zellers_birthday.py | 0 .../searches}/binary_search.py | 0 .../searches}/interpolation_search.py | 0 .../searches}/linear_search.py | 0 .../searches}/ternary_search.py | 0 .../sorting}/binary_search.py | 0 {sorting => algorithms/sorting}/bogo_sort.py | 0 .../sorting}/bubble_sort.py | 0 .../sorting}/bucket_sort.py | 0 .../sorting}/counting_sort.py | 0 {sorting => algorithms/sorting}/heap_sort.py | 0 .../sorting}/insertion_sort.py | 0 {sorting => algorithms/sorting}/merge_sort.py | 0 {sorting => algorithms/sorting}/quick_sort.py | 0 {sorting => algorithms/sorting}/radix_sort.py | 0 .../sorting}/selection_sort.py | 0 .../strings}/anagram_check.py | 0 .../strings}/anagram_search.py | 0 .../strings}/k_frequent_words.py | 0 .../strings}/letter_case_permutation.py | 0 .../strings}/longest_substring.py | 0 {strings => algorithms/strings}/morse_code.py | 0 {strings => algorithms/strings}/palindrome.py | 0 .../strings}/password_checker.py | 0 .../strings}/pattern_match.py | 0 {strings => algorithms/strings}/rabin_karp.py | 0 .../strings}/recursive_palindrome.py | 0 .../strings}/substring_check.py | 0 .../strings}/vowel_count.py | 0 license | 2 +- readme.md | 472 ++++++++++++++---- src/.gitkeep | 0 84 files changed, 418 insertions(+), 221 deletions(-) create mode 100644 .github/code-of-conduct.md create mode 100644 .github/contributing.md create mode 100644 .github/issue-template.md create mode 100644 .github/pull-request-template.md delete mode 100644 .gitignore rename {artificial-intelligence => algorithms/artificial-intelligence}/dbscan.py (100%) rename {cellular-automaton => algorithms/cellular-automaton}/conways_game_of_life.py (100%) rename {ciphers => algorithms/ciphers}/bkdr.py (100%) rename {cryptography => algorithms/cryptography}/aes.py (100%) rename {cryptography => algorithms/cryptography}/caesar_cipher.py (100%) rename {cryptography => algorithms/cryptography}/playfair.py (100%) rename {data-structures => algorithms/data-structures}/hashs/hash_table.py (100%) rename {data-structures => algorithms/data-structures}/linked-lists/linked_list.py (100%) rename {data-structures => algorithms/data-structures}/trees/avl.py (100%) rename {data-structures => algorithms/data-structures}/trees/binary_search_tree.py (100%) rename {data-structures => algorithms/data-structures}/trees/heap.py (100%) rename {data-structures => algorithms/data-structures}/trees/lowest_common_ancestor.py (100%) rename {data-structures => algorithms/data-structures}/trees/min_height_bst.py (100%) rename {dynamic-programming => algorithms/dynamic-programming}/FloydWarshall.py (100%) rename {dynamic-programming => algorithms/dynamic-programming}/binomial_coefficient.py (100%) rename {dynamic-programming => algorithms/dynamic-programming}/coin_change.py (100%) rename {dynamic-programming => algorithms/dynamic-programming}/edit_distance.py (100%) rename {dynamic-programming => algorithms/dynamic-programming}/knapsack.py (100%) rename {dynamic-programming => algorithms/dynamic-programming}/lcs.py (100%) rename {dynamic-programming => algorithms/dynamic-programming}/longest_increasing_subsequence.py (100%) rename {dynamic-programming => algorithms/dynamic-programming}/rod_cutting.py (100%) rename {dynamic-programming => algorithms/dynamic-programming}/rod_cutting_problem.py (100%) rename {graphs => algorithms/graphs}/bellman_ford.py (100%) rename {graphs => algorithms/graphs}/bfs.py (100%) rename {graphs => algorithms/graphs}/breadth_first_search.py (100%) rename {graphs => algorithms/graphs}/cycle_in_directed.py (100%) rename {graphs => algorithms/graphs}/cycle_in_undirected.py (100%) rename {graphs => algorithms/graphs}/dfs.py (100%) rename {graphs => algorithms/graphs}/dijkstra.py (100%) rename {graphs => algorithms/graphs}/floyd_warshall.py (100%) rename {graphs => algorithms/graphs}/ford_fulkerson.py (100%) rename {graphs => algorithms/graphs}/kruskals_MST.py (100%) rename {graphs => algorithms/graphs}/prims_MST.py (100%) rename {graphs => algorithms/graphs}/topological_sort.py (100%) rename {greedy => algorithms/greedy}/coin_change.py (100%) rename {greedy => algorithms/greedy}/dijkstra_algo.py (100%) rename {greedy => algorithms/greedy}/fractional_knapsack.py (100%) rename {math => algorithms/math}/calcu_trig.py (100%) rename {math => algorithms/math}/check_armstrong.py (100%) rename {math => algorithms/math}/collatz.py (100%) rename {math => algorithms/math}/ducci.py (100%) rename {math => algorithms/math}/factorial_iterative.py (100%) rename {math => algorithms/math}/factorial_recursive.py (100%) rename {math => algorithms/math}/lucky_numbers.py (100%) rename {math => algorithms/math}/magic_square.py (100%) rename {math => algorithms/math}/nth_fibonacci_using_goldenratio.py (100%) rename {math => algorithms/math}/pascals_triangle.py (100%) rename {math => algorithms/math}/zellers_birthday.py (100%) rename {searches => algorithms/searches}/binary_search.py (100%) rename {searches => algorithms/searches}/interpolation_search.py (100%) rename {searches => algorithms/searches}/linear_search.py (100%) rename {searches => algorithms/searches}/ternary_search.py (100%) rename {sorting => algorithms/sorting}/binary_search.py (100%) rename {sorting => algorithms/sorting}/bogo_sort.py (100%) rename {sorting => algorithms/sorting}/bubble_sort.py (100%) rename {sorting => algorithms/sorting}/bucket_sort.py (100%) rename {sorting => algorithms/sorting}/counting_sort.py (100%) rename {sorting => algorithms/sorting}/heap_sort.py (100%) rename {sorting => algorithms/sorting}/insertion_sort.py (100%) rename {sorting => algorithms/sorting}/merge_sort.py (100%) rename {sorting => algorithms/sorting}/quick_sort.py (100%) rename {sorting => algorithms/sorting}/radix_sort.py (100%) rename {sorting => algorithms/sorting}/selection_sort.py (100%) rename {strings => algorithms/strings}/anagram_check.py (100%) rename {strings => algorithms/strings}/anagram_search.py (100%) rename {strings => algorithms/strings}/k_frequent_words.py (100%) rename {strings => algorithms/strings}/letter_case_permutation.py (100%) rename {strings => algorithms/strings}/longest_substring.py (100%) rename {strings => algorithms/strings}/morse_code.py (100%) rename {strings => algorithms/strings}/palindrome.py (100%) rename {strings => algorithms/strings}/password_checker.py (100%) rename {strings => algorithms/strings}/pattern_match.py (100%) rename {strings => algorithms/strings}/rabin_karp.py (100%) rename {strings => algorithms/strings}/recursive_palindrome.py (100%) rename {strings => algorithms/strings}/substring_check.py (100%) rename {strings => algorithms/strings}/vowel_count.py (100%) create mode 100644 src/.gitkeep diff --git a/.github/code-of-conduct.md b/.github/code-of-conduct.md new file mode 100644 index 0000000..f809c8b --- /dev/null +++ b/.github/code-of-conduct.md @@ -0,0 +1,40 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ diff --git a/.github/contributing.md b/.github/contributing.md new file mode 100644 index 0000000..01f6600 --- /dev/null +++ b/.github/contributing.md @@ -0,0 +1,3 @@ +## Contributing + +> Please note that this project is released with a [Contributor Code of Conduct](code-of-conduct.md). By participating in this project you agree to abide by its terms. \ No newline at end of file diff --git a/.github/issue-template.md b/.github/issue-template.md new file mode 100644 index 0000000..99764fe --- /dev/null +++ b/.github/issue-template.md @@ -0,0 +1 @@ +I am creating an issue because... diff --git a/.github/pull-request-template.md b/.github/pull-request-template.md new file mode 100644 index 0000000..3bc0935 --- /dev/null +++ b/.github/pull-request-template.md @@ -0,0 +1,6 @@ +I am creating a pull request for... + +- [ ] New algorithm +- [ ] Update to an algorithm +- [ ] Fix an error +- [ ] Other - *Describe below* \ No newline at end of file diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 8820bb7..0000000 --- a/.gitignore +++ /dev/null @@ -1,115 +0,0 @@ -# Byte-compiled / optimized / DLL files -__pycache__/ -*.py[cod] -*$py.class - -# C extensions -*.so - -# Distribution / packaging -.Python -build/ -develop-eggs/ -dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -wheels/ -*.egg-info/ -.installed.cfg -*.egg -MANIFEST - -# PyInstaller -# Usually these files are written by a python script from a template -# before PyInstaller builds the exe, so as to inject date/other infos into it. -*.manifest -*.spec - -# Installer logs -pip-log.txt -pip-delete-this-directory.txt - -# Unit test / coverage reports -htmlcov/ -.tox/ -.nox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*.cover -.hypothesis/ -.pytest_cache/ - -# Translations -*.mo -*.pot - -# Django stuff: -*.log -local_settings.py -db.sqlite3 - -# Flask stuff: -instance/ -.webassets-cache - -# Scrapy stuff: -.scrapy - -# Sphinx documentation -docs/_build/ - -# PyBuilder -target/ - -# Jupyter Notebook -.ipynb_checkpoints - -# IPython -profile_default/ -ipython_config.py - -# pyenv -.python-version - -# celery beat schedule file -celerybeat-schedule - -# SageMath parsed files -*.sage.py - -# Environments -.env -.venv -env/ -venv/ -ENV/ -env.bak/ -venv.bak/ - -# Spyder project settings -.spyderproject -.spyproject - -# Rope project settings -.ropeproject - -# mkdocs documentation -/site - -# mypy -.mypy_cache/ -.dmypy.json -dmypy.json - -# macOS -.DS_Store -.localized diff --git a/artificial-intelligence/dbscan.py b/algorithms/artificial-intelligence/dbscan.py similarity index 100% rename from artificial-intelligence/dbscan.py rename to algorithms/artificial-intelligence/dbscan.py diff --git a/cellular-automaton/conways_game_of_life.py b/algorithms/cellular-automaton/conways_game_of_life.py similarity index 100% rename from cellular-automaton/conways_game_of_life.py rename to algorithms/cellular-automaton/conways_game_of_life.py diff --git a/ciphers/bkdr.py b/algorithms/ciphers/bkdr.py similarity index 100% rename from ciphers/bkdr.py rename to algorithms/ciphers/bkdr.py diff --git a/cryptography/aes.py b/algorithms/cryptography/aes.py similarity index 100% rename from cryptography/aes.py rename to algorithms/cryptography/aes.py diff --git a/cryptography/caesar_cipher.py b/algorithms/cryptography/caesar_cipher.py similarity index 100% rename from cryptography/caesar_cipher.py rename to algorithms/cryptography/caesar_cipher.py diff --git a/cryptography/playfair.py b/algorithms/cryptography/playfair.py similarity index 100% rename from cryptography/playfair.py rename to algorithms/cryptography/playfair.py diff --git a/data-structures/hashs/hash_table.py b/algorithms/data-structures/hashs/hash_table.py similarity index 100% rename from data-structures/hashs/hash_table.py rename to algorithms/data-structures/hashs/hash_table.py diff --git a/data-structures/linked-lists/linked_list.py b/algorithms/data-structures/linked-lists/linked_list.py similarity index 100% rename from data-structures/linked-lists/linked_list.py rename to algorithms/data-structures/linked-lists/linked_list.py diff --git a/data-structures/trees/avl.py b/algorithms/data-structures/trees/avl.py similarity index 100% rename from data-structures/trees/avl.py rename to algorithms/data-structures/trees/avl.py diff --git a/data-structures/trees/binary_search_tree.py b/algorithms/data-structures/trees/binary_search_tree.py similarity index 100% rename from data-structures/trees/binary_search_tree.py rename to algorithms/data-structures/trees/binary_search_tree.py diff --git a/data-structures/trees/heap.py b/algorithms/data-structures/trees/heap.py similarity index 100% rename from data-structures/trees/heap.py rename to algorithms/data-structures/trees/heap.py diff --git a/data-structures/trees/lowest_common_ancestor.py b/algorithms/data-structures/trees/lowest_common_ancestor.py similarity index 100% rename from data-structures/trees/lowest_common_ancestor.py rename to algorithms/data-structures/trees/lowest_common_ancestor.py diff --git a/data-structures/trees/min_height_bst.py b/algorithms/data-structures/trees/min_height_bst.py similarity index 100% rename from data-structures/trees/min_height_bst.py rename to algorithms/data-structures/trees/min_height_bst.py diff --git a/dynamic-programming/FloydWarshall.py b/algorithms/dynamic-programming/FloydWarshall.py similarity index 100% rename from dynamic-programming/FloydWarshall.py rename to algorithms/dynamic-programming/FloydWarshall.py diff --git a/dynamic-programming/binomial_coefficient.py b/algorithms/dynamic-programming/binomial_coefficient.py similarity index 100% rename from dynamic-programming/binomial_coefficient.py rename to algorithms/dynamic-programming/binomial_coefficient.py diff --git a/dynamic-programming/coin_change.py b/algorithms/dynamic-programming/coin_change.py similarity index 100% rename from dynamic-programming/coin_change.py rename to algorithms/dynamic-programming/coin_change.py diff --git a/dynamic-programming/edit_distance.py b/algorithms/dynamic-programming/edit_distance.py similarity index 100% rename from dynamic-programming/edit_distance.py rename to algorithms/dynamic-programming/edit_distance.py diff --git a/dynamic-programming/knapsack.py b/algorithms/dynamic-programming/knapsack.py similarity index 100% rename from dynamic-programming/knapsack.py rename to algorithms/dynamic-programming/knapsack.py diff --git a/dynamic-programming/lcs.py b/algorithms/dynamic-programming/lcs.py similarity index 100% rename from dynamic-programming/lcs.py rename to algorithms/dynamic-programming/lcs.py diff --git a/dynamic-programming/longest_increasing_subsequence.py b/algorithms/dynamic-programming/longest_increasing_subsequence.py similarity index 100% rename from dynamic-programming/longest_increasing_subsequence.py rename to algorithms/dynamic-programming/longest_increasing_subsequence.py diff --git a/dynamic-programming/rod_cutting.py b/algorithms/dynamic-programming/rod_cutting.py similarity index 100% rename from dynamic-programming/rod_cutting.py rename to algorithms/dynamic-programming/rod_cutting.py diff --git a/dynamic-programming/rod_cutting_problem.py b/algorithms/dynamic-programming/rod_cutting_problem.py similarity index 100% rename from dynamic-programming/rod_cutting_problem.py rename to algorithms/dynamic-programming/rod_cutting_problem.py diff --git a/graphs/bellman_ford.py b/algorithms/graphs/bellman_ford.py similarity index 100% rename from graphs/bellman_ford.py rename to algorithms/graphs/bellman_ford.py diff --git a/graphs/bfs.py b/algorithms/graphs/bfs.py similarity index 100% rename from graphs/bfs.py rename to algorithms/graphs/bfs.py diff --git a/graphs/breadth_first_search.py b/algorithms/graphs/breadth_first_search.py similarity index 100% rename from graphs/breadth_first_search.py rename to algorithms/graphs/breadth_first_search.py diff --git a/graphs/cycle_in_directed.py b/algorithms/graphs/cycle_in_directed.py similarity index 100% rename from graphs/cycle_in_directed.py rename to algorithms/graphs/cycle_in_directed.py diff --git a/graphs/cycle_in_undirected.py b/algorithms/graphs/cycle_in_undirected.py similarity index 100% rename from graphs/cycle_in_undirected.py rename to algorithms/graphs/cycle_in_undirected.py diff --git a/graphs/dfs.py b/algorithms/graphs/dfs.py similarity index 100% rename from graphs/dfs.py rename to algorithms/graphs/dfs.py diff --git a/graphs/dijkstra.py b/algorithms/graphs/dijkstra.py similarity index 100% rename from graphs/dijkstra.py rename to algorithms/graphs/dijkstra.py diff --git a/graphs/floyd_warshall.py b/algorithms/graphs/floyd_warshall.py similarity index 100% rename from graphs/floyd_warshall.py rename to algorithms/graphs/floyd_warshall.py diff --git a/graphs/ford_fulkerson.py b/algorithms/graphs/ford_fulkerson.py similarity index 100% rename from graphs/ford_fulkerson.py rename to algorithms/graphs/ford_fulkerson.py diff --git a/graphs/kruskals_MST.py b/algorithms/graphs/kruskals_MST.py similarity index 100% rename from graphs/kruskals_MST.py rename to algorithms/graphs/kruskals_MST.py diff --git a/graphs/prims_MST.py b/algorithms/graphs/prims_MST.py similarity index 100% rename from graphs/prims_MST.py rename to algorithms/graphs/prims_MST.py diff --git a/graphs/topological_sort.py b/algorithms/graphs/topological_sort.py similarity index 100% rename from graphs/topological_sort.py rename to algorithms/graphs/topological_sort.py diff --git a/greedy/coin_change.py b/algorithms/greedy/coin_change.py similarity index 100% rename from greedy/coin_change.py rename to algorithms/greedy/coin_change.py diff --git a/greedy/dijkstra_algo.py b/algorithms/greedy/dijkstra_algo.py similarity index 100% rename from greedy/dijkstra_algo.py rename to algorithms/greedy/dijkstra_algo.py diff --git a/greedy/fractional_knapsack.py b/algorithms/greedy/fractional_knapsack.py similarity index 100% rename from greedy/fractional_knapsack.py rename to algorithms/greedy/fractional_knapsack.py diff --git a/math/calcu_trig.py b/algorithms/math/calcu_trig.py similarity index 100% rename from math/calcu_trig.py rename to algorithms/math/calcu_trig.py diff --git a/math/check_armstrong.py b/algorithms/math/check_armstrong.py similarity index 100% rename from math/check_armstrong.py rename to algorithms/math/check_armstrong.py diff --git a/math/collatz.py b/algorithms/math/collatz.py similarity index 100% rename from math/collatz.py rename to algorithms/math/collatz.py diff --git a/math/ducci.py b/algorithms/math/ducci.py similarity index 100% rename from math/ducci.py rename to algorithms/math/ducci.py diff --git a/math/factorial_iterative.py b/algorithms/math/factorial_iterative.py similarity index 100% rename from math/factorial_iterative.py rename to algorithms/math/factorial_iterative.py diff --git a/math/factorial_recursive.py b/algorithms/math/factorial_recursive.py similarity index 100% rename from math/factorial_recursive.py rename to algorithms/math/factorial_recursive.py diff --git a/math/lucky_numbers.py b/algorithms/math/lucky_numbers.py similarity index 100% rename from math/lucky_numbers.py rename to algorithms/math/lucky_numbers.py diff --git a/math/magic_square.py b/algorithms/math/magic_square.py similarity index 100% rename from math/magic_square.py rename to algorithms/math/magic_square.py diff --git a/math/nth_fibonacci_using_goldenratio.py b/algorithms/math/nth_fibonacci_using_goldenratio.py similarity index 100% rename from math/nth_fibonacci_using_goldenratio.py rename to algorithms/math/nth_fibonacci_using_goldenratio.py diff --git a/math/pascals_triangle.py b/algorithms/math/pascals_triangle.py similarity index 100% rename from math/pascals_triangle.py rename to algorithms/math/pascals_triangle.py diff --git a/math/zellers_birthday.py b/algorithms/math/zellers_birthday.py similarity index 100% rename from math/zellers_birthday.py rename to algorithms/math/zellers_birthday.py diff --git a/searches/binary_search.py b/algorithms/searches/binary_search.py similarity index 100% rename from searches/binary_search.py rename to algorithms/searches/binary_search.py diff --git a/searches/interpolation_search.py b/algorithms/searches/interpolation_search.py similarity index 100% rename from searches/interpolation_search.py rename to algorithms/searches/interpolation_search.py diff --git a/searches/linear_search.py b/algorithms/searches/linear_search.py similarity index 100% rename from searches/linear_search.py rename to algorithms/searches/linear_search.py diff --git a/searches/ternary_search.py b/algorithms/searches/ternary_search.py similarity index 100% rename from searches/ternary_search.py rename to algorithms/searches/ternary_search.py diff --git a/sorting/binary_search.py b/algorithms/sorting/binary_search.py similarity index 100% rename from sorting/binary_search.py rename to algorithms/sorting/binary_search.py diff --git a/sorting/bogo_sort.py b/algorithms/sorting/bogo_sort.py similarity index 100% rename from sorting/bogo_sort.py rename to algorithms/sorting/bogo_sort.py diff --git a/sorting/bubble_sort.py b/algorithms/sorting/bubble_sort.py similarity index 100% rename from sorting/bubble_sort.py rename to algorithms/sorting/bubble_sort.py diff --git a/sorting/bucket_sort.py b/algorithms/sorting/bucket_sort.py similarity index 100% rename from sorting/bucket_sort.py rename to algorithms/sorting/bucket_sort.py diff --git a/sorting/counting_sort.py b/algorithms/sorting/counting_sort.py similarity index 100% rename from sorting/counting_sort.py rename to algorithms/sorting/counting_sort.py diff --git a/sorting/heap_sort.py b/algorithms/sorting/heap_sort.py similarity index 100% rename from sorting/heap_sort.py rename to algorithms/sorting/heap_sort.py diff --git a/sorting/insertion_sort.py b/algorithms/sorting/insertion_sort.py similarity index 100% rename from sorting/insertion_sort.py rename to algorithms/sorting/insertion_sort.py diff --git a/sorting/merge_sort.py b/algorithms/sorting/merge_sort.py similarity index 100% rename from sorting/merge_sort.py rename to algorithms/sorting/merge_sort.py diff --git a/sorting/quick_sort.py b/algorithms/sorting/quick_sort.py similarity index 100% rename from sorting/quick_sort.py rename to algorithms/sorting/quick_sort.py diff --git a/sorting/radix_sort.py b/algorithms/sorting/radix_sort.py similarity index 100% rename from sorting/radix_sort.py rename to algorithms/sorting/radix_sort.py diff --git a/sorting/selection_sort.py b/algorithms/sorting/selection_sort.py similarity index 100% rename from sorting/selection_sort.py rename to algorithms/sorting/selection_sort.py diff --git a/strings/anagram_check.py b/algorithms/strings/anagram_check.py similarity index 100% rename from strings/anagram_check.py rename to algorithms/strings/anagram_check.py diff --git a/strings/anagram_search.py b/algorithms/strings/anagram_search.py similarity index 100% rename from strings/anagram_search.py rename to algorithms/strings/anagram_search.py diff --git a/strings/k_frequent_words.py b/algorithms/strings/k_frequent_words.py similarity index 100% rename from strings/k_frequent_words.py rename to algorithms/strings/k_frequent_words.py diff --git a/strings/letter_case_permutation.py b/algorithms/strings/letter_case_permutation.py similarity index 100% rename from strings/letter_case_permutation.py rename to algorithms/strings/letter_case_permutation.py diff --git a/strings/longest_substring.py b/algorithms/strings/longest_substring.py similarity index 100% rename from strings/longest_substring.py rename to algorithms/strings/longest_substring.py diff --git a/strings/morse_code.py b/algorithms/strings/morse_code.py similarity index 100% rename from strings/morse_code.py rename to algorithms/strings/morse_code.py diff --git a/strings/palindrome.py b/algorithms/strings/palindrome.py similarity index 100% rename from strings/palindrome.py rename to algorithms/strings/palindrome.py diff --git a/strings/password_checker.py b/algorithms/strings/password_checker.py similarity index 100% rename from strings/password_checker.py rename to algorithms/strings/password_checker.py diff --git a/strings/pattern_match.py b/algorithms/strings/pattern_match.py similarity index 100% rename from strings/pattern_match.py rename to algorithms/strings/pattern_match.py diff --git a/strings/rabin_karp.py b/algorithms/strings/rabin_karp.py similarity index 100% rename from strings/rabin_karp.py rename to algorithms/strings/rabin_karp.py diff --git a/strings/recursive_palindrome.py b/algorithms/strings/recursive_palindrome.py similarity index 100% rename from strings/recursive_palindrome.py rename to algorithms/strings/recursive_palindrome.py diff --git a/strings/substring_check.py b/algorithms/strings/substring_check.py similarity index 100% rename from strings/substring_check.py rename to algorithms/strings/substring_check.py diff --git a/strings/vowel_count.py b/algorithms/strings/vowel_count.py similarity index 100% rename from strings/vowel_count.py rename to algorithms/strings/vowel_count.py diff --git a/license b/license index dd4858b..559a12b 100644 --- a/license +++ b/license @@ -19,4 +19,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +SOFTWARE. \ No newline at end of file diff --git a/readme.md b/readme.md index d40afb4..dd64172 100644 --- a/readme.md +++ b/readme.md @@ -1,37 +1,83 @@ -
-
-
-
- -
-
-
-
- -
+We are accepting all pull requests. [Read More](https://github.com/AllAlgorithms/algorithms/issues/40) + +


-

All ▲lgorithms implemented in Python


- - - - -
-
+ Algorithms Logo

- allalgorithms.com



+ +

+ What is an algorithm?    + Contributing    + Stickers & T-Shirts +

+ + +

+ + Twitter +    + + Instagram +    + + Github +    +

+ +
+

+ Huge collection of All ▲lgorithms implemented in multiple languages +

+
+ + + + + +
-See all algorithms and their explanation and categories at [@AllAlgorithms/algorithms](https://github.com/abranhe/algorithms). Check out the Python Library for The All ▲lgorithms project at [@abranhe/python-lib](https://github.com/abranhe/python-lib) +## See -## Contents +- [What is an algorithm](#what-is-an-algorithm) +- [Contributing](https://github.com/AllAlgorithms/algorithms/blob/master/.github/contributing.md) +- [Code of Conduct](https://github.com/AllAlgorithms/algorithms/blob/master/.github/code-of-conduct.md) +- [Stickers and T-Shirts](https://www.redbubble.com/people/abranhe/works/34285088) +- [Twitter](https://twitter.com/AllAlgorithms) +- [Instagram](https://instagram.com/AllAlgorithms) +- [Algorithms Categories](#categories) +- [Maintainers](#maintainers) +- [License](#license) + + +## What is an algorithm? + +Informally, an algorithm is any well-defined computational procedure that takes +some value, or set of values, as input and produces some value, or set of values, as +output. An algorithm is thus a sequence of computational steps that transform the +input into the output. + +An algorithm should have three important characteristics to be considered valid: + +- **It should be finite**: If your algorithm never ends trying to solve the problem +it was designed to solve then it is useless +- **It should have well defined instructions**: Each step of the algorithm has to +be precisely defined; the instructions should be unambiguously specified for each case. +- **It should be effective**: The algorithm should solve the problem it was designed +to solve. And it should be possible to demonstrate that the algorithm converges with +just a paper and pencil. + +## Categories + +> Structure of The All ▲lgoritms project - [Artificial Intelligence](#artificial-intelligence) - [Backtracking](#backtracking) @@ -58,97 +104,313 @@ See all algorithms and their explanation and categories at [@AllAlgorithms/algor - [Online Challenges](#online-challenges) - [Others](#others) -## Cryptography - -- [Advanced Encryption Standard](cryptography/aes.py) -- [Caesar Cipher](cryptography/caesar_cipher.py) -- [Playfair Cipher](cryptography/playfair.py) - -## Data Structures - -- [Hashes](#hashs) -- [Linked Lists](#linked-lists) -- [Trees](#trees) - -#### Hashes -- [Hash Table](data-structures/hashs/hash_table.py) - -#### Linked Lists - -- [Linked List](data-structures/linked-lists/linked_list.py) - -#### Trees - -- [AVL Tree](data-structures/trees/binary_search_tree.py) -- [Binary Search Tree](data-structures/trees/binary_search_tree.py) -- [Heap](data-structures/trees/heap.py) -- [Lowest Common Ancestor](data-structures/trees/lowest_common_ancestor.py) -- [Minimum Height Binary Search Tree](data-structures/trees/min_height_bst.py) - - - -## Maintainers - -| [![M1][m1-i]][m1] | -| :-: | -| [Carlos Abraham][m1] | +## [Artificial Intelligence](artificial-intelligence) + +- [Density-based spatial clustering of applications with noise (DBSCAN Clustering)](https://allalgorithms.com/docs/dbscan) +- [Interactive Self-Organizing Data Analysis Technique yAy! (ISODATA Clustering)](https://allalgorithms.com/docs/isodata) +- [Linear Regression](https://allalgorithms.com/docs/linear-regression) +- [Logistic Regression](https://allalgorithms.com/docs/logistic-regression) +- [Neutral Style Transfer](https://allalgorithms.com/docs/neutral-style-transfer) +- [SATisfiable (SAT)](https://allalgorithms.com/docs/sat) +- [Travelling salesman problem (TSP)](https://allalgorithms.com/docs/tsp) +- [A* (A Star)](https://allalgorithms.com/docs/a-star) +- [Artificial Neutral Network](https://allalgorithms.com/docs/artificial-neutral-network) +- [Convolutional Neutral Network](https://allalgorithms.com/docs/convolutional-neutral-network) +- [Decision Tree](https://allalgorithms.com/docs/decision-tree) +- [Factorization Machines](https://allalgorithms.com/docs/factorization-machines) +- [Gaussian Mixture Model](https://allalgorithms.com/docs/gaussian-mixtrue-model) +- [Gradient Boosting Trees](https://allalgorithms.com/docs/gradient-boostring-trees) +- [Hierachical Clustering](https://allalgorithms.com/docs/hierachical-clustering) +- [Image Processing](https://allalgorithms.com/docs/image-processing) +- [K Nearest Neighbors](https://allalgorithms.com/docs/k-nearest-neighbors) +- [K Means](https://allalgorithms.com/docs/k-means) +- [Minimax](https://allalgorithms.com/docs/minimax) +- [Native Bayes](https://allalgorithms.com/docs/native-bayes) +- [Nearest Sequence Memory](https://allalgorithms.com/docs/nearest-sequence-memory) +- [Neutral Network](https://allalgorithms.com/docs/neutral-network) +- [Perceptron](https://allalgorithms.com/docs/perceptron) +- [Principal Component Analysis](https://allalgorithms.com/docs/principal-component-analysis) +- [Q Learing](https://allalgorithms.com/docs/q-learning) +- [Random Forests](https://allalgorithms.com/docs/random-forest) +- [Restricted Boltzman Machine](https://allalgorithms.com/docs/restricted-boltzman-machine) + +## [Backtracking](backtracking) + +- [Algorithm X](backtracking/algorithm-x) +- [Crossword Puzzle](backtracking/crossword-Puzzle) +- [Knight Tour](backtracking/knight-tour) +- [M Coloring Problem](backtracking/m-coloring-problem) +- [N Queen](backtracking/n-queen) +- [Number of ways in Maze](backtracking/number-of-ways-in-maze) +- [Partitions of set](backtracking/partitions-of-set) +- [Permutation of Strings](backtracking/permutation-of-strings) +- [Powerset](backtracking/powerset) +- [Rat in maze](backtracking/rat-in-maze) +- [Subset Sum](backtracking/subset-sum) +- [Sudoku Solve](backtracking/sudoku-solve) + +## [Bit Manipulation](bit-manipulation) + +- [Addition using bits](bit-manipulation/adding-using-bits) +- [Bit divisor](bit-manipulation/bit-divisor) +- [Byte swapper](bit-manipulation/byte-swapper) +- [Convert numbers to binary](bit-manipulation/convert-numbers-to-binary) +- [Count set bits](bit-manipulation/count-set-bits) +- [Flip bits](bit-manipulation/flip-bits) +- [Hamming distance](bit-manipulation/hamming-distace) +- [Invert bit](bit-manipulation/invert-bit) +- [Lonely integer](bit-manipulation/lonely-integer) +- [Magic Number](bit-manipulation/magic-number) +- [Maximum XOR Value](bit-manipulation/maximun-xor-value) +- [Power of 2](bit-manipulation/power-of-2) +- [Subset Generation](bit-manipulation/subset-generation) +- [Sum binary numbers](bit-manipulation/sum-binary-numbers) +- [Sum equals XOR](bit-manipulation/sum-equals-xor) +- [Thrice unique number](bit-manipulation/thrice-unique-number) +- [Twice unique number](bit-manipulation/twice-unique-number) +- [XOR Swap](bit-manipulation/xor-swap) + +## [Cellular Automaton](cellular-automaton) + +- [Brians Brain](cellular-automaton/brians-brain) +- [Conways Game of life](cellular-automaton/conways-game-of-life) +- [Elementary Cellular Automata](cellular-automaton/elementary-cellular-automata) +- [Generic Algorithm](cellular-automaton/generic-algorithm) +- [Langtons Ant](cellular-automaton/langtons-ant) +- [Nobili Cellular Automata](cellular-automaton/nobili-cellular-automata) +- [Von Neoumann Cellular Automata](cellular-automaton/von-neoumann-cellular-automata) + +## [Computational Geometry](computational-geometry) + +- [2D Line intersection](computational-geometry/) +- [2D Separating Axis test](computational-geometry/) +- [Area of polygon](computational-geometry/) +- [Area of triangle](computational-geometry/) +- [Axis aligned bounding box collision](computational-geometry/) +- [Bresenham Line](computational-geometry/) +- [Chans Algorithm](computational-geometry/) +- [Cohen Sutherland Lineclip](computational-geometry/) +- [Distance between points](computational-geometry/) +- [Graham Scan](computational-geometry/) +- [Halfplane intersection](computational-geometry/) +- [Jarvis March](computational-geometry/) +- [Quickull](computational-geometry/) +- [Sphere tetrahedron intersection](computational-geometry/) +- [Sutherland Hodgeman clipping](computational-geometry/) + +## [Cryptography](cryptography) + +- [Affine Cipher](cryptography/) +- [Atbash Cipher](cryptography/) +- [Autokey Cipher](cryptography/) +- [Baconian Cipher](cryptography/) +- [Caesar Cipher](cryptography/) +- [Colummnar Cipher](cryptography/) +- [Vigenere Cipher](cryptography/) + +## [Data Structures](data-structures) + +- [Bag](data-structures/bag/) +- [Hashes](data-structures/hashes/) +- [Linked List](data-structures/linked-list/) +- [List](data-structures/list/) +- [Queue](data-structures/queue/) +- [Stack](data-structures/stack/) +- [Tree](data-structures/tree/) + +## [Divide and conquer](divide-and-conquer) + +- [Strassen Matrix Manipulation](divide-and-conquer/) +- [Closest Pair of Point](divide-and-conquer/) +- [Inversion Count](divide-and-conquer/) +- [Karatsuba Multiplication](divide-and-conquer/) +- [Maximum Contiguous subsequence sum](divide-and-conquer/) +- [Merge Sort using divide and conquer](divide-and-conquer/) +- [Quick Sort using divide and conquer](divide-and-conquer/) +- [Tournament Method to find min max](divide-and-conquer/) +- [Warnock Algorithm](divide-and-conquer/) +- [X Power Y](divide-and-conquer/) + +## [Dynamic Programming](dynamic-programming) + +- [Array Median](dynamic-programming) +- [Optima Binary Search Tree](dynamic-programming) +- [Binomial Coefficient](dynamic-programming) + +## [Gaming Theory](gaming-theory) + +- [Nim Next Best Move Game](gaming-theory/) +- [Nim Win Loss Game](gaming-theory/) +- [Grundy Numbers Kayle Game](gaming-theory/) + +## [Graphs](graphs) + +- [Bipartite Check](graphs/) +- [Adjacency Lists graphs representation](graphs/) +- [A* (A Star)](https://allalgorithms.com/docs/a-star) + +## [Greedy Algorithms](greedy-algorithms) + +- [Activity Selection](greedy-algorithms) +- [Dijkstra Shortest Path](greedy-algorithms) +- [Egyptian Fraction](greedy-algorithms) + +## [Math](math) + +- [2 Sum](math/) +- [Add Polynomials](math/) +- [Amicable Numbers](math/) +- [Armstrong Numbers](math/) +- [Automorphic Numbers](math/) +- [Average Stream Numbers](math/) +- [Babylonian Method](math/) +- [Binomial Coefficient](math/) +- [Catalan Number](math/) +- [Check is Square](math/) +- [Convolution](math/) +- [Coprime Numbers](math/) +- [Count Digits](math/) +- [Count Trailing Zeroes](math/) +- [Decoding of String](math/) +- [Delannoy Number](math/) +- [Derangements](math/) +- [DFA Division](math/) +- [Diophantine](math/) +- [Divided Differences](math/) +- [Euler Totient](math/) +- [Exponentiation Power](math/) +- [Factorial](math/factorial) +- [Fast Fourier transform](math/) +- [Fast inverse (sqrt) Square Root](math/) + +## [Networking](networking) + +- [Packet Sniffer](networking/) +- [Determine Endianess](networking/) +- [Validate IP](networking/) + +## [Numerical Analysis](numerical-analysis) + +- [Integral](numerical-analysis/integral) +- [Monte Carlo](numerical-analysis/monte-carlo) +- [Runge Kutt](numerical-analysis/runge-kutt) + +## [Operating system](operating-system) + +- [Currency](operating-system/) +- [Deadlocks](operating-system/) +- [Memory Management](operating-system/) +- [Scheduling](operating-system/) +- [Shell](operating-system/) + +## [Randomized Algorithms](randomized-algorithms) + +- [Birthday Paradox](randomized-algorithms) +- [Karger Minimum Cut Algorithm](randomized-algorithms) +- [Kth Smallest Element Algorithm](randomized-algorithms) +- [Random from Stream](randomized-algorithms) +- [Random Node Linked list](randomized-algorithms) +- [Randomized Quicksort](randomized-algorithms) +- [Reservoir Sampling](randomized-algorithms) +- [Shuffle an Array](randomized-algorithms) + +## [Searches](searches) + +- [Binary Search](searches) +- [Exponential Search](searches) +- [Fibonacci Search](searches) +- [Fuzzy Search](searches) +- [Interpolation Search](searches) +- [Jump Search](searches) +- [Linear Search](searches) +- [Ternay Search](searches) + +## [Selections Algorithms](selections-algorithms) + +- [Median of Medians](selections-algorithms) +- [Quick Select](selections-algorithms) + +## [Sorting](sorting) + +- [Bead Sort](sorting/) +- [Bogo Sort](sorting/) +- [Bubble Sort](sorting/) +- [Bucket Sort](sorting/) +- [Circle Sort](sorting/) +- [Comb Sort](sorting/) +- [Counting Sort](sorting/) +- [Cycle Sort](sorting/) +- [Flash Sort](sorting/) +- [Gnome Sort](sorting/) +- [Heap Sort](sorting/) +- [Insertion Sort](sorting/) +- [Intro Sort](sorting/) +- [Median Sort](sorting/) +- [Merge Sort](sorting/) +- [Pipeonhole Sort](sorting/) +- [Quick Sort](sorting/) +- [Radix Sort](sorting/) +- [Selection Sort](sorting/) +- [Shaker Sort](sorting/) +- [Shell Sort](sorting/) +- [Sleep Sort](sorting/) +- [Stooge Sort](sorting/) +- [Topological Sort](sorting/) +- [Tree Sort](sorting/) + +## [Strings](strings) + +- [Aho Corasick Algorithm](strings) +- [Anagram Search](strings) +- [Arithmetic on large numbers](strings) +- [Boyer Moore Algorithm](strings) +- [Finite Automata](strings) +- [Kasai Algorithm](strings) +- [Kmp Algorithm](strings) +- [Levenshteing Distance](strings) +- [Lipogram Checker](strings) + +## [Online Challenges](online-challenges) + +- [Coderbyte](online-challenges/coderbyte) +- [Code Chef](online-challenges/code-chef) +- [Code Eval](online-challenges/code-eval) +- [Hackerearth](online-challenges/hackerearth) +- [Hackerrank](online-challenges/hackerrank) +- [LeetCode](online-challenges/leetcode) +- [Project Euler](online-challenges/project-euler) +- [Rosalind](online-challenges/rosalind) +- [SPOJ](online-challenges/spoj) +- [Top Coder](online-challenges/top-coder)` + +## [Others](others) + +- [Average](others/) +- [Biggest of n numbers](others/) +- [Biggest Suffix](others/) +- [Fifteen Puzzle](others/) +- [Jaccard Similarity](others/) +- [Jose Phus Problem](others/) +- [Lapindrom Checker](others/) +- [Leap Year](others/) +- [Magic Square](others/) +- [Majority Element](others/) +- [Minimum subarray size with degree](others/) +- [No operator addition](others/) +- [Paint fill](others/) +- [Split list](others/) +- [Tokenizer](others/) +- [Unique number](others/) ## License -This work is released under [MIT License](https://github.com/abranhe/algorithms/blob/master/LICENSE) - -[![MIT][mit-license]][mit-link] - -To the extent possible under law, [Carlos Abraham](https://go.abranhe.com/github) has waived all copyright and related or neighboring rights to this work. +This work is released under MIT License. +To the extent possible under law, [Abraham Hernandez (@abranhe)](https://go.abranhe.com/github) has waived all copyright and related or neighboring rights to this work.

-
- - -[mit-license]: https://cdn.abranhe.com/projects/algorithms/mit-license.png -[mit-link]: https://github.com/abranhe/algorithms/blob/master/license - - -[m1]: https://github.com/abranhe -[m1-i]: https://avatars2.githubusercontent.com/u/21347264?s=70 +
\ No newline at end of file diff --git a/src/.gitkeep b/src/.gitkeep new file mode 100644 index 0000000..e69de29 From 641dbc494b7477a49b2e3baac675772c8afc3f10 Mon Sep 17 00:00:00 2001 From: RadientBrain Date: Sat, 3 Oct 2020 02:52:50 +0530 Subject: [PATCH 34/88] Graham Scan Algo Added --- .../computational-geometry/graham_scan.py | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 algorithms/computational-geometry/graham_scan.py diff --git a/algorithms/computational-geometry/graham_scan.py b/algorithms/computational-geometry/graham_scan.py new file mode 100644 index 0000000..80996f5 --- /dev/null +++ b/algorithms/computational-geometry/graham_scan.py @@ -0,0 +1,61 @@ +from random import randint +import matplotlib.pyplot as plt + + +def orientation(m, n, o): + val = ((n[1]-m[1])*(o[0]-n[0])) - ((o[1]-n[1])*(n[0]-m[0])) + if val > 0: + return 1 + elif val < 0: + return -1 + else: + return 0 + +def distance(m, n): + return (n[0]-m[0])**2 + (n[1]-m[1])**2 + +def Sorting_with_bubble(coordinates, b): + for coord_ith in range(len(coordinates)): + for j in range(len(coordinates)-coord_ith-1): + if (orientation(b, coordinates[j], coordinates[j+1]) > 0) or (orientation(b, coordinates[j], coordinates[j+1])==0 and (distance(b, coordinates[j]) > distance(b, coordinates[j+1]))): + temp = coordinates[j+1] + coordinates[j+1] = coordinates[j] + coordinates[j] = temp + + return coordinates + + +def Convex_hull_through_graham(coordinates): + b = min(coordinates, key= lambda coord: (coord[1], coord[0])) + coord_ith = coordinates.index(b) + coordinates[coord_ith]=coordinates[0] + coordinates[0] = b + coordinates = [b] + Sorting_with_bubble(coordinates[1:], b) + size_triplet = [coordinates[0], coordinates[1], coordinates[2]] + for coord_ith in range(3, len(coordinates)): + while len(size_triplet)>=3 and orientation(size_triplet[-2], size_triplet[-1], coordinates[coord_ith]) >= 0: + size_triplet.pop() + size_triplet.append(coordinates[coord_ith]) + return size_triplet+[size_triplet[0]] + + +def random_points(n=30): + coordinates = [(randint(0, n), randint(0, n)) for _ in range(n)] + print (coordinates) + return coordinates + + +if __name__ == "__main__": + coordinates = random_points(120) + + X = [coord[0] for coord in coordinates] + Y = [coord[1] for coord in coordinates] + plt.plot(X, Y, '.b') + + boundary_poly = Convex_hull_through_graham(coordinates) + + X = [coord[0] for coord in boundary_poly] + Y = [coord[1] for coord in boundary_poly] + plt.plot(X, Y, '-og') + + plt.show() \ No newline at end of file From 360943b90b89019a3ce813c8ff5a0f1fef0f8c26 Mon Sep 17 00:00:00 2001 From: RadientBrain Date: Sat, 3 Oct 2020 02:58:32 +0530 Subject: [PATCH 35/88] Graham Scan Algo Added --- algorithms/computational-geometry/graham_scan.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/algorithms/computational-geometry/graham_scan.py b/algorithms/computational-geometry/graham_scan.py index 80996f5..f968159 100644 --- a/algorithms/computational-geometry/graham_scan.py +++ b/algorithms/computational-geometry/graham_scan.py @@ -1,3 +1,10 @@ +''' +Layout: algorithms +Title : Graham Scan Algorithm +Author: RadientBrain +''' + + from random import randint import matplotlib.pyplot as plt From 8b348ac5f22353457ba3b34170119175fafb09b0 Mon Sep 17 00:00:00 2001 From: Josh Date: Wed, 30 Sep 2020 23:49:05 +0100 Subject: [PATCH 36/88] Create change_case.py --- strings/change_case.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 strings/change_case.py diff --git a/strings/change_case.py b/strings/change_case.py new file mode 100644 index 0000000..17da182 --- /dev/null +++ b/strings/change_case.py @@ -0,0 +1,12 @@ +# Simple function that converts uppercase characters to lowercase and vice versa. +# Author: jotslo + +def change_case(string): + # Iterates through string, if character is lowercase, convert to upper else lower + new_string = [char.upper() if char.islower() else char.lower() for char in string] + + # Joins list with an empty string to form the new string and return + return "".join(new_string) + +print(change_case("Hello, world!")) # hELLO, WORLD! +print(change_case("TEST")) # test From bcf7e286e7d909b3a12569e05848bbf5489af615 Mon Sep 17 00:00:00 2001 From: Gajesh Date: Sun, 27 Oct 2019 02:12:05 +0530 Subject: [PATCH 37/88] Added Trie Logic --- data-structures/trie/trie.py | 40 ++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 data-structures/trie/trie.py diff --git a/data-structures/trie/trie.py b/data-structures/trie/trie.py new file mode 100644 index 0000000..13f5568 --- /dev/null +++ b/data-structures/trie/trie.py @@ -0,0 +1,40 @@ +class trienode: + def __init__(self,character): + self.character = character + self.nextnodes = {} + self.isEnd = False + self.dataNode = None + +class trie: # use case: username/password + def __init__(self): + self.start = trienode('') + def insert(self,id,value): # returns true on successful insertion (value == password) + temp = self.start + for nextChar in id: + temp.nextnodes[nextChar] = temp.nextnodes.get(nextChar,trienode(nextChar)) + temp = temp.nextnodes[nextChar] + if temp.isEnd == True: + print("ID already Exists!!") + return False + temp.isEnd =True + temp.dataNode = value + return True + def findNode(self,id): # returns false if node doesn't exist and true, node if it does + temp = self.start + for nextChar in id: + next = temp.nextnodes.get(nextChar,None) + if next is None: + return False,None + temp = next + if temp.isEnd == True: + return True,temp + else: + return False,None + +if __name__ == '__main__': + t = trie() + t.insert('test1',"dummy1") + t.insert('test2',"dummy2") + print(t.findNode('test')) # (false,None) + a,b = t.findNode('test1') + print(a,b.dataNode) # true,dummy1 \ No newline at end of file From e43b6bfcf165e400c8ae1b25bb215063544e8ecd Mon Sep 17 00:00:00 2001 From: gaurangvyas98 Date: Wed, 30 Oct 2019 22:39:21 +0530 Subject: [PATCH 38/88] stacks.py --- data-structures/stacks/stacks.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 data-structures/stacks/stacks.py diff --git a/data-structures/stacks/stacks.py b/data-structures/stacks/stacks.py new file mode 100644 index 0000000..22d90bd --- /dev/null +++ b/data-structures/stacks/stacks.py @@ -0,0 +1,17 @@ +myStack = [] + +myStack.append('a') +myStack.append('b') +myStack.append('c') + +myStack + + +myStack.pop() + +myStack.pop() + +myStack.pop() + + +myStack.pop() \ No newline at end of file From 9c4c5e5eaa4c4e0ca31e41353cbe97da3e106299 Mon Sep 17 00:00:00 2001 From: CO18326 <42867901+CO18326@users.noreply.github.com> Date: Mon, 28 Oct 2019 21:32:43 +0530 Subject: [PATCH 39/88] Create common_divisor_count.py --- math/common_divisor_count.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 math/common_divisor_count.py diff --git a/math/common_divisor_count.py b/math/common_divisor_count.py new file mode 100644 index 0000000..ef28f92 --- /dev/null +++ b/math/common_divisor_count.py @@ -0,0 +1,31 @@ + + + +''' + +The function takes two integers as input and return the number of common divisors of +that pair + + + +''' +def cd_count(a,b): + + if a==0 or b==0: + return 2 + a=(-1*a if a<0 else a) + b=(-1*b if b<0 else b) + + result=0 + while a!=0: + c=a + a=b%a + b=c + + for i in range(1,int((b**0.5)+1)): + if b%i==0: + if b/i==i: + result=result+1 + else: + result=result+2 + return result From 493ffc8e9d1b034351dc065aeec146149aaa45c3 Mon Sep 17 00:00:00 2001 From: aniakubik Date: Mon, 21 Oct 2019 20:54:12 +0200 Subject: [PATCH 40/88] add extended euclidean algorithm --- math/extendedEuclidean.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 math/extendedEuclidean.py diff --git a/math/extendedEuclidean.py b/math/extendedEuclidean.py new file mode 100644 index 0000000..f220a37 --- /dev/null +++ b/math/extendedEuclidean.py @@ -0,0 +1,20 @@ +""" + for numbers a, b returns x, y such as x * a + y * b = gcd(a,b) +""" + +def extendedEuclidean(a,b): + a_old, b_old = a,b + a, b = max(a, b), min(a, b) + x, y, old_x, old_y = 0, 1, 1, 0 + while b != 0: + quotient = a // b + residue = a % b + a, b = b, residue + x, old_x = old_x, (old_x - quotient * x) + y, old_y = old_y, (old_y - quotient * y) + if a_old > b_old: + return x, y + return y, x + + + From 5410c95662772f8f121765fc2e4a984c4f7ac8b1 Mon Sep 17 00:00:00 2001 From: aniakubik Date: Fri, 25 Oct 2019 18:19:14 +0200 Subject: [PATCH 41/88] added euler totien function --- math/eulerTotient.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 math/eulerTotient.py diff --git a/math/eulerTotient.py b/math/eulerTotient.py new file mode 100644 index 0000000..bb9af68 --- /dev/null +++ b/math/eulerTotient.py @@ -0,0 +1,24 @@ +from math import sqrt + +""" +this function calculate euler totien function +""" +def eulerTotienFunction(n): + if n == 1: + return 1 + result = 1 + temp = n + for i in range(2,int(sqrt(n))+10): + if (temp % i == 0): + j = 0 + while(temp % i == 0): + j += 1 + temp //= i + result = result * (i**(j-1)) * (i-1) + if temp == n: + return n-1 + return result + + + + From 15fdd2ca513d7481a9308ebe31047af61d398f94 Mon Sep 17 00:00:00 2001 From: Saeed Date: Wed, 2 Oct 2019 00:16:46 +0330 Subject: [PATCH 42/88] The Exponential Search --- searches/exponential_search.py | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 searches/exponential_search.py diff --git a/searches/exponential_search.py b/searches/exponential_search.py new file mode 100644 index 0000000..9021089 --- /dev/null +++ b/searches/exponential_search.py @@ -0,0 +1,7 @@ +def exponentialSearch(lys, val): + if lys[0] == val: + return 0 + index = 1 + while index < len(lys) and lys[index] <= val: + index = index * 2 + return BinarySearch( arr[:min(index, len(lys))], val) From faff65fa9bf726025f1e1167c45c2bb55c54ff54 Mon Sep 17 00:00:00 2001 From: AayusHTiw Date: Wed, 2 Oct 2019 02:39:53 +0530 Subject: [PATCH 43/88] Added algorithm of Sieve of eratosthenes --- math/Sieve of Eratosthenes.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 math/Sieve of Eratosthenes.py diff --git a/math/Sieve of Eratosthenes.py b/math/Sieve of Eratosthenes.py new file mode 100644 index 0000000..d4b866d --- /dev/null +++ b/math/Sieve of Eratosthenes.py @@ -0,0 +1,20 @@ +def SieveOfEratosthenes(n): + prime = [True for i in range(n+1)] + p = 2 + while (p * p <= n): + # If prime[p] is not changed, then it is a prime + if (prime[p] == True): + # Update all multiples of p + for i in range(p * p, n+1, p): + prime[i] = False + p += 1 + # Print all prime numbers + for p in range(2, n): + if prime[p]: + print (p), + # driver program +if __name__=='__main__': + n = 30 + print ("Following are the prime numbers smaller") + print ("than or equal to", n) + SieveOfEratosthenes(n) From f63cd01657c4dc22fba2dea3e5eb82212476f907 Mon Sep 17 00:00:00 2001 From: "ramona.burger" Date: Thu, 3 Oct 2019 00:32:26 +0200 Subject: [PATCH 44/88] add gaussian filter --- math/gaussfilter.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 math/gaussfilter.py diff --git a/math/gaussfilter.py b/math/gaussfilter.py new file mode 100644 index 0000000..724a5e8 --- /dev/null +++ b/math/gaussfilter.py @@ -0,0 +1,35 @@ +import math + + +def gaussfilt(xdata, ydata, sigma, xfilt=None, M=None, extrap=None): + if xfilt is None: + xfilt = xdata + if M is None: + M = 3 * sigma + if extrap is None: + extrap = 0 + yfilt = [0] * len(xfilt) + for i in range(0, len(xfilt), 1): + indices = [k for k, x in enumerate(xdata) if x > (xfilt[i] - M) and x < (xfilt[i] + M)] + if indices: + x = [] + for ind in indices: + x.append(xdata[ind] - xfilt[i]) + gaussfactors = gausskernel(x, sigma) + y = [] + yd = [] + for ind in indices: + yd.append(ydata[ind]) + for j in range(0, len(gaussfactors), 1): + y.append(gaussfactors[j] * yd[j]) + yfilt[i] = sum(y) / sum(gaussfactors) + if not indices: + yfilt[i] = extrap + return yfilt + + +def gausskernel(x, sigma): + res = [] + for element in x: + res.append(1 / (sigma * math.sqrt(2 * math.pi)) * math.exp(-0.5 * pow((element / sigma), 2))) + return res From f3ed52b4401bd80ebba3ea4e87a6b0509a38bf18 Mon Sep 17 00:00:00 2001 From: David Voigt Date: Thu, 3 Oct 2019 23:13:13 +0200 Subject: [PATCH 45/88] Added recursive function to determine the greatest common divisor of two integers --- math/recursive_greatest_common_divisor.py | 26 +++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 math/recursive_greatest_common_divisor.py diff --git a/math/recursive_greatest_common_divisor.py b/math/recursive_greatest_common_divisor.py new file mode 100644 index 0000000..e2f43d7 --- /dev/null +++ b/math/recursive_greatest_common_divisor.py @@ -0,0 +1,26 @@ +""" +In mathematics, the greatest common divisor (gcd) of two or more integers, +which are not all zero, is the largest positive integer that divides each of the integers. +For example, the gcd of 8 and 12 is 4. +» https://en.wikipedia.org/wiki/Greatest_common_divisor + +Due to limited recursion depth this algorithm is not suited for calculating the GCD of big integers. +""" + +def recGCD(x, y, div = 0): + # Detemine which integer is greater and set the divisor accordingly + if div == 0: + if x > y: + div = x + else: + div = y + # If both integers can be divided without a remainder the gcd has been found + if x % div == 0 and y % div == 0: + return div + # Decrease divisor by one and try again + else: + return recGCD(x, y, div-1) + +x = int(input("x = ")) +y = int(input("y = ")) +print(f"gcd({x}, {y}) = {recGCD(x,y)}") \ No newline at end of file From c1f6470ce1cd210e2f645fed2be7653047db7b6c Mon Sep 17 00:00:00 2001 From: David Voigt Date: Thu, 3 Oct 2019 23:14:06 +0200 Subject: [PATCH 46/88] Added new line at the end --- math/recursive_greatest_common_divisor.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/math/recursive_greatest_common_divisor.py b/math/recursive_greatest_common_divisor.py index e2f43d7..5983355 100644 --- a/math/recursive_greatest_common_divisor.py +++ b/math/recursive_greatest_common_divisor.py @@ -23,4 +23,4 @@ def recGCD(x, y, div = 0): x = int(input("x = ")) y = int(input("y = ")) -print(f"gcd({x}, {y}) = {recGCD(x,y)}") \ No newline at end of file +print(f"gcd({x}, {y}) = {recGCD(x,y)}") From 813a1eafccb47a6a7e784b612666ae12d62e5922 Mon Sep 17 00:00:00 2001 From: MaxFeussner Date: Fri, 4 Oct 2019 13:41:04 +0100 Subject: [PATCH 47/88] Added Bron-Kerbosch Algorithm for finding cliques --- graphs/Bron-Kerbosch.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 graphs/Bron-Kerbosch.py diff --git a/graphs/Bron-Kerbosch.py b/graphs/Bron-Kerbosch.py new file mode 100644 index 0000000..d802445 --- /dev/null +++ b/graphs/Bron-Kerbosch.py @@ -0,0 +1,29 @@ +# dealing with a graph as list of lists +graph = [[0,1,0,0,1,0],[1,0,1,0,1,0],[0,1,0,1,0,0],[0,0,1,0,1,1],[1,1,0,1,0,0],[0,0,0,1,0,0]] + + +#function determines the neighbors of a given vertex +def N(vertex): + c = 0 + l = [] + for i in graph[vertex]: + if i is 1 : + l.append(c) + c+=1 + return l + +#the Bron-Kerbosch recursive algorithm +def bronk(r,p,x): + if len(p) == 0 and len(x) == 0: # when no more possible neighbors are found, the max clique is printed + print(r) + return + for vertex in p[:]: # iterates through all possible neigbors + r_new = r[::] + r_new.append(vertex) + p_new = [val for val in p if val in N(vertex)] # p intersects N(vertex) + x_new = [val for val in x if val in N(vertex)] # x intersects N(vertex) + bronk(r_new,p_new,x_new) # recursiv call with new r, p and x + p.remove(vertex) + x.append(vertex) + +bronk([], [0,1,2,3,4,5], []) \ No newline at end of file From 2d209d6c8e5a6a0623bd1ea4fae64d1b150ac720 Mon Sep 17 00:00:00 2001 From: mecklenborg Date: Fri, 4 Oct 2019 17:32:54 -0500 Subject: [PATCH 48/88] Adding shell sort --- sorting/shell_sort.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 sorting/shell_sort.py diff --git a/sorting/shell_sort.py b/sorting/shell_sort.py new file mode 100644 index 0000000..1269179 --- /dev/null +++ b/sorting/shell_sort.py @@ -0,0 +1,35 @@ +"""This is a Python implementation of the shell sort algorithm + +Shell sort is a variation of insertion sort. This method starts by sorting +pairs of elements far away from each other, then progressively reducing the +gap between elements to be compared. + +""" +from random import randint + + +def shell_sort(arr): + + n = len(arr) + gap = n//2 + + while gap > 0: + for i in range(gap, n): + tmp = arr[i] + + j = i + while j >= gap and arr[j-gap] > tmp: + arr[j] = arr[j-gap] + j -= gap + arr[j] = tmp + + gap //= 2 + + return arr + + +# Tests +if __name__ == '__main__': + print(shell_sort([randint(0, 1000) for _ in range(10)])) + print(shell_sort([randint(-500, 500) for _ in range(10)])) + From 0de78cb53e47d7945651dea3e57cd52ea6476151 Mon Sep 17 00:00:00 2001 From: anish03 Date: Sat, 6 Oct 2018 12:41:51 -0700 Subject: [PATCH 49/88] Python implementation for recursively reversing a linkedlist --- linkedlist/reverse_linkedlist.py | 64 ++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 linkedlist/reverse_linkedlist.py diff --git a/linkedlist/reverse_linkedlist.py b/linkedlist/reverse_linkedlist.py new file mode 100644 index 0000000..c5b75de --- /dev/null +++ b/linkedlist/reverse_linkedlist.py @@ -0,0 +1,64 @@ +# Recursively reverse a linked list + +class Node: + def __init__(self,data): + self.data = data + self.next = None + +class LinkedList: + def __init__(self): + self.head = None + self.tail = None + self.count = 0 + + def isEmpty(self): + if self.count == 0: + return True + return False + + def addnode(self,data): + new = Node(data) + if self.isEmpty(): + self.head = new + self.tail = new + self.count += 1 + else: + new.next = self.head + self.head = new + self.count += 1 + + def show(self): + list = '' + ptr = self.head + while ptr: + list += str(ptr.data) + list += '->' + ptr = ptr.next + print list + + def reverse(self,cur): + cur = cur + n = cur.next + + if n.next: + self.reverse(cur.next) + n.next = cur + cur.next = None + else: + n.next = cur + self.head = n + +def main(): + L = LinkedList() + L.addnode(89) + L.addnode(67) + L.addnode(21) + L.addnode(32) + L.addnode(2) + L.show() + L.reverse(L.head) + L.show() + + +if __name__ == '__main__': + main() From 2a0012597cb11899a2160840c4c20a27101a8a7f Mon Sep 17 00:00:00 2001 From: Syed Mujtaba <42322958+mujtaba1747@users.noreply.github.com> Date: Tue, 8 Oct 2019 12:34:14 +0530 Subject: [PATCH 50/88] Added Matrix Chain Multiplication in Python --- .../matrix_chain_multiplication.py | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 dynamic-programming/matrix_chain_multiplication.py diff --git a/dynamic-programming/matrix_chain_multiplication.py b/dynamic-programming/matrix_chain_multiplication.py new file mode 100644 index 0000000..f0c73a5 --- /dev/null +++ b/dynamic-programming/matrix_chain_multiplication.py @@ -0,0 +1,39 @@ +# Python program to solve Matrix chain multiplication using Dynamic Programming +# MatrixChain returns the minimum number of scalar multiplications needed to +# Compute the product of the chain +import sys +# Matrix Ai has dimension p[i-1] x p[i] for i = 1..n +def MatrixChain(p, n): + # For simplicity of the program, one extra row and one + # extra column are allocated in m[][]. 0th row and 0th + # column of m[][] are not used + m = [[0 for x in range(n)] for x in range(n)] + + # m[i, j] = Minimum number of scalar multiplications needed + # to compute the matrix A[i]A[i + 1]...A[j] = A[i..j] where + # dimension of A[i] is p[i-1] x p[i] + + # cost is zero when multiplying one matrix. + for i in range(1, n): + m[i][i] = 0 + + # L is chain length. + for L in range(2, n): + for i in range(1, n-L + 1): + j = i + L-1 + m[i][j] = sys.maxsize # sys.maxsize is a very large integer value (Refer https://stackoverflow.com/questions/48138632/in-python-what-is-sys-maxsize for more details if intrested) + for k in range(i, j): + + # q = cost / scalar multiplications + q = m[i][k] + m[k + 1][j] + p[i-1]*p[k]*p[j] + if q < m[i][j]: + m[i][j] = q + + return m[1][n-1] + +# Program to test above function +arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] +size = len(arr) + +print("Minimum number of multiplications is " + + str(MatrixChain(arr, size))) From 12007f016a724cfbc366a1cafc2e558e26b48f33 Mon Sep 17 00:00:00 2001 From: hosein Date: Tue, 8 Oct 2019 22:52:23 +0330 Subject: [PATCH 51/88] add python script binary-search in data-structures --- data-structures/binarySerach.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 data-structures/binarySerach.py diff --git a/data-structures/binarySerach.py b/data-structures/binarySerach.py new file mode 100644 index 0000000..4169aee --- /dev/null +++ b/data-structures/binarySerach.py @@ -0,0 +1,25 @@ +def binSearch(a, x, low, high): + #Return True if target is found in indicated portion of a Python list. + #The search only considers the portion from data[low] to data[high] inclusive. + + if low > high: + return False # interval is empty; no match + else: + mid = (low + high) // 2 + if x == a[mid]: # found a match + return True + elif x < a[mid]: + # recur on the portion left of the middle + return binSearch(a, x, low, mid - 1) + else: + # recur on the portion right of the middle + return binSearch(a, x, mid + 1, high) +a = [5, 10, 15, 20, 25, 30, 40] +x = 20 +low = 0 +high = 6 +result = binSearch(a, x, low, high) +if result: + print("The value ", x, " Found") +else: + print("The value ", x, " Not found") From 938f4e36fbddbe0f5e9c0bc7a9833eb45e7d66d4 Mon Sep 17 00:00:00 2001 From: David Voigt Date: Wed, 16 Oct 2019 21:05:48 +0200 Subject: [PATCH 52/88] word:length dict --- strings/word_length_dict.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 strings/word_length_dict.py diff --git a/strings/word_length_dict.py b/strings/word_length_dict.py new file mode 100644 index 0000000..673fb8d --- /dev/null +++ b/strings/word_length_dict.py @@ -0,0 +1,10 @@ +""" + Determines the length of each word in a string and puts the word and its length in a dictionary +""" + +def word_length_dict(text): + d = {e: len(e) for e in text.split(" ")} + return d + +text = "The quick brown fox jumps over the lazy dog" +print(word_length_dict(text)) From 4c9a4344c8c0e4cc0b6cdb5d213a4e38ad3bf430 Mon Sep 17 00:00:00 2001 From: siw3kosky Date: Mon, 21 Oct 2019 19:06:43 +0200 Subject: [PATCH 53/88] Create Fibonacci_Sequence.py --- math/Fibonacci_Sequence.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 math/Fibonacci_Sequence.py diff --git a/math/Fibonacci_Sequence.py b/math/Fibonacci_Sequence.py new file mode 100644 index 0000000..507c766 --- /dev/null +++ b/math/Fibonacci_Sequence.py @@ -0,0 +1,12 @@ +# Fibonacci Sequence + +if __name__ == '__main__': + f = [0, 1] + index1=0 + index2=1 + fibonacci_len = 10 # Lenght of Fibonacci Sequence + for n in range(fibonacci_len): + val = f[index1+n]+f[index2+n] + f.append(val) + f.pop(0) + print f From 0a155b758cb5bbb2e7c437c33845824f61d4c3e6 Mon Sep 17 00:00:00 2001 From: crysoar <67792666+crysoar@users.noreply.github.com> Date: Sat, 3 Oct 2020 13:11:11 +0530 Subject: [PATCH 54/88] Added Sieve Of Eratosthenes to algorithms -> math This is my first time adding committing anything to Open Source so do let me know if I'm doing anything wrong. --- algorithms/math/SieveOfEratosthenes.py | 31 ++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 algorithms/math/SieveOfEratosthenes.py diff --git a/algorithms/math/SieveOfEratosthenes.py b/algorithms/math/SieveOfEratosthenes.py new file mode 100644 index 0000000..8fbb1ba --- /dev/null +++ b/algorithms/math/SieveOfEratosthenes.py @@ -0,0 +1,31 @@ +import math + + +def sieve(number): # taking a number as input and we'll find all prime values below it + primes = [0] * number + primes[0] = primes[1] = 1 # initialise 0 and 1 to not prime numbers + for prime in range(2, int(math.sqrt(len(primes)))): + if primes[prime] == 0: + for y in range(prime * 2, len(primes), prime): + primes[y] = 1 + else: + pass + + return primes + + +while True: # take input and reject any non integer inputs + try: + num = int(input("Type in a number: ")) + break + + except ValueError: + print("Type in an integer!") + +nums = sieve(num) + +for num in range(len(nums)): + if nums[num] == 0: + print(num) + else: + pass From 756e04c37b540a2239e33e530030df662495681c Mon Sep 17 00:00:00 2001 From: ayushijain218 Date: Sat, 3 Oct 2020 22:41:52 +0530 Subject: [PATCH 55/88] Added Armstrong Number --- math/armstrong_number.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 math/armstrong_number.py diff --git a/math/armstrong_number.py b/math/armstrong_number.py new file mode 100644 index 0000000..4a37b0a --- /dev/null +++ b/math/armstrong_number.py @@ -0,0 +1,18 @@ +def armstrong(number): + l1=list(number) + Sum=0 + order=len(l1) + for i in l1: + Sum+=(int(i)**order) + + if Sum==int(number): + + print(number,"is an Armstrong number") + else: + + print(number,"is not an Armstrong number") + + + +number=input("Enter the number to check for Armstrong : ") +armstrong(number) \ No newline at end of file From 6bc9c84fa22087f3c4db570831532aac7a8c1167 Mon Sep 17 00:00:00 2001 From: MANYAJAIN195 Date: Sat, 3 Oct 2020 22:56:01 +0530 Subject: [PATCH 56/88] add factorial program --- math/factorial.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 math/factorial.py diff --git a/math/factorial.py b/math/factorial.py new file mode 100644 index 0000000..ac732ea --- /dev/null +++ b/math/factorial.py @@ -0,0 +1,21 @@ +''' +To find factorial of a number +''' +def factorial(num): #recursive function + if num==1 or num==0: + return 1 + else: + return factorial(num-1)*num #function calling itself + +num=int(input("Enter the number to find factorial:")) +''' +To check whether the number inputted is positive or not +''' +while num<0: + print("INVALID INPUT !") + num=int(input("Enter the number to find factorial:")) +''' +function calling +''' +x=factorial(num) +print("Factorial of ",num," is ",x) \ No newline at end of file From f1e1ce3e6a7c8c9bdc9ac028e71eba4e71f3369f Mon Sep 17 00:00:00 2001 From: Abraham Hernandez Date: Sun, 4 Oct 2020 02:05:11 -0400 Subject: [PATCH 57/88] cleanup --- .../data-structures}/binarySerach.py | 0 .../data-structures}/stack/stack.py | 0 .../data-structures}/stacks/node.py | 0 .../data-structures}/stacks/stack.py | 0 .../data-structures}/stacks/stacks.py | 0 .../data-structures}/stacks/test_node.py | 0 .../data-structures}/stacks/test_stack.py | 0 .../data-structures}/trie/trie.py | 0 .../matrix_chain_multiplication.py | 0 {graphs => algorithms/graphs}/Bron-Kerbosch.py | 0 .../linkedlist}/middle_of_linkedlist.py | 0 .../linkedlist}/reverse_linkedlist.py | 0 {math => algorithms/math}/Fibonacci_Sequence.py | 0 {math => algorithms/math}/Sieve of Eratosthenes.py | 0 .../math}/SieveOfEratosthenes_PrimeNumbers.py | 0 {math => algorithms/math}/armstrong_number.py | 0 {math => algorithms/math}/common_divisor_count.py | 0 {math => algorithms/math}/eulerTotient.py | 0 {math => algorithms/math}/extendedEuclidean.py | 0 {math => algorithms/math}/factorial.py | 0 {math => algorithms/math}/fibonacci-recursive.py | 0 {math => algorithms/math}/fibonacci.py | 0 {math => algorithms/math}/gaussfilter.py | 0 {math => algorithms/math}/gcd.py | 0 .../math}/recursive_greatest_common_divisor.py | 0 .../recursion}/Coin-Change-Problem.py | 0 .../searches}/exponential_search.py | 0 .../searches}/fibonacci_search.py | 0 {searches => algorithms/searches}/jump_search.py | 0 {sorting => algorithms/sorting}/shell_sort.py | 0 {strings => algorithms/strings}/change_case.py | 0 .../strings}/word_length_dict.py | 0 math/GCD.py | 14 -------------- 33 files changed, 14 deletions(-) rename {data-structures => algorithms/data-structures}/binarySerach.py (100%) rename {data-structures => algorithms/data-structures}/stack/stack.py (100%) rename {data-structures => algorithms/data-structures}/stacks/node.py (100%) rename {data-structures => algorithms/data-structures}/stacks/stack.py (100%) rename {data-structures => algorithms/data-structures}/stacks/stacks.py (100%) rename {data-structures => algorithms/data-structures}/stacks/test_node.py (100%) rename {data-structures => algorithms/data-structures}/stacks/test_stack.py (100%) rename {data-structures => algorithms/data-structures}/trie/trie.py (100%) rename {dynamic-programming => algorithms/dynamic-programming}/matrix_chain_multiplication.py (100%) rename {graphs => algorithms/graphs}/Bron-Kerbosch.py (100%) rename {linkedlist => algorithms/linkedlist}/middle_of_linkedlist.py (100%) rename {linkedlist => algorithms/linkedlist}/reverse_linkedlist.py (100%) rename {math => algorithms/math}/Fibonacci_Sequence.py (100%) rename {math => algorithms/math}/Sieve of Eratosthenes.py (100%) rename {math => algorithms/math}/SieveOfEratosthenes_PrimeNumbers.py (100%) rename {math => algorithms/math}/armstrong_number.py (100%) rename {math => algorithms/math}/common_divisor_count.py (100%) rename {math => algorithms/math}/eulerTotient.py (100%) rename {math => algorithms/math}/extendedEuclidean.py (100%) rename {math => algorithms/math}/factorial.py (100%) rename {math => algorithms/math}/fibonacci-recursive.py (100%) rename {math => algorithms/math}/fibonacci.py (100%) rename {math => algorithms/math}/gaussfilter.py (100%) rename {math => algorithms/math}/gcd.py (100%) rename {math => algorithms/math}/recursive_greatest_common_divisor.py (100%) rename {recursion => algorithms/recursion}/Coin-Change-Problem.py (100%) rename {searches => algorithms/searches}/exponential_search.py (100%) rename {searches => algorithms/searches}/fibonacci_search.py (100%) rename {searches => algorithms/searches}/jump_search.py (100%) rename {sorting => algorithms/sorting}/shell_sort.py (100%) rename {strings => algorithms/strings}/change_case.py (100%) rename {strings => algorithms/strings}/word_length_dict.py (100%) delete mode 100644 math/GCD.py diff --git a/data-structures/binarySerach.py b/algorithms/data-structures/binarySerach.py similarity index 100% rename from data-structures/binarySerach.py rename to algorithms/data-structures/binarySerach.py diff --git a/data-structures/stack/stack.py b/algorithms/data-structures/stack/stack.py similarity index 100% rename from data-structures/stack/stack.py rename to algorithms/data-structures/stack/stack.py diff --git a/data-structures/stacks/node.py b/algorithms/data-structures/stacks/node.py similarity index 100% rename from data-structures/stacks/node.py rename to algorithms/data-structures/stacks/node.py diff --git a/data-structures/stacks/stack.py b/algorithms/data-structures/stacks/stack.py similarity index 100% rename from data-structures/stacks/stack.py rename to algorithms/data-structures/stacks/stack.py diff --git a/data-structures/stacks/stacks.py b/algorithms/data-structures/stacks/stacks.py similarity index 100% rename from data-structures/stacks/stacks.py rename to algorithms/data-structures/stacks/stacks.py diff --git a/data-structures/stacks/test_node.py b/algorithms/data-structures/stacks/test_node.py similarity index 100% rename from data-structures/stacks/test_node.py rename to algorithms/data-structures/stacks/test_node.py diff --git a/data-structures/stacks/test_stack.py b/algorithms/data-structures/stacks/test_stack.py similarity index 100% rename from data-structures/stacks/test_stack.py rename to algorithms/data-structures/stacks/test_stack.py diff --git a/data-structures/trie/trie.py b/algorithms/data-structures/trie/trie.py similarity index 100% rename from data-structures/trie/trie.py rename to algorithms/data-structures/trie/trie.py diff --git a/dynamic-programming/matrix_chain_multiplication.py b/algorithms/dynamic-programming/matrix_chain_multiplication.py similarity index 100% rename from dynamic-programming/matrix_chain_multiplication.py rename to algorithms/dynamic-programming/matrix_chain_multiplication.py diff --git a/graphs/Bron-Kerbosch.py b/algorithms/graphs/Bron-Kerbosch.py similarity index 100% rename from graphs/Bron-Kerbosch.py rename to algorithms/graphs/Bron-Kerbosch.py diff --git a/linkedlist/middle_of_linkedlist.py b/algorithms/linkedlist/middle_of_linkedlist.py similarity index 100% rename from linkedlist/middle_of_linkedlist.py rename to algorithms/linkedlist/middle_of_linkedlist.py diff --git a/linkedlist/reverse_linkedlist.py b/algorithms/linkedlist/reverse_linkedlist.py similarity index 100% rename from linkedlist/reverse_linkedlist.py rename to algorithms/linkedlist/reverse_linkedlist.py diff --git a/math/Fibonacci_Sequence.py b/algorithms/math/Fibonacci_Sequence.py similarity index 100% rename from math/Fibonacci_Sequence.py rename to algorithms/math/Fibonacci_Sequence.py diff --git a/math/Sieve of Eratosthenes.py b/algorithms/math/Sieve of Eratosthenes.py similarity index 100% rename from math/Sieve of Eratosthenes.py rename to algorithms/math/Sieve of Eratosthenes.py diff --git a/math/SieveOfEratosthenes_PrimeNumbers.py b/algorithms/math/SieveOfEratosthenes_PrimeNumbers.py similarity index 100% rename from math/SieveOfEratosthenes_PrimeNumbers.py rename to algorithms/math/SieveOfEratosthenes_PrimeNumbers.py diff --git a/math/armstrong_number.py b/algorithms/math/armstrong_number.py similarity index 100% rename from math/armstrong_number.py rename to algorithms/math/armstrong_number.py diff --git a/math/common_divisor_count.py b/algorithms/math/common_divisor_count.py similarity index 100% rename from math/common_divisor_count.py rename to algorithms/math/common_divisor_count.py diff --git a/math/eulerTotient.py b/algorithms/math/eulerTotient.py similarity index 100% rename from math/eulerTotient.py rename to algorithms/math/eulerTotient.py diff --git a/math/extendedEuclidean.py b/algorithms/math/extendedEuclidean.py similarity index 100% rename from math/extendedEuclidean.py rename to algorithms/math/extendedEuclidean.py diff --git a/math/factorial.py b/algorithms/math/factorial.py similarity index 100% rename from math/factorial.py rename to algorithms/math/factorial.py diff --git a/math/fibonacci-recursive.py b/algorithms/math/fibonacci-recursive.py similarity index 100% rename from math/fibonacci-recursive.py rename to algorithms/math/fibonacci-recursive.py diff --git a/math/fibonacci.py b/algorithms/math/fibonacci.py similarity index 100% rename from math/fibonacci.py rename to algorithms/math/fibonacci.py diff --git a/math/gaussfilter.py b/algorithms/math/gaussfilter.py similarity index 100% rename from math/gaussfilter.py rename to algorithms/math/gaussfilter.py diff --git a/math/gcd.py b/algorithms/math/gcd.py similarity index 100% rename from math/gcd.py rename to algorithms/math/gcd.py diff --git a/math/recursive_greatest_common_divisor.py b/algorithms/math/recursive_greatest_common_divisor.py similarity index 100% rename from math/recursive_greatest_common_divisor.py rename to algorithms/math/recursive_greatest_common_divisor.py diff --git a/recursion/Coin-Change-Problem.py b/algorithms/recursion/Coin-Change-Problem.py similarity index 100% rename from recursion/Coin-Change-Problem.py rename to algorithms/recursion/Coin-Change-Problem.py diff --git a/searches/exponential_search.py b/algorithms/searches/exponential_search.py similarity index 100% rename from searches/exponential_search.py rename to algorithms/searches/exponential_search.py diff --git a/searches/fibonacci_search.py b/algorithms/searches/fibonacci_search.py similarity index 100% rename from searches/fibonacci_search.py rename to algorithms/searches/fibonacci_search.py diff --git a/searches/jump_search.py b/algorithms/searches/jump_search.py similarity index 100% rename from searches/jump_search.py rename to algorithms/searches/jump_search.py diff --git a/sorting/shell_sort.py b/algorithms/sorting/shell_sort.py similarity index 100% rename from sorting/shell_sort.py rename to algorithms/sorting/shell_sort.py diff --git a/strings/change_case.py b/algorithms/strings/change_case.py similarity index 100% rename from strings/change_case.py rename to algorithms/strings/change_case.py diff --git a/strings/word_length_dict.py b/algorithms/strings/word_length_dict.py similarity index 100% rename from strings/word_length_dict.py rename to algorithms/strings/word_length_dict.py diff --git a/math/GCD.py b/math/GCD.py deleted file mode 100644 index 56e6f20..0000000 --- a/math/GCD.py +++ /dev/null @@ -1,14 +0,0 @@ -def gcd (small, large) : - if (small == 0): - return large - else: - return gcd(large % small, small) - - -gcdList = [[6, 9], [6, 12], [12, 18], [7, 14], [7, 13]] - -for Set in gcdList : - small = Set[0] - large = Set[1] - Gcd=gcd(small, large) - print(f"GCD for {small} and {large} is {Gcd}") \ No newline at end of file From e743b42ab2405bfeb56b8ec242e480915262b7ca Mon Sep 17 00:00:00 2001 From: shivansh2310 Date: Mon, 5 Oct 2020 20:39:06 +0530 Subject: [PATCH 58/88] Added implementation of Hill_cipher In python --- algorithms/cryptography/Hill_cipher.py | 42 ++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 algorithms/cryptography/Hill_cipher.py diff --git a/algorithms/cryptography/Hill_cipher.py b/algorithms/cryptography/Hill_cipher.py new file mode 100644 index 0000000..943c463 --- /dev/null +++ b/algorithms/cryptography/Hill_cipher.py @@ -0,0 +1,42 @@ +import numpy as np +s=list(input("Enter a string")) +c=[] +for i in range(len(s)): + c.append(ord(s[i])-65) + +arr= np.array(c) + +a1=np.transpose(arr) +print(a1) +a1= a1.reshape(3,1) +print(a1.shape) + + +#key input +print("Enter the key for the encryption") +R = int(input("rows:")) +C = int(input("columns:")) +matrix = [] +print("Enter the key:") + +for i in range(R): + a =[] + for j in range(C): + a.append(int(input())) + matrix.append(a) + +for i in range(R): + for j in range(C): + print(matrix[i][j], end = " ") +matrix = np.array(matrix) +print(matrix.shape) +print(matrix[1][1]) + +mul=np.matmul(matrix,a1) +mul = np.array(mul) +print(mul.shape) +print(mul) +for i in range(R): + mul[i]=mul[i]%26 + +print(mul) From 86120d3d5cb7703a8129a941bfea79a5127f8fce Mon Sep 17 00:00:00 2001 From: Vishnu-M Date: Sun, 4 Oct 2020 11:57:09 +0530 Subject: [PATCH 59/88] Added Merge Sort --- algorithms/divide-and-conquer/mergesort.py | 26 ++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 algorithms/divide-and-conquer/mergesort.py diff --git a/algorithms/divide-and-conquer/mergesort.py b/algorithms/divide-and-conquer/mergesort.py new file mode 100644 index 0000000..05e5a0b --- /dev/null +++ b/algorithms/divide-and-conquer/mergesort.py @@ -0,0 +1,26 @@ +def merge(left_subarray,right_subarray): + i,j = 0,0 + result = [] + + while i Date: Sun, 4 Oct 2020 12:12:04 +0530 Subject: [PATCH 60/88] Added Kadanes algorithm for finding Maximum Subarray Sum --- .../dynamic-programming/kadanes_algorithm.py | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 algorithms/dynamic-programming/kadanes_algorithm.py diff --git a/algorithms/dynamic-programming/kadanes_algorithm.py b/algorithms/dynamic-programming/kadanes_algorithm.py new file mode 100644 index 0000000..04cf630 --- /dev/null +++ b/algorithms/dynamic-programming/kadanes_algorithm.py @@ -0,0 +1,27 @@ +def Kadane(array): + partialSum = bestSum = array[0] + fromIndex = toIndex = 0 + + for i in range(1, len(array)): + if array[i] > partialSum + array[i]: + partialSum = array[i] + fromIndex = i + else: + partialSum += array[i] + + if partialSum >= bestSum: + bestSum = partialSum + toIndex = i + + return { + "fromIndex" : fromIndex, + "toIndex" : toIndex, + "bestSum" : bestSum + } + +n = int(input("Enter the size of the array: ")) +print("Input the array") +array = map(int,raw_input().split()) + +kadane = Kadane(array) +print("Sum: %d From: %d To: %d" % (kadane['bestSum'], kadane['fromIndex'], kadane['toIndex'])) \ No newline at end of file From 14630fe008f882d733d6b3d491d5b0376006e047 Mon Sep 17 00:00:00 2001 From: adi0311 <2018308@iiitdmj.ac.in> Date: Mon, 5 Oct 2020 13:59:49 +0530 Subject: [PATCH 61/88] Added Subtree Size --- .../data-structures/trees/size_of_subtree.py | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 algorithms/data-structures/trees/size_of_subtree.py diff --git a/algorithms/data-structures/trees/size_of_subtree.py b/algorithms/data-structures/trees/size_of_subtree.py new file mode 100644 index 0000000..eb594f0 --- /dev/null +++ b/algorithms/data-structures/trees/size_of_subtree.py @@ -0,0 +1,28 @@ +""" + This is an efficient algorithm to find the size of a subtree from every node in O(n) time. + The idea is to use one dfs and first calculate the size of subtree of children of a node recursively. + Then add the size of each subtree of its children to get the size of its subtree. +""" +from collections import defaultdict as dd + + +def dfs(source, parent): + # Initial size of root is 1 + size[source] = 1 + for child in graph[source]: + if child != parent: + # Recursively calculate size of subtree of children nodes + dfs(child, source) + # Adding size of each child's subtree. + size[source] += size[child] + + +size = dd(int) +graph = dd(set) +n = int(input()) +for i in range(n-1): + u, v = map(int, input().split()) + graph[u].add(v) + graph[v].add(u) +dfs(1, 0) +print(size) From 965d88c5d6fd4be8be74406f23435d46869c6fef Mon Sep 17 00:00:00 2001 From: shivansh2310 Date: Mon, 5 Oct 2020 20:39:06 +0530 Subject: [PATCH 62/88] Added implementation of Hill_cipher In python --- algorithms/cryptography/Hill_cipher.py | 42 ++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 algorithms/cryptography/Hill_cipher.py diff --git a/algorithms/cryptography/Hill_cipher.py b/algorithms/cryptography/Hill_cipher.py new file mode 100644 index 0000000..943c463 --- /dev/null +++ b/algorithms/cryptography/Hill_cipher.py @@ -0,0 +1,42 @@ +import numpy as np +s=list(input("Enter a string")) +c=[] +for i in range(len(s)): + c.append(ord(s[i])-65) + +arr= np.array(c) + +a1=np.transpose(arr) +print(a1) +a1= a1.reshape(3,1) +print(a1.shape) + + +#key input +print("Enter the key for the encryption") +R = int(input("rows:")) +C = int(input("columns:")) +matrix = [] +print("Enter the key:") + +for i in range(R): + a =[] + for j in range(C): + a.append(int(input())) + matrix.append(a) + +for i in range(R): + for j in range(C): + print(matrix[i][j], end = " ") +matrix = np.array(matrix) +print(matrix.shape) +print(matrix[1][1]) + +mul=np.matmul(matrix,a1) +mul = np.array(mul) +print(mul.shape) +print(mul) +for i in range(R): + mul[i]=mul[i]%26 + +print(mul) From 741d7e3f5d04d532c2257c07bbe900bf9fd2da3b Mon Sep 17 00:00:00 2001 From: hosein Date: Tue, 8 Oct 2019 22:52:23 +0330 Subject: [PATCH 63/88] add python script binary-search in data-structures --- data-structures/binarySerach.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 data-structures/binarySerach.py diff --git a/data-structures/binarySerach.py b/data-structures/binarySerach.py new file mode 100644 index 0000000..4169aee --- /dev/null +++ b/data-structures/binarySerach.py @@ -0,0 +1,25 @@ +def binSearch(a, x, low, high): + #Return True if target is found in indicated portion of a Python list. + #The search only considers the portion from data[low] to data[high] inclusive. + + if low > high: + return False # interval is empty; no match + else: + mid = (low + high) // 2 + if x == a[mid]: # found a match + return True + elif x < a[mid]: + # recur on the portion left of the middle + return binSearch(a, x, low, mid - 1) + else: + # recur on the portion right of the middle + return binSearch(a, x, mid + 1, high) +a = [5, 10, 15, 20, 25, 30, 40] +x = 20 +low = 0 +high = 6 +result = binSearch(a, x, low, high) +if result: + print("The value ", x, " Found") +else: + print("The value ", x, " Not found") From 55368818daa524ea193eecbb9b5be94730c9476c Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 6 Oct 2020 16:05:55 +0330 Subject: [PATCH 64/88] single_linked_module --- .../linked-lists/singleLinkedModule.py | 97 +++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 data-structures/linked-lists/singleLinkedModule.py diff --git a/data-structures/linked-lists/singleLinkedModule.py b/data-structures/linked-lists/singleLinkedModule.py new file mode 100644 index 0000000..bda9418 --- /dev/null +++ b/data-structures/linked-lists/singleLinkedModule.py @@ -0,0 +1,97 @@ +# The program that creates a single link list of true values +# and implements the actions outlined in the link list. + +class LinkedList: + class ListNode: + def __init__(self, data, next= None): + self.info = data + self.next = next + + def getInfo(self): + return self.info + + def setInfo(self, value): + self.info = value + + def getNext(self): + return self.next + + def setNext(self, ptr): + self.next = ptr #end of listNode class + + def __init__(self): + self.head = None + self.last = None + self.size = 0 + + def __del__(self): + current = self.head + while current: + ptr = current + current = current.next + del ptr + + def getSize(self): + return self.size + def isEmpty(self): + return self.head == None + +#Search Node + + def searchNode(self, data): + if (self.isEmpty()): + return None + else: + ptr = self.head + found = False + while ptr and found is False: + if ptr.getInfo() == data: + found == True + else: + ptr == ptr.getNext() + return ptr + + def insertAtFirst(self, ptr): + self.head = ptr + self.size += 1 + if self.getSize() == 1: + self.last = self.head + return True + + def insertAfterNode(self, ptr): + if (self.isEmpty()): + self.head = self.last = ptr + else: + self.last.next = ptr + self.last = ptr + self.size += 1 + + def deleteNode(self, data): + current = self.head + pre = None + found = False + while current and found is False: + if current.getInfo() == data: + found = True + else: + pre = current + current = current.getNext() + if found: + if current == self.head: #first Node deleted + self.head = current.next + del current + else: + pre.next = current.next + current.next = None + del current #current = None + self.size -= 1 + return found + + def traverse(self): + if (self.isEmpty() != True): + ptr = self.head + while ptr: + print(ptr.info, end = "\n") + ptr = ptr.getNext() + + From 3df093a6681f57a57cffff774c6a5c22d1d61989 Mon Sep 17 00:00:00 2001 From: AryashDubey <70095055+AryashDubey@users.noreply.github.com> Date: Wed, 7 Oct 2020 02:11:06 +0530 Subject: [PATCH 65/88] Create Factorial By Recursion Python.py --- algorithms/recursion/Factorial By Recursion Python.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 algorithms/recursion/Factorial By Recursion Python.py diff --git a/algorithms/recursion/Factorial By Recursion Python.py b/algorithms/recursion/Factorial By Recursion Python.py new file mode 100644 index 0000000..25ec0d6 --- /dev/null +++ b/algorithms/recursion/Factorial By Recursion Python.py @@ -0,0 +1,11 @@ +#FINDING FACTORIAL THROUGH RECURSION +def recursion(n): + if(n==0): + return 1 + else: + return n*recursion(n-1) +a=int(input("Enter The Number You Want The Factorial Of")) #Asking User The Number for the factorial +if(a>=0): # Checking if the Number is positive or not + print(recursion()) +else: + print("Enter Valid Positive Number") From a632c7450b9a19df18d12771d6bd45ae3b605944 Mon Sep 17 00:00:00 2001 From: Yuvraj Singh <71546888+YuvrajSHAD@users.noreply.github.com> Date: Wed, 7 Oct 2020 19:42:36 +0530 Subject: [PATCH 66/88] Added New Data-Structure program the code will Help the user to find same elements in given two arrays by the user. Thank You!! --- data-structures/Array Intersection.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 data-structures/Array Intersection.py diff --git a/data-structures/Array Intersection.py b/data-structures/Array Intersection.py new file mode 100644 index 0000000..86545d5 --- /dev/null +++ b/data-structures/Array Intersection.py @@ -0,0 +1,14 @@ +### Here You can Use this Program For Finding Same elements in two Arrays. +def Array_Inter(arr1,n,arr2,m): ## Here I am Function + for i in range(n) : + for j in range(m) : + if arr1[i] == arr2[j] : + print(arr1[i], end = " ") + break +t=int(input("Test cases: ")) ## take test cases to be run +for k in range(t): + n=int(input("Size of Array One: ")) ## Size of array one by the user + arr1=[int(x) for x in input().split()] ## take inputs from user seperated by space + m=int(input("Size Of Array Two: ")) + arr2=[int(y) for y in input().split()] +Array_Inter(arr1,n,arr2,m) From aef86a870278b380e07bb0808c831e6dbfdfecca Mon Sep 17 00:00:00 2001 From: Eduardo Galeano Date: Wed, 7 Oct 2020 21:46:25 -0500 Subject: [PATCH 67/88] Added recursive optimized exponetiation algorithm. --- algorithms/recursion/exponentiation.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 algorithms/recursion/exponentiation.py diff --git a/algorithms/recursion/exponentiation.py b/algorithms/recursion/exponentiation.py new file mode 100644 index 0000000..2c6cfdc --- /dev/null +++ b/algorithms/recursion/exponentiation.py @@ -0,0 +1,18 @@ + +def exponentiation(baseNumber, power): + answer = None + + if power == 1: + answer = baseNumber + + elif power == 2: + answer = baseNumber * baseNumber + + else: + halfAnswer = exponentiation(baseNumber, power//2) + answer = halfAnswer * halfAnswer + + if power%2 == 1: + answer *= baseNumber + + return answer \ No newline at end of file From a77de02e8492f1e6d0efde04fc12b9c566f79992 Mon Sep 17 00:00:00 2001 From: hinevics Date: Thu, 8 Oct 2020 12:08:18 +0300 Subject: [PATCH 68/88] add algorithm for calculating Levenshtein Distance --- algorithms/strings/levenstein.py | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 algorithms/strings/levenstein.py diff --git a/algorithms/strings/levenstein.py b/algorithms/strings/levenstein.py new file mode 100644 index 0000000..66ad47d --- /dev/null +++ b/algorithms/strings/levenstein.py @@ -0,0 +1,9 @@ +def distance_levenstein(a, b): + f = [[(i+j) if i*j == 0 else 0 for j in range(len(b)+1)] for i in range(len(a) + 1)] + for i in range(1, len(a) + 1): + for j in range(1, len(b) + 1): + if a[i-1] == b[j-1]: + f[i][j] = f[i-1][j-1] + else: + f[i][j] = 1 + min(f[i-1][j], f[i][j-1], f[i-1][j-1]) + return f[len(a)][len(b)] From 1f4e774f6b2fea031e0d905bcdea9ed7cbbae253 Mon Sep 17 00:00:00 2001 From: Eduardo Galeano Date: Thu, 8 Oct 2020 20:33:43 -0500 Subject: [PATCH 69/88] Fixed working for 0 and negative power values. --- algorithms/recursion/exponentiation.py | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/algorithms/recursion/exponentiation.py b/algorithms/recursion/exponentiation.py index 2c6cfdc..5709894 100644 --- a/algorithms/recursion/exponentiation.py +++ b/algorithms/recursion/exponentiation.py @@ -2,17 +2,20 @@ def exponentiation(baseNumber, power): answer = None - if power == 1: - answer = baseNumber - - elif power == 2: - answer = baseNumber * baseNumber - - else: + if power > 1: halfAnswer = exponentiation(baseNumber, power//2) answer = halfAnswer * halfAnswer if power%2 == 1: answer *= baseNumber - return answer \ No newline at end of file + elif power == 1: + answer = baseNumber + + elif power == 0: + answer = 1 + + else: # negative power + answer = 1 / exponentiation(baseNumber, abs(power)) + + return answer From ebd5e4356a7ffca77efccae08fbb8c11cf4d4cd9 Mon Sep 17 00:00:00 2001 From: Gaurav Dubey <56021774+gauravdubey110@users.noreply.github.com> Date: Mon, 12 Oct 2020 08:40:20 +0530 Subject: [PATCH 70/88] Create Fibonacci-Series-by-python.py This program creates user defined Fibonacci series using recursion --- algorithms/recursion/Fibonacci-Series-by-python.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 algorithms/recursion/Fibonacci-Series-by-python.py diff --git a/algorithms/recursion/Fibonacci-Series-by-python.py b/algorithms/recursion/Fibonacci-Series-by-python.py new file mode 100644 index 0000000..33bf3a3 --- /dev/null +++ b/algorithms/recursion/Fibonacci-Series-by-python.py @@ -0,0 +1,13 @@ + +### Program to calculate fibonacci series + +def fibo(n): // function to calculate fibonacci series + if(n == 0): + return 0 + elif(n == 1): + return 1 + else: + return(fibo(n-1) + fibo(n-2)) +num = int(input("Enter a number: ")) // enter number upto which you want to calculate fibonacci series +for n in range(0,(num+1)): + print(fibo(n),end=" ") From 337e3003d9305a14e7ad0cb3b44d86b4feefaaac Mon Sep 17 00:00:00 2001 From: Nithya-Prakash Date: Tue, 13 Oct 2020 15:08:02 +0530 Subject: [PATCH 71/88] added is_palindrome --- data-structures/linked-lists/is_palindrome.py | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 data-structures/linked-lists/is_palindrome.py diff --git a/data-structures/linked-lists/is_palindrome.py b/data-structures/linked-lists/is_palindrome.py new file mode 100644 index 0000000..22c93ce --- /dev/null +++ b/data-structures/linked-lists/is_palindrome.py @@ -0,0 +1,72 @@ +def is_palindrome(head): + if not head: + return True + fast, slow = head.next, head + while fast and fast.next: + fast = fast.next.next + slow = slow.next + second = slow.next + node = None + while second: + nxt = second.next + second.next = node + node = second + second = nxt + while node: + if node.val != head.val: + return False + node = node.next + head = head.next + return True + + +def is_palindrome_stack(head): + if not head or not head.next: + return True + + # Get the midpoint + slow = fast = cur = head + while fast and fast.next: + fast, slow = fast.next.next, slow.next + + # Push the second half into the stack + stack = [slow.val] + while slow.next: + slow = slow.next + stack.append(slow.val) + + # Comparison + while stack: + if stack.pop() != cur.val: + return False + cur = cur.next + + return True + + +def is_palindrome_dict(head): + if not head or not head.next: + return True + d = {} + pos = 0 + while head: + if head.val in d.keys(): + d[head.val].append(pos) + else: + d[head.val] = [pos] + head = head.next + pos += 1 + checksum = pos - 1 + middle = 0 + for v in d.values(): + if len(v) % 2 != 0: + middle += 1 + else: + step = 0 + for i in range(0, len(v)): + if v[i] + v[len(v) - 1 - step] != checksum: + return False + step += 1 + if middle > 1: + return False + return True From f481d6a2cac8e8a03886e3ceb7ffe818abebe6ae Mon Sep 17 00:00:00 2001 From: Madhav Mishra <59422042+carbseater@users.noreply.github.com> Date: Fri, 16 Oct 2020 19:34:33 +0530 Subject: [PATCH 72/88] Find length of linked list --- algorithms/linkedlist/find_length_linkedList | 56 ++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 algorithms/linkedlist/find_length_linkedList diff --git a/algorithms/linkedlist/find_length_linkedList b/algorithms/linkedlist/find_length_linkedList new file mode 100644 index 0000000..7fe4cf7 --- /dev/null +++ b/algorithms/linkedlist/find_length_linkedList @@ -0,0 +1,56 @@ +# A complete working Python program to find length of a +# Linked List iteratively + +# Node class +class Node: + # Function to initialise the node object + def __init__(self, data): + self.data = data # Assign data + self.next = None # Initialize next as null + + +# Linked List class contains a Node object +class LinkedList: + + # Function to initialize head + def __init__(self): + self.head = None + + + # This function is in LinkedList class. It inserts + # a new node at the beginning of Linked List. + def push(self, new_data): + + # 1 & 2: Allocate the Node & + # Put in the data + new_node = Node(new_data) + + # 3. Make next of new Node as head + new_node.next = self.head + + # 4. Move the head to point to new Node + self.head = new_node + + + # This function counts number of nodes in Linked List + # iteratively, given 'node' as starting node. + def getCount(self): + temp = self.head # Initialise temp + count = 0 # Initialise count + + # Loop while end of linked list is not reached + while (temp): + count += 1 + temp = temp.next + return count + + +# Code execution starts here +if __name__=='__main__': + llist = LinkedList() + llist.push(1) + llist.push(3) + llist.push(1) + llist.push(2) + llist.push(1) + print ("Count of nodes is :",llist.getCount()) From d681e0970bca7328dc03ccee0100b843427887b9 Mon Sep 17 00:00:00 2001 From: yashaswiadyalu Date: Sun, 18 Oct 2020 20:05:46 +0530 Subject: [PATCH 73/88] code for circulardoublylinkedlist --- .../linked-lists/circulardoublylinkedlist.py | 109 ++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 data-structures/linked-lists/circulardoublylinkedlist.py diff --git a/data-structures/linked-lists/circulardoublylinkedlist.py b/data-structures/linked-lists/circulardoublylinkedlist.py new file mode 100644 index 0000000..eef2769 --- /dev/null +++ b/data-structures/linked-lists/circulardoublylinkedlist.py @@ -0,0 +1,109 @@ +class Node: + def __init__(self, data): + self.data = data + self.next = None + self.prev = None + + +class CircularDoublyLinkedList: + def __init__(self): + self.first = None + + def get_node(self, index): + current = self.first + for i in range(index): + current = current.next + if current == self.first: + return None + return current + + def insert_after(self, ref_node, new_node): + new_node.prev = ref_node + new_node.next = ref_node.next + new_node.next.prev = new_node + ref_node.next = new_node + + def insert_before(self, ref_node, new_node): + self.insert_after(ref_node.prev, new_node) + + def insert_at_end(self, new_node): + if self.first is None: + self.first = new_node + new_node.next = new_node + new_node.prev = new_node + else: + self.insert_after(self.first.prev, new_node) + + def insert_at_beg(self, new_node): + self.insert_at_end(new_node) + self.first = new_node + + def remove(self, node): + if self.first.next == self.first: + self.first = None + else: + node.prev.next = node.next + node.next.prev = node.prev + if self.first == node: + self.first = node.next + + def display(self): + if self.first is None: + return + current = self.first + while True: + print(current.data, end = ' ') + current = current.next + if current == self.first: + break + + +a_cdllist = CircularDoublyLinkedList() + +print('Menu') +print('insert after ') +print('insert before ') +print('insert at beg') +print('insert at end') +print('remove ') +print('quit') + +while True: + print('The list: ', end = '') + a_cdllist.display() + print() + do = input('What would you like to do? ').split() + + operation = do[0].strip().lower() + + if operation == 'insert': + data = int(do[1]) + position = do[3].strip().lower() + new_node = Node(data) + suboperation = do[2].strip().lower() + if suboperation == 'at': + if position == 'beg': + a_cdllist.insert_at_beg(new_node) + elif position == 'end': + a_cdllist.insert_at_end(new_node) + else: + index = int(position) + ref_node = a_cdllist.get_node(index) + if ref_node is None: + print('No such index.') + continue + if suboperation == 'after': + a_cdllist.insert_after(ref_node, new_node) + elif suboperation == 'before': + a_cdllist.insert_before(ref_node, new_node) + + elif operation == 'remove': + index = int(do[1]) + node = a_cdllist.get_node(index) + if node is None: + print('No such index.') + continue + a_cdllist.remove(node) + + elif operation == 'quit': + break \ No newline at end of file From f05173438f6340e07af916fa77cf5a88ffcdda8e Mon Sep 17 00:00:00 2001 From: yashaswiadyalu Date: Sun, 18 Oct 2020 20:49:05 +0530 Subject: [PATCH 74/88] code for dequeue --- data-structures/dequeue.py | 48 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 data-structures/dequeue.py diff --git a/data-structures/dequeue.py b/data-structures/dequeue.py new file mode 100644 index 0000000..884c698 --- /dev/null +++ b/data-structures/dequeue.py @@ -0,0 +1,48 @@ +class Dequeue: + def __init__(self): + self.items = [] + + def is_empty(self): + return self.items == [] + + def append(self, data): + self.items.append(data) + + def append_left(self, data): + self.items.insert(0, data) + + def pop(self): + return self.items.pop() + + def pop_left(self): + return self.items.pop(0) + + +q = Dequeue() +print('Menu') +print('append ') +print('appendleft ') +print('pop') +print('popleft') +print('quit') + +while True: + do = input('What would you like to do? ').split() + + operation = do[0].strip().lower() + if operation == 'append': + q.append(int(do[1])) + elif operation == 'appendleft': + q.append_left(int(do[1])) + elif operation == 'pop': + if q.is_empty(): + print('Dequeue is empty.') + else: + print('Popped value from right: ', q.pop()) + elif operation == 'popleft': + if q.is_empty(): + print('Dequeue is empty.') + else: + print('Popped value from left: ', q.pop_left()) + elif operation == 'quit': + break \ No newline at end of file From ad7fd094659999374d9688337d4f036d134b1874 Mon Sep 17 00:00:00 2001 From: yashaswiadyalu Date: Sun, 18 Oct 2020 22:42:14 +0530 Subject: [PATCH 75/88] Insertion and deletion in cicrcular single linked list --- .../linked-lists/circularsinglelinkedlist.py | 116 ++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 data-structures/linked-lists/circularsinglelinkedlist.py diff --git a/data-structures/linked-lists/circularsinglelinkedlist.py b/data-structures/linked-lists/circularsinglelinkedlist.py new file mode 100644 index 0000000..45fd10e --- /dev/null +++ b/data-structures/linked-lists/circularsinglelinkedlist.py @@ -0,0 +1,116 @@ +class Node: + def __init__(self, data): + self.data = data + self.next = None + + +class CircularLinkedList: + def __init__(self): + self.head = None + + def get_node(self, index): + if self.head is None: + return None + current = self.head + for i in range(index): + current = current.next + if current == self.head: + return None + return current + + def get_prev_node(self, ref_node): + if self.head is None: + return None + current = self.head + while current.next != ref_node: + current = current.next + return current + + def insert_after(self, ref_node, new_node): + new_node.next = ref_node.next + ref_node.next = new_node + + def insert_before(self, ref_node, new_node): + prev_node = self.get_prev_node(ref_node) + self.insert_after(prev_node, new_node) + + def insert_at_end(self, new_node): + if self.head is None: + self.head = new_node + new_node.next = new_node + else: + self.insert_before(self.head, new_node) + + def insert_at_beg(self, new_node): + self.insert_at_end(new_node) + self.head = new_node + + def remove(self, node): + if self.head.next == self.head: + self.head = None + else: + prev_node = self.get_prev_node(node) + prev_node.next = node.next + if self.head == node: + self.head = node.next + + def display(self): + if self.head is None: + return + current = self.head + while True: + print(current.data, end = ' ') + current = current.next + if current == self.head: + break + + +a_cllist = CircularLinkedList() + +print('Menu') +print('insert after ') +print('insert before ') +print('insert at beg') +print('insert at end') +print('remove ') +print('quit') + +while True: + print('The list: ', end = '') + a_cllist.display() + print() + do = input('What would you like to do? ').split() + + operation = do[0].strip().lower() + + if operation == 'insert': + data = int(do[1]) + position = do[3].strip().lower() + new_node = Node(data) + suboperation = do[2].strip().lower() + if suboperation == 'at': + if position == 'beg': + a_cllist.insert_at_beg(new_node) + elif position == 'end': + a_cllist.insert_at_end(new_node) + else: + index = int(position) + ref_node = a_cllist.get_node(index) + if ref_node is None: + print('No such index.') + continue + if suboperation == 'after': + a_cllist.insert_after(ref_node, new_node) + elif suboperation == 'before': + a_cllist.insert_before(ref_node, new_node) + + elif operation == 'remove': + index = int(do[1]) + node = a_cllist.get_node(index) + if node is None: + print('No such index.') + continue + a_cllist.remove(node) + + elif operation == 'quit': + break \ No newline at end of file From f12050990c064f20d27947084edd3ce57863efb6 Mon Sep 17 00:00:00 2001 From: Yashaswi A <59396277+yashaswiadyalu@users.noreply.github.com> Date: Sun, 18 Oct 2020 22:57:35 +0530 Subject: [PATCH 76/88] Delete circularsinglelinkedlist.py --- .../linked-lists/circularsinglelinkedlist.py | 116 ------------------ 1 file changed, 116 deletions(-) delete mode 100644 data-structures/linked-lists/circularsinglelinkedlist.py diff --git a/data-structures/linked-lists/circularsinglelinkedlist.py b/data-structures/linked-lists/circularsinglelinkedlist.py deleted file mode 100644 index 45fd10e..0000000 --- a/data-structures/linked-lists/circularsinglelinkedlist.py +++ /dev/null @@ -1,116 +0,0 @@ -class Node: - def __init__(self, data): - self.data = data - self.next = None - - -class CircularLinkedList: - def __init__(self): - self.head = None - - def get_node(self, index): - if self.head is None: - return None - current = self.head - for i in range(index): - current = current.next - if current == self.head: - return None - return current - - def get_prev_node(self, ref_node): - if self.head is None: - return None - current = self.head - while current.next != ref_node: - current = current.next - return current - - def insert_after(self, ref_node, new_node): - new_node.next = ref_node.next - ref_node.next = new_node - - def insert_before(self, ref_node, new_node): - prev_node = self.get_prev_node(ref_node) - self.insert_after(prev_node, new_node) - - def insert_at_end(self, new_node): - if self.head is None: - self.head = new_node - new_node.next = new_node - else: - self.insert_before(self.head, new_node) - - def insert_at_beg(self, new_node): - self.insert_at_end(new_node) - self.head = new_node - - def remove(self, node): - if self.head.next == self.head: - self.head = None - else: - prev_node = self.get_prev_node(node) - prev_node.next = node.next - if self.head == node: - self.head = node.next - - def display(self): - if self.head is None: - return - current = self.head - while True: - print(current.data, end = ' ') - current = current.next - if current == self.head: - break - - -a_cllist = CircularLinkedList() - -print('Menu') -print('insert after ') -print('insert before ') -print('insert at beg') -print('insert at end') -print('remove ') -print('quit') - -while True: - print('The list: ', end = '') - a_cllist.display() - print() - do = input('What would you like to do? ').split() - - operation = do[0].strip().lower() - - if operation == 'insert': - data = int(do[1]) - position = do[3].strip().lower() - new_node = Node(data) - suboperation = do[2].strip().lower() - if suboperation == 'at': - if position == 'beg': - a_cllist.insert_at_beg(new_node) - elif position == 'end': - a_cllist.insert_at_end(new_node) - else: - index = int(position) - ref_node = a_cllist.get_node(index) - if ref_node is None: - print('No such index.') - continue - if suboperation == 'after': - a_cllist.insert_after(ref_node, new_node) - elif suboperation == 'before': - a_cllist.insert_before(ref_node, new_node) - - elif operation == 'remove': - index = int(do[1]) - node = a_cllist.get_node(index) - if node is None: - print('No such index.') - continue - a_cllist.remove(node) - - elif operation == 'quit': - break \ No newline at end of file From ff3385a78f0ac242f87edea92712e94f620759b1 Mon Sep 17 00:00:00 2001 From: Yashaswi A <59396277+yashaswiadyalu@users.noreply.github.com> Date: Sun, 18 Oct 2020 23:02:24 +0530 Subject: [PATCH 77/88] insertion and deletion in circular SLL --- .../linked-lists/circularsinglelinkedlist.py | 116 ++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 data-structures/linked-lists/circularsinglelinkedlist.py diff --git a/data-structures/linked-lists/circularsinglelinkedlist.py b/data-structures/linked-lists/circularsinglelinkedlist.py new file mode 100644 index 0000000..1ef3c6e --- /dev/null +++ b/data-structures/linked-lists/circularsinglelinkedlist.py @@ -0,0 +1,116 @@ +class Node: + def __init__(self, data): + self.data = data + self.next = None + + +class CircularLinkedList: + def __init__(self): + self.head = None + + def get_node(self, index): + if self.head is None: + return None + current = self.head + for i in range(index): + current = current.next + if current == self.head: + return None + return current + + def get_prev_node(self, ref_node): + if self.head is None: + return None + current = self.head + while current.next != ref_node: + current = current.next + return current + + def insert_after(self, ref_node, new_node): + new_node.next = ref_node.next + ref_node.next = new_node + + def insert_before(self, ref_node, new_node): + prev_node = self.get_prev_node(ref_node) + self.insert_after(prev_node, new_node) + + def insert_at_end(self, new_node): + if self.head is None: + self.head = new_node + new_node.next = new_node + else: + self.insert_before(self.head, new_node) + + def insert_at_beg(self, new_node): + self.insert_at_end(new_node) + self.head = new_node + + def remove(self, node): + if self.head.next == self.head: + self.head = None + else: + prev_node = self.get_prev_node(node) + prev_node.next = node.next + if self.head == node: + self.head = node.next + + def display(self): + if self.head is None: + return + current = self.head + while True: + print(current.data, end = ' ') + current = current.next + if current == self.head: + break + + +a_cllist = CircularLinkedList() + +print('Menu') +print('insert after ') +print('insert before ') +print('insert at beg') +print('insert at end') +print('remove ') +print('quit') + +while True: + print('The list: ', end = '') + a_cllist.display() + print() + do = input('What would you like to do? ').split() + + operation = do[0].strip().lower() + + if operation == 'insert': + data = int(do[1]) + position = do[3].strip().lower() + new_node = Node(data) + suboperation = do[2].strip().lower() + if suboperation == 'at': + if position == 'beg': + a_cllist.insert_at_beg(new_node) + elif position == 'end': + a_cllist.insert_at_end(new_node) + else: + index = int(position) + ref_node = a_cllist.get_node(index) + if ref_node is None: + print('No such index.') + continue + if suboperation == 'after': + a_cllist.insert_after(ref_node, new_node) + elif suboperation == 'before': + a_cllist.insert_before(ref_node, new_node) + + elif operation == 'remove': + index = int(do[1]) + node = a_cllist.get_node(index) + if node is None: + print('No such index.') + continue + a_cllist.remove(node) + + elif operation == 'quit': + break \ No newline at end of file From d57fbd5bd50940831ef04ab62544732b108d189e Mon Sep 17 00:00:00 2001 From: Yashaswi A <59396277+yashaswiadyalu@users.noreply.github.com> Date: Mon, 19 Oct 2020 12:33:09 +0530 Subject: [PATCH 78/88] Delete circulardoublylinkedlist.py --- .../linked-lists/circulardoublylinkedlist.py | 109 ------------------ 1 file changed, 109 deletions(-) delete mode 100644 data-structures/linked-lists/circulardoublylinkedlist.py diff --git a/data-structures/linked-lists/circulardoublylinkedlist.py b/data-structures/linked-lists/circulardoublylinkedlist.py deleted file mode 100644 index eef2769..0000000 --- a/data-structures/linked-lists/circulardoublylinkedlist.py +++ /dev/null @@ -1,109 +0,0 @@ -class Node: - def __init__(self, data): - self.data = data - self.next = None - self.prev = None - - -class CircularDoublyLinkedList: - def __init__(self): - self.first = None - - def get_node(self, index): - current = self.first - for i in range(index): - current = current.next - if current == self.first: - return None - return current - - def insert_after(self, ref_node, new_node): - new_node.prev = ref_node - new_node.next = ref_node.next - new_node.next.prev = new_node - ref_node.next = new_node - - def insert_before(self, ref_node, new_node): - self.insert_after(ref_node.prev, new_node) - - def insert_at_end(self, new_node): - if self.first is None: - self.first = new_node - new_node.next = new_node - new_node.prev = new_node - else: - self.insert_after(self.first.prev, new_node) - - def insert_at_beg(self, new_node): - self.insert_at_end(new_node) - self.first = new_node - - def remove(self, node): - if self.first.next == self.first: - self.first = None - else: - node.prev.next = node.next - node.next.prev = node.prev - if self.first == node: - self.first = node.next - - def display(self): - if self.first is None: - return - current = self.first - while True: - print(current.data, end = ' ') - current = current.next - if current == self.first: - break - - -a_cdllist = CircularDoublyLinkedList() - -print('Menu') -print('insert after ') -print('insert before ') -print('insert at beg') -print('insert at end') -print('remove ') -print('quit') - -while True: - print('The list: ', end = '') - a_cdllist.display() - print() - do = input('What would you like to do? ').split() - - operation = do[0].strip().lower() - - if operation == 'insert': - data = int(do[1]) - position = do[3].strip().lower() - new_node = Node(data) - suboperation = do[2].strip().lower() - if suboperation == 'at': - if position == 'beg': - a_cdllist.insert_at_beg(new_node) - elif position == 'end': - a_cdllist.insert_at_end(new_node) - else: - index = int(position) - ref_node = a_cdllist.get_node(index) - if ref_node is None: - print('No such index.') - continue - if suboperation == 'after': - a_cdllist.insert_after(ref_node, new_node) - elif suboperation == 'before': - a_cdllist.insert_before(ref_node, new_node) - - elif operation == 'remove': - index = int(do[1]) - node = a_cdllist.get_node(index) - if node is None: - print('No such index.') - continue - a_cdllist.remove(node) - - elif operation == 'quit': - break \ No newline at end of file From e090edae3ac0529140f57024cc85899683b4f517 Mon Sep 17 00:00:00 2001 From: kmehuly <72296700+kmehuly@users.noreply.github.com> Date: Fri, 16 Oct 2020 14:34:51 +0530 Subject: [PATCH 79/88] Create InorderTreeTraversal.py --- data-structures/InorderTreeTraversal.py | 50 +++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 data-structures/InorderTreeTraversal.py diff --git a/data-structures/InorderTreeTraversal.py b/data-structures/InorderTreeTraversal.py new file mode 100644 index 0000000..4929c7c --- /dev/null +++ b/data-structures/InorderTreeTraversal.py @@ -0,0 +1,50 @@ +class Node: + """A binary tree node""" + def __init__(self, data, left=None, right=None): + self.data = data + self.left = left + self.right = right + + +def morris_traversal(root): + """Generator function for iterative inorder tree traversal""" + + current = root + + while current is not None: + + if current.left is None: + yield current.data + current = current.right + else: + + # Find the inorder predecessor of current + pre = current.left + while pre.right is not None and pre.right is not current: + pre = pre.right + + if pre.right is None: + + # Make current as right child of its inorder predecessor + pre.right = current + current = current.left + + else: + # Revert the changes made in the 'if' part to restore the + # original tree. i.e., fix the right child of predecessor + pre.right = None + yield current.data + current = current.right + +# Driver program to test the above function + +root = Node(1, + right = Node(3), + left = Node(2, + left = Node(4), + right = Node(5) + ) + ) + +for v in morris_traversal(root): + print(v, end=' ') From 890eca9abe04b8fa21c732a8db1a68d1632df934 Mon Sep 17 00:00:00 2001 From: panos21kyr Date: Fri, 16 Oct 2020 23:21:33 +0300 Subject: [PATCH 80/88] add cocktail_sort --- algorithms/sorting/cocktail_sort.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 algorithms/sorting/cocktail_sort.py diff --git a/algorithms/sorting/cocktail_sort.py b/algorithms/sorting/cocktail_sort.py new file mode 100644 index 0000000..71f7b38 --- /dev/null +++ b/algorithms/sorting/cocktail_sort.py @@ -0,0 +1,26 @@ +def cocktailSort(array) + n = len(array) + swap = 1 + begin = 0 + end = n-1 + #Sorting start + while (swap == 1): + swap = 0 + + #sorting from begin + for i in range (begin, end): + if (a[i] > a[i+1]) : + a[i], a[i+1]= a[i+1], a[i] + swap=1 + + if (swap==0): + break swap = 0 + + end = end-1 + #sorting from end + for i in range(end-1, begin-1,-1): + if (a[i] > a[i+1]): + a[i], a[i+1] = a[i+1], a[i] + swap = 1 + + begin = begin+1 \ No newline at end of file From 14745bf6220229bf1c6c26666634557d53881661 Mon Sep 17 00:00:00 2001 From: yashaswiadyalu Date: Sun, 18 Oct 2020 20:05:46 +0530 Subject: [PATCH 81/88] code for circulardoublylinkedlist --- .../linked-lists/circulardoublylinkedlist.py | 109 ++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 data-structures/linked-lists/circulardoublylinkedlist.py diff --git a/data-structures/linked-lists/circulardoublylinkedlist.py b/data-structures/linked-lists/circulardoublylinkedlist.py new file mode 100644 index 0000000..eef2769 --- /dev/null +++ b/data-structures/linked-lists/circulardoublylinkedlist.py @@ -0,0 +1,109 @@ +class Node: + def __init__(self, data): + self.data = data + self.next = None + self.prev = None + + +class CircularDoublyLinkedList: + def __init__(self): + self.first = None + + def get_node(self, index): + current = self.first + for i in range(index): + current = current.next + if current == self.first: + return None + return current + + def insert_after(self, ref_node, new_node): + new_node.prev = ref_node + new_node.next = ref_node.next + new_node.next.prev = new_node + ref_node.next = new_node + + def insert_before(self, ref_node, new_node): + self.insert_after(ref_node.prev, new_node) + + def insert_at_end(self, new_node): + if self.first is None: + self.first = new_node + new_node.next = new_node + new_node.prev = new_node + else: + self.insert_after(self.first.prev, new_node) + + def insert_at_beg(self, new_node): + self.insert_at_end(new_node) + self.first = new_node + + def remove(self, node): + if self.first.next == self.first: + self.first = None + else: + node.prev.next = node.next + node.next.prev = node.prev + if self.first == node: + self.first = node.next + + def display(self): + if self.first is None: + return + current = self.first + while True: + print(current.data, end = ' ') + current = current.next + if current == self.first: + break + + +a_cdllist = CircularDoublyLinkedList() + +print('Menu') +print('insert after ') +print('insert before ') +print('insert at beg') +print('insert at end') +print('remove ') +print('quit') + +while True: + print('The list: ', end = '') + a_cdllist.display() + print() + do = input('What would you like to do? ').split() + + operation = do[0].strip().lower() + + if operation == 'insert': + data = int(do[1]) + position = do[3].strip().lower() + new_node = Node(data) + suboperation = do[2].strip().lower() + if suboperation == 'at': + if position == 'beg': + a_cdllist.insert_at_beg(new_node) + elif position == 'end': + a_cdllist.insert_at_end(new_node) + else: + index = int(position) + ref_node = a_cdllist.get_node(index) + if ref_node is None: + print('No such index.') + continue + if suboperation == 'after': + a_cdllist.insert_after(ref_node, new_node) + elif suboperation == 'before': + a_cdllist.insert_before(ref_node, new_node) + + elif operation == 'remove': + index = int(do[1]) + node = a_cdllist.get_node(index) + if node is None: + print('No such index.') + continue + a_cdllist.remove(node) + + elif operation == 'quit': + break \ No newline at end of file From 8a2ff795a4b6a3d90530e9fa09adcc8b717f641e Mon Sep 17 00:00:00 2001 From: yashaswiadyalu Date: Sun, 18 Oct 2020 20:49:05 +0530 Subject: [PATCH 82/88] code for dequeue --- data-structures/dequeue.py | 48 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 data-structures/dequeue.py diff --git a/data-structures/dequeue.py b/data-structures/dequeue.py new file mode 100644 index 0000000..884c698 --- /dev/null +++ b/data-structures/dequeue.py @@ -0,0 +1,48 @@ +class Dequeue: + def __init__(self): + self.items = [] + + def is_empty(self): + return self.items == [] + + def append(self, data): + self.items.append(data) + + def append_left(self, data): + self.items.insert(0, data) + + def pop(self): + return self.items.pop() + + def pop_left(self): + return self.items.pop(0) + + +q = Dequeue() +print('Menu') +print('append ') +print('appendleft ') +print('pop') +print('popleft') +print('quit') + +while True: + do = input('What would you like to do? ').split() + + operation = do[0].strip().lower() + if operation == 'append': + q.append(int(do[1])) + elif operation == 'appendleft': + q.append_left(int(do[1])) + elif operation == 'pop': + if q.is_empty(): + print('Dequeue is empty.') + else: + print('Popped value from right: ', q.pop()) + elif operation == 'popleft': + if q.is_empty(): + print('Dequeue is empty.') + else: + print('Popped value from left: ', q.pop_left()) + elif operation == 'quit': + break \ No newline at end of file From aa27330575aa4b09db3f4adc2cba4e50996b2671 Mon Sep 17 00:00:00 2001 From: yashaswiadyalu Date: Sun, 18 Oct 2020 22:42:14 +0530 Subject: [PATCH 83/88] Insertion and deletion in cicrcular single linked list --- .../linked-lists/circularsinglelinkedlist.py | 116 ++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 data-structures/linked-lists/circularsinglelinkedlist.py diff --git a/data-structures/linked-lists/circularsinglelinkedlist.py b/data-structures/linked-lists/circularsinglelinkedlist.py new file mode 100644 index 0000000..45fd10e --- /dev/null +++ b/data-structures/linked-lists/circularsinglelinkedlist.py @@ -0,0 +1,116 @@ +class Node: + def __init__(self, data): + self.data = data + self.next = None + + +class CircularLinkedList: + def __init__(self): + self.head = None + + def get_node(self, index): + if self.head is None: + return None + current = self.head + for i in range(index): + current = current.next + if current == self.head: + return None + return current + + def get_prev_node(self, ref_node): + if self.head is None: + return None + current = self.head + while current.next != ref_node: + current = current.next + return current + + def insert_after(self, ref_node, new_node): + new_node.next = ref_node.next + ref_node.next = new_node + + def insert_before(self, ref_node, new_node): + prev_node = self.get_prev_node(ref_node) + self.insert_after(prev_node, new_node) + + def insert_at_end(self, new_node): + if self.head is None: + self.head = new_node + new_node.next = new_node + else: + self.insert_before(self.head, new_node) + + def insert_at_beg(self, new_node): + self.insert_at_end(new_node) + self.head = new_node + + def remove(self, node): + if self.head.next == self.head: + self.head = None + else: + prev_node = self.get_prev_node(node) + prev_node.next = node.next + if self.head == node: + self.head = node.next + + def display(self): + if self.head is None: + return + current = self.head + while True: + print(current.data, end = ' ') + current = current.next + if current == self.head: + break + + +a_cllist = CircularLinkedList() + +print('Menu') +print('insert after ') +print('insert before ') +print('insert at beg') +print('insert at end') +print('remove ') +print('quit') + +while True: + print('The list: ', end = '') + a_cllist.display() + print() + do = input('What would you like to do? ').split() + + operation = do[0].strip().lower() + + if operation == 'insert': + data = int(do[1]) + position = do[3].strip().lower() + new_node = Node(data) + suboperation = do[2].strip().lower() + if suboperation == 'at': + if position == 'beg': + a_cllist.insert_at_beg(new_node) + elif position == 'end': + a_cllist.insert_at_end(new_node) + else: + index = int(position) + ref_node = a_cllist.get_node(index) + if ref_node is None: + print('No such index.') + continue + if suboperation == 'after': + a_cllist.insert_after(ref_node, new_node) + elif suboperation == 'before': + a_cllist.insert_before(ref_node, new_node) + + elif operation == 'remove': + index = int(do[1]) + node = a_cllist.get_node(index) + if node is None: + print('No such index.') + continue + a_cllist.remove(node) + + elif operation == 'quit': + break \ No newline at end of file From 802e23cea0b0b54a05e1dc50b2799382676effcd Mon Sep 17 00:00:00 2001 From: Yashaswi A <59396277+yashaswiadyalu@users.noreply.github.com> Date: Sun, 18 Oct 2020 22:57:35 +0530 Subject: [PATCH 84/88] Delete circularsinglelinkedlist.py --- .../linked-lists/circularsinglelinkedlist.py | 116 ------------------ 1 file changed, 116 deletions(-) delete mode 100644 data-structures/linked-lists/circularsinglelinkedlist.py diff --git a/data-structures/linked-lists/circularsinglelinkedlist.py b/data-structures/linked-lists/circularsinglelinkedlist.py deleted file mode 100644 index 45fd10e..0000000 --- a/data-structures/linked-lists/circularsinglelinkedlist.py +++ /dev/null @@ -1,116 +0,0 @@ -class Node: - def __init__(self, data): - self.data = data - self.next = None - - -class CircularLinkedList: - def __init__(self): - self.head = None - - def get_node(self, index): - if self.head is None: - return None - current = self.head - for i in range(index): - current = current.next - if current == self.head: - return None - return current - - def get_prev_node(self, ref_node): - if self.head is None: - return None - current = self.head - while current.next != ref_node: - current = current.next - return current - - def insert_after(self, ref_node, new_node): - new_node.next = ref_node.next - ref_node.next = new_node - - def insert_before(self, ref_node, new_node): - prev_node = self.get_prev_node(ref_node) - self.insert_after(prev_node, new_node) - - def insert_at_end(self, new_node): - if self.head is None: - self.head = new_node - new_node.next = new_node - else: - self.insert_before(self.head, new_node) - - def insert_at_beg(self, new_node): - self.insert_at_end(new_node) - self.head = new_node - - def remove(self, node): - if self.head.next == self.head: - self.head = None - else: - prev_node = self.get_prev_node(node) - prev_node.next = node.next - if self.head == node: - self.head = node.next - - def display(self): - if self.head is None: - return - current = self.head - while True: - print(current.data, end = ' ') - current = current.next - if current == self.head: - break - - -a_cllist = CircularLinkedList() - -print('Menu') -print('insert after ') -print('insert before ') -print('insert at beg') -print('insert at end') -print('remove ') -print('quit') - -while True: - print('The list: ', end = '') - a_cllist.display() - print() - do = input('What would you like to do? ').split() - - operation = do[0].strip().lower() - - if operation == 'insert': - data = int(do[1]) - position = do[3].strip().lower() - new_node = Node(data) - suboperation = do[2].strip().lower() - if suboperation == 'at': - if position == 'beg': - a_cllist.insert_at_beg(new_node) - elif position == 'end': - a_cllist.insert_at_end(new_node) - else: - index = int(position) - ref_node = a_cllist.get_node(index) - if ref_node is None: - print('No such index.') - continue - if suboperation == 'after': - a_cllist.insert_after(ref_node, new_node) - elif suboperation == 'before': - a_cllist.insert_before(ref_node, new_node) - - elif operation == 'remove': - index = int(do[1]) - node = a_cllist.get_node(index) - if node is None: - print('No such index.') - continue - a_cllist.remove(node) - - elif operation == 'quit': - break \ No newline at end of file From 8e834e971836a74744507091bce48df04fbbd90e Mon Sep 17 00:00:00 2001 From: Madhav Mishra <59422042+carbseater@users.noreply.github.com> Date: Tue, 20 Oct 2020 23:00:00 +0530 Subject: [PATCH 85/88] Rename find_length_linkedList to find_length_linkedList.py --- .../{find_length_linkedList => find_length_linkedList.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename algorithms/linkedlist/{find_length_linkedList => find_length_linkedList.py} (100%) diff --git a/algorithms/linkedlist/find_length_linkedList b/algorithms/linkedlist/find_length_linkedList.py similarity index 100% rename from algorithms/linkedlist/find_length_linkedList rename to algorithms/linkedlist/find_length_linkedList.py From 8aae48324555d20cfbb5d1b87c555b31484d2093 Mon Sep 17 00:00:00 2001 From: Sakshi Agrawal <66746828+SakshiiAgrawal@users.noreply.github.com> Date: Wed, 21 Oct 2020 22:17:16 +0530 Subject: [PATCH 86/88] zigzag traversal in a binary tree The idea is to use two stacks. We can use one stack for printing from left to right and other stack for printing from right to left. In every iteration, we have nodes of one level in one of the stacks. We print the nodes, and push nodes of next level in other stack. --- data-structures/zigzagtraversal_iterative.py | 75 ++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 data-structures/zigzagtraversal_iterative.py diff --git a/data-structures/zigzagtraversal_iterative.py b/data-structures/zigzagtraversal_iterative.py new file mode 100644 index 0000000..fa485b3 --- /dev/null +++ b/data-structures/zigzagtraversal_iterative.py @@ -0,0 +1,75 @@ +class Node: + """ + A Node has data variable and pointers to its left and right nodes. + """ + + def __init__(self, data): + self.left = None + self.right = None + self.data = data + +def make_tree() -> Node: + root = Node(1) + root.left = Node(2) + root.right = Node(3) + root.left.left = Node(4) + root.left.right = Node(5) + return root + +def zigzag_iterative(root: Node): + """ + ZigZag traverse by iterative method: Print node left to right and right to left, alternatively. + """ + if root == None: + return + + # two stacks to store alternate levels + s1 = [] # For levels to be printed from right to left + s2 = [] # For levels to be printed from left to right + + # append first level to first stack 's1' + s1.append(root) + + # Keep printing while any of the stacks has some nodes + while not len(s1) == 0 or not len(s2) == 0: + + # Print nodes of current level from s1 and append nodes of next level to s2 + while not len(s1) == 0: + temp = s1[-1] + s1.pop() + print(temp.data, end = " ") + + # Note that is left is appended before right + if temp.left: + s2.append(temp.left) + if temp.right: + s2.append(temp.right) + + # Print nodes of current level from s2 and append nodes of next level to s1 + while not len(s2) == 0: + temp = s2[-1] + s2.pop() + print(temp.data, end = " ") + + # Note that is rightt is appended before left + if temp.right: + s1.append(temp.right) + if temp.left: + s1.append(temp.left) + +def main(): # Main function for testing. + """ + Create binary tree. + """ + root = make_tree() + print("\nZigzag order traversal(iterative) is: ") + zigzag_iterative(root) + print() + + +if __name__ == "__main__": + import doctest + + doctest.testmod() + main() + From dcbc0ea14a967941785d4e19a9b8962fbeee2920 Mon Sep 17 00:00:00 2001 From: shivansh kumar <42717219+shivansh2310@users.noreply.github.com> Date: Thu, 22 Oct 2020 00:29:23 +0530 Subject: [PATCH 87/88] Railfence Cipher implementation in cipher --- algorithms/cryptography/railfence_cipher.py | 78 +++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 algorithms/cryptography/railfence_cipher.py diff --git a/algorithms/cryptography/railfence_cipher.py b/algorithms/cryptography/railfence_cipher.py new file mode 100644 index 0000000..0cdf24a --- /dev/null +++ b/algorithms/cryptography/railfence_cipher.py @@ -0,0 +1,78 @@ +def railencrypt(st,k): + c = 0 + x = 0 + m =[[0] * (len(st)) for i in range(k)] + for r in range(len(st)): + m[c][r] = st[r] + if x == 0: + if c == (k-1): + x = 1 + c -= 1 + else: + c += 1 + else: + if c == 0: + x = 0 + c += 1 + else: + c -= 1 + + result = [] + for i in range(k): + for j in range(len(st)): + if m[i][j] != 0: + result.append(m[i][j]) + print("CipherText:","" . join(result)) + +def raildecrypt(st,k): + c , x = 0 , 0 + m =[[0] * (len(st)) for i in range(k)] + for r in range(len(st)): + m[c][r] = 1 + if x == 0: + if c == (k-1): + x = 1 + c -= 1 + else: + c += 1 + else: + if c == 0: + x = 0 + c += 1 + else: + c -= 1 + result = [] + c , x = 0 , 0 + for i in range(k): + for j in range(len(st)): + if m[i][j] == 1: + m[i][j] = st[x] + x += 1 + for r in range(len(st)): + if m[c][r] != 0: + result.append(m[c][r]) + if x == 0: + if c == (k-1): + x = 1 + c -= 1 + else: + c += 1 + else: + if c == 0: + x = 0 + c += 1 + else: + c -= 1 + print("PlainText:","" . join(result)) + +if __name__ == "__main__": + string = input("Enter the Message:") + string = string.upper() + key = int(input("Enter the Key:")) + n = int(input("1.Encryption\n2.Decryption\nInput Your choice:")) + if(n == 1): + railencrypt(string,key) + elif(n == 2): + raildecrypt(string,key) + else: + print("Error") From e08137879036d93042dc3ea7aa3a57bbf58728ca Mon Sep 17 00:00:00 2001 From: Hemanth Date: Mon, 2 Nov 2020 22:24:17 +0530 Subject: [PATCH 88/88] Add Tim Sort implementation --- algorithms/sorting/tim_sort.py | 90 ++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 algorithms/sorting/tim_sort.py diff --git a/algorithms/sorting/tim_sort.py b/algorithms/sorting/tim_sort.py new file mode 100644 index 0000000..993c07e --- /dev/null +++ b/algorithms/sorting/tim_sort.py @@ -0,0 +1,90 @@ +from random import randint + + +class TimSort: + """ A class to demonstrate Tim Sort """ + + def __init__(self, array): + self.array = array + self.arrayLength = len(array) + self.__RUN = 32 + + def insertionSort(self, arr): + """ Sorts the given array from given starting index to ending index """ + + for i in range(1, len(arr)): + currentElement = arr[i] + j = i - 1 + while j >= 0 and arr[j] > currentElement: + arr[j + 1] = arr[j] + j -= 1 + arr[j + 1] = currentElement + + return arr + + def mergeRuns(self, arr1, arr2): + """ Merges the given two arrays: arr1 and arr2 """ + + newArray = list() + lengthOfArr1 = len(arr1) + lengthOfArr2 = len(arr2) + + # The variable i is used to keep track of the indices of the first array + # The variable j is used to keep track of the indices of the second array + # The variable k is used to keep track of the indices of the newArray array which is to be returned + i, j, k = 0, 0, 0 + + while i < lengthOfArr1 and j < lengthOfArr2: + if arr1[i] <= arr2[j]: + newArray[k] = arr1[i] + k += 1 + i += 1 + elif arr1[i] >= arr2[j]: + newArray[k] = arr2[j] + k += 1 + j += 1 + + # The below two loops will append any remaining elements left in any of the two arrays. + while i < lengthOfArr1: + newArray.append(arr1[i]) + i += 1 + + while j < lengthOfArr2: + newArray.append(arr2[j]) + j += 1 + + return newArray + + def changeRun(self, newRun): + self.__RUN = newRun + + def algorithm(self): + """ This function will perfom Tim Sort on the given array """ + + # Breaking the array into chunks of subarray(RUNS) of size RUN and perfomring insertionSort on them. + for i in range(0, self.arrayLength, self.__RUN): + currentRunElements = self.array[i: i + self.__RUN] + + self.array[i: i + + self.__RUN] = self.insertionSort(currentRunElements) + + temp_runner = self.__RUN + while temp_runner < self.arrayLength: + for idx in range(0, self.arrayLength, temp_runner * 2): + firstArray = self.array[idx: idx + temp_runner] + secondArray = self.array[idx + + temp_runner: idx + temp_runner * 2] + self.array[idx: idx + temp_runner * + 2] = self.mergeRuns(firstArray, secondArray) + temp_runner = self.__RUN * 2 + + print(f"The sorted array is : {self.array}") + + def __repr__(self): + return f"Array: {self.array}\nRUN: {self.__RUN}" + + +myArray = [randint(1, 100) for i in range(15)] +demo = TimSort(myArray) +print(demo) +demo.algorithm()