python 变量的拷贝 copy

假设有如下代码:

A = 10
tmpA = A
print id(A),id(tmpA)
可以看到,id(A)与id(tmpA)相同。这意味着执行 tmpA = A的时候,电脑并未给A赋予一块新的地址,而是让tmpA指向A的存储地址。


可以通过下面的方法得到A的拷贝:

import copy
A = 10
tmpA = copy.copy(A)
print id(A),id(tmpA)
得到的A,tmpA的id不同。


下面用一个leetcode的例子说明拷贝的重要性。

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path 1->2->3 which represents the number 123.

Find the total sum of all root-to-leaf numbers.

For example,

    1
   / \
  2   3

The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.

Return the sum = 12 + 13 = 25.

统计所有结点的和,树的结点每向下一层,数值左移一位,最后求和。

代码:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
import copy
class Solution(object):
    def sumNumbers(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        return self.excute(root,0)
        
        
    def excute(self,root,Sum):
        tmpSum = copy.copy(Sum)  #这里必须用copy的方法,否则在不同的迭代周期中,Sum的值都有可能被改变。
        if not root.left and not root.right:
            return 10*tmpSum+root.val
        elif root.left and not root.right:
            return self.excute(root.left,10*tmpSum+root.val)
        elif root.right and not root.left:
            return self.excute(root.right,10*tmpSum+root.val)
        else:
            return self.excute(root.left,10*tmpSum+root.val)+self.excute(root.right,10*tmpSum+root.val)

另外,copy分为copy.copy() 和 copy.deepcopy(),具体不同请参考这篇 文章


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值