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

How to make my code more simple by using a loop or someting else?

I have to return a symbol from a dictionary of lists when I am given a [x, y] coordinate. The dictionary of lists is this :

GOBBLET_REPRESENTATION = {
    1: ["▫", "◇", "◯", "□"],
    2: ["▪", "◆", "●", "■"],
}

Here is what I tried:

def formate_gobblet(gobblet):
    if gobblet == []:
        return "   "
    else:
        if gobblet == [1,0]:
            return f' {GOBBLET_REPRESENTATION.get(1)[0]} '
        elif gobblet == [1,1]:
            return f' {GOBBLET_REPRESENTATION.get(1)[1]} '
        elif gobblet == [1,2]:
            return f' {GOBBLET_REPRESENTATION.get(1)[2]} '
        elif gobblet == [1,3]:
            return f' {GOBBLET_REPRESENTATION.get(1)[3]} '
        elif gobblet == [2,0]:
            return f' {GOBBLET_REPRESENTATION.get(2)[0]} '
        elif gobblet == [2,1]:
            return f' {GOBBLET_REPRESENTATION.get(2)[1]} '
        elif gobblet == [2,2]:
            return f' {GOBBLET_REPRESENTATION.get(2)[2]} '
        elif gobblet == [2,3]:
            return f' {GOBBLET_REPRESENTATION.get(2)[3]} '

Having formate_gobblet(gobblet) with gobblet = [1,2] should return ◯ . This code does that but, I was wandering if there was a way to make my code simpler for the else statement since it looks like this could be resolved using a loop.

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 do not need a loop for this. In fact, this can be done in one line using indexing itself.

def formate_gobblet(gobblet):
    if gobblet == []:
        return "   "
    else:
        return return f' {GOBBLET_REPRESENTATION.get(gobblet[0])[gobblet[1]]}  '

What the code above does is it checks for an empty gobbletotherwise returns the representation which is at the position pointed by the first element gobblet[0] and the second element gobblet[1]

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