def findCoords(gs, candidates=None): if candidates == None: candidates=[] # List all the possible z-level (heights) zRange = list(takewhile(lambda x : x < gs.boardSize[2], \ sort(unique(flatten(gs.heightMap()))))) if zRange==[]: print "Board is full, cannot find legal coordinates !" return None else: zRange = sort(unique(map(third,candidates))) # Do we have a choice on the z-level ? if len(zRange)==1: z = zRange[0] else: print "\n",gs.boardToASCII(markedCubes=candidates) # Discard the z height max if zRange[-1]==gs.boardSize[2]: zRange = zRange[:-1] z = -1+input("Which z-level ? (%d-%d)\n> " \ % (zRange[0]+1,zRange[-1]+1)) candidates = filter(lambda c: c[2]==z, candidates) if len(candidates)>1: # Display the z-level with xy coordinates as letter-number print ' '+''.join(chr(97+x) for x in xrange(gs.boardSize[0])) print ' +'+'-'*gs.boardSize[0] lines = gs.boardToASCII(zRange=[z],markedCubes=candidates)\ .split('\n') for y in xrange(gs.boardSize[1]): print '%s |%s' % (str(y+1).zfill(2),lines[y]) print "\n" xy = raw_input("Which xy coordinates ?\n> ") return array([ord(xy[0])-97,int(xy[1:])-1,z]) else: return candidates[0]
def getReductionList(colnum, rownum, sizeOfM=28): """"given the rows and columns we are intrested on and the size of the Picture, and returns the relevant Pixels's numbers. because the 0-place represents b in the classifier (w*x)+b it must be a part of the reduced set""" reduced = [0] for c in colnum: for i in xrange(0, sizeOfM): reduced.append(c + i * sizeOfM) for r in rownum: for i in xrange(0, sizeOfM): reduced.append(i + r * sizeOfM) return sort(list(set(reduced)))
def getReductionList(colnum,rownum,sizeOfM=28): """"given the rows and columns we are intrested on and the size of the Picture, and returns the relevant Pixels's numbers. because the 0-place represents b in the classifier (w*x)+b it must be a part of the reduced set""" reduced = [0] for c in colnum: for i in xrange(0,sizeOfM): reduced.append(c+i*sizeOfM) for r in rownum: for i in xrange(0,sizeOfM): reduced.append(i+r*sizeOfM) return sort(list(set(reduced)))
def printResults(self): """ prints the result of the game to the output specified in output """ cls() result = calculateResult(self.circuit) results = [] for player in self.players: results.append((hamming(result, player.endconfig), player.name)) reversed(sort(results)) _, y = results[0] output('Player ' + str(y) + ' wins!\n' + str(results)) printSeparation() output(self.circuit.draw())
def univariate_selection(dataframe: pd.DataFrame, num_features: int, data_class: str) -> pd.DataFrame: # Remove ``timestamp`` and ``Hospital Number`` columns as they ought to be present in the dataset dataframe = dataframe.drop(["event_timestamp", "Hospital Number"], axis=1) if num_features > 9: raise ValueError( f"Number of features must be <= 9; you've given {num_features}") X = dataframe.iloc[:, dataframe.columns != data_class] y = dataframe.loc[:, data_class] test = SelectKBest(score_func=f_classif, k=num_features) fit = test.fit(X, y) indices = sort((-fit.scores_).argsort()[:num_features]) column_names = list(map(X.columns.__getitem__, indices)) column_names.extend([data_class]) features = fit.transform(X) return pd.DataFrame(np.c_[features, y.to_numpy()], columns=column_names)
def transformSeries(self, series, as_is=True, sort_series=True, set_series=False): values = [] for value in series.values: value = word_tokenize(value) tempTokens = [] for token in value: token = self.stemmer.stem(token) tempTokens.append(token) if as_is: values.append(' '.join(tempTokens)) else: values.extend(tempTokens) ret = list(values) if set_series: ret = list(set(ret)) if sort_series: ret = sort(ret) return Series(ret)
def histogramdd(sample, bins=10, range=None, normed=False, weights=None): """histogramdd(sample, bins=10, range=None, normed=False, weights=None) Return the N-dimensional histogram of the sample. Parameters: sample : sequence or array A sequence containing N arrays or an NxM array. Input data. bins : sequence or scalar A sequence of edge arrays, a sequence of bin counts, or a scalar which is the bin count for all dimensions. Default is 10. range : sequence A sequence of lower and upper bin edges. Default is [min, max]. normed : boolean If False, return the number of samples in each bin, if True, returns the density. weights : array Array of weights. The weights are normed only if normed is True. Should the sum of the weights not equal N, the total bin count will not be equal to the number of samples. Returns: hist : array Histogram array. edges : list List of arrays defining the lower bin edges. SeeAlso: histogram Example >>> x = random.randn(100,3) >>> hist3d, edges = histogramdd(x, bins = (5, 6, 7)) """ try: # Sample is an ND-array. N, D = sample.shape except (AttributeError, ValueError): # Sample is a sequence of 1D arrays. sample = atleast_2d(sample).T N, D = sample.shape nbin = empty(D, int) edges = D * [None] dedges = D * [None] if weights is not None: weights = asarray(weights) try: M = len(bins) if M != D: raise AttributeError, 'The dimension of bins must be a equal to the dimension of the sample x.' except TypeError: bins = D * [bins] # Select range for each dimension # Used only if number of bins is given. if range is None: smin = atleast_1d(array(sample.min(0), float)) smax = atleast_1d(array(sample.max(0), float)) else: smin = zeros(D) smax = zeros(D) for i in arange(D): smin[i], smax[i] = range[i] # Make sure the bins have a finite width. for i in arange(len(smin)): if smin[i] == smax[i]: smin[i] = smin[i] - .5 smax[i] = smax[i] + .5 # Create edge arrays for i in arange(D): if isscalar(bins[i]): nbin[i] = bins[i] + 2 # +2 for outlier bins edges[i] = linspace(smin[i], smax[i], nbin[i] - 1) else: edges[i] = asarray(bins[i], float) nbin[i] = len(edges[i]) + 1 # +1 for outlier bins dedges[i] = diff(edges[i]) nbin = asarray(nbin) # Compute the bin number each sample falls into. Ncount = {} for i in arange(D): Ncount[i] = digitize(sample[:, i], edges[i]) # Using digitize, values that fall on an edge are put in the right bin. # For the rightmost bin, we want values equal to the right # edge to be counted in the last bin, and not as an outlier. outliers = zeros(N, int) for i in arange(D): # Rounding precision decimal = int(-log10(dedges[i].min())) + 6 # Find which points are on the rightmost edge. on_edge = where( around(sample[:, i], decimal) == around(edges[i][-1], decimal))[0] # Shift these points one bin to the left. Ncount[i][on_edge] -= 1 # Flattened histogram matrix (1D) hist = zeros(nbin.prod(), float) # Compute the sample indices in the flattened histogram matrix. ni = nbin.argsort() shape = [] xy = zeros(N, int) for i in arange(0, D - 1): xy += Ncount[ni[i]] * nbin[ni[i + 1:]].prod() xy += Ncount[ni[-1]] # Compute the number of repetitions in xy and assign it to the flattened histmat. if len(xy) == 0: return zeros(nbin - 2, int), edges flatcount = bincount(xy, weights) a = arange(len(flatcount)) hist[a] = flatcount # Shape into a proper matrix hist = hist.reshape(sort(nbin)) for i in arange(nbin.size): j = ni[i] hist = hist.swapaxes(i, j) ni[i], ni[j] = ni[j], ni[i] # Remove outliers (indices 0 and -1 for each dimension). core = D * [slice(1, -1)] hist = hist[core] # Normalize if normed is True if normed: s = hist.sum() for i in arange(D): shape = ones(D, int) shape[i] = nbin[i] - 2 hist = hist / dedges[i].reshape(shape) hist /= s return hist, edges
def histogram(a, bins=10, range=None, normed=False): """Compute the histogram from a set of data. Parameters: a : array The data to histogram. n-D arrays will be flattened. bins : int or sequence of floats If an int, then the number of equal-width bins in the given range. Otherwise, a sequence of the lower bound of each bin. range : (float, float) The lower and upper range of the bins. If not provided, then (a.min(), a.max()) is used. Values outside of this range are allocated to the closest bin. normed : bool If False, the result array will contain the number of samples in each bin. If True, the result array is the value of the probability *density* function at the bin normalized such that the *integral* over the range is 1. Note that the sum of all of the histogram values will not usually be 1; it is not a probability *mass* function. Returns: hist : array The values of the histogram. See `normed` for a description of the possible semantics. lower_edges : float array The lower edges of each bin. SeeAlso: histogramdd """ a = asarray(a).ravel() if (range is not None): mn, mx = range if (mn > mx): raise AttributeError, 'max must be larger than min in range parameter.' if not iterable(bins): if range is None: range = (a.min(), a.max()) mn, mx = [mi + 0.0 for mi in range] if mn == mx: mn -= 0.5 mx += 0.5 bins = linspace(mn, mx, bins, endpoint=False) else: if (any(bins[1:] - bins[:-1] < 0)): raise AttributeError, 'bins must increase monotonically.' # best block size probably depends on processor cache size block = 65536 n = sort(a[:block]).searchsorted(bins) for i in xrange(block, a.size, block): n += sort(a[i:i + block]).searchsorted(bins) n = concatenate([n, [len(a)]]) n = n[1:] - n[:-1] if normed: db = bins[1] - bins[0] return 1.0 / (a.size * db) * n, bins else: return n, bins
import numpy as pd from numpy.core.fromnumeric import sort #Read the content of the file ages = pd.loadtxt('ages.txt') #Print the content of the file print(ages) #Print the number of the number of items print(ages.shape) #Print the shorted list print(sort(ages))
def algebraic_connectiveity(self): eigenvector = nx.laplacian_spectrum(self.gra) return round(sort(eigenvector)[1], 4)
def histogram(a, bins=10, range=None, normed=False): """Compute the histogram from a set of data. Parameters: a : array The data to histogram. n-D arrays will be flattened. bins : int or sequence of floats If an int, then the number of equal-width bins in the given range. Otherwise, a sequence of the lower bound of each bin. range : (float, float) The lower and upper range of the bins. If not provided, then (a.min(), a.max()) is used. Values outside of this range are allocated to the closest bin. normed : bool If False, the result array will contain the number of samples in each bin. If True, the result array is the value of the probability *density* function at the bin normalized such that the *integral* over the range is 1. Note that the sum of all of the histogram values will not usually be 1; it is not a probability *mass* function. Returns: hist : array The values of the histogram. See `normed` for a description of the possible semantics. lower_edges : float array The lower edges of each bin. SeeAlso: histogramdd """ a = asarray(a).ravel() if not iterable(bins): if range is None: range = (a.min(), a.max()) mn, mx = [mi+0.0 for mi in range] if mn == mx: mn -= 0.5 mx += 0.5 bins = linspace(mn, mx, bins, endpoint=False) # best block size probably depends on processor cache size block = 65536 n = sort(a[:block]).searchsorted(bins) for i in xrange(block, a.size, block): n += sort(a[i:i+block]).searchsorted(bins) n = concatenate([n, [len(a)]]) n = n[1:]-n[:-1] if normed: db = bins[1] - bins[0] return 1.0/(a.size*db) * n, bins else: return n, bins
def histogramdd(sample, bins=10, range=None, normed=False, weights=None): """histogramdd(sample, bins=10, range=None, normed=False, weights=None) Return the N-dimensional histogram of the sample. Parameters: sample : sequence or array A sequence containing N arrays or an NxM array. Input data. bins : sequence or scalar A sequence of edge arrays, a sequence of bin counts, or a scalar which is the bin count for all dimensions. Default is 10. range : sequence A sequence of lower and upper bin edges. Default is [min, max]. normed : boolean If False, return the number of samples in each bin, if True, returns the density. weights : array Array of weights. The weights are normed only if normed is True. Should the sum of the weights not equal N, the total bin count will not be equal to the number of samples. Returns: hist : array Histogram array. edges : list List of arrays defining the lower bin edges. SeeAlso: histogram Example >>> x = random.randn(100,3) >>> hist3d, edges = histogramdd(x, bins = (5, 6, 7)) """ try: # Sample is an ND-array. N, D = sample.shape except (AttributeError, ValueError): # Sample is a sequence of 1D arrays. sample = atleast_2d(sample).T N, D = sample.shape nbin = empty(D, int) edges = D*[None] dedges = D*[None] if weights is not None: weights = asarray(weights) try: M = len(bins) if M != D: raise AttributeError, 'The dimension of bins must be a equal to the dimension of the sample x.' except TypeError: bins = D*[bins] # Select range for each dimension # Used only if number of bins is given. if range is None: smin = atleast_1d(array(sample.min(0), float)) smax = atleast_1d(array(sample.max(0), float)) else: smin = zeros(D) smax = zeros(D) for i in arange(D): smin[i], smax[i] = range[i] # Make sure the bins have a finite width. for i in arange(len(smin)): if smin[i] == smax[i]: smin[i] = smin[i] - .5 smax[i] = smax[i] + .5 # Create edge arrays for i in arange(D): if isscalar(bins[i]): nbin[i] = bins[i] + 2 # +2 for outlier bins edges[i] = linspace(smin[i], smax[i], nbin[i]-1) else: edges[i] = asarray(bins[i], float) nbin[i] = len(edges[i])+1 # +1 for outlier bins dedges[i] = diff(edges[i]) nbin = asarray(nbin) # Compute the bin number each sample falls into. Ncount = {} for i in arange(D): Ncount[i] = digitize(sample[:,i], edges[i]) # Using digitize, values that fall on an edge are put in the right bin. # For the rightmost bin, we want values equal to the right # edge to be counted in the last bin, and not as an outlier. outliers = zeros(N, int) for i in arange(D): # Rounding precision decimal = int(-log10(dedges[i].min())) +6 # Find which points are on the rightmost edge. on_edge = where(around(sample[:,i], decimal) == around(edges[i][-1], decimal))[0] # Shift these points one bin to the left. Ncount[i][on_edge] -= 1 # Flattened histogram matrix (1D) hist = zeros(nbin.prod(), float) # Compute the sample indices in the flattened histogram matrix. ni = nbin.argsort() shape = [] xy = zeros(N, int) for i in arange(0, D-1): xy += Ncount[ni[i]] * nbin[ni[i+1:]].prod() xy += Ncount[ni[-1]] # Compute the number of repetitions in xy and assign it to the flattened histmat. if len(xy) == 0: return zeros(nbin-2, int), edges flatcount = bincount(xy, weights) a = arange(len(flatcount)) hist[a] = flatcount # Shape into a proper matrix hist = hist.reshape(sort(nbin)) for i in arange(nbin.size): j = ni[i] hist = hist.swapaxes(i,j) ni[i],ni[j] = ni[j],ni[i] # Remove outliers (indices 0 and -1 for each dimension). core = D*[slice(1,-1)] hist = hist[core] # Normalize if normed is True if normed: s = hist.sum() for i in arange(D): shape = ones(D, int) shape[i] = nbin[i]-2 hist = hist / dedges[i].reshape(shape) hist /= s return hist, edges