Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading