Combine 2 for loops in python [closed] - python

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 4 months ago.
Improve this question
In C, I can do
for(i=0, j=0; i < k; i++, j++) {
// do stuff
}
Is there an equivalent of that in Python?

If you mean exactly what you wrote, then not really, because Python does not have C-style loop.
If you actually mean something like "iterate on two collections at the same time" then yes: you compose the two collections into one iterator using zip or zip_longuest:
for a, b in zip(x, y):
...
That works with arbitrary collections so e.g.
for i, j in zip(range(k), itertools.count()):
...
will perform the same traversal of i and j your C example does, assuming the loop body does not actually update either. Which obviously makes your example not very useful, because i and j always have the same value.
If i and j need to be updated during the loop, then your only recourse is to use a fully desugared while loop and manual increment, possibly an offset rather than two counters. Because, again, Python doesn't have C-style loops.

Related

runtime of using [::-1] on a list [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
prepping for interviews and this is something i couldnt find. https://blog.finxter.com/python-list-reverse/#:~:text=The%20time%20complexity%20of%20the,the%20number%20of%20list%20elements. says .reverse() is the O(n) which I assume is because it replaces every index. is [::-1] just printing the list backwards or is something similar going on
list.reverse operates in place. That means that it almost certainly does something like this under the hood:
for i in range(len(self) // 2):
j = len(self) - 1 - i
self[i], self[j] = self[j], self[i]
The actual method is implemented in C, so of course it will be much more verbose, especially in the swapping operation.
list[::-1] creates a copy of the original. The idea is similar, but since the reversal of not in place, you have the luxury of just writing to a destination index rather than swapping via a temporary object:
new = [None] * len(self)
for i in range(len(self)):
j = len(self) - 1 - i
new[j] = self[i]
The actual slice processing code is much more complex since it has to be able to accept integers and all sorts of unorthodox slice expressions that set custom start and stop bounds, and step sizes.

Is there some benefits for using enumerate instead of range in python? [duplicate]

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 8 years ago.
Improve this question
Could you please tell me why it is considered as "not pythonic" when I need the index and the value when looping over a list and use:
a = [1,2,3]
for i in range(len(a)):
# i is the idx
# a[i] is the value
but rather it is recommended to use
for idx, val in enumerate(a):
print idx, val
who defines "pythonic" and why is the latter one better? I mean it's not that much better concerning readability, is it!?
Thanks in advance
First of all, the first way is ugly: You either need a separate variable assignment to get the element or use a[i] all the time which could theoretically be an expensive operation. Imagine a being a database cursor: When you iterate it (a.__iter__ being called) the object can safely assume that you are going to iterate over all its items. So all or at least multiple rows could be retrieved at once. When getting the length such an optimization would be stupid though since you surely don't want to retrieve data just because you want the number of items. Also, when retrieving a specific item you cannot assume that other items will be retrieved, too.
Additionally, using enumerate() works with any iterable while range(len()) only works with countable, indexable objects.

What is the equivalent C/C++ loselose algorithm in python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
For a particular reason I am trying to find (not exhaustively) the worst hash algorithm. I found this post analyzing some, and I targeted the Loselose algorithm. This page states the algorithm in C (I think) as:
unsigned long hash(unsigned char *str)
{
unsigned int hash = 0;
int c;
while (c = *str++)
hash += c;
return hash;
}
I'm not a programmer, and C (or C++ ?) of this block is killing me. Could you please give me a help and provide the equivalent in python?
PS.: For those asking "why the worst hash?",I intend to create set2, an "equivalent" to an original set1, but reduced in elements due to high algorithm hash collisions. I don't need to go back to the original set1. I just need to know if a hash is present in set2.
The C++ code that you have provided simply iterates over each character of the given string and adds its ASCII value to the variable hash and returns the hash.
We can achieve the same in Python 2.7 by doing this:
def custom_hash(s):
hsh = 0
for c in s: hsh += ord(c)
return hsh
Or you can always try to be Pythonic and do the same in one line :)
hsh = reduce(lambda x, y: ord(x) + ord(y), list(s))

Loop for in Python with php [closed]

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 7 years ago.
Improve this question
How to do loop like: for(i = 0; i < 100; i++)?
This code is in PHP, i want create this loop like in Python 3x.
Thanks my brothers for any what you do for me.
Use the built-in range function which takes an optional step and an interval [a, b) like so:
for i in range(0, 100, 1):
# do something
A range based for loop in python is not equivalent to C like for loop that is prevalent in javascript, php or languages as such which supports them. Particularly, the distinction comes in
when the need comes to change the iterator variable inside the loop block
Condition is more complex beyond a limiting condition
Ideally the best alternative is to re-write the for loop to a while loop in the similar way as you would have written in languages that supports both. For example
for(<initializer>; <cond>; <increment>) {
// Loop Body
}
should equivalently be written as
<initializer>
while cond:
<Loop Body>
<increment>
so in your particular case, the equivalent of the php for(i = 0; i < 100; i++) construct in python would be
i = 0
while i < 100:
# Loop Body
i += 1
Using any other construct might have some surprising consequences.
for i in range(100):
# code here

Pythonic: range vs enumerate in python for loop [closed]

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 8 years ago.
Improve this question
Could you please tell me why it is considered as "not pythonic" when I need the index and the value when looping over a list and use:
a = [1,2,3]
for i in range(len(a)):
# i is the idx
# a[i] is the value
but rather it is recommended to use
for idx, val in enumerate(a):
print idx, val
who defines "pythonic" and why is the latter one better? I mean it's not that much better concerning readability, is it!?
Thanks in advance
First of all, the first way is ugly: You either need a separate variable assignment to get the element or use a[i] all the time which could theoretically be an expensive operation. Imagine a being a database cursor: When you iterate it (a.__iter__ being called) the object can safely assume that you are going to iterate over all its items. So all or at least multiple rows could be retrieved at once. When getting the length such an optimization would be stupid though since you surely don't want to retrieve data just because you want the number of items. Also, when retrieving a specific item you cannot assume that other items will be retrieved, too.
Additionally, using enumerate() works with any iterable while range(len()) only works with countable, indexable objects.

Categories

Resources