파이썬 질문. 주어진 문자열에서 가장 작은 알파벳, 세번째 작은 알파벳, 가장 많이 나온 알파벳 구하기.

조회수 961회

학교 수업에서 파이썬 3을 배우고 있는 학생입니다. 학교 숙제를 받았는데 어떻게 시작할지를 모르겠어서 여기에다가 질문 올려요.

1. Write a function, q2(inputString, minLetter), that takes as input a string of letters and returns six things: the lexicographically smallest letter (z/Z > y/Y > ... > a/A) greater or equal to minLetter, the smallest index at which that letter occurs, the third smallest letter greater than minLetter, the smallest index at which that letter occurs, the most common letter, and how many times the most common letter occurs. The third smallest letter must be distinct from the second smallest which must be distinct from the smallest. E.g. 'b' is the second smallest and 'c' is the third smallest in 'ababdc'

Ignore case during computation. E.g. 'z' and 'Z' are considered the same letter. Use lower case when returning letters.

Return None for smallest and thirdSmallest letters and corresponding indices when appropriate.

You may not assume that the input string contains at least three different characters (or even any characters at all). Make sure to recognize various situations where fewer than three different letters appear in the string, and where there is no third smallest or smallest greater than minLetter.

If two or more letters tie for most common, return the lexicographically smallest one.

For example:

>>> q2('aacyYcqyQQqyqc', 'b')
('c', 2, 'y', 3, 'q', 5)

>>> q2('aacyYcqyQQqyqc', 'r')
('y', 3, None, None, 'q', 5)

질문은 이건데 학교에서 list 나 sort 는 아직 안배웠다고 쓰지말라고 하셔서 어떻게 해야할지 모르겠어요. 파이썬 처음 배우는거라 뭐가 뭔지도 모르겠는데 수업에서 잘 알려주지도 않아서 걱정입니다. 파이썬 고수분들 제발 도움좀 주세요.

지금 당장 코드 두줄밖에 못짰는데 어떻게 접근해야할지를 모르겠어요.

  • 리스트를 안쓰고 이게 가능한지..? 엽토군 2020.2.11 15:39
  • 결과가 튜플입니다. 리스트는 안되고 튜플은 되나봐요...즉 리스트전에 튜플은 배웠다는 이야기인가요? 정영훈 2020.2.11 19:28
  • 질문하고 example 결과하고 도통 매칭이 안되는 것 같습니다. ('c', 2, 'y', 3, 'q', 5) 의 결과의 의미가 무엇인가요? 정영훈 2020.2.11 20:51

1 답변

  • smallest = None
    smallestIdx = None
    idx = 0
    
    for c in inputString:
        if smallest == None:
            if c >= minLetter:
                smallest = c
                smallestIdx = idx
        else:
            if c > smallest:
                smallest = c
                smallestIdx = idx
        idx += 1
    

    다 소문자화 해 놓았다고 가정을 하고요. 일단 가장 작은놈 찾아내는 겁니다. 한놈씩 꺼내서 가장작은놈하고 비교해서, 이번에 꺼낸놈이 더 작으면 그놈을 가장작은놈이라고 하는 겁니다.

    이게 이해가 가면 3번째 작은놈 구하는 건, 그냥 3개 기억해 놓고 루프 돌리면 되니까 간단합니다.

    갯수 세는 것도 조금 더 생각을 확장해야 하지만 루프돌리면서 한놈씩 꺼내서 비교해보면서 카운터를 바꿔주는 게 그리 다르지 않아요.

    • 여기까지는 이해한 거 같아요! 한가지 헷갈리는부분은 if smallest == None: 인데 이 부분이 꼭 필요한 이유가 뭔가요?? 그리고 smallest를 None으로 두었으면 thirdSmallest도 None으로 두어야 하나요?? 알 수 없는 사용자 2020.2.12 02:44
    • smallest 가 None 인 경우는 지금까지 minLetter 이상인 글자가 없었을 때에요. 문제 조건과 예시를 보면 minLetter 이상인 게 하나도 없으면, None 을 반환하기 때문에, 초기값을 그렇게 세팅한 겁니다. 그런 의도입니다. 이게 꼭 정답은 아니고 다른 방법도 있을 수 있어요. 굳럭. nowp 2020.2.12 12:57

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)