首页 > 解决方案 > 在 Python 中,根据表达式和特定区间创建数组

问题描述

我需要在 python 中创建一个程序,在其中我询问用户他们想要的间隔数,以及数组的特定间隔 [a,b]。由此,我需要基于表达式 (ba)/n 创建数组元素。

这是我的代码到目前为止的样子:


n= int(input("Enter the number of intervals: "))
a= float(input("Enter the min point of the interval: "))
b= float(input("Enter the max point of the interval: "))

xPoints=list() #create a list of the x points
xPoints.append(float(a))

#code for elements in between a and b

xPoints.append(float(b))
print(xPoints)

对阵列的任何帮助将不胜感激。谢谢!

标签: pythonarrayspython-3.7

解决方案


def get_array(n, a, b):
    if n == 0:
        return []
    elif n == 1:
        return [a, b]
    else:
        return [a] + [a+i*((b-a)/n) for i in range(1, n)] + [b]

n = int(input("Enter the number of intervals: "))
a = float(input("Enter the lowest number of the interval: "))
b = float(input("Enter the highest number of the interval: "))

print(get_array(n, a, b))

推荐阅读