본문 바로가기
python-algorithm

leetcode 2164. Sort Even and Odd Indices Independently

by 무적김두칠 2023. 3. 3.

https://leetcode.com/problems/sort-even-and-odd-indices-independently/description/

 

Sort Even and Odd Indices Independently - LeetCode

Can you solve this real interview question? Sort Even and Odd Indices Independently - You are given a 0-indexed integer array nums. Rearrange the values of nums according to the following rules: 1. Sort the values at odd indices of nums in non-increasing o

leetcode.com

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import itertools as it
class Solution:
    def sortEvenOdd(self, nums: List[int]) -> List[int]:
        odds,evens = [], []
        for i in range(len(nums)):
            if i%2 == 0:
                evens.append(nums[i])
            else:
                odds.append(nums[i])
 
        odds.sort(reverse = True)
        evens.sort()
         
        answer = list(it.chain(*zip(evens, odds)))
        if len(odds) < len(evens):
            answer.append(evens[-1])
        elif len(odds) > len(evens):
            answer.append(odds[-1])
 
        return answer
cs

list를 교차로 합치고 싶을때 itertools의 chain 함수를 사용하시면됩니당
Line 15-18의 조건문은 홀수 인덱스와 짝수 인덱스 개수가 다를때는 더 개수가 많은쪽의 마지막 값이 합쳐지지 않아서 따로 예외처리한 부분입니다.

When you want to cross-join a list, you can use itertools' chain function.
The conditional statement in Lines 15-18 is
an exception handling part because when the number of odd indexes and even indexes are different, the last value of the larger number is not combined.

 

참고 링크:
https://docs.python.org/3/library/itertools.html#itertools.chain

 

itertools — Functions creating iterators for efficient looping

This module implements a number of iterator building blocks inspired by constructs from APL, Haskell, and SML. Each has been recast in a form suitable for Python. The module standardizes a core set...

docs.python.org

 

반응형

댓글