1. 蛇形矩阵是由1开始的自然数依次排列成的一个矩阵上三角形。
例如,当输入5时,应该输出的三角形为:
1 3 6 10 15
2 5 9 14
4 8 13
7 12
11
import sys
def generate_snake_matrix(n):matrix = [[0]*n for _ in range(n)]curent_num = 1for i in range(n):for j in range(i+1):matrix[i-j][j] = curent_numcurent_num += 1result = []for i in range(n):result.append([n_ for n_ in matrix[i] if n_ != 0])return result
for line in sys.stdin:a = line.split()result = generate_snake_matrix(int(a[0]))for line in result:print(' '.join(map(str, line)))
2.
根据输入的日期,计算是这一年的第几天。
保证年份为4位数且日期合法。
输入:2012 12 31
输出:366
import sysdef is_leap_year(year):# 判断是否为闰年return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)def days_in_month(month, year):# 每个月的天数days_in_months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]if is_leap_year(year):days_in_months[1] = 29 # 2月在闰年为29天return days_in_months[month - 1]def day_of_year(year, month, day):# 计算日期前所有月份的天数之和day_of_year = sum(days_in_month(m, year) for m in range(1, month)) + dayreturn day_of_yearfor line in sys.stdin:a = line.split()year = int(a[0])month = int(a[1])day = int(a[2])print(day_of_year(year, month, day))