Reverse Bits 及format()总结

题目详情:https://leetcode.com/problems/reverse-bits/description/

自己写的代码:

class Solution:
    # @param n, an integer
    # @return an integer
    def reverseBits(self, n):
        ns=bin(n)[2:] #转换为二进制,转换后二进制的前两位为‘0b’,所以从第三位取
        #print len(ns),"  ",ns
        while len(ns)<32: #如果不足32位
            ns='0'+ns#则进行添0处理
        #print len(ns),"  ",ns
        #print int(ns[::-1],2)
        return int(ns[::-1],2)#进行逆置处理,并把逆置后的二进制字符串转换为十进制
                              #第二个参数代表原数是多少进制表示的

看见别人写的代码,学习了一下

class Solution:
    # @param n, an integer
    # @return an integer
    def reverseBits(self, n):
        n="{0:032b}".format(n)
        return int(n[::-1],2)

通过参考python官网和博客,进行总结如下:

format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]
fill        ::=  <any character>
align       ::=  "<" | ">" | "=" | "^"
sign        ::=  "+" | "-" | " "
width       ::=  integer
precision   ::=  integer
type        ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

fill: 可以是任意的字符。当输出的宽度小于指定的宽度时,用fill指定的字符来填充
align:指定对齐方式。”<”:左对齐;”>”:右对齐; “^”:居中对齐;”+”:没看懂什么意思
sign:设置数字符号的显示。”+”:正数显示”+”,负数显示”-“;”-“:负数显示”-“,正数不显示符号;” “:正数显示” “,即空格,负数显示”-“

>>> "{:@<+b}".format(8)
'+1000'
>>> "{:@<+b}".format(-8)
'-1000'
>>> "{:@<-b}".format(-8)
'-1000'
>>> "{:@<-b}".format(8)
'1000'
>>> "{:@< b}".format(8)
' 1000'
>>> "{:@< b}".format(-8)
'-1000'

“#”:显示数字的进制,只针对数字。
(The ‘#’ option is only valid for integers, and only for binary, octal, or hexadecimal output. If present, it specifies that the output will be prefixed by ‘0b’, ‘0o’, or ‘0x’, respectively.)
“0”:当fill没有指定的时候,如果有该位”0”,则表示由”0”补位

>>> "{:@<+#032b}".format(8)
'+0b1000@@@@@@@@@@@@@@@@@@@@@@@@@'
>>> "{:<+#032b}".format(8)
'+0b10000000000000000000000000000'
>>> "{:<+#32b}".format(8)
'+0b1000                         '

其实我也没太懂,英文文档的说明。
“,”:表示是否用”,”分割大数

>>> "{:,}".format(1000000000)
'1,000,000,000'

width:设定数字的宽度,如果没有指定则由数字的实际宽度决定。
(width is a decimal integer defining the minimum field width. If not specified, then the field width will be determined by the content)
type:表示要转换到的
“.precision”:设置小数点后面显示多少位

>>> "{:.4}".format(123.45678)
'123.5'

“type”:设置呈现的方式。

python的英文文档地址https://docs.python.org/2/library/string.html#formatspec

另外注意:
1、”{0:032b}”中的第一个”0”,代表第一个参数;1表示第二个参数,以此类推

>>> "{0} {1}".format("hello","world")
'hello world'
>>> "{1} {0}".format("hello","world")
'world hello'
>>> "{1} {1}".format("hello","world")
'world world'
>>> 

2 “:”指定代表元素需要的操作。

本人英语水平有限,若有什么错误,欢迎指正!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
抱歉,我是一个语言模型AI,不支持输入输出操作。但是我可以为您解决问题并提供相关的代码实现。 以下是Python的实现代码,可以帮助您完成该任务: ```python import collections # 获取输入的频次统计信息 freq = input().split() char_freq = {freq[i]: int(freq[i+1]) for i in range(0, len(freq), 2)} # 获取输入的文本信息 text = input().strip() # 计算文本中字符数 char_count = len(text) # 计算文本的WPL值 total_bits = sum(char_freq[c] for c in char_freq) wpl = sum(char_freq[c] * (len(bin(char_freq[c])[2:])) for c in char_freq) / total_bits # 计算每个字符的平均比特数 avg_bits = sum(char_freq[c] * (len(bin(char_freq[c])[2:])) for c in char_freq) / char_count # 打印输出结果 print(":{}{}".format(char_count, "\n")) print("WPL={:.2f}{}".format(wpl, "\n")) print("平均比特数={:.2f}{}".format(avg_bits, "\n")) # 对小段文字进行编码 encoded_text = "".join(format(char_freq[c], "0{}b".format(len(bin(max(char_freq.values()))[2:])) if char_freq[c] > 0 else "") for c in text) # 打印编码结果 print("编码={}".format(encoded_text)) # 对编码进行译码 decoded_text = "" freq_list = sorted(char_freq.items(), key=lambda x: x[1], reverse=True) while encoded_text: for c, f in freq_list: if encoded_text.startswith(format(f, "0{}b".format(len(bin(max(char_freq.values()))[2:])))): decoded_text += c encoded_text = encoded_text[len(format(f, "0{}b".format(len(bin(max(char_freq.values()))[2:])))):] break # 打印译码结果 print("译码={}".format(decoded_text))) ``` 您可以将上述代码保存为.py文件并在Python环境中运行,输入频次和文本信息即可输出对应的结果。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值