text
stringlengths
37
1.41M
#!/usr/bin/env python # -*- coding: utf-8 -*- r"""vernalequinox -- DESCRIPTION """ from abc import ABCMeta as _ABCMeta, abstractmethod as _abstractmethod from datetime import date __all__ = ['CalcVernalEquinox'] class Longitude(object): r"""SUMMARY """ __metaclass__ = _ABCMeta _month = 3 @_abstractmethod def ismatch(self, year): raise NotImplementedError() @_abstractmethod def calc(self, year): raise NotImplementedError() def _getday(self, year, day): r"""SUMMARY _getday(day) @Arguments: - `day`: @Return: """ return date(year, self._month, day) class Before1980_0Longitude(Longitude): r"""SUMMARY VernalEquinox """ def ismatch(self, year): r"""SUMMARY ismatch(year) @Arguments: - `year`: @Return: """ return year <= 1979 def calc(self, year): r"""SUMMARY calc(year) @Arguments: - `year`: @Return: """ # 一年のずれ 閏年のずれ day = int(20.8357 + 0.242194 * (year - 1980) - int((year - 1980) // 4)) return self._getday(year, day) class From1980To2100_0Longitude(Longitude): r"""SUMMARY """ def ismatch(self, year): r"""SUMMARY ismatch(year) @Arguments: - `year`: @Return: """ return 1980 <= year <= 2099 def calc(self, year): r"""SUMMARY calc(year) @Arguments: - `year`: @Return: """ # 一年のずれ 閏年のずれ day = int(20.8431 + 0.242194 * (year - 1980) - int((year - 1980) // 4)) return self._getday(year, day) class From2100To2150_0Longitude(Longitude): r"""SUMMARY """ def ismatch(self, year): r"""SUMMARY ismatch(year) @Arguments: - `year`: @Return: """ return 2100 <= year <= 2150 def calc(self, year): r"""SUMMARY calc(year) @Arguments: - `year`: @Return: """ # 一年のずれ 閏年のずれ day = int(21.8510 + 0.242194 * (year - 1980) - int((year - 1980) // 4)) return self._getday(year, day) class CalcVernalEquinox(object): r"""SUMMARY """ _spans = [Before1980_0Longitude(), From1980To2100_0Longitude(), From2100To2150_0Longitude()] def calc(self, year): r"""SUMMARY get_vernal_day(year) @Arguments: - `year`: @Return: """ for span in self._spans: if span.ismatch(year): return span.calc(year) # TODO: (Atami) [2014/06/30] raise StandardError() # For Emacs # Local Variables: # coding: utf-8 # End: # vernalequinox.py ends here
hrs = float(input("Enter Hours:")) rate = float(input("Enter Rate:")) if hrs > 40: result = hrs * rate a = (hrs - 40) * (rate * 0.5) result = result + a else: result = hrs * rate print(result)
#现在有多个字典或者映射,你想将它们从逻辑上合并为一个单一的映射后执行某些操作, 比如查找值或者检查某些键是否存在。 from collections import ChainMap a = {'x': 1, 'z': 3 } b = {'y': 2, 'z': 4 } c = ChainMap(b,a) print(c['x']) # Outputs 1 (from a) print(c['y']) # Outputs 2 (from b) print(c['z']) # Outputs 3 (from a) #一个 ChainMap 接受多个字典并将它们在逻辑上变为一个字典。 然后,这些字典并不是真的合并在一起了, #对于字典的更新或删除操作总是影响的是列表中第一个字典。 c['z'] = 10 print(b) values = ChainMap() values['x'] = 1 # Add a new mapping values = values.new_child() values['x'] = 2 # Add a new mapping values = values.new_child() values['x'] = 3 print(values) ChainMap({'x': 3}, {'x': 2}, {'x': 1}) print(values['x']) # Discard last mapping values = values.parents print(values['x']) # Discard last mapping values = values.parents print(values['x']) print(values) merged = dict(b) merged.update(a) #如果原字典做了更新,这种改变不会反应到新的合并字典中去
#first create class #self represet object when we create object class Person: def __init__(self,first_name,last_name,age): # instance variable initilise print("init method // constructor get called") self.first_name = first_name self.last_name = last_name self.age = age p1 = Person('deepak','saini',45) p2 = Person('rahul','saini',67) print(p1.first_name)
def even_odd(y): if (y%2==0): print("the number is even") else: print("the number is odd")
# # @lc app=leetcode id=145 lang=python3 # # [145] Binary Tree Postorder Traversal # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: res = [] def dfs(node): if not node: return dfs(node.left) dfs(node.right) res.append(node.val) dfs(root) return res # class Solution: # def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: # if not root: # return [] # result , stack = [], [] # prev, node = None, root # while stack or node: # # if node is valid, add it to the stack and keep going left # if node: # stack.append(node) # node = node.left # else: # # done with all left children for this node # top = stack[-1] # # check if this top of stack node has any right children yet to be explored # # Also, make sure that right child wasn't just previously visited # if top.right and top.right != prev: # node = top.right # else: # # no right child, so this should be a leaf node # result.append(top.val) # prev = top # stack.pop() # return result # @lc code=end
# # @lc app=leetcode id=5 lang=python3 # # [5] Longest Palindromic Substring # # @lc code=start class Solution: def longestPalindrome(self, s: str) -> str: if not s: return "" n = len(s) is_palindrome = [[False]*n for _ in range(n)] for i in range(n): is_palindrome[i][i] = True for i in range(1,n): is_palindrome[i][i-1] = True longest, start, end = 1, 0, 0 for length in range(1,n): for i in range(n-length): j = i + length is_palindrome[i][j] = s[i] == s[j] and is_palindrome[i+1][j-1] if is_palindrome[i][j] and length+1 > longest: longest = length + 1 start, end = i, j return s[start: end+1] # @lc code=end
# # @lc app=leetcode id=461 lang=python3 # # [461] Hamming Distance # # @lc code=start class Solution: def hammingDistance(self, x: int, y: int) -> int: distance = 0 while(x !=0 or y!=0): if(x%2 != y%2): distance += 1 x = x //2 y = y //2 return distance # @lc code=end
# # @lc app=leetcode id=530 lang=python3 # # [530] Minimum Absolute Difference in BST # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: nums = [] def getMinimumDifference(self, root: TreeNode) -> int: """ :type root: TreeNode :rtype: int """ self.res = float("inf") self.prev = None self.inOrder(root) return self.res def inOrder(self, root): if not root: return self.inOrder(root.left) if self.prev: self.res = min(self.res, root.val - self.prev.val) self.prev = root self.inOrder(root.right) # @lc code=end
# # @lc app=leetcode id=240 lang=python3 # # [240] Search a 2D Matrix II # # @lc code=start class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: if not matrix or not matrix[0]: return False rows = len(matrix) cols = len(matrix[0]) row, col = 0, cols - 1 while True: if row < rows and col >= 0: if matrix[row][col] == target: return True elif matrix[row][col] < target: row += 1 else: col -= 1 else: return False # @lc code=end
def bubblesort(items): lst = list(items) for i in range(len(lst)): for j in range(i + 1, len(lst)): if lst[j] < lst[i]: lst[j], lst[i] = lst[i], lst[j] return lst
#hangman using turtle import turtle import random def draw(x): if x==1: #h t.circle(60) elif x==2: #a t.right(90) t.right(30) t.forward(100) t.backward(100) elif x==3: #n t.left(60) t.forward(100) t.backward(100) t.right(30) elif x==4: #g t.forward(100) elif x==5: #m t.right(30) t.forward(100) t.backward(100) elif x==6: #a t.left(60) t.forward(100) t.up() t.home() elif x==7: #n t.goto(0,120) t.down() t.left(90) t.forward(20) t.left(90) t.forward(150) t.left(90) t.forward(400) vowels=['a','e','i','o','u'] def show(movie,letter=[]): for i in movie: if i !=' ': if i in letter: print(i,end=' ') elif i in vowels: print(i,end=' ') else: print("_",end=' ') else: print(i,end=' ') f=open('movie.txt','r') mc=1 r=random.randint(1,50) #print(r) while mc<=50: st=f.readline().strip() lstr=st.split(',') #print(lstr) if lstr[0]==str(r): m=lstr[1].lower() break mc+=1 f.close() print("Guess the movie \n") show(m) s1=set() for i in m: if i!=' ': if i not in vowels: s1.add(i) l=[] g=[] hm="hangman" hmc=0 s=turtle.getscreen() t=turtle.Turtle() while(len(l)!=7): c=input("\nguess letter ") if c in vowels: print("vowels already shown ") continue if c in m: g.append(c) print("\nright guess \n") show(m,g) else: print("\nwrong guess \n") l.append(hm[hmc]) hmc+=1 draw(len(l)) s2=set(g) if len(s2)==len(s1): print("\ncongrats, you have won") break #print(l) if len(l)>=7: print("sorry you have lost \n game over")
def main(): print('Cálculo do fatorial de um número\n') n = int(input('Digite um número inteiro não-negativo: ')) if n < 0: print('Impossível calcular números negativos') i = 1 n_fat = 1 while i <= n: n_fat = n_fat * i i = i + 1 print("%d! = %d" % (n, n_fat)) main()
import numpy as np def game_core(number): """Guess a number with binary search Keyword arguments: number -- number to guess """ count = 0 start = 0 end = 101 predict = end // 2 while number != predict: count += 1 if number > predict: start = predict predict += (end - predict) // 2 elif number < predict: end = predict predict -= (predict - start) // 2 return count def score_game(game_core): """Launch game 1000 time to know how fast it guesses a number""" count_ls = [] np.random.seed(1) random_array = np.random.randint(1, 101, size=(1000)) for number in random_array: count_ls.append(game_core(number)) score = int(np.mean(count_ls)) print(f"Your algorithm guesses the number on average in {score} attempts") return score # Launch score_game(game_core)
import numpy as np #importamos numpy import random #libreria para elegir al ganador class Arreglos: #creamos una clase array1 = [] array2 = [] diagonal = [] invetido = [] def _init_(self): #agregamos el constructor pass def crear_arreglos(self): #creamos un error try: #intente hace todo lo de adentro (si hay errores) for i in range(2): #de la vuelta dos veces para las dos matrices print("\nGrupo "+str(i+1)+":") #indique el grupo filas = int(input("Ingresa no. filas: ")) #pedimos filas y columnas que ingrese el usuario columnas = int(input("Ingresa no. columnas: ")) for j in range(filas): #que recorra las filas if i == 0: #si está en la posición 0 almacena array1 self.array1.append([]) else: #caso contrario en el 2 self.array2.append([]) print("Fila "+str(j+1)+":") #nos imprima el no. de fila que va recorriendo for k in range(columnas): #que recorra las columnas lista = int(input("Ingresa elemento para columna "+str(k+1)+": ")) #aquí vamos preguntando los valores que va a almacenar if i == 0: #si es posición 0 almacena array1 self.array1[j].append(lista) else: #caso contrario en el 2 self.array2[j].append(lista) self.array1 = np.array(self.array1) #convetimos el array a uno mismo pero con las propiedades de NUmpy, lo mismo el 2 self.array2 = np.array(self.array2) print("\nAcomodo del grupo 1: \n",self.array1) #imprimimos ambas matrices print("Acomodo del grupo 2: \n",self.array2) except: #si hay algún error imprima un mensja y vuelva a ejecutar el método print("Datos incorrectos, intente de nuevo.") return self.crear_arreglos() def eliminar(self): #método para eliminar alguna columna try: arreglo = int(input("Ingrese grupo (1 o 2) para eliminar columna: ")) #preguntamos cuál matriz if arreglo == 1: #si es igual a 1 es la matriz 1 tamaño1 = self.array1.shape #obtenemos las dimensiones columnas = int(input("Ahora ingresa el no. columna (hay "+str(tamaño1[1])+"): ")) #pedimos la posición self.array1 = np.delete(self.array1, columnas, axis = 1) #con delete reciebiendo como parametro el nombre del array, la posición y axis igual a 1 que indica que va a eliminar una columna print("\nNuevo acomodo: \n",self.array1) #imprimimos nuevo valor de la matriz elif arreglo == 2: #si es igual a 2 es la matriz 2 tamaño2 = self.array2.shape #obtenemos las dimensiones columnas = int(input("Ahora ingresa el no. columna (hay "+str(tamaño2[1])+"): ")) #pedimos la posición self.array2 = np.delete(self.array2, columnas, axis = 1) #con delete reciebiendo como parametro el nombre del array, la posición y axis igual a 1 que indica que va a eliminar una columna print("\nNuevo acomodo: \n",self.array2) #imprimimos nuevo valor de la matriz else: #si no es ni 1 ni 2 mande un mensaje y repita el método print("Datos incorrectos, intente de nuevo.") return self.eliminar() except: #si ingresó la columna fuera de rango o diferente tipo de dato lo muestre y ejecute el método de nuevo print("Columna incorrecta, intente de nuevo.") return self.eliminar() def agregar(self): #metodo agregar fila columna en cualquier matriz try: tamaño1 = self.array1.shape #obtenemos las dimensiones tamaño2 = self.array2.shape arreglo = int(input("Ingrese grupo (1 o 2) para agregar elemento: ")) #preguntamos cuál matriz if arreglo == 1: #si es igual a 1 es la matriz 1 elegir = input("¿Deseas ingresar fila o columna? ").lower() #preguntamos si fila o columna if elegir == "fila": #si es fila print("Al querer ingresar una fila tiene que ingresar una matriz con el mismo no. de columnas ("+str(tamaño1[1])+" elementos): ") #mostramos qué tiene que ingresar el usuario row = [] for z in range (tamaño1[1]): #lo repetimos el no. de columnas que tenga esa matriz elemento = int(input("Ingresa elemento "+str(z+1)+": ")) #pedimos los valores row.append(elemento) #los almacenamos valores = np.array(row) #usamos propiedades de Numpy valores = valores.reshape(1,-1) #lo hacemos matriz leyendo una fila y que en automatico se ajuste el no. de columnas self.array1 = np.append(self.array1, valores, axis =0) #con append recibiendo como parametros la matriz, los nuevos valores y la axis indicando fila elif elegir == "columna": #si es columna print("Al querer ingresar una columna tiene que ingresar una matriz con el mismo no. de filas ("+str(tamaño1[0])+" elementos): ") #mostramos qué tiene que ingresar el usuario row = [] for z in range (tamaño1[0]): #lo repetimos el no. de filas que tenga esa matriz elemento = int(input("Ingresa elemento "+str(z+1)+": ")) #pedimos los valores row.append(elemento) #los almacenamos valores = np.array(row) #usamos propiedades de Numpy valores = valores.reshape(-1,1) #lo hacemos matriz leyendo una columna y que en automatico se ajuste el no. de filas self.array1 = np.append(self.array1, valores, axis =1) #con append recibiendo como parametros la matriz, los nuevos valores y la axis indicando columna else: #si escribe mal el usuario mande un mensaje y vuelva a ejecutar el método print("Datos inccorrectos, favor de verificar.") print("\nNuevo acomodo: \n",self.array1) #nos muestra el nuevo resultado elif arreglo == 2: #mismo proceso que anterior, solo que con la matriz 2: elegir = input("¿Deseas ingresar fila o columna:").lower() if elegir == "fila": print("Al querer ingresar una fila tiene que ingresar una matriz con el mismo no. de columnas ("+str(tamaño2[1])+" elementos): ") row = [] for z in range (tamaño2[1]): elemento = int(input("Ingresa elemento "+str(z+1)+": ")) row.append(elemento) valores = np.array(row) valores = valores.reshape(1,-1) self.array2 = np.append(self.array2, valores, axis =0) elif elegir == "columna": print("Al querer ingresar una columna tiene que ingresar una matriz con el mismo no. de filas ("+str(tamaño2[0])+" elementos): ") row = [] for z in range (tamaño2[0]): elemento = int(input("Ingresa elemento "+str(z+1)+": ")) row.append(elemento) valores = np.array(row) valores = valores.reshape(-1,1) self.array2 = np.append(self.array2, valores, axis =1) else: print("Datos inccorrectos, favor de verificar.") print("\nNuevo acomodo: \n",self.array2) #nos muestra el nuevo resultado else: print("Datos incorrectos, intente de nuevo.") #si ingreso el numero de matriz incorrecto return self.eliminar() repetir = input("¿Desea agregar más elementos? (SI/NO): ").lower() #preguntamos si desea almacenar más elementos if repetir == "si": #si es si vuelva a ejecutar todo el método return self.agregar() except: #si hay algún error mande y mensaje y retorne el método print("Datos erroneos, intente de nuevo.") return self.agregar() def sumar_multiplicar(self): #método sumar y multiplicar ambas matrices tamaño1 = self.array1.shape #obtenemos las dimensiones fila1 = tamaño1[0] #obtemos tamaño de fila de la matriz 1 columna1 = tamaño1[1] #obtemos tamaño de columna de la matriz 1 tamaño2 = self.array2.shape fila2 = tamaño2[0] #obtemos tamaño de fila de la matriz 2 columna2 = tamaño2[1] #obtemos tamaño de columna de la matriz 2 if fila1 == fila2 and columna1 == columna2: #hacemos varias validaciones, si ambas matrices son del mismo tamaño en automatico haga la suma y la multiplicación, así también imprimir suma = self.array1 + self.array2 print("\nGrupos ajustados: \n") print(self.array1,"\n", self.array2) print ("\nSuma de ambos grupos: \n",suma) multiplicacion = self.array1 * self.array2 print ("Multiplicación de ambos grupos: \n",multiplicacion) elif fila1 == columna2 and fila2 == columna1: #si la fila de matriz 1 es igual a la columna de matriz 2 y la fila de matriz 2 es igual a la columna de matriz 1 solo invertimos las filas por columnas de la matriz 2, hacemos las operaciones e imprimimos self.array2 = self.array2.tranpose() print("\nGrupos ajustados: \n") print(self.array1,"\n",self.array2) suma = self.array1 + self.array2 print ("\nSuma de ambos grupos: \n",suma) multiplicacion = self.array1 * self.array2 print ("Multiplicación de ambos grupos: \n",multiplicacion) elif fila1 > fila2: #si la fila de la matriz 1 es mayor a la de 2 self.array1 = np.delete(self.array1, -1, axis = 0) #eliminar la ultima fila de la matriz 1 return self.sumar_multiplicar() #vuelve a ejecutar el método elif columna1 > columna2: #si la columna de la matriz 1 es mayor a la de 2 self.array1 = np.delete(self.array1, -1, axis = 1) #eliminar la ultima columna de la matriz 1 return self.sumar_multiplicar() #vuelve a ejecutar el método elif fila1 < fila2: #si la fila de la matriz 1 es menor a la de 2 self.array2 = np.delete(self.array2, -1, axis = 0) #eliminar la ultima fila de la matriz 2 return self.sumar_multiplicar() #vuelve a ejecutar el método elif columna1 < columna2: #si la columna de la matriz 1 es menor a la de 2 self.array2 = np.delete(self.array2, -1, axis = 1) #eliminar la ultima columna de la matriz 2 return self.sumar_multiplicar() #vuelve a ejecutar el método #seguirá el bucle hasta que cumpla la condición 1 o 2 del método def invertir(self): #metodo para invertir una matriz seleccionada arreglo = int(input("Ingresa grupo a invertir (1 o 2): ")) #pedimos cuál matriz if arreglo == 1: #si es igual a 1 invertimos filas por columnas en la matriz 1 self.invertido = self.array1.transpose() #el resultado lo guardamos en otra variable elif arreglo == 2: #si es igual a 1 invertimos filas por columnas en la matriz 1 self.invertido = self.array2.transpose() #el resultado lo guardamos en otra variable else: #si no es ni 1 ni 2 enviamos mensaje y retornamos el método print("Datos incorrectos, favor de verificar: ") return self.invertir() print("Grupo seleccionado invertido: \n",self.invertido) #mostramos el resultado def diagonal(self): #metodo para generar una diagonal de una matriz seleccionada arreglo = int(input("Ingresa grupo para diagonal (1 o 2): ")) #pedimos cuál matriz if arreglo == 1: #si es igual a 1 generamos la diagonal en matriz 1 self.diagonal = np.diag(self.array1) #el resultado lo guardamos en otra variable elif arreglo == 2: #si es igual a 1 generamos la diagonal en matriz 2 self.diagonal = np.diag(self.array2) #el resultado lo guardamos en otra variable else: #si no es ni 1 ni 2 enviamos mensaje y retornamos el método print("Datos incorrectos, favor de verificar: ") return self.invertir() print("Diagonal de grupo seleccionado: \n",self.diagonal) #mostramos el resultado def modificar(self): #metodo para modificar un elemento de una matriz seleccionada tamaño1 = self.array1.shape #obtenemos las dimensiones tamaño2 = self.array2.shape arreglo = int(input("Ingresa grupo a modificar (1 o 2): ")) #pedimos cuál matriz if arreglo == 1: #si es igual a 1 modifica matriz 1 fila = int(input("Ingresa posición de fila (hay "+str(tamaño1[0])+"): ")) #pedimos cuál posición en filas columna = int(input("Ingresa posición de columna (hay "+str(tamaño1[1])+"): ")) #pedimos cuál posición en columnas valor = int(input("Ingresa valor para esa posición: ")) #pedimos el valor nuevo para modificarlo self.array1[fila][columna] = valor #ingresamos posiciones y valor en matriz 1 para modificarlo print("Grupo modificado: \n",self.array1) #mostramos resultados elif arreglo == 2: #si es igual a 2 modifica matriz 2 fila = int(input("Ingresa posición de fila (hay "+str(tamaño2[0])+"): ")) #pedimos cuál posición en filas columna = int(input("Ingresa posición de columna (hay "+str(tamaño2[1])+"): ")) #pedimos cuál posición en columnas valor = int(input("Ingresa valor para esa posición: ")) #pedimos el valor nuevo para modificarlo self.array2[fila][columna] = valor #ingresamos posiciones y valor en matriz 2 para modificarlo print("Grupo modificado: \n",self.array2) #mostramos resultados else: #si no es ni 1 ni 2 enviamos mensaje y retornamos el método print("Datos incorrectos, favor de verificar: ") return self.invertir() repetir = input("¿Desea modificar otro elemento? (SI/NO): ").lower() #preguntamos si desea modificar otro elemento if repetir == "si": #si es si vuelva a ejecutar todo el método return self.agregar() def ganador(self): seleccion = random.randint(1, 2) #generamos un número random entre 1 y 2 print("\nElección del ganador: ") if seleccion == 1: #si el número random es 1 toma la diagonal tamaño = len(self.diagonal) #leemos la longitud del vector ganador = random.randint(0, tamaño - 1) #pedimos un número ganador entre 0 y la longitud -1 para poder tomar alguna posición print ("¡El ganador es el número "+str(self.diagonal[ganador])+"!") #imprimimos el ganador con la diagonal indicando la posición aleatoria else: #caso contrario si toma dos tamaño = self.invertido.shape #obtenemos las dimensiones de la matriz invertida fila = random.randint(0, tamaño[0] - 1) #pedimos una fila entre 0 y el tamaño de la fila -1 para poder tomar alguna posición columna = random.randint(0, tamaño[1] - 1) #pedimos una columna entre 0 y el tamaño de la columna -1 para poder tomar alguna posición print ("¡El ganador es el número "+str(self.invertido[fila][columna])+"!") #imprimimos el ganador con la mtriz invertida indicando la fila y columna aleatoria objeto= Arreglos() #creamos el objeto que llame a la clase objeto.crear_arreglos() #llamamos a cada método para que se ejecute objeto.eliminar() objeto.agregar() objeto.sumar_multiplicar() objeto.modificar() objeto.invertir() objeto.diagonal() objeto.ganador()
""" Elabora un codigo donde dada una palbra la invierta (usa la estructura de datos pila) """ def stringToList(string): ls=[]#declaracion lista ls[:0]=string #pasar de str a lista return ls#retornar la variable ls def listToString(string): str1 = "" #declaracion de string for i in string:#ciclo for str1 += i#concatenacion return str1 #retorno de la variable str1 def split(read): ls = []#declaracion de lista for i in range(len(read)):#ciclo for ls.append(read.pop())#agregar a la lista el ultimo valor de la lista read return ls#retorno de la variable ls print(listToString(split(stringToList(input("Ingrese una plabra: ")))))#llamada de metodos
# -*- coding:utf-8 -*- # !/usr/bin/env pyhon3 #import matplotlib import matplotlib.pyplot as plt #matplotlib.use("Agg") input_value = [1, 2, 3, 4, 5] squares = [1, 4, 9, 16, 25] plt.plot(input_value, squares, linewidth=5) #设置图标标题,并给坐标轴加上标签 plt.title("Square Number", fontsize=24) plt.xlabel("Value", fontsize=14) plt.ylabel("Square of value", fontsize=14) #设置刻度标记的大小 plt.tick_params(axis='both', labelsize=14) plt.show()
def magic_tuples(total_sum, max_number): return ((i, j) for i in range(1, max_number) for j in range(1, max_number) if (i+j) == total_sum) if __name__ == "__main__": for t in magic_tuples(10, 10): print(t)
class Foo(object): _instances = [] def __new__(cls, x): if x in cls._instances: pass else: cls._instances.append(x) return super(Foo, cls).__new__(cls) def __init__(self, x): self.x = x class Uniquish(): _instances = [] def __new__(cls, x): if x in cls._instances: pass else: cls._instances.append(x) return super(Uniquish, cls).__new__(cls) def __init__(self, x): self.x = x class Bar(Uniquish): def __init__(self, x): self.x = x f1 = Foo(10) f2 = Foo(10) f3 = Foo(10) s = {f1, f2, f3} for i in s: print(i) b1 = Bar(10) b2 = Bar(10) b3 = Bar(10) r = {b1, b2, b3} for i in r: print(r)
t = int(input()) for qwerty in range(t): #n,q=input().split() #n,q=int(n),int(q) n=int(input()) #arr=list(map(int,input().split())) firstName=[] lastName=[] for i in range(n): x,y=input().split() firstName.append(x) lastName.append(y) for i in range(n): if(firstName.count(firstName[i])>1): print(firstName[i],lastName[i],sep=" ") else: print(firstName[i])
#!/usr/bin/env python from collections import Counter, defaultdict import sys try: columns = int(sys.argv[1]) except IndexError: columns = 3 words = ['about', 'after', 'again', 'below', 'could', 'every', 'first', 'found', 'great', 'house', 'large', 'learn', 'never', 'other', 'place', 'plant', 'point', 'right', 'small', 'sound', 'spell', 'still', 'study', 'their', 'there', 'these', 'thing', 'think', 'three', 'water', 'where', 'which', 'world', 'would', 'write'] indexes = {0: 'First', 1: 'Second', 2: 'Third'} possibles = [] for index in range(columns): curr_words = words[:] column = raw_input("{} column of letter: ".format(indexes[index])) for word in words: if word[index] not in column: curr_words.remove(word) words = curr_words print words
from cola import Cola from random import randint # cola_datos = Cola() # cola_aux = Cola() # for i in range (0,10): # num = randint(0,100) # cola_datos.arribo(num) # print(num) # print() # cantidad_elemento = 0 # while(cantidad_elemento < cola_datos.tamanio()): # dato = cola_datos.mover_final() # print(dato) # cantidad_elemento =+ 1 # while(not cola_datos.cola_vacia()): # dato = cola_datos.atencion() # cola_aux.arribo(dato) # print(dato) # while (not cola_aux.cola_vacia()): # dato = cola_aux.atencion() # cola_datos.arribo(dato) #Ejercicio 1 # cola_letras = Cola() # palabra = input ('Ingrese una palabra') # for letra in palabra: # cola_letras.arribo(letra.lower)() # vocales = ['a', 'e', 'i', 'o', 'u'] # i, cantidad_elemento = 0 , cola_letras.tamanio() # while(i < cantidad_elemento): # dato = cola_letras.atencion() # if(not dato in vocales): # cola_letras.arribo(dato) # i += 1 # cantidad_elemento = 0 # while(cantidad_elemento < cola_letras.tamanio()): # dato = cola_letras.mover_final() # print(dato) # cantidad_elemento =+ 1 # Ejercicio 2 # from pila import Pila # datos = Cola() # datos_aux = Pila() # for i in range (0, 10): # num = randint(0, 100) # datos.arribo(num) # print(num) # print () # while(not datos.cola_vacia()): # datos_aux.apilar(datos.atencion()) # while (not datos_aux.pila_vacia()): # datos.arribo(datos_aux.desapilar()) # cantidad_elemento = 0 # while(cantidad_elemento < datos.tamanio()): # dato = datos.mover_final() # print(dato) # cantidad_elemento += 1 # Ejercicio 4 def es_primo(num): for n in range(2, num): if num % n == 0: return False return True datos_cola = Cola() for i in range (0, 10): num = randint(0, 100) datos_cola.arribo(num) print(num) print () i = 0 cantidad_elemento = datos_cola.tamanio() while(i < cantidad_elemento): numero = datos_cola.atencion() if(es_primo(numero)): datos_cola.arribo(numero) i += 1 cantidad_elemento = 0 while(cantidad_elemento < datos_cola.tamanio()): dato = datos_cola.mover_final() print(dato) cantidad_elemento += 1
#Password Checker print("Welcome to PGO Security Systems") print("*******************************") attempts = 0 while attempts != 3: password = input("Enter your password: ") attempts = attempts + 1 if password == "abcd1234": print("Access Granted") attempts = 3 else: print("password incorrect") if password != "abcd1234": print("You are locked out") input("Press ENTER to exit the program")
#!/usr/bin/python """TODO(prasana): DO NOT SUBMIT without one-line documentation for main. A simple main function TODO(prasana): DO NOT SUBMIT without a detailed description of main. """ import sys # sys.argv import argparse ## for argument parsing def print_str(s): print (str(s)) def fact(n, verbose): if n <= 1: return n else: if verbose: print_str(str(n)+"*"+str(n-1)) return (n*fact(n-1, verbose)) def reverse_file(f): return def revese_str(s): return v def flagHandler(): parser = argparse.ArgumentParser() help_str = "calculate factorial" parser.add_argument("factorial", type=int, help=help_str) parser.add_argument('--verbose', '-v', action='count') args = parser.parse_args() return args def main(argv): cli_args=flagHandler() if cli_args.factorial: f = fact(cli_args.factorial, cli_args.verbose) print_str(f) return ## main loop main(sys.argv)
# Zad. 1 Program do obliczania podatku. """Prosta aplikacja do liczenia należnego podatku z funkcją sprawdzania poprawności wprowadzonych danych""" def tax(): prompt = """Prosta aplikacja do liczenia należnego podatku z funkcją sprawdzania poprawności wprowadzonych danych""" pr1 = 3091 pr2 = 85528 st1 = 0.18 st2 = 0.32 prompt1 = "Podaj jaki masz dochód" print(prompt1) while True: try: bejmy = float(input('zł :')) except ValueError: print('Podałeś niewłaściwe dane. Wpisz kwote.') else: break if pr1 < bejmy < pr2: ciezar = st1 * (bejmy - pr1) print(f"Musisz odprowadzić {round(ciezar, 2)} zł podatku") elif bejmy > pr2: ciezar2 = st1 * (pr2 - pr1) + st2 * (bejmy - pr2) print(f"Musisz odprowadzić {round(ciezar2, 2)} zł podatku") else: print('Jesteś zwolniony z podatku "szczęsciarzu"')
class Dog: def __init__(self, name, age): self.name = name self.age = age def show(self): print(f'hi my name is {self.name} and my age is {self.age}') d = Dog('fred', 15) d1 = Dog('bob', 10) d2 = Dog('blah', 3) d.show() d1.show() d2.show()
def find_missing_element(l1, l2): num = 0 for item in l1 + l2: num ^= item return num print(find_missing_element([1,2,3,4,5], [1,3,4,5]))
def is_anagram(s1, s2): counts = {} for letter in s1: num = counts.get(letter, 0) + 1 counts[letter] = num for letter in s2: num = counts.get(letter, 0) - 1 counts[letter] = num for letter in counts: if counts[letter] != 0: return False return True print(is_anagram("dog", "god")) print(is_anagram("dog", "gods"))
class Queue: def __init__(self): self.stack1 = [] self.stack2 = [] def offer(self, item): self.stack1.append(item) def poll(self): if not self.stack2: # nothing in the polling stack while self.stack1: # add everything from the first stack self.stack2.append(self.stack1.pop()) return self.stack2.pop() # return the last element in the polling stack q = Queue() for x in range(10): q.offer(x) assert q.poll() == 0 assert q.poll() == 1 assert q.poll() == 2 assert q.poll() == 3 q.offer(15) assert q.poll() == 4 assert q.poll() == 5 assert q.poll() == 6 assert q.poll() == 7 assert q.poll() == 8 assert q.poll() == 9 assert q.poll() == 15
# -*- coding: utf-8 -*- """ Created on Tue Jan 5 01:16:08 2021 @author: Astitva """ import turtle win = turtle.Screen() win.title("Pong") win.bgcolor("black") win.setup(width = 800, height = 600) win.tracer(0) #Paddle A paddle_a = turtle.Turtle() paddle_a.speed(0) paddle_a.shape("square") paddle_a.shapesize(stretch_wid=5, stretch_len=1) paddle_a.color("white") paddle_a.penup() paddle_a.goto(-350,0) #Paddle B paddle_b = turtle.Turtle() paddle_b.speed(0) paddle_b.shape("square") paddle_b.shapesize(stretch_wid=5, stretch_len=1) paddle_b.color("white") paddle_b.penup() paddle_b.goto(350,0) #Ball ball = turtle.Turtle() ball.speed(0) ball.shape("square") ball.color("white") ball.penup() ball.goto(0,0) ball.dx = 0.15 ball.dy = -0.15 #Function def paddle_a_up(): y = paddle_a.ycor() y+=20 paddle_a.sety(y) def paddle_a_down(): y = paddle_a.ycor() y-=20 paddle_a.sety(y) def paddle_b_up(): y = paddle_b.ycor() y+=20 paddle_b.sety(y) def paddle_b_down(): y = paddle_b.ycor() y-=20 paddle_b.sety(y) Ascore = 0 Bscore = 0 #pen pen = turtle.Turtle() pen.speed(0) pen.color("white") pen.penup() pen.hideturtle() pen.goto(0,260) pen.clear() pen.write("Player A: "+ str(Ascore)+" Player B: "+str(Bscore), align="center", font=("Courier",18,"normal")) #Keyboard Binding win.listen() win.onkeypress(paddle_a_up,"w") win.onkeypress(paddle_a_down,"s") win.onkeypress(paddle_b_up,"Up") win.onkeypress(paddle_b_down,"Down") #Main game loop while True: win.update() #Move ball ball.setx(ball.xcor()+ball.dx) ball.sety(ball.ycor()+ball.dy) #Border checks if ball.ycor() > 290: ball.sety(290) ball.dy*=-1 if ball.ycor() < -290: ball.sety(-290) ball.dy*=-1 if ball.xcor() > 390: ball.goto(0,0) ball.dx*=-1 Ascore +=1 pen.clear() pen.write("Player A: "+ str(Ascore)+" Player B: "+str(Bscore), align="center", font=("Courier",18,"normal")) if ball.xcor() < -390: ball.goto(0,0) ball.dx*=-1 Bscore+=1 pen.clear() pen.write("Player A: "+ str(Ascore)+" Player B: "+str(Bscore), align="center", font=("Courier",18,"normal")) #paddle hit if (ball.xcor() >340) and (ball.xcor()<350) and (ball.ycor()<(paddle_b.ycor()+40)) and (ball.ycor()> (paddle_b.ycor()-40)): ball.setx(340) ball.dx*=-1 if ball.dx <0: ball.dx-=0.02 else: ball.dx+=0.02 if ball.dy <0: ball.dy-=0.02 else: ball.dy+=0.02 #print(ball.dx,ball.dy) if (ball.xcor() < -340) and (ball.xcor()>-350) and (ball.ycor()<(paddle_a.ycor()+40)) and (ball.ycor()> (paddle_a.ycor()-40)): ball.setx(-340) ball.dx*=-1 if ball.dx <0: ball.dx-=0.02 else: ball.dx+=0.02 if ball.dy <0: ball.dy-=0.02 else: ball.dy+=0.02 #print(ball.dx,ball.dy) #endgame if Ascore== 7 : pen.clear() pen.write("Player A WINS !", align="center", font=("Courier",28,"normal")) turtle.exitonclick() break if Bscore== 7 : pen.clear() pen.write("Player B WINS!", align="center", font=("Courier",28,"normal")) turtle.exitonclick() break
inp = input() flag = False result = "" tmp = "" tmp2 = "" for i in inp: if not flag: if i == "<": flag = True result += tmp[::-1] tmp = "<" elif i == " ": if tmp: result += tmp[::-1] + " " tmp = "" else: tmp += i else: tmp += i if i == ">": flag = False result += tmp tmp = "" if tmp: result += tmp[::-1] print(result)
# expression = input() # neg = False # tmp = "" # answer = 0 # for ex in expression: # if ex == "-": # if "+" in tmp: # if neg: # answer -= sum(list(map(int, tmp.split("+")))) # else: # answer += sum(list(map(int, tmp.split("+")))) # else: # if neg: # answer -= int(tmp) # else: # answer += int(tmp) # tmp = "" # neg = True # else: # tmp += ex # if "+" in tmp: # if neg: # answer -= sum(list(map(int, tmp.split("+")))) # else: # answer += sum(list(map(int, tmp.split("+")))) # else: # if neg: # answer -= int(tmp) # else: # answer += int(tmp) # print(answer) # 수정 ver # split에 반드시 그 기호를 포함할 필요 X => neg변수 필요 X expression = input().split("-") answer = sum(list(map(int, expression[0].split("+")))) for ex in expression[1:]: answer -= sum(list(map(int, ex.split("+")))) print(answer)
import math M,N = map(int, (input().split())) prime = [True for _ in range(N+1)] prime[1] = False for i in range(2, int(math.sqrt(N+1)+1)): if prime[i]: for j in range(i+i, N+1, i): # step i 를 이용해서 배수 제거 ☆ prime[j] = False for i in range(M, N+1): if prime[i]: print(i)
n = int(input('Diga qual e o seu numero?')) a = n - 1 s = n + 1 print('O antecessor do seu numero e:{}\ne o seu numero foi:{}\ne o seu sucessor e :{}'.format(a, n, s))
#m = float(input('digite o seu valor em metros: ')) #c = m * 100 #mm = m * 1000 #print('O seu valor em metros digitado foi de: {} e o seu valor convertidor em centimentros e:{}'.format(m,c)) #print('O seu valor convertidor em milimitros e:{}'.format(mm)) met = float(input('Uma distancia em metro: ')) km = met / 1000 hm = met / 100 dam = met / 10 dm = met * 10 cm = met * 100 mm = met * 1000 print('A sua medida em metros foi de:{}\ne o valor em Km e de:{}\ne o valor em Hm e de:{}\ne o valor em dam e de:{}'.format(met, km, hm,dam)) print('e o valor em dm e de:{}\neo valor em cm e de:{}\neo valor em mm e de:{}'.format(dm, cm, mm))
s = 0 cont = 0 for c in range(1, 7): n = int(input('Digite o {}º valor:'.format(c))) if n % 2 == 0: s += n cont += 1 print('Você Informou {} numeros e a soma dos Pares foi {}'.format(cont, s)) s = 0 cont = 0 for c in range(1, 7): n = int(input('Digite o {}º valor:'.format(c))) if n % 2 == 1: s += n cont += 1 print('Você Informou {} numeros e a soma dos Impares foi {}'.format(cont, s))
print('-' * 15) print('LOJA DO PAULO') print('-' * 15) total = totmil = menor = cont = 0 barato = '' while True: prod = str(input('Nome do Produto: ')) prec = float(input('Preço: R$ ')) cont += 1 total += prec if prec > 1000: totmil += 1 if cont == 1 or prec < menor: menor = prec barato = prod '''else: if prec < menor: menor = prec barato = prod''' resp = ' ' while resp not in 'SN': resp = str(input('Quer continuar? [S/N]')).strip().upper()[0] if resp == 'N': break print('{:-^40}'.format('Fim Do Programa')) print(f'O total da compra foi R${total:.2f}') print(f'Temos {totmil} produtos custando mais de R$1000.00') print(f'O produto mais barato foi {barato} que custa R${menor:.2f}')
''' 一个变量等于2000如果他大于1000会打印I'm rich!!不然就会打印I'm not rich!!But I might be later... ''' money = 2000 if money > 1000: print("I'm rich!!") else: print("I'm not rich!!") print("But I might be later...")
from tkinter import * import random tk =Tk() canvas = Canvas(tk,width=400,height=400) canvas.pack() for m in range(0,101): g = ['red', 'pink', 'green','gray'] h = random.randint(0,2) a = random.randint(0, 400) b = random.randint(0, 400) c = random.randint(0, 400) d = random.randint(0, 400) e = random.randint(0, 400) f = random.randint(0, 400) canvas.create_polygon(a, b, c, d, e, f, fill=g[h],outline="black") g = ['red', 'pick', 'green'] tk.mainloop()
''' 创造一个变量他等于5如果这个变量小于10会打印我打得过那些忍者,小于30会打印有点难,不过我能应付如果小于50会打印太多了 ''' ninjas = 5 if ninjas < 10: print('我打得过那些忍者') elif ninjas < 30: print('有点难,不过我能应付') elif ninjas < 50: print('太多了')
import cv2 import imutils # construct a range of colors of our ball, # this sets a minimum and maximum range in HSV space and makes it white # and makes everything else white. This mask is much easier to identify # features in the image greenLower = (73, 91, 52) # (h, s, v) greenUpper = (82, 218, 255) # Note: h (hue) is normally 0 to 359 on the color wheel but OpenCV uses 0 to 179, # s (saturation) is normally 0 to 100 but 255 in OpenCV, # v (value) also is normally 0 to 100 but 255 in OpenCV def test(img): # We want to blur the image do reduce noise to improve the HSV space conversion # https://docs.opencv.org/master/d4/d13/tutorial_py_filtering.html blurred = cv2.GaussianBlur(img, (11, 11), 0) hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV) # create a black and white bitmap (not greyscale) version that shows # pixels that match the color range mask = cv2.inRange(hsv, greenLower, greenUpper) # a series of dilations and erosions # erosions do a 3x3 moving matrix that replaces the center with the minimum mask = cv2.erode(mask, None, iterations=2) # dilations do a 3x3 moving matrix that replaces the center with the maximum mask = cv2.dilate(mask, None, iterations=2) # the above removes any small blobs left in the mask # https://docs.opencv.org/2.4/doc/tutorials/imgproc/erosion_dilatation/erosion_dilatation.html # Now find contours in the mask we created and initialize the current # (x, y) center of the contour # https://docs.opencv.org/3.4/d4/d73/tutorial_py_contours_begin.html cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) for c in cnts: # find the largest contour in the mask, then use # it to compute the minimum enclosing circle and # centroid # minArea = 0 # Does it help to clear this? # c = max(cnts, key=cv2.contourArea) storage = None minArea = cv2.minAreaRect(c) # to find the centroid (center) of the identified blob we # will use the calculated moments where x = m10/m00 and # and y is m01/m00 # https://www.learnopencv.com/find-center-of-blob-centroid-using-opencv-cpp-python/ M = cv2.moments(c) center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"])) # only proceed if the minArea meets a minimum size if minArea > 10: # draw a circle the circle and centroid on the frame, circleColor = (0, 255, 17) # TODO verify, I think it is B, G, R thickness = 2 shift = 0 lineType=8 cv2.rectangle(img, (int(x), int(y)), circleColor, thickness, lineType, shift) # then update the list of tracked points # circleColor = (0, 0, 255) # thickness = -1 # -1 is filled # cv2.circle(frame, center, 5, circleColor, thickness) # convert it to grayscale # gray = mask[:,:,2] # We want to only keep the v channel center = None # only update the trail a contour was found if len(cnts) > 0: # find the largest contour in the mask, then use # it to compute the minimum enclosing circle and # centroid # minArea = 0 # Does it help to clear this? c = max(cnts, key=cv2.contourArea) minArea = cv2.minAreaRect2(c, storage) # to find the centroid (center) of the identified blob we # will use the calculated moments where x = m10/m00 and # and y is m01/m00 # https://www.learnopencv.com/find-center-of-blob-centroid-using-opencv-cpp-python/ M = cv2.moments(c) center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"])) # only proceed if the minArea meets a minimum size if minArea > 10: # draw a circle the circle and centroid on the frame, circleColor = (0, 255, 17) # TODO verify, I think it is B, G, R thickness = 2 shift = 0 lineType=8 cv2.rectangle(img, (int(x), int(y)), circleColor, thickness, lineType, shift) # then update the list of tracked points # circleColor = (0, 0, 255) # thickness = -1 # -1 is filled # cv2.circle(frame, center, 5, circleColor, thickness) return img, center
numbers = [1, 2, 3] print(numbers) # This will print as [1,2,3] # What if you want to print individual numbers without square brackets, unpacking operator is used print(*numbers) # unpacking operator values = [*range(5), *"HELLO"] print(*values) # unpacking operator # We can combine two lists with unpacking operator first = [1, 2] second = [3, 4] values = [*first, "a", *second, "WELCOME"] values = [*first, *second] print(*values) # unpacking operator # We can use unpacking operator to combine dictionaries with ** first = {"x": 1} second = {"x": 10, "y": 3} combined = {**first, **second, "z": 1} print(combined)
from sys import getsizeof # When comprehension is used with tuple, generator object is created and we have to iterate over it # Generator : it doesn't loads all the values in memory values = (x*2 for x in range(100000)) print("gen :", getsizeof(values)) values = [x*2 for x in range(100000)] # It loads all the values in memory print("list :", getsizeof(values))
print ("Hores : ") horas= int( input()) print ("Minuts : ") minutos= int( input()) print ("Segons : ") segundos= int( input()) hora_segundo=horas*3600 minutos_segundo=minutos*60 suma=hora_segundo+minutos_segundo+segundos print(suma)
import re from typing import List, Optional from word2number import w2n from ._custom_types import * from ._languages import Languages, Language class WordsNumbersConverterException(Exception): """Exception thrown when the text representation of the number cannot be converted.""" pass class WordsNumbersConverter: """Class for converting text representation of numbers into their digits representation For czech language it uses custom converting algorithms, which should be enable to convert numbers even in form of "petadvacet". For english it uses external package distributed via PyPI. """ #: Text numbers table for czech language CS = { 'nula': 0, 'jedna': 1, 'jeden': 1, 'dva': 2, 'dvě': 2, 'tři': 3, 'čtyři': 4, 'pět': 5, 'šest': 6, 'sedm': 7, 'osm': 8, 'devět': 9, 'deset': 10, 'jedenáct': 11, 'dvanáct': 12, 'třináct': 13, 'čtrnáct': 14, 'patnáct': 15, 'šestnáct': 16, 'sedmnáct': 17, 'osmnáct': 18, 'devatenáct': 19, 'dvacet': 20, 'třicet': 30, 'čtyřicet': 40, 'padesát': 50, 'šedesát': 60, 'sedmdesát': 70, 'osmdesát': 80, 'devadesát': 90, } #: Text numbers table for english language EN = { 'zero': 0, 'null': 0, # 'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9, 'ten': 10, 'eleven': 11, 'twelve': 12, 'thirteen': 13, 'fourteen': 14, 'fifteen': 15, 'sixteen': 16, 'seventeen': 17, 'eighteen': 18, 'nineteen': 19, 'twenty': 20, 'thirty': 30, 'forty': 40, 'fifty': 50, 'sixty': 60, 'seventy': 70, 'eighty': 80, 'ninety': 90 } #: Regular expression pattern to search any number in string (czech) __CS_words_regex = re.compile(r"\b(" + "|".join(CS.keys()) + r")\b", re.IGNORECASE) #: Regular expression pattern to search any number in string (english) __EN_words_regex = re.compile(r"\b(" + "|".join(EN.keys()) + r")\b", re.IGNORECASE) @staticmethod def contains_text_numbers(sentence: str, language: Language) -> bool: """Verifies whenever the sentence contains any text-represented number It searches via regex for any word which should be indicating there is some number. It does not check any validity of the number. :param sentence: Sentence to search number in :param language: Language of the sentence :return: Bool whenever it contains any number """ if language == Languages.CS and WordsNumbersConverter.__CS_words_regex.search(sentence): return True elif language == Languages.EN and WordsNumbersConverter.__EN_words_regex.search(sentence): return True return False @staticmethod def convert(phrase: List[str], language: Language) -> Optional[Number]: """Convert text-represented numbers into digits Based on list of words on input it construct one number which should be digits representation of those words. For czech it uses custom algorithm, for english external package is called. Supports only integers. :param phrase: List of words with numbers as text :param language: Language of the phrase words :return: Number if conversion was successful, None otherwise """ if language == Languages.CS: return WordsNumbersConverter.__cz_converter(phrase) elif language == Languages.EN: return WordsNumbersConverter.__en_converter(phrase) return None @staticmethod def __cz_converter(phrase: List[str]) -> Number: """Converts czech words into single number""" sum = 0 scaling = [Languages.CS.big_numbers_scale[word][0] for word in phrase if word in Languages.CS.big_numbers_scale.keys()] last_number = 0 previous_was_scaling = False for word in phrase: if WordsNumbersConverter.__czech_shortcuts(word): # format "pětadvacet" last_number += WordsNumbersConverter.__czech_shortcuts(word) previous_was_scaling = False elif word in WordsNumbersConverter.CS.keys(): last_number += WordsNumbersConverter.CS[word] previous_was_scaling = False elif word in Languages.CS.big_numbers_scale.keys(): actual_scaling = scaling.pop(0) if previous_was_scaling and last_number > 0: last_number *= Languages.CS.big_numbers_scale[word][0] elif last_number == 0: last_number = Languages.CS.big_numbers_scale[word][0] else: last_number = last_number * Languages.CS.big_numbers_scale[word][0] if scaling and actual_scaling >= max(scaling): sum += last_number last_number = 0 previous_was_scaling = True else: raise WordsNumbersConverterException("invalid word to convert") if last_number > 0: sum += last_number return sum @staticmethod def __czech_shortcuts(phrase: str) -> Number: """Converts number as 'pětadvacet' into digits""" parts = re.search(r"(jedn|dva|tři|čtyři|pět|šest|sedm|osm|devět)a(dvacet|třicet|čtyřicet|padesát|šedesát|sedmdesát|osmdesát|devadesát)", phrase, re.IGNORECASE) if not parts: return False return WordsNumbersConverter.CS[parts.group(2)] + WordsNumbersConverter.CS[parts.group(1) if parts.group(1) != "jedn" else "jedna"] @staticmethod def __en_converter(phrase: List[str]) -> Number: """Convers english phrase using w2n package""" if len(phrase) == 1 and phrase[0] in Languages.EN.big_numbers_scale: return Languages.EN.big_numbers_scale[phrase[0]][0] return w2n.word_to_num(" ".join(phrase))
#!/usr/bin/env python import random def roll(num = 1): return [random.choice([u'\u2680', u'\u2681', u'\u2682', u'\u2683', u'\u2684', u'\u2685']) for x in range(num)] if __name__ == '__main__': import argparse arg_parser = argparse.ArgumentParser() arg_parser.add_argument('-n', default=1, type=int, help='number of dice to roll') arg_parser.add_argument('-t', default=1, type=int, help='number of times to roll N dice') args = arg_parser.parse_args() if args.t >= 1: for num in range(args.t): print ' '.join(roll(args.n))
######################################################################### # Date: 2018/10/02 # file name: 3rd_assignment_main.py # Purpose: this code has been generated for the 4 wheel drive body # moving object to perform the project with line detector # this code is used for the student only ######################################################################### from car import Car import time import constant_setting from multiprocessing import Process from GPIO_PWM_Buzzer_thread import Buzzer class myCar(object): def __init__(self, car_name): self.car = Car(car_name) self.default_degree = constant_setting.turning_rate #기본적으로 꺽어야하는 기본 각도 self.weight = [-4,-2,0,2,4] #검은 색 선의 위치에 따라 곱해야할 배수 self.buzzer = None def drive_parking(self): self.car.drive_parking() # move front when speed is positive, else move back def move(self, speed): speed = int(speed) if speed < 0: self.car.accelerator.go_backward(abs(speed)) else: self.car.accelerator.go_forward(speed) # stop def stop(self): self.car.accelerator.stop() def read_digit(self): return self.car.line_detector.read_digital() def turn(self, degree): min_degree = -35 max_degree = 35 degree = max(min_degree, min(max_degree, degree)) self.car.steering.turn(90 + degree) # ======================================================================= # 3RD_ASSIGNMENT_CODE # Complete the code to perform Third Assignment # ======================================================================= def Sort_line(self,past_degree,speed): print("Sort_line") temp = past_degree - 90 angle = 90 - temp self.car.steering.turn(angle) self.car.accelerator.go_backward(int(speed * 0.7)) #양쪽 모터 값이 speed로 바뀜 while (not self.car.line_detector.is_in_line()): continue time.sleep(0.1) self.car.steering.turn(past_degree) self.car.accelerator.go_forward(speed) #self.set_L_R_speed(past_degree,speed) def set_L_R_speed(self,degree,speed): temp_degree = 90 - degree left_motor_speed = speed right_motor_speed = speed if temp_degree >= 0 : speed_ratio = (1 - temp_degree/50) left_motor_speed = left_motor_speed * speed_ratio elif temp_degree < 0: speed_ratio = (1 + temp_degree/50) right_motor_speed = right_motor_speed * speed_ratio self.car.accelerator.right_wheel.speed = int(left_motor_speed) self.car.accelerator.left_wheel.speed = int(right_motor_speed) def Obstacle_detect(self,Limit_distance): #distance_arr = sorted([self.car.distance_detector.get_distance() for i in range(3)]) #distance = distance_arr[2] distance = self.car.distance_detector.get_distance() # print(distance) if distance < Limit_distance and distance > 0: return True else: return False def avoid_Obastacle(self, speed): print("avoiding") self.move(speed) self.turn(-30) time.sleep(1) while(not self.car.line_detector.is_in_line()): continue self.turn(30) time.sleep(1.6) while(not self.car.line_detector.is_in_line()): continue self.turn(-14) time.sleep(1.9) self.turn(4) self.move(-speed) time.sleep(1.8) self.move(speed) def compute_degree(self,lines): degree = 0 check = False for i in range(len(lines)): if lines[i] == 1: # 맨 처음 1을 만났을 때는 가중치를 곱해줌 if check == False: degree += self.weight[i] * self.default_degree check = True # check_start = False elif check == True: # 그 다음 1을 만났을 때는 기본 각도만큼 더해줌 degree += self.default_degree return check,degree def count_line(self,lines): count = 0 for i in lines: if i == 1: count += 1 return count #T_parking def T_parking(self): print("T_parking") speed = constant_setting.T_parking_speed self.move(speed) self.turn(25) time.sleep(1.5) self.turn(-13) self.move(-speed) time.sleep(1) line_count = 0 while line_count < 3: lines = self.read_digit() line_count = self.count_line(lines) self.turn(20) print("touch line") line_count = 5 while line_count > 2: lines = self.read_digit() line_count = self.count_line(lines) line_count = 0 past_degree = 0 check_out = False while line_count < 4: line_count = 0 lines = self.read_digit() check,degree = self.compute_degree(lines) for i in lines: if i==1: line_count+=1 if(lines == [0,0,0,0,0]): #print(past_degree) if check_out == False: self.turn(past_degree) check_out = True elif(past_degree != degree): past_degree = degree self.turn(-degree) check_out = False self.turn(0) self.move(speed) line_count = 5 while line_count >2 : lines = self.read_digit() line_count = self.count_line(lines) time.sleep(0.05) self.stop() print("T_parking Complete") while(not self.Obstacle_detect(30)): continue while(self.Obstacle_detect(30)): continue time.sleep(1.5) self.turn(5) self.move(speed) while self.car.line_detector.is_in_line(): continue self.turn(-18) time.sleep(1.5) self.turn(24) self.move(-speed) line_count = 0 while line_count < 3: lines = self.read_digit() line_count = self.count_line(lines) print("After T_parking Process Finsish") self.turn(0) self.move(speed) time.sleep(1) def line_tracing(self): print("line_tracing") past_degree = 90 # 처음은 정면 #check_start = True # 만약 센서가 검은색 선 위에 없이 시작했을 경우에도 작동하기 위해 만든 변수 speed = constant_setting.driving_speed self.car.accelerator.go_forward(speed) # 전진 count = 0 count_obstacle = 0 pass_obstacle = 0 check_T = True while (True): if(pass_obstacle<2): if (self.Obstacle_detect(30)): count_obstacle += 1 if (count_obstacle >= 3): self.avoid_Obastacle(constant_setting.evading_speed) pass_obstacle += 1 print(pass_obstacle) else: count_obstacle = 0 status = self.car.line_detector.read_digital() # 5개의 센서값 받아옴 check,degree = self.compute_degree(status) #check는 라인밖으로 나갔는지 degree는 꺽어야할 각도 if pass_obstacle ==1: pass print(status) if check == False: count=0 self.Sort_line(past_degree,speed) elif degree != past_degree: # 전에 꺽은 각도와 다른 경우에만 서보모터에 각도 적용 self.turn(degree) past_degree = degree #self.set_L_R_speed(degree,speed) elif [1,1,1,1,1] == status and count > 4000: break if (status == [1,1,1,0,0] or status == [1,1,1,1,0] or status == [0,1,1,1,0] or status == [1,0,1,1,0] or status == [1,0,1,0,0]) and pass_obstacle==1 and check_T == True: self.T_parking() check_T = False count+=1 self.car.accelerator.stop() def car_startup(self): self.buzzer = Buzzer(self.car.distance_detector.get_distance) p = Process(target = self.buzzer.run) p.start() # implement the assignment code here self.line_tracing() pass if __name__ == "__main__": try: myCar = myCar("CarName") myCar.car_startup() #myCar.car.accelerator.go_forward(60) #myCar.car.accelerator.left_wheel.speed = 30 #while(1): # continue except KeyboardInterrupt: # when the Ctrl+C key has been pressed, # the moving object will be stopped myCar.buzzer.stop() myCar.drive_parking()
''' Conceptualize a sorted half and an unsorted half Initially the sorted half consists of just the first element Iterate along the rest of the array Place it in its appropriate spot in the sorted half the sorted half grows until it encompasses the whole array ''' class Book: def __init__(self, title, author, genre): self.title = title self.author = author self.genre = genre def insertion_sort_books(self, arr_of_books): # sort by the title for i in range(1, len(arr_of_books)): curr_book = arr_of_books[i] j = i # put curr_book in the appropriate spot in our sorted half # loop through our sorted half and find the appropriate spot while j > 0 and curr_book.title < arr_of_books[j - 1].title: # taking the j - 1 book and copying it over to the jth spot # arr_of_books[j], arr_of_books[j - 1] = arr_of_books[j - 1], arr_of_books[j] arr_of_books[j] = arr_of_books[j - 1] j -= 1 # insert the book at the correct position arr_of_books[j] = curr_book return arr_of_books
# -*- coding: utf-8 -*- """ Created on Sun Mar 28 12:10:12 2021 @author: Wilms """ import itertools import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd import pygmo as pg import utils matplotlib.rcParams['text.usetex'] = True # %% Accuracy function def acc(population, x0, f0, target, f_tol = 1e-06, x_tol = 1e-04): """Compute accuracy measures given population, starting values, target values and tolerance Compute varios accuracy measures for assesment of algorithm performance for both function value and decision vector. Absolute deviation, absolute normed deviation, log10 of absolute normed deviation and whether the algorithm converged in f and x. Parameters ---------- population: pygmo population A population class from the pygmo library. x0: array_like Starting values of decision vector of an algorithm. f0: float Function value of the starting decision vector x0. target: list List that contains an array of the optimal decision vector, as the first entry and the function value at the optimum as the second. f_tol: float, default = 1e-06 Deviation from optimum that is considered as acceptable for convergence. x_tol: float, default = 1e-04 Deviation from optimal decision vector that is considered as acceptable for convergence. Returns ------- ser_acc: Series Returns a pandas series with entries for the accuracy measures describe above. Notes ----- The accuracy measures returned are defined as in [1]_ -- math:: f_{acc} = f(\bar{x}) - f(x^*) x_{acc} = ||\bar{x} - x^*|| f_{acc}^n = \frac{f(\bar{x}) - f(x^*)}{f(x^0) - f(x^*)} x_{acc}^n = \frac{||\bar{x} - x^*||}{||x^0 - x^*||} f_{acc}^l = -\log_10(f_{acc}^n) x_{acc}^l = -\log_10(x_{acc}^n) References ---------- .. [1] Vahid Beiranvand, Warren Hare and Yves Lucet, "Best Practice for Comparing Optimization Algorithms", Optimization and Engineering, vol. 18, pp. 815-848, 2017. """ f_best = population.champion_f x_best = population.champion_x # Target is a list supplied by the user f_prime = target[1] x_prime = target[0] # Calculate accuracy measures f_acc_abs = np.abs(f_best - f_prime) f_acc_n = f_acc_abs / (f0 - f_prime) # If accuracy is smaller than 5.25569e-141 set f_acc_l equal to infinity. if f_acc_n <= 5.25569e-141: f_acc_l = np.inf else: f_acc_l = -np.log10(f_acc_n) # Account for multiple global minima if x_prime.ndim == 1: x_acc_abs = np.linalg.norm(x_best - x_prime) x_acc_n = x_acc_abs / np.linalg.norm(x0 - x_prime) else: x_acc_abs = np.linalg.norm(x_best - x_prime, axis = 1).min() x_acc_n = x_acc_abs / np.linalg.norm(x0 - x_prime, axis = 1).min() if x_acc_n <= 5.25569e-141: x_acc_l = np.inf else: x_acc_l = -np.log10(x_acc_n) # Boolean for convergence. Use stopping criteria from pygmo library converged_f = (f_acc_abs < f_tol) converged_x = (x_acc_abs < x_tol) list_acc_index = ["acc_abs_f", "acc_abs_x", "acc_norm_f", "acc_norm_x", "acc_log_f", "acc_log_x", "converged_f", "converged_x"] return pd.Series([f_acc_abs, x_acc_abs, f_acc_n, x_acc_n, f_acc_l, x_acc_l, converged_f, converged_x], index = list_acc_index, dtype = float ) # %% Iterate on problem for single algorithm def get_results_algo_problem( problem, algorithm_name, target, kwargs_algorithm = None, gen = 1000, pop_size = 100, iterations = 100, seed = 2093111, verbosity = 1, f_tol = 1e-06, x_tol = 1e-04 ): """Compute for a given problem and algorithm perofrmance measures for several runs. Due to the stochastic nature of most algorithms it is important to test several starting points. This function computes accuracy measures using the `acc` function. Paramters --------- problem: pygmo problem class A `pygmo` object of the class problem. algorithm_name: str A string referencing an algorithm from the `pygmo` library. target: list List that contains the optimal decision vector, as the first entry and the function value at the optimum as the second. kwargs_algorithm: dictionary, default = None Keywords that are passed to the `pygmo` algorithm class to define the solver. gen: int, default = 1000 The number of generations a population is evolved before the process is stopped. pop_size: int, default = 100 The number of individuals in a generation. Every individual has a decision vector and a fitness value which is the function evaluated at the decision vector. iterations: int, default = 100 The number of experiments that is run. seed: int, default = 2093111 For reproducability a seed is set to generate populations. The number of seeds used equals the number of iterations. The seed for iteration one is equal to the input. The numer is then progressing with each iteration. verbosity: int, default = 1 The number of generations for which a log entry is added. The value of 1 implies an entry every generation. While a value of x > 1 adds an entry every x generations. f_tol: float, default = 1e-06 Deviation from optimum that is considered as acceptable for convergence. x_tol: float, default = 1e-04 Deviation from optimal decision vector that is considered as acceptable for convergence. Returns ------- df_acc: DataFrame A pandas dataframe with accuracy measures computed by the `acc` function. Each row is one iteration. Columns for identification are given as well. df_logs: DataFrame A pandas dataframe containing log entries and accuracy measures. Each row is one generation for a given iteration. Columns for identification are given as well. Notes ----- This function builds on the applications provided by the `pygmo` library [1]_. Custom problems and algorithms can be easily added to `pygmo` and then used for benchmarking exercises. References ---------- .. [1] Francesco Biscani and Dario Izzo, "A parallel global multiobjective framework for optimization: pagmo", Journal of Open Source Software, vol. 5, p. 2339, 2020. """ list_acc = list() list_logs = list() for iter in range(iterations): # Generate a population that with size equal pop_size population = pg.population(problem, size = pop_size, seed = seed + iter) # Multiple starting points. Use best x0 at the starting point. x0 = population.champion_x f0 = population.champion_f if algorithm_name == "mbh": if not problem.has_gradient(): kwargs_algorithm["algo"] = pg.nlopt("neldermead") if (problem.get_nc() > 0): kwargs_algorithm["algo"] = pg.nlopt("slsqp") algorithm = pg.algorithm(getattr(pg, algorithm_name)(seed = seed + iter, **kwargs_algorithm)) elif algorithm_name == "naive": if problem.has_gradient() and problem.get_nc() == 0: uda = pg.nlopt("lbfgs") elif problem.has_gradient() and problem.get_nc() > 0: uda = pg.nlopt("slsqp") elif not problem.has_gradient() and problem.get_nc() == 0: uda = pg.nlopt("neldermead") else: uda = pg.nlopt("cobyla") algorithm = pg.algorithm(uda) elif kwargs_algorithm is None: algorithm = pg.algorithm(getattr(pg, algorithm_name)(gen, seed = seed + iter)) else: algorithm = pg.algorithm(getattr(pg, algorithm_name)(gen, seed = seed + iter, **kwargs_algorithm)) algorithm.set_verbosity(verbosity) population = algorithm.evolve(population) if algorithm_name == "naive": log = algorithm.extract(pg.nlopt).get_log() else: log = algorithm.extract(getattr(pg, algorithm_name)).get_log() # Performance profiles need all observations if algorithm_name == "bee_colony": df_log = pd.DataFrame(log).iloc[:, [0, 1, 3]] elif algorithm_name == "mbh": df_log = pd.DataFrame(log).iloc[:, 0:2] df_log = pd.concat([pd.DataFrame(np.ones(df_log.shape[0])), df_log], axis = 1) elif algorithm_name == "naive": df_log = pd.DataFrame(log).iloc[:, 0:2] df_log[2] = df_log[0] df_log = df_log.iloc[:, [0, 2, 1]] elif len(log) == 0: return None else: df_log = pd.DataFrame(log).iloc[:, 0:3] df_log.columns = ["gen", "f_evals", "best"] # Add column for iteration number and algorithm df_log["iteration"] = iter + 1 df_log["algorithm"] = algorithm_name # A column for relative loss log and negative log_10 loss # Since the log file, doesn't return the best x vector can only compute function loss df_log["acc_norm_f"] = np.abs((df_log["best"] - target[1]) / (f0 - target[1])) # log10 returns -inf if acc_norm_f < ser_acc_norm_f = df_log["acc_norm_f"] ser_acc_log_f = pd.Series(np.repeat(np.inf, len(ser_acc_norm_f))) ser_acc_log_f.loc[ser_acc_norm_f > 5.25569e-141] = -np.log10(ser_acc_norm_f) df_log["acc_log_f"] = ser_acc_log_f df_log["converged_f"] = np.abs(df_log["best"] - target[1]) < f_tol # Append results to lists list_logs.append(df_log) ser_acc = acc(population, x0, f0, target, f_tol, x_tol) ser_acc["iteration"] = iter + 1 ser_acc["algorithm"] = algorithm_name ser_acc["f_eval"] = population.problem.get_fevals() ser_acc["g_eval"] = population.problem.get_gevals() ser_acc["h_eval"] = population.problem.get_hevals() # pygmo doesn't list_acc.append(ser_acc) df_acc = pd.DataFrame(list_acc) df_acc = df_acc.astype({"converged_f": bool, "converged_x": bool}) df_logs = pd.concat(list_logs) return df_acc, df_logs # %% Iterate on problem single algorithm for multiple popsizes def get_results_popsize( problem, algorithm_name, target, kwargs_algorithm = None, gen = 1000, list_pop_size = [20, 50, 100, 250], iterations = 100, seed = 2093111, verbosity = 1, f_tol = 1e-06, x_tol = 1e-04 ): """Compute for a given problem, algorithm and population size perofrmance measures for several runs. Since the population size is a tuning parameter of interest as well this function computes accuracy measures for differing population sizes. Due to the stochastic nature of most algorithms it is important to try out several starting points Paramters --------- problem: pygmo problem class A `pygmo` object of the class problem. algorithm_name: str A string referencing an algorithm from the `pygmo` library. target: list List that contains the optimal decision vector, as the first entry and the function value at the optimum as the second. kwargs_algorithm: dictionary, default = None Keywords that are passed to the `pygmo` algorithm class to define the solver. gen: int, default = 1000 The number of generations a population is evolved before the process is stopped. list_pop_size: list, default = [20, 50, 100, 250] List with the number of individuals in a generation. Every individual has a decision vector and a fitness value which is the function evaluated at the decision vector. iterations: int, default = 100 The number of experiments that is run. seed: int, default = 2093111 For reproducability a seed is set to generate populations. The number of seeds used equals the number of iterations. The seed for iteration one is equal to the input. The numer is then progressing with each iteration. verbosity: int, default = 1 The number of generations for which a log entry is added. The value of 1 implies an entry every generation. While a value of x > 1 adds an entry every x generations. f_tol: float, default = 1e-06 Deviation from optimum that is considered as acceptable for convergence. x_tol: float, default = 1e-04 Deviation from optimal decision vector that is considered as acceptable for convergence. Returns ------- df_acc: DataFrame A pandas dataframe with accuracy measures computed by the `acc` function. Each row is one iteration. Columns for identification are given as well. df_logs: DataFrame A pandas dataframe containing log entries and accuracy measures. Each row is one generation for a given iteration. Columns for identification are given as well. Notes ----- This function builds on the applications provided by the `pygmo` library [1]_. Custom problems and algorithms can be easily added to `pygmo` and then used for benchmarking exercises. References ---------- .. [1] Francesco Biscani and Dario Izzo, "A parallel global multiobjective framework for optimization: pagmo", Journal of Open Source Software, vol. 5, p. 2339, 2020. """ list_acc_popsize = list() list_logs_popsize = list() for pop_size in list_pop_size: # Store in differing df_acc, df_logs = get_results_algo_problem( problem, algorithm_name, target, kwargs_algorithm, gen, pop_size, iterations, seed, verbosity, f_tol, x_tol ) # Set popsize as variable df_acc["pop_size"] = pop_size df_logs["pop_size"] = pop_size list_acc_popsize.append(df_acc) list_logs_popsize.append(df_logs) df_acc_popsize = pd.concat(list_acc_popsize) df_logs_popsize = pd.concat(list_logs_popsize) return df_acc_popsize, df_logs_popsize # %% Benchmark everything def get_results_all( list_problem_names, list_algorithm_names, kwargs_problem = None, kwargs_algorithm = None, gen = 1000, list_pop_size = [20, 50, 100, 250], iterations = 100, seed = 2093111, verbosity = 1, f_tol = 1e-06, x_tol = 1e-04 ): """Compute for a set of given problems, algorithms and population size performance measures for several runs. This function calculates performance measures for differing algorithms on multiple problems with differing population sizes. Due to the stochastic nature of most global optimizers, multiple runs are executed for a given problem algorithm and population size Paramters --------- list_problem_names: list of str A list containing the names of the problems used for benchmarking from the `pygmo` library list_algorithm_names: list of str A list of strings referencing the algorithms to be benchmarked from the `pygmo` library. kwargs_problem: dicitonary, default = None A dictionary with keys as the strings from `list_problem_names`. For every key the value has to be a dictionary of arguments passed to the `pygmo` problem class. Keywords can be dimension or other parameters kwargs_algorithm: dictionary, default = None A dictionary with keys as the strings from `list_algorithm_names`. For every key the value has to be a dictionary of arguments passed to the `pygmo` algorithm class. gen: int, default = 1000 The number of generations a population is evolved before the process is aborted. list_pop_size: list, default = [20, 50, 100, 250] List with the number of individuals in a generation. Every individual has a decision vector and a fitness value which is the function evaluated at the decision vector. iterations: int, default = 100 The number of experiments that is run. seed: int, default = 2093111 For reproducability a seed is set to generate populations. The number of seeds used equals the number of iterations. The seed for iteration one is equal to the input. The numer is then progressing with each iteration. verbosity: int, default = 1 The number of generations for which a log entry is added. The value of 1 implies an entry every generation. While a value of x > 1 adds an entry every x generations. f_tol: float, default = 1e-06 Deviation from optimum that is considered as acceptable for convergence. x_tol: float, default = 1e-04 Deviation from optimal decision vector that is considered as acceptable for convergence. Returns ------- df_acc: DataFrame A pandas dataframe with accuracy measures computed by the `acc` function. Each row is one iteration. Columns for identification are given as well. df_logs: DataFrame A pandas dataframe containing log entries and accuracy measures. Each row is one generation for a given iteration. Columns for identification are given as well. Notes ----- This function builds on the applications provided by the `pygmo` library [1]_. Custom problems and algorithms can be easily added to `pygmo` and then used for benchmarking exercises. References ---------- .. [1] Francesco Biscani and Dario Izzo, "A parallel global multiobjective framework for optimization: pagmo", Journal of Open Source Software, vol. 5, p. 2339, 2020. """ if kwargs_problem is None: kwargs_problem = dict() for problem_name in list_problem_names: kwargs_problem[problem_name] = {"dim": None} if kwargs_algorithm is None: kwargs_algorithm = dict() for algorithm_name in list_algorithm_names: kwargs_algorithm[algorithm_name] = None # Check that a kwarg is present for every problem/algorithm if len(list_problem_names) != len(kwargs_problem): raise KeyError("kwargs_problem has to contain an entry for every problem. If you don't intend \ to supply any values set it equal to None") if len(list_algorithm_names) != len(kwargs_algorithm): raise KeyError("kwargs_algorithm has to contain an entry for every algorithm. If you don't intend \ to supply any values set it equal to None") # Containers for output list_acc_all = list() list_logs_all = list() # Greate a grid of problem and algorithm names over which to loop for problem_name, algorithm_name in itertools.product(list_problem_names, list_algorithm_names): # Define the problem if kwargs_problem[problem_name] is not None: try: problem = pg.problem( getattr(pg, problem_name)(**kwargs_problem[problem_name]) ) except AttributeError: problem = pg.problem( getattr(utils, problem_name)(**kwargs_problem[problem_name]) ) else: try: problem = pg.problem(getattr(pg, problem_name)()) except AttributeError: problem = pg.problem(getattr(utils, problem_name)()) # Get target for given problem target = utils.get_target(problem_name, kwargs_problem[problem_name]) # Apply the get_results_popsize df_acc_problem_algorithm, df_logs_problem_algorithm = \ get_results_popsize( problem, algorithm_name, target, kwargs_algorithm[algorithm_name], gen, list_pop_size, iterations, seed, verbosity ) # Add a column to every dataframe identifying the problem considered df_acc_problem_algorithm["problem"] = problem_name df_logs_problem_algorithm["problem"] = problem_name # Put into list containers list_acc_all.append(df_acc_problem_algorithm) list_logs_all.append(df_logs_problem_algorithm) print("Currently at algorithm {0} and problem {1}".format(algorithm_name, problem_name)) # Put into dataframe format df_acc_all = pd.concat(list_acc_all) df_logs_all = pd.concat(list_logs_all) return df_acc_all, df_logs_all # %% Convergence Plot def convergence_plot( df_logs, problem, algorithm = "all", metric = "median", subplot_kwargs = {"alpha": 0.75, "xscale": "linear", "yscale": "linear"}, fig_kwargs = {"figsize": (21, 10.5), "dpi": 150}, labels = None, label_kwargs = {"fontsize": 19} ): """Calculate a convergence plot from a log file. The convergence plot compares the best function value achieved by different algorithm against the number of function evaluations. The plot compares multipe algorithms aggregated over all iterations on the same problem. Parameters ---------- df_logs: Dataframe A pandas dataframe usually output of get_results_all. The dataframe should contain the columns gen (generation), f_evals (function evaluations), best (best current fitness value), iteration, algorithm, pop_size, problem. problem: str Define for which problem in the log file a plot is drawn. algorithm: list of str, default = "all" Contains the name of the benchmarked algorithms as strings. By default all algorithms contained in the algorithm column of df_logs are used. metric: {"mean", "median"}, default = "median" The statistical estimator applied to df_logs for different iterations. subplot_kwargs: dictionary, default = {"alpha": 0.75, "xscale": "linear", "yscale": "linear"} Keyword arguments that are passed to the add_subplot call. fig_kwargs: dictionary, default = {"figsize": (21, 10.5), "dpi": 150} Keyword arguments that are passed to pyplot figure call. labels: dictionary, default = None Dictionary that passes a label for a given algorithm name. labels_kwargs: dictionary, default = {"fontsize": 19} Sets text properties that control the appearance of the labels. All labels are set simultaneously. Returns ------- fig: matplotlib.fig.Figure A matplotlib figure. How many figures are returned depends on the number of different population sizes in df_logs. Notes ----- This function builds upon the pygmo library. However, every dataframe that fits the structure of df_logs can passed to the function. The convergence plot is ill suited to compare the performance of many optimizers on a large sample of problems. Further, if many differing starting points are computed for an algorithm on a certain problem aggregation is difficult. The mean is prone to outliers and can therefore warp the actual performance of the optimizer. As a substitute the median is chosen. However, this will lead to an increase in function value after all iterations that did converge have terminated. """ df_logs = df_logs.copy() # Need to filter the log dataframe depending on inputs if algorithm != "all": df_logs = df_logs[df_logs["algorithms"].isin(algorithm)] df_logs = df_logs[df_logs["problem"] == problem] # Find the number of subplots. Problems in the rows and popsize in the columns. arr_algorithms = df_logs["algorithm"].unique() arr_pop_size = df_logs["pop_size"].unique() cardinality_pop_size = arr_pop_size.shape[0] if labels is None: labels = dict(zip(arr_algorithms, [x.replace("_", " ").upper() for x in arr_algorithms])) fig, ax = plt.subplots( ncols = cardinality_pop_size, sharex = False, sharey = "row", subplot_kw = subplot_kwargs, **fig_kwargs ) # Only single x-label. Add one big frame fig.add_subplot(111, frameon = False) plt.tick_params(labelcolor = "none", top = False, bottom = False, left = False, right = False) plt.grid(False) plt.xlabel("Function Evaulations", **label_kwargs) plt.ylabel("Function Value", **label_kwargs) for col, algo in itertools.product( range(cardinality_pop_size), arr_algorithms ): df_logs_sub = (df_logs[ (df_logs["pop_size"] == arr_pop_size[col]) & (df_logs["algorithm"] == algo) ]) # Calculate mean, sd, and 95CI for every level of f_eval df_descriptives = (df_logs_sub. groupby("f_evals"). aggregate({"best": {metric}})) df_descriptives.columns = df_descriptives.columns.droplevel() ax[col].plot( df_descriptives.index, df_descriptives[metric], label = labels[algo] ) ax[col].axhline(y = 0, color = "black") ax[col].set_title("Popsize: {}".format(arr_pop_size[col]), **label_kwargs) ax[col].tick_params(labelsize = 16) handles, labels = ax[0].get_legend_handles_labels() plt.legend(handles, labels, loc = "upper right", **label_kwargs) return fig # %% Performance Profile def performance_profile( df_acc, range_tau = 50, problem = "all", algorithm = "all", conv_measure = "f_value", subplot_kwargs = {"alpha": 0.75}, fig_kwargs = {"figsize": (21, 10.5), "dpi": 150}, labels = None, labels_kwargs = {"fontsize": 19} ): """Plot performance profiles given an accuracy data frame. A performance profile shows for what percentage of problems (for a given tolerance) the candidate solution of an algorithm is among the best solvers. Parameters ---------- df_acc: Dataframe A pandas dataframe usually output of get_results_all. The dataframe should contain the columns acc_abs_f (absolute accuracy of f), acc_abs_x (absolute accurcay of x), acc_norm_f (normalized accuracy of f), acc_norm_x (normalized accuracy of x), acc_log_f (log10 of normalized accuracy of f), acc_log_x (log 10 of normalized accuracy of x), converged_f, converged_x, f_evals (function evaluations), iteration, algorithm, pop_size, problem. range_tau, int, default = 50 Gives the range for which a performance profile is plotted. problem: str, default = "all" Define for which problems in df_acc file a plot is drawn. algorithm: list of str, default = "all" Contains the name of the benchmarked algorithms as strings. By default all algorithms contained in the algorithm column of df_acc are used. conv_measure: {"f_value", "x_value"}, default = "f_value" Which measure to consider for deciding on convergence of algortihms subplot_kwargs: dictionary, default = {"alpha": 0.75, "xscale": "linear", "yscale": "linear"} Keyword arguments that are passed to the add_subplot call. fig_kwargs: dictionary, default = {"figsize": (21, 10.5), "dpi": 150} Keyword arguments that are passed to pyplot figure call. labels: dictionary, default = None Dictionary that passes a label for a given algorithm name. labels_kwargs: dictionary, default = {"fontsize": 19} Sets text properties that control the appearance of the labels. All labels are set simultaneously. Returns ------- fig: matplotlib.fig.Figure A matplotlib figure. How many figures are returned depends on the number of different population sizes in df_acc. Notes ----- This function builds upon the pygmo library. However, every dataframe that fits the structure of df_acc as outlined above can be passed to the function. As an example, a ratio value of 10 for example would show us what percentage of a given algorithm achieve convergence in at least ten times the amount of evaluations of the best optimizer. It is important to consider that the best solution found, doesn't have to be the correct global minimum. """ df_acc = df_acc.copy() # Need to filter the log dataframe depending on inputs of problem and algorithm if problem != "all": df_acc = df_acc[df_acc["problem"].isin(problem)] if algorithm != "all": df_acc = df_acc[df_acc["algorithm"].isin(algorithm)] arr_algorithms = df_acc["algorithm"].unique() arr_problems = df_acc["problem"].unique() arr_pop_size = df_acc["pop_size"].unique() cardinality_problems = df_acc["problem"].nunique() cardinality_pop_size = df_acc["pop_size"].nunique() cardinality_iteration = df_acc["iteration"].nunique() df_acc["perf_ratio"] = np.inf df_acc["sum_eval"] = df_acc[["f_eval", "g_eval", "h_eval"]].sum(axis = 1) if conv_measure == "x_value": df_acc["converged"] = df_acc["converged_x"] else: df_acc["converged"] = df_acc["converged_f"] # Need to calculate performance ratio for algo, problem and pop_size for algo, problem, pop in itertools.product( arr_algorithms, arr_problems, arr_pop_size ): str_query = ("problem == '{0}' \ and pop_size == {1} \ and converged == True". format(problem, pop)) fl_min_measure = (df_acc.loc[df_acc.eval(str_query), "sum_eval"]. dropna(). min()) if fl_min_measure is np.nan: pass else: str_query_pr_best = ( str_query + " and algorithm == '{0}' \ and sum_eval == {1}". format(algo, fl_min_measure) ) df_acc.loc[df_acc.eval(str_query_pr_best), "perf_ratio"] = 1 str_query_pr_rest = ( str_query + " and algorithm == '{0}' \ and converged == True". format(algo) ) df_acc.loc[df_acc.eval(str_query_pr_rest), "perf_ratio"] = ( df_acc.loc[df_acc.eval(str_query_pr_rest), "sum_eval"] / fl_min_measure ) # Create a grid for tau and compute performance profile given algo and pop arr_tau = np.arange(1, range_tau + 1) list_perf_profile = list() for algo, pop in itertools.product(arr_algorithms, arr_pop_size): df_perf_profile_sub = pd.DataFrame( data = arr_tau, columns = ["tau"] ) df_perf_profile_sub["algorithm"] = algo df_perf_profile_sub["pop_size"] = pop df_perf_profile_sub["perf_profile"] = np.nan str_query = "algorithm == '{0}' and pop_size == {1}".format(algo, pop) for tau in arr_tau: df_perf_profile_sub.loc[ df_perf_profile_sub["tau"] == tau, "perf_profile"] = ( np.sum(df_acc.loc[df_acc.eval(str_query), "perf_ratio"] < tau) / (cardinality_problems * cardinality_iteration) ) list_perf_profile.append(df_perf_profile_sub) df_perf_profile = pd.concat(list_perf_profile) # Creat one figure for every pop_size if labels is None: labels = dict(zip(arr_algorithms, [x.replace("_", " ").upper() for x in arr_algorithms])) fig, ax = plt.subplots( ncols = cardinality_pop_size, sharex = False, sharey = "row", subplot_kw = subplot_kwargs, **fig_kwargs ) # Only single x-label. Add one big frame fig.add_subplot(111, frameon = False) plt.tick_params(labelcolor = "none", top = False, bottom = False, left = False, right = False) plt.grid(False) plt.xlabel("Ratio", **labels_kwargs) plt.ylabel("Performance Profile", **labels_kwargs) for algo, col in itertools.product(arr_algorithms, range(cardinality_pop_size)): str_query = "algorithm == '{0}' and pop_size == {1}".format(algo, arr_pop_size[col]) df_perf_profile_sub = df_perf_profile.query(str_query) ax[col].step( x = "tau", y = "perf_profile", data = df_perf_profile_sub, label = labels[algo] ) ax[col].axhline(y = 0, color = "black") ax[col].set_title("Popsize: {}".format(arr_pop_size[col]), **labels_kwargs) ax[col].tick_params(labelsize = 16) handles, labels = ax[0].get_legend_handles_labels() plt.legend(handles, labels, loc = "upper right", **labels_kwargs) return fig # %% Accuracy Profile def accuracy_profile( df_acc, range_tau = 15, problem = "all", algorithm = "all", profile_type = "f_value", max_improvement = 15, subplot_kwargs = {"alpha": 0.75}, fig_kwargs = {"figsize": (21, 10.5), "dpi": 150}, labels = None, labels_kwargs = {"fontsize": 19} ): """Plot accuracy profiles given an accuracy data frame. An accuracy profile shows for what proportion of problems an algorithm achieved an accuracy of at least a given value. Parameters ---------- df_acc: Dataframe A pandas dataframe usually output of get_results_all. The dataframe should contain the columns acc_abs_f (absolute accuracy of f), acc_abs_x (absolute accurcay of x), acc_norm_f (normalized accuracy of f), acc_norm_x (normalized accuracy of x), acc_log_f (log10 of normalized accuracy of f), acc_log_x (log 10 of normalized accuracy of x), converged_f, converged_x, f_evals (function evaluations), iteration, algorithm, pop_size, problem. range_tau, int, default = 15 Gives the range for which an accuracy profile is plotted. Can be interpreted as the digits of accuracy achieved problem: str, default = "all" Define for which problems in df_acc file a plot is drawn. algorithm: list of str, default = "all" Contains the name of the benchmarked algorithms as strings. By default all algorithms contained in the algorithm column of df_acc are used. profile_type: {"f_value", "x_value"}, default = "f_value" Determines whether a data profile is drawn for accuracy of the function value or for the decision vector. subplot_kwargs: dictionary, default = {"alpha": 0.75, "xscale": "linear", "yscale": "linear"} Keyword arguments that are passed to the add_subplot call. fig_kwargs: dictionary, default = {"figsize": (21, 10.5), "dpi": 150} Keyword arguments that are passed to pyplot figure call. labels: dictionary, default = None Dictionary that passes a label for a given algorithm name. labels_kwargs: dictionary, default = {"fontsize": 19} Sets text properties that control the appearance of the labels. All labels are set simultaneously. Returns ------- fig: matplotlib.fig.Figure A matplotlib figure. How many figures are returned depends on the number of different population sizes in df_acc. Notes ----- This function builds upon the pygmo library. However, every dataframe that fits the structure of df_acc as outlined above can be passed to the function. This function is only applicable for problems with a known global optimum. """ df_acc = df_acc.copy() # Need to filter the log dataframe depending on inputs of problem and algorithm if problem != "all": df_acc = df_acc[df_acc["problem"].isin(problem)] if algorithm != "all": df_acc = df_acc[df_acc["algorithm"].isin(algorithm)] arr_algorithms = df_acc["algorithm"].unique() arr_pop_size = df_acc["pop_size"].unique() cardinality_problems = df_acc["problem"].nunique() cardinality_pop_size = df_acc["pop_size"].nunique() cardinality_iteration = df_acc["iteration"].nunique() if profile_type == "x_value": df_acc["accuracy"] = df_acc["acc_log_x"] else: df_acc["accuracy"] = df_acc["acc_log_f"] df_acc["gamma"] = max_improvement df_acc.loc[df_acc["accuracy"] <= max_improvement, "gamma"] = ( df_acc.loc[df_acc["accuracy"] <= max_improvement, "accuracy"] ) # Create a grid for tau and compute accuracy profile given algo and pop arr_tau = np.arange(0, range_tau + 1) list_acc_profile = list() for algo, pop in itertools.product(arr_algorithms, arr_pop_size): df_acc_profile_sub = pd.DataFrame( data = arr_tau, columns = ["tau"] ) df_acc_profile_sub["algorithm"] = algo df_acc_profile_sub["pop_size"] = pop df_acc_profile_sub["acc_profile"] = np.nan str_query = "algorithm == '{0}' and pop_size == {1}".format(algo, pop) for tau in arr_tau: df_acc_profile_sub.loc[ df_acc_profile_sub["tau"] == tau, "acc_profile"] = ( np.sum(df_acc.loc[df_acc.eval(str_query), "gamma"] >= tau) / (cardinality_problems * cardinality_iteration) ) list_acc_profile.append(df_acc_profile_sub) df_acc_profile = pd.concat(list_acc_profile) # Creat one figure for every pop_size if labels is None: labels = dict(zip(arr_algorithms, [x.replace("_", " ").upper() for x in arr_algorithms])) fig, ax = plt.subplots( ncols = cardinality_pop_size, sharex = False, sharey = "row", subplot_kw = subplot_kwargs, **fig_kwargs ) # Only single x-label. Add one big frame fig.add_subplot(111, frameon = False) plt.tick_params(labelcolor = "none", top = False, bottom = False, left = False, right = False) plt.grid(False) plt.xlabel("Digits of Accuracy", **labels_kwargs) plt.ylabel("Accuracy Profile", **labels_kwargs) for algo, col in itertools.product(arr_algorithms, range(cardinality_pop_size)): str_query = "algorithm == '{0}' and pop_size == {1}".format(algo, arr_pop_size[col]) df_acc_profile_sub = df_acc_profile.query(str_query) ax[col].step( x = "tau", y = "acc_profile", data = df_acc_profile_sub, label = labels[algo] ) ax[col].axhline(y = 0, color = "black") ax[col].set_title("Popsize: {}".format(arr_pop_size[col]), **labels_kwargs) ax[col].tick_params(labelsize = 16) handles, labels = ax[0].get_legend_handles_labels() plt.legend(handles, labels, loc = "upper right") return fig # %% Data Profile def data_profile( df_acc, problem = "all", algorithm = "all", profile_type = "f_value", perf_measure = 1e-06, problem_kwargs = None, subplot_kwargs = {"alpha": 0.75}, fig_kwargs = {"figsize": (21, 10.5), "dpi": 150}, labels = None, labels_kwargs = {"fontsize": 19} ): """Plot data profiles given an accuracy data frame. A data profile shows what percentage of problems (for a given tolerance) can be solved given a budget of $ k $ function evaluations. Parameters ---------- df_acc: Dataframe A pandas dataframe usually output of get_results_all. The dataframe should contain the columns converged_f and/or converged_x, f_evals (function evaluations), iteration, algorithm, pop_size, problem. problem: str, default = "all" Define for which problems in df_acc file a plot is drawn. algorithm: list of str, default = "all" Contains the name of the benchmarked algorithms as strings. By default all algorithms contained in the algorithm column of df_acc are used. profile_type: {"f_value", "x_value"}, default = "f_value" Determines whether a data profile is drawn for accuracy of the function value or for the decision vector. perf_measure: float, default = 1e-06 Measure that determines whether convergence has been achieved. problem_kwargs: dictionary, default = None Keyword arguments passed to the test function. subplot_kwargs: dictionary, default = {"alpha": 0.75, "xscale": "linear", "yscale": "linear"} Keyword arguments that are passed to the add_subplot call. fig_kwargs: dictionary, default = {"figsize": (21, 10.5), "dpi": 150} Keyword arguments that are passed to pyplot figure call. labels_kwargs: dictionary, default = None Dictionary that passes a label for a given algorithm name. Returns ------- fig: matplotlib.fig.Figure A matplotlib figure. How many figures are returned depends on the number of different population sizes in df_acc. Notes ----- This function builds upon the pygmo library. However, every dataframe that fits the structure of df_acc as outlined above can be passed to the function. To make algorithms that use gradients/hessians and algorithms that don't comparable, the number of gradient and hessian evaluations are considered as well. """ df_acc = df_acc.copy() # Need to filter the log dataframe depending on inputs of problem and algorithm if problem != "all": df_acc = df_acc[df_acc["problem"].isin(problem)] if algorithm != "all": df_acc = df_acc[df_acc["algorithm"].isin(algorithm)] arr_algorithms = df_acc["algorithm"].unique() arr_problems = df_acc["problem"].unique() arr_pop_size = df_acc["pop_size"].unique() cardinality_problems = df_acc["problem"].nunique() cardinality_pop_size = df_acc["pop_size"].nunique() cardinality_iterations = df_acc["iteration"].nunique() df_acc["sum_eval"] = df_acc[["f_eval", "g_eval", "h_eval"]].sum(axis = 1) df_acc["conv_criterion"] = np.nan for problem in arr_problems: if problem_kwargs is None or problem_kwargs[problem] is None: int_dim_problem = 2 elif problem_kwargs[problem]["dim"] is not None: int_dim_problem = problem_kwargs[problem]["dim"] else: int_dim_problem = 2 if profile_type == "f_value": str_query = "problem == '{}' and converged_f == True".format(problem) else: str_query = "problem == '{}' and converged_x == True".format(problem) df_acc.loc[df_acc.eval(str_query), "conv_criterion"] = ( df_acc.loc[df_acc.eval(str_query), "sum_eval"] / (int_dim_problem + 1) ) df_acc["conv_criterion"] = np.ceil(df_acc["conv_criterion"]) list_data_profile = list() # For every pop build a grid of max function evaluations for every algorithm. for pop in arr_pop_size: str_query_pop = "pop_size == {}".format(pop) # conv. criterion still has to be divided by pop size df_acc.loc[df_acc.eval(str_query_pop), "conv_criterion"] = ( df_acc.loc[df_acc.eval(str_query_pop), "conv_criterion"] / pop ) # Gen is equal to f_eval divided by pop int_max_eval = df_acc.loc[df_acc.eval(str_query_pop), "f_eval"].max() / pop arr_eval_range = np.arange(0, int_max_eval + pop, pop) # Repeat this for every algorithm df_eval_algo = pd.DataFrame(np.tile(arr_eval_range, len(arr_algorithms)), columns = ["eval"]) df_eval_algo["algorithm"] = np.repeat(arr_algorithms, len(arr_eval_range)) df_eval_algo["pop_size"] = pop df_eval_algo["data_profile"] = np.nan for algo, evals in itertools.product(arr_algorithms, arr_eval_range): str_query_algo = "pop_size == {0} and algorithm == '{1}'".format(pop, algo) fl_data_profile = (np.sum( df_acc.loc[df_acc.eval(str_query_algo), "conv_criterion"] < evals ) / (cardinality_problems * cardinality_iterations) ) df_eval_algo.loc[ df_eval_algo.eval(str_query_algo + " and eval == {}".format(evals)), "data_profile"] = fl_data_profile list_data_profile.append(df_eval_algo) df_data_profile = pd.concat(list_data_profile) # Creat one figure for every pop_size if labels is None: labels = dict(zip(arr_algorithms, [x.replace("_", " ").upper() for x in arr_algorithms])) fig, ax = plt.subplots( ncols = cardinality_pop_size, sharex = False, sharey = "row", subplot_kw = subplot_kwargs, **fig_kwargs ) # Only single x-label. Add one big frame fig.add_subplot(111, frameon = False) plt.tick_params(labelcolor = "none", top = False, bottom = False, left = False, right = False) plt.grid(False) plt.xlabel("Function Evaulations", **labels_kwargs) plt.ylabel("Data Profile", **labels_kwargs) for algo, col in itertools.product(arr_algorithms, range(cardinality_pop_size)): str_query = "algorithm == '{0}' and pop_size == {1}".format(algo, arr_pop_size[col]) df_data_profile_sub = df_data_profile.query(str_query) ax[col].step( x = "eval", y = "data_profile", data = df_data_profile_sub, label = labels[algo] ) ax[col].axhline(y = 0, color = "black") ax[col].set_title("Popsize: {}".format(arr_pop_size[col]), **labels_kwargs) ax[col].tick_params(labelsize = 16) handles, labels = ax[0].get_legend_handles_labels() plt.legend(handles, labels, loc = "upper right") return fig # %% Descriptive def descriptive(df_acc): """Calculate descriptive measure given a dataframe containing accuracy and evaluation measures For every problem and popuplation size descriptives are computed. If applicable median, mean, quantiles and standard deviation. Further, descriptives are aggregated by population and problem. Parameters ---------- df_acc: DataFrame A pandas dataframe usually output of get_results_all. The dataframe should contain the columns converged_f and/or converged_x, f_evals (function evaluations), iteration, algorithm, pop_size, problem. what: iterable, default = ["eval", "acc", "conv", "competition"] For which variables descriptive metrics should be calculated. Returns ------- df_descriptive: DataFrame A pandas dataframe that contains 25%, 50%, 75% quantile and mean for numeric accuracy measures. Both for accuracy of the decision vector and function value. Metrics are grouped by algorithm, population size and problems. Further descriptives for the number of evaluations are given. For convergence in function value and in x-vector the mean is calculated which is equivalent to the convergence probability. df_comp: DataFrame A pandas dataframe containing the competitive classification proposed by [1]_. Furhter the probability of convergence in function and x-value is added to put competitiveness into perspective. Notes ----- An algorithm is considered competitive by [1]_ if its solving time :math:`T_{algo} \leq 2 T_{min}`. The algorithm is further said to be very competitive if :math:`T_{algo} \leq T_{min}`. Solving time is measured as the sum of function, gradient and hessian evaluations. References ---------- .. [1] Stephen C. Billups, Steven P. Dirkse and Michael C. Ferris, "A Comparison of Large Scale Mixed Complementarity Problem Solvers", Copmutational Optimization and Applications, vol. 7, pp 3-25, 1997. """ # Transform column labels and string columns first df_acc = df_acc.copy() df_acc["eval"] = df_acc[["f_eval", "g_eval", "h_eval"]].sum(axis = 1) df_acc["problem"] = df_acc["problem"].str.title() df_acc["algorithm"] = df_acc["algorithm"].str.upper() dict_mapper = dict( zip( df_acc.columns, [ "Abs. Accuracy f-value", "Abs. Accuracy x-value", "Norm. Accuracy f-value", "Norm. Accuracy x-value", "Log of Norm. Accuracy f-value", "Log of Norm. Accuracy x-value", "Convergence in f-value in %", "Convergence in x-value in %", "Iteration", "Algorithm", "Function Evaluations", "Gradient Evaluations", "Hessian Evaluations", "Population Size", "Problem", "Evaluations" ] ) ) df_acc.rename(dict_mapper, axis = 1, inplace = True) df_descriptives = (df_acc. groupby(["Algorithm", "Population Size", "Problem"]). aggregate( { "Abs. Accuracy f-value": [utils.q25, "median", "mean", utils.q75], "Norm. Accuracy f-value": [utils.q25, "median", "mean", utils.q75], "Log of Norm. Accuracy f-value": [utils.q25, "median", "mean", utils.q75], "Abs. Accuracy x-value": [utils.q25, "median", "mean", utils.q75], "Norm. Accuracy x-value": [utils.q25, "median", "mean", utils.q75], "Log of Norm. Accuracy x-value": [utils.q25, "median", "mean", utils.q75], "Evaluations": [utils.q25, "median", "mean", utils.q75], "Convergence in f-value in %": ["mean"], "Convergence in x-value in %": ["mean"] } ).transpose() ) df_descriptives.index.set_levels(["Mean", "Median", "25%", "75%"], level = 1, inplace = True) df_descriptives.loc[["Convergence in f-value in %", "Convergence in x-value in %"]] = ( np.round( df_descriptives.loc[["Convergence in f-value in %", "Convergence in x-value in %"]] * 100, 2 ) ) arr_algorithms = df_acc["Algorithm"].unique() arr_problems = df_acc["Problem"].unique() arr_pop_size = df_acc["Population Size"].unique() # Calculate total descriptives for algo in arr_algorithms: df_descriptives[algo, "All", "All"] = df_descriptives[algo].mean(axis = 1) for algo, pop in itertools.product(arr_algorithms, arr_pop_size): df_descriptives[algo, pop, "All"] = df_descriptives[algo, pop].mean(axis = 1) for algo, problem in itertools.product(arr_algorithms, arr_problems): df_descriptives[algo, "All", problem] = ( df_descriptives.loc(axis = 1)[algo, :, problem].mean(axis = 1) ) # Calculate competitiveness of algorithm overall # Column evaluations for converged all str_query = "`Convergence in f-value in %` == True or `Convergence in x-value in %` == True" df_compet = ( df_acc. query(str_query). groupby("Algorithm"). aggregate({"Evaluations": "mean"}) ) fl_eval_min = df_compet["Evaluations"].min() df_compet["Competitiveness"] = "Not competitive" df_compet.loc[df_compet["Evaluations"] <= (2 * fl_eval_min), "Competitiveness"] = "Competitive" df_compet.loc[df_compet["Evaluations"] <= (4 / 3 * fl_eval_min), "Competitiveness"] = "Very competitive" # Get Probability of convergence as extra column df_prob_conv = ( df_descriptives. loc[ (["Convergence in f-value in %", "Convergence in x-value in %"]), (slice(None), "All", "All") ]. transpose() ) df_prob_conv.index = df_prob_conv.index.droplevel(["Population Size", "Problem"]) df_prob_conv.columns = df_prob_conv.columns.droplevel(level = 1) # Merge dataframe df_compet = df_compet.merge(df_prob_conv, on = "Algorithm") return df_descriptives, df_compet # %% Define Benchmark class class benchmark: """Run and analyse benchmarking experiments. This class allows comparison of several global optimizers on different problems and for different population sizes and parameters settings. Experiments can be run and analysed using kpis and graphics. Parameters ---------- problem_names: list of str A list containing the names of the problems used for benchmarking from the `pygmo` library algorithm_names: list of str A list of strings referencing the algorithms to be benchmarked from the `pygmo` library. kwargs_problem: dicitonary, default = None A dictionary with keys as the strings from `list_problem_names`. For every key the value has to be a dictionary of arguments passed to the `pygmo` problem class. Keywords can be dimension or other parameters kwargs_algorithm: dictionary, default = None A dictionary with keys as the strings from `list_algorithm_names`. For every key the value has to be a dictionary of arguments passed to the `pygmo` algorithm class. gen: int, default = 1000 The number of generations a population is evolved before the process is aborted. pop_size: list, default = [20, 50, 100, 250] List with the number of individuals in a generation. Every individual has a decision vector and a fitness value which is the function evaluated at the decision vector. iterations: int, default = 100 The number of experiments that is run. seed: int, default = 2093111 For reproducability a seed is set to generate populations. The number of seeds used equals the number of iterations. The seed for iteration one is equal to the input. The numer is then progressing with each iteration. verbosity: int, default = 1 The number of generations for which a log entry is added. The value of 1 implies an entry every generation. While a value of x > 1 adds an entry every x generations. f_tol: float, default = 1e-06 Deviation from optimum that is considered as acceptable for convergence. x_tol: float, default = 1e-04 Deviation from optimal decision vector that is considered as acceptable for convergence. Notes ----- References ---------- Examples -------- """ def __init__( self, problem_names, algorithm_names, kwargs_problem = None, kwargs_algorithm = None, gen = 1000, pop_size = [20, 50, 100, 250], iterations = 100, seed = 2093, verbosity = 1, f_tol = 1e-06, x_tol = 1e-04 ): """Initialize variables to run the benchmarking exercise """ (self.problem_names, self.algorithm_names, self.kwargs_problem, self.kwargs_algorithm, self.gen, self.pop_size, self.iterations, self.seed, self.verbosity, self.f_tol, self.x_tol, self.accuracy, self.logs, self.descriptive, self.competition ) = ( problem_names, algorithm_names, kwargs_problem, kwargs_algorithm, gen, pop_size, iterations, seed, verbosity, f_tol, x_tol, "Run experiment first!", "Run experiment first!", "Run experiment first!", "Run experiment first!" ) def run_experiment(self): """Compute for a set of given problems, algorithms and population size performance measures for several runs. This function calculates performance measures for differing algorithms on multiple problems with differing population sizes. Due to the stochastic nature of most global optimizers, multiple runs are executed for a given problem algorithm and population size. Parameters are passed directly from the class to the method. By changing an instance you can change the experiment. Notes ----- This function builds on the applications provided by the `pygmo` library [1]_. Custom problems and algorithms can be easily added to `pygmo` and then used for benchmarking exercises. References ---------- .. [1] Francesco Biscani and Dario Izzo, "A parallel global multiobjective framework for optimization: pagmo", Journal of Open Source Software, vol. 5, p. 2339, 2020. """ self.accuracy, self.logs = get_results_all( list_problem_names = self.problem_names, list_algorithm_names = self.algorithm_names, kwargs_problem = self.kwargs_problem, kwargs_algorithm = self.kwargs_algorithm, gen = self.gen, list_pop_size = self.pop_size, iterations = self.iterations, seed = self.seed, verbosity = self.verbosity, f_tol = self.f_tol, x_tol = self.x_tol ) def get_descriptives(self): """Calculate descriptive measure given a dataframe containing accuracy and evaluation measures For every problem and popuplation size descriptives are computed. If applicable median, mean, quantiles and standard deviation. Further, descriptives are aggregated by population and problem. Parameters are passed directly from the class to the method. By changing an instance you can change the experiment. To use this method execute the method `run_experiment` first. Notes ----- An algorithm is considered competitive by [1]_ if its solving time :math:`T_{algo} \leq 2 T_{min}`. The algorithm is further said to be very competitive if :math:`T_{algo} \leq T_{min}`. Solving time is measured as the sum of function, gradient and hessian evaluations. References ---------- .. [1] Stephen C. Billups, Steven P. Dirkse and Michael C. Ferris, "A Comparison of Large Scale Mixed Complementarity Problem Solvers", Copmutational Optimization and Applications, vol. 7, pp 3-25, 1997. """ self.descriptive, self.competition = descriptive(self.accuracy) def convergence_plot(self, problem, algorithm = "all", metric = "median", subplot_kwargs = {"alpha": 0.75, "xscale": "linear", "yscale": "linear"}, fig_kwargs = {"figsize": (21, 10.5), "dpi": 150}, labels = None, label_kwargs = {"fontsize": 19} ): """Calculate a convergence plot for the log instance. The convergence plot compares the best function value achieved by different algorithms against the number of function evaluations. The convergence is aggregated over all iterations on the same problem. Parameters ---------- problem: str Define for which problem in the log file a plot is drawn. algorithm: list of str, default = "all" Contains the name of the benchmarked algorithms as strings. By default all algorithms contained in the algorithm column of the logs instance are used. subplot_kwargs: dictionary, default = {"alpha": 0.75, "xscale": "linear", "yscale": "linear"} Keyword arguments that are passed to the add_subplot call. fig_kwargs: dictionary, default = {"figsize": (21, 10.5), "dpi": 150} Keyword arguments that are passed to pyplot figure call. labels: dictionary, default = None Dictionary that passes a label for a given algorithm name. labels_kwargs: dictionary, default = {"fontsize": 19} Sets text properties that control the appearance of the labels. All labels are set simultaneously. Returns ------- fig_conv_plot: matplotlib.fig.Figure A matplotlib figure. How many figures are returned depends on the number of different population sizes in the logs instance. Notes ----- The convergence plot is ill suited to compare the performance of many optimizers on a large sample of problems. Further, if many differing starting points are computed for an algorithm on a certain problem aggregation is difficult. The mean is prone to outliers and can therefore warp the actual performance of the optimizer. As a substitute the median is chosen. However, this will lead to an increase in function value after all iterations that did converge have terminated. """ fig_conv_plot = convergence_plot( self.logs, problem, algorithm, metric, subplot_kwargs, fig_kwargs, labels, label_kwargs ) return fig_conv_plot def performance_profile(self, range_tau = 50, problem = "all", algorithm = "all", conv_measure = "f_value", subplot_kwargs = {"alpha": 0.75}, fig_kwargs = {"figsize": (21, 10.5), "dpi": 150}, labels = None, labels_kwargs = {"fontsize": 19} ): """Plot performance profiles for the accuracy instance. A performance profile shows for what percentage of problems (for a given tolerance) the candidate solution of an algorithm is among the best solvers. Parameters ---------- range_tau, int, default = 50 Gives the range for which a performance profile is plotted. problem: str, default = "all" Define for which problems in the accuracy instance a plot is drawn. algorithm: list of str, default = "all" Contains the name of the benchmarked algorithms as strings. By default all algorithms contained in the algorithm column of the accuracy instance are used. conv_measure: {"f_value", "x_value"}, default = "f_value" Which measure to consider for deciding on convergence of algortihms subplot_kwargs: dictionary, default = {"alpha": 0.75, "xscale": "linear", "yscale": "linear"} Keyword arguments that are passed to the add_subplot call. fig_kwargs: dictionary, default = {"figsize": (21, 10.5), "dpi": 150} Keyword arguments that are passed to pyplot figure call. labels: dictionary, default = None Dictionary that passes a label for a given algorithm name. labels_kwargs: dictionary, default = {"fontsize": 19} Sets text properties that control the appearance of the labels. All labels are set simultaneously. Returns ------- fig_perf_profile: matplotlib.fig.Figure A matplotlib figure. How many figures are returned depends on the number of different population sizes in df_acc. Notes ----- As an example, a ratio value of 10 for example would show us what percentage of a given algorithm achieve convergence in at least ten times the amount of evaluations of the best optimizer. It is important to consider that the best solution found, doesn't have to be the correct global minimum. """ fig_perf_profile = performance_profile( self.accuracy, range_tau, problem, algorithm, conv_measure, subplot_kwargs, fig_kwargs, labels, labels_kwargs ) return fig_perf_profile def accuracy_profile(self, range_tau = 15, problem = "all", algorithm = "all", profile_type = "f_value", max_improvement = 15, subplot_kwargs = {"alpha": 0.75}, fig_kwargs = {"figsize": (21, 10.5), "dpi": 150}, labels = None, labels_kwargs = {"fontsize": 19} ): """Plot accuracy profiles for the accuracy instance. An accuracy profile shows for what proportion of problems an algorithm achieved an accuracy of at least a given value. Parameters ---------- range_tau, int, default = 50 Gives the range for which an accuracy profile is plotted. Can be interpreted as the digits of accuracy achieved problem: str, default = "all" Define for which problems in the accuracy file a plot is drawn. algorithm: list of str, default = "all" Contains the name of the benchmarked algorithms as strings. By default all algorithms contained in the algorithm column of the accuracy instance are used. profile_type: {"f_value", "x_value"}, default = "f_value" Determines whether a data profile is drawn for accuracy of the function value or for the decision vector. subplot_kwargs: dictionary, default = {"alpha": 0.75, "xscale": "linear", "yscale": "linear"} Keyword arguments that are passed to the add_subplot call. fig_kwargs: dictionary, default = {"figsize": (21, 10.5), "dpi": 150} Keyword arguments that are passed to pyplot figure call. labels: dictionary, default = None Dictionary that passes a label for a given algorithm name. labels_kwargs: dictionary, default = {"fontsize": 19} Sets text properties that control the appearance of the labels. All labels are set simultaneously. Returns ------- fig_acc_profile: matplotlib.fig.Figure A matplotlib figure. How many figures are returned depends on the number of different population sizes in df_acc. Notes ----- This function builds upon the pygmo library. However, every dataframe that fits the structure of df_acc as outlined above can be passed to the function. This function is only applicable for problems with a known global optimum. """ fig_acc_profile = accuracy_profile( self.accuracy, range_tau, problem, algorithm, profile_type, max_improvement, subplot_kwargs, fig_kwargs, labels, labels_kwargs ) return fig_acc_profile def data_profile(self, problem = "all", algorithm = "all", profile_type = "f_value", perf_measure = 1e-06, subplot_kwargs = {"alpha": 0.75}, fig_kwargs = {"figsize": (21, 10.5), "dpi": 150}, labels = None, labels_kwargs = {"fontsize": 19} ): """Plot data profiles given an accuracy instance. A data profile shows what percentage of problems (for a given tolerance) can be solved given a budget of $ k $ function evaluations. Parameters ---------- problem: str, default = "all" Define for which problems in df_acc file a plot is drawn. algorithm: list of str, default = "all" Contains the name of the benchmarked algorithms as strings. By default all algorithms contained in the algorithm column of the accuracy instance are used. profile_type: {"f_value", "x_value"}, default = "f_value" Determines whether a data profile is drawn for accuracy of the function value or for the decision vector. perf_measure: float, default = 1e-06 Measure that determines whether convergence has been achieved. subplot_kwargs: dictionary, default = {"alpha": 0.75, "xscale": "linear", "yscale": "linear"} Keyword arguments that are passed to the add_subplot call. fig_kwargs: dictionary, default = {"figsize": (21, 10.5), "dpi": 150} Keyword arguments that are passed to pyplot figure call. labels_kwargs: dictionary, default = None Dictionary that passes a label for a given algorithm name. Returns ------- fig_data_profile: matplotlib.fig.Figure A matplotlib figure. How many figures are returned depends on the number of different population sizes in df_acc. Notes ----- To make algorithms that use gradients/hessians and algorithms that don't comparable, the number of gradient and hessian evaluations are considered as well. """ fig_data_profile = data_profile(self.accuracy, problem, algorithm, profile_type, perf_measure, self.kwargs_problem, subplot_kwargs, fig_kwargs, labels, labels_kwargs ) return fig_data_profile
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np "Vecteur des temperature (step1) to maillage" def VectorToMatrix(vector,Nr,Nz): a=vector.copy() newMatrix=np.zeros((Nz,Nr)) for i in range(0,Nr): for j in range(0,Nz): pl=i+j*Nr newMatrix[j,i]=a[pl] return newMatrix
# Necessary libraries import random import random from statistics import median # Common functions #import numpy as np #import pandas as pd #import seaborn as sns #import matplotlib.pyplot as plt #from scipy import stats # Class Population class Population(object): def __init__(self, dimensions,activism): assert type(dimensions)==int and dimensions>0,"The first argument is not an acceptable input" assert type(activism)==float and 0.0<activism<=1.0,"The third argument is not an acceptable input" self.dimensions = dimensions self.activism = activism self.members = [] def __str__(self): if self.members == []: return "<0;" + str(self.dimensions) + "-D;" + str(self.activism * 100) + ">" else: med = [] for i in range(self.dimensions): x = [] for j in range(self.size): x.append(j.policies[i]) med.append(median(x)) return "<" + str(self.size) + ";" + str(self.dimensions) + "-D; " + str( self.activism * 100) + ">. The median policy on each dimension are: " + str(med) def get_size(self): return self.size def get_activism(self): return self.size def get_dimensions(self): return self.dimensions def populate(self,size): assert type(size)==int and size>2,"The second argument is not an acceptable input" self.size = size Individual.reset_id() for i in range(self.size): i = Individual(self.dimensions, st_trunc_gauss(0.5)) self.members.append(i) # return self.members def drift(self): return None class Individual(Population): """ The object holds each member of the Population :param: :insta: """ id = 1 def __init__(self, dimensions, involvement,activism, parent1=None, parent2=None): Population.__init__(self, dimensions, activism) self.involvement = involvement self.parent1 = parent1 self.parent2 = parent2 self.policies = [] self.values = [] self.id = Individual.id Individual.id += 1 self.policies, self.values = self.birth() def __str__(self): return "<" + str(self.id) + ":" + str(self.dimensions) + ":" + str(self.involvement) + ":(" + str( self.parent1) + ":" + str(self.parent2) + ")>" def __add__(self, other): return Individual(self.dimensions,self.involvement, st_trunc_gauss(0.5), self, other) def get_involvement(self): return self.involvement def get_parent1(self): return self.parent1 def get_parent2(self): return self.parent2 def get_id(self): return str(self.id).zfill(4) def set_id(self, counter): self.id = counter def reset_id(self): Individual.id = 1 def birth(self): if self.parent1 == None or self.parent2 == None: for i in range(self.dimensions): preference = st_trunc_gauss(0.5) self.policies.append(preference) if random.random() < self.involvement: disutility = st_trunc_gauss(0.75) else: disutility = st_trunc_gauss(0.25) self.values.append(disutility) else: for i in range(self.dimensions): preference = st_trunc_gauss((self.parent1.policies[i] + self.parent2.policies[i]) / 2 + random.random()) self.policies.append(preference) disutility = st_trunc_gauss(0.5) self.values.append(disutility) return self.policies, self.values def update(self): old_id = self.get_id() self = Individual(self.dimensions, self.involvement, self, self) self.set_id(old_id) return self A=Individual(3, 0.9, 0.5) B=Individual(3, 0.9, 0.8) C=A+B C.update()
""" A Python script that will calculate the value of Pi to a set number of decimal places. """ from decimal import Decimal, getcontext import math as m import time as t import colorama from colorama import Fore as f colorama.init() numberofdigits = int(input("Please enter the number of decimal places to calculate Pi to:")) getcontext().prec = numberofdigits start_time = t.time() def calc(n): t = Decimal(0) pi = Decimal(0) deno = Decimal(0) k = 0 for k in range(n): t = (Decimal(-1)**k)*(m.factorial(Decimal(6)*k))*(13591409 + 545140134*k) deno = m.factorial(3*k)*(m.factorial(k)**Decimal(3))*(640320**(3*k)) pi += Decimal(t)/Decimal(deno) pi = pi * Decimal(12)/Decimal(640320**Decimal(1.5)) pi = 1/pi return str(pi) # run the calculation print(calc(1)) print(f.RED + "\nTime taken:", t.time() - start_time)
""" Unit tests provide a way of testing individual components of your program. This will help you with debugging and making sure you don't break your code! Here, we provide some unit tests and a skeleton for a few others. Note that you do not have to follow these exactly, they are designed to help you. What other unit tests might you want to write? - Think about the traceback and writing the output file. - Try to write at least one or two additional tests as you think of them. To run: python align_test.py Make sure align_key.py is located in the same directory, and the test_example.input file is present! """ import unittest from align import * TEST_INPUT_FILE="test_example.input" class TestAlignmentClasses(unittest.TestCase): def test_match_matrix(self): """ Tests match matrix object """ match_matrix = MatchMatrix() match_matrix.set_score("A", "C", 5) self.assertEqual(match_matrix.get_score("A", "C"), 5) def test_score_matrix_score(self): """ Tests score matrix object score set + get methods """ ### FILL IN ### # this should be very similar to test match matrix return def test_score_matrix_pointers(self): """ Tests score matrix object pointer set + get methods """ ### FILL IN ### return def test_param_loading(self): """ Tests AlignmentParameters "load_params_from_file()" function """ align_params = AlignmentParameters() align_params.load_params_from_file(TEST_INPUT_FILE) self.assertEqual(align_params.seq_a, "AATGC") self.assertEqual(align_params.seq_b, "AGGC") self.assertTrue(align_params.global_alignment) self.assertEqual(align_params.dx, 0.1) self.assertEqual(align_params.ex, 0.5) self.assertEqual(align_params.dy, 0.6) self.assertEqual(align_params.ey, 0.3) self.assertEqual(align_params.alphabet_a, "ATGC") self.assertEqual(align_params.alphabet_b, "ATGCX") self.assertEqual(align_params.len_alphabet_a, 4) self.assertEqual(align_params.len_alphabet_b, 5) # test that the match match is set up correctly # if this fails, make sure you are loading the asymmetric matrix properly! match_mat = align_params.match_matrix self.assertEqual(match_mat.get_score("A", "X"), 0.3) self.assertEqual(match_mat.get_score("C", "G"), -0.3) self.assertEqual(match_mat.get_score("G", "C"), 0) def test_update_ix(self): """ Test AlignmentAlgorithm's update Ix """ # configure alignment params align_params = AlignmentParameters() align_params.dy = 1 align_params.ey = 0.5 # create an alignment object align = Align("", "") align.align_params = align_params align.m_matrix = ScoreMatrix("M", 5, 4) align.ix_matrix = ScoreMatrix("Ix", 5, 4) align.m_matrix.set_score(2,2, 3) align.ix_matrix.set_score(2,2, 2.5) # run the method! align.update_ix(3, 2) score = align.ix_matrix.get_score(3,2) self.assertEqual(score, 2) ### FILL IN for checking pointers! ### # note - in this example, it should point to M -AND- Ix # check by hand! def test_update_m(self): """ Test AlignmentAlgorithm's update M """ ### FILL IN ### return def test_update_iy(self): """ Test AlignmentAlgorithm's update Iy """ ### FILL IN ### return def test_traceback_start(self): """ Tests that the traceback finds the correct start Should test local and global alignment! """ return if __name__=='__main__': unittest.main()
#Vérifier si un nombre est premier a,compt=1,0 print('Entrez un nombre : ') numb=int(input) while a<=numb: if numb%a==0: compt+=1 a+=1 else: a+=1 if compt==2: print(numb,'est un nombre premier') else: print(numb,'n\'est pas un nombre premier')
import itertools # declaram un dictionar ca sa tinem scorul scoreboard = {1: 0, 2: 0} # declaram o variabila pentru numarul de jocuri game_count = int(input("How many times do you want to play? Enter a number: ")) # declaram o variabila pentru numarul de miscari game_moves = 0 def win(current_game): def all_same(l): if l.count(l[0]) == len(l) and l[0] != 0: return True else: return False # Horizontal for row in game: print(row) if all_same(row): print(f"Player {row[0]} is the winner horizontally!") # adaugam un punct castigatorului scoreboard[row[0]] += 1 return True # Diagonal diags = [] for col, row in enumerate(reversed(range(len(game)))): diags.append(game[row][col]) if all_same(diags): print(f"Player {diags[0]} is the winner diagonally!") # adaugam un punct castigatorului scoreboard[diags[0]] += 1 return True diags = [] for ix in range(len(game)): diags.append(game[ix][ix]) if all_same(diags): print(f"Player {diags[0]} is the winner diagonally!") # adaugam un punct castigatorului scoreboard[diags[0]] += 1 return True # Vertical for col in range(len(game)): check = [] for row in game: check.append(row[col]) if all_same(check): print(f"Player {check[0]} is the winner vertically!") # adaugam un punct castigatorului scoreboard[check[0]] += 1 return True # verificam daca avem toate miscarile posibile, fara un castigator. # adaugam acest if statement la sfarsitul functiei win(), astfel incat # daca ultima miscare este castigatoare, sa nu fie considerata egalitate if game_moves == game_size * game_size: print("Tie!") return True return False def game_board(game_map, player=0, row=0, column=0, just_display=False): try: if game_map[row][column] != 0: print("This position is occupied! Choose another!") return game_map, False print(" " + " ".join([str(i) for i in range(len(game_map))])) if not just_display: game_map[row][column] = player for count, row in enumerate(game_map): print(count, row) return game_map, True except IndexError as e: print("Error: make sure you input row/column as 0, 1 or 2", e) return game_map, False except Exception as e: print("Something went wrong...", e) return game_map, False play = True players = [1, 2] while play: game_size = int(input("What size game of tic tac toe? ")) game = [[0 for i in range(game_size)] for i in range(game_size)] game_won = False game, _ = game_board(game, just_display=True) player_choice = itertools.cycle([1, 2]) while not game_won: current_player = next(player_choice) print(f"Current player {current_player}") played = False while not played: column_choice = int(input("What column do you want to play? (0, 1, 2): ")) row_choice = int(input("What row do you want to play? (0, 1, 2): ")) game, played = game_board(game, current_player, row_choice, column_choice) # incrementam numarul de miscari game_moves += 1 if win(game): # scadem numarul de jocuri ramase game_count -= 1 game_won = True if game_count: print("The game is over, restarting....") else: # afisam scorul print(f"The score is: \nPlayer 1: {scoreboard[1]} points\nPlayer 2: {scoreboard[2]} points") play = False
def number_of_ways_to_form_coin(coin): """ """ count = 0 for two_pound in xrange(0, 2): if (two_pound * 200) > coin: break for one_pound in xrange(0, 3): if (one_pound * 100) > coin: break for fifty_p in xrange(0, 5): if (fifty_p * 50) > coin: break for twenty_p in xrange(0, 11): if (twenty_p * 20) > coin: break for ten_p in xrange(0, 21): if (ten_p * 10) > coin: break for five_p in xrange(0, 41): if (five_p * 5) > coin: break for two_p in xrange(0, 101): if (two_p * 2) > coin: break for one_p in xrange(0, 201): value = (two_pound * 200) + \ (one_pound * 100) + \ (fifty_p * 50) + \ (twenty_p * 20) + \ (ten_p * 10) + \ (five_p * 5) + \ (two_p * 2) + \ (one_p * 1) if value > coin or value < coin: continue count += 1 return count if __name__ == "__main__": print number_of_ways_to_form_coin(coin=200) # better method, much faster # TODO: solve using dynamic programming method # # def number_of_ways_to_form_coin(): # """ # """ # count = 0 # for two_pound in xrange(201, 0, -200): # 201 to handle >=, not just > decrement case # for one_pound in xrange(two_pound, 0, -100): # for fifty_p in xrange(one_pound, 0, -50): # for twenty_p in xrange(fifty_p, 0, -20): # for ten_p in xrange(twenty_p, 0, -10): # for five_p in xrange(ten_p, 0, -5): # for two_p in xrange(five_p, 0, -2): # count += 1 # # return count # # if __name__ == "__main__": # print number_of_ways_to_form_coin()
POWER = 5 MIN = 0 MAX = 999999 def power_of(n, exp=POWER): r = 1 i = 0 while i < exp: r *= n i += 1 return r def get_sum_of_powers(n): digits = [] while (n > 0): digits.append(n % 10) n /= 10 digits = [power_of(i) for i in digits] r = 0 for i in digits: r += i return r def is_sum_of_powers(n): return get_sum_of_powers(n) == n if __name__ == "__main__": sums = [] for i in range(MIN, MAX + 1): if is_sum_of_powers(i): sums.append(get_sum_of_powers(i)) print sums r = 0 for i in sums: r += i r -= 1 # subtract the 1 as this is not permitted print r
def isNumeratorLonger(num, den): """ """ return len(str(num)) > len(str(den)) def calc(): """ """ num = 3 den = 2 count = 0 i = 1 while i <= 1000: if isNumeratorLonger(num=num, den=den): count += 1 nextNum = num + (den * 2) nextDen = num + den num = nextNum den = nextDen i += 1 return count if __name__ == "__main__": print calc()
def powerOf(n, p): """ """ r = 1 while p > 0: r *= n p -= 1 return r def getDigitalSum(n): """ """ l = ''.join(str(n)) l = [int(x) for x in l] return sum(l) if len(l) > 0 else 0 if __name__ == "__main__": print powerOf(3, 2) print powerOf(3, 3) lower = 1 upper = 99 ans = 0 for i in xrange(lower, upper + 1): for j in xrange(lower, upper + 1): p = powerOf(n=i, p=j) ds = getDigitalSum(n=p) if ds > ans: ans = ds print ans
''' Created on 2017/12/17 @author: kshig ''' for n in range(2, 100): for x in range(2, n): if n % x == 0: print(n, " = ", x, "*", n//x) break else: print(n, "is a prime number!")
#Database of words. class Wordbank(object): def __init__(self, words=[]): self.word_to_index = {"":-1, ".":-1, "?":-2, "!":-3} self.index_to_word = {-1:".", -2:"?", -3:"!"} self.num_words = 0 self.add(words) def __len__(self): return self.num_words def __getitem__(self, i): if type(i) == type(1): return self.index_to_word[i] return self.word_to_index[i] def __setitem__(self, i, j): #TODO delete old entries on overwrite if type(i) == type(1): self.index_to_word[i] = j self.word_to_index[j] = i return self.word_to_index[i] = j self.index_to_word[j] = i return def append(self, word): if word in self.word_to_index: return self.index_to_word[self.num_words] = word self.word_to_index[word] = self.num_words self.num_words += 1 def add(self, words): for word in words: self.append(word) return [self[word] for word in words] """ #test W = Wordbank() W.append("dog") W.append("cat") W.append("parrot") print W["dog"] print W[1] print W[2] W[2] = "ferret" print W[2] print W.word_to_index """
from wheel import Wheel from table import Table from bin_builder import BinBuilder from bet import Bet import sys class Player(object): """Base class for players.""" def __init__(self, table): self.stake = None self.rounds_to_go = sys.maxint self.table = table self.last_outcomes = None # PUBLIC def get_table(self): return self.table def get_stake(self): return self.stake def set_stake(self, budget): """Set the budget of the player.""" self.stake = budget def set_rounds_to_go(self, rounds_to_go): """Set maximum rounds the player will play.""" self.rounds_to_go = rounds_to_go def playing(self): """Returns true while the player is still active.""" return self.rounds_to_go > 0 and self.stake > 0 def place_bets(self, bets): """Updates the Table with the various Bet s. Args: bets: List of bets to be placed on the table. It could be just one bet Returns: True if all bets were placed ok. False if some bets couldn't be placed because run out of stake. """ # if only one bet is passed, put it into a list if type(bets) != list: bets = [bets] # place each bet of the list for bet in bets: # check if player has money to bet if bet.get_amount() <= self.stake: # place bet on table self.table.place_bet(bet) # update stake and rounds to go self.stake -= bet.get_amount() self.rounds_to_go -= 1 else: return False return True def win(self, bet): """Notification from the Game that the Bet was a winner. The amount of money won is available via a the winAmount() method of the Bet. Args: bet: The bet which won. """ # update stake self.stake += bet.win_amount() # remove bet self.table.remove_bet(bet) def lose(self, bet): """Notification from the Game that the Bet was a loser. Args: bet: The bet wich lose.""" # remove bet self.table.remove_bet(bet) def winners(self, outcomes): """This is notification from the Game of all the winning outcomes.""" self.last_outcomes = outcomes def get_outcome(self, outcome_name): """Query a constructed wheel for getting outcome.""" # create Whell wheel = Wheel() return wheel.get_outcome(outcome_name) class Martingale(Player): """Martingale is a Player who places bets in Roulette. This player doubles their bet on every loss and resets their bet to a base amount on each win.""" # DATA BASE_BET = "Black" BASE_AMOUNT = 1 # FIELDS loss_count = 0 bet_multiple = 1 # PUBLIC def place_bets(self): """Create bet and update table with it.""" # create bet bet = Bet(self.BASE_AMOUNT * self.bet_multiple, self.get_outcome(self.BASE_BET)) # update table with bet success = super(Martingale, self).place_bets(bet) # if bet coudn't be placed because no more money, leave and reset if not success: self.set_rounds_to_go(0) self.loss_count = 0 self.bet_multiple = 1 return success def win(self, bet): """Notification from the Game that the Bet was a winner. Reset loss_count and bet_multiple and update stake. Args: bet: The bet which won. """ # reset loss_count and bet_multiple self.loss_count = 0 self.bet_multiple = 1 # update stake and remove bet from table super(Martingale, self).win(bet) def lose(self, bet): """Notification from the Game that the Bet was a loser. Update loss_count, bet_multiple and stake. Args: bet: The bet wich lose.""" # update loss_count and bet_multiple self.loss_count += 1 self.bet_multiple = self.bet_multiple * 2 # update stake and remove bet from table super(Martingale, self).lose(bet) class SevenReds(Martingale): """SevenReds is a Martingale player who places bets in Roulette. This player waits until the wheel has spun red seven times in a row before betting black.""" red_count = 7 def place_bets(self): """If redCount is zero, this places a bet on black, using the bet multiplier.""" # check if there is no more reds to go if self.red_count == 0: # place bets following Martingale method success = super(SevenReds, self).place_bets() if success: self.red_count = 7 def winners(self, outcomes): """This is notification from the Game of all the winning outcomes. If this vector includes red, redCount is decremented. Otherwise, red_count is reset to 7.""" if self.get_outcome("Red") in outcomes: self.red_count -= 1 else: self.red_count = 7 class Passenger57(Player): """Stub subclass to get a player running in order to create Game class. The Passenger57 only bets a fixed amount to black outcome.""" # DATA BASE_BET = "Black" BASE_AMOUNT = 100 # FIELDS stake = 200 # PUBLIC def place_bets(self): """Updates the Table with the various bets.""" # create bet bet = Bet(self.BASE_AMOUNT, self.get_outcome(self.BASE_BET)) # update table with bet super(Passenger57, self).place_bets(bet)
class car(object): def __init__(self, price, speed, fuel, mileage): self.price = price self.speed = speed self.fuel = fuel self.mileage = mileage #self.displayall() if price > 10000: self.tax = .15 else: self.tax = .12 self.displayall() def displayall(self): print "your price is: " + str(self.price) print "your mph are: " + self.speed print "your fuel is: " + self.fuel print "your mileage is: " + self.mileage print "your taxes are: " + str(self.tax) sample1 = car(2000, '35mph', 'FULL', '15MPG') sample2 = car(2000, '5mph', 'NOT FULL', '105MPG') sample3 = car(2000, '15mph', 'KINDA FULL', '95MPG') sample4 = car(2000, '25mph', 'FULL', '25MPG') sample5 = car(2000, '45mph', 'EMPTY', '25MPG') sample6 = car(20000000, '35mph', 'EMPTY', '15MPG')
#!/usr/bin/env python from subprocess import Popen, PIPE import sys #import list_all_cars import get_cars import login import solve_car def solved_file_name(): return "solved_cars" def read_solved_file(): try: solved_file = open(solved_file_name()) solved_list = [line.strip() for line in solved_file.readlines()] solved_file.close() except IOError: solved_list = [] return solved_list def write_solved_file(solved_list): solved_file = open(solved_file_name(), "w") [solved_file.write(car + "\n") for car in solved_list] solved_file.close() if __name__ == '__main__': if len(sys.argv) != 2 and len(sys.argv) != 3: print "Usage: solve_all_cars.py [-r|--reverse] <circuit>" sys.exit() if len(sys.argv) == 3: if sys.argv[1] == "-r" or sys.argv[1] == "--reverse": reverse = True else: print "Invalid option: " + sys.argv[1] sys.exit() circuit = sys.argv[2] else: reverse = False circuit = sys.argv[1] solved_list = sorted(read_solved_file(), key=int) write_solved_file(solved_list) solved_set = set(solved_list) print str(len(solved_list)) + " cars solved" print login.login() cars = map(lambda x: str(x[0]),get_cars.foo({})) #list_all_cars.list_all_cars() if reverse: cars.reverse() for car in cars: if car in solved_set: print car + ": solved" else: print car + ":" if solve_car.solve_car(car, circuit): print "*** SOLVED ***" + "\007" solved_set.add(car) solved_list = sorted(list(solved_set), key=int) write_solved_file(solved_list) print
#selection def selection(arr): # 0부터 n-1까지 반복 for i in range(0, len(arr)-1): #i값을 잡고 min으로 둔 다음 min값을 계속 찾는다 min = i # i+1부터 n까지 반복, 가장 작은 값을 찾아 min에 저장 for j in range(i, len(arr)): if arr[min] > arr[j]: min = j # i번째 인덱스와 제일 작은 값을 swap arr[min], arr[i] = arr[i], arr[min] # main data = [int(x) for x in input("여러개 숫자 입력 : ").strip().split()] print("원본 데이터 : ",data) selection(data) print("정렬 후 데이터 : ",data)
import unittest from typing import cast from monkey import lexer from monkey import obj as objmod from monkey import parser from monkey import evaluator class TestEvaluator(unittest.TestCase): def test_eval_integer_expression(self): tests = [ ("5", 5), ("10", 10), ("-5", -5), ("-10", -10), ("5 + 5 + 5 + 5 - 10", 10), ("2 * 2 * 2 * 2 * 2", 32), ("-50 + 100 + -50", 0), ("5 * 2 + 10", 20), ("5 + 2 * 10", 25), ("20 + 2 * -10", 0), ("50 / 2 * 2 + 10", 60), ("2 * (5 + 10)", 30), ("3 * 3 * 3 + 10", 37), ("3 * (3 * 3) + 10", 37), ("(5 + 10 * 2 + 15 / 3) * 2 + -10", 50), ] for input, expected in tests: with self.subTest(input): evaluated = self._eval(input) self.assert_integer_object(evaluated, expected) def _eval(self, input: str) -> objmod.Object: psr = parser.Parser(lexer.Lexer(input)) program = psr.parse() env = objmod.Environment() return evaluator.eval(program, env) def assert_integer_object(self, obj: objmod.Object, expected: int): self.assertIsInstance(obj, objmod.Integer) result = cast(objmod.Integer, obj) self.assertEqual(result.value, expected) def test_eval_boolean_expression(self): tests = [ ("true", True), ("false", False), ("1 < 2", True), ("1 > 2", False), ("1 < 1", False), ("1 > 1", False), ("1 == 1", True), ("1 != 1", False), ("1 == 2", False), ("1 != 2", True), ("true == true", True), ("false == false", True), ("true == false", False), ("true != false", True), ("false != true", True), ("(1 < 2) == true", True), ("(1 < 2) == false", False), ("(1 > 2) == true", False), ("(1 > 2) == false", True), ] for input, expected in tests: with self.subTest(input): evaluated = self._eval(input) self.assert_boolean_object(evaluated, expected) def assert_boolean_object(self, obj: objmod.Object, expected: bool): self.assertIsInstance(obj, objmod.Boolean) result = cast(objmod.Boolean, obj) self.assertEqual(result.value, expected) def test_bang_operator(self): tests = [ ("!true", False), ("!false", True), ("!5", False), ("!!true", True), ("!!false", False), ("!!5", True), ] for input, expected in tests: with self.subTest(input): evaluated = self._eval(input) self.assert_boolean_object(evaluated, expected) def test_if_else_expression(self): tests = [ ("if (true) { 10 }", 10), ("if (false) { 10 }", None), ("if (1) { 10 }", 10), ("if (1 < 2) { 10 }", 10), ("if (1 > 2) { 10 }", None), ("if (1 > 2) { 10 } else { 20 }", 20), ("if (1 < 2) { 10 } else { 20 }", 10), ] for input, expected in tests: with self.subTest(input): evaluated = self._eval(input) if isinstance(expected, int): self.assert_integer_object(evaluated, expected) else: self.assertIs(evaluated, evaluator.NULL) def test_return_statements(self): tests = [ ("return 10;", 10), ("return 10; 9", 10), ("return 2 * 5; 9", 10), ("9; return 10; 9", 10), ( """ if (10 > 1) { if (10 > 1) { return 10; } return 1; }""", 10, ), ] for input, expected in tests: with self.subTest(input): evaluated = self._eval(input) self.assert_integer_object(evaluated, expected) def test_error_handling(self): tests = [ ("5 + true;", "type mismatch: INTEGER + BOOLEAN"), ("5 + true; 5;", "type mismatch: INTEGER + BOOLEAN"), ("-true", "unknown operator: -BOOLEAN"), ("true + false;", "unknown operator: BOOLEAN + BOOLEAN"), ("5; true + false; 5", "unknown operator: BOOLEAN + BOOLEAN"), ("if (10 > 1) { true + false; }", "unknown operator: BOOLEAN + BOOLEAN"), ( """ if (10 > 1) { if (10 > 1) { return true + false; } return 1; } """, "unknown operator: BOOLEAN + BOOLEAN", ), ("foobar", "identifier not found: foobar") ] for input, expected_message in tests: with self.subTest(input): evaluated = self._eval(input) self.assertIsInstance(evaluated, objmod.Error) err_obj = cast(objmod.Error, evaluated) self.assertEqual(err_obj.message, expected_message) def test_let_statements(self): tests = [ ("let a = 5; a;", 5), ("let a = 5 * 5; a;", 25), ("let a = 5; let b = a; b;", 5), ("let a = 5; let b = a; let c = a + b + 5; c;", 15), ] for input, expected in tests: with self.subTest(input): evaluated = self._eval(input) if isinstance(expected, int): self.assert_integer_object(evaluated, expected) else: self.assertIs(evaluated, evaluator.NULL) def test_function_object(self): input = "fn(x) { x + 2; };" evaluated = self._eval(input) self.assertIsInstance(evaluated, objmod.Function) fn = cast(objmod.Function, evaluated) self.assertEqual(len(fn.parameters), 1) self.assertEqual(str(fn.parameters[0]), "x") self.assertEqual(str(fn.body), "(x + 2)") def test_function_application(self): tests = [ ("let identity = fn(x) { x; }; identity(5);", 5), ("let identity = fn(x) { return x; }; identity(5);", 5), ("let double = fn(x) { x * 2; }; double(5);", 10), ("let add = fn(x, y) { return x + y; }; add(5, 5);", 10), ("let add = fn(x, y) { return x + y; }; add(5 + 5, add(5, 5));", 20), ("fn(x) { x; }(5);", 5), ] for input, expected in tests: with self.subTest(input): evaluated = self._eval(input) self.assert_integer_object(evaluated, expected)
from random import shuffle class Game: def __init__(self): """Return the inital state of the board.""" x = list(range(1, 9)) x.append('X') shuffle(x) self.board = [x[0:3], x[3:6], x[6:]] def terminal_state(self): """Return True if game has ended, False otherwise.""" terminal_board = [[1, 2, 3], [4, 5, 6], [7, 8, 'X']] return True if self.board == terminal_board else False def exec_UP(self): """Execute the move up.""" r, c = self._pos() tmp = self.board[r - 1][c] self.board[r - 1][c] = 'X' self.board[r][c] = tmp def exec_DOWN(self): """Execute the move down.""" r, c = self._pos() tmp = self.board[r + 1][c] self.board[r + 1][c] = 'X' self.board[r][c] = tmp def exec_RIGHT(self): """Execute the move right.""" r, c = self._pos() tmp = self.board[r][c + 1] self.board[r][c + 1] = 'X' self.board[r][c] = tmp def exec_LEFT(self): """Execute the move left.""" r, c = self._pos() tmp = self.board[r][c - 1] self.board[r][c - 1] = 'X' self.board[r][c] = tmp def UP(self): """Returnt he result of the move up.""" r, c = self._pos() tmp = self.board[r - 1][c] b = self.board b[r - 1][c] = 'X' b[r][c] = tmp return b def DOWN(self): """Returnt he result of the move down.""" r, c = self._pos() tmp = self.board[r + 1][c] b = self.board b[r + 1][c] = 'X' b[r][c] = tmp return b def RIGHT(self): """Returnt he result of the move right.""" r, c = self._pos() tmp = self.board[r][c + 1] b = self.board b[r][c + 1] = 'X' b[r][c] = tmp return b def LEFT(self): """Return the result of the move left.""" r, c = self._pos() tmp = self.board[r][c - 1] b = self.board b[r][c - 1] = 'X' b[r][c] = tmp return b def _pos(self): """Return position of player on the board.""" for row in range(0, 3): for column in range(0, 3): if self.board[row][column] == "X": return row, column def available_moves(self): """Return set of available moves.""" row, column = self._pos() moves = set() if row != 2: moves.add('DOWN') if row != 0: moves.add('UP') if column != 0: moves.add('LEFT') if column != 2: moves.add('RIGHT') return moves def __str__(self): return (f""" {self.board[0][0]} || {self.board[0][1]} || {self.board[0][2]} ============ {self.board[1][0]} || {self.board[1][1]} || {self.board[1][2]} ============ {self.board[2][0]} || {self.board[2][1]} || {self.board[2][2]}""")
def parse_json(filename): if not isinstance(filename, str): return 'Filename must be a string' try: with open(filename, 'r') as myfile: line = str(myfile.readlines()) result = 0 temp = "" for key, value in enumerate(line): """ This condition could generate error if first in row is any digit, but not in format of JSON """ if value.isdigit() or value == "-": if key < len(line) - 1 and line[key + 1].isdigit(): temp += line[key] else: temp += line[key] result += int(temp) temp = "" except FileNotFoundError: print('File does not exist') return None except ValueError: print('Wrong format of file') return None return result # print(parse_json('jsonreading.txt')) # 111754
def computegrade(score): if score >= 0.9: grade = 'A' elif score >= 0.8: grade = 'B' elif score >= 0.7: grade = 'C' elif score >= 0.6: grade = 'D' else: grade = 'F' return grade marks = float(input('Enter score: ')) print(f'GRADE: {computegrade(marks)}')
#calculating total number of items and average numCounter = 0 total = 0.0 while True: number = input("Enter a number: ") if number == 'done': break try : num1 = float(number) except: print('Invalid Input') continue numCounter = numCounter+1 total = total + num1 print (f'Total: {total} Number of Items: {numCounter} Average: {total/numCounter}')
def computepay(hour, rate): if hour <= 40: pay = hour * rate else: pay = ((hour - 40) * (1.5 * rate)) + (40 * rate) return pay hours = float(input('Enter Hours: ')) rates = float(input('Enter Rate: ')) print(f'Pay: {computepay(hours, rates)}')
import random import letterfrequencychart alphabet = "abcdefghijklmnopqrstuvwxyz" def make_mono_sub(message): ciphertext = "" new_alphabet = "" message = message.lower() random_letter = random.randint(0,25) while len(new_alphabet) < 26: if alphabet[random_letter] not in new_alphabet: new_alphabet = new_alphabet + alphabet[random_letter] random_letter = random.randint(0, 25) else: random_letter = random.randint(0,25) for le in message: if le in alphabet: messagenum = alphabet.find(le) ciphertext = ciphertext + new_alphabet[messagenum] else: ciphertext = ciphertext + le print (ciphertext) x = letterfrequencychart.frequency_chart(ciphertext) print (x[1]) return [ ciphertext + "\n" + x[0], message + "\nAlphabet used: " + new_alphabet]
# 4. Найти значение минимального элемента списка import random n = int(input("Input list size:\n")) A = [] for i in range(n): A.append(random.randint(0, 99)) print(A) B = set(A) A = list(B) print(A[0])
import random rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) (____) ---.__(___) ''' choice = int(input("What do you choose 0 for rock, for paper or 2 for sciessors")) if choice == 0: print(f"You have choosen\n{rock}") elif choice == 1: print(f"You jave chhosen\n{paper}") elif choice == 2: print(f"You have choosen\n{scissors}") computer_choice = random.randint(0,2) if computer_choice == 0: print(f"Computer has choosen\n{rock}") elif computer_choice == 1: print(f"Computer has chhosen\n{paper}") else: print(f"Computer has choosen\n{scissors}") if choice >= 3: print("Invalid Choice, You lose!") elif choice == 0 and computer_choice == 2: print("You won!") elif computer_choice == 0 and choice == 2: print("You lose!") elif choice > computer_choice: print("You won!") elif choice == computer_choice: print("It's a draw!")
def multiplicationTable(number): for i in range(1, 11): print(number, "x", i, " : ", number * i) number = input("Enter number : ") number = (int)(number) print("Multiplication Table for ", number) multiplicationTable(number)
def compoud_interest(p, r, t): print("Principal Amount : ", p, "INR") print("Rate of Interest : ", r, "%") print("Time Duration :", t, "years") interest = (float)(p) * pow((1 + (float)(r) / 100), (int)(t)) print("Compound interest :", interest) p = input("Enter Principal amount :") r = input("Enter rate of Interest :") t = input("Enter time duration : ") compoud_interest(p, r, t)
def cube(n): temp = (int)(n) sum = 0 while temp != 0: digit = (int)(temp % 10) sum += digit * digit * digit temp = (int)(temp / 10) if (int)(n) == (int)(sum): return True else: return False testcases = input("Enter number of testcases :") t = (int)(testcases) while t > 0: number = input("Enter number : ") if cube(number) == True: print(number, "is an Armstrong Number.") else: print(number, "is not an Armstrong number") t -= 1
import matplotlib.pyplot as plt from matplotlib import style style.use('ggplot') import numpy as np from sklearn.cluster import KMeans from sklearn import preprocessing import pandas as pd ''' Pclass Passenger Class (1 = 1st; 2 = 2nd; 3 = 3rd) survival Survival (0 = No; 1 = Yes) name Name sex Sex age Age sibsp Number of Siblings/Spouses Aboard parch Number of Parents/Children Aboard ticket Ticket Number fare Passenger Fare (British pound) cabin Cabin embarked Port of Embarkation (C = Cherbourg; Q = Queenstown; S = Southampton) boat Lifeboat body Body Identification Number home.dest Home/Destination ''' #Reading Titanic data from the excel and make into an data frame. df = pd.read_excel('titanic.xls') #print(df.head()) #Removing body and name which is irrelevent for the prediction df.drop(['body','name'], 1, inplace=True) #pd.to_numeric(list(df)) #Converting all the values in dataframe to an numeric value df.convert_objects(convert_numeric=True) df.fillna(0, inplace=True) #print(df.head()) #Function for handling non numeric data - def handle_non_numerical_data(df): columns = df.columns.values for column in columns: text_digit_vals = {} def convert_to_int(val): return text_digit_vals[val] if df[column].dtype != np.int64 and df[column].dtype != np.float64: column_contents = df[column].values.tolist() unique_elements = set(column_contents) x = 0 for unique in unique_elements: if unique not in text_digit_vals: text_digit_vals[unique] = x x+=1 #Applying the convert_to_int to all the values in the column df[column] = list(map(convert_to_int, df[column])) # Dictionary for future reference - we can convert numeric value to real value if you want print(text_digit_vals) return df df = handle_non_numerical_data(df) #Dropping the SEX and BOAT for irrelevance(Trail and error - If you find more accuracy, continue with it) #Using dropping for these, I found maximum accuracy. df.drop(['sex','boat'], 1, inplace=True) #Training data without LABEl X = np.array(df.drop(['survived'], 1).astype(float)) #processing the data with additiong of decimals in numeric value to increase accuracy X = preprocessing.scale(X) #Label data - Survived or not y = np.array(df['survived']) #Applying the KMeans algorithm with clustor of 2(survived and non survived) clf = KMeans(n_clusters=2) #Process the model clf.fit(X) correct = 0 for i in range(len(X)): predict_me = np.array(X[i].astype(float)) predict_me = predict_me.reshape(-1, len(predict_me)) prediction = clf.predict(predict_me) if prediction[0] == y[i]: correct += 1 print(correct/len(X))
a = int(input()) b = int(input()) c = int(input()) def add(first,second): summ = first + second return summ s = add(a,b) def subs(the_sum,third): f = the_sum- third return f final = subs(s,c) print(final)
class Article: def __init__(self,title,content,author): self.title = title self.content = content self.author = author def Edit(self, new_content): self.content = new_content def ChangeAuthor(self, new_author): self.author = new_author def Rename(self, new_title): self.title = new_title def ToString(self): print(f'{self.title} - {self.content}:{self.author}') article = input().split(', ') curent_title = article[0] curent_content = article[1] curent_author = article[2] curentobject = Article(curent_content, curent_content, curent_author) n = int(input()) for i in range(n): line = input().split(': ') if line[0] == 'Edit': curentobject.Edit(line[1]) elif line[0] == 'ChangeAuthor': curentobject.ChangeAuthor(line[1]) elif line[0] == 'Rename': curentobject.Rename(line[1]) curentobject.ToString()
passw = input() def Is_Valid(password): valid_length = False two_digits = False only = True digit = 0 let_dig = 0 if len(password) >= 6 and len(password) <= 10: valid_length = True else: print('Password must be between 6 and 10 characters') for i in password: if ((ord(i) >= 48 and ord(i) <= 57) or (ord(i) >= 65 and ord(i) <= 90) or (ord(i) >= 97 and ord(i) <= 122)): let_dig +=1 if let_dig != len(password): only = False if not only: print('Password must consist only of letters and digits') for i in password: if ord(i) >= 48 and ord(i) <= 57: digit += 1 if digit >= 2: two_digits = True else: print('Password must have at least 2 digits') if valid_length and two_digits and only: print('Password is valid.') Is_Valid(passw)
text = input() strength = 0 i = 0 while i < len(text): symbol = text[i] if symbol == '>': strength += int(text[i + 1]) i += 1 continue if strength > 0: text = text[:i] + text[i+1:] i -=1 strength -=1 i +=1 print(text)
import re n = int(input()) for _ in range(n): barcode = input() pattern = "^@[#]+[A-Z][a-zA-Z0-9]{4,}[A-Z]@#+$" matches = re.findall(pattern,barcode) if matches: pb = '(?P<prod>\d)' m = re.findall(pb,barcode) if m: print(f"Product group: {''.join(m)}") else: print(f"Product group: 00") else: print('Invalid barcode')
#Sinartisi Roman def roman(num): #arithmoi numbers = [1000,900,500,400,100,90,50,40,10,9,5,4,1] #Simbola romans = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"] i = 0 res = "" while num > 0: for j in range(num//numbers[i]): res += romans[i] num -= numbers[i] i += 1 print (res) n =input('grapse enan arithmo: ') try: roman(int(n)) except ValueError: print('den einai arihtmos')
# convert file path def make_pythonreadable_windows_path(windows_path = [r'C:\Users\mehedee\Documents']): python_path = '' for character in windows_path: if character == '\\': python_path += '/' else: python_path += character return python_path print(make_pythonreadable_windows_path([r'C:\Users\mehedee\Documents']))
# 1. revarse string using one command a = "ilovepython" print a[::-1] # out: nohtypevoli # 2. last value of list a2 = [1,2,3,4,5,6] a2str = 'abcd' print(a2[-1]) print(a2str[-1]) #out : 6 #d # 3. list to string with separator row = ["1", "bob", "developer", "python"] print(*row,sep='.') #out: 1.bob.developer.python # 4.
# -*- coding: utf-8 -*- # Extracting and Parsing Web Site Data (Python) # prepare for Python version 3x features and functions from __future__ import division, print_function # import packages for web scraping/parsing import requests # functions for interacting with web pages from lxml import html # functions for parsing HTML from bs4 import BeautifulSoup # DOM html manipulation # ----------------------------------------------- # demo using the requests and lxml packages # ----------------------------------------------- # test requests package on the home page for ToutBay web_page = requests.get('http://www.toutbay.com/', auth=('user', 'pass')) # obtain the entire HTML text for the page of interest # show the status of the page... should be 200 (no error) web_page.status_code # show the encoding of the page... should be utf8 web_page.encoding # show the text including all of the HTML tags... lots of tags web_page_text = web_page.text print(web_page_text) # parse the web text using html functions from lxml package # store the text with HTML tree structure web_page_html = html.fromstring(web_page_text) # extract the text within paragraph tags using an lxml XPath query # XPath // selects nodes anywhere in the document p for paragraph tags web_page_content = web_page_html.xpath('//p/text()') # show the resulting text string object print(web_page_content) # has a few all-blank strings print(len(web_page_content)) print(type(web_page_content)) # a list of character strings # ----------------------------------------------------------- # demo of parsing HTML with beautiful soup instead of lxml # ----------------------------------------------------------- my_soup = BeautifulSoup(web_page_text) # note that my_soup is a BeautifulSoup object print(type(my_soup)) # remove JavaScript code from Beautiful Soup page object # using a comprehension approach [x.extract() for x in my_soup.find_all('script')] # gather all the text from the paragraph tags within the object # using another list comprehension soup_content = [x.text for x in my_soup.find_all('p')] # show the resulting text string object print(soup_content) # note absence of all-blank strings print(len(soup_content)) print(type(soup_content)) # a list of character strings # there are carriage return, line feed characters, and spaces # to delete from the text... but we have extracted the essential # content of the toutbay.com home page for further analysis # example of output to a text file import os # access to operating system commands os.getcwd() # shows location of current working directory my_file_object = open('my_file.txt', 'w') # opens file for writing # convert soup_content to a sequence of strings and write to file my_file_object.writelines(str(soup_content)) my_file_object.close() # close file so it can be used by other applications # go to the working directory and locate the file # drag the file into your favorite text editor (e.g. notepad++ on Windows)
#Напишите функцию ask_user(), которая с помощью input() спрашивает пользователя “Как дела?”, пока он не ответит “Хорошо” #Создайте словарь типа "вопрос": "ответ", например: {"Как дела": "Хорошо!", "Что делаешь?": "Программирую"} и так далее #Доработайте ask_user() так, чтобы когда пользователь вводил вопрос который есть в словаре, программа давала ему #соответствующий ответ. Например: #Пользователь: Что делаешь? #Программа: Программирую ask_answer_dict = {"Как дела?": "Хорошо!", "Что делаешь?": "Программирую"} def ask_user(): answer = '' while answer != 'Хорошо': answer = input('Как дела?\n') ask_user() def ask_user_pro(ask_answer_dict): while True: answer = input('Задайте вопрос или попращайтесь, написав Пока:\n') print(ask_answer_dict.get(answer,'Я даже не знаю, что ответить...')) if answer == 'Пока': break ask_user_pro(ask_answer_dict)
""" Write a function that takes in a two-dimensional list (a list that contains lists) and returns a new list which contains only the lists from the original which: 1. were not empty 2. have items that are all of the same type You can assume that the lists inside the list will only contain integers or strings. Also, for this challenge, we are assuming that empty arrays are not homogenous. Also, the resultant lists should be in the same order as the original list and none of the values should be changed. **Example:** Given `[[1, 5, 4], ['a', 3, 5], ['b'], [], ['1', 2, 3]]`, your function should return `[[1, 5, 4], ['b']]`. """ from functools import reduce def filter_homogenous(arrays): # Your code here newArray = [] for array in arrays: print("array: ", array) if len(array) == 0: continue if len(array) == 1: newArray.append(array) continue is_homogenous = True for i in range(len(array) - 1): # while i < len(array) - 1: if type(array[i]) != type(array[i + 1]): is_homogenous = False if is_homogenous: newArray.append(array) print("Added array to newArray", newArray) print("is homogenous: ", is_homogenous) # i += 1 print(newArray) def filter_homogenous_reduce(arrays): return_array = [] for list in arrays: if len(list) < 1: continue homogenous = reduce(type_check, list, list[0]) if homogenous: return_array.append(list) return return_array def type_check(x, y): if type(x) == type(y): return x return False print(filter_homogenous([[1, 5, 4], ['a', 3, 5], ['b'], [], ['1', 2, 3]])) # def filter_homogenous(arrays): # # iterate through the outer list # new_list = [] # for outer_item in arrays: # for inner_item in outer_item: # # iterate through the inner list, check the values # if (inner_item.isinstance(outer_item)): # new_list.append(inner_item) # return new_list
""" Prog: Lab1.py Auth: Oleksii Krutko, IO-z91 Desc: Computer graphics Lab 1. 2020 """ from math import * import graphics as glib import matplotlib.pyplot as plt import turtle def transform_point_perspective(point_original, perspective_center): """ Transforms a 3d point to a 2d using perspective transformation. :param point_original: point in 3d space :param perspective_center: center of perspective in 3d space :return: 2d point """ point = [perspective_center[0] + (point_original[0] - perspective_center[0]) / ( 1 - point_original[2] / perspective_center[2]), perspective_center[1] + (point_original[1] - perspective_center[1]) / ( 1 - point_original[2] / perspective_center[2])] return point class SubWindow(object): """ Represents a sub window in the main 2d window. """ def __init__(self): self.name = '' self.zero_point = (0.0, 0.0) self.width = 0.0 self.height = 0.0 self.x_scale = 1.0 self.y_scale = 1.0 self.x_axis_name = 'X' self.y_axis_name = 'Y' self.title_area_height = 50 class Engine(object): """ Base engine class for simple drawing """ def __init__(self, window_width, window_height, background_color): self.title = 'Engine' self.window_width = window_width self.window_height = window_height self.background_color = background_color # always 4! self._sub_windows_num = 4 self._title_area_height = 50 self.sub_windows = [] for i in range(0, self._sub_windows_num): sub_window = SubWindow() sub_window.name = 'Window ' + str(i + 1) sub_window.width = self.window_width / 2 sub_window.height = (self.window_height - self._title_area_height) / 2 sub_window.zero_point = ((i // 2) * self.window_width / 2, (i % 2) * sub_window.height + self._title_area_height) self.sub_windows.append(sub_window) def setup_sub_window(self, sub_window_number, name, x_axis_name, y_axis_name): """ Sets sub window parameters. :param sub_window_number: sub window id :param name: new title :param x_axis_name: new x axis name :param y_axis_name: new y axis name :return: """ self.sub_windows[sub_window_number - 1].name = name self.sub_windows[sub_window_number - 1].x_axis_name = x_axis_name self.sub_windows[sub_window_number - 1].y_axis_name = y_axis_name def draw_debug_info(self): """ Draws elements that help to debug :return: """ for i in range(1, self._sub_windows_num + 1): self.draw_line(i, ((0.0, 0.0), (self.sub_windows[i - 1].width, 0.0)), 'gray') self.draw_line(i, ((self.sub_windows[i - 1].width, 0.0), (self.sub_windows[i - 1].width, self.sub_windows[i - 1].height)), 'gray') self.draw_line(i, ((self.sub_windows[i - 1].width, self.sub_windows[i - 1].height), (0.0, self.sub_windows[i - 1].height)), 'gray') self.draw_line(i, ((0.0, self.sub_windows[i - 1].height), (0.0, 0.0)), 'gray') def draw_curve(self, sub_window, points, color): """ Draws a curve. :param sub_window: sub window id :param points: set of points of the curve :param color: outline color :return: """ pass def draw_line(self, sub_window, points, color): """ Draws a line :param sub_window: sub window id :param points: points of the line :param color: color to draw with :return: """ pass def draw_polygon(self, sub_window, points, outline_color, fill_color): """ Draws a polygon. :param sub_window: sub window id :param points: points of the polygon :param outline_color: outline color :param fill_color: color to fill with :return: """ pass def draw_text(self, sub_window, text, position): """ Draws text in sub window coords. :param sub_window: sub window id :param text: text to write :param position: position of the text :return: """ pass def draw_text_main(self, text, position): """ Draws text in main window coords. :param text: text to write :param position: position of the text :return: """ pass def draw_titles(self): """ Draws main and sub windows titles. :return: """ self.draw_text_main(self.title, (self.window_width / 2, self._title_area_height / 2)) for i in range(1, self._sub_windows_num + 1): self.draw_text(i, self.sub_windows[i - 1].name, (self.sub_windows[i - 1].width / 2, self.sub_windows[i - 1].title_area_height / 2)) def draw_aux(self): """ Draws auxiliary elements. :return: """ i = 0 while i < len(self.sub_windows): self.draw_line(i, ((0.0, 0.0), (self.window_width / 3, 0.0)), 'gray') self.draw_line(i, ((0.0, -self.window_height / 8), (0.0, self.window_height / 8)), 'gray') self.draw_text(i, 'X', (self.window_width / 3, 20.0)) self.draw_text(i, 'Y', (-20.0, -self.window_height / 8)) i = i + 1 def show(self): """ Performs needed actions to start rendering. :return: """ pass class MathPlotLibEngine(Engine): """ Implements simple drawing using Mathplot lib. """ def __init__(self, window_width, window_height, background_color): super(MathPlotLibEngine, self).__init__(window_width, window_height, background_color) self.__fig, self.__axs = plt.subplots(2, 2) self.__fig.canvas.set_window_title('Matplotlib engine') def setup_sub_window(self, sub_window_number, name, x_axis_name, y_axis_name): super(MathPlotLibEngine, self).setup_sub_window(sub_window_number, name, x_axis_name, y_axis_name) # self.__axs[(sub_window_number - 1) // 2, (sub_window_number - 1) % 2]\ # .axis([0.0, self.window_width, self.window_height, 0.0]) self.__axs[(sub_window_number - 1) // 2, (sub_window_number - 1) % 2].set_title(name) self.__axs[(sub_window_number - 1) // 2, (sub_window_number - 1) % 2].set_aspect('equal') self.__axs[(sub_window_number - 1) // 2, (sub_window_number - 1) % 2].invert_yaxis() def draw_debug_info(self): pass def draw_titles(self): pass def draw_curve(self, sub_window, points, color): x = [] y = [] for point in points: x.append(point[0]) for point in points: y.append(point[1]) self.__axs[(sub_window - 1) // 2, (sub_window - 1) % 2].plot(x, y, color=color) def draw_line(self, sub_window, points, color): self.__axs[(sub_window - 1) // 2, (sub_window - 1) % 2].plot([points[0][0], points[1][0]], [points[0][1], points[1][1]], color=color) def draw_polygon(self, sub_window, points, outline_color, fill_color): x = [] y = [] for point in points: x.append(point[0]) for point in points: y.append(point[1]) self.__axs[(sub_window - 1) // 2, (sub_window - 1) % 2].fill(x, y, facecolor=fill_color, edgecolor=outline_color) def draw_aux(self): pass def show(self): plt.show() class GraphicsEngine(Engine): """ Implements simple drawing using Graphics lib. """ def __init__(self, window_width, window_height, background_color): super(GraphicsEngine, self).__init__(window_width, window_height, background_color) self.title = 'Graphics lib engine' self.win = glib.GraphWin("Lab 1. Task 1", window_width, window_height) self.win.setBackground(background_color) def draw_curve(self, sub_window, points, color): for point in points: p = glib.Point( self.sub_windows[sub_window - 1].zero_point[0] + point[0] * self.sub_windows[sub_window - 1].x_scale, self.sub_windows[sub_window - 1].zero_point[1] + point[1] * self.sub_windows[sub_window - 1].y_scale) p.setOutline(color) p.draw(self.win) def draw_line(self, sub_window, points, color): line = glib.Line( glib.Point(self.sub_windows[sub_window - 1].zero_point[0] + points[0][0], self.sub_windows[sub_window - 1].zero_point[1] + points[0][1]), glib.Point(self.sub_windows[sub_window - 1].zero_point[0] + points[1][0], self.sub_windows[sub_window - 1].zero_point[1] + points[1][1])) line.setOutline(color) line.setWidth(3) line.draw(self.win) def draw_polygon(self, sub_window, points, outline_color, fill_color): poly_points = [] for p in points: poly_points.append(glib.Point(self.sub_windows[sub_window - 1].zero_point[0] + p[0], self.sub_windows[sub_window - 1].zero_point[1] + p[1])) polygon = glib.Polygon(poly_points) polygon.setOutline(outline_color) polygon.setFill(fill_color) polygon.setWidth(3) polygon.draw(self.win) def draw_text(self, sub_window, text, position): label = glib.Text( glib.Point(self.sub_windows[sub_window - 1].zero_point[0] + position[0], self.sub_windows[sub_window - 1].zero_point[1] + position[1]), text) label.draw(self.win) def draw_text_main(self, text, position): label = glib.Text( glib.Point(position[0], position[1]), text) label.draw(self.win) def show(self): self.win.getMouse() self.win.close() class TurtleEngine(Engine): """ Implements simple drawing using Turtle lib. """ def __init__(self, window_width, window_height, background_color): super(TurtleEngine, self).__init__(window_width, window_height, background_color) self.title = 'Turtle lib engine' turtle.screensize(self.window_width, self.window_height) turtle.speed(10) turtle.pensize(3) turtle.radians() turtle.penup() def draw_curve(self, sub_window, points, color): turtle.pencolor(color) turtle.goto( self.sub_windows[sub_window - 1].zero_point[0] + points[0][0] * self.sub_windows[sub_window - 1].x_scale + - self.window_width / 2, self.window_height / 2 - self.sub_windows[sub_window - 1].zero_point[1] - points[0][1] * self.sub_windows[ sub_window - 1].x_scale) turtle.pendown() i = 1 while i < len(points) - 1: turtle.goto( self.sub_windows[sub_window - 1].zero_point[0] + points[i][0] * self.sub_windows[ sub_window - 1].x_scale - self.window_width / 2, self.window_height / 2 - self.sub_windows[sub_window - 1].zero_point[1] - points[i + 1][ 1] * self.sub_windows[sub_window - 1].x_scale) i = i + 1 turtle.penup() def draw_line(self, sub_window, points, color): moved_point_from = [self.sub_windows[sub_window - 1].zero_point[0] + points[0][0] - self.window_width / 2, self.window_height / 2 - self.sub_windows[sub_window - 1].zero_point[1] - points[0][1]] moved_point_to = [self.sub_windows[sub_window - 1].zero_point[0] + points[1][0] - self.window_width / 2, self.window_height / 2 - self.sub_windows[sub_window - 1].zero_point[1] - points[1][1]] length = sqrt((moved_point_to[0] - moved_point_from[0]) * (moved_point_to[0] - moved_point_from[0]) + (moved_point_to[1] - moved_point_from[1]) * (moved_point_to[1] - moved_point_from[1])) angle = acos((moved_point_to[0] - moved_point_from[0]) / length) if moved_point_to[1] < moved_point_from[1]: angle = 2 * pi - angle turtle.goto(moved_point_from[0], moved_point_from[1]) turtle.setheading(0) turtle.pencolor(color) turtle.pendown() turtle.left(angle) turtle.forward(length) turtle.penup() def draw_polygon(self, sub_window, points, outline_color, fill_color): turtle.begin_fill() turtle.fillcolor(fill_color) i = 0 while i < len(points) - 1: self.draw_line(sub_window, [points[i], points[i + 1]], outline_color) i = i + 1 self.draw_line(sub_window, [points[i], points[0]], outline_color) turtle.end_fill() def draw_text(self, sub_window, text, position): turtle.goto(self.sub_windows[sub_window - 1].zero_point[0] + position[0] - self.window_width / 2, self.window_height / 2 - self.sub_windows[sub_window - 1].zero_point[1] - position[1]) turtle.write(text) def draw_text_main(self, text, position): turtle.goto(position[0] - self.window_width / 2, self.window_height / 2 - position[1]) turtle.write(text) def draw_aux(self): i = 0 while i < len(self.sub_windows): self.draw_line(i, ((0.0, 0.0), (self.window_width / 3, 0.0)), 'gray') self.draw_line(i, ((0.0, -self.window_height / 8), (0.0, self.window_height / 8)), 'gray') self.draw_text(i, 'X', (self.window_width / 3, 20.0)) self.draw_text(i, 'Y', (-20.0, -self.window_height / 8)) i = i + 1 def draw_task_one(engine): """ Lab 1. Task 1. Draw squares and triangles using linear perspective transformation. :param engine: graphics engine to render with :return: """ engine.setup_sub_window(1, "Triangle - polygon (-30)", "", "") engine.setup_sub_window(2, "Triangle - polygon (-100)", "", "") engine.setup_sub_window(3, "Square - lines (-30)", "", "") engine.setup_sub_window(4, "Square - lines (-100)", "", "") engine.draw_debug_info() engine.draw_titles() # shift the zero point and the scale for better visualizing # in the engines that do not support auto scaling. for i in range(0, 4): engine.sub_windows[i].zero_point = (engine.sub_windows[i].zero_point[0] + 100, engine.sub_windows[i].zero_point[1] + 100) engine.sub_windows[i].x_scale = 10 engine.sub_windows[i].y_scale = 10 def draw_figure_two_with_perspective(sub_window_num, perspective_depth, width, height, depth_step, count, inner_color, outer_color): """ Draws squares on given depth levels according given perspective. :param sub_window_num: sub window id :param perspective_depth: z-coord of perspective center point :param width: square side length :param height: square height :param depth_step: depth increment :param count: number of squares :param inner_color: color of inner squares :param outer_color: color of outer squares :return: """ perspective_center = (width / 2, height / 2, perspective_depth) for i in range(0, count): # calc points for single depth level p_top_left = transform_point_perspective((0.0, 0.0, i * depth_step), perspective_center) p_top_right = transform_point_perspective((width, 0.0, i * depth_step), perspective_center) p_bottom_left = transform_point_perspective((0.0, height, i * depth_step), perspective_center) p_bottom_right = transform_point_perspective((width, height, i * depth_step), perspective_center) if i == 0 or i == count - 1: color = outer_color else: color = inner_color # draw using lines engine.draw_line(sub_window_num, [p_top_left, p_top_right], color) engine.draw_line(sub_window_num, [p_top_left, p_bottom_left], color) engine.draw_line(sub_window_num, [p_bottom_left, p_bottom_right], color) engine.draw_line(sub_window_num, [p_top_right, p_bottom_right], color) draw_figure_two_with_perspective(3, -30, 200.0, 200.0, 20.0, 5, 'green', 'blue') draw_figure_two_with_perspective(4, -100, 200.0, 200.0, 20.0, 5, 'green', 'blue') def draw_figure_one_with_perspective(sub_window_num, perspective_depth, width, height, depth_step, count, inner_color, outer_color): """ Draws triangles on given depth levels according given perspective. :param sub_window_num: sub window id :param perspective_depth: z-coord of perspective center point :param width: triangle base length :param height: triangle height :param depth_step: depth increment :param count: number of triangles :param inner_color: color of inner triangles :param outer_color: color of outer triangles :return: """ perspective_center = (width / 2, height / 2, perspective_depth) for i in range(0, count): # calc points for single depth level p_top = transform_point_perspective( (width / 2, 0.0, i * depth_step), perspective_center) p_bottom_left = transform_point_perspective( (0.0, height, i * depth_step), perspective_center) p_bottom_right = transform_point_perspective( (width, height, i * depth_step), perspective_center) if i == 0 or i == count - 1: color = outer_color else: color = inner_color # draw using polygon engine.draw_polygon(sub_window_num, [p_top, p_bottom_left, p_bottom_right], color, glib.color_rgb(255, 255, 190)) draw_figure_one_with_perspective(1, -30, 300.0, 200.0, 20.0, 4, 'green', 'blue') draw_figure_one_with_perspective(2, -100, 300.0, 200.0, 20.0, 4, 'green', 'blue') def draw_task_two(engine): """ Lab 1. Task 2. Draw logo. :param engine: graphics engine to render with :return: """ engine.setup_sub_window(1, "Monochrome-polygon", "", "") engine.setup_sub_window(2, "Monochrome-lines", "", "") engine.setup_sub_window(3, "Color-lines", "", "") engine.setup_sub_window(4, "Color-polygon", "", "") engine.draw_debug_info() engine.draw_titles() def with_options(sub_window, monochrome, lines): """ Draws logo with appearance options. :param sub_window: sub window id :param monochrome: monochrome if true, in colors otherwise :param lines: use lines to draw if true, polygons otherwise :return: """ def rotate_point(cx, cy, x, y, rot_angle): """ Rotates 2d point around another point. :param cx: x of point to rotate around :param cy: y of point to rotate around :param x: x of point to rotate :param y: y of point to rotate :param rot_angle: rotation angle :return: rotated point """ s = sin(rot_angle) c = cos(rot_angle) origin_x = x - cx origin_y = y - cy new_x = origin_x * c - origin_y * s new_y = origin_x * s + origin_y * c return new_x + cx, new_y + cy # setup size and colors width = 200.0 height = 200.0 outline_colors = [glib.color_rgb(0, 101, 182), glib.color_rgb(16, 171, 1), 'red', glib.color_rgb(255, 149, 1)] fill_colors = [glib.color_rgb(255, 149, 1), 'red', glib.color_rgb(16, 171, 1), glib.color_rgb(0, 101, 182)] # calc points # lets calc a single leaf the crescent and then rotate it four times center_point = (engine.window_width / 4, engine.window_height / 4) shift = height / 32 angle = 0.0 for i in range(0, 4): point_left = rotate_point(center_point[0], center_point[1], center_point[0] + width / 2, center_point[1] - shift + height / 5, angle) point_right = rotate_point(center_point[0], center_point[1], center_point[0] + width / 2, center_point[1] - shift - height / 5, angle) if monochrome: outline_color = 'black' fill_color = 'white' else: outline_color = outline_colors[i] fill_color = fill_colors[i] if lines: engine.draw_line(sub_window, [center_point, point_left], outline_color) engine.draw_line(sub_window, [point_left, point_right], outline_color) engine.draw_line(sub_window, [point_right, center_point], outline_color) else: engine.draw_polygon(sub_window, [center_point, point_left, point_right], outline_color, fill_color) angle = angle + pi / 2 # draw with different options with_options(1, True, False) with_options(2, True, True) with_options(3, False, True) with_options(4, False, False) def draw_task_three(engine): """ Lab 1. Task 3. Simulate analogue amplifier signals. :param engine: graphics engine to render with :return: """ engine.setup_sub_window(1, "Sin", "", "") engine.setup_sub_window(2, "Tan", "", "") engine.setup_sub_window(3, "Ctg", "", "") engine.setup_sub_window(4, "Sum", "", "") engine.draw_debug_info() engine.draw_titles() # shift the zero point and the scale for better visualizing # in the engines that do not support auto scaling. for i in range(0, 4): engine.sub_windows[i].zero_point = (engine.sub_windows[i].zero_point[0] + 50, engine.sub_windows[i].zero_point[1] + 150) engine.sub_windows[i].x_scale = 10 engine.sub_windows[i].y_scale = 10 engine.draw_aux() # Student number a = 10.0 def func_one(arg_x): return a * 0.1 * sin(arg_x) def func_two(arg_x): return a * 0.1 * tan(arg_x) def func_three(arg_x): return a * 0.1 * cos(arg_x) / sin(arg_x) color_one = 'red' color_two = 'green' color_three = 'blue' # setup ranges x_min = 0.0 x_max = 20.0 y_abs_max = 2.0 # calculate points of curves x = x_min step = 0.01 points_one = [] points_two = [] points_three = [] while x <= x_max: points_one.append((x, func_one(x))) try: y = func_two(x) if abs(y) < y_abs_max: points_two.append((x, func_two(x))) except ZeroDivisionError: pass try: y = func_three(x) if abs(y) < y_abs_max: points_three.append((x, func_three(x))) except ZeroDivisionError: pass x = x + step # draw engine.draw_curve(1, points_one, color_one) engine.draw_curve(2, points_two, color_two) engine.draw_curve(3, points_three, color_three) engine.draw_curve(4, points_one, color_one) engine.draw_curve(4, points_two, color_two) engine.draw_curve(4, points_three, color_three) def main(): """ Here it can be chosen which task of Lab 1 to run and which engine to use. :return: """ # engine = MathPlotLibEngine(1024, 768, 'white') # engine = GraphicsEngine(1024, 768, 'white') engine = TurtleEngine(1024, 768, 'white') # draw_task_one(engine) # draw_task_two(engine) draw_task_three(engine) engine.show() main()
#Import libs import matplotlib.pyplot as plt import seaborn as sns #Load the data data = sns.load_dataset("mpg") #print head print(data.head()) #Generate the box plot sns.boxplot(x="cylinders",y="mpg", data=data) #display plot plt.show()
import numpy time_format = '%Y-%m-%d %H:%M:%S.%f' def hr_avg(heart_rates): """ Calculates the average heart of an input list :param heart_rates: :return: avg """ avg = numpy.mean(heart_rates) return avg def find_cutoff_index(time_input, heart_rate_times): """ Finds the index in a time array corresponding to the specified time cutoff :param time_input: :param heart_rate_times: :return: cutoff_index """ time_delta = [] time_delta_sign = [] for reading in heart_rate_times: delta = reading - time_input time_delta.append(abs(delta)) time_delta_sign.append(numpy.sign(delta.total_seconds())) cutoff_value = numpy.min(time_delta) # Finds delta closest to zero index = time_delta.index(cutoff_value) if time_delta_sign[index] == 1.: cutoff_index = index else: cutoff_index = index + 1 return cutoff_index def check_tachycardia(age, avg_hr): """ Checks if patient data indicates tachycardia :param age: :param avg_hr: :return: tach """ if 0 <= age <= 1 and avg_hr > 159: tach = 1 elif 1 < age <= 2 and avg_hr > 151: tach = 1 elif 2 < age <= 4 and avg_hr > 137: tach = 1 elif 4 < age <= 7 and avg_hr > 133: tach = 1 elif 7 < age <= 11 and avg_hr > 130: tach = 1 elif 11 < age <= 15 and avg_hr > 119: tach = 1 elif age > 15 and avg_hr > 100: tach = 1 else: tach = 0 return tach
import sqlite3 # Данных # Базы Данных # SQL - язык работы с данными # sqlite - версия / отдельная база данных # Таблица "Люди" # id | Имя | Возраст | # 0 | Max | 16 # 1 | Olga | 41 # Создаем объект соединения with sqlite3.connect('try_slite.db') as con: # выполнить команду SQL try: con.execute('create table people (id int, name varchar(100), age int)') except sqlite3.OperationalError: pass # добавляем строку в таблицу #con.execute("insert into people (id, name, age) values (2, 'Olga', 41)") # выборка из таблицы # for a in con.execute("select * from people"): # print( a ) r = con.execute("select * from people") #print(r.description) print( r.fetchone() ) # print( r ) # Так можно получить курсор: # cur = con.cursor() # cur.execute() # Выборка с условием # for a in con.execute("select * from people where age > ? and name like ?", (40, 'O%') ): # print( a ) # con.executescript(''' # create table tst_table (id int, name varchar(100), age int); # create table tst_table2 (id int, name varchar(100), age int); # # insert into tst_table2 (id, name, age) values (2, 'Olga', 41); # # drop table tst_table; # ''') # # cur = con.cursor() # cur.execute() # 1. цвет # 2. пробег # 3. марка автомобиля # 4. номерной знак
text = ''' Hello, Bill!! Send me some info about lesson. ''' words = text.split() lev_syms = [ ',', '!', '.' ] for word in words: if 'i' in word or 'o' in word: # if len(word) > 2: # word = word[:3] # for sym in lev_syms: # word = word.replace(sym, '') for sym in lev_syms: while sym in word: word = word[:-1] print( word ) #print( type(words) ) #print( len( words ) ) # ''.split(<делитель>) ''.split()
# Echo server program import socket def serve(HOST, PORT): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: # Резервируем адрес и порт в системе s.bind((HOST, PORT)) # Ждать соединений s.listen(1) # одновременных соединений может быть не больше 1 while True: # Принимаем соединение conn, addr = s.accept() # Объект соедиени, адрес (откуда) with conn: print('Connected by', addr) while handle(conn): pass def handle(conn): data = conn.recv(1024) ## посчитать ## print('getted:', data) if not data: return False data = data.decode('utf-8') # 10;20;+ a, b, operation = data.split(';') result = calc(int(a), int(b), operation) # отправить результат # result = 'result: {}'.format(result).encode('utf-8') print(result) conn.sendall(result) return True def calc( a, b, operation ): if operation == '+': return a + b elif operation == '-': return a - b elif operation == '*': return a*b elif operation == '/': return a/b if __name__=='__main__': serve('', 50008)
# # про список # if "hello" in s: # s.append('buy') lst = [1, 2, 3] #print( str(lst) ) lst_2 = [] for sym in lst: sym = str(sym) lst_2.append(sym) lst_2 = set(lst_2) s = ';'.join(lst_2) print(s) #s = '1;2;3' x = 0 for i in range(12): for j in range(20): x += i * j if j > x > i: continue elif x == i == j: print('OK!!!') print(x)
lst = [ "hello", "buy", "item" ] # Список с длинами слов: lst2 = [ len(i) for i in lst ] print( lst2 )
# Функция внутри функции def func(): x = 100 def other_func(): print('hello!') other_func() func() # Полезный вариант def func(count): def other_func(n): # принимает на вход n print('hello!', n) for i in range(count): other_func(i) func(1000) # global и nonlocal GLOB = 123 def func(): global GLOB GLOB = 170 func() print(GLOB) GLOB = 'GLOB' def func(): NE_GLOB = 'NE GLOB' def other_func(): global GLOB GLOB = 'GLOB after other_func!!!' NE_GLOB = 'NE GLOB 1' print('NE_GLOB:', NE_GLOB) print('GLOB in other_func:', GLOB) other_func() print('old NE_GLOB:', NE_GLOB) print('GLOB in func:', GLOB) func() # nonlocal def func(): NE_GLOB = 'NE GLOB' def other_func(): nonlocal NE_GLOB # ТОЛЬКО python 3!!!! NE_GLOB = 'NE GLOB after other_func' other_func() print('NE_GLOB:', NE_GLOB) func() def creater(): def shower(a, b): print('a: {} b: {}'.format(a, b)) def summer(a, b): return a + b def empty(): pass return shower, summer new_shower, summer = creater() new_shower(100, 102) # ЗАМЫКАНИЯ def creater(a, b): def shower(): print('a: {} b: {}'.format(a, b)) return shower new_shower = creater('hello', 'by') new_shower() new_shower() new_shower() def counter(n): count = 0 def gen(): nonlocal count count += 1 for i in range(n): print(count, '-->', i) return gen #counter(n=10)() # так можно сразу запустить gen = counter(n=3) gen() gen() gen() def webserver(url): def ya_ru(): return '<html>Yandex</html>' def google(): return '<html>Google</html>' urls = { 'ya.ru': ya_ru, 'google.com': google, } return urls[url]() print( webserver(url='ya.ru', name='Alex') ) # 1. приветсвие от Yandex-а b от Гугла # 2. сделать программу калькулятор # вечный цикл # вычисление того, что получили через input # EXIT - выход из программы # 3. сделать функцию: на входе кол-во = длина списка # на выходе список случайных чисел # модуль random
class Transport: price = 0 speed = 0 def time(self, way): return way / self.speed class Taxi(Transport): price = 45 speed = 60 class Tram(Transport): price = 30 speed = 40 class Trolleybus(Transport): price = 30 speed = 50 class Autobus(Transport): price = 30 speed = 40 class Metro(Transport): price = 35 speed = 80 class YandexTaxi(Taxi): pass class Taxovichkoff(Taxi): pass way = [Tram(), Metro(), Autobus()] t = 0 total_price = 0 for w in way: t += w.time(30) total_price += w.price print( u''' Вы проехали ваш маршрут за: - {} рублей, - {} часов. '''.format(total_price, t) ) # ДЗ поместить рассчет маршрута в метод # - в какой класс вы поместите? # - какой тип метода используете?
# coding: utf-8 # 1. Исправить ошибки в этом программном коде n = 0 def smart_task(): n += 1 print( 'start of smart_task #{}'.format('n') ) def other_task(): ## + param_1 = None, param_2 = None if param_1 == None: return None print( "task" other_task.__name__ "start") for p in param_1: print("\t- count of 'p': " + param_2.count(p) ## + print(" task" other_task.__name__ "stop") smart_task() smart_task() other_task[('3', '4'), str(325543523)] smart_task()