How can i make python shuffleCards program output one of each card and not random amounts

Question:

Python newbie
How can i make the output be 52 cards but one of each and not randomly created cards. As of now output becomes for example 2 clover, 2 clover, 5 diamonds .. etc.
I know its an issue with the shuffeling i am doing but i am not allowed to use "random.shuffle"

import math
import random

def main():
    createDeck()
    shuffleDeck()
    printDeck()

deck = ['A'] * 52


def createDeck():
    suits = [" Heart", " Spades", " Clover", " Diamonds"]
    cardsHeld = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]

    for i in range(len(deck)):
        deck[i] = cardsHeld[int(i%13)] + suits[int(i/13)] 
        


def shuffleDeck():
    rand=0
    num = 0

    for i in range(len(deck)):
        rand = random.random()
       
        num = rand * 52
        num = math.floor(num)
        deck[i] = deck[num] 
          

def printDeck():    
    for i in range(len(deck)):    
        print(deck[i])   
main()        

I changed

def shuffleDeck():
    rand=0
    num = 0

    for i in range(len(deck)):
        rand = random.random()
       
        num = rand * 52
        num = math.floor(num)
        deck[i] = deck[num] 

with

def shuffleDeck():
   random.shuffle(deck)

That worked however i am not allowed to use "random.shuffle(deck)" So im not sure how i should be doing the shuffeling then.

Asked By: SharkFish423

||

Answers:

When you do deck[i] = deck[num] you overwrite the value at index i while keeping the same value at index num. You need to swap the values with deck[i], deck[num] = deck[num], deck[i]. But there’s no need to write something like this yourself. Simply use one line of code with random.shuffle from Pythons standard library.

if you do import random the code is:

def shuffle_deck(deck):
    random.shuffle(deck)

I changed the name of the function to be consistent with the Style Guide for Python Code and added deck as a parameter.

Answered By: Matthias
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.