1

基本上,我需要让我的程序能够为我创建多个(无限)变量,我仍然可以通过我的代码进行操作,而无需我定义它们。

我想用一个字母和一个数字作为变量名,例如 a1,并让程序创建新变量,只需在数字上加 1。所以它会创建a1a30左右。我该怎么做?

我的程序将添加多项式,变量(或现在列出)是分开不同的单项式,因为我不知道多项式中有多少单项式,所以我需要一种使数字灵活的方法所以我对单项式有准确的空格数,没有多余的,也没有更少。

这是代码:

# Sample polynomial set to x, the real code will say x = (raw_input("Enter a Polynomial")).

x = '(5xx + 2y + 2xy)+ (4xx - 1xy)'

# Isdigit command set to 't' to make the code easier to write.
t = str.isdigit

# Defining v for later use.
v = 0

# Defining 'b' which will be the index number that the program will look at.
b = 1

# Creating 'r' to parse the input to whatever letter is next.
r = x [b]

# Defining n which will be used later to tell if the character is numeric.
n = 0

# Defining r1 which will hold one of the monomials, ( **will be replaced with a list**)

#This was the variable in question.
r1 = ''

# Setting 'p' to evaluate if R is numeric ( R and T explained above).
p = t(r)

# Setting 'n' to 1 or 0 to replace having to write True or False later.
if p == True:
    n = 1
else:
    n = 0

# Checking if r is one of the normal letters used in Algebra, and adding it to a variable
if r == 'x':
    v = 'x'
    c = 1
elif r == 'y':
    v = 'y'
    c = 1
elif r == 'z':
    v = 'z'
    c = 1

# If the character is a digit, set c to 0, meaning that the program has not found a letter yet (will be used later in the code).
elif n == 1:
    v = r
    c = 0

# Adding what the letter has found to a variable (will be replaced with a list).
r1 = r1 + v

b = b + 1

我最终会把它变成一个循环。

我在代码中添加了注释,这样更容易理解。

4

2 回答 2

6

本质上,您正在尝试以编程方式动态修改变量所在的堆空间。我真的不认为这是可能的。如果是的话,那就太晦涩了。

我明白你来自哪里。当我第一次学习编程时,我曾想过以需要这种“动态创建”变量的方式来解决问题。解决方案实际上是识别哪种(集合)数据结构适合您的需求。

如果你想a1通过变量a30,创建一个列表a。然后a1a[1]a30a[30]。写起来有点不同,但它应该给你你需要的行为。

于 2012-10-12T21:25:59.047 回答
1

我花了至少五分钟试图思考你为什么要首先这样做,直到我决定我可以在不到五分钟的时间内编写代码,并希望作为回报你会告诉我们你为什么要这样做做这个。

这是代码:

def new(value):
    highest = -1
    for name in globals():
        if name.startswith('a'):
            try:
                number = int(name[1:])
            except:
                continue

            if number > highest:
                highest = number


    globals()['a%d' % (highest + 1, )] = value


new("zero")
new("one")
new("two")

print a2 # prints two
于 2012-10-12T21:44:29.243 回答