mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-01-30 22:23:42 +00:00
Sync Fork - TheAlgorithms/master
Sync Fork
This commit is contained in:
commit
aa11f16a42
19
Maths/3n+1.py
Normal file
19
Maths/3n+1.py
Normal file
|
@ -0,0 +1,19 @@
|
|||
def main():
|
||||
def n31(a):# a = initial number
|
||||
c = 0
|
||||
l = [a]
|
||||
while a != 1:
|
||||
if a % 2 == 0:#if even divide it by 2
|
||||
a = a // 2
|
||||
elif a % 2 == 1:#if odd 3n+1
|
||||
a = 3*a +1
|
||||
c += 1#counter
|
||||
l += [a]
|
||||
|
||||
return l , c
|
||||
print(n31(43))
|
||||
print(n31(98)[0][-1])# = a
|
||||
print("It took {0} steps.".format(n31(13)[1]))#optional finish
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
|
@ -1,8 +1,7 @@
|
|||
# NguyenU
|
||||
|
||||
import math
|
||||
def find_max(nums):
|
||||
max = 0
|
||||
max = nums[0]
|
||||
for x in nums:
|
||||
if x > max:
|
||||
max = x
|
||||
|
|
12
Maths/FindMin.py
Normal file
12
Maths/FindMin.py
Normal file
|
@ -0,0 +1,12 @@
|
|||
def main():
|
||||
def findMin(x):
|
||||
minNum = x[0]
|
||||
for i in x:
|
||||
if minNum > i:
|
||||
minNum = i
|
||||
return minNum
|
||||
|
||||
print(findMin([0,1,2,3,4,5,-3,24,-56])) # = -56
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
18
Maths/abs.py
Normal file
18
Maths/abs.py
Normal file
|
@ -0,0 +1,18 @@
|
|||
def absVal(num):
|
||||
"""
|
||||
Function to fins absolute value of numbers.
|
||||
>>>absVal(-5)
|
||||
5
|
||||
>>>absVal(0)
|
||||
0
|
||||
"""
|
||||
if num < 0:
|
||||
return -num
|
||||
else:
|
||||
return num
|
||||
|
||||
def main():
|
||||
print(absVal(-34)) # = 34
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
22
Maths/absMax.py
Normal file
22
Maths/absMax.py
Normal file
|
@ -0,0 +1,22 @@
|
|||
from abs import absVal
|
||||
def absMax(x):
|
||||
"""
|
||||
>>>absMax([0,5,1,11])
|
||||
11
|
||||
>>absMax([3,-10,-2])
|
||||
-10
|
||||
"""
|
||||
j = x[0]
|
||||
for i in x:
|
||||
if absVal(i) < j:
|
||||
j = i
|
||||
return j
|
||||
#BUG: i is apparently a list, TypeError: '<' not supported between instances of 'list' and 'int' in absVal
|
||||
|
||||
|
||||
def main():
|
||||
a = [1,2,-11]
|
||||
print(absVal(a)) # = -11
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
20
Maths/absMin.py
Normal file
20
Maths/absMin.py
Normal file
|
@ -0,0 +1,20 @@
|
|||
from abs import absVal
|
||||
def absMin(x):
|
||||
"""
|
||||
>>>absMin([0,5,1,11])
|
||||
0
|
||||
>>absMin([3,-10,-2])
|
||||
-2
|
||||
"""
|
||||
j = x[0]
|
||||
for i in x:
|
||||
if absVal(i) < j:
|
||||
j = i
|
||||
return j
|
||||
|
||||
def main():
|
||||
a = [1,2,-11]
|
||||
print(absMin(a)) # = 1
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
79
README.md
79
README.md
|
@ -2,15 +2,15 @@
|
|||
|
||||
### All algorithms implemented in Python (for education)
|
||||
|
||||
These are for demonstration purposes only. There are many implementations of sorts in the Python standard library that are much better for performance reasons.
|
||||
These implementations are for demonstration purposes. They are less efficient than the implementations in the Python standard library.
|
||||
|
||||
## Sort Algorithms
|
||||
## Sorting Algorithms
|
||||
|
||||
|
||||
### Bubble Sort
|
||||
![alt text][bubble-image]
|
||||
|
||||
From [Wikipedia][bubble-wiki]: **Bubble sort**, sometimes referred to as *sinking sort*, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted.
|
||||
From [Wikipedia][bubble-wiki]: **Bubble sort**, sometimes referred to as *sinking sort*, is a simple sorting algorithm that repeatedly steps through the list, compares adjacent pairs and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted.
|
||||
|
||||
__Properties__
|
||||
* Worst case performance O(n<sup>2</sup>)
|
||||
|
@ -23,7 +23,7 @@ __Properties__
|
|||
![alt text][bucket-image-1]
|
||||
![alt text][bucket-image-2]
|
||||
|
||||
From [Wikipedia][bucket-wiki]: Bucket sort, or bin sort, is a sorting algorithm that works by distributing the elements of an array into a number of buckets. Each bucket is then sorted individually, either using a different sorting algorithm, or by recursively applying the bucket sorting algorithm.
|
||||
From [Wikipedia][bucket-wiki]: Bucket sort, or bin sort, is a sorting algorithm that distributes elements of an array into a number of buckets. Each bucket is then sorted individually, either using a different sorting algorithm, or by recursively applying the bucket sorting algorithm.
|
||||
|
||||
__Properties__
|
||||
* Worst case performance O(n<sup>2</sup>)
|
||||
|
@ -57,7 +57,7 @@ __Properties__
|
|||
### Merge Sort
|
||||
![alt text][merge-image]
|
||||
|
||||
From [Wikipedia][merge-wiki]: **Merge sort** (also commonly spelled *mergesort*) is an efficient, general-purpose, comparison-based sorting algorithm. Most implementations produce a stable sort, which means that the implementation preserves the input order of equal elements in the sorted output. Mergesort is a divide and conquer algorithm that was invented by John von Neumann in 1945.
|
||||
From [Wikipedia][merge-wiki]: **Merge sort** (also commonly spelled *mergesort*) is an efficient, general-purpose, comparison-based sorting algorithm. Most implementations produce a stable sort, which means the order of equal items is the same in the input and output. Mergesort is a divide and conquer algorithm that was invented by John von Neumann in 1945.
|
||||
|
||||
__Properties__
|
||||
* Worst case performance O(n log n)
|
||||
|
@ -74,20 +74,20 @@ From [Wikipedia][quick-wiki]: **Quicksort** (sometimes called *partition-exchang
|
|||
|
||||
__Properties__
|
||||
* Worst case performance O(n<sup>2</sup>)
|
||||
* Best case performance O(n log n) or O(n) with three-way partition
|
||||
* Average case performance O(n log n)
|
||||
* Best case performance O(*n* log *n*) or O(n) with three-way partition
|
||||
* Average case performance O(*n* log *n*)
|
||||
|
||||
###### View the algorithm in [action][quick-toptal]
|
||||
|
||||
|
||||
### Heap
|
||||
|
||||
From [Wikipedia][heap-wiki]: Heapsort is a comparison-based sorting algorithm. It can be thought of as an improved selection sort. It divides its input into a sorted and an unsorted region, and it iteratively shrinks the unsorted region by extracting the largest element and moving that to the sorted region
|
||||
From [Wikipedia](https://en.wikipedia.org/wiki/Heapsort): Heapsort is a comparison-based sorting algorithm. It can be thought of as an improved selection sort. It divides its input into a sorted and an unsorted region, and it iteratively shrinks the unsorted region by extracting the largest element and moving that to the sorted region
|
||||
|
||||
__Properties__
|
||||
* Worst case performance O(n log n)
|
||||
* Best case performance O(n log n)
|
||||
* Average case performance O(n log n)
|
||||
* Worst case performance O(*n* log *n*)
|
||||
* Best case performance O(*n* log *n*)
|
||||
* Average case performance O(*n* log *n*)
|
||||
|
||||
|
||||
|
||||
|
@ -95,7 +95,7 @@ __Properties__
|
|||
|
||||
### Radix
|
||||
|
||||
From [Wikipedia][radix-wiki]: In computer science, radix sort is a non-comparative integer sorting algorithm that sorts data with integer keys by grouping keys by the individual digits which share the same significant position and value.
|
||||
From [Wikipedia][radix-wiki]: Radix sort is a non-comparative integer sorting algorithm that sorts data with integer keys by grouping keys by the individual digits which share the same significant position and value.
|
||||
|
||||
__Properties__
|
||||
* Worst case performance O(wn)
|
||||
|
@ -120,15 +120,15 @@ __Properties__
|
|||
From [Wikipedia][shell-wiki]: **Shellsort** is a generalization of *insertion sort* that allows the exchange of items that are far apart. The idea is to arrange the list of elements so that, starting anywhere, considering every nth element gives a sorted list. Such a list is said to be h-sorted. Equivalently, it can be thought of as h interleaved lists, each individually sorted.
|
||||
|
||||
__Properties__
|
||||
* Worst case performance O(nlog2 2n)
|
||||
* Best case performance O(n log n)
|
||||
* Worst case performance O(*n*log<sup>2</sup>*n*)
|
||||
* Best case performance O(*n* log *n*)
|
||||
* Average case performance depends on gap sequence
|
||||
|
||||
###### View the algorithm in [action][shell-toptal]
|
||||
|
||||
### Topological
|
||||
|
||||
From [Wikipedia][topological-wiki]: In the field of computer science, a topological sort or topological ordering of a directed graph is a linear ordering of its vertices such that for every directed edge uv from vertex u to vertex v, u comes before v in the ordering. For instance, the vertices of the graph may represent tasks to be performed, and the edges may represent constraints that one task must be performed before another; in this application, a topological ordering is just a valid sequence for the tasks. A topological ordering is possible if and only if the graph has no directed cycles, that is, if it is a directed acyclic graph (DAG). Any DAG has at least one topological ordering, and algorithms are known for constructing a topological ordering of any DAG in linear time.
|
||||
From [Wikipedia][topological-wiki]: A topological sort or topological ordering of a directed graph is a linear ordering of its vertices such that for every directed edge uv from vertex u to vertex v, u comes before v in the ordering. For instance, the vertices of the graph may represent tasks to be performed, and the edges may represent constraints that one task must be performed before another; in this application, a topological ordering is just a valid sequence for the tasks. A topological ordering is possible if and only if the graph has no directed cycles, that is, if it is a directed acyclic graph (DAG). Any DAG has at least one topological ordering, and algorithms are known for constructing a topological ordering of any DAG in linear time.
|
||||
|
||||
### Time-Complexity Graphs
|
||||
|
||||
|
@ -136,7 +136,7 @@ Comparing the complexity of sorting algorithms (*Bubble Sort*, *Insertion Sort*,
|
|||
|
||||
![Complexity Graphs](https://github.com/prateekiiest/Python/blob/master/sorts/sortinggraphs.png)
|
||||
|
||||
Choosing of a sort technique-Quicksort is a very fast algorithm but can be pretty tricky to implement ,Bubble sort is a slow algorithm but is very easy to implement. To sort small sets of data, bubble sort may be a better option since it can be implemented quickly, but for larger datasets, the speedup from quicksort might be worth the trouble implementing the algorithm.
|
||||
Selecting a sort technique: Quicksort is a very fast algorithm but can be pretty tricky to implement while bubble sort is a slow algorithm which is very easy to implement. For a small datasets bubble sort may be a better option since it can be implemented quickly, but for larger datasets, the speedup from quicksort might be worth the trouble implementing the algorithm.
|
||||
|
||||
|
||||
|
||||
|
@ -147,7 +147,7 @@ Choosing of a sort technique-Quicksort is a very fast algorithm but can be prett
|
|||
### Linear
|
||||
![alt text][linear-image]
|
||||
|
||||
From [Wikipedia][linear-wiki]: **Linear search** or *sequential search* is a method for finding a target value within a list. It sequentially checks each element of the list for the target value until a match is found or until all the elements have been searched. Linear search runs in at worst linear time and makes at most n comparisons, where n is the length of the list.
|
||||
From [Wikipedia][linear-wiki]: **Linear search** or *sequential search* is a method for finding an element in a list. It sequentially checks each element of the list until a match is found or all the elements have been searched.
|
||||
|
||||
__Properties__
|
||||
* Worst case performance O(n)
|
||||
|
@ -167,7 +167,7 @@ __Properties__
|
|||
* Worst case space complexity O(1)
|
||||
|
||||
## Interpolation
|
||||
Interpolation search is an algorithm for searching for a key in an array that has been ordered by numerical values assigned to the keys (key values). It was first described by W. W. Peterson in 1957.[1] Interpolation search resembles the method by which people search a telephone directory for a name (the key value by which the book's entries are ordered): in each step the algorithm calculates where in the remaining search space the sought item might be, based on the key values at the bounds of the search space and the value of the sought key, usually via a linear interpolation. The key value actually found at this estimated position is then compared to the key value being sought. If it is not equal, then depending on the comparison, the remaining search space is reduced to the part before or after the estimated position. This method will only work if calculations on the size of differences between key values are sensible.
|
||||
Interpolation search is an algorithm for searching for a key in an array that has been ordered by numerical values assigned to the keys (key values). It was first described by W. W. Peterson in 1957. Interpolation search resembles the method by which people search a telephone directory for a name (the key value by which the book's entries are ordered): in each step the algorithm calculates where in the remaining search space the sought item might be, based on the key values at the bounds of the search space and the value of the sought key, usually via a linear interpolation. The key value actually found at this estimated position is then compared to the key value being sought. If it is not equal, then depending on the comparison, the remaining search space is reduced to the part before or after the estimated position. This method will only work if calculations on the size of differences between key values are sensible.
|
||||
|
||||
By comparison, binary search always chooses the middle of the remaining search space, discarding one half or the other, depending on the comparison between the key found at the estimated position and the key sought — it does not require numerical values for the keys, just a total order on them. The remaining search space is reduced to the part before or after the estimated position. The linear search uses equality only as it compares elements one-by-one from the start, ignoring any sorting.
|
||||
|
||||
|
@ -177,26 +177,27 @@ In interpolation-sequential search, interpolation is used to find an item near t
|
|||
###### Source: [Wikipedia](https://en.wikipedia.org/wiki/Interpolation_search)
|
||||
|
||||
## Jump Search
|
||||
In computer science, a jump search or block search refers to a search algorithm for ordered lists. It works by first checking all items Lkm, where {\displaystyle k\in \mathbb {N} } k\in \mathbb {N} and m is the block size, until an item is found that is larger than the search key. To find the exact position of the search key in the list a linear search is performed on the sublist L[(k-1)m, km].
|
||||
![alt text][JumpSearch-image]
|
||||
In computer science, a jump search or block search refers to a search algorithm for ordered lists. It works by first checking all items L<sub>km</sub>, where ![](https://wikimedia.org/api/rest_v1/media/math/render/svg/2a5bc4b7383031ba693b7433198ead7170954c1d) and *m* is the block size, until an item is found that is larger than the search key. To find the exact position of the search key in the list a linear search is performed on the sublist L<sub>[(k-1)m, km]</sub>.
|
||||
|
||||
The optimal value of m is √n, where n is the length of the list L. Because both steps of the algorithm look at, at most, √n items the algorithm runs in O(√n) time. This is better than a linear search, but worse than a binary search. The advantage over the latter is that a jump search only needs to jump backwards once, while a binary can jump backwards up to log n times. This can be important if a jumping backwards takes significantly more time than jumping forward.
|
||||
|
||||
The algorithm can be modified by performing multiple levels of jump search on the sublists, before finally performing the linear search. For an k-level jump search the optimum block size ml for the lth level (counting from 1) is n(k-l)/k. The modified algorithm will perform k backward jumps and runs in O(kn1/(k+1)) time.
|
||||
The algorithm can be modified by performing multiple levels of jump search on the sublists, before finally performing the linear search. For an k-level jump search the optimum block size m<sub>l</sub> for the l<sup>th</sup> level (counting from 1) is n<sup>(k-l)/k</sup>. The modified algorithm will perform *k* backward jumps and runs in O(kn<sup>1/(k+1)</sup>) time.
|
||||
###### Source: [Wikipedia](https://en.wikipedia.org/wiki/Jump_search)
|
||||
|
||||
## Quick Select
|
||||
![alt text][QuickSelect-image]
|
||||
In computer science, quickselect is a selection algorithm to find the kth smallest element in an unordered list. It is related to the quicksort sorting algorithm. Like quicksort, it was developed by Tony Hoare, and thus is also known as Hoare's selection algorithm.[1] Like quicksort, it is efficient in practice and has good average-case performance, but has poor worst-case performance. Quickselect and its variants are the selection algorithms most often used in efficient real-world implementations.
|
||||
In computer science, quickselect is a selection algorithm to find the kth smallest element in an unordered list. It is related to the quicksort sorting algorithm. Like quicksort, it was developed by Tony Hoare, and thus is also known as Hoare's selection algorithm. Like quicksort, it is efficient in practice and has good average-case performance, but has poor worst-case performance. Quickselect and its variants are the selection algorithms most often used in efficient real-world implementations.
|
||||
|
||||
Quickselect uses the same overall approach as quicksort, choosing one element as a pivot and partitioning the data in two based on the pivot, accordingly as less than or greater than the pivot. However, instead of recursing into both sides, as in quicksort, quickselect only recurses into one side – the side with the element it is searching for. This reduces the average complexity from O(n log n) to O(n), with a worst case of O(n2).
|
||||
Quickselect uses the same overall approach as quicksort, choosing one element as a pivot and partitioning the data in two based on the pivot, accordingly as less than or greater than the pivot. However, instead of recursing into both sides, as in quicksort, quickselect only recurses into one side – the side with the element it is searching for. This reduces the average complexity from O(n log n) to O(n), with a worst case of O(n<sup>2</sup>).
|
||||
|
||||
As with quicksort, quickselect is generally implemented as an in-place algorithm, and beyond selecting the k'th element, it also partially sorts the data. See selection algorithm for further discussion of the connection with sorting.
|
||||
###### Source: [Wikipedia](https://en.wikipedia.org/wiki/Quickselect)
|
||||
|
||||
## Tabu
|
||||
Tabu search uses a local or neighborhood search procedure to iteratively move from one potential solution {\displaystyle x} x to an improved solution {\displaystyle x'} x' in the neighborhood of {\displaystyle x} x, until some stopping criterion has been satisfied (generally, an attempt limit or a score threshold). Local search procedures often become stuck in poor-scoring areas or areas where scores plateau. In order to avoid these pitfalls and explore regions of the search space that would be left unexplored by other local search procedures, tabu search carefully explores the neighborhood of each solution as the search progresses. The solutions admitted to the new neighborhood, {\displaystyle N^{*}(x)} N^*(x), are determined through the use of memory structures. Using these memory structures, the search progresses by iteratively moving from the current solution {\displaystyle x} x to an improved solution {\displaystyle x'} x' in {\displaystyle N^{*}(x)} N^*(x).
|
||||
Tabu search uses a local or neighborhood search procedure to iteratively move from one potential solution ![](https://wikimedia.org/api/rest_v1/media/math/render/svg/87f9e315fd7e2ba406057a97300593c4802b53e4) to an improved solution ![](https://wikimedia.org/api/rest_v1/media/math/render/svg/0ac74959896052e160a5953102e4bc3850fe93b2) in the neighborhood of ![](https://wikimedia.org/api/rest_v1/media/math/render/svg/87f9e315fd7e2ba406057a97300593c4802b53e4), until some stopping criterion has been satisfied (generally, an attempt limit or a score threshold). Local search procedures often become stuck in poor-scoring areas or areas where scores plateau. In order to avoid these pitfalls and explore regions of the search space that would be left unexplored by other local search procedures, tabu search carefully explores the neighborhood of each solution as the search progresses. The solutions admitted to the new neighborhood, ![](https://wikimedia.org/api/rest_v1/media/math/render/svg/4db1b4a2cfa6f356afe0738e999f0af2bed27f45), are determined through the use of memory structures. Using these memory structures, the search progresses by iteratively moving from the current solution ![](https://wikimedia.org/api/rest_v1/media/math/render/svg/87f9e315fd7e2ba406057a97300593c4802b53e4) to an improved solution ![](https://wikimedia.org/api/rest_v1/media/math/render/svg/0ac74959896052e160a5953102e4bc3850fe93b2) in ![](https://wikimedia.org/api/rest_v1/media/math/render/svg/4db1b4a2cfa6f356afe0738e999f0af2bed27f45).
|
||||
|
||||
These memory structures form what is known as the tabu list, a set of rules and banned solutions used to filter which solutions will be admitted to the neighborhood {\displaystyle N^{*}(x)} N^*(x) to be explored by the search. In its simplest form, a tabu list is a short-term set of the solutions that have been visited in the recent past (less than {\displaystyle n} n iterations ago, where {\displaystyle n} n is the number of previous solutions to be stored — is also called the tabu tenure). More commonly, a tabu list consists of solutions that have changed by the process of moving from one solution to another. It is convenient, for ease of description, to understand a “solution” to be coded and represented by such attributes.
|
||||
These memory structures form what is known as the tabu list, a set of rules and banned solutions used to filter which solutions will be admitted to the neighborhood ![](https://wikimedia.org/api/rest_v1/media/math/render/svg/4db1b4a2cfa6f356afe0738e999f0af2bed27f45) to be explored by the search. In its simplest form, a tabu list is a short-term set of the solutions that have been visited in the recent past (less than ![](https://wikimedia.org/api/rest_v1/media/math/render/svg/a601995d55609f2d9f5e233e36fbe9ea26011b3b) iterations ago, where ![](https://wikimedia.org/api/rest_v1/media/math/render/svg/a601995d55609f2d9f5e233e36fbe9ea26011b3b) is the number of previous solutions to be stored — is also called the tabu tenure). More commonly, a tabu list consists of solutions that have changed by the process of moving from one solution to another. It is convenient, for ease of description, to understand a “solution” to be coded and represented by such attributes.
|
||||
###### Source: [Wikipedia](https://en.wikipedia.org/wiki/Tabu_search)
|
||||
----------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
|
@ -225,26 +226,26 @@ Mathematically a bijective function is used on the characters' positions to encr
|
|||
###### Source: [Wikipedia](https://en.wikipedia.org/wiki/Transposition_cipher)
|
||||
|
||||
### RSA (Rivest–Shamir–Adleman)
|
||||
RSA (Rivest–Shamir–Adleman) is one of the first public-key cryptosystems and is widely used for secure data transmission. In such a cryptosystem, the encryption key is public and it is different from the decryption key which is kept secret (private). In RSA, this asymmetry is based on the practical difficulty of the factorization of the product of two large prime numbers, the "factoring problem". The acronym RSA is made of the initial letters of the surnames of Ron Rivest, Adi Shamir, and Leonard Adleman, who first publicly described the algorithm in 1978. Clifford Cocks, an English mathematician working for the British intelligence agency Government Communications Headquarters (GCHQ), had developed an equivalent system in 1973, but this was not declassified until 1997.[1]
|
||||
RSA (Rivest–Shamir–Adleman) is one of the first public-key cryptosystems and is widely used for secure data transmission. In such a cryptosystem, the encryption key is public and it is different from the decryption key which is kept secret (private). In RSA, this asymmetry is based on the practical difficulty of the factorization of the product of two large prime numbers, the "factoring problem". The acronym RSA is made of the initial letters of the surnames of Ron Rivest, Adi Shamir, and Leonard Adleman, who first publicly described the algorithm in 1978. Clifford Cocks, an English mathematician working for the British intelligence agency Government Communications Headquarters (GCHQ), had developed an equivalent system in 1973, but this was not declassified until 1997.
|
||||
|
||||
A user of RSA creates and then publishes a public key based on two large prime numbers, along with an auxiliary value. The prime numbers must be kept secret. Anyone can use the public key to encrypt a message, but with currently published methods, and if the public key is large enough, only someone with knowledge of the prime numbers can decode the message feasibly.[2] Breaking RSA encryption is known as the RSA problem. Whether it is as difficult as the factoring problem remains an open question.
|
||||
A user of RSA creates and then publishes a public key based on two large prime numbers, along with an auxiliary value. The prime numbers must be kept secret. Anyone can use the public key to encrypt a message, but with currently published methods, and if the public key is large enough, only someone with knowledge of the prime numbers can decode the message feasibly. Breaking RSA encryption is known as the RSA problem. Whether it is as difficult as the factoring problem remains an open question.
|
||||
###### Source: [Wikipedia](https://en.wikipedia.org/wiki/RSA_(cryptosystem))
|
||||
|
||||
## ROT13
|
||||
![alt text][ROT13-image]
|
||||
ROT13 ("rotate by 13 places", sometimes hyphenated ROT-13) is a simple letter substitution cipher that replaces a letter with the 13th letter after it, in the alphabet. ROT13 is a special case of the Caesar cipher which was developed in ancient Rome.
|
||||
|
||||
Because there are 26 letters (2×13) in the basic Latin alphabet, ROT13 is its own inverse; that is, to undo ROT13, the same algorithm is applied, so the same action can be used for encoding and decoding. The algorithm provides virtually no cryptographic security, and is often cited as a canonical example of weak encryption.[1]
|
||||
Because there are 26 letters (2×13) in the basic Latin alphabet, ROT13 is its own inverse; that is, to undo ROT13, the same algorithm is applied, so the same action can be used for encoding and decoding. The algorithm provides virtually no cryptographic security, and is often cited as a canonical example of weak encryption.
|
||||
###### Source: [Wikipedia](https://en.wikipedia.org/wiki/ROT13)
|
||||
|
||||
## XOR
|
||||
In cryptography, the simple XOR cipher is a type of additive cipher,[1] an encryption algorithm that operates according to the principles:
|
||||
In cryptography, the simple XOR cipher is a type of additive cipher, an encryption algorithm that operates according to the principles:
|
||||
|
||||
A {\displaystyle \oplus } \oplus 0 = A,
|
||||
A {\displaystyle \oplus } \oplus A = 0,
|
||||
(A {\displaystyle \oplus } \oplus B) {\displaystyle \oplus } \oplus C = A {\displaystyle \oplus } \oplus (B {\displaystyle \oplus } \oplus C),
|
||||
(B {\displaystyle \oplus } \oplus A) {\displaystyle \oplus } \oplus A = B {\displaystyle \oplus } \oplus 0 = B,
|
||||
where {\displaystyle \oplus } \oplus denotes the exclusive disjunction (XOR) operation. This operation is sometimes called modulus 2 addition (or subtraction, which is identical).[2] With this logic, a string of text can be encrypted by applying the bitwise XOR operator to every character using a given key. To decrypt the output, merely reapplying the XOR function with the key will remove the cipher.
|
||||
A ![](https://wikimedia.org/api/rest_v1/media/math/render/svg/8b16e2bdaefee9eed86d866e6eba3ac47c710f60) 0 = A,
|
||||
A ![](https://wikimedia.org/api/rest_v1/media/math/render/svg/8b16e2bdaefee9eed86d866e6eba3ac47c710f60) A = 0,
|
||||
(A ![](https://wikimedia.org/api/rest_v1/media/math/render/svg/8b16e2bdaefee9eed86d866e6eba3ac47c710f60) B) ![](https://wikimedia.org/api/rest_v1/media/math/render/svg/8b16e2bdaefee9eed86d866e6eba3ac47c710f60) C = A ![](https://wikimedia.org/api/rest_v1/media/math/render/svg/8b16e2bdaefee9eed86d866e6eba3ac47c710f60) (B ![](https://wikimedia.org/api/rest_v1/media/math/render/svg/8b16e2bdaefee9eed86d866e6eba3ac47c710f60) C),
|
||||
(B ![](https://wikimedia.org/api/rest_v1/media/math/render/svg/8b16e2bdaefee9eed86d866e6eba3ac47c710f60) A) ![](https://wikimedia.org/api/rest_v1/media/math/render/svg/8b16e2bdaefee9eed86d866e6eba3ac47c710f60) A = B ![](https://wikimedia.org/api/rest_v1/media/math/render/svg/8b16e2bdaefee9eed86d866e6eba3ac47c710f60) 0 = B,
|
||||
where ![](https://wikimedia.org/api/rest_v1/media/math/render/svg/8b16e2bdaefee9eed86d866e6eba3ac47c710f60) denotes the exclusive disjunction (XOR) operation. This operation is sometimes called modulus 2 addition (or subtraction, which is identical). With this logic, a string of text can be encrypted by applying the bitwise XOR operator to every character using a given key. To decrypt the output, merely reapplying the XOR function with the key will remove the cipher.
|
||||
###### Source: [Wikipedia](https://en.wikipedia.org/wiki/XOR_cipher)
|
||||
|
||||
[bubble-toptal]: https://www.toptal.com/developers/sorting-algorithms/bubble-sort
|
||||
|
@ -283,14 +284,16 @@ where {\displaystyle \oplus } \oplus denotes the exclusive disjunction (XOR) op
|
|||
[topological-wiki]: https://en.wikipedia.org/wiki/Topological_sorting
|
||||
|
||||
[linear-wiki]: https://en.wikipedia.org/wiki/Linear_search
|
||||
[linear-image]: http://www.tutorialspoint.com/data_structures_algorithms/images/linear_search.gif
|
||||
[linear-image]: http://www.tutorialspoint.com/data_structures_algorithms/images/linear_search.gif "Linear Search"
|
||||
|
||||
[binary-wiki]: https://en.wikipedia.org/wiki/Binary_search_algorithm
|
||||
[binary-image]: https://upload.wikimedia.org/wikipedia/commons/f/f7/Binary_search_into_array.png
|
||||
[binary-image]: https://upload.wikimedia.org/wikipedia/commons/f/f7/Binary_search_into_array.png "Binary Search"
|
||||
|
||||
|
||||
[caesar]: https://upload.wikimedia.org/wikipedia/commons/4/4a/Caesar_cipher_left_shift_of_3.svg
|
||||
[caesar]: https://upload.wikimedia.org/wikipedia/commons/4/4a/Caesar_cipher_left_shift_of_3.svg "Caesar"
|
||||
|
||||
[ROT13-image]: https://upload.wikimedia.org/wikipedia/commons/3/33/ROT13_table_with_example.svg
|
||||
[ROT13-image]: https://upload.wikimedia.org/wikipedia/commons/3/33/ROT13_table_with_example.svg "ROT13"
|
||||
|
||||
[QuickSelect-image]: https://upload.wikimedia.org/wikipedia/commons/0/04/Selecting_quickselect_frames.gif
|
||||
[JumpSearch-image]: https://i1.wp.com/theoryofprogramming.com/wp-content/uploads/2016/11/jump-search-1.jpg "Jump Search"
|
||||
|
||||
[QuickSelect-image]: https://upload.wikimedia.org/wikipedia/commons/0/04/Selecting_quickselect_frames.gif "Quick Select"
|
||||
|
|
BIN
analysis/compression_analysis/PSNR-example-base.png
Normal file
BIN
analysis/compression_analysis/PSNR-example-base.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 4.3 MiB |
BIN
analysis/compression_analysis/PSNR-example-comp-10.jpg
Normal file
BIN
analysis/compression_analysis/PSNR-example-comp-10.jpg
Normal file
Binary file not shown.
After Width: | Height: | Size: 104 KiB |
BIN
analysis/compression_analysis/example_wikipedia_image.jpg
Normal file
BIN
analysis/compression_analysis/example_wikipedia_image.jpg
Normal file
Binary file not shown.
After Width: | Height: | Size: 476 KiB |
Before Width: | Height: | Size: 82 KiB After Width: | Height: | Size: 82 KiB |
|
@ -1,38 +1,39 @@
|
|||
import numpy as np
|
||||
"""
|
||||
Peak signal-to-noise ratio - PSNR - https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio
|
||||
Soruce: https://tutorials.techonical.com/how-to-calculate-psnr-value-of-two-images-using-python/
|
||||
"""
|
||||
|
||||
import math
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
def Representational(r,g,b):
|
||||
return (0.299*r+0.287*g+0.114*b)
|
||||
def psnr(original, contrast):
|
||||
mse = np.mean((original - contrast) ** 2)
|
||||
if mse == 0:
|
||||
return 100
|
||||
PIXEL_MAX = 255.0
|
||||
PSNR = 20 * math.log10(PIXEL_MAX / math.sqrt(mse))
|
||||
return PSNR
|
||||
|
||||
def calculate(img):
|
||||
b,g,r = cv2.split(img)
|
||||
pixelAt = Representational(r,g,b)
|
||||
return pixelAt
|
||||
|
||||
def main():
|
||||
|
||||
#Loading images (orignal image and compressed image)
|
||||
orignal_image = cv2.imread('orignal_image.png',1)
|
||||
compressed_image = cv2.imread('compressed_image.png',1)
|
||||
|
||||
#Getting image height and width
|
||||
height,width = orignal_image.shape[:2]
|
||||
# Loading images (original image and compressed image)
|
||||
original = cv2.imread('original_image.png')
|
||||
contrast = cv2.imread('compressed_image.png', 1)
|
||||
|
||||
orignalPixelAt = calculate(orignal_image)
|
||||
compressedPixelAt = calculate(compressed_image)
|
||||
original2 = cv2.imread('PSNR-example-base.png')
|
||||
contrast2 = cv2.imread('PSNR-example-comp-10.jpg', 1)
|
||||
|
||||
diff = orignalPixelAt - compressedPixelAt
|
||||
error = np.sum(np.abs(diff) ** 2)
|
||||
|
||||
error = error/(height*width)
|
||||
|
||||
#MSR = error_sum/(height*width)
|
||||
PSNR = -(10*math.log10(error/(255*255)))
|
||||
|
||||
print("PSNR value is {}".format(PSNR))
|
||||
# Value expected: 29.73dB
|
||||
print("-- First Test --")
|
||||
print(f"PSNR value is {psnr(original, contrast)} dB")
|
||||
|
||||
# # Value expected: 31.53dB (Wikipedia Example)
|
||||
print("\n-- Second Test --")
|
||||
print(f"PSNR value is {psnr(original2, contrast2)} dB")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
||||
main()
|
||||
|
|
|
@ -15,7 +15,7 @@ def bisection(function, a, b): # finds where the function becomes 0 in [a,b] us
|
|||
return
|
||||
else:
|
||||
mid = (start + end) / 2
|
||||
while abs(start - mid) > 0.0000001: # until we achieve precise equals to 10^-7
|
||||
while abs(start - mid) > 10**-7: # until we achieve precise equals to 10^-7
|
||||
if function(mid) == 0:
|
||||
return mid
|
||||
elif function(mid) * function(start) < 0:
|
||||
|
@ -29,5 +29,5 @@ def bisection(function, a, b): # finds where the function becomes 0 in [a,b] us
|
|||
def f(x):
|
||||
return math.pow(x, 3) - 2*x - 5
|
||||
|
||||
|
||||
print(bisection(f, 1, 1000))
|
||||
if __name__ == "__main__":
|
||||
print(bisection(f, 1, 1000))
|
||||
|
|
|
@ -5,12 +5,13 @@ def intersection(function,x0,x1): #function is the f we want to find its root an
|
|||
x_n1 = x1
|
||||
while True:
|
||||
x_n2 = x_n1-(function(x_n1)/((function(x_n1)-function(x_n))/(x_n1-x_n)))
|
||||
if abs(x_n2 - x_n1)<0.00001 :
|
||||
if abs(x_n2 - x_n1) < 10**-5:
|
||||
return x_n2
|
||||
x_n=x_n1
|
||||
x_n1=x_n2
|
||||
|
||||
def f(x):
|
||||
return math.pow(x,3)-2*x-5
|
||||
return math.pow(x , 3) - (2 * x) -5
|
||||
|
||||
print(intersection(f,3,3.5))
|
||||
if __name__ == "__main__":
|
||||
print(intersection(f,3,3.5))
|
||||
|
|
|
@ -1,13 +1,14 @@
|
|||
# lower–upper (LU) decomposition - https://en.wikipedia.org/wiki/LU_decomposition
|
||||
import numpy
|
||||
|
||||
def LUDecompose (table):
|
||||
#table that contains our data
|
||||
#table has to be a square array so we need to check first
|
||||
# Table that contains our data
|
||||
# Table has to be a square array so we need to check first
|
||||
rows,columns=numpy.shape(table)
|
||||
L=numpy.zeros((rows,columns))
|
||||
U=numpy.zeros((rows,columns))
|
||||
if rows!=columns:
|
||||
return
|
||||
return []
|
||||
for i in range (columns):
|
||||
for j in range(i-1):
|
||||
sum=0
|
||||
|
@ -22,13 +23,10 @@ def LUDecompose (table):
|
|||
U[i][j]=table[i][j]-sum1
|
||||
return L,U
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
matrix =numpy.array([[2,-2,1],[0,1,2],[5,3,1]])
|
||||
L,U = LUDecompose(matrix)
|
||||
print(L)
|
||||
print(U)
|
||||
if __name__ == "__main__":
|
||||
matrix =numpy.array([[2,-2,1],
|
||||
[0,1,2],
|
||||
[5,3,1]])
|
||||
L,U = LUDecompose(matrix)
|
||||
print(L)
|
||||
print(U)
|
||||
|
|
|
@ -1,15 +1,18 @@
|
|||
# Newton's Method - https://en.wikipedia.org/wiki/Newton%27s_method
|
||||
|
||||
def newton(function,function1,startingInt): #function is the f(x) and function1 is the f'(x)
|
||||
x_n=startingInt
|
||||
while True:
|
||||
x_n1=x_n-function(x_n)/function1(x_n)
|
||||
if abs(x_n-x_n1)<0.00001:
|
||||
if abs(x_n-x_n1) < 10**-5:
|
||||
return x_n1
|
||||
x_n=x_n1
|
||||
|
||||
def f(x):
|
||||
return (x**3)-2*x-5
|
||||
return (x**3) - (2 * x) -5
|
||||
|
||||
def f1(x):
|
||||
return 3*(x**2)-2
|
||||
return 3 * (x**2) -2
|
||||
|
||||
print(newton(f,f1,3))
|
||||
if __name__ == "__main__":
|
||||
print(newton(f,f1,3))
|
||||
|
|
11
ciphers/base16.py
Normal file
11
ciphers/base16.py
Normal file
|
@ -0,0 +1,11 @@
|
|||
import base64
|
||||
|
||||
def main():
|
||||
inp = input('->')
|
||||
encoded = inp.encode('utf-8') #encoded the input (we need a bytes like object)
|
||||
b16encoded = base64.b16encode(encoded) #b16encoded the encoded string
|
||||
print(b16encoded)
|
||||
print(base64.b16decode(b16encoded).decode('utf-8'))#decoded it
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
11
ciphers/base32.py
Normal file
11
ciphers/base32.py
Normal file
|
@ -0,0 +1,11 @@
|
|||
import base64
|
||||
|
||||
def main():
|
||||
inp = input('->')
|
||||
encoded = inp.encode('utf-8') #encoded the input (we need a bytes like object)
|
||||
b32encoded = base64.b32encode(encoded) #b32encoded the encoded string
|
||||
print(b32encoded)
|
||||
print(base64.b32decode(b32encoded).decode('utf-8'))#decoded it
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
11
ciphers/base64_cipher.py
Normal file
11
ciphers/base64_cipher.py
Normal file
|
@ -0,0 +1,11 @@
|
|||
import base64
|
||||
|
||||
def main():
|
||||
inp = input('->')
|
||||
encoded = inp.encode('utf-8') #encoded the input (we need a bytes like object)
|
||||
b64encoded = base64.b64encode(encoded) #b64encoded the encoded string
|
||||
print(b64encoded)
|
||||
print(base64.b64decode(b64encoded).decode('utf-8'))#decoded it
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
11
ciphers/base85.py
Normal file
11
ciphers/base85.py
Normal file
|
@ -0,0 +1,11 @@
|
|||
import base64
|
||||
|
||||
def main():
|
||||
inp = input('->')
|
||||
encoded = inp.encode('utf-8') #encoded the input (we need a bytes like object)
|
||||
a85encoded = base64.a85encode(encoded) #a85encoded the encoded string
|
||||
print(a85encoded)
|
||||
print(base64.a85decode(a85encoded).decode('utf-8'))#decoded it
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
|
@ -34,35 +34,30 @@ def brute_force(strng):
|
|||
|
||||
|
||||
def main():
|
||||
print('-' * 10 + "\n**Menu**\n" + '-' * 10)
|
||||
print("1.Encrpyt")
|
||||
print("2.Decrypt")
|
||||
print("3.BruteForce")
|
||||
print("4.Quit")
|
||||
while True:
|
||||
print('-' * 10 + "\n**Menu**\n" + '-' * 10)
|
||||
print("1.Encrpyt")
|
||||
print("2.Decrypt")
|
||||
print("3.BruteForce")
|
||||
print("4.Quit")
|
||||
choice = input("What would you like to do?: ")
|
||||
if choice not in ['1', '2', '3', '4']:
|
||||
print ("Invalid choice")
|
||||
elif choice == '1':
|
||||
strng = input("Please enter the string to be ecrypted: ")
|
||||
while True:
|
||||
key = int(input("Please enter off-set between 1-94: "))
|
||||
if key in range(1, 95):
|
||||
print (encrypt(strng, key))
|
||||
main()
|
||||
key = int(input("Please enter off-set between 1-94: "))
|
||||
if key in range(1, 95):
|
||||
print (encrypt(strng.lower(), key))
|
||||
elif choice == '2':
|
||||
strng = input("Please enter the string to be decrypted: ")
|
||||
while True:
|
||||
key = int(input("Please enter off-set between 1-94: "))
|
||||
if key > 0 and key <= 94:
|
||||
print(decrypt(strng, key))
|
||||
main()
|
||||
key = int(input("Please enter off-set between 1-94: "))
|
||||
if key > 0 and key <= 94:
|
||||
print(decrypt(strng, key))
|
||||
elif choice == '3':
|
||||
strng = input("Please enter the string to be decrypted: ")
|
||||
brute_force(strng)
|
||||
main()
|
||||
elif choice == '4':
|
||||
print ("Goodbye.")
|
||||
sys.exit()
|
||||
|
||||
break
|
||||
main()
|
||||
|
|
|
@ -1,3 +1,3 @@
|
|||
arr = [10, 20, 30, 40]
|
||||
arr[1] = 30
|
||||
arr[1] = 30 # set element 1 (20) of array to 30
|
||||
print(arr)
|
||||
|
|
|
@ -21,7 +21,7 @@ def minDist(mdist, vset, V):
|
|||
def Dijkstra(graph, V, src):
|
||||
mdist=[float('inf') for i in range(V)]
|
||||
vset = [False for i in range(V)]
|
||||
mdist[src] = 0.0;
|
||||
mdist[src] = 0.0
|
||||
|
||||
for i in range(V-1):
|
||||
u = minDist(mdist, vset, V)
|
||||
|
|
|
@ -40,7 +40,7 @@ class Heap:
|
|||
def buildHeap(self,a):
|
||||
self.currsize = len(a)
|
||||
self.h = list(a)
|
||||
for i in range(self.currsize/2,-1,-1):
|
||||
for i in range(self.currsize//2,-1,-1):
|
||||
self.maxHeapify(i)
|
||||
|
||||
def getMax(self):
|
||||
|
|
|
@ -2,49 +2,50 @@
|
|||
- A linked list is similar to an array, it holds values. However, links in a linked list do not have indexes.
|
||||
- This is an example of a double ended, doubly linked list.
|
||||
- Each link references the next link and the previous one.
|
||||
'''
|
||||
- A Doubly Linked List (DLL) contains an extra pointer, typically called previous pointer, together with next pointer and data which are there in singly linked list.
|
||||
- Advantages over SLL - IT can be traversed in both forward and backward direction.,Delete operation is more efficent'''
|
||||
from __future__ import print_function
|
||||
|
||||
|
||||
class LinkedList:
|
||||
class LinkedList: #making main class named linked list
|
||||
def __init__(self):
|
||||
self.head = None
|
||||
self.tail = None
|
||||
|
||||
def insertHead(self, x):
|
||||
newLink = Link(x) #Create a new link with a value attached to it
|
||||
if(self.isEmpty() == True): #Set the first element added to be the tail
|
||||
newLink = Link(x) #Create a new link with a value attached to it
|
||||
if(self.isEmpty() == True): #Set the first element added to be the tail
|
||||
self.tail = newLink
|
||||
else:
|
||||
self.head.previous = newLink # newLink <-- currenthead(head)
|
||||
newLink.next = self.head # newLink <--> currenthead(head)
|
||||
self.head = newLink # newLink(head) <--> oldhead
|
||||
self.head.previous = newLink # newLink <-- currenthead(head)
|
||||
newLink.next = self.head # newLink <--> currenthead(head)
|
||||
self.head = newLink # newLink(head) <--> oldhead
|
||||
|
||||
def deleteHead(self):
|
||||
temp = self.head
|
||||
self.head = self.head.next # oldHead <--> 2ndElement(head)
|
||||
self.head.previous = None # oldHead --> 2ndElement(head) nothing pointing at it so the old head will be removed
|
||||
self.head = self.head.next # oldHead <--> 2ndElement(head)
|
||||
self.head.previous = None # oldHead --> 2ndElement(head) nothing pointing at it so the old head will be removed
|
||||
if(self.head is None):
|
||||
self.tail = None
|
||||
self.tail = None #if empty linked list
|
||||
return temp
|
||||
|
||||
def insertTail(self, x):
|
||||
newLink = Link(x)
|
||||
newLink.next = None # currentTail(tail) newLink -->
|
||||
self.tail.next = newLink # currentTail(tail) --> newLink -->
|
||||
newLink.previous = self.tail #currentTail(tail) <--> newLink -->
|
||||
self.tail = newLink # oldTail <--> newLink(tail) -->
|
||||
newLink.next = None # currentTail(tail) newLink -->
|
||||
self.tail.next = newLink # currentTail(tail) --> newLink -->
|
||||
newLink.previous = self.tail #currentTail(tail) <--> newLink -->
|
||||
self.tail = newLink # oldTail <--> newLink(tail) -->
|
||||
|
||||
def deleteTail(self):
|
||||
temp = self.tail
|
||||
self.tail = self.tail.previous # 2ndLast(tail) <--> oldTail --> None
|
||||
self.tail.next = None # 2ndlast(tail) --> None
|
||||
self.tail = self.tail.previous # 2ndLast(tail) <--> oldTail --> None
|
||||
self.tail.next = None # 2ndlast(tail) --> None
|
||||
return temp
|
||||
|
||||
def delete(self, x):
|
||||
current = self.head
|
||||
|
||||
while(current.value != x): # Find the position to delete
|
||||
while(current.value != x): # Find the position to delete
|
||||
current = current.next
|
||||
|
||||
if(current == self.head):
|
||||
|
@ -57,10 +58,10 @@ class LinkedList:
|
|||
current.previous.next = current.next # 1 --> 3
|
||||
current.next.previous = current.previous # 1 <--> 3
|
||||
|
||||
def isEmpty(self): #Will return True if the list is empty
|
||||
def isEmpty(self): #Will return True if the list is empty
|
||||
return(self.head is None)
|
||||
|
||||
def display(self): #Prints contents of the list
|
||||
def display(self): #Prints contents of the list
|
||||
current = self.head
|
||||
while(current != None):
|
||||
current.displayLink()
|
||||
|
@ -68,8 +69,8 @@ class LinkedList:
|
|||
print()
|
||||
|
||||
class Link:
|
||||
next = None #This points to the link in front of the new link
|
||||
previous = None #This points to the link behind the new link
|
||||
next = None #This points to the link in front of the new link
|
||||
previous = None #This points to the link behind the new link
|
||||
def __init__(self, x):
|
||||
self.value = x
|
||||
def displayLink(self):
|
||||
|
|
|
@ -8,53 +8,53 @@ class Node: # create a Node
|
|||
|
||||
|
||||
class Linked_List:
|
||||
def insert_tail(Head, data):
|
||||
if Head.next is None:
|
||||
Head.next = Node(data)
|
||||
def __init__(self):
|
||||
self.Head = None # Initialize Head to None
|
||||
|
||||
def insert_tail(self, data):
|
||||
if(self.Head is None): self.insert_head(data) #If this is first node, call insert_head
|
||||
else:
|
||||
Head.next.insert_tail(data)
|
||||
temp = self.Head
|
||||
while(temp.next != None): #traverse to last node
|
||||
temp = temp.next
|
||||
temp.next = Node(data) #create node & link to tail
|
||||
|
||||
def insert_head(Head, data):
|
||||
tamp = Head
|
||||
if tamp is None:
|
||||
newNod = Node() # create a new Node
|
||||
newNod.data = data
|
||||
newNod.next = None
|
||||
Head = newNod # make new node to Head
|
||||
else:
|
||||
newNod = Node()
|
||||
newNod.data = data
|
||||
newNod.next = Head # put the Head at NewNode Next
|
||||
Head = newNod # make a NewNode to Head
|
||||
return Head
|
||||
def insert_head(self, data):
|
||||
newNod = Node(data) # create a new node
|
||||
if self.Head != None:
|
||||
newNod.next = self.Head # link newNode to head
|
||||
self.Head = newNod # make NewNode as Head
|
||||
|
||||
def printList(Head): # print every node data
|
||||
tamp = Head
|
||||
def printList(self): # print every node data
|
||||
tamp = self.Head
|
||||
while tamp is not None:
|
||||
print(tamp.data)
|
||||
tamp = tamp.next
|
||||
|
||||
def delete_head(Head): # delete from head
|
||||
if Head is not None:
|
||||
Head = Head.next
|
||||
return Head # return new Head
|
||||
def delete_head(self): # delete from head
|
||||
temp = self.Head
|
||||
if self.Head != None:
|
||||
self.Head = self.Head.next
|
||||
temp.next = None
|
||||
return temp
|
||||
|
||||
def delete_tail(self): # delete from tail
|
||||
tamp = self.Head
|
||||
if self.Head != None:
|
||||
if(self.Head.next is None): # if Head is the only Node in the Linked List
|
||||
self.Head = None
|
||||
else:
|
||||
while tamp.next.next is not None: # find the 2nd last element
|
||||
tamp = tamp.next
|
||||
tamp.next, tamp = None, tamp.next #(2nd last element).next = None and tamp = last element
|
||||
return tamp
|
||||
|
||||
def delete_tail(Head): # delete from tail
|
||||
if Head is not None:
|
||||
tamp = Node()
|
||||
tamp = Head
|
||||
while tamp.next.next is not None: # find the 2nd last element
|
||||
tamp = tamp.next
|
||||
# delete the last element by give next None to 2nd last Element
|
||||
tamp.next = None
|
||||
return Head
|
||||
def isEmpty(self):
|
||||
return self.Head is None # Return if Head is none
|
||||
|
||||
def isEmpty(Head):
|
||||
return Head is None # Return if Head is none
|
||||
|
||||
def reverse(Head):
|
||||
def reverse(self):
|
||||
prev = None
|
||||
current = Head
|
||||
current = self.Head
|
||||
|
||||
while current:
|
||||
# Store the current node's next node.
|
||||
|
@ -66,5 +66,32 @@ class Linked_List:
|
|||
# Make the current node the next node (to progress iteration)
|
||||
current = next_node
|
||||
# Return prev in order to put the head at the end
|
||||
Head = prev
|
||||
return Head
|
||||
self.Head = prev
|
||||
|
||||
def main():
|
||||
A = Linked_List()
|
||||
print("Inserting 10 at Head")
|
||||
A.insert_head(10)
|
||||
print("Inserting 0 at Head")
|
||||
A.insert_head(0)
|
||||
print("\nPrint List : ")
|
||||
A.printList()
|
||||
print("\nInserting 100 at Tail")
|
||||
A.insert_tail(100)
|
||||
print("Inserting 1000 at Tail")
|
||||
A.insert_tail(1000)
|
||||
print("\nPrint List : ")
|
||||
A.printList()
|
||||
print("\nDelete Head")
|
||||
A.delete_head()
|
||||
print("Delete Tail")
|
||||
A.delete_tail()
|
||||
print("\nPrint List : ")
|
||||
A.printList()
|
||||
print("\nReverse Linked List")
|
||||
A.reverse()
|
||||
print("\nPrint List : ")
|
||||
A.printList()
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
|
|
@ -6,7 +6,7 @@ __author__ = 'Omkar Pathak'
|
|||
|
||||
|
||||
def balanced_parentheses(parentheses):
|
||||
""" Use a stack to check if a string of parentheses are balanced."""
|
||||
""" Use a stack to check if a string of parentheses is balanced."""
|
||||
stack = Stack(len(parentheses))
|
||||
for parenthesis in parentheses:
|
||||
if parenthesis == '(':
|
||||
|
|
|
@ -11,8 +11,6 @@ def MatrixChainOrder(array):
|
|||
N=len(array)
|
||||
Matrix=[[0 for x in range(N)] for x in range(N)]
|
||||
Sol=[[0 for x in range(N)] for x in range(N)]
|
||||
for i in range(1,N):
|
||||
Matrix[i][i]=0
|
||||
|
||||
for ChainLength in range(2,N):
|
||||
for a in range(1,N-ChainLength+1):
|
||||
|
|
|
@ -50,7 +50,7 @@ if __name__=='__main__':
|
|||
tim.append(end-strt)
|
||||
print("No of Inputs Time Taken")
|
||||
for i in range(len(inputs)):
|
||||
print((inputs[i],'\t\t',tim[i]))
|
||||
print(inputs[i],'\t\t',tim[i])
|
||||
plt.plot(inputs,tim)
|
||||
plt.xlabel("Number of Inputs");plt.ylabel("Time taken in seconds ")
|
||||
plt.show()
|
||||
|
|
19
factorial_python.py
Normal file
19
factorial_python.py
Normal file
|
@ -0,0 +1,19 @@
|
|||
# Python program to find the factorial of a number provided by the user.
|
||||
|
||||
# change the value for a different result
|
||||
num = 10
|
||||
|
||||
# uncomment to take input from the user
|
||||
#num = int(input("Enter a number: "))
|
||||
|
||||
factorial = 1
|
||||
|
||||
# check if the number is negative, positive or zero
|
||||
if num < 0:
|
||||
print("Sorry, factorial does not exist for negative numbers")
|
||||
elif num == 0:
|
||||
print("The factorial of 0 is 1")
|
||||
else:
|
||||
for i in range(1,num + 1):
|
||||
factorial = factorial*i
|
||||
print("The factorial of",num,"is",factorial)
|
|
@ -1,12 +1,8 @@
|
|||
import math
|
||||
def primeCheck(number):
|
||||
prime = True
|
||||
for i in range(2, int(number**(0.5)+1), 2):
|
||||
if i != 2:
|
||||
i = i - 1
|
||||
if number % i == 0:
|
||||
prime = False
|
||||
break
|
||||
return prime
|
||||
if number % 2 == 0 and number > 2:
|
||||
return False
|
||||
return all(number % i for i in range(3, int(math.sqrt(number)) + 1, 2))
|
||||
|
||||
def main():
|
||||
print(primeCheck(37))
|
||||
|
|
|
@ -1,8 +1,11 @@
|
|||
# Fibonacci Sequence Using Recursion
|
||||
|
||||
def recur_fibo(n):
|
||||
return n if n <= 1 else (recur_fibo(n-1) + recur_fibo(n-2))
|
||||
|
||||
if n <= 1:
|
||||
return n
|
||||
else:
|
||||
(recur_fibo(n-1) + recur_fibo(n-2))
|
||||
|
||||
def isPositiveInteger(limit):
|
||||
return limit >= 0
|
||||
|
||||
|
|
29
simple_client/client.py
Normal file
29
simple_client/client.py
Normal file
|
@ -0,0 +1,29 @@
|
|||
# client.py
|
||||
|
||||
import socket
|
||||
|
||||
HOST, PORT = '127.0.0.1', 1400
|
||||
|
||||
s = socket.socket(
|
||||
|
||||
socket.AF_INET, # ADDRESS FAMILIES
|
||||
#Name Purpose
|
||||
#AF_UNIX, AF_LOCAL Local communication
|
||||
#AF_INET IPv4 Internet protocols
|
||||
#AF_INET6 IPv6 Internet protocols
|
||||
#AF_APPLETALK Appletalk
|
||||
#AF_BLUETOOTH Bluetooth
|
||||
|
||||
|
||||
socket.SOCK_STREAM # SOCKET TYPES
|
||||
#Name Way of Interaction
|
||||
#SOCK_STREAM TCP
|
||||
#SOCK_DGRAM UDP
|
||||
)
|
||||
s.connect((HOST, PORT))
|
||||
|
||||
s.send('Hello World'.encode('ascii'))#in UDP use sendto()
|
||||
data = s.recv(1024)#in UDP use recvfrom()
|
||||
|
||||
s.close()#end the connection
|
||||
print(repr(data.decode('ascii')))
|
21
simple_client/server.py
Normal file
21
simple_client/server.py
Normal file
|
@ -0,0 +1,21 @@
|
|||
# server.py
|
||||
|
||||
import socket
|
||||
|
||||
HOST, PORT = '127.0.0.1', 1400
|
||||
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)#refer to client.py
|
||||
s.bind((HOST, PORT))
|
||||
s.listen(1)#listen for 1 connection
|
||||
|
||||
conn, addr = s.accept()#start the actual data flow
|
||||
|
||||
print('connected to:', addr)
|
||||
|
||||
while 1:
|
||||
data = conn.recv(1024).decode('ascii')#receive 1024 bytes and decode using ascii
|
||||
if not data:
|
||||
break
|
||||
conn.send((data + ' [ addition by server ]').encode('ascii'))
|
||||
|
||||
conn.close()
|
|
@ -1,14 +0,0 @@
|
|||
# client.py
|
||||
|
||||
import socket
|
||||
|
||||
HOST, PORT = '127.0.0.1', 1400
|
||||
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
s.connect((HOST, PORT))
|
||||
|
||||
s.send(b'Hello World')
|
||||
data = s.recv(1024)
|
||||
|
||||
s.close()
|
||||
print(repr(data.decode('ascii')))
|
|
@ -1,21 +0,0 @@
|
|||
# server.py
|
||||
|
||||
import socket
|
||||
|
||||
HOST, PORT = '127.0.0.1', 1400
|
||||
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
s.bind((HOST, PORT))
|
||||
s.listen(1)
|
||||
|
||||
conn, addr = s.accept()
|
||||
|
||||
print('connected to:', addr)
|
||||
|
||||
while 1:
|
||||
data = conn.recv(1024)
|
||||
if not data:
|
||||
break
|
||||
conn.send(data + b' [ addition by server ]')
|
||||
|
||||
conn.close()
|
|
@ -17,6 +17,9 @@ def bubble_sort(collection):
|
|||
|
||||
>>> bubble_sort([-2, -5, -45])
|
||||
[-45, -5, -2]
|
||||
|
||||
>>> bubble_sort([-23,0,6,-4,34])
|
||||
[-23,-4,0,6,34]
|
||||
"""
|
||||
length = len(collection)
|
||||
for i in range(length-1):
|
||||
|
|
Loading…
Reference in New Issue
Block a user