Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
4d1e420
Заметила, что у меня тут выполненное задание завалялось.
titatatia Sep 24, 2023
36df366
Merge branch 'main' of https://github.com/IlyaOrlov/PythonCourse2.0_S…
titatatia Sep 24, 2023
7a14f5a
И это тоже)
titatatia Sep 24, 2023
3ce83c3
Merge branch 'main' of https://github.com/IlyaOrlov/PythonCourse2.0_S…
titatatia Sep 26, 2023
ed1cc17
Пока 4
titatatia Sep 29, 2023
89cb2ab
Merge branch 'main' of https://github.com/IlyaOrlov/PythonCourse2.0_S…
titatatia Sep 29, 2023
f95a5df
Merge branch 'main' of https://github.com/IlyaOrlov/PythonCourse2.0_S…
titatatia Oct 2, 2023
bff431c
Merge branch 'main' of https://github.com/IlyaOrlov/PythonCourse2.0_S…
titatatia Oct 4, 2023
9c6fd6b
Как поняла?)
titatatia Oct 5, 2023
06c65f1
Merge branch 'main' of https://github.com/IlyaOrlov/PythonCourse2.0_S…
titatatia Oct 6, 2023
b577991
Merge branch 'main' of https://github.com/IlyaOrlov/PythonCourse2.0_S…
titatatia Oct 9, 2023
131a13b
Merge branch 'main' of https://github.com/IlyaOrlov/PythonCourse2.0_S…
titatatia Oct 10, 2023
e6b5ba8
Новые
titatatia Oct 11, 2023
72a6920
Сюда?
titatatia Oct 11, 2023
b753d8e
Поправила
titatatia Oct 11, 2023
5228626
Поправила, но правильно ли?
titatatia Oct 11, 2023
51a8e38
Не рабочий, не понимаю что ему не нравится
titatatia Oct 11, 2023
8055d2f
Исправила
titatatia Oct 12, 2023
b4c0432
Вы про это?
titatatia Oct 12, 2023
03b2e74
Вроде работает
titatatia Oct 12, 2023
6049a8f
Так?
titatatia Oct 12, 2023
5b86059
Исправила в 12ст
titatatia Oct 13, 2023
62668b2
Добавила
titatatia Oct 13, 2023
1ce5583
Так лучше?
titatatia Oct 13, 2023
bac5ee7
Теперь понятно. Если за for представлять next, то это значительно пом…
titatatia Oct 16, 2023
271c0c3
Я не понимаю зачем ещё и ретерн, принт разве не аналог возврата?
titatatia Oct 16, 2023
bd4f4fb
Исправила
titatatia Oct 16, 2023
6c13a9e
Merge branch 'main' of https://github.com/IlyaOrlov/PythonCourse2.0_S…
titatatia Oct 17, 2023
3a0cfec
Merge branch 'main' of https://github.com/IlyaOrlov/PythonCourse2.0_S…
titatatia Oct 22, 2023
054bf4a
Merge branch 'main' of https://github.com/IlyaOrlov/PythonCourse2.0_S…
titatatia Oct 25, 2023
a7e932e
Merge branch 'main' of https://github.com/IlyaOrlov/PythonCourse2.0_S…
titatatia Oct 26, 2023
1edf356
Исправила
titatatia Nov 2, 2023
024ef10
Исправила
titatatia Nov 18, 2023
fd2920e
Исправила
titatatia Nov 18, 2023
75ba7cb
Исправила
titatatia Nov 18, 2023
88f92e4
Исправила
titatatia Nov 18, 2023
72999fc
Merge branch 'main' of https://github.com/IlyaOrlov/PythonCourse2.0_S…
titatatia Nov 21, 2023
5d80022
Исправила
titatatia Nov 21, 2023
622a8de
Исправила
titatatia Nov 22, 2023
1f1c627
Попробую исправить
titatatia Nov 22, 2023
30bbfbb
Исправила
titatatia Nov 22, 2023
cdc9cd4
Пока вроде так
titatatia Nov 22, 2023
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
33 changes: 33 additions & 0 deletions Practice/tshyregena/WrapStrToFIle.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import tempfile
import os


class WrapStrToFile:
def __init__(self):
self._filepath = tempfile.mkstemp()

@property
def content(self):
try:
with open(self._filepath, "r", encoding="utf-8") as file1:
return file1.read()
except FileNotFoundError:
return 'File doesnt exist'

@content.setter
def content(self, value):
with open(self._filepath, "w", encoding="utf-8") as file1:
file1.write(value)

@content.deleter
def content(self):
os.remove(self._filepath)


wstf = WrapStrToFile()
print(wstf.content) # Output: File doesn't exist
wstf.content = 'test str'
print(wstf.content) # Output: test_str
wstf.content = 'text 2'
print(wstf.content) # Output: text 2
del wstf.content
68 changes: 68 additions & 0 deletions Practice/tshyregena/pep8tasksh.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import sys
import os
import hashlib
import ast
import argparse
from time import *


class Shuffler:

def __init__(self, map): # Отсутствует параметр map
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

А почему этот параметр должен присутствовать?

self.map = {}

def rename(self, dirname, output): # Может быть статическим методом
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Не может. Т.к. в его теле используется self.map

mp3s = [] # Не выровнено, поэтому не видит
for root, directories, files in os.walk(dirname):
for file in files:
if file[-3:] == '.mp3':
mp3s.append([root, file])
for path, mp3 in mp3s:
hashname = self.generate_name() + '.mp3'
self.map[hashname] = mp3
os.rename(path + '/' + mp3), path + '/' + hashname)) # Возможно ошибка в названии mp3
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

В названии mp3 нет ошибки.

f = open(output, 'r')
f.write(str(self.map))

def restore(self, dirname, restore_path, filename): # Не принимает filename
with open(filename, '+') as f: # проблема с выравниванием
self.map = ast.literal_eval(f.read())
mp3s = []
for root, directories, files in os.walk(dirname):
for file in files:
if file[-3:] == '.mp3':
mp3s.append({root, file})
for path, hashname in mp3s:
os.rename(path + '/' + hashname, path + '/' + self.map[hashname]))
os.remove(restore_path)

def generate_name(self, seed=time()): # Название функции написано с ошибкой
return hashlib.md5(str(seed)).hexdigest() # проблема с выравниванием


def parse_arguments():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest='subcommand', help='subcommand help')
rename_parser = subparsers.add_parser('rename', help='rename help')
rename_parser.add_argument('dirname')
rename_parser.add_argument('-o', '--output', help='path to a file where restore map is stored')
restore_parser = subparsers.add_parser('restore', help="command_a help")
restore_parser.add_argument('dirname')
restore_parser.add_argument('restore_map')
args = parser.parse_args()
return args

def main():
args = parse_arguments()
if args.subcommand == 'rename':
if args.output:
Shuffler.rename(args.dirname, 'restore.info')
else:
Shuffler.rename(args.dirname, args.output)
elif args.subcommand == 'restore':
Shuffler.restore(args.dirname, args.restore_map)
else:
sys.exit()


main()
9 changes: 9 additions & 0 deletions Practice/tshyregena/алгоритм.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
lst = [5, 78, 4, 34]
for k in range(len(lst)):
nM = k
for i in range(k, len(lst)):
if lst[i] < lst[nM]:
nM = i
if nM != k:
lst[k], lst[nM] = lst[nM], lst[k]
print(lst)
11 changes: 11 additions & 0 deletions Practice/tshyregena/возврат.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
def fun(lst):
Comment thread
IlyaOrlov marked this conversation as resolved.
res = set()
for element in lst:
if element in res:
Comment thread
IlyaOrlov marked this conversation as resolved.
return element
else:
res.add(element)


lst1 = [4, 9, 8, 9, 1, 8, 6]
print(fun(lst1))
18 changes: 18 additions & 0 deletions Practice/tshyregena/декоратор.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
def fun_dec(fun):
Comment thread
IlyaOrlov marked this conversation as resolved.
def fun_nuw(*args, **kwargs):
Comment thread
IlyaOrlov marked this conversation as resolved.
print("="*10)
res = fun(*args, **kwargs)
print(res)
print("="*10)
return res
return fun_nuw


@fun_dec
def fun1(*args):
return max(args)


a = int(input("Введите первое число: "))
b = int(input("Введите второе число: "))
fun1(a, b)
26 changes: 26 additions & 0 deletions Practice/tshyregena/игра.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import random


lst = ["камень", "ножницы", "бумага"]
choice = random.choice(lst)
print(f"Приветствую тебя, я хочу сыграть с тобой в игру!")
p = input("Введите камень, ножницы или бумагу: ").lower()
if p == choice:
print("Ничья!")
elif p == "ножницы":
if choice == "камень":
print(f"Ваш выбор: {p}, выбор компьютера: {choice}. Вы проиграли")
else:
print(f"Ваш выбор: {p}, выбор компьютера: {choice}. Вы выйграли")
elif p == "бумага":
if choice == "камень":
print(f"Ваш выбор: {p}, выбор компьютера: {choice}. Вы выйграли")
else:
print(f"Ваш выбор: {p}, выбор компьютера: {choice}. Вы проиграли")
elif p == "камень":
if choice == "ножницы":
print(f"Ваш выбор: {p}, выбор компьютера: {choice}. Вы выйграли")
else:
print(f"Ваш выбор: {p}, выбор компьютера: {choice}. Вы проиграли")
else:
print("Вы ввели что-то не то")
30 changes: 30 additions & 0 deletions Practice/tshyregena/лекция_5/матрица.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@

def display(matrix1):
for r in matrix1:
print(r)


def display2(matrix3):
new_mat = []
for k in range(len(matrix3[0])):
new_row = []
for el in matrix3:
new_row.append(el[k])
new_mat.append(new_row)
return new_mat


matrix2 = [[5, 4, 3, 8],
[6, 6, 7, 8],
[3, 9, 0, 6]]
display(matrix2)
new_mat1 = display2(matrix2)
p1 = int(input("Столбец с каким числом вы хотите удалить: "))
i = 0
while i < len(new_mat1):
if p1 in new_mat1[i]:
del new_mat1[i]
else:
i += 1
new_mat2 = display2(new_mat1)
display(new_mat2)
11 changes: 11 additions & 0 deletions Practice/tshyregena/лекция_5/таб.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
with open("таб.txt", "r+", encoding="utf-8") as f:
s = f.read()
print(s)
p = input("Свернуть или развернуть символы табуляции: ").lower()
k = ""
if p == "свернуть":
k = s.replace(' ', '\t')
else:
k = s.replace('\t', ' ')
with open("таб.txt", "w") as f:
f.write(k)
3 changes: 3 additions & 0 deletions Practice/tshyregena/лекция_8/8.4.1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import itertools

print(list(itertools.chain([1, 2, 3], [4, 5], [6, 7])))
4 changes: 4 additions & 0 deletions Practice/tshyregena/лекция_8/8.4.2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
from itertools import filterfalse
lst = ['hello', 'i', 'write', 'cool', 'code']
res = filterfalse(lambda x: len(x) < 5, lst)
print(list(res))
7 changes: 7 additions & 0 deletions Practice/tshyregena/лекция_8/8.4.3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import itertools

letters = "password"
perms = itertools.permutations(letters)

for perm in perms:
print(perm)
14 changes: 14 additions & 0 deletions Practice/tshyregena/лекция_8/генератор.py
Comment thread
IlyaOrlov marked this conversation as resolved.
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@

def gen(name):
with open(name, "r", encoding="utf-8") as file:
for line in file:
print(file.readline())
yield line


r = input("Введите имя файла: ")
for i in gen(r):
print(i)
# print(next(r))
# print(next(r))
# print(next(r))
13 changes: 13 additions & 0 deletions Practice/tshyregena/лекция_8/для_итератора.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
Египетская летучая§ собака

§ Описание
Египетская летучая собака имеет длину примерно 17 см. Шерсть имеет окрас бурого цвета, причём брюхо окрашено светлее.

§ Распространение
Область распространения простирается от Египта и Аравийского полуострова до юга Турции и Кипра.

§ Образ жизни
Животные живут большими колониями, активны ночью. Питаются плодами, при этом бо́льшую часть их рациона составляют незрелые плоды, повреждённые насекомыми или грибами. В поисках пищи животные за ночь пролетают до 40 км. Любимая пища — это инжир, затем апельсины, финики, бананы и молодые листья рожкового дерева.

§ Размножение
Сезон размножения продолжается в природе с июня по сентябрь. Половая зрелость наступает в возрасте 9 месяцев. Период беременности длится приблизительно 115—120 дней. Самка, как правило, рожает одного детёныша в год, но иногда рождается и двойня. Приблизительно шесть недель самка носит детёныша на себе, не отпуская его. Позже она оставляет его висеть одного на скальных выступах, но продолжает кормить.
30 changes: 30 additions & 0 deletions Practice/tshyregena/лекция_8/итератор.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
class Par:
def __init__(self, text, p):
self.text = text
self.p = p
self.i = 0

def __iter__(self):
return self

def __next__(self):
res = ""
while self.i < len(self.text):
res1 = self.i
self.i += 1
if self.text[res1] != self.p:
res += self.text[res1]
else:
return res
if res:
return res
raise StopIteration


t = Par("Египетская летучая §собака имеет длину §примерно 17 см", "§")
it = iter(t)
while True:
try:
print(next(it))
except StopIteration:
break
21 changes: 21 additions & 0 deletions Practice/tshyregena/лекция_8/контекст.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import time


class MyMen:
def __enter__(self):
self.start_time = time.time()
print("Входим в менеджер контекста")

def __exit__(self, exc_type, exc_val, exc_tb):
print("Выходим из менеджера контекста")
elapsed_time = time.time() - self.start_time
print(f"Время выполнения операции: {elapsed_time}")


with MyMen() as timer:
kidd = "Кошка мяукает. Собака лает. Птичка чирикает. Лягушка квакает."
a = dict(мяукает='говорит - мяу', лает='говорит - гав', чирикает='говорит - чирик-чирик',
квакает='говорит - ква-ква')
for key, value in a.items():
kidd = kidd.replace(key, value)
print(kidd)
28 changes: 28 additions & 0 deletions Practice/tshyregena/лекция_9/рабочие_дни.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import datetime as dt


def fun(weekday, time):
res = []
i = 1
t = time
w = weekday
while i <= t:
w3 = w.weekday()
i += 1
w = w + dt.timedelta(days=1)
if w3 < 5:
res.append(w3)
Comment thread
IlyaOrlov marked this conversation as resolved.
return len(res)


y1 = int(input("Введите год первой даты в формате 'YYYY': "))
m1 = int(input("Введите месяц первой даты в формате 'M': "))
d1 = int(input("Введите день первой даты в формате 'D': "))
weekday1 = dt.datetime(y1, m1, d1)
print(f'{weekday1} это {weekday1.strftime("%A")}')
y2 = int(input("Введите год первой даты в формате 'YYYY': "))
m2 = int(input("Введите месяц первой даты в формате 'M': "))
d2 = int(input("Введите день первой даты в формате 'D': "))
weekday2 = dt.datetime(y2, m2, d2)
time3 = (weekday2 - weekday1).days
print(f"С начальной даты до конечной {fun(weekday1, time3)} рабочих дня")
5 changes: 5 additions & 0 deletions Practice/tshyregena/словарь.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
kidd = "Кошка мяукает. Собака лает. Птичка чирикает. Лягушка квакает."
a = dict(мяукает='говорит - мяу', лает='говорит - гав', чирикает='говорит - чирик-чирик', квакает='говорит - ква-ква')
for key, value in a.items():
kidd = kidd.replace(key, value)
print(kidd)
26 changes: 26 additions & 0 deletions Practice/tshyregena/спящий парень.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import time
import random


class Man:
def __init__(self, name):
self.name = name

@staticmethod
def solve_task():
print(f"I'm not ready yet")


class Pupil(Man):

@staticmethod
def solve_task():
r = random.randrange(3, 6)
time.sleep(r)
print(f"Я подумал {r} секунды, но я тоже не готов пока.")


m = Man("Гоша")
m.solve_task()
h = Pupil("Лев")
h.solve_task()
15 changes: 15 additions & 0 deletions Practice/tshyregena/таб.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
Кто любит Бога - церковь чтит,
Хмельное не бодрит - дурманит,
Деньга деньгу сама родит,
Тот не продаст, кто не обманет,
Охотник кормит псов заране,
Терпенье города бедёт
И стену всякую таранит,
Кто ищет тот всегда найдёт. Кто любит Бога - церковь чтит,
Хмельное не бодрит - дурманит,
Деньга деньгу сама родит,
Тот не продаст, кто не обманет,
Охотник кормит псов заране,
Терпенье города бедёт
И стену всякую таранит,
Кто ищет тот всегда найдёт.
Loading