提问人:Jocke011 提问时间:1/17/2023 最后编辑:mozwayJocke011 更新时间:1/17/2023 访问量:39
了解 Python 序列
Understanding Python sequence
问:
我正在做一个名为 Flipping bits 的 hackerrank 示例,其中给出了一个 32 位无符号整数的列表。翻转所有位(1->0 和 0->1)并将结果作为无符号整数返回。 正确的代码是:
def flippingBits(n):
seq = format(n, '032b')
return int(''.join(['0' if bit == '1' else '1' for bit in seq]), 2)
我不明白最后一行,“”是什么意思。部分做?为什么最后有一个 ,2?
我已经理解了大部分代码,但在理解最后一部分时需要帮助。
答:
0赞
Guru Stron
1/17/2023
#1
''.部分做
''
表示一个空字符串,该字符串将用作分隔符以将集合元素联接到字符串中(可以在此处找到一些示例))
为什么最后有一个 ,2?
来自文档:int
class int(x=0) class int(x, base=10)
返回一个由数字或字符串 x 构造的整数对象
在这种情况下,它会将以二进制格式(即以 2 为基数)提供的字符串解析为 int。
0赞
abdou_dev
1/17/2023
#2
我希望下面的解释有所帮助:
def flippingBits(n):
seq = format(n, '032b') # change the format from base 10 to base 2 with 32bit size unsigned integer into string
return int(''.join(['0' if bit == '1' else '1' for bit in seq]), 2)
# ['0' if bit == '1' else '1' for bit in seq] => means: build a list of characters from "seq" string
# in which whenever there is 1 convert it to 0, and to 1 otherwise; then
# ''.join(char_list) => means: build string by joining characters in char_list
# without space between them ('' means empty delimiter); then
# int(num_string, 2) => convert num_string from string to integer in a base 2
请注意,您可以使用按位操作进行位翻转,而无需来回转换为字符串。
def flippingBits(n):
inverted_n = ~n # flip all bits from 0 to 1, and 1 to 0
return inverted_n+2**32 # because the number is a signed integer, the most significant bit should be flipped as well
评论
1赞
Serge Ballesta
1/17/2023
哎呀,因为 python 中整数的位大小默认为 32......你真的确定吗?在旧的 Python 2 版本中确实如此,但在当前的 Python3.x 版本中,整数类型是一种多精度类型,可以根据需要使用任意数量的位。无论如何,您的代码对于任何低于 2^32 的正整数都可以正常工作,这是 OP 所关心的。
0赞
abdou_dev
1/17/2023
感谢@SergeBallesta指出这一点。答案已得到纠正。
上一个:没有__iter__的序列?
下一个:两个相关序列
评论