0

## [發問] Python3 要怎麼打印階乘?

Sisi 2020-11-18 19:45:171034 瀏覽

def dispFacNumList(n):
for j in range(1, n + 1):
n = n * j
return n

def getFacNumList(n):
for i in range(1, n + 1):
print('n = {} : n! = {}\t'.format(i,dispFacNumList(n)))

def main():
n = 8
dispFacNumList(getFacNumList(n))

main()

n = 1 : n! = 8
n = 2 : n! = 8
n = 3 : n! = 8
n = 4 : n! = 8
n = 5 : n! = 8
n = 6 : n! = 8
n = 7 : n! = 8
n = 8 : n! = 8

ccutmis iT邦高手 7 級 ‧ 2020-11-18 19:57:06 檢舉

https://www.pythonfibonacci.com/

### 4 個回答

0
RoT
iT邦新手 5 級 ‧ 2020-11-18 20:38:08

Sisi, 你好

`要求getFacNumList(n)這邊印出1-8`

``````def getFacNumList(n):
for j in range(1, n):
print('n = {} : n! = {}\t'.format(j,dispFacNumList(j)))

def dispFacNumList(n):
Sum = 1
for i in range(1, n+1):
Sum *= i
return Sum

if __name__ == '__main__':
n = 8
getFacNumList(n)
``````

Sisi iT邦新手 5 級 ‧ 2020-11-18 21:06:52 檢舉

TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' 的問題。。。

RoT iT邦新手 5 級 ‧ 2020-11-18 21:59:54 檢舉

Sisi, 你好

`但是題目要求最後main()那裡需要引用dispFacNumList(getFacNumList(n))`

`我不知道要怎麼處理 for i in range(1, n+1): TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' 的問題`

Sisi iT邦新手 5 級 ‧ 2020-11-18 22:15:14 檢舉

Sisi iT邦新手 5 級 ‧ 2020-11-18 22:16:41 檢舉

RoT iT邦新手 5 級 ‧ 2020-11-19 00:23:28 檢舉

Sisi, 你好

return 回 def dispFacNumList(n):

`dispFacNumList(getFacNumList(n))`

Sisi iT邦新手 5 級 ‧ 2020-11-21 15:49:55 檢舉

RoT iT邦新手 5 級 ‧ 2020-11-21 19:25:56 檢舉

Sisi, 你好

2

iT邦大師 1 級 ‧ 2020-11-19 02:35:18
``````#!/usr/bin/env python3

def getFacNumList(n):
s = []
s=[s[-1] for x in range(1,n+1) if not s.append(x*s[-1] if s else 1)]
return s

def dispFacNumList(lst):
for i, elem in enumerate(lst):
print('%d! = %d' % (i+1, elem))

if __name__ == '__main__':
n = 8
dispFacNumList(getFacNumList(n))

``````
``````|=> ./ithelp201118.py
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
``````

J4(解釋)一下拉:

``````s=[s[-1] for x in range(1,n+1) if not s.append(x*s[-1] if s else 1)]
``````
``````s[-1] 就是 s list 的最後一筆.

def getFacNumList(n):
s = [1]
s=[s[-1] for x in range(1,n+1) if not s.append(x*s[-1])]
return s
``````

``````# 改成 + 累加
>> n = 3
>>> s = []
>>> s = [s[-1] for x in range(1,n+1) if not s.append(x+s[-1] if s else 1)]
>>> s
[1, 3, 6]
``````
0

iT邦大神 1 級 ‧ 2020-11-19 07:36:04

0
froce
iT邦大師 1 級 ‧ 2020-11-19 10:32:42
``````def dispFacNumList(n):
return eval("*".join([str(i) for i in range(1, n+1)]))

def getFacNumList(n):
print("n={0}: n!={1}".format(n, dispFacNumList(n)))

for i in range(1, 9):
getFacNumList(i)
``````

``````import math
def dispFacNumList(n):
return math.prod([i for i in range(1, n+1)])

def getFacNumList(n):
print("n={0}: n!={1}".format(n, dispFacNumList(n)))

for i in range(1, 9):
getFacNumList(i)
``````

math.prod版