-3

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.

Marcello B.
  • 4,177
  • 11
  • 45
  • 65
GopherTech
  • 59
  • 1
  • 3
  • 16

3 Answers3

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
  • there is an answer to your other question now as well – Joran Beasley Sep 18 '15 at 23:12
  • 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
0
sum([int(x) for i, x in enumerate(reversed('12345678')) if i % 2 == 0]
Chad Kennedy
  • 1,716
  • 13
  • 16