Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中,如何从输入字符串中返回接近特定字符数的单词?_Python_Algorithm_Knapsack Problem - Fatal编程技术网

在Python中,如何从输入字符串中返回接近特定字符数的单词?

在Python中,如何从输入字符串中返回接近特定字符数的单词?,python,algorithm,knapsack-problem,Python,Algorithm,Knapsack Problem,输入时,我们有一长串单词。我应该返回一个由输入列表中的单词组成的任意字符串,并且只返回其中的一个。结果字符串的总长度应接近下界(行)的15个字符(忽略空格) str_ign_space = string.replace(' ', '') 分解if..elif..else条件块。不能使用elif启动条件块,因此您将得到一个语法错误 将elif替换为常规的if以启动新的条件块,代码将被解析。一个elif必须直接跟随一个if或另一个elif。您正在尝试放置以下语句: def return_word

输入时,我们有一长串单词。我应该返回一个由输入列表中的单词组成的任意字符串,并且只返回其中的一个。结果字符串的总长度应接近下界(行)的15个字符(忽略空格)

str_ign_space = string.replace(' ', '') 
分解
if
..
elif
..
else
条件块。不能使用
elif
启动条件块,因此您将得到一个语法错误


elif
替换为常规的
if
以启动新的条件块,代码将被解析。

一个
elif
必须直接跟随一个
if
或另一个elif。您正在尝试放置以下语句:

def return_words(string):
    MAXSYMB = 15
    if not string or string.isspace():
        return 'You did not enter any string'
    str_ign_space = string.replace(' ', '') 
    elif len(str_ign_space) <= MAXSYMB: 
        cur_str = string.split()
        return ' '.join(word for word in cur_str)
    else:
        a = [(i, len(i)) for i in cur_st]
        sorted_items = sorted(((length, word)
                       for word, length in a),
                      reverse = True)
        wt = 0
        bagged = []
        for length, word in sorted_items:
            portion = min(MAXSYMB - wt, length)
            wt     += portion
            bagged += [(word, portion)]
            if wt >= MAXSYMB:
                break
        return ' '.join(item[0] for item in bagged)
str_ign_space = string.replace(' ', '') 
if
elif
之间,这是没有意义的。相反,将该行放在
if
之前。这也可以简化
if
条件-由于您删除了所有空格,因此任何时候
string.isspace()
都是真的,您也会有
str\u ign\u space
为空:

def return_words(string):
    MAXSYMB = 15
    str_ign_space = string.replace(' ', '')
    if not str_ign_space:
        # Didn't enter a string without spaces
    elif len(str_ign_space) <= MAXSYMB:
        ....
这一行直接在
else:
下面,但是
cur\u st
只在它上面的
elif
中定义。每当
else
运行时,elif就不会运行了(根据定义),
cur\u st
将命名错误。我想你可能是指
for I in string.split()
。整个
elif
块非常奇怪。首先,请注意:

' '.join(word for word in cur_str)
与以下内容完全相同:

' '.join(cur_str)

很明显,你是在用空格分割字符串。只是立即用空格重新连接这些部分。这有时是合理的(它将多个空格压缩为一个),但这很不寻常——如果你是故意这么做的,那就值得一提解释原因。

你在第8行缺少了一个括号。投票以拼写错误结束与此类似,可能会有用。(你的同学?:-)@AlexThornton他说他在elif语句中有一个编译错误。我不认为失踪者)完全解决了问题+1实际上解决了问题,而不是像评论者那样直接跳到失踪者那里
a = [(i, len(i)) for i in cur_st]
' '.join(word for word in cur_str)
' '.join(cur_str)
from collections import Counter

def find_highest_combo_lte_target(lencounts, target):
    # highest achievable values == sum of all items
    total = sum(length*num for length,num in lencounts)

    if total <= target:
        # exact solution or not reachable - return everything
        return lencounts
    else:
        # dynamic programming solution
        found = {0: []}
        for length,num in lencounts:
            new_found = {}
            for k in range(1, num+1):
                val = length * k
                if (target - val) in found:
                    return found[target - val] + [(length, k)]
                else:
                    for total,values in found.items():
                        newtotal = val + total
                        if newtotal < target and newtotal not in found:
                            new_found[newtotal] = found[total] + [(length, k)]
            found.update(new_found)
        best = max(found)
        return found[best]

def build_string(words, lencounts):
    len_num = dict(lencounts)
    result = []
    for word in words:
        wl = len(word)
        if len_num.get(wl, 0) > 0:
            result.append(word)
            len_num[wl] -= 1
    return " ".join(result)

def return_words(s, targetlen):
    words   = s.split()         
    counts  = Counter(len(word) for word in words).items()
    bestsol = find_highest_combo_lte_target(counts, targetlen)
    return build_string(words, bestsol)

def main():
    s = "This is a very long string containing some words odd and eerie"
    for i in range(30):
        print("{:>2}: {}".format(i, return_words(s, i)))

if __name__=="__main__":
    main()
 0: 
 1: a
 2: is
 3: is a
 4: a odd
 5: is odd
 6: is a odd
 7: a odd and
 8: is odd and
 9: is a odd and
10: This odd and
11: This a odd and
12: This is odd and
13: This is a odd and
14: This very odd and
15: This a very odd and
16: This is very odd and
17: This is a very odd and
18: This very long odd and
19: This a very long odd and
20: This is very long odd and
21: This is a very long odd and
22: This very long some odd and
23: This a very long some odd and
24: This is very long some odd and
25: This is a very long some odd and
26: This is very long some words odd
27: This very long some words odd and
28: This a very long some words odd and
29: This is very long some words odd and