超強!略微簡練一些的代碼

來源: chirolike 2016-01-06 13:42:29 [] [博客] [舊帖] [給我悄悄話] 本文已被閱讀: 次 (1296 bytes)
本文內容已被 [ chirolike ] 在 2016-01-06 15:00:33 編輯過。如有問題,請報告版主或論壇管理刪除.
回答: 用Python解決一道小學數學題在城裏2016-01-05 20:01:05
import itertools
import re

BAD_LIST        = ['55', '5(', ')(', ')5', '(5)']
FIRST_CHAR_LIST = ['(', '-', '5']
LAST_CHAR_LIST  = [')', '5']
exp_list        = []
my_list         = [r for r in itertools.product(FIRST_CHAR_LIST, LAST_CHAR_LIST)]
init_lst        = ['5', '5', '5', '5', '5', '+', '-', '*', '/', '(', ')']

if  __name__ == '__main__':
    print '======= Possible combinations for the math question ============'
    for first, last in my_list:
        lst = list(init_lst)
        lst.remove(first)
        lst.remove(last)
        for exp in [first + ''.join(f) + last for f in itertools.permutations(lst)]:
            if  any([y in exp for y in BAD_LIST]) or\
                re.search(r'[-*/+][-*/+]+|^\(.*\)$', exp): continue
            elif exp not in exp_list:
                try:
                    print "%s = %d" % (exp, eval(exp))
                    exp_list.append(exp)
                except: pass
    print 'Total expressions found = ', len(exp_list)

所有跟帖: 

的確簡潔多了,讚! -在城裏- 給 在城裏 發送悄悄話 在城裏 的博客首頁 (0 bytes) () 01/06/2016 postreply 18:42:05

請您先登陸,再發跟帖!

發現Adblock插件

如要繼續瀏覽
請支持本站 請務必在本站關閉/移除任何Adblock

關閉Adblock後 請點擊

請參考如何關閉Adblock/Adblock plus

安裝Adblock plus用戶請點擊瀏覽器圖標
選擇“Disable on www.wenxuecity.com”

安裝Adblock用戶請點擊圖標
選擇“don't run on pages on this domain”