id stringlengths 22 24 | content stringlengths 88 2.59k | max_stars_repo_path stringlengths 40 71 |
|---|---|---|
quixbugs-python_data_1 |
def knapsack(capacity, items):
from collections import defaultdict
memo = defaultdict(int)
for i in range(1, len(items) + 1):
weight, value = items[i - 1]
for j in range(1, capacity + 1):
memo[i, j] = memo[i - 1, j]
if weight < j:
memo[i, j] = max(... | QuixBugs/QuixBugs/python_programs/knapsack.py |
quixbugs-python_data_2 | def gcd(a, b):
if b == 0:
return a
else:
return gcd(a % b, b)
"""
Input:
a: A nonnegative int
b: A nonnegative int
Greatest Common Divisor
Precondition:
isinstance(a, int) and isinstance(b, int)
Output:
The greatest int that divides evenly into a and b
Example:
>>> gcd... | QuixBugs/QuixBugs/python_programs/gcd.py |
quixbugs-python_data_3 |
def is_valid_parenthesization(parens):
depth = 0
for paren in parens:
if paren == '(':
depth += 1
else:
depth -= 1
if depth < 0:
return False
return True
"""
Nested Parens
Input:
parens: A string of parentheses
Precondition:
al... | QuixBugs/QuixBugs/python_programs/is_valid_parenthesization.py |
quixbugs-python_data_4 |
def minimum_spanning_tree(weight_by_edge):
group_by_node = {}
mst_edges = set()
for edge in sorted(weight_by_edge, key=weight_by_edge.__getitem__):
u, v = edge
if group_by_node.setdefault(u, {u}) != group_by_node.setdefault(v, {v}):
mst_edges.add(edge)
group_by_node... | QuixBugs/QuixBugs/python_programs/minimum_spanning_tree.py |
quixbugs-python_data_5 | from .node import Node
from .reverse_linked_list import reverse_linked_list
"""
Driver to test reverse linked list
"""
def main():
# Case 1: 5-node list input
# Expected Output: 1 2 3 4 5
node1 = Node(1)
node2 = Node(2, node1)
node3 = Node(3, node2)
node4 = Node(4, node3)
node5 = Node(5, n... | QuixBugs/QuixBugs/python_programs/reverse_linked_list_test.py |
quixbugs-python_data_6 | from .node import Node
from .detect_cycle import detect_cycle
"""
Driver to test reverse linked list
"""
def main():
# Case 1: 5-node list input with no cycle
# Expected Output: Cycle not detected!
node1 = Node(1)
node2 = Node(2, node1)
node3 = Node(3, node2)
node4 = Node(4, node3)
node5 =... | QuixBugs/QuixBugs/python_programs/detect_cycle_test.py |
quixbugs-python_data_7 | def wrap(text, cols):
lines = []
while len(text) > cols:
end = text.rfind(' ', 0, cols + 1)
if end == -1:
end = cols
line, text = text[:end], text[end:]
lines.append(line)
return lines
"""
Wrap Text
Given a long string and a column width, break the string on sp... | QuixBugs/QuixBugs/python_programs/wrap.py |
quixbugs-python_data_8 | from .node import Node
from .breadth_first_search import breadth_first_search
"""
Driver to test breadth first search
"""
def main():
# Case 1: Strongly connected graph
# Output: Path found!
station1 = Node("Westminster")
station2 = Node("Waterloo", None, [station1])
station3 = Node("Trafalgar Squ... | QuixBugs/QuixBugs/python_programs/breadth_first_search_test.py |
quixbugs-python_data_9 | def topological_ordering(nodes):
ordered_nodes = [node for node in nodes if not node.incoming_nodes]
for node in ordered_nodes:
for nextnode in node.outgoing_nodes:
if set(ordered_nodes).issuperset(nextnode.outgoing_nodes) and nextnode not in ordered_nodes:
ordered_nodes.app... | QuixBugs/QuixBugs/python_programs/topological_ordering.py |
quixbugs-python_data_10 | def next_palindrome(digit_list):
high_mid = len(digit_list) // 2
low_mid = (len(digit_list) - 1) // 2
while high_mid < len(digit_list) and low_mid >= 0:
if digit_list[high_mid] == 9:
digit_list[high_mid] = 0
digit_list[low_mid] = 0
high_mid += 1
low_mi... | QuixBugs/QuixBugs/python_programs/next_palindrome.py |
quixbugs-python_data_11 | def reverse_linked_list(node):
prevnode = None
while node:
nextnode = node.successor
node.successor = prevnode
node = nextnode
return prevnode
"""
Reverse Linked List
Reverses a linked list and returns the new head.
Input:
node: The head of a singly-linked list
Precondition:... | QuixBugs/QuixBugs/python_programs/reverse_linked_list.py |
quixbugs-python_data_12 |
def powerset(arr):
if arr:
first, *rest = arr #python3 just like car and cdr (in this case anyway..)
rest_subsets = powerset(rest)
return [[first] + subset for subset in rest_subsets]
else:
return [[]]
"""
Power Set
Input:
arr: A list
Precondition:
arr has no duplica... | QuixBugs/QuixBugs/python_programs/powerset.py |
quixbugs-python_data_13 |
def get_factors(n):
if n == 1:
return []
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return [i] + get_factors(n // i)
return []
"""
Prime Factorization
Factors an int using naive trial division.
Input:
n: An int to factor
Output:
A list of the prime fact... | QuixBugs/QuixBugs/python_programs/get_factors.py |
quixbugs-python_data_14 | def kth(arr, k):
pivot = arr[0]
below = [x for x in arr if x < pivot]
above = [x for x in arr if x > pivot]
num_less = len(below)
num_lessoreq = len(arr) - len(above)
if k < num_less:
return kth(below, k)
elif k >= num_lessoreq:
return kth(above, k)
else:
return... | QuixBugs/QuixBugs/python_programs/kth.py |
quixbugs-python_data_15 | def subsequences(a, b, k):
if k == 0:
return []
ret = []
for i in range(a, b + 1 - k):
ret.extend(
[i] + rest for rest in subsequences(i + 1, b, k - 1)
)
return ret
"""
Subsequences
Input:
a: An int
b: An int
k: A positive int
Output:
A list of ... | QuixBugs/QuixBugs/python_programs/subsequences.py |
quixbugs-python_data_16 | def levenshtein(source, target):
if source == '' or target == '':
return len(source) or len(target)
elif source[0] == target[0]:
return 1 + levenshtein(source[1:], target[1:])
else:
return 1 + min(
levenshtein(source, target[1:]),
levenshtein(source[1:],... | QuixBugs/QuixBugs/python_programs/levenshtein.py |
quixbugs-python_data_17 |
def lis(arr):
ends = {}
longest = 0
for i, val in enumerate(arr):
prefix_lengths = [j for j in range(1, longest + 1) if arr[ends[j]] < val]
length = max(prefix_lengths) if prefix_lengths else 0
if length == longest or val < arr[ends[length + 1]]:
ends[length + 1] = i... | QuixBugs/QuixBugs/python_programs/lis.py |
quixbugs-python_data_18 |
def pascal(n):
rows = [[1]]
for r in range(1, n):
row = []
for c in range(0, r):
upleft = rows[r - 1][c - 1] if c > 0 else 0
upright = rows[r - 1][c] if c < r else 0
row.append(upleft + upright)
rows.append(row)
return rows
"""
Pascal's Triangl... | QuixBugs/QuixBugs/python_programs/pascal.py |
quixbugs-python_data_19 | from .node import Node
from .depth_first_search import depth_first_search
"""
Driver to test depth first search
"""
def main():
# Case 1: Strongly connected graph
# Output: Path found!
station1 = Node("Westminster")
station2 = Node("Waterloo", None, [station1])
station3 = Node("Trafalgar Square", ... | QuixBugs/QuixBugs/python_programs/depth_first_search_test.py |
quixbugs-python_data_20 | class Node:
def __init__(self, value=None, successor=None, successors=[], predecessors=[], incoming_nodes=[], outgoing_nodes=[]):
self.value = value
self.successor = successor
self.successors = successors
self.predecessors = predecessors
self.incoming_nodes = incoming_nodes
... | QuixBugs/QuixBugs/python_programs/node.py |
quixbugs-python_data_21 |
import string
def to_base(num, b):
result = ''
alphabet = string.digits + string.ascii_uppercase
while num > 0:
i = num % b
num = num // b
result = result + alphabet[i]
return result
"""
Integer Base Conversion
base-conversion
Input:
num: A base-10 integer to convert.
... | QuixBugs/QuixBugs/python_programs/to_base.py |
quixbugs-python_data_22 |
def next_permutation(perm):
for i in range(len(perm) - 2, -1, -1):
if perm[i] < perm[i + 1]:
for j in range(len(perm) - 1, i, -1):
if perm[j] < perm[i]:
next_perm = list(perm)
next_perm[i], next_perm[j] = perm[j], perm[i]
... | QuixBugs/QuixBugs/python_programs/next_permutation.py |
quixbugs-python_data_23 | def quicksort(arr):
if not arr:
return []
pivot = arr[0]
lesser = quicksort([x for x in arr[1:] if x < pivot])
greater = quicksort([x for x in arr[1:] if x > pivot])
return lesser + [pivot] + greater
"""
QuickSort
Input:
arr: A list of ints
Output:
The elements of arr in sorted ... | QuixBugs/QuixBugs/python_programs/quicksort.py |
quixbugs-python_data_24 |
from collections import deque as Queue
def breadth_first_search(startnode, goalnode):
queue = Queue()
queue.append(startnode)
nodesseen = set()
nodesseen.add(startnode)
while True:
node = queue.popleft()
if node is goalnode:
return True
else:
queu... | QuixBugs/QuixBugs/python_programs/breadth_first_search.py |
quixbugs-python_data_25 | # Python 3
def possible_change(coins, total):
if total == 0:
return 1
if total < 0:
return 0
first, *rest = coins
return possible_change(coins, total - first) + possible_change(rest, total)
"""
Making Change
change
Input:
coins: A list of positive ints representing coin denomin... | QuixBugs/QuixBugs/python_programs/possible_change.py |
quixbugs-python_data_26 | def kheapsort(arr, k):
import heapq
heap = arr[:k]
heapq.heapify(heap)
for x in arr:
yield heapq.heappushpop(heap, x)
while heap:
yield heapq.heappop(heap)
"""
K-Heapsort
k-heapsort
Sorts an almost-sorted array, wherein every element is no more than k units from its sorted posi... | QuixBugs/QuixBugs/python_programs/kheapsort.py |
quixbugs-python_data_27 |
def rpn_eval(tokens):
def op(symbol, a, b):
return {
'+': lambda a, b: a + b,
'-': lambda a, b: a - b,
'*': lambda a, b: a * b,
'/': lambda a, b: a / b
}[symbol](a, b)
stack = []
for token in tokens:
if isinstance(token, float):
... | QuixBugs/QuixBugs/python_programs/rpn_eval.py |
quixbugs-python_data_28 | from .minimum_spanning_tree import minimum_spanning_tree
"""
Driver to test minimum spanning tree
"""
def main():
# Case 1: Simple tree input.
# Output: (1, 2) (3, 4) (1, 4)
result = minimum_spanning_tree({
(1, 2): 10,
(2, 3): 15,
(3, 4): 10,
(1, 4): 10})
for edge in re... | QuixBugs/QuixBugs/python_programs/minimum_spanning_tree_test.py |
quixbugs-python_data_29 | def find_in_sorted(arr, x):
def binsearch(start, end):
if start == end:
return -1
mid = start + (end - start) // 2
if x < arr[mid]:
return binsearch(start, mid)
elif x > arr[mid]:
return binsearch(mid, end)
else:
return mid
... | QuixBugs/QuixBugs/python_programs/find_in_sorted.py |
quixbugs-python_data_30 | def depth_first_search(startnode, goalnode):
nodesvisited = set()
def search_from(node):
if node in nodesvisited:
return False
elif node is goalnode:
return True
else:
return any(
search_from(nextnode) for nextnode in node.successors
... | QuixBugs/QuixBugs/python_programs/depth_first_search.py |
quixbugs-python_data_31 | def bucketsort(arr, k):
counts = [0] * k
for x in arr:
counts[x] += 1
sorted_arr = []
for i, count in enumerate(arr):
sorted_arr.extend([i] * count)
return sorted_arr
"""
Bucket Sort
Input:
arr: A list of small ints
k: Upper bound of the size of the ints in arr (not in... | QuixBugs/QuixBugs/python_programs/bucketsort.py |
quixbugs-python_data_32 | def flatten(arr):
for x in arr:
if isinstance(x, list):
for y in flatten(x):
yield y
else:
yield flatten(x)
"""
Flatten
Flattens a nested list data structure into a single list.
Input:
arr: A list
Precondition:
The input has no list containment ... | QuixBugs/QuixBugs/python_programs/flatten.py |
quixbugs-python_data_33 |
def mergesort(arr):
def merge(left, right):
result = []
i = 0
j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j +... | QuixBugs/QuixBugs/python_programs/mergesort.py |
quixbugs-python_data_34 |
def bitcount(n):
count = 0
while n:
n ^= n - 1
count += 1
return count
"""
Bitcount
bitcount
Input:
n: a nonnegative int
Output:
The number of 1-bits in the binary encoding of n
Examples:
>>> bitcount(127)
7
>>> bitcount(128)
1
"""
| QuixBugs/QuixBugs/python_programs/bitcount.py |
quixbugs-python_data_35 |
def shortest_paths(source, weight_by_edge):
weight_by_node = {
v: float('inf') for u, v in weight_by_edge
}
weight_by_node[source] = 0
for i in range(len(weight_by_node) - 1):
for (u, v), weight in weight_by_edge.items():
weight_by_edge[u, v] = min(
weight_b... | QuixBugs/QuixBugs/python_programs/shortest_paths.py |
quixbugs-python_data_36 | def longest_common_subsequence(a, b):
if not a or not b:
return ''
elif a[0] == b[0]:
return a[0] + longest_common_subsequence(a[1:], b)
else:
return max(
longest_common_subsequence(a, b[1:]),
longest_common_subsequence(a[1:], b),
key=len
... | QuixBugs/QuixBugs/python_programs/longest_common_subsequence.py |
quixbugs-python_data_37 | from .shortest_path_lengths import shortest_path_lengths
"""
Test shortest path lengths
"""
def main():
# Case 1: Basic graph input.
# Output:
graph = {
(0, 2): 3,
(0, 5): 5,
(2, 1): -2,
(2, 3): 7,
(2, 4): 4,
(3, 4): -5,
(4, 5): -1
}
result =... | QuixBugs/QuixBugs/python_programs/shortest_path_lengths_test.py |
quixbugs-python_data_38 |
def shunting_yard(tokens):
precedence = {
'+': 1,
'-': 1,
'*': 2,
'/': 2
}
rpntokens = []
opstack = []
for token in tokens:
if isinstance(token, int):
rpntokens.append(token)
else:
while opstack and precedence[token] <= preced... | QuixBugs/QuixBugs/python_programs/shunting_yard.py |
quixbugs-python_data_39 | def detect_cycle(node):
hare = tortoise = node
while True:
if hare.successor is None:
return False
tortoise = tortoise.successor
hare = hare.successor.successor
if hare is tortoise:
return True
"""
Linked List Cycle Detection
tortoise-hare
Implement... | QuixBugs/QuixBugs/python_programs/detect_cycle.py |
quixbugs-python_data_40 | from .node import Node
from .topological_ordering import topological_ordering
"""
Driver to test topological ordering
"""
def main():
# Case 1: Wikipedia graph
# Output: 5 7 3 11 8 10 2 9
five = Node(5)
seven = Node(7)
three = Node(3)
eleven = Node(11)
eight = Node(8)
two = Node(2... | QuixBugs/QuixBugs/python_programs/topological_ordering_test.py |
quixbugs-python_data_41 | def find_first_in_sorted(arr, x):
lo = 0
hi = len(arr)
while lo <= hi:
mid = (lo + hi) // 2
if x == arr[mid] and (mid == 0 or x != arr[mid - 1]):
return mid
elif x <= arr[mid]:
hi = mid
else:
lo = mid + 1
return -1
"""
Fancy Bina... | QuixBugs/QuixBugs/python_programs/find_first_in_sorted.py |
quixbugs-python_data_42 |
def sqrt(x, epsilon):
approx = x / 2
while abs(x - approx) > epsilon:
approx = 0.5 * (approx + x / approx)
return approx
"""
Square Root
Newton-Raphson method implementation.
Input:
x: A float
epsilon: A float
Precondition:
x >= 1 and epsilon > 0
Output:
A float in the interva... | QuixBugs/QuixBugs/python_programs/sqrt.py |
quixbugs-python_data_43 | from collections import defaultdict
def shortest_path_lengths(n, length_by_edge):
length_by_path = defaultdict(lambda: float('inf'))
length_by_path.update({(i, i): 0 for i in range(n)})
length_by_path.update(length_by_edge)
for k in range(n):
for i in range(n):
for j in range(n):
... | QuixBugs/QuixBugs/python_programs/shortest_path_lengths.py |
quixbugs-python_data_44 | def lcs_length(s, t):
from collections import Counter
dp = Counter()
for i in range(len(s)):
for j in range(len(t)):
if s[i] == t[j]:
dp[i, j] = dp[i - 1, j] + 1
return max(dp.values()) if dp else 0
"""
Longest Common Substring
longest-common-substring
Input:
... | QuixBugs/QuixBugs/python_programs/lcs_length.py |
quixbugs-python_data_45 | def hanoi(height, start=1, end=3):
steps = []
if height > 0:
helper = ({1, 2, 3} - {start} - {end}).pop()
steps.extend(hanoi(height - 1, start, helper))
steps.append((start, helper))
steps.extend(hanoi(height - 1, helper, end))
return steps
"""
Towers of Hanoi
hanoi
An a... | QuixBugs/QuixBugs/python_programs/hanoi.py |
quixbugs-python_data_46 | from .shortest_paths import shortest_paths
"""
Test shortest paths
"""
def main():
# Case 1: Graph with multiple paths
# Output: {'A': 0, 'C': 3, 'B': 1, 'E': 5, 'D': 10, 'F': 4}
graph = {
('A', 'B'): 3,
('A', 'C'): 3,
('A', 'F'): 5,
('C', 'B'): -2,
('C', 'D'): 7,
... | QuixBugs/QuixBugs/python_programs/shortest_paths_test.py |
quixbugs-python_data_47 |
def max_sublist_sum(arr):
max_ending_here = 0
max_so_far = 0
for x in arr:
max_ending_here = max_ending_here + x
max_so_far = max(max_so_far, max_ending_here)
return max_so_far
"""
Max Sublist Sum
max-sublist-sum
Efficient equivalent to max(sum(arr[i:j]) for 0 <= i <= j <= len(arr)... | QuixBugs/QuixBugs/python_programs/max_sublist_sum.py |
quixbugs-python_data_48 | from heapq import *
def shortest_path_length(length_by_edge, startnode, goalnode):
unvisited_nodes = [] # FibHeap containing (node, distance) pairs
heappush(unvisited_nodes, (0, startnode))
visited_nodes = set()
while len(unvisited_nodes) > 0:
distance, node = heappop(unvisited_nodes)
... | QuixBugs/QuixBugs/python_programs/shortest_path_length.py |
quixbugs-python_data_49 | def sieve(max):
primes = []
for n in range(2, max + 1):
if any(n % p > 0 for p in primes):
primes.append(n)
return primes
"""
Sieve of Eratosthenes
prime-sieve
Input:
max: A positive int representing an upper bound.
Output:
A list containing all primes up to and including max
... | QuixBugs/QuixBugs/python_programs/sieve.py |
quixbugs-python_data_50 | from .node import Node
from .shortest_path_length import shortest_path_length
"""
Test shortest path length
"""
def main():
node1 = Node("1")
node5 = Node("5")
node4 = Node("4", None, [node5])
node3 = Node("3", None, [node4])
node2 = Node("2", None, [node1, node3, node4])
node0 = Node("0", No... | QuixBugs/QuixBugs/python_programs/shortest_path_length_test.py |
quixbugs-python_data_51 |
def knapsack(capacity, items):
from collections import defaultdict
memo = defaultdict(int)
for i in range(1, len(items) + 1):
weight, value = items[i - 1]
for j in range(1, capacity + 1):
memo[i, j] = memo[i - 1, j]
if weight <= j:
memo[i, j] = max... | QuixBugs/QuixBugs/correct_python_programs/knapsack.py |
quixbugs-python_data_52 |
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
| QuixBugs/QuixBugs/correct_python_programs/gcd.py |
quixbugs-python_data_53 |
def is_valid_parenthesization(parens):
depth = 0
for paren in parens:
if paren == '(':
depth += 1
else:
depth -= 1
if depth < 0:
return False
return depth == 0
"""
def is_valid_parenthesization(parens):
depth = 0
for paren in par... | QuixBugs/QuixBugs/correct_python_programs/is_valid_parenthesization.py |
quixbugs-python_data_54 |
def minimum_spanning_tree(weight_by_edge):
group_by_node = {}
mst_edges = set()
for edge in sorted(weight_by_edge, key=weight_by_edge.__getitem__):
u, v = edge
if group_by_node.setdefault(u, {u}) != group_by_node.setdefault(v, {v}):
mst_edges.add(edge)
group_by_node... | QuixBugs/QuixBugs/correct_python_programs/minimum_spanning_tree.py |
quixbugs-python_data_55 | from .node import Node
from .reverse_linked_list import reverse_linked_list
"""
Driver to test reverse linked list
"""
def main():
# Case 1: 5-node list input
# Expected Output: 1 2 3 4 5
node1 = Node(1)
node2 = Node(2, node1)
node3 = Node(3, node2)
node4 = Node(4, node3)
node5 = Node(5, n... | QuixBugs/QuixBugs/correct_python_programs/reverse_linked_list_test.py |
quixbugs-python_data_56 | from .node import Node
from .detect_cycle import detect_cycle
"""
Driver to test reverse linked list
"""
def main():
# Case 1: 5-node list input with no cycle
# Expected Output: Cycle not detected!
node1 = Node(1)
node2 = Node(2, node1)
node3 = Node(3, node2)
node4 = Node(4, node3)
node5 =... | QuixBugs/QuixBugs/correct_python_programs/detect_cycle_test.py |
quixbugs-python_data_57 |
def wrap(text, cols):
lines = []
while len(text) > cols:
end = text.rfind(' ', 0, cols + 1)
if end == -1:
end = cols
line, text = text[:end], text[end:]
lines.append(line)
lines.append(text)
return lines
| QuixBugs/QuixBugs/correct_python_programs/wrap.py |
quixbugs-python_data_58 | from .node import Node
from .breadth_first_search import breadth_first_search
"""
Driver to test breadth first search
"""
def main():
# Case 1: Strongly connected graph
# Output: Path found!
station1 = Node("Westminster")
station2 = Node("Waterloo", None, [station1])
station3 = Node("Trafalgar Squ... | QuixBugs/QuixBugs/correct_python_programs/breadth_first_search_test.py |
quixbugs-python_data_59 | def topological_ordering(nodes):
ordered_nodes = [node for node in nodes if not node.incoming_nodes]
for node in ordered_nodes:
for nextnode in node.outgoing_nodes:
if set(ordered_nodes).issuperset(nextnode.incoming_nodes) and nextnode not in ordered_nodes:
ordered_nodes.app... | QuixBugs/QuixBugs/correct_python_programs/topological_ordering.py |
quixbugs-python_data_60 | def next_palindrome(digit_list):
high_mid = len(digit_list) // 2
low_mid = (len(digit_list) - 1) // 2
while high_mid < len(digit_list) and low_mid >= 0:
if digit_list[high_mid] == 9:
digit_list[high_mid] = 0
digit_list[low_mid] = 0
high_mid += 1
low_mi... | QuixBugs/QuixBugs/correct_python_programs/next_palindrome.py |
quixbugs-python_data_61 |
def reverse_linked_list(node):
prevnode = None
while node:
nextnode = node.successor
node.successor = prevnode
prevnode = node
node = nextnode
return prevnode
"""
def reverse_linked_list(node):
prevnode = None
while node:
nextnode = node.successor
no... | QuixBugs/QuixBugs/correct_python_programs/reverse_linked_list.py |
quixbugs-python_data_62 |
def powerset(arr):
if arr:
first, *rest = arr
rest_subsets = powerset(rest)
return rest_subsets + [[first] + subset for subset in rest_subsets]
else:
return [[]]
"""
def powerset(arr):
if arr:
first, *rest = arr
rest_subsets = powerset(rest)
return [... | QuixBugs/QuixBugs/correct_python_programs/powerset.py |
quixbugs-python_data_63 |
def get_factors(n):
if n == 1:
return []
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return [i] + get_factors(n // i)
return [n]
"""
def get_factors(n):
if n == 1:
return []
for i in range(2, n + 1):
if n % i == 0:
return [i] + ge... | QuixBugs/QuixBugs/correct_python_programs/get_factors.py |
quixbugs-python_data_64 |
def kth(arr, k):
pivot = arr[0]
below = [x for x in arr if x < pivot]
above = [x for x in arr if x > pivot]
num_less = len(below)
num_lessoreq = len(arr) - len(above)
if k < num_less:
return kth(below, k)
elif k >= num_lessoreq:
return kth(above, k - num_lessoreq)
else... | QuixBugs/QuixBugs/correct_python_programs/kth.py |
quixbugs-python_data_65 |
def subsequences(a, b, k):
if k == 0:
return [[]]
ret = []
for i in range(a, b + 1 - k):
ret.extend(
[i] + rest for rest in subsequences(i + 1, b, k - 1)
)
return ret
| QuixBugs/QuixBugs/correct_python_programs/subsequences.py |
quixbugs-python_data_66 |
def levenshtein(source, target):
if source == '' or target == '':
return len(source) or len(target)
elif source[0] == target[0]:
return levenshtein(source[1:], target[1:])
else:
return 1 + min(
levenshtein(source, target[1:]),
levenshtein(source[1:], ta... | QuixBugs/QuixBugs/correct_python_programs/levenshtein.py |
quixbugs-python_data_67 |
def lis(arr):
ends = {}
longest = 0
for i, val in enumerate(arr):
prefix_lengths = [j for j in range(1, longest + 1) if arr[ends[j]] < val]
length = max(prefix_lengths) if prefix_lengths else 0
if length == longest or val < arr[ends[length + 1]]:
ends[length + 1] = i... | QuixBugs/QuixBugs/correct_python_programs/lis.py |
quixbugs-python_data_68 |
def pascal(n):
rows = [[1]]
for r in range(1, n):
row = []
for c in range(0, r + 1):
upleft = rows[r - 1][c - 1] if c > 0 else 0
upright = rows[r - 1][c] if c < r else 0
row.append(upleft + upright)
rows.append(row)
return rows
| QuixBugs/QuixBugs/correct_python_programs/pascal.py |
quixbugs-python_data_69 | from .node import Node
from .depth_first_search import depth_first_search
"""
Driver to test depth first search
"""
def main():
# Case 1: Strongly connected graph
# Output: Path found!
station1 = Node("Westminster")
station2 = Node("Waterloo", None, [station1])
station3 = Node("Trafalgar Square", ... | QuixBugs/QuixBugs/correct_python_programs/depth_first_search_test.py |
quixbugs-python_data_70 | class Node:
def __init__(self, value=None, successor=None, successors=[], predecessors=[], incoming_nodes=[], outgoing_nodes=[]):
self.value = value
self.successor = successor
self.successors = successors
self.predecessors = predecessors
self.incoming_nodes = incoming_nodes
... | QuixBugs/QuixBugs/correct_python_programs/node.py |
quixbugs-python_data_71 |
import string
def to_base(num, b):
result = ''
alphabet = string.digits + string.ascii_uppercase
while num > 0:
i = num % b
num = num // b
result = alphabet[i] + result
return result
"""
import string
def to_base(num, b):
result = ''
alphabet = string.digits + string.as... | QuixBugs/QuixBugs/correct_python_programs/to_base.py |
quixbugs-python_data_72 |
def next_permutation(perm):
for i in range(len(perm) - 2, -1, -1):
if perm[i] < perm[i + 1]:
for j in range(len(perm) - 1, i, -1):
if perm[i] < perm[j]:
next_perm = list(perm)
next_perm[i], next_perm[j] = perm[j], perm[i]
... | QuixBugs/QuixBugs/correct_python_programs/next_permutation.py |
quixbugs-python_data_73 |
def quicksort(arr):
if not arr:
return []
pivot = arr[0]
lesser = quicksort([x for x in arr[1:] if x < pivot])
greater = quicksort([x for x in arr[1:] if x >= pivot])
return lesser + [pivot] + greater
"""
def quicksort(arr):
if not arr:
return []
pivot = arr[0]
lesser... | QuixBugs/QuixBugs/correct_python_programs/quicksort.py |
quixbugs-python_data_74 |
from collections import deque as Queue
def breadth_first_search(startnode, goalnode):
queue = Queue()
queue.append(startnode)
nodesseen = set()
nodesseen.add(startnode)
while queue:
node = queue.popleft()
if node is goalnode:
return True
else:
que... | QuixBugs/QuixBugs/correct_python_programs/breadth_first_search.py |
quixbugs-python_data_75 |
def possible_change(coins, total):
if total == 0:
return 1
if total < 0 or not coins:
return 0
first, *rest = coins
return possible_change(coins, total - first) + possible_change(rest, total)
"""
def possible_change(coins, total):
if total == 0:
return 1
if not coins o... | QuixBugs/QuixBugs/correct_python_programs/possible_change.py |
quixbugs-python_data_76 |
def kheapsort(arr, k):
import heapq
heap = arr[:k]
heapq.heapify(heap)
for x in arr[k:]:
yield heapq.heappushpop(heap, x)
while heap:
yield heapq.heappop(heap)
| QuixBugs/QuixBugs/correct_python_programs/kheapsort.py |
quixbugs-python_data_77 |
def rpn_eval(tokens):
def op(symbol, a, b):
return {
'+': lambda a, b: a + b,
'-': lambda a, b: a - b,
'*': lambda a, b: a * b,
'/': lambda a, b: a / b
}[symbol](a, b)
stack = []
for token in tokens:
if isinstance(token, float):
... | QuixBugs/QuixBugs/correct_python_programs/rpn_eval.py |
quixbugs-python_data_78 | from .minimum_spanning_tree import minimum_spanning_tree
"""
Driver to test minimum spanning tree
"""
def main():
# Case 1: Simple tree input.
# Output: (1, 2) (3, 4) (1, 4)
result = minimum_spanning_tree({
(1, 2): 10,
(2, 3): 15,
(3, 4): 10,
(1, 4): 10})
for edge in re... | QuixBugs/QuixBugs/correct_python_programs/minimum_spanning_tree_test.py |
quixbugs-python_data_79 |
def find_in_sorted(arr, x):
def binsearch(start, end):
if start == end:
return -1
mid = start + (end - start) // 2
if x < arr[mid]:
return binsearch(start, mid)
elif x > arr[mid]:
return binsearch(mid + 1, end)
else:
return mid... | QuixBugs/QuixBugs/correct_python_programs/find_in_sorted.py |
quixbugs-python_data_80 |
def depth_first_search(startnode, goalnode):
nodesvisited = set()
def search_from(node):
if node in nodesvisited:
return False
elif node is goalnode:
return True
else:
nodesvisited.add(node)
return any(
search_from(nextnod... | QuixBugs/QuixBugs/correct_python_programs/depth_first_search.py |
quixbugs-python_data_81 |
def bucketsort(arr, k):
counts = [0] * k
for x in arr:
counts[x] += 1
sorted_arr = []
for i, count in enumerate(counts):
sorted_arr.extend([i] * count)
return sorted_arr
"""
def bucketsort(arr, k):
counts = [0] * k
for x in arr:
counts[x] += 1
sorted_arr = []... | QuixBugs/QuixBugs/correct_python_programs/bucketsort.py |
quixbugs-python_data_82 |
def flatten(arr):
for x in arr:
if isinstance(x, list):
for y in flatten(x):
yield y
else:
yield x
| QuixBugs/QuixBugs/correct_python_programs/flatten.py |
quixbugs-python_data_83 |
def mergesort(arr):
def merge(left, right):
result = []
i = 0
j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j +... | QuixBugs/QuixBugs/correct_python_programs/mergesort.py |
quixbugs-python_data_84 |
def bitcount(n):
count = 0
while n:
n &= n - 1
count += 1
return count
| QuixBugs/QuixBugs/correct_python_programs/bitcount.py |
quixbugs-python_data_85 |
def shortest_paths(source, weight_by_edge):
weight_by_node = {
v: float('inf') for u, v in weight_by_edge
}
weight_by_node[source] = 0
for i in range(len(weight_by_node) - 1):
for (u, v), weight in weight_by_edge.items():
weight_by_node[v] = min(
weight_by_n... | QuixBugs/QuixBugs/correct_python_programs/shortest_paths.py |
quixbugs-python_data_86 |
def longest_common_subsequence(a, b):
if not a or not b:
return ''
elif a[0] == b[0]:
return a[0] + longest_common_subsequence(a[1:], b[1:])
else:
return max(
longest_common_subsequence(a, b[1:]),
longest_common_subsequence(a[1:], b),
key=len
... | QuixBugs/QuixBugs/correct_python_programs/longest_common_subsequence.py |
quixbugs-python_data_87 | from .shortest_path_lengths import shortest_path_lengths
"""
Test shortest path lengths
"""
def main():
# Case 1: Basic graph input.
# Output:
graph = {
(0, 2): 3,
(0, 5): 5,
(2, 1): -2,
(2, 3): 7,
(2, 4): 4,
(3, 4): -5,
(4, 5): -1
}
result =... | QuixBugs/QuixBugs/correct_python_programs/shortest_path_lengths_test.py |
quixbugs-python_data_88 |
def shunting_yard(tokens):
precedence = {
'+': 1,
'-': 1,
'*': 2,
'/': 2
}
rpntokens = []
opstack = []
for token in tokens:
if isinstance(token, int):
rpntokens.append(token)
else:
while opstack and precedence[token] <= preced... | QuixBugs/QuixBugs/correct_python_programs/shunting_yard.py |
quixbugs-python_data_89 | def detect_cycle(node):
hare = tortoise = node
while True:
if hare is None or hare.successor is None:
return False
tortoise = tortoise.successor
hare = hare.successor.successor
if hare is tortoise:
return True
"""
def detect_cycle(node):
hare = to... | QuixBugs/QuixBugs/correct_python_programs/detect_cycle.py |
quixbugs-python_data_90 | from .node import Node
from .topological_ordering import topological_ordering
"""
Driver to test topological ordering
"""
def main():
# Case 1: Wikipedia graph
# Output: 5 7 3 11 8 10 2 9
five = Node(5)
seven = Node(7)
three = Node(3)
eleven = Node(11)
eight = Node(8)
two = Node(2... | QuixBugs/QuixBugs/correct_python_programs/topological_ordering_test.py |
quixbugs-python_data_91 |
def find_first_in_sorted(arr, x):
lo = 0
hi = len(arr)
while lo < hi:
mid = (lo + hi) // 2
if x == arr[mid] and (mid == 0 or x != arr[mid - 1]):
return mid
elif x <= arr[mid]:
hi = mid
else:
lo = mid + 1
return -1
"""
def find_fi... | QuixBugs/QuixBugs/correct_python_programs/find_first_in_sorted.py |
quixbugs-python_data_92 |
def sqrt(x, epsilon):
approx = x / 2
while abs(x - approx ** 2) > epsilon:
approx = 0.5 * (approx + x / approx)
return approx
"""
def sqrt(x, epsilon):
approx = x / 2
while abs(x - approx * approx) > epsilon:
approx = 0.5 * (approx + x / approx)
return approx
"""
| QuixBugs/QuixBugs/correct_python_programs/sqrt.py |
quixbugs-python_data_93 |
from collections import defaultdict
def shortest_path_lengths(n, length_by_edge):
length_by_path = defaultdict(lambda: float('inf'))
length_by_path.update({(i, i): 0 for i in range(n)})
length_by_path.update(length_by_edge)
for k in range(n):
for i in range(n):
for j in range(n):
... | QuixBugs/QuixBugs/correct_python_programs/shortest_path_lengths.py |
quixbugs-python_data_94 |
def lcs_length(s, t):
from collections import Counter
dp = Counter()
for i in range(len(s)):
for j in range(len(t)):
if s[i] == t[j]:
dp[i, j] = dp[i - 1, j - 1] + 1
return max(dp.values()) if dp else 0
| QuixBugs/QuixBugs/correct_python_programs/lcs_length.py |
quixbugs-python_data_95 |
def hanoi(height, start=1, end=3):
steps = []
if height > 0:
helper = ({1, 2, 3} - {start} - {end}).pop()
steps.extend(hanoi(height - 1, start, helper))
steps.append((start, end))
steps.extend(hanoi(height - 1, helper, end))
return steps
| QuixBugs/QuixBugs/correct_python_programs/hanoi.py |
quixbugs-python_data_96 | from .shortest_paths import shortest_paths
"""
Test shortest paths
"""
def main():
# Case 1: Graph with multiple paths
# Output: {'A': 0, 'C': 3, 'B': 1, 'E': 5, 'D': 10, 'F': 4}
graph = {
('A', 'B'): 3,
('A', 'C'): 3,
('A', 'F'): 5,
('C', 'B'): -2,
('C', 'D'): 7,
... | QuixBugs/QuixBugs/correct_python_programs/shortest_paths_test.py |
quixbugs-python_data_97 |
def max_sublist_sum(arr):
max_ending_here = 0
max_so_far = 0
for x in arr:
max_ending_here = max(0, max_ending_here + x)
max_so_far = max(max_so_far, max_ending_here)
return max_so_far
"""
def max_sublist_sum(arr):
max_ending_here = 0
max_so_far = 0
for x in arr:
... | QuixBugs/QuixBugs/correct_python_programs/max_sublist_sum.py |
quixbugs-python_data_98 | from heapq import *
def shortest_path_length(length_by_edge, startnode, goalnode):
unvisited_nodes = [] # FibHeap containing (node, distance) pairs
heappush(unvisited_nodes, (0, startnode))
visited_nodes = set()
while len(unvisited_nodes) > 0:
distance, node = heappop(unvisited_nodes)
... | QuixBugs/QuixBugs/correct_python_programs/shortest_path_length.py |
quixbugs-python_data_99 |
def sieve(max):
primes = []
for n in range(2, max + 1):
if all(n % p > 0 for p in primes):
primes.append(n)
return primes
"""
def sieve(max):
primes = []
for n in range(2, max + 1):
if not any(n % p == 0 for p in primes):
primes.append(n)
return primes
... | QuixBugs/QuixBugs/correct_python_programs/sieve.py |
quixbugs-python_data_100 |
from .node import Node
from .shortest_path_length import shortest_path_length
"""
Test shortest path length
"""
def main():
node1 = Node("1")
node5 = Node("5")
node4 = Node("4", None, [node5])
node3 = Node("3", None, [node4])
node2 = Node("2", None, [node1, node3, node4])
node0 = Node("0", N... | QuixBugs/QuixBugs/correct_python_programs/shortest_path_length_test.py |
README.md exists but content is empty.
- Downloads last month
- 5