[英]Python pyramid practice question generated different output
I was practicing pyramid patterns for a test in python. 我正在练习金字塔图案以进行python测试。 One question was about a pyramid pattern including 1s and 0s.
一个问题是关于包括1和0的金字塔图案。
Output to generate: 输出生成:
1
10
101
1010
10101
Output that I got: 我得到的输出:
10
110
1110
11110
111110
My Efforts for this problem statement: 我对此问题所做的努力:
def pattern(n):
for i in range(n):
num = 1
for j in range(i+1):
print(num,end="")
print(num-1)
What am i doing wrong? 我究竟做错了什么?
You need to change num
each time you go through the for j in range(i+1):
loop, otherwise you'll just keep printing the same number like in your output. 每次
for j in range(i+1):
循环中的for j in range(i+1):
您都需要更改num
,否则您将继续输出与输出中相同的数字。 You could try changing num
in each pass through the loop. 您可以尝试在每次循环中更改
num
。 The modulus operator %
will be useful for switching back and forth between 0 and 1: 模运算符
%
对于在0和1之间来回切换非常有用。
def pattern(n):
for i in range(n):
num = 1
for j in range(i+1):
print(num,end="")
num = (num+1)%2
because output format is 1010101
, you should change num
in loop, and you can use XOR ^
to switch between 0
and 1
: 因为输出格式为
1010101
,所以您应该循环更改num
,并且可以使用XOR ^
在0
和1
之间切换:
def pattern(n):
for i in range(n):
num = 1
for j in range(i+1):
print(num, end="")
num ^= 1
print()
test: 测试:
pattern(5)
output: 输出:
1
10
101
1010
10101
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.