100+Python挑战性编程练习系列 -- day 2
Question 4
编写一个程序,从控制台接收一个逗号分隔的数字序列,并生成一个列表和一个包含每个数字的元组。假设向程序提供以下输入:34,67,55,33,12,98 然后,输出应为:[‘34’, ‘67’, ‘55’, ‘33’, ‘12’, ‘98’]
(‘34’, ‘67’, ‘55’, ‘33’, ‘12’, ‘98’)
lst = input().split(',') # the input is being taken as string and as it is string it has a built in
# method name split. ',' inside split function does split where it finds any ','
# and save the input as list in lst variable
tpl = tuple(lst) # tuple method converts list to tuple
print(lst)
print(tpl)
Question 5
定义一个至少有两个方法的类:
getString:从控制台输入获取字符串
printString:以大写打印字符串。
也请包含简单的测试函数来测试类方法。
class IOstring():
def get_string(self):
self.s = input()
def print_string(self):
print(self.s.upper())
xx = IOstring()
xx.get_string()
xx.print_string()
Question 6
编写一个程序,根据给定的公式计算并打印值:
Q =[(2 × C × D)/ H]的平方根
以下是C和H的固定值:
C是50。H是30。
D是一个变量,它的值应该以逗号分隔的顺序输入到程序中。例如,让我们假设以下逗号分隔的输入序列被赋予程序: 100,150,180 程序的输出应为: 18,22,24
解法1:
from math import sqrt
C,H = 50,30
def calc(D):
return sqrt((2*C*D)/H)
D = input().split(',') # splits in comma position and set up in list
D = [str(round(calc(int(i)))) for i in D] # using comprehension method. It works in order of the previous code
print(",".join(D))
解法2:
from math import sqrt
C, H = 50, 30
mylist = input().split(',')
print(*(round(sqrt(2*C*int(D)/H)) for D in mylist), sep=",")
解法3:
my_list = [int(x) for x in input('').split(',')]
C, H, x = 50, 30, []
for D in my_list:
Q = ((2*C*D)/H)**(1/2)
x.append(round(Q))
print(','.join(map(str, x)))
Question 7
编写一个程序,它以2位数字X,Y作为输入,并生成一个二维数组。数组第i行和第j列的元素值应该是i × j。*
注意:i= 0,1。.,X-1; j= 0,1,…Y-1。假设将以下输入提供给程序:3,5
然后,程序的输出应该是: [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]
方法1:
x,y = map(int,input().split(','))
lst = []
for i in range(x):
tmp = []
for j in range(y):
tmp.append(i*j)
lst.append(tmp)
print(lst)
方法2:
x,y = map(int,input().split(','))
lst = [[i*j for j in range(y)] for i in range(x)]
print(lst)
Question 8
编写一个程序,接受逗号分隔的单词序列作为输入,并在按字母顺序排序后以逗号分隔的顺序打印单词。
假设向程序提供以下输入: without,hello,bag,world
然后,输出应为: bag,hello,without,world
lst = input().split(',')
lst.sort()
print(",".join(lst))
Question 9
写一个程序,接受一系列的行作为输入,并在将句子中的所有字符大写后打印这些行。
假设向程序提供以下输入:
Hello world
Practice makes perfect
然后,输出应为:
HELLO WORLD
PRACTICE MAKES PERFECT
解法1:
lst = []
while True:
x = input()
if len(x)==0:
break
lst.append(x.upper())
for line in lst:
print(line)
解法2:
def inputs():
while True:
string = input()
if not string:
return
yield string
print(*(line.upper() for line in inputs()),sep='\n')