Zhuanli&Blog


  • 首页

  • 标签

  • 分类

  • 归档

python2和python3的字符编码问题

发表于 2018-06-08 | 分类于 python

Python2和Python3在字符串编码上是有明显的区别。

在Python2中,字符串无法完全地支持国际字符集和Unicode编码。为了解决这种限制,Python2对Unicode数据使用了单独的字符串类型。要输入Unicode字符串字面量,要在第一个引号前加上’u’。Python2中普通字符串实际上就是已经编码(非Unicode)的字节字符串。

在Python3中,不必加入这个前缀字符,否则是语法错误,这是因为所有的字符串默认已经是Unicode编码了。

python2实例:

>>> ‘张三’ #python2 会自动将字符串转换为合适编码的字节字符串
‘\xe5\xbc\xa0\xe4\xbf\x8a’ #自动转换为utf-8编码的字节字符串

>>> u’张三’ #显式指定字符串类型为unicode类型, 此类型字符串没有编码,保存的是字符在unicode字符集中的代码序号
u’\u5f20\u4fca’

>>> ‘张三’.encode(‘utf-8’) #python2 已经自动将其转化为utf-8类型编码,因此再次编码(python2会将该字符串当作用ascii或unicode编码过)会出现错误。
Traceback (most recent call last):
File ““, line 1, in
UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xe5 in position 0: ordinal not in range(128)

>>> ‘张三’.decode(‘utf-8’) #python2 可以正常解码,返回的字符串类是无编码的unicode类型
u’\u5f20\u4fca’

>>> b’张三’ # ‘张三’ 已被python2转换为utf-8编码,因此已为字节字符串
‘\xe5\xbc\xa0\xe4\xbf\x8a’

>>> print ‘张三’
张三

>>> print u’张三’
张三

>>> print b’张三’
张三

python3实例:

>>> ‘张三’ #python3的字符串默认为unicode格式(无编码)
‘张三’

>>> u’张三’ #由于默认为unicode格式,因此字符串不用像python2一样显式地指出其类型,否则是语法错误。
File ““, line 1
u’张三’
^
SyntaxError: invalid syntax

>>> type(‘张三’) #python3中文本字符串和字节字符串是严格区分的,默认为unicode格式的文本字符串

>>> ‘张三’.decode(‘utf-8’) #因为默认的文本字符串为unicode格式,因此文本字符串没有decode方法
Traceback (most recent call last):
File ““, line 1, in
AttributeError: ‘str’ object has no attribute ‘decode’

>>> ‘张三’.encode(‘utf-8’) #将文本字符串编码,转换为已编码的字节字符串类型
b’\xe5\xbc\xa0\xe4\xbf\x8a’

>>> type(‘张三’.encode(‘utf-8’))

>>> print (‘张三’.encode(‘utf-8’)) #对于已编码的字节字符串,文本字符串的许多特性和方法已经不能使用。
b’\xe5\xbc\xa0\xe4\xbf\x8a’

>>>print (‘张三’.encode(‘utf-8’))
b’\xe5\xbc\xa0\xe4\xbf\x8a’

>>> print (‘张三’.encode(‘utf-8’).decode(‘utf-8’)) #必须将字节字符串解码后才能打印出来
张三

leetcode 375. Guess Number Higher or Lower II

发表于 2018-06-08 | 分类于 leetcode

We are playing the Guess Game. The game is as follows:

I pick a number from 1 to n. You have to guess which number I picked.

Every time you guess wrong, I’ll tell you whether the number I picked is higher or lower.

However, when you guess a particular number x, and you guess wrong, you pay $x. You win the game when you guess the number I picked.

Example:


n = 10, I pick 8.

First round: You guess 5, I tell you that it’s higher. You pay $5.
Second round: You guess 7, I tell you that it’s higher. You pay $7.
Third round: You guess 9, I tell you that it’s lower. You pay $9.

Game over. 8 is the number I picked.

You end up paying $5 + $7 + $9 = $21.

Given a particular n ≥ 1, find out how much money you need to have to guarantee a win.

  • dfs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution(object):
def getMoneyAmount(self, n):
"""
:type n: int
:rtype: int
:dfs
"""
#dp[i][j] = x + max(dp[i][x-1],dp[x+1][j])
def dfs(dp,left,right):
if left >= right:return 0
if dp[left][right]: return dp[left][right]
ans = float("inf")
for i in range(left,right+1):
ans = min(ans,i+max(dfs(dp,left,i-1),dfs(dp,i+1,right)))
dp[left][right] = ans
return ans

dp = [[0 for i in range(n+1)] for j in range(n+1) ]
dfs(dp,1,n)
return dp[1][n]
  • dp
1
2
3
4
5
6
7
8
9
10
def getMoneyAmountDP(self, n):
dp = [[0] * (n+1) for _ in xrange(n+1)]
for l in xrange(2, n+1):
for i in xrange(1, n-l+2):
min_cost = float('inf')
j = i + l - 1
for p in xrange(i, j):
res = p + max(dp[i][p-1], dp[p+1][j])
min_cost = min(min_cost, res)
dp[i][j] = min_cost

leetcode 373. Find K Pairs with Smallest Sums

发表于 2018-06-07 | 分类于 leetcode

You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k.

Define a pair (u,v) which consists of one element from the first array and one element from the second array.

Find the k pairs (u1,v1),(u2,v2) …(uk,vk) with the smallest sums.

Example 1:


Given nums1 = [1,7,11], nums2 = [2,4,6], k = 3

Return: [1,2],[1,4],[1,6]

The first 3 pairs are returned from the sequence:
[1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]

Example 2:


Given nums1 = [1,1,2], nums2 = [1,2,3], k = 2

Return: [1,1],[1,1]

The first 2 pairs are returned from the sequence:
[1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]

Example 3:


Given nums1 = [1,2], nums2 = [3], k = 3

Return: [1,3],[2,3]

All possible pairs are returned from the sequence:
[1,3],[2,3]

  • mysolution the limit exceeded
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution(object):
def kSmallestPairs(self, nums1, nums2, k):
"""
:type nums1: List[int]
:type nums2: List[int]
:type k: int
:rtype: List[List[int]]
"""
tmp = []
if not nums1 or not nums2:
return []
for i in nums1:
for j in nums2:
tmp.append([i+j,i,j])
tmp = sorted(tmp,key=lambda x:x[0])
out = []
for l in tmp:
out.append(l[1:])
if k > len(out):return out
return out[:k]
  • a o(k*logk) solution
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
from heapq import *
class Solution:
def kSmallestPairs(self, nums1, nums2, k):
"""
:type nums1: List[int]
:type nums2: List[int]
:type k: int
:rtype: List[List[int]]
"""
if not nums1 or not nums2:
return []

heap = [(nums1[0] + nums2[0], 0, 0)]
visited = set()
output = []

while len(output) < k and heap:
val = heappop(heap)
output.append([nums1[val[1]], nums2[val[2]]])

if val[1] < len(nums1) - 1 and (val[1]+1, val[2]) not in visited:
visited.add((val[1]+1, val[2]))
heappush(heap, (nums1[val[1] + 1] + nums2[val[2]], val[1] + 1, val[2]))
if val[2] < len(nums2) - 1 and (val[1], val[2] + 1) not in visited:
visited.add((val[1], val[2] + 1))
heappush(heap, (nums1[val[1]] + nums2[val[2] + 1], val[1], val[2] + 1))

return output

git操作速查表

发表于 2018-06-07 | 分类于 tools

git速查表

leetcode 378. Kth Smallest Element in a Sorted Matrix

发表于 2018-06-06 | 分类于 leetcode

Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.

Note that it is the kth smallest element in the sorted order, not the kth distinct element.

Example:


matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
],
k = 8,

return 13.

Note:
You may assume k is always valid, 1 ≤ k ≤ n2.

  • simple solution
1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
def kthSmallest(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
slist = []
for row in matrix:
slist.extend(row)
slist.sort()
return slist[k-1]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#binary search
class Solution:
def kthSmallest(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
m, n = len(matrix), len(matrix[0])
left, right = matrix[0][0], matrix[m-1][n-1]
while left < right:
mid = left+(right-left)//2
cnt = 0
j = n-1
for i in range(m):
while j >= 0 and matrix[i][j] > mid:
j -= 1
cnt += (j+1)
if cnt < k: left = mid+1
else: right = mid
return left

leetcode 381. Insert Delete GetRandom O(1) - Duplicates allowed

发表于 2018-06-05 | 分类于 leetcode

Design a data structure that supports all following operations in average O(1) time.

Note: Duplicate elements are allowed.

  1. insert(val): Inserts an item val to the collection.
  2. remove(val): Removes an item val from the collection if present.
  3. getRandom: Returns a random element from current collection of elements. The probability of each element being returned is linearly related to the number of same value the collection contains.

Example:


// Init an empty collection.
RandomizedCollection collection = new RandomizedCollection();

// Inserts 1 to the collection. Returns true as the collection did not contain 1.
collection.insert(1);

// Inserts another 1 to the collection. Returns false as the collection contained 1. Collection now contains [1,1].
collection.insert(1);

// Inserts 2 to the collection, returns true. Collection now contains [1,1,2].
collection.insert(2);

// getRandom should return 1 with the probability 2/3, and returns 2 with the probability 1/3.
collection.getRandom();

// Removes 1 from the collection, returns true. Collection now contains [1,2].
collection.remove(1);

// getRandom should return 1 and 2 both equally likely.
collection.getRandom();

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
import collections
class RandomizedCollection:

def __init__(self):
"""
Initialize your data structure here.
"""
self.nums = []
self.dic = collections.defaultdict(set)

def insert(self, val):
"""
Inserts a value to the collection. Returns true if the collection did not already contain the specified element.
:type val: int
:rtype: bool
"""
self.nums.append(val)
self.dic[val].add(len(self.nums) - 1)
return len(self.dic[val]) == 1

def remove(self, val):
"""
Removes a value from the collection. Returns true if the collection contained the specified element.
:type val: int
:rtype: bool
"""
if self.dic[val]:
rmindex,lastval = self.dic[val].pop(),self.nums[-1]
self.nums[rmindex] = lastval
self.dic[lastval].add(rmindex)
self.dic[lastval].discard(len(self.nums)-1)
self.nums.pop()
return True
return False


def getRandom(self):
"""
Get a random element from the collection.
:rtype: int
"""
import random
return random.choice(self.nums)



# Your RandomizedCollection object will be instantiated and called as such:
# obj = RandomizedCollection()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()

leetcode 380. Insert Delete GetRandom O(1)

发表于 2018-06-05 | 分类于 leetcode

Design a data structure that supports all following operations in average O(1) time.

  1. insert(val): Inserts an item val to the set if not already present.
  2. remove(val): Removes an item val from the set if present.
  3. getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.

Example:


// Init an empty set.
RandomizedSet randomSet = new RandomizedSet();

// Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomSet.insert(1);

// Returns false as 2 does not exist in the set.
randomSet.remove(2);

// Inserts 2 to the set, returns true. Set now contains [1,2].
randomSet.insert(2);

// getRandom should return either 1 or 2 randomly.
randomSet.getRandom();

// Removes 1 from the set, returns true. Set now contains [2].
randomSet.remove(1);

// 2 was already in the set, so return false.
randomSet.insert(2);

// Since 2 is the only number in the set, getRandom always return 2.
randomSet.getRandom();

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
class RandomizedSet:

def __init__(self):
"""
Initialize your data structure here.
"""
self.nums = []
self.dic = {}

def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
:type val: int
:rtype: bool
"""
if val not in self.dic:
self.nums.append(val)
self.dic[val] = len(self.nums) - 1
return True
return False

def remove(self, val):
"""
Removes a value from the set. Returns true if the set contained the specified element.
:type val: int
:rtype: bool
"""
if val in self.dic:
rmindex,lastval = self.dic[val],self.nums[-1]
self.nums[rmindex],self.dic[lastval] = lastval,rmindex
self.nums.pop()
self.dic.pop(val)
return True
return False

def getRandom(self):
"""
Get a random element from the set.
:rtype: int
"""
import random
return random.choice(self.nums)


# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()

leetcode 382. Linked List Random Node

发表于 2018-06-04 | 分类于 leetcode

Given a singly linked list, return a random node’s value from the linked list. Each node must have the same probability of being chosen.

Follow up:
What if the linked list is extremely large and its length is unknown to you? Could you solve this efficiently without using extra space?

Example:


// Init a singly linked list [1,2,3].
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
Solution solution = new Solution(head);

// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
solution.getRandom();

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
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution(object):

def __init__(self, head):
"""
@param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node.
:type head: ListNode
"""
self.xlist = []
node = head
while node:
self.xlist.append(node.val)
if node.next:
node = node.next
else:break

def getRandom(self):
"""
Returns a random node's value.
:rtype: int
"""
import random
return self.xlist[random.randint(0,len(self.xlist)-1)]



# Your Solution object will be instantiated and called as such:
# obj = Solution(head)
# param_1 = obj.getRandom()

leetcode 384. Shuffle an Array

发表于 2018-06-04 | 分类于 leetcode

Shuffle a set of numbers without duplicates.

Example:


// Init an array with set 1, 2, and 3.
int[] nums = {1,2,3};
Solution solution = new Solution(nums);

// Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned.
solution.shuffle();

// Resets the array back to its original configuration [1,2,3].
solution.reset();

// Returns the random shuffling of array [1,2,3].
solution.shuffle();

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
class Solution(object):

def __init__(self, nums):
"""
:type nums: List[int]
"""
self.nums = nums

def reset(self):
"""
Resets the array to its original configuration and return it.
:rtype: List[int]
"""
return self.nums

def shuffle(self):
"""
Returns a random shuffling of the array.
:rtype: List[int]
"""
from random import shuffle
from copy import deepcopy
nums = deepcopy(self.nums)
shuffle(nums)
return nums



# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.reset()
# param_2 = obj.shuffle()

leetcode 385. Mini Parser

发表于 2018-06-01 | 分类于 leetcode

Given a nested list of integers represented as a string, implement a parser to deserialize it.

Each element is either an integer, or a list – whose elements may also be integers or other lists.

Note:
You may assume that the string is well-formed:

  • String is non-empty.
  • String does not contain white spaces.
  • String contains only digits 0-9, [, - ,, ].

Example 1:

Given s = "324",

You should return a NestedInteger object which contains a single integer 324.

Example 2:

Given s = "[123,[456,[789]]]",

Return a NestedInteger object containing a nested list with 2 elements:

1. An integer containing value 123.
2. A nested list containing two elements:
    i.  An integer containing value 456.
    ii. A nested list with one element:
         a. An integer containing value 789.
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
class Solution(object):
def deserialize(self, s):
"""
:type s: str
:rtype: NestedInteger
"""

if s[0]!='[': return NestedInteger(int(s))

stack=[NestedInteger()]
num=''
for i in s:
if i=='[':
stack.append(NestedInteger())
elif i==']':
if num:
stack[-1].add(int(num))
num=''
buf=stack.pop()
stack[-1].add(buf)
elif i==',':
if num:
stack[-1].add(int(num))
num=''
else:
num+=i

return stack[0].getList()[0]
1…131415…20

zhuanli

194 日志
9 分类
41 标签
GitHub
© 2018 — 2019 zhuanli
由 Hexo 强力驱动
|
主题 — NexT.Pisces v5.1.4