python马丁challenge11.A triangle o
2019-04-03 本文已影响0人
33jubi
Write a program characters_triangle.py that gets a strictly positive integer N as input and outputs a
triangle of height N. For instance, when N = 5, the triangle looks like this:
image
Two built-in functions are useful for this exercise:
- ord() returns the integer that encodes the character provided as argument;
- chr() returns the character encoded by the integer provided as argument.
For instance:
/>>> ord(’A’)
65
/>>> chr(65)
’A’
Consecutive uppercase letters are encoded by consecutive integers. For instance:
/>>> ord(’A’), ord(’B’), ord(’C’)
(65, 66, 67)
Insert your code into characters_triangle.py. If you are stuck, but only when you are stuck, then use characters_triangle_scaffold_1.py.
# 我的解法
import sys
# Insert your code here
def triangle(n):
c=65
for i in range(n):
for x in range(n-i-1):
print(' ',end='')
for x in range(i+1):
print(chr(c),end='')
c+=1
if c>90:
c=65
cc=c-1
for x in range(i):
cc=cc-1
if cc==63:
cc=89
elif cc<65:
cc=90
#cc=cc-1
print(chr(cc),end='')
print()
while True:
try:
n = int(input('Enter strictly positive number: '))
if n <= 0:
raise ValueError
break
except ValueError:
print('Incorrect input, try again.')
triangle(n)
#马丁解法
# Written by Eric Martin for COMP9021
'''
Prompts the user for a strictly positive number N
and outputs an equilateral triangle of height N.
The top of the triangle (line 1) is labeled with the letter A.
For all nonzero p < N, line p+1 of the triangle is labeled
with letters that go up in alphabetical order modulo 26
from the beginning of the line to the middle of the line,
starting with the letter that comes next in alphabetical order
modulo 26 to the letter in the middle of line p,
and then down in alphabetical order modulo 26
from the middle of the line to the end of the line.
'''
while True:
try:
height = int(input('Enter strictly positive number: '))
if height <= 0:
raise ValueError
break
except ValueError:
print('Incorrect input, try again.')
A_code = ord('A')
c = A_code
for i in range(1, height + 1):
# Displays spaces on the left
print(' ' * (height - i), end = '')
# Displays letters before middle column
for _ in range(1, i):
print(chr(c), end = '')
# Code of next letter
c = (c - A_code + 1) % 26 + A_code#这里取余的做法代替了到极限复原
# Displays middle column
print(chr(c), end = '')
# Displays letters after middle column
for _ in range(1, i):
# Code of previous letter
c = (c - A_code - 1) % 26 + A_code
print(chr(c), end = '')
print()
# Code of first letter to be input on next line
c = ((1 + i) * i // 2) % 26 + A_code