From bbce0e24828769d89df2442d341fb3b2396e24e8 Mon Sep 17 00:00:00 2001 From: Ranausama420 <43530464+Ranausama420@users.noreply.github.com> Date: Thu, 6 Apr 2023 16:37:24 +0500 Subject: [PATCH 1/6] comments added for better understanding in basic_string.py --- genetic_algorithm/basic_string.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/genetic_algorithm/basic_string.py b/genetic_algorithm/basic_string.py index 45b8be651f6e..53aeac0eab76 100644 --- a/genetic_algorithm/basic_string.py +++ b/genetic_algorithm/basic_string.py @@ -20,9 +20,11 @@ # Just a seed to improve randomness required by the algorithm. 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 @@ -122,6 +124,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 = [] @@ -139,6 +144,10 @@ 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) @@ -146,6 +155,13 @@ def crossover(parent_1: str, parent_2: str) -> tuple[str, str]: 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) From 9d722a8c44d90deecb680cd253b9476e75b237ce Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Thu, 6 Apr 2023 11:40:55 +0000 Subject: [PATCH 2/6] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- genetic_algorithm/basic_string.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/genetic_algorithm/basic_string.py b/genetic_algorithm/basic_string.py index 53aeac0eab76..a95b4ebedb2a 100644 --- a/genetic_algorithm/basic_string.py +++ b/genetic_algorithm/basic_string.py @@ -20,6 +20,7 @@ # Just a seed to improve randomness required by the algorithm. 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]: @@ -124,7 +125,7 @@ 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. + """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]: @@ -145,7 +146,7 @@ def select(parent_1: tuple[str, float]) -> list[str]: 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 + 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]: @@ -155,13 +156,14 @@ def crossover(parent_1: str, parent_2: str) -> tuple[str, str]: 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. + """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 + 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 + 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) From 527f616e95500fba3ad3d36a528c3fd7c75230fb Mon Sep 17 00:00:00 2001 From: Ranausama420 <43530464+Ranausama420@users.noreply.github.com> Date: Mon, 10 Apr 2023 23:29:36 +0500 Subject: [PATCH 3/6] refactored some code tried to reduced number of lines of code and added comments for better understanding --- ciphers/mixed_keyword_cypher.py | 42 ++++++++++++++++++++++----------- 1 file changed, 28 insertions(+), 14 deletions(-) diff --git a/ciphers/mixed_keyword_cypher.py b/ciphers/mixed_keyword_cypher.py index 806004faa079..ba31bcc44502 100644 --- a/ciphers/mixed_keyword_cypher.py +++ b/ciphers/mixed_keyword_cypher.py @@ -1,3 +1,9 @@ +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: """ @@ -21,23 +27,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): @@ -59,9 +72,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 From bbf6d4d19881eb6ef64d2660dd15b4e92c1bcc59 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 10 Apr 2023 18:39:27 +0000 Subject: [PATCH 4/6] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- ciphers/mixed_keyword_cypher.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/ciphers/mixed_keyword_cypher.py b/ciphers/mixed_keyword_cypher.py index ba31bcc44502..4d843ae5dfa7 100644 --- a/ciphers/mixed_keyword_cypher.py +++ b/ciphers/mixed_keyword_cypher.py @@ -1,9 +1,12 @@ import string -"""This function takes two parameters: a string variable named + +"""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'). + 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: """ @@ -47,9 +50,9 @@ def mixed_keyword(key: str = "college", pt: str = "UNIVERSITY") -> str: # modalpha.append(s) k = 0 - """These lines of code creates a dictionary by iterating over the list of + """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 + 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 = [] @@ -72,7 +75,7 @@ def mixed_keyword(key: str = "college", pt: str = "UNIVERSITY") -> str: break k += 1 print(d) - cypher = ''.join(d[c] for c in pt) + cypher = "".join(d[c] for c in pt) # cypher = "" # for i in pt: # cypher += d[i] From 840f592007bd68ace427770aa3d6d2f753de8836 Mon Sep 17 00:00:00 2001 From: Ranausama420 <43530464+Ranausama420@users.noreply.github.com> Date: Wed, 12 Apr 2023 22:35:27 +0500 Subject: [PATCH 5/6] explanation of function merge in mergesort.py --- divide_and_conquer/max_subarray_sum.py | 1 + divide_and_conquer/mergesort.py | 11 +++++++++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/divide_and_conquer/max_subarray_sum.py b/divide_and_conquer/max_subarray_sum.py index f23e81719025..d2da19f42046 100644 --- a/divide_and_conquer/max_subarray_sum.py +++ b/divide_and_conquer/max_subarray_sum.py @@ -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 diff --git a/divide_and_conquer/mergesort.py b/divide_and_conquer/mergesort.py index 628080cefc9b..ff79f3e78dc9 100644 --- a/divide_and_conquer/mergesort.py +++ b/divide_and_conquer/mergesort.py @@ -1,6 +1,10 @@ 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. @@ -34,7 +38,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] From 90196a975dabea9433b4515becbaae97976f8a42 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 12 Apr 2023 17:39:42 +0000 Subject: [PATCH 6/6] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- divide_and_conquer/max_subarray_sum.py | 2 +- divide_and_conquer/mergesort.py | 8 +++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/divide_and_conquer/max_subarray_sum.py b/divide_and_conquer/max_subarray_sum.py index d2da19f42046..e188d310c820 100644 --- a/divide_and_conquer/max_subarray_sum.py +++ b/divide_and_conquer/max_subarray_sum.py @@ -26,7 +26,7 @@ def max_sum_from_start(array): array_sum += num if array_sum > max_sum: max_sum = array_sum - + return max_sum diff --git a/divide_and_conquer/mergesort.py b/divide_and_conquer/mergesort.py index ff79f3e78dc9..3ce20faece4f 100644 --- a/divide_and_conquer/mergesort.py +++ b/divide_and_conquer/mergesort.py @@ -2,9 +2,11 @@ """ 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 +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. @@ -38,8 +40,8 @@ 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 + """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):