Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am just learning Python with ebook of A Byte in Python and some youtube tutorial. I have reached up to For loop statement. Its not that I don't understand it, but the beginner examples only show: " for i in range..." My question is why only 'in range' option is given. I know how this statement, both for and range, works. But are there other options instead of range?
Can you give me a simple Syntax for usage of for loop? They don't have it in this ebook. Thanks and sorry if I was irritating and confusing. I am just learning by myself.
Of course, there are many ways to use a for-loop. for i in range() is commonly used to loop through something a specific amount of times, or just do something a repeated amount of times with a counter.
Infact, you don't even have to iterate over lists. You can iterate over a string:
>>> for char in 'hello':
... print char
...
h
e
l
l
o
Or even a dictionary:
>>> for key in {'foo':'bar','cabbage':'cake'}:
... print key
...
cabbage
foo
Python does not have the typical for loop construct that the "c-family" languages like java, c, c++, etc have. Python isn't the only scripting language that does this ( I believe bash does it too but don't quote me ). If you want something as true as can be to the "normal" for loop ( and I'm assuming you do ) :
for( int i = 0; i < n; i++ ){ /* do something */ }
I would suggest a while loop in python
i = 0
while ( i < n ) :
// do something
Or use xrange
for i in xrange( 0, n ) :
// do something
xrange is a lot like range, but it doesn't store all the values simultaneously : http://docs.python.org/2/library/functions.html#xrange
I personally would use xrange, I don't know of a better solution. Good luck!
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am new to Python, could someone give some pointers as to how this C code can be done in Python:
for(i=0, j=0; j<n; i++, j++){
A[i] = A2[j];
}
I gave this as a example. I am working on a web scraping project where I have to compare each word in a string given by the user to another string and should count proximity of each word and the strings I've to compare are in an array.
You are basically copying an array, equivalent to a python list. You could simply do:
A = list(A2)
In a for loop scenario (which isn't even needed due to the availability of the list call), you'd do:
for ind, val in enumerate(A2):
A[ind] = val
you really have many other options too, A2.copy(), A2[:], a list comprehension and in most recent python versions [*A2]. Python generally makes it very easy to do this.
Python supports iteration over collections/iterables (so range, for example) which are generally discrete. So, you can rewrite that as a while loop:
i = 0
j = 0
while j < n:
A[i] = A2[j]
i += 1
j += 1
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I apologize because I am coming from Perl and I am new to Python.
The following example looks very long to me:
#!/usr/bin/python
import re
r = re.compile('(?i)m(|[ldf])(\d+)')
m = r.match(text)
if m:
print m.group(2)
In Perl for example it is only one line and it's pretty readable.
#!/usr/bin/perl
print $2 if /m(|[ldf])(\d+)/i
How can I rewrite my Python example to be simpler. If possible to be as light as it is with Perl.
I am planning to write plenty tests and if I want to keep my code readable I would like to avoid consuming lines that will not help people to understand my program. I guess that something like this below would be more readable that my first solution:
r = R()
if r.exec('(?i)m(|[ldf])(\d+)', text): print r.group(2)
if r.exec('(?i)k(|[rhe])(\d{2})', text): print r.group(2)
Unfortunately in this case I have to write a class for this.
The Python way values clarity over brevity, so things are generally going to be more verbose than they are in Perl. That said, the re.compile step is optional.
m = re.match('(?i)m(|[ldf])(\d+)', text)
if m:
print m.group(2)
In Python, assignments are not expressions; they can't be used as values. So there's no way to skip the separate assignment statement (m = ...) or combine it with the if . And if you want to refer to the match object later, you do need an explicit assignment - there's no global implicit state analogous to the Perl $n variables that stores the capture groups automatically.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I am trying to translate a Perl function into a Python function, but I am having trouble figuring out what some of the Perl to Python function equivalents.
Perl function:
sub reverse_hex {
my $HEXDATE = shift;
my #bytearry=();
my $byte_cnt = 0;
my $max_byte_cnt = 8;
my $byte_offset = 0;
while($byte_cnt < $max_byte_cnt) {
my $tmp_str = substr($HEXDATE,$byte_offset,2);
push(#bytearry,$tmp_str);
$byte_cnt++;
$byte_offset+=2;
}
return join('',reverse(#bytearry));
}
I am not sure what "push", "shift", and "substr" are doing here that would be the same in Python.
Any help will be much appreciated.
The Perl subroutine seems rather complicated for what it does, viz., taking chunks of two chars at a time (the first 16 chars) from the sent string and then reverses it. Another Perl option is:
sub reverse_hex {
return join '', reverse unpack 'A2' x 8, $_[0];
}
First, unpack here takes two characters at a time (eight times) and produces a list. That list is reversed and joined to produce the final string.
Here's a Python subroutine to accomplish this:
def reverse_hex(HEXDATE):
hexVals = [HEXDATE[i:i + 2] for i in xrange(0, 16, 2)]
reversedHexVals = hexVals[::-1]
return ''.join(reversedHexVals)
The list comprehension produces eight elements of two characters each. [::-1] reverses the list's elements and the result is joined and returned.
Hope this helps!
I realize that you are asking about the perl to python translation, but if you have any control over the perl, I would like to point out that this function is a lot more complicated than it needs to be.
The entire thing could be replaced with:
sub reverse_hex
{
my $hexdate = shift;
my #bytes = $hexdate =~ /../g; # break $hexdate into array of character pairs
return join '', reverse(#bytes);
}
Not only is this shorter, it is much easier to get your head around.
Of course, if you have no control over the perl, you are stuck with what you were dealt.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I had to write a script that generates some fixture file with increasing fake MAC addresses.
To do that, I decided to have some fun and try to make it as compact as I could. I ended up with:
def mac_address(i):
return ':'.join(['%02x'] * 6) % tuple([(i >> (8 * j)) & 0xFF for j in reversed(range(6))])
Which actually works pretty well. Obviously, writing this that way is the best way to get slapped by the future person that must work on it, but I did it for the fun (and wrote a more readable version in comment).
But now I'm curious, can you think of any more compact way of writing that ? (That is without removing the spaces).
What about
':'.join('%02x' % (i>>(8*j) & 0xFF) for j in reversed(range(6)))
That is more compact and easier to understand.
def mac_address(i):
return ':'.join(a+b for a, b in zip(*[iter('{:012x}'.format(i))]*2))
The first step is to get a hex string zero filled so that it is exactly 12 digits, which is what '{:012x}'.format(i) does. Then we break that string up in two-character chunks using the method of grouping items from the zip() documentation, and join the result on ':'.
Maybe:
from struct import pack, unpack
def mac_address(i):
return ":".join(["%02x"] * 6) % unpack("BBBBBB", pack("!Q", i)[2:])
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
In Python, I really enjoy how concise an implementation can be when using list comprehension. I love to do concise list comprehensions this:
myList = [1, 5, 11, 20, 30, 35] #input data
bigNumbers = [x for x in myList if x > 10]
However, I often encounter more verbose implementations like this:
myList = [1, 5, 11, 20, 30, 35] #input data
bigNumbers = []
for i in xrange(0, len(myList)):
if myList[i] > 10:
bigNumbers.append(myList[i])
When a for loop only looks through one data structure (e.g. myList[]), there is usually a straightforward list comprehension statement that is equivalent to the loop.
With this in mind, is there a refactoring tool that converts verbose Python loops into concise list comprehension statements?
Previous StackOverflow questions have asked for advice on transforming loops into list comprehension. But, I have yet to find a question about automatically converting loops into list comprehension expressions.
Motivation: There are numerous ways to answer the question "what does it mean for code to be clean?" Personally, I find that making code concise and getting rid of some of the fluff tends to make code cleaner and more readable. Naturally there's a line in the sand between "concise code" and "incomprehensible one-liners." Still, I often find it satisfying to write and work with concise code.
2to3 is a refactoring tool that can perform arbitrary refactorings, as long as you can specify them with a syntactical pattern. The pattern you might want to look for is this
VARIABLE1 = []
for VARIABLE2 in EXPRESSION1:
if EXPRESSION2:
VARIABLE1.append(EXPRESSION3)
This can be refactored safely to
VARIABLE1 = [EXPRESSION3 for VARIABLE2 in EXPRESSION1 if EXPRESSION2]
In your specific example, this would give
bigNumbers = [myList[i] for i in xrange(0, len(myList)) if myList[i] > 10]
Then, you can have another refactoring that replaces xrange(0, N) with xrange(N),
and another one that replaces
[VARIABLE1[VARIABLE2] for VARIABLE2 in xrange(len(VARIABLE1)) if EXPRESSION1]
with
[VARIABLE3 for VARIABLE3 in VARIABLE1 if EXPRESSION1PRIME]
There are several problems with this refactoring:
EXPRESSION1PRIME must be EXPRESSION1 with all occurrences of
VARIABLE1[VARIABLE2] replaced by VARIABLE3. This is possible with
2to3, but requires explicit code to do the traversal and replacement.
EXPRESSION1PRIME then must not contain no further occurrences of
VARIABLE1. This can also be checked with explicit code.
One needs to come up with a name for VARIABLE3. You have chosen x;
there is no reasonable way to have this done automatically. You could
chose to recycle VARIABLE1 (i.e. i) for that, but that may be confusing
as it suggests that i is still an index. It might work to pick a synthetic
name, such as VARIABLE1_VARIABLE2 (i.e. myList_i), and check whether
that's not used otherwise.
One needs to be sure that VARIABLE1[VARIABLE2] yields the same as you get
when using iter(VARIABLE1). It's not possible to do this automatically.
If you want to learn how to write 2to3 fixers, take a look at Lennart Regebro's book.