Home > Net >  append to a list based on occurrence in Python
append to a list based on occurrence in Python

Time:03-08

My Python func takes each element in a list and compares to the ORIGINAL, if the letter of an element is IN ORIGINAL, convert the corresponding letter with dash. Here is the catch, if the ORIGINAL has two repeat letters, the element has the same letter with three repeats, then replace only the first two letters with dash.

Example:

ORIGINAL = 'tyyyt'
element = 'yyttt'

result: element = '----t'

My tentative solution is to append to a seen list, if there is a repeat, append the 2nd time. How can I append the letter to a list based on occurrence? Below is my code, it is not working as expected. Thank you.

ORIGINAL = 'rssrs'
word_list = ['srrsr', 'rsrrr', 'sssrr', 'ssssr']
result, modified_list = [], []
for word in word_list:
    seen = []
    for i in range(len(word)):
        if word[i] in ORIGINAL and ORIGINAL.count(word[i]) == 1 and word[i] not in seen:            
            l = '-'
            seen.append(word[i])
        elif word[i] in ORIGINAL and ORIGINAL.count(word[i]) in (2,3):
            l = '-'
            seen.append(word[i])
        else:
            l = word[i]
        result.append(l)
    modified_list.append(''.join(result))
    result.clear()
print(modified_list)

Output:

['-----', '-----', '-----', '-----']

Desired Output:

['----r', '---rr', '-----', '---s-']

CodePudding user response:

As Sam Poirer says, it could be more straightforward, but you were nearly there with your solution. The following tweak produces the desired output.

ORIGINAL = 'rssrs'
word_list = ['srrsr', 'rsrrr', 'sssrr', 'ssssr']
result, modified_list = [], []
for word in word_list:
    seen = []
    for i in range(len(word)):
        if word[i] in ORIGINAL and ORIGINAL.count(word[i]) == 1 and word[i] not in seen:            
            l = '-'
            seen.append(word[i])
        elif (seen.count(word[i])   1) <= ORIGINAL.count(word[i]):
            l = '-'
            seen.append(word[i])
        else:
            l = word[i]
        result.append(l)
    modified_list.append(''.join(result))
    result.clear()
print(modified_list)

CodePudding user response:

You've got a good idea there, though it's more complicated than it needs to be. A simpler method would be to simply compare each word to a copy of the original, and if the letter is present, remove it. This means that a letter will never be removed too many times. For example:

def occurenceCheck(origin, other):
  newWord = ""
  replaceChar = "-"
  
  for char in other:
    if char in origin:
      newWord  = replaceChar
      origin = origin.replace(char, "", 1)
    else:
      newWord  = char

  return newWord
  
  
original = "rssrs"
wordList = ['srrsr', 'rsrrr', 'sssrr', 'ssssr']

for word in wordList:
  print(occurenceCheck(original, word))

Running this gives this for output:

----r
---rr
-----
---s-

  • Related