0

I am a beginner programmer and currently trying to code moral worth in the context of a public good game with cooperators, deceptors, and peer-punishers.

To start, I wanted to start simple and associate being a cooperator and a peer-punisher with +1 moral worth, and being a deceptor with -1 moral worth.

What I tried

# Calculate moral worth
def computeMoralWorth(k, playertype):  
    mw = 0
    if playertype == 'D':
        mw -= 1
    elif playertype == 'C' or playertype == 'Pep':
        mw += 1   
    return mw

# Simulate moral worth over time
def simulateMoralWorth(k, T, s):
    m_w = {} # Used to store moral worth data
    for playertype in k.keys():
        m_w[playertype] = [k[playertype]]*T
    for i in range(T):
        pop = generatePop(k)
        moralw = {}
        for playertype in k.keys():
            moralw[playertype] = computeMoralWorth(k, playertype)
        m_w = logmoralw(m_w, moralw, i)
    return m_w

# Generate population based on initial composition 'k'
def generatePop(k):
    pop = []
    for playertype in k.keys():
        for i in range(int(k[playertype])):
            player = {}
            player['type'] = playertype
            pop.append(player)
    return pop

# Log moral worth data over time
def logmoralw(m_w, moralw, i):
    for playertype in moralw.keys():
        m_w[playertype][i] = moralw[playertype]
    return m_w

# Define simulation parameters
k = {'C':0, 'D':N, 'Pep':0}
T = 100000 # Time
N = 100 # Total population size
s = np.inf # Imitation strength

# Run simulation
moral_worth_data = simulateMoralWorth(k, T, s)
print(moral_worth_data['C'][-1])
print(moral_worth_data['D'][-1])
print(moral_worth_data['Pep'][-1])

Output it gives me:

0 100 0

I expected to have something like this show up:

{'C': some_number,
     'D': some_number,
     'PeP':some_number}

BUT

It seems when I try to run the simulation, nothing actually shows up. What am I doing wrong? (I get no errors btw)

Joca97
  • 3
  • 3

1 Answers1

0

You haven't output anything. Try adding this to the end -

print(moral_worth_data)

here is the full code with added line, and a value substituted into the population size N, which is assigned to variable 'D':

import numpy as np
# Calculate moral worth
def computeMoralWorth(k, playertype):  
    mw = 0
    if playertype == 'D':
        mw -= 1
    elif playertype == 'C' or playertype == 'Pep':
        mw += 1   
    return mw

# Simulate moral worth over time
def simulateMoralWorth(k, T, s):
    m_w = {} # Used to store moral worth data
    for playertype in k.keys():
        m_w[playertype] = [k[playertype]]*T
    for i in range(T):
        pop = generatePop(k)
        moralw = {}
        for playertype in k.keys():
            moralw[playertype] = computeMoralWorth(k, playertype)
        m_w = logmoralw(m_w, moralw, i)
    return m_w

# Generate population based on initial composition 'k'
def generatePop(k):
    pop = []
    for playertype in k.keys():
        for i in range(int(k[playertype])):
            player = {}
            player['type'] = playertype
            pop.append(player)
    return pop

# Log moral worth data over time
def logmoralw(m_w, moralw, i):
    for playertype in moralw.keys():
        m_w[playertype][i] = moralw[playertype]
    return m_w

# Define simulation parameters
k = {'C':0, 'D':500, 'Pep':0}
T = 100000 # Time
N = 100 # Total population size
s = np.inf # Imitation strength

# Run simulation
moral_worth_data = simulateMoralWorth(k, T, s)

Suggested addition at the end:

# Assign final values to new dictionary
Output = {key:moral_worth_data[key][-1] for key in moral_worth_data.keys()}
# show results
print(Output)

Alternatively use a for loop

for key in moral_worth_data.keys():
    print(key,":",np.average(moral_worth_data[key]))

or hard code your print statement:

print('C :',moral_worth_data['C'])
print('D :',moral_worth_data['D'])
print('Pep :',moral_worth_data['Pep'])

The added step is a dictionary comprehension that extracts the last score given to / item in the list for 'C', 'D', and 'Pep', rather than assigning an aggregate value such as sum(moral_worth_data[key]) or np.mean(moral_worth_data[key]). I take this from the discussion in comments.

ciaran haines
  • 294
  • 1
  • 11
  • I have edited my question since I've tried something new. If I try the way that you mentioned, it just lists a multitude of numbers and not the output I was want. – Joca97 Mar 27 '23 at 13:24
  • Hey @Joca97. Where you have `print(moral_worth_data['C'][-1])` you are only outputting the value. It looks like you want the key & value together. See my edited answer for a suggestion. Maybe assign a new value for the outputs eg `Output = {key:moral_worth_data[key][-1] for key in moral_worth_data.keys()}` then `print(output)` – ciaran haines Mar 27 '23 at 13:30
  • If this answers your query, please consider marking my response as the solution. Cheers x – ciaran haines Mar 27 '23 at 13:31
  • Also, did you mean to use a number instead or N in this line `k = {'C':0, 'D':N, 'Pep':0}`? – ciaran haines Mar 27 '23 at 13:33
  • No, I meant to use N, which represents the total population size. Also I added your suggestion, but unfortunately it gives me a syntax error. – Joca97 Mar 28 '23 at 06:35
  • If you share the syntax error, we may be able to move forward. Answer edited with a full program with my suggested solution. I don't get a syntax error. – ciaran haines Mar 28 '23 at 08:32
  • try `[print(key,":",np.average(moral_worth_data[key])) for key in moral_worth_data.keys()]` to make this a list comprehension, or use a for loop which I'll add to the answer. – ciaran haines Mar 28 '23 at 08:40
  • I still get a syntax error when I try that. I've also tried this [for key in moral_worth_data.keys(): print(key, ":", sum(moral_worth_data[key]))}' ] but then it says N isn't defined, which I have defined it. Thank you for your continuing help btw :) – Joca97 Mar 28 '23 at 08:44
  • in a list comprehension, the for statement must go after the action. In a for loop, you can't have brackets around it. You also have mixed brackets, starting with `[` and ending with `}` – ciaran haines Mar 28 '23 at 08:46
  • 1
    I've changed it, but for some reason it gives me the same error. Am I supposed to add the brackets as well? Because when I do, it gives me that "N not defined" error, but when I don't, it gives me the following error. ``Cell In[6], line 45 print(key,":",np.average(moral_worth_data[key])) for key in moral_worth_data.keys() ^ SyntaxError: invalid syntax`` – Joca97 Mar 28 '23 at 09:02
  • When it says "N not defined", that is the code working. You need to tell your code how many times to run, so you must replace N with an integer value. – ciaran haines Mar 28 '23 at 09:05
  • I've just realised that you have assigned a value to N, but only after you have assigned N to k. if you move `k = {'C':0, 'D':N, 'Pep':0}` after `N=100` it should work. – ciaran haines Mar 28 '23 at 09:11
  • 1
    I will mess around with the code for a while to see if I haven't missed anything you suggested doing, and I will get back to you, if that's okay. Thank you very much for the help! – Joca97 Mar 28 '23 at 09:26
  • If this works for you, please consider marking my answer as the solution. Good luck on your python journey :) – ciaran haines Mar 28 '23 at 09:44
  • Thank you and If it works, I'll give credit where credit is due. Thank you :) – Joca97 Mar 28 '23 at 12:39