
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Move Spaces to Front of String in Single Traversal
Given a string that has set of words and spaces, our task is to move all spaces to front of string, by traversing the string only once. We will solve this problem quickly in Python using List Comprehension.
Example
Input: string = "python program" Output: string= “ pythonprogram"
Algorithm
Step1: input a string with word and space. Step2: Traverse the input string and using list comprehension create a string without any space. Step 3: Then calculate a number of spaces. Step 4: Next create a final string with spaces. Step 5: Then concatenate string having no spaces. Step 6: Display string.
Example Code
# Function to move spaces to front of string # in single traversal in Python def frontstringmove(str): noSp = [i for i in str if i!=' '] space= len(str) - len(noSp) result = ' '*space result = '"'+result + ''.join(noSp)+'" print ("Final Result ::>",result) # Driver program if __name__ == "__main__": str = input("Enter String") frontstringmove(str)
Output
Enter String python program Final Result ::>" pythonprogram"
Advertisements