diff --git "a/dataset/processed/dataset_step1_length_normalized.csv" "b/dataset/processed/dataset_step1_length_normalized.csv"
new file mode 100644--- /dev/null
+++ "b/dataset/processed/dataset_step1_length_normalized.csv"
@@ -0,0 +1,25969 @@
+Code_ID,Code_Text,"Label (0- HUMAN, 1-AI)",Source_Type,Generation_Prompt,Language,normalized_code,original_line_count,normalized_line_count
+,"import requests
+from bs4 import BeautifulSoup
+from concurrent.futures import ThreadPoolExecutor # Import ThreadPoolExecutor for multi-threading
+import urllib.robotparser
+from urllib.parse import urlparse, urljoin # Import urlparse and urljoin for URL manipulation
+
+
+def is_allowed(url, user_agent='*'):
+
+ parsed_url = urlparse(url)
+ base_url = f'{parsed_url.scheme}://{parsed_url.netloc}'
+ robots_url = urljoin(base_url, 'robots.txt')
+
+
+ rp = urllib.robotparser.RobotFileParser()
+ rp.set_url(robots_url)
+ rp.read()
+
+
+ return rp.can_fetch(user_agent, url)
+
+
+def fetch_page(url):
+
+ if not is_allowed(url):
+ print(f'Scraping not allowed for {url}')
+ return None
+
+ try:
+
+ response = requests.get(url)
+
+ if response.status_code == 200:
+ print(f'Successfully fetched {url}')
+
+ soup = BeautifulSoup(response.content, 'html.parser')
+ return soup
+ else:
+ print(f'Failed to fetch {url} with status code {response.status_code}')
+ except Exception as e:
+ print(f'Exception occurred while fetching {url}: {e}')
+ return None
+
+
+def extract_links(soup, base_url):
+ links = []
+ if soup:
+
+ for link in soup.find_all('a', href=True):
+
+ full_url = urljoin(base_url, link['href'])
+ links.append(full_url)
+ return links
+
+
+def scrape_urls(urls, max_workers=5):
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
+
+ futures = {executor.submit(fetch_page, url): url for url in urls}
+ results = []
+ for future in futures:
+ result = future.result()
+ if result:
+ results.append(result)
+ return results
+
+
+def main():
+ start_url = 'https://example.com' # Replace with the URL you want to start scraping from
+
+ soup = fetch_page(start_url)
+ if not soup:
+ return
+
+
+ links = extract_links(soup, start_url)
+
+ pages = scrape_urls(links)
+
+
+ for page in pages:
+
+ if page:
+ title = page.find('title').get_text()
+ print(f'Page title: {title}')
+
+if __name__ == '__main__':
+ main()",0.0,W3RESOURCE,,PYTHON,"import requests
+from bs4 import BeautifulSoup
+from concurrent.futures import ThreadPoolExecutor # Import ThreadPoolExecutor for multi-threading
+import urllib.robotparser
+from urllib.parse import urlparse, urljoin # Import urlparse and urljoin for URL manipulation
+
+
+def is_allowed(url, user_agent='*'):
+
+ parsed_url = urlparse(url)
+ base_url = f'{parsed_url.scheme}://{parsed_url.netloc}'
+ robots_url = urljoin(base_url, 'robots.txt')
+
+
+ rp = urllib.robotparser.RobotFileParser()
+ rp.set_url(robots_url)
+ rp.read()
+
+
+ return rp.can_fetch(user_agent, url)
+
+
+def fetch_page(url):
+
+ if not is_allowed(url):
+ print(f'Scraping not allowed for {url}')
+ return None
+
+ try:
+
+ response = requests.get(url)
+
+ if response.status_code == 200:
+ print(f'Successfully fetched {url}')
+
+ soup = BeautifulSoup(response.content, 'html.parser')
+ return soup
+ else:
+ print(f'Failed to fetch {url} with status code {response.status_code}')
+ except Exception as e:
+ print(f'Exception occurred while fetching {url}: {e}')
+ return None
+
+
+def extract_links(soup, base_url):
+ links = []
+ if soup:
+
+ for link in soup.find_all('a', href=True):
+
+ full_url = urljoin(base_url, link['href'])
+ links.append(full_url)
+ return links
+
+
+def scrape_urls(urls, max_workers=5):
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
+
+ futures = {executor.submit(fetch_page, url): url for url in urls}
+ results = []
+ for future in futures:
+ result = future.result()
+ if result:
+ results.append(result)
+ return results
+
+
+def main():
+ start_url = 'https://example.com' # Replace with the URL you want to start scraping from
+
+ soup = fetch_page(start_url)
+ if not soup:
+ return
+
+
+ links = extract_links(soup, start_url)
+
+ pages = scrape_urls(links)
+
+
+ for page in pages:
+
+ if page:
+ title = page.find('title').get_text()
+ print(f'Page title: {title}')
+
+if __name__ == '__main__':
+ main()",88,88
+,"import numpy as np
+
+arr = np.random.randint(0, 10**6, size=10**7)
+
+# For loop
+def find_max(arr):
+ m = arr[0]
+ for num in arr:
+ if num > m:
+ m = num
+ return m
+
+print(""Max with loop:"", find_max(arr))
+print(""Max with np.max:"", np.max(arr))",1.0,DEEPAI,Write a NumPy program to generate a large NumPy array and write a function to find the maximum element using a for loop. Optimize it using NumPy's built-in functions.,PYTHON,"import numpy as np
+
+arr = np.random.randint(0, 10**6, size=10**7)
+
+# For loop
+def find_max(arr):
+ m = arr[0]
+ for num in arr:
+ if num > m:
+ m = num
+ return m
+
+print(""Max with loop:"", find_max(arr))
+print(""Max with np.max:"", np.max(arr))",14,14
+,"import time # Import the time module to measure execution time
+
+class LogExecutionTime: # Define a class for the decorator
+ def __init__(self, func): # Initialize the decorator with the function to be decorated
+ self.func = func # Store the function to be decorated
+
+ def __get__(self, instance, owner): # Define the descriptor method to handle instance methods
+ return lambda *args, **kwargs: self(instance, *args, **kwargs) # Return a lambda that passes the instance
+
+ def __call__(self, *args, **kwargs): # Make the class instance callable
+ instance = args[0] # Extract the instance from the arguments
+ start_time = time.time() # Record the start time
+ result = self.func(instance, *args[1:], **kwargs) # Call the original function with its arguments
+ end_time = time.time() # Record the end time
+ execution_time = end_time - start_time # Calculate the execution time
+ print(f""Execution time of {self.func.__name__}: {execution_time:.4f} seconds"") # Log the execution time
+ return result # Return the result of the original function call
+
+# Example usage:
+
+class ExampleClass: # Define an example class to demonstrate the decorator
+ @LogExecutionTime # Apply the decorator to the method
+ def example_method(self): # Define a method in the class
+ for _ in range(1000000): # A sample computation to add some delay
+ pass # Do nothing
+
+# Instantiate the example class and call the decorated method
+example = ExampleClass() # Create an instance of the ExampleClass
+example.example_method() # Call the decorated method to see the execution time log",0.0,W3RESOURCE,,PYTHON,"import time # Import the time module to measure execution time
+
+class LogExecutionTime: # Define a class for the decorator
+ def __init__(self, func): # Initialize the decorator with the function to be decorated
+ self.func = func # Store the function to be decorated
+
+ def __get__(self, instance, owner): # Define the descriptor method to handle instance methods
+ return lambda *args, **kwargs: self(instance, *args, **kwargs) # Return a lambda that passes the instance
+
+ def __call__(self, *args, **kwargs): # Make the class instance callable
+ instance = args[0] # Extract the instance from the arguments
+ start_time = time.time() # Record the start time
+ result = self.func(instance, *args[1:], **kwargs) # Call the original function with its arguments
+ end_time = time.time() # Record the end time
+ execution_time = end_time - start_time # Calculate the execution time
+ print(f""Execution time of {self.func.__name__}: {execution_time:.4f} seconds"") # Log the execution time
+ return result # Return the result of the original function call
+
+# Example usage:
+
+class ExampleClass: # Define an example class to demonstrate the decorator
+ @LogExecutionTime # Apply the decorator to the method
+ def example_method(self): # Define a method in the class
+ for _ in range(1000000): # A sample computation to add some delay
+ pass # Do nothing
+
+# Instantiate the example class and call the decorated method
+example = ExampleClass() # Create an instance of the ExampleClass
+example.example_method() # Call the decorated method to see the execution time log",29,29
+,"import numpy as np
+
+# Example 2D array
+arr = np.array([[3, 2, 5],
+ [1, 4, 6],
+ [2, 1, 7]])
+
+n = 1 # The column index to sort by (0-based)
+
+# Get the indices that would sort the array by column n
+sorted_indices = np.argsort(arr[:, n])
+
+# Sort the array by the specified column
+sorted_arr = arr[sorted_indices]
+
+print(""Array sorted by column"", n, "":\n"", sorted_arr)",1.0,DEEPAI,Write a NumPy program to sort an given array by the nth column.,PYTHON,"import numpy as np
+
+# Example 2D array
+arr = np.array([[3, 2, 5],
+ [1, 4, 6],
+ [2, 1, 7]])
+
+n = 1 # The column index to sort by (0-based)
+
+# Get the indices that would sort the array by column n
+sorted_indices = np.argsort(arr[:, n])
+
+# Sort the array by the specified column
+sorted_arr = arr[sorted_indices]
+
+print(""Array sorted by column"", n, "":\n"", sorted_arr)",16,16
+,"# Define a function to perform matrix multiplication of matrices A and B
+def matrix_multiplication(A, B):
+ """"""
+ Perform matrix multiplication of matrices A and B.
+
+ Args:
+ A: First matrix (list of lists).
+ B: Second matrix (list of lists).
+
+ Returns:
+ Result of matrix multiplication (list of lists).
+ """"""
+ if len(A[0]) != len(B):
+ raise ValueError(""Number of columns in A must equal number of rows in B"")
+
+ # Number of rows and columns in resulting matrix
+ num_rows_A = len(A)
+ num_cols_B = len(B[0])
+
+ # Perform matrix multiplication using list comprehension
+ result = [[sum(A[i][k] * B[k][j] for k in range(len(B))) for j in range(num_cols_B)] for i in range(num_rows_A)]
+
+ return result
+
+# Example usage:
+if __name__ == ""__main__"":
+ # Example matrices A and B
+ A = [[1, 2, 3],
+ [4, 5, 6]]
+
+ B = [[7, 8],
+ [9, 10],
+ [11, 12]]
+
+ # Print the result of matrix multiplication
+ print(matrix_multiplication(A, B))
+Output:",0.0,W3RESOURCE,,PYTHON,"# Define a function to perform matrix multiplication of matrices A and B
+def matrix_multiplication(A, B):
+ """"""
+ Perform matrix multiplication of matrices A and B.
+
+ Args:
+ A: First matrix (list of lists).
+ B: Second matrix (list of lists).
+
+ Returns:
+ Result of matrix multiplication (list of lists).
+ """"""
+ if len(A[0]) != len(B):
+ raise ValueError(""Number of columns in A must equal number of rows in B"")
+
+ # Number of rows and columns in resulting matrix
+ num_rows_A = len(A)
+ num_cols_B = len(B[0])
+
+ # Perform matrix multiplication using list comprehension
+ result = [[sum(A[i][k] * B[k][j] for k in range(len(B))) for j in range(num_cols_B)] for i in range(num_rows_A)]
+
+ return result
+
+# Example usage:
+if __name__ == ""__main__"":
+ # Example matrices A and B
+ A = [[1, 2, 3],
+ [4, 5, 6]]
+
+ B = [[7, 8],
+ [9, 10],
+ [11, 12]]
+
+ # Print the result of matrix multiplication
+ print(matrix_multiplication(A, B))
+Output:",37,37
+,"import numpy as np
+
+arr = np.array([9, 3, 5, 1, 8, 2, 7])
+n = 4 # Number of elements to sort from the beginning
+
+# Sort the first n elements
+sorted_part = np.sort(arr[:n])
+
+# Concatenate sorted part with the rest of the array
+result = np.concatenate((sorted_part, arr[n:]))
+
+print(""Array after sorting first"", n, ""elements:"", result)",1.0,DEEPAI,Write a NumPy program to sort the specified number of elements from beginning of a given array.,PYTHON,"import numpy as np
+
+arr = np.array([9, 3, 5, 1, 8, 2, 7])
+n = 4 # Number of elements to sort from the beginning
+
+# Sort the first n elements
+sorted_part = np.sort(arr[:n])
+
+# Concatenate sorted part with the rest of the array
+result = np.concatenate((sorted_part, arr[n:]))
+
+print(""Array after sorting first"", n, ""elements:"", result)",12,12
+,"# Import the queue module to use PriorityQueue
+import queue
+# Import the threading module to use threads and locks
+import threading
+
+# Define a class for a thread-safe priority queue
+class ThreadSafePriorityQueue:
+ def __init__(self):
+ # Initialize a PriorityQueue object to hold the items
+ self._queue = queue.PriorityQueue()
+ # Initialize a lock to ensure thread safety
+ self._lock = threading.Lock()
+
+ # Method to put an item into the priority queue
+ def put(self, item, priority):
+ # Acquire the lock to ensure thread safety
+ with self._lock:
+ # Put the item into the queue with its priority
+ self._queue.put((priority, item))
+
+ # Method to get an item from the priority queue
+ def get(self):
+ # Acquire the lock to ensure thread safety
+ with self._lock:
+ # Check if the queue is not empty
+ if not self._queue.empty():
+ # Get the item with the highest priority (lowest priority number)
+ priority, item = self._queue.get()
+ # Return the item
+ return item
+ else:
+ # Return None if the queue is empty
+ return None
+
+# Example usage to demonstrate the thread-safe priority queue
+if __name__ == ""__main__"":
+ # Define a producer function to add items to the queue
+ def producer(q):
+ # Add 5 items to the queue with their priority as their value
+ for i in range(5):
+ q.put(i, i)
+
+ # Define a consumer function to get items from the queue
+ def consumer(q):
+ # Continuously get items from the queue
+ while True:
+ # Get an item from the queue
+ item = q.get()
+ # If the item is None, break the loop (end of processing)
+ if item is None:
+ break
+ # Print the consumed item
+ print(""Consumed:"", item)
+
+ # Create an instance of the thread-safe priority queue
+ q = ThreadSafePriorityQueue()
+ # Create a producer thread to add items to the queue
+ producer_thread = threading.Thread(target=producer, args=(q,))
+ # Create a consumer thread to get items from the queue
+ consumer_thread = threading.Thread(target=consumer, args=(q,))
+
+ # Start the producer thread
+ producer_thread.start()
+ # Start the consumer thread
+ consumer_thread.start()
+
+ # Wait for the producer thread to finish
+ producer_thread.join()
+ # Add a sentinel value to the queue to signal the consumer to stop
+ q.put(None, None)
+ # Wait for the consumer thread to finish
+ consumer_thread.join()",0.0,W3RESOURCE,,PYTHON,"# Import the queue module to use PriorityQueue
+import queue
+# Import the threading module to use threads and locks
+import threading
+
+# Define a class for a thread-safe priority queue
+class ThreadSafePriorityQueue:
+ def __init__(self):
+ # Initialize a PriorityQueue object to hold the items
+ self._queue = queue.PriorityQueue()
+ # Initialize a lock to ensure thread safety
+ self._lock = threading.Lock()
+
+ # Method to put an item into the priority queue
+ def put(self, item, priority):
+ # Acquire the lock to ensure thread safety
+ with self._lock:
+ # Put the item into the queue with its priority
+ self._queue.put((priority, item))
+
+ # Method to get an item from the priority queue
+ def get(self):
+ # Acquire the lock to ensure thread safety
+ with self._lock:
+ # Check if the queue is not empty
+ if not self._queue.empty():
+ # Get the item with the highest priority (lowest priority number)
+ priority, item = self._queue.get()
+ # Return the item
+ return item
+ else:
+ # Return None if the queue is empty
+ return None
+
+# Example usage to demonstrate the thread-safe priority queue
+if __name__ == ""__main__"":
+ # Define a producer function to add items to the queue
+ def producer(q):
+ # Add 5 items to the queue with their priority as their value
+ for i in range(5):
+ q.put(i, i)
+
+ # Define a consumer function to get items from the queue
+ def consumer(q):
+ # Continuously get items from the queue
+ while True:
+ # Get an item from the queue
+ item = q.get()
+ # If the item is None, break the loop (end of processing)
+ if item is None:
+ break
+ # Print the consumed item
+ print(""Consumed:"", item)
+
+ # Create an instance of the thread-safe priority queue
+ q = ThreadSafePriorityQueue()
+ # Create a producer thread to add items to the queue
+ producer_thread = threading.Thread(target=producer, args=(q,))
+ # Create a consumer thread to get items from the queue
+ consumer_thread = threading.Thread(target=consumer, args=(q,))
+
+ # Start the producer thread
+ producer_thread.start()
+ # Start the consumer thread
+ consumer_thread.start()
+
+ # Wait for the producer thread to finish
+ producer_thread.join()
+ # Add a sentinel value to the queue to signal the consumer to stop
+ q.put(None, None)
+ # Wait for the consumer thread to finish
+ consumer_thread.join()",72,72
+,"import numpy as np
+
+arr = np.array([9, 3, 5, 1, 8, 2, 7])
+k = 3 # Partition index
+
+partitioned_arr = np.partition(arr, k)
+print(""Partitioned array:"", partitioned_arr)",1.0,DEEPAI,"Write a NumPy program to partition a given array in a specified position and move all the smaller elements values to the left of the partition, and the remaining values to the right, in arbitrary order (based on random choice)",PYTHON,"import numpy as np
+
+arr = np.array([9, 3, 5, 1, 8, 2, 7])
+k = 3 # Partition index
+
+partitioned_arr = np.partition(arr, k)
+print(""Partitioned array:"", partitioned_arr)",7,7
+,"import numpy as np
+
+arr = np.array([3+4j, 1+7j, 3+2j, 2+5j, 1+2j])
+# Use lexsort with imaginary part as the first key, real part as the second
+sorted_indices = np.lexsort((np.imag(arr), np.real(arr)))
+sorted_arr = arr[sorted_indices]
+
+print(""Sorted array:"", sorted_arr)",1.0,DEEPAI,"Write a NumPy program to sort a given complex array using the real part first, then the imaginary part.",PYTHON,"import numpy as np
+
+arr = np.array([3+4j, 1+7j, 3+2j, 2+5j, 1+2j])
+# Use lexsort with imaginary part as the first key, real part as the second
+sorted_indices = np.lexsort((np.imag(arr), np.real(arr)))
+sorted_arr = arr[sorted_indices]
+
+print(""Sorted array:"", sorted_arr)",8,8
+,"# Define a class representing a node in a tree
+class TreeNode:
+ def __init__(self, value):
+ self.value = value
+ self.children = [] # Initialize an empty list to store child nodes
+
+ def add_child(self, child_node):
+ self.children.append(child_node) # Add a child node to the list of children
+
+# Define a class implementing a custom iterator for tree traversal
+class TreeIterator:
+ def __init__(self, root):
+ self.stack = [root] # Initialize stack with root node
+
+ def __iter__(self):
+ return self
+
+ def __next__(self):
+ if not self.stack: # If stack is empty, no more nodes to traverse
+ raise StopIteration
+ node = self.stack.pop() # Get the top node from stack
+ for child in reversed(node.children): # Add children to stack in reverse order
+ self.stack.append(child)
+ return node.value
+
+# Example usage:
+if __name__ == ""__main__"":
+ # Create a tree with a root node and some child nodes
+ root = TreeNode(1)
+ root.add_child(TreeNode(2))
+ root.add_child(TreeNode(3))
+ root.children[0].add_child(TreeNode(4))
+ root.children[0].add_child(TreeNode(5))
+ root.children[1].add_child(TreeNode(6))
+
+ # Create a TreeIterator instance and iterate over the tree
+ tree_iterator = TreeIterator(root)
+ for value in tree_iterator:
+ print(value)",0.0,W3RESOURCE,,PYTHON,"# Define a class representing a node in a tree
+class TreeNode:
+ def __init__(self, value):
+ self.value = value
+ self.children = [] # Initialize an empty list to store child nodes
+
+ def add_child(self, child_node):
+ self.children.append(child_node) # Add a child node to the list of children
+
+# Define a class implementing a custom iterator for tree traversal
+class TreeIterator:
+ def __init__(self, root):
+ self.stack = [root] # Initialize stack with root node
+
+ def __iter__(self):
+ return self
+
+ def __next__(self):
+ if not self.stack: # If stack is empty, no more nodes to traverse
+ raise StopIteration
+ node = self.stack.pop() # Get the top node from stack
+ for child in reversed(node.children): # Add children to stack in reverse order
+ self.stack.append(child)
+ return node.value
+
+# Example usage:
+if __name__ == ""__main__"":
+ # Create a tree with a root node and some child nodes
+ root = TreeNode(1)
+ root.add_child(TreeNode(2))
+ root.add_child(TreeNode(3))
+ root.children[0].add_child(TreeNode(4))
+ root.children[0].add_child(TreeNode(5))
+ root.children[1].add_child(TreeNode(6))
+
+ # Create a TreeIterator instance and iterate over the tree
+ tree_iterator = TreeIterator(root)
+ for value in tree_iterator:
+ print(value)",39,39
+,"import numpy as np
+
+arr = np.array([4, 2, 9, 7, 1])
+indices = np.argsort(arr)
+print(""Indices of sorted elements:"", indices)",1.0,DEEPAI,Write a NumPy program to get the indices of the sorted elements of a given array.,PYTHON,"import numpy as np
+
+arr = np.array([4, 2, 9, 7, 1])
+indices = np.argsort(arr)
+print(""Indices of sorted elements:"", indices)",5,5
+,"# Import necessary modules
+from dataclasses import dataclass, field, fields, Field
+from typing import Any, Callable, List, get_type_hints
+
+# Custom exception for validation errors
+class ValidationError(Exception):
+ pass
+
+# Function to validate dataclass fields
+def validate(instance):
+ cls = instance.__class__
+ hints = get_type_hints(cls)
+ # Iterate through fields and type hints
+ for name, type_hint in hints.items():
+ value = getattr(instance, name)
+ # Check if value matches type hint
+ if not isinstance(value, type_hint):
+ raise ValidationError(f""Field '{name}' expects {type_hint}, got {type(value)}"")
+ # Check for custom validators
+ field: Field = next(f for f in fields(cls) if f.name == name)
+ if 'validators' in field.metadata:
+ for validator in field.metadata['validators']:
+ validator(instance, value)
+
+# Decorator to define a validator function
+def validator(func: Callable[[Any, Any], None]):
+ if not callable(func):
+ raise ValueError(""Validator must be callable"")
+ func._is_validator = True
+ return func
+
+# Function to define a field with validation
+def field_with_validation(*, default: Any = None, default_factory: Callable[[], Any] = None, validators: List[Callable[[Any, Any], None]] = None) -> Field:
+ # Ensure only one of default or default_factory is provided
+ if default is not None and default_factory is not None:
+ raise ValueError('cannot specify both default and default_factory')
+
+ metadata = {}
+ # Attach validators to metadata
+ if validators:
+ metadata['validators'] = validators
+
+ # Define field with appropriate parameters
+ if default is not None:
+ return field(default=default, metadata=metadata)
+ elif default_factory is not None:
+ return field(default_factory=default_factory, metadata=metadata)
+ else:
+ return field(metadata=metadata)
+
+# Dataclass representing a User with validation
+@dataclass
+class User:
+ # Define fields with validation
+ name: str
+ age: int = field_with_validation(default=0, validators=[
+ validator(lambda instance, value: value >= 0 or ValidationError(""Age must be non-negative"")),
+ validator(lambda instance, value: value <= 150 or ValidationError(""Age must be 150 or less""))
+ ])
+ email: str = field_with_validation(default="""", validators=[
+ validator(lambda instance, value: ""@"" in value or ValidationError(""Invalid email address""))
+ ])
+
+# Example usage
+try:
+ user = User(name=""Arsen"", age=30, email=""arsen@example.com"")
+ validate(user)
+ print(""User is valid"")
+except ValidationError as e:
+ print(f""Validation error: {e}"")",0.0,W3RESOURCE,,PYTHON,"# Import necessary modules
+from dataclasses import dataclass, field, fields, Field
+from typing import Any, Callable, List, get_type_hints
+
+# Custom exception for validation errors
+class ValidationError(Exception):
+ pass
+
+# Function to validate dataclass fields
+def validate(instance):
+ cls = instance.__class__
+ hints = get_type_hints(cls)
+ # Iterate through fields and type hints
+ for name, type_hint in hints.items():
+ value = getattr(instance, name)
+ # Check if value matches type hint
+ if not isinstance(value, type_hint):
+ raise ValidationError(f""Field '{name}' expects {type_hint}, got {type(value)}"")
+ # Check for custom validators
+ field: Field = next(f for f in fields(cls) if f.name == name)
+ if 'validators' in field.metadata:
+ for validator in field.metadata['validators']:
+ validator(instance, value)
+
+# Decorator to define a validator function
+def validator(func: Callable[[Any, Any], None]):
+ if not callable(func):
+ raise ValueError(""Validator must be callable"")
+ func._is_validator = True
+ return func
+
+# Function to define a field with validation
+def field_with_validation(*, default: Any = None, default_factory: Callable[[], Any] = None, validators: List[Callable[[Any, Any], None]] = None) -> Field:
+ # Ensure only one of default or default_factory is provided
+ if default is not None and default_factory is not None:
+ raise ValueError('cannot specify both default and default_factory')
+
+ metadata = {}
+ # Attach validators to metadata
+ if validators:
+ metadata['validators'] = validators
+
+ # Define field with appropriate parameters
+ if default is not None:
+ return field(default=default, metadata=metadata)
+ elif default_factory is not None:
+ return field(default_factory=default_factory, metadata=metadata)
+ else:
+ return field(metadata=metadata)
+
+# Dataclass representing a User with validation
+@dataclass
+class User:
+ # Define fields with validation
+ name: str
+ age: int = field_with_validation(default=0, validators=[
+ validator(lambda instance, value: value >= 0 or ValidationError(""Age must be non-negative"")),
+ validator(lambda instance, value: value <= 150 or ValidationError(""Age must be 150 or less""))
+ ])
+ email: str = field_with_validation(default="""", validators=[
+ validator(lambda instance, value: ""@"" in value or ValidationError(""Invalid email address""))
+ ])
+
+# Example usage
+try:
+ user = User(name=""Arsen"", age=30, email=""arsen@example.com"")
+ validate(user)
+ print(""User is valid"")
+except ValidationError as e:
+ print(f""Validation error: {e}"")",70,70
+,"import numpy as np
+
+ids = np.array([101, 102, 103, 104, 105])
+heights = np.array([165, 170.5, 168.2, 172, 160.4])
+idx = np.argsort(heights)
+print(""Indices:"", idx)
+print(""Sorted IDs:"", ids[idx])",1.0,DEEPAI,Write a NumPy program to sort the student id with increasing height of the students from given students id and height. Print the integer indices that describes the sort order by multiple columns and the sorted data,PYTHON,"import numpy as np
+
+ids = np.array([101, 102, 103, 104, 105])
+heights = np.array([165, 170.5, 168.2, 172, 160.4])
+idx = np.argsort(heights)
+print(""Indices:"", idx)
+print(""Sorted IDs:"", ids[idx])",7,7
+,"import heapq
+
+# Define a class to represent a node in the graph
+class Node:
+ def __init__(self, state, parent=None, action=None, cost=0, heuristic=0):
+ self.state = state # Current state
+ self.parent = parent # Parent node
+ self.action = action # Action taken to reach this node
+ self.cost = cost # Cost from start node to this node
+ self.heuristic = heuristic # Heuristic estimate of cost to goal
+
+ # Compare nodes based on total cost (cost + heuristic)
+ def __lt__(self, other):
+ return (self.cost + self.heuristic) < (other.cost + other.heuristic)
+
+# Define the A* search function
+def astar_search(start_state, goal_state, actions, transition_model, cost_fn, heuristic_fn):
+ # Initialize start node
+ start_node = Node(state=start_state, cost=0, heuristic=heuristic_fn(start_state))
+
+ # Priority queue for open nodes
+ open_nodes = []
+ heapq.heappush(open_nodes, start_node)
+
+ # Set of explored states
+ explored = set()
+
+ while open_nodes:
+ # Pop node with lowest total cost from priority queue
+ current_node = heapq.heappop(open_nodes)
+
+ # Check if goal state reached
+ if current_node.state == goal_state:
+ return get_solution(current_node)
+
+ # Add current state to explored set
+ explored.add(current_node.state)
+
+ # Generate successor states
+ for action in actions(current_node.state): # Fix: Call actions function with current state
+ next_state = transition_model(current_node.state, action)
+ if next_state not in explored:
+ cost = current_node.cost + cost_fn(current_node.state, action, next_state)
+ heuristic = heuristic_fn(next_state)
+ next_node = Node(state=next_state, parent=current_node, action=action, cost=cost, heuristic=heuristic)
+ heapq.heappush(open_nodes, next_node)
+
+ return None # No solution found
+
+# Function to reconstruct the solution path
+def get_solution(node):
+ path = []
+ while node:
+ path.append((node.state, node.action))
+ node = node.parent
+ return list(reversed(path))
+
+# Example usage:
+if __name__ == ""__main__"":
+ # Define example functions and parameters for pathfinding problem
+ def actions(state):
+ return ['up', 'down', 'left', 'right']
+
+ def transition_model(state, action):
+ if action == 'up':
+ return (state[0] - 1, state[1])
+ elif action == 'down':
+ return (state[0] + 1, state[1])
+ elif action == 'left':
+ return (state[0], state[1] - 1)
+ elif action == 'right':
+ return (state[0], state[1] + 1)
+
+ def cost_fn(state, action, next_state):
+ return 1
+
+ def heuristic_fn(state):
+ return abs(state[0] - goal_state[0]) + abs(state[1] - goal_state[1])
+
+ # Define start and goal states
+ start_state = (0, 0)
+ goal_state = (3, 3)
+
+ # Perform A* search
+ solution = astar_search(start_state, goal_state, actions, transition_model, cost_fn, heuristic_fn)
+ print(""Solution:"", solution)
",0.0,W3RESOURCE,,PYTHON,"import heapq
+
+# Define a class to represent a node in the graph
+class Node:
+ def __init__(self, state, parent=None, action=None, cost=0, heuristic=0):
+ self.state = state # Current state
+ self.parent = parent # Parent node
+ self.action = action # Action taken to reach this node
+ self.cost = cost # Cost from start node to this node
+ self.heuristic = heuristic # Heuristic estimate of cost to goal
+
+ # Compare nodes based on total cost (cost + heuristic)
+ def __lt__(self, other):
+ return (self.cost + self.heuristic) < (other.cost + other.heuristic)
+
+# Define the A* search function
+def astar_search(start_state, goal_state, actions, transition_model, cost_fn, heuristic_fn):
+ # Initialize start node
+ start_node = Node(state=start_state, cost=0, heuristic=heuristic_fn(start_state))
+
+ # Priority queue for open nodes
+ open_nodes = []
+ heapq.heappush(open_nodes, start_node)
+
+ # Set of explored states
+ explored = set()
+
+ while open_nodes:
+ # Pop node with lowest total cost from priority queue
+ current_node = heapq.heappop(open_nodes)
+
+ # Check if goal state reached
+ if current_node.state == goal_state:
+ return get_solution(current_node)
+
+ # Add current state to explored set
+ explored.add(current_node.state)
+
+ # Generate successor states
+ for action in actions(current_node.state): # Fix: Call actions function with current state
+ next_state = transition_model(current_node.state, action)
+ if next_state not in explored:
+ cost = current_node.cost + cost_fn(current_node.state, action, next_state)
+ heuristic = heuristic_fn(next_state)
+ next_node = Node(state=next_state, parent=current_node, action=action, cost=cost, heuristic=heuristic)
+ heapq.heappush(open_nodes, next_node)
+
+ return None # No solution found
+
+# Function to reconstruct the solution path
+def get_solution(node):
+ path = []
+ while node:
+ path.append((node.state, node.action))
+ node = node.parent
+ return list(reversed(path))
+
+# Example usage:
+if __name__ == ""__main__"":
+ # Define example functions and parameters for pathfinding problem
+ def actions(state):
+ return ['up', 'down', 'left', 'right']
+
+ def transition_model(state, action):
+ if action == 'up':
+ return (state[0] - 1, state[1])
+ elif action == 'down':
+ return (state[0] + 1, state[1])
+ elif action == 'left':
+ return (state[0], state[1] - 1)
+ elif action == 'right':
+ return (state[0], state[1] + 1)
+
+ def cost_fn(state, action, next_state):
+ return 1
+
+ def heuristic_fn(state):
+ return abs(state[0] - goal_state[0]) + abs(state[1] - goal_state[1])
+
+ # Define start and goal states
+ start_state = (0, 0)
+ goal_state = (3, 3)
+
+ # Perform A* search
+ solution = astar_search(start_state, goal_state, actions, transition_model, cost_fn, heuristic_fn)
+ print(""Solution:"", solution)",86,86
+,"import numpy as np
+
+dt = [('name', 'U20'), ('height', 'f4'), ('class', 'i4')]
+data = np.array([('Alice', 165, 2), ('Bob', 170.5, 1), ('Charlie', 168.2, 2), ('David', 172, 1), ('Eve', 160.4, 3)], dtype=dt)
+print(np.sort(data, order=['class', 'height']))",1.0,DEEPAI,"Write a NumPy program to create a structured array from given student name, height, class and their data types. Now sort by class, then height if class are equal.",PYTHON,"import numpy as np
+
+dt = [('name', 'U20'), ('height', 'f4'), ('class', 'i4')]
+data = np.array([('Alice', 165, 2), ('Bob', 170.5, 1), ('Charlie', 168.2, 2), ('David', 172, 1), ('Eve', 160.4, 3)], dtype=dt)
+print(np.sort(data, order=['class', 'height']))",5,5
+,"import os # Import the os module for interacting with the operating system
+import shutil # Import the shutil module for file operations
+import argparse # Import the argparse module for command-line argument parsing
+
+def synchronize(source_dir, destination_dir):
+ # Ensure both directories exist
+ if not os.path.exists(source_dir):
+ print(f""Source directory '{source_dir}' does not exist."")
+ return
+ if not os.path.exists(destination_dir):
+ print(f""Destination directory '{destination_dir}' does not exist."")
+ return
+
+ # Iterate over files in source directory
+ for root, dirs, files in os.walk(source_dir):
+ # Get corresponding path in destination directory
+ relative_path = os.path.relpath(root, source_dir)
+ dest_path = os.path.join(destination_dir, relative_path)
+
+ # Ensure corresponding directory structure exists in destination
+ if not os.path.exists(dest_path):
+ os.makedirs(dest_path)
+
+ # Copy files from source to destination
+ for file in files:
+ source_file = os.path.join(root, file)
+ dest_file = os.path.join(dest_path, file)
+ shutil.copy2(source_file, dest_file)
+ print(f""Copied: {source_file} -> {dest_file}"")
+
+ print(""Synchronization complete."")
+
+if __name__ == ""__main__"":
+ # Create argument parser
+ parser = argparse.ArgumentParser(description=""Synchronize files between two directories."")
+ # Add argument for source directory
+ parser.add_argument(""source"", help=""Source directory"")
+ # Add argument for destination directory
+ parser.add_argument(""destination"", help=""Destination directory"")
+ # Parse the command-line arguments
+ args = parser.parse_args()
+
+ # Call the synchronize function with the provided arguments
+ synchronize(args.source, args.destination)",0.0,W3RESOURCE,,PYTHON,"import os # Import the os module for interacting with the operating system
+import shutil # Import the shutil module for file operations
+import argparse # Import the argparse module for command-line argument parsing
+
+def synchronize(source_dir, destination_dir):
+ # Ensure both directories exist
+ if not os.path.exists(source_dir):
+ print(f""Source directory '{source_dir}' does not exist."")
+ return
+ if not os.path.exists(destination_dir):
+ print(f""Destination directory '{destination_dir}' does not exist."")
+ return
+
+ # Iterate over files in source directory
+ for root, dirs, files in os.walk(source_dir):
+ # Get corresponding path in destination directory
+ relative_path = os.path.relpath(root, source_dir)
+ dest_path = os.path.join(destination_dir, relative_path)
+
+ # Ensure corresponding directory structure exists in destination
+ if not os.path.exists(dest_path):
+ os.makedirs(dest_path)
+
+ # Copy files from source to destination
+ for file in files:
+ source_file = os.path.join(root, file)
+ dest_file = os.path.join(dest_path, file)
+ shutil.copy2(source_file, dest_file)
+ print(f""Copied: {source_file} -> {dest_file}"")
+
+ print(""Synchronization complete."")
+
+if __name__ == ""__main__"":
+ # Create argument parser
+ parser = argparse.ArgumentParser(description=""Synchronize files between two directories."")
+ # Add argument for source directory
+ parser.add_argument(""source"", help=""Source directory"")
+ # Add argument for destination directory
+ parser.add_argument(""destination"", help=""Destination directory"")
+ # Parse the command-line arguments
+ args = parser.parse_args()
+
+ # Call the synchronize function with the provided arguments
+ synchronize(args.source, args.destination)",44,44
+,"import json
+
+# Define the Address and Person classes
+class Address:
+ def __init__(self, street, city, state, zip_code):
+ self.street = street
+ self.city = city
+ self.state = state
+ self.zip_code = zip_code
+
+class Person:
+ def __init__(self, name, age, address):
+ self.name = name
+ self.age = age
+ self.address = address
+
+# Custom JSON Encoder
+class ComplexEncoder(json.JSONEncoder):
+ def default(self, obj):
+ if isinstance(obj, Address):
+ return {
+ '__type__': 'Address',
+ 'street': obj.street,
+ 'city': obj.city,
+ 'state': obj.state,
+ 'zip_code': obj.zip_code
+ }
+ elif isinstance(obj, Person):
+ return {
+ '__type__': 'Person',
+ 'name': obj.name,
+ 'age': obj.age,
+ 'address': obj.address
+ }
+ return json.JSONEncoder.default(self, obj)
+
+# Custom JSON Decoder
+def complex_decoder(dct):
+ if '__type__' in dct:
+ if dct['__type__'] == 'Address':
+ return Address(dct['street'], dct['city'], dct['state'], dct['zip_code'])
+ elif dct['__type__'] == 'Person':
+ address = dct['address']
+ if isinstance(address, dict):
+ address = complex_decoder(address)
+ return Person(dct['name'], dct['age'], address)
+ return dct
+
+# Example usage
+address = Address(""123 ABCD St."", ""Paris"", ""CA"", ""12345"")
+person = Person(""Roslindis Bronwen"", 30, address)
+
+# Serialize to JSON
+person_json = json.dumps(person, cls=ComplexEncoder)
+print(""Serialized JSON:"", person_json)
+
+# Deserialize from JSON
+decoded_person = json.loads(person_json, object_hook=complex_decoder)
+print(""\nDecoded Object:"", decoded_person.name, decoded_person.age, decoded_person.address.street)",0.0,W3RESOURCE,,PYTHON,"import json
+
+# Define the Address and Person classes
+class Address:
+ def __init__(self, street, city, state, zip_code):
+ self.street = street
+ self.city = city
+ self.state = state
+ self.zip_code = zip_code
+
+class Person:
+ def __init__(self, name, age, address):
+ self.name = name
+ self.age = age
+ self.address = address
+
+# Custom JSON Encoder
+class ComplexEncoder(json.JSONEncoder):
+ def default(self, obj):
+ if isinstance(obj, Address):
+ return {
+ '__type__': 'Address',
+ 'street': obj.street,
+ 'city': obj.city,
+ 'state': obj.state,
+ 'zip_code': obj.zip_code
+ }
+ elif isinstance(obj, Person):
+ return {
+ '__type__': 'Person',
+ 'name': obj.name,
+ 'age': obj.age,
+ 'address': obj.address
+ }
+ return json.JSONEncoder.default(self, obj)
+
+# Custom JSON Decoder
+def complex_decoder(dct):
+ if '__type__' in dct:
+ if dct['__type__'] == 'Address':
+ return Address(dct['street'], dct['city'], dct['state'], dct['zip_code'])
+ elif dct['__type__'] == 'Person':
+ address = dct['address']
+ if isinstance(address, dict):
+ address = complex_decoder(address)
+ return Person(dct['name'], dct['age'], address)
+ return dct
+
+# Example usage
+address = Address(""123 ABCD St."", ""Paris"", ""CA"", ""12345"")
+person = Person(""Roslindis Bronwen"", 30, address)
+
+# Serialize to JSON
+person_json = json.dumps(person, cls=ComplexEncoder)
+print(""Serialized JSON:"", person_json)
+
+# Deserialize from JSON
+decoded_person = json.loads(person_json, object_hook=complex_decoder)
+print(""\nDecoded Object:"", decoded_person.name, decoded_person.age, decoded_person.address.street)",59,59
+,"import hashlib
+
+class BloomFilter:
+ def __init__(self, size, hash_count):
+ self.size = size # Size of the bit array
+ self.hash_count = hash_count # Number of hash functions
+ self.bit_array = [0] * size # Bit array to store elements
+
+ def _hashes(self, item):
+ """"""Generate hash_count hashes for the item using different hash functions.""""""
+ hashes = []
+ for i in range(self.hash_count):
+ # Create a unique hash for each iteration
+ hash_result = int(hashlib.md5((str(item) + str(i)).encode()).hexdigest(), 16) % self.size
+ hashes.append(hash_result)
+ return hashes
+
+ def add(self, item):
+ """"""Add an item to the Bloom filter.""""""
+ hashes = self._hashes(item)
+ for hash_value in hashes:
+ self.bit_array[hash_value] = 1
+
+ def check(self, item):
+ """"""Check if an item is possibly in the Bloom filter.""""""
+ hashes = self._hashes(item)
+ return all(self.bit_array[hash_value] == 1 for hash_value in hashes)
+
+# Example usage
+size = 1000 # Size of the bit array
+hash_count = 10 # Number of hash functions
+
+bloom_filter = BloomFilter(size, hash_count)
+
+# Add items to the Bloom filter
+bloom_filter.add(""Red"")
+bloom_filter.add(""Green"")
+bloom_filter.add(""Blue"")
+bloom_filter.add(""Orange"")
+
+# Check for item membership
+print(""Red in filter:"", bloom_filter.check(""Red"")) # Should be True
+print(""Green in filter:"", bloom_filter.check(""Green"")) # Should be True
+print(""Orange in filter:"", bloom_filter.check(""Orange"")) # Should be True
+print(""Black in filter:"", bloom_filter.check(""Black"")) # Should be False (most likely)",0.0,W3RESOURCE,,PYTHON,"import hashlib
+
+class BloomFilter:
+ def __init__(self, size, hash_count):
+ self.size = size # Size of the bit array
+ self.hash_count = hash_count # Number of hash functions
+ self.bit_array = [0] * size # Bit array to store elements
+
+ def _hashes(self, item):
+ """"""Generate hash_count hashes for the item using different hash functions.""""""
+ hashes = []
+ for i in range(self.hash_count):
+ # Create a unique hash for each iteration
+ hash_result = int(hashlib.md5((str(item) + str(i)).encode()).hexdigest(), 16) % self.size
+ hashes.append(hash_result)
+ return hashes
+
+ def add(self, item):
+ """"""Add an item to the Bloom filter.""""""
+ hashes = self._hashes(item)
+ for hash_value in hashes:
+ self.bit_array[hash_value] = 1
+
+ def check(self, item):
+ """"""Check if an item is possibly in the Bloom filter.""""""
+ hashes = self._hashes(item)
+ return all(self.bit_array[hash_value] == 1 for hash_value in hashes)
+
+# Example usage
+size = 1000 # Size of the bit array
+hash_count = 10 # Number of hash functions
+
+bloom_filter = BloomFilter(size, hash_count)
+
+# Add items to the Bloom filter
+bloom_filter.add(""Red"")
+bloom_filter.add(""Green"")
+bloom_filter.add(""Blue"")
+bloom_filter.add(""Orange"")
+
+# Check for item membership
+print(""Red in filter:"", bloom_filter.check(""Red"")) # Should be True
+print(""Green in filter:"", bloom_filter.check(""Green"")) # Should be True
+print(""Orange in filter:"", bloom_filter.check(""Orange"")) # Should be True
+print(""Black in filter:"", bloom_filter.check(""Black"")) # Should be False (most likely)",45,45
+,"import numpy as np
+
+x = np.arange(7)
+print(""Original:"", x)
+print(""Powers (element-wise ^3):"", np.power(x, 3))
",1.0,PERPLEXITY,Write a NumPy program to get the powers of an array values element-wise.,PYTHON,"import numpy as np
+
+x = np.arange(7)
+print(""Original:"", x)
+print(""Powers (element-wise ^3):"", np.power(x, 3))",5,5
+,"# Import the asyncio library for asynchronous programming
+import asyncio
+
+# Import nest_asyncio to handle nested event loops
+import nest_asyncio
+
+# Apply nest_asyncio to allow nested event loops
+nest_asyncio.apply()
+
+# Define the TaskScheduler class
+class TaskScheduler:
+ def __init__(self):
+ # Initialize an empty list to store tasks
+ self.tasks = []
+
+ def schedule(self, coro, *args):
+ """"""Schedule a coroutine with given arguments.""""""
+ # Append the coroutine with its arguments to the tasks list
+ self.tasks.append(coro(*args))
+
+ async def run(self):
+ """"""Run all scheduled tasks concurrently.""""""
+ # Use asyncio.gather to run all tasks concurrently
+ await asyncio.gather(*self.tasks)
+
+# Define an example coroutine that simulates a task
+async def example_task(name, duration):
+ """"""An example coroutine that simulates a task.""""""
+ # Print a message when the task starts
+ print(f""Task {name} started, will take {duration} seconds."")
+ # Simulate a delay using asyncio.sleep
+ await asyncio.sleep(duration)
+ # Print a message when the task finishes
+ print(f""Task {name} finished."")
+
+# Define the main coroutine for example usage
+async def main():
+ # Create an instance of TaskScheduler
+ scheduler = TaskScheduler()
+
+ # Schedule example tasks with different durations
+ scheduler.schedule(example_task, ""A"", 2)
+ scheduler.schedule(example_task, ""B"", 3)
+ scheduler.schedule(example_task, ""C"", 1)
+
+ # Run all scheduled tasks concurrently
+ await scheduler.run()
+
+# Run the main function using asyncio's event loop
+asyncio.run(main())",0.0,W3RESOURCE,,PYTHON,"# Import the asyncio library for asynchronous programming
+import asyncio
+
+# Import nest_asyncio to handle nested event loops
+import nest_asyncio
+
+# Apply nest_asyncio to allow nested event loops
+nest_asyncio.apply()
+
+# Define the TaskScheduler class
+class TaskScheduler:
+ def __init__(self):
+ # Initialize an empty list to store tasks
+ self.tasks = []
+
+ def schedule(self, coro, *args):
+ """"""Schedule a coroutine with given arguments.""""""
+ # Append the coroutine with its arguments to the tasks list
+ self.tasks.append(coro(*args))
+
+ async def run(self):
+ """"""Run all scheduled tasks concurrently.""""""
+ # Use asyncio.gather to run all tasks concurrently
+ await asyncio.gather(*self.tasks)
+
+# Define an example coroutine that simulates a task
+async def example_task(name, duration):
+ """"""An example coroutine that simulates a task.""""""
+ # Print a message when the task starts
+ print(f""Task {name} started, will take {duration} seconds."")
+ # Simulate a delay using asyncio.sleep
+ await asyncio.sleep(duration)
+ # Print a message when the task finishes
+ print(f""Task {name} finished."")
+
+# Define the main coroutine for example usage
+async def main():
+ # Create an instance of TaskScheduler
+ scheduler = TaskScheduler()
+
+ # Schedule example tasks with different durations
+ scheduler.schedule(example_task, ""A"", 2)
+ scheduler.schedule(example_task, ""B"", 3)
+ scheduler.schedule(example_task, ""C"", 1)
+
+ # Run all scheduled tasks concurrently
+ await scheduler.run()
+
+# Run the main function using asyncio's event loop
+asyncio.run(main())",50,50
+,"import numpy as np
+
+x = np.arange(10)
+print(""Original:"", x)
+print(""Floor division by 3:"", np.floor_divide(x, 3))
",1.0,PERPLEXITY,Write a NumPy program to get the largest integer smaller or equal to the division of the inputs.,PYTHON,"import numpy as np
+
+x = np.arange(10)
+print(""Original:"", x)
+print(""Floor division by 3:"", np.floor_divide(x, 3))",5,5
+,"from collections import OrderedDict
+
+# Define a class for the caching system with LRU eviction policy
+class LRUCache:
+ # Initialize the cache with a maximum capacity
+ def __init__(self, capacity):
+ self.capacity = capacity # Set the maximum capacity
+ self.cache = OrderedDict() # Use OrderedDict for O(1) access and ordering
+
+ # Get the value associated with the key from the cache
+ def get(self, key):
+ # If the key is not in the cache, return -1
+ if key not in self.cache:
+ return -1
+ # Move the accessed key to the end to indicate recent use
+ self.cache.move_to_end(key)
+ # Return the value associated with the key
+ return self.cache[key]
+
+ # Put a key-value pair into the cache
+ def put(self, key, value):
+ # If the key is already in the cache, update its value and move it to the end
+ if key in self.cache:
+ self.cache[key] = value
+ self.cache.move_to_end(key)
+ else:
+ # If the cache is at capacity, remove the least recently used item
+ if len(self.cache) == self.capacity:
+ self.cache.popitem(last=False) # Remove the first item (least recently used)
+ # Add the new key-value pair to the cache
+ self.cache[key] = value
+
+# Example usage
+if __name__ == ""__main__"":
+ # Create a cache with a capacity of 2
+ cache = LRUCache(2)
+ # Put key-value pairs into the cache
+ cache.put(1, 1)
+ cache.put(2, 2)
+ # Retrieve and print the value associated with key 1 (should be 1)
+ print(cache.get(1))
+ # Put a new key-value pair into the cache (evicting key 2)
+ cache.put(3, 3)
+ # Retrieve and print the value associated with key 2 (should be -1, as it was evicted)
+ print(cache.get(2))
+ # Retrieve and print the value associated with key 3 (should be 3)
+ print(cache.get(3))",0.0,W3RESOURCE,,PYTHON,"from collections import OrderedDict
+
+# Define a class for the caching system with LRU eviction policy
+class LRUCache:
+ # Initialize the cache with a maximum capacity
+ def __init__(self, capacity):
+ self.capacity = capacity # Set the maximum capacity
+ self.cache = OrderedDict() # Use OrderedDict for O(1) access and ordering
+
+ # Get the value associated with the key from the cache
+ def get(self, key):
+ # If the key is not in the cache, return -1
+ if key not in self.cache:
+ return -1
+ # Move the accessed key to the end to indicate recent use
+ self.cache.move_to_end(key)
+ # Return the value associated with the key
+ return self.cache[key]
+
+ # Put a key-value pair into the cache
+ def put(self, key, value):
+ # If the key is already in the cache, update its value and move it to the end
+ if key in self.cache:
+ self.cache[key] = value
+ self.cache.move_to_end(key)
+ else:
+ # If the cache is at capacity, remove the least recently used item
+ if len(self.cache) == self.capacity:
+ self.cache.popitem(last=False) # Remove the first item (least recently used)
+ # Add the new key-value pair to the cache
+ self.cache[key] = value
+
+# Example usage
+if __name__ == ""__main__"":
+ # Create a cache with a capacity of 2
+ cache = LRUCache(2)
+ # Put key-value pairs into the cache
+ cache.put(1, 1)
+ cache.put(2, 2)
+ # Retrieve and print the value associated with key 1 (should be 1)
+ print(cache.get(1))
+ # Put a new key-value pair into the cache (evicting key 2)
+ cache.put(3, 3)
+ # Retrieve and print the value associated with key 2 (should be -1, as it was evicted)
+ print(cache.get(2))
+ # Retrieve and print the value associated with key 3 (should be 3)
+ print(cache.get(3))",47,47
+,"import numpy as np
+
+x = np.arange(10)
+print(""Original:"", x)
+print(""True division by 3:"", x / 3)
",1.0,PERPLEXITY,"
+Write a NumPy program to get true division of the element-wise array inputs.",PYTHON,"import numpy as np
+
+x = np.arange(10)
+print(""Original:"", x)
+print(""True division by 3:"", x / 3)",5,5
+,"# Import the Abstract Syntax Tree (AST) module
+import ast
+
+# Import the math module for mathematical functions and constants
+import math
+
+# Define a class for evaluating mathematical expressions
+class MathExpressionEvaluator:
+ def __init__(self):
+ pass
+
+ # Method to evaluate mathematical expressions
+ def evaluate(self, expression):
+ try:
+ # Parse the expression into an Abstract Syntax Tree (AST)
+ parsed_expression = ast.parse(expression, mode='eval')
+
+ # Define the allowed names (functions and constants) for evaluation
+ allowed_names = {
+ 'sin': math.sin,
+ 'cos': math.cos,
+ 'tan': math.tan,
+ 'log': math.log,
+ 'sqrt': math.sqrt,
+ **vars(math) # Include all functions and constants from the math module
+ }
+
+ # Evaluate the AST using a custom namespace that includes the allowed names
+ result = eval(compile(parsed_expression, filename='', mode='eval'), {}, allowed_names)
+ return result
+ except SyntaxError:
+ print(""Invalid expression syntax."")
+ return None
+ except Exception as e:
+ print(""Error:"", e)
+ return None
+
+# Example usage
+if __name__ == ""__main__"":
+ evaluator = MathExpressionEvaluator()
+
+ # Evaluate mathematical expressions
+ print(""Evaluation Results:"")
+ print(""10 + 12 * 4 ="", evaluator.evaluate(""10 + 12 * 4""))
+ print(""(12 + 13) * 4 ="", evaluator.evaluate(""(12 + 13) * 4""))
+ print(""sin(0.5) ="", evaluator.evaluate(""sin(0.5)""))
+ print(""log(10) ="", evaluator.evaluate(""log(10)""))",0.0,W3RESOURCE,,PYTHON,"# Import the Abstract Syntax Tree (AST) module
+import ast
+
+# Import the math module for mathematical functions and constants
+import math
+
+# Define a class for evaluating mathematical expressions
+class MathExpressionEvaluator:
+ def __init__(self):
+ pass
+
+ # Method to evaluate mathematical expressions
+ def evaluate(self, expression):
+ try:
+ # Parse the expression into an Abstract Syntax Tree (AST)
+ parsed_expression = ast.parse(expression, mode='eval')
+
+ # Define the allowed names (functions and constants) for evaluation
+ allowed_names = {
+ 'sin': math.sin,
+ 'cos': math.cos,
+ 'tan': math.tan,
+ 'log': math.log,
+ 'sqrt': math.sqrt,
+ **vars(math) # Include all functions and constants from the math module
+ }
+
+ # Evaluate the AST using a custom namespace that includes the allowed names
+ result = eval(compile(parsed_expression, filename='', mode='eval'), {}, allowed_names)
+ return result
+ except SyntaxError:
+ print(""Invalid expression syntax."")
+ return None
+ except Exception as e:
+ print(""Error:"", e)
+ return None
+
+# Example usage
+if __name__ == ""__main__"":
+ evaluator = MathExpressionEvaluator()
+
+ # Evaluate mathematical expressions
+ print(""Evaluation Results:"")
+ print(""10 + 12 * 4 ="", evaluator.evaluate(""10 + 12 * 4""))
+ print(""(12 + 13) * 4 ="", evaluator.evaluate(""(12 + 13) * 4""))
+ print(""sin(0.5) ="", evaluator.evaluate(""sin(0.5)""))
+ print(""log(10) ="", evaluator.evaluate(""log(10)""))",47,47
+,"import numpy as np
+
+print(np.logaddexp(np.log(1e-50), np.log(2.5e-50)))
+print(np.logaddexp2(np.log(1e-50), np.log(2.5e-50)))
",1.0,PERPLEXITY,"Write a NumPy program to compute logarithm of the sum of exponentiations of the inputs, sum of exponentiations of the inputs in base-2.",PYTHON,"import numpy as np
+
+print(np.logaddexp(np.log(1e-50), np.log(2.5e-50)))
+print(np.logaddexp2(np.log(1e-50), np.log(2.5e-50)))",4,4
+,"# Import necessary modules
+import json
+import threading
+import time
+import signal
+import os
+from watchdog.observers import Observer
+from watchdog.events import FileSystemEventHandler
+
+# Define the ConfigManager class to manage configurations
+class ConfigManager:
+ def __init__(self, config_file):
+ # Initialize with the configuration file path
+ self.config_file = config_file
+ # Initialize the configuration data dictionary
+ self.config_data = {}
+ # Create a lock for thread-safe operations
+ self.lock = threading.Lock()
+ # Load the initial configuration
+ self.load_config()
+
+ def load_config(self):
+ # Load the configuration file in a thread-safe manner
+ with self.lock:
+ with open(self.config_file, 'r') as f:
+ self.config_data = json.load(f)
+ # Print the loaded configuration for debugging
+ print(""Configuration reloaded:"", self.config_data)
+
+ def get_config(self):
+ # Get the current configuration in a thread-safe manner
+ with self.lock:
+ return self.config_data
+
+ def start_watching(self):
+ # Create a file system event handler for the configuration file
+ event_handler = ConfigFileHandler(self, self.config_file)
+ # Create an observer to monitor file system changes
+ observer = Observer()
+ # Schedule the observer to watch the current directory for changes
+ observer.schedule(event_handler, path='.', recursive=False)
+ # Start the observer
+ observer.start()
+ print(""Started watching for configuration changes..."")
+
+ try:
+ # Continuously check if the stop event is set
+ while not stop_event.is_set():
+ time.sleep(1)
+ except KeyboardInterrupt:
+ pass
+ finally:
+ # Stop the observer when shutting down
+ print(""Stopping observer..."")
+ observer.stop()
+ observer.join()
+ print(""Observer stopped."")
+
+# Define the file system event handler class for configuration file changes
+class ConfigFileHandler(FileSystemEventHandler):
+ def __init__(self, config_manager, config_file):
+ # Initialize with the config manager and the configuration file path
+ self.config_manager = config_manager
+ self.config_file = os.path.abspath(config_file)
+
+ def on_modified(self, event):
+ # Check if the modified file is the configuration file
+ if os.path.abspath(event.src_path) == self.config_file:
+ # Print the modification event for debugging
+ print(f""Configuration file {event.src_path} changed, reloading..."")
+ # Reload the configuration
+ self.config_manager.load_config()
+
+# Define a signal handler for SIGINT to handle graceful shutdown
+def handle_sigint(signal, frame):
+ global stop_event
+ print(""Shutting down..."")
+ # Set the stop event to terminate the program
+ stop_event.set()
+
+# Example usage
+if __name__ == ""__main__"":
+ # Define the path to the configuration file
+ config_file = 'config.json'
+ # Create an instance of ConfigManager with the configuration file
+ config_manager = ConfigManager(config_file)
+
+ # Create an event to signal stopping
+ stop_event = threading.Event()
+ # Register the signal handler for SIGINT
+ signal.signal(signal.SIGINT, handle_sigint)
+
+ # Start watching for configuration changes in a separate thread
+ watcher_thread = threading.Thread(target=config_manager.start_watching)
+ watcher_thread.start()
+
+ # Simulate application usage
+ try:
+ while not stop_event.is_set():
+ # Get and print the current configuration periodically
+ config = config_manager.get_config()
+ print(""Current configuration:"", config)
+ time.sleep(5)
+ except KeyboardInterrupt:
+ pass
+
+ # Signal the watcher thread to stop
+ stop_event.set()
+ # Wait for the watcher thread to finish
+ watcher_thread.join()
+ print(""Program terminated."")",0.0,W3RESOURCE,,PYTHON,"# Import necessary modules
+import json
+import threading
+import time
+import signal
+import os
+from watchdog.observers import Observer
+from watchdog.events import FileSystemEventHandler
+
+# Define the ConfigManager class to manage configurations
+class ConfigManager:
+ def __init__(self, config_file):
+ # Initialize with the configuration file path
+ self.config_file = config_file
+ # Initialize the configuration data dictionary
+ self.config_data = {}
+ # Create a lock for thread-safe operations
+ self.lock = threading.Lock()
+ # Load the initial configuration
+ self.load_config()
+
+ def load_config(self):
+ # Load the configuration file in a thread-safe manner
+ with self.lock:
+ with open(self.config_file, 'r') as f:
+ self.config_data = json.load(f)
+ # Print the loaded configuration for debugging
+ print(""Configuration reloaded:"", self.config_data)
+
+ def get_config(self):
+ # Get the current configuration in a thread-safe manner
+ with self.lock:
+ return self.config_data
+
+ def start_watching(self):
+ # Create a file system event handler for the configuration file
+ event_handler = ConfigFileHandler(self, self.config_file)
+ # Create an observer to monitor file system changes
+ observer = Observer()
+ # Schedule the observer to watch the current directory for changes
+ observer.schedule(event_handler, path='.', recursive=False)
+ # Start the observer
+ observer.start()
+ print(""Started watching for configuration changes..."")
+
+ try:
+ # Continuously check if the stop event is set
+ while not stop_event.is_set():
+ time.sleep(1)
+ except KeyboardInterrupt:
+... truncated ...
+ # Initialize with the config manager and the configuration file path
+ self.config_manager = config_manager
+ self.config_file = os.path.abspath(config_file)
+
+ def on_modified(self, event):
+ # Check if the modified file is the configuration file
+ if os.path.abspath(event.src_path) == self.config_file:
+ # Print the modification event for debugging
+ print(f""Configuration file {event.src_path} changed, reloading..."")
+ # Reload the configuration
+ self.config_manager.load_config()
+
+# Define a signal handler for SIGINT to handle graceful shutdown
+def handle_sigint(signal, frame):
+ global stop_event
+ print(""Shutting down..."")
+ # Set the stop event to terminate the program
+ stop_event.set()
+
+# Example usage
+if __name__ == ""__main__"":
+ # Define the path to the configuration file
+ config_file = 'config.json'
+ # Create an instance of ConfigManager with the configuration file
+ config_manager = ConfigManager(config_file)
+
+ # Create an event to signal stopping
+ stop_event = threading.Event()
+ # Register the signal handler for SIGINT
+ signal.signal(signal.SIGINT, handle_sigint)
+
+ # Start watching for configuration changes in a separate thread
+ watcher_thread = threading.Thread(target=config_manager.start_watching)
+ watcher_thread.start()
+
+ # Simulate application usage
+ try:
+ while not stop_event.is_set():
+ # Get and print the current configuration periodically
+ config = config_manager.get_config()
+ print(""Current configuration:"", config)
+ time.sleep(5)
+ except KeyboardInterrupt:
+ pass
+
+ # Signal the watcher thread to stop
+ stop_event.set()
+ # Wait for the watcher thread to finish
+ watcher_thread.join()
+ print(""Program terminated."")",111,101
+,"import numpy as np
+
+print(""Add:"", np.add(1.0, 4.0))
+print(""Subtract:"", np.subtract(1.0, 4.0))
+print(""Multiply:"", np.multiply(1.0, 4.0))
+print(""Divide:"", np.divide(1.0, 4.0))
",1.0,PERPLEXITY,"Write a NumPy program to add, subtract, multiply, divide arguments element-wise.",PYTHON,"import numpy as np
+
+print(""Add:"", np.add(1.0, 4.0))
+print(""Subtract:"", np.subtract(1.0, 4.0))
+print(""Multiply:"", np.multiply(1.0, 4.0))
+print(""Divide:"", np.divide(1.0, 4.0))",6,6
+,"# Import the random module for generating random numbers
+import random
+# Import the numpy module for numerical operations
+import numpy as np
+
+# Problem definition: Example function to optimize (e.g., Rastrigin function)
+def rastrigin(x):
+ # Define the constant A
+ A = 10
+ # Compute the Rastrigin function value for the input x
+ return A * len(x) + sum([(xi**2 - A * np.cos(2 * np.pi * xi)) for xi in x])
+
+# GA Parameters
+# Set the population size
+population_size = 100
+# Set the genome length (number of genes in a chromosome)
+genome_length = 10
+# Set the crossover rate
+crossover_rate = 0.8
+# Set the mutation rate
+mutation_rate = 0.01
+# Set the number of generations
+num_generations = 100
+# Define the bounds for the gene values
+bounds = [-5.12, 5.12]
+
+# Initialization
+def initialize_population(pop_size, genome_len, bounds):
+ # Generate a population of random individuals within the given bounds
+ return [np.random.uniform(bounds[0], bounds[1], genome_len) for _ in range(pop_size)]
+
+# Fitness function
+def evaluate_fitness(population):
+ # Evaluate the fitness of each individual in the population using the Rastrigin function
+ return [rastrigin(individual) for individual in population]
+
+# Selection (Tournament Selection)
+def tournament_selection(population, fitness, tournament_size=3):
+ # Initialize the list of selected individuals
+ selected = []
+ # Select individuals based on tournament selection
+ for _ in range(len(population)):
+ # Choose random aspirants for the tournament
+ aspirants = [random.randint(0, len(population) - 1) for _ in range(tournament_size)]
+ # Select the individual with the best fitness among the aspirants
+ selected.append(min(aspirants, key=lambda aspirant: fitness[aspirant]))
+ # Return the selected individuals
+ return [population[i] for i in selected]
+
+# Crossover (Single Point Crossover)
+def single_point_crossover(parent1, parent2):
+ # Perform crossover with a given probability
+ if random.random() < crossover_rate:
+ # Choose a random crossover point
+ point = random.randint(1, len(parent1) - 1)
+ # Create children by combining the parents at the crossover point
+ child1 = np.concatenate([parent1[:point], parent2[point:]])
+ child2 = np.concatenate([parent2[:point], parent1[point:]])
+ # Return the children
+ return child1, child2
+ # If no crossover, return the parents as is
+ return parent1, parent2
+
+# Mutation
+def mutate(individual, mutation_rate, bounds):
+ # Mutate each gene with a given probability
+ for i in range(len(individual)):
+ if random.random() < mutation_rate:
+ # Replace the gene with a random value within the bounds
+ individual[i] = np.random.uniform(bounds[0], bounds[1])
+ # Return the mutated individual
+ return individual
+
+# Genetic Algorithm
+def genetic_algorithm():
+ # Initialize the population
+ population = initialize_population(population_size, genome_length, bounds)
+
+ # Iterate over the number of generations
+ for generation in range(num_generations):
+ # Evaluate the fitness of the population
+ fitness = evaluate_fitness(population)
+
+ # Selection
+ # Select individuals based on their fitness
+ selected_population = tournament_selection(population, fitness)
+
+ # Crossover
+ # Create the next generation through crossover
+ next_population = []
+ for i in range(0, len(selected_population), 2):
+ parent1 = selected_population[i]
+ parent2 = selected_population[min(i + 1, len(selected_population) - 1)]
+ child1, child2 = single_point_crossover(parent1, parent2)
+ next_population.extend([child1, child2])
+
+ # Mutation
+ # Mutate the individuals in the next generation
+ population = [mutate(individual, mutation_rate, bounds) for individual in next_population]
+
+ # Evaluation
+ # Re-evaluate the fitness of the new population
+ fitness = evaluate_fitness(population)
+ # Find the best fitness and corresponding individual
+ best_fitness = min(fitness)
+ best_individual = population[fitness.index(best_fitness)]
+
+ # Print the best fitness of the current generation
+ print(f'Generation {generation + 1}: Best Fitness = {best_fitness}')
+
+ # Return the best individual found
+ return best_individual
+
+# Uncomment the line below to run the genetic algorithm
+best_solution = genetic_algorithm()
+# Print the best solution found
+print(""Best solution found:"", best_solution)",0.0,W3RESOURCE,,PYTHON,"# Import the random module for generating random numbers
+import random
+# Import the numpy module for numerical operations
+import numpy as np
+
+# Problem definition: Example function to optimize (e.g., Rastrigin function)
+def rastrigin(x):
+ # Define the constant A
+ A = 10
+ # Compute the Rastrigin function value for the input x
+ return A * len(x) + sum([(xi**2 - A * np.cos(2 * np.pi * xi)) for xi in x])
+
+# GA Parameters
+# Set the population size
+population_size = 100
+# Set the genome length (number of genes in a chromosome)
+genome_length = 10
+# Set the crossover rate
+crossover_rate = 0.8
+# Set the mutation rate
+mutation_rate = 0.01
+# Set the number of generations
+num_generations = 100
+# Define the bounds for the gene values
+bounds = [-5.12, 5.12]
+
+# Initialization
+def initialize_population(pop_size, genome_len, bounds):
+ # Generate a population of random individuals within the given bounds
+ return [np.random.uniform(bounds[0], bounds[1], genome_len) for _ in range(pop_size)]
+
+# Fitness function
+def evaluate_fitness(population):
+ # Evaluate the fitness of each individual in the population using the Rastrigin function
+ return [rastrigin(individual) for individual in population]
+
+# Selection (Tournament Selection)
+def tournament_selection(population, fitness, tournament_size=3):
+ # Initialize the list of selected individuals
+ selected = []
+ # Select individuals based on tournament selection
+ for _ in range(len(population)):
+ # Choose random aspirants for the tournament
+ aspirants = [random.randint(0, len(population) - 1) for _ in range(tournament_size)]
+ # Select the individual with the best fitness among the aspirants
+ selected.append(min(aspirants, key=lambda aspirant: fitness[aspirant]))
+ # Return the selected individuals
+ return [population[i] for i in selected]
+
+# Crossover (Single Point Crossover)
+... truncated ...
+ if random.random() < mutation_rate:
+ # Replace the gene with a random value within the bounds
+ individual[i] = np.random.uniform(bounds[0], bounds[1])
+ # Return the mutated individual
+ return individual
+
+# Genetic Algorithm
+def genetic_algorithm():
+ # Initialize the population
+ population = initialize_population(population_size, genome_length, bounds)
+
+ # Iterate over the number of generations
+ for generation in range(num_generations):
+ # Evaluate the fitness of the population
+ fitness = evaluate_fitness(population)
+
+ # Selection
+ # Select individuals based on their fitness
+ selected_population = tournament_selection(population, fitness)
+
+ # Crossover
+ # Create the next generation through crossover
+ next_population = []
+ for i in range(0, len(selected_population), 2):
+ parent1 = selected_population[i]
+ parent2 = selected_population[min(i + 1, len(selected_population) - 1)]
+ child1, child2 = single_point_crossover(parent1, parent2)
+ next_population.extend([child1, child2])
+
+ # Mutation
+ # Mutate the individuals in the next generation
+ population = [mutate(individual, mutation_rate, bounds) for individual in next_population]
+
+ # Evaluation
+ # Re-evaluate the fitness of the new population
+ fitness = evaluate_fitness(population)
+ # Find the best fitness and corresponding individual
+ best_fitness = min(fitness)
+ best_individual = population[fitness.index(best_fitness)]
+
+ # Print the best fitness of the current generation
+ print(f'Generation {generation + 1}: Best Fitness = {best_fitness}')
+
+ # Return the best individual found
+ return best_individual
+
+# Uncomment the line below to run the genetic algorithm
+best_solution = genetic_algorithm()
+# Print the best solution found
+print(""Best solution found:"", best_solution)",117,101
+,"def abc():
+ x = 1
+ y = 2
+ str1 = ""w3resource""
+ print(""Python Exercises"")
+
+print(abc.__code__.co_nlocals) # Output: 3
",1.0,PERPLEXITY,Write a Python program to detect the number of local variables declared in a function.,PYTHON,"def abc():
+ x = 1
+ y = 2
+ str1 = ""w3resource""
+ print(""Python Exercises"")
+
+print(abc.__code__.co_nlocals) # Output: 3",7,7
+,"# Define a function that returns the maximum of two numbers
+def max_of_two(x, y):
+ # Check if x is greater than y
+ if x > y:
+ # If x is greater, return x
+ return x
+ # If y is greater or equal to x, return y
+ return y
+
+# Define a function that returns the maximum of three numbers
+def max_of_three(x, y, z):
+ # Call max_of_two function to find the maximum of y and z,
+ # then compare it with x to find the overall maximum
+ return max_of_two(x, max_of_two(y, z))
+
+# Print the result of calling max_of_three function with arguments 3, 6, and -5
+print(max_of_three(3, 6, -5)) ",0.0,W3RESOURCE,,PYTHON,"# Define a function that returns the maximum of two numbers
+def max_of_two(x, y):
+ # Check if x is greater than y
+ if x > y:
+ # If x is greater, return x
+ return x
+ # If y is greater or equal to x, return y
+ return y
+
+# Define a function that returns the maximum of three numbers
+def max_of_three(x, y, z):
+ # Call max_of_two function to find the maximum of y and z,
+ # then compare it with x to find the overall maximum
+ return max_of_two(x, max_of_two(y, z))
+
+# Print the result of calling max_of_three function with arguments 3, 6, and -5
+print(max_of_three(3, 6, -5)) ",17,17
+,"def test(a):
+ def add(b):
+ nonlocal a
+ a += 1
+ return a + b
+ return add
+
+a = int(input(""Enter value for a: ""))
+func = test(a)
+b = int(input(""Enter value for b: ""))
+print(""Result:"", func(b))
",1.0,PERPLEXITY,Write a Python program to access a function inside a function.,PYTHON,"def test(a):
+ def add(b):
+ nonlocal a
+ a += 1
+ return a + b
+ return add
+
+a = int(input(""Enter value for a: ""))
+func = test(a)
+b = int(input(""Enter value for b: ""))
+print(""Result:"", func(b))",11,11
+,"# Define a function named 'sum' that takes a list of numbers as input
+def sum(numbers):
+ # Initialize a variable 'total' to store the sum of numbers, starting at 0
+ total = 0
+
+ # Iterate through each element 'x' in the 'numbers' list
+ for x in numbers:
+ # Add the current element 'x' to the 'total'
+ total += x
+
+ # Return the final sum stored in the 'total' variable
+ return total
+
+# Print the result of calling the 'sum' function with a tuple of numbers (8, 2, 3, 0, 7)
+print(sum((8, 2, 3, 0, 7))) ",0.0,,,PYTHON,"# Define a function named 'sum' that takes a list of numbers as input
+def sum(numbers):
+ # Initialize a variable 'total' to store the sum of numbers, starting at 0
+ total = 0
+
+ # Iterate through each element 'x' in the 'numbers' list
+ for x in numbers:
+ # Add the current element 'x' to the 'total'
+ total += x
+
+ # Return the final sum stored in the 'total' variable
+ return total
+
+# Print the result of calling the 'sum' function with a tuple of numbers (8, 2, 3, 0, 7)
+print(sum((8, 2, 3, 0, 7))) ",15,15
+,"# Define a function named 'multiply' that takes a list of numbers as input
+def multiply(numbers):
+ # Initialize a variable 'total' to store the multiplication result, starting at 1
+ total = 1
+
+ # Iterate through each element 'x' in the 'numbers' list
+ for x in numbers:
+ # Multiply the current element 'x' with the 'total'
+ total *= x
+
+ # Return the final multiplication result stored in the 'total' variable
+ return total
+
+# Print the result of calling the 'multiply' function with a tuple of numbers (8, 2, 3, -1, 7)
+print(multiply((8, 2, 3, -1, 7))) ",0.0,W3RESOURCE,,PYTHON,"# Define a function named 'multiply' that takes a list of numbers as input
+def multiply(numbers):
+ # Initialize a variable 'total' to store the multiplication result, starting at 1
+ total = 1
+
+ # Iterate through each element 'x' in the 'numbers' list
+ for x in numbers:
+ # Multiply the current element 'x' with the 'total'
+ total *= x
+
+ # Return the final multiplication result stored in the 'total' variable
+ return total
+
+# Print the result of calling the 'multiply' function with a tuple of numbers (8, 2, 3, -1, 7)
+print(multiply((8, 2, 3, -1, 7))) ",15,15
+,"def bold(fn): return lambda: f""{fn()}""
+def italic(fn): return lambda: f""{fn()}""
+def underline(fn): return lambda: f""{fn()}""
+
+text = input(""Enter text: "")
+hello = underline(italic(bold(lambda: text)))
+print(hello())
",1.0,PERPLEXITY,"Write a Python program to create a chain of function decorators (bold, italic, underline etc.).",PYTHON,"def bold(fn): return lambda: f""{fn()}""
+def italic(fn): return lambda: f""{fn()}""
+def underline(fn): return lambda: f""{fn()}""
+
+text = input(""Enter text: "")
+hello = underline(italic(bold(lambda: text)))
+print(hello())",7,7
+,"# Define a function named 'string_reverse' that takes a string 'str1' as input
+def string_reverse(str1):
+ # Initialize an empty string 'rstr1' to store the reversed string
+ rstr1 = ''
+
+ # Calculate the length of the input string 'str1'
+ index = len(str1)
+
+ # Execute a while loop until 'index' becomes 0
+ while index > 0:
+ # Concatenate the character at index - 1 of 'str1' to 'rstr1'
+ rstr1 += str1[index - 1]
+
+ # Decrement the 'index' by 1 for the next iteration
+ index = index - 1
+
+ # Return the reversed string stored in 'rstr1'
+ return rstr1
+
+# Print the result of calling the 'string_reverse' function with the input string '1234abcd'
+print(string_reverse('1234abcd'))",0.0,W3RESOURCE,,PYTHON,"# Define a function named 'string_reverse' that takes a string 'str1' as input
+def string_reverse(str1):
+ # Initialize an empty string 'rstr1' to store the reversed string
+ rstr1 = ''
+
+ # Calculate the length of the input string 'str1'
+ index = len(str1)
+
+ # Execute a while loop until 'index' becomes 0
+ while index > 0:
+ # Concatenate the character at index - 1 of 'str1' to 'rstr1'
+ rstr1 += str1[index - 1]
+
+ # Decrement the 'index' by 1 for the next iteration
+ index = index - 1
+
+ # Return the reversed string stored in 'rstr1'
+ return rstr1
+
+# Print the result of calling the 'string_reverse' function with the input string '1234abcd'
+print(string_reverse('1234abcd'))",21,21
+,"def printValues():
+ l = [i**2 for i in range(1, 31)]
+ print(l)
+
+printValues()
",1.0,PERPLEXITY,"
+Write a Python function to create and print a list where the values are the squares of numbers between 1 and 30 (both included).",PYTHON,"def printValues():
+ l = [i**2 for i in range(1, 31)]
+ print(l)
+
+printValues()",5,5
+,"# Define a function named 'factorial' that calculates the factorial of a number 'n'
+def factorial(n):
+ # Check if the number 'n' is 0
+ if n == 0:
+ # If 'n' is 0, return 1 (factorial of 0 is 1)
+ return 1
+ else:
+ # If 'n' is not 0, recursively call the 'factorial' function with (n-1) and multiply it with 'n'
+ return n * factorial(n - 1)
+
+# Ask the user to input a number to compute its factorial and store it in variable 'n'
+n = int(input(""Input a number to compute the factorial: ""))
+
+# Print the factorial of the number entered by the user by calling the 'factorial' function
+print(factorial(n))",0.0,W3RESOURCE,,PYTHON,"# Define a function named 'factorial' that calculates the factorial of a number 'n'
+def factorial(n):
+ # Check if the number 'n' is 0
+ if n == 0:
+ # If 'n' is 0, return 1 (factorial of 0 is 1)
+ return 1
+ else:
+ # If 'n' is not 0, recursively call the 'factorial' function with (n-1) and multiply it with 'n'
+ return n * factorial(n - 1)
+
+# Ask the user to input a number to compute its factorial and store it in variable 'n'
+n = int(input(""Input a number to compute the factorial: ""))
+
+# Print the factorial of the number entered by the user by calling the 'factorial' function
+print(factorial(n))",15,15
+,"# Input
+user_input = input(""Enter hyphen-separated words: "")
+
+# Process
+items = [n for n in user_input.split('-')]
+items.sort()
+result = '-'.join(items)
+
+# Output
+print(""Sorted:"", result)
",1.0,PERPLEXITY,Write a Python program that accepts a hyphen-separated sequence of words as input and prints the words in a hyphen-separated sequence after sorting them alphabetically.,PYTHON,"# Input
+user_input = input(""Enter hyphen-separated words: "")
+
+# Process
+items = [n for n in user_input.split('-')]
+items.sort()
+result = '-'.join(items)
+
+# Output
+print(""Sorted:"", result)",10,10
+,"# Define a function named 'test_range' that checks if a number 'n' is within the range 3 to 8 (inclusive)
+def test_range(n):
+ # Check if 'n' is within the range from 3 to 8 (inclusive) using the 'in range()' statement
+ if n in range(3, 9):
+ # If 'n' is within the range, print that 'n' is within the given range
+ print(""%s is in the range"" % str(n))
+ else:
+ # If 'n' is outside the range, print that the number is outside the given range
+ print(""The number is outside the given range."")
+
+# Call the 'test_range' function with the argument 5
+test_range(5)",0.0,W3RESOURCE,,PYTHON,"# Define a function named 'test_range' that checks if a number 'n' is within the range 3 to 8 (inclusive)
+def test_range(n):
+ # Check if 'n' is within the range from 3 to 8 (inclusive) using the 'in range()' statement
+ if n in range(3, 9):
+ # If 'n' is within the range, print that 'n' is within the given range
+ print(""%s is in the range"" % str(n))
+ else:
+ # If 'n' is outside the range, print that the number is outside the given range
+ print(""The number is outside the given range."")
+
+# Call the 'test_range' function with the argument 5
+test_range(5)",12,12
+,"import string
+
+def ispangram(str1, alphabet=string.ascii_lowercase):
+ alphaset = set(alphabet)
+ str_set = set(str1.lower())
+ return alphaset <= str_set
+
+# Test
+print(ispangram('The quick brown fox jumps over the lazy dog')) # True
",1.0,PERPLEXITY,Write a Python function to check whether a string is a pangram or not.,PYTHON,"import string
+
+def ispangram(str1, alphabet=string.ascii_lowercase):
+ alphaset = set(alphabet)
+ str_set = set(str1.lower())
+ return alphaset <= str_set
+
+# Test
+print(ispangram('The quick brown fox jumps over the lazy dog')) # True",9,9
+,"# Define a function named 'string_test' that counts the number of upper and lower case characters in a string 's'
+def string_test(s):
+ # Create a dictionary 'd' to store the count of upper and lower case characters
+ d = {""UPPER_CASE"": 0, ""LOWER_CASE"": 0}
+
+ # Iterate through each character 'c' in the string 's'
+ for c in s:
+ # Check if the character 'c' is in upper case
+ if c.isupper():
+ # If 'c' is upper case, increment the count of upper case characters in the dictionary
+ d[""UPPER_CASE""] += 1
+ # Check if the character 'c' is in lower case
+ elif c.islower():
+ # If 'c' is lower case, increment the count of lower case characters in the dictionary
+ d[""LOWER_CASE""] += 1
+ else:
+ # If 'c' is neither upper nor lower case (e.g., punctuation, spaces), do nothing
+ pass
+
+ # Print the original string 's'
+ print(""Original String: "", s)
+
+ # Print the count of upper case characters
+ print(""No. of Upper case characters: "", d[""UPPER_CASE""])
+
+ # Print the count of lower case characters
+ print(""No. of Lower case Characters: "", d[""LOWER_CASE""])
+
+# Call the 'string_test' function with the input string 'The quick Brown Fox'
+string_test('The quick Brown Fox')",0.0,W3RESOURCE,,PYTHON,"# Define a function named 'string_test' that counts the number of upper and lower case characters in a string 's'
+def string_test(s):
+ # Create a dictionary 'd' to store the count of upper and lower case characters
+ d = {""UPPER_CASE"": 0, ""LOWER_CASE"": 0}
+
+ # Iterate through each character 'c' in the string 's'
+ for c in s:
+ # Check if the character 'c' is in upper case
+ if c.isupper():
+ # If 'c' is upper case, increment the count of upper case characters in the dictionary
+ d[""UPPER_CASE""] += 1
+ # Check if the character 'c' is in lower case
+ elif c.islower():
+ # If 'c' is lower case, increment the count of lower case characters in the dictionary
+ d[""LOWER_CASE""] += 1
+ else:
+ # If 'c' is neither upper nor lower case (e.g., punctuation, spaces), do nothing
+ pass
+
+ # Print the original string 's'
+ print(""Original String: "", s)
+
+ # Print the count of upper case characters
+ print(""No. of Upper case characters: "", d[""UPPER_CASE""])
+
+ # Print the count of lower case characters
+ print(""No. of Lower case Characters: "", d[""LOWER_CASE""])
+
+# Call the 'string_test' function with the input string 'The quick Brown Fox'
+string_test('The quick Brown Fox')",30,30
+,"def pascal_triangle(n):
+ for i in range(n):
+ row = [1]
+ for j in range(1, i):
+ row.append(row[j-1] + row[j])
+ row.append(1) if i > 0 else None
+ print(row)
+
+# Test
+pascal_triangle(6)
",1.0,PERPLEXITY,Write a Python function that prints out the first n rows of Pascal's triangle.,PYTHON,"def pascal_triangle(n):
+ for i in range(n):
+ row = [1]
+ for j in range(1, i):
+ row.append(row[j-1] + row[j])
+ row.append(1) if i > 0 else None
+ print(row)
+
+# Test
+pascal_triangle(6)",10,10
+,"# Define a function named 'unique_list' that takes a list 'l' as input and returns a list of unique elements
+def unique_list(l):
+ # Create an empty list 'x' to store unique elements
+ x = []
+
+ # Iterate through each element 'a' in the input list 'l'
+ for a in l:
+ # Check if the element 'a' is not already present in the list 'x'
+ if a not in x:
+ # If 'a' is not in 'x', add it to the list 'x'
+ x.append(a)
+
+ # Return the list 'x' containing unique elements
+ return x
+
+# Print the result of calling the 'unique_list' function with a list containing duplicate elements
+print(unique_list([1, 2, 3, 3, 3, 3, 4, 5])) ",0.0,W3RESOURCE,,PYTHON,"# Define a function named 'unique_list' that takes a list 'l' as input and returns a list of unique elements
+def unique_list(l):
+ # Create an empty list 'x' to store unique elements
+ x = []
+
+ # Iterate through each element 'a' in the input list 'l'
+ for a in l:
+ # Check if the element 'a' is not already present in the list 'x'
+ if a not in x:
+ # If 'a' is not in 'x', add it to the list 'x'
+ x.append(a)
+
+ # Return the list 'x' containing unique elements
+ return x
+
+# Print the result of calling the 'unique_list' function with a list containing duplicate elements
+print(unique_list([1, 2, 3, 3, 3, 3, 4, 5])) ",17,17
+,"def isPalindrome(string):
+ left_pos = 0
+ right_pos = len(string) - 1
+
+ while right_pos >= left_pos:
+ if string[left_pos] != string[right_pos]:
+ return False
+ left_pos += 1
+ right_pos -= 1
+
+ return True
+
+# Test
+print(isPalindrome('aza')) # True
",1.0,PERPLEXITY,Write a Python function that checks whether a passed string is a palindrome or not.,PYTHON,"def isPalindrome(string):
+ left_pos = 0
+ right_pos = len(string) - 1
+
+ while right_pos >= left_pos:
+ if string[left_pos] != string[right_pos]:
+ return False
+ left_pos += 1
+ right_pos -= 1
+
+ return True
+
+# Test
+print(isPalindrome('aza')) # True",14,14
+,"# Define a function named 'test_prime' that checks if a number 'n' is a prime number
+def test_prime(n):
+ # Check if 'n' is equal to 1
+ if (n == 1):
+ # If 'n' is 1, return False (1 is not a prime number)
+ return False
+ # Check if 'n' is equal to 2
+ elif (n == 2):
+ # If 'n' is 2, return True (2 is a prime number)
+ return True
+ else:
+ # Iterate through numbers from 2 to (n-1) using 'x' as the iterator
+ for x in range(2, n):
+ # Check if 'n' is divisible by 'x' without any remainder
+ if (n % x == 0):
+ # If 'n' is divisible by 'x', return False (not a prime number)
+ return False
+ # If 'n' is not divisible by any number from 2 to (n-1), return True (prime number)
+ return True
+
+# Print the result of checking if 9 is a prime number by calling the 'test_prime' function
+print(test_prime(9))",0.0,W3RESOURCE,,PYTHON,"# Define a function named 'test_prime' that checks if a number 'n' is a prime number
+def test_prime(n):
+ # Check if 'n' is equal to 1
+ if (n == 1):
+ # If 'n' is 1, return False (1 is not a prime number)
+ return False
+ # Check if 'n' is equal to 2
+ elif (n == 2):
+ # If 'n' is 2, return True (2 is a prime number)
+ return True
+ else:
+ # Iterate through numbers from 2 to (n-1) using 'x' as the iterator
+ for x in range(2, n):
+ # Check if 'n' is divisible by 'x' without any remainder
+ if (n % x == 0):
+ # If 'n' is divisible by 'x', return False (not a prime number)
+ return False
+ # If 'n' is not divisible by any number from 2 to (n-1), return True (prime number)
+ return True
+
+# Print the result of checking if 9 is a prime number by calling the 'test_prime' function
+print(test_prime(9))",22,22
+,"def perfect_number(n):
+ sum_div = 0
+ for x in range(1, n):
+ if n % x == 0:
+ sum_div += x
+ return sum_div == n
+
+# Test
+print(perfect_number(6)) # True (1+2+3=6)
",1.0,PERPLEXITY,"Write a Python function to check whether a number is ""Perfect"" or not.",PYTHON,"def perfect_number(n):
+ sum_div = 0
+ for x in range(1, n):
+ if n % x == 0:
+ sum_div += x
+ return sum_div == n
+
+# Test
+print(perfect_number(6)) # True (1+2+3=6)",9,9
+,"# Define a function named 'is_even_num' that takes a list 'l' as input and returns a list of even numbers
+def is_even_num(l):
+ # Create an empty list 'enum' to store even numbers
+ enum = []
+
+ # Iterate through each number 'n' in the input list 'l'
+ for n in l:
+ # Check if the number 'n' is even (divisible by 2 without a remainder)
+ if n % 2 == 0:
+ # If 'n' is even, append it to the 'enum' list
+ enum.append(n)
+
+ # Return the list 'enum' containing even numbers
+ return enum
+
+# Print the result of calling the 'is_even_num' function with a list of numbers
+print(is_even_num([1, 2, 3, 4, 5, 6, 7, 8, 9])) ",0.0,W3RESOURCE,,PYTHON,"# Define a function named 'is_even_num' that takes a list 'l' as input and returns a list of even numbers
+def is_even_num(l):
+ # Create an empty list 'enum' to store even numbers
+ enum = []
+
+ # Iterate through each number 'n' in the input list 'l'
+ for n in l:
+ # Check if the number 'n' is even (divisible by 2 without a remainder)
+ if n % 2 == 0:
+ # If 'n' is even, append it to the 'enum' list
+ enum.append(n)
+
+ # Return the list 'enum' containing even numbers
+ return enum
+
+# Print the result of calling the 'is_even_num' function with a list of numbers
+print(is_even_num([1, 2, 3, 4, 5, 6, 7, 8, 9])) ",17,17
+,"def is_even_num(l):
+ return [n for n in l if n % 2 == 0]
+
+# Example usage
+print(is_even_num([1, 2, 3, 4, 5, 6, 7, 8, 9]))
",1.0,PERPLEXITY,Write a Python program to print the even numbers from a given list.,PYTHON,"def is_even_num(l):
+ return [n for n in l if n % 2 == 0]
+
+# Example usage
+print(is_even_num([1, 2, 3, 4, 5, 6, 7, 8, 9]))",5,5
+,"# Define a function named 'perfect_number' that checks if a number 'n' is a perfect number
+def perfect_number(n):
+ # Initialize a variable 'sum' to store the sum of factors of 'n'
+ sum = 0
+
+ # Iterate through numbers from 1 to 'n-1' using 'x' as the iterator
+ for x in range(1, n):
+ # Check if 'x' is a factor of 'n' (divides 'n' without remainder)
+ if n % x == 0:
+ # If 'x' is a factor of 'n', add it to the 'sum'
+ sum += x
+
+ # Check if the 'sum' of factors is equal to the original number 'n'
+ return sum == n
+
+# Print the result of checking if 6 is a perfect number by calling the 'perfect_number' function
+print(perfect_number(6))",0.0,W3RESOURCE,,PYTHON,"# Define a function named 'perfect_number' that checks if a number 'n' is a perfect number
+def perfect_number(n):
+ # Initialize a variable 'sum' to store the sum of factors of 'n'
+ sum = 0
+
+ # Iterate through numbers from 1 to 'n-1' using 'x' as the iterator
+ for x in range(1, n):
+ # Check if 'x' is a factor of 'n' (divides 'n' without remainder)
+ if n % x == 0:
+ # If 'x' is a factor of 'n', add it to the 'sum'
+ sum += x
+
+ # Check if the 'sum' of factors is equal to the original number 'n'
+ return sum == n
+
+# Print the result of checking if 6 is a perfect number by calling the 'perfect_number' function
+print(perfect_number(6))",17,17
+,"def test_prime(n):
+ if n <= 1:
+ return False
+ for x in range(2, n):
+ if n % x == 0:
+ return False
+ return True
+
+# Accepts input from user
+n = int(input(""Enter a number: ""))
+print(test_prime(n))
",1.0,PERPLEXITY,"Write a Python function that takes a number as a parameter and checks whether the number is prime or not.
+
+Note : A prime number (or a prime) is a natural number greater than 1 and that has no positive divisors other than 1 and itself.",PYTHON,"def test_prime(n):
+ if n <= 1:
+ return False
+ for x in range(2, n):
+ if n % x == 0:
+ return False
+ return True
+
+# Accepts input from user
+n = int(input(""Enter a number: ""))
+print(test_prime(n))",11,11
+,"# Define a function named 'isPalindrome' that checks if a string is a palindrome
+def isPalindrome(string):
+ # Initialize left and right pointers to check characters from the start and end of the string
+ left_pos = 0
+ right_pos = len(string) - 1
+
+ # Loop until the pointers meet or cross each other
+ while right_pos >= left_pos:
+ # Check if the characters at the left and right positions are not equal
+ if not string[left_pos] == string[right_pos]:
+ # If characters don't match, return False (not a palindrome)
+ return False
+
+ # Move the left pointer to the right and the right pointer to the left to continue checking
+ left_pos += 1
+ right_pos -= 1
+
+ # If the loop finishes without returning False, the string is a palindrome, so return True
+ return True
+
+# Print the result of checking if the string 'aza' is a palindrome by calling the 'isPalindrome' function
+print(isPalindrome('aza')) ",0.0,W3RESOURCE,,PYTHON,"# Define a function named 'isPalindrome' that checks if a string is a palindrome
+def isPalindrome(string):
+ # Initialize left and right pointers to check characters from the start and end of the string
+ left_pos = 0
+ right_pos = len(string) - 1
+
+ # Loop until the pointers meet or cross each other
+ while right_pos >= left_pos:
+ # Check if the characters at the left and right positions are not equal
+ if not string[left_pos] == string[right_pos]:
+ # If characters don't match, return False (not a palindrome)
+ return False
+
+ # Move the left pointer to the right and the right pointer to the left to continue checking
+ left_pos += 1
+ right_pos -= 1
+
+ # If the loop finishes without returning False, the string is a palindrome, so return True
+ return True
+
+# Print the result of checking if the string 'aza' is a palindrome by calling the 'isPalindrome' function
+print(isPalindrome('aza')) ",22,22
+,"def unique_list(l):
+ return list(set(l))
+
+# Example usage
+print(unique_list([1, 2, 3, 3, 3, 3, 4, 5]))
",1.0,PERPLEXITY,Write a Python function that takes a list and returns a new list with distinct elements from the first list.,PYTHON,"def unique_list(l):
+ return list(set(l))
+
+# Example usage
+print(unique_list([1, 2, 3, 3, 3, 3, 4, 5]))",5,5
+,"# Define a function named 'pascal_triangle' that generates Pascal's Triangle up to row 'n'
+def pascal_triangle(n):
+ # Initialize the first row of Pascal's Triangle with value 1 as a starting point
+ trow = [1]
+
+ # Create a list 'y' filled with zeros to be used for calculations
+ y = [0]
+
+ # Iterate through a range starting from 0 up to the maximum of 'n' or 0 (taking the maximum to handle negative 'n')
+ for x in range(max(n, 0)):
+ # Print the current row of Pascal's Triangle
+ print(trow)
+
+ # Update the current row based on the previous row by calculating the next row using list comprehension
+ # The formula for generating the next row in Pascal's Triangle is based on addition of consecutive elements
+ trow = [l + r for l, r in zip(trow + y, y + trow)]
+
+ # Return True if 'n' is greater than or equal to 1, else return False
+ return n >= 1
+
+# Generate Pascal's Triangle up to row 6 by calling the 'pascal_triangle' function
+pascal_triangle(6) ",0.0,W3RESOURCE,,PYTHON,"# Define a function named 'pascal_triangle' that generates Pascal's Triangle up to row 'n'
+def pascal_triangle(n):
+ # Initialize the first row of Pascal's Triangle with value 1 as a starting point
+ trow = [1]
+
+ # Create a list 'y' filled with zeros to be used for calculations
+ y = [0]
+
+ # Iterate through a range starting from 0 up to the maximum of 'n' or 0 (taking the maximum to handle negative 'n')
+ for x in range(max(n, 0)):
+ # Print the current row of Pascal's Triangle
+ print(trow)
+
+ # Update the current row based on the previous row by calculating the next row using list comprehension
+ # The formula for generating the next row in Pascal's Triangle is based on addition of consecutive elements
+ trow = [l + r for l, r in zip(trow + y, y + trow)]
+
+ # Return True if 'n' is greater than or equal to 1, else return False
+ return n >= 1
+
+# Generate Pascal's Triangle up to row 6 by calling the 'pascal_triangle' function
+pascal_triangle(6) ",22,22
+,"def string_test(s):
+ upper_count = 0
+ lower_count = 0
+
+ for ch in s:
+ if ch.isupper():
+ upper_count += 1
+ elif ch.islower():
+ lower_count += 1
+
+ print(""No. of Upper case characters :"", upper_count)
+ print(""No. of Lower case Characters :"", lower_count)
+
+# Example usage
+string_test('The quick Brow Fox')
",1.0,PERPLEXITY,"Write a Python function that accepts a string and counts the number of upper and lower case letters.
+
+Sample String : 'The quick Brow Fox'
+Expected Output :
+No. of Upper case characters : 3
+No. of Lower case Characters : 12",PYTHON,"def string_test(s):
+ upper_count = 0
+ lower_count = 0
+
+ for ch in s:
+ if ch.isupper():
+ upper_count += 1
+ elif ch.islower():
+ lower_count += 1
+
+ print(""No. of Upper case characters :"", upper_count)
+ print(""No. of Lower case Characters :"", lower_count)
+
+# Example usage
+string_test('The quick Brow Fox')",15,15
+,"# Import the 'string' and 'sys' modules
+import string
+import sys
+
+# Define a function named 'ispangram' that checks if a string is a pangram
+def ispangram(str1, alphabet=string.ascii_lowercase):
+ # Create a set 'alphaset' containing all lowercase letters from the provided alphabet
+ alphaset = set(alphabet)
+
+ # Convert the input string to lowercase and create a set from it
+ str_set = set(str1.lower())
+
+ # Check if the set of lowercase characters in the input string covers all characters in 'alphaset'
+ return alphaset <= str_set
+
+# Print the result of checking if the string is a pangram by calling the 'ispangram' function
+print(ispangram('The quick brown fox jumps over the lazy dog'))
+",0.0,W3RESOURCE,,PYTHON,"# Import the 'string' and 'sys' modules
+import string
+import sys
+
+# Define a function named 'ispangram' that checks if a string is a pangram
+def ispangram(str1, alphabet=string.ascii_lowercase):
+ # Create a set 'alphaset' containing all lowercase letters from the provided alphabet
+ alphaset = set(alphabet)
+
+ # Convert the input string to lowercase and create a set from it
+ str_set = set(str1.lower())
+
+ # Check if the set of lowercase characters in the input string covers all characters in 'alphaset'
+ return alphaset <= str_set
+
+# Print the result of checking if the string is a pangram by calling the 'ispangram' function
+print(ispangram('The quick brown fox jumps over the lazy dog')) ",17,17
+,"def in_range(n, low, high):
+ return low <= n <= high
+
+# ---------- INPUT ----------
+n, low, high = 5, 3, 8
+
+# ---------- OUTPUT ----------
+if in_range(n, low, high):
+ print(f""{n} is in the range {low} to {high}"")
+else:
+ print(f""{n} is outside the range {low} to {high}"")
",1.0,GPT,Write a Python function to check whether a number falls within a given range.,PYTHON,"def in_range(n, low, high):
+ return low <= n <= high
+
+# ---------- INPUT ----------
+n, low, high = 5, 3, 8
+
+# ---------- OUTPUT ----------
+if in_range(n, low, high):
+ print(f""{n} is in the range {low} to {high}"")
+else:
+ print(f""{n} is outside the range {low} to {high}"")",11,11
+,"# Take user input and split it into a list based on the hyphen (""-"") separator, creating a list named 'items'
+items = [n for n in input().split('-')]
+
+# Sort the elements in the 'items' list in lexicographical order (alphabetical and numerical sorting)
+items.sort()
+
+# Join the sorted elements in the 'items' list using the hyphen (""-"") separator and print the resulting string
+print('-'.join(items)) ",0.0,W3RESOURCE,,PYTHON,"# Take user input and split it into a list based on the hyphen (""-"") separator, creating a list named 'items'
+items = [n for n in input().split('-')]
+
+# Sort the elements in the 'items' list in lexicographical order (alphabetical and numerical sorting)
+items.sort()
+
+# Join the sorted elements in the 'items' list using the hyphen (""-"") separator and print the resulting string
+print('-'.join(items)) ",8,8
+,"def factorial(n):
+ if n == 0:
+ return 1
+ return n * factorial(n - 1)
+
+# General usage
+print(factorial(6)) # Output: 720
+",1.0,PERPLEXITY,Write a Python function to calculate the factorial of a number (a non-negative integer). The function accepts the number as an argument.,PYTHON,"def factorial(n):
+ if n == 0:
+ return 1
+ return n * factorial(n - 1)
+
+# General usage
+print(factorial(6)) # Output: 720",7,7
+,"# Define a function named 'printValues' that generates a list of squares of numbers from 1 to 20
+def printValues():
+ # Create an empty list 'l'
+ l = list()
+
+ # Iterate through numbers from 1 to 20 (inclusive)
+ for i in range(1, 21):
+ # Calculate the square of 'i' and append it to the list 'l'
+ l.append(i**2)
+
+ # Print the list containing squares of numbers from 1 to 20
+ print(l)
+
+# Call the 'printValues' function to generate and print the list of squares
+printValues() ",0.0,W3RESOURCE,,PYTHON,"# Define a function named 'printValues' that generates a list of squares of numbers from 1 to 20
+def printValues():
+ # Create an empty list 'l'
+ l = list()
+
+ # Iterate through numbers from 1 to 20 (inclusive)
+ for i in range(1, 21):
+ # Calculate the square of 'i' and append it to the list 'l'
+ l.append(i**2)
+
+ # Print the list containing squares of numbers from 1 to 20
+ print(l)
+
+# Call the 'printValues' function to generate and print the list of squares
+printValues() ",15,15
+,"def string_reverse(text):
+ return text[::-1]
+
+# General usage
+input_string = ""python""
+print(string_reverse(input_string)) # Output: ""nohtyp""
",1.0,PERPLEXITY,"Write a Python program to reverse a string.
+Sample String : ""1234abcd""
+Expected Output : ""dcba4321"" dont give the code for this particular samples , give it in a general way of i/o",PYTHON,"def string_reverse(text):
+ return text[::-1]
+
+# General usage
+input_string = ""python""
+print(string_reverse(input_string)) # Output: ""nohtyp""",6,6
+,"# Define a decorator 'make_bold' that adds bold HTML tags to the wrapped function's return value
+def make_bold(fn):
+ def wrapped():
+ return """" + fn() + """"
+ return wrapped
+
+# Define a decorator 'make_italic' that adds italic HTML tags to the wrapped function's return value
+def make_italic(fn):
+ def wrapped():
+ return """" + fn() + """"
+ return wrapped
+
+# Define a decorator 'make_underline' that adds underline HTML tags to the wrapped function's return value
+def make_underline(fn):
+ def wrapped():
+ return """" + fn() + """"
+ return wrapped
+
+# Apply multiple decorators (@make_bold, @make_italic, @make_underline) to the 'hello' function
+@make_bold
+@make_italic
+@make_underline
+def hello():
+ return ""hello world""
+
+# Print the result of the decorated 'hello' function, which adds HTML tags for bold, italic, and underline
+
+print(hello()) ## returns ""hello world""",0.0,W3RESOURCE,,PYTHON,"# Define a decorator 'make_bold' that adds bold HTML tags to the wrapped function's return value
+def make_bold(fn):
+ def wrapped():
+ return """" + fn() + """"
+ return wrapped
+
+# Define a decorator 'make_italic' that adds italic HTML tags to the wrapped function's return value
+def make_italic(fn):
+ def wrapped():
+ return """" + fn() + """"
+ return wrapped
+
+# Define a decorator 'make_underline' that adds underline HTML tags to the wrapped function's return value
+def make_underline(fn):
+ def wrapped():
+ return """" + fn() + """"
+ return wrapped
+
+# Apply multiple decorators (@make_bold, @make_italic, @make_underline) to the 'hello' function
+@make_bold
+@make_italic
+@make_underline
+def hello():
+ return ""hello world""
+
+# Print the result of the decorated 'hello' function, which adds HTML tags for bold, italic, and underline
+
+print(hello()) ## returns ""hello world""",28,28
+,"def multiply_numbers(numbers):
+ return 1 if not numbers else numbers[0] * multiply_numbers(numbers[1:])
+
+# Or using reduce (from functools)
+from functools import reduce
+def multiply_numbers(numbers):
+ return reduce(lambda x, y: x * y, numbers, 1)
+
+print(multiply_numbers([8, 2, 3, -1, 7])) # Output: -336
",1.0,PERPLEXITY,"Write a Python function to multiply all the numbers in a list. Sample List : (8, 2, 3, -1, 7)
+Expected Output : -336",PYTHON,"def multiply_numbers(numbers):
+ return 1 if not numbers else numbers[0] * multiply_numbers(numbers[1:])
+
+# Or using reduce (from functools)
+from functools import reduce
+def multiply_numbers(numbers):
+ return reduce(lambda x, y: x * y, numbers, 1)
+
+print(multiply_numbers([8, 2, 3, -1, 7])) # Output: -336",9,9
+,"# Define a string variable 'mycode' containing a Python code as a string
+mycode = 'print(""hello world"")'
+
+# Define a multi-line string variable 'code' containing Python code as a string
+code = """"""
+def mutiply(x,y):
+ return x*y
+
+print('Multiply of 2 and 3 is: ',mutiply(2,3))
+""""""
+
+# Execute the Python code represented by the string stored in the variable 'mycode'
+exec(mycode)
+
+# Execute the Python code represented by the multi-line string stored in the variable 'code'
+exec(code) ",0.0,W3RESOURCE,,PYTHON,"# Define a string variable 'mycode' containing a Python code as a string
+mycode = 'print(""hello world"")'
+
+# Define a multi-line string variable 'code' containing Python code as a string
+code = """"""
+def mutiply(x,y):
+ return x*y
+
+print('Multiply of 2 and 3 is: ',mutiply(2,3))
+""""""
+
+# Execute the Python code represented by the string stored in the variable 'mycode'
+exec(mycode)
+
+# Execute the Python code represented by the multi-line string stored in the variable 'code'
+exec(code) ",16,16
+,"def sum_numbers(numbers):
+ return sum(numbers)
+
+print(sum_numbers([8, 2, 3, 0, 7])) # Output: 20
",1.0,PERPLEXITY,"Write a Python function to sum all the numbers in a list.
+Sample List : (8, 2, 3, 0, 7)
+Expected Output : 20",PYTHON,"def sum_numbers(numbers):
+ return sum(numbers)
+
+print(sum_numbers([8, 2, 3, 0, 7])) # Output: 20",4,4
+,"# Define a function named 'test' that takes a parameter 'a'
+def test(a):
+ # Define a nested function 'add' that takes a parameter 'b'
+ def add(b):
+ # Declare 'a' from the outer scope as nonlocal to modify its value
+ nonlocal a
+
+ # Increment the value of 'a' by 1
+ a += 1
+
+ # Return the sum of 'a' (modified by the nonlocal statement) and 'b'
+ return a + b
+
+ # Return the inner function 'add' and its scope is retained due to closure
+ return add
+
+# Call the 'test' function with an argument '4' and assign the returned function to 'func'
+func = test(4)
+
+# Call the function 'func' with argument '4' and print the result
+print(func(4)) ",0.0,W3RESOURCE,,PYTHON,"# Define a function named 'test' that takes a parameter 'a'
+def test(a):
+ # Define a nested function 'add' that takes a parameter 'b'
+ def add(b):
+ # Declare 'a' from the outer scope as nonlocal to modify its value
+ nonlocal a
+
+ # Increment the value of 'a' by 1
+ a += 1
+
+ # Return the sum of 'a' (modified by the nonlocal statement) and 'b'
+ return a + b
+
+ # Return the inner function 'add' and its scope is retained due to closure
+ return add
+
+# Call the 'test' function with an argument '4' and assign the returned function to 'func'
+func = test(4)
+
+# Call the function 'func' with argument '4' and print the result
+print(func(4)) ",21,21
+,"def max_of_three(a, b, c):
+ return max(a, b, c)
+
+# ---------- INPUT ----------
+x, y, z = 3, 6, -5
+
+# ---------- OUTPUT ----------
+print(""Maximum:"", max_of_three(x, y, z))
+",1.0,GPT,Write a Python function to find the maximum of three numbers.,PYTHON,"def max_of_three(a, b, c):
+ return max(a, b, c)
+
+# ---------- INPUT ----------
+x, y, z = 3, 6, -5
+
+# ---------- OUTPUT ----------
+print(""Maximum:"", max_of_three(x, y, z))",8,8
+,"# Define a function named 'abc'
+def abc():
+ # Define and assign values to local variables 'x', 'y', and 'str1' inside the function 'abc'
+ x = 1
+ y = 2
+ str1 = ""w3resource""
+
+ # Print the string ""Python Exercises""
+ print(""Python Exercises"")
+
+# Access the number of local variables in the function 'abc' using the __code__.co_nlocals attribute
+print(abc.__code__.co_nlocals) ",0.0,W3RESOURCE,,PYTHON,"# Define a function named 'abc'
+def abc():
+ # Define and assign values to local variables 'x', 'y', and 'str1' inside the function 'abc'
+ x = 1
+ y = 2
+ str1 = ""w3resource""
+
+ # Print the string ""Python Exercises""
+ print(""Python Exercises"")
+
+# Access the number of local variables in the function 'abc' using the __code__.co_nlocals attribute
+print(abc.__code__.co_nlocals) ",12,12
+,"import random, numpy as np
+
+f = lambda x: 10*len(x) + sum(x*x - 10*np.cos(2*np.pi*x))
+
+def GA(pop=50, n=5, gen=50):
+ P = [np.random.uniform(-5,5,n) for _ in range(pop)]
+ for g in range(gen):
+ P = sorted(P, key=f)
+ print(f""Gen {g+1} Best:"", f(P[0]))
+ N = P[:10]
+ while len(N) self.cap:
+ self.d.popitem(last=False)
",1.0,GPT,Write a Python program to create a caching system with support for LRU eviction policy TO PASS ALL THE TEST CASES,PYTHON,"from collections import OrderedDict
+
+class LRUCache:
+ def __init__(self, cap):
+ self.cap, self.d = cap, OrderedDict()
+
+ def get(self, k):
+ if k not in self.d: return -1
+ self.d.move_to_end(k)
+ return self.d[k]
+
+ def put(self, k, v):
+ if k in self.d: self.d.move_to_end(k)
+ self.d[k] = v
+ if len(self.d) > self.cap:
+ self.d.popitem(last=False)",16,16
+,"import numpy as np
+x = [1., 2., 3., 4.]
+print(""Original array:"")
+print(x)
+print(""Largest integer smaller or equal to the division of the inputs:"")
+print(np.floor_divide(x, 1.5))
+",0.0,W3RESOURCE,,PYTHON,"import numpy as np
+x = [1., 2., 3., 4.]
+print(""Original array:"")
+print(x)
+print(""Largest integer smaller or equal to the division of the inputs:"")
+print(np.floor_divide(x, 1.5))",6,6
+,"import asyncio
+
+class Scheduler:
+ def __init__(self): self.tasks=[]
+ def add(self, coro, *args): self.tasks.append(coro(*args))
+ async def run(self): await asyncio.gather(*self.tasks)
+
+async def task(name, t):
+ print(f""Task {name} started ({t}s)"")
+ await asyncio.sleep(t)
+ print(f""Task {name} finished"")
+
+# ---------- INPUT ----------
+async def main():
+ s = Scheduler()
+ s.add(task, ""A"", 2)
+ s.add(task, ""B"", 1)
+ s.add(task, ""C"", 3)
+ await s.run()
+
+# ---------- OUTPUT ----------
+asyncio.run(main())
+",1.0,GPT,Write a Python program that builds a concurrent task scheduler using asyncio WITH I/O,PYTHON,"import asyncio
+
+class Scheduler:
+ def __init__(self): self.tasks=[]
+ def add(self, coro, *args): self.tasks.append(coro(*args))
+ async def run(self): await asyncio.gather(*self.tasks)
+
+async def task(name, t):
+ print(f""Task {name} started ({t}s)"")
+ await asyncio.sleep(t)
+ print(f""Task {name} finished"")
+
+# ---------- INPUT ----------
+async def main():
+ s = Scheduler()
+ s.add(task, ""A"", 2)
+ s.add(task, ""B"", 1)
+ s.add(task, ""C"", 3)
+ await s.run()
+
+# ---------- OUTPUT ----------
+asyncio.run(main())",22,22
+,"# Importing the NumPy library
+import numpy as np
+
+# Creating an array from 0 to 6
+x = np.arange(7)
+
+# Displaying the original array
+print(""Original array:"")
+print(x)
+
+# Raising the elements of the array to the power of 3 and displaying the result
+print(""First array elements raised to powers from second array, element-wise:"")
+print(np.power(x, 3)) ",0.0,W3RESOURCE,,PYTHON,"# Importing the NumPy library
+import numpy as np
+
+# Creating an array from 0 to 6
+x = np.arange(7)
+
+# Displaying the original array
+print(""Original array:"")
+print(x)
+
+# Raising the elements of the array to the power of 3 and displaying the result
+print(""First array elements raised to powers from second array, element-wise:"")
+print(np.power(x, 3)) ",13,13
+,"import hashlib
+
+class Bloom:
+ def __init__(s,n,k):
+ s.n,s.k,s.b=n,k,[0]*n
+
+ def _h(s,x):
+ h1=int(hashlib.sha256(x.encode()).hexdigest(),16)
+ h2=int(hashlib.md5(x.encode()).hexdigest(),16)
+ return [(h1+i*h2)%s.n for i in range(s.k)]
+
+ def add(s,x):
+ for i in s._h(x): s.b[i]=1
+
+ def check(s,x):
+ return all(s.b[i] for i in s._h(x))
+",1.0,GPT,"WRITE THE PYTHON CODE FOR Bloom Filter Implementation with i/o , let the code you provide be efficient and accurate for the results it provide",PYTHON,"import hashlib
+
+class Bloom:
+ def __init__(s,n,k):
+ s.n,s.k,s.b=n,k,[0]*n
+
+ def _h(s,x):
+ h1=int(hashlib.sha256(x.encode()).hexdigest(),16)
+ h2=int(hashlib.md5(x.encode()).hexdigest(),16)
+ return [(h1+i*h2)%s.n for i in range(s.k)]
+
+ def add(s,x):
+ for i in s._h(x): s.b[i]=1
+
+ def check(s,x):
+ return all(s.b[i] for i in s._h(x))",16,16
+,"def binary_search(item_list,item):
+ first = 0
+ last = len(item_list)-1
+ found = False
+ while( first<=last and not found):
+ mid = (first + last)//2
+ if item_list[mid] == item :
+ found = True
+ else:
+ if item < item_list[mid]:
+ last = mid - 1
+ else:
+ first = mid + 1
+ return found
+
+print(binary_search([1,2,3,5,8], 6))
+print(binary_search([1,2,3,5,8], 5))",0.0,W3RESOURCE,,PYTHON,"def binary_search(item_list,item):
+ first = 0
+ last = len(item_list)-1
+ found = False
+ while( first<=last and not found):
+ mid = (first + last)//2
+ if item_list[mid] == item :
+ found = True
+ else:
+ if item < item_list[mid]:
+ last = mid - 1
+ else:
+ first = mid + 1
+ return found
+
+print(binary_search([1,2,3,5,8], 6))
+print(binary_search([1,2,3,5,8], 5))",17,17
+,"import json
+
+class Address:
+ def __init__(s,st,ct,stt,z): s.street, s.city, s.state, s.zip = st,ct,stt,z
+
+class Person:
+ def __init__(s,n,a,ad): s.name, s.age, s.address = n,a,ad
+
+class Encoder(json.JSONEncoder):
+ def default(s,o):
+ if hasattr(o,""__dict__""):
+ return {""__t__"":o.__class__.__name__, **o.__dict__}
+ return super().default(o)
+
+def decoder(d):
+ if ""__t__"" in d:
+ cls = {""Address"":Address,""Person"":Person}[d.pop(""__t__"")]
+ return cls(**d)
+ return d
",1.0,GPT,GIVE me a python code for Custom JSON Encoder/Decoder,PYTHON,"import json
+
+class Address:
+ def __init__(s,st,ct,stt,z): s.street, s.city, s.state, s.zip = st,ct,stt,z
+
+class Person:
+ def __init__(s,n,a,ad): s.name, s.age, s.address = n,a,ad
+
+class Encoder(json.JSONEncoder):
+ def default(s,o):
+ if hasattr(o,""__dict__""):
+ return {""__t__"":o.__class__.__name__, **o.__dict__}
+ return super().default(o)
+
+def decoder(d):
+ if ""__t__"" in d:
+ cls = {""Address"":Address,""Person"":Person}[d.pop(""__t__"")]
+ return cls(**d)
+ return d",19,19
+,"def Sequential_Search(dlist, item):
+
+ pos = 0
+ found = False
+
+ while pos < len(dlist) and not found:
+ if dlist[pos] == item:
+ found = True
+ else:
+ pos = pos + 1
+
+ return found, pos
+
+print(Sequential_Search([11,23,58,31,56,77,43,12,65,19],31))",0.0,W3RESOURCE,,PYTHON,"def Sequential_Search(dlist, item):
+
+ pos = 0
+ found = False
+
+ while pos < len(dlist) and not found:
+ if dlist[pos] == item:
+ found = True
+ else:
+ pos = pos + 1
+
+ return found, pos
+
+print(Sequential_Search([11,23,58,31,56,77,43,12,65,19],31))",14,14
+,"import os, shutil, argparse
+
+def sync(src, dst):
+ if not os.path.isdir(src) or not os.path.isdir(dst):
+ print(""Invalid source or destination""); return
+ for r,_,fs in os.walk(src):
+ d = os.path.join(dst, os.path.relpath(r, src))
+ os.makedirs(d, exist_ok=True)
+ for f in fs:
+ shutil.copy2(os.path.join(r,f), os.path.join(d,f))
+
+if __name__ == ""__main__"":
+ p = argparse.ArgumentParser()
+ p.add_argument(""src""); p.add_argument(""dst"")
+ a = p.parse_args()
+ sync(a.src, a.dst)
+ print(""Sync complete"")
",1.0,GPT,"GIVE ME A python CODE FOR Command-Line File Synchronizer , make it more shorter for effective to pass all the testcases",PYTHON,"import os, shutil, argparse
+
+def sync(src, dst):
+ if not os.path.isdir(src) or not os.path.isdir(dst):
+ print(""Invalid source or destination""); return
+ for r,_,fs in os.walk(src):
+ d = os.path.join(dst, os.path.relpath(r, src))
+ os.makedirs(d, exist_ok=True)
+ for f in fs:
+ shutil.copy2(os.path.join(r,f), os.path.join(d,f))
+
+if __name__ == ""__main__"":
+ p = argparse.ArgumentParser()
+ p.add_argument(""src""); p.add_argument(""dst"")
+ a = p.parse_args()
+ sync(a.src, a.dst)
+ print(""Sync complete"")",17,17
+,"def Ordered_binary_Search(olist, item):
+
+ if len(olist) == 0:
+ return False
+ else:
+ midpoint = len(olist) // 2
+ if olist[midpoint] == item:
+ return True
+ else:
+ if item < olist[midpoint]:
+ return binarySearch(olist[:midpoint], item)
+ else:
+ return binarySearch(olist[midpoint+1:], item)
+
+def binarySearch(alist, item):
+
+ first = 0
+ last = len(alist) - 1
+ found = False
+
+ while first <= last and not found:
+ midpoint = (first + last) // 2
+ if alist[midpoint] == item:
+ found = True
+ else:
+ if item < alist[midpoint]:
+ last = midpoint - 1
+ else:
+ first = midpoint + 1
+
+ return found
+
+print(Ordered_binary_Search([0, 1, 3, 8, 14, 18, 19, 34, 52], 3))
+print(Ordered_binary_Search([0, 1, 3, 8, 14, 18, 19, 34, 52], 17))",0.0,W3RESOURCE,,PYTHON,"def Ordered_binary_Search(olist, item):
+
+ if len(olist) == 0:
+ return False
+ else:
+ midpoint = len(olist) // 2
+ if olist[midpoint] == item:
+ return True
+ else:
+ if item < olist[midpoint]:
+ return binarySearch(olist[:midpoint], item)
+ else:
+ return binarySearch(olist[midpoint+1:], item)
+
+def binarySearch(alist, item):
+
+ first = 0
+ last = len(alist) - 1
+ found = False
+
+ while first <= last and not found:
+ midpoint = (first + last) // 2
+ if alist[midpoint] == item:
+ found = True
+ else:
+ if item < alist[midpoint]:
+ last = midpoint - 1
+ else:
+ first = midpoint + 1
+
+ return found
+
+print(Ordered_binary_Search([0, 1, 3, 8, 14, 18, 19, 34, 52], 3))
+print(Ordered_binary_Search([0, 1, 3, 8, 14, 18, 19, 34, 52], 17))",34,34
+,"import heapq
+
+def astar(start, goal, g, h):
+ pq = [(h(start), 0, start, [start])]
+ seen = set()
+ while pq:
+ f,c,u,p = heapq.heappop(pq)
+ if u == goal: return p, c
+ if u in seen: continue
+ seen.add(u)
+ for v,w in g[u]:
+ heapq.heappush(pq,(c+w+h(v), c+w, v, p+[v]))
+
+# ---------- INPUT ----------
+graph = {
+ 'A':[('B',1),('C',3)],
+ 'B':[('D',1),('E',4)],
+ 'C':[('F',5)],
+ 'D':[('G',1)],
+ 'E':[('G',1)],
+ 'F':[('G',1)],
+ 'G':[]
+}
+heuristic = {'A':5,'B':4,'C':4,'D':2,'E':2,'F':3,'G':0}
+
+path, cost = astar('A','G',graph,lambda n: heuristic[n])
+
+# ---------- OUTPUT ----------
+print(""Path:"", path)
+print(""Cost:"", cost)
",1.0,GPT,give me the code for A* Search Algorithm in shorter lines to implement it with i/o,PYTHON,"import heapq
+
+def astar(start, goal, g, h):
+ pq = [(h(start), 0, start, [start])]
+ seen = set()
+ while pq:
+ f,c,u,p = heapq.heappop(pq)
+ if u == goal: return p, c
+ if u in seen: continue
+ seen.add(u)
+ for v,w in g[u]:
+ heapq.heappush(pq,(c+w+h(v), c+w, v, p+[v]))
+
+# ---------- INPUT ----------
+graph = {
+ 'A':[('B',1),('C',3)],
+ 'B':[('D',1),('E',4)],
+ 'C':[('F',5)],
+ 'D':[('G',1)],
+ 'E':[('G',1)],
+ 'F':[('G',1)],
+ 'G':[]
+}
+heuristic = {'A':5,'B':4,'C':4,'D':2,'E':2,'F':3,'G':0}
+
+path, cost = astar('A','G',graph,lambda n: heuristic[n])
+
+# ---------- OUTPUT ----------
+print(""Path:"", path)
+print(""Cost:"", cost)",30,30
+,"def bubbleSort(nlist):
+ for passnum in range(len(nlist)-1,0,-1):
+ for i in range(passnum):
+ if nlist[i]>nlist[i+1]:
+ temp = nlist[i]
+ nlist[i] = nlist[i+1]
+ nlist[i+1] = temp
+
+nlist = [14,46,43,27,57,41,45,21,70]
+bubbleSort(nlist)
+print(nlist)",0.0,W3RESOURCE,,PYTHON,"def bubbleSort(nlist):
+ for passnum in range(len(nlist)-1,0,-1):
+ for i in range(passnum):
+ if nlist[i]>nlist[i+1]:
+ temp = nlist[i]
+ nlist[i] = nlist[i+1]
+ nlist[i+1] = temp
+
+nlist = [14,46,43,27,57,41,45,21,70]
+bubbleSort(nlist)
+print(nlist)",11,11
+,"from dataclasses import dataclass, field, fields
+
+class ValidationError(Exception): pass
+
+def vfield(d=None, v=()):
+ return field(default=d, metadata={""v"": v})
+
+def validate(o):
+ for f in fields(o):
+ for fn in f.metadata.get(""v"", ()):
+ if not fn(getattr(o, f.name)):
+ raise ValidationError(f""{f.name} invalid"")
+
+@dataclass
+class User:
+ name: str
+ age: int = vfield(0, v=[lambda x: 0 <= x <= 150])
+ email: str = vfield("""", v=[lambda x: ""@"" in x])
+
+# ---------- INPUT ----------
+u = User(""Arsen"", 30, ""arsen@example.com"")
+
+# ---------- OUTPUT ----------
+try:
+ validate(u)
+ print(""User is valid"")
+except ValidationError as e:
+ print(e)
+",1.0,GPT,write a shorter python code for Data Validation Library with Dataclasses including I/O,PYTHON,"from dataclasses import dataclass, field, fields
+
+class ValidationError(Exception): pass
+
+def vfield(d=None, v=()):
+ return field(default=d, metadata={""v"": v})
+
+def validate(o):
+ for f in fields(o):
+ for fn in f.metadata.get(""v"", ()):
+ if not fn(getattr(o, f.name)):
+ raise ValidationError(f""{f.name} invalid"")
+
+@dataclass
+class User:
+ name: str
+ age: int = vfield(0, v=[lambda x: 0 <= x <= 150])
+ email: str = vfield("""", v=[lambda x: ""@"" in x])
+
+# ---------- INPUT ----------
+u = User(""Arsen"", 30, ""arsen@example.com"")
+
+# ---------- OUTPUT ----------
+try:
+ validate(u)
+ print(""User is valid"")
+except ValidationError as e:
+ print(e)",28,28
+,"def selectionSort(nlist):
+ for fillslot in range(len(nlist)-1,0,-1):
+ maxpos=0
+ for location in range(1,fillslot+1):
+ if nlist[location]>nlist[maxpos]:
+ maxpos = location
+
+ temp = nlist[fillslot]
+ nlist[fillslot] = nlist[maxpos]
+ nlist[maxpos] = temp
+
+nlist = [14,46,43,27,57,41,45,21,70]
+selectionSort(nlist)
+print(nlist)
",0.0,W3RESOURCE,,PYTHON,"def selectionSort(nlist):
+ for fillslot in range(len(nlist)-1,0,-1):
+ maxpos=0
+ for location in range(1,fillslot+1):
+ if nlist[location]>nlist[maxpos]:
+ maxpos = location
+
+ temp = nlist[fillslot]
+ nlist[fillslot] = nlist[maxpos]
+ nlist[maxpos] = temp
+
+nlist = [14,46,43,27,57,41,45,21,70]
+selectionSort(nlist)
+print(nlist)",14,14
+,"from queue import PriorityQueue
+from threading import Thread
+
+q = PriorityQueue()
+
+def producer():
+ for _ in range(int(input(""Items: ""))):
+ x,p = map(int,input(""item priority: "").split())
+ q.put((p,x))
+ q.put((None,None))
+
+def consumer():
+ while (p,x := q.get()) != (None,None):
+ print(""Consumed:"", x)
+
+Thread(target=producer).start()
+Thread(target=consumer).start()
",1.0,GPT,"# Import the queue module to use PriorityQueue import queue # Import the threading module to use threads and locks import threading # Define a class for a thread-safe priority queue class ThreadSafePriorityQueue: def __init__(self): # Initialize a PriorityQueue object to hold the items self._queue = queue.PriorityQueue() # Initialize a lock to ensure thread safety self._lock = threading.Lock() # Method to put an item into the priority queue def put(self, item, priority): # Acquire the lock to ensure thread safety with self._lock: # Put the item into the queue with its priority self._queue.put((priority, item)) # Method to get an item from the priority queue def get(self): # Acquire the lock to ensure thread safety with self._lock: # Check if the queue is not empty if not self._queue.empty(): # Get the item with the highest priority (lowest priority number) priority, item = self._queue.get() # Return the item return item else: # Return None if the queue is empty return None # Example usage to demonstrate the thread-safe priority queue if __name__ == ""__main__"": # Define a producer function to add items to the queue def producer(q): # Add 5 items to the queue with their priority as their value for i in range(5): q.put(i, i) # Define a consumer function to get items from the queue def consumer(q): # Continuously get items from the queue while True: # Get an item from the queue item = q.get() # If the item is None, break the loop (end of processing) if item is None: break # Print the consumed item print(""Consumed:"", item) # Create an instance of the thread-safe priority queue q = ThreadSafePriorityQueue() # Create a producer thread to add items to the queue producer_thread = threading.Thread(target=producer, args=(q,)) # Create a consumer thread to get items from the queue consumer_thread = threading.Thread(target=consumer, args=(q,)) # Start the producer thread producer_thread.start() # Start the consumer thread consumer_thread.start() # Wait for the producer thread to finish producer_thread.join() # Add a sentinel value to the queue to signal the consumer to stop q.put(None, None) # Wait for the consumer thread to finish consumer_thread.join() refer this code and give me the shorter version of this code with minimal lines to implement it efficiently",PYTHON,"from queue import PriorityQueue
+from threading import Thread
+
+q = PriorityQueue()
+
+def producer():
+ for _ in range(int(input(""Items: ""))):
+ x,p = map(int,input(""item priority: "").split())
+ q.put((p,x))
+ q.put((None,None))
+
+def consumer():
+ while (p,x := q.get()) != (None,None):
+ print(""Consumed:"", x)
+
+Thread(target=producer).start()
+Thread(target=consumer).start()",17,17
+,"def insertionSort(nlist):
+ for index in range(1,len(nlist)):
+
+ currentvalue = nlist[index]
+ position = index
+
+ while position>0 and nlist[position-1]>currentvalue:
+ nlist[position]=nlist[position-1]
+ position = position-1
+
+ nlist[position]=currentvalue
+
+nlist = [14,46,43,27,57,41,45,21,70]
+insertionSort(nlist)
+print(nlist)",0.0,W3RESOURCE,,PYTHON,"def insertionSort(nlist):
+ for index in range(1,len(nlist)):
+
+ currentvalue = nlist[index]
+ position = index
+
+ while position>0 and nlist[position-1]>currentvalue:
+ nlist[position]=nlist[position-1]
+ position = position-1
+
+ nlist[position]=currentvalue
+
+nlist = [14,46,43,27,57,41,45,21,70]
+insertionSort(nlist)
+print(nlist)",15,15
+,"def matmul(A, B):
+ return [[sum(a*b for a,b in zip(r,c)) for c in zip(*B)] for r in A]
+
+r1,c1 = map(int,input(""A rows cols: "").split())
+A = [list(map(int,input().split())) for _ in range(r1)]
+
+r2,c2 = map(int,input(""B rows cols: "").split())
+B = [list(map(int,input().split())) for _ in range(r2)]
+
+print(matmul(A,B))
+",1.0,GPT,give me a pythoncode for Matrix Multiplication via List Comprehensions also add a way to give input and get the result of the matrix multiplication within a shorter lines of code,PYTHON,"def matmul(A, B):
+ return [[sum(a*b for a,b in zip(r,c)) for c in zip(*B)] for r in A]
+
+r1,c1 = map(int,input(""A rows cols: "").split())
+A = [list(map(int,input().split())) for _ in range(r1)]
+
+r2,c2 = map(int,input(""B rows cols: "").split())
+B = [list(map(int,input().split())) for _ in range(r2)]
+
+print(matmul(A,B))",10,10
+,"def shellSort(alist):
+ sublistcount = len(alist)//2
+ while sublistcount > 0:
+ for start_position in range(sublistcount):
+ gap_InsertionSort(alist, start_position, sublistcount)
+
+ print(""After increments of size"",sublistcount, ""The list is"",nlist)
+
+ sublistcount = sublistcount // 2
+
+def gap_InsertionSort(nlist,start,gap):
+ for i in range(start+gap,len(nlist),gap):
+
+ current_value = nlist[i]
+ position = i
+
+ while position>=gap and nlist[position-gap]>current_value:
+ nlist[position]=nlist[position-gap]
+ position = position-gap
+
+ nlist[position]=current_value
+
+
+nlist = [14,46,43,27,57,41,45,21,70]
+shellSort(nlist)
+print(nlist)
",0.0,W3RESOURCE,,PYTHON,"def shellSort(alist):
+ sublistcount = len(alist)//2
+ while sublistcount > 0:
+ for start_position in range(sublistcount):
+ gap_InsertionSort(alist, start_position, sublistcount)
+
+ print(""After increments of size"",sublistcount, ""The list is"",nlist)
+
+ sublistcount = sublistcount // 2
+
+def gap_InsertionSort(nlist,start,gap):
+ for i in range(start+gap,len(nlist),gap):
+
+ current_value = nlist[i]
+ position = i
+
+ while position>=gap and nlist[position-gap]>current_value:
+ nlist[position]=nlist[position-gap]
+ position = position-gap
+
+ nlist[position]=current_value
+
+
+nlist = [14,46,43,27,57,41,45,21,70]
+shellSort(nlist)
+print(nlist)",26,26
+,"class Node:
+ def __init__(self, v, kids=None):
+ self.v, self.kids = v, kids or []
+
+ def __iter__(self):
+ stack = [self]
+ while stack:
+ n = stack.pop()
+ yield n.v
+ stack.extend(reversed(n.kids))
",1.0,GPT,give me the shorter lines of python code for Custom Tree Iterator,PYTHON,"class Node:
+ def __init__(self, v, kids=None):
+ self.v, self.kids = v, kids or []
+
+ def __iter__(self):
+ stack = [self]
+ while stack:
+ n = stack.pop()
+ yield n.v
+ stack.extend(reversed(n.kids))",10,10
+,"def mergeSort(nlist):
+ print(""Splitting "",nlist)
+ if len(nlist)>1:
+ mid = len(nlist)//2
+ lefthalf = nlist[:mid]
+ righthalf = nlist[mid:]
+
+ mergeSort(lefthalf)
+ mergeSort(righthalf)
+ i=j=k=0
+ while i < len(lefthalf) and j < len(righthalf):
+ if lefthalf[i] < righthalf[j]:
+ nlist[k]=lefthalf[i]
+ i=i+1
+ else:
+ nlist[k]=righthalf[j]
+ j=j+1
+ k=k+1
+
+ while i < len(lefthalf):
+ nlist[k]=lefthalf[i]
+ i=i+1
+ k=k+1
+
+ while j < len(righthalf):
+ nlist[k]=righthalf[j]
+ j=j+1
+ k=k+1
+ print(""Merging "",nlist)
+
+nlist = [14,46,43,27,57,41,45,21,70]
+mergeSort(nlist)
+print(nlist)
",0.0,W3RESOURCE,,PYTHON,"def mergeSort(nlist):
+ print(""Splitting "",nlist)
+ if len(nlist)>1:
+ mid = len(nlist)//2
+ lefthalf = nlist[:mid]
+ righthalf = nlist[mid:]
+
+ mergeSort(lefthalf)
+ mergeSort(righthalf)
+ i=j=k=0
+ while i < len(lefthalf) and j < len(righthalf):
+ if lefthalf[i] < righthalf[j]:
+ nlist[k]=lefthalf[i]
+ i=i+1
+ else:
+ nlist[k]=righthalf[j]
+ j=j+1
+ k=k+1
+
+ while i < len(lefthalf):
+ nlist[k]=lefthalf[i]
+ i=i+1
+ k=k+1
+
+ while j < len(righthalf):
+ nlist[k]=righthalf[j]
+ j=j+1
+ k=k+1
+ print(""Merging "",nlist)
+
+nlist = [14,46,43,27,57,41,45,21,70]
+mergeSort(nlist)
+print(nlist)",33,33
+,"import time
+
+class Timer:
+ def __init__(self, func):
+ self.func = func
+
+ def __get__(self, obj, objtype=None):
+ return lambda *a, **k: self(obj, *a, **k)
+
+ def __call__(self, obj, *a, **k):
+ t = time.time()
+ r = self.func(obj, *a, **k)
+ print(f""{self.func.__name__}: {time.time()-t:.4f}s"")
+ return r
+",1.0,GPT,"write a python code for Class-Based Decorator for Execution Time , let the code be more shorter .",PYTHON,"import time
+
+class Timer:
+ def __init__(self, func):
+ self.func = func
+
+ def __get__(self, obj, objtype=None):
+ return lambda *a, **k: self(obj, *a, **k)
+
+ def __call__(self, obj, *a, **k):
+ t = time.time()
+ r = self.func(obj, *a, **k)
+ print(f""{self.func.__name__}: {time.time()-t:.4f}s"")
+ return r",14,14
+,"def quickSort(data_list):
+ quickSortHlp(data_list,0,len(data_list)-1)
+
+def quickSortHlp(data_list,first,last):
+ if first < last:
+
+ splitpoint = partition(data_list,first,last)
+
+ quickSortHlp(data_list,first,splitpoint-1)
+ quickSortHlp(data_list,splitpoint+1,last)
+
+
+def partition(data_list,first,last):
+ pivotvalue = data_list[first]
+
+ leftmark = first+1
+ rightmark = last
+
+ done = False
+ while not done:
+
+ while leftmark <= rightmark and data_list[leftmark] <= pivotvalue:
+ leftmark = leftmark + 1
+
+ while data_list[rightmark] >= pivotvalue and rightmark >= leftmark:
+ rightmark = rightmark -1
+
+ if rightmark < leftmark:
+ done = True
+ else:
+ temp = data_list[leftmark]
+ data_list[leftmark] = data_list[rightmark]
+ data_list[rightmark] = temp
+
+ temp = data_list[first]
+ data_list[first] = data_list[rightmark]
+ data_list[rightmark] = temp
+
+
+ return rightmark
+
+data_list = [54,26,93,17,77,31,44,55,20]
+quickSort(data_list)
+print(data_list)",0.0,W3RESOURCE,,PYTHON,"def quickSort(data_list):
+ quickSortHlp(data_list,0,len(data_list)-1)
+
+def quickSortHlp(data_list,first,last):
+ if first < last:
+
+ splitpoint = partition(data_list,first,last)
+
+ quickSortHlp(data_list,first,splitpoint-1)
+ quickSortHlp(data_list,splitpoint+1,last)
+
+
+def partition(data_list,first,last):
+ pivotvalue = data_list[first]
+
+ leftmark = first+1
+ rightmark = last
+
+ done = False
+ while not done:
+
+ while leftmark <= rightmark and data_list[leftmark] <= pivotvalue:
+ leftmark = leftmark + 1
+
+ while data_list[rightmark] >= pivotvalue and rightmark >= leftmark:
+ rightmark = rightmark -1
+
+ if rightmark < leftmark:
+ done = True
+ else:
+ temp = data_list[leftmark]
+ data_list[leftmark] = data_list[rightmark]
+ data_list[rightmark] = temp
+
+ temp = data_list[first]
+ data_list[first] = data_list[rightmark]
+ data_list[rightmark] = temp
+
+
+ return rightmark
+
+data_list = [54,26,93,17,77,31,44,55,20]
+quickSort(data_list)
+print(data_list)",44,44
+,"import requests
+from bs4 import BeautifulSoup
+from concurrent.futures import ThreadPoolExecutor
+from urllib.parse import urljoin
+
+def fetch(url):
+ try:
+ return BeautifulSoup(requests.get(url, timeout=5).text, ""html.parser"")
+ except:
+ return None
+
+def scrape(urls, workers=10):
+ with ThreadPoolExecutor(workers) as t:
+ return [s for s in t.map(fetch, urls) if s]
+
+start = ""https://example.com""
+soup = fetch(start)
+
+links = {urljoin(start, a[""href""]) for a in soup.select(""a[href]"")}
+pages = scrape(links)
+
+for p in pages:
+ print(p.title.string if p.title else ""No title"")
",1.0,GPT,give me the python3 code for multithread webscrapper in an more efficient way with shorter lines of code to implement ,PYTHON,"import requests
+from bs4 import BeautifulSoup
+from concurrent.futures import ThreadPoolExecutor
+from urllib.parse import urljoin
+
+def fetch(url):
+ try:
+ return BeautifulSoup(requests.get(url, timeout=5).text, ""html.parser"")
+ except:
+ return None
+
+def scrape(urls, workers=10):
+ with ThreadPoolExecutor(workers) as t:
+ return [s for s in t.map(fetch, urls) if s]
+
+start = ""https://example.com""
+soup = fetch(start)
+
+links = {urljoin(start, a[""href""]) for a in soup.select(""a[href]"")}
+pages = scrape(links)
+
+for p in pages:
+ print(p.title.string if p.title else ""No title"")",23,23
+,"def counting_sort(array1, max_val):
+ m = max_val + 1
+ count = [0] * m
+
+ for a in array1:
+ # count occurences
+ count[a] += 1
+ i = 0
+ for a in range(m):
+ for c in range(count[a]):
+ array1[i] = a
+ i += 1
+ return array1
+
+print(counting_sort( [1, 2, 7, 3, 2, 1, 4, 2, 3, 2, 1], 7 ))",0.0,GFG,,PYTHON,"def counting_sort(array1, max_val):
+ m = max_val + 1
+ count = [0] * m
+
+ for a in array1:
+ # count occurences
+ count[a] += 1
+ i = 0
+ for a in range(m):
+ for c in range(count[a]):
+ array1[i] = a
+ i += 1
+ return array1
+
+print(counting_sort( [1, 2, 7, 3, 2, 1, 4, 2, 3, 2, 1], 7 ))",15,15
+,"def maxProfit(prices):
+ min_price = float('inf')
+ max_profit = 0
+
+ for price in prices:
+ min_price = min(min_price, price)
+ max_profit = max(max_profit, price - min_price)
+
+ return max_profit
+",1.0,GPT,"You are given an array prices where prices[i] is the price of a stock on day i.
+You may choose one day to buy and a later day to sell.
+Return the maximum profit you can achieve. If no profit is possible, return 0.
+
+Provide:
+- An optimal O(n) solution
+- Explanation of the approach
+- Python implementation",PYTHON,"def maxProfit(prices):
+ min_price = float('inf')
+ max_profit = 0
+
+ for price in prices:
+ min_price = min(min_price, price)
+ max_profit = max(max_profit, price - min_price)
+
+ return max_profit",9,9
+,"class Solution:
+ def maxProfit(self, prices: List[int]) -> int:
+ maxP = 0
+ minBuy = prices[0]
+
+ for sell in prices:
+ maxP = max(maxP, sell - minBuy)
+ minBuy = min(minBuy, sell)
+ return maxP",0.0,GFG,,PYTHON,"class Solution:
+ def maxProfit(self, prices: List[int]) -> int:
+ maxP = 0
+ minBuy = prices[0]
+
+ for sell in prices:
+ maxP = max(maxP, sell - minBuy)
+ minBuy = min(minBuy, sell)
+ return maxP",9,9
+,"from collections import Counter
+
+def topKFrequent(nums, k):
+ count = Counter(nums)
+ buckets = [[] for _ in range(len(nums) + 1)]
+
+ for num, freq in count.items():
+ buckets[freq].append(num)
+
+ res = []
+ for i in range(len(buckets) - 1, 0, -1):
+ for num in buckets[i]:
+ res.append(num)
+ if len(res) == k:
+ return res
+",1.0,GPT,"Given an integer array nums and an integer k, return the k most frequent elements.
+The solution must be better than O(n log n).
+
+Provide:
+- Optimal approach
+- Python code using efficient data structures",PYTHON,"from collections import Counter
+
+def topKFrequent(nums, k):
+ count = Counter(nums)
+ buckets = [[] for _ in range(len(nums) + 1)]
+
+ for num, freq in count.items():
+ buckets[freq].append(num)
+
+ res = []
+ for i in range(len(buckets) - 1, 0, -1):
+ for num in buckets[i]:
+ res.append(num)
+ if len(res) == k:
+ return res",15,15
+,"class Solution:
+ def topKFrequent(self, nums: List[int], k: int) -> List[int]:
+ count = {}
+ freq = [[] for i in range(len(nums) + 1)]
+
+ for num in nums:
+ count[num] = 1 + count.get(num, 0)
+ for num, cnt in count.items():
+ freq[cnt].append(num)
+
+ res = []
+ for i in range(len(freq) - 1, 0, -1):
+ for num in freq[i]:
+ res.append(num)
+ if len(res) == k:
+ return res",0.0,GFG,,PYTHON,"class Solution:
+ def topKFrequent(self, nums: List[int], k: int) -> List[int]:
+ count = {}
+ freq = [[] for i in range(len(nums) + 1)]
+
+ for num in nums:
+ count[num] = 1 + count.get(num, 0)
+ for num, cnt in count.items():
+ freq[cnt].append(num)
+
+ res = []
+ for i in range(len(freq) - 1, 0, -1):
+ for num in freq[i]:
+ res.append(num)
+ if len(res) == k:
+ return res",16,16
+,"def longestConsecutive(nums):
+ num_set = set(nums)
+ longest = 0
+
+ for num in num_set:
+ if num - 1 not in num_set:
+ length = 1
+ while num + length in num_set:
+ length += 1
+ longest = max(longest, length)
+
+ return longest
+",1.0,GPT,"Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
+The solution must run in O(n) time.",PYTHON,"def longestConsecutive(nums):
+ num_set = set(nums)
+ longest = 0
+
+ for num in num_set:
+ if num - 1 not in num_set:
+ length = 1
+ while num + length in num_set:
+ length += 1
+ longest = max(longest, length)
+
+ return longest",12,12
+,"class Solution:
+ def longestConsecutive(self, nums: List[int]) -> int:
+ mp = defaultdict(int)
+ res = 0
+
+ for num in nums:
+ if not mp[num]:
+ mp[num] = mp[num - 1] + mp[num + 1] + 1
+ mp[num - mp[num - 1]] = mp[num]
+ mp[num + mp[num + 1]] = mp[num]
+ res = max(res, mp[num])
+ return res",0.0,GFG,,PYTHON,"class Solution:
+ def longestConsecutive(self, nums: List[int]) -> int:
+ mp = defaultdict(int)
+ res = 0
+
+ for num in nums:
+ if not mp[num]:
+ mp[num] = mp[num - 1] + mp[num + 1] + 1
+ mp[num - mp[num - 1]] = mp[num]
+ mp[num + mp[num + 1]] = mp[num]
+ res = max(res, mp[num])
+ return res",12,12
+,"def twoSum(numbers, target):
+ l, r = 0, len(numbers) - 1
+
+ while l < r:
+ s = numbers[l] + numbers[r]
+ if s == target:
+ return [l + 1, r + 1]
+ elif s < target:
+ l += 1
+ else:
+ r -= 1
+",1.0,GPT,"Given a sorted array of integers and a target,
+return the 1-based indices of the two numbers such that they add up to the target.
+Use only constant extra space.",PYTHON,"def twoSum(numbers, target):
+ l, r = 0, len(numbers) - 1
+
+ while l < r:
+ s = numbers[l] + numbers[r]
+ if s == target:
+ return [l + 1, r + 1]
+ elif s < target:
+ l += 1
+ else:
+ r -= 1",11,11
+,"class Solution:
+ def twoSum(self, numbers: List[int], target: int) -> List[int]:
+ l, r = 0, len(numbers) - 1
+
+ while l < r:
+ curSum = numbers[l] + numbers[r]
+
+ if curSum > target:
+ r -= 1
+ elif curSum < target:
+ l += 1
+ else:
+ return [l + 1, r + 1]
+ return []",0.0,GFG,,PYTHON,"class Solution:
+ def twoSum(self, numbers: List[int], target: int) -> List[int]:
+ l, r = 0, len(numbers) - 1
+
+ while l < r:
+ curSum = numbers[l] + numbers[r]
+
+ if curSum > target:
+ r -= 1
+ elif curSum < target:
+ l += 1
+ else:
+ return [l + 1, r + 1]
+ return []",14,14
+,"def maxArea(height):
+ l, r = 0, len(height) - 1
+ res = 0
+
+ while l < r:
+ res = max(res, min(height[l], height[r]) * (r - l))
+ if height[l] < height[r]:
+ l += 1
+ else:
+ r -= 1
+
+ return res
+",1.0,GPT,"Given an array height, find two lines that together with the x-axis form a container,
+such that the container contains the most water.",PYTHON,"def maxArea(height):
+ l, r = 0, len(height) - 1
+ res = 0
+
+ while l < r:
+ res = max(res, min(height[l], height[r]) * (r - l))
+ if height[l] < height[r]:
+ l += 1
+ else:
+ r -= 1
+
+ return res",12,12
+,"class Solution:
+ def maxArea(self, heights: List[int]) -> int:
+ l, r = 0, len(heights) - 1
+ res = 0
+
+ while l < r:
+ area = min(heights[l], heights[r]) * (r - l)
+ res = max(res, area)
+ if heights[l] <= heights[r]:
+ l += 1
+ else:
+ r -= 1
+ return res",0.0,GFG,,PYTHON,"class Solution:
+ def maxArea(self, heights: List[int]) -> int:
+ l, r = 0, len(heights) - 1
+ res = 0
+
+ while l < r:
+ area = min(heights[l], heights[r]) * (r - l)
+ res = max(res, area)
+ if heights[l] <= heights[r]:
+ l += 1
+ else:
+ r -= 1
+ return res",13,13
+,"def trap(height):
+ l, r = 0, len(height) - 1
+ left_max = right_max = 0
+ res = 0
+
+ while l < r:
+ if height[l] < height[r]:
+ left_max = max(left_max, height[l])
+ res += left_max - height[l]
+ l += 1
+ else:
+ right_max = max(right_max, height[r])
+ res += right_max - height[r]
+ r -= 1
+
+ return res
+",1.0,GPT,"Given an array height representing elevation map,
+compute how much water it can trap after raining.",PYTHON,"def trap(height):
+ l, r = 0, len(height) - 1
+ left_max = right_max = 0
+ res = 0
+
+ while l < r:
+ if height[l] < height[r]:
+ left_max = max(left_max, height[l])
+ res += left_max - height[l]
+ l += 1
+ else:
+ right_max = max(right_max, height[r])
+ res += right_max - height[r]
+ r -= 1
+
+ return res",16,16
+,"class Solution:
+ def trap(self, height: List[int]) -> int:
+ if not height:
+ return 0
+
+ l, r = 0, len(height) - 1
+ leftMax, rightMax = height[l], height[r]
+ res = 0
+ while l < r:
+ if leftMax < rightMax:
+ l += 1
+ leftMax = max(leftMax, height[l])
+ res += leftMax - height[l]
+ else:
+ r -= 1
+ rightMax = max(rightMax, height[r])
+ res += rightMax - height[r]
+ return res",0.0,GFG,,PYTHON,"class Solution:
+ def trap(self, height: List[int]) -> int:
+ if not height:
+ return 0
+
+ l, r = 0, len(height) - 1
+ leftMax, rightMax = height[l], height[r]
+ res = 0
+ while l < r:
+ if leftMax < rightMax:
+ l += 1
+ leftMax = max(leftMax, height[l])
+ res += leftMax - height[l]
+ else:
+ r -= 1
+ rightMax = max(rightMax, height[r])
+ res += rightMax - height[r]
+ return res",18,18
+,"from collections import Counter
+
+def checkInclusion(s1, s2):
+ if len(s1) > len(s2):
+ return False
+
+ s1_count = Counter(s1)
+ window = Counter(s2[:len(s1)])
+
+ if s1_count == window:
+ return True
+
+ for i in range(len(s1), len(s2)):
+ window[s2[i]] += 1
+ window[s2[i - len(s1)]] -= 1
+ if window[s2[i - len(s1)]] == 0:
+ del window[s2[i - len(s1)]]
+ if window == s1_count:
+ return True
+
+ return False
+",1.0,GPT,"Given two strings s1 and s2, return true if s2 contains a permutation of s1.
+Use a sliding window approach.",PYTHON,"from collections import Counter
+
+def checkInclusion(s1, s2):
+ if len(s1) > len(s2):
+ return False
+
+ s1_count = Counter(s1)
+ window = Counter(s2[:len(s1)])
+
+ if s1_count == window:
+ return True
+
+ for i in range(len(s1), len(s2)):
+ window[s2[i]] += 1
+ window[s2[i - len(s1)]] -= 1
+ if window[s2[i - len(s1)]] == 0:
+ del window[s2[i - len(s1)]]
+ if window == s1_count:
+ return True
+
+ return False",21,21
+,"class Solution:
+ def checkInclusion(self, s1: str, s2: str) -> bool:
+ if len(s1) > len(s2):
+ return False
+
+ s1Count, s2Count = [0] * 26, [0] * 26
+ for i in range(len(s1)):
+ s1Count[ord(s1[i]) - ord('a')] += 1
+ s2Count[ord(s2[i]) - ord('a')] += 1
+
+ matches = 0
+ for i in range(26):
+ matches += (1 if s1Count[i] == s2Count[i] else 0)
+
+ l = 0
+ for r in range(len(s1), len(s2)):
+ if matches == 26:
+ return True
+
+ index = ord(s2[r]) - ord('a')
+ s2Count[index] += 1
+ if s1Count[index] == s2Count[index]:
+ matches += 1
+ elif s1Count[index] + 1 == s2Count[index]:
+ matches -= 1
+
+ index = ord(s2[l]) - ord('a')
+ s2Count[index] -= 1
+ if s1Count[index] == s2Count[index]:
+ matches += 1
+ elif s1Count[index] - 1 == s2Count[index]:
+ matches -= 1
+ l += 1
+ return matches == 26",0.0,GFG,,PYTHON,"class Solution:
+ def checkInclusion(self, s1: str, s2: str) -> bool:
+ if len(s1) > len(s2):
+ return False
+
+ s1Count, s2Count = [0] * 26, [0] * 26
+ for i in range(len(s1)):
+ s1Count[ord(s1[i]) - ord('a')] += 1
+ s2Count[ord(s2[i]) - ord('a')] += 1
+
+ matches = 0
+ for i in range(26):
+ matches += (1 if s1Count[i] == s2Count[i] else 0)
+
+ l = 0
+ for r in range(len(s1), len(s2)):
+ if matches == 26:
+ return True
+
+ index = ord(s2[r]) - ord('a')
+ s2Count[index] += 1
+ if s1Count[index] == s2Count[index]:
+ matches += 1
+ elif s1Count[index] + 1 == s2Count[index]:
+ matches -= 1
+
+ index = ord(s2[l]) - ord('a')
+ s2Count[index] -= 1
+ if s1Count[index] == s2Count[index]:
+ matches += 1
+ elif s1Count[index] - 1 == s2Count[index]:
+ matches -= 1
+ l += 1
+ return matches == 26",34,34
+,"from collections import Counter
+
+def minWindow(s, t):
+ if not t or not s:
+ return """"
+
+ t_count = Counter(t)
+ window = {}
+ have, need = 0, len(t_count)
+ res, res_len = [-1, -1], float('inf')
+ l = 0
+
+ for r in range(len(s)):
+ c = s[r]
+ window[c] = window.get(c, 0) + 1
+
+ if c in t_count and window[c] == t_count[c]:
+ have += 1
+
+ while have == need:
+ if (r - l + 1) < res_len:
+ res = [l, r]
+ res_len = r - l + 1
+
+ window[s[l]] -= 1
+ if s[l] in t_count and window[s[l]] < t_count[s[l]]:
+ have -= 1
+ l += 1
+
+ l, r = res
+ return s[l:r+1] if res_len != float('inf') else """"
+",1.0,GPT,"Given strings s and t, return the minimum window in s which contains all characters of t.
+If no such window exists, return an empty string.",PYTHON,"from collections import Counter
+
+def minWindow(s, t):
+ if not t or not s:
+ return """"
+
+ t_count = Counter(t)
+ window = {}
+ have, need = 0, len(t_count)
+ res, res_len = [-1, -1], float('inf')
+ l = 0
+
+ for r in range(len(s)):
+ c = s[r]
+ window[c] = window.get(c, 0) + 1
+
+ if c in t_count and window[c] == t_count[c]:
+ have += 1
+
+ while have == need:
+ if (r - l + 1) < res_len:
+ res = [l, r]
+ res_len = r - l + 1
+
+ window[s[l]] -= 1
+ if s[l] in t_count and window[s[l]] < t_count[s[l]]:
+ have -= 1
+ l += 1
+
+ l, r = res
+ return s[l:r+1] if res_len != float('inf') else """"",31,31
+,"class Solution:
+ def minWindow(self, s: str, t: str) -> str:
+ if t == """":
+ return """"
+
+ countT, window = {}, {}
+ for c in t:
+ countT[c] = 1 + countT.get(c, 0)
+
+ have, need = 0, len(countT)
+ res, resLen = [-1, -1], float(""infinity"")
+ l = 0
+ for r in range(len(s)):
+ c = s[r]
+ window[c] = 1 + window.get(c, 0)
+
+ if c in countT and window[c] == countT[c]:
+ have += 1
+
+ while have == need:
+ if (r - l + 1) < resLen:
+ res = [l, r]
+ resLen = r - l + 1
+
+ window[s[l]] -= 1
+ if s[l] in countT and window[s[l]] < countT[s[l]]:
+ have -= 1
+ l += 1
+ l, r = res
+ return s[l : r + 1] if resLen != float(""infinity"") else """"",0.0,GFG,,PYTHON,"class Solution:
+ def minWindow(self, s: str, t: str) -> str:
+ if t == """":
+ return """"
+
+ countT, window = {}, {}
+ for c in t:
+ countT[c] = 1 + countT.get(c, 0)
+
+ have, need = 0, len(countT)
+ res, resLen = [-1, -1], float(""infinity"")
+ l = 0
+ for r in range(len(s)):
+ c = s[r]
+ window[c] = 1 + window.get(c, 0)
+
+ if c in countT and window[c] == countT[c]:
+ have += 1
+
+ while have == need:
+ if (r - l + 1) < resLen:
+ res = [l, r]
+ resLen = r - l + 1
+
+ window[s[l]] -= 1
+ if s[l] in countT and window[s[l]] < countT[s[l]]:
+ have -= 1
+ l += 1
+ l, r = res
+ return s[l : r + 1] if resLen != float(""infinity"") else """"",30,30
+,"def dailyTemperatures(temperatures):
+ res = [0] * len(temperatures)
+ stack = []
+
+ for i, temp in enumerate(temperatures):
+ while stack and temp > stack[-1][0]:
+ stack_temp, idx = stack.pop()
+ res[idx] = i - idx
+ stack.append((temp, i))
+
+ return res
+",1.0,GPT,"Given an array temperatures, return an array such that each index shows
+how many days until a warmer temperature.
+Use a monotonic stack.",PYTHON,"def dailyTemperatures(temperatures):
+ res = [0] * len(temperatures)
+ stack = []
+
+ for i, temp in enumerate(temperatures):
+ while stack and temp > stack[-1][0]:
+ stack_temp, idx = stack.pop()
+ res[idx] = i - idx
+ stack.append((temp, i))
+
+ return res",11,11
+,"class Solution:
+ def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
+ n = len(temperatures)
+ res = [0] * n
+
+ for i in range(n - 2, -1, -1):
+ j = i + 1
+ while j < n and temperatures[j] <= temperatures[i]:
+ if res[j] == 0:
+ j = n
+ break
+ j += res[j]
+
+ if j < n:
+ res[i] = j - i
+ return res",0.0,GFG,,PYTHON,"class Solution:
+ def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
+ n = len(temperatures)
+ res = [0] * n
+
+ for i in range(n - 2, -1, -1):
+ j = i + 1
+ while j < n and temperatures[j] <= temperatures[i]:
+ if res[j] == 0:
+ j = n
+ break
+ j += res[j]
+
+ if j < n:
+ res[i] = j - i
+ return res",16,16
+,"def carFleet(target, position, speed):
+ cars = sorted(zip(position, speed), reverse=True)
+ stack = []
+
+ for pos, spd in cars:
+ time = (target - pos) / spd
+ if not stack or time > stack[-1]:
+ stack.append(time)
+
+ return len(stack)
+",1.0,GPT,"Given target, position, and speed arrays,
+return the number of car fleets that will arrive at the destination.",PYTHON,"def carFleet(target, position, speed):
+ cars = sorted(zip(position, speed), reverse=True)
+ stack = []
+
+ for pos, spd in cars:
+ time = (target - pos) / spd
+ if not stack or time > stack[-1]:
+ stack.append(time)
+
+ return len(stack)",10,10
+,"class Solution:
+ def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
+ pair = [(p, s) for p, s in zip(position, speed)]
+ pair.sort(reverse=True)
+
+ fleets = 1
+ prevTime = (target - pair[0][0]) / pair[0][1]
+ for i in range(1, len(pair)):
+ currCar = pair[i]
+ currTime = (target - currCar[0]) / currCar[1]
+ if currTime > prevTime:
+ fleets += 1
+ prevTime = currTime
+ return fleets",0.0,GFG,,PYTHON,"class Solution:
+ def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
+ pair = [(p, s) for p, s in zip(position, speed)]
+ pair.sort(reverse=True)
+
+ fleets = 1
+ prevTime = (target - pair[0][0]) / pair[0][1]
+ for i in range(1, len(pair)):
+ currCar = pair[i]
+ currTime = (target - currCar[0]) / currCar[1]
+ if currTime > prevTime:
+ fleets += 1
+ prevTime = currTime
+ return fleets",14,14
+,"import math
+
+def minEatingSpeed(piles, h):
+ l, r = 1, max(piles)
+
+ while l < r:
+ m = (l + r) // 2
+ hours = sum(math.ceil(p / m) for p in piles)
+ if hours <= h:
+ r = m
+ else:
+ l = m + 1
+
+ return l
+",1.0,GPT,"Given an array piles where piles[i] is the number of bananas in the ith pile,
+and an integer h representing hours,
+find the minimum integer eating speed k such that Koko can eat all bananas within h hours.",PYTHON,"import math
+
+def minEatingSpeed(piles, h):
+ l, r = 1, max(piles)
+
+ while l < r:
+ m = (l + r) // 2
+ hours = sum(math.ceil(p / m) for p in piles)
+ if hours <= h:
+ r = m
+ else:
+ l = m + 1
+
+ return l",14,14
+,"class Solution:
+ def minEatingSpeed(self, piles: List[int], h: int) -> int:
+ l, r = 1, max(piles)
+ res = r
+
+ while l <= r:
+ k = (l + r) // 2
+
+ totalTime = 0
+ for p in piles:
+ totalTime += math.ceil(float(p) / k)
+ if totalTime <= h:
+ res = k
+ r = k - 1
+ else:
+ l = k + 1
+ return res",0.0,GFG,,PYTHON,"class Solution:
+ def minEatingSpeed(self, piles: List[int], h: int) -> int:
+ l, r = 1, max(piles)
+ res = r
+
+ while l <= r:
+ k = (l + r) // 2
+
+ totalTime = 0
+ for p in piles:
+ totalTime += math.ceil(float(p) / k)
+ if totalTime <= h:
+ res = k
+ r = k - 1
+ else:
+ l = k + 1
+ return res",17,17
+,"def searchMatrix(matrix, target):
+ if not matrix or not matrix[0]:
+ return False
+
+ rows, cols = len(matrix), len(matrix[0])
+ l, r = 0, rows * cols - 1
+
+ while l <= r:
+ m = (l + r) // 2
+ val = matrix[m // cols][m % cols]
+ if val == target:
+ return True
+ elif val < target:
+ l = m + 1
+ else:
+ r = m - 1
+
+ return False
+",1.0,GPT,"Solve the problem ""Search a 2D Matrix"".
+
+The matrix has the following properties:
+- Integers in each row are sorted
+- First integer of each row is greater than the last integer of the previous row
+
+Given a target, return true if found.
+
+Provide O(log(m*n)) Python solution.
+",PYTHON,"def searchMatrix(matrix, target):
+ if not matrix or not matrix[0]:
+ return False
+
+ rows, cols = len(matrix), len(matrix[0])
+ l, r = 0, rows * cols - 1
+
+ while l <= r:
+ m = (l + r) // 2
+ val = matrix[m // cols][m % cols]
+ if val == target:
+ return True
+ elif val < target:
+ l = m + 1
+ else:
+ r = m - 1
+
+ return False",18,18
+,"class Solution:
+ def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
+ ROWS, COLS = len(matrix), len(matrix[0])
+
+ l, r = 0, ROWS * COLS - 1
+ while l <= r:
+ m = l + (r - l) // 2
+ row, col = m // COLS, m % COLS
+ if target > matrix[row][col]:
+ l = m + 1
+ elif target < matrix[row][col]:
+ r = m - 1
+ else:
+ return True
+ return False",0.0,GFG,,PYTHON,"class Solution:
+ def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
+ ROWS, COLS = len(matrix), len(matrix[0])
+
+ l, r = 0, ROWS * COLS - 1
+ while l <= r:
+ m = l + (r - l) // 2
+ row, col = m // COLS, m % COLS
+ if target > matrix[row][col]:
+ l = m + 1
+ elif target < matrix[row][col]:
+ r = m - 1
+ else:
+ return True
+ return False",15,15
+,"def findMedianSortedArrays(nums1, nums2):
+ A, B = nums1, nums2
+ if len(A) > len(B):
+ A, B = B, A
+
+ total = len(A) + len(B)
+ half = total // 2
+ l, r = 0, len(A)
+
+ while True:
+ i = (l + r) // 2
+ j = half - i
+
+ Aleft = A[i - 1] if i > 0 else float('-inf')
+ Aright = A[i] if i < len(A) else float('inf')
+ Bleft = B[j - 1] if j > 0 else float('-inf')
+ Bright = B[j] if j < len(B) else float('inf')
+
+ if Aleft <= Bright and Bleft <= Aright:
+ if total % 2:
+ return min(Aright, Bright)
+ return (max(Aleft, Bleft) + min(Aright, Bright)) / 2
+ elif Aleft > Bright:
+ r = i - 1
+ else:
+ l = i + 1
+",1.0,GPT,"Solve the problem ""Median of Two Sorted Arrays"".
+
+Given two sorted arrays nums1 and nums2,
+return the median of the two sorted arrays.
+The overall time complexity must be O(log(min(n, m))).",PYTHON,"def findMedianSortedArrays(nums1, nums2):
+ A, B = nums1, nums2
+ if len(A) > len(B):
+ A, B = B, A
+
+ total = len(A) + len(B)
+ half = total // 2
+ l, r = 0, len(A)
+
+ while True:
+ i = (l + r) // 2
+ j = half - i
+
+ Aleft = A[i - 1] if i > 0 else float('-inf')
+ Aright = A[i] if i < len(A) else float('inf')
+ Bleft = B[j - 1] if j > 0 else float('-inf')
+ Bright = B[j] if j < len(B) else float('inf')
+
+ if Aleft <= Bright and Bleft <= Aright:
+ if total % 2:
+ return min(Aright, Bright)
+ return (max(Aleft, Bleft) + min(Aright, Bright)) / 2
+ elif Aleft > Bright:
+ r = i - 1
+ else:
+ l = i + 1",26,26
+,"class Solution:
+ def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
+ A, B = nums1, nums2
+ total = len(nums1) + len(nums2)
+ half = total // 2
+
+ if len(B) < len(A):
+ A, B = B, A
+
+ l, r = 0, len(A) - 1
+ while True:
+ i = (l + r) // 2
+ j = half - i - 2
+
+ Aleft = A[i] if i >= 0 else float(""-infinity"")
+ Aright = A[i + 1] if (i + 1) < len(A) else float(""infinity"")
+ Bleft = B[j] if j >= 0 else float(""-infinity"")
+ Bright = B[j + 1] if (j + 1) < len(B) else float(""infinity"")
+
+ if Aleft <= Bright and Bleft <= Aright:
+ if total % 2:
+ return min(Aright, Bright)
+ return (max(Aleft, Bleft) + min(Aright, Bright)) / 2
+ elif Aleft > Bright:
+ r = i - 1
+ else:
+ l = i + 1",0.0,GFG,,PYTHON,"class Solution:
+ def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
+ A, B = nums1, nums2
+ total = len(nums1) + len(nums2)
+ half = total // 2
+
+ if len(B) < len(A):
+ A, B = B, A
+
+ l, r = 0, len(A) - 1
+ while True:
+ i = (l + r) // 2
+ j = half - i - 2
+
+ Aleft = A[i] if i >= 0 else float(""-infinity"")
+ Aright = A[i + 1] if (i + 1) < len(A) else float(""infinity"")
+ Bleft = B[j] if j >= 0 else float(""-infinity"")
+ Bright = B[j + 1] if (j + 1) < len(B) else float(""infinity"")
+
+ if Aleft <= Bright and Bleft <= Aright:
+ if total % 2:
+ return min(Aright, Bright)
+ return (max(Aleft, Bleft) + min(Aright, Bright)) / 2
+ elif Aleft > Bright:
+ r = i - 1
+ else:
+ l = i + 1",27,27
+,"def reverseList(head):
+ prev = None
+ curr = head
+
+ while curr:
+ nxt = curr.next
+ curr.next = prev
+ prev = curr
+ curr = nxt
+
+ return prev
+",1.0,GPT,"Solve the problem ""Reverse a Linked List"".
+
+Given the head of a singly linked list,
+reverse the list and return the new head.",PYTHON,"def reverseList(head):
+ prev = None
+ curr = head
+
+ while curr:
+ nxt = curr.next
+ curr.next = prev
+ prev = curr
+ curr = nxt
+
+ return prev",11,11
+,"# Definition for singly-linked list.
+# class ListNode:
+# def __init__(self, val=0, next=None):
+# self.val = val
+# self.next = next
+
+class Solution:
+ def reverseList(self, head: ListNode) -> ListNode:
+ prev, curr = None, head
+
+ while curr:
+ temp = curr.next
+ curr.next = prev
+ prev = curr
+ curr = temp
+ return prev",0.0,GFG,,PYTHON,"# Definition for singly-linked list.
+# class ListNode:
+# def __init__(self, val=0, next=None):
+# self.val = val
+# self.next = next
+
+class Solution:
+ def reverseList(self, head: ListNode) -> ListNode:
+ prev, curr = None, head
+
+ while curr:
+ temp = curr.next
+ curr.next = prev
+ prev = curr
+ curr = temp
+ return prev",16,16
+,"def reorderList(head):
+ if not head:
+ return
+
+ slow, fast = head, head
+ while fast and fast.next:
+ slow = slow.next
+ fast = fast.next.next
+
+ prev, curr = None, slow.next
+ slow.next = None
+
+ while curr:
+ nxt = curr.next
+ curr.next = prev
+ prev = curr
+ curr = nxt
+
+ first, second = head, prev
+ while second:
+ tmp1, tmp2 = first.next, second.next
+ first.next = second
+ second.next = tmp1
+ first, second = tmp1, tmp2
+",1.0,GPT,"Solve the problem ""Reorder Linked List"".
+
+Reorder the list as:
+L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …
+
+Do it in-place with O(1) extra space.
+",PYTHON,"def reorderList(head):
+ if not head:
+ return
+
+ slow, fast = head, head
+ while fast and fast.next:
+ slow = slow.next
+ fast = fast.next.next
+
+ prev, curr = None, slow.next
+ slow.next = None
+
+ while curr:
+ nxt = curr.next
+ curr.next = prev
+ prev = curr
+ curr = nxt
+
+ first, second = head, prev
+ while second:
+ tmp1, tmp2 = first.next, second.next
+ first.next = second
+ second.next = tmp1
+ first, second = tmp1, tmp2",24,24
+,"# Definition for singly-linked list.
+# class ListNode:
+# def __init__(self, val=0, next=None):
+# self.val = val
+# self.next = next
+
+class Solution:
+ def reorderList(self, head: Optional[ListNode]) -> None:
+ slow, fast = head, head.next
+ while fast and fast.next:
+ slow = slow.next
+ fast = fast.next.next
+
+ second = slow.next
+ prev = slow.next = None
+ while second:
+ tmp = second.next
+ second.next = prev
+ prev = second
+ second = tmp
+
+ first, second = head, prev
+ while second:
+ tmp1, tmp2 = first.next, second.next
+ first.next = second
+ second.next = tmp1
+ first, second = tmp1, tmp2",0.0,GFG,,PYTHON,"# Definition for singly-linked list.
+# class ListNode:
+# def __init__(self, val=0, next=None):
+# self.val = val
+# self.next = next
+
+class Solution:
+ def reorderList(self, head: Optional[ListNode]) -> None:
+ slow, fast = head, head.next
+ while fast and fast.next:
+ slow = slow.next
+ fast = fast.next.next
+
+ second = slow.next
+ prev = slow.next = None
+ while second:
+ tmp = second.next
+ second.next = prev
+ prev = second
+ second = tmp
+
+ first, second = head, prev
+ while second:
+ tmp1, tmp2 = first.next, second.next
+ first.next = second
+ second.next = tmp1
+ first, second = tmp1, tmp2",27,27
+,"def findDuplicate(nums):
+ slow = fast = nums[0]
+
+ while True:
+ slow = nums[slow]
+ fast = nums[nums[fast]]
+ if slow == fast:
+ break
+
+ slow = nums[0]
+ while slow != fast:
+ slow = nums[slow]
+ fast = nums[fast]
+
+ return slow
+",1.0,GPT,"Solve the problem ""Find the Duplicate Number"".
+
+Given an array nums containing n+1 integers where each integer is in the range [1, n],
+return the duplicate number without modifying the array
+and using constant extra space.
+
+Provide Python solution using cycle detection.
+",PYTHON,"def findDuplicate(nums):
+ slow = fast = nums[0]
+
+ while True:
+ slow = nums[slow]
+ fast = nums[nums[fast]]
+ if slow == fast:
+ break
+
+ slow = nums[0]
+ while slow != fast:
+ slow = nums[slow]
+ fast = nums[fast]
+
+ return slow",15,15
+,"class Solution:
+ def findDuplicate(self, nums: List[int]) -> int:
+ slow, fast = 0, 0
+ while True:
+ slow = nums[slow]
+ fast = nums[nums[fast]]
+ if slow == fast:
+ break
+
+ slow2 = 0
+ while True:
+ slow = nums[slow]
+ slow2 = nums[slow2]
+ if slow == slow2:
+ return slow",0.0,GFG,,PYTHON,"class Solution:
+ def findDuplicate(self, nums: List[int]) -> int:
+ slow, fast = 0, 0
+ while True:
+ slow = nums[slow]
+ fast = nums[nums[fast]]
+ if slow == fast:
+ break
+
+ slow2 = 0
+ while True:
+ slow = nums[slow]
+ slow2 = nums[slow2]
+ if slow == slow2:
+ return slow",15,15
+,"def mergeTwoLists(l1, l2):
+ dummy = curr = ListNode(0)
+
+ while l1 and l2:
+ if l1.val < l2.val:
+ curr.next = l1
+ l1 = l1.next
+ else:
+ curr.next = l2
+ l2 = l2.next
+ curr = curr.next
+
+ curr.next = l1 or l2
+ return dummy.next
+",1.0,GPT,"Solve the problem ""Merge Two Sorted Linked Lists"".
+
+Given two sorted linked lists,
+merge them into one sorted list and return its head.",PYTHON,"def mergeTwoLists(l1, l2):
+ dummy = curr = ListNode(0)
+
+ while l1 and l2:
+ if l1.val < l2.val:
+ curr.next = l1
+ l1 = l1.next
+ else:
+ curr.next = l2
+ l2 = l2.next
+ curr = curr.next
+
+ curr.next = l1 or l2
+ return dummy.next",14,14
+,"# Definition for singly-linked list.
+# class ListNode:
+# def __init__(self, val=0, next=None):
+# self.val = val
+# self.next = next
+
+class Solution:
+ def mergeTwoLists(self, list1: ListNode, list2: ListNode) -> ListNode:
+ dummy = node = ListNode()
+
+ while list1 and list2:
+ if list1.val < list2.val:
+ node.next = list1
+ list1 = list1.next
+ else:
+ node.next = list2
+ list2 = list2.next
+ node = node.next
+
+ node.next = list1 or list2
+
+ return dummy.next",0.0,GFG,,PYTHON,"# Definition for singly-linked list.
+# class ListNode:
+# def __init__(self, val=0, next=None):
+# self.val = val
+# self.next = next
+
+class Solution:
+ def mergeTwoLists(self, list1: ListNode, list2: ListNode) -> ListNode:
+ dummy = node = ListNode()
+
+ while list1 and list2:
+ if list1.val < list2.val:
+ node.next = list1
+ list1 = list1.next
+ else:
+ node.next = list2
+ list2 = list2.next
+ node = node.next
+
+ node.next = list1 or list2
+
+ return dummy.next",22,22
+,"def reverseKGroup(head, k):
+ dummy = ListNode(0)
+ dummy.next = head
+ prev = dummy
+
+ while True:
+ kth = prev
+ for _ in range(k):
+ kth = kth.next
+ if not kth:
+ return dummy.next
+
+ nxt = kth.next
+ curr = prev.next
+
+ for _ in range(k):
+ tmp = curr.next
+ curr.next = nxt
+ nxt = curr
+ curr = tmp
+
+ tmp = prev.next
+ prev.next = kth
+ prev = tmp
+",1.0,GPT,"Solve the problem ""Reverse Nodes in K-Group"".
+
+Given a linked list, reverse the nodes of the list k at a time.
+If the number of nodes is not a multiple of k, leave them as is.
+
+Provide Python solution.
+",PYTHON,"def reverseKGroup(head, k):
+ dummy = ListNode(0)
+ dummy.next = head
+ prev = dummy
+
+ while True:
+ kth = prev
+ for _ in range(k):
+ kth = kth.next
+ if not kth:
+ return dummy.next
+
+ nxt = kth.next
+ curr = prev.next
+
+ for _ in range(k):
+ tmp = curr.next
+ curr.next = nxt
+ nxt = curr
+ curr = tmp
+
+ tmp = prev.next
+ prev.next = kth
+ prev = tmp",24,24
+,"# Definition for singly-linked list.
+# class ListNode:
+# def __init__(self, val=0, next=None):
+# self.val = val
+# self.next = next
+
+class Solution:
+ def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
+ dummy = ListNode(0, head)
+ groupPrev = dummy
+
+ while True:
+ kth = self.getKth(groupPrev, k)
+ if not kth:
+ break
+ groupNext = kth.next
+
+ prev, curr = kth.next, groupPrev.next
+ while curr != groupNext:
+ tmp = curr.next
+ curr.next = prev
+ prev = curr
+ curr = tmp
+
+ tmp = groupPrev.next
+ groupPrev.next = kth
+ groupPrev = tmp
+ return dummy.next
+
+ def getKth(self, curr, k):
+ while curr and k > 0:
+ curr = curr.next
+ k -= 1
+ return curr",0.0,GFG,,PYTHON,"# Definition for singly-linked list.
+# class ListNode:
+# def __init__(self, val=0, next=None):
+# self.val = val
+# self.next = next
+
+class Solution:
+ def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
+ dummy = ListNode(0, head)
+ groupPrev = dummy
+
+ while True:
+ kth = self.getKth(groupPrev, k)
+ if not kth:
+ break
+ groupNext = kth.next
+
+ prev, curr = kth.next, groupPrev.next
+ while curr != groupNext:
+ tmp = curr.next
+ curr.next = prev
+ prev = curr
+ curr = tmp
+
+ tmp = groupPrev.next
+ groupPrev.next = kth
+ groupPrev = tmp
+ return dummy.next
+
+ def getKth(self, curr, k):
+ while curr and k > 0:
+ curr = curr.next
+ k -= 1
+ return curr",34,34
+,"def invertTree(root):
+ if not root:
+ return None
+
+ root.left, root.right = invertTree(root.right), invertTree(root.left)
+ return root
+",1.0,GPT,"Solve the problem ""Invert Binary Tree"".
+
+Given the root of a binary tree,
+invert the tree and return its root.
+
+Provide Python solution.
+",PYTHON,"def invertTree(root):
+ if not root:
+ return None
+
+ root.left, root.right = invertTree(root.right), invertTree(root.left)
+ return root",6,6
+,"# Definition for a binary tree node.
+# class TreeNode:
+# def __init__(self, val=0, left=None, right=None):
+# self.val = val
+# self.left = left
+# self.right = right
+
+class Solution:
+ def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
+ if not root:
+ return None
+ stack = [root]
+ while stack:
+ node = stack.pop()
+ node.left, node.right = node.right, node.left
+ if node.left:
+ stack.append(node.left)
+ if node.right:
+ stack.append(node.right)
+ return root",0.0,GFG,,PYTHON,"# Definition for a binary tree node.
+# class TreeNode:
+# def __init__(self, val=0, left=None, right=None):
+# self.val = val
+# self.left = left
+# self.right = right
+
+class Solution:
+ def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
+ if not root:
+ return None
+ stack = [root]
+ while stack:
+ node = stack.pop()
+ node.left, node.right = node.right, node.left
+ if node.left:
+ stack.append(node.left)
+ if node.right:
+ stack.append(node.right)
+ return root",20,20
+,"def isBalanced(root):
+ def dfs(node):
+ if not node:
+ return 0
+
+ left = dfs(node.left)
+ if left == -1:
+ return -1
+ right = dfs(node.right)
+ if right == -1:
+ return -1
+
+ if abs(left - right) > 1:
+ return -1
+
+ return 1 + max(left, right)
+
+ return dfs(root) != -1
+",1.0,GPT,"Solve the problem ""Balanced Binary Tree"".
+
+Given a binary tree,
+determine if it is height-balanced.
+
+Provide Python solution.
+",PYTHON,"def isBalanced(root):
+ def dfs(node):
+ if not node:
+ return 0
+
+ left = dfs(node.left)
+ if left == -1:
+ return -1
+ right = dfs(node.right)
+ if right == -1:
+ return -1
+
+ if abs(left - right) > 1:
+ return -1
+
+ return 1 + max(left, right)
+
+ return dfs(root) != -1",18,18
+,"# Definition for a binary tree node.
+# class TreeNode:
+# def __init__(self, val=0, left=None, right=None):
+# self.val = val
+# self.left = left
+# self.right = right
+
+class Solution:
+ def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
+ if not root:
+ return None
+ stack = [root]
+ while stack:
+ node = stack.pop()
+ node.left, node.right = node.right, node.left
+ if node.left:
+ stack.append(node.left)
+ if node.right:
+ stack.append(node.right)
+ return root",0.0,GFG,,PYTHON,"# Definition for a binary tree node.
+# class TreeNode:
+# def __init__(self, val=0, left=None, right=None):
+# self.val = val
+# self.left = left
+# self.right = right
+
+class Solution:
+ def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
+ if not root:
+ return None
+ stack = [root]
+ while stack:
+ node = stack.pop()
+ node.left, node.right = node.right, node.left
+ if node.left:
+ stack.append(node.left)
+ if node.right:
+ stack.append(node.right)
+ return root",20,20
+,"def isSubtree(root, subRoot):
+ def isSame(a, b):
+ if not a and not b:
+ return True
+ if not a or not b or a.val != b.val:
+ return False
+ return isSame(a.left, b.left) and isSame(a.right, b.right)
+
+ if not root:
+ return False
+ if isSame(root, subRoot):
+ return True
+ return isSubtree(root.left, subRoot) or isSubtree(root.right, subRoot)
+",1.0,GPT,"Solve the problem ""Subtree of Another Tree"".
+
+Given the roots of two binary trees root and subRoot,
+return true if there is a subtree of root with the same structure and values as subRoot.
+
+Provide Python solution.
+",PYTHON,"def isSubtree(root, subRoot):
+ def isSame(a, b):
+ if not a and not b:
+ return True
+ if not a or not b or a.val != b.val:
+ return False
+ return isSame(a.left, b.left) and isSame(a.right, b.right)
+
+ if not root:
+ return False
+ if isSame(root, subRoot):
+ return True
+ return isSubtree(root.left, subRoot) or isSubtree(root.right, subRoot)",13,13
+,"# Definition for a binary tree node.
+# class TreeNode:
+# def __init__(self, val=0, left=None, right=None):
+# self.val = val
+# self.left = left
+# self.right = right
+
+class Solution:
+ def serialize(self, root: Optional[TreeNode]) -> str:
+ if root == None:
+ return ""$#""
+
+ return (""$"" + str(root.val) + self.serialize(root.left) + self.serialize(root.right))
+
+ def z_function(self, s: str) -> list:
+ z = [0] * len(s)
+ l, r, n = 0, 0, len(s)
+ for i in range(1, n):
+ if i <= r:
+ z[i] = min(r - i + 1, z[i - l])
+ while i + z[i] < n and s[z[i]] == s[i + z[i]]:
+ z[i] += 1
+ if i + z[i] - 1 > r:
+ l, r = i, i + z[i] - 1
+ return z
+
+ def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
+ serialized_root = self.serialize(root)
+ serialized_subRoot = self.serialize(subRoot)
+ combined = serialized_subRoot + ""|"" + serialized_root
+
+ z_values = self.z_function(combined)
+ sub_len = len(serialized_subRoot)
+
+ for i in range(sub_len + 1, len(combined)):
+ if z_values[i] == sub_len:
+ return True
+ return False",0.0,GFG,,PYTHON,"# Definition for a binary tree node.
+# class TreeNode:
+# def __init__(self, val=0, left=None, right=None):
+# self.val = val
+# self.left = left
+# self.right = right
+
+class Solution:
+ def serialize(self, root: Optional[TreeNode]) -> str:
+ if root == None:
+ return ""$#""
+
+ return (""$"" + str(root.val) + self.serialize(root.left) + self.serialize(root.right))
+
+ def z_function(self, s: str) -> list:
+ z = [0] * len(s)
+ l, r, n = 0, 0, len(s)
+ for i in range(1, n):
+ if i <= r:
+ z[i] = min(r - i + 1, z[i - l])
+ while i + z[i] < n and s[z[i]] == s[i + z[i]]:
+ z[i] += 1
+ if i + z[i] - 1 > r:
+ l, r = i, i + z[i] - 1
+ return z
+
+ def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
+ serialized_root = self.serialize(root)
+ serialized_subRoot = self.serialize(subRoot)
+ combined = serialized_subRoot + ""|"" + serialized_root
+
+ z_values = self.z_function(combined)
+ sub_len = len(serialized_subRoot)
+
+ for i in range(sub_len + 1, len(combined)):
+ if z_values[i] == sub_len:
+ return True
+ return False",38,38
+,"from collections import deque
+
+def levelOrder(root):
+ if not root:
+ return []
+
+ res = []
+ q = deque([root])
+
+ while q:
+ level = []
+ for _ in range(len(q)):
+ node = q.popleft()
+ level.append(node.val)
+ if node.left:
+ q.append(node.left)
+ if node.right:
+ q.append(node.right)
+ res.append(level)
+
+ return res
+",1.0,GPT,"Solve the problem ""Binary Tree Level Order Traversal"".
+
+Given the root of a binary tree,
+return the level order traversal of its nodes' values.
+
+Provide Python solution using BFS.
+",PYTHON,"from collections import deque
+
+def levelOrder(root):
+ if not root:
+ return []
+
+ res = []
+ q = deque([root])
+
+ while q:
+ level = []
+ for _ in range(len(q)):
+ node = q.popleft()
+ level.append(node.val)
+ if node.left:
+ q.append(node.left)
+ if node.right:
+ q.append(node.right)
+ res.append(level)
+
+ return res",21,21
+,"# Definition for a binary tree node.
+# class TreeNode:
+# def __init__(self, val=0, left=None, right=None):
+# self.val = val
+# self.left = left
+# self.right = right
+
+class Solution:
+ def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
+ res = []
+
+ q = collections.deque()
+ q.append(root)
+
+ while q:
+ qLen = len(q)
+ level = []
+ for i in range(qLen):
+ node = q.popleft()
+ if node:
+ level.append(node.val)
+ q.append(node.left)
+ q.append(node.right)
+ if level:
+ res.append(level)
+
+ return res",0.0,GFG,,PYTHON,"# Definition for a binary tree node.
+# class TreeNode:
+# def __init__(self, val=0, left=None, right=None):
+# self.val = val
+# self.left = left
+# self.right = right
+
+class Solution:
+ def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
+ res = []
+
+ q = collections.deque()
+ q.append(root)
+
+ while q:
+ qLen = len(q)
+ level = []
+ for i in range(qLen):
+ node = q.popleft()
+ if node:
+ level.append(node.val)
+ q.append(node.left)
+ q.append(node.right)
+ if level:
+ res.append(level)
+
+ return res",27,27
+,"def exist(board, word):
+ rows, cols = len(board), len(board[0])
+
+ def dfs(r, c, i):
+ if i == len(word):
+ return True
+ if r < 0 or c < 0 or r >= rows or c >= cols or board[r][c] != word[i]:
+ return False
+
+ tmp = board[r][c]
+ board[r][c] = ""#""
+ found = (dfs(r+1, c, i+1) or dfs(r-1, c, i+1) or
+ dfs(r, c+1, i+1) or dfs(r, c-1, i+1))
+ board[r][c] = tmp
+ return found
+
+ for r in range(rows):
+ for c in range(cols):
+ if dfs(r, c, 0):
+ return True
+ return False
+",1.0,GPT,"Solve the problem ""Word Search"".
+
+Given a 2D board of characters and a word,
+return true if the word exists in the grid.
+The word can be constructed from adjacent cells
+(horizontal or vertical) without reusing a cell.",PYTHON,"def exist(board, word):
+ rows, cols = len(board), len(board[0])
+
+ def dfs(r, c, i):
+ if i == len(word):
+ return True
+ if r < 0 or c < 0 or r >= rows or c >= cols or board[r][c] != word[i]:
+ return False
+
+ tmp = board[r][c]
+ board[r][c] = ""#""
+ found = (dfs(r+1, c, i+1) or dfs(r-1, c, i+1) or
+ dfs(r, c+1, i+1) or dfs(r, c-1, i+1))
+ board[r][c] = tmp
+ return found
+
+ for r in range(rows):
+ for c in range(cols):
+ if dfs(r, c, 0):
+ return True
+ return False",21,21
+,"class Solution:
+ def exist(self, board: List[List[str]], word: str) -> bool:
+ ROWS, COLS = len(board), len(board[0])
+
+ def dfs(r, c, i):
+ if i == len(word):
+ return True
+ if (r < 0 or c < 0 or r >= ROWS or c >= COLS or
+ word[i] != board[r][c] or board[r][c] == '#'):
+ return False
+
+ board[r][c] = '#'
+ res = (dfs(r + 1, c, i + 1) or
+ dfs(r - 1, c, i + 1) or
+ dfs(r, c + 1, i + 1) or
+ dfs(r, c - 1, i + 1))
+ board[r][c] = word[i]
+ return res
+
+ for r in range(ROWS):
+ for c in range(COLS):
+ if dfs(r, c, 0):
+ return True
+ return False",0.0,GFG,,PYTHON,"class Solution:
+ def exist(self, board: List[List[str]], word: str) -> bool:
+ ROWS, COLS = len(board), len(board[0])
+
+ def dfs(r, c, i):
+ if i == len(word):
+ return True
+ if (r < 0 or c < 0 or r >= ROWS or c >= COLS or
+ word[i] != board[r][c] or board[r][c] == '#'):
+ return False
+
+ board[r][c] = '#'
+ res = (dfs(r + 1, c, i + 1) or
+ dfs(r - 1, c, i + 1) or
+ dfs(r, c + 1, i + 1) or
+ dfs(r, c - 1, i + 1))
+ board[r][c] = word[i]
+ return res
+
+ for r in range(ROWS):
+ for c in range(COLS):
+ if dfs(r, c, 0):
+ return True
+ return False",24,24
+,"def letterCombinations(digits):
+ if not digits:
+ return []
+
+ phone = {
+ ""2"": ""abc"", ""3"": ""def"", ""4"": ""ghi"",
+ ""5"": ""jkl"", ""6"": ""mno"", ""7"": ""pqrs"",
+ ""8"": ""tuv"", ""9"": ""wxyz""
+ }
+
+ res = []
+
+ def backtrack(i, cur):
+ if i == len(digits):
+ res.append(cur)
+ return
+ for ch in phone[digits[i]]:
+ backtrack(i + 1, cur + ch)
+
+ backtrack(0, """")
+ return res
+",1.0,GPT,"Solve the problem ""Letter Combinations of a Phone Number"".
+
+Given a string of digits from 2 to 9,
+return all possible letter combinations that the number could represent.",PYTHON,"def letterCombinations(digits):
+ if not digits:
+ return []
+
+ phone = {
+ ""2"": ""abc"", ""3"": ""def"", ""4"": ""ghi"",
+ ""5"": ""jkl"", ""6"": ""mno"", ""7"": ""pqrs"",
+ ""8"": ""tuv"", ""9"": ""wxyz""
+ }
+
+ res = []
+
+ def backtrack(i, cur):
+ if i == len(digits):
+ res.append(cur)
+ return
+ for ch in phone[digits[i]]:
+ backtrack(i + 1, cur + ch)
+
+ backtrack(0, """")
+ return res",21,21
+,"class Solution:
+ def letterCombinations(self, digits: str) -> List[str]:
+ if not digits:
+ return []
+
+ res = [""""]
+ digitToChar = {
+ ""2"": ""abc"",
+ ""3"": ""def"",
+ ""4"": ""ghi"",
+ ""5"": ""jkl"",
+ ""6"": ""mno"",
+ ""7"": ""qprs"",
+ ""8"": ""tuv"",
+ ""9"": ""wxyz"",
+ }
+
+ for digit in digits:
+ tmp = []
+ for curStr in res:
+ for c in digitToChar[digit]:
+ tmp.append(curStr + c)
+ res = tmp
+ return res",0.0,GFG,,PYTHON,"class Solution:
+ def letterCombinations(self, digits: str) -> List[str]:
+ if not digits:
+ return []
+
+ res = [""""]
+ digitToChar = {
+ ""2"": ""abc"",
+ ""3"": ""def"",
+ ""4"": ""ghi"",
+ ""5"": ""jkl"",
+ ""6"": ""mno"",
+ ""7"": ""qprs"",
+ ""8"": ""tuv"",
+ ""9"": ""wxyz"",
+ }
+
+ for digit in digits:
+ tmp = []
+ for curStr in res:
+ for c in digitToChar[digit]:
+ tmp.append(curStr + c)
+ res = tmp
+ return res",24,24
+,"from collections import Counter
+
+def leastInterval(tasks, n):
+ count = Counter(tasks)
+ max_freq = max(count.values())
+ max_count = sum(1 for v in count.values() if v == max_freq)
+
+ return max(len(tasks), (max_freq - 1) * (n + 1) + max_count)
+",1.0,GPT,"Solve the problem ""Task Scheduler"".
+
+Given a list of tasks and a cooldown n,
+return the least number of units of time needed to finish all tasks
+with cooldown constraints.
+",PYTHON,"from collections import Counter
+
+def leastInterval(tasks, n):
+ count = Counter(tasks)
+ max_freq = max(count.values())
+ max_count = sum(1 for v in count.values() if v == max_freq)
+
+ return max(len(tasks), (max_freq - 1) * (n + 1) + max_count)",8,8
+,"class Solution:
+ def leastInterval(self, tasks: List[str], n: int) -> int:
+ count = [0] * 26
+ for task in tasks:
+ count[ord(task) - ord('A')] += 1
+
+ maxf = max(count)
+ maxCount = 0
+ for i in count:
+ maxCount += 1 if i == maxf else 0
+
+ time = (maxf - 1) * (n + 1) + maxCount
+ return max(len(tasks), time)",0.0,GFG,,PYTHON,"class Solution:
+ def leastInterval(self, tasks: List[str], n: int) -> int:
+ count = [0] * 26
+ for task in tasks:
+ count[ord(task) - ord('A')] += 1
+
+ maxf = max(count)
+ maxCount = 0
+ for i in count:
+ maxCount += 1 if i == maxf else 0
+
+ time = (maxf - 1) * (n + 1) + maxCount
+ return max(len(tasks), time)",13,13
+,"def combinationSum(candidates, target):
+ res = []
+
+ def backtrack(i, total, cur):
+ if total == target:
+ res.append(cur[:])
+ return
+ if i >= len(candidates) or total > target:
+ return
+
+ cur.append(candidates[i])
+ backtrack(i, total + candidates[i], cur)
+ cur.pop()
+ backtrack(i + 1, total, cur)
+
+ backtrack(0, 0, [])
+ return res
+",1.0,GPT,"Solve the problem ""Combination Sum"".
+
+Given an array of distinct integers candidates and a target,
+return all unique combinations where candidates sum to target.
+Each number may be used unlimited times.",PYTHON,"def combinationSum(candidates, target):
+ res = []
+
+ def backtrack(i, total, cur):
+ if total == target:
+ res.append(cur[:])
+ return
+ if i >= len(candidates) or total > target:
+ return
+
+ cur.append(candidates[i])
+ backtrack(i, total + candidates[i], cur)
+ cur.pop()
+ backtrack(i + 1, total, cur)
+
+ backtrack(0, 0, [])
+ return res",17,17
+,"class Solution:
+ def combinationSum(self, nums: List[int], target: int) -> List[List[int]]:
+ res = []
+ nums.sort()
+
+ def dfs(i, cur, total):
+ if total == target:
+ res.append(cur.copy())
+ return
+
+ for j in range(i, len(nums)):
+ if total + nums[j] > target:
+ return
+ cur.append(nums[j])
+ dfs(j, cur, total + nums[j])
+ cur.pop()
+
+ dfs(0, [], 0)
+ return res",0.0,GFG,,PYTHON,"class Solution:
+ def combinationSum(self, nums: List[int], target: int) -> List[List[int]]:
+ res = []
+ nums.sort()
+
+ def dfs(i, cur, total):
+ if total == target:
+ res.append(cur.copy())
+ return
+
+ for j in range(i, len(nums)):
+ if total + nums[j] > target:
+ return
+ cur.append(nums[j])
+ dfs(j, cur, total + nums[j])
+ cur.pop()
+
+ dfs(0, [], 0)
+ return res",19,19
+,"def generateParenthesis(n):
+ res = []
+
+ def backtrack(opened, closed, cur):
+ if opened == closed == n:
+ res.append(cur)
+ return
+ if opened < n:
+ backtrack(opened + 1, closed, cur + ""("")
+ if closed < opened:
+ backtrack(opened, closed + 1, cur + "")"")
+
+ backtrack(0, 0, """")
+ return res
+",1.0,GPT,"Solve the problem ""Generate Parentheses"".
+
+Given n pairs of parentheses,
+generate all combinations of well-formed parentheses.
+
+Provide Python backtracking solution.
+",PYTHON,"def generateParenthesis(n):
+ res = []
+
+ def backtrack(opened, closed, cur):
+ if opened == closed == n:
+ res.append(cur)
+ return
+ if opened < n:
+ backtrack(opened + 1, closed, cur + ""("")
+ if closed < opened:
+ backtrack(opened, closed + 1, cur + "")"")
+
+ backtrack(0, 0, """")
+ return res",14,14
+,"class Solution:
+ def generateParenthesis(self, n):
+ res = [[] for _ in range(n+1)]
+ res[0] = [""""]
+
+ for k in range(n + 1):
+ for i in range(k):
+ for left in res[i]:
+ for right in res[k-i-1]:
+ res[k].append(""("" + left + "")"" + right)
+
+ return res[-1]",0.0,GFG,,PYTHON,"class Solution:
+ def generateParenthesis(self, n):
+ res = [[] for _ in range(n+1)]
+ res[0] = [""""]
+
+ for k in range(n + 1):
+ for i in range(k):
+ for left in res[i]:
+ for right in res[k-i-1]:
+ res[k].append(""("" + left + "")"" + right)
+
+ return res[-1]",12,12
+,"import heapq
+
+def lastStoneWeight(stones):
+ stones = [-s for s in stones]
+ heapq.heapify(stones)
+
+ while len(stones) > 1:
+ a = -heapq.heappop(stones)
+ b = -heapq.heappop(stones)
+ if a != b:
+ heapq.heappush(stones, -(a - b))
+
+ return -stones[0] if stones else 0
+",1.0,GPT,"Solve the problem ""Last Stone Weight"".
+
+Given a list of stones,
+repeatedly smash the two heaviest stones.
+Return the weight of the remaining stone or 0.
+
+Provide Python solution using heap.
+",PYTHON,"import heapq
+
+def lastStoneWeight(stones):
+ stones = [-s for s in stones]
+ heapq.heapify(stones)
+
+ while len(stones) > 1:
+ a = -heapq.heappop(stones)
+ b = -heapq.heappop(stones)
+ if a != b:
+ heapq.heappush(stones, -(a - b))
+
+ return -stones[0] if stones else 0",13,13
+,"class Solution:
+ def lastStoneWeight(self, stones: List[int]) -> int:
+
+ maxStone = max(stones)
+ bucket = [0] * (maxStone + 1)
+ for stone in stones:
+ bucket[stone] += 1
+
+ first = second = maxStone
+ while first > 0:
+ if bucket[first] % 2 == 0:
+ first -= 1
+ continue
+
+ j = min(first - 1, second)
+ while j > 0 and bucket[j] == 0:
+ j -= 1
+
+ if j == 0:
+ return first
+ second = j
+ bucket[first] -= 1
+ bucket[second] -= 1
+ bucket[first - second] += 1
+ first = max(first - second, second)
+ return first",0.0,GFG,,PYTHON,"class Solution:
+ def lastStoneWeight(self, stones: List[int]) -> int:
+
+ maxStone = max(stones)
+ bucket = [0] * (maxStone + 1)
+ for stone in stones:
+ bucket[stone] += 1
+
+ first = second = maxStone
+ while first > 0:
+ if bucket[first] % 2 == 0:
+ first -= 1
+ continue
+
+ j = min(first - 1, second)
+ while j > 0 and bucket[j] == 0:
+ j -= 1
+
+ if j == 0:
+ return first
+ second = j
+ bucket[first] -= 1
+ bucket[second] -= 1
+ bucket[first - second] += 1
+ first = max(first - second, second)
+ return first",26,26
+,"import heapq
+
+def findKthLargest(nums, k):
+ return heapq.nlargest(k, nums)[-1]
+",1.0,GPT,"Solve the problem ""Kth Largest Element in an Array"".
+
+Given an integer array nums and an integer k,
+return the kth largest element.
+Do not sort the entire array.",PYTHON,"import heapq
+
+def findKthLargest(nums, k):
+ return heapq.nlargest(k, nums)[-1]",4,4
+,"class Solution:
+
+ def findKthLargest(self, nums: List[int], k: int) -> int:
+ k = len(nums) - k
+
+ def quickSelect(l, r):
+ pivot, p = nums[r], l
+ for i in range(l, r):
+ if nums[i] <= pivot:
+ nums[p], nums[i] = nums[i], nums[p]
+ p += 1
+ nums[p], nums[r] = nums[r], nums[p]
+
+ if p > k:
+ return quickSelect(l, p - 1)
+ elif p < k:
+ return quickSelect(p + 1, r)
+ else:
+ return nums[p]
+
+ return quickSelect(0, len(nums) - 1)",0.0,GFG,,PYTHON,"class Solution:
+
+ def findKthLargest(self, nums: List[int], k: int) -> int:
+ k = len(nums) - k
+
+ def quickSelect(l, r):
+ pivot, p = nums[r], l
+ for i in range(l, r):
+ if nums[i] <= pivot:
+ nums[p], nums[i] = nums[i], nums[p]
+ p += 1
+ nums[p], nums[r] = nums[r], nums[p]
+
+ if p > k:
+ return quickSelect(l, p - 1)
+ elif p < k:
+ return quickSelect(p + 1, r)
+ else:
+ return nums[p]
+
+ return quickSelect(0, len(nums) - 1)",21,21
+,"def subsetsWithDup(nums):
+ nums.sort()
+ res = []
+
+ def backtrack(i, cur):
+ res.append(cur[:])
+ for j in range(i, len(nums)):
+ if j > i and nums[j] == nums[j - 1]:
+ continue
+ cur.append(nums[j])
+ backtrack(j + 1, cur)
+ cur.pop()
+
+ backtrack(0, [])
+ return res
+",1.0,GPT,"Solve the problem ""Subsets II"".
+
+Given an integer array nums that may contain duplicates,
+return all possible subsets without duplicate subsets.",PYTHON,"def subsetsWithDup(nums):
+ nums.sort()
+ res = []
+
+ def backtrack(i, cur):
+ res.append(cur[:])
+ for j in range(i, len(nums)):
+ if j > i and nums[j] == nums[j - 1]:
+ continue
+ cur.append(nums[j])
+ backtrack(j + 1, cur)
+ cur.pop()
+
+ backtrack(0, [])
+ return res",15,15
+,"class Solution:
+ def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
+ nums.sort()
+ res = [[]]
+ prev_Idx = idx = 0
+
+ for i in range(len(nums)):
+ idx = prev_idx if i >= 1 and nums[i] == nums[i - 1] else 0
+ prev_idx = len(res)
+ for j in range(idx, prev_idx):
+ tmp = res[j].copy()
+ tmp.append(nums[i])
+ res.append(tmp)
+
+ return res",0.0,GFG,,PYTHON,"class Solution:
+ def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
+ nums.sort()
+ res = [[]]
+ prev_Idx = idx = 0
+
+ for i in range(len(nums)):
+ idx = prev_idx if i >= 1 and nums[i] == nums[i - 1] else 0
+ prev_idx = len(res)
+ for j in range(idx, prev_idx):
+ tmp = res[j].copy()
+ tmp.append(nums[i])
+ res.append(tmp)
+
+ return res",15,15
+,"import heapq
+
+def minMeetingRooms(intervals):
+ if not intervals:
+ return 0
+
+ intervals.sort(key=lambda x: x[0])
+ heap = []
+
+ for start, end in intervals:
+ if heap and heap[0] <= start:
+ heapq.heappop(heap)
+ heapq.heappush(heap, end)
+
+ return len(heap)
+",1.0,GPT,"Solve the problem ""Meeting Rooms II"".
+
+Given an array of meeting time intervals where intervals[i] = [start, end],
+return the minimum number of conference rooms required.",PYTHON,"import heapq
+
+def minMeetingRooms(intervals):
+ if not intervals:
+ return 0
+
+ intervals.sort(key=lambda x: x[0])
+ heap = []
+
+ for start, end in intervals:
+ if heap and heap[0] <= start:
+ heapq.heappop(heap)
+ heapq.heappush(heap, end)
+
+ return len(heap)",15,15
+,"""""""
+Definition of Interval:
+class Interval(object):
+ def __init__(self, start, end):
+ self.start = start
+ self.end = end
+""""""
+
+class Solution:
+ def minMeetingRooms(self, intervals: List[Interval]) -> int:
+ time = []
+ for i in intervals:
+ time.append((i.start, 1))
+ time.append((i.end, -1))
+
+ time.sort(key=lambda x: (x[0], x[1]))
+
+ res = count = 0
+ for t in time:
+ count += t[1]
+ res = max(res, count)
+ return res",0.0,GFG,,PYTHON,"""""""
+Definition of Interval:
+class Interval(object):
+ def __init__(self, start, end):
+ self.start = start
+ self.end = end
+""""""
+
+class Solution:
+ def minMeetingRooms(self, intervals: List[Interval]) -> int:
+ time = []
+ for i in intervals:
+ time.append((i.start, 1))
+ time.append((i.end, -1))
+
+ time.sort(key=lambda x: (x[0], x[1]))
+
+ res = count = 0
+ for t in time:
+ count += t[1]
+ res = max(res, count)
+ return res",22,22
+,"def setZeroes(matrix):
+ rows, cols = len(matrix), len(matrix[0])
+ row_zero = any(matrix[0][c] == 0 for c in range(cols))
+ col_zero = any(matrix[r][0] == 0 for r in range(rows))
+
+ for r in range(1, rows):
+ for c in range(1, cols):
+ if matrix[r][c] == 0:
+ matrix[r][0] = matrix[0][c] = 0
+
+ for r in range(1, rows):
+ for c in range(1, cols):
+ if matrix[r][0] == 0 or matrix[0][c] == 0:
+ matrix[r][c] = 0
+
+ if row_zero:
+ for c in range(cols):
+ matrix[0][c] = 0
+ if col_zero:
+ for r in range(rows):
+ matrix[r][0] = 0
+",1.0,GPT,"Solve the problem ""Set Matrix Zeroes"".
+
+Given an m x n matrix,
+if an element is 0, set its entire row and column to 0.
+Do it in-place with constant extra space.
+
+Provide Python solution.
+",PYTHON,"def setZeroes(matrix):
+ rows, cols = len(matrix), len(matrix[0])
+ row_zero = any(matrix[0][c] == 0 for c in range(cols))
+ col_zero = any(matrix[r][0] == 0 for r in range(rows))
+
+ for r in range(1, rows):
+ for c in range(1, cols):
+ if matrix[r][c] == 0:
+ matrix[r][0] = matrix[0][c] = 0
+
+ for r in range(1, rows):
+ for c in range(1, cols):
+ if matrix[r][0] == 0 or matrix[0][c] == 0:
+ matrix[r][c] = 0
+
+ if row_zero:
+ for c in range(cols):
+ matrix[0][c] = 0
+ if col_zero:
+ for r in range(rows):
+ matrix[r][0] = 0",21,21
+,"class Solution:
+ def setZeroes(self, matrix: List[List[int]]) -> None:
+ ROWS, COLS = len(matrix), len(matrix[0])
+ rowZero = False
+
+ for r in range(ROWS):
+ for c in range(COLS):
+ if matrix[r][c] == 0:
+ matrix[0][c] = 0
+ if r > 0:
+ matrix[r][0] = 0
+ else:
+ rowZero = True
+
+ for r in range(1, ROWS):
+ for c in range(1, COLS):
+ if matrix[0][c] == 0 or matrix[r][0] == 0:
+ matrix[r][c] = 0
+
+ if matrix[0][0] == 0:
+ for r in range(ROWS):
+ matrix[r][0] = 0
+
+ if rowZero:
+ for c in range(COLS):
+ matrix[0][c] = 0",0.0,GFG,,PYTHON,"class Solution:
+ def setZeroes(self, matrix: List[List[int]]) -> None:
+ ROWS, COLS = len(matrix), len(matrix[0])
+ rowZero = False
+
+ for r in range(ROWS):
+ for c in range(COLS):
+ if matrix[r][c] == 0:
+ matrix[0][c] = 0
+ if r > 0:
+ matrix[r][0] = 0
+ else:
+ rowZero = True
+
+ for r in range(1, ROWS):
+ for c in range(1, COLS):
+ if matrix[0][c] == 0 or matrix[r][0] == 0:
+ matrix[r][c] = 0
+
+ if matrix[0][0] == 0:
+ for r in range(ROWS):
+ matrix[r][0] = 0
+
+ if rowZero:
+ for c in range(COLS):
+ matrix[0][c] = 0",26,26
+,"def solveNQueens(n):
+ res = []
+ cols, diag1, diag2 = set(), set(), set()
+ board = [["".""] * n for _ in range(n)]
+
+ def backtrack(r):
+ if r == n:
+ res.append(["""".join(row) for row in board])
+ return
+ for c in range(n):
+ if c in cols or (r - c) in diag1 or (r + c) in diag2:
+ continue
+ cols.add(c)
+ diag1.add(r - c)
+ diag2.add(r + c)
+ board[r][c] = ""Q""
+
+ backtrack(r + 1)
+
+ cols.remove(c)
+ diag1.remove(r - c)
+ diag2.remove(r + c)
+ board[r][c] = "".""
+
+ backtrack(0)
+ return res
+",1.0,GPT,"Solve the problem ""N-Queens"".
+
+Given an integer n,
+return all distinct solutions to the n-queens puzzle.",PYTHON,"def solveNQueens(n):
+ res = []
+ cols, diag1, diag2 = set(), set(), set()
+ board = [["".""] * n for _ in range(n)]
+
+ def backtrack(r):
+ if r == n:
+ res.append(["""".join(row) for row in board])
+ return
+ for c in range(n):
+ if c in cols or (r - c) in diag1 or (r + c) in diag2:
+ continue
+ cols.add(c)
+ diag1.add(r - c)
+ diag2.add(r + c)
+ board[r][c] = ""Q""
+
+ backtrack(r + 1)
+
+ cols.remove(c)
+ diag1.remove(r - c)
+ diag2.remove(r + c)
+ board[r][c] = "".""
+
+ backtrack(0)
+ return res",26,26
+,"class Solution:
+ def solveNQueens(self, n: int) -> List[List[str]]:
+ col = 0
+ posDiag = 0
+ negDiag = 0
+ res = []
+ board = [["".""] * n for i in range(n)]
+
+ def backtrack(r):
+ nonlocal col, posDiag, negDiag
+ if r == n:
+ copy = ["""".join(row) for row in board]
+ res.append(copy)
+ return
+ for c in range(n):
+ if ((col & (1 << c)) or (posDiag & (1 << (r + c)))
+ or (negDiag & (1 << (r - c + n)))):
+ continue
+ col ^= (1 << c)
+ posDiag ^= (1 << (r + c))
+ negDiag ^= (1 << (r - c + n))
+ board[r][c] = ""Q""
+
+ backtrack(r + 1)
+
+ col ^= (1 << c)
+ posDiag ^= (1 << (r + c))
+ negDiag ^= (1 << (r - c + n))
+ board[r][c] = "".""
+
+ backtrack(0)
+ return res",0.0,GFG,,PYTHON,"class Solution:
+ def solveNQueens(self, n: int) -> List[List[str]]:
+ col = 0
+ posDiag = 0
+ negDiag = 0
+ res = []
+ board = [["".""] * n for i in range(n)]
+
+ def backtrack(r):
+ nonlocal col, posDiag, negDiag
+ if r == n:
+ copy = ["""".join(row) for row in board]
+ res.append(copy)
+ return
+ for c in range(n):
+ if ((col & (1 << c)) or (posDiag & (1 << (r + c)))
+ or (negDiag & (1 << (r - c + n)))):
+ continue
+ col ^= (1 << c)
+ posDiag ^= (1 << (r + c))
+ negDiag ^= (1 << (r - c + n))
+ board[r][c] = ""Q""
+
+ backtrack(r + 1)
+
+ col ^= (1 << c)
+ posDiag ^= (1 << (r + c))
+ negDiag ^= (1 << (r - c + n))
+ board[r][c] = "".""
+
+ backtrack(0)
+ return res",32,32
+,"def numIslands(grid):
+ if not grid:
+ return 0
+
+ rows, cols = len(grid), len(grid[0])
+ count = 0
+
+ def dfs(r, c):
+ if r < 0 or c < 0 or r >= rows or c >= cols or grid[r][c] != ""1"":
+ return
+ grid[r][c] = ""0""
+ dfs(r+1, c)
+ dfs(r-1, c)
+ dfs(r, c+1)
+ dfs(r, c-1)
+
+ for r in range(rows):
+ for c in range(cols):
+ if grid[r][c] == ""1"":
+ dfs(r, c)
+ count += 1
+
+ return count
+",1.0,GPT,"Solve the problem ""Number of Islands"".
+
+Given a 2D grid of '1's (land) and '0's (water),
+return the number of islands.",PYTHON,"def numIslands(grid):
+ if not grid:
+ return 0
+
+ rows, cols = len(grid), len(grid[0])
+ count = 0
+
+ def dfs(r, c):
+ if r < 0 or c < 0 or r >= rows or c >= cols or grid[r][c] != ""1"":
+ return
+ grid[r][c] = ""0""
+ dfs(r+1, c)
+ dfs(r-1, c)
+ dfs(r, c+1)
+ dfs(r, c-1)
+
+ for r in range(rows):
+ for c in range(cols):
+ if grid[r][c] == ""1"":
+ dfs(r, c)
+ count += 1
+
+ return count",23,23
+,"class Solution:
+ def numIslands(self, grid: List[List[str]]) -> int:
+ directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]
+ ROWS, COLS = len(grid), len(grid[0])
+ islands = 0
+
+ def bfs(r, c):
+ q = deque()
+ grid[r][c] = ""0""
+ q.append((r, c))
+
+ while q:
+ row, col = q.popleft()
+ for dr, dc in directions:
+ nr, nc = dr + row, dc + col
+ if (nr < 0 or nc < 0 or nr >= ROWS or
+ nc >= COLS or grid[nr][nc] == ""0""
+ ):
+ continue
+ q.append((nr, nc))
+ grid[nr][nc] = ""0""
+
+ for r in range(ROWS):
+ for c in range(COLS):
+ if grid[r][c] == ""1"":
+ bfs(r, c)
+ islands += 1
+
+ return islands",0.0,GFG,,PYTHON,"class Solution:
+ def numIslands(self, grid: List[List[str]]) -> int:
+ directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]
+ ROWS, COLS = len(grid), len(grid[0])
+ islands = 0
+
+ def bfs(r, c):
+ q = deque()
+ grid[r][c] = ""0""
+ q.append((r, c))
+
+ while q:
+ row, col = q.popleft()
+ for dr, dc in directions:
+ nr, nc = dr + row, dc + col
+ if (nr < 0 or nc < 0 or nr >= ROWS or
+ nc >= COLS or grid[nr][nc] == ""0""
+ ):
+ continue
+ q.append((nr, nc))
+ grid[nr][nc] = ""0""
+
+ for r in range(ROWS):
+ for c in range(COLS):
+ if grid[r][c] == ""1"":
+ bfs(r, c)
+ islands += 1
+
+ return islands",29,29
+,"from collections import deque
+
+def orangesRotting(grid):
+ rows, cols = len(grid), len(grid[0])
+ q = deque()
+ fresh = 0
+
+ for r in range(rows):
+ for c in range(cols):
+ if grid[r][c] == 2:
+ q.append((r, c))
+ elif grid[r][c] == 1:
+ fresh += 1
+
+ time = 0
+ directions = [(1,0), (-1,0), (0,1), (0,-1)]
+
+ while q and fresh:
+ for _ in range(len(q)):
+ r, c = q.popleft()
+ for dr, dc in directions:
+ nr, nc = r + dr, c + dc
+ if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1:
+ grid[nr][nc] = 2
+ fresh -= 1
+ q.append((nr, nc))
+ time += 1
+
+ return time if fresh == 0 else -1
+",1.0,GPT,"Solve the problem ""Rotting Oranges"".
+
+Given a grid where:
+0 = empty, 1 = fresh, 2 = rotten,
+return the minimum minutes to rot all fresh oranges.
+If impossible, return -1.
+",PYTHON,"from collections import deque
+
+def orangesRotting(grid):
+ rows, cols = len(grid), len(grid[0])
+ q = deque()
+ fresh = 0
+
+ for r in range(rows):
+ for c in range(cols):
+ if grid[r][c] == 2:
+ q.append((r, c))
+ elif grid[r][c] == 1:
+ fresh += 1
+
+ time = 0
+ directions = [(1,0), (-1,0), (0,1), (0,-1)]
+
+ while q and fresh:
+ for _ in range(len(q)):
+ r, c = q.popleft()
+ for dr, dc in directions:
+ nr, nc = r + dr, c + dc
+ if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1:
+ grid[nr][nc] = 2
+ fresh -= 1
+ q.append((nr, nc))
+ time += 1
+
+ return time if fresh == 0 else -1",29,29
+,"class Solution:
+ def orangesRotting(self, grid: List[List[int]]) -> int:
+ ROWS, COLS = len(grid), len(grid[0])
+ fresh = 0
+ time = 0
+
+ for r in range(ROWS):
+ for c in range(COLS):
+ if grid[r][c] == 1:
+ fresh += 1
+
+ directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
+
+ while fresh > 0:
+ flag = False
+ for r in range(ROWS):
+ for c in range(COLS):
+ if grid[r][c] == 2:
+ for dr, dc in directions:
+ row, col = r + dr, c + dc
+ if (row in range(ROWS) and
+ col in range(COLS) and
+ grid[row][col] == 1):
+ grid[row][col] = 3
+ fresh -= 1
+ flag = True
+
+ if not flag:
+ return -1
+
+ for r in range(ROWS):
+ for c in range(COLS):
+ if grid[r][c] == 3:
+ grid[r][c] = 2
+
+ time += 1
+
+ return time",0.0,GFG,,PYTHON,"class Solution:
+ def orangesRotting(self, grid: List[List[int]]) -> int:
+ ROWS, COLS = len(grid), len(grid[0])
+ fresh = 0
+ time = 0
+
+ for r in range(ROWS):
+ for c in range(COLS):
+ if grid[r][c] == 1:
+ fresh += 1
+
+ directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
+
+ while fresh > 0:
+ flag = False
+ for r in range(ROWS):
+ for c in range(COLS):
+ if grid[r][c] == 2:
+ for dr, dc in directions:
+ row, col = r + dr, c + dc
+ if (row in range(ROWS) and
+ col in range(COLS) and
+ grid[row][col] == 1):
+ grid[row][col] = 3
+ fresh -= 1
+ flag = True
+
+ if not flag:
+ return -1
+
+ for r in range(ROWS):
+ for c in range(COLS):
+ if grid[r][c] == 3:
+ grid[r][c] = 2
+
+ time += 1
+
+ return time",38,38
+,"def solve(board):
+ if not board:
+ return
+
+ rows, cols = len(board), len(board[0])
+
+ def dfs(r, c):
+ if r < 0 or c < 0 or r >= rows or c >= cols or board[r][c] != ""O"":
+ return
+ board[r][c] = ""T""
+ dfs(r+1, c)
+ dfs(r-1, c)
+ dfs(r, c+1)
+ dfs(r, c-1)
+
+ for r in range(rows):
+ dfs(r, 0)
+ dfs(r, cols - 1)
+ for c in range(cols):
+ dfs(0, c)
+ dfs(rows - 1, c)
+
+ for r in range(rows):
+ for c in range(cols):
+ if board[r][c] == ""O"":
+ board[r][c] = ""X""
+ elif board[r][c] == ""T"":
+ board[r][c] = ""O""
+",1.0,GPT,"Solve the problem ""Surrounded Regions"".
+
+Given a board of 'X' and 'O',
+capture all regions surrounded by 'X'.",PYTHON,"def solve(board):
+ if not board:
+ return
+
+ rows, cols = len(board), len(board[0])
+
+ def dfs(r, c):
+ if r < 0 or c < 0 or r >= rows or c >= cols or board[r][c] != ""O"":
+ return
+ board[r][c] = ""T""
+ dfs(r+1, c)
+ dfs(r-1, c)
+ dfs(r, c+1)
+ dfs(r, c-1)
+
+ for r in range(rows):
+ dfs(r, 0)
+ dfs(r, cols - 1)
+ for c in range(cols):
+ dfs(0, c)
+ dfs(rows - 1, c)
+
+ for r in range(rows):
+ for c in range(cols):
+ if board[r][c] == ""O"":
+ board[r][c] = ""X""
+ elif board[r][c] == ""T"":
+ board[r][c] = ""O""",28,28
+,"class Solution:
+ def solve(self, board: List[List[str]]) -> None:
+ ROWS, COLS = len(board), len(board[0])
+ directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
+
+ def capture():
+ q = deque()
+ for r in range(ROWS):
+ for c in range(COLS):
+ if (r == 0 or r == ROWS - 1 or
+ c == 0 or c == COLS - 1 and
+ board[r][c] == ""O""
+ ):
+ q.append((r, c))
+ while q:
+ r, c = q.popleft()
+ if board[r][c] == ""O"":
+ board[r][c] = ""T""
+ for dr, dc in directions:
+ nr, nc = r + dr, c + dc
+ if 0 <= nr < ROWS and 0 <= nc < COLS:
+ q.append((nr, nc))
+
+ capture()
+ for r in range(ROWS):
+ for c in range(COLS):
+ if board[r][c] == ""O"":
+ board[r][c] = ""X""
+ elif board[r][c] == ""T"":
+ board[r][c] = ""O""",0.0,GFG,,PYTHON,"class Solution:
+ def solve(self, board: List[List[str]]) -> None:
+ ROWS, COLS = len(board), len(board[0])
+ directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
+
+ def capture():
+ q = deque()
+ for r in range(ROWS):
+ for c in range(COLS):
+ if (r == 0 or r == ROWS - 1 or
+ c == 0 or c == COLS - 1 and
+ board[r][c] == ""O""
+ ):
+ q.append((r, c))
+ while q:
+ r, c = q.popleft()
+ if board[r][c] == ""O"":
+ board[r][c] = ""T""
+ for dr, dc in directions:
+ nr, nc = r + dr, c + dc
+ if 0 <= nr < ROWS and 0 <= nc < COLS:
+ q.append((nr, nc))
+
+ capture()
+ for r in range(ROWS):
+ for c in range(COLS):
+ if board[r][c] == ""O"":
+ board[r][c] = ""X""
+ elif board[r][c] == ""T"":
+ board[r][c] = ""O""",30,30
+,"from collections import deque
+
+def ladderLength(beginWord, endWord, wordList):
+ wordSet = set(wordList)
+ if endWord not in wordSet:
+ return 0
+
+ q = deque([(beginWord, 1)])
+
+ while q:
+ word, steps = q.popleft()
+ if word == endWord:
+ return steps
+ for i in range(len(word)):
+ for c in ""abcdefghijklmnopqrstuvwxyz"":
+ new = word[:i] + c + word[i+1:]
+ if new in wordSet:
+ wordSet.remove(new)
+ q.append((new, steps + 1))
+
+ return 0
+",1.0,GPT,"Solve the problem ""Word Ladder"".
+
+Given beginWord, endWord, and a wordList,
+return the length of the shortest transformation sequence.",PYTHON,"from collections import deque
+
+def ladderLength(beginWord, endWord, wordList):
+ wordSet = set(wordList)
+ if endWord not in wordSet:
+ return 0
+
+ q = deque([(beginWord, 1)])
+
+ while q:
+ word, steps = q.popleft()
+ if word == endWord:
+ return steps
+ for i in range(len(word)):
+ for c in ""abcdefghijklmnopqrstuvwxyz"":
+ new = word[:i] + c + word[i+1:]
+ if new in wordSet:
+ wordSet.remove(new)
+ q.append((new, steps + 1))
+
+ return 0",21,21
+,"class Solution:
+ def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
+ if endWord not in wordList or beginWord == endWord:
+ return 0
+ m = len(wordList[0])
+ wordSet = set(wordList)
+ qb, qe = deque([beginWord]), deque([endWord])
+ fromBegin, fromEnd = {beginWord: 1}, {endWord: 1}
+
+ while qb and qe:
+ if len(qb) > len(qe):
+ qb, qe = qe, qb
+ fromBegin, fromEnd = fromEnd, fromBegin
+ for _ in range(len(qb)):
+ word = qb.popleft()
+ steps = fromBegin[word]
+ for i in range(m):
+ for c in range(97, 123):
+ if chr(c) == word[i]:
+ continue
+ nei = word[:i] + chr(c) + word[i + 1:]
+ if nei not in wordSet:
+ continue
+ if nei in fromEnd:
+ return steps + fromEnd[nei]
+ if nei not in fromBegin:
+ fromBegin[nei] = steps + 1
+ qb.append(nei)
+ return 0",0.0,GFG,,PYTHON,"class Solution:
+ def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
+ if endWord not in wordList or beginWord == endWord:
+ return 0
+ m = len(wordList[0])
+ wordSet = set(wordList)
+ qb, qe = deque([beginWord]), deque([endWord])
+ fromBegin, fromEnd = {beginWord: 1}, {endWord: 1}
+
+ while qb and qe:
+ if len(qb) > len(qe):
+ qb, qe = qe, qb
+ fromBegin, fromEnd = fromEnd, fromBegin
+ for _ in range(len(qb)):
+ word = qb.popleft()
+ steps = fromBegin[word]
+ for i in range(m):
+ for c in range(97, 123):
+ if chr(c) == word[i]:
+ continue
+ nei = word[:i] + chr(c) + word[i + 1:]
+ if nei not in wordSet:
+ continue
+ if nei in fromEnd:
+ return steps + fromEnd[nei]
+ if nei not in fromBegin:
+ fromBegin[nei] = steps + 1
+ qb.append(nei)
+ return 0",29,29
+,"import heapq
+
+def swimInWater(grid):
+ n = len(grid)
+ heap = [(grid[0][0], 0, 0)]
+ visited = set()
+
+ while heap:
+ time, r, c = heapq.heappop(heap)
+ if (r, c) in visited:
+ continue
+ visited.add((r, c))
+ if r == n - 1 and c == n - 1:
+ return time
+ for dr, dc in [(1,0), (-1,0), (0,1), (0,-1)]:
+ nr, nc = r + dr, c + dc
+ if 0 <= nr < n and 0 <= nc < n:
+ heapq.heappush(heap, (max(time, grid[nr][nc]), nr, nc))
+",1.0,GPT,"Solve the problem ""Swim in Rising Water"".
+
+Given an n x n grid,
+return the minimum time required to swim from top-left to bottom-right.",PYTHON,"import heapq
+
+def swimInWater(grid):
+ n = len(grid)
+ heap = [(grid[0][0], 0, 0)]
+ visited = set()
+
+ while heap:
+ time, r, c = heapq.heappop(heap)
+ if (r, c) in visited:
+ continue
+ visited.add((r, c))
+ if r == n - 1 and c == n - 1:
+ return time
+ for dr, dc in [(1,0), (-1,0), (0,1), (0,-1)]:
+ nr, nc = r + dr, c + dc
+ if 0 <= nr < n and 0 <= nc < n:
+ heapq.heappush(heap, (max(time, grid[nr][nc]), nr, nc))",18,18
+,"class Solution:
+ def swimInWater(self, grid: List[List[int]]) -> int:
+ N = len(grid)
+ visit = set()
+ minH = [[grid[0][0], 0, 0]] # (time/max-height, r, c)
+ directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
+
+ visit.add((0, 0))
+ while minH:
+ t, r, c = heapq.heappop(minH)
+ if r == N - 1 and c == N - 1:
+ return t
+ for dr, dc in directions:
+ neiR, neiC = r + dr, c + dc
+ if (neiR < 0 or neiC < 0 or
+ neiR == N or neiC == N or
+ (neiR, neiC) in visit
+ ):
+ continue
+ visit.add((neiR, neiC))
+ heapq.heappush(minH, [max(t, grid[neiR][neiC]), neiR, neiC])",0.0,GFG,,PYTHON,"class Solution:
+ def swimInWater(self, grid: List[List[int]]) -> int:
+ N = len(grid)
+ visit = set()
+ minH = [[grid[0][0], 0, 0]] # (time/max-height, r, c)
+ directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
+
+ visit.add((0, 0))
+ while minH:
+ t, r, c = heapq.heappop(minH)
+ if r == N - 1 and c == N - 1:
+ return t
+ for dr, dc in directions:
+ neiR, neiC = r + dr, c + dc
+ if (neiR < 0 or neiC < 0 or
+ neiR == N or neiC == N or
+ (neiR, neiC) in visit
+ ):
+ continue
+ visit.add((neiR, neiC))
+ heapq.heappush(minH, [max(t, grid[neiR][neiC]), neiR, neiC])",21,21
+,"from collections import deque
+
+def wallsAndGates(rooms):
+ rows, cols = len(rooms), len(rooms[0])
+ q = deque()
+
+ for r in range(rows):
+ for c in range(cols):
+ if rooms[r][c] == 0:
+ q.append((r, c))
+
+ directions = [(1,0), (-1,0), (0,1), (0,-1)]
+
+ while q:
+ r, c = q.popleft()
+ for dr, dc in directions:
+ nr, nc = r + dr, c + dc
+ if 0 <= nr < rows and 0 <= nc < cols and rooms[nr][nc] == 2147483647:
+ rooms[nr][nc] = rooms[r][c] + 1
+ q.append((nr, nc))
",1.0,GPT,"Solve the problem ""Walls and Gates"" (Islands and Treasure).
+
+Given a grid with:
+-1 = wall, 0 = gate, INF = empty room,
+fill each empty room with distance to its nearest gate.",PYTHON,"from collections import deque
+
+def wallsAndGates(rooms):
+ rows, cols = len(rooms), len(rooms[0])
+ q = deque()
+
+ for r in range(rows):
+ for c in range(cols):
+ if rooms[r][c] == 0:
+ q.append((r, c))
+
+ directions = [(1,0), (-1,0), (0,1), (0,-1)]
+
+ while q:
+ r, c = q.popleft()
+ for dr, dc in directions:
+ nr, nc = r + dr, c + dc
+ if 0 <= nr < rows and 0 <= nc < cols and rooms[nr][nc] == 2147483647:
+ rooms[nr][nc] = rooms[r][c] + 1
+ q.append((nr, nc))",20,20
+,"class Solution:
+ def islandsAndTreasure(self, grid: List[List[int]]) -> None:
+ ROWS, COLS = len(grid), len(grid[0])
+ visit = set()
+ q = deque()
+
+ def addCell(r, c):
+ if (min(r, c) < 0 or r == ROWS or c == COLS or
+ (r, c) in visit or grid[r][c] == -1
+ ):
+ return
+ visit.add((r, c))
+ q.append([r, c])
+
+ for r in range(ROWS):
+ for c in range(COLS):
+ if grid[r][c] == 0:
+ q.append([r, c])
+ visit.add((r, c))
+
+ dist = 0
+ while q:
+ for i in range(len(q)):
+ r, c = q.popleft()
+ grid[r][c] = dist
+ addCell(r + 1, c)
+ addCell(r - 1, c)
+ addCell(r, c + 1)
+ addCell(r, c - 1)
+ dist += 1",0.0,GFG,,PYTHON,"class Solution:
+ def islandsAndTreasure(self, grid: List[List[int]]) -> None:
+ ROWS, COLS = len(grid), len(grid[0])
+ visit = set()
+ q = deque()
+
+ def addCell(r, c):
+ if (min(r, c) < 0 or r == ROWS or c == COLS or
+ (r, c) in visit or grid[r][c] == -1
+ ):
+ return
+ visit.add((r, c))
+ q.append([r, c])
+
+ for r in range(ROWS):
+ for c in range(COLS):
+ if grid[r][c] == 0:
+ q.append([r, c])
+ visit.add((r, c))
+
+ dist = 0
+ while q:
+ for i in range(len(q)):
+ r, c = q.popleft()
+ grid[r][c] = dist
+ addCell(r + 1, c)
+ addCell(r - 1, c)
+ addCell(r, c + 1)
+ addCell(r, c - 1)
+ dist += 1",30,30
+,"def climbStairs(n):
+ if n <= 2:
+ return n
+
+ a, b = 1, 2
+ for _ in range(3, n + 1):
+ a, b = b, a + b
+
+ return b
+",1.0,GPT,"Solve the problem ""Climbing Stairs"".
+
+You can climb 1 or 2 steps at a time.
+Given n steps, return how many distinct ways you can climb.",PYTHON,"def climbStairs(n):
+ if n <= 2:
+ return n
+
+ a, b = 1, 2
+ for _ in range(3, n + 1):
+ a, b = b, a + b
+
+ return b",9,9
+,"class Solution:
+ def climbStairs(self, n: int) -> int:
+ one, two = 1, 1
+
+ for i in range(n - 1):
+ temp = one
+ one = one + two
+ two = temp
+
+ return one",0.0,GFG,,PYTHON,"class Solution:
+ def climbStairs(self, n: int) -> int:
+ one, two = 1, 1
+
+ for i in range(n - 1):
+ temp = one
+ one = one + two
+ two = temp
+
+ return one",10,10
+,"def rob(nums):
+ prev, curr = 0, 0
+ for n in nums:
+ prev, curr = curr, max(curr, prev + n)
+ return curr
+",1.0,GPT,"Solve the problem ""House Robber"".
+
+Given an integer array nums representing the amount of money in each house,
+return the maximum amount of money you can rob without robbing adjacent houses.
+",PYTHON,"def rob(nums):
+ prev, curr = 0, 0
+ for n in nums:
+ prev, curr = curr, max(curr, prev + n)
+ return curr",5,5
+,"class Solution:
+ def rob(self, nums: List[int]) -> int:
+ rob1, rob2 = 0, 0
+
+ for num in nums:
+ temp = max(num + rob1, rob2)
+ rob1 = rob2
+ rob2 = temp
+ return rob2",0.0,GFG,,PYTHON,"class Solution:
+ def rob(self, nums: List[int]) -> int:
+ rob1, rob2 = 0, 0
+
+ for num in nums:
+ temp = max(num + rob1, rob2)
+ rob1 = rob2
+ rob2 = temp
+ return rob2",9,9
+,"def coinChange(coins, amount):
+ dp = [amount + 1] * (amount + 1)
+ dp[0] = 0
+
+ for a in range(1, amount + 1):
+ for c in coins:
+ if a - c >= 0:
+ dp[a] = min(dp[a], dp[a - c] + 1)
+
+ return dp[amount] if dp[amount] != amount + 1 else -1
+",1.0,GPT,"Solve the problem ""Coin Change"".
+
+Given an array coins and an integer amount,
+return the fewest number of coins needed to make up that amount.
+If not possible, return -1.",PYTHON,"def coinChange(coins, amount):
+ dp = [amount + 1] * (amount + 1)
+ dp[0] = 0
+
+ for a in range(1, amount + 1):
+ for c in coins:
+ if a - c >= 0:
+ dp[a] = min(dp[a], dp[a - c] + 1)
+
+ return dp[amount] if dp[amount] != amount + 1 else -1",10,10
+,"class Solution:
+ def coinChange(self, coins: List[int], amount: int) -> int:
+ if amount == 0:
+ return 0
+
+ q = deque([0])
+ seen = [False] * (amount + 1)
+ seen[0] = True
+ res = 0
+
+ while q:
+ res += 1
+ for _ in range(len(q)):
+ cur = q.popleft()
+ for coin in coins:
+ nxt = cur + coin
+ if nxt == amount:
+ return res
+ if nxt > amount or seen[nxt]:
+ continue
+ seen[nxt] = True
+ q.append(nxt)
+
+ return -1",0.0,GFG,,PYTHON,"class Solution:
+ def coinChange(self, coins: List[int], amount: int) -> int:
+ if amount == 0:
+ return 0
+
+ q = deque([0])
+ seen = [False] * (amount + 1)
+ seen[0] = True
+ res = 0
+
+ while q:
+ res += 1
+ for _ in range(len(q)):
+ cur = q.popleft()
+ for coin in coins:
+ nxt = cur + coin
+ if nxt == amount:
+ return res
+ if nxt > amount or seen[nxt]:
+ continue
+ seen[nxt] = True
+ q.append(nxt)
+
+ return -1",24,24
+,"def uniquePaths(m, n):
+ dp = [1] * n
+ for _ in range(m - 1):
+ for j in range(1, n):
+ dp[j] += dp[j - 1]
+ return dp[-1]
+",1.0,GPT,"Solve the problem ""Unique Paths"".
+
+Given m and n representing grid dimensions,
+return the number of unique paths from top-left to bottom-right.",PYTHON,"def uniquePaths(m, n):
+ dp = [1] * n
+ for _ in range(m - 1):
+ for j in range(1, n):
+ dp[j] += dp[j - 1]
+ return dp[-1]",6,6
+,"class Solution:
+ def uniquePaths(self, m: int, n: int) -> int:
+ dp = [1] * n
+ for i in range(m - 2, -1, -1):
+ for j in range(n - 2, -1, -1):
+ dp[j] += dp[j + 1]
+
+ return dp[0]",0.0,GFG,,PYTHON,"class Solution:
+ def uniquePaths(self, m: int, n: int) -> int:
+ dp = [1] * n
+ for i in range(m - 2, -1, -1):
+ for j in range(n - 2, -1, -1):
+ dp[j] += dp[j + 1]
+
+ return dp[0]",8,8
+,"def maxCoins(nums):
+ nums = [1] + nums + [1]
+ n = len(nums)
+ dp = [[0] * n for _ in range(n)]
+
+ for length in range(2, n):
+ for l in range(0, n - length):
+ r = l + length
+ for k in range(l + 1, r):
+ dp[l][r] = max(
+ dp[l][r],
+ nums[l] * nums[k] * nums[r] + dp[l][k] + dp[k][r]
+ )
+
+ return dp[0][n - 1]
+",1.0,GPT,"Solve the problem ""Burst Balloons"".
+
+Given an array nums,
+return the maximum coins you can collect by bursting balloons wisely.",PYTHON,"def maxCoins(nums):
+ nums = [1] + nums + [1]
+ n = len(nums)
+ dp = [[0] * n for _ in range(n)]
+
+ for length in range(2, n):
+ for l in range(0, n - length):
+ r = l + length
+ for k in range(l + 1, r):
+ dp[l][r] = max(
+ dp[l][r],
+ nums[l] * nums[k] * nums[r] + dp[l][k] + dp[k][r]
+ )
+
+ return dp[0][n - 1]",15,15
+,"class Solution:
+ def maxCoins(self, nums):
+ n = len(nums)
+ new_nums = [1] + nums + [1]
+
+ dp = [[0] * (n + 2) for _ in range(n + 2)]
+ for l in range(n, 0, -1):
+ for r in range(l, n + 1):
+ for i in range(l, r + 1):
+ coins = new_nums[l - 1] * new_nums[i] * new_nums[r + 1]
+ coins += dp[l][i - 1] + dp[i + 1][r]
+ dp[l][r] = max(dp[l][r], coins)
+
+ return dp[1][n]",0.0,GFG,,PYTHON,"class Solution:
+ def maxCoins(self, nums):
+ n = len(nums)
+ new_nums = [1] + nums + [1]
+
+ dp = [[0] * (n + 2) for _ in range(n + 2)]
+ for l in range(n, 0, -1):
+ for r in range(l, n + 1):
+ for i in range(l, r + 1):
+ coins = new_nums[l - 1] * new_nums[i] * new_nums[r + 1]
+ coins += dp[l][i - 1] + dp[i + 1][r]
+ dp[l][r] = max(dp[l][r], coins)
+
+ return dp[1][n]",14,14
+,"def canJump(nums):
+ max_reach = 0
+ for i, n in enumerate(nums):
+ if i > max_reach:
+ return False
+ max_reach = max(max_reach, i + n)
+ return True
+",1.0,GPT,"Solve the problem ""Jump Game"".
+
+Given an array nums where nums[i] represents maximum jump length,
+return true if you can reach the last index.",PYTHON,"def canJump(nums):
+ max_reach = 0
+ for i, n in enumerate(nums):
+ if i > max_reach:
+ return False
+ max_reach = max(max_reach, i + n)
+ return True",7,7
+,"class Solution:
+ def canJump(self, nums: List[int]) -> bool:
+ goal = len(nums) - 1
+
+ for i in range(len(nums) - 2, -1, -1):
+ if i + nums[i] >= goal:
+ goal = i
+ return goal == 0",0.0,GFG,,PYTHON,"class Solution:
+ def canJump(self, nums: List[int]) -> bool:
+ goal = len(nums) - 1
+
+ for i in range(len(nums) - 2, -1, -1):
+ if i + nums[i] >= goal:
+ goal = i
+ return goal == 0",8,8
+,"def canCompleteCircuit(gas, cost):
+ total = curr = start = 0
+
+ for i in range(len(gas)):
+ total += gas[i] - cost[i]
+ curr += gas[i] - cost[i]
+ if curr < 0:
+ start = i + 1
+ curr = 0
+
+ return start if total >= 0 else -1
+",1.0,GPT,"Solve the problem ""Gas Station"".
+
+Given gas and cost arrays,
+return the starting gas station index if you can travel around once.
+Otherwise return -1.",PYTHON,"def canCompleteCircuit(gas, cost):
+ total = curr = start = 0
+
+ for i in range(len(gas)):
+ total += gas[i] - cost[i]
+ curr += gas[i] - cost[i]
+ if curr < 0:
+ start = i + 1
+ curr = 0
+
+ return start if total >= 0 else -1",11,11
+,"class Solution:
+ def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
+ if sum(gas) < sum(cost):
+ return -1
+
+ total = 0
+ res = 0
+ for i in range(len(gas)):
+ total += (gas[i] - cost[i])
+
+ if total < 0:
+ total = 0
+ res = i + 1
+
+ return res",0.0,GFG,,PYTHON,"class Solution:
+ def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
+ if sum(gas) < sum(cost):
+ return -1
+
+ total = 0
+ res = 0
+ for i in range(len(gas)):
+ total += (gas[i] - cost[i])
+
+ if total < 0:
+ total = 0
+ res = i + 1
+
+ return res",15,15
+,"def isHappy(n):
+ seen = set()
+
+ while n != 1 and n not in seen:
+ seen.add(n)
+ n = sum(int(c) ** 2 for c in str(n))
+
+ return n == 1
+",1.0,GPT,"Solve the problem ""Happy Number"".
+
+Determine if a number is happy.
+Use cycle detection or a set.
+
+Provide Python solution.
+",PYTHON,"def isHappy(n):
+ seen = set()
+
+ while n != 1 and n not in seen:
+ seen.add(n)
+ n = sum(int(c) ** 2 for c in str(n))
+
+ return n == 1",8,8
+,"class Solution:
+ def isHappy(self, n: int) -> bool:
+ slow, fast = n, self.sumOfSquares(n)
+ power = lam = 1
+
+ while slow != fast:
+ if power == lam:
+ slow = fast
+ power *= 2
+ lam = 0
+ fast = self.sumOfSquares(fast)
+ lam += 1
+ return True if fast == 1 else False
+
+ def sumOfSquares(self, n: int) -> int:
+ output = 0
+
+ while n:
+ digit = n % 10
+ digit = digit ** 2
+ output += digit
+ n = n // 10
+ return output",0.0,GFG,,PYTHON,"class Solution:
+ def isHappy(self, n: int) -> bool:
+ slow, fast = n, self.sumOfSquares(n)
+ power = lam = 1
+
+ while slow != fast:
+ if power == lam:
+ slow = fast
+ power *= 2
+ lam = 0
+ fast = self.sumOfSquares(fast)
+ lam += 1
+ return True if fast == 1 else False
+
+ def sumOfSquares(self, n: int) -> int:
+ output = 0
+
+ while n:
+ digit = n % 10
+ digit = digit ** 2
+ output += digit
+ n = n // 10
+ return output",23,23
+,"def isInterleave(s1, s2, s3):
+ if len(s1) + len(s2) != len(s3):
+ return False
+
+ dp = [[False] * (len(s2) + 1) for _ in range(len(s1) + 1)]
+ dp[0][0] = True
+
+ for i in range(len(s1) + 1):
+ for j in range(len(s2) + 1):
+ if i > 0:
+ dp[i][j] |= dp[i - 1][j] and s1[i - 1] == s3[i + j - 1]
+ if j > 0:
+ dp[i][j] |= dp[i][j - 1] and s2[j - 1] == s3[i + j - 1]
+
+ return dp[-1][-1]
+",1.0,GPT,"Solve the problem ""Interleaving String"".
+
+Given strings s1, s2, and s3,
+determine if s3 is formed by interleaving s1 and s2.",PYTHON,"def isInterleave(s1, s2, s3):
+ if len(s1) + len(s2) != len(s3):
+ return False
+
+ dp = [[False] * (len(s2) + 1) for _ in range(len(s1) + 1)]
+ dp[0][0] = True
+
+ for i in range(len(s1) + 1):
+ for j in range(len(s2) + 1):
+ if i > 0:
+ dp[i][j] |= dp[i - 1][j] and s1[i - 1] == s3[i + j - 1]
+ if j > 0:
+ dp[i][j] |= dp[i][j - 1] and s2[j - 1] == s3[i + j - 1]
+
+ return dp[-1][-1]",15,15
+,"class Solution:
+ def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
+ m, n = len(s1), len(s2)
+ if m + n != len(s3):
+ return False
+ if n < m:
+ s1, s2 = s2, s1
+ m, n = n, m
+
+ dp = [False for _ in range(n + 1)]
+ dp[n] = True
+ for i in range(m, -1, -1):
+ nextDp = True if i == m else False
+ for j in range(n, -1, -1):
+ res = False if j < n else nextDp
+ if i < m and s1[i] == s3[i + j] and dp[j]:
+ res = True
+ if j < n and s2[j] == s3[i + j] and nextDp:
+ res = True
+ dp[j] = res
+ nextDp = dp[j]
+ return dp[0]",0.0,GFG,,PYTHON,"class Solution:
+ def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
+ m, n = len(s1), len(s2)
+ if m + n != len(s3):
+ return False
+ if n < m:
+ s1, s2 = s2, s1
+ m, n = n, m
+
+ dp = [False for _ in range(n + 1)]
+ dp[n] = True
+ for i in range(m, -1, -1):
+ nextDp = True if i == m else False
+ for j in range(n, -1, -1):
+ res = False if j < n else nextDp
+ if i < m and s1[i] == s3[i + j] and dp[j]:
+ res = True
+ if j < n and s2[j] == s3[i + j] and nextDp:
+ res = True
+ dp[j] = res
+ nextDp = dp[j]
+ return dp[0]",22,22
+,"def findTargetSumWays(nums, target):
+ total = sum(nums)
+ if abs(target) > total or (total + target) % 2:
+ return 0
+
+ s = (total + target) // 2
+ dp = [0] * (s + 1)
+ dp[0] = 1
+
+ for num in nums:
+ for i in range(s, num - 1, -1):
+ dp[i] += dp[i - num]
+
+ return dp[s]
+",1.0,GPT,"Solve the problem ""Target Sum"".
+
+Given an array nums and a target,
+return the number of ways to assign + or - to reach target.",PYTHON,"def findTargetSumWays(nums, target):
+ total = sum(nums)
+ if abs(target) > total or (total + target) % 2:
+ return 0
+
+ s = (total + target) // 2
+ dp = [0] * (s + 1)
+ dp[0] = 1
+
+ for num in nums:
+ for i in range(s, num - 1, -1):
+ dp[i] += dp[i - num]
+
+ return dp[s]",14,14
+,"class Solution:
+ def findTargetSumWays(self, nums: List[int], target: int) -> int:
+ dp = defaultdict(int)
+ dp[0] = 1
+
+ for num in nums:
+ next_dp = defaultdict(int)
+ for total, count in dp.items():
+ next_dp[total + num] += count
+ next_dp[total - num] += count
+ dp = next_dp
+
+ return dp[target]",0.0,GFG,,PYTHON,"class Solution:
+ def findTargetSumWays(self, nums: List[int], target: int) -> int:
+ dp = defaultdict(int)
+ dp[0] = 1
+
+ for num in nums:
+ next_dp = defaultdict(int)
+ for total, count in dp.items():
+ next_dp[total + num] += count
+ next_dp[total - num] += count
+ dp = next_dp
+
+ return dp[target]",13,13
+,"def numDecodings(s):
+ if not s or s[0] == ""0"":
+ return 0
+
+ dp1, dp2 = 1, 1
+
+ for i in range(1, len(s)):
+ cur = 0
+ if s[i] != ""0"":
+ cur += dp2
+ if 10 <= int(s[i - 1:i + 1]) <= 26:
+ cur += dp1
+ dp1, dp2 = dp2, cur
+
+ return dp2
+",1.0,GPT,"Solve the problem ""Decode Ways"".
+
+Given a string s containing digits,
+return the number of ways to decode it.",PYTHON,"def numDecodings(s):
+ if not s or s[0] == ""0"":
+ return 0
+
+ dp1, dp2 = 1, 1
+
+ for i in range(1, len(s)):
+ cur = 0
+ if s[i] != ""0"":
+ cur += dp2
+ if 10 <= int(s[i - 1:i + 1]) <= 26:
+ cur += dp1
+ dp1, dp2 = dp2, cur
+
+ return dp2",15,15
+,"class Solution:
+ def numDecodings(self, s: str) -> int:
+ dp = dp2 = 0
+ dp1 = 1
+ for i in range(len(s) - 1, -1, -1):
+ if s[i] == ""0"":
+ dp = 0
+ else:
+ dp = dp1
+
+ if i + 1 < len(s) and (s[i] == ""1"" or
+ s[i] == ""2"" and s[i + 1] in ""0123456""
+ ):
+ dp += dp2
+ dp, dp1, dp2 = 0, dp, dp1
+ return dp1",0.0,GFG,,PYTHON,"class Solution:
+ def numDecodings(self, s: str) -> int:
+ dp = dp2 = 0
+ dp1 = 1
+ for i in range(len(s) - 1, -1, -1):
+ if s[i] == ""0"":
+ dp = 0
+ else:
+ dp = dp1
+
+ if i + 1 < len(s) and (s[i] == ""1"" or
+ s[i] == ""2"" and s[i + 1] in ""0123456""
+ ):
+ dp += dp2
+ dp, dp1, dp2 = 0, dp, dp1
+ return dp1",16,16
+,"import json
+json_obj = '{ ""Name"":""David"", ""Class"":""I"", ""Age"":6 }'
+python_obj = json.loads(json_obj)
+print(""\nJSON data:"")
+print(python_obj)
+print(""\nName: "",python_obj[""Name""])
+print(""Class: "",python_obj[""Class""])
+print(""Age: "",python_obj[""Age""])
",0.0,WE3RESOURCE,,PYTHON,"import json
+json_obj = '{ ""Name"":""David"", ""Class"":""I"", ""Age"":6 }'
+python_obj = json.loads(json_obj)
+print(""\nJSON data:"")
+print(python_obj)
+print(""\nName: "",python_obj[""Name""])
+print(""Class: "",python_obj[""Class""])
+print(""Age: "",python_obj[""Age""]) ",8,8
+,"import requests
+from requests.exceptions import SSLError, RequestException
+
+url = ""https://www.google.com"" # valid SSL certificate
+
+try:
+ # By default, verify=True, so SSL certificates are checked
+ response = requests.get(url, timeout=10)
+ print(""Status Code:"", response.status_code)
+ print(""SSL certificate verified successfully."")
+
+except SSLError as ssl_err:
+ print(""SSL Certificate verification failed!"")
+ print(ssl_err)
+
+except RequestException as req_err:
+ print(""Request failed:"")
+ print(req_err)
",1.0,GPT," Write a Python program to verifiy SSL certificates for HTTPS requests using requests module.
+Note: Requests verifies SSL certificates for HTTPS requests, just like a web browser. By default, SSL verification is enabled, and Requests will throw a SSLError if it's unable to verify the certificate",PYTHON,"import requests
+from requests.exceptions import SSLError, RequestException
+
+url = ""https://www.google.com"" # valid SSL certificate
+
+try:
+ # By default, verify=True, so SSL certificates are checked
+ response = requests.get(url, timeout=10)
+ print(""Status Code:"", response.status_code)
+ print(""SSL certificate verified successfully."")
+
+except SSLError as ssl_err:
+ print(""SSL Certificate verification failed!"")
+ print(ssl_err)
+
+except RequestException as req_err:
+ print(""Request failed:"")
+ print(req_err)",18,18
+,"import json
+# a Python object (dict):
+python_obj = {
+ ""name"": ""David"",
+ ""class"":""I"",
+ ""age"": 6
+}
+print(type(python_obj))
+# convert into JSON:
+j_data = json.dumps(python_obj)
+
+# result is a JSON string:
+print(j_data)
",0.0,WE3RESOURCE,,PYTHON,"import json
+# a Python object (dict):
+python_obj = {
+ ""name"": ""David"",
+ ""class"":""I"",
+ ""age"": 6
+}
+print(type(python_obj))
+# convert into JSON:
+j_data = json.dumps(python_obj)
+
+# result is a JSON string:
+print(j_data)",13,13
+,"import requests
+
+url = ""https://www.example.com""
+
+# Send GET request
+response = requests.get(url)
+
+print(""URL:"", response.url)
+print(""Status Code:"", response.status_code)
+print(""Reason:"", response.reason)
+print(""Encoding:"", response.encoding)
+
+print(""\nHeaders:"")
+for key, value in response.headers.items():
+ print(f""{key}: {value}"")
+
+print(""\nHistory (Redirects):"")
+print(response.history)
+
+print(""\nCookies:"")
+print(response.cookies)
+
+print(""\nElapsed Time:"")
+print(response.elapsed)
+
+print(""\nRequest Info:"")
+print(""Method:"", response.request.method)
+print(""Request URL:"", response.request.url)
+print(""Request Headers:"", response.request.headers)
+
+print(""\nContent (first 500 bytes):"")
+print(response.content[:500])
",1.0,GPT," Write a Python program to display the contains of different attributes like different attributes like status_code, headers, url, history, encoding, reason, cookies, elapsed, request and content of a specified resource.",PYTHON,"import requests
+
+url = ""https://www.example.com""
+
+# Send GET request
+response = requests.get(url)
+
+print(""URL:"", response.url)
+print(""Status Code:"", response.status_code)
+print(""Reason:"", response.reason)
+print(""Encoding:"", response.encoding)
+
+print(""\nHeaders:"")
+for key, value in response.headers.items():
+ print(f""{key}: {value}"")
+
+print(""\nHistory (Redirects):"")
+print(response.history)
+
+print(""\nCookies:"")
+print(response.cookies)
+
+print(""\nElapsed Time:"")
+print(response.elapsed)
+
+print(""\nRequest Info:"")
+print(""Method:"", response.request.method)
+print(""Request URL:"", response.request.url)
+print(""Request Headers:"", response.request.headers)
+
+print(""\nContent (first 500 bytes):"")
+print(response.content[:500])",32,32
+,"import json
+python_dict = {""name"": ""David"", ""age"": 6, ""class"":""I""}
+python_list = [""Red"", ""Green"", ""Black""]
+python_str = ""Python Json""
+python_int = (1234)
+python_float = (21.34)
+python_T = (True)
+python_F = (False)
+python_N = (None)
+
+json_dict = json.dumps(python_dict)
+json_list = json.dumps(python_list)
+json_str = json.dumps(python_str)
+json_num1 = json.dumps(python_int)
+json_num2 = json.dumps(python_float)
+json_t = json.dumps(python_T)
+json_f = json.dumps(python_F)
+json_n = json.dumps(python_N)
+
+print(""json dict : "", json_dict)
+print(""jason list : "", json_list)
+print(""json string : "", json_str)
+print(""json number1 : "", json_num1)
+print(""json number2 : "", json_num2)
+print(""json true : "", json_t)
+print(""json false : "", json_f)
+print(""json null ; "", json_n)
",0.0,WE3RESOURCE,,PYTHON,"import json
+python_dict = {""name"": ""David"", ""age"": 6, ""class"":""I""}
+python_list = [""Red"", ""Green"", ""Black""]
+python_str = ""Python Json""
+python_int = (1234)
+python_float = (21.34)
+python_T = (True)
+python_F = (False)
+python_N = (None)
+
+json_dict = json.dumps(python_dict)
+json_list = json.dumps(python_list)
+json_str = json.dumps(python_str)
+json_num1 = json.dumps(python_int)
+json_num2 = json.dumps(python_float)
+json_t = json.dumps(python_T)
+json_f = json.dumps(python_F)
+json_n = json.dumps(python_N)
+
+print(""json dict : "", json_dict)
+print(""jason list : "", json_list)
+print(""json string : "", json_str)
+print(""json number1 : "", json_num1)
+print(""json number2 : "", json_num2)
+print(""json true : "", json_t)
+print(""json false : "", json_f)
+print(""json null ; "", json_n)",27,27
+,"import requests
+import datetime
+
+def get_m4_5_plus_count(start_time: str, end_time: str) -> int:
+ """"""
+ Returns the number of earthquakes globally with magnitude >= 4.5
+ between start_time and end_time (ISO format).
+ """"""
+ url = ""https://earthquake.usgs.gov/fdsnws/event/1/query""
+ params = {
+ ""format"": ""geojson"",
+ ""starttime"": start_time,
+ ""endtime"": end_time,
+ ""minmagnitude"": 4.5,
+ }
+
+ response = requests.get(url, params=params)
+
+ if response.status_code == 200:
+ data = response.json()
+ # 'count' field in 'metadata' holds the number of matching events
+ return data.get(""metadata"", {}).get(""count"", 0)
+ else:
+ print(f""Error: {response.status_code}"")
+ return 0
+
+if __name__ == ""__main__"":
+ # Set time period (last 30 days)
+ end_time = datetime.datetime.utcnow().date().isoformat()
+ start_time = (datetime.datetime.utcnow() - datetime.timedelta(days=30)).date().isoformat()
+
+ count = get_m4_5_plus_count(start_time, end_time)
+ print(f""Number of earthquakes with magnitude >= 4.5 between {start_time} and {end_time}: {count}"")
",1.0,GPT,Write a Python program to get the number of magnitude 4.5+ earthquakes detected worldwide by the USGS.,PYTHON,"import requests
+import datetime
+
+def get_m4_5_plus_count(start_time: str, end_time: str) -> int:
+ """"""
+ Returns the number of earthquakes globally with magnitude >= 4.5
+ between start_time and end_time (ISO format).
+ """"""
+ url = ""https://earthquake.usgs.gov/fdsnws/event/1/query""
+ params = {
+ ""format"": ""geojson"",
+ ""starttime"": start_time,
+ ""endtime"": end_time,
+ ""minmagnitude"": 4.5,
+ }
+
+ response = requests.get(url, params=params)
+
+ if response.status_code == 200:
+ data = response.json()
+ # 'count' field in 'metadata' holds the number of matching events
+ return data.get(""metadata"", {}).get(""count"", 0)
+ else:
+ print(f""Error: {response.status_code}"")
+ return 0
+
+if __name__ == ""__main__"":
+ # Set time period (last 30 days)
+ end_time = datetime.datetime.utcnow().date().isoformat()
+ start_time = (datetime.datetime.utcnow() - datetime.timedelta(days=30)).date().isoformat()
+
+ count = get_m4_5_plus_count(start_time, end_time)
+ print(f""Number of earthquakes with magnitude >= 4.5 between {start_time} and {end_time}: {count}"")",33,33
+,"import json
+j_str = {'4': 5, '6': 7, '1': 3, '2': 4}
+print(""Original String:"")
+print(j_str)
+print(""\nJSON data:"")
+print(json.dumps(j_str, sort_keys=True, indent=4))
",0.0,WE3RESOURCE,,PYTHON,"import json
+j_str = {'4': 5, '6': 7, '1': 3, '2': 4}
+print(""Original String:"")
+print(j_str)
+print(""\nJSON data:"")
+print(json.dumps(j_str, sort_keys=True, indent=4))",6,6
+,"import requests
+import random
+
+API_KEY = ""YOUR_TMDB_API_KEY"" # <-- replace with your API key
+BASE_URL = ""https://api.themoviedb.org/3""
+
+# Step 1: Get popular movies (several pages available)
+popular_url = f""{BASE_URL}/movie/popular""
+params = {
+ ""api_key"": API_KEY,
+ ""language"": ""en-US"",
+ ""page"": random.randint(1, 20) # random page for randomness
+}
+
+response = requests.get(popular_url, params=params)
+response.raise_for_status()
+
+movies = response.json()[""results""]
+
+# Step 2: Randomly select 10 movies
+random_movies = random.sample(movies, 10)
+
+print(""Top 10 Random Movies:\n"")
+
+for i, movie in enumerate(random_movies, start=1):
+ title = movie[""title""]
+ year = movie[""release_date""][:4] if movie[""release_date""] else ""N/A""
+ summary = movie[""overview""]
+
+ print(f""{i}. Movie Name : {title}"")
+ print(f"" Year : {year}"")
+ print(f"" Summary : {summary}\n"")
",1.0,GPT,"Write a Python program to get movie name, year and a brief summary of the top 10 random movies",PYTHON,"import requests
+import random
+
+API_KEY = ""YOUR_TMDB_API_KEY"" # <-- replace with your API key
+BASE_URL = ""https://api.themoviedb.org/3""
+
+# Step 1: Get popular movies (several pages available)
+popular_url = f""{BASE_URL}/movie/popular""
+params = {
+ ""api_key"": API_KEY,
+ ""language"": ""en-US"",
+ ""page"": random.randint(1, 20) # random page for randomness
+}
+
+response = requests.get(popular_url, params=params)
+response.raise_for_status()
+
+movies = response.json()[""results""]
+
+# Step 2: Randomly select 10 movies
+random_movies = random.sample(movies, 10)
+
+print(""Top 10 Random Movies:\n"")
+
+for i, movie in enumerate(random_movies, start=1):
+ title = movie[""title""]
+ year = movie[""release_date""][:4] if movie[""release_date""] else ""N/A""
+ summary = movie[""overview""]
+
+ print(f""{i}. Movie Name : {title}"")
+ print(f"" Year : {year}"")
+ print(f"" Summary : {summary}\n"")",32,32
+,"import json
+
+jobj_dict = '{""name"": ""David"", ""age"": 6, ""class"": ""I""}'
+jobj_list = '[""Red"", ""Green"", ""Black""]'
+jobj_string = '""Python Json""'
+jobj_int = '1234'
+jobj_float = '21.34'
+python_dict = json.loads(jobj_dict)
+python_list = json.loads(jobj_list)
+python_str = json.loads(jobj_string)
+python_int = json.loads(jobj_int)
+python_float = json.loads(jobj_float)
+
+print(""Python dictionary: "", python_dict)
+print(""Python list: "", python_list)
+print(""Python string: "", python_str)
+print(""Python integer: "", python_int)
+print(""Python float: "", python_float)
",0.0,WE3RESOURCE,,PYTHON,"import json
+
+jobj_dict = '{""name"": ""David"", ""age"": 6, ""class"": ""I""}'
+jobj_list = '[""Red"", ""Green"", ""Black""]'
+jobj_string = '""Python Json""'
+jobj_int = '1234'
+jobj_float = '21.34'
+python_dict = json.loads(jobj_dict)
+python_list = json.loads(jobj_list)
+python_str = json.loads(jobj_string)
+python_int = json.loads(jobj_int)
+python_float = json.loads(jobj_float)
+
+print(""Python dictionary: "", python_dict)
+print(""Python list: "", python_list)
+print(""Python string: "", python_str)
+print(""Python integer: "", python_int)
+print(""Python float: "", python_float)",18,18
+,"import requests, time
+from bs4 import BeautifulSoup
+
+B=""https://www.imdb.com""; H={""User-Agent"":""Mozilla/5.0""}
+s=BeautifulSoup(requests.get(B+""/chart/top/"",headers=H).text,""html.parser"")
+
+for m in s.select(""td.titleColumn""):
+ t=m.a.text; y=m.span.text.strip(""()""); u=B+m.a[""href""]
+ d=BeautifulSoup(requests.get(u,headers=H).text,""html.parser"").select(""div.credit_summary_item"")
+ dr="", "".join(a.text for a in d[0].select(""a""))
+ st="", "".join(a.text for a in d[1].select(""a"") if ""name"" in a[""href""])
+ print(f""{t} ({y}) | Dir: {dr} | Stars: {st}"")
+ time.sleep(0.5)
",1.0,GPT,"Write a Python program to download IMDB's Top 250 data (movie name, Initial release, director name and stars).GIVE ME THE CODE AS SHORT AS POSSIBLE",PYTHON,"import requests, time
+from bs4 import BeautifulSoup
+
+B=""https://www.imdb.com""; H={""User-Agent"":""Mozilla/5.0""}
+s=BeautifulSoup(requests.get(B+""/chart/top/"",headers=H).text,""html.parser"")
+
+for m in s.select(""td.titleColumn""):
+ t=m.a.text; y=m.span.text.strip(""()""); u=B+m.a[""href""]
+ d=BeautifulSoup(requests.get(u,headers=H).text,""html.parser"").select(""div.credit_summary_item"")
+ dr="", "".join(a.text for a in d[0].select(""a""))
+ st="", "".join(a.text for a in d[1].select(""a"") if ""name"" in a[""href""])
+ print(f""{t} ({y}) | Dir: {dr} | Stars: {st}"")
+ time.sleep(0.5)",13,13
+,"import json
+
+with open('states.json') as f:
+ state_data= json.load(f)
+
+for state in state_data['states']:
+ del state['area_codes']
+
+with open('new_states.json', 'w') as f:
+ json.dump(state_data, f, indent=2)
",0.0,WE3RESOURCE,,PYTHON,"import json
+
+with open('states.json') as f:
+ state_data= json.load(f)
+
+for state in state_data['states']:
+ del state['area_codes']
+
+with open('new_states.json', 'w') as f:
+ json.dump(state_data, f, indent=2)",10,10
+,"import requests
+from bs4 import BeautifulSoup
+
+url = ""https://mlh.io/seasons/2026/events""
+headers = {""User-Agent"":""Mozilla/5.0""}
+
+# Fetch event list
+resp = requests.get(url, headers=headers)
+soup = BeautifulSoup(resp.text, ""html.parser"")
+
+events = soup.select("".event-card"")[:25] # next 25 events
+
+print(f""{'Date':<20}{'Days':<10}{'Title':<50}{'City':<20}{'Country'}"")
+
+for e in events:
+ date = e.select_one("".event-date"").text.strip() if e.select_one("".event-date"") else ""N/A""
+ title = e.select_one("".event-name"").text.strip() if e.select_one("".event-name"") else ""N/A""
+ location = e.select_one("".event-location"").text.strip().split("","") if e.select_one("".event-location"") else [""N/A""]
+ city = location[0].strip() if len(location)>0 else ""N/A""
+ country = location[-1].strip() if len(location)>1 else ""N/A""
+
+ # compute approximate event duration if date range present
+ days = ""1"" if ""-"" not in date else date.split(""-"")[1].strip()
+
+ print(f""{date:<20}{days:<10}{title:<50}{city:<20}{country}"")
",1.0,GPT,"Write a Python program to display the date, days, title, city, country of next 25 Hackevents.",PYTHON,"import requests
+from bs4 import BeautifulSoup
+
+url = ""https://mlh.io/seasons/2026/events""
+headers = {""User-Agent"":""Mozilla/5.0""}
+
+# Fetch event list
+resp = requests.get(url, headers=headers)
+soup = BeautifulSoup(resp.text, ""html.parser"")
+
+events = soup.select("".event-card"")[:25] # next 25 events
+
+print(f""{'Date':<20}{'Days':<10}{'Title':<50}{'City':<20}{'Country'}"")
+
+for e in events:
+ date = e.select_one("".event-date"").text.strip() if e.select_one("".event-date"") else ""N/A""
+ title = e.select_one("".event-name"").text.strip() if e.select_one("".event-name"") else ""N/A""
+ location = e.select_one("".event-location"").text.strip().split("","") if e.select_one("".event-location"") else [""N/A""]
+ city = location[0].strip() if len(location)>0 else ""N/A""
+ country = location[-1].strip() if len(location)>1 else ""N/A""
+
+ # compute approximate event duration if date range present
+ days = ""1"" if ""-"" not in date else date.split(""-"")[1].strip()
+
+ print(f""{date:<20}{days:<10}{title:<50}{city:<20}{country}"")",25,25
+,"import json
+
+def encode_complex(object):
+ # check using isinstance method
+ if isinstance(object, complex):
+ return [object.real, object.imag]
+ # raised error if object is not complex
+ raise TypeError(repr(object) + "" is not JSON serialized"")
+
+complex_obj = json.dumps(2 + 3j, default=encode_complex)
+print(complex_obj)
",0.0,WE3RESOURCE,,PYTHON,"import json
+
+def encode_complex(object):
+ # check using isinstance method
+ if isinstance(object, complex):
+ return [object.real, object.imag]
+ # raised error if object is not complex
+ raise TypeError(repr(object) + "" is not JSON serialized"")
+
+complex_obj = json.dumps(2 + 3j, default=encode_complex)
+print(complex_obj) ",11,11
+,"import requests
+
+API_KEY = ""YOUR_API_KEY_HERE"" # <-- put your API key here
+
+city = input(""Enter city name: "")
+
+url = ""https://api.openweathermap.org/data/2.5/weather""
+params = {
+ ""q"": city,
+ ""appid"": API_KEY,
+ ""units"": ""metric"" # Celsius
+}
+
+try:
+ r = requests.get(url, params=params, timeout=10)
+ r.raise_for_status()
+ data = r.json()
+
+ temp = data[""main""][""temp""]
+ wind = data[""wind""][""speed""]
+ weather = data[""weather""][0][""main""]
+ desc = data[""weather""][0][""description""]
+
+ print(""\nLive Weather Report"")
+ print(""-------------------"")
+ print(""City :"", city)
+ print(""Temperature :"", temp, ""°C"")
+ print(""Wind Speed :"", wind, ""m/s"")
+ print(""Weather :"", weather)
+ print(""Description :"", desc)
+
+except requests.exceptions.RequestException as e:
+ print(""Error fetching weather data:"", e)
",1.0,GPT," Write a Python program to find the live weather report (temperature, wind speed, description and weather) of a given city.let the code u give me be efficient and clear ",PYTHON,"import requests
+
+API_KEY = ""YOUR_API_KEY_HERE"" # <-- put your API key here
+
+city = input(""Enter city name: "")
+
+url = ""https://api.openweathermap.org/data/2.5/weather""
+params = {
+ ""q"": city,
+ ""appid"": API_KEY,
+ ""units"": ""metric"" # Celsius
+}
+
+try:
+ r = requests.get(url, params=params, timeout=10)
+ r.raise_for_status()
+ data = r.json()
+
+ temp = data[""main""][""temp""]
+ wind = data[""wind""][""speed""]
+ weather = data[""weather""][0][""main""]
+ desc = data[""weather""][0][""description""]
+
+ print(""\nLive Weather Report"")
+ print(""-------------------"")
+ print(""City :"", city)
+ print(""Temperature :"", temp, ""°C"")
+ print(""Wind Speed :"", wind, ""m/s"")
+ print(""Weather :"", weather)
+ print(""Description :"", desc)
+
+except requests.exceptions.RequestException as e:
+ print(""Error fetching weather data:"", e)",33,33
+,"import json
+def is_complex_num(objct):
+ if '__complex__' in objct:
+ return complex(objct['real'], objct['img'])
+ return objct
+
+complex_object =json.loads('{""__complex__"": true, ""real"": 4, ""img"": 5}', object_hook = is_complex_num)
+simple_object =json.loads('{""real"": 4, ""img"": 3}', object_hook = is_complex_num)
+print(""Complex_object: "",complex_object)
+print(""Without complex object: "",simple_object)
+",0.0,WE3RESOURCE,,PYTHON,"import json
+def is_complex_num(objct):
+ if '__complex__' in objct:
+ return complex(objct['real'], objct['img'])
+ return objct
+
+complex_object =json.loads('{""__complex__"": true, ""real"": 4, ""img"": 5}', object_hook = is_complex_num)
+simple_object =json.loads('{""real"": 4, ""img"": 3}', object_hook = is_complex_num)
+print(""Complex_object: "",complex_object)
+print(""Without complex object: "",simple_object)",10,10
+,"import snscrape.modules.twitter as sntwitter
+
+username = input(""Enter Twitter username: "")
+
+count = 0
+for i, _ in enumerate(sntwitter.TwitterUserScraper(username).get_items()):
+ if i == 1000: break
+ count += 1
+
+print(f""Tweets counted (latest 1000 max): {count}"")
+",1.0,GPT,Write a Python program to scrap number of tweets of a given Twitter account. ASK THE USER TO INPUT THIER ACCOUNT ,PYTHON,"import snscrape.modules.twitter as sntwitter
+
+username = input(""Enter Twitter username: "")
+
+count = 0
+for i, _ in enumerate(sntwitter.TwitterUserScraper(username).get_items()):
+ if i == 1000: break
+ count += 1
+
+print(f""Tweets counted (latest 1000 max): {count}"")",10,10
+,"import json
+python_obj = '{""a"": 1, ""a"": 2, ""a"": 3, ""a"": 4, ""b"": 1, ""b"": 2}'
+print(""Original Python object:"")
+print(python_obj)
+json_obj = json.loads(python_obj)
+print(""\nUnique Key in a JSON object:"")
+print(json_obj)
+",0.0,WE3RESOURCE,,PYTHON,"import json
+python_obj = '{""a"": 1, ""a"": 2, ""a"": 3, ""a"": 4, ""b"": 1, ""b"": 2}'
+print(""Original Python object:"")
+print(python_obj)
+json_obj = json.loads(python_obj)
+print(""\nUnique Key in a JSON object:"")
+print(json_obj) ",7,7
+,"import tweepy
+
+# Replace with your actual bearer token from Twitter Developer Portal
+BEARER_TOKEN = 'YOUR_BEARER_TOKEN_HERE'
+
+# Initialize the client with bearer token (sufficient for read access)
+client = tweepy.Client(bearer_token=BEARER_TOKEN)
+
+# Input for Twitter username (without @)
+username = input(""Enter Twitter username: "")
+
+try:
+ # Get the user by username
+ user = client.get_user(username=username)
+
+ if user.data:
+ # Access public_metrics which includes total tweet count
+ public_metrics = user.data.public_metrics
+ tweet_count = public_metrics['tweet_count']
+
+ print(f""@{username} has posted {tweet_count:,} tweets (including retweets and replies)."")
+ else:
+ print(""User not found."")
+
+except tweepy.TweepyException as e:
+ print(f""Error: {e}"")
+",1.0,PERPLEXITY,Write a Python program to count number of tweets by a given Twitter account. add a input feature where the user would give their account as an input .,PYTHON,"import tweepy
+
+# Replace with your actual bearer token from Twitter Developer Portal
+BEARER_TOKEN = 'YOUR_BEARER_TOKEN_HERE'
+
+# Initialize the client with bearer token (sufficient for read access)
+client = tweepy.Client(bearer_token=BEARER_TOKEN)
+
+# Input for Twitter username (without @)
+username = input(""Enter Twitter username: "")
+
+try:
+ # Get the user by username
+ user = client.get_user(username=username)
+
+ if user.data:
+ # Access public_metrics which includes total tweet count
+ public_metrics = user.data.public_metrics
+ tweet_count = public_metrics['tweet_count']
+
+ print(f""@{username} has posted {tweet_count:,} tweets (including retweets and replies)."")
+ else:
+ print(""User not found."")
+
+except tweepy.TweepyException as e:
+ print(f""Error: {e}"")",26,26
+,"from urllib.request import urlopen
+from bs4 import BeautifulSoup
+html = urlopen('https://www.wikipedia.org/')
+bs = BeautifulSoup(html, ""html.parser"")
+nameList = bs.findAll('a', {'class' : 'link-box'})
+for name in nameList:
+ print(name.get_text())
+ ",0.0,WE3RESOURCE,,PYTHON,"from urllib.request import urlopen
+from bs4 import BeautifulSoup
+html = urlopen('https://www.wikipedia.org/')
+bs = BeautifulSoup(html, ""html.parser"")
+nameList = bs.findAll('a', {'class' : 'link-box'})
+for name in nameList:
+ print(name.get_text())",7,7
+,"import tweepy
+
+# Replace with your actual bearer token from X Developer Portal
+BEARER_TOKEN = 'YOUR_BEARER_TOKEN_HERE'
+
+# Initialize the client with bearer token (sufficient for read access)
+client = tweepy.Client(bearer_token=BEARER_TOKEN)
+
+# Input for Twitter username (without @)
+username = input(""Enter Twitter username: "")
+
+try:
+ # Get the user by username
+ user = client.get_user(username=username, user_fields=['public_metrics'])
+
+ if user.data:
+ # Access public_metrics.like_count for number of liked posts
+ public_metrics = user.data.public_metrics
+ likes_count = public_metrics['like_count']
+
+ print(f""@{username} has liked {likes_count:,} posts."")
+ else:
+ print(""User not found."")
+
+except tweepy.TweepyException as e:
+ print(f""Error: {e}"")
",1.0,PERPLEXITY,Write a Python program to get the number of post on Twitter liked by a given account,PYTHON,"import tweepy
+
+# Replace with your actual bearer token from X Developer Portal
+BEARER_TOKEN = 'YOUR_BEARER_TOKEN_HERE'
+
+# Initialize the client with bearer token (sufficient for read access)
+client = tweepy.Client(bearer_token=BEARER_TOKEN)
+
+# Input for Twitter username (without @)
+username = input(""Enter Twitter username: "")
+
+try:
+ # Get the user by username
+ user = client.get_user(username=username, user_fields=['public_metrics'])
+
+ if user.data:
+ # Access public_metrics.like_count for number of liked posts
+ public_metrics = user.data.public_metrics
+ likes_count = public_metrics['like_count']
+
+ print(f""@{username} has liked {likes_count:,} posts."")
+ else:
+ print(""User not found."")
+
+except tweepy.TweepyException as e:
+ print(f""Error: {e}"")",26,26
+,"#https://bit.ly/2lVhlLX
+# via: https://analytics.usa.gov/
+import requests
+url = 'https://analytics.usa.gov/data/live/realtime.json'
+j = requests.get(url).json()
+print(""Number of people visiting a U.S. government website-"")
+print(""Active Users Right Now:"")
+print(j['data'][0]['active_visitors'])
+ ",0.0,WE3RESOURCE,,PYTHON,"#https://bit.ly/2lVhlLX
+# via: https://analytics.usa.gov/
+import requests
+url = 'https://analytics.usa.gov/data/live/realtime.json'
+j = requests.get(url).json()
+print(""Number of people visiting a U.S. government website-"")
+print(""Active Users Right Now:"")
+print(j['data'][0]['active_visitors'])",8,8
+,"import tweepy
+
+# Replace with your actual bearer token from X Developer Portal
+BEARER_TOKEN = 'YOUR_BEARER_TOKEN_HERE'
+
+# Initialize the client with bearer token (sufficient for read access)
+client = tweepy.Client(bearer_token=BEARER_TOKEN)
+
+# Input for Twitter username (without @)
+username = input(""Enter Twitter username: "")
+
+try:
+ # Get the user by username with public_metrics
+ user = client.get_user(username=username, user_fields=['public_metrics'])
+
+ if user.data:
+ # Access public_metrics.following count
+ public_metrics = user.data.public_metrics
+ following_count = public_metrics['following']
+
+ print(f""@{username} is following {following_count:,} accounts."")
+ else:
+ print(""User not found."")
+
+except tweepy.TweepyException as e:
+ print(f""Error: {e}"")
",1.0,PERPLEXITY,Write a Python program to get the number of following on a Twitter account.,PYTHON,"import tweepy
+
+# Replace with your actual bearer token from X Developer Portal
+BEARER_TOKEN = 'YOUR_BEARER_TOKEN_HERE'
+
+# Initialize the client with bearer token (sufficient for read access)
+client = tweepy.Client(bearer_token=BEARER_TOKEN)
+
+# Input for Twitter username (without @)
+username = input(""Enter Twitter username: "")
+
+try:
+ # Get the user by username with public_metrics
+ user = client.get_user(username=username, user_fields=['public_metrics'])
+
+ if user.data:
+ # Access public_metrics.following count
+ public_metrics = user.data.public_metrics
+ following_count = public_metrics['following']
+
+ print(f""@{username} is following {following_count:,} accounts."")
+ else:
+ print(""User not found."")
+
+except tweepy.TweepyException as e:
+ print(f""Error: {e}"")",26,26
+,"#https://bit.ly/2lVhlLX
+import requests
+from lxml import html
+url = 'https://www.us-cert.gov/ncas/alerts'
+doc = html.fromstring(requests.get(url).text)
+print(""The number of security alerts issued by US-CERT in the current year:"")
+print(len(doc.cssselect('.item-list li')))
+ ",0.0,WE3RESOURCE,,PYTHON,"#https://bit.ly/2lVhlLX
+import requests
+from lxml import html
+url = 'https://www.us-cert.gov/ncas/alerts'
+doc = html.fromstring(requests.get(url).text)
+print(""The number of security alerts issued by US-CERT in the current year:"")
+print(len(doc.cssselect('.item-list li')))",7,7
+,"import tweepy
+
+client = tweepy.Client(bearer_token='YOUR_BEARER_TOKEN_HERE')
+username = input(""Enter Twitter username: "")
+
+try:
+ user = client.get_user(username=username, user_fields=['public_metrics'])
+ print(f""@{username} has {user.data.public_metrics['followers_count']:,} followers"")
+except:
+ print(""Error fetching data"")
",1.0,PERPLEXITY,Write a Python program to get the number of followers of a given twitter account. GIVE THE CODE IN FEWER LINES FOR EFFECTIVENESS,PYTHON,"import tweepy
+
+client = tweepy.Client(bearer_token='YOUR_BEARER_TOKEN_HERE')
+username = input(""Enter Twitter username: "")
+
+try:
+ user = client.get_user(username=username, user_fields=['public_metrics'])
+ print(f""@{username} has {user.data.public_metrics['followers_count']:,} followers"")
+except:
+ print(""Error fetching data"")",10,10
+,"#https://bit.ly/2lVhlLX
+import requests
+from lxml import html
+url = 'http://www.state.gov/r/pa/ode/socialmedia/'
+doc = html.fromstring(requests.get(url).text)
+pinlinks = [a for a in doc.cssselect('a') if 'pinterest.com' in str(a.attrib.get('href'))]
+print(""The number of Pinterest accounts maintained by U.S. State Department embassies and missions:"")
+print(len(pinlinks))
+ ",0.0,WE3RESOURCE,,PYTHON,"#https://bit.ly/2lVhlLX
+import requests
+from lxml import html
+url = 'http://www.state.gov/r/pa/ode/socialmedia/'
+doc = html.fromstring(requests.get(url).text)
+pinlinks = [a for a in doc.cssselect('a') if 'pinterest.com' in str(a.attrib.get('href'))]
+print(""The number of Pinterest accounts maintained by U.S. State Department embassies and missions:"")
+print(len(pinlinks))",8,8
+,"import requests
+from lxml import html
+
+url = 'https://www.state.gov/r/pa/ode/socialmedia/'
+doc = html.fromstring(requests.get(url).text)
+pinterest_links = [a for a in doc.cssselect('a') if 'pinterest.com' in str(a.attrib.get('href'))]
+print(f""Number of Pinterest accounts: {len(pinterest_links)}"")
",1.0,PERPLEXITY," Write a Python program to get the number of Pinterest accounts maintained by U.S. State Department embassies and missions.
+Source: https://www.state.gov/r/pa/ode/socialmedia/",PYTHON,"import requests
+from lxml import html
+
+url = 'https://www.state.gov/r/pa/ode/socialmedia/'
+doc = html.fromstring(requests.get(url).text)
+pinterest_links = [a for a in doc.cssselect('a') if 'pinterest.com' in str(a.attrib.get('href'))]
+print(f""Number of Pinterest accounts: {len(pinterest_links)}"")",7,7
+,"from bs4 import BeautifulSoup
+import requests
+handle = input('Input your account name on Twitter: ')
+temp = requests.get('https://twitter.com/'+handle)
+bs = BeautifulSoup(temp.text,'lxml')
+try:
+ follow_box = bs.find('li',{'class':'ProfileNav-item ProfileNav-item--followers'})
+ followers = follow_box.find('a').find('span',{'class':'ProfileNav-value'})
+ print(""Number of followers: {} "".format(followers.get('data-count')))
+except:
+ print('Account name not found...')
+ ",0.0,WERESOURCE,,PYTHON,"from bs4 import BeautifulSoup
+import requests
+handle = input('Input your account name on Twitter: ')
+temp = requests.get('https://twitter.com/'+handle)
+bs = BeautifulSoup(temp.text,'lxml')
+try:
+ follow_box = bs.find('li',{'class':'ProfileNav-item ProfileNav-item--followers'})
+ followers = follow_box.find('a').find('span',{'class':'ProfileNav-value'})
+ print(""Number of followers: {} "".format(followers.get('data-count')))
+except:
+ print('Account name not found...')",11,11
+,"import requests
+from bs4 import BeautifulSoup
+from datetime import datetime
+
+url = 'https://www.us-cert.gov/ncas/alerts'
+response = requests.get(url)
+soup = BeautifulSoup(response.text, 'html.parser')
+
+# Current year
+current_year = datetime.now().year
+alerts = soup.find_all('article', {'data-year': str(current_year)})
+
+print(f""US-CERT security alerts in {current_year}: {len(alerts)}"")
",1.0,PERPLEXITY,"Write a Python program get the number of security alerts issued by US-CERT in the current year.
+Source: https://www.us-cert.gov/ncas/alerts",PYTHON,"import requests
+from bs4 import BeautifulSoup
+from datetime import datetime
+
+url = 'https://www.us-cert.gov/ncas/alerts'
+response = requests.get(url)
+soup = BeautifulSoup(response.text, 'html.parser')
+
+# Current year
+current_year = datetime.now().year
+alerts = soup.find_all('article', {'data-year': str(current_year)})
+
+print(f""US-CERT security alerts in {current_year}: {len(alerts)}"")",13,13
+,"from bs4 import BeautifulSoup
+import requests
+
+handle = input('Input your account name on Twitter: ')
+temp = requests.get('https://twitter.com/'+handle)
+bs = BeautifulSoup(temp.text,'lxml')
+
+try:
+ favorite_box = bs.find('li',{'class':'ProfileNav-item ProfileNav-item--favorites'})
+ favorite = favorite_box.find('a').find('span',{'class':'ProfileNav-value'})
+ print(""Number of post {} liked are {}: "".format(handle,favorite.get('data-count')))
+
+except:
+ print('Account name not found...')
+ ",0.0,WERESOURCE,,PYTHON,"from bs4 import BeautifulSoup
+import requests
+
+handle = input('Input your account name on Twitter: ')
+temp = requests.get('https://twitter.com/'+handle)
+bs = BeautifulSoup(temp.text,'lxml')
+
+try:
+ favorite_box = bs.find('li',{'class':'ProfileNav-item ProfileNav-item--favorites'})
+ favorite = favorite_box.find('a').find('span',{'class':'ProfileNav-value'})
+ print(""Number of post {} liked are {}: "".format(handle,favorite.get('data-count')))
+
+except:
+ print('Account name not found...')",14,14
+,"import requests
+import json
+
+url = 'https://analytics.usa.gov/data/live/realtime.json'
+data = requests.get(url).json()
+active_users = data['totals']['activeUsers']
+print(f""Currently {active_users:,} people visiting U.S. government websites"")
",1.0,PERPLEXITY,"Write a Python program to get the number of people visiting a U.S. government website right now.
+Source: https://analytics.usa.gov/data/live/realtime.json",PYTHON,"import requests
+import json
+
+url = 'https://analytics.usa.gov/data/live/realtime.json'
+data = requests.get(url).json()
+active_users = data['totals']['activeUsers']
+print(f""Currently {active_users:,} people visiting U.S. government websites"")",7,7
+,"from bs4 import BeautifulSoup
+import requests
+
+handle = input('Input your account name on Twitter: ')
+temp = requests.get('https://twitter.com/'+handle)
+bs = BeautifulSoup(temp.text,'lxml')
+
+try:
+ following_box = bs.find('li',{'class':'ProfileNav-item ProfileNav-item--following'})
+ following = following_box.find('a').find('span',{'class':'ProfileNav-value'})
+ print(""{} is following {} people."".format(handle,following.get('data-count')))
+
+except:
+ print('Account name not found...')
+ ",0.0,WERESOURCE,,PYTHON,"from bs4 import BeautifulSoup
+import requests
+
+handle = input('Input your account name on Twitter: ')
+temp = requests.get('https://twitter.com/'+handle)
+bs = BeautifulSoup(temp.text,'lxml')
+
+try:
+ following_box = bs.find('li',{'class':'ProfileNav-item ProfileNav-item--following'})
+ following = following_box.find('a').find('span',{'class':'ProfileNav-value'})
+ print(""{} is following {} people."".format(handle,following.get('data-count')))
+
+except:
+ print('Account name not found...')",14,14
+,"import requests
+from bs4 import BeautifulSoup
+
+url = 'https://www.wikipedia.org/'
+soup = BeautifulSoup(requests.get(url).text, 'html.parser')
+
+langs = soup.find('ul', class_='languages').find_all('li')
+for lang in langs:
+ name = lang.text.strip()
+ count = lang.a['title'].split(' ')[0].replace(',', '')
+ print(f""{name}: {count}"")
",1.0,PERPLEXITY,Write a Python program to list all language names and number of related articles in the order they appear in wikipedia.org.,PYTHON,"import requests
+from bs4 import BeautifulSoup
+
+url = 'https://www.wikipedia.org/'
+soup = BeautifulSoup(requests.get(url).text, 'html.parser')
+
+langs = soup.find('ul', class_='languages').find_all('li')
+for lang in langs:
+ name = lang.text.strip()
+ count = lang.a['title'].split(' ')[0].replace(',', '')
+ print(f""{name}: {count}"")",11,11
+,"from bs4 import BeautifulSoup
+import requests
+
+handle = input('Input your account name on Twitter: ')
+temp = requests.get('https://twitter.com/'+handle)
+bs = BeautifulSoup(temp.text,'lxml')
+
+try:
+ tweet_box = bs.find('li',{'class':'ProfileNav-item ProfileNav-item--tweets is-active'})
+ tweets= tweet_box.find('a').find('span',{'class':'ProfileNav-value'})
+ print(""{} tweets {} number of tweets."".format(handle,tweets.get('data-count')))
+
+except:
+ print('Account name not found...')
+ ",0.0,WERESOURCE,,PYTHON,"from bs4 import BeautifulSoup
+import requests
+
+handle = input('Input your account name on Twitter: ')
+temp = requests.get('https://twitter.com/'+handle)
+bs = BeautifulSoup(temp.text,'lxml')
+
+try:
+ tweet_box = bs.find('li',{'class':'ProfileNav-item ProfileNav-item--tweets is-active'})
+ tweets= tweet_box.find('a').find('span',{'class':'ProfileNav-value'})
+ print(""{} tweets {} number of tweets."".format(handle,tweets.get('data-count')))
+
+except:
+ print('Account name not found...')",14,14
+,"import json
+import io
+
+def convert_json_to_object(data_source):
+ """"""
+ Converts JSON data from various forms (string, file, or stream)
+ into a Python object.
+ """"""
+ try:
+ # Case 1: If data_source is already a file-like object/stream
+ if hasattr(data_source, 'read'):
+ return json.load(data_source)
+
+ # Case 2: If data_source is a string
+ if isinstance(data_source, str):
+ # Check if it's a file path by looking for a .json extension
+ if data_source.strip().endswith('.json'):
+ with open(data_source, 'r', encoding='utf-8') as f:
+ return json.load(f)
+ # Otherwise, treat it as a raw JSON string
+ return json.loads(data_source)
+
+ # Case 3: If data_source is bytes
+ if isinstance(data_source, bytes):
+ return json.loads(data_source.decode('utf-8'))
+
+ raise ValueError(""Unsupported data format."")
+
+ except json.JSONDecodeError as e:
+ return f""Invalid JSON: {e}""
+ except FileNotFoundError:
+ return ""Error: The specified file was not found.""
+
+# --- Examples of Usage ---
+
+# 1. From a JSON String
+json_string = '{""name"": ""Alice"", ""role"": ""Engineer"", ""active"": true}'
+obj_from_str = convert_json_to_object(json_string)
+
+# 2. From a File-like object (Stream)
+stream = io.StringIO('[1, 2, 3, {""key"": ""value""}]')
+obj_from_stream = convert_json_to_object(stream)
+
+print(f""String conversion: {obj_from_str['name']}"")
+print(f""Stream conversion: {obj_from_stream[3]['key']}"")",1.0,GEMINI,Write a Python program to convert JSON data to Python object.Make the code effiecient to accept the json in various countforms,PYTHON,"import json
+import io
+
+def convert_json_to_object(data_source):
+ """"""
+ Converts JSON data from various forms (string, file, or stream)
+ into a Python object.
+ """"""
+ try:
+ # Case 1: If data_source is already a file-like object/stream
+ if hasattr(data_source, 'read'):
+ return json.load(data_source)
+
+ # Case 2: If data_source is a string
+ if isinstance(data_source, str):
+ # Check if it's a file path by looking for a .json extension
+ if data_source.strip().endswith('.json'):
+ with open(data_source, 'r', encoding='utf-8') as f:
+ return json.load(f)
+ # Otherwise, treat it as a raw JSON string
+ return json.loads(data_source)
+
+ # Case 3: If data_source is bytes
+ if isinstance(data_source, bytes):
+ return json.loads(data_source.decode('utf-8'))
+
+ raise ValueError(""Unsupported data format."")
+
+ except json.JSONDecodeError as e:
+ return f""Invalid JSON: {e}""
+ except FileNotFoundError:
+ return ""Error: The specified file was not found.""
+
+# --- Examples of Usage ---
+
+# 1. From a JSON String
+json_string = '{""name"": ""Alice"", ""role"": ""Engineer"", ""active"": true}'
+obj_from_str = convert_json_to_object(json_string)
+
+# 2. From a File-like object (Stream)
+stream = io.StringIO('[1, 2, 3, {""key"": ""value""}]')
+obj_from_stream = convert_json_to_object(stream)
+
+print(f""String conversion: {obj_from_str['name']}"")
+print(f""Stream conversion: {obj_from_stream[3]['key']}"")",45,45
+,"from bs4 import BeautifulSoup
+import requests
+handle = input('Input your account name on Twitter: ')
+ctr = int(input('Input number of tweets to scrape: '))
+res=requests.get('https://twitter.com/'+ handle)
+bs=BeautifulSoup(res.content,'lxml')
+all_tweets = bs.find_all('div',{'class':'tweet'})
+if all_tweets:
+ for tweet in all_tweets[:ctr]:
+ context = tweet.find('div',{'class':'context'}).text.replace(""\n"","" "").strip()
+ content = tweet.find('div',{'class':'content'})
+ header = content.find('div',{'class':'stream-item-header'})
+ user = header.find('a',{'class':'account-group js-account-group js-action-profile js-user-profile-link js-nav'}).text.replace(""\n"","" "").strip()
+ time = header.find('a',{'class':'tweet-timestamp js-permalink js-nav js-tooltip'}).find('span').text.replace(""\n"","" "").strip()
+ message = content.find('div',{'class':'js-tweet-text-container'}).text.replace(""\n"","" "").strip()
+ footer = content.find('div',{'class':'stream-item-footer'})
+ stat = footer.find('div',{'class':'ProfileTweet-actionCountList u-hiddenVisually'}).text.replace(""\n"","" "").strip()
+ if context:
+ print(context)
+ print(user,time)
+ print(message)
+ print(stat)
+ print()
+else:
+ print(""List is empty/account name not found."")
+ ",0.0,WERESOURCE,,PYTHON,"from bs4 import BeautifulSoup
+import requests
+handle = input('Input your account name on Twitter: ')
+ctr = int(input('Input number of tweets to scrape: '))
+res=requests.get('https://twitter.com/'+ handle)
+bs=BeautifulSoup(res.content,'lxml')
+all_tweets = bs.find_all('div',{'class':'tweet'})
+if all_tweets:
+ for tweet in all_tweets[:ctr]:
+ context = tweet.find('div',{'class':'context'}).text.replace(""\n"","" "").strip()
+ content = tweet.find('div',{'class':'content'})
+ header = content.find('div',{'class':'stream-item-header'})
+ user = header.find('a',{'class':'account-group js-account-group js-action-profile js-user-profile-link js-nav'}).text.replace(""\n"","" "").strip()
+ time = header.find('a',{'class':'tweet-timestamp js-permalink js-nav js-tooltip'}).find('span').text.replace(""\n"","" "").strip()
+ message = content.find('div',{'class':'js-tweet-text-container'}).text.replace(""\n"","" "").strip()
+ footer = content.find('div',{'class':'stream-item-footer'})
+ stat = footer.find('div',{'class':'ProfileTweet-actionCountList u-hiddenVisually'}).text.replace(""\n"","" "").strip()
+ if context:
+ print(context)
+ print(user,time)
+ print(message)
+ print(stat)
+ print()
+else:
+ print(""List is empty/account name not found."")",25,25
+,"import json
+
+def convert_to_json(data, indent=4):
+ """"""
+ Converts a Python object to a JSON string.
+ Includes a fallback for custom objects that aren't natively serializable.
+ """"""
+ try:
+ # indent=4 makes the output 'pretty' and readable
+ # sort_keys=True organizes the dictionary keys alphabetically
+ return json.dumps(data, indent=indent, sort_keys=True, default=str)
+ except Exception as e:
+ return f""Error converting to JSON: {e}""
+
+# --- Examples of Usage ---
+
+# 1. Converting a standard Dictionary
+user_profile = {
+ ""username"": ""coder_123"",
+ ""id"": 882,
+ ""tags"": [""python"", ""api"", ""json""],
+ ""is_premium"": False,
+ ""location"": None
+}
+
+json_output = convert_to_json(user_profile)
+print(""--- Standard Dictionary to JSON ---"")
+print(json_output)
+
+# 2. Converting to a JSON File
+with open(""data.json"", ""w"", encoding=""utf-8"") as f:
+ json.dump(user_profile, f, indent=4)
+ print(""\n[System] Data successfully written to data.json"")",1.0,GEMINI,Write a Python program to convert Python object to JSON data.,PYTHON,"import json
+
+def convert_to_json(data, indent=4):
+ """"""
+ Converts a Python object to a JSON string.
+ Includes a fallback for custom objects that aren't natively serializable.
+ """"""
+ try:
+ # indent=4 makes the output 'pretty' and readable
+ # sort_keys=True organizes the dictionary keys alphabetically
+ return json.dumps(data, indent=indent, sort_keys=True, default=str)
+ except Exception as e:
+ return f""Error converting to JSON: {e}""
+
+# --- Examples of Usage ---
+
+# 1. Converting a standard Dictionary
+user_profile = {
+ ""username"": ""coder_123"",
+ ""id"": 882,
+ ""tags"": [""python"", ""api"", ""json""],
+ ""is_premium"": False,
+ ""location"": None
+}
+
+json_output = convert_to_json(user_profile)
+print(""--- Standard Dictionary to JSON ---"")
+print(json_output)
+
+# 2. Converting to a JSON File
+with open(""data.json"", ""w"", encoding=""utf-8"") as f:
+ json.dump(user_profile, f, indent=4)
+ print(""\n[System] Data successfully written to data.json"")",33,33
+,"import requests
+from pprint import pprint
+def weather_data(query):
+ res=requests.get('http://api.openweathermap.org/data/2.5/weather?'+query+'&APPID=****************************8&units=metric');
+ return res.json();
+def print_weather(result,city):
+ print(""{}'s temperature: {}°C "".format(city,result['main']['temp']))
+ print(""Wind speed: {} m/s"".format(result['wind']['speed']))
+ print(""Description: {}"".format(result['weather'][0]['description']))
+ print(""Weather: {}"".format(result['weather'][0]['main']))
+def main():
+ city=input('Enter the city:')
+ print()
+ try:
+ query='q='+city;
+ w_data=weather_data(query);
+ print_weather(w_data, city)
+ print()
+ except:
+ print('City name not found...')
+if __name__=='__main__':
+ main()
+ ",0.0,WERESOURCE,,PYTHON,"import requests
+from pprint import pprint
+def weather_data(query):
+ res=requests.get('http://api.openweathermap.org/data/2.5/weather?'+query+'&APPID=****************************8&units=metric');
+ return res.json();
+def print_weather(result,city):
+ print(""{}'s temperature: {}°C "".format(city,result['main']['temp']))
+ print(""Wind speed: {} m/s"".format(result['wind']['speed']))
+ print(""Description: {}"".format(result['weather'][0]['description']))
+ print(""Weather: {}"".format(result['weather'][0]['main']))
+def main():
+ city=input('Enter the city:')
+ print()
+ try:
+ query='q='+city;
+ w_data=weather_data(query);
+ print_weather(w_data, city)
+ print()
+ except:
+ print('City name not found...')
+if __name__=='__main__':
+ main()",22,22
+,"import json
+
+def python_to_json_display(data):
+ # Convert Python object to a JSON formatted string
+ # indent=4 adds whitespace for readability
+ # sort_keys=True keeps the output consistent
+ json_string = json.dumps(data, indent=4, sort_keys=True)
+
+ print(""--- Generated JSON String ---"")
+ print(json_string)
+
+ # To ""print all values"" specifically from the resulting JSON
+ # we first load it back to iterate through it
+ print(""\n--- Individual Values Extracted ---"")
+ parsed_data = json.loads(json_string)
+
+ if isinstance(parsed_data, dict):
+ for key, value in parsed_data.items():
+ print(f""Key: {key:12} | Value: {value} ({type(value).__name__})"")
+
+# Example Python Object (Dictionary)
+employee_data = {
+ ""name"": ""Marcus Aurelius"",
+ ""department"": ""Philosophy"",
+ ""years_active"": 19,
+ ""is_remote"": True,
+ ""skills"": [""Leadership"", ""Writing"", ""Logic""],
+ ""office_id"": None
+}
+
+if __name__ == ""__main__"":
+ python_to_json_display(employee_data)",1.0,GEMINI,Write a Python program to convert Python objects into JSON strings. Print all the values.,PYTHON,"import json
+
+def python_to_json_display(data):
+ # Convert Python object to a JSON formatted string
+ # indent=4 adds whitespace for readability
+ # sort_keys=True keeps the output consistent
+ json_string = json.dumps(data, indent=4, sort_keys=True)
+
+ print(""--- Generated JSON String ---"")
+ print(json_string)
+
+ # To ""print all values"" specifically from the resulting JSON
+ # we first load it back to iterate through it
+ print(""\n--- Individual Values Extracted ---"")
+ parsed_data = json.loads(json_string)
+
+ if isinstance(parsed_data, dict):
+ for key, value in parsed_data.items():
+ print(f""Key: {key:12} | Value: {value} ({type(value).__name__})"")
+
+# Example Python Object (Dictionary)
+employee_data = {
+ ""name"": ""Marcus Aurelius"",
+ ""department"": ""Philosophy"",
+ ""years_active"": 19,
+ ""is_remote"": True,
+ ""skills"": [""Leadership"", ""Writing"", ""Logic""],
+ ""office_id"": None
+}
+
+if __name__ == ""__main__"":
+ python_to_json_display(employee_data)",32,32
+,"import requests
+from bs4 import BeautifulSoup
+res = requests.get('https://hackevents.co/hackathons')
+bs = BeautifulSoup(res.text, 'lxml')
+hacks_data = bs.find_all('div',{'class':'hackathon '})
+for i,f in enumerate(hacks_data,1):
+ hacks_month = f.find('div',{'class':'date'}).find('div',{'class':'date-month'}).text.strip()
+ hacks_date = f.find('div',{'class':'date'}).find('div',{'class':'date-day-number'}).text.strip()
+ hacks_days = f.find('div',{'class':'date'}).find('div',{'class':'date-week-days'}).text.strip()
+ hacks_final_date = ""{} {}, {} "".format(hacks_date, hacks_month, hacks_days )
+ hacks_name = f.find('div',{'class':'info'}).find('h2').text.strip()
+ hacks_city = f.find('div',{'class':'info'}).find('p').find('span',{'class':'city'}).text.strip()
+ hacks_country = f.find('div',{'class':'info'}).find('p').find('span',{'class':'country'}).text.strip()
+ print(""{:<5}{:<15}: {:<90}: {}, {}\n "".format(str(i)+')',hacks_final_date, hacks_name.title(), hacks_city, hacks_country))
+ ",0.0,WERESOURCE,,PYTHON,"import requests
+from bs4 import BeautifulSoup
+res = requests.get('https://hackevents.co/hackathons')
+bs = BeautifulSoup(res.text, 'lxml')
+hacks_data = bs.find_all('div',{'class':'hackathon '})
+for i,f in enumerate(hacks_data,1):
+ hacks_month = f.find('div',{'class':'date'}).find('div',{'class':'date-month'}).text.strip()
+ hacks_date = f.find('div',{'class':'date'}).find('div',{'class':'date-day-number'}).text.strip()
+ hacks_days = f.find('div',{'class':'date'}).find('div',{'class':'date-week-days'}).text.strip()
+ hacks_final_date = ""{} {}, {} "".format(hacks_date, hacks_month, hacks_days )
+ hacks_name = f.find('div',{'class':'info'}).find('h2').text.strip()
+ hacks_city = f.find('div',{'class':'info'}).find('p').find('span',{'class':'city'}).text.strip()
+ hacks_country = f.find('div',{'class':'info'}).find('p').find('span',{'class':'country'}).text.strip()
+ print(""{:<5}{:<15}: {:<90}: {}, {}\n "".format(str(i)+')',hacks_final_date, hacks_name.title(), hacks_city, hacks_country))",14,14
+,"import json
+
+def convert_dict_to_sorted_json(data_dict):
+ """"""
+ Converts a dictionary to a JSON string sorted by keys
+ with an indent of 4 spaces.
+ """"""
+ try:
+ # sort_keys=True: Alphabetizes the keys
+ # indent=4: Adds 4 spaces for nested members
+ json_output = json.dumps(data_dict, sort_keys=True, indent=4)
+
+ print(""Successfully converted to Sorted JSON:"")
+ print(json_output)
+
+ return json_output
+ except (TypeError, ValueError) as e:
+ print(f""Error converting object: {e}"")
+ return None
+
+# Example dictionary with unsorted keys
+blog_post = {
+ ""title"": ""Python JSON Guide"",
+ ""author"": ""Jane Doe"",
+ ""views"": 1500,
+ ""tags"": [""python"", ""json"", ""tutorial""],
+ ""published"": True,
+ ""category"": ""Programming""
+}
+
+# Execute conversion
+convert_dict_to_sorted_json(blog_post)",1.0,GEMINI,Write a Python program to convert Python dictionary object (sort by key) to JSON data. Print the object members with indent level 4.,PYTHON,"import json
+
+def convert_dict_to_sorted_json(data_dict):
+ """"""
+ Converts a dictionary to a JSON string sorted by keys
+ with an indent of 4 spaces.
+ """"""
+ try:
+ # sort_keys=True: Alphabetizes the keys
+ # indent=4: Adds 4 spaces for nested members
+ json_output = json.dumps(data_dict, sort_keys=True, indent=4)
+
+ print(""Successfully converted to Sorted JSON:"")
+ print(json_output)
+
+ return json_output
+ except (TypeError, ValueError) as e:
+ print(f""Error converting object: {e}"")
+ return None
+
+# Example dictionary with unsorted keys
+blog_post = {
+ ""title"": ""Python JSON Guide"",
+ ""author"": ""Jane Doe"",
+ ""views"": 1500,
+ ""tags"": [""python"", ""json"", ""tutorial""],
+ ""published"": True,
+ ""category"": ""Programming""
+}
+
+# Execute conversion
+convert_dict_to_sorted_json(blog_post)",32,32
+,"#https://bit.ly/2NyxdAG
+from bs4 import BeautifulSoup
+import requests
+import re
+
+# Download IMDB's Top 250 data
+url = 'http://www.imdb.com/chart/top'
+response = requests.get(url)
+soup = BeautifulSoup(response.text, 'lxml')
+
+movies = soup.select('td.titleColumn')
+links = [a.attrs.get('href') for a in soup.select('td.titleColumn a')]
+crew = [a.attrs.get('title') for a in soup.select('td.titleColumn a')]
+ratings = [b.attrs.get('data-value') for b in soup.select('td.posterColumn span[name=ir]')]
+votes = [b.attrs.get('data-value') for b in soup.select('td.ratingColumn strong')]
+
+imdb = []
+
+# Store each item into dictionary (data), then put those into a list (imdb)
+for index in range(0, len(movies)):
+ # Seperate movie into: 'place', 'title', 'year'
+ movie_string = movies[index].get_text()
+ movie = (' '.join(movie_string.split()).replace('.', ''))
+ movie_title = movie[len(str(index))+1:-7]
+ year = re.search('\((.*?)\)', movie_string).group(1)
+ place = movie[:len(str(index))-(len(movie))]
+ data = {""movie_title"": movie_title,
+ ""year"": year,
+ ""place"": place,
+ ""star_cast"": crew[index],
+ ""rating"": ratings[index],
+ ""vote"": votes[index],
+ ""link"": links[index]}
+ imdb.append(data)
+
+for item in imdb:
+ print(item['place'], '-', item['movie_title'], '('+item['year']+') -', 'Starring:', item['star_cast'])
+ ",0.0,WERESOURCE,,PYTHON,"#https://bit.ly/2NyxdAG
+from bs4 import BeautifulSoup
+import requests
+import re
+
+# Download IMDB's Top 250 data
+url = 'http://www.imdb.com/chart/top'
+response = requests.get(url)
+soup = BeautifulSoup(response.text, 'lxml')
+
+movies = soup.select('td.titleColumn')
+links = [a.attrs.get('href') for a in soup.select('td.titleColumn a')]
+crew = [a.attrs.get('title') for a in soup.select('td.titleColumn a')]
+ratings = [b.attrs.get('data-value') for b in soup.select('td.posterColumn span[name=ir]')]
+votes = [b.attrs.get('data-value') for b in soup.select('td.ratingColumn strong')]
+
+imdb = []
+
+# Store each item into dictionary (data), then put those into a list (imdb)
+for index in range(0, len(movies)):
+ # Seperate movie into: 'place', 'title', 'year'
+ movie_string = movies[index].get_text()
+ movie = (' '.join(movie_string.split()).replace('.', ''))
+ movie_title = movie[len(str(index))+1:-7]
+ year = re.search('\((.*?)\)', movie_string).group(1)
+ place = movie[:len(str(index))-(len(movie))]
+ data = {""movie_title"": movie_title,
+ ""year"": year,
+ ""place"": place,
+ ""star_cast"": crew[index],
+ ""rating"": ratings[index],
+ ""vote"": votes[index],
+ ""link"": links[index]}
+ imdb.append(data)
+
+for item in imdb:
+ print(item['place'], '-', item['movie_title'], '('+item['year']+') -', 'Starring:', item['star_cast'])",37,37
+,"import json
+
+# JSON encoded data (often received from an API or web request)
+json_data = '''
+{
+ ""company"": ""TechFlow"",
+ ""location"": ""San Francisco"",
+ ""employees"": 150,
+ ""is_hiring"": true,
+ ""tech_stack"": [""Python"", ""React"", ""PostgreSQL""],
+ ""revenue"": null
+}
+'''
+
+def decode_json(json_string):
+ try:
+ # Convert JSON string to Python object (Dictionary)
+ python_obj = json.loads(json_string)
+
+ print(""Successfully converted JSON to Python Object:"")
+ print(f""Type: {type(python_obj)}"")
+ print(""-"" * 30)
+
+ # Accessing the data using Python keys
+ print(f""Company Name: {python_obj['company']}"")
+ print(f""Main Language: {python_obj['tech_stack'][0]}"")
+ print(f""Hiring Status: {python_obj['is_hiring']}"")
+
+ return python_obj
+
+ except json.JSONDecodeError as e:
+ print(f""Failed to decode JSON: {e}"")
+
+# Execute the conversion
+decoded_data = decode_json(json_data)",1.0,GEMINI,Write a Python program to convert JSON encoded data into Python objects.,PYTHON,"import json
+
+# JSON encoded data (often received from an API or web request)
+json_data = '''
+{
+ ""company"": ""TechFlow"",
+ ""location"": ""San Francisco"",
+ ""employees"": 150,
+ ""is_hiring"": true,
+ ""tech_stack"": [""Python"", ""React"", ""PostgreSQL""],
+ ""revenue"": null
+}
+'''
+
+def decode_json(json_string):
+ try:
+ # Convert JSON string to Python object (Dictionary)
+ python_obj = json.loads(json_string)
+
+ print(""Successfully converted JSON to Python Object:"")
+ print(f""Type: {type(python_obj)}"")
+ print(""-"" * 30)
+
+ # Accessing the data using Python keys
+ print(f""Company Name: {python_obj['company']}"")
+ print(f""Main Language: {python_obj['tech_stack'][0]}"")
+ print(f""Hiring Status: {python_obj['is_hiring']}"")
+
+ return python_obj
+
+ except json.JSONDecodeError as e:
+ print(f""Failed to decode JSON: {e}"")
+
+# Execute the conversion
+decoded_data = decode_json(json_data)",35,35
+,"from bs4 import BeautifulSoup
+import requests
+import random
+def get_imd_movies(url):
+ page = requests.get(url)
+ soup = BeautifulSoup(page.text, 'html.parser')
+ movies = soup.find_all(""td"", class_=""titleColumn"")
+ random.shuffle(movies)
+ return movies
+def get_imd_summary(url):
+ movie_page = requests.get(url)
+ soup = BeautifulSoup(movie_page.text, 'html.parser')
+ return soup.find(""div"", class_=""summary_text"").contents[0].strip()
+
+def get_imd_movie_info(movie):
+ movie_title = movie.a.contents[0]
+ movie_year = movie.span.contents[0]
+ movie_url = 'http://www.imdb.com' + movie.a['href']
+ return movie_title, movie_year, movie_url
+
+def imd_movie_picker():
+ ctr=0
+ print(""--------------------------------------------"")
+ for movie in get_imd_movies('http://www.imdb.com/chart/top'):
+ movie_title, movie_year, movie_url = get_imd_movie_info(movie)
+ movie_summary = get_imd_summary(movie_url)
+ print(movie_title, movie_year)
+ print(movie_summary)
+ print(""--------------------------------------------"")
+ ctr=ctr+1
+ if (ctr==10):
+ break;
+if __name__ == '__main__':
+ imd_movie_picker()
+ ",0.0,WERESOURCE,,PYTHON,"from bs4 import BeautifulSoup
+import requests
+import random
+def get_imd_movies(url):
+ page = requests.get(url)
+ soup = BeautifulSoup(page.text, 'html.parser')
+ movies = soup.find_all(""td"", class_=""titleColumn"")
+ random.shuffle(movies)
+ return movies
+def get_imd_summary(url):
+ movie_page = requests.get(url)
+ soup = BeautifulSoup(movie_page.text, 'html.parser')
+ return soup.find(""div"", class_=""summary_text"").contents[0].strip()
+
+def get_imd_movie_info(movie):
+ movie_title = movie.a.contents[0]
+ movie_year = movie.span.contents[0]
+ movie_url = 'http://www.imdb.com' + movie.a['href']
+ return movie_title, movie_year, movie_url
+
+def imd_movie_picker():
+ ctr=0
+ print(""--------------------------------------------"")
+ for movie in get_imd_movies('http://www.imdb.com/chart/top'):
+ movie_title, movie_year, movie_url = get_imd_movie_info(movie)
+ movie_summary = get_imd_summary(movie_url)
+ print(movie_title, movie_year)
+ print(movie_summary)
+ print(""--------------------------------------------"")
+ ctr=ctr+1
+ if (ctr==10):
+ break;
+if __name__ == '__main__':
+ imd_movie_picker()",34,34
+,"import json
+from datetime import datetime
+
+def replicate_json_file(source_filename, destination_filename):
+ try:
+ # 1. Open and read the existing JSON file
+ with open(source_filename, 'r', encoding='utf-8') as source_file:
+ data = json.load(source_file)
+
+ # 2. (Optional) Modify the data
+ # For example, let's add metadata about when this copy was created
+ if isinstance(data, dict):
+ data['processed_at'] = datetime.now().strftime(""%Y-%m-%d %H:%M:%S"")
+ data['status'] = ""replicated""
+
+ # 3. Write the data to a new JSON file
+ with open(destination_filename, 'w', encoding='utf-8') as dest_file:
+ # indent=4 makes the new file human-readable
+ json.dump(data, dest_file, indent=4, sort_keys=True)
+
+ print(f""Successfully created '{destination_filename}' from '{source_filename}'."")
+
+ except FileNotFoundError:
+ print(""Error: The source file does not exist."")
+ except json.JSONDecodeError:
+ print(""Error: Failed to decode JSON. Check if the source file is valid."")
+ except Exception as e:
+ print(f""An unexpected error occurred: {e}"")
+
+# --- Usage ---
+# Ensure you have a file named 'source.json' in your directory before running
+replicate_json_file('source.json', 'new_backup.json')",1.0,GEMINI,Write a Python program to create a new JSON file from an existing JSON file.,PYTHON,"import json
+from datetime import datetime
+
+def replicate_json_file(source_filename, destination_filename):
+ try:
+ # 1. Open and read the existing JSON file
+ with open(source_filename, 'r', encoding='utf-8') as source_file:
+ data = json.load(source_file)
+
+ # 2. (Optional) Modify the data
+ # For example, let's add metadata about when this copy was created
+ if isinstance(data, dict):
+ data['processed_at'] = datetime.now().strftime(""%Y-%m-%d %H:%M:%S"")
+ data['status'] = ""replicated""
+
+ # 3. Write the data to a new JSON file
+ with open(destination_filename, 'w', encoding='utf-8') as dest_file:
+ # indent=4 makes the new file human-readable
+ json.dump(data, dest_file, indent=4, sort_keys=True)
+
+ print(f""Successfully created '{destination_filename}' from '{source_filename}'."")
+
+ except FileNotFoundError:
+ print(""Error: The source file does not exist."")
+ except json.JSONDecodeError:
+ print(""Error: Failed to decode JSON. Check if the source file is valid."")
+ except Exception as e:
+ print(f""An unexpected error occurred: {e}"")
+
+# --- Usage ---
+# Ensure you have a file named 'source.json' in your directory before running
+replicate_json_file('source.json', 'new_backup.json')",32,32
+,"#https://bit.ly/2lVhlLX
+# landing page:
+# http://earthquake.usgs.gov/earthquakes/feed/v1.0/csv.php
+import csv
+import requests
+csvurl = 'http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_month.csv'
+rows = list(csv.DictReader(requests.get(csvurl).text.splitlines()))
+print(""The number of magnitude 4.5+ earthquakes detected worldwide by the USGS:"", len(rows))
+ ",0.0,WERESOURCE,,PYTHON,"#https://bit.ly/2lVhlLX
+# landing page:
+# http://earthquake.usgs.gov/earthquakes/feed/v1.0/csv.php
+import csv
+import requests
+csvurl = 'http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_month.csv'
+rows = list(csv.DictReader(requests.get(csvurl).text.splitlines()))
+print(""The number of magnitude 4.5+ earthquakes detected worldwide by the USGS:"", len(rows))",8,8
+,"def check_if_complex(data):
+ """"""
+ Checks if the provided data instance is of the complex type.
+ """"""
+ if isinstance(data, complex):
+ print(f""✓ {data} is a complex number."")
+ print(f"" - Real part: {data.real}"")
+ print(f"" - Imaginary part: {data.imag}"")
+ else:
+ print(f""✗ {data} (type: {type(data).__name__}) is NOT a complex number."")
+
+# --- Testing various instances ---
+
+# A standard complex number
+val1 = 5 + 3j
+
+# A complex number created via constructor
+val2 = complex(10, -2)
+
+# A standard integer
+val3 = 100
+
+# A float
+val4 = 7.5
+
+print(""Starting Instance Check:\n"" + ""-""*25)
+check_if_complex(val1)
+check_if_complex(val2)
+check_if_complex(val3)
+check_if_complex(val4)",1.0,GEMINI,Write a Python program to check whether an instance is complex or not.,PYTHON,"def check_if_complex(data):
+ """"""
+ Checks if the provided data instance is of the complex type.
+ """"""
+ if isinstance(data, complex):
+ print(f""✓ {data} is a complex number."")
+ print(f"" - Real part: {data.real}"")
+ print(f"" - Imaginary part: {data.imag}"")
+ else:
+ print(f""✗ {data} (type: {type(data).__name__}) is NOT a complex number."")
+
+# --- Testing various instances ---
+
+# A standard complex number
+val1 = 5 + 3j
+
+# A complex number created via constructor
+val2 = complex(10, -2)
+
+# A standard integer
+val3 = 100
+
+# A float
+val4 = 7.5
+
+print(""Starting Instance Check:\n"" + ""-""*25)
+check_if_complex(val1)
+check_if_complex(val2)
+check_if_complex(val3)
+check_if_complex(val4)",30,30
+,"import requests
+response = requests.get('https://python.org')
+print(""Status Code: "",response.status_code)
+print(""Headers: "",response.headers)
+print(""Url: "",response.url)
+print(""History: "",response.history)
+print(""Encoding: "",response.encoding)
+print(""Reason: "",response.reason)
+print(""Cookies: "",response.cookies)
+print(""Elapsed: "",response.elapsed)
+print(""Request: "",response.request)
+print(""Content: "",response._content)
+ ",0.0,WERESOURCE,,PYTHON,"import requests
+response = requests.get('https://python.org')
+print(""Status Code: "",response.status_code)
+print(""Headers: "",response.headers)
+print(""Url: "",response.url)
+print(""History: "",response.history)
+print(""Encoding: "",response.encoding)
+print(""Reason: "",response.reason)
+print(""Cookies: "",response.cookies)
+print(""Elapsed: "",response.elapsed)
+print(""Request: "",response.request)
+print(""Content: "",response._content)",12,12
+,"import json
+
+def has_complex_structure(data):
+ """"""
+ Recursively checks if a Python object contains nested
+ collections (dict or list).
+ """"""
+ # If the root is a list, check its elements
+ if isinstance(data, list):
+ for item in data:
+ if isinstance(item, (dict, list)):
+ return True
+ return False
+
+ # If the root is a dict, check if any value is a dict or list
+ if isinstance(data, dict):
+ for value in data.values():
+ if isinstance(value, (dict, list)):
+ return True
+
+ return False
+
+def check_json_complexity(json_str):
+ try:
+ parsed = json.loads(json_str)
+ if has_complex_structure(parsed):
+ print(""Complexity Found: This JSON contains nested objects/arrays."")
+ else:
+ print(""Simple JSON: This is a flat key-value structure."")
+ except json.JSONDecodeError:
+ print(""Invalid JSON string."")
+
+# --- Test Cases ---
+
+simple_json = '{""name"": ""Alice"", ""age"": 30}'
+complex_json = '{""user"": {""id"": 1, ""name"": ""Alice""}, ""tags"": [""admin"", ""dev""]}'
+
+print(""Checking simple_json:"")
+check_json_complexity(simple_json)
+
+print(""\nChecking complex_json:"")
+check_json_complexity(complex_json)",1.0,GEMINI,Write a Python program to check whether a JSON string contains complex object or not,PYTHON,"import json
+
+def has_complex_structure(data):
+ """"""
+ Recursively checks if a Python object contains nested
+ collections (dict or list).
+ """"""
+ # If the root is a list, check its elements
+ if isinstance(data, list):
+ for item in data:
+ if isinstance(item, (dict, list)):
+ return True
+ return False
+
+ # If the root is a dict, check if any value is a dict or list
+ if isinstance(data, dict):
+ for value in data.values():
+ if isinstance(value, (dict, list)):
+ return True
+
+ return False
+
+def check_json_complexity(json_str):
+ try:
+ parsed = json.loads(json_str)
+ if has_complex_structure(parsed):
+ print(""Complexity Found: This JSON contains nested objects/arrays."")
+ else:
+ print(""Simple JSON: This is a flat key-value structure."")
+ except json.JSONDecodeError:
+ print(""Invalid JSON string."")
+
+# --- Test Cases ---
+
+simple_json = '{""name"": ""Alice"", ""age"": 30}'
+complex_json = '{""user"": {""id"": 1, ""name"": ""Alice""}, ""tags"": [""admin"", ""dev""]}'
+
+print(""Checking simple_json:"")
+check_json_complexity(simple_json)
+
+print(""\nChecking complex_json:"")
+check_json_complexity(complex_json)",42,42
+,"def get_unique_values(data_obj):
+ # We use set() because sets automatically remove duplicates
+ unique_values = set(data_obj.values())
+ return list(unique_values)
+
+# Example: Several keys share the same value
+employee_roles = {
+ ""Alice"": ""Engineer"",
+ ""Bob"": ""Manager"",
+ ""Charlie"": ""Engineer"",
+ ""David"": ""Intern"",
+ ""Eve"": ""Manager""
+}
+
+print(f""Unique Roles: {get_unique_values(employee_roles)}"")",1.0,GEMINI,Write a Python program to access only unique key value of a Python object.,PYTHON,"def get_unique_values(data_obj):
+ # We use set() because sets automatically remove duplicates
+ unique_values = set(data_obj.values())
+ return list(unique_values)
+
+# Example: Several keys share the same value
+employee_roles = {
+ ""Alice"": ""Engineer"",
+ ""Bob"": ""Manager"",
+ ""Charlie"": ""Engineer"",
+ ""David"": ""Intern"",
+ ""Eve"": ""Manager""
+}
+
+print(f""Unique Roles: {get_unique_values(employee_roles)}"")",15,15
+,"public class OddEvenArray
+{
+public static void main(String args[])
+{
+int s, i;
+int[] a = { 33, 2, 4, 71, 88, 92, 9, 1 };
+for (i = 0; i < a.length; i++)
+{
+for (int j = i + 1; j < a.length; j++)
+{
+if (a[i] > a[j])
+{
+s = a[i];
+a[i] = a[j];
+a[j] = s;
+}
+
+}
+}
+System.out.print(""Input numbers :"");
+for (i = 0; i < a.length; i++)
+{
+System.out.print("" "" + a[i]);
+}
+System.out.print(""\nOdd numbers :"");
+for (i = 0; i <= a.length - 1; i++)
+{
+if (a[i] % 2 != 0)
+{
+System.out.print("" "" + a[i]);
+}
+}
+System.out.print(""\nEven numbers :"");
+for (i = 0; i < a.length; i++)
+{
+if (a[i] % 2 == 0)
+{
+System.out.print("" "" + a[i]);
+}
+}
+}
+}
",0.0,IPSGWALIOR.ORG,,JAVA,"public class OddEvenArray
+{
+public static void main(String args[])
+{
+int s, i;
+int[] a = { 33, 2, 4, 71, 88, 92, 9, 1 };
+for (i = 0; i < a.length; i++)
+{
+for (int j = i + 1; j < a.length; j++)
+{
+if (a[i] > a[j])
+{
+s = a[i];
+a[i] = a[j];
+a[j] = s;
+}
+
+}
+}
+System.out.print(""Input numbers :"");
+for (i = 0; i < a.length; i++)
+{
+System.out.print("" "" + a[i]);
+}
+System.out.print(""\nOdd numbers :"");
+for (i = 0; i <= a.length - 1; i++)
+{
+if (a[i] % 2 != 0)
+{
+System.out.print("" "" + a[i]);
+}
+}
+System.out.print(""\nEven numbers :"");
+for (i = 0; i < a.length; i++)
+{
+if (a[i] % 2 == 0)
+{
+System.out.print("" "" + a[i]);
+}
+}
+}
+}",42,42
+,"public List> groupAnagrams(String[] strs) {
+ Map> map = new HashMap<>();
+ for (String s : strs) {
+ char[] ca = s.toCharArray();
+ Arrays.sort(ca);
+ String key = String.valueOf(ca);
+ map.computeIfAbsent(key, k -> new ArrayList<>()).add(s);
+ }
+ return new ArrayList<>(map.values());
+}",1.0,GEMINI,"Given an array of strings, group anagrams together.",JAVA,"public List> groupAnagrams(String[] strs) {
+ Map> map = new HashMap<>();
+ for (String s : strs) {
+ char[] ca = s.toCharArray();
+ Arrays.sort(ca);
+ String key = String.valueOf(ca);
+ map.computeIfAbsent(key, k -> new ArrayList<>()).add(s);
+ }
+ return new ArrayList<>(map.values());
+}",10,10
+,"class MatrixAddition
+{
+public static void main(String args[])
+{
+int[][] a = new int[][] { { 1, 2, 3},{ 4, 5, 6},{ 7, 8, 9} };
+
+int[][] b = new int[][] { { 10, 11, 12},{ 13, 14, 15},{ 16, 17, 18} };
+int[][] c = new int[3][3];
+if(a.length == b.length && a[0].length == b[0].length)
+{
+for(int i = 0;i < a.length;i++)
+{
+for(int j = 0;j < a[i].length;j++)
+{
+c[i][j] = a[i][j] + b[i][j];
+}
+}
+}
+else
+{
+System.out.println(""'A' and 'B' Matrix are not SAME"");
+return;
+}
+System.out.println(""The Matrix 'A' Value:"");
+for(int i = 0;i < a.length;i++)
+{
+for(int j = 0;j < a[i].length;j++)
+{
+System.out.print(a[i][j] + "" "");
+}
+System.out.println();
+}
+
+System.out.println(""The Matrix 'B' Value:"");
+for(int i = 0;i < a.length;i++)
+{
+for(int j = 0;j < a[i].length;j++)
+{
+System.out.print(b[i][j]+ "" "");
+ }
+System.out.println();
+}
+ System.out.println(""The Addition Matrix of 'A' and 'B' Value:"");
+for(int i = 0;i < a.length;i++)
+{
+for(int j = 0;j < a[i].length;j++)
+{
+System.out.print(c[i][j] + "" "");
+}
+System.out.println();
+}
+}
+}",0.0,IPSGWALIOR.ORG,,JAVA,"class MatrixAddition
+{
+public static void main(String args[])
+{
+int[][] a = new int[][] { { 1, 2, 3},{ 4, 5, 6},{ 7, 8, 9} };
+
+int[][] b = new int[][] { { 10, 11, 12},{ 13, 14, 15},{ 16, 17, 18} };
+int[][] c = new int[3][3];
+if(a.length == b.length && a[0].length == b[0].length)
+{
+for(int i = 0;i < a.length;i++)
+{
+for(int j = 0;j < a[i].length;j++)
+{
+c[i][j] = a[i][j] + b[i][j];
+}
+}
+}
+else
+{
+System.out.println(""'A' and 'B' Matrix are not SAME"");
+return;
+}
+System.out.println(""The Matrix 'A' Value:"");
+for(int i = 0;i < a.length;i++)
+{
+for(int j = 0;j < a[i].length;j++)
+{
+System.out.print(a[i][j] + "" "");
+}
+System.out.println();
+}
+
+System.out.println(""The Matrix 'B' Value:"");
+for(int i = 0;i < a.length;i++)
+{
+for(int j = 0;j < a[i].length;j++)
+{
+System.out.print(b[i][j]+ "" "");
+ }
+System.out.println();
+}
+ System.out.println(""The Addition Matrix of 'A' and 'B' Value:"");
+for(int i = 0;i < a.length;i++)
+{
+for(int j = 0;j < a[i].length;j++)
+{
+System.out.print(c[i][j] + "" "");
+}
+System.out.println();
+}
+}
+}",53,53
+,"class LRUCache extends LinkedHashMap {
+ private final int capacity;
+ public LRUCache(int capacity) {
+ super(capacity, 0.75f, true);
+ this.capacity = capacity;
+ }
+ protected boolean removeEldestEntry(Map.Entry eldest) {
+ return size() > capacity;
+ }
+}",1.0,GEMINI,Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.,JAVA,"class LRUCache extends LinkedHashMap {
+ private final int capacity;
+ public LRUCache(int capacity) {
+ super(capacity, 0.75f, true);
+ this.capacity = capacity;
+ }
+ protected boolean removeEldestEntry(Map.Entry eldest) {
+ return size() > capacity;
+ }
+}",10,10
+,"class NullMatrix
+{
+public static void main(String args[])
+{
+int[][] a = new int[][] { { 0, 0, 0},{ 0, 0, 1},{ 0, 0, 0} };
+boolean setValue = true;
+abc: for(int i = 0;i < a.length;i++)
+{
+for(int j = 0;j < a[i].length;j++)
+{
+if(a[i][j] != 0)
+{
+setValue = false;
+break abc;
+}
+}
+}
+
+System.out.println(""The Given Matrix Value:"");
+for(int i = 0;i < a.length;i++)
+{
+for(int j = 0;j < a[i].length;j++)
+{
+System.out.print(a[i][j] + "" "");
+}
+System.out.println();
+}
+if(setValue == true)
+{
+System.out.println(""The Given Matrix is a Null Matrix"");
+}
+else
+{
+System.out.println(""The Given Matrix is not a Null Matrix"");
+}
+}
+}
",0.0,IPSGWALIOR.ORG,,JAVA,"class NullMatrix
+{
+public static void main(String args[])
+{
+int[][] a = new int[][] { { 0, 0, 0},{ 0, 0, 1},{ 0, 0, 0} };
+boolean setValue = true;
+abc: for(int i = 0;i < a.length;i++)
+{
+for(int j = 0;j < a[i].length;j++)
+{
+if(a[i][j] != 0)
+{
+setValue = false;
+break abc;
+}
+}
+}
+
+System.out.println(""The Given Matrix Value:"");
+for(int i = 0;i < a.length;i++)
+{
+for(int j = 0;j < a[i].length;j++)
+{
+System.out.print(a[i][j] + "" "");
+}
+System.out.println();
+}
+if(setValue == true)
+{
+System.out.println(""The Given Matrix is a Null Matrix"");
+}
+else
+{
+System.out.println(""The Given Matrix is not a Null Matrix"");
+}
+}
+}",37,37
+,"public int lengthOfLongestSubstring(String s) {
+ int max = 0;
+ Map map = new HashMap<>();
+ for (int j = 0, i = 0; j < s.length(); j++) {
+ if (map.containsKey(s.charAt(j))) i = Math.max(map.get(s.charAt(j)), i);
+ max = Math.max(max, j - i + 1);
+ map.put(s.charAt(j), j + 1);
+ }
+ return max;
+}",1.0,GEMINI,Find the length of the longest substring without repeating characters.,JAVA,"public int lengthOfLongestSubstring(String s) {
+ int max = 0;
+ Map map = new HashMap<>();
+ for (int j = 0, i = 0; j < s.length(); j++) {
+ if (map.containsKey(s.charAt(j))) i = Math.max(map.get(s.charAt(j)), i);
+ max = Math.max(max, j - i + 1);
+ map.put(s.charAt(j), j + 1);
+ }
+ return max;
+}",10,10
+,"class DiagonalMatrix
+ {
+ public static void main(String args[])
+ {
+ int[][] a = new int[][] { { 1, 0, 1},{ 0, 3, 0},{ 0, 0, 3} };
+ boolean setValue = true;
+ abc: for(int i = 0;i < a.length;i++)
+ {
+ for(int j = 0;j < a[i].length;j++)
+ {
+
+ if(i == j)
+ {
+ if(a[i][j] == 0)
+ {
+ setValue = false;
+ break abc;
+ }
+ }
+ else if(a[i][j] != 0)
+ {
+ setValue = false;
+ break abc;
+ }
+ }
+ }
+
+ System.out.println(""The Given Matrix Value:"");
+ for(int i = 0;i < a.length;i++)
+ {
+ for(int j = 0;j < a[i].length;j++)
+ {
+ System.out.print(a[i][j] + "" "");
+ }
+ System.out.println();
+ }
+
+ if(setValue == true)
+ {
+ System.out.println(""The Given Matrix is a Diagonal Matrix"");
+ }
+ else
+ {
+ System.out.println(""The Given Matrix is not a Diagonal Matrix"");
+ }
+ }
+ }
",0.0,IPSGWALIOR.ORG,,JAVA,"class DiagonalMatrix
+ {
+ public static void main(String args[])
+ {
+ int[][] a = new int[][] { { 1, 0, 1},{ 0, 3, 0},{ 0, 0, 3} };
+ boolean setValue = true;
+ abc: for(int i = 0;i < a.length;i++)
+ {
+ for(int j = 0;j < a[i].length;j++)
+ {
+
+ if(i == j)
+ {
+ if(a[i][j] == 0)
+ {
+ setValue = false;
+ break abc;
+ }
+ }
+ else if(a[i][j] != 0)
+ {
+ setValue = false;
+ break abc;
+ }
+ }
+ }
+
+ System.out.println(""The Given Matrix Value:"");
+ for(int i = 0;i < a.length;i++)
+ {
+ for(int j = 0;j < a[i].length;j++)
+ {
+ System.out.print(a[i][j] + "" "");
+ }
+ System.out.println();
+ }
+
+ if(setValue == true)
+ {
+ System.out.println(""The Given Matrix is a Diagonal Matrix"");
+ }
+ else
+ {
+ System.out.println(""The Given Matrix is not a Diagonal Matrix"");
+ }
+ }
+ }",47,47
+,"class MinStack {
+ private Stack st = new Stack<>(), minSt = new Stack<>();
+ public void push(int x) {
+ st.push(x);
+ if (minSt.isEmpty() || x <= minSt.peek()) minSt.push(x);
+ }
+ public void pop() {
+ if (st.pop().equals(minSt.peek())) minSt.pop();
+ }
+ public int getMin() { return minSt.peek(); }
+}",1.0,GEMINI,"Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.",JAVA,"class MinStack {
+ private Stack st = new Stack<>(), minSt = new Stack<>();
+ public void push(int x) {
+ st.push(x);
+ if (minSt.isEmpty() || x <= minSt.peek()) minSt.push(x);
+ }
+ public void pop() {
+ if (st.pop().equals(minSt.peek())) minSt.pop();
+ }
+ public int getMin() { return minSt.peek(); }
+}",11,11
+,"import java.util.Scanner;
+class LinearSearch
+{
+public static void main(String args[])
+{
+int i, num, searchval, array[];
+Scanner in = new Scanner(System.in);
+System.out.println(""Enter number of elements"");
+num = in.nextInt();
+array = new int[num];
+System.out.println(""Enter "" + num + "" integers"");
+
+for (i = 0; i < num; i++)
+array[i] = in.nextInt();
+System.out.println(""Enter the search value:"");
+searchval = in.nextInt();
+in.close();
+for (i = 0; i < num; i++)
+{
+if (array[i] == searchval)
+{
+System.out.println(searchval + "" is present at location "" + (i + 1));
+break;
+}
+}
+if (i == num)
+System.out.println(searchval + "" is not exist in array."");
+}
",0.0,IPSGWALIOR.ORG,,JAVA,"import java.util.Scanner;
+class LinearSearch
+{
+public static void main(String args[])
+{
+int i, num, searchval, array[];
+Scanner in = new Scanner(System.in);
+System.out.println(""Enter number of elements"");
+num = in.nextInt();
+array = new int[num];
+System.out.println(""Enter "" + num + "" integers"");
+
+for (i = 0; i < num; i++)
+array[i] = in.nextInt();
+System.out.println(""Enter the search value:"");
+searchval = in.nextInt();
+in.close();
+for (i = 0; i < num; i++)
+{
+if (array[i] == searchval)
+{
+System.out.println(searchval + "" is present at location "" + (i + 1));
+break;
+}
+}
+if (i == num)
+System.out.println(searchval + "" is not exist in array."");
+}",28,28
+,"public int findKthLargest(int[] nums, int k) {
+ PriorityQueue pq = new PriorityQueue<>();
+ for (int val : nums) {
+ pq.offer(val);
+ if (pq.size() > k) pq.poll();
+ }
+ return pq.peek();
+}",1.0,GEMINI,Find the kth largest element in an unsorted array.,JAVA,"public int findKthLargest(int[] nums, int k) {
+ PriorityQueue pq = new PriorityQueue<>();
+ for (int val : nums) {
+ pq.offer(val);
+ if (pq.size() > k) pq.poll();
+ }
+ return pq.peek();
+}",8,8
+,"import java.util.Scanner;
+public class BinarySearch
+{
+public static void main(String args[])
+{
+int counter, num, item, array[], first, last, middle;
+Scanner input = new Scanner(System.in);
+System.out.println(""Enter number of elements:"");
+num = input.nextInt();
+array = new int[num];
+System.out.println(""Enter "" + num + "" integers"");
+for (counter = 0; counter < num; counter++)
+array[counter] = input.nextInt();
+System.out.println(""Enter the search value:"");
+item = input.nextInt();
+first = 0;
+last = num - 1;
+middle = (first + last) / 2;
+while (first <= last)
+{
+if (array[middle] < item)
+first = middle + 1;
+else if (array[middle] == item)
+{
+System.out.println(item + "" found at location "" + (middle + 1) + ""."");
+break;
+
+}
+else
+{
+last = middle - 1;
+}
+middle = (first + last) / 2;
+}
+if (first > last)
+System.out.println(item + "" is not found.\n"");
+}
+}
+",0.0,IPSGWALIOR.ORG,,JAVA,"import java.util.Scanner;
+public class BinarySearch
+{
+public static void main(String args[])
+{
+int counter, num, item, array[], first, last, middle;
+Scanner input = new Scanner(System.in);
+System.out.println(""Enter number of elements:"");
+num = input.nextInt();
+array = new int[num];
+System.out.println(""Enter "" + num + "" integers"");
+for (counter = 0; counter < num; counter++)
+array[counter] = input.nextInt();
+System.out.println(""Enter the search value:"");
+item = input.nextInt();
+first = 0;
+last = num - 1;
+middle = (first + last) / 2;
+while (first <= last)
+{
+if (array[middle] < item)
+first = middle + 1;
+else if (array[middle] == item)
+{
+System.out.println(item + "" found at location "" + (middle + 1) + ""."");
+break;
+
+}
+else
+{
+last = middle - 1;
+}
+middle = (first + last) / 2;
+}
+if (first > last)
+System.out.println(item + "" is not found.\n"");
+}
+}",38,38
+,"public ListNode mergeKLists(ListNode[] lists) {
+ PriorityQueue pq = new PriorityQueue<>((a, b) -> a.val - b.val);
+ for (ListNode l : lists) if (l != null) pq.add(l);
+ ListNode dummy = new ListNode(0), tail = dummy;
+ while (!pq.isEmpty()) {
+ tail.next = pq.poll();
+ tail = tail.next;
+ if (tail.next != null) pq.add(tail.next);
+ }
+ return dummy.next;
+}",1.0,GEMINI,write a program to Merge k sorted linked lists into one sorted linked list.,JAVA,"public ListNode mergeKLists(ListNode[] lists) {
+ PriorityQueue pq = new PriorityQueue<>((a, b) -> a.val - b.val);
+ for (ListNode l : lists) if (l != null) pq.add(l);
+ ListNode dummy = new ListNode(0), tail = dummy;
+ while (!pq.isEmpty()) {
+ tail.next = pq.poll();
+ tail = tail.next;
+ if (tail.next != null) pq.add(tail.next);
+ }
+ return dummy.next;
+}",11,11
+,"public class FindHCFAndLCM
+{
+public static void main(String args[])
+{
+int a, b, x, y, t, hcf, lcm;
+x = 6;
+y = 10;
+a = x;
+b = y;
+while (b != 0)
+{
+t = b;
+b = a % b;
+a = t;
+}
+hcf = a;
+lcm = (x * y) / hcf;
+System.out.print(""HCF and LCM of : "" + x + "" and "" + y + "" is :\n"");
+System.out.print(""HCF = "" + hcf);
+System.out.print(""\nLCM = "" + lcm);
+}
+}
",0.0,IPSGWALIOR.ORG,,JAVA,"public class FindHCFAndLCM
+{
+public static void main(String args[])
+{
+int a, b, x, y, t, hcf, lcm;
+x = 6;
+y = 10;
+a = x;
+b = y;
+while (b != 0)
+{
+t = b;
+b = a % b;
+a = t;
+}
+hcf = a;
+lcm = (x * y) / hcf;
+System.out.print(""HCF and LCM of : "" + x + "" and "" + y + "" is :\n"");
+System.out.print(""HCF = "" + hcf);
+System.out.print(""\nLCM = "" + lcm);
+}
+}",22,22
+,"public int trap(int[] height) {
+ int l = 0, r = height.length - 1, lMax = 0, rMax = 0, ans = 0;
+ while (l < r) {
+ if (height[l] < height[r]) {
+ if (height[l] >= lMax) lMax = height[l]; else ans += lMax - height[l];
+ l++;
+ } else {
+ if (height[r] >= rMax) rMax = height[r]; else ans += rMax - height[r];
+ r--;
+ }
+ }
+ return ans;
+}",1.0,GEMINI,"write a java progrom for Given n non-negative integers representing an elevation map, compute how much water it can trap.",JAVA,"public int trap(int[] height) {
+ int l = 0, r = height.length - 1, lMax = 0, rMax = 0, ans = 0;
+ while (l < r) {
+ if (height[l] < height[r]) {
+ if (height[l] >= lMax) lMax = height[l]; else ans += lMax - height[l];
+ l++;
+ } else {
+ if (height[r] >= rMax) rMax = height[r]; else ans += rMax - height[r];
+ r--;
+ }
+ }
+ return ans;
+}",13,13
+,"public class Cube {
+public static void main(String arg[]) {
+int side=5;
+float volume=side * side * side;
+System.out.println(""Volume of Cube :""+ volume);
+}
+}
",0.0,IPSGWALIOR.ORG,,JAVA,"public class Cube {
+public static void main(String arg[]) {
+int side=5;
+float volume=side * side * side;
+System.out.println(""Volume of Cube :""+ volume);
+}
+}",7,7
+,"public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
+ if (root == null || root == p || root == q) return root;
+ TreeNode left = lowestCommonAncestor(root.left, p, q);
+ TreeNode right = lowestCommonAncestor(root.right, p, q);
+ return left == null ? right : right == null ? left : root;
+}",1.0,GEMINI,Find the lowest common ancestor of two given nodes in a tree.,JAVA,"public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
+ if (root == null || root == p || root == q) return root;
+ TreeNode left = lowestCommonAncestor(root.left, p, q);
+ TreeNode right = lowestCommonAncestor(root.right, p, q);
+ return left == null ? right : right == null ? left : root;
+}",6,6
+,"public class ReverseNum
+{
+public static void main(String[] args)
+{
+
+int rev = 0;
+int num = 1234;
+int no=num;
+while (num > 0)
+{
+int rem = num % 10;
+rev = rem + (rev * 10);
+num = num / 10;
+}
+System.out.println(""Number = ""+no);
+System.out.println(""Reverse = ""+rev);
+}
+}",0.0,IPSGWALIOR.ORG,,JAVA,"public class ReverseNum
+{
+public static void main(String[] args)
+{
+
+int rev = 0;
+int num = 1234;
+int no=num;
+while (num > 0)
+{
+int rem = num % 10;
+rev = rem + (rev * 10);
+num = num / 10;
+}
+System.out.println(""Number = ""+no);
+System.out.println(""Reverse = ""+rev);
+}
+}",18,18
+,"public int ladderLength(String begin, String end, List wordList) {
+ Set set = new HashSet<>(wordList);
+ Queue q = new LinkedList<>(); q.add(begin);
+ int step = 1;
+ while (!q.isEmpty()) {
+ int size = q.size();
+ for (int i = 0; i < size; i++) {
+ char[] cur = q.poll().toCharArray();
+ for (int j = 0; j < cur.length; j++) {
+ char tmp = cur[j];
+ for (char c = 'a'; c <= 'z'; c++) {
+ cur[j] = c; String next = new String(cur);
+ if (set.contains(next)) {
+ if (next.equals(end)) return step + 1;
+ q.add(next); set.remove(next);
+ }
+ }
+ cur[j] = tmp;
+ }
+ }
+ step++;
+ }
+ return 0;
+}",1.0,GEMINI,give me an java program to Find the length of shortest transformation sequence from beginWord to endWord.,JAVA,"public int ladderLength(String begin, String end, List wordList) {
+ Set set = new HashSet<>(wordList);
+ Queue q = new LinkedList<>(); q.add(begin);
+ int step = 1;
+ while (!q.isEmpty()) {
+ int size = q.size();
+ for (int i = 0; i < size; i++) {
+ char[] cur = q.poll().toCharArray();
+ for (int j = 0; j < cur.length; j++) {
+ char tmp = cur[j];
+ for (char c = 'a'; c <= 'z'; c++) {
+ cur[j] = c; String next = new String(cur);
+ if (set.contains(next)) {
+ if (next.equals(end)) return step + 1;
+ q.add(next); set.remove(next);
+ }
+ }
+ cur[j] = tmp;
+ }
+ }
+ step++;
+ }
+ return 0;
+}",24,24
+,"import java.util.HashMap;
+import java.util.Scanner;
+public class IntegertoRoman
+{
+private static int[] bases = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
+private static HashMap map = new HashMap();
+private static void setup()
+{
+map.put(1, ""I"");
+map.put(4, ""IV"");
+map.put(5, ""V"");
+map.put(9, ""IX"");
+map.put(10, ""X"");
+map.put(40, ""XL"");
+map.put(50, ""L"");
+map.put(90, ""XC"");
+map.put(100, ""C"");
+map.put(400, ""CD"");
+map.put(500, ""D"");
+map.put(900, ""CM"");
+map.put(1000, ""M"");
+}
+public String intToRoman(int num)
+{
+setup();
+String result = new String();
+for (int i : bases)
+{
+while (num >= i)
+{
+
+result += map.get(i);
+num -= i;
+}
+}
+return result;
+}
+public static void main(String arg[])
+{
+System.out.println(""Enter the number : "");
+Scanner sc = new Scanner(System.in);
+int no = sc.nextInt();
+IntegertoRoman in = new IntegertoRoman();
+int value=no;
+String sd = in.intToRoman(value);
+System.out.println(value+"" ---> "" + sd);
+}
+}
",0.0,IPSGWALIOR.ORG,,JAVA,"import java.util.HashMap;
+import java.util.Scanner;
+public class IntegertoRoman
+{
+private static int[] bases = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
+private static HashMap map = new HashMap();
+private static void setup()
+{
+map.put(1, ""I"");
+map.put(4, ""IV"");
+map.put(5, ""V"");
+map.put(9, ""IX"");
+map.put(10, ""X"");
+map.put(40, ""XL"");
+map.put(50, ""L"");
+map.put(90, ""XC"");
+map.put(100, ""C"");
+map.put(400, ""CD"");
+map.put(500, ""D"");
+map.put(900, ""CM"");
+map.put(1000, ""M"");
+}
+public String intToRoman(int num)
+{
+setup();
+String result = new String();
+for (int i : bases)
+{
+while (num >= i)
+{
+
+result += map.get(i);
+num -= i;
+}
+}
+return result;
+}
+public static void main(String arg[])
+{
+System.out.println(""Enter the number : "");
+Scanner sc = new Scanner(System.in);
+int no = sc.nextInt();
+IntegertoRoman in = new IntegertoRoman();
+int value=no;
+String sd = in.intToRoman(value);
+System.out.println(value+"" ---> "" + sd);
+}
+}",48,48
+,"public class Singleton {
+ private static volatile Singleton instance;
+ public static Singleton getInstance() {
+ if (instance == null) {
+ synchronized (Singleton.class) {
+ if (instance == null) instance = new Singleton();
+ }
+ }
+ return instance;
+ }
+}",1.0,GEMINI,write a program to Implement a thread-safe Singleton that prevents unnecessary synchronization.,JAVA,"public class Singleton {
+ private static volatile Singleton instance;
+ public static Singleton getInstance() {
+ if (instance == null) {
+ synchronized (Singleton.class) {
+ if (instance == null) instance = new Singleton();
+ }
+ }
+ return instance;
+ }
+}",11,11
+,"public class WordCount
+{
+public static void main(String args[])
+{
+String s = ""welcome to candid java tutorial"";
+int count = 1;
+for (int i = 0; i < s.length() - 1; i++)
+{
+if ((s.charAt(i) == ' ') && (s.charAt(i + 1) != ' '))
+{
+count++;
+}
+}
+System.out.println(""Number of words in a string = "" + count);
+}
",0.0,IPSGWALIOR.ORG,,JAVA,"public class WordCount
+{
+public static void main(String args[])
+{
+String s = ""welcome to candid java tutorial"";
+int count = 1;
+for (int i = 0; i < s.length() - 1; i++)
+{
+if ((s.charAt(i) == ' ') && (s.charAt(i + 1) != ' '))
+{
+count++;
+}
+}
+System.out.println(""Number of words in a string = "" + count);
+}",15,15
+,"class PC {
+ LinkedList list = new LinkedList<>();
+ public void produce() throws InterruptedException {
+ synchronized(this) {
+ while (list.size() == 1) wait();
+ list.add(1); notify();
+ }
+ }
+ public void consume() throws InterruptedException {
+ synchronized(this) {
+ while (list.isEmpty()) wait();
+ list.removeFirst(); notify();
+ }
+ }
+}",1.0,GEMINI,give me a java program to Implement the Producer-Consumer pattern using wait() and notify(),JAVA,"class PC {
+ LinkedList list = new LinkedList<>();
+ public void produce() throws InterruptedException {
+ synchronized(this) {
+ while (list.size() == 1) wait();
+ list.add(1); notify();
+ }
+ }
+ public void consume() throws InterruptedException {
+ synchronized(this) {
+ while (list.isEmpty()) wait();
+ list.removeFirst(); notify();
+ }
+ }
+}",15,15
+,"public class CountWords
+{
+public static void main(String[] args)
+{
+String input=""Welcome to Java Session Session Session"";
+String[] words=input.split("" "");
+int wrc=1;
+for(int i=0;i { synchronized(r1) { synchronized(r2) {} } }).start();
+ new Thread(() -> { synchronized(r2) { synchronized(r1) {} } }).start();
+}",1.0,GEMINI,Write a Java program that results in a deadlock.,JAVA,"public void deadlock() {
+ String r1 = ""r1"", r2 = ""r2"";
+ new Thread(() -> { synchronized(r1) { synchronized(r2) {} } }).start();
+ new Thread(() -> { synchronized(r2) { synchronized(r1) {} } }).start();
+}",5,5
+,"public class RemoveDuplicate
+{
+public static void main(String[] args)
+{
+String input=""Welcome to Java Session Java Session Session Java"";
+String[] words=input.split("" "");
+for(int i=0;i= lMax) lMax = height[l]; else trapped += lMax - height[l++];
+ } else {
+ if (height[r] >= rMax) rMax = height[r]; else trapped += rMax - height[r--];
+ }
+ }
+ return trapped;
+}",1.0,GEMINI,"write an effective java code for a Given elevation map (array), calculate how much water it can trap after raining. Use a two-pointer approach for $O(n)$ time and $O(1)$ space.",JAVA,"public int trap(int[] height) {
+ int l = 0, r = height.length - 1, lMax = 0, rMax = 0, trapped = 0;
+ while (l < r) {
+ if (height[l] < height[r]) {
+ if (height[l] >= lMax) lMax = height[l]; else trapped += lMax - height[l++];
+ } else {
+ if (height[r] >= rMax) rMax = height[r]; else trapped += rMax - height[r--];
+ }
+ }
+ return trapped;
+}",11,11
+,"import java.io.IOException;
+
+ public class FindTtalCountWords
+ {
+
+ public static void main(String args[]) throws IOException
+ {
+ countWords(""apple banna apple fruit fruit apple hello hi hi hello hi"");
+
+ }
+
+ static void countWords(String st)
+ {
+ String[] words = st.split(""\\s"");
+ int[] fr = new int[words.length];
+ for (int i = 0; i < fr.length; i++)
+ fr[i] = 0;
+ for (int i = 0; i < words.length; i++)
+ {
+ for (int j = 0; j < words.length; j++)
+ {
+ if (words[i].equals(words[j]))
+ {
+
+ fr[i]++;
+
+ }
+ }
+ }
+
+ for (int i = 0; i < words.length; i++)
+ {
+ for (int j = 0; j < words.length; j++)
+ {
+ if (words[i].equals(words[j]))
+ {
+ if (i != j)
+ {
+ words[i] = """";
+ }
+ }
+ }
+ }
+
+ int total = 0;
+ System.out.println(""Words and words count:"");
+ for (int i = 0; i < words.length; i++)
+ {
+ if (words[i] != """")
+ {
+
+ System.out.println(words[i] + ""="" + fr[i]);
+
+ total += fr[i];
+
+ }
+ }
+ System.out.println(""Total words counted: "" + total);
+ }
+ }
",0.0,IPSGWALIOR.ORG,,JAVA,"import java.io.IOException;
+
+ public class FindTtalCountWords
+ {
+
+ public static void main(String args[]) throws IOException
+ {
+ countWords(""apple banna apple fruit fruit apple hello hi hi hello hi"");
+
+ }
+
+ static void countWords(String st)
+ {
+ String[] words = st.split(""\\s"");
+ int[] fr = new int[words.length];
+ for (int i = 0; i < fr.length; i++)
+ fr[i] = 0;
+ for (int i = 0; i < words.length; i++)
+ {
+ for (int j = 0; j < words.length; j++)
+ {
+ if (words[i].equals(words[j]))
+ {
+
+ fr[i]++;
+
+ }
+ }
+ }
+
+ for (int i = 0; i < words.length; i++)
+ {
+ for (int j = 0; j < words.length; j++)
+ {
+ if (words[i].equals(words[j]))
+ {
+ if (i != j)
+ {
+ words[i] = """";
+ }
+ }
+ }
+ }
+
+ int total = 0;
+ System.out.println(""Words and words count:"");
+ for (int i = 0; i < words.length; i++)
+ {
+ if (words[i] != """")
+ {
+
+ System.out.println(words[i] + ""="" + fr[i]);
+
+ total += fr[i];
+
+ }
+ }
+ System.out.println(""Total words counted: "" + total);
+ }
+ }",60,60
+,"class Printer {
+ boolean oddTurn = true;
+ synchronized void print(int n, boolean isOdd) throws Exception {
+ while (oddTurn != isOdd) wait();
+ System.out.println(n);
+ oddTurn = !isOdd;
+ notifyAll();
+ }
+}
+// Logic: Thread 1 calls print(i, true), Thread 2 calls print(i, false)",1.0,GEMINI,Create two threads—one printing odd numbers and one even—ensuring they print in perfect sequence up to $N$.,JAVA,"class Printer {
+ boolean oddTurn = true;
+ synchronized void print(int n, boolean isOdd) throws Exception {
+ while (oddTurn != isOdd) wait();
+ System.out.println(n);
+ oddTurn = !isOdd;
+ notifyAll();
+ }
+}
+// Logic: Thread 1 calls print(i, true), Thread 2 calls print(i, false)",10,10
+,"public class PalindromeChecking
+{
+public static void main(String[] args)
+{
+String inpstr =""AMMA"";
+char[] inpArray = inpstr.toCharArray();
+char[] revArray = new char[inpArray.length];
+int j=0;
+for (int i = inpArray.length - 1; i >= 0; i--) {
+revArray[j]=inpArray[i];
+j++;
+}
+String revstr=String.valueOf(revArray);
+if(inpstr.equals(revstr))
+{
+System.out.println(""The given string is a Palindrome"");
+}
+else
+{
+System.out.println(""The given string is not a Palindrome"");
+}
+}
+}
",0.0,IPSGWALIOR.ORG,,JAVA,"public class PalindromeChecking
+{
+public static void main(String[] args)
+{
+String inpstr =""AMMA"";
+char[] inpArray = inpstr.toCharArray();
+char[] revArray = new char[inpArray.length];
+int j=0;
+for (int i = inpArray.length - 1; i >= 0; i--) {
+revArray[j]=inpArray[i];
+j++;
+}
+String revstr=String.valueOf(revArray);
+if(inpstr.equals(revstr))
+{
+System.out.println(""The given string is a Palindrome"");
+}
+else
+{
+System.out.println(""The given string is not a Palindrome"");
+}
+}
+}",23,23
+,"public List flattenAndProcess(List> nested) {
+ return nested.stream()
+ .flatMap(Collection::stream)
+ .map(String::toUpperCase)
+ .distinct()
+ .collect(Collectors.toList());
+}",1.0,GEMINI,"Write a Java Stream pipeline to flatten a List> into a single list of uppercase strings, removing duplicates.",JAVA,"public List flattenAndProcess(List> nested) {
+ return nested.stream()
+ .flatMap(Collection::stream)
+ .map(String::toUpperCase)
+ .distinct()
+ .collect(Collectors.toList());
+}",7,7
+,"public class RemoveAllVovels {
+
+ public static void main(String[] args) {
+ String string = ""Welcome to Candid Java Programming"";
+ System.out.println(""Input String : ""+string);
+ string = string.replaceAll(""[AaEeIiOoUu]"", """");
+ System.out.println(string);
+ }
+ }
",0.0,IPSGWALIOR.ORG,,JAVA,"public class RemoveAllVovels {
+
+ public static void main(String[] args) {
+ String string = ""Welcome to Candid Java Programming"";
+ System.out.println(""Input String : ""+string);
+ string = string.replaceAll(""[AaEeIiOoUu]"", """");
+ System.out.println(string);
+ }
+ }",9,9
+,"public List> threeSum(int[] nums) {
+ Arrays.sort(nums);
+ List> res = new ArrayList<>();
+ for (int i = 0; i < nums.length - 2 && nums[i] <= 0; i++) {
+ if (i > 0 && nums[i] == nums[i-1]) continue;
+ int l = i + 1, r = nums.length - 1;
+ while (l < r) {
+ int sum = nums[i] + nums[l] + nums[r];
+ if (sum < 0) l++;
+ else if (sum > 0) r--;
+ else {
+ res.add(Arrays.asList(nums[i], nums[l++], nums[r--]));
+ while (l < r && nums[l] == nums[l-1]) l++;
+ }
+ }
+ }
+ return res;
+}",1.0,GEMINI,Find all unique triplets in an array that sum to zero. Avoid duplicate triplets in the output.,JAVA,"public List> threeSum(int[] nums) {
+ Arrays.sort(nums);
+ List> res = new ArrayList<>();
+ for (int i = 0; i < nums.length - 2 && nums[i] <= 0; i++) {
+ if (i > 0 && nums[i] == nums[i-1]) continue;
+ int l = i + 1, r = nums.length - 1;
+ while (l < r) {
+ int sum = nums[i] + nums[l] + nums[r];
+ if (sum < 0) l++;
+ else if (sum > 0) r--;
+ else {
+ res.add(Arrays.asList(nums[i], nums[l++], nums[r--]));
+ while (l < r && nums[l] == nums[l-1]) l++;
+ }
+ }
+ }
+ return res;
+}",18,18
+,"public class StringCapital
+ {
+ public static void main(String[] args)
+ {
+ String str = ""welcome to candid java program"";
+ StringBuilder result = new StringBuilder(str.length());
+
+ String words[] = str.split(""\\ "");
+ for (int i = 0; i < words.length; i++)
+ {
+
+result.append(Character.toUpperCase(words[i].charAt(0))).append(words[i].substring(1)).append
+("" "");
+
+ }
+
+ System.out.println(result);
+
+
+ }
+
+ }",0.0,IPSGWALIOR.ORG,,JAVA,"public class StringCapital
+ {
+ public static void main(String[] args)
+ {
+ String str = ""welcome to candid java program"";
+ StringBuilder result = new StringBuilder(str.length());
+
+ String words[] = str.split(""\\ "");
+ for (int i = 0; i < words.length; i++)
+ {
+
+result.append(Character.toUpperCase(words[i].charAt(0))).append(words[i].substring(1)).append
+("" "");
+
+ }
+
+ System.out.println(result);
+
+
+ }
+
+ }",22,22
+,"import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
+public class ThreadSafeLRUCache {
+ private final int capacity;
+ private final ConcurrentHashMap> cache;
+ private final DoublyLinkedList dll;
+ private final ReentrantReadWriteLock lock;
+
+ private static class Node {
+ K key;
+ V value;
+ Node prev;
+ Node next;
+
+ Node(K key, V value) {
+ this.key = key;
+ this.value = value;
+ }
+ }
+
+ private static class DoublyLinkedList {
+ private Node head;
+ private Node tail;
+
+ void addToFront(Node node) {
+ if (head == null) {
+ head = tail = node;
+ } else {
+ node.next = head;
+ head.prev = node;
+ head = node;
+ }
+ }
+
+ void remove(Node node) {
+ if (node.prev != null) {
+ node.prev.next = node.next;
+ } else {
+ head = node.next;
+ }
+
+ if (node.next != null) {
+ node.next.prev = node.prev;
+ } else {
+ tail = node.prev;
+ }
+
+ node.prev = node.next = null;
+ }
+
+ Node removeLast() {
+ if (tail == null) return null;
+ Node last = tail;
+ remove(last);
+ return last;
+ }
+
+ void moveToFront(Node node) {
+ remove(node);
+ addToFront(node);
+ }
+ }
+
+ public ThreadSafeLRUCache(int capacity) {
+ this.capacity = capacity;
+ this.cache = new ConcurrentHashMap<>();
+ this.dll = new DoublyLinkedList<>();
+ this.lock = new ReentrantReadWriteLock();
+ }
+
+ public V get(K key) {
+ lock.readLock().lock();
+ try {
+ Node node = cache.get(key);
+ if (node == null) return null;
+
+ lock.readLock().unlock();
+ lock.writeLock().lock();
+ try {
+ dll.moveToFront(node);
+ return node.value;
+ } finally {
+ lock.readLock().lock();
+ lock.writeLock().unlock();
+ }
+ } finally {
+ lock.readLock().unlock();
+ }
+ }
+
+ public void put(K key, V value) {
+ lock.writeLock().lock();
+ try {
+ Node node = cache.get(key);
+
+ if (node != null) {
+ node.value = value;
+ dll.moveToFront(node);
+ } else {
+ node = new Node<>(key, value);
+
+ if (cache.size() >= capacity) {
+ Node removed = dll.removeLast();
+ if (removed != null) {
+ cache.remove(removed.key);
+ }
+ }
+
+ cache.put(key, node);
+ dll.addToFront(node);
+ }
+ } finally {
+ lock.writeLock().unlock();
+ }
+ }
+
+ public int size() {
+ lock.readLock().lock();
+ try {
+ return cache.size();
+ } finally {
+ lock.readLock().unlock();
+ }
+ }
+}",1.0,DEEPSEEK,Design and implement a thread-safe Least Recently Used (LRU) cache with O(1) average time complexity for get and put operations. The cache should have a fixed capacity and evict the least recently used item when capacity is reached.,JAVA,"import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
+public class ThreadSafeLRUCache {
+ private final int capacity;
+ private final ConcurrentHashMap> cache;
+ private final DoublyLinkedList dll;
+ private final ReentrantReadWriteLock lock;
+
+ private static class Node {
+ K key;
+ V value;
+ Node prev;
+ Node next;
+
+ Node(K key, V value) {
+ this.key = key;
+ this.value = value;
+ }
+ }
+
+ private static class DoublyLinkedList {
+ private Node head;
+ private Node tail;
+
+ void addToFront(Node node) {
+ if (head == null) {
+ head = tail = node;
+ } else {
+ node.next = head;
+ head.prev = node;
+ head = node;
+ }
+ }
+
+ void remove(Node node) {
+ if (node.prev != null) {
+ node.prev.next = node.next;
+ } else {
+ head = node.next;
+ }
+
+ if (node.next != null) {
+ node.next.prev = node.prev;
+ } else {
+ tail = node.prev;
+ }
+
+ node.prev = node.next = null;
+ }
+... truncated ...
+
+ lock.readLock().unlock();
+ lock.writeLock().lock();
+ try {
+ dll.moveToFront(node);
+ return node.value;
+ } finally {
+ lock.readLock().lock();
+ lock.writeLock().unlock();
+ }
+ } finally {
+ lock.readLock().unlock();
+ }
+ }
+
+ public void put(K key, V value) {
+ lock.writeLock().lock();
+ try {
+ Node node = cache.get(key);
+
+ if (node != null) {
+ node.value = value;
+ dll.moveToFront(node);
+ } else {
+ node = new Node<>(key, value);
+
+ if (cache.size() >= capacity) {
+ Node removed = dll.removeLast();
+ if (removed != null) {
+ cache.remove(removed.key);
+ }
+ }
+
+ cache.put(key, node);
+ dll.addToFront(node);
+ }
+ } finally {
+ lock.writeLock().unlock();
+ }
+ }
+
+ public int size() {
+ lock.readLock().lock();
+ try {
+ return cache.size();
+ } finally {
+ lock.readLock().unlock();
+ }
+ }
+}",126,101
+,"public class CommaSeparated
+{
+public static void main(String[] args)
+{
+String input=""Welcome,to,Java Session Session Session"";
+String[] words=input.split("","");
+for(int k=0;k capacity) {
+ throw new IllegalArgumentException(""Invalid token request"");
+ }
+
+ lock.lock();
+ try {
+ refillTokens();
+
+ if (availableTokens >= tokens) {
+ availableTokens -= tokens;
+ return true;
+ }
+ return false;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ public boolean tryAcquireWithTimeout(long tokens, long timeout, TimeUnit unit)
+ throws InterruptedException {
+ long timeoutMillis = unit.toMillis(timeout);
+ long startTime = System.currentTimeMillis();
+
+ while (System.currentTimeMillis() - startTime < timeoutMillis) {
+ if (tryAcquire(tokens)) {
+ return true;
+ }
+
+ // Calculate wait time for next token
+ lock.lock();
+ try {
+ refillTokens();
+ if (availableTokens < tokens && refillTokensPerSecond > 0) {
+ long tokensNeeded = tokens - availableTokens;
+ long waitTimeMillis = (tokensNeeded * 1000) / refillTokensPerSecond;
+ Thread.sleep(Math.min(waitTimeMillis, 100));
+ }
+ } finally {
+ lock.unlock();
+ }
+ }
+ return false;
+ }
+
+ private void refillTokens() {
+ long now = System.currentTimeMillis();
+ long timeElapsed = now - lastRefillTimestamp;
+
+ if (timeElapsed > 0) {
+ long tokensToAdd = (timeElapsed * refillTokensPerSecond) / 1000;
+
+ if (tokensToAdd > 0) {
+ availableTokens = Math.min(capacity, availableTokens + tokensToAdd);
+ lastRefillTimestamp = now;
+ }
+ }
+ }
+
+ public long getAvailableTokens() {
+ lock.lock();
+ try {
+ refillTokens();
+ return availableTokens;
+ } finally {
+ lock.unlock();
+ }
+ }
+}",1.0,DEEPSEEK,Implement a thread-safe rate limiter using the token bucket algorithm that allows a maximum of N requests per second.,JAVA,"import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.ReentrantLock;
+
+public class TokenBucketRateLimiter {
+ private final long capacity;
+ private final long refillTokensPerSecond;
+ private long availableTokens;
+ private long lastRefillTimestamp;
+ private final ReentrantLock lock;
+
+ public TokenBucketRateLimiter(long capacity, long refillTokensPerSecond) {
+ this.capacity = capacity;
+ this.refillTokensPerSecond = refillTokensPerSecond;
+ this.availableTokens = capacity;
+ this.lastRefillTimestamp = System.currentTimeMillis();
+ this.lock = new ReentrantLock();
+ }
+
+ public boolean tryAcquire() {
+ return tryAcquire(1);
+ }
+
+ public boolean tryAcquire(long tokens) {
+ if (tokens <= 0 || tokens > capacity) {
+ throw new IllegalArgumentException(""Invalid token request"");
+ }
+
+ lock.lock();
+ try {
+ refillTokens();
+
+ if (availableTokens >= tokens) {
+ availableTokens -= tokens;
+ return true;
+ }
+ return false;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ public boolean tryAcquireWithTimeout(long tokens, long timeout, TimeUnit unit)
+ throws InterruptedException {
+ long timeoutMillis = unit.toMillis(timeout);
+ long startTime = System.currentTimeMillis();
+
+ while (System.currentTimeMillis() - startTime < timeoutMillis) {
+ if (tryAcquire(tokens)) {
+ return true;
+ }
+
+ // Calculate wait time for next token
+ lock.lock();
+ try {
+ refillTokens();
+ if (availableTokens < tokens && refillTokensPerSecond > 0) {
+ long tokensNeeded = tokens - availableTokens;
+ long waitTimeMillis = (tokensNeeded * 1000) / refillTokensPerSecond;
+ Thread.sleep(Math.min(waitTimeMillis, 100));
+ }
+ } finally {
+ lock.unlock();
+ }
+ }
+ return false;
+ }
+
+ private void refillTokens() {
+ long now = System.currentTimeMillis();
+ long timeElapsed = now - lastRefillTimestamp;
+
+ if (timeElapsed > 0) {
+ long tokensToAdd = (timeElapsed * refillTokensPerSecond) / 1000;
+
+ if (tokensToAdd > 0) {
+ availableTokens = Math.min(capacity, availableTokens + tokensToAdd);
+ lastRefillTimestamp = now;
+ }
+ }
+ }
+
+ public long getAvailableTokens() {
+ lock.lock();
+ try {
+ refillTokens();
+ return availableTokens;
+ } finally {
+ lock.unlock();
+ }
+ }
+}",91,91
+,"public class AsciiToCharacter
+{
+public static void main(String[] args)
+{
+char c;
+for(int i=65;i<=90;i++)
+{
+c =(char)i;
+System.out.println(i+"" = ""+c);
+}
+}
+}",0.0,IPSGWALIOR.ORG,,JAVA,"public class AsciiToCharacter
+{
+public static void main(String[] args)
+{
+char c;
+for(int i=65;i<=90;i++)
+{
+c =(char)i;
+System.out.println(i+"" = ""+c);
+}
+}
+}",12,12
+,"import java.util.concurrent.locks.Condition;
+import java.util.concurrent.locks.ReentrantLock;
+
+public class CircularBuffer {
+ private final T[] buffer;
+ private final int capacity;
+ private int head;
+ private int tail;
+ private int count;
+ private final ReentrantLock lock;
+ private final Condition notEmpty;
+ private final Condition notFull;
+ private volatile boolean isShutdown;
+
+ @SuppressWarnings(""unchecked"")
+ public CircularBuffer(int capacity) {
+ this.capacity = capacity;
+ this.buffer = (T[]) new Object[capacity];
+ this.lock = new ReentrantLock();
+ this.notEmpty = lock.newCondition();
+ this.notFull = lock.newCondition();
+ this.isShutdown = false;
+ }
+
+ public boolean put(T item) throws InterruptedException {
+ return put(item, -1);
+ }
+
+ public boolean put(T item, long timeoutMillis) throws InterruptedException {
+ if (item == null) throw new NullPointerException();
+
+ lock.lock();
+ try {
+ // Wait until buffer is not full or shutdown
+ while (count == capacity && !isShutdown) {
+ if (timeoutMillis <= 0) {
+ notFull.await();
+ } else {
+ if (!notFull.await(timeoutMillis, java.util.concurrent.TimeUnit.MILLISECONDS)) {
+ return false;
+ }
+ }
+ }
+
+ if (isShutdown) return false;
+
+ buffer[tail] = item;
+ tail = (tail + 1) % capacity;
+ count++;
+ notEmpty.signal();
+ return true;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ public T take() throws InterruptedException {
+ return take(-1);
+ }
+
+ public T take(long timeoutMillis) throws InterruptedException {
+ lock.lock();
+ try {
+ // Wait until buffer is not empty or shutdown
+ while (count == 0 && !isShutdown) {
+ if (timeoutMillis <= 0) {
+ notEmpty.await();
+ } else {
+ if (!notEmpty.await(timeoutMillis, java.util.concurrent.TimeUnit.MILLISECONDS)) {
+ return null;
+ }
+ }
+ }
+
+ if (count == 0 && isShutdown) return null;
+
+ T item = buffer[head];
+ buffer[head] = null; // Help GC
+ head = (head + 1) % capacity;
+ count--;
+ notFull.signal();
+ return item;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ public boolean offer(T item) {
+ if (item == null) throw new NullPointerException();
+
+ lock.lock();
+ try {
+ if (count == capacity || isShutdown) {
+ return false;
+ }
+
+ buffer[tail] = item;
+ tail = (tail + 1) % capacity;
+ count++;
+ notEmpty.signal();
+ return true;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ public T poll() {
+ lock.lock();
+ try {
+ if (count == 0) {
+ return null;
+ }
+
+ T item = buffer[head];
+ buffer[head] = null;
+ head = (head + 1) % capacity;
+ count--;
+ notFull.signal();
+ return item;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ public int size() {
+ lock.lock();
+ try {
+ return count;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ public boolean isEmpty() {
+ lock.lock();
+ try {
+ return count == 0;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ public boolean isFull() {
+ lock.lock();
+ try {
+ return count == capacity;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ public void shutdown() {
+ lock.lock();
+ try {
+ isShutdown = true;
+ notEmpty.signalAll();
+ notFull.signalAll();
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ public void clear() {
+ lock.lock();
+ try {
+ for (int i = 0; i < capacity; i++) {
+ buffer[i] = null;
+ }
+ head = tail = count = 0;
+ notFull.signalAll();
+ } finally {
+ lock.unlock();
+ }
+ }
+}",1.0,DEEPSEEK,Implement a thread-safe circular buffer (ring buffer) with fixed capacity that supports concurrent producers and consumers.,JAVA,"import java.util.concurrent.locks.Condition;
+import java.util.concurrent.locks.ReentrantLock;
+
+public class CircularBuffer {
+ private final T[] buffer;
+ private final int capacity;
+ private int head;
+ private int tail;
+ private int count;
+ private final ReentrantLock lock;
+ private final Condition notEmpty;
+ private final Condition notFull;
+ private volatile boolean isShutdown;
+
+ @SuppressWarnings(""unchecked"")
+ public CircularBuffer(int capacity) {
+ this.capacity = capacity;
+ this.buffer = (T[]) new Object[capacity];
+ this.lock = new ReentrantLock();
+ this.notEmpty = lock.newCondition();
+ this.notFull = lock.newCondition();
+ this.isShutdown = false;
+ }
+
+ public boolean put(T item) throws InterruptedException {
+ return put(item, -1);
+ }
+
+ public boolean put(T item, long timeoutMillis) throws InterruptedException {
+ if (item == null) throw new NullPointerException();
+
+ lock.lock();
+ try {
+ // Wait until buffer is not full or shutdown
+ while (count == capacity && !isShutdown) {
+ if (timeoutMillis <= 0) {
+ notFull.await();
+ } else {
+ if (!notFull.await(timeoutMillis, java.util.concurrent.TimeUnit.MILLISECONDS)) {
+ return false;
+ }
+ }
+ }
+
+ if (isShutdown) return false;
+
+ buffer[tail] = item;
+ tail = (tail + 1) % capacity;
+ count++;
+ notEmpty.signal();
+... truncated ...
+ lock.lock();
+ try {
+ return count;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ public boolean isEmpty() {
+ lock.lock();
+ try {
+ return count == 0;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ public boolean isFull() {
+ lock.lock();
+ try {
+ return count == capacity;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ public void shutdown() {
+ lock.lock();
+ try {
+ isShutdown = true;
+ notEmpty.signalAll();
+ notFull.signalAll();
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ public void clear() {
+ lock.lock();
+ try {
+ for (int i = 0; i < capacity; i++) {
+ buffer[i] = null;
+ }
+ head = tail = count = 0;
+ notFull.signalAll();
+ } finally {
+ lock.unlock();
+ }
+ }
+}",175,101
+,"public class VowelswithStar
+{
+
+public static void main(String[] args)
+{
+String string = ""Welcome to Candid Java Programming""; //Input String
+System.out.println(""Input String : ""+string); //Displaying Input String
+string = string.replaceAll(""[AaEeIiOoUu]"", ""*""); //Replace vowels with star
+System.out.println(string); //Display the word after replacement
+}
+}
",0.0,IPSGWALIOR.ORG,,JAVA,"public class VowelswithStar
+{
+
+public static void main(String[] args)
+{
+String string = ""Welcome to Candid Java Programming""; //Input String
+System.out.println(""Input String : ""+string); //Displaying Input String
+string = string.replaceAll(""[AaEeIiOoUu]"", ""*""); //Replace vowels with star
+System.out.println(string); //Display the word after replacement
+}
+}",11,11
+,"import java.util.concurrent.atomic.AtomicReference;
+import java.util.concurrent.atomic.AtomicInteger;
+
+public class NonBlockingStack {
+ private static class Node {
+ final T value;
+ Node next;
+
+ Node(T value) {
+ this.value = value;
+ }
+ }
+
+ private final AtomicReference> top = new AtomicReference<>();
+ private final AtomicInteger size = new AtomicInteger(0);
+ private final AtomicInteger operationCount = new AtomicInteger(0);
+
+ public void push(T value) {
+ Node newHead = new Node<>(value);
+ Node oldHead;
+
+ do {
+ oldHead = top.get();
+ newHead.next = oldHead;
+ } while (!top.compareAndSet(oldHead, newHead));
+
+ size.incrementAndGet();
+ operationCount.incrementAndGet();
+ }
+
+ public T pop() {
+ Node oldHead;
+ Node newHead;
+
+ do {
+ oldHead = top.get();
+ if (oldHead == null) {
+ return null;
+ }
+ newHead = oldHead.next;
+ } while (!top.compareAndSet(oldHead, newHead));
+
+ size.decrementAndGet();
+ operationCount.incrementAndGet();
+ return oldHead.value;
+ }
+
+ public T peek() {
+ Node currentTop = top.get();
+ return currentTop != null ? currentTop.value : null;
+ }
+
+ public boolean isEmpty() {
+ return top.get() == null;
+ }
+
+ public int size() {
+ return size.get();
+ }
+
+ public int getOperationCount() {
+ return operationCount.get();
+ }
+
+ // Optimistic traversal for size (not thread-safe for exact count)
+ public int optimisticSize() {
+ int count = 0;
+ Node current = top.get();
+ while (current != null) {
+ count++;
+ current = current.next;
+ }
+ return count;
+ }
+}",1.0,DEEPSEEK,Implement a thread-safe non-blocking stack using atomic operations (Treiber's algorithm).,JAVA,"import java.util.concurrent.atomic.AtomicReference;
+import java.util.concurrent.atomic.AtomicInteger;
+
+public class NonBlockingStack {
+ private static class Node {
+ final T value;
+ Node next;
+
+ Node(T value) {
+ this.value = value;
+ }
+ }
+
+ private final AtomicReference> top = new AtomicReference<>();
+ private final AtomicInteger size = new AtomicInteger(0);
+ private final AtomicInteger operationCount = new AtomicInteger(0);
+
+ public void push(T value) {
+ Node newHead = new Node<>(value);
+ Node oldHead;
+
+ do {
+ oldHead = top.get();
+ newHead.next = oldHead;
+ } while (!top.compareAndSet(oldHead, newHead));
+
+ size.incrementAndGet();
+ operationCount.incrementAndGet();
+ }
+
+ public T pop() {
+ Node oldHead;
+ Node newHead;
+
+ do {
+ oldHead = top.get();
+ if (oldHead == null) {
+ return null;
+ }
+ newHead = oldHead.next;
+ } while (!top.compareAndSet(oldHead, newHead));
+
+ size.decrementAndGet();
+ operationCount.incrementAndGet();
+ return oldHead.value;
+ }
+
+ public T peek() {
+ Node currentTop = top.get();
+ return currentTop != null ? currentTop.value : null;
+ }
+
+ public boolean isEmpty() {
+ return top.get() == null;
+ }
+
+ public int size() {
+ return size.get();
+ }
+
+ public int getOperationCount() {
+ return operationCount.get();
+ }
+
+ // Optimistic traversal for size (not thread-safe for exact count)
+ public int optimisticSize() {
+ int count = 0;
+ Node current = top.get();
+ while (current != null) {
+ count++;
+ current = current.next;
+ }
+ return count;
+ }
+}",75,75
+,"public class LetterPositionCount
+ {
+
+ public static void main(String args[])
+ {
+
+ String s = ""CANDIDJAVA"";
+ char[] a = s.toCharArray();
+ int i = 1;
+ {
+ for (char output : a)
+ {
+
+ System.out.print(output + "" "" + i + "" "");
+ i++;
+
+ }
+ }
+
+ }
+ }
",0.0,IPSGWALIOR.ORG,,JAVA,"public class LetterPositionCount
+ {
+
+ public static void main(String args[])
+ {
+
+ String s = ""CANDIDJAVA"";
+ char[] a = s.toCharArray();
+ int i = 1;
+ {
+ for (char output : a)
+ {
+
+ System.out.print(output + "" "" + i + "" "");
+ i++;
+
+ }
+ }
+
+ }
+ }",21,21
+,"import java.util.concurrent.*;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.Condition;
+import java.util.concurrent.locks.ReentrantLock;
+
+public class CustomThreadPool {
+ private final BlockingQueue taskQueue;
+ private final WorkerThread[] workers;
+ private volatile boolean isShutdown;
+ private final ReentrantLock mainLock = new ReentrantLock();
+ private final Condition termination = mainLock.newCondition();
+ private final AtomicInteger activeWorkers = new AtomicInteger(0);
+ private final ThreadFactory threadFactory;
+
+ private class WorkerThread extends Thread {
+ private volatile Runnable currentTask;
+ private volatile boolean stopped;
+
+ public WorkerThread(String name) {
+ super(name);
+ }
+
+ @Override
+ public void run() {
+ activeWorkers.incrementAndGet();
+
+ try {
+ while (!stopped && !isShutdown) {
+ try {
+ // Poll with timeout to allow graceful shutdown
+ Runnable task = taskQueue.poll(100, TimeUnit.MILLISECONDS);
+
+ if (task != null) {
+ currentTask = task;
+ try {
+ task.run();
+ } catch (RuntimeException e) {
+ System.err.println(""Task execution failed: "" + e.getMessage());
+ } finally {
+ currentTask = null;
+ }
+ }
+ } catch (InterruptedException e) {
+ // Thread interrupted, check if we should exit
+ if (stopped || isShutdown) {
+ break;
+ }
+ }
+ }
+ } finally {
+ activeWorkers.decrementAndGet();
+ signalIfTerminated();
+ }
+ }
+
+ public void stopWorker() {
+ this.stopped = true;
+ this.interrupt();
+ }
+
+ public Runnable getCurrentTask() {
+ return currentTask;
+ }
+ }
+
+ public CustomThreadPool(int poolSize) {
+ this(poolSize, Executors.defaultThreadFactory());
+ }
+
+ public CustomThreadPool(int poolSize, ThreadFactory threadFactory) {
+ if (poolSize <= 0) {
+ throw new IllegalArgumentException(""Pool size must be positive"");
+ }
+
+ this.taskQueue = new LinkedBlockingQueue<>();
+ this.workers = new WorkerThread[poolSize];
+ this.threadFactory = threadFactory;
+ this.isShutdown = false;
+
+ // Initialize workers
+ for (int i = 0; i < poolSize; i++) {
+ WorkerThread worker = new WorkerThread(""CustomPool-Worker-"" + i);
+ workers[i] = worker;
+ worker.start();
+ }
+ }
+
+ public void execute(Runnable task) {
+ if (task == null) throw new NullPointerException();
+ if (isShutdown) throw new RejectedExecutionException(""Thread pool is shutdown"");
+
+ try {
+ taskQueue.put(task);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new RejectedExecutionException(""Interrupted while submitting task"", e);
+ }
+ }
+
+ public Future> submit(Runnable task) {
+ FutureTask future = new FutureTask<>(task, null);
+ execute(future);
+ return future;
+ }
+
+ public Future submit(Callable task) {
+ FutureTask future = new FutureTask<>(task);
+ execute(future);
+ return future;
+ }
+
+ public void shutdown() {
+ mainLock.lock();
+ try {
+ isShutdown = true;
+ } finally {
+ mainLock.unlock();
+ }
+ }
+
+ public void shutdownNow() {
+ mainLock.lock();
+ try {
+ isShutdown = true;
+
+ // Clear task queue
+ taskQueue.clear();
+
+ // Interrupt all workers
+ for (WorkerThread worker : workers) {
+ if (worker != null) {
+ worker.stopWorker();
+ }
+ }
+ } finally {
+ mainLock.unlock();
+ }
+ }
+
+ public boolean isShutdown() {
+ return isShutdown;
+ }
+
+ public boolean isTerminated() {
+ return isShutdown && activeWorkers.get() == 0 && taskQueue.isEmpty();
+ }
+
+ public boolean awaitTermination(long timeout, TimeUnit unit)
+ throws InterruptedException {
+ long nanos = unit.toNanos(timeout);
+ mainLock.lock();
+ try {
+ while (!isTerminated()) {
+ if (nanos <= 0) {
+ return false;
+ }
+ nanos = termination.awaitNanos(nanos);
+ }
+ return true;
+ } finally {
+ mainLock.unlock();
+ }
+ }
+
+ public int getActiveCount() {
+ return activeWorkers.get();
+ }
+
+ public int getPoolSize() {
+ return workers.length;
+ }
+
+ public long getTaskCount() {
+ return taskQueue.size();
+ }
+
+ private void signalIfTerminated() {
+ mainLock.lock();
+ try {
+ if (isTerminated()) {
+ termination.signalAll();
+ }
+ } finally {
+ mainLock.unlock();
+ }
+ }
+}",1.0,DEEPSEEK,"Implement a custom thread pool executor with fixed thread count, task queue, and shutdown capabilities.",JAVA,"import java.util.concurrent.*;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.Condition;
+import java.util.concurrent.locks.ReentrantLock;
+
+public class CustomThreadPool {
+ private final BlockingQueue taskQueue;
+ private final WorkerThread[] workers;
+ private volatile boolean isShutdown;
+ private final ReentrantLock mainLock = new ReentrantLock();
+ private final Condition termination = mainLock.newCondition();
+ private final AtomicInteger activeWorkers = new AtomicInteger(0);
+ private final ThreadFactory threadFactory;
+
+ private class WorkerThread extends Thread {
+ private volatile Runnable currentTask;
+ private volatile boolean stopped;
+
+ public WorkerThread(String name) {
+ super(name);
+ }
+
+ @Override
+ public void run() {
+ activeWorkers.incrementAndGet();
+
+ try {
+ while (!stopped && !isShutdown) {
+ try {
+ // Poll with timeout to allow graceful shutdown
+ Runnable task = taskQueue.poll(100, TimeUnit.MILLISECONDS);
+
+ if (task != null) {
+ currentTask = task;
+ try {
+ task.run();
+ } catch (RuntimeException e) {
+ System.err.println(""Task execution failed: "" + e.getMessage());
+ } finally {
+ currentTask = null;
+ }
+ }
+ } catch (InterruptedException e) {
+ // Thread interrupted, check if we should exit
+ if (stopped || isShutdown) {
+ break;
+ }
+ }
+ }
+ } finally {
+... truncated ...
+ }
+
+ public boolean isShutdown() {
+ return isShutdown;
+ }
+
+ public boolean isTerminated() {
+ return isShutdown && activeWorkers.get() == 0 && taskQueue.isEmpty();
+ }
+
+ public boolean awaitTermination(long timeout, TimeUnit unit)
+ throws InterruptedException {
+ long nanos = unit.toNanos(timeout);
+ mainLock.lock();
+ try {
+ while (!isTerminated()) {
+ if (nanos <= 0) {
+ return false;
+ }
+ nanos = termination.awaitNanos(nanos);
+ }
+ return true;
+ } finally {
+ mainLock.unlock();
+ }
+ }
+
+ public int getActiveCount() {
+ return activeWorkers.get();
+ }
+
+ public int getPoolSize() {
+ return workers.length;
+ }
+
+ public long getTaskCount() {
+ return taskQueue.size();
+ }
+
+ private void signalIfTerminated() {
+ mainLock.lock();
+ try {
+ if (isTerminated()) {
+ termination.signalAll();
+ }
+ } finally {
+ mainLock.unlock();
+ }
+ }
+}",187,101
+,"public class ReverseWord
+{
+public static void main(String[] args)
+{
+String input=""Welcome to Java Session"";
+String[] words=input.split("" "");
+String[] revwords=new String[words.length];
+int j=0;
+for(int i=words.length-1;i>=0;i--)
+ {
+revwords[j]=words[i];
+ System.out.print(revwords[j]+"" "");
+j++;
+}
+}
+
+}",0.0,IPSGWALIOR.ORG,,JAVA,"public class ReverseWord
+{
+public static void main(String[] args)
+{
+String input=""Welcome to Java Session"";
+String[] words=input.split("" "");
+String[] revwords=new String[words.length];
+int j=0;
+for(int i=words.length-1;i>=0;i--)
+ {
+revwords[j]=words[i];
+ System.out.print(revwords[j]+"" "");
+j++;
+}
+}
+
+}",17,17
+,"import java.util.concurrent.locks.AbstractQueuedSynchronizer;
+import java.util.concurrent.locks.Condition;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReadWriteLock;
+
+public class WriterPreferenceReadWriteLock implements ReadWriteLock {
+ private final Sync sync;
+
+ public WriterPreferenceReadWriteLock() {
+ this.sync = new Sync();
+ }
+
+ private static class Sync extends AbstractQueuedSynchronizer {
+ private static final int READER_MASK = (1 << 16) - 1;
+ private static final int WRITER_MASK = ~READER_MASK;
+
+ private int readers() {
+ return getState() & READER_MASK;
+ }
+
+ private int writers() {
+ return (getState() >>> 16) & READER_MASK;
+ }
+
+ private int incrementReaders() {
+ return getState() + 1;
+ }
+
+ private int decrementReaders() {
+ return getState() - 1;
+ }
+
+ private int incrementWriters() {
+ return getState() + (1 << 16);
+ }
+
+ private int decrementWriters() {
+ return getState() - (1 << 16);
+ }
+
+ @Override
+ protected boolean tryAcquire(int arg) {
+ Thread current = Thread.currentThread();
+ int state = getState();
+
+ // If no readers or writers, try to acquire write lock
+ if (state == 0) {
+ if (compareAndSetState(0, 1 << 16)) {
+ setExclusiveOwnerThread(current);
+ return true;
+ }
+ } else if (getExclusiveOwnerThread() == current) {
+ // Reentrant write lock
+ setState(state + (1 << 16));
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ protected boolean tryRelease(int arg) {
+ if (getExclusiveOwnerThread() != Thread.currentThread()) {
+ throw new IllegalMonitorStateException();
+ }
+
+ int newState = decrementWriters();
+ boolean free = (newState & WRITER_MASK) == 0;
+
+ if (free) {
+ setExclusiveOwnerThread(null);
+ }
+ setState(newState);
+ return free;
+ }
+
+ @Override
+ protected int tryAcquireShared(int arg) {
+ Thread current = Thread.currentThread();
+ int state = getState();
+
+ // If there are waiting writers, don't acquire read lock
+ if (hasQueuedPredecessors()) {
+ return -1;
+ }
+
+ // If no writers, try to acquire read lock
+ if ((state & WRITER_MASK) == 0) {
+ if (compareAndSetState(state, incrementReaders())) {
+ return 1;
+ }
+ }
+ return -1;
+ }
+
+ @Override
+ protected boolean tryReleaseShared(int arg) {
+ int newState;
+ int currentState;
+
+ do {
+ currentState = getState();
+ newState = decrementReaders();
+ } while (!compareAndSetState(currentState, newState));
+
+ return true;
+ }
+
+ @Override
+ protected boolean isHeldExclusively() {
+ return getExclusiveOwnerThread() == Thread.currentThread();
+ }
+
+ Condition newCondition() {
+ return new ConditionObject();
+ }
+ }
+
+ private static class ReadLock implements Lock {
+ private final Sync sync;
+
+ ReadLock(Sync sync) {
+ this.sync = sync;
+ }
+
+ @Override
+ public void lock() {
+ sync.acquireShared(1);
+ }
+
+ @Override
+ public void lockInterruptibly() throws InterruptedException {
+ sync.acquireSharedInterruptibly(1);
+ }
+
+ @Override
+ public boolean tryLock() {
+ return sync.tryAcquireShared(1) >= 0;
+ }
+
+ @Override
+ public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
+ return sync.tryAcquireSharedNanos(1, unit.toNanos(time));
+ }
+
+ @Override
+ public void unlock() {
+ sync.releaseShared(1);
+ }
+
+ @Override
+ public Condition newCondition() {
+ throw new UnsupportedOperationException(""Read locks don't support conditions"");
+ }
+ }
+
+ private static class WriteLock implements Lock {
+ private final Sync sync;
+
+ WriteLock(Sync sync) {
+ this.sync = sync;
+ }
+
+ @Override
+ public void lock() {
+ sync.acquire(1);
+ }
+
+ @Override
+ public void lockInterruptibly() throws InterruptedException {
+ sync.acquireInterruptibly(1);
+ }
+
+ @Override
+ public boolean tryLock() {
+ return sync.tryAcquire(1);
+ }
+
+ @Override
+ public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
+ return sync.tryAcquireNanos(1, unit.toNanos(time));
+ }
+
+ @Override
+ public void unlock() {
+ sync.release(1);
+ }
+
+ @Override
+ public Condition newCondition() {
+ return sync.newCondition();
+ }
+ }
+
+ @Override
+ public Lock readLock() {
+ return new ReadLock(sync);
+ }
+
+ @Override
+ public Lock writeLock() {
+ return new WriteLock(sync);
+ }
+}",1.0,DEEPSEEK,Implement a read-write lock that gives preference to writers to prevent writer starvation.,JAVA,"import java.util.concurrent.locks.AbstractQueuedSynchronizer;
+import java.util.concurrent.locks.Condition;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReadWriteLock;
+
+public class WriterPreferenceReadWriteLock implements ReadWriteLock {
+ private final Sync sync;
+
+ public WriterPreferenceReadWriteLock() {
+ this.sync = new Sync();
+ }
+
+ private static class Sync extends AbstractQueuedSynchronizer {
+ private static final int READER_MASK = (1 << 16) - 1;
+ private static final int WRITER_MASK = ~READER_MASK;
+
+ private int readers() {
+ return getState() & READER_MASK;
+ }
+
+ private int writers() {
+ return (getState() >>> 16) & READER_MASK;
+ }
+
+ private int incrementReaders() {
+ return getState() + 1;
+ }
+
+ private int decrementReaders() {
+ return getState() - 1;
+ }
+
+ private int incrementWriters() {
+ return getState() + (1 << 16);
+ }
+
+ private int decrementWriters() {
+ return getState() - (1 << 16);
+ }
+
+ @Override
+ protected boolean tryAcquire(int arg) {
+ Thread current = Thread.currentThread();
+ int state = getState();
+
+ // If no readers or writers, try to acquire write lock
+ if (state == 0) {
+ if (compareAndSetState(0, 1 << 16)) {
+ setExclusiveOwnerThread(current);
+ return true;
+... truncated ...
+ }
+
+ private static class WriteLock implements Lock {
+ private final Sync sync;
+
+ WriteLock(Sync sync) {
+ this.sync = sync;
+ }
+
+ @Override
+ public void lock() {
+ sync.acquire(1);
+ }
+
+ @Override
+ public void lockInterruptibly() throws InterruptedException {
+ sync.acquireInterruptibly(1);
+ }
+
+ @Override
+ public boolean tryLock() {
+ return sync.tryAcquire(1);
+ }
+
+ @Override
+ public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
+ return sync.tryAcquireNanos(1, unit.toNanos(time));
+ }
+
+ @Override
+ public void unlock() {
+ sync.release(1);
+ }
+
+ @Override
+ public Condition newCondition() {
+ return sync.newCondition();
+ }
+ }
+
+ @Override
+ public Lock readLock() {
+ return new ReadLock(sync);
+ }
+
+ @Override
+ public Lock writeLock() {
+ return new WriteLock(sync);
+ }
+}",203,101
+,"public class StringReverse {
+
+ public static void main(String args[])
+ {
+ String string = ""Welcome to Java Programming and Dotnet Programming"";
+ String[] wordsCount = string.split("" "");
+
+ System.out.println(""The Given String is:\n"" + string + ""\n"");
+ System.out.println(""After Reverse String is:"");
+
+ for(int i = wordsCount.length;i > 0;i--)
+ {
+ System.out.print(wordsCount[i - 1] + "" "");
+ }
+ }
+ }",0.0,IPSGWALIOR.ORG,,JAVA,"public class StringReverse {
+
+ public static void main(String args[])
+ {
+ String string = ""Welcome to Java Programming and Dotnet Programming"";
+ String[] wordsCount = string.split("" "");
+
+ System.out.println(""The Given String is:\n"" + string + ""\n"");
+ System.out.println(""After Reverse String is:"");
+
+ for(int i = wordsCount.length;i > 0;i--)
+ {
+ System.out.print(wordsCount[i - 1] + "" "");
+ }
+ }
+ }",16,16
+,"import java.util.*;
+import java.util.concurrent.*;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.ReentrantLock;
+
+public class DistributedTaskScheduler {
+ private final ExecutorService executor;
+ private final List workerNodes;
+ private final Map tasks;
+ private final AtomicInteger taskIdCounter;
+ private final ReentrantLock lock;
+ private final ScheduledExecutorService healthCheckScheduler;
+
+ public static class WorkerNode {
+ private final String id;
+ private final String host;
+ private final int port;
+ private volatile boolean healthy;
+ private volatile long lastHeartbeat;
+
+ public WorkerNode(String id, String host, int port) {
+ this.id = id;
+ this.host = host;
+ this.port = port;
+ this.healthy = true;
+ this.lastHeartbeat = System.currentTimeMillis();
+ }
+
+ // Getters and setters
+ public String getId() { return id; }
+ public String getHost() { return host; }
+ public int getPort() { return port; }
+ public boolean isHealthy() { return healthy; }
+ public void setHealthy(boolean healthy) { this.healthy = healthy; }
+ public long getLastHeartbeat() { return lastHeartbeat; }
+ public void updateHeartbeat() { this.lastHeartbeat = System.currentTimeMillis(); }
+ }
+
+ public static class ScheduledTask {
+ private final String id;
+ private final Runnable task;
+ private final long initialDelay;
+ private final long period;
+ private final TimeUnit timeUnit;
+ private volatile TaskStatus status;
+ private volatile String assignedWorker;
+ private volatile Future> future;
+
+ public ScheduledTask(String id, Runnable task, long initialDelay,
+ long period, TimeUnit timeUnit) {
+ this.id = id;
+ this.task = task;
+ this.initialDelay = initialDelay;
+ this.period = period;
+ this.timeUnit = timeUnit;
+ this.status = TaskStatus.PENDING;
+ }
+
+ public enum TaskStatus {
+ PENDING, SCHEDULED, RUNNING, COMPLETED, FAILED, CANCELLED
+ }
+
+ // Getters and setters
+ public String getId() { return id; }
+ public Runnable getTask() { return task; }
+ public long getInitialDelay() { return initialDelay; }
+ public long getPeriod() { return period; }
+ public TimeUnit getTimeUnit() { return timeUnit; }
+ public TaskStatus getStatus() { return status; }
+ public void setStatus(TaskStatus status) { this.status = status; }
+ public String getAssignedWorker() { return assignedWorker; }
+ public void setAssignedWorker(String workerId) { this.assignedWorker = workerId; }
+ public Future> getFuture() { return future; }
+ public void setFuture(Future> future) { this.future = future; }
+ }
+
+ public DistributedTaskScheduler(int corePoolSize) {
+ this.executor = Executors.newFixedThreadPool(corePoolSize);
+ this.workerNodes = new CopyOnWriteArrayList<>();
+ this.tasks = new ConcurrentHashMap<>();
+ this.taskIdCounter = new AtomicInteger(0);
+ this.lock = new ReentrantLock();
+ this.healthCheckScheduler = Executors.newScheduledThreadPool(1);
+
+ // Start health check
+ startHealthCheck();
+ }
+
+ private void startHealthCheck() {
+ healthCheckScheduler.scheduleAtFixedRate(() -> {
+ checkWorkerHealth();
+ reassignFailedTasks();
+ }, 30, 30, TimeUnit.SECONDS);
+ }
+
+ private void checkWorkerHealth() {
+ long currentTime = System.currentTimeMillis();
+ long threshold = currentTime - 60000; // 1 minute timeout
+
+ for (WorkerNode worker : workerNodes) {
+ if (worker.getLastHeartbeat() < threshold) {
+ worker.setHealthy(false);
+ System.err.println(""Worker "" + worker.getId() + "" marked as unhealthy"");
+ }
+ }
+ }
+
+ private void reassignFailedTasks() {
+ lock.lock();
+ try {
+ for (ScheduledTask task : tasks.values()) {
+ if (task.getStatus() == ScheduledTask.TaskStatus.RUNNING) {
+ WorkerNode assignedWorker = findWorkerById(task.getAssignedWorker());
+ if (assignedWorker == null || !assignedWorker.isHealthy()) {
+ // Task is running on failed worker, reschedule
+ rescheduleTask(task);
+ }
+ }
+ }
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ private void rescheduleTask(ScheduledTask task) {
+ task.setStatus(ScheduledTask.TaskStatus.PENDING);
+ task.setAssignedWorker(null);
+ if (task.getFuture() != null) {
+ task.getFuture().cancel(false);
+ }
+
+ scheduleTask(task);
+ }
+
+ private WorkerNode findWorkerById(String workerId) {
+ if (workerId == null) return null;
+
+ for (WorkerNode worker : workerNodes) {
+ if (worker.getId().equals(workerId)) {
+ return worker;
+ }
+ }
+ return null;
+ }
+
+ public void registerWorker(WorkerNode worker) {
+ workerNodes.add(worker);
+ System.out.println(""Registered worker: "" + worker.getId());
+ }
+
+ public void unregisterWorker(String workerId) {
+ workerNodes.removeIf(worker -> worker.getId().equals(workerId));
+
+ // Reassign tasks from removed worker
+ reassignFailedTasks();
+ }
+
+ public String scheduleTask(Runnable task, long initialDelay,
+ long period, TimeUnit unit) {
+ String taskId = ""task-"" + taskIdCounter.incrementAndGet();
+ ScheduledTask scheduledTask = new ScheduledTask(taskId, task,
+ initialDelay, period, unit);
+
+ tasks.put(taskId, scheduledTask);
+ scheduleTask(scheduledTask);
+
+ return taskId;
+ }
+
+ private void scheduleTask(ScheduledTask scheduledTask) {
+ WorkerNode worker = selectWorker();
+ if (worker == null)",1.0,DEEPSEEK,Design a task scheduler that can distribute tasks across multiple worker nodes and handle failures.,JAVA,"import java.util.*;
+import java.util.concurrent.*;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.ReentrantLock;
+
+public class DistributedTaskScheduler {
+ private final ExecutorService executor;
+ private final List workerNodes;
+ private final Map tasks;
+ private final AtomicInteger taskIdCounter;
+ private final ReentrantLock lock;
+ private final ScheduledExecutorService healthCheckScheduler;
+
+ public static class WorkerNode {
+ private final String id;
+ private final String host;
+ private final int port;
+ private volatile boolean healthy;
+ private volatile long lastHeartbeat;
+
+ public WorkerNode(String id, String host, int port) {
+ this.id = id;
+ this.host = host;
+ this.port = port;
+ this.healthy = true;
+ this.lastHeartbeat = System.currentTimeMillis();
+ }
+
+ // Getters and setters
+ public String getId() { return id; }
+ public String getHost() { return host; }
+ public int getPort() { return port; }
+ public boolean isHealthy() { return healthy; }
+ public void setHealthy(boolean healthy) { this.healthy = healthy; }
+ public long getLastHeartbeat() { return lastHeartbeat; }
+ public void updateHeartbeat() { this.lastHeartbeat = System.currentTimeMillis(); }
+ }
+
+ public static class ScheduledTask {
+ private final String id;
+ private final Runnable task;
+ private final long initialDelay;
+ private final long period;
+ private final TimeUnit timeUnit;
+ private volatile TaskStatus status;
+ private volatile String assignedWorker;
+ private volatile Future> future;
+
+ public ScheduledTask(String id, Runnable task, long initialDelay,
+ long period, TimeUnit timeUnit) {
+... truncated ...
+ }
+
+ private void rescheduleTask(ScheduledTask task) {
+ task.setStatus(ScheduledTask.TaskStatus.PENDING);
+ task.setAssignedWorker(null);
+ if (task.getFuture() != null) {
+ task.getFuture().cancel(false);
+ }
+
+ scheduleTask(task);
+ }
+
+ private WorkerNode findWorkerById(String workerId) {
+ if (workerId == null) return null;
+
+ for (WorkerNode worker : workerNodes) {
+ if (worker.getId().equals(workerId)) {
+ return worker;
+ }
+ }
+ return null;
+ }
+
+ public void registerWorker(WorkerNode worker) {
+ workerNodes.add(worker);
+ System.out.println(""Registered worker: "" + worker.getId());
+ }
+
+ public void unregisterWorker(String workerId) {
+ workerNodes.removeIf(worker -> worker.getId().equals(workerId));
+
+ // Reassign tasks from removed worker
+ reassignFailedTasks();
+ }
+
+ public String scheduleTask(Runnable task, long initialDelay,
+ long period, TimeUnit unit) {
+ String taskId = ""task-"" + taskIdCounter.incrementAndGet();
+ ScheduledTask scheduledTask = new ScheduledTask(taskId, task,
+ initialDelay, period, unit);
+
+ tasks.put(taskId, scheduledTask);
+ scheduleTask(scheduledTask);
+
+ return taskId;
+ }
+
+ private void scheduleTask(ScheduledTask scheduledTask) {
+ WorkerNode worker = selectWorker();
+ if (worker == null)",172,101
+,"import java.util.Scanner;
+class MinMaxInArray
+{
+int getMax(int[]inputArray)
+{
+int maxValue=inputArray[0];
+for(int i=1;imaxValue)
+{
+maxValue=inputArray[i];
+}
+}
+return maxValue;
+}
+int getMin(int[]inputArray)
+{
+int minValue=inputArray[0];
+for(int i=1;imaxValue)
+{
+maxValue=inputArray[i];
+}
+}
+return maxValue;
+}
+int getMin(int[]inputArray)
+{
+int minValue=inputArray[0];
+for(int i=1;i userWindows;
+
+ private static class Window {
+ final ConcurrentLinkedQueue timestamps;
+ final AtomicInteger currentRequests;
+
+ Window() {
+ this.timestamps = new ConcurrentLinkedQueue<>();
+ this.currentRequests = new AtomicInteger(0);
+ }
+ }
+
+ public SlidingWindowRateLimiter(int maxRequests, long windowDuration, TimeUnit timeUnit) {
+ this.maxRequests = maxRequests;
+ this.windowMillis = timeUnit.toMillis(windowDuration);
+ this.userWindows = new ConcurrentHashMap<>();
+ }
+
+ public boolean allowRequest(String userId) {
+ Window window = userWindows.computeIfAbsent(userId, k -> new Window());
+ long currentTime = System.currentTimeMillis();
+ long cutoffTime = currentTime - windowMillis;
+
+ // Clean old timestamps
+ while (!window.timestamps.isEmpty() &&
+ window.timestamps.peek() < cutoffTime) {
+ window.timestamps.poll();
+ window.currentRequests.decrementAndGet();
+ }
+
+ // Check if under limit
+ if (window.currentRequests.get() >= maxRequests) {
+ return false;
+ }
+
+ // Add new request
+ window.timestamps.offer(currentTime);
+ window.currentRequests.incrementAndGet();
+ return true;
+ }
+
+ public void reset(String userId) {
+ userWindows.remove(userId);
+ }
+}",1.0,DEEPSEEK,Create a rate limiter that allows N requests per minute with sliding window algorithm.,JAVA,"import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+public class SlidingWindowRateLimiter {
+ private final int maxRequests;
+ private final long windowMillis;
+ private final ConcurrentHashMap userWindows;
+
+ private static class Window {
+ final ConcurrentLinkedQueue timestamps;
+ final AtomicInteger currentRequests;
+
+ Window() {
+ this.timestamps = new ConcurrentLinkedQueue<>();
+ this.currentRequests = new AtomicInteger(0);
+ }
+ }
+
+ public SlidingWindowRateLimiter(int maxRequests, long windowDuration, TimeUnit timeUnit) {
+ this.maxRequests = maxRequests;
+ this.windowMillis = timeUnit.toMillis(windowDuration);
+ this.userWindows = new ConcurrentHashMap<>();
+ }
+
+ public boolean allowRequest(String userId) {
+ Window window = userWindows.computeIfAbsent(userId, k -> new Window());
+ long currentTime = System.currentTimeMillis();
+ long cutoffTime = currentTime - windowMillis;
+
+ // Clean old timestamps
+ while (!window.timestamps.isEmpty() &&
+ window.timestamps.peek() < cutoffTime) {
+ window.timestamps.poll();
+ window.currentRequests.decrementAndGet();
+ }
+
+ // Check if under limit
+ if (window.currentRequests.get() >= maxRequests) {
+ return false;
+ }
+
+ // Add new request
+ window.timestamps.offer(currentTime);
+ window.currentRequests.incrementAndGet();
+ return true;
+ }
+
+ public void reset(String userId) {
+ userWindows.remove(userId);
+ }
+}",53,53
+,"class NoOfOccurenceOfCharacters
+{
+ static final int MAX_CHAR = 256;
+ static void getOccuringChar(String str)
+ {
+ int count[] = new int[MAX_CHAR];
+ int len = str.length();
+ for (int i = 0; i < len; i++)
+ count[str.charAt(i)]++;
+ char ch[] = new char[str.length()];
+ for (int i = 0; i < len; i++) {
+ ch[i] = str.charAt(i);
+ int find = 0;
+ for (int j = 0; j <= i; j++) {
+ if (str.charAt(i) == ch[j])
+ find++;
+ }
+ if (find == 1)
+ System.out.println(""Number of Occurrence of "" +
+
+ str.charAt(i) + "" is:"" + count[str.charAt(i)]);
+ }
+ }
+ public static void main(String[] args)
+ {
+ Scanner sc = new Scanner(System.in);
+ String str = ""geeksforgeeks"";
+ getOccuringChar(str);
+ }
+}",0.0,IPSGWALIOR.ORG,,JAVA,"class NoOfOccurenceOfCharacters
+{
+ static final int MAX_CHAR = 256;
+ static void getOccuringChar(String str)
+ {
+ int count[] = new int[MAX_CHAR];
+ int len = str.length();
+ for (int i = 0; i < len; i++)
+ count[str.charAt(i)]++;
+ char ch[] = new char[str.length()];
+ for (int i = 0; i < len; i++) {
+ ch[i] = str.charAt(i);
+ int find = 0;
+ for (int j = 0; j <= i; j++) {
+ if (str.charAt(i) == ch[j])
+ find++;
+ }
+ if (find == 1)
+ System.out.println(""Number of Occurrence of "" +
+
+ str.charAt(i) + "" is:"" + count[str.charAt(i)]);
+ }
+ }
+ public static void main(String[] args)
+ {
+ Scanner sc = new Scanner(System.in);
+ String str = ""geeksforgeeks"";
+ getOccuringChar(str);
+ }
+}",30,30
+,"import java.time.Duration;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Predicate;
+
+public class RetryExecutor {
+ private final int maxAttempts;
+ private final Duration initialDelay;
+ private final Duration maxDelay;
+ private final double backoffMultiplier;
+ private final Predicate retryPredicate;
+
+ private RetryExecutor(Builder builder) {
+ this.maxAttempts = builder.maxAttempts;
+ this.initialDelay = builder.initialDelay;
+ this.maxDelay = builder.maxDelay;
+ this.backoffMultiplier = builder.backoffMultiplier;
+ this.retryPredicate = builder.retryPredicate;
+ }
+
+ public T execute(Callable task) throws Exception {
+ Exception lastException = null;
+ Duration currentDelay = initialDelay;
+
+ for (int attempt = 1; attempt <= maxAttempts; attempt++) {
+ try {
+ return task.call();
+ } catch (Exception e) {
+ lastException = e;
+
+ if (attempt == maxAttempts || !shouldRetry(e)) {
+ throw e;
+ }
+
+ if (attempt < maxAttempts) {
+ sleepWithJitter(currentDelay);
+ currentDelay = calculateNextDelay(currentDelay);
+ }
+ }
+ }
+
+ throw lastException;
+ }
+
+ private boolean shouldRetry(Exception e) {
+ return retryPredicate == null || retryPredicate.test(e);
+ }
+
+ private void sleepWithJitter(Duration delay) {
+ try {
+ long jitter = ThreadLocalRandom.current().nextLong(
+ (long) (delay.toMillis() * 0.1)
+ );
+ Thread.sleep(delay.toMillis() + jitter);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new RuntimeException(""Retry interrupted"", e);
+ }
+ }
+
+ private Duration calculateNextDelay(Duration currentDelay) {
+ long nextDelayMillis = (long) (currentDelay.toMillis() * backoffMultiplier);
+ if (nextDelayMillis > maxDelay.toMillis()) {
+ nextDelayMillis = maxDelay.toMillis();
+ }
+ return Duration.ofMillis(nextDelayMillis);
+ }
+
+ public static class Builder {
+ private int maxAttempts = 3;
+ private Duration initialDelay = Duration.ofMillis(100);
+ private Duration maxDelay = Duration.ofSeconds(30);
+ private double backoffMultiplier = 2.0;
+ private Predicate retryPredicate;
+
+ public Builder maxAttempts(int maxAttempts) {
+ this.maxAttempts = maxAttempts;
+ return this;
+ }
+
+ public Builder initialDelay(Duration initialDelay) {
+ this.initialDelay = initialDelay;
+ return this;
+ }
+
+ public Builder maxDelay(Duration maxDelay) {
+ this.maxDelay = maxDelay;
+ return this;
+ }
+
+ public Builder backoffMultiplier(double backoffMultiplier) {
+ this.backoffMultiplier = backoffMultiplier;
+ return this;
+ }
+
+ public Builder retryOn(Predicate retryPredicate) {
+ this.retryPredicate = retryPredicate;
+ return this;
+ }
+
+ public RetryExecutor build() {
+ return new RetryExecutor(this);
+ }
+ }
+}",1.0,DEEPSEEK,Create a retry mechanism that handles transient failures with exponential backoff.,JAVA,"import java.time.Duration;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Predicate;
+
+public class RetryExecutor {
+ private final int maxAttempts;
+ private final Duration initialDelay;
+ private final Duration maxDelay;
+ private final double backoffMultiplier;
+ private final Predicate retryPredicate;
+
+ private RetryExecutor(Builder builder) {
+ this.maxAttempts = builder.maxAttempts;
+ this.initialDelay = builder.initialDelay;
+ this.maxDelay = builder.maxDelay;
+ this.backoffMultiplier = builder.backoffMultiplier;
+ this.retryPredicate = builder.retryPredicate;
+ }
+
+ public T execute(Callable task) throws Exception {
+ Exception lastException = null;
+ Duration currentDelay = initialDelay;
+
+ for (int attempt = 1; attempt <= maxAttempts; attempt++) {
+ try {
+ return task.call();
+ } catch (Exception e) {
+ lastException = e;
+
+ if (attempt == maxAttempts || !shouldRetry(e)) {
+ throw e;
+ }
+
+ if (attempt < maxAttempts) {
+ sleepWithJitter(currentDelay);
+ currentDelay = calculateNextDelay(currentDelay);
+ }
+ }
+ }
+
+ throw lastException;
+ }
+
+ private boolean shouldRetry(Exception e) {
+ return retryPredicate == null || retryPredicate.test(e);
+ }
+
+ private void sleepWithJitter(Duration delay) {
+ try {
+... truncated ...
+ Thread.currentThread().interrupt();
+ throw new RuntimeException(""Retry interrupted"", e);
+ }
+ }
+
+ private Duration calculateNextDelay(Duration currentDelay) {
+ long nextDelayMillis = (long) (currentDelay.toMillis() * backoffMultiplier);
+ if (nextDelayMillis > maxDelay.toMillis()) {
+ nextDelayMillis = maxDelay.toMillis();
+ }
+ return Duration.ofMillis(nextDelayMillis);
+ }
+
+ public static class Builder {
+ private int maxAttempts = 3;
+ private Duration initialDelay = Duration.ofMillis(100);
+ private Duration maxDelay = Duration.ofSeconds(30);
+ private double backoffMultiplier = 2.0;
+ private Predicate retryPredicate;
+
+ public Builder maxAttempts(int maxAttempts) {
+ this.maxAttempts = maxAttempts;
+ return this;
+ }
+
+ public Builder initialDelay(Duration initialDelay) {
+ this.initialDelay = initialDelay;
+ return this;
+ }
+
+ public Builder maxDelay(Duration maxDelay) {
+ this.maxDelay = maxDelay;
+ return this;
+ }
+
+ public Builder backoffMultiplier(double backoffMultiplier) {
+ this.backoffMultiplier = backoffMultiplier;
+ return this;
+ }
+
+ public Builder retryOn(Predicate retryPredicate) {
+ this.retryPredicate = retryPredicate;
+ return this;
+ }
+
+ public RetryExecutor build() {
+ return new RetryExecutor(this);
+ }
+ }
+}",105,101
+,"// Define the Cat class
+public class Cat {
+ // Private instance variables
+ private String name;
+ private int age;
+ // Default constructor
+ public Cat() {
+ // Initialize name to ""Unknown""
+ this.name = ""Unknown"";
+ // Initialize age to 0
+ this.age = 0;
+ }
+ // Getter for name
+ public String getName() {
+ return name;
+ }
+ // Getter for age
+ public int getAge() {
+ return age;
+ }
+ // Main method to test the Cat class
+ public static void main(String[] args) {
+ // Create a new Cat object using the default constructor
+ Cat myCat = new Cat();
+ // Use the getter methods to access private variables
+ System.out.println(""Cat's Name: "" + myCat.getName());
+ System.out.println(""Cat's Age: "" + myCat.getAge());
+ }
+}
",0.0,WE3RESOURCE,,JAVA,"// Define the Cat class
+public class Cat {
+ // Private instance variables
+ private String name;
+ private int age;
+ // Default constructor
+ public Cat() {
+ // Initialize name to ""Unknown""
+ this.name = ""Unknown"";
+ // Initialize age to 0
+ this.age = 0;
+ }
+ // Getter for name
+ public String getName() {
+ return name;
+ }
+ // Getter for age
+ public int getAge() {
+ return age;
+ }
+ // Main method to test the Cat class
+ public static void main(String[] args) {
+ // Create a new Cat object using the default constructor
+ Cat myCat = new Cat();
+ // Use the getter methods to access private variables
+ System.out.println(""Cat's Name: "" + myCat.getName());
+ System.out.println(""Cat's Age: "" + myCat.getAge());
+ }
+}",29,29
+,"import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+public class DatabaseConnectionPool {
+ private final BlockingQueue availableConnections;
+ private final AtomicInteger activeConnections = new AtomicInteger(0);
+ private final int maxPoolSize;
+ private final String url;
+ private final String username;
+ private final String password;
+ private volatile boolean isClosed = false;
+
+ public DatabaseConnectionPool(String url, String username,
+ String password, int maxPoolSize) {
+ this.url = url;
+ this.username = username;
+ this.password = password;
+ this.maxPoolSize = maxPoolSize;
+ this.availableConnections = new LinkedBlockingQueue<>(maxPoolSize);
+ initializePool();
+ }
+
+ private void initializePool() {
+ for (int i = 0; i < maxPoolSize / 2; i++) {
+ try {
+ availableConnections.offer(createConnection());
+ } catch (SQLException e) {
+ throw new RuntimeException(""Failed to initialize connection pool"", e);
+ }
+ }
+ }
+
+ private PooledConnection createConnection() throws SQLException {
+ Connection connection = DriverManager.getConnection(url, username, password);
+ return new PooledConnection(connection, this);
+ }
+
+ public Connection getConnection() throws SQLException {
+ return getConnection(30, TimeUnit.SECONDS);
+ }
+
+ public Connection getConnection(long timeout, TimeUnit unit) throws SQLException {
+ if (isClosed) {
+ throw new SQLException(""Connection pool is closed"");
+ }
+
+ try {
+ // Try to get existing connection
+ PooledConnection pooledConn = availableConnections.poll(timeout, unit);
+ if (pooledConn != null) {
+ if (!pooledConn.getConnection().isValid(2)) {
+ closeQuietly(pooledConn.getConnection());
+ pooledConn = createConnection();
+ }
+ activeConnections.incrementAndGet();
+ return pooledConn;
+ }
+
+ // Create new connection if pool not full
+ if (activeConnections.get() < maxPoolSize) {
+ PooledConnection newConn = createConnection();
+ activeConnections.incrementAndGet();
+ return newConn;
+ }
+
+ throw new SQLException(""Connection pool exhausted"");
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new SQLException(""Interrupted while waiting for connection"");
+ }
+ }
+
+ void returnConnection(PooledConnection connection) {
+ if (isClosed) {
+ closeQuietly(connection.getConnection());
+ return;
+ }
+
+ try {
+ if (connection.getConnection().isClosed() ||
+ !connection.getConnection().isValid(2)) {
+ closeQuietly(connection.getConnection());
+ availableConnections.offer(createConnection());
+ } else {
+ availableConnections.offer(connection);
+ }
+ } catch (SQLException e) {
+ // Connection is invalid, create new one
+ closeQuietly(connection.getConnection());
+ try {
+ availableConnections.offer(createConnection());
+ } catch (SQLException ex) {
+ // Log error but don't throw
+ }
+ } finally {
+ activeConnections.decrementAndGet();
+ }
+ }
+
+ public void close() {
+ isClosed = true;
+ availableConnections.forEach(conn ->
+ closeQuietly(conn.getConnection())
+ );
+ availableConnections.clear();
+ }
+
+ public int getActiveConnections() {
+ return activeConnections.get();
+ }
+
+ public int getIdleConnections() {
+ return availableConnections.size();
+ }
+
+ private void closeQuietly(Connection connection) {
+ try {
+ if (connection != null && !connection.isClosed()) {
+ connection.close();
+ }
+ } catch (SQLException e) {
+ // Ignore
+ }
+ }
+
+ private class PooledConnection extends ConnectionWrapper {
+ private final DatabaseConnectionPool pool;
+
+ PooledConnection(Connection connection, DatabaseConnectionPool pool) {
+ super(connection);
+ this.pool = pool;
+ }
+
+ @Override
+ public void close() throws SQLException {
+ pool.returnConnection(this);
+ }
+ }
+
+ private abstract class ConnectionWrapper implements Connection {
+ protected final Connection delegate;
+
+ ConnectionWrapper(Connection delegate) {
+ this.delegate = delegate;
+ }
+
+ // Delegate all Connection methods to the wrapped connection
+ @Override
+ public Statement createStatement() throws SQLException {
+ return delegate.createStatement();
+ }
+
+ // ... implement all other Connection methods similarly
+
+ @Override
+ public boolean isWrapperFor(Class> iface) throws SQLException {
+ return iface.isInstance(delegate) || delegate.isWrapperFor(iface);
+ }
+
+ @SuppressWarnings(""unchecked"")
+ @Override
+ public T unwrap(Class iface) throws SQLException {
+ if (iface.isInstance(delegate)) {
+ return (T) delegate;
+ }
+ return delegate.unwrap(iface);
+ }
+ }
+}",1.0,DEEPSEEK,Create a generic connection pool for managing database connections.,JAVA,"import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+public class DatabaseConnectionPool {
+ private final BlockingQueue availableConnections;
+ private final AtomicInteger activeConnections = new AtomicInteger(0);
+ private final int maxPoolSize;
+ private final String url;
+ private final String username;
+ private final String password;
+ private volatile boolean isClosed = false;
+
+ public DatabaseConnectionPool(String url, String username,
+ String password, int maxPoolSize) {
+ this.url = url;
+ this.username = username;
+ this.password = password;
+ this.maxPoolSize = maxPoolSize;
+ this.availableConnections = new LinkedBlockingQueue<>(maxPoolSize);
+ initializePool();
+ }
+
+ private void initializePool() {
+ for (int i = 0; i < maxPoolSize / 2; i++) {
+ try {
+ availableConnections.offer(createConnection());
+ } catch (SQLException e) {
+ throw new RuntimeException(""Failed to initialize connection pool"", e);
+ }
+ }
+ }
+
+ private PooledConnection createConnection() throws SQLException {
+ Connection connection = DriverManager.getConnection(url, username, password);
+ return new PooledConnection(connection, this);
+ }
+
+ public Connection getConnection() throws SQLException {
+ return getConnection(30, TimeUnit.SECONDS);
+ }
+
+ public Connection getConnection(long timeout, TimeUnit unit) throws SQLException {
+ if (isClosed) {
+ throw new SQLException(""Connection pool is closed"");
+ }
+... truncated ...
+ }
+ } catch (SQLException e) {
+ // Ignore
+ }
+ }
+
+ private class PooledConnection extends ConnectionWrapper {
+ private final DatabaseConnectionPool pool;
+
+ PooledConnection(Connection connection, DatabaseConnectionPool pool) {
+ super(connection);
+ this.pool = pool;
+ }
+
+ @Override
+ public void close() throws SQLException {
+ pool.returnConnection(this);
+ }
+ }
+
+ private abstract class ConnectionWrapper implements Connection {
+ protected final Connection delegate;
+
+ ConnectionWrapper(Connection delegate) {
+ this.delegate = delegate;
+ }
+
+ // Delegate all Connection methods to the wrapped connection
+ @Override
+ public Statement createStatement() throws SQLException {
+ return delegate.createStatement();
+ }
+
+ // ... implement all other Connection methods similarly
+
+ @Override
+ public boolean isWrapperFor(Class> iface) throws SQLException {
+ return iface.isInstance(delegate) || delegate.isWrapperFor(iface);
+ }
+
+ @SuppressWarnings(""unchecked"")
+ @Override
+ public T unwrap(Class iface) throws SQLException {
+ if (iface.isInstance(delegate)) {
+ return (T) delegate;
+ }
+ return delegate.unwrap(iface);
+ }
+ }
+}",174,101
+,"// Define the Dog class
+public class Dog {
+ // Private instance variables
+ private String name;
+ private String color;
+
+ // Parameterized constructor
+ public Dog(String name, String color) {
+ // Initialize name with the provided parameter
+ this.name = name;
+ // Initialize color with the provided parameter
+ this.color = color;
+ }
+
+ // Main method to test the Dog class
+ public static void main(String[] args) {
+ // Create a new Dog object using the parameterized constructor
+ Dog myDog = new Dog(""Bailey"", ""Black"");
+ // Print the values of the instance variables
+ System.out.println(""Dog's Name: "" + myDog.name);
+ System.out.println(""Dog's Color: "" + myDog.color);
+ }
+}
",0.0,WE3RESOURCE,,JAVA,"// Define the Dog class
+public class Dog {
+ // Private instance variables
+ private String name;
+ private String color;
+
+ // Parameterized constructor
+ public Dog(String name, String color) {
+ // Initialize name with the provided parameter
+ this.name = name;
+ // Initialize color with the provided parameter
+ this.color = color;
+ }
+
+ // Main method to test the Dog class
+ public static void main(String[] args) {
+ // Create a new Dog object using the parameterized constructor
+ Dog myDog = new Dog(""Bailey"", ""Black"");
+ // Print the values of the instance variables
+ System.out.println(""Dog's Name: "" + myDog.name);
+ System.out.println(""Dog's Color: "" + myDog.color);
+ }
+}",23,23
+,"import java.time.Instant;
+import java.util.*;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.stream.Collectors;
+
+public class EventStore {
+ private final ConcurrentHashMap> streams;
+ private final ConcurrentHashMap streamVersions;
+
+ public EventStore() {
+ this.streams = new ConcurrentHashMap<>();
+ this.streamVersions = new ConcurrentHashMap<>();
+ }
+
+ public static class Event {
+ private final String eventId;
+ private final String streamId;
+ private final String eventType;
+ private final Map data;
+ private final Map metadata;
+ private final Instant timestamp;
+ private final long version;
+
+ public Event(String streamId, String eventType,
+ Map data, long version) {
+ this.eventId = UUID.randomUUID().toString();
+ this.streamId = streamId;
+ this.eventType = eventType;
+ this.data = Collections.unmodifiableMap(new HashMap<>(data));
+ this.metadata = new HashMap<>();
+ this.timestamp = Instant.now();
+ this.version = version;
+ }
+
+ // Getters
+ public String getEventId() { return eventId; }
+ public String getStreamId() { return streamId; }
+ public String getEventType() { return eventType; }
+ public Map getData() { return data; }
+ public Map getMetadata() { return metadata; }
+ public Instant getTimestamp() { return timestamp; }
+ public long getVersion() { return version; }
+
+ public void addMetadata(String key, Object value) {
+ metadata.put(key, value);
+ }
+ }
+
+ public AppendResult appendToStream(String streamId, List events,
+ long expectedVersion) {
+ if (events == null || events.isEmpty()) {
+ throw new IllegalArgumentException(""Events cannot be empty"");
+ }
+
+ streams.compute(streamId, (key, existingEvents) -> {
+ long currentVersion = streamVersions
+ .computeIfAbsent(streamId, k -> new AtomicLong(0))
+ .get();
+
+ // Optimistic concurrency check
+ if (expectedVersion != -1 && currentVersion != expectedVersion) {
+ throw new ConcurrencyException(
+ String.format(""Expected version %d but was %d"",
+ expectedVersion, currentVersion)
+ );
+ }
+
+ List streamEvents = existingEvents != null ?
+ new ArrayList<>(existingEvents) : new ArrayList<>();
+
+ // Assign versions to events
+ for (int i = 0; i < events.size(); i++) {
+ Event event = events.get(i);
+ Event versionedEvent = new Event(
+ streamId,
+ event.eventType,
+ event.data,
+ currentVersion + i + 1
+ );
+ event.metadata.forEach(versionedEvent::addMetadata);
+ streamEvents.add(versionedEvent);
+ }
+
+ // Update version
+ streamVersions.get(streamId).addAndGet(events.size());
+
+ return Collections.unmodifiableList(streamEvents);
+ });
+
+ return new AppendResult(streamId,
+ streamVersions.get(streamId).get(),
+ events.size()
+ );
+ }
+
+ public List readStream(String streamId) {
+ List events = streams.get(streamId);
+ return events != null ? new ArrayList<>(events) : new ArrayList<>();
+ }
+
+ public List readStream(String streamId, long fromVersion) {
+ List events = streams.get(streamId);
+ if (events == null) {
+ return new ArrayList<>();
+ }
+
+ return events.stream()
+ .filter(e -> e.getVersion() >= fromVersion)
+ .collect(Collectors.toList());
+ }
+
+ public List readAllEvents() {
+ return streams.values().stream()
+ .flatMap(List::stream)
+ .sorted(Comparator.comparing(Event::getTimestamp)
+ .thenComparing(Event::getVersion))
+ .collect(Collectors.toList());
+ }
+
+ public long getStreamVersion(String streamId) {
+ AtomicLong version = streamVersions.get(streamId);
+ return version != null ? version.get() : 0;
+ }
+
+ public void subscribe(EventSubscriber subscriber) {
+ // Implementation for event subscription
+ }
+
+ public static class AppendResult {
+ private final String streamId;
+ private final long newVersion;
+ private final int eventsAppended;
+
+ AppendResult(String streamId, long newVersion, int eventsAppended) {
+ this.streamId = streamId;
+ this.newVersion = newVersion;
+ this.eventsAppended = eventsAppended;
+ }
+
+ public String getStreamId() { return streamId; }
+ public long getNewVersion() { return newVersion; }
+ public int getEventsAppended() { return eventsAppended; }
+ }
+
+ public interface EventSubscriber {
+ void handle(Event event);
+ }
+
+ public static class ConcurrencyException extends RuntimeException {
+ public ConcurrencyException(String message) {
+ super(message);
+ }
+ }
+}",1.0,DEEPSEEK,Create an event store for CQRS pattern with optimistic concurrency control.,JAVA,"import java.time.Instant;
+import java.util.*;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.stream.Collectors;
+
+public class EventStore {
+ private final ConcurrentHashMap> streams;
+ private final ConcurrentHashMap streamVersions;
+
+ public EventStore() {
+ this.streams = new ConcurrentHashMap<>();
+ this.streamVersions = new ConcurrentHashMap<>();
+ }
+
+ public static class Event {
+ private final String eventId;
+ private final String streamId;
+ private final String eventType;
+ private final Map data;
+ private final Map metadata;
+ private final Instant timestamp;
+ private final long version;
+
+ public Event(String streamId, String eventType,
+ Map data, long version) {
+ this.eventId = UUID.randomUUID().toString();
+ this.streamId = streamId;
+ this.eventType = eventType;
+ this.data = Collections.unmodifiableMap(new HashMap<>(data));
+ this.metadata = new HashMap<>();
+ this.timestamp = Instant.now();
+ this.version = version;
+ }
+
+ // Getters
+ public String getEventId() { return eventId; }
+ public String getStreamId() { return streamId; }
+ public String getEventType() { return eventType; }
+ public Map getData() { return data; }
+ public Map getMetadata() { return metadata; }
+ public Instant getTimestamp() { return timestamp; }
+ public long getVersion() { return version; }
+
+ public void addMetadata(String key, Object value) {
+ metadata.put(key, value);
+ }
+ }
+
+ public AppendResult appendToStream(String streamId, List events,
+... truncated ...
+ }
+
+ return events.stream()
+ .filter(e -> e.getVersion() >= fromVersion)
+ .collect(Collectors.toList());
+ }
+
+ public List readAllEvents() {
+ return streams.values().stream()
+ .flatMap(List::stream)
+ .sorted(Comparator.comparing(Event::getTimestamp)
+ .thenComparing(Event::getVersion))
+ .collect(Collectors.toList());
+ }
+
+ public long getStreamVersion(String streamId) {
+ AtomicLong version = streamVersions.get(streamId);
+ return version != null ? version.get() : 0;
+ }
+
+ public void subscribe(EventSubscriber subscriber) {
+ // Implementation for event subscription
+ }
+
+ public static class AppendResult {
+ private final String streamId;
+ private final long newVersion;
+ private final int eventsAppended;
+
+ AppendResult(String streamId, long newVersion, int eventsAppended) {
+ this.streamId = streamId;
+ this.newVersion = newVersion;
+ this.eventsAppended = eventsAppended;
+ }
+
+ public String getStreamId() { return streamId; }
+ public long getNewVersion() { return newVersion; }
+ public int getEventsAppended() { return eventsAppended; }
+ }
+
+ public interface EventSubscriber {
+ void handle(Event event);
+ }
+
+ public static class ConcurrencyException extends RuntimeException {
+ public ConcurrencyException(String message) {
+ super(message);
+ }
+ }
+}",155,101
+,"// Define the Book class
+public class Book {
+ // Private instance variables
+ private String title;
+ private String author;
+ private double price;
+
+ // Default constructor
+ public Book() {
+ // Initialize title to ""Unknown""
+ this.title = ""Unknown"";
+ // Initialize author to ""Unknown""
+ this.author = ""Unknown"";
+ // Initialize price to 0.0
+ this.price = 0.0;
+ }
+
+ // Parameterized constructor (title, author)
+ public Book(String title, String author) {
+ // Initialize title with the provided parameter
+ this.title = title;
+ // Initialize author with the provided parameter
+ this.author = author;
+ // Initialize price to 0.0
+ this.price = 0.0;
+ }
+
+ // Parameterized constructor (title, author, price)
+ public Book(String title, String author, double price) {
+ // Initialize title with the provided parameter
+ this.title = title;
+ // Initialize author with the provided parameter
+ this.author = author;
+ // Initialize price with the provided parameter
+ this.price = price;
+ }
+
+ // Main method to test the Book class
+ public static void main(String[] args) {
+ // Create a new Book object using the default constructor
+ Book book1 = new Book();
+ // Print the values of the instance variables for book1
+ System.out.println(""Book1 Title: "" + book1.title);
+ System.out.println(""Book1 Author: "" + book1.author);
+ System.out.println(""Book1 Price: "" + book1.price);
+
+ // Create a new Book object using the parameterized constructor (title, author)
+ Book book2 = new Book(""Amatka"", ""Karin Tidbeck"");
+ // Print the values of the instance variables for book2
+ System.out.println(""Book2 Title: "" + book2.title);
+ System.out.println(""Book2 Author: "" + book2.author);
+ System.out.println(""Book2 Price: "" + book2.price);
+
+ // Create a new Book object using the parameterized constructor (title, author, price)
+ Book book3 = new Book(""Altered Carbon"", ""Richard K. Morgan"", 18.99);
+ // Print the values of the instance variables for book3
+ System.out.println(""Book3 Title: "" + book3.title);
+ System.out.println(""Book3 Author: "" + book3.author);
+ System.out.println(""Book3 Price: "" + book3.price);
+ }
+}
",0.0,WE3RESOURCE,,JAVA,"// Define the Book class
+public class Book {
+ // Private instance variables
+ private String title;
+ private String author;
+ private double price;
+
+ // Default constructor
+ public Book() {
+ // Initialize title to ""Unknown""
+ this.title = ""Unknown"";
+ // Initialize author to ""Unknown""
+ this.author = ""Unknown"";
+ // Initialize price to 0.0
+ this.price = 0.0;
+ }
+
+ // Parameterized constructor (title, author)
+ public Book(String title, String author) {
+ // Initialize title with the provided parameter
+ this.title = title;
+ // Initialize author with the provided parameter
+ this.author = author;
+ // Initialize price to 0.0
+ this.price = 0.0;
+ }
+
+ // Parameterized constructor (title, author, price)
+ public Book(String title, String author, double price) {
+ // Initialize title with the provided parameter
+ this.title = title;
+ // Initialize author with the provided parameter
+ this.author = author;
+ // Initialize price with the provided parameter
+ this.price = price;
+ }
+
+ // Main method to test the Book class
+ public static void main(String[] args) {
+ // Create a new Book object using the default constructor
+ Book book1 = new Book();
+ // Print the values of the instance variables for book1
+ System.out.println(""Book1 Title: "" + book1.title);
+ System.out.println(""Book1 Author: "" + book1.author);
+ System.out.println(""Book1 Price: "" + book1.price);
+
+ // Create a new Book object using the parameterized constructor (title, author)
+ Book book2 = new Book(""Amatka"", ""Karin Tidbeck"");
+ // Print the values of the instance variables for book2
+ System.out.println(""Book2 Title: "" + book2.title);
+ System.out.println(""Book2 Author: "" + book2.author);
+ System.out.println(""Book2 Price: "" + book2.price);
+
+ // Create a new Book object using the parameterized constructor (title, author, price)
+ Book book3 = new Book(""Altered Carbon"", ""Richard K. Morgan"", 18.99);
+ // Print the values of the instance variables for book3
+ System.out.println(""Book3 Title: "" + book3.title);
+ System.out.println(""Book3 Author: "" + book3.author);
+ System.out.println(""Book3 Price: "" + book3.price);
+ }
+}",61,61
+,"import java.time.Instant;
+import java.util.concurrent.atomic.AtomicLong;
+
+public class SnowflakeIdGenerator {
+ private static final long EPOCH = 1609459200000L; // 2021-01-01
+ private static final long WORKER_ID_BITS = 5L;
+ private static final long DATACENTER_ID_BITS = 5L;
+ private static final long SEQUENCE_BITS = 12L;
+
+ private static final long MAX_WORKER_ID = (1L << WORKER_ID_BITS) - 1;
+ private static final long MAX_DATACENTER_ID = (1L << DATACENTER_ID_BITS) - 1;
+ private static final long MAX_SEQUENCE = (1L << SEQUENCE_BITS) - 1;
+
+ private static final long WORKER_ID_SHIFT = SEQUENCE_BITS;
+ private static final long DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
+ private static final long TIMESTAMP_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS;
+
+ private final long workerId;
+ private final long datacenterId;
+ private final AtomicLong sequence = new AtomicLong(0);
+ private volatile long lastTimestamp = -1L;
+
+ public SnowflakeIdGenerator(long workerId, long datacenterId) {
+ if (workerId > MAX_WORKER_ID || workerId < 0) {
+ throw new IllegalArgumentException(
+ String.format(""Worker ID must be between 0 and %d"", MAX_WORKER_ID)
+ );
+ }
+ if (datacenterId > MAX_DATACENTER_ID || datacenterId < 0) {
+ throw new IllegalArgumentException(
+ String.format(""Datacenter ID must be between 0 and %d"", MAX_DATACENTER_ID)
+ );
+ }
+
+ this.workerId = workerId;
+ this.datacenterId = datacenterId;
+ }
+
+ public synchronized long nextId() {
+ long timestamp = currentTimestamp();
+
+ if (timestamp < lastTimestamp) {
+ throw new IllegalStateException(
+ String.format(""Clock moved backwards. Refusing to generate ID for %d milliseconds"",
+ lastTimestamp - timestamp)
+ );
+ }
+
+ if (timestamp == lastTimestamp) {
+ long currentSequence = (sequence.incrementAndGet() & MAX_SEQUENCE);
+ if (currentSequence == 0) {
+ // Sequence overflow, wait for next millisecond
+ timestamp = waitNextMillis(lastTimestamp);
+ }
+ } else {
+ sequence.set(0);
+ }
+
+ lastTimestamp = timestamp;
+
+ return ((timestamp - EPOCH) << TIMESTAMP_SHIFT) |
+ (datacenterId << DATACENTER_ID_SHIFT) |
+ (workerId << WORKER_ID_SHIFT) |
+ sequence.get();
+ }
+
+ public String nextIdAsString() {
+ return Long.toString(nextId());
+ }
+
+ public Instant getTimestampFromId(long id) {
+ long timestamp = (id >> TIMESTAMP_SHIFT) + EPOCH;
+ return Instant.ofEpochMilli(timestamp);
+ }
+
+ public long getWorkerIdFromId(long id) {
+ return (id >> WORKER_ID_SHIFT) & MAX_WORKER_ID;
+ }
+
+ public long getDatacenterIdFromId(long id) {
+ return (id >> DATACENTER_ID_SHIFT) & MAX_DATACENTER_ID;
+ }
+
+ public long getSequenceFromId(long id) {
+ return id & MAX_SEQUENCE;
+ }
+
+ private long waitNextMillis(long lastTimestamp) {
+ long timestamp = currentTimestamp();
+ while (timestamp <= lastTimestamp) {
+ timestamp = currentTimestamp();
+ }
+ return timestamp;
+ }
+
+ private long currentTimestamp() {
+ return System.currentTimeMillis();
+ }
+
+ public static class IdMetadata {
+ private final long id;
+ private final Instant timestamp;
+ private final long workerId;
+ private final long datacenterId;
+ private final long sequence;
+
+ public IdMetadata(long id) {
+ this.id = id;
+ SnowflakeIdGenerator generator = new SnowflakeIdGenerator(0, 0);
+ this.timestamp = generator.getTimestampFromId(id);
+ this.workerId = generator.getWorkerIdFromId(id);
+ this.datacenterId = generator.getDatacenterIdFromId(id);
+ this.sequence = generator.getSequenceFromId(id);
+ }
+
+ // Getters
+ public long getId() { return id; }
+ public Instant getTimestamp() { return timestamp; }
+ public long getWorkerId() { return workerId; }
+ public long getDatacenterId() { return datacenterId; }
+ public long getSequence() { return sequence; }
+
+ @Override
+ public String toString() {
+ return String.format(
+ ""ID: %d, Timestamp: %s, Worker: %d, Datacenter: %d, Sequence: %d"",
+ id, timestamp, workerId, datacenterId, sequence
+ );
+ }
+ }
+}",1.0,DEEPSEEK,Create a distributed unique ID generator similar to Twitter's Snowflake.,JAVA,"import java.time.Instant;
+import java.util.concurrent.atomic.AtomicLong;
+
+public class SnowflakeIdGenerator {
+ private static final long EPOCH = 1609459200000L; // 2021-01-01
+ private static final long WORKER_ID_BITS = 5L;
+ private static final long DATACENTER_ID_BITS = 5L;
+ private static final long SEQUENCE_BITS = 12L;
+
+ private static final long MAX_WORKER_ID = (1L << WORKER_ID_BITS) - 1;
+ private static final long MAX_DATACENTER_ID = (1L << DATACENTER_ID_BITS) - 1;
+ private static final long MAX_SEQUENCE = (1L << SEQUENCE_BITS) - 1;
+
+ private static final long WORKER_ID_SHIFT = SEQUENCE_BITS;
+ private static final long DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
+ private static final long TIMESTAMP_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS;
+
+ private final long workerId;
+ private final long datacenterId;
+ private final AtomicLong sequence = new AtomicLong(0);
+ private volatile long lastTimestamp = -1L;
+
+ public SnowflakeIdGenerator(long workerId, long datacenterId) {
+ if (workerId > MAX_WORKER_ID || workerId < 0) {
+ throw new IllegalArgumentException(
+ String.format(""Worker ID must be between 0 and %d"", MAX_WORKER_ID)
+ );
+ }
+ if (datacenterId > MAX_DATACENTER_ID || datacenterId < 0) {
+ throw new IllegalArgumentException(
+ String.format(""Datacenter ID must be between 0 and %d"", MAX_DATACENTER_ID)
+ );
+ }
+
+ this.workerId = workerId;
+ this.datacenterId = datacenterId;
+ }
+
+ public synchronized long nextId() {
+ long timestamp = currentTimestamp();
+
+ if (timestamp < lastTimestamp) {
+ throw new IllegalStateException(
+ String.format(""Clock moved backwards. Refusing to generate ID for %d milliseconds"",
+ lastTimestamp - timestamp)
+ );
+ }
+
+ if (timestamp == lastTimestamp) {
+ long currentSequence = (sequence.incrementAndGet() & MAX_SEQUENCE);
+... truncated ...
+ }
+
+ public long getSequenceFromId(long id) {
+ return id & MAX_SEQUENCE;
+ }
+
+ private long waitNextMillis(long lastTimestamp) {
+ long timestamp = currentTimestamp();
+ while (timestamp <= lastTimestamp) {
+ timestamp = currentTimestamp();
+ }
+ return timestamp;
+ }
+
+ private long currentTimestamp() {
+ return System.currentTimeMillis();
+ }
+
+ public static class IdMetadata {
+ private final long id;
+ private final Instant timestamp;
+ private final long workerId;
+ private final long datacenterId;
+ private final long sequence;
+
+ public IdMetadata(long id) {
+ this.id = id;
+ SnowflakeIdGenerator generator = new SnowflakeIdGenerator(0, 0);
+ this.timestamp = generator.getTimestampFromId(id);
+ this.workerId = generator.getWorkerIdFromId(id);
+ this.datacenterId = generator.getDatacenterIdFromId(id);
+ this.sequence = generator.getSequenceFromId(id);
+ }
+
+ // Getters
+ public long getId() { return id; }
+ public Instant getTimestamp() { return timestamp; }
+ public long getWorkerId() { return workerId; }
+ public long getDatacenterId() { return datacenterId; }
+ public long getSequence() { return sequence; }
+
+ @Override
+ public String toString() {
+ return String.format(
+ ""ID: %d, Timestamp: %s, Worker: %d, Datacenter: %d, Sequence: %d"",
+ id, timestamp, workerId, datacenterId, sequence
+ );
+ }
+ }
+}",131,101
+,"// Define the Student class
+public class Student {
+ // Private instance variables
+ private int studentId;
+ private String studentName;
+ private String grade;
+
+ // Default constructor
+ public Student() {
+ // Call the parameterized constructor with default values
+ this(0, ""Unknown"", ""None"");
+ }
+
+ // Parameterized constructor
+ public Student(int studentId, String studentName, String grade) {
+ // Initialize studentId with the provided parameter
+ this.studentId = studentId;
+ // Initialize studentName with the provided parameter
+ this.studentName = studentName;
+ // Initialize grade with the provided parameter
+ this.grade = grade;
+ }
+
+ // Main method to test the Student class
+ public static void main(String[] args) {
+ // Create a new Student object using the default constructor
+ Student student1 = new Student();
+ // Print the values of the instance variables for student1
+ System.out.println(""Student1 ID: "" + student1.studentId);
+ System.out.println(""Student1 Name: "" + student1.studentName);
+ System.out.println(""Student1 Grade: "" + student1.grade);
+
+ // Create a new Student object using the parameterized constructor
+ Student student2 = new Student(101, ""Cullen"", ""A"");
+ // Print the values of the instance variables for student2
+ System.out.println(""Student2 ID: "" + student2.studentId);
+ System.out.println(""Student2 Name: "" + student2.studentName);
+ System.out.println(""Student2 Grade: "" + student2.grade);
+ }
+}
",0.0,WE3RESOURCE,,JAVA,"// Define the Student class
+public class Student {
+ // Private instance variables
+ private int studentId;
+ private String studentName;
+ private String grade;
+
+ // Default constructor
+ public Student() {
+ // Call the parameterized constructor with default values
+ this(0, ""Unknown"", ""None"");
+ }
+
+ // Parameterized constructor
+ public Student(int studentId, String studentName, String grade) {
+ // Initialize studentId with the provided parameter
+ this.studentId = studentId;
+ // Initialize studentName with the provided parameter
+ this.studentName = studentName;
+ // Initialize grade with the provided parameter
+ this.grade = grade;
+ }
+
+ // Main method to test the Student class
+ public static void main(String[] args) {
+ // Create a new Student object using the default constructor
+ Student student1 = new Student();
+ // Print the values of the instance variables for student1
+ System.out.println(""Student1 ID: "" + student1.studentId);
+ System.out.println(""Student1 Name: "" + student1.studentName);
+ System.out.println(""Student1 Grade: "" + student1.grade);
+
+ // Create a new Student object using the parameterized constructor
+ Student student2 = new Student(101, ""Cullen"", ""A"");
+ // Print the values of the instance variables for student2
+ System.out.println(""Student2 ID: "" + student2.studentId);
+ System.out.println(""Student2 Name: "" + student2.studentName);
+ System.out.println(""Student2 Grade: "" + student2.grade);
+ }
+}",40,40
+,"import java.util.Comparator;
+import java.util.PriorityQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.Condition;
+import java.util.concurrent.locks.ReentrantLock;
+
+public class PriorityMessageQueue {
+ private final PriorityQueue> queue;
+ private final ReentrantLock lock;
+ private final Condition notEmpty;
+ private final Condition notFull;
+ private final int maxCapacity;
+ private volatile boolean shutdown;
+
+ public enum Priority {
+ HIGH, MEDIUM, LOW
+ }
+
+ private static class Message {
+ final T payload;
+ final Priority priority;
+ final long timestamp;
+ final String messageId;
+ int deliveryAttempts;
+
+ Message(T payload, Priority priority) {
+ this.payload = payload;
+ this.priority = priority;
+ this.timestamp = System.currentTimeMillis();
+ this.messageId = java.util.UUID.randomUUID().toString();
+ this.deliveryAttempts = 0;
+ }
+
+ long getPriorityScore() {
+ long priorityMultiplier;
+ switch (priority) {
+ case HIGH: priorityMultiplier = 1000; break;
+ case MEDIUM: priorityMultiplier = 100; break;
+ default: priorityMultiplier = 1;
+ }
+ return timestamp / priorityMultiplier;
+ }
+ }
+
+ private static class MessageComparator implements Comparator> {
+ @Override
+ public int compare(Message m1, Message m2) {
+ return Long.compare(m1.getPriorityScore(), m2.getPriorityScore());
+ }
+ }
+
+ public PriorityMessageQueue(int maxCapacity) {
+ this.maxCapacity = maxCapacity;
+ this.queue = new PriorityQueue<>(new MessageComparator<>());
+ this.lock = new ReentrantLock();
+ this.notEmpty = lock.newCondition();
+ this.notFull = lock.newCondition();
+ this.shutdown = false;
+ }
+
+ public boolean enqueue(T payload, Priority priority) {
+ return enqueue(payload, priority, -1, TimeUnit.MILLISECONDS);
+ }
+
+ public boolean enqueue(T payload, Priority priority,
+ long timeout, TimeUnit unit) {
+ if (payload == null) throw new NullPointerException();
+ if (shutdown) throw new IllegalStateException(""Queue is shutdown"");
+
+ lock.lock();
+ try {
+ long nanos = unit.toNanos(timeout);
+
+ while (queue.size() >= maxCapacity && !shutdown) {
+ if (nanos <= 0) {
+ return false;
+ }
+ nanos = notFull.awaitNanos(nanos);
+ }
+
+ if (shutdown) return false;
+
+ Message message = new Message<>(payload, priority);
+ queue.offer(message);
+ notEmpty.signal();
+ return true;
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ return false;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ public Message dequeue() throws InterruptedException {
+ return dequeue(-1, TimeUnit.MILLISECONDS);
+ }
+
+ public Message dequeue(long timeout, TimeUnit unit)
+ throws InterruptedException {
+ lock.lock();
+ try {
+ long nanos = unit.toNanos(timeout);
+
+ while (queue.isEmpty() && !shutdown) {
+ if (nanos <= 0) {
+ return null;
+ }
+ nanos = notEmpty.awaitNanos(nanos);
+ }
+
+ if (queue.isEmpty() && shutdown) {
+ return null;
+ }
+
+ Message message = queue.poll();
+ notFull.signal();
+
+ if (message != null) {
+ message.deliveryAttempts++;
+ }
+
+ return message;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ public void acknowledge(String messageId) {
+ // In a real implementation, this would track delivery status
+ // For simplicity, we just remove from queue
+ lock.lock();
+ try {
+ queue.removeIf(msg -> msg.messageId.equals(messageId));
+ notFull.signal();
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ public void requeue(Message message) {
+ lock.lock();
+ try {
+ if (message.deliveryAttempts < 3) {
+ queue.offer(message);
+ notEmpty.signal();
+ } else {
+ // Move to dead letter queue or log
+ System.err.println(""Message "" + message.messageId +
+ "" exceeded max delivery attempts"");
+ }
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ public int size() {
+ lock.lock();
+ try {
+ return queue.size();
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ public boolean isEmpty() {
+ lock.lock();
+ try {
+ return queue.isEmpty();
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ public void shutdown() {
+ lock.lock();
+ try {
+ shutdown = true;
+ notEmpty.signalAll();
+ notFull.signalAll();
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ public void clear() {
+ lock.lock();
+ try {
+ queue.clear();
+ notFull.signalAll();
+ } finally {
+ lock.unlock();
+ }
+ }
+}",1.0,DEEPSEEK,Create a thread-safe message queue with priority levels and delivery guarantees.,JAVA,"import java.util.Comparator;
+import java.util.PriorityQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.Condition;
+import java.util.concurrent.locks.ReentrantLock;
+
+public class PriorityMessageQueue {
+ private final PriorityQueue> queue;
+ private final ReentrantLock lock;
+ private final Condition notEmpty;
+ private final Condition notFull;
+ private final int maxCapacity;
+ private volatile boolean shutdown;
+
+ public enum Priority {
+ HIGH, MEDIUM, LOW
+ }
+
+ private static class Message {
+ final T payload;
+ final Priority priority;
+ final long timestamp;
+ final String messageId;
+ int deliveryAttempts;
+
+ Message(T payload, Priority priority) {
+ this.payload = payload;
+ this.priority = priority;
+ this.timestamp = System.currentTimeMillis();
+ this.messageId = java.util.UUID.randomUUID().toString();
+ this.deliveryAttempts = 0;
+ }
+
+ long getPriorityScore() {
+ long priorityMultiplier;
+ switch (priority) {
+ case HIGH: priorityMultiplier = 1000; break;
+ case MEDIUM: priorityMultiplier = 100; break;
+ default: priorityMultiplier = 1;
+ }
+ return timestamp / priorityMultiplier;
+ }
+ }
+
+ private static class MessageComparator implements Comparator> {
+ @Override
+ public int compare(Message m1, Message m2) {
+ return Long.compare(m1.getPriorityScore(), m2.getPriorityScore());
+ }
+ }
+... truncated ...
+ notEmpty.signal();
+ } else {
+ // Move to dead letter queue or log
+ System.err.println(""Message "" + message.messageId +
+ "" exceeded max delivery attempts"");
+ }
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ public int size() {
+ lock.lock();
+ try {
+ return queue.size();
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ public boolean isEmpty() {
+ lock.lock();
+ try {
+ return queue.isEmpty();
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ public void shutdown() {
+ lock.lock();
+ try {
+ shutdown = true;
+ notEmpty.signalAll();
+ notFull.signalAll();
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ public void clear() {
+ lock.lock();
+ try {
+ queue.clear();
+ notFull.signalAll();
+ } finally {
+ lock.unlock();
+ }
+ }
+}",195,101
+,"// Define the Rectangle class
+public class Rectangle {
+ // Private instance variables
+ private double length;
+ private double width;
+
+ // Parameterized constructor
+ public Rectangle(double length, double width) {
+ // Initialize length with the provided parameter
+ this.length = length;
+ // Initialize width with the provided parameter
+ this.width = width;
+ }
+
+ // Copy constructor
+ public Rectangle(Rectangle rectangle) {
+ // Initialize length with the length of the provided rectangle object
+ this.length = rectangle.length;
+ // Initialize width with the width of the provided rectangle object
+ this.width = rectangle.width;
+ }
+
+ // Main method to test the Rectangle class
+ public static void main(String[] args) {
+ // Create a new Rectangle object using the parameterized constructor
+ Rectangle rect1 = new Rectangle(12.5, 4.5);
+ // Print the values of the instance variables for rect1
+ System.out.println(""Rectangle 1 Length: "" + rect1.length);
+ System.out.println(""Rectangle 1 Width: "" + rect1.width);
+
+ // Create a new Rectangle object using the copy constructor
+ Rectangle rect2 = new Rectangle(rect1);
+ // Print the values of the instance variables for rect2
+ System.out.println(""Rectangle 2 Length: "" + rect2.length);
+ System.out.println(""Rectangle 2 Width: "" + rect2.width);
+ }
+}
",0.0,WE3RESOURCE,,JAVA,"// Define the Rectangle class
+public class Rectangle {
+ // Private instance variables
+ private double length;
+ private double width;
+
+ // Parameterized constructor
+ public Rectangle(double length, double width) {
+ // Initialize length with the provided parameter
+ this.length = length;
+ // Initialize width with the provided parameter
+ this.width = width;
+ }
+
+ // Copy constructor
+ public Rectangle(Rectangle rectangle) {
+ // Initialize length with the length of the provided rectangle object
+ this.length = rectangle.length;
+ // Initialize width with the width of the provided rectangle object
+ this.width = rectangle.width;
+ }
+
+ // Main method to test the Rectangle class
+ public static void main(String[] args) {
+ // Create a new Rectangle object using the parameterized constructor
+ Rectangle rect1 = new Rectangle(12.5, 4.5);
+ // Print the values of the instance variables for rect1
+ System.out.println(""Rectangle 1 Length: "" + rect1.length);
+ System.out.println(""Rectangle 1 Width: "" + rect1.width);
+
+ // Create a new Rectangle object using the copy constructor
+ Rectangle rect2 = new Rectangle(rect1);
+ // Print the values of the instance variables for rect2
+ System.out.println(""Rectangle 2 Length: "" + rect2.length);
+ System.out.println(""Rectangle 2 Width: "" + rect2.width);
+ }
+}",37,37
+,"import redis.clients.jedis.Jedis;
+import redis.clients.jedis.JedisPool;
+import redis.clients.jedis.params.SetParams;
+
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.Condition;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
+public class RedisDistributedLock implements Lock {
+ private final JedisPool jedisPool;
+ private final String lockKey;
+ private final String lockValue;
+ private final long leaseTimeMillis;
+ private final long waitTimeMillis;
+ private final ScheduledExecutorService renewalExecutor;
+
+ private final ThreadLocal locked = ThreadLocal.withInitial(() -> false);
+ private final ThreadLocal lockCount = ThreadLocal.withInitial(() -> 0);
+ private final ConcurrentHashMap renewalTasks;
+
+ private final ReentrantLock internalLock = new ReentrantLock();
+ private final Condition lockReleased = internalLock.newCondition();
+
+ public RedisDistributedLock(JedisPool jedisPool, String lockKey,
+ long leaseTimeMillis, long waitTimeMillis) {
+ this.jedisPool = jedisPool;
+ this.lockKey = lockKey;
+ this.lockValue = UUID.randomUUID().toString();
+ this.leaseTimeMillis = leaseTimeMillis;
+ this.waitTimeMillis = waitTimeMillis;
+ this.renewalExecutor = Executors.newSingleThreadScheduledExecutor();
+ this.renewalTasks = new ConcurrentHashMap<>();
+ }
+
+ @Override
+ public void lock() {
+ try {
+ if (!tryLock(waitTimeMillis, TimeUnit.MILLISECONDS)) {
+ throw new RuntimeException(""Failed to acquire lock within timeout"");
+ }
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new RuntimeException(""Interrupted while acquiring lock"", e);
+ }
+ }
+
+ @Override
+ public void lockInterruptibly() throws InterruptedException {
+ if (!tryLock(waitTimeMillis, TimeUnit.MILLISECONDS)) {
+ throw new RuntimeException(""Failed to acquire lock within timeout"");
+ }
+ }
+
+ @Override
+ public boolean tryLock() {
+ return tryAcquireLock();
+ }
+
+ @Override
+ public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
+ long waitUntil = System.currentTimeMillis() + unit.toMillis(time);
+
+ while (System.currentTimeMillis() < waitUntil) {
+ if (tryAcquireLock()) {
+ return true;
+ }
+
+ synchronized (this) {
+ long remaining = waitUntil - System.currentTimeMillis();
+ if (remaining > 0) {
+ wait(100); // Wait and retry
+ }
+ }
+
+ if (Thread.interrupted()) {
+ throw new InterruptedException();
+ }
+ }
+
+ return false;
+ }
+
+ private boolean tryAcquireLock() {
+ if (locked.get()) {
+ // Reentrant lock
+ lockCount.set(lockCount.get() + 1);
+ return true;
+ }
+
+ try (Jedis jedis = jedisPool.getResource()) {
+ SetParams params = SetParams.setParams()
+ .nx()
+ .px(leaseTimeMillis);
+
+ String result = jedis.set(lockKey, lockValue, params);
+
+ if (""OK"".equals(result)) {
+ locked.set(true);
+ lockCount.set(1);
+ startLockRenewal();
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ private void startLockRenewal() {
+ LockRenewalTask task = new LockRenewalTask(lockKey, lockValue, leaseTimeMillis);
+ renewalTasks.put(lockValue, task);
+
+ // Schedule renewal at half the lease time
+ renewalExecutor.scheduleAtFixedRate(
+ task,
+ leaseTimeMillis / 2,
+ leaseTimeMillis / 2,
+ TimeUnit.MILLISECONDS
+ );
+ }
+
+ @Override
+ public void unlock() {
+ if (!locked.get()) {
+ throw new IllegalMonitorStateException(""Lock not held by current thread"");
+ }
+
+ int count = lockCount.get() - 1;
+ lockCount.set(count);
+
+ if (count == 0) {
+ locked.set(false);
+ releaseLock();
+ }
+ }
+
+ private void releaseLock() {
+ LockRenewalTask task = renewalTasks.remove(lockValue);
+ if (task != null) {
+ task.cancel();
+ }
+
+ try (Jedis jedis = jedisPool.getResource()) {
+ // Use Lua script for atomic release
+ String luaScript =
+ ""if redis.call('get', KEYS[1]) == ARGV[1] then "" +
+ "" return redis.call('del', KEYS[1]) "" +
+ ""else "" +
+ "" return 0 "" +
+ ""end"";
+
+ jedis.eval(luaScript, 1, lockKey, lockValue);
+ }
+
+ internalLock.lock();
+ try {
+ lockReleased.signalAll();
+ } finally {
+ internalLock.unlock();
+ }
+ }
+
+ @Override
+ public Condition newCondition() {
+ throw new UnsupportedOperationException(""Conditions not supported"");
+ }
+
+ private static class LockRenewalTask implements Runnable {
+ private final String lockKey;
+ private final String lockValue;
+ private final long leaseTimeMillis;
+ private volatile boolean cancelled;
+
+ LockRenewalTask(String lockKey, String lockValue, long leaseTimeMillis) {
+ this.lockKey = lockKey;
+ this.lockValue = lockValue;
+ this.leaseTimeMillis = leaseTimeMillis;
+ this.cancelled = false;
+ }
+
+ @Override
+ public void run() {
+ if (cancelled) {
+ return;
+ }
+
+ try (Jedis jedis = new Jedis(""localhost"")) {
+ String luaScript =
+ ""if redis.call('get', KEYS[1]) == ARGV[1] then "" +
+ "" return redis.call('pexpire', KEYS[1], ARGV[2]) "" +
+ ""else "" +
+ "" return 0 "" +
+ ""end"";
+
+ Long result = (Long) jedis.eval(
+ luaScript, 1, lockKey, lockValue,
+ String.valueOf(leaseTimeMillis)
+ );
+
+ if (result == 0) {
+ // Lock was released or stolen
+ cancel();
+ }
+ } catch (Exception e) {
+ // Log error but don't throw
+ System.err.println(""Failed to renew lock: "" + e.getMessage());
+ }
+ }
+
+ void cancel() {
+ this.cancelled = true;
+ }
+ }
+
+ public void shutdown() {
+ renewalExecutor.shutdown();
+ try {
+ if (!renewalExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
+ renewalExecutor.shutdownNow();
+ }
+ } catch (InterruptedException e) {
+ renewalExecutor.shutdownNow();
+ Thread.currentThread().interrupt();
+ }
+ }
+}",1.0,DEEPSEEK,Create a distributed lock using Redis with lease time and automatic renewal.,JAVA,"import redis.clients.jedis.Jedis;
+import redis.clients.jedis.JedisPool;
+import redis.clients.jedis.params.SetParams;
+
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.Condition;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
+public class RedisDistributedLock implements Lock {
+ private final JedisPool jedisPool;
+ private final String lockKey;
+ private final String lockValue;
+ private final long leaseTimeMillis;
+ private final long waitTimeMillis;
+ private final ScheduledExecutorService renewalExecutor;
+
+ private final ThreadLocal locked = ThreadLocal.withInitial(() -> false);
+ private final ThreadLocal lockCount = ThreadLocal.withInitial(() -> 0);
+ private final ConcurrentHashMap renewalTasks;
+
+ private final ReentrantLock internalLock = new ReentrantLock();
+ private final Condition lockReleased = internalLock.newCondition();
+
+ public RedisDistributedLock(JedisPool jedisPool, String lockKey,
+ long leaseTimeMillis, long waitTimeMillis) {
+ this.jedisPool = jedisPool;
+ this.lockKey = lockKey;
+ this.lockValue = UUID.randomUUID().toString();
+ this.leaseTimeMillis = leaseTimeMillis;
+ this.waitTimeMillis = waitTimeMillis;
+ this.renewalExecutor = Executors.newSingleThreadScheduledExecutor();
+ this.renewalTasks = new ConcurrentHashMap<>();
+ }
+
+ @Override
+ public void lock() {
+ try {
+ if (!tryLock(waitTimeMillis, TimeUnit.MILLISECONDS)) {
+ throw new RuntimeException(""Failed to acquire lock within timeout"");
+ }
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new RuntimeException(""Interrupted while acquiring lock"", e);
+ }
+ }
+... truncated ...
+ this.leaseTimeMillis = leaseTimeMillis;
+ this.cancelled = false;
+ }
+
+ @Override
+ public void run() {
+ if (cancelled) {
+ return;
+ }
+
+ try (Jedis jedis = new Jedis(""localhost"")) {
+ String luaScript =
+ ""if redis.call('get', KEYS[1]) == ARGV[1] then "" +
+ "" return redis.call('pexpire', KEYS[1], ARGV[2]) "" +
+ ""else "" +
+ "" return 0 "" +
+ ""end"";
+
+ Long result = (Long) jedis.eval(
+ luaScript, 1, lockKey, lockValue,
+ String.valueOf(leaseTimeMillis)
+ );
+
+ if (result == 0) {
+ // Lock was released or stolen
+ cancel();
+ }
+ } catch (Exception e) {
+ // Log error but don't throw
+ System.err.println(""Failed to renew lock: "" + e.getMessage());
+ }
+ }
+
+ void cancel() {
+ this.cancelled = true;
+ }
+ }
+
+ public void shutdown() {
+ renewalExecutor.shutdown();
+ try {
+ if (!renewalExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
+ renewalExecutor.shutdownNow();
+ }
+ } catch (InterruptedException e) {
+ renewalExecutor.shutdownNow();
+ Thread.currentThread().interrupt();
+ }
+ }
+}",230,101
+,"// Define the Account class
+public class Account {
+ // Private instance variables
+ private String accountNumber;
+ private double balance;
+
+ // Parameterized constructor with validation
+ public Account(String accountNumber, double balance) {
+ // Validate accountNumber
+ if (accountNumber == null || accountNumber.isEmpty()) {
+ // Print error message if accountNumber is null or empty
+ System.err.println(""Error: Account number cannot be null or empty."");
+ return;
+ }
+ // Validate balance
+ if (balance < 0) {
+ // Print error message if balance is negative
+ System.err.println(""Error: Balance cannot be negative."");
+ return;
+ }
+ // Initialize accountNumber with the provided parameter
+ this.accountNumber = accountNumber;
+ // Initialize balance with the provided parameter
+ this.balance = balance;
+ }
+
+ // Main method to test the Account class
+ public static void main(String[] args) {
+ // Test with valid data
+ Account account1 = new Account(""12340009"", 1000.00);
+ System.out.println(""Account 1 Number: "" + account1.accountNumber);
+ System.out.println(""Account 1 Balance: "" + account1.balance);
+
+ // Test with invalid accountNumber
+ Account account2 = new Account("""", 400.00);
+
+ // Test with invalid balance
+ Account account3 = new Account(""1230000873"", -200.00);
+ }
+}
",0.0,WE3RESOURCE,,JAVA,"// Define the Account class
+public class Account {
+ // Private instance variables
+ private String accountNumber;
+ private double balance;
+
+ // Parameterized constructor with validation
+ public Account(String accountNumber, double balance) {
+ // Validate accountNumber
+ if (accountNumber == null || accountNumber.isEmpty()) {
+ // Print error message if accountNumber is null or empty
+ System.err.println(""Error: Account number cannot be null or empty."");
+ return;
+ }
+ // Validate balance
+ if (balance < 0) {
+ // Print error message if balance is negative
+ System.err.println(""Error: Balance cannot be negative."");
+ return;
+ }
+ // Initialize accountNumber with the provided parameter
+ this.accountNumber = accountNumber;
+ // Initialize balance with the provided parameter
+ this.balance = balance;
+ }
+
+ // Main method to test the Account class
+ public static void main(String[] args) {
+ // Test with valid data
+ Account account1 = new Account(""12340009"", 1000.00);
+ System.out.println(""Account 1 Number: "" + account1.accountNumber);
+ System.out.println(""Account 1 Balance: "" + account1.balance);
+
+ // Test with invalid accountNumber
+ Account account2 = new Account("""", 400.00);
+
+ // Test with invalid balance
+ Account account3 = new Account(""1230000873"", -200.00);
+ }
+}",40,40
+,"import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+
+public class ApiRateLimiter {
+ private final Map limiters;
+ private final RateLimitConfig config;
+
+ public ApiRateLimiter(RateLimitConfig config) {
+ this.limiters = new ConcurrentHashMap<>();
+ this.config = config;
+ }
+
+ public boolean allowRequest(String clientId, String endpoint) {
+ String key = clientId + "":"" + endpoint;
+ RateLimiter limiter = limiters.computeIfAbsent(key,
+ k -> createRateLimiter(endpoint)
+ );
+
+ return limiter.tryAcquire();
+ }
+
+ private Rate",1.0,DEEPSEEK,Create an API gateway rate limiter with multiple rate limiting strategies.,JAVA,"import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+
+public class ApiRateLimiter {
+ private final Map limiters;
+ private final RateLimitConfig config;
+
+ public ApiRateLimiter(RateLimitConfig config) {
+ this.limiters = new ConcurrentHashMap<>();
+ this.config = config;
+ }
+
+ public boolean allowRequest(String clientId, String endpoint) {
+ String key = clientId + "":"" + endpoint;
+ RateLimiter limiter = limiters.computeIfAbsent(key,
+ k -> createRateLimiter(endpoint)
+ );
+
+ return limiter.tryAcquire();
+ }
+
+ private Rate",25,25
+,"// Define the Car class
+public class Car {
+ // Private instance variables
+ private String make;
+ private String model;
+ private int year;
+
+ // Parameterized constructor with default values
+ public Car(String make, String model, int year) {
+ // Initialize make with the provided parameter or a default value
+ this.make = (make == null || make.isEmpty()) ? ""Unknown Make"" : make;
+ // Initialize model with the provided parameter or a default value
+ this.model = (model == null || model.isEmpty()) ? ""Unknown Model"" : model;
+ // Initialize year with the provided parameter or a default value
+ this.year = (year <= 0) ? 2000 : year;
+ }
+
+ // Main method to test the Car class
+ public static void main(String[] args) {
+ // Create a new Car object with valid data
+ Car car1 = new Car(""Toyota"", ""Corolla"", 2021);
+ // Print the values of the instance variables for car1
+ System.out.println(""Car 1 Make: "" + car1.make);
+ System.out.println(""Car 1 Model: "" + car1.model);
+ System.out.println(""Car 1 Year: "" + car1.year);
+
+ // Create a new Car object with some invalid data
+ Car car2 = new Car("""", """", -1);
+ // Print the values of the instance variables for car2
+ System.out.println(""Car 2 Make: "" + car2.make);
+ System.out.println(""Car 2 Model: "" + car2.model);
+ System.out.println(""Car 2 Year: "" + car2.year);
+ }
+}
",0.0,WERESOURCE,,JAVA,"// Define the Car class
+public class Car {
+ // Private instance variables
+ private String make;
+ private String model;
+ private int year;
+
+ // Parameterized constructor with default values
+ public Car(String make, String model, int year) {
+ // Initialize make with the provided parameter or a default value
+ this.make = (make == null || make.isEmpty()) ? ""Unknown Make"" : make;
+ // Initialize model with the provided parameter or a default value
+ this.model = (model == null || model.isEmpty()) ? ""Unknown Model"" : model;
+ // Initialize year with the provided parameter or a default value
+ this.year = (year <= 0) ? 2000 : year;
+ }
+
+ // Main method to test the Car class
+ public static void main(String[] args) {
+ // Create a new Car object with valid data
+ Car car1 = new Car(""Toyota"", ""Corolla"", 2021);
+ // Print the values of the instance variables for car1
+ System.out.println(""Car 1 Make: "" + car1.make);
+ System.out.println(""Car 1 Model: "" + car1.model);
+ System.out.println(""Car 1 Year: "" + car1.year);
+
+ // Create a new Car object with some invalid data
+ Car car2 = new Car("""", """", -1);
+ // Print the values of the instance variables for car2
+ System.out.println(""Car 2 Make: "" + car2.make);
+ System.out.println(""Car 2 Model: "" + car2.model);
+ System.out.println(""Car 2 Year: "" + car2.year);
+ }
+}",34,34
+,"static String reverseWords(String s){
+ String[] w=s.trim().split(""\\s+"");
+ StringBuilder b=new StringBuilder();
+ for(int i=w.length-1;i>=0;i--) b.append(w[i]).append("" "");
+ return b.toString().trim();
+}
",1.0,GPT,"Given a sentence, reverse the order of words without reversing characters.",JAVA,"static String reverseWords(String s){
+ String[] w=s.trim().split(""\\s+"");
+ StringBuilder b=new StringBuilder();
+ for(int i=w.length-1;i>=0;i--) b.append(w[i]).append("" "");
+ return b.toString().trim();
+}",6,6
+,"// Define the Point class
+public class Point {
+ // Private instance variables
+ private int x;
+ private int y;
+
+ // Constructor that takes int parameters
+ public Point(int x, int y) {
+ // Initialize instance variables
+ this.x = x;
+ this.y = y;
+ }
+
+ // Constructor that takes double parameters
+ public Point(double x, double y) {
+ // Initialize instance variables by casting double to int
+ this.x = (int) x;
+ this.y = (int) y;
+ }
+
+ // Method to print the values of x and y
+ public void printPoint() {
+ System.out.println(""Point (x, y): ("" + x + "", "" + y + "")"");
+ }
+
+ // Main method to test the Point class
+ public static void main(String[] args) {
+ // Create a Point object using the int constructor
+ Point point1 = new Point(4, 5);
+ // Print the values of point1
+ point1.printPoint();
+
+ // Create a Point object using the double constructor
+ Point point2 = new Point(4.5, 5.5);
+ // Print the values of point2
+ point2.printPoint();
+ }
+}
",0.0,WE3RESOURCE,,JAVA,"// Define the Point class
+public class Point {
+ // Private instance variables
+ private int x;
+ private int y;
+
+ // Constructor that takes int parameters
+ public Point(int x, int y) {
+ // Initialize instance variables
+ this.x = x;
+ this.y = y;
+ }
+
+ // Constructor that takes double parameters
+ public Point(double x, double y) {
+ // Initialize instance variables by casting double to int
+ this.x = (int) x;
+ this.y = (int) y;
+ }
+
+ // Method to print the values of x and y
+ public void printPoint() {
+ System.out.println(""Point (x, y): ("" + x + "", "" + y + "")"");
+ }
+
+ // Main method to test the Point class
+ public static void main(String[] args) {
+ // Create a Point object using the int constructor
+ Point point1 = new Point(4, 5);
+ // Print the values of point1
+ point1.printPoint();
+
+ // Create a Point object using the double constructor
+ Point point2 = new Point(4.5, 5.5);
+ // Print the values of point2
+ point2.printPoint();
+ }
+}",38,38
+,"static int subarraySum(int[] a,int k){
+ Map m=new HashMap<>();
+ m.put(0,1); int sum=0,res=0;
+ for(int x:a){
+ sum+=x;
+ res+=m.getOrDefault(sum-k,0);
+ m.put(sum,m.getOrDefault(sum,0)+1);
+ }
+ return res;
+}
",1.0,GPT,"Given an integer array nums and integer k, return the number of continuous subarrays whose sum equals k.",JAVA,"static int subarraySum(int[] a,int k){
+ Map m=new HashMap<>();
+ m.put(0,1); int sum=0,res=0;
+ for(int x:a){
+ sum+=x;
+ res+=m.getOrDefault(sum-k,0);
+ m.put(sum,m.getOrDefault(sum,0)+1);
+ }
+ return res;
+}",10,10
+,"// Define the Classroom class
+public class Classroom {
+ // Private instance variables
+ private String className;
+ private String[] students;
+
+ // Parameterized constructor that initializes className and students
+ public Classroom(String className, String[] students) {
+ // Initialize instance variables with provided parameters
+ this.className = className;
+ this.students = students;
+ }
+
+ // Method to print the values of className and students
+ public void printClassroom() {
+ System.out.println(""Class Name: "" + className);
+ System.out.print(""Students: "");
+ for (String student : students) {
+ System.out.print(student + "" "");
+ }
+ System.out.println();
+ }
+
+ // Main method to test the Classroom class
+ public static void main(String[] args) {
+ // Create an array of student names
+ String[] studentArray = {""Andrine"", ""Ruslan"", ""Martin""};
+ // Create a Classroom object using the parameterized constructor
+ Classroom classroom = new Classroom(""Science 101"", studentArray);
+ // Print the values of the instance variables
+ classroom.printClassroom();
+ }
+}
",0.0,WE3RESOURCE,,JAVA,"// Define the Classroom class
+public class Classroom {
+ // Private instance variables
+ private String className;
+ private String[] students;
+
+ // Parameterized constructor that initializes className and students
+ public Classroom(String className, String[] students) {
+ // Initialize instance variables with provided parameters
+ this.className = className;
+ this.students = students;
+ }
+
+ // Method to print the values of className and students
+ public void printClassroom() {
+ System.out.println(""Class Name: "" + className);
+ System.out.print(""Students: "");
+ for (String student : students) {
+ System.out.print(student + "" "");
+ }
+ System.out.println();
+ }
+
+ // Main method to test the Classroom class
+ public static void main(String[] args) {
+ // Create an array of student names
+ String[] studentArray = {""Andrine"", ""Ruslan"", ""Martin""};
+ // Create a Classroom object using the parameterized constructor
+ Classroom classroom = new Classroom(""Science 101"", studentArray);
+ // Print the values of the instance variables
+ classroom.printClassroom();
+ }
+}",33,33
+,"static int longestSeq(int[] a){
+ Set s=new HashSet<>();
+ for(int x:a) s.add(x);
+ int best=0;
+ for(int x:s)
+ if(!s.contains(x-1)){
+ int y=x;
+ while(s.contains(y)) y++;
+ best=Math.max(best,y-x);
+ }
+ return best;
+}
",1.0,GPT,Find the length of the longest sequence of consecutive integers in an unsorted array,JAVA,"static int longestSeq(int[] a){
+ Set s=new HashSet<>();
+ for(int x:a) s.add(x);
+ int best=0;
+ for(int x:s)
+ if(!s.contains(x-1)){
+ int y=x;
+ while(s.contains(y)) y++;
+ best=Math.max(best,y-x);
+ }
+ return best;
+}",12,12
+,"// Define the Singleton class
+public class Singleton {
+ // Private static variable to hold the single instance
+ private static Singleton singleInstance = null;
+
+ // Private constructor to prevent instantiation
+ private Singleton() {
+ // Print a message indicating the creation of the instance
+ System.out.println(""Singleton instance created."");
+ }
+
+ // Public static method to get the single instance of the class
+ public static Singleton getInstance() {
+ // If the single instance is null, create a new instance
+ if (singleInstance == null) {
+ singleInstance = new Singleton();
+ }
+ // Return the single instance
+ return singleInstance;
+ }
+
+ // Main method to test the Singleton class
+ public static void main(String[] args) {
+ // Get the single instance of Singleton
+ Singleton instance1 = Singleton.getInstance();
+ // Try to get another instance of Singleton
+ Singleton instance2 = Singleton.getInstance();
+
+ // Check if both instances are the same
+ if (instance1 == instance2) {
+ System.out.println(""Both instances are the same."");
+ } else {
+ System.out.println(""Instances are different."");
+ }
+ }
+}
",0.0,WE3RESOURCE,,JAVA,"// Define the Singleton class
+public class Singleton {
+ // Private static variable to hold the single instance
+ private static Singleton singleInstance = null;
+
+ // Private constructor to prevent instantiation
+ private Singleton() {
+ // Print a message indicating the creation of the instance
+ System.out.println(""Singleton instance created."");
+ }
+
+ // Public static method to get the single instance of the class
+ public static Singleton getInstance() {
+ // If the single instance is null, create a new instance
+ if (singleInstance == null) {
+ singleInstance = new Singleton();
+ }
+ // Return the single instance
+ return singleInstance;
+ }
+
+ // Main method to test the Singleton class
+ public static void main(String[] args) {
+ // Get the single instance of Singleton
+ Singleton instance1 = Singleton.getInstance();
+ // Try to get another instance of Singleton
+ Singleton instance2 = Singleton.getInstance();
+
+ // Check if both instances are the same
+ if (instance1 == instance2) {
+ System.out.println(""Both instances are the same."");
+ } else {
+ System.out.println(""Instances are different."");
+ }
+ }
+}",36,36
+,"static int[] prod(int[] a){
+ int n=a.length; int[] r=new int[n];
+ r[0]=1;
+ for(int i=1;i=0;i--){ r[i]*=p; p*=a[i]; }
+ return r;
+}
",1.0,GPT,Return an array where each element is product of all other elements without using division.,JAVA,"static int[] prod(int[] a){
+ int n=a.length; int[] r=new int[n];
+ r[0]=1;
+ for(int i=1;i=0;i--){ r[i]*=p; p*=a[i]; }
+ return r;
+}",8,8
+,"//IncrementThread.java
+public class IncrementThread extends Thread {
+ private Counter counter;
+ private int incrementsPerThread;
+ public IncrementThread(Counter counter, int incrementsPerThread) {
+ this.counter = counter;
+ this.incrementsPerThread = incrementsPerThread;
+ }
+ @Override
+ public void run() {
+ for (int i = 0; i < incrementsPerThread; i++) {
+ counter.increment();
+ }
+ }
+}
",0.0,WE3RESOURCE,,JAVA,"//IncrementThread.java
+public class IncrementThread extends Thread {
+ private Counter counter;
+ private int incrementsPerThread;
+ public IncrementThread(Counter counter, int incrementsPerThread) {
+ this.counter = counter;
+ this.incrementsPerThread = incrementsPerThread;
+ }
+ @Override
+ public void run() {
+ for (int i = 0; i < incrementsPerThread; i++) {
+ counter.increment();
+ }
+ }
+}",15,15
+,"static List anagrams(String s,String p){
+ int[] c=new int[26];
+ for(char x:p.toCharArray()) c[x-'a']++;
+ int l=0,r=0,cnt=p.length();
+ List res=new ArrayList<>();
+ while(r0) cnt--;
+ if(cnt==0) res.add(l);
+ if(r-l==p.length() && c[s.charAt(l++)-'a']++ >=0) cnt++;
+ }
+ return res;
+}
",1.0,GPT,Find all start indices of p's anagrams in s.,JAVA,"static List anagrams(String s,String p){
+ int[] c=new int[26];
+ for(char x:p.toCharArray()) c[x-'a']++;
+ int l=0,r=0,cnt=p.length();
+ List res=new ArrayList<>();
+ while(r0) cnt--;
+ if(cnt==0) res.add(l);
+ if(r-l==p.length() && c[s.charAt(l++)-'a']++ >=0) cnt++;
+ }
+ return res;
+}",12,12
+,"// ProducerConsumer.java
+import java.util.LinkedList;
+import java.util.Queue;
+
+public class ProducerConsumer {
+ private static final int BUFFER_SIZE = 5;
+ private static final Queue < Integer > buffer = new LinkedList < > ();
+
+ public static void main(String[] args) {
+ Thread producerThread = new Thread(new Producer());
+ Thread consumerThread = new Thread(new Consumer());
+
+ producerThread.start();
+ consumerThread.start();
+ }
+
+ static class Producer implements Runnable {
+ public void run() {
+ int value = 0;
+ while (true) {
+ synchronized(buffer) {
+ // Wait if the buffer is full
+ while (buffer.size() == BUFFER_SIZE) {
+ try {
+ buffer.wait();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+
+ System.out.println(""Producer produced: "" + value);
+ buffer.add(value++);
+
+ // Notify the consumer that an item is produced
+ buffer.notify();
+
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ }
+ }
+
+ static class Consumer implements Runnable {
+ public void run() {
+ while (true) {
+ synchronized(buffer) {
+ // Wait if the buffer is empty
+ while (buffer.isEmpty()) {
+ try {
+ buffer.wait();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+
+ int value = buffer.poll();
+ System.out.println(""Consumer consumed: "" + value);
+
+ // Notify the producer that an item is consumed
+ buffer.notify();
+
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ }
+ }
+}
",0.0,WE3RESOURCE,,JAVA,"// ProducerConsumer.java
+import java.util.LinkedList;
+import java.util.Queue;
+
+public class ProducerConsumer {
+ private static final int BUFFER_SIZE = 5;
+ private static final Queue < Integer > buffer = new LinkedList < > ();
+
+ public static void main(String[] args) {
+ Thread producerThread = new Thread(new Producer());
+ Thread consumerThread = new Thread(new Consumer());
+
+ producerThread.start();
+ consumerThread.start();
+ }
+
+ static class Producer implements Runnable {
+ public void run() {
+ int value = 0;
+ while (true) {
+ synchronized(buffer) {
+ // Wait if the buffer is full
+ while (buffer.size() == BUFFER_SIZE) {
+ try {
+ buffer.wait();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+
+ System.out.println(""Producer produced: "" + value);
+ buffer.add(value++);
+
+ // Notify the consumer that an item is produced
+ buffer.notify();
+
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ }
+ }
+
+ static class Consumer implements Runnable {
+ public void run() {
+ while (true) {
+ synchronized(buffer) {
+ // Wait if the buffer is empty
+ while (buffer.isEmpty()) {
+ try {
+ buffer.wait();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+
+ int value = buffer.poll();
+ System.out.println(""Consumer consumed: "" + value);
+
+ // Notify the producer that an item is consumed
+ buffer.notify();
+
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ }
+ }
+}",75,75
+,"static int[][] kClose(int[][] p,int k){
+ PriorityQueue q=new PriorityQueue<>(
+ (a,b)->b[0]*b[0]+b[1]*b[1]-a[0]*a[0]-a[1]*a[1]);
+ for(int[] x:p){ q.add(x); if(q.size()>k) q.poll(); }
+ return q.toArray(new int[k][2]);
+}
",1.0,GPT,"WRITE A JAVA PROGRAM WHERE THE Given points in 2D, return k closest points to origin.",JAVA,"static int[][] kClose(int[][] p,int k){
+ PriorityQueue q=new PriorityQueue<>(
+ (a,b)->b[0]*b[0]+b[1]*b[1]-a[0]*a[0]-a[1]*a[1]);
+ for(int[] x:p){ q.add(x); if(q.size()>k) q.poll(); }
+ return q.toArray(new int[k][2]);
+}",6,6
+,"// SharedResourceExercise.java
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
+public class SharedResourceExercise {
+ private static final int NUM_THREADS = 3;
+ private static final int NUM_ITERATIONS = 5;
+
+ public static void main(String[] args) {
+ Lock lock = new ReentrantLock();
+ SharedResource sharedResource = new SharedResource();
+
+ Thread[] threads = new Thread[NUM_THREADS];
+ for (int i = 0; i < NUM_THREADS; i++) {
+ threads[i] = new Thread(new Worker(lock, sharedResource));
+ threads[i].start();
+ }
+
+ try {
+ for (Thread thread: threads) {
+ thread.join();
+ }
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+
+ static class Worker implements Runnable {
+ private Lock lock;
+ private SharedResource sharedResource;
+
+ public Worker(Lock lock, SharedResource sharedResource) {
+ this.lock = lock;
+ this.sharedResource = sharedResource;
+ }
+
+ public void run() {
+ for (int i = 0; i < NUM_ITERATIONS; i++) {
+ lock.lock();
+ try {
+ sharedResource.doWork();
+ } finally {
+ lock.unlock();
+ }
+ }
+ }
+ }
+
+ static class SharedResource {
+ public void doWork() {
+ String threadName = Thread.currentThread().getName();
+ System.out.println(""Thread-> "" + threadName + "" is performing work."");
+ // Perform work on the shared resource
+ }
+ }
+}
",0.0,WE3RESOURCE,,JAVA,"// SharedResourceExercise.java
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
+public class SharedResourceExercise {
+ private static final int NUM_THREADS = 3;
+ private static final int NUM_ITERATIONS = 5;
+
+ public static void main(String[] args) {
+ Lock lock = new ReentrantLock();
+ SharedResource sharedResource = new SharedResource();
+
+ Thread[] threads = new Thread[NUM_THREADS];
+ for (int i = 0; i < NUM_THREADS; i++) {
+ threads[i] = new Thread(new Worker(lock, sharedResource));
+ threads[i].start();
+ }
+
+ try {
+ for (Thread thread: threads) {
+ thread.join();
+ }
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+
+ static class Worker implements Runnable {
+ private Lock lock;
+ private SharedResource sharedResource;
+
+ public Worker(Lock lock, SharedResource sharedResource) {
+ this.lock = lock;
+ this.sharedResource = sharedResource;
+ }
+
+ public void run() {
+ for (int i = 0; i < NUM_ITERATIONS; i++) {
+ lock.lock();
+ try {
+ sharedResource.doWork();
+ } finally {
+ lock.unlock();
+ }
+ }
+ }
+ }
+
+ static class SharedResource {
+ public void doWork() {
+ String threadName = Thread.currentThread().getName();
+ System.out.println(""Thread-> "" + threadName + "" is performing work."");
+ // Perform work on the shared resource
+ }
+ }
+}",56,56
+,"static String decode(String s){
+ Stack n=new Stack<>();
+ Stack st=new Stack<>();
+ String cur=""""; int k=0;
+ for(char c:s.toCharArray()){
+ if(Character.isDigit(c)) k=k*10+c-'0';
+ else if(c=='['){ n.push(k); st.push(cur); k=0; cur=""""; }
+ else if(c==']'){ cur=st.pop()+cur.repeat(n.pop()); }
+ else cur+=c;
+ }
+ return cur;
+}
",1.0,GPT,"write a java program toDecode strings like ""3[a2[c]]"" → ""accaccacc"".",JAVA,"static String decode(String s){
+ Stack n=new Stack<>();
+ Stack st=new Stack<>();
+ String cur=""""; int k=0;
+ for(char c:s.toCharArray()){
+ if(Character.isDigit(c)) k=k*10+c-'0';
+ else if(c=='['){ n.push(k); st.push(cur); k=0; cur=""""; }
+ else if(c==']'){ cur=st.pop()+cur.repeat(n.pop()); }
+ else cur+=c;
+ }
+ return cur;
+}",12,12
+,"//SemaphoreExercise.java
+import java.util.concurrent.Semaphore;
+
+public class SemaphoreExercise {
+ private static final int NUM_THREADS = 5;
+ private static final int NUM_PERMITS = 2;
+
+ public static void main(String[] args) {
+ Semaphore semaphore = new Semaphore(NUM_PERMITS);
+
+ Thread[] threads = new Thread[NUM_THREADS];
+ for (int i = 0; i < NUM_THREADS; i++) {
+ threads[i] = new Thread(new Worker(semaphore));
+ threads[i].start();
+ }
+
+ try {
+ for (Thread thread: threads) {
+ thread.join();
+ }
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+
+ static class Worker implements Runnable {
+ private Semaphore semaphore;
+
+ public Worker(Semaphore semaphore) {
+ this.semaphore = semaphore;
+ }
+
+ public void run() {
+ try {
+ semaphore.acquire();
+
+ // Perform work that requires the semaphore
+ System.out.println(""Thread "" + Thread.currentThread().getName() + "" acquired the semaphore."");
+ Thread.sleep(2000); // Simulating work
+ System.out.println(""Thread "" + Thread.currentThread().getName() + "" released the semaphore."");
+
+ semaphore.release();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+}
",0.0,WE3RESOURCE,,JAVA,"//SemaphoreExercise.java
+import java.util.concurrent.Semaphore;
+
+public class SemaphoreExercise {
+ private static final int NUM_THREADS = 5;
+ private static final int NUM_PERMITS = 2;
+
+ public static void main(String[] args) {
+ Semaphore semaphore = new Semaphore(NUM_PERMITS);
+
+ Thread[] threads = new Thread[NUM_THREADS];
+ for (int i = 0; i < NUM_THREADS; i++) {
+ threads[i] = new Thread(new Worker(semaphore));
+ threads[i].start();
+ }
+
+ try {
+ for (Thread thread: threads) {
+ thread.join();
+ }
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+
+ static class Worker implements Runnable {
+ private Semaphore semaphore;
+
+ public Worker(Semaphore semaphore) {
+ this.semaphore = semaphore;
+ }
+
+ public void run() {
+ try {
+ semaphore.acquire();
+
+ // Perform work that requires the semaphore
+ System.out.println(""Thread "" + Thread.currentThread().getName() + "" acquired the semaphore."");
+ Thread.sleep(2000); // Simulating work
+ System.out.println(""Thread "" + Thread.currentThread().getName() + "" released the semaphore."");
+
+ semaphore.release();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+}",48,48
+,"static boolean canFinish(int n,int[][] p){
+ List[] g=new ArrayList[n];
+ for(int i=0;i();
+ int[] in=new int[n];
+ for(int[] e:p){ g[e[1]].add(e[0]); in[e[0]]++; }
+ Queue q=new LinkedList<>();
+ for(int i=0;i[] g=new ArrayList[n];
+ for(int i=0;i();
+ int[] in=new int[n];
+ for(int[] e:p){ g[e[1]].add(e[0]); in[e[0]]++; }
+ Queue q=new LinkedList<>();
+ for(int i=0;i q){
+ String s=q.poll();
+ if(s.equals(""#"")) return null;
+ Node n=new Node(Integer.parseInt(s));
+ n.left=des(q); n.right=des(q);
+ return n;
+}
",1.0,GPT,Convert binary tree to string and restore it.,JAVA,"static void ser(Node r,StringBuilder b){
+ if(r==null){b.append(""#,"");return;}
+ b.append(r.val).append("","");
+ ser(r.left,b); ser(r.right,b);
+}
+static Node des(Queue q){
+ String s=q.poll();
+ if(s.equals(""#"")) return null;
+ Node n=new Node(Integer.parseInt(s));
+ n.left=des(q); n.right=des(q);
+ return n;
+}",12,12
+,"import java.util.concurrent.CountDownLatch;
+
+public class CountDownLatchExercise {
+ private static final int NUM_THREADS = 3;
+ private static final CountDownLatch startLatch = new CountDownLatch(1);
+ private static final CountDownLatch finishLatch = new CountDownLatch(NUM_THREADS);
+
+ public static void main(String[] args) {
+ Thread[] threads = new Thread[NUM_THREADS];
+ for (int i = 0; i < NUM_THREADS; i++) {
+ threads[i] = new Thread(new Worker());
+ threads[i].start();
+ }
+
+ // Allow threads to start simultaneously
+ startLatch.countDown();
+
+ try {
+ finishLatch.await();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+
+ System.out.println(""All threads have finished their work."");
+ }
+
+ static class Worker implements Runnable {
+ public void run() {
+ try {
+ startLatch.await();
+
+ // Perform work
+
+ System.out.println(""Thread "" + Thread.currentThread().getName() + "" has finished its work."");
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ } finally {
+ finishLatch.countDown();
+ }
+ }
+ }
+}
",0.0,WE3RESOURCE,,JAVA,"import java.util.concurrent.CountDownLatch;
+
+public class CountDownLatchExercise {
+ private static final int NUM_THREADS = 3;
+ private static final CountDownLatch startLatch = new CountDownLatch(1);
+ private static final CountDownLatch finishLatch = new CountDownLatch(NUM_THREADS);
+
+ public static void main(String[] args) {
+ Thread[] threads = new Thread[NUM_THREADS];
+ for (int i = 0; i < NUM_THREADS; i++) {
+ threads[i] = new Thread(new Worker());
+ threads[i].start();
+ }
+
+ // Allow threads to start simultaneously
+ startLatch.countDown();
+
+ try {
+ finishLatch.await();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+
+ System.out.println(""All threads have finished their work."");
+ }
+
+ static class Worker implements Runnable {
+ public void run() {
+ try {
+ startLatch.await();
+
+ // Perform work
+
+ System.out.println(""Thread "" + Thread.currentThread().getName() + "" has finished its work."");
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ } finally {
+ finishLatch.countDown();
+ }
+ }
+ }
+}",42,42
+,"static String minWin(String s,String t){
+ int[] c=new int[128]; for(char x:t.toCharArray()) c[x]++;
+ int l=0,start=0,min=Integer.MAX_VALUE,need=t.length();
+ for(int r=0;r0) need--;
+ while(need==0){
+ if(r-l+10) need--;
+ while(need==0){
+ if(r-l+1 w){
+ Set s=new HashSet<>(w); Queue q=new LinkedList<>();
+ q.add(b); int lvl=1;
+ while(!q.isEmpty()){
+ for(int i=q.size();i>0;i--){
+ String x=q.poll();
+ if(x.equals(e)) return lvl;
+ for(int j=0;j w){
+ Set s=new HashSet<>(w); Queue q=new LinkedList<>();
+ q.add(b); int lvl=1;
+ while(!q.isEmpty()){
+ for(int i=q.size();i>0;i--){
+ String x=q.poll();
+ if(x.equals(e)) return lvl;
+ for(int j=0;j map = new ConcurrentHashMap < > ();
+
+ // Create and start the writer threads
+ Thread writerThread1 = new Thread(new Writer(map, ""Thread-1"", 1));
+ Thread writerThread2 = new Thread(new Writer(map, ""Thread-2"", 2));
+ writerThread1.start();
+ writerThread2.start();
+
+ // Create and start the reader threads
+ Thread readerThread1 = new Thread(new Reader(map, ""Thread-1""));
+ Thread readerThread2 = new Thread(new Reader(map, ""Thread-2""));
+ readerThread1.start();
+ readerThread2.start();
+ }
+
+ static class Writer implements Runnable {
+ private ConcurrentHashMap < String, Integer > map;
+ private String threadName;
+ private int value;
+
+ public Writer(ConcurrentHashMap < String, Integer > map, String threadName, int value) {
+ this.map = map;
+ this.threadName = threadName;
+ this.value = value;
+ }
+
+ public void run() {
+ for (int i = 0; i < 5; i++) {
+ map.put(threadName, value);
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ }
+
+ static class Reader implements Runnable {
+ private ConcurrentHashMap < String, Integer > map;
+ private String threadName;
+
+ public Reader(ConcurrentHashMap < String, Integer > map, String threadName) {
+ this.map = map;
+ this.threadName = threadName;
+ }
+
+ public void run() {
+ for (int i = 0; i < 5; i++) {
+ Integer value = map.get(threadName);
+ System.out.println(""Thread "" + threadName + "" read value: "" + value);
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ }
+}
",0.0,WE3RESOURCE,,JAVA,"import java.util.concurrent.ConcurrentHashMap;
+
+public class ConcurrentHashMapExercise {
+ public static void main(String[] args) {
+ ConcurrentHashMap < String, Integer > map = new ConcurrentHashMap < > ();
+
+ // Create and start the writer threads
+ Thread writerThread1 = new Thread(new Writer(map, ""Thread-1"", 1));
+ Thread writerThread2 = new Thread(new Writer(map, ""Thread-2"", 2));
+ writerThread1.start();
+ writerThread2.start();
+
+ // Create and start the reader threads
+ Thread readerThread1 = new Thread(new Reader(map, ""Thread-1""));
+ Thread readerThread2 = new Thread(new Reader(map, ""Thread-2""));
+ readerThread1.start();
+ readerThread2.start();
+ }
+
+ static class Writer implements Runnable {
+ private ConcurrentHashMap < String, Integer > map;
+ private String threadName;
+ private int value;
+
+ public Writer(ConcurrentHashMap < String, Integer > map, String threadName, int value) {
+ this.map = map;
+ this.threadName = threadName;
+ this.value = value;
+ }
+
+ public void run() {
+ for (int i = 0; i < 5; i++) {
+ map.put(threadName, value);
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ }
+
+ static class Reader implements Runnable {
+ private ConcurrentHashMap < String, Integer > map;
+ private String threadName;
+
+ public Reader(ConcurrentHashMap < String, Integer > map, String threadName) {
+ this.map = map;
+ this.threadName = threadName;
+ }
+
+ public void run() {
+ for (int i = 0; i < 5; i++) {
+ Integer value = map.get(threadName);
+ System.out.println(""Thread "" + threadName + "" read value: "" + value);
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ }
+}",64,64
+,"static int maxRect(int[] h){
+ Stack s=new Stack<>(); int max=0;
+ for(int i=0;i<=h.length;i++){
+ int cur=i==h.length?0:h[i];
+ while(!s.isEmpty()&&cur s=new Stack<>(); int max=0;
+ for(int i=0;i<=h.length;i++){
+ int cur=i==h.length?0:h[i];
+ while(!s.isEmpty()&&cur queue = new ConcurrentLinkedQueue < > ();
+
+ // Create and start the producer threads
+ Thread producerThread1 = new Thread(new Producer(queue, ""Producer-1""));
+ Thread producerThread2 = new Thread(new Producer(queue, ""Producer-2""));
+ producerThread1.start();
+ producerThread2.start();
+
+ // Create and start the consumer threads
+ Thread consumerThread1 = new Thread(new Consumer(queue, ""Consumer-1""));
+ Thread consumerThread2 = new Thread(new Consumer(queue, ""Consumer-2""));
+ consumerThread1.start();
+ consumerThread2.start();
+ }
+
+ static class Producer implements Runnable {
+ private ConcurrentLinkedQueue < String > queue;
+ private String producerName;
+ private int counter;
+
+ public Producer(ConcurrentLinkedQueue < String > queue, String producerName) {
+ this.queue = queue;
+ this.producerName = producerName;
+ this.counter = 0;
+ }
+
+ public void run() {
+ while (true) {
+ String item = producerName + ""-Item-"" + counter++;
+ queue.offer(item);
+ System.out.println(""Produced: "" + item);
+
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ }
+
+ static class Consumer implements Runnable {
+ private ConcurrentLinkedQueue < String > queue;
+ private String consumerName;
+
+ public Consumer(ConcurrentLinkedQueue < String > queue, String consumerName) {
+ this.queue = queue;
+ this.consumerName = consumerName;
+ }
+
+ public void run() {
+ while (true) {
+ String item = queue.poll();
+ if (item != null) {
+ System.out.println(consumerName + "" consumed: "" + item);
+ }
+
+ try {
+ Thread.sleep(1500);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ }
+}
",0.0,WE3RESOURCE,,JAVA,"import java.util.concurrent.ConcurrentLinkedQueue;
+
+public class ConcurrentQueueExercise {
+ public static void main(String[] args) {
+ ConcurrentLinkedQueue < String > queue = new ConcurrentLinkedQueue < > ();
+
+ // Create and start the producer threads
+ Thread producerThread1 = new Thread(new Producer(queue, ""Producer-1""));
+ Thread producerThread2 = new Thread(new Producer(queue, ""Producer-2""));
+ producerThread1.start();
+ producerThread2.start();
+
+ // Create and start the consumer threads
+ Thread consumerThread1 = new Thread(new Consumer(queue, ""Consumer-1""));
+ Thread consumerThread2 = new Thread(new Consumer(queue, ""Consumer-2""));
+ consumerThread1.start();
+ consumerThread2.start();
+ }
+
+ static class Producer implements Runnable {
+ private ConcurrentLinkedQueue < String > queue;
+ private String producerName;
+ private int counter;
+
+ public Producer(ConcurrentLinkedQueue < String > queue, String producerName) {
+ this.queue = queue;
+ this.producerName = producerName;
+ this.counter = 0;
+ }
+
+ public void run() {
+ while (true) {
+ String item = producerName + ""-Item-"" + counter++;
+ queue.offer(item);
+ System.out.println(""Produced: "" + item);
+
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ }
+
+ static class Consumer implements Runnable {
+ private ConcurrentLinkedQueue < String > queue;
+ private String consumerName;
+
+ public Consumer(ConcurrentLinkedQueue < String > queue, String consumerName) {
+ this.queue = queue;
+ this.consumerName = consumerName;
+ }
+
+ public void run() {
+ while (true) {
+ String item = queue.poll();
+ if (item != null) {
+ System.out.println(consumerName + "" consumed: "" + item);
+ }
+
+ try {
+ Thread.sleep(1500);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ }
+}",70,70
+,"static int max=Integer.MIN_VALUE;
+static int path(Node n){
+ if(n==null) return 0;
+ int l=Math.max(0,path(n.left)), r=Math.max(0,path(n.right));
+ max=Math.max(max,l+r+n.val);
+ return Math.max(l,r)+n.val;
+}
",1.0,GPT,write a java program to Find max sum of any path in tree.,JAVA,"static int max=Integer.MIN_VALUE;
+static int path(Node n){
+ if(n==null) return 0;
+ int l=Math.max(0,path(n.left)), r=Math.max(0,path(n.right));
+ max=Math.max(max,l+r+n.val);
+ return Math.max(l,r)+n.val;
+}",7,7
+,"import java.util.concurrent.Phaser;
+
+public class PhaserExercise {
+
+ public static void main(String[] args) {
+ // Create a Phaser with 4 registered parties
+ Phaser phaser = new Phaser(4);
+
+ // Create and start three worker threads
+ Thread thread1 = new Thread(new Worker(phaser, ""Thread 1""));
+ Thread thread2 = new Thread(new Worker(phaser, ""Thread 2""));
+ Thread thread3 = new Thread(new Worker(phaser, ""Thread 3""));
+ Thread thread4 = new Thread(new Worker(phaser, ""Thread 4""));
+ thread1.start();
+ thread2.start();
+ thread3.start();
+ thread4.start();
+
+ // Wait for all threads to complete
+ phaser.awaitAdvance(phaser.getPhase());
+
+ System.out.println(""All threads have completed their tasks."");
+ }
+
+ static class Worker implements Runnable {
+ private final Phaser phaser;
+ private final String name;
+
+ public Worker(Phaser phaser, String name) {
+ this.phaser = phaser;
+ this.name = name;
+ }
+
+ @Override
+ public void run() {
+ System.out.println(name + "" starting phase 1"");
+ phaser.arriveAndAwaitAdvance(); // Wait for all threads to reach this point
+
+ // Perform phase 1 tasks
+ System.out.println(name + "" performing phase 1 tasks"");
+
+ // Wait for all threads to complete phase 1
+ phaser.arriveAndAwaitAdvance();
+
+ System.out.println(name + "" starting phase 2"");
+ phaser.arriveAndAwaitAdvance(); // Wait for all threads to reach this point
+
+ // Perform phase 2 tasks
+ System.out.println(name + "" performing phase 2 tasks"");
+
+ // Wait for all threads to complete phase 2
+ phaser.arriveAndAwaitAdvance();
+
+ System.out.println(name + "" completed all phases"");
+ phaser.arriveAndDeregister(); // Deregister from the Phaser
+ }
+ }
+}
",0.0,WE3RESOURCE,,JAVA,"import java.util.concurrent.Phaser;
+
+public class PhaserExercise {
+
+ public static void main(String[] args) {
+ // Create a Phaser with 4 registered parties
+ Phaser phaser = new Phaser(4);
+
+ // Create and start three worker threads
+ Thread thread1 = new Thread(new Worker(phaser, ""Thread 1""));
+ Thread thread2 = new Thread(new Worker(phaser, ""Thread 2""));
+ Thread thread3 = new Thread(new Worker(phaser, ""Thread 3""));
+ Thread thread4 = new Thread(new Worker(phaser, ""Thread 4""));
+ thread1.start();
+ thread2.start();
+ thread3.start();
+ thread4.start();
+
+ // Wait for all threads to complete
+ phaser.awaitAdvance(phaser.getPhase());
+
+ System.out.println(""All threads have completed their tasks."");
+ }
+
+ static class Worker implements Runnable {
+ private final Phaser phaser;
+ private final String name;
+
+ public Worker(Phaser phaser, String name) {
+ this.phaser = phaser;
+ this.name = name;
+ }
+
+ @Override
+ public void run() {
+ System.out.println(name + "" starting phase 1"");
+ phaser.arriveAndAwaitAdvance(); // Wait for all threads to reach this point
+
+ // Perform phase 1 tasks
+ System.out.println(name + "" performing phase 1 tasks"");
+
+ // Wait for all threads to complete phase 1
+ phaser.arriveAndAwaitAdvance();
+
+ System.out.println(name + "" starting phase 2"");
+ phaser.arriveAndAwaitAdvance(); // Wait for all threads to reach this point
+
+ // Perform phase 2 tasks
+ System.out.println(name + "" performing phase 2 tasks"");
+
+ // Wait for all threads to complete phase 2
+ phaser.arriveAndAwaitAdvance();
+
+ System.out.println(name + "" completed all phases"");
+ phaser.arriveAndDeregister(); // Deregister from the Phaser
+ }
+ }
+}",58,58
+,"static String alien(String[] w){
+ Map> g=new HashMap<>();
+ Map in=new HashMap<>();
+ for(String s:w) for(char c:s.toCharArray()){g.putIfAbsent(c,new HashSet<>());in.putIfAbsent(c,0);}
+ for(int i=0;i q=new LinkedList<>();
+ for(char c:in.keySet()) if(in.get(c)==0) q.add(c);
+ StringBuilder r=new StringBuilder();
+ while(!q.isEmpty()){
+ char c=q.poll(); r.append(c);
+ for(char n:g.get(c)) if(in.put(n,in.get(n)-1)==1) q.add(n);
+ }
+ return r.toString();
+}
",1.0,GPT,give me an java code to Find character order from sorted alien words.,JAVA,"static String alien(String[] w){
+ Map> g=new HashMap<>();
+ Map in=new HashMap<>();
+ for(String s:w) for(char c:s.toCharArray()){g.putIfAbsent(c,new HashSet<>());in.putIfAbsent(c,0);}
+ for(int i=0;i q=new LinkedList<>();
+ for(char c:in.keySet()) if(in.get(c)==0) q.add(c);
+ StringBuilder r=new StringBuilder();
+ while(!q.isEmpty()){
+ char c=q.poll(); r.append(c);
+ for(char n:g.get(c)) if(in.put(n,in.get(n)-1)==1) q.add(n);
+ }
+ return r.toString();
+}",20,20
+,"import java.util.concurrent.Exchanger;
+
+public class ExchangerExercise {
+
+ public static void main(String[] args) {
+ Exchanger < String > exchanger = new Exchanger < > ();
+
+ // Create and start two worker threads
+ Thread thread1 = new Thread(new Worker(exchanger, ""Data from Thread 1""));
+ Thread thread2 = new Thread(new Worker(exchanger, ""Data from Thread 2""));
+ thread1.start();
+ thread2.start();
+ }
+
+ static class Worker implements Runnable {
+ private final Exchanger < String > exchanger;
+ private final String data;
+
+ public Worker(Exchanger < String > exchanger, String data) {
+ this.exchanger = exchanger;
+ this.data = data;
+ }
+
+ @Override
+ public void run() {
+ try {
+ System.out.println(Thread.currentThread().getName() + "" sending data: "" + data);
+ String receivedData = exchanger.exchange(data); // Exchange data with the other thread
+
+ System.out.println(Thread.currentThread().getName() + "" received data: "" + receivedData);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+}
",0.0,WE3RESOURCE,,JAVA,"import java.util.concurrent.Exchanger;
+
+public class ExchangerExercise {
+
+ public static void main(String[] args) {
+ Exchanger < String > exchanger = new Exchanger < > ();
+
+ // Create and start two worker threads
+ Thread thread1 = new Thread(new Worker(exchanger, ""Data from Thread 1""));
+ Thread thread2 = new Thread(new Worker(exchanger, ""Data from Thread 2""));
+ thread1.start();
+ thread2.start();
+ }
+
+ static class Worker implements Runnable {
+ private final Exchanger < String > exchanger;
+ private final String data;
+
+ public Worker(Exchanger < String > exchanger, String data) {
+ this.exchanger = exchanger;
+ this.data = data;
+ }
+
+ @Override
+ public void run() {
+ try {
+ System.out.println(Thread.currentThread().getName() + "" sending data: "" + data);
+ String receivedData = exchanger.exchange(data); // Exchange data with the other thread
+
+ System.out.println(Thread.currentThread().getName() + "" received data: "" + receivedData);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+}",36,36
+,"static boolean dfs(char[][] b,int i,int j,String w,int k){
+ if(k==w.length()) return true;
+ if(i<0||j<0||i==b.length||j==b[0].length||b[i][j]!=w.charAt(k)) return false;
+ char t=b[i][j]; b[i][j]='#';
+ boolean r=dfs(b,i+1,j,w,k+1)||dfs(b,i-1,j,w,k+1)||dfs(b,i,j+1,w,k+1)||dfs(b,i,j-1,w,k+1);
+ b[i][j]=t; return r;
+}
",1.0,GPT,give me an efficient java code to Find if word exists in grid using DFS + Trie.,JAVA,"static boolean dfs(char[][] b,int i,int j,String w,int k){
+ if(k==w.length()) return true;
+ if(i<0||j<0||i==b.length||j==b[0].length||b[i][j]!=w.charAt(k)) return false;
+ char t=b[i][j]; b[i][j]='#';
+ boolean r=dfs(b,i+1,j,w,k+1)||dfs(b,i-1,j,w,k+1)||dfs(b,i,j+1,w,k+1)||dfs(b,i,j-1,w,k+1);
+ b[i][j]=t; return r;
+}",7,7
+,"import java.util.concurrent.*;
+
+public class CallableFutureExercise {
+
+ public static void main(String[] args) {
+ // Create a thread pool with a single worker thread
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+
+ // Submit a Callable task to the executor
+ Future < String > future = executor.submit(new Task());
+
+ // Perform other operations while the task is executing
+
+ try {
+ // Wait for the task to complete and get the result
+ String result = future.get();
+
+ System.out.println(""Task result: "" + result);
+ } catch (InterruptedException | ExecutionException e) {
+ e.printStackTrace();
+ }
+
+ // Shutdown the executor
+ executor.shutdown();
+ }
+
+ static class Task implements Callable < String > {
+ @Override
+ public String call() throws Exception {
+ // Perform the task and return the result
+ Thread.sleep(2000); // Simulate some time-consuming operation
+ return ""Task completed!"";
+ }
+ }
+}
",0.0,WE3RESOURCE,,JAVA,"import java.util.concurrent.*;
+
+public class CallableFutureExercise {
+
+ public static void main(String[] args) {
+ // Create a thread pool with a single worker thread
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+
+ // Submit a Callable task to the executor
+ Future < String > future = executor.submit(new Task());
+
+ // Perform other operations while the task is executing
+
+ try {
+ // Wait for the task to complete and get the result
+ String result = future.get();
+
+ System.out.println(""Task result: "" + result);
+ } catch (InterruptedException | ExecutionException e) {
+ e.printStackTrace();
+ }
+
+ // Shutdown the executor
+ executor.shutdown();
+ }
+
+ static class Task implements Callable < String > {
+ @Override
+ public String call() throws Exception {
+ // Perform the task and return the result
+ Thread.sleep(2000); // Simulate some time-consuming operation
+ return ""Task completed!"";
+ }
+ }
+}",35,35
+,"static int[] redundant(int[][] e){
+ int[] p=new int[1001];
+ for(int i=1;i {
+ private final int[] array;
+ private final int start;
+ private final int end;
+
+ public SumTask(int[] array, int start, int end) {
+ this.array = array;
+ this.start = start;
+ this.end = end;
+ }
+
+ @Override
+ protected Integer compute() {
+ if (end - start <= 2) {
+ int sum = 0;
+ for (int i = start; i < end; i++) {
+ sum += array[i];
+ }
+ return sum;
+ } else {
+ int mid = start + (end - start) / 2;
+
+ SumTask leftTask = new SumTask(array, start, mid);
+ SumTask rightTask = new SumTask(array, mid, end);
+
+ invokeAll(leftTask, rightTask);
+
+ return leftTask.join() + rightTask.join();
+ }
+ }
+ }
+}
",0.0,WE3RESOURCE,,JAVA,"import java.util.concurrent.ForkJoinPool;
+import java.util.concurrent.RecursiveTask;
+
+public class ForkJoinPoolExercise {
+
+ public static void main(String[] args) {
+ int[] array = {
+ 1,
+ 2,
+ 3,
+ 4,
+ 5,
+ 6,
+ 7,
+ 8,
+ 9,
+ 10
+ };
+
+ ForkJoinPool forkJoinPool = new ForkJoinPool();
+
+ int sum = forkJoinPool.invoke(new SumTask(array, 0, array.length));
+
+ System.out.println(""Sum: "" + sum);
+ }
+
+ static class SumTask extends RecursiveTask < Integer > {
+ private final int[] array;
+ private final int start;
+ private final int end;
+
+ public SumTask(int[] array, int start, int end) {
+ this.array = array;
+ this.start = start;
+ this.end = end;
+ }
+
+ @Override
+ protected Integer compute() {
+ if (end - start <= 2) {
+ int sum = 0;
+ for (int i = start; i < end; i++) {
+ sum += array[i];
+ }
+ return sum;
+ } else {
+ int mid = start + (end - start) / 2;
+
+ SumTask leftTask = new SumTask(array, start, mid);
+ SumTask rightTask = new SumTask(array, mid, end);
+
+ invokeAll(leftTask, rightTask);
+
+ return leftTask.join() + rightTask.join();
+ }
+ }
+ }
+}",58,58
+,"static int decodeWays(String s){
+ if(s.charAt(0)=='0') return 0;
+ int a=1,b=1;
+ for(int i=1;i=10&&x<=26) c+=a;
+ a=b; b=c;
+ } return b;
+}
",1.0,GPT,"You are given a string s containing only digits ('0'–'9') that represents an encoded message where:
+
+'A' → ""1""
+
+'B' → ""2""
+
+...
+
+'Z' → ""26""
+
+Write a java function to determine how many different ways the string can be decoded into letters.",JAVA,"static int decodeWays(String s){
+ if(s.charAt(0)=='0') return 0;
+ int a=1,b=1;
+ for(int i=1;i=10&&x<=26) c+=a;
+ a=b; b=c;
+ } return b;
+}",11,11
+,"import java.util.concurrent.locks.StampedLock;
+
+public class StampedLockExercise {
+
+ public static void main(String[] args) {
+ SharedResource sharedResource = new SharedResource();
+
+ // Start multiple reader threads
+ for (int i = 0; i < 5; i++) {
+ new Thread(() -> {
+ int value = sharedResource.getValue();
+ System.out.println(""Reader thread: "" + Thread.currentThread().getName() + "", value: "" + value);
+ }).start();
+ }
+
+ // Start a writer thread
+ new Thread(() -> {
+ sharedResource.setValue(42);
+ System.out.println(""Writer thread: "" + Thread.currentThread().getName() + "" set value to 42"");
+ }).start();
+ }
+
+ static class SharedResource {
+ private int value;
+ private final StampedLock lock = new StampedLock();
+
+ public int getValue() {
+ long stamp = lock.tryOptimisticRead(); // Optimistically acquire a read lock
+
+ int currentValue = value;
+
+ if (!lock.validate(stamp)) { // Check for concurrent write
+ stamp = lock.readLock(); // Upgrade to a read lock
+ try {
+ currentValue = value;
+ } finally {
+ lock.unlockRead(stamp); // Release the read lock
+ }
+ }
+
+ return currentValue;
+ }
+
+ public void setValue(int value) {
+ long stamp = lock.writeLock(); // Acquire a write lock
+
+ try {
+ this.value = value;
+ } finally {
+ lock.unlockWrite(stamp); // Release the write lock
+ }
+ }
+ }
+}
",0.0,WE3RESOURCE,,JAVA,"import java.util.concurrent.locks.StampedLock;
+
+public class StampedLockExercise {
+
+ public static void main(String[] args) {
+ SharedResource sharedResource = new SharedResource();
+
+ // Start multiple reader threads
+ for (int i = 0; i < 5; i++) {
+ new Thread(() -> {
+ int value = sharedResource.getValue();
+ System.out.println(""Reader thread: "" + Thread.currentThread().getName() + "", value: "" + value);
+ }).start();
+ }
+
+ // Start a writer thread
+ new Thread(() -> {
+ sharedResource.setValue(42);
+ System.out.println(""Writer thread: "" + Thread.currentThread().getName() + "" set value to 42"");
+ }).start();
+ }
+
+ static class SharedResource {
+ private int value;
+ private final StampedLock lock = new StampedLock();
+
+ public int getValue() {
+ long stamp = lock.tryOptimisticRead(); // Optimistically acquire a read lock
+
+ int currentValue = value;
+
+ if (!lock.validate(stamp)) { // Check for concurrent write
+ stamp = lock.readLock(); // Upgrade to a read lock
+ try {
+ currentValue = value;
+ } finally {
+ lock.unlockRead(stamp); // Release the read lock
+ }
+ }
+
+ return currentValue;
+ }
+
+ public void setValue(int value) {
+ long stamp = lock.writeLock(); // Acquire a write lock
+
+ try {
+ this.value = value;
+ } finally {
+ lock.unlockWrite(stamp); // Release the write lock
+ }
+ }
+ }
+}",54,54
+,"static int dfs(int[][] m,int i,int j,int[][] d){
+ if(d[i][j]>0) return d[i][j];
+ int r=1;
+ for(int[] x:new int[][]{{1,0},{-1,0},{0,1},{0,-1}}){
+ int a=i+x[0],b=j+x[1];
+ if(a>=0&&b>=0&&am[i][j])
+ r=Math.max(r,1+dfs(m,a,b,d));
+ }
+ return d[i][j]=r;
+}
",1.0,GPT,"You are given an m x n integer matrix matrix.
+From any cell, you can move up, down, left, or right to another cell only if the next cell has a strictly larger value.
+
+Write a java function that returns the length of the longest strictly increasing path in the matrix.",JAVA,"static int dfs(int[][] m,int i,int j,int[][] d){
+ if(d[i][j]>0) return d[i][j];
+ int r=1;
+ for(int[] x:new int[][]{{1,0},{-1,0},{0,1},{0,-1}}){
+ int a=i+x[0],b=j+x[1];
+ if(a>=0&&b>=0&&am[i][j])
+ r=Math.max(r,1+dfs(m,a,b,d));
+ }
+ return d[i][j]=r;
+}",10,10
+,"public int romanToInt(String s) {
+ int ans = 0, num = 0;
+ for (int i = s.length()-1; i >= 0; i--) {
+ switch(s.charAt(i)) {
+ case 'I': num = 1; break;
+ case 'V': num = 5; break;
+ case 'X': num = 10; break;
+ case 'L': num = 50; break;
+ case 'C': num = 100; break;
+ case 'D': num = 500; break;
+ case 'M': num = 1000; break;
+ }
+ if (4 * num < ans) ans -= num;
+ else ans += num;
+ }
+ return ans;
+ }",0.0,leetcode,,JAVA,"public int romanToInt(String s) {
+ int ans = 0, num = 0;
+ for (int i = s.length()-1; i >= 0; i--) {
+ switch(s.charAt(i)) {
+ case 'I': num = 1; break;
+ case 'V': num = 5; break;
+ case 'X': num = 10; break;
+ case 'L': num = 50; break;
+ case 'C': num = 100; break;
+ case 'D': num = 500; break;
+ case 'M': num = 1000; break;
+ }
+ if (4 * num < ans) ans -= num;
+ else ans += num;
+ }
+ return ans;
+ }",17,17
+,"// 1. Binary Search (AI-generated for sorted array lookup)
+public class BinarySearch {
+ public static int search(int[] arr, int target) {
+ int left = 0, right = arr.length - 1;
+ while (left <= right) {
+ int mid = left + (right - left) / 2;
+ if (arr[mid] == target) return mid;
+ if (arr[mid] < target) left = mid + 1;
+ else right = mid - 1;
+ }
+ return -1;
+ }
+}
+",1.0,PERPLEXITY,Write a Java method for binary search on a sorted integer array that returns the index or -1 if not found,JAVA,"// 1. Binary Search (AI-generated for sorted array lookup)
+public class BinarySearch {
+ public static int search(int[] arr, int target) {
+ int left = 0, right = arr.length - 1;
+ while (left <= right) {
+ int mid = left + (right - left) / 2;
+ if (arr[mid] == target) return mid;
+ if (arr[mid] < target) left = mid + 1;
+ else right = mid - 1;
+ }
+ return -1;
+ }
+}",13,13
+,"class Solution {
+ public String intToRoman(int num) {
+ String Roman = """";
+ int[][] storeIntRoman = {{1000, ""M""}, {900, ""CM""}, {500, ""D""}, {400, ""CD""}, {100, ""C""}, {90, ""XC""}, {50, ""L""}, {40, ""XL""}, {10, ""X""}, {9, ""IX""}, {5, ""V""}, {4, ""IV""}, {1, ""I""}};
+ for (int i = 0; i < storeIntRoman.length; i++) {
+ while (num >= storeIntRoman[i][0]) {
+ Roman += storeIntRoman[i][1];
+ num -= storeIntRoman[i][0];
+ }
+ }
+ return Roman;
+ }
+}",0.0,leetcode,,JAVA,"class Solution {
+ public String intToRoman(int num) {
+ String Roman = """";
+ int[][] storeIntRoman = {{1000, ""M""}, {900, ""CM""}, {500, ""D""}, {400, ""CD""}, {100, ""C""}, {90, ""XC""}, {50, ""L""}, {40, ""XL""}, {10, ""X""}, {9, ""IX""}, {5, ""V""}, {4, ""IV""}, {1, ""I""}};
+ for (int i = 0; i < storeIntRoman.length; i++) {
+ while (num >= storeIntRoman[i][0]) {
+ Roman += storeIntRoman[i][1];
+ num -= storeIntRoman[i][0];
+ }
+ }
+ return Roman;
+ }
+}",13,13
+,"public class BubbleSort {
+ public static void sort(int[] arr) {
+ int n = arr.length;
+ for (int i = 0; i < n - 1; i++) {
+ for (int j = 0; j < n - i - 1; j++) {
+ if (arr[j] > arr[j + 1]) {
+ int temp = arr[j];
+ arr[j] = arr[j + 1];
+ arr[j + 1] = temp;
+ }
+ }
+ }
+ }
+}
+",1.0,PERPLEXITY,Create a Java class with a static method to sort an integer array using bubble sort in-place.,JAVA,"public class BubbleSort {
+ public static void sort(int[] arr) {
+ int n = arr.length;
+ for (int i = 0; i < n - 1; i++) {
+ for (int j = 0; j < n - i - 1; j++) {
+ if (arr[j] > arr[j + 1]) {
+ int temp = arr[j];
+ arr[j] = arr[j + 1];
+ arr[j + 1] = temp;
+ }
+ }
+ }
+ }
+}",14,14
+,"class Solution {
+ private Map digitToLetters = new HashMap<>();
+ private List resultList = new ArrayList<>();
+
+ public List letterCombinations(String digits) {
+ if (digits == null || digits.length() == 0) {
+ return resultList;
+ }
+
+ digitToLetters.put('2', ""abc"");
+ digitToLetters.put('3', ""def"");
+ digitToLetters.put('4', ""ghi"");
+ digitToLetters.put('5', ""jkl"");
+ digitToLetters.put('6', ""mno"");
+ digitToLetters.put('7', ""pqrs"");
+ digitToLetters.put('8', ""tuv"");
+ digitToLetters.put('9', ""wxyz"");
+
+ generateCombinations(digits, 0, new StringBuilder());
+
+ return resultList;
+
+
+ }
+
+
+ private void generateCombinations(String digits, int currentIndex, StringBuilder currentCombination) {
+ if (currentIndex == digits.length()) {
+ resultList.add(currentCombination.toString());
+ return;
+ }
+
+ char currentDigit = digits.charAt(currentIndex);
+ String letterOptions = digitToLetters.get(currentDigit);
+
+ if (letterOptions != null) {
+ for (int i = 0; i < letterOptions.length(); i++) {
+ char letter = letterOptions.charAt(i);
+ currentCombination.append(letter);
+ generateCombinations(digits, currentIndex + 1, currentCombination);
+ currentCombination.deleteCharAt(currentCombination.length() - 1);
+ }
+ }
+ }
+}",0.0,leetcode,,JAVA,"class Solution {
+ private Map digitToLetters = new HashMap<>();
+ private List resultList = new ArrayList<>();
+
+ public List letterCombinations(String digits) {
+ if (digits == null || digits.length() == 0) {
+ return resultList;
+ }
+
+ digitToLetters.put('2', ""abc"");
+ digitToLetters.put('3', ""def"");
+ digitToLetters.put('4', ""ghi"");
+ digitToLetters.put('5', ""jkl"");
+ digitToLetters.put('6', ""mno"");
+ digitToLetters.put('7', ""pqrs"");
+ digitToLetters.put('8', ""tuv"");
+ digitToLetters.put('9', ""wxyz"");
+
+ generateCombinations(digits, 0, new StringBuilder());
+
+ return resultList;
+
+
+ }
+
+
+ private void generateCombinations(String digits, int currentIndex, StringBuilder currentCombination) {
+ if (currentIndex == digits.length()) {
+ resultList.add(currentCombination.toString());
+ return;
+ }
+
+ char currentDigit = digits.charAt(currentIndex);
+ String letterOptions = digitToLetters.get(currentDigit);
+
+ if (letterOptions != null) {
+ for (int i = 0; i < letterOptions.length(); i++) {
+ char letter = letterOptions.charAt(i);
+ currentCombination.append(letter);
+ generateCombinations(digits, currentIndex + 1, currentCombination);
+ currentCombination.deleteCharAt(currentCombination.length() - 1);
+ }
+ }
+ }
+}",45,45
+,"class Solution {
+ public boolean isValidSudoku(char[][] board) {
+ boolean[][] rows = new boolean[9][9];
+ boolean[][] cols = new boolean[9][9];
+ boolean[][] boxes = new boolean[9][9];
+
+ for (int i = 0; i < 9; i++) {
+ for (int j = 0; j < 9; j++) {
+ if (board[i][j] != '.') {
+ int num = board[i][j] - '1';
+ int boxIndex = (i / 3) * 3 + (j / 3);
+
+ if (rows[i][num] || cols[j][num] || boxes[boxIndex][num]) {
+ return false;
+ }
+
+ rows[i][num] = cols[j][num] = boxes[boxIndex][num] = true;
+ }
+ }
+ }
+ return true;
+ }
+}",0.0,leetcode,,JAVA,"class Solution {
+ public boolean isValidSudoku(char[][] board) {
+ boolean[][] rows = new boolean[9][9];
+ boolean[][] cols = new boolean[9][9];
+ boolean[][] boxes = new boolean[9][9];
+
+ for (int i = 0; i < 9; i++) {
+ for (int j = 0; j < 9; j++) {
+ if (board[i][j] != '.') {
+ int num = board[i][j] - '1';
+ int boxIndex = (i / 3) * 3 + (j / 3);
+
+ if (rows[i][num] || cols[j][num] || boxes[boxIndex][num]) {
+ return false;
+ }
+
+ rows[i][num] = cols[j][num] = boxes[boxIndex][num] = true;
+ }
+ }
+ }
+ return true;
+ }
+}",23,23
+,"import java.util.HashMap;
+public class Fibonacci {
+ private static HashMap memo = new HashMap<>();
+ public static long fib(int n) {
+ if (n <= 1) return n;
+ if (memo.containsKey(n)) return memo.get(n);
+ long result = fib(n - 1) + fib(n - 2);
+ memo.put(n, result);
+ return result;
+ }
+}
+",1.0,PERPLEXITY,Write a Java Fibonacci function using recursion with HashMap memoization for efficiency,JAVA,"import java.util.HashMap;
+public class Fibonacci {
+ private static HashMap memo = new HashMap<>();
+ public static long fib(int n) {
+ if (n <= 1) return n;
+ if (memo.containsKey(n)) return memo.get(n);
+ long result = fib(n - 1) + fib(n - 2);
+ memo.put(n, result);
+ return result;
+ }
+}",11,11
+,"class Solution {
+public:
+ string fractionToDecimal(int numerator, int denominator) {
+ if (numerator == 0)
+ return ""0"";
+
+ string fraction;
+ if ((numerator < 0) ^ (denominator < 0))
+ fraction += ""-"";
+
+ long long dividend = llabs((long long)numerator);
+ long long divisor = llabs((long long)denominator);
+ fraction += to_string(dividend / divisor);
+ long long remainder = dividend % divisor;
+ if (remainder == 0) {
+ return fraction;
+ }
+
+ fraction += ""."";
+ unordered_map map;
+ while (remainder != 0) {
+ if (map.count(remainder)) {
+ fraction.insert(map[remainder], ""("");
+ fraction += "")"";
+ break;
+ }
+ map[remainder] = fraction.size();
+ remainder *= 10;
+ fraction += to_string(remainder / divisor);
+ remainder %= divisor;
+ }
+
+ return fraction;
+ }
+};",0.0,leetcode,,JAVA,"class Solution {
+public:
+ string fractionToDecimal(int numerator, int denominator) {
+ if (numerator == 0)
+ return ""0"";
+
+ string fraction;
+ if ((numerator < 0) ^ (denominator < 0))
+ fraction += ""-"";
+
+ long long dividend = llabs((long long)numerator);
+ long long divisor = llabs((long long)denominator);
+ fraction += to_string(dividend / divisor);
+ long long remainder = dividend % divisor;
+ if (remainder == 0) {
+ return fraction;
+ }
+
+ fraction += ""."";
+ unordered_map map;
+ while (remainder != 0) {
+ if (map.count(remainder)) {
+ fraction.insert(map[remainder], ""("");
+ fraction += "")"";
+ break;
+ }
+ map[remainder] = fraction.size();
+ remainder *= 10;
+ fraction += to_string(remainder / divisor);
+ remainder %= divisor;
+ }
+
+ return fraction;
+ }
+};",35,35
+,"class Solution {
+ public int numJewelsInStones(String jewels, String stones)
+ {
+ int cnt=0;
+ for(int i=0;i map = new HashMap<>();
+ int max = 0;
+
+ for (int j = i + 1; j < n; j++) {
+ int dx = points[j][0] - points[i][0];
+ int dy = points[j][1] - points[i][1];
+
+ int g = gcd(dx, dy);
+ dx /= g;
+ dy /= g;
+
+ String key = dx + "","" + dy;
+ map.put(key, map.getOrDefault(key, 0) + 1);
+ max = Math.max(max, map.get(key));
+ }
+
+ result = Math.max(result, max + 1); // +1 for anchor point
+ }
+
+ return result;
+ }
+
+ private int gcd(int a, int b) {
+ if (b == 0) return a;
+ return gcd(b, a % b);
+ }
+}",0.0,leetcode,,JAVA,"class Solution {
+ public int maxPoints(int[][] points) {
+ int n = points.length;
+ if (n <= 2) return n;
+
+ int result = 0;
+
+ for (int i = 0; i < n; i++) {
+ Map map = new HashMap<>();
+ int max = 0;
+
+ for (int j = i + 1; j < n; j++) {
+ int dx = points[j][0] - points[i][0];
+ int dy = points[j][1] - points[i][1];
+
+ int g = gcd(dx, dy);
+ dx /= g;
+ dy /= g;
+
+ String key = dx + "","" + dy;
+ map.put(key, map.getOrDefault(key, 0) + 1);
+ max = Math.max(max, map.get(key));
+ }
+
+ result = Math.max(result, max + 1); // +1 for anchor point
+ }
+
+ return result;
+ }
+
+ private int gcd(int a, int b) {
+ if (b == 0) return a;
+ return gcd(b, a % b);
+ }
+}",35,35
+,"import java.util.ArrayList;
+public class Stack {
+ private ArrayList stack = new ArrayList<>();
+ public void push(T item) { stack.add(item); }
+ public T pop() { return stack.remove(stack.size() - 1); }
+ public T peek() { return stack.get(stack.size() - 1); }
+ public boolean isEmpty() { return stack.isEmpty(); }
+}
+",1.0,PERPLEXITY,"Implement a generic Stack class in Java using ArrayList with push, pop, peek, and isEmpty methods",JAVA,"import java.util.ArrayList;
+public class Stack {
+ private ArrayList stack = new ArrayList<>();
+ public void push(T item) { stack.add(item); }
+ public T pop() { return stack.remove(stack.size() - 1); }
+ public T peek() { return stack.get(stack.size() - 1); }
+ public boolean isEmpty() { return stack.isEmpty(); }
+}",8,8
+,"public class Solution {
+ public ListNode detectCycle(ListNode head) {
+ ListNode slow = head;
+ ListNode fast = head;
+
+ while(fast != null && fast.next != null) {
+ slow = slow.next;
+ fast = fast.next.next;
+
+ if(slow == fast) {
+ slow = head;
+
+ while(slow != fast) {
+ slow = slow.next;
+ fast = fast.next;
+ }
+ return slow;
+ }
+ }
+ return null;
+ }
+}",0.0,leetcode,,JAVA,"public class Solution {
+ public ListNode detectCycle(ListNode head) {
+ ListNode slow = head;
+ ListNode fast = head;
+
+ while(fast != null && fast.next != null) {
+ slow = slow.next;
+ fast = fast.next.next;
+
+ if(slow == fast) {
+ slow = head;
+
+ while(slow != fast) {
+ slow = slow.next;
+ fast = fast.next;
+ }
+ return slow;
+ }
+ }
+ return null;
+ }
+}",22,22
+,"class ListNode {
+ int val; ListNode next;
+ ListNode(int val) { this.val = val; }
+}
+public class LinkedListOps {
+ public ListNode reverse(ListNode head) {
+ ListNode prev = null, curr = head;
+ while (curr != null) {
+ ListNode next = curr.next;
+ curr.next = prev;
+ prev = curr; curr = next;
+ }
+ return prev;
+ }
+}
+",1.0,PERPLEXITY,"Write Java code to reverse a singly linked list given a ListNode head, using iterative approach",JAVA,"class ListNode {
+ int val; ListNode next;
+ ListNode(int val) { this.val = val; }
+}
+public class LinkedListOps {
+ public ListNode reverse(ListNode head) {
+ ListNode prev = null, curr = head;
+ while (curr != null) {
+ ListNode next = curr.next;
+ curr.next = prev;
+ prev = curr; curr = next;
+ }
+ return prev;
+ }
+}",15,15
+,"public List wordBreak(String s, Set wordDict) {
+ return DFS(s, wordDict, new HashMap>());
+}
+
+// DFS function returns an array including all substrings derived from s.
+List DFS(String s, Set wordDict, HashMap>map) {
+ if (map.containsKey(s))
+ return map.get(s);
+
+ LinkedListres = new LinkedList();
+ if (s.length() == 0) {
+ res.add("""");
+ return res;
+ }
+ for (String word : wordDict) {
+ if (s.startsWith(word)) {
+ Listsublist = DFS(s.substring(word.length()), wordDict, map);
+ for (String sub : sublist)
+ res.add(word + (sub.isEmpty() ? """" : "" "") + sub);
+ }
+ }
+ map.put(s, res);
+ return res;
+}",0.0,leetcode,,JAVA,"public List wordBreak(String s, Set wordDict) {
+ return DFS(s, wordDict, new HashMap>());
+}
+
+// DFS function returns an array including all substrings derived from s.
+List DFS(String s, Set wordDict, HashMap>map) {
+ if (map.containsKey(s))
+ return map.get(s);
+
+ LinkedList