Python练习题2 python题目及答案
- 题目1:快速构造二维数组[[1, 2, 3, 4], [-1, -2, -3, -4], [1, 2, 3, 4], [-1, -2, -3, -4]]
# using nested while-loop
matrix = [[] for sublist in range(4)] # initialize nested list
row = 0
while row < len(matrix):
col = 1
while col < len(matrix) + 1:
if row % 2 == 0:
matrix[row].append(col)
else:
matrix[row].append(-col)
col += 1
row += 1
print(matrix)
# using nested for-loop
matrix = [[] for sublist in range(4)]
for row in range(4):
for col in range(1, 5)
if row % 2 == 0:
matrix[row].append(col)
else:
matrix[row].append(-col)
print(matrix)
运行结果:
- 题目2:由数字1、2、3、4可组成多少个数字各不相同的三位数?分别是多少?
# using nested foor-loop
keys = []
for hundreds in range(1, 5):
for tens in range(1, 5):
for units in range(1, 5):
if hundreds != tens and tens != units and units != hundreds:
keys.append(int(str(hundreds)+str(tens)+str(units)))
result_num = len(keys)
print(f'''\
There are {result_num} eligible three-digit numbers meet the problem requirements.\
''')
print(f'All keys is shown below: ')
for key in keys:
print(key, end=' ')
# using list comprehension
element_nums = [1, 2, 3, 4]
keys = [hundreds*100 + tens*10 + units*1
for hundreds in element_nums
for tens in element_nums
for units in element_nums
if (hundreds != tens and tens != units and units != hundreds)]
result_num = len(keys)
print(f'''\
There are {result_num} eligible three-digit numbers meet the problem requirements.\
''')
print(f'All keys is shown below: ')
for key in keys:
print(key, end=' ')
运行结果:
题目3:打印所有水仙花数(水仙花数:满足各位数字的立方和等于该数本身的一个三位数,例如,153=1^3+5^3+3^3)
# using while-loop
daffodil_num = 100
while daffodil_num < 1000:
hundreds = daffodil_num // 100
tens = daffodil_num // 10 % 10
units = daffodil_num % 10
if hundreds ** 3 + tens ** 3 + units ** 3 == daffodil_num:
print(daffodil_num, end=' ')
daffodil_num += 1
# using foor-loop
for daffodil_num in range(100, 1000):
hundreds = daffodil_num // 100
tens = daffodil_num // 10 % 10
units = daffodil_num % 10
if hundreds ** 3 + tens ** 3 + units ** 3 == daffodil_num:
print(daffodil_num, end=' ')
运行结果:
题目4:一个整数,当它加上100后是一个完全平方数,然后再加上168后正好也是一个完全平方数,这样的整数有多少个?分别是多少?
"""
解题思路:
设整数为x, 则有x + 100 = a2 x + 100 + 168 = b2 ,|a| < |b|且a,b均为整数
b2 - a2 = 168 即(b-a)(b+a)=168 令(b-a) = m (b+a) = n (m + n)/2 = b (n - m)/2 = a
将168进行因式分解可分为16组:(1,168),(2,84),(3,56),(4,42),(6,28),(7,24),(8,21),(12,14),(14,12),
(21,8),(24,7),(28,6),(42,4),(56,3),(84,2),(168,1)
因为x为整数,所以a2-100和b2-268必然是一个整数,所以(n-m)/2和(n+m)/2也必须是一个整数,
也就是说16个元组,必须满足元组中的元素同为奇数或同为偶数,因此可以排除(1,168), (3,56),
(7,24), (8,21),(21,8), (24, 7), (56, 3), (168, 1)这八组,剩下(2,84),(4,42),(6,28),(12,14),(14,12),(28,6)
(42,4),(84,2)这八组
x = |2-84|2/4 - 100 , x = |4-42|2/4 -100, x = |6-28|2/4 -100 , x = |12-14|2/4 -100
"""
tuple_lst = []
i = 1
while i <= 168:
if 168 % i == 0:
tuple_lst.append((i, 168//i))
i += 1
# print(tuple_lst)
i = 0
while i < len(tuple_lst):
j = 0
while j < len(tuple_lst) - i:
if not (tuple_lst[i][0] + tuple_lst[i][1]) % 2 == 0:
del tuple_lst[i]
j += 1
i += 1
# print(tuple_lst)
a_list = []
x_list = []
i = 0
while i < len(tuple_lst):
a_list.append((tuple_lst[i][0] - tuple_lst[i][1]) // 2)
i += 1
for a in a_list:
x = a ** 2 - 100
x_list.append(x)
x_list = list(set(x_list))
print(f"这样的整数有{len(x_list)}个,分别是{x_list}")
题目5:输入某年某月某日,判断这一天是这一年的第几天?
def is_leap_year(year):
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
return True
else:
return False
offset_days = {1: 0, 2: 31, 3: 59, 4: 90, 5: 120, 6: 151, 7: 181, 8: 212, 9: 243, 10: 273, 11: 304, 12: 334}
def calc_date():
global input_year, input_month, input_day
while True:
try:
input_year = int(input("Enter a year: "))
assert 0 <= input_year <= 9999
except ValueError:
print("Not a integer! Please try again.")
continue
except AssertionError:
print("Please enter a valid year!")
continue
try:
input_month = int(input("Enter a month: "))
except ValueError:
print("Not a integer! Please try again.")
continue
if input_month not in range(1, 13):
print("Please enter a valid month!")
continue
try:
input_day = int(input("Enter a day: "))
except ValueError:
print("Not a integer! Please try again.")
continue
if input_month in {1, 3, 5, 7, 8, 10, 12}:
try:
assert 1 <= input_day <= 31
except AssertionError:
print("Invalid day!")
continue
elif input_month in {4, 6, 9, 11}:
try:
assert 1 <= input_day <= 30
except AssertionError:
print("Invalid day!")
continue
elif input_month in {2}:
if is_leap_year(input_year):
try:
assert 1 <= input_day <= 29
except AssertionError:
print("Invalid day!")
continue
else:
try:
assert 1 <= input_day <= 28
except AssertionError:
print("Invalid day!")
continue
break
if is_leap_year(input_year) and input_month > 2:
year_day = offset_days[input_month] + input_day + 1
else:
year_day = offset_days[input_month] + input_day
print(f"It is the {year_day}th day of {input_year}.")
calc_date()
运行结果: