小编Dev*_*gue的帖子

检查是否可以使用提供的列表中的单词将字符串拆分为句子

我最近偶然发现了编码任务,我一直在努力做到正确.它是这样的:


给定非空字符串sword_list包含非空单词列表的列表,确定是否s可以将其分段为一个或多个字典单词的空格分隔序列.您可以假设word_list它不包含重复项,但每个单词可以多次使用.

例如,给定:

s = 'whataniceday'
word_list = ['a', 'what', 'an', 'nice', 'day']
Run Code Online (Sandbox Code Playgroud)

返回True,因为'whataniceday'可以分段为'what a nice day'.


我提出了一个非常幼稚的解决方案,适用于这个特定的例子,但不难让它失败,例如通过向word_list列表中的另一个单词添加一个单词(即['a', 'wha', 'what', 'an', 'nice', 'day']).还有很多其他的东西可能会破坏我的解决方案,但无论如何这里有:

s = "whataniceday"
word_list = ["h", "a", "what", "an", "nice", "day"]

def can_be_segmented(s, word_list):
    tested_str = s
    buildup_str = ''

    for letter in tested_str:        
        buildup_str += letter

        if buildup_str not in word_list:
            continue

        tested_str = tested_str[len(buildup_str):]
        buildup_str = '' …
Run Code Online (Sandbox Code Playgroud)

python python-3.x

5
推荐指数
2
解决办法
95
查看次数

在Go中将uint16转换为int16的正确方法

按位操作和Go newbie在这里:DI正在使用Go从传感器读取一些数据,我将其作为2个字节 - 比方说0xFFFE.很容易把它转换为uint16,因为在Go中我们可以做uint16(0xFFFE)但我需要的是将它转换为整数,因为传感器实际上返回范围从-32768到32767.现在我想"也许Go会是这个很好,如果我这样做int16(0xFFFE)会明白我想要的吗?" , 但不是.我最终使用了以下解决方案(我从网上翻译了一些python代码):

x := 0xFFFE

if (x & (1 << 15)) != 0 {
    x = x - (1<<16)
}
Run Code Online (Sandbox Code Playgroud)

它似乎工作,但A)我不完全确定为什么,和B)它看起来有点难看,我想象应该是一个简单的解决方案,将uint16转换为int16.任何人都可以帮我一把,并澄清为什么这只是这样做的方法?或者还有其他可行的方法吗?

bit-manipulation go uint16

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

Python在迭代字典时省略了一些条目,为什么?

这是我的字典和迭代方法:

update_config_switch = OrderedDict([
    (mode0               , self.mode0Box),
    (config_list[14]     , self.baudrate0Box),
    (config_list[1]      , self.RX_size_uart0Box),
    (config_list[2]      , self.RX_timeout_uart0Box),
    (config_list[3]      , self.TX_size_uart0Box),
    (mode1               , self.mode1Box),
    (config_list[15]     , self.baudrate1Box),
    (config_list[5]      , self.RX_size_uart1Box),
    (config_list[6]      , self.RX_timeout_uart1Box),
    (config_list[7]      , self.TX_size_uart1Box),
    (config_list[8]      , self.RX_size_socket0Box),
    (config_list[9]      , self.RX_timeout_socket0Box),
    (config_list[10]     , self.TX_size_socket0Box),
    (config_list[11]     , self.RX_size_socket1Box),
    (config_list[12]     , self.RX_timeout_socket1Box),
    (config_list[13]     , self.TX_size_socket1Box)])
    print update_config_switch
    for key, val in update_config_switch.iteritems():
        print key
        try:
            index = val.findText(str(key))
            if index >= 0:
                val.setCurrentIndex(index)
        except:
            val.setProperty("value", int(key))
Run Code Online (Sandbox Code Playgroud)

这个dict应该有16个项目,但是当我打印它或每次循环时我打印键时,我只得到7个结果,如下所示:

OrderedDict([('eth',),(9600,),(300,),(500,),('dev',),(115200,),(1000,)])

为什么这样以及如何解决这个问题?

python iteration collections dictionary

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