Cumulative values in for loop? [closed] - python

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Is there a way to get the "cumulative" values in a Python for-loop? In Java there is the way of += to a variable during each loop iteration and it would continue to add it on. Is there an option like this available in Python?

So many ways. Python calls these the "in-place" operators.
You've also got functional approaches like sum and more general accumulators like reduce, which in Python 3 moved to functools.
acc = 0
for i in range(10):
acc += i
or
acc = sum(range(10))
or
from operator import add
from functools import reduce
acc = reduce(add, range(10))

Yes, there is a += operator in Python.
x = 0
for i in range(10):
x += 1
print x

foo = 0
for i in range(0, 12):
foo += 1
print(foo)

for i in range(0, 5):
print i
Output:
0
1
2
3
4
Or, if you want to go by more than one:
for i in range(0, 10, 2):
print i
Output:
0
2
4
6
8

Related

Assigning variable in python confusion [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 3 years ago.
Improve this question
I am trying to understand how a code works. I saw a variable declaration like the one below in the code, but don't understand how that works.
what is the difference between
m += 1
and
1 += m
So if m = 5, then m becomes 6:
m += 1
means you're incrementing m by 1 (post-increment)
its the same thing as:
m = m + 1
You can't assign:
1 += m
that's an illegal operation, the error you should see is:
SyntaxError: can't assign to literal
1 += m is not a correct syntax. You may get an Error something like: SyntaxError: can't assign to literal.
In general,
m += 1
means
m = m + 1,
therefore,
1 += m
means
1 = 1 + m which is syntactically wrong because you can not assign anything into an integer literal.

Convert a List to integer without using map() or join() [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 4 years ago.
Improve this question
if I have
list=[1,2,3,4,5,6]
How can i make it
list=123456
Thanks for your help in advance!
You can do this:
inlist=[1,2,3,4,5,6]
length = len(inlist)
s = 0
for i in range(length):
s += (inlist[i] * ( 10 ** (length-1-i)))
inlist = s
print(inlist)
This will give you:
123456
You need to utilize the power of 10 to multiply it with each number.
Note that you shouldn't use list as a variable name as it is a Python keyword.
Another version (without using any built-in functions at all):
inlist=[1,2,3,4,5,6]
count = 1
s = 0
for elem in inlist[::-1]:
s += (elem * ( 10 ** (count-1)))
count += 1
inlist = s
print(inlist)
you can do it by for and join likes the following:
int(''.join([str(i) for i in my_list]))

How to write a for loop 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 5 years ago.
Improve this question
I have a for in c++ and I want to write it in python but I don't Know how to handle the condition in the for. Can anyone help me ?
for (int b = (i - a) / 2; a + b <= i; b++);
The terminating condition a + b <= i is equivalent to b <= i - a which in turn (as Python for uses less than not less than or equal) would be b < i - a + 1.
That means in Python you could write:
for b in range((i - a) / 2, i - a + 1):
...
But very often you don't want to write like for like when converting from C/C++ to Python. You may be better to restructure the code entirely.
use while
a=something
i=something
b=(i-a)/2
while(a+b<=i):
###do whatever you want in the loop###
b+=1
You could use the for loop and range() function. Example:
for i in range(15):
#code to execute 15 times
However, because of your code, I'd recommend using a while loop instead:
i = 1 #your value for i
b = (i-a)/2
while a+b <= i:
# Other code
b+=1
Your confusion stems from the over-generality of C's iteration construct. Python insists that all loop parameters implicitly refer to the loop index. For the terminating condition, solve your inequality in terms of b, and without equality: b < i - a + 1
Now we get the for loop
for b in range((i-a)/2, (i-a)+1):
One interpretation is that you have a range from 0 to i-a, and you want to deal with the upper half of that.
To answer your question directly:
for b in range((i-a)/2,a+b-1):
print (b)
And if, for some reason, you need a terminating value:
terminatingValue = 0
for b in range((i-a)/2,a+b-1):
terminatingValue = b
print (b)

Python FOR Loop [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
I know the similar question has been asked before and I looked through a lot of previous questions but couldn't find the answer hence I am posting it.
I have a basic question about for loop. I have been using VBA for a long time and recently have to learn Python for work. I will need to use FOR LOOP in the middle of the code and looks like there in no NEXT following the FOR in python. For example, this is what the code looks like in VBA:
sub test()
dim i as integer
dim j as integer
for I = 1 to 10
j = j+i
Next
.
Print(j)
.
.
'rest of the code
end
Can someone please tell me how to define the FOR LOOP in the middle of the code? Thanks
Python alternative for your function
def test():
for i in range(1, 10):
print(i)
Note out that python has no variable declaration as it is not strongly-typed language.
Also instead of next it has indentation as depth of execution.
In python for loop are used over iterable object or generator.
List:
num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for x in num:
print x
Generator:
for x in range(10):
print x
For more example, see https://wiki.python.org/moin/ForLoop
Your question not very clear, so if this does not answer your question do not hesitate to edit your message.
This will also do your job.
for i in range(10): # from 0 to 9.
j = j + i

How to limit the no. of times cycle should run in python [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 6 years ago.
Improve this question
from itertools import count,repeat,cycle
for i in cycle("raghav"):
print(i)
if len(i) >= 6:
break
My code is running infinitely even though i have limit the len, I have also tried count(i) >= 6 but then it returns an error:
TypeError: a number is required
Set up a count object outside the loop and use its next method:
from itertools import count, cycle
c = count()
for i in cycle("raghav"):
print(i)
if next(c) >= 6:
break
len(i) will always be 1 as i is just one character in 'raghav'. If you just want it to print out 'raghav' letter-by-letter, as it seems, you can do this
for i in 'raghav':
print(i)
You can slice the itertools.cycle object using itertools.islice:
>>> from itertools import cycle, islice
>>> for i in islice(cycle('raghav'), 6):
print (i)
...
r
a
g
h
a
v
for i, x in enumerate(cycle('raghav')):
print(x)
if i >= 6:
break
This is a perfect use case for enumerate
Oh, you want to repeatedly print 'raghav'. For that use repeat not cycle:
from itertools import repeat
for i, x in enumerate(repeat('raghav')):
print(x)
if i == 5:
break
Or just
for i in range(5):
print('raghav')

Categories

Resources