mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-23 21:11:08 +00:00
Pyupgrade to python3.8 (#3616)
* Upgrade to Python 3.8 syntax * updating DIRECTORY.md Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
This commit is contained in:
parent
74233022a0
commit
9b95e4f662
|
@ -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)
|
||||
|
|
|
@ -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:
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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()
|
||||
|
||||
|
|
|
@ -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()
|
||||
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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()
|
||||
|
|
|
@ -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
|
||||
)
|
||||
|
||||
|
|
|
@ -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
|
||||
"""
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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)
|
||||
]
|
||||
)
|
||||
),
|
||||
|
|
|
@ -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]:
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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]
|
||||
|
||||
|
||||
|
|
|
@ -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]
|
||||
|
|
|
@ -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(",")))
|
||||
|
|
|
@ -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]])
|
||||
|
|
|
@ -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()
|
||||
|
|
|
@ -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()
|
||||
|
|
|
@ -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
|
||||
)
|
||||
|
||||
|
||||
|
|
|
@ -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)
|
||||
|
|
Loading…
Reference in New Issue
Block a user