定义并测试myRange函数

2024-09-27 00:23:14 发布

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

我不断地发现这个错误: 回溯(最近一次呼叫最后一次): 文件“/root/sandbox7723bf31/nt-test-68764d5e.py”,第2行,在 从testmyrange导入myRange ImportError:无法从“testmyrange”导入名称“myRange”(/root/sandbox7723bf31/testmyrange.py)

#define and test a function range with a main defined
#define myRange() method

def myRange(p, q == None and r == None):
  
    if p == 0 and q == None and r == None:
         return []
    if r == None:
         step = 1
    else:
         step = r

    if q == None:
        start = 0
        stop = p
    else:
        start = p
      stop = q

    res = []
    i = start

def main():

    while True:
        res.append(i)

    if step > 0 and i + step >= stop:
        break
    elif step < 0 and i + step <= stop:
        break
    else:
        i = i + step
    return res

#call main and end program

if __name__ == "__main__" :
    
    main()

Tags: andpytestnoneifmainstepres
1条回答
网友
1楼 · 发布于 2024-09-27 00:23:14

对MyRange进行简单测试的代码

def myRange(p = None, q = None, r = None):
  " Provides version of range function "

  # Get arguments which are not none
  args = []
  for i in [p, q, r]:
    if i is not None:
        args.append(i)
   
  # Find start, stop, step from args
  if len(args) == 1:
    # Only one non-none
    start = 0
    stop = args[0]
    step = 1
  elif len(args) == 2:
    start, stop, step = *args, 1 # unpack two from args and add 1 value for step
  elif len(args) == 3:
    start, stop, step = args    # assign all arguments
  
  # Generate list of values based upon
  # start, stop, step
  res = []
  if step > 0:
    # list is incrementing up
    while start < stop:
      res.append(start)
      start += step
  else:
    # list is incrementing down
    while start > stop:
      res.append(start)
      start += step

  return res

def check_result(actual, expected):
    " Checks if results is as expected "
    print("Test: Expected {}, Actual {}, Equal? {}".format(expected, actual, actual == expected))

def main():
  check_result(myRange(0), [])
  check_result(myRange(10), list(range(10)))
  check_result(myRange(0, 5, 2), list(range(0, 5, 2)))
  check_result(myRange(10, 0, -2), list(range(10, 0, -2)))
  check_result(myRange(10, 0, 2), [])
  
if __name__ == "__main__" :
  main()

输出

Test: Expected [], Actual [], Equal? True
Test: Expected [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], Actual [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], Equal? True
Test: Expected [0, 2, 4], Actual [0, 2, 4], Equal? True
Test: Expected [10, 8, 6, 4, 2], Actual [10, 8, 6, 4, 2], Equal? True
Test: Expected [], Actual [], Equal? True

相关问题 更多 >

    热门问题