📜  Python – 迭代对模式

📅  最后修改于: 2022-05-13 01:54:18.791000             🧑  作者: Mango

Python – 迭代对模式

有时,在使用Python时,我们可能会遇到需要执行模式构造或迭代对字符串的问题,其中第二个元素不断增加。这类问题在日间编程和学校编程中都有应用。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环
这是可以执行此任务的蛮力方式。在此,我们手动检查第二个元素并在每次迭代和存储中执行增量。

Python3
# Python3 code to demonstrate working of
# Iterative Pair Pattern
# Using loop
 
# initializing 1st element
frst_ele = 'G'
 
# initializing 2nd element
secnd_ele = '*'
 
# initializing N
N = 4
 
# Iterative Pair Pattern
# Using loop
res = frst_ele + secnd_ele
for idx in range(1, N):
    res += frst_ele + secnd_ele * (idx + 1)
 
# printing result
print("The constructed pattern is : " + str(res))


Python3
# Python3 code to demonstrate working of
# Iterative Pair Pattern
# Using join() + generator expression
 
# initializing 1st element
frst_ele = 'G'
 
# initializing 2nd element
secnd_ele = '*'
 
# initializing N
N = 4
 
# Iterative Pair Pattern
# Using join() + generator expression
res = frst_ele.join(secnd_ele * idx for idx in range(N + 1))
 
# printing result
print("The constructed pattern is : " + str(res))


输出 :
The constructed pattern is : G*G**G***G****


方法 #2:使用 join() + 生成器表达式
上述方法的组合可用于执行此任务。在此,我们在生成器表达式的一个线性逻辑中执行增量和模式构造的任务。

Python3

# Python3 code to demonstrate working of
# Iterative Pair Pattern
# Using join() + generator expression
 
# initializing 1st element
frst_ele = 'G'
 
# initializing 2nd element
secnd_ele = '*'
 
# initializing N
N = 4
 
# Iterative Pair Pattern
# Using join() + generator expression
res = frst_ele.join(secnd_ele * idx for idx in range(N + 1))
 
# printing result
print("The constructed pattern is : " + str(res))
输出 :
The constructed pattern is : G*G**G***G****