text
stringlengths
37
1.41M
import math def running_median(stream): # Fill this in. # Define accumulator acc = [] # Iterate over the stream for n in stream: # Push and sort accumulator acc.append(n) acc.sort() # Find median element index size = len(acc) if size % 2 == 1: # Odd size is just the number in the middle idx = math.floor(size / 2) median = acc[idx] else: # Even size is average between the two in the middle # Find lower and upper bounds for the range to sum and divide idx_dn = int(size / 2) - 1 idx_up = idx_dn + 2 median = sum(acc[idx_dn:idx_up]) / 2 # Spit it out print(median) running_median([2, 1, 4, 7, 2, 0, 5]) # 2 1.5 2 3.0 2 2.0 2
class calculate: def __init__(self,num): self.result = num def plus(self, num): self.result += num return self.result def minus(self, num): self.result -= num return self.result def multi(self, num): self.result = self.result * num return self.result def divide(self, num): if num == 0: print('0으로 나눌 수 없습니다.') else: self.result = self.result / num return self.result num_two = int(input('숫자를 입력하시오')) c = calculate(num_two) while True: operation = input('원하는 사칙연산을 입력하시오(예 : + ) : ') num_one = int(input('숫자를 입력하시오')) ending = input('등호를 입력하시면 결과가 산출됩니다.') if ending == '=': if operation == '+': c.plus(num_one) print(c.result) elif operation == '-': c.minus(num_one) print(c.result) elif operation == '*': c.multi(num_one) print(c.result) elif operation == '/': c.divide(num_one) print(c.result) else: operation = input('사칙연산만 입력해주십시오 : ')
# The program demonstrates an environment to perform an analysis of the frequencies of a two-channel wave audio source. For this step, # DTFT (Discrete Time Fourier Transform) of the wave audio source (a wave file) is performed. # Assuming that the necessary analysis is performed, next step is to "sew back" the original wave audio from the frequency information. # For this, the IDTFT (Inverse Discrete Time Fourier Transform)is used. To play the reconstructed wave audio, the contents are written # into a output wave file "Output.wav". Playback of this file is attempted to verify the authenticity of the reconstructed data. # Importing the essential sound and plot modules import winsound import wave import matplotlib.pyplot as plt import numpy as np # Importing the essential FFT/DTFT and IFFT/IDTFT modules from scipy.fftpack import fft, ifft from scipy.io import wavfile # get the api # Defining the source and destination files. These should be present in the same folder as of this script file. source = r".\input file.wav" destination = r".\output file.wav" # Play the source audio file for the listener winsound.PlaySound(source, winsound.SND_FILENAME) # Step 1: Perform DTFT of the source audio fs, data = wavfile.read(source) # load the data data = data.T[0] # This is to extract information from the first channel of the two channel soundtrack # Plot the audio data in a chart. This is how the audio "looks" like in the time domain. plt.figure(1) plt.plot(data,'r') plt.title("Time Domain of Input Audio. Closing these windows will start Step 2.") plt.xlabel("time") plt.ylabel("amplitude") fftdata = fft(data) # calculate fourier transform (complex numbers list) xval = np.linspace(0.,fs,(len(fftdata)-1)) # Plot the frequency data, which is the output of the DTFT plt.figure(2) plt.plot(xval, abs(fftdata[:(len(fftdata)-1)]),'r') plt.title("Frequency Spectrum of Input Audio. Closing these windows will start Step 2.") plt.xlabel("frequency samples") plt.ylabel("amplitude") plt.show() # Step 2: Perform IDTFT of the frequency data ifftdata = ifft(fftdata) ifftdataround = np.round(ifftdata).astype('int16') # Write the reconstructed results into the output wave file. wavfile.write(destination,fs,ifftdataround) # Play the wave file winsound.PlaySound(destination, winsound.SND_FILENAME) # Plot the timeline of the reconstructed wave audio. plt.figure(3) plt.plot(ifftdata.real, 'g') plt.title("Time domain of Reconstructed Audio") plt.xlabel("time") plt.ylabel("amplitude") plt.show() # End of program. Designed and implemented by Varun Chandramohan, 2016.
# -*- coding: utf-8 -*- """ Created on Thu Feb 25 18:51:48 2021 @author: R005 """ #Leer una tabla de multiplicar e imprimir dicha tabla desde el 1 hasta el 20 #y sumar sus resultados. Usar para la solución ciclo While #Declarar variables tabla=0 resultado=0 sumaresultados=0 conrepciclo=1 multiplicador=1 #Leer el número de la tabla para la cual vamos a realizar las operaciones tabla=int(input("Tabla:")) #Leer el multiplicador multiplicador=int(input("multiplicador:")) #Inicio del ciclo repetitio while(conrepciclo <= multiplicador): resultado=tabla*conrepciclo sumaresultados=sumaresultados+resultado print(tabla,"*",conrepciclo, "=",resultado) #Incrementar la variable que controla el ciclo conrepciclo=conrepciclo+1 print("La suma de los resultados es :",sumaresultados)
# -*- coding: utf-8 -*- """ Created on Mon Mar 22 20:30:45 2021 @author: R005 Se realiza la carga de 10 valores enteros por teclado. Se desea conocer: a) La cantidad de valores ingresados negativos. b) La cantidad de valores ingresados positivos. c) La cantidad de múltiplos de 15. d) El valor acumulado de los números ingresados que son pares. """ num=int(input("Digite cantidad de números:")) positivos=0 negativos=0 cero=0 multiplos15=0 parespositivos=0 paresnegativos=0 sumapares=0 for x in range (num): n=int(input("Digite números: ")) if n>0: positivos=positivos+1 else: if n<0: negativos=negativos+1 else: cero=cero +1 if n%15==0 and n>=15: multiplos15=multiplos15+1 if n%2==0 and n>=2: parespositivos=parespositivos+n if n%-2==0 and n<=-2: paresnegativos=paresnegativos+n sumapares=parespositivos+paresnegativos print() print("Cantidad positivos: ",positivos) print("Cantidad negativos: ",negativos) print("Cantidad cero: ",cero) print("Cantidad multiplos de 15: ",multiplos15) print("Acumulado pares: ",sumapares)
# -*- coding: utf-8 -*- """ Created on Mon Mar 22 14:02:21 2021 @author: Sebastian Marulanda Correa Ejercicio 13 curso. funciones Python Definir por asignación una lista de enteros en el bloque principal del programa. Elaborar tres funciones, la primera recibe la lista y retorna la suma de todos sus elementos, la segunda recibe la lista y retorna el mayor valor y la última recibe la lista y retorna el menor. """ def sumarizar(lista): suma=0 for x in range(len(lista)): suma=suma+lista[x] return suma def mayor(lista): may=lista[0] for x in range(1,len(lista)): if lista[x]>may: may=lista[x] return may def menor(lista): men=lista[0] for x in range(1,len(lista)): if lista[x]<men: men=lista[x] return men # bloque principal del programa listavalores=[1, 2, 3, 4, 5] print("La lista completa es") print(listavalores) print("La suma de todos su elementos es", sumarizar(listavalores)) print("El mayor valor de la lista es", mayor(listavalores)) print("El menor valor de la lista es", menor(listavalores))
# -*- coding: utf-8 -*- """ Created on Mon Mar 22 14:42:45 2021 @author: Sebastian Marulanda Correa Ejercicio 17 curso. funciones Python Definir una lista de enteros por asignación en el bloque principal. Llamar a una función que reciba la lista y nos retorne el producto de todos sus elementos. Mostrar dicho producto en el bloque principal de nuestro programa. """ def producto(lista): prod=1 for x in range(len(lista)): prod=prod*lista[x] return prod # bloque principal lista=[1, 2, 3, 4, 5] print("Lista:", lista) print("Multiplicacion de todos sus elementos:",producto(lista))
# -*- coding: utf-8 -*- """ Created on Thu Feb 18 19:44:26 2021 @author: SEBASTIAN MARULANDA CORREA """ #solicita al usuario ingresar por teclado 3 números diferentes print("ingrese 3 numeros enteros diferenetes") #Variable denominada e tipo entero, para solicitar al usuario que ingrese 1 o 2 según el orden #en que desea que se organicen los números e = int(input("elija 1 si lo quiere de mayor a menor y 2 si lo quiere de menor a mayor")) #Variable denominada a, tipo entero, para solicitar al usuario que ingrese por teclado el primer número a = int(input("ingrese el numero a")) #Variable denominada b, tipo entero, para solicitar al usuario que ingrese por teclado el segundo número b = int(input("ingrese el numero b")) #Variable denominada c, tipo entero, para solicitar al usuario que ingrese por teclado el tercer número c = int(input("ingrese el numero c")) #Utiliza condicional if para que al usar el operador == compare e con 1 y si es verdadero ejecute a la línea siguiente #basicamente desde este condicional si el usuario escogió la opción 1 al principio del programa ejecutaría algortimo #oganizando los números de mayor a menor if (e == 1): #Una vez el usuario ha seleccionado la opción 1, se empieza a comparar a como el mayor respecto a b y c #si se cumple la condición anterior se compara si a es mayor que b if (a > b): #si se cumple la condición anterior se compara si a es mayor que c if (a > c): #si se cumple la condición anterior se compara si b es mayor que c if(b > c): #si se cumplen las condiciones anteriores se imprima el resultado de las variables en orden a,b,c siendo a el mayor, #b el valor medio y c el menor print(a, b, c) #si no se cumplen las condiciones anteriores else: #se imprime los número en orden a,c,b. Siendo a el mayor, c el intermedio y b el menor print(a, c, b) #Una vez el usuario ha seleccionado la opción 1, se empieza a comparar c como el mayor respecto a a y b #Si c es mayor que a ejecuta línea siguiente if (c > a): #si c es mayor que b ejecuta la siguiente línea if (c > b): #si b es mayor que a ejecuta la siguiente línea if(b > a): #al cumplir las ultimas condiciones anteriores imprime los números en orden c,b,a. siendo c el mayor, b el intermedio #y a el menor print(c, b, a) #si no se cumple lo anterior else: #imprime c como el mayor, a el intermedio y b el menor print(c, a, b) #Una vez el usuario ha seleccionado la opción 1, se empieza a comparar b como el mayor respecto a a y c #Si b es mayor que a se ejecuta la siguiente línea if (b > a): #Si b es mayor que c se ejecuta la siguiente línea if (b > c): #Si a es mayor que c se ejecuta la siguiente línea if(a > c): #al cumplir las ultimas condiciones anteriores imprime los números en orden b,a,c. siendo b el mayor, a el intermedio #y c el menor print(b, a, c) #si no se cumplen estas condiciones entonces else: #imprime b como el mayor, c el intermedio y a el menor print(b, c, a) #Utiliza condicional if para que al usar el operador == compare e con 2 y si es verdadero ejecute a la línea siguiente #basicamente desde este condicional si el usuario escogió la opción 2 al principio del programa ejecutaría algortimo #oganizando los números de menor a mayor if (e == 2): #Una vez el usuario ha seleccionado la opción 2, se empieza a comparar a como el menor respecto a b y c #si se cumple la condición anterior se compara si a es menor que b if (a < b): #si a es menor que c ejecuta la siguiente línea if (a < c): #si b es menor que c ejecuta siguiente línea if(b < c): #dado el cumplimiento de condiciones anteriores se imprimirian los números en orden a,b c, siendo a el menor, #b el intermedio y c el mayor print(a, b, c) # si no se cumplen condiciones anteriores else: # se imprime a como el menor, c el intermedio y b el mayor print(a, c, b) #se empieza a comparar si c es menor respecto a a y b #compara si c es menor que a if (c < a): #compara si c es menor que b if (c < b): #compara si b es menor que a if(b < a): #al cumplir las ultimas condiciones imprime los números en oren c, b, a siendo c el menor, b intermedio y a mayor print(c, b, a) #si no se cumplen else: #se imprime en orden c,a b siendo c el menor, a el intermedio y b el mayor print(c, a, b) #por ultimo se compara si b es el menor respecto a a y c #inicialmente compara si b es menor que a if (b < a): #luego si b es menor que c if (b < c): #si a es menor que c if(a < c): #si se cumplen las condiciones se imprime en orden b,a,c siendo b el menor, a el intermedio y c el mayor print(b, a, c) #de lo contrario else: #se imprime b como el menor, c el intermedio y a el mayor print(b, c, a) #dado el caso que si de los 3 números ingresados, dos o mas son iguales se ejecutarían las siguienes líneas. #dependiendo los que se detecten como iguales entre si, se le mostrarian al usuario #se compara si a es igual a b if (a == b): #si es verdadera la sentencia anterior entonces se imprime al usuario la indicación que b y a son iguales print("b y a son iguales") #se compara si a es igual respecto a c if (a == c): #si lo anterior fuese cierto se imprimiría que a y c son iguales print("a y c son iguales") #se compara si b es igual respecto a c if(b == c): #si lo anterior es cierto se imprime que b y c son iguales print(" b y c con iguales") #Por ultimo se comparan los tres números if(a == b == c): #si se determina que todos son iguales se imprime esta sentencia al usuario print("todos son iguales")
# -*- coding: utf-8 -*- """ Created on Mon Mar 22 20:21:25 2021 @author: R005 Desarrollar un programa que muestre la tabla de multiplicar del 5 (del 5 al 50) """ for f in range(5,51,5): print(f)
# -*- coding: utf-8 -*- """ Created on Thu Feb 18 15:50:51 2021 @author: R005 """ #Escribir un programa que solicite ingresar 10 notas #de alumnos y nos informe cuántos tienen notas mayores o iguales a 7 y cuántos menores. altas=0 bajas=0 x=1 while x<=10: nota=int(input("ingrese las notas:")) if nota>=7: altas=altas+1 else: bajas=bajas+1 x=x+1 print("cantidad de alumnos con notas mayores o iguales que 7:") print(altas) print("cantidad de alumnos con notas menores que 7:") print(bajas)
# -*- coding: utf-8 -*- """ Created on Tue Mar 9 18:36:56 2021 @author: SEBASTIAN MARULANDA CORREA Leer N, generar aleatrorios y calcular suma y promedio de: números aleatorios, números positivos, números negativos Mostrar los números aleatorios Mostrar cantidad total de números Mostrar cantidad de números positivos Mostrar cantidad de números negativos Mostrar mayor positivo, menor positivo, mayor negativo, menor negativo Nota: para saber cuando un número negativo es mayor que otro negativo, cuanto mas bajo sea el número en valor absoluto (sin signo) mayor será. """ #IMportar libreria import random #Area de definición de variables cantidadnumeros=0 contadorrepeticioneshile=0 numero=0 acumuladorsuma=0 promedionumerosaleatotorios=0.0 #Variables segunda parte del ejercicio acumuladorpositivos=0 acumuladornegativos=0 contadorpositivos=0 contadornegativos=0 promediopositivos=0.0 promedionegativos=0.0 #Variables tercera parte del ejercicio mayorpositivo=0 mayornegativo=0 menorpositivo=1000 #En este caso el rango es -1000 a 1000 para aleatorios menornegativo=-1000 #En este caso el rango es -1000 a 1000 para aleatorios #Entradas cantidadnumeros=int(input("Cantidad de números: ")) #Procesos #Ciclo While while contadorrepeticioneshile<cantidadnumeros: numero= random.randint(-1000,1000) acumuladorsuma=acumuladorsuma+numero #Segunda parte del ejercicio if numero>0:#Cálculo para números positivos print("Número positivo: ",numero) acumuladorpositivos=acumuladorpositivos+numero contadorpositivos=contadorpositivos+1 #Tercera parte del ejercicio #Identificar el mayor de los positivos if numero>mayorpositivo: mayorpositivo=numero #Identificar el menor de los positivos if numero<menorpositivo: menorpositivo=numero else:#Cálculos para números negativos print("Número negativo: ",numero) acumuladornegativos=acumuladornegativos+numero contadornegativos=contadornegativos+1 #Identificar el mayor de los negativos if numero<mayornegativo: mayornegativo=numero #Identificar el menor de los negativos if numero>menornegativo: menornegativo=numero #Fin de la segunda parte del ejercicio contadorrepeticioneshile=contadorrepeticioneshile+1 #FIn ciclo #Cálculo de promedios promedionumerosaleatotorios=acumuladorsuma/contadorrepeticioneshile promediopositivos=acumuladorpositivos/contadorpositivos promedionegativos=acumuladornegativos/contadornegativos #Salidas de todos los números print("Suma de numeros aleatorios:",acumuladorsuma) print("Promedio de numeros aleatorios:",promedionumerosaleatotorios) #Salidas de todos los números positivos print("Cantidad números positivos: ",contadorpositivos) print("suma de numeros positivos: ",acumuladorpositivos) print("Promedio de numeros positivos: ",promediopositivos) #Salidas de todos los números negativos print("Cantidad números negativos: ",contadornegativos) print("suma de numeros negativos: ",acumuladornegativos) print("Promedio de numeros negativos: ",promedionegativos) #Imprimir mayor de los positivos y menor de los positivos print("Mayor de los positivos: ",mayorpositivo) print("Menor de los positivos: ",menorpositivo) #Imprimir mayor de los negativos y menor de los negativos print("Mayor de los negativos: ",menornegativo) print("Menor de los negativos: ",mayornegativo)
# -*- coding: utf-8 -*- """ Created on Tue May 4 18:23:46 2021 @author: R005 """ import pandas as pd notafundamentos=pd.DataFrame ({'Nombres':['andres','sebastian','laura','camila'],'semestre':[2,3,3,2]}) #notafundamentos es el dataframe print(notafundamentos) print() notafundamentos.insert(2,'ciudad',['Manizales','Pereira','Manizales','Pereira']) print(notafundamentos) print() notafundamentos['nota1']=4 #Asi también se puede insertar columna haciendo uso del operador print(notafundamentos) print() notafundamentos['nota2']=[3,5,4,4] print(notafundamentos) print() notafundamentos.loc[4]=['maria',2,'Manizales',5,4] print(notafundamentos) print() #Agregar fila con append. se coloca ignore_index ya que los datos no se ingresaron en orden de acuerdo a las columnas entonces asi los ingresa notafundamentos.append({'semestre':2,'nota1':3,'Nombres':'lucia','ciudad':'Armenia','nota2':5},ignore_index=True) print(notafundamentos) print() #modificar datos iloc. Se indica la posición de lo que quiero que cambie y el dato que deseo que quede notafundamentos.iloc[2,2]='Pereira' print(notafundamentos)
# -*- coding: utf-8 -*- """ Created on Thu Apr 22 18:41:51 2021 @author: R005 """ #Métodos de ordenamiento #Crear lista y darle valores listabase=[34,12,45,2,60,34,8] print("Lista base desordenada: ",listabase) #Ordenar la lista con una función de python de manera ascendente listabase.sort() #Sin nada en el parentesis de sort ordena ascendente #Imprimir lista ordenada ascendente print("Lista base ordenada ascendente: ",listabase) #Ordenar vista descendente #Colocando dentro del parentesis de .sort reverse=true ordena descendente listabase.sort(reverse=True) #Imprimir lista ordenada descendente print("Lista base ordenada descendente: ",listabase)
# -*- coding: utf-8 -*- """ Created on Mon Mar 22 10:07:44 2021 @author: Sebastian Marulanda Correa Ejercicio 1 curso. funciones Python Confeccionar una aplicación que muestre una presentación en pantalla del programa. Solicite la carga de dos valores y nos muestre la suma. Mostrar finalmente un mensaje de despedida del programa """ def mostrar_mensaje(mensaje): print("*********") print(mensaje) print("*********") def carga_suma(): valor1=int(input("Ingrese el primer valor:")) valor2=int(input("Ingrese el segundo valor:")) suma=valor1+valor2 print("La suma de los dos valores es:",suma) # programa principal mostrar_mensaje("El programa calcula la suma de dos valores ingresados por teclado.") carga_suma() mostrar_mensaje("Gracias por utilizar el programa")
# -*- coding: utf-8 -*- """ Created on Mon Mar 22 13:09:05 2021 @author: Sebastian Marulanda Correa Ejercicio 8 curso. funciones Python Confeccionar una función que le enviemos como parámetro un string y nos retorne la cantidad de caracteres que tiene. En el bloque principal solicitar la carga de dos nombres por teclado y llamar a la función dos veces. Imprimir en el bloque principal cual de las dos palabras tiene más caracteres. """ def mas_caracteres(cadena): return len(cadena) nombre1=input("Digite primer nombre: ") nombre2=input("Digite segundo nombre: ") largo1=mas_caracteres(nombre1) largo2=mas_caracteres(nombre2) if largo1==largo2: print("Los nombres ",nombre1," y ",nombre2,"tienen igual cantidad de caracteres: ",largo1) else: if largo1>largo2: print("El nombre ",nombre1," tiene mas caraceres: ",largo1) else: print("El nombre ",nombre2," tiene mas caraceres ",largo2)
# -*- coding: utf-8 -*- """ Created on Mon Mar 1 17:57:08 2021 @author: SEBASTIAN MARULANDA CORREA """ #Sumar los números enteros de 1 a 100 suma=0 for i in range (1,101): suma=suma+(i) print(i) print("la suma es:",suma)
# Написать fizzbuzz для 20 троек чисел, которые записаны в файл. Читаете из файла первую строку, # берете из нее числа, считаете для них fizzbuzz, выводите. f = open("fizz.txt", "r") for i in f: line = list(map(int, i.split())) line1 = int(line[0]) line2 = int(line[1]) line3 = int(line[2]) s = int() for s in range(1, line3 +1): if s % line1 == 0 and s % line2 == 0: print("FB", end=",") elif s % line2 == 0: print("F", end=",") elif s % line1 == 0: print("B", end=",") else: print(s, end=",") print("") f.close()
radius = int(input("Введите радиус: ")) if radius >= 0: print("Длина окружности = ", 2 * 3.14 * radius) print("Площадь = ", 3.14 * radius ** 2) else: print("Пожалуйста, введите положительное число")
n1=int(input('Me diga sua primeira nota:')) n2=int(input('Me diga sua segunda nota:')) n3=int(input('Me diga sua terceira nota:')) m = (n1+n2+n3)/3 print('Sua média é {:.2f}'.format(m))
numero = int(input('Me diga um número:')) unidade = (numero // 1 % 10) % 2 #Se o resto da divisão da unidade for igual a 0, então ele é par if unidade == 0: print('Seu número é par.') else: print('Seu número é impar.')
cidade = str(input('Digite o nome de uma cidade:')).strip() ## o nome da cidade começa com Santo? cidade = cidade.capitalize() print('Santo' in cidade)
salario = float(input('Qual o valor do seu salário? R$')) if salario > 1250: print('Você recebeu um aumento, e seu novo salário é R${:.2f}.'.format((salario * 10 / 100) + salario)) else: print('Você recebeu um aumento, e seu novo salário é R${:.2f}'.format((salario * 15/100) + salario))
a = int(input('Escreva o primeiro número:')) b = int(input('Escreva o segundo valor:')) c = int(input('Escreva o terceiro valor:')) # O menor menor = a if b<a and b<c: menor = b if c<a and c<b: menor = c # O maior maior = a if b>a and b>c: maior = b if c>a and c>b: maior = c print('O menor valor foi {}.'.format(menor)) print('O maior valor foi {}.'.format(maior))
num = 0 while (num < 10): num += 1 print(str(num))
import random my_random_number = random.randint(1, 10) print("I am thinking of a number between 1 and 10.") number = input("What's the number? ") guess = 5 while int(number) != my_random_number and guess > 0: print ("Nope, try again.") print ("You have " + str(guess) + " guesses left.") guess = guess - 1 if (int(number) < my_random_number): print ( str(number) + " is too low." ) if (int(number) > my_random_number): print( str(number) + " is to high.") number = input("What's the number? ") if guess == 0: print ("You ran out of guesses") else: print("Yes! You win!")
class Vehicle: def __init__(self, make, model, year): self.make = make self.model = model self.year = year def print_info(self): print(self.make + " " + self.model + " " + self.year) class Person: def __init__(self, name, email, phone): self.name = name self.email = email self.phone = phone self.friends = [] self.greeting_count = 0 def greet(self, other_person): print ('Hello {}, I am {}!'.format(other_person.name, self.name)) self.greeting_count = self.greeting_count + 1 def print_contact_info(self): print("Sonny's email: " + self.email + " , Sonny's phone number: " + self.phone) def num_friends(self): return len(self.friends) def add_friend(self, other_person): self.friends.append(other_person) def __str__(self): return 'Person: {} {} {}'.format(self.name, self.email, self.phone) #def num_unique_people_greeted(self): # return number #Question # 1 sonny = Person('Sonny', '[email protected]', '438-485-4948') #Question # 2 jordan = Person('Jordan', '[email protected]', '495-586-3456') #Question # 3 #sonny.greet(jordan) # Question # 4 #jordan.greet(sonny) # Question # 5 print(sonny.email + " " + sonny.phone) # Question # 6 print(jordan.email + " " + jordan.phone) # Question # 1 car = Vehicle('Nissan', 'Leaf', '2015') # Question # 2 print(car.make, car.model, car.year) # Question # 3 car.print_info() # Question # 4 sonny.print_contact_info() # Question # 5 sonny.friends.append(jordan) # Question # 6 jordan.friends.append(sonny) sonny.friends.append(jordan) # Question # 7 print(len(jordan.friends)) # Queston # 8 jordan.add_friend(sonny) #Question # 9 print(jordan.num_friends()) # Question # 10 print(sonny.greeting_count) sonny.greet(jordan) print(sonny.greeting_count) sonny.greet(jordan) print(sonny.greeting_count) print(jordan)
import random class Character: def __init__(self, health, power, name, mult, value, dead, weapon): self.health = health self.power = power self.name = name self.mult = mult self.value = value self.dead = True self.weapon = weapon def super_tonic(self): self.health = self.health + 10 def alive(self): if self.health <= 0: print("{} is dead.".format(self.name)) return False else: return True def attack(self, enemy): if enemy.name == "zombie": enemy.never_hurt() elif enemy.name == "military": self.death(enemy) elif self.name == "hero": self.hero_attack(enemy) else: enemy.health -= self.power print("{} do {} damage to the {}.".format(self.name,self.power,enemy.name)) if (self.name == "medic"): self.heal_two def print_status(self): print("{} have {} health and {} power.".format(self.name, self.health, self.power)) def defeated_coins(self, enemy): if (enemy.dead == False): return enemy.value enemy.value = 0 else: print("You must need your eyes checked the dead guy just hit you BRO!!") enemy.attack(self) class Hero(Character): def hero_attack(self, enemy): randNum = random.randint(1,5) if randNum == 5: enemy.health = enemy.health - self.power * 2 else: enemy.health = enemy.health - self.power class Goblin(Character): pass class Zombie(Character): def never_hurt(self): print("You cant hurt the Zombie, but I am too slow and cant hurt u either") class Medic(Character): def heal_two(self): randNum = random.randit(1,5) if randNum == 5: self.health = self.health + 2 class Shadow(Character): def shadow_attack(self, enemy): randNum = random.randit(1,10) if randNum == 10: self.power = self.power - 1 class Lizard(Character): # He has a 5 percent chance of healing himself when attacking a target. # He does this by stealing power from the enemy/ def spell_attack(self, enemy): randNum = random.randit(1,10) if randNum == 20: self.power = 10 enemy.power = enemy.power - 1 class Military(Character): def death(self, enemy): enemy.health = 0 print("Why would you attacked the Military: Death")
import random import sys import math import pickle DEBUG = True class TicTacToePlayer: TYPES = ["HUMAN", "COMPUTER"] def __init__(self, player, player_type): self.player = player self.player_type = player_type def reset(self): pass def feed_reward(self, reward): pass def add_state(self, state): pass def equals3(self, a, b, c): return a == b and b == c and (a == 'X' or a == 'O') def space_exist(self, board): return (board.count('X') + board.count('O')) != 9 def can_move(self, move, board): return (move != None) and move in range(0,9) and not(board[move] in ('X', 'O')) def possible_moves(self, board): moves = [] for i in board: if i != 'X' and i != 'O': moves.append(i) return moves def choose_action(self, board): return random.choice(self.possible_moves(board)) def can_win(self, board): for i in range(3): if self.equals3(board[i*3+0], board[i*3+1], board[i*3+2]): return True, board[i*3+0] for i in range(3): if self.equals3(board[0+i], board[3+i], board[6+i]): return True, board[0+i] if self.equals3(board[0], board[4], board[8]) or self.equals3(board[6], board[4], board[2]): return True, board[4] return False, None class MinimaxPlayer(TicTacToePlayer): MAX_DEPTH = 10 def __init__(self, player): super().__init__(player, TicTacToePlayer.TYPES[1]) def choose_action(self, board): potential_moves = self.possible_moves(board) action = None if len(potential_moves) > 0: bestScore = -math.inf for i in potential_moves: nextState = board.copy() nextState[i] = self.player score = self.minimax(nextState, 0, -math.inf, math.inf, False) if score > bestScore: action = i bestScore = score return action def minimax(self, board, depth, alpha, beta, maximizingPlayer): # someone wins wins, winner = self.can_win(board) if wins: if winner == self.player: return 10 * (MinimaxPlayer.MAX_DEPTH - depth + 1) else: return -10 * (MinimaxPlayer.MAX_DEPTH - depth + 1) moves = self.possible_moves(board) # tie or reached maximum search depth if len(moves) == 0 or depth == MinimaxPlayer.MAX_DEPTH: return 0 if maximizingPlayer: maxEval = -math.inf for i in moves: nextState = board.copy() nextState[i] = self.player score = self.minimax(nextState, depth+1, alpha, beta, False) maxEval = max(maxEval, score) alpha = max(alpha, score) if beta <= alpha: break return maxEval else: minEval = math.inf if self.player == 'X': opponent = 'O' else: opponent = 'X' for i in moves: board[i] = opponent score = self.minimax(board, depth+1, alpha, beta, True) board[i] = i minEval = min(minEval, score) beta = min(beta, score) if beta <= alpha: break return minEval class RLPlayer(TicTacToePlayer): def __init__(self, player, playerType=TicTacToePlayer.TYPES[1], exp_rate=0.3): super().__init__(player, playerType) self.states = [] # record all positions taken self.lr = 0.2 # learning rate self.exp_rate = exp_rate self.decay_gamma = 0.9 self.states_value = {} # dictionary of state -> value def get_hash(self, board, state=None): return (str(board) if state == None else str(state)) def add_state(self, state): self.states.append(state) def choose_action(self, board): positions = self.possible_moves(board) action = None if random.uniform(0,1) <= self.exp_rate: action = random.choice(positions) else: value_max = -math.inf for p in positions: next_state = board.copy() next_state[p] = self.player next_state_value = self.states_value.get(self.get_hash(next_state)) value = 0 if next_state_value is None else next_state_value if value >= value_max: value_max = value action = p return action def feed_reward(self, reward): for s in reversed(self.states): if self.states_value.get(s) is None: self.states_value[s] = 0 self.states_value[s] += self.lr * (self.decay_gamma * reward - self.states_value[s]) reward = self.states_value[s] def reset(self): self.states = [] def save_policy(self): fw = open('policy_' + str(self.player), 'wb') pickle.dump(self.states_value, fw) fw.close() def load_policy(self, file): fr = open(file, 'rb') self.states_value = pickle.load(fr) fr.close() class State: def __init__(self, p1, p2): self.board = [i for i in range(0,9)] self.p1 = p1 self.p2 = p2 self.reset() def get_hash(self): self.boardHash = str(self.board) return self.boardHash def winner(self): self.isEnd, winner = self.current_player.can_win(self.board) return winner def update_state(self, action): self.board[action] = self.current_player.player def give_reward(self): result = self.winner() if result == self.p1.player: self.p1.feed_reward(1) self.p2.feed_reward(-1) elif result == self.p2.player: self.p1.feed_reward(-1) self.p2.feed_reward(1) else: # tie self.current_player.feed_reward(0.1) self.next_player.feed_reward(0.5) def print_board(self): x = 1 for index,i in enumerate(self.board): end = ' | ' if x%3 == 0: end = '\n' if i != 1: end += '--------\n' char = ' ' if i in ('X', 'O'): char = i else: char = index x+=1 print (char, end = end) print('\n') def reset(self): self.board = [i for i in range(0,9)] self.boardHash = None self.isEnd = False self.p1.reset() self.p2.reset() self.current_player = self.p1 self.next_player = self.p2 def play(self, rounds=100): for i in range(rounds): #print ("Round {}".format(i)) move_counter = 0 while not self.isEnd: #positions = self.current_player.possible_moves(self.board) action = self.current_player.choose_action(self.board) #print("Move: %s to %s" %(self.current_player.player, action)) self.update_state(action) self.boardHash = self.get_hash() self.current_player.add_state(self.boardHash) move_counter = move_counter + 1 winner = self.winner() if winner == self.current_player.player or not self.next_player.space_exist(self.board): if winner is not None: print("Round %s: Winner is %s in %s moves" %(i, winner, move_counter)) #self.print_board() else: print("Round %s: Tie in %s moves" %(i, move_counter)) self.give_reward() self.reset() break # game is not over, update current player temp_player = self.current_player self.current_player = self.next_player self.next_player = temp_player def play2(self): move_counter = 0 print("\n\nHuman vs RL player\n\n") while not self.isEnd: self.print_board() action = None #if human player, solicit input for move! if self.current_player.player_type == TicTacToePlayer.TYPES[0]: print('Make your move [0-8]: ') action = int(input()) else: #positions = self.current_player.possible_moves(self.board) action = self.current_player.choose_action(self.board) print("Move: %s to %s" %(self.current_player.player, action)) self.update_state(action) self.boardHash = self.get_hash() self.current_player.add_state(self.boardHash) move_counter = move_counter + 1 winner = self.winner() if winner == self.current_player.player or not self.next_player.space_exist(self.board): if winner is not None: print("Winner is %s in %s moves" %(winner, move_counter)) self.print_board() else: print("Tie in %s moves" %(move_counter)) self.give_reward() self.reset() break # game is not over, update current player temp_player = self.current_player self.current_player = self.next_player self.next_player = temp_player if __name__ == "__main__": #training p1 = RLPlayer('X') p2 = RLPlayer('O') s = State(p1, p2) #print("training...") #s.play(50000) #p1.save_policy() #p2.save_policy() #against human p1 = TicTacToePlayer('X', TicTacToePlayer.TYPES[0]) p2 = MinimaxPlayer('O') s.p1 = p1 s.p2 = p2 s.reset() s.play2()
PUZZLE1 = ''' glkutqyu onnkjoaq uaacdcne gidiaayu urznnpaf ebnnairb xkybnick ujvaynak ''' PUZZLE2 = ''' fgbkizpyjohwsunxqafy hvanyacknssdlmziwjom xcvfhsrriasdvexlgrng lcimqnyichwkmizfujqm ctsersavkaynxvumoaoe ciuridromuzojjefsnzw bmjtuuwgxsdfrrdaiaan fwrtqtuzoxykwekbtdyb wmyzglfolqmvafehktdz shyotiutuvpictelmyvb vrhvysciipnqbznvxyvy zsmolxwxnvankucofmph txqwkcinaedahkyilpct zlqikfoiijmibhsceohd enkpqldarperngfavqxd jqbbcgtnbgqbirifkcin kfqroocutrhucajtasam ploibcvsropzkoduuznx kkkalaubpyikbinxtsyb vjenqpjwccaupjqhdoaw ''' def rotate_puzzle(puzzle): '''(str) -> str Return the puzzle rotated 90 degrees to the left. ''' raw_rows = puzzle.split('\n') rows = [] # if blank lines or trailing spaces are present, remove them for row in raw_rows: row = row.strip() if row: rows.append(row) # calculate number of rows and columns in original puzzle num_rows = len(rows) num_cols = len(rows[0]) # an empty row in the rotated puzzle empty_row = [''] * num_rows # create blank puzzle to store the rotation rotated = [] for row in range(num_cols): rotated.append(empty_row[:]) for x in range(num_rows): for y in range(num_cols): rotated[y][x] = rows[x][num_cols - y - 1] # construct new rows from the lists of rotated new_rows = [] for rotated_row in rotated: new_rows.append(''.join(rotated_row)) rotated_puzzle = '\n'.join(new_rows) return rotated_puzzle def lr_occurrences(puzzle, word): '''(str, str) -> int Return the number of times word is found in puzzle in the left-to-right direction only. >>> lr_occurrences('xaxy\nyaaa', 'xy') 1 ''' return puzzle.count(word) # ---------- Your code to be added below ---------- # *task* 3: write the code for the following function. # We have given you the header, type contract, example, and description. def total_occurrences(puzzle, word): '''(str, str) -> int Return total occurrences of word in puzzle. All four directions are counted as occurrences: left-to-right, top-to-bottom, right-to-left, and bottom-to-top. >>> total_occurrences('xaxy\nyaaa', 'xy') 2 ''' # your code here # check if the word occurs left-to-right save to L_to_R L_to_R = lr_occurrences(puzzle, word) # check if the word occurs right-to-left save to R_to_L R_to_L = lr_occurrences(rotate_puzzle(rotate_puzzle(puzzle)), word) # check if the word occurs top-to-bottom save to top_to_bottom top_to_bottom = lr_occurrences(rotate_puzzle(puzzle), word) # check if the word occurs bottom-to-top save to bottom_to_top bottom_to_top = lr_occurrences(rotate_puzzle(rotate_puzzle (rotate_puzzle(puzzle))), word) # add up all the directions of word and return the amount of times # it occurs return (L_to_R+R_to_L+top_to_bottom+bottom_to_top) # *task* 5: write the code for the following function. # We have given you the function name only. # You must follow the design recipe and complete all parts of it. # Check the handout for what the function should do. def in_puzzle_horizontal(puzzle, word): '''(str,str) -> bool user will input the string/puzzle with the designated word\ he/she is lookng for left-to-right, and right-to-left and if\ it can be found more than once including 1, true will be returned\ meaning we found it from either side (or both) as previously mentioned,\ and false if we cant find it at all (word DNE as a possibility) from\ either side (or both). REQ: string is inputed for both the puzzle variable and word variable REQ: string inputed matches the exact word in the puzzle (case sensitive) >>>in_puzzle_horizontal(PUZZLE1, "brian") True >>>in_puzzle_horizontal(PUZZLE1, "nick") True >>>in_puzzle_horizontal(PUZZLE1, "dan") False >>>in_puzzle_horizontal(PUZZLE1, "BRIAN") False >>>in_puzzle_horizontal(PUZZLE1, "an") True >>>in_puzzle_horizontal(PUZZLE1,"anya") True >>>in_puzzle_horizontal(PUZZLE1,"paco") False >>>in_puzzle_horizontal(PUZZLE2, "brian") False >>>in_puzzle_horizontal(PUZZLE2, "nick") True >>>in_puzzle_horizontal(PUZZLE2, "dan") False >>>in_puzzle_horizontal(PUZZLE2, "BRIAN") False >>>in_puzzle_horizontal(PUZZLE2, "an") True >>>in_puzzle_horizontal(PUZZLE2,"anya") True >>>in_puzzle_horizontal(PUZZLE2,"paco") False ''' # check if the word occurs left to right save to L_to_R L_to_R = lr_occurrences(puzzle, word) # check if the word occurs right to left and save to R_to_L R_to_L = lr_occurrences(rotate_puzzle(rotate_puzzle(puzzle)), word) # add the two above if its >=1 return True if not then False return ((L_to_R + R_to_L) >= 1) # *task* 8: write the code for the following function. # We have given you the function name only. # You must follow the design recipe and complete all parts of it. # Check the handout for what the function should do. def in_puzzle_vertical(puzzle, word): '''(str,str) -> bool user will input the string/puzzle with the designated word\ he/she is lookng for top-to-bottom, and bottom-to-top and\ if it can be found more than once including 1 (vertically), true will be returned meaning we found it from either side\ (or both) as previously mentioned, and false if we cant find\ it at all (even if word DNE in general) from either side (or both). REQ: string is inputed for both the puzzle variable and word variable REQ: string inputed matches the exact word in the puzzle (case sensitive) >>>in_puzzle_vertical(PUZZLE1, "brian") True >>>in_puzzle_vertical(PUZZLE2, "brian") True >>>in_puzzle_vertical(PUZZLE1, "nick") True >>>in_puzzle_vertical(PUZZLE2, "nick") True >>>in_puzzle_vertical(PUZZLE1, "dan") True >>>in_puzzle_vertical(PUZZLE2, "dan") True >>>in_puzzle_vertical(PUZZLE1, "BRIAN") False >>>in_puzzle_vertical(PUZZLE2, "BRIAN") False >>>in_puzzle_vertical(PUZZLE1, "an") True >>>in_puzzle_vertical(PUZZLE2, "an") True >>>in_puzzle_vertical(PUZZLE1,"anya") True >>>in_puzzle_vertical(PUZZLE2, "anya") True >>>in_puzzle_vertical(PUZZLE1,"paco") True >>>in_puzzle_vertical(PUZZLE2, "paco") True ''' # check if the word occurs top to bottom and save it to top_to_bottom top_to_bottom = lr_occurrences(rotate_puzzle(puzzle), word) # check if the word occurs bottom to top and save it save to bottom_to_top bottom_to_top = lr_occurrences(rotate_puzzle (rotate_puzzle(rotate_puzzle(puzzle))), word) # add the two to see if it equals 1 or more then return true or false return(top_to_bottom + bottom_to_top >= 1) # *task* 9: write the code for the following function. # We have given you the function name only. # You must follow the design recipe and complete all parts of it. # Check the handout for what the function should do. def in_puzzle(puzzle, word): '''(str,str) -> bool user will input the string/puzzle with the designated word\ he/she is lookng for top-to-bottom,bottom-to-top,right-to-left\ and left-to-right if it can be found more than once including 1\ true will be returned meaning we found it from any side\ (1 or 2 or 3 or 4 of the sides) as previously mentioned, and\ false if we cant find it at all from either of the four sides. REQ: string is inputed for both the puzzle variable and word variable REQ: string inputed matches the exact word in the puzzle (case sensitive) >>>in_puzzle(PUZZLE1, "brian") True >>>in_puzzle(PUZZLE1, "nick") True >>>in_puzzle(PUZZLE1, "dan") True >>>in_puzzle(PUZZLE1, "BRIAN") False >>>in_puzzle(PUZZLE1, "an") True >>>in_puzzle(PUZZLE1,"anya") True >>>in_puzzle(PUZZLE1,"paco") True >>>in_puzzle(PUZZLE2, "brian") True >>>in_puzzle(PUZZLE2, "nick") True >>>in_puzzle(PUZZLE2, "dan") True >>>in_puzzle(PUZZLE2, "BRIAN") False >>>in_puzzle(PUZZLE2, "an") True >>>in_puzzle(PUZZLE2,"anya") True >>>in_puzzle(PUZZLE2,"paco") True ''' # call total_occurences that takes all 4 directions into account # >=1 True is returned if not then False is returned return (total_occurrences(puzzle, word) >= 1) # *task* 10: write the code for the following function. # We have given you only the function name and parameters. # You must follow the design recipe and complete all parts of it. # Check the handout for what the function should do. def in_exactly_one_dimension(puzzle, word): '''(str,str) -> bool user will input the string/puzzle he or she is looking at\ with the word he or she is looking for and if it appears only\ in one direction (only horizontal/vertical) then return true\ signifying it can only be found in one dimension but if its\ both or it cant be found false is returned signifying it\ can't be found or it occurs in more than one direction REQ: str==str (word by word, case sensitive) REQ: a str is inputed for both puzzle and word >>>in_exactly_one_dimension(PUZZLE1, "brian") False >>>in_exactly_one_dimension(PUZZLE1, "nick") False >>>in_exactly_one_dimension(PUZZLE1, "dan") True >>>in_exactly_one_dimension(PUZZLE1, "BRIAN") False >>>in_exactly_one_dimension(PUZZLE1, "an") False >>>in_exactly_one_dimension(PUZZLE1,"anya") False >>>in_exactly_one_dimension(PUZZLE1,"paco") True >>>in_exactly_one_dimension(PUZZLE2, "brian") True >>>in_exactly_one_dimension(PUZZLE2, "nick") False >>>in_exactly_one_dimension(PUZZLE2, "dan") True >>>in_exactly_one_dimension(PUZZLE2, "BRIAN") False >>>in_exactly_one_dimension(PUZZLE2, "an") False >>>in_exactly_one_dimension(PUZZLE2,"anya") False >>>in_exactly_one_dimension(PUZZLE2,"paco") True ''' # if one side of in_puzzle_vertical/horizontal is True # and the other False and vice versa True is returned # if not then False is to be returned return (((in_puzzle_vertical(puzzle, word) == True and in_puzzle_horizontal(puzzle, word) == False) or (in_puzzle_vertical(puzzle, word) == False and in_puzzle_horizontal(puzzle, word) == True))) # *task* 11: write the code for the following function. # We have given you only the function name and parameters. # You must follow the design recipe and complete all parts of it. # Check the handout for what the function should do. def all_horizontal(puzzle, word): '''(str,str) -> bool The user will input the designated puzzle/string he/she is looking at\ and the word he/she is trying to verify within it, if the words occurence\ is only horizontal or the word doesnt exist, true is returned, if neither\ of the previously mentioned conditions are met False is returned meaning\ it occurs vertically and horizontally or it occurs x amount of times\ vertically REQ: str==str (case sensitive) REQ: str is inputed >>>all_horizontal(PUZZLE1, "brian") False >>>all_horizontal(PUZZLE1, "nick") False >>>all_horizontal(PUZZLE1, "dan") False >>>all_horizontal(PUZZLE1, "BRIAN") True >>>all_horizontal(PUZZLE1, "an") False >>>all_horizontal(PUZZLE1,"anya") False >>>all_horizontal(PUZZLE1,"paco") False >>>all_horizontal("aabc\naabc","aa") False >>>all_horizontal(PUZZLE2, "brian") False >>>all_horizontal(PUZZLE2, "nick") False >>>all_horizontal(PUZZLE2, "dan") False >>>all_horizontal(PUZZLE2, "BRIAN") True >>>all_horizontal(PUZZLE2, "an") False >>>all_horizontal(PUZZLE2,"anya") False >>>all_horizontal(PUZZLE2,"paco") False >>>all_horizontal("abc\nabc","abc") True ''' # if in_puzzle_horizontal is True and in_puzzle_vertical # is False or the word doesn exist then True is returned # if the conditions are met then False is to be returned return ((in_puzzle_vertical(puzzle, word) == False and in_puzzle_horizontal(puzzle, word) == True) or total_occurrences(puzzle, word) == 0) # *task* 12: write the code for the following function. # We have given you only the function name and parameters. # You must follow the design recipe and complete all parts of it. # Check the handout for what the function should do. def at_most_one_vertical(puzzle, word): '''(str,str) -> bool The user will call the following function and check\ to see if the inputed word occurs at most once if\ the word doesnt occur True is returned, if the word\ is found once and the only case it can be found is\ vertically then True is returned, if the word occurs\ more than once or if does occurs once but it does so\ horizontally False is to be returned. REQ: str is inputed for both parameters in the function REQ: str== str (word exactly matches the word found in\ the string/puzzle, so case sensitve) >>>at_most_one_vertical("abac\nabfc","aa") False >>>at_most_one_vertical(PUZZLE1, "paco") True >>>at_most_one_vertical(PUZZLE2, "paco") True >>>at_most_one_vertical(PUZZLE1, "brian") False >>>at_most_one_vertical(PUZZLE1, "nick") False >>>at_most_one_vertical(PUZZLE2, "nick") False >>>at_most_one_vertical(PUZZLE2, "brian") False >>>at_most_one_vertical(PUZZLE1, "anya") False >>>at_most_one_vertical(PUZZLE2, "dan") False >>>at_most_one_vertical(PUZZLE1, "dan") False >>>at_most_one_vertical(PUZZLE2, "anya") False >>>at_most_one_vertical(PUZZLE2, "BRIAN") True >>>at_most_one_vertical(PUZZLE1, "BRIAN") True >>>at_most_one_vertical("bbb\nalc", "ba") True ''' # if the word occurs once and that occurence is # vertical or the total occurnce is 0 then True # is returned, if the conditions aren't met then # False is to be returned return ((total_occurrences(puzzle, word) == 1 and in_puzzle_vertical(puzzle, word) == True)or total_occurrences(puzzle, word) == 0) def do_tasks(puzzle, name): '''(str, str) -> NoneType puzzle is a word search puzzle and name is a word. Carry out the tasks specified here and in the handout. ''' # *task* 1a: add a print call below the existing one to print # the number of times that name occurs in the puzzle left-to-right. # Hint: one of the two starter functions defined above will be useful. # the end='' just means "Don't start a newline, the next thing # that's printed should be on the same line as this text print('Number of times', name, 'occurs left-to-right: ', end='') # your print call here print(lr_occurrences(puzzle, name)) # *task* 1b: add code that prints the number of times # that name occurs in the puzzle top-to-bottom. # (your format for all printing should be similar to # the print statements above) print('Number of times', name, 'occurs top-to-bottom: ', end='') # Hint: both starter functions are going to be useful this time! print(lr_occurrences(rotate_puzzle(puzzle), name)) # *task* 1c: add code that prints the number of times print('Number of times', name, 'occurs right-to-left: ', end='') # that name occurs in the puzzle right-to-left. print(lr_occurrences(rotate_puzzle(rotate_puzzle(puzzle)), name)) # *task* 1d: add code that prints the number of times print('Number of times', name, 'occurs bottom-to-top: ', end='') # that name occurs in the puzzle bottom-to-top. print(lr_occurrences(rotate_puzzle(rotate_puzzle(rotate_puzzle (puzzle))), name)) # *task* 4: print the results of calling total_occurrences on # puzzle and name. # Add only one line below. # Your code should print a single number, nothing else. print (total_occurrences(puzzle, name)) # *task* 6: print the results of calling in_puzzle_horizontal on # puzzle and name. # Add only one line below. The code should print only True or False. print(in_puzzle_horizontal(puzzle, name)) do_tasks(PUZZLE1, 'brian') # *task* 2: call do_tasks on PUZZLE1 and 'nick'. # Your code should work on 'nick' with no other changes made. # If it doesn't work, check your code in do_tasks. # Hint: you shouldn't be using 'brian' anywhere in do_tasks. do_tasks(PUZZLE1, 'nick') # *task* 7: call do_tasks on PUZZLE2 (that's a 2!) and 'nick'. # Your code should work on the bigger puzzle with no changes made to do_tasks. # If it doesn't work properly, go over your code carefully and fix it. do_tasks(PUZZLE2, 'nick') # *task* 9b: print the results of calling in_puzzle on PUZZLE1 and 'nick'. # Add only one line below. Your code should print only True or False. print(in_puzzle(PUZZLE1, 'nick')) # *task* 9c: print the results of calling in_puzzle on PUZZLE2 and 'anya'. # Add only one line below. Your code should print only True or False. print(in_puzzle(PUZZLE2, 'anya'))
from copy import deepcopy from math import sqrt class Configuration: """ Configuration of the puzzle """ def __init__(self, matrix): self.__matrix = deepcopy(matrix) def getLength(self): return len(self.__matrix[1]) def getValues(self): return deepcopy(self.__matrix) def nextConfig(self, i, j): next = [] newmatrix = deepcopy(self.__matrix) if (newmatrix[i][j] != 0): return next for x in range(self.getLength() + 1): if x not in newmatrix[i]: if x not in [row[j] for row in newmatrix]: if x not in self.getSquareElems(i, j): newmatrix[i][j] = x next.append(Configuration(newmatrix)) return next def __str__(self): return str(self.__matrix) def getSquareElems(self, i, j): l = [] width = sqrt(self.getLength()) startRow = int(int(i / width) * width) startCol = int(int(j / width) * width) endRow = int(startRow + width) endCol = int(startCol + width) for x in range(startRow, endRow): for y in range(startCol, endCol): l.append(self.__matrix[x][y]) return l def __eq__(self, other): if self.__matrix == other.getValues(): return True else: return False # conf = Configuration([[2,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0]]) # conf2 = Configuration([[2,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0]]) # print(conf==conf2) # for i in conf.nextConfig(1, 2): # print("") # for j in i.getValues(): # print(j)
def add(x, y): return x + y def sub(x, y): return x - y def prod(x, y): return x * y def do(func, x, y): return func(x, y) print(do(add, 12, 4)) # 'add' as arg print(do(sub, 12, 4)) # 'sub' as arg print(do(prod, 12, 4)) # 'prod' as arg
# Type your code here def de_ascii(n): return(ord(n)) n=input("enter a char") print(de_ascii(n))
# Type your code here def asterick(n): for i in range(n): print('*'*n) n=int(input("Enter an integer: ")) asterick(n)
class Point: def __init__(self,x,y,z): self.x=x self.y=y self.z=z def __str__(self): my_str="point: ({0},{1},{2})".format(self.x,self.y,self.z) return my_str p1=Point(4,2,1) print(p1)
# coding:utf8 ''' Created on 2018年1月30日 @author: XuXianda ''' #划分数据集:按照最优特征划分数据集 #@dataSet:待划分的数据集 #@axis:划分数据集的特征 #@value:特征的取值 def splitDataSet(dataSet,axis,value): #需要说明的是,python语言传递参数列表时,传递的是列表的引用 #如果在函数内部对列表对象进行修改,将会导致列表发生变化,为了 #不修改原始数据集,创建一个新的列表对象进行操作 retDataSet=[] #提取数据集的每一行的特征向量 for featVec in dataSet: #针对axis特征不同的取值,将数据集划分为不同的分支 #如果该特征的取值为value if featVec[axis]==value: #将特征向量的0~axis-1列存入列表reducedFeatVec reducedFeatVec=featVec[:axis] #将特征向量的axis+1~最后一列存入列表reducedFeatVec #extend()是将另外一个列表中的元素(以列表中元素为对象)一一添加到当前列表中,构成一个列表 #比如a=[1,2,3],b=[4,5,6],则a.extend(b)=[1,2,3,4,5,6] reducedFeatVec.extend(featVec[axis+1:]) #简言之,就是将原始数据集去掉当前划分数据的特征列 #append()是将另外一个列表(以列表为对象)添加到当前列表中 ##比如a=[1,2,3],b=[4,5,6],则a.extend(b)=[1,2,3,[4,5,6]] retDataSet.append(reducedFeatVec) return retDataSet
days = int(raw_input("Enter days: ")) months = days / 30 days = days % 30 print "months = %d Days = %d" % (months, days) import math a = int(raw_input("Enter value of a: ")) b = int(raw_input("Enter value of b: ")) c = int(raw input("Enter value of c: ")) d = b * b - 4 * a * c if d < 0: print "ROOTS are imaginary" else: root1 = (-b + math.sqrt(d)) / (2.0 * a) root2 = (-b - math.sqrt(d)) / (2.0 * a) print "ROOT 1 = ", root1 print "ROOT 2 = ", root2 basic_salary = 1500 bonus_rate = 200 commision_rate = 0.02 numberofcamera = int(raw_input("Enter the number of inputs sold: ")) price = float(raw_input("Enter the total prices: ")) bonus = (bonus_rate * numberofcamera) commision = (commision_rate * numberofcamera * price) print "Bonus = %6.2f" % bonus print "Commision = %6.2f" % commision print "Gross salary = %6.2f" % (basic_salary + bonus + commision)
"""Homework 2 - needs to be presented before exam day""" # 20P # 1) Prove that "and" operation takes precedence over "or" operation by setting # parentheses in the following expression (False or False and True or True) # 40P # 2) Get from input two different times in the format dd:hh:mm:ss and print the difference between them in the # received format dd:hh:mm:ss # dd is number of days # hh is number of hours (00-23) # mm is number od minutes (00-59) # ss is number of seconds (00-59) # 40P # Calculate the diagonal of a rectangle with sides lenght recievd from input #p1 print((False or False and True or True)) print((False or False) and (True or True)) print((False or (False and True) or True)) #p2 x = input('Get date1:') days = x[0:2] hours = x[3:5] minutes = x[6:8] seconds = x[9:11] y = input("Get date2: ") days2 = y[0:2] hours2 = y[3:5] minutes2 = y[6:8] seconds2 = y[9:11] t1 = int(days*24*hours+3600*hours+60*minutes+60*seconds) t2 = int(days2*24*hours2+3600*hours2+60*minutes2+60*seconds2) tf = t1 - t2 print('The diference is:', tf) #p3 import math L = int(input("Enter Length: ")) w = int(input("Enter Width: ")) diagonal =round(math.sqrt((w*2) + (L*2))) print("Diagonal is: ", diagonal)
from modul3.app1 import primes import random def select_primes(num,limita) : i = 0 fin_list = [] my_list = primes(limita) y = len(my_list) for _ in range(num): x = random.randint(0,y - 1) fin_list.append(my_list.pop(x)) y -= 1 print(fin_list) my_primes = primes(100) print(my_primes) select_primes(5,100)
# to import another python file just same folder and type the python file name import app import csv import sqlite3 #connect to database connection = sqlite3.connect("new.db") cursor = connection.cursor() # read file appointment with open('appointments.csv', 'r') as file: for row in file: cursor.execute("INSERT INTO Appointment (Patient_Name,Start_Date,Start_Time,Appointment_Type) VALUES (?,?,?,?)", row.split(',')) connection.commit() connection.close()
""" driver.py Includes main functions to run the boggle word finder using DFS on an input board (storing a dictionary of valid words as a Trie). @author: Sanjana Marce """ import vocab import trie import argparse """ get_neighbors: returns a list of tuples corresponding to the (r, c) coordinates of those cells within the input board around the cell at (row, col). Takes into account if the input cell is at an edge and does not return cells that would lie outside the board @param: 2D list - board: input board @param: int - row: row coordinate of the cell whose neighbors we get @param: int - col: col coordinate of the cell whose neighbors we get @return: list of tuples """ def get_neighbors(board, row, col): neighbors = [] diff = [-1, 0, 1] M, N = len(board), len(board[0]) for i in diff: if (row + i) < 0 or (row + i) >= M: continue for j in diff: if (col + j) < 0 or (col + j) >= N: continue if (i == j == 0) : continue neighbors.append((row+i,col+j)) return neighbors """ recursive_solve: helper function for solve that recursively searches the board using DFS while leveraging the Trie data structure to prevent searching deeper in directions where no valid words lie. @param: 2D list - board: input board @param: Trie - vocab_trie: Trie of the active vocabulary @param: 2D list - visited: 2D list equal in dimensions to the input board that maintains cells that have already been visited in this branch @param: int - row: row coordinate of the cell we are exploring from @param: int - col: col coordinate of the cell we are exploring from @param: str - word: word that has been produced so far from this branch of the search @return: list """ def recursive_solve(board, vocab_trie, visited, row, col, word): min_word_len = 3 output_words = [] visited[row][col] = True word = word + board[row][col] prefix = vocab_trie.is_valid(word) if len(word) >= min_word_len and prefix == 0: output_words.append(word) if prefix >= 0: neighbors = get_neighbors(board, row, col) for neighbor in neighbors: new_row = neighbor[0] new_col = neighbor[1] if not visited[new_row][new_col]: output_words = output_words + recursive_solve(board, vocab_trie, visited, new_row, new_col, word) # backtrack word = word[:-1] visited[row][col] = False return output_words """ solve: function to run the boggle word finder using DFS on an input board (storing a dictionary of valid words as a Trie). Returns list of all the output_words found in the board. @param: 2D list - board: input board @param: Trie - vocab_trie: Trie of the active vocabulary @return: list """ def solve(board, vocab_trie): M, N = len(board), len(board[0]) visited = [[False for i in range(N)] for j in range(M)] output_words = [] for row in range(M): for col in range(N): output_words = output_words + recursive_solve(board, vocab_trie, visited, row, col, "") return output_words """ construct_vocab_trie: given an input board and a dictionary txt file loads in the dictionary, reduces the dictionary to only include those words with characters that appear in the board, and populates and returns a Trie with that reduced dictionary @param: 2D list - board: input board @param: str - vocab_file: path to dictionary txt file @return: Trie """ def construct_vocab_trie(board, vocab_file): # flatten 2 dimensional board into single list of characters and remove duplicates to create # an alphabet of all the characters seen on the board alphabet = list(set([ch for row in board for ch in row])) full_vocab = vocab.load_dictionary(vocab_file) active_vocab = vocab.reduce_vocab(full_vocab, alphabet) # store vocab as trie for optimized checking if word is in the dictionary vocab_trie = trie.Trie(alphabet) vocab_trie.construct(active_vocab) return vocab_trie """ get_args: uses the argparse package to take in optional command line arguments specifying an input Boggle board and a txt file containing a dictionary of valid words. --board: board represented as a string with spaces between each row default board: "rael mofs teok nati" --vocab: txt file of vocabulary with each valid word on a new line default vocab: "dictionary.txt"; Source: http://www.gwicks.net/dictionaries.htm (194,000 English words) """ def get_args(): my_parser = argparse.ArgumentParser() my_parser.add_argument("-b", "--board", default = "rael mofs teok nati", type=str, help='board represented as a string with spaces between each row') my_parser.add_argument("-v", "--vocab", default = "dictionary.txt", type=str, help='txt file of vocabulary with each valid word on a new line') args = my_parser.parse_args() return args if __name__ == '__main__': args = get_args() # Convert board string into 2D array board_str = args.board board = [list(row) for row in board_str.split()] vocab_file = args.vocab vocab_trie = construct_vocab_trie(board, vocab_file) output_words = solve(board, vocab_trie) ## If we would like to ignore cases where the same word can be formed in multiple ways, ## uncomment the following: # output_words = list(set(output_words)) print(output_words)
####heapsort###### class Heap: def __init__(self, arr): self.arr = arr def heapify(self, arr, n, i): largest = i left = 2*i + 1 right = 2*i + 2 if left <n and arr[largest] < arr[left]: largest = left if right < n and arr[largest] < arr[right]: largest = right if largest != i: arr[i], arr[largest] = arr[largest], arr[i] self.heapify(arr, n, largest) def heapsort(self, arr): n = len(arr) for i in range(n, -1, -1): self.heapify(arr, n, i) for i in range(n-1, 0, -1): arr[i], arr[0] = arr[0], arr[i] self.heapify(arr, i, 0) def print_array(self, arr): for i in range(len(arr)): print(arr[i], end = " ") print()
#!/usr/bin/python3 """File storage class""" import json import os import datetime class FileStorage: """ Serializes instances to a JSON file and deserializes Json file to instances """ __file_path = "file.json" __objects = {} def all(self): """Returns the dictionary __objects""" return self.__objects def new(self, obj): """Sets in __objects the obj with key <obj class name>.id""" # obj.__dict__["updated_at"] = str(obj.__dict__["created_at"]) # obj.__dict__["created_at"] = str(obj.__dict__["created_at"]) self.__objects[str(obj.__class__.__name__) + "." + obj.id] = obj.__dict__ def save(self): """serializes __objects to a JSON path from __file_path """ new_dict = {} for key, value in self.__objects.items(): new_dict[key] = str(value) with open(FileStorage.__file_path, 'w') as filee: json.dump(new_dict, filee) def reload(self): """Deserializes the JSON file to __objects""" if os.path.isfile(self.__file_path): with open(self.__file_path, 'r') as my_file: one_obj_dictionary = json.load(my_file) for key, value in one_obj_dictionary.items(): self.__objects[key] = value else: return
#!/usr/bin/env python # ECE 2524 Homework 3 Problem 1 # Thomas Elliott import argparse import sys parser = argparse.ArgumentParser(description='Multiply some integers.') args = parser.parse_args() product = 1 for data in iter(sys.stdin.readline, ''): try: if data == '\n': print product product = 1 else: product *= int(data) except ValueError as e: e = "You must use only integers, other characters are not excepted\n" sys.stderr.write(e) sys.exit(1) print product
import pandas as pd import numpy as np if __name__ == "__main__": ''' Traditional way of running a linear regression: OLS method (ordinary least squares) 最小二乘法 Model deployment --- Score new data So, should we plug the original data of new file into the selected model directly? No, we should standardize data. (值-均值)/标准差 Of course, we should convert outcome into original data. Four questions we have answered - What is data partition? - When do we need to partition data? - Why do we need to partition data? - How do we partition data in Python? If we use only 60% percent of data to be training data, is it waste? Overfitting Data partition can help detect the overfitting issue - If a model overfits, we can detect the overfitting through its relative poor predictive performance over the test partition. Specifically, we can compare 1. The 'predictive performance' of the model over the non-test partition 2. The 'predictive performance' of the model over the test partition ''' # Part 7 Score the new data test_dict = {'Vacation':['No'] , 'SW':['No'], 'S_INCOME':[28760],'E_INCOME':[27664],'S_POP':[4557004],'E_POP':[3195503], 'SLOT':['Free'],'GATE':['Free'],'DISTANCE':[1976]} td = pd.DataFrame(test_dict) print(td) pass
""" TicTacToeParser Copyright(C) Simon Raichl 2018 MIT License """ from core import Core again = None while again is None or again == "y": print(Core().get_board()) again = input("Again? Y/N\n").lower()
#Return most-common number in list. def most_common(my_list): counter = 0 #initialize counter #loop through to get frequency of each element for number in my_list: frequency = my_list.count(number) #if current frequency is > than counter, update our counter with the new frequency if frequency > counter: counter = frequency return number print(most_common([1,1,2,2,2,2,2]))
#Return new list of tripled nums for those nums divisible by 4. def tripled_nums(nums): return [num**3 for num in nums if num%4 == 0]
# Is phrase a palindrome? def is_palindrome(phrase): converted_phrase = phrase.lower() reversed_word = converted_phrase[::-1] if converted_phrase == reversed_word: return "Is palindrome" else: return "Not palindrome" print(is_palindrome("Pop")) # Is palindrome print(is_palindrome("cat")) # Not palindrome print(is_palindrome("yooy")) # Is palindrome
import random import sys file1=open("Result3.txt","a+") class Game: def _init_(self): print("class initialised") def startgame(self): score=0 ques1=["Which was India’s first-ever tactical missile?"," Which type of coal is difficult to light in the open air?","Which industry was started first in India? ","Which metal is non toxic in nature?","Which is used as the logo of the World Wide Fund for Nature (WWF) ?"] ans1=["AGNI","PEAT","TEA","GOLD","PANDA"] for j in range(5,0,-1): x=random.randint(0,j-1) print(str(ques1[x]).upper()) a=input() if str(a).upper() == str(ans1[x]): print("YEAH!YOU ARE CORREECT!!!") score=score+10 else: print("OOPS!YOU ARE WRONG!!!") del ques1[x] del ans1[x] file1.write(str(score)+"\n") print(score,end='') def displaydetails(self): name,score=checkuser() print("ENTER YOUR CHOICE:\n1.SHOW ALL PARTICIPANTS SCORE\n2.SHOW WINNERS\n3.EXIT") choice=input() if choice == '' or int(choice) == 3: print('THANK YOU !') sys.exit() if(int(choice)==1): print("ALL PARTICIPANTS DETAILS") x=len(name) for i in range(0,x): print("NAME : "+name[i]+"\tSCORE : "+score[i]) elif(int(choice)==2): print("WINNER DETAILS:") x=max(score) y=len(score) if int(x)>0: for i in range(0,y): if int(x)==int(score[i]): print("NAME : "+name[i]+"\tSCORE : "+score[i]) else: print("NO WINNERS IN THE GAME") else: print("SORRY YOU HAVE ENTERED WRONG CHOICE") def checkuser(): name=list() score=list() file2=open("Result3.txt","r") content=file2.readlines() content = [x.strip() for x in content] x=len(content) for i in range(0,x): if i%2==0: name.append(content[i]) else: score.append(content[i]) return name,score s=Game() flag="y" temp=0 nam=list() while flag=="Y" or flag=="y": print("WELCOME TO THE GAME!!!") Name=input("ENTER YOUR NAME:") name,score=checkuser() x=len(nam) for i in range(0,x): if str(Name).upper()==str(nam[i]): temp=1 x=len(name) for i in range(0,x): if str(Name).upper()==str(name[i]): temp=1 break if temp==1: print("USERNAME HAS ALREADY ATTENDED!!!TRYWITH ANOTHER NAME!") else: nam.append(Name.upper()) file1.write(str(Name).upper()+"\n") s.startgame() print(" IS YOUR SCORE "+Name.upper()) print("ENTER Y TO CONTINUE") flag=input() temp=0 file1.close() flag="y" while flag=="Y" or flag=="y": s.displaydetails() print("ENTER Y TO CONTINUE DISPLAY DETAILS OR PRESS ANYOTHER KEY TO EXIT") flag=input() print("THANK YOU FOR PARTICIPATING IN THE QUIZ!!!")
name=input("enter the name:") if name>"a"and name<"z": surname=input("enter the surname") id=input("enter your email address or phone number") if id>"a"and id<"z"or id>"0" and id<"9"or id=="@": password=input("enter the password") if password>"a"and password <"z"or password<"9"or password=="@": print("its strong password") date=(input("enter the birth of date")) if date>"0" and date<"9": gender=input("enter the gender") if gender=="female"or gender=="male": print("your account is created successfully") else: print("abx") else: print("qwert") else: print("yuiop") else: print("fjjj") else: print("hhfjc")
# a=300-123 # num=int(input("enter the number")) # if a==num: # print("equal") # else: # print("not equal")
# a=int(input("enter the triangle")) # b=int(input("enter the triangle")) # c=int(input("enter the triangle")) # if a+b+c==180: # print("it is valid") # else: # print("not valid")
#이 클래스는 shipclass와 유사하다. import pygame from pygame.sprite import Sprite import random class Fish(Sprite): """첫번째 물고기 하나를 표현하는 클래스""" def __init__(self, screen,p): """물고기를 초기화하고 시작 위치를 지정한다""" super(Fish, self).__init__() self.screen = screen #물고기 이미지를 불러오고 이 이미지를 rect 속성으로 설정한다 self.image = pygame.image.load('img/fish4.png') self.rect = self.image.get_rect() try: self.screen_rect = screen.get_rect() except: p=0 #물고기는 화면 왼쪽에서 나옵니다. self.x = float(self.rect.x) self.rect.y = random.randint(250,450) #이 물고기는 y좌표 250부터 450사이에서 나옵니다 self.speed_factor = 11 self.name=("현재잡은 물고기는 2.5kg에요 (게임 상)\n 이름: 꽁치, 꽁치는 봄이 되면 동해안에서 떼를 지어 산란하고 동해와 남해, 북태평양에 서식해요!|\n") #물고기 설명 self.weight=2.5 #물고기 무게 def nameing(self): print(self.name) def update(self,fishes): #물고기 위치 업데이트 """물고기를 오른쪽으로 움직이고 화면밖을 지나가면 없애버림""" self.x += self.speed_factor self.rect.x = self.x for fish in fishes.copy(): if fish.rect.left>=800: fishes.remove(fish) def blitme(self): #물고기를 스크린에 띄우기 self.screen.blit(self.image, self.rect) class Fish2(Sprite): """두번째 물고기를 표현하는 클래스""" def __init__(self, screen,p): super(Fish2, self).__init__() self.screen = screen self.image = pygame.image.load('img/fish2.png') self.rect = self.image.get_rect() try: self.screen_rect = screen.get_rect() except: p=0 self.x = float(self.rect.x) self.rect.y = random.randint(320,520) self.speed_factor = 8 self.name=("현재잡은 물고기는 2kg에요 (게임 상)\n이름: 아귀, 아귀는 주로 태평양과 인도양에서 서식하며 물고기와 오징어를 먹어요!\n") self.weight=2 def nameing(self): print(self.name) def update(self,fishes): self.x += self.speed_factor self.rect.x = self.x for fish in fishes.copy(): if fish.rect.left>=800: fishes.remove(fish) def blitme(self): self.screen.blit(self.image, self.rect) class Fish3(Sprite): def __init__(self, screen,p): super(Fish3, self).__init__() self.screen = screen self.image = pygame.image.load('img/fish3.png') self.rect = self.image.get_rect() try: self.screen_rect = screen.get_rect() except: p=0 self.x = float(self.rect.x) self.rect.y = random.randint(400,600) self.speed_factor = 8 self.name=("현재잡은 물고기는 3.5kg에요 (게임 상)\n이름: 홍가자미, 홍가자미는 일본 북부 캄차카반도까지 서식하며 갑각류를 먹어요!\n") self.weight=3.5 def nameing(self): print(self.name) def update(self,fishes): self.x += self.speed_factor self.rect.x = self.x for fish in fishes.copy(): if fish.rect.left>=800: fishes.remove(fish) def blitme(self): self.screen.blit(self.image, self.rect) class Fish4(Sprite): def __init__(self, screen,p): super(Fish4, self).__init__() self.screen = screen self.image = pygame.image.load('img/fish_1.png') self.rect = self.image.get_rect() try: self.screen_rect = screen.get_rect() except: p=0 self.x = float(self.rect.x) self.rect.y = random.randint(460,620) self.speed_factor = 6 self.name=("현재잡은 물고기는 1.5kg에요 (게임 상)\n이름: 고등어, 태평양, 고등어는 대서양에서 주로 서식하고 오징어,작은 어류를 주로 먹어요!\n") self.weight=1.5 def nameing(self): print(self.name) def update(self,fishes): self.x += self.speed_factor self.rect.x = self.x for fish in fishes.copy(): if fish.rect.left>=800: fishes.remove(fish) def blitme(self): self.screen.blit(self.image, self.rect) class Fish5(Sprite): def __init__(self, screen,p): super(Fish5, self).__init__() self.screen = screen self.image = pygame.image.load('img/fish5.png') self.rect = self.image.get_rect() try: self.screen_rect = screen.get_rect() except: p=0 self.x = float(self.rect.x) self.rect.y = random.randint(300,450) self.speed_factor = 5 self.name=("현재잡은 물고기는 4kg에요 (게임 상)\n광어(넙치), 광어는 바다의 바닥에 붙어서 살고 바닥에 따라 몸의 무늬가 바뀌어요!\n") self.weight=3.5 def nameing(self): print(self.name) def update(self,fishes): self.x += self.speed_factor self.rect.x = self.x for fish in fishes.copy(): if fish.rect.left>=800: fishes.remove(fish) def blitme(self): self.screen.blit(self.image, self.rect) class Fish6(Sprite): def __init__(self, screen,p): super(Fish6, self).__init__() self.screen = screen self.image = pygame.image.load('img/fish6.png') self.rect = self.image.get_rect() try: self.screen_rect = screen.get_rect() except: p=0 #물고기는 화면 왼쪽에서 나옵니다. self.x = float(self.rect.x) self.rect.y = random.randint(350,550) self.speed_factor = 12 self.name=("현재잡은 물고기는 1kg에요 (게임 상)\n이름: 망상어,망상어는 알을 품어 그 새끼가 알에서 나오면새끼를 낳아요!\n") self.weight=1 def nameing(self): print(self.name) def update(self,fishes): #물고기 위치 업데이트 self.x += self.speed_factor self.rect.x = self.x for fish in fishes.copy(): if fish.rect.left>=800: fishes.remove(fish) def blitme(self): #물고기를 스크린에 띄우기 self.screen.blit(self.image, self.rect) class Shark(Sprite): """아기상어를 표현하는 클래스""" def __init__(self, screen): """상어를 초기화하고 시작 위치를 지정한다""" super(Shark, self).__init__() self.screen = screen #상어 이미지를 불러오고 이 이미지를 rect 속성으로 설정한다 self.image = pygame.image.load('img/Shark.png') self.rect = self.image.get_rect() self.screen_rect = screen.get_rect() #상어는 다른물고기와 다르게 화면 오른쪽에서 나옵니다. self.x = float(800-(self.rect.x)) self.rect.y = random.randint(250,550) self.speed_factor = 18 self.name=("이름:백상아리, 백상아리는 무시무시한 바다의 포식자에요!\n") self.weight=21 #상어를 잡으면 게임종료 def nameing(self): print(self.name) def update(self,fishes): #상어 위치 업데이트 """물고기를 오른쪽으로 움직이고 화면밖을 지나가면 없애버림""" self.x -= self.speed_factor self.rect.x = self.x for fish in fishes.copy(): if fish.rect.right<=0: fishes.remove(fish) def blitme(self): #상어를 스크린에 띄우기 self.screen.blit(self.image, self.rect)
mylist=[89,39,90,62,77,56] print('elements in the list',mylist) listsum=sum(mylist) print('sum of elements in the list is:: ',listsum)
# This is going to be a really crappily designed idle game tbh # Modules import random from time import sleep from os import system, name #global vars gold = 1 max_health = 10 curr_health = 10 attack = 3 max_mana = 10 curr_mana = 10 level = 1 intel = 3 luck = 1 speed = 3 crit_chance = 1 crit_strike = 1 wisdom = 3 curr_floor = 1 player_name = 'NA' gender = 'NA' null = '0' null_pass = 1 #Creation of the character! This will be before the main menu and not able to be returned to def create(): global gold, max_health, max_mana, curr_health, curr_mana, level, attack, intel, luck, speed, crit_chance, crit_strike, wisdom, player_name, gender, curr_floor, null, major, minor difficulty = 0 major = 0 minor = 0 null = 0 clear() print('Hello and welcome to the never ending tower of Doom.... I kid, but really it is dangrous, if you die on this tower, then you are done for good there are no secound chances in this tower. The higer in the tower that you manage the more money, riches, and other wonderful tresures will be yours, but you have to fight for it. This will be your greatest challenge in your life. Will you take the challenge or will you give up before even starting.') pause() # ^^ Opening statement to the game I guess player_name = str(input(' What is your name? ')) # Changes everything but luck gender = str(input(' What is your gender? ')) # Changes total luck while difficulty == 0 or difficulty < 1 or difficulty > 10: # Checks and makes sure the this number is an interger try: difficulty = int(input(' From a scale from 1-10 how much do you hate yourself? ')) # Height of the tower difficulty * 10 if difficulty < 1 or difficulty > 10: # Confirms the vlaues is within range print(' That is not within the correct range') sleep(1) else: pass except ValueError: print(' Only a number will do') sleep(1) print('\n Thank you your input will change how the game is played\n \n The next step is that we are going to chose the focuse areas of your character, there are no classes, because I have no idea of what I want to do with those yet') pause() clear() print('\nThis is how it is going to work, you are going to pick a major and minor stat this will give thoes stats a higher chance to grow per level that you gain. Finally you can also pick a null stat this will stop this stat from growing but give major stat a 100% chance to increase every level') try: null_choice = int(input( '\n Would you like to use a null stat 1-Yes 0-No: ')) if null_choice == 1: while True: clear() print_stats() try: stat_choice = int(input('\n What stat do you just not care about? (You can not Null out health yet.....): ')) if stat_choice == 1: #Health print('Nope you can not null out health yet') sleep(1) elif stat_choice == 2: #Mana max_mana = 0 curr_mana = 0 null = 'Mana' print(' It is done your Mana will be 0') break elif stat_choice == 3: #Attack attack = 0 null = 'Attack' print(' It is done your Strength will be 0') break elif stat_choice == 4: #Speed speed = 0 null = 'Speed' print(' It is done your Aglity will be 0') break elif stat_choice == 5: #Intelligance intel = 0 null = 'Intelligance' print(' It is done your Intelligance will be 0') break elif stat_choice == 6: #Wisdom wisdom = 0 null = 'Wisdom' print(' It is done your Wisdom will be 0') break elif stat_choice == 7: #Critical Chance crit_chance = 0 null = 'Critical Chance' print(' It is done your Critical Chance will be 0') break elif stat_choice == 8: #Critical Strike crit_strike = 0 null = 'Critical Strike' print(' It is done your Critical Strike will be 0') break elif stat_choice == 9: #Luck luck = 0 null = 'Luck' print(' It is done your Luck will be 0') break else: print(' That is not a valid option') sleep(1) except ValueError: print(' Only a number will do') elif null_choice == 0: print(' Cool, moving on to picking your major and minor stats') else: print(' That is not a valid option') sleep(1) except ValueError: print(' Only a number will do') sleep(1) pause() # This will allow the player to select the Major stat clear() print('\n For your Major stat you will start with 2 extra bonus points and a 66% chance that you will level up in that stat. For your minor stat you will start with one extra point and a 40% to earn a point every level. For all other stats you will have a 15% to gain a point in any of the remaining skills. \n Note: If you have a null stat then you will have a 100% chance to gain a point in your major stat. \n') print_stats() while True: try: major_choice = int(input('\n What do you want your major stat to be?: ')) if major_choice == 1: #Health if null == 'Health': print('This is your null stat it can not be your major stat') else: max_health = 12 curr_health = max_health major = 'Health' print('Your total health has been set to:', max_health) break elif major_choice == 2: #Mana if null == 'Mana': print('This is your null stat it can not be your major stat') else: max_mana = 12 curr_mana = max_mana major = 'Mana' print('Your total mana has been set to:', max_mana) break elif major_choice == 3: #Attack if null == 'Attack': print('This is your null stat it can not be your major stat') else: attack = 5 major = 'Attack' print('Your strength has been set to:', attack) break elif major_choice == 4: #Speed if null == 'Speed': print('This is your null stat it can not be your major stat') else: speed = 5 major = 'Speed' print('Your aglity has been set to:', speed) break elif major_choice == 5: #Intelligance if null == 'Intelligance': print('This is your null stat it can not be your major stat') else: intel = 5 major = 'Intelligance' print('Your intelligance has been set to:', intel) break elif major_choice == 6: #Wisdom if null == 'Wisdom': print('This is your null stat it can not be your major stat') else: wisdom = 5 major = 'Wisdom' print('Your wisdom has been set to:', wisdom) break elif major_choice == 7: #Critical Chance if null == 'Critical Chance': print('This is your null stat it can not be your major stat') else: crit_chance = 3 major = 'Critical Chance' print('Your criical chance has been set to:', crit_chance) break elif major_choice == 8: #Critical Strike if null == 'Critical Strike': print('This is your null stat it can not be your major stat') else: crit_strike = 3 major = 'Critical Strike' print('Your critical strike has been set to:', crit_strike) break elif major_choice == 9: #Luck if null == 'Luck': print('This is your null stat it can not be your major stat') else: luck = 3 major = 'Luck' print('Your luck has been set to:', luck) break else: print(' That is not a valid option') sleep(1) except ValueError: print(' Only a number will do') while True: # Picking the minor stat try: minor_choice = int(input('\n What do you want your minor stat to be?: ')) if minor_choice == 1: #Health if null == 'Health': print('This is your null stat it can not be your minor stat') elif null == 'Health': print('This is your major stat it can not be your minor stat') else: max_health = 11 curr_health = max_health minor = 'Health' print('Your total health has been set to:', max_health) break elif minor_choice == 2: #Mana if null == 'Mana': print('This is your null stat it can not be your minor stat') elif major == 'Mana': print('This is your major stat it can not be your minor stat') else: max_mana = 11 curr_mana = max_mana minor = 'Mana' print('Your total mana has been set to:', max_mana) break elif minor_choice == 3: #Attack if null == 'Attack': print('This is your null stat it can not be your minor stat') elif major == 'Attack': print('This is your major stat it can not be your minor stat') else: attack = 4 minor = 'Attack' print('Your strength has been set to:', attack) break elif minor_choice == 4: #Speed if null == 'Speed': print('This is your null stat it can not be your minor stat') elif major == 'Speed': print('This is your major stat it can not be your minor stat') else: speed = 4 minor = 'Speed' print('Your aglity has been set to:', speed) break elif minor_choice == 5: #Intelligance if null == 'Intelligance': print('This is your null stat it can not be your minor stat') elif major == 'Intelligance': print('This is your major stat it can not be your minor stat') else: intel = 4 minor = 'Intelligance' print('Your intelligance has been set to:', intel) break elif minor_choice == 6: #Wisdom if null == 'Wisdom': print('This is your null stat it can not be your minor stat') elif major == 'Wisdom': print('This is your major stat it can not be your minor stat') else: wisdom = 4 minor = 'Wisdom' print('Your wisdom has been set to:', wisdom) break elif minor_choice == 7: #Critical Chance if null == 'Critical Chance': print('This is your null stat it can not be your minor stat') elif major == 'Critical Chance': print('This is your major stat it can not be your minor stat') else: crit_chance = 2 minor = 'Critical Chance' print('Your criical chance has been set to:', crit_chance) break elif minor_choice == 8: #Critical Strike if null == 'Critical Strike': print('This is your null stat it can not be your minor stat') elif major == 'Critical Strike': print('This is your major stat it can not be your minor stat') else: crit_strike = 2 minor = 'Critical Strike' print('Your critical strike has been set to:', crit_strike) break elif minor_choice == 9: #Luck if null == 'Luck': print('This is your null stat it can not be your minor stat') elif major == 'Luck': print('This is your major stat it can not be your minor stat') else: luck = 2 minor = 'Luck' print('Your luck has been set to:', luck) break else: print(' That is not a valid option') sleep(1) except ValueError: print(' Only a number will do') # This is going to be changes to the players stats that I won't tell the player about, because fuck them change_luck = (len(gender) // 2) # I want a higher luck stat to make the game harder somehow, either with harder monsters, or making the tower taller. chance = random.randint(0, 10) + luck if chance <= 5: luck = luck - change_luck else: luck = luck + change_luck if luck < 0: # makes sure that luck does not go negitive luck = 0 else: pass # plan to do somthing with the name len as well, but I do not know what to do for now pause() #Main menu def main(): global gold, curr_floor choice = 0 while choice == 0: # While loop will reset when the main function is called again. This is correct for incorrect inputs clear() print('\n Welcome to the main menu! The following are your options\n \n 1-See Character Info\n 2-Attack a New Monster\n 3-Inventory\n 4-Blacksmith\n 5-Item Merchant\n 6-Go up a floor\n 7-Leave the Tower') basestats() try: choice = int(input('\n What would you like to do?: ')) if choice == 1: # This statment will move the players choice on to the correct function stats() elif choice == 2: mon1() elif choice == 3: inventory() elif choice == 4: blacksmith() elif choice == 5: itmm() elif choice == 6: floor() elif choice == 7: exit() else: print('You did not enter a valid option') sleep(1) except ValueError: print('You did not enter a valid option') sleep(1) # Base stats, this is to show basic vlaues like current health, and mana and attack def basestats(): global gold, max_health, max_mana, curr_health, curr_mana, level, curr_floor, stats print('\n You are currently level', level, '\n Your current health is', curr_health, '/', max_health, '\n Your current mana is', curr_mana, '/', max_mana) print('\n You currently have: ', gold, 'gold.') print(' You are currently on floor: ', curr_floor) # Stats, shows the stats for the character that you have farther then basic stats shown in the welcome screen def stats(): global gold, max_health, max_mana, curr_health, curr_mana, level, attack, intel, luck, speed, crit_chance, crit_strike, wisdom, null, major, minor, player_name, gender, curr_floor clear() print('\n Hello', player_name, ' with the you are the gender of', gender) print('\n This is your current stats!') print('\n You are currently level', level, '\n Your current health is', curr_health, '/', max_health, '\n Your current mana is', curr_mana, '/', max_mana) print('\n You currently have,', gold, 'gold.') print(' You are currently on floor: ', curr_floor) print('\n Other stats') print('\n Strength: ', attack, '\n Aglity: ', speed, '\n Intelligance: ', intel, '\n Wisdom: ', wisdom, '\n Critical chance: ', crit_chance, '\n Critical Strike: ', crit_strike, '\n Luck: ', luck) if null == '0': print ('\n Your major stat is', major, '\n Your minor stat is', minor) else: print ('\n Your major stat is', major, '\n Your minor stat is', minor, '\n Your null stat is', null) pause() main() #Monster rng 1 basic easy grunt monster def mon1(): monster_name = [ 'Skeleton', 'Goblin', 'Chicken', 'Spider' ] print('\n mon1 \n') #Monster rng 2 medium monster def mon2(): print('\n mon2 \n') #Monster rng 3 mini boss level monsters. #You will have to add more functions for the other monsters to change the diffrent move pools, but that is for a later time def mon3(): print('\n mon3 \n') #Blacksmith alloes the crafting of basic items def blacksmith(): print('\n blacksmith \n') #Item Merchant buying assorricies/potions, and other crafting materials def itmm(): print('\n itmm \n') #Function to go up a floor will check if you are high enough level/fought enought monsters def floor(): print('\n floor \n') #Looking at and managing the inventory of the player def inventory(): print('\n This is what is currently in your bag\n') #Clear the screan function to make the program look cleaner def clear(): if name == 'nt': _ = system('cls') else: _ = system('clear') #Pause and wait until player input def pause(): programPause = input("\n Press the <ENTER> key to continue...") # Im lazy and this is in my program like 3 times def print_stats(): print('\n You have the following stats, \n \n 1-Health \n 2-Mana \n 3-Strength \n 4-Aglity \n 5-Intelligance \n 6-Wisdom \n 7-Critical Chance \n 8-Critical Strike \n 9-Luck') create() main()
s1 = int(raw_input("enter side 1 length ")) s2 = int(raw_input("enter side 2 length ")) s3 = int(raw_input("enter side 3 length ")) if #YOUR CODE HERE: print("can make a triangle") else: print("can't make a triangle") # Try lengths: # s1 = 5, s2 = 6, s3 = 7 -> can make # s1 = 1, s2 = 2, s3= 6 -> can't make # try some more!
produto = input('digite o nome do produto: ') categoria = int(input('digite a categoria do produto: 1- Alcoolico 2- Não Alcoolico')) if categoria == 1: print(f'\nProduto: {produto}\nCategoria: Alcoolico') else: print(f'\nProduto: {produto}\nCategoria: Não Alcoolico')
lista = [] lista2 = ['Marcela', 'Nicole', '*Matheus', 10] lista3 = [1, 2, 3, 5] print(lista) print(lista2) print(lista3) lista.append(lista2) lista.append(lista3) print(lista) lista_perguntas = [input('Digite seu artista favorito'), input('Digite seu guitarrista favorito')] print(lista_perguntas) posicao = int(input('Digite a posicao: ')) print(lista2[posicao-1])
from sys import argv script, file = argv #used to move the file on def advance(): global currentLine currentLine = source.readline() #determines what type of comman is on that line def commandType(currentLine): if currentLine[0] == '(': return 'L' elif currentLine[0] == '@': return 'A' else: return 'C' #returns the symbol for L and A commands def symbol(currentLine): #handles L commands to return whatever is in parentheses if currentLine[0] == '(': symbol = currentLine[1:-1] return symbol #handles a commands to return whatever is after the at symbol if currentLine[0] == '@': symbol = currentLine[1:] return symbol #returns the destination memonic for a c command def dest(currentLine): if currentLine.count('=') > 0: dest = currentLine.split('=') return dest[0] else: return None #returns the computation memonic for C commands. handles 4 cases def comp(currentLine): #all cases that have a destination or a jump if currentLine.count('=') > 0 or currentLine.count(';') > 0: #if both are present if currentLine.count('=') > 0 and currentLine.count(';') > 0: comp = currentLine.split('=') comp = comp[1].split(';') return comp[0] #if only jump is present if currentLine.count(';') > 0: comp = currentLine.split(';') return comp[0] #if only destination is present else: comp = currentLine.split('=') return comp[1] #no destination or jump else: return currentLine #returns the jump field in a C command def jump(currentLine): if currentLine.count(';') > 0: jump = currentLine.split(';') return jump[1] else: return None source = open(file) numLines = len(source.readlines()) source.seek(0) #list to store the output with comments stripped tokenStream = [] for line in range(numLines): advance() #makes a list out of the string split at the coment symbol currentLine = currentLine.split('//') #if a coment was present removes it from the list created by the split if len(currentLine) > 1: currentLine.pop(1) currentLine = currentLine[0].strip() #handles lines with only comments by only appending non empty strings if currentLine != '': tokenStream.append(currentLine) source.seek(0) out = [] #main processing loop. Takes each line and splits it into a list of its components which is appended to the master list for line in tokenStream: if commandType(line) == 'C': temp = ['C', dest(line), comp(line), jump(line)] out.append(temp) else: temp = [commandType(line), symbol(line).isdigit(), symbol(line)] out.append(temp) def main(): return out
#攝氏('C')轉換成華氏('F')程式 cels = input('請輸入攝氏溫度: ') cels = float(cels) fahr = float(cels * (9 / 5) + 32) print('攝氏轉換成華氏:%3.1f ', fahr) print('攝氏轉換成華氏:%.2f '%fahr)
#! /usr/bin/python # coding:utf-8 def do_sort(): # 冒泡排序要排序n个数,由于每遍历一趟只排好一个数字, # 则需要遍历n-1趟,所以最外层循环是要循环n-1次,而 # 每趟遍历中需要比较每归位的数字,则要在n-1次比较 # 中减去已排好的第i位数字,即每趟循环要遍历是n-1-i次 lst = [1, 4, 3, 5, 2] for i in range(len(lst)-1): for j in range(len(lst)-1-i): if lst[j] < lst[j+1]: lst[j], lst[j+1] = lst[j+1], lst[j] # 这里使用的是序列解包进行值互换 print(lst) do_sort()
def count_games(file_name): with open(file_name, 'r') as source_file: return sum(1 for line in source_file) def decide(file_name, year): if str(year) in open(file_name).read(): return True else: return False def list_from_file(file_name, place, type): data = [] with open(file_name, 'r') as source_file: for line in source_file: data.append(line.strip().split('\t')) temp = [] counter = 0 for item in data: temp.append(type(data[counter][place])) counter += 1 return data, temp, counter def get_latest(file_name): data, temp, counter = list_from_file(file_name, 2, int) latest = temp.index(max(temp)) return str(data[latest][0]) def count_by_genre(file_name, genre): data, temp, counter = list_from_file(file_name, 3, str) genre_dict = dict((i, temp.count(i)) for i in temp) return genre_dict.get(genre) def get_line_number_by_title(file_name, title): try: data, temp, counter = list_from_file(file_name, 0, str) return int(temp.index(title)) + 1 except BaseException: raise ValueError def sort_abc(file_name): data, temp, counter = list_from_file(file_name, 0, str) new_list = [] while temp: minimum = min(temp) for item in temp: if item < minimum: minimum = item new_list.append(minimum) temp.remove(minimum) return new_list def get_genres(file_name): data, temp, counter = list_from_file(file_name, 3, str) new_list = set(temp) return sorted(new_list, key=str.lower) def when_was_top_sold_fps(file_name): try: data, temp, counter = list_from_file(file_name, 3, str) date = [] sold = [] place = 0 for item in temp: if item == 'First-person shooter': date.append(int(data[place][2])) sold.append(float(data[place][1])) place += 1 top_sold = sold.index(max(sold)) return int(date[top_sold]) except BaseException: raise ValueError
################################################################## # 해당 소스파일의 저작권은 없습니다. # 필요하신 분들은 언제나 사용하시길 바라며, 해당 소스코드의 부족한 부분에 대해서는 # [email protected]으로 언제든지 피드백 주시길 바랍니다. # 소스설명 : 데이터 읽기 함수로 EDA 등 데이터분석이 끝난 데이터를 읽어오는 함수입니다. # 포함함수 : csv 파일 읽기, excel 파일 읽기 ################################################################## def read_csv(address): import pandas as pd data = pd.read_csv(address) print("데이터 shape \n {}".format(data.shape)) print("데이터 5개 미리보기 \n {}".format(data.head(5))) print("데이터 정보 \n {}".format(data.info())) print("null값을 가지고 있는 데이터 \n {}".format(data.isnull().sum())) return data def read_excel(address): import pandas as pd data = pd.read_excel(address) #print("데이터 shape \n {}".format(data.shape)) #print("데이터 5개 미리보기 \n {}".format(data.head(5))) #print("데이터 정보 \n {}".format(data.info())) #print("null값을 가지고 있는 데이터 \n {}".format(data.isnull().sum())) return data
# Linguagem de estimacao escolhida: Python from socket import * type = raw_input("HTTP, FTP ou SMTP?\n") while (not type.upper() in ['HTTP', 'FTP', 'SMTP']): type = raw_input("Por favor, coloque um protocolo valido (HTTP, FTP ou STMP)\n") # Codigo caso a requisicao seja valida if (type.upper() == "HTTP" or type.upper() == "FTP" or type.upper() == "SMTP"): serverName = raw_input("Digite o servidor:\n") serverPort = raw_input("Digite a porta:\n") # Cria o socket do cliente # AF_INET => rede utilizando IPv4 # SOCK_STREAM => socket TCP clientSocket = socket(AF_INET, SOCK_STREAM) # Estabelece a conexao TCP com o servidor clientSocket.connect((serverName,int(serverPort))) # Codigo Protocolo HTTP if type.upper() == "HTTP": requisicao = raw_input('Digite sua requisicao: ') requisicao = requisicao + "\r\n" + 'Host: ' + serverName + "\r\n\r\n" # Envia a requisicao para o servidor clientSocket.send(requisicao) # Recebe a resposta serverResponse = clientSocket.recv(1024) print '\nhttp> ' + serverResponse + '\n' # Fecha a conexao TCP entre cliente e o servidor clientSocket.close() # Codigo Protocolo FTP if type.upper() == "FTP": serverResponse = clientSocket.recv(1024) print '\nftp> ' + serverResponse + '\n' requisicao = raw_input('Digite sua requisicao: ') requisicao = requisicao + "\r\n" # Envia a requisicao FTP para o servidor clientSocket.send(requisicao) # Recebe a resposta serverResponse = clientSocket.recv(1024) print '\nftp> ' + serverResponse + '\n' # Fecha a conexao TCP entre cliente e o servidor clientSocket.close() # Codigo Protocolo SMTP if type.upper() == "SMTP": serverResponse = clientSocket.recv(1024) print '\nsmtp> ' + serverResponse + '\n' requisicao = raw_input('Digite sua requisicao: ') requisicao = requisicao + "\r\n" # Envia a requisicao SMTP para o servidor clientSocket.send(requisicao) # Recebe a resposta serverResponse = clientSocket.recv(1024) print '\nsmtp> ' + serverResponse + '\n' # Fecha a conexao TCP entre cliente e o servidor clientSocket.close()
import random def jogar_forca(): print("Bem vindo ao jogo de forca!") palavra_secreta = carrega_palavra() letras_acertadas = ininializa_letras_acertadas(palavra_secreta) enforcou = False acertou = False erros = 0 print(letras_acertadas) while (not enforcou and not acertou): chute = input("Qual letra? ") # Retira os espaços chute = chute.strip().upper() # unper retorna sempre em maisculas, para minusculas utilizar o lower if (chute in palavra_secreta): index = 0 for letra in palavra_secreta: if (chute == letra): letras_acertadas[index] = letra index += 1 else: erros += 1 enforcou = erros == 6 # limita o numero de tentativas em 6 acertou = "_" not in letras_acertadas print(letras_acertadas) if (acertou): print("Parabéns você ganhou!") else: print("Você perdeu, a palavra secreta era",format(palavra_secreta)) print("Fim de jogo") def carrega_palavra(): arquivo = open("palavras.txt", "r") palavras = [] for linha in arquivo: linha = linha.strip() palavras.append(linha) arquivo.close() numero = random.randrange(0, len(palavras)) palavra_secreta = palavras[numero].upper() return palavra_secreta def ininializa_letras_acertadas(palavra): return ["_" for letra in palavra] if (__name__ == "__main__"): jogar_forca()
import random import pygame pygame.init() class Circle: def __init__(self, x, y, radius): self.x = x self.y = y self.radius = radius self.color = [255, 0, 0] self.direction = "up" def draw(self, window): pygame.draw.circle(window, self.color, (self.x, self.y), self.radius) def resize(self): if self.direction == "down": self.radius -= 1 if self.radius < 10: self.direction = "up" elif self.direction == "up": self.radius += 1 if self.radius > 100: self.direction = "down" def recolor(self): rgb = random.randint(0, 2) if self.color[rgb] < 254: self.color[rgb] += 10 if self.color[rgb] >= 254: self.color[rgb] = 0
from tkinter import * from math import sqrt def distance(x1, y1, x2, y2): "distance séparant les points x1,y1 et x2,y2" d = sqrt((x2-x1)**2 + (y2-y1)**2) # théorème de Pythagore return d def forceG(m1, m2, di): "force de gravitation s'exerçant entre m1 et m2 pour une distance di" return m1*m2*6.67e-11/di**2 # loi de Newton def avance(n, gd, hb): "déplacement de l'astre n, de gauche à droite ou de haut en bas" global x, y, step # nouvelles coordonnées : x[n], y[n] = x[n] +gd, y[n] +hb # déplacement du dessin dans le canevas : can.coords(astre[n], x[n]-10, y[n]-10, x[n]+10, y[n]+10) # calcul de la nouvelle interdistance : di = distance(x[0], y[0], x[1], y[1]) # conversion de la distance "écran" en distance "astronomique" : diA = di*1e9 # (1 pixel => 1 million de km) # calcul de la force de gravitation correspondante : f = forceG(m1, m2, diA) # affichage des nouvelles valeurs de distance et force : valDis.configure(text="Distance = " +str(diA) +" m") valFor.configure(text="Force = " +str(f) +" N") # adaptation du "pas" de déplacement en fonction de la distance : step = di/10 def gauche1(): avance(0, -step, 0) def droite1(): avance(0, step, 0) def haut1(): avance(0, 0, -step) def bas1(): avance(0, 0, step) def gauche2(): avance(1, -step, 0) def droite2(): avance (1, step, 0) def haut2(): avance(1, 0, -step) def bas2(): avance(1, 0, step) # Masses des deux astres : m1 = 6e24 # (valeur de la masse de la terre, en kg) m2 = 6e24 # astre = [0]*2 # liste servant à mémoriser les références des dessins x =[50., 350.] # liste des coord. X de chaque astre (à l'écran) y =[100., 100.] # liste des coord. Y de chaque astre step =10 # "pas" de déplacement initial # Construction de la fenêtre : fen = Tk() fen.title(' Gravitation universelle suivant Newton') # Libellés : valM1 = Label(fen, text="M1 = " +str(m1) +" kg") valM1.grid(row =1, column =0) valM2 = Label(fen, text="M2 = " +str(m2) +" kg") valM2.grid(row =1, column =1) valDis = Label(fen, text="Distance") valDis.grid(row =3, column =0) valFor = Label(fen, text="Force") valFor.grid(row =3, column =1) # Canevas avec le dessin des 2 astres: can = Canvas(fen, bg ="light yellow", width =400, height =200) can.grid(row =2, column =0, columnspan =2) astre[0] = can.create_oval(x[0]-10, y[0]-10, x[0]+10, y[0]+10, fill ="red", width =1) astre[1] = can.create_oval(x[1]-10, y[1]-10, x[1]+10, y[1]+10, fill ="blue", width =1) # 2 groupes de 4 boutons, chacun installé dans un cadre (frame) : fra1 = Frame(fen) fra1.grid(row =4, column =0, sticky =W, padx =10) Button(fra1, text="<-", fg ='red',command =gauche1).pack(side =LEFT) Button(fra1, text="->", fg ='red', command =droite1).pack(side =LEFT) Button(fra1, text="^", fg ='red', command =haut1).pack(side =LEFT) Button(fra1, text="v", fg ='red', command =bas1).pack(side =LEFT) fra2 = Frame(fen) fra2.grid(row =4, column =1, sticky =E, padx =10) Button(fra2, text="<-", fg ='blue', command =gauche2).pack(side =LEFT) Button(fra2, text="->", fg ='blue', command =droite2).pack(side =LEFT) Button(fra2, text="^", fg ='blue', command =haut2).pack(side =LEFT) Button(fra2, text="v", fg ='blue', command =bas2).pack(side =LEFT) fen.mainloop()
""" ===> Programa: Interface ===> Função: Criar GUI ===> Descrição: Criar Widgets dinamicamente para uso da GUI ===> Criador: Adenisio Pereira de Freitas ===> Ano Criação: 2018 """ #importando classe tkinter from tkinter import * class Interface(object): def __init__(self, instanciaTK): #instanciando classe interface e passando como parametro um endereço da instacia de tkinter da classe principal self.tk = instanciaTK #carregando variavel com parametro tkinter #criando um lable para inserir as mensagens das caixas de aviso e entradas de dados def setLblText(self, txt): self.txt_lbl = Label(self.tk, text=txt) self.txt_lbl.pack() #label mensagem para mosttrar resultado de funções processadas def setLblmensagem(self, txt): self.lbl_mensagem = Label(self.tk, text=txt) self.lbl_mensagem.pack() #muda o valor da mensagem quando um processo é concluido def mudaMensagen(self, txt): self.lbl_mensagem['text'] = txt #imput de entrada para dados, carrega dados do usuario, variaveis que receberam e manterão esses dados seram da classe DTO def setInput(self): self.txt_entry = Entry(self.tk) self.txt_entry.pack() return self.txt_entry #temos que retornar toda a estrutura do entry #cria um botão que recebe o texto e a função que usuari definir na classe principal def setBtn(self, txt, cmd): self.btn = Button(self.tk, text=txt, command=cmd) self.btn.pack()
#coding:utf8 # staticmethod 不会收到默认的第一个参数 cls。 # staticmethod 类似于Java中的 静态方法 # classmethod 可以说是 静态方法的一个变种,多出来的第一个参数,有时会有神奇的作用。 class A(object): @staticmethod def f(arg1, arg2): print arg1,arg2 # 静态方法 可以用 类名,或者 实例来调用 A.f(1,3) A().f(3,4)
velocidade = float(input('Qual a velocidade do seu carro? Km/h _')) if velocidade > 80: excesso = velocidade - 80 print(f'Você excedeu em {excesso:.2f} Km/h o limite de velocidade e a sua multa é de {excesso*7:.2f} MZN') print('Continuação de boa viagem')
pauta = [] templis = [] contador = 0 while True: pauta.append(templis[:]) nome = input("Nome: ") nota1 = float(input("Nota 1: ")) nota2 = float(input("Nota 2: ")) stop = input("Quer continuar? (s/n)").upper() pauta[contador].append(nome) pauta[contador].append(nota1) pauta[contador].append(nota2) templis.clear() contador += 1 #A solucao mais simples é ler tudo e fazer o append ja como lista. if stop == "N": #Sem necessidade de contadores ou break #de listas temporarias print('-='*15) print(f"{'No.':<5}{'NOME':<15}{'MEDIA':>10}\n{'-'*30}") for p in range(0,len(pauta)): media = (pauta[p][1] + pauta[p][2])/2 print(f"{p:<5}{pauta[p][0]:<15}{media:>10}") print('-'*30) while True: var = int(input("Digite o codigo do aluno para ver as notas (999 para sair): ")) if var == 999: break print(f"As notas do {pauta[var][0]} são: [{pauta[var][1]}, {pauta[var][2]}]\n") print(f"{'-='*3}{' FIM DO PROGRAMA '}{'=-'*3}")
import sys DIGIT_MAP = { 'zero': '0', 'um': '1', 'dois': '2', 'três': '3', 'quatro': '4', 'cinco': '5', 'seis': '6', 'sete': '7', 'oito': '8', 'nove': '9', } ''' primeira forma de tratar excepções def converter(s): try: number = '' for token in s: number += DIGIT_MAP[token] return int(number) except (KeyError, TypeError): pass #alternativamente return -1 ''' #segunda forma de tratar excepções def converter(s): try: number = '' for token in s: number += DIGIT_MAP[token] return int(number) except (KeyError, TypeError) as e: print(f "Conversion error: {e!r}", file=sys.stderr) return -1
lista = list() lista_par = list() lista_impar = list() while True: lista.append(int(input("Introduza um nr: "))) continuar = input("Deseja continuar? (S/N) _").strip().upper()[0] if continuar == "N": break for c in lista: if c % 2 == 0: lista_par.append(c) else: lista_impar.append(c) print(f"A lista completa é: {lista}") print(f"A lista de pares é: {lista_par}") print(f"A lista de ímpares é: {lista_impar}")
from time import sleep def contador(inicio, fim, intervalo): if intervalo < 0: intervalo *= -1 if intervalo == 0: intervalo = 1 print('-='*25) print(f'Contagem de {inicio} até {fim} de {intervalo} em {intervalo}') conta = inicio if inicio < fim: while conta <= fim: print(conta, end=' ', flush=True) conta += intervalo sleep(0.5) elif fim < inicio: while conta >= fim: print(conta, end=' ', flush=True) conta -= intervalo sleep(0.5) print('FIM!') sleep(1) print('-='*25) contador(1,10,1) contador(10,0,2) print('Agora é sua vez de personalizar a contagem!') comecar = int(input('Inicio: ')) terminar = int(input('Fim: ')) salto = int(input('Passo: ')) contador(comecar, terminar, salto)
lista = list() limite = int(input("Quantos nrs queres digitar? ")) for c in range(0,limite): x = int(input("Digite um nr: ")) if x not in lista: lista.append(x) else: print(f"O valor {x} já existe na lista") print(lista) print(sorted(lista))
casa = float(input('Qual o valor da sua casa? MZN_')) salario = float(input('Qual o seu salário mensal líquido? MZN_')) anos = int(input('Em quantos anos pretendes pagar o empréstimo? ')) valor_prestacao = casa/(anos*12) if valor_prestacao >= salario*0.3: print('Emprestimo negado') else: print(f'Emprestimo aceite, a sua prestacao sera de {valor_prestacao}')
l1 = float(input('Medida do 1º lado: ')) l2 = float(input('Medida do 2º lado: ')) l3 = float(input('Medida do 3º lado: ')) if l1 < l2 + l3 and l2 < l1 + l3 and l3 < l1 + l2: print('Os segmentos podem formar um triangulo', end=": ") if l1 == l2 == l3: print('Equilatero') elif l1 != l2 != l3: print('Escaleno') else: print('Isosceles') else: print('Nao podem formar um triangulo')
pauta = {} pauta['nome'] = input("Nome: ") pauta['media'] = float(input("Media: ")) print('-='*20) if pauta['media'] >= 14: pauta['situacao'] = 'Aprovado' elif pauta['media'] < 8: pauta['situacao'] = 'Reprovado' else: pauta['situacao'] = 'Recuperacao' for k,v in pauta.items(): print(f" - {k} é igual a {v}")
lista_par = list() lista_impar = list() lista = [lista_par,lista_impar] for c in range(0,7): x = int(input(f"Digite o {c+1}o numero: ")) if x % 2 == 0: lista_par.append(x) else: lista_impar.append(x) print(f"Os numeros pares digitados foram: {sorted(lista_par)}") print(f"Os numeros impares digitados foram: {sorted(lista_impar)}")
try: temp_C =float(input('Please enter temperature in Celsius:')) temp_F = temp_C*1.8+32 print('The temperature in', temp_C , 'Celsius is equal to', temp_F , 'in Fahrenheit') except: print('Please enter number only.')
import matplotlib count = 0 total = 0 while True: line = input('Enter a number:') if line == 'done': break try: itervar = float(line) total = total + itervar count = count + 1 except: print('Bad data') continue print('total=', total, 'count=', count, 'average=', total / count)
fname = input("Enter a file name:") fhand = open(fname) for line in fhand: if line.startswith('From'): words = line.split() print(words[1]) else: continue
from square import Square class Grid: def __init__(self): self.grid = [[]] * 9 self.build_grid() def build_grid(self): self.grid = [[Square(), Square(), Square(), Square(), Square(), Square(), Square(), Square(), Square() ] for spot in self.grid] def total_mines_calculator(self): return sum([sum([int(val.check_mine()) for val in row]) for row in self.grid]) def total_mines_revealed_calculator(self): return sum([sum([int(val.mine_revealed) for val in row]) for row in self.grid]) def value_generator(self, x, y): self.grid[x][y].set_value(self.adjacent_square_checker(x, y) + self.diagonal_square_checker(x, y)) if not self.grid[x][y].flagged() else 0 self.grid[x - 1][y].set_value(self.adjacent_square_checker(x - 1, y) + self.diagonal_square_checker(x - 1, y)) if x - 1 >= 0 and not self.grid[x - 1][y].flagged() else 0 self.grid[x + 1][y].set_value(self.adjacent_square_checker(x + 1, y) + self.diagonal_square_checker(x + 1, y)) if x + 1 < 9 and not self.grid[x + 1][y].flagged()else 0 self.grid[x][y - 1].set_value(self.adjacent_square_checker(x, y - 1) + self.diagonal_square_checker(x, y - 1)) if y - 1 >= 0 and not self.grid[x][y - 1].flagged()else 0 self.grid[x][y + 1].set_value(self.adjacent_square_checker(x, y + 1) + self.diagonal_square_checker(x, y + 1)) if y + 1 < 9 and not self.grid[x][y + 1].flagged()else 0 self.grid[x - 1][y - 1].set_value(self.adjacent_square_checker(x - 1, y - 1) + self.diagonal_square_checker(x - 1, y - 1)) if x - 1 >= 0 and y - 1 >= 0 and not self.grid[x - 1][y - 1].flagged() else 0 self.grid[x + 1][y - 1].set_value(self.adjacent_square_checker(x + 1, y - 1) + self.diagonal_square_checker(x + 1, y - 1)) if x + 1 < 9 and y - 1 >= 0 and not self.grid[x + 1][y - 1].flagged() else 0 self.grid[x - 1][y + 1].set_value(self.adjacent_square_checker(x - 1, y + 1) + self.diagonal_square_checker(x - 1, y + 1)) if x - 1 >= 0 and y + 1 < 9 and not self.grid[x - 1][y + 1].flagged() else 0 self.grid[x + 1][y + 1].set_value(self.adjacent_square_checker(x + 1, y + 1) + self.diagonal_square_checker(x + 1, y + 1)) if x + 1 < 9 and y + 1 < 9 and not self.grid[x + 1][y + 1].flagged() else 0 def adjacent_square_checker(self, x, y): total = 0 total += 1 if x - 1 >= 0 and self.grid[x - 1][y].check_mine() else 0 total += 1 if x + 1 < 9 and self.grid[x + 1][y].check_mine() else 0 total += 1 if y - 1 >= 0 and self.grid[x][y - 1].check_mine() else 0 total += 1 if y + 1 < 9 and self.grid[x][y + 1].check_mine() else 0 return total def diagonal_square_checker(self, x, y): total = 0 total += 1 if x - 1 >= 0 and y - 1 >= 0 and self.grid[x - 1][y - 1].check_mine() else 0 total += 1 if x + 1 < 9 and y - 1 >= 0 and self.grid[x + 1][y - 1].check_mine() else 0 total += 1 if x - 1 >= 0 and y + 1 < 9 and self.grid[x - 1][y + 1].check_mine() else 0 total += 1 if x + 1 < 9 and y + 1 < 9 and self.grid[x + 1][y + 1].check_mine() else 0 return total def flag_square(self, x, y): self.grid[x][y].set_value("F") def display_grid(self): [print([row[0].get_value(), row[1].get_value(), row[2].get_value(), row[3].get_value(), row[4].get_value(), row[5].get_value(), row[6].get_value(), row[7].get_value(), row[8].get_value() ]) for row in self.grid]
import sqlite3 mainpath = __file__[:-13] + "client_chat\\" path = mainpath print(path) def create_table(): conn = sqlite3.connect(path) c = conn.cursor() try: c.execute("""CREATE TABLE chat( username text, conversation text )""") except Exception as e: print("[EXCEPTION]", e) conn.commit() conn.close() def showall(): conn = sqlite3.connect(path) c = conn.cursor() c.execute("SELECT * FROM user") # c.execute("SELECT * FROM user WHERE username LIKE 'so%'") items = c.fetchall() for item in items: print(item) conn.close() def exist(name): conn = sqlite3.connect(path) c = conn.cursor() c.execute("SELECT * FROM chat WHERE EXISTS(SELECT 1 FROM chat WHERE username = (?))", (name, )) statement = True if c.fetchone() else False conn.close() return statement def update_chat(name, msg): conn = sqlite3.connect(path) c = conn.cursor() if not exist(name): c.execute("INSERT INTO chat VALUES (?, ?)", (name, "")) c.execute("SELECT * FROM chat WHERE username = (?)", (name, )) text = c.fetchone()[1] + msg c.execute("UPDATE chat SET conversation = (?) WHERE username = (?)", (text, name)) conn.commit() conn.close() def show(name): if not exist(name): print("Wrong name") return -1 conn = sqlite3.connect(path) c = conn.cursor() c.execute("SELECT * FROM chat WHERE username = (?)", (name, )) text = c.fetchone()[1] # print(text) conn.commit() conn.close() return text def clear(name): conn = sqlite3.connect(path) c = conn.cursor() c.execute("UPDATE chat SET conversation = (?) WHERE username = (?)", ("", name)) conn.commit() conn.close() # path = mainpath + "sora.db" # msg = show("bot") # print(msg) # print("\n\n\n") # path = mainpath + "bot.db" # show("sora")
# Define function to reverse string def reverse_string(str): return str[::-1] # Import regular expressions module import re # Input text text_input = input("Input some text: ") # Remove non-alphabetic characters from string, then make it lowercase text_input = re.sub(r'[^A-Za-z]', '', text_input) text_input = text_input.lower() # Reverse the string text_reverse = reverse_string(text_input) # Check to see if the text is a palindrome! if text_input == text_reverse: print("This is a palindrome!") else: print("This is not a palindrome.")
""" The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively. Example: Input: 4 Output: [ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."] ] Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above. """ # 2018-6-21 # N-Queens class Solution1: def solveNQueens(self, n): """ :type n: int :rtype: List[List[str]] """ self.res = [] self.dfs([-1] * n, 0) return self.res def dfs(self, nums, index): # print(nums,index) if index == len(nums): self.save_result(nums) return for i in range(len(nums)): nums[index] = i # print(nums) if self.is_valid(nums, index): self.dfs(nums, index+1) def is_valid(self, nums, n): for i in range(n): if nums[i] == nums[n] or abs(nums[i] - nums[n]) == n - i: return False return True def save_result(self, nums): print(nums) board, row, n = [], [], len(nums) for q_pos in nums: for i in range(n): if i != q_pos: row.append('.') else: row.append('Q') board.append(''.join(row)) row[:] = [] self.res.append(board[:]) # state 存放每行皇后所在列 class Solution2: def solveNQueens(self, n): """ :type n: int :rtype: List[List[str]] """ self.res = [] state = [-1]*n self.helper(state,0) # 从第一行开始 return self.res def helper(self,state,row): if row == len(state): self.save(state) for col in range(n): if self.isValid(state,row,col): state[row] = col self.helper(state,row+1) state[row] -= 1 def isValid(self,state,row,col): # print(row,col) for i in range(row): # 判断列不出现重复,对角线不出现重复 if state[i] == col or abs(row - i) == abs(col - state[i]): # 关键 return False return True def save(self,state): # print(state) board, row, n = [], [], len(state) for q_pos in state: for i in range(n): if i != q_pos: row.append('.') else: row.append('Q') board.append(''.join(row)) row[:] = [] self.res.append(board[:]) # test n = 4 test = Solution2() r = test.solveNQueens(n) print(r)
import sys def getox(num): """获得十六进制""" if num == 0: return [0] ret = [] while num: cur = num % 16 ret.append(cur) num = num // 16 return ret def isPanlindrome(nums): """验证是否为回文串""" if nums == nums[::-1]: return 1 return 0 def solver(num): """方法入口""" ox = getox(num) ret = isPanlindrome(ox) return ret def test(): num = 1 ret = solver(num) print(ret) if __name__ == '__main__': test()
# coding:utf-8 # 股票最大利润,只能买卖一次 def solver(nums): minNum = nums[0] maxProfit = 0 for n in nums: maxProfit = max(maxProfit, n - minNum) if n < minNum: minNum = n return maxProfit def test(): nums = [7,1,5,3,6,4] ret = solver(nums) print(ret) if __name__ == '__main__': test()
# 2018-8-7 # read data from file class ReadData(object): """ Usage: test = ReadData(filename) test.getKcol(2, force=True) to get K column data ingore string test.getKAvg(2, force=True) to get the average of k column data ingore string or other type """ def __init__(self, filename,): self.file = filename self.nums = [] self.col = 0 self.getCol() def getData(self): f = open(self.file,"r+") data = f.read(); tmp = [] res = [] for i in data: if i != ' ' and i != '\n' and i != '\r': tmp.append(i) else: res.append(tmp) tmp = [] self.nums = res def getCol(self): f = open(self.file,"r") data = f.read() col = 0 for i in data: if i == '\n' or i == '\r': col += 1 break elif i == ' ': col += 1 self.col = col return col def getKCol(self, Kcol, force = False): self.getData() res = self.handle(Kcol, force) if res: return res else: return False def handle(self, Kcol, isForce): if Kcol > self.col: print("Input must less than the total column of file. Please check!") return False lens = len(self.nums) res = [] i = 0 for c in self.nums: if (i % self.col) == (Kcol - 1): tmp = "".join(self.nums[i]) if isForce: try: res.append(int(tmp)) except: print("Skip : ", tmp) else: try: res.append(int(tmp)) except: print("Exists string or other type that can no trnsfer to Integer. Please use \"force=True\" inorder to get protype data.") return False i += 1 return res def getKAvg(self, Kcol, force = False): data = self.getKCol(Kcol, force) if data: lens = len(data) sums = sum(data) return float(sums / lens) else: print("Fail to get average.") return False if __name__ == "__main__": file = "read_test.txt" test = ReadData(file) res = test.getData() r1 = test.getKCol(3,True) avg = test.getKAvg(3) col = test.getCol() print(res,"----", col,"----", r1, "----", avg)
''' Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: I can be placed before V (5) and X (10) to make 4 and 9. X can be placed before L (50) and C (100) to make 40 and 90. C can be placed before D (500) and M (1000) to make 400 and 900. Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999. Example 1: Input: 3 Output: "III" Example 2: Input: 4 Output: "IV" Example 3: Input: 9 Output: "IX" Example 4: Input: 58 Output: "LVIII" Explanation: C = 100, L = 50, XXX = 30 and III = 3. Example 5: Input: 1994 Output: "MCMXCIV" Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. ''' # 2018-6-16 # Integer to Roman class Solution: def intToRoman(self, num): """ :type num: int :rtype: str """ r = [] res = '' x = 1 while num > 0: r.append((num % 10)*x) num = num // 10 x *= 10 lens = len(r)-1 for i in range(lens,-1,-1): if r[i]//1000 > 0: res += "M"*(r[i]//1000) if r[i]//100 > 0 and r[i]//100 < 10: j = r[i]//100 if j<4: res += "C"*(j) elif j == 4: res += "CD" elif j == 5: res += "D" elif j > 5 and j < 9: res += "D" + "C"*(j-5) else: res += "CM" if r[i]//10 > 0 and r[i]//10 < 10: t = r[i]//10 if t<4: res += "X"*(t) elif t == 4: res += "XL" elif t == 5: res += "L" elif t > 5 and t < 9: res += "L" +"X"*(t-5) else: res += "XC" if r[i]//1 > 0 and r[i]//1 < 10: n = r[i]//1 if n<4: res += "I"*(n) elif n == 4: res += "IV" elif n == 5: res += "V" elif n > 5 and n < 9: res += "V" +"I"*(n-5) else: res += "IX" return res # test num = 114 test = Solution() res = test.intToRoman(num) print(res) """ class Solution { public String intToRoman(int num) { int cur = 0; int carry = 1; // Deque<String> ret = new LinkedList<>(); String ret; while (num > 0) { cur = (num % 10) * carry; carry *= 10; num /= 10; if (cur >= 1000) { while (cur > 0) { ret = "M" + ret; cur -= 1000; } } else if (cur >= 500) { String tmp = "D"; cur -= 500; while (cur > 0) { tmp = tmp + "C"; } ret = tmp + ret; } else if (cur >= 100) { if (cur == 400) { ret = "CD" + ret; } else { while (cur > 0) { ret = "C" + ret; cur -= 100; } } } else if (cur >) } } } """
''' Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. Example: Input: [ 1->4->5, 1->3->4, 2->6 ] Output: 1->1->2->3->4->4->5->6 ''' # 2018-6-18 # Merge k Sorted Lists # 超出内存限制 # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ res = [] lens = len(lists) if lens == 0: return lists res = self.toLists(res,lists) res = sorted(res) dummy = l = ListNode(0) for i in res: cur = ListNode(i) l.next = cur l = cur return dummy.next def toLists(self,res,lists): if len(lists) == 0: return res head = lists[0] while head: res.append(head.val) head = head.next return self.toLists(res,lists[1:]) ####################################################################### from queue import PriorityQueue # class Comp: # 可比较对象,放入优先队列中 # def __init__(self, priority, description): # self.priority = priority # self.description = description # return # def __cmp__(self, other): # 比较规则的指定,谁做根(大顶堆,小顶堆) # # 返回的是布尔类型 # if self.priority >= other.priority: # return True # else: # return False class Solution2(object): def mergeKLists(self, lists): dummy = ListNode(None) curr = dummy q = PriorityQueue() for index, node in enumerate(lists): if node: # print(node.val) # 有问题 unorderable types: ListNode() < ListNode() # q.put((node.val, node)) q.put((node.val, index, node)) while q.qsize() > 0: cur = q.get() curr.next, index = cur[2], cur[1] curr = curr.next if curr.next: q.put((curr.next.val, index, curr.next)) return dummy.next lis = [[1,2,4],[1,3,4],[7],[49],[73],[58],[30],[72],[44],[78],[23],[9],[40],[65],[92],[42],[87],[3],[27],[29],[40],[12],[3],[69],[9]] l = [] for j in lis: head = lists = ListNode(0) for i in j: cur = ListNode(i) lists.next = cur lists = cur l.append(head.next) test = Solution2() res = test.mergeKLists(l) # show lists while res: print(res.val) res = res.next
""" Given two binary trees, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical and the nodes have the same value. Example 1: Input: 1 1 / \ / \ 2 3 2 3 [1,2,3], [1,2,3] Output: true Example 2: Input: 1 1 / \ 2 2 [1,2], [1,null,2] Output: false Example 3: Input: 1 1 / \ / \ 2 1 1 2 [1,2,1], [1,1,2] Output: false Example 4: Input:[1,1],[1,null,1] Output: false """ # 2018-6-30 # Same Tree # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None # error for example 4 class Solution1: def isSameTree(self, p, q): """ :type p: TreeNode :type q: TreeNode :rtype: bool """ l1 = self.recursive(p,[]) l2 = self.recursive(q,[]) return l1 == l2 def recursive(self,root,lists): if root == None: lists.append("nul") return self.recursive(root.left,lists) lists.append(root.val) self.recursive(root.right,lists) return lists # https://leetcode.com/problems/same-tree/discuss/32687/Five-line-Java-solution-with-recursion class Solution2: def isSameTree(self, p, q): """ :type p: TreeNode :type q: TreeNode :rtype: bool """ if p == None and q == None: return True if p == None or q == None: return False if p.val == q.val: return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) return False """ # java public boolean isSameTree(TreeNode p, TreeNode q) { if(p == null && q == null) return true; if(p == null || q == null) return false; if(p.val == q.val) return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); return false; } """
""" Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last index. Example 1: Input: [2,3,1,1,4] Output: true Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. Example 2: Input: [3,2,1,0,4] Output: false Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. """ # 2018-6-21 # 55.Jump game(medium) class Solution: def canJump(self, nums): """ :type nums: List[int] :rtype: bool """ counter = 1 for i in range(len(nums)): if counter < 1: # can't reach the next position return False counter = max(counter-1,nums[i]) return True # test nums = [[2,3,1,1,4,2],[3,2,1,0,4]] test = Solution() for nums in nums: res = test.canJump(nums) print(nums,"--is",res)
# 2018-8-21 # 单源最短路径 # Dijkstra算法 # 算法导论 P383 # 数据结构与算法分析 P224 class graphNode(object): def __init__(self): self.known = False self.dist = INF self.p = None self.adj = [] def dijkstra(G): """ 每次取出最小dist并且属性known为False的节点v,对v的邻节点进行松弛操作, 直到G中的known属性为False的节点为0。 """ while len(G) != 0: v = smallestUnknownDist(G) v.known = True for w in v.adj: if w.known == False: relax(w, v) def relax(w, v): """ 松弛操作 """ if v.dist + dist(w, v) < w.dist: w.dist = v.dist + dist(w, v) w.p = v def dist(w, v): """ 返回 w 到 v 之间的距离 """ pass def smallestUnknownDist(G): """ 返回图G中unknown且dist最小的节点 """ pass
# 2018-8-16 # greedy algorithm # example def change(money, values, count): lens = len(values) res = [0] * lens c = 0 for i in range(lens): if money <= 0: break c = min(money // values[i], count[i]) res[i] = c money -= c * values[i] return res count = [ 3, 1, 2, 1, 1, 3, 5 ] values = [1,2,5,10,20,50,100] values = values[::-1] count = count[::-1] money = 442 r = change(money, values, count) c = 0 for i in r: if i != 0: print("需要",i, "张",values[c],"块") c += 1
# coding:utf-8 # 数组循环右移 将一个长度为n的数组A的元素循环右移k位, # 比如 数组 1, 2, 3, 4, 5 循环右移3位之后变成 3, 4, 5, 1, 2 def solver(nums, k): lenNums = len(nums) if k > lenNums: k = k % lenNums left = lenNums - k numsL = nums[:left][::-1] # print(numsL) numsR = nums[left:][::-1] numsL.extend(numsR) return numsL[::-1] def test(): nums = [1,2,3,4,5] for k in range(1, 10): ret = solver(nums, k) print("k:{}, ret:{}".format(k, ret)) if __name__ == '__main__': test() # k:1, ret:[5, 1, 2, 3, 4] # k:2, ret:[4, 5, 1, 2, 3] # k:3, ret:[3, 4, 5, 1, 2] # k:4, ret:[2, 3, 4, 5, 1] # k:5, ret:[1, 2, 3, 4, 5] # k:6, ret:[5, 1, 2, 3, 4] # k:7, ret:[4, 5, 1, 2, 3] # k:8, ret:[3, 4, 5, 1, 2] # k:9, ret:[2, 3, 4, 5, 1]
#!/usr/bin/python # -*- coding: utf-8 -*- ''' Welcome to vivo ! ''' def solution(total_disk,total_memory,app_list): # TODO Write your code here ret = 0 que = [[total_disk, total_memory, 0]] # 初始15磁盘, 10内存,0个用户 while len(que) != 0: curSize = len(que) tmp = [] for i in range(curSize): cur = que.pop() for app in app_list: disk, memory, curUser = cur if disk < app[0] or memory < app[1]: if ret < curUser: ret = curUser else: tmp.append([disk-app[0], memory-app[1], curUser + app[2]]) que = tmp return ret def inputs(): input1 = input() disk = int(input1.split()[0]) memory = int(input1.split()[1]) input2 = input1.split()[2] app_list = [[int(j) for j in i.split(',')] for i in input2.split('#')] print(solution(disk,memory,app_list)) def test(): disk = 15 memory = 10 s = "5,1,1000#2,3,3000#5,2,15000#10,4,16000" app_list = [list(map(int, x.split(","))) for x in s.split("#")] print(solution(disk,memory,app_list)) if __name__ == "__main__": test()
# Definition for singly-linked list. class ListNode(object): def __init__(self): self.val = None self.next = None class ListNode_handle: def __init__(self): self.cur_node = None def add(self, data): # add a new node pointed to previous node node = ListNode() node.val = data node.next = self.cur_node self.cur_node = node return node def print_ListNode(self, node): while node: print ('\nnode: ', node, ' value: ', node.val, ' next: ', node.next ) node = node.next def _reverse(self, nodelist): list = [] while nodelist: list.append(nodelist.val) nodelist = nodelist.next result = ListNode() result_handle = ListNode_handle() for i in list: result = result_handle.add(i) return result ListNode_1 = ListNode_handle() # l1 = ListNode() l1_list = [1,8,3] for i in l1_list: l1 = ListNode_1.add(i) # l1 = ListNode_1._reverse(l1) ListNode_1.print_ListNode(l1)
#OS模块遍历文件 #date(2018-4-15) import os dirpath = input("请输入要遍历的文件夹:") def getdir(dirpath,level=0): level += 2 if not dirpath: dirpath = os.getcwd() mylist = os.listdir(dirpath) #写到if条件外面 for name in mylist: print('-'*level+'|'+name) name = os.path.join(dirpath,name) if os.path.isdir(name): getdir(name,level) getdir(dirpath) #捕获异常 def func(var, index): return var[index] mylist = input('请输入你要访问的列表:') index = input('请输入你要访问的位置:') try: #input获得的是字符串,需要转为列表 mylist = eval(mylist) index = int(index) num = func(mylist, index) except TypeError: print('你的传递顺序颠倒了') except IndexError: print('你的索引超出了列表上限') except ValueError: print('值出现错误') else: print(num) finally: print('使用完毕')
# 2018-8-21 # 拓扑排序 # 算法导论 P335 # 数据结构与算法分析 P219 class Vertex(object): def __init__(self, name=None, degree=None, p=[], c=[]): self.name = name self.degree = degree # 入度 self.p = None # 前驱 self.c = None self.sortNum = None def topSort(G): """ 使用BFS实现拓扑排序。 每次找到入度为0的节点放入列队,遍历与入度为0的点相邻的节点,并将度数减少1,如果度数变为0则放入列队。直到列队为空。 """ Q = [] # 列队存储每个节点 counter = 0 sort = {} for i in G: if i.degree == 0: Q.append(i) while len(Q) != 0: vertex = Q.pop() sort[vertex] = counter counter += 1 if vertex.c == None: continue for j in vertex.c : j.degree -= 1 if j.degree == 0: Q.append(j) if len(sort) != len(G): print("Graph has a cycle!") return None return sort def test(): # 数据结构与算法分析 P218 图9-4 # 实例图 v1 = Vertex(name="v1",degree=0) v2 = Vertex(name="v2",degree=1) v3 = Vertex(name="v3",degree=2) v4 = Vertex(name="v4",degree=3) v5 = Vertex(name="v5",degree=1) v6 = Vertex(name="v6",degree=3) v7 = Vertex(name="v7",degree=2) v1.c = [v2,v3,v4] v2.p = [v1] v2.c = [v4,v5] v3.p = [v1,v4] v3.c = [v6] v4.p = [v1,v2,v5] v4.c = [v3,v6,v7] v5.p = [v2] v5.c = [v4,v7] v6.p = [v3,v4,v7] v7.p = [v4,v5] v7.c = [v6] G = [v1,v2,v3,v4,v5,v6,v7] test = topSort(G) for i in test: print(i.name) if __name__ == "__main__": test() """ v1 v2 v5 v4 v7 v3 v6 符合 数据结构与算法分析 P219 图9-6 结果 """