diff --git a/DIRECTORY.md b/DIRECTORY.md index d9196e130196692e8940629bd7e73cc3e8314aae..866e0d658bf660c9c65bc826a368a7b2090d4483 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -323,6 +323,10 @@ * [Sdbm](https://github.com/TheAlgorithms/Python/blob/master/hashes/sdbm.py) * [Sha1](https://github.com/TheAlgorithms/Python/blob/master/hashes/sha1.py) +## Knapsack + * [Knapsack](https://github.com/TheAlgorithms/Python/blob/master/knapsack/knapsack.py) + * [Test Knapsack](https://github.com/TheAlgorithms/Python/blob/master/knapsack/test_knapsack.py) + ## Linear Algebra * Src * [Lib](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/lib.py) @@ -502,6 +506,7 @@ * [Magicdiamondpattern](https://github.com/TheAlgorithms/Python/blob/master/other/magicdiamondpattern.py) * [Markov Chain](https://github.com/TheAlgorithms/Python/blob/master/other/markov_chain.py) * [Max Sum Sliding Window](https://github.com/TheAlgorithms/Python/blob/master/other/max_sum_sliding_window.py) + * [Median Of Two Arrays](https://github.com/TheAlgorithms/Python/blob/master/other/median_of_two_arrays.py) * [Nested Brackets](https://github.com/TheAlgorithms/Python/blob/master/other/nested_brackets.py) * [Palindrome](https://github.com/TheAlgorithms/Python/blob/master/other/palindrome.py) * [Password Generator](https://github.com/TheAlgorithms/Python/blob/master/other/password_generator.py) diff --git a/ciphers/simple_substitution_cipher.py b/ciphers/simple_substitution_cipher.py index f5b711e616af8630205ce9cddcac99426e57ee18..646ea449fc06ae229e1c894bba178cdf34e92507 100644 --- a/ciphers/simple_substitution_cipher.py +++ b/ciphers/simple_substitution_cipher.py @@ -18,7 +18,7 @@ def main(): mode = "decrypt" translated = decryptMessage(key, message) - print("\n{}ion: \n{}".format(mode.title(), translated)) + print(f"\n{mode.title()}ion: \n{translated}") def checkValidKey(key: str) -> None: diff --git a/ciphers/xor_cipher.py b/ciphers/xor_cipher.py index 27e4262bc924d7beb86f5912d0f5a21bd86a9915..32a350d4e61cc9567a1579730d958a27315dbbc5 100644 --- a/ciphers/xor_cipher.py +++ b/ciphers/xor_cipher.py @@ -141,14 +141,14 @@ class XORCipher: assert isinstance(file, str) and isinstance(key, int) try: - with open(file, "r") as fin: + with open(file) as fin: with open("encrypt.out", "w+") as fout: # actual encrypt-process for line in fin: fout.write(self.encrypt_string(line, key)) - except IOError: + except OSError: return False return True @@ -166,14 +166,14 @@ class XORCipher: assert isinstance(file, str) and isinstance(key, int) try: - with open(file, "r") as fin: + with open(file) as fin: with open("decrypt.out", "w+") as fout: # actual encrypt-process for line in fin: fout.write(self.decrypt_string(line, key)) - except IOError: + except OSError: return False return True diff --git a/compression/lempel_ziv.py b/compression/lempel_ziv.py index 3ac8573c43d8e89c0b338cf45c7235416ce81d01..2d0601b27b3434385dbfe279feebeb564c9e891d 100644 --- a/compression/lempel_ziv.py +++ b/compression/lempel_ziv.py @@ -17,10 +17,10 @@ def read_file_binary(file_path: str) -> str: with open(file_path, "rb") as binary_file: data = binary_file.read() for dat in data: - curr_byte = "{0:08b}".format(dat) + curr_byte = f"{dat:08b}" result += curr_byte return result - except IOError: + except OSError: print("File not accessible") sys.exit() @@ -105,7 +105,7 @@ def write_file_binary(file_path: str, to_write: str) -> None: for elem in result_byte_array: opened_file.write(int(elem, 2).to_bytes(1, byteorder="big")) - except IOError: + except OSError: print("File not accessible") sys.exit() diff --git a/compression/lempel_ziv_decompress.py b/compression/lempel_ziv_decompress.py index 05c26740bf62c701cd0775bd537a01d7fe7e3df8..4d3c2c0d2cf305c14fb17d38e5a99ab4423a9635 100644 --- a/compression/lempel_ziv_decompress.py +++ b/compression/lempel_ziv_decompress.py @@ -16,10 +16,10 @@ def read_file_binary(file_path: str) -> str: with open(file_path, "rb") as binary_file: data = binary_file.read() for dat in data: - curr_byte = "{0:08b}".format(dat) + curr_byte = f"{dat:08b}" result += curr_byte return result - except IOError: + except OSError: print("File not accessible") sys.exit() @@ -76,7 +76,7 @@ def write_file_binary(file_path: str, to_write: str) -> None: for elem in result_byte_array[:-1]: opened_file.write(int(elem, 2).to_bytes(1, byteorder="big")) - except IOError: + except OSError: print("File not accessible") sys.exit() diff --git a/data_structures/binary_tree/segment_tree_other.py b/data_structures/binary_tree/segment_tree_other.py index df98eeffb3c65735429903e7f8284ae33be55e55..90afd7ca8b71a94f81a2741b9f788269b244c3a3 100644 --- a/data_structures/binary_tree/segment_tree_other.py +++ b/data_structures/binary_tree/segment_tree_other.py @@ -7,7 +7,7 @@ from collections.abc import Sequence from queue import Queue -class SegmentTreeNode(object): +class SegmentTreeNode: def __init__(self, start, end, val, left=None, right=None): self.start = start self.end = end @@ -17,10 +17,10 @@ class SegmentTreeNode(object): self.right = right def __str__(self): - return "val: %s, start: %s, end: %s" % (self.val, self.start, self.end) + return f"val: {self.val}, start: {self.start}, end: {self.end}" -class SegmentTree(object): +class SegmentTree: """ >>> import operator >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add) diff --git a/data_structures/heap/heap.py b/data_structures/heap/heap.py index b901c54a4284a81d781332243d7f5023a8cd6aa0..2dc047436a772f38a3d5fc20699656ea40936084 100644 --- a/data_structures/heap/heap.py +++ b/data_structures/heap/heap.py @@ -1,7 +1,7 @@ #!/usr/bin/python3 -class Heap(object): +class Heap: """ >>> unsorted = [103, 9, 1, 7, 11, 15, 25, 201, 209, 107, 5] >>> h = Heap() diff --git a/data_structures/linked_list/deque_doubly.py b/data_structures/linked_list/deque_doubly.py index b93fb8c4005e2b5a6f190cb1658392c9dbdac9b9..894f91d561cc6c90ef3ac48f31210e50aa5eb7f1 100644 --- a/data_structures/linked_list/deque_doubly.py +++ b/data_structures/linked_list/deque_doubly.py @@ -20,7 +20,7 @@ class _DoublyLinkedBase: self._next = link_n def has_next_and_prev(self): - return " Prev -> {0}, Next -> {1}".format( + return " Prev -> {}, Next -> {}".format( self._prev is not None, self._next is not None ) diff --git a/graphs/minimum_spanning_tree_boruvka.py b/graphs/minimum_spanning_tree_boruvka.py index 3b05f94b514045a42f61b8e545bd13dbd0fc8f04..32548b2ecb6c8f0863706b31ba80d68f755ab6a9 100644 --- a/graphs/minimum_spanning_tree_boruvka.py +++ b/graphs/minimum_spanning_tree_boruvka.py @@ -99,7 +99,7 @@ class Graph: g.add_edge(*edge) return g - class UnionFind(object): + class UnionFind: """ Disjoint set Union and Find for Boruvka's algorithm """ diff --git a/machine_learning/astar.py b/machine_learning/astar.py index 2f5c21a2bd5f93f999d0d41fc39b7aa9b738488c..ee3fcff0b7bf2413e4949fe6c3bc4e29b854c6b2 100644 --- a/machine_learning/astar.py +++ b/machine_learning/astar.py @@ -13,7 +13,7 @@ is made.A* also known as the algorithm with brains import numpy as np -class Cell(object): +class Cell: """ Class cell represents a cell in the world which have the property position : The position of the represented by tupleof x and y @@ -45,7 +45,7 @@ class Cell(object): print(self.position) -class Gridworld(object): +class Gridworld: """ Gridworld class represents the external world here a grid M*M matrix diff --git a/machine_learning/k_means_clust.py b/machine_learning/k_means_clust.py index 130e7f1ad6699f090bb71e9e4e9b6bd17a9dfdb8..f155d4845f413fef99ef7428c23d69d3d937ad0d 100644 --- a/machine_learning/k_means_clust.py +++ b/machine_learning/k_means_clust.py @@ -251,7 +251,7 @@ def ReportGenerator( lambda x: np.mean( np.nan_to_num( sorted(x)[ - round((len(x) * 25 / 100)) : round(len(x) * 75 / 100) + round(len(x) * 25 / 100) : round(len(x) * 75 / 100) ] ) ), diff --git a/maths/entropy.py b/maths/entropy.py index 74980ef9e0c681d948eb6ceae0d08ec0b5c0a5ff..43bb3860fc12cfb14f4d9242e489ca62bf986a6a 100644 --- a/maths/entropy.py +++ b/maths/entropy.py @@ -68,7 +68,7 @@ def calculate_prob(text: str) -> None: my_fir_sum += prob * math.log2(prob) # entropy formula. # print entropy - print("{0:.1f}".format(round(-1 * my_fir_sum))) + print("{:.1f}".format(round(-1 * my_fir_sum))) # two len string all_sum = sum(two_char_strings.values()) @@ -83,10 +83,10 @@ def calculate_prob(text: str) -> None: my_sec_sum += prob * math.log2(prob) # print second entropy - print("{0:.1f}".format(round(-1 * my_sec_sum))) + print("{:.1f}".format(round(-1 * my_sec_sum))) # print the difference between them - print("{0:.1f}".format(round(((-1 * my_sec_sum) - (-1 * my_fir_sum))))) + print("{:.1f}".format(round((-1 * my_sec_sum) - (-1 * my_fir_sum)))) def analyze_text(text: str) -> tuple[dict, dict]: diff --git a/maths/numerical_integration.py b/maths/numerical_integration.py index 67fbc0ddbf3080a8eea031c32c35f62350e94d97..87184a76b7405ce459d6a7f2d57b0fab8ec89ebe 100644 --- a/maths/numerical_integration.py +++ b/maths/numerical_integration.py @@ -62,5 +62,5 @@ if __name__ == "__main__": i = 10 while i <= 100000: area = trapezoidal_area(f, -5, 5, i) - print("with {} steps: {}".format(i, area)) + print(f"with {i} steps: {area}") i *= 10 diff --git a/project_euler/problem_013/sol1.py b/project_euler/problem_013/sol1.py index 19b427337c3d3d857e8c2cc6471e7023179422e4..1ea08b12ee93770fba42aaf85eea2c23a0b72f6d 100644 --- a/project_euler/problem_013/sol1.py +++ b/project_euler/problem_013/sol1.py @@ -17,7 +17,7 @@ def solution(): '5537376230' """ file_path = os.path.join(os.path.dirname(__file__), "num.txt") - with open(file_path, "r") as file_hand: + with open(file_path) as file_hand: return str(sum([int(line) for line in file_hand]))[:10] diff --git a/project_euler/problem_018/solution.py b/project_euler/problem_018/solution.py index 38593813901e83ebde96eeb296cf8ca841184e5c..82fc3ce3c9dbebd56f4bf8f93e2cd4eacd553681 100644 --- a/project_euler/problem_018/solution.py +++ b/project_euler/problem_018/solution.py @@ -41,7 +41,7 @@ def solution(): script_dir = os.path.dirname(os.path.realpath(__file__)) triangle = os.path.join(script_dir, "triangle.txt") - with open(triangle, "r") as f: + with open(triangle) as f: triangle = f.readlines() a = [[int(y) for y in x.rstrip("\r\n").split(" ")] for x in triangle] diff --git a/project_euler/problem_042/solution42.py b/project_euler/problem_042/solution42.py index 1e9bb49c7a06f694b32261a3f99eb25148acd80a..b3aecf4cf14473ae9979798259c81cff877b64cf 100644 --- a/project_euler/problem_042/solution42.py +++ b/project_euler/problem_042/solution42.py @@ -30,7 +30,7 @@ def solution(): wordsFilePath = os.path.join(script_dir, "words.txt") words = "" - with open(wordsFilePath, "r") as f: + with open(wordsFilePath) as f: words = f.readline() words = list(map(lambda word: word.strip('"'), words.strip("\r\n").split(","))) diff --git a/project_euler/problem_049/sol1.py b/project_euler/problem_049/sol1.py index 6c3d69ad0d1149b41d8bc8f0b31edcfca7ac1545..c0d0715be91c097be354196225faacb9162acc8e 100644 --- a/project_euler/problem_049/sol1.py +++ b/project_euler/problem_049/sol1.py @@ -114,7 +114,7 @@ def solution(): if ( abs(candidate[i] - candidate[j]) == abs(candidate[j] - candidate[k]) - and len(set([candidate[i], candidate[j], candidate[k]])) == 3 + and len({candidate[i], candidate[j], candidate[k]}) == 3 ): passed.append( sorted([candidate[i], candidate[j], candidate[k]]) diff --git a/project_euler/problem_054/sol1.py b/project_euler/problem_054/sol1.py index 4d75271784deb0e06dbf5cab5e068e9baaec7437..d2fd810d1b69933cfc94ed8f1d138463f37487c4 100644 --- a/project_euler/problem_054/sol1.py +++ b/project_euler/problem_054/sol1.py @@ -45,7 +45,7 @@ from __future__ import annotations import os -class PokerHand(object): +class PokerHand: """Create an object representing a Poker Hand based on an input of a string which represents the best 5 card combination from the player's hand and board cards. @@ -366,7 +366,7 @@ def solution() -> int: answer = 0 script_dir = os.path.abspath(os.path.dirname(__file__)) poker_hands = os.path.join(script_dir, "poker_hands.txt") - with open(poker_hands, "r") as file_hand: + with open(poker_hands) as file_hand: for line in file_hand: player_hand = line[:14].strip() opponent_hand = line[15:].strip() diff --git a/project_euler/problem_054/test_poker_hand.py b/project_euler/problem_054/test_poker_hand.py index f60c3aba66167867daca069e309b047a4f1f0485..96317fc7df336c4d6882c403b90fe518e2c02f00 100644 --- a/project_euler/problem_054/test_poker_hand.py +++ b/project_euler/problem_054/test_poker_hand.py @@ -217,7 +217,7 @@ def test_euler_project(): answer = 0 script_dir = os.path.abspath(os.path.dirname(__file__)) poker_hands = os.path.join(script_dir, "poker_hands.txt") - with open(poker_hands, "r") as file_hand: + with open(poker_hands) as file_hand: for line in file_hand: player_hand = line[:14].strip() opponent_hand = line[15:].strip() diff --git a/project_euler/problem_063/sol1.py b/project_euler/problem_063/sol1.py index f6a8d3240ffdf6272c4ff611b6e1e00e4c8a85b9..29efddba4216c125bbc3ead5fc6a4ddb09ee3f77 100644 --- a/project_euler/problem_063/sol1.py +++ b/project_euler/problem_063/sol1.py @@ -26,7 +26,7 @@ def solution(max_base: int = 10, max_power: int = 22) -> int: bases = range(1, max_base) powers = range(1, max_power) return sum( - 1 for power in powers for base in bases if len(str((base ** power))) == power + 1 for power in powers for base in bases if len(str(base ** power)) == power ) diff --git a/project_euler/problem_067/sol1.py b/project_euler/problem_067/sol1.py index 9494ff7bbabdb4a91b9b63ab23dbb120f9ea720f..ebfa865a9479dbabeb1cea38762ecb151b282c66 100644 --- a/project_euler/problem_067/sol1.py +++ b/project_euler/problem_067/sol1.py @@ -25,7 +25,7 @@ def solution(): script_dir = os.path.dirname(os.path.realpath(__file__)) triangle = os.path.join(script_dir, "triangle.txt") - with open(triangle, "r") as f: + with open(triangle) as f: triangle = f.readlines() a = map(lambda x: x.rstrip("\r\n").split(" "), triangle)