我在Python 3.6中使用以下代码,该代码返回给定单词在按字母顺序排序的单词的所有可能排列的列表中的位置。例如,请参见下面的测试。提交此代码时,测试环境使用的2.7破坏了我的代码,您知道如何轻松修复它吗?我不熟悉2.7和3.6之间的区别。
我的代码和测试:
def listPosition(word):
val = [ord(char) - 96 for char in word.lower()]
minn = 1
maxx = npermutations(word)
if all(a >= b for a, b in zip(val, val[1:])):
return maxx
if all(a <= b for a, b in zip(val, val[1:])):
return minn
for indx in range(len(word)):
ordi = order(val[indx:],val[indx])
between = (maxx+1-minn)
if ordi is 0:
maxx = maxx - int(between * (1-frequency(val[indx:],val[indx])))
elif ordi is max([order(val[indx:],i) for i in val[indx:]]):
minn = minn + int(between * (1-frequency(val[indx:],val[indx])))
else:
before = sumfreq(val[indx:],val[indx],'before')
minn = minn + int(round((between * before),0))
after = sumfreq(val[indx:],val[indx],'after')
maxx = maxx - int(round((between * after),0))
return maxx
import operator from collections
import Counter from math
import factorial from functools
import reduce
def npermutations(word):
num = factorial(len(word))
mults = Counter(word).values()
den = reduce(operator.mul, (factorial(v) for v in mults), 1)
return int(num / den)
def frequency(val,value):
f = [val.count(i)/len(val) for i in val]
indx = val.index(value)
return f[indx]
def order(val,value):
return sorted([i for i in set(val)]).index(value)
def sumfreq(val,value,BorA):
if BorA is 'before':
check = [i for i in set(val) if i < value]
if BorA is 'after':
check = [i for i in set(val) if i > value]
freqs = [frequency(val,i) for i in check]
return sum(freqs)
tests = ['A','ABAB','AAAB','BAAA','QUESTION','BOOKKEEPER','ABCABC']
print(listPosition(tests[0]),"should equal 1")
print(listPosition(tests[1]),"should equal 2")
print(listPosition(tests[2]),"should equal 1")
print(listPosition(tests[3]),"should equal 4")
print(listPosition(tests[4]),"should equal 24572")
print(listPosition(tests[5]),"should equal 10743")
print(listPosition(tests[6]),"should equal 13")
Python 3.6的输出:
1 should equal 1
2 should equal 2
1 should equal 1
4 should equal 4
24572 should equal 24572
10743 should equal 10743
13 should equal 13
提交此代码进行评分时,事实证明测试环境使用的是Python 2.7,这给了我以下输出:
Test Passed
Incorrect list position for: ABAB: 0 should equal 2
Incorrect list position for: QUESTION: 40320 should equal 24572
Incorrect list position for: BOOKKEEPER: 0 should equal 10743
Test Passed
Test Passed
答案 0 :(得分:2)
在python 2中,/运算符的行为如下
3 / 2 == 1 # True
在python3中
3 / 2 == 1.5 # True
3 // 2 == 1 # True
编辑
解决此问题的最简单方法是添加
from __future__ import division
在代码的第一行