{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import random\n",
    "from scipy.stats import chi2, poisson"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[2, 3, 4, 1, 3, 2, 1, 2, 2, 1, 3, 1, 3, 1, 2, 3, 2, 4, 2, 1, 4, 3, 4, 4, 3, 4, 1, 3, 4, 4, 3, 1, 4, 2, 1, 4]\n"
     ]
    }
   ],
   "source": [
    "# roll 36 4-sided dice\n",
    "rolls = [random.randint(1, 4) for i in range(36)]\n",
    "print(rolls)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[9, 9, 9, 9]\n",
      "[9, 8, 9, 10]\n"
     ]
    }
   ],
   "source": [
    "expected = [9, 9, 9, 9]\n",
    "# count each of the 1s, 2s, 3s, and 4s\n",
    "observed = [rolls.count(1), rolls.count(2), \n",
    "            rolls.count(3), rolls.count(4)]\n",
    "print(expected)\n",
    "print(observed)\n",
    "# [9, 9, 9, 9]\n",
    "# [9, 8, 9, 10]\n",
    "# by hand -> 2/9 chi2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.2222222222222222\n"
     ]
    }
   ],
   "source": [
    "# calculate the chi^2-value\n",
    "chi_squared = ((rolls.count(1) - 9) ** 2 / 9) + \\\n",
    "                ((rolls.count(2) - 9) ** 2 / 9) + \\\n",
    "                ((rolls.count(3) - 9) ** 2 / 9) + \\\n",
    "                ((rolls.count(4) - 9) ** 2 / 9)\n",
    "print(chi_squared)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9739245692310424\n"
     ]
    }
   ],
   "source": [
    "# get our p-value\n",
    "degrees_of_freedom = 3 # 4 - 1\n",
    "print(1 - chi2.cdf(chi_squared, df = degrees_of_freedom))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
