Exemplo n.º 1
0
def get_closing_ind(expr):
    paren_indices = list(
        map(lambda tup: tup[0],
            filter(lambda tup: tup[1] in '()', enumerate(expr))))
    return paren_indices[list(
        acc(map(lambda ind: 1
                if expr[ind] == '(' else -1, paren_indices))).index(0)]
Exemplo n.º 2
0
 def insert(self, text, line_no = 'end'):
     """Insert a piece of text (containing possibly many lines) to
     the file starting at the specified line number. Any existing 
     text is pushed down. """
     
     text_lines = text.split('\n')
     text_lines = [line + '\n' for line in text_lines]
     
     # Add one for the extra newline char added
     offset = len(text) + 1
     try:
         if line_no == 'end':
             line_no = len(self.lines)
         
         self.lines = self.lines[0: line_no - 1] + text_lines +  self.lines[line_no - 1: ]
         self.line_pos = [0] + list(acc([len(line) for line in self.lines]))
         
         current_pos = self.line_pos[line_no - 1]
         
         with open(self.filename, 'r+') as f:
             f.seek(current_pos)
             for i in range(line_no - 1, len(self.lines)):
                 f.write(self.lines[i])
     except IndexError:
         print('Error: line number out of range')
Exemplo n.º 3
0
    def balancedStringSplit(self, s: str) -> int:
        #1
        r_num = 0
        l_num = 0
        res = 0
        for c in s:
            if c == 'R':
                r_num += 1
            elif c == 'L':
                l_num += 1
            if r_num != 0 and r_num == l_num:
                res += 1
        return res

        #2
        d = {'R': 0, 'L': 0}
        res = 0
        for c in s:
            d[c] += 1
            if d['R'] == d['L']:
                res += 1
        return res

        #From others

        #one line
        return list(acc(1 if c == 'L' else -1 for c in s)).count(0)

        # (True = 1)
        res = cnt = 0
        for c in s:
            cnt += c == 'L'
            cnt -= c == 'R'
            res += cnt == 0
        return res
Exemplo n.º 4
0
def sos_calculation(game_data):
  """
  For each team, performs Strength of Schedule (SOS) calculations for each season for which they were in the FBS
  This function takes up a majority of training time, and I'm always looking for ways to improve its speed.
  """
  for team in cfg.ratings_dict.keys():
    for season in range(cfg.first_season, cfg.last_season + 1):
      if cfg.ratings_dict[team][str(season)+'League'] != 'FCS':
        season_indices = cfg.index_dict[team][season]
        opponents = game_data.at[season_indices['total'][-1],'home_opponents'][:-1]
        opp_ratings = np.array([cfg.ratings_dict[opp][str(season) + 'Rating'] for opp in opponents])
        avg_sos = pd.Series(np.concatenate([[0.5],
            np.array(list(acc(opp_ratings, lambda x, y: x*cfg.r + y)))/
            np.array(list(acc([1]*(len(opp_ratings)), lambda x, y: x*cfg.r + y)))]),
          season_indices['total'])
        
        game_data.at[season_indices['home'], 'home_SOS'] = avg_sos.loc[season_indices['home']]
        game_data.at[season_indices['away'], 'away_SOS'] = avg_sos.loc[season_indices['away']]
Exemplo n.º 5
0
def gini():
    aux=0
    #ya está ordenado así que no hace falta ordenarlo
    accu=list(acc(distr['probab']))
    plt.plot(np.linspace(0,1,len(accu)),accu)
    plt.plot(np.linspace(0,1,len(accu)),np.linspace(0,1,len(accu)))
    plt.show()
    for i in range(1,len(accu)):
        aux+=(accu[i]+accu[i-1])/len(accu)
    return 1-aux
Exemplo n.º 6
0
def NumArray(nums):
    cumsum = []
    cumsum = list(acc(nums))

    def sumRange(i, j):
        nonlocal cumsum
        return cumsum[j] - (cumsum[i - 1] if i > 0 else 0)

    def caller():
        pass

    caller.sumRange = sumRange
    return caller
Exemplo n.º 7
0
 def replace(self, text, line_no = 'end'):
     """Replace a set of lines in the file with a block of text starting
     at the specified line number. """
     text_lines = text.split('\n')
     text_lines = [line + '\n' for line in text_lines]
     
     # Add one for the extra newline char added
     offset = len(text) + 1
     try:
         if line_no == 'end':
             line_no = len(self.lines)
         
         self.lines = self.lines[0: line_no - 1] + text_lines +  self.lines[line_no - 1 + len(text): ]
         self.line_pos = [0] + list(acc([len(line) for line in self.lines]))
         
         current_pos = self.line_pos[line_no - 1]
         
         with open(self.filename, 'r+') as f:
             f.seek(current_pos)
             for i in range(line_no - 1, len(self.lines)):
                 f.write(self.lines[i])
     except IndexError:
         print('Error: line number out of range')
Exemplo n.º 8
0
def monthdays(year, month):
    assert 0 <= month < 12
    d = [
        0, 31, 29 if leap(year) else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
    ]
    return list(acc(d))[month]
Exemplo n.º 9
0
import numpy as np
from itertools import accumulate as acc
import matplotlib.pyplot as plt

h = []
plt.figure(1)
plt.subplot(211)
for i in range(1000):
    a = list(acc(list(np.random.choice([-1, 1], size=5000))))
    h.append(a[49])
    lst1 = [0] + a
    plt.plot(lst1, linewidth=0.2)
plt.subplot(212)
n, bins, patches = plt.hist(h, 10, normed=1)
plt.subplots_adjust(top=1, bottom=0, left=0, right=1, hspace=0, wspace=0)
plt.show()
Exemplo n.º 10
0
from itertools import accumulate as acc
a = [i for i in range(1000)]
a = list(acc(a))

A, B = map(int, input().split())
print(a[B - A] - B)
Exemplo n.º 11
0
import sys
from itertools import accumulate as acc

s = sys.stdin.readlines()
N, M, _ = map(int, s[0].split())
X = [[0] * N for _ in [0] * N]
for L, R in (map(int, e.split()) for e in s[1:M + 1]):
    X[L - 1][R - 1] += 1
S = [tuple(acc(reversed(s))) for s in zip(*(acc(x) for x in X))]
print('\n'.join(
    map(str, (S[q - 1][N - p]
              for p, q in (map(int, e.split()) for e in s[M + 1:])))))
Exemplo n.º 12
0
 def balancedStringSplit4(self, s: str) -> int:
     return list(acc(map({'R': -1, 'L': 1}.get, s))).count(0)
Exemplo n.º 13
0
 def balancedStringSplit3(self, s: str) -> int:
     return list(acc(map(" L".find, s))).count(
         0)  #stringS = " L"; stringS.find(c); for c in s. #TODO
Exemplo n.º 14
0
def data_gather(data_type = 'adv', verbose = True):  
  """
  Returns a DataFrame of cumulative statistics that the model can be trained on.
  ----------  
  Parameters
  ----------
    first_season, last_season: int
      The function gathers statistics from the years in the range [first_season, last_season].
    data_type: str
      The type of statistics to be prepared. Right now, the function only works for "advanced" statistics.
      I plan to add the ability to gather and prepare "regular" statistics as well.
    verbose: bool
  -----
  Notes
  -----
  The function performs several tasks:
   - Scrapes game information, per-game statistics, and talent ratings
   - Calculates each team's cumulative per-game statistics
     - e.g. a team's offensive efficiency statistic in its 5th game will be the mean of its offensive efficiency statistics
       from games 1-4.
   - Normalizes the talent ratings and cumulative statistics
   - Initializes SOS and last season ratings
   - It is admittedly messy
  """
  total = pd.DataFrame()
  for season in range(cfg.first_season, cfg.last_season + 1):
    if verbose == True:
      print('Gathering stats from', season)

    games = data_scrape.games_scrape(season)
    games = game_data_filter(games, season)
    game_data = pd.DataFrame({'id': games.id,
                              'home_team': games.home_team,
                              'away_team': games.away_team,
                              'home_conference': games.home_conference,
                              'away_conference': games.away_conference,
                              'season': games.season,
                              'week': games.week,
                              'neutral': games.neutral_site,
                              'y_actual': games.home_points - games.away_points,
                              'home_points': games.home_points,
                              'away_points': games.away_points,
                              'home_opponents': None,
                              'away_opponents': None
                              }
                             )

    if data_type == 'adv':
      season_data = data_scrape.adv_data_scrape(season)
      season_data = adv_season_data_filter(season_data, season).drop(
        columns = ['gameId']).sort_values('week').fillna(season_data.mean())
    elif data_type == 'reg':
      season_data = data_scrape.reg_data_scrape(season).drop(
        columns = ['gameId']).sort_values('week').fillna(season_data.mean())
      
    n_cols = len(season_data.columns)
    means = season_data.mean()
    fbs_teams = set([team for team in season_data.team if len(season_data[season_data.team == team]) > 3])

    season_data['offpoints'] = None
    season_data['defpoints'] = None
    season_data['games'] = None
    
    for team in fbs_teams:
      season_data = season_data.append(
        pd.Series([20,team,team]+[None]*n_cols, index = season_data.columns),
        ignore_index = True)

      team_season_data = season_data[season_data.team==team]
      opponents = list(team_season_data.opponent)
      game_data = game_data.append(
        pd.Series([None]+[team]*2+[None]*2+[season, 20]+[None]*4+[opponents]+[None],
        index = game_data.columns), ignore_index=True)

      n_games = len(team_season_data) - 1
      game_range_discount = np.array(list(acc([1]*(n_games), lambda x, y: x*cfg.r + y)))
      tsd_index = team_season_data.index      
      for col in season_data.columns[3:-3]:
        season_data.at[tsd_index, col] = pd.Series(np.concatenate(
          [[means[col]], np.array(list(acc(team_season_data[col][:-1], lambda x, y: x*cfg.r + y))
          )/game_range_discount]), index = tsd_index)
        
      season_data.at[tsd_index, 'games'] = pd.Series([i for i in range(n_games + 1)],
        index = tsd_index)
      
      season_data.at[tsd_index, 'offpoints'] = pd.Series(np.concatenate([[30.0], np.array(
        list(acc(game_data.loc[game_data.home_team == team, 'home_points'].append(
          game_data.loc[game_data.away_team == team, 'away_points']
          ).dropna().sort_index()[:n_games], lambda x, y: x*cfg.r + y))
          )/game_range_discount]), index = tsd_index)
      
      season_data.at[tsd_index, 'defpoints'] = pd.Series(np.concatenate([[30.0], np.array(
        list(acc(game_data.loc[game_data.home_team == team, 'away_points'].append(
          game_data.loc[game_data.away_team == team, 'home_points']
          ).dropna().sort_index()[:n_games], lambda x, y: x*cfg.r + y))
          )/game_range_discount]), index = tsd_index)

    talent = data_scrape.talent_scrape(season)
    talent.talent = talent.talent.astype('float32')
    talent.talent -= min(talent.talent)
    talent.talent /= max(talent.talent)
    season_data = season_data.merge(talent, how = 'left', on = 'team').fillna(0.0)
    
    game_data = game_data.merge(season_data, left_on = ['home_team', 'away_team', 'week'],
                                right_on = ['team', 'opponent', 'week']
                                ).drop(columns = ['team', 'opponent'])
    col_dict = {}
    for col in game_data.columns[13:]:
      col_dict[col] = 'home_' + col
    game_data = game_data.rename(columns = col_dict)
    
    game_data['home_last_rating'] = 0.5
    game_data['home_SOS'] = 0.45

    game_data = game_data.merge(season_data, left_on = ['away_team', 'home_team', 'week'],
                                right_on = ['team', 'opponent', 'week']
                               ).drop(columns = ['team', 'opponent'])
    col_dict = {}
    for col in game_data.columns[(len(game_data.columns) - 13)//2 + 14:]:
      col_dict[col] = 'away_' + col
    game_data = game_data.rename(columns = col_dict)

    game_data['away_last_rating'] = 0.5
    game_data['away_SOS'] = 0.45

    game_data = add_sp_ratings(game_data, season)

    total = pd.concat([total, game_data])

  for col in total.columns[13:(len(total.columns)-13)//2 + 10]:
    custom_normalization(total, col)
    """home_away = np.concatenate([total[col], total['away_' + col[5:]]])
    col_min = min(home_away)
    col_max = max(home_away)
    total[col] = (total[col] - col_min)/(col_max - col_min)
    total['away_' + col[5:]] = (total['away_' + col[5:]] - col_min)/(col_max - col_min)"""
    
  return total.reset_index(drop=True)
Exemplo n.º 15
0
 def runningSum(self, numbers: list[int]) -> list[int]:
     return list(acc(numbers))
 def balancedStringSplit(self, s: str) -> int:
     return list(acc(1 if c == 'L' else -1 for c in s)).count(0)
Exemplo n.º 17
0
ai = lambda: list(map(int, input().split()))

n, m = ai()
x = ai()
y = ai()
mod = 10**9 + 7

from itertools import accumulate as acc
sx = list(acc(x))
ssx = list(acc(x[::-1]))
sy = list(acc(y))
ssy = list(acc(y[::-1]))

a = sum(ssx[i] - sx[i] for i in range(n)) % mod
b = sum(ssy[i] - sy[i] for i in range(m)) % mod

print(a * b % mod)
Exemplo n.º 18
0
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
from itertools import accumulate as acc

mpl.rcParams['legend.fontsize'] = 7

fig = plt.figure()
ax = fig.gca(projection='3d')
for i in range(5):
    z = list(
        acc(np.random.choice(np.arange(-1, 1, step=(i + 1) * 0.01), size=200)))
    x = list(
        acc(np.random.choice(np.arange(-1, 1, step=(i + 1) * 0.01), size=200)))
    y = list(
        acc(np.random.choice(np.arange(-1, 1, step=(i + 1) * 0.01), size=200)))
    ax.plot(x, y, z, label='3d Brawny wit dt = {}'.format((i + 1) * 0.01))
ax.legend()

plt.show()
def sum_sq():
    for y in range(N):
        sq[y] = list(acc(sq[y]))
    for y in range(1, N):
        for x in range(N):
            sq[y][x] += sq[y - 1][x]
Exemplo n.º 20
0
from itertools import accumulate as acc

n1, n2, n3 = map(int, input().split())  # useless

s = [set(acc(map(int, reversed(input().strip().split())))) for _ in range(3)]

s = set.intersection(*s)

print(max(s) if len(s) > 0 else 0)
Exemplo n.º 21
0
 def __init__(self, weights):
     total = sum(weights)
     self.p = list(acc(i / total for i in weights))