我正在尝试找到等于或大于N且可被3整除且仅包含0和1的数字
这是我的代码:
for x in range(1, 11):
p = x**10 # power x by 10
print(x, p) # output number itself and power result
此时我陷入困境:我们需要找到数字等于或大于N可被3整除仅包含0和1。
如果我尝试:
while True:
try:
N = int(input('Enter number from 1 to 10: '))
except ValueError:
print("That's not a number!")
pass
else:
if 1 <= N < 10:
print('Everythig is OK, you entered number in 1 to 10 range')
# start variant 1
found = False
i = N
while not found:
if i % 3 == 0:
try:
dummy = int(str(i), 2)
print(i)
found = True
except:
pass
i += 1
# end variant 1
pass
else:
print('Out of range. Try again')
pass
输入范围内任意数字的结果 111
返回相同的结果:
import itertools
while True:
try:
N = int(input('Enter number from 1 to 10: '))
except ValueError:
print("That's not a number!")
pass
else:
if 1 <= N < 10:
print('Everythig is OK, you entered number in 1 to 10 range')
# start variant 2
ints = itertools.count(N + 1)
filtered = filter(lambda x: set(str(x)) <= {"0", "1"}, ints)
filtered = filter(lambda x: not x % 3, filtered)
result = next(filtered)
print(result)
# end variant 2
pass
else:
print('Out of range. Try again')
pass
如果我们改变数字列表的条件如果1&lt; = N&lt; 10 到如果1&lt; = N&lt; 10 10 **两种变体都是正确的。
P.S。如果我们输入例如234234234数算法几乎死了。发现的数字越少越好)) 谢谢你的帮助!
答案 0 :(得分:2)
让我们一步一步来看:
生成大于N的所有整数:
ints = itertools.count(N + 1)
仅保留十进制表示由0和1组成的那些:
filtered = filter(lambda x: set(str(x)) <= {"0", "1"}, ints)
保持3点可见的那些:
filtered = filter(lambda x: not x % 3, filtered)
采取第一个:
result = next(filtered)
你已经完成了!
P.S。欢迎来到函数式编程的世界,由Python制作精美:)
答案 1 :(得分:0)
假设您已经定义了N,
i = N
while True:
if i % 3 == 0:
try:
dummy = int(str(i), 2)
print i
break
except:
pass
i += 1
如果数字不是二进制, int(str(i), 2)
会引发异常
有一种更有效的方法,包括生成仅包含高于N的1和0的所有数字,但我真的认为您不需要这种优化级别。