【每日一题20220422】排队游戏

:mage:‍ 我们今天的任务是给元素进行排序,已知的条件是一个表示元素顺序的提示文字。请编写一个函数返回正确顺序的列表。

【示例】
输入:[“white has black on his left”,“red has green on his right”,“black has green on his left”]
输出:[“red”, “green”, “black”, “white”]
解释:根据提示可以得到:red后面是green,green后面是black,black后面是white。

题目难度:中等
题目来源:CodeWars-Line up

def solution(hints: list)-> list:
    # your code here

assert solution(["d has c on his left","c has b on his left","b has a on his left"]) == ["a", "b", "c", "d"]
assert solution(["d has c on his right","c has b on his right","b has a on his right"]) == ["d", "c", "b", "a"]
assert solution(["red has green on his right","green has red on his left"]) == ["red", "green"]

def solution(hints: list) -> list:
    li = []
    for s in hints:
        *values, direction = s.replace("has ", "").replace("on his ", "").split(" ")
        if direction == "left": values.reverse()
        if not li:
            li.extend(values)
            continue
        if values[0] in li and values[1] in li:
            continue
        elif values[0] in li:
            li.insert(li.index(values[0]) + 1, values[1])
        elif values[1] in li:
            li.insert(li.index(values[1]), values[0])
        else:
            if s == hints[-1]:
                raise AttributeError
            hints.append(s)
    return li

4 个赞
def solution(hints: list) -> list:
    li = []
    try:
        for s in hints:
            values = s.replace("has ", "").replace("on his ", "").split(" ")
            if values[-1] == "left":
                if len(li) == 0:
                    li.append(values[1])
                    li.append(values[0])
                    continue
                elif values[1] not in li and values[0] in li:
                    li.reverse()
                    li.append(values[1])
                    li.reverse()
                    continue
            elif values[-1] == "right":
                if len(li) == 0:
                    li.append(values[0])
                    li.append(values[1])
                    continue
                elif values[1] not in li and values[0] in li:
                    li.append(values[1])
                    continue
                elif values[1] not in li and values[0] not in li:
                    li.reverse()
                    li.append(values[1])
                    li.append(values[0])
                    li.reverse()
                    continue
    except Exception as e:
        print(e)
    return li

哥子,第三条用例貌似过不了。

['red', 'green', 'green'] should equal ['red', 'green']

好了

def solution(hints: list)-> list:
    # your code here
    item_dict = {}
    for index,item in enumerate(hints):
        hints[index] = []
        hints[index].append(item.split()[0])
        hints[index].append(item.split()[2])
        hints[index].append(item.split()[-1])
        item_dict.setdefault(item.split()[0],0)
        item_dict.setdefault(item.split()[2], 0)
    for item in hints:
        if "left" == item[-1]:
            item_dict[item[1]] = item_dict[item[0]] - 1
        elif "right" == item[-1]:
            item_dict[item[1]] = item_dict[item[0]] + 1
    item_dict = sorted(item_dict.items(), key=lambda k: k[1])
    return [item[0] for item in item_dict]


assert solution(["d has c on his left","c has b on his left","b has a on his left"]) == ["a", "b", "c", "d"]
assert solution(["d has c on his right","c has b on his right","b has a on his right"]) == ["d", "c", "b", "a"]
assert solution(["red has green on his right","green has red on his left"]) == ["red", "green"]

R-C

else:
    if s == hints[-1]:
        raise AttributeError
    hints.append(s)

妙 啊 ~

我的这份代码在kata上执行全部用例会超时。期待大佬们其他NB的解法 :eyes:

def solution(hints: list) -> list:
    hints = list(map(lambda x: x.split(" "), hints))
    chaos_list = [list([sentence[0], sentence[2]]) if sentence[5] == "right" else (sentence[2], sentence[0]) for sentence in hints]

    ranked_dict = list(chaos_list[0])
    chaos_list.pop(0)

    counter = 0
    while len(chaos_list) > 0:
        counter += 1
        index = counter % len(chaos_list)
        if chaos_list[index][0] == ranked_dict[-1]:
            ranked_dict.append(chaos_list[index][1])
            chaos_list.pop(index)
        elif chaos_list[index][1] == ranked_dict[0]:
            ranked_dict.insert(0, chaos_list[index][0])
            chaos_list.pop(index)
        elif chaos_list[index][1] == ranked_dict[-1] or chaos_list[index][0] == ranked_dict[0]:
            chaos_list.pop(index)
        else:
            continue
    return ranked_dict
def solution(hints: list)-> list:
    # your code here
    l1 = []
    for a in hints:
        if a.split()[0] not in l1:
            l1.append(a.split()[0])
        if a.split()[2] not in l1:
            l1.append(a.split()[2])
    for a in hints:
        for i in range(len(l1) - 1):
            for j in range(i + 1, len(l1)):
                if a.split()[-1] == "left" and l1.index(a.split()[0]) < l1.index(a.split()[2]):
                    l1[i], l1[j]= l1[j], l1[i]
    return l1
  
            
assert solution(["d has c on his left","c has b on his left","b has a on his left"]) == ["a", "b", "c", "d"]
assert solution(["d has c on his right","c has b on his right","b has a on his right"]) == ["d", "c", "b", "a"]
assert solution(["red has green on his right","green has red on his left"]) == ["red", "green"]

#!/usr/bin/python
# -*- coding: utf-8 -*-
import re


def solution(hits: list) -> list:
    rlt = []
    patten = re.compile(r"(\w+) has (\w+) on his (\w+)")
    for hit in hits:
        match = patten.fullmatch(hit)
        e1, e2, direct = match.groups()
        if direct not in ['left', 'right']:
            raise ValueError("unknown direction")
        if direct == 'right':
            e1, e2 = e2, e1
        index1 = -1
        index2 = -1
        try:
            index1 = rlt.index(e1)
            index2 = rlt.index(e2)
        except ValueError:
            pass
        if index1 != -1:
            rlt.insert(index1, e2)
        elif index2 != -1:
            rlt.insert(index2 + 1, e1)
        else:
            rlt.append(e2)
            rlt.append(e1)
        # print(hit, rlt)
    # print(rlt)
    return rlt


if __name__ == '__main__':
    assert solution(["d has c on his left", "c has b on his left", "b has a on his left"]) == ["a", "b", "c", "d"]
    assert solution(["d has c on his right", "c has b on his right", "b has a on his right"]) == ["d", "c", "b", "a"]
    assert solution(["red has green on his right", "green has red on his left"]) == ["red", "green"]
def solution(hints: list) -> list:
    result1 = {}
    result2 = []
    for x in hints:
        if 'left' in x:
            result1[x.split(' ')[2]] = x.split(' ')[0]
        else:
            result1[x.split(' ')[0]] = x.split(' ')[2]
    keys = []
    values = []
    for k, v in result1.items():
        keys.append(k)
        values.append(v)
    for k in keys:
        if k not in values:
            result2.append(k)
    for i in range(len(result1)):
        result2.append(result1[result2[i]])
    return result2

assert solution(["d has c on his left", "c has b on his left", "b has a on his left"]) == ["a", "b", "c", "d"]
assert solution(["d has c on his right", "c has b on his right", "b has a on his right"]) == ["d", "c", "b", "a"]
assert solution(["red has green on his right", "green has red on his left"]) == ["red", "green"]

def solution(hints: list) -> list:
    result, result_last = [], []
    for i in hints:
        index1 = i.find(" ")
        index2 = i.find(" ", index1 + 1, len(i))
        index3 = i.find(" ", index2 + 1, len(i))
        str1, str2, str3 = i[:index1], i[index2 + 1:index3], i[i.rfind(" ") + 1:len(i) + 1]
        lists = [str2, str1] if str3 == "left" else [str1, str2]
        if len(result) > 0 and (str1 in result[0] or str2 in result[0]):
            result.insert(0, lists)
        else:
            result.append(lists)
    for i in range(len(result)):
        if len(result_last) == 0:
            result_last.append(result[i][0])
            result_last.append(result[i][1])
        elif result[i][1] == result_last[0]:
            result_last.insert(0, result[i][0])
        elif result[i][0] == result_last[-1]:
            result_last.append(result[i][1])
    return result_last
def solution(hints: list)-> list:
    list1 = []
    for hint in hints:
        li = hint.split(" ")
        if li[0] not in list1:
            list1.append(li[0])
            if li[2] not in list1:
                if li[5] == "right":
                    list1.append(li[2])
                else:
                    list1.insert(0,li[2])
            elif li[2] in list1:
                if li[5] =="right":
                    list1.insert(list1.index(li[2]),li[0])
                else:
                    list1.insert(list1.index(li[2])+1,li[0])
        elif li[0] in list1 and li[2] not in list1:
            if li[5] == "right":
                list1.insert(list1.index(li[0])+1, li[2])
            else:
                list1.insert(list1.index(li[0]), li[2])
        elif li[0] in list1 and li[2] in list1:
            continue
    return list1


assert solution(["d has c on his left","c has b on his left","b has a on his left"]) == ["a", "b", "c", "d"]
assert solution(["d has c on his right","c has b on his right","b has a on his right"]) == ["d", "c", "b", "a"]
assert solution(["red has green on his right","green has red on his left"]) == ["red", "green"]
封装一个装饰器
def qianzhi(*args):
    def exe(func):
        def wrapper():
            list_1=[]
            for arg in args:
                old_list=[str(i).replace(' has ', '|').replace(' on his ', '|').split('|')  for i in arg]
                list_1.append(old_list)
            for y in list_1:
                for i in y:
                    if 'left' in i:
                        i.remove('left')
                        i[0],i[1]=i[1],i[0]
                    if 'right' in i:i.remove('right')
            return func(list_1)
        return wrapper
    return exe

@qianzhi(["d has c on his left","c has b on his left","b has a on his left"],["d has c on his right","c has b on his right","b has a on his right"],["red has green on his right","green has red on his left"])
def solution(old_list: list)-> list:
    all_result=[]
    new_list=[]
    for i in old_list:
        for y in i:
            if not new_list:
                new_list.extend(y)
            elif y[0] in new_list and y[1] not in new_list:
                new_list.insert(new_list.index(y[0])+1,y[1])
            elif y[1] in new_list and y[0] not in new_list:
                new_list.insert(new_list.index(y[1]), y[0])
        all_result.append(new_list)
        new_list = []
    return all_result

print(solution())

虽然Kata全量测试超时了,但是先跑通再说。

def solution(hints: list) -> list:
    # your code here
    result = []
    while len(hints) > 0:
        i = hints[:][0]
        str_list = i.split(' ')
        if len(result) > 0:
            if str_list[0] in result and str_list[2] in result:
                if 'left' in str_list:
                    if result.index(str_list[2]) > result.index(str_list[0]):
                        result[result.index(str_list[0])], result[result.index(str_list[2])] = str_list[2], str_list[0]
                        hints.remove(i)
                    else:
                        hints.remove(i)
                else:
                    if result.index(str_list[2]) < result.index(str_list[0]):
                        result[result.index(str_list[0])], result[result.index(str_list[2])] = str_list[2], str_list[0]
                        hints.remove(i)
            elif str_list[0] in result and str_list[2] not in result:
                if 'left' in str_list:
                    result.insert(result.index(str_list[0]), str_list[2])
                    hints.remove(i)
                else:
                    result.insert(result.index(str_list[0]) + 1, str_list[2])
                    hints.remove(i)
            elif str_list[0] not in result and str_list[2] in result:
                if 'left' in str_list:
                    result.insert(result.index(str_list[2]) + 1, str_list[0])
                    hints.remove(i)
                else:
                    result.insert(result.index(str_list[2]), str_list[0])
                    hints.remove(i)
            else:
                hints[0], hints[len(hints) - 1] = hints[len(hints) - 1], i
        else:
            if 'left' in str_list:
                result.extend([str_list[2], str_list[0]])
                hints.remove(i)
            else:
                result.extend([str_list[0], str_list[2]])
                hints.remove(i)
    return result

看了大佬的解题思路,我悟了。

def solution(hints: list) -> list:
    d = dict((h[0], h[2]) if h[5] == 'right' else (h[2], h[0]) for h in map(str.split, hints))
    res = list(d.keys() - d.values())
    while res[-1] in d: res.append(d[res[-1]])
    return res
1 个赞

妙 哇 :star_struck:~
妙 哇 :star_struck:~

是啊 看了大佬的这段代码 瞬间念头通达。

def solution(hints: list)-> list:
    graph = dict( (a,b) if side=='right' else (b,a) for a,_,b,_,_,side in map(str.split,hints))
    result = list(set(graph) - set(graph.values()))
    while graph.get(result[-1]) is not None:
        result.append(graph.get(result[-1]))
    return result