Skip to content
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
89 changes: 89 additions & 0 deletions Practice/MIsakichev/Lecture2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
#Лекция ДВА
# first task
def biggestPrint(a,b):
if(a>b):
print(a)
else: print(b)
biggestPrint(2,4)
biggestPrint(15,11)

#second task
def biggestReturn(a,b):
if(a>b):
return a
else:return b
result = biggestReturn(100,200)
result2=biggestReturn(1000,500)
print(result)
print(result2)

#oop task GAME
class Characters:
def __init__(self,name,capability):
self.name=name,
self.capability=capability
@staticmethod
def gameStarted():
print("Game started")

def running(self,speed):
print(f'{self.name} is beginning running with speed {speed}')
return 'Running'

def usingCapability(self):
print(f'{self.name}using capability {self.capability}')
return self.capability

def pickUpItemForUpgrade(self):
print(f'{self.name}picked up item BonusSpeed')
return 'BonusSpeed'

def pickUpItemForDowngrade(self):
print(f'{self.name}picked up item SlowSpeed')
return 'SlowSpeed'

def UsingItem(self,item,speed,obj):
print(f"{self.name}using item on {obj}")
if item == 'BonusSpeed':
return speed + 10
elif item=='SlowSpeed':
return speed - 20
else : return 0

def flying(self,speed):
print(f'{self.name} is beginning flying with speed {speed} ')
return 'flying'
#воспроизвести в зависимости от действия анимацию
def chooseAnimation(self,anim):
if anim == 'Running':
print(f'{self.name} run animation starts')
if anim == 'flying':
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.

Почему здесь и ниже if, а не elif? В чем будет разница?

print(f'{self.name} fly animation starts')
if anim == 'Shooting':
print(f'{self.name} shooting animation starts')
if anim == 'Attack from air':
print(f'{self.name} attack from air animation starts')
if anim == 'Attack with axe':
print(f'{self.name} attack with axe animation starts')
#Взять анимацию
def getAnim(self,anim):
return anim

def getItem(self,item):
return item

Characters.gameStarted()
human = Characters("Human","Shooting")
daemon = Characters("Demon","Attack from air")
ork=Characters("Ork","Attack with axe")

human.chooseAnimation(human.getAnim(human.running(50)))
daemon.chooseAnimation(daemon.getAnim(daemon.flying(100)))
ork.chooseAnimation(ork.getAnim(ork.running(75)))
speedDown = daemon.UsingItem(daemon.getItem(daemon.pickUpItemForDowngrade()),50,'Human')
human.chooseAnimation(human.getAnim(human.running(speedDown)))
speedUp=human.UsingItem(human.getItem(human.pickUpItemForUpgrade()),speedDown,'Human')
human.chooseAnimation(human.getAnim(human.running(speedUp)))
human.chooseAnimation(human.getAnim(human.usingCapability()))
daemon.chooseAnimation(daemon.getAnim(daemon.usingCapability()))
ork.chooseAnimation(ork.getAnim(ork.usingCapability()))
90 changes: 90 additions & 0 deletions Practice/MIsakichev/Lecture3_4.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
#Лекция 3-4
#task one
def FizzBuzz(i):
if i % 15 == 0:
print("FizzBuzz")
elif i % 5 == 0:
print("Buzz")
elif i % 3 == 0:
print("Fizz")
else: print(i)

for i in range(1,101):
FizzBuzz(i)

#task two
def number():
num = input('Enter the number')
j=0
for i in num:
if(len(num) > 5):
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.

Не стоит эту проверку повторять для КАЖДОГО символа.

print("Можно вводить только пятизначные цифры")
break
else:
j+=1
print(f'{j} цифра равна {i}')
number()

#task three
def selecting_sort(arr):
for i in range(len(arr) - 1):
k= i
j = i + 1
while j < len(arr):
if arr[j] < arr[k]:
k = j
j += 1
arr[i], arr[k] = arr[k], arr[i]

arr = [0,3,24,2,3,7]
print('Before sorting')
print(arr)
selecting_sort(arr)
print('after sorting')
print(arr)

#task four

def str_deploy(str):
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.

Имеет смысл передавать сюда отдельным параметром опцию, что на что менять, чтоб не было путаницы.

ch=' '
if '\t' in str:
if ch in str:
str = str.replace(ch, '\t')
str = str.replace('\t',' ')
return str

str1 = 'Privet\tmenya zovut Vasya\tI live in Moscow'
str3 = str_deploy(str1)
print(str1)


#task five
def templates(line):
dict = {'Goodbye':'Hello','hate':'Love'}
for key, v in dict.items():
line = line.replace(key, v)
return line

string = 'Goodbye I hate you '
print(templates(string))

#task six
import numpy as np
def deleting_column(list):
k=0
num = int(input('enter the number for deleting column consist of this number'))
for i in list:
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.

list - далеко не самое удачное имя для переменной, т.к. это имя типа.

for j in i:
if j == num:
list = np.delete(list,k,1)
else:
k+=1
k=0
return list
l =[[1,2,33,100],
[44,5,6,245],
[7,8,9,17]]
l = deleting_column(l)
print('Matrix after deleting')
print(l)
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.

Однако, если посмотреть на вывод, столбец, как таковой не удаляется, просто вместо чисел в нем остаются пустые элементы.


69 changes: 69 additions & 0 deletions Practice/MIsakichev/Lecture5.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
#ЛЕКЦИЯ ПЯТЬ
#task one
class Man:
def __init__(self,name):
self.name=name

def solve_task(self):
print ("I'm not ready yet")
man = Man("Vasya")
man.solve_task()

#task two
import time
import random

class Pupil(Man):
def __init__(self,name):
super().__init__(name)

def solve_task(self):
a = random.randint(3,6)
time.sleep(a)
print("I'm not ready yet")
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.

Тот же код есть у родителя. Лучше переиспользовать его.


p = Pupil('Vasya')
p.solve_task()

#task three
import tempfile
import os
class WrapStrToFile:
def __init__(self):
self.filepath = tempfile.mktemp()

@property
def content(self):
try:
file = open(self.filepath, 'r')
string = file.read()
file.close()
return string

except OSError:
return "File not found"

@content.setter
def content(self, value):
try:
file = open(self.filepath, 'w')
file.write(value)
file.close()
except Exception as ex:
print("Unexpected error: {}".format(ex))

@content.deleter
def content(self):
try:
os.remove(self.filepath)
except Exception as ex:
print("Unexpected error: {}".format(ex))


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
29 changes: 29 additions & 0 deletions Practice/MIsakichev/Lecture6.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#ЛЕКЦИЯ ШЕСТЬ
#task three
import time
class Calculate_time:
def __init__(self):
self.start = 0

def __enter__(self):
self.start = time.time()
return self

def __exit__(self, exc_type, exc_val, exc_tb):
print(f"Time of execution is = {time.time() - self.start}")


with Calculate_time():
buffer = []
for k in range(1, 10000000):
buffer.append(k**2)

#task four
import itertools as it
def list_transform(arr):
list(it.chain([1, 2, 3], [4, 5], [6, 7]))
print(list(it.filterfalse(lambda x: len(x) < 5, arr)))
return list(it.combinations("testing", 4))

a = ['Hello','my','name','is','Vasya']
print(list_transform(a))
92 changes: 92 additions & 0 deletions Practice/MIsakichev/Lecture7.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
#ЛЕКЦИЯ СЕМЬ
#task one
import datetime as dating

def calculate_working_days(start, end):

if start > end:
return "Uncorrect date"
else:
total = ((end - start).days)+ 1
days = (int(total / 7))
summary = days * 5

for key in range(days * 7 , total):
holyday = (start + dating.timedelta(key)).weekday()
if holyday!= 5 and holyday != 6:
summary = summary + 1
return summary

date_01 =dating.date(2015,4,11)
date_02 = dating.date(2020,4,11)
print(f'Количество дней = {calculate_working_days(date_01,date_02)}')
date_02 =dating.date(2015,4,11)
date_01 = dating.date(2020,4,11)
print(calculate_working_days(date_01,date_02))

#Task two
import subprocess

def reading_file(name):
process = subprocess.Popen(['type', name], shell=True)
process.wait()
res = process.communicate()
if process.returncode:
return res
reading_file('test.txt')
print(" ")

#Task three
import pickle
import random


class Human:
def __init__(self, first_name, surname, age, place,work):
self.first_name = first_name
self.surname = surname
self.age = age
self.place = place
self.work = work

def __str__(self):
str = f'first_name = {self.first_name} , surname = {self.surname}, age = {self.age} , place = {self.place}, work = {self.work}'
return str


def create_people(ammount):
first_names = ['Alexander', 'Ivan', 'Kirill', 'Mikhail', 'Vasya']
surname = ['Makarov', 'Bobrov', 'Svetlov', 'Ivanov', 'Klimov']
place = ['Moscow', 'Nizhy_Novgorod', 'Kazan', 'New_York', 'Paris']
work = ['developer', 'plumber', 'surgery', 'manager', 'tester']
list= []
if ammount > 0:
for key in range(ammount):
list.append(Human(random.choice(first_names),
random.choice(surname),
random.randint(18, 50),
random.choice(place),
random.choice(work)))
with open('human.data', 'wb') as readings:
j = 0
while j < ammount:
pickle.dump(list[j], readings, protocol=pickle.HIGHEST_PROTOCOL)
j += 1
elif ammount <= 0:
print("Количество должно быть больше нуля")

return list


def printing_list(file, buffer):
with open(file, 'rb+') as files:
for key in buffer:
people_list = pickle.load(files)
print(f'{people_list}')


if __name__ == '__main__':
arr = create_people(5)
printing_list('human.data', arr)
arr = create_people(0)
printing_list('human.data',arr)
Loading