text stringlengths 37 1.41M |
|---|
import random
def get_non_prize_door(host, num_doors, player_choice):
i = 1
while (i == host or i == player_choice):
i = (i + 1) % (num_doors)
return i
def switch_function(shown_door, num_doors, player_choice):
i = 1
while (i == shown_door or i == player_choice):
i = (i + 1) % (num_doors)
return i
def monty_hall_game(switch, num_tests):
win_switch_cnt = 0
win_no_switch_cnt = 0
lose_switch_cnt = 0
lose_no_switch_cnt = 0
doors = [0, 1, 2] # Get the doors
num_doors = len(doors) # Get the number of doors
for i in range(0, num_tests):
door_with_prize = random.randint(0, num_doors - 1)
print('\nRandom Test Case ',i+1,":")
host = door_with_prize
player_choice = random.randint(0, num_doors - 1)
print('The Player Chose Door:', player_choice, '')
original_player_choice = player_choice
shown_door = get_non_prize_door(host, num_doors, player_choice)
if switch == True:
player_choice = switch_function(shown_door, num_doors, player_choice)
if player_choice == host and switch == False:
# Then the player wins from not switching
print('Player Wins (No switch) - The player chose door: ', player_choice, ' Original choice: ',
original_player_choice, ', Door with prize:', door_with_prize, ', Shown Door: ', shown_door,'\n\n')
win_no_switch_cnt = win_no_switch_cnt + 1
elif player_choice == host and switch == True:
# Then the player wins from switching
print('Player Wins (switch) - The player chose door: ', player_choice, ' Original choice: ',
original_player_choice, ', Door with prize:', door_with_prize, ', Shown Door: ', shown_door)
win_switch_cnt = win_switch_cnt + 1
elif player_choice != host and switch == False:
# The player lost from not switching
print('Player Lost (No switch) - The player chose door: ', player_choice, ' Original choice: ',
original_player_choice, ', Door with prize:', door_with_prize, ', Shown Door: ', shown_door)
lose_no_switch_cnt = lose_no_switch_cnt + 1
elif player_choice != host and switch == True:
# The player lost from switching
print('Player Lost (switch) - The player chose door: ', player_choice, ' Original choice: ',
original_player_choice, ', Door with prize:', door_with_prize, ', Shown Door: ', shown_door)
lose_switch_cnt = lose_switch_cnt + 1
else:
print('SOMETHING IS WRONG')
return win_no_switch_cnt, win_switch_cnt, lose_no_switch_cnt, lose_switch_cnt, num_tests
x = monty_hall_game(True, 10)
print('\n\nWin switch %: ', x[1]/ x[4])
print('Lose switch %: ', x[3]/ x[4])
print('Win No switch %: ', x[0]/ x[4])
print('Lose No switch %: ', x[2]/ x[4]) |
class Car():
def __init__(self, name, model, year):
self.name = name
self.model = model
self.year = year
class Battery ():
def __init__(self, battery_size = 90):
self.battery_size = battery_size
def upgrade_battery(self):
if self.battery_size != 85:
self.battery_size = 85
print('Battery upgraded to', self.battery_size)
else:
return
self.battery_size
class ECar(Car):
def __init__(self, name, model, year):
super().__init__(name, model, year)
self.battery = Battery()
def desc_car(self):
print(self.name.title(),self.model.title(),self.year)
def get_range(self):
if self.battery.battery_size == 70:
print('The range is 300.')
elif self.battery.battery_size == 85:
print('The range is 450.')
else:
print('We don\'nt have data for your battery type.')
MyEcar = ECar('tesla','model 3','2018')
MyEcar.desc_car()
MyEcar.get_range()
MyEcar.battery.upgrade_battery()
MyEcar.get_range()
|
# http://www.cs.bilkent.edu.tr/~atat/473/lecture05.pdf
# bu linkteki syf 5 ve 21 deki pseudo'lar kullanılmıştır
def lomuto(arr, p, r):
pivot = arr[r]
i = p-1
j = p
while j < r:
if arr[j] <= pivot:
i = i+1
arr[i],arr[j] = arr[j],arr[i]
j = j+1
arr[i+1],arr[r] = arr[r],arr[i+1]
return i+1
def hoare(arr, p, r):
pivot = arr[p]
i = p - 1 # Initialize left index
j = r + 1 # Initialize right index
while True:
# Find a value in right side smaller
while True:
j = j - 1
if arr[j] <= pivot:
break
# Find a value in left side greater
while True:
i = i + 1
if arr[i] >= pivot:
break
if i < j :
arr[i], arr[j] = arr[j], arr[i]
else:
return j
def sortHoare(arr, p, r):
if (p < r ) :
q = hoare(arr, p, r)
sortHoare(arr, p, q);
sortHoare(arr, q + 1, r);
def sortLomuto(arr, p, r):
if (p < r ) :
q = lomuto(arr, p, r)
sortLomuto(arr, p, q-1);
sortLomuto(arr, q + 1, r);
def quickSortHoare(arr):
temp = arr[:]
sortHoare(temp, 0, (len(temp) - 1))
return temp
def quickSortLomuto(arr):
temp = arr[:]
sortLomuto(temp, 0, len(temp)-1)
return temp
arr = [15,4,68,24,75,16,42]
qsh = quickSortHoare(arr)
print(qsh)
qsl = quickSortLomuto(arr)
print(qsl)
|
#!/usr/bin/env python
fst = lambda ab: ab[0]
snd = lambda ab: ab[1]
head = lambda xs: xs[0]
tail = lambda xs: xs[1:]
def is_inter(a, b):
""" Integer -> Integer -> Bool"""
return a == b - 1 or a == b
def list_sort(data):
""" :: set -> [Integer],
where the result is sorted
"""
return sorted(list(data))
def interm(ab, n):
""" :: (Integer, Integer) -> Integer -> (Integer, Integer) """
if is_inter(snd(ab), n):
return fst(ab), n
else:
return n, n
def acc_reduce(xs, ab):
""" [Integer] -> (Integer, Integer) -> [(Integer, Integer)]"""
if xs == []:
return [ab]
else:
x = head(xs)
base = interm(ab, x)
if base == (x, x):
return [ab] + acc_reduce(tail(xs), base)
else:
return acc_reduce(tail(xs), base)
def create_intervals(the_set):
if len(the_set) == 0:
return []
xs = list_sort(the_set)
return tail(acc_reduce(xs, (head(xs), head(xs))))
def test_create_intervals():
data = {1, 2, 3, 4, 5, 7, 8, 12}
ls_data = [1, 2, 3, 4, 5, 7, 8, 12]
data2 = {1, 2, 3, 6, 7, 8, 4, 5}
assert is_inter(2, 3) == True
assert is_inter(3, 3) == True
assert is_inter(3, 2) == False
assert is_inter(3, 5) == False
assert interm((1,1), 2) == (1,2)
assert interm((1,2), 4) == (4,4)
assert list_sort(data) == ls_data
assert create_intervals(data) == [(1, 5), (7, 8), (12, 12)]
assert create_intervals(data2) == [(1, 8)]
assert create_intervals({}) == []
assert create_intervals({1}) == [(1, 1)]
assert create_intervals({1, 1}) == [(1, 1)]
assert create_intervals({1, 2, 3}) == [(1, 3)]
assert create_intervals([]) == []
if __name__ == '__main__':
test_create_intervals()
|
# DNA Matching Algorithm
def char2base4(S):
""" Convert gene sequence to base 4 string
"""
c2b = {}
c2b['A'] = '0'
c2b['C'] = '1'
c2b['G'] = '2'
c2b['T'] = '3'
L = ''
for s in S:
L += c2b[s]
return L
def hash10(S, base):
"""Convert list S to base-10 number where
base specifies the base of S
"""
f = 0
for s in S[:-1]:
f = base*(int(s)+f)
f += int(S[-1])
return f
def pairSearch(L,pairs):
"""Find locations within adjacent strings (contained in input list,L)
that match k-mer pairs found in input list pairs. Each element of pairs
is a 2-element tuple containing k-mer strings
"""
# Convert L to base 4 (Note that the input is being modified)
n = len(L)
for i in range(n):
L[i] = char2base4(L[i])
# Convert each pairs to base 4
pairs4 = []
n = len(pairs)
for i in range(n):
pairs4.append((char2base4(pairs[i][0]), char2base4(pairs[i][1])))
# Create a dictionary, with keys as hashes of the first of the pairs,
# and values as lists of tuples, with the second of the pairs with its index in pairs
pairs_hash_dict = {}
for index, pair in enumerate(pairs4):
# Calculate hash of the base 4 k-mers in pairs
hashed0 = hash10(pair[0], 4)
hashed1 = hash10(pair[1], 4)
if hashed0 in pairs_hash_dict:
if hashed1 in pairs_hash_dict[hashed0]:
pairs_hash_dict[hashed0][hashed1].append(index)
else:
pairs_hash_dict[hashed0].update({hashed1: [index]})
else:
pairs_hash_dict[hashed0] = {hashed1: [index]}
# Initialize
k = len(pairs[0][0])
N = len(L[0]) # Assumes all l in L are of length N
locations = []
first_digit = [int(l[0]) for l in L]
# Compute first k-mer hash for all sequences
hashes = [hash10(l[:k], 4) for l in L]
# Main loop across base 4 strings in l for loop below
for j in range(k-1, N):
# Loop across l in L
match = False
for i, l in enumerate(L):
# Separate case for first step
if j != k-1:
# Complete the rolling hash calculation
hashes[i] = 4 * (hashes[i] - first_digit[i]*4**(k-1)) + int(l[j])
# Store first base 4 digit to subtract at next iteration
first_digit[i] = int(l[j-k+1])
# If previous sequence matched with first of a pair
if match:
# Check for a match in this sequence
if hashes[i] in pairs_hash_dict[match]:
index_list = pairs_hash_dict[match][hashes[i]]
# Below loop accounts for EXACT duplicates in pairs
for index in index_list:
locations.append([j-k+1, i-1, index])
# Check if k-mer exists in first of pairs in pairs
if hashes[i] in pairs_hash_dict:
# Check pair2 in next sequence
match = hashes[i]
else:
match = False
return locations
if __name__ == "__main__":
pass
|
# -*- coding: utf-8 -*-
"""Contain game-calc logic."""
from random import randrange, choice
from operator import add, mul, sub
DESCRIPTION = "What is the result of the expression?"
OPERATORS = [('+', add),
('-', sub),
('*', mul)]
def logic():
"""Define logic for brain-calc game, return question, answer"""
_operator, function = choice(OPERATORS)
number_left = randrange(100)
number_right = randrange(100)
question = f'{number_left} {_operator} {number_right}'
answer = function(number_left, number_right)
return question, str(answer)
|
#!/usr/bin/python
import sys
def generate_parentheses(n):
if n is None:
return n
if n is 1:
return ['()']
prev = generate_parentheses(n - 1)
return _add_new_parenthesis(prev)
def _add_new_parenthesis(prev):
curr1 = ['()' + x for x in prev]
curr2 = ['(' + x + ')' for x in prev]
return curr1 + curr2
if __name__ == '__main__':
lis = generate_parentheses(int(sys.argv[1]))
for p in lis:
print p
|
# ------------------------------
# 687. Longest Univalue Path
#
# Description:
# Given a binary tree, find the length of the longest path where each node in the path has the same value.
# This path may or may not pass through the root.
#
# Note: The length of path between two nodes is represented by the number of edges between them.
#
# Example 1:
# Input:
# 5
# / \
# 4 5
# / \ \
# 1 1 5
# Output:
# 2
#
# Input:
# 1
# / \
# 4 5
# / \ \
# 4 4 5
# Output:
# 2
#
# Version: 1.0
# 12/06/17 by Jianfa
# ------------------------------
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def longestUnivaluePath(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.res = 0
def length_path(node):
if not node:
return 0
left_length = length_path(node.left)
right_length = length_path(node.right)
left_temp = right_temp = 0
if node.left and node.val == node.left.val:
left_temp = left_length + 1
if node.right and node.val == node.right.val:
right_temp = right_length + 1
self.res = max(self.res, left_temp + right_temp)
return max(left_temp, right_temp)
length_path(root)
return self.res
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Recursive solution.
# Key point is the returning result is different from length of path with current node as root.
# Returning result is the max length of left path and right path;
# Length of path with current node as root is the sum of left and right path. |
# ------------------------------
# 206. Reverse Linked List
#
# Description:
# Reverse a singly linked list.
#
# Example:
# Input: 1->2->3->4->5->NULL
# Output: 5->4->3->2->1->NULL
#
# Follow up:
# A linked list can be reversed either iteratively or recursively. Could you implement both?
#
# Version: 3.0
# 11/10/19 by Jianfa
# ------------------------------
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
cur = head
last = None
while cur is not None:
temp = cur.next
cur.next = last
last = cur
cur = temp
return last
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Iterative solution: reverse from begining.
#
# O(N) time O(1) space |
# ------------------------------
# 105. Construct Binary Tree from Preorder and Inorder Traversal
#
# Description:
# Given preorder and inorder traversal of a tree, construct the binary tree.
# Note:
# You may assume that duplicates do not exist in the tree.
#
# For example, given
# preorder = [3,9,20,15,7]
# inorder = [9,3,15,20,7]
#
# Return the following binary tree:
# 3
# / \
# 9 20
# / \
# 15 7
#
# Version: 1.0
# 08/11/18 by Jianfa
# ------------------------------
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
if not preorder:
return None
root = TreeNode(preorder[0])
rootidx = inorder.index(preorder[0])
left_pre = preorder[1:1+rootidx]
left_in = inorder[:rootidx]
right_pre = preorder[rootidx+1:]
right_in = inorder[rootidx+1:]
root.left = self.buildTree(left_pre, left_in)
root.right = self.buildTree(right_pre, right_in)
return root
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# DFS recursive solution. Two order lists have different usage:
# 1. preorder: the first item is root node
# 2. inorder: find the root index, then the left side of root is left child tree of root,
# the right side of root is right child tree.
#
# Recursively build tree. |
# ------------------------------
# 77. Combinations
#
# Description:
# Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
#
# For example,
# If n = 4 and k = 2, a solution is:
# [
# [2,4],
# [3,4],
# [2,3],
# [1,2],
# [1,3],
# [1,4],
# ]
#
# Version: 1.0
# 01/20/18 by Jianfa
# ------------------------------
class Solution(object):
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
if n < k:
return []
res = []
currlist = []
self.backtrack(n, k, currlist, 1, res)
return res
def backtrack(self, n, k, currlist, start, res):
if len(currlist) == k:
temp = [x for x in currlist]
res.append(temp)
elif n - start + 1 + len(currlist) < k:
return
else:
for i in range(start, n+1):
currlist.append(i)
self.backtrack(n, k, currlist, i+1, res)
currlist.pop()
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Backtrack solution.
# The tough point is you must clearly understand what every step is in the backtrack process.
# I didn't think quite clear at first, but finally I realized that there is a stack in the
# backtrack function. Check "else" part in backtrack(), there will be an append() before
# recursive backtrack, and a pop() after the recursive backtrack. |
# ------------------------------
# 539. Minimum Time Difference
#
# Description:
# Given a list of 24-hour clock time points in "Hour:Minutes" format, find the minimum minutes
# difference between any two time points in the list.
#
# Example 1:
# Input: ["23:59","00:00"]
# Output: 1
#
# Note:
# The number of time points in the given list is at least 2 and won't exceed 20000.
# The input time is legal and ranges from 00:00 to 23:59.
#
# Version: 1.0
# 01/18/20 by Jianfa
# ------------------------------
class Solution:
def findMinDifference(self, timePoints: List[str]) -> int:
times = [False] * 24 * 60
for point in timePoints:
hour = int(point.split(":")[0])
minute = int(point.split(":")[1])
if times[hour * 60 + minute]:
# duplicate time point appears
return 0
times[hour * 60 + minute] = True
small = 1440 # smallest time point in times list
large = 0 # largest time point in times list
prev = 0 # last time point
diff = 1440
for i in range(1440):
if times[i]:
if small != 1440:
# current i is not the first time point
diff = min(diff, i - prev)
small = min(small, i)
large = max(large, i) # update largest time point
prev = i
print(small, large)
diff = min(diff, 1440 - large + small)
return diff
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Get idea from: https://leetcode.com/problems/minimum-time-difference/discuss/100640/Verbose-Java-Solution-Bucket |
# ------------------------------
# 47. Permutations II
#
# Description:
# Given a collection of numbers that might contain duplicates, return all possible unique permutations.
#
# For example,
# [1,1,2] have the following unique permutations:
# [
# [1,1,2],
# [1,2,1],
# [2,1,1]
# ]
#
# Version: 1.0
# 11/03/17 by Jianfa
# ------------------------------
class Solution(object):
def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
res = self.backtrack(nums)
return res
def backtrack(self, nums):
if not nums:
return [nums]
res = []
curr = [x for x in nums]
for idx, i in enumerate(curr):
if idx > 0 and i == curr[idx - 1]:
continue
temp = []
rest = [curr[j] for j in range(len(curr)) if j != idx]
temp = self.backtrack(rest)
for item in temp:
item.insert(0, i)
res += temp
return res
if __name__ == "__main__":
test = Solution()
nums = [1,1,2]
print(test.permute(nums))
# ------------------------------
# Summary:
# Similar to 46.py, also using backtrack. The difference is when traverse the number in line 36, need to skip
# the same item. So I sort the nums at first and just pick the first item to backtrack if it has duplicates. |
# ------------------------------
# 135. Candy
#
# Description:
# There are N children standing in a line. Each child is assigned a rating value.
# You are giving candies to these children subjected to the following requirements:
# Each child must have at least one candy.
# Children with a higher rating get more candies than their neighbors.
# What is the minimum candies you must give?
#
# Example 1:
# Input: [1,0,2]
# Output: 5
# Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
#
# Example 2:
# Input: [1,2,2]
# Output: 4
# Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
# The third child gets 1 candy because it satisfies the above two conditions.
#
# Version: 1.0
# 10/09/18 by Jianfa
# ------------------------------
class Solution:
def candy(self, ratings):
"""
:type ratings: List[int]
:rtype: int
"""
if not ratings:
return 0
res = 0
left2right = [1 for _ in range(len(ratings))] # store the number of candies required by the current student taking care of his left neighbour
right2left = [1 for _ in range(len(ratings))] # store the number of candies required by the current student taking care of his right neighbour
for i in range(1, len(ratings)):
if ratings[i] > ratings[i-1]:
left2right[i] = left2right[i-1] + 1
for i in range(len(ratings) - 1)[::-1]:
if ratings[i] > ratings[i+1]:
right2left[i] = right2left[i+1] + 1
for i in range(len(ratings)):
res += max(left2right[i], right2left[i])
return res
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Follow idea from Solution section
# Use left2right and right2left array to store the number of candy when taking care of
# neighbour at one side
# Get the max value for each index of left2right and right2left as final result, then sum them |
# ------------------------------
# 459. Repeated Substring Pattern
#
# Description:
# Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.
# Example 1:
# Input: "abab"
# Output: True
# Explanation: It's the substring "ab" twice.
#
# Example 2:
# Input: "aba"
# Output: False
#
# Example 3:
# Input: "abcabcabcabc"
# Output: True
# Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)
#
# Version: 1.0
# 07/07/18 by Jianfa
# ------------------------------
class Solution(object):
def repeatedSubstringPattern(self, s):
"""
:type s: str
:rtype: bool
"""
return (s + s)[1:-1].find(s) != -1
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Let S1 = s + s, S2 = S1[1:-1] (without first and last char).
# If s in S2, then s has repeated substring pattern.
# https://leetcode.com/problems/repeated-substring-pattern/discuss/94334/Easy-python-solution-with-explaination |
# ------------------------------
# 150. Evaluate Reverse Polish Notation
#
# Description:
# Evaluate the value of an arithmetic expression in Reverse Polish Notation.
# Valid operators are +, -, *, /. Each operand may be an integer or another expression.
#
# Note:
# Division between two integers should truncate toward zero.
# The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation.
#
# Example 1:
# Input: ["2", "1", "+", "3", "*"]
# Output: 9
# Explanation: ((2 + 1) * 3) = 9
#
# Example 2:
# Input: ["4", "13", "5", "/", "+"]
# Output: 6
# Explanation: (4 + (13 / 5)) = 6
#
# Example 3:
# Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
# Output: 22
# Explanation:
# ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
# = ((10 * (6 / (12 * -11))) + 17) + 5
# = ((10 * (6 / -132)) + 17) + 5
# = ((10 * 0) + 17) + 5
# = (0 + 17) + 5
# = 17 + 5
# = 22
#
# Version: 1.0
# 08/25/18 by Jianfa
# ------------------------------
class Solution(object):
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
stack = []
for x in tokens:
if x not in ('+', '-', '*', '/'):
stack.append(int(x))
else:
n2 = stack.pop()
n1 = stack.pop()
if x == '+':
stack.append(n1 + n2)
elif x == '-':
stack.append(n1 - n2)
elif x == '*':
stack.append(n1 * n2)
else:
temp = n1 / n2
if temp < 0 and n1 % n2 != 0:
temp += 1
stack.append(temp)
return stack[0]
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Note "Division between two integers should truncate toward zero.", so 6 / -132 = 0 rather than -1 |
# ------------------------------
# 69. Sqrt(x)
#
# Description:
# Implement int sqrt(int x).
# Compute and return the square root of x.
# x is guaranteed to be a non-negative integer.
#
# Example 1:
#
# Input: 4
# Output: 2
#
# Example 2:
#
# Input: 8
# Output: 2
# Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated.
#
# Version: 1.0
# 01/17/18 by Jianfa
# ------------------------------
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
if x == 0 or x == 1:
return x
s = 1
while s * s < x:
s *= 2
if s * s == x:
return s
else:
for i in range(s/2, s):
if i * i < x:
i += 1
else:
break
if i * i == x:
return i
else:
return i - 1
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Initially I start from 1 to check power value of each number, but exceed limit time. So I make
# the number times 2 every time to decrease checking number.
# While this problem is best to use binary search.
# Let low = 0, high = x, mid = (low + high + 1) / 2
# if mid * mid <= x:
# low = mid
# else:
# high = mid - 1 |
# ------------------------------
# 526. Beautiful Arrangement
#
# Description:
# Suppose you have N integers from 1 to N. We define a beautiful arrangement as an array
# that is constructed by these N numbers successfully if one of the following is true for
# the ith position (1 <= i <= N) in this array:
#
# The number at the ith position is divisible by i.
# i is divisible by the number at the ith position.
#
# Now given N, how many beautiful arrangements can you construct?
#
# Example 1:
#
# Input: 2
# Output: 2
#
# Explanation:
# The first beautiful arrangement is [1, 2]:
# Number at the 1st position (i=1) is 1, and 1 is divisible by i (i=1).
# Number at the 2nd position (i=2) is 2, and 2 is divisible by i (i=2).
#
# The second beautiful arrangement is [2, 1]:
# Number at the 1st position (i=1) is 2, and 2 is divisible by i (i=1).
# Number at the 2nd position (i=2) is 1, and i (i=2) is divisible by 1.
#
# Note:
# N is a positive integer and will not exceed 15.
#
# Version: 1.0
# 01/17/20 by Jianfa
# ------------------------------
class Solution:
count = 0
def countArrangement(self, N: int) -> int:
visited = [False] * (N + 1)
def helper(N: int, pos: int) -> None:
if pos > N:
self.count += 1
return
for i in range(1, N+1):
if not visited[i] and (i % pos == 0 or pos % i == 0):
visited[i] = True
helper(N, pos + 1)
visited[i] = False
helper(N, 1)
return self.count
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Get idea from Solution: https://leetcode.com/problems/beautiful-arrangement/solution/
# and https://leetcode.com/problems/beautiful-arrangement/discuss/99707/Java-Solution-Backtracking
# Key idea is to generate all possible permutations.
#
# O(k) time complexity, k is the number of valid permutation
# O(n) space complexity |
# ------------------------------
# 623. Add One Row to Tree
#
# Description:
# Given the root of a binary tree, then value v and depth d, you need to add a row of nodes with value v at the given depth d. The root node is at depth 1.
# The adding rule is: given a positive integer depth d, for each NOT null tree nodes N in depth d-1, create two tree nodes with value v as N's left subtree root and right subtree root. And N's original left subtree should be the left subtree of the new left subtree root, its original right subtree should be the right subtree of the new right subtree root. If depth d is 1 that means there is no depth d-1 at all, then create a tree node with value v as the new root of the whole original tree, and the original tree is the new root's left subtree.
#
# Example 1:
# Input:
# A binary tree as following:
# 4
# / \
# 2 6
# / \ /
# 3 1 5
#
# v = 1
# d = 2
#
# Output:
# 4
# / \
# 1 1
# / \
# 2 6
# / \ /
# 3 1 5
# Example 2:
# Input:
# A binary tree as following:
# 4
# /
# 2
# / \
# 3 1
#
# v = 1
# d = 3
#
# Output:
# 4
# /
# 2
# / \
# 1 1
# / \
# 3 1
#
# Note:
# The given d is in range [1, maximum depth of the given tree + 1].
# The given binary tree has at least one tree node.
#
# Version: 1.0
# 12/22/18 by Jianfa
# ------------------------------
class Solution:
def addOneRow(self, root, v, d):
"""
:type root: TreeNode
:type v: int
:type d: int
:rtype: TreeNode
"""
if d == 1:
newroot = TreeNode(v)
newroot.left = root
return newroot
depth = 1 # Current depth of the tree
nodes = [root]
while nodes and depth < d - 1: # Loop to depth d - 1
temp = []
for i in range(len(nodes)):
node = nodes[i]
if node.left:
temp.append(node.left)
if node.right:
temp.append(node.right)
nodes = temp
depth += 1
for node in nodes:
# Insert left node
newLeftNode = TreeNode(v) # The new left node to insert
if node.left:
newLeftNode.left = node.left
node.left = newLeftNode
# Insert right node
newRightNode = TreeNode(v) # The new right node to insert
if node.right:
newRightNode.right = node.right
node.right = newRightNode
return root
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Traverse until the depth d - 1 to get all nodes at the row.
# Insert left and right node to each of the node at the row. |
# ------------------------------
# 25. Reverse Nodes in k-Group
#
# Description:
# Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
# k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
#
# You may not alter the values in the nodes, only nodes itself may be changed.
# Only constant memory is allowed.
# For example,
# Given this linked list: 1->2->3->4->5
# For k = 2, you should return: 2->1->4->3->5
# For k = 3, you should return: 3->2->1->4->5
#
# Version: 1.0
# 09/21/17 by Jianfa
# ------------------------------
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
pointer = {}
if not head:
return None
else:
i = 0
temp = head
while temp and i < k:
pointer[i] = temp
temp = temp.next
i += 1
if i < k:
return head
else:
while i > 1:
pointer[i-1].next = pointer[i-2]
i -= 1
pointer[0].next = self.reverseKGroup(temp, k)
return pointer[k-1]
# Used for test
# if __name__ == "__main__":
# test = Solution()
# d = ListNode(2)
# d.next = None
# c = ListNode(1)
# c.next = d
# b = ListNode(4)
# b.next = c
# a = ListNode(3)
# a.next = b
# head = test.reverseKGroup(a, 3)
# while head != None:
# print(head.val)
# head = head.next
# ------------------------------
# Summary:
# Still using recursion solution
# Some ideas from other solutions are processing every k nodes every time, until there are
# no k nodes in the list. |
# ------------------------------
# 87. Scramble String
#
# Description:
# Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings
# recursively.
# Below is one possible representation of s1 = "great":
# great
# / \
# gr eat
# / \ / \
# g r e at
# / \
# a t
# To scramble the string, we may choose any non-leaf node and swap its two children.
#
# For example, if we choose the node "gr" and swap its two children, it produces a scrambled string "rgeat".
# rgeat
# / \
# rg eat
# / \ / \
# r g e at
# / \
# a t
# We say that "rgeat" is a scrambled string of "great".
#
# Similarly, if we continue to swap the children of nodes "eat" and "at", it produces a scrambled string "rgtae".
# rgtae
# / \
# rg tae
# / \ / \
# r g ta e
# / \
# t a
# We say that "rgtae" is a scrambled string of "great".
#
# Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1.
#
# Version: 1.0
# 01/28/18 by Jianfa
# ------------------------------
import collections
class Solution(object):
def isScramble(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: bool
"""
if s1 == s2:
return True
char_dict = collections.defaultdict(int)
for c in s1:
char_dict[c] += 1
for c in s2:
char_dict[c] -= 1
for key in char_dict:
if char_dict[key] != 0:
return False
length = len(s1)
for i in range(1,length):
if self.isScramble(s1[0:i], s2[0:i]) and self.isScramble(s1[i:], s2[i:]):
return True
if self.isScramble(s1[0:i], s2[length-i:]) and self.isScramble(s1[i:], s2[0:length-i]):
return True
return False
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Follow the idea from: https://leetcode.com/problems/scramble-string/discuss/29392/. |
# ------------------------------
# 448. Find All Numbers Disappeared in an Array
#
# Description:
# Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
# Find all the elements of [1, n] inclusive that do not appear in this array.
# Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
# Example:
# Input:
# [4,3,2,7,8,2,3,1]
# Output:
# [5,6]
#
# Version: 1.0
# 07/06/18 by Jianfa
# ------------------------------
class Solution(object):
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
res = []
for i in nums:
if nums[abs(i) - 1] > 0:
nums[abs(i)- 1] *= -1
for j in range(len(nums)):
if nums[j] > 0:
res.append(j+1)
return res
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# It's very smart solution from https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/92956/Java-accepted-simple-solution |
# ------------------------------
# 128. Longest Consecutive Sequence
#
# Description:
# Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
# Your algorithm should run in O(n) complexity.
#
# Example:
# Input: [100, 4, 200, 1, 3, 2]
# Output: 4
# Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
#
# Version: 1.0
# 10/08/18 by Jianfa
# ------------------------------
from collections import defaultdict
class Solution:
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
sizeMap = defaultdict(int)
for n in nums:
if sizeMap[n] > 0: # Duplicate
continue
if sizeMap[n-1] > 0 and sizeMap[n+1] > 0: # If n can connect left and right subsequence
leftSize = sizeMap[n-1] # Get the size of longest consecutive sequence that has one end n-1
rightSize = sizeMap[n+1] # Get the size of longest consecutive sequence that has one end n+1
sizeMap[n-leftSize] = sizeMap[n+rightSize] = sizeMap[n] = leftSize + rightSize + 1 # Update two end's value to extend size
elif sizeMap[n-1] > 0: # If only left side of n can add n into subsequence
leftSize = sizeMap[n-1]
sizeMap[n-leftSize] = sizeMap[n] = leftSize + 1
elif sizeMap[n+1] > 0: # If only right side of n can add n into subsequence
rightSize = sizeMap[n+1]
sizeMap[n+rightSize] = sizeMap[n] = rightSize + 1
else: # If no subsequence can add n
sizeMap[n] = 1
print(sizeMap)
return max(sizeMap.values()) # Return the max size value
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# The key idea is use the map to record largest size
# We can only update value for two ends of a subsequence.
# e.g. for (1,2,3,4), we can update map[1] = map[4] = 4, map[2] and map[3] can be 1.
# because only if we meet 5 or 0, then we need to extend the size of this subsequence,
# otherwise, size of this subsequence will keep same. |
# ------------------------------
# 40. Combination Sum II
#
# Description:
# Given a collection of candidate numbers (candidates) and a target number (target), find
# all unique combinations in candidates where the candidate numbers sums to target.
#
# Each number in candidates may only be used once in the combination.
#
# Note:
#
# All numbers (including target) will be positive integers.
# The solution set must not contain duplicate combinations.
#
# Example 1:
# Input: candidates = [10,1,2,7,6,1,5], target = 8,
# A solution set is:
# [
# [1, 7],
# [1, 2, 5],
# [2, 6],
# [1, 1, 6]
# ]
#
# Example 2:
# Input: candidates = [2,5,2,1,2], target = 5,
# A solution set is:
# [
# [1,2,2],
# [5]
# ]
#
# Version: 2.0
# 11/15/19 by Jianfa
# ------------------------------
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
if not candidates:
return []
candidates.sort()
res = []
def backtrack(curr, index, target, start):
# start is the index of where starting to check in this round
if target == 0:
res.append(curr[:])
else:
while index < len(candidates) and candidates[index] <= target:
if index > start and candidates[index] == candidates[index-1]:
# skip this value to avoid duplicate check
index += 1
continue
curr.append(candidates[index])
backtrack(curr, index+1, target - candidates[index], index+1)
curr.pop()
index += 1
backtrack([], 0, target, 0)
return res
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Met similar problem in Microsoft onsite interview. Difference is duplicate may exist in
# this problem so have to avoid it.
#
# More concose solution than 40.py.
#
# O(2^n) time |
# ------------------------------
# 504. Base 7
#
# Description:
# Given an integer, return its base 7 string representation.
# Example 1:
# Input: 100
# Output: "202"
#
# Example 2:
# Input: -7
# Output: "-10"
# Note: The input will be in range of [-1e7, 1e7].
#
# Version: 1.0
# 07/12/18 by Jianfa
# ------------------------------
class Solution(object):
def convertToBase7(self, num):
"""
:type num: int
:rtype: str
"""
if num == 0:
return '0'
flag = 1 if num > 0 else -1
num = abs(num)
power = 0
while pow(7, power) <= num:
power += 1
res = ""
for i in range(power)[::-1]:
res += str(num / pow(7, i))
num = num % pow(7, i)
if flag == 1:
return res
else:
return "-" + res
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Note that condition for power is pow(7, i) <= num rather than pow(7, i) < num |
# ------------------------------
# 530. Minimum Absolute Difference in BST
#
# Description:
# Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.
# Example:
# Input:
# 1
# \
# 3
# /
# 2
# Output:
# 1
# Explanation:
# The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).
#
# Note: There are at least two nodes in this BST.
#
# Version: 1.0
# 07/14/18 by Jianfa
# ------------------------------
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def __init__(self):
self.minDiff = float('inf')
self.pre = None
def getMinimumDifference(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return self.minDiff
self.getMinimumDifference(root.left)
if self.pre != None:
self.minDiff = min(self.minDiff, root.val - self.pre)
self.pre = root.val
self.getMinimumDifference(root.right)
return self.minDiff
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Inorder travesal solution. Idea from https://leetcode.com/problems/minimum-absolute-difference-in-bst/discuss/99905/Two-Solutions-in-order-traversal-and-a-more-general-way-using-TreeSet |
# ------------------------------
# 117. Populating Next Right Pointers in Each Node II
#
# Description:
# Given a binary tree
# struct TreeLinkNode {
# TreeLinkNode *left;
# TreeLinkNode *right;
# TreeLinkNode *next;
# }
# Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
# Initially, all next pointers are set to NULL.
# Note:
# You may only use constant extra space.
# Recursive approach is fine, implicit stack space does not count as extra space for this problem.
#
# Example:
# Given the following binary tree,
# 1
# / \
# 2 3
# / \ \
# 4 5 7
#
# After calling your function, the tree should look like:
# 1 -> NULL
# / \
# 2 -> 3 -> NULL
# / \ \
# 4-> 5 -> 7 -> NULL
#
# Version: 1.0
# 08/14/18 by Jianfa
# ------------------------------
# Definition for binary tree with next pointer.
# class TreeLinkNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None
class Solution:
# @param root, a tree link node
# @return nothing
def connect(self, root):
while root:
prev = TreeLinkNode(0)
curr = prev
while root:
if root.left:
curr.next = root.left
curr = curr.next
if root.right:
curr.next = root.right
curr = curr.next
root = root.next
root = prev.next
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# |
# ------------------------------
# 500. Keyboard Row
#
# Description:
# Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below.
#
# Example 1:
# Input: ["Hello", "Alaska", "Dad", "Peace"]
# Output: ["Alaska", "Dad"]
# Note:
# You may use one character in the keyboard more than once.
# You may assume the input string will only contain letters of alphabet.
#
# Version: 1.0
# 07/10/18 by Jianfa
# ------------------------------
class Solution(object):
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
row1 = set('qwertyuiop')
row2 = set('asdfghjkl')
row3 = set('zxcvbnm')
res = []
for w in words:
if set(w.lower()).issubset(row1) or set(w.lower()).issubset(row2) or set(w.lower()).issubset(row3):
res.append(w)
return res
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# The smart point here is using set.issubset()
# Idea from https://leetcode.com/problems/keyboard-row/discuss/97913/Easy-understand-solution-in-7-lines-for-everyone |
# ------------------------------
# 284. Peeking Iterator
#
# Description:
#
# Version: 1.0
# 09/30/18 by Jianfa
# ------------------------------
# Below is the interface for Iterator, which is already defined for you.
#
# class Iterator:
# def __init__(self, nums):
# """
# Initializes an iterator object to the beginning of a list.
# :type nums: List[int]
# """
#
# def hasNext(self):
# """
# Returns true if the iteration has more elements.
# :rtype: bool
# """
#
# def next(self):
# """
# Returns the next element in the iteration.
# :rtype: int
# """
class PeekingIterator:
def __init__(self, iterator):
"""
Initialize your data structure here.
:type iterator: Iterator
"""
self.iterator = []
while iterator.hasNext():
self.iterator.append(iterator.next())
def peek(self):
"""
Returns the next element in the iteration without advancing the iterator.
:rtype: int
"""
if self.hasNext():
return self.iterator[0]
else:
return None
def next(self):
"""
:rtype: int
"""
if self.hasNext():
return self.iterator.pop(0)
else:
return None
def hasNext(self):
"""
:rtype: bool
"""
return True if len(self.iterator) > 0 else False
# Your PeekingIterator object will be instantiated and called as such:
# iter = PeekingIterator(Iterator(nums))
# while iter.hasNext():
# val = iter.peek() # Get the next element but not advance the iterator.
# iter.next() # Should return the same value as [val].
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Use a list to represent iterator. May cost much space.
# Think about using provided method. |
# ------------------------------
# 173. Binary Search Tree Iterator
#
# Description:
# Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
# Calling next() will return the next smallest number in the BST.
# Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
#
# Version: 1.0
# 08/26/18 by Jianfa
# ------------------------------
# Definition for a binary tree node
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class BSTIterator(object):
def __init__(self, root):
"""
:type root: TreeNode
"""
self.stack = []
self.pushAll(root)
def hasNext(self):
"""
:rtype: bool
"""
return True if self.stack else False
def next(self):
"""
:rtype: int
"""
node = self.stack.pop()
self.pushAll(node.right)
return node.val
def pushAll(self, node):
while node:
self.stack.append(node)
node = node.left
# Your BSTIterator will be called like this:
# i, v = BSTIterator(root), []
# while i.hasNext(): v.append(i.next())
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Get idea from https://leetcode.com/problems/binary-search-tree-iterator/discuss/52525/My-solutions-in-3-languages-with-Stack |
# ------------------------------
# 417. Pacific Atlantic Water Flow
#
# Description:
# Given an m x n matrix of non-negative integers representing the height of each unit cell in a
# continent, the "Pacific ocean" touches the left and top edges of the matrix and the "Atlantic
# ocean" touches the right and bottom edges.
#
# Water can only flow in four directions (up, down, left, or right) from a cell to another one
# with height equal or lower.
#
# Find the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean.
#
# Note:
# The order of returned grid coordinates does not matter.
# Both m and n are less than 150.
#
# Example:
# Given the following 5x5 matrix:
#
# Pacific ~ ~ ~ ~ ~
# ~ 1 2 2 3 (5) *
# ~ 3 2 3 (4) (4) *
# ~ 2 4 (5) 3 1 *
# ~ (6) (7) 1 4 5 *
# ~ (5) 1 1 2 4 *
# * * * * * Atlantic
#
# Return:
# [[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions with parentheses in above matrix).
#
# Version: 2.0
# 10/10/19 by Jianfa
# ------------------------------
class Solution:
def pacificAtlantic(self, matrix: List[List[int]]) -> List[List[int]]:
if not matrix or not matrix[0]:
return
res = []
n = len(matrix)
m = len(matrix[0])
pacific = [[False for _ in range(m)] for _ in range(n)]
atlantic = [[False for _ in range(m)] for _ in range(n)]
for i in range(n):
self.dfs(matrix, pacific, -sys.maxsize, i, 0)
self.dfs(matrix, atlantic, -sys.maxsize, i, m-1)
for j in range(m):
self.dfs(matrix, pacific, -sys.maxsize, 0, j)
self.dfs(matrix, atlantic, -sys.maxsize, n-1, j)
# Look for all coordinates that are visited
for i in range(n):
for j in range(m):
if pacific[i][j] and atlantic[i][j]:
res.append([i, j])
return res
def dfs(self, matrix, visited, height, x, y):
if x < 0 or x >= len(matrix) or y < 0 or y >= len(matrix[0]) or visited[x][y] or matrix[x][y] < height:
return
visited[x][y] = True
dir = [(0, 1), (1, 0), (0, -1), (-1, 0)]
for d in dir:
self.dfs(matrix, visited, matrix[x][y], x + d[0], y + d[1])
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Idea from: https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/90733/Java-BFS-and-DFS-from-Ocean
# DFS solution, but same idea as 417.py |
# ------------------------------
# 105. Construct Binary Tree from Preorder and Inorder Traversal
#
# Description:
# Given preorder and inorder traversal of a tree, construct the binary tree.
#
# Note:
# You may assume that duplicates do not exist in the tree.
#
# For example, given
#
# preorder = [3,9,20,15,7]
# inorder = [9,3,15,20,7]
# Return the following binary tree:
#
# 3
# / \
# 9 20
# / \
# 15 7
#
# Version: 2.0
# 11/11/19 by Jianfa
# ------------------------------
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
def helper(in_l, in_r):
nonlocal pre_idx
# in_l is left bound of inorder range, in_r is right bound of inorder range
if in_l == in_r:
return None
rootVal = preorder[pre_idx] # get current root value
root = TreeNode(rootVal) # build the root TreeNode
index = inorderDict[rootVal]
pre_idx += 1 # Follow the order of preorder is actually DFS
root.left = helper(in_l, index) # recursively get left and right subtree
root.right = helper(index+1, in_r)
return root
inorderDict = {val:i for i, val in enumerate(inorder)}
pre_idx = 0
return helper(0, len(inorder))
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Recursion solution from https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/solution/
# Compare to 105.py, the better point is using index to denote what is the inorder range
# of a tree, without sending a subarray as parameter.
#
# O(N) time O(N) space
#
# nonlocal: make a function inside a function, which uses the variable x (in the outer function)
# as a non local variable |
# ------------------------------
# 19. Remove Nth Node From End of List
#
# Description:
# Given a linked list, remove the nth node from the end of list and return its head.
#
# For example,
# Given linked list: 1->2->3->4->5, and n = 2.
#
# After removing the second node from the end, the linked list becomes 1->2->3->5.
#
# Note:
# Given n will always be valid.
# Try to do this in one pass.
#
# Version: 1.0
# 10/18/17 by Jianfa
# ------------------------------
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
count = 0
dict_Node = {}
while head:
dict_Node[count] = head
count += 1
head = head.next
target = count - n
if target - 1 in dict_Node and target + 1 in dict_Node:
dict_Node[target - 1].next = dict_Node[target + 1]
return dict_Node[0]
elif target - 1 not in dict_Node and target + 1 in dict_Node:
return dict_Node[target + 1]
elif target - 1 in dict_Node and target + 1 not in dict_Node:
dict_Node[target - 1].next = None
return dict_Node[0]
else:
return None
# Summary
# I use a dictionary to store every node during counting, and remove the target one.
# Need to think over some boundary condition, for example the first Node or the last Node.
#
# Get a good idea from the shortest-time solution:
# Use two pointer p1 and p2. Start from head, move p1 n steps. If p1 == None, then head is the target to be
# removed. If p1 is not None, then move p1 and p2 together until p1 reach None. Then p2.next is the target
# to be removed. This idea is very smart! |
# ------------------------------
# 244. Shortest Word Distance II
#
# Description:
# Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the shortest distance between these two words in the list. Your method will be called repeatedly many times with different parameters.
#
# Example:
# Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
#
# Input: word1 = “coding”, word2 = “practice”
# Output: 3
# Input: word1 = "makes", word2 = "coding"
# Output: 1
#
# Note:
# You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
#
# Version: 1.0
# 11/03/18 by Jianfa
# ------------------------------
import sys
class WordDistance:
def __init__(self, words):
"""
:type words: List[str]
"""
self.wordDict = {}
for i, w in enumerate(words):
if w in self.wordDict:
self.wordDict[w].append(i)
else:
self.wordDict[w] = [i]
def shortest(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
index1 = self.wordDict[word1]
index2 = self.wordDict[word2]
i = j = 0
minDist = sys.maxsize
while i < len(index1) and j < len(index2):
idx1 = index1[i]
idx2 = index2[j]
if idx1 < idx2:
minDist = min(minDist, idx2 - idx1)
i += 1
else:
minDist = min(minDist, idx1 - idx2)
j += 1
return minDist
# Your WordDistance object will be instantiated and called as such:
# obj = WordDistance(words)
# param_1 = obj.shortest(word1,word2)
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Use hash map to store indexs of every word in the list
# Use two pointer to check every index of word1, find the closest index in the word2 of it and compare the distance of them. |
# ------------------------------
# 212. Word Search II
#
# Description:
# Given a 2D board and a list of words from the dictionary, find all words in the board.
# Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
#
# Example:
# Input:
# words = ["oath","pea","eat","rain"] and board =
# [
# ['o','a','a','n'],
# ['e','t','a','e'],
# ['i','h','k','r'],
# ['i','f','l','v']
# ]
# Output: ["eat","oath"]
#
# Note:
# You may assume that all inputs are consist of lowercase letters a-z.
#
# Version: 1.0
# 11/14/18 by Jianfa
# ------------------------------
class Solution:
def findWords(self, board, words):
"""
:type board: List[List[str]]
:type words: List[str]
:rtype: List[str]
"""
if not board or not board[0] or not words:
return []
res = []
root = self.buildTrie(words)
for i in range(len(board)):
for j in range(len(board[0])):
self.dfs(i, j, board, root, res)
return res
def dfs(self, i, j, board, root, res):
c = board[i][j]
index = ord(c) - ord('a')
if c == '#' or not root.links[index]: # this unit is visited or it cannot be found in trie
return
root = root.links[index]
if root.word: # found a word
res.append(root.word)
root.word = "" # avoid duplicate
board[i][j] = '#' # indicate this unit is visited
# Do dfs in 4 directions
if i > 0:
self.dfs(i-1, j, board, root, res)
if j > 0:
self.dfs(i, j-1, board, root, res)
if i < len(board) - 1:
self.dfs(i+1, j, board, root, res)
if j < len(board[0]) - 1:
self.dfs(i, j+1, board, root, res)
board[i][j] = c # Set it back
def buildTrie(self, words):
root = TrieNode()
for w in words:
p = root
for c in w:
index = ord(c) - ord('a')
if not p.links[index]:
p.links[index] = TrieNode()
p = p.links[index]
p.word = w
return root
class TrieNode:
def __init__(self):
self.links = [None] * 26
self.word = ""
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Follow idea from https://leetcode.com/problems/word-search-ii/discuss/59780/Java-15ms-Easiest-Solution-(100.00)
# Main idea is to build a trie to record all words.
# Then start from every unit in the board, to find whether a specific word exists. |
# ------------------------------
# 721. Accounts Merge
#
# Description:
# Given a list accounts, each element accounts[i] is a list of strings, where the first
# element accounts[i][0] is a name, and the rest of the elements are emails representing
# emails of the account.
#
# Now, we would like to merge these accounts. Two accounts definitely belong to the same
# person if there is some email that is common to both accounts. Note that even if two
# accounts have the same name, they may belong to different people as people could have
# the same name. A person can have any number of accounts initially, but all of their
# accounts definitely have the same name.
#
# After merging the accounts, return the accounts in the following format: the first
# element of each account is the name, and the rest of the elements are emails in sorted
# order. The accounts themselves can be returned in any order.
#
# Example 1:
# Input:
# accounts = [["John", "johnsmith@mail.com", "john00@mail.com"], ["John", "johnnybravo@mail.com"],
# ["John", "johnsmith@mail.com", "john_newyork@mail.com"], ["Mary", "mary@mail.com"]]
# Output: [["John", 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com'],
# ["John", "johnnybravo@mail.com"], ["Mary", "mary@mail.com"]]
#
# Explanation:
# The first and third John's are the same person as they have the common email "johnsmith@mail.com".
# The second John and Mary are different people as none of their email addresses are used by other accounts.
# We could return these lists in any order, for example the answer [['Mary', 'mary@mail.com'], ['John', 'johnnybravo@mail.com'],
# ['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] would still be accepted.
#
# Note:
#
# The length of accounts will be in the range [1, 1000].
# The length of accounts[i] will be in the range [1, 10].
# The length of accounts[i][j] will be in the range [1, 30].
#
# Version: 1.0
# 11/04/19 by Jianfa
# ------------------------------
class DSU:
def __init__(self):
self.p = [i for i in range(10001)] # [0, 1, ..., 10000]
def find(self, x):
if self.p[x] != x:
self.p[x] = self.find(self.p[x])
return self.p[x]
def union(self, x, y):
self.p[self.find(x)] = self.find(y)
class Solution:
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
dsu = DSU()
owners = {} # dictionary {email: owner}
ids = {} # dictionary {email: id}
i = 0
for acc in accounts:
name = acc[0]
for email in acc[1:]:
owners[email] = name
if email not in ids:
# grant an id to email if it's not shown before
ids[email] = i
i += 1
dsu.union(ids[email], ids[acc[1]]) # union id of email and id of first email of this account
ans = collections.defaultdict(list)
for email in owners:
ans[dsu.find(ids[email])].append(email)
return [[owners[v[0]]] + sorted(v) for v in ans.values()]
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Union Find solution from https://leetcode.com/problems/accounts-merge/solution/
# https://leetcode.com/problems/accounts-merge/discuss/109157/JavaC%2B%2B-Union-Find is
# also a good explanation.
#
# O(A * logA) time where A = sum(a_i), a_i = len(accounts[i])
# O(A) space |
# ------------------------------
# 124. Binary Tree Maximum Path Sum
#
# Description:
# Given a non-empty binary tree, find the maximum path sum.
# For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
#
# Example 1:
# Input: [1,2,3]
# 1
# / \
# 2 3
# Output: 6
#
# Example 2:
# Input: [-10,9,20,null,null,15,7]
# -10
# / \
# 9 20
# / \
# 15 7
# Output: 42
#
# Version: 1.0
# 12/18/18 by Jianfa
# ------------------------------
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import sys
class Solution:
maxSum = 0
maxNode = -sys.maxsize # In case the largest path sum equal to some node, then return the largest node
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.helper(root)
return self.maxSum if self.maxSum != 0 else self.maxNode
def helper(self, root):
if not root:
return 0
left = self.helper(root.left)
right = self.helper(root.right)
self.maxNode = max(self.maxNode, root.val)
self.maxSum = max(self.maxSum, root.val + left + right)
maxSideSum = max(root.val + left, root.val + right) # Max sum of a single side starting from root node
return maxSideSum if maxSideSum > 0 else 0 # Return value will not be less than 0
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Similar idea from problem 543.
# 1. Calculate left and right max sum
# 2. Update maximum sum when path sum including current node is larger
# 3. Return largest path sum starting from current node |
# ------------------------------
# 729. My Calendar I
#
# Description:
# Implement a MyCalendar class to store your events. A new event can be added if adding
# the event will not cause a double booking.
#
# Your class will have the method, book(int start, int end). Formally, this represents a
# booking on the half open interval [start, end), the range of real numbers x such that
# start <= x < end.
#
# A double booking happens when two events have some non-empty intersection (ie., there
# is some time that is common to both events.)
#
# For each call to the method MyCalendar.book, return true if the event can be added to
# the calendar successfully without causing a double booking. Otherwise, return false and
# do not add the event to the calendar.
#
# Your class will be called like this: MyCalendar cal = new MyCalendar(); MyCalendar.book(start, end)
#
# Example 1:
# MyCalendar();
# MyCalendar.book(10, 20); // returns true
# MyCalendar.book(15, 25); // returns false
# MyCalendar.book(20, 30); // returns true
# Explanation:
# The first event can be booked. The second can't because time 15 is already booked by another event.
# The third event can be booked, as the first event takes every time less than 20, but not including 20.
#
# Note:
#
# The number of calls to MyCalendar.book per test case will be at most 1000.
# In calls to MyCalendar.book(start, end), start and end are integers in the range [0, 10^9].
#
# Version: 1.0
# 11/02/19 by Jianfa
# ------------------------------
import bisect
class MyCalendar:
def __init__(self):
self.starts = []
self.ends = []
def book(self, start: int, end: int) -> bool:
if not self.starts:
self.starts.append(start)
self.ends.append(end)
return True
else:
index = bisect.bisect(self.starts, start)
if index == 0:
# if start value is smaller than all previous starts
if end > self.starts[0]:
# there is overlap with the first range
return False
else:
self.starts.insert(0, start)
self.ends.insert(0, end)
return True
elif index == len(self.starts):
# if start value is greater than all previous starts
if start < self.ends[-1]:
# there is overlap with the last range
return False
else:
self.starts.append(start)
self.ends.append(end)
return True
else:
if start < self.ends[index-1] or end > self.starts[index]:
return False
else:
self.starts.insert(index, start)
self.ends.insert(index, end)
return True
# Your MyCalendar object will be instantiated and called as such:
# obj = MyCalendar()
# param_1 = obj.book(start,end)
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Binary search solution.
# Store the start and end of each range. When a new book check is coming, binary search
# the index for new range. If it's valid, update the start and end list, otherwise return
# false.
#
# O(n^2) time for insert, O(n) space |
# ------------------------------
# 61. Rotate List
#
# Description:
# Given a list, rotate the list to the right by k places, where k is non-negative.
# Example:
# Given 1->2->3->4->5->NULL and k = 2,
# return 4->5->1->2->3->NULL.
#
# Version: 1.0
# 01/15/18 by Jianfa
# ------------------------------
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not head or not head.next or k == 0:
return head
dict_node = {}
start = 0
while head:
dict_node[start] = head
start += 1
head = head.next
if k >= start:
k = k % start
if k == 0:
return dict_node[0]
dict_node[start-k-1].next = None
dict_node[start-1].next = dict_node[0]
return dict_node[start-k]
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Use a dictionary to store every node in the list at first.
# There are three situation for k:
# 1. k = 0, just no change
# 2. k less than list length n, then the (n-k+1)th node will be the head node when return. Make
# some change to node pointing relation.
# 3. k greater than or equal to length n, k = k % n, then come back to situation 1 or 2. |
# ------------------------------
# 95. Unique Binary Search Trees II
#
# Description:
# Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n.
# Example:
# Input: 3
# Output:
# [
# [1,null,3,2],
# [3,2,null,1],
# [3,1,null,null,2],
# [2,1,3],
# [1,null,2,null,3]
# ]
# Explanation:
# The above output corresponds to the 5 unique BST's shown below:
# 1 3 3 2 1
# \ / / / \ \
# 3 2 1 1 3 2
# / / \ \
# 2 1 2 3
#
# Version: 1.0
# 08/08/18 by Jianfa
# ------------------------------
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
if n <= 0:
return []
nums = [i for i in range(1, n+1)]
return self.buildBST(nums)
def buildBST(self, nums):
if not nums:
return [None]
if len(nums) == 1:
return [TreeNode(nums[0])]
currlist = []
for i in range(len(nums)):
leftBST = self.buildBST(nums[:i])
rightBST = self.buildBST(nums[i+1:])
for j in range(len(leftBST)): # Use nested for loop to build BST
for k in range(len(rightBST)):
cur = TreeNode(nums[i])
cur.left = leftBST[j]
cur.right = rightBST[k]
currlist.append(cur)
return currlist
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Dynamic programming solution. |
# ------------------------------
# 434. Number of Segments in a String
#
# Description:
# Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.
# Please note that the string does not contain any non-printable characters.
# Example:
# Input: "Hello, my name is John"
# Output: 5
#
# Version: 1.0
# 07/02/18 by Jianfa
# ------------------------------
class Solution(object):
def countSegments(self, s):
"""
:type s: str
:rtype: int
"""
return len(s.split())
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Difference between s.split() and s.split(' '):
# ''.split() = []
# ''.split(' ') = [''] |
# ------------------------------
# 253. Meeting Rooms II
#
# Description:
# Given an array of meeting time intervals consisting of start and end times
# [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required.
#
# Example 1:
# Input: [[0, 30],[5, 10],[15, 20]]
# Output: 2
#
# Example 2:
# Input: [[7,10],[2,4]]
# Output: 1
#
# NOTE: input types have been changed on April 15, 2019. Please reset to default code
# definition to get new method signature.
#
# Version: 2.0
# 11/18/19 by Jianfa
# ------------------------------
import heapq
class Solution:
def minMeetingRooms(self, intervals: List[List[int]]) -> int:
intervals.sort(key=lambda x:x[0])
rooms = [] # store the end time of each room
for itv in intervals:
if not rooms or rooms[0] > itv[0]:
heapq.heappush(rooms, itv[1])
else:
heapq.heapreplace(rooms, itv[1])
return len(rooms)
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# More consise implementation. |
# ------------------------------
# 289. Game of Life
#
# Description:
# According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton
# devised by the British mathematician John Horton Conway in 1970."
#
# Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts
# with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the
# above Wikipedia article):
#
# Any live cell with fewer than two live neighbors dies, as if caused by under-population.
# Any live cell with two or three live neighbors lives on to the next generation.
# Any live cell with more than three live neighbors dies, as if by over-population..
# Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
# Write a function to compute the next state (after one update) of the board given its current state.
#
# Version: 1.0
# 11/08/17 by Jianfa
# ------------------------------
class Solution(object):
def gameOfLife(self, board):
"""
:type board: List[List[int]]
:rtype: void Do not return anything, modify board in-place instead.
"""
if not board or not board[0]:
return
m = len(board)
n = len(board[0])
for i in range(m):
for j in range(n):
liveNeighbour = self.countLives(board, i, j, m, n)
if board[i][j] == 1 and liveNeighbour >=2 and liveNeighbour <= 3:
board[i][j] = 3
elif board[i][j] == 0 and liveNeighbour == 3:
board[i][j] = 2
for i in range(m):
for j in range(n):
board[i][j] = board[i][j] / 2 # if python 3 here is board[i][j] // 2
def countLives(self, board, i, j, m, n):
lives = 0
for x in range(max(i-1, 0), min(i+2, m)): # At first I wrote min(i+1, m-1) which led to a wrong range
for y in range(max(j-1, 0), min(j+2, n)):
lives += board[x][y] % 2
lives -= board[i][j] % 2
return lives
# ------------------------------
# Summary:
# Use 2-digit number to represent state transition:
# 00: 0 -> 0 (0)
# 01: 1 -> 0 (1)
# 10: 0 -> 1 (2)
# 11: 1 -> 1 (3)
# First calculate the number of 1's (or 1 in 1st state, e.g. 01 and 11) around the target position
# Then modify the state in place. For example, 0 to 2 means dead to live, because 00 - > 01
# Finally traverse every cell again, to make the result only 0 or 1. |
# ------------------------------
# 450. Delete Node in a BST
#
# Description:
# Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.
#
# Basically, the deletion can be divided into two stages:
# Search for a node to remove.
# If the node is found, delete the node.
#
# Note: Time complexity should be O(height of tree).
#
# Example:
# root = [5,3,6,2,4,null,7]
# key = 3
# 5
# / \
# 3 6
# / \ \
# 2 4 7
#
# Given key to delete is 3. So we find the node with value 3 and delete it.
# One valid answer is [5,4,6,2,null,null,7], shown in the following BST.
# 5
# / \
# 4 6
# / \
# 2 7
#
# Another valid answer is [5,2,6,null,4,null,7].
# 5
# / \
# 2 6
# \ \
# 4 7
#
# Version: 1.0
# 12/21/18 by Jianfa
# ------------------------------
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def deleteNode(self, root, key):
"""
:type root: TreeNode
:type key: int
:rtype: TreeNode
"""
if not root:
return None
if key < root.val:
root.left = self.deleteNode(root.left, key)
elif key > root.val:
root.right = self.deleteNode(root.right, key)
else:
if not root.left: # If there is no left subtree, return right subtree directly
root = root.right
elif not root.right: # If there is no right subtree, return left subtree directly
root = root.left
else:
minNode = self.findMin(root.right) # Find a minimum node at the right subtree and replace root with it
root.val = minNode.val
root.right = self.deleteNode(root.right, root.val)
return root
def findMin(self, root):
while root.left:
root = root.left
return root
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Get idea from https://leetcode.com/problems/delete-node-in-a-bst/discuss/93296/Recursive-Easy-to-Understand-Java-Solution
# Steps:
#
# Recursively find the node that has the same value as the key, while setting the left/right nodes equal to the returned subtree
# Once the node is found, have to handle the below 4 cases
# node doesn't have left or right - return null
# node only has left subtree- return the left subtree
# node only has right subtree- return the right subtree
# node has both left and right - find the minimum value in the right subtree, set that value to the currently found node, then recursively delete the minimum value in the right subtree |
# ------------------------------
# 15. 3Sum
#
# Description:
# Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0?
# Find all unique triplets in the array which gives the sum of zero.
#
# Note: The solution set must not contain duplicate triplets.
# For example, given array S = [-1, 0, 1, 2, -1, -4],
# A solution set is:
# [
# [-1, 0, 1],
# [-1, -1, 2]
# ]
#
# Version: 1.0
# 10/11/17 by Jianfa
# ------------------------------
# import itertools
# class Solution(object):
# def threeSum(self, nums):
# """
# :type nums: List[int]
# :rtype: List[List[int]]
# """
# result = []
# count_0 = nums.count(0)
# if count_0 >= 3:
# result.append([0,0,0])
# nums.append(0)
# nums.sort()
# pos_0 = nums.index(0)
# left = set(itertools.combinations(nums[:pos_0], 2))
# for pair in left:
# if -sum(pair) in nums[pos_0:]:
# triplet = list(pair)
# triplet.append(-sum(pair))
# result.append(triplet)
# right = set(itertools.combinations(nums[pos_0+1:], 2))
# for pair in right:
# if -sum(pair) in nums[:pos_0]:
# triplet = list(pair)
# triplet.append(-sum(pair))
# result.append(triplet)
# return result
class Solution(object):
def threeSum(self, nums):
nums.sort()
res = []
if len(nums) < 3:
return res
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i-1]:
continue
sum_rest = 0 - nums[i]
low = i + 1
high = len(nums) - 1
while low < high:
if nums[low] + nums[high] == sum_rest:
res.append([nums[i], nums[low], nums[high]])
while low < high and nums[low] == nums[low+1]:
low += 1
while low < high and nums[high] == nums[high-1]:
high -= 1
low += 1
high -= 1
elif nums[low] + nums[high] < sum_rest:
low += 1
else:
high -= 1
return res
# Used for test
if __name__ == "__main__":
test = Solution()
num = [-1, 0, 1, 2, -1, -4]
print(test.threeSum(num))
# Summary
# My first solution meets Time Limit Exceeded. To sort it at first is a good start, but I shouln't do combination,
# which is time-consuming.
#
# I follow an idea "Concise O(N^2) Java solution" from discuss section.
# The key idea is to run through all indices of a possible first element of a triplet. For each
# possible first element we make a standard bi-directional 2Sum sweep of the remaining part of
# the array. Remember to skip equal items to avoid duplicates. |
# ------------------------------
# 113. Path Sum II
#
# Description:
# Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
# Note: A leaf is a node with no children.
# Example:
# Given the below binary tree and sum = 22,
# 5
# / \
# 4 8
# / / \
# 11 13 4
# / \ / \
# 7 2 5 1
#
# Return:
# [
# [5,4,11,2],
# [5,8,4,5]
# ]
#
# Version: 1.0
# 08/12/18 by Jianfa
# ------------------------------
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
if not root:
return []
res = []
curlist = []
self.helper(res, curlist, root, sum)
return res
def helper(self, res, curlist, root, sum):
if not root:
return
curlist.append(root.val)
if sum == root.val and not root.left and not root.right:
temp = [x for x in curlist]
res.append(temp)
curlist.pop()
return
else:
self.helper(res, curlist, root.left, sum - root.val)
self.helper(res, curlist, root.right, sum - root.val)
curlist.pop()
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Notice the number may be negative integer. |
# ------------------------------
# 240. Search a 2D Matrix II
#
# Description:
# Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
# Integers in each row are sorted in ascending from left to right.
# Integers in each column are sorted in ascending from top to bottom.
#
# Example:
# Consider the following matrix:
# [
# [1, 4, 7, 11, 15],
# [2, 5, 8, 12, 19],
# [3, 6, 9, 16, 22],
# [10, 13, 14, 17, 24],
# [18, 21, 23, 26, 30]
# ]
# Given target = 5, return true.
# Given target = 20, return false.
#
# Version: 1.0
# 09/26/18 by Jianfa
# ------------------------------
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix or not matrix[0]:
return False
rightMost = len(matrix[0]) - 1 # Range of right most
bottomMost = len(matrix) - 1 # Range of bottom most
i = j = 0 # Starting point
while i <= bottomMost and j <= rightMost:
if matrix[i][j] == target:
return True
elif matrix[i][j] > target:
return False
for m in range(i, bottomMost + 1):
if matrix[m][j] == target:
return True
elif matrix[m][j] > target:
bottomMost = m - 1
break
for n in range(j, rightMost + 1):
if matrix[i][n] == target:
return True
elif matrix[i][n] > target:
rightMost = n - 1
break
i += 1
j += 1
return False
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Divide and conquer solution. Complexity is O(mn)
# Another much better solution would be start from the top right.
# If the target is less than current number, the target cannot be in an entire column;
# if the target is greater than current number, the targer cannot be in an entire row.
# The complexity will be O(m + n) |
# ------------------------------
# 236. Lowest Common Ancestor of a Binary Tree
#
# Description:
# Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
#
# According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
#
# Given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4]
# _______3______
# / \
# ___5__ ___1__
# / \ / \
# 6 _2 0 8
# / \
# 7 4
#
# Example 1:
# Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
# Output: 3
# Explanation: The LCA of of nodes 5 and 1 is 3.
#
# Example 2:
# Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
# Output: 5
# Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself
# according to the LCA definition.
#
# Note:
# All of the nodes' values will be unique.
# p and q are different and both values will exist in the binary tree.
#
# Version: 1.0
# 09/26/18 by Jianfa
# ------------------------------
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if root in (None, p, q):
return root
left = self.lowestCommonAncestor(root.left, p, q) # Recursively to check the left subtree of root
right = self.lowestCommonAncestor(root.right, p, q) # Recursively to check the right subtree of root
if left and right: # If p and q are in left and right respectively, return root
return root
else: # Else return either left or right
return left or right
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Idea from https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/65225/4-lines-C++JavaPythonRuby |
# ------------------------------
# 215. Kth Largest Element in an Array
#
# Description:
# Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
# Example 1:
# Input: [3,2,1,5,6,4] and k = 2
# Output: 5
#
# Example 2:
# Input: [3,2,3,1,2,4,5,5,6] and k = 4
# Output: 4
#
# Version: 1.0
# 09/04/18 by Jianfa
# ------------------------------
class Solution:
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
nums.sort(reverse=True)
return nums[k-1]
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# |
# ------------------------------
# 228. Summary Ranges
#
# Description:
# Given a sorted integer array without duplicates, return the summary of its ranges.
#
# Example 1:
# Input: [0,1,2,4,5,7]
# Output: ["0->2","4->5","7"]
# Example 2:
# Input: [0,2,3,4,6,8,9]
# Output: ["0","2->4","6","8->9"]
#
# Version: 1.0
# 12/11/17 by Jianfa
# ------------------------------
class Solution(object):
def summaryRanges(self, nums):
"""
:type nums: List[int]
:rtype: List[str]
"""
if not nums:
return []
res = []
s = nums[0]
e = nums[0]
for x in nums[1:]:
if x - e == 1:
e = x
else:
if s == e:
res.append(str(s))
else:
res.append("%d->%d" % (s, e))
s = x
e = x
if s == e:
res.append(str(s))
else:
res.append("%d->%d" % (s, e))
return res
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Initialize s and e, then check from the second item in array one by one. If a new item is more than 1 greater
# than the previous, add a new summary to result list.
# Finally add the last summary string to the result. |
# ------------------------------
# 259. 3Sum Smaller
#
# Description:
# Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 <= i < j < k < n
# that satisfy the condition nums[i] + nums[j] + nums[k] < target.
#
# For example, given nums = [-2, 0, 1, 3], and target = 2.
# Return 2. Because there are two triplets which sums are less than 2:
#
# [-2, 0, 1]
# [-2, 0, 3]
#
# Version: 1.0
# 11/14/17 by Jianfa
# ------------------------------
class Solution(object):
def threeSumSmaller(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
count = 0
for i in range(len(nums) - 2):
newTarget = target - nums[i]
left = i + 1
right = len(nums) - 1
while left < right:
if nums[left] + nums[right] < newTarget:
count += right - left
left += 1
else:
right -= 1
return count
# ------------------------------
# Summary:
# O(n^2) solution. The idea is to sort the nums at first. Then for every number from the least one, set a new
# target by target - nums[i]. Set two pointer for the rest number, calculate the possible pairs.
# E.g. [1,2,3,4,5] target is 9
# For 1, the new target is 8. since 2 + 5 < 8, so there are three possible pairs: (2,3), (2,4), (2,5) when
# when left = 2.
# More details can refer the solution section. |
# ------------------------------
# 201. Bitwise AND of Numbers Range
#
# Description:
# Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.
# Example 1:
# Input: [5,7]
# Output: 4
#
# Example 2:
# Input: [0,1]
# Output: 0
#
# Version: 1.0
# 08/27/18 by Jianfa
# ------------------------------
class Solution(object):
def rangeBitwiseAnd(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
if m == 0:
return 0
moveFactor = 1
while m != n:
m >>= 1
n >>= 1
moveFactor <<= 1
return m * moveFactor
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# From solution: https://leetcode.com/problems/bitwise-and-of-numbers-range/discuss/56729/Bit-operation-solution(JAVA)
# Key point: when m != n, There is at least an odd number and an even number, so the last bit position result is 0. |
# ------------------------------
# 271. Encode and Decode Strings
#
# Description:
# https://leetcode.com/problems/encode-and-decode-strings/description/
#
# Version: 1.0
# 11/10/17 by Jianfa
# ------------------------------
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string.
:type strs: List[str]
:rtype: str
"""
return "".join("%d:" % len(s) + s for s in strs)
def decode(self, s):
"""Decodes a single string to a list of strings.
:type s: str
:rtype: List[str]
"""
i = 0
decoded = []
while(i < len(s)):
j = s.find(":", i)
i = j + int(s[i:j]) + 1
decoded.append(s[j+1:i])
return decoded
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(strs))
# ------------------------------
# Summary:
# Follow the same idea from other's solution.
# Use "length:sentence" to encode a sentence, e.g 3:app5:apple9:pineapple, then decode based on every ":s" |
# ------------------------------
# 111. Minimum Depth of Binary Tree
#
# Description:
# Given a binary tree, find its minimum depth.
# The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
# Note: A leaf is a node with no children.
# Example:
# Given binary tree [3,9,20,null,null,15,7],
# 3
# / \
# 9 20
# / \
# 15 7
# return its minimum depth = 2.
#
# Version: 1.0
# 06/07/18 by Jianfa
# ------------------------------
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
visited = [root]
depth = 1
while visited:
for i in range(len(visited)):
cur = visited.pop(0)
if not cur.left and not cur.right:
return depth
if cur.left:
visited.append(cur.left)
if cur.right:
visited.append(cur.right)
depth += 1
return depth
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# BFS solution. Once a node with no child is found, return current depth. |
# ------------------------------
# c696. Count Binary Substrings (Weekly Contest 54)
#
# Description:
# Give a string s, count the number of non-empty (contiguous) substrings that have the same number of 0's
# and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively.
#
# Substrings that occur multiple times are counted the number of times they occur.
#
# Example 1:
# Input: "00110011"
# Output: 6
# Explanation: There are 6 substrings that have equal number of consecutive 1's and 0's: "0011", "01",
# "1100", "10", "0011", and "01".
#
# Notice that some of these substrings repeat and are counted the number of times they occur.
#
# Also, "00110011" is not a valid substring because all the 0's (and 1's) are not grouped together.
# Example 2:
# Input: "10101"
# Output: 4
# Explanation: There are 4 substrings: "10", "01", "10", "01" that have equal number of consecutive 1's and 0's.
#
# Version: 1.0
# 10/14/17 by Jianfa
# ------------------------------
class Solution(object):
def countBinarySubstrings(self, s):
"""
:type s: str
:rtype: int
"""
res = 0
l0 = l1 = 0
if int(s[0]):
flag = True
l1 += 1
else:
flag = False
l0 += 1
pre_len = 0
for idx, num in enumerate(s[1:]):
if flag:
if int(num):
l1 += 1
if l1 <= l0:
res += 1
else:
flag = False
l0 = 1
res += 1
else:
if not int(num):
l0 += 1
if l0 <= l1:
res += 1
else:
flag = True
l1 = 1
res += 1
return res
a = [1,2,3,4]
b = a[a<2]
# ------------------------------
# Summary:
# |
# ------------------------------
# 119. Pascal's Triangle II
#
# Description:
# Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.
# Note that the row index starts from 0.
# Example:
# Input: 3
# Output: [1,3,3,1]
#
# Follow up:
# Could you optimize your algorithm to use only O(k) extra space?
#
# Version: 1.0
# 06/07/18 by Jianfa
# ------------------------------
class Solution(object):
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
row = [1]
for i in range(rowIndex):
row = [x + y for x, y in zip([0] + row, row + [0])]
return row
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Use the idea from https://leetcode.com/problems/pascals-triangle-ii/discuss/38467/Very-simple-Python-solution |
# ------------------------------
# 315. Count of Smaller Numbers After Self
#
# Description:
# You are given an integer array nums and you have to return a new counts array. The counts
# array has the property where counts[i] is the number of smaller elements to the right of nums[i].
#
# Example:
#
# Input: [5,2,6,1]
# Output: [2,1,1,0]
# Explanation:
# To the right of 5 there are 2 smaller elements (2 and 1).
# To the right of 2 there is only 1 smaller element (1).
# To the right of 6 there is 1 smaller element (1).
# To the right of 1 there is 0 smaller element.
#
# Version: 1.0
# 11/18/19 by Jianfa
# ------------------------------
class Solution:
def countSmaller(self, nums: List[int]) -> List[int]:
def sortEnum(enum):
half = len(enum) // 2
if half:
left, right = sortEnum(enum[:half]), sortEnum(enum[half:])
for i in range(len(enum))[::-1]:
if not right or left and left[-1][1] > right[-1][1]:
# smaller number on the left, larger number on the right
smaller[left[-1][0]] += len(right)
enum[i] = left.pop()
else:
enum[i] = right.pop()
return enum
smaller = [0] * len(nums)
enums = list(enumerate(nums))
sortEnum(enums)
return smaller
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Merge sort solution from: https://leetcode.com/problems/count-of-smaller-numbers-after-self/discuss/76584/Mergesort-solution
# Key idea is the smaller numbers on the right of a number are exactly those that jump from
# its right to its left during a stable sort. So I do mergesort with added tracking of those
# right-to-left jumps.
#
# O(N * logN) time |
# ------------------------------
# 89. Gray Code
#
# Description:
# The gray code is a binary numeral system where two successive values differ in only one bit.
#
# Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray
# code. A gray code sequence must begin with 0.
# For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:
#
# 00 - 0
# 01 - 1
# 11 - 3
# 10 - 2
#
# Note:
# For a given n, a gray code sequence is not uniquely defined.
# For example, [0,2,3,1] is also a valid gray code sequence according to the above definition.
#
# Version: 1.0
# 02/02/18 by Jianfa
# ------------------------------
class Solution(object):
def grayCode(self, n):
"""
:type n: int
:rtype: List[int]
"""
res = []
for i in range(1 << n):
res.append(i ^ i >> 1)
return res
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Terrible problem.
# Idea from: https://leetcode.com/problems/gray-code/discuss/29881/An-accepted-three-line-solution-in-JAVA |
# ------------------------------
# 58. Length of Last Word
#
# Description:
# vGiven a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length
# of last word in the string.
# If the last word does not exist, return 0.
#
# Note: A word is defined as a character sequence consists of non-space characters only.
# Example:
# Input: "Hello World"
# Output: 5
#
# Version: 1.0
# 11/21/17 by Jianfa
# ------------------------------
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
words = s.split(' ')
for w in words[::-1]:
if len(w) > 0:
return len(w)
return 0
# Used for testing
if __name__ == "__main__":
test = Solution()
s = "world "
print(test.lengthOfLastWord(s))
# ------------------------------
# Summary:
# Note that the string may leave space at the end. |
# ------------------------------
# 118. Pascal's Triangle
#
# Description:
# Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
# In Pascal's triangle, each number is the sum of the two numbers directly above it.
# Example:
# Input: 5
# Output:
# [
# [1],
# [1,1],
# [1,2,1],
# [1,3,3,1],
# [1,4,6,4,1]
# ]
#
# Version: 1.0
# 06/07/18 by Jianfa
# ------------------------------
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if not numRows:
return []
pascal = [[1]]
for i in range(1, numRows):
last = pascal[i-1]
curr = [1]
for j in range(len(last) - 1):
curr.append(last[j]+last[j+1])
curr.append(1)
pascal.append(curr)
return pascal
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Calculate row by row. |
# ------------------------------
# 397. Integer Replacement
#
# Description:
# Given a positive integer n and you can do operations as follow:
#
# If n is even, replace n with n/2.
# If n is odd, you can replace n with either n + 1 or n - 1.
# What is the minimum number of replacements needed for n to become 1?
#
# Example 1:
# Input:
# 8
# Output:
# 3
# Explanation:
# 8 -> 4 -> 2 -> 1
#
# Example 2:
# Input:
# 7
# Output:
# 4
# Explanation:
# 7 -> 8 -> 4 -> 2 -> 1
# or
# 7 -> 6 -> 3 -> 2 -> 1
#
# Version: 1.0
# 10/09/19 by Jianfa
# ------------------------------
class Solution:
def integerReplacement(self, n: int) -> int:
if n == 1:
return 0
replaceCount = {1:0}
def dp(n: int) -> int:
if n in replaceCount:
return replaceCount[n]
if n % 2 == 0:
res = dp(n / 2) + 1
else:
res = min(dp(n + 1), dp(n - 1)) + 1
replaceCount[n] = res
return res
return dp(n)
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Dynamic programming solution.
# While there is another smart math solution idea from: https://leetcode.com/problems/integer-replacement/discuss/87928/Java-12-line-4(5)ms-iterative-solution-with-explanations.-No-other-data-structures.
# When n is even, the operation is fixed. The procedure is unknown when it is odd. When n is
# odd it can be written into the form n = 2k+1 (k is a non-negative integer.). That is,
# n+1 = 2k+2 and n-1 = 2k. Then, (n+1)/2 = k+1 and (n-1)/2 = k. So one of (n+1)/2 and (n-1)/2
# is even, the other is odd. And the "best" case of this problem is to divide as much as
# possible. Because of that, always pick n+1 or n-1 based on if it can be divided by 4. The
# only special case of that is when n=3 you would like to pick n-1 rather than n+1.
|
# ------------------------------
# 29. Divide Two Integers
#
# Description:
# Divide two integers without using multiplication, division and mod operator.
#
# If it is overflow, return MAX_INT.
#
# Version: 1.0
# 12/18/17 by Jianfa
# ------------------------------
class Solution(object):
def divide(self, dividend, divisor):
"""
:type dividend: int
:type divisor: int
:rtype: int
"""
positive = (dividend < 0) is (divisor < 0)
dividend, divisor = abs(dividend), abs(divisor)
res = 0
while dividend >= divisor:
temp, i = divisor, 1
while dividend >= temp:
dividend -= temp
res += i
i <<= 1
temp <<= 1
if not positive:
res = -res
return min(max(-2147483648, res), 2147483647)
# Used for testing
if __name__ == "__main__":
test = Solution()
dividend, divisor = 15, 3
print(test.divide(dividend, divisor))
# ------------------------------
# Summary:
# Solution from "Clear python code" in discuss section. |
# ------------------------------
# 153. Find Minimum in Rotated Sorted Array
#
# Description:
# Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
#
# (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
#
# Find the minimum element.
# You may assume no duplicate exists in the array.
#
# Example 1:
# Input: [3,4,5,1,2]
# Output: 1
#
# Example 2:
# Input: [4,5,6,7,0,1,2]
# Output: 0
#
# Version: 2.0
# 11/10/19 by Jianfa
# ------------------------------
class Solution:
def findMin(self, nums: List[int]) -> int:
low = 0
high = len(nums) - 1
# at least one side is monotonic increasing,
# so try to find which side the rotation pivot is on based on if that side is not monotonic increasing
while low < high:
mid = (low + high) // 2
if nums[mid] > nums[high]:
low = mid + 1
else:
high = mid
return nums[low]
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# More concise solution, similar to 153.py |
# ------------------------------
# 242. Valid Anagram
#
# Description:
# Given two strings s and t , write a function to determine if t is an anagram of s.
#
# Example 1:
# Input: s = "anagram", t = "nagaram"
# Output: true
#
# Example 2:
# Input: s = "rat", t = "car"
# Output: false
# Note:
# You may assume the string contains only lowercase alphabets.
# Follow up:
# What if the inputs contain unicode characters? How would you adapt your solution to such case?
#
# Version: 1.0
# 06/22/18 by Jianfa
# ------------------------------
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
sdict = {}
for i in s:
if i not in sdict:
sdict[i] = 1
else:
sdict[i] += 1
for j in t:
if j not in sdict:
return False
else:
sdict[j] -= 1
if sdict[j] == 0:
del sdict[j]
if len(sdict) != 0:
return False
return True
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Answer to follow-up:
# Use a hash table instead of a fixed size counter. Imagine allocating a large size array to fit the entire range of unicode characters, which could go up to more than 1 million. A hash table is a more generic solution and could adapt to any range of characters. |
# ------------------------------
# 103. Binary Tree Zigzag Level Order Traversal
#
# Description:
# Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
# For example:
# Given binary tree [3,9,20,null,null,15,7],
# 3
# / \
# 9 20
# / \
# 15 7
# return its zigzag level order traversal as:
# [
# [3],
# [20,9],
# [15,7]
# ]
#
# Version: 1.0
# 08/10/18 by Jianfa
# ------------------------------
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
stack = [root]
res = []
order = True # from left to right
while stack:
temp = []
if order:
res.append([node.val for node in stack])
else:
res.append([node.val for node in stack[::-1]])
for node in stack:
temp.extend([node.left, node.right])
stack = [node for node in temp if node]
order = not order
return res
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Similar to problem 102. |
# ------------------------------
# 34. Search for a Range
#
# Description:
# Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
#
# (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
# You are given a target value to search. If found in the array return its index, otherwise return -1.
#
# You may assume no duplicate exists in the array.
#
#
# Version: 1.0
# 10/24/17 by Jianfa
# ------------------------------
class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) / 2
if nums[mid] > target:
right = mid - 1
elif nums[mid] < target:
left = mid + 1
else:
break
if left > right:
return [-1, -1]
tmp_m = mid
while left <= tmp_m:
if nums[(left + tmp_m) / 2] == target:
tmp_m = (left + tmp_m) / 2 - 1
else:
left += 1
tmp_m = mid
while right >= tmp_m:
if nums[(right + tmp_m) / 2] == target:
tmp_m = (right + tmp_m) / 2 + 1
else:
right -= 1
return [left, right]
# Used for test
if __name__ == "__main__":
test = Solution()
nums = [5,7,7,8,8,10]
target = 8
print(test.searchRange(nums, target))
# ------------------------------
# Summary:
# Binary search. |
# ------------------------------
# 75. Sort Colors
#
# Description:
# Given an array with n objects colored red, white or blue, sort them in-place so that
# objects of the same color are adjacent, with the colors in the order red, white and
# blue.
#
# Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue
# respectively.
#
# Note: You are not suppose to use the library's sort function for this problem.
#
# Example:
#
# Input: [2,0,2,1,1,0]
# Output: [0,0,1,1,2,2]
#
# Follow up:
# A rather straight forward solution is a two-pass algorithm using counting sort.
# First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array
# with total number of 0's, then 1's and followed by 2's.
# Could you come up with a one-pass algorithm using only constant space?
#
# Version: 1.0
# 10/06/17 by Jianfa
# ------------------------------
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
if not nums:
return nums
l = 0
while l < len(nums) and nums[l] == 0:
l += 1
r = len(nums) - 1
while r >= 0 and nums[r] == 2:
r -= 1
i = l
while i <= r:
if nums[i] == 0:
nums[i] = nums[l]
nums[l] = 0
l += 1
i += 1
elif nums[i] == 2:
nums[i] = nums[r]
nums[r] = 2
r -= 1
else:
i += 1
# Used for test
if __name__ == "__main__":
test = Solution()
nums = [2,0]
test.sortColors(nums)
print(nums)
# ------------------------------
# Summary:
# O(n) solution.
# Set l, i, r pointer. Move l forward to the first position that is not 0, move r backward to the first position
# that is not 2.
# While i <= r, do judgement
# if meeting a "0", exchange number in l and i, then move 1 step both l and i (note)
# if meeting a "1", move i
# if meeting a "2", exchange number in r and i, then just move r 1 step back!! (just r) |
# ------------------------------
# 406. Queue Reconstruction by Height
#
# Description:
# Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the queue.
#
# Note:
# The number of people is less than 1,100.
#
# Example
# Input:
# [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
#
# Output:
# [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
#
# Version: 1.0
# 11/25/17 by Jianfa
# ------------------------------
class Solution(object):
def reconstructQueue(self, people):
"""
:type people: List[List[int]]
:rtype: List[List[int]]
"""
people.sort(key=lambda person: (-person[0], person[1]))
queue = []
for p in people:
queue.insert(p[1], p)
return queue
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# I didn't come up with this idea myself. Reference is in the discuss section. "Explanation of the neat Sort+Insert solution" |
class bin_heap:
def __init__(self):
self.heapsize = 0
self.heaplist = [0]
def heapify(self, i):
largest = i
l = 2*i + 1
r = 2*i + 2
# print('larg = ', largest, self.heaplist[largest])
# print('l = ', l, self.heaplist[l])
# print('r = ', r, self.heaplist[r])
if l < self.heapsize and self.heaplist[l] > self.heaplist[i]:
largest = l
if r < self.heapsize and self.heaplist[r] > self.heaplist[largest]:
largest = r
if largest != i:
self.heaplist[i], self.heaplist[largest] = self.heaplist[largest], self.heaplist[i]
self.heapify(largest)
def buildHeap(self, list):
self.heaplist = list
self.heapsize = len(list)
# Индексы c середины и до нуля включительно
# print(self.heapsize)
for i in range(len(list) // 2, -1, -1):
print(i)
self.heapify(i)
return self.heaplist
|
def main():
v, e = map(int, input('Введите через пробел количество вершин и ребер: ').split())
A = [[0] * (v) for i in range(v)] # создаем матрицу V на V
for i in range(e):
a, b = map(int, input('Введите ребро номер ' + str(i) +' из ' + str(e) + ': ').split())
A[a][b] = 1
A[b][a] = 1 # Для создания ориентированного графа закомментировать эту сроку
for i in A:
print(i)
if __name__ == '__main__':
main()
|
#--------------iteration algo------------------
N = [i for i in range(100)]
def binary_s(N, A):
M = 0
while M != A:
n = len(N)//2
M = N[n]
N_left, N_right = N[:n], N[n+1:] # постоянно забываю что сюда передаем не переменную, а ее положение в списке
if A == M:
print("I found it!!")
elif A > M:
N = N_right[:]
#binary_s(N,A)
elif A < M:
N = N_left[:]
#binary_s(N, A)
binary_s(N, 30)
#----------------------------------------------------------------------------------
#-------------------with recursion-------------------------------------------------
#----------------------------------------------------------------------------------
N = [i for i in range(100)]
def binary_s(N, A):
n = len(N)//2
M = N[n]
N_left, N_right = N[:n], N[n+1:]
if A == M:
print("I found it!! with recursion")
elif A > M:
N = N_right[:]
binary_s(N,A)
elif A < M:
N = N_left[:]
binary_s(N, A)
binary_s(N, 99) |
G = {0: [1, 6],
1: [2, 3],
2: [1],
3: [1, 4],
4: [3, 5],
5: [4, 6],
6: [5, 0]
}
n = len(G.keys())
print(n)
s = 0 #начало пути
visited = [False] * n # массив посещенных вершин
# аглоритм прохода в глубину определяет колличество вершин в данном компоненте связности
def dfs(v):
visited[v] = True
print('visit = ', v)
print('G = ', G.get(v))
for w in G.get(v):
print('w = ', w)
if visited[w] == False: # посещён ли текущий сосед?
print('w=', w)
dfs(w)
# print(dfs(s))
# print(visited)
#---------------------------------------------------------------------------
def dfs2(vertex, graph, used):
# used = used or set() #питон умеет так))))
used.add(vertex)
for neighbour in graph[vertex]:
if neighbour not in used:
dfs2(neighbour, graph, used)
print(vertex)
used = set()
N = 0
for vertex in G:
if vertex not in used:
dfs2(vertex, G, used)
N += 1 # подсчет компонени связности
print(N) |
import random
import unittest
from recur_binary_search import binary_search
from random import choice
class TestCase(unittest.TestCase):
# def test_true_recursion(self):
# array = [1, 2, 7, 12, 43, 44, 54, 100, 124, 147]
# n = choice(array)
# print(f"Random numbers: {n}")
# result = binary_search(array, n)
# self.assertTrue(result)
def test_random_recursion(self):
array = [1, 2, 7, 12, 43, 44, 54, 100, 124, 147]
false_array = [i for i in range(1, 150)]
for n in false_array:
result = binary_search(array, n)
if n in array:
self.assertTrue(result)
print("Trouvé")
else:
self.assertFalse(result)
print("Pas dedans")
if __name__ == '__main__':
unittest.main() |
import random
def Quotes():
QUOTE_DICT = {"patience" : [["\"Patience, grasshopper\", said Maia. \"Good things come to those who wait.\" \"I always thought that was \'Good things come to those who do the wave\'\", said Simon. \"No wonder I\'ve been so confused all my life.\"",
"Cassandra Clare",
"City of Glass"],
["He that can have patience can have what he will.",
"Benjamin Franklin",
""],
["Patience is bitter, but its fruit is sweet.",
"Aristotle",
""],
["Why is patience so important? Because it makes us pay attention.",
"Paulo Coelho",
""],
["Patience, he thought. So much of this was patience - waiting, and thinking and doing things right. So much of all this, so much of all living was patience and thinking.",
"Gary Paulsen",
"Hatchet"],
["Waiting and hoping is a hard thing to do when you've already been waiting and hoping for almost as long as you can bear it.",
"Jenny Nimmo",
"Charlie Bone and the Time Twister"],
["But if we hope for what we do not see, we wait for it with patience.",
"",
"The Bible, Romans 8, 25"]],
"love" : []}
QUOTES = sorted(QUOTE_DICT['patience'], key=lambda k: random.random())
return QUOTES
# num = random.randint(0, 6)
# for i in QUOTE_DICT['patience'][num]:
# return i
# print str()
# return str(QUOTE_DICT['patience'][num][0])
|
__arglist__ = {'2選1:(關數請寫1,卡片數請寫2)': 'x', '其數量': 'card', '時間': 'time'}
def __invoke__(arg):
Time = float(arg["time"])
Card = int(arg["card"])
Choice = int(arg["x"])
if Choice==1:
if Card <= 35:
Card = Card + Card // 5 * 2 + (Card+2) // 5
else:
Card = 56 + (Card-35) * 2 + (Card-35)//2 * 4
Cardpertime = float(Card/Time)
print("平均每分鐘獲得的卡片數量 : ", Cardpertime)
if Cardpertime <= 4:
print("沒有效率!")
elif Cardpertime >= 4 and Cardpertime <= 5:
print("還可以")
else:
print("有效率!!!")
|
#!/usr/bin/env python
import turtle
class Window:
"""Provides methods for manipulating the tkinter/turtle window/screen"""
def __init__(self, bounds, bg):
"""Initialize the tkinter/turtle window/screen for interfacing."""
self.screen = turtle.Screen()
assert isinstance(bounds, tuple), "`bounds` must be a tuple"
for n in bounds:
assert isinstance(n, (int, float)), "`bounds` content not digit"
assert len(bounds) == 4, "`bounds` must only have 4 values"
self.bounds = bounds
self.screen.setworldcoordinates(*self.bounds)
assert isinstance(bg, str), "`bg` must be a str"
if "." in bg:
assert bg.endswith(".gif"), "`bg` must be .gif image"
self.screen.bgpic(bg)
else:
self.screen.bgcolor(bg)
def draw_line(self, x=None, y=None, color="black"):
"""Draws a non-diagonal line onscreen for a given bounding box
The optional parameters `x` and `y` are mutually exclusive and
one must be set, specifying the line to be drawn.
"""
lhb, lvb, uhb, uvb = self.bounds
pen = turtle.Turtle(visible=False)
pen.pencolor(color)
pen.speed(0)
pen.penup()
assert x is not None or y is not None, "Neither `x` or `y` are set"
if x is not None:
assert isinstance(x, (int, float)), "`x` is not a valid number"
pen.setposition(x, lvb)
pen.pendown()
pen.sety(uvb)
else:
assert isinstance(y, (int, float)), "`y` is not a valid number"
pen.setposition(lhb, y)
pen.pendown()
pen.setx(uhb)
pen.penup()
def draw_grid(self, size=10):
abs_vb, abs_hb = self.bounds[2:]
for n in range(0, abs_hb + 1, size):
if n != 0:
for coord in n, -n:
Window.draw_line(self, y=coord)
else:
Window.draw_line(self, y=n, color="red")
for n in range(0, abs_vb + 1, size):
if n != 0:
for coord in n, -n:
Window.draw_line(self, x=coord)
else:
Window.draw_line(self, x=n, color="red")
|
#using boolean
#is_male = input(" Enter True or False: Are you male? :")
#is_tall = input(" Enter True or False: Are you male? :")
is_male=False
is_tall=False
if is_male and is_tall:
print("You are male and tall")
elif is_male and not is_tall:
print("You are a short male")
elif not is_male and is_tall:
print("You are a not male but tall")
else:
print("You are not a male and not tall") |
#檔案的讀取、寫入
#Open("檔案路徑", mode= "開啟模式")
# 絕對路徑 Ex: C:/Users/didd4/OneDrive/文件\python
# 相對路徑 以程式的位置做延伸 ex: 123.txt
# mode = "r" 讀取
# mode = "w" 複寫
# mode = "a" 在原先的資料後寫東西
file = open("123.txt",mode="a",encoding="utf-8")
# for line in file:
# print(line)
file.write("\n蔡陰魂")
file.close()
|
# for 迴圈
# for 變數 in 字串OR列表:
# 要重覆執行的程式碼
#for letter in "我是皮卡丘":
# print(letter)
#for num in[0,1,2,3,4]:
# print(num)
#for num in range(2,7):
# print(num)
def power(base_num,pow_num):
result = 1
for index in range(pow_num):
result = result * base_num
return result
print(power(2,5))
|
class Cards:
def __init__(self, hand_one=[], hand_two=[]):
self.player_1 = hand_one
self.player_2 = hand_two
def deal(self, data):
player_1 = data[0].split('\n')[1:]
player_2 = data[1].split('\n')[1:]
self.player_1 = list(map(int, player_1))
self.player_2 = list(map(int, player_2))
def play(self):
deck = len(self.player_1) + len(self.player_2)
game_over = False
while not game_over:
p1 = self.player_1.pop(0)
p2 = self.player_2.pop(0)
if p1 > p2:
self.player_1.append(p1)
self.player_1.append(p2)
else:
self.player_2.append(p2)
self.player_2.append(p1)
game_over = (len(self.player_1) == deck or len(self.player_2) == deck)
self.winner = self.player_1 if len(self.player_1) else self.player_2
def score(self):
total = 0
top = len(self.winner)
for i, val in enumerate(self.winner):
total += (top - i) * val
return total
def to_key(hand):
return ":".join(map(str,hand))
class RecursiveCombat(Cards):
def __init__(self, hand_one=[], hand_two=[]):
super().__init__(hand_one, hand_two)
self.hands_one = set()
self.hands_two = set()
def play(self):
deck = len(self.player_1) + len(self.player_2)
game_over = False
while not game_over:
h1 = to_key(self.player_1)
h2 = to_key(self.player_2)
if h1 in self.hands_one or h2 in self.hands_two:
self.winner = self.player_1
return True
self.hands_one.add(h1)
self.hands_two.add(h2)
p1 = self.player_1.pop(0)
p2 = self.player_2.pop(0)
p1_win = p1 > p2 if len(self.player_1) < p1 or len(self.player_2) < p2 else RecursiveCombat(self.player_1[:p1],self.player_2[:p2]).play()
if p1_win:
self.player_1.extend([p1,p2])
else:
self.player_2.extend([p2,p1])
game_over = (len(self.player_1) == deck or len(self.player_2) == deck)
if len(self.player_1) == deck:
self.winner = self.player_1
return True
else:
self.winner = self.player_2
return False
if __name__ == '__main__':
data = open("input.txt","r").read().split("\n\n")
game = Cards()
game.deal(data)
game.play()
print("Part 1:",game.score())
game = RecursiveCombat()
game.deal(data)
game.play()
print("Part 2:", game.score()) |
# Problem for Cracking the Coding Interview: Chapter 1
# 1.6
# String Compression:
# Implement a method to perform basic string compression using the counts of repeated characters.
# For example, the string aabcccccaaa would become a2b1c5a3.
# If the "compressed" string would not become smaller than the original string,
# your method should return the original string.
# You can assume the string has only uppercase and lowercase letters.
def compressString(s):
compressed = ''
count = 0
prevChar = s[0]
for char in s:
if char == prevChar:
count += 1
else:
compressed += prevChar + str(count)
count = 1
prevChar = char
if count != 0:
compressed += s[len(s) - 1] + str(count)
if len(compressed) <= len(s):
return compressed
else:
return s
s = 'aabcccccaaa'
print(s + ' = ' + compressString(s))
s = 'abcde'
print(s + ' = ' + compressString(s))
s = 'aaa'
print(s + ' = ' + compressString(s))
## Thoughts
# Thought about using a hashmap/array to map characters and the order but won't work
# because the same letter can appear again
# For loop through the string
# If the character is the same from the previous iteration
# add count
# else
# compressed += prevChar + str(count)
# count = 0
#
|
# "Maximum Substring With Non-Repeating Characters" from SWE Careers
# Given a string, find the length of the longest substring without repeating characters.
# Example 1:
# Input: "abcabcbb"
# Output: 3
# Explanation: The answer is "abc", with the length of 3.
# Example 2:
# Input: "bbbbb"
# Output: 1
# Explanation: The answer is "b", with the length of 1.
def lengthOfLongestSubstring(s: str):
if len(s) == 1 or len(s) == 0:
return len(s)
maxLength = 1
for i in range(0, len(s) - 1):
substr = s[i]
allCharIsUnique = True
j = i + 1
while (allCharIsUnique):
# If next character doesn't exist
if j != len(s) and substr.count(s[j]) == 0:
# Append the next character to substr
substr += s[j]
if (len(substr) > maxLength): maxLength = len(substr)
j += 1
else:
allCharIsUnique = False
return maxLength
def lengthOfLongestSubstring(s: str):
if len(s) == 1 or len(s) == 0:
return len(s)
maxLength = 1
startIndex = 0
substr = s[0]
for endIndex in range(len(s)):
if substr.find(s[endIndex]) == -1:
substr += s[endIndex]
maxLength = max(len(substr), maxLength)
else:
startIndex +=1
substr = s[startIndex]
return maxLength
str = 'dvdfabc'
print(lengthOfLongestSubstring(str))
|
from disassembler import *
def factorial(n):
if n==0:
return 1
return n*factorial(n-1)
def main():
x = int(input("Please enter an integer: "))
y = factorial(x)
print("Factorial of", x, "is", str(y)+".")
print(type(x))
print(type(factorial))
z = type(factorial)
print(z)
print(type(z))
print(type(type(z)))
print(type(print))
disassemble(factorial)
disassemble(main) |
import disassembler
def factorial(n):
if n==0:
return 1
return n*factorial(n-1)
def main():
print(factorial(5))
#main()
disassembler.disassemble(factorial)
disassembler.disassemble(main) |
class PlayerStats:
""" Statistics on a basketball team """
#def __init__ (self, total_num_players, num_guards, num_forwards, num_centers, avg_years_played):
_player_manager = None
def __init__(self, player_manager):
self._player_manager = player_manager
def get_total_num_players(self):
""" Returns the number of total players """
total_num_players = self._player_manager.get_all()
return len(total_num_players)
def get_num_guards(self):
""" Returns the number of guards """
total_num_guards = self._player_manager.get_all_by_type("guard")
return len(total_num_guards)
def get_num_forwards(self):
""" Returns the number of forwards """
total_num_forwards = self._player_manager.get_all_by_type("forward")
return len(total_num_forwards)
def get_num_centers(self):
""" Returns the number of centers """
total_num_centers = self._player_manager.get_all_by_type("center")
return len(total_num_centers)
def get_avg_years_played(self):
""" Returns the average years played """
all_players = self._player_manager.get_all()
for player in all_players:
number = player.get_player_year_drafted()
number2 = 2019 - number
number3 = 0
number3 = number3 + number2
avg_years_played = number3 / len(all_players)
return avg_years_played
|
# Анализатор текста
# Демонстрирует работу функции len() и оператора in
# всё просто
msg = input('Введите текст: ')
print('\nДлина введенного вами текста составляет:', len(msg))
new_msg = ''
for letter in msg[::-1]:
new_msg += letter
print('Создана новая строка:', new_msg)
input('\n\nНажмите Enter, что бы выйти...') |
"""Можно конечно просто без вариативно написать, переменню цитаты и кто сказал"""
favorite_quote = None # всё так же как и в предыдущей задаче
while not favorite_quote:
favorite_quote = input('Ваша любимая цитата?') # дотех пор пока нет вводе будет повторяться до бесконечности
name = input('Автор?') # если не ввисти будет я по умолчанию
if not name:
name = 'Im'
print(f' {favorite_quote.upper()} \n\n' # поднимим к верхниму ригистру
f'{name.capitalize():>50}') # сдвиним имя автора вправо, до сих пор не нарадуюсь f строкам!!
input('\n\nНажмите Enter, что бы выйти...')
|
import numpy as np
def rolling_window(a, window, step):
"""
Make an ndarray with a rolling window of the last dimension with a given step size.
Parameters
----------
a : array_like
Array to add rolling window to
window : int
Size of rolling window
step : int
Size of steps between windows
Returns
-------
Array that is a view of the original array with a added dimension
of size window.
Examples
--------
>>> x=np.arange(10).reshape((2,5))
>>> rolling_window(x, 3)
array([[[0, 1, 2], [1, 2, 3], [2, 3, 4]],
[[5, 6, 7], [6, 7, 8], [7, 8, 9]]])
Calculate rolling mean of last dimension:
>>> np.mean(rolling_window(x, 3), -1)
array([[ 1., 2., 3.],
[ 6., 7., 8.]])
"""
if window < 1:
raise ValueError("`window` must be at least 1.")
if window > a.shape[-1]:
raise ValueError("`window` is too long.")
shape = a.shape[:-1] + ((a.shape[-1] - window) // step + 1, window)
strides = a.strides[:-1] + (step * a.strides[-1], a.strides[-1])
return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
def segment_signal(signal, segment_length, segment_step):
return rolling_window(signal, segment_length, segment_step)
def segment_and_sequence_psg(segmentation, fs, psg, hypnogram):
psg_seg = {key: [] for key in psg.keys()}
num_segments_in_sequence = int(
segmentation['SEQUENCE_DURATION_MIN'] / segmentation['EPOCH_LENGTH_SEC'] * 60)
for chn in psg_seg.keys():
segment_length_sec = segmentation['SEGMENT_LENGTH'][chn]
segment_overlap = segmentation['SEGMENT_OVERLAP'][chn]
segment_length = int(segment_length_sec * fs)
segment_step = int((segment_length_sec - segment_overlap) * fs)
psg_seg[chn] = segment_signal(psg[chn], segment_length, segment_step)
# # Create sequences
# psg_seg[chn] = np.reshape(psg_seg[chn], [psg_seg[chn].shape[0], num_segments_in_sequence, -1, segment_length])
# Segment the hypnogram
hypno_seg = segment_signal(
hypnogram, num_segments_in_sequence, num_segments_in_sequence)
# # If the signals and hypnogram are of different lengths, we assume that the start time is fixed for both,
# # so we trim the ends
trim_length = np.min([hypno_seg.shape[0], psg_seg['eeg'].shape[1]])
hypno_seg = hypno_seg[:num_segments_in_sequence *
(trim_length//num_segments_in_sequence), :]
psg_seg = {chn: sig[:, :num_segments_in_sequence *
(trim_length//num_segments_in_sequence), :] for chn, sig in psg_seg.items()}
# # Need to make sure the duration is divisible by the sequence length
# psg_seg = {chn: np.reshape(sig, [sig.shape[0], -1, num_segments_in_sequence, segment_length]) for chn, sig in psg_seg.items()}
# hypno_seg = np.reshape(hypno, [-1, num_segments_in_sequence])
#
# # Tranpose so that we have "batch size" ie. number of sequences in the first dimension, time step in the second
# # dimension (ie. number of segments in sequence), number of channels, number of features (ie. 1), and number of time
# # steps in segment (N, T, C, H, W)
# psg_seg = {chn: np.transpose(sig, axes=[1, 0])}
return psg_seg, hypno_seg
def segmentPSG(segmentation, fs, psg):
psg_seg = {key: [] for key in psg.keys()}
for chn in psg_seg.keys():
segmentLength_sec = segmentation['SEGMENT_LENGTH'][chn]
segmentOverlap = segmentation['SEGMENT_OVERLAP'][chn]
segmentLength = int(segmentLength_sec * fs)
segmentStep = int((segmentLength_sec - segmentOverlap) * fs)
psg_seg[chn] = segment_signal(psg[chn], segmentLength, segmentStep)
return psg_seg
|
'''
@autor: Vanderson Andrade
@data: 00/00/2019
@versão: 1.0
@descrição: Ler a velocidade de um carro e diz se ele foi multado por velocidade e mostra o valor da multa
'''
kmPermitido = 80
velocidadeCarro = float(input('Qual a velocidade do Carro em KM/H: '))
if velocidadeCarro > kmPermitido:
valorMulta = (velocidadeCarro - kmPermitido) * 7.0
print('Você exedeu o limite permitido de velocidade')
print('Valor da multa: R${:.2f}'.format(valorMulta))
else:
print('Dentro do limite de 80Km/h') |
'''
@autor: Vanderson Andrade
@data: 00/00/2019
@versão: 1.0
@descrição: emprestimo bancario para compra de uma casa
'''
nome = str(input('Nome: '))
salario = float(input('Salário: R$'))
vcasa = float(input('Valor do emprestimo: R$'))
tempoano = int(input('Quantos anos para pagar: '))
prestacao = vcasa / (tempoano*15)
if prestacao > (salario * 0.30):
print('\033[31;1;4mInfelizmente não podemos liberar seu emprestimo no momento.\033[m')
elif prestacao < (salario * 0.30):
print('\033[32mSeu emprestimo foi aprovado, verifique seu saldo.\033[m')
|
'''
@autor: Vanderson Andrade
@data: 00/00/2019
@versão: 1.0
@descrição: ler tres segmentos e dizer se é posivel forma um triangulo
'''
print('\033[32;1m-=\033[m'*13)
print(' \033[36;1mDesafio do Triangulo\033[m ')
print('\033[32;1m-=\033[m'*13)
s1 = float(input('Digite o primeiro segmento: '))
s2 = float(input('Digite o segundo segmento: '))
s3 = float(input('Digite o terceiro segmento: '))
if s1 < s2+s3 and s2 < s1+s3 and s3 < s1+s2 :
print('\033[32;1m\nOs segmentos podem formar um triângulo\033[m')
else:
print('\033[31;1m\nOs segmentos não podem formar um triângulo\033[m')
|
'''
@autor: Vanderson Andrade
@data: 00/00/2019
@versão: 1.0
@descrição: Reajuste salarial
'''
salario = float(input('Quanto está recebendo hoje? '))
if salario > 1250.00:
reajuste = (salario * 0.10) + salario
print('Reajuste de: \033[1;4;36mR${:.2f}\033[m'.format(salario * 0.10))
print('Novo salário: \033[1;4;32mR${:.2f}\033[m'.format(reajuste))
else:
reajuste = (salario * 0.15) + salario
print('Reajuste de: \033[1;4;36mR${:.2f}\033[m'.format(salario * 0.15))
print('Novo salário: \033[1;4;32mR${:.2f}\033[m'.format(reajuste))
|
'''
@autor: Vanderson Andrade
@data: 00/00/2019
@versão: 1.0
@descrição:
'''
'''
simples:
if condição:
bloco verdadeiro
else:
bloco falso
simples(simplificada)
'bloco verdadeiro' if condição else 'bloco falso'
'''
#Exemplos:
tempo = int(input('Quantos anos tem seu carro: '))
if tempo <= 3 :
print('Carro Novo')
else:
print('Carro Velho')
print('Carro Novo'if tempo <= 3 else 'Carro Velho') |
class Game(object):
"""Class Game"""
def __init__(self, name, release, developer, rating):
self.name = name
self.release=release
self.developer = developer
self.rating = rating
def __str__(self):
return self.name
def full_info(self):
game_str = self.name + "| Release Date: "+self.release +" | Developer: " + self.developer + " | Rating: " + self.rating
return game_str
|
#!/usr/bin/env python
import os
##从文件中读数据
def file_write_read():
"""
文件读、写,的步骤:
1.打开文件
2.读/写
3.关闭文件
"""
fn = open("名单","rb")
print(fn.read())
fn.seek(0)
content = fn.readlines() ## 读取所有行并返回列表
print(content)
for i in content:
print(i.decode("utf-8").strip())
fn.close()
##把数据写入到文件
fp = open("名单.txt", "wb")
address = ["中国","美国","新加坡"]
for i in address:
fp.write("{}\n".format(i).encode("utf-8"))
fp.close()
if __name__ == "__main__":
file_write_read()
|
smallest = None
largest = None
my_list = []
while True:
numb = input("Enter Number:")
if numb == ("done"):
break
try:
my_list.append (int(numb))
except:
print('Invalid input')
continue
for i in my_list:
if largest is None:
largest = i
elif i > largest:
largest = i
print ('Maximum is',largest)
for i in my_list:
if smallest is None:
smallest = i
elif i < smallest:
smallest = i
print ('Minimum is',smallest)
|
# French Cards
# French Cards have two states: hidden and visible.
# Choose 1 or 2 to flip that card between hidden and visible.
# Every time you hide a card, it's replaced with a
# random card from the rest of the deck.
# Game is over when all cards have been shown and then hidden.
import random
# hidden and deck used as constants.
hidden = True
# All cards encoded into a list
deck = list(range(100,113)) + \
list(range(200,213)) + \
list(range(300,313)) + \
list(range(400,413))
def printcards (card1, cardstate1, card2, cardstate2):
rank = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King']
suit = ["0", "Hearts", "Spades", "Diamonds", "Clubs"]
# Translate each deck code to a card to output
if card1:
cardrank = card1%100
cardsuit = card1//100
cardtoprint1 = rank[cardrank] + " of " + suit[cardsuit]
else:
cardtoprint1 = "< >" # No cards left to play here.
if card2:
cardrank = card2%100
cardsuit = card2//100
cardtoprint2 = rank[cardrank] + " of " + suit[cardsuit]
else:
cardtoprint2 = "< >"
if card1 and cardstate1 == hidden:
cardtoprint1 = "<==1==>" # Card is face down
if card2 and cardstate2 == hidden:
cardtoprint2 = "<==2==>"
print ("\n", cardtoprint1, " ", cardtoprint2, "\n")
return None
# picks a random card from the deck after removing the current card.
def setcard (excludelist):
for card in excludelist:
if card in deck:
deck.remove (card)
if deck:
card = random.choice (deck)
else:
card = False
return card
def main ():
cardstate1 = cardstate2 = hidden
card1 = card2 = 0
excludelist = [card1, card2]
card1 = setcard (excludelist)
card2 = setcard (excludelist)
while card1 or card2:
excludelist = [card1, card2]
printcards (card1, cardstate1, card2, cardstate2)
click = input ("Click a card (enter 1 or 2): ")
if click == '1' and cardstate1 == hidden:
cardstate1 = not hidden
elif click == '1' and cardstate1 == (not hidden):
cardstate1 = hidden
card1 = setcard (excludelist)
elif click == '2' and cardstate2 == hidden:
cardstate2 = not hidden
elif click == '2' and cardstate2 == (not hidden):
cardstate2 = hidden
card2 = setcard (excludelist)
else: # any other input quits.
break
if not deck:
printcards (card1, cardstate1, card2, cardstate2)
print ("All cards played.")
else:
print ("\nQuitting.")
return None
##
main ()
##
|
"""
This program computes maximum number of edges that can be inserted in a bipartite graph
without violating its bipartite property.
"""
print("No. of vertices: ")
n = int(input())
print("No. of edges: ")
e = int(input())
adjlst = {}
print("Enter edges - enter 'a b' if there is an edge between a and b :")
for i in range(e):
x,y = map(int, input().split(' '))
if(adjlst.get(x, -1) == -1):
adjlst[x] = [y]
else:
adjlst[x].append(y)
color = [0]*(n+1)
for i in adjlst.keys():
for j in range(len(adjlst[i])):
if(color[i] == color[adjlst[i][j]]):
color[adjlst[i][j]] = color[i] + 1
r = 0
g = 0
for i in range(1,n+1):
if(color[i] == 0):
g += 1
else:
r += 1
print("Maximum no. of edges that can be added without violating bipartite property is:")
print(g*r - e)
|
def shortestPath(ar,previndex=0,i=0):
m = i+1
if len(ar)==0:
return 0
if(i>= len(ar)):
return 0
if(i==0):
return ar[i][0] + shortestPath(ar,0,1)
if(previndex == 0 ):
result = min(ar[i][0],ar[i][1])
index = ar[i].index(result)
return result + shortestPath(ar,index,m)
elif(previndex == len(ar[i])-1):
result = min(ar[i][-2],ar[i][-1])
index = ar[i].index(result)
return result + shortestPath(ar,index,m)
else:
result = min(ar[i][previndex-1],ar[i][previndex],ar[i][previndex+1])
index = ar[i].index(result)
return result + shortestPath(ar,index,m)
triangles = [[2],[3,4],[6,5,7],[4,1,8,3]]
print(shortestPath(triangles)) |
def common_sub(str1,str2):
if(len(str1)==1 or len(str2)==1):
return 1
if(str1[-1]==str2[-1]):
count=common_sub(str1[:-1],str2[:-1])+1
else:
count=max(common_sub(str1[:-1],str2),common_sub(str1,str2[:-1]))
return count
str1="abcdaf"
str2="acbcf"
com=common_sub(str1,str2)
print(com) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.