replaced items problem | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

replaced items problem

why when i try to replace the count item bigger than 1 just two items replaced and the last item not replaced.. thanks a = ['one' , 'one' , 'one' , 'two' , 'three'] i = 0 sec = [] for x in range(len(a)): if a.count(a[x]) > 1: a[x] = 'replaced' i = i + 1 print(a) ## out put : # ['replaced', 'replaced', 'one', 'two', 'three']

24th Mar 2018, 11:26 AM
Mohamed Rashidey Hasan
Mohamed Rashidey Hasan - avatar
4 Answers
+ 2
The issue with your code is this: First time the program goes through the loop, the count for 'one' is 3 and so it replaces the first occurrence of 'one' by 'replaced'. The second time the count for 'one' is 2 and it replaces that one once again. By the time it gets to the 3rd 'one' the count for 'one' is now 1 and thus nothing is replaced. Take a look at the answer marked as best in the thread in the link bellow. I think it will help soleve the issue... They used enumerate. It might be an opportunity to learn something new as well. ;) https://stackoverflow.com/questions/2582138/finding-and-replacing-elements-in-a-list-JUMP_LINK__&&__python__&&__JUMP_LINK
24th Mar 2018, 12:06 PM
cyk
cyk - avatar
+ 2
Alternatively, you can turn the list into a String and take advantage of Strings replace method... This might be slower though depending on the time complexity of those methods https://code.sololearn.com/czVR0A98zb5t/?ref=app
24th Mar 2018, 12:32 PM
cyk
cyk - avatar
+ 1
I assume desired output is replaced on every number that has already occured. maybe this helps:: if x in dupl variable: replace elif x in a: replace add x to found dupl variable
24th Mar 2018, 12:22 PM
Markus Kaleton
Markus Kaleton - avatar
+ 1
لان عدد مرات ظهور عنصر ال( x) المطلوب بالنسبه للشرط الموضوع هو مرتين لكن لو a[x] >=1 هيستبدل ٣ مرات وكذلك باقي العناصر وال i ليس لها افاده وكذلك ال sec
26th Mar 2018, 1:17 PM
moamen
moamen - avatar