如何在Python中检查某物是否是x折叠的?

2024-09-29 23:28:04 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,我正在努力做这个节目,我现在非常接近,但我不能做最后的润色。我追踪了我的问题,因为问题在于模的用法。我试图得到e的五倍,但是当我这样做的时候,我的列表中的第三个元素得到-2,这不是我所期望的。你知道吗

这可能是因为我试图用模除一个负数,但我不能解决这个问题,因为我不知道怎么做。有人能帮我解决这个问题吗?你知道吗

def f10(start, n):
    """
    The parameters start and n are both int's. Furthermore n > 0.
    The function f10() should return a list of int's that contains n
    elements.
    The first element (e) in the resulting list has to be start.
    The successor of an element e is calculated as follows:
    - if e is a fivefold (e.g. n is divisible by 5),
      then the next value of e is e / 5
    - if e is not a fivefold, then the next value of e is e - 4

    Example:
        f10(1, 10) should return
        [1, -3, -7, -11, -15, -3, -7, -11, -15, -3]
        f10(9, 12) should return
        [9, 5, 1, -3, -7, -11, -15, -3, -7, -11, -15, -3]
    """

    pass

    new_list = []
    k = range(start, n+1)
    e = k[0]

    new_list.append(e)

    for e in k:
        if e % 5 == 0:
            e = float(e) / 5
        else:
            e -= 4

        new_list.append(e)

    return new_list

print f10(1, 10)
print f10(9, 12)

所以,我应该得到:

[1, -3, -7, -11, -15, -3, -7, -11, -15, -3]

但我明白了

[1, -3, -2, -1, 0, 1.0, 2, 3, 4, 5, 2.0]

我们将不胜感激。你知道吗


Tags: oftheinnewreturnifiselement
2条回答

必须使用以前的值来计算新值。你知道吗

def f10(start, n):

    result = [start] # I put first element

    for _ in range(n-1): # I have to put other n-1 elements yet
        if start % 5 == 0:
            start //= 5
        else:
            start -= 4

        result.append(start)

    return result

#  - compare result with expected list  -

print(f10(1, 10) == [1, -3, -7, -11, -15, -3, -7, -11, -15, -3])
# True

print(f10(9, 12) == [9, 5, 1, -3, -7, -11, -15, -3, -7, -11, -15, -3])
# True

编辑:如果您不想要range(),那么您可以使用while len(result) < n:

def f10(start, n):

    result = [start]

    while len(result) < n:
        if start % 5 == 0:
            start //= 5
        else:
            start -= 4

        result.append(start)

    return result

这里有一些问题。最重要的是,您正在尝试使用变量e来迭代循环和存储计算结果。你知道吗

试试这个:

def f10(start, n):
    x = start
    new_list = []
    for i in range(n):
        new_list.append(x)
        x = x-4 if x%5 else x//5
    return new_list

相关问题 更多 >

    热门问题