kandi background
Explore Kits

Python | All Algorithms implemented in Python | Learning library

 by   TheAlgorithms Python Version: Current License: MIT

 by   TheAlgorithms Python Version: Current License: MIT

Download this library from

kandi X-RAY | Python Summary

Python is a Python library typically used in Tutorial, Learning, Example Codes applications. Python has no bugs, it has build file available, it has a Permissive License and it has medium support. However Python has 1 vulnerabilities. You can download it from GitHub.
                   .
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • Python has a medium active ecosystem.
  • It has 117097 star(s) with 31466 fork(s). There are 5947 watchers for this library.
  • It had no major release in the last 12 months.
  • There are 10 open issues and 737 have been closed. On average issues are closed in 9 days. There are 34 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of Python is current.
Python Support
Best in #Learning
Average in #Learning
Python Support
Best in #Learning
Average in #Learning

quality kandi Quality

  • Python has 0 bugs and 0 code smells.
Python Quality
Best in #Learning
Average in #Learning
Python Quality
Best in #Learning
Average in #Learning

securitySecurity

  • Python has 1 vulnerability issues reported (0 critical, 0 high, 1 medium, 0 low).
  • Python code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
Python Security
Best in #Learning
Average in #Learning
Python Security
Best in #Learning
Average in #Learning

license License

  • Python is licensed under the MIT License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
Python License
Best in #Learning
Average in #Learning
Python License
Best in #Learning
Average in #Learning

buildReuse

  • Python releases are not available. You will need to build from source code and install.
  • Build file is available. You can build the component from source.
  • Python saves you 15079 person hours of effort in developing the same functionality from scratch.
  • It has 34533 lines of code, 2847 functions and 1003 files.
  • It has high code complexity. Code complexity directly impacts maintainability of the code.
Python Reuse
Best in #Learning
Average in #Learning
Python Reuse
Best in #Learning
Average in #Learning
Top functions reviewed by kandi - BETA

kandi has reviewed Python and discovered the below as its top functions. This is intended to give you an instant insight into Python implemented functionality, and help decide if they suit your requirements.

  • Decrypt a caesar ciphertext using the given ciphertext .
  • Converts from_type to to_type .
  • Checks if the given number is a prime number .
  • Merge a collection of items in a collection .
  • Gathers the angle between a set of points .
  • Generates a report for each cluster .
  • Generate a random population .
  • Convert date_input to zeller
  • Encrypts and returns the ciphertext .
  • r Pollard s Rho algorithm .

Python Key Features

All Algorithms implemented in Python

Python/Docker ImportError: cannot import name 'json' from itsdangerous

copy iconCopydownload iconDownload
pip install Flask=2.0.3
-----------------------
pip install Flask=2.0.1
pip install Flask=2.1.0
pip install Flask==1.1.4
pip install markupsafe==2.0.1
-----------------------
pip install Flask=2.0.1
pip install Flask=2.1.0
pip install Flask==1.1.4
pip install markupsafe==2.0.1
-----------------------
pip install Flask=2.0.1
pip install Flask=2.1.0
pip install Flask==1.1.4
pip install markupsafe==2.0.1

Why is it faster to compare strings that match than strings that do not?

copy iconCopydownload iconDownload
import dis

In [24]: dis.dis("'time'=='time'")
  1           0 LOAD_CONST               0 ('time')  # <-- same object (0)
              2 LOAD_CONST               0 ('time')  # <-- same object (0)
              4 COMPARE_OP               2 (==)
              6 RETURN_VALUE

In [25]: dis.dis("'time'=='1234'")
  1           0 LOAD_CONST               0 ('time')  # <-- different object (0)
              2 LOAD_CONST               1 ('1234')  # <-- different object (1)
              4 COMPARE_OP               2 (==)
              6 RETURN_VALUE
In [26]: timeit.timeit("x='time'; y='time'; x==y", number=1000000)
Out[26]: 0.0745926329982467

In [27]: timeit.timeit("x='time'; y='1234'; x==y", number=1000000)
Out[27]: 0.10328884399496019
int
_PyUnicode_Equal(PyObject *str1, PyObject *str2)
{
    assert(PyUnicode_CheckExact(str1));
    assert(PyUnicode_CheckExact(str2));
    if (str1 == str2) {                  // <-- Here
        return 1;
    }
    if (PyUnicode_READY(str1) || PyUnicode_READY(str2)) {
        return -1;
    }
    return unicode_compare_eq(str1, str2);
}
-----------------------
import dis

In [24]: dis.dis("'time'=='time'")
  1           0 LOAD_CONST               0 ('time')  # <-- same object (0)
              2 LOAD_CONST               0 ('time')  # <-- same object (0)
              4 COMPARE_OP               2 (==)
              6 RETURN_VALUE

In [25]: dis.dis("'time'=='1234'")
  1           0 LOAD_CONST               0 ('time')  # <-- different object (0)
              2 LOAD_CONST               1 ('1234')  # <-- different object (1)
              4 COMPARE_OP               2 (==)
              6 RETURN_VALUE
In [26]: timeit.timeit("x='time'; y='time'; x==y", number=1000000)
Out[26]: 0.0745926329982467

In [27]: timeit.timeit("x='time'; y='1234'; x==y", number=1000000)
Out[27]: 0.10328884399496019
int
_PyUnicode_Equal(PyObject *str1, PyObject *str2)
{
    assert(PyUnicode_CheckExact(str1));
    assert(PyUnicode_CheckExact(str2));
    if (str1 == str2) {                  // <-- Here
        return 1;
    }
    if (PyUnicode_READY(str1) || PyUnicode_READY(str2)) {
        return -1;
    }
    return unicode_compare_eq(str1, str2);
}
-----------------------
import dis

In [24]: dis.dis("'time'=='time'")
  1           0 LOAD_CONST               0 ('time')  # <-- same object (0)
              2 LOAD_CONST               0 ('time')  # <-- same object (0)
              4 COMPARE_OP               2 (==)
              6 RETURN_VALUE

In [25]: dis.dis("'time'=='1234'")
  1           0 LOAD_CONST               0 ('time')  # <-- different object (0)
              2 LOAD_CONST               1 ('1234')  # <-- different object (1)
              4 COMPARE_OP               2 (==)
              6 RETURN_VALUE
In [26]: timeit.timeit("x='time'; y='time'; x==y", number=1000000)
Out[26]: 0.0745926329982467

In [27]: timeit.timeit("x='time'; y='1234'; x==y", number=1000000)
Out[27]: 0.10328884399496019
int
_PyUnicode_Equal(PyObject *str1, PyObject *str2)
{
    assert(PyUnicode_CheckExact(str1));
    assert(PyUnicode_CheckExact(str2));
    if (str1 == str2) {                  // <-- Here
        return 1;
    }
    if (PyUnicode_READY(str1) || PyUnicode_READY(str2)) {
        return -1;
    }
    return unicode_compare_eq(str1, str2);
}
-----------------------
>>> x = 'toto'
>>> y = 'toto'
>>> z = 'totoo'[:-1]
>>> w = 'abcd'
>>> x == y
True
>>> x == z
True
>>> x == w
False
>>> id(x) == id(y)
True
>>> id(x) == id(z)
False
>>> id(x) == id(w)
False
>>> timeit.timeit('x==y', number=100000000, globals={'x': x, 'y': y})
3.893762200000083
>>> timeit.timeit('x==z', number=100000000, globals={'x': x, 'z': z})
4.205321462000029
>>> timeit.timeit('x==w', number=100000000, globals={'x': x, 'w': w})
4.15288594499998

Why is `np.sum(range(N))` very slow?

copy iconCopydownload iconDownload
/* Fast addition by keeping temporary sums in C instead of new Python objects.
   Assumes all inputs are the same type.  If the assumption fails, default
   to the more general routine.
*/
from functools import singledispatch

def sum_range(range_, /, start=0):
    """Overloaded `sum` for range, compute arithmetic sum"""
    n = len(range_)
    if not n:
        return start
    return int(start + (n * (range_[0] + range_[-1]) / 2))

sum = singledispatch(sum)
sum.register(range, sum_range)

def test():
    """
    >>> sum(range(0, 100))
    4950
    >>> sum(range(0, 10, 2))
    20
    >>> sum(range(0, 9, 2))
    20
    >>> sum(range(0, -10, -1))
    -45
    >>> sum(range(-10, 10))
    -10
    >>> sum(range(-1, -100, -2))
    -2500
    >>> sum(range(0, 10, 100))
    0
    >>> sum(range(0, 0))
    0
    >>> sum(range(0, 100), 50)
    5000
    >>> sum(range(0, 0), 10)
    10
    """

if __name__ == "__main__":
    import doctest
    doctest.testmod()
-----------------------
/* Fast addition by keeping temporary sums in C instead of new Python objects.
   Assumes all inputs are the same type.  If the assumption fails, default
   to the more general routine.
*/
from functools import singledispatch

def sum_range(range_, /, start=0):
    """Overloaded `sum` for range, compute arithmetic sum"""
    n = len(range_)
    if not n:
        return start
    return int(start + (n * (range_[0] + range_[-1]) / 2))

sum = singledispatch(sum)
sum.register(range, sum_range)

def test():
    """
    >>> sum(range(0, 100))
    4950
    >>> sum(range(0, 10, 2))
    20
    >>> sum(range(0, 9, 2))
    20
    >>> sum(range(0, -10, -1))
    -45
    >>> sum(range(-10, 10))
    -10
    >>> sum(range(-1, -100, -2))
    -2500
    >>> sum(range(0, 10, 100))
    0
    >>> sum(range(0, 0))
    0
    >>> sum(range(0, 100), 50)
    5000
    >>> sum(range(0, 0), 10)
    10
    """

if __name__ == "__main__":
    import doctest
    doctest.testmod()
-----------------------
# sum_range:          1.4830789409988938
# sum_rangelist:      3.6745876889999636
%%timeit x = list(range(N))
    ...: sum(x)
# npsum_range:        16.216972655000063
# npsum_fromiterrange:3.47655400199983
# sum_arange:         16.656015603000924
# sum_list_arange:    19.500842117000502
# sum_arange_tolist:  4.004777374000696
# npsum_arange:       0.2332638230000157
# array_basic:        16.1631146109994
# array_dtype:        16.550737804000164
# array_iter:         3.9803170430004684
-----------------------
# sum_range:          1.4830789409988938
# sum_rangelist:      3.6745876889999636
%%timeit x = list(range(N))
    ...: sum(x)
# npsum_range:        16.216972655000063
# npsum_fromiterrange:3.47655400199983
# sum_arange:         16.656015603000924
# sum_list_arange:    19.500842117000502
# sum_arange_tolist:  4.004777374000696
# npsum_arange:       0.2332638230000157
# array_basic:        16.1631146109994
# array_dtype:        16.550737804000164
# array_iter:         3.9803170430004684
-----------------------
# sum_range:          1.4830789409988938
# sum_rangelist:      3.6745876889999636
%%timeit x = list(range(N))
    ...: sum(x)
# npsum_range:        16.216972655000063
# npsum_fromiterrange:3.47655400199983
# sum_arange:         16.656015603000924
# sum_list_arange:    19.500842117000502
# sum_arange_tolist:  4.004777374000696
# npsum_arange:       0.2332638230000157
# array_basic:        16.1631146109994
# array_dtype:        16.550737804000164
# array_iter:         3.9803170430004684
-----------------------
# sum_range:          1.4830789409988938
# sum_rangelist:      3.6745876889999636
%%timeit x = list(range(N))
    ...: sum(x)
# npsum_range:        16.216972655000063
# npsum_fromiterrange:3.47655400199983
# sum_arange:         16.656015603000924
# sum_list_arange:    19.500842117000502
# sum_arange_tolist:  4.004777374000696
# npsum_arange:       0.2332638230000157
# array_basic:        16.1631146109994
# array_dtype:        16.550737804000164
# array_iter:         3.9803170430004684
-----------------------
# sum_range:          1.4830789409988938
# sum_rangelist:      3.6745876889999636
%%timeit x = list(range(N))
    ...: sum(x)
# npsum_range:        16.216972655000063
# npsum_fromiterrange:3.47655400199983
# sum_arange:         16.656015603000924
# sum_list_arange:    19.500842117000502
# sum_arange_tolist:  4.004777374000696
# npsum_arange:       0.2332638230000157
# array_basic:        16.1631146109994
# array_dtype:        16.550737804000164
# array_iter:         3.9803170430004684
-----------------------
# sum_range:          1.4830789409988938
# sum_rangelist:      3.6745876889999636
%%timeit x = list(range(N))
    ...: sum(x)
# npsum_range:        16.216972655000063
# npsum_fromiterrange:3.47655400199983
# sum_arange:         16.656015603000924
# sum_list_arange:    19.500842117000502
# sum_arange_tolist:  4.004777374000696
# npsum_arange:       0.2332638230000157
# array_basic:        16.1631146109994
# array_dtype:        16.550737804000164
# array_iter:         3.9803170430004684
-----------------------
# sum_range:          1.4830789409988938
# sum_rangelist:      3.6745876889999636
%%timeit x = list(range(N))
    ...: sum(x)
# npsum_range:        16.216972655000063
# npsum_fromiterrange:3.47655400199983
# sum_arange:         16.656015603000924
# sum_list_arange:    19.500842117000502
# sum_arange_tolist:  4.004777374000696
# npsum_arange:       0.2332638230000157
# array_basic:        16.1631146109994
# array_dtype:        16.550737804000164
# array_iter:         3.9803170430004684
-----------------------
# sum_range:          1.4830789409988938
# sum_rangelist:      3.6745876889999636
%%timeit x = list(range(N))
    ...: sum(x)
# npsum_range:        16.216972655000063
# npsum_fromiterrange:3.47655400199983
# sum_arange:         16.656015603000924
# sum_list_arange:    19.500842117000502
# sum_arange_tolist:  4.004777374000696
# npsum_arange:       0.2332638230000157
# array_basic:        16.1631146109994
# array_dtype:        16.550737804000164
# array_iter:         3.9803170430004684
-----------------------
# sum_range:          1.4830789409988938
# sum_rangelist:      3.6745876889999636
%%timeit x = list(range(N))
    ...: sum(x)
# npsum_range:        16.216972655000063
# npsum_fromiterrange:3.47655400199983
# sum_arange:         16.656015603000924
# sum_list_arange:    19.500842117000502
# sum_arange_tolist:  4.004777374000696
# npsum_arange:       0.2332638230000157
# array_basic:        16.1631146109994
# array_dtype:        16.550737804000164
# array_iter:         3.9803170430004684
-----------------------
# sum_range:          1.4830789409988938
# sum_rangelist:      3.6745876889999636
%%timeit x = list(range(N))
    ...: sum(x)
# npsum_range:        16.216972655000063
# npsum_fromiterrange:3.47655400199983
# sum_arange:         16.656015603000924
# sum_list_arange:    19.500842117000502
# sum_arange_tolist:  4.004777374000696
# npsum_arange:       0.2332638230000157
# array_basic:        16.1631146109994
# array_dtype:        16.550737804000164
# array_iter:         3.9803170430004684
-----------------------
tmp = list(range(10_000_000))

# Numpy implicitly convert the list in a Numpy array but 
# still automatically detect the input type to use
np.sum(tmp)
tmp = list(range(10_000_000))

# The array is explicitly converted using a well-defined type and 
# thus there is no need to perform an automatic detection 
# (note that the result is still wrong since it does not fit in a np.int32)
tmp2 = np.array(tmp, dtype=np.int32)
result = np.sum(tmp2)
-----------------------
tmp = list(range(10_000_000))

# Numpy implicitly convert the list in a Numpy array but 
# still automatically detect the input type to use
np.sum(tmp)
tmp = list(range(10_000_000))

# The array is explicitly converted using a well-defined type and 
# thus there is no need to perform an automatic detection 
# (note that the result is still wrong since it does not fit in a np.int32)
tmp2 = np.array(tmp, dtype=np.int32)
result = np.sum(tmp2)

Repeatedly removing the maximum average subarray

copy iconCopydownload iconDownload
# Lengths of the segments in the upper convex hull
# of the cumulative sum graph
def upperSumHullLengths(arr):
    if len(arr) < 2:
        if len(arr) < 1:
            return []
        else:
            return [1]
    
    hull = [(0, 0),(1, arr[0])]
    for x in range(2, len(arr)+1):
        # this has x coordinate x-1
        prevPoint = hull[len(hull) - 1]
        # next point in cumulative sum
        point = (x, prevPoint[1] + arr[x-1])
        # remove points not on the convex hull
        while len(hull) >= 2:
            p0 = hull[len(hull)-2]
            dx0 = prevPoint[0] - p0[0]
            dy0 = prevPoint[1] - p0[1]
            dx1 = x - prevPoint[0]
            dy1 = point[1] - prevPoint[1]
            if dy1*dx0 < dy0*dx1:
                break
            hull.pop()
            prevPoint = p0
        hull.append(point)
    
    return [hull[i+1][0] - hull[i][0] for i in range(0, len(hull)-1)]


print(upperSumHullLengths([  1,   7,   8,   4,   2,   1,   4]))
[3, 1, 3]
-----------------------
# Lengths of the segments in the upper convex hull
# of the cumulative sum graph
def upperSumHullLengths(arr):
    if len(arr) < 2:
        if len(arr) < 1:
            return []
        else:
            return [1]
    
    hull = [(0, 0),(1, arr[0])]
    for x in range(2, len(arr)+1):
        # this has x coordinate x-1
        prevPoint = hull[len(hull) - 1]
        # next point in cumulative sum
        point = (x, prevPoint[1] + arr[x-1])
        # remove points not on the convex hull
        while len(hull) >= 2:
            p0 = hull[len(hull)-2]
            dx0 = prevPoint[0] - p0[0]
            dy0 = prevPoint[1] - p0[1]
            dx1 = x - prevPoint[0]
            dy1 = point[1] - prevPoint[1]
            if dy1*dx0 < dy0*dx1:
                break
            hull.pop()
            prevPoint = p0
        hull.append(point)
    
    return [hull[i+1][0] - hull[i][0] for i in range(0, len(hull)-1)]


print(upperSumHullLengths([  1,   7,   8,   4,   2,   1,   4]))
[3, 1, 3]
-----------------------
from itertools import accumulate, pairwise

def Matt_Pychoed(arr):
    hull = [(0, 0)]
    for x, y in enumerate(accumulate(arr), 1):
        while len(hull) >= 2:
            (x0, y0), (x1, y1) = hull[-2:]
            dx0 = x1 - x0
            dy0 = y1 - y0
            dx1 = x - x1
            dy1 = y - y1
            if dy1*dx0 < dy0*dx1:
                break
            hull.pop()
        hull.append((x, y))
    return [q[0] - p[0] for p, q in pairwise(hull)]
from itertools import accumulate, count
from operator import truediv

def kc_Pychoed_2(nums):
    removals = []
    while nums:
        averages = map(truediv, accumulate(nums), count(1))
        remove = max(zip(averages, count(1)))[1]
        removals.append(remove)
        nums = nums[remove:]
    return removals
  min   median   mean     max  
 65 ms  164 ms  159 ms  249 ms  kc
 38 ms   98 ms   92 ms  146 ms  kc_Pychoed_1
 58 ms  127 ms  120 ms  189 ms  kc_Pychoed_2
134 ms  137 ms  138 ms  157 ms  Matt
101 ms  102 ms  103 ms  111 ms  Matt_Pychoed
  min   median   mean     max  
102 ms  106 ms  107 ms  116 ms  kc
 60 ms   61 ms   61 ms   62 ms  kc_Pychoed_1
 76 ms   77 ms   77 ms   86 ms  kc_Pychoed_2
  0 ms    1 ms    1 ms    1 ms  Matt
  0 ms    0 ms    0 ms    0 ms  Matt_Pychoed
from timeit import default_timer as timer
from statistics import mean, median
import random
from typing import List, Tuple
import math
from itertools import accumulate, count
from operator import truediv

def kc(nums: List[int]) -> List[int]:
    """Return list of lengths of max average prefix reductions."""

    def max_prefix_avg(arr: List[int]) -> Tuple[float, int]:
        """Return value and length of max average prefix in arr"""
        if len(arr) == 0:
            return (-math.inf, 0)
        
        best_length = 1
        best_average = -math.inf
        running_sum = 0.0

        for i, x in enumerate(arr, 1):
            running_sum += x
            new_average = running_sum / i
            
            if (new_average >= best_average
                or math.isclose(new_average, best_average)):
                
                best_average = new_average
                best_length = i

        return (best_average, best_length)

    removed_lengths = []
    total_removed = 0

    while total_removed < len(nums):
        _, new_removal = max_prefix_avg(nums[total_removed:])
        removed_lengths.append(new_removal)
        total_removed += new_removal

    return removed_lengths

def kc_Pychoed_1(nums: List[int]) -> List[int]:
    """Return list of lengths of max average prefix reductions."""

    def max_prefix_avg(arr: List[int]) -> Tuple[float, int]:
        """Return value and length of max average prefix in arr"""
        if len(arr) == 0:
            return (-math.inf, 0)
        
        best_length = 1
        best_average = -math.inf
        running_sum = 0

        for i, x in enumerate(arr, 1):
            running_sum += x
            new_average = running_sum / i
            
            if new_average >= best_average:
                
                best_average = new_average
                best_length = i

        return (best_average, best_length)

    removed_lengths = []
    total_removed = 0

    while total_removed < len(nums):
        _, new_removal = max_prefix_avg(nums[total_removed:])
        removed_lengths.append(new_removal)
        total_removed += new_removal

    return removed_lengths

def kc_Pychoed_2(nums):
    removals = []
    while nums:
        averages = map(truediv, accumulate(nums), count(1))
        remove = max(zip(averages, count(1)))[1]
        removals.append(remove)
        nums = nums[remove:]
    return removals

# Lengths of the segments in the upper convex hull
# of the cumulative sum graph
def Matt(arr):
    if len(arr) < 2:
        if len(arr) < 1:
            return []
        else:
            return [1]
    
    hull = [(0, 0),(1, arr[0])]
    for x in range(2, len(arr)+1):
        # this has x coordinate x-1
        prevPoint = hull[len(hull) - 1]
        # next point in cumulative sum
        point = (x, prevPoint[1] + arr[x-1])
        # remove points not on the convex hull
        while len(hull) >= 2:
            p0 = hull[len(hull)-2]
            dx0 = prevPoint[0] - p0[0]
            dy0 = prevPoint[1] - p0[1]
            dx1 = x - prevPoint[0]
            dy1 = point[1] - prevPoint[1]
            if dy1*dx0 < dy0*dx1:
                break
            hull.pop()
            prevPoint = p0
        hull.append(point)
    
    return [hull[i+1][0] - hull[i][0] for i in range(0, len(hull)-1)]

def pairwise(lst):
    return zip(lst, lst[1:])

def Matt_Pychoed(arr):
    hull = [(0, 0)]
    for x, y in enumerate(accumulate(arr), 1):
        while len(hull) >= 2:
            (x0, y0), (x1, y1) = hull[-2:]
            dx0 = x1 - x0
            dy0 = y1 - y0
            dx1 = x - x1
            dy1 = y - y1
            if dy1*dx0 < dy0*dx1:
                break
            hull.pop()
        hull.append((x, y))
    return [q[0] - p[0] for p, q in pairwise(hull)]

funcs = kc, kc_Pychoed_1, kc_Pychoed_2, Matt, Matt_Pychoed
stats = min, median, mean, max
tss = [[] for _ in funcs]
for r in range(1, 21):
    print(f'After round {r}:')
    arr = random.choices(range(1, 1001), k=100_000)
    # arr = list(range(1000, 1, -1))
    expect = None
    print(*(f'{stat.__name__:^7}' for stat in stats))
    for func, ts in zip(funcs, tss):
        t0 = timer()
        result = func(arr)
        t1 = timer()
        ts.append(t1 - t0)
        if expect is None:
            expect = result
        assert result == expect
        print(*('%3d ms ' % (stat(ts) * 1e3) for stat in stats), func.__name__)
    print()
-----------------------
from itertools import accumulate, pairwise

def Matt_Pychoed(arr):
    hull = [(0, 0)]
    for x, y in enumerate(accumulate(arr), 1):
        while len(hull) >= 2:
            (x0, y0), (x1, y1) = hull[-2:]
            dx0 = x1 - x0
            dy0 = y1 - y0
            dx1 = x - x1
            dy1 = y - y1
            if dy1*dx0 < dy0*dx1:
                break
            hull.pop()
        hull.append((x, y))
    return [q[0] - p[0] for p, q in pairwise(hull)]
from itertools import accumulate, count
from operator import truediv

def kc_Pychoed_2(nums):
    removals = []
    while nums:
        averages = map(truediv, accumulate(nums), count(1))
        remove = max(zip(averages, count(1)))[1]
        removals.append(remove)
        nums = nums[remove:]
    return removals
  min   median   mean     max  
 65 ms  164 ms  159 ms  249 ms  kc
 38 ms   98 ms   92 ms  146 ms  kc_Pychoed_1
 58 ms  127 ms  120 ms  189 ms  kc_Pychoed_2
134 ms  137 ms  138 ms  157 ms  Matt
101 ms  102 ms  103 ms  111 ms  Matt_Pychoed
  min   median   mean     max  
102 ms  106 ms  107 ms  116 ms  kc
 60 ms   61 ms   61 ms   62 ms  kc_Pychoed_1
 76 ms   77 ms   77 ms   86 ms  kc_Pychoed_2
  0 ms    1 ms    1 ms    1 ms  Matt
  0 ms    0 ms    0 ms    0 ms  Matt_Pychoed
from timeit import default_timer as timer
from statistics import mean, median
import random
from typing import List, Tuple
import math
from itertools import accumulate, count
from operator import truediv

def kc(nums: List[int]) -> List[int]:
    """Return list of lengths of max average prefix reductions."""

    def max_prefix_avg(arr: List[int]) -> Tuple[float, int]:
        """Return value and length of max average prefix in arr"""
        if len(arr) == 0:
            return (-math.inf, 0)
        
        best_length = 1
        best_average = -math.inf
        running_sum = 0.0

        for i, x in enumerate(arr, 1):
            running_sum += x
            new_average = running_sum / i
            
            if (new_average >= best_average
                or math.isclose(new_average, best_average)):
                
                best_average = new_average
                best_length = i

        return (best_average, best_length)

    removed_lengths = []
    total_removed = 0

    while total_removed < len(nums):
        _, new_removal = max_prefix_avg(nums[total_removed:])
        removed_lengths.append(new_removal)
        total_removed += new_removal

    return removed_lengths

def kc_Pychoed_1(nums: List[int]) -> List[int]:
    """Return list of lengths of max average prefix reductions."""

    def max_prefix_avg(arr: List[int]) -> Tuple[float, int]:
        """Return value and length of max average prefix in arr"""
        if len(arr) == 0:
            return (-math.inf, 0)
        
        best_length = 1
        best_average = -math.inf
        running_sum = 0

        for i, x in enumerate(arr, 1):
            running_sum += x
            new_average = running_sum / i
            
            if new_average >= best_average:
                
                best_average = new_average
                best_length = i

        return (best_average, best_length)

    removed_lengths = []
    total_removed = 0

    while total_removed < len(nums):
        _, new_removal = max_prefix_avg(nums[total_removed:])
        removed_lengths.append(new_removal)
        total_removed += new_removal

    return removed_lengths

def kc_Pychoed_2(nums):
    removals = []
    while nums:
        averages = map(truediv, accumulate(nums), count(1))
        remove = max(zip(averages, count(1)))[1]
        removals.append(remove)
        nums = nums[remove:]
    return removals

# Lengths of the segments in the upper convex hull
# of the cumulative sum graph
def Matt(arr):
    if len(arr) < 2:
        if len(arr) < 1:
            return []
        else:
            return [1]
    
    hull = [(0, 0),(1, arr[0])]
    for x in range(2, len(arr)+1):
        # this has x coordinate x-1
        prevPoint = hull[len(hull) - 1]
        # next point in cumulative sum
        point = (x, prevPoint[1] + arr[x-1])
        # remove points not on the convex hull
        while len(hull) >= 2:
            p0 = hull[len(hull)-2]
            dx0 = prevPoint[0] - p0[0]
            dy0 = prevPoint[1] - p0[1]
            dx1 = x - prevPoint[0]
            dy1 = point[1] - prevPoint[1]
            if dy1*dx0 < dy0*dx1:
                break
            hull.pop()
            prevPoint = p0
        hull.append(point)
    
    return [hull[i+1][0] - hull[i][0] for i in range(0, len(hull)-1)]

def pairwise(lst):
    return zip(lst, lst[1:])

def Matt_Pychoed(arr):
    hull = [(0, 0)]
    for x, y in enumerate(accumulate(arr), 1):
        while len(hull) >= 2:
            (x0, y0), (x1, y1) = hull[-2:]
            dx0 = x1 - x0
            dy0 = y1 - y0
            dx1 = x - x1
            dy1 = y - y1
            if dy1*dx0 < dy0*dx1:
                break
            hull.pop()
        hull.append((x, y))
    return [q[0] - p[0] for p, q in pairwise(hull)]

funcs = kc, kc_Pychoed_1, kc_Pychoed_2, Matt, Matt_Pychoed
stats = min, median, mean, max
tss = [[] for _ in funcs]
for r in range(1, 21):
    print(f'After round {r}:')
    arr = random.choices(range(1, 1001), k=100_000)
    # arr = list(range(1000, 1, -1))
    expect = None
    print(*(f'{stat.__name__:^7}' for stat in stats))
    for func, ts in zip(funcs, tss):
        t0 = timer()
        result = func(arr)
        t1 = timer()
        ts.append(t1 - t0)
        if expect is None:
            expect = result
        assert result == expect
        print(*('%3d ms ' % (stat(ts) * 1e3) for stat in stats), func.__name__)
    print()
-----------------------
from itertools import accumulate, pairwise

def Matt_Pychoed(arr):
    hull = [(0, 0)]
    for x, y in enumerate(accumulate(arr), 1):
        while len(hull) >= 2:
            (x0, y0), (x1, y1) = hull[-2:]
            dx0 = x1 - x0
            dy0 = y1 - y0
            dx1 = x - x1
            dy1 = y - y1
            if dy1*dx0 < dy0*dx1:
                break
            hull.pop()
        hull.append((x, y))
    return [q[0] - p[0] for p, q in pairwise(hull)]
from itertools import accumulate, count
from operator import truediv

def kc_Pychoed_2(nums):
    removals = []
    while nums:
        averages = map(truediv, accumulate(nums), count(1))
        remove = max(zip(averages, count(1)))[1]
        removals.append(remove)
        nums = nums[remove:]
    return removals
  min   median   mean     max  
 65 ms  164 ms  159 ms  249 ms  kc
 38 ms   98 ms   92 ms  146 ms  kc_Pychoed_1
 58 ms  127 ms  120 ms  189 ms  kc_Pychoed_2
134 ms  137 ms  138 ms  157 ms  Matt
101 ms  102 ms  103 ms  111 ms  Matt_Pychoed
  min   median   mean     max  
102 ms  106 ms  107 ms  116 ms  kc
 60 ms   61 ms   61 ms   62 ms  kc_Pychoed_1
 76 ms   77 ms   77 ms   86 ms  kc_Pychoed_2
  0 ms    1 ms    1 ms    1 ms  Matt
  0 ms    0 ms    0 ms    0 ms  Matt_Pychoed
from timeit import default_timer as timer
from statistics import mean, median
import random
from typing import List, Tuple
import math
from itertools import accumulate, count
from operator import truediv

def kc(nums: List[int]) -> List[int]:
    """Return list of lengths of max average prefix reductions."""

    def max_prefix_avg(arr: List[int]) -> Tuple[float, int]:
        """Return value and length of max average prefix in arr"""
        if len(arr) == 0:
            return (-math.inf, 0)
        
        best_length = 1
        best_average = -math.inf
        running_sum = 0.0

        for i, x in enumerate(arr, 1):
            running_sum += x
            new_average = running_sum / i
            
            if (new_average >= best_average
                or math.isclose(new_average, best_average)):
                
                best_average = new_average
                best_length = i

        return (best_average, best_length)

    removed_lengths = []
    total_removed = 0

    while total_removed < len(nums):
        _, new_removal = max_prefix_avg(nums[total_removed:])
        removed_lengths.append(new_removal)
        total_removed += new_removal

    return removed_lengths

def kc_Pychoed_1(nums: List[int]) -> List[int]:
    """Return list of lengths of max average prefix reductions."""

    def max_prefix_avg(arr: List[int]) -> Tuple[float, int]:
        """Return value and length of max average prefix in arr"""
        if len(arr) == 0:
            return (-math.inf, 0)
        
        best_length = 1
        best_average = -math.inf
        running_sum = 0

        for i, x in enumerate(arr, 1):
            running_sum += x
            new_average = running_sum / i
            
            if new_average >= best_average:
                
                best_average = new_average
                best_length = i

        return (best_average, best_length)

    removed_lengths = []
    total_removed = 0

    while total_removed < len(nums):
        _, new_removal = max_prefix_avg(nums[total_removed:])
        removed_lengths.append(new_removal)
        total_removed += new_removal

    return removed_lengths

def kc_Pychoed_2(nums):
    removals = []
    while nums:
        averages = map(truediv, accumulate(nums), count(1))
        remove = max(zip(averages, count(1)))[1]
        removals.append(remove)
        nums = nums[remove:]
    return removals

# Lengths of the segments in the upper convex hull
# of the cumulative sum graph
def Matt(arr):
    if len(arr) < 2:
        if len(arr) < 1:
            return []
        else:
            return [1]
    
    hull = [(0, 0),(1, arr[0])]
    for x in range(2, len(arr)+1):
        # this has x coordinate x-1
        prevPoint = hull[len(hull) - 1]
        # next point in cumulative sum
        point = (x, prevPoint[1] + arr[x-1])
        # remove points not on the convex hull
        while len(hull) >= 2:
            p0 = hull[len(hull)-2]
            dx0 = prevPoint[0] - p0[0]
            dy0 = prevPoint[1] - p0[1]
            dx1 = x - prevPoint[0]
            dy1 = point[1] - prevPoint[1]
            if dy1*dx0 < dy0*dx1:
                break
            hull.pop()
            prevPoint = p0
        hull.append(point)
    
    return [hull[i+1][0] - hull[i][0] for i in range(0, len(hull)-1)]

def pairwise(lst):
    return zip(lst, lst[1:])

def Matt_Pychoed(arr):
    hull = [(0, 0)]
    for x, y in enumerate(accumulate(arr), 1):
        while len(hull) >= 2:
            (x0, y0), (x1, y1) = hull[-2:]
            dx0 = x1 - x0
            dy0 = y1 - y0
            dx1 = x - x1
            dy1 = y - y1
            if dy1*dx0 < dy0*dx1:
                break
            hull.pop()
        hull.append((x, y))
    return [q[0] - p[0] for p, q in pairwise(hull)]

funcs = kc, kc_Pychoed_1, kc_Pychoed_2, Matt, Matt_Pychoed
stats = min, median, mean, max
tss = [[] for _ in funcs]
for r in range(1, 21):
    print(f'After round {r}:')
    arr = random.choices(range(1, 1001), k=100_000)
    # arr = list(range(1000, 1, -1))
    expect = None
    print(*(f'{stat.__name__:^7}' for stat in stats))
    for func, ts in zip(funcs, tss):
        t0 = timer()
        result = func(arr)
        t1 = timer()
        ts.append(t1 - t0)
        if expect is None:
            expect = result
        assert result == expect
        print(*('%3d ms ' % (stat(ts) * 1e3) for stat in stats), func.__name__)
    print()
-----------------------
from itertools import accumulate, pairwise

def Matt_Pychoed(arr):
    hull = [(0, 0)]
    for x, y in enumerate(accumulate(arr), 1):
        while len(hull) >= 2:
            (x0, y0), (x1, y1) = hull[-2:]
            dx0 = x1 - x0
            dy0 = y1 - y0
            dx1 = x - x1
            dy1 = y - y1
            if dy1*dx0 < dy0*dx1:
                break
            hull.pop()
        hull.append((x, y))
    return [q[0] - p[0] for p, q in pairwise(hull)]
from itertools import accumulate, count
from operator import truediv

def kc_Pychoed_2(nums):
    removals = []
    while nums:
        averages = map(truediv, accumulate(nums), count(1))
        remove = max(zip(averages, count(1)))[1]
        removals.append(remove)
        nums = nums[remove:]
    return removals
  min   median   mean     max  
 65 ms  164 ms  159 ms  249 ms  kc
 38 ms   98 ms   92 ms  146 ms  kc_Pychoed_1
 58 ms  127 ms  120 ms  189 ms  kc_Pychoed_2
134 ms  137 ms  138 ms  157 ms  Matt
101 ms  102 ms  103 ms  111 ms  Matt_Pychoed
  min   median   mean     max  
102 ms  106 ms  107 ms  116 ms  kc
 60 ms   61 ms   61 ms   62 ms  kc_Pychoed_1
 76 ms   77 ms   77 ms   86 ms  kc_Pychoed_2
  0 ms    1 ms    1 ms    1 ms  Matt
  0 ms    0 ms    0 ms    0 ms  Matt_Pychoed
from timeit import default_timer as timer
from statistics import mean, median
import random
from typing import List, Tuple
import math
from itertools import accumulate, count
from operator import truediv

def kc(nums: List[int]) -> List[int]:
    """Return list of lengths of max average prefix reductions."""

    def max_prefix_avg(arr: List[int]) -> Tuple[float, int]:
        """Return value and length of max average prefix in arr"""
        if len(arr) == 0:
            return (-math.inf, 0)
        
        best_length = 1
        best_average = -math.inf
        running_sum = 0.0

        for i, x in enumerate(arr, 1):
            running_sum += x
            new_average = running_sum / i
            
            if (new_average >= best_average
                or math.isclose(new_average, best_average)):
                
                best_average = new_average
                best_length = i

        return (best_average, best_length)

    removed_lengths = []
    total_removed = 0

    while total_removed < len(nums):
        _, new_removal = max_prefix_avg(nums[total_removed:])
        removed_lengths.append(new_removal)
        total_removed += new_removal

    return removed_lengths

def kc_Pychoed_1(nums: List[int]) -> List[int]:
    """Return list of lengths of max average prefix reductions."""

    def max_prefix_avg(arr: List[int]) -> Tuple[float, int]:
        """Return value and length of max average prefix in arr"""
        if len(arr) == 0:
            return (-math.inf, 0)
        
        best_length = 1
        best_average = -math.inf
        running_sum = 0

        for i, x in enumerate(arr, 1):
            running_sum += x
            new_average = running_sum / i
            
            if new_average >= best_average:
                
                best_average = new_average
                best_length = i

        return (best_average, best_length)

    removed_lengths = []
    total_removed = 0

    while total_removed < len(nums):
        _, new_removal = max_prefix_avg(nums[total_removed:])
        removed_lengths.append(new_removal)
        total_removed += new_removal

    return removed_lengths

def kc_Pychoed_2(nums):
    removals = []
    while nums:
        averages = map(truediv, accumulate(nums), count(1))
        remove = max(zip(averages, count(1)))[1]
        removals.append(remove)
        nums = nums[remove:]
    return removals

# Lengths of the segments in the upper convex hull
# of the cumulative sum graph
def Matt(arr):
    if len(arr) < 2:
        if len(arr) < 1:
            return []
        else:
            return [1]
    
    hull = [(0, 0),(1, arr[0])]
    for x in range(2, len(arr)+1):
        # this has x coordinate x-1
        prevPoint = hull[len(hull) - 1]
        # next point in cumulative sum
        point = (x, prevPoint[1] + arr[x-1])
        # remove points not on the convex hull
        while len(hull) >= 2:
            p0 = hull[len(hull)-2]
            dx0 = prevPoint[0] - p0[0]
            dy0 = prevPoint[1] - p0[1]
            dx1 = x - prevPoint[0]
            dy1 = point[1] - prevPoint[1]
            if dy1*dx0 < dy0*dx1:
                break
            hull.pop()
            prevPoint = p0
        hull.append(point)
    
    return [hull[i+1][0] - hull[i][0] for i in range(0, len(hull)-1)]

def pairwise(lst):
    return zip(lst, lst[1:])

def Matt_Pychoed(arr):
    hull = [(0, 0)]
    for x, y in enumerate(accumulate(arr), 1):
        while len(hull) >= 2:
            (x0, y0), (x1, y1) = hull[-2:]
            dx0 = x1 - x0
            dy0 = y1 - y0
            dx1 = x - x1
            dy1 = y - y1
            if dy1*dx0 < dy0*dx1:
                break
            hull.pop()
        hull.append((x, y))
    return [q[0] - p[0] for p, q in pairwise(hull)]

funcs = kc, kc_Pychoed_1, kc_Pychoed_2, Matt, Matt_Pychoed
stats = min, median, mean, max
tss = [[] for _ in funcs]
for r in range(1, 21):
    print(f'After round {r}:')
    arr = random.choices(range(1, 1001), k=100_000)
    # arr = list(range(1000, 1, -1))
    expect = None
    print(*(f'{stat.__name__:^7}' for stat in stats))
    for func, ts in zip(funcs, tss):
        t0 = timer()
        result = func(arr)
        t1 = timer()
        ts.append(t1 - t0)
        if expect is None:
            expect = result
        assert result == expect
        print(*('%3d ms ' % (stat(ts) * 1e3) for stat in stats), func.__name__)
    print()
-----------------------
from itertools import accumulate, pairwise

def Matt_Pychoed(arr):
    hull = [(0, 0)]
    for x, y in enumerate(accumulate(arr), 1):
        while len(hull) >= 2:
            (x0, y0), (x1, y1) = hull[-2:]
            dx0 = x1 - x0
            dy0 = y1 - y0
            dx1 = x - x1
            dy1 = y - y1
            if dy1*dx0 < dy0*dx1:
                break
            hull.pop()
        hull.append((x, y))
    return [q[0] - p[0] for p, q in pairwise(hull)]
from itertools import accumulate, count
from operator import truediv

def kc_Pychoed_2(nums):
    removals = []
    while nums:
        averages = map(truediv, accumulate(nums), count(1))
        remove = max(zip(averages, count(1)))[1]
        removals.append(remove)
        nums = nums[remove:]
    return removals
  min   median   mean     max  
 65 ms  164 ms  159 ms  249 ms  kc
 38 ms   98 ms   92 ms  146 ms  kc_Pychoed_1
 58 ms  127 ms  120 ms  189 ms  kc_Pychoed_2
134 ms  137 ms  138 ms  157 ms  Matt
101 ms  102 ms  103 ms  111 ms  Matt_Pychoed
  min   median   mean     max  
102 ms  106 ms  107 ms  116 ms  kc
 60 ms   61 ms   61 ms   62 ms  kc_Pychoed_1
 76 ms   77 ms   77 ms   86 ms  kc_Pychoed_2
  0 ms    1 ms    1 ms    1 ms  Matt
  0 ms    0 ms    0 ms    0 ms  Matt_Pychoed
from timeit import default_timer as timer
from statistics import mean, median
import random
from typing import List, Tuple
import math
from itertools import accumulate, count
from operator import truediv

def kc(nums: List[int]) -> List[int]:
    """Return list of lengths of max average prefix reductions."""

    def max_prefix_avg(arr: List[int]) -> Tuple[float, int]:
        """Return value and length of max average prefix in arr"""
        if len(arr) == 0:
            return (-math.inf, 0)
        
        best_length = 1
        best_average = -math.inf
        running_sum = 0.0

        for i, x in enumerate(arr, 1):
            running_sum += x
            new_average = running_sum / i
            
            if (new_average >= best_average
                or math.isclose(new_average, best_average)):
                
                best_average = new_average
                best_length = i

        return (best_average, best_length)

    removed_lengths = []
    total_removed = 0

    while total_removed < len(nums):
        _, new_removal = max_prefix_avg(nums[total_removed:])
        removed_lengths.append(new_removal)
        total_removed += new_removal

    return removed_lengths

def kc_Pychoed_1(nums: List[int]) -> List[int]:
    """Return list of lengths of max average prefix reductions."""

    def max_prefix_avg(arr: List[int]) -> Tuple[float, int]:
        """Return value and length of max average prefix in arr"""
        if len(arr) == 0:
            return (-math.inf, 0)
        
        best_length = 1
        best_average = -math.inf
        running_sum = 0

        for i, x in enumerate(arr, 1):
            running_sum += x
            new_average = running_sum / i
            
            if new_average >= best_average:
                
                best_average = new_average
                best_length = i

        return (best_average, best_length)

    removed_lengths = []
    total_removed = 0

    while total_removed < len(nums):
        _, new_removal = max_prefix_avg(nums[total_removed:])
        removed_lengths.append(new_removal)
        total_removed += new_removal

    return removed_lengths

def kc_Pychoed_2(nums):
    removals = []
    while nums:
        averages = map(truediv, accumulate(nums), count(1))
        remove = max(zip(averages, count(1)))[1]
        removals.append(remove)
        nums = nums[remove:]
    return removals

# Lengths of the segments in the upper convex hull
# of the cumulative sum graph
def Matt(arr):
    if len(arr) < 2:
        if len(arr) < 1:
            return []
        else:
            return [1]
    
    hull = [(0, 0),(1, arr[0])]
    for x in range(2, len(arr)+1):
        # this has x coordinate x-1
        prevPoint = hull[len(hull) - 1]
        # next point in cumulative sum
        point = (x, prevPoint[1] + arr[x-1])
        # remove points not on the convex hull
        while len(hull) >= 2:
            p0 = hull[len(hull)-2]
            dx0 = prevPoint[0] - p0[0]
            dy0 = prevPoint[1] - p0[1]
            dx1 = x - prevPoint[0]
            dy1 = point[1] - prevPoint[1]
            if dy1*dx0 < dy0*dx1:
                break
            hull.pop()
            prevPoint = p0
        hull.append(point)
    
    return [hull[i+1][0] - hull[i][0] for i in range(0, len(hull)-1)]

def pairwise(lst):
    return zip(lst, lst[1:])

def Matt_Pychoed(arr):
    hull = [(0, 0)]
    for x, y in enumerate(accumulate(arr), 1):
        while len(hull) >= 2:
            (x0, y0), (x1, y1) = hull[-2:]
            dx0 = x1 - x0
            dy0 = y1 - y0
            dx1 = x - x1
            dy1 = y - y1
            if dy1*dx0 < dy0*dx1:
                break
            hull.pop()
        hull.append((x, y))
    return [q[0] - p[0] for p, q in pairwise(hull)]

funcs = kc, kc_Pychoed_1, kc_Pychoed_2, Matt, Matt_Pychoed
stats = min, median, mean, max
tss = [[] for _ in funcs]
for r in range(1, 21):
    print(f'After round {r}:')
    arr = random.choices(range(1, 1001), k=100_000)
    # arr = list(range(1000, 1, -1))
    expect = None
    print(*(f'{stat.__name__:^7}' for stat in stats))
    for func, ts in zip(funcs, tss):
        t0 = timer()
        result = func(arr)
        t1 = timer()
        ts.append(t1 - t0)
        if expect is None:
            expect = result
        assert result == expect
        print(*('%3d ms ' % (stat(ts) * 1e3) for stat in stats), func.__name__)
    print()

WARNING: Running pip as the 'root' user

copy iconCopydownload iconDownload
FROM python:3.8.3-alpine

RUN pip install --upgrade pip

RUN adduser -D myuser
USER myuser
WORKDIR /home/myuser

COPY --chown=myuser:myuser requirements.txt requirements.txt
RUN pip install --user -r requirements.txt

ENV PATH="/home/myuser/.local/bin:${PATH}"

COPY --chown=myuser:myuser . .

CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]
-----------------------
# temp stage
FROM python:3.9-slim as builder

WORKDIR /app

ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

RUN apt-get update && \
    apt-get install -y --no-install-recommends gcc

RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"

COPY requirements.txt .
RUN pip install -r requirements.txt


# final stage
FROM python:3.9-slim

COPY --from=builder /opt/venv /opt/venv

WORKDIR /app

ENV PATH="/opt/venv/bin:$PATH"
ARG DEBIAN_FRONTEND=noninteractive
ARG DEBCONF_NOWARNINGS="yes"

RUN python -m pip install --upgrade pip && \
    ...
-----------------------
# temp stage
FROM python:3.9-slim as builder

WORKDIR /app

ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

RUN apt-get update && \
    apt-get install -y --no-install-recommends gcc

RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"

COPY requirements.txt .
RUN pip install -r requirements.txt


# final stage
FROM python:3.9-slim

COPY --from=builder /opt/venv /opt/venv

WORKDIR /app

ENV PATH="/opt/venv/bin:$PATH"
ARG DEBIAN_FRONTEND=noninteractive
ARG DEBCONF_NOWARNINGS="yes"

RUN python -m pip install --upgrade pip && \
    ...

How do I calculate square root in Python?

copy iconCopydownload iconDownload
>>> import math
>>> math.sqrt(9)
3.0
>>> 9 ** (1/2)
3.0
>>> 9 ** .5  # Same thing
3.0
>>> 2 ** .5
1.4142135623730951
>>> 8 ** (1/3)
2.0
>>> 125 ** (1/3)
4.999999999999999
>>> (-25) ** .5  # Should be 5j
(3.061616997868383e-16+5j)
>>> 8j ** .5  # Should be 2+2j
(2.0000000000000004+2j)
>>> import cmath
>>> cmath.sqrt(-25)
5j
>>> cmath.sqrt(8j)
(2+2j)
>>> n = 10**30
>>> square = n**2
>>> x = square**.5
>>> x == n
False
>>> x - n  # how far off are they?
0.0
>>> int(x) - n  # how far off is the float from the int?
19884624838656
>>> decimal.Decimal('9') ** .5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for ** or pow(): 'decimal.Decimal' and 'float'
>>> decimal.Decimal('9') ** decimal.Decimal('.5')
Decimal('3.000000000000000000000000000')
-----------------------
>>> import math
>>> math.sqrt(9)
3.0
>>> 9 ** (1/2)
3.0
>>> 9 ** .5  # Same thing
3.0
>>> 2 ** .5
1.4142135623730951
>>> 8 ** (1/3)
2.0
>>> 125 ** (1/3)
4.999999999999999
>>> (-25) ** .5  # Should be 5j
(3.061616997868383e-16+5j)
>>> 8j ** .5  # Should be 2+2j
(2.0000000000000004+2j)
>>> import cmath
>>> cmath.sqrt(-25)
5j
>>> cmath.sqrt(8j)
(2+2j)
>>> n = 10**30
>>> square = n**2
>>> x = square**.5
>>> x == n
False
>>> x - n  # how far off are they?
0.0
>>> int(x) - n  # how far off is the float from the int?
19884624838656
>>> decimal.Decimal('9') ** .5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for ** or pow(): 'decimal.Decimal' and 'float'
>>> decimal.Decimal('9') ** decimal.Decimal('.5')
Decimal('3.000000000000000000000000000')
-----------------------
>>> import math
>>> math.sqrt(9)
3.0
>>> 9 ** (1/2)
3.0
>>> 9 ** .5  # Same thing
3.0
>>> 2 ** .5
1.4142135623730951
>>> 8 ** (1/3)
2.0
>>> 125 ** (1/3)
4.999999999999999
>>> (-25) ** .5  # Should be 5j
(3.061616997868383e-16+5j)
>>> 8j ** .5  # Should be 2+2j
(2.0000000000000004+2j)
>>> import cmath
>>> cmath.sqrt(-25)
5j
>>> cmath.sqrt(8j)
(2+2j)
>>> n = 10**30
>>> square = n**2
>>> x = square**.5
>>> x == n
False
>>> x - n  # how far off are they?
0.0
>>> int(x) - n  # how far off is the float from the int?
19884624838656
>>> decimal.Decimal('9') ** .5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for ** or pow(): 'decimal.Decimal' and 'float'
>>> decimal.Decimal('9') ** decimal.Decimal('.5')
Decimal('3.000000000000000000000000000')
-----------------------
>>> import math
>>> math.sqrt(9)
3.0
>>> 9 ** (1/2)
3.0
>>> 9 ** .5  # Same thing
3.0
>>> 2 ** .5
1.4142135623730951
>>> 8 ** (1/3)
2.0
>>> 125 ** (1/3)
4.999999999999999
>>> (-25) ** .5  # Should be 5j
(3.061616997868383e-16+5j)
>>> 8j ** .5  # Should be 2+2j
(2.0000000000000004+2j)
>>> import cmath
>>> cmath.sqrt(-25)
5j
>>> cmath.sqrt(8j)
(2+2j)
>>> n = 10**30
>>> square = n**2
>>> x = square**.5
>>> x == n
False
>>> x - n  # how far off are they?
0.0
>>> int(x) - n  # how far off is the float from the int?
19884624838656
>>> decimal.Decimal('9') ** .5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for ** or pow(): 'decimal.Decimal' and 'float'
>>> decimal.Decimal('9') ** decimal.Decimal('.5')
Decimal('3.000000000000000000000000000')
-----------------------
>>> import math
>>> math.sqrt(9)
3.0
>>> 9 ** (1/2)
3.0
>>> 9 ** .5  # Same thing
3.0
>>> 2 ** .5
1.4142135623730951
>>> 8 ** (1/3)
2.0
>>> 125 ** (1/3)
4.999999999999999
>>> (-25) ** .5  # Should be 5j
(3.061616997868383e-16+5j)
>>> 8j ** .5  # Should be 2+2j
(2.0000000000000004+2j)
>>> import cmath
>>> cmath.sqrt(-25)
5j
>>> cmath.sqrt(8j)
(2+2j)
>>> n = 10**30
>>> square = n**2
>>> x = square**.5
>>> x == n
False
>>> x - n  # how far off are they?
0.0
>>> int(x) - n  # how far off is the float from the int?
19884624838656
>>> decimal.Decimal('9') ** .5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for ** or pow(): 'decimal.Decimal' and 'float'
>>> decimal.Decimal('9') ** decimal.Decimal('.5')
Decimal('3.000000000000000000000000000')
-----------------------
>>> import math
>>> math.sqrt(9)
3.0
>>> 9 ** (1/2)
3.0
>>> 9 ** .5  # Same thing
3.0
>>> 2 ** .5
1.4142135623730951
>>> 8 ** (1/3)
2.0
>>> 125 ** (1/3)
4.999999999999999
>>> (-25) ** .5  # Should be 5j
(3.061616997868383e-16+5j)
>>> 8j ** .5  # Should be 2+2j
(2.0000000000000004+2j)
>>> import cmath
>>> cmath.sqrt(-25)
5j
>>> cmath.sqrt(8j)
(2+2j)
>>> n = 10**30
>>> square = n**2
>>> x = square**.5
>>> x == n
False
>>> x - n  # how far off are they?
0.0
>>> int(x) - n  # how far off is the float from the int?
19884624838656
>>> decimal.Decimal('9') ** .5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for ** or pow(): 'decimal.Decimal' and 'float'
>>> decimal.Decimal('9') ** decimal.Decimal('.5')
Decimal('3.000000000000000000000000000')
-----------------------
>>> import math
>>> math.sqrt(9)
3.0
>>> 9 ** (1/2)
3.0
>>> 9 ** .5  # Same thing
3.0
>>> 2 ** .5
1.4142135623730951
>>> 8 ** (1/3)
2.0
>>> 125 ** (1/3)
4.999999999999999
>>> (-25) ** .5  # Should be 5j
(3.061616997868383e-16+5j)
>>> 8j ** .5  # Should be 2+2j
(2.0000000000000004+2j)
>>> import cmath
>>> cmath.sqrt(-25)
5j
>>> cmath.sqrt(8j)
(2+2j)
>>> n = 10**30
>>> square = n**2
>>> x = square**.5
>>> x == n
False
>>> x - n  # how far off are they?
0.0
>>> int(x) - n  # how far off is the float from the int?
19884624838656
>>> decimal.Decimal('9') ** .5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for ** or pow(): 'decimal.Decimal' and 'float'
>>> decimal.Decimal('9') ** decimal.Decimal('.5')
Decimal('3.000000000000000000000000000')
-----------------------
>>> import numpy as np
>>> np.sqrt(25)
5.0
>>> np.sqrt([2, 3, 4])
array([1.41421356, 1.73205081, 2.        ])
>>> a = np.array([4, -1, np.inf])
>>> np.sqrt(a)
<stdin>:1: RuntimeWarning: invalid value encountered in sqrt
array([ 2., nan, inf])
>>> np.lib.scimath.sqrt(a)
array([ 2.+0.j,  0.+1.j, inf+0.j])
>>> a = a.astype(complex)
>>> np.sqrt(a)
array([ 2.+0.j,  0.+1.j, inf+0.j])
-----------------------
>>> import numpy as np
>>> np.sqrt(25)
5.0
>>> np.sqrt([2, 3, 4])
array([1.41421356, 1.73205081, 2.        ])
>>> a = np.array([4, -1, np.inf])
>>> np.sqrt(a)
<stdin>:1: RuntimeWarning: invalid value encountered in sqrt
array([ 2., nan, inf])
>>> np.lib.scimath.sqrt(a)
array([ 2.+0.j,  0.+1.j, inf+0.j])
>>> a = a.astype(complex)
>>> np.sqrt(a)
array([ 2.+0.j,  0.+1.j, inf+0.j])
-----------------------
>>> import numpy as np
>>> np.sqrt(25)
5.0
>>> np.sqrt([2, 3, 4])
array([1.41421356, 1.73205081, 2.        ])
>>> a = np.array([4, -1, np.inf])
>>> np.sqrt(a)
<stdin>:1: RuntimeWarning: invalid value encountered in sqrt
array([ 2., nan, inf])
>>> np.lib.scimath.sqrt(a)
array([ 2.+0.j,  0.+1.j, inf+0.j])
>>> a = a.astype(complex)
>>> np.sqrt(a)
array([ 2.+0.j,  0.+1.j, inf+0.j])
-----------------------
import sympy
sympy.sqrt(2)
# => sqrt(2)
sympy.sqrt(8) / sympy.sqrt(27)
# => 2*sqrt(6)/9
s = sympy.sqrt(2)
s**2
# => 2
type(s**2)
#=> <class 'sympy.core.numbers.Integer'>
(2**0.5)**2
# => 2.0000000000000004

from decimal import Decimal
(Decimal('2')**Decimal('0.5'))**Decimal('2')
# => Decimal('1.999999999999999999999999999')
from sympy import Symbol, integrate, pi, sqrt, exp, oo
x = Symbol('x')
integrate(exp(-x**2), (x, -oo, oo))
# => sqrt(pi)
integrate(exp(-x**2), (x, -oo, oo)) == sqrt(pi)
# => True
sympy.N(sympy.sqrt(2), 1_000_000)
# => 1.4142135623730950488016...........2044193016904841204
-----------------------
import sympy
sympy.sqrt(2)
# => sqrt(2)
sympy.sqrt(8) / sympy.sqrt(27)
# => 2*sqrt(6)/9
s = sympy.sqrt(2)
s**2
# => 2
type(s**2)
#=> <class 'sympy.core.numbers.Integer'>
(2**0.5)**2
# => 2.0000000000000004

from decimal import Decimal
(Decimal('2')**Decimal('0.5'))**Decimal('2')
# => Decimal('1.999999999999999999999999999')
from sympy import Symbol, integrate, pi, sqrt, exp, oo
x = Symbol('x')
integrate(exp(-x**2), (x, -oo, oo))
# => sqrt(pi)
integrate(exp(-x**2), (x, -oo, oo)) == sqrt(pi)
# => True
sympy.N(sympy.sqrt(2), 1_000_000)
# => 1.4142135623730950488016...........2044193016904841204
-----------------------
import sympy
sympy.sqrt(2)
# => sqrt(2)
sympy.sqrt(8) / sympy.sqrt(27)
# => 2*sqrt(6)/9
s = sympy.sqrt(2)
s**2
# => 2
type(s**2)
#=> <class 'sympy.core.numbers.Integer'>
(2**0.5)**2
# => 2.0000000000000004

from decimal import Decimal
(Decimal('2')**Decimal('0.5'))**Decimal('2')
# => Decimal('1.999999999999999999999999999')
from sympy import Symbol, integrate, pi, sqrt, exp, oo
x = Symbol('x')
integrate(exp(-x**2), (x, -oo, oo))
# => sqrt(pi)
integrate(exp(-x**2), (x, -oo, oo)) == sqrt(pi)
# => True
sympy.N(sympy.sqrt(2), 1_000_000)
# => 1.4142135623730950488016...........2044193016904841204
-----------------------
import sympy
sympy.sqrt(2)
# => sqrt(2)
sympy.sqrt(8) / sympy.sqrt(27)
# => 2*sqrt(6)/9
s = sympy.sqrt(2)
s**2
# => 2
type(s**2)
#=> <class 'sympy.core.numbers.Integer'>
(2**0.5)**2
# => 2.0000000000000004

from decimal import Decimal
(Decimal('2')**Decimal('0.5'))**Decimal('2')
# => Decimal('1.999999999999999999999999999')
from sympy import Symbol, integrate, pi, sqrt, exp, oo
x = Symbol('x')
integrate(exp(-x**2), (x, -oo, oo))
# => sqrt(pi)
integrate(exp(-x**2), (x, -oo, oo)) == sqrt(pi)
# => True
sympy.N(sympy.sqrt(2), 1_000_000)
# => 1.4142135623730950488016...........2044193016904841204
-----------------------
import sympy
sympy.sqrt(2)
# => sqrt(2)
sympy.sqrt(8) / sympy.sqrt(27)
# => 2*sqrt(6)/9
s = sympy.sqrt(2)
s**2
# => 2
type(s**2)
#=> <class 'sympy.core.numbers.Integer'>
(2**0.5)**2
# => 2.0000000000000004

from decimal import Decimal
(Decimal('2')**Decimal('0.5'))**Decimal('2')
# => Decimal('1.999999999999999999999999999')
from sympy import Symbol, integrate, pi, sqrt, exp, oo
x = Symbol('x')
integrate(exp(-x**2), (x, -oo, oo))
# => sqrt(pi)
integrate(exp(-x**2), (x, -oo, oo)) == sqrt(pi)
# => True
sympy.N(sympy.sqrt(2), 1_000_000)
# => 1.4142135623730950488016...........2044193016904841204
-----------------------
import sympy
sympy.sqrt(2)
# => sqrt(2)
sympy.sqrt(8) / sympy.sqrt(27)
# => 2*sqrt(6)/9
s = sympy.sqrt(2)
s**2
# => 2
type(s**2)
#=> <class 'sympy.core.numbers.Integer'>
(2**0.5)**2
# => 2.0000000000000004

from decimal import Decimal
(Decimal('2')**Decimal('0.5'))**Decimal('2')
# => Decimal('1.999999999999999999999999999')
from sympy import Symbol, integrate, pi, sqrt, exp, oo
x = Symbol('x')
integrate(exp(-x**2), (x, -oo, oo))
# => sqrt(pi)
integrate(exp(-x**2), (x, -oo, oo)) == sqrt(pi)
# => True
sympy.N(sympy.sqrt(2), 1_000_000)
# => 1.4142135623730950488016...........2044193016904841204
-----------------------
def int_squareroot(d: int) -> tuple[int, bool]:
    """Try calculating integer squareroot and return if it's exact"""
    left, right = 1, (d+1)//2
    while left<right-1:
        x = (left+right)//2
        if x**2 > d:
            left, right = left, x
        else:
            left, right = x, right
    return left, left**2==d
-----------------------
from fractions import Fraction

def sqrt(x, n):
    x = x if isinstance(x, Fraction) else Fraction(x)
    upper = x + 1
    for i in range(0, n):
        upper = (upper + x/upper) / 2
    lower = x / upper
    if lower > upper:
        raise ValueError("Sanity check failed")
    return (lower, upper)
-----------------------
new_estimate = (estimate + num/estimate) / 2
def newtons_method(num, estimate):
    # Computing a new_estimate
    new_estimate = (estimate + num/estimate) / 2
    print(new_estimate)
    # Base Case: Comparing our estimate with built-in functions value
    if new_estimate == math.sqrt(num):
        return True
    else:
        return newtons_method(num, new_estimate)
newtons_method(30,5)
5.5
5.477272727272727
5.4772255752546215
5.477225575051661
-----------------------
new_estimate = (estimate + num/estimate) / 2
def newtons_method(num, estimate):
    # Computing a new_estimate
    new_estimate = (estimate + num/estimate) / 2
    print(new_estimate)
    # Base Case: Comparing our estimate with built-in functions value
    if new_estimate == math.sqrt(num):
        return True
    else:
        return newtons_method(num, new_estimate)
newtons_method(30,5)
5.5
5.477272727272727
5.4772255752546215
5.477225575051661
-----------------------
new_estimate = (estimate + num/estimate) / 2
def newtons_method(num, estimate):
    # Computing a new_estimate
    new_estimate = (estimate + num/estimate) / 2
    print(new_estimate)
    # Base Case: Comparing our estimate with built-in functions value
    if new_estimate == math.sqrt(num):
        return True
    else:
        return newtons_method(num, new_estimate)
newtons_method(30,5)
5.5
5.477272727272727
5.4772255752546215
5.477225575051661
-----------------------
new_estimate = (estimate + num/estimate) / 2
def newtons_method(num, estimate):
    # Computing a new_estimate
    new_estimate = (estimate + num/estimate) / 2
    print(new_estimate)
    # Base Case: Comparing our estimate with built-in functions value
    if new_estimate == math.sqrt(num):
        return True
    else:
        return newtons_method(num, new_estimate)
newtons_method(30,5)
5.5
5.477272727272727
5.4772255752546215
5.477225575051661
-----------------------
from math import isqrt

def str_sqrt(num, digits):
    """ Arbitrary precision square root

        num arg must be a string
        Return a string with `digits` after
        the decimal point

        Written by PM 2Ring 2022.01.26
    """

    int_part , _, frac_part = num.partition('.')
    num = int_part + frac_part

    # Determine the required precision
    width = 2 * digits - len(frac_part)

    # Truncate or pad with zeroes
    num = num[:width] if width < 0 else num + '0' * width
    s = str(isqrt(int(num)))

    if digits:
        # Pad, if necessary
        s = '0' * (1 + digits - len(s)) + s
        s = f"{s[:-digits]}.{s[-digits:]}"
    return s
print(str_sqrt("2.0", 30))
1.414213562373095048801688724209
-----------------------
from math import isqrt

def str_sqrt(num, digits):
    """ Arbitrary precision square root

        num arg must be a string
        Return a string with `digits` after
        the decimal point

        Written by PM 2Ring 2022.01.26
    """

    int_part , _, frac_part = num.partition('.')
    num = int_part + frac_part

    # Determine the required precision
    width = 2 * digits - len(frac_part)

    # Truncate or pad with zeroes
    num = num[:width] if width < 0 else num + '0' * width
    s = str(isqrt(int(num)))

    if digits:
        # Pad, if necessary
        s = '0' * (1 + digits - len(s)) + s
        s = f"{s[:-digits]}.{s[-digits:]}"
    return s
print(str_sqrt("2.0", 30))
1.414213562373095048801688724209
-----------------------
from math import isqrt

def str_sqrt(num, digits):
    """ Arbitrary precision square root

        num arg must be a string
        Return a string with `digits` after
        the decimal point

        Written by PM 2Ring 2022.01.26
    """

    int_part , _, frac_part = num.partition('.')
    num = int_part + frac_part

    # Determine the required precision
    width = 2 * digits - len(frac_part)

    # Truncate or pad with zeroes
    num = num[:width] if width < 0 else num + '0' * width
    s = str(isqrt(int(num)))

    if digits:
        # Pad, if necessary
        s = '0' * (1 + digits - len(s)) + s
        s = f"{s[:-digits]}.{s[-digits:]}"
    return s
print(str_sqrt("2.0", 30))
1.414213562373095048801688724209

pip-compile raising AssertionError on its logging handler

copy iconCopydownload iconDownload
pip install --upgrade pip-tools
-----------------------
pip install --upgrade pip-tools

ImportError: cannot import name 'url' from 'django.conf.urls' after upgrading to Django 4.0

copy iconCopydownload iconDownload
from django.urls import include, re_path

from myapp.views import home

urlpatterns = [
    re_path(r'^$', home, name='home'),
    re_path(r'^myapp/', include('myapp.urls'),
]
from django.urls import include, path

from myapp.views import home

urlpatterns = [
    path('', home, name='home'),
    path('myapp/', include('myapp.urls'),
]
-----------------------
from django.urls import include, re_path

from myapp.views import home

urlpatterns = [
    re_path(r'^$', home, name='home'),
    re_path(r'^myapp/', include('myapp.urls'),
]
from django.urls import include, path

from myapp.views import home

urlpatterns = [
    path('', home, name='home'),
    path('myapp/', include('myapp.urls'),
]
-----------------------
from django.conf.urls import url
from django.urls import re_path as url
-----------------------
from django.conf.urls import url
from django.urls import re_path as url

How did print(*a, a.pop(0)) change?

copy iconCopydownload iconDownload
  1           0 LOAD_NAME                0 (f)
              2 LOAD_NAME                1 (a)
              4 LOAD_NAME                1 (a)
              6 LOAD_METHOD              2 (pop)
              8 CALL_METHOD              0
             10 BUILD_TUPLE              1
             12 BUILD_TUPLE_UNPACK_WITH_CALL     2
             14 CALL_FUNCTION_EX         0
             16 RETURN_VALUE
  1           0 LOAD_NAME                0 (f)
              2 BUILD_LIST               0
              4 LOAD_NAME                1 (a)
              6 LIST_EXTEND              1
              8 LOAD_NAME                1 (a)
             10 LOAD_METHOD              2 (pop)
             12 CALL_METHOD              0
             14 LIST_APPEND              1
             16 LIST_TO_TUPLE
             18 CALL_FUNCTION_EX         0
             20 RETURN_VALUE
-----------------------
  1           0 LOAD_NAME                0 (f)
              2 LOAD_NAME                1 (a)
              4 LOAD_NAME                1 (a)
              6 LOAD_METHOD              2 (pop)
              8 CALL_METHOD              0
             10 BUILD_TUPLE              1
             12 BUILD_TUPLE_UNPACK_WITH_CALL     2
             14 CALL_FUNCTION_EX         0
             16 RETURN_VALUE
  1           0 LOAD_NAME                0 (f)
              2 BUILD_LIST               0
              4 LOAD_NAME                1 (a)
              6 LIST_EXTEND              1
              8 LOAD_NAME                1 (a)
             10 LOAD_METHOD              2 (pop)
             12 CALL_METHOD              0
             14 LIST_APPEND              1
             16 LIST_TO_TUPLE
             18 CALL_FUNCTION_EX         0
             20 RETURN_VALUE

What's the mathematical reason behind Python choosing to round integer division toward negative infinity?

copy iconCopydownload iconDownload
#include <iostream>

int main()
{
    int dividend, divisor, quotient, remainder, check;
    std::cout << "Enter Dividend: ";                        // -27
    std::cin >> dividend;
    std::cout << "Enter Divisor: ";                         // 4
    std::cin >> divisor;

    quotient = dividend / divisor;
    std::cout << "Quotient = " << quotient << std::endl;    // -6
    remainder = dividend % divisor;
    std::cout << "Remainder = " << remainder << std::endl;  // -3

    check = quotient * divisor + remainder;
    std::cout << "Check = " << check << std::endl;          // -27
    return 0;
}
print("Enter Dividend: ")             # -27
dividend = int(input())
print("Enter Divisor: ")              # 4
divisor = int(input())
quotient = dividend // divisor;
print("Quotient = " + str(quotient))  # -7
modulus = dividend % divisor;
print("Modulus = " + str(modulus))    # 1
check = quotient * divisor + modulus; # -27
print("Check = " + str(check))
-----------------------
#include <iostream>

int main()
{
    int dividend, divisor, quotient, remainder, check;
    std::cout << "Enter Dividend: ";                        // -27
    std::cin >> dividend;
    std::cout << "Enter Divisor: ";                         // 4
    std::cin >> divisor;

    quotient = dividend / divisor;
    std::cout << "Quotient = " << quotient << std::endl;    // -6
    remainder = dividend % divisor;
    std::cout << "Remainder = " << remainder << std::endl;  // -3

    check = quotient * divisor + remainder;
    std::cout << "Check = " << check << std::endl;          // -27
    return 0;
}
print("Enter Dividend: ")             # -27
dividend = int(input())
print("Enter Divisor: ")              # 4
divisor = int(input())
quotient = dividend // divisor;
print("Quotient = " + str(quotient))  # -7
modulus = dividend % divisor;
print("Modulus = " + str(modulus))    # 1
check = quotient * divisor + modulus; # -27
print("Check = " + str(check))
-----------------------
heading = (heading + angle) % 360
heading = (heading + angle) % 360;
if (heading < 0) heading += 360;
heading = ((heading + angle) % 360) + 360) % 360;
-----------------------
heading = (heading + angle) % 360
heading = (heading + angle) % 360;
if (heading < 0) heading += 360;
heading = ((heading + angle) % 360) + 360) % 360;
-----------------------
heading = (heading + angle) % 360
heading = (heading + angle) % 360;
if (heading < 0) heading += 360;
heading = ((heading + angle) % 360) + 360) % 360;
-----------------------
(n+d)/d = (n/d)+1
(-n)/d = -(n/d)
-----------------------
>>> -35 // 16 # If we move 35 pixels left of the origin...
-3
>>> -35 % 16 # then we are 13 pixels from the left edge of a tile in row -3.
13
-----------------------
a == (a div b)*b + (a mod b)
   ^ y = x mod 5
 4 |   *    *    *    *    *
   |  *    *    *    *    *
   | *    *    *    *    *    *
   |*    *    *    *    *    *
 0 +----*----*----*----*----*->
       -5    0    5   10   15 x
   ^ y = x mod 5
 4 |             *    *    *
   |            *    *    *
   |           *    *    *    *
   |          *    *    *    *
 0 |    *    *    *    *    *
   |   *    *
   |  *    *
   | *    *
-4 |*    *
   +----+----+----+----+----+->
       -5    0    5   10   15 x
-----------------------
a == (a div b)*b + (a mod b)
   ^ y = x mod 5
 4 |   *    *    *    *    *
   |  *    *    *    *    *
   | *    *    *    *    *    *
   |*    *    *    *    *    *
 0 +----*----*----*----*----*->
       -5    0    5   10   15 x
   ^ y = x mod 5
 4 |             *    *    *
   |            *    *    *
   |           *    *    *    *
   |          *    *    *    *
 0 |    *    *    *    *    *
   |   *    *
   |  *    *
   | *    *
-4 |*    *
   +----+----+----+----+----+->
       -5    0    5   10   15 x
-----------------------
a == (a div b)*b + (a mod b)
   ^ y = x mod 5
 4 |   *    *    *    *    *
   |  *    *    *    *    *
   | *    *    *    *    *    *
   |*    *    *    *    *    *
 0 +----*----*----*----*----*->
       -5    0    5   10   15 x
   ^ y = x mod 5
 4 |             *    *    *
   |            *    *    *
   |           *    *    *    *
   |          *    *    *    *
 0 |    *    *    *    *    *
   |   *    *
   |  *    *
   | *    *
-4 |*    *
   +----+----+----+----+----+->
       -5    0    5   10   15 x

Community Discussions

Trending Discussions on Python
  • Python/Docker ImportError: cannot import name 'json' from itsdangerous
  • Why is it faster to compare strings that match than strings that do not?
  • Why is `np.sum(range(N))` very slow?
  • Error while downloading the requirements using pip install (setup command: use_2to3 is invalid.)
  • Repeatedly removing the maximum average subarray
  • WARNING: Running pip as the 'root' user
  • How do I calculate square root in Python?
  • pip-compile raising AssertionError on its logging handler
  • ImportError: cannot import name 'url' from 'django.conf.urls' after upgrading to Django 4.0
  • How did print(*a, a.pop(0)) change?
Trending Discussions on Python

QUESTION

Python/Docker ImportError: cannot import name 'json' from itsdangerous

Asked 2022-Mar-31 at 12:49

I am trying to get a Flask and Docker application to work but when I try and run it using my docker-compose up command in my Visual Studio terminal, it gives me an ImportError called ImportError: cannot import name 'json' from itsdangerous. I have tried to look for possible solutions to this problem but as of right now there are not many on here or anywhere else. The only two solutions I could find are to change the current installation of MarkupSafe and itsdangerous to a higher version: https://serverfault.com/questions/1094062/from-itsdangerous-import-json-as-json-importerror-cannot-import-name-json-fr and another one on GitHub that tells me to essentially change the MarkUpSafe and itsdangerous installation again https://github.com/aws/aws-sam-cli/issues/3661, I have also tried to make a virtual environment named veganetworkscriptenv to install the packages but that has also failed as well. I am currently using Flask 2.0.0 and Docker 5.0.0 and the error occurs on line eight in vegamain.py.

Here is the full ImportError that I get when I try and run the program:

veganetworkscript-backend-1  | Traceback (most recent call last):
veganetworkscript-backend-1  |   File "/app/vegamain.py", line 8, in <module>
veganetworkscript-backend-1  |     from flask import Flask
veganetworkscript-backend-1  |   File "/usr/local/lib/python3.9/site-packages/flask/__init__.py", line 19, in <module>
veganetworkscript-backend-1  |     from . import json
veganetworkscript-backend-1  |   File "/usr/local/lib/python3.9/site-packages/flask/json/__init__.py", line 15, in <module>
veganetworkscript-backend-1  |     from itsdangerous import json as _json
veganetworkscript-backend-1  | ImportError: cannot import name 'json' from 'itsdangerous' (/usr/local/lib/python3.9/site-packages/itsdangerous/__init__.py)
veganetworkscript-backend-1 exited with code 1

Here are my requirements.txt, vegamain.py, Dockerfile, and docker-compose.yml files:

requirements.txt:

Flask==2.0.0
Flask-SQLAlchemy==2.4.4
SQLAlchemy==1.3.20
Flask-Migrate==2.5.3
Flask-Script==2.0.6
Flask-Cors==3.0.9
requests==2.25.0
mysqlclient==2.0.1
pika==1.1.0
wolframalpha==4.3.0

vegamain.py:

# Veganetwork (C) TetraSystemSolutions 2022
# all rights are reserved.  
# 
# Author: Trevor R. Blanchard Feb-19-2022-Jul-30-2022
#

# get our imports in order first
from flask import Flask # <-- error occurs here!!!

# start the application through flask.
app = Flask(__name__)

# if set to true will return only a "Hello World" string.
Debug = True

# start a route to the index part of the app in flask.
@app.route('/')
def index():
    if (Debug == True):
        return 'Hello World!'
    else:
        pass

# start the flask app here --->
if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0') 

Dockerfile:

FROM python:3.9
ENV PYTHONUNBUFFERED 1
WORKDIR /app
COPY requirements.txt /app/requirements.txt
RUN pip install -r requirements.txt
COPY . /app

docker-compose.yml:

version: '3.8'
services:
  backend:
    build:
      context: .
      dockerfile: Dockerfile
    command: 'python vegamain.py'
    ports:
      - 8004:5000
    volumes:
      - .:/app
    depends_on:
      - db

#  queue:
#    build:
#      context: .
#      dockerfile: Dockerfile
#    command: 'python -u consumer.py'
#    depends_on:
#      - db

  db:
    image: mysql:5.7.22
    restart: always
    environment:
      MYSQL_DATABASE: admin
      MYSQL_USER: root
      MYSQL_PASSWORD: root
      MYSQL_ROOT_PASSWORD: root
    volumes:
      - .dbdata:/var/lib/mysql
    ports:
      - 33069:3306

How exactly can I fix this code? thank you!

ANSWER

Answered 2022-Feb-20 at 12:31

I was facing the same issue while running docker containers with flask.

I downgraded Flask to 1.1.4 and markupsafe to 2.0.1 which solved my issue.

Check this for reference.

Source https://stackoverflow.com/questions/71189819

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

The package python/cpython from 0 and before 3.6.13, from 3.7.0 and before 3.7.10, from 3.8.0 and before 3.8.8, from 3.9.0 and before 3.9.2 are vulnerable to Web Cache Poisoning via urllib.parse.parse_qsl and urllib.parse.parse_qs by using a vector called parameter cloaking. When the attacker can separate query parameters using a semicolon (;), they can cause a difference in the interpretation of the request between the proxy (running with default configuration) and the server. This can result in malicious requests being cached as completely safe ones, as the proxy would usually not see the semicolon as a separator, and therefore would not include it in a cache key of an unkeyed parameter.
CVE-2021-3177 CRITICAL
Python 3.x through 3.9.1 has a buffer overflow in PyCArg_repr in _ctypes/callproc.c, which may lead to remote code execution in certain Python applications that accept floating-point numbers as untrusted input, as demonstrated by a 1e300 argument to c_double.from_param. This occurs because sprintf is used unsafely.
In Python 3 through 3.9.0, the Lib/test/multibytecodec_support.py CJK codec tests call eval() on content retrieved via HTTP.
An issue was discovered in urllib2 in Python 2.x through 2.7.16 and urllib in Python 3.x through 3.7.3. CRLF injection is possible if the attacker controls a url parameter, as demonstrated by the first argument to urllib.request.urlopen with \r\n (specifically in the path component of a URL that lacks a ? character) followed by an HTTP header or a Redis command. This is similar to the CVE-2019-9740 query string issue. This is fixed in: v2.7.17, v2.7.17rc1, v2.7.18, v2.7.18rc1; v3.5.10, v3.5.10rc1, v3.5.8, v3.5.8rc1, v3.5.8rc2, v3.5.9; v3.6.10, v3.6.10rc1, v3.6.11, v3.6.11rc1, v3.6.12, v3.6.9, v3.6.9rc1; v3.7.4, v3.7.4rc1, v3.7.4rc2, v3.7.5, v3.7.5rc1, v3.7.6, v3.7.6rc1, v3.7.7, v3.7.7rc1, v3.7.8, v3.7.8rc1, v3.7.9.
An issue was discovered in urllib2 in Python 2.x through 2.7.16 and urllib in Python 3.x through 3.7.3. CRLF injection is possible if the attacker controls a url parameter, as demonstrated by the first argument to urllib.request.urlopen with \r\n (specifically in the query string after a ? character) followed by an HTTP header or a Redis command. This is fixed in: v2.7.17, v2.7.17rc1, v2.7.18, v2.7.18rc1; v3.5.10, v3.5.10rc1, v3.5.8, v3.5.8rc1, v3.5.8rc2, v3.5.9; v3.6.10, v3.6.10rc1, v3.6.11, v3.6.11rc1, v3.6.12, v3.6.9, v3.6.9rc1; v3.7.4, v3.7.4rc1, v3.7.4rc2, v3.7.5, v3.7.5rc1, v3.7.6, v3.7.6rc1, v3.7.7, v3.7.7rc1, v3.7.8, v3.7.8rc1, v3.7.9.

Install Python

You can download it from GitHub.
You can use Python like any standard Python library. You will need to make sure that you have a development environment consisting of a Python distribution including header files, a compiler, pip, and git installed. Make sure that your pip, setuptools, and wheel are up to date. When using pip it is generally recommended to install packages in a virtual environment to avoid changes to the system.

Support

Read our Contribution Guidelines before you contribute.

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Explore Related Topics

Share this Page

share link
Reuse Pre-built Kits with Python
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.