I want to iterate through numbers which met a specific condition. I have done it with the following code. But it has two for loops which may not be efficient. Is it possible to make this code shorter?
for g in [i for i in range(10) if i % 2 == 0]:
print(g)
I tried the following but this syntax does not work:
for i in range(10) if i % 2 == 0:
print(i)
The second syntax is invalid, but you can split it into two lines:
for i in range(10):
if i % 2 == 0:
print(i)
If shortening your code is the motive(which shouldn't be), then here are 2 one-liners:
>>> print('\n'.join(map(str, filter(lambda x:not x%2, range(10)))))
0
2
4
6
8
or
>>> print('\n'.join(map(str, range(0, 10, 2))))
0
2
4
6
8
Related
I have list of 5 elements which could be 50000, now I want to sum all the combinations from the same list and create a dataframe from the results, so I am writing following code,
x =list(range(1,5))
t=[]
for i in x:
for j in x:
t.append((i,j,i+j))
df=pd.Dataframe(t)
The above code is generating the correct results but taking so long to execute when I have more elements in the list. Looking for the fastest way to do the same thing
Combinations can be obtained through the pandas.merge() method without using explicit loops
x = np.arange(1, 5+1)
df = pd.DataFrame(x, columns=['x']).merge(pd.Series(x, name='y'), how='cross')
df['sum'] = df.x.add(df.y)
print(df)
x y sum
0 1 1 2
1 1 2 3
2 1 3 4
3 1 4 5
4 1 5 6
5 2 1 3
6 2 2 4
...
Option 2: with itertools.product()
import itertools
num = 5
df = pd.DataFrame(itertools.product(range(1,num+1),range(1,num+1)))
df['sum'] = df[0].add(df[1])
print(df)
List Comprehension can make it faster. So, you can use t=[(i,j,i+j) for i in x for j in x] instead of for loop, as the traditional for loop is slower than list comprehensions, and nested loop is even slower. Here's the updated code in replacement of nested loops.
x =list(range(1,5))
t=[(i,j,i+j) for i in x for j in x]
df=pd.Dataframe(t)
I have a unsorted list. I'm asked to print k-times number of positive values in a segment.The boarders for segment start with 1 not 0. So, if the boarder [1,3] it means that we should find all positives among elements with indices [0,1,2]
For example,
2 -1 2 -2 3
4
1 1
1 3
2 4
1 5
The answer needs to be:
1
2
1
3
Currently, I'm creating a list with length as original where i equals 1 if original is positive and 0 if original is negative or zero. After that I sum for this segment:
lst = list(map(int, input().split()))
k = int(input())
neg = [1 if x > 0 else 0 for x in lst]
for i in range(k):
l,r = map(int, input().split())
l = l - 1
print(sum(neg[l:r]))
Despite the fact that it's the fastest code that I created so far, it is still too slow for this task. How would I optimize it (or make it faster)?
If I understand you correctly, there doesn't seem to be a lot of room for optimization. The only thing that comes to mind really is that the lst and neg steps could be combined, which would save one loop:
positive = [int(x) > 0 for x in input().split()]
k = int(input())
for i in range(k):
l, r = map(int, input().split())
print(sum(positive[l-1:r]))
We can just have bools in the positive list, because bool is just a subclass of int, meaning True is treated like 1 and False like 0. (Also I would call the list positive instead of neg.)
The complexity is still O(n) though.
I'm sorry if the title is confusing. Here's a better explanation:
So basically what I need to do is iterate through every number in list and print the biggest number west (list[0:i]) and the biggest number east. If the biggest number is smaller than i, we print i. So for list [1, 3, 2, 4, 3] the output should be:
1 4
3 4
3 4
4 4
4 3
I thought my code was correct but it doesn't work for the last number in list, is anyone able to help?
'a' is the list in my code
a = [1, 3, 2, 4, 3]
for i in a:
west = a[0:i]
east = a[i:int(len(a))]
if max(west) > i:
print(max(west))
else:
print(i)
if max(east) > i:
print(max(east))
else:
print(i)
Try:
for i in range(len(a)):
print(max(a[:i+1]))
print(max(a[i:]))
You are not iterating over the indices in your original code; and thus the partition does not make sense.
The only mistake in your code is the for i in a loop, which loops throgh i = 1,3,2,4,3 and not i=0,1,2,3,4
The following piece of code works
a=[1,3,2,4,3]
for i in range(len(a)) :
print max(i,max(a[:i+1]))
print max(i,max(a[i:]))
this may work... not fully tested but it looks correct
a = [1, 3, 2, 4, 3]
for i in a[:-1]:
west = a[0:i]
east = a[i:int(len(a))]
if max(west) > i:
print(max(west))
else:
print(i)
if max(east) > i:
print(max(east))
else:
print(i)
num = a[-1]
west = a[0:-1]
if max(west) > num:
print(max(west))
else:
print(str(a[-1]))
print(str(a[-1]))
Output: 1 4 3 4 4 4 4 3
How can I write the for loop in Python as I write it in C:
for(i=0;i<10;)
{
if(i%2==0)
i=i+3;
else
i++;
printf("%d\n",i);
}
Can anyone tell me about this? I searched a lot but couldn't find it. I wrote it like this in Python:
for i in range(0,10):
if (i%2==0):
i+=3
else:
i+=1
print i
Output:
3
2
5
4
7
6
9
8
11
10
Expected output:
3
4
7
8
11
Can anyone also explain the reason of this output?
To write the same loop in Python:
i = 0
while i < 10:
if i % 2 == 0:
i += 3
else:
i += 1
print i
Which gives:
3
4
7
8
11
Note that, per the tutorial:
The for statement in Python differs a bit from what you may be used to
in C or Pascal. Rather than always iterating over an arithmetic
progression of numbers (like in Pascal), or giving the user the
ability to define both the iteration step and halting condition (as
C), Python’s for statement iterates over the items of any sequence (a
list or a string), in the order that they appear in the sequence.
In a Python for loop, any changes to the loop variable (i, in this case) that occur during the loop are ignored when the loop repeats, and the next value from the object being iterated over is used. In this case, the object is a list of numbers:
>>> range(10) # note that a 0 start is the default
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Some languages call this a for each loop. See also the language reference for more details.
range(0, 10) function returns list of values from 0 to 9:
range(0, 10) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Then for body is executed for each element in this list.
If You have 0, the 0 % 2 == 0 so it prints 0 + 3 etc.
In C You changed i value so You jumped to other value in set. Using python's for You will get through all elements. You should use
i = 0
while i < 10:
if (i % 2 == 0):
i += 3
else:
i += 1
print i
To have same results as in C
try this
for i in range(10):
if i%2 == 0:
i = i+3
else:
i = i + 1
print i
it gives the same output u asked for...hope this helps
I have a sorted list like this
s = [1 , 4 ,6 , 9 ,10 ]
I want to know if either a number is present in the list or if it is present in between two numbers. If it is present in between two numbers, I want to print them out.
Right now my code looks like this
for x in s:
if b == x: \\ b is the number
print b
elif b > x and b < s[s.index(x) + 1] and s.index(x) < len(s):
print b , s[s.index(x) + 1]
Is there a better way to do so?
bisect module does exactly that:
s = [1 , 4 ,6 , 9 ,10 ]
import bisect
x = 5
n = bisect.bisect_left(s, x)
if s[n:n+1] == [x]:
print x, 'is in the list'
else:
print x, 'comes between', s[n-1:n], 'and', s[n:n+1]
This is not perfect optimized, but you can avoid using index() method many times!
for i,j in enumerate(s,1):
if b == j: \\ b is the number
print b
elif b > j and b < s[i+1] and s[i] < len(s):
print b , s[i + 1]