Home > Back-end >  Creating string based on first letters of each element of the list
Creating string based on first letters of each element of the list

Time:11-14

Example:

list = [abcc, typpaw, gfssdwww]
expected result = atgbyfcpscpsadwwww

Any ideas?

This is what i made so far:

def lazy_scribe(sources: list):
    result: str = ''
    i = 0
    while i < len(max(sources, key=len)):
        for source in sources:
            for char in source:
                if i <= len(source):
                    result = result   source[int(i)]
                else:
                    continue
                i  = 1 / (len(sources))
                break
    return result


sources = ["python", "java", "golang"]
print(lazy_scribe(sources))
print(len(sources))

result: "pjgyaoyvlhaaononngn". I dont know why there is "y" instead of t (7 char in result string)

CodePudding user response:

Another possible solution is as follows:

l = ['abcc', 'typpaw', 'gfssdwww']
max_len = len(max(l, key=len))
padded_l = list(zip(*[e   " " * (max_len - len(e)) for e in l]))
''.join([''.join(e) for e in padded_l]).replace(' ', '')
  1. find the longest string in the list
  2. then pad all the strings in the list with blank space
  3. use zip on the result list
  4. join the elements and replace the blank space to get the desired result

CodePudding user response:

If I understand the problem correctly, this should work.

list = ["abcc", "typpaw", "gfssdwww"]

max_len = len(max(list, key=len))

res = ""
char_iterator = 0

while char_iterator < max_len:
    for word in list:
        if char_iterator < len(word):
            res  = word[char_iterator]
    char_iterator  = 1

print(res)

  • Related