【问题标题】:Python sorted list containing all integers in both consumed listPython 排序列表包含两个消费列表中的所有整数
【发布时间】:2015-07-07 05:56:07
【问题描述】:

我将如何编写一个递归函数,该函数使用两个列表,然后生成一个包含两个列表中元素的列表?如果两个列表中都有一个数字两次,则生成的列表中也会有两次该数字。 这是我目前所拥有的:

def merge(L1, L2, i, j, R): if L1[i] == L2[j]: R.append(L1[i]) R.append(L2[j]) merge(L1, L2, i, j+1, R) else: merge(L1, L2, i+1, j, R)
def sorted_intersection(lst1, lst2): R = [] return merge(lst1, lst2, lst1[0], lst2[0], R)

Nvm,找到了代码。感谢大家的帮助!

【问题讨论】:

  • 您能否发布一个您尝试过的示例和预期的输出?
  • “消耗两个列表”是什么意思?很容易拥有这样的功能:def consume(list1, list2): return list1 + list2。你是否认为 list1 和 list2 已经被消费了,我不知道。
  • Python 中的递归有两条规则: 1. 只有在没有其他方法的情况下才使用递归。 2. 总有另一种方式。
  • 我添加了我目前的工作

标签: python list sorting recursion


【解决方案1】:

请参阅模块collections 的文档,其中包含许多功能任务的帮助器:

from collections import defaultdict, Counter

# Preserves the order of b:
def in_both(a, b):
    # Count the occurrences of elements in a:
    a = Counter(a)
    # Default to 0:
    a = defaultdict(lambda: 0, a)

    # Return true if there is a positive amount of items x in a left:
    def take_from_a(x):
        cur = a[x]
        if cur > 0:
            a[x] = cur - 1
            return True

    # Filter out elements in b that are not often enough in b:
    return filter(take_from_a, b)

in_both("abbcccdddd", "abcdabcde") == "abcdbcd"

这里a 和b 都迭代了一次。

【讨论】:

    【解决方案2】:

    为什么要递归?

    a = [1, 2, 2, 3, 3] 
    b = [2, 3, 4] 
    
    result = [[x, b.remove(x)][0] for x in a if x in b] 
    result
    [2, 3, 3]
    

    【讨论】:

    • 我将测试我在不替换或查找的情况下递归编写这些类型的python函数的能力
    猜你喜欢
    • 1970-01-01
    • 2012-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多