使用matplotlib进行Python阶乘和绘图

时间:2016-09-21 04:15:52

标签: python csv matplotlib

我是python的新手。我试图编写一个函数来计算数字N的阶乘函数,然后将数据写入csv文件。下一步是从文件中读取数据并绘制N对N!的日志样式图。这是我到目前为止的代码,但它不起作用。对不起我的无知。谢谢。我不断得到i和N因子未定义的错误。

def factorial(N):
"""Compute N! = 1*2*...*N and 0!=1 where N >=0 and is an integer. 
Args:
    N: (int) must be >=0
Returns:
    (int) the evaluation of N!
    write the value of N and N! to data.csv file.
Raises:
    ValueError if N is not an integer
    ValueError if N<0 
"""
if type(N) is not int:
    raise ValueError('factorial() only takes integer input')
if N < 0:
    raise ValueError('factorial() only takes integers >= 0')
    Nfactorial = 1
for i in range(0,10):
    Nfactorial *=i
return Nfactorial, i
zip (i, Nfactorial)
import csv
with open('data.csv', 'w') as fh:
writer = csv.writer(fh, delimiter = '\t')
for n, m in zip(i,Nfactorial):
    writer.writerow([i,Nfactorial])

def factorialplot():
"""
Take value of N and N! from data.csv file
Args:
plot a  log function of N vs N!
Returns:
a log plot of N vs N!
"""
import matplotlib.pyplot as plt
import csv
x = []
y = []
with open('datafile.txt','r') as csvfile:
plots = csv.reader(csvfile,delimiter=',')
for row in plots:
        x.append(int(row[0]))
        y.append(int(row[1]))
plt.plot(x,y, label = 'factorial plot')
plt.xlabel('N!')
plt.ylabel('N')
plt.yscale('log')
plt.legend()
plt.show()

0 个答案:

没有答案