0

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")
Omer Tekbiyik
  • 4,255
  • 1
  • 15
  • 27
  • you should edit this to be in a code block so we can read it. I believe there is a button "code" when you create a post, or you can use ctrl-k when creating a post. You can also put small snips of code in backticks ` – Reedinationer Jan 24 '19 at 17:47
  • 2
    Possible duplicate of [Using global variables in a function](https://stackoverflow.com/questions/423379/using-global-variables-in-a-function) – mad_ Jan 24 '19 at 18:03

1 Answers1

0

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.

Amarth Gûl
  • 1,040
  • 2
  • 14
  • 33
  • Nope you do not need to define `maxSum` to be global inside the function as list is immutable – mad_ Jan 24 '19 at 18:06
  • Your answer needs an edit as the language is quite ambiguous to me. Have a read through https://medium.com/@meghamohan/mutable-and-immutable-side-of-python-c2145cf72747 – mad_ Jan 24 '19 at 18:16