id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
178,738
for i in range(cities-1): u, v, w = map(int, input().split()) graph[v].append((u, w)) graph[u].append((v, w)) def dijkstra(graph, start, end): shortest_distance = {} non_visited_nodes = {} for i in graph: non_visited_nodes[i] = graph[i] infinit = float('inf') for no in non_visited_nodes: shortest_distance[no] = infinit shortest_distance[start] = 0 while non_visited_nodes != {}: shortest_extracted_node = None for i in non_visited_nodes: if shortest_extracted_node is None: shortest_extracted_node = i elif shortest_distance[i] < shortest_distance[shortest_extracted_node]: shortest_extracted_node = i for no_v, Weight in graph[shortest_extracted_node]: if Weight + shortest_distance[shortest_extracted_node] < shortest_distance[no_v]: shortest_distance[no_v] = Weight + shortest_distance[shortest_extracted_node] non_visited_nodes.pop(shortest_extracted_node) return shortest_distance
null
178,739
def rec_fib(n): if n == 1: return 1 elif n == 0: return 0 else: return rec_fib(n-1)+rec_fib(n-2)
null
178,740
def binary_rec_fib(n): if n == 2 or n == 1: return 1 elif n == 0: return 0 else: # This recursive step takes advantage of the following two properties of the fibonacci numbers: # Fibo(2n) = Fibo(n+1)^2 + Fibo(n)^2 # Fibo(2n+1) = Fibo(n+1)^2 - Fibo(n-1)^2 sgn = n % 2 return binary_rec_fib((n-sgn)/2 + 1)**2 - ((-1)**sgn) * binary_rec_fib((n+sgn)/2 - 1)**2
null
178,741
def sieve(n): prime_list = [] for i in range(2, n+1): if i not in prime_list: print(i) for j in range(i*i, n+1, i): prime_list.append(j)
null
178,742
from greatest_common_divisor import gcd def gcd(x, y): def gcd(x, y): def gcd(x, y): def lcm(x, y): return abs(x * y) // gcd(x, y)
null
178,743
def power(x, y, p) : res = 1 # Initialize result # Update x if it is more # than or equal to p x = x % p while (y > 0) : # If y is odd, multiply # x with result if ((y & 1) == 1) : res = (res * x) % p # y must be even now y = y >> 1 # y = y/2 x = (x * x) % p return res
null
178,744
def factorial(number): answer = 1 if number == 0: return 1 else: for num in range(1, number+1): answer = answer * num return answer
null
178,745
def convert(n, from_base, to_base): """ This algorithm convert numbers between any base to any base like: convert("10",2,10) ~> "2" This function recive 3 parameters n -> the number from_base -> base of n | to_base -> base of the result | you can pass the bases as number like base 2 or as string like "binary" Why the n and the return is an string? Because bases greater the 10 use leathers to represents the numbers """ n = str(n) from_base = verify_base(from_base) to_base = verify_base(to_base) # Corner case 0 if(n == "0"): return n if(n[0] == '-'): n = n[1:] negative = True else: negative = False # We convert to decimal because is the easy way to convert to all multi = 1 decimal_number = 0 if(from_base == 10): decimal_number = int(n) else: for i in range(len(n) - 1, -1, -1): decimal_number += (multi * decimal_value(n[i])) multi *= from_base if(to_base == 10): decimal_number = str(decimal_number) if(negative): decimal_number = '-' + decimal_number return decimal_number result = "" while(decimal_number > 0): value = decimal_number % to_base result = to_special_caracter(value) + result decimal_number = int((decimal_number - value)/to_base) if(negative): result = '-' + result return result def test_convert(): print(convert("1111000111", 2, 8) == "1707") print(convert("1111000111", 2, 10) == "967") print(convert("1111000111", 2, 16) == "3c7") print(convert("1234567", 8, 2) == "1010011100101110111") print(convert("1234567", 8, 10) == "342391") print(convert("1234567", 8, 16) == "53977") print(convert("987123", 10, 2) == "11110000111111110011") print(convert("987123", 10, 8) == "3607763") print(convert("987123", 10, 16) == "f0ff3") print(convert("abcdef", 16, 2) == "101010111100110111101111") print(convert("abcdef", 16, 8) == "52746757") print(convert("abcdef", 16, 10) == "11259375") print(convert("179", 10, 16) == "b3") print(convert("b3", 16, 10) == "179") # Negative Tests print("Negative Tests") print(convert("-179", 10, 16) == "-b3") print(convert("-b3", 16, 10) == "-179") print(convert("-1111000111", 2, 10) == "-967")
null
178,746
def prime(limit): count = 1 while (count < limit): flag = 0 for i in range(3, count, 2): if (count % i == 0): flag = 1 if (flag == 0): print(count) count += 2
null
178,747
def factorial(number): if number == 0 or number == 1: return 1 answer = number * factorial(number - 1) return answer
null
178,748
def pow_of_two(n): return(n and (not(n&(n-1))))
null
178,749
The provided code snippet includes necessary dependencies for implementing the `is_perfect_square` function. Write a Python function `def is_perfect_square(num)` to solve the following problem: Given a positive integer num, write a function which returns True if num is a perfect square else False. Note: Do not use any built-in library function such as `sqrt`. :type num: int :rtype: bool Here is the function: def is_perfect_square(num): """ Given a positive integer num, write a function which returns True if num is a perfect square else False. Note: Do not use any built-in library function such as `sqrt`. :type num: int :rtype: bool """ i = 0 while i * i < num: i += 1 if i * i == num: return True else: return False
Given a positive integer num, write a function which returns True if num is a perfect square else False. Note: Do not use any built-in library function such as `sqrt`. :type num: int :rtype: bool
178,750
def sum_of_digits(n): n = int(input()) # here n is the number if n % 9 != 0: print(n % 9) else: print("9")
null
178,751
def remove(s): stack = [] for element in s: if stack and element == stack[-1]: stack.pop() else: stack.append(element)
null
178,752
def max_area_histogram(histogram): stack = list() max_area = 0 # Initialize max area index = 0 while index < len(histogram): if (not stack) or (histogram[stack[-1]] <= histogram[index]): stack.append(index) index += 1 else: top_of_stack = stack.pop() area = (histogram[top_of_stack] * ((index - stack[-1] - 1) if stack else index)) max_area = max(max_area, area) while stack: top_of_stack = stack.pop() area = (histogram[top_of_stack] * ((index - stack[-1] - 1) if stack else index)) max_area = max(max_area, area) return max_area
null
178,753
stack = [] def checkBalanced(expr): for i in expr: if i == "{" or i == "[" or i == "(": stack.append(i) elif i == "}" or i == "]" or i == ")": if not stack: return False top = stack.pop() if i == "}" and top != "{": return False elif i == "]" and top != "[": return False elif i == ")" and top != "(": return False else: print("Invalid Expression") return False if not len(stack): return True else: return False
null
178,754
def check(s): stack = [] for element in s: if element == '(': stack.append(')') elif element == '[': stack.append(']') elif element == '{': stack.append('}') elif not stack or stack.pop() != element: return False return not stack
null
178,755
def verify(pushed, popped): i = 0 stack = [] for x in pushed: stack.append(x) while stack and i < len(popped) and stack[-1] == popped[i]: stack.pop() i += 1 return i == len(popped)
null
178,756
def LSB(n): return n & -n
null
178,757
def flood_fill_util(screen, x, y, prev_color, new_color): def flood_fill(screen, x, y, new_color): prev_color = screen[x][y] # Finding the previous color on x and y flood_fill_util(screen, x, y, prev_color, new_color)
null
178,758
def search(mat, n, x): i = 0 j = n - 1 while i < n and j >=0: if mat[i][j] == x: print("Found at - ", i, j) return 1 if mat[i][j] > x: j -= 1 else: i += 1 print("Element not found") return 0
null
178,759
def delete(head, val): if head == None: return "List is empty" curr = head prev = None while curr.val != val: if curr.next == head: return "Val not in list" prev = curr curr = curr.next if curr.next == head: head = None return "Deleted" if curr == head: prev = head while prev.next != head: prev = prev.next head = curr.next prev.next = head elif curr.next == head: prev.next = head else: prev.next = curr.next return "Deleted"
null
178,760
class Node(): def __init__(self, val): def push(head, val): if not head: head = Node(val) head.next = head return curr = head while curr: if curr.next == head: break curr = curr.next curr.next = Node(val) curr.next.next = head
null
178,761
def print_list(head): if not head: return curr = head while curr: print(curr.val, end=" ") curr = curr.next if curr == head: break
null
178,762
def check(head): if not head: return True curr = head while curr: if curr.next == head: return True elif curr.next == None: return False curr = curr.next
null
178,763
def gcd(a, b): def rotate(arr, d): n = len(arr) g = gcd(n, d) for i in range(g): temp = arr[i] j = i while 1: k = j + d if k >= n: k -= n if k == i: break arr[j] = arr[k] j = k arr[j] = temp
null
178,764
def peak(arr, low, high): n = len(arr) while low <= high: mid = low + (high - low) / 2 mid = int(mid) if (mid == 0 or arr[mid-1] <= arr[mid]) and (mid == n-1 or arr[mid+1] <= arr[mid]): return(arr[mid]) elif mid > 0 and arr[mid-1] > arr[mid]: high = mid - 1 else: low = mid + 1
null
178,765
def intersection(arr1, arr2): res = [] i, j = 0, 0 while i < len(arr1) and j < len(arr2): if arr1[i] < arr2[j]: i += 1 elif arr2[j] < arr1[i]: j += 1 else: res.append(arr1[i]) i += 1 j += 1 return res
null
178,766
import sys def check(arr): min = sys.maxsize for i in arr: if i < min: min = i for i in arr: if not i % min == 0: return False return True
null
178,767
def product(arr): prods = [1] * len(arr) temp = 1 for i in range(len(arr)): prods[i] = temp temp = temp * prods[i] temp = 1 for i in reversed(range(len(arr))): prods[i] = prods[i] * temp temp = temp * arr[i] return temp
null
178,768
def partition(arr): s = sum(arr) if not s % 3 == 0: return False s = s / 3 targets = [2*s, s] acc = 0 for a in arr: acc += a if acc == targets[-1]: targets.pop() if not targets: return True return False
null
178,769
def binary_search(arr, start, end, val): while start <= end: mid = (start + end)//2 if val == arr[mid]: return mid elif val > arr[mid]: start = mid + 1 else: end = mid - 1 return -1 def search(arr, val): if len(arr) == 1: if arr[0] == val: return "Found" else: return "Not found" temp = arr[0] low = 0 high = 1 while temp < val: low = 0 high = 2 * high temp = arr[high] ans = binary_search(arr, low, high, val) if ans == -1: return "Not Found" else: return "Found at index {}".format(ans)
null
178,770
def rearrange(arr): i = -1 for j in range(len(arr)): if arr[j] < 0: i += 1 # maintaining index of the last negative number arr[j], arr[i] = arr[i], arr[j] pos = i + 1 # index of first positive number neg = 0 # index of first negative number while pos < len(arr) and neg < pos and arr[neg] < 0: arr[pos], arr[neg] = arr[neg], arr[pos] pos += 1 neg += 2 print(arr)
null
178,771
The provided code snippet includes necessary dependencies for implementing the `find_odd_number` function. Write a Python function `def find_odd_number(nums)` to solve the following problem: Find one number in array which is not duplicated, or exsits odd times. Here is the function: def find_odd_number(nums): """ Find one number in array which is not duplicated, or exsits odd times. """ s = 0 for n in nums: s ^= n return s
Find one number in array which is not duplicated, or exsits odd times.
178,772
def square(arr): n = len(arr) j = 0 # Counting the number of negative elements while j < n and arr[j] < 0: j += 1 i = j - 1 # index of last negative element ans = [] while 0 <= i and j < n: if arr[i] ** 2 < arr[j] ** 2: ans.append(arr[i] ** 2) i -= 1 else: ans.append(arr[j] ** 2) j += 1 while i >= 0: ans.append(arr[i] ** 2) i -= 1 while j < n: ans.append(arr[j] ** 2) j += 1 return ans
null
178,773
def dutch(arr): low = 0 mid = 0 high = len(arr) - 1 while mid <= high: if arr[mid] == 0: arr[low], arr[mid] = arr[mid], arr[low] low += 1 mid += 1 elif arr[mid] == 1: mid += 1 else: arr[mid], arr[high] = arr[high], arr[mid] high -= 1
null
178,774
def rearrange(arr): for i in range(1, len(arr)): if i % 2 == 0: if arr[i] > arr[i-1]: arr[i-1], arr[i] = arr[i], arr[i-1] else: if arr[i] < arr[i-1]: arr[i-1], arr[i] = arr[i], arr[i-1] print(arr)
null
178,775
import sys def largest(arr): l = -sys.maxsize for i in arr: if i > l: l = i print(l)
null
178,776
def find_sum(arr, s): curr_sum = arr[0] start = 0 n = len(arr) - 1 i = 1 while i <= n: while curr_sum > s and start < i: curr_sum = curr_sum - arr[start] start += 1 if curr_sum == s: return "Found between {} and {}".format(start, i - 1) curr_sum = curr_sum + arr[i] i += 1 return "Sum not found"
null
178,777
def min_swaps(arr, k): # First find out how many elements are there which are less than or # equal to k count = 0 for i in arr: if i <= k: count += 1 # This count defines a window - inside this window all our elements should # be placed # Find the count of bad elements - elements which are more than k and that will be # our starting answer as we will have to swap them out bad = 0 for i in range(0, count): if arr[i] > k: bad += 1 ans = bad j = count for i in range(0, len(arr)): if j == len(arr): break if arr[i] > k: bad -= 1 # because we have moved the bad element out of the window if arr[j] > k: bad += 1 ans = min(bad, ans) j += 1 print('answer - ', ans)
null
178,778
def find(arr): if len(arr) == 1: return arr[0] count_negative = 0 count_zero = 0 max_neg = float('-inf') min_pos = float('inf') prod = 1 for num in arr: if num == 0: count_zero += 1 continue if num < 0: count_negative += 1 max_neg = max(max_neg, num) if num > 0: min_pos = min(min_pos, num) prod *= num if count_zero == len(arr) or (count_negative == 0 and count_zero > 0): return 0 if count_negative == 0: return min_pos if count_negative & 1 == 0 and count_negative != 0: prod = int(prod / max_neg) return prod
null
178,779
def common(arr1, arr2, arr3): res = [] i, j, k = 0, 0, 0 while i < len(arr1) and j < len(arr2) and k < len(arr3): if arr1[i] == arr2[j] and arr2[j] == arr3[k]: res.append(arr1[i]) i += 1 j += 1 k += 1 elif arr1[i] < arr2[j]: i += 1 elif arr2[j] < arr3[k]: j += 1 else: k += 1 return res
null
178,780
import sys def product(arr): min1 = sys.maxsize min2 = sys.maxsize max1 = -sys.maxsize max2 = -sys.maxsize max3 = -sys.maxsize for n in arr: if n <= min1: min2 = min1 min1 = n elif n <= min2: min2 = n if n >= max1: max3 = max2 max2 = max1 max1 = n elif n >= max2: max3 = max2 max2 = n elif n >= max3: max3 = n return max(min1*min2*max1, max1*max2*max3)
null
178,781
def majority(arr): maj_index = 0 count = 1 for i in range(1, len(arr)): if arr[i] == arr[maj_index]: count += 1 else: count -= 1 if count == 0: maj_index = i count = 1 return arr[maj_index]
null
178,782
def find_equi(arr): total_sum = sum(arr) left_sum = 0 for i, num in enumerate(arr): total_sum -= num if left_sum == total_sum: return i left_sum += num return -1
null
178,783
def duplicate(arr): res = [] for x in arr: if arr[abs(x) - 1] < 0: res.append(abs(x)) else: arr[abs(x) - 1] *= -1 return res
null
178,784
def rotate(arr, d): return arr[d:]+arr[:d]
null
178,785
def duplicate(arr): tortoise = arr[0] hare = arr[0] while True: tortoise = arr[tortoise] hare = arr[arr[hare]] if tortoise == hare: break ptr1 = arr[0] ptr2 = tortoise while ptr1 != ptr2: ptr1 = arr[ptr1] ptr2 = arr[ptr2] return ptr1
null
178,786
for p in permutation(data): print(p) def permutation(lst): if len(lst) == 0: return [] if len(lst) == 1: return [lst] l = [] for i in range(len(lst)): m = lst[i] rem_lst = lst[:i] + lst[i+1:] for p in permutation(rem_lst): l.append([m] + p) return l
null
178,787
def place(arr): for i in range(len(arr)): if arr[i] >= 0 and arr[i] != i: arr[arr[i]], arr[i] = arr[i], arr[arr[i]] else: i += 1
null
178,788
def pivot(arr): s = sum(arr) left_sum = 0 for i, x in enumerate(arr): if left_sum == (s - x - left_sum): return i left_sum += x return -1
null
178,789
def max_sum(arr): max_so_far = arr[0] curr_max = arr[0] for i in range(1, len(arr)): curr_max = max(arr[i], curr_max + arr[i]) max_so_far = max(max_so_far, curr_max) return max_so_far
null
178,790
import sys def max_sum(arr): first = second = third = -sys.maxsize for i in arr: if i > first: third = second second = first first = i elif i > second: third = second second = i elif i > third: third = i return first + second + third
null
178,791
m = random_matrix(9) The provided code snippet includes necessary dependencies for implementing the `random_matrix` function. Write a Python function `def random_matrix(n)` to solve the following problem: Generate random n x n matrix without repeated entries in rows or columns. The entries are integers between 1 and n. Here is the function: def random_matrix(n): """ Generate random n x n matrix without repeated entries in rows or columns. The entries are integers between 1 and n. """ from random import shuffle a = list(range(n + 1)) shuffle(a) # Use slicing to left rotate m = [a[i:] + a[:i] for i in range(n + 1)] # Shuffle rows in matrix shuffle(m) # Shuffle cols in matrix (optional) m = list(map(list, zip(*m))) # Transpose the matrix shuffle(m) return m
Generate random n x n matrix without repeated entries in rows or columns. The entries are integers between 1 and n.
178,792
def first_recurrence(s): checker = 0 pos = 0 for i in s: val = ord(i) - ord('a') if (checker & (1 << val) > 0): return i checker = checker | (1 << val) pos += 1 return -1
null
178,793
import sys def get_searchable_numbers(arr, n): left_max = [None] * n right_min = [None] * n left_max[0] = float('-inf') right_min[n-1] = float('inf') for i in range(1, n): left_max[i] = max(left_max[i-1], arr[i-1]) for i in range(len(arr) - 2, -1, -1): right_min[i] = min(right_min[i+1], arr[i+1]) res = [] count = 0 for i in range(0, n): num = arr[i] left = left_max[i] right = right_min[i] if left < num < right: res.append(num) count += 1 return count, res
null
178,794
def find(arr, target): i = 0 j = len(arr) - 1 while i < j: if arr[i] + arr[j] == target: return [i+1, j+1] elif arr[i] + arr[j] > target: j -= 1 else: i += 1 return []
null
178,795
def union(arr1, arr2): res = [] i, j = 0, 0 while i < len(arr1) and j < len(arr2): if arr1[i] < arr2[j]: res.append(arr1[i]) i += 1 elif arr1[i] > arr2[j]: res.append(arr2[j]) j += 1 else: res.append(arr1[i]) res.append(arr2[j]) i += 1 j += 1 while i < len(arr1): res.append(arr1[i]) i += 1 while j < len(arr2): res.append(arr2[j]) j += 1 return res
null
178,796
def find_common(arr1, arr2, arr3): i, j, k = 0, 0, 0 while i < len(arr1) and j < len(arr2) and k < len(arr3): if arr1[i] == arr2[j] == arr3[k]: print(arr1[i]) i += 1 j += 1 k += 1 elif arr1[i] < arr2[j]: i += 1 elif arr2[j] < arr3[k]: j += 1 else: k += 1
null
178,797
def max_ones(arr): max = 0 count = 0 for i in arr: if i == 1: count += 1 if count > max: max = count if i == 0: count = 0 return max
null
178,798
def max_product(arr): n = len(arr) if n == 0: return 0 if n == 1: return arr[0] a = arr[0] b = arr[1] maxprod = a * b for i in range(n): for j in range(i + 1, n): if (arr[i] * arr[j]) > maxprod: a = arr[i] b = arr[j] maxprod = a * b return maxprod
null
178,799
def sort_parity(arr): i = 0 j = len(arr) - 1 while i < j: if arr[i] % 2 > arr[j] % 2: arr[i], arr[j] = arr[j], arr[i] if arr[i] % 2 == 0: i += 1 if arr[j] % 2 == 1: j -= 1
null
178,800
def quicksort(array): if len(array) < 2: return array else: pivot = array[0] less = [i for i in array[1:] if i <= pivot] greater = [i for i in array[1:] if i > pivot] return quicksort(less) + [pivot] + quicksort(greater)
null
178,801
def count(arr): start = 0 end = len(arr) - 1 while start <= end: mid = (start + end) // 2 if arr[mid] == 1 and (arr[mid + 1] == 0 or mid == high): return mid + 1 if arr[mid] == 1: start = mid + 1 else: end = mid - 1 return 0
null
178,802
import sys def three_largest(arr): first = second = third = -sys.maxsize for i in arr: if i > first: third = second second = first first = i elif i > second: third = second second = i elif i > third: third = i print(first, second, third)
null
178,803
def find_hash(arr, sum): for i in range(0, len(arr) - 1): s = set() current_sum = sum - arr[i] for j in range(i+1, len(arr)): if (current_sum - arr[j]) in s: return "Values are {}, {}, {}".format(arr[i], arr[j], current_sum-arr[j]) s.add(arr[j]) return "Not found"
null
178,804
def move(arr): count = 0 for a in arr: if not a == 0: arr[count] = a count += 1 while count < len(nums): arr[count] = 0 count += 1
null
178,805
def find(arr): n = len(arr) index = 0 for i in range(n): index = abs(arr[i]) - 1 arr[index] = -(abs(arr[index])) return [i+1 for i in range(len(arr)) if arr[i] > 0]
null
178,806
def print_vertical_util(root, col, d): if not root: return if col in d: d[col].append(root.val) else: d[col] = [root.val] print_vertical_util(root.left, col-1, d) print_vertical_util(root.right, col+1, d) print("Iterative solution - ") def print_vertical(root): d = {} col = 0 print_vertical_util(root, col, d) for k, v in sorted(d.items()): for i in v: print(i, end=' ') print()
null
178,807
print("Iterative solution - ") def print_vertical_iterative(root): queue = [] col = 0 d = {} queue.append(root) root.col = col while queue: root = queue.pop(0) col = root.col if col not in d: d[col] = [root.val] else: d[col].append(root.val) if root.left: queue.append(root.left) root.left.col = col - 1 if root.right: queue.append(root.right) root.right.col = col + 1 for k, v in sorted(d.items()): for i in v: print(i, end=' ') print()
null
178,808
def right_view_util(root, max_level, level): if not root: return if max_level[0] < level: print(root.val) max_level[0] = level right_view_util(root.right, max_level, level+1) right_view_util(root.left, max_level, level+1) def right_view(root): max_level = [0] right_view_util(root, max_level, 1)
null
178,809
def evaluate(root): if root is None: return 0 # Check for leaf node if root.left is None and root.right is None: return int(root.data) # Evaluate left tree left_sum = evaluate(root.left) # Evaluate right tree right_sum = evaluate(root.right) # Check which operator to apply if root.data == '+': return left_sum + right_sum elif root.data == '-': return left_sum - right_sum elif root.data == '*': return left_sum * right_sum else: return left_sum / right_sum
null
178,810
def no_siblings(root): if root is None: return if root.left is not None and root.right is not None: no_siblings(root.left) no_siblings(root.right) elif root.right is not None: print(root.right.val) no_siblings(root.right) elif root.left is not None: print(root.left.val) no_siblings(root.left)
null
178,811
def height(root, ans): if not root: return 0 lheight = height(root.left, ans) rheight = height(root.right, ans) ans[0] = max(ans[0], 1 + lheight + rheight) # This is for diameter return 1 + max(lheight, rheight) # This is for height def diameter(root): if not root: return 0 ans = [-9999999999] h = height(root, ans) return ans[0]
null
178,812
def find_depth(root): d = 0 while root: d += 1 root = root.left return d def check_perfect(root, d, level=0): if not root: return True # If leaf node, then its depth must be same as that of other nodes if root.left is None and root.right is None: return d == (level + 1) # An internal node with only one child if root.left is None or root.right is None: return False return check_perfect(root.left, d, level+1) and check_perfect(root.right, d, level+1) def is_perfect(root): d = find_depth(root) return check_perfect(root, d)
null
178,813
def diagonal_print_util(root, d, diagonal_map): if root is None: return try: diagonal_map[d].append(root.val) except: diagonal_map[d] = [root.val] # Increase vertical distance if left child diagonal_print_util(root.left, d+1, diagonal_map) # Vertical distance remains same for the right child diagonal_print_util(root.right, d, diagonal_map) def diagonal_print(root): diagonal_map = dict() diagonal_print_util(root, 0, diagonal_map) for i in diagonal_map: for j in diagonal_map[i]: print(j, end=" ") print('')
null
178,814
def check(root): if not root: return True if not root.left and not root.right: return True if root.left and root.right: return check(root.left) and check(root.right)
null
178,815
def length(root, ans): def longest_path(root): ans = [0] length(root, ans) return ans[0]
null
178,816
def top_view(root): if not root: return queue = [] col = 0 d = {} queue.append(root) root.col = col while queue: root = queue.pop(0) col = root.col if col not in d: d[col] = root.val if root.left: queue.append(root.left) root.left.col = col - 1 if root.right: queue.append(root.right) root.right.col = col + 1 for i in sorted(d): print(d[i], end=" ")
null
178,817
def print_leaves(root): if root: print_leaves(root.left) if not root.left and not root.right: print(root.val, end=' ') print_leaves(root.right) def print_left_boundary(root): if root: if root.left: print(root.val, end=' ') print_left_boundary(root.left) elif root.right: print(root.val, end=' ') print_left_boundary(root.right) def print_right_boundary(root): """ The traversal here will be from top to bottom because this will be called after finishing the left side which is top-to-bottom traversal """ if root: if root.right: print_right_boundary(root.right) print(root.val, end=' ') elif root.left: print_right_boundary(root.left) print(root.val, end=' ') def print_boundary(root): if root: print(root.val) print_left_boundary(root.left) print_leaves(root.left) print_leaves(root.right) print_right_boundary(root.right)
null
178,818
def sum_prop(root): l = r = 0 if not root or (not root.left and not root.right): return True else: if root.left: l = root.left.val if root.right: r = root.right.val if (root.val == l + r) and sum_prop(root.left) and sum_prop(root.right): return True else: return False
null
178,819
import math def sum_nodes(l): leaf_nodes = math.pow(2, l-1) s = (leaf_nodes + (leaf_nodes + 1)) / 2 res = s * l return int(res)
null
178,820
def level(root, node, lev): if not root: return 0 if root == node: return lev l = level(root.left, node, lev+1) if not l == 0: return l l = level(root.right, node, lev+1) def is_sibling(root, a, b): if not root: return False return (root.left == a and root.right == b) or \ (root.right == b and root.left == a) or \ is_sibling(root.left, a, b) or \ is_sibling(root.right, a, b) def is_cousin(root, a, b): if level(root, a, 1) == level(root, b, 1) and not is_sibling(root, a, b): return True else: return False
null
178,821
def print_full(root): if not root: return if root.left and root.right: print(root.val, end=' ') print_full(root.left) print_full(root.right)
null
178,822
def convert(root): if root is None: return convert(root.left) convert(root.right) if root.left == None: root.left = root.right else: root.left.right = root.right root.right = None
null
178,823
def left_view_util(root, max_level, level): if not root: return if max_level[0] < level: print(root.val) max_level[0] = level left_view_util(root.left, max_level, level+1) left_view_util(root.right, max_level, level+1) def left_view(root): max_level = [0] left_view_util(root, max_level, 1)
null
178,824
def find_depth(node): def is_perfect_util(root, d, level=0): def is_perfect(root): depth = find_depth(root) return is_perfect_util(root, depth)
null
178,825
arr = inorder(root) def inorder(root): if not root: return None arr = [] stack = [] while True: if root: stack.append(root) root = root.left else: if not stack: break root = stack.pop() arr.append(root.val) root = root.right return arr
null
178,826
def replace_nodes(root, arr): if not root: return stack = [] i = 1 while True: if root: stack.append(root) root = root.left else: if not stack: break root = stack.pop() root.val = arr[i-1] + arr[i+1] i += 1 root = root.right return root
null
178,827
def sum_nodes(root): if root is None: return 0 return root.val + sum_nodes(root.left) + sum_nodes(root.right)
null
178,828
def height(root): if not root: return 0 lheight = height(root.left) rheight = height(root.right) return 1 + max(lheight, rheight) def print_level(root, level, left_to_right): if not root: return if level == 1: print(root.val, end=' ') elif level > 1: if left_to_right: print_level(root.left, level-1, left_to_right) print_level(root.right, level-1, left_to_right) else: print_level(root.right, level-1, left_to_right) print_level(root.left, level-1, left_to_right) def print_spiral(root): h = height(root) left_to_right = False for i in range(1, h+1): print_level(root, i, left_to_right) left_to_right = not left_to_right
null
178,829
def sum_util(root, ans): if root is None: return 0 s = root.val + sum_util(root.left, ans) + sum_util(root.right, ans) ans[0] = max(ans[0], s) return s def find_sum(root): if root is None: return 0 ans = [-99999999] sum_util(root, ans) return ans[0]
null
178,830
def height(root): if not root: return 0 else: lheight = height(root.left) rheight = height(root.right) return 1 + max(lheight, rheight)
null
178,831
class Node: def __init__(self, val): self.val = val self.left = None self.right = None def create_tree(arr): curr_ptr = 0 child_ptr = 0 root = Node(arr[0]) curr_node = root while i < (len(arr) - 1)/2: curr_ptr = arr[i] child_ptr = i + 1 left_child = arr[child_ptr] right_child = arr[child_ptr + 1] curr_node.left = Node(left_child) curr_node.right = Node(right_child)
null
178,832
def identical(root1, root2): if root1 is None and root2 is None: return True if root1 is not None and root2 is not None: return root1.val == root2.val and identical(root1.left, root2.left) and identical(root1.right, root2.right) return False
null
178,833
def foldable(left, right): if left is None and right is None: return True if left is None or right is None: return False return left.val == right.val and foldable(left.left, right.right) and foldable(left.right, right.left)
null
178,834
def has_path(root, stack, x): if not root: return False stack.append(root.val) if root.val == x: return True if has_path(root.left, stack, x) or has_path(root.right, stack, x): return True stack.pop() return False def print_path(root, x): arr = [] if has_path(root, arr, x): for i in arr: print(i, end=' ') else: print('Path not present')
null
178,835
def count(root): if not root: return 0 return count(root.left) + count(root.right) + 1 def check_util(root, n): if root == None: return False # Check for root if count(root) == n - count(root): return True # Check for all the other nodes return check_util(root.left, n) or check_util(root.right, n) def check(root): n = count(root) return check_util(root, n)
null
178,836
def print_k(root, k): if root is None: return if k == 0: print(root.val) else: print_k(root.left, k-1) print_k(root.right, k-1)
null
178,837
def print_odd(root, is_odd=True): if not root: return if is_odd: print(root.val, end=' ') print_odd(root, not is_odd) print_odd(root, not is_odd)
null