python字首 python字首和演算法

2021-10-18 15:00:21 字數 2660 閱讀 2517

我試圖理解字首和概念背後的思想,看看codity here(蘑菇揀選器問題)在字首和課程中給出的例子

我的理解是,整個概念是基於乙個簡單的屬性,即為了求陣列a的兩個位置a(pos_left,pos_right)之間的所有元素的和,使用第二個陣列p,其中所有元素都是連續求和的,其中搜尋到的和計算為

值(p(pos_right+1))—值(p(pos_left))。在a 1 2 3 4 5 6

p 0 1 3 6 10 15 21

sum of all elements between a[2] and a[5] = 3+ 4 + 5 = 12

or using the prefix sums" p[5+1] - p[2] = 15 -3 = 12the problem

there is a street with mushroom at every place represented

by a non-empty vector. given the initial position of a picker and its

movement range, possible maximum number of mushrooms to collect is

looked for.

看看這個例子,我不明白迴圈構造背後的邏輯。有人能解釋一下這個演算法的原理嗎?

其次,我發現這個例子中的positionin索引非常混亂和麻煩。通常的做法是將帶有字首和的向量的開頭的零「移位」嗎?(在python中,從0開始計算向量中的元素這一事實已經引起了一些混亂)。在

解決方案

^$我已經為乙個小陣列a= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]執行了一些例子,選擇了位置k=5和範圍m=3。我不明白建立兩個迴圈檢查的範圍的邏輯。在

我得到了迴圈的以下引數(p=, left_pos=, right_pos=)

loop 1 (0,5,8), (1,4,6),(2,3,5),(3,2,5)

loop 2 (0,2,5), (1,4,6), (2,5,7), (3,5,8)

蘭吉各不相同。為什麼?在

用於除錯的版本def mushrooms2(a, k, m):

n = len(a)

result = 0

pref = prefix_sums(a)

l1 =min(m, k) + 1

print 'loop p in xrange(min(m, k) + 1): %d' % l1

for p in xrange(min(m, k) + 1):

print 'p %d' % p

print 'a= %r' % a

print 'pref= %r' % pref

left_pos = k - p

right_pos = min(n - 1, max(k, k + m - 2 * p))

result = max(result, count_total(pref, left_pos, right_pos))

print 'left_pos = k - p= %d' % left_pos

print 'right_pos= min(n-1,max(k,k+m-2*p))= %d' % right_pos

print 'max'

print '(result %d' % result

print 'count_total(pref, left_pos, right_pos)) %r, %r, %r, %r' % (pref,left_pos, right_pos,count_total(pref, left_pos, right_pos))

print 'result= %d' % result

print 'next p'

l2=min(m + 1, n - k)

print 'loop xrange(min(m + 1, n - k)): %d' % l2

for p in xrange(min(m + 1, n - k)):

print 'p %d' % p

print 'a= %r' % a

print 'pref= %r' % pref

right_pos = k + p

left_pos = max(0, min(k, k - (m - 2 * p)))

result = max(result, count_total(pref, left_pos, right_pos))

print 'right_pos = k + p= %d' % right_pos

print 'left_pos = max(0, min(k, k - (m - 2 * p)))= %d' % left_pos

print 'max'

print '(result %d' % result

print 'count_total(pref, left_pos, right_pos)) %r, %r, %r, %r' % (pref,left_pos, right_pos,count_total(pref, left_pos, right_pos))

print 'result= %d' % result

print 'next p'

print 'result %d' % result

return result

字首樹python實現

file name 字首樹.py class trienode object def init self self.path 0 路過此節點幾個 self.end 0 以此為結尾的幾個 self.map none for i in range 26 每乙個節點有26條路 class trie obj...

python演算法 字首和

這裡有 n 個航班,它們分別從 1 到 n 進行編號。有乙份航班預訂表 bookings 表中第 i 條預訂記錄 bookings i firsti,lasti,seatsi 意味著在從 firsti 到 lasti 包含 firsti 和 lasti 的 每個航班 上預訂了 seatsi 個座位。...

python函式前篇

函式特性 什麼是函式?函式就是具備某一特定功能的工具 函式的使用必須遵循 先定義後使用的原則 先定義就是事先準備好工具 後使用,或者說拿來就用,重複使用,指的就是函式的呼叫 定義函式 定義無參函式 def fun 指定函式名,呼叫的時候寫上函式名即可 注釋,方便理解的 pass deffun1 pa...