所以,我正在努力制作这个节目,我现在非常接近,但我无法完成最后的工作。我追踪了我的问题,因为问题在于使用模数。我试图获得五倍的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]
非常感谢帮助。
答案 0 :(得分:1)
这里有一些问题。最重要的是,您尝试使用变量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
答案 1 :(得分:1)
您必须使用以前的值来计算新值。
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