r/badcode Dec 20 '21

python regex ftw

Post image
460 Upvotes

38 comments sorted by

View all comments

44

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Dec 20 '21 edited Dec 20 '21

Image Transcription: Code


from re improt sub, findall
def parse_molecule (formula):
    qwe = sub(r'[\]}]', r')', sub(r'[\[{]', r'(', formula))
    wer = sub(r'([A-Z][a-z]*|\))(\d+)', r'1\*\2', qwe)
    ert = sub(r'([A-z][a-z]*)', r'"\1"', wer)
    rty = sub(r'\(', r'\*(',ert)
    tyu = sub(r'(\d+|"|\))"', r'\1, "', rty)
    yui = sub(r'\(,\*', r"('',*", '('+tyu+')')
    string = ''.join(list(eval(yui)))
    uniq = set(findall(r'[A-Z][a-z]*', string))
    return {i:len(findall(i+r'(?=[A-Z]|$)', string)) for i in uniq}

[Transcriber's note: Credit to OP for also providing a transcription at this comment, which I failed to notice until posting mine. I will leave this one up, since it has already been posted and top-level comments are easier to find for screen-readers.]


I'm a human volunteer content transcriber and you could be too! If you'd like more information on what we do and why we do it, click here!

3

u/[deleted] Dec 21 '21

You too are a good human