text
stringlengths
37
1.41M
#Создайте игру, в которой компьютер выбирает какое-либо слово, а игрок должен его отгадать. #Компьютер сообщает игроку, сколько букв в слове, и дает пять попыток узнать, #есть ли какая-либо буква в слове, причем программа может отвечать только "Да" и "Нет". #Вслед за тем игрок должен попробовать отгадать слово. #Кодзоков М.М., 26.05.2016 import random words=("мурат","зачет","ргсу","алексей","солнце","настроение","работа") choice=random.choice(words) check=choice numbers=len(choice) symbol = random.randrange(numbers) i=4 k=0 print("Давай поиграемв игру. Я загадываю слово, а ты его отгадываешь.\nСначала ты называешь буквы, а я проверяю, если ли она в слове! У тебя 5 попыток") print("Слово загадано. В нем",numbers,"букв.") vibor=input("Вводи букву: ") while i>0: if vibor in check: print("Есть такая буква!") else: print("Нет такой буквы!") i-=1 vibor=input("Вводи еще одну букву: ") print("Попытки кончились. Теперь отгадывай слово!") while vibor != choice: vibor=input("Это слово: ") if vibor !=choice: print("Неправильно. Попробуй еще") print("Угадал! Это слово",choice) input("Нажми ENTER, чтобы я тебя освободил!")
# Задача 3. Вариант 8 # Напишите программу, которая выводит имя "Борис Николаевич Бугаев", # и запрашивает его псевдоним. Программа должна сцеплять две # эти строки и выводить полученную строку, разделяя имя и псевдоним с помощью тире. # # Egorov V. I. # 24.02.2016 name = "Борис Николаевич Бугаев" psname = "Андрей Белый" print(name, " - настоящее имя русский писателя, поэта, критика, мемуариста, стиховеда.") answer = input("\nВведите имя под которым прославилась знаменитость: ") while answer.find(psname) == -1 and answer.find("0") == -1: print(answer, "- неверный ответ.", name, "известна под другим именем.") answer = input("\nПопробуйте ещё раз (или введите \"0\" для выхода): ") if answer.find(psname) != -1: print(answer, "- правильный ответ!") print("\nЗавершение программы.") input("\n\nНажмите Enter для выхода.")
# Задача 5, Вариант 8 # Напишите программу, которая бы при запуске # случайным образом отображала название одного # из семи дней недели. # Карамян Н.Г. # 22.05.2016 input ("Жмак......\n") import random day = random.randint(1, 7) if (day) == 1: print ("Понедельник") elif (day) == 2: print ("Вторник") elif (day) == 3: print ("Среда") elif (day) == 4: print ("Четверг") elif (day) == 5: print ("Пятница") elif (day) == 6: print ("Суббота") elif (day) == 7: print ("Воскресенье") input ("\n\nЕщё раз!\n") day = random.randrange(7)+1 if (day) == 1: print ("Понедельник") elif (day) == 2: print ("Вторник") elif (day) == 3: print ("Среда") elif (day) == 4: print ("Четверг") elif (day) == 5: print ("Пятница") elif (day) == 6: print ("Суббота") elif (day) == 7: input ("Вот и всё.") input ("\n\nВот и всё.")
#Задача 12. Вариант 15. #1-50. Разработайте игру "Крестики-нолики". (см. М.Доусон Программируем на Python гл. 6). # Mitin D.S., 28.05.2016, 14:53 X="X" O="O" EMPTY=" " TIE="Ничья" NUM_SQUARES=9 def display_instruct(): print(''' Привет, студент! Давай поиграем в крестики-нолики! Вводи число от 0 до 8. Числа соответствуют полям доски - так, поле ниже: 0 | 1 | 2 --------- 3 | 4 | 5 --------- 6 | 7 | 8''') def ask_yes_no(question): response = None while response not in ("да", "нет"): response = input(question).lower() return response def ask_number(question, low, high): response = None while response not in range(low, high): response = int(input(question)) return response def pieces(): go_first = ask_yes_no("Хочешь ходить первым? (да/нет): ") if go_first == "да": print("\nХоди крестиками.") human = X computer = O else: print("\nЯ хожу, ты играешь ща нолики") computer = X human = O return computer, human def new_board(): board = [] for square in range(NUM_SQUARES): board.append(EMPTY) return board def display_board(board): print("\n\t", board[0], "|", board[1], "|", board[2]) print("\t", "---------") print("\t", board[3], "|", board[4], "|", board[5]) print("\t", "---------") print("\t", board[6], "|", board[7], "|", board[8]) def legal_moves(board): moves = [] for square in range(NUM_SQUARES): if board[square] == EMPTY: moves.append(square) return moves def winner(board): WAYS_TO_WIN = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)) for row in WAYS_TO_WIN: if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY: winner = board[row[0]] return winner if EMPTY not in board: return TIE return None def human_move(board, human): legal = legal_moves(board) move = None while move not in legal: move = ask_number("Твой ход. Выбери поле (0-8):", 0, NUM_SQUARES) if move not in legal: print("\nУже занято. Выбери другое поле\n") return move def computer_move(board, computer, human): board = board[:] BEST_MOVES = (4, 0, 2, 6, 8, 1, 3, 5, 7) print("Я выберу поле №", end = " ") for move in legal_moves(board): board[move] = computer if winner(board) == computer: print(move) return move board[move] = EMPTY for move in legal_moves(board): board[move] = human if winner(board) == human: print(move) return move board[move] = EMPTY for move in BEST_MOVES: if move in legal_moves(board): print(move) return move def next_turn(turn): if turn == X: return O else: return X def congrat_winner(the_winner, computer, human): if the_winner != TIE: print("Три", the_winner, "!\n") else: print("Ничья!\n") if the_winner == computer: print("Я победил!") elif the_winner == human: print("Ты выиграл! Молодец!") elif the_winner == TIE: print("Так и быть, победила дружба!") def main(): display_instruct() computer, human = pieces() turn = X board = new_board() display_board(board) while not winner(board): if turn == human: move = human_move(board, human) board[move] = human else: move = computer_move(board, computer, human) board[move] = computer display_board(board) turn=next_turn(turn) the_winner=winner(board) congrat_winner(the_winner, computer, human) main() input("\n\nНажмите ENTER для продолжения.")
# Задача 6. Вариант 11. #Создайте игру, в которой компьютер загадывает название # одного из девяти действующих вокзалов Москвы, а игрок должен его угадать. # Kurchatov N. V. # 11.04.2016 import random x=random.randint(1,9) if x==1: name="Белорусский" elif x==2: name = "Казанский" elif x==3: name = "Киевский" elif x==4: name = "Курский" elif x==5: name = "Ленинградский" elif x==6: name = "Павелецкий" elif x==7: name = "Рижский" elif x==8: name = "Савёловский" elif x==9: name = "Ярославский" print("Давайте поиграем в игру. Я загадываю один из девяти вокзалов Москвы, а вы должны угадать, какой именно.") ans=input() while(name!=ans ): print("\n Не этот вокзал. Попробуешь еще угадать?") print ("Введите название вокзала") ans=input() if name==ans: print("Верно! я загадал "+name+" вокзал.") input("Нажмите Enter для выхода")
# Задача 12. Вариант 49. #Разработайте игру "Крестики-нолики" #Valkovskey M.A. size = 3 board = [ 0 ] * size * size pics = [' . ', ' x ', ' o '] def print_board (board): print() for num in range(size): print(' ' + str(num +1) + ' ', end='') print() index = 1 letter = 97 for cell in board: print('|', end='') print(pics[cell], end='') if index == size: print('| ' + chr(letter)) letter += 1 index = 0 index += 1 print() def check_board (board): for row in range(size): if board[row] in [1, 2]: count = 0 for cell in range(size): if board[row+cell*size] == board[row]: count += 1 else: break if count == size: print_board(board) print('x' if board[row] == 1 else 'o', 'is winner!') return True for row in range(0, size * size, size): if board[row] in [1, 2]: count = 0 for cell in range(size): if board[row+cell] == board[row]: count += 1 else: break if count == size: print_board(board) print('x' if board[row] == 1 else 'o', 'is winner!') return True for row in [0, size-1]: if board[row] in [1, 2]: count = 0 for cell in range(size): if board[row+cell*(size + (1 if row==0 else -1))] == board[row]: count += 1 else: break if count == size: print_board(board) print('x' if board[row] == 1 else 'o', 'is winner!') return True print('\nWelcome! Make your turns like this - \'2a\' or \'3c\'') ixes = True while True: print_board(board) turn = input(('x' if ixes else 'o') + ' turn > ') try: index = ( int(turn[0]) -1 + (ord(turn[1]) -97) * size ) if board[index] in [1, 2]: raise board[index] = 1 if ixes else 2 except: print('invalid value', turn) else: if check_board(board): break ixes = not ixes input('Press Enter..')
# Задача 2. Вариант 45 # Напишите программу, которая будет выводить на экран наиболее понравившееся вам # высказывание, автором которого является Эзоп. Не забудьте о том, что автор # должен быть упомянут на отдельной строке. # Goman D.V. # 29.03.2016 print ('Невсегда будет лето.') print ('\n\t\tЭзоп') input ('\n\nВведите Enter для выхода.')
# Задание 4. Вариант 10. # Напишите программу, которая выводит имя, под которым скрывается Уильям Сидни # Портер. Дополнительно необходимо вывести область интересов указанной # личности, место рождения, годы рождения и смерти (если человек умер), # вычислить возраст на данный момент (или момент смерти). Для хранения всех # необходимых данных требуется использовать переменные. После вывода # информации программа должна дожидаться пока пользователь нажмет Enter # для выхода. # Колеганов Никита Сергеевич # 29.05.2016 name=input("Герой нашей программы - Уильям Сидни Портер.\nПод каким же именем мы знаем этого человека?") print("Ваш ответ:", name) print("Все верно: Уильям Сидни Портер -", name) print("Место рождения: Гринсборо, Северная Каролина.") print("Год рождения: 1862.") print("Год смерти: 1910.") print("Возраст на момент смерти:", 1910-1862) print("Область интересов: Писатель.") input("\n\nНажмите Enter для выхода.")
print ("Герой нашей сегодняшней программы - Аврора Дюпен") name = input ('Под каким именем мы знаем этого человка? Ваш ответ: ') print ("Всё верно: Аврора Дюпен - " + name + "!")
#Задача 7. Вариант 22 #Разработайте систему начисления очков для задачи 6, в соответствии с которой игрок получал бы большее количество баллов за меньшее количество попыток. #Rudich A.C. #31.03.2016 print('Угадайте имя одного из двух братьев, легендарных основателей Рима, которую загадал компьютер') import random a = random.choice(['Ромул', 'Рем']) b = input('Ваш ответ: ') b ='' balls = 10 while a !=b : print ('Вы не угадали') balls = balls - 1 b = input('Ваш ответ: ') print ('Вы угадали: ' + a + ' - ' + b) print ('Вы закончили игру с очками: ', balls) input('\nНажмите Enter для выхода')
# Задача 2. Вариант 20. # Напишите программу, которая будет выводить на экран наиболее понравившееся #вам высказывание, автором которого является Овидий. Не забудьте о том, что #автор должен быть упомянут на отдельной строке. # Titov I. V. # 02.06.2016 print("Происхождение человека есть , по видимому одно из самых случайных явлений.") print("\t\t\tИнокентий") input("\n\nНажмите Enter для выхода.")
#Задача №3 Вариант 34 #Напишите программу, которая выводит имя "Александр Михайлович Гликберг", и запрашивает его псевдоним. Программа должна сцеплять две эти строки и выводить полученную строку, разделяя имя и псевдоним с помощью тире. #Novikova J. V. #26.04.2016 print ("Герой нашей сегоднящней программы - Александр Михайлович Гликберг") psev=input("Под каким же именем мы знаем этого человека? Ваш ответ:") if (psev)==("Саша Черный"): print ("Всё верно: - Александр Михайлович Гликберг"+psev) else: print ("Вы ошиблись, это не его псевдоним.") input("нажмите Enter для выхода")
#Задача5.Вариант40. #Напишите программу, которая бы при запуске случайным образом отображала название одного из четырнадцати гражданских чинов, занесенных в Петровскую «Табель о рангах» . #Zinovieva Z.M. #31.03.2016 impot random n=random.randint(1,14) elif n==1: print("Канцлер") elif n==2: print("Вице-Канцлер") elif n==3: print("Тайный советник") elif n==4: print("Действительный статский советник") elif n==5: print("Статский советник") elif n==6: print("Коллежский советник") elif n==7: print("Надворный советник") elif n==8: print("Коллежский асессор") elif n==9: print("Титульный советник") elif n==10: print("Коллежский секретарь") elif n==11: print("Корабельный секретарь") elif n==12: print("Губернский секретарь") elif n==13: print("Кабинтеский регистратор") elif n==14: print("Коллежский регистратор") print(random)
# Задача 3. Вариант 15. # Напишите программу, которая выводит имя "Лариса Петровна Косач-Квитка", и запрашивает его псевдоним. # Программа должна сцеплять две эти строки и выводить полученную строку, разделяя имя и псевдоним с помощью тире. # Mitin D.S. # 05.03.2016, 23:14. print('Введите псевдоним Ларисы Петровны "Косач-Квитка": ') real_name="Лариса Петровна Коcач-Квитка" answer= input() print(real_name+" - это "+answer) input("Намжите Enter для выхода.")
# Задача 7. Вариант 50. #Разработайте систему начисления очков для задачи 6, в соответствии с которой #игрок получал бы большее количество баллов за меньшее количество попыток. # Alekseev I.S. # 15.05.2016 import random print("Программа случайным образом загадывает название одной из республик СССР, а игрок должен его угадать.\nЧем меньше попыток вы используете, тем больше баллов заработаете.") animal_numbers = random.randint(1,4) repub_numbers = random.randint(1,15) if repub_numbers == 1 : repub = 'РСФСР' elif repub_numbers == 2 : repub = 'Украина' elif repub_numbers == 3 : repub = 'Белоруссия' elif repub_numbers == 4 : repub = 'Узбекистан' elif repub_numbers == 5 : repub = 'Таджикистан' elif repub_numbers == 6 : repub = 'Казахстан' elif repub_numbers == 7 : repub = 'Грузия' elif repub_numbers == 8 : repub = 'Азербайджан' elif repub_numbers == 9 : repub = 'Литва' elif repub_numbers == 10 : repub = 'Молдавия' elif repub_numbers == 11 : repub = 'Латвия' elif repub_numbers == 12 : repub = 'Киргизия' elif repub_numbers == 13 : repub = 'Армения' elif repub_numbers == 14 : repub = 'Туркменистан' elif repub_numbers == 15 : repub = 'Эстония' trial = 3 bonus = 3000 while trial > 0 : answer = input('\nНазовите одно из животных, встреченных Колобком в лесу: ') if answer == repub : print('\nВы угадали!') print('Вам начислено', bonus, 'баллов.') break else : print('\nВы не угадали!!!') if trial > 1 : print('Попробуйте еще раз.') else : print('Правильный ответ: ', repub) trial -= 1 bonus -= 1000 input("\n\nНажмите Enter для выхода.")
# Задача 9. Вариант 31. # 1-50. Создайте игру, в которой компьютер выбирает какое-либо слово, а игрок должен его отгадать. Компьютер сообщает игроку, сколько букв в слове, и дает пять попыток узнать, есть ли какая-либо буква в слове, причем программа может отвечать только "Да" и "Нет". Вслед за тем игрок должен попробовать отгадать слово. # Shemyakin A.V. # 29.05.2016 import random slova = ("клавиатура", "доспех", "самолет", "корабль", "документ", "ракушка") word = random.choice(slova) tryes = 5 bukvi = len(word) bukva = "" slovo = "" print("Компьютер выбрал слово и вам нужно его отгадать. ") print("В этом слове", str(bukvi), "букв.") print("У вас есть ", str(tryes), " попыток угадать букву") while tryes > 0: bukva = input ("\nВведите букву: ") if bukva in list(word): print("Да.") tryes -= 1 else: print("Нет.") tryes -= 1 if tryes <= 0: slovo = input("У вас закончились попытки. Попробуйте угадать слово: ") if slovo == word: print("Поздравляю! Вы угадали слово. ") else: print("К сожалению вы не угадали. ") input("\nДля выхода нажмите Enter")
# Задача 5. Вариант 39. # Напишите программу, которая бы при запуске случайным образом отображала название одной из четырех основных мастей лошадей. # Korotkova D.S. # 26.03.2016 print("Одной из основны мастей лошадей является:") import random mast=("Вороная масть","Гнедая масть","Рыжая масть","Пегая масть") B=random.randint(0,4) print(mast[B]) input('\nНажмите enter, чтобы закрыть')
# Задание 4. Вариант 27. # Напишите программу, которая выводит имя, под которым скрывается Доменико # Теотокопули. Дополнительно необходимо вывести область интересов указанной # личности, место рождения, годы рождения и смерти (если человек умер), вычислить # возраст на данный момент (или момент смерти). Для хранения всех необходимых # данных требуется использовать переменные. После вывода информации программа # должна дожидаться пока пользователь нажмет Enter для выхода. # Чернов Михаил Сергеевич # 28.05.2016 name=input("Герой нашей программы - Доменико Теотокопули.\nПод каким же именем мы знаем этого человека?") print("Ваш ответ:", name) print("Все верно: Доменико Теотокопули -", name) print("Место рождения: Крит, Греция.") print("Год рождения: 1541.") print("Год смерти: 1614.") print("Возраст на момент смерти:", 1541-1614) print("Область интересов: Художник.") input("\n\nНажмите Enter для выхода.")
# Задача 6. Вариант 45 # Создайте игру, в которой компьютер загадывает название одного из семи чудес # света, а игрок должен его угадать. # Goman D.V. # 29.03.2016 import random n = random.randrange(7) chudo = ('Пирамида Хеопса', 'Висячие сады Семирамиды', 'Статуя Зевса в Олимпии', 'Храм Артемиды в Эфесе', 'Мавзолей в Галикарнасе', 'Колосс Родосский', 'Александрийский маяк') print (n) print ('Предлагаю Вам отгадать одно из чудес света.') user_chudo = input ('Введите Ваш вариант: ') while user_chudo.lower() !=chudo[n].lower(): user_chudo = input ('Вы не угадали, попробуйте еще раз: ') print ('Вы угадали! Это '+chudo[n]+'.')
#Задача 6. Вариант 46 #Создайте игру, в которой компьютер загадывает название одной из трех стран, входящих в #военно-политический блок "Антанта", а игрок должен его угадать. #Gryadin V. D. import random print("Попробуй угадать,какую страну входящую в Антанту я загадал") a = random.choice(['Россия','Англия','Франция']) b=input("Твой ответ:") i=0 while b!=a: print("Ты ошибся, попробуй снова") i+=1 b=input("Твой ответ:") else: print("Ты абсолютно прав!") print("Число твоих попыток: " + str(i)) input("\nВведите Enter для завершения")
#Задача 9. Вариант 1. #Создайте игру, в которой компьютер выбирает какое-либо слово, а игрок должен его отгадать. Компьютер сообщает игроку, сколько букв в слове, и дает пять попыток узнать, есть ли какая-либо буква в слове, причем программа может отвечать только "Да" и "Нет". Вслед за тем игрок должен попробовать отгадать слово. import random WORDS=("питон", "скорпион", "тритон", "крокодил", "ягуар", "леопард", "павлин", "антилопа") word=random.choice(WORDS) live=5 bukva="" slovo="" (number)=len(word) print("Компьютер загадал слово. Твоя цель угадать его. \nВ этом слове ",str(number)," букв.") print("У тебя "+str(live)+" попыток угадать буквы.") while live>0: bukva=input("Введите букву\n") if bukva in list (word): print("Да") live=live-1 else: print("Нет") live=live-1 if live==0: slovo=input("Ваши попытки кончились. \nВведите слово\n") if slovo==word: print("Поздравляю! Вы угадали слово :)") else: print("Вы не угадали слово :(") input("Нажмите Enter") #Abdrahmanova G. I. #11.04.2016
import sys import json import requests def convert(amount, base, to): url = f'https://api.ratesapi.io/api/latest?base={base}&symbols={to}' response = requests.get(url).json() return float(response['rates'][to])*float(amount) if __name__ == "__main__": if len(sys.argv) == 4: amount = sys.argv[1] base = sys.argv[2].upper() to_currency = sys.argv[3].upper() else: amount = int(input("[*]Enter amount > ")) base = input("[*]Enter Base Currency > ").upper() to_currency = input( "[*]Enter the currency you need to convert in > ").upper() result = convert(amount, base, to_currency) print(result)
# Add "Hello" and "Goodbye" buttons ################################################### # Student should add code where relevant to the following. import simplegui # Handlers for buttons def print_hello(): print("Hello") def print_goodbye(): print("Goodbye") # Create frame and assign callbacks to event handlers frame = simplegui.create_frame("Hello and Goodbye", 200, 200) frame.add_button("Hello", print_hello) frame.add_button("Goodbye", print_goodbye) # Start the frame animation frame.start() ################################################### # Test print_hello() print_hello() print_goodbye() print_hello() print_goodbye() ################################################### # Expected output from test #Hello #Hello #Goodbye #Hello #Goodbye
# Vector addition function ################################################### # Student should enter code below def add_vector(u, v): u1, u2 = u v1, v2 = v return [u1 + v1, u2 + v2] ################################################### # Test print(add_vector([3, 4], [5, -1])) print(add_vector([4, 3], [0, 0])) print(add_vector([1, 2], [3, 4])) print(add_vector([2, 3], [-6, -3])) ################################################### # Output #[4, 3] #[4, 6] #[-4, 0]
year = 1 numberOfSlowWumpuses = 1000 numberOfFastWumpuses = 1 print(year, numberOfSlowWumpuses, numberOfFastWumpuses) while numberOfSlowWumpuses >= numberOfFastWumpuses: numberOfSlowWumpuses *= 2 numberOfSlowWumpuses *= 0.6 numberOfFastWumpuses *= 2 numberOfFastWumpuses *= 0.7 year += 1 print(year, numberOfSlowWumpuses, numberOfFastWumpuses)
# Counter with buttons ################################################### # Student should add code where relevant to the following. import simplegui counter = 0 # Timer handler def tick(): global counter print counter counter += 1 # Event handlers for buttons def start_handler(): timer.start() def stop_handler(): timer.stop() def reset_handler(): global counter print counter counter = 0 # start, stop and reset the counter # Create frame and timer frame = simplegui.create_frame("Counter with buttons", 200, 200) timer = simplegui.create_timer(1000, tick) frame.add_button('Start', start_handler) frame.add_button('Stop', stop_handler) frame.add_button('Reset', reset_handler) # Start timer timer.start()
name = input("Enter file:") if len(name) < 1 : name = "mbox-short.txt" fh = open(name) email_histogram = {} for line in fh: # find line that starts with “From” if line.startswith("From "): words = line.split() # who sent the message # words = [0]From [1] [email protected] Sat Jan 5 09:14:16 2008 message_sender = words[1] if message_sender not in email_histogram: email_histogram[message_sender] = 1 else: email_histogram[message_sender] = email_histogram[message_sender] + 1 highest_count = 0 lowest_count = float("inf") mst_message = tuple lst_message = tuple least_messages = {} for email in email_histogram: if email_histogram[email] > highest_count: highest_count = email_histogram[email] mst_message = (email, highest_count) if email_histogram[email] < lowest_count: lowest_count = email_histogram[email] lst_message = (email, lowest_count) print(mst_message[0], mst_message[1])
""" Exercise 5: (Advanced) Change the socket program so that it only shows data after the headers and a blank line have been received. Remember that recv receives characters (newlines and all), not lines. """ import socket import re web_address = input('Enter - ') if len(web_address) < 1 : web_address = 'http://data.pr4e.org/romeo.txt' HOST = re.findall('^https?://(.+)/', web_address) mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) mysock.connect((HOST[0], 80)) GET_REQUEST= 'GET {} HTTP/1.0\r\n\r\n'.format(web_address) cmd = GET_REQUEST.encode() mysock.send(cmd) text = b"" while True: data = mysock.recv(512) if len(data) < 1: break text = text + data mysock.close() # Look for the end of the header (2 CRLF) pos = text.find(b"\r\n\r\n") #print(text[:pos].decode()) text = text[pos+4:].decode() print(text)
n = 100 numbers = range(2, n) results = [] while numbers != []: results.append(numbers[0]) numbers = [n for n in numbers if n % numbers[0] != 0] # print(len(results)) print(range(2, 16, 3)) print(range(15, 2, -3)) print(range(2, 18, 3)) ## 168
# Prime number lists ################################################### # Student should enter code below start = 1 end = 13 prime_list = [] for val in range(start, end + 1): # If num is divisible by any number # between 2 and val, it is not prime if val > 1: for n in range(2, val): if (val % n) == 0: break else: prime_list.append(val) print(prime_list[1], prime_list[3], prime_list[5]) ################################################### # Expected output #3 7 13
hours = float(input("Enter Hours: ")) rate_per_hour = float(input("Enter Rate: ")) pay = hours * rate_per_hour print("Pay: ", pay)
import operator fruit = {"oranges": 3, "apples": 5, "bananas": 7, "pears": 2} print("Fruit Before: {}".format(fruit)) # Sorts by Name print("Fruit After: {}".format(sorted(fruit.items(), key=operator.itemgetter(0)))) # Sort by values print("Fruit After: {}".format(sorted(fruit.items(), key=operator.itemgetter(1)))) print("Fruit After: {}" .format(sorted( fruit.items(), key = operator.itemgetter(1), reverse=True)) ) # You can further practice this by sorting the logs that you would fetch using regular expressions from the previous section.
c = float(input("Give a temperature in celsius: ")) f = (c * 9/5) + 32 print(f)
""" The program will prompt for a URL, read the JSON data from that URL using urllib and then parse and extract the comment counts from the JSON data, compute the sum of the numbers in the file. """ import json import urllib.request, urllib.parse, urllib.error import ssl # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE url = input('Enter URL: ') if len(url) < 1 : url = 'http://py4e-data.dr-chuck.net/comments_383952.json' total= 0 print('Retrieving', url) json_data = urllib.request.urlopen(url, context=ctx).read() print('Retrieved', len(json_data), 'characters') info = json.loads(json_data) comments = info['comments'] for comment in comments: count = int(comment['count']) total = total + count print('Count:', len(comments)) print("Sum: ", total)
p = True q = True print(not(p or not q)) p = True q = False print(not(p or not q)) p = False q = True print(not(p or not q)) p = False q = False print(not(p or not q))
t = input() while(t): t -= 1 colors = raw_input().split() case1 = colors[0:2] case2 = colors[2:4] case3 = colors[4:] tempcase1 = list(set(case1).intersection(case2)) tempcase2 = list(set(tempcase1).intersection(case3)) if(len(tempcase2)>0): print "YES" else: print "NO"
def print_arr(arr): for a in arr: print a, print "" return t = input() while(t): t -= 1 n,m = map(int,raw_input().split()) works = range(1,n+1) done = list(map(int,raw_input().split())) for work in done: try: works.remove(work) except: print "Unable to find ",work works.sort() chef = works[::2] assist = works[1::2] print_arr(chef) print_arr(assist)
def substrings(string): subs = [] for a in range(len(string)+1): for b in range(a): subs.append(string[b:a]) return subs def diffrk(string): return string.count('r')-string.count('k') t = raw_input() arr = substrings(t) for a in arr: print a,diffrk(a)
prime = [2] def isprime(num): if num<2: return False elif num == 2: return True for a in prime: if num % a == 0: return False prime.append(num) return True def primes(num): for i in range(max(prime)+1,num+1): flag = 1 for j in prime: if(i%j==0): flag = 0 break if(flag): prime.append(i) t =input() while(t): t -= 1 start = input() if(max(primes)<start): primes(start) while(not isprime(start+1)): start += 1 print start
def suminv(n): tmp = 0 for a in range(1,n+1): tmp += 1.0/(a+1) return tmp frac = input() while(frac): n = 1 while(suminv(n)<frac): n += 1 print str(n) + ' card(s)' frac = input()
def isPal(x): return x == x[::-1] t = input() while(t): t -= 1 string = raw_input() count = 0 for a in range(len(string)): for b in range(a+1,len(string)+1): if(isPal(string[a:b])): count += 1 print count
def has_negatives(a): nums = {} result = [] #Need to return a list of nums with negs #Loop through each number in the list for num in a: #need to check if the absolute value of our number is in our dict.. if nums.get(abs(num)): #If if is, we can add it to our result list result.append(abs(num)) else: #If not we can add the absoulte value to our dict nums[abs(num)] = num return result if __name__ == "__main__": print(has_negatives([-1,-2,1,2,3,4,-4]))
# Реализовать дескриптор валидации для атрибута email. Ваш дескриптор должен проверять формат email # который вы пытаетесь назначить. class EmailDescriptor: def __init__(self): pass # self.email def __get__(self, instance, owner): return self.email def __set__(self, instance, value): print(value.find('@')) if (('@' in value) and ('.' in value) and (0 < value.find('@') < (value.find('.') - 1))): print(value.find('@')) self.email = value else: raise Exception class MyClass: email = EmailDescriptor() my_class = MyClass() my_class.email = "[email protected]" print(my_class.email) my_class.email = "novalidemail" # Raised Exception
import sys import math import cmath #python program that hosts multiple calculators for simple applications def quad1(a, b, c): d = (b**2) - (4*a*c) x = (-b + math.sqrt(d))/(2*a) return x def quad2(a, b, c): d = (b**2) - (4*a*c) x = (-b - math.sqrt(d))/(2*a) return x number = 0 while number != "999": print("Enter 1 to calculate simple interest ") print("Enter 2 to calculate compound interest ") print("Enter 3 to use a simple calculator ") print("Enter 4 to use the pythagoreon theorum ") print("Enter 5 to find the distance between 2 points ") print("Enter 6 to use the quadratic formula ") print("Enter 999 to quit the program ") number = input() if number == "1": #simple interest principle = input("\nEnter the original amount: ") interestRate = input("\nEnter the interest rate as a decimal: ") time = input("\nEnter the length of time for interest to accrue: ") finalAmount = float(principle) * (1 + float(interestRate) * float(time)) print("Your original amount of {0} will have increased to {1} over {2} years\n".format(principle, finalAmount, time)) elif number == "2": #compound interest principle = input("\nEnter the original amount: ") interestRate = input("\nEnter the interest rate as a decimal: ") time = input("\nEnter the length of time for interest to accrue: ") compounded = input("\nEnter the number of times per year the interest is compounded: ") finalAmount = float(principle) * (1 + float(interestRate) / float(compounded))**(float(time)*float(compounded)) print("Your original amount of {0} will have increased to {1} over {2} years\n".format(principle, finalAmount, time)) elif number == "3": #simple calculator number1 = float(input("\nPlease enter the first number ")) print("Now choose an operation ") print("add = +") print("subtract = -") print("multiply = *") print("divide = /") print("Exponent = ^") choice = input() if choice in ('+', '-', '*', '/' , '^'): if choice == "+": number2 = float(input("Please enter the second number ")) answer = number1 + number2 print("The sum of {0} and {1} is {2}".format(number1, number2, answer)) if choice == "-": number2 = float(input("Please enter the second number ")) answer = number1 - number2 print("The difference of {0} and {1} is {2}".format(number1, number2, answer)) if choice == "*": number2 = float(input("Please enter the second number ")) answer = number1 * number2 print("The product of {0} and {1} is {2}".format(number1, number2, answer)) if choice == "/": number2 = float(input("Please enter the second number ")) answer = number1 / number2 print("The quotient of {0} and {1} is {2}".format(number1, number2, answer)) if choice == "^": number2 = float(input("Please enter the second number ")) answer = number1 ** number2 print("The product of {0} to the {1} is {2}".format(number1, number2, answer)) else: print("Operation is invalid") print() elif number == "4": #pythagoreon theorum a = float(input("\nEnter the length of the first side of the triangle ")) b = float(input("Enter the length of the second side of the triangle ")) c = math.sqrt((a**2) + (b**2)) print("The hypotenuse of the triangle is {0}\n".format(c)) elif number == "5": #distance formula x1 = float(input("\nEnter the length of the first x coordinate ")) y1 = float(input("Enter the length of the first y coordinate ")) x2 = float(input("Enter the length of the second x coordinate ")) y2 = float(input("Enter the length of the second x coordinate ")) d = math.sqrt(((x2 - x1)**2) + ((y2 - y1)**2)) print("The distace between ({0}, {1}) and ({2}, {3}) is {4}\n".format(x1, y1, x2, y2, d)) elif number == "6": #Quadratic Formula num1 = float(input("\nEnter the value of a ")) num2 = float(input("Enter the value of b ")) num3 = float(input("Enter the value of c ")) positive = quad1(num1, num2, num3) negative = quad2(num1, num2, num3) print("The solutions are x = {0} and x = {1}\n".format(positive, negative))
import pandas as pd import numpy as np import requests import os def sanitize_characters(raw, clean): for line in input_file: out = line output_file.write(line) sanitize_characters(input_file, output_file) def standardize_text(df, text_field): df[text_field] = df[text_field].str.replace(r"http\S+", "") df[text_field] = df[text_field].str.replace(r"http", "") df[text_field] = df[text_field].str.replace(r"@\S+", "") df[text_field] = df[text_field].str.replace(r"[^A-Za-z0-9(),!?@\'\`\"\_\n]", " ") df[text_field] = df[text_field].str.replace(r"@", "at") df[text_field] = df[text_field].str.lower() return df
import os def savePlainTextToFile(data, fileName): print "Creating file" f = open(fileName, 'w') f.write( str(data) ) f.close() print "File has been created" return def saveItemsOnFile(items, file): f = open(file,'w') for i in items: f.write(removeNonAscii(i) + '\n') f.close() return def deleteFile(fileName): print "Cleaning" os.remove(fileName) print "Done cleaning" def removeNonAscii(i): result = "" for j in i: if ord(j) < 128 : result = result + j return result
""" Rules for the game environment(s) and the basic player actions. All environments are grid-based cellular automata with discrete evolution. Agents can perform actions within/upon the environments outside of an evolutionary step. Therefore, an environment is primarily responsible for three things: 1. maintaining environment state (and saving and loading it); 2. advancing the environment one step; 3. executing agent actions and edits. """ import os from importlib import import_module from functools import wraps import numpy as np from .helper_utils import ( wrapping_array, wrapped_convolution as convolve2d, ) from .random import coinflip, get_rng, set_rng from .speedups import advance_board, alive_counts, execute_actions ORIENTATION = { "UP": 0, "RIGHT": 1, "DOWN": 2, "LEFT": 3, "FORWARD": 4, "BACKWARD": 6, } class CellTypes(object): """ Collection of flags for cellular automata. Attributes ---------- alive Every cell in the cellular automata system can either be 'alive' or 'dead'. At each evolutionary step live cells can be converted to dead cells and vice versa depending on the presence of neighboring live cells. movable Marks cells that can be pushed by the agent. destructible Marks cells that can be destroyed by the agent. frozen Frozen cells do not change during each evolutionary step. They won't become alive if they're dead, and they won't die if they're alive. preserving Preserving cells prevent all of their neighbors from dying. inhibiting Inhibiting cells prevent all neighbors from being born. spawning Spawning cells randomly create new living cells as their neighbors. color_(rgb) Every cell can have one of three color flags, for a total of 8 possible colors. New cells typically take on the color attributes of the cells that created them. agent Special flag to mark the cell as being occupied by an agent. Mostly used for rendering (both to humans and machines), as the actual location of the agent is stored separately. exit Special flag to mark a level's exit. The environment typically stops once an agent reaches the exit. """ alive_bit = 0 # Cell obeys Game of Life rules. agent_bit = 1 pushable_bit = 2 # Can be pushed by agent. pullable_bit = 15 # (out of order for historical reasons) destructible_bit = 3 frozen_bit = 4 # Does not evolve. preserving_bit = 5 # Neighboring cells do not die. inhibiting_bit = 6 # Neighboring cells cannot be born. spawning_bit = 7 # Randomly generates neighboring cells. exit_bit = 8 color_bit = 9 orientation_bit = 12 alive = np.uint16(1 << alive_bit) agent = np.uint16(1 << agent_bit) pushable = np.uint16(1 << pushable_bit) pullable = np.uint16(1 << pullable_bit) destructible = np.uint16(1 << destructible_bit) frozen = np.uint16(1 << frozen_bit) preserving = np.uint16(1 << preserving_bit) inhibiting = np.uint16(1 << inhibiting_bit) spawning = np.uint16(1 << spawning_bit) exit = np.uint16(1 << exit_bit) color_r = np.uint16(1 << color_bit) color_g = np.uint16(1 << color_bit + 1) color_b = np.uint16(1 << color_bit + 2) orientation_mask = np.uint16(3 << orientation_bit) empty = np.uint16(0) freezing = inhibiting | preserving movable = pushable | pullable # Note that the player is marked as "destructible" so that they never # contribute to producing indestructible cells. player = agent | freezing | frozen | destructible wall = frozen crate = frozen | movable spawner = frozen | spawning | destructible hard_spawner = frozen | spawning level_exit = frozen | exit life = alive | destructible colors = (color_r, color_g, color_b) rainbow_color = color_r | color_g | color_b ice_cube = frozen | freezing | movable plant = frozen | alive | movable tree = frozen | alive fountain = preserving | frozen parasite = inhibiting | alive | pushable | frozen weed = preserving | alive | pushable | frozen powers = alive | freezing | spawning class GameState(object): """ Attributes ---------- board : ndarray of ints with shape (h, w) Array of cells that make up the board. Note that the board is laid out according to the usual array convention where [0,0] corresponds to the top left. agent_locs : ndarray Coordinates of each agent on the board (row, col) orientation : int Which way the agent is pointing. In range [0,3] with 0 indicating up. spawn_prob : float in [0,1] Probability for spawning new live cells next to spawners. file_name : str Path to .npz file where the state is to be saved. points_on_level_exit : float game_over : bool Flag to indicate that the current game has ended. num_steps : int Number of steps taken since last reset. seed : np.random.SeedSequence Seed used for stochastic dynamics """ spawn_prob = 0.3 edit_loc = (0, 0) edit_color = 0 board = None file_name = None game_over = False points_on_level_exit = +1 num_steps = 0 _seed = None _rng = None def __init__(self, board_size=(10,10)): self.exit_locs = (np.array([], dtype=int), np.array([], dtype=int)) self.agent_locs = np.empty((0,2), dtype=int) if board_size is None: # assume we'll load a new board from file pass else: self.make_default_board(board_size) self._init_data = self.serialize() @property def seed(self): return self._seed @seed.setter def seed(self, seed): if not isinstance(seed, np.random.SeedSequence): seed = np.random.SeedSequence(seed) self._seed = seed self._rng = np.random.default_rng(seed) @property def rng(self): return self._rng if self._rng is not None else get_rng() @staticmethod def use_rng(f): @wraps(f) def wrapper(self, *args, **kwargs): with set_rng(self.rng): return f(self, *args, **kwargs) return wrapper def make_default_board(self, board_size): self.board = np.zeros(board_size, dtype=np.uint16) self.agent_locs = np.array(board_size).reshape(1,2) // 2 self.agent_names = np.array(['agent0']) self.board[self.agent_locs_idx] = CellTypes.player def serialize(self): """Return a dict of data to be serialized.""" cls = self.__class__ return { "spawn_prob": self.spawn_prob, "agent_locs": self.agent_locs.copy(), "agent_names": self.agent_names.copy(), "board": self.board.copy(), "class": "%s.%s" % (cls.__module__, cls.__name__), } def deserialize(self, data, as_initial_state=True): """Load game state from a dictionary or npz archive.""" keys = data.dtype.fields if hasattr(data, 'dtype') else data if as_initial_state: self._init_data = data self.board = data['board'].copy() if 'spawn_prob' in keys: self.spawn_prob = float(data['spawn_prob']) if 'agent_loc' in keys: # Old single agent setting self.agent_locs = np.array(data['agent_loc'])[None,::-1] elif 'agent_locs' in keys: self.agent_locs = np.array(data['agent_locs']) if 'agent_names' in keys: self.agent_names = np.array(data['agent_names']) else: self.agent_names = np.array([ 'agent%i' % i for i in range(len(self.agent_locs)) ]) if 'orientation' in keys: self.orientation = int(data['orientation']) self.update_exit_locs() self.game_over = False self.num_steps = 0 def save(self, file_name=None): """Saves the game state to disk.""" file_name = os.path.expanduser(file_name) file_name = os.path.abspath(file_name) if file_name is None: file_name = self.file_name if file_name is None: raise ValueError("Must specify a file name") if not file_name.endswith('.npz'): file_name += '.npz' self.file_name = file_name self._init_data = self.serialize() self.num_steps = 0 np.savez_compressed(file_name, **self._init_data) def revert(self): """Revert to the last saved state.""" if hasattr(self, '_init_data'): self.deserialize(self._init_data) return True return False @classmethod def loaddata(cls, data, auto_cls=True): """Load game state from a dictionary or npz archive (class agnostic)""" keys = data.dtype.fields if hasattr(data, 'dtype') else data if auto_cls and 'class' in keys: cls_components = str(data['class']).split('.') mod_name = '.'.join(cls_components[:-1]) cls_name = cls_components[-1] try: mod = import_module(mod_name) except ImportError: mod = import_module(__name__) cls = getattr(mod, cls_name) obj = cls(board_size=None) obj.deserialize(data) return obj @classmethod def load(cls, file_name, auto_cls=True): """Load game state from disk.""" file_name = os.path.expanduser(file_name) file_name = os.path.abspath(file_name) obj = cls.loaddata(np.load(file_name), auto_cls) obj.file_name = file_name return obj @property def width(self): """Width of the game board.""" return self.board.shape[1] @property def height(self): """Height of the game board.""" return self.board.shape[0] @property def title(self): """The bare file name without path or extension.""" if self.file_name is None: return None else: fname = os.path.split(self.file_name)[-1] fname, *ext = fname.rsplit('.', 1) procgen = ext and ext[0] in ('json', 'yaml') if procgen and self._seed and self._seed.spawn_key: # Append the spawn key as the episode number fname += '-e' + str(self._seed.spawn_key[-1]) return fname @property def edit_color_name(self): return [ 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', ][(self.edit_color & CellTypes.rainbow_color) >> CellTypes.color_bit] @property def orientation(self): """Orientation of the agents. For backwards compatibility.""" agents = self.board[self.agent_locs_idx] out = (agents & CellTypes.orientation_mask) >> CellTypes.orientation_bit return out.astype(np.int64) @orientation.setter def orientation(self, value): value = (np.array(value, dtype=np.uint16) & 3) << CellTypes.orientation_bit self.board[self.agent_locs_idx] &= ~CellTypes.orientation_mask self.board[self.agent_locs_idx] |= value @property def agent_locs_idx(self): """ Convenience for easier array indexing. E.g., ``agents = self.board[self.agent_locs_idx]`` """ return tuple(self.agent_locs.T) def execute_action(self, action): """ Perform a named agent action. This is primarily for interactive use. Learning algorithms and environments should call `execute_actions()` instead. """ if self.game_over or len(self.agent_locs) == 0: pass elif action.startswith("MOVE "): direction = ORIENTATION[action[5:]] flip = 2 if direction == 6 else 0 if direction < 4: self.execute_actions(direction + 1) else: # Relative direction. Either forward (4) or backward (6) direction = self.orientation ^ flip self.execute_actions(direction + 1) self.orientation ^= flip self.game_over = self.has_exited().any() elif action.startswith("TURN "): direction = ORIENTATION[action[5:]] self.orientation += 2 - direction self.orientation %= 4 elif action.startswith("FACE "): self.orientation = ORIENTATION[action[5:]] elif action.startswith("TOGGLE"): if len(action) > 6: # Toggle in a particular direction direction = ORIENTATION[action[7:]] else: direction = self.orientation self.execute_actions(direction + 5) elif action in ("RESTART", "ABORT LEVEL", "PREV LEVEL", "NEXT LEVEL"): self.game_over = action return 0 def execute_actions(self, actions): """ Perform (potentially different) actions for each agent. Parameters ---------- actions : int or ndarray Actions for each agent. Should be in range [0-8]. """ execute_actions(self.board, self.agent_locs, actions) def execute_edit(self, command, board=None): """ Edit the board. Returns an error or success message, or None. Parameters ---------- command : str """ named_objects = { 'EMPTY': CellTypes.empty, 'LIFE': CellTypes.life, 'HARD LIFE': CellTypes.alive, 'WALL': CellTypes.wall, 'CRATE': CellTypes.crate, 'SPAWNER': CellTypes.spawner, 'HARD SPAWNER': CellTypes.hard_spawner, 'EXIT': CellTypes.level_exit, 'ICECUBE': CellTypes.ice_cube, 'PLANT': CellTypes.plant, 'TREE': CellTypes.tree, 'FOUNTAIN': CellTypes.fountain, 'PARASITE': CellTypes.parasite, 'WEED': CellTypes.weed, 'AGENT': CellTypes.player, } toggles = { "AGENT": CellTypes.agent, "ALIVE": CellTypes.alive, "PUSHABLE": CellTypes.pushable, "PULLABLE": CellTypes.pullable, "DESTRUCTIBLE": CellTypes.destructible, "FROZEN": CellTypes.frozen, "PRESERVING": CellTypes.preserving, "INHIBITING": CellTypes.inhibiting, "SPAWNING": CellTypes.spawning, "EXIT": CellTypes.exit, } if board is None: board = self.board edit_loc = self.edit_loc if command.startswith("MOVE "): direction = ORIENTATION[command[5:]] if direction % 2 == 0: dx = np.array([direction - 1, 0]) else: dx = np.array([0, 2 - direction]) self.edit_loc = tuple((edit_loc + dx) % board.shape) elif command.startswith("PUT ") and command[4:] in named_objects: board[edit_loc] = named_objects[command[4:]] if board[edit_loc]: board[edit_loc] |= self.edit_color elif command == "NEXT EDIT COLOR": self.edit_color += CellTypes.color_r self.edit_color &= CellTypes.rainbow_color return "EDIT COLOR: " + self.edit_color_name elif command == "PREVIOUS EDIT COLOR": self.edit_color -= CellTypes.color_r self.edit_color &= CellTypes.rainbow_color return "EDIT COLOR: " + self.edit_color_name elif command == "APPLY EDIT COLOR": board[edit_loc] &= ~CellTypes.rainbow_color board[edit_loc] |= self.edit_color elif command.startswith("TOGGLE ") and command[7:] in toggles: board[edit_loc] ^= toggles[command[7:]] elif command == "REVERT": if not self.revert(): return "No saved state; cannot revert." elif command in ("ABORT LEVEL", "PREV LEVEL", "NEXT LEVEL"): self.game_over = command self.update_exit_locs() self.update_exit_colors() self.update_agent_locs() def shift_board(self, dx, dy): """Utility function. Translate the entire board (edges wrap).""" self.board = np.roll(self.board, dy, axis=0) self.board = np.roll(self.board, dx, axis=1) self.agent_locs += [dy, dx] self.agent_locs %= self.board.shape self.update_exit_locs() def resize_board(self, dx, dy): """Utility function. Expand or shrink the board.""" height, width = self.board.shape if width <= 0 or height <= 0: raise ValueError("Cannot resize to zero.") new_board = np.zeros((height+dy, width+dx), dtype=self.board.dtype) height += min(0, dy) width += min(0, dx) new_board[:height, :width] = self.board[:height, :width] self.board = new_board out_of_bounds = np.any(self.agent_locs >= new_board.shape, axis=1) self.agent_locs = self.agent_locs[~out_of_bounds] self.edit_loc = tuple(np.array(self.edit_loc) % new_board.shape) self.update_exit_locs() def clip_board(self, left=0, right=0, top=0, bottom=0): """Utility function. Clip edges off of the board.""" height, width = self.board.shape if left + right >= width or top + bottom >= height: raise ValueError("Board clipped to zero") self.shift_board(-left, -top) self.resize_board(-(left+right), -(bottom+top)) def advance_board(self): """ Apply one timestep of physics. """ raise NotImplementedError @property def is_stochastic(self): raise NotImplementedError def has_exited(self): """ Boolean value for each agent. """ agents = self.board[self.agent_locs_idx] return agents & (CellTypes.agent | CellTypes.exit) == CellTypes.exit def agent_is_active(self): """ Boolean value for each agent """ agents = self.board[self.agent_locs_idx] return agents & CellTypes.agent > 0 def current_points(self): """ Current point value of the board. This depends on the current board state only. It does not depend on the initial board state or the board history. """ return self.points_on_level_exit * self.has_exited() def can_exit(self): # As long as the agent is on the board, it can exit # (this is overridden below) return self.board[self.agent_locs_idx] & CellTypes.agent > 0 def update_exit_locs(self): exits = self.board & (CellTypes.exit | CellTypes.agent) == CellTypes.exit self.exit_locs = np.nonzero(exits) def update_exit_colors(self): can_exit = self.can_exit() # Set the exit bit on top of each agent that is allowed to exit self.board[self.agent_locs_idx] &= ~CellTypes.exit self.board[self.agent_locs_idx] |= CellTypes.exit * can_exit # If any agent can exit, set the exit color to red. # This is mostly a visual aid for humans, but could conceivably be # used by non-human agents too (e.g., recognize when another agent is # able to open the exit). if can_exit.any(): exit_type = CellTypes.level_exit | CellTypes.color_r else: exit_type = CellTypes.level_exit self.board[self.exit_locs] = exit_type def update_agent_locs(self): new_locs = np.stack( np.nonzero(self.board & CellTypes.agent), axis=1) # Do some gymnastics to respect the old order old_locs = self.agent_locs compare = np.all(new_locs[None] == old_locs[:,None], axis=-1) self.agent_locs = np.append( old_locs[np.any(compare, axis=1)], new_locs[~np.any(compare, axis=0)], axis=0) # but for now, don't do the same gymnastics with agent names # (this should be fixed later) if len(old_locs) != len(new_locs): self.agent_names = np.array([ 'agent%i' % i for i in range(len(self.agent_locs)) ]) class GameWithGoals(GameState): """ Mixin for adding goal states to the game. Attributes ---------- goals : ndarray Point value associated with each cell. Can be negative. points_table: ndarray Lookup table that maps goals (rows) and cell colors (columns) to point values for individual cells. Colors are KRGYBMCW. min_performance : float Don't allow the agent to exit the level until the level is at least this fraction completed. If negative, the agent can always exit. """ goals = None _static_goals = None # can be set to True for minor performance boost min_performance = -1 # TODO: make a different point table for each color agent default_points_table = np.array([ # k r g y b m c w empty [+0, -1, +0, +0, +0, +0, +0, +0, 0], # black / no goal [-3, +3, -3, +0, -3, +0, -3, -3, 0], # red goal [+0, -3, +5, +0, +0, +0, +3, +0, 0], # green goal [-3, +0, +0, +3, +0, +0, +0, +0, 0], # yellow goal [+3, -3, +3, +0, +5, +3, +3, +3, 0], # blue goal [-3, +3, -3, +0, -3, +5, -3, -3, 0], # magenta goal [+3, -3, +3, +0, +3, +0, +5, +3, 0], # cyan goal [+0, -1, +0, +0, +0, +0, +0, +0, 0], # white / rainbow goal ]) default_points_table.setflags(write=False) def make_default_board(self, board_size): super().make_default_board(board_size) self.goals = np.zeros_like(self.board) self._needs_new_counts = True self.setup_initial_counts() self.reset_points_table() def serialize(self): data = super().serialize() data['goals'] = self.goals.copy() data['points_table'] = self.points_table.copy() data['min_performance'] = self.min_performance return data def deserialize(self, data, as_initial_state=True): super().deserialize(data, as_initial_state) keys = data.dtype.fields if hasattr(data, 'dtype') else data self.goals = data['goals'] if 'min_performance' in keys: self.min_performance = data['min_performance'] if 'points_table' in keys: self.points_table = data['points_table'] else: self.reset_points_table() self._needs_new_counts = True if as_initial_state: self.setup_initial_counts() self._static_goals = None self.update_exit_colors() def execute_edit(self, command): if command.startswith("GOALS "): rval = super().execute_edit(command[6:], self.goals) self._static_goals = None else: rval = super().execute_edit(command) self._needs_new_counts = True if len(self.points_table) != len(self.agent_locs): # Ideally we would handle this in a smarter way, but for now # if we add or subtract an agent, we just reset the scoring to # the default values. self.reset_points_table() return rval def execute_action(self, action): self._needs_new_counts = True return super().execute_action(action) @property def alive_counts(self): if getattr(self, '_needs_new_counts', True): self._needs_new_counts = False self._alive_counts = alive_counts(self.board, self.goals) self._alive_counts.setflags(write=False) return self._alive_counts def setup_initial_counts(self): """ Record the counts of live cells and possible colors for new cells. """ self.initial_counts = self.alive_counts self.initial_colors = np.zeros(9, dtype=bool) generators = CellTypes.agent | CellTypes.alive | CellTypes.spawning colors = self.board[self.board & generators > 0] & CellTypes.rainbow_color colors = np.unique(colors) >> CellTypes.color_bit self.initial_colors[colors] = True self.initial_colors[-1] = True # 'empty' color def reset_points_table(self): """ Reset the points table to default values. """ num_agents = len(self.agent_locs) self.points_table = np.tile(self.default_points_table, [num_agents, 1, 1]) def current_points(self): points = self.points_table * self.alive_counts points = points.reshape(-1,72) # unravel the points for easier sum return np.sum(points, axis=1) + super().current_points() def points_earned(self): """Number of points that have been earned.""" delta_counts = self.alive_counts - self.initial_counts points = self.points_table * delta_counts points = points.reshape(-1,72) # unravel the points for easier sum return np.sum(points, axis=1) + super().current_points() def initial_available_points(self): """ Total points available to the agents, assuming all goals can be filled. """ goal_counts = np.sum(self.initial_counts, axis=1) # int array, length 8 # Zero out columns in the point table corresponding to unavailable colors points_table = self.points_table * self.initial_colors # shape (n,8,9) max_points = np.max(points_table, axis=2) # shape (n,8) total_available = np.sum(max_points * goal_counts, axis=1) # shape (n,) initial_points = self.points_table * self.initial_counts initial_points = np.sum(initial_points.reshape(-1,72), axis=1) return total_available - initial_points def required_points(self): """Total number of points needed to open the level exit.""" req_points = self.min_performance * self.initial_available_points() return np.maximum(0, np.int64(np.ceil(req_points))) def can_exit(self): points_earned = np.maximum(0, self.points_earned()) is_agent = self.board[self.agent_locs_idx] & CellTypes.agent > 0 return is_agent & (points_earned >= self.required_points()) def shift_board(self, dx, dy): """Utility function. Translate the entire board (edges wrap).""" super().shift_board(dx, dy) self.goals = np.roll(self.goals, dy, axis=0) self.goals = np.roll(self.goals, dx, axis=1) def resize_board(self, dx, dy): """Utility function. Expand or shrink the board.""" super().resize_board(dx, dy) height, width = self.goals.shape new_goals = np.zeros((height+dy, width+dx), dtype=self.goals.dtype) height += min(0, dy) width += min(0, dx) new_goals[:height, :width] = self.goals[:height, :width] self.goals = new_goals class SafeLifeGame(GameWithGoals): """ Specifies all rules for the SafeLife game environment. Along with parent classes, this defines all of SafeLife's basic physics and the actions that the player can take. """ @GameState.use_rng def advance_board(self): self.num_steps += 1 self._needs_new_counts = True self.board = advance_board(self.board, self.spawn_prob) if not self._static_goals: new_goals = advance_board(self.goals, self.spawn_prob) if self._static_goals is None: # Check to see if they are, in fact, static self._static_goals = ( not (new_goals & CellTypes.spawning).any() and (new_goals == self.goals).all() ) self.goals = new_goals @property def is_stochastic(self): return (self.board & CellTypes.spawning).any() class GameOfLife(GameWithGoals): """ A more general version of SafeLifeGame which can use different cellular automata rules. Experimental! Conway's Game of Life uses cellular automata rules B3/S23. These can be changed though. Attributes ---------- survive_rule : tuple of ints Number of neighbors that are required for a cell to survive to the next generation. born_rule : tuple of ints Number of neighbors that are required for a dead cell to come to life. """ survive_rule = (2, 3) born_rule = (3,) @GameState.use_rng def advance_board(self): """ Apply one timestep of physics using Game of Life rules. """ # We can advance the board using a pretty simple convolution, # so we don't have to execute a lot of loops in python. # Of course, this probably won't be sufficient for extremely # large boards. self.num_steps += 1 board = self.board cfilter = np.array([[1,1,1],[1,0,1],[1,1,1]], dtype=np.uint16) alive = board & CellTypes.alive > 0 spawning = board & CellTypes.spawning > 0 frozen = board & CellTypes.frozen > 0 can_die = ~frozen & ( convolve2d(board & CellTypes.preserving, cfilter) == 0) can_grow = ~frozen & ( convolve2d(board & CellTypes.inhibiting, cfilter) == 0) num_neighbors = convolve2d(alive, cfilter) num_spawn = convolve2d(spawning, cfilter) spawn_prob = 1 - (1 - self.spawn_prob)**num_spawn has_spawned = coinflip(spawn_prob, board.shape) born_rule = np.zeros(9, dtype=bool) born_rule[list(self.born_rule)] = True dead_rule = np.ones(9, dtype=bool) dead_rule[list(self.survive_rule)] = False new_alive = (born_rule[num_neighbors] | has_spawned) & ~alive & can_grow new_dead = dead_rule[num_neighbors] & alive & can_die new_flags = np.zeros_like(board) color_weights = 1 * alive + 2 * spawning for color in CellTypes.colors: # For each of the colors, see if there are two or more neighbors # that have it. If so, any new cells (whether born or spawned) # will also get that color. has_color = board & color > 0 new_color = convolve2d(has_color * color_weights, cfilter) >= 2 new_flags += color * new_color indestructible = alive & (board & CellTypes.destructible == 0) new_flags += CellTypes.destructible * (convolve2d(indestructible, cfilter) < 2) board *= ~(new_alive | new_dead) board += new_alive * (CellTypes.alive + new_flags) @property def is_stochastic(self): return (self.board & CellTypes.spawning).any() class AsyncGame(GameWithGoals): """ Game with asynchronous updates. Experimental! Asynchronous game physics work by updating the board one cell at a time, with many individual cell updates occurring for each board update. The order is random, so the system is naturally stochastic. In addition, a temperature parameter can be tuned to make the individual cell updates stochastic. Attributes ---------- energy_rules : array of shape (2, num_neighbors + 1) The energy difference between a cell living and dying given its current state (live and dead, respectively) and the number of living neighbors that it has. The number of neighbors should either be 4, 6, or 8 for Von Neumann, hexagonal, and Moore neighborhoods respectively. temperature : float Higher temperatures lead to noisier systems, and are equivalent to lowering the values in the energy rules. Zero temperature yields a perfectly deterministic update per cell (although the cell update ordering is still random). cells_per_update : float Number of cell updates to perform at each board update, expressed as a fraction of the total board size. Can be more than 1. """ energy_rule_sets = { 'conway': ( (-1, -1, +1, +1, -1, -1, -1, -1, -1), (-1, -1, -1, +1, -1, -1, -1, -1, -1), ), 'ising': ( (-2, -1, 0, +1, +2), (-2, -1, 0, +1, +2), ), 'vine': ( (-1, -1, +1, +1, +1), (-1, +1, -1, -1, -1), ), } energy_rules = energy_rule_sets['conway'] temperature = 0 cells_per_update = 0.3 def serialize(self): data = super().serialize() data['energy_rules'] = self.energy_rules return data def deserialize(self, data, *args, **kw): super().deserialize(data, *args, **kw) self.energy_rules = data['energy_rules'] @GameState.use_rng def advance_board(self): """ Apply one timestep of physics using an asynchronous update. Note that this is going to be quite slow. It should probably be replaced by an implementation in C, especially if used for training AI agents. """ board = self.board rules = self.energy_rules h, w = board.shape beta = 1.0 / max(1e-20, self.temperature) if len(rules[0]) - 1 == 4: neighborhood = np.array([[0,1,0],[1,0,1],[0,1,0]]) elif len(rules[0]) - 1 == 6: neighborhood = np.array([[0,1,1],[1,0,1],[1,1,0]]) elif len(rules[0]) - 1 == 8: neighborhood = np.array([[1,1,1],[1,0,1],[1,1,1]]) else: raise RuntimeError("async rules must have length 5, 7, or 9") rng = get_rng() for _ in range(int(board.size * self.cells_per_update)): x = rng.choice(w) y = rng.choice(h) if board[y, x] & CellTypes.frozen: continue neighbors = board.view(wrapping_array)[y-1:y+2, x-1:x+2] * neighborhood alive_neighbors = np.sum(neighbors & CellTypes.alive > 0) spawn_neighbors = np.sum(neighbors & CellTypes.spawning > 0) frozen = np.sum(neighbors & CellTypes.freezing) > 0 if frozen: continue if board[y, x] & CellTypes.alive: H = rules[0][alive_neighbors] else: H = rules[1][alive_neighbors] P = 0.5 + 0.5*np.tanh(H * beta) P = 1 - (1-P)*(1-self.spawn_prob)**spawn_neighbors board[y, x] = CellTypes.life if coinflip(P) else CellTypes.empty
mid_score = float(input('Enter Midterm Score (30) : ')) if(mid_score >30 or mid_score<0): print('Error Midterm score | enter again') mid_score = 0.0 final_score = float(input('Enter Final Score (30) : ')) if(final_score >30 or final_score<0): print('Error Final Score | enter again') final_score = 0.0 work_score = float(input('Enter Work Score (30) : ')) if(work_score >30 or work_score<0): print('Error Work Score | enter again') work_score = 0.0 affective_score = float(input('Enter Affective Score (10) : ')) if(affective_score >10 or affective_score<0): print('Error Affective Score | enter again') affective_score = 0.0 total_score = float(mid_score + final_score + work_score + affective_score) print('--------------------------------------') print('Score Report') print('Midterm Score (30) : ' , mid_score) print('Final Score (30) : ' , final_score) print('Work Score (30) : ' , work_score) print('Affective Score (10) : ' , affective_score) print('Total (100) : ' , total_score) print('--------------------------------------') if(total_score > 100 or total_score < 0): print('Grade cannot calculate') elif(total_score >= 80): print('Grade Result = 4') elif(total_score >= 75): print('Grade Result = 3.5') elif(total_score >= 70): print('Grade Result = 3') elif(total_score >= 65): print('Grade Result = 2.5') elif(total_score >= 60): print('Grade Result = 2') elif(total_score >= 55): print('Grade Result = 1.5') elif(total_score >= 50): print('Grade Result = 1') else: print('Grade Result = 0')
#!/home/bespontoff/PycharmProjects/checkio/venv/bin/checkio --domain=py run find-rectangles # This mission is an adaptation of the "Rectangles" game (fromSimon Tatham's Portable Puzzle Collection). If you are lost or just want to play, the game is availablehere. # # You have to divide a rectangular grid into rectangles, so that each rectangle contains exactly one cell with a non-empty number and the rectangle area is equal to this number. # # The grid will be represented by a list of list of integers. # A rectangle will be represented by a tuple or list of four integers:the first two are the coordinates of the top left corner ;the last two are the coordinates of the bottom right corner. # # Input:A list of list of integers. # # Output:An iterable/list/set of tuple/list of four integers. # # Preconditions:All puzzles have one and only one solution.6 ≤ len(grid) ≤ 50 and 6 ≤ len(grid[0]) ≤ 50.all(len(row) == len(grid[0]) for row in grid). # # # END_DESC from typing import List, Tuple, Iterable def rectangles(grid: List[List[int]]) -> Iterable[Tuple[int, int, int, int]]: return [] if __name__ == '__main__': GRIDS = ( [[3, 0, 0, 0, 0, 2], [2, 0, 0, 4, 0, 0], [0, 5, 0, 0, 0, 0], [3, 0, 3, 2, 0, 0], [0, 0, 2, 0, 0, 6], [0, 0, 0, 4, 0, 0]], [[6, 0, 0, 0, 0, 0, 0, 2, 0], [0, 2, 0, 2, 0, 0, 4, 0, 0], [0, 0, 0, 0, 0, 0, 5, 0, 0], [0, 12, 2, 0, 5, 0, 0, 0, 0], [0, 0, 2, 0, 3, 0, 2, 0, 0], [0, 0, 0, 0, 0, 0, 0, 2, 0], [0, 0, 0, 0, 0, 0, 0, 0, 7], [0, 0, 3, 0, 0, 12, 0, 0, 0], [0, 2, 0, 0, 0, 4, 0, 0, 4]], [[2, 6, 0, 0, 0, 0, 0, 3], [0, 2, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 8, 0, 0], [4, 0, 0, 2, 0, 0, 0, 0], [0, 0, 6, 0, 0, 0, 2, 2], [0, 2, 0, 0, 0, 0, 0, 6], [2, 0, 0, 0, 0, 0, 0, 0], [0, 2, 0, 0, 0, 0, 0, 0], [0, 0, 8, 0, 0, 0, 0, 0], [3, 0, 0, 3, 14, 0, 0, 4], [0, 0, 0, 0, 4, 0, 3, 0]], ) def checker(grid, result): from itertools import product try: result = list(result) except TypeError: raise AssertionError('Your result must be iterable.') nb_rects = sum(cell != 0 for row in grid for cell in row) if len(result) != nb_rects: print(f'There are {nb_rects} rectangles to detect, ' f'but you gave {len(result)} rectangle(s).') nb_rows, nb_cols = len(grid), len(grid[0]) colored_grid = [[0 for _ in range(nb_cols)] for _ in range(nb_rows)] prev_rects = set() for color, rect in enumerate(result, 1): assert (isinstance(rect, (tuple, list)) and len(rect) == 4 and all(isinstance(coord, int) for coord in rect)), \ (f'{rect} does not represent a rectangle, ' 'it should be a tuple/list of four integers.') assert tuple(rect) not in prev_rects, \ f'You gave the same rectangle {rect} twice.' prev_rects.add(tuple(rect)) x1, y1, x2, y2 = rect assert x1 <= x2 and y1 <= y2, \ (f'The rectangle {rect} must be ' '(top left coords, bottom right coords).') for x, y in ((x1, y1), (x2, y2)): assert 0 <= x < nb_rows and 0 <= y < nb_cols, \ (f'The rectangle {rect} contains {x, y} ' 'which is not in the grid.') area = (x2 + 1 - x1) * (y2 + 1 - y1) grid_area = None for x, y in product(range(x1, x2 + 1), range(y1, y2 + 1)): assert not colored_grid[x][y], \ (f'Rectangle #{color} intersects ' f'rectangle #{colored_grid[x][y]} at {x, y}.') colored_grid[x][y] = color if grid[x][y]: assert grid_area is None, \ (f'The rectangle {rect} contains two area values: ' f'{grid_area} and {grid[x][y]}.') grid_area = grid[x][y] assert grid[x][y] == area, \ (f'The rectangle {rect} have area={area} ' f'and contains another area value: {grid[x][y]}.') assert grid_area is not None, f'{rect} contains no area value.' nb_uncovered = sum(not cell for row in colored_grid for cell in row) assert not nb_uncovered, f'{nb_uncovered} cells are still not covered.' for test_nb, grid in enumerate(GRIDS, 1): result = rectangles([row[:] for row in grid]) try: checker(grid, result) except AssertionError as error: print(f'You failed the test #{test_nb}:') print(error.args[0]) break else: print('Well done! Click on "Check" for bigger tests.')
#!/home/bespontoff/PycharmProjects/checkio/venv/bin/checkio --domain=py run shortest-knight-path # Sofi found a chess set in the supply closet on the robots ship. She has decided to learn how to play the game of chess starts by attempting to understand how the knight moves.Chess is played on a square board of eight rows (called ranks and denoted with numbers 1 to 8) and eight columns (called files and denoted with letters a to h) of squares.Sofi found a chess set in the supply closet on the robots’ ship. She has decided to learn how to play the game of chess by attempting to understand how the knight moves first.Chess is played on a square board of eight rows (called ranks and denoted with numbers 1 to 8) and eight columns (called files and denoted with letters a to h) of squares. # # The knight moves to any of the closest squares that are not on the same rank, file, or diagonal, thus, the move forms an "L"-shape: two squares vertically and one square horizontally, or two squares horizontally and one square vertically. # # You are given the start and end squares as chess coordinates separated by a hyphen. You should find the length of the shortest path for the knight from one point to another on the chessboard. # # # # You can learn more about chess here onWikipedia.Input:Squares coordinates as a string. # # Output:The number of moves in the shortest path the knight can take as an integer. # # Example: # # checkio("b1-d5") == 2, "First" # checkio("a6-b8") == 1, "Second" # checkio("h1-g2") == 4, "Third" # checkio("h8-d7") == 3, "Fourth" # checkio("a1-h8") == 6, "Fifth" # Precondition:An input string satisfies regexp "[a-h][1-8]-[a-h][1-8]". # start_cell != end_cell # # # # The knight moves to any of the closest squares that are not on the same rank, file, or diagonal, thus the move forms an "L"-shape: two squares vertically and one square horizontally, or two squares horizontally and one square vertically. # # You are given the start and end squares as chess coordinates separated by a hyphen. You should find the length of the shortest path for the knight from one point to another on the chessboard. # # # # You can learn more about chess here onWikipedia.Input:Squares coordinates as a string. # # Output:The number of moves in the shortest path the knight can take as an integer. # # Example: # # checkio("b1-d5") == 2, "First" # checkio("a6-b8") == 1, "Second" # checkio("h1-g2") == 4, "Third" # checkio("h8-d7") == 3, "Fourth" # checkio("a1-h8") == 6, "Fifth" # Precondition:An input string satisfies regexp "[a-h][1-8]-[a-h][1-8]". # start_cell != end_cell # # # # # # # # # # # # # # # END_DESC def checkio(cells): """str -> int Number of moves in the shortest path of knight """ return 0 if __name__ == "__main__": #These "asserts" using only for self-checking and not necessary for auto-testing assert checkio("b1-d5") == 2, "1st example" assert checkio("a6-b8") == 1, "2nd example" assert checkio("h1-g2") == 4, "3rd example" assert checkio("h8-d7") == 3, "4th example" assert checkio("a1-h8") == 6, "5th example"
#!/home/bespontoff/PycharmProjects/checkio/venv/bin/checkio --domain=py run army-units # You are the developer of the new strategy game and you need to add the soldier creation process to it. Let's start with the 2 types - AsianArmy and EuropeanArmy (each of them will be a subclass of the Army - class with the methods for the creation of soldiers). Also there will be 3 types of soldiers in the game - Swordsman, Lancer, and Archer (also the classes). Each army has unique names for those 3 types. For the EuropeanArmy there are: Knight (for Swordsman), Raubritter (for Lancer), and Ranger (for Archer). For the AsianArmy: Samurai (for Swordsman), Ronin (for Lancer), and Shinobi (for Archer). # Each army can create all 3 types of the soldiers using the next methods: # # train_swordsman(name) - create an instance of the Swordsman. # train_lancer(name) - create an instance of the Lancer. # train_archer(name) - create an instance of the Archer. # # All 3 classes (Swordsman, Lancer, and Archer) should have theintroduce()method, which returns the string that describes the soldiers in the following format: # "'type' 'name', 'army type' 'specialization(basic class)'", for example: # "Raubritter Harold, European lancer" # "Shinobi Kirigae, Asian archer" # # In this mission you should use theAbstract Factorydesign pattern. # # Example: # my_army = EuropeanArmy() # enemy_army = AsianArmy() # # soldier_1 = my_army.train_swordsman("Jaks") # soldier_2 = my_army.train_lancer("Harold") # soldier_3 = my_army.train_archer("Robin") # # soldier_4 = enemy_army.train_swordsman("Kishimoto") # soldier_5 = enemy_army.train_lancer("Ayabusa") # soldier_6 = enemy_army.train_archer("Kirigae") # # soldier_1.introduce() == "Knight Jaks, European swordsman" # soldier_2.introduce() == "Raubritter Harold, European lancer" # soldier_3.introduce() == "Ranger Robin, European archer" # # soldier_4.introduce() == "Samurai Kishimoto, Asian swordsman" # soldier_5.introduce() == "Ronin Ayabusa, Asian lancer" # soldier_6.introduce() == "Shinobi Kirigae, Asian archer" # # # Input:The names of the soldiers and class methods. # # Output:The description of soldiers. # # Precondition:2 types of the army. # 3 categories of soldiers. # # # END_DESC class Army: pass class Swordsman: pass class Lancer: pass class Archer: pass class AsianArmy(Army): pass class EuropeanArmy(Army): pass if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing my_army = EuropeanArmy() enemy_army = AsianArmy() soldier_1 = my_army.train_swordsman("Jaks") soldier_2 = my_army.train_lancer("Harold") soldier_3 = my_army.train_archer("Robin") soldier_4 = enemy_army.train_swordsman("Kishimoto") soldier_5 = enemy_army.train_lancer("Ayabusa") soldier_6 = enemy_army.train_archer("Kirigae") assert soldier_1.introduce() == "Knight Jaks, European swordsman" assert soldier_2.introduce() == "Raubritter Harold, European lancer" assert soldier_3.introduce() == "Ranger Robin, European archer" assert soldier_4.introduce() == "Samurai Kishimoto, Asian swordsman" assert soldier_5.introduce() == "Ronin Ayabusa, Asian lancer" assert soldier_6.introduce() == "Shinobi Kirigae, Asian archer" print("Coding complete? Let's try tests!")
#!/home/bespontoff/PycharmProjects/checkio/venv/bin/checkio --domain=py run army-battles # In the previous mission - Warriors - you've learned how to make a duel between 2 warriors happen. Great job! But let's move to something that feels a little more epic - the armies! In this mission your task is to add new classes and functions to the existing ones. The new class should be theArmyand have the methodadd_units()- for adding the chosen amount of units to the army. The first unit added will be the first to go to fight, the second will be the second, ... # Also you need to create aBattle()class with afight()function, which will determine the strongest army. # The battles occur according to the following principles: # at first, there is a duel between the first warrior of the first army and the first warrior of the second army. As soon as one of them dies - the next warrior from the army that lost the fighter enters the duel, and the surviving warrior continues to fight with his current health. This continues until all the soldiers of one of the armies die. In this case, the fight() function should returnTrue, if the first army won, orFalse, if the second one was stronger. # # # Note that army 1 have the advantage to start every fight! # # Input:The warriors and armies. # # Output:The result of the battle (True or False). # # Precondition:2 types of unitsFor all battles, each army is obviously not empty at the beginning. # # # END_DESC # Taken from mission The Warriors class Warrior: def __init__(self): self.is_alive = True self.health = 50 self.attack = 5 class Knight(Warrior): def __init__(self): super(Knight, self).__init__() self.attack = 7 def fight(unit_1, unit_2, unit_1_attack = True): unit_1_attack = unit_1_attack while unit_1.is_alive and unit_2.is_alive: if unit_1_attack: unit_2.health -= unit_1.attack if unit_2.health <= 0: unit_2.is_alive = False unit_1_attack = False else: unit_1.health -= unit_2.attack if unit_1.health <= 0: unit_1.is_alive = False unit_1_attack = True return True if unit_1.is_alive else False class Army: def __init__(self): self.units = [] def add_units(self, unit, count): for _ in range(count): self.units.append(unit()) def is_defeat(self): for unit in self.units: if unit.is_alive: return False return True class Battle: def __init__(self): pass def fight(self, army_1, army_2): white = army_1.units.pop(0) black = army_2.units.pop(0) while True: white_win = fight(white, black) if white_win: army_2.units.append(black) if army_2.is_defeat(): return True black = army_2.units.pop(0) else: army_1.units.append(white) if army_1.is_defeat(): return False white = army_1.units.pop(0) if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing chuck = Warrior() bruce = Warrior() carl = Knight() dave = Warrior() mark = Warrior() assert fight(chuck, bruce) == True assert fight(dave, carl) == False assert chuck.is_alive == True assert bruce.is_alive == False assert carl.is_alive == True assert dave.is_alive == False assert fight(carl, mark) == False assert carl.is_alive == False print("Coding complete? Let's try tests!") if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing #fight tests chuck = Warrior() bruce = Warrior() carl = Knight() dave = Warrior() mark = Warrior() assert fight(chuck, bruce) == True assert fight(dave, carl) == False assert chuck.is_alive == True assert bruce.is_alive == False assert carl.is_alive == True assert dave.is_alive == False assert fight(carl, mark) == False assert carl.is_alive == False #battle tests my_army = Army() my_army.add_units(Knight, 3) enemy_army = Army() enemy_army.add_units(Warrior, 3) army_3 = Army() army_3.add_units(Warrior, 20) army_3.add_units(Knight, 5) army_4 = Army() army_4.add_units(Warrior, 30) battle = Battle() assert battle.fight(my_army, enemy_army) == True assert battle.fight(army_3, army_4) == False print("Coding complete? Let's try tests!")
#!/home/bespontoff/PycharmProjects/checkio/venv/bin/checkio --domain=py run wrong-family # Michael always knew that there was something wrong with his family. Many strangers were introduced to him as part of it. # # Michael should figure this out. He's spent almost a month parsing the family archives. He has all father-son connections of his entire family collected in one place. # # With all that data Michael can easily understand who the strangers are. Or maybe the only stranger in this family is Michael? Let's see. # # You have a list of family ties between father and son. Each element on this list has two elements. The first is the father's name, the second is the son's name. All names in the family are unique. Check if the family tree is correct. There are no strangers in the family tree. All connections in the family are natural. # # Input:list of lists. Each element has two strings. The list has at least one element # # Output:bool. Is the family tree correct. # # # # # Precondition:1 <= len(tree) < 100 # # # END_DESC def is_family(tree: list[list[str]]) -> bool: return True if __name__ == "__main__": #These "asserts" using only for self-checking and not necessary for auto-testing assert is_family([ ['Logan', 'Mike'] ]) == True, 'One father, one son' assert is_family([ ['Logan', 'Mike'], ['Logan', 'Jack'] ]) == True, 'Two sons' assert is_family([ ['Logan', 'Mike'], ['Logan', 'Jack'], ['Mike', 'Alexander'] ]) == True, 'Grandfather' assert is_family([ ['Logan', 'Mike'], ['Logan', 'Jack'], ['Mike', 'Logan'] ]) == False, 'Can you be a father to your father?' assert is_family([ ['Logan', 'Mike'], ['Logan', 'Jack'], ['Mike', 'Jack'] ]) == False, 'Can you be a father to your brother?' assert is_family([ ['Logan', 'William'], ['Logan', 'Jack'], ['Mike', 'Alexander'] ]) == False, 'Looks like Mike is stranger in Logan\'s family' assert is_family([ ['Jack', 'Mike'], ['Logan', 'Mike'], ['Logan', 'Jack'], ]) == False, 'Two fathers' print("Looks like you know everything. It is time for 'Check'!")
#!/home/bespontoff/PycharmProjects/checkio/venv/bin/checkio --domain=py run the-highest-building # The main architect of the city wants to build a new highest building. # You have to help him find the current highest building in the city. # # # # Input:Heights of the buildings as a 2D-array. # # Output:The number of the highest building and height of it as a list of integers (Important: in this task the building numbers starts from "1", not from "0") # # Precondition: # array width<= 10 # array height<= 10 # There is only 1 highest building in each array # # # END_DESC def highest_building(buildings): for floor in buildings: if 1 in floor: # 1 means roof return [floor.index(1)+1, len(buildings)-buildings.index(floor)]
#!/home/bespontoff/PycharmProjects/checkio/venv/bin/checkio --domain=py run eaten-go-stones # A quite unbelievable event has occurred several years ago, in the spring of 2016 - the computer programAlphaGo, developed by Google DeepMind, won against the world's best player in theGo gamewith the result 4-1. Until the very last moment nobody believed that the computer can beat a man in the ancient Japanese game, in which the quantity of possible variants is greater than the number of atoms in the whole Universe! # # Unlike chess, where every player from the very beginning of the game has the full set of figures on the 8x8 board, and can analyse all moves just by using the estimation strategy, the Go game requires very different skills. First of all, this game uses the board which is almost 6 times greater than the chessboard - 361 game points against only 64 in chess. Secondly, the game begins with an absolutely empty board and till the middle of it your success is based strictly on your intuition and the sense of the harmonious placement of stones. # Regardless, due to the machine learning and the huge number of games AlphaGo has played with itself, the program became stronger than a man. # # In this mission you'll learn how to analyze the board situation along with the basic rules of the Go game. Here are some of them: # - 2 men play with stones (game figures) of different colors; # - the stones are put on the intersections; # - every stone or the group of stones has a certain degree of freedom or 'liberties' - dame (traditional Japanese word for this term). These are the points which contact with the stone/group horizontally and vertically; # - the whole group is a group of stones that contact with each other horizontally and vertically. The group has mutual 'liberties'; # - if all 'liberties' of the stone or the group are blocked/closed by the stones of the other player - these stones are being "eaten" and removed from the board. # Here is a demonstration of the 'liberties' concept. # # # # In this mission your task is to count how many stones of each color have been 'eaten'.The input will be a two-dimensional array - the list of the strings, where the empty intersections will be '+', the black stones - 'B' and the white stones - 'W' (black & white are the traditional colors for this game). You should return the answer in the dictionary format, like this: {'B': n, 'W': m}, where n and m are the amount of black and white stones which have been 'eaten'. For example, if there have been eaten 3 black stones, and 4 white, the answer will be: {'B': 3, 'W': 4}. # # # # Input:A two-dimensional array (the list of the strings). # # Output:Dictionary with the amount of the 'eaten' stones of each color. # # Precondition: # Board - 9х9, 7x7, 5x5 # # # END_DESC def go_game(board): #replace this for solution return board if __name__ == '__main__': print("Example:") print(go_game(['++++W++++', '+++WBW+++', '++BWBBW++', '+W++WWB++', '+W++B+B++', '+W+BWBWB+', '++++BWB++', '+B++BWB++', '+++++B+++'])) #These "asserts" using only for self-checking and not necessary for auto-testing assert go_game(['++++W++++', '+++WBW+++', '++BWBBW++', '+W++WWB++', '+W++B+B++', '+W+BWBWB+', '++++BWB++', '+B++BWB++', '+++++B+++']) == {'B': 3, 'W': 4} print("Coding complete? Click 'Check' to earn cool rewards!")
#!/home/bespontoff/PycharmProjects/checkio/venv/bin/checkio --domain=py run friends # pre.example { border: 1px solid #aaa; border-radius: 3px; background: #eee; margin-left: 20px; padding: 5px; overflow: auto; } p.indent { margin-left: 20px; }For the mission"How to find friends", it’s nice to have access to a specially made data structure. In this mission we will realize a data structure which we will use to store and work with a friend network. # # The class "Friends" should contains names and the connections between them. Names are represented as strings and are case sensitive. Connections are undirected, so if "sophia" is connected with "nikola", then it's also correct in reverse. # # classFriends(connections) # # Returns a new Friends instance."connections"is an iterable of sets with two elements in each. Each connection contains two names as strings. Connections can be repeated in the initial data, but inside it's stored once. Each connection has only two states - existing or not. # # # >>> Friends(({"a", "b"}, {"b", "c"}, {"c", "a"}, {"a", "c"})) # >>> Friends([{"1", "2"}, {"3", "1"}]) # # add(connection) # # Add a connection in the instance."connection"is a set of two names (strings). Returns True if this connection is new. Returns False if this connection exists already. # # # >>> f = Friends([{"1", "2"}, {"3", "1"}]) # >>> f.add({"1", "3"}) # False # >>> f.add({"4", "5"}) # True # # remove(connection) # # Remove a connection from the instance."connection"is a set of two names (strings). Returns True if this connection exists. Returns False if this connection is not in the instance. # # # >>> f = Friends([{"1", "2"}, {"3", "1"}]) # >>> f.remove({"1", "3"}) # True # >>> f.remove({"4", "5"}) # False # # names() # # Returns a set of names. The set contains only names which are connected with somebody. # # # >>> f = Friends(({"a", "b"}, {"b", "c"}, {"c", "d"})) # >>> f.names() # {"a", "b", "c", "d"} # >>> f.remove({"d", "c"}) # True # >>> f.names() # {"a", "b", "c"} # # connected(name) # # Returns a set of names which is connected with the given"name". If "name" does not exist in the instance, then return an empty set. # # # >>> f = Friends(({"a", "b"}, {"b", "c"}, {"c", "a"})) # >>> f.connected("a") # {"b", "c"} # >>> f.connected("d") # set() # >>> f.remove({"c", "a"}) # True # >>> f.connected("c") # {"b"} # >>> f.remove({"c", "b"}) # True # >>> f.connected("c") # set() # # In this mission all data will be correct and you don't need to implement value checking. # # Input:Statements and expression with the Friends class. # # Output:The behaviour as described. # # Precondition:All data is correct. # # # END_DESC class Friends: def __init__(self, connections): self.connections = list(connections) def add(self, connection): if connection in self.connections: return False else: self.connections.append(connection) return True def remove(self, connection): if connection in self.connections: self.connections.remove(connection) return True else: return False def names(self): res = set() for connection in self.connections: for name in connection: res.add(name) return res def connected(self, name): res = set() for connection in self.connections: if name in connection: tmp = connection.copy() tmp.remove(name) res.add(tmp.pop()) return res if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing letter_friends = Friends(({"a", "b"}, {"b", "c"}, {"c", "a"}, {"a", "c"})) digit_friends = Friends([{"1", "2"}, {"3", "1"}]) assert letter_friends.add({"c", "d"}) is True, "Add" assert letter_friends.add({"c", "d"}) is False, "Add again" assert letter_friends.remove({"c", "d"}) is True, "Remove" assert digit_friends.remove({"c", "d"}) is False, "Remove non exists" assert letter_friends.names() == {"a", "b", "c"}, "Names" assert letter_friends.connected("d") == set(), "Non connected name" assert letter_friends.connected("a") == {"b", "c"}, "Connected name"
#!/home/bespontoff/PycharmProjects/checkio/venv/bin/checkio --domain=py run straight-fight # A new unit type won’t be added in this mission, but instead we’ll add a new tactic -straight_fight(army_1, army_2). It should be the method of the Battle class and it should work as follows: # at the beginning there will be a few duels between each pair of soldiers from both armies (the first unit against the first, the second against the second and so on). After that all dead soldiers will be removed and the process repeats until all soldiers of one of the armies will be dead. Armies might not have the same number of soldiers. If a warrior doesn’t have an opponent from the enemy army - we’ll automatically assume that he’s won a duel (for example - 9th and 10th units from the first army, if the second has only 8 soldiers). # # Input:The warriors and armies. # # Output:The result of the battle (True or False). # # Precondition:5 types of units, 2 types of battles # # # END_DESC class Warrior: def __init__(self): self.is_alive = True self.health = 50 self.attack = 5 self.army = None def damage(self, attack): self.health -= attack return attack def hit(self, unit): unit.damage(self.attack) self.heal_me() def heal_me(self): if self.army is not None and len(self.army.units): if self.army.units[0].__class__.__name__ == "Healer": self.army.units[0].heal(self) class Knight(Warrior): def __init__(self): super(Knight, self).__init__() self.attack = 7 class Defender(Warrior): def __init__(self): super(Defender, self).__init__() self.health = 60 self.attack = 3 self.defense = 2 def damage(self, attack): if attack > self.defense: self.health -= attack - self.defense return attack - self.defense class Vampire(Warrior): def __init__(self): super(Vampire, self).__init__() self.health = 40 self.attack = 4 self.vampirism = 50 # in percents def hit(self, unit): dmg = unit.damage(self.attack) self.health += dmg * (self.vampirism / 100) self.heal_me() class Lancer(Warrior): def __init__(self): super(Lancer, self).__init__() self.attack = 6 def hit(self, unit): unit.damage(self.attack) if unit.army: unit.army.units[0].damage(self.attack * 0.5) self.heal_me() class Healer(Warrior): def __init__(self): super(Healer, self).__init__() self.health = 60 self.attack = 0 def heal(self, unit): if self.is_alive: unit.health += 2 def fight(unit_1, unit_2, unit_1_attack=True): unit_1_attack = unit_1_attack while unit_1.is_alive and unit_2.is_alive: if unit_1_attack: unit_1.hit(unit_2) if unit_2.health <= 0: unit_2.is_alive = False unit_1_attack = False else: unit_2.hit(unit_1) if unit_1.health <= 0: unit_1.is_alive = False unit_1_attack = True return True if unit_1.is_alive else False class Army: def __init__(self): self.units = [] def add_units(self, unit, count): for _ in range(count): soldier = unit() soldier.army = self self.units.append(soldier) def is_defeat(self): for unit in self.units: if unit.is_alive: return False return True def get_live_unit(self): for unit in self.units: if unit.is_alive: return unit return False class Battle: def __init__(self): pass def fight(self, army_1, army_2): white = army_1.units.pop(0) black = army_2.units.pop(0) while True: white_win = fight(white, black) if white_win: army_2.units.append(black) if army_2.is_defeat(): return True black = army_2.units.pop(0) else: army_1.units.append(white) if army_1.is_defeat(): return False white = army_1.units.pop(0) def straight_fight(self, army_1, army_2): while True: if army_1.is_defeat(): return False if army_2.is_defeat(): return True fight(army_1.get_live_unit(), army_2.get_live_unit()) if __name__ == '__main__': # These "asserts" using only for self-checking and not necessary for auto-testing chuck = Warrior() bruce = Warrior() carl = Knight() dave = Warrior() mark = Warrior() assert fight(chuck, bruce) == True assert fight(dave, carl) == False assert chuck.is_alive == True assert bruce.is_alive == False assert carl.is_alive == True assert dave.is_alive == False assert fight(carl, mark) == False assert carl.is_alive == False print("Coding complete? Let's try tests!") if __name__ == '__main__': # These "asserts" using only for self-checking and not necessary for auto-testing # fight tests chuck = Warrior() bruce = Warrior() carl = Knight() dave = Warrior() mark = Warrior() assert fight(chuck, bruce) == True assert fight(dave, carl) == False assert chuck.is_alive == True assert bruce.is_alive == False assert carl.is_alive == True assert dave.is_alive == False assert fight(carl, mark) == False assert carl.is_alive == False # battle tests my_army = Army() my_army.add_units(Knight, 3) enemy_army = Army() enemy_army.add_units(Warrior, 3) army_3 = Army() army_3.add_units(Warrior, 20) army_3.add_units(Knight, 5) army_4 = Army() army_4.add_units(Warrior, 30) battle = Battle() assert battle.fight(my_army, enemy_army) == True assert battle.fight(army_3, army_4) == False print("Coding complete? Let's try tests!") if __name__ == '__main__': # These "asserts" using only for self-checking and not necessary for auto-testing # fight tests chuck = Warrior() bruce = Warrior() carl = Knight() dave = Warrior() mark = Warrior() bob = Defender() mike = Knight() rog = Warrior() lancelot = Defender() assert fight(chuck, bruce) == True assert fight(dave, carl) == False assert chuck.is_alive == True assert bruce.is_alive == False assert carl.is_alive == True assert dave.is_alive == False assert fight(carl, mark) == False assert carl.is_alive == False assert fight(bob, mike) == False assert fight(lancelot, rog) == True # battle tests my_army = Army() my_army.add_units(Defender, 1) enemy_army = Army() enemy_army.add_units(Warrior, 2) army_3 = Army() army_3.add_units(Warrior, 1) army_3.add_units(Defender, 1) army_4 = Army() army_4.add_units(Warrior, 2) battle = Battle() assert battle.fight(my_army, enemy_army) == False assert battle.fight(army_3, army_4) == True print("Coding complete? Let's try tests!") if __name__ == '__main__': # These "asserts" using only for self-checking and not necessary for auto-testing # fight tests chuck = Warrior() bruce = Warrior() carl = Knight() dave = Warrior() mark = Warrior() bob = Defender() mike = Knight() rog = Warrior() lancelot = Defender() eric = Vampire() adam = Vampire() richard = Defender() ogre = Warrior() assert fight(chuck, bruce) == True assert fight(dave, carl) == False assert chuck.is_alive == True assert bruce.is_alive == False assert carl.is_alive == True assert dave.is_alive == False assert fight(carl, mark) == False assert carl.is_alive == False assert fight(bob, mike) == False assert fight(lancelot, rog) == True assert fight(eric, richard) == False assert fight(ogre, adam) == True # battle tests my_army = Army() my_army.add_units(Defender, 2) my_army.add_units(Vampire, 2) my_army.add_units(Warrior, 1) enemy_army = Army() enemy_army.add_units(Warrior, 2) enemy_army.add_units(Defender, 2) enemy_army.add_units(Vampire, 3) army_3 = Army() army_3.add_units(Warrior, 1) army_3.add_units(Defender, 4) army_4 = Army() army_4.add_units(Vampire, 3) army_4.add_units(Warrior, 2) battle = Battle() assert battle.fight(my_army, enemy_army) == False assert battle.fight(army_3, army_4) == True print("Coding complete? Let's try tests!") if __name__ == '__main__': # These "asserts" using only for self-checking and not necessary for auto-testing # fight tests chuck = Warrior() bruce = Warrior() carl = Knight() dave = Warrior() mark = Warrior() bob = Defender() mike = Knight() rog = Warrior() lancelot = Defender() eric = Vampire() adam = Vampire() richard = Defender() ogre = Warrior() freelancer = Lancer() vampire = Vampire() assert fight(chuck, bruce) == True assert fight(dave, carl) == False assert chuck.is_alive == True assert bruce.is_alive == False assert carl.is_alive == True assert dave.is_alive == False assert fight(carl, mark) == False assert carl.is_alive == False assert fight(bob, mike) == False assert fight(lancelot, rog) == True assert fight(eric, richard) == False assert fight(ogre, adam) == True assert fight(freelancer, vampire) == True assert freelancer.is_alive == True # battle tests my_army = Army() my_army.add_units(Defender, 2) my_army.add_units(Vampire, 2) my_army.add_units(Lancer, 4) my_army.add_units(Warrior, 1) enemy_army = Army() enemy_army.add_units(Warrior, 2) enemy_army.add_units(Lancer, 2) enemy_army.add_units(Defender, 2) enemy_army.add_units(Vampire, 3) army_3 = Army() army_3.add_units(Warrior, 1) army_3.add_units(Lancer, 1) army_3.add_units(Defender, 2) army_4 = Army() army_4.add_units(Vampire, 3) army_4.add_units(Warrior, 1) army_4.add_units(Lancer, 2) battle = Battle() assert battle.fight(my_army, enemy_army) == True assert battle.fight(army_3, army_4) == False print("Coding complete? Let's try tests!") if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing #fight tests chuck = Warrior() bruce = Warrior() carl = Knight() dave = Warrior() mark = Warrior() bob = Defender() mike = Knight() rog = Warrior() lancelot = Defender() eric = Vampire() adam = Vampire() richard = Defender() ogre = Warrior() freelancer = Lancer() vampire = Vampire() priest = Healer() assert fight(chuck, bruce) == True assert fight(dave, carl) == False assert chuck.is_alive == True assert bruce.is_alive == False assert carl.is_alive == True assert dave.is_alive == False assert fight(carl, mark) == False assert carl.is_alive == False assert fight(bob, mike) == False assert fight(lancelot, rog) == True assert fight(eric, richard) == False assert fight(ogre, adam) == True assert fight(freelancer, vampire) == True assert freelancer.is_alive == True assert freelancer.health == 14 priest.heal(freelancer) assert freelancer.health == 16 #battle tests my_army = Army() my_army.add_units(Defender, 2) my_army.add_units(Healer, 1) my_army.add_units(Vampire, 2) my_army.add_units(Lancer, 2) my_army.add_units(Healer, 1) my_army.add_units(Warrior, 1) enemy_army = Army() enemy_army.add_units(Warrior, 2) enemy_army.add_units(Lancer, 4) enemy_army.add_units(Healer, 1) enemy_army.add_units(Defender, 2) enemy_army.add_units(Vampire, 3) enemy_army.add_units(Healer, 1) army_3 = Army() army_3.add_units(Warrior, 1) army_3.add_units(Lancer, 1) army_3.add_units(Healer, 1) army_3.add_units(Defender, 2) army_4 = Army() army_4.add_units(Vampire, 3) army_4.add_units(Warrior, 1) army_4.add_units(Healer, 1) army_4.add_units(Lancer, 2) army_5 = Army() army_5.add_units(Warrior, 10) army_6 = Army() army_6.add_units(Warrior, 6) army_6.add_units(Lancer, 5) battle = Battle() assert battle.fight(my_army, enemy_army) == False assert battle.fight(army_3, army_4) == True assert battle.straight_fight(army_5, army_6) == False print("Coding complete? Let's try tests!")
#!/home/bespontoff/PycharmProjects/checkio/venv/bin/checkio --domain=py run 88th-puzzle # p.quote-source { float: right; font-size: 10px; }Dr. Emmett Brown: If my calculations are correct, when this baby hits 88 miles per hour... you're gonna see some serious shit. # # === # # Marty McFly: Hey, Doc, we better back up. We don't have enough road to get up to 88. # Dr. Emmett Brown: Roads? Where we're going, we don't need roads. # # "Back to the Future" (1985) # # According to ancient Chinese legend, 88 is a magic number. On the 88th page of the book, "Ancient human puzzles catalog for modern robots", you will find a puzzle which Nikola’s archaeologist uncle discovered a very long time ago in an ancient human magazine. Nikola has been trying to solve this puzzle since he first rolled off his parents assembly line, and now it’s time for us to help him figure this out once and for all. # # The puzzle looks like four intersecting circles with 12 colored marbles: 2 red, 2 blue, 2 green, 2 orange and 4 grey. Take a look at the illustration to see how this setup works. The marbles should be placed as it shown below. Each hole and color has a number for data representing a state. Colored numbers: 1 - blue, 2 - green, 3 - red, 4 - orange, 0 - grey. The initial state (or completed) will be represented as the sequence of numbers, where an index is a “hole” number: # (1, 2, 1, 0, 2, 0, 0, 3, 0, 4, 3, 4). # # # # You can rotate the rings clockwise. Each move rotates the ring by 90 degrees. The rings are numbered and sequence of action should be represented as a list/tuple of numbers from 1 to 4. # # You are given a twisted puzzle state as a tuple of numbers. You should return it to the initial state with the minimal number of steps. For example, the state in the picture below would be represented as (0,2,1,3,2,1,4,0,0,4,0,3) and can be solved in 4 steps "1433" or "4133". The first means "rotate 1st ring one time (by 90 degrees of course), 4th - one time, 3th - two times. # # # # Input:A puzzle state as a tuple of integers. # # Output:The shortest solution as a string. # # Precondition: # len(state) == 12 # all(0 ≤ n ≤ 4 for n in state) # All test cases are solvable. # # # END_DESC GOAL = (1, 2, 1, 0, 2, 0, 0, 3, 0, 4, 3, 4) def puzzle88(state): return "" if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing assert puzzle88((0, 2, 1, 3, 2, 1, 4, 0, 0, 4, 0, 3)) in ('1433', '4133'), "Example" assert puzzle88((0, 2, 1, 2, 0, 0, 4, 1, 0, 4, 3, 3)) in ('4231', '4321'), "Rotate all" assert puzzle88((0, 2, 1, 2, 4, 0, 0, 1, 3, 4, 3, 0)) in ('2314', '2341', '3214', '3241'), "Four paths"
#!/home/bespontoff/PycharmProjects/checkio/venv/bin/checkio --domain=py run matrix-transpose # In linear algebra, the transpose of a matrixAis another matrixAT(also writtenA′,Atr,tAorAt) created by any one of the following equivalent actions: # # reflectAover its main diagonal (which runs from top-left to bottom-right) to obtainATwrite the rows ofAas the columns ofATwrite the columns ofAas the rows ofATFormally, theithrow,jthcolumn element ofATis thejthrow,ithcolumn element ofA: # # [AT]i j= [A]j i # # IfAis anm×nmatrix thenATis ann×mmatrix. # # You have been given a matrix as a 2D list with integers. Your task is to return a transposed matrix based on input. # # Input:A matrix as a list of lists with integers. # # Output:The transposed matrix as a list/tuple of lists/tuples with integers. # # Precondition: # 0 < len(matrix) < 10 # all(0 < len(row) < 10 for row inmatrix) # # # END_DESC def checkio(data): dataT = [] for i in range(len(data[0])): s = [] for j in range(len(data)): s.append(data[j][i]) dataT.append(s) #replace this for solution return dataT #These "asserts" using only for self-checking and not necessary for auto-testing if __name__ == '__main__': assert isinstance(checkio([[0]]).pop(), list) is True, "Match types" assert checkio([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [[1, 4, 7], [2, 5, 8], [3, 6, 9]], "Square matrix" assert checkio([[1, 4, 3], [8, 2, 6], [7, 8, 3], [4, 9, 6], [7, 8, 1]]) == [[1, 8, 7, 4, 7], [4, 2, 8, 9, 8], [3, 6, 3, 6, 1]], "Rectangle matrix"
#!/home/bespontoff/PycharmProjects/checkio/venv/bin/checkio --domain=py run ryerson-letter-grade # Given the grade percentage for the course, calculate and return the letter grade that would appear in the Ryerson’s grade transcript, as defined on the pageRyerson Grade Scales. The letter grade should be returned as a string that consists of the uppercase letter followed by the possible modifier "+" or "-" . # # Input:Int. Grade percentage. # # Output:Str. The letter grade. # # Precondition:argument can be from 0 to 150 # # The mission was taken from Python CCPS 109 Fall 2018. It is taught for Ryerson Chang School of Continuing Education byIlkka Kokkarinen # # # END_DESC # feel free to change table structure in any way TABLE = ''' A 85-89% A- 80-84% B+ 77-79% B 73-76% B- 70-72% C+ 67-69% C 63-66% C- 60-62% D+ 57-59% D 53-56% D- 50-52% ''' def ryerson_letter_grade(pct: int) -> str: # your code here return "A" if __name__ == '__main__': print("Example:") print(ryerson_letter_grade(45)) # These "asserts" are used for self-checking and not for an auto-testing assert ryerson_letter_grade(45) == "F" assert ryerson_letter_grade(62) == "C-" print("Coding complete? Click 'Check' to earn cool rewards!")
#!/home/bespontoff/PycharmProjects/checkio/venv/bin/checkio --domain=py run how-much-gold # Our Favorite Trio has found a mysterious metal bar. This bar appears to be made of various metal including gold, iron, copper and tin. The bar does not contain any other metal except these. We do not know the quantity of each metal in the bar, but we do know the proportions of the various alloys. For example: the gold and tin proportion is 1/2, gold and iron -- 1/3, gold and copper -- 1/4. "the gold and tin proportion is 1/2" means that gold and tin together (their sum, not their ratio!) are the 1/2 of the whole bar (the sum of them all). You should calculate the proportion of gold in the entire bar. # # The proportions are given as a dictionary where keys are alloy names and values are proportions. The alloy names are presented as strings, which are composed of two metal names separated by a dash (Ex: "gold-tin", "iron-copper", "iron-gold"). The proportions are presented as fractions (fractions.Fractiondate type.Read about this module). # # # # You should return the proportion of gold in the bar as a fraction (fractions.Fraction). # # Input:Alloys names and proportions as a dictionary. # # Output:Proportion of gold as a fractions.Fraction. # # Precondition: # All tests are solvable. # The bar contains all four metals. # # # # END_DESC from fractions import Fraction METALS = ('gold', 'tin', 'iron', 'copper') def checkio(alloys): """ Find proportion of gold """ return Fraction(1, 1) #These "asserts" using only for self-checking and not necessary for auto-testing if __name__ == '__main__': assert checkio({ 'gold-tin': Fraction(1, 2), 'gold-iron': Fraction(1, 3), 'gold-copper': Fraction(1, 4), }) == Fraction(1, 24), "1/24 of gold" assert checkio({ 'tin-iron': Fraction(1, 2), 'iron-copper': Fraction(1, 2), 'copper-tin': Fraction(1, 2), }) == Fraction(1, 4), "quarter"
# 1. Дано целое число (int). Определить сколько нулей в этом числе. ######################################################################## value = 20020025876055505 value_str = str(value) zero = value_str.count('0') print("В числе ", value, "находится", zero, "нулей") ######################################################################## # 2. Дано целое число (int). Определить сколько нулей в конце этого числа. ######################################################################## value = 1025005500000 res = int(str(value)[::-1]) zero = len(str(value)) - len(str(res)) print("В конце числа ", value, "находится", zero, "нулей") ######################################################################## # 3a. Даны списки my_list_1 и my_list_2. # Создать список my_result в который вначале поместить # элементы на четных местах из my_list_1, а потом все элементы на нечетных местах из my_list_2. ######################################################################## my_list_1 = [1, 2, 3, 4, 5, 6] my_list_2 = [7, 8, 9, 10, 11, 12] my_result = [] for index in range(len(my_list_1)): if not index % 2: my_result.append(my_list_1[index]) for index in range(len(my_list_2)): if index % 2: my_result.append(my_list_2[index]) print(my_result) ######################################################################## # 3b. Даны списки my_list_1 и my_list_2. Создать список my_result в который # вначале поместить четные элементы (ИМЕННО ЭЛЕМЕНТЫ) из my_list_1 и потом нечетные элементы из my_list_2. # my_list_1 = [1,2,3,4,5], my_list_2 = [10, 15, 20, 25] -> my_result [2, 4, 15, 25] ######################################################################## my_list_1 = [1, 2, 3, 4, 5, 6] my_list_2 = [7, 8, 9, 10, 11, 12] my_result = [] for index in range(len(my_list_1)): if index % 2: my_result.append(my_list_1[index]) for index in range (len(my_list_2)): if not index % 2: my_result.append(my_list_2[index]) print(my_result) ######################################################################## # 4. Дан список my_list. СОЗДАТЬ НОВЫЙ список new_list у которого первый элемент из my_list # стоит на последнем месте. Если my_list [1,2,3,4], то new_list [2,3,4,1] ######################################################################## my_list = [1, 2, 3, 4] new_list = [] new_list.extend(my_list[1::]) new_list.append(my_list[:1:]) print(new_list) ######################################################################## # 5.Дан список my_list. В ЭТОМ списке первый элемент переставить на последнее место. # [1,2,3,4] -> [2,3,4,1]. Пересоздавать список нельзя! (используйте метод pop) ######################################################################## my_list = [1, 2, 3, 4] my_list.append(my_list[:1:]) my_list.pop(0) print(my_list) ######################################################################## # 6. Дана строка в которой есть числа (разделяются пробелами). # Например "43 больше чем 34 но меньше чем 56". Найти сумму ВСЕХ ЧИСЕЛ (А НЕ ЦИФР) в этой строке. # Для данного примера ответ - 133. ######################################################################## my_str = "43 больше чем 34 но меньше чем 56" words = my_str.split(" ") product = 0 for word in words: try: value = int(word) product += value except: pass print(product) ######################################################################## # 7. Дана строка my_str. Разделите эту строку на пары из двух символов и поместите эти пары в список. # Если строка содержит нечетное количество символов, пропущенный второй символ последней пары должен # быть заменен подчеркиванием ('_'). Примеры: 'abcd' -> ['ab', 'cd'], 'abcde' -> ['ab', 'cd', e_'] ######################################################################## my_string = 'abcde' my_string = my_string if not len(my_string) % 2 else my_string + "_" print(my_string) my_list = [] [my_list.append(my_string[i:i+1]+my_string[i+1:i+2]) for i in range(0, len(my_string), 2)] print(my_list) ######################################################################## # 8. Дана строка my_str в которой символы не повторяются и два символа l_limit, r_limit, # которые точно находятся в этой строке. Причем l_limit левее чем r_limit. # В переменную sub_str поместить часть строки между этими символами. # my_str = "My_long str", l_limit = "o", r_limit = "t" -> sub_str = "ng s" ######################################################################## my_str = "My_long str" l_limit = "o" r_limit = "t" sub_str = my_str[my_str.find(l_limit)+1: my_str.find(r_limit)] print(sub_str) ######################################################################## # 9. Дана строка my_str в которой символы МОГУТ повторяться и два символа l_limit, r_limit, # которые точно находятся в этой строке. Причем l_limit левее чем r_limit. # В переменную sub_str поместить НАИБОЛЬШУЮ часть строки между этими символами. # my_str = "My long string", l_limit = "o", r_limit = "g" -> sub_str = "ng strin". ######################################################################## my_str = "My long string" l_limit = "o" r_limit = "g"*2 sub_str = my_str[my_str.find(l_limit)+1: my_str.find(r_limit)] print(sub_str) ######################################################################## # 10. Дан список чисел. Определите, сколько в этом списке элементов, # которые больше суммы двух своих соседей (слева и справа), и НАПЕЧАТАЙТЕ КОЛИЧЕСТВО таких элементов. # Крайние элементы списка никогда не учитываются, поскольку у них недостаточно соседей. # Для списка [2,4,1,5,3,9,0,7] ответом будет 3 потому что 4 > 2+1, 5 > 1+3, 9>3+0. ######################################################################## my_list = [2, 4, 1, 5, 3, 9, 0, 7] num = 0 for i in range(1, len(my_list)-1): if int(my_list[i-1]) < int(my_list[i]) and int(my_list[i]) > int(my_list[i+1]): num += 1 print(num) ########################################################################
#!/usr/bin/python3 def change_int(num): num += 5 print("Inside the function with num changed to : " + str(num)) #main myNum = 5 print("Inside the main function with num being: " + str(myNum)) print("calling the change int function") change_int(myNum) print("now my int is : " + str(myNum))
#!/usr/bin/python3 # # longestRun.py # # Description: given a number, find the longest sequence of 1s given its binary representation # # Created: 12/14/2019 # # Developer: codex040 # # Version: 1.0 # ######################### Function definition ######################### def longestRun(num): # validate the input if num < 1: return 0 # 1 convert the num to binary and get a string representation. Make sure to remove the leading two characters '0b' # 2 Pick the max sequence of 1s # 3 Return the length of that sequence return len(max((bin(num)[2:]).split('0'), key=len)) ''' First solution # local variables longestSoFar = 0 currentRun = 0 # iterate through each bit and check whethe it's a "0" or a "1" while num: if num & 1: currentRun += 1 else: longestSoFar = max(longestSoFar, currentRun) currentRun = 0 num = num >> 1 # check the last iteration longestSoFar = max(longestSoFar, currentRun) # return the longest seen sequence return longestSoFar ''' ######################### Driver Code ######################### number = 446 print("Longest seen sequence is : " + str(longestRun(number)))
#sort.py #given an array which consists of three unique values, sort them in #increasing order ######################################################################## #Function definitions ######################################################################## def sortNums(nums): #check if there are any number to process if(len(nums) == 0): return [] #local variables numbers = [] unique_values = {} #iterate through the list and categorize the values for num in nums: if(num not in unique_values.keys()): unique_values[num] = [] unique_values[num].append(num) #append the three indiividual lists into the main "number" one #and return the list for k in sorted(unique_values.keys()): numbers += unique_values[k] #return the list return numbers ######################################################################## #Main function ######################################################################## numbers = [2, 1, 2, 1, 2, 1, 3, 3, 3, 2, 1] print("Initial list: ") print(numbers) print("Sorting the numbers....") sorted_numbers = sortNums(numbers) print("Sorted list: " ) print(sorted_numbers)
#!/usr/bin/python3 ''' binary search implement binary search created: 09/03/2020 version: 1.0 ''' ######################## Function Definition #################### def binary_search(numbers, target, is_sorted = False): #local variables s = 0 #start of the list e = len(numbers) - 1 #end of the list #sort the numbers if they are not already sorted if is_sorted != True: numbers.sort() #validation check if e < 0: return -1 #indicate the number which was #searched for doesn't exist in the current list #iterate through each respective section of the list and #check whether the number to be searched for is there while s < e: m = (s + e) // 2 #perform checks if numbers[m] < target: #need to check right side s = m + 1 elif numbers[m] > target: #need to check left side e = m - 1 else: #found the number return m #at this point, s == e and it's possible it will match #the number tha is being searched if numbers[s] == target: return s else: return -1
""" longestSubstr.py given a string, find the longest substring with no repeating characters """ def findLongestSubstr(textStr): if len(textStr) <= 1: return subStr = set(textStr[0]) i = 1 startPos = 0 longestSubstrLen = 1 longestSubstring = textStr[0] while i < len(textStr): if textStr[i] not in subStr: subStr.add(textStr[i]) longestSubstring += textStr[i] longestSubstrLen += 1 i += 1 elif len(subStr) > longestSubstrLen: longestSubstrLen = len(subStr) longestSubstring = textStr[startPos: startPos + len(subStr)] startPos = startPos + len(subStr) subStr = set() i += 1 else: i += 1 return [longestSubstrLen, longestSubstring] #main myString = "abcabcadefghiabc" print("String: " + myString) print("Length: " + str(len(myString))) result = findLongestSubstr(myString) print("Longest substring length: " + str(result[0]) + " Longest substring: " + result[1])
#!/usr/bin/python3 ''' schedule_tasks.py A task is a some work to be done which can be assumed takes 1 unit of time. Between the same type of tasks you must take at least n units of time before running the same tasks again. Given a list of tasks (each task will be represented by a string), and a positive integer n representing the time it takes to run the same task again, find the minimum amount of time needed to run all tasks. created: 09/06/2020 version: 1.0 ''' ############################### Import required modules ################################### from collections import Counter from operator import itemgetter ################################ Function Definition ###################################### def schedule(tasks, time): # validation checks num_tasks = len(tasks) if num_tasks == 0 or time <= 0: return 0 if num_tasks == 1: return num_tasks # additional local variables task_counts = Counter(tasks).most_common() # get a list of tuples showing the unique tasks as well as their counts ordered by their frequency tasks_remaining = dict(sorted(task_counts, key=itemgetter(1), reverse=True)) # get the keys from the above list so that we can keep track of how many still remain tasks = list(tasks_remaining.keys()) time_blocks = task_counts[0][1] schedule = [[] for i in range(time_blocks)] # used to hold the final propposed schedule # iterate for as long as there are still tasks remaining while tasks_remaining: for i in range(len(tasks)): schedule[i].append(tasks[0]) tasks_remaining[tasks[0]] -= 1 if tasks_remaining[tasks[0]] == 0: del (tasks_remaining[tasks[0]]) del (tasks[0]) # determine whether any time blocks need to have an idle slot (the last block doesn't need to be considered as #there is no need to idle once all tasks are completed) for i in range(time_blocks - 1): diff = time - len(schedule[i]) if diff > 0: for j in range(diff): schedule[i].append('idle') else: continue #flatten the list and return its length final_schedule = [ task for sub_schedule in schedule for task in sub_schedule] print(len(final_schedule)) ################################ Main Function ###################################### tasks = ['q', 'q', 'q', 'w', 'w', 's'] # call the schedule function schedule(tasks, 4)
#two_sum.py #given a list and a target "k" find if there are two numbers in the list #that can add up to the target #function definition def two_sum(list, k): #iterate through the list and check if a pair exists for i in range(0,len(list)): diff = k - list[i] if diff in list[i:]: return True #at this point there is no pair that can add up to the target return False #main nums = [4, 7, 1, -3, 2] target = 6 print("List is: ") print(list) print("Target is: " + str(target)) print("Searching ..... ") result = two_sum(nums, target) print("Has pair : " + str(result))
class Demo: name = "" #assign val by constructor def __init__(self, name): self.name = name #get val by method def func(self): print("My name is "+self.name) ob = Demo("Harshil") ob.func()
# Arithmetic Operators => +, -, //, *, % # Comparison operators => ==,!=,<=,=>,<,> # Logical operators => and, or, not # Assignment operators => =,+=,-=,*=,/=,//= # Membership Operators => in, not in # Identity Operators => is, is not print(2+3) print(2>=3) if 4 % 2 == 0: print("modulo is 0") a = 2 b = 3 a *= b print(a) li = [2,51,68,90] if 2 in li: print("Element exist!") print(a is b)
print("break---->") for i in range(1,6): if i == 3: break print(i) print("continue---->") for i in range(1,6): if i == 3: continue print(i)
import nltk from nltk.tokenize import sent_tokenize from nltk.tokenize import word_tokenize from textblob import TextBlob text=("My name is Adithya! What about yours? It is a very beautiful day today.") tokenized_text=sent_tokenize(text) print(tokenized_text) #breaks paras into sentences. text=("My name is Adithya! What about yours? It is a very beautiful day today.") tokenized_word=word_tokenize(text) print(tokenized_word) #text into words #correcting spelling using textblob b = TextBlob("EEEnglish is nott my first language") print(b.correct()) #translation to spanish a= TextBlob("What is your name") a.translate(to='es') print(a)
''' OpenCV provides the bilateralFilter() function to apply the bilateral filter on the image. The bilateral filter can reduce unwanted noise very well while keeping edges sharp. The syntax of the function is given below src- It denotes the source of the image. It can be an 8-bit or floating-point, 1-channel image. dst- It denotes the destination image of the same size. Its type will be the same as the src image. d - It denotes the diameter of the pixel neighborhood (integer type) that is used during filtering. If its value is negative, then it is computed from sigmaSpace. sigmaColor - It denotes the filter sigma in the color space. sigmaSpace - It denotes the filter sigma in the coordinate space. ''' import cv2 import numpy as np from matplotlib import pyplot as plt img = cv2.imread('./Media/sample.jpeg',1) blur = cv2.bilateralFilter(img,9,75,75) plt.subplot(121),plt.imshow(img),plt.title('Original') plt.xticks([]), plt.yticks([]) plt.subplot(122),plt.imshow(blur),plt.title('Bilateral Filter') plt.xticks([]), plt.yticks([]) plt.show() cv2.waitKey(0) & 0xFF cv2.destroyAllWindows()
from unittest import TestCase from collections import defaultdict, namedtuple from shopping_basket.pricer import BasketPricer class TestBasketPricer(TestCase): def setUp(self): self.basket = defaultdict(int) self.catalogue = { "Baked Beans": 0.99, "Biscuits": 1.20, "Sardines": 1.89, "Shampoo": 2.00, "Corona Vaccine": 1000000000.00, } offer = namedtuple("Offer", ["name", "x", "y", "percentage"]) self.offers = { "Baked Beans": offer("BuyXgetYfree", 2, 1, 0.0), "Sardines": offer("discount_percentage", 0, 0, 0.25), "Shampoo": offer("BuyXgetYfree", 3, 1, 0.0), "Corona Vaccine": offer("BuyForFree", 0, 0, 1.0), } def test_empty_basket(self): """ An empty basket has a sub-total, discount and total each of zero. """ pricer = BasketPricer(self.basket, self.catalogue, self.offers) subtotal, discounts, total = pricer() self.assertEqual([0.0, 0.0, 0.0], [subtotal, discounts, total]) def test_calculate_subtotal(self): """ sub-total: The undiscounted cost of items in a basket. """ self.basket["Biscuits"] += 2 self.basket["Shampoo"] += 2 pricer = BasketPricer(self.basket, self.catalogue, self.offers) self.assertEqual(6.4, pricer._calculate_subtotal()) def test_calculate_total_discounts(self): """ The amount of money which must be subtracted from the subtotal in order to calculate the final price of the goods in the basket. """ self.basket["Baked Beans"] += 4 self.basket["Sardines"] += 1 pricer = BasketPricer(self.basket, self.catalogue, self.offers) self.assertEqual(1.46, pricer._calculate_total_discounts()) def test_no_discounts(self): self.basket["Biscuits"] += 2 pricer = BasketPricer(self.basket, self.catalogue, self.offers) self.assertEqual(0.0, pricer._calculate_total_discounts()) def test_calculate_discount_percentage(self): pricer = BasketPricer(self.basket, self.catalogue, self.offers) self.assertEqual(0.95, pricer._calculate_discount("Sardines", 2)) def test_calculate_discount_buyXgetY(self): pricer = BasketPricer(self.basket, self.catalogue, self.offers) self.assertEqual(2.0, pricer._calculate_discount("Shampoo", 4)) def test_calculate_discount_unknown_discount(self): pricer = BasketPricer(self.basket, self.catalogue, self.offers) with self.assertRaises(Exception): self.assertEqual(2.0, pricer._calculate_discount("Corona Vaccine", 1)) def test_assignment_example_one(self): self.basket["Baked Beans"] += 4 self.basket["Biscuits"] += 1 pricer = BasketPricer(self.basket, self.catalogue, self.offers) self.assertEqual((5.16, 0.99, 4.17), pricer()) def test_assignment_example_two(self): self.basket["Baked Beans"] += 2 self.basket["Biscuits"] += 1 self.basket["Sardines"] += 2 pricer = BasketPricer(self.basket, self.catalogue, self.offers) self.assertEqual((6.96, 0.95, 6.01), pricer())
# FontLab script to generate OpenType feature substitution code for selected glyphs # works with simple ligatures and alternates. # Does not attempt to decode multiple-feature glyphs such as "f_f_i.alt" # as there is no single clear right input set for that # # by Thomas Phinney, open source under Apache 2.0 license f = fl.font if f == None: exit # function to call for each glyph... # it takes two arguments def printCode(g): if g == None: return # take the part of the glyph name before the period: dropDot = g.name.split(".")[0] # separate ligature components: ligSplit = dropDot.replace("_"," ") # if neither of these substitutions did anything, exit function and don't print the replacement code if ligSplit == g.name : return # hey, let's print the glyph replacement code now! print " sub", ligSplit, "by", g.name , ";" # This is the actual program (using the function above) font = fl.font glyphs = font.glyphs # for every glyph in the font for index in range(len(glyphs)): if fl.Selected(index): printCode(glyphs[index])
import RPi.GPIO as GPIO from time import sleep # GPIO Pins, needs to be fixed later, as 1-6 are obviously not valid # TODO: All the turn sleeps are probably wrong, will fix as soon as circuit is built Motor_ONE_A = 1 Motor_TWO_A = 2 Motor_ONE_B = 3 Motor_TWO_B = 4 Motor_THREE_A = 5 Motor_THREE_B = 6 def forward(): print "Setting up forward" GPIO.output(Motor_ONE_A, GPIO.HIGH) GPIO.output(Motor_ONE_B, GPIO.LOW) GPIO.output(Motor_TWO_A, GPIO.LOW) GPIO.output(Motor_TWO_B, GPIO.HIGH) print "Should be moving forward now" sleep(2) print "Shutting down ONE AND TWO" GPIO.output(Motor_ONE_A, GPIO.LOW) GPIO.output(Motor_TWO_B, GPIO.LOW) def backward(): print "Setting up backward" GPIO.output(Motor_ONE_A, GPIO.LOW) GPIO.output(Motor_ONE_B, GPIO.HIGH) GPIO.output(Motor_TWO_A, GPIO.HIGH) GPIO.output(Motor_TWO_B, GPIO.LOW) print "Should be moving backward now" sleep(2) print "Shutting down ONE and TWO" GPIO.output(Motor_ONE_B, GPIO.LOW) GPIO.output(Motor_TWO_A, GPIO.LOW) def left(): print "Adjusting to turn" GPIO.output(Motor_ONE_A, GPIO.HIGH) GPIO.output(Motor_ONE_B, GPIO.LOW) print "Actually turning" sleep(1) GPIO.output(Motor_ONE_A, GPIO.LOW) GPIO.output(Motor_ONE_B, GPIO.LOW) print "Setting up left" GPIO.output(Motor_THREE_A, GPIO.HIGH) GPIO.output(Motor_THREE_B, GPIO.LOW) GPIO.output(Motor_TWO_A, GPIO.LOW) GPIO.output(Motor_TWO_B, GPIO.HIGH) print "Should be moving forward now" sleep(2) print "Shutting down TWO AND THREE" GPIO.output(Motor_THREE_A, GPIO.LOW) GPIO.output(Motor_TWO_B, GPIO.LOW) print "Readjusting to turn" GPIO.output(Motor_ONE_B, GPIO.HIGH) GPIO.output(Motor_ONE_A, GPIO.LOW) sleep(1) GPIO.output(Motor_ONE_B, GPIO.LOW) def right(): print "Adjusting to turn" GPIO.output(Motor_ONE_B, GPIO.HIGH) GPIO.output(Motor_ONE_A, GPIO.LOW) print "Actually turning" sleep(1) GPIO.output(Motor_ONE_B, GPIO.LOW) print "Setting up left" GPIO.output(Motor_THREE_A, GPIO.HIGH) GPIO.output(Motor_THREE_B, GPIO.LOW) GPIO.output(Motor_TWO_A, GPIO.LOW) GPIO.output(Motor_TWO_B, GPIO.HIGH) print "Should be moving forward now" sleep(2) print "Shutting down TWO AND THREE" GPIO.output(Motor_THREE_A, GPIO.LOW) GPIO.output(Motor_TWO_B, GPIO.LOW) print "Readjusting to turn" GPIO.output(Motor_ONE_A, GPIO.HIGH) GPIO.output(Motor_ONE_B, GPIO.LOW) sleep(1) GPIO.output(Motor_ONE_A, GPIO.LOW) def clockwise(): print "Staring to turn" GPIO.output(Motor_ONE_A, GPIO.HIGH) GPIO.output(Motor_ONE_B, GPIO.LOW) GPIO.output(Motor_TWO_A, GPIO.HIGH) GPIO.output(Motor_TWO_B, GPIO.LOW) GPIO.output(Motor_THREE_A, GPIO.HIGH) GPIO.output(Motor_THREE_B, GPIO.LOW) print "Lets turn ClockWise" sleep(2) print "Turning off clockwise" GPIO.output(Motor_THREE_A, GPIO.LOW) GPIO.output(Motor_ONE_A, GPIO.LOW) GPIO.output(Motor_TWO_A, GPIO.LOW) def counterClockwise(): print "Staring to turn" GPIO.output(Motor_ONE_A, GPIO.LOW) GPIO.output(Motor_ONE_B, GPIO.HIGH) GPIO.output(Motor_TWO_A, GPIO.LOW) GPIO.output(Motor_TWO_B, GPIO.HIGH) GPIO.output(Motor_THREE_A, GPIO.LOW) GPIO.output(Motor_THREE_B, GPIO.HIGH) print "Lets turn CounterClockWise" sleep(2) print "Turning off counterclockwise" GPIO.output(Motor_THREE_B, GPIO.LOW) GPIO.output(Motor_ONE_B, GPIO.LOW) GPIO.output(Motor_TWO_B, GPIO.LOW) def execute(queue): GPIO.setmode(GPIO.BOARD) GPIO.setup(Motor_ONE_A, GPIO.OUT) GPIO.setup(Motor_ONE_B, GPIO.OUT) GPIO.setup(Motor_TWO_A, GPIO.OUT) GPIO.setup(Motor_TWO_B, GPIO.OUT) GPIO.setup(Motor_THREE_A, GPIO.OUT) GPIO.setup(Motor_THREE_B, GPIO.OUT) for item in queue: if(item == "Up"): forward() elif(item == "Down"): backward() elif(item == "Left"): left() elif(item == "Right"): right() elif(item == "CW"): clockwise() elif(item == "CCW"): counterClockwise() shutdown() def shutdown(): GPIO.cleanup()
""" This was written the 26th of January 2017. The code aims to determine the exact composition of a molecule and displays the number of the consisting atoms. An example is shown at the end. @author: Tarek Samaali """ import re class Stack : """ The stack will be useful when dealing with brackets, curlies and parentheses. It will be used when determining the coefficients of the elements. """ open=['(','[','{'] close=[')',']','}'] stack=[] def stackk(self): return self.stack def push(self,item): self.stack.append(item) def pop(self): self.stack.pop() class chemical_elements: def uniq(self,list): """ ==> Unique elements of the formula """ unique=[] for el in list: if not(el in unique) : unique.append(el) return unique def exist(self,el,string): try: a=string.index(el) return [a,True] except ValueError: return False def detect_positions(self,el,string): """ We will work with the elements' positions at first. For this purpose, the function gives back an array of the wanted positions. A little difficulty here to combine single-word elements and double-word ones. """ result=[] while(self.exist(el,string)) : result.append(self.exist(el,string)[0]) string=string[:string.index(el)]+'*'*len(el)+string[string.index(el)+len(el):] return result def parse_molecule(self,formula): entities=self.uniq(re.findall('[A-Z][a-z]|[A-Z]',formula)) sorted=entities sorted.sort(key=lambda x:len(x)) sorted=sorted[::-1] dict={} redlist=[] for el in sorted : """ We will run through the chemical elements one by one """ positions=self.detect_positions(el,formula) totalcoeff=0 prototype=formula """ Each element might appear in different positions within diverse forms. We will go through the positions of each element. """ for pos in positions : if not(pos in redlist) : redlist.append(pos) count=pos coeff=1 mult=re.findall(re.escape(el)+'\d*',prototype) """ In case the considered element is followed by a coefficient, this will be taken into account. """ if mult: try: mult=re.findall('\d+$',mult[0])[0] coeff=int(mult) count+=len(str(mult[0])) except IndexError: pass s=Stack() """ We're checking here if the found closing items (')',']','}') contain the current chemical element. If so, the element coefficient is updated when necessary. """ while count<(len(prototype)): if prototype[count] in s.open: s.push(prototype[count]) try : if prototype[count] in s.close: s.pop() except IndexError: mult=re.findall(re.escape(prototype[count-1]+prototype[count])+'\d+',prototype) try : if mult : mult=re.findall('\d+$',mult[0]) coeff*=int(mult[0]) count+=len(str(mult[0])) except IndexError: pass count+=1 totalcoeff+=coeff prototype=prototype[:pos]+'*'*len(el)+prototype[pos+len(el):] dict[el]=totalcoeff return dict #>>>ch=chemical_elements() #>>>ch.parse_molecule('(C5H5)Fe(CO)2CH3') #{'H': 8, 'C': 8, 'Fe': 1, 'O': 2}
import sys import struct import numpy import matplotlib.pyplot as plt from PIL import Image # Decompose a binary file into an array of bits def decompose(data): #the array of bits we will fill v = [] #Length of the file. Will be used in the nex loop fSize = len(data) #add the header onto the string. This will tell us when to stop reading. bytes = [ord(b) for b in struct.pack("i", fSize)] #now add the rest of the data onto the string. bytes += [ord(b) for b in data] #append each byte in the string to the array. Bitwise and each one to turn them into pure 1's and 0's for b in bytes: #append each bit to the array starting from the LSB to the MSB. Bitwise and it with a 1 to grab the original value for i in range(7, -1, -1): v.append((b >> i) & 0x1) return v # Assemble an array of bits into a binary file def assemble(v): bytes = "" length = len(v) for idx in range(0, len(v)//8): byte = 0 for i in range(0, 8): if (idx*8+i < length): byte = (byte<<1) + v[idx*8+i] bytes = bytes + chr(byte) size_of_file_to_hide = struct.unpack("i", bytes[:4])[0] # size_of_file_to_hide = struct.unpack("i", bytes[:4])[0] return bytes[4: size_of_file_to_hide + 4] # Set the i-th bit of v to x def set_bit(n, i, x): mask = 1 << i n &= ~mask if x: n |= mask return n # Embed payload file into LSB bits of an image def embed(hide_stuff_in_file, file_we_want_to_hide): # Process source image img = Image.open(hide_stuff_in_file) (width, height) = img.size conv = img.convert("RGBA").getdata() print("[*] Input image size: %dx%d pixels." % (width, height)) max_size = width*height*3.0/8/1024 # max file_we_want_to_hide size print("[*] Usable file_we_want_to_hide size: %.2f KB." % (max_size)) f = open(file_we_want_to_hide, "rb") data = f.read() f.close() print ("[+] file_we_want_to_hide size: %.3f KB " % (len(data)/1024.0)) # Encypt # cipher = AESCipher(password) # data_enc = cipher.encrypt(data) # Process data from file_we_want_to_hide file v = decompose(data) #v = decompose(data_enc) #add until divisible by 3 so we can divide the bits into rgb values while(len(v)%3): v.append(0) #turn the filesize into kb's size_of_file_to_hide = len(v)/8/1024.0 print("[+] Encrypted file_we_want_to_hide size: %.3f KB " % (size_of_file_to_hide)) #if the file we want to hide is larger than the max size plus stop reader header if (size_of_file_to_hide > max_size - 4): print("[-] Cannot embed. File too large") sys.exit() # Create output image file_with_hidden_image = Image.new('RGBA',(width, height)) data_of_file_with_hidden_image = file_with_hidden_image.getdata() idx = 0 for h in range(height): for w in range(width): (r, g, b, a) = conv.getpixel((w, h)) if idx < len(v): r = set_bit(r, 0, v[idx]) g = set_bit(g, 0, v[idx+1]) b = set_bit(b, 0, v[idx+2]) data_of_file_with_hidden_image.putpixel((w,h), (r, g, b, a)) idx = idx + 3 file_with_hidden_image.save("stego.png", "PNG") print("[+] %s embedded successfully!" % file_we_want_to_hide) # Extract data embedded into LSB of the input file def extract(stuff_is_hidden_in_this_file, revealed_image_file): # Process source image img = Image.open(stuff_is_hidden_in_this_file) (width, height) = img.size conv = img.convert("RGBA").getdata() print("[+] Image size: %dx%d pixels." % (width, height)) # Extract LSBs v = [] for h in range(height): for w in range(width): (r, g, b, a) = conv.getpixel((w, h)) v.append(r & 1) v.append(g & 1) v.append(b & 1) data_out = assemble(v) # set up a file to write output to. out_f = open(revealed_image_file, "wb") # Write inserted hidden bits to output file. out_f.write(data_out) out_f.close() print("[+] Written extracted data to %s." % revealed_image_file) def usage(progName): print("LSB steganogprahy. Hide files within least significant bits of image.\n") print("Usage:") print(" %s hide <file_we_want_to_hide_stuff_in> <file_we_want_to_hide>" % progName) print(" %s extract <file_with_hidden_image> <file_with_revealed_image>" % progName) sys.exit() if __name__ == "__main__": if len(sys.argv) < 3: usage(sys.argv[0]) if sys.argv[1] == "hide": embed(sys.argv[2], sys.argv[3]) elif sys.argv[1] == "extract": extract(sys.argv[2], sys.argv[3]) else: print("[-] Invalid operation specified")
from linked_list.linked_list import LinkedList, Node def test_import(): assert LinkedList # Code Challenge 06 # Add a node to the end of the linked list def test_append(): node = Node(0) link = LinkedList(node) link.insert_node(4) link.append(10) actual = str(link) expected = f'{{ 4 }} -> {{ 0 }} -> {{ 10 }} -> NULL' assert actual == expected # Can successfully add multiple nodes to the end of a linked list def test_multi_append(): link = LinkedList() link.insert_node(4) link.append(1) link.append(2) link.append(3) actual = str(link) expected = f'{{ 4 }} -> {{ 1 }} -> {{ 2 }} -> {{ 3 }} -> NULL' # Insert a node before a node located in the middle of a linked list def test_before(): node = Node(0) link = LinkedList(node) link.insert_node(4) link.append(10) link.insert_before(0, 5) actual = str(link) expected = f'{{ 4 }} -> {{ 5 }} -> {{ 0 }} -> {{ 10 }} -> NULL' assert actual == expected # Can successfully insert a node before the first node of a linked list def test_before_first(): node = Node(0) link = LinkedList(node) link.insert_node(4) link.append(10) link.insert_node(5) actual = str(link) expected = f'{{ 5 }} -> {{ 4 }} -> {{ 0 }} -> {{ 10 }} -> NULL' assert actual == expected # Can successfully insert after a node in the middle of the linked list def test_after(): node = Node(0) link = LinkedList(node) link.insert_node(4) link.append(10) link.insert_after(0, 5) actual = str(link) expected = f'{{ 4 }} -> {{ 0 }} -> {{ 5 }} -> {{ 10 }} -> NULL' assert actual == expected # Can successfully insert a node after the last node of the linked list def test_after_last(): node = Node(0) link = LinkedList(node) link.insert_node(4) link.append(10) link.insert_after(10, 5) actual = str(link) expected = f'{{ 4 }} -> {{ 0 }} -> {{ 10 }} -> {{ 5 }} -> NULL' assert actual == expected
# T.J. Flesher # Info 2900 # P. Phillips # Lab2A - Try Looping # Fahrenheit to Celsius or Celsius to Fahrenheit Converter #display instructions print("Enter 'C' to convert a Celsius temperature to Fahrenheit") print("or") print("Enter 'F' to convert a Fahrenheit temperature to Celsius") #get user input cF = input(":") while cF.upper() == "C" or cF.upper() == "F": temperature = float(input("Enter a temperature: ")) if cF.upper() == "C": cToF = (temperature * 9/5) + 32 print(temperature, "degrees Celsius is", cToF, "degrees Fahrenheit\n") elif cF.upper() == "F": fToC = (temperature - 32) * 9/5 print(temperature, "degrees Fahrenheit is", fToC, "degrees Celsius\n") print("Enter 'C' to convert a Celsius temperature to Fahrenheit") print("or") print("Enter 'F' to convert a Fahrenheit temperature to Celsius") #get user input cF = input(":") print("Start over -- and please select a 'C' or 'F' from the menu.")
#!/usr/bin/python ''' ############################################### Sockets File: server.py Usage: python server.py <port> Description: Starts a TCP connection to exchange messages with clients connected to the same port. Python modified from my IRC chatbot. C modified from my CS344 encryption/decryption program. ################################################# ''' import socket import sys #True to print test statements TEST = False #10 char client name + ": " + 500 char + terminator MAX_CHAR = 513 EXIT_MSG = "\quit" #Set server values ''' @connect(): tries to bind to a port and listen @get_message(): prints messages over socket @send_message(): sends messages over socket ''' class server: ''' @serverPort: port number @serverSocket: new TCP socket @connectionSocket: socket object for transmitting data @addr: client address ''' def __init__(self): #set 2nd argument as port self.serverPort = int(sys.argv[1]) self.serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.connectionSocket = None self.addr = None #define server functions ''' Startup - Bind to port and listen ''' def connect(self): try: #try to bind to the given port self.serverSocket.bind(('',self.serverPort)) #break if port is in use/illegal except Exception as e: if TEST: print(e) print("Port connection denied. Try another one.") sys.exit() #listen for messages on socket self.serverSocket.listen(1) self.connectionSocket, self.addr = self.serverSocket.accept() if TEST: print('Server connected on ' + socket.gethostname()) print('Listening for client on ' + str(self.serverPort)) ''' Receive Message @message: message from client ''' def get_message(self): while True: message = self.connectionSocket.recv(MAX_CHAR) print(message) #if client exits, wait for a new client to connect if (message[-5:] == EXIT_MSG): print("Client has quit. Waiting for new connection.") self.connectionSocket.close() self.connectionSocket, self.addr = self.serverSocket.accept() #otherwise we can respond to the message else: self.send_message() ''' Send Message @message: input to send to client ''' def send_message(self): message = raw_input('Server: ')[:MAX_CHAR] self.connectionSocket.send('Server: ' + message) #if our message is \quit, exit if (message[-5:] == EXIT_MSG): sys.exit() else: return def main(): chat_server = server() chat_server.connect() chat_server.get_message() main()
#Advent of Code '17 #Day 12b: Digital Plumber import re #read input file = open('input12.txt','r') input = file.read().split('\n') file.close() #list of which we have found to be connected connected = [] for x in range(0, len(input)): input[x] = input[x].split(' ') connected.append( False ) def checkGroup( startPosition ): totalConnections = 0 toAdd = [] toAdd.append(startPosition) while( len(toAdd) ): nextLine = toAdd.pop() if connected[nextLine] == False: connected[nextLine] = True totalConnections += 1 for value in range( 2, len(input[nextLine]) ): number = re.sub("[^0-9]","",input[nextLine][value]) toAdd.append( int(number) ) #checkGroup( 0 ) #find the next unconnected node def findUnconnected(): for x in range(0,len(input) ): if connected[x] == False: return x return -1 totalGroups = 0 nextStart = findUnconnected() while nextStart != -1: checkGroup( nextStart ) totalGroups += 1 nextStart = findUnconnected() print( "TotalGroups: " + str(totalGroups) )
#Advent of Code 18a # Duet file = open('input18.txt','r') #file = open('inputTest.txt','r') input = file.read().split('\n') file.close() registerLetters = 'abcdefghijklmnop' registerLetterLength = len( registerLetters ) registerValues = [] for letter in registerLetters: registerValues.append( 0 ) def getRegisterPosition(input): for x in range(0, registerLetterLength): if input == registerLetters[x]: return x print("register not found " +str(input)) return None def getRegisterValue(input): index = getRegisterPosition(input) if index != None : return registerValues[index] else: print("register value couldn't be recovered" + str(input) ) def setRegister(letter, value): index = getRegisterPosition(letter) registerValues[index] = value #get the value of an operand which could be a number or register name def getOperandValue( input ): if input.isnumeric() or input[0] == '-' : return int( input ) return int( getRegisterValue( input )) #apply instructions to registers running = True currentIndex = 0 op1 =0 op2 = 0 lastFrequency = -1 while running: #print( str(currentIndex) ) instruction = input[currentIndex].split() print( instruction ) jmp = 1 #value to jump..1 is default, ie just move to next instruction #process instructions command = instruction[0] op1 = instruction[1] if command == 'snd': lastFrequency = getOperandValue( op1 ) elif command == 'set': op2 = instruction[2] if op2.isnumeric(): newvalue = op2 else: newvalue = getRegisterValue(op2) setRegister( op1, newvalue ) elif command == 'add': op2 = instruction[2] setRegister( op1, ( getOperandValue( op1 ) + getOperandValue( op2 ) ) ) elif command == 'mul': op2 = instruction[2] setRegister( op1, ( getOperandValue( op1 ) * getOperandValue( op2 ) ) ) elif command == 'mod': op2 = instruction[2] setRegister( op1, ( getOperandValue( op1 ) % getOperandValue( op2 ) ) ) elif command == 'rcv': op1 = getOperandValue( op1 ) if op1 != 0: print( "last frequency: " + str(lastFrequency) ) break elif command == 'jgz': op1 = getOperandValue( op1 ) op2 = instruction[2] if op1 > 0: jmp = int(op2) #move instruction pointer currentIndex += jmp #finish if index is out of bounds if currentIndex >= len(input) or currentIndex < 0: running = False print( registerValues )
#Advent of Code '17 #Day 16b Permutation Promenade def getIndex( value ): for x in range(0,len(programs) ): if programs[x] == value: return x print("get Index found nothing") return -1 def spin( size ): global programs size = len(programs) - size programs = programs[size:] + programs[:size] def exchange( first, second ): global programs temp = programs[first] programs[first] = programs[second] programs[second] = temp def partner( first, second ): global programs indexOne = getIndex( first ) indexTwo = getIndex( second ) exchange( indexOne, indexTwo ) #programs = ['a','b','c','d','e'] startState = programs = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p'] programs = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p'] #spin(1) #exchange( 4, 3 ) #partner( 'e','b') #read input #file = open('inputTest.txt','r') file = open('input16.txt','r') input = file.read().split(',') file.close() def dance(): #parse the instructions for instruction in input: #print( instruction ) if instruction[0] == 's': #spin value = int ( instruction[1:] ) #print( str( value ) ) spin( value ) elif instruction[0] == 'x': #exchange #print('x') values = instruction[1:].split('/') exchange( int( values[0] ), int( values[1] ) ) #print( values ) elif instruction[0] == 'p': #partner #print('p') partner( instruction[1], instruction[3] ) def cookedDance(): global programs #seperate the cooked dance into one set of swaps for the positions (spin and exchange operation) programs = [ programs[14], programs[3],programs[15],programs[10],programs[12],programs[9],programs[13],programs[7],programs[2],programs[1],programs[6],programs[8],programs[0],programs[11],programs[4],programs[5] ] # and one set of swaps for the letters (partner operation) #programs = [ programs[], programs[],programs[],programs[],programs[],programs[],programs[],programs[],programs[],programs[],programs[],programs[],programs[],programs[],programs[],programs[] ] partner( 'a','n' ) partner( 'k','o' ) partner( 'b','l' ) partner( 'h','c' ) partner( 'd','p' ) partner( 'e','m' ) partner( 'g','i' ) partner( 'c','j' ) partner( 'c','g' ) partner( 'e','g' ) partner( 'b','g' ) partner( 'b','d' ) #combined position one doesn't work.. #programs = [ programs[10], programs[15],programs[1],programs[14],programs[3],programs[4],programs[0],programs[9],programs[7],programs[11],programs[8],programs[2],programs[13],programs[6],programs[12],programs[5] ] #import time #start_time = time.time() #for x in range( 0, 1000000000 ): #following loop shows the state repeats every 43 times.. ##for x in range( 0, 1000000 ): ## dance() ## if programs == startState: ## print( str(x+1) + ' iterations' ) ## break #repeats after 44 dances #print ( 1000000000 % 44 ) #so loop 32 times.. for x in range( 0, 32 ): dance() #print(time.time() - start_time ) #print( str(programs) ) result = "" for letter in programs: result += letter print( result ) # keafhbmgplionjcd
#Import dependencies import os import csv import pandas as pd #Bring in CSV file budget_data = os.path.join("budget_data_1.csv") csv_path = "raw_data/budget_data_1.csv" #Create dataframe pd.read_csv(csv_path) budget_df = pd.read_csv(csv_path) #Find total month count month_counts = budget_df["Date"].value_counts() total_months = month_counts.sum() #Find total revenue revenue_count = budget_df["Revenue"].sum() #Find min and max dates and revenues max_value = budget_df["Revenue"].max() max_date = budget_df["Date"].max() min_value = budget_df["Revenue"].max() min_date = budget_df["Date"].min() #Find avg change average_change = int((revenue_count)/(total_months)) #Print Results print("Financial Analysis") print("-------------------------") print("Total Months: "+ str(total_months)) print("Total Revenue: $" +str(revenue_count)) print("Average Revenue Change: $" + str(average_change)) print("Greatest Increase in Revenue: " +str(max_date) + " ($" + str(max_value)+ ")") print("Greatest Decrease in Revenue: " +str(min_date) + " ($" + str(min_value)+")") #Output to txt file #in terminal use: #python main.py > pybank.txt import subprocess with open("pybank.txt", "w+") as output: subprocess.call(["python", "./main.py"], stdout=output);
class Node: def __init__(self,data): self.data = data self.left = None self.right = None def inorderTraversal(root): if root: inorderTraversal(root.left) print(root.data, end = ' ') inorderTraversal(root.right) def morris_traversal(root): curr = root while curr: if curr.left is None: print(curr.data, end = ' ') curr = curr.right else: prev = curr.left while prev.right and prev.right != curr: prev = prev.right if prev.right is None: prev.right = curr curr = curr.left else: prev.right = None print(curr.data, end = ' ') curr = curr.right def KthLargest_(root,k): if root: dat = KthLargest_(root.right,k) if dat: return dat k[0] = k[0] - 1 if k[0] == 0: return root.data return KthLargest_(root.left, k) def kthLargest(root, k): return KthLargest_(root,[k]) root = Node(4) root.right = Node(5) root.left = Node(2) root.left.left = Node(1) root.left.right = Node(3) #morris_traversal(root) #inorderTraversal(root) print(kthLargest(root, 3))
#!/usr/bin/python import math class AKEncoderDecoder: def __init__(self): pass def ak_encoder(self, raw_string, pass_key): encoded_str = "" for char in raw_string: converted_char = ord(char) if converted_char >= 65 and converted_char <= 122: converted_char -= 64 else: converted_char += 58 converted_char = (converted_char + pass_key) * int(math.sqrt(pass_key)) encoded_str += str(converted_char)[::-1] encoded_str += 'O' return encoded_str def ak_decoder(self, encoded_str, pass_key): decoded_str = "" for number in encoded_str.split('O'): if number is not None and number != "": num = int(number[::-1]) num = (num / int(math.sqrt(pass_key))) - pass_key if num >= 1 and num <= 58: num += 64 else: num -= 58 decoded_str += chr(num) return decoded_str
#! /usr/bin/env python3 # **************************************************************************** # # # # ::: :::::::: # # generator.py :+: :+: :+: # # +:+ +:+ +:+ # # By: darodrig <[email protected]> +#+ +:+ +#+ # # +#+#+#+#+#+ +#+ # # Created: 2020/04/13 17:30:14 by darodrig #+# #+# # # Updated: 2020/04/13 17:30:14 by darodrig ### ########.fr # # # # **************************************************************************** # from random import shuffle def generator(text, sep=" ", option=None): try: words = text.split(sep) if option == "shuffle": shuffle(words) elif option == "ordered": words.sort(key=lambda words:words[0].swapcase()) elif option != None: raise SyntaxError for each in words: yield each except TypeError: print("First parameter must be a string") except SyntaxError: print("Not a valid option: \"shuffle\" or \"ordered\"") """ if __name__ == "__main__": text = "Le Lorem Ipsum est simplement du faux texte." for word in generator(text): print(word) """ """ if __name__ == "__main__": text = "Le Lorem Ipsum est simplement du faux texte." for word in generator(text, sep=" ", option="shuffle"): print(word) """ """ if __name__ == "__main__": text = "Le Lorem Ipsum est simplement du faux texte." for word in generator(text, sep=" ", option="ordered"): print(word) """
#! /usr/bin/env python3 from FileLoader import FileLoader import pandas as pd def howManyMedalsByCountry(df, name): country = df.loc[df['Team'] == name] dic = {} for index, row in country.iterrows(): dic[row['Year']] = {'G': 0, 'S': 0, 'B': 0} if row['Medal'] == 'Gold': dic[row['Year']]['G'] += 1 if row['Medal'] == 'Silver': dic[row['Year']]['S'] += 1 if row['Medal'] == 'Bronze': dic[row['Year']]['B'] += 1 return dic if __name__ == "__main__": df = FileLoader.load("../resources/athlete_events.csv") print(howManyMedalsByCountry(df, 'China'))
#! /usr/bin/env python3 import sys def main(): if len(sys.argv) < 2: return 0 list = sys.argv[:0:-1] for each in list: for letter in each[::-1]: if letter.isupper(): sys.stdout.write(letter.lower()) else: sys.stdout.write(letter.upper()) if each != sys.argv[1]: sys.stdout.write(' ') print("") if __name__ == "__main__": main()
#! /usr/bin/env python3 import pandas as pd class FileLoader: @staticmethod def load(path): data = pd.read_csv(path) print("Loading dataset of dimensions " + "{} x {}".format(data.shape[0], data.shape[1])) return data @staticmethod def display(df, n): if n > 0: print(df.head(n)) elif n < 0: print(df.tail(-n)) if __name__ == "__main__": data = FileLoader.load("../resources/athlete_events.csv") FileLoader.display(data, -4) FileLoader.display(data, 6)
# coding=utf-8 """ This module provides functions for working with and resolving data from a CSV file. """ import os import csv import itertools from cards.templatefield import TemplateField, fields from cards.markdown import markdown from cards.util import FileWrapper, lower_first_row from cards.warning import WarningDisplay, WarningContext from cards.constants import Columns, ColumnDescriptors class Column: """ Represents a column in a datasource. """ def __init__(self, name: str, content: str=None): self.name = name self.content = content def is_excluded(self) -> bool: """ Determine whether the column should be excluded. """ return (self.name.startswith('(') and self.name.endswith(')') if self.name is not None else False) def is_special(self) -> bool: """ Determine whether the column is to be treated as a special column. """ return (self.name.startswith('@') if self.name is not None else False) def is_back_only(self) -> bool: """ Determine whether the column is only intended for the back of a card. """ return (self.name.endswith(ColumnDescriptors.BACK_ONLY) if self.name is not None else False) def is_front_only(self) -> bool: """ Determine whether the column is only intended for the front of a card. """ return (self.name.endswith(ColumnDescriptors.FRONT_ONLY) if self.name is not None else False) class Row: """ Represents a row in a datasource. """ def __init__(self, data: dict, data_path: str=None, row_index: int=None, is_excluded: bool=False): self.data = data self.data_path = data_path self.row_index = row_index self.is_excluded = is_excluded def _usable_columns(self): return (column for column in (Column(name, content) for name, content in self.data.items()) if not column.is_excluded() and not column.is_special()) def _both_data(self) -> dict: """ Return a dict containing items fit for both the front- and back of a card. """ return {column.name: column.content for column in self._usable_columns() if not column.is_back_only() and not column.is_front_only()} def _front_data(self) -> dict: """ Return a dict containing only items fit for the front of a card. """ front_only_data = {column.name[:-len(ColumnDescriptors.FRONT_ONLY)]: column.content for column in self._usable_columns() if column.is_front_only()} return {**self._both_data(), **front_only_data} def _back_data(self) -> dict: """ Return a dict containing only items fit for the back of a card. """ back_only_data = {column.name[:-len(ColumnDescriptors.BACK_ONLY)]: column.content for column in self._usable_columns() if column.is_back_only()} return {**self._both_data(), **back_only_data} def front_row(self) -> 'Row': """ Return a Row containing only data fit for the front of a card. """ return Row(data=self._front_data(), data_path=self.data_path, row_index=self.row_index) def back_row(self) -> 'Row': """ Return a Row containing only data fit for the back of a card. """ return Row(data=self._back_data(), data_path=self.data_path, row_index=self.row_index) def is_prototype(self) -> bool: """ Determine whether the row is a prototype row. """ return self.data.get(Columns.COUNT, '').strip() == '~' def determine_count(self) -> (int, bool): """ Determine and return count value from the @count column in a row. """ # determine how many instances of this card to generate # (defaults to a single instance if not specified) count = self.data.get(Columns.COUNT, '1').strip() was_indeterminable = False if len(count) > 0: # the count column has content, so attempt to parse it try: count = int(count) except ValueError: # count could not be determined, so default to skip this card count = 0 was_indeterminable = True else: # the count column did not have content, so default count to 1 count = 1 if count < 0: count = 0 was_indeterminable = True return count, was_indeterminable @staticmethod def is_excluded(row_string: str) -> bool: """ Determine if a line in a file should be excluded. """ return row_string.strip().startswith('#') class InvalidColumnError: # pylint: disable=too-few-public-methods """ Provides additional information about invalid data columns. """ def __init__(self, column_name: str, reason: str): self.column_name = column_name self.reason = reason def __str__(self): return '\'{0}\' {1}'.format(self.column_name, self.reason) def __repr__(self): return self.__str__() class ColumnResolutionData: # pylint: disable=too-few-public-methods """ Provides additional data about the resolution of a data column. """ def __init__(self, column_references: set=(), definition_references: set=()): self.column_references = column_references self.definition_references = definition_references def get_invalid_columns(column_names: list) -> list: """ Return a list of errors for each invalid column. """ return [InvalidColumnError(column_name, reason='contains whitespace (should be an underscore)') for column_name in column_names if ' ' in column_name] def size_identifier_from_columns(column_names: list) -> (str, list): """ Parse and determine card size identifier from a list of column names. """ size_identifier = None parsed_column_names = column_names for column_index, column_name in enumerate(column_names): # look for the '@template' column if column_name.startswith(Columns.TEMPLATE): # and isn't just '@template-back' if column_name != Columns.TEMPLATE_BACK: # then determine preferred card size, if any. # it should look like e.g. '@template:standard' size_index = column_name.rfind(':') if size_index != -1: # a size identifier was found- so isolate it from the rest of the column size_identifier = column_name[size_index + 1:].strip() # and remove it so we have a clean column name (important for any column # references to resolve properly) parsed_column_names[column_index] = column_name[:size_index].strip() break return size_identifier, parsed_column_names def get_row(row_number: int, referencing_row: Row, referencing_column: Column) -> Row: """ Return the row at a row index. """ context = os.path.basename(referencing_row.data_path) from_row_index = referencing_row.row_index from_column_name = referencing_column.name # when looking at rows in a CSV they are not zero-based, and the first row # is always the headers, which makes the first row of actual data (that # you see) appear visually at row #2, like for example: # #1 'rank,title' # #2 '2,My Card' # #2 '4,My Other Card' # however, of course, when reading from the file, the first row is # actually at index 0, so we have to take this into account # this logic essentially makes '#0' and '#1' invalid row numbers line_number = row_number - 2 if line_number < 0: if row_number == 1: # special case- user probably meant the first data row (which is always #2) WarningDisplay.referencing_row_header( WarningContext(context, row_index=from_row_index, column=from_column_name)) else: WarningDisplay.referencing_row_out_of_bounds( WarningContext(context, row_index=from_row_index, column=from_column_name), referenced_row_number=row_number) return None with open(referencing_row.data_path) as data_file_raw: data_file = FileWrapper(data_file_raw) # read data appropriately data = csv.DictReader(lower_first_row(data_file)) try: # then read rows until reaching the target row_number row_data = next(itertools.islice(data, line_number, None)) except StopIteration: WarningDisplay.referencing_row_out_of_bounds( WarningContext(context, row_index=from_row_index, column=from_column_name), referenced_row_number=row_number) else: if Row.is_excluded(data_file.raw_line): WarningDisplay.referencing_excluded_row( WarningContext(context, row_index=from_row_index, column=from_column_name), referenced_row_number=row_number) else: # create a new row with the data at the referenced row return Row(row_data, referencing_row.data_path) def get_row_reference(field: TemplateField, in_reference_row: Row, in_reference_column: Column) -> (str, Row, bool): """ Return the column and row of data that a template field references. If a field like 'title #6' is passed, then return 'title' and row number 6. If it is not a reference, return the row passed. """ # set default field name and row to whatever is passed reference_column = None reference_row = in_reference_row is_invalid_reference = False if reference_row.data_path is not None and len(reference_row.data_path) > 0: # a data path has been supplied, so we can attempt determining whether this # field is a reference to a column in another row if field.has_row_reference(): # it might be, because there's multiple components in the field name # we've determined that this is probably a reference to another row # so get the row number row_number = field.context[1:] try: row_number = int(row_number) except ValueError: row_number = None if row_number is not None: if row_number == reference_row.row_index: # the row number would lead to the same row that was passed, so we clean up # the field by removing the number reference, but otherwise leave the row as is return field.name, reference_row, is_invalid_reference reference_row = get_row(row_number, reference_row, in_reference_column) if reference_row is None: is_invalid_reference = True else: reference_row.row_index = row_number # however, we don't want to provide every column found in this row; # we *only* want the columns also available in the originating row reference_row.data = {column: column_content for column, column_content in reference_row.data.items() if column in in_reference_row.data} reference_column = field.name return reference_column, reference_row, is_invalid_reference def resolve_column(column: Column, in_row: Row, definitions: dict, content_resolver=None, field_resolver=None) -> (str, ColumnResolutionData): """ Return the content of a column by recursively resolving any fields within. """ column_references = [] definition_references = [] is_resolving_definition = in_row.data == definitions resolved_column_content = column.content for reference_field in fields(resolved_column_content): # determine whether this field is a row reference reference_column, reference_row, is_invalid_reference = get_row_reference( reference_field, in_reference_row=in_row, in_reference_column=column) if is_invalid_reference: # it was a row reference, but the reference was invalid- so we gotta move on continue if reference_column is None: # it was not a row reference reference_column = reference_field.inner_content # determine if the field occurs as a definition is_definition = reference_column in definitions # determine if the field occurs as a column in the current row- note that if # the current row is actually the definitions, then it actually *is* a column, # but it should not be treated as such is_column = reference_column in reference_row.data and not is_resolving_definition if not is_column and not is_definition: # the field is not a reference that can be resolved right now, so skip it # (it might be an image reference, an include field or similar) continue context = (os.path.basename(reference_row.data_path) if reference_row.data_path is not None else ('definitions' if is_resolving_definition else '')) # this field refers to the column in the same row that is already being resolved; # i.e. an infinite cycle (if it was another row it might not be infinite) is_infinite_column_ref = reference_column == column.name and reference_row is in_row # this definition field refers to itself; also leading to an infinite cycle is_infinite_definition_ref = (is_infinite_column_ref and is_definition and not is_column) if is_infinite_definition_ref: WarningDisplay.unresolved_infinite_definition_reference( WarningContext(context, row_index=reference_row.row_index, column=column.name), reference_field.inner_content) continue if is_infinite_column_ref: WarningDisplay.unresolved_infinite_column_reference( WarningContext(context, row_index=reference_row.row_index, column=column.name), reference_field.inner_content) continue # only resolve further if it would not lead to an infinite cycle use_column = is_column and not is_infinite_column_ref # however, the field might ambiguously refer to a definition too, # so if this could be resolved, use the definition value instead use_definition = (is_definition and not use_column and not is_infinite_definition_ref) if not use_column and not use_definition: # could not resolve this field at all WarningDisplay.unresolved_reference( WarningContext(context, row_index=reference_row.row_index, column=column.name), reference_field.inner_content) continue if use_column: # prioritize the column reference by resolving it first, # even if it could also be a definition instead (but warn about that later) column_reference_content, resolution_data = get_column_contentd( reference_column, reference_row, definitions, content_resolver, field_resolver) elif use_definition: # resolve the definition reference, keeping track of any discovered references column_reference_content, resolution_data = get_definition_contentd( definition=reference_column, in_definitions=definitions, content_resolver=content_resolver, field_resolver=field_resolver) column_references.extend(list(resolution_data.column_references)) definition_references.extend(list(resolution_data.definition_references)) occurences = 0 if field_resolver is not None: resolved_column_content, occurences = field_resolver( reference_field.inner_content, column_reference_content, resolved_column_content) if occurences > 0: if use_column: column_references.append(reference_column) elif use_definition: definition_references.append(reference_column) if is_definition and is_column and not is_resolving_definition: # the reference could point to both a column and a definition if use_column: # the column data was preferred over the definition data WarningDisplay.ambiguous_reference_used_column( WarningContext(context), reference_column, column_reference_content) elif use_definition: # the definition data was preferred over the column data; # this is likely because the column reference was an infinite reference # don't inform about that detail, but do warn that the definition was used WarningDisplay.ambiguous_reference_used_definition( WarningContext(context), reference_column, column_reference_content) resolution_data = ColumnResolutionData( set(column_references), set(definition_references)) return resolved_column_content, resolution_data def get_column_contentd(column: str, in_row: Row, definitions: dict, content_resolver=None, field_resolver=None) -> (str, ColumnResolutionData): """ Return the content of a column, recursively resolving any column/definition references. """ # get the raw content of the column, optionally assigning a default value column_content = in_row.data.get(column, None) if column_content is None: # return early with default content return column_content, ColumnResolutionData() # strip excess whitespace column_content = column_content.strip() if len(column_content) == 0: # return early with default content return column_content, ColumnResolutionData() if content_resolver is not None: # the content resolver typically fills any include, date or empty fields column_content = content_resolver(column_content, in_row.data_path) resolved_column_content, resolution_data = resolve_column( Column(column, column_content), in_row, definitions, content_resolver, field_resolver) # transform content to html using any applied markdown formatting resolved_column_content = markdown(resolved_column_content) return resolved_column_content, resolution_data def get_definition_contentd(definition: str, in_definitions: dict, content_resolver=None, field_resolver=None) -> (str, ColumnResolutionData): """ Return the content of a definition, recursively resolving any references. """ definition_content, resolution_data = get_column_contentd( column=definition, in_row=Row(data=in_definitions), definitions=in_definitions, content_resolver=content_resolver, field_resolver=field_resolver) return definition_content, resolution_data def get_definition_content(definition: str, in_definitions: dict, content_resolver=None, field_resolver=None) -> str: """ Return the content of a definition, recursively resolving any references. """ return get_definition_contentd( definition, in_definitions, content_resolver, field_resolver)[0]
""" Write two Python functions to find the minimum number in a list. The first function should compare each number to every other number on the list. O(n^2). The second function should be linear O(n). """ from time import time from random import randint def minNum1(nums): start = time() minNum = nums[0] for num in nums: for num in nums: if num < minNum: minNum = num end = time() return minNum, end - start def minNum2(nums): start = time() minNum = nums[0] for num in nums: if num < minNum: minNum = num end = time() return minNum, end - start if __name__ == '__main__': print('This program is being run by itself') else: print('I am being imported from another module') nums = [] for i in range(10000): nums.append(randint(1, 100)) print(minNum2(nums)) print(minNum1(nums))
""" Write recursive algorithm that rolves the Tower of Hanoi problem. Explanation: The key to the simplicity of this algorithm is that we make two different recursive calls. The first recursive call moves all but the bottom disk on the initial tower to an intermediate pole. The next line simply moves the bottom disk to its final resting place. Then the second recursive call moves the tower from the intermediate pole on top of the largest disk. The base case is detected when the tower height is 0, there is no task to be completed so move_tower simply returns. """ def move_tower(height, from_pole, to_pole, with_pole): if height >= 1: move_tower(height - 1, from_pole, with_pole, to_pole) move_disk(from_pole, to_pole) move_tower(height - 1, with_pole, to_pole, from_pole) def move_disk(fp, tp): print("moving disk from", fp, "to", tp) def main(): move_tower(4, "A", "C", "B") if __name__ == "__main__": main()
import time def sumOfN2(n): start = time.time() theSum = 0 for i in range(1, n+1): theSum = theSum + i end = time.time() print(theSum, end - start) return theSum, end - start def sumOfN3(n): start = time.time() theSum = (n * (n+1)) / 2 end = time.time() return theSum, end - start if __name__ == '__main__': print('This program is being run by itself') else: print('I am being imported from another module')
"""Implementation of palindrom checker.""" from deque import Deque def check(expr): chars = Deque() for char in expr: chars.addRear(char) while chars.size() > 1: char_one = chars.removeFront() char_two = chars.removeRear() if char_one != char_two: return False return True def main(): print(check("radar")) print(check("toot")) print(check("racecar")) print(check("moon")) if __name__ == "__main__": main()
class PrioQueue: def __init__(self, Listlen): self.data = [] for i in range(Listlen): self.data.append(-1) self.Length = 0 self.Front = -1 self.Back = -1 def add(entry): if self.Back == -1: self.data[0] = entry self.Back = 0 else: newlist = [] for j in range(self.Length): if self.data[j]>=entry: newlist.append(j) elif self.data[j]<=entry: newlist.append(entry) while j<self.Length: newlist.append(self.data[j]) j+=1 self.data = templist if Front == -1: Front = 0 x = PrioQueue(2) print(x.Back) x.add() print(x.data)
class MyClass: """A simple example class""" i = 12345 def __init__(self): self.new = 7 def f(self): return 'hello world' sample = MyClass() sample.i = "hello" print(sample.new)
class Curso: def __init__(self,IdCurso,Descripcion,IdEmpleado): self.IdCurso = IdCurso self.Descripcion = Descripcion self.IdEmpleado = IdEmpleado def Guardar(P_Id,P_Descripcion,P_IdEmpleado): curso = Curso(P_Id,P_Descripcion,P_IdEmpleado) lstCurso = [] lstCurso.append(P_Id) lstCurso.append(P_Descripcion) lstCurso.append(P_IdEmpleado) return lstCurso def Consultar_Todo(P_tplCurso): print("| Id_Curso | Descripción | Id_Empleado 1") for curso in range(0,len(P_tplCurso)): print(f"| {P_tplCurso[curso][0]} | {P_tplCurso[curso][1]} | {P_tplCurso[curso][2]} |") def Consultar_Por_Id(P_tplCurso,P_Id): print("| Id_Curso | Descripción | Id_Empleado 1") for curso in range(0,len(P_tplCurso)): if P_tplCurso[curso][0] == P_Id: print(f"| {P_tplCurso[curso][0]} | {P_tplCurso[curso][1]} | {P_tplCurso[curso][2]} |")