Last active
March 29, 2020 08:16
-
-
Save SharapaGorg/ed70b2fc16cddf8133dc5673cdb3f0b5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #Во входном файле записано два целых числа, каждое в отдельной строке. Выведите в выходной файл их сумму. | |
| with open('input.txt') as datfile: | |
| text = datfile.read() | |
| print(sum(map(int, text.split(None, 2)[:2]))) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #Дан файл. Определите сколько в нем букв (латинского алфавита), слов, строк. Выведите три найденных числа в формате, приведенном в примере. | |
| #Для экономии памяти читайте файл посимвольно, то есть не сохраняя целиком в памяти файл или отдельные его строки. | |
| import re | |
| A = [] | |
| lines = 0 | |
| fil = open('input.txt', 'r') | |
| file = fil.readlines() | |
| words = re.findall(r"[A-Za-z]+", ' '.join(file)) | |
| wordres = re.findall(r"[A-Za-z]+", ' '.join(file)) | |
| for item in file: | |
| lines += 1 | |
| for i in range(len(words) - 1): | |
| words[0] += words[i + 1] | |
| letters = len(words[0]) | |
| print('Input file contains:') | |
| print(str(letters) + ' letters') | |
| print(str(len(wordres)) + ' words') | |
| print(str(lines) + ' lines') |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #Зашифруйте данный текстовый файл шифром Цезаря, при этом символы первой строки файла должны циклически сдвигаться на 1, второй строки — на 2, третьей строки — на три и т.д. | |
| #В этой задаче удобно считывать файл построчно, шифруя каждую строку в отдельности. | |
| import re | |
| i = 0 | |
| fil = open('input.txt', 'r').readlines() | |
| alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' | |
| def CaesarCipherChar(c, k): | |
| d = alphabet.find(c.lower()) | |
| l = len(alphabet) // 2 | |
| if d < l and c in alphabet: | |
| l *= 2 | |
| if c.islower(): | |
| return alphabet[(d + k) % len(alphabet)].lower() | |
| else: | |
| return alphabet[(d + k) % len(alphabet)].upper() | |
| elif c not in alphabet: | |
| return c | |
| if c.islower(): | |
| return alphabet[d + k - l].lower() | |
| else: | |
| return alphabet[d + k - l].upper() | |
| def CaesarCipher(s, k): | |
| for item in s: | |
| yield CaesarCipherChar(item, k) | |
| for item in fil: | |
| i += 1 | |
| print(*CaesarCipher(item[:-1], i), sep='') |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #В олимпиаде по информатике принимало участие несколько человек. Победителем олимпиады становится человек, набравший больше всех баллов. Победители определяются независимо по каждому классу. Определите количество баллов, которое набрал победитель в каждом классе. Гарантируется, что в каждом классе был хотя бы один участник. | |
| fil = open('input.txt', 'r') | |
| mma = fil.readlines() | |
| FUCK = [] | |
| word = ' 9 ' | |
| word1 = ' 10 ' | |
| word2 = ' 11 ' | |
| worddef = '\n' | |
| g = 1 | |
| gg = 1 | |
| i = 0 | |
| ii = 0 | |
| iii = 0 | |
| h = 0 | |
| hh = 0 | |
| hhh = 0 | |
| AA, BB, CC, AA1, BB1, CC1, AA2, BB2, CC2 = [], [], [], [], [], [], [], [], [] | |
| for item in mma: #9 no filt | |
| if word in item: | |
| AA.append(item[-3:]) | |
| for item in mma:#10 no filt | |
| if word1 in item: | |
| BB.append(item[-3:]) | |
| for item in mma: #11 no filt | |
| if word2 in item: | |
| CC.append(item[-3:]) | |
| for i in range(len(AA)): #9 filt1 | |
| AA1.append(AA[i].replace('\n', '')) | |
| i+=1 | |
| for ii in range(len(BB)): #10 filt1 | |
| BB1.append(BB[ii].replace('\n', '')) | |
| ii+=1 | |
| for iii in range(len(CC)): #11 filt1 | |
| CC1.append(CC[iii].replace('\n', '')) | |
| iii+=1 | |
| for h in range(len(AA1)): #9 max fit | |
| AA2.append(AA1[h].replace(' ', '')) | |
| i+=1 | |
| for hh in range(len(BB1)): #10 max filt | |
| BB2.append(BB1[hh].replace(' ', '')) | |
| hh+=1 | |
| for hhh in range(len(CC1)): | |
| CC2.append(CC1[hhh].replace(' ', '')) | |
| hhh+=1 | |
| a = max(AA2) | |
| b = max(BB2) | |
| c = max(CC2) | |
| if g == gg: | |
| FUCK.append(a) | |
| FUCK.append(b) | |
| FUCK.append(c) | |
| print(*FUCK) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #В условиях предыдущей задачи определите и выведите средние баллы участников олимпиады в 9 классе, в 10 классе, в 11 классе. | |
| g, d = 1, 1 | |
| COMPLETE = [] | |
| fil = open('input.txt', 'r') | |
| file = fil.readlines() | |
| A, B, C = [], [], [] | |
| for item in file: | |
| a = list(item.split()) | |
| if a[2] == '9': | |
| A.append(int(a[3])) | |
| elif a[2] == '10': | |
| B.append(int(a[3])) | |
| else: | |
| C.append(int(a[3])) | |
| aa = (sum(A)/len(A)) | |
| bb = (sum(B)/len(B)) | |
| cc = (sum(C)/len(C)) | |
| if d == g: | |
| COMPLETE.append(aa) | |
| COMPLETE.append(bb) | |
| COMPLETE.append(cc) | |
| print(*COMPLETE) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #В условиях предыдущей задачи определите количество школьников, ставших победителями в каждом классе. Победителями объявляются все, кто набрал наибольшее число баллов по данному классу. Гарантируется, что в каждом классе был хотя бы один участник. | |
| d, g = 1, 1 | |
| fil = open('input.txt', 'r') | |
| file = fil.readlines() | |
| A, B, C = [], [], [] | |
| for item in file: | |
| a = list(item.split()) | |
| if a[2] == '9': | |
| A.append(int(a[3])) | |
| elif a[2] == '10': | |
| B.append(int(a[3])) | |
| else: | |
| C.append(int(a[3])) | |
| a1 = max(A) | |
| b1 = max(B) | |
| c1 = max(C) | |
| COMPLETE = [] | |
| aa = A.count(a1) | |
| bb = B.count(b1) | |
| cc = C.count(c1) | |
| if d == g: | |
| COMPLETE.append(aa) | |
| COMPLETE.append(bb) | |
| COMPLETE.append(cc) | |
| print(*COMPLETE) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #Зачет в олимпиаде проводится без деления на классы. Выведите фамилию и имя победителя олимпиады. Если таких несколько - выведите только их количество. | |
| fil = open('input.txt', 'r') | |
| file = fil.readlines() | |
| A, AA = [], [] | |
| for item in file: | |
| A.append(item.split()) | |
| max1 = -1 | |
| i = 0 | |
| for i in range(len(A)): | |
| if int(A[i][3]) > max1: | |
| max1 = int(A[i][3]) | |
| i += 1 | |
| else: | |
| i += 1 | |
| j = 0 | |
| k = 0 | |
| cheat = 0 | |
| for k in range(len(A)): | |
| if str(max1) in A[k]: | |
| cheat += 1 | |
| else: | |
| k += 1 | |
| if cheat == 1: | |
| for j in range(len(A)): | |
| if str(max1) in A[j]: | |
| print(A[j][0], A[j][1]) | |
| else: | |
| j += 1 | |
| else: | |
| print(cheat) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #Зачет проводится отдельно в каждом классе. Победителями олимпиады становятся школьники, которые набрали наибольший балл среди всех участников в данном классе. | |
| #Для каждого класса определите максимальный балл, который набрал школьник, не ставший победителем в данном классе. | |
| fil = open('input.txt', 'r') | |
| file = fil.readlines() | |
| A, B, C = [], [], [] | |
| COMPLETE = [] | |
| A1, B1, C1 = [], [], [] | |
| A12, B12, C12 = [], [], [] | |
| for item in file: | |
| a = list(item.split()) | |
| if a[2] == '9': | |
| A.append(int(a[3])) | |
| elif a[2] == '10': | |
| B.append(int(a[3])) | |
| else: | |
| C.append(int(a[3])) | |
| A1 = sorted(A, key = int) | |
| B1 = sorted(B, key = int) | |
| C1 = sorted(C, key = int) | |
| a1 = A1.index(max(A1)) - 1 | |
| b1 = B1.index(max(B1)) - 1 | |
| c1 = C1.index(max(C1)) - 1 | |
| a12 = A1.index(max(A1)) | |
| b12 = B1.index(max(B1)) | |
| c12 = C1.index(max(C1)) | |
| for a1 in range(len(A1)): | |
| if A1[a1] < A1[a12]: | |
| A12.append(A1[a1]) | |
| else: | |
| a1 -= 1 | |
| for b1 in range(len(B1)): | |
| if B1[b1] < B1[b12]: | |
| B12.append(B1[b1]) | |
| else: | |
| b1 -= 1 | |
| for c1 in range(len(C1)): | |
| if C1[c1] < C1[c12]: | |
| C12.append(C1[c1]) | |
| else: | |
| c1 -= 1 | |
| print(max(A12), max(B12), max(C12)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #Результаты олимпиады подводятся без деления на классы. Победителем олимпиады становятся те, кто набрал больше всего баллов. Призерами олимпиады становятся участники, следующие за победителями. | |
| #Определите наибольший балл, который набрали призеры олимпиады и количество участников олимпиады, набравших такой балл. | |
| import collections | |
| fil = open('input.txt', 'r', encoding = 'utf-8') | |
| file = fil.readlines() | |
| A = [] | |
| for i in range(len(file)): | |
| last_name, first_name, class_number, points = map( | |
| str, file[i].replace('\n', '').split()) | |
| A.append(int(points)) | |
| a1 = max(A) | |
| for i in range(A.count(a1)): | |
| A.remove(a1) | |
| print(max(A), A.count(max(A))) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #В условиях предыдущей задачи выведите фамилию и имя участника олимпиады, набравшего наибольший балл, но не ставшего победителем. Если таких школьников несколько - выведите их количество. | |
| import collections | |
| fil = open('input.txt', 'r') | |
| file = fil.readlines() | |
| A, AA = [], [] | |
| F = [] | |
| for item in file: | |
| A.append(item.split()) | |
| for i in range(len(file)): | |
| last_name, first_name, class_number, points = map( | |
| str, file[i].replace('\n', '').split()) | |
| F.append(int(points)) | |
| f = max(F) | |
| for i in range(F.count(f)): | |
| F.remove(f) | |
| max1 = max(F) | |
| cheat = F.count(max1) | |
| j = 0 | |
| if cheat == 1: | |
| for j in range(len(A)): | |
| if str(max1) in A[j]: | |
| print(A[j][0], A[j][1]) | |
| else: | |
| j += 1 | |
| else: | |
| print(cheat) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #В олимпиаде по информатике принимало участие N человек. Определите школы, из которых в олимпиаде принимало участие больше всего участников. В этой задаче необходимо считывать данные построчно, не сохраняя в памяти данные обо всех участниках, а только подсчитывая число участников для каждой школы. | |
| A, AA, sortlist, d, d1 = [], [], [], {}, {} | |
| fil = open('input.txt', 'r') | |
| file = fil.readlines() | |
| for item in file: | |
| A.append(item.split()) | |
| for item in A: | |
| if item[2] not in d.keys(): | |
| d[item[2]] = 0 | |
| d[item[2]] += int(item[3]) | |
| for item in A: | |
| if item[2] not in d1.keys(): | |
| d1[item[2]] = 0 | |
| d1[item[2]] += 1 | |
| max_val = max(d1.values()) | |
| for i in d1: | |
| if d1[i] == max_val: #number of max student's school | |
| AA.append(i) | |
| print(*sorted(AA, key = int)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Во входном файле записано два целых числа, которые могут быть разделены пробелами и концами строк. Выведите в выходной файл их сумму. | |
| #Указание. Считайте весь файл в строковую переменную при помощи метода read() и разбейте ее на части при помощи метода split(). | |
| with open('input.txt') as datfile: | |
| text = datfile.read() | |
| print(sum(map(int, text.split(None, 2)[:2]))) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #В условиях предыдущей задачи определите школы, из которых в олимпиаде принимало участие меньше всего участников (но был хотя бы один участник). | |
| A, AA, sortlist, d, d1 = [], [], [], {}, {} | |
| fil = open('input.txt', 'r') | |
| file = fil.readlines() | |
| for item in file: | |
| A.append(item.split()) | |
| for item in A: | |
| if item[2] not in d.keys(): | |
| d[item[2]] = 0 | |
| d[item[2]] += int(item[3]) | |
| for item in A: | |
| if item[2] not in d1.keys(): | |
| d1[item[2]] = 0 | |
| d1[item[2]] += 1 | |
| max_val = min(d1.values()) | |
| for i in d1: | |
| if d1[i] == max_val: #number of max student's school | |
| AA.append(i) | |
| print(*sorted(AA, key = int)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #Известно, что фамилии всех участников — различны. Сохраните в массивах список всех участников и выведите его, отсортировав по фамилии в лексикографическом порядке. | |
| #При выводе указываете фамилию, имя участника и его балл. | |
| import operator | |
| fil = open('input.txt', 'r') | |
| file = fil.readlines() | |
| people = [] | |
| for item in file: | |
| people.append(item.split()) | |
| def gag(x): | |
| return x[0] | |
| people = sorted(people, key = gag) | |
| for item in people: | |
| print(item[0], item[1], item[3]) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #Отсортируйте список участников олимпиады: | |
| #1) По убыванию набранного балла | |
| #2) При равных значения балла - по фамилии в лексикографическом порядке. | |
| #3) При совпадающих баллах и фамилии - по имени в лексикографическом порядке. | |
| fil = open('input.txt', 'r', encoding = 'utf8').readlines() | |
| fil = [fil[i][:-1] if fil[i][-1] == '\n' else fil[i] for i in range(len(fil))] | |
| fil.sort(key = lambda x: (-1 * int(x.split()[3]), x.split()[0], x.split()[1])) | |
| print('\n'.join([fil[i].split()[0] + ' ' + fil[i].split()[1] + ' ' + fil[i].split()[3] for i in range(len(fil))])) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #В условиях предыдущей задачи выведите в порядке возрастания номера школ, в которых есть хотя бы один победитель олимпиады. | |
| fil = open('input.txt', 'r') | |
| file = fil.readlines() | |
| array_of_school = [0] * 100 | |
| max1 = 0 | |
| for item in file: | |
| last_name, first_name, school_number, points = map( | |
| str, item.replace('\n', '').split()) | |
| if max1 <= int(points): | |
| max1 = int(points) | |
| for item in file: | |
| last_name, first_name, school_number, points = map( | |
| str, item.replace('\n', '').split()) | |
| if int(points) == max1: | |
| array_of_school[int(school_number)] += 1 | |
| for i in range(1, 100): | |
| if array_of_school[i] != 0: | |
| print(i, end=' ') | |
| fil.close() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #Во входном файле записана одна текстовая строка, возможно, содержащая пробелы. Выведите эту строку в обратном порядке. | |
| #Строка во входном файле заканчивается символом конца строки '\n'. | |
| input2 = open('input.txt', 'r') | |
| s = input2.read() | |
| s = s.replace('\n', '') | |
| s = s[::-1] | |
| print(s) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #Выведите все строки данного файла в обратном порядке. Для этого считайте список всех строк при помощи метода readlines(). | |
| #Последняя строка входного файла обязательно заканчивается символом '\n'. | |
| aa = open('input.txt', 'r') | |
| aa1= aa.readlines() | |
| for i in range(len(aa1) - 1, -1, -1): | |
| print(aa1[i].replace('\n', '').replace('\\n', '')) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #Выведите в обратном порядке содержимое всего файла полностью. Для этого считайте файл целиком при помощи метода read(). | |
| input2 = open('input.txt', 'r') | |
| s = input2.read() | |
| print(s[::-1]) | |
| #for item in list(reversed(s[0])): | |
| #print(item , sep = '', end = '') |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #В выходной файл выведите все строки наибольшей длины из входного файла, не меняя их порядок. | |
| #В данной задаче удобно считать список строк входного файла целиком при помощи метода readlines(). | |
| fil = open('input.txt', 'r') | |
| file = fil.readlines() | |
| i = 0 | |
| AA = [] | |
| fuck = -1 | |
| for item in file: | |
| gg = len(item) | |
| if gg >= fuck: | |
| fuck = gg | |
| for item in file: | |
| gg = len(item) | |
| if gg == fuck: | |
| AA.append(item) | |
| print(*AA, sep = '') |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #Определите, есть ли во входном файле символ '@'. Выведите слово YES или NO. | |
| #Входной файл может быть очень большим, поэтому считывать файл нужно посимвольно. | |
| f = open('input.txt', 'r') | |
| word = '@' | |
| print('YES' if word in f.read() else 'NO') |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #Дан файл, каждая строка которого может содержать одно или несколько целых чисел, разделенных одним или несколькими пробелами. | |
| #Вычислите сумму чисел в каждой строке и выведите эту сумму (для каждой строки выводится сумма чисел в этой строке). | |
| #В данной задаче удобно считывать данные построчно. N неограниченно. Сумма чисел в каждой строке не превосходит 10**9. | |
| fil = open('input.txt', 'r') | |
| fuckingread = fil.readlines() | |
| AA = [] | |
| for i in range(len(fuckingread)): | |
| gg = fuckingread[i].replace('\n', '').split() | |
| gg1 = 0 | |
| j = 0 | |
| for j in range(len(gg)): | |
| gg1+= int(gg[j]) | |
| AA.append(gg1) | |
| ii = 0 | |
| for ii in range(len(AA)): | |
| print(AA[ii]) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #В файле могут быть записаны десятичные цифры и все, что угодно. Числом назовем последовательность цифр, идущих подряд (т.е. число всегда неотрицательно). | |
| #Вычислите сумму всех чисел, записанных в файле. В данной задаче удобно считывать данные посимвольно. | |
| import re | |
| fil = open('input.txt', 'r') | |
| a = 0 | |
| chisla = re.findall(r"[0-9]+", ' '.join(fil.readlines())) | |
| for i in range(len(chisla)): | |
| a += int(chisla[i]) | |
| print(a) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment