【问题标题】:Need logic for this (ANDing list elements to get Power of Two)为此需要逻辑(ANDing 列表元素以获得二的幂)
【发布时间】:2018-01-31 19:37:35
【问题描述】:

我有一个问题:

给定一个数组 A。是否存在数组 A 的任何子集,如果我们对该子集的所有元素进行 AND 运算,那么输出应该是 2 的幂(例如:1、2、4、8、16 等)。

观察后我是这样尝试的:

s = list(map(int,raw_input().split()))
x = [ True for x in s if x | (x+1) == (x+1)*2]
if len(x) > 0:
    print "YES"
else:
    print "NO"

有人会提出除此之外的任何其他逻辑吗?

【问题讨论】:

标签: python


【解决方案1】:

我们将使用itertools.combinations 从输入集中获取所有元素组合。

from itertools import combinations

def is_power_two(n):
    if n==1:
        return True
    if n<1:
        return False
    return is_power_two(n/2)

def do_they_and(s):
    for i in range(2, len(s)+1): 
        for j in combinations(s, i):
            total = 0
            for n in j:
                total &= n
            if is_power_two(total):
                return True

这可能是最简单的编程方法,但从效率的角度来看,最好的解决方案可能是动态编程。

【讨论】:

  • 这不适用于 python 2.. 使用 from __future__ import division 修复
猜你喜欢
  • 2023-03-25
  • 1970-01-01
  • 2019-05-05
  • 2018-12-09
  • 2010-12-31
  • 2021-06-28
相关资源
最近更新 更多