How can I change a global variable from a function without the use of global keyword ? (Python)
I am asked to do it like this : seq = [1,2,3,4,5] reverse(seq) the spread operator is not allowed for me: seq[:] and I should make the reverse function myself.
5/30/2020 10:44:50 AMSaeed Alqassabi
10 AnswersNew Answer
Saeed Alqassabi list() returnes a new list while seq.clear() is op on the same list. Sooner or later advanced pythonistas should understand thr differences. If u got it... 👍
for i in range(3,-1,-1): seq.append(seq.pop(i))
Pass your list as an argument to the function, then use its methods to change it. def f(seq): seq.reverse()
@HonFu I am not allowed to do that too, see this: You are not allowed to use the following: - python 2 - slice notations - defining an empty list: . Use "x=list()" instead if you need it - list comprehensions - the spread operator inside square brackets - "tuple" and "reversed" builtins have been deactivated The "list" builtin has been replaced with another implementation with the following specifications: - list.reverse is forbidden - list.__reversed__ is forbidden - slicing is forbidden All other usual methods of the list class are still present.
I just found a solution for that, what happened is that I reassigned the variable seq: seq = list() # to clear the list - I use it regularly - inside the function and that caused the problem, the code thought that meant to create a new variable, but I used the clear method of the list instead : seq.clear() and it worked. Nice LOL.
@Abhay try to see this because even I don't understand why it doesn't work, def reverse(seq): indexes = list() seqLen = len(seq) while len(indexes) < len(seq): seqLen -= 1 indexes.append(seqLen) store = dict(enumerate(seq)) seq = list() for i in indexes: seq.append(store.get(i))
It works perfectly Saeed Alqassabi just you aren't printing out the seq 🤔
Is that a problem on a site like Codewars? If I had to reverse by hand, I'd do this: def rev(seq): for i in range(len(seq)//2): seq[i], seq[-i-1] = seq[-i-1], seq[i]
@Oma Falk that answer is amazing, I thought that range() can't go backward, I am really sure that yours is the shortest and the most understandable. @HunFu thanks for the help dude I am always learning new tricks from you.