2017-02-19 91 views
-1

我需要创建一个函数,我应该得到N!的最后一个非零数字。Python:从阶乘(N)得到最后一个非零元素

以下代码返回错误答案。

def get_last_nonzero_elem(n): 
    if 0 <= n <= 1000000: 
    factorial = reduce(lambda x, y: x * y,[1] + range(1, n+1)) 
    list_factorial = map(int, str(factorial)) 
    for i in reversed(list_factorial): 
     if i != 0: 
      return i 
else: 
    return None 

我在做什么错在这里?

+0

预期输入与 “错” 的输出? – Jarvis

+0

@Jarvis错误的输出 –

+0

@PetrPetrov不,你是什么人,你会得到什么? – Roope

回答

0

一旦你的阶乘,只是这样做:

a = str(factorial) 
output = int(a.replace('0', '')[-1]) 

假设你n不是它的阶乘太大而无法存储在int。否则,请使用lists来计算巨大数字的阶乘。

0

看到这个代码:

def fact(n): 
    if n==0: 
      return 1 
    else : 
      return n*fact(n-1) 


x = fact(44) # x =2658271574788448768043625811014615890319638528000000000L 
y=str(x)[::-1] # convert x to string and invers it 
str(int(y))[0] # convert y to int after to string and get the first char 
#8 
0

没有递归限制,低内存占用,这一个:

from functools import reduce 

def fact(n): 
    if n==0: 
     return 1 
    else : 
     # in python 2 replace range by xrange: 
     return reduce(lambda x, y: x * y, range(1, n+1)) 

def last_non_zero(n): 
    while n: 
     d = n%10 
     if d!=0: 
      return d 
     else: 
      n //= 10 

N = 1000 
f = fact(N) 
print("factorial of {} is : {}".format(N, f)) 
print("last non zero is:", last_non_zero(f))