This commit is contained in:
Марычев Павел Иванович 2021-07-31 17:10:28 +04:00
commit 8eaa630f67
12 changed files with 337 additions and 0 deletions

1
ch1/rock.py Normal file
View File

@ -0,0 +1 @@
print('You rock!')

6
ch2/dogcalc.py Normal file
View File

@ -0,0 +1,6 @@
dog_name = input('Как зовут вашу собаку? ')
dog_age = input('Сколько лет вашей собаке? ')
human_age = int(dog_age) * 7
# print(human_age)
print('Вашей собаке', dog_name, 'сейчас', human_age, 'по меркам людей')

41
ch3/rock.py Normal file
View File

@ -0,0 +1,41 @@
# Импорт библотеки рандом, для генерации случайных чисел
import random
winner = ''
random_choice = random.randint(0, 2)
# print('Компьютер выбирает', random_choice)
# присваиваем строку результату рандомного числа
if random_choice == 0:
computer_choice = 'камень'
elif random_choice == 1:
computer_choice = 'бумага'
else:
computer_choice = 'ножницы'
# print('Компьюетр выбирает', computer_choice)
user_choice = ''
# пользователь вводит свои данные
# user_choice = input('камень, ножницы или бумага? ')
while (user_choice != 'камень'
and user_choice != 'ножницы'
and user_choice != 'бумага'):
user_choice = input('камень, ножницы или бумага? ')
# print('Вы выбрали', user_choice, 'компьютер выбрал', computer_choice)
# логика программы
if computer_choice == user_choice:
winner = 'ничья'
elif computer_choice == 'бумага' and user_choice == 'камень':
winner = 'Компьютер'
elif computer_choice == 'камень' and user_choice == 'ножницы':
winner = 'Компьютер'
elif computer_choice == 'ножницы' and user_choice == 'бумага':
winner = 'Компьютер'
else:
winner = 'Пользователь'
# print(winner, 'выиграл!')
# результат программы, вывод на экран
if winner == 'ничья':
print('Мы оба выбрали', computer_choice, 'играем снова.')
else:
print(winner, 'выиграл, я выбрал', computer_choice, '.')

51
ch4/bubbles.py Normal file
View File

@ -0,0 +1,51 @@
scores = [
60, 50, 60, 58, 54, 54, 58, 50, 52,
54, 48, 69, 34, 55, 51, 52, 44, 51,
69, 64, 66, 55, 52, 61, 46, 31, 57,
52, 44, 18, 41, 53, 55, 61, 51, 44
]
costs = [
.25, .27, .25, .25, .25, .25,
.33, .31, .25, .29, .27, .22,
.31, .25, .25, .33, .21, .25,
.25, .25, .28, .25, .24, .22,
.20, .25, .30, .25, .24, .25,
.25, .25, .27, .25, .26, .29
]
# i = 0
length = len(scores)
max = 0
min = 0
max_list = []
# while i < length:
for i in range(length):
print('Пузырьковый раствор #' + str(i), '- результат:', scores[i])
# i += 1
if max < scores[i]:
max = scores[i]
print('Пузырьковых тестов:', length)
print('Наибольший результат:', max)
for i in range(length):
if scores[i] == max:
max_list.append(i)
cost = 100.0
most_effective = 0
# for i in range(len(costs)):
# if scores[i] == max and costs[i] <= cost:
# most_effective = i
# cost = costs[i]
# for i in max_list:
# if costs[i] <= cost:
# most_effective = i
# cost = costs[i]
for i in range(len(max_list)):
index = max_list[i]
if cost > costs[index]:
most_effective = index
cost = costs[index]
print('Наибольший результат:', max_list)
print('Раствор:', most_effective, 'самый выгодный, его цена -', cost)

16
ch4/scores.py Normal file
View File

@ -0,0 +1,16 @@
scores = [
60, 50, 60, 58, 54, 54, 58, 50, 52,
54, 48, 69, 34, 55, 51, 52, 44, 51,
69, 64, 66, 55, 52, 61, 46, 31, 57,
52, 44, 18, 41, 53, 55, 61, 51, 44
]
i = 0
max = 0
for i in range(len(scores)):
print('Пузырьковый раствор #', i, '- результат:', scores[i])
if max < scores[i]:
max = scores[i]
print('Пузырьковых тестов:', i)
print('Наибольший результат:', max)
print(max in scores)

27
ch4/sort.py Normal file
View File

@ -0,0 +1,27 @@
scores = [
60, 50, 60, 58, 54, 54, 58, 50, 52,
54, 48, 69, 34, 55, 51, 52, 44, 51,
69, 64, 66, 55, 52, 61, 46, 31, 57,
52, 44, 18, 41, 53, 55, 61, 51, 44
]
number_of_list = len(scores)
solution_numbers = list(range(number_of_list))
def bubble_sort(list, numbers):
swapped = True
while swapped:
swapped = False
for i in range(len(list)-1):
if list[i] < list[i+1]:
temp = list[i]
list[i] = list[i+1]
list[i+1] = temp
temp = numbers[i]
numbers[i] = numbers[i + 1]
numbers[i + 1] = temp
swapped = True
for i in range(0, 5):
print(str(i + 1) + '.', 'Пузырьковый раствор №' + str(solution_numbers[i]), '- результат:', scores[i])
bubble_sort(scores, solution_numbers)

16
ch4/super.py Normal file
View File

@ -0,0 +1,16 @@
characters = 'wasitar'
output = ''
length = len(characters)
i = 0
while (i < length):
output = output + characters[i]
i += 1
length = length * -1
i = -2
while (i >= length):
output = output + characters[i]
i = i -1
print(output)

14
ch5/avatar.py Normal file
View File

@ -0,0 +1,14 @@
def get_attribute(query, default):
question = query + ' [' + default + ']? '
answer = input(question)
if answer == '':
answer = default
print('Вы выбрали', answer)
return answer
hair = get_attribute('Цвет волос', 'темные')
hair_lenght = get_attribute('Длина волос', 'короткие')
eye = get_attribute('Цвет глаз', 'голубые')
gender = get_attribute('Пол', 'женский')
glasses = get_attribute('Носит очки', 'нет')
beard = get_attribute('Носит бороду', 'нет')

11
ch5/bark.py Normal file
View File

@ -0,0 +1,11 @@
def bark(name, weight):
if weight > 20:
print(name, 'говорит ГАВ-ГАВ')
else:
print(name, 'говорит гав-гав')
bark('Тузик', 40)
bark('Смайли', 9)
bark('Джексон', 12)
bark('Филя', 65)

90
ch6/analyze.py Normal file
View File

@ -0,0 +1,90 @@
import ch1text
def count_syllables_in_word(word):
count = 0
endings = '.,;!?:'
last_char = word[-1]
if last_char in endings:
processed_word = word[:-1]
else:
processed_word = word
if len(processed_word) <= 3:
return 1
if processed_word[-1] in 'eE':
processed_word = processed_word[:-1]
vowels = 'aeiouAEIOU'
prev_char_was_vowel = False
for char in processed_word:
if char in vowels:
if not prev_char_was_vowel:
count += 1
prev_char_was_vowel = True
else:
prev_char_was_vowel = False
if processed_word[-1] in 'yY':
count += 1
return count
def count_syllables(words):
count = 0
for word in words:
word_count = count_syllables_in_word(word)
count = count + word_count
return count
def count_sentences(text):
count = 0
for char in text:
if char in ('.', '?', '!'):
count += 1
return count
def output_results(score):
if score >= 90:
return 'Уровень 5-го класса'
elif score >= 80:
return 'Уровень 6-го класса'
elif score >= 70:
return 'Уровень 7-го класса'
elif score >= 60:
return 'Уровень 8-9-го класса'
elif score >= 50:
return 'Уровень 10-11-го класса'
elif score >= 30:
return 'Уровень студента вуза'
else:
return 'Уровень выпускнинка вуза'
def compute_readability(text):
total_words = 0
total_sentences = 0
total_syllables = 0
score = 0
words = text.split()
total_words = len(words)
total_sentences = count_sentences(text)
total_syllables = count_syllables(words)
score = (206.835 - 1.015 * (total_words / total_sentences) - 84.6 * (total_syllables / total_words))
score_result = output_results(score)
# print(words)
print(total_words, 'слов')
print(total_sentences, 'предложений')
print(total_syllables, 'слогов')
print(score, ' - удобочитаемость')
print(score_result)
# print(text)
compute_readability(ch1text.text)

33
ch6/ch1text.py Normal file
View File

@ -0,0 +1,33 @@
text = '''The first thing that stands between you and writing your first, real,
piece of code, is learning the skill of breaking problems down into
acheivable little actions that a computer can do for you. Of course,
you and the computer will also need to be speaking a common language,
but we'll get to that topic in just a bit.
Now breaking problems down into a number of steps may sound a new
skill, but its actually something you do every day. Lets look at an
example, a simple one: say you wanted to break the activity of fishing
down into a simple set of instructions that you could hand to a robot,
who would do your fishing for you. Heres our first attempt to do that,
check it out:
You can think of these statements as a nice recipe for fishing. Like any
recipe, this one provides a set of steps, that when followed in order,
will produce some result or outcome in our case, hopefully, catching
some fish.
Notice that most steps consists of simple instruction, like "cast line
into pond", or "pull in the fish." But also notice that other
instructions are a bit different because they depend on a condition,
like is the bobber above or below water?". Instructions might also
direct the flow of the recipe, like "if you havent finished fishing,
then cycle back to the beginning and put another worm on the hook."
Or, how about a condition for stopping, as in if youre done then go
home.
Youre going to find these simple statements or instructions are the
first key to coding, in fact every App or software program youve ever
used has been nothing more than a (sometimes large) set of simple
instructions to the computer that tell it what to do.'''
# print(text)

31
ch6/text.txt Normal file
View File

@ -0,0 +1,31 @@
The first thing that stands between you and writing your first, real,
piece of code, is learning the skill of breaking problems down into
acheivable little actions that a computer can do for you. Of course,
you and the computer will also need to be speaking a common language,
but we'll get to that topic in just a bit.
Now breaking problems down into a number of steps may sound a new
skill, but its actually something you do every day. Lets look at an
example, a simple one: say you wanted to break the activity of fishing
down into a simple set of instructions that you could hand to a robot,
who would do your fishing for you. Heres our first attempt to do that,
check it out:
You can think of these statements as a nice recipe for fishing. Like any
recipe, this one provides a set of steps, that when followed in order,
will produce some result or outcome in our case, hopefully, catching
some fish.
Notice that most steps consists of simple instruction, like "cast line
into pond", or "pull in the fish." But also notice that other
instructions are a bit different because they depend on a condition,
like “is the bobber above or below water?". Instructions might also
direct the flow of the recipe, like "if you havent finished fishing,
then cycle back to the beginning and put another worm on the hook."
Or, how about a condition for stopping, as in “if youre done” then go
home.
Youre going to find these simple statements or instructions are the
first key to coding, in fact every App or software program youve ever
used has been nothing more than a (sometimes large) set of simple
instructions to the computer that tell it what to do.