text
stringlengths 37
1.41M
|
---|
'''module to add brick on board'''
from make_brick import MakeBrick
def brick(bricks):
'''make all bricks'''
brk = MakeBrick(30, 23, 1)
bricks.append(brk)
brk = MakeBrick(35, 23, -2)
bricks.append(brk)
brk = MakeBrick(40, 23, -2)
bricks.append(brk)
brk = MakeBrick(45, 23, -2)
bricks.append(brk)
brk = MakeBrick(50, 23, 5)
bricks.append(brk)
brk = MakeBrick(55, 23, 1)
bricks.append(brk)
brk = MakeBrick(40, 13, -2)
bricks.append(brk)
brk = MakeBrick(45, 13, 1)
bricks.append(brk)
brk = MakeBrick(145, 20, 1)
bricks.append(brk)
brk = MakeBrick(150, 20, -2)
bricks.append(brk)
brk = MakeBrick(155, 20, -2)
bricks.append(brk)
brk = MakeBrick(160, 20, 5)
bricks.append(brk)
brk = MakeBrick(165, 20, -2)
bricks.append(brk)
brk = MakeBrick(195, 20, 5)
bricks.append(brk)
brk = MakeBrick(230, 20, -2)
bricks.append(brk)
brk = MakeBrick(320, 20, 1)
bricks.append(brk)
brk = MakeBrick(330, 20, -2)
bricks.append(brk)
brk = MakeBrick(360, 20, -2)
bricks.append(brk)
brk = MakeBrick(365, 20, 1)
bricks.append(brk)
brk = MakeBrick(370, 20, -2)
bricks.append(brk)
brk = MakeBrick(375, 20, 1)
bricks.append(brk)
brk = MakeBrick(365, 9, 5)
bricks.append(brk)
brk = MakeBrick(370, 9, -2)
bricks.append(brk)
brk = MakeBrick(415, 24, -2)
bricks.append(brk)
brk = MakeBrick(420, 20, 1)
bricks.append(brk)
brk = MakeBrick(425, 16, 1)
bricks.append(brk)
brk = MakeBrick(430, 12, -2)
bricks.append(brk)
brk = MakeBrick(550, 23, 1)
bricks.append(brk)
brk = MakeBrick(555, 23, -2)
bricks.append(brk)
brk = MakeBrick(560, 23, 5)
bricks.append(brk)
brk = MakeBrick(570, 23, -2)
bricks.append(brk)
brk = MakeBrick(575, 23, 1)
bricks.append(brk)
|
'''class to make bricks'''
class MakeBrick:
'''class to make bricks'''
def __init__(self, x, y, t):
self.posx = x
self.posy = y
self.type = t
def get_x(self):
'''getter for x'''
return self.posx
def get_y(self):
'''getter for y'''
return self.posy
|
def print_sum(student_marks,query_name):
total = 0
for key,value in student_marks.items():
if key == query_name:
total = sum(value)/len(value)
print(total)
if __name__ == '__main__':
#read number of students, followed by each student name along with their marks
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()
#print given student average marks
print_sum(student_marks,query_name)
|
from random import shuffle
def player_guess():
guess = ''
while guess not in ['0','1','2']:
guess = input('Please enter the guess 0,1 or 2: ')
return int(guess)
def shuffle_list(mylist):
shuffle(mylist)
return mylist
def check_guess(mylist,guess):
if mylist[guess] == 'O':
print('Congratulations! Your guess is correct:')
print(mylist)
else:
print('Sorry, Wrong guess. Try again to test your luck!')
print(mylist)
if __name__ == '__main__':
# read input guess from customer
mylist = [' ', 'O', ' ']
guess = player_guess()
#print(guess)
mixed_list = shuffle_list(mylist)
#print(mixed_list)
check_guess(mixed_list, guess)
|
new_list = []
if __name__ == '__main__':
N = int(input())
operations = {}
for _ in range(N):
op,*line = input.split()
item = list(map(int,line))
operations[op] = item
for item in N:
operation = input()
if operation == 'print':
funPrint()
elif operation == 'insert':
funInsert()
elif operation == 'append':
funAppend()
elif operation == 'pop':
funPop()
elif operation == 'reverse':
funReverse()
else operation == 'sort':
funSort()
|
# The rand7() API is already defined for you.
from random import randint
def rand7():
return randint(1, 7)
class Solution:
def rand10(self):
"""
:rtype: int
"""
r7_1 = rand7()
r7_2 = rand7()
idx = (r7_2-1) * 7 + r7_1
if idx > 40:
return self.rand10()
else:
return idx % 10 + 1
so = Solution()
for i in range(10):
print(so.rand10()) |
# coding: utf-8
# Bubble Sort, Reverse = True則大至小(預設值);反之小至大
def bubble_sort_fun(x, reverse = 1):
for i in range(0, len(x) - 1):
for j in range(i + 1, len(x)):
if reverse == 0:
if x[i] > x[j]:
x[i], x[j] = x[j], x[i]
elif reverse == 1:
if x[i] < x[j]:
x[i], x[j] = x[j], x[i]
return x
import random
lst = random.sample(range(0, 100), 20)
print('亂數數列:', lst, sep = '\n')
print('排序數列(大至小):', exchange_sort(lst, reverse = 1), sep = '\n')
print('排序數列(小至大):', exchange_sort(lst, reverse = 0), sep = '\n')
|
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 04 03:02:59 2018
@author: pushkar
"""
import pygame
import math
import time
from copy import deepcopy
class BoxesGame():
def __init__(self):
#initialize variables for the current state
self.hColor=[[0 for x in range(6)] for y in range(7)]
self.vColor=[[0 for x in range(7)] for y in range(6)]
self.boardh = [[False for x in range(6)] for y in range(7)]
self.boardv = [[False for x in range(7)] for y in range(6)]
#initialize variables for tracking the score
self.score_player1=0;
self.score_player2=0;
def update(self):
print 'Player 2'
self.player2();
print 'Player1'
self.player1();
# A function to lost all the possible moves
def list_possible_moves(self,state_h,state_v):
#make the move true if the last move is not true to be true in the psuedo list
next_moves=[];
for x in range (7):
for y in range(6):
if(state_h[x][y]==False):
next_moves.append([x,y,1]); # append all horizontal moves
for x in range (6):
for y in range(7):
if(state_v[x][y]==False):
next_moves.append([x,y,0]); # append all horizontal moves
return next_moves
# gives the current state of the system
def current_state(self):
'''
h_matrix =[[False for x in range(6)] for y in range(7)];
v_matrix=[[False for x in range(7)] for y in range(6)];
for x in range (7):
for y in range(6):
h_matrix[x][y]=self.boardh[x][y]
for x in range (6):
for y in range(7):
v_matrix[x][y]=self.boardv[x][y]
'''
h2=deepcopy(list(self.boardh))
v2=deepcopy(list(self.boardv))
return h2,v2
#checks if the score has been updated by a given move or not
def increment_score(self,move,h_matrix,v_matrix):
temp_score=0;
xpos=move[0];
ypos=move[1];
if(move[2]==0): # vertical matrices
if(ypos==0):# left most edge
if(h_matrix[xpos][ypos]==True and h_matrix[xpos+1][ypos]==True and v_matrix[xpos][ypos+1]==True):
temp_score=1;
elif(ypos==6):# left most edge
if(h_matrix[xpos][ypos-1]==True and h_matrix[xpos+1][ypos-1]==True and v_matrix[xpos][ypos-1]==True):
temp_score=1;
else:
if(h_matrix[xpos][ypos]==True and h_matrix[xpos+1][ypos]==True and v_matrix[xpos][ypos+1]==True):
temp_score=temp_score+1;
if(h_matrix[xpos][ypos-1]==True and h_matrix[xpos+1][ypos-1]==True and v_matrix[xpos][ypos-1]==True):
temp_score=temp_score+1;
if(move[2]==1): # horizontal matrices
if(xpos==0):
if(v_matrix[xpos][ypos]==True and v_matrix[xpos][ypos+1]==True and h_matrix[xpos+1][ypos]==True):
temp_score=1;
elif(xpos==6):
if(v_matrix[xpos-1][ypos]==True and v_matrix[xpos-1][ypos+1]==True and h_matrix[xpos-1][ypos]==True):
temp_score=1;
else:
if(v_matrix[xpos][ypos]==True and v_matrix[xpos][ypos+1]==True and h_matrix[xpos+1][ypos]==True):
temp_score=temp_score+1;
if(v_matrix[xpos-1][ypos]==True and v_matrix[xpos-1][ypos+1]==True and h_matrix[xpos-1][ypos]==True):
temp_score=temp_score+1;
return temp_score;
# function to actulally make a move
def make_move(self,move,player_id):
#print 'value before coming',self.boardh
xpos=move[0];
ypos=move[1];
print xpos,ypos
if(move[2]==1):# Vertical Matrices
self.boardh[xpos][ypos]=True;
if(move[2]==0):
self.boardv[xpos][ypos]=True;
#self.boardh_temp = self.boardh
#self.boardv_temp = self.boardv
score=self.increment_score(move,self.boardh,self.boardv);
if(player_id==0):
self.score_player1=self.score_player1+self.increment_score(move,self.boardh,self.boardv);
if(player_id==1):
self.score_player2=self.score_player2+self.increment_score(move,self.boardh,self.boardv);
#ikimasu / delete later
#print self.current_state()
# function for printing the next state of the system
def next_state(self,move,h1,v1):
xpos=move[0];
ypos=move[1];
h_matrix1=deepcopy(list(h1))
v_matrix1=deepcopy(list(v1))
score=self.increment_score(move,h_matrix1,v_matrix1);
#ikimasu / delete later
#print score;
#print move[2];
if(move[2]==0):#vetical matrices
v_matrix1[xpos][ypos]=True;
#self.boardv[xpos][ypos]=False
if(move[2]==1):#horizontal matrices
h_matrix1[xpos][ypos]=True;
#self.boardh[xpos][ypos]=False
#print move ,h_matrix,v_matrix
return h_matrix1,v_matrix1,score;
# function for
def game_ends(self,temp_h,temp_v):
count=True;
for x in range(6):
for y in range(7):
if not temp_h[y][x]:
count=False;
for x in range(7):
for y in range(6):
if not temp_v[y][x]:
count=False;
return count;
def player1(self):
temp_h=self.boardh
temp_v=self.boardv
next_move=self.list_possible_moves(temp_h,temp_v);
#print self.boardh_temp,self.boardv_temp
#print next_move
#best_move=next_move[random.randint(0, len(next_move))-1]; #random movement
#print 'before loop'
best_move=next_move[0];
best_score=0;
for move in next_move:
temp_h,temp_v,score=self.next_state(move,temp_h,temp_v);
#print score
if(score>best_score):
best_score=score;
best_move=move;
#print 'Player 1 next moves', next_move_list
#print 'Player 1 move made', next_move_list[0];
self.make_move(best_move,0);
print 'move made by player 1', best_move
#if(make_move(next))
def player2(self):
'''
Call the minimax/alpha-beta pruning function to return the optimal move
'''
## change the next line of minimax/ aplpha-beta pruning according to your input and output requirments
temp_h=self.boardh
temp_v=self.boardv
moves = self.list_possible_moves(temp_h,temp_v)
#next_move=self.minimax(self.current_state(), 0); #minimax search
next_move=self.alphabetapruning(self.current_state(), 1); #alpha-beta pruning version
self.make_move(next_move,1)
print 'move_made by player 2',next_move
'''
Write down the code for minimax to a certain depth do no implement minimax all the way to the final state.
'''
def minimax(self, state, input_depth):
# cutoff depth
d = input_depth
# unpacks h and v from input state
cur_h,cur_v = state
# setting up argmax
def argmin(seq, fn):
best = seq[0]; best_score = fn(best)
for x in seq:
x_score = fn(x)
if x_score < best_score:
best, best_score = x, x_score
return best
def argmax(seq, fn):
return argmin(seq, lambda x: -fn(x))
# max value for player 2; s1 & s2 = player1 & player2 score deltas
def max_value(h,v,depth,s1,s2):
if depth > d or self.game_ends(h,v):
return self.evaluate(h,v,s1,s2)
next_moves = self.list_possible_moves(h,v)
temp_value = float("-inf")
for m in next_moves:
next_h, next_v, next_score = self.next_state(m,h,v)
temp_value = max(temp_value, min_value(next_h, next_v, depth+1, s1, s2-next_score))
return temp_value
# min value for player 1; s1 & s2 = player1 & player2 score deltas
def min_value(h,v,depth,s1,s2):
if depth > d or self.game_ends(h,v):
return self.evaluate(h,v,s1,s2)
next_moves = self.list_possible_moves(h,v)
temp_value = float("inf")
for m in next_moves:
next_h, next_v, next_score = self.next_state(m,h,v)
temp_value = min(temp_value, max_value(next_h, next_v, depth+1, s1+next_score, s2))
return temp_value
# unzips move to use min_value
def get_min(m):
next_h, next_v, score = self.next_state(m,cur_h,cur_v)
return min_value(next_h, next_v, 0, 0, 0)
# find best move
best_move = argmax(self.list_possible_moves(cur_h,cur_v), lambda m: get_min(m))
return best_move;
'''
Change the alpha beta pruning function to return the optimal move .
'''
def alphabetapruning(self, state, input_depth):
# cutoff depth
d = input_depth
# unpacks h and v from input state
cur_h,cur_v = state
# setting up argmax
def argmin(seq, fn):
best = seq[0]; best_score = fn(best)
for x in seq:
x_score = fn(x)
if x_score < best_score:
best, best_score = x, x_score
return best
def argmax(seq, fn):
return argmin(seq, lambda x: -fn(x))
# max value for player2; s1 & s2 = player1 & player2 score deltas
def max_value(state, alpha, beta, depth, s1, s2, print_values=False):
h,v = state
# don't print alpha and beta values by default
if print_values is False:
if depth > d or self.game_ends(h,v):
return self.evaluate(h,v,s1,s2)
next_moves = self.list_possible_moves(h,v)
temp_value = float("-inf")
for m in next_moves:
next_h, next_v, next_score = self.next_state(m,h,v)
temp_value = max(temp_value, min_value((next_h,next_v), alpha, beta, depth+1, s1, s2-next_score))
if temp_value >= beta:
return temp_value
alpha = max(alpha, temp_value)
return temp_value
# print alpha and beta values
else:
if depth > d or self.game_ends(h,v):
return self.evaluate(h,v,s1,s2)
next_moves = self.list_possible_moves(h,v)
temp_value = float("-inf")
for m in next_moves:
next_h, next_v, next_score = self.next_state(m,h,v)
temp_value = max(temp_value, min_value((next_h,next_v), alpha, beta, depth+1, s1, s2-next_score, True))
if temp_value >= beta:
return temp_value
alpha = max(alpha, temp_value)
# print final alpha and beta values
print "Alpha: ",alpha," Beta: ",beta
return temp_value
# min value for player1; s1 & s2 = player1 & player2 score deltas
def min_value(state, alpha, beta, depth, s1, s2, print_values=False):
h,v = state
# don't print by default
if print_values is False:
if depth > d or self.game_ends(h,v):
return self.evaluate(h,v,s1,s2)
next_moves = self.list_possible_moves(h,v)
temp_value = float("inf")
for m in next_moves:
next_h, next_v, next_score = self.next_state(m,h,v)
temp_value = min(temp_value, max_value((next_h,next_v), alpha, beta, depth+1, s1+next_score, s2))
if temp_value <= alpha:
return temp_value
beta = min(beta, temp_value)
return temp_value
# otherwise request to print alpha and beta values
else:
if depth > d or self.game_ends(h,v):
return self.evaluate(h,v,s1,s2)
next_moves = self.list_possible_moves(h,v)
temp_value = float("inf")
for m in next_moves:
next_h, next_v, next_score = self.next_state(m,h,v)
temp_value = min(temp_value, max_value((next_h,next_v), alpha, beta, depth+1, s1+next_score, s2, True))
if temp_value <= alpha:
return temp_value
beta = min(beta, temp_value)
return temp_value
# unzips move to use min_value
def get_min(m):
next_h, next_v, next_score = self.next_state(m,cur_h,cur_v)
return min_value((next_h,next_v), float("-inf"), float("inf"), 0, 0, 0)
# prints final alpha and beta values after finding the best move
def print_final_values(m):
next_h, next_v, next_score = self.next_state(m,cur_h,cur_v)
return min_value((next_h,next_v), float("-inf"), float("inf"), 0, 0, 0, True)
# find best move
best_move = argmax(self.list_possible_moves(cur_h,cur_v), lambda m: get_min(m))
# print final alpha and beta values
print_final_values(best_move)
return best_move
'''
Write down you own evaluation strategy in the evaluation function
'''
# assumes player is player2
# calculates the optimal score delta difference and picks move based on that
# s1 = player1 score delta, s2 = player2 score delta
def evaluate(self, h, v, s1, s2):
score = s2 - s1
#print "Score delta: ",score
return score
bg=BoxesGame();
while (bg.game_ends(bg.boardh,bg.boardv)==False):
bg.update();
print 'Player1 : score',bg.score_player1;
print 'Player2 : score',bg.score_player2;
#time.sleep(2)
print 'Player 2 wins' if bg.score_player2 >= bg.score_player1 else 'Player 1 wins'
#time.sleep(10)
pygame.quit()
|
'''
Analisis pseint
Entradas: Nombre1, Nombre2
Salidas: ultima1,ultima2,primera1,primera2
si primera1 es igual a primera 2, escribir quer hay coincidencia, si ultima 1 es igual a ultima 2, hay coincidencia, sino escribir que no hay .
pseudocodigo:
Algoritmo p1
Escribir 'Ingresar primer nombre'
leer n1
Escribir 'Ingresar segundo nombre'
leer n2
primera1 <- Minusculas(Subcadena(n1,1,1))
ultima1 <- Minusculas(Subcadena(n1,Longitud(n1)-0,Longitud(n1)-0))
primera2 <- Minusculas(Subcadena(n2,1,1))
ultima2 <- Minusculas(Subcadena(n2,Longitud(n2)-0,Longitud(n2)-0))
si primera1==primera2
Imprimir 'Si hay coincidencia'
SiNo
si ultima1==ultima2
Imprimir 'Si hay coincidencia'
SiNo
Imprimir 'No hay coincidencia'
FinSi
FinSi
FinAlgoritmo
'''
#tienes dos nombres,
nombre1 = input("Ingresa un nombre: ")
nombre2 = input("Ingresa un nombre: ")
primera_letra1 = nombre1[0].lower()
ultima_letra1 = nombre1[-1].lower()
primera_letra2 = nombre2[0].lower()
ultima_letra2 = nombre2[-1].lower()
if primera_letra1 == primera_letra2:
print("Hay coincidencia")
elif ultima_letra1 == ultima_letra2:
print("Hay coincidencia")
else:
print("No hay coincidencia")
input('Enter para salir') |
def suma(a,b):
total=a+b
return total
a=int(input("ingrese un numero: "))
b=int(input("ingrese otro numero: "))
resultado=suma(a,b)
print("el resultado la suma de los numeros es:",resultado)
input('Apretar enter para terminar') |
#Descripcion: Eliminar todos los 0 de una lista definida
#Entrada: No posee parametros de entrada
#Salida: Lista sin cero
lista = [0,5,1,0,3,5,4,8,9,0,2,1,0,6,0,0,1,6,8]
while 0 in lista: lista.remove(0)
print("La lista sin el numero cero es la siguiente:",lista) #[5, 1, 3, 5, 4, 8, 9, 2, 1, 6, 1, 6, 8] |
'''
Analisis
Entrada: aleat, aleat2, aleat3
Salida: (aleat+aleat2+aleat3)/3
Proceso: def alear, aleat2, aleat3 <-(azar(7)), resultado<- (aleat+aleat2+aleat3)/3
Pseudocodigo:
Algoritmo lab36
definir aleat,aleat2,aleat3 como real
aleat <- (azar(7))
aleat2 <- (azar(7))
aleat3<- (azar(7))
Escribir aleat
Escribir aleat2
Escribir aleat3
resultado<- (aleat+aleat2+aleat3)/3
Escribir "El promedio entre estos numeros es:" ,resultado
FinAlgoritmo
'''
#Algoritmo para calcular el promedio entre 3 valores
import random #Importar random
num1 = (random.uniform(0,7))
num2 = (random.uniform(0,7))
num3 = (random.uniform(0,7))
result = (num1+num2+num3)/3 #resultado de la suma de 3 numeros y dividido en 3
print("",num1)
print("",num2)
print("",num3)
print("==========")
print("El promedio entre estos numeros es: ", result) #Mostrar resultado
print("==========")
input("Presiona ENTER para salir.") |
## Descripcion: Une los dominios y los nombres en orden aleatorio
## Entradas: nombre, dominio
## Salidas: juntar(nombre,dominio)
from random import randint
nombre=["Nicolas","Andres","Ricardo","Exequiel","Catalina"]
dominio=["@goqoez.com","@gmail.com","@outlook.cl","@educa.uct","@adretail.cl","@grange.cl","@outlook.com","@hotmail.cl","@yopmail.cr","@alu.uct.cl"]
def juntar(nombre,dominio):
a=nombre[(randint(0,4))]
b=dominio[randint(0,9)]
correo=a+b
texto="".join(correo)
return texto
a=juntar(nombre,dominio)
b=juntar(nombre,dominio)
c=juntar(nombre,dominio)
d=juntar(nombre,dominio)
e=juntar(nombre,dominio)
lista=[a,b,c,d,e]
print(lista)
|
'''
Analisis
Entradas: ncandidato
salidas: candidato_voto
Pseudocodigo:
Algoritmo votos
Imprimir 'Los candidatos a las votaciones son: '
Imprimir '1.Emilia Hajimeru'
Imprimir '2.Martin Completos'
Imprimir '3.Armando Casas'
Imprimir '4.Ignacio Montero'
Imprimir '5.Ricardo Milos'
Escribir 'Ingresar numero de candidato a votar: '
leer ncandidato
si ncandidato="1"
Escribir 'Usted votara por Emilia Hajimeru, del color gris'
SiNo
si ncandidato="2"
Escribir 'Usted votara por Martin Completos, del color verde'
SiNo
si ncandidato="3"
Escribir 'Usted votara por Armando Casas, del color azul'
SiNo
si ncandidato="4"
Escribir 'Usted votara por Ignacio Montero, del color rojo'
SiNo
Si ncandidato="5"
Escribir 'Usted votara por Ricardo Milos, del color amarillo'
FinSi
FinSi
FinSi
FinSi
FinSi
FinAlgoritmo
'''
print('La lista de candidatos es: \n1)Emilia Hajimeru\n2)Martin Completos\n3)Armando Casas\n4)Ignacio Montero\n5)Ricardo Milos')
numeroc=input("Ingresar el numero de candidato elegido: ")
c1="El numero elegido corresponde al candidato \"Emilia Hajimeru\" de color gris"
c2="El numero elegido corresponde al candidato \"Martin Completos\" de color verde"
c3="El numero elegido corresponde al candidato \"Armando Casas\" de color azul"
c4="El numero elegido corresponde al candidato \"Ignacio Montero\" de color rojo"
c5="El numero elegido corresponde al candidato \"Ricardo Milos\" de color amarillo"
####
if numeroc=="1":
print(c1)
elif numeroc=="2":
print(c2)
elif numeroc=="3":
print(c3)
elif numeroc=="4":
print(c4)
elif numeroc=="5":
print(c5)
else:
print('No se ha ingresado ningun numero o el numero ingresada es incorrecto')
input('Presionar enter para terminar') |
##descripion: mostrar por pantalla los primeros 15 numeros de la sucesion de fibonacci
##entrada: no posee parametro de entrada
##salida: muestra por pantalla la secuencia de fibonacci (primeros 15 numeros)
def fibonacci(n):
a=0
b=1
for i in range(n):
c=a+b
a=b
b=c
return b
for numero in range(15):
print(fibonacci(numero))
|
## Descripcion: Juntar dos cadenas de caracteres e imprimir
## Entradas: A,B
## Salidas: joint(A,B)
a = ["Usted tiene 20 horas para vivir"," deme todos sus mangas"]
b = [","]
def joint(a,b):
caracteres = a[0]+b[0]+a[1]
return caracteres
frase = joint(a,b)
print(frase)
|
#importar libreria para graficos de visualizacion
import matplotlib.pyplot as plt
import numpy as np
f, ax = plt.subplots()
x = np.linspace(0, 2*np.pi)
y = np.sin(x)
ax.plot(x, np.sin(x), 'r', label='sin ruido')
# añadimos algo de ruido
xr = x + np.random.normal(scale=0.1, size=x.shape)
yr = y + np.random.normal(scale=0.2, size=y.shape)
ax.scatter(xr, yr, label='con ruido')
ax.legend()
plt.show() |
from Tkinter import *
root = Tk()
#grid configures the widget in a tabular format
label = Label(root,text="Name")
label2 = Label(root,text="Password")
entry_1 =Entry(root) #textbox
entry_2 = Entry(root)
label.grid(row=0,sticky=E)
label2.grid(row=1,sticky=E) #sticky is used for alligning the labels in East direction :D
#perform the program without using sticky argument
entry_1.grid(row=0,column=1)
entry_2.grid(row=1,column=1) #row and column in grid
c = Checkbutton(root,text="Keep me logged in")
c.grid(columnspan=2) #Using columnspan we have allocated two column space for checkbutton
root.mainloop() |
from Tkinter import *
#Creating the toolbar
def ahi():
print("ahi")
root = Tk()
toolbar = Frame(root,bg="blue")
button_1 = Button(toolbar,text="Insert Img",command=ahi)
button_1.pack(side=LEFT,padx=2,pady=2)
printbut = Button(toolbar,text="print ahi",command=ahi)
printbut.pack(side=LEFT,padx=2,pady=2)
toolbar.pack(side=TOP,fill=X)
root.mainloop() |
import base
def bubblesort(arr):
for i in range (len(arr)-1):
for j in range (len(arr)-1 , i, -1):
if arr[j] < arr[j-1]:
arr[j], arr[j-1] = arr[j-1], arr[j]
return arr
if __name__ == '__main__':
for i in range (10):
arr = base.genlist ()
arr = bubblesort (arr)
if base.isSorted(arr) :
print "Correct!,result is", arr
else:
print "Wrong!,result is", arr
|
# _*_ coding:utf-8 _*_
# 函数的返回值可以是一个函数
def myabs(x):
return abs(x)
# 直接调用myabs 返回是abs的函数
print myabs(-1)
#任务
#请编写一个函数calc_prod(lst),它接收一个list,返回一个函数,返回函数可以计算参数的乘积。
def calc_prod(lst):
def calc(x,y):
return x*y
def delay_calc_prod():
return reduce(calc,lst)
return delay_calc_prod
f = calc_prod([1, 2, 3, 4])
print f()
#注意返回值是函数 还是 函数运行后计算的结构 里面的函数该干嘛就干嘛 关键是最后的返回值 要注意
|
#-*- coding:utf-8 -*-
# 定义一个无理数的加减乘除
class Rational(object):
"""docstring for Rational."""
#定义一个无理数,里面有分子和分母
def __init__(self, son,mother):
self.son = son
self.mother = mother
self.__getSimperRational()
# 分数的加法运算
def __add__(self,next):
if self.mother == next.mother:
return Rational(self.son+next.son,self.mother)
return Rational(self.son*next.mother+self.mother*next.son,self.mother
*next.mother)
#定义一个输出的无理数的方法
def __str__(self):
if self.son % self.mother == 0:
#能除尽,直接显示
return str(self.son/self.mother)
#用分数表示
return '%s/%s' % (self.son,self.mother)
#减法
def __sub__(self,next):
#2个分数一样的情况
if self.son*next.mother-self.mother*next.son == 0 :
return 0
#分母一样的情况
if self.mother == next.mother:
return Rational(self.son-next.son,self.mother)
return Rational(self.son*next.mother-self.mother*next.son,self.mother
*next.mother)
#定义一个函数,化简分数
def __getSimperRational(self):
if self.son > self.mother:
minnum = self.mother
else:
minnum = self.son
for i in range(minnum,1,-1):
if self.son % i == 0 and self.mother % i ==0:
self.son = self.son/i
self.mother = self.mother/i
break
#定义一个乘法
def __mul__(self,next):
return Rational(self.son*next.son,self.mother*next.mother)
#第一个除法
def __div__(self,next):
return Rational(self.son*next.mother,self.mother*next.son)
#可以讲结果转换成浮点数
def __float__(self):
return self.son*1.0/self.mother
#转换成整数
def __int__(self):
return self.son // self.mother
r1 = Rational(9,2)
r2 = Rational(2,2)
r3 = Rational(10,3)
print int(r3)
print float(r3)
print r3
print r1 + r2
print r1 - r2
print r1*r2
print r1/r2
|
#-*- coding:utf-8 -*-
# 类属性
class Person(object):
count = 0
def __init__(self):
Person.count += 1
p1 = Person()
p2 = Person()
p3 = Person()
p4 = Person()
p5 = Person()
p6 = Person()
print p2.count |
# _*_ coding:utf-8 _*_
# sorted()也是一个高阶函数,它可以接收一个比较函数来实现自定义排序,
#比较函数的定义是,传入两个待比较的元素 x, y,
#如果 x 应该排在 y 的前面,返回 -1,
#如果 x 应该排在 y 的后面,返回 1。
#如果 x 和 y 相等,返回 0。
L1 = [36, 5, 12, 9, 21]
L2 = sorted(L1)
print L2
def reversed_cmp(x,y):
if x > y:
return -1
elif x < y:
return 1
else:
return 0
L3 = sorted(L1,reversed_cmp)
print L3
#作业
#对字符串排序时,有时候忽略大小写排序更符合习惯。请利用sorted()高阶函数,实现忽略大小
#写排序的算法。
L4 = ['bob', 'about', 'Zoo', 'Credit']
#['about', 'bob', 'Credit', 'Zoo']
# 怎么实现
def cmp_ignore_case(t):
return t.lower()
print sorted(['bob', 'about', 'Zoo', 'Credit'], key=cmp_ignore_case)
def cmp_ignore_case2(s1,s2):
s1 = s1.upper()
s2 = s2.upper()
if s1 > s2:
return 1
if s1 < s2:
return -1
return 0
print sorted(['bob', 'about', 'Zoo', 'Credit'],cmp_ignore_case2)
print 'Abbbb'<'Baaaaa'
# 这里是我想多了 字符串也能比较大小 而且比较函数里面的参数你即使加工了 但却不影响原来
#list里面的值
L5 = [x for x in L4 for y in L4 if x.upper()<y.upper]
print L5
|
# _*_ coding:utf-8 _*_
# list :python 内置的一种列表数据类型 特点:1.有序 2.可以随意删除和修改 3. 中括号表示(和js的数组类似)
La = ['Micheal','Bob','Tracy']
Lb = ['Adam', 95.5, 'Lisa', 85, 'Bart', 59]
print Lb
#list 元素的访问,利用索引 从0开始
print Lb[0]
#当然也可以倒序访问 默认最后一个元素的索引是-1, 利用len方法可以获取对象的长度 所以第一个元素就应该是 -len(L)
print Lb[-len(Lb)]
#添加新的元素 list
#
#第一种办法:append(),把要追加的元素放到list的末尾
#
Lb.append('Lisa')
print Lb
print Lb[-1]
#第二种办法:利用insert 方法 这个方法有2个参数:1.索引 2.值 注意:这个只将替换索引出的值 而且将替换的值后移
Lb.insert(-1,'Lilei')
print Lb
Lb.insert(1,'Huge')
print Lb
#删除元素 用pop 方法 特点:里面可以加参数 参数代表索引 返回值是删除的这个元素
print Lb.pop()
print Lb
print Lb.pop(-1)
print Lb
#元素替换 这个就很简单了 直接利用索引获取元素后 赋值即可
Lb[-1] = 'NewLilei'
print Lb
|
# _*_ coding:utf-8 _*_
def testFileFunc():
'''
用来测试文件打开的模式不同带来的结果
'''
# keywords = raw_input("请输入您要测试的模式:")
# if keywords.lower() == 'r':
# print '我是只读文件'
# elif keywords.lower() == 'w':
# print '我是可写文件'
# else:
# print '您的输入不正常'
fp = open('hello.txt','a+')
print fp.read()
fp.close()
fp = open('hello.txt','a+')
fp.write('hello world')
fp.close()
if __name__ == '__main__':
testFileFunc()
|
# /usr/bin/env python
# _*_ coding:utf-8 _*_
# author:eno2050
# email:[email protected]
# 2017-10-2
import re
pattern = re.compile(r'(\w+) (\w+)')
s = 'i say, hello world!'
# 正则的方法完成替换
print re.sub(pattern,r'\2 \1', s)
# 函数的方法完成替换
def func(m):
return m.group(1).title() + ' ' + m.group(2).title()
print re.sub(pattern,func, s)
### output ###
# say i, world hello!
# I Say, Hello World!
|
"""
Define a function `isPrime(number)` that returns `true` if `number` is prime.
Otherwise, false. Assume `number` is a positive integer.
Examples:
isPrime(2); // => true
isPrime(10); // => false
isPrime(11); // => true
isPrime(9); // => false
isPrime(2017); // => true
***************************************************************************/
function isPrime(number) {
// start at 2 and check to see if number is divisible
// if divisible by any number other than 1, then return false
// otherwise, we would return true
for (let i = 2; i < number; i++) {
if (number % i === 0) { // 11 % 10 === 0
return false;
}
}
return true;
}
console.log(isPrime(2))
console.log(isPrime(10))
console.log(isPrime(11))
console.log(isPrime(9))
console.log(isPrime(2017))
"""
def isprime(number):
if number < 2:
False
for i in range(number):
i=1
i+=1
if number % i == 0:
return False
return True
print(isprime(5))
print(isprime(10))
print(isprime(11))
print(isprime(9))
print(isprime(2017)) |
#link for question
#https://onlinecourses.nptel.ac.in/noc19_cs08/progassignment?name=102
def progression(l):
i,j=0,1;
n=len(l);
if(n<=1):
return True;
d=l[0]-l[1];
while(j<n):
if(l[i]-l[j]!=d):
return False;
i,j=i+1,j+1;
return True;
def primesquare(l):
n=len(l);
if(n<=1):
return True;
return square_prime(l,0) or square_prime(l,1);
#wrong submission :(
'''def square_prime(l,rem):
start=l[rem];
n=len(l);
for i in range(n):
if(i%2==rem):
if(l[i]!=start**(i//2+1)):
return False;
else:
if(not isprime(l[i])):
return False;
return True;
'''
def square_prime(l,rem):
n=len(l);
for i in range(n):
if(i%2==rem):
if(not issquare(l[i])):
return False;
else:
if(not isprime(l[i])):
return False;
return True;
def issquare(n):
return int(n**0.5)**2==n;
def isprime(n):
if(n<=1):
return False;
for i in range(2,int(n**0.5)+1):
if(n%i==0):
return False;
return True;
def matrixflip(m,d):
m=m[:]
if(d=='h'):
n=len(m);
for i in range(n):
m[i]=m[i][-1::-1];
elif(d=='v'):
m=m[-1::-1];
return m;
|
age = int(input('Please enter a persons age.'))
if age >= 20:
print 'The person is eligible to vote.'
else
print 'The person is not eligible to vote'
|
#
# 定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseList(self, head):
cur, prev = head, None
# prev 是反转后的下一节点
# cur 是当前节点位置
# cur.next 当前的下一节点
while cur:
next = cur.next
cur.next = prev
prev = cur
cur = next
z = [1,2,3,4,5]
p = Solution.reverseList()
|
# 从一个线程向另一个线程发送数据最安全的方式可能就是使用
# queue 库中的队列了。创建一个被多个线程共享的 Queue 对象,
# 这些线程通过使用 put() 和 get() 操作来向队列中添加或者删除元素。 例如:
from queue import Queue
from threading import Thread
def producer(out_q):
i =1
while True:
...
out_q.put(i)
i +=1
if i >100:
break
def consumer(in_q):
while True:
data = in_q.get()
print('这是消费者',data)
...
q =Queue()
t1 = Thread(target=consumer, args=(q,))
t2 = Thread(target=producer, args=(q,))
t1.start()
t2.start()
qq =[]
qq.append() |
# 将format()函数和字符串方法是使得一个对象能够支持自定义方法的格式化
# 自定义格式化输出
_formats = {
'ymd' : '{d.year}-{d.month}-{d.day}',
'mdy' : '{d.month}/{d.day}/{d.year}',
'dmy' : '{d.day}/{d.month}/{d.year}'
}
class Date:
def __init__(self,year,month,day):
self.year = year
self.month = month
self.day = day
def __format__(self, code):
if code =='':
code ='ymd'
fmt = _formats[code]
return fmt.format(d=self)
d =Date(2020,12,3)
z =format(d,'mdy')
print(z)
# 这些可以参考date类
from datetime import date
d = date(2021,12,21)
print(format(d)) |
# 输入一个整型数组,数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值
# 要求时间复杂度为O(n)。
# 连续子数组:指在那个数组的连续的元素是连续截取出来的数组
# 动态规划
List = list
class Solution:
def maxSubArray(self, nums: list):
max_list = []
for i in range(len(nums)):
if len(max_list) == 0:
z = nums[i]
else:
z = nums[i] + max_list[-1] if max_list[-1] > 0 else nums[i]
max_list.append(z)
print(max_list)
return max(max_list)
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
for i in nums:
continue
P = Solution()
z = P.maxSubArray(nums)
print(z)
|
# 给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
# 此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
# 输入:[2,0,2,1,1,0]
# 输出:[0,0,1,1,2,2]
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
i, j, k = 0, len(nums)-1, 0
while k < len(nums):
if nums[k] == 0 and k > i:
nums[k], nums[i] = nums[i], nums[k]
i += 1
elif nums[k] == 2 and k < j:
nums[k], nums[j] = nums[j], nums[k]
j -= 1
else:
k+=1
|
# 请编写一个函数,使其可以删除某个链表中给定的(非末尾)节点,你将只被给定要求被删除的节点。
# 输入:head = [4,5,1,9], node = 5
# 输出:[4,1,9]
class Solution:
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val = node.next.val
node.next = node.next.next
|
# 给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
# 输入:babad
# 输出:bab
class Solution:
def longestPalindrome(self, s: str) -> str:
self.start = 0
self.max_len = 0
n = len(s)
if n < 2:
return s
def helper(i,j):
while i >= 0 and j < n and s[i] == s[j]:
i -= 1
j += 1
if self.max_len < j - i - 1:
self.max_len = j - i - 1
self.start = i + 1
for k in range(n):
helper(k, k)
helper(k, k+1)
return s[self.start:self.start+self.max_len]
|
# 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
# 有效字符串需满足:
# 左括号必须用相同类型的右括号闭合。
# 左括号必须以正确的顺序闭合。
# 输入:"{[]}"
# 输出:true
class Solution:
def isValid(self, s: str) -> bool:
while '{}' in s or '()' in s or '[]' in s:
s = s.replace('{}','')
s = s.replace('()','')
s = s.replace('[]','')
return s == ''
|
import csv
import pandas as pd
import argparse
def or_1(filename, output):
df = pd.read_csv(filename)
key_1 = input('First keyword : ')
loc = df[df['message'].str.contains(key_1)]
loc.to_csv(output, encoding='utf8')
print("Finish!")
def or_2(filename, output):
df = pd.read_csv(filename)
key_1 = input('First keyword : ')
key_2 = input('Second keyword : ')
key = key_1 + "|" + key_2
loc = df[df['message'].str.contains(key)]
loc.to_csv(output, encoding='utf8')
print("Finish!")
def or_3(filename, output):
df = pd.read_csv(filename)
key_1 = input('First keyword : ')
key_2 = input('Second keyword : ')
key_3 = input('Third keyword : ')
key = key_1 + "|" + key_2 + "|" + key_3
loc = df[df['message'].str.contains(key)]
loc.to_csv(output, encoding='utf8')
print("Finish!")
def or_4(filename, output):
df = pd.read_csv(filename)
key_1 = input('First keyword : ')
key_2 = input('Second keyword : ')
key_3 = input('Third keyword : ')
key_4 = input('Fourth keyword : ')
key = key_1 + "|" + key_2 + "|" + key_3 + "|" + key_4
loc = df[df['message'].str.contains(key)]
loc.to_csv(output, encoding='utf8')
print("Finish!")
def or_5(filename, output):
df = pd.read_csv(filename)
key_1 = input('First keyword : ')
key_2 = input('Second keyword : ')
key_3 = input('Third keyword : ')
key_4 = input('Fourth keyword : ')
key_5 = input('Fifth keyword : ')
key = key_1 + "|" + key_2 + "|" + key_3 + "|" + key_4 + "|" + key_5
loc = df[df['message'].str.contains(key)]
loc.to_csv(output, encoding='utf8')
print("Finish!")
def or_6(filename, output):
df = pd.read_csv(filename)
key_1 = input('First keyword : ')
key_2 = input('Second keyword : ')
key_3 = input('Third keyword : ')
key_4 = input('Fourth keyword : ')
key_5 = input('Fifth keyword : ')
key_6 = input('Sixth keyword : ')
key = key_1 + "|" + key_2 + "|" + key_3 + "|" + key_4 + "|" + key_5 + "|" + key_6
loc = df[df['message'].str.contains(key)]
loc.to_csv(output, encoding='utf8')
print("Finish!")
def or_7(filename, output):
df = pd.read_csv(filename)
key_1 = input('First keyword : ')
key_2 = input('Second keyword : ')
key_3 = input('Third keyword : ')
key_4 = input('Fourth keyword : ')
key_5 = input('Fifth keyword : ')
key_6 = input('Sixth keyword : ')
key_7 = input('Seventh keyword : ')
key = key_1 + "|" + key_2 + "|" + key_3 + "|" + key_4 + "|" + key_5 + "|" + key_6 + "|" + key_7
loc = df[df['message'].str.contains(key)]
loc.to_csv(output, encoding='utf8')
print("Finish!")
def or_8(filename, output):
df = pd.read_csv(filename)
key_1 = input('First keyword : ')
key_2 = input('Second keyword : ')
key_3 = input('Third keyword : ')
key_4 = input('Fourth keyword : ')
key_5 = input('Fifth keyword : ')
key_6 = input('Sixth keyword : ')
key_7 = input('Seventh keyword : ')
key_8 = input('Eighth keyword : ')
key = key_1 + "|" + key_2 + "|" + key_3 + "|" + key_4 + "|" + key_5 + "|" + key_6 + "|" + key_7 + "|" + key_8
loc = df[df['message'].str.contains(key)]
loc.to_csv(output, encoding='utf8')
print("Finish!")
def or_9(filename, output):
df = pd.read_csv(filename)
key_1 = input('First keyword : ')
key_2 = input('Second keyword : ')
key_3 = input('Third keyword : ')
key_4 = input('Fourth keyword : ')
key_5 = input('Fifth keyword : ')
key_6 = input('Sixth keyword : ')
key_7 = input('Seventh keyword : ')
key_8 = input('Eighth keyword : ')
key_9 = input('Ninth keyword : ')
key = key_1 + "|" + key_2 + "|" + key_3 + "|" + key_4 + "|" + key_5 + "|" + key_6 + "|" + key_7 + "|" + key_8 + "|" + key_9
loc = df[df['message'].str.contains(key)]
loc.to_csv(output, encoding='utf8')
print("Finish!")
def or_10(filename, output):
df = pd.read_csv(filename)
key_1 = input('First keyword : ')
key_2 = input('Second keyword : ')
key_3 = input('Third keyword : ')
key_4 = input('Fourth keyword : ')
key_5 = input('Fifth keyword : ')
key_6 = input('Sixth keyword : ')
key_7 = input('Seventh keyword : ')
key_8 = input('Eighth keyword : ')
key_9 = input('Ninth keyword : ')
key_10 = input('Tenth keyword : ')
key = key_1 + "|" + key_2 + "|" + key_3 + "|" + key_4 + "|" + key_5 + "|" + key_6 + "|" + key_7 + "|" + key_8 + "|" + key_9 + "|" + key_10
loc = df[df['message'].str.contains(key)]
loc.to_csv(output, encoding='utf8')
print("Finish!")
# ===============================================================================================
def and_2(filename, output):
df = pd.read_csv(filename)
key_1 = input('First keyword : ')
key_2 = input('Second keyword : ')
loc = df[df['message'].str.contains(key_1)]
loc = loc[loc['message'].str.contains(key_2)]
loc.to_csv(output, encoding='utf8')
print("Finish!")
def and_3(filename, output):
df = pd.read_csv(filename)
key_1 = input('First keyword : ')
key_2 = input('Second keyword : ')
key_3 = input('Third keyword : ')
loc = df[df['message'].str.contains(key_1)]
loc = loc[loc['message'].str.contains(key_2)]
loc = loc[loc['message'].str.contains(key_3)]
loc.to_csv(output, encoding='utf8')
print("Finish!")
def and_4(filename, output):
df = pd.read_csv(filename)
key_1 = input('First keyword : ')
key_2 = input('Second keyword : ')
key_3 = input('Third keyword : ')
key_4 = input('Fourth keyword : ')
loc = df[df['message'].str.contains(key_1)]
loc = loc[loc['message'].str.contains(key_2)]
loc = loc[loc['message'].str.contains(key_3)]
loc = loc[loc['message'].str.contains(key_4)]
loc.to_csv(output, encoding='utf8')
print("Finish!")
def and_5(filename, output):
df = pd.read_csv(filename)
key_1 = input('First keyword : ')
key_2 = input('Second keyword : ')
key_3 = input('Third keyword : ')
key_4 = input('Fourth keyword : ')
key_5 = input('Fifth keyword : ')
loc = df[df['message'].str.contains(key_1)]
loc = loc[loc['message'].str.contains(key_2)]
loc = loc[loc['message'].str.contains(key_3)]
loc = loc[loc['message'].str.contains(key_4)]
loc = loc[loc['message'].str.contains(key_5)]
loc.to_csv(output, encoding='utf8')
print("Finish!")
def and_6(filename, output):
df = pd.read_csv(filename)
key_1 = input('First keyword : ')
key_2 = input('Second keyword : ')
key_3 = input('Third keyword : ')
key_4 = input('Fourth keyword : ')
key_5 = input('Fifth keyword : ')
key_6 = input('Sixth keyword : ')
loc = df[df['message'].str.contains(key_1)]
loc = loc[loc['message'].str.contains(key_2)]
loc = loc[loc['message'].str.contains(key_3)]
loc = loc[loc['message'].str.contains(key_4)]
loc = loc[loc['message'].str.contains(key_5)]
loc = loc[loc['message'].str.contains(key_6)]
loc.to_csv(output, encoding='utf8')
print("Finish!")
def and_7(filename, output):
df = pd.read_csv(filename)
key_1 = input('First keyword : ')
key_2 = input('Second keyword : ')
key_3 = input('Third keyword : ')
key_4 = input('Fourth keyword : ')
key_5 = input('Fifth keyword : ')
key_6 = input('Sixth keyword : ')
key_7 = input('Seventh keyword : ')
loc = df[df['message'].str.contains(key_1)]
loc = loc[loc['message'].str.contains(key_2)]
loc = loc[loc['message'].str.contains(key_3)]
loc = loc[loc['message'].str.contains(key_4)]
loc = loc[loc['message'].str.contains(key_5)]
loc = loc[loc['message'].str.contains(key_6)]
loc = loc[loc['message'].str.contains(key_7)]
loc.to_csv(output, encoding='utf8')
print("Finish!")
def and_8(filename, output):
df = pd.read_csv(filename)
key_1 = input('First keyword : ')
key_2 = input('Second keyword : ')
key_3 = input('Third keyword : ')
key_4 = input('Fourth keyword : ')
key_5 = input('Fifth keyword : ')
key_6 = input('Sixth keyword : ')
key_7 = input('Seventh keyword : ')
key_8 = input('Eighth keyword : ')
loc = df[df['message'].str.contains(key_1)]
loc = loc[loc['message'].str.contains(key_2)]
loc = loc[loc['message'].str.contains(key_3)]
loc = loc[loc['message'].str.contains(key_4)]
loc = loc[loc['message'].str.contains(key_5)]
loc = loc[loc['message'].str.contains(key_6)]
loc = loc[loc['message'].str.contains(key_7)]
loc = loc[loc['message'].str.contains(key_8)]
loc.to_csv(output, encoding='utf8')
print("Finish!")
def and_9(filename, output):
df = pd.read_csv(filename)
key_1 = input('First keyword : ')
key_2 = input('Second keyword : ')
key_3 = input('Third keyword : ')
key_4 = input('Fourth keyword : ')
key_5 = input('Fifth keyword : ')
key_6 = input('Sixth keyword : ')
key_7 = input('Seventh keyword : ')
key_8 = input('Eighth keyword : ')
key_9 = input('Ninth keyword : ')
loc = df[df['message'].str.contains(key_1)]
loc = loc[loc['message'].str.contains(key_2)]
loc = loc[loc['message'].str.contains(key_3)]
loc = loc[loc['message'].str.contains(key_4)]
loc = loc[loc['message'].str.contains(key_5)]
loc = loc[loc['message'].str.contains(key_6)]
loc = loc[loc['message'].str.contains(key_7)]
loc = loc[loc['message'].str.contains(key_8)]
loc = loc[loc['message'].str.contains(key_9)]
loc.to_csv(output, encoding='utf8')
print("Finish!")
def and_10(filename, output):
df = pd.read_csv(filename)
key_1 = input('First keyword : ')
key_2 = input('Second keyword : ')
key_3 = input('Third keyword : ')
key_4 = input('Fourth keyword : ')
key_5 = input('Fifth keyword : ')
key_6 = input('Sixth keyword : ')
key_7 = input('Seventh keyword : ')
key_8 = input('Eighth keyword : ')
key_9 = input('Ninth keyword : ')
key_10 = input('Tenth keyword : ')
loc = df[df['message'].str.contains(key_1)]
loc = loc[loc['message'].str.contains(key_2)]
loc = loc[loc['message'].str.contains(key_3)]
loc = loc[loc['message'].str.contains(key_4)]
loc = loc[loc['message'].str.contains(key_5)]
loc = loc[loc['message'].str.contains(key_6)]
loc = loc[loc['message'].str.contains(key_7)]
loc = loc[loc['message'].str.contains(key_8)]
loc = loc[loc['message'].str.contains(key_9)]
loc = loc[loc['message'].str.contains(key_10)]
loc.to_csv(output, encoding='utf8')
print("Finish!")
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Search keywords in .csv',
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('filename', help='.csv filename')
parser.add_argument("mode", type=str, nargs="+")
parser.add_argument('output', help='output name')
args = parser.parse_args()
if args.mode[0] == "or":
print("Search Mode : Or, " + args.mode[1] + " keyword.")
if args.mode[1] == "1":
or_1(args.filename, args.output)
if args.mode[1] == "2":
or_2(args.filename, args.output)
if args.mode[1] == "3":
or_3(args.filename, args.output)
if args.mode[1] == "4":
or_4(args.filename, args.output)
if args.mode[1] == "5":
or_5(args.filename, args.output)
if args.mode[1] == "6":
or_6(args.filename, args.output)
if args.mode[1] == "7":
or_7(args.filename, args.output)
if args.mode[1] == "8":
or_9(args.filename, args.output)
if args.mode[1] == "9":
or_9(args.filename, args.output)
if args.mode[1] == "10":
or_10(args.filename, args.output)
if args.mode[0] == "and":
print("Search Mode : And, " + args.mode[1] + " keyword.")
if args.mode[1] == "1":
or_1(args.filename, args.output)
if args.mode[1] == "2":
and_2(args.filename, args.output)
if args.mode[1] == "3":
and_3(args.filename, args.output)
if args.mode[1] == "4":
and_4(args.filename, args.output)
if args.mode[1] == "5":
and_5(args.filename, args.output)
if args.mode[1] == "6":
and_6(args.filename, args.output)
if args.mode[1] == "7":
and_7(args.filename, args.output)
if args.mode[1] == "8":
and_8(args.filename, args.output)
if args.mode[1] == "9":
and_9(args.filename, args.output)
if args.mode[1] == "10":
and_10(args.filename, args.output)
|
def skal_proizv(a, b):
if len(a) != len(b):
raise Exception('Векторы имеют разную длину')
res = 0
for i in range(len(a)):
res += a[i]*b[i]
#print('Скалярное произведение векторов =', res)
return res
def write_vec():
print('Введите координаты вектора в строку через пробел')
return list(map(int, input().split()))
def write_matrix():
A = []
print('Введите количество строк матрицы')
n = int(input())
print('Введите строки матрицы, разделяя элементы пробелом')
for i in range(n):
A.append([int(x) for x in input().split()])
return A
def matrix_2D(A): #Печатает матрицу
for i in range(len(A)):
print(*A[i])
print()
def trans_matrix(A):
B = [[] for i in range(len(A[0]))]
for i in range(len(A)):
for j in range(len(A[0])):
B[j].append(A[i][j])
return B
def matrix_multiply(A, B):
C = [[] for i in range(len(A))]
B = trans_matrix(B)
for i in range(len(A)):
for j in range(len(B)):
C[i].append(skal_proizv(A[i], B[j]))
return C
def podmatrix_for_first_stroke(A, j):
B = []
A = A[1:] + A[0:1]
for i in range(len(A)-1):
B.append(A[i][0:j] + A[i][j+1:])
return B
def det(A):
res = 0
z = 0
if len(A) != len(A[0]):
raise Exception("Матрица не является квадратной")
if len(A[0]) == 1: #Крайний случай
return int(A[0][0])
else:
for j in range(len(A[0])):
z = det(podmatrix_for_first_stroke(A, j))
res += (-1)**(j)*A[0][j]*z
return res
def podmatrix(A, i, j):
B = []
A = A[:i] + A[i+1:]
for k in range(len(A)):
B.append(A[k][0:j] + A[k][j + 1:])
return B
def invert_matrix(A):
d = det(A)
if d == 0:
raise Exception("Матрица вырождена")
if len(A) != len(A[0]):
raise Exception("Матрица не является квадратной")
B = [[0*len(A)]*len(A) for i in range(len(A))]
for i in range(len(A)):
for j in range(len(A)):
B[i][j] = (-1)**(i+j)*(det(podmatrix(A, i, j))/d)
return trans_matrix(B)
A = write_matrix()
matrix_2D(invert_matrix(A)) |
print "You enter a dark room with two doors. Do you go through door #1, door #2, or door #3?"
door = raw_input("> ")
if door == "1":
print "There's a giant bear here eating a cheesecake. What do you do?"
print "1. Take the cake."
print "2. Scream at the bear."
bear = raw_input("> ")
if bear == "1":
print "The bear eats your face off. Ouch!"
elif bear == "2":
print "The bear eats your legs off. Ouch!"
else:
print "Well, doing %s is probably better. Bear runs away." % bear
if door == "2":
print "You stare into the endless abyss at Cthulhu's retina."
print "1. Blueberries."
print "2. Yellow jacket clothespins."
print "3. Understanding revolvers yelling melodies."
insanity = raw_input("> ")
if insanity == "1" or insanity == "2":
print "Your body survives powered by a mind of jello. Ouch!"
else:
print "The insanity rots your eyes into a pool of much. Ouch!"
if door >= "3":
print "It's very dark in here. What else is in here?"
print "1. A ghost! Yikes!"
print "2. A very soft and comfortable bed. Good night moon."
darkness = raw_input("? ")
if darkness == "1" or darkness =="2":
print "You are getting very sleepy."
else:
print "Lights out princess."
|
#http://ideone.com/DRnYj1
class AdoptionCenter:
def __init__(self, name, species_type, location):
self.name = name
self.location = float(location[0]),float(location[1])
self.species_type = species_type
def get_name(self):
return self.name
def get_location(self):
return self.location
def get_species_count(self):
return self.species_type.copy()
def get_number_of_species(self, species_name):
if species_name in self.species_type:
return (self.species_type[species_name])
return 0
def adopt_pet(self, species_name):
if species_name in self.species_type:
self.species_type[species_name] -= 1
if self.species_type[species_name] <= 0:
del self.species_type[species_name]
class Adopter:
def __init__(self, name, desired_species):
self.name = name
self.desired_species = desired_species
def get_name(self):
return self.name
def get_desired_species(self):
return self.desired_species
def get_score(self, adoption_center):
num_desired = adoption_center.get_number_of_species(self.desired_species)
return float(1 * num_desired)
adopter = Adopter("place", "cat")
place = AdoptionCenter("place", {"cat":4, "dog":5, "horse":3}, (4,5))
print(adopter.get_score(place))
|
#!/usr/bin/env python3
class Player():
def __init__(self, name_list:list=["X","Y","Z"]):
"""Takes two player names, or defaults to X and Y"""
self.name_list = name_list
self.index = 0
def switch(self):
"""Change current player"""
self.index = (1+self.index) % len(self.name_list)
def name(self):
"""Return current player name"""
return(self.name_list[self.index])
def test():
"""To test code in this module"""
pl = Player()
assert(pl.name() == "X")
pl.switch()
assert(pl.name() == "Y")
pl.switch()
assert(pl.name() == "Z")
pl.switch()
assert(pl.name() == "X")
pl2= Player(["X", "O"])
assert(pl2.name() == "X")
pl2.switch()
assert(pl2.name() == "O")
test()
## For writing test-first python |
def e_impar(n):
return n%2 == 0
n = int(input('digite um número:'))
print(f'o número {n} é ímpar?', not e_impar(n))
|
sequence = 'Hello World'
# expected output:
# dlroW olleH
for char in reversed(sequence):
print(char, end='')
print()
# expected output:
# dlroW olleH
for idx in range(len(sequence)-1, -1, -1):
char = sequence[idx]
print(char, end='')
print()
# expected output:
# dlroW olleH
for char in sequence[::-1]:
print(char, end='')
print()
char_list = list(sequence)
char_list.reverse()
# expected output:
# dlroW olleH
for char in char_list:
print(char, end='')
s = "Hello"
# expected output:
# olleH
print( s[::-1] )
char_list = list(s)
char_list.reverse()
print( ''.join(char_list) )
print()
s = "Hello"
# expected output:
# olleH
for i in range(0, len(s)):
print(s[len(s)-i-1], end='')
|
def should_react(current, previous):
if current.lower() != previous.lower():
return False
elif current == previous:
return False
elif current.upper() == previous or current == previous.upper():
return True
if __name__ == '__main__':
with open('input.txt', 'r') as f:
stack = []
while True:
current = f.read(1)
if not current or current == '\n':
break
elif len(stack) == 0:
stack.append(current)
continue
previous = stack.pop()
if not should_react(current, previous):
stack.append(previous)
stack.append(current)
print('Length of sequence:', len(stack))
|
#!/usr/bin/env python
def isDivisibleByAll(number):
for i in xrange(1,21):
if number % i != 0:
return False
return True
def problem5():
# note you can also set this number below to the lcm of
# any of the prior in sequence, for example 1..10 = 2520
number = 20 # largest number amongst divisors
while True:
if isDivisibleByAll(number):
break
number += 20
print "%d is divisible by each of 1 thru 20" % (number)
problem5() |
# Question 1
def main():
# You don't need to modify this function.
a = input('Enter one number')
b = input('Enter another number')
compare = which_number_is_larger(a, b)
if compare == 'same':
print('The two numbers are the same')
else:
print('The %s number is larger' % compare)
def which_number_is_larger(first, second):
# TODO if the first number is larger, return the string 'first'
# TODO if the second number is larger, return the string 'second'
# TODO if the numbers are the same, return the string 'same'
return # TODO replace this with your code
# You don't need to modify this code.
if __name__ == "__main__":
main()
|
from collections import defaultdict, deque
class Solution:
def get_order(self, word1, word2):
n, m = len(word1), len(word2)
i = j = 0
while i < n and j < m and word1[i] == word2[j]:
i += 1
j += 1
if i == n:
return None, None
return word1[i], word2[j]
def get_graph(self, words):
graph = defaultdict(list)
n = len(words)
for i in range(1, n):
u, v = self.get_order(words[i - 1], words[i])
if u is None:
continue
graph[u].append(v)
graph[v]
return graph
def getAlienDictionary_dfs(self, words):
def is_circle(v):
visit[v] = True
cir_stack[v] = True
for u in graph[v]:
if not visit[u] and is_circle(u):
return True
if visit[u] and cir_stack[u]:
return True
stack.append(v)
cir_stack[v] = False
return False
graph = self.get_graph(words)
stack = []
visit = {v: False for v in graph}
cir_stack = visit.copy()
for v in visit:
if visit[v]:
continue
if is_circle(v):
return ""
return "".join(stack[::-1])
def getAlienDictionary(self, words):
graph = self.get_graph(words)
in_degree = defaultdict(int)
for u in graph:
for v in graph[u]:
in_degree[v] += 1
que = deque()
for u in graph:
if in_degree[u] == 0:
que.append(u)
order = ""
while que:
u = que.popleft()
order += u
for v in graph[u]:
in_degree[v] -= 1
if in_degree[v] != 0:
continue
que.append(v)
if len(order) != len(graph):
return ""
return order
if __name__ == '__main__':
sol = Solution()
words = ["wrt", "wrf", "er", "ett", "rftt"]
print(sol.getAlienDictionary(words))
print(sol.getAlienDictionary(['z', 'x']))
print(sol.getAlienDictionary(['z', 'x', 'z']))
print(sol.getAlienDictionary(['abc', 'abcd', 'fg', 'hi']))
|
"""
314. Binary Tree Vertical Order Traversal
Medium
1615
212
Add to List
Share
Given the root of a binary tree, return the vertical order traversal of its nodes' values. (i.e., from top to bottom, column by column).
If two nodes are in the same row and column, the order should be from left to right.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [[9],[3,15],[20],[7]]
Example 2:
Input: root = [3,9,8,4,0,1,7]
Output: [[4],[9],[3,0,1],[8],[7]]
Example 3:
Input: root = [3,9,8,4,0,1,7,null,null,null,2,5]
Output: [[4],[9,5],[3,0,1],[8,2],[7]]
Example 4:
Input: root = []
Output: []
Constraints:
The number of nodes in the tree is in the range [0, 100].
-100 <= Node.val <= 100
"""
# solution 1
from collections import deque, defaultdict
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def verticalOrder(self, root: TreeNode) -> List[List[int]]:
que = deque([(root, 0)])
col_map = defaultdict(list)
while que:
node, x = que.popleft()
if not node:
continue
col_map[x].append(node.val)
que.append((node.left, x - 1))
que.append((node.right, x + 1))
res = []
for col in sorted(col_map):
res.append(col_map[col])
return res
# solution 2
from collections import deque, defaultdict
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def verticalOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if not root:
return []
que = deque([(root, 0)])
res = defaultdict(list)
lt = rt = 0
while que:
node, x = que.popleft()
res[x].append(node.val)
if node.left:
que.append((node.left, x - 1))
lt = min(lt, x - 1)
if node.right:
que.append((node.right, x + 1))
rt = max(rt, x + 1)
out = []
for x in range(lt, rt + 1):
out.append(res[x])
return out |
"""
270. Closest Binary Search Tree Value
Easy
1160
81
Add to List
Share
Given the root of a binary search tree and a target value, return the value in the BST that is closest to the target.
Example 1:
Input: root = [4,2,5,1,3], target = 3.714286
Output: 4
Example 2:
Input: root = [1], target = 4.428571
Output: 1
Constraints:
The number of nodes in the tree is in the range [1, 104].
0 <= Node.val <= 109
-109 <= target <= 109
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def closestValue(self, root: TreeNode, target: float) -> int:
closest = root.val
while root:
closest = min(closest, root.val, key=lambda x: abs(x - target))
if closest == target:
break
if root.val < target:
root = root.right
else:
root = root.left
return closest |
#!/usr/bin/py
"""
Consider an array of integers, A, where all but one of the integers occur in pairs. In other words, every element in A
occurs exactly twice except for one unique element. Find the unique element.
Solution: Using bitwise xor on each integer, each integer pair will cancel each other out to return 0, which will leave the unique integer.
"""
def lonelyinteger(a):
answer = 0
for number in a:
answer = answer ^ number
return answer
if __name__ == '__main__':
a = input()
b = map(int, raw_input().strip().split(" "))
print lonelyinteger(b)
|
# Caleb Manor
# This is a Python comment
# Create some dynamically typed variables and intitialize them
an_integer = 55
a_string = "This is a Python program"
a_bool = True
a_float = 3.25
# Here is a calculation
the_answer = an_integer * a_float + ord(a_string[0]) + int(a_bool)
print(the_answer)
# Write code that will output an_integer to the fourth power
# output the_answer to one decimal place
print(pow(an_integer, 4))
print(round(the_answer, 1))
|
#2. input a number. check if the number is 0 or 1, if so print '0 or 1
# otherwise check if the number is -1, if so print '-1'
# otherwise print 'unknown number'
a = int(input('input num to check a = '))
if a == 0 or a == 1:
print('num is 0 or 1')
else:
if a == -1:
print('num is -1')
else:
# if a < -1 or a > 1:
print('unknown num') |
# -*- encoding: utf-8 -*-
"""
链表练习
@File : link_exercises.py
@Time : 2020/04/13 23:05:41
@Author : Zhong Hao
@Version : 1.0
@Contact : [email protected]
@Desc : None
"""
from model import init_link, Link, Node
def find_last_node(link, reverse_index: int):
" 不使用 length 属性,查询倒数的节点 "
first_node = link.head_node
second_node = link.head_node
for i in range(reverse_index):
if not second_node:
return None
second_node = second_node.next_node
while second_node:
second_node = second_node.next_node
first_node = first_node.next_node
return first_node
def find_middle_node(link: Link) -> Node:
" 查找中间的节点 "
first_node = link.head_node
second_node = link.head_node
while second_node.next_node and second_node.next_node.next_node:
first_node = first_node.next_node
second_node = second_node.next_node.next_node
return first_node
def reverse_link(link: Link) -> Link:
" 反转链表 "
new_head_node = None
current_node = link.head_node
while current_node:
next_node = current_node.next_node
current_node.next_node = new_head_node
new_head_node = current_node
current_node = next_node
link.head_node = new_head_node
return link
def reverse_print(node: Node):
" 反转打印 "
if node.next_node:
reverse_print(node.next_node)
print(f'{node} -> ', end='')
def get_cycle_length(link: Link) -> int:
"""
获取环的长度
环的长度即为相遇时 first 走过的长度
"""
first_node = link.head_node
second_node = link.head_node
length = 0
while first_node and first_node.get_next and second_node and second_node.get_next:
first_node = first_node.next_node
second_node = second_node.next_node.next_node
length += 1
if first_node == second_node:
return length
return 0
if __name__ == "__main__":
# link = init_link(10)
# print(link)
# node = find_last_node(link, 11)
# print(node)
# node = link.find_node(11)
# print(node)
# node = link.find_last_node(11)
# print(node)
# node = find_middle_node(link)
# print(f'middle node: {node}')
# _link = reverse_link(init_link(20))
# print(f'reverse_link: {_link}')
# print('reverse_print')
# reverse_print(init_link(10).head_node)
print()
_link = init_link(10)
# 设置环
_link.find_node(10).next_node = _link.find_node(5)
print(f'环的长度为:{get_cycle_length(_link)}')
|
import tkinter
class Store:
def __init__(self):
self.variable = tkinter.IntVar()
def add(self, value):
var = self.variable
var.set(var.get() + value)
return var.get()
class Main(tkinter.Tk):
def __init__(self, *args, **kwargs):
tkinter.Tk.__init__(self, *args, **kwargs)
var = Store()
self.label = tkinter.Label(self, textvariable=var.variable)
self.button = tkinter.Button(self, command=lambda: var.add(1), text='+1')
self.label.pack()
self.button.pack()
root = Main()
root.mainloop() |
from instantiate import room
from player import Player
from room import Room
from item import Item
from functions import print_slow
import sys
#
# Main
#
# Make a new player object that is currently in the 'entrance' room.
player = Player()
player.current_room = room['entrance']
# Write a loop that:
#
# * Prints the current room name
# * Prints the current description (the textwrap module might be useful here).
# * Waits for user input and decides what to do.
#
# If the user enters a cardinal direction, attempt to move to the room there.
# Print an error message if the movement isn't allowed.
#
# If the user enters "q", quit the game.
# Intro and instructions
print_slow('You wake up at the entrance of a mansion\nYou notice a piece of paper in your hand, it reads\n\"Find the Cybertruck.\"\n')
print_slow('You see a hallway to your north, a door to your east and west, and no exit behind you.\n')
print_slow('Enter \'n\', \'e\', \'s\', or \'w\' to move around.\n')
print_slow('Type \'search\' in any room to look for items in that room\n')
print_slow('To see what items you have, type \'items\'.\n\n')
print_slow('To quit type \'q\'\n')
print_slow('PRO TIP: Keep track of where you are so you don\'t get lost!\n\n')
while player.foundTruck == False:
action = input('Move or search? (n, e, s, w, or search): ').upper()
print('\n')
if action == 'SEARCH':
player.search()
elif action == 'ITEMS':
player.checkInventory()
elif action[0] in ['N', 'E', 'S', 'W']:
player.move(action)
elif action == 'Q':
sys.exit()
else:
print_slow('Incorrect input')
if player.current_room.name == room['cybertruck'].name:
player.foundTruck = True
take_job = input('Do you take the job? (Y/N): ').upper()
if take_job == 'Y':
print_slow('\nCongratulations! You managed to find the Cybertruck and get a job! Well done!\n')
elif take_job == 'N':
print_slow('\nSad Elon is sad, but you still managed to find the Cybertruck!\n')
input('Press \'Enter\' to exit!') |
#meses = ["janeiro", "fevereiro","março","abril","maio","junho","julho","agosto","setembro","outubro","novembro","dezembro"]
mes = str(input("insira o mes do nascimento de Jose Carlos: "))
dia = int(input("insira o dia do seu aniversario: "))
if mes == "abril":
print("Estação do aniversario de José Carlos é outono!")
else:
print("José não nasceu nesse mes, opção invalida")
|
import sys
def fizz_buzz():
"""
Classic fizz buzz
"""
test_cases = open( sys.argv[1], 'r' )
for test in test_cases:
if len( test ) == 0: # ignore empty line
continue
else:
## read arguments ##
args = test.split()
x = int( args[0] )
y = int( args[1] )
n = int( args[2] )
## count up ##
out_string = ''
for i in range( 1, n + 1 ):
if i % x == 0:
out_string += 'F'
if i % y == 0:
out_string += 'B'
if i % x != 0 and i % y != 0:
out_string += str( i )
out_string += ' '
print( out_string.strip() )
|
def distance(dna_strand_one, dna_strand_two):
# Check if both have same size
if len(dna_strand_one) != len(dna_strand_two):
raise ValueError
distance_count = 0
for nucleotide_one, nucleotide_two in zip(dna_strand_one, dna_strand_two):
if not nucleotide_one == nucleotide_two:
distance_count += 1
return distance_count
|
""" 25. Em uma eleição presidencial existem 3 (três) candidatos. Os votos são informados através de códigos.
Os dados utilizados para a contagem dos votos obedecem à seguinte codificação:
· 1, 2, 3 = voto para os respectivos candidatos; · 9 = voto nulo; · 0 = voto em branco;
Escreva um algoritmo que leia o código votado por N eleitores. Ao final, calcule e escreva:
a) total de votos para cada candidato; b) total de votos nulos; c) total de votos em branco; d) quem venceu a eleição.
"""
print('Questão 25.')
def main():
voto = int(input('Digite o seu voto /0- Branco/1- Fulano/2- Beltrano/3- Cicrano/9- Nulo/4- FIM): '))
eleicao(voto,0,0,0,0,0,0,0)
def eleicao (voto,eleitores, cont_1, cont_2, cont_3, cont_9, cont_0, vencedor):
while voto != 4:
if voto == 1 or voto == 2 or voto == 3 or voto == 9 or voto == 0:
eleitores += 1
if voto == 1:
cont_1 += 1
if voto == 2:
cont_2 += 1
if voto == 3:
cont_3 += 1
if voto == 9:
cont_9 += 1
if voto == 0:
cont_0 += 1
voto = int(input('Digite o seu voto /0- Branco/1- Fulano/2- Beltrano/3- Cicrano/9- Nulo/4- FIM): '))
else:
if cont_1 > cont_2 and cont_1 > cont_3 and cont_1 > cont_9 and cont_1 > cont_0:
vencedor = "O candidato vencedor é: /1- Fulano/"
elif cont_2 > cont_1 and cont_2 > cont_3 and cont_2 > cont_9 and cont_2 > cont_0:
vencedor = "O candidato vencedor é: /2- Beltrano/"
elif cont_3 > cont_1 and cont_3 > cont_2 and cont_3 > cont_9 and cont_3 > cont_0:
vencedor = "O candidato vencedor é: /3- Cicrano/"
elif cont_9 > cont_1 and cont_9 > cont_2 and cont_9 > cont_3 and cont_9 > cont_0:
vencedor = "A maioria dos votos foi /9- NULO/"
elif cont_0 > cont_1 and cont_0 > cont_2 and cont_0 > cont_3 and cont_1 > cont_9:
vencedor = "A maioria dos votos foi /0- BRANCO/"
print('=============================================')
print('Nesta eleição tivemos %d eleitores presentes.' % eleitores)
print('O candidato /1- Fulano/ obteve %d votos.' % cont_1)
print('O candidato /2- Beltrano/ obteve %d votos.' % cont_2)
print('O candidato /3- Cicrano/ obteve %d votos.' % cont_3)
print('Total de nulos: %d' % cont_9)
print('Total de brancos: %d' % cont_0)
print (vencedor)
if __name__ == '__main__':
main()
|
'''07. Leia um número N, some todos os números inteiros entre 1 e N e escreva o resultado obtido.'''
print('Questão 07.')
numero = int(input('Informe um valor limite: '))
contador = 0
def total(contador, numero):
for soma in range(1, numero+1):
resultado = contador + soma
contador += soma
return contador
print(total(contador,numero)) |
# -*- coding: utf-8 -*-
"""20. Leia uma temperatura em °C, calcule e escreva a equivalente em °F. (t°F = (9 * t°C + 160) / 5) """
temp_c = float(input('Digite a temperatura em ºC: '))
temp_f = (9* temp_c + 160)/5
print ('A temperatura %.1f ºC equivale a %.1f ºF.' % (temp_c, temp_f))
|
n = int(input("Enter a Number : "))
series_sum = []
for i in range(1,n+1):
series_sum.append(i)
if i==n:
print(i, end='')
else:
print(i,end=' + ')
print(' = ', sum(series_sum), sep='')
|
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
listt = []
for num in a:
if num <5:
listt.append(num)
print(listt)
# one liner
print([aa for aa in a if aa < 5]) |
#python file to convert csv disease file to json
import json
csvfile = open("convertcsv.csv", 'r')
json_list = list()
disease_dict = dict()
disease = ""; count_occurence = 0; symptoms = []
#disease_done = False
for line in csvfile:
if line.startswith(",,"):
#disease_done = False
symptoms.append(line[2:])
else:
#disease_done = True
disease_dict["Symptoms"] = symptoms
print("APPEND", disease_dict)
print()
json_list.append(disease_dict)
disease_dict = dict(); symptoms = []
#print(line.split(","))
disease = line.split(",")[0]; count_occurence = line.split(",")[1]; symptoms.append(line.split(",")[2])
disease_dict["Disease"] = disease
disease_dict["Count"] = count_occurence
disease_dict["Symptoms"] = symptoms
csvfile.close()
json_list = json_list[1:]
print(json_list)
json.dumps(json_list)
with open("final.json", 'w') as outfile:
json.dump(json_list, outfile)
|
from abc import ABC, abstractmethod
class Pessoa:
def __init__(self, nome, idade):
self._nome = nome
self._idade = idade
@property
def nome(self):
return self._nome
@property
def idade(self):
return self._idade
class Conta(ABC):
def __init__(self, agencia, conta, saldo):
self._agencia = agencia
self._conta = conta
self._saldo = saldo
def depositar(self, valor):
self._saldo += valor
self.detalhes_conta()
def detalhes_conta(self):
print(f"Agência: {self._agencia}")
print(f"Conta: {self._conta}")
print(f"Saldo: R${self._saldo:.2f}")
@abstractmethod
def sacar(self):
pass
|
from termcolor import colored, cprint
import random, math
score = 0
pos = 0
global full
full = 0
real = open('/usr/share/dict/words').read().split() #Added files to my computer
fake = open('/usr/share/dict/fake').read().split()
fake = sorted(set(fake))
def draw():
for k in range(0, 3):
print ''
def check(var):
# print var.split()
for k in var.split():
# print k
if k in prof:
return True
# else:
# return False
draw()
cprint('YOU HAVE STARTED WORD LEARNING! CONGRATULATIONS!', 'red')
draw()
cprint('This test will give you random words, and you have to say whether they are real or not.', 'yellow')
draw()
cprint("Hit ENTER when you're ready! Good luck!", 'cyan')
raw_input()
for k in range(1, 11):
num = random.randint(1, 2)
if num == 1:
word = random.choice(real)
cprint('Is %s a real word?' %(word.lower()), 'blue')
var = raw_input()
if var.lower().startswith('y') == True:
cprint('Yes!', 'green')
score+=1
elif var.lower().startswith('n') == True
cprint('No!', 'red')
pos+=1
full = (int((float(score)/float(pos))*100))
cprint('Your score so far is %d%%!' %(full), 'cyan')
else:
word = random.choice(fake)
cprint('Is %s a real word?' %(word.lower()), 'blue')
var = raw_input()
if var.lower().startswith('n') == True and check(var) != True:
cprint('Yes!', 'green')
score+=1
elif var.lower().startswith('y') == True and check(var) != True:
cprint('No!', 'red')
else:
var = var.split()
for k in var:
if k in prof:
print 'You too!'
break
cprint('STOP CUSSING!', 'magenta')
pos+=1
full = (int((float(score)/float(pos))*100))
cprint('Your score so far is %d%%!' %(full), 'cyan')
def evaluate():
global full
if full <= 20:
level = 1
elif full > 20 and full <= 40:
level = 2
elif full > 40 and full <= 60:
level = 3
elif full > 60 and full <= 80:
level = 4
else:
level = 5
return int(level)
|
username = input("输入角色")
equipment = input("请输入拥有的装备")
buy_equipent = input("请输入想购买的装备")
payment_amount= input("请输入付款金额")
print("{}购买了{}装备,花了{}钱".format(username,buy_equipent,payment_amount)) |
# 1234能组成多少个数字1.0 强算法
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9,]
list2= []
for i in list1:
a = 100 * i # 百位
for x in list1:
if x == i:
continue
else:
b = 10 * x # 十位
for y in list1:
if y == x:
continue
elif y == i:
continue
else:
c = 1 * y # 个位
d = a + b + c
list2.append(d)
print("一共有{}种可能".format(len(list2)))
print("分别为:\n{}".format(list2))
|
a = input("请输入数字:")
b = 0
for i in range(int(a)):
b += i+1
print("从1到{}的和为{}.".format(a,b))
|
#4个数能组成多少种可能通
def func(a):
ls=[]
for i in range(1,5):
for j in range(1,5):
for k in range(1, 5):
for n in range(1, 5):
b="{}{}{}{}".format(i,j,k,n)
ls.append(b)
return ls
a=func(4)
print(len(a)) |
list1 = eval(input("输入一个列表:")) # 获得用户输入
num1 = eval(input("输入:")) #获得用户输入
list2 = [] # 定义一个空列表
for i in list1: # 遍历一遍用户输入
for y in list1: # 遍历一遍用户输入
if y == i: # 如果 y==i则跳出当次循环
continue
else: # 不等于则
if i + y == num1: # 判断 i + y 是否等于 rargrt
list2.append(i) # 是的话则向列表添加 i 和y
list2.append(y)
break # 跳出当前循环
print(list2) |
#身体bmi值
num1=eval(input("输入身高(米):"))
num2=eval(input("输入体重(千克):"))
bim=num2/pow(num1,2)
print("身体的BMI值为:{:.2f}".format(bim))
a=""#国外
b=""#国内
if bim<18.5:
a="偏瘦"
b="偏瘦"
elif 18.5<=bim<25:
a="正常"
elif 18.5<=bim<24:
b="正常"
elif 24<=bim<28:
b="偏胖"
elif bim>=28:
b="肥胖"
elif 25<=bim<30:
a="偏胖"
else:
a="肥胖"
print("国内:{}\n国外:{}".format(b,a))
|
# 工作人进步周末退步365天后
dayup = 1
dayx = 0.01
for i in range(365):
if i % 7 in [0, 6]:
dayup = dayup - dayx * dayup
else:
dayup = dayup + dayx * dayup
print("365天后为:{:.2f}".format(dayup))
|
num1=input("输入:")
num1=eval(num1)
for i in range(1,num1+1):
num1=i*num1
print(num1) |
#靶盘
from turtle import *
setup(900,900,0,0)
pencolor("green")
pensize(300)
goto(-350,350)
fd(700)
for i in range(2):
circle(-100,180)
fd(700)
circle(100,180)
fd(700)
goto(0,0)
pensize(15)
pencolor("red")
circle(5)
pensize(12)
yanse=['white','black']
r=10
for i in range(100):
pencolor(yanse[i%len(yanse)])
circle(r)
r=r+10
penup()
goto(0,-10*(i+1))
pendown()
done() |
#文本刷新
import time
print("-----程序开始-----")
num1=10
for i in range(num1+1):
a="**"*i
b="--"*(num1-i)
c=(i/num1)*100
print("{:^3.0f}%[{}->{}]".format(c,a,b))
time.sleep(0.1)
print("-----程序结束-----")
|
print('***************************')
print('''欢迎光临小象奶茶馆!
您已进入小象奶茶自助点餐系统!
小象奶茶馆售卖宇宙无敌奶茶!
奶茶虽好,可不要贪杯哦!
1号. 原味冰奶茶 3元
2号. 香蕉冰奶茶 5元
3号. 草莓冰奶茶 5元
4号. 蒟蒻冰奶茶 7元
5号. 珍珠冰奶茶 7元 ''')
print('***************************')
milktea_name=int(input('请输入奶茶号:'))
print('***************************')
milktea_number=int(input('请输入要购买奶茶数量:'))
print('***************************')
Vip=input('请确认是否为会员(会员输入y,非会员输入n)')
print('***************************')
print('您选择的是{}号奶茶,数量为{}杯'.format(milktea_name,milktea_number))
print('***************************')
if milktea_name==1:
toltal=3*milktea_number
elif milktea_name==2:
toltal=5*milktea_number
elif milktea_name==3:
toltal=5*milktea_number
elif milktea_name==4:
toltal=7*milktea_number
elif milktea_name==5:
toltal=7*milktea_number
if Vip=='y':
print('您是本店会员,可以享受会员价')
a = 0.9* toltal
print('请您支付{}元'.format(a))
elif Vip=='n':
print('不好意思哦,您目前还不是我们的会员,\n本次无法享受会员价喽,永远爱你么么哒!')
print('请您支付{}元'.format(toltal))
else:
print('我还是个小宝宝,您的输入我看不懂,您拿着小票问问小象君吧!')
print('****************************************')
print('做一枚有态度、有思想的奶茶馆(傲娇脸)!\n\t祝您今日购物愉快!\n\t\t诚挚欢迎您再次光临!')
print('****************************************') |
class MyClass:
def __init__(self):
self.public_attribute = "This is a public attribute"
self.__private_attribute = "This is a private attribute"
def public_method(self):
print("This is a public method")
def __private_method(self):
print("This is a private method")
my_object = MyClass()
# We can access the public attribute and method from outside the class
print(my_object.public_attribute)
my_object.public_method()
# But we cannot access the private attribute or method
try:
print(my_object.__private_attribute)
except Exception as e:
print(e)
try:
my_object.__private_method()
except Exception as e:
print(e)
|
'''
NAME
reverse-complement.py
VERSION
1.0
AUTHOR
Hely Salgado, Axel Zagal, Azaid Ordaz
DESCRIPTION
Make the reverse complement of DNA sequence
CATEGORY
Genomic Sequence
USAGE
% python reverse-complement.py -i
example
% python reverse-complement -i
'''
import argparse
# program arguments
parser = argparse.ArgumentParser(description="Make the reverse complement of DNA sequence")
parser.add_argument(
"-i", "--input",
help="genomic sequence file in raw or fastA format",
required=True)
args = vars(parser.parse_args())
# Getting the dna sequence from the file
with open(args['input'],'r') as readFile:
sequence = "";
for line in readFile:
# Ignore comments or FastA head line
if line.startswith('#') or line.startswith('>'):
continue
else:
sequence += line.strip()
sequence = sequence.upper()
# Dictionary containing the complement equivalents
sequence = sequence[::-1].translate(str.maketrans({'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'}))
print ('{}'.format(sequence))
print("Hello World")
|
"""
一个回合制游戏,游戏中有两个角色,每个角色都有HP、Power、Armor三种基本属性,主角属性有初始值
HP代表血量(初始值为100),Power代表攻击力(初始值为10),Armor代表护甲(初始值为10)
定义一个fight方法
final_HP = HP - enemy_Power + My_Armor
enemy_final_HP = enemy_HP - my_Power + enemy_Armor
血量变为0的一方获胜
"""
import random
class game_characters:
pro_hp: int
pro_power: int
pro_armor: int
enemy_hp: int
enemy_power: int
enemy_armor: int
def __init__(self):
self.pro_hp = random.randint(100, 120)
self.pro_power = random.randint(10, 15)
self.pro_armor = random.randint(0, 5)
self.enemy_hp = random.randint(120, 150)
self.enemy_power = random.randint(5, 10)
self.enemy_armor = random.randint(0, 10)
def fight(self):
while self.pro_hp >= 0 and self.enemy_hp >= 0:
self.pro_hp = self.pro_hp - self.enemy_power + self.pro_armor
self.enemy_hp = self.enemy_hp - self.pro_power + self.enemy_armor
print(f"主角当前剩余血量:{self.pro_hp}")
print(f"敌人当前剩余血量:{self.enemy_hp}")
if self.pro_hp > self.enemy_hp:
print("Win")
else:
print("Lose")
class protagonist(game_characters):
def introduce(self):
print(f"血量:{self.pro_hp} 攻击力:{self.pro_power} 护甲:{self.pro_armor}")
def protagonist_back(self):
pass
class enemy(game_characters):
def introduce(self):
print(f"血量:{self.enemy_hp} 攻击力:{self.enemy_power} 护甲:{self.enemy_armor}")
def enemy_back(self):
pass
|
from random import randint
catalog = {1: 'Rock', 2: 'Paper', 3: 'Scissors'}
player, comp = 0, 0
print("Game - \"Rock / Paper / Scissors\"")
while player < 3 and comp < 3:
print('Enter 1 for Rock, 2 for Paper, 3 for Scissors')
com_choice = randint(1, 3)
try:
pl_choice = int(input('Your turn: '))
result = pl_choice - com_choice
print(f"{catalog[pl_choice]} vs {catalog[com_choice]}")
except:
print('Wrong input')
continue
if result == 0:
print(f'Draw \n {player}:{comp}\n')
elif result == 1 or result == -2:
player += 1
print(f'User wins this round \n {player}:{comp}\n')
else:
comp += 1
print(f'Computer wins this round \n {player}:{comp}\n')
if player > comp:
print('User wins!')
else:
print('Computer wins!')
|
from random import randint
class Phone:
def __init__(self):
self.number = randint(10000000000, 99999999999)
class Samsung(Phone):
brand = "Samsung"
os = "Android"
class Apple(Phone):
brand = "Apple"
os = "IOS"
new1 = Samsung()
print(new1.brand, new1.os, new1.number)
|
first = int(input("Start: "))
second = int(input("End: "))
total = 0
for i in range(first, second + 1):
if i % 13 == 0 or i % 4 > 0 and 99 < i < 1000:
continue
elif 999 < i < 10000 and i % 7000 == 0:
break
else:
total += i
print(f"Sum: {total}")
|
a = float(input("Для уравнения вида ax^2+bx+c=0\nУкажите коэфициент а "))
b = float(input("Укажите коэфициент b "))
c = float(input("Укажите коэфициент c "))
if a == 0:
if b != 0:
x = -c / b;
print("x = ", x)
else:
c == 0;
print("c = 0")
elif b == 0:
if c > 0:
print("Корней нет")
else :
x1 = (-c / a)**0.5;
x2 = -((-c / a)**0.5);
print("x1 = ", x1, "\nx2 = ", x2)
elif (c == 0):
x1 = 0;
x2 = -b / a;
print("x1 = ", x1, "\nx2 = ", x2)
else:
D = (pow(b, 2)) - (4 * a * c);
if (D < 0):
print("Действительных корней нет")
elif (D == 0):
x = -b / 2 * a;
print("x = ", x)
else:
x1 = (-b - (D**0.5)) / (2 * a);
x2 = (-b + (D**0.5)) / (2 * a);
print("x1 = ", x1, "\nx2 = ", x2) |
name=input("Please enter your name: \t")
if(name=="Anu"):
print("Hi I stay in cluster Y")
elif(name=="Mahi"):
print("Hi I stay in cluster U")
else:
print("I dont know where I stay")
|
# name="Aarav"
# print("welcome",name)
# print("i love coding")
num1=13
num2=4
print("numbers",num1,num2)
print("addition",num1+num2)
print("subtraction",num1-num2)
print("multiplication",num1*num2)
print("division",num1/num2)
print("quotient",num1//num2)
print("remainder",num1%num2)
print("repeated multiplication",num1**2) |
#!/usr/bin/env python3
"""
Module of helper functions for dealing with patterns in entity regex.
"""
import re
from itertools import chain
import exrex
def make_clean_input(pattern):
"""
Enforces that entities or words have parentheses around them and have trailing spaces
>>> make_clean_input("@num{3}")
'(@(num ) ){3}'
>>> make_clean_input("num{3}")
'(num ){3}'
Entities can sometimes have underscores
>>> make_clean_input("@NUM_PLURAL{3}")
'(@(NUM_PLURAL ) ){3}'
Entities or words should have at least one character
>>> make_clean_input("a{10}")
'(a ){10}'
"""
entity_pattern = re.compile(r"(@[a-zA-Z\_][\w]*)")
pattern = re.sub(
entity_pattern, lambda match: "({} )".format(match.group()), pattern
)
word_pattern = re.compile(r"([a-zA-Z\_][\w]*)")
pattern = re.sub(word_pattern, lambda match: "({} )".format(match.group()), pattern)
return pattern
def strip_extra_spaces(input_string):
"""
Removes extra spaces from input string
>>> strip_extra_spaces("I have no cats")
'I have no cats'
"""
while " " in input_string:
input_string = input_string.replace(" ", " ")
return input_string
def expand_this(pattern):
"""
Cleans then expands any and all patterns
>>> expand_this("@num{1,2}")
[['@num'], ['@num', '@num']]
>>> expand_this("spam{3}")
[['spam', 'spam', 'spam']]
>>> expand_this("(a|f) b c")
[['a', 'b', 'c'], ['f', 'b', 'c']]
>>> expand_this("a{10}")
[['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a']]
>>> expand_this("@banana_2{1,2}")
[['@banana_2'], ['@banana_2', '@banana_2']]
"""
pattern = make_clean_input(pattern)
patterns = [strip_extra_spaces(_).split() for _ in exrex.generate(pattern)]
return patterns
def expand_these(patterns):
"""
Cleans then expands any and all patterns
>>> expand_these("@num{1,2}")
[['@num'], ['@num', '@num']]
>>> expand_these(["Lovely spam{3}", "wonderful spam{4}"])
[['Lovely', 'spam', 'spam', 'spam'], ['wonderful', 'spam', 'spam', 'spam', 'spam']]
Now for things without regex - make sure we don't do anything to patterns like these
>>> expand_these([[['a', 'f'], 'b', 'c'], ['b', 'c', 'f']])
[[['a', 'f'], 'b', 'c'], ['b', 'c', 'f']]
>>> expand_these(['a test'.split()])
[['a', 'test']]
>>> expand_these([["@num", "@letter"]])
[['@num', '@letter']]
This handles strings by themselves too now
>>> expand_these('a test')
[['a', 'test']]
Handle repeated patterns
>>> expand_these(["@num{1,2}", "@letter? @num{1,2}"])
[['@num'], ['@num', '@num'], ['@letter', '@num'], ['@letter', '@num', '@num']]
"""
if isinstance(patterns, str):
output = expand_this(patterns)
else:
output = list(
chain.from_iterable(
[expand_this(_) if isinstance(_, str) else [_] for _ in patterns]
)
)
unique_patterns = []
for pattern in output:
if pattern not in unique_patterns:
unique_patterns.append(pattern)
return unique_patterns
if __name__ == "__main__":
import doctest
doctest.testmod(raise_on_error=False, verbose=True)
|
#!/usr/bin/env python3
"""
Freezes objects into immutable objects so they can hash
Also contains wrapper for freezing arguments to lru_cache and unfreeze routine
"""
import collections
import functools
from immutables import Map
def freeze_map(obj):
"""
freezes components of all mappables
"""
return Map({key: freeze(value) for key, value in obj.items()})
def freeze_iter(obj):
"""
freezes components of all iterables
"""
return (frozenset if isinstance(obj, set) else tuple)(freeze(i) for i in obj)
def raise_freezing_error(obj):
"""
Custom error message with type of object
"""
msg = "Unsupported type: %r" % type(obj).__name__
raise TypeError(msg)
def freeze(obj):
"""Convert data structure into an immutable data structure.
>>> list_test = [1, 2, 3]
>>> freeze(list_test)
(1, 2, 3)
>>> set_test = {1, 2, 3}
>>> freeze(set_test)
frozenset({1, 2, 3})
"""
if isinstance(obj, collections.abc.Hashable):
pass
elif isinstance(obj, collections.abc.Mapping):
obj = freeze_map(obj)
elif isinstance(obj, collections.abc.Iterable):
obj = freeze_iter(obj)
else:
raise_freezing_error(obj)
return obj
def unfreeze_map(obj):
"""
Unfreezes all elements of mappables
"""
return {key: unfreeze(value) for key, value in obj.items()}
def unfreeze_iter(obj):
"""
Unfreezes all elements of iterables
"""
return list(unfreeze(i) for i in obj)
def unfreeze_set(obj):
"""
Unfreezes all elements of frozensets
"""
return set(unfreeze(i) for i in obj)
def unfreeze(obj):
"""Convert all map objects to dicts.
>>> map_object = Map({
... "key": Map({"nested_key": "nested_value"})
... })
>>> unfreeze(map_object)
{'key': {'nested_key': 'nested_value'}}
"""
if isinstance(obj, (str, int, float, bool)):
pass
elif isinstance(obj, frozenset):
obj = unfreeze_set(obj)
elif isinstance(obj, collections.abc.Mapping):
obj = unfreeze_map(obj)
elif isinstance(obj, collections.abc.Iterable):
obj = unfreeze_iter(obj)
else:
raise_freezing_error(obj)
return obj
def freezeargs(func):
"""
Transform all mutable objects into immutables using freeze
For the sake of lru_cache
"""
@functools.wraps(func)
def wrapped(*args, **kwargs):
args = tuple(freeze(arg) for arg in args)
kwargs = {k: freeze(v) for k, v in kwargs.items()}
return func(*args, **kwargs)
return wrapped
|
from collections import deque
import numpy as np
'''
OBJECTIVE LEGEND:
0 = looking for food
1 = count the available space
2 = check if we can see our tail (unused)
'''
#breadth first search floodfill to find a goal
def bfs(board, start, objective, tail):
count = 1
queue = deque()
queue.append(start)
closed = np.copy(board)
#priority queue for bfs loop
while queue:
count = count + 1
current = queue.popleft()
closed[current[0]][current[1]] = -1
#if found food
if board[current[0]][current[1]] == 2 and objective == 0:
return current
#if found tail
if current[0] == tail[0] and current[1] == tail[1] and objective == 2:
return True
#move through board for algorithm
for x in range(0, 4):
# left
if x is 0:
if current[0] == 0:
continue
neighbour = (current[0] - 1, current[1])
# up
if x is 1:
if current[1] == 0:
continue
neighbour = (current[0], current[1] - 1)
# right
if x is 2:
if current[0] == board.shape[0] - 1:
continue
neighbour = (current[0] + 1, current[1])
# down
if x is 3:
if current[1] == board.shape[1] - 1:
continue
neighbour = (current[0], current[1] + 1)
#if not wall
if closed[neighbour[0]][neighbour[1]] != -1:
queue.append(neighbour)
closed[neighbour[0]][neighbour[1]] = -1
#return count of available space
if objective == 1:
return count
return False
#tester main
if __name__ == '__main__':
board = np.zeros((19, 19), dtype=int)
board[10][10] = 2
test = bfs(board, (3, 3))
#print(test)
|
#! /user/bin/python
# -*- coding: iso-8859-15
import os
num = int(input("Positivo y Negativo: "))
if num > 0:
print("El número introducido es positivo")
elif num < 0:
print("El número introducido es negativo")
else:
print("El número introducio es 0") |
enum=int(input())
if enum>0:
print("positive")
elif enum<0:
print("negative")
elif enum==0:
print("zero")
|
for _ in range(int(input())):
n = int(input())
temp = (n - 1) // 26
temp2 = n % 26
ans = 2**temp
if n == 0: print(1,0,0)
elif temp2 > 0 and temp2 < 3: print(ans,0,0)
elif temp2 > 2 and temp2 < 11: print(0,ans,0)
else: print(0,0,ans) |
'''
Automate the Boring stuff
First program in Python
- prints to screen
- prints user inputs to screen
- prints user inputs through string calls
'''
print('Hello world!') # Prints to screen
print('What is your name?') # ask for their name
myName = input() # Takes user input
print('It is good to meet you, ' + myName) # prints data type to screen
# nested functions in print call reduces redundant variable use
# Note len returns an integer, to print an integer we use %d
print('The length of your name is: %d' % len(myName))
print('What is your age?') # ask for their age
myAge = input() # Takes an integer input stores as string
print('You will be ' + str(int(myAge) + 1) + ' in a year.') # Typecasting to add value to the integer
mycolour = input("What is your favorite colour? ")
# printing multiple inputs in one sentence
print('Your name is %s, your age is %d, your favorite color is %s' % (myName, int(myAge), mycolour))
|
# Sorting and creating set items
# (i.e. removing redundant or repeated items from a list)
List1 = [10,9,9,9,9,9,8,7,6,5,5,4,4,3,2,1,1,1,1,1,1]
print("Your list is "), print(List1)
print("Your list sorted is: ")
List1.sort()
print(List1)
List3 = list(set(List1))
List3.sort()
print("Your list as a set is: "), print(List3)
|
import csv
import numpy as np
from sklearn.svm import SVR
import matplotlib.pyplot as plt
dates = []
prices = []
def data(filename):
with open(filename, 'r') as csvfile:
csvFileReader = csv.reader(csvfile)
# to skip column names
next(csvFileReader)
for row in csvFileReader:
dates.append(int(row[0].split('/')[0]))
prices.append(float(row[1]))
return
def predict(dates, prices):
# converting to matrix of n X 1
dates = np.reshape(dates,(len(dates), 1))
# defining the support vector regression models
lin = SVR(kernel= 'linear', C= 1e3)
poly = SVR(kernel= 'poly', C= 1e3, degree= 2)
rbf = SVR(kernel= 'rbf', C= 1e3, gamma= 0.1)
# fitting the data points in the models
rbf.fit(dates, prices)
lin.fit(dates, prices)
poly.fit(dates, prices)
# plotting the initial datapoints
plt.scatter(dates, prices, color= 'black', label= 'Data')
# plotting the line made by the RBF kernel
plt.plot(dates, rbf.predict(dates), color= 'red', label= 'RBF model')
# plotting the line made by linear kernel
plt.plot(dates,lin.predict(dates), color= 'green', label= 'Linear model')
# plotting the line made by polynomial kernel
plt.plot(dates,poly.predict(dates), color= 'blue', label= 'Polynomial model')
plt.xlabel('Date')
plt.ylabel('Price')
plt.title('Support Vector Regression')
plt.legend()
plt.show()
return
# calling get method and passing csv file as an argument
data('pricedata.csv')
# calling predict method
predict(dates, prices)
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def getMinimumDifference(self, root: TreeNode) -> int:
res = []
self.dfs(root, res)
smallest_difference = float('inf')
for i in range(len(res) - 1):
smallest_difference = min(
abs(res[i] - res[i+1]), smallest_difference)
return smallest_difference
def dfs(self, node, res):
if node:
self.dfs(node.left, res)
res.append(node.val)
self.dfs(node.right, res)
|
import unittest
# Using cyclic sort - O(n) time ; O(1) space
def find_repeat(nums):
# Find a number that appears more than once
for i in range(len(nums)):
while nums[i] != i + 1:
j = nums[i] - 1
if nums[i] == nums[j]:
return nums[i]
nums[i], nums[j] = nums[j], nums[i]
return -1
# Using modified binary search:
# Tests
class Test(unittest.TestCase):
def test_just_the_repeated_number(self):
actual = find_repeat([1, 1])
expected = 1
self.assertEqual(actual, expected)
def test_short_list(self):
actual = find_repeat([1, 2, 3, 2])
expected = 2
self.assertEqual(actual, expected)
def test_medium_list(self):
actual = find_repeat([1, 2, 5, 5, 5, 5])
expected = 5
self.assertEqual(actual, expected)
def test_long_list(self):
actual = find_repeat([4, 1, 4, 8, 3, 2, 7, 6, 5])
expected = 4
self.assertEqual(actual, expected)
unittest.main(verbosity=2)
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
if not root:
return True
left = self.calcDepth(root.left)
right = self.calcDepth(root.right)
if left == -1 or right == -1:
return False
return abs(left - right) <= 1
def calcDepth(self, root):
if (not root):
return 0
left = self.calcDepth(root.left)
right = self.calcDepth(root.right)
if left == -1 or right == -1:
return -1
if abs(left - right) <= 1:
return 1 + max(left, right)
return -1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.