Загружаю еще ДЗ

This commit is contained in:
ehermakov 2023-07-03 23:57:22 +03:00
parent 6e479b101c
commit c821586597
54 changed files with 1062 additions and 0 deletions

3
Excercises/Magic/.idea/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/venv" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.11 (Magic)" project-jdk-type="Python SDK" />
</project>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/Magic.iml" filepath="$PROJECT_DIR$/.idea/Magic.iml" />
</modules>
</component>
</project>

27
Excercises/Magic/Point.py Normal file
View File

@ -0,0 +1,27 @@
from math import sqrt
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return '(' + str(self.x) + '|' + str(self.y) + ')'
def __eq__(self, other):
if type(other) is Point:
return self.x == other.x and self.y == other.y
return False
def __ne__(self, other):
return not self.__eq__(other)
def _intern(self):
return self.x + 42
def distance(self, point):
if type(point) is Point:
return sqrt((self.x - point.x) ** 2 + (self.y - point.y) ** 2)
else:
return 0

View File

@ -0,0 +1,68 @@
from Point import Point
class Rectangle:
def __init__(self, p1, p2):
self.p1 = Point(10, 20)
self.p2 = Point(20, 10)
if type(p1) is Point:
self.p1 = p1
if type(p2) is Point:
self.p2 = p2
def __eq__(self,other):
if other is Rectangle:
return self.p1 == other.p1 and self.p2 == other.p2
return False
def __ne__(self, other):
return not self.__eq__(other)
def a(self):
# return abs(self.p1.x - self.p2.x)
if self.p1.x > self.p2.x:
return self.p1.x - self.p2.x
else:
return self.p2.x - self.p1.x
def b(self):
# return abs(self.p1.y - self.p2.y)
if self.p1.y > self.p2.y:
return self.p1.y - self.p2.y
else:
return self.p2.y - self.p1.y
def perimeter(self):
return 2 * (self.a() + self.b())
def area(self):
return self.a() * self.b()
def intersection(self, other):
if self.p1.x <= other.p2.x <= self.p2.x and self.p2.y <= other.p1.y <= self.p1.y:
return True
elif self.p1.x <= other.p1.x <= self.p2.x and self.p2.y <= other.p1.y <= self.p1.y:
return True
elif other.p1.x <= self.p1.x <= other.p2.x and other.p2.y <= self.p1.y <= other.p1.y:
return True
elif other.p1.x <= self.p2.x <= other.p2.x and other.p2.y <= self.p1.y <= other.p1.y:
return True
else:
return False
def merge(self, other):
if type(other) is Rectangle:
a = min(self.p1.x, other.p1.x)
b = max(self.p1.y, other.p1.y)
c = max(self.p2.x, other.p2.x)
d = min(self.p2.y, other.p2.y)
return Rectangle(Point(a, b), Point(c, d))
else:
return self

31
Excercises/Magic/main.py Normal file
View File

@ -0,0 +1,31 @@
from Point import Point
from Rectangle import Rectangle
r0 = Rectangle(Point(10, 20), Point(20, 10))
r1 = Rectangle(Point(5, 15), Point(15, 5))
r2 = Rectangle(Point(15, 25), Point(25, 15))
r3 = Rectangle(Point(5, 25), Point(15, 15))
r4 = Rectangle(Point(15, 15), Point(25, 5))
r5 = Rectangle(Point(0, 15), Point(9, 5))
r6 = Rectangle(Point(21, 15), Point(25, 15))
r7 = Rectangle(Point(5, 9), Point(15, 0))
r8 = Rectangle(Point(5, 25), Point(15, 21))
# Эти четыре команды должны вывести True
print(r0.intersection(r1))
print(r0.intersection(r2))
print(r0.intersection(r3))
print(r0.intersection(r4))
# Эти четыре команды должны вывести False
print(r0.intersection(r5))
print(r0.intersection(r6))
print(r0.intersection(r7))
print(r0.intersection(r8))
print(r0.merge(r1))
print(r0.merge(r2))

View File

@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

View File

@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.11 (ДЗ 03072023)" project-jdk-type="Python SDK" />
</project>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/ДЗ 03072023.iml" filepath="$PROJECT_DIR$/.idea/ДЗ 03072023.iml" />
</modules>
</component>
</project>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/venv" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@ -0,0 +1,12 @@
def word_count(text):
import re
a = re.sub("[^А-Яа-я-A-Z-a-z ]", "", text)
b = list(a)
for i in b:
c = b.count(i)
return b
f = 'Я пришел, я ушел, я нашел'
print(word_count(f))

View File

View File

@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.11 (ДЗ 1 на пайтоне)" project-jdk-type="Python SDK" />
</project>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/ДЗ 1 на пайтоне.iml" filepath="$PROJECT_DIR$/.idea/ДЗ 1 на пайтоне.iml" />
</modules>
</component>
</project>

View File

@ -0,0 +1,61 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AutoImportSettings">
<option name="autoReloadType" value="SELECTIVE" />
</component>
<component name="ChangeListManager">
<list default="true" id="d68d4d79-2a82-42b3-8c06-d534d65e7a72" name="Changes" comment="" />
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="MarkdownSettingsMigration">
<option name="stateVersion" value="1" />
</component>
<component name="ProjectId" id="2HxWezTmVNf3ePlhI2YtX90ZLJD" />
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent">{
&quot;keyToString&quot;: {
&quot;RunOnceActivity.OpenProjectViewOnStart&quot;: &quot;true&quot;,
&quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot;
}
}</component>
<component name="RunManager">
<configuration name="ДЗ редактор массива" type="PythonConfigurationType" factoryName="Python" nameIsGenerated="true">
<module name="ДЗ 1 на пайтоне" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
</envs>
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
<option name="IS_MODULE_SDK" value="true" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/ДЗ редактор массива.py" />
<option name="PARAMETERS" value="" />
<option name="SHOW_COMMAND_LINE" value="false" />
<option name="EMULATE_TERMINAL" value="false" />
<option name="MODULE_MODE" value="false" />
<option name="REDIRECT_INPUT" value="false" />
<option name="INPUT_FILE" value="" />
<method v="2" />
</configuration>
</component>
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="d68d4d79-2a82-42b3-8c06-d534d65e7a72" name="Changes" comment="" />
<created>1669227314301</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1669227314301</updated>
</task>
<servers />
</component>
</project>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/venv" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@ -0,0 +1,45 @@
def myAdd(array):
a = input("Введите целое число ")
b = a.lstrip('-')
if b.isnumeric() and float(a) % 1 == 0:
a = int(a)
array.append(a)
return array
else:
return array
def myCut(array):
if len(array) > 0:
del array[-1]
return array
def menu():
print("1. Добавить элемент в массив")
print("2. Удалить последний элемент массива")
print("3. Выход")
array = []
while True:
menu()
inp = input()
if inp.isnumeric():
op = int(inp)
if 1 <= op <= 3:
if op == 1:
result = myAdd(array)
print("Ваш массив", result)
elif op == 2:
result = myCut(array)
print("Ваш массив", result)
elif op == 3:
print("Ваш массив", array)
print("Программа завершена")
break
else:
print("Ваш массив", array)
else:
print("Ваш массив", array)

View File

@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

View File

@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.11 (ДЗ рекурсия 1)" project-jdk-type="Python SDK" />
</project>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/ДЗ рекурсия 1.iml" filepath="$PROJECT_DIR$/.idea/ДЗ рекурсия 1.iml" />
</modules>
</component>
</project>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/venv" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@ -0,0 +1,81 @@
def factorial(n):
if type(n) is int or type(n) is float:
if n == 1 or n == 0:
return 1
elif n < 0:
return None
else:
return factorial(int(n-1)) * int(n)
else:
return None
def digits_r2l(n):
if type(n) is not int or n < 0:
return None
elif n < 10:
return str(n)
else:
s = str(n % 10)
return s + " " + digits_r2l(n // 10)
def digits_l2r(n):
if type(n) is not int or n < 0:
return None
elif n < 10:
return str(n)
else:
s = str(n % 10)
return digits_l2r(n // 10) + " " + s
#################################################
def verifier(test_name, actual, expected):
print(test_name)
if actual != expected:
print("=======> FAILED! <=======")
print(f"Got value <{actual}>")
print(f"Expected value is <{expected}>")
else:
print("PASSED")
print()
fact_tests = [(0, 1),
(1, 1),
(7, 5040),
(-1, None),
(1.1, 1),
(5.4, 120),
("Str", None),
(True, None)]
dr2l_tests = [(100, "0 0 1"),
(9871, "1 7 8 9"),
(1, "1"),
(-100, None),
(1.1, None),
(5.4, None),
("Str", None),
(True, None)]
dl2r_tests = [(100, "1 0 0"),
(9871, "9 8 7 1"),
(1, "1"),
(-100, None),
(1.1, None),
(5.4, None),
("Str", None),
(True, None)]
for i in range(len(fact_tests)):
verifier(f"Factorial test {i+1}", factorial(fact_tests[i][0]), fact_tests[i][1])
for i in range(len(dr2l_tests)):
verifier(f"DR2L test {i+1}", digits_r2l(dr2l_tests[i][0]), dr2l_tests[i][1])
for i in range(len(dl2r_tests)):
verifier(f"DL2R test {i+1}", digits_l2r(dl2r_tests[i][0]), dl2r_tests[i][1])

View File

@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

View File

@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.11 (Задача по рекурсии)" project-jdk-type="Python SDK" />
</project>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/Задача по рекурсии.iml" filepath="$PROJECT_DIR$/.idea/Задача по рекурсии.iml" />
</modules>
</component>
</project>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/venv" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@ -0,0 +1,75 @@
def factorial(n):
if type(n) is not int:
if type(n) is float:
m = int(n)
return factorial(m - 1) * m
if type(n) is str:
return None
else:
if n < 0:
return None
if n == 0:
return 1
return factorial(n - 1) * n
def digits_r2l(n):
if n % 1 != 0 or n <= 0:
return None
else:
return str(n % 10)
def digits_l2r(n):
pass
#################################################
def verifier(test_name, actual, expected):
print(test_name)
if actual != expected:
print("=======> FAILED! <=======")
print(f"Got value <{actual}>")
print(f"Expected value is <{expected}>")
else:
print("PASSED")
print()
fact_tests = [(0, 1),
(1, 1),
(7, 5040),
(-1, None),
(1.1, 1),
(5.4, 120),
("Str", None),
(True, None)]
dr2l_tests = [(100, "0 0 1"),
(9871, "1 7 8 9"),
(1, "1"),
(-100, None),
(1.1, None),
(5.4, None),
("Str", None),
(True, None)]
dl2r_tests = [(100, "1 0 0"),
(9871, "9 8 7 1"),
(1, "1"),
(-100, None),
(1.1, None),
(5.4, None),
("Str", None),
(True, None)]
for i in range(len(fact_tests)):
verifier(f"Factorial test {i+1}", factorial(fact_tests[i][0]), fact_tests[i][1])
for i in range(len(dr2l_tests)):
verifier(f"DR2L test {i+1}", digits_r2l(dr2l_tests[i][0]), dr2l_tests[i][1])
for i in range(len(dl2r_tests)):
verifier(f"DL2R test {i+1}", digits_l2r(dl2r_tests[i][0]), dl2r_tests[i][1])

View File

@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

View File

@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.11 (Задачи на исправление ошибок)" project-jdk-type="Python SDK" />
</project>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/Задачи на исправление ошибок.iml" filepath="$PROJECT_DIR$/.idea/Задачи на исправление ошибок.iml" />
</modules>
</component>
</project>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/venv" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@ -0,0 +1,37 @@
# Развернуть строку (например "Abc" -> "cbA")
def invert_string(string):
str_left = ""
str_right = ""
for i in range(len(string)//2):
str_left += string[-i-1]
str_right = string[i] + str_right
if len(string) % 2 > 0:
return str_left + string[len(string)//2] + str_right
return str_left + str_right
#################################################
def verifier(test_name, actual, expected):
print(test_name)
if actual != expected:
print("=======> FAILED! <=======")
print(f"Got value <{actual}>")
print(f"Expected value is <{expected}>")
else:
print("PASSED")
print()
test_string1 = "The World is not enough"
test_string2 = "Testing is key"
test_palindrome1 = "Sir, I demand, I am a maid named Iris"
test_palindrome2 = "Satire: Veritas"
test_palindrome3 = "Saippuakivikauppias"
string_tests = [test_string1, test_string2, test_palindrome1, test_palindrome2, test_palindrome3, '']
for i in range(len(string_tests)):
verifier(f"INVERT_STRING TEST {i+1}", invert_string(string_tests[i]), string_tests[i][::-1])

View File

@ -0,0 +1,46 @@
# "Ручной" аналог функции split()
def split_string(string, separator):
array = []
element = ""
for i in string:
if i != separator:
element += i
else:
array.append(element)
element = ""
array.append(element)
return array
#################################################
def verifier(test_name, actual, expected):
print(test_name)
if actual != expected:
print("=======> FAILED! <=======")
print(f"Got value <{actual}>")
print(f"Expected value is <{expected}>")
else:
print("PASSED")
print()
test_string1 = "The World is not enough"
test_string2 = "Testing is key"
test_split1 = "1, 2, 3, 4, 5, 6, 7, 8, 9"
test_split2 = "1 2 3 4 5 6 7 8 9"
test_split3 = "bagahajemanbdneorijahdhrea4"
split_string_tests = [test_split1, test_split2, test_split3, test_string1, test_string2, '']
for i in range(len(split_string_tests)):
separator = ','
verifier(f"SPLIT_STRING (SEPARATOR='{separator}') TEST {i+1}",
split_string(split_string_tests[i], separator),
split_string_tests[i].split(separator))
for i in range(len(split_string_tests)):
separator = ' '
verifier(f"SPLIT_STRING (SEPARATOR='{separator}') TEST {i+1}",
split_string(split_string_tests[i], separator),
split_string_tests[i].split(separator))

View File

@ -0,0 +1,76 @@
# "Ручной" аналог функции replace()
def replace_string(string, to_find, to_replace):
result = ""
ln_find = len(to_find)
ln_str = len(string)
i = 0
while i < ln_str:
if i + ln_find <= ln_str:
found = True
for j in range(ln_find):
if to_find[j] != string[i + j]:
found = False
break
if found:
result += to_replace
i += ln_find
else:
result += string[i]
i += 1
else:
result += string[i]
i += 1
return result
#################################################
def verifier(test_name, actual, expected):
print(test_name)
if actual != expected:
print("=======> FAILED! <=======")
print(f"Got value <{actual}>")
print(f"Expected value is <{expected}>")
else:
print("PASSED")
print()
test_replace_string1 = "The World is not enough"
test_replace_string2 = "Testing is key"
test_replace_string3 = "Sir, I demand, I am a maid named Iris"
test_replace_string4 = "Satire: Veritas"
test_replace_string5 = "Brum Brum Brum Brum "
replace_string_tests = [test_replace_string1, test_replace_string2, test_replace_string3, test_replace_string4, test_replace_string5, '']
for i in range(len(replace_string_tests)):
to_find = ' '
to_replace = '#'
verifier(f"SPLIT_STRING (FIND='{to_find}', REPLACE='{to_replace}') TEST {i+1}",
replace_string(replace_string_tests[i], to_find, to_replace),
replace_string_tests[i].replace(to_find, to_replace))
for i in range(len(replace_string_tests)):
to_find = 'no'
to_replace = 'NO'
verifier(f"SPLIT_STRING (FIND='{to_find}', REPLACE='{to_replace}') TEST {i+1}",
replace_string(replace_string_tests[i], to_find, to_replace),
replace_string_tests[i].replace(to_find, to_replace))
for i in range(len(replace_string_tests)):
to_find = ' is '
to_replace = 'BLUB'
verifier(f"SPLIT_STRING (FIND='{to_find}', REPLACE='{to_replace}') TEST {i+1}",
replace_string(replace_string_tests[i], to_find, to_replace),
replace_string_tests[i].replace(to_find, to_replace))
for i in range(len(replace_string_tests)):
to_find = 'Brum '
to_replace = ''
verifier(f"SPLIT_STRING (FIND='{to_find}', REPLACE='{to_replace}') TEST {i+1}",
replace_string(replace_string_tests[i], to_find, to_replace),
replace_string_tests[i].replace(to_find, to_replace))

View File

@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

View File

@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.11 (Много простых задач)" project-jdk-type="Python SDK" />
</project>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/Много простых задач.iml" filepath="$PROJECT_DIR$/.idea/Много простых задач.iml" />
</modules>
</component>
</project>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/venv" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@ -0,0 +1,214 @@
# Сумма элементов массива
def sum_array(array):
# Что должна возвращать функция?
sum = 0
# Проводим вычисления
for a in array:
sum = sum + a
# Вернуть значение
return sum
# Из суммы элементов с четным индексом вычесть элементы с нечетным индексом (0 - четный)
def sum_diff_array(array):
# Что должна возвращать функция?
result = 0
# Проводим вычисления
for e in range(len(array)):
if e % 2 == 0:
result = result + array[e]
else:
result = result - array[e]
# Вернуть значение
return result
# Максимальное число из массива помножить на минимальное число из массива
def max_mul_min_array(array):
if len(array) == 0:
return 0
max_x = array[0]
min_x = array[0]
for w in array:
if w > max_x:
max_x = w
if w < min_x:
min_x = w
return max_x * min_x
# Развернуть строку (например "Abc" -> "cbA")
def invert_string(string):
# Что должна возвращать функция?
str1 = ""
# Проводим вычисления
length = len(string) - 1
while length >= 0:
str1 = str1 + string[length]
length = length - 1
# Вернуть значение
return str1
# Все буквы сделать заглавными (например "aBc" -> "ABC")
def to_upper_string(string):
str2 = ""
for c in string:
if 97 <= ord(c) <= 122:
str2 += chr(ord(c) - 32)
else:
str2 += c
return str2
# Все буквы сделать прописными (например "aBc" -> "abc")
def to_lower_string(string):
# Что должна возвращать функция?
str3 = ""
# Проводим вычисления
for c in string:
# Проверить, какая буква
if 65 <= ord(c) <= 90:
# Если большая - то превращаем в маленькую и добавляем в итоговую строку
str3 += chr(ord(c) + 32)
else:
str3 += c
return str3
# Проверить, является ли строка палиндромом (независимо от больших/маленьких букв)
def check_palindrome(string):
string = to_lower_string(string)
for c in range(len(string)//2):
if string[c] != string[-1-c]:
return False
return True
# Проверить, является ли строка палиндромом (независимо от больших/маленьких букв и знаков пунктуации/пробелов)
def check_palindrome_escaped(string):
string = to_lower_string(string)
marks = [' ', ':', ',', '.', '?', '!']
left = 0
right = len(string) - 1
while right > left:
if string[left] in marks:
left += 1
if string[right] in marks:
right -= 1
if string[left] != string[right]:
return False
left += 1
right -= 1
return True
string = check_palindrome(string)
return string
# "Ручной" аналог функции split()
def split_string(string, separator):
pass
# "Ручной" аналог функции join()
def join_array(array, separator):
pass
#################################################
def verifier(test_name, actual, expected):
print(test_name)
if actual != expected:
print("=======> FAILED! <=======")
print(f"Got value <{actual}>")
print(f"Expected value is <{expected}>")
else:
print("PASSED")
print()
test_array1 = [6, 4, 7, -3, 6, -1, 5, 8, 4, -6, 8, 3, 6, 4, -7, 21, 6, 4, -1, 1]
test_array2 = [987, 342, -876, 182, -6534, 998, -11, 334, 0, 6654, -9901, 333, 111, 664]
test_array3 = [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
test_string1 = "The World is not enough"
test_string2 = "Testing is key"
test_palindrome1 = "Sir, I demand, I am a maid named Iris"
test_palindrome2 = "Satire: Veritas"
test_palindrome3 = "Saippuakivikauppias"
test_split1 = "1, 2, 3, 4, 5, 6, 7, 8, 9"
test_split2 = "1 2 3 4 5 6 7 8 9"
test_split3 = "bagahajemanbdneorijahdhrea4"
test_array4 = test_split1.split(',')
test_array5 = test_split2.split(' ')
test_array6 = test_split3.split('a')
sum_array_tests = [test_array1, test_array2, test_array3, [], [0]]
string_tests = [test_string1, test_string2, test_palindrome1, test_palindrome2, test_palindrome3, '']
palindrome_tests = [test_string1, test_string2, test_palindrome1, test_palindrome2, test_palindrome3, '']
split_string_tests = [test_split1, test_split2, test_split3, test_string1, test_string2, '']
join_array_tests = [test_array4, test_array5, test_array6, [], ['']]
for i in range(len(sum_array_tests)):
verifier(f"SUM_ARRAY TEST {i+1}", sum_array(sum_array_tests[i]), sum(sum_array_tests[i]))
for i in range(len(sum_array_tests)):
verifier(f"SUM_DIFF_ARRAY TEST {i+1}", sum_diff_array(sum_array_tests[i]), sum(sum_array_tests[i][0::2]) - sum(sum_array_tests[i][1::2]))
for i in range(len(sum_array_tests)):
if len(sum_array_tests[i]) == 0:
verifier(f"MAX_MUL_MIN_ARRAY TEST {i + 1}", max_mul_min_array(sum_array_tests[i]), 0)
else:
verifier(f"MAX_MUL_MIN_ARRAY TEST {i+1}", max_mul_min_array(sum_array_tests[i]), max(sum_array_tests[i]) * min(sum_array_tests[i]))
for i in range(len(string_tests)):
verifier(f"INVERT_STRING TEST {i+1}", invert_string(string_tests[i]), string_tests[i][::-1])
for i in range(len(string_tests)):
verifier(f"TO_UPPER_STRING TEST {i+1}", to_upper_string(string_tests[i]), string_tests[i].upper())
for i in range(len(string_tests)):
verifier(f"TO_LOWER_STRING TEST {i+1}", to_lower_string(string_tests[i]), string_tests[i].lower())
for i in range(len(palindrome_tests)):
verifier(f"CHECK_PALINDROME TEST {i+1}",
check_palindrome(palindrome_tests[i]),
(palindrome_tests[i].lower() == palindrome_tests[i].lower()[::-1]))
for i in range(len(palindrome_tests)):
val = "".join(e for e in palindrome_tests[i] if e.isalpha())
verifier(f"CHECK_PALINDROME_ESCAPED TEST {i+1}",
check_palindrome_escaped(palindrome_tests[i]),
(val.lower() == val.lower()[::-1]))
for i in range(len(split_string_tests)):
separator = ','
verifier(f"SPLIT_STRING (SEPARATOR='{separator}') TEST {i+1}",
split_string(split_string_tests[i], separator),
split_string_tests[i].split(separator))
for i in range(len(split_string_tests)):
separator = ' '
verifier(f"SPLIT_STRING (SEPARATOR='{separator}') TEST {i+1}",
split_string(split_string_tests[i], separator),
split_string_tests[i].split(separator))
for i in range(len(join_array_tests)):
separator = '#'
verifier(f"JOIN_ARRAY (SEPARATOR='{separator}') TEST {i+1}", join_array(join_array_tests[i], separator), separator.join(join_array_tests[i]))
for i in range(len(join_array_tests)):
separator = ''
verifier(f"JOIN_ARRAY (SEPARATOR='{separator}') TEST {i+1}", join_array(join_array_tests[i], separator), separator.join(join_array_tests[i]))

View File

@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

View File

@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.11 (задача на типы данных)" project-jdk-type="Python SDK" />
</project>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/задача на типы данных.iml" filepath="$PROJECT_DIR$/.idea/задача на типы данных.iml" />
</modules>
</component>
</project>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/venv" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@ -0,0 +1,44 @@
def verify(actual, expected):
if type(actual) == str:
actual = actual.lower()
if type(expected) == str:
expected = expected.lower()
if type(actual) != type(expected):
return -1
elif type(actual) == type(expected) and actual == expected:
return 1
else:
return 0
#################################################
def verifier(test_data):
print(test_data[0])
result = verify(test_data[1], test_data[2])
if result != test_data[3]:
print("=======> FAILED! <====ф===")
print(f"Got result <{result}>")
print(f"Expected result is <{test_data[3]}>")
else:
print("PASSED")
print()
tests = [
("Integer test 1", 1, 2, 0),
("Integer test 2", 2, 2, 1),
("Integer test 3", 2, -2, 0),
("Integer test 4", True, 2, -1),
("String test 1", "ABC", "CBA", 0),
("String test 2", "ABC", "ABC", 1),
("String test 3", "ABC", "abc", 1),
("String test 4", True, "True", -1),
("Bool test 1", True, False, 0),
("Bool test 2", True, True, 1),
("Bool test 3", False, False, 1),
("Bool test 4", None, True, -1),
]
for test in tests:
verifier(test)