python's People
python's Issues
Les17_123
O(n*m)
O(1)
O(nm + m^2)
Hash
class HashTable:
def init(self, size):
self.elems = [None] * size
self.size = size
def hash(self, key):
return key % self.size
def add(self, value):
hash = self.hash(value)
if self.elems[hash] is None:
self.elems[hash] = value
else:
i = 1
while True:
index = (hash + i) % self.size
if self.elems[index] is None:
self.elems[index] = value
break
i += 1
def print_ht(self):
output = []
for i in range(self.size):
if self.elems[i] is not None:
output.append(f"{i} -> {self.elems[i]}")
else:
output.append(f"{i} -> ")
print("\n".join(output))
ht = HashTable(10)
ht.add(13)
ht.add(73)
ht.add(23)
ht.add(14)
ht.print_ht()
Les3_2
stage_1 = str(input('1 стадия развития человека'))
stage_2 = str(input('2 стадия развития человека'))
stage_3 = str(input('3 стадия развития человека'))
stage_4 = str(input('4 стадия развития человека'))
stage_5 = str(input('5 стадия развития человека'))
print(stage_1, stage_2, stage_3, stage_4, stage_5, sep='=>')
Les4_2
num = str(input('Введите 5-ти значное число'))
res1 = int(num[-2]) ** int(num[-1])
res2 = res1 * int(num[-3])
res3 = int(num[-5]) - int(num[-4])
result = float(res2 / res3)
print(result)
Les6_2
x = int(input('Введите натуральное число: '))
if x > 2000000000:
print('Ошибка: введённое число больше 2 млрд.')
else:
count = 0
while x > 0:
x //= 2
count += 1
print(count)
Les15_1
class Transport:
def __init__(self, name, max_speed, mileage):
self.name = name
self.max_speed = max_speed
self.mileage = mileage
def get_trans(self):
print(f'Название автомобиля: {self.name}')
print(f'Максимальная скорость: {self.max_speed}')
print(f'Пробег: {self.mileage}')
autobus = Transport('Ikarus', 120, 30000)
autobus.get_trans()
Les4_1
side_A = float(input('Введите первую сторону прямоугольника'))
side_B = float(input('Введите вторую сторону прямоугольника'))
ploshad = side_A * side_B
perimetr = side_A * 2 + side_B * 2
print(f'Площадь прямоугольника: {ploshad}')
print(f'Периметр прямоугольника: {perimetr}')
Les11_1
num = int(input('Введите натуральное целое число: '))
def fact_to_mas(num):
mas = []
for i in range(1, num + 1):
f = fact(i)
mas.append(f)
mas.reverse()
return mas
def fact(num):
count = 1
for i in range(1, num + 1):
count += i
return count
factorial = fact_to_mas(num
)
print(factorial)
Les11_2
import collections
pets = {}
pets[0] = 0
def create():
last = collections.deque(pets, maxlen=1)[0]
id = last + 1
pets[id] = {}
name = str(input(f'Введите имя питомца: '))
pets[id][name] = {
'Вид питомца': '',
'Возраст питомца': 0,
'Имя владельца': ''
}
type = str(input(f'Вид питомца: '))
pets[id][name]['Вид питомца'] = type
age = int(input(f'Возраст питомца: '))
pets[id][name]['Возраст питомца'] = age
owner = str(input(f'Имя владельца: '))
pets[id][name]['Имя владельца'] = owner
print('Запись о питомце добавлена!')
return True
def read(id):
if id in pets:
name = get_name(id)
age = int(str(pets[id][name]['Возраст питомца'])[-1])
god = get_suffix(age)
print(f'Это {pets[id][name]["Вид питомца"]} по кличке "{name}". Возраст питомца: {pets[id][name]["Возраст питомца"]} {god}. Имя владельца: {pets[id][name]["Имя владельца"]}')
return True
else:
print('питомец не найден')
return False
def update(id):
if id in pets:
name = get_name(id)
type = str(input(f'Вид питомца: '))
pets[id][name]['Вид питомца'] = type
age = int(input(f'Возраст питомца: '))
pets[id][name]['Возраст питомца'] = age
owner = str(input(f'Имя владельца: '))
pets[id][name]['Имя владельца'] = owner
print('Запись о питомце изменена!')
return True
else:
print('Питомец не найден')
return False
def delete(id):
if id in pets:
del pets[id]
print('Запись удалена!')
return True
else:
print('Питомец не найден')
return False
def get_pet(id):
if id > 0 in pets.keys():
return print(pets[id])
else:
return False
def get_name(id):
for name in pets[id]:
return name
def get_suffix(age):
god = ''
if age in range(11, 15) or age in [0, 5, 6, 7, 8, 9]:
god = 'лет'
elif age == 1:
god = 'год'
else:
god = 'года'
return god
def pets_list():
for id in pets:
get_pet(id)
return True
command = str(input('Введите команду: '))
while command != 'stop':
if command == '':
print('Пустая строка')
elif command == 'create':
create()
elif command == 'read':
id = int(input('Введите id питомца: '))
read(id)
elif command == 'update':
id = int(input('Введите id питомца: '))
update(id)
elif command == 'delete':
id = int(input('Введите id питомца: '))
delete(id)
elif command == 'pets_list':
pets_list()
command = str(input('Введите команду: '))
Les3_1
type_animal = str(input())
age = int(input())
name = str(input())
print(f'Это {type_animal} по кличке "{name}". Возраст: {age} года.')
Les10_2
my_dict = {}
num_1 = int(input('Введите первое число: '))
num_2 = int(input('Введите второе число: '))
if num_1 < num_2:
for i in range(num_1, num_2 + 1):
my_dict[i] = i ** i
print(my_dict)
else:
for i in range(num_1, num_2 - 1, -1):
my_dict[i] = i ** i
print(my_dict)
Les16_2
class Turtle:
def init(self, x=0, y=0, s=1):
self.x = x
self.y = y
self.s = s
def go_up(self):
self.y += self.s
def go_down(self):
self.y -= self.s
def go_left(self):
self.x -= self.s
def go_right(self):
self.x += self.s
def evolve(self):
self.s += 1
def degrade(self):
if self.s > 1:
self.s -= 1
else:
raise ValueError("S should be more than 0")
def count_moves(self, x2, y2):
dist_x = abs(self.x - x2)
dist_y = abs(self.y - y2)
moves = (dist_x + dist_y) / self.s
if moves % 1 != 0:
moves = int(moves) + 1
else:
moves = int(moves)
return moves
turtle = Turtle(0, 0, 1)
print(turtle.count_moves(-5, 7))
Les7_1
s = str(input(f'Введите одну строку без пробелов: '))
d = int(len(s))
poly = True
for i in range(d):
if s[i] == s[d-1]:
d -= 1
else:
poly = False
if poly is True:
print('yes')
else:
print('no')
Derevo
class Node:
def init(self, value):
self.value = value
self.left = None
self.right = None
self.parent = None
class BinarySearchTree:
def init(self):
self.root = None
def add_list(self, l):
self.root = self.add_data(l, 0, len(l)-1)
def add_data(self, l, left, right):
if left > right:
return None
mid = (left + right) // 2
node = Node(l[mid])
node.left = self.add_data(l, left, mid-1)
if node.left is not None:
node.left.parent = node
node.right = self.add_data(l, mid+1, right)
if node.right is not None:
node.right.parent = node
return node
def find(self, value):
if self.root.value is None:
return False
if self.root.value == value:
return True
node = self.find_node(self.root, value)
if node is None:
return False
return True
def find_node(self, cn, value):
if cn is None:
return None
if cn.value == value:
return cn
if cn.value > value:
res = self.find_node(cn.left, value)
return res
else:
res = self.find_node(cn.right, value)
return res
def find_min(self):
node = self.find_min_node(self.root)
return node.value
def find_min_node(self, cn):
if cn.left is None:
return cn
node = self.find_min_node(cn.left)
return node
def find_max(self):
node = self.find_max_node(self.root)
return node.value
def find_max_node(self, cn):
if cn.right is None:
return cn
node = self.find_max_node(cn.right)
return node
def delete(self, value):
if (self.root.left is None and
self.root.right is None and
self.root.value == value):
self.root.value = None
return
if (self.root.left is not None and
self.root.right is None and
self.root.value == value):
self.root = self.root.left
self.root.parent = None
return
if (self.root.left is None and
self.root.right is not None and
self.root.value == value):
self.root = self.root.right
self.root.parent = None
return
node = self.find_node(self.root, value)
if node is None:
raise Exception('Не могу найти узел для удаления')
self.delete_data(node)
def delete_data(self, node):
if (node.left is None and node.right is None):
if node.parent.left == node:
node.parent.left = None
else:
node.parent.right = None
return
if (node.left is not None and node.right is None):
if node.parent.left == node:
node.parent.left = node.left
else:
node.parent.right = node.left
return
if (node.left is None and node.right is not None):
if node.parent.left == node:
node.parent.left = node.right
else:
node.parent.right = node.right
return
if (node.left is not None and node.right is not None):
if node.parent is None:
self.root = self.find_min_node(node.right)
self.root.left = node.left
self.root.right = node.right
return
min_node_of_right = self.find_min_node(node.right)
min_node_of_right.left = node.left
if node.parent.left == node:
node.parent.left = min_node_of_right
else:
node.parent.right = min_node_of_right
return
raise Exception('Что-то пощло не так. Не могу удалить узел')
def print_tree(self, node, level=0):
if node is not None:
print(' ' * 4 * level + f'- {node.value}')
self.print_tree(node.left, level + 1)
self.print_tree(node.right, level + 1)
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
bst = BinarySearchTree()
bst.add_list(nums)
bst.print_tree(bst.root)
bst.delete(8)
bst.print_tree(bst.root)
Les9_2
x = set()
y = set()
z = set()
numX = int(input(f'Введите количество чисел для первого списка: '))
if not (numX <= 100000):
print(f'Число "{numX}" превышает допустимое значение в 100000.')
else:
k = 0
for i in range(numX):
k = int(input(f'Введите {i + 1}-е число: '))
x.add(k)
numY = int(input(f'Введите количество чисел для второго списка: '))
if not (numY <= 100000):
print(f'Число "{numY}" превышает допустимое значение в 100000.')
else:
k = 0
for i in range(numY):
k = int(input(f'Введите {i + 1}-е число: '))
y.add(k)
z = x.intersection(y)
print(len(z))
Les15_2
class Transport:
def init(self, name, max_speed, mileage):
self.name = name
self.max_speed = max_speed
self.mileage = mileage
def seating_capacity(self, capacity):
return f"Вместимость одного автобуса {self.name} {capacity} пассажиров"
class Autobus(Transport):
def seating_capacity(self, capacity = 50):
return f"Вместимость одного автобуса {self.name} {capacity} пассажиров"
autobus = Autobus('Икарус', 120, 30000)
print(autobus.seating_capacity())
Les13_1
import random
def create():
mas = []
rows = int(input(f'Введите количество чисел по горизонтали: '))
cols = int(input(f'Введите количество чисел по вертикали: '))
for i in range(rows):
row = []
for j in range(cols):
row.append(random.randint(1, 100))
mas.append(row)
return mas
def sum(mas_1, mas_2):
if (len(mas_1) != len(mas_2) and len(mas_1[0]) != len(mas_2[0])):
return None
result = []
for i in range(len(mas_1)):
row = []
for j in range(len(mas_2[0])):
row.append(mas_1[i][j] + mas_2[i][j])
result.append(row)
return result
def mas_list(mas):
for row in mas:
for item in row:
print(item, end=" ")
print()
mas_1 = create()
mas_list(mas_1)
mas_2 = create()
mas_list(mas_2)
mas_3 = sum(mas_1, mas_2)
print(f'Сумма массивов: ')
mas_list(mas_3)
Les3_1
type_animal = str(input())
age = int(input())
name = str(input())
print(f'Это {type_animal} по кличке "{name}". Возраст: {age} года.')
Les6_1
num = int(input('Введите любое число: '))
num2 = [int(input(f'Введите {i+1}-е целое число: ')) for i in range(num)]
count = 0
for i in range(num):
if num2[i] == 0:
count += 1
print(count)
Les9_3
num = input(f'Введите числа через пробел: ').split()
unique_num = set()
for i in num:
if i in unique_num:
print("YES")
else:
print("NO")
unique_num.add(i)
Les8_1
num = int(input('Введите любое целое число: '))
while num < 0:
num = int(input(f'Число "{num}" не является положительным числом. Повторите ввод: '))
mas = []
k = 0
for i in range(num):
k = int(input(f'Введите {i+1}-е целое число: '))
while not (1 <= k <= 100000):
k = int(input(f'Введенное число "{k}" не входит в диапазон от 1 до 100000. Повторите ввод: '))
else:
mas.append(k)
mas.reverse()
print(*mas)
Les8_3
boat = int(input(f'Введите максимальную массу которую может выдержать лодка: '))
flag = False
mas = []
if not (1 <= boat <= 1000000):
print(f'Масса "{boat}"кг не входит в диапахон от 1 до 1000000.')
else:
count_fisher = int(input(f'Введите количество рыбаков: '))
if not (1 <= count_fisher <= 100):
print(f'Количество должно соответствовать диапазону от 1 до 100.')
else:
k = 0
for i in range(count_fisher):
k = int(input(f'Введите массу {i + 1}-го рыбака: '))
while not (1 <= k <= boat):
k = int(input(f'Введеная масса "{k}" не входит в диапазон от 1 до "{boat}" кг. Повторите ввод: '))
else:
mas.append(k)
flag = True
if flag is True:
count = 0
while len(mas) > 0:
ekipag = max(mas) + min(mas)
if ekipag < boat:
count += 1
mas.remove(max(mas))
if len(mas) > 0:
mas.remove(min(mas))
else:
count += 1
mas.remove(max(mas))
print(count)
Les14_1
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
def print_list(list, i = 0):
if i == len(list):
print('Конец списка')
return
print(list[i])
print_list(list, i + 1)
print_list(my_list)
Les8_2
num = int(input('Введите любое целое число: '))
while not (1 <= num <= 100000):
num = int(input(f'Число "{num}" не входит в диапахон от 1 до 100000. Повторите ввод: '))
arr = list(map(int, input(f'Введите массив чисел через пробел: ').split()))
f = True
for i in arr:
if not (1 <= i <= 1000000000):
print(f'Одно из введённых чисел не входит в диапазон от 1 до 1000000000.')
f = False
if f is True:
arr[2] = arr[1]
arr[1] = arr[0]
arr[0] = arr[-1]
print(*arr)
Les6_3
numA = int(input(f'Введите число А: '))
numB = int(input(f'Введите число B: '))
if numA > numB:
print(f'Ошибка. Должно соблюдаться условие A <= B')
else:
string = ''
for i in range(numA, numB):
if i % 2 == 0:
string += (str(i) + ' ')
i += 1
print(f'Все чётные числа на отрезке от {numA} до {numB}: {string}')
Les5_1
num = int(input('Введите любое целое число:'))
if num > 0:
if num % 2 == 0:
print('Положительное четное число')
else:
print('Положительное нечетное число')
elif num % 2 == 0:
print('Отрицательное четное число')
else:
print('Отрицательное нечетное число')
Les7_2
s = input("Введите строку до 1000 символов: ")
if len(s) > 1000:
print('Длина строки превосходит 1000 символов')
else:
new_s = ' '.join(s.split())
print(f'Изменённая строка: {new_s}')
Les9_1
num = int(input(f'Введите любое целое число: '))
max_value = 2000000000
if not (1 <= num <= 100000):
print(f'Число "{num}" не входит в диапахон от 1 до 100000.')
else:
numbers = set()
k = 0
for i in range(num):
k = int(input(f'Введите {i + 1}-е целое число: '))
while not (k < max_value):
k = int(input(f'Введенное число "{k}" превышает допустимое значение 2*10е9. Повторите ввод: '))
else:
numbers.add(k)
print(len(numbers))
Less4_1
Les16_1
class Kassa:
def init(self, balance = 0):
self.balance = balance
def top_up(self, cash):
self.balance += cash
return f'Баланс пополнен на: {cash}, и теперь составляет: {self.balance}'
def count_1000(self):
if self.balance < 1000:
return 'В кассе меньше 1 тысячи'
else:
res = self.balance // 1000
return f'В кассе {res} целых тысяч'
def take_awey(self, expense):
if self.balance < expense:
return 'В кассе недостаточно денег'
else:
self.balance -= expense
return f'Снятие наличных на сумму: {expense}. В кассе осталось: {self.balance}'
kassa = Kassa()
print(kassa.top_up(5439))
print(kassa.count_1000())
print(kassa.take_awey(3400))
Les10_1
pets = {}
name = str(input(f'Введите имя питомца: '))
pets[name] = {
'Вид питомца':'',
'Возраст питомца':0,
'Имя владельца':''
}
type = str(input(f'Вид питомца: '))
pets[name]['Вид питомца'] = type
age = int(input(f'Возраст питомца: '))
pets[name]['Возраст питомца'] = age
owner = str(input(f'Имя владельца: '))
pets[name]['Имя владельца'] = owner
year = int(str(pets[name]['Возраст питомца'])[-1])
god = ''
if year in range(11, 15) or year in [0, 5, 6, 7, 8, 9]:
god = 'лет'
elif year == 1:
god = 'год'
else:
god = 'года'
for key in pets:
print(f'Это {pets[key]["Вид питомца"]} по кличке "{key}". Возраст питомца: {pets[key]["Возраст питомца"]} {god}. Имя владельца: {pets[key]["Имя владельца"]}')
Les5_3
x = int(input('Введите минимальную сумму инвестиций:'))
maik = int(input('Введите количество денег Майкла:'))
ivan = int(input('Введите количество денег Ивана:'))
duble = maik + ivan
if duble < x:
print('0')
elif duble > x:
if maik > x < ivan:
print('2')
elif maik > x > ivan:
print('Maik')
elif maik < x < ivan:
print('Ivan')
else:
print('1')
Les5_2
s = str(input('Введите слово из маленьких латинских букв:'))
count = s.count('a')
if count > 0:
print(f'Слово содержит букву "a", и она встречается {count} раз(а)')
else:
print('false')
count = s.count('e')
if count > 0:
print(f'Слово содержит букву "e", и она встречается {count} раз(а)')
else:
print('false')
count = s.count('i')
if count > 0:
print(f'Слово содержит букву "i", и она встречается {count} раз(а)')
else:
print('false')
count = s.count('o')
if count > 0:
print(f'Слово содержит букву "o", и она встречается {count} раз(а)')
else:
print('false')
count = s.count('u')
if count > 0:
print(f'Слово содержит букву "u", и она встречается {count} раз(а)')
else:
print('false')
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.