[Tutor] Basic Question

Mrb Rafi mrbrafi1971 at gmail.com
Fri Sep 10 12:48:56 EDT 2021


Hello Osmaan,

Are you working on this as a part of your homework?
It's just yesterday when one of my friends asked me about this game. He has
got this game as a homework in his varsity.

Rafi

On Fri, Sep 10, 2021 at 8:28 PM Peter Otten <__peter__ at web.de> wrote:

> On 10/09/2021 10:21, Alan Gauld via Tutor wrote:
> > 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
>
> > 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]
>
> Osmaan, while I agree with Alan that the if statements aren't "terrible"
> I'd like to suggest that you revisit your failed attempt to use loops:
>
> >     for na in range(a - 1, a + 1):
> >         for nb in range(b - 1, b + 1):
> >             if (na != a and nb != b) and old_arr[na][nb]:
> >                 neighbors = neighbors + 1
>
> This should work once
>
> (1) you get the range() calls right
>
> hint: Python's ranges are "half open", i. e. they do not include the
> last value:
>
>  >>> list(range(3))
> [0, 1, 2]
>  >>> a = 42
>  >>> list(range(a-1, a+1))
> [41, 42]
>
> (2) in the first condition of the if statement you only exclude the cell
> (a, b)
>
> hint: start with an expression that's true for (a, b), then negate that
> with
>
> if not (...to be done...) and old_arr[na][nb]:
>      ...
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list