Ask Your Question

Assigning variable values in a program

For a cryptography application, I want to assigned values of 0 or 1 to the following variables (x0, x1, x2, ..., x128). I want to define a function to take a hexadecimal representation of the 128 bits and assigned a 0 or 1 to each variable.

This can easily be done manually in sage by simply stating:
sage: x0 = 0
sage: x1 = 1 # and so on.

But I'm having finding a way to include this type of variable assignment in a function. I can do it by writting to a file and loading the file in Sage, but that required manual intervention to load the file.

Sorry if this is a trivial question, but I couldn't find an answer in the documentation

Thanks!

edit retag close merge delete

2 answers

Sort by ยป oldest newest most voted

If you're planning on running the function from say the notebook or and interactive prompt, you can do something like the following technique:

def f(n):
for i, value in enumerate(Integer(n).digits(2)):
globals()['x%s'%i] = value


Then, you can do something like:

sage: f(8)
sage: x0
0
sage: x3
1


A more Pythonic way to do things (without messing with the global namespace) would be something like:

def f(n):
return Integer(n).digits(2)


and then:

sage: x = f(8)
sage: x[0]
0
sage: x[3]
1

more

Comments

Using the global namespace worked great for my application. Thanks for the quick response.

( 2011-08-01 09:43:17 -0500 )edit

This is probably bad style. I think it would be better to do it like Mike Hansen's second suggestion, or use a dictionary (I don't understand what you are trying to do with your function, but this just returns the hexadecimal form of your number):

sage: value_dict = dict([('x' + str(number), Integer(number).digits(16)) for number in range(129)])
sage: value_dict['x128']
[0, 8]

more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Stats

Asked: 2011-08-01 08:09:57 -0500

Seen: 943 times

Last updated: Aug 01 '11