How do you select every other number using loops? Lets say we have a sequence of 8 digits, 12345678
How do we select alternate numbers starting from the right and add them? Therefore we would have to add 8 + 6 + 4 + 2.
Asked
Active
Viewed 2,113 times
-3

Marcello B.
- 4,177
- 11
- 45
- 65

GopherTech
- 59
- 1
- 3
- 16
-
addition doesnt care about order ... you get the same answer regardless of order – Joran Beasley Sep 18 '15 at 22:35
-
Why are you adding `2` twice and skipping `4`? – Barmar Sep 18 '15 at 22:44
-
@Barmar Sorry, my bad. I corrected it. – GopherTech Sep 18 '15 at 22:44
-
possible duplicate of [How do get more control over loop increments in Python?](http://stackoverflow.com/questions/4930404/how-do-get-more-control-over-loop-increments-in-python) – Prune Sep 18 '15 at 22:56
3 Answers
3
reduce(sum,a[-1::-2])
explain to teacher that under the hood both filter and sum are loops
see also the following
https://docs.python.org/2/tutorial/introduction.html#lists
http://pythoncentral.io/how-to-slice-listsarrays-and-tuples-in-python/
https://docs.python.org/2.3/whatsnew/section-slices.html
in answer to your other question
def isvalid(c):
return not (sum(c[-1::-2])+sum(map(int,"".join(map(str,(2*x for x in c[-2::-2] ))))))%10
def get_cc_num():
while True:
try: return map(int,raw_input("enter 8 digit number"))
except ValueError:print "Invalid number"
print isvalid(get_cc_num())

Joran Beasley
- 110,522
- 12
- 160
- 179
-
Thank you. How would we write it as the addition of alternate numbers? why did we use -1 and -2? – GopherTech Sep 18 '15 at 22:54
-
it means start at the end (a[-1]) and go to the begining, and each time step -2 places – Joran Beasley Sep 18 '15 at 22:57
-
Thank You. This is part of the original problem I am working on here http://stackoverflow.com/questions/32658339/using-loops-in-python-to-configure-credit-card-number Would you please take a look at my code and help? – GopherTech Sep 18 '15 at 22:58
-
-
Oh I see. Sorry we aren't supposed to use def and return statements as we havent gone through them yet. Only for and while loops. Sorry for being a pain but I have been trying to do this code since 9 this morning before posting it here 4 hours ago. – GopherTech Sep 18 '15 at 23:25
1
Use python's built in range([start], stop [, step]) method.
You can iterate backwards from 8 to 1 in steps of -2
like this:
total=sum(range(8, 0, -2))
Or forward from 1 to 8 in steps of 2 like this:
total=sum(range(2, 9, 2))

asdf
- 2,927
- 2
- 21
- 42
-
Thank you, and just for knowledge, why did we enter 8, 0, -2 inside the bracket?Very new to Python but developing a love for it – GopherTech Sep 18 '15 at 22:31
-
@JoshShroeder Those are the start, end, and stepping parameters for the function. – Barmar Sep 18 '15 at 22:42