以2的幂的和以升序打印数字 [英] Printing a number as a sum of powers of 2 in increasing order

查看:73
本文介绍了以2的幂的和以升序打印数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图打印出一个十进制整数(非负数)作为2的幂的和,即输入10,它应该打印不带引号的"2 8".我已经写了这段代码,但是有人可以给我一个衬里吗.

I am trying to print out a decimal integer(non-negative) as sum of powers of 2 i.e for input 10, it should print "2 8" without quotes. I already wrote this code, but can someone give me a one liner for this.

n = bin(int(raw_input()))[-1:1:-1]
print (' ').join([str((int(n[j])+1)**j) for j in xrange(len(n)) if n[j] == '1'])

推荐答案

最好将其分布在多个行中,并且在列表理解中使用和input会隐藏代码内容的关键信息做.

It much better to have this spread across muplitple lines, and using and input inside a list comprehension hides a key piece of the information of what your code is doing.

最终,您要执行的操作看起来并不漂亮,但无论如何,这是应该的:

Ultimately, what you are asking to doisn't pretty, but here it is anyway:

print (' ').join([str(2**i) for i,j in enumerate(bin(int(raw_input()))[-1:1:-1]) if j == '1'])

精美印刷是:

print ' '.join(
    [str(2**i)
     for i,j in enumerate(
         bin(int(raw_input()))[-1:1:-1]
       )
      if j == '1']
  )

注意:

  • int(n[j])+1)始终为2,因为仅在j为1时才进行迭代.
  • enumerate返回一个元组列表,每个元组都包含索引和值,因此您不需要存储n,并且可以直接针对j进行测试.
  • Python可以遍历项目列表,而不必按索引获取它们,这是[list[i]**2 for i in len(list)][i**2 for i in list]
  • 之间的区别
  • 您不需要在字符串前后加上方括号,因此可以节省一些空间:

  • int(n[j])+1) will always be 2, since you are only iterating if j is 1.
  • enumerate returns a list of tuples each containing the index and value, so you don't need to store n, and can test against j directly.
  • Python can iterate over a list of items without having to fetch them by index, its the difference between [list[i]**2 for i in len(list)] and [i**2 for i in list]
  • You don't need to put brackets around the string, so you can save some space by doing this:

" ".join(...)

代替此:

(" ").join(...)

这篇关于以2的幂的和以升序打印数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆