4

I have an assignment on python(2.7) which ask me to get output for a string. In the 4 question it is asked to give the letter of the alphabet that come earlier. This test only the first character of each word of the sentence. Example: "this is a sentence" the result should be "a" as it is the first letter of the alphabet.

Here is my code (including the previous questions of the assignment)

def GetNumWords ( Sentence ):
    Count = 0
    Length = len( Sentence )
    Index = 0
    while Index < Length:
        Char = Sentence [ Index ]
        if Char != ' ':
            Count += 1
            while Char != ' ' and Index < Length:
                Char = Sentence [ Index ]
                Index += 1
        else:
            Index += 1
    return Count

def GetWordNum ( Sentence, WordNum ):
    Count = 0
    Length = len( Sentence )
    Index = 0
    Word = ''   
    while Index < Length:
        Char = Sentence [ Index ]
        if Char != ' ':
            Count += 1
            while Char != ' ' and Index < Length:
                Char = Sentence [ Index ]
                Index += 1
                if Count == WordNum:
                    Word = Word + Char
        else:
            Index += 1
    if Word == '':
        return ''
    else:
        return Word

def GetFirstLetter ( Sentence, SpecificNum):
    TheWord = GetWordNum ( Sentence, SpecificNum )
    if TheWord == '':
        return ''
    else:
        FirstLetter = TheWord [ 0 ]
        return FirstLetter

def GetEarliestLetter ( Sentence ):
    CurrentMinNum = 1
    CurrentMin = GetFirstLetter ( Sentence, CurrentMinNum )
    LastWord = GetNumWords ( Sentence )
    if CurrentMin == '':
        return ''
    else:
        while CurrentMinNum <=  LastWord:
            FirstLetter = CurrentMin
            if FirstLetter < CurrentMin:
                CurrentMin = FirstLetter
                CurrentMinNum += 1
            else:
                break
        return CurrentMin

Doing so gives me the first letter of the first word of the sentence and not the earliest letter in the alphabet order.

Where did I do wrong? I have looked at this for the past 2 days, and I can't see where I am doing wrong.

9
  • 2
    Are the strings always lowercase and all alpha characters? Commented Jul 13, 2015 at 11:12
  • @PadraicCunningham: Don't forget about spaces. :) It appears that sylvain is using Python 2, since they mention "raw_input" in a comment, & so I guess we can safely assume the strings are byte strings, not Unicode. OTOH, they might contain accented letters... Commented Jul 13, 2015 at 11:18
  • 1
    BTW, it's conventional in Python to write plain variable names in all lower case. Names beginning with an upper-case letter are normally used for classes. The Stack Overflow syntax highlighting renders class names in cyan, so your script look a bit strange and jarring to Python veterans. Commented Jul 13, 2015 at 11:21
  • 1
    @sylvainpissardmaillet, the possible input and the case is pretty important to how the problem can be solved, if you always have lowercase letters then it is trivial to solve with a loop Commented Jul 13, 2015 at 11:26
  • 1
    Tell your lecturer to read PEP0008 Commented Jul 13, 2015 at 11:27

2 Answers 2

6

I think you might be overcomplicating it.

>>> s = "this is a sentence"
>>> min(c for c in s if c.isalpha())
'a'
Sign up to request clarification or add additional context in comments.

5 Comments

ha, sorry I forgot to say that I cannot use any libraries for the assignment. Only "input" "raw_input" and "len"
there's no outside library, min and isalpha are built in function/method
The goal is to force us to learn the hard way, but he didn't precise for the isalpha. he told us that we should compare each first character of each words of the sentence. Every time replacing the minimum character if the compared one is before.
@sylvainpissardmaillet: If the program is only supposed to test the first character of each word you need to state that clearly in your question.
Bad start for me in the forum. Yes my current problem is to find the earliest character in the alphabet. Using only the first character of each words
2

If you cannot use any str methods and can only use a while loop, raw_input and len then your input must be restricted so this will find the lowest first letter from each word:

def first_alpha():
    s = raw_input()
    mn, curr = s[0], s[0]
    i = 1
    while i < len(s):
        if s[i] == " ":
            if curr < mn:
                mn = curr
            curr = s[i+1]
        i += 1
    return mn if curr > mn else curr

Like I said this works for restricted inputs which are letters and the words are spaced by single spaces.

In [5]: first_alpha()
this is a sentence
Out[5]: 'a'    
In [6]: first_alpha()
lowest char is trailing a
Out[6]: 'a'    
In [7]: first_alpha()
lowest char is upper A
Out[7]: 'A'

Obviously min(word[0] for word in s.split()) would be a lot simpler way to do it if you were not restricted.

To catch only letters with non letters and catch spaces at the end:

def first_alpha():
    s = raw_input()
    # ord("{") == 123
    mn, curr = "{", "{"
    i = 0
    # catch line ending in a space
    ln = len(s) if s[-1] != " " else len(s) - 1
    while i < ln:
        if s[i] == " ": 
            if curr <= mn:
                mn = curr
            ch = s[i+1]
            # make sure we have a letter
            if "a" <= ch <= "z" or "A" <= ch <= "Z":
                curr = ch
        i += 1
    return mn if curr > mn else curr

Output:

In [29]: first_alpha()
this is sentence where the lowest is ! but we return a
Out[29]: 'a'
In [30]: first_alpha()
lots of   spaces and    but we return a     
Out[30]: 'a'

The only edge case would be a string where you had no letters, then the lowest would be } so you can decide what should happen in that case

12 Comments

Um, why do you pass s as a parameter and get it using raw_input?
@PM2Ring, was just passing a string to test show the output forgot to remove the s
Rightio. Going from their example code I think the OP actually wants to pass s as a parameter rather than calling raw_input inside the function. Also, your code will crash if the sentence ends with a space, since s[i+1] will raise an IndexError. But I guess that won't happen on the restricted input data they're using...
@PM2Ring, yep, I presumed the input is going to be in a particular format, you could catch all non alpha and trailing or multiple spaces, I might add a function that does that.
I realise that teachers create these artificial restrictions in order to create learning exercises, but gee they can lead to ugly non-Pythonic code. Doing stuff like this should be classed as cruel & unusual punishment. :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.