Py学习  »  Python

在python中尝试“1-x+x^2-x^3+x^4-x^5…”这个系列,有人有什么想法吗?

coconido • 5 年前 • 1754 次点击  

我试图编写一个python脚本来计算以下系列:

1-x+x^2-x^3+x^4。。。

如果有人能提供一些关于如何使这项工作有任何价值的指导,我将不胜感激?

到目前为止,我只能通过对所有操作进行硬编码来做到这一点:D

提前谢谢!

我目前的解决方案:

def seriesrun(x,n):
    ncurrent = 0
    total = 1
    while ncurrent <= n:
        if ncurrent == 0:
            ncurrent = ncurrent + 1
            total = total * 1
            print(ncurrent, total)
        elif ncurrent == 1:
            ncurrent = ncurrent + 1
            total = total - x
            print(ncurrent, total)
        elif ncurrent == 2:
            ncurrent = ncurrent + 1
            total = total + x**2
            print(ncurrent, total)
        elif ncurrent == 3:
            ncurrent = ncurrent + 1
            total = total - x**3
            print(ncurrent, total)
        elif ncurrent == 4:
            ncurrent = ncurrent + 1
            total = total + x**4
            print(ncurrent, total)
        elif ncurrent == 5:
            ncurrent = ncurrent + 1
            total = total - x**5
            print(ncurrent, total)
    return total

x = int(input('What is your starting x value?\n'))
n = 5
# n = int(input('How far should the series go?'))
# the current n position you are at...

print('Final answer is: '+str(seriesrun(x,n)))
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/50006
 
1754 次点击  
文章 [ 6 ]  |  最新文章 5 年前