0
点赞
收藏
分享

微信扫一扫

【DataWhale】14dayPythonTask1


Task1

  • ​​比较运算符​​
  • ​​运算符的优先级​​
  • ​​保留指定的小数位数​​
  • ​​布尔型​​
  • ​​获取类型信息​​
  • ​​输出print()​​
  • ​​位运算​​
  • ​​练习题​​

比较运算符

  • is, is not 比较的是两个变量的内存地址
  • ==,!=比较的是两个变量的值

比较两个地址不可变类型的变量(str),a和b变量的地址是一样的,如下

a="hello"
b="hello"
print(a is b,a==b) # True True
print(a is not b,a!=b) # False False

比较两个地址可变类型的变量(list,dict,tuple等),a和b变量的地址就不一样了,如下

a = ["hello"]
b = ["hello"]
print(a is b, a == b) # False True
print(a is not b, a != b) # True False

运算符的优先级

  • 一元运算符优于二元运算符。例如​​3 ** -2​​​等价于​​3 ** (-2)​​。
  • 先算术运算,后移位运算,最后位运算。例如 ​​1 << 3 + 2 & 7​​​等价于 ​​(1 << (3 + 2)) & 7​​。
  • 逻辑运算最后结合。例如​​3 < 4 and 4 < 5​​​等价于​​(3 < 4) and (4 < 5)​​。

保留指定的小数位数

有时候我们想保留浮点型的小数点后 ​​n​​​ 位。可以用 ​​decimal​​​ 包里的 ​​Decimal​​​ 对象和 ​​getcontext()​​ 方法来实现。默认是28位

import decimal
from decimal import Decimal
decimal.getcontext().prec = 4
c = Decimal(1) / Decimal(3)
print(c)

# 0.3333

布尔型

  • 对于数值变量,0或者0.0位FALSE,其余的为True
  • 对于容器变量,只要容器内有元素,无论大小和数量,都是True

获取类型信息

  • ​type(object)​​ 获取类型信息,不会考虑继承关系。
  • ​isinstance(object, classinfo)​​ 判断一个对象是否是一个已知的类型,考虑继承关系。

输出print()

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

默认的结束符号为换行符。

可以修改end参数:

shoplist = ['apple', 'mango', 'carrot', 'banana']
print("This is printed with 'end='&''.")
for item in shoplist:
print(item, end='&')
print('hello world')

# This is printed with 'end='&''.
# apple&mango&carrot&banana&hello world

可以修改sep参数分割两个字符串:

shoplist = ['apple', 'mango', 'carrot', 'banana']
print("This is printed with 'sep='&''.")
for item in shoplist:
print(item, 'another string', sep='&')

# This is printed with 'sep='&''.
# apple&another string
# mango&another string
# carrot&another string
# banana&another string

位运算

n << 1 -> 计算 n*2
n >> 1 -> 计算 n/2,负奇数的运算不可用
n << m -> 计算 n*(2^m),即乘以 2 的 m 次方
n >> m -> 计算 n/(2^m),即除以 2 的 m 次方
1 << n -> 2^n

练习题

leetcode 习题 136. 只出现一次的数字

给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。

尝试使用位运算解决此题。

Hints: 使用异或的性质(交换律,n ^ 0 =n, n ^ n=0),对每一个数异或

class Solution():
def singleNumber(self,nums):
a=0
for i in nums:
a^=i
return a

nums=[1,2,2,1,3,5,5]
s=Solution()
r=s.singleNumber(nums)
print(r)

参考:​​Leetcode—— 136.只出现一次的数字​​


举报

相关推荐

0 条评论