text
stringlengths
37
1.41M
l=[] highest=[] scores=set() for i in range(int(input())): name=input() score=float(input()) l.append([name,score]) scores.add(score) h=sorted(scores)[-1] for name,score in l: if h==score: highest.append(name) for i in sorted(highest): print(i,end="\n")
# Code for testing if statement in python nm=input("Enter name ") basic=int(input("enter basic salary ")) if basic>5000: allowance=basic*45/100 bonus=basic*30/100 elif basic>3000: allowance=basic*25/100 bonus=basic*10/100 else: allowance=basic*15/100 bonus=0 total=basic+allowance+bonus print("Total salary is %d" %total) # content of sohamglobal.com
# Addition of elements of Lists and NumPy arrays import numpy as np # Working with lists lst1=[1,2,3,4,5] lst2=[1,2,3,4,5] add_res=lst1+lst2 print(add_res) #creating array from list np_lst1=np.array(lst1) np_lst2=np.array(lst2) npres=np_lst1+np_lst2 print(npres) # Content of Sohamglobal.com
# Demo program on class and object class numbers: a=0 b=0 def __init__(self): print("Welcome to python class") def calcsum(self): sum=self.a+self.b return sum def showmessage(self,name): print("your name is ",name) obj=numbers() obj.showmessage("Ethan Hunt") obj.a=11 obj.b=22 c=obj.calcsum() print(c) #content of sohamglobal.com
#-*- coding:utf-8 -*- nums = [10,11,12,13,14,15] #在for中无break会执行的,没什么用 for num in nums: print num break else: print('='*10)
import random USER_PROMPT = "guess a number between {} and {}: \n" LOWEST_NUMBER = 1 HIGHEST_NUMBER = 10 while True: randomNumber = random.randint(LOWEST_NUMBER, HIGHEST_NUMBER) userGuess = 0 while randomNumber != userGuess: userPrompt = USER_PROMPT.format(LOWEST_NUMBER, HIGHEST_NUMBER) userGuess = input(userPrompt) userGuess = int(userGuess) print("you guessed:", userGuess) if randomNumber > userGuess: print("the number is higher!") elif randomNumber < userGuess: print("the number is lower!") print("you are correct! yay!") print("") playAgain = input("Do you want to play again? y/n ") if playAgain == "n": break
def repeatedStringMatch(self, A, B): if B in A: return 1 if set(B) > set(A): return -1 n = len(B) // len(A) if B in A * n: return n if B in A * (n + 1): return n + 1 if B in A * (n + 2): return n + 2
weight = float(input("Weight: ")) w_type = input("L(bs) or (K)g: ") # lbs = float(weight) * 0.45 # kg = float(weight) / 0.45 if w_type.upper() == "L": #the upper method will make the data input uppercase converted = weight * 0.45 print(f'You are {converted} kgs') elif w_type.upper() == "K": converted = weight / 0.45 # // will give us an integer print(f'You are {converted} pounds')
list = [2, 3, 1, 5, 2, 1, 3, 9, 9] for remove in list: if list.count(remove) == 2: list.remove(remove) print(list) #Mosh way list = [2, 3, 1, 5, 2, 1, 3, 9, 9] unique = [] for number in list: if number not in unique: unique.append(number) print(unique) x, y, z, a, b = unique print(x)
# 퀴즈 9 클래스 class house: def __init__(self, location, house_type, deal_type, price, completion_year): self.location = location self.house_type = house_type self.deal_type = deal_type self.price = price self.completion_year = completion_year def show_detail(self): print(self.location,self.house_type,self.deal_type, self.price, self.completion_year) houselist = [] h1 = house("강남","아파트","매매","10억","2010년") h2 = house("마포","오피스텔","전세","5억","2007년") h3 = house("송파","빌라","월세","500/50","2000년") houselist.append(h1) houselist.append(h2) houselist.append(h3) for house in houselist: house.show_detail()
import cs50 from sys import argv if len(argv) != 2: print ("usage error") exit() db = cs50.SQL("sqlite:///students.db") rows = db.execute('SELECT * FROM students WHERE house = ? ORDER BY last, first' , argv[-1]) for row in rows: if row["middle"] == None: print( row["first"] + " " + row["last"] + ", born " + str(row["birth"]), sep =' ') else: print( row["first"] + " " + row["middle"] + " " + row["last"] + ", born " + str(row["birth"]), sep =' ')
letter = input() grade = float(ord('E') - ord(letter[0])) if len(letter) == 2: if letter[1] == "+" and grade != 4: grade += 0.3 elif letter[1] == "-": grade -= 0.3 # if letter is 'F', our calculation gives -1 if grade > 0: print(grade) else: print(0.0)
print("Guess a number from 1 to 10. You have 3 tries.\n") i=1 while i<=3: num= int(input("Guess: ")) i = i +
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jan 6 12:25:49 2021 @author: RileyBallachay """ import threading def worker(): """thread worker function""" print ('Worker') return threads = [] for i in range(5): t = threading.Thread(target=worker) threads.append(t) t.start()
# coding: utf-8 # In[14]: import datetime as dt import matplotlib.pyplot as plt from matplotlib import style import pandas as pd import pandas_datareader.data as web # In[15]: #we're setting a visulization style style.use('ggplot') # In[16]: #we're setting a start and end datetime object #this will be the range of dates that we're going to grab stock pricing information foR start = dt.datetime(2017, 1, 1) end = dt.datetime(2017, 7, 31) # In[18]: #Select the ticker and source of stock data df = web.DataReader('AAPL', "yahoo", start, end) # In[20]: #Adj Close is helpful, since it accounts for future stock splits, and gives the relative price to splits #For this reason, the adjusted prices are the prices you're most likely to be dealing with. df.tail() # In[21]: #We can save them easily to a csv in our wd df.to_csv('AAPL.csv') # In[22]: #We can either read data from DataFrame or from a CSV file into a DataFrame: df = pd.read_csv('AAPL.csv', parse_dates=True, index_col=0) # In[26]: ##Now, we can graph it df.plot() plt.show() # In[27]: #Now, we can graph one specific column in the DataFrame df['Adj Close'].plot() plt.show() # In[29]: #Call one or more columns in the DataFrame df[['High','Low']]
# print a question about age print("How old are you?", end= ' ') # ask for the age age = input() # print a question about height print("How tall are you?", end=' ') # input for height height = input() # print a question about weigh print("How much do you weigh?", end=' ') # input for weight weight = input () # print all three inputs in one string print(f"So, you're {age} old, {height} tall, and {weight} heavy.")
print(" Hi, this is a tracker for you body status. ") x = int(input(" Number of times you have thought about your body: ")) y = int(input(" Number of times you have gone out for a run: ")) def adonis(): z = y - x print(f"\t {z}") print(" When this numer is positive you will feel better.") adonis()
print("""You enter a dark room with two doors. Do you go through door #1 or door #2?""") door = input("> ") if door == "1": print("There is a giant bear here eating a cheese cake.") print("What do you do?") print("1. Take the cake.") print("2. Scream at the bear.") bear = input("> ") if bear == "1": print("The bears eats your face off. You are dead.") elif bear == "2": print("The bear eats your legs off. You run away.") else: print(f"Well, doing {bear} is probably better.") print("Bear runs away.") elif door == "2": print("You stare into the endless abyss at Cthulhu's retina.") print("1. Blueberries.") print("2. Yellow jacket clothespins.") print("3. Undestanding revolvers yelling melodies") insanity = input("> ") if insanity == "1" or insanity == "2": print("Your body survives powered by a mind of jello.") print("Good job!") else: print("The insanity rots your eyes into a pool of muck.") print("Good job!") elif door == "4": print("Aha! I see you are a man of knowledge.") print("You pass through the hidden door.") print("Inside a giant triangle with an eye stares into infinty.") print("Open your eyes and see the truth!") print("You have gained the power of articulation!") else: print("You stumble around and fall on a knife and die. Dipshit.")
#ex13: Parameters, unpacking, variables from sys import argv # 'import' tells the program to use 'argv' from the 'sys' module # (sometimes also called 'libraries') # 'argv' is the 'argument variable'. This variable holds the # arguments you pass into your python script when you run it. script, first, second, third = argv # This line 'unpacks' argv so that rather than holding # all the arguments, it gets assigned to four variables # that you can work with: script, first, second, and third. # 'Take whatever is in argv, unpack it, and assign # it to all of these variables on the left in order' print "The script is called:", script print "Your first variable is:", first print "Your second variable is:", second print "Your third variable is:", third
#ex05: More variables and printing name = 'Claire F. Esau' age = 28 # not a lie height = (5*12) + 6 # inches weight = (9*14) + 10 # lbs eyes = 'Hazel' teeth = 'White' hair = 'Brown' print "\nLet's talk about %s." % name print "She's %d inches tall." % height print "She weighs %d pounds." % weight print "Actually that's not too heavy." print "She's got %s eyes and %s hair." % (eyes, hair) print "Her teeth are usually %s depending on the coffee." % teeth print "If I add %d, %d, and %d I get %d." % ( age, height, weight, age + height + weight) # Try more formatting characters greeting = "Hello,\t" firstname = "Claire" surname = "Esau" # compare %s and %r formats print "\nFormatting with %r: %s my name is %s %s\n and I'm %d years old." % ( '%s', greeting, firstname, surname, age) print "Formatting with %r: %r my name is %s %s\n and I'm %d years old." % ( '%r', greeting, firstname, surname, age) # convert inches and pounds to centimetres and kilos inch2cm = 2.54 lb2kg = 0.453592 # print height in cm to 2 d.p. print "\nShe's %.2f centimetres tall." % (height * inch2cm) # print weight in kg to 3 d.p. print "She weighs %.3f kg." % (weight * lb2kg)
# -*- coding: utf-8 -*- import platform import os from datetime import datetime, date def limpiar_pantalla(): sistema_operativo = platform.system() if sistema_operativo.lower() == "windows": os.system("cls") else: os.system("clear") def leer_entero(mensaje, min_val=None, max_val=None, requerido=False): """ leer_entero(string, int, int, boolean) -> int Pide que se ingrese número entre un rango dado. Los rangos son opcionales. Solo se retorna resultado cuando se ingresa un valor válido, si éste es requerido. @Parámetros mensaje : mensaje que se muestra al usuario. Obligatorio. min_val : el valor mínimo que usuario debe ingresar. default: None max_val : el valor máximo que usuario debe ingresar. default: None requerido : Indica si el valor es obligatorio (True). default: False """ while True: # establecer un ciclo indefinido, hasta que el valor ingresado sea válido. val = input(mensaje) if not requerido and val.strip() == '': # permite ingresar cadena vacía si el valor no es obligatorio. return val else: # valor es requerido. Validar entero. try: val = int(val) except ValueError: # no se puede parsear a int. Valor inválido. print("Debe introducir un número entero.") else: # verificamos si se encuentra dentro del rango (min_val, max_val) if min_val is not None and val < min_val: print("Valor fuera de rango. No puede ser menor a {}".format(min_val)) elif max_val is not None and val > max_val: print("Valor fuera de rango. No puede ser mayor a {}".format(max_val)) else: # se superó la validación. Retornar valor ingresado. return val def leer_cadena(mensaje, requerido=False): """ leer_cadena(string, boolean) -> str Pide que se ingrese una cadena. @Parámetros mensaje : mensaje que se muestra al usuario. Obligatorio. requerido : Indica si el valor es obligatorio (True). default: False """ while True: # establecer un ciclo indefinido, hasta que el valor ingresado sea válido. val = input(mensaje) if requerido and val.strip() == '': print("No puede dejar vacío este campo. Ingrese de nuevo") else: return val def presiona_continuar(): mensaje = "Presione 'Enter' para continuar..." leer_cadena(mensaje, requerido=False) limpiar_pantalla() def leer_dato_binario(mensaje, opciones): """ Función para validar el ingreso de datos donde sólamente son posibles dos respuestas. Case sensitive. @Parámetros opciones: lista de elementos str. con las posibles respuestas """ print(mensaje) while True: val = input() if val in opciones: return val else: print("Ingresó un valor incorrecto. Las opciones son " + str(opciones)) def si_no_pregunta(pregunta): pregunta += " (S/N):" valores_si = ['si', 'sí', 's', 'yes', 'y'] valores_no = ['no', 'n'] while True: val = input(pregunta) if val.lower() in valores_si: return True elif val.lower() in valores_no: return False else: print("Ingresó una respuesta no válida...") def fecha_actual(): """Función que retorna la fecha actual""" return datetime.now().date() def hora_actual(): """Función que retorna la hora actual""" return datetime.now().time()
class Solution: def repeatedNTimes(A): for a in range(len(A)): if A[a] in A[:a]: return A[a] sol = Solution print("Container with most water = {}" .format(sol.repeatedNTimes([5,4,3,3])))
def diagonalDifference(arr): # Write your code here return arr sum_a = 0 sum_b = 0 for i in range(len(arr)): sum_a = sum_a + arr[i][i] sum_b = sum_b + arr[len(arr)-i-1][i] return abs(sum_a - sum_b) print("a") print(diagonalDifference([[11, 2, 4], [4, 5, 6], [10, 8, -12]]))
def readFile(filepath): file = open(filepath, "r") lines = [line.strip("\n") for line in file.readlines()] return lines def infix2postfix(expression): postExp = [] stack = [] for i in range(len(expression)): if expression[i] == " ": continue elif '0' <= expression[i] <= '9': # operand -> post expression postExp.append(expression[i]) elif expression[i] in ['+', '*']: # operator while len(stack) > 0 and stack[-1] != '(': postExp.append(stack[-1]) stack = stack[:-1] stack.append(expression[i]) elif expression[i] == '(': # '(' -> stack stack.append('(') elif expression[i] == ')': # ')' while len(stack) > 0 and stack[-1] != '(': postExp.append(stack[-1]) stack = stack[:-1] if len(stack) > 0 and stack[-1] == '(': stack = stack[:-1] while len(stack) > 0: postExp.append(stack[-1]) stack = stack[:-1] return postExp precedence = {'*': 1, '+': 2} def infix2postfix2(expression): postExp = [] stack = [] for i in range(len(expression)): if expression[i] == " ": continue elif '0' <= expression[i] <= '9': # operand -> post expression postExp.append(expression[i]) elif expression[i] in ['+', '*']: # operator while len(stack) > 0 and stack[-1] != '(' and precedence[expression[i]] <= precedence[stack[-1]]: postExp.append(stack[-1]) stack = stack[:-1] stack.append(expression[i]) elif expression[i] == '(': # '(' -> stack stack.append('(') elif expression[i] == ')': # ')' while len(stack) > 0 and stack[-1] != '(': postExp.append(stack[-1]) stack = stack[:-1] if len(stack) > 0 and stack[-1] == '(': stack = stack[:-1] while len(stack) > 0: postExp.append(stack[-1]) stack = stack[:-1] return postExp def evaluePostExp(postExp): stack = [] for i in range(len(postExp)): if '0' <= postExp[i] <= '9': stack.append(postExp[i]) else: a = int(stack[-1]) b = int(stack[-2]) re = 0 if postExp[i] == '+': re = a + b elif postExp[i] == '*': re = a * b stack[-2] = re stack = stack[:-1] return stack[-1] def day18P1(hws): sum = 0 for hw in hws: exp = [l for l in hw if l != ' '] postExp = infix2postfix(exp) print(postExp) value = evaluePostExp(postExp) sum += value return sum def day18P2(hws): sum = 0 for hw in hws: exp = [l for l in hw if l != ' '] postExp = infix2postfix2(exp) print(postExp) value = evaluePostExp(postExp) sum += value return sum if __name__ == "__main__": hws = readFile("./input") value = day18P2(hws) print(value)
pizzas = ['calabreza', 'peperonni', 'Muzzarela'] for pizza in pizzas: print("I love pizza de " + pizza.title()) print("I really love pizza de " + pizza.title() + "\n") friends_pizzas = pizzas[:] friends_pizzas.append('tortella') print(friends_pizzas) print() print("Minhas pizzas favoritas são: " + str(pizzas) + "\n") print() print("As pizzas favoritas dos meus amigos são: " + str(friends_pizzas) + "\n") print() for pizza in pizzas: print("Minha Predileta é " + str(pizza))
animals = ['dog', 'cat', 'bear'] for animal in animals: print ("A " + animal.title() + " would be a great domestic animal!") print("Which one of these animals could be a great domestical animal!")
import sys import inspect import heapq, random from collections import deque """ Data structures useful for implementing SearchAgents """ # TODO modify the priority queue function as per the latest doc strings to add all the required functionalities. class Stack(deque): "A container with a last-in-first-out (LIFO) queuing policy." def __init__(self): self.stack = deque([]) def push(self ,item): "Push 'item' onto the stack. In this case appends to the right" self.stack.append(item) def isEmpty(self): "Returns true if the stack is empty" return len(self.list) == 0 class Queue(deque): "A container with a first-in-first-out (FIFO) queuing policy." def __init__(self): self.queue = deque([]) def push(self, item): "Enqueue the 'item' into the queue" self.queue.append(item) def pop(self): """ Dequeue the earliest enqueued item still in the queue. This operation removes the item from the queue. Overwrites the standard pop function of the deque object to enforce FIFO. """ return self.queue.popleft() def isEmpty(self): "Returns true if the queue is empty" return len(self.list) == 0 class PriorityQueue: """ Implements a priority queue data structure. Each inserted item has a priority associated with it and the client is usually interested in quick retrieval of the lowest-priority item in the queue. This data structure allows O(1) access to the lowest-priority item. Note that this PriorityQueue does not allow you to change the priority of an item. However, you may insert the same item multiple times with different priorities. """ def __init__(self): self.heap = [] def push(self, item, priority): pair = (priority, item) heapq.heappush(self.heap, pair) def pop(self): (priority, item) = heapq.heappop(self.heap) return item def isEmpty(self): return len(self.heap) == 0 def raiseNotDefined(): print (f"Method not implemented: {inspect.stack()[1][3]}") sys.exit(1) def flipCoin(p) : """ p is the beas of the coin in favor of True""" r = random.random() return r < p def pause(): """ Pauses the output stream awaiting user feedback. """ print("<Press enter/return to continue>") input()
'''读取csv文件''' import csv data = csv.reader(open('info.csv','r')) for user in data: print(user) # print(user[0]) #读取每一行的第1个数据
# Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1. # Example 1: # Input: [0,1] # Output: 2 # Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1. # Example 2: # Input: [0,1,0] # Output: 2 # Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1. # Note: The length of the given binary array will not exceed 50,000. # [0, 0, 1, 0, 0, 0, 1, 1] => 6 # possible arrays all start with the 0 index or 2nd to last index class Solution: def findMaxLength(self, nums): ''' >>> nums = [0, 0, 1, 0, 0, 0, 1, 1] >>> solution = Solution() >>> solution.findMaxLength(nums) 6 >>> nums = [0,1,0] >>> solution.findMaxLength(nums) 2 ''' dict_count_idx = {} sub_array = 0 counter = 0 for i in range(len(nums)): if nums[i] == 1: counter += 1 else: counter += -1 if counter == 0: sub_array = i + 1 if counter in dict_count_idx: sub_array = max(sub_array, i-dict_count_idx[counter]) else: dict_count_idx[counter] = i return sub_array if __name__ == '__main__': import doctest if doctest.testmod(verbose=True).failed == 0: print('all tests passed')
class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool nested loop through rows, columns check if coord is target, return true if target for quicker - use binary search """ ## naive solution if matrix == []: return 0 row, col = len(matrix), len(matrix[0]) for r in range(row): for c in range(col): if matrix[r][c] == target: return True return False matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 3 matrix2 = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target2 = 13 solution = Solution() print(solution.searchMatrix(matrix, target)) print(solution.searchMatrix(matrix2, target2))
class TicTacToe: ''' A Tic-Tac-Toe board is given as a string array board. Return True if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game. The board is a 3 x 3 array, and consists of characters " ", "X", and "O". The " " character represents an empty square. Here are the rules of Tic-Tac-Toe: Players take turns placing characters into empty squares (" "). The first player always places "X" characters, while the second player always places "O" characters. "X" and "O" characters are always placed into empty squares, never filled ones. The game ends when there are 3 of the same (non-empty) character filling any row, column, or diagonal. The game also ends if all squares are non-empty. No more moves can be played if the game is over. The first player always plays "X". >>> board = ["O ", " ", " "] >>> game = TicTacToe() >>> game.validTicTacToe(board) False Players take turns making moves. >>> board = ["XOX", " X ", " "] >>> game.validTicTacToe(board) False >>> board = ["XXX", " ", "OOO"] >>> game.validTicTacToe(board) False >>> board = ["XOX", "O O", "XOX"] >>> game.validTicTacToe(board) True >>> board = ["XXX","OOX","OOX"] >>> game.validTicTacToe(board) True >>> board = ["XXX","XOO","OO "] >>> game.validTicTacToe(board) False >>> board = ["OXX","XOX","OXO"] >>> game.validTicTacToe(board) False ''' def count_dict(self, board): mark_dict = {} for row in board: for col in row: if col == 'X' or col == 'O': mark_dict[col] = mark_dict.get(col, 0) + 1 return mark_dict def winner_dict(self, board): winners_dict = {} if board[0][0] == board[0][1] == board[0][2] != ' ': winners_dict[board[0][0]] = winners_dict.get(board[0][0], 0) + 1 if board[1][0] == board[1][1] == board[1][2] != ' ': winners_dict[board[1][0]] = winners_dict.get(board[1][0], 0) + 1 if board[2][0] == board[2][1] == board[2][2] != ' ': winners_dict[board[2][0]] = winners_dict.get(board[2][0], 0) + 1 if board[0][0] == board[1][1] == board[2][2] != ' ': winners_dict[board[0][0]] = winners_dict.get(board[0][0], 0) + 1 if board[0][2] == board[1][1] == board[2][0] != ' ': winners_dict[board[0][2]] = winners_dict.get(board[0][2], 0) + 1 if board[0][0] == board[1][0] == board[2][0] != ' ': winners_dict[board[0][0]] = winners_dict.get(board[0][0], 0) + 1 if board[0][1] == board[1][1] == board[2][1] != ' ': winners_dict[board[0][1]] = winners_dict.get(board[0][1], 0) + 1 if board[0][2] == board[1][2] == board[2][2] != ' ': winners_dict[board[0][2]] = winners_dict.get(board[0][2], 0) + 1 return winners_dict def validTicTacToe(self, board): winners_dict = self.winner_dict(board) count_dict = self.count_dict(board) if len(winners_dict) > 1: return False elif 'O' in winners_dict and count_dict['O'] != count_dict.get('X', 0): return False elif not (count_dict.get('X', 0) - count_dict.get('O', 0) >= 0 and count_dict.get('X', 0) - count_dict.get('O', 0) <= 1): return False elif 'X' in winners_dict and 'X' in count_dict and count_dict['X'] - count_dict.get('O', 0) != 1: return False else: return True if __name__ == '__main__': import doctest if doctest.testmod(verbose=True).failed == 0: print('all tests passed')
def contains_duplicates(lst): """ Runtime is O(n log n). Sorting is O(n log n) and the loop is O(n) >>> contains_duplicates([1,2,3,1]) True >>> contains_duplicates([1,2,3,4]) False """ lst.sort() for idx in range(1, len(lst)): if lst[idx-1] == lst[idx]: return True return False def contains_duplicates_sets(lst): """ >>> contains_duplicates_sets([1,2,3,1]) True >>> contains_duplicates_sets([1,2,3,4]) False """ lst_set = set(lst) if len(lst_set) != len(lst): return True return False if __name__ == "__main__": import doctest result = doctest.testmod() if result.failed == 0: print("All tests passed.")
s = 'azcbobobegghekl' #s = 'abcbcd' currentString = s[0] longestString = '' i = 0 for i in range(1,len(s)): if s[i] >= s[i-1]: currentString = currentString + s[i] else: if len(currentString) > len(longestString): longestString = currentString currentString = s[i] print longestString
"""Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. (寻找最大长度的回文子串) exp: Input: "babad" Output: "bab" Note: "aba" is also a valid answer. """ def longestPalindrome(self,s): """ 当新增一个字符最大回文子串长只可能增加1或者2.而且最大回文子串办函这个新字符。 """ maxlength = 1 start = 0 for i in range(len(s)): if i-maxlength >= 1 and s[i-maxlength-1:i+1] == s[i-maxlength-1:i+1][::-1]: start = i-maxlength-1 maxlength += 2 continue if i-maxlength >= 0 and s[i-maxlength:i+1] == s[i-maxlength:i+1][::-1]: start = i-maxlength maxlength += 1 return s[start:start+maxlength]
import os, fnmatch def getCsvFiles(path, extension=None): """ Listing files with given extension in a folder. :param path: string - folder in which the files are :param extension: string - format: "*.csv" file extension what it looks for :return: list - list of csv files in from the path """ if extension: fileExtension = extension else: fileExtension = "*.csv" files = [] # get all files in folder fileList = os.listdir(path) # filter on csv files for name in fileList: if fnmatch.fnmatch(name, fileExtension) == True: files.append(os.path.join(path, name)) return files
import streamlit as st import pandas as pd import plotly.express as px #Título st.title("Mi primer app de streamlit") #Para ejecutar, desde la consola escribimos: streamlit run nombrearhivo.py #header st.header("Semestre Sep-Enero 2021") #Texto st.text("Herramientas para el análisis de datos") #Markdown st.markdown("### Hola") #Mensajes st.success("Successful") st.info("Information!") st.warning("This is a warning") st.error("This is an error Danger") st.text("Lo interesante de streamlit son los widgets:") valor = st.checkbox("Show/Hide") # Checkbox if valor: st.text("Showing or Hiding Widget") # Radio Buttons status = st.radio("What is your status", ("Active", "Inactive")) if status == 'Active': st.success("You are Active") else: st.warning("Inactive, Activate") # SelectBox occupation = st.selectbox( "Your Occupation", ["Programmer", "DataScientist", "Doctor", "Businessman"]) st.write("You selected this option ", occupation) # MultiSelect location = st.multiselect("Where do you work?", ("London", "New York", "Accra", "Kiev", "Nepal")) st.write("You selected", len(location), "locations") # Slider level = st.slider("What is your level", 1, 5) # Buttons st.button("Simple Button") if st.button("About"): st.text("Streamlit is Cool") # SIDEBARS st.sidebar.header("About") st.sidebar.text("This is Streamlit Tut") #Tambien podemos seguir llamando al código de python con el que hemos estado trabajando: pandas, plots, etc, @st.cache # Para que los datos solo se descarguen una vez def get_data(): url = "http://data.insideairbnb.com/united-states/ny/new-york-city/2019-09-12/visualisations/listings.csv" return pd.read_csv(url) df = get_data() st.dataframe(df.head()) st.map(df) values = st.sidebar.slider("Price range", float(df.price.min()), 1000.0, (50.0, 300.0)) st.write(values[1]) f = px.histogram(df[(df.price > int(values[0])) & (df.price < int(values[1]))], x="price", nbins=15, title="Price distribution") f.update_xaxes(title="Price") f.update_yaxes(title="No. of listings") st.plotly_chart(f)
a = int(input()) b = int(input()) d = 1 while d % a != 0 or d % b != 0: d += 1 print(d)
#!/usr/bin/env python import math # Draw an arc of equally spaced circles arcRadius = 400 # Radius of the arc to place the circles on arcDegrees = 180 # Number of degrees to spread the circles over arcOffset = 0 # Angle to start from pinRadius = 7 # Radius of the circles pinCount = 25 # How many circles to place pinFill = '0' # not filled # pinFill = 'f' # filled with bg colour # pinFill = 'F' # filled with pen colour # Draw origin pin print("C 0 0 {} 1 0 N".format(pinRadius)) # arc of pins for pin in range(0,pinCount): angle = math.radians(arcOffset + (pin*arcDegrees/float(pinCount-1))) X = int(round(math.sin(angle)*arcRadius)) Y = int(round(math.cos(angle)*arcRadius)) # Draw the circle: # C X Y radius part dmg pen fill print("C {} {} {} 1 0 N".format(X,Y,pinRadius))
#! python3 """Class Employee Module.""" # Program name: jmEmployee.py # Author: Jonathan McDonald # Date last updated: 4/16/2017 # Purpose: This is a class constructor for the Employee class that # that will hold the attributes: name, ID, dept, and job title. # import modules # # import antigravity # none # Initialize My Variables # # none for global scoping # Class Employee class Employee: """Class Employee Constructor for Class Instances.""" # initialize the object's data attributes def __init__(self, name, idNumber, dept, jobTitle): """Initialize the self.""" self.__name = name # employee full name self.__idNumber = idNumber # employee ID number self.__dept = dept # employee department self.__jobTitle = jobTitle # employee job title # Setter Methods # # public method to set name, a private data attribute def set_name(self, name): self.__name = name # public method to set ID number, a private data attribute def set_idNumber(self, idNumber): self.__idNumber = idNumber # public method to set dept, a private data attribute def set_dept(self, dept): self.__dept = dept # public method to set job title, a private data attribute def set_jobTitle(self, jobTitle): self.__jobTitle = jobTitle # Getter Methods # # public method to return the data attribute name, a private data attribute def get_name(self): return self.__name # public method to return the data attribute ID number, a private data attribute def get_idNumber(self): return self.__idNumber # public method to return the data attribute dept, a private data attribute def get_dept(self): return self.__dept # public method to return the data attribute job title, a private data attribute def get_jobTitle(self): return self.__jobTitle # Print or return Object's state as a string # def __str__(self): return "Name: " + self.__name + \ "\nID Number: " + self.__idNumber + \ "\nDepartment: " + self.__dept + \ "\nTitle: " + self.__jobTitle # End Of Program # # let user know program has finished # End Of Line #
#! python3 # Program name: jmKilometers.py # Author: Jonathan McDonald # Date last updated: 2/26/2017 # Purpose: This program converts user entered Kilometers to Miles and displays both back to the user # Initialize My Variables # ##myMile as Float ##MY_K_M_CONST As Float MY_K_M_CONST = 0.6214 #conversion constant for miles per kilometer ##usrMile as Float ##usrKM as Int #my function get the user input def compute_miles(myKm): """Convert Kilometers to Miles""" ##myMile as Float myMile = 0.0 #convert Km to miles ##should make 0.6214 a constant myMile = myKm * MY_K_M_CONST #return computed miles return myMile #my function get the user input def getUserNum(): """Get and validate user Kilometer input""" #set myNum as neg one to accept zero as an input myNum = -1 #set myInputCheck as false to enter input loop myInputCheck = False while myInputCheck == False: #ask user for number of kilometers myNum_Validation = (input(u'Enter the Kilometers for conversion: ')) #call my getValidation to check values entered myNum = getValidation(myNum_Validation) #check if user entered a valid number if myNum == -1: print('\nPlease enter your number. \nEnter a positive real number >= 0') myInputCheck = False elif myNum == 0: print('\nYou have entered 0 for the number of Kilometers.') myInputCheck = True elif myNum > 0: #number is greater than zero myInputCheck = True else: #number is not greater than zero myInputCheck = False return int(myNum) #my function to check that inputs are numbers only def getValidation(myInput): """Validate user input is a number""" if myInput == "": print('You did not enter a number.') return -1 elif myInput.isnumeric() == False: if myInput == str(-99): return -1 elif isfloat(myInput) == True: if float(myInput) < 0: print('You entered a negative value, please enter positive numbers only.') return -1 else: return float(myInput) else: print('You entered a negative or a text value, please enter numerical digits only.') return -1 elif myInput.isnumeric() == True: return float(myInput) else: print('There has been a read error, please re-enter your number') return -1 #my function to check if a float was provided def isfloat(myVarCheck): """See if string contains a float""" try: float(myVarCheck) #print('Input accepted as a floating point.') return True except ValueError: return False #inform user what this program accepts for input print('This program accepts positive integer values equal to or greater than 0 only.') #initilize user kilometers usrKM = 0 #get user kilometer input usrKM = getUserNum() #initilize user miles conversion usrMile = 0.0 #run user K to M conversion usrMile = compute_miles(usrKM) #return the Kilometers to Miles to the user print('\nKilometers ' + str(usrKM) + ' is equal to ' + format(usrMile, '.2f') + ' miles') # End Of Program # #let user know program has finished print('\nProgram has finished, good bye.') # End Of Line #
# Program name: jmCelsiusToFah.py # Author: Jonathan McDonald # Date last updated: 2/17/2017 # Purpose: This program prints a conversion table of Celsius and Fahrenheit temperatures # from 1 through 20 degrees Celsius. # Initialize My Variables # ##my_PL_inc As Int #this is my print line increment my_PL_inc = 0 ##myStart as Int myStart = 0 ##myEnd as Int #the range stops at n-1 or myEnd-1 myEnd = 21 ##myR_inc as Int #this is my range incrementation myR_inc = 1 #my function to convert deg Fahrenheit to deg Celsius def getF_to_C(myDeg_F): """Get degree Fahrenheit and convert to Celsius""" ##deg_C As Float #explicit float deg_C = 0.0 #do math conversion deg_C = (5.0/9.0)*(myDeg_F - 32.0) return deg_C #my function to convert deg Celsius to deg Fahrenheit def getC_to_F(myDeg_C): """Get degree Celsius and convert to Fahrenheit""" ##deg_F As Float #explicite float deg_F = 0.0 #do math conversion deg_F = (myDeg_C * (9.0/5.0)) + 32.0 return deg_F #my function to print the conversion table def showDegreeOutput(myDeg_In, myDeg_Equ, myCurLine): """Prints out the degree conversion table""" ##first call if myCurLine == 0: print('\t________________') print('\t| Deg C\t| Deg F\t|') #there are two leading spaces elif myCurLine < (myEnd - 1): #print('\t-----------------------------') print('\t| ' + format(myDeg_In, '.1f') + '\t| ' + format(myDeg_Equ, '.1f') + '\t|') #there are three leading spaces elif myCurLine == (myEnd - 1): #print('\t-----------------------------') print('\t| ' + format(myDeg_In, '.1f') + '\t| ' + format(myDeg_Equ, '.1f') + '\t|') #there are three leading spaces print('\t-----------------------------') else: print('Loop control count error.') #inform user what this program accepts for input print('This program output the degree Fahrenheit from 0 to 20 degrees in Celsius.\n') ##for myDegree in range(0, 21, 1): ##changed from hard coded to varible values for myDegree in range(myStart, myEnd, myR_inc): #increment range starting at 0 but ends at n-1 #deg_equ as float, degree equlivulant deg_equ = 0.0 #explicit float reset and initial value #call my getC_to_F function to convert degree deg_equ = getC_to_F(myDegree) #call showDegreeOutput showDegreeOutput(myDegree, deg_equ, my_PL_inc) #increment line control my_PL_inc = my_PL_inc + 1 # End Of Program # #let user know program has finished print('\nProgram has finished, good bye.') # End Of Line #
#! python3.4 ####################################################################### # Author: Jonathan McDonald # CST 100 Fall B # ID: 1208311061 # Section: # Date: 11/05/2014 ####################################################################### # PROGRAM DESCRIPTION # This program will play a number guessing game. That will allow a user three # attempts to guess a randomly generated number between 1 and 20. A while loop # is used to set the maximum number of attempts with if conditionals to catch correct # guesses. # # DESCRIPTION OF VARIABLES # NAME | TYPE | DESCRIPTION # ------------------------------------------------------------------- # intro_name | str | the opening introduction to get name # intro_num | str | the opening introduction to get number # too_low | str | return string for low guess # too_high | str | return string for high guess # try_again | str | return string to try again # winner | str | return string for correct guess # gm_lost | str | return string one for out of guesses # user_att | int | the number of attempts of the player # ran_num | num | random number used for game # user_name | str | the name of the player # user_number | num | the number picked by the player # ------------------------------------------------------------------- ####################################################################### ##* MAIN PROGRAM *## import random #get extended random functionality# #* Declare and initialize variables *# intro_name = "Hello! What is your name?" intro_num = "I am thinking of a number between 1 and 20. Take a guess and give me a number." too_low = "Your guess is to low." too_high = "Your guess is to high." try_again = "Try another guess." winner = "Winner you have correctly guessed the number" gm_lost = "Your three guesses are over. The number I was thinking of was" #* Set initial conditions *# user_att = 0 #set to starting attempts of none# ran_num = random.randrange (1,21) #initialize the random number between [1,21)# #* Define functions *# def guess_tree (guess, random, attempt): if guess < random: #to low# print (too_low) guess = int(input(print (try_again))) else: guess > random #to high# print (too_high) guess = int(input(print (try_again))) return guess, attempt + 1 #if guess = random then it is passed back and caught by the second if statement# #* Run the game *# user_name = input(print(intro_name )) #get user name and assign# #print(ran_num ) #this is used for checking the logic flow by displaying the random number. Normally commented out# user_num = int(input(print("Hi, ", user_name, intro_num ))) #get user number# if user_num == ran_num: #check for correct first guess# print (winner , " on the first try!" ) else: while user_att < 2: #this is for re guessing# if user_num != ran_num: user_num, user_att = guess_tree (user_num, ran_num, user_att) if user_num == ran_num: #this catches the correct second guess# print (winner, "on attempt number", user_att + 1 ) break #this is to prevent an endless loop and to exit while# if user_num != ran_num: #this catches the third try wrong guess# print(gm_lost, ran_num) print("Game Over") ##* END OF MAIN PROGRAM *## ##* Exit the program *## ####################################################################### ##* END OF LINE *##
''' Created on 19 Feb 2018 @author: williamherbosch Proof-of-Concept : Convolution Neural Network for MNist dataset This program offers an alternative architectural structure to neural network design by applying a convolutional model to the MNist dataset. A convolutional network is a form of deep, feed-forward neural network that variations of multi-layered perceptrons to require minimal preprocessing, by having their architecture "share" weights between different layers. What this means is that instead of taking a picture of MNist and splitting each 28x28 image into a row of pixels, a convolutional network looks at the 2D image itself and learns from the image as a whole. For the most part, this program is practically identical to the Dense Keras neural network, with two main distinctions 1) The way in which the different sub-datasets are initialised (i.e. trainingobjects, testobjects, traininglabels, testlabels) 2) The actual structure of the neural network to implement convolutional layers. This alternative neural network does take some time to run when compared to the dense network, so a workaround will try to be found. ''' #IMPORTS #################################################################################### #Allows for the use of more advanced mathematical structures and calculations to be computed in Python. import numpy as np #Import the entirty of Keras, needed for both converting the vectors of the image into a matrix import keras #Needed for importing the mnist dataset, a dataset of 60000 white images that are 28x28 (784) pixels of the 10 digits, along with a test set of 10000 images. from keras.datasets import mnist #Imports the sequential keras model. This computes a linear stack of layers similar to that in neural networks from keras.models import Sequential #Operations that are used in the layers of the network #Dense is used for the operation "output = activation(dot(input, kernel)) + bias" #Dropout consists of randomly setting a rate at which it converts inputs to 0 after each update. This helps prevents overfitting #Conv2D represents a 2D convolutional layer (specifically for images (which are 2D)) #MaxPooling2D allows the network to down-sample an input representation, reducing its dimensionality and allowing for assumptions to be made about features contained within the network's individual bins. #Flatten the inputs to form a single line. Does not effect batch size. from keras.layers import Dense, Dropout, Conv2D, MaxPooling2D, Flatten ##An optimizer for compiling Keras from keras.optimizers import RMSprop #A 2D plotting library that displays the images in the dataset. import matplotlib.pyplot as mplpp #imports the randomizer for picking different test objects import random #GLOBAL #################################################################################### #Set the number of itterations the network trains for numberOfEpochs = 20 #Set the batchSize (have the network train on chunks of the data rather than a whole). Number should preferably be divisible by training samples batchSize = 100 #The number of outputs/classes the network can have (0-9 in this case) numberOfClasses = 10 #Original MNist has 60K training samples, filter this down to 2K (80% training data) ntrainingObservations = 2000 #Original MNist has 10K test samples, filter this down to 400 (20% test data) ntestObservations = 10000 #METHODS #################################################################################### #a method used to display a test opject in a popup window, takes in the testobject element number, the testobjects themselves and their corrisponding labels def displayMNist(number, testObjectsFilter, testLabelsFilter): #Assigns the label of the corrisponding test object label = testLabelsFilter[number].argmax(axis=0) #takes the information from the test object and reshapes it into a 28x28 grid (the image) image = testObjectsFilter[number].reshape([28, 28]) #Sets a title containing which test element is being presented, as well as displaying the true label mplpp.title("Example: %d Label: %d"%(number, label)) #Display the image in white on black mplpp.imshow(image, cmap=mplpp.get_cmap("gray")) mplpp.show() #a method used for predicting the test object's label def predict(range): #range is a list of 10 elements, each element represents the likelyhood of a test object being of that label (i.e. the 1st value represents how likely it is a 0) #Therefore, we can take these values, find which is the greates, and assume that this is the most likeliest label, thus we make it our prediction #If the element with the highest value in the list is the 1st element (start from range[0]), then return 0 if max(range) == range[0]: return 0 #Repeat for all numbers 0-9 if max(range) == range[1]: return 1 if max(range) == range[2]: return 2 if max(range) == range[3]: return 3 if max(range) == range[4]: return 4 if max(range) == range[5]: return 5 if max(range) == range[6]: return 6 if max(range) == range[7]: return 7 if max(range) == range[8]: return 8 if max(range) == range[9]: return 9 #MAIN #################################################################################### def main(): #Loads the MNist dataset and assigns it to training and test observations #Training = 60000 rows and 784 cols - Testing = 10000 rows and 784 cols #784 attributes because we check each cell in the 28x28 grid of the image (trainingObjects, trainingLabels), (testObjects, testLabels) = mnist.load_data() #Reshape the data so that we have each row as a different observation (for the backend, we assume that the data format is (rows, cols, channels)) trainingObjects = trainingObjects.reshape(trainingObjects.shape[0], 28, 28, 1) #Do the same for the test objects testObjects = testObjects.reshape(testObjects.shape[0], 28, 28, 1) #set the type of values in the sets as float32 (single precision float) trainingObjects = trainingObjects.astype("float32") testObjects = testObjects.astype("float32") #We want to work on a small section of the data, so we only look at the specified number of rows (this might create unbalance however) trainingObjectsFilter = trainingObjects[:ntrainingObservations, :] testObjectsFilter = testObjects[:ntestObservations, :] #Print some information to the terminal so we know what data we are focusing on print("trainingObjects dimensions:", trainingObjectsFilter.shape) print("training samples:", trainingObjectsFilter.shape[0]) print("test samples:", testObjectsFilter.shape[0]) #Now that we have data, we can assign their corresponding labels #This is done by converting a class vector of labels into a binary class matrix trainingLabels = keras.utils.to_categorical(trainingLabels, numberOfClasses) testLabels = keras.utils.to_categorical(testLabels, numberOfClasses) #Filter the test labels trainingLabelsFilter = trainingLabels[:ntrainingObservations, :] testLabelsFilter = testLabels[:ntestObservations, :] #Initialize a sequential model for the neural network #The Sequential model is a linear stack of layers #These layers act somewhat similar to hidden layers in a multi-layerd neural network model = Sequential() #Add out first (input) layer, a Conv2D #32 refers to the dimensionality of the output space (i.e. the number of output filters in the convolution) #the kernel size specifies the width and height of a 2d convolution window. #Our input shape (for when we add our input later) is the dimentions of the format of the backend model.add(Conv2D(32, kernel_size=(3, 3), activation="sigmoid", input_shape=(28, 28, 1))) #An additional layer that has an output filter of double that of the previous model.add(Conv2D(64, (3, 3), activation="sigmoid")) #A maxpool layer used to downscale the input in both width and height model.add(MaxPooling2D(pool_size=(2, 2))) #Because we do not want to risk overfitting, we drop some neurons with the least relevant information once undergone the initial layer model.add(Dropout(0.2)) #A flatten layer used to represent all data thus far on a single row of data (a now 1D representation of the MNist image) model.add(Flatten()) #From here, it's almost identical to the Dense neural network #again, for same as the Dense neural network, we'll have a value of 500 model.add(Dense(500, activation="sigmoid")) #Repeat for a second time model.add(Dropout(0.2)) #Formulates the outputs into a range of 0-9 values (this is the output layer) model.add(Dense(numberOfClasses, activation="softmax")) #Gives a summary of the structure of the network created (i.e. how many neurons in each layer, etc) model.summary() #Compiles the model #Catagorical Crossentropy refers to the loss generated between predictions and target outputs #Also initializes an optimiser in RMSprop, which is a learning rate method that divides the learning rate by an exponentially decaying average of squared gradients model.compile(loss='categorical_crossentropy', optimizer = RMSprop(), metrics = ['accuracy']) #Fits the model and commenses training history = model.fit(trainingObjectsFilter, trainingLabelsFilter, batch_size=batchSize, epochs=numberOfEpochs, verbose=1, validation_data=(testObjectsFilter, testLabelsFilter)) #Evaluates the final learning experience of the network by providing the total loss and the accuracy of predictions score = model.evaluate(testObjectsFilter, testLabelsFilter, verbose=0) #prints loss and accuracy to terminal print("Test loss:", score[0]) print("Test accuracy:", score[1]) #Uses the now trained model on the test dataset in batches of 10 and predicts labels for each object predictions = model.predict(testObjectsFilter, batch_size = 10) #For 20 different test objects for i in range(2): rand = random.randint(0,199) #Print the predicted output to the terminal print("Prediction: ",predict(predictions[rand])) #Display the target output in a popup window displayMNist(rand, testObjectsFilter, testLabelsFilter) #Begins the program by running Main method if __name__ == '__main__': main()
# python ScriptDescomposicion.py [int] import sys if len(sys.argv)==2: numero=sys.argv[1] longitud=len(numero) unidades={1:"unidad",2:"decena",3:"centena",4:"unidad de millar",5:"decena de millar"} numero=numero[::-1] for i in range(longitud): num=int(numero[i]) * 10**i # numero*(10^i) print(f"{num:5d} {unidades[i+1]}") else: print("error")
numbers = [14,5,6,7,4,8,15] def square(x): return x*x # new_list = [] # for x in numbers: # new_list.append(square(x)) new_list = [square(x) for x in numbers] new_list2 = map(square, numbers) print(new_list) print(list(new_list2))
age = 23 if age >= 18: adult = True print("you're an adult") else: adult = False print("you aren't an adult") # ternary operator adult = True if age >= 18 else False # one line print("you're an adult" if adult else "you aren't an adult") # number = 10 print("this number is very large" if number > 1000 else "this number is quiet large" )
numbers = [1, 5, 7, 12, 5, 10, 4, 2] new_list = [] for number in numbers: if number % 2 == 0: new_list.append(number) print(new_list) # Using list comprehension new_list_C = [x for x in numbers if x%2 == 0] print(new_list_C) # powers_of_two = [2 ** x for x in numbers] print(powers_of_two) # words = ['aUtO', 'cAR', 'AnGer', 'fox', 'PEoplE'] words = [word.upper() if word.startswith(('a', 'A')) else word.lower() for word in words ] print(words)
n1=float(input("Ingresa el primer numero: ")) n2=float(input("Ingresa el segundo numero: ")) print("Son iguales?",n1==n2) print("Son iguales?",n1!=n2) ## cadena=input("Escribe una cadena") lon=len(cadena) print("es mayor que 3 y menor que 10?",3<lon<10) ## NumeroMagico=12345679 NumeroUsuario=int(input("ingresa un numero entero entre 1 y 9: ")) NumeroUsuario*=9 NumeroMagico*=NumeroUsuario print("Numero Magico: ",NumeroMagico) ## comando="Salir" if comando=="Entrar": print("Entrar") elif comando=="saluda": print("hola") elif comando=="Salir": print("Salir") else: print("comando no reconocido") pass
## script, abrir con cmd ejemplo: python sys_1.py "palabra" 5 import sys print("hola") if len(sys.argv)==3: texto=sys.argv[1] repeticiones=int(sys.argv[2]) for r in range(repeticiones): print(texto) else: print("introduce los argumentos correctamente")
##tuplas, usa metodos muy similares a las listas pero no pueden ser modificadas tupla=(10,[1,2,3],"hola",-50); print(tupla,"\n",tupla[0],"\n",tupla[1],"\n",tupla[1:],) ## No se puede redefinir el valor de una tupla print(len(tupla),len(tupla[1])) print(tupla.index(-50)) ## dice el indice en donde se encuentra el valor -50 print(tupla.count(-50)) ## Cuenta las veces que esta -50 en la tupla ## Conjuntos print("conjuntos\n") conjuntoV=set() ##Conjunto vacio conjunto={1,2,3} ## Conjunto inicializado conjunto.add(4) # Metodo para agregar valores print(conjunto) conjunto.add(0) # Agrega elementos al conjunto en colecciones desordenadas print(conjunto) conjunto.add('A') conjunto.add('H') conjunto.add('Z') conjunto.discard('A') print(conjunto) test={"jesus","jesus","jesus"} ## Elimina los valores repetidos print(test) l=[1,2,5,5,2,3,1] c=set(l) #transforma la lista l a un conjunto print(c) #los valores repetidos son eliminados l=list(c) #transforma conjunto a lista l=list(set(l)) #hace todo lo anterior cad="hola mundo" # Se puede hacer lo mismo con cadenas c=set(cad) print(c) ## Diccionarios diccionarioVacio={} type(diccionarioVacio) #muestra el tipo de variable colores={"amarillo":"yellow","azul":"blue","verde":"green"} print(colores) # No es ordenado print(colores["amarillo"]) #se usa la palabra clave "amarillo" para ingresar al valor ("yellow") numeros={1:"numero1",2:"numero2",3:"numero3"} print(numeros[2]) #tambien se pueden usar numeros colores["amarillo"]="amarillow" #se pueden modificar los valores refiriendonos a la palabra clave print(colores) del(colores["azul"]) #se pueden borrar lo valores print(colores) edades={"jesus":22,"juan":33,"mario":22,"oscar":50} edades["jesus"]+=1 print(edades) for clave in edades: ## acceder a valores de un diccionario print(clave," tiene: ",edades[clave]) ## la variable edad hace referencia a las palabras clave ## Otro metodo para hacerlo (uso de items) print("lo mismo pero con items") for clave,valor in edades.items(): print(clave,valor) ## Personajes personajes=[] #lista vacia p1={"Nombre":"Jesus","Pais":"Mexico","ocupacion":"estudiante"} p2={"Nombre":"juan","Pais":"guatemala","ocupacion":"huachicolero"} p3={"Nombre":"maria","Pais":"colombia","ocupacion":"estudiante"} personajes.append(p1) personajes.append(p2) personajes.append(p3) print(personajes) for p in personajes: #print(p) print(p["Nombre"],p["Pais"],p["ocupacion"])
def CuentaAtras(num): num-=1 if num>0: print(num) CuentaAtras(num) # Funcion llamada a si misma else: print("fin de la cuenta") print(f"fin de la funcion {num}") # el mensaje se muestra al final de cada ocacion # que se llamo la funcion a si misma CuentaAtras(5) ## Factorial def Factorial(num): print(f"Valor inicial = {num}") if num>1: num=num*Factorial(num-1) print(f"Valor final = {num}") return num n=5 print(f"factorial de {n} = {Factorial(n)}")
#finding hcf using Euclids division lemma def HCF(NO1, NO2): if NO2>NO1: temp = NO1 NO1 = NO2 NO2 = temp del temp while True: rem = NO1 % NO2 if rem != 0: NO1 = NO2 NO2 = rem else: return NO2 break num1 = int(input("Please enter the first number: ")) num2 = int(input("Please enter the second number: ")) hcf = HCF(num1, num2) print(f"The HCF of the {num1} & {num2} is: {hcf}")
import sys sys.path.insert(0, '..') from search import * if __name__ == '__main__': print('### Test Recursion ###') l = [4, 5, 8, 9, 10, 15, 17] print(f'list: {l}') key = 15 print(f'search for {key}: ', end = '') print(binary_search(l, 0, len(l)-1, key)) key = 4 print(f'search for {key}: ', end = '') print(binary_search(l, 0, len(l)-1, key)) key = 17 print(f'search for {key}: ', end = '') print(binary_search(l, 0, len(l)-1, key)) key = 6 print(f'search for {key}: ', end = '') print(binary_search(l, 0, len(l)-1, key)) print('\n### Test Recursion Iteration ###') l = [4, 5, 8, 9, 10, 15, 17] print(f'list: {l}') key = 15 print(f'search for {key}: ', end = '') print(binary_search_iteration(l, key)) key = 4 print(f'search for {key}: ', end = '') print(binary_search_iteration(l, key)) key = 17 print(f'search for {key}: ', end = '') print(binary_search_iteration(l, key)) key = 6 print(f'search for {key}: ', end = '') print(binary_search_iteration(l, key))
#You are given a space separated list of numbers. #Your task is to print a reversed NumPy array with the element type float. #Input Format #A single line of input containing space separated numbers. #Output Format #Print the reverse NumPy array with type float. #Sample Input # 1 2 3 4 -8 -10 #Sample Output #[-10. -8. 4. 3. 2. 1.] #Write your code below list1 = [] number = int(input("enter num")) for i in range(number): arr = int(input()) list1.append(arr) list1.reverse() print(list1)
''' You are given an array of integers. You should find the sum of the elements with even indexes (0th, 2nd, 4th...) then multiply this summed number and the final element of the array together. Don't forget that the first element has an index of 0. For an empty array, the result will always be 0 (zero). Input: A list of integers. Output: The number as an integer. Precondition: 0 ≤ len(array) ≤ 20 all(isinstance(x, int) for x in array) all(-100 < x < 100 for x in array) ''' def checkio(array): length = len(array) if length == 0: return 0 count = result = 0 while count < length: result += array[count] count += 2 result *= array[length-1] return result ''' Clear: 1. if len(array) == 0: return 0 return sum(array[0::2]) * array[-1] 2. checkio=lambda x: sum(x[::2])*x[-1] if x else 0 3. return sum(el for el in array[::2]) * array[-1] if array else 0 4. if not array: return 0 return sum(array[::2])*array[-1] Creative: 5. checkio = lambda array: sum(array[::2]) * sum(array[-1:]) ''' #These "asserts" using only for self-checking and not necessary for auto-testing if __name__ == '__main__': assert checkio([0, 1, 2, 3, 4, 5]) == 30, "(0+2+4)*5=30" assert checkio([1, 3, 5]) == 30, "(1+5)*5=30" assert checkio([6]) == 36, "(6)*6=36" assert checkio([]) == 0, "An empty array = 0"
''' The labyrinth has no walls, but bushes surround the path on each side. If a players move into a bush, they lose. The labyrinth is presented as a matrix (a list of lists): 1 is a bush and 0 is part of the path. The labyrinth's size is 12 x 12 and the outer cells are also bushes. Players start at cell (1,1). The exit is at cell (10,10). You need to find a route through the labyrinth. Players can move in only four directions--South (down [1,0]), North (up [-1,0]), East (right [0,1]), West (left [0, -1]). The route is described as a string consisting of different characters: "S"=South, "N"=North, "E"=East, and "W"=West. Input: A labyrinth map as a list of lists with 1 and 0. Output: The route as a string that contains "W", "E", "N" and "S". Precondition: Outer cells are pits. len(labyrinth) == 12 all(len(row) == 12 for row in labyrinth) ''' #Your code here #You can import some modules or create additional functions ori_right = ['N', 'W', 'S', 'E'] ori_left = ['N', 'E', 'S', 'W'] def turn_right(ori): return ori_right[ori_right.index(ori) - 1] def turn_left(ori): return ori_left[ori_left.index(ori) - 1] def front_watch(maze_map, ori, px, py): if ori == 'N': px -= 1 if ori == 'E': py += 1 if ori == 'S': px += 1 if ori == 'W': py -= 1 return maze_map[px][py] def real_walk(ori, px, py): if ori == 'N': px -= 1 if ori == 'E': py += 1 if ori == 'S': px += 1 if ori == 'W': py -= 1 return px, py def left_watch(maze_map, ori, px, py): ori = turn_left(ori) return front_watch(maze_map, ori, px, py) def right_watch(maze_map, ori, px, py): ori = turn_right(ori) return front_watch(maze_map, ori, px, py) def walk(maze_map, ori, px, py, result): if left_watch(maze_map, ori, px, py) == 0: ori = turn_left(ori) if front_watch(maze_map, ori, px, py) == 0: result += ori px, py = real_walk(ori, px, py) return [result, ori, px, py] else: ori = turn_right(ori) return walk(maze_map, ori, px, py, result) def checkio(maze_map): orientation = 'E' position = [1, 1] result = '' while 1: result, orientation, position[0], position[1] = walk(maze_map, orientation, position[0], position[1], result) if position[0] == 10 and position[1] == 10: break return result # def checkio(maze_map): # def canwalk(come, px, py): # out = '' # if maze_map[px-1][py] == 0: # out += 'N' # if maze_map[px][py+1] == 0: # out += 'E' # if maze_map[px+1][py] == 0: # out += 'S' # if maze_map[px][py-1] == 0: # out += 'W' # if come == 'N': # come = 'S' # elif come == 'S': # come = 'N' # elif come == 'W': # come = 'E' # elif come == 'E': # come = 'W' # out = out.replace(come, '') # return out # def walk(orientation, px, py): # if orientation == 'N': # px -= 1 # if orientation == 'E': # py += 1 # if orientation == 'S': # px += 1 # if orientation == 'W': # py -= 1 # return [px, py] # def load(save_p, save_choose, save_result): # position = save_p[-1] # del save_p[-1] # choose = save_choose[-1] # del save_choose[-1] # result = save_result[-1] # del save_result[-1] # return [position, choose, result] # def save(position, choose, result, save_p, save_choose, save_result): # save_p.append(position) # save_choose.append(choose) # save_result.append(result) # position = [1, 1] # choose = canwalk('', position[0], position[1]) # result = '' # save_p = [] # save_choose = [] # save_result = [] # while 1: # if len(choose) == 0: # if len(save_p) > 0: # position, choose, result = load(save_p, save_choose, save_result) # continue # orientation = choose[0] # if len(choose) > 1: # if position in save_p: # if position == save_p[-1]: # del save_p[-1] # del save_choose[-1] # del save_result[-1] # position, choose, result = load(save_p, save_choose, save_result) # continue # save(position, choose.replace(orientation, ''), result, save_p, save_choose, save_result) # position = walk(orientation, position[0], position[1]) # result += orientation # if position[0] == 10 and position[1] == 10: # return result # choose = canwalk(orientation, position[0], position[1]) if __name__ == '__main__': #This code using only for self-checking and not necessary for auto-testing def check_route(func, labyrinth): MOVE = {"S": (1, 0), "N": (-1, 0), "W": (0, -1), "E": (0, 1)} #copy maze route = func([row[:] for row in labyrinth]) pos = (1, 1) goal = (10, 10) for i, d in enumerate(route): move = MOVE.get(d, None) if not move: print("Wrong symbol in route") return False pos = pos[0] + move[0], pos[1] + move[1] if pos == goal: return True if labyrinth[pos[0]][pos[1]] == 1: print("Player in the pit") return False print("Player did not reach exit") return False # These assert are using only for self-testing as examples. assert check_route(checkio, [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1], [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1], [1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1], [1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1], [1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1], [1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1], [1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]), "First maze" assert check_route(checkio, [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]), "Empty maze" assert check_route(checkio, [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1], [1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1], [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1], [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1], [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1], [1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1], [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1], [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1], [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1], [1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]), "Up and down maze" assert check_route(checkio, [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1], [1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1], [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1], [1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1], [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1], [1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1], [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1], [1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1], [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1], [1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]), "Dotted maze" assert check_route(checkio, [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1], [1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1], [1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1], [1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1], [1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1], [1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1], [1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1], [1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]), "Need left maze" assert check_route(checkio, [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1], [1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1], [1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1], [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1], [1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]), "The big dead end." print("The local tests are done.")
# coding=utf-8 #DCT中的M和N参数,此处设置为8 MN = 8; def Block(matrix, sizeX,sizeY): little_matrix = [] #start_point是每个8*8矩阵的第一个点 for Y in range(0, sizeY / MN): for X in range(0, sizeX / MN): start_point = Y * sizeX * 8 + X * 8 #初始化中间矩阵 mid_matrix = [] #生成中间矩阵 for i in range(0, MN): for j in range(0, MN): mid_matrix.append(matrix[start_point + i*sizeX + j]) #压栈 little_matrix.append(mid_matrix) return little_matrix def De_Block(little_matrix, size): matrix = [] for Y in range(0, size[1] / MN): for count1 in range(0, MN): for X in range(0, size[0] / MN): for count2 in range(0, MN): if X+Y*(size[0]/MN) >= len(little_matrix): print ("?0") elif count2+count1*MN >= len(little_matrix[X+Y*(size[0]/MN)]): print ("?1 %d %d %d %d %d %d" %(X,Y,count1, count2,count2+count1*MN, len(little_matrix[X+Y*(size[0]/MN)]))) matrix.append(little_matrix[X+Y*(size[0]/MN)][count2+count1*MN]) # matrix.append(count2 + X*MN + count1*MN*(size[0]/MN) + Y*MN*(size[0]/MN)*MN) return matrix
""" Author: Adam Harris Create a set of images containing a random number of omniglot charachters in arbitrary configurations, alongside a CSV of image labels (the number of charachters contained in the image). Omniglot characters downloaded from https://github.com/brendenlake/omniglot Lake, B. M., Salakhutdinov, R., and Tenenbaum, J. B. (2015). Human-level concept learning through probabilistic program induction. Science, 350(6266), 1332-1338. """ from PIL import Image, ImageDraw import numpy as np import os import pandas as pd num = 10000 # How many images do you want WIDTH, HEIGHT = 500, 500 # Dimensions of image in pixels xaxis = [50, 150, 250, 350, 450] # Possible x-axis positions where an image could be placed yaxis = [50, 150, 250, 350, 450] # Possible y-axis positions where an image could be placed BG = 255, 255, 255 # Background colour label = np.zeros((num,), dtype=int) # Initialise vector for image labels dirName = r"/Users/AdamHarris/Desktop/images_background" # Where are you omniglot charachters stored? outputDirName = r"/Users/AdamHarris/Desktop/OmniglotData" # Where would you like to save the dataset ''' Search the directory containing the omniglot characters and store the paths to the images ''' def getListOfFiles(dirName): # create a list of file and sub directories # names in the given directory listOfFile = os.listdir(dirName) allFiles = list() # Iterate over all the entries for entry in listOfFile: # Create full path fullPath = os.path.join(dirName, entry) # If entry is a directory then get the list of files in this directory if os.path.isdir(fullPath): allFiles = allFiles + getListOfFiles(fullPath) else: allFiles.append(fullPath) return allFiles omniglot = getListOfFiles(dirName) ''' Generate dataset using the image paths. For each image, an random threshold number between 0-1 is generated. For each x,y coordinate pair within that image, a second number, prop is generated. If variable Prob is less than the threshold for that image, a random omniglot charachter is pasted in that location, with a randomly selected size and x,y jitter. The function to choose an arbitrary orientation has been ''' for image in range(num): # Create blank canvas with properties specified above img = Image.new('RGB', (WIDTH, HEIGHT), BG) draw = ImageDraw.Draw(img) # set threshold for this image thresh = np.random.uniform(0, 1) # Cycles through each x,y coordinate pair for i in range(len(xaxis)): for t in range(len(yaxis)): # Will this location have an image? prob = np.random.uniform(0, 1) if prob < thresh: # Counter for the image label label[image] += 1 # Select random omniglot charachter index = np.random.randint(0, len(omniglot)) path = omniglot[index] character = Image.open(path) #angle = np.random.randint(0, 360) #shape = shape.rotate(angle, expand=1) # X,y jitter to reduce to ouvert grid configuration (hardcoded bounds) x_jitter, y_jitter = np.random.randint(-30, 30), np.random.randint(-30, 30) # Resize charachter with hardcoded bounds to prevent overlap size = np.random.randint(10, 40) character = character.resize((2 * size, 2 * size)) character = character.convert('RGBA') # Paste in resized charachter at jittered position position = [(xaxis[i] - (size)) + x_jitter, (yaxis[t] - size) + y_jitter, (xaxis[i] + size) + x_jitter, (yaxis[t] + size) + y_jitter] img.paste(character, position, character) # Connvert to greyscale and save img = img.convert('L') img.save(outputDirName + "/Images/" + str(image + 1).zfill(5) + ".png") print(label[image]) # Print labels for dataset and save them to a csv print(label) df = pd.DataFrame(label) df.to_csv(outputDirName + '/labels.csv', index=False, header=False)
""" DEAD_CELLS = 0 [x as representation] ALIVE_CELLS = 1 [* as representation] RULES of LIFE: Any live cell with 0 or 1 live neighbors becomes dead, because of underpopulation Any live cell with 2 or 3 live neighbors stays alive, because its neighborhood is just right Any live cell with more than 3 live neighbors becomes dead, because of overpopulation Any dead cell with exactly 3 live neighbors becomes alive, by reproduction """ from pprint import pprint import math, random import copy import time import sys import argparse def dead_state(width, height): return [[0 for _ in range(height)] for _ in range(width)] def get_board_dimensions(board): width = len(board) height = len(board[0]) return width, height def random_state(width, height): board_state = dead_state(width, height) for row in range(len(board_state)): for col in range(len(board_state[row])): random_no = random.random() if random_no >= 0.85: board_state[row][col] = 1 else: board_state[row][col] = 0 return board_state def render(initial_board_state): lines = [] char_map = { 0 : " ", 1 : u"\u2588" } board_state = copy.deepcopy(initial_board_state) board_width, board_height = get_board_dimensions(initial_board_state) for col in range(0,board_height): line = '' for row in range(0,board_width): line += char_map[initial_board_state[row][col]] * 2 lines.append(line) print("\n".join(lines)) def get_new_cell_value(row, col, initial_state): cell_neighbour_population = 0 range_start = { row: (row - 1), col: (col - 1) } range_end = { row: (row + 1), col: (col + 1) } board_width, board_height = get_board_dimensions(initial_state) return_val = 0 for i in range(range_start[row], range_end[row] + 1): if i < 0 or i >= board_width: continue for j in range(range_start[col], range_end[col] + 1): if j < 0 or j >= board_height: continue if i == row and j == col: continue if initial_state[i][j] == 1: cell_neighbour_population += 1 if initial_state[row][col] == 1: if cell_neighbour_population <= 1: return_val = 0 elif cell_neighbour_population <= 3: return_val = 1 else: return_val = 0 else: if cell_neighbour_population == 3: return_val = 1 else: return_val = 0 return return_val def next_board_state(initial_board_state): board_width, board_height = get_board_dimensions(initial_board_state) new_state = dead_state(board_width, board_height) for row in range(0,board_width): for col in range(0,board_height): new_val = get_new_cell_value(row, col, initial_board_state) new_state[row][col] = new_val return new_state def load_state_from_file(file_path): with open(file_path, 'r') as infile: lines = [l.rstrip() for l in infile.readlines()] output = dead_state(len(lines), len(lines[0])) for i,line in enumerate(lines): for j,val in enumerate(line): output[i][j] = int(val) return output def main(): parser = argparse.ArgumentParser(description="Runs Conway's Game of Life simulation.") parser.add_argument('--grid-size', dest='N', required=False) parser.add_argument('--interval', dest='interval', required=False) parser.add_argument('--toad', action='store_true',required=False) parser.add_argument('--blinker', action='store_true',required=False) parser.add_argument('--beacon', action='store_true',required=False) parser.add_argument('--glider', action='store_true',required=False) ## TODO: Add gosper glider gun # parser.add_argument('--gosper', required=False) args = parser.parse_args() N = 100 if args.N and float(args.N) > 8: N = int(args.N) update_interval = 0.05 if args.interval: update_interval = float(args.interval) board_state = random_state(N, N) if args.toad: board_state = load_state_from_file('./toad.txt') elif args.blinker: board_state = load_state_from_file('./blinker.txt') elif args.beacon: board_state = load_state_from_file('./beacon.txt') elif args.glider: board_state = load_state_from_file('./glider.txt') next_state = board_state while True: render(next_state) next_state = next_board_state(next_state) time.sleep(update_interval) if __name__ == "__main__": main()
# string of numbers as input for 4 digit OTP generation a=input() str1="" str2="" # to iterate through the string for i in a: # to ignore number if it is even if int(i)%2==0: continue #else for odd number square it else: b=int(i)*int(i) str1=str1+str(b) for i in range(len(str1)): if len(str2)!=4: str2=str2+str1[i] print(str2)
a=input().split(',') str2="" for j in a: str1="" l=[] # to separate digits and numbers for i in j: if i.isdigit()==True: l.append(i) elif i.isalpha()==True: str1=str1+i l1=list(map(int,l)) l1.sort() l1.reverse() m=min(l1) # if length of name given is present in number than return letter at that position if len(str1) in l1: str2=str2+str1[len(str1)-1] else: for i in l1: #otherwise print letter at position less than length if i<len(str1) and i>=m: m=i n=str1[m-1] break # if there is no number less than length of name return 'X' else: n='X' str2=str2+n print(str2)
#function definition def most_frequent(string): frequency = {} test= string for x in test: if x in frequency: frequency[x] +=1 else: frequency [x] =1 #sorting and reversing the dictionary values sort_freq = sorted(frequency.items(), key=lambda x: x[1], reverse=True) for i in sort_freq: print(i[0] +" = "+ str(i[1])) #main function _in = input ("Please enter a string\n") most_frequent(_in)
import random import math #rock crush scissors #scissors cut paper #paper covers rock #lizard poisions spock #spock lazers rock #scissors decapites lizard #paper disproves spock #lizzard eats paper #rock crushes lizard #spock smashes scissors def rpsSwitch(argument): switcher ={ 1: "Rock", 2: "Paper", 3: "Scissors", 4: "Lizzard", 5: "Spock" } print(switcher.get(argument, "invalid answer")) def winnerCheck(user, ai): if user == ai: print("We tied") elif user == 1: if ai == 2: print("Paper cover Rock, You Loose") elif ai ==3: print("Rock Smashes Scissor, You Win") elif ai == 4: print("Rock Kills Lizard, You Win") elif ai == 5: print("Spock Vaporizes Rock, You Loose") elif user == 2: if ai == 1: print("Paper cover Rock, You Loose") elif ai == 3: print("Scissors cuts Paper, You Loose") elif ai == 4: print("Lizzard eats Paper, You Loose") elif ai == 5: print("Paper disproves Spock, You Win") elif user == 3: if ai == 1: print("Rock Smashes Scissor, You Loose") elif ai == 2: print("Scissors cuts Paper, You Win") elif ai == 4: print("Scissors dicapitates Lizzard, You Win") elif ai == 5: print("Spock breaks Scissors, You Loose") elif user == 4: if ai == 1: print("Rock Kills Lizard, You Loose") elif ai == 2: print("Lizzard eats Paper, You Win") elif ai == 3: print("Scissors dicapitates Lizzard, You Loose") elif ai == 5: print("Lizard poisons Spock, You Win") elif user == 5: if ai == 1: print("Spock Vaporizes Rock, You Win") elif ai == 2: print("Papper disproves Spock, You Loose") elif ai == 3: print("Spock breaks Scissors, You Win") elif ai == 4: print("Lizzard poisons Spock, You Loose") yn = 0 rock = 1 paper =2 scissors=3 lizard=4 spock=5 print("Let's PLay Rock Paper Scissors Lizard Spock!\n") while (yn == 0): choice = random.randint(1, 5) print("Select Your Choice") print("Type:\n1 for rock\n2 for scissors\n3 forpaper\n4 for lizzard\n5 for spock\n") x = int(input("Enter your choice: ")) print("Your choice: ") rpsSwitch(x) print("") print ("My Choice: ") rpsSwitch(choice) print("") winnerCheck(x, choice) yn = int(input("Play again?\n type 0 for yes, 1 for no\n"))
#!/usr/bin/python # -*- coding: utf-8 -*- #UNAM-CERT # ### Funcion que valide si es un palindromo recibe cadena y devuelve true o false def valida_palindromo(cadena): tam = 0 while tam < len(cadena): if cadena[tam] != cadena[-(tam+1)]: return False tam+=1 return True if valida_palindromo("anitalavalatina"): print "Es palindromo: True" else: print "Es palindromo: False"
# In this section we take integer input from user.. row=int(input("enter no of rows")) # This is for loop.. for i in range(1,row+1): for j in range(1,i+1): print("*", end="") print() for k in range(row+1,0,-1): for l in range(k+1,1,-1): print("*",end="") print()
from collections import Counter COLORS = {1,2,3,4} def _find_constraint_and_filter(items, key, side): """Iterate over `items` to determine a constraint value and return a list of elements from `items` that map to that constraint via `key`. `items` : an iterable `key` : a callable accepting single elements from `items` and returning something `side` : a callable accepting an iterable of elements and returning one of those elements, such as `min()` or `max()`""" scores = {x : key(x) for x in items} constraint = side(v for v in scores.values()) return [x for x in items if scores[x] == constraint] def _legal_colors(vertex, neighboring, coloring): """Return a set of the colors that are not assigned to any of the neighbors of `vertex`. `vertex` : a vertex (int) of the graph represented by `neighboring` `neighboring` : a dict from vertex (int) to a set of the vertices that share an edge with that key `coloring` : a dict from vertex (int) to color (int 1-4)""" return COLORS - {coloring.get(neighbor, 0) for neighbor in neighboring.get(vertex, [])} def vertices_edges_neighboring(graph): """Return the vertices, edges, and vertex-to-neighbors dict based on `graph`. `graph` : a set of vertices (int) and edges (frozenset of two ints) This function encapsulates some boilerplate to keep `color()` clean and to provide easy access to the neighbor dict when coloring interactively in a shell.""" vertices, edges, neighboring = [], [], {} for thing in graph: if isinstance(thing, int): vertices.append(thing) else: edges.append(thing) for order in [thing, reversed(list(thing))]: a,b = order if a not in neighboring: neighboring[a] = set() neighboring[a].add(b) return vertices, edges, neighboring def hypothetical_coloring(coloring, what_if): """Return a modified version of `coloring` in which the mappings from `what_if` supplant the pre-exisiting color assignments. `coloring` : a dict mapping from vertex (int) to color (int 1-4) `what_if` : a frozenset of (vertex,color) tuples; this could be read as "What if this vertex were this color and that vertex were that color and ...?" """ recolor = coloring.copy() for v,c in what_if: recolor[v] = c return recolor def chetwork(vertex, color1, color2, neighboring, coloring): """Identify and return a single-connected-component subgraph (set of vertices) of the graph defined by `neighboring` containing only vertices whose color is `color1` or `color2`. `vertex` : a vertex with an uncolored and uncolorable neighbor and which will be the seed from which a two-color subgraph is grown `color1` : a color (int 1-4) `color2` : another color (int 1-4), different from `color1` `neighboring` : a dict from vertex (int) to a set of the vertices that share an edge with that key `coloring` : a dict from vertex (int) to color (int 1-4) This sort of two-color subgraph is meant to be recolored in one move so as to enable an uncolorable vertex adjacent to the subgraph to have a legal color.""" colors = {color1, color2} core, edge, news = set(), set(), {vertex} while news: edge, news = news, set() for v in edge: news.update(neighbor for neighbor in neighboring[v] if (neighbor not in core and neighbor not in edge and coloring.get(neighbor,0) in colors)) core.update(edge) return frozenset(core) def _get_colored_neighbors(vertex, neighboring, coloring): """Return a subset of the neighbors of `vertex` where every member of the set has been assigned a color `vertex` : a vertex with at least one neighbor of each color `neighboring` : a dict from vertex (int) to a set of the vertices that share an edge with that key `init_coloring` : the established coloring assignments for the graph, of which a modified version should be returned""" return {neighbor for neighbor in neighboring[vertex] if coloring.get(neighbor,0) != 0} def _chain_shift(vertex, neighboring, init_coloring): """Check the neighbors of `vertex` to see if there's a way to open up a legal color for `vertex` by simultaneously recoloring all the vertices of a two-color subgraph. If there is, return a modified version of `init_coloring` in which the two colors of that subgraph are swapped. `vertex` : a vertex with at least one neighbor of each color `neighboring` : a dict from vertex (int) to a set of the vertices that share an edge with that key `init_coloring` : the established coloring assignments for the graph, of which a modified version should be returned""" colored_neighbors = _get_colored_neighbors(vertex, neighboring, init_coloring) options = set() for neighbor in colored_neighbors: color = init_coloring[neighbor] other_colors = COLORS - {color} for other in other_colors: subgraph = chetwork( neighbor, color, other, neighboring, init_coloring) if len(subgraph & neighboring[vertex]) == 1: # TODO does it really need to only contain exactly 1 neighbor? # or is it possible to hold 2 or more neighbors as long as all # neighbors in the chetwork are the same color? # That would be: # if len({init_coloring[x] # for x in subgraph & neighboring[vertex]}) == 1: options.add((subgraph, frozenset([color, other]))) what_ifs = [frozenset((vertex, (color1 if (init_coloring.get(vertex,0) == color2) else color2)) for vertex in subgraph) for subgraph, (color1, color2) in options] what_ifs.sort(key=len) try: return next(iter( hypotheticolor for hypotheticolor in (hypothetical_coloring(init_coloring, what_if) for what_if in what_ifs) if _legal_colors(vertex, neighboring, hypotheticolor))) except StopIteration: raise CannotColor() def _local_shift(vertex, neighboring, init_coloring): """Check the neighbors of `vertex` to see if any of them can make room for `vertex` to have a legal color option by changing to another color that they have available. If there is such a thing, return a modified color assignment based on `init_coloring` which has one of the neighbors of `vertex` recolored in that way. :param vertex: a vertex with at least one neighbor of each color :param neighboring: a dict from vertex (int) to a set of the vertices that share an edge with that key :param init_coloring: the established coloring assignments for the graph, of which a modified version should be returned """ neighbors_with_options = [ n for n in neighboring[vertex] if (n in init_coloring and init_coloring[n] != 0 and _legal_colors(n, neighboring, init_coloring) > {init_coloring[n]})] what_ifs = set() for neighbor in neighbors_with_options: options = _legal_colors(neighbor, neighboring, init_coloring) options.remove(init_coloring[neighbor]) for option in options: what_if = frozenset([(neighbor, option)]) what_ifs.add(what_if) try: return next(iter( hypotheticolor for hypotheticolor in (hypothetical_coloring(init_coloring, what_if) for what_if in sorted(what_ifs)) if _legal_colors(vertex, neighboring, hypotheticolor))) except StopIteration: raise CannotColor() def sidetrack(vertex, neighboring, init_coloring): """Try to find a way to make it possible to legally color `vertex` by checking for legal tweaks to the estabished coloring of the vertices near `vertex` that would make room for `vertex` to have at least one legal color. `vertex` : a vertex with at least one neighbor of each color `neighboring` : a dict from vertex (int) to a set of the vertices that share an edge with that key `init_coloring` : the established coloring assignments for the graph, of which a modified version should be returned This function is named in contrast to the backtracking technique for coloring a graph, which take eons to color a graph with thousands of vertices based on the electoral precincts of an entire state.""" for technique in [_local_shift, _chain_shift]: try: return technique(vertex, neighboring, init_coloring) except CannotColor: continue else: raise CannotColor() class CannotColor(Exception): pass def color(graph, init_coloring=None): """:param graph: a set of vertices (int) and edges (frozenset) which each contain two vertices that are connected. :param init_coloring: (optional) partial coloring of the graph, a dict from vertex (int) to color (int 1-4)""" #boilerplate vertices, edges, neighboring = vertices_edges_neighboring(graph) #meat coloring = dict(init_coloring) if init_coloring is not None else {} while any(coloring.get(v,0) == 0 for v in vertices): uncolored_vertices = [v for v in vertices if coloring.get(v,0) == 0] most_constrained_vertices = _find_constraint_and_filter( uncolored_vertices, (lambda v : len(_legal_colors(v, neighboring, coloring))), min) vertex = next(iter(most_constrained_vertices)) try: color = min(_legal_colors(vertex, neighboring, coloring)) except ValueError: #no legal colors try: coloring = sidetrack(vertex, neighboring, coloring) except CannotColor: print('Painted myself into a corner on vertex %s' % vertex) break #out of while loop color = min(_legal_colors(vertex, neighboring, coloring)) coloring[vertex] = color else: # Exiting normally rather than due to a problem # Randomize colors to smooth for vertex in vertices: legals = _legal_colors(vertex, neighboring, coloring) if legals: counts = Counter(coloring.values()) coloring[vertex] = min(legals, key=(lambda c : counts[c])) # then check for single-color weirdness counts = Counter(coloring.values()) coloring_list = list(counts.most_common()) c0, n0 = coloring_list[0] c_, n_ = coloring_list[-1] if n0 - n_ > 1: vs_c0 = {k for k,v in coloring.items() if v == c0} try: x = next(iter(v for v in vs_c0 if c_ in _legal_colors(v, neighboring, coloring))) except StopIteration: pass else: coloring[x] = c_ print(sum(1 for v in coloring.values() if v != 0), Counter(coloring.values())) illegal_edge_count = sum(1 for a,b in (x for x in graph if isinstance(x, frozenset)) if (a in coloring and b in coloring and coloring[a] == coloring[b])) if illegal_edge_count: print(f'{illegal_edge_count} illegal edges') return coloring def coloring_number(graph): """Find how many colors are needed to color this graph based on K_x subgraphs. """ nay = {i:set() for i in graph if isinstance(i, int)} for e in graph: if isinstance(e, frozenset): a,b = e nay[a].add(b) nay[b].add(a) PTS = {e for e in graph if isinstance(e, frozenset)} scale = 2 while len(PTS) >= scale + 1: scale += 1 pts, PTS = PTS, set() for e in pts: pool = _mass_intxn(nay[v] for v in e) for z in pool: PTS.add(frozenset(e | {z})) return scale, pts def _mass_intxn(sets): it = iter(sets) pool = next(it) while True: try: pool &= next(it) except StopIteration: break return pool
"""A script to do point-in-polygon testing for GIS.""" from enum import Enum _MAX = float('inf') _MIN = -_MAX class BoundaryException(Exception): """An exception raised when a point being tested sits on the boundary of a polygon. That fact defines the point's inside/outside status. An exception thrown back up the call stack provides a shortcut and a quicker answer.""" pass class BBox: """A class to model the bounding box of a collection of points in 2D space.""" ADD_IDENT = None def __init__(self, x, X, y, Y, illegal=False): """`x`: low x value `X`: high x value `y`: low y value `Y`: high y value `illegal`: if True, skip tests to check that low x and y values are less or equal to their high counterparts. Defaults to False.""" if not illegal: assert x <= X, 'x > X: %s > %s' % (x, X) assert y <= Y, 'y > Y: %s > %s' % (y, Y) self.x = x self.y = y self.X = X self.Y = Y def __contains__(self, item): x,y = item #treat equality as inside so that if the point is on the polygon #boundary then the caller's edge_okay value gets returned return self.x <= x and x <= self.X and self.y <= y and y <= self.Y def __add__(self, bbox): if not isinstance(bbox, BBox): raise TypeError x = min(self.x, bbox.x) X = max(self.X, bbox.X) y = min(self.y, bbox.y) Y = max(self.Y, bbox.Y) return BBox(x,X,y,Y) def __bool__(self): return True def __str__(self): return 'BBox(%s, %s, %s, %s)' % tuple(self) def __repr__(self): return str(self) def __iter__(self): return iter([self.x, self.X, self.y, self.Y]) BBox.ADD_IDENT = BBox(_MAX, _MIN, _MAX, _MIN, illegal=True) class _Ring(list): """A class to represent an inner or outer boundary of a Polygon and to maintain a reference to that boundary's bounding box.""" def __init__(self, points): assert all(points[0][i] == points[-1][i] for i in range(2)), ( ('first and last point on a boundary must have the same first ' 'two dimensions: %s,%s != %s,%s') % (points[0][0], points[0][1], points[-1][0], points[-1][1])) p0x, p0y = points[0][:2] p1x, p1y = points[-1][:2] if p0x != p1x or p0y != p1y: raise ValueError( ('first and last point on a boundary must have the same first ' 'two dimensions: %s,%s != %s,%s') % (p0x, p0y, p1x, p1y)) import shapefile self.area = shapefile.signed_area(points) super(_Ring, self).__init__(points if self.area >= 0 else reversed(points)) self.area = abs(self.area) e = BBox(10**9, -10**9, 10**9, -10**9, illegal=True) for point in self: x,y = point e.x = min(x, e.x) e.X = max(x, e.X) e.y = min(y, e.y) e.Y = max(y, e.Y) self.bbox = e def __bool__(self): return True def __contains__(self, point): return point in self.bbox and -4 == _winding(point, self) def contains(self, point, edge_okay=False): try: return point in self except BoundaryException: return edge_okay def _turning_sign(point, v1, v2): #cross-product x = ((v2[0] - point[0]) * (v1[1] - point[1]) - (v2[1] - point[1]) * (v1[0] - point[0])) if x > 0: return 1 elif x < 0: return -1 else: #x == 0 raise BoundaryException() class Quad(Enum): I = 0 # First quadrant, for x>0, y>0 II = 1 # Second quadrant, for x>0, y<0 III = 2 # Third quadrant, for x<0, y<0 IV = 3 # Fourth quadrant, for x<0, y>0 _ERR_RAD_DEG = 8.98315e-07 #in degrees. Along equator, about 10 centimeters _ERR_RAD_DEG_SQ = _ERR_RAD_DEG ** 2 #precomputed for reuse #Return the quadrant v is in with respect to point as the origin. def _orient(point, v): vx, vy = v[0], v[1] px, py = point[0], point[1] dx = vx - px dy = vy - py if _ERR_RAD_DEG_SQ > dx ** 2 + dy ** 2: raise BoundaryException() if dx * dy == 0: #along an axis if dx == 0: return Quad.I if dy > 0 else Quad.III else: #dy == 0 return Quad.II if dx > 0 else Quad.IV else: if dx < 0: return Quad.III if dy < 0 else Quad.IV else: #dx > 0 return Quad.II if dy < 0 else Quad.I def _turning(point, v1, v2): o1 = _orient(point, v1).value o2 = _orient(point, v2).value #call early in case it raises BoundaryException sign = _turning_sign(point, v1, v2) angle = o2 - o1 if angle < -2: angle += 4 elif angle > 2: angle -= 4 elif abs(angle) == 2: angle = 2 * sign return angle def _winding(point, ring): return sum(_turning(point, ring[i-1], ring[i]) for i in range(1, len(ring))) def point_in_polygon(point, vertex_ring, edge_okay=False): """Return True if the `point` is inside the `vertex_ring`, False otherwise. :param point: a tuple of numbers with at least two elements or any other object subscriptable with 0 and 1 (for example, a dict {1: -43, 50: 'a', 0: 91}) :param vertex_ring: The vertices of the polygon. The first vertex must be repeated as the final element. :param edge_okay: Return this value if `point` is on the boundary of the `vertex_ring`. False by default.""" try: return point in _Ring(vertex_ring) except BoundaryException: return edge_okay def _SORT_BY_AREA_VERTS(ring): try: return 1 / ring.area / len(ring) except ZeroDivisionError: return _MAX class Polygon: """A polygon for GIS, with >=1 outer bounds and >=0 inner bounds.""" def __init__(self, outers, inners=None, info=None, edge_okay=False): """Make a Polygon :param outers: a list of one or more outer boundaries :param inners: if specified, a list of zero or more inner boundaries :param info: Any data or metadata object the user wants. :param edge_okay: `point in self` will evaluate to this if `point` sits on a boundary. False by default.""" if not len(outers): raise ValueError('need at least one outer boundary') inners = inners or [] self.outers = [_Ring(outer) for outer in outers] self.inners = [_Ring(inner) for inner in inners] self.info = info self.edge_okay = edge_okay self.outers.sort(key=_SORT_BY_AREA_VERTS) self._out_to_in = {i:[] for i in range(len(self.outers))} if self.inners: unassigned_inners = list(self.inners) while unassigned_inners: assign_me = unassigned_inners.pop() point = assign_me[0] containers = [i for i in range(len(self.outers)) if self.outers[i].contains(point, edge_okay=True)] container = min(containers, key=(lambda x : self.outers[x].area)) self._out_to_in[container].append(assign_me) for v in self._out_to_in.values(): v.sort(key=_SORT_BY_AREA_VERTS) self._bbox = None self.__hash = None def __contains__(self, point): """Determine whether `point` is in this Polygon. Return `self.edge_okay` if `point` is exactly on a boundary.""" try: #which outer boundary contains `point`? outerbound_containing_point = next(iter( i for i in range(len(self.outers)) if point in self.outers[i])) #and which inner boundaries are inside that outer-bound? inners = self._out_to_in[outerbound_containing_point] #if `point` is in any inner boundary, then it's not in the Polygon return all(point not in inner for inner in inners) except StopIteration: #none of the outers contain `point` return False except BoundaryException: # `point` sits on an outer or inner bound return self.edge_okay def __hash__(self): if self.__hash is None: self.__hash = hash((tuple(tuple(tuple(point) for point in outer) for outer in self.outers), tuple(tuple(tuple(point) for point in inner) for inner in self.inners))) return self.__hash def __eq__(self, other): return self is other #return self.outers == other.outers and self.inners == other.inners def to_kml(self, soup=None): import kml if soup is None: result = '<Placemark>%s</Placemark>' if len(self.outers) > 1: result %= '<MultiGeometry>%s</MultiGeometry>' for i, outer in enumerate(self.outers): inners = self._out_to_in[i] polygon = '<Polygon><outerBoundaryIs><LinearRing><coordinates>' polygon += kml.coords_to_text(outer) polygon += '</coordinates></LinearRing></outerBoundaryIs>' for inner in inners: polygon += '<innerBoundaryIs><LinearRing><coordinates>' polygon += kml.coords_to_text(inner) polygon += '</coordinates></LinearRing></innerBoundaryIs>' polygon += '</Polygon>%s' result %= polygon result %= '' return result else: result = soup.new_tag('Placemark') focus = result if len(self.outers) > 1: focus = kml.add(focus, 'MultiGeometry', soup=soup) for i, outer in enumerate(self.outers): inners = self._out_to_in[i] polygon = kml.add(focus, 'Polygon', soup=soup) kml.add(polygon, ['outerBoundaryIs', 'LinearRing', 'coordinates'], soup=soup).string = kml.coords_to_text(outer) for inner in inners: kml.add(polygon, ['innerBoundaryIs', 'LinearRing', 'coordinates'], soup=soup).string = kml.coords_to_text(inner) return result def spatial_index(self, scale): import spindex cells = set() for outer in self.outers: cells.update(spindex.get_cells_2d(outer, scale=scale)) rims = [spindex.get_cells_1d(inner, scale=scale) for inner in self.inners] guts = [spindex.get_cells_2d(inner, scale=scale, boundary_cells=rims[i]) for i, inner in enumerate(self.inners)] for gut in guts: cells -= gut for rim in rims: cells.update(rim) return cells @property def _rings(self): """Iterate over inner and outer boundaries.""" for o in self.outers: yield o for i in self.inners: yield i @property def stokesable(self): """Yield copies of all boundaries, with inner bounds reversed.""" for o in self.outers: yield list(o) for i in self.inners: yield list(reversed(i)) @property def bbox(self): """The least and greatest x and y coordinates of the vertices.""" if not self._bbox: self._bbox = sum((ring.bbox for ring in self._rings), BBox(_MAX, _MIN, _MAX, _MIN, illegal=True)) return self._bbox @property def vertices(self): """Iterates over all the vertices of this Polygon. Since the first point of a boundary is duplicated as the last point, all such points will occur twice.""" for ring in self._rings: for vertex in ring: yield vertex @property def sides(self): """Iterate over the sides of the outer and inner boundaries.""" for ring in self._rings: for i in range(1, len(ring)): yield ring[i-1:i+1] @staticmethod def from_shape(shape, info=None, edge_okay=False): """Convert a shapefile.Shape into a Polygon. Because inner and outer boundaries in the shapefile standard are defined as such only implicity via their curling orientation, distinguishing whether a given boundary is inner or outer requires detecting its curling orientation, which is achieved via `shapefile.signed_area`. :param shape: a shapefile.Shape object :param info: passed to __init__ :param edge_okay: passed to __init__""" import shapefile bounds = list(shape.parts) + [len(shape.points)] outers = [] inners = [] for i in range(1, len(bounds)): start, stop = bounds[i-1], bounds[i] line = shape.points[start:stop] #value >= 0 indicates a counter-clockwise oriented ring #Negative value -> outer boundary a = shapefile.signed_area(line) if a >= 0: inners.append(line) else: outers.append(line) return Polygon(outers, inners, info=info, edge_okay=edge_okay) @staticmethod def from_boundaries(boundaries, info=None, edge_okay=False): from shapefile import signed_area outers, inners = [], [] for boundary in boundaries: if signed_area(boundary) >= 0: outers.append(boundary) else: inners.append(boundary) return Polygon(outers, inners, info=info, edge_okay=edge_okay) @staticmethod def from_kml(placemark, info=None, edge_okay=False): """Convert a KML Placemark into a Polygon. :param placemark: a <Placemark> tag from a KML document :param info: passed to __init__ :param edge_okay: passed to __init__""" import kml, itertools geo = placemark.MultiGeometry or placemark.Polygon if geo is None: print(placemark) outers = [kml.coords_from_tag(obi.coordinates) for obi in geo('outerBoundaryIs')] #The KML spec indicates that there is only one LinearRing per #innerBoundaryIs, but KMLs generated by Google Earth from shapefiles #may put (and render) multiple LinearRings in a single innerBoundaryIs inners = [kml.coords_from_tag(coordinates_tag) for coordinates_tag in itertools.chain.from_iterable( ibi('coordinates') for ibi in geo('innerBoundaryIs'))] return Polygon(outers, inners, info=info, edge_okay=edge_okay)
import random; formats = open('formats').read().split('\n'); types = ['names', 'nouns', 'units', 'updowns', 'persons', 'ages', 'n2ouns', 'futures', 'verbs', 'adjectives']; for i in types: exec(i+' = open("'+i+'").read().split(",");'); def generateHeadline(): format = random.choice(formats); for i in types: exec('format = format.replace("$'+i[:-1].upper()+'$", "'+random.choice(eval(i))+'");'); return format.replace("$NUMBER$", str(random.randrange(100))); print generateHeadline();
from tkinter import * import random import itertools import bot class mastermind: def __init__(self): return # handmatig de code invullen def manualcode(self): self.colourcode = [] colours = ['red', 'pink', 'yellow', 'green', 'orange','blue'] print('red,', 'pink', ' yellow,', ' green,', ' orange,',' blue') self.color1 = input('Vul uw 1e kleur in: ') self.color2 = input('Vul uw 2e kleur in: ') self.color3 = input('Vul uw 3e kleur in: ') self.color4 = input('Vul uw 4e kleur in: ') if self.color1 not in colours or self.color2 not in colours or self.color3 not in colours or self.color4 not in colours: print('probeer het opnieuw') mastermind.manualcode(self) else: self.colourcode = [self.color1, self.color2, self.color3, self.color4] print(self.colourcode) # de bot maakt de code def AIcode(self): colours = ['red', 'pink', 'yellow', 'green', 'orange','blue'] self.colourcode = [] for value in range(0, 4): self.colourcode.append(random.choice(colours)) # houdt het aantal pogingen bij, als de grens wordt overscheden wordt het spel stop gezet def pogingen(self): self.attempts += 1 if self.attempts > 9: self.helaasFrame = Frame(self.gameFrame, bg='green') self.helaasFrame.place(y=70, x=100, height=450, width=200) self.helaasLabel = Label(self.helaasFrame, bg='green', fg='red', text='Helaas!\n U heeft verloren', font=('ariel', 16, 'bold')) self.helaasLabel.place(y=0, x=0) self.returnButton = Button(self.helaasFrame, command=lambda: mastermind.Afsluiten(self), text='Afsluiten', bg='pink', fg='blue', font=('ariel', 8, 'bold')) self.returnButton.place(y=150, x=60) else: mastermind.manualguess(self) # handmatig de code van de bot oplossen def manualguess(self): self.correct = 0 self.wrongplace = 0 self.colours1 = ['red', 'pink', 'yellow', 'green', 'orange', 'blue'] self.colours2 = ['red', 'pink', 'yellow', 'green', 'orange', 'blue'] self.colours3 = ['red', 'pink', 'yellow', 'green', 'orange', 'blue'] self.colours4 = ['red', 'pink', 'yellow', 'green', 'orange', 'blue'] valueY = 480 - (self.attempts - 1) * 50 self.raadFrame = Frame(self.mastermindFrame, bg='black', highlightbackground='white', highlightthickness=3) self.raadFrame.place(x=0, y=valueY, height=50, width=450) self.guessingButton1 = Button(self.raadFrame, text='[X]', command = lambda: mastermind.colourguess(self, 1), bg='black', fg='white', font=('ariel', 12, 'bold'), width=10, borderwidth = 0) self.guessingButton1.place(x=30, y=10) self.guessingButton2 = Button(self.raadFrame, text='[X]', command=lambda: mastermind.colourguess(self, 2), bg='black', fg='white', font=('ariel', 12, 'bold'), width=10, borderwidth = 0) self.guessingButton2.place(x=130, y=10) self.guessingButton3 = Button(self.raadFrame, text='[X]', command=lambda: mastermind.colourguess(self, 3), bg='black', fg='white', font=('ariel', 12, 'bold'), width=10, borderwidth = 0) self.guessingButton3.place(x=230, y=10) self.guessingButton4 = Button(self.raadFrame, text='[X]', command=lambda: mastermind.colourguess(self, 4), bg='black', fg='white', font=('ariel', 12, 'bold'), width=10, borderwidth = 0) self.guessingButton4.place(x=330, y=10) # buttons voor het handmatig raden def colourguess(self, guess): if guess == 1: self.guessingButton1.config(text = self.colours1[0], fg = self.colours1[0]) self.selectedcolour1 = self.colours1[0] self.colours1.append(self.colours1[0]) self.colours1.pop(0) elif guess == 2: self.guessingButton2.config(text=self.colours2[0], fg=self.colours2[0]) self.selectedcolour2 = self.colours2[0] self.colours2.append(self.colours2[0]) self.colours2.pop(0) elif guess == 3: self.guessingButton3.config(text=self.colours3[0], fg=self.colours3[0]) self.selectedcolour3 = self.colours3[0] self.colours3.append(self.colours3[0]) self.colours3.pop(0) elif guess == 4: self.guessingButton4.config(text = self.colours4[0], fg = self.colours4[0]) self.selectedcolour4 = self.colours4[0] self.colours4.append(self.colours4[0]) self.colours4.pop(0) # controle of de door de persoon opgegeven antwoorden kloppen def checkAwnsers(self): colours = ['red', 'pink', 'yellow', 'green', 'orange', 'blue'] self.wrongplacecolours = [] self.almost = 0 self.rightplace = 0 print(self.colourcode) valueY = 480 - (self.attempts - 1) * 50 scorevak = Frame(self.mastermindFrame, bg='black', highlightbackground='green', highlightthickness=1.5) scorevak.place(x=500, y=valueY, height=50, width=50) try: self.selectedcolour1 if self.selectedcolour1 in self.colourcode: if self.selectedcolour1 == self.colourcode[0]: if self.colourcode.count(self.selectedcolour1) == 1: self.wrongplacecolours.append(self.selectedcolour1) self.correct += 1 self.rightplace += 1 self.score1 = Label(scorevak, text='X', bg='red', fg='red', font=('ariel', 8, 'bold'), width=2) self.score1.place(x=26, y=26) elif self.colourcode.count(self.selectedcolour1) > 1: self.correct += 1 self.rightplace += 1 self.score1 = Label(scorevak, text='X', bg='red', fg='red', font=('ariel', 8, 'bold'), width=2) self.score1.place(x=26, y=26) else: if self.selectedcolour1 not in self.wrongplacecolours: self.wrongplacecolours.append(self.selectedcolour1) self.wrongplace += 1 self.almost += 1 self.wrongscore1 = Label(scorevak, text='X', bg='white', fg='white', font=('ariel', 8, 'bold'), width=2) self.wrongscore1.place(x=26, y=26) except: print('hi') try: if self.selectedcolour2 in self.colourcode: if self.selectedcolour2 == self.colourcode[1]: if self.colourcode.count(self.selectedcolour2) == 1: self.wrongplacecolours.append(self.selectedcolour2) self.correct += 1 self.rightplace +=1 self.score2 = Label(scorevak, text='X', bg='red', fg='red', font=('ariel', 8, 'bold'), width=2) self.score2.place(x=0, y=0) elif self.colourcode.count(self.selectedcolour2) > 1: self.correct += 1 self.rightplace += 1 self.score2 = Label(scorevak, text='X', bg='red', fg='red', font=('ariel', 8, 'bold'), width=2) self.score2.place(x=0, y=0) else: if self.selectedcolour2 not in self.wrongplacecolours: self.wrongplacecolours.append(self.selectedcolour2) self.wrongplace += 1 self.almost += 1 self.wrongscore2 = Label(scorevak, text='X', bg='white', fg='white', font=('ariel', 8, 'bold'), width=2) self.wrongscore2.place(x=0, y=0) except: print('hi') try: if self.selectedcolour3 in self.colourcode: if self.selectedcolour3 == self.colourcode[2]: if self.colourcode.count(self.selectedcolour3) == 1: self.wrongplacecolours.append(self.selectedcolour3) self.correct += 1 self.rightplace += 1 self.score3 = Label(scorevak, text='X', bg='red', fg='red', font=('ariel', 8, 'bold'), width=2) self.score3.place(x=0, y=26) elif self.colourcode.count(self.selectedcolour3) > 1: self.correct += 1 self.rightplace += 1 self.score3 = Label(scorevak, text='X', bg='red', fg='red', font=('ariel', 8, 'bold'), width=2) self.score3.place(x=0, y=26) else: if self.selectedcolour3 not in self.wrongplacecolours: self.wrongplacecolours.append(self.selectedcolour3) self.wrongplace += 1 self.almost += 1 self.wrongscore3 = Label(scorevak, text='X', bg='white', fg='white', font=('ariel', 8, 'bold'), width=2) self.wrongscore3.place(x=0, y=26) except: print('hi') try: if self.selectedcolour4 in self.colourcode: if self.selectedcolour4 == self.colourcode[3]: if self.colourcode.count(self.selectedcolour4) == 1: self.wrongplacecolours.append(self.selectedcolour4) self.correct += 1 self.rightplace += 1 self.score4 = Label(scorevak, text='X', bg='red', fg='red', font=('ariel', 8, 'bold'), width=2) self.score4.place(x=26, y=0) elif self.colourcode.count(self.selectedcolour4) > 1: self.correct += 1 self.rightplace += 1 self.score4 = Label(scorevak, text='X', bg='red', fg='red', font=('ariel', 8, 'bold'), width=2) self.score4.place(x=26, y=0) else: if self.selectedcolour4 not in self.wrongplacecolours: self.wrongplacecolours.append(self.selectedcolour4) self.wrongplace += 1 self.almost += 1 self.wrongscore4 = Label(scorevak, text='X', bg='white', fg='white', font=('ariel', 8, 'bold'), width=2) self.wrongscore4.place(x=26, y=0) except: print('hi') if self.correct == 4: mastermind.Finish(self) # als de speler de code goed heeft ingeleverd krijgt de speler dit te zien def Finish(self): self.gefeliciteerdFrame = Frame(self.gameFrame, bg = 'green') self.gefeliciteerdFrame.place(y = 70, x = 100, height = 450, width= 200) self.gefeliciteerdLabel = Label(self.gefeliciteerdFrame, bg = 'green', fg = 'red', text = 'Gefeliciteerd!\n U heeft gewonnen', font=('ariel', 16, 'bold')) self.gefeliciteerdLabel.place(y = 0, x = 0) self.afsluitButton = Button(self.gefeliciteerdFrame, command = lambda: mastermind.Afsluiten(self) ,text = 'Afsluiten', bg = 'pink', fg = 'blue', font=('ariel', 8, 'bold')) self.afsluitButton.place(y = 150, x = 60) def Afsluiten(self): self.parent.destroy()
n = input("") # Apenas para saber o indice de n2 original_crive = range(3, n, 2) crive = range(3, n, 2) index = 0 remove = [] n2 = 0 n_int_sqrt = int(n**(0.5)) print original_crive print n_int_sqrt while crive[index] <= n_int_sqrt: n2 = crive[index] * crive[index] print crive[index], n2, original_crive.index(n2) remove = [] while n2 <= n: remove.append(n2) if n2 in crive: crive.remove(n2) n2 += (crive[index]*2) print remove print crive index += 1 # Incluimos o 2 tambem print [2] + crive
#!/usr/bin/env python # Copyright (c) 2021- The University of Notre Dame. # This software is distributed under the GNU General Public License. # See the file COPYING for details. # This program is a simple example of how to use Work Queue. # It is a toy example of diffusion of particles by Brownian motion. # It accepts two parameters: number of particles and time steps. # Each work queue task will simulate the Brownian motion of a particle that can # move left or right each probability 1/2. import work_queue as wq import sys import math from collections import defaultdict def show_help(): print("""Toy example of diffusion of particles by Brownian motion. Usage: work_queue_basic_example.py PARTICLES MAX_STEPS where: PARTICLES Number of particles to simulate STEPS Number of steps each particle randomly moves""") def read_arguments(): try: (total_particles, steps) = sys.argv[1:] except ValueError: show_help() print("Error: Incorrect number of arguments") try: total_particles = int(total_particles) steps = int(steps) except ValueError: print("Error: Arguments are not integers") return (total_particles, steps) def process_result(particle_index, particles_at_position): simulation_result = "particle_{}.out".format(particle_index) try: with open(simulation_result) as f: for (time, position) in enumerate(f): position = int(position) particles_at_position[time][position] += 1 except IOError as e: print("Error reading file: {}: {}".format(simulation_result, e)) def analyze_results(particles_at_position, total_particles, steps): print("time-step\tavg\tsd") for step in range(0, steps+1, 10): mean = 0 for (pos, count) in particles_at_position[step].items(): mean += pos * count mean /= total_particles var = 0 for (pos, count) in particles_at_position[step].items(): var += count * ((pos - mean) ** 2) var /= total_particles print("{:9d}\t{:.3f}\t{:.3f}".format(step, mean, math.sqrt(var))) def print_error_log(particle_index): error_log = "particle_{}.err".format(particle_index) try: with open(error_log) as f: print(f.read()) except IOError: pass # particles_at_position[TIME][POSITION] is a mapping that keeps the count of # particles at a given TIME and POSITION. particles_at_position = defaultdict(lambda: defaultdict(lambda: 0)) (total_particles, steps) = read_arguments() q = wq.WorkQueue(port=9123) for particle_index in range(total_particles): output_name = "particle_{}.out".format(particle_index) error_name = "particle_{}.err".format(particle_index) t = wq.Task("./random_walk.py {steps} {out} 2> {err}".format(steps=steps, out=output_name, err=error_name)) t.specify_tag("{}".format(particle_index)) t.specify_input_file("random_walk.py", cache=True) t.specify_output_file(output_name, cache=False) t.specify_output_file(error_name, cache=False) t.specify_cores(1) t.specify_memory(100) t.specify_disk(200) q.submit(t) # wait for all tasks to complete while not q.empty(): t = q.wait(5) if t: print("Task {id} has returned.".format(id=t.id)) if t.result == wq.WORK_QUEUE_RESULT_SUCCESS and t.return_status == 0: particle_index = t.tag process_result(particle_index, particles_at_position) else: print(" It could not be completed successfully. Result: {}. Exit code: {}".format(t.result, t.return_status)) print_error_log(particle_index) print("All task have finished.") print("Computing results:") analyze_results(particles_at_position, total_particles, steps)
import random # help http://blog.yhat.com/posts/the-beer-bandit.html class BernoulliArm: def __init__(self, p): self.p = p def draw(self): return 0.0 if random.random() > self.p else 1 class EpsilonGreedy: # constructor # epsilon (float): tradeoff exploration/exploitation def __init__(self, epsilon): self.epsilon = epsilon # re-initialize the algorithm in order to run a new simulation # n_arms (int): number of arms def initialize(self, n_arms): self.iter = 0 self.n_arms = n_arms self.gain = [0.0] * n_arms # return a index of the chosen decision def select_arm(self): if random.random() > self.epsilon: return self.gain.index(max(self.gain)) else: return random.randint(self.n_arms) # update knowledge # chosen_arm (int): the decision that has been made def update(self, chosen_arm, reward): if self.iter == 1: self.gain[chosen_arm] = reward * self.epsilon self.iter += 1 def test_algorithm(algo, means, num_sims, horizon): # init. all decisions arms = [BernoulliArm(mu) for mu in means] rewards = [] for sim in range(num_sims): algo.initialize(len(arms)) for t in range(horizon): chosen_arm = algo.select_arm() reward = arms[chosen_arm].draw() algo.update(chosen_arm, reward) rewards.append(reward)
from numpy import * print("Zadanie 1:") a = arange(3) b = arange(3,6,1) print(a,b,a*b) print("Zadanie 2:") a = array([[7, 4, 2], [1, 1, 3], [0, 9, 6]]) b = array([[3, 1, 5, 1], [9, 8, 7, 5], [1, 3, 2, 4], [5, 7, 3, 0]]) print(a) print(b) print(a.min(axis=0), a.min(axis=1)) print(b.min(axis=0), b.min(axis=1)) print("Zadanie 3:") a = arange(3) b = arange(3,6,1) print(dot(a,b)) print("Zadanie 4:") a = arange(3) b = linspace(3,4,3) print(a*b) print("Zadanie 5 - 7:") a = sin(array([[2,3], [6,2], [1,1]])) b = cos(array([[4,2], [1,7], [9,2]])) print(a+b) print("Zadanie 8:") a = array([[7, 4, 2], [1, 1, 3], [0, 9, 6]]) for x in a: print(x) print("Zadanie 9:") a = array([[7, 4, 2], [1, 1, 3], [0, 9, 6]]) for x in a.flat: print(x) print("Zadanie 10:") a = arange(81).reshape((9,9)) print(a) b = a.reshape((3,27)) print(b) print("Zadanie 11:") a = arange(12) a = a.reshape((3,4)) print(a) b = arange(12) b = b.reshape((4,3)) print(b) c = arange(12) c = c.reshape((2,6)) print(c) a = a.ravel() b = b.ravel() c = c.ravel() print(a,b,c)
# https://www.hackerrank.com/challenges/insertionsort2/problem # Tag(s): sorting def _print(arr): for x in arr: print(x, end=' ') print() def insertionSort1(n, arr): k = arr[n-1] index = n - 2 while index >= 0: if arr[index] < k: if index + 1 < n: arr[index + 1] = k index = 0 else: arr[index + 1] = arr[index] if index == 0: arr[0] = k index -= 1 def insertionSort2(n, arr): for i in range(2, n+1): insertionSort1(i, arr) _print(arr) if __name__ == '__main__': n = int(input()) arr = list(map(int, input().split())) insertionSort2(n, arr)
from typing import Tuple """Given an integer, print the next smallest and next largest number that have the same number of 1 bits in their binary representation. """ """ Approach Prior observations: - If we turn on a 0, we need to turn off a 1. i.e 0->1 and 1->0. To keep the same number of 1 bits. - I we 0->1 at bit i and turn off a 1 at bit j, the number changes by 2^i - 2^j Example: 10100 (20) i = 3 and j = 2 | 2^3 = 8 | 2^2 = 4 | 2^i - 2^j = 4 11000 (24) - Notice that if we want to get a bigger number with the same number of 1s and 0s, i must be bigger than j. Solution: 1) Get the next greatest number - Traverse from rigth to left. Once we've passed a 1, turn on the next 0. We've now increased the number by 2^i. Example: xxxx011100 becomes xxxx111100. - Turn off the one that's just to the right side of that. We're now bigger by 2^i-2^(i-1). Example: xxxx111100 becomes xxxx101100. - Make the number as small as possible by rearranging all the 1s to be as far right as possible. Example: xxxx101100 becomes xxxx100011. 2) Get the next smallest number - Traverse from right to left. Once we've passed a zero, turn off the next 1. Example: xxxx100011 becomes xxxx000011. - Turn on the 0 that is directly to the right. Example: xxxx000011 becomes xxxx010011. - Make the number as big as possible by shifting all the ones as far to the left as possible. Example: xxxx010011 becomes xxxx011100. """ def convert_int_to_str_bin(n: int) -> str: ans = "" while n: ans += str(n % 2) n //= 2 return ans[::-1] def convert_str_binary_to_int(str_bin: str) -> int: max_power = len(str_bin) - 1 ans = int() for bit in str_bin: ans += 2**max_power * (1 if bit == "1" else 0) max_power -= 1 return ans def turn_on_next_zero_after_one(str_bin: str) -> Tuple[str, int]: len_size = len(str_bin) new_str = "" has_found_one = False has_to_add_digit = True ptr = -1 for i in range(len_size - 1, -1, -1): if str_bin[i] == "0" and has_found_one: new_str += "1" new_str += str_bin[:i][::-1] has_to_add_digit = False ptr += 1 break if str_bin[i] == "1" and not has_found_one: has_found_one = True new_str += str_bin[i] ptr += 1 if has_to_add_digit: new_str = ("0" * len_size) + "1" ptr += 1 return (new_str[::-1], ptr) def is_power_of_two(str_bin: str) -> bool: x = 0 while x < len(str_bin): if str_bin[x] != "0": break x += 1 trail_elements = set(str_bin[x+1:]) return ( str_bin[x] == "1" and (trail_elements == {"0"} or trail_elements == set()) ) def turn_x_given_bit_pos(str_bin: str, bit_pos: int, on: bool) -> str: n = len(str_bin) idx = n - bit_pos - 1 bit = 1 if on else 0 return str_bin[0:idx] + str(bit) + str_bin[idx+1:] def small_number(str_bin: str, bit_pos: int) -> str: """Make the number as small as possible by rearranging all the 1s to be as far right as possible, considering only the bits after the given bit_pos. Example: 101100 becomes 100011. """ number_trail_zeros = 0 n = len(str_bin) idx = n - bit_pos - 1 for i in range(n-1, -1, -1): if str_bin[i] == "1": break number_trail_zeros += 1 smaller_number = str_bin[0:idx+1] smaller_number += "0"*number_trail_zeros smaller_number += str_bin[idx+1:n-number_trail_zeros] return smaller_number def big_number(str_bin: str, bit_pos: int) -> str: """Make the number as big as possible by shifting all the ones as far to the left as possible, considering only the bits after the given bit_pos. Example: 010011 becomes 011100. """ number_head_zeros = 0 n = len(str_bin) idx = n - bit_pos - 1 for i in range(idx+1, n): if str_bin[i] == "1": break number_head_zeros += 1 bigger_number = str_bin[0:idx+1] bigger_number += str_bin[idx+1+number_head_zeros:n] bigger_number += "0"*number_head_zeros return bigger_number def turn_off_next_one_after_zero(str_bin) -> Tuple[str, int]: n = len(str_bin) new_str = "" has_found_zero = False ptr = -1 for i in range(n - 1, -1, -1): if str_bin[i] == "1" and has_found_zero: new_str += "0" new_str += str_bin[:i][::-1] ptr += 1 break if str_bin[i] == "0" and not has_found_zero: has_found_zero = True new_str += str_bin[i] ptr += 1 return (new_str[::-1], ptr) def find_next_greatest(str_binary: str) -> int: if is_power_of_two(str_binary): return convert_str_binary_to_int(str_binary) * 2 greater_by_i, idx = turn_on_next_zero_after_one(str_binary) if len(greater_by_i) == len(str_binary): # turn off bit idx-1 greater_by_i_1 = turn_x_given_bit_pos(greater_by_i, idx-1, on=False) small_as_possible = small_number(greater_by_i_1, idx) else: number_1_bits = len(str_binary) small_as_possible = "10" + "1"*(number_1_bits - 1) return convert_str_binary_to_int(small_as_possible) def find_next_smallest(str_binary: str) -> int: if is_power_of_two(str_binary): return convert_str_binary_to_int(str_binary) // 2 smaller_by_i, idx = turn_off_next_one_after_zero(str_binary) # turn on bit idx-1 smaller_by_i_1 = turn_x_given_bit_pos(smaller_by_i, idx-1, on=True) big_as_possible = big_number(smaller_by_i_1, idx-1) return convert_str_binary_to_int(big_as_possible) if __name__ == '__main__': n = int(input()) str_binary = convert_int_to_str_bin(n) next_largest_number = find_next_greatest(str_binary) next_smallest_number = find_next_smallest(str_binary) print(f"{next_smallest_number} {n} {next_largest_number}")
# https://www.hackerrank.com/challenges/find-the-median/problem # tag(s): sorting, implementation if __name__ == "__main__": n = int(input()) arr = list(map(int, input().split(" "))) arr.sort() print(arr[len(arr) // 2])
#!/usr/bin/env python # -*- coding: utf-8 -*- from fractions import Fraction ff = [] while True: try: line = raw_input() if not line: break except EOFError: break ff.append(map(int, line.split())) res = Fraction() for f in ff: res += Fraction(f[0], f[1]) print "{} / {}".format(res.numerator, res.denominator)
# https://omegaup.com/arena/problem/Dominos#problems def pow(x, n, I, mult): if n == 0: return I elif n == 1: return x else: y = pow(x, n // 2, I, mult) y = mult(y, y) if n % 2: y = mult(x, y) return y def identity_matrix(n): """Returns the n by n identity matrix.""" r = list(range(n)) return [[1 if i == j else 0 for i in r] for j in r] def matrix_multiply(A, B): BT = list(zip(*B)) return [[sum(a * b for a, b in zip(row_a, col_b))%100000009 for col_b in BT] for row_a in A] def fib(n): F = pow([[1, 1], [1, 0]], n, identity_matrix(2), matrix_multiply) return F[0][1] if __name__ == '__main__': n = raw_input() n = long(n) fn = fib(n) print(fn)
def is_anagram(str_1, str_2): return sorted(str_1) == sorted(str_2) if __name__ == '__main__': str_1 = input("Type first word: ") str_2 = input("Type second word: ") print(is_anagram(str_1, str_2))
# https://app.codesignal.com/interview-practice/task/uX5iLwhc6L5ckSyNC # Tag(s): Arrays def firstNotRepeatingCharacter(s): conts = [0]*26 n = len(s) for i in range(n): conts[ord(s[i])-97] += 1 ans = '_' for i in range(n): if(conts[ord(s[i])-97] == 1): ans = s[i] break return ans if __name__ == '__main__': str = input() print(firstNotRepeatingCharacter(str))
def scalarProduct(a, b): assert len(a) == len(b) a, b = sorted(a), sorted(b) return sum(a[i] * b[i] for i in range(len(a))) if __name__== '__main__': a = [1, 3, 6, 8] b = [7, 23, 1, 0] print(scalarProduct(a, b))
# https://app.codesignal.com/interview-practice/task/oJXTWuwEZiC6FTw3A/description # Tag(s): DP def climbingStairs(n): a, b = 1, 1 for i in range(2, n+1): a, b = a + b, a return a if __name__ == '__main__': n = int(input('')) print(climbingStairs(n))
# https://www.hackerrank.com/challenges/cavity-map/problem # Tag(s): Implementation def find_cavities(grid:list) -> list: n = len(grid) for i in range(1, n-1): for j in range(1, n-1): if grid[i][j] > grid[i-1][j] and grid[i][j] > grid[i+1][j]: if grid[i][j] > grid[i][j-1] and grid[i][j] > grid[i][j+1]: grid[i][j] = 'X' return grid if __name__ == '__main__': n = int(input()) grid = [] for i in range(n): digs = list(input()) grid.append(digs) modified_grid = find_cavities(grid) for row in modified_grid: for x in row: print(x, end='') print("")
# https://www.hackerrank.com/challenges/py-the-captains-room/problem if __name__ == '__main__': k = int(input()) room_numbers = list(map(int, input().split())) n = len(room_numbers) room_numbers = sorted(room_numbers) left = [] right = [] flip = True for i in range(n): if flip: left.append(room_numbers[i]) else: right.append(room_numbers[i]) flip = not flip print(set(left).symmetric_difference(set(right)).pop())
#!/usr/bin/env python3 # https://www.hackerrank.com/challenges/finding-the-percentage/problem # tags: tipos de datos y estructuras de datos, diccionario if __name__ == '__main__': n = int(input()) estudiantes = {} # crear el diccionario for _ in range(n): # leemos el nombre y las calis como cadenas # con el asterisco es para leer el resto de cadenas resultantes del split nombre, *calis = input().split() # parseamos las calis a float calis = list(map(float, calis)) # agregamos el estudiante al diccionario estudiantes[nombre] = calis # leemos el nombre del alumno a consultar query_name = input() calificaciones = estudiantes[query_name] suma = 0.0 for c in calificaciones: suma += c promedio = suma / 3.0 print("%.2f" % promedio)
# https://www.hackerrank.com/challenges/alternating-characters/problem # Tag(s): Greedy, strings def alternatingCharacters(s): flag_1 = 'A' flag_2 = 'B' x = 0 y = 0 n = len(s) for i in range(n): if s[i] == flag_1: flag_1 = ('B' if flag_1 == 'A' else 'A') else: x += 1 if s[i] == flag_2: flag_2 = ('B' if flag_2 == 'A' else 'A') else: y += 1 return min(x, y) if __name__ == '__main__': T = int(input()) for _ in range(T): s = input() print(alternatingCharacters(s))
# A object orientated game import math import random class GameObject: x = 0 y = 0 def distance_to_game_object(self, obj): return math.sqrt( pow(self.x - obj.x, 2) + \ pow(self.y - obj.y, 2) ) class Player(GameObject): pass class Treasure(GameObject): def randomize_location(self): self.x = random.randint(-10, 10) self.y = random.randint(-10, 10) player = Player() treasure = Treasure() treasure.randomize_location() while True: print("You are at ({}, {}). The treasure is {} metres away!".format( player.x, player.y, treasure.distance_to_game_object(player) )) direction = input("Which way would you like to go? ") if direction == 'up': player.y += 1 elif direction == 'down': player.y -= 1 elif direction == 'left': player.x -= 1 elif direction == 'right': player.x += 1 else: print("That's not a real direction!") continue
n = int(input('Please enter a natural number greater than 1: ')) primes = [] for tested in range(2,n+1): for p in primes: if not tested % p: # exact division by p break else: primes.append(tested) print(primes)
#!/usr/bin/python #Author: Jay Gurnani from sys import exit, argv import os,re def main (arg): if len(arg) < 1: print "Wrong syntax. Required format = ./comment_parser.py argument.java" exit(0) else: checker(arg) def checker (file_entered): fileName, fileExt = os.path.splitext(file_entered) if (fileExt == ".java"): java_comment(file_entered) elif (fileExt == ".c" or fileExt == ".cpp"): c_comment(file_entered) elif (fileExt == ".php"): php_comment(file_entered) else: print "No recognized syntax. Only Java/C/PHP allowed" exit(0) def java_comment(file_entered): f = open(file_entered, 'r') for line in f: if (re.search('\/*.*\/', line) or re.search('\/\/', line)): line = line.strip() print line f.close() def c_comment(file_entered): f = open(file_entered, 'r') for line in f: if (re.search('\/*.*\/', line) or re.search('\/*', line) or re.search('\/\/', line)): line = line.strip() print line f.close() def php_comment(file_entered): f = open(file_entered, 'r') for line in f: if (re.search('\/*.*\/', line) or re.search('\/\/', line) or re.search('#', line)): line = line.strip() print line f.close()
# Stack (Implementation: Partial) # Queue (Implementation: Partial) # BinarySearchTree (Implementation: Partial) # AVL Tree (Implementation: Partial) # Heaps (Implementation: Incomplete) # Red Black Tree (Implementation: Incomplete) # B Tree (Implementation: Incomplete) # B+ Tree (Implementation: Incomplete) # Graphs: Prims, Kruskals... (Implementation: Future Plan) from avltree import AVLTree from bst import BinarySearchTree from treenode import TreeNode # Testing Binary Search Tree Deletion class MyTreeNode(TreeNode): value = 0 def __init__(self, value): self.value = value def compare_to(self, object): if object.value < self.value: return 1 if object.value > self.value : return -1 return 0 def __str__(self): return str(self.value) avl = AVLTree() def print_tree(avl): print("Inorder: ", [str(i) for i in avl.get_inorder_traversal()], " Postorder: ", [str(i) for i in avl.get_postorder_traversal()], avl.get_height()) avl.add(MyTreeNode(20)) print_tree(avl) # avl.add(MyTreeNode(30)) # print_tree(avl) # avl.add(MyTreeNode(35)) # print_tree(avl) # avl.add(MyTreeNode(40)) # print_tree(avl) # avl.add(MyTreeNode(41)) # print_tree(avl) # avl.add(MyTreeNode(45)) # print_tree(avl) # avl.add(MyTreeNode(46)) # print_tree(avl) # avl.add(MyTreeNode(50)) # print_tree(avl) # avl.add(MyTreeNode(60)) # print_tree(avl) # avl.add(MyTreeNode(70)) # print_tree(avl) # avl.add(MyTreeNode(42)) # print_tree(avl) print(avl.remove(MyTreeNode(20))) print_tree(avl)
import turtle import random import time screen = turtle.Screen() screen.bgcolor("black") screen.colormode(255) t = turtle.Turtle() for i in range(99999): t.shape("classic") x = random.randint(-200, 200) height = random.randint(100,350) t.left(90) t.penup() t.goto(x,-150) t.pendown() t.speed(1) t.color(100, 100, 100) t.forward(height) size = 50 r = random.randint(0, 255) g = random.randint(0, 255) b = random.randint(0, 255) t.color(r, g, b) type = random.randint(1, 3) t.clear() if type == 2 : t.speed(2) t.color(0, 0, 0) t.shape("circle") for i in range(12): turn = random.randint(1, 360) d = random.randint(10,50) t.color(r, g, b) t.left(90) t.color(0, 0, 0) t.forward(d) if type == 1 : t.speed(100) for i in range(36): t.forward(size) t.backward(size) t.left(10) if type == 3 : t.penup() screen.bgcolor(r, g, b) time.sleep(0.3) screen.bgcolor("black") wait = random.randint(0, 2) time.sleep(wait) t.clear() t.right(90)
import turtle def draw_square(some_turtle): for i in range(1,5): some_turtle.forward(100) some_turtle.right(90) def draw_art(): window = turtle.Screen() window.bgcolor("red") #Create the turtle Brad - Draws a square brad = turtle.Turtle() brad.shape("turtle") brad.color("blue") brad.speed(10) for i in range(1,37): draw_square(brad) brad.right(10) #Create the turtle Angie - Draws a circle #angie = turtle.Turtle() #angie.shape("arrow") #angie.color("white") #angie.circle(100) window.exitonclick() #draw_art() def draw_form(): window = turtle.Screen() window.bgcolor("black") #Create the turtle letter - Draw initials pen = turtle.Turtle() pen.color("white") pen.speed(5) for i in range(1,37): pen.forward(50) pen.right(120) pen.forward(100) pen.left(120) pen.forward(50) pen.left(120) pen.forward(100) pen.right(10) window.exitonclick() draw_form()
class Evento: def __init__(self, nomeEvento, dataEvento, dataFim): self.nomeEvento = nomeEvento self.dataEvento = dataEvento self.dataFim = dataFim def __str__(self): return "Nome do Evento: " + self.nomeEvento + "\nData do Evento:" + self.dataEvento class Pessoa: def __init__(self, nome, dataNasc, evento): self.nome = nome self.dataNasc = dataNasc self.evento = evento def __str__(self): return "Nome: " + self.nome + "\nData Nascimento: " + self.dataNasc + "\nEvento:" + self.evento class Autor(Pessoa): def __init__(self, curriculo, cpf, nome, data_nascimento): self.curriculo = curriculo super().__init__(cpf, nome, data_nascimento) def __str__(self): return "Nome: " + self.Pessoa.nome + "\nData Nascimento: " + self.Pessoa.dataNasc + "\nEvento:" + self.Pessoa.evento + "\nCategoria Autor:" + self.categoria class Artigo: def __init__(self, nomeArtigo, palavras_chave, dataArtigo): self.nomeArtigo = nomeArtigo self.dataArtigo = dataArtigo self.palavras_chave = palavras_chave def __str__(self): return "Nome do Artigo: " + self.nomeArtigo + "\tData Artigo: " + self.dataArtigo class ArtigoAutor: def __init__(self, artigo, autor): self.artigo = artigo self.autor = autor def __str__(self): return "Artigo: " + self.artigo + "\tAutor: " + self.autor class PessoaFisica(Pessoa): def __init__(self, cpf, nome, data_nascimento, evento): self.cpf = cpf super().__init__(nome, data_nascimento, evento) def __str__(self): return "Nome: " + self.Pessoa.nome + "\nData Nascimento: " + self.Pessoa.dataNasc + "\nEvento:" + self.Pessoa.evento + "\nCPF:" + self.cpf class PessoaJuridica(Pessoa): def __init__(self, cnpj, nome, data_nascimento, evento): self.cnpj = cnpj super().__init__(nome, data_nascimento, evento) def __str__(self): return "Nome: " + self.Pessoa.nome + "\nData Nascimento: " + self.Pessoa.dataNasc + "\nEvento:" + self.Pessoa.evento + "\nCNPJ:" + self.cnpj pf = PessoaFisica("11111", "thomas", "97", Evento("Xodrom", "03/02", "31/02")) print(pf.nome)
class SLNode: def __init__(self,value): self.value = value self.next = None class SList: def __init__(self): #node = SLNode(value) #self.head = node self.head = None def addNode(self,value): node = SLNode(value) #runner = self.head #when Head has value runner = self.head runner = node while(runner.next!=None): #check what runner's next is pointing to runner = runner.next # set runner point to runner(new node's: which we set on the line just above) next runner.next = node def printNode(self): runner = self.head print("\n\nhead points to ", id(self.head)) while(runner.next!=None): print(runner.value) runner = runner.next print(runner.value) def removfromFront(self): temp = self.head self.head.next = temp print(temp.next) #self.head = temp.next print("\n\n\n\n================== StArT OF ThE PrOgRaM ================") list = SList() list.addNode(7) list.addNode(10) list.addNode("Alice") list.printNode() list.removeNode() list.printNode()
''' x = [ [5,2,3], [10,8,9] ] students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'} ] sports_directory = { 'basketball' : ['Kobe', 'Jordan', 'James', 'Curry'], 'soccer' : ['Messi', 'Ronaldo', 'Rooney'] } z = [ {'x': 10, 'y': 20} ] ''' #1How would you change the value 10 in x to 15? Once you're done x should then be [ [5,2,3], [15,8,9] ]. x=[] x=[[5,2,3],[10,8,9]] for index in range(len(x)): for j in range(index): if(x[index][j]==10): x[index][j]=15 print(x) #2How would you change the last_name of the first student from 'Jordan' to "Bryant"? students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'} ] for key in range(len(students)): for value in students[key]: if(students[key][value]=='Jordan'): students[key][value]='Bryant' print(students) #For the sports_directory, how would you change 'Messi' to 'Andres'? sports_directory = { 'basketball' : ['Kobe', 'Jordan', 'James', 'Curry'], 'soccer' : ['Messi', 'Ronaldo', 'Rooney'] } '''print(sports_directory['soccer'][0]) for key in range(len(sports_directory)): #iterating through key till the length of the list for index in sports_directory[key]: print(sports_directory[key][index]) if(sports_directory[key][index]=='Messi'): sports_directory[key][index]='Andres' print(sports_directory)''' for key, val in sports_directory.items(): # print(val) for index in range(len(val)): #print(index) if(val[index]=='Messi'): val[index] ='Andres' print(sports_directory) #For z, how would you change the value 20 to 30? z = [ {'x': 10, 'y': 20} ] for key in range(len(z)): for value in z[key]: if(z[key][value]==20): z[key][value]=30 print(z) '''2. Create a function that given a list of dictionaries, it loops through each dictionary in the list and prints each key and the associated value. For example, given the following list: students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ] ''' dictt=[{'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'}] def printKeyValue(students): for key in students: print("first_name-"+key['first_name']+" "+"last_name-"+key['last_name']) printKeyValue(dictt) '''3. Create a function that given a list of dictionaries and a key name, it outputs the value stored in that key for each dictionary. For example, iterateDictionary2('first_name', students) should output Michael John Mark KB ''' students=[{'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'}] def printKeyValue(students,skey): for index in range(len(students)): for key,val in students[index].items(): if(key==skey): print(val) printKeyValue(students,'first_name') ''' Create a function that prints the name of each location and also how many locations the Dojo currently has. Have the function also print the name of each instructor and how many instructors the Dojo currently has. For example, printDojoInfo(dojo) should output ''' dojo = { 'locations': ['San Jose', 'Seattle', 'Dallas', 'Chicago', 'Tulsa', 'DC', 'Burbank'], 'instructors': ['Michael', 'Amy', 'Eduardo', 'Josh', 'Graham', 'Patrick', 'Minh', 'Devon'] } def printDojoInfo(dojo): for key,value in dojo.items(): print(f"{len(value)}"+key) print(value) printDojoInfo(dojo)
class PhoneBook: def __init__(self,line,dict): self.line = line self.phonedict = dict if len(self.line.split()) == 2: self.phonedict[self.line.split()[0]] = self.line.split()[1] def queryPhone(self,name): self.name = name if name in self.phonedict: print("{}={}".format(self.name,self.phonedict[self.name])) else: print("Not found") n = int(input()) phonedict = dict() for i in range(0, n): line = str(input()) p = PhoneBook(line,phonedict) qry_list = [] qry = str(input()) while qry: qry_list.append(qry) try: qry = str(input()) except (EOFError): break for name in qry_list: p.queryPhone(name)
def list_files(dpath, pattern=None, extension=".nc", include=None, exclude=None, verbose=0): """ list_files list files in a folder according to patterns Parameters ---------- dpath : string or pathlib.Path The path to the files (str) pattern : str, optional The pattern to follow, by default None extension : str, optional the extension, by default ".nc" include : str, optional a string that the items in the list must contain, by default None exclude : str, optional a string that the items in the list must contain, by default None verbose : int, optional whether or not to output some diagnostics, by default 0 Returns ------- list The sorted list of files """ import pathlib if not isinstance(dpath, pathlib.PosixPath): dpath = pathlib.Path(dpath) lfiles = list(dpath.glob(f"{pattern}*{extension}")) if len(lfiles) == 0: raise ValueError("No files in list") else: if include is not None: lfiles = [x for x in lfiles if include in str(x)] if exclude is not None: lfiles = [x for x in lfiles if exclude not in str(x)] lfiles.sort() if verbose == 1: print(f"loaded files, list length {len(lfiles)}") print(f"the first file is {str(lfiles[0])}") print(f"the last file is {str(lfiles[-1])}") return lfiles
# # IndentWriter # # An indented text printer. # # Makes clever use of the semantics of the Python 2.5+ "with" # statement to allow indented generator code to indent along # with its indented output. This allows generator code to # look much cleaner. # # (c) 2011 Lee Supe (lain_proliant) # Released under the GNU General Public License # import sys from abc import ABCMeta, abstractmethod #-------------------------------------------------------------------- class IndentBase (object): """ An abstract base class for string indenting. """ __metaclass__ = ABCMeta def __init__ (self, outfile = sys.stdout): """ Initializes an IndentWriter. """ self.il = 0 self.indentStr = ' ' self.enabled = True self.isnewline = False @abstractmethod def _write_raw (self, output): """ The raw write method. This method is private. This method is abstract and must be implemented by subclasses to pass on the output. """ pass def write (self, output): """ Print the given line to output, indenting if necessary. """ if self.isnewline: self.isnewline = False self._write_raw (self.indentStr * self.il) self._write_raw (output) def indent (self, level = 1): """ Indent the given number of levels. A minimum indent level is not enforced by this method, though an indent level below zero is equivalent zero. """ self.il += level def unindent (self, level = 1): """ Unindent the given number of levels. The indent level cannot go below 0 if this method is used to decrease the indent level. """ self.il -= level if self.il < 0: self.il = 0 def setIndentString (self, indentStr): """ Sets the string used to indent. This string is prepended to each line printed for each indent level. """ self.indentStr = indentStr def setEnabled (self, enabled): """ Sets whether indenting is enabled. """ self.enabled = enabled def println (self, output): """ Print the given line to output, indenting if necessary. A newline is appended to the output. """ self.write (output) self.newline () def printLines (self, output): """ Prints the given string with multiple lines to output, indenting each line. """ for line in output.splitlines (): self.println (line) def writeln (self, output): """ A synonym for println. """ self.println (output) def newline (self): """ Append a newline to the output. """ self.isnewline = True self._write_raw ('\n') def __enter__ (self): """ This method is called when the object enters the context of a with block. EXAMPLE: iw = IndentWriter () iw.println ("Hello,") with iw: iw.println ("World!") OUTPUT: Hello, World! """ self.indent () def __exit__ (self, excType, excVal, excTraceback): """ This method is called when the object leaves the context of a with block. EXAMPLE: iw = IndentWriter () with iw: iw.println ("Hello,") iw.println ("World!") OUTPUT: Hello, World! """ self.unindent () #-------------------------------------------------------------------- class IndentWriter (IndentBase): """ An indented text printer. """ def __init__ (self, outfile = sys.stdout): """ Initializes an IndentWriter. """ IndentBase.__init__ (self) self.outfile = outfile def _write_raw (self, output): """ The raw write method. Sends the output on to the output file. """ self.outfile.write (output) #-------------------------------------------------------------------- class IndentStringBuilder (IndentBase): """ An indented string builder. Appends all of the given input into a string, which can be fetched via str () or via IndentStringBuilder.getString (). """ def __init__ (self): """ Initializes an IndentStringBuilder. """ IndentBase.__init__ (self) self.strings = [] def _write_raw (self, output): """ The raw write method. Adds the given output string to a list of strings to be concatenated when necessary. """ self.strings.append (output) def getLines (self): """ Gets all of the individual lines of output. """ lines = [] for outputStr in self.strings: lines.extend (filter (None, outputStr.split ('\n'))) return lines def getString (self): """ Concatenates the list of output strings. This is much more efficient than concatenating on each write. """ return ''.join (self.strings) def __str__ (self): """ Calls getString to get a full string representation of the output. See getString for more details. """ return self.getString ()
#!/usr/bin/env python import itertools # A ring class - we use it to transpose our basic scale : C D E F G A B class Ring: def __init__(self, l): if not len(l): raise "ring must have at least one element" self._data = l def __repr__(self): return repr(self._data) def __len__(self): return len(self._data) def __getitem__(self, i): if i >= len(self._data): i = i % len(self._data) return self._data[i] def __delitem__(self, i): del self._data[i] def index(self, i): return self._data.index(i) def turn(self): # Scales turn in reverse-order first = self._data.pop(0) self._data.append(first) def first(self): return self._data[0] def last(self): return self._data[-1] def turn_until(self, value): while self.first() != value: self.turn() def turn_ntimes(self, times): i = 0 while i < times: self.turn() i += 1 scales = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"] modes = {"Ionian" : "C", "Dorian" : "D", "Phrygian" : "E", "Lydian" : "F", "Mixolydian" : "G", "Aeolian" : "A", "Locrian" : "B"} class Scale: def __init__(self, scale="C", formula=[2, 2, 1, 2, 2, 2, 1]): self.start = Ring(["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]) # We store a modified scale as numbers : 1 means no sharp or flat, 0.5, one flat, 1.5 one sharp self.formula = formula self.transpose_scale(scale) #self.change_mode(mode) def transpose_scale(self, start_letter): self.start.turn_until(start_letter) def change_mode(self, mode_letter): v = ["C", "D", "E", "F", "G", "A", "B"] self.values.turn_ntimes(v.index(mode_letter)) def __str__(self): retscale = self.start[0] + " " notes = self.start translation_table = { "Cb": "B", "Db" : "C#", "Eb" : "D#", "Fb" : "E", "Gb" : "F#", "Ab" : "G#", "Bb" : "A#", "B#" : "C", "E#" : "F", } i = 0 j = 0 while i < 11 and j < 6: # reduce(lambda x,y: x+y, self.values) n = self.formula[j] retscale += notes[i+n] i += n j += 1 # Don't forget to increment j to avoid looping. retscale += " " return retscale if __name__ == "__main__": s = Scale("C", [2, 1, 1, 2, 2, 2, 1]) print str(s)
import re text = 'abbaabbbbaaaaa' pattern = 'ab' for match in re.findall(pattern, text): print ('Found {!r}'.format(match))