Skip to content

Commit

Permalink
Fix flake8 related issues
Browse files Browse the repository at this point in the history
  • Loading branch information
kamyu104 committed Apr 21, 2018
1 parent 49ee3ca commit adbdf8e
Show file tree
Hide file tree
Showing 40 changed files with 336 additions and 239 deletions.
11 changes: 9 additions & 2 deletions Python/basic-calculator-ii.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
# Implement a basic calculator to evaluate a simple expression string.
#
# The expression string contains only non-negative integers, +, -, *, /
# operators and empty spaces . The integer division should truncate toward zero.
# operators and empty spaces . The integer division should truncate toward
# zero.
#
# You may assume that the given expression is always valid.
#
Expand All @@ -15,6 +16,12 @@
# Note: Do not use the eval built-in library function.
#

try:
xrange # Python 2
except NameError:
xrange = range # Python 3


class Solution:
# @param {string} s
# @return {integer}
Expand All @@ -24,7 +31,7 @@ def calculate(self, s):
for i in reversed(xrange(len(s))):
if s[i].isdigit():
operand += s[i]
if i == 0 or not s[i-1].isdigit():
if i == 0 or not s[i-1].isdigit():
operands.append(int(operand[::-1]))
operand = ""
elif s[i] == ')' or s[i] == '*' or s[i] == '/':
Expand Down
12 changes: 9 additions & 3 deletions Python/basic-calculator-iii.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
# The expression string may contain open ( and closing parentheses ),
# the plus + or minus sign -, non-negative integers and empty spaces .
#
# The expression string contains only non-negative integers, +, -, *, / operators ,
# The expression string contains only non-negative integers, +, -, *, /
# operators ,
# open ( and closing parentheses ) and empty spaces .
# The integer division should truncate toward zero.
#
Expand All @@ -21,6 +22,12 @@
#
# Note: Do not use the eval built-in library function.

try:
xrange # Python 2
except NameError:
xrange = range # Python 3


class Solution(object):
def calculate(self, s):
"""
Expand All @@ -32,7 +39,7 @@ def calculate(self, s):
for i in reversed(xrange(len(s))):
if s[i].isdigit():
operand += s[i]
if i == 0 or not s[i-1].isdigit():
if i == 0 or not s[i-1].isdigit():
operands.append(int(operand[::-1]))
operand = ""
elif s[i] == ')' or s[i] == '*' or s[i] == '/':
Expand Down Expand Up @@ -63,4 +70,3 @@ def compute(self, operands, operators):
operands.append(left * right)
elif op == '/':
operands.append(left / right)

37 changes: 24 additions & 13 deletions Python/basic-calculator-iv.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
# Time: +: O(d * t), t is the number of terms, d is the average degree of terms
# Time: +: O(d * t), t is the number of terms,
# d is the average degree of terms
# -: O(d * t)
# *: O(d * t^2)
# eval: O(d * t)
# to_list: O(d * tlogt)
# Space: O(e + d * t), e is the number of evalvars

# Given an expression such as expression = "e + 8 - a + 5" and
# an evaluation map such as {"e": 1} (given in terms of evalvars = ["e"] and evalints = [1]),
# return a list of tokens representing the simplified expression, such as ["-1*a","14"]
# - An expression alternates chunks and symbols, with a space separating each chunk and symbol.
# - A chunk is either an expression in parentheses, a variable, or a non-negative integer.
# an evaluation map such as {"e": 1}
# (given in terms of evalvars = ["e"] and evalints = [1]),
# return a list of tokens representing the simplified expression,
# such as ["-1*a","14"]
# - An expression alternates chunks and symbols,
# with a space separating each chunk and symbol.
# - A chunk is either an expression in parentheses, a variable,
# or a non-negative integer.
# - A variable is a string of lowercase letters (not including digits.)
# Note that variables can be multiple letters, and note that variables never
# have a leading coefficient or unary operator like "2x" or "-x".
Expand All @@ -20,15 +25,19 @@
#
# The format of the output is as follows:
# - For each term of free variables with non-zero coefficient,
# we write the free variables within a term in sorted order lexicographically.
# we write the free variables within a term in sorted order
# lexicographically.
# For example, we would never write a term like "b*a*c", only "a*b*c".
# - Terms have degree equal to the number of free variables being multiplied,
# counting multiplicity. (For example, "a*a*b*c" has degree 4.)
# We write the largest degree terms of our answer first,
# breaking ties by lexicographic order ignoring the leading coefficient of the term.
# - The leading coefficient of the term is placed directly to the left with an asterisk separating it
# from the variables (if they exist.) A leading coefficient of 1 is still printed.
# - An example of a well formatted answer is ["-2*a*a*a", "3*a*a*b", "3*b*b", "4*a", "5*c", "-6"]
# breaking ties by lexicographic order ignoring the leading coefficient of
# the term.
# - The leading coefficient of the term is placed directly to the left with an
# asterisk separating it from the variables (if they exist.)
# A leading coefficient of 1 is still printed.
# - An example of a well formatted answer is
# ["-2*a*a*a", "3*a*a*b", "3*b*b", "4*a", "5*c", "-6"]
# - Terms (including constant terms) with coefficient 0 are not included.
# For example, an expression of "0" has an output of [].
#
Expand All @@ -50,7 +59,8 @@
# Input: expression = "a * b * c + b * a * c * 4", evalvars = [], evalints = []
# Output: ["5*a*b*c"]
#
# Input: expression = "((a - b) * (b - c) + (c - a)) * ((a - b) + (b - c) * (c - a))",
# Input: expression =
# "((a - b) * (b - c) + (c - a)) * ((a - b) + (b - c) * (c - a))",
# evalvars = [], evalints = []
# Output:
# ["-1*a*a*b*b","2*a*a*b*c","-1*a*a*c*c","1*a*b*b*b","-1*a*b*b*c","-1*a*b*c*c",
Expand Down Expand Up @@ -120,8 +130,9 @@ def eval(self, lookup):
return result

def to_list(self):
return ["*".join((str(v),) + k) \
for k, v in sorted(self.items(), key=lambda(k, _): (-len(k), k)) \
return ["*".join((str(v),) + k)
for k, v in sorted(self.items(),
key=lambda(k, _): (-len(k), k))
if v]


Expand Down
8 changes: 7 additions & 1 deletion Python/basic-calculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@
# "(1+(4+5+2)-3)+(6+8)" = 23
#

try:
xrange # Python 2
except NameError:
xrange = range # Python 3


class Solution:
# @param {string} s
# @return {integer}
Expand All @@ -23,7 +29,7 @@ def calculate(self, s):
for i in reversed(xrange(len(s))):
if s[i].isdigit():
operand += s[i]
if i == 0 or not s[i-1].isdigit():
if i == 0 or not s[i-1].isdigit():
operands.append(int(operand[::-1]))
operand = ""
elif s[i] == ')' or s[i] == '+' or s[i] == '-':
Expand Down
20 changes: 14 additions & 6 deletions Python/battleships-in-a-board.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@
# Space: O(1)

# Given an 2D board, count how many different battleships are in it.
# The battleships are represented with 'X's, empty slots are represented with '.'s.
# The battleships are represented with 'X's, empty slots are represented with
# '.'s.
# You may assume the following rules:
#
# You receive a valid board, made of only battleships or empty slots.
# Battleships can only be placed horizontally or vertically. In other words,
# they can only be made of the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column),
# they can only be made of the shape 1xN (1 row, N columns) or Nx1
# (N rows, 1 column),
# where N can be of any size.
# At least one horizontal or vertical cell separates between two battleships -
# there are no adjacent battleships.
Expand All @@ -21,9 +23,15 @@
# ...X
# XXXX
# ...X
# This is not a valid board - as battleships will always have a cell separating between them.
# This is not a valid board - as battleships will always have a cell
# separating between them.
# Your algorithm should not modify the value of the board.

try:
xrange # Python 2
except NameError:
xrange = range # Python 3


class Solution(object):
def countBattleships(self, board):
Expand All @@ -37,7 +45,7 @@ def countBattleships(self, board):
cnt = 0
for i in xrange(len(board)):
for j in xrange(len(board[0])):
cnt += int(board[i][j] == 'X' and \
(i == 0 or board[i - 1][j] != 'X') and \
(j == 0 or board[i][j - 1] != 'X'))
cnt += int(board[i][j] == 'X' and
(i == 0 or board[i - 1][j] != 'X') and
(j == 0 or board[i][j - 1] != 'X'))
return cnt
15 changes: 9 additions & 6 deletions Python/beautiful-arrangement-ii.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,31 @@
# Space: O(1)

# Given two integers n and k,
# you need to construct a list which contains n different positive integers ranging
# from 1 to n and obeys the following requirement:
# you need to construct a list which contains n different positive integers
# ranging from 1 to n and obeys the following requirement:
# Suppose this list is [a1, a2, a3, ... , an],
# then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] has exactly k distinct integers.
# then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] has
# exactly k distinct integers.
#
# If there are multiple answers, print any of them.
#
# Example 1:
# Input: n = 3, k = 1
# Output: [1, 2, 3]
# Explanation: The [1, 2, 3] has three different positive integers ranging from 1 to 3,
# and the [1, 1] has exactly 1 distinct integer: 1.
# Explanation: The [1, 2, 3] has three different positive integers ranging
# from 1 to 3, and the [1, 1] has exactly 1 distinct integer: 1.
#
# Example 2:
# Input: n = 3, k = 2
# Output: [1, 3, 2]
# Explanation: The [1, 3, 2] has three different positive integers ranging from 1 to 3,
# Explanation: The [1, 3, 2] has three different positive integers ranging
# from 1 to 3,
# and the [2, 1] has exactly 2 distinct integers: 1 and 2.
#
# Note:
# The n and k are in the range 1 <= k < n <= 10^4.


class Solution(object):
def constructArray(self, n, k):
"""
Expand Down
22 changes: 15 additions & 7 deletions Python/beautiful-arrangement.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
# Space: O(n)

# 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:
# 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.
Expand All @@ -28,21 +30,27 @@
# Note:
# N is a positive integer and will not exceed 15.

try:
xrange # Python 2
except NameError:
xrange = range # Python 3


class Solution(object):
def countArrangement(self, N):
"""
:type N: int
:rtype: int
"""
def countArrangementHelper(n, arrangement):
def countArrangementHelper(n, arr):
if n <= 0:
return 1
count = 0
for i in xrange(n):
if arrangement[i] % n == 0 or n % arrangement[i] == 0:
arrangement[i], arrangement[n-1] = arrangement[n-1], arrangement[i]
count += countArrangementHelper(n - 1, arrangement)
arrangement[i], arrangement[n-1] = arrangement[n-1], arrangement[i]
if arr[i] % n == 0 or n % arr[i] == 0:
arr[i], arr[n-1] = arr[n-1], arr[i]
count += countArrangementHelper(n - 1, arr)
arr[i], arr[n-1] = arr[n-1], arr[i]
return count

return countArrangementHelper(N, range(1, N+1))
16 changes: 12 additions & 4 deletions Python/best-meeting-point.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@

from random import randint

try:
xrange # Python 2
except NameError:
xrange = range # Python 3


class Solution(object):
def minTotalDistance(self, grid):
"""
Expand All @@ -14,14 +20,16 @@ def minTotalDistance(self, grid):
mid_x = self.findKthLargest(x, len(x) / 2 + 1)
mid_y = self.findKthLargest(y, len(y) / 2 + 1)

return sum([abs(mid_x-i) + abs(mid_y-j) \
for i, row in enumerate(grid) for j, v in enumerate(row) if v == 1])
return sum([abs(mid_x-i) + abs(mid_y-j)
for i, row in enumerate(grid)
for j, v in enumerate(row) if v == 1])

def findKthLargest(self, nums, k):
left, right = 0, len(nums) - 1
while left <= right:
pivot_idx = randint(left, right)
new_pivot_idx = self.PartitionAroundPivot(left, right, pivot_idx, nums)
new_pivot_idx = self.PartitionAroundPivot(left, right,
pivot_idx, nums)
if new_pivot_idx == k - 1:
return nums[new_pivot_idx]
elif new_pivot_idx > k - 1:
Expand All @@ -35,7 +43,7 @@ def PartitionAroundPivot(self, left, right, pivot_idx, nums):
nums[pivot_idx], nums[right] = nums[right], nums[pivot_idx]
for i in xrange(left, right):
if nums[i] > pivot_value:
nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i]
nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i]
new_pivot_idx += 1

nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right]
Expand Down
13 changes: 7 additions & 6 deletions Python/best-time-to-buy-and-sell-stock-ii.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@
# However, you may not engage in multiple transactions at the same time
# (ie, you must sell the stock before you buy again).

try:
xrange # Python 2
except NameError:
xrange = range # Python 3


class Solution:
# @param prices, a list of integer
Expand All @@ -21,9 +26,5 @@ def maxProfit(self, prices):
return profit

def maxProfit2(self, prices):
return sum(map(lambda x: max(prices[x + 1] - prices[x], 0), range(len(prices[:-1]))))


if __name__ == "__main__":
result = Solution().maxProfit([3, 2, 1, 4, 2, 5, 6])
print result
return sum(map(lambda x: max(prices[x + 1] - prices[x], 0),
xrange(len(prices[:-1]))))
Loading

0 comments on commit adbdf8e

Please sign in to comment.