>>> infix_2_prefix("a+b^c") # doctest: +NORMALIZE_WHITESPACE Symbol | Stack | Postfix ---------------------------- c | | c ^ | ^ | c b | ^ | cb + | + | cb^ a | + | cb^a | | c
(infix: str)
| 125 | |
| 126 | |
| 127 | def infix_2_prefix(infix: str) -> str: |
| 128 | """ |
| 129 | >>> infix_2_prefix("a+b^c") # doctest: +NORMALIZE_WHITESPACE |
| 130 | Symbol | Stack | Postfix |
| 131 | ---------------------------- |
| 132 | c | | c |
| 133 | ^ | ^ | c |
| 134 | b | ^ | cb |
| 135 | + | + | cb^ |
| 136 | a | + | cb^a |
| 137 | | | cb^a+ |
| 138 | '+a^bc' |
| 139 | |
| 140 | >>> infix_2_prefix("1*((-a)*2+b)") # doctest: +NORMALIZE_WHITESPACE |
| 141 | Symbol | Stack | Postfix |
| 142 | ------------------------------------------- |
| 143 | ( | ( | |
| 144 | b | ( | b |
| 145 | + | (+ | b |
| 146 | 2 | (+ | b2 |
| 147 | * | (+* | b2 |
| 148 | ( | (+*( | b2 |
| 149 | a | (+*( | b2a |
| 150 | - | (+*(- | b2a |
| 151 | ) | (+* | b2a- |
| 152 | ) | | b2a-*+ |
| 153 | * | * | b2a-*+ |
| 154 | 1 | * | b2a-*+1 |
| 155 | | | b2a-*+1* |
| 156 | '*1+*-a2b' |
| 157 | |
| 158 | >>> infix_2_prefix('') |
| 159 | Symbol | Stack | Postfix |
| 160 | ---------------------------- |
| 161 | '' |
| 162 | |
| 163 | >>> infix_2_prefix('(()') |
| 164 | Traceback (most recent call last): |
| 165 | ... |
| 166 | IndexError: list index out of range |
| 167 | |
| 168 | >>> infix_2_prefix('())') |
| 169 | Traceback (most recent call last): |
| 170 | ... |
| 171 | ValueError: invalid expression |
| 172 | """ |
| 173 | reversed_infix = list(infix[::-1]) # reverse the infix equation |
| 174 | |
| 175 | for i in range(len(reversed_infix)): |
| 176 | if reversed_infix[i] == "(": |
| 177 | reversed_infix[i] = ")" # change "(" to ")" |
| 178 | elif reversed_infix[i] == ")": |
| 179 | reversed_infix[i] = "(" # change ")" to "(" |
| 180 | |
| 181 | # call infix_2_postfix on Infix, return reverse of Postfix |
| 182 | return (infix_2_postfix("".join(reversed_infix)))[::-1] |
| 183 | |
| 184 |
no test coverage detected