社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

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

coconido • 5 年前 • 1718 次点击  

我试图编写一个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
 
1718 次点击  
文章 [ 6 ]  |  最新文章 5 年前
rusu_ro1
Reply   •   1 楼
rusu_ro1    6 年前

你可以用 reduce

from functools import reduce


def seriesrun(x, n):

    return reduce(lambda c, i: c + x**i*(-1)**i , range(n + 1), 0)
FuzzyLeapfrog
Reply   •   2 楼
FuzzyLeapfrog    6 年前

尝试使用序列的基本规则/结构:

result = 1
for i in n:
    result += (-x)**i
Heyran.rs
Reply   •   3 楼
Heyran.rs    6 年前

试试这个:

def seriesrun(x, n):
    power = 0
    s = 0

    while power < n:
        s += (-x)**power

        power +=1
    return s
ForceBru
Reply   •   4 楼
ForceBru    6 年前

嗯,加减法是根据某种规律交替进行的:

result = sum((-1)**i * x**i for i in range(5))

那个 (-1)**i 将是一个或负一个:

>>> [(-1)**i for i in range(5)]
[1, -1, 1, -1, 1]
Learning is a mess
Reply   •   5 楼
Learning is a mess    6 年前

您可以尝试:

series = 0
pow = 0
while True:
    series += (-1*x)**pow
    pow += 1

这是一个无限循环,所以由你来添加一个退出条件。

编辑:忘记交替标志

chepner
Reply   •   6 楼
chepner    6 年前

不需要显式求幂。每学期 -x 乘以上学期。

def seriesrun(x, n):
    result = 0
    term = 1

    for _ in range(n):
        result += term
        term *= -x  # -x == 1 * -x, x^2 == (-x) * (-x), -x^3 == x^2 * (-x), etc
    return result