资讯专栏INFORMATION COLUMN

Python基础练习100题 ( 11~ 20)

luckyw / 2408人阅读

摘要:刷题继续上一期和大家分享了前道题,今天继续来刷解法一解法二解法三解法一解法二解法三解法四解法一解法二解法三解法一解法二解法三解法一解法二解法一解法一解法二解法一解法二解法三解法四解法一解法一源代码下载这十道题的

刷题继续

上一期和大家分享了前10道题,今天继续来刷11~20

Question 11:

</>复制代码

  1. 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.

    Example:

</>复制代码

  1. 0100,0011,1010,1001

</>复制代码

  1. Then the output should be:

</>复制代码

  1. 1010

</>复制代码

  1. Notes: Assume the data is input by console.

解法一

</>复制代码

  1. def check(x): # check function returns true if divisible by 5
  2. return int(x,2)%5 == 0 # int(x,b) takes x as string and b as base from which
  3. # it will be converted to decimal
  4. data = input().split(",")
  5. data = list(filter(check,data)) # in filter(func,object) function, elements are picked from "data" if found True by "check" function
  6. print(",".join(data))
解法二

</>复制代码

  1. value = []
  2. items=[int(x) for x in input().split(",")]
  3. result = " ".join(str(x) for x in items if x %5==0 )
  4. print(",".join(result))
解法三

</>复制代码

  1. data = input().split(",")
  2. data = list(filter(lambda i:int(i,2)%5==0,data))
  3. print(",".join(data))
Question 12:

</>复制代码

  1. 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.

解法一

</>复制代码

  1. values = []
  2. for i in range(1000, 3001):
  3. s = str(i)
  4. if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0) and (int(s[3])%2==0):
  5. values.append(s)
  6. print (",".join(values))
解法二

</>复制代码

  1. lst = []
  2. for i in range(1000,3001):
  3. flag = 1
  4. for j in str(i): # every integer number i is converted into string
  5. if ord(j)%2 != 0: # ord returns ASCII value and j is every digit of i
  6. flag = 0 # flag becomes zero if any odd digit found
  7. if flag == 1:
  8. lst.append(str(i)) # i is stored in list as string
  9. print(",".join(lst))
解法三

</>复制代码

  1. def check(element):
  2. return all(ord(i)%2 == 0 for i in element) # all returns True if all digits i is even in element
  3. lst = [str(i) for i in range(1000,3001)] # creates list of all given numbers with string data type
  4. lst = list(filter(check,lst)) # filter removes element from list if check condition fails
  5. print(",".join(lst))
解法四

</>复制代码

  1. lst = [str(i) for i in range(1000,3001)]
  2. lst = list(filter(lambda i:all(ord(j)%2 == 0 for j in i),lst )) # using lambda to define function inside filter function
  3. print(",".join(lst))
Question 13:

</>复制代码

  1. Write a program that accepts a sentence and calculate the number of letters and digits.

    Suppose the following input is supplied to the program:

</>复制代码

  1. hello world! 123

</>复制代码

  1. Then, the output should be:

</>复制代码

  1. LETTERS 10
  2. DIGITS 3

解法一

</>复制代码

  1. text_input = input()
  2. d={"DIGITS":0, "LETTERS":0,"SPACE":0}
  3. d["DIGITS"]= sum(c.isdigit() for c in text_input)
  4. d["LETTERS"]= sum(c.isalpha() for c in text_input)
  5. d["SPACE"] = sum(c.isspace() for c in text_input)
  6. for k,v in d.items():
  7. print(k,v)
解法二

</>复制代码

  1. word = input()
  2. letter,digit = 0,0
  3. for i in word:
  4. if ("a"<=i and i<="z") or ("A"<=i and i<="Z"):
  5. letter+=1
  6. if "0"<=i and i<="9":
  7. digit+=1
  8. print("LETTERS {0}
  9. DIGITS {1}".format(letter,digit))
解法三

</>复制代码

  1. word = input()
  2. letter,digit = 0,0
  3. for i in word:
  4. letter+=i.isalpha() # returns True if alphabet
  5. digit+=i.isnumeric() # returns True if numeric
  6. print("LETTERS %d
  7. DIGITS %d"%(letter,digit)) # two different types of formating method is shown in both solution
Question 14:

</>复制代码

  1. 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:

</>复制代码

  1. Hello world!

</>复制代码

  1. Then, the output should be:

</>复制代码

  1. UPPER CASE 1
  2. LOWER CASE 9

解法一

</>复制代码

  1. word = input()
  2. upper,lower = 0,0
  3. for i in word:
  4. if "a"<=i and i<="z" :
  5. lower+=1
  6. if "A"<=i and i<="Z":
  7. upper+=1
  8. print("UPPER CASE {0}
  9. LOWER CASE {1}".format(upper,lower))
解法二

</>复制代码

  1. text_input = input()
  2. d={"UPPER CASE":0, "LOWER CASE":0}
  3. for c in text_input:
  4. if c.isupper():
  5. d["UPPER CASE"]+=1
  6. elif c.islower():
  7. d["LOWER CASE"]+=1
  8. else:
  9. pass
  10. print ("UPPER CASE", d["UPPER CASE"])
  11. print ("LOWER CASE", d["LOWER CASE"])
解法三

</>复制代码

  1. word = input()
  2. upper = sum(1 for i in word if i.isupper())
  3. lower = sum(1 for i in word if i.islower())
  4. print("UPPER CASE {0}
  5. LOWER CASE {1}".format(upper,lower))
Question 15:

</>复制代码

  1. Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a.

    Suppose the following input is supplied to the program:

</>复制代码

  1. 9

</>复制代码

  1. Then, the output should be:

</>复制代码

  1. 11106

解法一

</>复制代码

  1. a = input()
  2. total,tmp = 0,str() # initialing an integer and empty string
  3. for i in range(4):
  4. tmp+=a # concatenating "a" to "tmp"
  5. total+=int(tmp) # converting string type to integer type
  6. print(total)
解法二

</>复制代码

  1. a = input()
  2. total = int(a) + int(2*a) + int(3*a) + int(4*a) # N*a=Na, for example a="23", 2*a="2323",3*a="232323"
  3. print(total)
Question 16:

</>复制代码

  1. 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. 1,2,3,4,5,6,7,8,9

</>复制代码

  1. Then, the output should be:

</>复制代码

  1. 1,3,5,7,9

解法一

</>复制代码

  1. values = input()
  2. numbers = [x for x in values.split(",") if int(x)%2!=0]
  3. print (",".join(numbers))
Question 17:

</>复制代码

  1. 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:

</>复制代码

  1. D 100
  2. W 200

D means deposit while W means withdrawal.

</>复制代码

  1. Suppose the following input is supplied to the program:

</>复制代码

  1. D 300
  2. D 300
  3. W 200
  4. D 100

</>复制代码

  1. Then, the output should be:

</>复制代码

  1. 500

解法一

</>复制代码

  1. netAmount = 0
  2. while True:
  3. s = input()
  4. if not s:
  5. break
  6. values = s.split(" ")
  7. operation = values[0]
  8. amount = int(values[1])
  9. if operation=="D":
  10. netAmount+=amount
  11. elif operation=="W":
  12. netAmount-=amount
  13. else:
  14. pass
  15. print(netAmount)
解法二

</>复制代码

  1. total = 0
  2. while True:
  3. s = input().split()
  4. if not s: # break if the string is empty
  5. break
  6. cm,num = map(str,s)
  7. if cm=="D":
  8. total+=int(num)
  9. if cm=="W":
  10. total-=int(num)
  11. print(total)
Question 18:

</>复制代码

  1. 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:

At least 1 letter between [a-z]

At least 1 number between [0-9]

At least 1 letter between [A-Z]

At least 1 character from [$#@]

Minimum length of transaction password: 6

Maximum length of transaction password: 12

</>复制代码

  1. 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

  2. If the following passwords are given as input to the program:

</>复制代码

  1. ABd1234@1,a F1#,2w3E*,2We3345

</>复制代码

  1. Then, the output of the program should be:

</>复制代码

  1. ABd1234@1

解法一

</>复制代码

  1. import re
  2. value = []
  3. items=[x for x in input().split(",")]
  4. for p in items:
  5. if (len(p)<6 or len(p)>12):
  6. break
  7. elif not re.search("[a-z]",p):
  8. break
  9. elif not re.search("[0-9]",p):
  10. break
  11. elif not re.search("[A-Z]",p):
  12. break
  13. elif not re.search("[$#@]",p):
  14. break
  15. elif re.search("s",p):
  16. break
  17. else:
  18. value.append(p)
  19. break
  20. print (",".join(value))
解法二

</>复制代码

  1. def is_low(x): # Returns True if the string has a lowercase
  2. for i in x:
  3. if "a"<=i and i<="z":
  4. return True
  5. return False
  6. def is_up(x): # Returns True if the string has a uppercase
  7. for i in x:
  8. if "A"<= i and i<="Z":
  9. return True
  10. return False
  11. def is_num(x): # Returns True if the string has a numeric digit
  12. for i in x:
  13. if "0"<=i and i<="9":
  14. return True
  15. return False
  16. def is_other(x): # Returns True if the string has any "$#@"
  17. for i in x:
  18. if i=="$" or i=="#" or i=="@":
  19. return True
  20. return False
  21. s = input().split(",")
  22. lst = []
  23. for i in s:
  24. length = len(i)
  25. if 6 <= length and length <= 12 and is_low(i) and is_up(i) and is_num(i) and is_other(i): #Checks if all the requirments are fulfilled
  26. lst.append(i)
  27. print(",".join(lst))
解法三

</>复制代码

  1. def check(x):
  2. cnt = (6<=len(x) and len(x)<=12)
  3. for i in x:
  4. if i.isupper():
  5. cnt+=1
  6. break
  7. for i in x:
  8. if i.islower():
  9. cnt+=1
  10. break
  11. for i in x:
  12. if i.isnumeric():
  13. cnt+=1
  14. break
  15. for i in x:
  16. if i=="@" or i=="#"or i=="$":
  17. cnt+=1
  18. break
  19. return cnt == 5 # counting if total 5 all conditions are fulfilled then returns True
  20. s = input().split(",")
  21. lst = filter(check,s) # Filter function pick the words from s, those returns True by check() function
  22. print(",".join(lst))
解法四

</>复制代码

  1. import re
  2. s = input().split(",")
  3. lst = []
  4. for i in s:
  5. cnt = 0
  6. cnt+=(6<=len(i) and len(i)<=12)
  7. cnt+=bool(re.search("[a-z]",i)) # here re module includes a function re.search() which returns the object information
  8. cnt+=bool(re.search("[A-Z]",i)) # of where the pattern string i is matched with any of the [a-z]/[A-z]/[0=9]/[@#$] characters
  9. cnt+=bool(re.search("[0-9]",i)) # if not a single match found then returns NONE which converts to False in boolean
  10. cnt+=bool(re.search("[@#$]",i)) # expression otherwise True if found any.
  11. if cnt == 5:
  12. lst.append(i)
  13. print(",".join(lst))
Question 19:

</>复制代码

  1. You are required to write a program to sort the (name, age, score) tuples by ascending order where name is string, age and score 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

</>复制代码

  1. The priority is that name > age > score.

    If the following tuples are given as input to the program:

</>复制代码

  1. Tom,19,80
  2. John,20,90
  3. Jony,17,91
  4. Jony,17,93
  5. Json,21,85

</>复制代码

  1. Then, the output of the program should be:

</>复制代码

  1. [("John", "20", "90"), ("Jony", "17", "91"), ("Jony", "17", "93"), ("Json", "21", "85"), ("Tom", "19", "80")]

解法一

</>复制代码

  1. lst = []
  2. while True:
  3. s = input().split(",")
  4. if not s[0]: # breaks for blank input
  5. break
  6. lst.append(tuple(s))
  7. lst.sort(key= lambda x:(x[0],x[1],x[2]))
  8. print(lst)
Question 20:

</>复制代码

  1. Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n.

解法一

</>复制代码

  1. class Test:
  2. def generator(self,n):
  3. return [i for i in range(n) if i%7==0]
  4. n = int(input())
  5. num = Test()
  6. lst = num.generator(n)
  7. print(lst)
源代码下载

这十道题的代码在我的github上,如果大家想看一下每道题的输出结果,可以点击以下链接下载:

Python 11-20题

我的运行环境Python 3.6+,如果你用的是Python 2.7版本,绝大多数不同就体现在以下3点:

raw_input()在Python3中是input()

print需要加括号

fstring可以换成.format(),或者%s,%d

谢谢大家,我们下期见!希望各位朋友不要吝啬,把每道题的更高效的解法写在评论里,我们一起进步!!!

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/43935.html

相关文章

  • Python基础练习100 ( 31~ 40)

    摘要:刷题继续昨天和大家分享了题,今天继续来刷题解法一解法二解法一解法二解法一解法一解法一解法一解法一解法一解法二解法一解法二解法一源代码下载这十道题的代码在我的上,如果大家想看一下每道题的输出结果,可以点击以下链接下载题我的运行环境如果你 刷题继续 昨天和大家分享了21-30题,今天继续来刷31~40题 Question 31: Define a function which can pr...

    miracledan 评论0 收藏0
  • Python基础练习100 ( 41~ 50)

    摘要:刷题继续大家好,我又回来了,昨天和大家分享了题,今天继续来看题解法一解法二解法一解法二解法一解法二解法一解法二解法一解法一解法一解法一解法一解法一源代码下载这十道题的代码在我的上,如果大家想看一下每道题的输出结果,可以点击以下链接下载题 刷题继续 大家好,我又回来了,昨天和大家分享了31-40题,今天继续来看41~50题 Question 41: Write a program whi...

    mochixuan 评论0 收藏0
  • Python基础练习100 ( 61~ 70)

    摘要:刷题继续昨天和大家分享了题,今天继续来刷题解法一解法一解法一解法一解法一解法一解法一解法一解法二解法一解法二解法一解法二源代码下载这十道题的代码在我的上,如果大家想看一下每道题的输出结果,可以点击以下链接下载题 刷题继续 昨天和大家分享了51-60题,今天继续来刷61~70题 Question 61: The Fibonacci Sequence is computed based o...

    jeyhan 评论0 收藏0
  • Python基础练习100 ( 91~ 100

    摘要:刷题继续昨天和大家分享了题,今天继续来刷最后的题解法一解法二解法一解法二解法一鸡兔同笼解法一解法一解法二解法一解法二默认就是 刷题继续 昨天和大家分享了81-90题,今天继续来刷最后的91-100题 Question 91: Please write a program which accepts a string from console and print it in rever...

    Jrain 评论0 收藏0

发表评论

0条评论

luckyw

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<