Skip to content

Pyupgrade to python3.8 #3616

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 21, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion ciphers/simple_substitution_cipher.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
8 changes: 4 additions & 4 deletions ciphers/xor_cipher.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,14 +141,14 @@ def encrypt_file(self, file: str, key: int = 0) -> bool:
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
Expand All @@ -166,14 +166,14 @@ def decrypt_file(self, file: str, key: int) -> bool:
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
Expand Down
6 changes: 3 additions & 3 deletions compression/lempel_ziv.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down Expand Up @@ -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()

Expand Down
6 changes: 3 additions & 3 deletions compression/lempel_ziv_decompress.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down Expand Up @@ -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()

Expand Down
6 changes: 3 additions & 3 deletions data_structures/binary_tree/segment_tree_other.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
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
Expand All @@ -17,10 +17,10 @@ def __init__(self, start, end, val, left=None, right=None):
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)
Expand Down
2 changes: 1 addition & 1 deletion data_structures/heap/heap.py
Original file line number Diff line number Diff line change
@@ -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()
Expand Down
2 changes: 1 addition & 1 deletion data_structures/linked_list/deque_doubly.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def __init__(self, link_p, element, link_n):
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
)

Expand Down
2 changes: 1 addition & 1 deletion graphs/minimum_spanning_tree_boruvka.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ def build(vertices=None, edges=None):
g.add_edge(*edge)
return g

class UnionFind(object):
class UnionFind:
"""
Disjoint set Union and Find for Boruvka's algorithm
"""
Expand Down
4 changes: 2 additions & 2 deletions machine_learning/astar.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
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
Expand Down Expand Up @@ -45,7 +45,7 @@ def showcell(self):
print(self.position)


class Gridworld(object):
class Gridworld:
"""
Gridworld class represents the external world here a grid M*M
matrix
Expand Down
2 changes: 1 addition & 1 deletion machine_learning/k_means_clust.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
]
)
),
Expand Down
6 changes: 3 additions & 3 deletions maths/entropy.py
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand All @@ -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]:
Expand Down
2 changes: 1 addition & 1 deletion maths/numerical_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,5 +62,5 @@ def f(x):
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
2 changes: 1 addition & 1 deletion project_euler/problem_013/sol1.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]


Expand Down
2 changes: 1 addition & 1 deletion project_euler/problem_018/solution.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
2 changes: 1 addition & 1 deletion project_euler/problem_042/solution42.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(",")))
Expand Down
2 changes: 1 addition & 1 deletion project_euler/problem_049/sol1.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]])
Expand Down
4 changes: 2 additions & 2 deletions project_euler/problem_054/sol1.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
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.
Expand Down Expand Up @@ -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()
Expand Down
2 changes: 1 addition & 1 deletion project_euler/problem_054/test_poker_hand.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
2 changes: 1 addition & 1 deletion project_euler/problem_063/sol1.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
)


Expand Down
2 changes: 1 addition & 1 deletion project_euler/problem_067/sol1.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down