i'm giving a list in the function which takes the numbers and adds as more as possible in order return the higher sum possible which is smaller or even to the limit
maxsum=0
def maxDistance(lista,limit):
global maxsum
lista.sort(reverse=True)
for i in range(len(lista)):
global mega
mega[i]=0
for i in range(len(lista)):
if lista[i]<=limit:
for j in range(len(lista)):
if i!=j:
mega[i]=mega[i]+lista[j]
if mega[i]>limit:
mega[i]=mega[i]-lista[j]
maxsum=max(mega)
return maxsum
print ("Εισαγετε μια λιστα απο αποστασεις και υστερα αφου την καταχωρησετε ,καταχωρηστε εναν αριθμο ως οριο αθροισματος των προηγουμενων αποστασεων. Χωριστε τους αριθμους με κενα. ","\n")
lista=[float(x) for x in input("dose lista: ").split()]
limit=float(input("dose orio: "))
maxDistance(lista,limit)
print (maxsum)
input("press enter to continue")
You need to declare the variable mega
before using the global
keyword. I suggest:
mega = []
maxSum = 0
def foo():
global mega
global maxSum
...
As mad_ in the comment mentioned: in your case, if you're not altering the variable values, then you actually don't really need the global
keyword. After declaring them before the function, you can directly reference them.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.