[Tutor] Basic Question
Alan Gauld
alan.gauld at yahoo.co.uk
Fri Sep 10 04:21:34 EDT 2021
On 09/09/2021 22:58, Osmaan Mysorewala via Tutor wrote:
> One more question. In my get_neighbors function I use a terrible
> if-statement spam, how would I go about replacing that?
I assume you mean this section:
def get_neighbors(a, b):
neighbors = 0
if old_arr[a + 1][b] == 1:
neighbors = neighbors + 1
if old_arr[a - 1][b] == 1:
neighbors = neighbors + 1
if old_arr[a][b + 1] == 1:
neighbors = neighbors + 1
if old_arr[a][b - 1] == 1:
neighbors = neighbors + 1
if old_arr[a - 1][b - 1] == 1:
neighbors = neighbors + 1
if old_arr[a + 1][b - 1] == 1:
neighbors = neighbors + 1
if old_arr[a - 1][b + 1] == 1:
neighbors = neighbors + 1
if old_arr[a + 1][b + 1] == 1:
neighbors = neighbors + 1
I don't think its terrible but it can be tidied up provided
the values you store are zero and one. Then you can miss
out the if statements and replace them with addition:
neighbors = neighbors + old_arr[a + 1][b] # or using +=...
neighbours += old_arr[a - 1][b]
neighbours += old_arr[a][b+1]
neighbours += old_arr[a][b-1]
neighbours += old_arr[a - 1][b-1]
neighbours += old_arr[a + 1][b-1]
neighbours += old_arr[a - 1][b+1]
neighbours += old_arr[a + 1][b+1]
HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list