python challenge qn for loop
<p>EDIT: I SOLVED THE QUESTION BUT I WOULD APPRECIATE IF SOMEONE COULD JUST HELP ME MAKE MY CODE AS SHORT AS POSSIBLE (THE CHALLENGE WAS TO CODE IT WITH THE LEAST POSSIBLE CHARACTERS).</p>

<p>I was going through some python challenges online and I came across this question.</p>

<p><a href="https://i.stack.imgur.com/wGw4F.png" rel="nofollow">Click here to view the challenge question</a></p>

<p>I have been trying to solve it for quite a while but I am stuck in one place (heres my code):</p>

<pre><code>c = ['H','H','H','H','H','H','H','I','H','H','H','H','F','H','H','H','H','H','H','H','H','H','H','H','H',]
c_copy = list(c)

def prt():
    print("\n"+c[0]+"\t"+c[1]+"\t"+c[2]+"\t"+c[3]+"\t"+c[4]+"\n"+
          c[5]+"\t"+c[6]+"\t"+c[7]+"\t"+c[8]+"\t"+c[9]+"\n"+
          c[10]+"\t"+c[11]+"\t"+c[12]+"\t"+c[13]+"\t"+c[14]+"\n"+
          c[15]+"\t"+c[16]+"\t"+c[17]+"\t"+c[18]+"\t"+c[19]+"\n"+
          c[20]+"\t"+c[21]+"\t"+c[22]+"\t"+c[23]+"\t"+c[24])

generations = 3

while generations &gt; 0:
    for x, y in enumerate(c):

        if(y == 'F'):
            c_copy[x] = 'H'

        if(y == 'I'):
            c_copy[x] = 'F'

            try:
                if(c[x+1] == 'H'):
                    c_copy[x+1] = 'I'
                if(c[x-1] == 'H'):
                    c_copy[x-1] = 'I'
                if(c[x+5] == 'H'):
                    c_copy[x+5] = 'I'
                if(c[x-5] == 'H'):
                    c_copy[x-5] = 'I'
            except IndexError:
                pass

    c = list(c_copy)         
    generations = generations - 1

    prt()
</code></pre>

<p>I know where my problem is but I cant seem to get around it. In the for loop, when i[7] == I, I change the value to its east to 'I', but when the for loop goes to i[8], it will change the value to its east again. That keeps happening until the value is not 'I'. how do I get around that? And also if someone can do the challenge in a simpler and better way, please put up your code.
Thanks</p>

<p>Here is another solution:</p>

<pre><code>import sys
# use a string to hold the flowerbed
bed = 'HHHHH' 'HHIHH' 'HHFHH' 'HHHHH' 'HHHHH'

# a function to write out a flowerbed
pr = lambda b: sys.stdout.write('\n'.join(b[x:x+5] for x in range(0, 25, 5))+'\n\n')

# make a list of the cells to check for infection, for each bed position
ckl = [ list(cc for cc in (5*(r-1)+c, 5*r+c-1, 5*r+c, 5*r+c+1, 5*(r+1)+c)
             if 0 &lt;= cc &lt; 25 and (cc // 5 ==r or cc % 5 == c))
        for r in range(5)
        for c in range(5) ]

pr(bed)    # print the initial configuration
for gen in range(5):
    bed = ''.join([ tx.get(c, 'I' if bed[i]=='H' and any([bed[n]=='I' for n in ckl[i]])
                                  else 'H')
                    for i,c in enumerate(bed) ])
    pr(bed)
</code></pre>

python for-loop