在Python 3.6中

时间:2018-08-20 15:00:39

标签: python-3.x itertools

我正在尝试遍历数字序列。我有这个:

from itertools import islice, count
handle = int(input("Please enter a number:")
handler = str(handle)
parameter = []
for i in handler:
    parameter.append(i)
    print(parameter) #This was for debugging
    revised = parameter(count(1[2])) #I'm not sure I'm using the correct syntax here, the purpose is to make revised == parameter[0] and parameter[2]

最终,我要实现的目标是采用一两个数字序列并将其进行比较。例如,如果i [0] == i [1] + i [2],我想返回True,或者就此而言,如果i [0] == i [1]-i [2]。我希望程序遍历整个序列,检查这些类型的关联,例如23156将== true,因为2 * 3 = 6,2 + 3 = 5,5 + 1 = 6,2 + 3 + 1 = 6;等。严格来说,这只是出于我自己的目的,只是试图制作一个玩具。

当我利用     修订=参数(计数(1 [2]) 我收到一个错误消息,说内建函数。 TYPEERROR,类型int不可下标,但我明确将整数输入转换为字符串。

1 个答案:

答案 0 :(得分:0)

尽管不清楚,但是您试图描述的内容很难解释。它似乎类似于Running Total,但受限制且涉及各种操作,即加法,减法和乘积。

限制

  • 前两个数字是种子
  • 以下数字必须通过某些操作来累积
  • 积累必须连续发展

代码

import operator as op
import itertools as it


def accumulate(vals):
    """Return a set of results from prior, observed operations."""
    adds = set(it.accumulate(vals))                        # i[0] == i[1] + i[2]  
    muls = set(it.accumulate(vals, op.mul))                # i[0] == i[1] * i[2]  
    subs = {-x for x in it.accumulate(vals, func=op.sub)}  # i[0] == i[1] - i[2]
    #print(adds, muls, subs)
    return adds | muls | subs


def rolling_acc(vals):
    """Return accumulations by sweeping all contiguous, windowed values."""
    seen = set()
    for i, _ in enumerate(vals):
        window = vals[i:]
        if len(window) >= 3:
            seen |= accumulate(window)
    return seen


def is_operable(vals):
    """Return `True` if rolling operations on contiguous elements will be seen."""
    s = str(vals)
    nums = [int(x) for x in s]
    ahead = nums[2:]
    accums = rolling_acc(nums)
    #print(ahead, accums)
    return len(set(ahead) & accums) == len(ahead)

测试

assert is_operable(23156) == True
assert is_operable(21365) == False                         # {2,3} non-contiguous
assert is_operable(2136)  == True
assert is_operable(11125)  == True