Re: [討論] 用python找出一串數字中最長的"二數數串"

看板Python作者 (朱子)時間12年前 (2013/09/26 17:48), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串4/5 (看更多)
numstring = '889988899278392520771323543282829292222943485709' results = [] numset = set() for start in range(len(numstring)): for end in range(start,len(numstring)): numset.add(numstring[end]) if len(numset)>2: break results.append((start,end)) numset.clear() max_length = max([end-start for (start,end) in results]) max_intervals = [(start,end) for (start,end) in results if end-start==max_length] for start,end in max_intervals: print numstring[start:end] ※ 引述《uranusjr (←這人是超級笨蛋)》之銘言: : 我前陣子 (PyConTW 的時候) 才知道 collections 有一個很 IMBA 的東西叫 Counter : import sys : from collections import Counter : numstr = sys.argv[-1] # 這裡讀入要算的字串 : matches = [''] : for start in range(len(numstr)): : for end in range(start + 1, len(numstr) + 1): : substring = numstr[start:end] : counter = Counter(substring) : if len(counter) != 2: : continue : if len(matches[0]) < len(substring): : matches = [substring] : elif len(matches[0]) == len(substring): : matches.append(substring) : print('{count} matches (of length {length}):' : .format(count=len(matches), length=len(matches[0]))) : for match in matches: : print match : 淺顯易懂 : ※ 引述《dadadavid (大大大衛)》之銘言: : : numstring = "889988899278392520771323543282829292222943485709" : : def ngram(n, iter_tokens): : : """Return a generator of n-gram from an iterable""" : : z = len(iter_tokens) : : return (iter_tokens[i:i+n] for i in xrange(z-n+1)) : : for i in range(len(numstring), 1, -1): : : results = [ng for ng in ngram(i, numstring) if len(set(ng))==2] : : if len(results) > 0: : : print results : : break -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.125.33
文章代碼(AID): #1IH0BUWq (Python)
文章代碼(AID): #1IH0BUWq (Python)