Python Forum
phrase loop and character comparision
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
phrase loop and character comparision
#1
Hi

I have started few days ago, thus I am pretty new to the language.
This is my first post and I hope that this forum and the users' experience will help me to step up my understanding!
Thank yo uvery much in advance.

I am trying to write the code for the following instructions:

1- input a phrase such as: "My pet is a tiger; wild, white and with big eyes."
2- output the following list of words (all words for which the first letter is 'below' the letter "n"):
MY
IS
A
AND
BIG
EYES
3- I tried to follow the following instructions but so far I can only manage to write the code I have put at the bottom of my post:
Split the words using a variable MYVARIABLE
loop each character in the input string
check if character is a letter
add a letter to MYVARIABLE each loop until a non-alpha char is met

if character is alpha
add character to MYVARIABLE
non-alpha detected (space, punctuation, digit,...) defines the end of a word and goes to else
else
check if MYVARIABLE is smaller than "N" alphabetically
print MYVARIABLE
set MYVARIABLE = empty string
or else
set MYVARIABLE = empty string and build the next word


userinput = "My pet is a Tiger; wild, white and with big eyes."
userinput = userinput.lower()
start = 0
location = userinput.find(" ")
MYVARIABLE = ""
loop = 0

while location >= 0:
    for xyz in userinput[start:location]:
        if xyz.isalpha():
            MYVARIABLE = MYVARIABLE + xyz
        else:
            print(MYVARIABLE)
            pass
    letterx = MYVARIABLE[0]

    if letterx < "n":
        print(MYVARIABLE)
        MYVARIABLE = ""
    else:
        MYVARIABLE = ""
    
    loop += 1
    start = location
    location = userinput.find(" ",location+1)  
I know that I can use the split function but I would like to go with the above way to understand the logic.

When running the above I have an error at the "letterx".
Could seombody please explain me how to check the first letter and or how to write the code in a cleaner way?

Thank you.
Shiro
Reply
#2
Please, always post the entire traceback that you get, in error tags. We need to see the whole thing.
Take a time to read What to include in a post

I guess the problem is that word is not defined. Right? So, what you want variable word to be?

(Jun-25-2018, 05:59 AM)shiro26 Wrote: Could seombody please explain me how to check the first letter and or how to write the code in a cleaner way?

Use split for start? Then loop over the list of words that you get. convert word to lower case and use ord() builtin function to check that ascii code of word[0] is lower than ascii code of the control char e.g. ord(word[0]) < ord('n')
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
(Jun-25-2018, 06:09 AM)buran Wrote: Please, always post the entire traceback that you get, in error tags. We need to see the whole thing.
Take a time to read What to include in a post

I guess the problem is that word is not defined. Right? So, what you want variable word to be?

(Jun-25-2018, 05:59 AM)shiro26 Wrote: Could seombody please explain me how to check the first letter and or how to write the code in a cleaner way?

Use split for start? Then loop over the list of words that you get. convert word to lower case and use ord() builtin function to check that ascii code of word[0] is lower than ascii code of the control char e.g. ord(word[0]) < ord('n')

Hi buran,
Thank you for your reply.
I have indeed forgotten to define 'word'.

I have come up with the following:

userinput = "My pet is a tiger; wild, white and with big eyes."
userinput = userinput.lower()
start = 0
location = userinput.find(" ")
MYVARIABLE = ""
letterx = ""

while location >= 0:
    for xyz in userinput[start:location]:
        if xyz.isalpha():
            MYVARIABLE = MYVARIABLE + xyz
        else:
            print(MYVARIABLE)
            MYVARIABLE = ""
        
        letterx = MYVARIABLE[0]
        
        if letterx < "n":
            print(MYVARIABLE)
            MYVARIABLE = ""
        else:
            MYVARIABLE = ""
    
    start = location
    location = userinput.find(" ",location+1)
I have set up at the begining already the .lower() ; should I repeat it somewhere elese as well?
With the above I get the following message:

---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-147-827269f96974> in <module>()
21 MYVARIABLE = ""
22
---> 23 letterx = MYVARIABLE[0]
24 if letterx < "n":
25 print(MYVARIABLE)

IndexError: string index out of range

I hope that I have clarified the missing points you have highlighted.
Thank you,
Shiro

(Jun-25-2018, 06:09 AM)buran Wrote: Please, always post the entire traceback that you get, in error tags. We need to see the whole thing.
Take a time to read What to include in a post

I guess the problem is that word is not defined. Right? So, what you want variable word to be?

(Jun-25-2018, 05:59 AM)shiro26 Wrote: Could seombody please explain me how to check the first letter and or how to write the code in a cleaner way?

Use split for start? Then loop over the list of words that you get. convert word to lower case and use ord() builtin function to check that ascii code of word[0] is lower than ascii code of the control char e.g. ord(word[0]) < ord('n')


Dear buran,

I think I managed to go through it with the following:
userinput = "My pet is a tiger; wild, white and with big eyes."
userinput = userinput.lower()
start = 0
location = userinput.find(" ")
MYVARIABLE = ""

while location >= 0:
    for xyz in userinput[start:location]:
        if xyz.isalpha():
            MYVARIABLE = MYVARIABLE + xyz
        else:
            pass
        
    if MYVARIABLE[0] < "n":
        print(MYVARIABLE)
        MYVARIABLE = ""
    else:
        MYVARIABLE = ""
    
    start = location
    location = userinput.find(" ",location+1)
Could you please tell me if there is a more elegant way than the below and the above?
anotherinput = "My pet is a tiger; wild, white and with big eyes."
firstletter = ""
wordx = ""
for abc in anotherinput.split():
    if abc.isalpha():
        wordx = abc.lower()
        firstletter = wordx[0]
#        print(firstletter)
        if wordx[0] < "n":
            print(wordx)
        else:
            pass        
    else:
        pass   
Thank you very much in advance.
Shiro
Reply
#4
def find_words(phrase, control):
    phrase = phrase.lower().split()
    return [word for word in phrase if word[0] < control]
    
print(find_words("My pet is a Tiger; wild, white and with big eyes.", 'n'))
Output:
['my', 'is', 'a', 'and', 'big', 'eyes.']
in your code you don't need the else part, because you just pass there

below is your code, cleaned from redundant parts
anotherinput = "My pet is a tiger; wild, white and with big eyes."
for word in anotherinput.split():
    if word.isalpha():
        word = word.lower()
        if word[0] < "n":
            print(word)
Output:
my is a and big >>>
Note that it doesn't print eyes., because it has dot and isalpha() returns False
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
Dear Buran,
Thank you very much for your response as well as your solutions.
This is very clear. I am happy to read your function because I have difficulties to build them and use the "return" properly.

How can I get rid of the dot in both your function base solution and in the clean code based on my attempt?

Thank you so much.

Shiro
Reply
#6
from string import punctuation

def find_words(phrase, control):
    phrase = phrase.lower().split()
    words = [word.rstrip(punctuation) for word in phrase if word[0] < control]
    return words
    
my_phrase = "My pet is a Tiger; wild, white and with big eyes. Don't touch him."
     
print(find_words(phrase=my_phrase, control='n'))
['my', 'is', 'a', 'and', 'big', 'eyes', "don't", 'him']
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#7
(Jun-25-2018, 07:59 AM)buran Wrote:
from string import punctuation

def find_words(phrase, control):
    phrase = phrase.lower().split()
    words = [word.rstrip(punctuation) for word in phrase if word[0] < control]
    return words
    
my_phrase = "My pet is a Tiger; wild, white and with big eyes. Don't touch him."
     
print(find_words(phrase=my_phrase, control='n'))
['my', 'is', 'a', 'and', 'big', 'eyes', "don't", 'him']

Sorry for my late reply.
Thank you very much buran.
I understand from your quote that we can import the a punctuation package.
I am not familiar yet with 'rstrip' (just 'strip') so I will check it out.
Thank you again.
Shiro
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  comparision of texts in a file saisankalpj 1 781 Dec-22-2022, 03:11 PM
Last Post: Larz60+
  [solved] unexpected character after line continuation character paul18fr 4 3,387 Jun-22-2021, 03:22 PM
Last Post: deanhystad
  SyntaxError: unexpected character after line continuation character siteshkumar 2 3,157 Jul-13-2020, 07:05 PM
Last Post: snippsat
  loop only prints last character. mcmxl22 1 1,705 Feb-17-2020, 02:36 AM
Last Post: menator01
  how can i handle "expected a character " type error , when I input no character vivekagrey 2 2,731 Jan-05-2020, 11:50 AM
Last Post: vivekagrey
  Reverse order of phrase Error ilondire05 4 2,495 Aug-29-2019, 04:19 PM
Last Post: buran
  length constraint on phrase hash to password javaben 0 1,906 Aug-21-2019, 05:34 PM
Last Post: javaben
  Replace changing string including uppercase character with lowercase character silfer 11 6,166 Mar-25-2019, 12:54 PM
Last Post: silfer
  Finding exact phrase in list graham23s 2 2,886 Mar-13-2019, 06:47 PM
Last Post: graham23s
  Probelm using Boolean input phrase.isupper() skrivver99 4 3,099 Nov-04-2018, 09:21 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020