Word problem:
Spies must take care that the information conveyed in a text message does not fall into the wrong hands. A text acknowledgement is validated by the number of smiley faces it contains - in other words, the number of times it contains the string
":)"
. The proper reply to each text should contain exactly one more smiley face than the received text, and no other information. The reply will consist of only the correct number of instances of the string":)"
, separated by single white spaces (and with no leading or trailing spaces). Create a function to formulate and return the reply.Example Input and Output:
In:
"hey important info to follow :)"
Out:":) :)"
In:
"have u made contact?"
Out:":)"
I was able to solve the word problem with a print statement, but the problem is, I need to turn it into a function using return
. I used end= " "
to make it print on the same line but you can't return that.
def reply(s: str) -> str:
for i in range(s.count(':)') 1):
return ":)"
print(reply("hey important info to follow :)"))
CodePudding user response:
You can solve this by multiplying the return string by s.count(':)') 1
def reply(s: str) -> str:
return ":) " * (s.count(':)') 1)
print(reply("hey important info to follow :)"))
Outbut:
:) :)
CodePudding user response:
The problem with your solution is that when you use return the function stops running so it will never return more than one ':)'.
This solution works for me:
def reply(s):
total_smiles = s.count(':)')
output = ':) ' * (total_smiles 1)
# remove whitespace at the end and return
return output[:-1]
message = "hey important info to follow :)"
response = reply(message)
print(response)
CodePudding user response:
def reply(s: str) -> str:
for i in range(s.count(':)') 1):
return ":)"
return "exits the function or ends it"
You'll have to count then return, or, in other words, take your return out of the loop.
First I used a for loop like you did, then I used a generator statement because it adds readability to the code.
def reply(s):
words = s.split()
count = 1
for word in words:
if ":)" in word or "(:" in word:
count = 1
# or use generator
count = sum(1 for word in words if ":)" in word) 1
return " ".join(":)" for _ in range(count))
print(reply("hey important info to follow :)"))
# >> :) :)