0

So me and my buddy are helping each other learn about programming, and we have been coming up with challenges for ourselves. He came up with one where there are 20 switches. We need to write a program that first hits every other switch, and then every third switch, and then every fourth switch and have it output which are on and off.

I have the basic idea in my head about how to proceed but, I'm not entirely sure how to pick out every other/3rd/4th value from the list. I think once I get that small piece figured out the rest should be easy.

Here's the list:

start_list = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

I know I can select each element by doing:

start_list[2]

But then, how do I choose every other element, and then increment it by 1?

Rubens
  • 14,478
  • 11
  • 63
  • 92
Spurnout
  • 23
  • 4

3 Answers3

2

Use Python's List Slicing Notation:

start_list[::2]

Slicing goes as [start:stop:step]. [::2] means, from the beginning until the end, get every second element. This returns every second element.

I'm sure you can figure out how to get every third and fourth values :p.


To change the values of each, you can do this:

>>> start_list[::2] = len(start_list[::2])*[1]
>>> start_list
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0]
Community
  • 1
  • 1
TerryA
  • 58,805
  • 11
  • 114
  • 143
  • Ok, so I have that part down but I can't figure out how to increment each of those numbers by 1 now. – Spurnout Jul 08 '13 at 23:50
  • Great! That works! Just need to analyst it so that I understand what's going on there. Also, just one more question and I should be good to go. Is it possible to have it start with the 2nd number? so it's 0,1... – Spurnout Jul 08 '13 at 23:54
  • @Spurnout Yes! Just do `start_list[1::2]`. The beauty of slicing! – TerryA Jul 08 '13 at 23:54
  • We got a winner here! Thank you Haidro! – Spurnout Jul 09 '13 at 00:05
1

Every other switch:

mylist[::2]

Every third:

mylist[::3]

You can assign to it too:

mylist=[1,2,3,4]
mylist[::2]=[7,8]
Tiago
  • 212
  • 4
  • 16
  • start_list[::2]=[1]*((len(start_list)+1)/2) - You need to provide a list of the correct length when assigning to a slice. – Tiago Jul 08 '13 at 23:50
  • Thanks Tiago, I get this output when running that. TypeError: can't multiply sequence by non-int of type 'float' – Spurnout Jul 08 '13 at 23:51
  • Sorry, I am still working with python 2. In python 3 the int division get a float result. You should replace the '/' operator with the '// – Tiago Jul 08 '13 at 23:57
1
>>> start_list = [0] * 20
>>> for i in range(2, len(start_list)):
...     start_list[::i] = [1-x for x in start_list[::i]]
... 
>>> start_list
[0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1]
John La Rooy
  • 295,403
  • 53
  • 369
  • 502