Created
January 13, 2014 12:43
-
-
Save caoxudong/8399615 to your computer and use it in GitHub Desktop.
以均等概率随机打印数组的内容
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
#coding: utf-8 | |
#以均等概率随机打印数组中的数字 | |
import random | |
def print_with_modification_in_original_array(array): | |
""" | |
假设原数组长度为n,以n为上限获取一个随机数,打印数组中对应位置的值,并将该值与数组中最后一个元素的值交换。 | |
第2次,以(n-1)为数组长度再进行一遍此循环,直到最后只剩一个数 | |
""" | |
temp_length = len(array) | |
while temp_length > 1: | |
temp_index = temp_length - 1 | |
temp_pos = random.randint(0, temp_index) | |
print(array[temp_pos]) | |
array[temp_pos] ^= array[temp_index] | |
array[temp_index] ^= array[temp_pos] | |
array[temp_pos] ^= array[temp_index] | |
temp_length -= 1 | |
if __name__ == "__main__": | |
print_with_modification_in_original_array([1,2,3,4,5,6,7,8,9,0]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment