Je travaille avec le code qui lirait l'entrée des chaînes et calculerait si les parenthèses (en utilisant des caractères arbitraires pour ouvrir et fermer) sont équilibrées. Le but est d'inviter l'utilisateur à entrer le nombre de parenthèses sous forme de chaînes, de sorte que le compilateur calcule leur quantité et leur type (par exemple, si c'est '('
ou ')'
).Traitement de chaîne - Déterminer si les parenthèses sont équilibrées
J'ai été conseils donnés:
Hint1: introduce two counters initialized to zero in the beginning. Then explore the symbols of the string in a loop. For the current symbol increment the
left
counter by 1 if the symbol is'('
, otherwise, increment by 1 the `right' counterHint2: call a string math-like if the brackets occur like in a mathematical formula. For instance, the strings
'()'
,'(())()'
,'(()())'
are balanced, while the strings'))(())(('
and'())(()'
are not.
Mon code ressemble maintenant à ceci:
lefts =str(input("Please enter a left parenthesis: "))
rights =str(input("Please enter a right parenthesis: "))
#token parsing requires paying attention to the order of the parenthesis
def ptest(test): #testing with counters
lefts = 0
rights = 0
balance = 0 #additional counter that will help us determine the amount of strings and their relation to each other
for c in test:
if c == '(':
balance += 1
lefts += 1
elif c == ')':
balance -= 1
rights += 1
print ('testing "'+test+'"')
print ('lefts='+str(lefts)+' rights='+str(rights))
#if there will b a balance between the strings/parenthesis, they will possibly be balanced
if balance == 0: print 'same number of open/close, possibly balanced'
else: print 'different number of open/close, definitely not balanced'
ptest(test1)
ptest(test2)
Comment pourrais-je modifier ceci afin que cela fonctionnerait?
désolé j'ai modifié ma question maintenant –
duplication possible de [input() erreur - NameError: nom '...' n'est pas défini] (http://stackoverflow.com/questions/21122540/input-error-nameerror -name-is-not-defined) –
Lorsque vous entrez, donnez-le comme '(' – 0aslam0