Code: Alles auswählen
def summe(a, p):
if p<0:
return 0
return a[p] + summe(a, p-1)
Code: Alles auswählen
def summe(a, p):
if p<0:
return 0
return a[p] + summe(a, p-1)
Code: Alles auswählen
a = [1,2,3,4,5,6,7,8,9,10,11]
def summe(a,p):
if p>0:
return a[p]+summe(a,p-1)
if p=0
return a[p]
else:
return (0)
print(summe(a,4))
in deinem ersten Post stand als AufgabeStareDog hat geschrieben: ↑Sonntag 27. Mai 2018, 13:24 Also du meinst für die Fälle, indem p negativ ist, ist bei mir keine Lösung gegeben und deswegen ist deine Endbedingung besser? bzw. für negative p wird auch a[p] zurückgegeben. Stimmt, danke.
Code: Alles auswählen
a = [1,2,3,4,5,6,7,8,9,10,11] def summe(a,p): if p>0: return a[p]+summe(a,p-1) if p=0 return a[p] else: return (0) print(summe(a,4))
Nein, in keiner Weise.
@SiriusStareDog hat geschrieben: ↑Sonntag 27. Mai 2018, 13:24 Also du meinst für die Fälle, indem p negativ ist, ist bei mir keine Lösung gegeben und deswegen ist deine Endbedingung besser? bzw. für negative p wird auch a[p] zurückgegeben. Stimmt, danke.
also so!Code: Alles auswählen
a = [1,2,3,4,5,6,7,8,9,10,11] def summe(a,p): if p>0: return a[p]+summe(a,p-1) if p=0 return a[p] else: return (0) print(summe(a,4))
Code: Alles auswählen
a = [5,6,7,2,3,2,5,3,7,3,2,7,8]
def maximum(a,p):
if p<0:
return 0
else:
return max(maximum(a,p-1),a[p])
print(maximum(a,9))
Code: Alles auswählen
a = [5,6,7,2,3,2,5,3,7,3,2,7,8]
def maximum(a,p):
if p<0:
print ("error")
elif p==0:
return a[p]
else:
return max(maximum(a,p-1),a[p])
print(maximum(a,9))
Code: Alles auswählen
def maximum(a,p): #Liste a mit Länge p (len(a)=p)
if p==1 : #ist nur ein Element in der Liste
return a[0]
else:
maxi = max(a[1:p+1]) #Suche maximum von a[1] bis a[p]
if a[0] > maxi : #prüfe ob gefundenes Element a[maxi] > a[0] ist
return a[0]
else:
return maxi
Code: Alles auswählen
def maximum(a,p):
return max(a[:p+1])
Code: Alles auswählen
a = [5,6,7,2,3,2,5,3,7,3,2,7,8]
def maximum(a,p):
if p<0:
raise ValueError("cannot find maximum of an empty sequence")
elif p==0:
return a[p]
else:
if maximum(a,p-1)<a[p]:
return a[p]
else:
return maximum(a,p-1)
print(maximum(a,1))