2017-12-28 28 views
-2

알파벳 순서로 문자가 나오는 s 중에서 가장 긴 하위 문자열을 인쇄하는 프로그램을 작성하십시오. 예를 들어, s = 'azcbobobegghakl' 인 경우, 프로그램은 가장 긴 부분 문자열을 알파벳순으로 인쇄해야합니다 : beggh.누구나 python 다음 코드를 설명 할 수 있습니다 (신참 루키입니다)

동점의 경우 첫 번째 하위 문자열을 인쇄하십시오. 예를 들어,

s = "azcbobobegghakl" 

x = s[0] 

y = s[0] 


for i in range (1, len(s)): 

    if s[i] >= s[i-1]: 
     y += s[i] 

    else: 
     y = s[i] 

    if len(y) > len(x): 
     x = y    
print(x) 

답변

3

이 숙제 냄새,하지만 ... 여기 설명하는 주석이다 abcbc의의 = '

# assign a string to a variable named s 
s = "azcbobobegghakl" 

# assign the zeroth character of the string s to x 
x = s[0] 

# assign the zeroth character of the string s to y  
y = s[0] 


# loop through a range of numbers starting at 1 and going to the length of s 
# within each loop, the variable i tells us which iteration of the loop 
# we're currently in.  
for i in range(1, len(s)): 
    # compare the character in s at the position equal 
    # to the current iteration number to see if it's greater 
    # than or equal to the one before it. Alphabetic characters 
    # compared like this will evaluate as numbers corresponding 
    # to their position in the alphabet. 
    if s[i] >= s[i-1]: 
     # when characters are in alphabetical order, add them to string y 
     y += s[i] 
    else: 
     # when the characters are not in alphabetical order, replace y with 
     # the current character 
     y = s[i] 
    # when the length of y is greater than of x, assign y to x 
    if len(y) > len(x): 
     x = y 
# after finishing the loop, print x 
print(x) 
+0

정말 숙제이지만 내 좌절감 때문에 여기에 있습니다. 답을 고맙게 생각합니다. y와 x를 비교하여 y를 x에 대입하는 이유는 무엇인지 설명 할 수 있습니까? – ZeeShan

+0

"프로그램에서 가장 긴 부분 문자열" "을 인쇄해야 부분 문자열을 작성할 수 있으며 빌드 할 때마다 변경 될 때마다 마지막 부분과 비교할 수 있습니다. 길이가 길어지면 저장합니다. 동일하거나 더 짧은 경우 알파벳순으로 부분 문자열을 작성합니다. – TheAtomicOption

0

파이썬의 string 클래스가 포함 __lt__, __eq__ 데이터 모델 방법을 string 클래스 공동의

str1 = 'aaa' 
str2 = 'bbb' 
str3 = 'aaa' 

assert str2 < str1 # Will lead to AssertionError 
        # '<' calls the __lt__() method of the string class 

assert str1 == str3 # No AssertionError 
        #'==' calls the __eq__() method of the string class 

이 특정 데이터 모델 방법 - 어떤 할 우리를 수 mpare 문자열의 각 문자의 ASCII 값. 영어 알파벳의 각 문자의 ASCII 값은 'A'< 'B'< 'C'순차로 증가합니다. 한 번에 문자열을 하나 개의 문자를 통해

귀하의 코드

당신 루프 (2 문자에서 시작), 현재 캐릭터가 이전보다 더 큰 (또는 동일) ASCII 값이 있는지 확인하세요. 이 경우 문자가 y 문자열에 추가되고 결과 문자열은 y으로 저장됩니다. 그렇지 않은 경우 y는 현재 문자로 바뀝니다. 마지막으로 y의 문자 수가 x 이상이면 x의 문자열을 y으로 바꿉니다.

+0

이것은 내가 정확히 찾고 있었던 것이다. 고마워요. 정말 고마워요. 신의 축복이 있습니다. – ZeeShan

+0

당신을 진심으로 환영합니다. 원한다면이 대답을 받아 들일 수 있습니다. –