text
stringlengths
37
1.41M
# https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/submissions/ # # time: O(n^n) - generates a recursive tree for every entry # space: O(n) - only stores indexes and profit, but stores an index set for every root node class Solution: def maxProfit(self, prices: List[int]) -> int: return self.maxProfitFromIndex(prices, 0) def maxProfitFromIndex(self, prices: List[int], startIndex: int) -> int: maxProfitFromAllRoots = 0 # we might not need this! if startIndex >= len(prices): return 0 for treeRootIndex in range(startIndex, len(prices)): rootPrice = prices[treeRootIndex] rootTreeProfit = 0 for nextNodeIndex in range(treeRootIndex + 1, len(prices)): nextPrice = prices[nextNodeIndex] nextProfit = nextPrice - rootPrice print( f"looking at index combination {startIndex} {treeRootIndex} {nextNodeIndex}" ) # this is the single line that respects when we would be doing a "transaction" if nextProfit > 0: # this line determines that this particular transaction path is more valuable # than all the other potential transaction paths we could be doing thisTreeProfit = ( self.maxProfitFromIndex(prices, nextNodeIndex + 1) + nextProfit ) # assign the tree with this particular root to our top level profit tracker # if its higher than our current value if thisTreeProfit > rootTreeProfit: rootTreeProfit = thisTreeProfit # assign this root to the top level profit tracker # this is similar to the top level profit tracker above, but it works one level higher # (eg. across the whole tree, rather than across a single root) if rootTreeProfit > maxProfitFromAllRoots: maxProfitFromAllRoots = rootTreeProfit return maxProfitFromAllRoots
#!/ usr/bin/env python #coding: utf-8 """ Author: Arnaud Ferré Contact: [email protected] Date: 09/02/2017 Description: - A clean example of a Python script architecture for functions definition - Used to test commit command Licence: DSSL """ # Importations import math # Autres syntaxes/utilisations possibles : # from math import sqrt # import math as mat # Function definition def hypotenuse(a, b): """ Calculate the size of the hypotenuse of a triangle with the 2 other sides of size a and b. """ result = math.sqrt(a**2 + b**2) return result # Test/Demo of the local functions: if __name__ == '__main__': print("hyp(1,1)="+str(hypotenuse(1,1))) print("hyp(2,2)="+str(hypotenuse(2,2))) print("hyp(1,2)="+str(hypotenuse(1,2)))
#! /usr/bin/python def maxsub(a): ''' This returns the sum of the maximum continuous subsequence. ''' if len(a) == 1: return a[0] left = a[:len(a)/2] right = a[len(a)/2:] return max( max(maxsub(left), sum(left)+lborder(right)), # Left max(maxsub(right), sum(right)+rborder(left)), # Right rborder(left) + lborder(right)) def lborder(a): ''' Starting from the left, return the max sum ''' return max([sum(a[1:x])+a[0] for x in range(len(a))]) def rborder(a): ''' Starting from the right, return the max sum ''' return max([sum(a[x:-1])+a[-1] for x in range(len(a))]) if __name__ == '__main__': a = [4,-3,5,-2,-1,2,6,2] print maxsub(a) a = [-4,10,12,-5,-7,8,3,1] print maxsub(a)
a={1,2,3,4,5} b={4,5,6,7,8} print("the set value of a ",a) print("the set value of b ",b) a.difference_update(b) print("remove the intersection of 2nd set from set from the 1st set ",a)
#merged list of tuples from two lists l1=list(range(5)) l2=list(range(5,10)) t1=list(zip(l1,l2)) print(t1) #merge list and range to create list of tuples l=range(1,8) l1=["a","b","c","d","e"] print(list(zip(l,l1))) #sorting the list l=list(range(10,0,-1)) print(sorted(l)) #filter odd numbers l1=range(1,21) l=list(filter(lambda n:n%2!=0,l1)) print(l)
#multiply two arguments z=lambda x,y:x*y print(z(2,5)) #fibonacci series def fib(n): r=[0,1] any(map(lambda _:r.append(r[-1]+r[-2]),range(2,n))) print(r) n=int(input("Enter number")) fib(n) #multiply a number to the list l=list(range(10)) l=list(map(lambda n:n*3,l)) print(l) #divisible by 9 l=list(range(90)) l1=list(filter(lambda n:(n%9==0),l)) print(l1) #count of even no. l=list(range(1,11)) c=len(list(filter(lambda n:(n%2==0) ,l))) print(c)
""" 2. Faça um Programa que peça um valor e mostre na tela se o valor é positivo ou negativo. """ numero = int(input('Informe um número\n')) if numero >= 0: print('O número informado é positivo') else: print('O número informado é negativo\n')
""" 9. Faça um Programa que leia três números e mostre-os em ordem decrescente. """ numeros = set() while True: try: numero = int(input(f'Informe o {len(numeros)+1}º número\n')) numeros.add(numero) if len(numeros) == 3: break pass except ValueError: pass print(list(numeros)[::-1])
""" 26. Um posto está vendendo combustíveis com a seguinte tabela de descontos: Álcool: até 20 litros, desconto de 3% por litro acima de 20 litros, desconto de 5% por litro Gasolina: até 20 litros, desconto de 4% por litro acima de 20 litros, desconto de 6% por litro Escreva um algoritmo que leia o número de litros vendidos, o tipo de combustível (codificado da seguinte forma: A-álcool, G-gasolina), calcule e imprima o valor a ser pago pelo cliente sabendo-se que o preço do litro da gasolina é R$ 2,50 o preço do litro do álcool é R$ 1,90. """ while True: print('-' * 30) combustivel = input('[A] - álcool\n[G] - gasolina\n') if len(combustivel) == 0: pass combustivel = combustivel[0].upper() if combustivel not in 'AG': pass else: try: litros = abs(float(input('Número de litros vendidos\n'))) if combustivel == 'G': preco = 2.5 if litros <= 20: preco = preco * (1 - 0.04) elif litros > 20: preco = preco * (1 - 0.06) print(f'O valor a ser pago pelo cliente é R$ {round(litros * preco, 2)}') if combustivel == 'A': preco = 1.9 if litros <= 20: preco = preco * (1 - 0.03) elif litros > 20: preco = preco * (1 - 0.05) print(f'O valor a ser pago pelo cliente é R$ {round(litros * preco, 2)}') pass except ValueError: pass
""" 5. Faça um Programa que converta metros para centímetros """ metros = float(input('Informe a quantidade de metros\n')) print(f'{metros} metros equivale a {int(100*metros)} centimetros\n')
""" 25. Faça um programa que faça 5 perguntas para uma pessoa sobre um crime. As perguntas são: "Telefonou para a vítima?" "Esteve no local do crime?" "Mora perto da vítima?" "Devia para a vítima?" "Já trabalhou com a vítima?" O programa deve no final emitir uma classificação sobre a participação da pessoa no crime. Se a pessoa responder positivamente a 2 questões ela deve ser classificada como "Suspeita", entre 3 e 4 como "Cúmplice" e 5 como "Assassino". Caso contrário, ele será classificado como "Inocente". """ print('Sobre o crime, responda S para sim ou N para não\n') perguntas = ['Telefonou para a vítima?', 'Esteve no local do crime?', 'Mora perto da vítima?', 'Devia para a vítima?', 'Já trabalhou com a vítima?'] i = 0 classificacao = 0 while True: if i + 1 > len(perguntas): break resposta = input(perguntas[i] + '\n') if len(resposta) == 0: pass resposta = resposta[0].upper() if resposta == 'S': classificacao += 1 i += 1 pass if classificacao == 2: print('Você está classificado(a) como "Suspeito(a)"') elif 3 <= classificacao <= 4: print('Você está classificado(a) como "Cúmplice"') elif classificacao == 5: print('Você está classificado(a) como "Assassino"') else: print('Você está classificado(a) como "Inocente"')
"""Python Decorator Templated""" from functools import wraps, partial __all__ = [ 'base_decorator_func', 'base_decorator_func_with_args', 'BaseDecorator', ] def base_decorator_func(func): """Decorator function: This decorator overrides original 'function' and returns the wrapper function. Parameters ---------- function : function Function which execution shall be wrapper. Returns ------- function The wrapper function """ @wraps(func) # maintain all the info about the function def wrapper(*args, **kwargs): """Wrapper function: This wrapper executes the wrapper function along with whatever functionality you like. """ print('{} is called from the decorator' \ 'with arguments={} and kwargs={}'.format( func.__name__, args, kwargs)) result = func(*args, **kwargs) print('{} returns {}'.format(func.__name__, result)) return result return wrapper def base_decorator_func_with_args(func=None, *dec_args, **dec_kwargs): """Decorator function with optional arguments: This decorator receives arguments and returns the wrapper function. If the decorator is set with arguments when decorating a function, the decorator is returned as a partial function along with the kwargs. Parameters ---------- function : function, optional The function which shall be wrapper, by default None dec_kwargs: arguments, optional additional decorator arguments which can be used inside the wrapper function Returns ------- function The wrapper function """ if func is None: """A partial is a "non-complete function call" that includes a function and some arguments, so that they are passed around as one object without actually calling the function yet. """ return partial(base_decorator_func_with_args, args=dec_args, kwargs=dec_kwargs) @wraps(func) # maintain all the info about the function def wrapper(*args, **kwargs): """Wrapper function: This wrapper executes the wrapper function along with whatever functionality you like. The dec_kwargs can be used here. """ print('{} is called from the decorator with arguments={} and kwargs={}'.format(func.__name__, args, kwargs)) result = func(*args, **kwargs) print('{} returns {}'.format(func.__name__, result)) return result return wrapper # Sentinel to detect undefined function argument. UNDEFINED_FUNCTION = object() class BaseDecorator(object): """Base class to easily create convenient decorators. Override :py:meth:`setup`, :py:meth:`run` or :py:meth:`decorate` to create custom decorators: * :py:meth:`setup` is dedicated to setup, i.e. setting decorator's internal options. :py:meth:`__init__` calls :py:meth:`setup`. * :py:meth:`decorate` is dedicated to wrapping function, i.e. remember the function to decorate. :py:meth:`__init__` and :py:meth:`__call__` may call :py:meth:`decorate`, depending on the usage. * :py:meth:`run` is dedicated to execution, i.e. running the decorated function. :py:meth:`__call__` calls :py:meth:`run` if a function has already been decorated. Decorator instances are callables. The :py:meth:`__call__` method has a special implementation in Decorator. Generally, consider overriding :py:meth:`run` instead of :py:meth:`__call__`. This base class transparently proxies to decorated function: >>> @BaseDecorator ... def return_args(*args, **kwargs): ... return (args, kwargs) >>> return_args() ((), {}) >>> return_args(1, 2, three=3) ((1, 2), {'three': 3}) This base class stores decorator's options in ``options`` dictionary (but it doesn't use it): >>> @BaseDecorator ... def do_nothing(): ... pass >>> do_nothing.kwargs {} >>> @BaseDecorator() ... def do_nothing(): ... pass >>> do_nothing.kwargs {} >>> @BaseDecorator(one=1) ... def do_nothing(): ... pass >>> do_nothing.kwargs {'one': 1} """ def __init__(self, *args, **kwargs): """Constructor. Accepts positional and keyword argument: If the function is passed to the constructor it has to be the first argument. """ self.decorated = None # Check if the first argument is callable = a function is passed # If yes -> set it as decorated function and remove it from the args if args: if callable(args[0]): self.decorate(args[0]) args = args[1:] self.setup(*args, **kwargs) def decorate(self, func): """Remember the function to decorate. Raises TypeError if ``func`` is not callable. """ if not callable(func): raise TypeError('Cannot decorate a non callable object "{}"' .format(func)) self.decorated = func def setup(self, *args, **kwargs): """Store decorator's args and kwargs""" self.args = args self.kwargs = kwargs def __call__(self, *args, **kwargs): """Run decorated function if available, else decorate first arg. This base implementation is a transparent proxy to the decorated function: it passes positional and keyword arguments as is, and returns result.""" func = self.decorated if func is None: func = args[0] if args[1:] or kwargs: raise ValueError('Cannot decorate and setup simultaneously ' 'with __call__(). Use __init__() or ' 'setup() for setup. Use __call__() or ' 'decorate() to decorate.') self.decorate(func) return self else: return self.run(func, *args, **kwargs) def run(self, func, *args, **kwargs): """Actually run the decorator. This base implementation is a transparent proxy to the decorated function: it passes positional and keyword arguments as is, and returns result. """ @wraps(func) # maintain all the info about the function def wrapper(*args, **kwargs): """Run function: This wrapper executes the wrapper function along with whatever functionality you like. The args and kwargs can be used here. """ print('{} is called from the decorator with arguments={} and kwargs={}'.format(func.__name__, args, kwargs)) result = func(*args, **kwargs) print('{} returns {}'.format(func.__name__, result)) return result return wrapper(*args, **kwargs) def __getattr__(self, name): return self.decorated.__getattribute__(name) def __str__(self): return self.decorated.__str__() # class Decorated(object): # """A representation of a decorated class. # This user-immutable object provides information about the decorated # class, method, or function. The decorated callable can be called # by directly calling the ``Decorated`` instance, or via the # ``wrapped`` instance attribute. # The example below illustrates direct instantiation of the # ``Decorated`` class, but generally you will only deal with # instances of this class when they are passed to the functions # specified on generic decorators. # .. code:: python # from pydecor import Decorated # def some_function(*args, **kwargs): # return 'foo' # decorated = Decorated(some_function, ('a', 'b'), {'c': 'c'}) # assert decorated.wrapped.__name__ == some_function.__name__ # assert decorated.args == ('a', 'b') # assert decorated.kwargs == {'c': 'c'} # assert decorated.result is None # has not yet been called # res = decorated(decorated.args, decorated.kwargs) # assert 'foo' == res == decorated.result # .. note:: # identity tests ``decorated.wrapped is some_decorated_function`` # will not work on the ``wrapped`` attribute of a ``Decorated`` # instance, because internally the wrapped callable is wrapped # in a method that ensures that ``Decorated.result`` is set # whenever the callable is called. It is wrapped using # ``functools.wraps``, so attributes like ``__name__``, # ``__doc__``, ``__module__``, etc. should still be the # same as on an actual reference. # If you need to access a real reference to the wrapped # function for any reason, you can do so by accessing # the ``__wrapped__`` property, on ``wrapped``, which is # set by ``functools.wraps``, e.g. # ``decorated.wrapped.__wrapped__``. # :param wrapped: a reference to the wrapped callable. Calling the # wrapped callable via this reference will set the ``result`` # attribute. # :param args: a tuple of arguments with which the decorated function # was called # :param kwargs: a dict of arguments with which the decorated function # was called # :param result: either ``None`` if the wrapped callable has not yet # been called or the result of that call # """ # __slots__ = ("args", "kwargs", "wrapped", "result") # args: tuple # kwargs: dict # wrapped: t.Callable # result: t.Optional[t.Any] # def __init__(self, wrapped, args, kwargs, result=None): # """Instantiate a Decorated object # :param callable wrapped: the callable object being wrapped # :param tuple args: args with which the callable was called # :param dict kwargs: keyword arguments with which the callable # was called # :param # """ # sup = super(Decorated, self) # sup.__setattr__("args", get_fn_args(wrapped, args)) # sup.__setattr__("kwargs", kwargs) # sup.__setattr__("wrapped", self._sets_results(wrapped)) # sup.__setattr__("result", result) # def __str__(self): # """Return a nice string of self""" # if hasattr(self.wrapped, "__name__"): # name = self.wrapped.__name__ # else: # name = str(self.wrapped) # return "<Decorated {}({}, {})>".format(name, self.args, self.kwargs) # def __call__(self, *args, **kwargs): # """Call the function the specified arguments. # Also set ``self.result`` # """ # return self.wrapped(*args, **kwargs) # def __setattr__(self, key, value): # """Disallow attribute setting""" # raise AttributeError( # 'Cannot set "{}" because {} is immutable'.format(key, self) # ) # def _sets_results(self, wrapped): # """Ensure that calling ``wrapped()`` sets the result attr # :param callable wrapped: the wrapped function, class, or method # """ # @wraps(wrapped) # def wrapped_wrapped(*args, **kwargs): # """Set self.result after calling wrapped""" # res = wrapped(*args, **kwargs) # super(Decorated, self).__setattr__("result", res) # return res # return wrapped_wrapped
class Queue(object): def __init__(self): self.queue = [] def enqueue(self, val): self.queue.insert(0, val) def dequeue(self): if not self.is_empty(): self.queue.pop() else: print("underflow") def is_empty(self): return False if self.queue else True def travel(self): print(self.queue[-1::-1]) q = Queue() q.enqueue(1) q.enqueue(2) q.travel() q.dequeue() q.enqueue(3) q.travel() q.dequeue() q.dequeue() q.dequeue()
import doctest class Square(object): """A square object""" def __init__(self, value): #requires value upon initialization self.up = None # default self.down = None # default self.left = None # default self.right = None # default self.value = value # taken in above self.coordinates = None def carrot_missile(matrix): """Takes in matrix, holds other functions """ object_matrix = iterate_through_matrix(matrix) center_indices = find_center(object_matrix) coordinates, carrot_count = find_max_carrots(center_indices, object_matrix) carrots = carrot_seeking(coordinates, carrot_count, object_matrix) return carrots def iterate_through_matrix(matrix): """Traverse through matrix define where each square is in relation to others """ object_matrix = [] #creating a matrix to store objects that are created height = len(matrix) # find the length of matrix[0] <- (height) width = len(matrix[0]) # find width for row in matrix: row_list = [] for cell in row: square = Square(cell) row_list.append(square) object_matrix.append(row_list) # for each row in matrix, create an empty list # assign attributes to objects in matrix row_counter = 0 for row in object_matrix: # using obj_row instead of i cell_counter = 0 for cell in row: # using cell instead of j cell.coordinates = (row_counter, cell_counter) if cell_counter != (width - 1): # setting right cell.right = object_matrix[0][cell_counter + 1] if cell_counter != 0: # setting left cell.left = object_matrix[row_counter][cell_counter - 1] if row_counter != 0: # settting up cell.up = object_matrix[row_counter - 1][cell_counter] if row_counter != (height - 1): cell.down = object_matrix[row_counter + 1][cell_counter] cell_counter += 1 row_counter +=1 print object_matrix return object_matrix def find_center(object_matrix): """Find the middle grid""" height = len(object_matrix) # find the length of matrix[0] <- (height) width = len(object_matrix[0]) # find width if height == 0: return [] elif height % 2 == 0 and width % 2 == 0: # both even center_indices = ((((height/2)-1),((width/2)-1)), ((height/2)-1,(width/2)), ((height/2),((width/2)-1)), ((height/2),(width/2)),) elif height % 2 == 0 and width % 2 != 0: # number of lists even, length of lists odd center_indices = (((height/2)-1,(width/2)), ((height/2),(width/2),)) elif height % 2 != 0 and width % 2 == 0: # number of lists odd, length of lists even center_indices = (((height - 1)/2, ((width - 1)/2)), ((height - 1)/2, width/2),) else: # odd center_indices = (height/2, width/2,) return center_indices def find_max_carrots(center_indices, object_matrix): """Take in indices, find max carrots""" max_value = 0 for indices in center_indices: if (object_matrix[indices[0]][indices[1]]).value > max_value: max_value = (object_matrix[indices[0]][indices[1]]).value print "Max Value:", max_value coordinates = (indices[0],indices[1]) square = object_matrix[indices[0]][indices[1]] carrot_count = square.value square.value = 0 return (coordinates, carrot_count) def carrot_seeking(coordinates, carrot_count, object_matrix): """Look at 4 surrounding squares for highest carrot amount Stop when zero carrots are to be found """ current_square = object_matrix[coordinates[0]][coordinates[1]] surrounding_squares = [current_square.up, current_square.down, current_square.right, current_square.left] new_squares = [] for square in surrounding_squares: if square != None: new_squares.append(square) square_check = 0 if new_squares != []: for square in new_squares: square_check += square.value print "Square Check", square_check if square_check == 0: return carrot_count else: highest_value = 0 for square in new_squares: if square.value > highest_value: highest_value = square.value print "HV", highest_value for square in new_squares: if square.value == highest_value: carrot_count += square.value current_square = square square.value = 0 coordinates = current_square.coordinates print "Current Square Value:", current_square.value print "Carrot Count:", carrot_count carrot_seeking(coordinates, carrot_count, object_matrix)
#RUSHIKESH BANDIWADEKAR, SE-IT, A-37 #Program to traverse through given dictionaries using for loop #Taking how many data/values user want to enter/add in dictionary n = int(input("Enter how many number of datas you want to add in dictionary : ")) #Creating empty dictionary d = {} #We take rolll number and name as key and values in this example for i in range(n): keys = int(input("Enter roll number : ")) values = input("Enter name of student : ") d[keys] = values print("Values of dictionary are :") print(d)
# coding: cp949 #money = 2000 money =int(input("󸶸 ֽϱ? ")) # input ޴° string ó #card = 1 <- ī θ ǴϹǷ ޸ #card = True card = input("ī带 ϰֽϱ? (y/n) :") if card == 'y': card = True else: card = False if money >= 3000: print("Űó ý м мմϴ."); print("м Ϸᰡ Ǿϴ."); print("ýø Ÿ ") elif card == True: print("ýø Ÿ ") else: print("ɾ")
import os import time import random # --- NL = '\n' # --- GAMES_TO_PLAY = 10 SLEEP_TIME = 0.1 # --- players = [ { 'Name': 'Bob', 'Symbol': 'X', 'Wins': 0 }, { 'Name': 'Alice', 'Symbol': 'O', 'Wins': 0 } ] # Board stored as 3D char array board = [[' ' for i in range(3)] for j in range(3)] winner = None draws = 0 topBar = '' bottomBar = '' # Represents each possible 'line' of three cells that can be used to win the game. # This is used both by the core game loop and the AIs. potentialLines = [ [[0,0], [0,1], [0,2]], [[1,0], [1,1], [1,2]], [[2,0], [2,1], [2,2]], [[0,0], [1,0], [2,0]], [[0,1], [1,1], [2,1]], [[0,2], [1,2], [2,2]], [[0,0], [1,1], [2,2]], [[0,2], [1,1], [2,0]] ] # --- def printBoard(): # We store the basic building blocks of the board display here hLine = ' -----+-----+----- ' vLines = ' | | ' symbols = ' {} | {} | {} ' rowTemplate = vLines + NL + symbols + NL + vLines boardTemplate = \ rowTemplate + NL + hLine + NL + \ rowTemplate + NL + hLine + NL + \ rowTemplate boardAsText = boardTemplate.format( board[0][0], board[0][1], board[0][2], board[1][0], board[1][1], board[1][2], board[2][0], board[2][1], board[2][2] ) # Clear the console before reprinting the board os.system('cls') print(NL+topBar) print(NL+boardAsText) print(NL+bottomBar) # If we're simulating multiple games, display the win tally for each player below if GAMES_TO_PLAY > 1: print( NL + 'Wins:' + \ NL + '---+---' + \ NL + ' ' + players[0]['Symbol'] + ' | ' + players[0]['Name'] + ': ' + str(players[0]['Wins']) + \ NL + ' ' + players[1]['Symbol'] + ' | ' + players[1]['Name'] + ': ' + str(players[1]['Wins']) + \ NL + ' . | Draws: '+str(draws) ) # --- def resetGame(): global winner global board winner = None board = [[' ' for i in range(3)] for j in range(3)] # --- def isValid(move): return board[move['Position'][0]][move['Position'][1]] == ' ' # --- def executeMove(move): global board board[move['Position'][0]][move['Position'][1]] = move['Symbol'] # --- def checkPotentialTriple(symbol, symbolCount, posA, posB, posC): # Does the specified [symbol] appear in [symbolCount] of the three specified positions, # with the remaining position(s) being blank? hasSymbol = 0 boardCells = [ board[posA[0]][posA[1]], board[posB[0]][posB[1]], board[posC[0]][posC[1]] ] for cellValue in boardCells: if cellValue == symbol: hasSymbol += 1 elif cellValue != ' ': return False return hasSymbol == symbolCount # --- def isGameOver(): # Check all potential winning lines. If a player has filled a line, they are the winner. global winner for player in players: for line in potentialLines: if checkPotentialTriple(player['Symbol'], 3, line[0], line[1], line[2]): winner = player return True return False # --- def getValidMove(player, potentialMoves = []): # If we've been passed a list of moves to try, iterate over them and pick the first valid move for movePos in potentialMoves: move = { 'Position': [movePos[0], movePos[1]], 'Symbol': player['Symbol'] } if isValid(move): return move # If we haven't been passed any moves to try (or if none of the specified moves are valid), # just keep trying random moves until one is valid. while True: move = { 'Position': [random.randint(0,2), random.randint(0,2)], 'Symbol': player['Symbol'] } if isValid(move): return move # Important: This assumes that there exists at least one valid move. In other words, don't remove the # turnNum == 9 check in the main loop or this will continue searching for moves indefinitely. # --- def getP1Move(): # P1: Pretty good AI. Tries to win, also tries to prevent the other AI from winning. # 1/ If we can win this turn, finish the game for line in potentialLines: if checkPotentialTriple(players[0]['Symbol'], 2, line[0], line[1], line[2]): return getValidMove(players[0], line) # 2/ If other player is about to win, block them for line in potentialLines: if checkPotentialTriple(players[1]['Symbol'], 2, line[0], line[1], line[2]): return getValidMove(players[0], line) # 3/ Choose a random valid move return getValidMove(players[0]) # --- def getP2Move(): # P2: Not very good AI. Just picks a random, valid move. # # If we can win this turn, finish the game # for line in potentialLines: # if checkPotentialTriple(players[1]['Symbol'], 2, line[0], line[1], line[2]): # return getValidMove(players[1], line) # # # If other player is about to win, block them # for line in potentialLines: # if checkPotentialTriple(players[0]['Symbol'], 2, line[0], line[1], line[2]): # return getValidMove(players[1], line) # 1/ Choose a random valid move return getValidMove(players[1]) # --- for gameNum in range(1, GAMES_TO_PLAY+1): # Display information about the two players, as well as the game number (if move than one game is to be played) topBar = 'Tic Tac Toe - {} ({}) vs. {} ({}){}'.format( players[0]['Name'], players[0]['Symbol'], players[1]['Name'], players[1]['Symbol'], (' Game #'+str(gameNum)) if GAMES_TO_PLAY > 1 else '' ) resetGame() turnNum = 1 while winner is None: # Switch moves every turn and switch turn order every game P1Turn = turnNum % 2 == gameNum % 2 bottomBar = 'Turn {}, {}''s move...'.format( turnNum, players[0]['Name'] if P1Turn else players[1]['Name'] ) move = getP1Move() if P1Turn else getP2Move() # Each AI should only ever return valid moves, but just in case I've left this check in if isValid(move): executeMove(move) else: print('Invalid Move.') break if isGameOver(): # Display the winner bottomBar = 'Game over! Winner is '+winner['Name'] winner['Wins'] += 1 printBoard() # Sleep for longer than usual before the next game if SLEEP_TIME > 0: time.sleep(SLEEP_TIME*5) break if turnNum == 9: # We've reached turn 9 with no winner. Game is declared a draw. bottomBar = 'Draw.' draws += 1 printBoard() if SLEEP_TIME > 0: time.sleep(SLEEP_TIME*5) break # If the sleep time is zero, we don't bother printing the board each loop (just when the game ends) if SLEEP_TIME > 0: printBoard() time.sleep(SLEEP_TIME) turnNum += 1
#Nicolas Tracewell #[email protected] #programming assignment 3 #The program chooses a random number between 1 and 10 and gives the user three guesses to get it right, giving hints with each guess. import random x = random.randint(1,10) print("I'm thinking of an integer in the range 1 to 10. You have three guesses.\n") y = int(input("Enter your first guess: ")) if x==y: print("You win!\n") if x<y: print("Your guess is too high.\n") a = int(input("Enter your second guess: ")) if x==a: print("You win!\n") if x<a: print("Your guess is too high.\n") b=int(input("Enter your third guess: ")) if x==b: print("You win!\n") if x<b: print("Your guess is too high.\n") print("You lose. The number was %d." % (x)) if x>b: print("Your guess is too low.\n") print("You lose. The number was %d." % (x)) if x>a: print("Your guess is too low.\n") c=int(input("Enter your third guess: ")) if x==c: print("You win!\n") if x<c: print("Your guess is too high.\n") print("You lose. The number was %d." % (x)) if x>c: print("Your guess is too low.\n") print("You lose. The number was %d." % (x)) if x>y: print("Your guess is too low.\n") d = int(input("Enter your second guess: ")) if x==d: print("You win!\n") if x<d: print("Your guess is too high.\n") e=int(input("Enter your third guess: ")) if x==e: print("You win!\n") if x<e: print("Your guess is too high.\n") print("You lose. The number was %d." % (x)) if x>e: print("Your guess is too low.\n") print("You lose. The number was %d." % (x)) if x>d: print("Your guess is too low.\n") f=int(input("Enter your third guess: ")) if x==f: print("You win!\n") if x<f: print("Your guess is too high.\n") print("You lose. The number was %d." % (x)) if x>f: print("Your guess is too low.\n") print("You lose. The number was %d." % (x))
""" Takes an input label file and converts the labels currently as days (ints) into years (floats) """ input_file = open("/home/albert/Desktop/pic5_dataset/age/pic5_age_train.days.txt", "r") output_file = open("/home/albert/Desktop/pic5_dataset/age/pic5_age_train.years.txt", "w") lines = input_file.readlines() for line in lines: tokens = line.strip().split(" ") days = int(tokens[1]) years = int(1.0*days/365.25) output_file.write(tokens[0] + " " + str(years) + "\n") input_file.close() output_file.close()
import os import csv # Path to collect data budget_csv = os.path.join('budget_data.csv') # Read in the CSV file with open(budget_csv, 'r') as csvfile: # Split the data on commas csvreader = csv.reader(csvfile, delimiter=',') months = [] header = next(csvreader) net_pl = [] change_pl = [] # Loop through the data for row in csvreader: #The total number of months included in the dataset months.append(row[0]) #The net total amount of "Profit/Losses" over the entire period net_pl.append(float(row[1])) #The average of the changes in "Profit/Losses" over the entire period for i in range(1,len(net_pl)): change_pl.append(net_pl[i] - net_pl[i-1]) average_pl = sum(change_pl) / len(change_pl) #The greatest increase in profits (date and amount) over the entire period high_profit = max(change_pl) high_month = str(months[change_pl.index(max(change_pl))+1]) #The greatest decrease in losses (date and amount) over the entire period low_proft = min(change_pl) low_month = str(months[change_pl.index(min(change_pl))+1]) print ("Financial Analysis") print ("-------------------------------") print (f"Total Months: {len(months)}") print (f"Total: ${round(sum(net_pl))}") print (f"Average Change: ${round(average_pl,2)}") print (f"Greatest Increase in Profits: {high_month}, (${round(high_profit)})") print (f"Greatest Decrease in Profits: {low_month}, (${round(low_proft)})") f= open("Financial Analysis", 'w') f.write ("-------------------------------\n") f.write (f"Total Months: {len(months)}\n") f.write (f"Total: ${round(sum(net_pl))}\n") f.write (f"Average Change: ${round(average_pl,2)}\n") f.write (f"Greatest Increase in Profits: {high_month}, (${round(high_profit)})\n") f.write (f"Greatest Decrease in Profits: {low_month}, (${round(low_proft)})\n") f.close()
import src.ETL.Person as p class Drink: def __init__(self, drink_type, drink_name, details, price, id=None): self.id = id self.drink_type = drink_type self.drink_name = drink_name self.details = details self.price = price def get_info(self): return f"#{self.id} {self.drink_name} {self.details}" def get_name(self): return self.drink_name def contains(list, name_filter, details_filter): for drink_object in list: if name_filter(drink_object) and details_filter(drink_object): return drink_object return False def make_drink(db, drink_list, drink_type): drink_name = input(f"What {drink_type} drink do you want? ") if drink_name == "": print("Invalid selection returning to main menu") else: if drink_type == "Hot": details = milk_sugar() else: details = size() drink_check = contains(drink_list,lambda x: x.drink_name == drink_name.capitalize(),lambda x: x.details ==details) if not drink_check: price = input(f"What is the price of a {drink_name}? ") new_id = db.save_drink("drink", drink_type, drink_name.capitalize(), details, price) chosen_drink = Drink(drink_type, drink_name, details, price, int(new_id)) print("Drink added successfully") else: chosen_drink = drink_check drink_list.append(chosen_drink) return chosen_drink def milk_sugar(): details = int(input(""" [1] Extra milk [2] Sugar [3] N/A Selection: """)) if details == 1: return "extra milk" elif details == 2: return "with sugar" else: return "-" def size(): details = int(input(""" [1] Large [2] Small Selection: """)) if details == 1: return "large" else: return "small"
import matplotlib.pyplot as plt x1 = [1,2,3,4,5] y1 = [1,2,4,8,16] colors = ['green', 'red', 'blue', 'orange', 'lightgreen'] plt.bar(x1, y1, edgecolor='black', color = colors, linewidth = 3) plt.title("title") plt.xlabel("horizontal title") plt.ylabel("vertical title") plt.show()
#5-1 condition test car = 'subaru' print("is the car a 'subaru'? i predict true.") print (car == 'subaru') car = 'audi' print("\nis this car an 'audi'? i predict false") print (car != 'audi') name = 'peterson' print("\nis this persons name and 'peterson'? i predict true") print (car == 'peterson') car = 'peterson' print("\nis this persons name 'peterson'? i predict false") print (car != 'peterson') car_model = 'R32' print("\nis this car an 'audi'? i predict false") print (car_model == 'audi') car_model = 'R32' print("\nis this car a 'Golf R32'? i predict true") print (car_model == 'R32') computer = 'dell' print("\nis this computer a 'dell'? i predict true") print (car == 'dell') computer = 'dell' print("\nis this computer a 'dell'? i predict true") print (car != 'dell') dog = 'poodle' print("\nis this dog a 'poodle'? i predict false") print (car == 'poodle') dog = 'poodle' print("\nis this dog a 'poodle'? i predict false") print (car != 'poodle') #5-2 more condition tests names = 'jack' print("this persons name is jack") print(names == 'jack') print("this persons name is jack") print(names == 'john') print("this mans name is jack") print(names.lower() == 'jack') print("this mans name is jack") print(names.lower() == 'JACK') number = 12 numbeer2 = 19 number3 = 12 print(f'{number} is the same as {numbeer2}') print(number == numbeer2) print(f'{number} is the same as {number3}') print(number == number3) print(f'{number} is greater than {numbeer2}') print(number > numbeer2) print(f'{number} is greater than {numbeer2}') print(number < numbeer2) print(f'{number} is greater than or equal to {numbeer2}') print(number >= numbeer2) print(f'{number} is smaller than or equal to {numbeer2}') print(number <= numbeer2) age = 17 age1 = 19 age2= 21 print(f'{age} is the same as {age1} or {age} is the same as {age2}') print(age == age1 or age == age2) print(f'{age} is amaller than {age1} and {age} is smaller than {age2}') print(age < age1 and age < age2) dog_names = ['lilo', 'astro', 'snowy'] print(f'{dog_names[0]} is still in the yard') print('lilo' in dog_names) print('jock is still in the yard') print ('jock' in dog_names)
#5-8 hello admin names = ['admin', 'elgin', 'dylan', 'logan', 'keenan'] for name in names: if name == 'admin': print(f'hello {names[0]}, would you like to see a status report') if name == 'elgin': print(f'hello {names[1]}, thank you for logging in again') if name == 'dylan': print(f'hello {names[2]}, thank you for logging in again') if name == 'logan': print(f'hello {names[3]}, thank you for logging in again') if name == 'keenan': print(f'hello {names[4]}, thank you for logging in again') #5-9 no users name_1 = [] if name: for name in name_1: print("") else: print("we need to find more users") #5-10 checking usernames current_users = ['elgin', 'dylan', 'logan', 'keenan', 'tiffany'] new_users = ['tiffany', 'latisha', 'ashwyn', 'elgin', 'mishka']
# Part I: Members, Students and Instructors # You're starting your own web development school called Codebar! Everybody at Codebar -- whether they are attending workshops or teaching them -- is a Member. class Member: def __init__(self, full_name): self.full_name = full_name def hello(self): print(f"Hi my name is {self.full_name}") class Student(Member): def __init__(self, full_name, reason): Member.__init__(self, full_name) self.reason = reason class Instructor(Member): def __init__(self, full_name, bio): Member.__init__(self, full_name) self.skills = [] self.bio = bio def add_skill(self, new_skill): self.skills.append(new_skill) class Workshop: def __init__(self, date, subject): self.date = date self.subject = subject self.instructors = [] self.students = [] def add_participant(self, participant): if isinstance(participant, Instructor): self.instructors.append(participant) elif isinstance(participant, Student): self.students.append(participant) def print_details(self): print(f"Workshop - {self.date} - {self.subject}") print("Students") for index in range(len(self.students)): print(f"{index + 1}. {self.students[index].full_name} - {self.students[index].reason}") print("Instructors") for index, instructor in enumerate(self.instructors): print(f"{index + 1}. {instructor.full_name} - {', '.join(instructor.skills)} \n {instructor.bio}") workshop = Workshop("03/15/2010", "Python") tom = Student("Tom Lee", "I am trying to learn programming and need some help") stacy = Student("Stacy Smith", "I am really excited about learning to program!") vicky = Instructor("Vicky Python", "I want to help people learn coding.") vicky.add_skill("HTML") vicky.add_skill("JavaScript") nicole = Instructor("Nicole McMillan", "I have been programming for 5 years in Python and want to spread the love") nicole.add_skill("Python") workshop.add_participant(tom) workshop.add_participant(stacy) workshop.add_participant(vicky) workshop.add_participant(nicole) workshop.print_details
from itertools import chain, combinations def powerset(iterable): "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" s = list(iterable) return list(chain.from_iterable(combinations(s, r) for r in range(1, len(s)+1))) def subsequentset(iterable): sset = [] s = list(iterable) for idx, i in enumerate(s): sset.append(s[0:idx+1]) return sset
# Three-Dimensional Object # # This is a container class for three-dimensional objects. # # Last Modified 2013.01.13 22:24 # import ThreeVector class ThreeDimensionalObject: def __init__(self, X1 = 0, X2 = 0, Y1 = 0, Y2 = 0, Z1 = 0, Z2 = 0): self.X1 = X1 self.X2 = X2 self.Y1 = Y1 self.Y2 = Y2 self.Z1 = Z1 self.Z2 = Z2 def Contains(self, Point): IsContained = False if ((Point.X > self.X1) and (Point.X < self.X2) and (Point.Y > self.Y1) and (Point.Y < self.Y1) and (Point.Z > self.Z1) and (Point.Z < self.Z1)): IsContained = True return IsContained
valor_lado = int(input('Por favor ingrese el valor del lado: \t')) area = valor_lado * valor_lado perimetro = valor_lado + valor_lado + valor_lado + valor_lado print(f'El area es: {area}') print(f'el area del perimetro es: {perimetro}')
def line_break(x): print(str(x) + '---------' + str(x) + '---------' + str(x) + '---------' + str(x) + '---------') lb = line_break ''' ~appendix * this is the first note on building a python flask application * ~lb(0): flask is fun: what is going on here? ~lb(1): starting the flask app ~lb(2): updating your code to include some HTML ''' lb(0) # flask's official website offers the simplest application you can build on flask, # named 'Flask is Fun': from flask import Flask # [0] app = Flask(__name__) # [1] @app.route('/') def hello_world(): # [2] return 'Hello World!' # [3] # now, what is going on here with these four lines of code? #[0]: importing your flask class from the Flask module #[1]: then creating this app variable and setting it to an instance of Flask class. # now, passing in the __name__ an seem a bit confusing, # but __name__ is just a special variable in python that is just the name of the module * # *note: if you run the script with python directly,* # *__name__ can be equal to __main__ (you'll see that in just a second)* # *(basically, that is so Flask knows where to look for your templates and static files, etc.)* # so, now that you have an intantiated flask application in this app variable, # you can then create your routes. # routes are what you type into your browser to go different pages. # e.g. you have probably been to a webstie that has 'About' or 'Contents' pages, # in flask, you create these using route decorators. # note: you don't need to know the 100% in-and-out of decorators, # but basically decorators are just a way to add additional functionality to existing functions #[2]: in this case, the @app.route decorator will handle all of the complicated backend stuff # and simply allow you to write a function that returns the information that will be shown on your website # for this specific route. # this foreward slash (/) is just the route page of your website, which you can think of it as a homepage. #[3]: and you are simply returning the text "Hello World!" # this is normally where you would want to return some HTML, # but you'll start off with this text just to make sure it all works. # i.e. when you start your application, # if you navigate to the homepage, it should show you this text "Hello World!" lb(1) # to start the app, return to Terminal and navigate to the project directory. # right click on 'Flask_Directory' folder and select 'New Terminal at Folder' # before you run your application, # you want to set an environment variable to the file that you want to be your flask application. # type 'export FLASK_APP=flaskblog.py' into Terminal # and once the environment variable is set, simply type in 'flask run' into Terminal #returns (in terminal): ''' * Serving Flask app "flaskblog.py" * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: off 0---------0---------0---------0--------- 1---------1---------1---------1--------- * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) 127.0.0.1 - - [03/Aug/2020 17:51:46] "GET / HTTP/1.1" 200 - ''' #the 127.0.0.1 is the IP address of your local machine and # the :5000/ is the port number. #note: this is a running webserver (which actually comes with flask itself). #you have to have this terminal message running while you view your site #or else you won't be able to see it. #if you copy the 'http://127.0.0.1:5000/' onto your web browser, #you should see your sample application (Hello World!) #this 'Hello World!' is what you returned from your home route. #n.b. there is also an alias for the IP address '127.0.0.1', #and that alias is 'localhost' #i.e. entering 'http://localhost:5000/' into the webbrowser will yield the same (Hello World!). # # # # # # # # # # # # # # # # continue onto flaskblog2.py # # # # # # # # # # # # # # # #
from typing import List class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: res = sorted(nums1 + nums2) mid = (len(res) - 1) // 2 print(res[mid]) return res[mid] if len(res) % 2 != 0 else (res[mid] + res[mid + 1])/2 print(Solution().findMedianSortedArrays([1, 2], [3, 4]))
variable_creator = dict() for x in range(5): x = input("enter in your variable name:") y = input("enter its value:") variable_creator[x] = y x = "" y = "" print(variable_creator) n = input("which one do you want to access") print(variable_creator[n])
x=12 y=5 z=123 print(max(x,y)) print(min(z,y)) print(abs(-12)) print(pow(21,21)) print(round(3123.3223)) from math import * print(floor(3.678) , floor(3.2134) , floor(4)) print(ceil(3.6454) , ceil(3.4122) , ceil(3)) print(sqrt(25)) print(1)
# A string is an immutable, ordered, and it is represented by text # A string can be written in all these different ways and all have their own advantages # like the single quote one is easy # double quote help if you want to throw in a single quote # triple quote are used for multiple lines # var1 = 'Hello World' var2 = ",I got pies from the mar's planet" var3 = """ "Isn't cool" titan moons habitants said """ print(var1 + " " + var2 + "" + var3) # if you don't want multiple lines oyu can also do this var4 = """\ This \ is """ print(var4) # index fetching works the same as lists but you can't change it # This is a nice way to reverse reverse_mode = "This is sparta" print(reverse_mode[::-1]) # important:This function may not be used but is important it removes white space extra_dude = " lol " print(extra_dude.strip()) extra_dude_2 = "_____________lol__________" print(extra_dude_2.strip("_")) # different chars can be used #startswith function: It proves the starting value with boolean expression time_do_you_get_the_joke_scientist = "Hello time" print(time_do_you_get_the_joke_scientist.startswith("H")) # this function also have its opposite called endswith # and there is this split and join method,must know
import student # main functions section def addNewStudent(): def setStudentNo(): studentNo_ = input("3 reqemden ibaret telebe nomresini daxil edin: ").strip() if studentNo_.isdigit() and len(studentNo_) == 3: for s in student.userList: if s.studentNo == studentNo_: print("Bu koda sahib telebe artiq sistemde var!") return return studentNo_ else: print("Telebe nomresi dogru daxil edilmeyib!") studentNo = setStudentNo() def setName(): name_ = input("Adi daxil edin: ").strip() if len(name_) != 0: return name_ else: print("Ad bosh ola bilmez! Daxil edin.") name = "" if bool(studentNo): name = setName() def setSurname(): surname_ = input("Soyadi daxil edin: ").strip() if len(surname_) != 0: return surname_ else: print("Soyad bosh ola bilmez! Daxil edin.") surname = "" if bool(name): surname = setSurname() def setEmail(): email_ = input("Emaili daxil edin: ").strip() if email_.find("@") != -1 and len(email_) != 0: return email_ else: print("Email melumatlari dogru daxil edilmeyib! Tekarar daxil edin.") email = "" if bool(surname): email = setEmail() def setPhone(): phone_ = input("Telefon nomresini daxil edin (+994_________): ").strip() if phone_.startswith("+994") and len(phone_) == 13 and len(phone_) != 0: return phone_ else: print("Telefon nomresi dogru daxil edilmeyib! Tekrar daxil edin.") phone = "" if bool(email): phone = setPhone() if bool(studentNo) and bool(name) and bool(surname) and bool(email) and bool(phone): obj = student.Student(studentNo, name, surname, email, phone) student.userList.append(obj) def printStudents(): if len(student.userList) == 0: print("Sistemde telebe yoxdur!") else: for s in student.userList: s.printInfo() def deleteStudent(): studentNo_ = input("Silinecek telebenin kodunu daxil edin:").strip() if studentNo_.isdigit() and len(studentNo_) == 3: check = False def checkStudents(): for x in student.userList: if x.studentNo == studentNo_: return True check = checkStudents() if check: for s in student.userList: if studentNo_ == s.studentNo: student.userList.remove(s) print(f"{s.name} adli telebeye aid melumatlar sistemden ugurla silindi") else: print("Sistemde bu koda sahib telebe tapilmadi!") else: print("Telebe nomresi dogru daxil edilmeyib!") def editStudent(): studentNo = input("Melumatlarina duzelish edilecek telebenin kodunu daxil edin:").strip() if studentNo.isdigit() and len(studentNo) == 3: check = False def checkStudents(): for x in student.userList: if x.studentNo == studentNo: return True check = checkStudents() if check: for s in student.userList: if s.studentNo == studentNo: def setName(): name_ = input("Adi daxil edin: ").strip() if len(name_) != 0: return name_ else: print("Ad bosh ola bilmez! Daxil edin.") name = setName() def setSurname(): surname_ = input("Soyadi daxil edin: ").strip() if len(surname_) != 0: return surname_ else: print("Soyad bosh ola bilmez! Daxil edin.") surname = "" if bool(name): surname = setSurname() def setEmail(): email_ = input("Emaili daxil edin: ").strip() if email_.find("@") != -1 and len(email_) != 0: return email_ else: print("Email melumatlari dogru daxil edilmeyib! Tekarar daxil edin.") email = "" if bool(surname): email = setEmail() def setPhone(): phone_ = input("Telefon nomresini daxil edin (+994_________): ").strip() if phone_.startswith("+994") and len(phone_) == 13 and len(phone_) != 0: return phone_ else: print("Telefon nomresi dogru daxil edilmeyib! Tekrar daxil edin.") phone = "" if bool(email): phone = setPhone() if bool(studentNo) and bool(name) and bool(surname) and bool(email) and bool(phone): s.name = name s.surname = surname s.email = email s.phone = phone print(f"{s.studentNo} telebe koduna malik telebenin melumatlari ugurla yenilendi.") else: print("Sistemde bu koda sahib telebe tapilmadi!") else: print("Telebe nomresi dogru daxil edilmeyib! Tekrar daxil edin.") def printByName(): name = input("Telebe adini daxil edin: ").strip() check = False def checkStudents(): for x in student.userList: if name == x.name: return True check = checkStudents() if check: for s in student.userList: if name == s.name: s.printInfo() else: print("Sistemde bu ada sahib telebe tapilmadi!") # menu section def menu(): i = input(""" --------------------------------------------------------------------------- 1. Telebe daxil et 2. Telebe koduna gore telebe melumatlarini sil 3. Telebe koduna gore telebe melumatlarini deyishdir 4. Telebe adina gore telebe melumatlarini goster 5. Butun telebelerin melumatlarini goster 6. Sistemden chix Menyudaki emrleri icra etmek uhun muvafiq reqemi daxil edin: --------------------------------------------------------------------------- """).strip() if bool(i): return int(i) def showMenu(): command = menu() if command == 1: if len(student.userList) < 10: print(len(student.userList)) addNewStudent() else: print("Sistemde yeni telebe uchun yer yoxdur! Maksimum 10 telebe daxil ede bilersiz.") elif command == 2: deleteStudent() elif command == 3: editStudent() elif command == 4: printByName() elif command == 5: printStudents() elif command == 6: exit() else: print("Daxil etdiyiniz emr dogru deyil!") # App start section while True: showMenu()
N = input() if N < 60: print "Bad" elif N < 90: print "Good" elif N < 100: print "Great" else: print "Perfect"
# Get inputs from user print("Hi! I need a couple of inputs from you to make your experience jovial. So let's start then by hitting ENTER :)") name1 = input("Name: ") nickname = input("Nick Name: ") adjective1 = input("Adjective: ") verb1 = input("Verb: ") verb2 = input("Verb: ") famous_character1 = input("Famous Character: ") he_she = input("He/She: ") pronoun1 = input("Pronoun: ") noun1 = input("Noun: ") noun2 = input("Noun: ") noun3 = input("Noun: ") verb3 = input("Verb: ") adjective2 = input("Adjective: ") sound = input("Sound: ") famous_character2 = input("Famous Character: ") noun4 = input("Noun: ") paragraph = f""" Hello peeps! Let me introduce you to myself first, my name is {name1}, people often call me as {nickname}. I am a very {adjective1} person and I love to {verb1}. Although I don't {verb1} daily but I prefer to {verb1} quite often on and off basis. Have you ever heard about {famous_character1}? {he_she} is a very nice {noun1}. I used to play {noun2} with {pronoun1}. Last night I cooked {noun3} for {pronoun1} and believe me {noun1} was blown out of {verb3}. Haha...! {adjective2} right? {sound}...!!! Well.. {famous_character2} is calling me, gotta go now. Thanks for your time {noun4}! You are a lovely person. Have a great day mate! """ print(paragraph)
import math import random # string functions string = 'Monty Python' length = len(string) print("String = ",string,"\tlength = ",length) rep = string.replace('n','N') print(rep) upper = string.upper() lower = string.lower() print(upper) print(lower) # data functions character = 'A' ordchar = ord(character) char = chr(ordchar) print("Character = ",char,"\tOrd value = ",ordchar) # math functions degrees = 90 radians = math.radians(degrees) sinvalue = math.sin(radians) cosvalue = math.cos(radians) print("Degrees = ",degrees,"\tSin = ",sinvalue,"\tCos = ",cosvalue) print("Cos rounded = ",round(cosvalue,3)) #binary functions decimal = 123 binarynumber = bin(decimal) print("Decimal ",decimal,"\tBinary value ",binarynumber) hexnumber = hex(decimal) print("Decimal ",decimal,"\tHex value ",hexnumber) #exponential functions number = 2.0 exponent = 10.0 powervalue = math.pow(number,exponent) logvalue = math.log2(powervalue) print("Number = ",powervalue,"\tlog2 = ",logvalue) #random numbers rand = random.randint(0,100) print("Random value from 0 to 100 = ",rand) dice = random.randint(1,7) print("random dice value = ",dice) #accumulator sumstring = eval("1+2+3+4+5+6+7+8+9+10") print("Sum1 = ",sumstring) sumvalue = sum([1,2,3,4,5,6,7,8,9,10]) #list print("Sum2 = ",sumvalue) N = 10 sumcalc = N * (N+1) // 2 print("Sum3 = ",sumcalc)
import collections def TupleAssign(): (x,y,z) = ("python", "is", "Number 1") return x,y,z def TupleMinMax(tup): mn = min(tup) mx = max(tup) return mn,mx def TupleIndex(tup,val): y = tup.index(val) return y def TupleLen(tup): y = len(tup) return y def TupleStr(s): ts = tuple(s) return ts def TupleStar(tup): tuple2 = tup*3 return tuple2 def TuplePartition(s): print(s) tuplef = s.partition("g") tupler = s.rpartition("g") return tuplef,tupler def TupleJoin(tup): tuple2 = "--HiDeeHo--".join(tup) return tuple2 def TuplePoint(p): x = p[0] y = p[1] return x,y def TupleAlphabet(tup): alist = [] for i in range(len(tup)): alist.insert(i,chr(tup[i]+ord('a'))) return alist def sortLength(words): t = [] for word in words: t.append((len(word), word)) t.sort(reverse=True) res = [] for length, word in t: res.append((length,word)) return res def namedTupleEx(): Planet = collections.namedtuple('Planet',['name','distance','mass']) earth = Planet('Earth',1.0,1.0) mars = Planet('Mars',1.52,0.107) mercury = Planet('Mercury',0.39,0.055) venus = Planet('Venus',0.72,0.815) [print ("index[",i,"]\t",mars[i]) for i in range(len(mars))] print ("The planet name using keyname is : ",end ="") print (mercury.name) print ("The planet distance using getattr() is : ",end ="") print (getattr(venus,'distance')) print ("All the fields of the planet are: ") print (earth._fields) college = ("De", "Anza", "College") evens = (2,4,6,8,10) numbers = (0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25) pl = "Python Language" tuple1 = (44,22,13,22,45,555,32,33) sentence = ("The","quick","brown","fox","jumps","over","the","lazy","poodle") t = TupleAssign() print(t) print(*t) print('-'*25) t = TupleMinMax(tuple1) print(t) print("min = ",t[0],"\tmax = ",t[1]) print('-'*25) value = 555 t = TupleIndex(tuple1,value) print("the value of ",value," is at index ", t) print('-'*25) t = TupleLen(tuple1) print("The length of tuple1 is ",t) print('-'*25) t = TupleStr("python") print(t) print(*t) print('-'*25) t = TupleStar(numbers) print(t) print(*t) print('-'*25) t = TuplePartition(pl) print(t[0]) print(t[1]) print('-'*25) print(college) t = TupleJoin(college) print(t) print('-'*25) pointx,pointy = TuplePoint((123,234)) print("{0}X, {1}Y".format(pointx,pointy)) print('-'*25) alphabet = TupleAlphabet(numbers) print(alphabet) print(*alphabet) print('-'*25) t = sortLength(sentence) for length,word in t: print("length = {0}\tword = {1}".format(length,word)) namedTupleEx()
# Copyright (c) 2020. Adam Arthur Faizal from sys import copyright print("====== IMPLEMENTASI FUNGSI RANGE ======\n") print("--- Bagian 1 --- (Menampilkan rentang nilai)") # Menampilkan rentang nilai awal = int(input("Masukkan nilai awal : ")) akhir = int(input("Masukkan nilai akhir : ")) pembaruan = int(input("Masukkan nilai pembaruan : ")) for i in range(awal, akhir, pembaruan): print(i) pass print("\n--- Bagian 2 --- (Membangkitkan nilai dengan rentang tertentu)") # Membangkitkan nilai dengan rentang tertentu awal2 = int(input("Masukkan batas awal : ")) akhir2 = int(input("Masukkan batas akhir : ")) for i in range(awal2, akhir2): print(i) pass print("\n--- Bagian 3 --- (Memasukkan elemen list)") # Memasukkan elemen list jumlah = int(input("Masukkan jumlah elemen list : ")) print("Silahkan masukkan elemen list") Daftar = [] for i in range(jumlah): elemen = input("- ") Daftar.insert(i, elemen) pass print("Isi dari list :", Daftar) print('\n') print(copyright) # by Mbah Putih Mulyosugito
# Copyright (c) 2020. Adam Arthur Faizal from sys import copyright print("====== WHILE LOOP ======\n") angka = 0 while angka < 10: print("Nilai angka adalah :", angka) angka += 1 print("Di luar while") angka2 = 0 start = True while start: print("Nilai angka2 adalah :", angka2) angka2 += 1 if angka2 is 10: print("Oke udah sampe angka 10 nih") start = False angka3 = 0 while angka3 < 10: print("Nilai angka3 adalah :", angka3) angka3 += 1 if angka3 is 7: print("Checkpoint gais, ini nomer", angka3) # break continue # pass else: print("Nilai angka di akhir while adalah :", angka3) print("Akhir dari program") print('\n') print(copyright) # by Mbah Putih Mulyosugito
# Courses # Login/Signup # Palindrome or not? # Palindrome wo strings ya numbers hote hai jo ulta seedhe same hote hai. # Jaise, NITIN. Nitin ko aap left se padho ya right se, nitin hi hai. Aise hi MOM bhi ek # palindrome hai. Code likho jo check kare ki kya list palindrome hai ya nahi. Aur print karo # “Haan! palindrome hai” agar hai. Aur “nahi! Palindrome nahi hai” agar nahi hai. Abhi ke liye # iss list ko use kar ke code likh sakte ho: name=[ 'n', 'i', 't', 'i', 'n', ] new_list=[] i=1 while i<=len(name): new_list.append(name[-i]) i+=1 # print(new_list) if new_list==name: print("it is palindrome") else: print("it is not palindrome")
# duplicates # Duplicates # iss lists mei se duplicates nikal kar, kisi aur list mei daal kar print karne hai. a= [19, 17, 12, 17, 17, 18, 10, 17, 14, 12, 19, 17, 12, 13, 11] i=0 b=[] # count=0 while i<len(a): l=a[i] if l not in b: b.append(l) # count=count+1 i=i+1 print(b)
# Courses # Login/Signup # aao-jodein # Aao Jodein # Ek code likho jo kissi bhi list ke liye uss list ke do sum ka output karta hai, ki uss # list mei odd numbers ka sum aur even numbers ka sum kitna hai. elements = [23, 14, 56, 12, 19, 9, 15, 25, 31, 42, 43] a=[] sum1=0 i=0 sum=0 s=[] while i<len(elements): num=elements[i] if num%2==0: a.append(num) sum1=sum1+num else: s.append(num) sum=sum+num i=i+1 print("even",a,"sum",sum1) print("odd",s,"sum",sum)
# Author: Omar Shehab # Email: [email protected] # Date: May 4, 2017 # This program uses the Forest API from the Rigetti Quantum Computing # to solve a few challenge problems as a part of the interviewing process. # The author has tried to use as few quantum gates as he can. # This program is written for Goal 4. # Goal 4: Generalization. # Consider a collection of qubits in a quantum computer. Due to locality # constraints, two-qubit gates can often only be applied to neighboring # qubits, for some notion of "neighboring". This leads to a graph # structure, where edges of this graph represent where two-qubit gates # can be applied. # Using pyQuil, write a function to produce the |V|-qubit # state # (|000...0> + |111...1>) / sqrt(2) # on a graph G = (V, E). from pyquil.gates import CNOT from pyquil.gates import H from pyquil.gates import X import numpy as np from pyquil.quil import Program import pyquil.forest as forest quantum_simulator = forest.Connection() from pyquil.gates import I import itertools import goal_util import QGraph import random import networkx as nx # This function creates a planar lattice using the input graph connectivity. def run_qubit_graph(): while True: try: print "Input the number of nodes in the graph ('q' to quit): " n_in = raw_input() if n_in == 'q': print "Terminating the program..." return else: n = int(n_in) # Making sure that n is a nonzero positive integer. if n < 1: print "The number of qubits has to be at least 1." continue # edge_probability = random.random() # print "Creating a " + str(n) + "-node random graph with edge probability: " + str(edge_probability) # qgraph = QGraph.QGraph(nx.erdos_renyi_graph(n, edge_probability)) # qgraph.get_linear_chain_from_graph() print "Creating a " + str(n) + "-node comlete graph..." qgraph = QGraph.QGraph(nx.complete_graph(n)) qgraph.print_ghz_state_from_complete_graph() print "Creating a " + str(n) + "-node star graph..." qgraph = QGraph.QGraph(nx.star_graph(n - 1)) qgraph.print_ghz_state_from_star_graph() except ValueError: print "Oops! The input has to be an integer. Please try again..." except Exception as ex: print "Oops! Unknown error occured. Please try again..." template = "An exception of type {0} occurred. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) print message return
# Author: Omar Shehab # Email: [email protected] # Date: May 4, 2017 # This program uses the Forest API from the Rigetti Quantum Computing # to solve a few challenge problems as a part of the interviewing process. # The author has tried to use as few quantum gates as he can. # This program is written for Goal 3. # Goal 3: Same as Goal 2, except now the qubits you use are arranged on # the vertices of an N x N square lattice and the only two-qubit gates # available happen between neighboring qubits in the lattice, e.g. for # qubits numbered: # 6 7 8 # 3 4 5 # 0 1 2 # there is a two qubit gate allowed between (1 and 2) and (5 and 2) but # not between 2 and any other qubit. # No need to worry about implementing any kind of measurement on these states. # Just attempt to create the appropriate objects. Let me know if you have any # other questions as you approach the solution. from pyquil.gates import CNOT from pyquil.gates import H from pyquil.gates import X import numpy as np from pyquil.quil import Program import pyquil.forest as forest quantum_simulator = forest.Connection() from pyquil.gates import I import itertools import goal_util import sys class SquareLattice2D: # Constructor takes the N as input def __init__(self, dimension): # Making sure that is a nonzero positive integer. if dimension < 1: print "The number of qubits has to be at least 1." sys.exit() print "Creating " + str(dimension) + "-qubit square lattice states..." self.dimension = dimension self.program = Program() # This function applies a CNOT gate on the (row1, column1) and (row2, column2)-th qubits. def apply_CNOT_on_lattice_site(self, row1, column1, row2, column2): # Applying gate on the (row1, column1) and (row2, column2)-th qubits linear_index1 = self.get_linear_qubit_index_from_2D_coordinate(row1, column1) linear_index2 = self.get_linear_qubit_index_from_2D_coordinate(row2, column2) # Checking if these two qubits are connected. if (not self.are_connected((row1, column1), (row2, column2))): # print "Invalid pairs" return False self.program.inst(CNOT(linear_index1, linear_index2)) return True # This function applies an H gate on the (row, column)-th qubit. def apply_H_on_lattice_site(self, row, column): # Applying gate on the (row, column)-th qubit linear_index = self.get_linear_qubit_index_from_2D_coordinate(row, column) self.program.inst(H(linear_index)) return True # Create a linear chain of nearest neighbors from a square lattice. def get_linear_chain_from_square_lattice(self): chain_of_pairs = [] chain_of_qubits = [] start_qubit_of_the_row = 0 final_qubit_of_the_row = self.dimension step_of_increment = 1 finished_row_traversing = False final_row_traversed = False for row in range(self.dimension): for column in range(start_qubit_of_the_row, final_qubit_of_the_row, step_of_increment): chain_of_pairs.append((row, column)) chain_of_qubits.append(self.get_linear_qubit_index_from_2D_coordinate(row, column)) if ((column % self.dimension) == (self.dimension - 1)): if not finished_row_traversing: finished_row_traversing = True if row == self.dimension - 1: final_row_traversed = True return chain_of_pairs, chain_of_qubits row = row + 1 if row == self.dimension - 1: final_row_traversing = True start_qubit_of_the_row = self.dimension - 1 final_qubit_of_the_row = -1 step_of_increment = -1 continue else: finished_row_traversing = False continue elif (row > 0) and ((column % self.dimension) == 0): if not finished_row_traversing: finished_row_traversing = True if row == self.dimension - 1: final_row_traversed = True return chain_of_pairs, chain_of_qubits row = row + 1 start_qubit_of_the_row = 0 final_qubit_of_the_row = self.dimension step_of_increment = 1 continue else: finished_row_traversing = False continue else: print "" # Checks if the input qubit pair is a connected pair. def are_connected(self, qubit1, qubit2): # Basic validation to make sure that the coordinates are between 0 and n if qubit1[0] < 0 or qubit1[0] >= self.dimension or qubit1[1] < 0 or qubit1[1] >= self.dimension or qubit2[0] < 0 or qubit2[0] >= self.dimension or qubit2[1] < 0 or qubit2[1] >= self.dimension: print "Coordinates out of range." return False if (abs(qubit1[0] - qubit2[0]) == 1 and qubit1[1] == qubit2[1]) or (abs(qubit1[1] - qubit2[1]) == 1 and qubit1[0] == qubit2[0]): return True else: return False # Printing the latice state with probability. def print_lattice_state(self, basis_state, probability): print "Print lattice state..." lattice = [] # Location of one in the basis state. location_of_one = [i for i, letter in enumerate(basis_state) if letter == '1'] for row_count in range(self.dimension): row = ["|1>" if basis_state[self.get_linear_qubit_index_from_2D_coordinate(row_count, x)] == '1' else "|0>" for x in list(range(self.dimension))] lattice.append(row) for row in reversed(lattice): print('\t'.join(map(str, row))) print "Probability : " + str(probability) # Printing the latice. def print_lattice(self): lattice = [[]] for row_count in range(0, (self.dimension**2), self.dimension): # print "Row: " + str(row_count) row = [x + row_count for x in list(range(self.dimension))] lattice.append(row) for row in reversed(lattice): print('\t'.join(map(str, row))) # Return the 2D coordinates of the i-th qubit. The coordinate of the # bottom left qubit is 0,0. def get_2D_coordinate_from_linear_index(self, qubit): column = qubit % self.dimension row = qubit / self.dimension return (row, column) # Return the linear qubit index from 2D coordinates. The coordinate of the # bottom left qubit is 0,0. def get_linear_qubit_index_from_2D_coordinate(self, row, column): index = (row * self.dimension) + column return index # Checking if the current qubit is on the boundary. def is_boundary_qubit(self, qubit): # List of qubits on the right boundary right_boundary = [y + (self.dimension - 1) for y in [x * self.dimension for x in list(range(self.dimension))]] # List of qubits on the left boundary left_boundary = [x * self.dimension for x in list(range(self.dimension))] # Checking if the qubit is at the bottom edge. if qubit >= 0 and qubit < self.dimension: return True # Checking if the qubitis at the top edge. elif qubit >= (self.dimension * (self.dimension - 1 )) and qubit < ((self.dimension * self.dimension) - 1): return True # Checking if the qubitis at the left or right edges. elif qubit in left_boundary or qubit in right_boundary: return True else: return False def print_lattice_ghz_state(self): # Get all qubits in linear chain order. chain = self.get_linear_chain_from_square_lattice() chain_length = len(chain[1]) # Apply Hadamard gate on the first qubit p = Program(H(0)) # Run a loop to apply CNOT gate on all the consecutive pairs. for qubit1 in range(chain_length - 1): p.inst(CNOT(qubit1, qubit1 + 1)) # Print the details of the state basis_states, amplitudes, probabilities = goal_util.print_wavefunction_details(p) amplitudes.reset() probabilities.reset() for probability in probabilities: if probability == 0.0: continue self.print_lattice_state(basis_states[probabilities.iterindex], probability) print "\n" return
# On importe une librairie pour choisir un nombre aleatoire : import random # On cree une variable nombre_cacher # On y stock un nombre aleatoire en entre 0 et 100 # on fait appel a la fonction randint qui se trouve dans random nombre_cacher = random.randint(0, 100) print("Tape un nombre entre 0 et 100") entree_joueur = int( input(">>") ) if entree_joueur < nombre_cacher: print("Le nombre est petit") elif entree_joueur > nombre_cacher: print("Le nombre est grand") else : print("Bravo le nombre est bon")
import itertools from functools import reduce from typing import Set, List, Mapping from utils import NumType def get_primes_divisors(num: int) -> List[int]: prime_divisors = list() inner_num = num while inner_num % 2 == 0: prime_divisors.append(2) inner_num = int(inner_num / 2) for i in range(3, inner_num + 1, 2): while inner_num % i == 0: prime_divisors.append(i) inner_num = int(inner_num / i) return prime_divisors def get_divisors2(num: int) -> Set[int]: prime_divisors = get_primes_divisors(num) result = set([1]) for i in range(0, len(prime_divisors) + 1): for subset in itertools.combinations(prime_divisors, i): # no es óptimo if subset: result.add(reduce(lambda x, y: x*y, subset)) result.remove(num) return result def get_number_type2(num: int) -> NumType: primes_divisors = get_divisors2(num) divisors_sum = sum(primes_divisors) if divisors_sum < num: return NumType.DEFICIENT elif divisors_sum > num: return NumType.ABUNDANT return NumType.PERFECT def get_number_type_bulk2(num_list: List[int]) -> Mapping[int, NumType]: return {num: get_number_type2(num) for num in num_list if num}
todolist = [] while True: print("Welcome to my To-Do List\n") print("1)Add an item\n2)Mark an item as done\n3)View the list\n4)quit") choice = int(input("enter your choice\n")) if choice == 1: data = input("what do you want to add?") todolist.append(data) elif choice == 2: data = input("what item do you want to mark as done\n") if data in todolist: todolist.remove(data) else: print("item is not present in the list") elif choice == 3: print("To-Do List:-") i = 1 for item in todolist: print(str(i)+")", item) i += 1 elif choice == 4: exit("Bye") else: print("enter a valid option")
from xmltodict import parse import json def create_file_name(filename): """ change name from xml to json name """ sep = filename.split('.') name = './' + './' + '/' + sep[0] + '.json' return name, sep filename = input('file name(INPUT WITH .xml): ') file = open(filename).read() diction = parse(file) name, sep = create_file_name(filename) with open(name, 'w') as fp: json.dump(diction, fp, indent=4) print(sep[0] + '.json')
#!/bin/python3 import math import os import random import re import sys if __name__ == '__main__': gmail_regex = re.compile("^[a-z\.][email protected]$") gmail_accounts = dict() N = int(input().strip()) for _ in range(N): firstName, email = input().strip().split(' ') if gmail_regex.match(email): gmail_accounts[email] = firstName sorted_names = sorted(gmail_accounts.values()) print(*sorted_names, sep="\n")
############################################################ # Code for reading a textfile and calculating mean values # # Useful when calcualte the mean cross-section # ############################################################ # --data file f1name='xsec.dat' # --read file f = open(f1name,'r') lines = f.readlines() f.close() result=0 # --mean the values in each line for i in lines: result+=float(i) print f1name print result/len(lines)
from random import randint i = 0 num = randint(0, 20) for i in range(3): print(i) i += 1 answer = input("Pick a number") if (int(answer) == num): print("Congrats!") break elif (int(answer) > num): print("Guess lower.") elif (int(answer) < num): print("Guess higher.")
class Class1: def __init__(self, obj): self.obj = obj def print(self): print(self.obj.x) class Class2: def __init__(self): self.x = 5 g = Class2() h = Class1(g) h.print()
from constants import * from vector import Vector def draw_text(screen, text, color, x, y): ''' Draws a text on the desired position ''' # Puts the text into a surface text_surface = FONT.render(text, True, color) # Creates a rect object at the desired position text_rect = text_surface.get_rect() text_rect.center = (x, y) # Adds the text surface into the screen surface on the rect position screen.blit(text_surface, text_rect) class Player: ''' A player object that holds all the necessary methods ''' def __init__(self, x, y, screen): ''' Just takes in the position and the screen surface ''' self.pos = Vector(x, y) # Make the velocity 0 self.vel = Vector() self.screen = screen def move(self, y): ''' Function that moves the player by y pixels ''' self.vel.y = y def check_ball(self, ball): ''' Function that checks if the ball is colliding with the player ''' if (ball.pos.x + BALL_SIZE > self.pos.x and ball.pos.y + BALL_SIZE > self.pos.y) and ( ball.pos.x < self.pos.x + PLAYER_DIMENSIONS[0] and ball.pos.y < self.pos.y + PLAYER_DIMENSIONS[1]): return True return False def update(self, dt): ''' Function that updates the position ''' # Multiply by delta time so the game stay the same no matter the Fps self.pos += self.vel * dt # Checks if the player move too low if self.pos.y < 0: self.pos.y = 0 # Check if the player moves to high elif self.pos.y + PLAYER_DIMENSIONS[1] > WINDOW_HEIGHT: self.pos.y = WINDOW_HEIGHT - PLAYER_DIMENSIONS[1] # Reset the velocity so when the player lets go of the key, # it will stop moving self.vel *= 0 def draw(self): ''' Function that draws the player ''' pygame.draw.rect(self.screen, COLOR, pygame.Rect(self.pos.x, self.pos.y, PLAYER_DIMENSIONS[0], PLAYER_DIMENSIONS[1])) class Ball: ''' A ball object that holds all the necessary methods ''' def __init__(self, x, y, screen): ''' Just takes in the position and the screen surface ''' self.pos = Vector(x, y) # Make the velocity 0 self.vel = Vector() self.screen = screen def update(self, dt): ''' Function that updates the position ''' # Multiply by delta time so the game stay the same no matter the Fps self.pos += self.vel * dt def draw(self): ''' Function that draws the ball ''' pygame.draw.rect(self.screen, COLOR, pygame.Rect(self.pos.x, self.pos.y, BALL_SIZE, BALL_SIZE))
print(""" ************************************** ** Welcome to the Snakes Cafe! ** ** Please see our menu below. ** ** ** To quit at any time, type "quit" ** ************************************** Appetizers ---------- Wings Cookies Spring Rolls Entrees ------- Salmon Steak Meat Tornado A Literal Garden Desserts -------- Ice Cream Cake Pie Drinks ------ Coffee Tea Unicorn Tears *********************************** ** What would you like to order? ** *********************************** """) menu = ['wings', 'cookies', 'spring rolls', 'salmon', 'steak', 'meat tornado', 'a literal garden', 'ice Cream', 'cake', 'pie', 'coffee', 'tea', 'unicorn tears'] orders = [] names_of_order = [] def our_order(): order = input('please write your order >') if order.lower() in menu: orders.append(order) if order not in names_of_order: names_of_order.append(order) print( f'** {orders.count(order)} order of {order} have been added to your meal **') our_order() our_order()
import sys import random #GLOBAL VARIABLES arr_init = [] arr = [] current_line = -1 def draw(rows): width = rows*2 + 1 print('*'*width) for i in range(rows): if arr[i] < arr_init[i]: k = arr_init[i] - arr[i] else: k = 0 print('*' +' '*(rows-i-1) + '|'*arr[i]+ ' '* (rows-i-1+k)+"*") print('*'*width) def game(total, remove, rows, pvp): draw(rows) while total > 1: if pvp: total = player_turn("Player 1", remove, rows, total, pvp) else: total = player_turn("Player", remove, rows, total, pvp) if total == 1: if pvp: print("Player 1 wins!") return else: print("I lost... snif... but I'll get you next time!!") return 1 if pvp: total = player_turn("Player 2", remove, rows, total, pvp) if total == 1: print("Player 2 wins!") return else: ai = ai_turn(remove) if arr[ai[0]-1] > 0: arr[ai[0]-1] -= ai[1] total -= ai[1] draw(rows) if total == 1: print("You lost, too bad...") return 2 def player_turn(player_name, remove, rows, total, pvp): if pvp: print(player_name+"'s turn:") else: print("Your turn:") player = player_choice(remove, rows) if arr[player[0]-1] > 0: arr[player[0]-1] -= player[1] total -= player[1] print("\n"+player_name+" removed "+str(player[1]) + " match(es) from line "+str(player[0])) draw(rows) return total def player_choice(remove, rows): global current_line matches_input = "no" while matches_check(matches_input, remove) == False: line_input = input("Line: ") while line_check(line_input, rows) == False: line_input = input("Line: ") current_line = line_input matches_input = input("Matches: ") return [int(line_input), int(matches_input)] def line_check(line_input, rows): if not line_input.isdigit() or (line_input.isdigit() and int(line_input) <= 0): print("Error: invalid input (positive number expected)") return False elif not 1 <= int(line_input) <= rows or (arr[int(line_input)-1] == 0): print("Error: this line is out of range") return False else: return True def matches_check(matches_input, remove): if matches_input == "no": return False if int(matches_input) > arr[int(current_line)-1]: print("Error: not enough matches on this line") return False if int(matches_input) > remove: print("Error: you cannot remove more than "+str(remove)+" matches per turn") return False elif int(matches_input) <= 0: print("Error: you have to remove at least one match") return False else: return True def ai_turn(remove): av_rows = [] for i in range(len(arr)): if arr[i] > 0: av_rows.append(i+1) line = random.choice(av_rows) if arr[line-1] >= remove: matches = random.randint(1, remove) else: matches = random.randint(1, arr[line-1]) print("\nAI's turn...\nAI removed " + str(matches) + " match(es) from line "+str(line)) return [line, matches] def init(args): rows = "" total = 0 if args[-1] == "-pvp": pvp = True else: pvp = False if not args[1].isdigit() or not args[2].isdigit(): print("Invalid input, integers expected") return if int(args[1])>=100 or int(args[1])<=1: print("Error: number of rows must be between 1 and 100") return elif int(args[2])<=0: print("Error: number of removable matchsticks must be bigger than 0") return else: rows = int(args[1]) remove = int(args[2]) for i in range(rows): arr_init.append(2*i+1) arr.append(2*i+1) for sticks in arr: total += sticks game(total, remove, rows, pvp) init(sys.argv)
'''this piece of code shows the basic idea of polymorphism: you can see that we pass objects of different classes(duck and human) at run-time to the same function, and it performs different behaviors based on the object type. This is called polymorphism(multi-behavior)''' class duck: def talk(self): print('quack quack') class human: def talk(self): print('hello') def call_talk(obj): obj.talk() d=duck() call_talk(d) h=human() call_talk(h)
import pygame class Shape: def __init__(self, x, y, xSpeed, ySpeed, color): self.x = x self.y = y self.xSpeed = xSpeed self.ySpeed = ySpeed self.color = color def move(self): self.x = self.x + self.xSpeed self.y = self.y + self.ySpeed def show(self, surface): pygame.draw.circle(surface, self.color, (int(self.x), int(self.y)), 50) def getDistance(self, otherShape): return ((self.x - otherShape.x)**2 + (self.y - otherShape.y)**2)**.5 def getDistanceFromPoint(self, x, y): return ((self.x - x)**2 + (self.y - y)**2)**.5 def isOutOfBounds(self, width, height): outOfBounds = False if self.x < 0 and self.xSpeed < 0: outOfBounds = True if self.y < 0 and self.ySpeed < 0: outOfBounds = True if self.x > width and self.xSpeed > 0: outOfBounds = True if self.y > height and self.ySpeed > 0: outOfBounds = True return outOfBounds
from collections import defaultdict SPACE = ' ' def findRoot(employers): #finding node with no in-edges i.e not present in RHS root = list(employers.keys())[0] for key, values in employers.items(): for child in values: if child == root: root = key return root def findStruturePath(employers, depth, associate): current = employers[associate] if current == []: print(SPACE*depth, '-', associate) else: print(SPACE * depth, '-', associate) for value in current: findStruturePath(employers, depth+1, value) if __name__ == "__main__": employers = defaultdict(list) # input graph employers['aa'] = ['bb', 'cc', 'ee'] employers['cc'] = ['dd'] print(employers) root = findRoot(employers) depth = 0 struture = findStruturePath(employers, depth, root)
# First we'll import the os module # This will allow us to create file paths across operating systems import os # Module for reading CSV files import csv # path for budget data csvpath = os.path.join('Resources', 'budget_data.csv') # Variables that will be needed for the summary runningprofit = 0 currentprofit = 0 initialprofit = 0 lastprofit = 0 changeinprofit = 0 changeinprofit_sum = 0 changeinprofit_avg = 0 changeinprofit_list = [] months_list = [] with open(csvpath) as budgetfile: budgetreader = csv.reader(budgetfile, delimiter=',') # Move to next line past the header next(budgetreader) # Initialize variables with the first value in the record record = next(budgetreader) # Profit for current month currentprofit = int(record[1]) # Record Change in profit from previous month changeinprofit = currentprofit - lastprofit # This will store a running sum of all the changes in profit changeinprofit_sum += changeinprofit # Keep a list of all of the changes in profit. This will be used later for statistics on profit changes changeinprofit_list.append(changeinprofit) # Individual List of Months months_list.append(record[0]) # First Month's profit only collected from first record initialprofit = currentprofit # Set this months profit to previous month before going to next record lastprofit = currentprofit for record in budgetreader: # All variables here have the same meaning as above, but initial profit is not recorded currentprofit = int(record[1]) changeinprofit = currentprofit-lastprofit changeinprofit_sum += changeinprofit changeinprofit_list.append(changeinprofit) months_list.append(record[0]) lastprofit = currentprofit # Average Change in Profit changeinprofit_avg = changeinprofit_sum/len(changeinprofit_list) # String Construction for stdio and file header = "Financial Analysis\n"+'-'*28+'\n' months_str = f"Total Months: {len(months_list)}\n" total_str = f"Total: ${initialprofit-lastprofit}\n" avg_str = f"Average Change: ${changeinprofit_avg}\n" max_str = f"Greatest Increase in Profits: {months_list[changeinprofit_list.index(max(changeinprofit_list))]} (${max(changeinprofit_list)})\n" min_str = f"Greatest Decrease in Profits: {months_list[changeinprofit_list.index(min(changeinprofit_list))]} (${min(changeinprofit_list)})\n" # Consolidated string summary_str = header + months_str + total_str + avg_str + max_str + min_str # Print to stdio print(summary_str) # Print to file summaryfile = open("budget_summary.txt", "w") summaryfile.write(summary_str) summaryfile.close()
class Node: def __init__(self, data = '', prev = None, next = None): self.data = data self.prev = prev self.next = next class DLL(Node): def __init__(self): self.head = None self.tail = None self.current = None self.size = 0 def __str__(self): '''Returns string with all elements in the DLL''' out_str = '' n = self.head while n: out_str += str(n.data) + ' ' n = n.next return out_str def __len__(self): '''Retruns the length of the DLL''' out_int = 0 n = self.head while n: out_int += 1 n = n.next return out_int def insert(self, value): '''Inserts given value to the front of current position''' if self.current: new_node = Node(value, self.current, self.current.next) self.current.next = new_node self.current = new_node else: self.current = Node(value) self.size += 1 if self.size == 1: self.head = self.current # Set Head self.tail = self.current # Set Tail if self.current.next == None: # Check for head and tail self.tail = self.current if self.current.prev == None: self.head = self.current def remove(self): '''Removes current position's value''' if self.size <= 0: self.size = 0 return None if self.current.next == None and self.current.prev == None: # If we remove only one value self.current = None self.head = None self.tail = None elif self.current == self.head: # If current is head self.current = self.head.next self.current.prev = None self.head = self.current elif self.current == self.tail: # If current is tail self.current = self.tail.prev self.current.next = None self.tail = self.current else: self.current.next.prev = self.current.prev self.current.prev.next = self.current.next self.current = self.current.prev self.size -= 1 def get_value(self): '''Gets the value of current position''' if self.current: return str(self.current.data) def move_to_next(self): '''Moves the current position to the next''' if self.current: if self.current.next != None: self.current = self.current.next def move_to_prev(self): '''Moves the current position to the prev''' if self.current: if self.current.prev != None: self.current = self.current.prev def move_to_pos(self, position): '''Sets current position to given position''' if position < 0: position = self.size elif position > self.size: position = self.size node_at = self.head for _ in range(position - 1): node_at = node_at.next self.current = node_at def remove_all(self, value): '''Removes all value from DLL that are the sama as given value''' N = self.head while N: self.current = N if N.data == value: self.remove() # Remove N N = N.next self.current = self.head def reverse(self): '''Reverses the order of the DLL''' N = self.head while N: N_temp = N.next N.next = N.prev N.prev = N_temp N = N_temp temp_head = self.head self.head = self.tail self.tail = temp_head
import random class Pizza_slice(object): def __init__(self): self.__topings = self.add_topings() self.__ID = '' def add_topings(self): topping_list = ['Pepperoni', 'Mushrooms', 'Onions', 'Sausage', 'Bacon', 'Extra cheese', 'Black olives', 'Green peppers'] Out_put_list = [] Out_put_list.append(random.choice(topping_list)) return Out_put_list def __str__(self): return str(self.__topings) class Pizza_box(object): def __init__(self, pizza_list = []): self.__list = pizza_list pizza = Pizza_slice() print(pizza)
from tkinter import * from tkinter.colorchooser import * from tkinter.simpledialog import * ## 함수 선언 부분 ## def mouseClick(event): global x1, y1, x2, y2 x1 = event.x y1 = event.y def mouseDrop(event): global x1, y1, x2, y2, penWidth, penColor, penStyle x2 = event.x y2 = event.y if penStyle == 'c': canvas.create_oval(x1, y1, x2, y2, width=penWidth, fill=penColor) elif penStyle == 'l': canvas.create_line(x1, y1, x2, y2, width=penWidth, fill=penColor) def getColor(): global penColor color = askcolor() penColor = color[1] def getWidth(): global penWidth penWidth = askinteger("선 두께", "선 두께(1~10)를 입력하세요", minvalue = 1, maxvalue = 10) def clickCircle(): global penStyle penStyle = 'c' def clickLine(): global penStyle penStyle = 'l' ## 전역 변수 선언 부분 ## window = None canvas = None penStyle = 'l' # 'l' => line, 'c' => circle x1, y1, x2, y2 = None, None, None, None # 선의 시작점과 끝점 penColor = 'black' penWidth = 5 ## 메인 코드 부분 ## if __name__ == "__main__": window = Tk() window.title("그림판 비슷한 프로그램") canvas = Canvas(window, height = 300, width = 300) canvas.bind("<Button-1>", mouseClick) canvas.bind("<ButtonRelease-1>", mouseDrop) canvas.pack() mainMenu = Menu(window) window.config(menu = mainMenu) fileMenu = Menu(mainMenu) mainMenu.add_cascade(label = "설정", menu = fileMenu) fileMenu.add_command(label = "선 색상 선택", command = getColor) fileMenu.add_command(label = '선 두께 설정', command = getWidth) shapeMenu = Menu(mainMenu) mainMenu.add_cascade(label="도형", menu=shapeMenu) shapeMenu.add_command(label='원', command=clickCircle) shapeMenu.add_command(label='선', command=clickLine) window.mainloop()
import csv from tkinter.filedialog import * ## 우리회사 평균 연봉은? filename = askopenfilename( parent=None, filetypes=(("CSV 파일", "*.csv"), ("모든 파일", "*.*"))) csvList = [] with open(filename) as rfp: reader = csv.reader(rfp) headerList = next(reader) sum = 0 count = 0 for cList in reader: csvList.append(cList) ## 가격을 10% 인상시키기. #1. Cost 열의 위치를 찾아내기 headerList = [data.upper().strip() for data in headerList] pos = headerList.index('COST') for i in range(len(csvList)): rowList = csvList[i] cost = rowList[pos] cost = float(cost[1:]) cost *= 1.1 costStr = "${0:.2f}".format(cost) csvList[i][pos] = costStr print(csvList) ## 결과를 저장하기 saveFp = asksaveasfile(parent=None, mode='wt', filetypes=(("CSV파일", "*.csv"), ("모든파일", "*.*")), defaultextension='.csv') with open(saveFp.name, mode='w', newline='') as wFp: writer = csv.writer(wFp) writer.writerow(headerList) for row in csvList: writer.writerow(row)
'''To Do: This will be an exe, just run it to get gui and work from there. ''' import tkinter as tk from tkinter import messagebox import generator as gen #####Functions that will be used def get_evaluation(): """ get evaluation from entry fields """ dim = int(enter_dim.get()) if dim not in (1, 2, 3): messagebox.showwarning("Warning","The dimension must be 1, 2 or 3!") precision = int(enter_precision.get()) if precision<=0: messagebox.showwarning("Warning","The precision must be a positive number!") num_maps = int(enter_num_maps.get()) return (dim, num_maps, precision) def update_gui(): """ update the number of maps """ dim, num_maps, precision = get_evaluation() for widg in list(root.winfo_children())[8:]: widg.destroy() if dim == 1: for i in range(num_maps): tk.Label(root, text='Map '+str(i+1)+ ': x coord').grid(row=i+5) mapi = tk.Entry(root) mapi.grid(row=i+5, column=1) if dim == 2: for i in range(num_maps): tk.Label(root, text='Map '+str(i+1)+ ': x coord').grid(row=i+5) mapi = tk.Entry(root) mapi.grid(row=i+5, column=1) for i in range(num_maps): tk.Label(root, text='y coord').grid(row=i+5,column = 2) mapi = tk.Entry(root) mapi.grid(row=i+5, column=3) if dim == 3: for i in range(num_maps): tk.Label(root, text='Map '+str(i+1)+ ': x coord').grid(row=i+5) mapi = tk.Entry(root) mapi.grid(row=i+5, column=1) for i in range(num_maps): tk.Label(root, text='y coord').grid(row=i+5,column = 2) mapi = tk.Entry(root) mapi.grid(row=i+5, column=3) for i in range(num_maps): tk.Label(root, text='z coord').grid(row=i+5,column = 4, padx=5) mapi = tk.Entry(root) mapi.grid(row=i+5, column=5) tk.Button(root, text='Generate Fractal', command=make_pic).grid(sticky = 'w') def check_maps(map_entries): for map_func in map_entries: if len(str(map_func.get())) == 0: return True def make_pic(): """ get maps from map fields, makes a picture """ dim, num_maps, precision = get_evaluation() map_entries = list(root.winfo_children())[9:-1][::2] if check_maps(map_entries): messagebox.showwarning("Warning","Maps can't be empty!") return maps = [map_func.get() for map_func in map_entries] gen.gen_maps(maps,precision,dim) if __name__ == '__main__': #%matplotlib qt #Initial set-up root = tk.Tk() root.title("IFSGen") root.geometry("700x700") root.resizable(True, True) #Add buttons and entry boxes dynamically message= tk.Label(root, text='Welcome to IFSGen!') message.grid(row=0,columnspan=5, sticky = 'n') tk.Label(root, text='How many dimensions would you like in your IFS? (either 1, 2 or 3)').grid(row=1,sticky = 'w', columnspan = 3) enter_dim = tk.Entry(root) enter_dim.grid(row=1, column=3) enter_dim.insert(0,'2') tk.Label(root, text='How many functions would you like in your IFS?').grid(row=2,sticky = 'w', columnspan = 3) enter_num_maps = tk.Entry(root) enter_num_maps.grid(row=2, column=3) enter_num_maps.insert(0,'5') tk.Label(root, text='How many levels would you like to see? (Try 100 to start with)').grid(row=3,sticky = 'w',columnspan = 3) enter_precision = tk.Entry(root) enter_precision.grid(row=3, column=3) enter_precision.insert(0,'100') tk.Button(root, text='Update', command=update_gui).grid(row=4,sticky = 'w') for i in range(5): tk.Label(root, text='Map '+str(i+1)+ ': x coord').grid(row=i+5) mapi = tk.Entry(root) mapi.grid(row=i+5, column=1) for i in range(5): tk.Label(root, text='y coord').grid(row=i+5,column=2) mapi = tk.Entry(root) mapi.grid(row=i+5, column=3) tk.Button(root, text='Generate Fractal', command=make_pic).grid(sticky = 'w') root.mainloop()
import random def generate_cipher(): return random.sample(range(10), 4) def get_bulls_and_cows(cipher, guess): assert len(cipher) == len(guess), 'the arguments must be the same length' bulls = 0 cows = 0 for i in range(len(cipher)): if guess[i] == cipher[i]: bulls += 1 elif guess[i] in cipher: cows += 1 return bulls, cows def main_game(): bulls = 0 attempts = '' cipher = generate_cipher() print(cipher) while bulls != 4: guess = '' while len(set(guess)) != 4 or not guess.isdigit(): print('Enter your guess without spaces: ') guess = input() bulls, cows = get_bulls_and_cows(cipher, list(map(int, list(guess)))) attempts += '%s bulls: %d, cows: %d\n' % (guess, bulls, cows) print(attempts) print('Congrats, You win') # def test(): # print get_bulls_and_cows([1,2,3,4],[1,2,3,4]) == (4, 0) # print get_bulls_and_cows([1,2,3,4],[2,1,4,3]) == (0, 4) # print get_bulls_and_cows([1,2,3,4],[1,6,2,3]) == (1, 2) # print get_bulls_and_cows([1,2,3,4],[5,6,7,8]) == (0, 0) main_game()
""" 2 A Python implementation of GPS related time conversions. 3 4 Copyright 2002 by Bud P. Bruegger, Sistema, Italy 5 mailto:[email protected] 6 http://www.sistema.it 7 8 Modifications for GPS seconds by Duncan Brown 9 10 PyUTCFromGpsSeconds added by Ben Johnson 11 12 This program is free software; you can redistribute it and/or modify it under 13 the terms of the GNU Lesser General Public License as published by the Free 14 Software Foundation; either version 2 of the License, or (at your option) any 15 later version. 16 17 This program is distributed in the hope that it will be useful, but WITHOUT ANY 18 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A 19 PARTICULAR PURPOSE. See the GNU Lesser General Public License for more 20 details. 21 22 You should have received a copy of the GNU Lesser General Public License along 23 with this program; if not, write to the Free Software Foundation, Inc., 59 24 Temple Place, Suite 330, Boston, MA 02111-1307 USA 25 26 GPS Time Utility functions 27 28 This file contains a Python implementation of GPS related time conversions. 29 30 The two main functions convert between UTC and GPS time (GPS-week, time of 31 week in seconds, GPS-day, time of day in seconds). The other functions are 32 convenience wrappers around these base functions. 33 34 A good reference for GPS time issues is: 35 http://www.oc.nps.navy.mil/~jclynch/timsys.html 36 37 Note that python time types are represented in seconds since (a platform 38 dependent Python) Epoch. This makes implementation quite straight forward 39 as compared to some algorigthms found in the literature and on the web. 40 """ #-------------------- # Updated with fixes for Python 3 by Aslak Grinsted 2018 import time, math import datetime secsInWeek = 604800 secsInDay = 86400 gpsEpoch = (1980, 1, 6, 0, 0, 0) # (year, month, day, hh, mm, ss) def dayOfWeek(year, month, day): "returns day of week: 0=Sun, 1=Mon, .., 6=Sat" hr = 12 #make sure you fall into right day, middle is save t = time.mktime((year, month, day, hr, 0, 0, 0, 0, -1)) pyDow = time.localtime(t)[6] gpsDow = (pyDow + 1) % 7 return gpsDow def gpsWeek(year, month, day): "returns (full) gpsWeek for given date (in UTC)" hr = 12 #make sure you fall into right day, middle is save return gpsFromUTC(year, month, day, hr, 0, 0.0)[0] def julianDay(year, month, day): "returns julian day=day since Jan 1 of year" hr = 12 #make sure you fall into right day, middle is save t = time.mktime((year, month, day, hr, 0, 0, 0, 0, -1)) julDay = time.localtime(t)[7] # tm_yday return julDay def dateFromJulian( year, julian_day ): t0 = datetime.datetime( year, 1, 1 ) # first day of year t0 = t0 + datetime.timedelta( days=julian_day-1 ) return t0 def mkUTC(year, month, day, hour, min, sec): "similar to python's mktime but for utc" #spec = [year, month, day, hour, min, int(sec)] + [0, 0, 0] spec = datetime.datetime(year,month,day,hour,min,int(sec)).timetuple() utc = time.mktime(spec) - time.timezone return utc def ymdhmsFromPyUTC(pyUTC): "returns tuple from a python time value in UTC" ymdhmsXXX = time.gmtime(pyUTC) return ymdhmsXXX[:-3] def wtFromUTCpy(pyUTC, leapSecs=14): """convenience function: 87 allows to use python UTC times and returns only week and tow""" ymdhms = ymdhmsFromPyUTC(pyUTC) wSowDSoD = gpsFromUTC( *(ymdhms + (leapSecs,))) return wSowDSoD[0:2] def gpsFromUTC(year, month, day, hour, min, sec, leapSecs=14): """converts UTC to: gpsWeek, secsOfWeek, gpsDay, secsOfDay 95 96 a good reference is: http://www.oc.nps.navy.mil/~jclynch/timsys.html 97 98 This is based on the following facts (see reference above): 99 100 GPS time is basically measured in (atomic) seconds since 101 January 6, 1980, 00:00:00.0 (the GPS Epoch) 102 103 The GPS week starts on Saturday midnight (Sunday morning), and runs 104 for 604800 seconds. 105 106 Currently, GPS time is 13 seconds ahead of UTC (see above reference). 107 While GPS SVs transmit this difference and the date when another leap 108 second takes effect, the use of leap seconds cannot be predicted. This 109 routine is precise until the next leap second is introduced and has to be 110 updated after that. 111 112 SOW = Seconds of Week 113 SOD = Seconds of Day 114 115 N ote: Python represents time in integer seconds, fractions are lost!!! 116 """ secFract = sec % 1 epochTuple = gpsEpoch + (-1, -1, 0) t0 = time.mktime(epochTuple) t = time.mktime((year, month, day, hour, min, int(sec), -1, -1, 0)) # Note: time.mktime strictly works in localtime and to yield UTC, it should be 122 # corrected with time.timezone 123 # However, since we use the difference, this correction is unnecessary. 124 # Warning: trouble if daylight savings flag is set to -1 or 1 !!! 125 t = t + leapSecs tdiff = t - t0 gpsSOW = (tdiff % secsInWeek) + secFract gpsWeek = int(math.floor(tdiff/secsInWeek)) gpsDay = int(math.floor(gpsSOW/secsInDay)) gpsSOD = (gpsSOW % secsInDay) return (gpsWeek, gpsSOW, gpsDay, gpsSOD) def UTCFromGps(gpsWeek, SOW, leapSecs=14): """converts gps week and seconds to UTC 136 137 see comments of inverse function! 138 139 SOW = seconds of week 140 gpsWeek is the full number (not modulo 1024) 141 """ secFract = SOW % 1 epochTuple = gpsEpoch + (-1, -1, 0) t0 = time.mktime(epochTuple) - time.timezone #mktime is localtime, correct for UTC 145 tdiff = (gpsWeek * secsInWeek) + SOW - leapSecs t = t0 + tdiff (year, month, day, hh, mm, ss, dayOfWeek, julianDay, daylightsaving) = time.gmtime(t) #use gmtime since localtime does not allow to switch off daylighsavings correction!!! 149 return (year, month, day, hh, mm, ss + secFract) def GpsSecondsFromPyUTC( pyUTC, leapSecs=14 ): """converts the python epoch to gps seconds 153 154 pyEpoch = the python epoch from time.time() 155 """ t = t=gpsFromUTC(*ymdhmsFromPyUTC( pyUTC )) return int(t[0] * 60 * 60 * 24 * 7 + t[1]) def PyUTCFromGpsSeconds(gpsseconds): """converts gps seconds to the 161 python epoch. That is, the time 162 that would be returned from time.time() 163 at gpsseconds. 164 """ pyUTC #===== Tests ========================================= def testTimeStuff(): print("-"*20) print() print("The GPS Epoch when everything began (1980, 1, 6, 0, 0, 0, leapSecs=0)") (w, sow, d, sod) = gpsFromUTC(1980, 1, 6, 0, 0, 0, leapSecs=0) print("**** week: %s, sow: %s, day: %s, sod: %s" % (w, sow, d, sod)) print(" and hopefully back:") print("**** %s, %s, %s, %s, %s, %s\n" % UTCFromGps(w, sow, leapSecs=0)) print("The time of first Rollover of GPS week (1999, 8, 21, 23, 59, 47)") (w, sow, d, sod) = gpsFromUTC(1999, 8, 21, 23, 59, 47) print("**** week: %s, sow: %s, day: %s, sod: %s" % (w, sow, d, sod)) print(" and hopefully back:") print("**** %s, %s, %s, %s, %s, %s\n" % UTCFromGps(w, sow, leapSecs=14)) print("Today is GPS week 1186, day 3, seems to run ok (2002, 10, 2, 12, 6, 13.56)") (w, sow, d, sod) = gpsFromUTC(2002, 10, 2, 12, 6, 13.56) print("**** week: %s, sow: %s, day: %s, sod: %s" % (w, sow, d, sod)) print(" and hopefully back:") print("**** %s, %s, %s, %s, %s, %s\n" % UTCFromGps(w, sow)) def testJulD(): print("testJulD()") print('2002, 10, 11 -> 284 ==??== ', julianDay(2002, 10, 11)) print(" ") def testGpsWeek(): print("testGpsWeek()") print('2002, 10, 11 -> 1187 ==??== ', gpsWeek(2002, 10, 11)) print(" ") def testDayOfWeek(): print("testDayOfWeek()") print('2002, 10, 12 -> 6 ==??== dayOfWeek = ', dayOfWeek(2002, 10, 12)) print('2002, 10, 6 -> 0 ==??== dayOfWeek =', dayOfWeek(2002, 10, 6)) print(" ") def testNow(): now = datetime.datetime.now() - datetime.timedelta(days=2) #now = datetime.datetime(2014,2,23 ) # doy 54 print("testNow()") print(" now = ", now) print(" Julian day = ", julianDay( now.year, now.month, now.day )) print(" GPS week = ", gpsWeek( now.year, now.month, now.day)) print(" GPS day of week = ", dayOfWeek( now.year, now.month, now.day)) print(" date from Julian= ", dateFromJulian( now.year, julianDay(now.year, now.month, now.day) )) print('2002, 10, 6 -> 0 ==??== dayOfWeek =', dayOfWeek(2014, 1, 9)) def testPyUtilties(): print("testDayOfWeek()") ymdhms = (2014, 1, 9, 8, 34, 12.3) print("testing for: ", ymdhms) pyUtc = mkUTC(*ymdhms) back = ymdhmsFromPyUTC(pyUtc) print("yields : ", back) #*********************** !!!!!!!! #assert(ymdhms == back) 208 #! TODO: this works only with int seconds!!! fix!!! (w, t) = wtFromUTCpy(pyUtc) print("week and time: ", (w,t)) print(" ") #===== Main ========================================= if __name__ == "__main__": pass testTimeStuff() testGpsWeek() testJulD() testDayOfWeek() testPyUtilties() testNow()
#sorting numpy array import numpy as np; #single dim array sd=np.array([100,20,45,90,44,10,25]); print(np.sort(sd)); #sorting in ascending order print(np.sort(sd)[::-1]);#sorting and slicing in reverse direction (desc order) print("__________________________________________________________"); md=np.array([[20,10,5],[40,22,34],[90,94,2]]); print(md); print(np.sort(md));#will sort the rows print(md); print(np.sort(md,axis=None));#will sort and generate list of sorted element print(np.sort(md,axis=1));#will sort row wise print(np.sort(md,axis=0));#will sort column wise
#asarray function is like array #it can create an ndarray from list,tuple etc import numpy as np; list=[10,20,30]; tuple=(40,50,60,70); npa1=np.asarray(list); npa2=np.asarray(tuple); npa3=np.asarray(tuple,dtype=float); print(npa1); print(npa2); print(npa3);
from array import array tab = array('i', [1, 3, 5, 7, 9]) for i in range (0,len(tab)): print(tab[i]) def somme(tab): somme = 0 for i in range (0,len(tab)): somme += tab[i] return somme print("somme : ", somme(tab))
#!/usr/bin/env python3 # -*- coding:utf-8 -*- import numpy as np arr1 = np.array([1, 2, 3]) # 共享一块内存 arr2 = arr1 arr2[0] = 5 print(arr1) print(arr2) # [5 2 3] # [5 2 3] # 深拷贝 arr3 = arr1.copy() arr3[0] = 6 print(arr1) print(arr3) # [5 2 3] # [6 2 3]
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # 生成随机数的方式 import numpy as np # 生成3行2列从0到1的随机数 sample = np.random.random((3, 2)) print(sample) # [[0.94800964 0.91867228] # [0.3680591 0.14434706] # [0.33398542 0.50719141]] # 生成3行2列符合标准正态分布的随机数 sample2 = np.random.normal(size=(3, 2)) print(sample2) # [[ 0.22708609 -0.79131841] # [ 0.66393757 -0.18234665] # [ 0.98113021 0.93463262]] # 生成3行2列从0到10的随机整数 sample3 = np.random.randint(0, 10, size=(3, 2)) print(sample3) # [[4 7] # [5 9] # [6 2]] # 矩阵求和 print(np.sum(sample3)) # 33 # 矩阵求最小值 print(np.min(sample3)) # 2 # 矩阵求最大值 print(np.max(sample3)) # 9 # 矩阵列求和 print(np.sum(sample3, axis=0)) # [15 18] # 矩阵行求和 print(np.sum(sample3, axis=1)) # [11 14 8] # 矩阵最小值的索引 print(np.argmin(sample3)) print(sample3.argmin()) # 5 # 5 # 矩阵最大值的索引 print(np.argmax(sample3)) print(sample3.argmax()) # 3 # 3 # 矩阵所有元素的平均值 print(np.mean(sample3)) print(sample3.mean()) # 5.5 # 5.5 # 求所有元素的中位数 print(np.median(sample3)) # 5.5 # 求所有元素开方 print(np.sqrt(sample3)) # [[2. 2.64575131] # [2.23606798 3. ] # [2.44948974 1.41421356]] sample4 = np.random.randint(0, 10, size=(1, 10)) print(sample4) # [[7 4 1 1 7 6 3 3 7 2]] # 随机数排序 print(np.sort(sample4)) # [[1 1 2 3 3 4 6 7 7 7]] # 矩阵每一行排序 print(np.sort(sample)) # [[0.91867228 0.94800964] # [0.14434706 0.3680591 ] # [0.33398542 0.50719141]] # 小于2的变成2,大于7的变成7, 控制数字范围 print(np.clip(sample4, 2, 7)) # [[7 4 2 2 7 6 3 3 7 2]]
#Ex 4.1 #a def print_list(elements): print(elements) #b def print_reverse(elements): print(list(reversed(elements))) #c def len_function(elements): count = 0 for index in elements: count += 1 return count #Ex 4.2 def set_first_elem_to_zero(l): l[0] = 0 return l #Ex 4.4 def set_index_value_to_zero(l, index): l[index] = 0 #Ex 4.7 def myfilter(age): if (age < 18): return False return True #Ex 4.9 def longest_word_in_text(text): punctuation = [',', '?', '!', '.'] words = text.split() word_length = 0 longest_word = None for word in words: # remove punctuation word = [x for x in word if x not in punctuation] # check if longest if (word_length < len(word)): longest_word = word word_length = len(word) return ''.join(longest_word) #Ex 4.10 def collatz_as_list(n): FLAG = 1 collatz = [] x = n collatz.append(x) while(x != FLAG): if (x%2 == 0): x = x//2 else: x = 3*x +1 collatz.append(x) return collatz def longest_collatz(n): maximumValue = 0 maxNum = 0 for x in range (1, n): if (len(collatz_as_list(x))> maximumValue): maximumValue = len(collatz_as_list(x)) maxNum = x return maxNum #Ex 4.11 def pivots (x, y): output_list =[] for value in y: if (value < x): output_list.append(value) y.remove(value) output_list.append(x) for value in y: output_list.append(value) return output_list #Ex 4.12 def primes(n): primelist = lambda n : [x for x in range(2, n) if not 0 in map(lambda z : x % z, range(2,x))] return (primelist(n)) if __name__== "__main__": animals = ['cat', 'dog', 'fish', 'bison'] names = ['Eli', 'Karin', 'Dana', 'Eden'] print_list(animals) print_reverse(animals) print(len_function(animals)) #Ex 4.2 b = animals b[1] = 'cow' print (animals) #dog changed to cow because both b and animals point to the same place print(b) c= animals[:] c[2] = 'donkey' print (animals) #didn't changed because c is a copy of animals = new variable print (c) print(set_first_elem_to_zero(animals)) print(animals) # the original list also changed #Ex 4.3 a = [[]] * 3 b = [[] for _ in range(3)] print (a) print (b) #Ex 4.4 print(names) set_index_value_to_zero(names, 1) print(names) #Ex 4.7 print ("With my filter: ") ages = [5, 12, 17, 18, 24, 32] adults = filter(myfilter, ages) for x in adults: print(x) print ("Now without filter: ") adults_noFilter = [x for x in ages if x >= 18] print (adults_noFilter) #Ex 4.8 double_list = [[1,3], [5], [3,6]] no_sub_list = [] for element in double_list: if len(element) >= 1: for sub_element in element: no_sub_list.append(sub_element) print (no_sub_list) #Ex 4.9 print(longest_word_in_text("Hello, how was the football match earlier today???")) #Ex 4.10 print(collatz_as_list(5)) # answer: [5, 16, 8, 4, 2, 1] print(longest_collatz(5)) # answer: 3 #Ex 4.11 print(pivots(3, [6, 4, 1, 7])) #Ex 4.12 print(primes(12))
texto = "oi, eu sou a Urias" print(len(texto)) print(texto.upper()) print(texto.lower()) print(texto.capitalize()) print(texto.title())
#O programa pede para o usuário dois numeros e realiza a soma deles numero1 = int(input("Informe um valor:")) numero2 = int(input("Informe outro valor:")) resultado = numero1 + numero2 print("O resultado da soma é:", resultado)
entrada = "Pabllo;Urias;McTha;Dudinha" #Estrutura for for nome in entrada.split(";"): print(nome.upper())
#Fatiamento de string palavra = "Victoria Medej" #Para mostrar apenas uma letra da palavra (Ver a posição da letra) letra = palavra[3] print(letra) #Para mostrar um conjuto de letras de uma string letras = palavra[0:5] print(letras) #Para mostrar da posição escolhida até o final letras = palavra[5:] print(letras) #Para mostrar da posição escolhida até o começo letras = palavra[:11] print(letras)
#Programa valor = 0 contador = 0 while contador < 7: valor = valor + (valor / 2) + 4 if valor % 2 == 0: print (valor) else: print (valor//2) contador = contador + 1 #Resposta 4 10 9 16 26 41 64
print("Olá mundo!") #Isso é um comentário e não sera executado #A função input() sempre retorna uma string/texto nome = input("Digite o seu nome: ") print("Olá", nome)
valor_total = float(input("Informe o valor do produto: ")) quantidade_parcelas = int(input("Informe a quantidade de parcelas: ")) if quantidade_parcelas == 1: valor_final = valor_total * 0.9 elif quantidade_parcelas == 2: valor_final = valor_total elif quantidade_parcelas == 3: valor_final = valor_total * 1.05 else: valor_final = valor_total * 1.2 print("O valor final da compra é R$ %.2f, em %i vezes." % (valor_final, quantidade_parcelas))
#Estrutura de repetição numero_secreto = 13 acertou = False while acertou == False: chute = int(input("Informe seu chute: ")) if chute > numero_secreto: print("O número é menor") elif chute < numero_secreto: print("O número é maior") else: acertou = True print("Acertou!") print("Obrigada por jogar!")
numero1 = int (input ("informe um numero: ")) numero2 = int (input ("informe outro numero: ")) soma = numero1+numero2 print ("o resultado é: ", soma)
import tkinter import random window = tkinter.Tk() def Random_Number(): My_Random = random.randint(1,20) dice_thrown.configure(text = "Rolled: " + str(My_Random)) MyTitle = tkinter.Label(window, text = "DnD Dice Roller", font = "Arial 16") MyTitle.pack() MyButton = tkinter.Button(window, text = "Roll", command = Random_Number) MyButton.pack() dice_thrown = tkinter.Label(window, font = "Arial 16") dice_thrown.pack() window.mainloop()
# -*- coding: utf-8 -*- """ Created on Tue Jan 22 16:47:12 2019 @author: harsh """ #Program to reverse the string o(n) def reverseString(s1): print(len(s1)) reverse="" for i in range(0,len(s1)): reverse=s1[i]+reverse print(reverse) reverseString('Harsa') #Duplicates alphabets of string: def duplicates(s2): d={} count=0 for i in range(1,len(s2)): if s2[i] not in d: d.update({s2[i]:count}) else: d.update({s2[i]:count+1}) print(d) for key,value in d.items(): print(d.values()) duplicates('Harsha') #Anagrams: def anagrams(s1,s2): count=0 count1=0 d1={} d2={} for i in range(0,len(s1)): if i not in d1: d1.update({s1[i]:count}) else: d1 for i in range(0,len(s2)): if i not in d2: d2.update({s2[i]:count1}) else: d2.update({s2[i]:count1+1}) print(d1,d2) if(d1==d2): print('Anagrams'); else: print('No anagrams') anagrams("aba","baaa") #count of letters in words: def letters(s1): count=0 d1={} for i in range(0,len(s1)): if i not in d1: d1.update({s1[i]:count}) else: d1.update({s1[i]:count+1}) print(d1) for key,value in d1.items(): print(d1.values()) letters("Harshavardhan") s={'a':1} print(s.get(s,0)) def reverseString(s): start=0 end=len(s)-1 while(start<end): s[start],s[end]=s[end],s[start] start=start+1 end=end-1 print(s) reverseString(['h','v','a'])
# -*- coding: utf-8 -*- """ Created on Wed Sep 15 11:33:03 2021 @author: karth """ # Create class "Patient" class Patient: # Constructor def __init__(self, name, bloodgrp, address, branch): self.name = name self.bloodgrp = bloodgrp self.address = address self.branch = branch # Function to create and append new Patient def accept(self, Name, bloodgrp, address, branch ): # use ' int(input()) ' method to take input from user ob = Patient(Name, bloodgrp, address, branch ) ls.append(ob) # Function to display Patient details def display(self, ob): print("Name : ", ob.name) print("bloodgrp : ", ob.bloodgrp) print("address : ", ob.address) print("branch : ", ob.branch) print("\n") # Search Function def search(self, bloodgrp): for i in range(ls.__len__()): if(ls[i].bloodgrp == bloodgrp): return i # Delete Function def delete(self, bloodgrp): i = obj.search(bloodgrp) del ls[i] # Create a list to add Patients ls =[] # an object of Patient class obj = Patient('D', "A_n", "147_2_2", "XYZ") print("\nOperations used, ") print("\n1.Accept Patient details\n2.Display Patient Details\n" "3.Search Details of a Patient\n4.Delete Details of Patient" "\n6.Exit") # ch = int(input("Enter choice:")) # if(ch == 1): obj.accept("A", "A_p", "159_f", "XYZ_A") obj.accept("B", "O_p", "189_1_4", "XYZ_B") obj.accept("C", "AB_n", "145_8", "XYZ_C") # elif(ch == 2): print("\n") print("\nList of Patients\n") for i in range(ls.__len__()): obj.display(ls[i]) # elif(ch == 3): print("\n Patient Found, ") s = obj.search("A_p") obj.display(ls[s]) # elif(ch == 4): obj.delete("AB_n") print(ls.__len__()) print("List after deletion") for i in range(ls.__len__()): obj.display(ls[i]) # else: print("Thank You !")
def minCutsPalindrome(string): n = len(string) # dp for palindrome. pal[i][j] is true if string[i] to string[j] is a palindrome pal = [[False]*n for i in range(n)] for i in range(n): pal[i][i] = True # dp for mincuts. cuts[i][j] stores minimum cuts needed for string[i] to string[j] cuts = [[float('inf')]*n for i in range(n)] # calculate pal and cuts for substrings of length k in bottom up fashion for k in range(2, n+1): for i in range(0, n-k+1): j = i + k - 1 if k == 2: pal[i][j] = string[i] == string[j] else: pal[i][j] = (string[i] == string[j]) and pal[i+1][j-1] if pal[i][j]: cuts[i][j] = 0 else: for c in range(i, j): cuts[i][j] = min(cuts[i][j], cuts[i][c] + cuts[c+1][j] + 1) return cuts[0][n-1] print(minCutsPalindrome('ababbbabbababa'))
my_list=[5,10,15] print(list(map(lambda i: i*i, my_list))) #square bitches lingo=[(0,2),(4,3),(10,-1)] # sorting a tuple or dictorinary!!! lingo.sort(key=lambda x: x[1]) print(lingo)
class Pets(): animals = [] def __init__(self, animals): self.animals = animals def walk(self): for animal in self.animals: print(animal.walk()) class Cat(): is_lazy = True def __init__(self, name, age): self.name = name self.age = age def walk(self): return f'{self.name} is walking around' class Ember(Cat): def sing(self, sounds): return f'{sounds}' class Remy(Cat): def sing(self, sounds): return f'{sounds}' class Olive(Cat): def sing(self, sounds): return f'{sounds}' my_cats = [Ember('Ember', 3), Remy('Remy', 1), Olive('Olive', 4)] my_pets = Pets(my_cats) my_pets.walk()
# dummy import example # import statement does not require .py extension # a folder containing modules is called a package # the files in the folder are called modules # imported as module import utility # imported as package.module import ex_folder.multiply # another way to write this is # import * will import all functions # from ex_folder.multiply import * # utilized as module.function print(utility.addition(2,3)) print(utility.subtraction(2,3)) # utilized as package.module.function print(ex_folder.multiply.multiply(2,3)) # package may be assigned as a variable for QOL multi = ex_folder.multiply.multiply print(multi(3,6)) # individual functions may be imported from a package from ex_folder.multiply import divide # multiple functions may be imported from one package in one line from ex_folder.multiply import multiply, divide # the imported function is written as if it is based in this module print(divide(3,6)) if __name__ == '__main__': print('You are running the main')
# range() # return an object that produces a sequence # of intergers from start to stop for number in range(0, 10): print(number) for _ in range(10, 0, -1): print(list(range(10)))
# walrus operator # := # assigns values to variables as part # of a larger expression a = 'hello' if (len(a) > 4): print(f'too long {len(a)} elements') # using the walrus operator if ((n := len(a)) > 4): print(f'too long {n} elements') while ((n := len(a)) > 1): print(n) a = a[:-1] print(a)
# built in functions print(len('012345678')) # -> 9 greet = "hello" print(greet[0:len(greet)]) # methods # methods that can be used only on strings # .format() # this is a method quote = 'to be or not to be' print(quote.upper()) print(quote.capitalize()) print(quote.find('be')) # -> 3 finds index print(quote.replace('be', 'me')) # replaces word in string print(quote) # prints inital string -- strings are immutable quote2 = quote.replace('be', 'me') print(quote2) # prints replaced quote
# error handling # errors in python # an error that crashes a program is called an exception # SyntaxError denotes a non standard python syntax error # NameError denotes a name or variable that is undefined # IndexError indicates an index is nonexistant # KeyError indicates a key in a dictionary that does not exist # ZeroDivisionError shows when you attempt to divide by zero # error handling in python while True: try: # attempt to run this code age = int(input('How old are you? \n')) print(f'You are {age} years old') # raise ValueError('An error has occured') # will allow python error to display | will need to remove the ValueError except block except ValueError: # if an error occurs in the try block, do this print('Please enter a number') continue except ZeroDivisionError: # specific error dependant print('Please enter a value above 0') break else: # break out of loop if try is accepted print('Thank you') def sum(num1, num2): try: return num1 + num2 except (TypeError, ZeroDivisionError) as err: # combining and displaying errors print(f'Something went wrong...\nError: {err}') print(sum('1', 2))
# dictionary # dict # dictionary = { # 'KEY': VALUE, # 'KEY': VALUE # } # dictionary keys may be expressed as int str bool # they must be immutable # keys must be unique # if keys are not unique, the latter value will override dictionary = { 'a': 1, 'b': 2, 'c': 3 } print(dictionary['b']) # prints VALUE at KEY b dictionary_2 = { 'a': [1,2,3], 'b': 'hello', 'c': True } # valid syntax dictionary_3 = [ { 'a': [1,2,3], 'b': 'hello', 'c': True }, { 'a': [4,5,6], 'b': 'goodbye', 'c': False } ] print(dictionary_3[0]['a'][1]) user = { 'name': 'John', 'location': 'Canada' } print(user.get('age')) # -> none no value is assigned print(user.get('age', 30)) # -> 30 will assign value if not found # another way to create dictionaries user_2 = dict(name='Kevin') print(user_2) # in print('name' in user) # -> true print('Canada' in user.keys()) # -> false print('Canada' in user.values()) # -> true print(user.items()) user_3 = user.copy() # copies user dictionary print(user.clear()) # removes dictionary print(user_3) print(user_3.pop('location')) print(user_3.popitem()) print(user_3) print(user_3.update({'age': 50})) print(user_3)
n = int(input()) string = input() o_number = 0 zeros = 0 ones = 0 ans = "" for char in string: if char == 'o': o_number += 1 elif char == 'z': zeros += 1 ones = o_number - zeros while ones > 0 or zeros > 0: if ones: ans += "1 " ones -= 1 elif zeros: ans += "0 " zeros -= 1 print(ans)
n = int(input()) ans = "" for current in range(1, n+1): if current % 2 == 1: ans += "I hate " else: ans += "I love " if current == n: ans += "it" else: ans += "that " print(ans)
#!/usr/bin/python # # 12tweet - tiny little robots that live in the twittersphere # Created by Jeff Verkoeyen @featherless # # The brains of a basic twitter bot. Does little more than print # all tweets for the given twitter user. # import twitterbot import random class Bot(twitterbot.StandardBot): '''A generic twitter bot. ''' def __init__(self): twitterbot.StandardBot.__init__(self, dbuser = "12tweet", dbpass = "12tweet21r!", dbdb = "12tweet", twituser = '12tweetbot', twitpass = '12tweet21r!') def execute(self): # Fetch all tweets since our last commit. tweets = self.getTweets() # Commit our tweets right away. If there are any errors in code following # this, we won't run into an infinite loop of tweets being pulled. # You might choose to commit the tweets at a later point, however. self.commitTweets() if len(tweets) == 1: print str(len(tweets)) + " new tweet" elif len(tweets) > 1: print str(len(tweets)) + " new tweets" for tweet in tweets: if tweet.user.screen_name in self.existing_users: print tweet.user.screen_name+": " + tweet.text else: # Someone who isn't following us has sent us a reply. print "I don't know this person: " + tweet.user.screen_name
Exercise 1 print("Hello, World!") Exercise 2 mystring = "hello" myfloat = 10.0 myint = 20 if mystring == "hello": print("String: %s" % mystring) if isinstance(myfloat, float) and myfloat == 10.0: print("Float: %f" % myfloat) if isinstance(myint, int) and myint == 20: print("Integer: %d" % myint) Exercise 3 numbers = [] strings = [] names = ["John", "Eric", "Jessica"] # write your code here numbers.append(1) numbers.append(2) numbers.append(3) strings.append("hello") strings.append("world") second_name = names[1] # this code should write out the filled arrays and the second name in the names list (Eric). print(numbers) print(strings) print("The second name on the names list is %s" % second_name) Exercise 4
""" Module to manage AFW (Alternating Finite automaton on Words). Formally a AFW (Alternating Finite automaton on Words) is a tuple :math:`(Σ, S, s0, ρ, F )`, where: • Σ is a finite nonempty alphabet; • S is a finite nonempty set of states; • :math:`s0 ∈ S` is the initial state (notice that, as in dfas, we have a unique initial state); • F ⊆ S is the set of accepting states; • :math:`ρ : S × Σ → B+(S)` is a transition function. :math:`B+(X)` be the set of positive Boolean formulas over a given set X ex. of :math:`ρ: ρ(s, a) = (s1 ∧ s2) ∨ (s3 ∧ s4)` In this module a AFW is defined as follows AFW = dict() with the following keys-values: • alphabet => set() • states => set() • initial_state => 'state_0' • accepting_states => set() • transitions => dict(), where **key** (state ∈ states, action ∈ alphabet) **value** [string representing a PYTHON boolean expression over states; where we also allow the formulas *True* and *False*] """ from PySimpleAutomata import NFA import itertools import re from copy import deepcopy def __recursive_acceptance(afw, state, remaining_word): """ Recursive call for word acceptance. :param dict afw: input AFW; :param str state: current state; :param list remaining_word: list containing the remaining words. :return: *(bool)*, True if the word is accepted, false otherwise. """ # the word is accepted only if all the final states are # accepting states if len(remaining_word) == 0: if state in afw['accepting_states']: return True else: return False action = remaining_word[0] if (state, action) not in afw['transitions']: return False if afw['transitions'][state, action] == 'True': return True elif afw['transitions'][state, action] == 'False': return False transition = (state, action) # extract from the boolean formula of the transition the # states involved in it involved_states = list( set( re.findall(r"[\w']+", afw['transitions'][transition]) ).difference({'and', 'or', 'True', 'False'}) ) possible_assignments = set( itertools.product([True, False], repeat=len(involved_states))) # For all possible assignment of the the transition (a # boolean formula over the states) for assignment in possible_assignments: mapping = dict(zip(involved_states, assignment)) # If the assignment evaluation is positive if eval(afw['transitions'][transition], mapping): ok = True mapping.pop('__builtins__') # removes useless entry # added by the function eval() # Check if the word is accepted in ALL the states # mapped to True by the assignment for mapped_state in mapping: if mapping[mapped_state] == False: continue if not __recursive_acceptance(afw, mapped_state, remaining_word[1:]): # if one positive state of the assignment # doesn't accepts the word,the whole # assignment is discarded ok = False break if ok: # If at least one assignment accepts the word, # the word is accepted by the afw return True return False def afw_word_acceptance(afw: dict, word: list) -> bool: """ Checks if a **word** is accepted by input AFW, returning True/False. The word w is accepted by a AFW if exists at least an accepting run on w. A run for AFWs is a tree and an alternating automaton can have multiple runs on a given input. A run is accepting if all the leaf nodes are accepting states. :param dict afw: input AFW; :param list word: list of symbols ∈ afw['alphabet']. :return: *(bool)*, True if the word is accepted, False otherwise. """ return __recursive_acceptance(afw, afw['initial_state'], word) # Side effect on input afw def afw_completion(afw): """ Side effect on input! Complete the afw adding not present transitions and marking them as False. :param dict afw: input AFW. """ for state in afw['states']: for a in afw['alphabet']: if (state, a) not in afw['transitions']: afw['transitions'][state, a] = 'False' return afw def nfa_to_afw_conversion(nfa: dict) -> dict: """ Returns a AFW reading the same language of input NFA. Let :math:`A = (Σ,S,S^0, ρ,F)` be an nfa. Then we define the afw AA such that :math:`L(AA) = L(A)` as follows :math:`AA = (Σ, S ∪ {s_0}, s_0 , ρ_A , F )` where :math:`s_0` is a new state and :math:`ρ_A` is defined as follows: • :math:`ρ_A(s, a)= ⋁_{(s,a,s')∈ρ}s'`, for all :math:`a ∈ Σ` and :math:`s ∈ S` • :math:`ρ_A(s^0, a)= ⋁_{s∈S^0,(s,a,s')∈ρ}s'`, for all :math:`a ∈ Σ` We take an empty disjunction in the definition of AA to be equivalent to false. Essentially, the transitions of A are viewed as disjunctions in AA . A special treatment is needed for the initial state, since we allow a set of initial states in nondeterministic automata, but only a single initial state in alternating automata. :param dict nfa: input NFA. :return: *(dict)* representing a AFW. """ afw = { 'alphabet': nfa['alphabet'].copy(), 'states': nfa['states'].copy(), 'initial_state': 'root', 'accepting_states': nfa['accepting_states'].copy(), 'transitions': dict() } # Make sure "root" node doesn't already exists, in case rename it i = 0 while afw['initial_state'] in nfa['states']: afw['initial_state'] = 'root' + str(i) i += 1 afw['states'].add(afw['initial_state']) for (state, action) in nfa['transitions']: boolean_formula = str() for destination in nfa['transitions'][state, action]: boolean_formula += destination + ' or ' # strip last ' or ' from the formula string boolean_formula = boolean_formula[0:-4] afw['transitions'][state, action] = boolean_formula if state in nfa['initial_states']: afw['transitions'][afw['initial_state'], action] = boolean_formula return afw def afw_to_nfa_conversion(afw: dict) -> dict: """ Returns a NFA reading the same language of input AFW. Let :math:`A = (Σ, S, s^0 , ρ, F )` be an afw. Then we define the nfa :math:`A_N` such that :math:`L(A_N) = L(A)` as follows :math:`AN = (Σ, S_N , S^0_N , ρ_N , F_N )` where: • :math:`S_N = 2^S` • :math:`S^0_N= \{\{s^0 \}\}` • :math:`F_N=2^F` • :math:`(Q,a,Q') ∈ ρ_N` iff :math:`Q'` satisfies :math:`⋀_{ s∈Q} ρ(s, a)` We take an empty conjunction in the definition of :math:`ρ_N` to be equivalent to true; thus, :math:`(∅, a, ∅) ∈ ρ_N`. :param dict afw: input AFW. :return: *(dict)* representing a NFA. """ nfa = { 'alphabet': afw['alphabet'].copy(), 'initial_states': {(afw['initial_state'],)}, 'states': {(afw['initial_state'],)}, 'accepting_states': set(), 'transitions': dict() } # State of the NFA are composed by the union of more states of the AFW boundary = deepcopy(nfa['states']) possible_assignments = set( itertools.product([True, False], repeat=len(afw['states']))) while boundary: state = boundary.pop() # The state is accepting only if composed exclusively of final states if set(state).issubset(afw['accepting_states']): nfa['accepting_states'].add(state) for action in nfa['alphabet']: boolean_formula = 'True' # join the boolean formulas of the single states given the action for s in state: if (s, action) not in afw['transitions']: boolean_formula += ' and False' else: boolean_formula += \ ' and (' + \ afw['transitions'][s, action] + \ ')' for assignment in possible_assignments: mapping = dict(zip(afw['states'], assignment)) # If the formula is satisfied if eval(boolean_formula, mapping): # add the transition to the resulting NFA evaluation = \ tuple(k for k in mapping if mapping[k] is True) if evaluation not in nfa['states']: nfa['states'].add(evaluation) boundary.add(evaluation) nfa['transitions'].setdefault( (state, action), set()).add(evaluation) return nfa def formula_dual(input_formula: str) -> str: """ Returns the dual of the input formula. The dual operation on formulas in :math:`B^+(X)` is defined as: the dual :math:`\overline{θ}` of a formula :math:`θ` is obtained from θ by switching :math:`∧` and :math:`∨`, and by switching :math:`true` and :math:`false`. :param str input_formula: original string. :return: *(str)*, dual of input formula. """ conversion_dictionary = { 'and': 'or', 'or': 'and', 'True': 'False', 'False': 'True' } return re.sub( '|'.join(re.escape(key) for key in conversion_dictionary.keys()), lambda k: conversion_dictionary[k.group(0)], input_formula) def afw_complementation(afw: dict) -> dict: """ Returns a AFW reading the complemented language read by input AFW. Let :math:`A = (Σ, S, s^0 , ρ, F )`. Define :math:`Ā = (Σ, S, s^0 , \overline{ρ}, S − F )`, where :math:`\overline{ρ}(s, a) = \overline{ρ(s, a)}` for all :math:`s ∈ S` and :math:`a ∈ Σ`. That is, :math:`\overline{ρ}` is the dualized transition function. It can be shown that :math:`L( Ā) = Σ^∗ − L(A)`. The input afw need to be completed i.e. each non existing transition must be added pointing to False. :param dict afw: input AFW. :return: *(dict)* representing a AFW. """ completed_input = afw_completion(deepcopy(afw)) complemented_afw = { 'alphabet': completed_input['alphabet'], 'states': completed_input['states'], 'initial_state': completed_input['initial_state'], 'accepting_states': completed_input['states'].difference(afw['accepting_states']), 'transitions': dict() } for transition in completed_input['transitions']: complemented_afw['transitions'][transition] = \ formula_dual(completed_input['transitions'][transition]) return complemented_afw def __replace_all(repls: dict, input: str) -> str: """ Replaces from the string **input** all the occurrence of the keys element of the dictionary **repls** with their relative value. :param dict repls: dictionary containing the mapping between the values to be changed and their appropriate substitution; :param str input: original string. :return: *(str)*, string with the appropriate values replaced. """ return re.sub('|'.join(re.escape(key) for key in repls.keys()), lambda k: repls[k.group(0)], input) # SIDE EFFECTS def rename_afw_states(afw: dict, suffix: str): """ Side effect on input! Renames all the states of the AFW adding a **suffix**. It is an utility function used during testing to avoid automata to have states with names in common. Avoid suffix that can lead to special name like "as", "and",... :param dict afw: input AFW. :param str suffix: string to be added at beginning of each state name. """ conversion_dict = {} new_states = set() new_accepting = set() for state in afw['states']: conversion_dict[state] = '' + suffix + state new_states.add('' + suffix + state) if state in afw['accepting_states']: new_accepting.add('' + suffix + state) afw['states'] = new_states afw['initial_state'] = '' + suffix + afw['initial_state'] afw['accepting_states'] = new_accepting new_transitions = {} for transition in afw['transitions']: new_transition = __replace_all(conversion_dict, transition[0]) new_transitions[new_transition, transition[1]] = \ __replace_all(conversion_dict, afw['transitions'][transition]) afw['transitions'] = new_transitions def afw_union(afw_1: dict, afw_2: dict) -> dict: """ Returns a AFW that reads the union of the languages read by input AFWs. Let :math:`A_1 = (Σ, S_1 , s^0_1, ρ_1 , F_1 )` and :math:`A_2 = (Σ, S_2 , s^0_2, ρ_2 , F_2 )` be alternating automata accepting the languages :math:`L( A_1)` and :math:`L(A_2)`. Then, :math:`B_∪ = (Σ, S_1 ∪ S_2 ∪ {root}, ρ_∪ , root , F_1 ∪ F_2 )` with :math:`ρ_∪ = ρ_1 ∪ ρ_2 ∪ [(root, a): ρ(s^0_1 , a) ∨ ρ(s^0_2 , a)]` accepts :math:`L(A_1) ∪ L(A_2)`. Pay attention to avoid having the AFWs with state names in common, in case use :mod:`PySimpleAutomata.AFW.rename_afw_states` function. :param dict afw_1: first input AFW; :param dict afw_2: second input AFW;. :return: *(dict)* representing the united AFW. """ # make sure new root state is unique initial_state = 'root' i = 0 while initial_state in afw_1['states'] or initial_state in afw_2['states']: initial_state = 'root' + str(i) i += 1 union = { 'alphabet': afw_1['alphabet'].union(afw_2['alphabet']), 'states': afw_1['states'].union(afw_2['states']).union({initial_state}), 'initial_state': initial_state, 'accepting_states': afw_1['accepting_states'].union(afw_2['accepting_states']), 'transitions': deepcopy(afw_1['transitions']) } # add also afw_2 transitions union['transitions'].update(afw_2['transitions']) # if just one initial state is accepting, so the new one is if afw_1['initial_state'] in afw_1['accepting_states'] \ or afw_2['initial_state'] in afw_2['accepting_states']: union['accepting_states'].add(union['initial_state']) # copy all transitions of initial states and eventually their conjunction # into the new initial state for action in union['alphabet']: if (afw_1['initial_state'], action) in afw_1['transitions']: union['transitions'][initial_state, action] = \ '(' + \ afw_1['transitions'][afw_1['initial_state'], action] + \ ')' if (afw_2['initial_state'], action) in afw_2['transitions']: union['transitions'][initial_state, action] += \ ' or (' + \ afw_2['transitions'][afw_2['initial_state'], action] + \ ')' elif (afw_2['initial_state'], action) in afw_2['transitions']: union['transitions'][initial_state, action] = \ '(' + \ afw_2['transitions'][afw_2['initial_state'], action] + \ ')' return union def afw_intersection(afw_1: dict, afw_2: dict) -> dict: """ Returns a AFW that reads the intersection of the languages read by input AFWs. Let :math:`A_1 = (Σ, S_1 , s^0_1, ρ_1 , F_1 )` and :math:`A_2 = (Σ, S_2 , s^0_2, ρ_2 , F_2 )` be alternating automata accepting the languages :math:`L( A_1)` and :math:`L(A_2)`. Then, :math:`B_∩ = (Σ, S_1 ∪ S_2 ∪ {root}, root, ρ_∩ , F_1 ∪ F_2 )` with :math:`ρ_∩ = ρ_1 ∪ ρ_2 ∪ [(root, a): ρ(s^0_1 , a) ∧ ρ(s^0_2 , a)]` accepts :math:`L(A_1) ∩ L(A_2)`. :param dict afw_1: first input AFW; :param dict afw_2: second input AFW. :return: *(dict)* representing a AFW. """ # make sure new root state is unique initial_state = 'root' i = 0 while initial_state in afw_1['states'] or initial_state in afw_2['states']: initial_state = 'root' + str(i) i += 1 intersection = { 'alphabet': afw_1['alphabet'].union(afw_2['alphabet']), 'states': afw_1['states'].union(afw_2['states']).union({initial_state}), 'initial_state': initial_state, 'accepting_states': afw_1['accepting_states'].union(afw_2['accepting_states']), 'transitions': deepcopy(afw_1['transitions']) } # add also afw_2 transitions intersection['transitions'].update(afw_2['transitions']) # if both initial states are accepting, so the new one is if afw_1['initial_state'] in afw_1['accepting_states'] \ and afw_2['initial_state'] in afw_2['accepting_states']: intersection['accepting_states'].add( intersection['initial_state']) # New initial state transitions will be the conjunction of # precedent inital states ones for action in intersection['alphabet']: if (afw_1['initial_state'], action) in afw_1['transitions']: intersection['transitions'][initial_state, action] = \ '(' + \ afw_1['transitions'][afw_1['initial_state'], action] + \ ')' if (afw_2['initial_state'], action) in afw_2['transitions']: intersection['transitions'][initial_state, action] += \ ' and (' + \ afw_2['transitions'][afw_2['initial_state'], action] + \ ')' else: intersection['transitions'][ initial_state, action] += ' and False' elif (afw_2['initial_state'], action) in afw_2['transitions']: intersection['transitions'][initial_state, action] = \ 'False and (' + \ afw_2['transitions'][afw_2['initial_state'], action] + \ ')' return intersection def afw_nonemptiness_check(afw: dict) -> bool: """ Checks if the input AFW reads any language other than the empty one, returning True/False. The afw is translated into a nfa and then its nonemptiness is checked. :param dict afw: input AFW. :return: *(bool)*, True if input afw is nonempty, False otherwise. """ nfa = afw_to_nfa_conversion(afw) return NFA.nfa_nonemptiness_check(nfa) def afw_nonuniversality_check(afw: dict) -> bool: """ Checks if the language read by the input AFW is different from Σ∗, returning True/False. The afw is translated into a nfa and then its nonuniversality is checked. :param dict afw: input AFW. :return: *(bool)*, True if input afw is nonuniversal, False otherwise. """ nfa = afw_to_nfa_conversion(afw) return NFA.nfa_nonuniversality_check(nfa)
""" Module to manage NFA (Nondeterministic Finite Automata). Formally a NFA, Nondeterministic Finite Automaton, is a tuple :math:`(Σ, S, S^0 , ρ, F )`, where • Σ is a finite nonempty alphabet; • S is a finite nonempty set of states; • :math:`S^0` is the nonempty set of initial states; • F is the set of accepting states; • :math:`ρ: S × Σ × S` is a transition relation. Intuitively, :math:`(s, a, s' ) ∈ ρ` states that A can move from s into s' when it reads the symbol a. It is allowed that :math:`(s, a, s' ) ∈ ρ` and :math:`(s, a, s'' ) ∈ ρ` with :math:`S' ≠ S''` . In this module a NFA is defined as follows NFA = dict() with the following keys-values: • alphabet => set() ; • states => set() ; • initial_states => set() ; • accepting_states => set() ; • transitions => dict(), where **key**: (state in states, action in alphabet) **value**: {set of arriving states in states}. """ from PySimpleAutomata import DFA def nfa_intersection(nfa_1: dict, nfa_2: dict) -> dict: """ Returns a NFA that reads the intersection of the NFAs in input. Let :math:`A_1 = (Σ,S_1,S_1^0,ρ_1,F_1)` and :math:`A_2 =(Σ, S_2,S_2^0,ρ_2,F_2)` be two NFAs. There is a NFA :math:`A_∧` that runs simultaneously both :math:`A_1` and :math:`A_2` on the input word, so :math:`L(A_∧) = L(A_1)∩L(A_2)`. It is defined as: :math:`A_∧ = ( Σ , S , S_0 , ρ , F )` where • :math:`S = S_1 × S_2` • :math:`S_0 = S_1^0 × S_2^0` • :math:`F = F_1 × F_2` • :math:`((s,t), a, (s_X , t_X)) ∈ ρ` iff :math:`(s, a,s_X ) ∈ ρ_1` and :math:`(t, a, t_X ) ∈ ρ_2` :param dict nfa_1: first input NFA; :param dict nfa_2: second input NFA; :return: *(dict)* representing the intersected NFA. """ intersection = { 'alphabet': nfa_1['alphabet'].intersection(nfa_2['alphabet']), 'states': set(), 'initial_states': set(), 'accepting_states': set(), 'transitions': dict() } for init_1 in nfa_1['initial_states']: for init_2 in nfa_2['initial_states']: intersection['initial_states'].add((init_1, init_2)) intersection['states'].update(intersection['initial_states']) boundary = set() boundary.update(intersection['initial_states']) while boundary: (state_nfa_1, state_nfa_2) = boundary.pop() if state_nfa_1 in nfa_1['accepting_states'] \ and state_nfa_2 in nfa_2['accepting_states']: intersection['accepting_states'].add((state_nfa_1, state_nfa_2)) for a in intersection['alphabet']: if (state_nfa_1, a) not in nfa_1['transitions'] \ or (state_nfa_2, a) not in nfa_2['transitions']: continue s1 = nfa_1['transitions'][state_nfa_1, a] s2 = nfa_2['transitions'][state_nfa_2, a] for destination_1 in s1: for destination_2 in s2: next_state = (destination_1, destination_2) if next_state not in intersection['states']: intersection['states'].add(next_state) boundary.add(next_state) intersection['transitions'].setdefault( ((state_nfa_1, state_nfa_2), a), set()).add(next_state) if destination_1 in nfa_1['accepting_states'] \ and destination_2 in nfa_2['accepting_states']: intersection['accepting_states'].add(next_state) return intersection def nfa_union(nfa_1: dict, nfa_2: dict) -> dict: """ Returns a NFA that reads the union of the NFAs in input. Let :math:`A_1 = (Σ,S_1,S_1^0,ρ_1,F_1)` and :math:`A_2 =(Σ, S_2,S_2^0,ρ_2,F_2)` be two NFAs. here is a NFA :math:`A_∨` that nondeterministically chooses :math:`A_1` or :math:`A_2` and runs it on the input word. It is defined as: :math:`A_∨ = (Σ, S, S_0 , ρ, F )` where: • :math:`S = S_1 ∪ S_2` • :math:`S_0 = S_1^0 ∪ S_2^0` • :math:`F = F_1 ∪ F_2` • :math:`ρ = ρ_1 ∪ ρ_2` , that is :math:`(s, a, s' ) ∈ ρ` if :math:`[ s ∈ S_1\ and\ (s, a, s' ) ∈ ρ_1 ]` OR :math:`[ s ∈ S_2\ and\ (s, a, s' ) ∈ ρ_2 ]` Pay attention to avoid having the NFAs with state names in common, in case use :mod:`PySimpleAutomata.NFA.rename_nfa_states` function. :param dict nfa_1: first input NFA; :param dict nfa_2: second input NFA. :return: *(dict)* representing the united NFA. """ union = { 'alphabet': nfa_1['alphabet'].union(nfa_2['alphabet']), 'states': nfa_1['states'].union(nfa_2['states']), 'initial_states': nfa_1['initial_states'].union(nfa_2['initial_states']), 'accepting_states': nfa_1['accepting_states'].union(nfa_2['accepting_states']), 'transitions': nfa_1['transitions'].copy()} for trans in nfa_2['transitions']: for elem in nfa_2['transitions'][trans]: union['transitions'].setdefault(trans, set()).add(elem) return union # NFA to DFA def nfa_determinization(nfa: dict) -> dict: """ Returns a DFA that reads the same language of the input NFA. Let A be an NFA, then there exists a DFA :math:`A_d` such that :math:`L(A_d) = L(A)`. Intuitively, :math:`A_d` collapses all possible runs of A on a given input word into one run over a larger state set. :math:`A_d` is defined as: :math:`A_d = (Σ, 2^S , s_0 , ρ_d , F_d )` where: • :math:`2^S` , i.e., the state set of :math:`A_d` , consists of all sets of states S in A; • :math:`s_0 = S^0` , i.e., the single initial state of :math:`A_d` is the set :math:`S_0` of initial states of A; • :math:`F_d = \{Q | Q ∩ F ≠ ∅\}`, i.e., the collection of sets of states that intersect F nontrivially; • :math:`ρ_d(Q, a) = \{s' | (s,a, s' ) ∈ ρ\ for\ some\ s ∈ Q\}`. :param dict nfa: input NFA. :return: *(dict)* representing a DFA """ def state_name(s): return str(set(sorted(s))) dfa = { 'alphabet': nfa['alphabet'].copy(), 'initial_state': None, 'states': set(), 'accepting_states': set(), 'transitions': dict() } if len(nfa['initial_states']) > 0: dfa['initial_state'] = state_name(nfa['initial_states']) dfa['states'].add(state_name(nfa['initial_states'])) sets_states = list() sets_queue = list() sets_queue.append(nfa['initial_states']) sets_states.append(nfa['initial_states']) if len(sets_states[0].intersection(nfa['accepting_states'])) > 0: dfa['accepting_states'].add(state_name(sets_states[0])) while sets_queue: current_set = sets_queue.pop(0) for a in dfa['alphabet']: next_set = set() for state in current_set: if (state, a) in nfa['transitions']: for next_state in nfa['transitions'][state, a]: next_set.add(next_state) if len(next_set) == 0: continue if next_set not in sets_states: sets_states.append(next_set) sets_queue.append(next_set) dfa['states'].add(state_name(next_set)) if next_set.intersection(nfa['accepting_states']): dfa['accepting_states'].add(state_name(next_set)) dfa['transitions'][state_name(current_set), a] = state_name(next_set) return dfa def nfa_complementation(nfa: dict) -> dict: """ Returns a DFA reading the complemented language read by input NFA. Complement a nondeterministic automaton is possible complementing the determinization of it. The construction is effective, but it involves an exponential blow-up, since determinization involves an unavoidable exponential blow-up (i.e., if NFA has n states, then the DFA has :math:`2^n` states). :param dict nfa: input NFA. :return: *(dict)* representing a completed DFA. """ determinized_nfa = nfa_determinization(nfa) return DFA.dfa_complementation(determinized_nfa) def nfa_nonemptiness_check(nfa: dict) -> bool: """ Checks if the input NFA reads any language other than the empty one, returning True/False. The language L(A) recognized by the automaton A is nonempty iff there are states :math:`s ∈ S_0` and :math:`t ∈ F` such that t is connected to s. Thus, automata nonemptiness is equivalent to graph reachability. A breadth-first-search algorithm can construct in linear time the set of all states connected to a state in :math:`S_0`. A is nonempty iff this set intersects F nontrivially. :param dict nfa: input NFA. :return: *(bool)*, True if the input nfa is nonempty, False otherwise. """ # BFS queue = list() visited = set() for state in nfa['initial_states']: visited.add(state) queue.append(state) while queue: state = queue.pop(0) visited.add(state) for a in nfa['alphabet']: if (state, a) in nfa['transitions']: for next_state in nfa['transitions'][state, a]: if next_state in nfa['accepting_states']: return True if next_state not in visited: queue.append(next_state) return False def nfa_nonuniversality_check(nfa: dict) -> bool: """ Checks if the language read by the input NFA is different from Σ∗ (i.e. contains all possible words), returning True/False. To test nfa A for nonuniversality, it suffices to test Ā ( complementary automaton of A) for nonemptiness :param dict nfa: input NFA. :return: *(bool)*, True if input nfa is nonuniversal, False otherwise. """ # NAIVE Very inefficient (exponential space) : simply # construct Ā and then test its nonemptiness complemented_nfa = nfa_complementation(nfa) return DFA.dfa_nonemptiness_check(complemented_nfa) # EFFICIENT: # construct Ā “on-the-fly”: whenever the nonemptiness # algorithm wants to move from a state t_1 of Ā to a state t_2, # the algorithm guesses t_2 and checks that it is directly # connected to t_1 . Once this has been verified, # the algorithm can discard t_1 . def nfa_interestingness_check(nfa: dict) -> bool: """ Checks if the input NFA is interesting, returning True/False. An automaton is “interesting” if it defines an “interesting” language, i.e., a language that is neither empty nor contains all possible words. :param dict nfa: input NFA. :return: *(bool)*, True if the input nfa is interesting, False otherwise. """ return nfa_nonemptiness_check(nfa) and nfa_nonuniversality_check(nfa) def nfa_word_acceptance(nfa: dict, word: list) -> bool: """ Checks if a given word is accepted by a NFA. The word w is accepted by a NFA if exists at least an accepting run on w. :param dict nfa: input NFA; :param list word: list of symbols ∈ nfa['alphabet']; :return: *(bool)*, True if the word is accepted, False otherwise. """ current_level = set() current_level = current_level.union(nfa['initial_states']) next_level = set() for action in word: for state in current_level: if (state, action) in nfa['transitions']: next_level.update(nfa['transitions'][state, action]) if len(next_level) < 1: return False current_level = next_level next_level = set() if current_level.intersection(nfa['accepting_states']): return True else: return False # SIDE EFFECTS def rename_nfa_states(nfa: dict, suffix: str): """ Side effect on input! Renames all the states of the NFA adding a **suffix**. It is an utility function to be used to avoid automata to have states with names in common. Avoid suffix that can lead to special name like "as", "and",... :param dict nfa: input NFA. :param str suffix: string to be added at beginning of each state name. """ conversion_dict = {} new_states = set() new_initials = set() new_accepting = set() for state in nfa['states']: conversion_dict[state] = '' + suffix + state new_states.add('' + suffix + state) if state in nfa['initial_states']: new_initials.add('' + suffix + state) if state in nfa['accepting_states']: new_accepting.add('' + suffix + state) nfa['states'] = new_states nfa['initial_states'] = new_initials nfa['accepting_states'] = new_accepting new_transitions = {} for transition in nfa['transitions']: new_arrival = set() for arrival in nfa['transitions'][transition]: new_arrival.add(conversion_dict[arrival]) new_transitions[ conversion_dict[transition[0]], transition[1]] = new_arrival nfa['transitions'] = new_transitions return nfa