英文:
Python: Given a number return tuple from 0, a number given
问题
以下是要翻译的内容:
给定:num=4
期望:(0,1), (0,2), (0,3), (0,4), (1,2), (1,3), (1,4), (2,3), (2,4), (3,4)(以元组形式)
英文:
Hi I would like to knoq how I can achieve this in python.
given: num=4
expect: (0,1), (0,2), (0,3), (0,4), (1,2), (1,3), (1,4), (2,3), (2,4), (3,4) (in tuple)
答案1
得分: 1
使用嵌套循环:
>>> num = 4
>>> for i in range(num):
... for j in range(i+1, num+1):
... print((i, j))
...
(0, 1)
(0, 2)
(0, 3)
(0, 4)
(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)
使用 itertools
:
>>> import itertools
>>> print(*itertools.combinations(range(num+1), 2), sep="\n")
(0, 1)
(0, 2)
(0, 3)
(0, 4)
(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)
英文:
Using nested loops:
>>> num = 4
>>> for i in range(num):
... for j in range(i+1, num+1):
... print((i, j))
...
(0, 1)
(0, 2)
(0, 3)
(0, 4)
(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)
Using itertools
:
>>> import itertools
>>> print(*itertools.combinations(range(num+1), 2), sep="\n")
(0, 1)
(0, 2)
(0, 3)
(0, 4)
(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论