0
symbols coad coach
import string import re text = input() alphanumeric_chars = string.ascii_letters + string.digits for letters in text: if letters not in alphanumeric_chars: found_chars += letters for char in found_chars: text = text.replace(char, "") new_text = "" found_number = False #flag to track for i in range(len(text)): if i > 0 and (text[i].isupper() or (not found_number and text[i].isdigit())): new_text += " " + text[i] if text[i].isdigit(): found_number = True else: new_text += text[i] print(new_text) # Output: hello World 123 It works on all but test case 3 and 4. Can anyone help me with this
4 Réponses
+ 4
✳️ you have to define found_chars first before using it in the for loop. You also don't need the bottom part of your code if you just include string.whitespace in alphanumeric_chars.
import string
text = input()
alphanumeric_chars = string.ascii_letters + string.digits + string.whitespace
found_chars = ""
for letters in text:
if letters not in alphanumeric_chars:
found_chars += letters
for char in found_chars:
text = text.replace(char, "")
print(text)
✳️ But your solution is still too complicated. You can simplify it to:
import string
text = input()
valid_chars = string.ascii_letters + string.digits + string.whitespace
result = ""
for letter in text:
if letter in valid_chars:
result += letter
print(result)
✳️ Or use isalnum() and isspace() to build your string. Then you don't have to import any module at all.
text = input()
result = ""
for letter in text:
if letter.isalnum() or letter.isspace():
result += letter
print(result)
+ 1
Your code concatenates the words if the first letter is not capitalized. Also, you are making the assumption that the first letter of the words are capitalized based on the first two cases. That is wrong. Nothing in the problem description guarantees that. Look at the example input in the description.
Sample Input:
#l$e%ts go @an#d@@ g***et #l#unch$$
Sample Output:
lets go and get lunch
found_chars in your code does not collect the whitespace between words. When you reassemble the words , you wouldn't be able separate the words properly if they are all lowercase.
So you should also collect the whitespaces. Then you don't have to use the complicated method you're currently using.
0
Ok I did the last one and it worked.
But why wouldn't my solution work for 3 and 4?
0
And also, if the the words themselves would have spaces, my solution would have been better