python Exercise (13)

Note that the answer is just someone else's code. It's correct, but it's not necessarily going to pass the test (such as timeouts). It's just that they're unique, although most of them are better than mine.

Now it's more than simple.

Implement Queue using Stacks

subject

Implement the following operations of a queue using stacks.

push(x) – Push element x to the back of queue.
pop() – Removes the element from in front of queue.
peek() – Get the front element.
empty() – Return whether the queue is empty.
Notes:
You must use only standard operations of a stack – which means only push to top, peek/pop from top, size, and is empty operations are valid.
Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

Thoughts and Solutions

It's still simple, but it's the kind I don't really want to write about.

class MyQueue(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.l=[]

    def push(self, x):
        """
        Push element x to the back of queue.
        :type x: int
        :rtype: void
        """
        self.l.append(x)


    def pop(self):
        """
        Removes the element from in front of queue and returns that element.
        :rtype: int
        """
        a=self.l[0]
        del self.l[0]
        return a

    def peek(self):
        """
        Get the front element.
        :rtype: int
        """
        return self.l[0]

    def empty(self):
        """
        Returns whether the queue is empty.
        :rtype: bool
        """
        return len(self.l)==0

Well, that's it.

Answer

Ah ah ah, I didn't finish the problem at all. I just saw the simulated queue.
The Title requires that the queue be simulated by stack... So I didn't use the stack. The eggs hurt.
Don't want to write any more. Write your thoughts.
Two stacks are used to simulate the queue.
One is responsible for push and the other is responsible for pop.
When push, pop all the elements of outStack to inStack, and then inStack.append (push)
When pop, pop all the elements of inStack to outStack, and then outStack.pop
When peek, pop all the elements of inStack to outStack, and then outStack.peek
When empty, determine whether both stacks are empty
Post a copy of someone else's

class Queue(object):
    def __init__(self):
        """
        initialize your data structure here.
        """
        self.inStack, self.outStack = [], []

    def push(self, x):
        """
        :type x: int
        :rtype: nothing
        """
        self.inStack.append(x)

    def pop(self):
        """
        :rtype: nothing
        """
        self.move()
        self.outStack.pop()

    def peek(self):
        """
        :rtype: int
        """
        self.move()
        return self.outStack[-1]

    def empty(self):
        """
        :rtype: bool
        """
        return (not self.inStack) and (not self.outStack) 

    def move(self):
        """
        :rtype nothing
        """
        if not self.outStack:
            while self.inStack:
                self.outStack.append(self.inStack.pop())

Longest Uncommon Subsequence I

subject

Given a group of two strings, you need to find the longest uncommon subsequence of this group of two strings. The longest uncommon subsequence is defined as the longest subsequence of one of these strings and this subsequence should not be any subsequence of the other strings.

A subsequence is a sequence that can be derived from one sequence by deleting some characters without changing the order of the remaining elements. Trivially, any string is a subsequence of itself and an empty string is a subsequence of any string.

The input will be two strings, and the output needs to be the length of the longest uncommon subsequence. If the longest uncommon subsequence doesn't exist, return -1.

Example 1:
Input: "aba", "cdc"
Output: 3
Explanation: The longest uncommon subsequence is "aba" (or "cdc"),
because "aba" is a subsequence of "aba",
but not a subsequence of any other strings in the group of two strings.
Note:

Both strings' lengths will not exceed 100.
Only letters from a ~ z will appear in input strings.

Thoughts and Solutions

Or easy
Doesn't this title mean the longest one to return to?
Then it enters two identical...

class Solution(object):
    def findLUSlength(self, a, b):
        if a == b:return -1
        return len(a) if len(a)>len(b) else len(b)

Is this not Shi Lezhi???
Horizontal trough 0.77%

Answer

       return -1 if a == b else max(len(a),len(b))

I seem to be foolish again.

A lot of people in the forum thought it was a Stupid Question.
They thought about DP, DFS, BFS, LCS and other methods.

Combination Sum

subject

Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:
[
[7],
[2, 2, 3]
]

Thoughts and Solutions

Medium Difficulty
There are some impressions on this question.
It's like the dfs timeout list (impressive)
. Not really. That's just the number of returns. There's a queue.
I'm afraid it's not O(n^3) with that scheme.
It seems like dfs is good, because different list s need to be generated at the same time.
And variables can be defined within classes

class Solution(object):
    def __init__(self):
        self.res=[]
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        def dfs(a, l, n):#a Remaining Length, l Generated List, i Prevent Turning, Repetition
            if a == 0:
                self.res.append(l)
                return
            for i in range(n, len(candidates)):
                if candidates[i] > a:
                    break
                dfs(a - candidates[i], l + [candidates[i]], i)

        dfs(target, [], 0)
        return self.res                              

a set of candidate numbers is not duplicated, not sorted, erased.

class Solution(object):
    def __init__(self):
        self.res=[]
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        def dfs(a, l, n):#a Remaining Length, l Generated List, i Prevent Turning, Repetition
            if a == 0:
                self.res.append(l)
                return
            for i in range(n, len(c)):
                if c[i] > a:
                    break
                dfs(a - c[i], l + [c[i]], i)
        c = sorted(candidates)        
        dfs(target, [], 0)
        return self.res         

Answer

class Solution(object):
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        def dfs(remain, combo, index):
            if remain == 0:
                result.append(combo)
                return
            for i in range(index, len(candy)):
                if candy[i] > remain:
                    # exceeded the sum with candidate[i]
                    break #the for loop

                dfs(remain - candy[i], combo + [candy[i]], i)

        candy = sorted(candidates)
        result = []
        dfs(target, [], 0)
        return result

Subsets

subject

Given a set of distinct integers, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,3], a solution is:

[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]

Thoughts and Solutions

Double cycle, modify the second cycle length?

class Solution(object):
    def __init__(self):
        self.res=[]
    def subsets(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """

        def dfs(l,n):#L, N length
            self.res.append(l)
            if n == len(nums)-1:
                return
            for i in range(n+1,len(nums)):
                dfs(l+[nums[i]],i)
        dfs([],-1)
        return self.res
#[[],[1],[1,2],[1,2,3],[1,3],[2],[2,3],[3]]

A little bit similar to the previous question
8%, wipe 76ms

Answer

def subsets(self, S):#56ms
    if not S:
        return [[]]
    else:
        S.sort()
        pre_subsets = self.subsets(S[1:])
        #print pre_subsets,S
        #print pre_subsets + [[S[0]]+elem for elem in pre_subsets]
        return pre_subsets + [[S[0]]+elem for elem in pre_subsets]

#[[],[3],[2],[2,3],[1],[1,3],[1,2],[1,2,3]]
'''
[[]] [3]
[[], [3]]
[[], [3]] [2, 3]
[[], [3], [2], [2, 3]]
[[], [3], [2], [2, 3]] [1, 2, 3]
[[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]
'''

I said I couldn't find the subsets function until I noticed that it was myself.
Mine is from the back, and this is from the back to the front.

def subsets(self, nums):#49ms can only guess a rough idea
    return reduce(lambda L, ele: L + [l + [ele] for l in L], nums, [[]])
#[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]

def subsets(self, nums):#52ms product function...
    [[x for x in l if x is not None] for l in itertools.product(*zip(nums, [None] * len(nums)))]
#[[1,2,3],[1,2],[1,3],[1],[2,3],[2],[3],[]]

def subsets(self, nums): #52ms combinations
    [l for n in range(len(nums) + 1) for l in itertools.combinations(nums, n)]
#[[],[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3]]
class Solution: #62ms
    def subsets(self, S):
        # Base result
        result = [[]]
        for num in S:
            #print num,result
            for element in result[:]:
                x=element[:]
                #print x,num
                x.append(num)
                result.append(x)
        return result

#[[],[1],[1,2],[1,2,3],[1,3],[2],[2,3],[3]]
'''
1 [[]]
[] 1
2 [[], [1]]
[] 2
[1] 2
3 [[], [1], [2], [1, 2]]
[] 3
[1] 3
[2] 3
[1, 2] 3
'''

Finally, I saw one in the same order as my output.

# DFS recursively 48ms
def subsets1(self, nums):
    res = []
    self.dfs(sorted(nums), 0, [], res)
    return res

def dfs(self, nums, index, path, res):
    res.append(path)
    for i in xrange(index, len(nums)):
        self.dfs(nums, i+1, path+[nums[i]], res)
#[[], [1], [1,2], [1,2,3], [1,3], [2], [2,3], [3]] another one, but so much faster than I am.
# Bit Manipulation    #46ms is a bit operation, that is fast
def subsets2(self, nums):
    res = []
    nums.sort()
    for i in xrange(1<<len(nums)):
        tmp = []
        for j in xrange(len(nums)):
            if i & 1 << j:  # if i >> j & 1:
                tmp.append(nums[j])
        res.append(tmp)
    return res
#[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] 

# Iteratively #52ms
def subsets(self, nums):
    res = [[]]
    for num in sorted(nums):
        res += [item+[num] for item in res]
    return res
#[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
#It looks like a simplified version of the one above.

What else can I do, how can I ____________ .

Word Ladder II

This is hard. Looking at the question, it seems that you can do it with dfs, but it's estimated that it will be rather slow. Let's do the medium difficulty first.

Binary Tree Level Order Traversal

subject

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:
Given binary tree [3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7
return its level order traversal as:
[
  [3],
  [9,20],
  [15,7]
]

Thoughts and Solutions

dfs should be able to do, as long as the number of tree layers in dfs can be added, but how to determine the total number of tree layers to determine the length of the initial List, should not be able to
But it seems that bfs is better.

# 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.res=[]
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        def dfs(tree,n):
            if tree.left or tree.right:
                if len(self.res) < n+1:
                    self.res += [[]]
                if tree.left:
                    self.res[n] += [tree.left.val]
                    dfs(tree.left,n+1)
                if tree.right:
                    self.res[n] += [tree.right.val]
                    dfs(tree.right,n+1)
        if root:  
            self.res += [[root.val]]
            dfs(root,1)
        return self.res

Still use dfs, 42ms, 90%, oh oh oh

Answer

#Solution 1, (6 lines)
def levelOrder(self, root):
    ans, level = [], [root]
    while root and level:
        ans.append([node.val for node in level])
        LRpair = [(node.left, node.right) for node in level]
        level = [leaf for LR in LRpair for leaf in LR if leaf]
    return ans

#Solution 2, (5 lines), same idea but use only one list comprehension in while loop to get the next level
def levelOrder(self, root):
    ans, level = [], [root]
    while root and level:
        ans.append([node.val for node in level])            
        level = [kid for n in level for kid in (n.left, n.right) if kid]
    return ans

#Solution 3 (10 lines), just an expansion of solution 1&2 for better understanding.
def levelOrder(self, root):
    if not root:
        return []
    ans, level = [], [root]
    while level:
        ans.append([node.val for node in level])
        temp = []
        for node in level:
            temp.extend([node.left, node.right])
        level = [leaf for leaf in temp if leaf]
    return ans

bfs should be written like this

Keywords: Lambda IE

Added by FastLaneHosting on Tue, 04 Jun 2019 00:45:26 +0300