Spaces:
Runtime error
Runtime error
| Code_ID,Code_Text,Label,Source_Type,Generation_Prompt,Language,normalized_code,original_line_count,normalized_line_count | |
| ,"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 | |
| ,"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 | |
| ,"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 | |
| ,"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 | |
| ,"public class FactorialDP { | |
| public static long factorial(int n) { | |
| if (n <= 1) return 1; | |
| long[] dp = new long[n + 1]; | |
| dp[0] = dp[1] = 1; | |
| for (int i = 2; i <= n; i++) { | |
| dp[i] = dp[i - 1] * i; | |
| } | |
| return dp[n]; | |
| } | |
| } | |
| ",1.0,PERPLEXITY,Implement a Java dynamic programming solution to compute factorial of a large number using an array.,java,"public class FactorialDP { | |
| public static long factorial(int n) { | |
| if (n <= 1) return 1; | |
| long[] dp = new long[n + 1]; | |
| dp[0] = dp[1] = 1; | |
| for (int i = 2; i <= n; i++) { | |
| dp[i] = dp[i - 1] * i; | |
| } | |
| return dp[n]; | |
| } | |
| }",11,11 | |
| ,"class Solution { | |
| public int missingNumber(int[] nums) { | |
| int n = nums.length; | |
| int[] v = new int[n+1]; | |
| Arrays.fill(v, -1); | |
| for(int i = 0; i < nums.length; i++) { | |
| v[nums[i]] = nums[i]; | |
| } | |
| for(int i = 0; i < v.length; i++) { | |
| if(v[i] == -1) return i; | |
| } | |
| return 0; | |
| } | |
| } | |
| ",0.0,leetcode,,java,"class Solution { | |
| public int missingNumber(int[] nums) { | |
| int n = nums.length; | |
| int[] v = new int[n+1]; | |
| Arrays.fill(v, -1); | |
| for(int i = 0; i < nums.length; i++) { | |
| v[nums[i]] = nums[i]; | |
| } | |
| for(int i = 0; i < v.length; i++) { | |
| if(v[i] == -1) return i; | |
| } | |
| return 0; | |
| } | |
| }",14,14 | |
| ,"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 | |
| ,"# 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 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 | |
| ,"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 | |
| ,"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 | |
| ,"import java.lang.annotation.*; | |
| @Target(ElementType.METHOD) | |
| @Retention(RetentionPolicy.RUNTIME) | |
| public @interface LogExecution { | |
| String value() default """"; | |
| } | |
| public class AnnotationProcessor { | |
| public static void process(Object obj) throws Exception { | |
| for (java.lang.reflect.Method m : obj.getClass().getMethods()) { | |
| if (m.isAnnotationPresent(LogExecution.class)) { | |
| System.out.println(""Logging: "" + m.getName()); | |
| } | |
| } | |
| } | |
| } | |
| ",1.0,PERPLEXITY,Create a basic custom annotation with processor stub for runtime processing,java,"import java.lang.annotation.*; | |
| @Target(ElementType.METHOD) | |
| @Retention(RetentionPolicy.RUNTIME) | |
| public @interface LogExecution { | |
| String value() default """"; | |
| } | |
| public class AnnotationProcessor { | |
| public static void process(Object obj) throws Exception { | |
| for (java.lang.reflect.Method m : obj.getClass().getMethods()) { | |
| if (m.isAnnotationPresent(LogExecution.class)) { | |
| System.out.println(""Logging: "" + m.getName()); | |
| } | |
| } | |
| } | |
| }",15,15 | |
| ,"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 | |
| ,"public RandomListNode copyRandomList(RandomListNode head) { | |
| RandomListNode iter = head, next; | |
| // First round: make copy of each node, | |
| // and link them together side-by-side in a single list. | |
| while (iter != null) { | |
| next = iter.next; | |
| RandomListNode copy = new RandomListNode(iter.label); | |
| iter.next = copy; | |
| copy.next = next; | |
| iter = next; | |
| } | |
| // Second round: assign random pointers for the copy nodes. | |
| iter = head; | |
| while (iter != null) { | |
| if (iter.random != null) { | |
| iter.next.random = iter.random.next; | |
| } | |
| iter = iter.next.next; | |
| } | |
| // Third round: restore the original list, and extract the copy list. | |
| iter = head; | |
| RandomListNode pseudoHead = new RandomListNode(0); | |
| RandomListNode copy, copyIter = pseudoHead; | |
| while (iter != null) { | |
| next = iter.next.next; | |
| // extract the copy | |
| copy = iter.next; | |
| copyIter.next = copy; | |
| copyIter = copy; | |
| // restore the original list | |
| iter.next = next; | |
| iter = next; | |
| } | |
| return pseudoHead.next; | |
| }",0.0,leetcode,,java,"public RandomListNode copyRandomList(RandomListNode head) { | |
| RandomListNode iter = head, next; | |
| // First round: make copy of each node, | |
| // and link them together side-by-side in a single list. | |
| while (iter != null) { | |
| next = iter.next; | |
| RandomListNode copy = new RandomListNode(iter.label); | |
| iter.next = copy; | |
| copy.next = next; | |
| iter = next; | |
| } | |
| // Second round: assign random pointers for the copy nodes. | |
| iter = head; | |
| while (iter != null) { | |
| if (iter.random != null) { | |
| iter.next.random = iter.random.next; | |
| } | |
| iter = iter.next.next; | |
| } | |
| // Third round: restore the original list, and extract the copy list. | |
| iter = head; | |
| RandomListNode pseudoHead = new RandomListNode(0); | |
| RandomListNode copy, copyIter = pseudoHead; | |
| while (iter != null) { | |
| next = iter.next.next; | |
| // extract the copy | |
| copy = iter.next; | |
| copyIter.next = copy; | |
| copyIter = copy; | |
| // restore the original list | |
| iter.next = next; | |
| iter = next; | |
| } | |
| return pseudoHead.next; | |
| }",45,45 | |
| ,"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 | |
| ,"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 | |
| ,"class MagicDictionary { | |
| Set<String> originalWords; | |
| Map<String, Integer> extensions; | |
| public MagicDictionary() { | |
| originalWords = new HashSet<>(); | |
| extensions = new HashMap<>(); | |
| } | |
| public void buildDict(String[] dictionary) { | |
| for (String word : dictionary) { | |
| originalWords.add(word); | |
| char[] str = word.toCharArray(); | |
| int n = str.length; | |
| for (int i = 0; i < n; i++) { | |
| char temp = str[i]; | |
| str[i] = '*'; | |
| String key = new String(str); | |
| extensions.put(key, extensions.getOrDefault(key, 0) + 1); | |
| str[i] = temp; | |
| } | |
| } | |
| } | |
| public boolean search(String searchWord) { | |
| char[] str = searchWord.toCharArray(); | |
| int n = str.length; | |
| for (int i = 0; i < n; i++) { | |
| char temp = str[i]; | |
| str[i] = '*'; | |
| String key = new String(str); | |
| if (extensions.containsKey(key)) { | |
| // If count >= 2, then there's definitely a different word that maps to this pattern | |
| // If count == 1, make sure it's not the same word | |
| if (extensions.get(key) >= 2 || !originalWords.contains(searchWord)) { | |
| return true; | |
| } | |
| } | |
| str[i] = temp; | |
| } | |
| return false; | |
| } | |
| }",0.0,leetcode,,java,"class MagicDictionary { | |
| Set<String> originalWords; | |
| Map<String, Integer> extensions; | |
| public MagicDictionary() { | |
| originalWords = new HashSet<>(); | |
| extensions = new HashMap<>(); | |
| } | |
| public void buildDict(String[] dictionary) { | |
| for (String word : dictionary) { | |
| originalWords.add(word); | |
| char[] str = word.toCharArray(); | |
| int n = str.length; | |
| for (int i = 0; i < n; i++) { | |
| char temp = str[i]; | |
| str[i] = '*'; | |
| String key = new String(str); | |
| extensions.put(key, extensions.getOrDefault(key, 0) + 1); | |
| str[i] = temp; | |
| } | |
| } | |
| } | |
| public boolean search(String searchWord) { | |
| char[] str = searchWord.toCharArray(); | |
| int n = str.length; | |
| for (int i = 0; i < n; i++) { | |
| char temp = str[i]; | |
| str[i] = '*'; | |
| String key = new String(str); | |
| if (extensions.containsKey(key)) { | |
| // If count >= 2, then there's definitely a different word that maps to this pattern | |
| // If count == 1, make sure it's not the same word | |
| if (extensions.get(key) >= 2 || !originalWords.contains(searchWord)) { | |
| return true; | |
| } | |
| } | |
| str[i] = temp; | |
| } | |
| return false; | |
| } | |
| }",43,43 | |
| ,"// 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 | |
| ,"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 java.util.*; | |
| class Solution { | |
| public List<String> basicCalculatorIV(String expression, String[] evalvars, int[] evalints) { | |
| Map<String, Integer> evalmap = new HashMap<>(); | |
| for (int i = 0; i < evalvars.length; i++) evalmap.put(evalvars[i], evalints[i]); | |
| List<String> tokens = tokenize(expression); | |
| Map<List<String>, Integer> poly = parseExpression(tokens, evalmap); | |
| List<Map.Entry<List<String>, Integer>> list = new ArrayList<>(poly.entrySet()); | |
| list.sort((a, b) -> { | |
| if (b.getKey().size() != a.getKey().size()) return b.getKey().size() - a.getKey().size(); | |
| // lexicographic compare by joining with '*' | |
| return String.join(""*"", a.getKey()).compareTo(String.join(""*"", b.getKey())); | |
| }); | |
| List<String> ans = new ArrayList<>(); | |
| for (var e : list) { | |
| int coeff = e.getValue(); | |
| if (coeff == 0) continue; | |
| StringBuilder sb = new StringBuilder(); | |
| sb.append(coeff); | |
| for (String v : e.getKey()) sb.append(""*"").append(v); | |
| ans.add(sb.toString()); | |
| } | |
| return ans; | |
| } | |
| private List<String> tokenize(String expr) { | |
| List<String> tokens = new ArrayList<>(); | |
| StringBuilder sb = new StringBuilder(); | |
| for (char c : expr.toCharArray()) { | |
| if (Character.isLetterOrDigit(c)) sb.append(c); | |
| else { | |
| if (sb.length() > 0) { tokens.add(sb.toString()); sb.setLength(0); } | |
| if (c == '+' || c == '-' || c == '*' || c == '(' || c == ')') tokens.add(String.valueOf(c)); | |
| } | |
| } | |
| if (sb.length() > 0) tokens.add(sb.toString()); | |
| return tokens; | |
| } | |
| private Map<List<String>, Integer> parseExpression(List<String> tokens, Map<String, Integer> evalmap) { | |
| Deque<Map<List<String>, Integer>> vals = new ArrayDeque<>(); | |
| Deque<String> ops = new ArrayDeque<>(); | |
| Map<String, Integer> prec = Map.of(""+"",1, ""-"",1, ""*"",2); | |
| for (String tok : tokens) { | |
| if (tok.equals(""("")) ops.push(tok); | |
| else if (tok.equals("")"")) { | |
| while (!ops.peek().equals(""("")) applyOp(vals, ops.pop()); | |
| ops.pop(); | |
| } else if (prec.containsKey(tok)) { | |
| while (!ops.isEmpty() && prec.containsKey(ops.peek()) && prec.get(ops.peek()) >= prec.get(tok)) { | |
| applyOp(vals, ops.pop()); | |
| } | |
| ops.push(tok); | |
| } else { | |
| vals.push(parseToken(tok, evalmap)); | |
| } | |
| } | |
| while (!ops.isEmpty()) applyOp(vals, ops.pop()); | |
| return vals.isEmpty() ? new HashMap<>() : vals.pop(); | |
| } | |
| private void applyOp(Deque<Map<List<String>, Integer>> vals, String op) { | |
| Map<List<String>, Integer> b = vals.pop(); | |
| Map<List<String>, Integer> a = vals.pop(); | |
| if (op.equals(""+"")) vals.push(add(a, b)); | |
| else if (op.equals(""-"")) vals.push(sub(a, b)); | |
| else vals.push(mul(a, b)); | |
| } | |
| private Map<List<String>, Integer> parseToken(String tok, Map<String, Integer> evalmap) { | |
| Map<List<String>, Integer> res = new HashMap<>(); | |
| if (tok.matches(""-?\\d+"")) { | |
| res.put(Collections.emptyList(), Integer.parseInt(tok)); | |
| } else if (evalmap.containsKey(tok)) { | |
| res.put(Collections.emptyList(), evalmap.get(tok)); | |
| } else { | |
| res.put(Arrays.asList(tok), 1); | |
| } | |
| return res; | |
| } | |
| private Map<List<String>, Integer> combine(Map<List<String>, Integer> m) { | |
| Map<List<String>, Integer> res = new HashMap<>(); | |
| for (var e : m.entrySet()) { | |
| if (e.getValue() != 0) res.put(e.getKey(), res.getOrDefault(e.getKey(), 0) + e.getValue()); | |
| } | |
| res.entrySet().removeIf(kv -> kv.getValue() == 0); | |
| return res; | |
| } | |
| private Map<List<String>, Integer> add(Map<List<String>, Integer> a, Map<List<String>, Integer> b) { | |
| Map<List<String>, Integer> res = new HashMap<>(a); | |
| for (var e : b.entrySet()) res.put(e.getKey(), res.getOrDefault(e.getKey(), 0) + e.getValue()); | |
| return combine(res); | |
| } | |
| private Map<List<String>, Integer> sub(Map<List<String>, Integer> a, Map<List<String>, Integer> b) { | |
| Map<List<String>, Integer> res = new HashMap<>(a); | |
| for (var e : b.entrySet()) res.put(e.getKey(), res.getOrDefault(e.getKey(), 0) - e.getValue()); | |
| return combine(res); | |
| } | |
| private Map<List<String>, Integer> mul(Map<List<String>, Integer> a, Map<List<String>, Integer> b) { | |
| Map<List<String>, Integer> res = new HashMap<>(); | |
| for (var ea : a.entrySet()) { | |
| for (var eb : b.entrySet()) { | |
| List<String> merged = new ArrayList<>(ea.getKey()); | |
| merged.addAll(eb.getKey()); | |
| Collections.sort(merged); | |
| res.put(merged, res.getOrDefault(merged, 0) + ea.getValue() * eb.getValue()); | |
| } | |
| } | |
| return combine(res); | |
| } | |
| }",0.0,leetcode,,java,"import java.util.*; | |
| class Solution { | |
| public List<String> basicCalculatorIV(String expression, String[] evalvars, int[] evalints) { | |
| Map<String, Integer> evalmap = new HashMap<>(); | |
| for (int i = 0; i < evalvars.length; i++) evalmap.put(evalvars[i], evalints[i]); | |
| List<String> tokens = tokenize(expression); | |
| Map<List<String>, Integer> poly = parseExpression(tokens, evalmap); | |
| List<Map.Entry<List<String>, Integer>> list = new ArrayList<>(poly.entrySet()); | |
| list.sort((a, b) -> { | |
| if (b.getKey().size() != a.getKey().size()) return b.getKey().size() - a.getKey().size(); | |
| // lexicographic compare by joining with '*' | |
| return String.join(""*"", a.getKey()).compareTo(String.join(""*"", b.getKey())); | |
| }); | |
| List<String> ans = new ArrayList<>(); | |
| for (var e : list) { | |
| int coeff = e.getValue(); | |
| if (coeff == 0) continue; | |
| StringBuilder sb = new StringBuilder(); | |
| sb.append(coeff); | |
| for (String v : e.getKey()) sb.append(""*"").append(v); | |
| ans.add(sb.toString()); | |
| } | |
| return ans; | |
| } | |
| private List<String> tokenize(String expr) { | |
| List<String> tokens = new ArrayList<>(); | |
| StringBuilder sb = new StringBuilder(); | |
| for (char c : expr.toCharArray()) { | |
| if (Character.isLetterOrDigit(c)) sb.append(c); | |
| else { | |
| if (sb.length() > 0) { tokens.add(sb.toString()); sb.setLength(0); } | |
| if (c == '+' || c == '-' || c == '*' || c == '(' || c == ')') tokens.add(String.valueOf(c)); | |
| } | |
| } | |
| if (sb.length() > 0) tokens.add(sb.toString()); | |
| return tokens; | |
| } | |
| private Map<List<String>, Integer> parseExpression(List<String> tokens, Map<String, Integer> evalmap) { | |
| Deque<Map<List<String>, Integer>> vals = new ArrayDeque<>(); | |
| Deque<String> ops = new ArrayDeque<>(); | |
| Map<String, Integer> prec = Map.of(""+"",1, ""-"",1, ""*"",2); | |
| for (String tok : tokens) { | |
| if (tok.equals(""("")) ops.push(tok); | |
| ... truncated ... | |
| else if (op.equals(""-"")) vals.push(sub(a, b)); | |
| else vals.push(mul(a, b)); | |
| } | |
| private Map<List<String>, Integer> parseToken(String tok, Map<String, Integer> evalmap) { | |
| Map<List<String>, Integer> res = new HashMap<>(); | |
| if (tok.matches(""-?\\d+"")) { | |
| res.put(Collections.emptyList(), Integer.parseInt(tok)); | |
| } else if (evalmap.containsKey(tok)) { | |
| res.put(Collections.emptyList(), evalmap.get(tok)); | |
| } else { | |
| res.put(Arrays.asList(tok), 1); | |
| } | |
| return res; | |
| } | |
| private Map<List<String>, Integer> combine(Map<List<String>, Integer> m) { | |
| Map<List<String>, Integer> res = new HashMap<>(); | |
| for (var e : m.entrySet()) { | |
| if (e.getValue() != 0) res.put(e.getKey(), res.getOrDefault(e.getKey(), 0) + e.getValue()); | |
| } | |
| res.entrySet().removeIf(kv -> kv.getValue() == 0); | |
| return res; | |
| } | |
| private Map<List<String>, Integer> add(Map<List<String>, Integer> a, Map<List<String>, Integer> b) { | |
| Map<List<String>, Integer> res = new HashMap<>(a); | |
| for (var e : b.entrySet()) res.put(e.getKey(), res.getOrDefault(e.getKey(), 0) + e.getValue()); | |
| return combine(res); | |
| } | |
| private Map<List<String>, Integer> sub(Map<List<String>, Integer> a, Map<List<String>, Integer> b) { | |
| Map<List<String>, Integer> res = new HashMap<>(a); | |
| for (var e : b.entrySet()) res.put(e.getKey(), res.getOrDefault(e.getKey(), 0) - e.getValue()); | |
| return combine(res); | |
| } | |
| private Map<List<String>, Integer> mul(Map<List<String>, Integer> a, Map<List<String>, Integer> b) { | |
| Map<List<String>, Integer> res = new HashMap<>(); | |
| for (var ea : a.entrySet()) { | |
| for (var eb : b.entrySet()) { | |
| List<String> merged = new ArrayList<>(ea.getKey()); | |
| merged.addAll(eb.getKey()); | |
| Collections.sort(merged); | |
| res.put(merged, res.getOrDefault(merged, 0) + ea.getValue() * eb.getValue()); | |
| } | |
| } | |
| return combine(res); | |
| } | |
| }",120,101 | |
| ,"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 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 | |
| ,"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 WordFilter { | |
| constructor(words) { | |
| this.pTrie = new Array(27) | |
| this.sTrie = new Array(27) | |
| let wordSet = new Set() | |
| for (let index = words.length - 1; ~index; index--) { | |
| let word = words[index], wlen = word.length | |
| if (wordSet.has(word)) | |
| continue; | |
| wordSet.add(word) | |
| this.insert(word, index, this.pTrie, 0, wlen, 1) | |
| this.insert(word, index, this.sTrie, wlen-1, -1, -1) | |
| } | |
| } | |
| insert(word, index, trie, start, end, step) { | |
| for (let i = start; i != end; i += step) { | |
| let c = word.charCodeAt(i) - 97 | |
| if (!trie[c]) trie[c] = new Array(27) | |
| trie = trie[c] | |
| if (!trie[26]) trie[26] = [] | |
| trie[26].push(index) | |
| } | |
| } | |
| retrieve(word, trie, start, end, step) { | |
| for (let i = start; i != end; i += step) { | |
| let c = word.charCodeAt(i) - 97 | |
| if (!trie[c]) return [] | |
| trie = trie[c] | |
| } | |
| return trie[26] | |
| } | |
| f(pre, suf) { | |
| let pVals = this.retrieve(pre, this.pTrie, 0, pre.length, 1), | |
| sVals = this.retrieve(suf, this.sTrie, suf.length-1, -1, -1), | |
| svix = 0, pvix = 0 | |
| while (svix < sVals.length && pvix < pVals.length) { | |
| let sVal = sVals[svix], pVal = pVals[pvix] | |
| if (sVal === pVal) return sVal | |
| sVal > pVal ? svix++ : pvix++ | |
| } | |
| return -1 | |
| } | |
| };",0.0,leetcode,,java,"class WordFilter { | |
| constructor(words) { | |
| this.pTrie = new Array(27) | |
| this.sTrie = new Array(27) | |
| let wordSet = new Set() | |
| for (let index = words.length - 1; ~index; index--) { | |
| let word = words[index], wlen = word.length | |
| if (wordSet.has(word)) | |
| continue; | |
| wordSet.add(word) | |
| this.insert(word, index, this.pTrie, 0, wlen, 1) | |
| this.insert(word, index, this.sTrie, wlen-1, -1, -1) | |
| } | |
| } | |
| insert(word, index, trie, start, end, step) { | |
| for (let i = start; i != end; i += step) { | |
| let c = word.charCodeAt(i) - 97 | |
| if (!trie[c]) trie[c] = new Array(27) | |
| trie = trie[c] | |
| if (!trie[26]) trie[26] = [] | |
| trie[26].push(index) | |
| } | |
| } | |
| retrieve(word, trie, start, end, step) { | |
| for (let i = start; i != end; i += step) { | |
| let c = word.charCodeAt(i) - 97 | |
| if (!trie[c]) return [] | |
| trie = trie[c] | |
| } | |
| return trie[26] | |
| } | |
| f(pre, suf) { | |
| let pVals = this.retrieve(pre, this.pTrie, 0, pre.length, 1), | |
| sVals = this.retrieve(suf, this.sTrie, suf.length-1, -1, -1), | |
| svix = 0, pvix = 0 | |
| while (svix < sVals.length && pvix < pVals.length) { | |
| let sVal = sVals[svix], pVal = pVals[pvix] | |
| if (sVal === pVal) return sVal | |
| sVal > pVal ? svix++ : pvix++ | |
| } | |
| return -1 | |
| } | |
| };",46,46 | |
| ,"class Solution { | |
| public String[] findWords(String[] words) { | |
| ArrayList<String> ans=new ArrayList<>(); | |
| String first = ""qwertyuiop""; | |
| String Secound =""asdfghjkl""; | |
| String Third=""zxcvbnm""; | |
| for(String i : words){ | |
| if(isinrow(i,first) || isinrow(i,Secound) || isinrow(i,Third)) | |
| ans.add(i); | |
| } | |
| return ans.toArray(new String[0]); | |
| } | |
| private boolean isinrow(String s,String row){ | |
| for(char c:s.toCharArray()){ | |
| if(row.indexOf(Character.toLowerCase(c))==-1){ | |
| return false; | |
| } | |
| } | |
| return true; | |
| } | |
| }",0.0,leetcode,,java,"class Solution { | |
| public String[] findWords(String[] words) { | |
| ArrayList<String> ans=new ArrayList<>(); | |
| String first = ""qwertyuiop""; | |
| String Secound =""asdfghjkl""; | |
| String Third=""zxcvbnm""; | |
| for(String i : words){ | |
| if(isinrow(i,first) || isinrow(i,Secound) || isinrow(i,Third)) | |
| ans.add(i); | |
| } | |
| return ans.toArray(new String[0]); | |
| } | |
| private boolean isinrow(String s,String row){ | |
| for(char c:s.toCharArray()){ | |
| if(row.indexOf(Character.toLowerCase(c))==-1){ | |
| return false; | |
| } | |
| } | |
| return true; | |
| } | |
| }",21,21 | |
| ,"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 | |
| ,"public class Solution { | |
| public List<List<Integer>> palindromePairs(String[] words) { | |
| List<List<Integer>> res = new ArrayList<List<Integer>>(); | |
| if(words == null || words.length == 0){ | |
| return res; | |
| } | |
| //build the map save the key-val pairs: String - idx | |
| HashMap<String, Integer> map = new HashMap<>(); | |
| for(int i = 0; i < words.length; i++){ | |
| map.put(words[i], i); | |
| } | |
| //special cases: """" can be combine with any palindrome string | |
| if(map.containsKey("""")){ | |
| int blankIdx = map.get(""""); | |
| for(int i = 0; i < words.length; i++){ | |
| if(isPalindrome(words[i])){ | |
| if(i == blankIdx) continue; | |
| res.add(Arrays.asList(blankIdx, i)); | |
| res.add(Arrays.asList(i, blankIdx)); | |
| } | |
| } | |
| } | |
| //find all string and reverse string pairs | |
| for(int i = 0; i < words.length; i++){ | |
| String cur_r = reverseStr(words[i]); | |
| if(map.containsKey(cur_r)){ | |
| int found = map.get(cur_r); | |
| if(found == i) continue; | |
| res.add(Arrays.asList(i, found)); | |
| } | |
| } | |
| //find the pair s1, s2 that | |
| //case1 : s1[0:cut] is palindrome and s1[cut+1:] = reverse(s2) => (s2, s1) | |
| //case2 : s1[cut+1:] is palindrome and s1[0:cut] = reverse(s2) => (s1, s2) | |
| for(int i = 0; i < words.length; i++){ | |
| String cur = words[i]; | |
| for(int cut = 1; cut < cur.length(); cut++){ | |
| if(isPalindrome(cur.substring(0, cut))){ | |
| String cut_r = reverseStr(cur.substring(cut)); | |
| if(map.containsKey(cut_r)){ | |
| int found = map.get(cut_r); | |
| if(found == i) continue; | |
| res.add(Arrays.asList(found, i)); | |
| } | |
| } | |
| if(isPalindrome(cur.substring(cut))){ | |
| String cut_r = reverseStr(cur.substring(0, cut)); | |
| if(map.containsKey(cut_r)){ | |
| int found = map.get(cut_r); | |
| if(found == i) continue; | |
| res.add(Arrays.asList(i, found)); | |
| } | |
| } | |
| } | |
| } | |
| return res; | |
| } | |
| public String reverseStr(String str){ | |
| StringBuilder sb= new StringBuilder(str); | |
| return sb.reverse().toString(); | |
| } | |
| public boolean isPalindrome(String s){ | |
| int i = 0; | |
| int j = s.length() - 1; | |
| while(i <= j){ | |
| if(s.charAt(i) != s.charAt(j)){ | |
| return false; | |
| } | |
| i++; | |
| j--; | |
| } | |
| return true; | |
| }",0.0,leetcode,,java,"public class Solution { | |
| public List<List<Integer>> palindromePairs(String[] words) { | |
| List<List<Integer>> res = new ArrayList<List<Integer>>(); | |
| if(words == null || words.length == 0){ | |
| return res; | |
| } | |
| //build the map save the key-val pairs: String - idx | |
| HashMap<String, Integer> map = new HashMap<>(); | |
| for(int i = 0; i < words.length; i++){ | |
| map.put(words[i], i); | |
| } | |
| //special cases: """" can be combine with any palindrome string | |
| if(map.containsKey("""")){ | |
| int blankIdx = map.get(""""); | |
| for(int i = 0; i < words.length; i++){ | |
| if(isPalindrome(words[i])){ | |
| if(i == blankIdx) continue; | |
| res.add(Arrays.asList(blankIdx, i)); | |
| res.add(Arrays.asList(i, blankIdx)); | |
| } | |
| } | |
| } | |
| //find all string and reverse string pairs | |
| for(int i = 0; i < words.length; i++){ | |
| String cur_r = reverseStr(words[i]); | |
| if(map.containsKey(cur_r)){ | |
| int found = map.get(cur_r); | |
| if(found == i) continue; | |
| res.add(Arrays.asList(i, found)); | |
| } | |
| } | |
| //find the pair s1, s2 that | |
| //case1 : s1[0:cut] is palindrome and s1[cut+1:] = reverse(s2) => (s2, s1) | |
| //case2 : s1[cut+1:] is palindrome and s1[0:cut] = reverse(s2) => (s1, s2) | |
| for(int i = 0; i < words.length; i++){ | |
| String cur = words[i]; | |
| for(int cut = 1; cut < cur.length(); cut++){ | |
| if(isPalindrome(cur.substring(0, cut))){ | |
| String cut_r = reverseStr(cur.substring(cut)); | |
| if(map.containsKey(cut_r)){ | |
| int found = map.get(cut_r); | |
| if(found == i) continue; | |
| res.add(Arrays.asList(found, i)); | |
| } | |
| } | |
| if(isPalindrome(cur.substring(cut))){ | |
| String cut_r = reverseStr(cur.substring(0, cut)); | |
| if(map.containsKey(cut_r)){ | |
| int found = map.get(cut_r); | |
| if(found == i) continue; | |
| res.add(Arrays.asList(i, found)); | |
| } | |
| } | |
| } | |
| } | |
| return res; | |
| } | |
| public String reverseStr(String str){ | |
| StringBuilder sb= new StringBuilder(str); | |
| return sb.reverse().toString(); | |
| } | |
| public boolean isPalindrome(String s){ | |
| int i = 0; | |
| int j = s.length() - 1; | |
| while(i <= j){ | |
| if(s.charAt(i) != s.charAt(j)){ | |
| return false; | |
| } | |
| i++; | |
| j--; | |
| } | |
| return true; | |
| }",79,79 | |
| ,"public int deleteAndEarn(int[] nums) { | |
| var numToCount = new HashMap<Integer, Integer>(); | |
| var min = Integer.MAX_VALUE; | |
| var max = Integer.MIN_VALUE; | |
| for (var num : nums) { | |
| numToCount.compute(num, (k, v) -> v == null ? 1 : ++v); | |
| min = Math.min(min, num); | |
| max = Math.max(max, num); | |
| } | |
| var prevIncEarn = 0; | |
| var prevExcEarn = 0; | |
| for (var i = min; i <= max; i++) { | |
| var incEarn = prevExcEarn + i * numToCount.getOrDefault(i, 0); | |
| var excEarn = Math.max(prevIncEarn, prevExcEarn); | |
| prevIncEarn = incEarn; | |
| prevExcEarn = excEarn; | |
| } | |
| return Math.max(prevIncEarn, prevExcEarn); | |
| }",0.0,leetcode,,java,"public int deleteAndEarn(int[] nums) { | |
| var numToCount = new HashMap<Integer, Integer>(); | |
| var min = Integer.MAX_VALUE; | |
| var max = Integer.MIN_VALUE; | |
| for (var num : nums) { | |
| numToCount.compute(num, (k, v) -> v == null ? 1 : ++v); | |
| min = Math.min(min, num); | |
| max = Math.max(max, num); | |
| } | |
| var prevIncEarn = 0; | |
| var prevExcEarn = 0; | |
| for (var i = min; i <= max; i++) { | |
| var incEarn = prevExcEarn + i * numToCount.getOrDefault(i, 0); | |
| var excEarn = Math.max(prevIncEarn, prevExcEarn); | |
| prevIncEarn = incEarn; | |
| prevExcEarn = excEarn; | |
| } | |
| return Math.max(prevIncEarn, prevExcEarn); | |
| }",20,20 | |
| ,"import java.util.UUID; | |
| public class UUIDUtil { | |
| public static String generate() { | |
| return UUID.randomUUID().toString(); | |
| } | |
| public static boolean isValid(String uuid) { | |
| try { | |
| UUID.fromString(uuid); | |
| return true; | |
| } catch (IllegalArgumentException e) { | |
| return false; | |
| } | |
| } | |
| } | |
| ",1.0,PERPLEXITY,Implement a Java utility to generate UUID v4 strings and validate their format,java,"import java.util.UUID; | |
| public class UUIDUtil { | |
| public static String generate() { | |
| return UUID.randomUUID().toString(); | |
| } | |
| public static boolean isValid(String uuid) { | |
| try { | |
| UUID.fromString(uuid); | |
| return true; | |
| } catch (IllegalArgumentException e) { | |
| return false; | |
| } | |
| } | |
| }",14,14 | |
| ,"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 | |
| ,"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 | |
| ,"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 | |
| ,"class Solution { | |
| public int findMaxLength(int[] nums) { | |
| // Map to store first occurrence of diff | |
| HashMap<Integer, Integer> map = new HashMap<>(); | |
| int zero = 0, one = 0; | |
| int res = 0; | |
| for (int i = 0; i < nums.length; i++) { | |
| if (nums[i] == 0) | |
| zero++; | |
| else | |
| one++; | |
| int diff = zero - one; | |
| // If diff == 0, subarray from 0 to i is valid | |
| if (diff == 0) { | |
| res = Math.max(res, i + 1); | |
| } | |
| // If diff not seen before, store index | |
| if (!map.containsKey(diff)) { | |
| map.put(diff, i); | |
| } | |
| // If seen before, calculate length | |
| else { | |
| int idx = map.get(diff); | |
| int len = i - idx; | |
| res = Math.max(res, len); | |
| } | |
| } | |
| return res; | |
| } | |
| }",0.0,leetcode,,java,"class Solution { | |
| public int findMaxLength(int[] nums) { | |
| // Map to store first occurrence of diff | |
| HashMap<Integer, Integer> map = new HashMap<>(); | |
| int zero = 0, one = 0; | |
| int res = 0; | |
| for (int i = 0; i < nums.length; i++) { | |
| if (nums[i] == 0) | |
| zero++; | |
| else | |
| one++; | |
| int diff = zero - one; | |
| // If diff == 0, subarray from 0 to i is valid | |
| if (diff == 0) { | |
| res = Math.max(res, i + 1); | |
| } | |
| // If diff not seen before, store index | |
| if (!map.containsKey(diff)) { | |
| map.put(diff, i); | |
| } | |
| // If seen before, calculate length | |
| else { | |
| int idx = map.get(diff); | |
| int len = i - idx; | |
| res = Math.max(res, len); | |
| } | |
| } | |
| return res; | |
| } | |
| }",37,37 | |
| ,"public class PalindromeChecker { | |
| public static boolean isPalindrome(String s) { | |
| s = s.toLowerCase().replaceAll(""[^a-z0-9]"", """"); | |
| int left = 0, right = s.length() - 1; | |
| while (left < right) { | |
| if (s.charAt(left++) != s.charAt(right--)) return false; | |
| } | |
| return true; | |
| } | |
| } | |
| ",1.0,PERPLEXITY,"Write a Java static method to check if a string is a palindrome, ignoring case and non-alphanumeric chars.",java,"public class PalindromeChecker { | |
| public static boolean isPalindrome(String s) { | |
| s = s.toLowerCase().replaceAll(""[^a-z0-9]"", """"); | |
| int left = 0, right = s.length() - 1; | |
| while (left < right) { | |
| if (s.charAt(left++) != s.charAt(right--)) return false; | |
| } | |
| return true; | |
| } | |
| }",10,10 | |
| ,"class Solution { | |
| public int getImportance(List<Employee> employees, int id) { | |
| Map<Integer, Employee> inputMap = new HashMap<>(); | |
| // Construct HashMap as getting the employee from id is difficult in a list | |
| for(Employee e : employees) { | |
| inputMap.put(e.id, e); | |
| } | |
| return helper(inputMap, id); | |
| } | |
| private static int helper(Map<Integer, Employee> inputMap, int id) { | |
| //Get the importance of the employee | |
| int imp = inputMap.get(id).importance; | |
| //Add importance of subordinates to employee importance | |
| for(int subId : inputMap.get(id).subordinates) { | |
| imp += helper(inputMap, subId); | |
| } | |
| return imp; | |
| } | |
| }",0.0,leetcode,,java,"class Solution { | |
| public int getImportance(List<Employee> employees, int id) { | |
| Map<Integer, Employee> inputMap = new HashMap<>(); | |
| // Construct HashMap as getting the employee from id is difficult in a list | |
| for(Employee e : employees) { | |
| inputMap.put(e.id, e); | |
| } | |
| return helper(inputMap, id); | |
| } | |
| private static int helper(Map<Integer, Employee> inputMap, int id) { | |
| //Get the importance of the employee | |
| int imp = inputMap.get(id).importance; | |
| //Add importance of subordinates to employee importance | |
| for(int subId : inputMap.get(id).subordinates) { | |
| imp += helper(inputMap, subId); | |
| } | |
| return imp; | |
| } | |
| }",22,22 | |
| ,"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 | |
| ,"import java.util.*; | |
| class Solution { | |
| public List<String> subdomainVisits(String[] cpdomains) { | |
| Map<String, Integer> map = new HashMap<>(); | |
| for (String domainCount : cpdomains) { | |
| int spaceIndex = domainCount.indexOf(' '); | |
| int count = Integer.parseInt(domainCount.substring(0, spaceIndex)); | |
| String domain = domainCount.substring(spaceIndex + 1); | |
| // Process each subdomain | |
| while (true) { | |
| map.merge(domain, count, Integer::sum); | |
| int dotIndex = domain.indexOf('.'); | |
| if (dotIndex == -1) break; | |
| domain = domain.substring(dotIndex + 1); | |
| } | |
| } | |
| List<String> result = new ArrayList<>(map.size()); | |
| for (Map.Entry<String, Integer> entry : map.entrySet()) { | |
| result.add(entry.getValue() + "" "" + entry.getKey()); | |
| } | |
| return result; | |
| } | |
| }",0.0,leetcode,,java,"import java.util.*; | |
| class Solution { | |
| public List<String> subdomainVisits(String[] cpdomains) { | |
| Map<String, Integer> map = new HashMap<>(); | |
| for (String domainCount : cpdomains) { | |
| int spaceIndex = domainCount.indexOf(' '); | |
| int count = Integer.parseInt(domainCount.substring(0, spaceIndex)); | |
| String domain = domainCount.substring(spaceIndex + 1); | |
| // Process each subdomain | |
| while (true) { | |
| map.merge(domain, count, Integer::sum); | |
| int dotIndex = domain.indexOf('.'); | |
| if (dotIndex == -1) break; | |
| domain = domain.substring(dotIndex + 1); | |
| } | |
| } | |
| List<String> result = new ArrayList<>(map.size()); | |
| for (Map.Entry<String, Integer> entry : map.entrySet()) { | |
| result.add(entry.getValue() + "" "" + entry.getKey()); | |
| } | |
| return result; | |
| } | |
| }",28,28 | |
| ,"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 | |
| ,"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 | |
| ,"#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 | |
| ,"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 { | |
| public boolean isPossible(int[] nums) { | |
| // freq: counts how many of each number are available to be used | |
| Map<Integer, Integer> freq = new HashMap<>(); | |
| // want: counts how many sequences are currently ending at (x-1) and need 'x' | |
| Map<Integer, Integer> want = new HashMap<>(); | |
| for (int i : nums) freq.put(i, freq.getOrDefault(i, 0) + 1); | |
| for (int i : nums) { | |
| if (freq.get(i) == 0) continue; // Already consumed by a previous 'new sequence' check | |
| // Option 1: Try to extend an existing sequence | |
| if (want.getOrDefault(i, 0) > 0) { | |
| freq.put(i, freq.get(i) - 1); | |
| want.put(i, want.get(i) - 1); | |
| want.put(i + 1, want.getOrDefault(i + 1, 0) + 1); | |
| } | |
| // Option 2: Try to create a new sequence of length 3 | |
| else if (freq.getOrDefault(i + 1, 0) > 0 && freq.getOrDefault(i + 2, 0) > 0) { | |
| freq.put(i, freq.get(i) - 1); | |
| freq.put(i + 1, freq.get(i + 1) - 1); | |
| freq.put(i + 2, freq.get(i + 2) - 1); | |
| // This sequence now ends at i+2, so it looks forward to i+3 | |
| want.put(i + 3, want.getOrDefault(i + 3, 0) + 1); | |
| } | |
| // Option 3: Impossible to use 'i' validly | |
| else { | |
| return false; | |
| } | |
| } | |
| return true; | |
| } | |
| }",0.0,leetcode,,java,"class Solution { | |
| public boolean isPossible(int[] nums) { | |
| // freq: counts how many of each number are available to be used | |
| Map<Integer, Integer> freq = new HashMap<>(); | |
| // want: counts how many sequences are currently ending at (x-1) and need 'x' | |
| Map<Integer, Integer> want = new HashMap<>(); | |
| for (int i : nums) freq.put(i, freq.getOrDefault(i, 0) + 1); | |
| for (int i : nums) { | |
| if (freq.get(i) == 0) continue; // Already consumed by a previous 'new sequence' check | |
| // Option 1: Try to extend an existing sequence | |
| if (want.getOrDefault(i, 0) > 0) { | |
| freq.put(i, freq.get(i) - 1); | |
| want.put(i, want.get(i) - 1); | |
| want.put(i + 1, want.getOrDefault(i + 1, 0) + 1); | |
| } | |
| // Option 2: Try to create a new sequence of length 3 | |
| else if (freq.getOrDefault(i + 1, 0) > 0 && freq.getOrDefault(i + 2, 0) > 0) { | |
| freq.put(i, freq.get(i) - 1); | |
| freq.put(i + 1, freq.get(i + 1) - 1); | |
| freq.put(i + 2, freq.get(i + 2) - 1); | |
| // This sequence now ends at i+2, so it looks forward to i+3 | |
| want.put(i + 3, want.getOrDefault(i + 3, 0) + 1); | |
| } | |
| // Option 3: Impossible to use 'i' validly | |
| else { | |
| return false; | |
| } | |
| } | |
| return true; | |
| } | |
| }",34,34 | |
| ,"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 | |
| ,"# 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 | |
| ,"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 | |
| ,"class Solution { | |
| public boolean wordPattern(String pattern, String s) { | |
| String[] words = s.split("" ""); | |
| if (pattern.length() != words.length) return false; | |
| Map<Character, String> charWord = new HashMap<>(); | |
| Map<String, Character> wordChar = new HashMap<>(); | |
| for (int i = 0; i < pattern.length(); i++) { | |
| char ch = pattern.charAt(i); | |
| String word = words[i]; | |
| if (charWord.containsKey(ch)) { | |
| if (!charWord.get(ch).equals(word)) { | |
| return false; | |
| } | |
| } else if (wordChar.containsKey(word)) { | |
| return false; | |
| } else { | |
| charWord.put(ch, word); | |
| wordChar.put(word, ch); | |
| } | |
| } | |
| return true; | |
| } | |
| }",0.0,leetcode,,java,"class Solution { | |
| public boolean wordPattern(String pattern, String s) { | |
| String[] words = s.split("" ""); | |
| if (pattern.length() != words.length) return false; | |
| Map<Character, String> charWord = new HashMap<>(); | |
| Map<String, Character> wordChar = new HashMap<>(); | |
| for (int i = 0; i < pattern.length(); i++) { | |
| char ch = pattern.charAt(i); | |
| String word = words[i]; | |
| if (charWord.containsKey(ch)) { | |
| if (!charWord.get(ch).equals(word)) { | |
| return false; | |
| } | |
| } else if (wordChar.containsKey(word)) { | |
| return false; | |
| } else { | |
| charWord.put(ch, word); | |
| wordChar.put(word, ch); | |
| } | |
| } | |
| return true; | |
| } | |
| }",29,29 | |
| ,"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 | |
| ,"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 | |
| ,"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 | |
| ,"public class MergeArrays { | |
| public static int[] merge(int[] a, int[] b) { | |
| int[] result = new int[a.length + b.length]; | |
| int i = 0, j = 0, k = 0; | |
| while (i < a.length && j < b.length) { | |
| if (a[i] <= b[j]) result[k++] = a[i++]; | |
| else result[k++] = b[j++]; | |
| } | |
| while (i < a.length) result[k++] = a[i++]; | |
| while (j < b.length) result[k++] = b[j++]; | |
| return result; | |
| } | |
| } | |
| ",1.0,PERPLEXITY,Create a Java method that merges two sorted integer arrays into one sorted array without extra space if possible.,java,"public class MergeArrays { | |
| public static int[] merge(int[] a, int[] b) { | |
| int[] result = new int[a.length + b.length]; | |
| int i = 0, j = 0, k = 0; | |
| while (i < a.length && j < b.length) { | |
| if (a[i] <= b[j]) result[k++] = a[i++]; | |
| else result[k++] = b[j++]; | |
| } | |
| while (i < a.length) result[k++] = a[i++]; | |
| while (j < b.length) result[k++] = b[j++]; | |
| return result; | |
| } | |
| }",13,13 | |
| ,"class Solution { | |
| public int nthUglyNumber(int n) { | |
| int[] primes = {2, 3, 5}; | |
| PriorityQueue<Long> uglyHeap = new PriorityQueue<>(); | |
| HashSet<Long> visited = new HashSet<>(); | |
| uglyHeap.add(1L); | |
| visited.add(1L); | |
| long curr = 1L; | |
| for (int i = 0; i < n; i++) { | |
| curr = uglyHeap.poll(); | |
| for (int prime : primes) { | |
| long new_ugly = curr * prime; | |
| if (!visited.contains(new_ugly)) { | |
| uglyHeap.add(new_ugly); | |
| visited.add(new_ugly); | |
| } | |
| } | |
| } | |
| return (int)curr; | |
| } | |
| }",0.0,leetcode,,java,"class Solution { | |
| public int nthUglyNumber(int n) { | |
| int[] primes = {2, 3, 5}; | |
| PriorityQueue<Long> uglyHeap = new PriorityQueue<>(); | |
| HashSet<Long> visited = new HashSet<>(); | |
| uglyHeap.add(1L); | |
| visited.add(1L); | |
| long curr = 1L; | |
| for (int i = 0; i < n; i++) { | |
| curr = uglyHeap.poll(); | |
| for (int prime : primes) { | |
| long new_ugly = curr * prime; | |
| if (!visited.contains(new_ugly)) { | |
| uglyHeap.add(new_ugly); | |
| visited.add(new_ugly); | |
| } | |
| } | |
| } | |
| return (int)curr; | |
| } | |
| }",23,23 | |
| ,"public class QuickSort { | |
| public static void sort(int[] arr, int low, int high) { | |
| if (low < high) { | |
| int pi = partition(arr, low, high); | |
| sort(arr, low, pi - 1); | |
| sort(arr, pi + 1, high); | |
| } | |
| } | |
| private static int partition(int[] arr, int low, int high) { | |
| int pivot = arr[high]; | |
| int i = low - 1; | |
| for (int j = low; j < high; j++) { | |
| if (arr[j] <= pivot) { | |
| i++; | |
| int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; | |
| } | |
| } | |
| int temp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp; | |
| return i + 1; | |
| } | |
| } | |
| ",1.0,PERPLEXITY,Write a Java quicksort algorithm to sort an integer array in-place using the Lomuto partition scheme,java,"public class QuickSort { | |
| public static void sort(int[] arr, int low, int high) { | |
| if (low < high) { | |
| int pi = partition(arr, low, high); | |
| sort(arr, low, pi - 1); | |
| sort(arr, pi + 1, high); | |
| } | |
| } | |
| private static int partition(int[] arr, int low, int high) { | |
| int pivot = arr[high]; | |
| int i = low - 1; | |
| for (int j = low; j < high; j++) { | |
| if (arr[j] <= pivot) { | |
| i++; | |
| int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; | |
| } | |
| } | |
| int temp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp; | |
| return i + 1; | |
| } | |
| }",21,21 | |
| ,"import java.util.*; | |
| class Solution { | |
| public int openLock(String[] deadends, String target) { | |
| Set<String> deadendSet = new HashSet<>(Arrays.asList(deadends)); | |
| if (deadendSet.contains(""0000"")) { | |
| return -1; | |
| } | |
| Queue<Pair<String, Integer>> queue = new LinkedList<>(); | |
| queue.offer(new Pair<>(""0000"", 0)); | |
| Set<String> visited = new HashSet<>(); | |
| visited.add(""0000""); | |
| while (!queue.isEmpty()) { | |
| Pair<String, Integer> current = queue.poll(); | |
| String currentCombination = current.getKey(); | |
| int moves = current.getValue(); | |
| if (currentCombination.equals(target)) { | |
| return moves; | |
| } | |
| for (int i = 0; i < 4; i++) { | |
| for (int delta : new int[]{-1, 1}) { | |
| int newDigit = (currentCombination.charAt(i) - '0' + delta + 10) % 10; | |
| String newCombination = currentCombination.substring(0, i) + | |
| newDigit + | |
| currentCombination.substring(i + 1); | |
| if (!visited.contains(newCombination) && !deadendSet.contains(newCombination)) { | |
| visited.add(newCombination); | |
| queue.offer(new Pair<>(newCombination, moves + 1)); | |
| } | |
| } | |
| } | |
| } | |
| return -1; // Target is not reachable | |
| } | |
| }",0.0,leetcode,,java,"import java.util.*; | |
| class Solution { | |
| public int openLock(String[] deadends, String target) { | |
| Set<String> deadendSet = new HashSet<>(Arrays.asList(deadends)); | |
| if (deadendSet.contains(""0000"")) { | |
| return -1; | |
| } | |
| Queue<Pair<String, Integer>> queue = new LinkedList<>(); | |
| queue.offer(new Pair<>(""0000"", 0)); | |
| Set<String> visited = new HashSet<>(); | |
| visited.add(""0000""); | |
| while (!queue.isEmpty()) { | |
| Pair<String, Integer> current = queue.poll(); | |
| String currentCombination = current.getKey(); | |
| int moves = current.getValue(); | |
| if (currentCombination.equals(target)) { | |
| return moves; | |
| } | |
| for (int i = 0; i < 4; i++) { | |
| for (int delta : new int[]{-1, 1}) { | |
| int newDigit = (currentCombination.charAt(i) - '0' + delta + 10) % 10; | |
| String newCombination = currentCombination.substring(0, i) + | |
| newDigit + | |
| currentCombination.substring(i + 1); | |
| if (!visited.contains(newCombination) && !deadendSet.contains(newCombination)) { | |
| visited.add(newCombination); | |
| queue.offer(new Pair<>(newCombination, moves + 1)); | |
| } | |
| } | |
| } | |
| } | |
| return -1; // Target is not reachable | |
| } | |
| }",41,41 | |
| ,"class TreeNode { | |
| int val; TreeNode left, right; | |
| TreeNode(int val) { this.val = val; } | |
| } | |
| public class TreeTraversal { | |
| public void inorder(TreeNode root, List<Integer> result) { | |
| if (root == null) return; | |
| inorder(root.left, result); | |
| result.add(root.val); | |
| inorder(root.right, result); | |
| } | |
| } | |
| ",1.0,PERPLEXITY,"Create a Java method for inorder traversal of a binary tree, collecting values in a List",java,"class TreeNode { | |
| int val; TreeNode left, right; | |
| TreeNode(int val) { this.val = val; } | |
| } | |
| public class TreeTraversal { | |
| public void inorder(TreeNode root, List<Integer> result) { | |
| if (root == null) return; | |
| inorder(root.left, result); | |
| result.add(root.val); | |
| inorder(root.right, result); | |
| } | |
| }",12,12 | |
| ,"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 | |
| ,"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 | |
| ,"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 | |
| ,"import org.apache.maven.plugin.AbstractMojo; | |
| import org.apache.maven.plugin.MojoExecutionException; | |
| import org.apache.maven.plugins.annotations.*; | |
| @Mojo(name = ""generate-props"", defaultPhase = LifecyclePhase.GENERATE_RESOURCES) | |
| public class PropertiesGeneratorMojo extends AbstractMojo { | |
| @Parameter(defaultValue = ""${project.build.directory}"") | |
| private String outputDirectory; | |
| public void execute() throws MojoExecutionException { | |
| getLog().info(""Generating properties file...""); | |
| // Generate properties logic here | |
| getLog().info(""Properties file generated successfully""); | |
| } | |
| } | |
| ",1.0,PERPLEXITY,Write a basic Maven plugin MOJO class that generates a properties file.,java,"import org.apache.maven.plugin.AbstractMojo; | |
| import org.apache.maven.plugin.MojoExecutionException; | |
| import org.apache.maven.plugins.annotations.*; | |
| @Mojo(name = ""generate-props"", defaultPhase = LifecyclePhase.GENERATE_RESOURCES) | |
| public class PropertiesGeneratorMojo extends AbstractMojo { | |
| @Parameter(defaultValue = ""${project.build.directory}"") | |
| private String outputDirectory; | |
| public void execute() throws MojoExecutionException { | |
| getLog().info(""Generating properties file...""); | |
| // Generate properties logic here | |
| getLog().info(""Properties file generated successfully""); | |
| } | |
| }",14,14 | |
| ,"class Solution { | |
| int maxF=0; | |
| List<Integer> maxSumArr = new ArrayList<>(); | |
| Map<Integer, Integer> f = new HashMap<>(); | |
| public int[] findFrequentTreeSum(TreeNode root) { | |
| solve(root); | |
| int[] arr = new int[maxSumArr.size()]; | |
| for(int i=0; i<arr.length; i++){ | |
| arr[i] = maxSumArr.get(i); | |
| } | |
| return arr; | |
| } | |
| public int solve(TreeNode root){ | |
| if(root == null) return 0; | |
| int sum = root.val + solve(root.left) + solve(root.right); | |
| f.put(sum , f.getOrDefault(sum, 0) + 1); | |
| if(f.get(sum) > maxF){ | |
| maxSumArr.clear(); | |
| maxSumArr.add(sum); | |
| maxF = f.get(sum); | |
| }else if(f.get(sum) == maxF){ | |
| maxSumArr.add(sum); | |
| } | |
| return sum; | |
| } | |
| }",0.0,leetcode,,java,"class Solution { | |
| int maxF=0; | |
| List<Integer> maxSumArr = new ArrayList<>(); | |
| Map<Integer, Integer> f = new HashMap<>(); | |
| public int[] findFrequentTreeSum(TreeNode root) { | |
| solve(root); | |
| int[] arr = new int[maxSumArr.size()]; | |
| for(int i=0; i<arr.length; i++){ | |
| arr[i] = maxSumArr.get(i); | |
| } | |
| return arr; | |
| } | |
| public int solve(TreeNode root){ | |
| if(root == null) return 0; | |
| int sum = root.val + solve(root.left) + solve(root.right); | |
| f.put(sum , f.getOrDefault(sum, 0) + 1); | |
| if(f.get(sum) > maxF){ | |
| maxSumArr.clear(); | |
| maxSumArr.add(sum); | |
| maxF = f.get(sum); | |
| }else if(f.get(sum) == maxF){ | |
| maxSumArr.add(sum); | |
| } | |
| return sum; | |
| } | |
| }",32,32 | |
| ,"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 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 java.util.Arrays; | |
| public class AnagramDetector { | |
| public static boolean areAnagrams(String s1, String s2) { | |
| s1 = s1.toLowerCase().replaceAll(""\\s"", """"); | |
| s2 = s2.toLowerCase().replaceAll(""\\s"", """"); | |
| if (s1.length() != s2.length()) return false; | |
| char[] a1 = s1.toCharArray(); char[] a2 = s2.toCharArray(); | |
| Arrays.sort(a1); Arrays.sort(a2); | |
| return Arrays.equals(a1, a2); | |
| } | |
| } | |
| ",1.0,PERPLEXITY,"Create a Java function to detect if two strings are anagrams, ignoring case and spaces.",java,"import java.util.Arrays; | |
| public class AnagramDetector { | |
| public static boolean areAnagrams(String s1, String s2) { | |
| s1 = s1.toLowerCase().replaceAll(""\\s"", """"); | |
| s2 = s2.toLowerCase().replaceAll(""\\s"", """"); | |
| if (s1.length() != s2.length()) return false; | |
| char[] a1 = s1.toCharArray(); char[] a2 = s2.toCharArray(); | |
| Arrays.sort(a1); Arrays.sort(a2); | |
| return Arrays.equals(a1, a2); | |
| } | |
| }",11,11 | |
| ,"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 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 | |
| ,"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 | |
| ,"# 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 | |
| ,"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<Exception> 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> T execute(Callable<T> 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<Exception> 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<Exception> 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<Exception> 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> T execute(Callable<T> 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<Exception> 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<Exception> retryPredicate) { | |
| this.retryPredicate = retryPredicate; | |
| return this; | |
| } | |
| public RetryExecutor build() { | |
| return new RetryExecutor(this); | |
| } | |
| } | |
| }",105,101 | |
| ,"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 | |
| ,"static boolean match(String s,String p){ | |
| boolean[][] d=new boolean[s.length()+1][p.length()+1]; | |
| d[0][0]=true; | |
| for(int j=2;j<=p.length();j++) | |
| if(p.charAt(j-1)=='*') d[0][j]=d[0][j-2]; | |
| for(int i=1;i<=s.length();i++) | |
| for(int j=1;j<=p.length();j++) | |
| if(p.charAt(j-1)=='*') | |
| d[i][j]=d[i][j-2]||(d[i-1][j]&&(p.charAt(j-2)=='.'||p.charAt(j-2)==s.charAt(i-1))); | |
| else | |
| d[i][j]=d[i-1][j-1]&&(p.charAt(j-1)=='.'||p.charAt(j-1)==s.charAt(i-1)); | |
| return d[s.length()][p.length()]; | |
| } | |
| ",1.0,GPT,write a java program to Implement regex matcher with . and *. ,java,"static boolean match(String s,String p){ | |
| boolean[][] d=new boolean[s.length()+1][p.length()+1]; | |
| d[0][0]=true; | |
| for(int j=2;j<=p.length();j++) | |
| if(p.charAt(j-1)=='*') d[0][j]=d[0][j-2]; | |
| for(int i=1;i<=s.length();i++) | |
| for(int j=1;j<=p.length();j++) | |
| if(p.charAt(j-1)=='*') | |
| d[i][j]=d[i][j-2]||(d[i-1][j]&&(p.charAt(j-2)=='.'||p.charAt(j-2)==s.charAt(i-1))); | |
| else | |
| d[i][j]=d[i-1][j-1]&&(p.charAt(j-1)=='.'||p.charAt(j-1)==s.charAt(i-1)); | |
| return d[s.length()][p.length()]; | |
| }",13,13 | |
| ,"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<String, Window> userWindows; | |
| private static class Window { | |
| final ConcurrentLinkedQueue<Long> 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<String, Window> userWindows; | |
| private static class Window { | |
| final ConcurrentLinkedQueue<Long> 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 | |
| ,"# 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 | |
| ,"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 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 { | |
| public Node cloneGraph(Node node) { | |
| if (node == null) return null; | |
| Map<Node, Node> copiedMap = new HashMap<>(); | |
| bfs(node, copiedMap); | |
| return copiedMap.get(node); | |
| } | |
| private void bfs(Node startNode, Map<Node, Node> copiedMap) { | |
| Queue<Node> queue = new ArrayDeque<>(); // include nodes that have been visited (copied) only | |
| // check & copy node at Generation | |
| copiedMap.put(startNode, new Node(startNode.val)); | |
| queue.offer(startNode); | |
| while (!queue.isEmpty()) { | |
| Node node = queue.poll(); | |
| // copy & link, add neighbors to Queue | |
| for (Node neighbor: node.neighbors) { | |
| // check & copy node at Generation | |
| if (copiedMap.containsKey(neighbor)) { // neighbor is already visited (copied), just link | |
| // IMPORTANT: DON'T JUST CONTINUE! | |
| copiedMap.get(node).neighbors.add(copiedMap.get(neighbor)); | |
| } else { // copy, link, add neighbor to queue to be visited | |
| copiedMap.put(neighbor, new Node(neighbor.val)); | |
| queue.offer(neighbor); | |
| copiedMap.get(node).neighbors.add(copiedMap.get(neighbor)); | |
| } | |
| } | |
| } | |
| } | |
| }",0.0,leetcode,,java,"class Solution { | |
| public Node cloneGraph(Node node) { | |
| if (node == null) return null; | |
| Map<Node, Node> copiedMap = new HashMap<>(); | |
| bfs(node, copiedMap); | |
| return copiedMap.get(node); | |
| } | |
| private void bfs(Node startNode, Map<Node, Node> copiedMap) { | |
| Queue<Node> queue = new ArrayDeque<>(); // include nodes that have been visited (copied) only | |
| // check & copy node at Generation | |
| copiedMap.put(startNode, new Node(startNode.val)); | |
| queue.offer(startNode); | |
| while (!queue.isEmpty()) { | |
| Node node = queue.poll(); | |
| // copy & link, add neighbors to Queue | |
| for (Node neighbor: node.neighbors) { | |
| // check & copy node at Generation | |
| if (copiedMap.containsKey(neighbor)) { // neighbor is already visited (copied), just link | |
| // IMPORTANT: DON'T JUST CONTINUE! | |
| copiedMap.get(node).neighbors.add(copiedMap.get(neighbor)); | |
| } else { // copy, link, add neighbor to queue to be visited | |
| copiedMap.put(neighbor, new Node(neighbor.val)); | |
| queue.offer(neighbor); | |
| copiedMap.get(node).neighbors.add(copiedMap.get(neighbor)); | |
| } | |
| } | |
| } | |
| } | |
| }",34,34 | |