【问题标题】:Why does it tell me I am comparing functions?为什么它告诉我我在比较函数?
【发布时间】:2022-06-16 00:11:15
【问题描述】:

我正在执行 CodeWars kata (Strings mix) 并且遇到错误。 我写了以下代码:

def mix(s1, s2):
    whitelist = set('abcdefghijklmnopqrstuvwxyz')
    out = []
    s1 = ''.join(sorted((c for c in s1 if c in whitelist), key = lambda c: (-s1.count(c), c)))
    s2 = ''.join(sorted((c for c in s2 if c in whitelist), key = lambda c: (-s2.count(c), c)))
    groups = sorted(list(set(s1) | set(s2)), key = lambda c: (-max([s1.count(c), s2.count(c)]), lambda v: 1 if (s1.count(v) > s2.count(v)) else 2, c))
    
    for i in groups:
        if max([s1.count(i), s2.count(i)]) <= 1:
            continue
        if s1.count(i) == s2.count(i):
            out.append('=:' + i * s1.count(i))
            continue
        if s1.count(i) > s2.count(i):
            out.append('1:' + i * s1.count(i))
            continue
        else:
            out.append('2:' + i * s2.count(i))
    
    return '/'.join(out)

第 6 行 (groups = sorted...) 的目标是根据 kata 的描述正确排序不同的单个字母。我正在使用 lambda 函数为 sorted() 方法创建键,该方法返回三个值的元组:

  • 两个字符串的最大字母数(c),反向排序时取反
  • 尝试如果s1 的字母数量相同,则优先于s2
  • 如果一切都失败了,最后按字母顺序

如果这没有意义,我建议阅读 kata 描述。 我收到错误消息:

Traceback (most recent call last):
  File "/workspace/default/tests.py", line 5, in <module>
    test.assert_equals(mix("Are they here", "yes, they are here"), "2:eeeee/2:yy/=:hh/=:rr")
  File "/workspace/default/solution.py", line 6, in mix
    groups = sorted(list(set(s1) | set(s2)), key = lambda c: (-max([s1.count(c), s2.count(c)]), lambda v: 1 if (s1.count(v) > s2.count(v)) else 2, c))
TypeError: '<' not supported between instances of 'function' and 'function'

我有点困惑为什么会发生这种情况,因为我看不出s1.count(v) 和s2.count(v) 是如何起作用的?

如果我尝试订购字母的方式完全错误,我不介意一些帮助。

【问题讨论】:

  • lambda c: (...) 返回的元组的第二个元素是lambda。它没有被调用,它被返回,然后sorted() 尝试比较它们。
  • key=lambda c: (-max(...), lambda v: ..., c) 是什么意思?

标签: python string function lambda comparison


猜你喜欢
  • 2010-12-07
  • 1970-01-01
  • 1970-01-01
  • 2021-12-22
  • 2019-03-09
  • 2015-10-11
  • 2021-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多