小编Ksh*_*ogi的帖子

三和的优化解

我正在尝试解决 3 Sum 问题,如下所示:

给定一个由 n 个整数组成的数组 S,S 中是否有元素 a、b、c 使得 a + b + c = 0?在数组中找到所有唯一的三元组,其总和为零。

注意:解决方案集不得包含重复的三元组。

这是我对这个问题的解决方案:

def threeSum(nums):
    """
    :type nums: List[int]
    :rtype: List[List[int]]
    """
    nums.sort()
    n = len(nums)
    solutions = []
    for i, num in enumerate(nums):
        if i > n - 3:
            break

        left, right = i+1, n-1
        while left < right:
            s = num + nums[left] + nums[right] # check if current sum is 0
            if s == 0:
                new_solution = [num, nums[left], nums[right]] …
Run Code Online (Sandbox Code Playgroud)

python algorithm

5
推荐指数
1
解决办法
4372
查看次数

PI中的数字位数不同

我是Python的初学者,我对PI有疑问.

>>> import math
>>> p = math.pi
>>> print p
3.14159265359
>>> math.pi
3.141592653589793
Run Code Online (Sandbox Code Playgroud)
  • 为什么两者的位数不同?
  • 如何在不使用Chudnovsky算法的情况下将Pi的值增加到更多小数位?

python printing variables pi

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

如何在 Python 元组中定义重复项?

定义由整数组成的元组(其中每个项目出现的次数已知)有哪些好方法?

例如,

我想定义一个元组,其中 3 个 2、2 个 4 和 1、3、5 出现一次。

为此,我始终可以采用手动方式:

foo = (1, 2, 2, 2, 3, 4, 4, 5)
Run Code Online (Sandbox Code Playgroud)

但是,当列表中的项目数量很大时,这会变得有点混乱。因此,我想知道有哪些方法可以自动执行生成每个项目所需数量的重复项的任务。

python indexing tuples python-3.x

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

Go中负整数的模数

我目前正在学习GoLang,而且我来自Python背景.

最近,我偶然发现了%(modulo)运算符的行为,它与Python中的相应运算符不同.与模运算和余数的定义完全相反,正整数的负整数模数返回负值.

例:

蟒蛇

a, b, n = -5, 5, 3
for i in range(a, b):
    print(i%n)    
Run Code Online (Sandbox Code Playgroud)

输出:

1
2
0
1
2
0
1
2
0
1
Run Code Online (Sandbox Code Playgroud)

a, b, n := -5, 5, 3
for i:=a; i<b; i++ {
    fmt.Println(i%n)
}
Run Code Online (Sandbox Code Playgroud)

输出:

-2
-1
0
-2
-1
0
1
2
0
1
Run Code Online (Sandbox Code Playgroud)

阅读后模运算符和几个类似的问题问及背后这些差异的原因,据我所知,这是由于设计有关语言的目标.

Q1.我想知道为什么Go遵循C/C++协议而不是Python.任何相关讨论的链接都会有所帮助.

Q2.Go中是否有内置功能可以复制Python的模数运算?
替代:是否有内部方法来计算"模数"而不是"余数"?

python go modulo

4
推荐指数
2
解决办法
1550
查看次数

删除字符串中的元音.我究竟做错了什么?

我试图通过将所有辅音放入不同的数组然后将第一个数组重新初始化为第二个数组来删除字符串的所有元音.之后,应该打印第一个数组,即只有辅音.我真的不确定问题出在哪里,我一直在看这个问题好三个小时,我已经厌倦了.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char str [100];
    char garbage[100];
    int loopcondition = 0 , j = 0 , k = 0;
    int userinput;
    char a = "a" , e = "e" , i = "i", o = "o" , u = "u";

    printf("!!!Hello World!!! Please type in a string from which I can  remove all the vowels:\n");

    //This program is supposed to take in a string and then delete all the vowels

    gets(str); //gets …
Run Code Online (Sandbox Code Playgroud)

c arrays string logical-operators

3
推荐指数
1
解决办法
204
查看次数

改善"增加数字表示的数字"的时间复杂性

问题 给定一个非负数表示为数字数组,

将数字加1(增加数字所代表的数字).

存储数字使得最高有效数字位于列表的开头.

例:

如果向量有[1,2,3]

返回的向量应为[1,2,4]

因为123 + 1 = 124.

我的守则

def plusOne(A):
    num = 0

    for digit in A:
        num = num*10 + digit

    retnum = num + 1

    retA = []

    while retnum > 0:
        retA.append(retnum % 10)
        retnum /= 10

    return retA[::-1]
Run Code Online (Sandbox Code Playgroud)

好吧,我得到了正确答案.但是,我对代码的时间复杂性并不满意.建议改进此代码.

python algorithm time-complexity

3
推荐指数
1
解决办法
720
查看次数

Python中的高效堆栈实现

第一个实现:以下堆栈实现假定列表的末尾将保存堆栈的顶部元素.随着堆栈的增长,新项目将添加到列表的末尾.

class Stack:
    def __init__(self):
        self.items = []

    def isEmpty(self):
        return self.items == []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        return self.items.pop()

    def peek(self):
        return self.items[len(self.items)-1]

    def size(self):
        return len(self.items)
Run Code Online (Sandbox Code Playgroud)

第二个实现:第二个实现假定列表的开头包含堆栈的顶部元素,并在索引0处添加新项目.

 class Stack:
     def __init__(self):
         self.items = []

     def isEmpty(self):
         return self.items == []

     def push(self, item):
         self.items.insert(0,item)

     def pop(self):
         return self.items.pop(0)

     def peek(self):
         return self.items[0]

     def size(self):
         return len(self.items)
Run Code Online (Sandbox Code Playgroud)

作为数据结构的初学者,我想知道:
1.哪种实现在时间或空间方面更有效,为什么?
2. insert(0)第二个实现中的时间复杂度是否为O(n).如果有,怎么样?

python performance stack abstract-data-type data-structures

3
推荐指数
1
解决办法
2428
查看次数

在Python中定义unicode变量

最近,我一直在阅读Python源代码编码,尤其是PEP 263PEP 3120.

我有以下代码:

# coding:utf-8

s = 'abc?´ƒ©'
ƒ = 'My name is'
ß = '?ß?ˆ†ˆ? ßå®åø©ˆ'
print('s =', s)
print('ƒ =', ƒ, 'ß =', ß)
Run Code Online (Sandbox Code Playgroud)

此代码适用于Python3,但SyntaxError在Python2.7中生成.
我知道这可能与源代码编码无关.
所以,我想知道是否有办法在Python2中支持Unicode变量名.

总而言之,我也很难弄清楚PEP究竟要解决的实际问题以及我如何(以及在​​何处)利用所提出的解决方案.我已经阅读了相同的讨论,但他们没有提出我的问题的答案,而是对正确语法的解释:

python unicode encoding python-2.7 python-3.5

3
推荐指数
1
解决办法
572
查看次数

在 Go 中验证 GitHub Webhook HMAC 签名

我编写了以下函数来验证X-Hub-Signature由 GitHub API 返回的请求标头作为 webhook 负载的一部分。

func isValidSignature(r *http.Request, key string) bool {
    // Assuming a non-empty header
    gotHash := strings.SplitN(r.Header.Get("X-Hub-Signature"), "=", 2)
    if gotHash[0] != "sha1" {
        return false
    }
    defer r.Body.Close()

    b, err := ioutil.ReadAll(r.Body)
    if err != nil {
        log.Printf("Cannot read the request body: %s\n", err)
        return false
    }

    hash := hmac.New(sha1.New, []byte(key))
    if _, err := hash.Write(b); err != nil {
        log.Printf("Cannot compute the HMAC for request: %s\n", err)
        return false
    }

    expectedHash := …
Run Code Online (Sandbox Code Playgroud)

go webhooks hmacsha1 github-api

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

欧拉计划 #19,Python

我正在解决Project Euler #19

在 20 世纪(1901 年 1 月 1 日至 2000 年 12 月 31 日),每月的第一个星期日有多少个星期日?

这是代码:

months = { "January": 31,
        "February" : 28,
        "March" : 31,
        "April" : 30,
        "May" : 31,
        "June" : 30,
        "July" : 31,
        "August" : 31,
        "September" : 30,
        "October" : 31,
        "November" : 30,
        "December" : 31}

def countingSundays():
    day = 1
    sunday_count = 0

    for year in xrange(1901,2001):

        for m in months:

            day += months[m]
            if year % …
Run Code Online (Sandbox Code Playgroud)

python date

0
推荐指数
1
解决办法
7600
查看次数

我应该如何在Python中使用参数传递参数(dict vs variables)?

我有一个函数/方法A()需要一些参数(包括可选参数).另一个功能B()是对要传递给所述功能的数据进行预处理A().我几乎没有该功能的替代实现,B()这使我对一个优于另一个的优点感到困惑.我想了解我应该使用哪些(如果有的话).

毕竟, There should be one-- and preferably only one --obvious way to do it.

这是代码片段:

class Foo(object):

    def __init__(self, param1, param2, param3=None):
        self.param1 = param1
        self.param2 = param2
        self.param3 = param3

    @classmethod
    def from_dump_v1(cls, dump):
        param1, param2, param3 = dump.get('param_1'), dump.get('_param_2'), dump.get('paramThree')
        return cls(param1, param2, param3)

    @classmethod
    def from_dump_v2(cls, dump):
        dump['param1'] = dump.pop('param_1')
        dump['param2'] = dump.pop('_param_2')
        dump['param3'] = dump.pop('paramThree')
        return cls(**dump)

    @classmethod
    def from_dump_v3(cls, dump):
        result = dict()
        result['param1'] = dump.get('param_1') …
Run Code Online (Sandbox Code Playgroud)

python parameters arguments function

0
推荐指数
1
解决办法
81
查看次数