【每日一题1027】对对碰

:mage:t2: 请编写一个函数,接收一个正整数n,生成一个包含成对元素的列表,需要符合条件0<= x <= y <= n,并且保持升序排列。

示例:
输入:n,输出: [ [0, 0], [0, 1], [0, 2], [1, 1], [1, 2], [2, 2] ]

题目难度:简单
题目来源:codewars

def gen_pairs(n: int) -> list:
    pass

assert gen_pairs(2) == [[0, 0], [0, 1], [0, 2], [1, 1], [1, 2], [2, 2]]
assert gen_pairs(0) == [[0, 0]]
def gen_pairs(n: int) -> list:
    pairs_list = []
    for i in range(n + 1):
        for a in range(i, n + 1):
            pairs = [i, a]
            pairs_list.append(pairs)
    return pairs_list

1 Like
def gen_pairs(n: int) -> list:
    returnList = []
    for i in range(0,n+1):
        for j in range(0,n+1):
            if 0<= i <= j <= n:
                tempList = [i,j]
                returnList.append(tempList)

    return returnList 

assert gen_pairs(2) == [[0, 0], [0, 1], [0, 2], [1, 1], [1, 2], [2, 2]]
assert gen_pairs(0) == [[0, 0]]
1 Like
def gen_pairs(n: int) -> list:
    rise_list = []
    for i in range(n+1):
        for j in range(n+1):
            if i <= j:
                rise_list.append([i, j])
    return rise_list


assert gen_pairs(2) == [[0, 0], [0, 1], [0, 2], [1, 1], [1, 2], [2, 2]]
assert gen_pairs(0) == [[0, 0]]
def gen_pairs(n: int) -> list:
    return [[i, j] for i in range(n + 1) for j in range(n + 1) if j >= i]


assert gen_pairs(2) == [[0, 0], [0, 1], [0, 2], [1, 1], [1, 2], [2, 2]]
assert gen_pairs(0) == [[0, 0]]
def gen_pairs(n: int) -> list:
    result = []
    for i in range(n+1):
        for j in range(i,n+1):
            result.append([i,j])
    return result

assert gen_pairs(2) == [[0, 0], [0, 1], [0, 2], [1, 1], [1, 2], [2, 2]]
assert gen_pairs(0) == [[0, 0]]
1 Like
return [[i, j] for i in range(n + 1) for j in range(i,n + 1) ]
也可以这样写 :grin:
1 Like
def like_sample_method(n):
    last_list=[]
    for i in range(0,n+1):
        for j in range(i,n+1):
            last_list.append([i,j])
    print(last_list)
def gen_pairs(n: int) -> list:
    result_list=[]
    for i in range(0,n+1):
        for j in range(i,n+1):
            list1=[i,j]
            result_list.append(list1)
    return result_list


assert gen_pairs(2) == [[0, 0], [0, 1], [0, 2], [1, 1], [1, 2], [2, 2]]
assert gen_pairs(0) == [[0, 0]]
public ArrayList<ArrayList<Integer>> genPairs(Integer integer){
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        for (int i = 0; i <= integer ; i++) {
            for (int j = i; j <=integer ; j++) {
                if (0<=i && i<=j && j<=integer){
                    ArrayList<Integer> arrayList = new ArrayList<>();
                    arrayList.add(i);
                    arrayList.add(j);
                    res.add(arrayList);
                }
            }
        }
        return res;
    }
关闭