user15364214
user15364214

Reputation:

How do I make my code output a formatted value at the end, and have it together in one function, with one return value?

(repost for clarity) This function basically returns the number of covid cases per gender + the %

How do I put together my code to make it one function, to return the already formatted value at the end, not print?

Upvotes: 0

Views: 61

Answers (2)

Joab Leite
Joab Leite

Reputation: 84

You can use Cereja lib. pip install cereja

import cereja as cj

genders = ['Female', 'Male', 'Female', 'Female', 'Female', 'Male', 'Female','trans']
freq = cj.Freq(genders) # Implementation available in https://github.com/cereja-project/cereja/blob/aa6f99549ff0ab084c213f25dd8685a41d36ab65/cereja/mltools/data.py#L43
freq.probability # OrderedDict([('Female', 0.625), ('Male', 0.25), ('trans', 0.125)])

Upvotes: 0

Tim Roberts
Tim Roberts

Reputation: 54978

You almost had it right.

def count_gender(genders):
    gender_types = valuesg1(genders)
    string = ''
    for gender in gender_types:
        count = genders.count(gender)
        string += '{}: {} cases {:.2%}\n'.format(gender, count, count/len(genders))
    return string

print( count_gender(genders) )

String concatenation is actually somewhat slow. You might consider:

def count_gender(genders):
    gender_types = valuesg1(genders)
    result = []
    for gender in gender_types:
        count = genders.count(gender)
        result.append( '{}: {} cases {:.2%}'.format(gender, count, count/len(genders)) )
    return '\n'.join(result)

print( count_gender(genders) )

Upvotes: 1

Related Questions