zzp's blog


  • 首页

  • 分类

  • 归档

  • 搜索

search for a range

发表于 2018-04-20 | 分类于 algorithm , leetcode | 阅读次数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"""
https://leetcode.com/problems/search-for-a-range/description/
"""

class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
>>> s = Solution()
>>> s.searchRange([5, 7, 7, 8, 8, 10], 8)
[3, 4]
>>> s.searchRange([5, 7, 7, 8, 8, 10], 6)
[-1, -1]
>>> s.searchRange([], 0)
[-1, -1]
>>> s.searchRange([1], 1)
[0, 0]
>>> s.searchRange([1, 3], 1)
[0, 0]
>>> s.searchRange([1, 4], 4)
[1, 1]
>>> s.searchRange([2, 2], 2)
[0, 1]
"""
start = 0
end = len(nums)
if end == 0:
return [-1, -1]
ex = -1
while True:
if end - start == 1:
if nums[start] == target:
ex = start
break
mid_ind = (start+end)//2
mid = nums[mid_ind]
if mid > target:
end = mid_ind
elif mid < target:
start = mid_ind
else:
ex = mid_ind
break
# cannot find target in nums.
if ex == -1:
return [-1, -1]

start = ex
end = ex

# extend to the end.
for idx in range(ex+1, len(nums)):
if nums[idx] == target:
end = idx
else:
break
# extend to the start.
for idx in range(ex-1, -1, -1):
if nums[idx] == target:
start = idx
else:
break

return [start, end]

string to integer / atoi

发表于 2018-04-20 | 分类于 algorithm , leetcode | 阅读次数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
"""
https://leetcode.com/problems/string-to-integer-atoi/description/
"""


class Solution(object):
def myAtoi(self, st):
"""
:type str: str
:rtype: int
>>> s = Solution()
>>> s.myAtoi("42")
42
>>> s.myAtoi(" -42")
-42
>>> s.myAtoi("4193 with words")
4193
>>> s.myAtoi("words and 987")
0
>>> s.myAtoi("-91283472332")
-2147483648
>>> s.myAtoi(" -12-45")
-12
>>> s.myAtoi("-")
0
>>> s.myAtoi("- 1")
0
>>> s.myAtoi("- 1")
0
>>> s.myAtoi("- -1")
0
>>> s.myAtoi("+1")
1
>>> s.myAtoi("123 456")
123
"""
INT_MAX = 2**31 - 1
INT_MIN = -2**31
start, end = -1, -1
if st == "":
return 0
for idx, i in enumerate(st):
if i == " ":
if start != -1:
end = idx
break
elif i in set({"-", "+"}):
if start == -1:
start = idx
else:
end = idx
break

elif i in set({"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}):
if start == -1:
start = idx
else:
if start == -1:
return 0
else:
end = idx
break
try:
if end == -1:
value = int(st[start:])
else:
value = int(st[start:end])
except ValueError:
return 0
if value > INT_MAX:
return INT_MAX
if value < INT_MIN:
return INT_MIN
return value

def myAtoi2(self, st):
"""
:type str: str
:rtype: int
"""
import re
st = st.strip()
try:
res = re.search('(^[\+\-]?\d+)', st).group()
res = int(res)
res = res if res <= 2147483647 else 2147483647
res = res if res >= -2147483648 else -2147483648
except:
res = 0
return res

powx-n

发表于 2018-04-13 | 分类于 algorithm , leetcode | 阅读次数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
>>> s = Solution()
>>> s.myPow(2.00000, 10)
1024.00000
>>> s.myPow(2.10000, 3)
9.26100
"""
# change n to position, check whether x is 1 or -1
if n == 0:
return 1
elif n > 0:
pass
else:
n = -n
x = 1 / x
if x == 1:
return 1
if x == -1:
return 1 if n % 2 == 0 else -1
return self.pow(x, n)

def pow(self, x, n):
# n is positive
if n == 0:
return 1
if n == 1:
return x
if n % 2 == 0:
return self.pow(x, n/2)**2
else:
return x*self.pow(x, n/2)**2


if __name__ == '__main__':
s = Solution()
print(s.myPow(0.000001, 2111121))

reverse integer

发表于 2018-04-13 | 分类于 algorithm , leetcode | 阅读次数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"""
https://leetcode.com/problems/reverse-integer/description/
"""

class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
>>> s = Solution()
>>> s.reverse(123)
321
>>> s.reverse(0)
0
>>> s.reverse(-123)
-321
>>> s.reverse(2**31)
0
>>> s.reverse(1563847412)
0
"""
if x == 0:
return x
if x < 0:
sig = -1
else:
sig = 1
s = int((str(abs(x))[::-1]))
if sig < 0:
if s > 2**31:
return 0
else:
if s > 2**31 - 1:
return 0
if sig == -1:
s = -s
return s


def test():
s = Solution()
s.reverse(123)
s.reverse(0)
s.reverse(-123)
s.reverse(2**31)
s.reverse(1563847412)


if __name__ == '__main__':
import timeit
print(timeit.timeit("test()", number=100000, setup="from __main__ import test"))

longest substring without repeating characters

发表于 2018-04-12 | 分类于 algorithm , leetcode | 阅读次数

“””
https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/description/
无重复字符的最长子串
“””

class Solution(object):
def lengthOfLongestSubstring(self, s):
“””
:type s: str
:rtype: int
>>> s = Solution()
>>> s.lengthOfLongestSubstring(“aab”)
2
>>> s.lengthOfLongestSubstring(“dvdf”)
3
>>> s.lengthOfLongestSubstring(“abcabcbb”)
3
>>> s.lengthOfLongestSubstring(“abcabcbb”)
3
>>> s.lengthOfLongestSubstring(“abba”)
2
>>> s.lengthOfLongestSubstring(“aaaaaaa”)
1
>>> s.lengthOfLongestSubstring(“a”)
1
>>> s.lengthOfLongestSubstring(“”)
0
“””
if s == “”:
return 0
if len(s) == 1:
return 1

# 记录字符到index的映射
dic = {}
L, start_ind = 0, 0
for idx, i in enumerate(s):
    # 第idx个字符在dic中且是超过start_ind的字符
    if i in dic and start_ind <= dic[i]:
        L = max(idx - start_ind, L)
        start_ind = dic[i] + 1
    dic[i] = idx
L = max(idx + 1 - start_ind, L)
return L

add two numbers

发表于 2018-04-12 | 分类于 algorithm , leetcode | 阅读次数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
"""
https://leetcode-cn.com/problems/add-two-numbers/description/

copy codes.
"""
class ListNode:
def __init__(self, x):
self.val = x
self.next = None


class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummy = ListNode(0)
current, carry = dummy, 0
while l1 or l2:
val = carry
if l1:
val += l1.val
l1 = l1.next
if l2:
val += l2.val
l2 = l2.next
carry, val = divmod(val, 10)
current.next = ListNode(val)
current = current.next
if carry == 1:
current.next = ListNode(1)
return dummy.next


if __name__ == '__main__':
a, a.next, a.next.next = ListNode(2), ListNode(4), ListNode(3)
b, b.next, b.next.next = ListNode(5), ListNode(6), ListNode(4)
result = Solution().addTwoNumbers(a, b)
print("{0} -> {1} -> {2}".format(result.val, result.next.val,
result.next.next.val))

two sum

发表于 2018-04-11 | 分类于 algorithm , leetcode | 阅读次数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
"""
https://leetcode-cn.com/problems/two-sum/description/
"""
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
>>> s = Solution()
>>> nums = [3, 2, 4]
>>> target = 6
>>> s.twoSum(nums, target)
[1, 2]
"""
# tmp = [target - i for i in nums]
# for idx, i in enumerate(tmp):
# try:
# idx2 = nums.index(i)
# if idx2 != idx:
# return [idx, idx2]
# except ValueError:
# pass

dic = {}
for idx, num in enumerate(nums):
if target - num in dic:
return [dic[target-num], idx]
dic[num] = idx

max sub-array problem

发表于 2018-04-10 | 分类于 algorithm , leetcode | 阅读次数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160

"""
MSP(max sub-array problem)
wiki(https://en.wikipedia.org/wiki/Maximum_subarray_problem).

1-D:
kadene's algorithm time complexity: O(n)
2-D:
~=O(n^3)
"""
import numpy as np
from itertools import combinations, accumulate


def msp_1D(A):
"""
1D array MSP.

Parameters
----------
A: list or np.ndarray

Returns
-------
max_so_far: max sum of subarraies.

>>> A = np.array([1, 2, 3, 0, -1, -2, 3, 4, 1, -2, 0])
>>> max_so_far = msp_1D(A)
>>> max_so_far == 11
True
"""
max_ending_here = max_so_far = 0
for x in A:
max_ending_here = max(0, max_ending_here + x)
max_so_far = max(max_so_far, max_ending_here)
return max_so_far


def msp_1D_with_index(A):
"""
solve 1D max sub-array problem.

Parameters
----------
A: list or np.ndarray

Returns
-------
start_ind: int
end_ind: int
max_so_far: max sum of subarraies.

That is to say:
>>> A = np.array([1, 2, 3, 0, -1, -2, 3, 4, 1, -2, 0])
>>> start_ind, end_ind, max_so_far = msp_1D_with_index(A)
>>> start_ind, end_ind, max_so_far
(0, 8, 11)
>>> sum(A[start_ind:end_ind+1]) == max_so_far
True
"""
start_ind, end_ind = 0, 0
max_ending_here, max_so_far = 0, 0
for idx, x in enumerate(A):
max_ending_here1 = max_ending_here + x
if max_ending_here1 > 0:
max_ending_here = max_ending_here1
else:
# start with this idx.
start_ind = idx + 1
max_ending_here = 0
if max_so_far < max_ending_here:
# end with this idx.
end_ind = idx
max_so_far = max_ending_here
return start_ind, end_ind, max_so_far


def msp_2D(A):
"""
2D array MSP.

Parameters
----------
A: np.ndarray

Returns
-------
start_ind: int
end_ind: int
max_so_far: max sum of subarraies.

Steps
-----
1. caculate acc matrix(accumulate of A).
2. for all indexes i, j pairs(i<j),
calculating sum of block for a k column(using acc matrix).
do 1-d MSP(get a max sum block under i, j)
3. return the max.

>>> A = np.array([\
[0, -2, -7, 0],\
[9, 2, -6, 2],\
[-4, 1, -4, 1],\
[-1, 8, 0, -2]])
>>> m = msp_2D(A)
>>> m == 15
True
"""
A = np.array(A)
acc = np.array([*accumulate(A)])
m = 0
for i, j in combinations(range(A.shape[0]), 2):
m_tmp = msp_1D([
acc[j, k] - acc[i - 1, k] if i != 0 else acc[j, k]
for k in range(A.shape[1])
])
if m_tmp > m:
m = m_tmp
return m


def msp_2D_with_index(A):
"""
2D array MSP.

Parameters
----------
A: np.ndarray

Returns
-------
start_ind: tuple
max sum block left-top position.
end_ind: tuple
max sum block right-bottom position.
max_so_far: max sum of subarraies.

That is to say:
>>> A = np.array([\
[0, -2, -7, 0],\
[9, 2, -6, 2],\
[-4, 1, -4, 1],\
[-1, 8, 0, -2]])
>>> start_ind, end_ind, m = msp_2D_with_index(A)
>>> A[start_ind[0]:end_ind[0]+1, start_ind[1]:end_ind[1]+1].sum() == m
True
"""
A = np.array(A)
acc = np.array([*accumulate(A)])
start_ind, end_ind, m = None, None, 0
for i, j in combinations(range(A.shape[0]), 2):
sind, eind, m_tmp = msp_1D_with_index([
acc[j, k] - acc[i - 1, k] if i != 0 else acc[j, k]
for k in range(A.shape[1])
])
if m_tmp > m:
m = m_tmp
start_ind = (i, sind)
end_ind = (j, eind)
return start_ind, end_ind, m

ubuntu桌面版屏保screensaver

发表于 2018-03-27 | 分类于 linux | 阅读次数
1
sudo apt-get install xscreensaver xscreensaver-gl-extra xscreensaver-data-extra
  • Atlantis
  • boxed
  • FadePlot
  • FlipFlop
  • GLMatrix
  • Grav
  • Juggler3D
  • Pacman
  • Rubik

锁屏进入屏保

1
xscreensaver-command -lock

或者自带的屏保gnome-screensaver

python: collections.ChainMap

发表于 2018-03-26 | 分类于 python | 阅读次数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# python3
import collections

# 初始化字典
dict1 = { 'a' : 1, 'b' : 2 }
dict2 = { 'b' : 3, 'c' : 4 }

# 初始化ChainMap
chain = collections.ChainMap(dict1, dict2)

# 使用maps输出chainMap
print(chain.maps) # [{'b': 2, 'a': 1}, {'b': 3, 'c': 4}]

# 输出key
print(list(chain.keys())) # ['b', 'c', 'a']

# 输出值
print(list(chain.values())) # [2, 4, 1]

# 访问
print(chain['b']) # 2
print(chain.get('b')) # 2

# 使用new_child添加新字典
dict3 = { 'f' : 5 }
new_chain = chain.new_child(dict3)
print (new_chain.maps) # [{'f': 5}, {'b': 2, 'a': 1}, {'b': 3, 'c': 4}]

new_chain.maps = reversed(new_chain.maps)
print(new_chain.maps)
1…456…9
ningning

ningning

86 日志
9 分类
GitHub
© 2018 - 2020 ningning
本站访客数 人次