DEV Community

Abdulla Ansari
Abdulla Ansari

Posted on • Updated on

Solution Convert List of String to Pair of String using Python. Example ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']

Hi folks programmers,
Today we are going to solve a problem of how to convert a list of string to pair of strings

Input
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']

Expected Output
A
AB, AC, AD, AE, AF, AG, AH, AI
ABC, ABD, ABE, ABF, ABG, ABH, ABI
ABCD, ABCE, ABCF, ABCG, ABCH, ABCI
ABCDE, ABCDF, ABCDG, ABCDH, ABCDI
ABCDEF, ABCDEG, ABCDEH, ABCDEI
ABCDEFG, ABCDEFH, ABCDEFI
ABCDEFGH, ABCDEFGI
ABCDEFGHI

So here now we will start our coding in python programming.
We have to use nested for loops because we need to iterate over a single list.

For now I am not going to measure any kind of run time or space complexities. So let's get started

mylst = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']

current_val = ""
count = 0

for i in range(len(mylst)):
  if i == 0:
    print(mylst[i])
  current_val = current_val + mylst[count]
  count += 1
  for j in mylst[i+1:]:
    if current_val == j:
      print(j)
    else:
      if mylst.index(j) == len(mylst) - 1:
        print(current_val + j, end=' ')
      else:
        print(current_val + j, end=', ')
  print('')
Enter fullscreen mode Exit fullscreen mode

I hope you would love this solution of the program and will surely give me a like.

Thanks for your valuable time.

If you really liked our content you can buy a cup of coffee.
Buy me Coffee

My other Blog Website over Technology

My YouTube Vlog Channel

Top comments (0)