text
stringlengths
37
1.41M
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: rem = 0 head = None tail = None while l1 is not None...
def find_solution(digits): c = 0 output = "" for d_str in digits: d = int(d_str) while c < d: output += "(" c += 1 while c > d: output += ")" c -= 1 output += d_str while c > 0: output += ")" c -= 1 re...
#!/usr/bin/python # -*- coding: utf-8 -*- def power(base, exponent): if exponent == 0: return 1 total = power(base, exponent / 2) if exponent % 2 == 0: return total ** 2 else: return base * total ** 2 if exponent > 0 else (total ** 2) / base def merge_sort(array): array_...
numbers = [1, 2, 3, 4, 5, 6, 7] print(numbers) # menambah numbers.append(99) print(numbers) # menyisipkan numbers.insert(2, 100) print(numbers) # menghapus sesuai index numbers.pop(1) print(numbers) # menghpaus sesuai item/elemet numbers.remove(7) print(numbers) # sorting numbers.sort() print(numbers)
index = 1 # while index <= 5: # print("Jalan") # index += 1 # print("Finish") while index <= 5: print("*" * index) index += 1 print("Finish")
# Spesifik Exception try: level = int(input("Masukkan level : ")) level = level / 0 print(level) except ZeroDivisionError: print("Error tidak bisa dibagi 0") except ValueError: print("Inputan anda bukan angka") # General Exception try: level = int(input("Masukkan level : ")) level = lev...
# number int price = 100000 print(price) # number float discount = 0.5 print(discount) # string price = "Atas" print(price) price = price * discount print(price) product_name = "Pull & Bear" print(product_name) # boolean is_discount = True print(is_discount)
sum = 0 for i in range (0,1000): if i % 3 ==0 or i % 5 == 0: sum = sum + i print (sum)
from sklearn import tree from sklearn import preprocessing file = open("training.txt") data = [] target = [] print "segregating data and splitting the test and train data..." for row in open("training.txt"): rowdata = row.split() labelEncoder = preprocessing.LabelEncoder() #using labelEncoder because the Dec...
class Solution: def validPalindrome(self, s: str) -> bool: if not s: return False left , right = 0, len(s) - 1 while left < right: if s[left] != s[right]: return self.isPalindrome(s[left+1:right+1]) or self.isPalindrome(s[left:right]) ...
# -*- coding: utf-8 -*- """ Created on Sat Aug 24 12:45:52 2019 @author: ASUS """ #**************WELCOME TO BATTLESHIP GAME**************** # This game will generate a single ship. # Battlefield size is input by the user and will be created accordingly. # Coordinates of the battlefield starts from (0,0) so th...
#-*-coding:utf-8-*- ''' Created on 20161119 @author: Ѧΰ ''' # for x in "abcd": # print x,"Hello world" # # fruits=["banana","apple","mango"] # for index in range(len(fruits)): # print "Current fruit:",fruits[index] # # print "Goodbye" # a=0 # for x in range(1,101): # a+=x # print a # # ...
def main()->None: locatie = input("Locatie:\r\n") rondetijd = float(input("Rondetijd in minuten:\r\n")) afstand = float(input("Afstand in km:\r\n")) # Tijd in minuten, maximale race duur tijds_limiet = 120 # Afstandslimiet in kilometers afstands_limiet = 305 # Aantal verreden rondes ...
import string def coordinates(inp: str)->tuple: """ Extracts coordinates from positions in Chess :param inp: Coordinates (D4) :return: X & Y Coordinates """ x = int(inp[1]) y = int(string.ascii_lowercase.index(inp[0])) + 1 return x, y def is_valid_move(set1: tuple, set2: tuple)->boo...
"""This file contains code used in "Think Stats", by Allen B. Downey, available from greenteapress.com Copyright 2013 Allen B. Downey License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html """ """This file contains a partial solution to a problem from MacKay, "Information Theory, Inference, and Learning Algorithms."...
class Card: SUIT = ['Clubs', 'Diamonds', 'Hearts', 'Spades'] VALUE = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'] def __init__(self, value=0, suit=0): self.value = value self.suit = suit def __str__(self): return '{0} of {1}'.format(Card.V...
class Pai(): def __init__(self): self.nome = '' self.idade = 0 self.nacionalidade = 'brasileira' def falar_portugues(self): print('Olá!. Como vai você?') class Mae(): def __init__(self): self.nome = '' self.idade = 0 def falar_fr...
#Funcoes e variaveis #1 - Lista de compras carrinho = [] #2 - Criar funcao para adicionar itens def adiciona_item(valor): carrinho.append(valor) #2 - funcao total carrinho def total_carrinho(lista_compras): for intem in lista_compras: soma += soma retorn soma
jogadores = 5 cadeira = 4 while jogadores > 1: print('Tocar música') print('Parou') print('Jogadores se movimentam') jogadores = jogadores - 1 cadeiras = +1 print('Fim de jogo') print('Cadeiras', cadeiras) print('Jogadores', jogadores) exit() num = 10 rodada = 1 while (rodada <=10): pr...
"""this is the main module for the routing algorithm project""" from argparse import ArgumentParser import socket from threading import Thread, Lock import time import pickle import math # global objects SOCKET1 = socket.socket(type=socket.SOCK_DGRAM) PRINT_LOCK = Lock() # each neighbor is stored as a list with route...
#day4 homework which is flow control running 99 mul #way 1 使用for...in循环打印出九九乘法表 print('**打印九九乘法表**') for i in range(1,10): for n in range(1,i+1): print(f'{i} * {n} =',n*i,end='\t') print() #way 1 使用for...in循环打印出九九乘法表,把偶数行去掉 print('**×打印九九乘法表,奇数行×**') for x in range(1,10,2): for m in range(1,x+1): ...
import json def read(str): try: obj = json.loads(str) for (k, v) in obj.items(): print('key:' + k, ' value:' + v) return obj except BaseException as e: print(e) def write(obj): str = json.dumps(obj) print(str) return str def write_to_file(file, obj):...
""" File: draw_line Name: Ben Huang ------------------------- TODO: Clicking the mouse to create 1st circle following by clicking the mouse again to create a line while the 1st disappear. The same pattern happens again while clicking again. """ from PIL.XVThumbImagePlugin import b from campy.graphics.gobjects i...
x = int(input("Masukkan Bilangan ===")) if x % 2 == 0: print("Bilangan {} adalah bilangan genap".format(x)) else: print("%i adalah bilangan ganjil".format(x)) # x.append(int(x)) # print(x)
#Programming Assignment II - WSD #Team Members: Neha Patil, Neha Nagarkar #Team Name: Power Team #Class: AIT 690 # Date: April 4, 2019 #This is scorer file used for finding accurracy and confusion matrix import pandas as pd import re import sys argList = sys.argv #To run the scorer program from command line - provid...
# this game is called the room from sys import exit import random def door2_room1(): print "You enter through door #2 and find yourself in a room with two doors" print "Above door #1 is a riddle with a combination to unlock the door" print "Door #2 has no riddle and is unlocked, but a horrid stench seeps through t...
""" #LZW加密算法实现 from LZW_Coding import LZW_coding address_in="LZW_in.txt" address_out="D:/PyQt/信息论课设/指定目录打开.txt" S_out = open(address_out,"r+") #用于保存结果 k=LZW_coding k.lzw_in(k,address_in,address_out) #str_x=list(map(str,x)) #S_out.writelines([line + '\n' for line in str_x]) #字符串定义 a=[[0.0 for m in range(10)] for n ...
# Created on Sun Dec 03 # Author: 10358601 Izabela Tyrna ###This is a program that test calcualtor_list.py import unittest from calculator_list import Calculator class TestCalculator(unittest.TestCase): def setUp(self): self.calc = Calculator() def test_calculator_add_method_returns_...
import sys import os class ValidAccounts(): # Take in text file, generate dictonary with valid accounts, functions that # add, remove and check for elements of the dictonary def __init__(self, file_path): self.valid_account_list = {} with open(file_path) as fp: line = fp.readl...
def SearchForMacAddress(): UserInput = input("Enter part of the MAC address you want to search for: ") CheckUserInput(UserInput) SearchResults = "\n".join(x for x in DataList if UserInput in x) SearchArray = SearchResults.splitlines() print("*"*70) if len(SearchArray) == 1: Result = Sear...
#!/usr/bin/python #Author: Johnathan Pfluger #Date: 22 February 2015 #Purpose: Implement PBC, Tabulate Energies, and Caculate Hamiltonian #Edited by Cyrus Ramavarapu 28 February 2015 #Edited by Cyrus Ramavarapu 1 March 2015 #Edited by Cyrus Ramavarapu 2 March 2015 - Simplified Hamiltonian Calculation import math ...
# Python Expressions Exercices (these should be practised on Python console, but this time they will be here) # import math module import math # Exercise 1 var = 5280 * 23 print(var) # Exercise 2 var = ((10*60*60)+(35*60)+24) print(var) # Exercise 3 var = (10*2)+(2*15) print(var) # Exercise 4 var = (10*25) print(...
def getMaxPrime(num): i = 2 while i*i < num: while num % i == 0: print(i) num = num / i i = i + 1 return num print (getMaxPrime(600851475143))
# -*- coding: utf-8 -*- #o tabuleiro é uma matriz de 12X18 em que 0 representa um espaço livre, 1 representa um espaço com #pedaços de tetrominos e -1 representa as bordas do tabuleiro from tetrominos import Tetromino class Tabuleiro: def __init__(self): self.matriz = [[0 for coluna in range(12)] for li...
from datetime import * import time print("UTC Now: ", datetime.utcnow()) print("UTC Now to Time: ", datetime.utcnow().time()) print("UTC Now to Timestamp: ", time.mktime(datetime.utcnow().timetuple())) print("UTC from Timestamp: ", datetime.fromtimestamp(time.mktime(datetime.utcnow().timetuple()))) print("Now: ", dat...
def sentence_reversal(s): words_list = [] spaces = [' '] length = len(s) i = 0 while i < length: if s[i] not in spaces: word_start = i while i < length and s[i] not in spaces: i += 1 words_list.append(s[word_start:i]) i += 1 ...
# This is a simple game which displays a clock which starts # when the player hits the start button. Points are awarded if # the player stops the watch on any integer number of seconds, # that is when the tenths digits is equal to zero # The score is displayed as a fraction on the canvas. import simplegui # Define ...
# Enter your code here. Read input from STDIN. Print output to STDOUT s = raw_input() first = False sec = False third = False fourth = False fifth = False for ch in s: if ch.isalnum(): first = True if ch.isalpha(): sec = True if ch.isdigit(): third = True if ch.islower(): ...
from __future__ import print_function N = int(raw_input()) for x in range(1, N+1): print (x, sep=' ', end='') # Enter your code here. Read input from STDIN. Print output to STDOUT #mylist = [x for x in range(1,N+1)] #F = map(print, mylist)
# ****************************** Developer Notes ****************************** # This is the main entry point for this application. You will run this script # to start the program. # ***************************************************************************** from DataCollector import DataCollector def main(): i...
def count_down(name, start): for i in range(int(start), 0, -1): print(name, i) print(name, "DONE!")
file = open('Email.txt') file_write_to = open('writefile.txt','w') for line in file: print(line.strip()) file_write_to.write(line)
n = input()[-1] result = 'hon' if n == '3': result = 'bon' elif n == '0' or n == '1' or n == '6' or n == '8': result = "pon" print(result)
#!/usr/bin/env python from __future__ import division # unit converters def kg2lb(kgs): weight = round(kgs * 2.20462262185, 4) return weight def lb2kg(lbs): weight = round(lbs * 0.45359237, 4) return weight def in2cm(inches): height = inches * 2.54 return height def pct(num): percent = num/100 return perce...
'''Assignment 4 (Version 1.2) Please add your code where indicated. You may conduct a superficial test of your code by executing this file in a python interpreter. The documentation strings ("docstrings") for each function tells you what the function should accomplish. If docstrings are unfamiliar to you, consult the...
num = int(input("Enter the value of n: ")) hold = num sum = 0 if num <= 0: print("Enter a whole positive number!") else: while num > 0: sum = sum + num num = num - 1; # displaying output print("Sum of first", hold, "natural numbers is: ", sum)
import scrabble letters = "abcdefghijklmnopqrstquwxyz" vowel = "aeiou" def has_all_vowels(word): for vowel in vowels: if vowel not in word: return False return True counter = 0 for word in scrabble.wordlist: if has_all_vowels(word): counter = counter + 1 print(word) pr...
""" ------------------------------------------------------------------------------- Name: Coin.py Purpose: Simulates a coin flip Author: Fabroa.E Created: 22/03/2019 ------------------------------------------------------------------------------ """ import random class Coin(object): """ Models a coin as a...
class Decimal: def __init__(self,number,place): self.number = number self.place = place def __repr__(self): return "%.{}f".format(self.place) % self.number class Currency(Decimal): def __init__(self,symbol,number,place): super().__init__(number, place) self.symbol =...
# **********---- Syntax Errors # Syntax errors are those when you do not write the statement correctly, they are also known as parsing errors, # These are like spelling mistakes in your program # why and how to use Exceptions in your program # To make sure your program or the software not to crash in the middle when ...
########## Decision Making # Most Important Thing to Remember in Python "INDENTATION", if you miss the indentation your code will not work. # Instead of { } as block, Indentation keeps your code aligned and maintains the block # Decision Making, we are going to learn if, if-else, else-if # lets declare ...
# **********---- Class Definition Syntax # A class is like a function but at completely very high level functionality # Classes are used to code for properties and functionalities for an object. # Class itself will not do any work, we will create objects with all the defined properties and functionalities # so the ob...
x,y=input().split() y=int(y) for i in range(y): b=(''.join(reversed(x))) print(b[i],end="")
#-*-coding:utf-8-*- # author: wangjinqi # date:2019-06-10 class Compare: def is_contain_str(self,str_one,str_two): '''判断一个字符串是否在另一个字符串中 str_one--被判断的字符串 str_two--作为比较的字符串 ''' flag = None if str_one in str_two: flag=True else: flag=Fals...
myStr="Hello World" myStr2="Hello,World" #Ayuda de cada tipo de dato con funciones #print(dir(myStr)) print(myStr) #concatenar print(myStr + "World") print(f"{myStr}World") # Concatenar pero de otra forma print("{0}World".format(myStr)) # Concatenar pero poniendo donde las llaves en la posicione n este caso 0 la pa...
# -*- coding: utf-8 -*- import math import re class ArrayProcessor: @staticmethod def SortAndFilter(array): new = [] for el in array: if (int(el/10) > 0)and(int(el/10 < 10)): new.append(el) new.sort() return new class Rectangle: def __init__(...
from scrapy import Selector # Create a Selector selecting html as the HTML document sel = Selector( text = html ) # Create a SelectorList of all div elements in the HTML document divs = sel.xpath( '//div' ) #Referring to the divs variable you created in the previous exercise, choose the incorrect response. """The c...
#maps li = [1, 9, 8, 4] print [elem * 2 for elem in li] # [2, 18, 16, 8] .... badass print li # [1, 9, 8, 4] #keys, values, items paramage = {'a':'dude', 'b':'no wai', 'c':'neato'} paramage.keys() # ['a','b','c'] paramage.values() # ['dude','no wai', 'neato'] paramage.items() # [('a','dude'), ('b','no wai'), ('c','ne...
from day_2 import DaysToThirty,Camp def ChooseFunction(): Choose = input(" witch function would you like") if Choose == "Camp": Camp() elif Choose == "DaysToThirty": DaysToThirty() else: print("wrong") ChooseFunction() ChooseFunction()
from arithmetic2 import add, subtract, multiply, divide, square, cube, power, mod while True:#repeat forever unless unser enters 'q': try: # read input calculation=raw_input("Enter your calculation; example format + 2 1; or press 'q' to quit. ") # tokenize input token=calculation.spl...
import pygame class Crosshair(object): def __init__(self, rotationCenterX, rotationCenterY): self.rotationCenterX = rotationCenterX # Center of the player X self.rotationCenterY = rotationCenterY # Center of the player Y self.distanceToPlayer = 50 # Radius of the circle between the play...
from abc import ABC, abstractmethod class BaseHandler(ABC): """ A base alert handler: a class that defines methods for sending alerts as a result of simulation events being detected. """ _attr_envvar_map = {} # A dictionary of argument names to environment variables @abstractmethod def ...
# https://stackoverflow.com/a/25307981/2142315 def LineIterator(P1, P2, img): """ Produces and array that consists of the coordinates and intensities of each pixel in a line between two points Parameters: -P1: a numpy array that consists of the coordinate of the first point (x,y) -P2: a num...
""" Names: Joachim Isaac & Micah-Lyn Scotland Course: CS 2433-101, Fall 19, Dr. Stringfellow. Purpose: To implement overloaded operators in Python; to implement several copy constructors and a toString method in Python. Also to extend the class. To perform software development with others. What we learned: --> you ca...
import csv import collections with open('faculty.csv') as f: reader = csv.reader(f) data = list(reader) emails = [i[3] for i in data if i[3] != data[0][3]] emailfile = open('emails.csv', 'wb') writer = csv.writer(emailfile) for i in emails: writer.writerow([i]) emailfile.close()
from typing import List def pacificAtlantic(heights: List[List[int]]) -> List[List[int]]: # This one's a DP problem visited = {x:set() for x in range(len(heights))} def bfs(x, y): res = {""} visited[x].add(y) if x == 0 or y == 0: res.add("P") if x == len(heig...
def func(nums): hold = set() for i in range(len(nums)): if i in hold: return [nums[i], nums[i] + 1] hold.add(nums[i]) print(func([2,2]))
def find_non_duplicate(A): xor_val = 0 for i in A: xor_val ^= i return xor_val print(find_non_duplicate([2,1,1,2,3,4,4,5,6,7,7,6,5]))
''' The most primitve method we have studied so far, the brute force approach This one is a less clever version of kadanes, all we do is iterate through every starting point, and see if the subarray from the start, to the end is the largest ''' def brute_force(A): ''' :param A: list passing into our functio...
def subarraySum(nums,k): # All prefixes we have seen so far. So, if we are total - k elements off, this denotes how many ways # We can cut off that difference to create our contiguous subarray prefixes = {0: 1} total = 0 amount = 0 for num in nums: # Keep a running count (THIS IS THE PRE...
class ESG: def __init__(self): self.values = { 'F': 0, 'CC': 1, 'CCC': 2, 'B': 3, 'BB': 4, 'BBB': 5, 'A': 6, 'AA': 7, 'AAA': 8, 'F': 9 } self.graph = dict() def inser...
import math from typing import List def coinChange(coins: List[int], amount: int) -> int: denominations = dict() min_amount = math.inf def merge_amounts(A): hold = dict() for j in A.keys(): for i in denominations.keys(): if abs(i-j) >= 0: if...
def round_nearest_05(x): ''' Rounds to nearest 0.05. This is optimized to produce accurate precision (see test file). ''' temp = 0.05 i = 0 while temp < 1: x *= 10 temp *= 10 i += 1 return (round(x / temp) * temp) / (100)
class organism(object): def __init__(self): super(organism,self).__init__() self.carbon=True self.oxygen=True def rot(self): print "It rots" class animal(organism): def __init__(self): super(animal,self).__init__() self.O2=True def shape(self): ...
#this file is to learn how to use the class Movie we created to work with this import database import fresh_tomatoes toy_story = database.Movie("Toy Story", "A story of a boy and his toys that come to life.", "https://upload.wikimedia.org/wikipedia/en/1/13/Toy_Story.jpg", "https://www.youtube.com/watch?v=KYz2wyB...
""" Patinya Sribrowornnara 19:22 4/6/2564 Exercise 5 : ปฏิบัติการพัฒนาโปรแกรมที่ใช้งานได้จริง และ ข้อมูล 2.ตั้งชื่อไฟล์ Exercise5_2_ชื่อ_ตัวอักษรแรกของนามสกุล.py เรื่องราวของวิชาฟิสิกส์ที่เรามักเจอกันในบทเรียนแรกๆ คือสูตร v=s/t ซึ่งคือสูตรในการคำนวณหาระยะทางที่เคลื่อนที่ได้ ต่อ 1 หน่วยเวลา v คืออัตราเร็วของการเคลื่อน...
# # Python Testing: Python Decorators # Python Techdegree # # Created by Dulio Denis on 1/22/19. # Copyright (c) 2019 ddApps. All rights reserved. # ------------------------------------------------ # Sometimes you can just write a function or # method or class and be done with it. # But sometimes you find that ...
from .automaton import Automaton from .automaton import State, LAMBDA from .automaton import remove_lambdas, determinize, automaton_to_wordtree from .wordtree import remove_empty_subtrees class Regex(): """ A Regex represents a regular expression. Each Regex has a type (CONCAT, CHOICE, REPEAT, RANGE). ...
from random import random class Wordtree: """ A Wordtree is a tree recognizing a word. It is a state with a set of successors, reachable through a range of characters. Furthermore, a Wordtree may be accepting, and is also labeled with the number of different words it can recognize. Simon B...
class InvalidPositionError(Exception): pass class Position(): def __init__(self, r: str=None, row: int=None, col: int=None): if r: self.position = r elif row is not None and col is not None: if row < 0 or row > 7 or col < 0 or col > 7: raise InvalidP...
import math import numpy list_of_primes = [] for num in range(2, 50000): if all(num % i != 0 for i in range(2, int(math.sqrt(num)) + 1)): list_of_primes.append(num) # print(num) print(list_of_primes) for j in range(len(list_of_primes)): # print(j) print(list_of_primes[:j + 1]) product =...
import random import numpy as np import matplotlib as plt ''' 随机生成圆,并且求出它到边界的最大半径,如果满足不重叠的要求就加入圆形列表中。 ''' class Circle: #定义构造函数 def __init__(self,x,y,r): self.x = x self.y = y self.radius = abs(r) def Center(self):#圆心坐标 center = complex(self.x,self.y) ...
#! /usr/bin/python3 import sys import fileinput from math import * import time def print_usage(): print("USAGE") print("\t./204duck a\n") print("DESCRIPTION") print("\ta\tconstant") def back_in_n_minutes(a, t): r = -a * exp(-t) - (4 - 3 * a) / 2 * exp(-2 * t) - (2 * a - 4) / 4 * exp(-4 * t) ...
def reverseList(self, head: ListNode) -> ListNode: prev=None current=head Next=None while current!=None: Next=current.next current.next=prev prev=current current=Next head=prev return head
while True: a=int(input("enter a integer ")) if a<0: continue elif a==0: break else: print("Square is ",a*a) print("Goodbye")
t = int(input()) for i in range(t): a = [] n = int(input()) for j in range(n): a.append(input()) ## print(a) if "cakewalk" in a: if "simple" in a: if "easy" in a: if "easy-medium" in a or "medium" in a: if "medium-hard" in a or "hard" in...
##bear and ladder ##There are roads 1-2, 3-4, 5-6, 7-8, and so on (there is a road between cities 2*i+1 and 2*i+2 for every non-negative integer i). ##There are roads 1-3, 3-5, 5-7, 7-9, ... (between every two consecutive odd numbers). ##There are roads 2-4, 4-6, 6-8, 8-10, ... (between every two consecutive even numbe...
i=0 a=int(input("enter no of rows : ")) while i<a : print(" "*i,end='') print("*"*(a-i)) i += 1
class ToDo: """ ALL TODOS WILL BE STORED AS INSTANCES OF THIS CLASS. THE 'ID' PROPERTY IS THE UNIQUE IDENTIFIER FOR EACH ID (BETWEEN 1 AND 999). THIS WILL BE USED TO FILTER A SPECIFIC ID IN THE PROGRAM. THE 'CONTENTS' PROPERTY CONTAINS THE USER-INPUTTED PART THE 'DONE' PROPERTY INDICATES WHETHER TH...
def my_func(flaga=True, name='my_string'): if flaga: print(name.upper()) else: print(name.lower()) my_func(False, name='Jacek') my_func(name='Jacek')
def check_for_escs(mal_str, ch, i, m_len): if ch == "\"" and i != 0 and i != m_len-1 or \ ch == "\\": mal_str = mal_str[:i] + "\\" + mal_str[i:] elif ch == "\n": mal_str = mal_str[:i] + "\\n" + mal_str[i+1:] else: return mal_str, i, m_len i += 1 m_len += 1 return ...
def interlock(str1, str2): if len(str2) > len(str1): str1, str2 = str2, str1 list1, list2 = map(list, [str1, str2]) for i in range(len(list2)): list1.insert(i*2 + 1, list2[i]) return "".join(list1)
''' Check if a word is a palindrome ''' import sys def IsPalindrome(word): # In case word is not a string if not type(word) is str: word = str(word) mid = len(word) / 2 return word[:mid] == word[::-1][:mid] def main(argv): # Check number of arguments if len(argv) != 2: pr...
''' All models need to return a CSP object, and a list of lists of Variable objects representing the board. The returned list of lists is used to access the solution. For example, after these three lines of code csp, var_array = kenken_csp_model(board) solver = BT(csp) solver.bt_search(prop_FC, v...
filename = input("Enter the filename (include the file extension e.g .txt): ") try: file = open(filename, 'r').readlines() except IOError: print ("File", filename, "not found. Program terminates") exit() # reading the file and saving the information to variables numberOfStates = int(file[0]) initi...
# Python program to check if the input number is prime or not import random def check(p): if p > 1: return miller_rabin(p, 40) else: return False def find_prime(bits, start=1, end=20): q = 2**bits for i in range(2**start+1, 2**end, 2): n = q - i if check(n): ...
import abc import numpy as np import random class Agent(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def select_action(self): """Method should return an action to take""" @abc.abstractmethod def send_observation(self, action, reward, obs_params): """ :param a...
import cv2 import gym import gym.spaces import numpy as np import collections # Class that defines method for skipping N number of frames # the motivation here is that going from 1 frame to an adjacent frame might not reveal much of a difference to our # network. skipping N frames still gives us proper dynamics while...
import numpy as np # This class is a recreation of OpenAI Gym FrozenLake-v0 Environment # The gym environment does not allow for the flexibility needed to solve using Dynamic Programming # as you cannot access states individually and perform actions. This environment gives the necessary control # FrozenLake Configura...
''' rhythm.py This module handles issues of rhythm in ABC. OVERVIEW: Every piece has a meter (M) ''' NOTES = "ABCDEFGabcdefg" # these are rhythms--we don't care about accidentals here # gets the duration of a phrase. "beat" was a very bad choice of term. CHANGE def duration(beat): stop = len(beat) i = 0 curr_len...