6.2练习

1.q5:

"""
Question:
Define a class which has at least two methods:
getString: to get a string from console input
printString: to print the string in upper case.
Also please include simple test function to test the class methods."""
class write:

	def getString(self):
		w= input()
		return w
	def printString(self):
		print(f"{self.getString()}".upper())

t=write()
t.printString()

input()

总结:其中self.getString()相当于一个变量,若要提取其字符串应用f

2.q7:

'''  Question:
Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array.
 The element value in the i-th row and j-th column of the array should be i*j.
Note: i=0,1.., X-1; j=0,1,..,Y-1.
Example
Suppose the following inputs are given to the program:
3,5
Then, the output of the program should be:
[[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]] 

'''
x=3
y=5
m=[[0 for i in range(y)] for j in range(x) ]
print(m)
for i in range(y):
	for j in range(x):
		m[j][i]=i*j
print(m)
c=[0 for i in range(3)]
print(c)

总结:注意二维数组的创建方法,注意提取其中元素的方法

3.q8:

"""Question:
Write a program that accepts a comma separated sequence of words as input and
 prints the words in a comma-separated sequence after sorting them alphabetically.
Suppose the following input is supplied to the program:
without,hello,bag,world
Then, the output should be:
bag,hello,without,world"""
input_="without,hello,bag,world"
inp=input_.split(",")

print(inp)
inp.sort()
print(inp)
print(','.join(inp))

#join函数连接字符,可以直接将列表中元素连接

总结:注意join函数可以连接字符串,sort函数对列表作用

4.q10

"""Question:
Write a program that accepts a sequence of whitespace separated words as input and
 prints the words after removing all duplicate words and sorting them alphanumerically.
Suppose the following input is supplied to the program:
hello world and practice makes perfect and hello world again
Then, the output should be:
again and hello makes perfect practice world
"""
w=input()
w=w.split(" ")

s=w[:]
while True:
	i=s.pop()
	for t in s:
		if i ==t:
			w.remove(t)
		else:
			continue
	if s==[]:
		break
print(w)
w.sort()
for i in w:
	print(i,end=" ")
input()

#方法二
s = raw_input()
words = [word for word in s.split(" ")]
print " ".join(sorted(list(set(words))))

总结:remove函数仅删除列表中的一个,若有重复的仅删一个。集合不入重复的元素

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值