在python中使用嵌套循环打印所有不同的三胞胎
我想在python3中编写一个函数printTriplet(n)
,该 ,该函数输入一个整数,并在不重复的情况下打印从0到n-1的所有可能的数字。 我想用三个嵌套循环进行操作:
def NewTrip(n):
for i in range(n-2):
for j in range(i+1,n-1):
for k in range(i+j+1,n):
print([i,j,k])
有趣的是,此功能的行为不像我预期的那样。例如,如果n = 4
因此输出
[0, 1, 2]
[0, 1, 3]
[0, 2, 3]
不打印三重[1,2,3]
。对于我尝试的每个值的每个值,都没有打印大量三元组。
我觉得我缺少关于嵌套的foor循环真正基本的东西。任何帮助都将非常重要!
I want to write a function PrintTriplets(n)
in Python3 that takes in input an integer and prints all the possible triplets of numbers from 0 to n-1 without repetition.
I wanted to do it with three nested for loops as follows:
def NewTrip(n):
for i in range(n-2):
for j in range(i+1,n-1):
for k in range(i+j+1,n):
print([i,j,k])
Interestingly this function does not behave as I expected. For example if n=4
the output is
[0, 1, 2]
[0, 1, 3]
[0, 2, 3]
Therefore it does not print the triple [1,2,3]
. For every value of n I tried, a large number of triples is not printed.
I feel that I am missing something really fundamental about nested foor loops. Any help will be very much aprecciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论