This question already has answers here:
How do I do multiple assignment in MATLAB?
(9 answers)
Closed 9 years ago.
I've noticed that in a python code you can do something like:
a=0
b=1
a,b=b,a
print(a,b)
which outputs (a=1,b=0) (i.e. each variable is assigned independently of the last assignment). Is there a way to do something similar in MATLAB?
Sorry if this is a really simple question, but I've been trying to find a clean answer to this for a bit of time now and haven't found anything.
There is no need for an additional temporary variable here. If you want multiple assignments in a single statement, you can use deal:
[a, b] = deal(b, a)
I believe this is what you're looking for.
It's always possible to do that with a temporary variable in any language. The unpacking method of Python is just a little syntax sugar to simplify the developer life :)
a = 0
b = 1
tmp = a
a = b
b = tmp
print(a,b)
Anyway, it's not magical, the Python byte code might implement the permutation with a temporary variable. (There's techniques to do this without temp variable, but well... for the sake of clarity use one :p)
Related
This question already has answers here:
Should I cache range results if I reuse them?
(2 answers)
Closed 2 years ago.
In a Python program which runs a for loop over a fixed range many times, e.g.,
while some_clause:
for i in range(0, 1000)
pass
...
does it make sense to cache range:
r = range(0, 1000)
while some_clause:
for i in r
pass
...
or will it not add much benefit?
It won't, a range call does almost nothing. Only the itering part, which is not optional, has a cost.
Interestingly, caching makes it slower for some reason, in the example below.
My benchmarks:
>>> timeit.timeit("""
for i in range(10000):
pass""",number=10000)
1.7728144999991855
>>> timeit.timeit("""
for i in r:
pass""","r=range(10000)",number=10000)
1.80037959999936
And caching it breaks readability, as the Zen of Python states:
Readability counts.
and
Explicit is better than implicit.
Simple is better than complex.
If you are using python 2.*, range will return a list, and you should usexrange.
xrange (2.) or range (3.) are lazy evaluated, which means it actually evaluated the next requested item when you ask for it.
So, no, no need to cache. Instantiate the range where you need it,
no need for tricks and magic there, it's already implemented in Python.
It won't benefit. If you want to enhance your loop activities refer to the comparison of : https://dev.to/duomly/loops-in-python-comparison-and-performance-4f2m
You can have an idea of how can improve things.
This question already has answers here:
How to get the original variable name of variable passed to a function [duplicate]
(13 answers)
Closed 7 years ago.
I'd like to be able to access the name of a variable that is passed to a function as e.g.
def f(x):
'''Returns name of list/dict variable passed to f'''
return magic(x)
>>a = [1,2,3]
>>print( f(a) )
'a'
>>print( f(2) )
None
I suspect this is possible using Python introspection but I don't know enough to understand the inspect module. (NB I know that the need for a function like magic() is questionable, but it is what I want.)
Actually, this is not possible. In Python names and values are quite separate. Inside f, you have access to the value of x, but it is not possible to find out what other names other functions might have given to that value.
Think of names as being somewhat like pointers in C. If you have a pointer, you can find out what object it points to. But if you have the object, you cannot find out what pointers are pointing to it.
This question already has answers here:
Using global variables in a function
(25 answers)
Closed 8 years ago.
I've been having trouble with the "def" function. I know this question has already been asked, but the answer didn't satisfy me and I didn't see how to apply it to my code. I'm trying to make the the popular game 2048 in Python. Basically, when I define the function that makes the entire board move left, it bites me with the error: UnboundLocalError: local variable referenced before assignment. It seems that I have to define the variables "bone" and "btwo" in somewhere that isn't, like, global. But I am yet to figure out how to get that working. Setting parameters in my moveleft() function isn't working, e.g moveleft(bone,btwo). So I'm at my wit's end.
Now, I'll include the entire code, all commented up, but the part I think has the problem is where I define the function moveleft(). Also, if there are any outstanding stupid bits of code, please tell me. Also, try and keep it simple, I'm pretty rubbish with programming and its associated phrases and terms. This is only my 3rd attempt at a code.
I realise I'm asking a lot, but I would really, really, appreciate help with this.
Code:
http://pastebin.ca/2824228
Minimized version:
bone, btwo = 1, 2
def move_left():
if bone == 1: print("bone is 1")
if btwo == 2: print("btwo is 2")
btwo = 3
bone = 2
move_left()
If you are writing to a global variable inside a function, then you need to explicitly say that you are referring to a global variable. So put this as the first line in your function:
global bone, btwo, bthree, bfour, bfive, bsix, bseven, beight, bnine
And, why don't you use a list instead of defining 9 variables?
This question already has answers here:
Simulating Pointers in Python
(11 answers)
Closed 9 years ago.
I'm a physics student, mostly programming in Python and Matlab, now getting into C to boost the performance of my simulations.
Simple question: are there pointers in Python? Are there pointers in Matlab? If yes, can I use them with similar "ease" as in C?
I know that behind the high-levelness in Python and Matlab, there are lots of pointers at work. The question is: can I do something like this C code explicitly in Python or Matlab:
int *p;
int someValue = 1;
p = &someValue;
doSomethingForMe = callSomeFunction(p);
I know there's probably no point in doing that anyway (for most applications). I just want to learn.
You will commonly hear that Python has names, not "variables" in the traditional sense. It also doesn't have "pointers" since such a concept is only meaningful when working at a low level, like with C. (For this reason, you can get "pointers" if you use a C compatibility library in Python, like ctypes. But, such pointers are meant only for interoperability with C.)
Most of the functionality you would use a pointer for in C is present in some other form in Python. For example:
Returning multiple values from a function. In C, you'd do int foo(int *, int *) to return two ints (and maybe an error code). In Python, just use tuple unpacking: x, y = foo() with return x, y in foo.
Passing in big objects. Since everything is pass-by-reference anyway, you can safely pass a reference to a huge object without having it get copied.
Modifying input parameters. Most of this is possible by choosing an appropriate mutable input. For example, you can pass a list into a function and modify the list within the function. In Python, since the references are the same, the input list will appear to be modified:
def change_list(l):
l[0] = 3
my_list = [1,2,3]
change_list(my_list)
print(my_list) # prints [3, 2, 3]
MATLAB has a different concept of variable than Python does. In MATLAB, a variable is a matrix with some dimensions. Writing x = y effectively copies y into x (setting xs dimensions appropriately). MATLAB internally does optimizations to avoid actually copying data unless necessary, but for the programmer it will seem as if x and y are separate matrices.
MATLAB also doesn't have pointers unless you are dealing with a compiled MEX extension (which is written in some other language like C). Like Python, you have mechanisms for passing things around without needing pointers (multiple input and output arguments, for example).
Python you can have pointers with ctypes library apparently. Also, you can simulate the notion of pointers in Python, like in this question.
In Matlab you don't have pointers either.
This question already has answers here:
Is it possible to implement a Python for range loop without an iterator variable?
(15 answers)
Closed 7 years ago.
Say I have a function foo that I want to call n times. In Ruby, I would write:
n.times { foo }
In Python, I could write:
for _ in xrange(n): foo()
But that seems like a hacky way of doing things.
My question: Is there an idiomatic way of doing this in Python?
You've already shown the idiomatic way:
for _ in range(n): # or xrange if you are on 2.X
foo()
Not sure what is "hackish" about this. If you have a more specific use case in mind, please provide more details, and there might be something better suited to what you are doing.
If you want the times method, and you need to use it on your own functions, try this:
def times(self, n, *args, **kwargs):
for _ in range(n):
self.__call__(*args, **kwargs)
import new
def repeatable(func):
func.times = new.instancemethod(times, func, func.__class__)
return func
now add a #repeatable decorator to any method you need a times method on:
#repeatable
def foo(bar):
print bar
foo.times(4, "baz") #outputs 4 lines of "baz"
Fastest, cleanest is itertools.repeat:
import itertools
for _ in itertools.repeat(None, n):
foo()
The question pre-supposes that calling foo() n times is an a priori necessary thing. Where did n come from? Is it the length of something iterable? Then iterate over the iterable. As I am picking up Python, I find that I'm using few to no arbitrary values; there is some more salient meaning behind your n that got lost when it became an integer.
Earlier today I happened upon Nicklaus Wirth's provocative paper for IEEE Computer entitled Good Ideas - Through the Looking Glass (archived version for future readers). In section 4 he brings a different slant on programming constructs that everyone (including himself) has taken for granted but that hold expressive flaws:
"The generality of Algol’s for
statement should have been a warning
signal to all future designers to
always keep the primary purpose of a
construct in mind, and to be weary of
exaggerated generality and complexity,
which may easily become
counter-productive."
The algol for is equivalent to the C/Java for, it just does too much. That paper is a useful read if only because it makes one not take for granted so much that we so readily do. So perhaps a better question is "Why would you need a loop that executes an arbitrary number of times?"