python编程100+题11—20(第二天)

**

python编程100题11—20(第二天)

自学python提高编程能力(第二天)

以下为python编程100题,来自github,原文链接如下:
https://github.com/zhiwehu/Python-programming-exercises/blob/master/100%2B%20Python%20challenging%20programming%20exercises.txt
文章的最后是一些知识点总结和提示
完成这些题目的基础上,进行了一些题目要求的翻译理解;添加了自己理解的注释和出过的错误,请同样学习的朋友们指正!

QUESTION11

'''
Question 11
Level 2

Question:
Write a program which accepts a sequence of comma separated 4 digit binary numbers
as its input and then check whether they are divisible by 5 or not.
The numbers that are divisible by 5 are to be printed in a comma separated sequence.
{输入逗号分割二进制数,输出能被5整除的数,同样逗号分隔}
Example:
0100,0011,1010,1001
Then the output should be:
1010
Notes: Assume the data is input by console.

Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
'''
output=[]
array=[x for x in input().split(",")]
for p in array:
    intp=int(p,2)    #2进制数字转为十进制int类型变量
    if intp%5==0:
        output.append(p)  #输出是通过.join(output)来输出,因而一定要是str类型列表,如果用intp,就会报错
        
print(",".join(output))
        

QUESTION12

'''
Question 12
Level 2

Question:
Write a program, which will find all such numbers between 1000 and 3000 (both included)
such that each digit of the number is an even number.
The numbers obtained should be printed in a comma-separated sequence on a single line.
{找出1000—3000中所有的数,该数字的每一位(四位数)都是偶数}
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
'''
count=[]
for i in range(1000,3001):
    stri=str(i)  #把int类型数给stri字符数组,即可完成数位的分离
    if int(stri[3])%2==0 and int(stri[2])%2==0 and int(stri[1])%2==0 and int(stri[0])%2==0:  #这里进行运算,类型应该是int类型
        count.append(stri)  #这里也是append,添加内容必须是str类型

print(",".join(count))

QUESTION13

'''
Question 13
Level 2

Question:
Write a program that accepts a sentence and calculate the number of letters and digits.
Suppose the following input is supplied to the program:
{计算输入句子中数字和字母的个数}
hello world! 123
Then, the output should be:
LETTERS 10
DIGITS 3

Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
'''
array=input()
d={"LETTERS":0,"DIGITS":0} #定义一个字典,表达数字、字母的对应关系
for a in array:
    if a.isalpha():
        d["LETTERS"]+=1
    elif a.isdigit():
        d["DIGITS"]+=1
    else:
        pass  #其余情况下,不进行操作,即退出此次判断,继续下一次判断,实际上不写这句话也可以
print("LETTERS",d["LETTERS"])
print("DIGITS",d["DIGITS"])

QUESTION14

'''
Question 14
Level 2

Question:
Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters.
{计数句子中大写字母,小写字母的数量}
Suppose the following input is supplied to the program:
Hello world!
Then, the output should be:
UPPER CASE 1
LOWER CASE 9

Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
'''
array=input()
output={"UPPER CASE":0,"LOWER CASE":0}
for each in array:
    if each.isupper()==1:
        output["UPPER CASE"]+=1
    elif each.islower()==1:
        output["LOWER CASE"]+=1
    else:
        pass                    #这里的else是可以省略的

print("UPPER CASE",output["UPPER CASE"])
print("LOWER CASE",output["LOWER CASE"])

QUESTION15

'''
Question 15
Level 2

Question:
Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a.
{输入a后,计算这个算式的值}
Suppose the following input is supplied to the program:
9
Then, the output should be:
11106

Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
'''
#我的做法:
a=int(input())
out=0
for i in range(1,5):          #一定要注意这里range的取值,(1,5)则取1,2,3,4,而(1,1)则输出为空
    for j in range(0,i):
        out=out+a*(10**j)
print(out)

#下面是答案给的方法为:
Solution:
a = input()
n1 = int( "%s" % a )
n2 = int( "%s%s" % (a,a) )  #通过""%(),生成一个字符型变量,双括号内写类型,括号内是扩展的符号
n3 = int( "%s%s%s" % (a,a,a) )
n4 = int( "%s%s%s%s" % (a,a,a,a) )
print n1+n2+n3+n4

QUESTION16

'''
Question 16
Level 2

Question:
Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers.
{列表输出奇数}
Suppose the following input is supplied to the program:
1,2,3,4,5,6,7,8,9
Then, the output should be:
1,3,5,7,9

Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
'''

array=input().split(",")
numbers=[x for x in array if int(x)%2!=0]
print(",".join(numbers))

QUESTION17

'''
Question 17
Level 2

Question:
Write a program that computes the net amount of a bank account based a transaction log from console input.
The transaction log format is shown as following:
D 100
W 200
{输入存取款金额,输出最终账户余额}
D means deposit while W means withdrawal.
Suppose the following input is supplied to the program:
D 300
D 300
W 200
D 100
Then, the output should be:
500

Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
'''

netAmount=0
while True:
    s=input()
    if not s:   #标准的输入非空检测
        break
    value=s.split(" ")
    operation=value[0]
    amount=int(value[1])
    if operation=="D":
        netAmount+=amount
    elif operation=="W":
        netAmount-=amount
    else:
        pass
print(netAmount)

QUESTION18

'''
Question 18
Level 3

Question:
A website requires the users to input username and password to register.
Write a program to check the validity of password input by users.
Following are the criteria for checking the password:
1. At least 1 letter between [a-z]
2. At least 1 number between [0-9]
1. At least 1 letter between [A-Z]
3. At least 1 character from [$#@]
4. Minimum length of transaction password: 6
5. Maximum length of transaction password: 12
{输入一串密码,对格式进行检查,输出正确的}
Your program should accept a sequence of comma separated passwords and
will check them according to the above criteria. Passwords that match the criteria are to be printed,
each separated by a comma.
Example
If the following passwords are given as input to the program:
ABd1234@1,a F1#,2w3E*,2We3345
Then, the output of the program should be:
ABd1234@1

Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
'''
import re
array=input().split(",")
value=[]
for each in array:
    if len(each)<6 or len(each)>12: #continue意思是判断结束,顺序往下继续执行
        continue                   #pass意思是推出for循环
    else:
        pass
    
    if not re.search("[a-z]",each):   #这里为什么是not?
        continue
    elif not re.search("[A-Z]",each):
        continue
    elif not re.search("[0-9]",each):
        continue
    elif not re.search("[$#@]",each):
        continue
    else:
        pass
    value.append(each)
print(",".join(value))

QUESTION19

'''
Question 19
Level 3

Question:
You are required to write a program to sort the (name, age, height) tuples by ascending order where name is string,
age and height are numbers. The tuples are input by console. The sort criteria is:
1: Sort based on name;
2: Then sort based on age;
3: Then sort by score.
The priority is that name > age > score.
{输入人名年龄分数信息,按优先级进行排序}
If the following tuples are given as input to the program:
Tom,19,80
John,20,90
Jony,17,91
Jony,17,93
Json,21,85
Then, the output of the program should be:
[('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Json', '21', '85'), ('Tom', '19', '80')]

Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
We use itemgetter to enable multiple sort keys.
'''
import operator
l=[]
while True:
    s=input()
    if not s:
        break
    l.append(tuple(s.split(",")))       #将s转为tuple再存入l
print(sorted(l,key=operator.itemgetter(0,1,2)))  #key是sorted函数的参数名,通过key来表明优先级
                                               #itemgetter函数,排序的先后顺序即为从排序的元组中选取第0 1 2个元素

QUESTION20

'''
Question 20
Level 3

Question:
Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n.
{定义一个类,函数功能为输出在0和n之间能被7整除}
Hints:
Consider use yield
'''
def putNumbers(n):
    i = 0
    while i<n:
        j=i
        i=i+1
        if j%7==0:
            yield j #相当于是return j作为输出,每次输出一个j,这就是一个生成器

for i in putNumbers(100):
    print(i)

1.python中的generator生成器类型:
(什么是generator?)generator是生成器,类似于指针,声明的generator可以通过next()展现所有的元素,并且是iterable的,可以被遍历;但不同于列表,不能用类似len()等函数。
(为什么用generator?)用generator迭代生成数列,比列表占用的内存小得多,并且速度快得多——生成列表是实实在在的在处理中生成了这么多数字,并且存储在内存中;而用generator生成是生成了一个生成器,在需要调用时才进行运行。
(什么时候用generator?)生成函数库,或者大容量的数组时,用generator节省内存,速度更快。
(怎么用generator?)

>>>num=[1,2,3,4,5]
>>>square=[n for n in num]
square
[1, 2, 3, 4, 5]
>>>square=(n for n in num)
>>>square
<generator object <genexpr> at 0x0344EAE0>

>>>print(square)
<generator object <genexpr> at 0x0344EAE0>
>>>print(next(square))
1
>>>print(next(square))
2
>>>print(next(square))
3
>>>print(next(square))
4
>>>print(next(square))
5
>>>print(next(square))
Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    print(next(square))
StopIteration

>>>num=[1,2,3,4,5]
>>>square=(n for n in num)
>>>for v in square:
>>>    print(v,end=",")
1,2,3,4,5,

2.yield和python生成器:
前面用()代替[]完成了数字序列的一个生成器,这里用yield可以代替函数来返回一个生成器。

>>>def generate_even(max):
>>>    for i in range(0,max+1):
>>>        if i % 2==0:
>>>            yield i
#yield即在这里返回一个生成器,当前值就是表达式的值,相当于调用时,yield返回一个数值后,函数暂停,等待下一次调用
>>>print(generate_even(10))
<generator object generate_even at 0x03A7B878>
>>>even_generator=generate_even(10):
>>>for n in even_generator:
>>>    print(n,end=" ")
0 2 4 6 8 10 
#for语句可以完成__next__的迭代输出的功能

用定义函数的方法定义生成器

>>>def even(max):
>>>    result=[]#固定格式1
>>>    for i in range(0,max+1):
>>>        if i % 2==0:
>>>            result.append(i)#固定格式2
>>>    return result#固定格式3
>>>for v in even(10):
>>>    print(v,end=" ")   
0 2 4 6 8 10 

4.python中的continue和pass:
continue:结束这次所有if、elif的判断,不进行下面的操作,直接进行下次判断
而pass:一般是不用写的,用来占位置,就是说下面的行为将继续进行

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值