0

Есть список: input_ = ['2', '+', '6', '/','4'].

Есть условие:

if '*' in input_ and '/' not in input_ or input_.index('/') > input_.index('*'):

Компилятор выкидывает ошибку:

if '*' in input_ and '/' not in input_ or input_.index('/') > input_.index('*'):

ValueError: '*' is not in list

Это как вообще работает?) А что дальше?

if 2 == 3:
    pass

ОШИБКА, 2 не равно 3! Так что ли?)

UPD:

Вот весь код:

def calc(input_):
    print(input_)
    if type( input_ ) == type( '' ) : 
        input_ = input_.split(' ')
    if '*' in input_ and '/' not in input_ or input_.index('/') > input_.index('*'):
        sim = input_.index('*')
        left = int ( input_.pop(sim - 1) )
        right = int ( input_.pop(sim) )
        input_[ input_.index('*') ] = left * right
        print(input_)
        calc(input_)
    elif '/' in input_:
        sim = input_.index('/')
        left = int ( input_.pop(sim - 1) )
        right = int ( input_.pop(sim) )
        input_[ input_.index('/') ] = left / right
        print(input_)
        calc(input_) 
    elif ('+' in input_) and ('*' not in input_ and '/' not in input_):
        print (input_)
        print ('+ interation')

calc('2 + 2 * 3 / 4')

2 ответа 2

1

Понял, компилятор ругается конкретно эту часть условия: or input_.index('/') > input_.index('*'): Так как '*' нет в списке, получается ошибка из-за input_index('*'). Остаётся только вкладывать условие в условие.

3
  • 1
    Правильно. Вот только не компиялтор, а интерпретатор. Используйте '*' in _index чтобы убедиться что элемент есть в списке, тогда input_.index('*') будет безопасным -- не выбросит исключение и вернет индекс элемента
    – gil9red
    20 авг 2018 в 15:39
  • @gil9red второй раз? Вот так? if '*' in input_ and '/' not in input_ or ( '*' in input_ and input_.index('/') > input_.index('*')): Работает, но выглядит очень плохо) 20 авг 2018 в 15:56
  • Например так, но мне непонятно условие (да и лениво его разбирать), поэтому не лезу советами по коду :)
    – gil9red
    20 авг 2018 в 16:57
0

Чтобы не путаться в цепочке сложных условий, индексы можно вычислить заранее

if len(input_) == 1:
    return
# прибавляем единицу, для совмещения свойств логической и позиционной переменной
operation_idx = lambda char: char in input_ and input_.index(char) + 1
multiply_idx = operation_idx('*')
divide_idx  = operation_idx('/')
if multiply_idx or divide_idx:
    if multiply_idx < divide_idx:   # умножаем
    else:                           # делим
else:
    add_idx = operation_idx('+')
    subtrac_idx  = operation_idx('-')
    if add_idx < subtrac_idx:       # сложение
    else:                           # вычитание

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.