Skip to content

Cyai patch 3 #2

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 5 commits into from
Jul 6, 2022
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
7 changes: 5 additions & 2 deletions arithmetic_analysis/in_static_equilibrium.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,11 @@ def polar_force(
True
>>> math.isclose(force[1], 7.0710678118654755)
True
>>> polar_force(10, 3.14, radian_mode=True)
[-9.999987317275396, 0.01592652916486828]
>>> force = polar_force(10, 3.14, radian_mode=True)
>>> math.isclose(force[0], -9.999987317275396)
True
>>> math.isclose(force[1], 0.01592652916486828)
True
"""
if radian_mode:
return [magnitude * cos(angle), magnitude * sin(angle)]
Expand Down
12 changes: 6 additions & 6 deletions ciphers/elgamal_key_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ def generate_key(key_size: int) -> tuple[tuple[int, int, int, int], tuple[int, i


def make_key_files(name: str, keySize: int) -> None:
if os.path.exists("%s_pubkey.txt" % name) or os.path.exists(
"%s_privkey.txt" % name
if os.path.exists(f"{name}_pubkey.txt") or os.path.exists(
f"{name}_privkey.txt"
):
print("\nWARNING:")
print(
Expand All @@ -50,14 +50,14 @@ def make_key_files(name: str, keySize: int) -> None:
sys.exit()

publicKey, privateKey = generate_key(keySize)
print("\nWriting public key to file %s_pubkey.txt..." % name)
with open("%s_pubkey.txt" % name, "w") as fo:
print(f"\nWriting public key to file {name}_pubkey.txt...")
with open(f"{name}_pubkey.txt", "w") as fo:
fo.write(
"%d,%d,%d,%d" % (publicKey[0], publicKey[1], publicKey[2], publicKey[3])
)

print("Writing private key to file %s_privkey.txt..." % name)
with open("%s_privkey.txt" % name, "w") as fo:
print(f"Writing private key to file {name}_privkey.txt...")
with open(f"{name}_privkey.txt", "w") as fo:
fo.write("%d,%d" % (privateKey[0], privateKey[1]))


Expand Down
4 changes: 2 additions & 2 deletions ciphers/rsa_cipher.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,15 +129,15 @@ def main() -> None:

message = input("\nEnter message: ")
pubkey_filename = "rsa_pubkey.txt"
print("Encrypting and writing to %s..." % (filename))
print(f"Encrypting and writing to {filename}...")
encryptedText = encrypt_and_write_to_file(filename, pubkey_filename, message)

print("\nEncrypted text:")
print(encryptedText)

elif mode == "decrypt":
privkey_filename = "rsa_privkey.txt"
print("Reading from %s and decrypting..." % (filename))
print(f"Reading from {filename} and decrypting...")
decrypted_text = read_from_file_and_decrypt(filename, privkey_filename)
print("writing decryption to rsa_decryption.txt...")
with open("rsa_decryption.txt", "w") as dec:
Expand Down
12 changes: 6 additions & 6 deletions ciphers/rsa_key_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ def generateKey(keySize: int) -> tuple[tuple[int, int], tuple[int, int]]:


def makeKeyFiles(name: str, keySize: int) -> None:
if os.path.exists("%s_pubkey.txt" % (name)) or os.path.exists(
"%s_privkey.txt" % (name)
if os.path.exists(f"{name}_pubkey.txt") or os.path.exists(
f"{name}_privkey.txt"
):
print("\nWARNING:")
print(
Expand All @@ -46,12 +46,12 @@ def makeKeyFiles(name: str, keySize: int) -> None:
sys.exit()

publicKey, privateKey = generateKey(keySize)
print("\nWriting public key to file %s_pubkey.txt..." % name)
with open("%s_pubkey.txt" % name, "w") as out_file:
print(f"\nWriting public key to file {name}_pubkey.txt...")
with open(f"{name}_pubkey.txt", "w") as out_file:
out_file.write(f"{keySize},{publicKey[0]},{publicKey[1]}")

print("Writing private key to file %s_privkey.txt..." % name)
with open("%s_privkey.txt" % name, "w") as out_file:
print(f"Writing private key to file {name}_privkey.txt...")
with open(f"{name}_privkey.txt", "w") as out_file:
out_file.write(f"{keySize},{privateKey[0]},{privateKey[1]}")


Expand Down
4 changes: 2 additions & 2 deletions ciphers/transposition_cipher.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

def main() -> None:
message = input("Enter message: ")
key = int(input("Enter key [2-%s]: " % (len(message) - 1)))
key = int(input(f"Enter key [2-{len(message) - 1}]: "))
mode = input("Encryption/Decryption [e/d]: ")

if mode.lower().startswith("e"):
Expand All @@ -19,7 +19,7 @@ def main() -> None:
text = decryptMessage(key, message)

# Append pipe symbol (vertical bar) to identify spaces at the end.
print("Output:\n%s" % (text + "|"))
print(f"Output:\n{text + '|'}")


def encryptMessage(key: int, message: str) -> str:
Expand Down
4 changes: 2 additions & 2 deletions ciphers/transposition_cipher_encrypt_decrypt_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ def main() -> None:
mode = input("Encrypt/Decrypt [e/d]: ")

if not os.path.exists(inputFile):
print("File %s does not exist. Quitting..." % inputFile)
print(f"File {inputFile} does not exist. Quitting...")
sys.exit()
if os.path.exists(outputFile):
print("Overwrite %s? [y/n]" % outputFile)
print(f"Overwrite {outputFile}? [y/n]")
response = input("> ")
if not response.lower().startswith("y"):
sys.exit()
Expand Down
2 changes: 1 addition & 1 deletion ciphers/vigenere_cipher.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ def main() -> None:
mode = "decrypt"
translated = decryptMessage(key, message)

print("\n%sed message:" % mode.title())
print(f"\n{mode.title()}ed message:")
print(translated)


Expand Down
2 changes: 1 addition & 1 deletion data_structures/binary_tree/binary_search_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def __repr__(self):

if self.left is None and self.right is None:
return str(self.value)
return pformat({"%s" % (self.value): (self.left, self.right)}, indent=1)
return pformat({f"{self.value}": (self.left, self.right)}, indent=1)


class BinarySearchTree:
Expand Down
2 changes: 1 addition & 1 deletion hashes/chaos_machine.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def reset():

# Pulling Data (Output)
while inp in ("e", "E"):
print("%s" % format(pull(), "#04x"))
print(f"{format(pull(), '#04x')}")
print(buffer_space)
print(params_space)
inp = input("(e)exit? ").strip()
4 changes: 2 additions & 2 deletions machine_learning/gradient_boosting_regressor.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,9 @@ def main():
y_pred = model.predict(X_test)

# The mean squared error
print("Mean squared error: %.2f" % mean_squared_error(y_test, y_pred))
print(f"Mean squared error: {mean_squared_error(y_test, y_pred):.2f}")
# Explained variance score: 1 is perfect prediction
print("Test Variance score: %.2f" % r2_score(y_test, y_pred))
print(f"Test Variance score: {r2_score(y_test, y_pred):.2f}")

# So let's run the model against the test data
fig, ax = plt.subplots()
Expand Down
4 changes: 1 addition & 3 deletions machine_learning/k_means_clust.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,9 +164,7 @@ def kmeans(
num_changed = np.sum(prev_cluster_assignment != cluster_assignment)
if verbose:
print(
" {:5d} elements changed their cluster assignment.".format(
num_changed
)
f" {num_changed:5d} elements changed their cluster assignment."
)

# Record heterogeneity convergence metric
Expand Down
2 changes: 1 addition & 1 deletion machine_learning/linear_regression.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ def main():
len_result = theta.shape[1]
print("Resultant Feature vector : ")
for i in range(0, len_result):
print("%.5f" % (theta[0, i]))
print(f"{theta[0, i]:.5f}")


if __name__ == "__main__":
Expand Down
2 changes: 1 addition & 1 deletion matrix/sherman_morrison.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ def test1():
v[0, 0], v[1, 0], v[2, 0] = 4, -2, 5
print(f"u is {u}")
print(f"v is {v}")
print("uv^T is %s" % (u * v.transpose()))
print(f"uv^T is {u * v.transpose()}")
# Sherman Morrison
print(f"(a + uv^T)^(-1) is {ainv.ShermanMorrison(u, v)}")

Expand Down
4 changes: 2 additions & 2 deletions neural_network/convolution_neural_network.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def save_model(self, save_path):
with open(save_path, "wb") as f:
pickle.dump(model_dic, f)

print("Model saved: %s" % save_path)
print(f"Model saved: {save_path}")

@classmethod
def ReadModel(cls, model_path):
Expand Down Expand Up @@ -303,7 +303,7 @@ def draw_error():
plt.show()

print("------------------Training Complished---------------------")
print((" - - Training epoch: ", rp, " - - Mse: %.6f" % mse))
print((" - - Training epoch: ", rp, f" - - Mse: {mse:.6f}"))
if draw_e:
draw_error()
return mse
Expand Down
2 changes: 1 addition & 1 deletion other/scoring_algorithm.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def procentual_proximity(

# weight not 0 or 1
else:
raise ValueError("Invalid weight of %f provided" % (weight))
raise ValueError(f"Invalid weight of {weight:f} provided")

score_lists.append(score)

Expand Down
4 changes: 2 additions & 2 deletions quantum/ripple_adder_classic.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
# https://en.wikipedia.org/wiki/Controlled_NOT_gate

from qiskit import Aer, QuantumCircuit, execute
from qiskit.providers import BaseBackend
from qiskit.providers import Backend


def store_two_classics(val1: int, val2: int) -> tuple[QuantumCircuit, str, str]:
Expand Down Expand Up @@ -62,7 +62,7 @@ def full_adder(
def ripple_adder(
val1: int,
val2: int,
backend: BaseBackend = Aer.get_backend("qasm_simulator"), # noqa: B008
backend: Backend = Aer.get_backend("qasm_simulator"), # noqa: B008
) -> int:
"""
Quantum Equivalent of a Ripple Adder Circuit
Expand Down
2 changes: 1 addition & 1 deletion scheduling/shortest_job_first.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ def calculate_average_times(
for i in range(no_of_processes):
total_waiting_time = total_waiting_time + waiting_time[i]
total_turn_around_time = total_turn_around_time + turn_around_time[i]
print("Average waiting time = %.5f" % (total_waiting_time / no_of_processes))
print(f"Average waiting time = {total_waiting_time / no_of_processes:.5f}")
print("Average turn around time =", total_turn_around_time / no_of_processes)


Expand Down
4 changes: 2 additions & 2 deletions searches/binary_tree_traversal.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,14 @@ def build_tree():
q.put(tree_node)
while not q.empty():
node_found = q.get()
msg = "Enter the left node of %s: " % node_found.data
msg = f"Enter the left node of {node_found.data}: "
check = input(msg).strip().lower() or "n"
if check == "n":
return tree_node
left_node = TreeNode(int(check))
node_found.left = left_node
q.put(left_node)
msg = "Enter the right node of %s: " % node_found.data
msg = f"Enter the right node of {node_found.data}: "
check = input(msg).strip().lower() or "n"
if check == "n":
return tree_node
Expand Down
41 changes: 41 additions & 0 deletions strings/hamming_distance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
def hamming_distance(string1: str, string2: str) -> int:
"""Calculate the Hamming distance between two equal length strings
In information theory, the Hamming distance between two strings of equal
length is the number of positions at which the corresponding symbols are
different. https://en.wikipedia.org/wiki/Hamming_distance

Args:
string1 (str): Sequence 1
string2 (str): Sequence 2

Returns:
int: Hamming distance

>>> hamming_distance("python", "python")
0
>>> hamming_distance("karolin", "kathrin")
3
>>> hamming_distance("00000", "11111")
5
>>> hamming_distance("karolin", "kath")
Traceback (most recent call last):
...
ValueError: String lengths must match!
"""
if len(string1) != len(string2):
raise ValueError("String lengths must match!")

count = 0

for char1, char2 in zip(string1, string2):
if char1 != char2:
count += 1

return count


if __name__ == "__main__":

import doctest

doctest.testmod()
12 changes: 6 additions & 6 deletions strings/min_cost_string_conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,28 +31,28 @@ def compute_transform_tables(

for i in range(1, len_source_seq + 1):
costs[i][0] = i * delete_cost
ops[i][0] = "D%c" % source_seq[i - 1]
ops[i][0] = f"D{source_seq[i - 1]:c}"

for i in range(1, len_destination_seq + 1):
costs[0][i] = i * insert_cost
ops[0][i] = "I%c" % destination_seq[i - 1]
ops[0][i] = f"I{destination_seq[i - 1]:c}"

for i in range(1, len_source_seq + 1):
for j in range(1, len_destination_seq + 1):
if source_seq[i - 1] == destination_seq[j - 1]:
costs[i][j] = costs[i - 1][j - 1] + copy_cost
ops[i][j] = "C%c" % source_seq[i - 1]
ops[i][j] = f"C{source_seq[i - 1]:c}"
else:
costs[i][j] = costs[i - 1][j - 1] + replace_cost
ops[i][j] = "R%c" % source_seq[i - 1] + str(destination_seq[j - 1])
ops[i][j] = f"R{source_seq[i - 1]:c}" + str(destination_seq[j - 1])

if costs[i - 1][j] + delete_cost < costs[i][j]:
costs[i][j] = costs[i - 1][j] + delete_cost
ops[i][j] = "D%c" % source_seq[i - 1]
ops[i][j] = f"D{source_seq[i - 1]:c}"

if costs[i][j - 1] + insert_cost < costs[i][j]:
costs[i][j] = costs[i][j - 1] + insert_cost
ops[i][j] = "I%c" % destination_seq[j - 1]
ops[i][j] = f"I{destination_seq[j - 1]:c}"

return costs, ops

Expand Down