# 运营商优先级：我怎么错？

65

``````9 * 8 + 1 - 4
``````

``````(((9 * 8) + 1) - 4) = 69 (* + -)
((9 * 8) + (1 - 4)) = 69 (* - +)
((9 * (8 + 1)) - 4) = 77 (+ * -)
(9 * ((8 + 1) - 4)) = 45 (+ - *)
((9 * 8) + (1 - 4)) = 69 (- * +)
(9 * (8 + (1 - 4))) = 45 (- + *)
``````

## 技术指标

• 输入表达式将不包含括号，并且每个运算符都是左关联的。
• 输入表达式将仅包含非负整数。但是，子表达式可能会得出负数（例如`1 - 4`）。
• 您可以采用任何合理格式的表达式。例如：
• `"9 * 8 + 1 - 4"`
• `"9*8+1-4"`
• `[9, "*", 8, "+", 1, "-", 4]`
• `[9, 8, 1, 4], ["*", "+", "-"]`
• 输入将包含至少1个，最多10个运算符。
• 包含除以0或以0为模的任何表达式都将被忽略。
• 您可以假设不会对模取负数。

## 测试用例

``````9 * 8 + 1 - 4             32
1 + 3 * 4                  3
1 + 1                      0
8 - 6 + 1 * 0              8
60 / 8 % 8 * 6 % 4 * 5    63
``````

1
@AndersKaseorg `%`在第二个示例中，您好像被视为具有两个不同的优先级。

1
“六个”中的三个相同，另外两个相同。剩下三个实际案例，而不是六个。
user207421'7

3
`%`运算符如何处理负数？像C或Python之类的方式？
tsh

8

Gryphon

1
@tsh任何行为。做你想做的。你可以让恶魔从我的鼻子里飞出来

27

# Python 2中，171个 156字节

``````lambda a:max(e(a))-min(e(a))
u=')%s('
def e(a,t=u):
try:b=[eval(a)]
except:b=[]
return sum([e('(%s)'%a.replace(o,t%o),u%t)for o in"+-*/%"if' '+o in a],b)
``````

### 这个怎么运作

`+``)+(`
`*``))*((`
`-``)))-(((`

`9 * 8 + 1 - 4``(((9 ))*(( 8 )+( 1 )))-((( 4)))`= `77`

Strigoides

@Strigoides我一直认为这是不相等的，因为在`sum`没有参数为空的情况下，可能为空，但是实际上是很好的，因为`eval`在这种情况下必须失败。谢谢。
Anders Kaseorg '17

8

# 果冻，126字节

“操作员优先？括号？帕，谁需要那个？” -将果冻用于操作员优先级挑战的挑战。

``````⁾[]i\$€Ḥæ%3+\¬œp¹Ḋ€
ÇµḟØDO%9µÐṀṪɓœṣ⁹,ṚÑj@¥/
ÇµVṾµ1ĿFḟØDḟ”-Lµ?ÐL
5Ḷx@€“]“[”ż⁸j/€,@y³Fɓ³i@€Ṁ’x@“[“]”jÇ
“+_×:%”Œ!Ç€µṾL_L’ỊµÐfV€ṢIS
``````

``````5Ḷx@€“]“[”ż⁸j/€,@y³Fɓ³i@€Ṁ’x@“[“]”jÇ (4) helper link: returns all outputs given a permutation. Input e.g. "_+:×%"
5Ḷx@€“]“[”           - repeat outer brackets to get ["",""],["]","["],["]]","[["],["]]]","[[["],["]]]]","[[[["]
ż⁸j/€      - insert the operations in to get "_","]+[","]]:[[","]]]×[[[","]]]]%[[[["
,@    - turn this into a mapping equivalent to "_"↦"_","+"↦"]+[",":"↦"]]:[[","×"↦"]]]×[[[","%"↦"]]]]%[[[["
y³F - use this mapping to get the right number of outward brackets on each operation. e.g. "1]+]]×[[[4"
ɓ³i@€Ṁ’x@“[“]”j      - add the right number of brackets to the end to get e.g."[[+]]×[[]]"
Ç     - this calls the link which evaluates the expression
“+_×:%”Œ!Ç€                          (5a) main link. Input e.g. "1+3×4"
“+_×:%”                                 - the string "+_×:%"
Œ!                               - all permutations
Ç€                             - apply link (4) to each permutation
``````

``````⁾[]i\$€Ḥæ%3+\¬œp¹Ḋ€      (1) Helper link: Outputs a list of expressions within brackets, e.g. "[[+]]×[[]]"↦"[+]","[]"
⁾[]i\$€Ḥæ%3                 - map "[" to 2, "]" to -2, and any other character to 0.
+\¬              - cumulative sum negated: 1s at characters not in brackets (includes opening brackets), 0s otherwise (includes closing brackets)
œp¹           - partition the input, not including borders, based on the sum to get "[[+]","[[]"
Ḋ€         - remove opening brackets
ÇµḟØDO%9µÐṀṪɓœṣ⁹,ṚÑj@¥/ (2) Return the input to this link with one of the expressions from (1) evaluated
ÇµVṾµ1ĿFḟØDḟ”-Lµ?ÐL     (3) link called from part 1: Evaluates expressions
µ  µ          µ?          - if:
1ĿFḟØDḟ”-L            - the input contains no operators within brackets:
VṾ                         - evaluate this one expression with normal Jelly calculation and return to string
- otherwise:
Ç                            - evaluate one subexpression using link (2)
ÐL       - repeat this until a single output is determined
``````

``````µṾL_L’ỊµÐfV€ṢIS (5b) determine difference between minimum and maximum
µ      µÐf        - filter out outputs involving division or modulo by 0. Determined with:
ṾL_L’Ị           - actual numbers have their unevaled form Ṿ no more than one byte longer than the non-unevaled form.
V€      - evaluate each of these valid numbers to get integers from strings
Ṣ     - sort
IS   - return the sum of all difference between consecutive elements.
``````

4

Keyu Gan

@KeyuGan如果您想要更长的果冻答案，请查看此答案。如果没有压缩，我想不出任何其他的Jelly长答案。
fireflame241

6

# Python 2中，235个234 233 226字节

-1个字节（和一个修复）感谢Anders Kaseorg

-7个字节感谢Step Hen

``````from itertools import*
def f(e,a=()):
for o in permutations("+-*/%"):
l=e[:]
for c in o:
for i in range(len(l),0,-1):
if l[i-1]==c:l[i-2:i+1]=["("+l[i-2]+l[i-1]+l[i]+")"]
try:a+=eval(*l),
except:0
print max(a)-min(a)
``````

1

Anders Kaseorg '17

T，蒂尔。谢谢你的提示！
notjagan

1

4

``````import Data.List
f x=case x of '+'->(+);'-'->(-);'*'->(*);'/'->div;_->rem
e _ s[]=s
e 1 s")"=e 0""s
e n s(')':a)=e(n-1)(s++")")a
e 0 s('(':a)=e 1 s a
e n s('(':a)=e(n+1)(s++"(")a
e n s(x:a)=e n(s++[x])a
n?s=take n\$cycle s
a!b=e 0""(9?"("++(concat\$zipWith(++)a(b++[[]]))++9?")")
a c=transpose\$map(\x->map((\(Just q)->q).lookup x)\$map(\a->zipWith(\x y->(y,x?")"++y:x?"("))[1..5]a)\$permutations"+-*%/")c
``````

``````(#) ["9","8","1","4"] "*+-" => 32
``````

1

Esolanging水果

maple_shaft

。– maple_shaft

3

# Pyth，45个字节

``````KS.nm.x.vj\ u.nm+*H/kHckHGd]s.iFQY.p_{eQ-eKhK
``````

2

2

# 数学，186个164 159字节

``````eMax@#-Min@#&[Fold[#//.{m___,x_,#2[],y_,n___}:>{m,x~Last@#2~y,n}&,e,#]&/@Permutations@{"+"@Plus,"-"[#-#2&],"*"@Times,"/"@Quotient,"%"@Mod}/. 0/0|1/0->{}]
``````

`\[Function]` 占用3个字节。

`#2-#&@MinMax[...]` 取代 `Max@#-Min@#&[...]`

`Head@#2` 取代 `#2[]`

http://sandbox.open.wolframcloud.com上在线尝试：`( .... )[{60, "/", 8, "%", 8, "*", 6, "%", 4, "*", 5}]``....`替换为上面的测试用例代码`60 / 8 % 8 * 6 % 4 * 5`。按`Shift + enter`评估。

2

# Javascript，280个字节

``````b=>(Math.max(...(f=(a,h="(",i=")",r=[...a[d="replace"](/[^-+*/%]|(.)(?=.*\1)/g,"")])=>(r?(r.map((c,j)=>s=s.concat(f(h+a[d](RegExp("\\"+(n=r.concat()).splice(j,1),"g"),i+c+h)+i,h+"(",i+")",n)),s=[]),s):(a=eval(`(\${a})`[d](/\(/g,"Math.floor(")))==a&&1/a?a:r))(b))-Math.min(...f(b)))
``````

``````g=

b=>(Math.max(...(f=(a,h="(",i=")",r=[...a[d="replace"](/[^-+*/%]|(.)(?=.*\1)/g,"")])=>(r?(r.map((c,j)=>s=s.concat(f(h+a[d](RegExp("\\"+(n=r.concat()).splice(j,1),"g"),i+c+h)+i,h+"(",i+")",n)),s=[]),s):(a=eval(`(\${a})`[d](/\(/g,"Math.floor(")))==a&&1/a?a:r))(b))-Math.min(...f(b)))

for(k=0;k<5;k++)
v=["9*8+1-4","1+3*4","1+1","8-6+1*0","60/8%8*6%4*5"][k],
console.log(`g(\${v}) = \${g(v)}`)``````

2015年

@trlkly `a/b|0`停止除/模0错误检查，但`Math.floor(a/b)`起作用
Herman L

2

``````import Data.List.Split
import Data.List
f s=(-)<\$>maximum<*>minimum\$permutations(zip"+-*/%"[p(+),p(-),p(*),c\$div,c\$mod])>>=(s!)
p=((pure.).)
c o a b=[o a b|b/=0]
s!((x,o):y)=case splitOn[x]s>>=(!y)of[]->[];l->l?o
[a]?_=[a]
(a:b)?o=b?o>>=o a
``````

`(%)`是模数运算符。它是左参数和右参数之间除法运算的其余部分。
maple_shaft

1

# Python 2中，262个256 254字节

``````from itertools import*
def r(s,o):
try:
while o in s:i=s.index(o)-1;s[i:i+3]=[`eval(''.join(s[i:i+3]))`]
return s
except:0
def f(s):
u=[int(v)for v in [reduce(r,O,s.split(' '))for O in permutations('*/%+-')]if v!=None];return abs(max(u)-min(u))
``````

1

1

# PHP，316字节

``<?for(;\$t++<54322;)count_chars(\$t,3)!=12345?:\$p[]=\$t;foreach(\$p as\$x){for(list(\$z,\$q)=\$_GET,\$b=1,\$i=0;\$y=strtr(\$x,12345,"/%*+-")[\$i++];)while(-1<\$k=array_flip(\$q)[\$y]){\$n=\$k+1;if(\$b&=\$z[\$n]||ord(\$y)%10<6)eval("\\$z[\$k]=\$z[\$k]\$y\$z[\$n]^0;");(\$s=array_splice)(\$z,\$n,1);\$s(\$q,\$k,1);}\$b?\$r[]=\$z:0;}echo max(\$r)-min(\$r);``

``````Expanded
for(;\$t++<54322;)
count_chars(\$t,3)!=12345?:\$p[]=\$t;
foreach(\$p as\$x){
for(list(\$z,\$q)=\$_GET,\$b=1,\$i=0;\$y=strtr(\$x,12345,"/%*+-")[\$i++];)
while(-1<\$k=array_flip(\$q)[\$y]){
\$n=\$k+1;
if(\$b&=\$z[\$n]||ord(\$y)%10<6)
eval("\\$z[\$k]=\$z[\$k]\$y\$z[\$n]^0;");
(\$s=array_splice)(\$z,\$n,1);
\$s(\$q,\$k,1);
}
\$b?\$r[]=\$z:0;
}
echo max(\$r)-min(\$r);
``````

H.PWiz

0

# Python 3，284字节

``````from itertools import*
def f(n,o):
z=[]
for p in permutations("+-*/%"):
try:
p,x,a=[*p],n[:],o[:]
while(p):
for i,d in enumerate(a):
if d==p:x[i+1]=str(eval(x[i]+d+x[i+1]));x.pop(i);a.pop(i)
p.pop(0)
z+=x
except:0
z=[*map(float,z)];return max(z)-min(z)
``````

1
`while(p)`可以变成`while p`保存一个字节。

0

# Clojure的（+组合学），342 377 + 41 = 418个字节

+ 35个字节，因为一个错误。

``(fn[x y](let[l filter s first z #(l(fn[y]y)%)r(sort(z(for[e(q/permutations[+ - * quot mod])](try(loop[t e m y a x](if(=[]t)(s a)(let[j(s t)i(reverse(keep-indexed #(if(= j %2)%)m))](recur(rest t)(l #(not= j %)m)(loop[d 0 h a](if(=(count i)d)h(let[c(nth i d)f(inc c)](recur(inc d)(vec(z(assoc h c(j(nth h c)(nth h f))f nil)))))))))))(catch Exception _ nil)))))](-(last r)(s r))))``

``(use '[clojure.math.combinatorics :as q])``

## 细微差别：

``((fn[x y]...) numbers operators)``

## 非高尔夫节目：

``````(defn precedence [numbers operators]
(let [results
(sort
(for [permute (c/permutations [+ - * / mod])]
(loop [p-temp permute
o-temp operators
n-temp numbers]
(if (empty? o-temp) (first n-temp)
(let [first-p (first p-temp)
indices (reverse (keep-indexed #(when (= first-p %2) %) o-temp))]
(recur
(rest p-temp)
(filter #(not= first-p %) o-temp)
(loop [ind 0
n-through n-temp]
(if (= ind (count indices)) n-through
(let [current-ind (nth indices ind)]
(recur
(inc ind)
(vec
(filter #(not (nil? %))
(assoc n-through
current-ind (first-p (nth n-through current-ind) (nth n-through (inc current-ind)))
(inc current-ind) nil)))))))))))))]
(- (last results) (first results))))``````

@ Challenger5我相信您最好在说明中写出来，因为默认情况下，`The characters used to import the library will likely be counted` codegolf.meta.stackexchange.com / questions / 10225 /…
Gan

@KeyuGan你是对的-我误解了Meta共识。我认为`require`需要包含在代码中，并且其长度应添加到字节数中。

@ Challenger5所以我需要在我的字节数中添加41个字节，对吗？好。
Qwerp-Derp

@ Qwerp-Derp是的，但是导入是代码的一部分，您可以进行高尔夫运动。

0

# JavaScript（ES6），210个字节

``k=>(m=n=-k,r=(o,k,j=0)=>{for(o||(m=m>k?m:k,n=n<k?n:k);q=o[j++];(q>'%'&q<'/'||z)&&r(o.slice(0,j-1)+o.slice(j),h))for(h=[...k],z=1;i=h.indexOf(q)+1;h.splice(i-2,3,eval(a=h[i-2]+q+h[i])|0))z*=h[i]})('+-*/%',k)|m-n``

``````k=>(
m = n = NaN,
r =(o, k, j=0) => {
// try all operators in o
for(;q = o[j]; j++)
{
// q : current operator,
// look for q inside the expression to evaluate
for(h = [...k], z = 1; i = h.indexOf(q) + 1;)
{
a = h[i - 2]
b = h[i]
z *= b // trace if any second operand is zero
// subst subexpression with its value
h.splice(i - 2, 3, eval(a + q + b) | 0)
}
// now all subexp involving current operator are evaluated
// the result is ok if current operator is not % or /
//  OR if no second operand was zero
(q > '%' & q < '/' || z) &&
// try again recursively
// using the remaining operators and the remaining expression
r(o.slice(0, j) + o.slice(j+1), h)
}
// if no more operators to try, check max and min
// k is an array with 1 element, can be used like a single number
o || (
m = m > k ? m : k,
n = n < k ? n : k
)
},
r('+-*/%', k),
m-n
)``````

``````var F=
k=>(m=n=-k,r=(o,k,j=0)=>{for(o||(m=m>k?m:k,n=n<k?n:k);q=o[j++];(q>'%'&q<'/'||z)&&r(o.slice(0,j-1)+o.slice(j),h))for(h=[...k],z=1;i=h.indexOf(q)+1;h.splice(i-2,3,eval(a=h[i-2]+q+h[i])|0))z*=h[i]})('+-*/%',k)|m-n

function update() {
var input = I.value.match(/\d+|\S/g)
var result = F(input)
O.textContent = I.value + ' -> ' + result + ' (max:'+m+' min:'+n+')'
}

update()``````
``````<input id=I value="60 / 8 % 8 * 6 % 4 * 5" oninput='update()'>
<pre id=O></pre>``````