(Python) 牛客 在线编程 python入门
作者:互联网
前言
本文为牛客的在线编程的python入门题集的个人解析 链接:
本人主语言C/C++ 来这边刷一下python的入门语法题,这个题库很基础很入门真的就是纯考python语法
本文虽然是展示AC代码,但实际是为了记录python的各种基础语法,便于以后遗忘了可以查看
本文代码默认在python3环境
牛客的环境是版本:Python3.9,支持大部分的常用库。Numpy库与SciPy库默认不支持,请根据题目要求查看是否支持。
AC代码
01 输入输出
NP1 Hello World!
# python 中的字符串 # 用单引号或者双引都可以 # 结尾加不加;都可以 # 这两点和JavaScript很像 print("Hello World!")
NP2 多行输出
str1 = "Hello World!" str2 = Hello Nowcoder! print(str1) print(str2); ################################## # print默认换行,中间可以用转移符 换行 print("Hello World! Hello Nowcoder!")
NP3 读入字符串
# python的输入input()默认输入的就是字符串 str = input() print(str) ######################### # 可以直接在输入作为输出的参数 print(input())
NP4 读入整数数字
这里输出<class int> 猜测python中所有类型都封装成了类
# 将读入的字符串强转成数值型 num = int(input()) print(num) # type()函数,返回变量的类型 print(type(num))
NP5 格式化输出(一)
name = input() # 单纯的字符串拼接 print("I am " + name + " and I am studying Python in Nowcoder!") # 都号分割,默认每两个之间有一个空格 print("I am", name, "and I am studying Python in Nowcoder!") # 类似于C语言的printf输出 print(I am %s and I am studying Python in Nowcoder! %name) # .format() 默认 print(I am {} and I am studying Python in Nowcoder! .format(name)) # .format() 加上位置 print(I am {0} and I am studying Python in Nowcoder! .format(name)) # .format() 指定参数 print(I am {str} and I am studying Python in Nowcoder! .format(str = name)) # 字符串前加个f则可直接将变量嵌入输出 print(fI am { str} and I am studying Python in Nowcoder!)
NP6 牛牛的小数输出
num = float(input()) # 用C语言式方便 print("%.2f" %num) # f用冒号加入参数 注意冒号后不要加空格 print(f"{ num :.2f}") # .format() 型类似 print("{:.2f}".format(num))
02 类型转换
NP7 小数化整数
fnum = float(input()) inum = int(fnum) print(inum) ################################# # 调用math的trunc()函数,截取整数部分 import math print(math.trunc(float(input())))
NP8 为整数增加小数点
num = int(input()) print("%.1f" %num) # 直接float()也行 这样会返回一个0.0 print(type(float()))
NP9 十六进制数字的大小
# python没有字符型变量,至于长度为1的字符串 num = input() # 第二个参数指定进制 print(int(num, 16))
03 字符串
NP10 牛牛最好的朋友们
str1 = input() str2 = input() print(str1 + str2)
NP11 单词的长度
str = input() # len函数 print(len(str)) # 类函数__len__() print(str.__len__())
NP12 格式化输出(二)
name = input() # 首字母大写 print(name.lower()) # 全大写 print(name.upper()) # 全小写 print(name.title())
NP13 格式化输出(三)
str = input() # 去除两侧的空格 print(str.strip())
NP14 不用循环语句的重复输出
str = input() # 直接用*复制 print(str * 100)
NP15 截取用户名前10位
str = input() # [begin, end) print(str[0 : 10]) # 默认从0开始 print(str[: 10])
04 列表
NP16 发送offer
list = ["Allen", "Tom"] for str in list : print("{s}, you have passed our interview and will soon become a member of our company." .format(s = str)) # 移除 list.remove("Tom") # 末尾添加 list.append("Andy") for str in list : print("%s, welcome to join us!" %str) ######################## # 多行字符串 ,这个居然不能过 print(Allen, you have passed our interview and will soon become a member of our company. Andy, you have passed our interview and will soon become a member of our company. Allen, welcome to join us! Andy, welcome to join us!)
NP17 生成列表
str = input(); # 分割,默认按照空格生成列表 print(str.split()) # 可以添加分割的参数 print(str.split( ))
NP18 生成数字列表
# 分割出来默认式字符串,本题要数字 arr = [int(x) for x in input().split()] print(arr)
NP19 列表的长度
list = input().split() # len函数 print(len(list)) # 内置__len__() print(list.__len__())
NP20 增加派对名单(一)
list = input().split() list.append("Allen") print(list)
NP21 增加派对名单(二)
list = input().split() # insert(位置, 内容) list.insert(0, "Allen") print(list)
NP22 删除简历
myList = input().split() # 删除第一个 del myList[0] # [begin, end) # del myList[0 : 1] # 指定移除 #myList.remove(myList[0]) print(myList)
NP23 删除好友
list = input().split() str = input() # 指定移除 # myList.remove(str) # index(data, begin, end) idx = list.index(str) del list[idx] print(list)
NP24 淘汰排名最后的学生
myList = input().split() # 切片 负数表示倒着来 del myList[-3 : ] print(myList) ################# # 指定倒数输出的位置 print(lis[:-3])
NP25 有序的列表
my_list = [x for x in "Python"] # sorted不改变远列表,有返回值 print(sorted(my_list)) print(my_list) print(sorted(my_list, reverse = True))
NP26 牛牛的反转列表
num = [3, 5, 9, 0, 1, 9, 0, 3] # reversed()函数 print(list(reversed(num))) ################# # 步长为-1,表示倒着 print(num[::-1])
NP27 朋友们的喜好
name = [Niumei, YOLO, Niu Ke Le, Mona] food = [pizza, fish, potato, beef] num = [3, 6, 0, 3] list = [] # list任何东西都能append进去 # 类似JavaScript中的一个对象 list.append(name) list.append(food) list.append(num) print(list)
NP28 密码游戏
list = [int(x) for x in input()] # 这里的遍历是非引用型 for i in range(len(list)): # list[i]是引用 list[i] = (list[i] + 3) % 9 # 一点计算机思维都没有 list[0], list[1], list[2], list[3] = list[2], list[3], list[0], list[1] # 根据前面的串连接 print("".join(map(str, list)))
NP29 用列表实现栈
# 列表模拟栈 stack = [1, 2, 3, 4, 5] # pop可以指定位置 stack.pop(-1) print(stack) # 默认pop最后一个 stack.pop() print(stack) num = int(input()) stack.append(num) print(stack)
NP30 用列表实现队列
# pop(0) 或者remove queue = [1, 2, 3, 4, 5] queue.pop(0) print(queue) queue.remove(queue[0]) print(queue) num = int(input()) queue.append(num) print(queue) ########## # 用双端队列 from collections import deque queue = deque([1, 2, 3, 4, 5]) queue.popleft() print(list(queue)) queue.popleft() print(list(queue)) num = int(input()) queue.append(num) print(list(queue))
NP31 团队分组
# 就是练分片 arr = [Tom, Allen, Jane, William, Tony] print(arr[0 : 0 + 2]) print(arr[len(arr) // 2 - 1 : len(arr) // 2 - 1 + 3]) print(arr[-2: ])
05 运算符
NP32 牛牛的加减器
num1 = int(input()) num2 = int(input()) print(num1 + num2) print(num1 - num2)
NP33 乘法与幂运算
x = int(input()) y = int(input()) print(x * y) print(x y)
NP34 除法与取模运算
x = int(input()) y = int(input()) # // 整数除法 print(x // y, x % y) # / 浮点数除法 print("%.2f" %(x / y))
NP35 朋友的年龄是否相等
# 这里用字符串比较一样 a, b = input().split() print(a == b) # 化成列表比较单个元素 list = input().split() print(list[0] == list[1])
NP36 谁的数字大
# 分割后用map函数转化成指定的类型赋值 x, y = map(int, input().split()) print(x > y) print(x < y)
NP37 不低于与不超过
x, maxx, minn = map(float, input().split()) print(x <= maxx) print(x >= minn)
NP38 牛牛的逻辑运算
x, y = map(int, input().split()) # python 中逻辑运算是用关键词 print(x and y) # 与 print(x or y) # 或 print(not x) # 非 print(not y)
NP39 字符串之间的比较
str1 = input() str2 = input() print(str1 == str2) print(str1.lower() == str2.lower())
NP40 俱乐部的成员
list = input().split() name = input() # 关键词 in print(name in list)
NP41 二进制位运算
x, y = map(int, input().split()) # 38题这么写就不行 print(x & y) print(x | y)
NP42 公式计算器
x, y, z, k = map(int, input().split()) print((x + y) * (z - k))
06 条件语句
NP43 判断布尔值
num = int(input()) # 非0即1 if num : print("Hello World!") else : print("Erros!")
NP44 判断列表是否为空
my_list = [] # 判空的方式比较多 # if my_list == [] : # if not my_list: if len(my_list) == 0 : print("my_list is empty!") else : print("my_list is not empty!")
NP45 禁止重复注册
current_users = [Niuniu, Niumei, GURR, LOLO] new_users = [GurR, Niu Ke Le, LoLo, Tuo Rui Chi] for name in new_users : if name.lower() in [s.lower() for s in current_users] : print("The user name %s has already been registered! Please change it and try again!" %name) else : print("Congratulations, the user name %s is available!" %name)
NP46 菜品的价格
# elif 不是 else if # 当然本题可以用字典来写 str = input() if str == pizza: print(10) elif str == rice: print(2) elif str == yogurt: print(5) else: print(8)
NP47 牛牛的绩点
# 阅读理解题 endInput = False sum1, sum2 = 0.0, 0.0 flag = 0.0 # 读到endInput截止 for line in iter(input, endInput): if line == A: flag = 4.0 elif line == B: flag = 3.0 elif line == C: flag = 2.0 elif line == D: flag = 1.0 elif line == F: flag = 0.0 else: sum1 += float(line) sum2 += float(line) * flag print("%.2f" %(sum2 / sum1))
NP48 验证登录名与密码
username = input() password = input() if username == admis and password == Nowcoder666: print(Welcome!) else: print("user id or password is not correct!")
07 循环语句
NP49 字符列表的长度
list = [P, y, t, h, o, n] print("Here is the original list:") print(list, end=" ") print("The number that my_list has is:") print(len(list))
NP50 程序员节
users_list = [Niuniu, Niumei, Niu Ke Le] # 复制列表中的每个元素 for str in users_list : print("Hi, {A}! Welcome to Nowcoder!" .format(A = str)) print("Happy Programmers Day to everyone!")
NP51 列表的最大与最小
list = [] for num in range(10, 50 + 1) : list.append(num) print(list) # 首部 尾部 print(list[0], list[-1])
NP52 累加数与平均值
arr = [int(x) for x in input().split()] sum = sum(arr) # 多个参数都写到%后的括号中 %() print("%d %.1f" %(sum, sum/len(arr)))
NP53 前10个偶数
# 第三个参数是步长 my_list = [x for x in range(0, 19, 2)] for x in my_list: print(x)
NP54 被5整除的数字
# 根据for后面的if的布尔值生成 my_list = [x for x in range(1, 50+1) if x % 5 == 0] for x in my_list: print(x)
NP55 2的次方数
# 生成的时候再加工 my_list = [2x for x in range(1, 10+1) ] for x in my_list: print(x)
NP56 列表解析
print([x for x in range(0, 9+1)])
NP57 格式化清单
list = [apple, ice cream, watermelon, chips, hotdogs, hotpot] while len(list): list.pop() print(list)
NP58 找到HR
users_list = [Niuniu, Niumei, HR, Niu Ke Le,GURR, LOLO] for name in users_list: if name == HR: print(Hi, HR! Would you like to hire someone?) else : print(fHi, { name}! Welcome to Nowcoder!)
NP59 提前结束的循环
list = [3, 45, 9, 8, 12, 89, 103, 42, 54, 79] num = int(input()) for x in list : if x == num : break else : print(x)
NP60 跳过列表的某个元素
# 遍历range默认是数字 for x in range(1, 15 + 1): if x != 13: print(x, end= )
NP61 牛牛的矩阵相加
# 二维数组 matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] num = int(input()) for i in range(len(matrix)): for j in range(len(matrix[i])): matrix[i][j] *= num print(matrix) # print([[x*num for x in i] for i in [[1,2,3],[4,5,6],[7,8,9]] ])
08 元组
NP62 运动会双人项目
str1 = input() str2 = input() tup = (str1, str2) # 元组不能修改 # (NiuNiu, NiuMei) print(tup)
NP63 修改报名名单
entry_form = ("Niuniu", "Niumei") print(entry_form) # 异常捕获 try: # 元组不可修改 entry_form[1] = Niukele except TypeError: print("The entry form cannot be modified!")
NP64 输出前三同学的成绩
tup = tuple(input().split()) print(tup[:3])
NP65 名单中出现过的人
tup = (Tom, Tony, Allen, Cydin, Lucy, Anna) print(tup) name = input() if name in tup : print("Congratulations!") else : print("What a pity!")
NP66 增加元组的长度
tup = tuple(range(1,6)) print(tup) print(len(tup)) # 可以用 += 猜测还是对象覆盖 tup += tuple(x for x in range(6, 10 + 1)) print(tup) print(len(tup))
09 字典
字典说白了就是键值对
NP67 遍历字典
operators_dict = { <: less than, ==: equal } print("Here is the original dict:") # 默认遍历key for key in sorted(operators_dict) : print("Operator %s means %s." %(key, operators_dict[key])) # 动态添加 operators_dict[>] = greater than print(" The dict was changed to:") # .items() 遍历key,val for key, val in sorted(operators_dict.items()): print("Operator %s means %s." %(key, val))
NP68 毕业生就业调查
survey_list = [Niumei, Niu Ke Le, GURR, LOLO] result_dict = { Niumei: Nowcoder, GURR: HUAWEI } for name in survey_list : # 根据key来in if name in result_dict: print("Hi, %s! Thank you for participating in our graduation survey!" %name) else : print("Hi, {}! Could you take part in our graduation survey?" .format(name))
NP69 姓名与学号
my_dict_1 = { name: Niuniu, Student ID: 1} my_dict_2 = { name: Niumei, Student ID: 2} my_dict_3 = { name: Niu Ke Le, Student ID: 3} dict_list = [] dict_list.append(my_dict_1) dict_list.append(my_dict_2) dict_list.append(my_dict_3) for it in dict_list: print("%ss student id is %d." %(it["name"], it["Student ID"]))
NP70 首都
# 键值对套键值对 cities_dict = { Beijing: { Capital: China}, Moscow: { Capital: Russia}, Paris: { Capital: France} } for it in sorted(cities_dict) : print(f"{ it} is the capital of { cities_dict[it][Capital]}!")
NP71 喜欢的颜色
result_dict = { Allen: [red, blue, yellow], Tom: [green, white, blue], Andy: [black, pink] } # 指定遍历key for it in sorted(result_dict.keys()): print(f"{ it}s favorite colors are:") for color in result_dict[it]: print(color)
NP72 生成字典
name = input().split() language = input().split() # zip() 函数 word = dict(zip(name, language)) print(word)
NP73 查字典
words = { a: [apple, abandon, ant], b: [banana, bee, become], c: [cat, come], d: [down] } str = input() for word in words[str]: print(word, end=" ")
NP74 字典新增
letter = input() word = input() words = { "a": ["apple", "abandon", "ant"], "b": ["banana", "bee", "become"], "c": ["cat", "come"], "d": "down", # 最后的,可加可不加 letter: word, } print(words)
NP75 使用字典计数
str = input() word = { } for ch in str : # 也可以用in判断 try : word[ch] += 1 except : # 初始必须设置值 word[ch] = 1 print(word)
10 内置函数
NP76 列表的最值运算
arr = [int(x) for x in input().split()] print(max(arr)) print(min(arr))
NP77 朋友的年龄和
arr = [int(x) for x in input().split()] print(sum(arr))
NP78 正数输出器
# 然而0不算正数 print(abs(int(input())))
NP79 字母转数字
# ord 十进制 print(ord(input()))
NP80 数字的十六进制
# hex 十六进制 print(hex(int(input())))
NP81 数字的二进制表示
# bin 二进制 print(bin(int(input())))
NP82 数学幂运算
x, y = map(int, input().split()) print(x y) print(pow(y, x))
NP83 错误出现的次数
list = input().split() print(list.count(0))
NP84 列表中第一次出现的位置
list = input().split() # 不存在返回非法值 print(list.index(NiuNiu))
NP85 字符的类型比较
str = input() print(str.isalpha()) print(str.isdigit()) print(str.isspace())
NP86 字符子串的查找
long_str = input() # 三个参数指定搜索范围,一个参数默认全范围 print(long_str.find(NiuNiu, 0, len(long_str)))
NP87 子串的数量
str = input() print(str.count(Niu, 0, len(str)))
NP88 句子拆分
# 默认分割成字符串 print(input().split())
NP89 单词造句
arr = [] endstr = 0 # 直到endstr位置,每行接收的东西 for line in iter(input, endstr): arr.append(line) print(" ".join(arr))
NP90 修正错误的字母
str = input(); # 默认全部替换 print(str.replace("a*", "ab")) # 指定,最多替换cnt次 # print(str.replace("a*", "ab", cnt))
NP91 小数位修正
num = float(input()) # 四舍五入保留至最多两位小数 print(round(num, 2))
NP92 公式计算器
str = input() # 根据表达式计算 这个挺强大的 print(eval(str))
NP93 创建集合
st = set(input().split()) print(sorted(st))
11 面向对象
NP94 函数求差
# 可以不指点类型和返回值 # 不return的话默认返回None def cal(a, b) : return a - b x = int(input()) y = int(input()) print(cal(x, y)) print(cal(y, x))
NP95 兔子的数量
# 指定参数类型和返回值 def fib(n : int) -> int : if n <= 2 : return n + 1 else : return fib(n-1) + fib(n-2) n = int(input()) print(fib(n))
NP96 球的表面积
import math def calBall(n) : # 需要导入math包 # pow可以不用math. return 4 * math.pi * math.pow(n, 2) arr = [1,2,4,9,10,13] for num in arr : print("%.2f" %calBall(num))
NP97 班级管理
name = input() id = input() score = int(input()) list = input().split() print("%ss student number is %s, and his grade is %d. He submitted %d assignments, each with a grade of " %(name, id, score, len(list)) , end="") for ch in list : print(ch, end=" ")
NP98 修改属性1
class Employee(): # 构造 def __init__(self, name: str, salary: int): self.name = name self.salary = salary # 第一个参数必须是self 当然可以写成别的名称 def setAge(self, age: int): self.age = age def printclass(self): try: print("%ssalary is %d, and his age is %d" % (self.name, self.salary, self.age)) except: print("Error! No age") name = input() salary = int(input()) e = Employee(name, salary) e.printclass() age = int(input()) e.setAge(age) e.printclass()
NP99 修改属性2
class Employee(): def __init__(self, name: str, salary: int): self.name = name self.salary = salary def printclass(self): print("%ssalary is %d, and his age is %d" % (self.name, self.salary, self.age)) name = input() salary = int(input()) age = int(input()) e = Employee(name, salary) # hasattr 是否有该成员变量 print(hasattr(e, age)) if not hasattr(e, age): # 添加成员变量 setattr(e, age, age) e.printclass()
NP100 重载运算
class Coordinate(): x, y = 0, 0 def __init__(self, x: int, y: int): self.x = x self.y = y # to_string 重载 def __str__(self): return "(" + str(self.x) + ", " + str(self.y) + ")" # 根据需求返回lhs还是rhs还是新值 def __add__(self, rhs): return Coordinate(self.x + rhs.x, self.y + rhs.y) x1, y1= map(int, input().split()) point1 = Coordinate(x1, y1) x2, y2= map(int, input().split()) point2 = Coordinate(x2, y2) point3 = point1 + point2 print(point3)
12 正则表达式
正则表达之我不熟悉,基本都是cv的
NP101 正则查找网址
import re cmp = https://www str = input() # 从开头匹配到第一位不匹配的范围 # 元组的形式 print(re.match(cmp, str).span())
NP102 提取数字电话
import re str = input() # r表示纯字符串 # 全部数字信息 # 0-9的数字 print(re.sub(r[^0-9], , str)) # D 等价于 数字 # d 等价于 非数字 print(re.sub(rD, , str))
NP103 截断电话号码
import re str = input() # 提取的仅包含数字和-的电话号码 res = re.match(r[0-9|-]*, str) print(res.group())