-
Notifications
You must be signed in to change notification settings - Fork 0
Lesson 5 #7
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
alardis
wants to merge
10
commits into
master
Choose a base branch
from
lesson_5
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Lesson 5 #7
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
063b2ca
Созданы файлы py для выполнения пятой домашки
alardis 7ae897a
Первая задача сделана
717a632
Вторая задача сделана
7cc9d4b
Третья задача сделана
378853b
Четвертая задача сделана
b15423c
Пятая задача сделана.
eb14a76
Шестая задача сделана
7d8ecac
Седьмая задача сделана
6d12a49
Добавлен файл для восьмой задачи
8c86599
Восьмая задача сделана
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| # Создать программно файл в текстовом формате, записать в него построчно данные, вводимые пользователем. | ||
| # Об окончании ввода данных свидетельствует пустая строка. | ||
|
|
||
| import os | ||
|
|
||
| with open(f'{os.path.abspath("Python_level_1/lesson_5")}/new_file.txt', 'w', encoding='utf-8') as file: | ||
| line = None | ||
| while line != '': | ||
| line = input('Введите строку, которую хотите записать в файл. Если не хотите, нажмите Enter\n') | ||
| file.write(f'{line}\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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| # Создать текстовый файл (не программно), сохранить в нем несколько строк, выполнить подсчет количества строк, | ||
| # количества слов в каждой строке. | ||
|
|
||
|
|
||
| import os | ||
|
|
||
| with open(f'{os.path.abspath("Python_level_1/lesson_5")}/new_file.txt', 'r', encoding='utf-8') as file: | ||
| lines = file.readlines() | ||
| for num, line in enumerate(lines): | ||
| if line.isspace(): | ||
| continue | ||
| else: | ||
| words = line.strip().split(' ') | ||
| print(f'Строка {num}: количество слов -- {len(words)}') |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| # Создать текстовый файл (не программно), построчно записать фамилии сотрудников и величину их окладов. | ||
| # Определить, кто из сотрудников имеет оклад менее 20 тыс., вывести фамилии этих сотрудников. | ||
| # Выполнить подсчет средней величины дохода сотрудников. | ||
|
|
||
|
|
||
| import os | ||
|
|
||
| with open(f'{os.path.abspath("Python_level_1/lesson_5")}/new_file.txt', 'r', encoding='utf-8') as file: | ||
| lines = file.readlines() | ||
| av_sum = 0 | ||
| for num, line in enumerate(lines): | ||
| if line.isspace(): | ||
| continue | ||
| else: | ||
| line = line.strip() | ||
| words = line.split(' ') | ||
| try: | ||
| salary = int(words[1]) | ||
| av_sum += salary | ||
| if salary <= 20000: | ||
| print(f'Сотрудник {words[0]} имеет низкую зарплату ({words[1]})') | ||
| except ValueError: | ||
| print(f'Проверьте данные в файле на строке {num}') | ||
|
|
||
| print(f'\nСредняя зарплата при этом составляет: {av_sum / len(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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| # Создать (не программно) текстовый файл со следующим содержимым: | ||
| # One — 1 | ||
| # Two — 2 | ||
| # Three — 3 | ||
| # Four — 4 | ||
| # Необходимо написать программу, открывающую файл на чтение и считывающую построчно данные. | ||
| # При этом английские числительные должны заменяться на русские. Новый блок строк должен записываться | ||
| # в новый текстовый файл. | ||
|
|
||
|
|
||
| import os | ||
|
|
||
| translator = {'One': 'Один', 'Two': 'Два', 'Three': 'Три', 'Four': 'Четыре'} | ||
| try: | ||
| with open(f'{os.path.abspath("Python_level_1/lesson_5")}/new_file.txt', 'x', encoding='utf-8') as file,\ | ||
| open(f'{os.path.abspath("Python_level_1/lesson_5")}/new_new_file.txt', 'a+', encoding='utf-8') as sec_file: | ||
| lines = file.readlines() | ||
| for line in lines: | ||
| words = line.split(' ') | ||
| if words[0] in translator.keys(): | ||
| words[0] = translator[words[0]] | ||
| sec_file.write(' '.join(words)) | ||
| except FileNotFoundError: | ||
| print('Один из файлов отсутствует!') |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| # Создать (программно) текстовый файл, записать в него программно набор чисел, разделенных пробелами. | ||
| # Программа должна подсчитывать сумму чисел в файле и выводить ее на экран. | ||
|
|
||
|
|
||
| import os | ||
| import random | ||
|
|
||
| # сперва создадим текстовый файл и набьем в него чисел | ||
| with open(f'{os.path.abspath("Python_level_1/lesson_5")}/new_file.txt', 'w+', encoding='utf-8') as file: | ||
| number_list = [] | ||
| for i in range(10): | ||
| number_list.append(str(random.randint(0, 40))) | ||
| file.write(' '.join(number_list)) | ||
|
|
||
| with open(f'{os.path.abspath("Python_level_1/lesson_5")}/new_file.txt', 'r', encoding='utf-8') as file: | ||
| number_list_2 = file.readline().split(' ') | ||
| print(f'Прочитанный из файла список -- {number_list_2}') | ||
| for num, item in enumerate(number_list_2[:]): | ||
| try: | ||
| number_list_2[num] = int(item) | ||
| except ValueError: | ||
| print('Ошибка при переводе числа из списка в числовой формат для сложения, проверьте') | ||
| print(f'Сумма чисел, записанных в файл -- {sum(number_list_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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| # Необходимо создать (не программно) текстовый файл, где каждая строка описывает учебный предмет и наличие лекционных, | ||
| # практических и лабораторных занятий по этому предмету и их количество. Важно, чтобы для каждого предмета | ||
| # не обязательно были все типы занятий. Сформировать словарь, содержащий название предмета | ||
| # и общее количество занятий по нему. | ||
| # Вывести словарь на экран. | ||
|
|
||
| # формат файла: | ||
| # Философия. Лекционное занятие: 10, Практическое занятие: 13 | ||
|
|
||
|
|
||
| import os | ||
|
|
||
|
|
||
| with open(f'{os.path.abspath("Python_level_1/lesson_5")}/new_file.txt', 'r', encoding='utf-8') as file: | ||
| lines_list = file.readlines() | ||
| lessons_dict = {} | ||
| for line in lines_list: | ||
| record = line.split('. ') | ||
| lesson_key = record[0] | ||
| lesson_val = 0 | ||
| for work in record[1].split(', '): | ||
| work_detailed = work.split(': ') | ||
| lesson_val += int(work_detailed[1]) | ||
| lessons_dict.update({lesson_key: lesson_val}) | ||
|
|
||
| for key, value in lessons_dict.items(): | ||
| print(f"{key}: {value}") | ||
|
|
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| # Создать (не программно) текстовый файл, в котором каждая строка должна содержать данные о фирме: | ||
| # название, форма собственности, выручка, издержки. Необходимо вычислить прибыль каждой компании и среднюю прибыль. | ||
| # Реализовать список, содержащий словарь (название фирмы и прибыль) и словарь с одним элементом (средняя прибыль). | ||
| # Добавить в первый словарь еще один элемент, содержащий результат вычисления отношения прибыли к убыткам. | ||
| # Итоговый список сохранить в файл. | ||
| # Подсказка: использовать менеджеры контекста. | ||
|
|
||
| # формат записи: | ||
| # Рога и Копыта, ООО, 100000, 4788 | ||
|
|
||
| import os | ||
|
|
||
| with open(f'{os.path.abspath("Python_level_1/lesson_5")}/new_file.txt', 'r', encoding='utf-8') as file,\ | ||
| open(f'{os.path.abspath("Python_level_1/lesson_5")}/new_new_file.txt', 'a+', encoding='utf-8') as new_file: | ||
| data_list = file.readlines() | ||
| # print(data_list) | ||
| whole_list = [] | ||
| av_income = 0 | ||
| for item in data_list: | ||
| local_data_list = item.split(', ') | ||
| income = 0 | ||
| try: | ||
| income = int(local_data_list[2]) - int(local_data_list[3]) | ||
| except ValueError: | ||
| print('Проверьте финансовые показатели организации!') | ||
| whole_list.append({'Название': f'{local_data_list[1]} {local_data_list[0]}', 'Прибыль': income}) | ||
| av_income += income | ||
| av_income = av_income / len(data_list) | ||
| whole_list.append({'Средняя прибыль': av_income}) | ||
| # print(whole_list) | ||
|
|
||
| for item in whole_list: | ||
| for key, value in item.items(): | ||
| line = f'{key}: {value}' | ||
| # print(line) | ||
| new_file.write(f'{line}\n') | ||
| new_file.write('\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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| # Написать лямбда функцию на вход принимающую строку из латинских символов на выходе возврадает символ | ||
| # в нижнем регистре который чаще всего встречается в строке, | ||
| # учитывать что символ верхнего регистра и символ нижнего регистра равны. | ||
| # Наша задача определить именно букву которая чаще всего встречается в строке | ||
|
|
||
|
|
||
| from collections import Counter | ||
|
|
||
|
|
||
| often_letter_2 = lambda line: max(zip( | ||
| (lambda local_line: {key: value for key, value in Counter(line.lower()).items() | ||
| if not key.isdigit() and not key.isspace()})(line).values(), | ||
| (lambda local_line: {key: value for key, value in Counter(line.lower()).items() | ||
| if not key.isdigit() and not key.isspace()})(line).keys() | ||
| ))[1] | ||
|
|
||
| print(often_letter_2('Раз два три четыре пять')) | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
перемудрли, есть функция filter она вам могла бы помочь