第一次编程练习

时间:2013-10-26 09:21:09

标签: python string substring

有史以来第一次编程...我正在尝试进行此练习......:

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

按字母顺序排列的最长子字符串是: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)) 

我知道这段代码很糟糕。我试图按字母顺序查找子字符串,并且保留最长的字符串!我知道可能是正常的,因为我之前没有编程,但我感到非常沮丧...任何好主意/帮助??

5 个答案:

答案 0 :(得分:0)

首先尝试将您的问题分解为小问题(不要优化!直到您的问题得到解决),如果您已经了解了函数,那么它们是将执行流分解为可读且易于理解的片段的好方法。

开始的一个例子是:

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

答案 1 :(得分:0)

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()

答案 2 :(得分:0)

以下代码使用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

答案 3 :(得分:0)

这些都假设你有一个字符串,并且需要按字母顺序找到最长的子字符串。

选项A

test = s[0]      # seed with first letter in string s
best = ''        # empty var for keeping track of longest sequence  

for n in range(1, len(s)):    # have s[0] so compare to s[1]
    if len(test) > len(best):
        best = test
    if s[n] >= s[n-1]:
        test = test + s[n]    # add s[1] to s[0] if greater or equal
    else:                     # if not, do one of these options 
        test = s[n]

print "Longest substring in alphabetical order is:", best

选项B

maxSub, currentSub, previousChar = '', '', ''
for char in s:
    if char >= previousChar:
        currentSub = currentSub + char
        if len(currentSub) > len(maxSub):
            maxSub = currentSub
    else: currentSub = char
    previousChar = char
print maxSub

选项C

matches = []
current = [s[0]]
for index, character in enumerate(s[1:]):
    if character >= s[index]: current.append(character)
    else:
        matches.append(current)
        current = [character]
print "".join(max(matches, key=len))

选项D

def longest_ascending(s):
    matches = []
    current = [s[0]]
    for index, character in enumerate(s[1:]):
        if character >= s[index]:
            current.append(character)
        else:
            matches.append(current)
            current = [character]
    matches.append(current)
    return "".join(max(matches, key=len))
print(longest_ascending(s))

答案 4 :(得分:0)

def longest(s):
    buff = ''
    longest = ''

    s += chr(255)
    for i in range(len(s)-1):
        buff += s[i]
        if not s[i] < s[i+1]:
            if len(buff) > len(longest):
                longest = buff
            buff = ''
    if len(buff) > len(longest):
        longest = buff

    return longest