Tallying the outcome of a coin flip [closed] - python

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:

Related

Is there a way to plot a "function string" 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 9 months ago.
Improve this question
Example: The user types "(x^2 + 5)^3" into the terminal and the script plots the function like WolframAlpha would do.
Is there an easy way to do that in python?
The function might include abs(), sqrt() etc.
Thanks in advance for your responses
You could try using eval with an inputted X or default x:
import matplotlib.pyplot as plt
import numpy as np
import re
def get_variables(input_string):
count = 0
matches = re.findall(r'(?i)[a-z]', input_string)
return set(matches) #returns unique variables
function = input('Input Function: ')
variables = get_variables(function)
print(variables, type(variables), function)
varDict = {v: np.arange(100) for v in variables} #maps the variable names to some default range
for v in variables: #changes the function string to work with the newly defined variables
pattern = r'\b%s\b' %v
function = re.sub(pattern,r'varDict["%s"]' %v,function)
answer = eval(function) #evaluates the function
if len(variables) == 1:
plt.plot(*varDict.values(),answer) #plot the results, in this case two dimensional
else:
ax = plt.axes(projection="3d")
ax.plot3D(*varDict.values(),answer) # line
#ax.scatter3D(*varDict.values(),answer); #scatter
plt.show()
You can change the 3d settings if you want a scatterplot or add logic to make a shape (ie using meshgrid)
Just be sure that the eval statements are fully sanitized. This also requires the function to be inputted in python syntax (** not ^), unless you want to add functions to edit common syntax differences in the string.

Python index error when trying to make a mean [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm trying to make an average but for some reason when I try to make one it doesn't work.
I have global variables and array defined at the begining of my document :
vent_moyenne_km = []
compteur_moyenne=0
I have one of my function that is called every X time. In that one, I calculate a velocity with some value that are display on a label of my interface. that part is working, but not the mean
global compteur_moyenne
compteur_moyenne += 1
ventkmh = (vent_1[3][0]*256 + vent_1[4][0]) /100 *3.6
label_vent2_2.config(text= "%.2f" % ventkmh)
vent_moyenne_km.append("%.2f" % ventkmh)
vent_1.clear()
if compteur_moyenne == 5:
compteur_moyenne = 0
print(vent_moyenne_km)
label_vent4_2.config(text=statistics.mean(vent_moyenne_km))
vent_moyenne_km.clear()
of course in my imports I have :
import statistics
When I comment the line label_vent4_2.config(text=statistics.mean(vent_moyenne_km)), everything works and I see in the terminal my array with 5 values. I also tried numpy and even tried to make a for items in array: then add then manually, and everytime I get the error : class 'IndexError'
I'm really not sure how to fix that.
For calculating an average of a list just use numpy:
def function():
value = random.randint(0,1)
return value
list = []
for i in range(100):
list.append(function())
if i%5 == 0:
print(np.average(list))

Weighted random choice: Generate a list of "n" words respecting the frequencies in a .txt file randomly [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 3 years ago.
Improve this question
I have a text file with 500 words and their respective frequencies.
I need a code that randomly generates a list of "n" words respecting the frequencies in the text file.
The .txt is this one:
palabrasyfrecuencias.txt
I'm using this code to read the file:
pd.read_fwf('palabrasyfrecuencias.txt', header=None, names=["Núm. orden", "Palabras", "Frecuencia"])
And this is the result I have right now:
Any help is welcome. Thank you very much!
Just a simple number generator trick leveraging cumulative probabilities will do the trick. (Forgive me if I messed up el Español).
import random
import pandas as pd
pd.read_fwf('palabrasyfrecuencias.txt', header=None, names=["Núm. orden", "Palabras", "Frecuencia"])
sum(df["Frecuencia"])
# This is actually a count, not a frequency
df["Contar"] = df["Frecuencia"]
# Compute the frequencies as a proportion of the total seen words
df["Frecuencia"] = df["Contar"] / sum(df["Contar"])
# Compute the cumulative distribution
df["Frecuencia_Acumulada"] = df['Frecuencia'].cumsum()
def generate_word(df):
"""
Generate a word according to the provided cumulative distribution using a random number
generator.
Args:
None
Returns:
The generated word
"""
rand = random.random()
# The first cumulative frequency in the range is the word we're looking for
return df[df["Frecuencia_Acumulada"] > rand]["Palabras"].iloc[0]
# Generate N words
N = 10
generated_words = [generate_word(df) for _ in range(N)]

A Program That Shuffles A Deck of Cards? [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 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]))

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.

Categories