# Generate a list of integer excluding -1, 1 and 0.

In python, I made this code to pick numbers from a list of numbers, excluding -1, 0 and 1. I can't find the equivalent in sage.

def alea(n, max):
complete_list = [i for i in range(-max, max+1, 1) if i != 0 and i != -1 and i != 1]
list = random.sample(complete_list, n)
return(list)


With Sage, I've done this :

sage: def alea(n, max):
....:     list = [randrange(-max, max+1) for i in range(n)]
....:     return list
....:
sage: a = alea(5,10)
sage: a
[1, 3, 8, -9, 7]


and as you can see, 1 is in the list of course.

My goal will then be to take for example 4 random numbers a, b, c and d, to make a sum of fractions a/b+c/d, and to generate the answer automatically to make a series of exercises in a document written with latex/sagetex. That's why I need to exclude -1, 0 and 1.

edit :

under sage (jupyter) I have this error

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-17-8b055ece5ba6> in <module>
3     list = random.sample(complete_list, n)
4     return(list)
----> 5 a = alea(Integer(5), Integer(10))
6 a

<ipython-input-17-8b055ece5ba6> in alea(n, max)
1 def alea(n, max):
2     complete_list = [i for i in range(-max, max+Integer(1), Integer(1)) if i != Integer(0) and i != -Integer(1) and i != Integer(1)]
----> 3     list = random.sample(complete_list, n)
4     return(list)
5 a = alea(Integer(5), Integer(10))

AttributeError: 'function' object has no attribute 'sample'

edit retag close merge delete

Why do you need an equivalent and what kind? Your Python code should work fine in Sage as is.

( 2022-07-08 14:27:43 +0100 )edit

I have an error under Sage, as I show in the "edit" part, and I have some difficulties to understand.

( 2022-07-08 14:56:53 +0100 )edit

You need to add import random before calling random.sample

( 2022-07-08 15:05:55 +0100 )edit

Of course ... thanks ... it was so simple. I forgot this.

( 2022-07-08 15:22:10 +0100 )edit

Sort by ยป oldest newest most voted

Sage language is Python with some additional functions and classes.

So, Sage has a random function defined, that returns a random number in the interval $[0,1]$:

sage: random()
0.2808809147593442


If you want to use the sample function from the random python module, you just have tom import it before your Python code:

sage: import random


If you do not want to overwrite the random Sage function by the random Python module, you can do:

sage: from random import sample


but then use sample instead of random.sample.

more

( 2022-07-08 15:25:19 +0100 )edit