在python中被雨水管击中

时间:2018-08-28 10:17:18

标签: python python-3.x data-structures

a = [3,0,0,2,0,4]       #input
l = []                  #left side 
r = []                  #right side
sum = 0                 #output
l[0] = a[0]             #loading a[0] into l[0]
for i in range(len(a)):     #finding left tallest
   l[i] = max(a[i],l[i-1])  #finding maximum and adding into left list
r[n-1] = a[n-1]             # loading the elements from last into right list 
for i in range(len(n-2)):   #finding right tallest
   r[i] = max(a[i],l[i+1])  #finding maximum and adding into right list
for i in range(0,len(n)):       
   sum = sum + (min(l[i],r[i])-a[i]*1)      #sum of inputs
print(sum)

期望输出总和= 10 3x2 + 1x1 + 1x3 = 10

上一个的更新代码。

def findwater(a,n):                     
left = [0]*n                    
right = [0]*n                   
sum = 0                 
left[0] = a[0]          
for i in range(1,n):    
    left[i] = max(left[i-1],a[i])   
right[n-1] = a[n-1]
for i in range((n-2),-1,-1):    
    right[i] = max(right[i+1],a[i])
for i in range(0,n):        
    sum = sum + (min(left[i],right[i])-a[i]*1)      
return sum

a = [3,0,0,2,0,4]   
n = len(a)
print(findwater(a,n))

这次我遇到此错误 left [i] = max(left [i-1],a [i]) TypeError:“ int”对象不可调用帮助我更正代码。

2 个答案:

答案 0 :(得分:0)

第8行: <!-- this entire html file the front page design and almost navigation to filter is going here --> <div class="col-xs-5 title"> <input type="search" placeholder="Type region or city" id="name" class="region-set" [(ngModel)]="search"> <div class="filter-search" *ngIf="search"> <div class="search-results" (scroll)="loadmore($event)" infiniteScroll [infiniteScrollDistance]="2" [infiniteScrollThrottle]="50" [scrollWindow]="false" [infiniteScrollDisabled]="isFullListDisplayed"> <div *ngFor="let items of itemsToShow | filter:search; let i=index" class="filter-borders"> <span (click)="selectCities($event)"> {{i + 1 + ' . ' + items.city}}&nbsp; &&nbsp; <strong>State</strong>: &nbsp;{{items.state}}</span> </div> </div> </div> </div> ,r的长度为0,n未初始化,所以我认为您的错误可能在这里。

希望对您有帮助。

答案 1 :(得分:0)

您的代码有多个问题。

  1. 变量名可以提供更多信息,l-> left_side。这样,您无需在每一行都添加评论。
  2. 您使用的变量n尚未初始化为任何变量。
  3. 也许将您的代码分为多个功能。然后,您可以调查每个功能是否应执行的操作。

第一个问题在第5行。您要做l[0] = ...问题是l是一个空列表,因此您无法访问元素[0],这就是为什么您得到错误。

相反,您可以将元素附加到l:

l.append(a[0])