Skip to content
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

Homework added #6

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 12 additions & 10 deletions 1_date_and_time.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import datetime

"""
Домашнее задание №2

Expand All @@ -9,19 +11,19 @@
"""

def print_days():
"""
Эта функция вызывается автоматически при запуске скрипта в консоли
В ней надо заменить pass на ваш код
"""
pass
dt_now = datetime.datetime.today()
delta = datetime.timedelta(days=1)
delta_30days = datetime.timedelta(days=30)

yesterday = dt_now - delta
today = datetime.datetime.today()

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Эта строчка дублирует 14ую. Можно не исправлять

thirty_days_ago = dt_now - delta_30days

print(f'Вчера: {yesterday},\nСегодня: {today},\n30 дней назад: {thirty_days_ago}')

def str_2_datetime(date_string):
"""
Эта функция вызывается автоматически при запуске скрипта в консоли
В ней надо заменить pass на ваш код
"""
pass
obj_dt = datetime.datetime.strptime(date_string, '%d/%m/%y %H:%M:%S.%f')
return obj_dt

if __name__ == "__main__":
print_days()
Expand Down
19 changes: 14 additions & 5 deletions 2_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,20 @@
"""

def main():
"""
Эта функция вызывается автоматически при запуске скрипта в консоли
В ней надо заменить pass на ваш код
"""
pass

with open('referat.txt', 'r', encoding='utf-8') as essay:
content = essay.read()

len_essay = len(content)
print(f'Количество символов: {len_essay}')

words_amount = len(content.split())
print(f'Количество слов: {words_amount}')

new_content = content.replace('.', '!')

with open('referat2.txt', 'w', encoding='utf-8') as new_essay:
new_essay.write(new_content)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

great!


if __name__ == "__main__":
main()
21 changes: 16 additions & 5 deletions 3_dict_to_csv.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import csv
"""

Домашнее задание №2
Expand All @@ -11,11 +12,21 @@
"""

def main():
"""
Эта функция вызывается автоматически при запуске скрипта в консоли
В ней надо заменить pass на ваш код
"""
pass

user_info = [
{'name': 'Маша', 'age': 25, 'job': 'Scientist'},
{'name': 'Вася', 'age': 8, 'job': 'Programmer'},
{'name': 'Эдуард', 'age': 48, 'job': 'Big boss'},
{'name': 'Ксения', 'age': 29, 'job': 'Python developer'},
]

with open('user_info.csv', 'w', encoding='utf-8') as csv_file:
fields = ['name', 'age', 'job']
writer = csv.DictWriter(csv_file, fields, delimiter=';')
writer.writeheader()

for user in user_info:
writer.writerow(user)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

аккуратно и верно


if __name__ == "__main__":
main()
189 changes: 189 additions & 0 deletions lesson2/dicts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
import collections

# Задание 1
# Дан список учеников, нужно посчитать количество повторений каждого имени ученика.
# students = [
# {'first_name': 'Вася'},
# {'first_name': 'Петя'},
# {'first_name': 'Маша'},
# {'first_name': 'Маша'},
# {'first_name': 'Петя'},
# ]

# all_names = []
# for name in students:
# all_names.append(name['first_name'])

# names_counter = collections.Counter(all_names)

# for name in names_counter:
# print(f'{name}: {names_counter[name]}')

# Пример вывода:
# Вася: 1
# Маша: 2
# Петя: 2


# Задание 2
# Дан список учеников, нужно вывести самое часто повторящееся имя.
# students = [
# {'first_name': 'Вася'},
# {'first_name': 'Петя'},
# {'first_name': 'Маша'},
# {'first_name': 'Маша'},
# {'first_name': 'Оля'},
# ]

# all_names = []
# for name in students:
# all_names.append(name['first_name'])

# common_name = collections.Counter(all_names).most_common(1)
# print(f'Самое частое имя среди учеников: {common_name[0][0]}')

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

в таком месте лучше не делать [0][0] а распаковать
most_common = common_name[0]
name, amount = most_common


# Пример вывода:
# Самое частое имя среди учеников: Маша

# Задание 3

# Есть список учеников в нескольких классах, нужно вывести самое частое имя в каждом классе.
# school_students = [
# [ # это – первый класс
# {'first_name': 'Вася'},
# {'first_name': 'Вася'},
# ],
# [ # это – второй класс
# {'first_name': 'Маша'},
# {'first_name': 'Маша'},
# {'first_name': 'Оля'},
# ]
# ]

# def define_common_name(clas):
# all_names = []
# for name in clas:
# all_names.append(name['first_name'])

# common_name = collections.Counter(all_names).most_common(1)
# return common_name[0][0]

# i = 1
# for clas in school_students:
# most_common_name = define_common_name(clas)
# print(f'Самое частое имя в классе {i}: {most_common_name}')
# i += 1

# Пример вывода:
# Самое частое имя в классе 1: Вася
# Самое частое имя в классе 2: Маша


# Задание 4
# Для каждого класса нужно вывести количество девочек и мальчиков в нём.
# school = [
# {'class': '2a', 'students': [{'first_name': 'Маша'}, {'first_name': 'Оля'}]},
# {'class': '3c', 'students': [{'first_name': 'Олег'}, {'first_name': 'Миша'}]},
# ]
# is_male = {
# 'Маша': False,
# 'Оля': False,
# 'Олег': True,
# 'Миша': True,
# }



# def count_girls_in_class(clas, names_info):
# students = clas['students']
# girls = 0
# for name in students:
# student_name = name['first_name']
# if student_name in names_info:
# if names_info[student_name] is False:
# girls += 1
# return girls

# def count_boys_in_class(clas, names_info):

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Лучше объединить подсчет мальчиков и девочек в одну функцию и возвращать
return boys, girls

Эту правку лучше сделать для практики

# students = clas['students']
# boys = 0
# for name in students:
# student_name = name['first_name']
# if student_name in names_info:
# if names_info[student_name] is True:
# boys += 1
# return boys

# for clas in school:
# class_name = clas["class"]
# girls_amount = count_girls_in_class(clas, is_male)
# boys_amount = count_boys_in_class(clas, is_male)
# print(f'В классе {class_name} {girls_amount} девочки и {boys_amount} мальчика.')

# Пример вывода:
# В классе 2a 2 девочки и 0 мальчика.
# В классе 3c 0 девочки и 2 мальчика.


# Задание 5
# По информации о учениках разных классов нужно найти класс, в котором больше всего девочек и больше всего мальчиков.
school = [
{'class': '2a', 'students': [{'first_name': 'Маша'}, {'first_name': 'Оля'}]},
{'class': '3c', 'students': [{'first_name': 'Олег'}, {'first_name': 'Миша'}]},
]
is_male = {
'Маша': False,
'Оля': False,
'Олег': True,
'Миша': True,
}


def count_girls_in_class(clas, names_info):
students = clas['students']
girls = 0
for name in students:
student_name = name['first_name']
if student_name in names_info:
if names_info[student_name] is False:
girls += 1
return girls

def count_boys_in_class(clas, names_info):
students = clas['students']
boys = 0
for name in students:
student_name = name['first_name']
if student_name in names_info:
if names_info[student_name] is True:
boys += 1
return boys


class_with_most_boys = ''
for clas in school:
class_name = clas["class"]
boys_amount = count_boys_in_class(clas, is_male)
max_boys_amount = 0
if boys_amount > max_boys_amount:
max_boys_amount = boys_amount
class_with_most_boys = class_name

class_with_most_girls = ''
for clas in school:
class_name = clas["class"]
girls_amount = count_girls_in_class(clas, is_male)
max_girls_amount = 0
if girls_amount > max_girls_amount:
max_girls_amount = girls_amount
class_with_most_girls = class_name


print(f'Больше всего мальчиков в классе {class_with_most_boys}')
print(f'Больше всего девочек в классе {class_with_most_girls}')



# Пример вывода:
# Больше всего мальчиков в классе 3c
# Больше всего девочек в классе 2a
69 changes: 69 additions & 0 deletions lesson2/for.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Задание 1
# Необходимо вывести имена всех учеников из списка с новой строки

# names = ['Оля', 'Петя', 'Вася', 'Маша']
# for name in names:
# print(name)


# Задание 2
# Необходимо вывести имена всех учеников из списка, рядом с именем показать количество букв в нём.

# names = ['Оля', 'Петя', 'Вася', 'Маша']
# for name in names:
# print(name, len(name))


# Задание 3
# Необходимо вывести имена всех учеников из списка, рядом с именем вывести пол ученика

# is_male = {
# 'Оля': False, # если True, то пол мужской
# 'Петя': True,
# 'Вася': True,
# 'Маша': False,
# }
# names = ['Оля', 'Петя', 'Вася', 'Маша']

# for name in is_male:
# if is_male[name] is True:
# print(name, 'Male')
# else:
# print(name, 'Female')


# Задание 4
# Даны группу учеников. Нужно вывести количество групп и для каждой группы – количество учеников в ней
# Пример вывода:
# Всего 2 группы.
# В группе 2 ученика.
# В группе 3 ученика.

# groups = [
# ['Вася', 'Маша'],
# ['Оля', 'Петя', 'Гриша'],
# ]

# amount_groups = len(groups)
# print(f'Всего {amount_groups}')

# for group in groups:
# amount_students = len(group)
# print(f'В группе {amount_students} ученика\ов')


# Задание 5
# Для каждой пары учеников нужно с новой строки перечислить учеников, которые в неё входят.
# Пример:
# Группа 1: Вася, Маша
# Группа 2: Оля, Петя, Гриша

groups = [
['Вася', 'Маша'],
['Оля', 'Петя', 'Гриша'],
]

i = 1
for group in groups:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут можно использовать enumerate() в остальном в этом файле всё ок

print(f'Группа {i}: {", ".join(group)}')
i += 1
Loading