0

Separating different elements in list

I'm trying to separate same elements from list and make individual list which contains same elements. I guess you will understand after running this program https://code.sololearn.com/cX0ZeMVDbz5m/?ref=app

2nd Mar 2021, 7:46 PM
🌀 Shail Murtaza شعیل مرتضیٰ
🌀 Shail Murtaza شعیل مرتضیٰ - avatar
6 Respostas
+ 3
Because the condition if prev!=i doesn't become true, because there is no different element after 6 The last group will always be missing in final, so just append it from ls2 after the loop
2nd Mar 2021, 8:14 PM
Benjamin Jürgens
Benjamin Jürgens - avatar
+ 3
Your code only works, if the elements are already grouped, for [1, 2, 1] it would give [[1], [2], [1]] I don't know if that's intentional or not. If not and the output should be [[1, 1], [2]], here are two short solutions; print([[val] * ls1.count(val) for val in sorted(set(ls1))]) from collections import Counter print([[val] * freq for val, freq in Counter(ls1).items()]) The one with Counter has better performance
2nd Mar 2021, 8:19 PM
Benjamin Jürgens
Benjamin Jürgens - avatar
+ 2
def getPairs(arr, n): ls = [] for i in range(0, n): for j in range(i + 1, n): if arr[i] == arr[j]: ls.append([arr[i],arr[j]]) return ls # Driver function arr = [1, 1, 9, 2, 2, 8, 3, 3, 4, 4, 5, 6, 6] n = len(arr) print(getPairs(arr, n))
2nd Mar 2021, 8:48 PM
iTech
iTech - avatar
+ 1
Shail Murtaza great! And remember that python "comes with batteries included", meaning that for all standard tasks it most likely offers a solution or at least functions that help you a lot. Use them to not only make your code shorter, but also more readable
2nd Mar 2021, 11:30 PM
Benjamin Jürgens
Benjamin Jürgens - avatar
0
Thank you very much You saved my time I was unable to figure out that simple thing.
2nd Mar 2021, 8:36 PM
🌀 Shail Murtaza شعیل مرتضیٰ
🌀 Shail Murtaza شعیل مرتضیٰ - avatar
0
iTech your code tries to solve something different, and it has a problem when an element occurs more than 2 times. Also you don't need to give n to the function
2nd Mar 2021, 11:42 PM
Benjamin Jürgens
Benjamin Jürgens - avatar