1

I'm quite new to python and programming in general and i'm currently doing an online course at Grok Online. Currently i am stuck on the second course (Robots in a line!) as the brief is to design a program that reads in a line of text and prints out whether the word robot appears, although it has to figure out whether the word is lowercase, uppercase or mixed case. This is my solution thus far:

text = input('Line: ')

if 'robot' in text:
  print('There is a small robot in the line.')

elif 'robot'.upper() in text:
  print('There is a big robot in the line.')

elif 'robot' or 'ROBOT' != text.isupper() and not text.islower():
  print('There is a medium sized robot in the line.')

else:
  print('No robots here.')

Another thing is that the program has to distinguish the word as an individual string, so it would print True for 'robot' but false for 'strobotron'.

Lesmana
  • 25,663
  • 9
  • 82
  • 87

5 Answers5

1

Your second elif statement should be

elif 'robot' in text.islower() and not ('ROBOT' in text or 'robot' in text):

if you want to do all that in one line.

For the second requirement, you could make use of regex word boundary anchors:

import re
if re.search(r"\brobot\b", text, flags=re.I):
    if re.search(r"\brobot\b", text):
        print('There is a small robot in the line.')
    elif re.search(r"\bROBOT\b", text):
        print('There is a big robot in the line.')
    else:
        print('There is a medium sized robot in the line.')
else:
    print('No robots here.')
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
1

I assumed that your input contain maximum of one robot string.

>>> def findrobot(text):
        if 'robot' in text:
            print('There is a small robot in the line.')
        elif 'robot'.upper() in text:
            print('There is a big robot in the line.')
        elif re.search(r'(?i)robot', text):
            if 'robot' not in text and 'ROBOT' not in text:
                print('MIxed cased robot found')
        else:
            print('No robots here.')


>>> text = input('Line: ')
Line: robot
>>> findrobot(text)
There is a small robot in the line.
>>> text = input('Line: ')
Line: ROBOT
>>> findrobot(text)
There is a big robot in the line.
>>> text = input('Line: ')
Line: RobOt
>>> findrobot(text)
MIxed cased robot found
>>> text = input('Line: ')
Line: foo
>>> findrobot(text)
No robots here.
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
1

This handles punctuation and also avoids matching strobotron:

text = input('Line: ')

text = text.replace('.,?;:"', ' ')
words = text.split()
lowers = text.lower().split()

if 'robot' in words:
  print('There is a small robot in the line.')
elif 'robot'.upper() in words:
  print('There is a big robot in the line.')
elif 'robot' in lowers:
  print('There is a medium sized robot in the line.')
else:
  print('No robots here.')
John1024
  • 109,961
  • 14
  • 137
  • 171
1

There are many ways to solve this problem. Regular expressions is one of the tools. Considering this is your second programming course I recommend against regular expressions. Instead I will try using more basic python tools and concepts.

First split the string at whitespace:

words = text.split()

This will split the string 'I am a robot' into a list of words: ['I', 'am', 'a', 'robot']. Note that this will not split punctuation. 'I am a robot.' will become ['I', 'am', 'a', 'robot.']. Note the dot at the end 'robot.'. For the rest of the answer I will pretend there are no punctuations, as this will complicate matters beyond the scope of a second programming course.

Now you can filter words for 'robot', regardless of case:

robots = []
for word in words:
  if word.lower() == 'robot':
    robots.append(word)

This loop can also be written like this:

robots = [word for word in words if word.lower() == 'robot']

That is called a list comprehension and is basically just a concise way to write a loop collecting certain items from a list into another list. If you have not learned list comprehension yet then just ignore this part.

Starting with the input 'I am a robot and you are a ROBOT and we are RoBoT but not strobotron' the list robots will be ['robot', 'ROBOT', 'RoBoT']. 'strobotron' is not in the list because it does not equal 'robot'. That solves the problem of finding 'robot' but not 'strobotron'.

If the robots list is empty then you know there are no robots at all. If it is not empty then you can check for small or large or medium robots.

if not robots:
  print('No robots here.')
elif 'robot' in robots:
  print('There is a small robot in the line.')
elif 'ROBOT' in robots:
  print('There is a big robot in the line.')
else:
  print('There is a medium sized robot in the line.')

The first condition (if not robots:) is using a mechanism of python called implicit booleanes. Almost anything can be used in an if condition like this and it will be implicitly transformed into a boolean value. In most cases if the thing is "empty" it will be regarded as false.

Note the order of the conditions in the if else chain. You have to check for an empty list first otherwise the else part will not work. The logic goes like this: if the list is not empty and there are no small or large robots in the list then any robots in the list must be medium.


There is an ambiguity in your problem description. What if there are both small and large (and medium) robots in the line. Should it report both? If both are in line the current code will only report a small robot. This is because it first checks for a small robot and then skips the rest (such is the semantic of elif).

To report both small and large (and medium) robots you can do it like this:

smallrobots = []
largerobots = []
mediumrobots = []
for robot in robots:
  if robot == 'robot':
    smallrobots.append(robot)
  elif robot == 'ROBOT':
    largerobots.append(robot)
  else:
    mediumrobots.append(robot)

if not robots:
  print('No robots here.')
if smallrobots:
  print('There is a small robot in the line.')
if largerobots:
  print('There is a big robot in the line.')
if mediumrobots:
  print('There is a medium sized robot in the line.')

Note that the elif is now only inside the loop. Using only if for reporting means it will not skip medium robots if small robots are found.

Bonus: you can now even differentiate whether there is one or more small robots in line:

if len(smallrobots) == 1:
  print('There is a small robot in the line.')
elif len(smallrobots) > 1:
  print('There are small robots in the line.')
Lesmana
  • 25,663
  • 9
  • 82
  • 87
0

Here is another approach using python collections

from collections import Counter

def get_words(text, line=""):
    lower_case, upper_case = text.lower(), text.upper()
    data = {'lower' : 0,'upper' : 0, 'mix' : 0}
    cnt = Counter()
    for word in line.split():
        cnt[word]+=1
    if cnt.has_key(lower_case):
        data['lower'] = cnt[lower_case]
        cnt.pop(lower_case)
    if cnt.has_key(upper_case):
        data['upper'] = cnt[upper_case]
        cnt.pop(upper_case)
    for x, y in cnt.iteritems():
        if x.lower()==lower_case:
            data['mix'] += y
    return data

it gives you count of text

get_words('robot', line="i am a robot with Robot who has a ROBOT")

Result :

{'lower': 1, 'mix': 1, 'upper': 1}
xrage
  • 4,690
  • 4
  • 25
  • 31