首次编程练习

2024-09-29 23:24:14 发布

您现在位置:Python中文网/ 问答频道 /正文

第一次编程。。。我试着做这个练习是为了。。公司名称:

编写一个程序,打印s中字母按字母顺序出现的最长子串。例如,如果s='azcbobebeghakl',那么您的程序应该打印

按字母顺序最长的子串是:beggh

我在这里…在开始发狂之前:

s = 'abcdezcbobobegghakl'
n = len(s) 
x = 0


x += 1
lengh = s[x-1]
if s[x] >= s[x-1]:
    lengh = lengh + s[x]


if s[x+1] < s[x]:
    n = len(lengh)
if x > n:
    break 

print('Longest substring in alphabetical order is: ' + str(lengh)) 

我知道这段代码不好…我正在尝试按字母顺序查找子字符串,并以某种方式保留最长的子字符串!我知道这可能是正常的,因为我以前从未编程,但我感到非常沮丧…有什么好主意/帮助??在


Tags: 字符串程序名称lenif顺序编程字母
3条回答
def find_longest_substr(my_str):

    # string var to hold the result
    res = ""

    # candidate for the longest sub-string 
    candidate = ""

    # for each char in string
    for char in my_str:

        # if candidate is empty, just add the first char to it
        if not candidate:
            candidate += char

        # if last char in candidate is "lower" than equal to current char, add char to candidate
        elif candidate[-1] <= char:
            candidate += char

        # if candidate is longer than result, we found new longest sub-string
        elif len(candidate) > len(res):
            res= candidate
            candidate = char

        # reset candidate and add current char to it
        else:
            candidate = char

    # last candidate is the longest, update result
    if len(candidate) > len(res):
        res= candidate

    return res


def main():
    str1 = "azcbobobegghaklbeggh"
    longest = find_longest_substr(str1)
    print longest


if __name__ == "__main__":
    main()

以下代码使用reduce方法解决了该问题:

solution = ''

def check(substr, char):
    global solution
    last_char = substr[-1]
    substr = (substr + char) if char >= last_char else char
    if len(substr) > len(solution):
        solution = substr
    return substr

def get_largest(s):
    global solution
    solution = ''
    reduce(check, list(s))
    return solution

首先试着把你的问题分解成小问题(不要优化!如果您了解了函数,它们是将执行流分解为可读和可理解片段的好方法。在

例如:

def get_sequence_size(my_string, start):
   # Your code here
   return size_of_sequence

current_position = 0
while current_position < len(my_string):
   # Your code here using get_sequence_size() function

相关问题 更多 >

    热门问题