你可以使用zip()
和list comprehension
做這樣的事情:
def get_pourcent(a, order='ascending'):
if order == 'ascending':
# Check if every element is inferior than his next in the list
b = [1 if j < v else 0 for j, v in zip(a, a[1:])]
# Get how much zeros in b
zeros = len(b) - sum(b)
percent = (1 - (float(zeros)/len(a)))*100
elif order == 'descending':
b = [1 if j > v else 0 for j, v in zip(a, a[1:])]
zeros = sum(b)
percent = (float(zeros)/len(a))*100
else:
return None
return '"%s": %.2f%% sorted' % (order, percent)
# Test
tests = [('ascending', [2,3,4,6,5]), ('ascending', [1,2,3,4,5]),
('ascending', [0,2,4,8,10]), ('descending', [2,3,4,6,5]), ('descending', [0,2,4,8,10])]
for k, v in tests:
print v, get_pourcent(v, order=k)
輸出:
[2, 3, 4, 6, 5] "ascending": 80.00% sorted
[1, 2, 3, 4, 5] "ascending": 100.00% sorted
[0, 2, 4, 8, 10] "ascending": 100.00% sorted
[2, 3, 4, 6, 5] "descending": 20.00% sorted
[0, 2, 4, 8, 10] "descending": 0.00% sorted
編輯:
tests = [[ 2, 4, 0, 8], [ 4, 24, 0, 16], [ 16, 2, 16, 32], [ 16, 2, 16, 128]]
for k in tests:
print get_pourcent(k)
將輸出:
"ascending": 75.00% sorted
"ascending": 75.00% sorted
"ascending": 75.00% sorted
"ascending": 75.00% sorted
對不起,但這不是一個編碼服務。你試過什麼了?你在哪裏掙扎? –
謝謝你@ImanolLuengo –