Cuando n = 5 el patrón debe ser:
1 121 12321 121 1Lo que probé hasta ahora:
# Pattern 1-121-12321 pyramid pattern # Reading number of rows row = int(input('Enter how many lines? ')) # Generating pattern for i in range(1,row+1): # for space for j in range(1, row+1-i): print(' ', end='') # for increasing pattern for j in range(1,i+1): print(j, end='') # for decreasing pattern for j in range(i-1,0,-1): print(j, end='') # Moving to next line print()Salida que estoy obteniendo:
1 121 12321 1234321 123454321Conozco la lógica de patrones similares como:
* *** ***** *******Pero el patrón numérico parece ser confuso y no puedo obtener la lógica.
Programa de Python para generar el siguiente patrón para imprimir n filas:
p.ej. Cuando n=7:
1 121 12321 1234321 12321 121 1¿Qué tal este código:
for i in range(n): temp = 0 # Store the value of the number to square (so 1, 11,...) if (i < n / 2): for j in range(i + 1): temp += 10 ** j # Construct the number (1 = 1, 11 = 1 + 10, 111 = 1 + 10 + 10 ^ 2,...) for _ in range(int(n / 2 - i)): print(' ', end = '') # Add space indentation else: for j in range(n - i): # Count in reverse now temp += 10 ** j # Construct the number (1 = 1, 11 = 1 + 10, 111 = 1 + 10 + 10 ^ 2,...) for _ in range(int(i - n / 2) + 1): print(' ', end = '') # Add space indentation print(temp ** 2) # Square the temporary value(Dato matemático divertido: la cadena que imprimes tiene una propiedad de:
1 = 1^2; 121 = 11^2; 12321 = 111^2;...)
También daré mi sugerencia. Así que aquí inicialmente solo subcontrato la producción de la línea en un método. Primero calculo la longitud de la línea actual y, dependiendo del número máximo de líneas que desee imprimir, determino el relleno para obtener esta forma de estrella. Luego produzco la cadena real, que depende del punto medio de la cadena, así que tan pronto como excedo esto, reduzco la numeración nuevamente.
from math import ceil def produce_line(line, maximum): middle = ceil(maximum / 2) padding = abs(middle - line) line_width = maximum - 2 * padding half_lw = ceil(line_width / 2) res = (" " * padding) + "".join([str(a) if a <= half_lw else str(abs(2 * half_lw - a)) for a in range(1, line_width + 1)]) return res lines = 9 for i in range(1, lines + 1): print(produce_line(i, lines))Puede agregar una declaración if y comenzar desde un conteo con una nueva variable c :
row = int(input('Enter how many lines? ')) c = row // 2 for i in range(1,row+1): if i <= (row // 2 + 1): # for space for j in range(1, row+1-i): print(' ', end='') # for increasing pattern for j in range(1,i+1): print(j, end='') # for decreasing pattern for j in range(i-1,0,-1): print(j, end='') else: for j in range(1, i): print(' ', end='') # for increasing pattern for j in range(1, c): print(j, end='') # for decreasing pattern for j in range(c, 0, -1): print(j, end='') c -= 1 # Moving to next line print()Producción:
Enter how many lines? 7 1 121 12321 1234321 12321 121 1