random.shuffle?

  • (2 Pages)
  • +
  • 1
  • 2

19 Replies - 8088 Views - Last Post: 13 April 2015 - 09:37 AM Rate Topic: -----

#1 marieh88   User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 20
  • Joined: 16-March 15

random.shuffle?

Posted 09 April 2015 - 05:45 AM

I thought the random module included shuffle. Do I need to import something else? Or why does it say it doesn't have the attribute shuffle?

In [61]:

from random import random
l=range(20)
random.shuffle(l)
print(l)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-61-12c44cc7c485> in <module>()
      1 from random import random
      2 l=range(20)
----> 3 random.shuffle(l)
      4 print(l)

AttributeError: 'builtin_function_or_method' object has no attribute 'shuffle'


Is This A Good Question/Topic? 0
  • +

Replies To: random.shuffle?

#2 andrewsw   User is offline

  • never lube your breaks
  • member icon

Reputation: 6829
  • View blog
  • Posts: 28,311
  • Joined: 12-December 12

Re: random.shuffle?

Posted 09 April 2015 - 06:01 AM

You've imported random but shuffle isn't a method of this object. You could import shuffle separately.

Also, range() on its own isn't a sequence, it is a function. You need to expand it:
from random import random, shuffle
l = [x for x in range(20)]
shuffle(l)
print(l)

I think range() is more correctly called an iterable object, rather than a function (as it is listed in the docs).

This post has been edited by andrewsw: 09 April 2015 - 06:06 AM

Was This Post Helpful? 0
  • +
  • -

#3 atraub   User is offline

  • Pythoneer
  • member icon

Reputation: 835
  • View blog
  • Posts: 2,267
  • Joined: 23-December 08

Re: random.shuffle?

Posted 09 April 2015 - 06:28 AM

An alternative syntax: you can also say, import random and then you can say random.shuffle(someList) error free.

I usually prefer this syntax. The dot notation makes it easier for people to see where the function came from immediately.

This post has been edited by atraub: 09 April 2015 - 06:35 AM

Was This Post Helpful? 2
  • +
  • -

#4 marieh88   User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 20
  • Joined: 16-March 15

Re: random.shuffle?

Posted 09 April 2015 - 06:38 AM

yes, that worked perfectly! Thank you:-) Could you maybe also help me with this? I need to get the result as a list. So far I can only get this:

from random import randint
 
l=range(20)
def mix(l):
    l=[i for i in range(20)]
    for i in l: 
        i=randint(0,19)
        print i
mix(l)
19
2
4
8
5
3
3
2
10
7
12
7
6
18
3
0
12
0
0
1


I have also tried this, but it didn't work:
def mix(l):
    l=[i for i in range(20)]
    mix=[]
    for i in l: 
        i=randint(0,19)
        print mix.extend(i)
mix(l)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-aa4ce9e63ec0> in <module>()
     10         i=randint(0,19)
     11         print mix.extend(i)
---> 12 mix(l)

<ipython-input-5-aa4ce9e63ec0> in mix(l)
      9     for i in l:
     10         i=randint(0,19)
---> 11         print mix.extend(i)
     12 mix(l)

TypeError: 'int' object is not iterable

Was This Post Helpful? 0
  • +
  • -

#5 atraub   User is offline

  • Pythoneer
  • member icon

Reputation: 835
  • View blog
  • Posts: 2,267
  • Joined: 23-December 08

Re: random.shuffle?

Posted 09 April 2015 - 10:50 AM

mix doesn't do what you want it to do. You're not shuffling a list, you're creating tons of random values. Thus you might have three 0's and no 9's, as your output does. Here's what you want
import random

l = [i for i in range(20)] #Creates a list
random.shuffle(l) #shuffles the list.



This creates a list with the values 0..19 and then takes that list and shuffles it. The result is that l contains all the values from 0 to 19 that are in a seemingly random order.

This post has been edited by atraub: 09 April 2015 - 01:00 PM

Was This Post Helpful? 0
  • +
  • -

#6 marieh88   User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 20
  • Joined: 16-March 15

Re: random.shuffle?

Posted 09 April 2015 - 12:26 PM

Ah, yes. Thank you. I didn't notice that. It is two different exercises though. I also have to create a list using the "def" function and "randint" taking the numbers out of one list and putting them randomly into another list. With the set( ) I thought I would be able to get rid of all the doubles, but it comes out empty?
In [4]:

from random import randint
 
l=range(20)
def mix(l):
    l=[i for i in range(20)]
    mix=set()
    for i in l: 
        i=randint(0,19)
        print mix.add(i)
        
mix(l)
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None

Was This Post Helpful? 0
  • +
  • -

#7 atraub   User is offline

  • Pythoneer
  • member icon

Reputation: 835
  • View blog
  • Posts: 2,267
  • Joined: 23-December 08

Re: random.shuffle?

Posted 09 April 2015 - 12:54 PM

It kinda looks like you're just spinning your wheels a bit here. Let's go over this code line by line

l=range(20)
def mix(l):
    l=[i for i in range(20)]
    mix=set()
    for i in l: 
        i=randint(0,19)
        print mix.add(i)
        
mix(l)



The first line you make a list holding the values 0..19. In python2 this is correct, in Python3, this doesn't work. Looking at your print statement, you're clearly using Python2, so this is fine.

in line 2 you define the mix function. Everything is looking good so far.

in line 3, you throw away whatever list was passed in as a parameter and create a new list instead with the values from 0..19. Why do this? Remove this line, it doesn't help you.

Next, we create an empty set. You don't put anything into this set, so now you have an empty set called mix. (Also, it's a bad idea to give a variable the same name as a function). I don't know why you made this empty set, but it's there. Frankly, I think you don't need the set and instead should just use a list. What if your original list has duplicates in it? Those will be lost.

Next, we iterate over each item in the list.

For each item in the new list you used to replace the input, we add a random number to mix. Thus we add 20 random numbers to mix, if there are any duplicates those get thrown away. So, you probably added something like 15 numbers. You also try to print the result of adding the number in. But set.add(i) doesn't return anything, so it'll just print none. mix is getting populated, and you can prove that simply by print mix.


That's what your function does. Obviously, it's not what you want to do. Instead, tell us in plain English what your program should do, step by step. Don't use any programmer talk like "conditionals" or "loops". If I was a child, how would you explain this one to me? If you can do that, we can definitely move forward.

P.S.andrewsw's comment regarding range() only pertains to Python3. Because you're using Python2, you can ignore that stuff, don't worry about trying to use l = [i for i in range(20)] for now. You don't need it for this assignment, l = range(20) is perfectly fine.

This post has been edited by atraub: 09 April 2015 - 01:01 PM

Was This Post Helpful? 1
  • +
  • -

#8 jon.kiparsky   User is offline

  • Beginner
  • member icon


Reputation: 11736
  • View blog
  • Posts: 19,929
  • Joined: 19-March 11

Re: random.shuffle?

Posted 09 April 2015 - 04:35 PM

View Postandrewsw, on 09 April 2015 - 08:01 AM, said:

Also, range() on its own isn't a sequence, it is a function. ...
I think range() is more correctly called an iterable object, rather than a function (as it is listed in the docs).


It depends on whether you're using python2 or python3. Before the Great Day Of Backwards Incompatibility, range() returned a list:


/Users/jpk/mc/accelerate:501 $ python2
Python 2.7.8 |Anaconda 2.0.1 (x86_64)| (default, Aug 21 2014, 15:21:46) 
[GCC 4.2.1 (Apple Inc. build 5577)] on darwin
>>> range(4)
[0, 1, 2, 3]
>>> >>> type(_)
<type 'list'>
>>> 




In the Modern Era, it returns (or, I suppose, is a constructor for) a range object:
/Users/jpk/mc/accelerate:502 $ python3
Python 3.4.1 (default, May 19 2014, 13:10:29) 
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> range(4)
range(0, 4)
>>> r = _
>>> type(r)
<class 'range'>
>>> dir (r)
['__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index', 'start', 'step', 'stop']
>>> 



In the latter case, you don't really want to walk the list to make a list of it. Better to just do

>>> list(r)
[0, 1, 2, 3]
>>> 


Since python2 is still in extremely wide use, it's not safe to assume which version someone is using.


As for the homework problems, it's not clear to me what the goal is. What is it that you want this function to do?


Quote

I also have to create a list using the "def" function and "randint" taking the numbers out of one list and putting them randomly into another list.


This is almost completely unclear. I know that you want numbers from one list to go into another list. Beyond that, I'm at sea. Can you give an example - ideally, some input, and what the output from that input ought to be?

Quote

using the "def" function

Umm... def is not a function. In fact, it's one of the few things in python that isn't an object...
Was This Post Helpful? 0
  • +
  • -

#9 andrewsw   User is offline

  • never lube your breaks
  • member icon

Reputation: 6829
  • View blog
  • Posts: 28,311
  • Joined: 12-December 12

Re: random.shuffle?

Posted 09 April 2015 - 04:40 PM

Thank you both. I hadn't checked whether the behaviour (the result) was different between Python 2 and 3.
Was This Post Helpful? 0
  • +
  • -

#10 marieh88   User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 20
  • Joined: 16-March 15

Re: random.shuffle?

Posted 10 April 2015 - 01:05 AM

Well the assignment goes: Programme a function that takes the items from one list and returns a reshuffled list. WITHOUT using the shuffle function.
So it should look something like this:
>>> mix([1,2,3,4,5])
[3,4,2,5,1]


I was trying to make a function, that took out random numbers of the one list (unsing randint) and put them in to an empty set( ). But I understand, that would make the list shorter than the original list because the set( ) removes all doubles.

I also tried this. But for some reason it organizes the order?
In [5]:

l=range(20)
reshuffle=set()
 
while len(reshuffle)< len(l):
    for i in l:
        i=randint(min(l),max(l))
        reshuffle.add(i)
reshuffle
Out[5]:
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19}

Was This Post Helpful? 0
  • +
  • -

#11 atraub   User is offline

  • Pythoneer
  • member icon

Reputation: 835
  • View blog
  • Posts: 2,267
  • Joined: 23-December 08

Re: random.shuffle?

Posted 10 April 2015 - 05:49 AM

What if you used randint to decide which number to take out of the original list. Thus if your original list has 20 values, and randint returned a 15, you'd take the 15th element out of your first list and put it into your second?
Was This Post Helpful? 0
  • +
  • -

#12 marieh88   User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 20
  • Joined: 16-March 15

Re: random.shuffle?

Posted 11 April 2015 - 01:47 AM

Yes, that is exactly what I would like it to do. But can I get it to randomly pick a number from a list using randint?
Was This Post Helpful? 0
  • +
  • -

#13 marieh88   User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 20
  • Joined: 16-March 15

Re: random.shuffle?

Posted 11 April 2015 - 01:55 AM

With this, I get it to remove a random number from my original-list. But then, how can I get it to add that removed number to another list?

ln [4]:

l=range(20)
 
l.remove(randint(min(l),max(l)))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 19]

Was This Post Helpful? 0
  • +
  • -

#14 atraub   User is offline

  • Pythoneer
  • member icon

Reputation: 835
  • View blog
  • Posts: 2,267
  • Joined: 23-December 08

Re: random.shuffle?

Posted 11 April 2015 - 07:21 AM

Instead of remove try pop. This will still remove the item but it also returns it. This is better but still won't work the way you want it to even after you utilize pop. But once you see your error you may be able to fix it on your own.
#pop demo
x = range(5) #x is [0,1,2,3,4] 
y = x.pop(2) #y is equal to 2
z = len(x)  #z is equal to 4
#x is now [0,2,3,4]



If you're not sure how to add a value to a list, the python docs is what you need.

This post has been edited by atraub: 11 April 2015 - 08:54 AM
Reason for edit:: Typo caught before someone caught it for me :-P

Was This Post Helpful? 0
  • +
  • -

#15 marieh88   User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 20
  • Joined: 16-March 15

Re: random.shuffle?

Posted 12 April 2015 - 11:49 PM

I am sorry, but I still don't understand what I am doing wrong. I tried this:
In [27]:


from random import randint
 
l=range(20)
mix=[]
 
i=l.pop(randint(min(l),max(l)))
mix.append(i)
mix
Out[27]:
[6]


And it looks like it's doing what I want it to. It is taking out one random number from the list l.
Is it not right i have to make the range in randint: min(l),max(l) to make it pick out a number from the list? randint needs two inputs as far as I have understood, and the function I am supposed to programme has to work on any list of numbers...

And then afterwards, I add the number I picked out, to my empty list mix.

I just need it to keep doing this as long as there are numbers in the list l. I thought I could do that with a while-loop, but I don't understand the error message I am getting:
In [29]:

# Beispiel für so eine Liste l, deren Einträge vermischt werden sollen.
from random import randint
 
l=range(20)
mix=[]
 
while len(l)>=0:
    i=l.pop(randint(min(l),max(l)))
    mix.append(i)
print mix
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-29-063dda905e81> in <module>()
      6 
      7 while len(l)>=0:
----> 8     i=l.pop(randint(min(l),max(l)))
      9     mix.append(i)
     10 print mix

IndexError: pop index out of range


Why is the pop index now out of range? It worked before?
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2