python类cmp_to_key()的实例源码

jsarray.py 文件源码 项目:blender 作者: gastrodia 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def sort(cmpfn):
        if not this.Class in {'Array', 'Arguments'}:
            return this.to_object() # do nothing
        arr = []
        for i in xrange(len(this)):
            arr.append(this.get(six.text_type(i)))

        if not arr:
            return this
        if not cmpfn.is_callable():
            cmpfn = None
        cmp = lambda a,b: sort_compare(a, b, cmpfn)
        if six.PY3:
            key = functools.cmp_to_key(cmp)
            arr.sort(key=key)
        else:
            arr.sort(cmp=cmp)
        for i in xrange(len(arr)):
            this.put(six.text_type(i), arr[i])

        return this
facet.py 文件源码 项目:solaris-ips 作者: oracle 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def __keylist_sort(self):
                """Update __keysort, which is used to determine facet matching
                order.  Inherited facets always take priority over local
                facets so make sure all inherited facets come before local
                facets in __keylist.  All facets from a given source are
                sorted by length, and facets of equal length are sorted
                lexically."""

                def facet_sort(x, y):
                        i = len(y) - len(x)
                        if i != 0:
                                return i
                        return misc.cmp(x, y)

                self.__keylist = []
                self.__keylist += sorted([
                        i
                        for i in self
                        if i in self.__inherited
                ], key=cmp_to_key(facet_sort))
                self.__keylist += sorted([
                        i
                        for i in self
                        if i not in self.__inherited
                ], key=cmp_to_key(facet_sort))
misc.py 文件源码 项目:yatta_reader 作者: sound88 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def cmp_to_key(mycmp):
    """Convert a cmp= function into a key= function"""
    class K(object):
        __slots__ = ['obj']
        def __init__(self, obj, *args):
            self.obj = obj
        def __lt__(self, other):
            return mycmp(self.obj, other.obj) < 0
        def __gt__(self, other):
            return mycmp(self.obj, other.obj) > 0
        def __eq__(self, other):
            return mycmp(self.obj, other.obj) == 0
        def __le__(self, other):
            return mycmp(self.obj, other.obj) <= 0
        def __ge__(self, other):
            return mycmp(self.obj, other.obj) >= 0
        def __ne__(self, other):
            return mycmp(self.obj, other.obj) != 0
        def __hash__(self):
            raise TypeError('hash not implemented')
    return K

# Back up our definitions above in case they're useful
parser.py 文件源码 项目:ln2sql 作者: FerreroJeremy 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def transformation_sort(cls,transition_list):
        # Sort on basis of two keys split length and then token lengths in the respective priority.
        return sorted(transition_list, key=functools.cmp_to_key(cls._myCmp),reverse=True)
loader.py 文件源码 项目:kinect-2-libras 作者: inessadl 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def getTestCaseNames(self, testCaseClass):
        """Return a sorted sequence of method names found within testCaseClass
        """
        def isTestMethod(attrname, testCaseClass=testCaseClass,
                         prefix=self.testMethodPrefix):
            return attrname.startswith(prefix) and \
                hasattr(getattr(testCaseClass, attrname), '__call__')
        testFnNames = filter(isTestMethod, dir(testCaseClass))
        if self.sortTestMethodsUsing:
            testFnNames.sort(key=_CmpToKey(self.sortTestMethodsUsing))
        return testFnNames
pstats.py 文件源码 项目:kinect-2-libras 作者: inessadl 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def sort_stats(self, *field):
        if not field:
            self.fcn_list = 0
            return self
        if len(field) == 1 and isinstance(field[0], (int, long)):
            # Be compatible with old profiler
            field = [ {-1: "stdname",
                       0:  "calls",
                       1:  "time",
                       2:  "cumulative"}[field[0]] ]

        sort_arg_defs = self.get_sort_arg_defs()
        sort_tuple = ()
        self.sort_type = ""
        connector = ""
        for word in field:
            sort_tuple = sort_tuple + sort_arg_defs[word][0]
            self.sort_type += connector + sort_arg_defs[word][1]
            connector = ", "

        stats_list = []
        for func, (cc, nc, tt, ct, callers) in self.stats.iteritems():
            stats_list.append((cc, nc, tt, ct) + func +
                              (func_std_string(func), func))

        stats_list.sort(key=cmp_to_key(TupleComp(sort_tuple).compare))

        self.fcn_list = fcn_list = []
        for tuple in stats_list:
            fcn_list.append(tuple[-1])
        return self
py23.py 文件源码 项目:TACTIC-Handler 作者: listyque 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def cmp_to_key(mycmp):
        """Convert a cmp= function into a key= function"""
        class K(object):
            __slots__ = ['obj']

            def __init__(self, obj):
                self.obj = obj

            def __lt__(self, other):
                return mycmp(self.obj, other.obj) < 0

            def __gt__(self, other):
                return mycmp(self.obj, other.obj) > 0

            def __eq__(self, other):
                return mycmp(self.obj, other.obj) == 0

            def __le__(self, other):
                return mycmp(self.obj, other.obj) <= 0

            def __ge__(self, other):
                return mycmp(self.obj, other.obj) >= 0

            def __ne__(self, other):
                return mycmp(self.obj, other.obj) != 0

            def __hash__(self):
                raise TypeError('hash not implemented')

        return K


# This function is intended to decorate other functions that will modify
# either a string directly, or a function's docstring.
advisory.py 文件源码 项目:arch-security-tracker 作者: archlinux 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def advisory_extend_html(advisory, issues, package):
    # sort issues by length to avoid clashes
    issues = sorted(issues, key=cmp_to_key(lambda a, b: len(a.id) - len(b.id)), reverse=True)
    for issue in issues:
        advisory = advisory.replace(' {}'.format(issue.id), ' <a href="/{0}">{0}</a>'.format(issue.id))
    advisory = sub('({}) '.format(package.pkgname), '<a href="/package/{0}">\g<1></a> '.format(package.pkgname), advisory, flags=IGNORECASE)
    advisory = sub(' ({})'.format(package.pkgname), ' <a href="/package/{0}">\g<1></a>'.format(package.pkgname), advisory, flags=IGNORECASE)
    advisory = sub(';({})'.format(package.pkgname), ';<a href="/package/{0}">\g<1></a>'.format(package.pkgname), advisory, flags=IGNORECASE)
    return advisory
Schedule.py 文件源码 项目:py-enarksh 作者: SetBased 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def get_queue(self):
        """
        Returns the queued nodes sorted by scheduling wait.

        :rtype: list[enarksh.controller.node.Node.Node]
        """
        return sorted(self.__queue, key=functools.cmp_to_key(Schedule.queue_compare))

# ----------------------------------------------------------------------------------------------------------------------
EventQueueEmptyEventHandler.py 文件源码 项目:py-enarksh 作者: SetBased 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def __queue_handler(controller):
        """
        Starts a node that is queued and for which there are enough resources available.

        :param enarksh.controller.Controller.Controller controller: The controller.
        """
        # Return immediately if there are no loaded schedules.
        if not controller.schedules:
            return

        start = False
        schedules = sorted(controller.schedules.values(),
                           key=functools.cmp_to_key(EventQueueEmptyEventHandler.queue_compare))
        for schedule in schedules:
            queue = schedule.get_queue()
            for node in queue:
                # Inquire if there are enough resources available for the node.
                start = node.inquire_resources()
                if start:
                    span_job = node.start()

                    # If required send a message to the spanner.
                    if span_job:
                        message = node.get_start_message(schedule.sch_id)
                        controller.message_controller.send_message('spawner', message)
                    else:
                        node.stop(0)

                    # If a node has been started leave inner loop.
                    break

            # If a node has been started leave the outer loop.
            if start:
                break

    # ------------------------------------------------------------------------------------------------------------------
persistent_homology.py 文件源码 项目:OpenTDA 作者: outlace 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def sortComplex(filterComplex, filterValues):
    pairedList = zip(filterComplex, filterValues)
    sortedComplex = sorted(pairedList, key=functools.cmp_to_key(compare))
    sortedComplex = [list(t) for t in zip(*sortedComplex)]

    return sortedComplex
loader.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def getTestCaseNames(self, testCaseClass):
        """Return a sorted sequence of method names found within testCaseClass
        """
        def isTestMethod(attrname, testCaseClass=testCaseClass,
                         prefix=self.testMethodPrefix):
            return attrname.startswith(prefix) and \
                hasattr(getattr(testCaseClass, attrname), '__call__')
        testFnNames = filter(isTestMethod, dir(testCaseClass))
        if self.sortTestMethodsUsing:
            testFnNames.sort(key=_CmpToKey(self.sortTestMethodsUsing))
        return testFnNames
pstats.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def sort_stats(self, *field):
        if not field:
            self.fcn_list = 0
            return self
        if len(field) == 1 and isinstance(field[0], (int, long)):
            # Be compatible with old profiler
            field = [ {-1: "stdname",
                       0:  "calls",
                       1:  "time",
                       2:  "cumulative"}[field[0]] ]

        sort_arg_defs = self.get_sort_arg_defs()
        sort_tuple = ()
        self.sort_type = ""
        connector = ""
        for word in field:
            sort_tuple = sort_tuple + sort_arg_defs[word][0]
            self.sort_type += connector + sort_arg_defs[word][1]
            connector = ", "

        stats_list = []
        for func, (cc, nc, tt, ct, callers) in self.stats.iteritems():
            stats_list.append((cc, nc, tt, ct) + func +
                              (func_std_string(func), func))

        stats_list.sort(key=cmp_to_key(TupleComp(sort_tuple).compare))

        self.fcn_list = fcn_list = []
        for tuple in stats_list:
            fcn_list.append(tuple[-1])
        return self
build.py 文件源码 项目:msys2-helpers 作者: lazka 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def sorted_with_cmp(sequence, cmp_func, **kwargs):
    # sort with a cmp func which works under both Python 2 and 3

    if sys.version_info[0] == 3:
        from functools import cmp_to_key

        key = cmp_to_key(cmp_func)

        def do_sort(x):
            return sorted(x, key=key, **kwargs)
    else:
        def do_sort(x):
            return sorted(x, cmp=cmp_func, **kwargs)

    return do_sort(sequence)
py23.py 文件源码 项目:SDK 作者: Keypirinha 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def cmp_to_key(mycmp):
        """Convert a cmp= function into a key= function"""
        class K(object):
            __slots__ = ['obj']

            def __init__(self, obj):
                self.obj = obj

            def __lt__(self, other):
                return mycmp(self.obj, other.obj) < 0

            def __gt__(self, other):
                return mycmp(self.obj, other.obj) > 0

            def __eq__(self, other):
                return mycmp(self.obj, other.obj) == 0

            def __le__(self, other):
                return mycmp(self.obj, other.obj) <= 0

            def __ge__(self, other):
                return mycmp(self.obj, other.obj) >= 0

            def __ne__(self, other):
                return mycmp(self.obj, other.obj) != 0

            def __hash__(self):
                raise TypeError('hash not implemented')

        return K


# This function is intended to decorate other functions that will modify
# either a string directly, or a function's docstring.
functools_cmp_to_key.py 文件源码 项目:pymotw3 作者: reingart 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def compare_obj(a, b):
    """Old-style comparison function.
    """
    print('comparing {} and {}'.format(a, b))
    if a.val < b.val:
        return -1
    elif a.val > b.val:
        return 1
    return 0

# Make a key function using cmp_to_key()
9.py 文件源码 项目:algorithm_course 作者: hrwhisper 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def solve_closest_pair_n_logn2(points):
    def closest_pair(L, R, points):
        if L == R: return 0x7fffffff, points[L], points[R]  # return int max
        if R - L == 1: return euclidean_dis_pow(points[L], points[R]), points[L], points[R]
        mid = (L + R) >> 1
        d, p1, p2 = closest_pair(L, mid, points)
        d2, p3, p4 = closest_pair(mid + 1, R, points)
        if d > d2:
            d, p1, p2 = d2, p3, p4

        min_x = points[mid][0] - d
        max_x = points[mid][0] + d

        suspect = [points[i] for i in range(L, R + 1) if min_x <= points[i][0] <= max_x]

        suspect.sort(key=lambda x: x[1])
        n = len(suspect)
        for i in range(n):
            for j in range(i + 1, n):
                if suspect[j][1] - suspect[i][1] > d: break
                t = euclidean_dis_pow(suspect[i], suspect[j])
                if t < d:
                    d = t
                    p1, p2 = suspect[i], suspect[j]
        return d, p1, p2

    points.sort(key=cmp_to_key(lambda x, y: x[0] - y[0] if x[0] != y[0] else x[1] - y[1]))
    return closest_pair(0, len(points) - 1, points)
2.py 文件源码 项目:algorithm_course 作者: hrwhisper 项目源码 文件源码 阅读 44 收藏 0 点赞 0 评论 0
def min_complete_time(p, f):
    n = len(p)
    t = list(zip(range(n), list(zip(p, f))))  # it will be like this: [_id,(pi,fi)]
    t.sort(key=cmp_to_key(lambda x, y: y[1][1] - x[1][1]))
    order = []
    min_time = timecost = 0
    for i in range(n):
        order.append(t[i][0])
        timecost += t[i][1][0]
        min_time = max(min_time, timecost + t[i][1][1])
    return min_time, order
testFiveCardStudUtils.py 文件源码 项目:RoomAI 作者: roomai 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test1(self):
        """

        """
        from functools import cmp_to_key
        public_cards = [[roomai.fivecardstud.FiveCardStudPokerCard("2_Spade"),\
                                     roomai.fivecardstud.FiveCardStudPokerCard("3_Spade"), \
                                     roomai.fivecardstud.FiveCardStudPokerCard("A_Spade")]]
        public_cards.sort(key = cmp_to_key(roomai.fivecardstud.FiveCardStudPokerCard.compare))
        for i in range(len(public_cards[0])):
            print (public_cards[0][i].key)
testBridge.py 文件源码 项目:RoomAI 作者: roomai 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def testAGame(self):
        env = roomai.bridge.BridgeEnv()
        allcards = list(roomai.bridge.AllBridgePokerCards.values())
        allcards.sort(key = cmp_to_key(roomai.common.PokerCard.compare))
        infos, public_state, person_states, private_state = env.init({"allcards":allcards, "start_turn":0})
        for i in range(4):
            print (i,person_states[i].hand_cards_dict, len(person_states[i].hand_cards_dict))
            self.assertEqual(len(person_states[i].hand_cards_dict),13)
        self.assertEqual(public_state.turn, 0)

        #### bidding stage
        action = roomai.bridge.BridgeAction.lookup("bidding_bid_A_Heart")
        infos, public_state, person_states, private_state = env.forward(action)
        action = roomai.bridge.BridgeAction.lookup("bidding_pass")
        infos, public_state, person_states, private_state = env.forward(action)
        infos, public_state, person_states, private_state = env.forward(action)
        infos, public_state, person_states, private_state = env.forward(action)
        self.assertEqual(public_state.stage, "playing")
        self.assertEqual(public_state.turn,0)

        #### playing_stage
        count = 0
        while env.public_state.is_terminal == False:
            action  = list(env.person_states[env.public_state.turn].available_actions.values())[0]
            count  += 1
            env.forward(action)
        self.assertEqual(count,13 * 4)
        self.assertTrue(env.public_state.scores[0] == 0)
        self.assertTrue(env.public_state.scores[1] > 0)
        print (env.public_state.scores)
        self.assertEqual(env.public_state.scores[1],350)


问题


面经


文章

微信
公众号

扫码关注公众号