创新互联制作网站网页找三站合一网站制作公司,专注于网页设计,网站制作、成都网站制作,网站设计,企业网站搭建,网站开发,建网站业务,680元做网站,已为近1000家服务,创新互联网站建设将一如既往的为我们的客户提供最优质的网站建设、网络营销推广服务!>#对于迭代器,产生的是对象临时副本,不能修改对象。
for i in lists:
change(i)
#在循环中修改迭代器迭代对象的地址,需要在while循环中重新迭代,不能继续在原有循环中
while list:
next=[]
for i in list:
do some thing
next.append(i)
list=next
is 使用id 判断,==使用value判断,少用is
http://www.toptal.com/python#hiring-guide
range(x),x不能取到,写代码时一定记住,range(len(s))刚好可以,因为下标减一
Python 负数取模运算
http://stackoverflow.com/questions/12946116/twos-complement-binary-in-python
https://leetcode.com/problems/single-number-ii/
class Solution:
# @param A, a list of integer
# @return an integerdef singleNumber(self, A):
ans= 0
for i in xrange(0,32):
count= 0
for a in A:
if ((a >> i) & 1):
count+=1
ans|= ((count%3) << i)
return self.convert(ans)
def convert(self,x):
if x >= 2**31:
x-= 2**32
return x
https://www.hackerrank.com/challenges/flipping-bits/editorial
python 按位取反 使用string replace
检查32位是否溢出
if res>= (1<<32)-1:
return 0
//python 在函数参数中传递引用时,函数中的修改不会改变这个引用在函数作用域以外的值.
https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/
class Solution {
public:
TreeNode*sortedListToBST(ListNode *head) {
int count = 0;
for (auto cur = head; cur;) {
cur= cur->next;
++count;
}
return helper(head, count);
}
private:
TreeNode*helper(ListNode *&p, int n) {
if (!n) return NULL;
auto left= helper(p, n / 2);
auto res= new TreeNode(p->val);
p= p->next;
res->left = left;
res->right = helper(p, n - n / 2 - 1);
return res;
}
};
# not right, p changed in c++ while head not changed in pythonclass Solution:
def f(self,head,num):
if num<=0:
return None
left=self.f(head,num/2)
res=TreeNode(head.val)
head=head.next
res.left,res.right=left,self.f(head,num-num/2-1)
return res
# @param {ListNode} head # @return {TreeNode} def sortedListToBST(self, head):
tmp,num=head,0
while tmp:
tmp=tmp.next
num+=1
return self.f(head,num)
#can be solved with a global variable
class Solution:
def f(self,l,r):
if l>r:
return None
m=(l+r)/2
left=self.f(l,m-1)
a=TreeNode(self.start.val)
self.start=self.start.next
right=self.f(m+1,r)
a.left,a.right=left,right
return a
# @param {ListNode} head # @return {TreeNode} def sortedListToBST(self, head):
if head is None:
return None
self.start=head
tmp,count=head,0
while tmp:
count+=1
tmp=tmp.next
return self.f(0,count-1)
enumerate, start means start from the wanted idx
a = [1, 2, 3]
>>> for idx, item in enumerate(a, start=2):
... print idx, item
...
2 13 24 3
better to do this
>>> for idx, item in enumerate(a[1:], start=2):
... print idx, item
...
2 2
3 3
maxlen= reduce(max, map(len, dict), 0)
网站标题:pythonpitfall-创新互联
链接URL:
http://chengdu.cdxwcx.cn/article/dpdjoj.html