Hello, a site says that the characters in the list should be printed in alphabetical order if the length is the same from the short one.
N=int(input())
N_list=['i', 'im', 'it', 'no', 'but', 'more', 'wont', 'wait', 'yours', 'cannot', 'hesitate']
N_list=list(set(N_list))
N_list.sort(key=len)
for i in N_list:
answer=''.join(i)
print(answer)
answer=''
I squeezed it like coding above, but the other one didn't seem to be abnormal
The word "wait" should come first. The word "wont" should come first.
In other words, I im it no but more wait your can't heate is the answer
"Won" comes first, followed by "wait"
Please advise me how to solve it.
A sort is sorted alphabetically.
You can do it one more time.
N_list=['i', 'im', 'it', 'no', 'but', 'more', 'wont', 'wait', 'yours', 'cannot', 'hesitate']
N_list.sort()
N_list.sort(key=lambda i:len(i))
N_list
['i',
'im',
'it',
'no',
'but',
'more',
'wait',
'wont',
'yours',
'cannot',
'hesitate']
def cmpFunc(x, y):
if len(x)==len(y):
if min(x,y)==x:
return -1
else:
return 1
return len(x) - len(y)
N_list=['i', 'im', 'it', 'no', 'but', 'more', 'wont', 'wait', 'yours', 'cannot', 'hesitate']
N_list=list(set(N_list))
N_list.sort(cmp=cmpFunc)
for i in N_list:
answer=''.join(i)
print(answer)
answer=''
Use cmp as the sort factor to determine the order by comparing the length in the same alphabetical order, and the difference in the length in the length in the same order.
I think there's a cleaner way, but unfortunately, I can't think of one.
Thank you.
© 2024 OneMinuteCode. All rights reserved.