华为OD试题九(高矮个子排队、We Are A Team)

1. 高矮个子排队

华为OD试题九(高矮个子排队、We Are A Team)_第1张图片
华为OD试题九(高矮个子排队、We Are A Team)_第2张图片
华为OD试题九(高矮个子排队、We Are A Team)_第3张图片

示例代码:

# 利用 列表 相邻 元素 之间的关系
# 测试数据
s1 = [4, 1, 3, 5, 2]
def fun(s):
	if all(_ == s[0] for _ in s):
		return s

	cur = 0
	while cur < len(s) - 1:
		if cur % 2 == 0:
			if s[cur] < s[cur + 1]:
				s[cur],s[cur + 1] = s[cur + 1],s[cur]
			elif cur % 2 == 1:
				if s[cur] > s[cur + 1]:
					s[cur], s[cur + 1] = s[cur + 1], s[cur]
		cur += 1
	return s

r = fun(s1)
print(r)

2. We Are A Team

华为OD试题九(高矮个子排队、We Are A Team)_第4张图片
华为OD试题九(高矮个子排队、We Are A Team)_第5张图片
示例代码:

# 核心 找出 当前元素的关联元素, 判断另一个元素是否在该集合中即可
# 测试数据
ss = [
    [1, 2, 0],
    [1, 2, 1],
    [1, 5, 0],
    [2, 3, 1],
    [2, 5, 1],
    [1, 3, 2]
]
# 该函数用于找出所有相关元素
def fun1(a_list,ss):
	
	# 递归终止条件
	if len(a_list) == 0:
		return []
	
	tmp = []
    for a in a_list:
        t = []
        for i in ss:
            if i[0] == a:
                tmp.append(i[1])
                t.append(i)
            if i[1] == a:
                tmp.append(i[0])
                t.append(i)
        if len(t) != 0:
            for ele in t:
                ss.remove(ele)
	# 递归 查找
    a_list.extend(fun1(tmp, ss))
    return a_list
	
def fun(ss):
    for i in ss:
        if i[2] == 1:
            new_list = [_ for _ in ss if _[2] == 0]
            a = i[0]
            b = i[1]
            a_list = [a, ]
            # 用于 a 元素的所关系元素
            aa = fun1(a_list, new_list)
            if b in aa:
                print("we are a team")
            else:
                print("we are not team")
        elif i[2] > 1:
            print("da pian zi")
fun(ss)

你可能感兴趣的:(OD试题,华为od,python)