Skip to content

Commit d0f3150

Browse files
authored
Merge pull request #1 from TheAlgorithms/master
fellow Python's master
2 parents 48553da + 70bb6b2 commit d0f3150

File tree

10 files changed

+298
-21
lines changed

10 files changed

+298
-21
lines changed

Graphs/pagerank.py

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
'''
2+
Author: https://github.com/bhushan-borole
3+
'''
4+
'''
5+
The input graph for the algorithm is:
6+
7+
A B C
8+
A 0 1 1
9+
B 0 0 1
10+
C 1 0 0
11+
12+
'''
13+
14+
graph = [[0, 1, 1],
15+
[0, 0, 1],
16+
[1, 0, 0]]
17+
18+
19+
class Node:
20+
def __init__(self, name):
21+
self.name = name
22+
self.inbound = []
23+
self.outbound = []
24+
25+
def add_inbound(self, node):
26+
self.inbound.append(node)
27+
28+
def add_outbound(self, node):
29+
self.outbound.append(node)
30+
31+
def __repr__(self):
32+
return 'Node {}: Inbound: {} ; Outbound: {}'.format(self.name,
33+
self.inbound,
34+
self.outbound)
35+
36+
37+
def page_rank(nodes, limit=3, d=0.85):
38+
ranks = {}
39+
for node in nodes:
40+
ranks[node.name] = 1
41+
42+
outbounds = {}
43+
for node in nodes:
44+
outbounds[node.name] = len(node.outbound)
45+
46+
for i in range(limit):
47+
print("======= Iteration {} =======".format(i+1))
48+
for j, node in enumerate(nodes):
49+
ranks[node.name] = (1 - d) + d * sum([ ranks[ib]/outbounds[ib] for ib in node.inbound ])
50+
print(ranks)
51+
52+
53+
def main():
54+
names = list(input('Enter Names of the Nodes: ').split())
55+
56+
nodes = [Node(name) for name in names]
57+
58+
for ri, row in enumerate(graph):
59+
for ci, col in enumerate(row):
60+
if col == 1:
61+
nodes[ci].add_inbound(names[ri])
62+
nodes[ri].add_outbound(names[ci])
63+
64+
print("======= Nodes =======")
65+
for node in nodes:
66+
print(node)
67+
68+
page_rank(nodes)
69+
70+
71+
if __name__ == '__main__':
72+
main()

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
# The Algorithms - Python <!-- [![Build Status](https://travis-ci.org/TheAlgorithms/Python.svg)](https://travis-ci.org/TheAlgorithms/Python) -->
2+
[![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.me/TheAlgorithms/100)
3+
24

35
### All algorithms implemented in Python (for education)
46

compression/huffman.py

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
import sys
2+
3+
class Letter:
4+
def __init__(self, letter, freq):
5+
self.letter = letter
6+
self.freq = freq
7+
self.bitstring = ""
8+
9+
def __repr__(self):
10+
return f'{self.letter}:{self.freq}'
11+
12+
13+
class TreeNode:
14+
def __init__(self, freq, left, right):
15+
self.freq = freq
16+
self.left = left
17+
self.right = right
18+
19+
20+
def parse_file(file_path):
21+
"""
22+
Read the file and build a dict of all letters and their
23+
frequences, then convert the dict into a list of Letters.
24+
"""
25+
chars = {}
26+
with open(file_path) as f:
27+
while True:
28+
c = f.read(1)
29+
if not c:
30+
break
31+
chars[c] = chars[c] + 1 if c in chars.keys() else 1
32+
letters = []
33+
for char, freq in chars.items():
34+
letter = Letter(char, freq)
35+
letters.append(letter)
36+
letters.sort(key=lambda l: l.freq)
37+
return letters
38+
39+
def build_tree(letters):
40+
"""
41+
Run through the list of Letters and build the min heap
42+
for the Huffman Tree.
43+
"""
44+
while len(letters) > 1:
45+
left = letters.pop(0)
46+
right = letters.pop(0)
47+
total_freq = left.freq + right.freq
48+
node = TreeNode(total_freq, left, right)
49+
letters.append(node)
50+
letters.sort(key=lambda l: l.freq)
51+
return letters[0]
52+
53+
def traverse_tree(root, bitstring):
54+
"""
55+
Recursively traverse the Huffman Tree to set each
56+
Letter's bitstring, and return the list of Letters
57+
"""
58+
if type(root) is Letter:
59+
root.bitstring = bitstring
60+
return [root]
61+
letters = []
62+
letters += traverse_tree(root.left, bitstring + "0")
63+
letters += traverse_tree(root.right, bitstring + "1")
64+
return letters
65+
66+
def huffman(file_path):
67+
"""
68+
Parse the file, build the tree, then run through the file
69+
again, using the list of Letters to find and print out the
70+
bitstring for each letter.
71+
"""
72+
letters_list = parse_file(file_path)
73+
root = build_tree(letters_list)
74+
letters = traverse_tree(root, "")
75+
print(f'Huffman Coding of {file_path}: ')
76+
with open(file_path) as f:
77+
while True:
78+
c = f.read(1)
79+
if not c:
80+
break
81+
le = list(filter(lambda l: l.letter == c, letters))[0]
82+
print(le.bitstring, end=" ")
83+
print()
84+
85+
if __name__ == "__main__":
86+
# pass the file path to the huffman function
87+
huffman(sys.argv[1])

graphs/Directed and Undirected (Weighted) Graph.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,7 @@ def cycle_nodes(self):
152152
parent = -2
153153
indirect_parents = []
154154
ss = s
155+
on_the_way_back = False
155156
anticipating_nodes = set()
156157

157158
while True:
@@ -199,6 +200,7 @@ def has_cycle(self):
199200
parent = -2
200201
indirect_parents = []
201202
ss = s
203+
on_the_way_back = False
202204
anticipating_nodes = set()
203205

204206
while True:
@@ -367,6 +369,7 @@ def cycle_nodes(self):
367369
parent = -2
368370
indirect_parents = []
369371
ss = s
372+
on_the_way_back = False
370373
anticipating_nodes = set()
371374

372375
while True:
@@ -414,6 +417,7 @@ def has_cycle(self):
414417
parent = -2
415418
indirect_parents = []
416419
ss = s
420+
on_the_way_back = False
417421
anticipating_nodes = set()
418422

419423
while True:

maths/BinaryExponentiation.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
#Author : Junth Basnet
2+
#Time Complexity : O(logn)
3+
4+
def binary_exponentiation(a, n):
5+
6+
if (n == 0):
7+
return 1
8+
9+
elif (n % 2 == 1):
10+
return binary_exponentiation(a, n - 1) * a
11+
12+
else:
13+
b = binary_exponentiation(a, n / 2)
14+
return b * b
15+
16+
17+
try:
18+
base = int(input('Enter Base : '))
19+
power = int(input("Enter Power : "))
20+
except ValueError:
21+
print ("Invalid literal for integer")
22+
23+
result = binary_exponentiation(base, power)
24+
print("{}^({}) : {}".format(base, power, result))
25+

maths/PrimeCheck.py

Lines changed: 48 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,54 @@
11
import math
2+
import unittest
3+
4+
25
def primeCheck(number):
3-
if number % 2 == 0 and number > 2:
6+
"""
7+
A number is prime if it has exactly two dividers: 1 and itself.
8+
"""
9+
if number < 2:
10+
# Negatives, 0 and 1 are not primes
411
return False
5-
return all(number % i for i in range(3, int(math.sqrt(number)) + 1, 2))
12+
if number < 4:
13+
# 2 and 3 are primes
14+
return True
15+
if number % 2 == 0:
16+
# Even values are not primes
17+
return False
18+
19+
# Except 2, all primes are odd. If any odd value divide
20+
# the number, then that number is not prime.
21+
odd_numbers = range(3, int(math.sqrt(number)) + 1, 2)
22+
return not any(number % i == 0 for i in odd_numbers)
23+
24+
25+
class Test(unittest.TestCase):
26+
def test_primes(self):
27+
self.assertTrue(primeCheck(2))
28+
self.assertTrue(primeCheck(3))
29+
self.assertTrue(primeCheck(5))
30+
self.assertTrue(primeCheck(7))
31+
self.assertTrue(primeCheck(11))
32+
self.assertTrue(primeCheck(13))
33+
self.assertTrue(primeCheck(17))
34+
self.assertTrue(primeCheck(19))
35+
self.assertTrue(primeCheck(23))
36+
self.assertTrue(primeCheck(29))
37+
38+
def test_not_primes(self):
39+
self.assertFalse(primeCheck(-19),
40+
"Negative numbers are not prime.")
41+
self.assertFalse(primeCheck(0),
42+
"Zero doesn't have any divider, primes must have two")
43+
self.assertFalse(primeCheck(1),
44+
"One just have 1 divider, primes must have two.")
45+
self.assertFalse(primeCheck(2 * 2))
46+
self.assertFalse(primeCheck(2 * 3))
47+
self.assertFalse(primeCheck(3 * 3))
48+
self.assertFalse(primeCheck(3 * 5))
49+
self.assertFalse(primeCheck(3 * 5 * 7))
650

7-
def main():
8-
print(primeCheck(37))
9-
print(primeCheck(100))
10-
print(primeCheck(77))
1151

1252
if __name__ == '__main__':
13-
main()
53+
unittest.main()
54+

other/sierpinski_triangle.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
Usage:
2222
- $python sierpinski_triangle.py <int:depth_for_fractal>
2323
24-
Credits: This code was written by editing the code from http://www.lpb-riannetrujillo.com/blog/python-fractal/
24+
Credits: This code was written by editing the code from http://www.riannetrujillo.com/blog/python-fractal/
2525
2626
'''
2727
import turtle
@@ -64,4 +64,4 @@ def triangle(points,depth):
6464
depth-1)
6565

6666

67-
triangle(points,int(sys.argv[1]))
67+
triangle(points,int(sys.argv[1]))

project_euler/problem_02/sol4.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import math
2+
from decimal import *
3+
4+
getcontext().prec = 100
5+
phi = (Decimal(5) ** Decimal(0.5) + 1) / Decimal(2)
6+
7+
n = Decimal(int(input()) - 1)
8+
9+
index = (math.floor(math.log(n * (phi + 2), phi) - 1) // 3) * 3 + 2
10+
num = round(phi ** Decimal(index + 1)) / (phi + 2)
11+
sum = num // 2
12+
13+
print(int(sum))

searches/binary_search.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,10 @@
2121
def binary_search(sorted_collection, item):
2222
"""Pure implementation of binary search algorithm in Python
2323
24-
Be careful collection must be sorted, otherwise result will be
24+
Be careful collection must be ascending sorted, otherwise result will be
2525
unpredictable
2626
27-
:param sorted_collection: some sorted collection with comparable items
27+
:param sorted_collection: some ascending sorted collection with comparable items
2828
:param item: item value to search
2929
:return: index of found item or None if item is not found
3030
@@ -60,10 +60,10 @@ def binary_search(sorted_collection, item):
6060
def binary_search_std_lib(sorted_collection, item):
6161
"""Pure implementation of binary search algorithm in Python using stdlib
6262
63-
Be careful collection must be sorted, otherwise result will be
63+
Be careful collection must be ascending sorted, otherwise result will be
6464
unpredictable
6565
66-
:param sorted_collection: some sorted collection with comparable items
66+
:param sorted_collection: some ascending sorted collection with comparable items
6767
:param item: item value to search
6868
:return: index of found item or None if item is not found
6969
@@ -89,11 +89,11 @@ def binary_search_by_recursion(sorted_collection, item, left, right):
8989

9090
"""Pure implementation of binary search algorithm in Python by recursion
9191
92-
Be careful collection must be sorted, otherwise result will be
92+
Be careful collection must be ascending sorted, otherwise result will be
9393
unpredictable
9494
First recursion should be started with left=0 and right=(len(sorted_collection)-1)
9595
96-
:param sorted_collection: some sorted collection with comparable items
96+
:param sorted_collection: some ascending sorted collection with comparable items
9797
:param item: item value to search
9898
:return: index of found item or None if item is not found
9999
@@ -123,11 +123,11 @@ def binary_search_by_recursion(sorted_collection, item, left, right):
123123
return binary_search_by_recursion(sorted_collection, item, midpoint+1, right)
124124

125125
def __assert_sorted(collection):
126-
"""Check if collection is sorted, if not - raises :py:class:`ValueError`
126+
"""Check if collection is ascending sorted, if not - raises :py:class:`ValueError`
127127
128128
:param collection: collection
129-
:return: True if collection is sorted
130-
:raise: :py:class:`ValueError` if collection is not sorted
129+
:return: True if collection is ascending sorted
130+
:raise: :py:class:`ValueError` if collection is not ascending sorted
131131
132132
Examples:
133133
>>> __assert_sorted([0, 1, 2, 4])
@@ -136,10 +136,10 @@ def __assert_sorted(collection):
136136
>>> __assert_sorted([10, -1, 5])
137137
Traceback (most recent call last):
138138
...
139-
ValueError: Collection must be sorted
139+
ValueError: Collection must be ascending sorted
140140
"""
141141
if collection != sorted(collection):
142-
raise ValueError('Collection must be sorted')
142+
raise ValueError('Collection must be ascending sorted')
143143
return True
144144

145145

@@ -150,7 +150,7 @@ def __assert_sorted(collection):
150150
try:
151151
__assert_sorted(collection)
152152
except ValueError:
153-
sys.exit('Sequence must be sorted to apply binary search')
153+
sys.exit('Sequence must be ascending sorted to apply binary search')
154154

155155
target_input = raw_input('Enter a single number to be found in the list:\n')
156156
target = int(target_input)

0 commit comments

Comments
 (0)