Skip to content

Refactor mixed_keyword_cypher.py file and added comments in code #8633

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

Closed
Closed
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
45 changes: 31 additions & 14 deletions ciphers/mixed_keyword_cypher.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
import string

"""This function takes two parameters: a string variable named
'key' (with a default value of 'college') and a string variable
named 'pt' (with a default value of 'UNIVERSITY').
The function returns a string that is a transformation of the 'pt' argument
based on a key-shift cipher"""


def mixed_keyword(key: str = "college", pt: str = "UNIVERSITY") -> str:
"""

Expand All @@ -21,23 +30,30 @@ def mixed_keyword(key: str = "college", pt: str = "UNIVERSITY") -> str:
"""
key = key.upper()
pt = pt.upper()
temp = []
for i in key:
if i not in temp:
temp.append(i)
## changed below lines added sets functionality and remove for loops to get unique elemnt in list
temp = list(set(key))
len_temp = len(temp)
# print(temp)
alpha = []
# string module can used to generate alphabets list instead of using loops
alpha = list(string.ascii_uppercase)
modalpha = []
for j in range(65, 91):
t = chr(j)
alpha.append(t)
if t not in temp:
temp.append(t)
for j in alpha:
if j not in temp:
temp.append(j)

# print(temp)
r = int(26 / 4)
# print(r)
print(r)
print(len_temp)
# for i in range(r*len_temp):
# s = [temp[i] for _ in range(len_temp) if i < 26]
# modalpha.append(s)

k = 0
"""These lines of code creates a dictionary by iterating over the list of
lists. Each letter in the alphabets list is mapped to a letter in a row of
the "modalpha" list. The mappings are stored in the dictionary with the
indices of the alphabets list as keys and the values fromthe corresponding modalpha lists as values"""
for _ in range(r):
s = []
for _ in range(len_temp):
Expand All @@ -59,9 +75,10 @@ def mixed_keyword(key: str = "college", pt: str = "UNIVERSITY") -> str:
break
k += 1
print(d)
cypher = ""
for i in pt:
cypher += d[i]
cypher = "".join(d[c] for c in pt)
# cypher = ""
# for i in pt:
# cypher += d[i]
return cypher


Expand Down
1 change: 1 addition & 0 deletions divide_and_conquer/max_subarray_sum.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ def max_sum_from_start(array):
array_sum += num
if array_sum > max_sum:
max_sum = array_sum

return max_sum


Expand Down
11 changes: 10 additions & 1 deletion divide_and_conquer/mergesort.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
from __future__ import annotations

"""
The function creates an empty list called "sorted_array" with the length equal to the sum of the lengths of the two lists. It then initializes three pointers - pointer1, pointer2, and index - to 0.
The function then enters a while loop that continues as long as pointer1 and pointer2 are less than the length of their respective lists. Within the loop, the function compares the values of the elements
at the current pointer positions in the left and right lists, and adds the smaller element to the sorted_array. The pointer for the list that contained the smaller element is then incremented, as well as the index pointer for the sorted_array.
"""


def merge(left_half: list, right_half: list) -> list:
"""Helper function for mergesort.
Expand Down Expand Up @@ -34,7 +40,10 @@ def merge(left_half: list, right_half: list) -> list:
pointer1 = 0 # pointer to current index for left Half
pointer2 = 0 # pointer to current index for the right Half
index = 0 # pointer to current index for the sorted array Half

"""After the while loop finishes, the function runs two more while
loops to add any remaining elements from the left and right lists to
the sorted_array, in case one of the lists was longer than the other.
Finally, the function returns the sorted_array."""
while pointer1 < len(left_half) and pointer2 < len(right_half):
if left_half[pointer1] < right_half[pointer2]:
sorted_array[index] = left_half[pointer1]
Expand Down
18 changes: 18 additions & 0 deletions genetic_algorithm/basic_string.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,11 @@
random.seed(random.randint(0, 1000))


# This function uses a genetic algorithm to evolve the string by randomly selecting characters from the genes list and comparing
# the resulting string to the original string, repeating this process until the two strings match.
def basic(target: str, genes: list[str], debug: bool = True) -> tuple[int, int, str]:
"""
These lines of code are testing a function called "basic"
Verify that the target contains no genes besides the ones inside genes variable.

>>> from string import ascii_lowercase
Expand Down Expand Up @@ -122,6 +125,9 @@ def evaluate(item: str, main_target: str = target) -> tuple[str, float]:
]

# Select, crossover and mutate a new population.
"""Select is responsible for selecting a second parent and generating a new population.
The function takes a tuple containing the first parent's string and its fitness score as input"""

def select(parent_1: tuple[str, float]) -> list[str]:
"""Select the second parent and generate new population"""
pop = []
Expand All @@ -139,13 +145,25 @@ def select(parent_1: tuple[str, float]) -> list[str]:
pop.append(mutate(child_2))
return pop

"""This function defines a crossover operation between two parent strings,
where a random slice point is chosen and the two parts of the parent strings
are combined to form two child strings. The function returns a tuple containing the two child strings."""

def crossover(parent_1: str, parent_2: str) -> tuple[str, str]:
"""Slice and combine two string at a random point."""
random_slice = random.randint(0, len(parent_1) - 1)
child_1 = parent_1[:random_slice] + parent_2[random_slice:]
child_2 = parent_2[:random_slice] + parent_1[random_slice:]
return (child_1, child_2)

"""This function takes a string, child, as an argument and returns a string.
The function mutates a random gene of the child by replacing it with a random gene from a list called "genes".
The mutation occurs only if a random number generated by the "random.uniform" function is less than a constant value called
"MUTATION_PROBABILITY".
The code first converts the string child to a list called "child_list". It then selects a random index from the child_list
using "random.randint" and replaces the value at that index with a random gene from "genes".
Finally, the function returns the mutated child as a string by joining the "child_list"."""

def mutate(child: str) -> str:
"""Mutate a random gene of a child with another one from the list."""
child_list = list(child)
Expand Down