result1 = [prg_count,prg_mt_count,dnt_prg_count,excld_count]
total_students = prg_count + prg_mt_count + dnt_prg_count + excld_count
result2 = ["Progress", "Progress(MT)", "Do not Progress(MT)", "Exclude"]
def histogram (list1):
for i in range (len(list1)):
for j in range (list1[i]):
print("*",end="")
print("")
print('_' * 30)
print("Horizontal Histogram")
histogram (result1)
print(total_students, "outcomes in total")
print('_' * 30)
I want to print the items in the result2 list, one by one with their histogram value.
Histogram value changes according to user inputs and they're assigned to result1 list items.
what I'm trying to get;
Progress : *
Progress(MT) : *
Do not Progress(MT) : **
Excluded 1 : *
Did some improvements to your code, instead of loop for * printing I used '*' * count, same like you did for horizontal line '_' * 30, also printed names of histogram keys as you wished in your Question, plus used string's method .ljust(21) which adds extra spaces to align several strings to the same width.
Also as an example I showed histogram values 1, 5, 2, 3, see my Output after code below.
Try it online!
prg_count, prg_mt_count, dnt_prg_count, excld_count = 1, 5, 2, 3
result1 = [prg_count,prg_mt_count,dnt_prg_count,excld_count]
total_students = prg_count + prg_mt_count + dnt_prg_count + excld_count
result2 = ["Progress", "Progress(MT)", "Do not Progress(MT)", "Exclude"]
def histogram (list1, list2):
for a, b in zip(list1, list2):
print(b.ljust(21) + '*' * a)
print('=' * 30)
print("Horizontal Histogram")
print('-' * 30)
histogram(result1, result2)
print('-' * 30)
print(total_students, "outcomes in total")
print('=' * 30)
Output:
==============================
Horizontal Histogram
------------------------------
Progress *
Progress(MT) *****
Do not Progress(MT) **
Exclude ***
------------------------------
11 outcomes in total
==============================
Your question is not clear, but I think I know what you are saying. If you want to print the titles to the values (as I think your desired output says) you need to pass your titles in.
result1 = [5, 4, 2, 3]
total_students = sum(result1)
result2 = ["Progress","Progress(MT)","Do not Progress(MT)","Exclude"]
def histogram(result2, result1):
for i in range(len(result2)):
print(result2[i], end=" ")
for j in range(result1[i]):
print('*', end="")
print('')
print('_' * 30)
print("Horizontal Histogram")
histogram (result2, result1)
print(total_students, "outcomes in total")
print('_' * 30)
If you want to make it more succinct you can do this instead.
output = zip(result2, result1)
def histogram(list1):
for title, value in list1:
print(f"{title:20} {''.join(['*' for i in range(value)])}\n")
histogram(output)
Related
I have my code
def Name(x1,y1,x2,y2,B):
and so on
I have made a multiply of these depending on how many values i have x1,y1-x14,y14 but I was wondering if I could use the if function to shorten it and have the code recognize which function to use by the n value next to the letter
def Name(x1,y1....xn,yn)
if n=12
uses Name12
sample of my code
def arb_2odds(x1,y1,x2,y2,B):
arb_o1=(100*y1)/(x1+y1)
arb_o2=(100*y2)/(y2+x2)
arb_total=arb_o1+arb_o2
bet_for_01=(round((B*arb_o1)/arb_total,2))
bet_for_02=(round((B*arb_o2)/arb_total,2))
payout_O1=round(((bet_for_01/y1)*x1+bet_for_01),2)
payout_O2=round(((bet_for_02/y2)*x2+bet_for_02),2)
Profit_O1=round(payout_O1-B,2)
Profit_O2=round(payout_O2-B,2)
roi=100-arb_total
print("//ARB calculations is",arb_total,"//the ROI is:", roi,"percent//")
print("//Place",round(bet_for_01,2),"Euros on the first Odds//Place", round(bet_for_02,2),"Euros on the second Odds//")
print("//If the first odds win the payout is:",payout_O1,"Euros, and the profit is:",Profit_O1,"Euros")
print("//If the second odds win the payout is:",payout_O2,"Euros, and the profit is:",Profit_O2,"Euros")
#3 outcome games
def arb_3odds(x1,y1,x2,y2,x3,y3,B):
arb_o1=(100*y1)/(x1+y1)
arb_o2=(100*y2)/(y2+x2)
arb_o3=(100*y3)/(y3+x3)
arb_total=arb_o1+arb_o2+arb_o3
bet_for_01=round((B*arb_o1)/arb_total,2)
bet_for_02=round((B*arb_o2)/arb_total,2)
bet_for_03=round((B*arb_o3)/arb_total,2)
toatl_payout=(bet_for_01*x1+y1*bet_for_01)/y1
profit=toatl_payout-B
roi=100-arb_total
print("//ARB calculations is",arb_total,"//the ROI is:", roi,"percent//")
print("//Place",round(bet_for_01,3),"Euros on the first Odds//Place",round(bet_for_02,3),"Euros on the second Odds//Place",round(bet_for_03,3),"Euros on the third Odds//")
print("//The total payout is",round(toatl_payout,3),"//The profit is",round(profit,3),"Euros//")
My approch:
from collections import namedtuple
from typing import Sequence
from random import randint
Point = namedtuple('Point', ['x', 'y'])
def arb_odds(points: Sequence[Point], B: int):
arbs = [(100 * p.y) / (p.x + p.y) for p in points]
arb_total = sum(arbs)
bets = [round((B * arb) / arb_total , 2) for arb in arbs]
roi = 100 - arb_total
print( f"//ARB calculations is {arb_total} //the ROI is: {roi} percent//")
if (length := len(points)) % 2 == 0:
payouts = [round(((bet / p.y) * p.x + bet), 2) for bet, p in zip(bets, points) ]
profits = [round(payout - B, 2) for payout in payouts]
# Use `humanize` package if you want nicer ordinal number string display
print(" ".join(
[f"//Place {round(bet, 3)} Euros on the {i+1}th Odds" for i, bet in enumerate(bets)]
))
print("\n".join(
[
f"//If the {i+1}th odds win the payout is: {payout} Euros, and the profit is: {profit} Euros"
for i, (payout, profit) in enumerate(zip(payouts, profits))
]
))
else:
total_payout = (bets[0] * points[0].x + points[0].y *bets[0]) / points[0].y
profit = total_payout - B
print(" ".join(
[f"//Place {round(bet, 3)} Euros on the {i+1}th Odds" for i, bet in enumerate(bets)]
))
print(f"//The total payout is {round(total_payout, 3)} //The profit is {round(profit, 3)} Euros//")
if __name__ == "__main__":
even_points = tuple(Point(randint(1, 10), randint(1, 10)) for _ in range(4))
odd_points = tuple(Point(randint(1, 10), randint(1, 10)) for _ in range(7))
print(even_points)
print(odd_points)
arb_odds(even_points, 6)
arb_odds(odd_points, 6)
In order to keep a consistent functional form, it would be better to take a list of input tuples as the first argument. You can then rewrite the function something like this:
ORDINAL_WORDS = ["first", "second", "third", "fourth", "fifth", "sixth"] # expand as needed
def arb_odds(inputs, B):
arb_total = sum((100 * y) / (x + y) for x, y in inputs)
print(f"//ARB calculations is {arb_total} //the ROI is: {100 - arb_total} percent//")
for i, (x, y) in enumerate(inputs):
bet = 100 * B * y / (x + y) / arb_total
print(f"//Place {bet:.2f} Euros on {ORDINAL_WORDS[i]} odds")
You would call this function like this:
arb_odds([(x1, y1), (x2, y2)], B)
#betting and hedging
def arb(*args):
N_arguments =len(args)
if N_arguments == 5:
arb_2odds(*args)
if N_arguments == 3:
Tester(*args)
if N_arguments == 7:
arb_3odds(*args)
if N_arguments == 9:
arb_4odds(*args)
if N_arguments ==11:
arb_5odds(*args)
if N_arguments == 13:
arb_6odds(*args)
if N_arguments == 15:
arb_7odds(*args)
if N_arguments ==17:
arb_8odds(*args)
try this :
def add_all(*args):
total=0
for i in args:
total+=i
return total
this is a part of my program which generates * patterns from 4 user inputs
total= progresscount + trailercount + retrivercount + excludecount
print("....................................................")
print("Histogram")
print("Progress",progresscount,":" , "*" * progresscount)
print("Trailer",trailercount,":" , "*" * trailercount)
print("Retriver",retrivercount,":" , "*" * retrivercount)
print("Excluded",excludecount ,":" , "*" * excludecount )
print("....................................................")
if I run my whole program and enter 2 3 1 and 2 for each input requests, output looks like this
....................................................
Histogram
Progress 2 : **
Trailer 3 : ***
Retriver 1 : *
Excluded 2 : **
....................................................
and I want to make a vertical version like this
....................................................
Progress Trailing Retriever Excluded
* * * *
* * *
*
....................................................
help me to figure this out?
You can create a custom function like below:
def display_vhist(data):
cell_len = max([len(k) for k in data]) + 2
max_val = max(data.values())
# display header
print(*[h.center(cell_len) for h in data.keys()], sep='')
# display histogram
for i in range(1, max_val+1):
for v in data.values():
c = '*' if i <= v else ' '
print(c.center(cell_len), end='')
print()
Usage:
data = {'Progress': 2, 'Trailer': 3, 'Retriver': 1, 'Excluded': 1}
display_vhist(data)
# Output
Progress Trailer Retriver Excluded
* * * *
* *
*
result1 = ["Progress","Progress(MT)","ModuleRT","Exclude"]
result2 = [3,4,3,5]
def histogram (list1,list2):
for i in range (len(list1)):
print(list1[i])
for j in range (list2[i]):
print("","*")
histogram(result1,result2)
I'm trying to get the output like this, but I can't seem to get that.
Progress Progress(MT) ModuleRT Excluded
* * * *
*
Using center(), you can build the columns with the width corresponding to their respective title size. The histogram itself will need as many lines as the maximum value in result2. Each column should only print a star if the line index is less than the corresponding value.
result1 = ["Progress","Progress(MT)","ModuleRT","Exclude"]
result2 = [3,4,3,5]
print(*result1)
for i in range(max(result2)):
print(*( " *"[i<r].center(len(t)) for t,r in zip(result1,result2)))
Progress Progress(MT) ModuleRT Exclude
* * * *
* * * *
* * * *
* *
*
The histogram would look better if the columns were above the titles. You can do this by simply reversing the order of the line index:
for i in reversed(range(max(result2))):
print(*( " *"[i<r].center(len(t)) for t,r in zip(result1,result2)))
print(*result1)
*
* *
* * * *
* * * *
* * * *
Progress Progress(MT) ModuleRT Exclude
Converted to a function:
def histogram(titles,values):
print(*titles)
for i in range(max(values)):
print(*( " *"[i<v].center(len(t)) for t,v in zip(titles,values)))
Hello Alex and welcome on the Stackoverflow
I assume that, you want to get something like this below:
Progress * * *
Progress(MT) * * * *
ModuleRT * * *
Exclude * * * * *
Then, you have to modify your code, so that the print method does not add a new line after every * printed. To do so, you use end argument and set it to an empty character, like this: print("some string", end='')
So your new code would be:
result1 = ["Progress","Progress(MT)","ModuleRT","Exclude"]
result2 = [3,4,3,5]
def histogram (list1,list2):
for i in range (len(list1)):
print(list1[i], end='') # here is the end added
for j in range (list2[i]):
print("","*", end='') # here is the end added
histogram(result1,result2)
Nevertheless, it won't end-up in something like this:
Progress * * *Progress(MT) * * * *ModuleRT * * *Exclude * * * * *
The thing is, that there's no new line character after first outer for loop iteration. So you print a new line with an empty print at the end of the outer loop like this print("").
So finally your code would look like this:
result1 = ["Progress","Progress(MT)","ModuleRT","Exclude"]
result2 = [3,4,3,5]
def histogram (list1,list2):
for i in range (len(list1)):
print(list1[i], end='')
for j in range (list2[i]):
print("","*", end='')
print("") # here is the print
histogram(result1,result2)
T_list = []
Temp_k = np.linspace(298, 398, 10)
#print (Temp_k)
current = np.linspace(0, 1.4, 5)
ppH2O = np.linspace(-2, -1, 5)
H2_pressure = []
H2O_pp = ppH2O
for i in (Temp_k):
print(i, 'i')
for j in (H2O_pp):
print(j, 'j')
for k in (current):
print (k, 'k')
partial_H2 = 5*np.exp((1.653 * k)/i) - 1/j
H2_pressure.append(partial_H2)
#print (H2_pressure)
I want to make a list of an array that gives me the values of
5*np.exp((1.653 * k)/i) - 1/j,
At each Temp_k, H2O_pp, current.
For example, value of when Temp_k , H2O_pp and current is at their initial value,
value at their second value, .... till it reaches to the end values.
Could someone please help me with this?
What about this
import numpy as np
temp_k = np.linspace(298, 398, 10)
pp_h2o = np.linspace(-2, -1, 5)
currents = np.linspace(0, 1.4, 5)
h2_pressures = []
for temp in temp_k:
for pp in pp_h2o:
for current in currents:
h2_pressure = 5 * np.exp((1.653 * current) / temp) - 1 / pp
h2_pressures.append(h2_pressure)
print(f'temp: {temp:0.1f}, pp: {pp:.2f}, current: {current:.3f}, h2_pressure: {h2_pressure:.4f}')
#print(h2_pressures)
Changes:
choose more logical variable names conform Python convention
removed the () around the lists in the for loops
put the h2_pressures.append in the inner for loop
format the print out
Your problem is you put append outside of every loop. You should append what you calculated at the most inner loop, where you calculated it. Otherwise when loop is terminated there is no access to previously calculated values.
T_list = []
Temp_k = np.linspace(298, 398, 10)
#print (Temp_k)
current = np.linspace(0, 1.4, 5)
ppH2O = np.linspace(-2, -1, 5)
H2_pressure = []
H2O_pp = ppH2O
for i in (Temp_k):
print(i, 'i')
for j in (H2O_pp):
print(j, 'j')
for k in (current):
print (k, 'k')
partial_H2 = 5*np.exp((1.653 * k)/i) - 1/j
H2_pressure.append(partial_H2)
Okay, so basically I have a list (seq) of 19 letters of DNA.
"CGGTACAATCGATTTAGAG"
I am looking to get the right code to count 'A','T','G','C'.
I have tried.
dna_count = seq.count <i>(i have done this for each letter)</i>
then i used: dna_fraction = dna_count/len(seq)
print(dna_fraction * 100)
this results in an error of, dna_count is not defined.
I also need to incorporate round() to 2d.p of the percentage outcome. and return this.
Code (from comment):
def percentBases(dnaStrand):
seq = "CGGTACAATCGATTTAGAG"
dna_count = seq.count("A") + seq.count("T") + seq.count("G") + seq.count("C")
dna_fraction = dna_count / len(seq)
print(dna_fraction * 100)
rawPerCent = 100/seq.count
percentC = round(rawPercent, 2)
return (percentC, percentG, percentA, percentT)
Error message (from comment):
dna_fraction = dna_count / len(seq)
NameError: name 'dna_count' is not defined
You can use Counter():
from collections import Counter
seq = "CGGTACAATCGATTTAGAG"
for element, count in Counter(seq).items(): # use Counter(seq).most_common() for sorted
print(f"{element}: {count / len(seq):.2%}")
Or you can do it in one line:
print(*(f"{e}: {c / len(seq):.2%}" for e, c in Counter(seq).items()), sep="\n")
# print("\n".join(f"{e}: {c / len(seq):.2%}" for e, c in Counter(seq).items()))
seq = "CGGTACAATCGATTTAGAG"
# use set to find every unique letter
for dna in set(seq):
# count total number for each DNA in sequence
dna_count = dna_count.count(dna)
# divide by total
dna_fraction = dna_count/len(seq)
# round by 2
dna_fraction = round(dna_fraction, 2)
# print percentage of dna in sequence
print(dna, dna_fraction * 100)