return语句只返回打印

时间:2018-03-25 00:10:19

标签: python return

我有一个代码,其中return语句似乎什么也没有返回,但是如果我在return语句的正上方添加一个print语句,print语句就可以了。例如:

return(test_list) #returns None

但如果我添加了print语句

print(test_list)

return(test_list) #print, prints the desired result

这怎么可能?

功能:

def reachable_destinations(iata_src: str, allowed: int, routes)\
    -> List[Set[str]]:

    """The first parameters represents an IATA code. The second parameter is 
    the maximum number of direct flights allowed. The last parameter represents
    route information. Return a list of the sets of IATA codes reachable from
    the first parameter in steps from 0 up to (and including) the maximum 
    number of hops."""    

    #For example, with IATA code 'AA1', maximum number of flights as 2, and the following route information
    #{'AA1': {'AA2', 'AA4'}, 'AA2': {'AA3'}, 'AA3': {'AA4', 'AA1'}, 'AA4': {'AA1'}}
    #the result should be [{'AA1'}, {'AA2', 'AA4'}, {'AA3'}].
    i = 0
    reachable_list = [{iata_src}]
    #print(reachable_list)
    for i in range(allowed):
        #print(i)
        total_set = set()
        #print(total_set)
        for j in range(len(reachable_list[i])):
            #print(j)
            #print(routes[list(reachable_list[i])[j]])
            total_set = total_set | routes[list(reachable_list[i])[j]]
            #print(total_set)
        dif = total_set - arbitrary_union(reachable_list)
        #print(dif)
        if dif == set():
            print('dif is empty')
            return reachable_list
        else:
            reachable_list.append(dif)   
            #print(reachable_list)
    print(reachable_list)        
    return reachable_list   

1 个答案:

答案 0 :(得分:0)

您可以使用递归函数来解决此类问题:

def destinations_reachable(departure, routes, result_accumulated, depth_allowed, depth_reached=0):
    if depth_reached + 1 > len(result_accumulated):
        result_accumulated.extend(set() for x in range(depth_reached + 1 - len(result_accumulated)))
    result_accumulated[depth_reached].add(departure)
    local_destinations_reachable = routes.get(departure, set())

    if depth_reached < depth_allowed :
        for next_destination in local_destinations_reachable:
            destinations_reachable(next_destination, routes, result_accumulated, depth_allowed, depth_reached + 1)


routes_references = {'AA1': {'AA2', 'AA4'}, 'AA2': {'AA3'}, 'AA3': {'AA4', 'AA1'}, 'AA4': {'AA1'}}
result = []
depth_maximum = 2

destinations_reachable('AA1', routes_references, result, depth_maximum)

for hops in enumerate(result):
    destinations = ", ".join(hops[1])
    print(f'Destinations reachable after {hops[0]} hops: {destinations}')

print('Reachable destinations:', result)

它给出了输出:

Destinations reachable after 0 hops: AA1
Destinations reachable after 1 hops: AA4, AA2
Destinations reachable after 2 hops: AA3, AA1
Reachable destinations: [{'AA1'}, {'AA4', 'AA2'}, {'AA3', 'AA1'}]

此解决方案的唯一问题是,如果您想要大量跳数的所有路由,我们可以达到函数可以调用自身的时间限制。