Thursday, December 26, 2024
Google search engine
HomeLanguagesPython – Remove K length Duplicates from String

Python – Remove K length Duplicates from String

Given a String remove all K length duplicates.

Input : test_str = ‘Lazyroarforfreeksfo’, K = 3
Output : Lazyroarforfree
Explanation : eek, eks, ksf, sfo already in string, hence removed.

Input : test_str = ‘Lazyroarforg’, K = 3
Output : Lazyroarforg
Explanation : No repeated string, nothing removed.

Method : Using loop + slicing

In this, we keep track of all the K length substrs encountered, extracted using slicing, and check each time for recurrence, if occurred they are removed.

Python3




# Python3 code to demonstrate working of 
# Remove K length Duplicates from String
# Using loop + slicing 
  
# initializing strings
test_str = 'Lazyroarforfreeksfo'
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing K 
K = 3
  
memo = set()
res = []
for idx in range(0, len(test_str) - K):
      
    # slicing K length substrings
    sub = test_str[idx : idx + K]
      
    # checking for presence
    if sub not in memo:
        memo.add(sub)
        res.append(sub)
          
res = ''.join(res[ele] for ele in range(0, len(res), K))
  
# printing result 
print("The modified string : " + str(res)) 


Output

The original string is : Lazyroarforfreeksfo
The modified string : Lazyroarforfree
Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments