def is_anagram_w_dict(w1, w2): """ Store counts of letters in dictionaries for word1 and word2. If all counts of letters match, the words are anagrams. type: str, str rtype: bool runtime: O(a + b) space: O(a + b) """ if not w1 or not w2 or (not w1 and not w2): return False len_w1, len_w2 = len(w1), len(w2) if len_w1 != len_w2: return False counts_a = Counter(w1) counts_b = Counter(w2) for letter in w1: if counts_a[letter] != counts_b[letter]: return False return True
def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool """ return Counter(s) == Counter(t)
def extract_featuresets(ticker): tickers, df = process_data(ticker) hm_days = 7 # predict the buy sell or hold for the next 7 days and store it in a map # buy_sell_hold returns a 1, or -1 if ANY of the 7 inputs exceeds requirement, # not a value for each input. So it returns one output for n inputs. df['{}_target'.format(ticker)] = list( map(buy_sell_hold, *[df['{}_{}d'.format(ticker, i)] for i in range(1, hm_days + 1)])) vals = df['{}_target'.format(ticker)].values.tolist() str_vals = [str(i) for i in vals] # Just to see how many buy, sell or hold instructions from the model print("Data spread:", Counter(str_vals)) df.fillna(0, inplace=True) # replace infinite changes in prices with np.nan df = df.replace([np.inf, -np.inf], np.nan) df.dropna(inplace=True) # we have to be very accurate with what features to be sent and not send the columns for values to be predicted # normalizing the values df_vals = df[[t for t in tickers]].pct_change() df_vals = df_vals.replace([np.inf, -np.inf], np.nan) df_vals.fillna(0, inplace=True) x = df_vals.values y = df['{}_target'.format(ticker)].values return x, y, df
def count_tags(filename): taglist = [] tagdict = {} for event, element in ET.iterparse(filename): if event == 'end': taglist.append(element.tag) tagdict = DICT(Counter(taglist)) return tagdict
def plot_in_degrees(counts, name): """ Plot the degrees (connected nodes count for each from_node) against the number of occurences of that number of degrees (density) """ x, y = zip(*counts.items()) #x = original node number (not used in plot) #normalize counts s = np.sum(y) norm_y = [count / s for count in y] #count freq each level of connectedness occurs freq = Counter(norm_y) #create new x, y for plot x, y = zip(*freq.items()) #create a log/log plot of distribution plt.figure(figsize=(12, 8)) plt.scatter(np.log10(x), np.log10(y), marker='.') plt.title('In-Degree Distribution of Nodes (log/log) for %s' % name) plt.xlabel('Number of In-Degrees') plt.ylabel('Freq of In-Degrees') plt.show()
def binomial_histogram(p: float, n: int, num_points: int) -> float: """Pick points from a Binomial(n, p) and plot their distribution""" data = [binomial(n, p) for _ in range(num_points)] # use a bar chart to show the actual binomial samples histogram = Counter(data) plt.bar([x - .4 for x in histogram.keys()], [v / num_points for v in histogram.values()], 0.8, color="0.75") # parameters of the normal distribution mu = p * n sigma = math.sqrt((1 - p) * p * n) # use a line chart to show the normal distribution xs = range(min(data), max(data) + 1) ys = [ normal_cdf(x + 0.5, mu, sigma) - normal_cdf(x - 0.5, mu, sigma) for x in xs ] plt.plot(xs, ys) plt.title("Binomial Distribution vs. Normal Approximation")
def __init__(self, sntFile, oscServer=[]): global ser, shields, oldrot, oldwarp oldwarp = -1 oldrot = 0 shields = -1 #shields=-1 ser = serial.Serial(port='COM5', baudrate=9600) #self.sendser("1"); #self.sendser("2"); #the current Ship ID self.shipId = 0 # ship stats self.shipStats = { "shield": -1, "energy": -1, "coordY": -1, "coordX": -1, "warp rate": -1, "rotation rate": -1, "impulse rate": -1, "unknown": -1, "unknown2": -1, "rotation": -1, "frontshield": -1, "rearshield": -1, "weaponlock": -1, "autobeams": -1, "speed": -1 } #a map of bitfield position to value name and type self.statMapHelm = { 15: ("energy", 'f'), 21: ("coordY", 'f'), 19: ("coordX", 'f'), 16: ("shield", 'h'), 14: ("warp rate", 'b'), 10: ("rotation rate", 'f'), 9: ("impulse rate", 'f'), 23: ("unknown2", 'f'), 25: ("speed", 'f'), 24: ("rotation", 'f'), 28: ("frontshield", 'f'), 30: ("rearshield", 'f'), 8: ("weaponlock", "i"), 13: ("autobeams", 'b') } #sizes of struct fmt types. struct.calcsize returns size including alignment which this seems to ignore sometimes self.numLens = {'f': 4, 'h': 2, 'i': 4, 'b': 1} #load the ship data from the snt file self.shipMap = self.loadShipData(sntFile) # nowe we know the coords of ship systems count the number of each # this is sent to osc servers so that total damage of # ship systems can be calculated. # This is how the client does it... warp: 25% means 1 out of 4 nodes isnt # damaged self.systemCount = Counter(self.shipMap.values()) self.sendOSC = True if len(oscServer) == 2: print "start osc client.." simpleOSC.initOSCClient(oscServer[0], oscServer[1]) print "done" self.sendOSC = True