would anyone help me to solve this? I have this code, they need the calculations to sort from the largest to the largest (first numbers) and then to eliminate duplications i know i should use .sort () but I'm clueless who I do
for these results
5=1=1
5=1=1
1=1=5
1=5=1
1=1=5
1=5=1
4=2=1
4=1=2
2=1=4
2=4=1
1=2=4
1=4=2
3=3=1
3=1=3
3=1=3
3=3=1
1=3=3
1=3=3
3=2=2
3=2=2
2=2=3
2=3=2
2=2=3
2=3=2
output inline thos I want this to do
1=1=5
1=2=4
1=3=3
1=4=2
1=5=1
2=1=4
2=2=3
2=3=2
2=4=1
3=1=3
3=2=2
3=3=1
4=1=2
4=2=1
5=1=1
code
def part(n, k):
def _part(n, k, pre):
if n <= 0:
return []
if k == 1:
if n <= pre:
return [[n]]
return []
ret = []
for i in range(min(pre, n), 0, -1):
ret = [[i] sub for sub in _part(n-i, k-1, i)]
return ret
return _part(n, k, n)
x = part(7,3)
for i in x:
print(str(i[0]) '=' str(i[1]) '=' str(i[2]))
print(str(i[0]) '=' str(i[2]) '=' str(i[1]))
print(str(i[1]) '=' str(i[2]) '=' str(i[0]))
print(str(i[1]) '=' str(i[0]) '=' str(i[2]))
print(str(i[2]) '=' str(i[1]) '=' str(i[0]))
print(str(i[2]) '=' str(i[0]) '=' str(i[1]))
CodePudding user response:
The standard list sorting will work on this.
To remove dupes, convert to set and back to list.
EDIT
So, slight editing of your last for loop. For readability I advise to use a so-called f-string.
I misunderstood your question due to the original code formatting, but this short example should work on the result of your function...
lst = []
for elem in x:
lst.append(f"{elem[0]}={elem[1]}={elem[2]}")
lst.append(f"{elem[0]}={elem[2]}={elem[1]}")
lst.append(f"{elem[1]}={elem[0]}={elem[2]}")
lst.append(f"{elem[1]}={elem[2]}={elem[0]}")
lst.append(f"{elem[2]}={elem[0]}={elem[1]}")
lst.append(f"{elem[2]}={elem[1]}={elem[0]}")
lst = sorted(list(set(lst)))
for elem in lst:
print(elem)
output
1=1=5
1=2=4
1=3=3
1=4=2
1=5=1
2=1=4
2=2=3
2=3=2
2=4=1
3=1=3
3=2=2
3=3=1
4=1=2
4=2=1
5=1=1
CodePudding user response:
You can use a set
set_data_str = """5=1=1
5=1=1
1=1=5
1=5=1
1=1=5
1=5=1
4=2=1
4=1=2
2=1=4
2=4=1
1=2=4
1=4=2
3=3=1
3=1=3
3=1=3
3=3=1
1=3=3
1=3=3
3=2=2
3=2=2
2=2=3
2=3=2
2=2=3
2=3=2"""
# break the string into a list on the new lines
# create a set from the list
set_data = set(set_data_str.split('\n'))
# sort the set into a list
sorted_set_data = sorted(set_data)
# convert the sorted list into a string to print it
print('\n'.join(sorted_set_data))
Credit to @Edo-Akse for better formatting