Python PacMan is a video game character who normally eats do

Python

Pac-Man is a video game character who normally eats dots, power pellets, and the occasional ghost. Recently, he’s fallen on hard times and has been reduced to (mainly) eating letters of the alphabet. Pac-Man can eat most letters of the alphabet, but he is unable to digest any of the characters in the word “GHOST” (uppercase or lowercase). When he reaches one of these characters in a string, he loses his appetite and stops eating.

Your job is to complete the pacman() function, which traces Pac-Man’s progress through a string of uppercase and lowercase letters (with no spaces, digits, or symbols) and prints out the final state of the string. Use under- scores ( ) to represent consumed characters and a less-than sign (<) to represent Pac-Man’s final position (either at the very beginning or end of the string, or right before the character that stopped him). Finally, your output should include any uneaten part of the string.

For example, consider the string “cat”. Pac-Man can eat the “c” and the “a”, but stops when he reaches “t” (because it is one of the letters in “GHOST”). Thus, the final string will be “ <t”.

Hint #1: Use two while loops to solve this problem: one for the characters before Pac-Man stops, and one for any letters that remain in the input after he stops eating.

Hint #2: If Pac-Man stops eating in the middle of the input, you will need to print him instead of the last character that he successfully consumed. Depending on how you approach this problem, you may find that string slicing is helpful to remove the final character of a string. To slice a string, follow the string variable’s name with square brackets; inside the brackets, write the starting index, followed by a colon (‘:’), followed by the ending index. The slice will contain all of the characters from the starting index up to but not including the ending index. For example, \"helloworld\"[3:7] will return the string “lowo”. Here, your ending index should probably be something like length of string - 1.

Solution

Python code:

s = \"pacmancanbeawinner\"
eaten = \"\"
flag = False
for i in range(0,len(s)):
   if(s[i] == \"G\" or s[i] == \"H\" or s[i] == \"O\" or s[i] == \"S\" or s[i] == \"T\" or s[i] == \"g\" or s[i] == \"h\" or s[i] == \"o\" or s[i] == \"s\" or s[i] == \"t\"):
       print eaten + \"<\" + s[i:len(s)]
       flag = True
       break
   else:
       eaten = eaten + \"_\"
if(flag == False):
   print eaten+ \"<\"

Sample Output:

s = \"cat\"

Output: __<t

s = \"randomstring\"

Output: ____<omstring

s = pacmancanbeawinner

output: __________________<

Python Pac-Man is a video game character who normally eats dots, power pellets, and the occasional ghost. Recently, he’s fallen on hard times and has been reduc

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site