Best Python code snippet using slash
core.py
Source:core.py  
1"""Python RunStats2Compute Statistics and Regression in a single pass.3"""4from __future__ import division5class Statistics(object):6    """Compute statistics in a single pass.7    # pylint: disable=too-many-instance-attributes8    Computes the minimum, maximum, mean, variance, standard deviation,9    skewness, and kurtosis.10    Statistics objects may also be added together and copied.11    Based entirely on the C++ code by John D Cook at12    http://www.johndcook.com/skewness_kurtosis.html13    """14    def __init__(self, iterable=()):15        """Initialize Statistics object.16        Iterates optional parameter `iterable` and pushes each value into the17        statistics summary.18        """19        self.clear()20        for value in iterable:21            self.push(value)22    def clear(self):23        """Clear Statistics object."""24        self._count = self._eta = self._rho = self._rho2 \25                    = self._max_offset = self._tau = self._phi = 0.026        self._min = self._max = float('nan')27        self._last = None28    def __eq__(self, that):29        return self.get_state() == that.get_state()30    def __ne__(self, that):31        return self.get_state() != that.get_state()32    def get_state(self):33        """Get internal state."""34        return (35            self._count,36            self._eta,37            self._rho,38            self._rho2,39            self._tau,40            self._phi,41            self._min,42            self._max,43            self._max_offset44        )45    def set_state(self, state):46        """Set internal state."""47        (48            self._count,49            self._eta,50            self._rho,51            self._rho2,52            self._tau,53            self._phi,54            self._min,55            self._max,56            self._max_offset57        ) = state58    @classmethod59    def fromstate(cls, state):60        """Return Statistics object from state."""61        stats = cls()62        stats.set_state(state)63        return stats64    def __reduce__(self):65        return make_statistics, (self.get_state(),)66    def copy(self, _=None):67        """Copy Statistics object."""68        return self.fromstate(self.get_state())69    __copy__ = copy70    __deepcopy__ = copy71    def __len__(self):72        """Number of values that have been pushed."""73        return int(self._count)74    def push(self, value, cur_max=None):75        """Add `value` to the Statistics summary."""76        value = float(value)77        if self._count == 0.0:78            self._min = value79            self._max = value80        else:81            self._min = min(self._min, value)82            self._max = max(self._max, value)83        delta = value - self._eta84        delta_n = delta / (self._count + 1)85        delta_n2 = delta_n * delta_n86        term = delta * delta_n * self._count87        self._count += 188        self._eta += delta_n89        self._phi += (90            term * delta_n2 * (self._count ** 2 - 3 * self._count + 3)91            + 6 * delta_n2 * self._rho92            - 4 * delta_n * self._tau93        )94        self._tau += (95            term * delta_n * (self._count - 2)96            - 3 * delta_n * self._rho97        )98        self._rho += term99        #additions100        if self._last is not None:101            self._rho2 += (value - self._last)**2102        self._last = value103        if cur_max is not None:104            self._max_offset += (value - cur_max)**2105    def minimum(self):106        """Minimum of values."""107        return self._min108    def maximum(self):109        """Maximum of values."""110        return self._max111    def mean(self):112        """Mean of values."""113        return self._eta114    def max_offset(self):115        """Mean of values."""116        return self._max_offset / self._count117    def local_variance(self, ddof=1.0):118        """Variance of values (with `ddof` degrees of freedom)."""119        return self._rho2 / (self._count - ddof)120    def variance(self, ddof=1.0):121        """Variance of values (with `ddof` degrees of freedom)."""122        return self._rho / (self._count - ddof)123    def stddev(self, ddof=1.0):124        """Standard deviation of values (with `ddof` degrees of freedom)."""125        return self.variance(ddof) ** 0.5126    def skewness(self):127        """Skewness of values."""128        return (self._count ** 0.5) * self._tau / pow(self._rho, 1.5)129    def kurtosis(self):130        """Kurtosis of values."""131        return self._count * self._phi / (self._rho * self._rho) - 3.0132    def __add__(self, that):133        """Add two Statistics objects together."""134        sigma = self.copy()135        sigma += that136        return sigma137    def __iadd__(self, that):138        """Add another Statistics object to this one."""139        sum_count = self._count + that._count140        if sum_count == 0:141            return self142        delta = that._eta - self._eta143        delta2 = delta ** 2144        delta3 = delta ** 3145        delta4 = delta ** 4146        sum_eta = (147            (self._count * self._eta + that._count * that._eta)148            / sum_count149        )150        sum_rho = (151            self._rho + that._rho152            + delta2 * self._count * that._count / sum_count153        )154        sum_rho2 = (155            self._rho2 + that._rho2156        )157        sum_tau = (158            self._tau + that._tau159            + delta3 * self._count * that._count160            * (self._count - that._count) / (sum_count ** 2)161            + 3.0 * delta162            * (self._count * that._rho - that._count * self._rho) / sum_count163        )164        sum_phi = (165            self._phi + that._phi166            + delta4 * self._count * that._count167            * (self._count ** 2 - self._count * that._count + that._count ** 2)168            / (sum_count ** 3)169            + 6.0 * delta2 * (170                self._count * self._count * that._rho171                + that._count * that._count * self._rho172            )173            / (sum_count ** 2)174            + 4.0 * delta175            * (self._count * that._tau - that._count * self._tau) / sum_count176        )177        if self._count == 0.0:178            self._min = that._min179            self._max = that._max180        elif that._count != 0.0:181            self._min = min(self._min, that._min)182            self._max = max(self._max, that._max)183        self._count = sum_count184        self._eta = sum_eta185        self._rho = sum_rho186        self._rho2 = sum_rho2187        self._tau = sum_tau188        self._phi = sum_phi189        return self190    def __mul__(self, that):191        """Multiply by a scalar to change Statistics weighting."""192        sigma = self.copy()193        sigma *= that194        return sigma195    __rmul__ = __mul__196    def __imul__(self, that):197        """Multiply by a scalar to change Statistics weighting in-place."""198        that = float(that)199        self._count *= that200        self._rho *= that201        self._rho2 *= that202        self._tau *= that203        self._phi *= that204        return self205def make_statistics(state):206    """Make Statistics object from state."""207    return Statistics.fromstate(state)208class Regression(object):209    """210    Compute simple linear regression in a single pass.211    Computes the slope, intercept, and correlation.212    Regression objects may also be added together and copied.213    Based entirely on the C++ code by John D Cook at214    http://www.johndcook.com/running_regression.html215    """216    def __init__(self, iterable=()):217        """Initialize Regression object.218        Iterates optional parameter `iterable` and pushes each pair into the219        regression summary.220        """221        self._xstats = Statistics()222        self._ystats = Statistics()223        self.clear()224        for xcoord, ycoord in iterable:225            self.push(xcoord, ycoord)226    def __eq__(self, that):227        return self.get_state() == that.get_state()228    def __ne__(self, that):229        return self.get_state() != that.get_state()230    def clear(self):231        """Clear Regression object."""232        self._xstats.clear()233        self._ystats.clear()234        self._count = self._sxy = 0.0235    def get_state(self):236        """Get internal state."""237        return (238            self._count, self._sxy, self._xstats.get_state(),239            self._ystats.get_state()240        )241    def set_state(self, state):242        """Set internal state."""243        count, sxy, xstats, ystats = state244        self._count = count245        self._sxy = sxy246        self._xstats.set_state(xstats)247        self._ystats.set_state(ystats)248    @classmethod249    def fromstate(cls, state):250        """Return Regression object from state."""251        regr = cls()252        regr.set_state(state)253        return regr254    def __reduce__(self):255        return make_regression, (self.get_state(),)256    def copy(self, _=None):257        """Copy Regression object."""258        return self.fromstate(self.get_state())259    __copy__ = copy260    __deepcopy__ = copy261    def __len__(self):262        """Number of values that have been pushed."""263        return int(self._count)264    def push(self, xcoord, ycoord):265        """Add a pair `(x, y)` to the Regression summary."""266        self._sxy += (267            (self._xstats.mean() - xcoord)268            * (self._ystats.mean() - ycoord)269            * self._count270            / (self._count + 1)271        )272        self._xstats.push(xcoord)273        self._ystats.push(ycoord)274        self._count += 1275    def slope(self, ddof=1.0):276        """Slope of values (with `ddof` degrees of freedom)."""277        sxx = self._xstats.variance(ddof) * (self._count - ddof)278        return self._sxy / sxx279    def intercept(self, ddof=1.0):280        """Intercept of values (with `ddof` degrees of freedom)."""281        return self._ystats.mean() - self.slope(ddof) * self._xstats.mean()282    def correlation(self, ddof=1.0):283        """Correlation of values (with `ddof` degrees of freedom)."""284        term = self._xstats.stddev(ddof) * self._ystats.stddev(ddof)285        return self._sxy / ((self._count - ddof) * term)286    def __add__(self, that):287        """Add two Regression objects together."""288        sigma = self.copy()289        sigma += that290        return sigma291    def __iadd__(self, that):292        """Add another Regression object to this one."""293        sum_count = self._count + that._count294        if sum_count == 0:295            return self296        sum_xstats = self._xstats + that._xstats297        sum_ystats = self._ystats + that._ystats298        deltax = that._xstats.mean() - self._xstats.mean()299        deltay = that._ystats.mean() - self._ystats.mean()300        sum_sxy = (301            self._sxy + that._sxy302            + self._count * that._count * deltax * deltay / sum_count303        )304        self._count = sum_count305        self._xstats = sum_xstats306        self._ystats = sum_ystats307        self._sxy = sum_sxy308        return self309def make_regression(state):310    """Make Regression object from state."""...arrayDynamic.py
Source:arrayDynamic.py  
1#!/usr/bin/python2import ctypes3class ArrayDynamic:4    def __init__(self, given_values=[]):5        if isinstance(given_values, list) and len(given_values) > 0:6            self._count = 07            self._capacity = len(given_values) * 28            self._low_level_array = self._new_low_level_array_c(self._capacity)9            self.extend(given_values)10        else:11            self._count = 012            self._capacity = 113            self._low_level_array = self._new_low_level_array_c(self._capacity)14    @property15    def count(self):16        return self._count17    @property18    def capacity(self):19        return self._capacity20    def __getitem__(self, index_value):21        if isinstance(index_value, slice):22            first = index_value.start23            end = index_value.stop24            step = index_value.step25        elif not (0 <= index_value < self._count):26            raise IndexError('Index value not valid!')27        else:28            return self._low_level_array[index_value]29        if index_value.step is None:30            step = 131        elif index_value.step < 0:32            step = index_value.step * -133        if first < 0 and end < 0:34            end = index_value.stop * -135            first = index_value.start * -136            new_arr = self._new_low_level_array_c(self._count)37            length_of = self._count - 138            for i in range(self._count - 1, -1, -1):39                new_arr[length_of - i] = self._low_level_array[i]40            if step == 1:41                return new_arr[(end - 1):(first - 1):step]42            else:43                return new_arr[(end - 1):first:step]44        elif not ((0 <= first < self._count - 1) and (0 < end <= self._count)):45            raise IndexError('Index value not valid!')46        elif step:47            return self._low_level_array[first:end:step]48        else:49            return self._low_level_array[first:end]50    def __setitem__(self, key, value):51        if not 0 <= key < self._count:52            raise IndexError('Index value not valid!')53        self._low_level_array[key] = value54    def append(self, value):55        if self.count == self.capacity:56            self._resize(2 * self.capacity)57        self._low_level_array[self.count] = value58        self._count += 159    def insert_at(self, index, item):60        if self._count == self._capacity:61            self._resize(2 * self._capacity)62        elif index >= self._count or index < 0:63            raise IndexError('Index out of range!')64        for i in range(self._count, index, -1):65            self._low_level_array[i] = self._low_level_array[i - 1]66        self._low_level_array[index] = item67        self._count += 168    def extend(self, iter_array):69        size_array = len(iter_array)70        if self.capacity == 1:71            self._resize(size_array * 3)72        elif (self.capacity - self.count) <= size_array:73            self._resize(2 * self._capacity + size_array)74        for i in range(size_array):75            self._low_level_array[self._count] = iter_array[i]76            self._count += 177    def like_pop(self, index=None):78        if (index == self._count - 1) or (index is None):79            for_return = self._low_level_array[self._count - 1]80            self._low_level_array[self._count - 1] = None81            self._count -= 182            if self._count == self._capacity // 4:83                self._resize(self._capacity // 2)84            return for_return85        elif index >= self._count or index < 0:86            raise IndexError('Out of range Index')87        value_to_remember = self._low_level_array[index]88        for i in range(index, self._count-1):89            self._low_level_array[i] = self._low_level_array[i+1]90        self._count -= 191        self._low_level_array[self._count] = None92        if self._count == self._capacity // 4:93            self._resize(self._capacity // 2)94        return value_to_remember95    def remove(self, value):96        if_find = 097        count = 098        for i in range(self._count):99            if self._low_level_array[i] == value:100                if_find = 1101                count += 1102                for j in range(i, self._count - 1):103                    self._low_level_array[j] = self._low_level_array[j+1]104                self._low_level_array[self._count - 1] = None105                self._count -= 1106            if count == 1:107                if self._count == self._capacity // 4:108                    self._resize(self._capacity // 2)109                return 1110        if if_find == 0:111            raise ValueError('Value not found!')112    def find_index(self, value):113        for i in range(self._count):114            if self._low_level_array[i] == value:115                return i116    def reverse_the_array(self):117        array_for_reverse = self._new_low_level_array_c(self._capacity)118        j = self._count - 1119        for i in range(self._count - 1, -1, -1):120            array_for_reverse[j - i] = self._low_level_array[i]121        self._low_level_array = array_for_reverse122    def _resize(self, given_capacity):123        new_array_for_swap = self._new_low_level_array_c(given_capacity)124        for i in range(self._count):125            new_array_for_swap[i] = self._low_level_array[i]126        self._low_level_array = new_array_for_swap127        self._capacity = given_capacity128    def _new_low_level_array_c(self, capacity_given):129        return (capacity_given * ctypes.py_object)()130    def __str__(self):131        string_to_return = '['132        for i in range(self._count):133            if 0 < i < self._count:134                string_to_return += ', ' + str(self._low_level_array[i])135            else:136                string_to_return += str(self._low_level_array[i])137        return string_to_return + ']'138def reversing(given_element):139    reversed_array = ArrayDynamic()140    for i in range(given_element.count - 1, -1, -1):141        reversed_array.append(given_element[i])...MinHeap.py
Source:MinHeap.py  
1class MinHeap(object):2    """3    Achieve a minimum heap by Array4    """56    def __init__(self, maxsize=None):7        self.maxsize = maxsize8        self._elements = [["id", 0] for i in range(self.maxsize)]9        self._count = 01011    def __len__(self):12        return self._count1314    def add(self, key, value):15        """16        Add an element to heap while keeping the attribute of heap unchanged.17        :param value: the value added to the heap18        :return: None19        """20        if self._count >= self.maxsize:21            raise Exception("The heap is full!")22        self._elements[self._count][0] = key23        self._elements[self._count][1] = value24        self._count += 125        self._siftup(self._count - 1)2627    def _siftup(self, index):28        """29        To keep the the attribute of heap unchanged while adding a new value.30        :param index: the index of value you want to swap31        :return: None32        """33        if index > 0:34            parent = int((index - 1) / 2)35            if self._elements[parent][1] > self._elements[index][1]:36                self._elements[parent], self._elements[index] = self._elements[index], self._elements[parent]37                self._siftup(parent)3839    def extract(self):40        """41        pop and return the value of root42        :return: the value of root43        """44        if self._count <= 0:45            raise Exception('The heap is empty!')4647        value = self._elements[0]48        self._count -= 149        self._elements[0] = self._elements[self._count]50        self._siftdown(0)51        return value5253    def _siftdown(self, index):54        """55        to keep the attribute of heap unchanged while pop out the root node.56        :param index: the index of value you want to swap57        :return: None58        """59        if index < self._count:60            left = 2 * index + 161            right = 2 * index + 262            if left < self._count and right < self._count \63                    and self._elements[left][1] <= self._elements[right][1] \64                    and self._elements[left][1] <= self._elements[index][1]:65                self._elements[left], self._elements[index] = self._elements[index], self._elements[left]66                self._siftdown(left)6768            elif left < self._count and right < self._count \69                    and self._elements[left][1] >= self._elements[right][1] \70                    and self._elements[right][1] <= self._elements[index][1]:71                self._elements[right], self._elements[index] = self._elements[index], self._elements[right]72                self._siftdown(left)7374            if left < self._count and right > self._count \75                    and self._elements[left][1] <= self._elements[index][1]:76                self._elements[left], self._elements[index] = self._elements[index], self._elements[left]77                self._siftdown(left)7879    def heavy_keep(self, key, value):80        """81        Add no more than maxsize elements to heap while keeping the attribute of heap unchanged.82        and keep the big elements83        :param value: the value added to the heap84        :return: None85        """86        if self._count < self.maxsize:87            self._elements[self._count][0] = key88            self._elements[self._count][1] = value89            self._count += 190            self._siftup(self._count - 1)91            return True9293        if self._count >= self.maxsize:94            if self._elements[0][1] < value:95                self._elements[0][0] = key96                self._elements[0][1] = value97                self._siftdown(0)
...task_10_3.py
Source:task_10_3.py  
1# 3. ÐÑÑÑеÑÑвиÑÑ Ð¿ÑогÑÐ°Ð¼Ð¼Ñ ÑабоÑÑ Ñ Ð¾ÑганиÑеÑкими клеÑками, ÑоÑÑоÑÑими из ÑÑеек. ÐеобÑ
одимо2# ÑоздаÑÑ ÐºÐ»Ð°ÑÑ Â«ÐлеÑка». Рего конÑÑÑÑкÑоÑе иниÑиализиÑоваÑÑ Ð¿Ð°ÑамеÑÑ, ÑооÑвеÑÑÑвÑÑÑий колиÑеÑÑвÑ3# ÑÑеек клеÑки (Ñелое ÑиÑло). РклаÑÑе Ð´Ð¾Ð»Ð¶Ð½Ñ Ð±ÑÑÑ ÑÐµÐ°Ð»Ð¸Ð·Ð¾Ð²Ð°Ð½Ñ Ð¼ÐµÑÐ¾Ð´Ñ Ð¿ÐµÑегÑÑзки аÑиÑмеÑиÑеÑкиÑ
 опеÑаÑоÑов:4# Ñложение (__add__()), вÑÑиÑание (__sub__()), Ñмножение (__mul__()), деление (__floordiv____truediv__()).5# ÐÑи меÑÐ¾Ð´Ñ Ð´Ð¾Ð»Ð¶Ð½Ñ Ð¿ÑименÑÑÑÑÑ ÑолÑко к клеÑкам и вÑполнÑÑÑ ÑвелиÑение, ÑменÑÑение, Ñмножение и окÑÑгление6# до Ñелого ÑиÑла Ð´ÐµÐ»ÐµÐ½Ð¸Ñ ÐºÐ»ÐµÑок ÑооÑвеÑÑÑвенно.7class Cell:8    def __init__(self, count: int):9        self._count = count10    def __add__(self, other: "Cell") -> "Cell":11        return Cell(self._count + other._count)12    def __sub__(self, other: "Cell") -> "Cell":13        if self._count > other._count:14            return Cell(self._count - other._count)15        # raise ValueError(f"{self._count} - {other._count}: impossible operation")16        print(f"{self._count} - {other._count}: impossible operation")17    def __mul__(self, other: "Cell") -> "Cell":18        return Cell(self._count * other._count)19    def __truediv__(self, other: "Cell") -> "Cell":20        return Cell(self._count // other._count)21    def make_order(self, per_row: int) -> str:22        rows, tail = self._count // per_row, self._count % per_row23        return '\n'.join(['*' * per_row] * rows + (['*' * tail] if tail else []))24    def __str__(self) -> str:25        return f"ÐлеÑка ÑоÑÑÐ¾Ð¸Ñ Ð¸Ð· {self._count} ÑÑеек"26if __name__ == '__main__':27    c1 = Cell(17)28    print(c1)29    c2 = Cell(13)30    print(c2)31    print(c1 + c2)32    print(c1 - c2)33    print(c2 - c1)34    print(c2 - c2)35    print(c1 * c2)36    print(c1 / c2)...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
