Shuffle an list in python

Python program for shuffle an list. Here more information.

import random
import sys
#  Python 3 program for
#  Shuffle the list elements
class Shuffling :
	#  Function which is swapping two list elements 
	#  of given location
	def swapElement(self, arr, i, j) :
		#  Get i location element
		temp = arr[i]
		#  Set new values
		arr[i] = arr[j]
		arr[j] = temp
	
	#  Returns the random location of list elements
	def randomLocation(self, min, max) :
		#  Calculate random number between given range
		return random.randint(min,max)
	
	#  Function which is shuffle given list elements
	def shuffleElement(self, arr, size) :
		#  (i,j) indicate locations
		j = 0
		i = 0
		#  Variable which is controlling the 
		#  execution process of loop
		counter = 0
		#  Loop which is shuffling random elements in list
		while (counter < size) :
			#  Get random location of list index
			i = self.randomLocation(0, size-1)
			j = self.randomLocation(0, size-1)
			if (i != j) :
				#  Swap list elements
				self.swapElement(arr, i, j)
				counter += 1
			
		
	
	#  Function which is display list elements
	def display(self, arr, size) :
		i = 0
		while (i < size) :
			#  Disply element value
			print("", arr[i], end = " ")
			i += 1
		
		print(end = "\n")
	

def main() :
	task = Shuffling()
	#  Define list of integer elements
	arr = [1, 0, -3, 8, 7, 3, 9, 4, 2, 5, 10, 6]
	size = len(arr)
	#  Before shuffling  list elements
	print(" Initial array elements")
	task.display(arr, size)
	print(" After Shuffle array elements")
	task.shuffleElement(arr, size)
	task.display(arr, size)
	task.shuffleElement(arr, size)
	task.display(arr, size)
	task.shuffleElement(arr, size)
	task.display(arr, size)

if __name__ == "__main__": main()

Output

 Initial array elements
 1  0  -3  8  7  3  9  4  2  5  10  6
 After Shuffle array elements
 9  7  5  6  4  10  -3  0  1  2  3  8
 1  7  10  8  6  5  0  2  9  -3  3  4
 -3  2  8  10  1  5  9  3  0  4  6  7


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved