0

我正在创建一个程序来计算数字列表中的最高小数位数。基本上,一个列表[123, 1233]将返回 4,因为 1233 中有四个数字,它是最大的。另一个例子是[12, 4333, 5, 555555]返回 6,因为 555555 有 6 个数字。

这是我的代码。

def place(listy):  
    if len(listy) == 1:  
        decimal = len(str(listy[0]))    
        print(decimal)  
    else:  
        if len(str(listy[0])) >= len(str(listy[1])):  
            new_list = listy[0:1]  
            for i in listy[2:]:  
                new_list.append(i)  
            place(new_list)  
        else:   
            place(listy[1:]) 

现在,当我使用print(decimal)它时,它可以工作,但如果我更改print(decimal)return decimal,它不会返回任何东西。为什么是这样?我该如何解决?我遇到过这些运行了很多次的返回语句。提前致谢!

4

5 回答 5

8

When you do a recursive call (i.e. when place calls place, and the called place returns a value, then the calling place must return it as well (i.e. the return value "bubbles up" to the initial caller).

So you need to replace every recursive call

place(...)

with

return place(...)

As others have said, there are easier solutions, such as using max(). If you want to keep a recursive approach, I would refactor your code as follows:

def place2(listy):
    if len(listy) < 1:
        return None
    elif len(listy) == 1:
        return len(str(listy[0]))
    else:
        v0, v1 = listy[0], listy[1]
        if v1 > v0:
            return place2(listy[1:])
        else:
            return place2([listy[0]]+listy[2:])

Although this is tail-recursive, Python does not really care so this approach will be inefficient. Using max(), or using a loop will be the better solution in Python.

于 2013-03-22T18:52:41.823 回答
1

It's not that the return doesn't do anything, it's that you don't propagate the return from your recursive call. You need a few more returns:

def place(listy):  
    if len(listy) == 1:  
        decimal = len(str(listy[0]))    
        return decimal
    else:  
        if len(str(listy[0])) >= len(str(listy[1])):  
            new_list = listy[0:1]  
            for i in listy[2:]:  
                new_list.append(i)  
            return place(new_list)  # <-- return added
        else:   
            return place(listy[1:]) # <-- return added

You can see the print at any level, but to get it back to the caller it needs to be propagated.

于 2013-03-22T18:50:46.090 回答
1

该函数确实返回该值,但它没有将其打印出来。
解决此问题的一种简单方法是,只需在 print 语句中调用该函数。
那是:

print(place(listy))
于 2018-08-19T04:53:41.377 回答
0

If all you want is to find the maximum length of a list of integers, consider:

max([len(str(n)) for n in N])

For example

N = [1,22,333,4444]
max([len(str(n)) for n in N]) # Returns 4

N = [12, 4333, 5, 555555]
max([len(str(n)) for n in N]) # Returns 6

Note: This will only work for positive integers.

Or more simply:

len(str(max(N)))

Which will also only work for positive integers.

于 2013-03-22T18:51:20.983 回答
-2

使用“全局变量”(google it)来访问和更改在您的函数之外定义的变量。

于 2014-05-28T09:06:02.113 回答