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
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 months ago.
Improve this question
The question I was given requires me to get an output within 3 secs
The constraint given is 2<= len(a) <= 5000000 and 1 <= a[i] <= 10**9
Below is the code I have written. I belive that the Big O efficiency of this code is linear or O(n) as I am only using one for loop. Is that the case? If can it run the max input size within 3 secs?
line = input()
m = line.split()
m.sort()
smallest_diff = 10 ** 9
for i in range(len(m)-1):
diff = abs(int(m[i]) - int(m[i+1]))
if diff < smallest_diff:
smallest_diff = diff
else:
smallest_diff = smallest_diff
if i+1 > len(m):
break
print(smallest_diff)
Your runtime complexity is currently O(N log(N)), dominated by the sort call. You're correct that the main work loop takes only O(N) time. However, the input size of 5*10^6 will be close to the borderline for what Python can get done in 3 seconds; you
I actually suspect your input loading may be eating up a lot of time. That's not an asymptotics issue; input is just often pretty slow. Here are things I'd try:
Check whether the website you're submitting to allows you to use PyPy instead of regular Python. You could still submit the same code either way, but it'll probably run a lot faster in PyPy.
Replace your first 2 lines with m = map(int, input().split()). This stores a list of int instead of string. ints make your code less memory-intensive and ints are what you want to use anyway. There are some more advanced tricks you could try to make the input loading steps even faster, like using BytesIO, but I'm just mentioning for fun; you probably don't want to get into that right now.
You currently have a few other unnecessary lines of code that slow your program down slightly, but they won't affect the runtime much.
Bonus note: I don't know the exact problem you're trying to solve, but your code probably has a bug where you sort the data. Your m is a list of strings, not ints, so for example your code would consider this array to be already sorted: ['10', '3'] (because the string '10' comes before the string '3'). This bug would be fixed as a side effect of my suggestion (2) above, since if you store the data as ints then you'd instead get [3, 10] which I'm pretty sure is what you're intending.
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.
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 4 years ago.
Improve this question
i am having an issue figuring out why my code is wrong.
def draw_poly(t, n, size):
for s in (n):
t.forward(sz)
t.left(45)
draw_poly (liz, 8, 50)
I am trying to make a octogon but it keeps on giving me an "'int' object is not iterable" error.
If you could help i would be forever grateful, Thanks.
The for-loop:
for s in (n):
Expects n to be some sort of iterable: a list, tuple, dictionary, etc, but you are passing an integer (int) - hence the error.
If you want s to take the values 0, 1, 2, ..., n then you should use the range() function to produce an iterable sequence of the numbers up to the number passed into it.
Therefore, what your probably want is:
for s in range(n):
which will allow you to work with an integer variable s in that code block.
If you want to debug your code, it often helps to print out the values of variables to check they are evaluating to what you think they should be.
For instance,
for i in range(4):
print(i)
gives:
0
1
2
3
which is to be expected.
The correct int iterable would be range(int), so, use this: for s in range(n):
For the future using of range(): this function creates a list of iterable int objects. In some cases using of xrange() is better, especially for large loops.
I.e. range(1000000000) creates a huge object in memory while xrange(1000000000) does not, though it works in a similar way giving you int numbers one by one.
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 5 years ago.
Improve this question
While programming in python 3.6, I came across with some problem in list :
l = [2,2,3,3,3]
for n in range(len(l)):
print(l[n+1]) #increasing value of n by 1
This code will obviously give an error :
IndexError: list index out of range
But in case of c language :
#include<stdio.h>
int main() {
int i =0;
int arr[5] = {1,2,3,4,5};
for(i = 0 ; i<=4;i++){
printf("%d " , arr[i+1]);
}
return(0);
}
Gives the correct output(including garbage value):
2 3 4 5 32764
I wanted to know why are we not getting the value of elements of list in python by using the future values of n whereas in c it is just reverse?
In C, an "array" is mainly a pointer to a memory location (nb: this is an obvious simplification, you can read this for more details), and arr[x] will return N bytes from address_of_arr + (N * x) (where N is the size of the array data type). Like all memory access in C, there's absolutely NO check so you can read (and write) just any arbitrary memory location.
Note that, as Daniel Pryden mentions in a comment, the behaviour you observe with your C example is called an "undefined behaviour", which means the result is not defined by the C langage specs, depends on the implementation (your C compiler, platform and whatnots), and could actually yield just any result (including a core dump, erasing your hard drive or launching a nuclear missile). Luckily the implementation you tested it with just returns garbage. Now if you really feel lucky, for a bit of fun try writing at this memory location and find out what happens ;)
In Python, a list is an object which knows it's length and won't let you try to access items at indexes that don't exist. Where and how the effective list contents are stored in memory is handled by the implementation and is totally opaque to the Python code.
Disclaimer : this answer is based on C implementations most commonly found on today's operating systems - the C language spec doesn't specify anything about how an array should be implemented (just how it's supposed to work) so an implementation could as well choose to store array datas on clay tablets disposed on a rubber band and move that rubber band by N positions left or right, in which case my answer would be totally irrelevant...
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))