Last active
May 19, 2017 02:57
-
-
Save tmessinis/ab84369f829720bcd2a128ab805a3e39 to your computer and use it in GitHub Desktop.
Write a program to compact spaces in a string i.e. Given a string you have to remove multiple occurrences of blank spaces by a single space and do that in a single pass of the arrays.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def compact_spaces(a_string): | |
space_check = [] | |
return_string = '' | |
for char in a_string: | |
if char == ' ' and char not in space_check: | |
space_check.append(char) | |
return_string += char | |
elif char == ' ': | |
continue | |
elif char != ' ' and space_check != []: | |
space_check.pop() | |
return_string += char | |
else: | |
return_string += char | |
return return_string | |
def compact_spaces_belmin(a_string): | |
space_added = False | |
return_string = '' | |
for char in a_string: | |
if char != ' ': | |
return_string += char | |
space_added = False | |
elif not space_added: | |
return_string += char | |
space_added = True | |
return return_string | |
print(compact_spaces('This is a test')) | |
print(compact_spaces_belmin('This is a test')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment