Python Example6.buy-lollipop买棒棒糖输入格式输出格式输入输出样例项目说明:Implements7.Flight航班时间输入格式输出格式数据范围输入样例:输出样例:Implements8.LOGO题目描述输入格式输出格式样例输入规定9.增量元素之间的最大差值样例1样例2Implements10.LOGO++题目背景输入格式输出格式样例输入规则ImplementsValidate InputImplementsCalculate Retire ScheduleImplementsisAnagramImplementsInsomnia cureDescriptionInputOutputExamplesInput1Output1Input2Output2NoteXenia and RingroadDescriptionInputOutputInput1Output1Input2Output2NoteImplementsTaxiDescriptionInputOutputExamplesInputOutputInputOutputImplementsStreamImplementsCSVSpecial TypingInputOutputExampleNoteImplementsGrammar LessonsInputOutputExamplesImplementsTo Do ListImplementsgrade-histogram要求ImplementsTwo-sumImplementsString-FormattingImplementsAlice, Bob and ChocolateDescriptionInputOutputExamplesInputOutputImplementsMagnetsInputOutputExamplesinputoutputinputoutputImplements
已知在思远哥哥的糖果商店,一根棒棒糖的价格是 6 元 7 角,而你有 a 元 b 角硬币,你最多能买多少根棒棒糖?
输入只有一行两个非负整数,以空格分隔,分别表示 a 和 b 。
输出一行一个整数,表示最多能买多少根棒棒糖。
输入1
xxxxxxxxxx20 3
输出1
xxxxxxxxxx3
输入2
xxxxxxxxxx19 15
输出2
xxxxxxxxxx3
src目录下为题目代码源文件,需要完成的内容为buy_lolipop.py里的方法。 src目录下的init.py文件不需要改动。
test目录下为测试用例文件,不可进行修改。
xxxxxxxxxxdef cal_amount_of_lolipop(): # your code here ^_^ a, b = map(int, input().split()) c = (a * 10 + b) // 67 print(c) return思远哥哥要去美国留学了。
思远哥哥的女朋友发现他上午十点出发,上午十二点到达美国,于是感叹到“现在飞机飞得真快,两小时就能到美国了”。但在仔细观察后发现飞机的起降时间都是当地时间。由于北京和美国东部有 12 小时时差,故飞机总共需要 14 小时的飞行时间。不久后思远哥哥的女朋友去冰岛旅游,思远哥哥并不知道冰岛与北京的时差。但是他得到了女朋友来回航班的起降时间。思远哥哥想知道女朋友的航班飞行时间是多少。
对于一个可能跨时区的航班,给定来回程的起降时间。假设飞机来回飞行时间相同,求飞机的飞行时间。
一个输入包含一组数据。
每组数据包含两行,第一行为去程的起降时间,第二行为回程的起降时间。
起降时间的格式如下:
h1:m1:s1 h2:m2:s2 h1:m1:s1 h3:m3:s3 (+1) h1:m1:s1 h4:m4:s4 (+2) 第一种格式表示该航班在当地时间h1时m1分s1秒起飞,在当地时间当日h2时m2分s2秒降落。
第二种格式表示该航班在当地时间h1时m1分s1秒起飞,在当地时间次日h2时m2分s2秒降落。
第三种格式表示该航班在当地时间h1时m1分s1秒起飞,在当地时间第三日h2时m2分s2秒降落。
对于每一组数据输出一行一个时间hh:mm:ss,表示飞行时间为hh小时mm分ss秒。
注意,当时间为一位数时,要补齐前导零,如三小时四分五秒应写为03:04:05。
保证输入时间合法(0≤h≤23,0≤m,s≤59),飞行时间不超过24小时。
xxxxxxxxxx样例一:17:48:19 21:57:2411:05:18 15:14:23样例二:17:21:07 00:31:46 (+1)23:02:41 16:13:20 (+1)样例三:10:19:19 20:41:2422:19:04 16:41:09 (+1)
xxxxxxxxxx04:09:0512:10:3914:22:05
xxxxxxxxxxdef to_second(h, m, s): return h * 3600 + m * 60 + sdef to_hms(seconds): h, seconds = divmod(seconds, 3600) m, s = divmod(seconds, 60) return f"{int(h):02d}:{int(m):02d}:{int(s):02d}"def calc_flight_time(depart, arrive, temp): depart_time = to_second(*depart) arrive_time = to_second(*arrive) arrive_time += 24 * 3600 * temp # 补上时间 flight_time = arrive_time - depart_time return flight_timedef flight_calculation(): s = input().split() temp1 = 0 time1 = list(map(int, s[0].split(":"))) time2 = list(map(int, s[1].split(":"))) if len(s) == 3: if s[2] == '(+1)': temp1 = 1 elif s[2] == '(+2)': temp1 = 2 else: temp1 = 0 Duration1 = calc_flight_time(time1, time2, temp1) s = (input()).split() time3 = list(map(int, s[0].split(":"))) time4 = list(map(int, s[1].split(":"))) temp2 = 0 if len(s) == 3: if s[2] == '(+1)': temp2 = 1 elif s[2] == '(+2)': temp2 = 2 else: temp2 = 0 Duration2 = calc_flight_time(time3, time4, temp2) if Duration1 != Duration2: Duration = (Duration2 + Duration1) / 2 print(to_hms(Duration)) else: print(to_hms(Duration2)) # enter your code hereflight_calculation()简单模拟LOGO语言的小乌龟。
有一个大小为10*10的方格棋盘,最左上角的格子中有一个正不动的小乌龟。你需要让这个小乌龟能按照一定的指示在棋盘上画出一些内容。我们会输入n条指令,每条指令有2或3个操作数。第一个是移动的方向:U、D、L、R分别代表接下来像上/下/左/右移动;第二个是移动的步数:每移动一步后都会在脚下的格子中填上特定的字符。第三个操作数则是要填的字符,如果它不存在则沿用上一次移动所填充的字符。在移动的过程中,如果乌龟在指令下移动到了棋盘之外,则立刻输出Error并结束程序。若n条指令执行完,则输出整个棋盘上所画的内容。
第一行一个数n,为指令的个数
接下来n行,每行2或3个字符,其中第一个为移动方向(UDLR中的一个),第二个为移动步数(0-9),第三个为一个字符(如果有)
Error!或10行10列字符,表示最后的棋盘的结果。
输入
xxxxxxxxxx2R 3 XD 5 Y
输出
xxxxxxxxxx0XXX000000000Y000000000Y000000000Y000000000Y000000000Y0000000000000000000000000000000000000000000000
注意此处的‘0’代表空白符,实际输出需用空白符代替。
输入
xxxxxxxxxx3D 2 1R 4U 1 2
输出
xxxxxxxxxx0000000000100020000011111000000000000000000000000000000000000000000000000000000000000000000000000000
输入
xxxxxxxxxx3R 1 NU 3 ED 7 G
输出
xxxxxxxxxxError!
指令条数1<=n<=15,保证不会出现不符合以上格式的指令,且第一条指令一定会指定要画的符号。
每次移动步数不会为0。
项目说明:
src目录下为题目代码源文件,需要完成的内容为logo.py里的logo_play()方法。 src目录下的init.py文件不需要改动。
xxxxxxxxxxdef logo_play(): get_direct = int(input()) count = 1 matrix = [] for i in range(10): row = [] for j in range(10): row.append(0) matrix.append(row) # initialize a two dim 10*10 list character = '0' x, y = (0, 0) while count <= get_direct: count += 1 s = input() if len(s) == 3: movement, distance = s.split() else: movement, distance, character = s.split() if movement == 'U': y -= int(distance) if y >= 0: for i in range(int(distance)): matrix[x][y + int(distance) - i - 1] = character else: print("Error!") return elif movement == 'D': y += int(distance) if y < 10: for i in range(int(distance)): matrix[x][y - int(distance) + i + 1] = character else: print("Error!") return elif movement == 'L': x -= int(distance) if x >= 0: for i in range(int(distance)): matrix[x + int(distance) - i - 1][y] = character else: print("Error!") return elif movement == 'R': x += int(distance) if x < 10: for i in range(int(distance)): matrix[x - int(distance) + i + 1][y] = character else: print("Error!") return for j in range(10): for i in range(10): if matrix[i][j] != 0: print(matrix[i][j], end='') else: print(" ", end='') print('') return
在一行中输入若干个整数,视为数组nums(长度为n), 请你计算 nums[j] - nums[i] 能求得的 最大差值 ,其中 0 <= i < j < n 且 nums[i] < nums[j] 。
返回 最大差值 。如果不存在满足要求的 i 和 j ,返回 -1 。
小提示:想过这道题的test,你可能需要知道print函数更多的一些细节哦ʕ •ᴥ•ʔ
xxxxxxxxxxinput: 7 1 5 4output: 4
xxxxxxxxxxinput: 9 4 3 2output: -1
xxxxxxxxxxdef cal_max_difference(): str_list = input().split() listing = [] for str_num in str_list: int_num = int(str_num) listing.append(int_num) length = len(listing) temp = 0 for i in range(length): for j in range(i + 1, length): if listing[i] < listing[j]: temp = max(temp, listing[j] - listing[i]) if temp == 0: print(-1, end='') else: print(temp, end='')同学们在上一次作业中完成了一个简单的LOGO模拟器,可以进行简单的绘画功能。这次同学们可以完成一些复杂指令,实现一些对复杂图形的绘制!
本次作业首先新增了两条指令:pen_up和pen_down,表示暂停或开始绘画模式。在暂停绘画的状态下小乌龟移动不会在路径上留下字符,只有在开始绘画的状态下才会留下字符。原有的移动功能会以move开头,操作数不变。然后新增三条复杂指令:cross、rect、rect_f。cross命令有1或2个操作数。rect、rect_f有2或3个操作数。最后还有一条指令end,它会结束绘图程序并输出棋盘。
cross命令会以小乌龟为中心画一个十字,十字的长度为第一个操作数,绘画的字符使用第二个操作数(如没有则沿用之前的画笔)。rect命令会以小乌龟的起始位置为左上角,向右下画出一个矩形。矩形的横向、纵向宽度分别为第一个、第二个操作数。第三个操作数同样是指定可能的画笔字符。rect_f命令大体与rect命令相同,但它会用当前的画笔填充所画的矩形。以上三种指令执行完毕后,小乌龟需要回到原先的位置,即指令不会让它的位置改变。
同样的,小乌龟不能移到屏幕外面,一旦出现则输出Error并结束模拟。
tips
1:以上几条命令能否用已有的move指令和pen_up、pen_down指令组合实现?
2:如果将move封装为函数,如何实现在移动完成后改变小乌龟的状态?
3:你可以实现一条print指令来便于你调试。测试用例里不会出现该条指令。
4:在题目中未明确的指令组合(比如连续两次pen_up)属于未定义行为。未定义行为你可以任意实现,测试用例中不会出现未定义行为。
若干行指令,每行有指令的名称与一定数量的操作数。
最后一行一定是end指令。
Error!或10行10列字符,表示最后的棋盘的结果。
输入
xxxxxxxxxxrect 3 5 aend
输出
xxxxxxxxxxaaa0000000a0a0000000a0a0000000a0a0000000aaa000000000000000000000000000000000000000000000000000000000
同样的,此处的‘0’代表空白符,实际输出需用空白符代替。
输入
xxxxxxxxxxrect_f 4 6 bend
输出
xxxxxxxxxxbbbb000000bbbb000000bbbb000000bbbb000000bbbb000000bbbb0000000000000000000000000000000000000000000000
输入
xxxxxxxxxxpen_upmove D 3move R 3pen_downcross 3 cend
输出
xxxxxxxxxx000c000000000c000000000c000000ccccccc000000c000000000c000000000c000000000000000000000000000000000000
在cross指令完毕后,小乌龟停在第四行第四列的位置。
输入
xxxxxxxxxxpen_upmove D 3move R 3pen_downcross 4 cend
输出
xxxxxxxxxxError!
指令条数1<=n<=20,保证不会出现不符合格式的指令。每次移动步数不会为0。指令序列中第一条在开始绘画状态下执行的指令一定有要画的字符。
项目说明:
src目录下为题目代码源文件,需要完成的内容为logo.py里的logo_play()方法。 src目录下的init.py文件不需要改动。
xxxxxxxxxxmatrix = []x, y = 0, 0ErrorCatch = TrueUp_Or_Down = True# define as global variablesdef change_place(direction, distance): global x, y if direction == 'U': y -= distance if y >= 0: pass else: print("Error!") return elif direction == 'D': y += distance if y < 10: pass else: print("Error!") return elif direction == 'L': x -= distance if x >= 0: pass else: print("Error!") return elif direction == 'R': x += distance if x < 10: pass else: print("Error!") return returndef logo_play(): global matrix global ErrorCatch global x, y global Up_Or_Down matrix = [] x, y = 0, 0 ErrorCatch = True Up_Or_Down = True for i in range(10): row = [] for j in range(10): row.append(' ') matrix.append(row) # initialize a two dim 10*10 list character = ' ' while True: line = input() string_cut = line.split() if 'end' in line: for j in range(10): for i in range(10): print(matrix[i][j], end='') print('') return elif line == 'pen_down': Up_Or_Down = True elif line == 'pen_up': Up_Or_Down = False elif string_cut[0] == 'move': direction = string_cut[1] distance = int(string_cut[2]) if len(string_cut) == 4: character = string_cut[3] move(direction, distance, character) change_place(direction, distance) elif string_cut[0] == 'cross': length = int(string_cut[1]) if len(string_cut) == 3: character = string_cut[2] cross(length, character) elif string_cut[0] == 'rect_f': width = int(string_cut[1]) length = int(string_cut[2]) if len(string_cut) == 4: character = string_cut[3] rect_f(width, length, character) elif string_cut[0] == 'rect': width = int(string_cut[1]) length = int(string_cut[2]) if len(string_cut) == 4: character = string_cut[3] rect(width, length, character) if not ErrorCatch: print("Error!") returndef move(direction, distance, character): global matrix global x, y global ErrorCatch if not Up_Or_Down: return if direction == 'U': if y - distance >= 0: for i in range(distance): matrix[x][y - i - 1] = character else: ErrorCatch = False return elif direction == 'D': if y + distance < 10: for i in range(distance): matrix[x][y + i + 1] = character else: ErrorCatch = False return elif direction == 'L': if x - distance >= 0: for i in range(distance): matrix[x - i - 1][y] = character else: ErrorCatch = False return elif direction == 'R': if x + distance < 10: for i in range(distance): matrix[x + i + 1][y] = character else: ErrorCatch = False returndef cross(length, character): global x, y global matrix global ErrorCatch if Up_Or_Down: matrix[x][y] = character for i in range(length): if y + i + 1 >= 10 or y - i - 1 < 0 or x - i - 1 < 0 or x + i + 1 >= 10: ErrorCatch = False return if Up_Or_Down: matrix[x][y + i + 1] = character matrix[x][y - i - 1] = character matrix[x - i - 1][y] = character matrix[x + i + 1][y] = characterdef rect_f(width, length, character): global x, y global matrix global ErrorCatch if Up_Or_Down: if x + width - 1 >= 10 or x + width - 1 < 0 or y + length - 1 >= 10 or y + length - 1 < 0: ErrorCatch = False return for i in range(width): for j in range(length): matrix[x + i][y + j] = characterdef rect(width, length, character): global x, y global matrix global ErrorCatch if Up_Or_Down: if x + width - 1 >= 10 or x + width - 1 < 0 or y + length - 1 >= 10 or y + length - 1 < 0: ErrorCatch = False return for i in range(width): matrix[x + i][y] = character matrix[x + i][y + length - 1] = character for i in range(length): matrix[x][y + i] = character matrix[x + width - 1][y + i] = characterWrite a program to validate the input data(First Name, Last Name, EmployeeID, Zip code). The first name and the last name must be filled in, which at least two letters. EmployeeID must be in such format:"AA-1234". Zip code must be numeric.
从命令后得到 first name、last name、 Zip code 和 EmployeeID. 然后程序判断:
项目说明:
src目录下为题目代码源文件,需要完成的内容为validate.py里的validate方法。 src目录下的init.py文件不需要改动。
test目录下为测试用例文件,不可进行修改。
示例:
xxxxxxxxxx输入:Enter the first name:JEnter the last name:Enter the ZIP code: ABCDEEnter an employee ID: A12-1234输出:(不包含每行开头的‘* ’部分;不要输出额外的内容,否则会影响结果判断的正确性)* "J" is not a valid first name. It is too short.* The last name must be filled in.* The ZIP code must be numeric.* A12-1234 is not a valid ID.
xxxxxxxxxx#! /usr/bin/env python# -*- coding: utf-8 -*-import redef validate(): print('dd') print('dd') string = input() pattern = r'[a-zA-Z]+' match = re.search(pattern, string) if match: if len(match.group()) == 1: print('\"{}\" is not a valid first name. It is too short.'.format(string)) else: print('The first name must be filled in.') string = input() pattern = r'[a-zA-Z]+' match = re.search(pattern, string) if match: if len(match.group()) == 1: print('\"{}\" is not a valid last name. It is too short.'.format(string)) else: print('The last name must be filled in.') num = input() if not num.isdecimal(): print("The ZIP code must be numeric.") string = input() pattern = r'^[A-Z]{2}-\d{4}$' if not re.match(pattern, string): print('{} is not a valid ID.'.format(string))Calculate Retire Schedule根据输入的当前年龄与退休年龄,计算退休年份
示例,->表示输出,<-表示输入:
-> What is your current age?
<- 25
-> At what age would you like to retire?
<- 65
-> You have 40 years left until you can retire.
-> It's 2018, so you can retire in 2058.
注意:
请使⽤系统当前时间进行计算
xxxxxxxxxx#! /usr/bin/env python# -*- coding: utf-8 -*-import datetimedef calculate(): current_age = int(input("What is your current age?")) retire_age = int(input("At what age would you like to retire?")) duration = retire_age - current_age print("You have {} years left until you can retire.".format(duration)) current_time = datetime.datetime.now() now = current_time.year retire_year = now + duration print("It's {}, so you can retire in {}.".format(now,retire_year))1.编写一个函数,比较两个字符串是否为字母异位,也就是包含字母一样,只是顺序不同:
2.函数参数为两个字符串str1,str2:
返回True或者False。
注意检查词长
项目说明:
src目录下为题目代码源文件,需要完成的内容为isAnagram_cal.py里的方法。 src目录下的init.py文件不需要改动。
test目录下为测试用例文件,不可进行修改。
示例:
xxxxxxxxxx函数接收输入:str1:notestr2:tone返回:True
xxxxxxxxxxdef is_anagram(str1, str2): len1 = len(str1) len2 = len(str2) if len1 != len2: return False elif len1 == 0 and len2 == 0: return True for i in range(len1): if str1.count(str1[i]) != str2.count(str1[i]): return False return Truexxxxxxxxxx«One dragon. Two dragon. Three dragon», — the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine.However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and she was fighting them off. Every *k*-th dragon got punched in the face with a frying pan. Every *l*-th dragon got his tail shut into the balcony door. Every *m*-th dragon got his paws trampled with sharp heels. Finally, she threatened every *n*-th dragon to call her mom, and he withdrew in panic.How many imaginary dragons suffered moral or physical damage tonight, if the princess counted a total of *d* dragons?
Input data contains integer numbers k, l, m, n and d, each number in a separate line (1 ≤ k, l, m, n ≤ 10, 1 ≤ d ≤ 105>).
Output the number of damaged dragons.
xxxxxxxxxx123412
xxxxxxxxxx12
xxxxxxxxxx234524
xxxxxxxxxx17
In the first case every first dragon got punched with a frying pan. Some of the dragons suffered from other reasons as well, but the pan alone would be enough.
In the second case dragons 1, 7, 11, 13, 17, 19 and 23 escaped unharmed.
xxxxxxxxxx"""write your code in method sove"""def solve(): k = int(input()) l = int(input()) m = int(input()) n = int(input()) total = int(input()) left_ones = total for i in range(1, total + 1): if i % k != 0 and i % l != 0 and i % m != 0 and i % n != 0: left_ones -= 1 print(left_ones) returnxxxxxxxxxxXenia lives in a city that has *n* houses built along the main ringroad. The ringroad houses are numbered 1 through *n* in the clockwise order. The ringroad traffic is one way and also is clockwise.Xenia has recently moved into the ringroad house number 1. As a result, she's got *m* things to do. In order to complete the *i*-th task, she needs to be in the house number *a*<sub>i</sub> and complete all tasks with numbers less than *i*. Initially, Xenia is in the house number 1, find the minimum time she needs to complete all her tasks if moving from a house to a neighboring one along the ringroad takes one unit of time.
The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105). The second line contains m integers a1, a2, ..., am (1 ≤ ai ≤ n). Note that Xenia can have multiple consecutive tasks in one house.
Print a single integer — the time Xenia needs to complete all tasks.
xxxxxxxxxx4 33 2 3
xxxxxxxxxx6
xxxxxxxxxx4 32 3 3
xxxxxxxxxx2
In the first test example the sequence of Xenia's moves along the ringroad looks as follows: 1 → 2 → 3 → 4 → 1 → 2 → 3. This is optimal sequence. So, she needs 6 time units.
xxxxxxxxxx"""write your code in method solve"""def solve(): n, m = map(int, input().split()) mapping = input().split() current = 1 lap = 0 for i in range(m): if current > int(mapping[i]): lap += 1 current = int(mapping[i]) else: current = int(mapping[i]) print(current - 1 + lap * n) returnAfter the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)?
The first line contains integer n (1 ≤ n ≤ 105) — the number of groups of schoolchildren. The second line contains a sequence of integers s1, s2, ..., sn (1 ≤ si ≤ 4). The integers are separated by a space, si is the number of children in the i-th group.
Print the single number — the minimum number of taxis necessary to drive all children to Polycarpus.
xxxxxxxxxx51 2 4 3 3
xxxxxxxxxx4
xxxxxxxxxx82 3 4 4 2 1 3 1
xxxxxxxxxx5
xxxxxxxxxx"""write your code in method solve"""def solve(): group_num = int(input())#ok details = input().split() one = 0 two = 0 three = 0 four = 0 for j in range(group_num): i = int(details[j]) if i == 2: two += 1 elif i == 3: three += 1 elif i == 1: one += 1 elif i == 4: four += 1 car = 0 left = 0 car1 = max(one, three) more = one - three car1 -= more // 4 * 3 more -= more // 4 * 4 car2 = two // 2 if two % 2 != 0: car2 += 1 if more > 0 and two % 2 != 0: car1 -= 1 car3 = four car = car1 + car2 + car3 print(car) return给定一个名称列表,其中一些名称仅包含一个字符
要求返回一个逗号分隔的字符串,该字符串中不包含单字母的名称,每个名称有且仅有首字母大写,且按照原顺序排列
示例参数:
xxxxxxxxxxList('neal', 's', 'stu', 'j', 'rich', 'bob')
示例返回:
xxxxxxxxxx'Neal,Stu,Rich,Bob'
xxxxxxxxxx#! /usr/bin/env python# -*- coding: utf-8 -*-def process(param): tmp = [] for strrr in param: if len(strrr) > 1: tmp.append(strrr.title()) return ','.join(tmp)本次作业,我们基于CSV实现一个简(jian)易(lou)的数据库。
CSV文件即逗号分隔值文件,示例:
xxxxxxxxxxSiyuanCen,ceo,85900JingLan,staff,51500JinboHu,manager,66500
三列的属性分别为Name,Title,Salary. 约定本题中所有的csv文件都由这三列构成。
您需实现以下操作:
INSERT Name,Title,Salary:向csv文件末尾追加写入一行 Name,Title,Salary.
SHOWALL:读取内容后,您需按Salary升序排序,并计算Salary的平均值AVG。输出格式为表格形式,各列左对齐,两列间隔一个空格(以列中最长字符串为基准)。最后需打印Salary平均值。示例:
xxxxxxxxxxName Title SalaryJingLan staff 51500.00JinboHu manager 66500.00SiyuanCen ceo 85900.00AVG:67966.66
输入:
xxxxxxxxxx第一行输入一个整数n,为需执行的指令的行数接下来n行,为指令
注意:
要读取的文件名将以参数的形式传递到待编写的函数中
Salary和平均值输出到小数点后两位
rawdata开头的文件请勿修改,它们保证在测试结束后将resource-x.csv文件恢复原状。自我测试的过程中请留意resource-x.csv的变化。
本地使用Pycharm测试时,若发生找不到文件的错误,请修改test_read_csv.py:
xxxxxxxxxxresource1 = 'test/resource-1.csv'resource2 = 'test/resource-2.csv'raw1 = 'test/rawdata1-ReadOnly.csv'raw2 = 'test/rawdata2-ReadOnly.csv'改为:
xxxxxxxxxxresource1 = '../test/resource-1.csv'resource2 = '../test/resource-2.csv'raw1 = 'rawdata1-ReadOnly.csv'raw2 = 'rawdata2-ReadOnly.csv'xxxxxxxxxx#! /usr/bin/env python# -*- coding: utf-8 -*-import csvfilename = []count = 0def getcommand(file): global filename,count n = int(input()) count += 1 if count == 1: with open(file, 'a', newline='') as f: writer = csv.writer(f) writer.writerow('') filename.append(file) for i in range(n): line = input().split() if 'INSERT' in line: with open(file, 'a', newline='') as f: writer = csv.writer(f) name, title, salary = line[1].split(',') writer.writerow([name, title, salary]) if 'SHOWALL' in line: with open(file) as f: rows = [] for row in f: row = row.split(',') if row: rows.append(row) sorted_rows = sorted(rows, key=lambda x: int(x[2])) max_lengths = [max([len(row[i]) for row in sorted_rows]) for i in range(3)] header = ["Name", "Title", "Salary"] table = [] table.append( f"{header[0]:<{max_lengths[0] + 1}}{header[1]:<{max_lengths[1] + 1}}{header[2]:<{max_lengths[2]}}") for row in sorted_rows: table.append( f"{row[0]:<{max_lengths[0] + 1}}{row[1]:<{max_lengths[1] + 1}}{float(row[2]):<{max_lengths[2] + 1}.2f}") avg_salary = sum(float(row[2]) for row in rows) / len(rows) table.append(f"AVG:{avg_salary:.2f}") print("\n".join(table).strip()) count = 0思远哥哥买了新键盘,价值不菲。他邀请大家来试用键盘,但前提是回答出以下问题。
您将获得两个字符串s和t,两者都由小写的英文字母组成。您将逐个字符地键入字符串s,从第一个字符到最后一个字符。
特别之处在于,键入字符时,您可以按
Backspace按钮,而不是按与之对应的按钮。Backspace会删除您刚刚键入的最后一个字符(如果您键入的字符串中没有字符,则不执行任何操作)。例如,如果s是"abcbd",并且您按Backspace而不是键入第一个和第四个字符,您将获得字符串"bd"(第一次按Backspace不删除任何字符,第二次按删除字符"c")。另一个例子,如果s是"abcaa",并且您用Backspace键代替最后两个字母,则得到的文本为"a"。您的任务是确定是否可以通过以上方式,从字符串s获取字符串t.
xxxxxxxxxx第一行是一个整数 q (1≤q≤10^5) ― 测试用例的数量。每个测试用例的第一行是字符串s (1≤s的长度≤10^5).s中的每个字符是小写的英文字母。每个测试用例的第二行是字符串t (1≤t的长度≤10^5).t中的每个字符是小写的英文字母。保证所有测试用例中字符串中的字符总数不超过10^5.
xxxxxxxxxx对于每个测试用例,如果可以按本题的方式从s得到t,请打印"YES",否则,打印"NO".
Input
xxxxxxxxxx4abababaabababbaaaaaaaaababaababa
Output
xxxxxxxxxxYESNONOYES
解释一下上述用例。
为了从"ababa"中获取"ba",您可以按Backspace而不是键入第一个和第四个字符。
从"ababa"无法获取"bb"。
从"aaa"无法获取"aaaa"。
为了从"aababa"获得"ababa",您必须按Backspace而不是键入第一个字符,然后键入所有剩余的字符。
xxxxxxxxxxdef special_typing(): q = int(input()) for k in range(q): s = input() t = input() Error = False for i in range(len(s)): if s[i] == t[0]: if len(s) - i < len(t) or (len(s) - i - len(t)) % 2 != 0: continue now = 1 j = i + 1 while j <= len(s) - 1: if now == len(t): if (len(s) - 1 - j) % 2 == 1: Error = False break if s[j] == t[now]: now += 1 j += 1 else: j += 2 if now == len(t): if (len(s) - j) % 2 == 0: Error = True if Error: print("YES") else: print("NO") returnPetya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules: There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb. There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine. Masculine adjectives end with -lios, and feminine adjectives end with -liala. Masculine nouns end with -etr, and feminime nouns end with -etra. Masculine verbs end with -initis, and feminime verbs end with -inites. Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language. It is accepted that the whole word consists of an ending. That is, words "lios", "liala", "etr" and so on belong to the Petya's language. There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications. A sentence is either exactly one valid language word or exactly one statement. Statement is any sequence of the Petya's language, that satisfy both conditions:
Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs. All words in the statement should have the same gender. After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language.
The first line contains one or more words consisting of lowercase Latin letters. The overall number of characters (including letters and spaces) does not exceed 105.
It is guaranteed that any two consecutive words are separated by exactly one space and the input data do not contain any other spaces. It is possible that given words do not belong to the Petya's language.
If some word of the given text does not belong to the Petya's language or if the text contains more that one sentence, print "NO" (without the quotes). Otherwise, print "YES" (without the quotes).
input
petr output YES
input
etis atis animatis etis atis amatis
output
NO
input
nataliala kataliala vetra feinites
output
YES
xxxxxxxxxxdef isPetyaLanguage(): # judge whether the word is Petya's language inputs = input() words = inputs.split() num = len(words) # judge whether it's Petya's language and its grammar # and the Masculine noun should match with its Masculine verb so was the Feminine noun if num == 1: if is_noun(words[0]) != 0 or is_verb(words[0]) != 0 or is_adjective(words[0]) != 0: print('YES') else: print('NO') elif num == 2: if is_adjective(words[0]) != 0 and is_noun(words[1]) != 0: if is_adjective(words[0]) == is_noun(words[1]): print('YES') else: print('NO') elif is_verb(words[1]) != 0 and is_noun(words[0]) != 0: if is_verb(words[0]) == is_noun(words[1]): print('YES') else: print('NO') else: print('NO') else: noun_count = 0 # the sentence may have zero or more verbs and adjectives, but only one noun if is_adjective(words[0]) != 0: # it should be the same gender like Masculine or Feminine gender = is_adjective(words[0]) else: gender = is_noun(words[0]) noun_count += 1 if gender == 0: print('NO') return for i in range(1, num): # it's not a legal word if is_noun(words[i]) == 0 and is_adjective(words[i]) == 0 and is_verb(words[i]) == 0: print('NO') return if is_adjective(words[i]) != 0 and is_adjective(words[i]) == gender and noun_count == 0: continue elif is_adjective(words[i]) != 0 and is_adjective(words[i]) != gender: print('NO') return elif is_adjective(words[i]) != 0 and noun_count != 0: print('NO') return if is_noun(words[i]) != 0 and is_noun(words[i]) == gender and noun_count == 0: noun_count += 1 continue elif is_noun(words[i]) != 0 and (is_noun(words[i]) != gender or noun_count == 1): print('NO') return if is_verb(words[i]) != 0 and is_verb(words[i]) == gender and noun_count == 1: continue elif is_verb(words[i]) != 0 and (is_verb(words[i]) != gender or noun_count == 0): print('NO') return if noun_count == 1: print('YES') else: print('NO') returndef is_verb(word): # judge whether the word end with -initis, or end with -inites # if it's initis, return 1, if it's inites, return 2 if word[-6:] == 'initis': return 1 elif word[-6:] == 'inites': return 2 else: return 0def is_adjective(word): # judge whether the word end with -lios, or end with -liala # if it's lios, return 1, if it's liala, return 2 if word[-4:] == 'lios': return 1 elif word[-5:] == 'liala': return 2 else: return 0def is_noun(word): # judge whether the word end with -etr, or end with -etra # if it's etr, return 1, if it's etra, return 2 if word[-3:] == 'etr': return 1 elif word[-4:] == 'etra': return 2 else: return 0# isPetyaLanguage()待办完成事项清单
编写一个命令行的待完成事项清单程序,用户按照格式输入命令,程序需要解析用户输入的命令,并完成相应的操作。
待办事项状态有两个状态:todo,表示待办;completed,表示已完成。命令和待办事项都为英文单词组成,单个待办事项为短语,不包含标点符号,首尾没有空格。
用户输入的命令和内容满足下列要求。
todo -a "todo item1" "todo item2"
表示增加(add)待办事项,待办事项可以为1个或多个,单个事项用双引号(英文)括起来,事项之间以空格分隔。 用户输入该命令后,程序应将待办事项保存到持久性位置(文件)。 存储时一行表示一个待办事项,格式为"状态:待办事项",状态包括todo和completed,待办事项就是上面的todo item1和todo item2。
todo -d "todo item1"
删除(delete)待办事项,待办事项可以为1个或多个,单个事项用双引号(英文)括起来,事项之间以空格分隔。 用户输入该命令后,程序应从所有任务中删去该任务,并同步到文件。
todo -c "todo item1" "todo item2"
修改待办事项为已完成(complete),待办事项可以为1个或多个,单个事项用双引号(英文)括起来,事项之间以空格分隔。 用户输入该命令后,程序应将这些任务的状态标记为已完成,并同步到文件。
todo -f status
查询(find)待办事项。status表示事项状态,可以是todo或completed。用户输入该命令后,程序应查询出指定状态的待办事项,并向控制台输出。 要求一行输出一个任务,并按照添加时的相对顺序输出,即先添加的输出在前(注:多个待办事项以一个命令添加的,位置靠前的是先添加的)。
todo -all
查询所有待办事项。用户输入该命令后,程序应查询出所有的待办事项,并向控制台输出。 要求一行输出一个任务,并按照添加时的相对顺序输出,即先添加的输出在前(注:多个待办事项以一个命令添加的,位置靠前的是先添加的)。
todo -quit
停止接收输入,结束方法,不要使用sys.exit()命令
程序操作过程分为:从控制台读取命令->解析命令->调用对应函数处理命令。
示例1:
xxxxxxxxxx1. 增加待办事项:输入:todo -a "complete homework" "do handwriting" "go shopping" "read books" "visit grandparents" "participate the interview"此时文件中保存内容如下:todo:complete homeworktodo:do handwritingtodo:go shoppingtodo:read bookstodo:visit grandparentstodo:participate the interview2. 删除待办事项:输入:todo -d "go shopping"此时文件中保存内容如下:todo:complete homeworktodo:do handwritingtodo:read bookstodo:visit grandparentstodo:participate the interview3. 修改待办事项为已完成:输入:todo -c "complete homework" "participate the interview" "read books"此时文件中保存内容如下:completed:complete homeworktodo:do handwritingcompleted:read bookstodo:visit grandparentscompleted:participate the interview4. 查询待办事项:输入:todo -f todo输出:todo:do handwritingtodo:visit grandparents5. 查询已完成事项:输入:todo -f completed输出:completed:complete homeworkcompleted:read bookscompleted:participate the interview6. 查询所有事项输入:todo -all输出:completed:complete homeworktodo:do handwritingcompleted:read bookstodo:visit grandparentscompleted:participate the interview
存储的文件名为tasks.txt,存储路径为ToDoList根目录,存储的文件路径已经设置在file变量中,不可修改文件名及路径 请严格按照示例规范输出,不可修改方法名称、参数以及文件名,可以添加自己的方法
"""write your code in following methods"""import refile_path = './tasks.txt'def to_do(): # judge whether to add or delete or list or complete # if add, call add_task # keep reading until quit while True: command = input() if "quit" in command: break else: # count store the number of "" count = findall(r'"', command) / 2 tmp = [] now = 0 for i in range(int(count)): # store all the tasks in tmp now = command.find('"', now + 1) tmp.append(command[now + 1:command.find('"', now + 1)]) now = command.find('"', now + 1) command = command.split() if command[1] == "-a": add_task(tmp) elif command[1] == "-d": delete_task(tmp) elif command[1] == "-c": complete_task(tmp) elif command[1] == "-all": list_task("all") elif command[1] == "-f": list_task(command[2]) returndef add_task(*task): # open file f = open(file_path, "a") task = task[0] t = len(task) for i in range(t): f.write("todo:" + str("".join(task[i])) + "\n") f.close() # write task # close file return# read one or more tasksdef delete_task(*task): task = task[0] for op in task: # open file and delete the task f = open(file_path, "r") lines = f.readlines() f.close() f = open(file_path, "w") # get all the tasks in the file for line in lines: if op in line: continue f.write("".join(line)) f.close() returndef list_task(status): f = open(file_path, "r") if status == "all": for i in f: print(i, end="") elif status == "todo": for i in f: if "todo" in i: print(i, end="") elif status == "completed": for i in f: if "completed" in i: print(i, end="") returndef complete_task(*task): # open file and change the task status to completed task = task[0] for op in task: # open file and delete the task f = open(file_path, "r") lines = f.readlines() f.close() f = open(file_path, "w") # get all the tasks in the file for line in lines: if op in line: line = line.replace("todo", "completed") f.write("".join(line)) f.close() returndef findall(pattern, string): return len(re.findall(pattern, string))if __name__ == '__main__': to_do()编写一个直方图程序
从"grades.in"文件中读取n个成绩(成绩为整形,在0-100之间,包括边界值)
首先输出每个区间内点的数目,用","隔开
然后打印直方图
文件格式如下:
xxxxxxxxxxnumStduents:intgrade1:int grade2:int .... gradeN:int
项目说明:
src目录下为题目代码源文件,需要完成的内容为grades_histogram.py里的histogram方法。 src目录下的init.py文件不需要改动。
示例:
xxxxxxxxxx1549 50 51 59 0 5 9 10 15 19 50 55 89 99 100输出格式如下:3,3,0,0,1,5,0,0,1,20 - 9:***10 - 19:***20 - 29:30 - 39:40 - 49:*50 - 59:*****60 - 69:70 - 79:80 - 89:*90 -100:**
"""write your code in method"""def histogram(fileName): # code here # read the file # create a dictionary with open(fileName, 'r') as file: # read the first line file.readline() grades = file.read().split() #init a list of 11 zeros grades_list = [0] * 11 for grade in grades: #convert to int grade = int(grade) #increment the count grades_list[grade//10] += 1 grades_list[9]+=grades_list[10] #print the number in each range for i in range(9): print(f'{grades_list[i]}',end=',') print(grades_list[9]) for i in range(10): # control the format if i != 9: print(f'{i*10:^3}-{i*10+9:3}:',end='') else: print(f'{i*10:^3}-{i*10+10:3}:',end='') #print the stars for j in range(grades_list[i]): print('*',end='') print() returnif __name__ == '__main__': histogram('grades.in')题目:
输入一个整数数组 nums 和一个整数目标值 target
请你在该数组中找出和为目标值 target 的那两个整数,由小到大返回它们的数组下标
每种输入只会对应一个答案,但是,数组中同一个位置的元素在答案里不能重复出现
项目说明:
src目录下为题目代码源文件,需要完成的内容为two_sum.py里的twoSum方法。 src目录下的init.py文件不需要改动。
示例:
xxxxxxxxxx输入:nums = [3,2,4], target = 6返回:[1,2]
"""write your code in method"""def twoSum(nums, target): for i in range(len(nums)): for j in range(i + 1, len(nums)): if nums[i] + nums[j] == target: return [i, j] #code here return给定一个许可密钥字符串 s,仅由字母、数字字符和破折号组成。字符串由 n 个破折号分成 n + 1 组。你也会得到一个整数 k 。
我们想要重新格式化字符串 s,分成若干组,使每一组包含 k 个字符,第一组除外(它可以比 k 短,但仍然必须包含至少一个字符)。此外,两组之间必须插入破折号,并且应该将所有小写字母转换为大写字母。
返回 重新格式化的许可密钥。
示例1:
xxxxxxxxxx输入: s = "5F3Z-2e-9-w", k = 4输出: "5F3Z-2E9W"
示例2:
xxxxxxxxxx输入:s = "2-5g-3-J", k = 2输出:"2-5G-3J"解释:字符串 s 被分成了 3 个部分,按照前面的规则描述,第一部分的字符可以少于给定的数量,其余部分皆为 2 个字符。
def formatting(s, k): split = "".join(s.split('-')) split = split.upper() temp = [] for i in range(len(split) - 1, -1, -k): # capitalize all the characters and print them if i - k + 1 >= 0: temp.append(split[i - k + 1:i + 1]) else: temp.append(split[0:i + 1]) temp.reverse() return '-'.join(temp)if __name__ == '__main__': s = '2-5g-3-J' k = 2 print(formatting(s, k))xxxxxxxxxxAlice and Bob like games. And now they are ready to start a new game. They have placed *n* chocolate bars in a line. Alice starts to eat chocolate bars one by one from left to right, and Bob — from right to left. For each chocolate bar the time, needed for the player to consume it, is known (Alice and Bob eat them with equal speed). When the player consumes a chocolate bar, he immediately starts with another. It is not allowed to eat two chocolate bars at the same time, to leave the bar unfinished and to make pauses. If both players start to eat the same bar simultaneously, Bob leaves it to Alice as a true gentleman.How many bars each of the players will consume?
The first line contains one integer n (1 ≤ n ≤ 105) — the amount of bars on the table. The second line contains a sequence t1, t2, ..., ti(1 ≤ t**i ≤ 1000), where ti is the time (in seconds) needed to consume the i-th bar (in the order from left to right).
Print two numbers a and b, where a is the amount of bars consumed by Alice, and b is the amount of bars consumed by Bob.
xxxxxxxxxx52 9 8 2 7
xxxxxxxxxx2 3
"""write your code in method solve"""def solve(): # input the number of chocolate bars bar_num = int(input()) # input the number of chocolate pieces in each bar bar_pieces = [int(x) for x in input().split()] # begin their game alice = 0 a = 0 b = 0 bob = bar_num-1 while alice < bob: if bar_pieces[alice] > 0: bar_pieces[alice] -= 1 elif bob != alice+1: alice += 1 bar_pieces[alice] -= 1 else: break if bar_pieces[bob] > 0: bar_pieces[bob] -= 1 elif bob-1 != alice: bob -= 1 bar_pieces[bob] -= 1 else: break print(alice+1,bar_num-alice - 1) returnif __name__ == '__main__': solve()Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.
Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own.

Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
On the single line of the output print the number of groups of magnets.
xxxxxxxxxx6101010011010
xxxxxxxxxx3
xxxxxxxxxx401011010
xxxxxxxxxx2
"""write your code in method solve"""def solve(): n = int(input()) a = input() magnets = [int(i) for i in a.split()] count = 0 for i in range(n - 1): if magnets[i] != magnets[i + 1]: count += 1 print(count + 1)if __name__ == '__main__': solve()