【发布时间】:2016-09-12 18:01:52
【问题描述】:
我在我的代码中找不到错误。它在我的 cmd 上运行得很好,但不会通过实验室平台测试。问题来了:
您需要设计一个迭代和递归函数,分别称为replicate_iter 和replicate_recur,它们将接收两个参数:times 是重复的次数,data 是要重复的数字或字符串。
该函数应返回一个包含重复数据参数的数组。例如,replicate_recur(3, 5) 或 replicate_iter(3,5) 应该返回 [5,5,5]。如果 times 参数为负数或零,则返回一个空数组。如果参数无效,请提出ValueError。"
现在这是我的代码:
my_list1 = []
my_list2 = []
def replicate_iter(times,data):
try:
if type(data) != int and type(data) != str:
raise ValueError('Invalid Argument')
times += 0
if times > 0:
x = 0
while x < times:
my_list2.append(data)
x = x+1
return my_list2
else:
return []
except (ValueError,AttributeError,TypeError):
raise ValueError('Invalid Argument')
def replicate_recur(times,data):
try:
if type(data) != int and type(data) != str:
raise ValueError('Invalid Argument')
times += 0
if times <= 0:
return my_list1
else:
my_list1.append(data)
return replicate_recur(times-1,data)
except(AttributeError,TypeError):
raise ValueError('Invalid Argument')
【问题讨论】:
-
请为该站点更好地格式化您的代码。如果你用 4 个字符空间缩进你的句子(通常是一个制表符),它会更好地显示一个代码块。
-
为什么要使用全局变量?
-
不知道这是否是你失败的原因,但这条线是错误的:
type(data) != int and type(data) != str: -
我正在使用全局变量,因为我不希望每次递归都改变值
-
不要打扰类型检查。任何此类异常都表明该函数被错误调用或代码中存在错误;任一种情况都可以通过让代码自然失败来有效地发出信号。
标签: python recursion iteration