SlideShare ist ein Scribd-Unternehmen logo
1 von 5
Downloaden Sie, um offline zu lesen
Hi can I see an example for the output of this code to make sure my output is correct.
import random
import time
import string
class TestDataGenerator:
def __init__(self):
pass
def generateData(self, size):
data = [""] * size
for i in range(size):
length = random.randint(1, 1000)
chars = string.ascii_uppercase + string.ascii_lowercase
string_val = ''.join(random.choice(chars) for _ in range(length))
data[i] = string_val
return data
from abc import ABC, abstractmethod
# abstract class to represent a set and its insert/search operations
class AbstractSet(ABC):
# constructor
@abstractmethod
def __init__(self):
pass
# inserts "element" in the set
# returns "True" after successful insertion, "False" if the element is already in the set
# element : str
# inserted : bool
@abstractmethod
def insertElement(self, element):
inserted = False
return inserted
# checks whether "element" is in the set
# returns "True" if it is, "False" otherwise
# element : str
# found : bool
@abstractmethod
def searchElement(self, element):
found = False
return found
# abstract class to represent a synthetic data generator
class AbstractTestDataGenerator(ABC):
# constructor
@abstractmethod
def __init__(self):
pass
# creates and returns a list of length "size" of strings
# size : int
# data : list
@abstractmethod
def generateData(self, size):
data = [""]*size
return data
import sys
sys.setrecursionlimit(10000)
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
self.color = "BLACK"
import timeit
import string
import random
import sys
sys.setrecursionlimit(10000)
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
self.color = "BLACK"
class BalancedSearchTreeSet(AbstractSet):
def __init__(self):
self.root = None
def rotateLeft(self, n):
x = n.right
n.right = x.left
x.left = n
x.color = n.color
n.color = "RED"
return x
def rotateRight(self, n):
x = n.left
n.left = x.right
x.right = n
x.color = n.color
n.color = "RED"
return x
def flipColor(self, n):
n.color = "RED"
n.left.color = "BLACK"
n.right.color = "BLACK"
def isRed(self, node):
if node is None:
return False
return node.color == "RED"
def insertElement(self, value):
self.root = self._insert(self.root, value)
self.root.color = "BLACK"
def _insert(self, node, value):
if node is None:
return Node(value)
if value < node.value:
node.left = self._insert(node.left, value)
else:
node.right = self._insert(node.right, value)
if self.isRed(node.right) and not self.isRed(node.left):
node = self.rotateLeft(node)
if self.isRed(node.left) and self.isRed(node.left.left):
node = self.rotateRight(node)
if self.isRed(node.left) and self.isRed(node.right):
self.flipColor(node)
return node
def searchElement(self, value):
return self._search(self.root, value)
def _search(self, node, value):
if node is None:
return None
if node.value.lower() == value.lower():
return node
if value.lower() < node.value.lower():
return self._search(node.left, value)
else:
return self._search(node.right, value)
bst_set = BalancedSearchTreeSet()
data_generator = TestDataGenerator()
# Test parameters
data_sizes = [100, 1000, 10000]
num_runs = 5
# Test with varying data sizes and distributions
for size in data_sizes:
print(f"Data size: {size}")
data = data_generator.generateData(size)
sorted_data = sorted(data)
reversed_data = list(reversed(sorted_data))
datasets = {"Random": data, "Sorted": sorted_data, "Reversed": reversed_data}
for dist, dataset in datasets.items():
print(f" Data distribution: {dist}")
# insertion time
insert_time = timeit.timeit(
lambda: [bst_set.insertElement(x) for x in dataset], number=num_runs
) / num_runs
# search time
search_time = timeit.timeit(
lambda: [x in bst_set for x in dataset], number=num_runs
) / num_runs
# Print the results
print(f" Insertion time: {insert_time:.6f} seconds")
print(f" Search time: {search_time:.6f} seconds")
print()
# Edge cases
edge_cases = [
("Empty set search", []),
("Duplicate insertion", data),
("Nonexistent element search", ["nonexistent_element"]),
]
for test_name, edge_data in edge_cases:
print(f"Edge case: {test_name}")

Weitere ähnliche Inhalte

Ähnlich wie Hi can I see an example for the output of this code to make sure my .pdf

# Imports# Include your imports here, if any are used. import.pdf
 # Imports# Include your imports here, if any are used. import.pdf # Imports# Include your imports here, if any are used. import.pdf
# Imports# Include your imports here, if any are used. import.pdf
gulshan16175gs
 
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
arihantelehyb
 
Inspect the class declaration for a doubly-linked list node in Node-h-.pdf
Inspect the class declaration for a doubly-linked list node in Node-h-.pdfInspect the class declaration for a doubly-linked list node in Node-h-.pdf
Inspect the class declaration for a doubly-linked list node in Node-h-.pdf
vishalateen
 
Need to be done in C Please Sorted number list implementation with.pdf
Need to be done in C  Please   Sorted number list implementation with.pdfNeed to be done in C  Please   Sorted number list implementation with.pdf
Need to be done in C Please Sorted number list implementation with.pdf
aathmaproducts
 
Need to be done in C++ Please Sorted number list implementation wit.pdf
Need to be done in C++  Please   Sorted number list implementation wit.pdfNeed to be done in C++  Please   Sorted number list implementation wit.pdf
Need to be done in C++ Please Sorted number list implementation wit.pdf
aathiauto
 
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
rushabhshah600
 
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdfAssignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Footageetoffe16
 

Ähnlich wie Hi can I see an example for the output of this code to make sure my .pdf (20)

# Imports# Include your imports here, if any are used. import.pdf
 # Imports# Include your imports here, if any are used. import.pdf # Imports# Include your imports here, if any are used. import.pdf
# Imports# Include your imports here, if any are used. import.pdf
 
python practicals-solution-2019-20-class-xii.pdf
python practicals-solution-2019-20-class-xii.pdfpython practicals-solution-2019-20-class-xii.pdf
python practicals-solution-2019-20-class-xii.pdf
 
Practicle 1.docx
Practicle 1.docxPracticle 1.docx
Practicle 1.docx
 
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
 
Inspect the class declaration for a doubly-linked list node in Node-h-.pdf
Inspect the class declaration for a doubly-linked list node in Node-h-.pdfInspect the class declaration for a doubly-linked list node in Node-h-.pdf
Inspect the class declaration for a doubly-linked list node in Node-h-.pdf
 
CBSE Class XII Comp sc practical file
CBSE Class XII Comp sc practical fileCBSE Class XII Comp sc practical file
CBSE Class XII Comp sc practical file
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
python_lab_manual_final (1).pdf
python_lab_manual_final (1).pdfpython_lab_manual_final (1).pdf
python_lab_manual_final (1).pdf
 
Python programming : Arrays
Python programming : ArraysPython programming : Arrays
Python programming : Arrays
 
Need to be done in C Please Sorted number list implementation with.pdf
Need to be done in C  Please   Sorted number list implementation with.pdfNeed to be done in C  Please   Sorted number list implementation with.pdf
Need to be done in C Please Sorted number list implementation with.pdf
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
Need to be done in C++ Please Sorted number list implementation wit.pdf
Need to be done in C++  Please   Sorted number list implementation wit.pdfNeed to be done in C++  Please   Sorted number list implementation wit.pdf
Need to be done in C++ Please Sorted number list implementation wit.pdf
 
Javascript & jQuery: A pragmatic introduction
Javascript & jQuery: A pragmatic introductionJavascript & jQuery: A pragmatic introduction
Javascript & jQuery: A pragmatic introduction
 
SlideSet_4_Arraysnew.pdf
SlideSet_4_Arraysnew.pdfSlideSet_4_Arraysnew.pdf
SlideSet_4_Arraysnew.pdf
 
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
 
ARRAY OPERATIONS.pptx
ARRAY OPERATIONS.pptxARRAY OPERATIONS.pptx
ARRAY OPERATIONS.pptx
 
Programs.doc
Programs.docPrograms.doc
Programs.doc
 
AI-Programs.pdf
AI-Programs.pdfAI-Programs.pdf
AI-Programs.pdf
 
fds Practicle 1to 6 program.pdf
fds Practicle 1to 6 program.pdffds Practicle 1to 6 program.pdf
fds Practicle 1to 6 program.pdf
 
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdfAssignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
 

Mehr von aggarwalshoppe14

I really need some help if I have this right so far. Please Resub.pdf
I really need some help if I have this right so far. Please Resub.pdfI really need some help if I have this right so far. Please Resub.pdf
I really need some help if I have this right so far. Please Resub.pdf
aggarwalshoppe14
 
I really need some help if I have this right so far. PLEASE CHANG.pdf
I really need some help if I have this right so far. PLEASE CHANG.pdfI really need some help if I have this right so far. PLEASE CHANG.pdf
I really need some help if I have this right so far. PLEASE CHANG.pdf
aggarwalshoppe14
 
I need this code, to show ALL inventory items, then with the remove .pdf
I need this code, to show ALL inventory items, then with the remove .pdfI need this code, to show ALL inventory items, then with the remove .pdf
I need this code, to show ALL inventory items, then with the remove .pdf
aggarwalshoppe14
 
I need help with the last 2 methods only in Huffman.java file the me.pdf
I need help with the last 2 methods only in Huffman.java file the me.pdfI need help with the last 2 methods only in Huffman.java file the me.pdf
I need help with the last 2 methods only in Huffman.java file the me.pdf
aggarwalshoppe14
 
I need help creating this flutter applicationPlease provide a com.pdf
I need help creating this flutter applicationPlease provide a com.pdfI need help creating this flutter applicationPlease provide a com.pdf
I need help creating this flutter applicationPlease provide a com.pdf
aggarwalshoppe14
 
Hile ��geni bileenlerini a�klar. Tannm bir kriminolog olan Donald .pdf
Hile ��geni bileenlerini a�klar. Tannm bir kriminolog olan Donald .pdfHile ��geni bileenlerini a�klar. Tannm bir kriminolog olan Donald .pdf
Hile ��geni bileenlerini a�klar. Tannm bir kriminolog olan Donald .pdf
aggarwalshoppe14
 
Hi could I get the java code for all the tasks pls, many thanks!.pdf
Hi could I get the java code for all the tasks pls, many thanks!.pdfHi could I get the java code for all the tasks pls, many thanks!.pdf
Hi could I get the java code for all the tasks pls, many thanks!.pdf
aggarwalshoppe14
 
Here is app.js, artist.js and songs.js file. Can you look at the my .pdf
Here is app.js, artist.js and songs.js file. Can you look at the my .pdfHere is app.js, artist.js and songs.js file. Can you look at the my .pdf
Here is app.js, artist.js and songs.js file. Can you look at the my .pdf
aggarwalshoppe14
 
Here are the instructions and then the code in a sec. Please R.pdf
Here are the instructions and then the code in a sec. Please R.pdfHere are the instructions and then the code in a sec. Please R.pdf
Here are the instructions and then the code in a sec. Please R.pdf
aggarwalshoppe14
 
help write program Project Desoription The purpose of thi project i.pdf
help write program Project Desoription The purpose of thi project i.pdfhelp write program Project Desoription The purpose of thi project i.pdf
help write program Project Desoription The purpose of thi project i.pdf
aggarwalshoppe14
 
I need a case analysis using Harvards Business School format please.pdf
I need a case analysis using Harvards Business School format please.pdfI need a case analysis using Harvards Business School format please.pdf
I need a case analysis using Harvards Business School format please.pdf
aggarwalshoppe14
 

Mehr von aggarwalshoppe14 (20)

I am sure you have heard the adage �my word is my bond�. We do not k.pdf
I am sure you have heard the adage �my word is my bond�. We do not k.pdfI am sure you have heard the adage �my word is my bond�. We do not k.pdf
I am sure you have heard the adage �my word is my bond�. We do not k.pdf
 
I really need some help if I have this right so far. Please Resub.pdf
I really need some help if I have this right so far. Please Resub.pdfI really need some help if I have this right so far. Please Resub.pdf
I really need some help if I have this right so far. Please Resub.pdf
 
I receive this answer for one of my questions, I need the reference .pdf
I receive this answer for one of my questions, I need the reference .pdfI receive this answer for one of my questions, I need the reference .pdf
I receive this answer for one of my questions, I need the reference .pdf
 
I really need some help if I have this right so far. PLEASE CHANG.pdf
I really need some help if I have this right so far. PLEASE CHANG.pdfI really need some help if I have this right so far. PLEASE CHANG.pdf
I really need some help if I have this right so far. PLEASE CHANG.pdf
 
I need this code, to show ALL inventory items, then with the remove .pdf
I need this code, to show ALL inventory items, then with the remove .pdfI need this code, to show ALL inventory items, then with the remove .pdf
I need this code, to show ALL inventory items, then with the remove .pdf
 
I need help with the last 2 methods only in Huffman.java file the me.pdf
I need help with the last 2 methods only in Huffman.java file the me.pdfI need help with the last 2 methods only in Huffman.java file the me.pdf
I need help with the last 2 methods only in Huffman.java file the me.pdf
 
I need help creating this flutter applicationPlease provide a com.pdf
I need help creating this flutter applicationPlease provide a com.pdfI need help creating this flutter applicationPlease provide a com.pdf
I need help creating this flutter applicationPlease provide a com.pdf
 
His Majesty�s Government report that 20 of officials arrive late fo.pdf
His Majesty�s Government report that 20 of officials arrive late fo.pdfHis Majesty�s Government report that 20 of officials arrive late fo.pdf
His Majesty�s Government report that 20 of officials arrive late fo.pdf
 
HIVin RNA genomu, bir RNA ablonundan bir DNA genomunu sentezlemek i.pdf
HIVin RNA genomu, bir RNA ablonundan bir DNA genomunu sentezlemek i.pdfHIVin RNA genomu, bir RNA ablonundan bir DNA genomunu sentezlemek i.pdf
HIVin RNA genomu, bir RNA ablonundan bir DNA genomunu sentezlemek i.pdf
 
Hile ��geni bileenlerini a�klar. Tannm bir kriminolog olan Donald .pdf
Hile ��geni bileenlerini a�klar. Tannm bir kriminolog olan Donald .pdfHile ��geni bileenlerini a�klar. Tannm bir kriminolog olan Donald .pdf
Hile ��geni bileenlerini a�klar. Tannm bir kriminolog olan Donald .pdf
 
Hi, I need help with this Probability question. Please show work and.pdf
Hi, I need help with this Probability question. Please show work and.pdfHi, I need help with this Probability question. Please show work and.pdf
Hi, I need help with this Probability question. Please show work and.pdf
 
Hi could I get the java code for all the tasks pls, many thanks!.pdf
Hi could I get the java code for all the tasks pls, many thanks!.pdfHi could I get the java code for all the tasks pls, many thanks!.pdf
Hi could I get the java code for all the tasks pls, many thanks!.pdf
 
HHI analysis indicates that many states have a highly concentrated i.pdf
HHI analysis indicates that many states have a highly concentrated i.pdfHHI analysis indicates that many states have a highly concentrated i.pdf
HHI analysis indicates that many states have a highly concentrated i.pdf
 
Hello I need help configuring the regression equation for this scatt.pdf
Hello I need help configuring the regression equation for this scatt.pdfHello I need help configuring the regression equation for this scatt.pdf
Hello I need help configuring the regression equation for this scatt.pdf
 
Health Economics with Taxation and Agrarian ReformActivity 2 Grap.pdf
Health Economics with Taxation and Agrarian ReformActivity 2 Grap.pdfHealth Economics with Taxation and Agrarian ReformActivity 2 Grap.pdf
Health Economics with Taxation and Agrarian ReformActivity 2 Grap.pdf
 
Here is app.js, artist.js and songs.js file. Can you look at the my .pdf
Here is app.js, artist.js and songs.js file. Can you look at the my .pdfHere is app.js, artist.js and songs.js file. Can you look at the my .pdf
Here is app.js, artist.js and songs.js file. Can you look at the my .pdf
 
Here is a short amino acid sequence mapped as polar (P) and nonpolar.pdf
Here is a short amino acid sequence mapped as polar (P) and nonpolar.pdfHere is a short amino acid sequence mapped as polar (P) and nonpolar.pdf
Here is a short amino acid sequence mapped as polar (P) and nonpolar.pdf
 
Here are the instructions and then the code in a sec. Please R.pdf
Here are the instructions and then the code in a sec. Please R.pdfHere are the instructions and then the code in a sec. Please R.pdf
Here are the instructions and then the code in a sec. Please R.pdf
 
help write program Project Desoription The purpose of thi project i.pdf
help write program Project Desoription The purpose of thi project i.pdfhelp write program Project Desoription The purpose of thi project i.pdf
help write program Project Desoription The purpose of thi project i.pdf
 
I need a case analysis using Harvards Business School format please.pdf
I need a case analysis using Harvards Business School format please.pdfI need a case analysis using Harvards Business School format please.pdf
I need a case analysis using Harvards Business School format please.pdf
 

Kürzlich hochgeladen

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 

Kürzlich hochgeladen (20)

HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 

Hi can I see an example for the output of this code to make sure my .pdf

  • 1. Hi can I see an example for the output of this code to make sure my output is correct. import random import time import string class TestDataGenerator: def __init__(self): pass def generateData(self, size): data = [""] * size for i in range(size): length = random.randint(1, 1000) chars = string.ascii_uppercase + string.ascii_lowercase string_val = ''.join(random.choice(chars) for _ in range(length)) data[i] = string_val return data from abc import ABC, abstractmethod # abstract class to represent a set and its insert/search operations class AbstractSet(ABC): # constructor @abstractmethod def __init__(self): pass # inserts "element" in the set # returns "True" after successful insertion, "False" if the element is already in the set # element : str # inserted : bool @abstractmethod def insertElement(self, element): inserted = False return inserted
  • 2. # checks whether "element" is in the set # returns "True" if it is, "False" otherwise # element : str # found : bool @abstractmethod def searchElement(self, element): found = False return found # abstract class to represent a synthetic data generator class AbstractTestDataGenerator(ABC): # constructor @abstractmethod def __init__(self): pass # creates and returns a list of length "size" of strings # size : int # data : list @abstractmethod def generateData(self, size): data = [""]*size return data import sys sys.setrecursionlimit(10000) class Node: def __init__(self, value): self.value = value self.left = None self.right = None self.color = "BLACK" import timeit import string
  • 3. import random import sys sys.setrecursionlimit(10000) class Node: def __init__(self, value): self.value = value self.left = None self.right = None self.color = "BLACK" class BalancedSearchTreeSet(AbstractSet): def __init__(self): self.root = None def rotateLeft(self, n): x = n.right n.right = x.left x.left = n x.color = n.color n.color = "RED" return x def rotateRight(self, n): x = n.left n.left = x.right x.right = n x.color = n.color n.color = "RED" return x def flipColor(self, n): n.color = "RED" n.left.color = "BLACK" n.right.color = "BLACK" def isRed(self, node): if node is None: return False return node.color == "RED" def insertElement(self, value): self.root = self._insert(self.root, value)
  • 4. self.root.color = "BLACK" def _insert(self, node, value): if node is None: return Node(value) if value < node.value: node.left = self._insert(node.left, value) else: node.right = self._insert(node.right, value) if self.isRed(node.right) and not self.isRed(node.left): node = self.rotateLeft(node) if self.isRed(node.left) and self.isRed(node.left.left): node = self.rotateRight(node) if self.isRed(node.left) and self.isRed(node.right): self.flipColor(node) return node def searchElement(self, value): return self._search(self.root, value) def _search(self, node, value): if node is None: return None if node.value.lower() == value.lower(): return node if value.lower() < node.value.lower(): return self._search(node.left, value) else: return self._search(node.right, value) bst_set = BalancedSearchTreeSet() data_generator = TestDataGenerator() # Test parameters data_sizes = [100, 1000, 10000] num_runs = 5 # Test with varying data sizes and distributions for size in data_sizes: print(f"Data size: {size}") data = data_generator.generateData(size)
  • 5. sorted_data = sorted(data) reversed_data = list(reversed(sorted_data)) datasets = {"Random": data, "Sorted": sorted_data, "Reversed": reversed_data} for dist, dataset in datasets.items(): print(f" Data distribution: {dist}") # insertion time insert_time = timeit.timeit( lambda: [bst_set.insertElement(x) for x in dataset], number=num_runs ) / num_runs # search time search_time = timeit.timeit( lambda: [x in bst_set for x in dataset], number=num_runs ) / num_runs # Print the results print(f" Insertion time: {insert_time:.6f} seconds") print(f" Search time: {search_time:.6f} seconds") print() # Edge cases edge_cases = [ ("Empty set search", []), ("Duplicate insertion", data), ("Nonexistent element search", ["nonexistent_element"]), ] for test_name, edge_data in edge_cases: print(f"Edge case: {test_name}")