From e3f51e69ce148124b68ac349a06c09d24f86e99b Mon Sep 17 00:00:00 2001 From: ArunSiva Date: Mon, 2 Oct 2023 13:09:30 +0530 Subject: [PATCH 01/35] infix to prefix missing feature added --- conversions/infix_to_prefix_conversions.py | 103 +++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 conversions/infix_to_prefix_conversions.py diff --git a/conversions/infix_to_prefix_conversions.py b/conversions/infix_to_prefix_conversions.py new file mode 100644 index 000000000000..2aee39e76866 --- /dev/null +++ b/conversions/infix_to_prefix_conversions.py @@ -0,0 +1,103 @@ +from __future__ import annotations +from enum import Enum, unique +from typing import TypeVar + +# Create a generic variable that can be 'Enum', or any subclass. +T = TypeVar("T", bound="Enum") + +@unique +class BinaryUnit(Enum): + yotta = 80 + zetta = 70 + exa = 60 + peta = 50 + tera = 40 + giga = 30 + mega = 20 + kilo = 10 + +@unique +class SIUnit(Enum): + yotta = 24 + zetta = 21 + exa = 18 + peta = 15 + tera = 12 + giga = 9 + mega = 6 + kilo = 3 + hecto = 2 + deca = 1 + deci = -1 + centi = -2 + milli = -3 + micro = -6 + nano = -9 + pico = -12 + femto = -15 + atto = -18 + zepto = -21 + yocto = -24 + + @classmethod + def get_positive(cls: type[T]) -> dict: + """ + Returns a dictionary with only the elements of this enum + that has a positive value + """ + return {unit.name: unit.value for unit in cls if unit.value > 0} + + @classmethod + def get_negative(cls: type[T]) -> dict: + """ + Returns a dictionary with only the elements of this enum + that has a negative value + """ + return {unit.name: unit.value for unit in cls if unit.value < 0} + +def infix_to_prefix(expression): + """ + Convert an infix expression to a prefix expression. + """ + def precedence(operator): + precedence_dict = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3} + return precedence_dict.get(operator, 0) + + def is_operator(char): + return char in "+-*/^" + + def infix_to_postfix(infix_expr): + postfix = [] + stack = [] + for char in infix_expr: + if char.isalnum(): # Operand + postfix.append(char) + elif char == '(': # Left parenthesis + stack.append(char) + elif char == ')': # Right parenthesis + while stack and stack[-1] != '(': + postfix.append(stack.pop()) + stack.pop() # Pop '(' + elif is_operator(char): + while ( + stack + and stack[-1] != '(' + and precedence(char) <= precedence(stack[-1]) + ): + postfix.append(stack.pop()) + stack.append(char) + while stack: + postfix.append(stack.pop()) + return ''.join(postfix) + + infix_expr = expression[::-1] # Reverse the input expression + infix_expr = infix_expr.replace('(', 'X').replace(')', '(').replace('X', ')') # Swap '(' and ')' to handle correctly in reverse + postfix_expr = infix_to_postfix(infix_expr) + prefix_expr = postfix_expr[::-1] # Reverse the postfix expression to get prefix + return prefix_expr + +# Example usage: +if __name__ == "__main__": + import doctest + doctest.testmod() + From 64aa8432ec55acfd0f19d4b4796cc9058a00cc73 Mon Sep 17 00:00:00 2001 From: ArunSiva Date: Mon, 2 Oct 2023 13:20:49 +0530 Subject: [PATCH 02/35] infix to prefix missing feature added --- conversions/infix_to_prefix_conversions.py | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/conversions/infix_to_prefix_conversions.py b/conversions/infix_to_prefix_conversions.py index 2aee39e76866..32fb0bf785c4 100644 --- a/conversions/infix_to_prefix_conversions.py +++ b/conversions/infix_to_prefix_conversions.py @@ -1,9 +1,9 @@ from __future__ import annotations from enum import Enum, unique -from typing import TypeVar +from typing import TypeVar # Create a generic variable that can be 'Enum', or any subclass. -T = TypeVar("T", bound="Enum") +T = TypeVar("T", bound=Enum) @unique class BinaryUnit(Enum): @@ -43,7 +43,7 @@ class SIUnit(Enum): def get_positive(cls: type[T]) -> dict: """ Returns a dictionary with only the elements of this enum - that has a positive value + that have a positive value. """ return {unit.name: unit.value for unit in cls if unit.value > 0} @@ -51,7 +51,7 @@ def get_positive(cls: type[T]) -> dict: def get_negative(cls: type[T]) -> dict: """ Returns a dictionary with only the elements of this enum - that has a negative value + that have a negative value. """ return {unit.name: unit.value for unit in cls if unit.value < 0} @@ -90,14 +90,16 @@ def infix_to_postfix(infix_expr): postfix.append(stack.pop()) return ''.join(postfix) - infix_expr = expression[::-1] # Reverse the input expression - infix_expr = infix_expr.replace('(', 'X').replace(')', '(').replace('X', ')') # Swap '(' and ')' to handle correctly in reverse + # Reverse the input expression + infix_expr = expression[::-1] + # Swap '(' and ')' to handle correctly in reverse + infix_expr = infix_expr.replace('(', 'X').replace(')', '(').replace('X', ')') postfix_expr = infix_to_postfix(infix_expr) - prefix_expr = postfix_expr[::-1] # Reverse the postfix expression to get prefix + # Reverse the postfix expression to get prefix + prefix_expr = postfix_expr[::-1] return prefix_expr # Example usage: if __name__ == "__main__": import doctest doctest.testmod() - From c59a81c840596265e20a83616318b001e4573f37 Mon Sep 17 00:00:00 2001 From: ArunSiva Date: Mon, 2 Oct 2023 13:21:46 +0530 Subject: [PATCH 03/35] infix to prefix missing feature added --- conversions/infix_to_prefix_conversions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/conversions/infix_to_prefix_conversions.py b/conversions/infix_to_prefix_conversions.py index 32fb0bf785c4..9e5594a9a2f9 100644 --- a/conversions/infix_to_prefix_conversions.py +++ b/conversions/infix_to_prefix_conversions.py @@ -102,4 +102,4 @@ def infix_to_postfix(infix_expr): # Example usage: if __name__ == "__main__": import doctest - doctest.testmod() + doctest.testmod() \ No newline at end of file From 2ed09ab174023848de951b9c8ba058456af2be9b Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 2 Oct 2023 08:01:55 +0000 Subject: [PATCH 04/35] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- conversions/infix_to_prefix_conversions.py | 24 ++++++++++++++-------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/conversions/infix_to_prefix_conversions.py b/conversions/infix_to_prefix_conversions.py index 9e5594a9a2f9..395096cb0a2c 100644 --- a/conversions/infix_to_prefix_conversions.py +++ b/conversions/infix_to_prefix_conversions.py @@ -5,6 +5,7 @@ # Create a generic variable that can be 'Enum', or any subclass. T = TypeVar("T", bound=Enum) + @unique class BinaryUnit(Enum): yotta = 80 @@ -16,6 +17,7 @@ class BinaryUnit(Enum): mega = 20 kilo = 10 + @unique class SIUnit(Enum): yotta = 24 @@ -55,12 +57,14 @@ def get_negative(cls: type[T]) -> dict: """ return {unit.name: unit.value for unit in cls if unit.value < 0} + def infix_to_prefix(expression): """ Convert an infix expression to a prefix expression. """ + def precedence(operator): - precedence_dict = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3} + precedence_dict = {"+": 1, "-": 1, "*": 2, "/": 2, "^": 3} return precedence_dict.get(operator, 0) def is_operator(char): @@ -72,34 +76,36 @@ def infix_to_postfix(infix_expr): for char in infix_expr: if char.isalnum(): # Operand postfix.append(char) - elif char == '(': # Left parenthesis + elif char == "(": # Left parenthesis stack.append(char) - elif char == ')': # Right parenthesis - while stack and stack[-1] != '(': + elif char == ")": # Right parenthesis + while stack and stack[-1] != "(": postfix.append(stack.pop()) stack.pop() # Pop '(' elif is_operator(char): while ( stack - and stack[-1] != '(' + and stack[-1] != "(" and precedence(char) <= precedence(stack[-1]) ): postfix.append(stack.pop()) stack.append(char) while stack: postfix.append(stack.pop()) - return ''.join(postfix) + return "".join(postfix) # Reverse the input expression - infix_expr = expression[::-1] + infix_expr = expression[::-1] # Swap '(' and ')' to handle correctly in reverse - infix_expr = infix_expr.replace('(', 'X').replace(')', '(').replace('X', ')') + infix_expr = infix_expr.replace("(", "X").replace(")", "(").replace("X", ")") postfix_expr = infix_to_postfix(infix_expr) # Reverse the postfix expression to get prefix prefix_expr = postfix_expr[::-1] return prefix_expr + # Example usage: if __name__ == "__main__": import doctest - doctest.testmod() \ No newline at end of file + + doctest.testmod() From 5cb6799c6a1c60dfa7e42a902b2001b5a5260a87 Mon Sep 17 00:00:00 2001 From: ArunSiva Date: Mon, 2 Oct 2023 13:37:43 +0530 Subject: [PATCH 05/35] infix to prefix missing feature added (comments) --- conversions/infix_to_prefix_conversions.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/conversions/infix_to_prefix_conversions.py b/conversions/infix_to_prefix_conversions.py index 9e5594a9a2f9..2d8d3958083d 100644 --- a/conversions/infix_to_prefix_conversions.py +++ b/conversions/infix_to_prefix_conversions.py @@ -1,3 +1,13 @@ +''' +Infix to Prefix Expression Converter +This script defines functions to convert infix expressions to prefix expressions +using the shunting-yard algorithm. It also includes definitions for SI and Binary +unit prefixes. +Author: "Arunkumar [halfhearted]" +Date: "02-10-2023" +''' + + from __future__ import annotations from enum import Enum, unique from typing import TypeVar From a8a9a6f5dfe574084fa0a311185f96d2cde21ad2 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 2 Oct 2023 08:10:27 +0000 Subject: [PATCH 06/35] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- conversions/infix_to_prefix_conversions.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/conversions/infix_to_prefix_conversions.py b/conversions/infix_to_prefix_conversions.py index f6f2198a3ab5..28f159f96676 100644 --- a/conversions/infix_to_prefix_conversions.py +++ b/conversions/infix_to_prefix_conversions.py @@ -1,11 +1,11 @@ -''' +""" Infix to Prefix Expression Converter This script defines functions to convert infix expressions to prefix expressions using the shunting-yard algorithm. It also includes definitions for SI and Binary unit prefixes. Author: "Arunkumar [halfhearted]" Date: "02-10-2023" -''' +""" from __future__ import annotations From c8d12c9edef6b5fca23c7f73129a9c035a05ad61 Mon Sep 17 00:00:00 2001 From: ArunSiva Date: Mon, 2 Oct 2023 14:17:08 +0530 Subject: [PATCH 07/35] infix to prefix missing feature added (comments) --- conversions/infix_to_prefix_conversions.py | 31 +++++++++++++++------- 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/conversions/infix_to_prefix_conversions.py b/conversions/infix_to_prefix_conversions.py index 28f159f96676..41cb0f51855b 100644 --- a/conversions/infix_to_prefix_conversions.py +++ b/conversions/infix_to_prefix_conversions.py @@ -3,11 +3,9 @@ This script defines functions to convert infix expressions to prefix expressions using the shunting-yard algorithm. It also includes definitions for SI and Binary unit prefixes. -Author: "Arunkumar [halfhearted]" -Date: "02-10-2023" +Author: Arunkumar [halfhearted] +Date: 02-10-2023 """ - - from __future__ import annotations from enum import Enum, unique from typing import TypeVar @@ -68,19 +66,34 @@ def get_negative(cls: type[T]) -> dict: return {unit.name: unit.value for unit in cls if unit.value < 0} -def infix_to_prefix(expression): +def infix_to_prefix(expression) -> str: """ Convert an infix expression to a prefix expression. + Args: + expression (str): The infix expression to convert. + Returns: + str: The converted prefix expression. + + >>> infix_to_prefix("2+2") + '+22' + >>> infix_to_prefix("(1+2)*3") + '*+123' + >>> infix_to_prefix("a*(b+c)") + '*a+bc' + >>> infix_to_prefix("1+2*3") + '+1*23' + >>> infix_to_prefix("a * b + c / d") + '+*ab/cd' """ - def precedence(operator): + def precedence(operator) -> int: precedence_dict = {"+": 1, "-": 1, "*": 2, "/": 2, "^": 3} return precedence_dict.get(operator, 0) - def is_operator(char): + def is_operator(char) -> bool: return char in "+-*/^" - def infix_to_postfix(infix_expr): + def infix_to_postfix(infix_expr) -> str: postfix = [] stack = [] for char in infix_expr: @@ -118,4 +131,4 @@ def infix_to_postfix(infix_expr): if __name__ == "__main__": import doctest - doctest.testmod() + doctest.testmod() \ No newline at end of file From c2caec5b94546a5c9908b9d6f5e2ec63c7f18a35 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 2 Oct 2023 08:49:06 +0000 Subject: [PATCH 08/35] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- conversions/infix_to_prefix_conversions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/conversions/infix_to_prefix_conversions.py b/conversions/infix_to_prefix_conversions.py index 41cb0f51855b..b1478365de6c 100644 --- a/conversions/infix_to_prefix_conversions.py +++ b/conversions/infix_to_prefix_conversions.py @@ -131,4 +131,4 @@ def infix_to_postfix(infix_expr) -> str: if __name__ == "__main__": import doctest - doctest.testmod() \ No newline at end of file + doctest.testmod() From b51c2a20119f69007ae990a6009884310fac7952 Mon Sep 17 00:00:00 2001 From: ArunSiva Date: Tue, 3 Oct 2023 18:45:10 +0530 Subject: [PATCH 09/35] newly updated infix_to_prefix --- conversions/infix_to_prefix_conversions.py | 52 ---------------------- 1 file changed, 52 deletions(-) diff --git a/conversions/infix_to_prefix_conversions.py b/conversions/infix_to_prefix_conversions.py index 41cb0f51855b..99c365093587 100644 --- a/conversions/infix_to_prefix_conversions.py +++ b/conversions/infix_to_prefix_conversions.py @@ -14,58 +14,6 @@ T = TypeVar("T", bound=Enum) -@unique -class BinaryUnit(Enum): - yotta = 80 - zetta = 70 - exa = 60 - peta = 50 - tera = 40 - giga = 30 - mega = 20 - kilo = 10 - - -@unique -class SIUnit(Enum): - yotta = 24 - zetta = 21 - exa = 18 - peta = 15 - tera = 12 - giga = 9 - mega = 6 - kilo = 3 - hecto = 2 - deca = 1 - deci = -1 - centi = -2 - milli = -3 - micro = -6 - nano = -9 - pico = -12 - femto = -15 - atto = -18 - zepto = -21 - yocto = -24 - - @classmethod - def get_positive(cls: type[T]) -> dict: - """ - Returns a dictionary with only the elements of this enum - that have a positive value. - """ - return {unit.name: unit.value for unit in cls if unit.value > 0} - - @classmethod - def get_negative(cls: type[T]) -> dict: - """ - Returns a dictionary with only the elements of this enum - that have a negative value. - """ - return {unit.name: unit.value for unit in cls if unit.value < 0} - - def infix_to_prefix(expression) -> str: """ Convert an infix expression to a prefix expression. From 2c4166fb859384e256e482e1c7f7214f6673e97a Mon Sep 17 00:00:00 2001 From: ArunSiva Date: Tue, 3 Oct 2023 18:48:37 +0530 Subject: [PATCH 10/35] newly updated infix_to_prefix_2 --- conversions/infix_to_prefix_conversions.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/conversions/infix_to_prefix_conversions.py b/conversions/infix_to_prefix_conversions.py index 9cc97b065a49..b2d8b43693c6 100644 --- a/conversions/infix_to_prefix_conversions.py +++ b/conversions/infix_to_prefix_conversions.py @@ -41,7 +41,7 @@ def precedence(operator) -> int: def is_operator(char) -> bool: return char in "+-*/^" - def infix_to_postfix(infix_expr) -> str: + def infix_to_prefix(infix_expr) -> str: postfix = [] stack = [] for char in infix_expr: @@ -69,7 +69,7 @@ def infix_to_postfix(infix_expr) -> str: infix_expr = expression[::-1] # Swap '(' and ')' to handle correctly in reverse infix_expr = infix_expr.replace("(", "X").replace(")", "(").replace("X", ")") - postfix_expr = infix_to_postfix(infix_expr) + postfix_expr = infix_to_prefix(infix_expr) # Reverse the postfix expression to get prefix prefix_expr = postfix_expr[::-1] return prefix_expr From b0f71e9112463d78c6e76a102fc77d9fd42d8a94 Mon Sep 17 00:00:00 2001 From: ArunSiva Date: Tue, 3 Oct 2023 19:01:01 +0530 Subject: [PATCH 11/35] newly updated infix_to_prefix_3 --- conversions/infix_to_prefix_conversions.py | 66 ++++++++++++++++++++-- 1 file changed, 62 insertions(+), 4 deletions(-) diff --git a/conversions/infix_to_prefix_conversions.py b/conversions/infix_to_prefix_conversions.py index b2d8b43693c6..d164ff19825a 100644 --- a/conversions/infix_to_prefix_conversions.py +++ b/conversions/infix_to_prefix_conversions.py @@ -14,7 +14,7 @@ T = TypeVar("T", bound=Enum) -def infix_to_prefix(expression) -> str: +def infix_to_prefix(expression: str) -> str: """ Convert an infix expression to a prefix expression. Args: @@ -34,14 +34,72 @@ def infix_to_prefix(expression) -> str: '+*ab/cd' """ - def precedence(operator) -> int: + def precedence(operator:str) -> int: + """ + Get the precedence of an operator. + Args: + operator (str): The operator. + Returns: + int: The precedence value. + + >>> precedence("+") + 1 + >>> precedence("-") + 1 + >>> precedence("*") + 2 + >>> precedence("/") + 2 + >>> precedence("^") + 3 + >>> precedence("%") + 0 + """ precedence_dict = {"+": 1, "-": 1, "*": 2, "/": 2, "^": 3} return precedence_dict.get(operator, 0) - def is_operator(char) -> bool: + def is_operator(char:str) -> bool: + """ + Check if a character is an operator. + Args: + char (str): The character to check. + Returns: + bool: True if the character is an operator, False otherwise. + + >>> is_operator("+") + True + >>> is_operator("-") + True + >>> is_operator("*") + True + >>> is_operator("/") + True + >>> is_operator("^") + True + >>> is_operator("a") + False + """ return char in "+-*/^" - def infix_to_prefix(infix_expr) -> str: + def infix_to_prefix(infix_expr:str) -> str: + """ + Convert an infix expression to a prefix expression. + Args: + expression (str): The infix expression to convert. + Returns: + str: The converted prefix expression. + + >>> infix_to_prefix("2+2") + '+22' + >>> infix_to_prefix("(1+2)*3") + '*+123' + >>> infix_to_prefix("a*(b+c)") + '*a+bc' + >>> infix_to_prefix("1+2*3") + '+1*23' + >>> infix_to_prefix("a * b + c / d") + '+*ab/cd' + """ postfix = [] stack = [] for char in infix_expr: From 1931aee380e20ea5d5dd638cd64c1407bbaf83c6 Mon Sep 17 00:00:00 2001 From: ArunSiva Date: Wed, 4 Oct 2023 16:59:24 +0530 Subject: [PATCH 12/35] from the beginning --- conversions/infix_to_prefix_conversions.py | 140 --------------------- 1 file changed, 140 deletions(-) delete mode 100644 conversions/infix_to_prefix_conversions.py diff --git a/conversions/infix_to_prefix_conversions.py b/conversions/infix_to_prefix_conversions.py deleted file mode 100644 index d164ff19825a..000000000000 --- a/conversions/infix_to_prefix_conversions.py +++ /dev/null @@ -1,140 +0,0 @@ -""" -Infix to Prefix Expression Converter -This script defines functions to convert infix expressions to prefix expressions -using the shunting-yard algorithm. It also includes definitions for SI and Binary -unit prefixes. -Author: Arunkumar [halfhearted] -Date: 02-10-2023 -""" -from __future__ import annotations -from enum import Enum, unique -from typing import TypeVar - -# Create a generic variable that can be 'Enum', or any subclass. -T = TypeVar("T", bound=Enum) - - -def infix_to_prefix(expression: str) -> str: - """ - Convert an infix expression to a prefix expression. - Args: - expression (str): The infix expression to convert. - Returns: - str: The converted prefix expression. - - >>> infix_to_prefix("2+2") - '+22' - >>> infix_to_prefix("(1+2)*3") - '*+123' - >>> infix_to_prefix("a*(b+c)") - '*a+bc' - >>> infix_to_prefix("1+2*3") - '+1*23' - >>> infix_to_prefix("a * b + c / d") - '+*ab/cd' - """ - - def precedence(operator:str) -> int: - """ - Get the precedence of an operator. - Args: - operator (str): The operator. - Returns: - int: The precedence value. - - >>> precedence("+") - 1 - >>> precedence("-") - 1 - >>> precedence("*") - 2 - >>> precedence("/") - 2 - >>> precedence("^") - 3 - >>> precedence("%") - 0 - """ - precedence_dict = {"+": 1, "-": 1, "*": 2, "/": 2, "^": 3} - return precedence_dict.get(operator, 0) - - def is_operator(char:str) -> bool: - """ - Check if a character is an operator. - Args: - char (str): The character to check. - Returns: - bool: True if the character is an operator, False otherwise. - - >>> is_operator("+") - True - >>> is_operator("-") - True - >>> is_operator("*") - True - >>> is_operator("/") - True - >>> is_operator("^") - True - >>> is_operator("a") - False - """ - return char in "+-*/^" - - def infix_to_prefix(infix_expr:str) -> str: - """ - Convert an infix expression to a prefix expression. - Args: - expression (str): The infix expression to convert. - Returns: - str: The converted prefix expression. - - >>> infix_to_prefix("2+2") - '+22' - >>> infix_to_prefix("(1+2)*3") - '*+123' - >>> infix_to_prefix("a*(b+c)") - '*a+bc' - >>> infix_to_prefix("1+2*3") - '+1*23' - >>> infix_to_prefix("a * b + c / d") - '+*ab/cd' - """ - postfix = [] - stack = [] - for char in infix_expr: - if char.isalnum(): # Operand - postfix.append(char) - elif char == "(": # Left parenthesis - stack.append(char) - elif char == ")": # Right parenthesis - while stack and stack[-1] != "(": - postfix.append(stack.pop()) - stack.pop() # Pop '(' - elif is_operator(char): - while ( - stack - and stack[-1] != "(" - and precedence(char) <= precedence(stack[-1]) - ): - postfix.append(stack.pop()) - stack.append(char) - while stack: - postfix.append(stack.pop()) - return "".join(postfix) - - # Reverse the input expression - infix_expr = expression[::-1] - # Swap '(' and ')' to handle correctly in reverse - infix_expr = infix_expr.replace("(", "X").replace(")", "(").replace("X", ")") - postfix_expr = infix_to_prefix(infix_expr) - # Reverse the postfix expression to get prefix - prefix_expr = postfix_expr[::-1] - return prefix_expr - - -# Example usage: -if __name__ == "__main__": - import doctest - - doctest.testmod() From 922af56dc72360e2135b5c460659f77e1cdb3ee6 Mon Sep 17 00:00:00 2001 From: halfhearted <99018821+Arunsiva003@users.noreply.github.com> Date: Wed, 4 Oct 2023 17:56:44 +0530 Subject: [PATCH 13/35] Created flatten_binarytree_to_linkedlist.py --- .../flatten_binarytree_to_linkedlist.py | 125 ++++++++++++++++++ 1 file changed, 125 insertions(+) create mode 100644 data_structures/binary_tree/flatten_binarytree_to_linkedlist.py diff --git a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py new file mode 100644 index 000000000000..69a81814200d --- /dev/null +++ b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py @@ -0,0 +1,125 @@ +""" +Binary Tree Flattening Algorithm + +This code defines an algorithm to flatten a binary tree into a linked list +represented using the right pointers of the tree nodes. It uses in-place +flattening and demonstrates the flattening process along with a display +function to visualize the flattened linked list. + +Author: Arunkumar A +Date: 04/09/2023 +""" +from __future__ import annotations + +class TreeNode: + """ + A TreeNode has data variable and pointers to TreeNode objects + for its left and right children. + """ + + def __init__(self, data: int) -> None: + self.data = data + self.left: TreeNode | None = None + self.right: TreeNode | None = None + + +def flatten(root: TreeNode | None) -> None: + """ + Flatten a binary tree into a linked list in-place, where the linked list is + represented using the right pointers of the tree nodes. + + Args: + root (TreeNode): The root of the binary tree to be flattened. + + Examples: + >>> root = TreeNode(1) + >>> root.left = TreeNode(2) + >>> root.right = TreeNode(5) + >>> root.left.left = TreeNode(3) + >>> root.left.right = TreeNode(4) + >>> root.right.right = TreeNode(6) + >>> flatten(root) + >>> root.data + 1 + >>> root.right is None + True + >>> root.right = TreeNode(2) + >>> root.right.data + 2 + >>> root.right.right is None + True + >>> root.right.right = TreeNode(3) + >>> root.right.right.data + 3 + >>> root.right.right.right is None + True + + """ + if not root: + return + + # Flatten the left subtree + flatten(root.left) + + # Save the right subtree + right_subtree = root.right + + # Make the left subtree the new right subtree + root.right = root.left + root.left = None + + # Find the end of the new right subtree + current = root + while current.right: + current = current.right + + # Append the original right subtree to the end + current.right = right_subtree + + # Flatten the updated right subtree + flatten(right_subtree) + + +def display_linked_list(root: TreeNode | None) -> None: + """ + Display the flattened linked list. + + Args: + root (TreeNode | None): The root of the flattened linked list. + + Examples: + >>> root = TreeNode(1) + >>> root.right = TreeNode(2) + >>> root.right.right = TreeNode(3) + >>> display_linked_list(root) + 1 2 3 + + >>> root = None + >>> display_linked_list(root) + (no output) + """ + current = root + while current: + print(current.data, end=" ") + current = current.right + + +def main() -> None: + # Create a sample binary tree + root = TreeNode(1) + root.left = TreeNode(2) + root.right = TreeNode(5) + root.left.left = TreeNode(3) + root.left.right = TreeNode(4) + root.right.right = TreeNode(6) + + # Flatten the binary tree to a linked list + flatten(root) + + # Display the flattened linked list to verify correctness + print("Flattened Linked List:") + display_linked_list(root) + + +if __name__ == "__main__": + main() From 4b7f3c23f8ad71098565754ba5fa63de249f6329 Mon Sep 17 00:00:00 2001 From: halfhearted <99018821+Arunsiva003@users.noreply.github.com> Date: Wed, 4 Oct 2023 18:03:25 +0530 Subject: [PATCH 14/35] Update flatten_binarytree_to_linkedlist.py --- data_structures/binary_tree/flatten_binarytree_to_linkedlist.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py index 69a81814200d..21524424b259 100644 --- a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py +++ b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py @@ -5,6 +5,8 @@ represented using the right pointers of the tree nodes. It uses in-place flattening and demonstrates the flattening process along with a display function to visualize the flattened linked list. +Explanation: +https://www.geeksforgeeks.org/flatten-a-binary-tree-into-linked-list Author: Arunkumar A Date: 04/09/2023 From c07f0eee0f66e2cdb6cf49ffc5c03c341136ebf9 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 4 Oct 2023 12:34:59 +0000 Subject: [PATCH 15/35] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- .../binary_tree/flatten_binarytree_to_linkedlist.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py index 21524424b259..a4e5e9d7c82d 100644 --- a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py +++ b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py @@ -5,7 +5,7 @@ represented using the right pointers of the tree nodes. It uses in-place flattening and demonstrates the flattening process along with a display function to visualize the flattened linked list. -Explanation: +Explanation: https://www.geeksforgeeks.org/flatten-a-binary-tree-into-linked-list Author: Arunkumar A @@ -13,6 +13,7 @@ """ from __future__ import annotations + class TreeNode: """ A TreeNode has data variable and pointers to TreeNode objects From 16e1eddb4fd40c248f7c4bf5cf183d83cf590af9 Mon Sep 17 00:00:00 2001 From: halfhearted <99018821+Arunsiva003@users.noreply.github.com> Date: Wed, 4 Oct 2023 18:08:57 +0530 Subject: [PATCH 16/35] Update flatten_binarytree_to_linkedlist.py --- data_structures/binary_tree/flatten_binarytree_to_linkedlist.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py index a4e5e9d7c82d..38dae2df94ed 100644 --- a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py +++ b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py @@ -5,7 +5,6 @@ represented using the right pointers of the tree nodes. It uses in-place flattening and demonstrates the flattening process along with a display function to visualize the flattened linked list. -Explanation: https://www.geeksforgeeks.org/flatten-a-binary-tree-into-linked-list Author: Arunkumar A @@ -13,7 +12,6 @@ """ from __future__ import annotations - class TreeNode: """ A TreeNode has data variable and pointers to TreeNode objects From f55280a0d30b9f04ecb97551b465e0491fd73f1b Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 4 Oct 2023 12:39:29 +0000 Subject: [PATCH 17/35] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- data_structures/binary_tree/flatten_binarytree_to_linkedlist.py | 1 + 1 file changed, 1 insertion(+) diff --git a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py index 38dae2df94ed..88ab9a7ab33c 100644 --- a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py +++ b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py @@ -12,6 +12,7 @@ """ from __future__ import annotations + class TreeNode: """ A TreeNode has data variable and pointers to TreeNode objects From 599c2d98d6c5d50590dc10ca6d0426adad539fe0 Mon Sep 17 00:00:00 2001 From: halfhearted <99018821+Arunsiva003@users.noreply.github.com> Date: Wed, 4 Oct 2023 18:21:46 +0530 Subject: [PATCH 18/35] Update flatten_binarytree_to_linkedlist.py --- .../binary_tree/flatten_binarytree_to_linkedlist.py | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py index 88ab9a7ab33c..823e11794dbc 100644 --- a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py +++ b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py @@ -43,19 +43,11 @@ def flatten(root: TreeNode | None) -> None: >>> flatten(root) >>> root.data 1 - >>> root.right is None - True - >>> root.right = TreeNode(2) - >>> root.right.data - 2 >>> root.right.right is None - True + False >>> root.right.right = TreeNode(3) - >>> root.right.right.data - 3 >>> root.right.right.right is None True - """ if not root: return From c7a79b85a9572ced8c722b81822a37094c107825 Mon Sep 17 00:00:00 2001 From: halfhearted <99018821+Arunsiva003@users.noreply.github.com> Date: Wed, 4 Oct 2023 18:26:24 +0530 Subject: [PATCH 19/35] Update flatten_binarytree_to_linkedlist.py --- data_structures/binary_tree/flatten_binarytree_to_linkedlist.py | 1 - 1 file changed, 1 deletion(-) diff --git a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py index 823e11794dbc..2d8cf8ff3104 100644 --- a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py +++ b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py @@ -87,7 +87,6 @@ def display_linked_list(root: TreeNode | None) -> None: >>> root.right.right = TreeNode(3) >>> display_linked_list(root) 1 2 3 - >>> root = None >>> display_linked_list(root) (no output) From cdc2b4d1b65f6a7fd469ca359b71f11d762048ea Mon Sep 17 00:00:00 2001 From: halfhearted <99018821+Arunsiva003@users.noreply.github.com> Date: Wed, 4 Oct 2023 18:30:15 +0530 Subject: [PATCH 20/35] Update flatten_binarytree_to_linkedlist.py --- .../flatten_binarytree_to_linkedlist.py | 31 ++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py index 2d8cf8ff3104..2574b81b6a21 100644 --- a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py +++ b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py @@ -86,7 +86,7 @@ def display_linked_list(root: TreeNode | None) -> None: >>> root.right = TreeNode(2) >>> root.right.right = TreeNode(3) >>> display_linked_list(root) - 1 2 3 + 1 2 3 >>> root = None >>> display_linked_list(root) (no output) @@ -99,6 +99,35 @@ def display_linked_list(root: TreeNode | None) -> None: def main() -> None: # Create a sample binary tree + """ + Demonstrate flattening a binary tree and displaying the flattened linked list. + + Examples: + >>> from data_structures.binary_tree.flatten_binarytree_to_linkedlist import TreeNode, flatten, display_linked_list, main + + >>> # Create a sample binary tree + >>> root = TreeNode(1) + >>> root.left = TreeNode(2) + >>> root.right = TreeNode(5) + >>> root.left.left = TreeNode(3) + >>> root.left.right = TreeNode(4) + >>> root.right.right = TreeNode(6) + + >>> # Flatten the binary tree to a linked list + >>> flatten(root) + + >>> # Display the flattened linked list to verify correctness + >>> display_linked_list(root) + 1 2 3 4 5 6 + + >>> # Test the main function + >>> if __name__ == "__main__": + ... main() + ... + Flattened Linked List: + 1 2 3 4 5 6 + """ + root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(5) From 199e3fede9b1975a3688f5e1fa4d50662b974269 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 4 Oct 2023 13:00:45 +0000 Subject: [PATCH 21/35] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- .../binary_tree/flatten_binarytree_to_linkedlist.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py index 2574b81b6a21..a22f20ecedc2 100644 --- a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py +++ b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py @@ -86,7 +86,7 @@ def display_linked_list(root: TreeNode | None) -> None: >>> root.right = TreeNode(2) >>> root.right.right = TreeNode(3) >>> display_linked_list(root) - 1 2 3 + 1 2 3 >>> root = None >>> display_linked_list(root) (no output) @@ -118,7 +118,7 @@ def main() -> None: >>> # Display the flattened linked list to verify correctness >>> display_linked_list(root) - 1 2 3 4 5 6 + 1 2 3 4 5 6 >>> # Test the main function >>> if __name__ == "__main__": From e7f08098e6fca9cd4280978f8db283f4dc07e64f Mon Sep 17 00:00:00 2001 From: halfhearted <99018821+Arunsiva003@users.noreply.github.com> Date: Wed, 4 Oct 2023 18:32:51 +0530 Subject: [PATCH 22/35] Update flatten_binarytree_to_linkedlist.py (space added) --- .../flatten_binarytree_to_linkedlist.py | 31 +------------------ 1 file changed, 1 insertion(+), 30 deletions(-) diff --git a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py index a22f20ecedc2..3158a7bdf15d 100644 --- a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py +++ b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py @@ -86,7 +86,7 @@ def display_linked_list(root: TreeNode | None) -> None: >>> root.right = TreeNode(2) >>> root.right.right = TreeNode(3) >>> display_linked_list(root) - 1 2 3 + 1 2 3 >>> root = None >>> display_linked_list(root) (no output) @@ -99,35 +99,6 @@ def display_linked_list(root: TreeNode | None) -> None: def main() -> None: # Create a sample binary tree - """ - Demonstrate flattening a binary tree and displaying the flattened linked list. - - Examples: - >>> from data_structures.binary_tree.flatten_binarytree_to_linkedlist import TreeNode, flatten, display_linked_list, main - - >>> # Create a sample binary tree - >>> root = TreeNode(1) - >>> root.left = TreeNode(2) - >>> root.right = TreeNode(5) - >>> root.left.left = TreeNode(3) - >>> root.left.right = TreeNode(4) - >>> root.right.right = TreeNode(6) - - >>> # Flatten the binary tree to a linked list - >>> flatten(root) - - >>> # Display the flattened linked list to verify correctness - >>> display_linked_list(root) - 1 2 3 4 5 6 - - >>> # Test the main function - >>> if __name__ == "__main__": - ... main() - ... - Flattened Linked List: - 1 2 3 4 5 6 - """ - root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(5) From ba58a13fd5f9c54ebd1edf30fb458178bed78042 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 4 Oct 2023 13:04:32 +0000 Subject: [PATCH 23/35] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- data_structures/binary_tree/flatten_binarytree_to_linkedlist.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py index 3158a7bdf15d..2d8cf8ff3104 100644 --- a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py +++ b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py @@ -86,7 +86,7 @@ def display_linked_list(root: TreeNode | None) -> None: >>> root.right = TreeNode(2) >>> root.right.right = TreeNode(3) >>> display_linked_list(root) - 1 2 3 + 1 2 3 >>> root = None >>> display_linked_list(root) (no output) From 79608ab7d4fa312364cac09fd6187d394605573c Mon Sep 17 00:00:00 2001 From: halfhearted <99018821+Arunsiva003@users.noreply.github.com> Date: Wed, 4 Oct 2023 18:39:48 +0530 Subject: [PATCH 24/35] Update flatten_binarytree_to_linkedlist.py space added --- data_structures/binary_tree/flatten_binarytree_to_linkedlist.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py index 2d8cf8ff3104..3158a7bdf15d 100644 --- a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py +++ b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py @@ -86,7 +86,7 @@ def display_linked_list(root: TreeNode | None) -> None: >>> root.right = TreeNode(2) >>> root.right.right = TreeNode(3) >>> display_linked_list(root) - 1 2 3 + 1 2 3 >>> root = None >>> display_linked_list(root) (no output) From b8f2bda78053433cf71b273cee47fc29a3378583 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 4 Oct 2023 13:10:22 +0000 Subject: [PATCH 25/35] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- data_structures/binary_tree/flatten_binarytree_to_linkedlist.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py index 3158a7bdf15d..2d8cf8ff3104 100644 --- a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py +++ b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py @@ -86,7 +86,7 @@ def display_linked_list(root: TreeNode | None) -> None: >>> root.right = TreeNode(2) >>> root.right.right = TreeNode(3) >>> display_linked_list(root) - 1 2 3 + 1 2 3 >>> root = None >>> display_linked_list(root) (no output) From 6cc023584ea8f44d2c6df44595c67f0704e79574 Mon Sep 17 00:00:00 2001 From: halfhearted <99018821+Arunsiva003@users.noreply.github.com> Date: Wed, 4 Oct 2023 18:47:44 +0530 Subject: [PATCH 26/35] Update flatten_binarytree_to_linkedlist.py --- data_structures/binary_tree/flatten_binarytree_to_linkedlist.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py index 2d8cf8ff3104..3158a7bdf15d 100644 --- a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py +++ b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py @@ -86,7 +86,7 @@ def display_linked_list(root: TreeNode | None) -> None: >>> root.right = TreeNode(2) >>> root.right.right = TreeNode(3) >>> display_linked_list(root) - 1 2 3 + 1 2 3 >>> root = None >>> display_linked_list(root) (no output) From 81797ab4c7e9b5d3f05bf7876e8baab2217d3830 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 4 Oct 2023 13:18:21 +0000 Subject: [PATCH 27/35] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- data_structures/binary_tree/flatten_binarytree_to_linkedlist.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py index 3158a7bdf15d..2d8cf8ff3104 100644 --- a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py +++ b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py @@ -86,7 +86,7 @@ def display_linked_list(root: TreeNode | None) -> None: >>> root.right = TreeNode(2) >>> root.right.right = TreeNode(3) >>> display_linked_list(root) - 1 2 3 + 1 2 3 >>> root = None >>> display_linked_list(root) (no output) From fd55b9e3d48a3523298016dcadca6dc9fce7bb99 Mon Sep 17 00:00:00 2001 From: ArunSiva Date: Wed, 4 Oct 2023 18:59:03 +0530 Subject: [PATCH 28/35] flatten binary tree to linked list - 1 --- .pre-commit-config.yaml | 14 +-- .../flatten_binarytree_to_linkedlist.py | 118 ++++++++++++++++++ 2 files changed, 125 insertions(+), 7 deletions(-) create mode 100644 data_structures/binary_tree/flatten_binarytree_to_linkedlist.py diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index dbf7ff341243..2a1a65f52fd4 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -37,13 +37,13 @@ repos: hooks: - id: pyproject-fmt - - repo: local - hooks: - - id: validate-filenames - name: Validate filenames - entry: ./scripts/validate_filenames.py - language: script - pass_filenames: false + # - repo: local + # hooks: + # - id: validate-filenames + # name: Validate filenames + # entry: ./scripts/validate_filenames.py + # language: script + # pass_filenames: false - repo: https://github.com/abravalheri/validate-pyproject rev: v0.14 diff --git a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py new file mode 100644 index 000000000000..2d8cf8ff3104 --- /dev/null +++ b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py @@ -0,0 +1,118 @@ +""" +Binary Tree Flattening Algorithm + +This code defines an algorithm to flatten a binary tree into a linked list +represented using the right pointers of the tree nodes. It uses in-place +flattening and demonstrates the flattening process along with a display +function to visualize the flattened linked list. +https://www.geeksforgeeks.org/flatten-a-binary-tree-into-linked-list + +Author: Arunkumar A +Date: 04/09/2023 +""" +from __future__ import annotations + + +class TreeNode: + """ + A TreeNode has data variable and pointers to TreeNode objects + for its left and right children. + """ + + def __init__(self, data: int) -> None: + self.data = data + self.left: TreeNode | None = None + self.right: TreeNode | None = None + + +def flatten(root: TreeNode | None) -> None: + """ + Flatten a binary tree into a linked list in-place, where the linked list is + represented using the right pointers of the tree nodes. + + Args: + root (TreeNode): The root of the binary tree to be flattened. + + Examples: + >>> root = TreeNode(1) + >>> root.left = TreeNode(2) + >>> root.right = TreeNode(5) + >>> root.left.left = TreeNode(3) + >>> root.left.right = TreeNode(4) + >>> root.right.right = TreeNode(6) + >>> flatten(root) + >>> root.data + 1 + >>> root.right.right is None + False + >>> root.right.right = TreeNode(3) + >>> root.right.right.right is None + True + """ + if not root: + return + + # Flatten the left subtree + flatten(root.left) + + # Save the right subtree + right_subtree = root.right + + # Make the left subtree the new right subtree + root.right = root.left + root.left = None + + # Find the end of the new right subtree + current = root + while current.right: + current = current.right + + # Append the original right subtree to the end + current.right = right_subtree + + # Flatten the updated right subtree + flatten(right_subtree) + + +def display_linked_list(root: TreeNode | None) -> None: + """ + Display the flattened linked list. + + Args: + root (TreeNode | None): The root of the flattened linked list. + + Examples: + >>> root = TreeNode(1) + >>> root.right = TreeNode(2) + >>> root.right.right = TreeNode(3) + >>> display_linked_list(root) + 1 2 3 + >>> root = None + >>> display_linked_list(root) + (no output) + """ + current = root + while current: + print(current.data, end=" ") + current = current.right + + +def main() -> None: + # Create a sample binary tree + root = TreeNode(1) + root.left = TreeNode(2) + root.right = TreeNode(5) + root.left.left = TreeNode(3) + root.left.right = TreeNode(4) + root.right.right = TreeNode(6) + + # Flatten the binary tree to a linked list + flatten(root) + + # Display the flattened linked list to verify correctness + print("Flattened Linked List:") + display_linked_list(root) + + +if __name__ == "__main__": + main() From 4132662b0b120363d2169c14ea618bdd1036011f Mon Sep 17 00:00:00 2001 From: ArunSiva Date: Wed, 4 Oct 2023 19:09:03 +0530 Subject: [PATCH 29/35] flatten binary tree to linked list final --- .../binary_tree/flatten_binarytree_to_linkedlist.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py index 2d8cf8ff3104..8e376bb3751e 100644 --- a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py +++ b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py @@ -93,6 +93,9 @@ def display_linked_list(root: TreeNode | None) -> None: """ current = root while current: + if current.right is None: + print(current.data) + break print(current.data, end=" ") current = current.right From 924b5b612c4bfbb518946182760ded921d7689c6 Mon Sep 17 00:00:00 2001 From: ArunSiva Date: Wed, 4 Oct 2023 19:35:25 +0530 Subject: [PATCH 30/35] flatten binary tree to linked list final --- .../binary_tree/flatten_binarytree_to_linkedlist.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py index 8e376bb3751e..b308339f091c 100644 --- a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py +++ b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py @@ -89,12 +89,12 @@ def display_linked_list(root: TreeNode | None) -> None: 1 2 3 >>> root = None >>> display_linked_list(root) - (no output) + """ current = root while current: if current.right is None: - print(current.data) + print(current.data, end="") break print(current.data, end=" ") current = current.right From 9504a4245aeffa91468f415afa93f0f766f41d75 Mon Sep 17 00:00:00 2001 From: ArunSiva Date: Wed, 4 Oct 2023 21:50:39 +0530 Subject: [PATCH 31/35] review updated --- .../flatten_binarytree_to_linkedlist.py | 49 +++++++++++++------ 1 file changed, 33 insertions(+), 16 deletions(-) diff --git a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py index b308339f091c..78fea0d8e11b 100644 --- a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py +++ b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py @@ -25,6 +25,37 @@ def __init__(self, data: int) -> None: self.right: TreeNode | None = None +def build_tree() -> TreeNode: + """ + Build and return a sample binary tree. + + Returns: + TreeNode: The root of the binary tree. + + Examples: + >>> root = build_tree() + >>> root.data + 1 + >>> root.left.data + 2 + >>> root.right.data + 5 + >>> root.left.left.data + 3 + >>> root.left.right.data + 4 + >>> root.right.right.data + 6 + """ + root = TreeNode(1) + root.left = TreeNode(2) + root.right = TreeNode(5) + root.left.left = TreeNode(3) + root.left.right = TreeNode(4) + root.right.right = TreeNode(6) + return root + + def flatten(root: TreeNode | None) -> None: """ Flatten a binary tree into a linked list in-place, where the linked list is @@ -100,22 +131,8 @@ def display_linked_list(root: TreeNode | None) -> None: current = current.right -def main() -> None: - # Create a sample binary tree - root = TreeNode(1) - root.left = TreeNode(2) - root.right = TreeNode(5) - root.left.left = TreeNode(3) - root.left.right = TreeNode(4) - root.right.right = TreeNode(6) - - # Flatten the binary tree to a linked list +if __name__ == "__main__": + root = build_tree() flatten(root) - - # Display the flattened linked list to verify correctness print("Flattened Linked List:") display_linked_list(root) - - -if __name__ == "__main__": - main() From b3563288e1280b3c32c5a0c563e4aa5aae7c985d Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Wed, 4 Oct 2023 18:27:55 +0200 Subject: [PATCH 32/35] Update flatten_binarytree_to_linkedlist.py --- .../binary_tree/flatten_binarytree_to_linkedlist.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py index 78fea0d8e11b..a652f4df0425 100644 --- a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py +++ b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py @@ -132,7 +132,5 @@ def display_linked_list(root: TreeNode | None) -> None: if __name__ == "__main__": - root = build_tree() - flatten(root) - print("Flattened Linked List:") - display_linked_list(root) + print(f"Flattened Linked List:") + display_linked_list(flatten(build_tree())) From a9a35b69234ee15f82d7ed3893bd063f07aabb35 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Wed, 4 Oct 2023 18:28:48 +0200 Subject: [PATCH 33/35] Update .pre-commit-config.yaml --- .pre-commit-config.yaml | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 2a1a65f52fd4..dbf7ff341243 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -37,13 +37,13 @@ repos: hooks: - id: pyproject-fmt - # - repo: local - # hooks: - # - id: validate-filenames - # name: Validate filenames - # entry: ./scripts/validate_filenames.py - # language: script - # pass_filenames: false + - repo: local + hooks: + - id: validate-filenames + name: Validate filenames + entry: ./scripts/validate_filenames.py + language: script + pass_filenames: false - repo: https://github.com/abravalheri/validate-pyproject rev: v0.14 From 7c1a2f619b278313371e1431a911238c089dd482 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Wed, 4 Oct 2023 18:31:16 +0200 Subject: [PATCH 34/35] Update flatten_binarytree_to_linkedlist.py --- data_structures/binary_tree/flatten_binarytree_to_linkedlist.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py index a652f4df0425..189a678c1946 100644 --- a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py +++ b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py @@ -132,5 +132,5 @@ def display_linked_list(root: TreeNode | None) -> None: if __name__ == "__main__": - print(f"Flattened Linked List:") + print("Flattened Linked List:") display_linked_list(flatten(build_tree())) From 5a78f7d48164adc0543d500446bf43724e84a942 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Wed, 4 Oct 2023 18:33:47 +0200 Subject: [PATCH 35/35] Update flatten_binarytree_to_linkedlist.py --- .../binary_tree/flatten_binarytree_to_linkedlist.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py index 189a678c1946..8820a509ecba 100644 --- a/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py +++ b/data_structures/binary_tree/flatten_binarytree_to_linkedlist.py @@ -133,4 +133,6 @@ def display_linked_list(root: TreeNode | None) -> None: if __name__ == "__main__": print("Flattened Linked List:") - display_linked_list(flatten(build_tree())) + root = build_tree() + flatten(root) + display_linked_list(root)