first time programming-exercise

2019-09-20 09:19发布

问题:

First time programming ever... I'm trying to do this exercise to.. :

Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print

Longest substring in alphabetical order is: beggh

I was here..before starting to freak out:

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

I know this code is bad..I m trying to find substring in alphabetical order and is some way keep the longest one! I know could be normal, because I never programmed before but i feel really frustrated...any good idea/help??

回答1:

First try to decompose your problem into little problems (do not optimize ! until your problem is solved), if you have learned about functions they are a good way to decompose execution flow into readable and understandable snippets.

An example to start would be :

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


回答2:

The following code solves the problem using the reduce method:

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:

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


回答4:

These are all assuming you have a string (s) and are needing to find the longest substring in alphabetical order.

Option 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

Option 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

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

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


回答5:

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