Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Support
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in / Register
Toggle navigation
C
cpython
Project overview
Project overview
Details
Activity
Releases
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Issues
0
Issues
0
List
Boards
Labels
Milestones
Merge Requests
0
Merge Requests
0
Analytics
Analytics
Repository
Value Stream
Wiki
Wiki
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Create a new issue
Commits
Issue Boards
Open sidebar
Kirill Smelkov
cpython
Commits
dc4872ee
Commit
dc4872ee
authored
Sep 07, 2010
by
Raymond Hettinger
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
Fix corner case for Random.choice() and add tests.
parent
c324697b
Changes
2
Show whitespace changes
Inline
Side-by-side
Showing
2 changed files
with
12 additions
and
1 deletion
+12
-1
Lib/random.py
Lib/random.py
+5
-1
Lib/test/test_random.py
Lib/test/test_random.py
+7
-0
No files found.
Lib/random.py
View file @
dc4872ee
...
...
@@ -239,7 +239,11 @@ class Random(_random.Random):
def
choice
(
self
,
seq
):
"""Choose a random element from a non-empty sequence."""
return
seq
[
self
.
_randbelow
(
len
(
seq
))]
# raises IndexError if seq is empty
try
:
i
=
self
.
_randbelow
(
len
(
seq
))
except
ValueError
:
raise
IndexError
(
'Cannot choose from an empty sequence'
)
return
seq
[
i
]
def
shuffle
(
self
,
x
,
random
=
None
,
int
=
int
):
"""x, random=random.random -> shuffle list x in place; return None.
...
...
Lib/test/test_random.py
View file @
dc4872ee
...
...
@@ -42,6 +42,13 @@ class TestBasicOps(unittest.TestCase):
self
.
assertRaises
(
TypeError
,
self
.
gen
.
seed
,
1
,
2
,
3
,
4
)
self
.
assertRaises
(
TypeError
,
type
(
self
.
gen
),
[])
def
test_choice
(
self
):
choice
=
self
.
gen
.
choice
with
self
.
assertRaises
(
IndexError
):
choice
([])
self
.
assertEqual
(
choice
([
50
]),
50
)
self
.
assertIn
(
choice
([
25
,
75
]),
[
25
,
75
])
def
test_sample
(
self
):
# For the entire allowable range of 0 <= k <= N, validate that
# the sample is of the correct length and contains only unique items
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment