python3代码“具有重复字符的单词的字典顺序”给出错误的输出

时间:2018-11-08 12:23:59

标签: string python-3.x overflow rank lexicographic

我的python 3代码用于查找具有重复字符的给定单词的词典编排,除“ lDoAgpWmipGWOUuCIksS”以外的所有输入都运行良好,我的代码返回739156,但是,预期的答案是739136,并且在返回的问题中提到(您的答案%1000003),因为答案可能不适合整数。我只是无法解决此问题,无法找到解决我问题的确切方法。可能是我没有正确处理溢出。 下面是我的代码:

class Solution:
# @param A : string
# @return an integer
def findRank(self, A):
    n = len(A)
    curr = 1
    for i in range(0,n):
        less=0
        #loop to calculate number of smaller characters after the current character
        for j in range(i+1,n):
            if(ord(A[j])<ord(A[i])):
                less+=1
        #count frequency of duplicate characters
        l=[0]*52
        for j in range(i,n):
            if ((ord(A[j]) >= ord('A')) and ord(A[j]) <= ord('Z')):
                l[ord(A[j]) - ord('A')] += 1 
            else:
                l[ord(A[j]) - ord('a') + 26] += 1
        count=1
        for ele in l:
            count*=fact(ele)
        curr += (fact(n - i - 1) * less) / count
    return int((curr)%(1000003))

计算阶乘的功能

def fact(m):
if(m==0 or m==1):
    return (1)
return (m*fact(m-1))

0 个答案:

没有答案