Huawei face questions Python (original)

Recently and happened to see this problem:

There are two sequences a, b, the size of any value are integers n, sequence elements, unordered;

By exchanging the smallest difference a, b of the elements, so that [element and a sequence] and [b and sequence elements] among: Requirements

After some deliberation, I tried to use brute-force method to solve the problem and thinking about the following:

1, respectively, find a, b, and the elements of the sequence sum_a, sum_b
2, calculated min = abs (sum_a - sum_b)

3, a traverse n * n: exchanging a, b is an arbitrary element; exchange after each exchange were calculated sum (a) -sum (b) the absolute value, as an element of a two-dimensional sequence t.

Wherein the sum (a) -sum (b) = sum_a - a [i] + b [j] - (sum_b + a [i] -b [j]) = sum_a -sum_b + 2 * (b [j] -a [I])
. 4, the other min_t = t [0] [0 ], then iterate through t-sequence: If min_t> t of the element, the element with the t as a new value min_t

5, to determine the size of the min and min_t: If min_t <min, then a, b do switching elements; the contrary, no.

I.e., the final output sequence is to meet the requirements.

code show as below:

#******穷举法******Python3.5******
import random
def random_int_list(start,stop,length):   #产生随机序列
    start,stop = (int(start),int(stop)) if start <= stop else (int(stop),int(start))
    length = int(abs(length)) if length else 0
    random_list = []
    for i in range(length):
        random_list.append(random.randint(start,stop))
    return random_list

a = random_int_list(1,100,5)
b = random_int_list(1,100,5) 
T = [[0 for I in Range (. 5)] for I in Range (. 5)] # initialization sequence dimensional T 
Print ( ' A = ' , A, ' B = ' , B, ' T = ' , T ) 
sum_a = SUM (A) 
sum_b = SUM (B) 
min = ABS (sum_a - sum_b)
 Print ( ' sum_a = ' , sum_a, ' sum_b = ' , sum_b, ' min = ' , min)
print('===============================================')

for i in range(5):
    for j in range(5):
        t[i][j] = abs(sum_a -sum_b + 2*(b[j] - a[i]))
print('t = ',t)
print('===============================================')

min_t = t[0][0]
for i in range(5):
    for j in range(5):
        if( min_t > t[i][j]):
            min_t = t[i][j]
            temp1= i
            temp2 = j
if min > min_t:
    temp = a[temp1]
    a[temp1] = b[temp2]
    b[temp2] = temp
print('a = ',a,'b = ',b)

large collection of python face questions

 

Guess you like

Origin www.cnblogs.com/pythongood/p/11223677.html
Recommended