Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding Adjacent Numbers in a Python String

I am attempting to code a FEN number calculator based on a board:

boardPeices = ['br', 'bn', 'bb', 'bq', 'bk', 'bb', 'bn', 'br',
                'bp', 'bp', 'bp', 'bp', 'bp','bp', 'bp', 'bp',
                ' ', ' ', ' ', ' ', ' ',' ', ' ', ' ',
                ' ', ' ', ' ', ' ', ' ',' ', ' ', ' ',
                ' ', ' ', ' ', ' ', ' ',' ', ' ', ' ',
                ' ', ' ', ' ', ' ', ' ',' ', ' ', ' ',
                'wp', 'wp', 'wp', 'wp', 'wp','wp', 'wp', 'wp',
                'wr', 'wn', 'wb', 'wq', 'wk','wb', 'wn', 'wr',
            ]

and have gotten pretty far, to where I have 8 stings, each with a row of the FEN number. Currently, the below code prints this: rnbqkbnr/pppppppp/11111111/11111111/11111111/11111111/PPPPPPPP/RNBQKBNR

print(f'{fenRow1}/{fenRow2}/{fenRow3}/{fenRow4}/{fenRow5}/{fenRow6}/{fenRow7}/{fenRow8}')

The problem is, the FEN number’s ones should be concentrated into 8’s, as there are 8 numbers next to each other. Due to everything being in strings, I cannot figure out how to add the 8 numbers together, in a way that a different position would still work, where the numbers are separated (ie, after e4)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use itertools.groupby:

from itertools import groupby

s = 'rnbqkbnr/pppppppp/11111111/11111111/11111111/11111111/PPPPPPPP/RNBQKBNR'

out = ''.join([x for k, g in groupby(s, lambda x: x=='1')
               for x in ([str(len(list(g)))] if k else list(g))])

Output:

'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR'

Example on another input (s = 'rnbqkbnr/ppp1pppp/111p1111/11111111/11111111/11111111/PPPPPPPP/RNBQKBNR'):

'rnbqkbnr/ppp1pppp/3p4/8/8/8/PPPPPPPP/RNBQKBNR'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading