小编Sol*_*ell的帖子

Python类型提示:将类型指定为数字列表(整数和/或浮点数)?

我如何具体的函数可以采用可以是整数或浮点数的列表?

我尝试使用Union这样的新类型:

num = Union[int, float]

def quick_sort(arr: List[num]) -> List[num]:
    ...
Run Code Online (Sandbox Code Playgroud)

但是,mypy并不喜欢这样:

 quickSortLomutoFirst.py:32: error: Argument 1 to "quickSortOuter" has
 incompatible type List[int]; expected List[Union[int, float]]  
Run Code Online (Sandbox Code Playgroud)

是否有包含整数和浮点数的类型?

python types type-hinting mypy

23
推荐指数
2
解决办法
8212
查看次数

Haskell:如何记住这个算法?

在 HackerRank 上硬币找零问题写了这个解决方案:

makeChange :: Int -> [Int] -> Int
makeChange n ys = go n (sort ys)
    where go _ [] = 0
          go n (x:xs)
            | x == n = 1
            | x > n = 0
            | otherwise = (makeChange n xs) + (makeChange (n - x) (x:xs))
Run Code Online (Sandbox Code Playgroud)

然而,它在一些较大的测试用例上超时。我看到这篇关于使用let绑定实现记忆的文章,但它大部分都让我无法理解,我不确定我将如何在这里实现它。有什么帮助吗?

我重写了它并获得了实质性的性能改进,但我仍然在黑客排名练习中超时:

makeChange' :: Int -> [Int] -> Int
makeChange' =
    let go _ [] = 0
        go n (x:xs)
          | …
Run Code Online (Sandbox Code Playgroud)

algorithm performance haskell memoization dynamic-programming

4
推荐指数
1
解决办法
221
查看次数

Karatsuba乘法实现

我最近实施了Karatsuba Multiplication作为个人练习.我按照维基百科上提供伪代码在Python中编写了我的实现:

procedure karatsuba(num1, num2)
if (num1 < 10) or (num2 < 10)
    return num1*num2
  /* calculates the size of the numbers */
  m = max(size_base10(num1), size_base10(num2))
  m2 = m/2
  /* split the digit sequences about the middle */
  high1, low1 = split_at(num1, m2)
  high2, low2 = split_at(num2, m2)
  /* 3 calls made to numbers approximately half the size */
  z0 = karatsuba(low1, low2)
  z1 = karatsuba((low1+high1), (low2+high2))
  z2 = karatsuba(high1, high2)
  return (z2*10^(2*m2)) + ((z1-z2-z0)*10^(m2)) …

python algorithm recursion karatsuba

2
推荐指数
1
解决办法
4986
查看次数