
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to convert a string to zigzag string of line count k in python
Suppose we have a string s and another value k, We have to find a new string by taking each character from s and starting diagonally from top left to bottom right until reaching the kth line, then go up to top right, and so on.
So, if the input is like s = "ilovepythonprogramming" k = 5, then the output will be
To solve this, we will follow these steps:
- line := a new map
- cnt := 0
- delta := 1
- for each index i and character c in s, do
- insert (c, i) at the end of line[cnt]
- cnt := cnt + delta
- if cnt is same as k, then
- delta := -1
- cnt := k - 2
- if cnt is same as 0, then
- delta := 1
- ans := a new list
- for each key i and value c in line, do
- prefix := a list of size same as s and fill that with single blank spaces
- for each pair (x, y) in c, do
- prefix[y] := x
- join each element present in prefix and insert it into ans
- return a new string by adding a new line between each consecutive elements in ans
Let us see the following implementation to get better understanding:
Example
from collections import defaultdict class Solution: def solve(self, s, k): line = defaultdict(list) cnt = 0 delta = 1 for i, c in enumerate(s): line[cnt].append((c, i)) cnt += delta if cnt == k: delta = -1 cnt = k - 2 if cnt == 0: delta = 1 ans = [] for i, c in line.items(): prefix = [" "] * (len(s)) for x, y in c: prefix[y] = x ans.append("".join(prefix)) return "\n".join(ans) ob = Solution() s = "ilovepythonprogramming" k = 5 print(ob.solve(s, k))
Input
"ilovepythonprogramming", 5
Output
- Related Articles
- Python Program – Convert String to matrix having K characters per row
- Convert a list to string in Python program
- Python program to convert list of string to comma separated string
- Python program to convert a list to string
- Python program to Count words in a given string?
- Python program to count occurrences of a word in a string
- Python Program to Convert Matrix to String
- Python Program to Count Number of Lowercase Characters in a String
- Python program to convert a string into uppercase
- Python program to convert a string into lowercase
- Write a python program to count occurrences of a word in string?
- Python program to count number of substring present in string
- Python program to count the number of spaces in string
- Python program to remove K length words in String
- Python program to convert hex string to decimal

Advertisements