+ 1
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.
10 ответов
+ 5
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... 👍
+ 5
for i in range(3,-1,-1):
seq.append(seq.pop(i))
+ 2
Pass your list as an argument to the function, then use its methods to change it.
def f(seq):
seq.reverse()
+ 2
@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.
+ 2
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.
+ 1
@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))
+ 1
It works perfectly Saeed Alqassabi just you aren't printing out the seq 🤔
+ 1
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]
+ 1
@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.