Day2
题目四
编写一个程序,从控制台接受一系列逗号分隔的数字,并生成一个列表和一个包含每个数字的元组。假设向程序提供了以下输入:
34,67,55,33,12,98
输出应该为:
[‘34’, ‘67’, ‘55’, ‘33’, ‘12’, ‘98’]
(‘34’, ‘67’, ‘55’, ‘33’, ‘12’, ‘98’)
代码实现
lst = input('请输入数组:').split(",") #输入的是字符串的模式,.split()函数能将指定字符去掉
print(lst)
tpl = tuple(lst) #tuple()函数能够将其他类型的变量转换成元组
print(tpl)
运行结果
请输入数组:1,2,3,4,5,6,7,8,9,122
['1', '2', '3', '4', '5', '6', '7', '8', '9', '122']
('1', '2', '3', '4', '5', '6', '7', '8', '9', '122')
题目五
定义至少有两个方法的类:getString;
从控制台获得字符串–printString;
以大写打印字符串。还请包括简单的测试函数来测试类方法。
代码实现
class string():
def __init__(self):
pass
def get_string(self):
self.s = input('请输入字符')
def print_string(self):
print(self.s.upper())
str1 = string()
str1.get_string()
str1.print_string()
运行结果
请输入字符abcdf
ABCDF
题目六
编写一个程序,根据给定的公式计算和打印该值:
Q = Square root of [(2 C D)/H]
C和H的固定值如下:
c = 50
h = 30
D是一个变量,它的值应该以逗号分隔的顺序输入到您的程序中。例如,让我们假设程序有以下逗号分隔的输入序列:
100,150,180
程序的输出应该是:
18,22,24
代码实现
import math
C, H = 50, 30
lst1 = []
def SQ(D):
return math.sqrt((2*C*D)/H)
lst = input('请输入数组').split(",")
print(lst)
for i in range(len(lst)):
lst1.append(int(SQ(int(lst[i]))))
print(lst1)
运行结果
请输入数组200,300,400
['200', '300', '400']
[25, 31, 36]
题目七
编写一个程序,以2位数,X,Y为输入,并生成一个二维数组.
数组的第一行和第j列中的元素值应该是Ij.
*注意: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]]
代码实现
方法一
x, y =map(int,input("请输入x,y的值").split(','))
lst = []
for i in range(x):
stl = []
for j in range(y):
stl.append(i * j)#列表元素的添加
lst.append(stl)
print(lst)
方法二
x, y = map(int,input("请输入x,y的值").split(","))
lst1 = [[i*j for j in range(y)] for i in range(x)]#第一个循环代表列,第二个是行
print(lst1)
运行结果
请输入x,y的值4,6
[[0, 0, 0, 0, 0, 0], [0, 1, 2, 3, 4, 5], [0, 2, 4, 6, 8, 10], [0, 3, 6, 9, 12, 15]]
请输入x,y的值4,6
[[0, 0, 0, 0, 0, 0], [0, 1, 2, 3, 4, 5], [0, 2, 4, 6, 8, 10], [0, 3, 6, 9, 12, 15]]
题目八
编写一个程序,接受逗号分隔的单词序列作为输入,并在按字母顺序排序后,以逗号分隔的顺序打印单词。
假设向程序提供了以下输入:
without,hello,bag,world
输出为:
bag,hello,without,world
代码实现
方法一
lst = input("请输入词组").split(',')
lst.sort() #sort函数可以直接对列表进行排序
print(','.join(lst))
方法二
lst = input("请输入词组").split(',')
lst1 = lst[ : ] #通过切片的方式将原列表赋值给新的列表
lst1.sort()
print(','.join(lst1))
方法三
lst = input("请输入词组").split(',')
lst1 = sorted(lst) #在既保留原列表的情况下产生新的列表
print(','.join(lst1))
运行结果
请输入词组without,hello,bag,world
bag,hello,without,world
请输入词组without,hello,bag,world
bag,hello,without,world
请输入词组without,hello,bag,world
bag,hello,without,world
题目九
编写一个程序,该程序接受行序列作为输入,并在使句子中的所有字符大写后打印行。
假设向程序提供了以下输入:
Hello world
Practice makes perfect
输出为:
HELLO WORLD
PRACTICE MAKES PERFECT
代码实现
方法一
def userinput():
while True:
s = input()
if not s:
return #此时后面不加任何东西的return相当于返回了none,此时程序就会停止
yield s #相当于return,并且告诉程序,下一个执行从此处开始执行
for line in map(str.upper, userinput()): #批量函数处理
print(line)
方法二
lst = []
while input():
x = input()
if len(x) == 0:
break
lst.append(x.upper())
for line in lst:
print(line)
运行结果
Hello world
HELLO WORLD
Practice makes perfect
PRACTICE MAKES PERFECT
asdfg
ASDFG

4401



被折叠的 条评论
为什么被折叠?



