text
stringlengths
37
1.41M
#!/bin/python """ Authors: Brett Creeley Matty Baba Allos """ from Config import set_pwm import warnings class Servo(object): """ Servo stores the following values: channel: The channel the Servo is connected to min_pulse: The minimum pulse the Servo allows max_pulse: The maximum pulse the Servo allows min_degree: The minimum degree the Servo can rotate to max_degree: The maximum degree the Servo can rotate to default_angle: The rest(initial)position of the servo. name: The name of the servo """ def __init__(self, id, min_pulse, max_pulse, min_degree=None, max_degree=None, default_angle= None, name="servo" ): self.id = id self.channel = self._id_to_channel(id) self.shield_id = self._id_to_shield_id(id) self.min_pulse = min_pulse self.max_pulse = max_pulse self.min_degree = min_degree self.max_degree = max_degree self.default_angle = default_angle self.name = name def _id_to_channel(self,id): """Given the id of the servo starting from 0 and because there are only 16 channels on hat we can know which channel the servo is connected into if we take the mod of the id. For example, a servo with id 34 is connected to channel 2 because 34%16 gives 2 because 16 fits into 34 two times and we left 2""" return id % 16 def _id_to_shield_id(self,id): """Given the id of the servo starting from 0 and because there are only 16 channels on hat we can know which shield the servo is plugged into if we divide the id by 16 and rounding to nearest integer. for example if we have servo plugged into channel 33 we know it's on shield 2, counting from 0, because 33/16=2.06 we round to the nearest int and we get a 2""" return int(round(id / 16)) #Make sure it's an int def rotate(self, degree): """ Rotate to the specified degrees """ try: pulse = self.degrees_to_pulse(degree) set_pwm(self.shield_id,self.channel, 0, pulse) except ValueError as exception: print(exception) print("Could not rotate {} to {} degree").format(self.name, degree) def initialize(self): """ Move servo to defult position """ print(self.default_angle) self.rotate(self.default_angle) def off(self): """ Rotate to the specified degrees """ try: set_pwm(self.shield_id,self.channel, 0, 0) except ValueError as exception: print(exception) print("Could not turn off {}").format(self.name) def degrees_to_pulse(self, degree): """ Map degree input value to a pulse length output value """ pulse = ((degree - self.min_degree) * (self.max_pulse - self.min_pulse + 1) / (self.max_degree - self.min_degree + 1) + self.min_pulse) # Check for boundary values if pulse < self.min_pulse: warnings.warn("Degree is out of range") return self.min_pulse elif pulse > self.max_pulse: warnings.warn("Degree is out of range") return self.max_pulse else: return pulse @property def min_pulse(self): return self.min_pulse @min_pulse.setter def min_pulse(self, value): """ Don't allow negative min_pulse value """ if value >= 0: self._min_pulse = value else: raise ValueError('Servo min_pulse must be >= 0') @min_pulse.getter def min_pulse(self): return self._min_pulse @property def max_pulse(self): return self._max_pulse @max_pulse.setter def max_pulse(self, value): """ Don't allow negative/zero max_pulse value """ if value > 0: self._max_pulse = value else: raise ValueError('Servo max_pulse must be > 0') @max_pulse.getter def max_pulse(self): return self._max_pulse @property def min_degree(self): return self.min_degree @min_degree.setter def min_degree(self, value=None): """ Only allow degree between -360 and 360 """ if value is None: # Default value self._min_degree = -90 elif value >= -360 and value <= 360: self._min_degree = value else: raise ValueError( 'Servo min_degree must be between -360 and 360 inclusive') @min_degree.getter def min_degree(self): return self._min_degree @property def max_degree(self): return self.max_degree @max_degree.setter def max_degree(self, value=None): """ Only allow degree between -360 and 360 """ if value is None: # Default value self._max_degree = 90 elif value >= -360 and value <= 360: self._max_degree = value else: raise ValueError( 'Servo max_degree must be between -360 and 360 inclusive') @max_degree.getter def max_degree(self): return self._max_degree
############################## PART A ############################## def find_matches(team): match_schedule = open("Scouting_2019_Match_Schedule.csv", "r") print(team + ": ", end = '') for line in match_schedule.readlines(): # Turn each line into a list of all the numbers line = line.split("\n") line = line[0] line = line.split(",") # If a number in the second through the seventh row = the team number, # the team is in that match for i in range(1,7): if line[i] == team: print(line[0] + ", ", end = '') break print("\n") match_schedule.close() find_matches("2168") ############################## PART B ############################## match_schedule = open("Scouting_2019_Match_Schedule.csv", "r") counter = 0 all_teams = [] team_repeated = 0 # Get a list of all teams for line in match_schedule.readlines(): if counter > 0: # Turn each line into a list of all the numbers line = line.split("\n") line = line[0] line = line.split(",") # Go through every team in the row for i in range (1,7): # Check if the team has already been added to the list for team in all_teams: if team == line[i]: team_repeated += 1 break # If the team wasn't added to the list yet, add it if team_repeated == 0: all_teams.append(line[i]) counter += 1 match_schedule.close() # Print matches of all teams for team in all_teams: find_matches(team)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Aug 3 18:50:05 2020 @author: william """ def two_sets(n): if (n+1)%4==0 or n%4==0 or n==3: print("YES") th1 = 0 th2 = 1 if n%4==0 else 3 seq_1 = [] seq_2 = [] for i in range(n+1): if i>0: if i%4 == th1 or i%4 == th2: seq_1.append(str(i)) else: seq_2.append(str(i)) print(len(seq_1)) print(' '.join(seq_1)) print(len(seq_2)) print(' '.join(seq_2)) else: print("NO") return None def main(): n = int(input()) res = two_sets(n) print(res) return None if __name__=="__main__": main()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jul 31 18:09:47 2020 @author: william """ def missing_number(n, numbers): res = (set(range(1, n+1))-numbers).pop() print(res) return None def main(): n = int(input()) numbers = set(map(int, input().split())) missing_number(n, numbers) return None if __name__=="__main__": main()
# Una forma de recorrer la cadena de caracteres en busca de '@' miEmail = input('Ingrese su email: ') email = False for i in miEmail: if (i == '@'): email = True if (email == True): # Esto se puede simplificar escribiendo: if email ---Esto automaticamente es lo mismo (email == True) print('El mail el correcto') else: print('El mail es incorrecto')
# Plantear una clase llamada Jugador. # Definir en la clase Jugador los atributos nombre y puntaje, y los métodos __init__, # imprimir y pasar_tiempo (que debe reducir en uno la variable de clase). # Declarar dentro de la clase Jugador una variable de clase que indique cuantos minutos falta # para el fin de juego (iniciarla con el valor 30) # Definir en el bloque principal dos objetos de la clase Jugador. # Reducir dicha variable hasta llegar a cero. class Jugador(): tiempo_finalizacion = 30 def __init__(self, nombre, puntaje): self.nombre = nombre self.puntaje = puntaje print("Comienza la partida") def imprimir(self): print("NOMBRE DE JUGADOR: ", self.nombre) print("PUNTUACION: ", self.puntaje) print("Finalizacion del juego en {} min".format(Jugador.tiempo_finalizacion)) def pasar_tiempo(self): Jugador.tiempo_finalizacion -= 1 # Bloque principal del programa jugador1 = Jugador("Ignacio", 200) jugador2 = Jugador("Ana", 59) while (Jugador.tiempo_finalizacion > 0): jugador1.imprimir() jugador2.imprimir() jugador1.pasar_tiempo() # Lo podemos llamar con cualquiera de los dos jugadores
# Realizar un programa que imprima en pantalla los números del 1 al 100. """ Modificar el programa para que resuelva: 1 - Imprimir los números del 1 al 500. 2 - Imprimir los números del 50 al 100. 3 - Imprimir los números del -50 al 0. 4 - Imprimir los números del 2 al 100 pero de 2 en 2 (2,4,6,8 ....100). """ x = 2 while (x <= 100): print(x) x+=2 print('El programa ha finalizado')
# Definir una serie de listas y tuplas anidadas empleados = ['Ignacio', 26, (18, 9, 2021)] print(empleados) empleados.append((19, 9, 2021)) print(empleados) alumnos = ('Ignacio', [10, 8]) print(alumnos) # La tupla no se puede modificar # Pero podemos agregar elementos a la lista alumnos[1].append(6) print(alumnos)
# Crear y cargar una lista con 5 enteros. Implementar un algoritmo que identifique el mayor valor de la lista. entero = [] for f in range(5): entero.append(int(input('Cargar valor: '))) print('La lista: {}'.format(entero)) # Basicamente toma un elemento cualquiera de la lista y lo compara con los demas mayor = entero[0] for x in range(len(entero)-1): if (entero[x] > mayor): mayor = entero[x] print('El mayor elemento de la lista es: {}'.format(mayor))
# Confeccionar una clase que permita carga el nombre y la edad de una persona. # Mostrar los datos cargados. Imprimir un mensaje si es mayor de edad (edad>=18) class Persona: def inicializar(self): self.nombre = input('Escriba el nombre de la persona: ') self.edad = int(input('Ingrese edad: ')) def mostrar(self): print('Datos de la persona') print('*Nombre:', self.nombre, '*Edad:', self.edad) def es_mayor(self): if (self.edad >= 18): print(self.nombre, 'es MAYOR de edad') else: print(self.nombre, 'es MENOR de edad') # Bloque principal del programa persona1 = Persona() persona1.inicializar() persona1.mostrar() persona1.es_mayor() persona2 = Persona() persona2.inicializar() persona2.mostrar() persona2.es_mayor()
# Confeccionar un módulo que implemente dos funciones, una que retorne el mayor de dos enteros # y otra que retorne el menor de dos enteros. def mayor(x1, x2): if (x1 > x2): return x1 else: return x2 def menor(x1, x2): if (x1 < x2): return x1 else: return x2
# Crear una lista y almacenar los nombres de 5 países. Ordenar alfabéticamente la lista e imprimirla pais = [] print('Escribir 5 paises') for f in range(5): pais.append(input("Nombre pais: ")) print('Lista paises -sin ordenar-\n{}'.format(pais)) for k in range(len(pais)-1): # Ordena la lista conformada con datos tipo string en orden alfabetico for x in range(len(pais)-k-1): if (pais[x] > pais[x+1]): # Como python diferencia entre mayusculas y minusculas pone en primer lugar a las mayusculas aux = pais[x] pais[x] = pais[x+1] pais[x+1] = aux print('Lista paises -ordenados-\n{}'.format(pais))
# Cargar una cadena por teclado luego: # 1) Imprimir los dos primeros caracteres. # 2) Imprimir los dos últimos # 3) Imprimir todos menos el primero y el último caracter. cadena = input('Ingrese un texto: ') # LOS DOS PRIMEROS CARACTERES: print(cadena[:2]) # LOS DOS ULTIMOS print(cadena[(len(cadena)-2):]) # SIN EL PRIMERO Y SIN EL ULTIMO print(cadena[1:(len(cadena)-1)])
# Confeccionar un programa que permita: # 1) Cargar una lista de 10 elementos enteros. # 2) Generar dos listas a partir de la primera. # En una guardar los valores positivos y en otra los negativos. # 3) Imprimir las dos listas generadas. def cargar_enteros(): lista = [] print('INGRESE 10 VALORES ENTEROS') for x in range(10): lista.append(int(input('{}- Ingrese valor: '.format(x+1)))) return lista def generador_lista(li): pos = [] neg = [] for x in range(len(li)): if (li[x] > 0): pos.append(li[x]) elif (li[x] < 0): neg.append(li[x]) return [pos, neg] def mostrar_listas(li): for x in range(len(li)): print(li[x]) # Bloque principal del programa lista = cargar_enteros() positivo, negativo = generador_lista(lista) print('Valores POSITIVOS:') mostrar_listas(positivo) print('Valores NEGATIVOS:') mostrar_listas(negativo)
# Desempaquetar una lista o tupla # Puede ser que tengamos una función que recibe una cantidad fija # de parámetros y necesitemos llamarla enviando valores que se # encuentran en una lista o tupla. La forma más sencilla es anteceder # el caracter * al nombre de la variable: def sumar(v1, v2, v3): sumar = v1 + v2 + v3 return sumar # Bloque principal del programa li = [2, 5, 6] # Puede ser tambien una TUPLA su = sumar(*li) print(su) # Lo que hicimos anteriormente es lo mismo que haremos a continuacion: print(sumar(li[0], li[1], li[2])) # La forma anterior en una forma mas resumidad de hacer esto mismo
# Desarrollar una clase que represente un punto en el plano y tenga los siguientes métodos: # inicializar los valores de x e y que llegan como parámetros, imprimir en que cuadrante se # encuentra dicho punto (concepto matemático, primer cuadrante si x e y son positivas, # si x<0 e y>0 segundo cuadrante, etc.) class Punto(): def __init__(self, x, y): self.x = x self.y = y def imprimir(self): print('Coordenada del punto') print('(', self.x, ',', self.y, ')', sep="") def cuadrante(self): if (self.x == 0 and self.y == 0): print('El punto se encuentra en el ORIGEN') elif (self.x > 0 and self.y > 0): print('El punto se encuentra en el PRIMER CUADRANTE') elif (self.x < 0 and self.y > 0): print('El punto se encuentra en el SEGUNDO CUADRANTE') elif (self.x < 0 and self.y < 0): print('El punto se encuentra en el TERCER CUADRANTE') else: print('El punto se encuentra en el CUARTO CUADRANTE') # Bloque principal del programa punto1 = Punto(0, 0) punto1.imprimir() punto1.cuadrante() punto2 = Punto(10, 50) punto2.imprimir() punto2.cuadrante() punto3 = Punto(-6, 5) punto3.imprimir() punto3.cuadrante() punto4 = Punto(-3, -1) punto4.imprimir() punto4.cuadrante() punto5 = Punto(7, -5) punto5.imprimir() punto5.cuadrante()
# Una empresa tiene dos turnos (mañana y tarde) en los que trabajan 8 empleados # (4 por la mañana y 4 por la tarde) Confeccionar un programa que permita almacenar # los sueldos de los empleados agrupados en dos listas. # Imprimir las dos listas de sueldos. manana = [] tarde = [] print('Ingrese sueldo de los empleados turno mañana') for f in range(4): manana.append(float(input('Ingrese sueldo: '))) print('Ingrese sueldo de los empleados turno tarde') for f in range(4): tarde.append(float(input('Ingrese sueldo: '))) print('Sueldo de los empleados turno (mañana): {}'.format(manana)) print('Sueldo de los empleados turno (tarde): {}'.format(tarde))
# Crear un diccionario en Python para almacenar los datos de empleados de una empresa. # La clave será su número de legajo y en su valor almacenar una lista con el nombre, profesión # y sueldo. # Desarrollar las siguientes funciones: # 1) Carga de datos de empleados. # 2) Permitir modificar el sueldo de un empleado. Ingresamos su número de legajo para buscarlo. # 3) Mostrar todos los datos de empleados que tienen una profesión de "analista de sistemas" def cargar_datos(): empleados = {} continuar = "s" while (continuar == "s"): legajo = int(input('Ingresar legajo: ')) lista = [] lista.append(input('Nombre empleado: ')) lista.append(input('Profesión del empleado: ')) lista.append(int(input('Sueldo empleado: '))) empleados[legajo] = lista continuar = input('¿Desea cargar datos de otro empleado? [s/n] ') return empleados def modificar_sueldos(empleados): legajo = int(input('Introducir legajo para buscar empleado: ')) if legajo in empleados: empleados[legajo][2] = int(input('Nuevo sueldo de empleado: ')) else: print('Legajo no corresponde al registro') def mostrar_datos(empleados): for legajos in empleados: if (empleados[legajos][1] == "analista de sistemas"): print(legajos, ': ', empleados[legajos][0], ' $', empleados[legajos][2], sep = "") def imprimir(empleados): print('Listado completo de empleados') for legajos in empleados: print(legajos, empleados[legajos][0], empleados[legajos][1], empleados[legajos][2]) # Bloque principal del programa empleados = cargar_datos() imprimir(empleados) print('-Modificar sueldo de empleado-') modificar_sueldos(empleados) imprimir(empleados) print('-Empleados \Analista de sistemas\-') mostrar_datos(empleados)
# Realizar la carga del nombre de una persona y luego mostrar el primer caracter del nombre # y la cantidad de letras que lo componen. nombre = input('Ingrese su nombre: ') print('La primera letra del nombres es:') print(nombre[0]) print('La cantidad de letras que tiene el nombre: ') print(len(nombre))
# Crear dos listas paralelas. En la primera ingresar los nombres de empleados y en la # segunda los sueldos de cada empleado. # Ingresar por teclado cuando inicia el programa la cantidad de empleados de la empresa. # Borrar luego todos los empleados que tienen un sueldo mayor a 10000 (tanto el sueldo como su nombre) empleados = [] sueldos = [] n = int(input('Cantidad de empleados en la empresa: ')) for k in range(n): empleados.append(input('Nombre del empleado: ')) sueldos.append(int(input('Sueldo del empleado: '))) print('Empleados de la empresa:') for k in range(n): print(empleados[k], sueldos[k]) posicion = 0 while (posicion < len(sueldos)): if (sueldos[posicion] > 10000): sueldos.pop(posicion) empleados.pop(posicion) else: posicion+=1 print('Empleados que cobran menos de 10000:') for k in range(len(sueldos)): print(empleados[k], sueldos[k])
# Confeccionar un programa que permita cargar un número entero positivo de hasta tres cifras # y muestre un mensaje # indicando si tiene 1, 2, o 3 cifras. Mostrar un mensaje de error si el número de cifras es mayor. num = int(input('Ingrese un numero entero positivo: ')) if (num <= 99): if (num <= 9): print('Tiene 1 CIFRA') else: print('Tiene 2 CIFRAS') else: if (num <= 999): print('Tiene 3 CIFRAS') else: print('Error')
# Plantear una clase Operaciones que solicite en el método __init__ la carga de dos enteros # e inmediatamente muestre su suma, resta, multiplicación y división. Hacer cada operación # en otro método de la clase Operación y llamarlos desde el mismo método __init__ class Operaciones(): def __init__(self): self.num1 = int(input('Ingrese un valor: ')) self.num2 = int(input('Ingrese otro valor: ')) self.sumar() self.restar() self.multiplicar() self.dividir() def sumar(self): suma = self.num1 + self.num2 print('El resultado de la suma es {}'.format(suma)) def restar(self): resta = self.num1 - self.num2 print('El resultado de la resta es {}'.format(resta)) def multiplicar(self): multi = self.num1 * self.num2 print('El resultado de la multiplicacion es {}'.format(multi)) def dividir(self): div = self.num1 / self.num2 print('El resultado de la division es {}'.format(div)) # Bloque principal del programa operacion1 = Operaciones()
# Almacenar en una lista los sueldos (valores float) de 5 operarios. Imprimir la lista y el promedio de sueldos. sueldos = [] suma = 0 for f in range(5): sueldos.append(float(input('Ingrese sueldo: '))) suma = suma + sueldos[f] prom = suma / 5 print('La lista de sueldo es:\n{}'.format(sueldos)) print('El promedio de los sueldos es: {}'.format(prom))
# Plantear una clase Club y otra clase Socio. # La clase Socio debe tener los siguientes atributos: nombre y la antigüedad en el club # (en años). # En el método __init__ de la clase Socio pedir la carga por teclado del nombre y su # antigüedad. # La clase Club debe tener como atributos 3 objetos de la clase Socio. # Definir una responsabilidad para imprimir el nombre del socio con mayor # antigüedad en el club class Socio: def __init__(self): self.nombre = input('Ingrese nombre del socio: ') self.antiguedad = int(input('Ingrese su antigüedad: ')) def imprimir(self): print('El socio {} tiene {} años de antiguedad'.format(self.nombre, self.antiguedad)) def retornar_antiguedad(self): return self.antiguedad class Club: def __init__(self): self.socio1 = Socio() self.socio2 = Socio() self.socio3 = Socio() def mayor_antiguedad(self): print('Socio con mayor antiguedad') if(self.socio1.retornar_antiguedad() > self.socio2.retornar_antiguedad() and self.socio1.retornar_antiguedad() > self.socio3.retornar_antiguedad()): self.socio1.imprimir() else: if (self.socio2.retornar_antiguedad() > self.socio3.retornar_antiguedad()): self.socio2.imprimir() else: self.socio3.imprimir() # Bloque principal del programa club1 = Club() club1.mayor_antiguedad()
# Desarrollar un programa que cargue una lista con 10 enteros. # Cargar los valores aleatorios con números enteros comprendidos entre 0 y 1000. # Mostrar la lista por pantalla. # Luego mezclar los elementos de la lista y volver a mostrarlo. import random def cargar(): lista = [] for x in range(10): lista.append(random.randint(0, 1000)) return lista def mostrar(lista): print(lista) def mezclar(lista): random.shuffle(lista) # Bloque principal del programa lista = cargar() # Al ser variable global se va modificando y no es necesario crear una nueva variable print('Lista generada aleatoriamente') mostrar(lista) mezclar(lista) print('La misma lista pero reorganizada') mostrar(lista)
# Cargar por teclado y almacenar en una lista las alturas de 5 personas (valores float) # Obtener el promedio de las mismas. Contar cuántas personas son más altas que el promedio y cuántas más bajas. altura = [] suma = 0 for f in range(5): altura.append(float(input('Ingrese altura: '))) suma = suma + altura[f] prom = suma / 5 altas = 0 bajas = 0 for i in range(len(altura)): if (altura[i] > prom): altas+=1 else: bajas+=1 print('El promedio de altura es: {}'.format(prom)) print('La cantidad de personas mas altas que el promedio es: {}'.format(altas)) print('La cantidad de personas mas bajas que el promedio es: {}'.format(bajas))
# Resolveremos el mismo problema anterior pero definiendo dos alias para las funciones # sqrt y pow del módulo math. from math import sqrt as raiz, pow as elevar # Definición de alias para una funcionalidad valor = int(input('Ingrese un valor: ')) valor1 = raiz(valor) print('La raiz cuadrada de {} es {}'.format(valor, valor1)) valor2 = elevar(valor, 3) print('El resultado de elevar al cubo {} es {}'.format(valor, valor2))
# De un operario se conoce su sueldo y los años de antigüedad. # Se pide confeccionar un programa que lea los datos de entrada e informe: # a) Si el sueldo es inferior a 500 y su antigüedad es igual o superior a 10 años, # otorgarle un aumento del 20 %, mostrar el sueldo a pagar. # b)Si el sueldo es inferior a 500 pero su antigüedad es menor a 10 años, otorgarle un aumento de 5 %. # c) Si el sueldo es mayor o igual a 500 mostrar el sueldo en pantalla sin cambios. sueldo = int(input('Ingrese el sueldo del operario: ')) antiguedad = int(input('Ingrese la antiguedad del operario: ')) if (sueldo >= 500): print('El sueldo del operario es: ${}'.format(sueldo)) else: if (sueldo < 500 and antiguedad >= 10): aumento = (sueldo*20)/100 + sueldo print('El sueldo a pagar será: ${}'.format(aumento)) else: aumento = (sueldo*5)/100 + sueldo print('El sueldo a pagar será: ${}'.format(aumento))
# Confeccionar una función que cargue por teclado una lista de 5 enteros y la retorne. # Una segunda función debe recibir una lista y mostrar todos los valores mayores a 10. # Desde el bloque principal del programa llamar a ambas funciones. def cargar_lista(): lista = [] for k in range(5): lista.append(int(input('Ingrese numero entero: '))) return lista def mayor_diez(li): lista_mayor = [] for k in range(len(li)): if (li[k] > 10): lista_mayor.append(li[k]) return lista_mayor # Bloque principal del programa print('Ingrese 5 valores enteros') lista = cargar_lista() print('Los valores de la lista son: ',lista) print('La nueva lista con valores mayor a 10 es: {}'.format(mayor_diez(lista)))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def optional_introduce(func): def wrapper (*args, introduce=False, **kwargs): if introduce is True: print(func.__name__) func(*args, **kwargs) return wrapper @optional_introduce def print_given(*args, **kwargs): answer = "" for arg in args: print(f"{arg} {type(arg)}") for k,v in kwargs.items(): print(f"{k} {v} {type(v)}") return answer print("\n", "="*50, " test 1", "\n") print(print_given( 1, 2, 3, [1, 2, 3], 'one', 'two', 'three', two = 2, one = 1, three = 3)) print("\n", "="*50," test 2", "\n") print(print_given( 2, 3, [1, 2, 3], 'one', 'two', 'three', two = 2, one = 1, three = 3)) print("\n", "="*15, " here input function name ", "="*15," test 3", "\n") print(print_given(1, 2, 3, [1, 2, 3], 'one', 'two', 'three', two = 2, one = 1, three = 3, introduce=True)) print("\n", "="*50, "\n")
# Isaac Padberg # 11.14.2019 """Radix Sort""" class Radix: def __init__(self, array): # Take the users input and copy it into our own array self.unsortedArray = array.copy() # Call radix sort and store its return value sortedArray = self.radixSort() self.sortedArray = [] print("Here is your sorted array:", sortedArray, "\n") def radixSort(self): # Get the number with the most decimal places in the array. maxDeci = max(self.unsortedArray) # Decimal place counter that will be incremented by a multiple of 10. deciPlace = 1 # Make 10 buckets(0-9) for the different values. self.sortedArray = [0] * len(self.unsortedArray) while deciPlace < maxDeci: # Call sortOnDeci and sort on the given decimal place. self.sortOnDeci(deciPlace) # Copy over the sorted array to the unsorted array self.unsortedArray = self.sortedArray.copy() # Increment decimal place by a factor of 10 deciPlace *= 10 return self.unsortedArray def sortOnDeci(self, deciPlace): length = len(self.unsortedArray) index = 0 # Create a count array to store the number of occurrences of each number. countOccur = [0] * 10 # Loop through the unsorted array and add the occurrence of each number to countOccur. for i in range(0, length): # Get the number from 0-9 at the specified decimal place index = (self.unsortedArray[i]/deciPlace) % 10 # Change index to an integer named intIndex. intIndex= int(index) # Increase the occurrence of number by 1 in the count array countOccur[intIndex]+=1 # Add up all the indices from the left to the right. # So (countOccur[1] = countedOccur[0]+countOccur[1]...) for a in range(0, len(countOccur)): countOccur[a] += countOccur[a-1] # Shift the values of each index in countOccur to the right. # Need to traverse array from right to left. # Index is now paired with the corresponding starting index of # that particular number in the sortedArray for x in reversed(range(0, len(countOccur))): countOccur[x] = countOccur[x-1] if x == 0: countOccur[x] = 0 # Finally place the contents of the unsortedArray to the sortedArray using # the countOccur as a template for which index to place each number at. # Index of countOccur is the number to be placed, and the value at that # index is the starting index to place it at. for j in self.unsortedArray: intIndex = int(j/deciPlace) % 10 self.sortedArray[countOccur[intIndex]] = j countOccur[intIndex] += 1 # Code to call the Radix Class and sort the given array. arr1 = [55, 31, 44, 4, 5, 63, 4] done = Radix(arr1) # Important scratch work for understanding how the code above works. # Still learning python so this is very helpful to have print("## Code I found Helpful ##") index1 = arr1.index(4) print("Index of the the value 4:", index1) arr2 = [1,23,4,1,2,] temp = int((4/1)%10) arr2 = arr1.copy() arr1 = [] arr1 = arr2.copy() count1 = [0]*10 count1[2] += 1 count1[2] += 1 print("Incrementing values at specific indices:",count1[2])
import pygame from UIComponents import Placeholder, Colors, Button, Slider # ---------- PYGAME SETUP ---------- pygame.init() size = (400, 700) surface = pygame.display.set_mode(size) clock = pygame.time.Clock() stop = False # ---------------------------------- # ----- CREATING A PLACEHOLDER ----- placeholder = Placeholder((10, 200, 300, 400)) # Creating sub objects slider = Slider((100, 100, 100, 5), 0, 100, 2, 50, Colors().red, Colors().black, 'My current value', font_size=20) button = Button((50, 300, 150, 50), Colors().red, 'Click Me!') # Adding sub objects placeholder.add_sub_object(slider) placeholder.add_sub_object(button) button_down = False # Standard game loop while not stop: # Standard event loop for event in pygame.event.get(): if event.type == pygame.QUIT: stop = True # User clicked mouse button (any) elif event.type == pygame.MOUSEBUTTONDOWN: # Keep track of if mouse button is still down button_down = True if slider.clicked(pygame.mouse.get_pos()): # Checking if user has clicked the slider and running click_function is yes print('Clicked!') # Do whatever you want to do after user has pressed a slider elif button.clicked(pygame.mouse.get_pos()): # Checking if user has clicked the button and running click_function is yes print('Clicked!') # Do whatever you want to do after user has pressed a slider elif event.type == pygame.MOUSEBUTTONUP: # Keep track of if mouse button is still down button_down = False # Check if user is slideing if button_down: slider.clicked(pygame.mouse.get_pos()) surface.fill(Colors().white) # Drawing a slider placeholder.draw(surface) pygame.display.flip() clock.tick(30) pygame.quit()
# -*- coding: utf-8 -*- """ Created on Fri Jul 19 21:01:08 2019 @author: Admin """ import matplotlib.pyplot as plt import numpy as np import math ## Create functions and set domain length x = np.arange(-5.0, 5.0, 0.01) y = x**x z=0 ## Plot functions and a point where they intersect plt.plot(x, y) plt.plot(x, z) plt.plot(1, 1, 'or') ## Config the graph plt.title('A Cool Graph') plt.xlabel('X') plt.ylabel('Y') #plt.ylim([0, 4]) plt.grid(True) plt.legend(['y = x', 'y = 2x'], loc='upper left') ## Show the graph plt.show()
num = int(input('Введите число \n')) i = num for i in range (num, 0, -1): if num % i == 0: print(i)
#1. def sortwithloops(input): length = len(input) for i in range(length): for k in range(i, length): if input[i] > input [k]: tempList = input[i] input[i] = input[k] input[k] = tempList return input #2. def sortwithoutloops(input): input.sort() return input #3. def searchwithloops(input, value): for i in input: if i == value: return "True" return "False" #4. def searchwithoutloops(input, value): return value in input if __name__ == "__main__": L = [5,3,6,3,13,5,6] print sortwithloops(L) # [3, 3, 5, 5, 6, 6, 13] print sortwithoutloops(L) # [3, 3, 5, 5, 6, 6, 13] print searchwithloops(L, 5) #true print searchwithloops(L, 11) #false print searchwithoutloops(L, 5) #true print searchwithoutloops(L, 11) #false
import timeit setup = ''' import copy import numpy as np def sortwithloops(input): length = len(input) for i in range(length): for k in range(i, length): if input[i] > input [k]: tempList = input[i] input[i] = input[k] input[k] = tempList return input def sortwithoutloops(input): input.sort() return input def searchwithloops(input, value): for i in input: if i == value: return "True" return "False" def searchwithoutloops(input, value): return value in input def sortwithnumpy(input): return np.sort(input) def searchwithnumpy(input, value): return value in np.array(input) L = [5,3,6,3,13,5,6] ''' n = 10000 t = timeit.Timer("x = copy.copy(L); sortwithloops(x)", setup = setup) print 'Sort with loops: ', n, 'loops takes ', t.timeit(n), 'seconds' t = timeit.Timer("x = copy.copy(L); sortwithoutloops(x)", setup = setup) print 'Sort without loops: ', n, 'loops takes ', t.timeit(n), 'seconds' t = timeit.Timer("x = copy.copy(L); sortwithnumpy(x)", setup = setup) print 'Sort with numpy: ', n, 'loops takes', t.timeit(n), 'seconds' t = timeit.Timer("x = copy.copy(L); searchwithloops(x,13)", setup = setup) print 'Search with loops: ', n, 'loops takes ', t.timeit(n), 'seconds' t = timeit.Timer("x = copy.copy(L); searchwithoutloops(x,13)", setup = setup) print 'Search without loops: ', n, 'loops takes ', t.timeit(n), 'seconds' t = timeit.Timer("x = copy.copy(L); searchwithnumpy(x,13)", setup = setup) print 'Search without numpy: ', n, 'loops takes ', t.timeit(n), 'seconds'
#!/usr/bin/python word = "21^^CV^^baby^you think?^" #word = "^^21CV^^" result = [] level = 0 incrementing = False decrementing = False escaped = False sequence = "" for letter in word: if letter != "^": sequence = sequence + letter if incrementing: incrementing = False escaped = True if decrementing: decrementing = False escaped = False continue if not incrementing and not decrementing and sequence != "": result.append((level, sequence)) sequence = "" if not escaped: incrementing = True else: decrementing = True if incrementing: level = level + 1 continue if decrementing : level = level - 1 continue if sequence != "": result.append((level, sequence)) print result
"""Write a function that takes an (unsigned) integer as input, and returns the number of bits that are equal to one in the binary representation of that number. Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case""" def countBits(n): return sum(1 for c in bin(n) if c == '1') assert countBits(0) == 0 assert countBits(4) == 1 assert countBits(7) == 3 assert countBits(9) == 2 assert countBits(10) == 2
from collections import defaultdict def frequency(l): d=defaultdict(int) for k in l: d[k]+=1 for k in set(l): print(k,"occurec",d[k],"times")
import functools def log(text): def decorator(fun): @functools.wraps(fun) #wrapper.__name__ = fun.__name__ def wrapper(*args, **kwargs): print("我就是想装饰一下%s, %s" % (fun.__name__, text)) return fun(*args, **kwargs) return wrapper return decorator # sum2num = log(text)(sum2num) @log('python是最好的语言') # sum2num=decorator(sum2num) def sum2num(a, b): return a + b print(sum2num(10, 20)) print(sum2num.__name__)
''' 实现类似cp的功能 python mycp.py ./mysys.py ps ''' import sys def mycp(src_path, dest_path): f1 = open(src_path) f2 = open(dest_path, "w") while True: rtext = f1.read(50) if rtext == "": break f2.write(rtext) f1.close() f2.close() def main(): if not(len(sys.argv) >= 3): print("至少需要两个参数") else: mycp(sys.argv[1], sys.argv[2]) if __name__ == "__main__": main()
''' 递归函数: 调用本函数 实现递归: 1.找递归点 2.找递归终止条件 ''' # 求给定整型数的前n项和 def sumn(n): if n == 0: return 0 return n + sumn(n-1) print(sumn(100)) ''' 汉诺塔问题 ''' cnt = 0 def move(m, n): global cnt cnt += 1 print(m,"--->", n) def hano(n, a, b, c): # 将a上的n个圆盘移动到b if n == 1: move(a, b) return None hano(n-1, a, c, b) hano(1, a, b, c) hano(n-1, c, b, a) hano(3, 'a', 'b', 'c') print("共{}次".format(cnt)) ''' rm def delfile(path): if path是目录 == False: del path return None else: 是目录 p = 打开目录---》得到目录下每一个文件的路径 delfile(p) '''
''' 循环: 循环变量初始化 while 条件: 循环体 循环变量改变 else: 执行体 for 循环变量 in 序列: 循环体 else: 执行体 ''' s = "Python" i = 0 # 循环变量 while i < len(s): if s[i] == 't': # break i += 1 continue # 终止本次循环,继续下一次循环(循环条件) print(s[i], end='') i += 1 else: # 当循环的终止是由于循环条件不满足而终止的,不是break终止的 print("执行结束") print('') # 换行 for i in s: if i == 't': # break 终止整个循环 continue print(i, end='') else: print('执行结束') print() print(range(10))# [0,10) i = 0 for i in range(len(s)): print(i) # range() for i in range(10): print(i) for i in range(5, 10): print(i) for i in range(1, 10, 2): print(i)
from tkinter import * # 移动 def moveToAnother(): selections = list1.curselection() for i in selections: name = list1.get(i) list2.insert(END, name) list1.delete(i) # 添加 def addItem(): s = var.get() list1.insert(END, s) var.set("") root = Tk() list1 = Listbox(root) list2 = Listbox(root) bnt1 = Button(root, text="移动->") bnt2 = Button(root, text="添加", command=addItem) var = StringVar() entry = Entry(root, textvariable = var) for name in ["Python", "C", "C++", "Go"]: list1.insert(0, name) # 默认第一个被选中 list1.activate(1) #???????? list1.pack(side=LEFT) list2.pack(side=RIGHT) bnt1['width'] = 10 bnt2['width'] = 10 # 移动按钮添加方法 bnt1['command'] = moveToAnother bnt1.pack() bnt2.pack() entry.pack() root.mainloop()
import random def qipan(pan): '''展示棋盘''' for hang in range(3): lie = hang * 3 print("{} {} {}".format(pan[lie], pan[lie + 1], pan[lie + 2])) def win(pan): '''判断是否胜利''' winls = ["012", "345", "678", "036", "147", "258", "048", "246"] for win in winls: i = 0 j = 0 for intex_ in win: if pan[int(intex_)] == "O": i += 1 if pan[int(intex_)] == "X": j += 1 if i == 3: return True elif j == 3: return False return def computer_zhineng(pan): '''机器人智能''' winls = ["012", "345", "678", "036", "147", "258", "048", "246"] yin = "" for win in winls: i = 0 for intex_ in win: if pan[int(intex_)] == "X": i += 1 elif pan[int(intex_)] != "O": yin = int(intex_) else: i -= 1 if i == 2: return yin for win in winls: i = 0 for intex_ in win: if pan[int(intex_)] == "O": i += 1 elif pan[int(intex_)] != "X": yin = intex_ else: i -= 1 if i == 2: return int(yin) return None def computer_xiaqi(pan): '''机器人下棋''' li = ["4", "0", "2", "6", "8", "1", "3", "5", "7"] if computer_zhineng(pan) != None: a = computer_zhineng(pan) return a else: for l in li: if pan[int(l)] != "O" and pan[int(l)] != "X": return int(l) def bisai(pan): '''比赛开始''' qipan(pan) person = int(input("请下子(输入棋盘上的数字)")) pan[person] = "O" j = 0 if win(pan) == True: return True elif win(pan) == False: return False for i in range(9): if pan[i] != str(i): j += 1 if j == 9: return None ''' 机器人下棋 ''' xia = computer_xiaqi(pan) pan[xia] = "X" j = 0 if win(pan) == True: return True elif win(pan) == False: return False for i in range(9): if pan[i] != str(i): j += 1 if j == 9: return None return bisai(pan) def main(): pan = ["0", "1", "2", "3", "4", "5", "6", "7", "8"] num = random.randint(1, 2) if num == 2: pan[computer_xiaqi(pan)] = "X" if bisai(pan) == True: print("真厉害你赢了") elif bisai(pan) == False: print("GAME OVER") else: print("平局") main()
from tkinter import * def hello(event): print(event.char) print("hello, x:%d, y:%d" % (event.x, event.y)) def hello_all(event): print("→→", event) root = Tk() root.geometry("200x200") # 绑定事件 root.bind('<Button-1>', hello) root.bind('<Return>', hello) root.bind('<Key>', hello) f1 = Frame(root, height=100, width=100, bg="red") f1.bind_all('<Button-3>', hello_all) f1.pack(side=TOP, expand=1, fill=BOTH) l1 = Label(f1, text="这是一个标签") l1.pack() Button(root, text="确定").pack() root.mainloop()
import os #Functions to handle operating system print(__file__)#__file__ is a constant that has the location of this script print(os.getcwd()) #gets current working directory print(os.path.realpath(__file__))#gets the directory of the file print(os.path.abspath(__file__))#does the same thing as above os.chdir(os.path.dirname(os.path.realpath(__file__)))#os.chdir changes the directory to the one specified, and os.path.dirname gets the name of the directory that the file is in. print(os.getcwd()) # some interesting stuff with files and directories thispath = os.getcwd() #path of an example files newpath = os.path.join(thispath,'newFolder') #Creates the directory for a new folder in the current working directory if not os.path.exists(newpath): #checks if path exists print("made a new folder!") os.makedirs(newpath) #creates path if it doesn't exist else: print("Folder already exists!") #directory is a pre-formatted directory string, localdir is a tuple, and name is the name of the file/folder def createPath(dir_name, localdir, name = ""): for item in localdir: dir_name = os.path.join(dir_name,item) newpath = os.path.join(newpath,name) return newpath def checkExist(dir_name): return os.path.exists(dir_name) def createFile(name, dir_name, *content):#content is by line newpath = createPath(dir_name, name) if not os.path.exists(newpath): file = open(newpath, "w+") file.write(str(name) + "\n") for item in content: file.write(str(item) + "\n") file.close() return True else: return False
x = int(input()) value_one = 0 value_two = x*(x+1) value_three = x-1 var = str() value_two = (value_two - value_three)*10 print(value_one,value_two) i = 0 while i < x: star,tri2,tri3 = '*',str(),'' star = star*i*2 k = 0 y = value_two while k<x-i: tri3 = tri3 + str(y) y += 10 k+=1 value_two = value_two - (x-i-1)*10 j = 0 while j<x-i: tri2 = tri2 + str(value_one+10) value_one += 10 j+=1 var = star+tri2+tri3[:-1] print(var) i+=1
""" Ejercicio 02 finanzas personales (ingresos y egresos) hacer un programa python para consola que le permita al usuario: 1. iniciar un proyecto de finanzas personales con cuenta a 0.00 2. dar opcion para registrar un ingreso o un egreso 3. si es un ingreso sumarlo a la cuenta 4. si es un egreso restarlo a la cuenta 5. verficar que si es un egreso y la cuenta esta a 0.0 debe aparecer el monto en negativo. 6. poder generar un reporte de todos los ingresos 7. poder generar un reporte de todos los egresos 8. poder generar un reporte de todas las transacciones (ingresos y egreso) 9. poder generar un reporte solo de el total de la cuenta restricciones del ejercicio: el proyecto finanzas debe ser una clase, un ingreso debe ser una clase y un egreso debe ser una clase tambien. """ from Class import (ProyectoFinanzas, Ingresos, Egresos) result1 = 0.0 resultIngresoT = [] resultEgresoT = [] while True: print("Bienvenido a su Programa de Finanzas") print("1. Monto que desea ingresar") print("2. Monto que desea egresar") print("3. Ingresos efectuados") print("4. Egresos efectuados") print("5. Reporte transacciones: ingresos y egresos") print("6. Saldo de la cuenta") print("0. Abandonar el Programa de Finanzas") selection = int(input("Seleccione una opcion ")) if selection==1: #Ingresar el valor del monto que se desea depositar Ingreso = float(input("Monto que desea ingresar $")) #Lista ingresos efectuados resultIngresoT.append(Ingreso) #Metodo Class Ingreso1 = Ingresos(Ingreso) resultIngreso = Ingreso1.sumIngresos() #Suma del monto a la cuenta result1 = result1+resultIngreso print(f"El saldo de la cuenta es de $ {result1}") elif selection==2: #Ingresar el valor del monto que se desea retirar Egreso = float(input("Monto que desea egresar $")) #Lista egresos efectuados resultEgresoT.append(Egreso) #Metodo Class Egreso1 = Egresos(Egreso) resultEgreso = Egreso1.nuevoEgreso() #Suma del monto a la cuenta result1 = result1+resultEgreso print(f"El saldo de la cuenta es de $ {result1}") elif selection==3: #Para obtener el reporte de ingresos for iterator in resultIngresoT: print(iterator) elif selection==4: #Para obtener el reporte de egresos for iterator in resultEgresoT: print(iterator) elif selection==5: #Para obtener el reporte de transacciones de ingresos y egresos print("Reporte de ingresos") for iterator in resultIngresoT: print(iterator) print("Reporte de egresos") for iterator in resultEgresoT: print(iterator) elif selection==6: #Para obtener el saldo total de la cuenta print(f"La cuenta tiene un saldo total de ${result1}") elif selection==0: #Para salir del programa break
label = ["Name", "Price", "Type", "Category"] def getByCat(items, category): return [item for item in items if item['Category'] == category] def readInput(): itemList = [] count = input() for x in range(count): item = [x.strip() for x in raw_input().split(",")] itemPair = zip(label, item) itemList.append(dict(itemPair)) return itemList if __name__ == '__main__': itemList = readInput() category = raw_input() print getByCat(itemList, category)
#outputs 1 to 10 all on different lines counter = 1 #loops so counter prints 10 times while counter >0 and counter <11: print(counter) #increases counter by 1 counter = counter + 1 #endwhile ## ACS Good work
#takes three numbers and prints from highest to lowest num1 = int(input("enter the first integer")) num2 = int(input("enter the second integer")) num3 = int(input("enter the third integer")) #finds the order of the sixe of the three numbers if num1 > num2 and num2 > num3: print(num1, num2, num3) elif num1 > num3 and num3 > num2: print(num1, num3, num2) elif num2 > num1 and num1 > num3: print(num2, num1, num3) elif num2 > num3 and num3 > num1: print(num2, num3, num1) elif num3 > num1 and num1 > num2: print(num3, num1, num2) elif num3 > num2 and num2 > num1: print(num3, num2, num1) #endif ## ACS Good but possibly not the most efficient solution. if there were 6 numbers this would get very long!
somestring = "here is a string" substring = "string" if substring in somestring: newstring = somestring.replace(substring, "") print(newstring)
class School(): def __init__(self, name): self.SchoolName = name self.programList = [] self.staffList = [] self.budgetIncome = float(0) self.budgetExpenses = float(0) self.budgetResult = float(0) def setSchoolName(self, name): self.name = name def addProgram(self, program): self.programList.append(program) def removeProgram(self): self.programList.pop() def addStaff(self, staff): self.staffList.append(staff) def removeStaff(self): self.staffList.pop() def getSchoolName(self): return self.SchoolName def calculateBudget(self): self.budgetIncome = 0 self.budgetExpenses = 0 for Staff in self.staffList: self.budgetExpenses += Staff.getPay() for Program in self.programList: self.budgetIncome += Program.expenses self.budgetResult = self.budgetIncome - self.budgetExpenses def reportBudget(self): self.calculateBudget() if self.budgetResult >= 0: string = "{} School is making {} in profit".format(self.SchoolName, self.budgetResult) return string if self.budgetResult < 0: string = "{} School is losing {}".format(self.SchoolName, self.budgetResult) return string
def multiply(x,y): return x*y if __name__=='__main__': print 'Enter first number: ', x = int(raw_input()) print 'Enter second number: ', y = int(raw_input()) print 'Multi: ',multiply(x,y)
# dijkstra.py # Afnan Enayet def dijkstra(graph, src): """ Dijkstra's algorithm with a regular queue :type graph: dict :type src: int """ dist = dict() # the distances from src to dist[x] prev = dict() # the previous node for node x visited = set() q = list() # Initialize Dijkstra for vertex in graph.keys(): dist[vertex] = INT.MAX prev[vertex] = None q.append(src) while len(q) > 0: # find vertex adj to q with min distance # TODO finish Dijkstra pass # test graph = dict()
class Node(object): def __init__(self, val): self.val = val self.children = dict() class Trie(object): def __init__(self): self.root = Node(None) def autocomplete(prefix: str, possible: list) -> list: """ Given a prefix string and a set of possibilities, returns a list of possible strings (like autocomplete suggestions) prefix: the input string possible: a list of possible strings, or the dictionary for this problem return: a list of autocomplete suggestions """ # first build a trie from the given dictionary trie = Trie() for word in possible: add_word_to_trie(trie, word) return get_suggestions_from_trie(trie, prefix) def add_word_to_trie(trie: Trie, word: str) -> Trie: # initialize to the roots curr_node = trie.root for letter in word: if letter in curr_node.children: curr_node = curr_node.children[letter] else: tmp = Node(letter) curr_node.children[letter] = tmp curr_node = tmp def get_suggestions_from_trie(trie: Trie, prefix: str) -> list: # first traverse to the node that corresponds to the last letter # of the prefix node = trie.root i = 0 while i < len(prefix) - 1 and prefix[i] in node.children: node = node.children[prefix[i]] i += 1 # now traverse from this node and get possible endings print(node.val) dfs(prefix, node) def dfs(prefix: str, node: Node): for child in node.children: new_prefix = prefix + node.val new_node = node.children[child] dfs(new_prefix, new_node) print(prefix) autocomplete("sal", ["salami", "salad", "bat"])
# -*- coding: utf-8 -*- # functions that use the trained model to classify a sample or a batch from data_loader import get_one_sample, get_random_sample from data_validation import validate_sample from model_validation import validate_model from train import load_model def classify_sample(sample) -> bool: """ classifies one sample """ is_sample_valid = validate_sample(sample) if is_sample_valid is False: raise Exception("Invalid sample") model = load_model() is_model_valid, _ = validate_model(model) if is_model_valid is False: raise Exception("Invalid model") predicted_class = int(model.predict(sample)[0]) return predicted_class def classify_batch(batch) -> list: """ classifies one batch of samples """ predicted_batch_classes = [classify_sample(sample) for sample in batch] return predicted_batch_classes def classify_one_sample() -> (int, int): """ loads one test sample and classifies it """ sample, sample_class = get_one_sample() predicted_class = classify_sample(sample) return predicted_class, sample_class def classify_random_sample() -> (int, int): """ loads one random test sample and classifies it """ sample, sample_class = get_random_sample() predicted_class = classify_sample(sample) return predicted_class, sample_class
from random import choice import time import twl # def get_dictionary(file): # dictionary = {} # with open(file) as whole_dictionary: # lines = whole_dictionary.readlines() # del lines[:lines.index("-START-\n")+1] # del lines[lines.index("-END-\n"):] # for line in lines: # line.rstrip() # index = line.index(" ") # word = line[0:index] # definition = line[index:].strip() # dictionary[word] = definition # print(dictionary) # return dictionary def make_board(width): all_letters = "AAABCDEEEFGHIIIJKLMNNOOOPQRSSTTUUUVWXYZ" board = [] letters_needed = width ** 2 board_letters = "" start = 0 while len(board_letters) < letters_needed: board_letters += choice(all_letters) for i in range(width): board.append([]) board[i].extend(board_letters[start: start + width]) start += width for i in range(width): print_board = " ".join(board[i]) for i in range(len(print_board)): if print_board[i] == "Q": print_board = print_board[:i+1] + "u" + print_board[i+2:] print(print_board) return board def find(board, word): """Can word be found in board?""" used_set = set() def check_next(position, word): """Checks current position for letter, then recursively checks neighbors. If on last letter of word, and position is that letter, returns True. """ x, y = position if x < 0 or x > (len(board)-1): return False elif y < 0 or y > (len(board)-1): return False elif board[x][y] == word[0] and (x, y) not in used_set: if word[0:2] == "QU": if len(word) == 2: return True else: used_set.add(position) neighbor_list = [(x+1, y), (x-1, y), (x, y+1), (x, y-1), (x+1, y+1), (x-1, y+1), (x+1, y-1), (x-1, y-1)] for i in range(len(neighbor_list)): if neighbor_list[i] not in used_set: if check_next(neighbor_list[i], word[2:]) is True: return True i += 1 else: used_set.remove(position) return False elif len(word) == 1: return True else: used_set.add(position) neighbor_list = [(x+1, y), (x-1, y), (x, y+1), (x, y-1), (x+1, y+1), (x-1, y+1), (x+1, y-1), (x-1, y-1)] for i in range(len(neighbor_list)): if neighbor_list[i] not in used_set: if check_next(neighbor_list[i], word[1:]) is True: return True i += 1 else: used_set.remove(position) return False return False for horizonal in range(len(board)): for vertical in range(len(board)): position = (horizonal, vertical) answer = check_next(position, word) if answer is True: return True return False def play_game_singleplayer(): print() print("WELCOME TO BOGGLE SOLITARE!") print() print("The rules are simple:") print("You have limited to type as many words as you can find.") print("you can go in any direction, but you can't use the same letter twice.") print("3 letter words and shorter are worth 1 point, ", "while longer words are worth 1 extra point per letter over 3") print("'Qu' can count as Q or QU in words.") print() length = input("How many seconds do you want for guessing? > " ) try: length = int(length) except ValueError: print("You failed to enter a valid number, default is 60 seconds") length = 60 else: if length < 0: print("You failed to enter a valid number, default is 60 seconds") length = 60 user_word_set = set() now = time.time() end = now + length score = 0 print(f"You have {length} seconds, starting...") time.sleep(2) print("NOW!") board = make_board(5) while time.time() < end: user_word_set.add(input("> ").upper()) print("STOP") time.sleep(1) for word in list(user_word_set): if twl.check(word.lower()) is False: print(f"{word} not in dictionary") user_word_set.remove(word) for word in user_word_set: if find(board, word): if len(word) <= 3: score += 1 else: score += len(word)-3 else: print(f"{word} is not on the board") print(f"your score is:{score}") play_game_singleplayer()
''' Jacob Tyson 10/1/2019 Title: Average Rainfall document. Description: This program will calculate the average rainfall over a certain amount of years, and then calculates the total average yearly rainfall and total average monthly rainfall. The input function will take in the users input, and the processing function will take from the input function to process the user input to obtain monthly rainfall, and calculate the monthly and yearly rainfall averages. ''' def main(): multiyear_total = 0 # used for challenge level - initialize 2 study-wide variables multiyear_avg = 0 # 2nd study-wide variable outputs() #Gather User input, with validation def inputs(): num_years = input('How many years are in your rainfall sample? ') while num_years.isnumeric() is False or int(num_years) < 0: num_years = input("Please enter a whole number greater than zero.") num_years = int(num_years) return num_years #Gathers monthly amount of rainfall, calculates average and total monthly and yearly rainfall. def processing(): multiyear_total = 0 multiyear_avg = 0 num_years = inputs() for year in range(num_years): total_rain_year = 0 avg_rain_year = 0.00 print(f'Rainfall info for year #{year + 1}: ') for month in range(12): rain_for_month = input(f'\tEnter rain for month #{month + 1}: ') while rain_for_month.isnumeric() is False or int(rain_for_month) < 0: #validation rain_for_month = input('please enter a whole number.') continue rain_for_month = int(rain_for_month) total_rain_year += rain_for_month avg_rain_year = total_rain_year / 12 print(f'Total rain in inches for year #{year + 1} = {total_rain_year}') print(f'Year #{year + 1} Monthly Avg Rainfall = {avg_rain_year :<.2f}') multiyear_total += total_rain_year multiyear_avg = multiyear_total / num_years / 12 # calc. study avg. return multiyear_total, multiyear_total #Gives output of total and average amount of rainfall. def outputs(): multiyear_total, multiyear_avg = processing() print(f'\nTotal rain, all years = {multiyear_total} inches') print(f'Average monthly rain, all years = {multiyear_avg} inches') print('Thanks for using the program!') # exit msg. main()
#Jacob Tyson """""" import math # cut off 7.89 to 7 print('7 with the .89 cut off = ' + str(round(7.89))) # round 54.345395 to 54.345 print('54.345395 rounded to 3 decimal places' + str(round(54.345395, 3)) # calculate the square root of 2 print(math.sqrt(2)) # calculate the sin of 7 print('The sin of 7 = ' + str(math.sin(7))) # display the value of pi print('The value of pi =' + str(math.pi)) # display pi rounded to 3 decimal places print('The value of pi rounded to 3 places = ' + str(round(math.pi, 3)))
''' Jacob Tyson credit card validator This program will ask user to input creditcard number, and validates it using different formats. 12/12/2019 ''' import re def main(): getCardNumber = inputs() # calls inputs getCardNumber = processing(getCardNumber) # calls proccessing outputs(getCardNumber) # calls outputs restart = input('Would you like to restart? y or n') # restart feature restart = restart.lower() if restart == 'y': # restart feature main() else: print('Thanks for using the program.') def inputs(): getCardNumber = input('Please enter your credit card number') # get user input return getCardNumber def processing(getCardNumber): compiler = re.compile(r'(\d\d\d\d+)([.]|[-]|\s )+(\d\d\d\d+)([.]|[-]|\s )+(\d\d\d\d+)([.]|[-]|[,] )+(\d\d\d\d+)') # regex card number validator while compiler.search(getCardNumber) == None: # validator getCardNumber = input('I am sorry our records do not recognize that number.\n Please use the followong format:\n xxxx.xxxx.xxxx.xxxx or xxxx-xxxx-xxxx-xxxx or xxxx,xxxx,xxxx,xxxx') return getCardNumber # returns validated card number. def outputs(getCardNumber): print(f' Success!!!! \n Your card number is: {getCardNumber}!!') # displays output main()
# -*- coding: utf-8 -*- """ Created on Mon Feb 8 18:42:08 2021 @author: gabri """ import urllib.parse import requests main_api = "https://www.mapquestapi.com/directions/v2/route?" key = "QvrROLQbeGnXmsgha3A7O4tiYI5XHBUo" #The "while True" construct creates an endless loop. while True: orig = input("Starting Location: ") if orig=="quit" or orig=="q": break dest = input("Destination: ") if dest=="quit" or dest=="q": break url = main_api + urllib.parse.urlencode({"key": key, "from": orig, "to": dest}) print("URL: " + (url))
# -*- coding: utf-8 -*- """ Created on Mon Feb 8 18:34:18 2021 @author: gabri """ aclNum=int(input("What is the IPv4 ACL number? ")) if aclNum>= 1 and aclNum<=99: print("\n This is a standard IPv4 ACL.") elif aclNum>= 100 and aclNum<=199: print("\n This is a extended IPv4 ACL.") else: print("\n This is not a standard or extended IPv4 ACL.")
from pygame import draw, image, transform from nn import NeuralNet import random class Environment: def __init__(self, display_height, display_width, unit_size): """Creates an object of type Environment. Args: display_height (int): Height of display in pixels. display_width (int): Width of display in pixels. unit_size (int): Size of each block in pixels. """ self.display_height = display_height self.display_width = display_width self.unit = unit_size self.apple_position = (0, 0) def draw_apple(self, environment, color): """Draw apple on the screen Args: environment (object): Instance of type Environment color (tuple): RGB values of colour Returns: environment: Returns instance of type Environment after drawing apple """ apple_image = image.load('apple.png') apple_image = transform.scale(apple_image, (10, 10)) environment.blit( apple_image, (self.apple_position[0], self.apple_position[1], self.unit, self.unit)) return environment def draw_boundary(self, environment, color): """Draws boundary on the screen Args: environment (object): Instance of type Environment color (tuple): RGB values of colour """ unit = self.unit for w in range(0, self.display_width, self.unit): draw.rect(environment, color, (w, 0, unit, unit)) draw.rect(environment, color, (w, self.display_height - unit, unit, unit)) for h in range(0, self.display_height, self.unit): draw.rect(environment, color, (0, h, unit, unit)) draw.rect(environment, color, (self.display_width - unit, h, unit, unit)) def create(self, environment, color): """Initialize the environment and draw boundaries Args: environment (object): Instance of type Environment color (tuple): RGB values of colour Returns: environment: Returns instance of type Environment after drawing apple """ environment.fill((200, 200, 200)) self.draw_boundary(environment, color) return environment def create_new_apple(self, snake_position): """Creates new apple, checks that the new apple does not appear on the body of the snake Args: snake_position (list): List of the snake body coordinates Returns: list: Coordinates of new apple position """ unit = self.unit apple_position = (unit*random.randint(2, self.display_width/unit - 2), unit*random.randint(2, self.display_height/unit - 2)) while any(body == apple_position for body in snake_position): apple_position = (unit*random.randint(2, self.display_width/unit - 2), unit*random.randint(2, self.display_height/unit - 2)) self.apple_position = apple_position return self.apple_position class snake: def __init__(self, display_width, display_height, NN_shape, unit, init_NN=True, random_start=True): """Initializes an object of type snake Args: display_height (int): Height of display in pixels. display_width (int): Width of display in pixels. NN_shape (list): Shape of neural network architecure unit_size (int): Size of each block in pixels. init_NN (bool, optional): Initalize neural network with random weights. Defaults to True. random_start (bool, optional): Start the snake position randomly or at predefined location. Defaults to True. """ self.snake_position = [] self.display_width = display_width self.display_height = display_height self.time_since_apple = 0 self.collision_with_boundary = False self.collision_with_self = False self.unit = unit self.neuralnet = NeuralNet( NN_shape, self.display_width, self.display_height, self.unit, init_NN) self.snake_position.append(self.initSnake(random_start)) def initSnake(self, random_start): """Set the start position and direction of snake Args: random_start (bool): Describes whether the snake should start randomly or Returns: tuple: X and Y coordinates of snake_head (starting position) """ if random_start: self.direction = random.choice(['RIGHT', 'UP', 'DOWN', 'LEFT']) self.head_x = random.randint( 3, self.display_width / self.unit - 3) * self.unit self.head_y = random.randint( 3, self.display_height / self.unit - 3) * self.unit else: self.direction = 'RIGHT' self.head_x, self.head_y = 40, 40 return (self.head_x, self.head_y) def isAlive(self): """Check if snake is alive Returns: bool: True if alive, False otherwise """ if not self.collision_with_self and not self.collision_with_boundary: return True return False def eatApple(self, direction): """Add the location to snake body and increase snake size by 1 Args: direction (str): Direction of movement after eating apple """ self.snake_position.insert(0, (self.head_x, self.head_y)) self.move(direction) def eatAppleHuman(self, direction): """Eat Apple method but for player playing the game instead of AI Args: direction (str): Direction of movement after eating apple """ self.snake_position.insert(0, (self.head_x, self.head_y)) self.moveHuman(direction) def moveInDirection(self, direction): """Move the snake in a particular direction, if chosen direction is valid. Else keep moving in current direction. Args: direction (str): Direction chosen by user """ if direction == 'UP': self.head_y = self.head_y - self.unit elif direction == 'DOWN': self.head_y = self.head_y + self.unit elif direction == 'LEFT': self.head_x = self.head_x - self.unit else: self.head_x = self.head_x + self.unit self.direction = direction self.snake_position.insert(0, (self.head_x, self.head_y)) self.snake_position.pop() self.check_valid() def check_valid(self): """Check if the snake is alive / has crashed into it's own body or boundary """ if self.head_x == self.unit or self.head_x == self.display_width - self.unit or self.head_y == self.unit or self.head_y == self.display_height - self.unit: self.collision_with_boundary = True for (body_x, body_y) in self.snake_position[1:]: if body_x == self.head_x and body_y == self.head_y: self.collision_with_self = True def move(self, result): """Move the snake in a chosen direction Args: result (int): Direction chosen by the AI for movement of the snake Returns: bool: Describes whether or not snake is alive after movement """ if self.direction == 'UP': if result == 1: self.moveInDirection('UP') elif result == 2: self.moveInDirection('LEFT') else: self.moveInDirection('RIGHT') elif self.direction == 'RIGHT': if result == 1: self.moveInDirection('RIGHT') elif result == 2: self.moveInDirection('UP') else: self.moveInDirection('DOWN') elif self.direction == 'DOWN': if result == 1: self.moveInDirection('DOWN') elif result == 2: self.moveInDirection('RIGHT') else: self.moveInDirection('LEFT') else: if result == 1: self.moveInDirection('LEFT') elif result == 2: self.moveInDirection('DOWN') else: self.moveInDirection('UP') self.time_since_apple += 1 return self.isAlive() def moveHuman(self, result): """Move the snake in a chosen direction for player, not for AI Args: result (int): Direction chosen by the player for movement of the snake Returns: bool: Describes whether or not snake is alive after movement """ if self.direction == 'UP': if result == 1: self.moveInDirection('UP') elif result == 2: self.moveInDirection('LEFT') elif result == 3: self.moveInDirection('RIGHT') elif self.direction == 'RIGHT': if result == 1: self.moveInDirection('UP') elif result == 3: self.moveInDirection('RIGHT') elif result == 4: self.moveInDirection('DOWN') elif self.direction == 'DOWN': if result == 2: self.moveInDirection('LEFT') elif result == 3: self.moveInDirection('RIGHT') elif result == 4: self.moveInDirection('DOWN') elif self.direction == 'LEFT': if result == 1: self.moveInDirection('UP') elif result == 2: self.moveInDirection('LEFT') elif result == 4: self.moveInDirection('DOWN') elif result!=0: self.moveInDirection(self.direction) return self.isAlive() def convAIToDirections(self, result): """Convert relative integer output by AI helper into absolute direction for the Args: result ([int]): Direction as output by the AI helper Returns: str : Absolute direction """ if self.direction == 'UP': if result == 1: return 'UP' elif result == 2: return 'LEFT' else: return 'RIGHT' elif self.direction == 'RIGHT': if result == 1: return 'RIGHT' elif result == 2: return 'UP' else: return 'DOWN' elif self.direction == 'DOWN': if result == 1: return 'DOWN' elif result == 2: return 'RIGHT' else: return 'LEFT' else: if result == 1: return 'LEFT' elif result == 2: return 'DOWN' else: return 'UP' def draw_snake(self, environment, color, color_head): """Draws the snake on the environment Args: environment (object): Instance of class environment color (tuple): RGB values of color of snake color_head (tuple): RGB values of color of snake Returns: environment: Returns the environment after the snake has been drawn """ l = self.unit for (x, y) in self.snake_position[1:]: draw.rect(environment, color, (x, y, l, l), 1) draw.rect(environment, color, (x+2, y+2, l-4, l-4)) draw.rect(environment, color_head, (self.head_x, self.head_y, l, l), 1) draw.rect(environment, color_head, (self.head_x+2, self.head_y+2, l-4, l-4)) return environment
def rea(f): with open(f) as d: w = d.read() words = w.split() return words #выдаёт список слов из текста в файле def d(a): words = rea(a) unw = [] for word in words: if len(word) > 1 and word[0] == 'u' and word[1] == 'n': unw.append(word) return unw #составляет список слов на "un" def am(a, e): un = d(a) fin = 0 f = 0 t = len(un) for u in un: if len(u) > e: fin = fin + 1 if t != 0: f = (fin / t)* 100 print('vsego:', t) print('dolya:', f,'%') #считает количество элементов списка и ищет % слов на "un" короче e букв(е вводит пользователь) def main(): e = int(input()) am("ment.txt", e) if __name__ == '__main__': main()
import re m = input() rig = re.search(r'(\+7|8)\d{10}$',m) if rig: print('ya') else: print('no')
# Your task is to create a Python script that analyzes the records to calculate each of the following: #Importing operating software and csv module import os import csv #Creating lists dates = [] profit = [] #Declaring variable value total_profit = 0 #Set path for the csv file csvpath = "../Resources/budget_data.csv" #Open the CSV file with open(csvpath, mode= 'r', newline = '') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') #for loop to create a new variable row_list next(csvreader) for row in csvreader: row_list= list(row) dates.append(row_list[0]) profit.append(int(row_list[1])) #print(sum(profit)) #print the total for dates. Minues 1 as the first row is a header. Print = count (total dates -1 (for header)) print(len(dates)) #Calculating total profit. First declated a new variable x who range startes from 1 and I put len(profit)-1 as the first column is classified as ) in Python #Then, I convert profit into integer and increase the running total for total_profit and print total profit. for x in range(0,len (profit)): total_profit = int(profit[x]) + total_profit print (total_profit) #Calculating average using total_profit and dividing my profit entries on the .csv average_change = total_profit/(len(profit)) print(average_change) # Declared two variables max and min. Used the range loop of line 31. Than if the profit is gretaer that the previous profit value, print the new profit value # as specfied. Same rule has been applied for minumum as well. max =0 min=0 for x in range(1, len(profit)-1): if int(profit[x]) > max: max= int(profit[x]) for x in range(1, len(profit)-1): if int(profit[x]) < min: min= int(profit[x]) print (max) print (min)
#!/usr/bin/env python # coding: utf-8 # In[3]: #4. Create a function showEmployee() in such a way that it should accept employee name, and it’s salary and display both, and if the salary is missing in function call it should show it as 50000 def showEmployee(name,salary=50000): print("Employee ",name," salary is: 50000") showEmployee("eddy",50000) showEmployee("eddy") # In[ ]:
# 斐波那契数列 def fib(n): a, b = 0, 1 while b < n: print(b, end=" ") a, b = b, a + b print() def fib02(n): result = [] a, b = 0, 1 while b < n: result.append(b) a, b = b, a + b return result
############类的对象############ # class PyClass: # i=12345 # def f(self): # return "hello world" # # #实例化类 # x=PyClass() # # #访问类的属性和方法 # print("访问属性",x.i) # print("访问方法:",x.f()) ############单继承################ # 类定义 class people: # 定义基本属性 name = '' age = 0 # 定义私有属性 __weight = 0 # 定义构造方法 def __init__(self, n, a, w): self.name = n self.age = a self.__weight = w def speak(self): print('{} 说:我{}岁。'.format(self.name, self.age)) # 单继承示例 class student(people): grade = '' def __init__(self, n, a, w, g): # 调用父类的构函 people.__init__(self, n, a, w) self.grade = g # 覆写父类的方法 def speak(self): print('{} 说:我{}岁了,我读{}年级。'.format(self.name, self.age, self.grade)) # 调用 s = student('ken', 10, 60, 3) s.speak()
""" str(): 函数返回一个用户易读的表达形式 repr(): 产生一个解释器易读的表达形式 字符串对象的 rjust() 方法, 它可以将字符串靠右, 并在左边填充空格。 ljust() center() """ for x in range(1, 11): print(repr(x).rjust(6), repr(x * x).rjust(6), end=" ") # 注意end的使用 print(repr(x * x * x).rjust(6)) for x in range(1, 11): print('{0:2d} {1:3d} {2:4d}'.format(x, x * x, x * x * x)) print('{} 网址:{}!'.format('菜鸟教程', 'www')) """ 美化表格: 在 : 后传入一个整数, 可以保证该域至少有这么多的宽度。 用于美化表格时很有用。 """ table = {'zhagnsan': 1, 'lisi': 2, 'wangwu': 3} for name, number in table.items(): print('{0:10} ===> {1:10d}'.format(name, number)) """ 旧式字符串格式化 [建议使用str.format()] """ import math print('常量PI的值近似为:%5.3f' % math.pi) print('常量 PI 的值近似为 {0:.3f}。'.format(math.pi)) # 保留小数后三位 """ 读取键盘输入 input() 内置函数 """ str1 = input("请输入:") print("你输入的是:", str1)
class parent: def myMethod(self): print("调用父类方法") class child(parent): def myMethod(self): print("调用子类方法") def __myPrivateMethod(self): print("这个是我的私有方法") # 调用 c = child() # 子类实例 c.myMethod() # 子类调用重写方法 super(child, c).myMethod() # 用子类对象调用父类已被覆盖的方法 # c.myPrivateMethod() # 报错,外部不能调用私有方法
class Iterator: """ Protocol for iterating over an object. """ def __init__(self, _iterable): """ Store iterable and initialize count. Args: _iterable (iterable object) - must have a 'length' and be indexable """ self._iterable = _iterable self.count = 0 def __iter__(self): """ Iterate over contents. """ return self def __next__(self): """ Advance iterator. """ if self.count >= len(self._iterable): raise StopIteration else: self.count += 1 return self._iterable[self.count - 1]
import turtle import random CELL_SIZE = 8 #size in pixels class Grid: def __init__(self, height, width): self.height, self.width = height, width #dimensions of the grid self.state = set() #state of the grid def isValidMove(self, x, y): return (0<=x<self.width) and (0<=y<self.height) def genGrid(self): self.clearGrid() for i in range(self.width): for j in range(self.height): if random.random() > 0.5: self.addToState(i,j) def clearGrid(self): self.state.clear() def addToState(self, x, y): if self.isValidMove(x, y): coord = (x, y) self.state.add(coord) else: raise ValueError("Coordinates {} and {} are not in range {} and {}".format(x, y, self.width, self.height)) def revCellState(self, x, y): if self.isValidMove(x, y): coord = (x, y) if coord in self.state: self.state.remove(coord) else: self.state.add(coord) else: raise ValueError("Coordinates {} and {} are not in range {} and {}".format(x, y, self.width, self.height)) def liveOrDie(self, cellState, liveNeighbours): if cellState and liveNeighbours<2: return False elif cellState and liveNeighbours>3: return False elif not cellState and liveNeighbours==3: return True return cellState def nextGen(self): nextGen = set() for i in range(self.width): posX = range(max(0, i-1), min(self.width, i+2)) for j in range(self.height): liveNeighbours = 0 cellState = ((i, j) in self.state) for iy in range(max(0, j-1), min(self.width, j+2)): for ix in posX: if (ix, iy) in self.state: liveNeighbours += 1 liveNeighbours -= cellState if self.liveOrDie(cellState, liveNeighbours): nextGen.add((i,j)) self.state = nextGen def draw(self, x, y): turtle.penup() coord = (x, y) if coord in self.state: turtle.setpos(x*CELL_SIZE, y*CELL_SIZE) turtle.color("black") turtle.pendown() turtle.setheading(0) turtle.begin_fill() for i in range(4): turtle.forward(CELL_SIZE-1) turtle.left(90) turtle.end_fill() def drawGrid(self): turtle.clear() for i in range(self.width): for j in range(self.height): self.draw(i, j) turtle.update() def display_instruction_window(width, height): from turtle import TK root = TK.Tk() frame = TK.Frame() canvas = TK.Canvas(root, width=width, height=height, bg="white") canvas.pack() instr_screen = turtle.TurtleScreen(canvas) instr_t = turtle.RawTurtle(instr_screen) instr_t.penup() instr_t.hideturtle() instr_t.speed('fastest') width, height = instr_screen.screensize() line_height = 20 y = height // 2 - 30 for s in ("Click on cells to make them alive or dead.", "Keyboard commands:", " E)rase the board", " R)andom fill", " S)tep once or", " C)ontinuously -- use 'S' to resume stepping", " Q)uit"): instr_t.setpos(-(width / 2), y) instr_t.write(s, font=('sans-serif', 14, 'normal')) y -= line_height
''' This function will filter two lists, removing duplicates from the first list It sums up the values of the removed duplicates and puts those in the new list Values in the first list and second list coorespond to each other ------------------- Application ------------------- Can be used with data from finicial application ß ''' def filter_sum(list1,list2): a = sorted(zip(list1,list2)) b = list(zip(*a)) list1 = b[0] list2 = b[1] c = Counter(list1) d = list(c.keys()) counted = list(c.values()) mega = [] omega = [] count = 0 for i in counted: mega+=[list(list1[count:count+i])] omega+=[list(list2[count:count+i])] count += i new_list2 = [] for i in omega: new_list2 += [sum(i)] return d,new_list2
def add(a,b): return str(a+b) def sub(a,b): return str(a-b) def mul(a,b): return str(a*b) def div(a,b): return str(a/b) print("selectt operation") print("1.Add") print("2.subtraction") print("3.multiply") print("4.div") choice=input("enter the choice(1 or 2 or 3 or 4)=") a=int(input("enter the fst numb=")) b=int(input("enter the second numb=")) if choice=="1": print(a,'+',b,'=',add(a,b)) elif choice=="2": print(a,'-',b,'=',sub(a,b)) elif choice == "3": print(a,'*',b,'=',mul(a,b)) elif choice=="4": print(a,'/',b,'=',div(a,b))
def quicksort(arr): if len(arr) <= 2: return arr else: pivot = arr[0] less = [n for n in arr[1:] if n < pivot] greater = [n for n in arr[1:] if n >= pivot] return quicksort(less) + [pivot] + quicksort(greater) arr = [1,3,4,5,3,7,8,1,2] arr2= [9,9,1,3,4,5,3,7,8,1,2] print(quicksort(arr2)) print(sorted(arr2)) print([2] + [3,5,6,1])
""" Tests for tree """ import unittest from tree import BSTNode from tree import Tree class TestBSTNode(unittest.TestCase): def test_init(self): test_node = BSTNode(5) self.assertEqual(test_node.value, 5) def test_append(self): test_node = BSTNode(5) test_node.append(BSTNode(3)) self.assertEqual(test_node.left.value, 3) self.assertEqual(test_node.right, None) def test_append_multi(self): test_node = BSTNode(5) test_node.append(BSTNode(3)) test_node.append(BSTNode(1)) test_node.append(BSTNode(4)) self.assertEqual(test_node.left.right.value, 4) self.assertEqual(test_node.left.left.value, 1) class TestTree(unittest.TestCase): def test_init(self): test_tree = Tree() self.assertEqual(test_tree.head, None) def test_add(self): test_tree = Tree() test_tree.add(5) self.assertIsInstance(test_tree.head, BSTNode) def main(): unittest.main() if __name__ == '__main__': main()
""" Write code to find the nth to last element of a linked list """ import unittest from linked_list import LinkedList class TestNthToLast(unittest.TestCase): def test_nth_to_last(self): ll_with_dups = LinkedList() ll_with_dups.append(2) ll_with_dups.append(3) ll_with_dups.append(2) ll_with_dups.append(5) ll_with_dups.append(6) ll_with_dups.append(1) ll_with_dups.append(2) ll_with_dups.append(999) self.assertEqual(ll_with_dups.nth_to_last(2).value, 1) self.assertEqual(ll_with_dups.nth_to_last(3).value, 6) self.assertEqual(ll_with_dups.nth_to_last(0).value, 999) def main(): unittest.main() if __name__ == '__main__': main()
 from time import sleep class Maze(object): """ draw : print current board am_i_out : not very usefull Playing : can_i_move move : perform move in the current dir turn_left turn_right Building the Maze : add_wall_horiz add_wall_vert """ def __init__(self, width, height, startX, startY): # private self._DIR_UP = 0 self._DIR_RIGHT = 1 self._DIR_DOWN = 2 self._DIR_LEFT = 3 self._wallToCheck = [ [0, 0], [1, 0], [0, 1], [0, 0], ] self._moves = [ [0, -1], [1, 0], [0, 1], [-1, 0], ] # public self.width = width self.height = height self.posX = startX self.posY = startY self.dir = self._DIR_RIGHT self.hWalls = [] self.vWalls = [] # init for j in range(height+2): tmp = [] for i in range(width+1): tmp.append(False) self.hWalls.append(tmp) for j in range(height+1): tmp = [] for i in range(width+2): tmp.append(False) self.vWalls.append(tmp) def get_char_or_space(self, cond, char): if cond: return char else: return ' ' def draw(self, turn): # for each line for j in range(self.height+1): # init seps = '+' cells = '' # for each col for i in range(self.width+1): # horiz line of sep if i is not self.width: seps += self.get_char_or_space(self.hWalls[j][i], '-') + '+' # horiz line of cells (with vert sep) cells += self.get_char_or_space(self.vWalls[j][i], '|') cells += self.get_char_or_space(self.posY == j and self.posX == i, 'X') # print print seps if j is not self.height: print cells print turn print '' def can_i_move(self): w2c = self._wallToCheck[self.dir] x = self.posX + w2c[0] y = self.posY + w2c[1] if (self.dir == self._DIR_UP) or (self.dir == self._DIR_DOWN): return not (self.hWalls[y][x]) else: return not (self.vWalls[y][x]) def am_i_out(self): return (self.posX < 0) or (self.posX > self.width-1) or (self.posY < 0) or (self.posY > self.height-1) def add_wall_horiz(self, x, y): if (x < 0) or (x > self.width) or (y < 0) or (y > self.height): print 'MAIS T4ES MALADE !!! -> add_wall_horiz()' else: self.hWalls[y][x] = True; def add_wall_vert(self, x, y): if (x < 0) or (x > self.width) or (y < 0) or (y > self.height): print 'MAIS T4ES MALADE !!! -> add_wall_vert()' else: self.vWalls[y][x] = True; def turn_left(self): self.dir = self._DIR_LEFT if (self.dir == self._DIR_UP) else (self.dir - 1) def turn_right(self): self.dir = self._DIR_UP if (self.dir == self._DIR_LEFT) else (self.dir + 1) def move(self): if not self.can_i_move(): return move = self._moves[self.dir] self.posX += move[0] self.posY += move[1] if self.am_i_out(): print 'Gagné !!' class MazeSolver(object): def __init__(self, MazeBuilder): self.maze = MazeBuilder() self.turn = 0 def solve(self): self.maze.draw(self.turn) while not self.maze.am_i_out(): self.your_turn() self.maze.draw(self.turn) self.turn += 1 sleep(0.1) def your_turn(self): print 'Implement this function (crete your class inheriting from class MazeSolver)'
import random EMPTY_CELL = 0 DIMENSION = 4 NEW_CELL_IS_2 = 2 NEW_CELL_IS_4 = 4 PROBABILITY_OF_4 = .25 def create_field(): ''' Get number of rows and columns in game field (N rows == N columns) and value that marks empty cell. Return game field as a list of lists. >>> create_field() [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] ''' return [ [EMPTY_CELL for _ in range(DIMENSION)] for _ in range(DIMENSION) ] def get_random_cell(): """ >>> 0 <= get_random_cell()[0] < DIMENSION True """ return \ random.randint(0, DIMENSION - 1), \ random.randint(0, DIMENSION - 1) def is_empty_cell(field, xy): ''' Get game field as list of lists and 2 coordinates of a cell as list or tuple. Return True if cell is empty, otherwise return False. >>> field = [[0, 2], [0, 0]] >>> is_empty_cell(field, [0, 0]) True >>> is_empty_cell(field, [0, 1]) False ''' row, column = xy return field[row][column] == EMPTY_CELL def get_new_xy(field): ''' Get game field as list of lists. Generate new coordinates until corresponding cell is empty. ''' while True: xy = get_random_cell() if is_empty_cell(field, xy): return xy def get_column(field, y): ''' Get game field and column index. Return column as a list. >>> get_column([[2, 4], [0, 2]], 0) [2, 0] >>> get_column([[2, 4], [0, 2]], 1) [4, 2] ''' return [row[y] for row in field] def get_row(field, x): ''' >>> get_string([[1, 2], [3, 4]], 0) [1, 2] >>> get_string([[5, 6], [7, 8]], 1) [7, 8] ''' return field[x] def shift_values(column, up=True): ''' Get column. Shift non-empty cells to the beginning (if up) or end (if down) of the list. Return shifted column. >>> shift_values([2, 2, 0, 2]) [2, 2, 2, 0] >>> shift_values([0, 2, 0, 4], False) [0, 0, 2, 4] >>> shift_values([4, 0, 0, 2]) [4, 2, 0, 0] >>> shift_values([2, 4, 2, 0], False) [0, 2, 4, 2] ''' empties = column.count(EMPTY_CELL) column = remove_empties(column) return column + get_empties(empties) if up \ else get_empties(empties) + column def get_empties(empties): return [EMPTY_CELL for _ in range(empties)] def remove_empties(column): return [cell for cell in column if cell != EMPTY_CELL] def merge_values(column, up=True): ''' Get column. Merge non-empty equal values, add empty cells. Return merged column. >>> merge_values([2, 2, 2, 0]) [4, 2, 0, 0] >>> merge_values([2, 2, 2, 2]) [4, 4, 0, 0] >>> merge_values([2, 2, 2, 2], False) [0, 0, 4, 4] >>> merge_values([0, 2, 2, 2], False) [0, 0, 2, 4] >>> merge_values([2, 2, 2, 0]) [4, 2, 0, 0] ''' if up: _merge_column( column, direction=1, start=0, end=DIMENSION - 1, insert=DIMENSION ) else: _merge_column( column, direction=-1, start=DIMENSION - 1, end=0, insert=0 ) return column def _merge_column(column, direction, start, end, insert): for i in range(start, end, direction): if column[i] != EMPTY_CELL and column[i] == column[i + direction]: column[i] *= 2 column.pop(i + direction) column.insert(insert, EMPTY_CELL) def return_column(field, column, y): ''' Get game field, column and column index. Replace column in game field with a new one. >>> return_column([[2, 2, 2, 2], [2, 2, 4, 0], [0, 2, 0, 0], [0, 0, 0, 0]], [4, 2, 0, 0], 1) [[2, 4, 2, 2], [2, 2, 4, 0], [0, 0, 0, 0], [0, 0, 0, 0]] ''' for x, value in enumerate(column): field[x][y] = value return field def return_row(field, row, x): field[x] = row return field def output(field): row_max = [len(str(max(row))) for row in zip(*field)] line = ('-') * (sum(row_max) + DIMENSION + 1) print(line) for row in field: print('', end='|') for index, cell in enumerate(row): print(str(cell).rjust(row_max[index]), end='|') print('\n' + line) # zip merge # for v1, v2 in list(zip(l, l[1:] + [0])): # if skip: # skip = False # continue # if v1 == v2: # res.append(v1 + v2) # skip = True # else: # res.append(v1) def generate_number(): return NEW_CELL_IS_2 \ if random.random() > PROBABILITY_OF_4 \ else NEW_CELL_IS_4 def shift_field_vertically(up, field): ''' Get field and direction of shift (up or down). Make shift of every column of the field. Return shifted field. >>> shift_field_vertically(False, [[2,2,2,4], [2,2,2,4],[0,0,0,0],[2,2,0,0]]) [[0, 0, 0, 0], [0, 0, 0, 0], [2, 2, 0, 0], [4, 4, 4, 8]] >>> shift_field_vertically(True, [[2,2,2,4], [2,2,2,4],[0,0,0,0],[2,2,0,0]]) [[4, 4, 4, 8], [2, 2, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] ''' for y in range(DIMENSION): column = get_column(field, y) new_column = merge_values(shift_values(column, up), up) return_column(field, new_column, y) return field def shift_field_horisontally(left, field): ''' Get field and direction of shift (left or right). Make shift of every row of the field. Return shifted field. >>> shift_field_horisontally(False, [[2,2,2,4], [4,2,2,2],[0,0,0,0],[2,2,0,0]]) [[0, 2, 4, 4], [0, 4, 2, 4], [0, 0, 0, 0], [0, 0, 0, 4]] >>> shift_field_horisontally(True, [[2,2,2,4], [4,2,2,2],[0,0,0,0],[2,2,0,0]]) [[4, 2, 4, 0], [4, 4, 2, 0], [0, 0, 0, 0], [4, 0, 0, 0]] ''' for x in range(DIMENSION): row = get_row(field, x) new_row = merge_values(shift_values(row, left), left) return_row(field, new_row, x) return field def check_gameover(field): ''' Get field. Return True if there is no empty cells in field, else False. >>> check_gameover([[2,2,2,4], [4,2,2,2],[2,2,4,2],[2,2,4,0]]) False >>> check_gameover([[2,2,2,4], [4,2,2,2],[2,2,4,2],[2,2,4,2]]) True ''' for row in field: if EMPTY_CELL in row: return False return True
#!/usr/bin/env python3 import sys insurance_dict = {'endowment_insurance':0.08, 'medical_insurance':0.02, 'unemplotment_insurance':0.005, 'injury_insurance':0, 'maternity_insurance':0, 'provient_found':0.06} staff_dict = {} def get_input(): if len(sys.argv) == 1: print("Parameter Error") return None for i in range(len(sys.argv)): if i == 1: continue inputList = sys.argv[i-1].split(':') try: income = int(inputList[1]) key = int(inputList[0]) except ValueError: print("Parameter Error") return None staff_dict[key] = income return True def calculate_insurance(income,insuranceSum): return income * insuranceSum def calculate_tax(income,insurance): incomeTax = income - insurance - 3500 if incomeTax <= 0: tax = 0 elif incomeTax <= 1500: tax = incomeTax * 0.03 elif incomeTax <=4500: tax = incomeTax * 0.10 - 105 elif incomeTax <= 9000: tax = incomeTax * 0.20 - 555 elif incomeTax <= 35000: tax = incomeTax * 0.25 - 1005 elif incomeTax <= 55000: tax = incomeTax * 0.30 - 2755 elif incomeTax <= 80000: tax = incomeTax * 0.35 - 5505 else: tax = incomeTax * 0.45 - 13505 return tax def calulate_finalIncome(income): insurance = calculate_insurance(income, insuranceSum) tax = calculate_tax(income, insurance) final_income = income - insurance - tax final_income = format(final_income,".2f") return final_income if __name__ == '__main__': insuranceSum = 0 for value in insurance_dict.values(): insuranceSum += value if get_input() == True: for key,value in staff_dict.items(): value = calulate_finalIncome(value) print("%d:%s" %(key,value))
#Q1 def mult(s,n=6): return s*n #Q2 def greeting(name,greeting="Hello ", excl="!"): return greeting + name + excl print(greeting("Bob")) print(greeting("")) print(greeting("Bob", excl="!!!")) #Q3 def sum( intx,intz=5): return intz + intx #Q4 def test(int,boole=True,dict1={2:3, 4:5, 6:8}): if boole: if int in dict1.keys(): return dict1[int] else: return boole #Q5 def checkingIfIn(str,direction=True,d={'apple': 2, 'pear': 1, 'fruit': 19, 'orange': 5, 'banana': 3, 'grapes': 2, 'watermelon': 7}): if direction: if str in d.keys(): return True else: return False else: if str not in d.keys(): return True else: return False #Q6 def checkingIfIn(a, direction = True, d = {'apple': 2, 'pear': 1, 'fruit': 19, 'orange': 5, 'banana': 3, 'grapes': 2, 'watermelon': 7}): if direction == True: if a in d: return d[a] else: return False else: if a not in d: return True else: return d[a] # Call the function so that it returns False and assign that function call to the variable c_false c_false=checkingIfIn('strawberry') # Call the fucntion so that it returns True and assign it to the variable c_true c_true=checkingIfIn('litchi',direction=False) # Call the function so that the value of fruit is assigned to the variable fruit_ans fruit_ans=checkingIfIn('fruit') # Call the function using the first and third parameter so that the value 8 is assigned to the variable param_check param_check=checkingIfIn('litchi',False,{'litchi':8})
class Module(): """ Class representing modules. """ def __init__(self, name=None, parent=None): self.name = name self.submodules = [] self.wires = [] self.parent = self if (parent == None) else parent def setName(self, name): self.name = name def addModule(self, module): self.submodules += [module] def addWire(self, wire): self.wires += [wire] def __str__(self): res = "Module {0}:\n".format(self.name) for wire in self.wires: res += "\t{0}\n".format(wire) for module in self.submodules: res += "{0}\n".format(module) return res.strip()
''' Finnian Wengerd Algorithms Daniel Showalter Eastern Mennonite University Job Scheduling: Stress Level and Optimum Value (BOTTOM-UP) ''' ''' .................................................................................................................................................... Given a sequence of n weeks, the manager must come up with a plan of action with the options: low-stress, high-stress, or rest resulting in the optimum sequence to bring in the most revenue. The problem: Given sets of values l1, l2,....ln and h1, h2,....,hn, find a plan of maximum value (revenue). (Such a plan will be called optimal). ..................................................................................................................................................... ''' from datetime import datetime import random opt_cache = { -1:0, #This begins the cache with pre-determined values for indexes of i less than 1 0:0, } '''Recursive function that returns the optimum value of the given parameter i''' def OPT(i): optimum_i = 0 #print(i, opt_cache) if (opt_cache.get(i)!= None): return opt_cache[i], plan else: optimum_i = max((l[i-1]+OPT(i-1)[0]),(h[i-1]+OPT(i-2)[0])) opt_cache[i] = optimum_i if optimum_i == (l[i-1]+OPT(i-1)[0]): plan[i-1]=("l") elif optimum_i == (h[i-1]+OPT(i-2)[0]): plan[i-2] = "r" plan[i-1]=("h") return optimum_i, plan '''Starting function that focuses on integrating each test case and deals with printing out the results (True if the expected result is equal to the optimum value)''' def My_Print(l,h, expected): plan = [0]*len(h) starttime = datetime.now() for i in range(len(l)): return_value = OPT(i) optimum_value = return_value[0] plan = return_value[1] #print(expected == optimum_value) endtime = datetime.now() deltaT = endtime-starttime totalTime.append(deltaT.total_seconds()) return deltaT ''' Start Code ''' totalTime = [] deltaT = 0 l = [] h=[] for i in range(50): i = random.randint(0,1000) l.append(i) for i in range(50): i = random.randint(0,1000) h.append(i) expected = 16969 plan = [0]*len(h) for i in range(1000): My_Print(l,h, expected) totalseconds = 0 averageTime = 0 for i in totalTime: totalseconds +=i averageTime = (totalseconds/len(totalTime)) print("Average runtime: %f seconds." %(averageTime))
#The football.csv file contains the results from the English Premier League. # The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of # goals scored for and against each team in that season (so Arsenal scored 79 goals # against opponents, and had 36 goals scored against them). Write a program to read the file, # then print the name of the team with the smallest difference in ‘for’ and ‘against’ goals. # The below skeleton is optional. You can use it or you can write the script with an approach of your choice. import csv def read_data(data): list = [] with open(data, 'rb') as csvfile: reader = csv.DictReader(csvfile) for row in reader: list.append(row) return list def get_min_score_difference(list): #(self, parsed_data): imin = 0 min = abs( int(list[0]['Goals']) - int(list[0]['Goals Allowed']) ) for i in range(1, len(list)): diff = abs( int(list[i]['Goals']) - int(list[i]['Goals Allowed']) ) if diff < min: imin = i min = diff return imin def get_team (list, imin): #(self, index_value, parsed_data): return list[imin]['Team'] list = read_data( 'football.csv' ) imin = get_min_score_difference( list ) team = get_team( list, imin ) print team
# This program shows implementation of stack data stucture in python using list class Stack : def __init__(self): self.list_of_items = [] def push(self,item): self.list_of_items.append(item) def pop(self): self.list_of_items.pop() #inbuilt pop operation for lists to remove and return topmost item of the stack def isEmpty(self): if not self.list_of_items: #to check for an empty list return True def peek(self): print(self.list_of_items[-1]) #returns topmost element of the stack def stack_items(self): print(self.list_of_items) def main() a=Stack() if (a.isEmpty()==True): a.push('A') a.push('B') a.push('C') a.push('D') a.stack_items() a.pop() a.pop() a.stack_items() a.push('2') a.stack_items() a.peek() else : print("Stack is not empty .It has following elements on it : ") a.stack_items() if __name__ == "__main__": main()
import datetime # Health Management System. # 3 clients - Harry , Rohan and Hmmad def gettime(): # to add date and time in log return datetime.datetime.now() def storedata(userinput): # for input Data for User. if userinput == 1: # Harry c = int(input("Enter 1 for Exercise and 2 for Food")) if c == 1: value = input("Enter your Exercise\n") with open("Harry-exercise.txt", "a") as op: op.write(str([str(gettime())])+" : " + value+"\n") print("Successfully Written Value.") elif c == 2: value = input("Enter your Food\n") with open("Harry-food.txt", "a") as op: op.write(str([str(gettime())]) + " : " + value + "\n") print("Successfully Written Value.") elif userinput == 2: # Rohan c = int(input("Enter 1 for Exercise and 2 for Food")) if c == 1: value = input("Enter your Exercise\n") with open("Rohan-exercise.txt", "a") as op: op.write(str([str(gettime())])+" : " + value+"\n") print("Successfully Written Value.") elif c == 2: value = input("Enter your Food\n") with open("Rohan-food.txt", "a") as op: op.write(str([str(gettime())]) + " : " + value + "\n") print("Successfully Written Value.") elif userinput == 3: # Hmmad c = int(input("Enter 1 for Exercise and 2 for Food")) if c == 1: value = input("Enter your Exercise\n") with open("Hmmad-exercise.txt", "a") as op: op.write(str([str(gettime())])+" : " + value+"\n") print("Successfully Written Value.") elif c == 2: value = input("Enter your Food\n") with open("Hmmad-food.txt", "a") as op: op.write(str([str(gettime())]) + " : " + value + "\n") print("Successfully Written Value.") else: print("You enter un-valid input") else: print("Please Enter valid input between 1 to 3") def output(userinput): # for user Showinng output for data. if userinput == 1: # Harry c = int(input("Enter 1 for Exercise and 2 for Food")) if c == 1: with open("Harry-exercise.txt") as op: for i in op: print(i, end="") elif c == 2: with open("Harry-food.txt") as op: for i in op: print(i, end="") else: print("You enter un-valid input") elif userinput == 2: # Rohan c = int(input("Enter 1 for Exercise and 2 for Food")) if c == 1: with open("Rohan-exercise.txt") as op: for i in op: print(i, end="") elif c == 2: with open("Rohan-food.txt") as op: for i in op: print(i, end="") else: print("You enter un-valid input") elif userinput == 3: # hmmad c = int(input("Enter 1 for Exercise and 2 for Food")) if c == 1: with open("Hmmad-exercise.txt") as op: for i in op: print(i, end="") elif c == 2: with open("Hmmad-food.txt") as op: for i in op: print(i, end="") else: print("You enter un-valid input") else: print("Please Enter valid input between 1 to 3") print("Welcame to Health Management System \n") log_ID = "Admin" log_PASS = "Admin" # we put User Inputs in Varibles. print("If you want to exit this program plase press Q") ID_system = input("Please Enter Your ID.\n") print("\n") while ID_system != log_ID: if ID_system == "q": break print("Acess Not Allowed\n") ID_system = input("Please Enter Your ID.\n") print("\n") # here serect work in script if (log_ID == ID_system): PASS_system = input("Please Enter Your PASSWORD.\n") print("\n") while PASS_system != log_PASS: if ID_system == "q": break print("Acess Not Allowed\n") PASS_system = input("Please Enter Your PASSWORD.\n") print("\n") if (log_PASS == PASS_system): print("Acess Allowed") a = int(input("Press 1 for enter the values or Press 2 for enter show values")) if a == 1: b = int(input("Press 1 for Harry , Press 2 for Rohan , Press for Hmmad")) storedata(b) elif a == 2: b = int(input("Press 1 for Harry , Press 2 for Rohan , Press for Hmmad")) output(b) else: print("Your Enterd incorrent Value Please try again")
''' Your function should take in a single parameter (a string `word`) Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters. Your function must utilize recursion. It cannot contain any loops. ''' # added count to function definition so that it may increment as it recurses def count_th(word, count = 0): if len(word) < 2: #base case return count #if th in word we slice from 2nd index, else from 1st index if word[:2] == 'th': count += 1 return count_th(word[2:], count) else: return count_th(word[1:], count)
#imports import csv #Variables current_ID = 1 new_additions = [] filename = "library.csv" fields = ['ID', 'Title', 'Author', 'Genre', 'Year', 'Location'] data = [] #Code print("------Welcome to the Python Library organiser------") choice = "" while choice.lower() != "x": print("""What would you like to do? 1 - Add a book 2 - Display your Books 3 - Search for a Book""") choice = input(">") if choice == "1": #Code to add a record elif choice == "2": #Display the data elif choice == "3": #Search the data #Display the results elif choice.lower() == "x": print("Thank you! Shutting down.") else: print("Sorry, I didnt recognise that option")
""" This script will extract the customer service offering information that is stored in SNOW """ from openpyxl import load_workbook def get_worksheet_table(worksheet, table_name): """ Get all tables from a given workbook. Returns a dictionary of tables. Requires a filename, which includes the file path and filename. """ # Load the workbook, from the filename # wb = load_workbook(filename=filename, read_only=False, keep_vba=False, data_only=True, keep_links=False) # Initialize the dictionary of tables service_offerings_list = [] for tbl in worksheet._tables: if tbl.name == table_name: # Grab the 'data' from the table data = worksheet[tbl.ref] # Now convert the table 'data' to a Pandas DataFrame # First get a list of all rows, including the first header row rows_list = [] for row in data: # Get a list of all columns in each row cols = [] for col in row: cols.append(col.value) rows_list.append(cols) # for column_name in rows_list[0]: # print("Column name:" + str(column_name)) # reader = csv.DictReader((row[0] for row in rows_list)) # for offering_row in reader: # print("Number: " + str(offering_row['Number']) + "Name: " + str(offering_row['Name'])) header_columns = [col.upper() for col in rows_list[0]] for data_row in rows_list[1:]: service_offering_dict = zip(header_columns, data_row) service_offerings_list.append(dict(service_offering_dict)) return service_offerings_list def list_defined_tables(worksheet): for tbl in worksheet._tables: print(" : " + tbl.displayName) print(" - name = " + tbl.name) print(" - type = " + tbl.tableType if isinstance(tbl.tableType, str) else 'n/a') print(" - range = " + tbl.ref) print(" - #cols = %d" % len(tbl.tableColumns)) for col in tbl.tableColumns: print(" : " + col.name) if __name__ == "__main__": service_offering_excel_workbook = "C:\\Users\\dhartman\\Documents\\Support\\AWS-Resources-Production.xlsx" # Run the function to return a dictionary of all tables in the Excel workbook # tables_dict = get_all_tables(filename=service_offering_excel_workbook) wb = load_workbook(filename=service_offering_excel_workbook, data_only=True) ws = wb["ServiceOfferings"] service_offerings_table = get_worksheet_table(ws, "SERVICE_OFFERINGS") filtered_offerings_list = [row for row in service_offerings_table if "INNIO" in row['COMPANY'].upper()] print(str(filtered_offerings_list))
def insertion_sort(A): for i in range(1, len(A)): key = A[i] j = i-1 while j >= 0 and key < A[j]: A[j+1] = A[j] j -= 1 A[j+1] = key def recurse_insertion(A, n): if n == 1: A[0] = A[0] elif n > 1: recurse_insertion(A, n-1) key = A[n-1] i = n-2 while i >= 0 and key < A[i]: A[i+1] = A[i] i -= 1 A[i+1] = key def main(): A = [6,1,3,4,2] recurse_insertion(A, 5) print(A) if __name__ == '__main__': main()
def merge(A, p, q, r): L = [0] * (q-p+1) R = [0] * (r-q) for i in range(len(L)): L[i] = A[p+i] for j in range(len(R)): R[j] = A[q+j+1] i = 0 j = 0 for k in range(p, r+1): if i >= len(L): A[k] = R[j] j += 1 elif j >= len(R): A[k] = L[i] i += 1 elif L[i] <= R[j]: A[k] = L[i] i += 1 else: A[k] = R[j] j += 1 def merge_sort_aux(A, p, r): if p < r: q = (p+r)//2 merge_sort_aux(A, p, q) merge_sort_aux(A, q+1, r) merge(A, p, q, r) def merge_sort(A): merge_sort_aux(A, 0, len(A)-1)
""" matrixes and conditions example - Michael """ import numpy as np import scipy as sp from scipy.linalg import hilbert # matrix definition A = np.matrix(([2, 3, 4], [1, 1, 1], [3, 4, 4])) AA = np.array(([2, 3, 4], [1, 1, 1], [3, 4, 4])) print('A=', A) print('AA=', AA) print('A*AA=', A*AA) # multiplaction matrix invA = np.linalg.inv(A) print('inv(A)=', invA) # opposite matrix print('A*inv(A)=', A*invA) # get matrix component print(A[0, 0]) B = np.zeros((3, 4), dtype=int) # matrix of zeros print('B=', B) C=np.ones((3, 4), dtype=int) # matrix of ones print('C=', C) # define hilbert matrix H(i,j)=1/(i+j+1) H = hilbert(4) print('H=', H) print('condition of H:', np.linalg.cond(H)) # cond of Hilbert matrix size 4 # implement solution of H*x=b with small error in initinal conditions b = np.matrix(([1], [1], [1], [1])) print('b', b) #solve x1=inv(H)*b x1 = np.linalg.inv(H)*b print('x1=', x1) # let's increase H[4,4] by 1%, H[4,4]=H[4,4]*1.01 H[3,3] = H[3, 3]*1.01 print('H=', H) x2 = np.linalg.inv(H)*b print('x1=', x2)
import numpy as np import sympy as sy x = sy.Symbol('x') # x is symbol varible so in f varible we can change the function and it will work because f is also symbol print('π = ', np.pi) # pi check def PI(n): i = 1 sum = 0 while i <= n: sum = sum + ((-1)**(i-1)*1/(2*i-1)) i = i + 1 sum = sum * 4 return sum n10 = PI(10) print('π with n = 10 is: ', n10) print('Absolute Error between π and n = 10 is: ', abs(np.pi - n10)) print('Relative Error between π and n = 10 is: ', abs(np.pi - n10)/abs(np.pi)) n20 = PI(20) print('π with n = 20 is: ', n20) print('Absolute Error between π and n = 20 is: ', abs(np.pi - n20)) print('Relative Error between π and n = 20 is: ', abs(np.pi - n20)/abs(np.pi)) n40 = PI(40) print('π with n = 40 is: ', n40) print('Absolute Error between π and n = 40 is: ', abs(np.pi - n40)) print('Relative Error between π and n = 40 is: ', abs(np.pi - n40)/abs(np.pi))
#Author:黄国栋 age=23 num=0 while num<3: age1=int(input("请输入年龄:")) if age==age1: print("猜对了") break elif age<age1: print("猜大了") else: print("猜小了") num+=1 if num==3: print("您已经超过三次机会。。。不好意思,小爷不陪你玩了")
''' This script is just to study the basics of colour manipulations. Pretty self explanatory. ''' from SimpleCV import * def main(): img = Image("simplecv") #Playing with Scaling thumbnail = img.scale(90,90) thumbnail = thumbnail.show() #Playing with erosion eroded = img.erode() eroded.show() #Effect of cropping cropped = img.crop() cropped.show()
# LEVEL 23 # www.pythonchallenge.com/pc/hex/bonus.html import this # ROT13 first = ord('a') last = ord('z') str1 = "".join([chr(x) for x in range(first, last + 1)]) str2 = "".join([chr(first + x + 13 - last - 1) if x + 13 > last else chr(x + 13) for x in range(first, last + 1)]) print(str1) print(str2) table = str.maketrans(str1, str2) print('va gur snpr bs jung?'.translate(table)) # in the face of what?
# LEVEL 15 # http://www.pythonchallenge.com/pc/return/uzi.html import calendar import datetime for year in range(2016, 1582, -1): if calendar.isleap(year): if datetime.date(year, 1, 1).weekday() == 3: # 3=Thursday if str(year)[0] == '1' and str(year)[3] == '6': print(year)