Home > Blockchain >  Remove dulpicates from a string
Remove dulpicates from a string

Time:05-02

I wrote this code which consists of an input of two words and outputs the letters in the second word which are in the exact position as the first word in uppercase and the characters in the first and second word but not in the exact position as the first in lowercase.The code works for two of my test cases but fails on the third when i input duplicate letters as the second word.

If i input zabbz and cbbxb it outputs .bB.b but there are only 2 b's in the first word,the output should be '.bB..' .Please assist if you can. Here is my code:

sec=list(input().upper())
guess=list(input().upper())
output=['.']*len(guess)
letters=''
for i in range(len(guess)-1,-1,-1):
       if guess[i]==sec[i]:
              output[i]=guess[i]
              sec[i]=guess[i]=0
for i in range (len(guess)):
       if guess[i] in sec and guess[i]!=0:
              output[i]=guess[i].lower()
for letter in output:
       letters=letters letter
print(letters)

CodePudding user response:

To remove duplicates I use something like this:

start_array = []
final_array = []
for i in start_array:
   if start_array[i] in final_array:
      #DO nothing its a duplicate and continue
      continue
   else:
      final_array.append(start_array[i])

This checks each entry in the array and checks if that entry is in the final array and if it is it continues. Otherwise, it will append. This is assuming you changed all cases to upper().

CodePudding user response:

Using list.count(item) method will allow u to verify that there are the same amount of letters in your output list as in your sec list and not more. Here is an example :

       if guess[i] in sec and sec.count(guess[i]) > output.count(guess[i]) output.count(guess[i].upper()):
          output[i] = guess[i].lower()

here is an example that i made real quick if you want to test it :

sec = list(input().upper())
guess = list(input().upper())
output = ["." for i in range(len(guess))]

for i in range(len(guess)):

       if guess[i] == sec[i]:
              output[i] = guess[i]

       elif guess[i] in sec and sec.count(guess[i]) > output.count(guess[i]) output.count(guess[i].upper()):
              output[i] = guess[i].lower()

output = "".join(output)

print(output)

also i noticed you were doing some string concatenation for the final result but if you want a simpler way to create a string from a list there is the "".join(list) method that allows you to join all elements in the list seperated by the str specified(in that case, seperated by nothing)

  • Related