【问题标题】:How to run and check this code? (Python basics)如何运行和检查这段代码? (Python 基础)
【发布时间】:2013-11-11 00:41:57
【问题描述】:

基本上,我的问题是关于如何运行这段代码? Finding the second smallest number from the given list using divide-and-conquer。我试过打印……但它什么也没给我。只是想看看这段代码是如何工作的。很抱歉这个简单的问题,在 Python 中是全新的。

【问题讨论】:

  • 在调用方法的地方添加一行“print two_min([...])”。 “全新”不是不思考的借口。

标签: python


【解决方案1】:

好吧,只需使用函数调用来运行它,并使用print 来打印它:

def two_min(arr):
    n = len(arr)
    if n==2: # Oops, we don't consider this as comparison, right?
        if arr[0]<arr[1]:                   # Line 1
            return (arr[0], arr[1])
        else:
            return (arr[1], arr[0])
    (least_left, sec_least_left) = two_min(arr[0:n/2])
    (least_right, sec_least_right) = two_min(arr[n/2:])
    if least_left < least_right:            # Line 2
        least = least_left
        if least_right < sec_least_left:    # Line 3
            return (least, least_right)
        else:
            return (least, sec_least_left)
    else:
        least = least_right
        if least_left < sec_least_right:    # Line 4
            return (least, least_left)
        else:
            return (least, sec_least_right)


print two_main([12,2])

如果您想知道这是如何工作的,可以查看在线 python 可视化工具。 Link.

【讨论】:

  • @Katty 如果这个答案对你有用,请投票并接受答案。
猜你喜欢
  • 2018-07-30
  • 2017-10-31
  • 2017-11-18
  • 2020-02-05
  • 1970-01-01
  • 1970-01-01
  • 2015-08-22
  • 1970-01-01
  • 2012-10-02
相关资源
最近更新 更多