Ask Your Question
0

Assigning variable values in a program

asked 2011-08-01 08:09:57 -0600

sagenewbie gravatar image

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 flag offensive close merge delete

2 answers

Sort by ยป oldest newest most voted
2

answered 2011-08-01 09:28:52 -0600

Mike Hansen gravatar image

updated 2011-08-01 09:34:14 -0600

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
edit flag offensive delete link more

Comments

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

sagenewbie gravatar imagesagenewbie ( 2011-08-01 09:43:17 -0600 )edit
0

answered 2011-08-01 10:31:40 -0600

Eviatar Bach gravatar image

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]
edit flag offensive delete link more

Your Answer

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

Add Answer

Question Tools

Stats

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

Seen: 821 times

Last updated: Aug 01 '11