Browse Source

Merge pull request #5 from jrtechs/master

Changes
pull/16/head
Sunny Patel 5 years ago
committed by GitHub
parent
commit
f184eab8df
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 550 additions and 3 deletions
  1. +3
    -0
      .gitignore
  2. +46
    -1
      README.md
  3. +63
    -0
      other/PortScan.py
  4. +46
    -0
      other/Stack.py
  5. +37
    -0
      searching_algo/DFS.py
  6. +12
    -0
      searching_algo/binary_search.py
  7. +6
    -0
      searching_algo/linera_search.py
  8. +14
    -0
      sorting/CombSort.py
  9. +172
    -0
      sorting/bintree.py
  10. +27
    -0
      sorting/merge_sort.py
  11. +44
    -0
      sorting/queque.py
  12. +50
    -2
      sorting/quickSort.py
  13. +14
    -0
      sorting/radix_sort.py
  14. +16
    -0
      sorting/selectionsort.py

+ 3
- 0
.gitignore View File

@ -102,3 +102,6 @@ venv.bak/
# mypy
.mypy_cache/
#texteditor
.vscode

+ 46
- 1
README.md View File

@ -4,4 +4,49 @@
```bash
python -m pip install -U pip
python -m pip install -U matplotlib
```
```
## Contributing
Modified from [Atom's CONTRIBUTING.md](https://github.com/atom/atom/blob/master/CONTRIBUTING.md#how-can-i-contribute)
First off, thanks for taking the time to contribute!
The following is a set of guidelines for contributing. These are mostly
guidelines, not rules. Use your best judgment, and feel free to propose changes
to this document in a pull request.
### How Can I Contribute?
#### Basic Guide
1. Fork the repository
2. `git clone` the repository to your local working space
3. Make changes
4. `git status` to check your untracked changes, `git add` added/modified files
5. `git commit` your changes, include a message if you want.
6. `git push` to your forked repository
7. Open a pull request in GitHub.
#### Reporting Bugs
How Do I Submit A (Good) Bug Report?
Bugs are tracked as GitHub issues. After you've determined which repository your bug is related to, create an issue on that repository and provide the following information by filling in the template.
Explain the problem and include additional details to help maintainers reproduce the problem:
- Use a **clear and descriptive title** for the issue to identify the problem.
- **Describe the exact steps** which reproduce the problem in as many details as possible. When listing steps, don't just say what you did, but explain how you did it.
- **Provide specific examples** to demonstrate the steps. Include links to files or GitHub projects, or copy/pasteable snippets, which you use in those examples. If you're providing snippets in the issue, use Markdown code blocks.
- **Describe the behavior** you observed after following the steps and point out what exactly is the problem with that behavior.
- Explain which **behavior you expected** to see instead and why.
### Suggesting Enhancements
#### How Do I Submit A (Good) Enhancement Suggestion?
Enhancement suggestions are tracked as GitHub issues. Create an issue on the repository and provide the following information:
- Use a **clear and descriptive title** for the issue to identify the suggestion.
- **Provide specific examples** to demonstrate the steps. Include copy/pasteable snippets which you use in those examples, as Markdown code blocks.
- **Describe the current behavior** and explain which behavior you expected to see instead and why.

+ 63
- 0
other/PortScan.py View File

@ -0,0 +1,63 @@
#!/usr/bin/env python3
''' PortScan v3
-----------
This application scans for open ports on the designated system. It uses
multiprocessing to speed up this process.
'''
import socket
import subprocess
import sys
from datetime import datetime
from multiprocessing import Pool
def scan(port):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((target_ip, port))
if result == 0:
print("Port {}:\tOpen".format(port))
sock.close()
except socket.gaierror:
print('Hostname could not be resolved.')
sys.exit(0)
except socket.error:
print("Couldn't connect to server.")
sys.exit(0)
except:
return
if __name__ == '__main__':
ports = list(range(1,4096))
target = ''
try:
target = sys.argv[1]
except:
print("\nUsage:\t{} [target]\n\n\tScan for open ports on target machine.\n".format(sys.argv[0]))
sys.exit(0)
# Clear the screen
subprocess.call('clear', shell=True)
target_ip = socket.gethostbyname(target)
# Print a nice banner with information on which host we are about to scan
print("-" * 60)
print("Please wait, scanning remote host", target_ip)
print("-" * 60)
# Check what time the scan started
t1 = datetime.now()
with Pool(processes = 8) as p:
p.map(scan, ports)
# Checking the time again
t2 = datetime.now()
# Calculates the difference of time, to see how long it took to run the script
total = t2 - t1
# Printing the information to screen
print('Scanning Completed in: ', total)

+ 46
- 0
other/Stack.py View File

@ -0,0 +1,46 @@
class Stack:
def __init__ (self):
self.items = list()
def push (self, item):
self.items.append (item)
def pop (self):
if len(self.items) > 0:
return self.items.pop()
return ('Stack is empty')
def isEmpty (self):
return self.items == list()
def size (self):
return len(self.items)
def peek (self):
return self.items[0]
def printStack (self):
print(self.items)
if __name__ == '__main__':
my_stack = Stack()
my_stack.push(1)
my_stack.printStack()
my_stack.push(5)
my_stack.push(3)
my_stack.printStack()
print('Pop {} from stack'.format(my_stack.pop()))
my_stack.printStack()
print('Now stack size is {}'.format(my_stack.size()))
print('First element in stack is {}'.format(my_stack.peek()))
print('Pop {} from stack'.format(my_stack.pop()))
my_stack.printStack()
print('Pop {} from stack'.format(my_stack.pop()))
my_stack.printStack()
print('Now stack size is {}'.format(my_stack.size()))
print(my_stack.pop())

+ 37
- 0
searching_algo/DFS.py View File

@ -0,0 +1,37 @@
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self,u,v):
self.graph[u].append(v)
def DFSUtil(self,v,visited):
visited[v]= True
print v,
for i in self.graph[v]:
if visited[i] == False:
self.DFSUtil(i, visited)
def DFS(self,v):
visited = [False]*(len(self.graph))
self.DFSUtil(v,visited)
g = Graph()
edges = input("input the number of edges : ")
print "enter nodes with zero based indexing : "
for i in range(edges):
a, b = map(int, raw_input().split())
g.addEdge(a, b)
check = input("DFS check from node : ")
g.DFS(check)

+ 12
- 0
searching_algo/binary_search.py View File

@ -0,0 +1,12 @@
def binary_search(arr,element):
lower = 0
upper = len(arr) - 1
while(lower < upper):
mid = (lower + (upper - 1)) // 2
if arr[mid] > element:
upper = mid-1
elif arr[mid] < element:
lower = mid + 1
else:
return True
return False

+ 6
- 0
searching_algo/linera_search.py View File

@ -0,0 +1,6 @@
def linear_search(arr, element):
for i in arr:
if i == element:
return True
return False

+ 14
- 0
sorting/CombSort.py View File

@ -0,0 +1,14 @@
def combsort(numbers_list):
ordered = numbers_list.copy()
gap = len(numbers_list) # initial gap (first and last element)
swaps = True
while swaps or gap!=1:
swaps = False
for i in range(len(numbers_list)-gap):
if ordered[i] > ordered[i+gap]: # swaps without extra variable
ordered[i] = ordered[i+gap] - ordered[i]
ordered[i+gap] = ordered[i+gap] - ordered[i]
ordered[i] = ordered[i+gap] + ordered[i]
swaps = True
gap = max(gap-1, 1) # update gap, minimum gap is 1
return ordered

+ 172
- 0
sorting/bintree.py View File

@ -0,0 +1,172 @@
class Node():
def __init__(self,key):
self.key = key
self.left = None
self.right = None
self.parent = None
class Tree():
def __init__(self):
self.root = None
def add_node(self,key,node=None):
if node is None:
node = self.root
if self.root is None:
self.root = Node(key)
else:
if key <= node.key :
if node.left is None:
node.left = Node(key)
node.left.parent = node
print "left"
return
else:
# return self.add_node(key,node = self.root.left)
return self.add_node(key,node = node.left)
else:
if node.right is None:
node.right = Node(key)
node.right.parent = node
print "right"
return
else:
# return self.add_node(key,node = self.root.right)
return self.add_node(key,node = node.right)
def search(self,key,node = None):
if node is None:
node = self.root
if self.root.key == key:
print "key is at the root"
return self.root
else:
if node.key == key :
print "key exists"
return node
elif key < node.key and node.left is not None:
print "left"
return self.search(key,node = node.left)
elif key > node.key and node.right is not None:
print "right"
return self.search(key,node = node.right)
else:
print "key does not exist"
return None
def delete_node(self,key,node=None):
#search for the node to be deleted in tree
if node is None:
node = self.search(key)#return the node to be deleted
#root has no parent node
if self.root.key == node.key: #if it is root
parent_node = self.root
else:
parent_node = node.parent
'''case 1: The node has no chidren'''
if node.left is None and node.right is None:
if key <= parent_node.key:
parent_node.left = None
else:
parent_node.right = None
return
'''case 2: The node has children'''
''' if it has a single left node'''
if node.left is not None and node.right is None :
if node.left.key < parent_node.key :
parent_node.left = node.left
else:
parent_node.right = node.left
return
'''if it has a single right node'''
if node.right is not None and node.left is None:
if node.key <= parent_node.key:
parent_node.left = node.right
else:
parent_node.right = node.right
return
'''if it has two children'''
'''find the node with the minimum value from the right subtree.
copy its value to thhe node which needs to be removed.
right subtree now has a duplicate and so remove it.'''
if node.left is not None and node.right is not None:
min_value = self.find_minimum(node)
node.key = min_value.key
min_value.parent.left = None
return
def find_minimum(self,node = None):
if node is None:
node = self.root
'''find mimimum value from the right subtree'''
'''case when there is only a root node'''
if node.right is not None:
node = node.right
else:
return node
if node.left is not None:
return self.find_minimum(node = node.left)
else:
return node
def tree_data(self,node=None):
if node is None:
node = self.root
stack = []
while stack or node:
if node is not None:
stack.append(node)
node = node.left
else:
node = stack.pop()
yield node.key
node = node.right
t=Tree()
t.add_node(10)
t.add_node(13)
t.add_node(14)
t.add_node(8)
t.add_node(9)
t.add_node(7)
t.add_node(11)
'''
10---8---7
| |
| ---9
---13---11
|
---14
'''

+ 27
- 0
sorting/merge_sort.py View File

@ -0,0 +1,27 @@
def merge_sort(a):
if len(a) < 2:
return a
l = a[0:len(a)//2]
r = a[len(a)//2:]
return merge(merge_sort(l), merge_sort(r))
def merge(a, b):
out = []
i = 0
j = 0
while i < len(a) or j < len(b):
if i >= len(a):
out.append(b[j])
j += 1
elif j >= len(b):
out.append(a[i])
i += 1
else:
if a[i] <= b[j]:
out.append(a[i])
i += 1
else:
out.append(b[j])
j += 1
return out

+ 44
- 0
sorting/queque.py View File

@ -0,0 +1,44 @@
class Queque:
def __init__(self):
self.queque = []
def enqueue(self, data):
if data not in self.queque:
self.queque.append(data)
return True
return False
def dequeue(self):
if len(self.queque) > 0:
return self.queque.pop(0)
return ('Queque empty')
def sizeQueque(self):
return len(self.queque)
def printQueque(self):
return self.queque
if __name__ == '__main__':
myqueque = Queque()
data = myqueque.enqueue(5)
data = myqueque.enqueue(6)
data = myqueque.enqueue(7)
data = myqueque.enqueue(10)
print(myqueque.sizeQueque())
print(myqueque.printQueque())
dequeue = myqueque.dequeue() # delete 5
dequeue = myqueque.dequeue() # delete 6
print(myqueque.printQueque())
print(myqueque.sizeQueque())

+ 50
- 2
sorting/quickSort.py View File

@ -49,7 +49,7 @@ def quick_sort_accumulation(data, a):
return a
less, equal, greater = partition(data)
return quick_sort_accumulation(less,
equal + quick_sort_accumulation(greater, a))
equal + quick_sort_accumulation(greater, a))
def quicksort(data):
@ -59,5 +59,53 @@ def quicksort(data):
return quick_sort_accumulation(data, [])
def iterative_partition(data, left, right):
"""
Function which partitions the data into two segments,
the left which is less than the pivot and the right
which is greater than the pivot. The pivot for this
algo is the right most index. This function returns
the ending index of the pivot.
:param data: array to be sorted
:param left: left most portion of array to look at
:param right: right most portion of the array to look at
"""
x = data[right]
i = left - 1
j = left
while j < right:
if data[j] <= x:
i = i + 1
data[i], data[j] = data[j], data[i]
j = j+1
data[i + 1], data[right] = data[right], data[i + 1]
return i + 1
def iterative_quick_sort(data):
"""
In place implementation of quick sort
Wrapper function for iterative_quick_sort_helper which
initalizes, left, right to be the extrema of the array.
"""
iterative_quick_sort_helper(data, 0, len(data) -1)
return data
def iterative_quick_sort_helper(data, left, right):
"""
Uses the divide and conquer algo to sort an array
:param data: array of data
:param left: left index bound for sorting
:param right: right bound for sorting
"""
if left < right:
pivot = iterative_partition(data, left, right)
iterative_quick_sort_helper(data, left, pivot -1)
iterative_quick_sort_helper(data, pivot+1, right)
print quicksort([1,3,1,5,7,9,2,3,5,5,6])
print iterative_quick_sort([1,3,1,5,7,9,2,3,5,5,6])

+ 14
- 0
sorting/radix_sort.py View File

@ -0,0 +1,14 @@
def radix_sort(lista):
max_len = max([len(numero) for numero in lista])
padded = list([str(num).rjust(max_len, "0") for num in lista])
for pos in reversed(range(max_len)):
buckets = [list() for x in range(0, 10)]
for num in padded:
bucket = int(num[pos])
buckets[bucket] += [num]
padded = sum(buckets, [])
return padded
if __name__ == "__main__":
print(radix_sort(["13", "105", "10", "150"]))

+ 16
- 0
sorting/selectionsort.py View File

@ -0,0 +1,16 @@
#selection sorting
import sys
A = [6, 2, 1, 3, 4]
for i in range(len(A)):
min_index = i
for j in range(i+1, len(A)):
if A[min_index] > A[j]:
min_index = j
A[i], A[min_index] = A[min_index], A[i]
print ("Sorted array")
for i in range(len(A)):
print("%d" %A[i])

Loading…
Cancel
Save