2014-10-01 77 views
-1

在我的程序中,我需要檢查一個用戶輸入公式以確保它是一個有效的公式。我通過使用myEquation[0].isdigitmyEquation[-1].isdigit()在開始或結束時刪除了任何運營商,但現在我需要確保沒有運營商相鄰。檢查Python中兩個字符不相鄰

我想過把'+',' - ','/','*'和'x'放到一個名爲operator的列表中,然後檢查列表中的任何內容是否相鄰,但是我沒有真的知道名單是否如此工作或如何做到這一點。

例如,如果用戶輸入"4++8-9"程序應返回False

+0

發表了一些例子。 – 2014-10-01 12:20:51

+0

請舉一些例子。 – 2014-10-01 12:21:19

回答

0

使用本:

([+-\/*x])\1+ 

演示在這裏:http://regex101.com/r/lL7bL8/2

這將取代運營商,如果他們是由一個反覆運營商

+1

我認爲他想要檢測連續的操作員,即使他們不是同一個操作員。防爆。 「a */b」是一個無效的等式。 – Kevin 2014-10-01 12:23:54

+0

@Kevin'+ -'可以是有效的,但:) :) – 2014-10-01 12:26:53

2

列表作品

operator = ['+', '-', '/', '*'] 

def is_valid_input(myEquation): 
    for c1,c2 in zip(myEquation[:-1],myEquation[1:]): 
     if c1 in operator and c2 in operator: 
      return False 
    return True 
0

給定一個字符串s其中包含一個公式,下面的代碼將迭代它並檢查沒有後續字符集合operators

from itertools import tee 

s = '2 +/3' 
operators = {'+', '-', '/', '*'} 

# Create two iterators to iterate over the string but then advance one of them with next() 
a, b = tee(s.replace(' ', '')) 
next(b) 

print(any(i in operators and j in operators for i, j in zip(a, b))) 
# True 

它使用itertools.tee建立一種可以遍歷反過來檢查鄰近字符迭代器。 any將返回True如果任何迭代返回True(在這種情況下,如果兩個相鄰字符在operators中)。

我也做了一些簡單的替換' '''考慮到誰喜歡在他們的方程中放置空格的人,這是你必須更認真思考的問題。

0

您可以生成所有對的連續字符是這樣的:

>>> eq = 'a+b*c' 
>>> zip(eq[:-1], eq[1:]) 
[('a', '+'), ('+', 'b'), ('b', '*'), ('*', 'c')] 

,那麼你只需要檢查有沒有任何的對 對於這兩個符號是運營商:

>>> def valid(eq): 
... ops = '+-*/' 
... return not any(x in ops and y in ops for x, y in zip(eq[:-1], eq[1:])) 
... 
>>> valid('a+/b') 
False 
>>> valid('a+b*c') 
True 
+0

好的答案伴隨代碼示例以及將來讀者的解釋。當問這個問題的人可能會理解你的答案時,解釋你如何到達它可能會幫助無數其他人。 – Stonz2 2014-10-01 12:56:01

0

你可以通過正則表達式來實現。

>>> import re 
>>> r = re.compile(r'^(?!.*?[-+*\/x][-+x*\/])') 
>>> if r.match('a+/b'): print 'Valid' 
... 
>>> if r.match('a+b*cxd'): print 'Valid' 
... 
Valid 

說明:

^(?!.*?[-+*\/x][-+x*\/])線的開始,只有當運營商不匹配連續存在。

相關問題