Выпуск №63. Основы Python из уроков Codecademy
|
|
"Машинное обучение — это область computer science, в которой машины учатся решать задачи, для которых они не были запрограммированы непосредственно. Проще говоря, машины наблюдают закономерности и пытаются прямо или косвенно некоторым способом имитировать их...
Глубокое обучение используется в промышленности для решения практических
задач в самых разных областях, таких как компьютерное зрение (изображения),
обработка естественного языка (текст) и автоматическое распознавание
речи. Проще говоря, глубокое обучение — это подмножество методов
машинного обучения, главным образом основанных на применении искусственных
нейронных сетей, которые представляют класс алгоритмов, подражающих
человеческому мозгу..." (Эндрю Траск)
Решил изучить нейронные сети, проведя обзор литературы на русском, остановился на книге Эндрю Траска "Грокаем глубокое обучение", где автор вначале книги дает понять, что основы Python необходимы. Прошел по быстрому курсы на Codecademy, и в качестве шпаргалки, сохранил для себя в этой статье 2 листинга (80% упражнений курса с комментариями)
Листинг main.py
c = "catS"[3] # 4 символ строки
print(c)
print(len(c)) # длина строки
print(c.lower()) # нижний регистр
print(c.upper()) # верхний регистр
print(str(2)) # переводим число в строку
print("life " + "of" + " Brain") # конкатенация
print(" pi around = "+str(3.14)) # при конкатенации преобразуем все в строку
name = "Mike"
name2 = "Sveta"
print("Hello %s! Hello %s" %(name,name2) ) # оператор переменной конкатинации
#name = input("What is your name?") # переназначаем переменную через ввод в консоли
print("Your name is %s" %(name))
from datetime import datetime # импортировали библиотеку даты и времени
print(datetime.now()) # текущее время
print(datetime.now().day)
print(datetime.now().date())
print(datetime.now().month)
# условные конструкции в процедуре
def clinic():
print ("You've just entered the clinic!")
print ("Do you take the door on the left or the right?")
answer = input("Type left or right and hit 'Enter'.").lower()
if answer == "left" or answer == "l":
print ("This is the Verbal Abuse Room, you heap of parrot droppings!")
elif answer == "right" or answer == "r":
print ("Of course this is the Argument Room, I've told you that already!")
else:
print ("You didn't pick left or right! Try again.")
clinic()
#clinic()
# условные конструкции в функции
def using_control_once():
if 2 < 3:
return "Success #1"
def using_control_again():
if 3 < 4:
return "Success #2"
print (using_control_once())
print (using_control_again())
# условные конструкции в функции с параметрами
def greater_less_equal_5(answer):
if answer > 5:
return 1
elif answer < 5:
return -1
else:
return 0
print (greater_less_equal_5(4))
print (greater_less_equal_5(5))
print (greater_less_equal_5(6))
# часть строки, к примеру ([1:6] выводит первые 6 символов со второй буквы)
pyg = 'ay'
#original = input('Enter a word:')
original = "Python"
if len(original) > 0 and original.isalpha():
print (original)
word = original.lower()
first = word[0]
new_word = word + first + pyg
new_word = new_word[1:len(new_word)]
print(new_word)
else:
print ('empty')
# импортирование библиотек
import math
print (math.sqrt(25))
everything = dir(math)
print(everything)
# Import *just* the sqrt function from math on line 3!
# from math import sqrt
# Встроенные функции
print(max(1,5,8))
print(min(-1,0,6,9,12))
print(type("Hello"))
print(abs(-42))
print(type(1.5))
#Пример листинга с функциями
def hotel_cost(nights):
return 140 * nights
def plane_ride_cost(city):
if city == "Charlotte":
return 183
elif city == "Tampa":
return 220
elif city == "Pittsburgh":
return 222
elif city == "Los Angeles":
return 475
def rental_car_cost(days):
cost = days * 40
if days >= 7:
return cost - 50
elif days >= 3:
return cost - 20
else:
return cost
def trip_cost(city, days, spending_money):
return rental_car_cost(days) + hotel_cost(days) + plane_ride_cost(city) + spending_money
print (trip_cost("Los Angeles", 5, 600))
# Lists - Списки
zoo_animals = ["pangolin", "cassowary", "sloth", "Cheburashka"];
# One animal is missing!
if len(zoo_animals) > 3:
print ("The first animal at the zoo is the " + zoo_animals[0])
print ("The second animal at the zoo is the " + zoo_animals[1])
print ("The third animal at the zoo is the " + zoo_animals[2])
print ("The fourth animal at the zoo is the " + zoo_animals[3])
numbers = [5, 6, 7, 8]
print ("Adding the numbers at indices 0 and 2...")
print (numbers[0] + numbers[2])
print ("Adding the numbers at indices 1 and 3...")
print (numbers[1] + numbers[3])
suitcase = []
suitcase.append("sunglasses")
suitcase.append("shirt")
suitcase.append("t-shirt")
suitcase.append("trousers")
list_length = len(suitcase) # Set this to the length of suitcase
print ("There are %d items in the suitcase." % (list_length))
print (suitcase)
animals = "catdogfrog"
cat = animals[:3] # The first three characters of animals
dog = animals[3:6] # The fourth through sixth characters
frog = animals[6:] # From the seventh character to the end
#Замена в словаре по индексу
animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]
duck_index = animals.index("duck") # Use index() to find "duck" / ищем индекс по значению и далее меняем на новое
animals.insert(duck_index, "cobra")
print (animals)
# Цикл для всех и каждого (For one and all)
my_list = [1,9,3,8,5,7]
for number in my_list:
print (number * 2)
# Сортировка
start_list = [5, 3, 1, 2, 4]
square_list = []
# Your code here!
for element in start_list:
square_list.append(element ** 2)
square_list.sort()
print (square_list)
residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106}
print (residents['Puffin'] )
print (residents['Sloth'])
print (residents['Burmese Python'])
#Добавление записей в списки
menu = {} # Empty dictionary
menu['Chicken Alfredo'] = 14.50 # Adding new key-value pair
print (menu['Chicken Alfredo'])
# Your code here: Add some dish-price pairs to menu!
menu['Chicken Romano'] = 19.90
menu['Chicken Ivano'] = 25.50
menu['Chicken Chickeno'] = 33.99
print ("There are " + str(len(menu)) + " items on the menu.")
print (menu)
# удаление записей
zoo_animals = { 'Unicorn' : 'Cotton Candy House',
'Sloth' : 'Rainforest Exhibit',
'Bengal Tiger' : 'Jungle House',
'Atlantic Puffin' : 'Arctic Exhibit',
'Rockhopper Penguin' : 'Arctic Exhibit'}
del zoo_animals['Unicorn']
del zoo_animals['Sloth']
del zoo_animals['Bengal Tiger']
zoo_animals['Rockhopper Penguin'] = 'Just a penguin'
print (zoo_animals)
backpack = ['xylophone', 'dagger', 'tent', 'bread loaf']
backpack.remove('dagger')
print (backpack)
shopping_list = ["banana", "orange", "apple"]
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
# Write your code below!
def compute_bill(food):
total = 0
for item in food:
total += prices[item]
return total
print (compute_bill(shopping_list))
# пример вложенных массивов
lloyd = {
"name": "Lloyd",
"homework": [90.0, 97.0, 75.0, 92.0],
"quizzes": [88.0, 40.0, 94.0],
"tests": [75.0, 90.0]
}
alice = {
"name": "Alice",
"homework": [100.0, 92.0, 98.0, 100.0],
"quizzes": [82.0, 83.0, 91.0],
"tests": [89.0, 97.0]
}
tyler = {
"name": "Tyler",
"homework": [0.0, 87.0, 75.0, 22.0],
"quizzes": [0.0, 75.0, 78.0],
"tests": [100.0, 100.0]
}
# Add your function below!
def average(numbers):
total = sum(numbers)
total = float(total)
total = total / len(numbers)
return total
def get_average(student):
homework = average(student["homework"])
quizzes = average(student["quizzes"])
tests = average(student["tests"])
return (0.1 * homework + 0.3 * quizzes + 0.6 * tests)
def get_letter_grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"
students = [lloyd, alice, tyler]
def get_class_average(students):
results = []
for student in students:
results.append(get_average(student))
return average(results)
print(get_class_average(students))
# добавление в конец списка
n = [1, 3, 5]
# Append the number 4 here
n.append(4)
print (n)
# удаление элементов из списков
n = [1, 3, 5]
# Remove the first item in the list here
n.pop(0)
print (n)
n = [1, 3, 5]
# Remove the first item in the list here
n.remove(1)
print (n)
n = [1, 3, 5]
# Remove the first item in the list here
del(n[0])
print (n)
# функция получения первого элемента списка
def list_function(x):
return x[0]
n = [3, 5, 7]
print (list_function(n))
# функция перебора списка
n = [3, 5, 7]
def print_list(x):
for i in range(0, len(x)):
print (x[i])
print_list(n)
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
# Add your function here
def flatten(lists):
results = []
for list in lists:
for numbers in list:
results.append(numbers)
return results
print (flatten(n))
# морской бой
# Импорт функции randint из библиотеки random.
from random import randint
# Объявление пустого списка с именем board
board = []
# Создание пяти строк, по пять ячеек в каждой, заполненных как ["O", "O", "O", "O", "O"]
for x in range(5):
board.append(["O"] * 5)
# Определение функции print_board(), которая через строчный метод .join объединит
# все пять “O” в целую строку, ликвидировав запятые и кавычки, которые мы видим при # выводе строки на экран.
def print_board(board):
for row in board:
print (" ".join(row))
print ("Let's play Battleship!")
print_board(board)
# Определение ф-ции, которая будет случайным образом генерировать координату
# игрового корабля по горизонтали.
def random_row(board):
return randint(0, len(board) - 1)
# Определение ф-ции, которая будет случайным образом генерировать координату
# игрового корабля по вертикали.
def random_col(board):
return randint(0, len(board[0]) - 1)
# Вызов ф-ций для генерации случайных координат игрового корабля.
ship_row = random_row(board)
ship_col = random_col(board)
print(ship_row)
print(ship_col)
# Everything from here on should go in your for loop!
# Be sure to indent four spaces!
# Поскольку игрок должен иметь 4 попытки, мы осуществляем 4-кратный проход по циклу.
for turn in range(4):
print ("Turn", turn + 1)
# Предлагаем игроку угадать координаты по горизонтали и по вертикали.
# guess_row = int(input("Guess Row:"))
# guess_col = int(input("Guess Col:"))
guess_row = ship_row # всегда победа, в настоящей игре этих строк нет
guess_col = ship_col # всегда победа, в настоящей игре этих строк нет
# Поясняем условия выигрыша. В случае победы завершаем работу программы.
if guess_row == ship_row and guess_col == ship_col:
print("Congratulations! You sunk my battleship!")
break
# Поясняем условия в случае отсутствия выигрыша.
else:
# Предусматриваем действие на случай, если игрок вышел за рамки игрового поля.
if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
print ("Oops, that's not even in the ocean.")
# Предусматриваем сообщение на случай, если игрок попал в ячейку, по которой уже стрелял.
elif (board[guess_row][guess_col] == "X"):
print ("You guessed that one already.")
# Предусматриваем сообщение на остальные случаи отсутствия выигрыша.
else:
print ("You missed my battleship!")
# Предусматриваем завершение игры, если игрок совершил уже 4 попытки.
if turn == 3:
print ("Game Over")
board[guess_row][guess_col] = "X"
# Print (turn + 1) here!
print_board(board)
# Циклы
count = 1
while True:
print (count)
count += 1
if count >= 10:
break
import random
count = 0
while count < 3:
num = random.randint(1, 6)
print (num)
if num == 5:
print ("Sorry, you lose!")
break
count += 1
else:
print ("You win!")
for i in range(20):
print (i)
numbers = [7, 9, 12, 54, 99]
print ("This list contains: ")
for num in numbers:
print (num)
# Add your loop below!
for num in numbers:
print (num ** 2)
d = {'a': 'apple', 'b': 'berry', 'c': 'cherry'}
for key in d:
# Your code here!
print ( key + " " + d[key])
#choices = ['pizza', 'pasta', 'salad', 'nachos']
#print ('Your choices are:')
#for index, item in enumerate(choices):
# print (index + 1, item)
list_a = [3, 9, 17, 15, 19]
list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]
for a, b in zip(list_a, list_b):
# Add your code here!
if a > b:
print (a)
else:
print (b)
# Является ли целым
def is_int(x):
if x - int(x) == 0:
return True
else:
return False
# факториал
def factorial(x):
result = x
medium = x
for i in range(x):
medium -= 1
if medium > 0:
result = result * medium
else:
break
return result
# является ли число простым
def is_prime(x):
if x < 2:
return False
if x == 2 or x == 3:
return True
else:
for n in range(2, x - 1):
if x % n == 0:
return False
return True
# в обратном порядке
def reverse(word):
reverse_word = []
rev_i = len(word) - 1
for letter in word:
if rev_i >= 0:
reverse_word.append(word[rev_i])
rev_i -= 1
else:
break
result = ''.join(reverse_word)
return result
print(reverse("Hello"))
def count(sequence, item):
result = 0
for i in range(len(sequence)):
if sequence[i] == item:
result += 1
return result
# произведение
def product(numbers):
result = 1
for i in range(len(numbers)):
result *= numbers[i]
return result
# Удалить повторы в списке not in (нет в)
def remove_duplicates(numbers):
result = []
for i in range(len(numbers)):
if numbers[i] not in result:
result.append(numbers[i])
return result
# Среднее значение
grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
def print_grades(grades):
for grade in grades:
print(grade)
def grades_sum(grades):
total = 0
for grade in grades:
total += grade
return total
def grades_average(grades):
sum_of_grades = grades_sum(grades)
average = sum_of_grades / float(len(grades))
return average
def grades_variance(scores):
average = grades_average(scores)
variance = 0
for score in scores:
variance += (average - score) ** 2
result = variance / len(scores)
return result
print(grades_variance(grades))
def grades_std_deviation(variance):
return variance ** 0.5
variance = grades_variance(grades)
print("All grades:", print_grades(grades))
print("Sum of grades:", grades_sum(grades))
print("Average grade:", grades_average(grades))
print("Grades variance:", grades_variance(grades))
print("Standard deviation:", grades_std_deviation(variance))
# ключи и значения в списках
my_dict = {
"First name": "Sergey",
"Last name": "Schmidtmann",
"Age": 109}
print (my_dict.keys())
print (my_dict.values())
# Построение списков
evens_to_50 = [i for i in range(51) if i % 2 == 0]
print (evens_to_50)
# Длина шага по индексу
to_one_hundred = range(101)
# Add your code below!
backwards_by_tens = to_one_hundred[::-10]
for i in backwards_by_tens:
print (i)
# Функциональное программирование (анонимные функции, лямбда)
my_list = range(16)
filt = filter(lambda x: x % 3 == 0, my_list)
for i in filt:
print (i)
languages = ["HTML", "JavaScript", "Python", "Ruby"]
l2 = filter(lambda x: x == "Python", languages)
for l in l2:
print(l)
# срезы
garbled = "!XeXgXaXsXsXeXmX XtXeXrXcXeXsX XeXhXtX XmXaX XI"
message = garbled[::-2]
print (message)
garbled = "IXXX aXXmX aXXXnXoXXXXXtXhXeXXXXrX sXXXXeXcXXXrXeXt mXXeXsXXXsXaXXXXXXgXeX!XX"
message = ""
l2=filter(lambda x: x != "X", garbled)
for l in l2:
message +=l
print (message)
from OOP import Fruit, ShoppingCart, Employee,PartTimeEmployee, Car
lemon = Fruit("lemon", "yellow", "sour", False)
lemon.description()
lemon.is_edible()
my_cart = ShoppingCart("John Doe")
my_cart.add_item("Trousers", 50)
milton = PartTimeEmployee("Bob")
print (milton.full_time_wage(10))
my_car = Car("DeLorean", "silver", 88)
print (my_car.condition)
my_car.drive_car()
print (my_car.condition)
# работа с файлами
#Запись
my_list = [i**2 for i in range(1,11)]
# Generates a list of squares of the numbers 1 - 10
f = open("output.txt", "w")
for item in my_list:
f.write(str(item) + "\n")
f.close()
#Чтение
my_file = open("output.txt", "r")
print (my_file.read())
my_file.close()
"""
with open("output.txt", "w") as my_file:
my_file.write("Abibas")
if my_file.closed != True:
my_file.close()
print (my_file.closed)
"""
Листинг OOP.py (в одной папке с main.py)
class Fruit(object):
"""A class that makes various tasty fruits."""
def __init__(self, name, color, flavor, poisonous):
self.name = name
self.color = color
self.flavor = flavor
self.poisonous = poisonous
def description(self):
print ("I'm a %s %s and I taste %s." % (self.color, self.name, self.flavor))
def is_edible(self):
if not self.poisonous:
print ("Yep! I'm edible.")
else:
print ("Don't eat me! I am super poisonous.")
#lemon = Fruit("lemon", "yellow", "sour", False)
#lemon.description()
#lemon.is_edible()
class ShoppingCart(object):
"""Creates shopping cart objects
for users of our fine website."""
items_in_cart = {}
def __init__(self, customer_name):
self.customer_name = customer_name
def add_item(self, product, price):
"""Add product to the cart."""
if not product in self.items_in_cart:
self.items_in_cart[product] = price
print (product + " added.")
else:
print (product + " is already in the cart.")
def remove_item(self, product):
"""Remove product from the cart."""
if product in self.items_in_cart:
del self.items_in_cart[product]
print (product + " removed.")
else:
print (product + " is not in the cart.")
# Наследование
class Employee(object):
"""Models real-life employees!"""
def __init__(self, employee_name):
self.employee_name = employee_name
def calculate_wage(self, hours):
self.hours = hours
return hours * 20.00
# Add your code below!
class PartTimeEmployee(Employee):
def calculate_wage(self, hours):
self.hours = hours
return hours * 12.00
def full_time_wage(self, hours):
return super(PartTimeEmployee, self).calculate_wage(hours)
#milton = PartTimeEmployee("Bob")
#print milton.full_time_wage(10)
class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
def display_car(self):
return "This is a " + str(self.color) + " " + str(self.model) + " with " + str(self.mpg) + " MPG."
def drive_car(self):
self.condition = "used"



















Добавить комментарий (через VK):