A Program That Shuffles A Deck of Cards? [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
For my intro to programming class, I need to create a program that randomly shuffles a deck of cards and then outputs the rank & suit (shown as a unicode symbol) in a 4x13 grid. What I have so far is below. How do I get it to give a random output? It currently outputs the cards in order by rank and suit. How do I get it to output in a 4x13 grid? It currently outputs in a 13x4 grid.
Here's an example of what my output is supposed to look like:
example output
(For the class, my prof wanted us to list both the separate tuples & nested sequence which is why they're both there, sorry if it makes the code appear messy)
import random
#Cards
SUITS = "\u2663","\u2665","\u2666","\u2660"
PIPS = "A","2","3","4","5","6","7","8","9","10","J","Q","K"
deck = [("A","\u2663"),("2","\u2663"),("3","\u2663"),("4","\u2663"),
("5","\u2663"),("6","\u2663"),("7","\u2663"),("8","\u2663"),("9","\u2663"),
("10","\u2663"),("J","\u2663"),("Q","\u2663"),("K","\u2663"),("A","\u2665"),
("2","\u2665"),("3","\u2665"),("4","\u2665"),("5","\u2665"),("6","\u2665"),
("7","\u2665"),("8","\u2665"),("9","\u2665"),("10","\u2665"),("J","\u2665"),
("Q","\u2665"),("K","\u2665"),("A","\u2666"),("2","\u2666"),("3","\u2666"),
("4","\u2666"),("5","\u2666"),("6","\u2666"),("7","\u2666"),("8","\u2666"),
("9","\u2666"),("10","\u2666"),("J","\u2666"),("Q","\u2666"),("K","\u2666"),
("A","\u2660"),("2","\u2660"),("3","\u2660"),("4","\u2660"),("5","\u2660"),
("6","\u2660"),("7","\u2660"),("8","\u2660"),("9","\u2660"),("10","\u2660"),
("J","\u2660"),("Q","\u2660"),("K","\u2660")]
#Retrieve random card
def deal_card():
for suit in SUITS:
for pip in PIPS:
print(suit + pip,end=" ")
print()
#Main Portion
deal_card()

from itertools import product
from random import shuffle
SUITS = ["\u2663","\u2665","\u2666","\u2660"]
PIPS = ["A","2","3","4","5","6","7","8","9","10","J","Q","K"]
deck = list(product(PIPS, SUITS))
shuffle(deck)
Then put in your print logic. Here is a fairly lazy print method that accomplishes what your example link shows:
for i in range(0, len(deck), 4):
print("{} {} {} {}".format(deck[i][0]+deck[i][1],deck[i+1][0]+deck[i+1][1],deck[i+2][0]+deck[i+2][1],deck[i+3][0]+deck[i+3][1]))

Related

How to count frequency of multiple items in a list and print relative frequencies [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Given two lists, I need to count the frequency of the items in one list as they are found in the other list; and place the relative frequencies of each item inside frequencyList (where the
frequency of searchFor[0] is stored in frequencyList[0])
I am unable to import anything
textList=['a','b','a','c',...]
searchFor=['a','b']
frequencyList=[2,1]
Try:
[textList.count(i) for i in searchFor]
Or?
list(map(textList.count, searchFor))
The other answer is quite compact and very pythonic but this is an alternate solution that is slightly more efficient as it only requires one pass over the input list.
textList=['a','b','a','c']
output_dict = {}
for i in textList:
try:
output_dict[i] = d[i] + 1
except:
output_dict[i] = 1
print(output_dict['a'])

Getting a value from list based on second list [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have a problem to get the value from first list based on second list. We can assume that we have an election. First list is the list of candidates, second list is the list of votes for this candidates.
candidatesList = [1,2,3,4]
voteList = [2,4,4,1]
One of the rules of election is that, if two or more candidates got same amount of votes then the winner is a candidate with lower number. In this case above output should be 2. I can change data structures but the output must be same.
Simplest way
candidatesList[voteList.index(max(voteList))]
max(voteList) gets you the max of the votes.
voteList.index(max(voteList)) gets you the index of the highest vote from the right hand side.
candidatesList[...] gets you the person
As far as I understand, this might be what you are looking for:
import numpy as np
candidates_list = [1,2,3,4]
vote_list = [2,4,4,1]
best_candidate_index = np.argmax(vote_list)
print("Best candidate", candidates_list[best_candidate_index])
Create dataframe, sort by ['voteList','candidatesList'] and use the top row.
d = dict(candidatesList = [1,2,3,4], voteList = [2,4,4,1])
pd.DataFrame(d).sort_values(by=['voteList','candidatesList'], ascending=[False,True]).candidatesList.iloc[0]

Tallying the outcome of a coin flip [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have written a little piece of code for modelling the outcome of a coin flip, and would like to find a better way of presenting the results than a list of consecutive coin flips. I'm one month into learning Python as part of my physics degree, if that helps provide some context.
Here's the code;
from pylab import *
x=0
while x<=100:
num = randint(0,2)
if num == 0:
print 'Heads'
else:
print 'Tails'
x=x+1
print 'Done'
What options do I have to present this data in an easier to interpret manner?
Instead of using a while loop and printing results to the screen, Python can do the counting and store the results very neatly using Counter, a subclass of the built in dictionary container.
For example:
from collections import Counter
import random
Counter(random.choice(['H', 'T']) for _ in range(100))
When I ran the code, it produced the following tally:
Counter({'H': 52, 'T': 48})
We can see that heads was flipped 52 times and tails 48 times.
This is already much easier to interpret, but now that you have the data in a data structure you can also plot a simple bar chart.
Following the suggestions in a Stack Overflow answer here, you could write:
import matplotlib.pyplot as plt
# tally = Counter({'H': 52, 'T': 48})
plt.bar(range(len(tally)), tally.values(), width=0.5, align='center')
plt.xticks(range(len(tally)), ['H', 'T'])
plt.show()
This produces a bar chart which looks like this:

How to create combat system in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Last line doesn't work and I wanna know how to give the Goblin random damage between 1-5.
my_character = {'name': '','health': 30}
print "You take a step back red eyes get closer..."
print "A goblin holding small dagger appears"
enemy = {'name':'Goblin','health':10}
print enemy
print "Goblin attacks you..."
my_character['health'] - 10
To choose a random number, you can use import randint fromm the random module.
To get a number between one and five use code like this:
from random import randint
goblin_damage = randint(1,5)
This will generate a random number between one and five.
To remove this amount of damage from player['health'] you can use player['health'] -= goblin_damage.
If you are wondering why my_character['health'] is not changed, the reason is simply that you never assign to it. Try
my_character['health'] = my_character['health'] - 10
or, the slighter shorter
my_character['health'] -= 10
If your question is something else, then please clarify the question.

Get the sum of a function in python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
My code:
# -*- coding: utf-8 -*-
def dice():
import random
number = random.randint(1,6)
print "The dice shows:" + str(number)
[dice() for _ in range(3)]
Example result:
The dice shows:2
The dice shows:4
The dice shows:3
If I want to sum all the numbers in the list, how do I do that? (In this case, I would get the sum 9)
Well, I think you should read a little bit more Python doc, because you have some doubts even before logic.
Here is what I think you wan to do.
import random
def dice():
return random.randint(1,6)
sum([dice() for i in range(3)])
Your function is printing result as string, not returning the result.
For manual suming:
import random
def dice():
return random.randint(1,6)
list = []
for i in range(3):
list.append(dice())
sum = 0
for i in list:
sum +=i
print sum
Built in suming:
print sum([dic() for _ in range(3))

Categories