断言列表中的所有项都满足Python中的一个条件



我需要你的帮助。我正在编写一段代码,将两个排序数组合并为一个排序数组。问题是我不知道如何设置输入的条件。

def merge_and_sort (A,B):
# condition that A and B are already sorted
necessary step
return result

例如,A=[1,2,4,10,20]和B=[2,4,4.5,10,100]将是可接受的;但是A=[1,2,4,10,20]和B=[2,4,4.5,100,10]不会。

提前谢谢。

检查列表中的数字是否小于下一个数字。

代码:

def is_sorted(L):
return all([ L[i] <= L[i+1] for i in range(len(L)-1)])

A=[1, 2, 4, 10, 20] 
B=[2, 4, 4.5, 100, 10]
B1=[2, 4, 4.5, 10, 100]
print('A is', ('not sorted', 'sorted')[is_sorted(A)])
print('B is', ('not sorted', 'sorted')[is_sorted(B)])
print('B1 is', ('not sorted', 'sorted')[is_sorted(B1)])
print('A and B are', ('not sorted', 'already sorted')[is_sorted(A) and is_sorted(B)])
print('A and B1 are', ('not sorted', 'already sorted')[is_sorted(A) and is_sorted(B1)])

输出:

A is sorted
B is not sorted
B1 is sorted
A and B are not sorted
A and B1 are already sorted
def merge_and_sort (A,B):
# maiking a varibale to check if both list are sorted
both_sorted = False

# comparing a orignal listed with a sorted on to check if 
# its already sorted or not 

if A == sorted(A) and B == sorted(B):
both_sorted = True
#This list will contain both the list
result  = []

#if both lists are sorted put list A in result
# and then list B
if both_sorted == True:
print("Both list accepted")
for i in A:
result.append(i)
for i in B:
result.append(i) 
result.sort()



else:
print("Lists are not sorted")           
return result

A = [1, 2, 4, 10, 20] 
B = [2, 4, 4.5, 10, 100] 
res = merge_and_sort(A,B)
print(res)

相关内容

  • 没有找到相关文章

最新更新