lista for
def lista_for(lista):
soma = 0
for el in lista:
soma += el
All generations.
def lista_for(lista):
soma = 0
for el in lista:
soma += el
def sumareltipo(lista):
# creo un dictionary vacio
dic = {}
# itero la lista
for i in lista:
# si ya existe la key en el dic le sumo 1
if i in dic:
dic[i] += 1
# si no existe la key le asigno 1
else:
dic[i] = 1
return dic
sumareltipo(["auto", "moto", "auto"])
def atender(persona):
if(persona[1] >= 18 and persona[2] > 150):
return persona[0]
return None
def filtrar(pacientes):
atendidas = Queue()
enEspera = Queue()
while(len(pacientes)>0):
persona = pacientes.pop()
if(atender(persona)):
atendidas.push(persona)
else:
enEspera.push(persona)
return {'Atendidas':atendidas, 'EnEspera':enEspera}
def ListaRepetidos(lista):
lista_respuesta = []
lista_auxiliar = []
if type(lista) != list:
return None
else:
lista_auxiliar = set(lista)
for elemento in lista_auxiliar:
cont = 0
for i in lista:
if i == elemento:
cont = cont + 1
lista_respuesta.append((elemento,cont))
return lista_respuesta
SELECT product, avg(amount) as promedio, stddev(amount) as desviacion, avg(amount) + 3 * stddev(amount) as umbral_superior, avg(amount) - 3 * stddev(amount) as umbral_inferior
FROM sales
GROUP BY product
SELECT C.ID, COUNT(*) AS 'NUMBER OF BRANCHES'
FROM Clientes C, Compras P
WHERE C.ID = P.CID
GROUP BY C.ID
HAVING COUNT(*) >1;
def ListaRepetidos(lista):
def dec2bin(num):
if (isinstance(num, int) or isinstance(num, float)) and num >= 0 :
return int(bin(num).replace("0b", ""))
else:
return "nulo"
dec2bin(0) # 0
dec2bin(1) # 1
dec2bin(2) # 10
dec2bin(3) # 11
dec2bin(4) # 100
dec2bin(5) # 101
dec2bin(6) # 110
dec2bin(11) # 1011
dec2bin(100) # 1100100
dec2bin(0.1) # nulo
dec2bin(-1) # nulo
dec2bin("a") # nulo
SELECT product, (sale_price-buy_price) as ganancia FROM products;
def burbujeo(lista):
for numero in range(len(lista)-1,0,-1):
for i in range(numero):
if lista[i]>lista[i+1]:
temp = lista[i]
lista[i] = lista[i+1]
lista[i+1] = temp
lista = [19,2,31,45,6,11,121,27]
burbujeo(lista)
print(lista)
def frac(n,d):
return bin(n)[2:] + "/" + bin(d)[2:]
frac(1,2)
def balanced(sentence):
pass
sentence = "[{()}]"
balanced(sentence)
def cuentaNodos(Lista):
if Lista.getCabecera() is None:
return 0
else:
return 1 + cuentaNodos(Lista.getCabecera().getSiguiente())
def max_hydroelectric_generation_year_europe(data: list):
"""
Esta función debe informar el año de mayor generación de energía hídrica (Hydro_Generation_TWh)
para la entidad 'Europe' retornando ese valor en un dato de tipo entero.
Parameters:
data: A list with electricity generation data
Returns:
A integer
"""
# YOUR CODE HERE
raise NotImplementedError()
SELECT branch_name, SUM(net_profit) FROM Sales WHERE branch_name="Buenos Aires"
def info(df):
return df.info()
info(df)
def selectColombiaMexico(df, column):
return df.loc[:,[column]].query('Fuente == "Colombia" or Fuente == "México"').shape
selectColombiaMexico(df, "Fuente")
select year, shipping_mode, sum(quantity) as total_year, (sum(quantity) / sum(sum(quantity)) over (partition by year)) as percent
from sales
group by year, shipping_mode
order by year, total_year desc;
with total_year as (
select year, sum(quantity) as total_year
from sales
group by year
)
select year, shipping_mode, quantity, (quantity / total_year) as percent
from sales left join total_year using (year)
order by year, quantity desc;
def list_repeats(lista):
if type(lista) != list:
return None
else:
repetidos = [(valor, lista.count(valor)) for valor in lista if lista.count(valor) > 1]
sin_repetir = list(dict.fromkeys(repetidos))
return sin_repetir
def arange(a, b):
l = []
for i in range(a, b):
l.append(i)
return l
arange(1, 10)
SELECT month(ventas.fecha) as mes, (SELECT SUM(ventas.precio*ventas.cantidad) FROM ventas WHERE YEAR(ventas.fecha) = 2020)-(SELECT SUM(compras.precio*compras.cantidad) FROM compras WHERE YEAR(compras.fecha) = 2020)-(SELECT SUM(gastos.monto) FROM gastos WHERE YEAR(gastos.fecha) = 2020) as ingresos FROM ventas WHERE YEAR(ventas.fecha) = 2020 GROUP BY mes;
SELECT SUM(profit) FROM orders WHERE branch="miami";
SELECT SUM(profit) FROM orders WHERE branch="miami" and month="jan";
def DividirDosNumeros(dividendo, divisor):
return dividendo // divisor, dividendo % divisor
DividirDosNumeros(10, 3)
SELECT COUNT(*) FROM clientes WHERE year(fecha_compra) = 2019;
SELECT COUNT(*) FROM clientes WHERE year(fecha_compra) = 2019 AND sucursal_id > 1;
def stringmaslargo(str):
words = str.split()
word_length = []
for n in words:
word_length.append((len(n), n))
word_length.sort()
return word_length[-1][1]
print(stringmaslargo('siempre me gustaron los nombres de niña'))
def decimal_a_binario(decimal):
if not isinstance(decimal, int) or decimal < 0:
return None
binario = ''
while decimal // 2 != 0:
binario = str(decimal % 2) + binario
decimal = decimal // 2
return str(decimal) + binario
def convert_to_bin(decimal):
binario = ''
if decimal >= 0:
while decimal // 2 != 0:
binario = str(decimal % 2) + binario
decimal = decimal // 2
return str(decimal) + binario
else:
return 'Error'
print('Binario de 10 es', convert_to_bin(10))
print('Binario de 15 es', convert_to_bin(15))
print('Binario de 16 es', convert_to_bin(16))
print('Binario de 19 es', convert_to_bin(19))
print('Binario de -1 es', convert_to_bin(-1))
print('Binario de "hola" es', convert_to_bin("hola"))
SELECT (COUNT(DISTINCT customer_id)/COUNT(customer_id))*100 FROM purchases WHERE DATE_FORMAT(purchase_date, '%Y') = '2019';
def binario(n):
if n>=0 and type(n)==int:
return bin(n)[2:]
else:
return None
SELECT Sucursal,Precio,Cantidad,Precio*Cantidad as Ventas FROM Ventas ORDER BY Ventas DESC LIMIT 1;
def arange(n):
return np.arange(n)
arange(10)
def cant_nodos(self):
cont = 0
actual = self.get_cabecera()
while actual != None:
cont += 1
actual = actual.get_proximo()
return cont
SELECT branch_name, SUM(net_profit) FROM branches WHERE year = 2019 GROUP BY branch_name;
def ordenar_diccionario(diccionario, clave, descendente=True):
if type(diccionario) is not dict or clave not in diccionario.keys():
return None
dicc_o = diccionario[clave]
dicc_o.sort()
diccionario_ordenado = {}
if descendente:
dicc_o.reverse()
for k in diccionario.keys():
diccionario_ordenado[k] = []
for i in range(len(dicc_o)):
for j in range(len(diccionario[k])):
if dicc_o[i] == diccionario[k][j]:
diccionario_ordenado[k].append(diccionario[k][j])
break
return diccionario_ordenado
dicc = {'clave1':['c','a','b'],
'clave2':
def ListaRepetidos(lista):
if not isinstance(lista, list):
return None
return [(elem, lista.count(elem)) for elem in lista if lista.count(elem) > 1]
def number_columns(df):
df.drop(['Code', 'Entity'], axis=1, inplace =True)
return df.shape[1]
number_columns(df)
def correct_parentheses(string):
# your code here
return True # or False
def ListaRepetidos(lista):
return
def well_bracketed(string):
count_parenthesis = 0
count_brackets = 0
count_braces = 0
for char in string:
if char == "(":
count_parenthesis += 1
elif char == ")":
count_parenthesis -= 1
elif char == "[":
count_brackets += 1
elif char == "]":
count_brackets -= 1
elif char == "{":
count_braces += 1
elif char == "}":
count_braces -= 1
if (count_parenthesis == 0 and count_brackets == 0 and count_braces == 0):
return True
else:
return False
def is_balanced(txt):
parentheses = 0
brackets = 0
braces = 0
for char in txt:
if char == "(":
parentheses += 1
elif char == ")":
parentheses -= 1
elif char == "[":
brackets += 1
elif char == "]":
brackets -= 1
elif char == "{":
braces += 1
elif char == "}":
braces -= 1
if parentheses == 0 and brackets == 0 and braces == 0:
return True
else:
return False
is_balanced("{ [ ] ( ) }")
# lista = [1,4,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,7,8,9,10,7,7,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9]
# lista = [1,4,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,7,8,9,10,7,7,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9]
def listaPrimos(lista):
if type(lista) != list:
return None
listaSinRepetir = []
for elemento in lista:
import numpy as np
def my_array(n=10):
return np.arange(n)
def number_of_records_in_year(df):
return df.groupby('Year')['Year'].count()
def get_total_consumption(df, entity, year):
return round(df[(df['Entity'] == entity) & (df['Year'] == year)]['Oil Consumption'].sum(), 2)
get_total_consumption(data_frames[0], 'World', 2019)
def count(Lista):
aux = Lista.getCabecera()
cont = 0
while aux != None:
cont += 1
aux = aux.getSiguiente()
return cont
import pandas as pd
import numpy as np
def maximo_energia_hidrica():
df = pd.read_csv("Fuentes_Consumo_Energia.csv", sep=',')
df['Hydro_Generation_TWh'] = df['Hydro_Generation_TWh'].replace(',','.', regex=True).astype(float)
df_europe = df[(df.Entity == 'Europe')]
df_europe_hydro = df_europe[['Year', 'Hydro_Generation_TWh']]
df_europe_hydro_max = df_europe_hydro[df_europe_hydro['Hydro_Generation_TWh'] == df_europe_hydro['Hydro_Generation_TWh'].max()]
return df_europe_hydro_max.iloc[0]['Year']
SELECT c.sucursal, SUM(c.ganancia_neta) AS "Total 2019"
FROM ventas c
WHERE c.fecha_venta BETWEEN '2019-01-01' AND '2019-12-31'
GROUP BY c.sucursal;
def sumareltipo(array):
result = {}
for tipo in array:
if tipo in result:
result[tipo] += 1
else:
result[tipo] = 1
return result
sumareltipo(['auto', 'moto', 'auto'])
def perimetro_cuadrado(lado):
return lado * 4
def ListaEnteros(inicio, tamanio):
pass
ListaEnteros(10, 5)
SELECT ROUND(SUM(CASE WHEN COUNT(*) >= 2 THEN 1 ELSE 0 END)/ COUNT(DISTINCT customer_id) * 100, 2)
FROM purchases
WHERE YEAR(purchase_date) = 2019;
def linspace(a, b, n=100):
return np.linspace(a, b, n)
linspace(0, 9, 100)
SELECT ROUND(COUNT(*)/(SELECT COUNT(*) FROM cliente WHERE cliente.id_cliente IN (SELECT id_cliente FROM compra WHERE YEAR(fecha_compra)=2019))*100,2) AS 'Por_dos_sucursales' FROM (SELECT id_cliente FROM compra WHERE YEAR(fecha_compra)=2019 GROUP BY id_cliente HAVING COUNT(DISTINCT id_sucursal)>=2)
def cantidadElementos(lista):
contador = 0
aux = lista
while aux != None:
aux = aux.getSiguiente()
contador += 1
return contador
SELECT ((SUM(CASE WHEN canal='online' THEN 1 ELSE 0 END))/(SELECT COUNT(*) FROM customers))*100 as online FROM customers;
def ordenar_dicc(diccionario, clave, descendente=True):
if type(diccionario) != dict:
return None
if clave not in diccionario.keys():
return None
if (type(descendente) == bool):
if (descendente):
return dict(sorted(diccionario.items()))
else:
return dict(sorted(diccionario.items(), reverse=True))
return None
ordenar_dicc({'clave1':['c','a','b'],
'clave2':[1,2,3],
'clave3':['hola','hola','hola'],
'clave4':[],
'clave5':['a','b','c']},
'clave1')
def is_balanced(string):
# Complete the function
return # True or False
string = "{[()]}"
is_balanced(string)
SELECT COUNT(cliente) AS clientes_repetidos
FROM (
SELECT cliente, COUNT(sucursal) AS sucursales_cliente
FROM compra
GROUP BY cliente
HAVING COUNT(sucursal) > 1
) AS T
# function: suma todos impares
def suma_impares(array):
suma_impares = 0
for number in array:
if number % 2 != 0:
suma_impares += number
return suma_impares
print(suma_impares([1,5,2,9,6,4]))
def get_count_year(data):
return data['Year'].count()
get_count_year(df)
SELECT product_id, (sale_price-buy_price) AS ganancia FROM sales WHERE year(sale_date)=2019;
def DividirDosNumeros(dividendo, divisor):
return dividendo // divisor, dividendo % divisor
def ordenar(diccionario, clave, descendente=True):
if type(diccionario) != type(dict) or clave not in diccionario:
return None
else:
lista = diccionario.get(clave)
claves = diccionario.keys()
lista_ordenada = sorted(lista, reverse=descendente)
dicc_ordenado = {k:[] for k in claves}
for i in range(0, len(lista)):
for k in diccionario:
dicc_ordenado[k].append(diccionario[k][i])
for i in range(0, len(lista_ordenada)):
for k in dicc_ordenado:
for j in range(0, len(dicc_ordenado[k])):
if dicc_ordenado[k][j] == lista_ordenada[i]:
dicc_ordenado[k
def Ret_Pregunta06(n1,n2,n3):
a = len(n1[0])
b = len(n2)
c = len(n3[0])
if a == b and b == c:
return True
else:
return False
def convert(a, b):
return a / b
convert(1, 2)
def to_bin(num):
if (not isinstance(num, int)) or (num < 0):
return None
if num == 0:
return '0'
return to_bin(num // 2) + str(num % 2)
def lista_repetidos(lista):
if not isinstance(lista,list):
return None
lista_final = []
for num in lista:
if num not in lista_final:
lista_final.append(num)
lista_resultado = []
for num in lista_final:
count = 0
for num2 in lista:
if num2 == num:
count +=1
lista_resultado.append((num,count))
return lista_resultado
SELECT sum(case when num_sucursales=1 then 1 else 0 end)/count(*)*100 as porcentaje from (
select count(distinct sucursal) as num_sucursales
from compra c
join sucursal s on c.id_sucursal=s.id
join clientes cl on c.id_cliente=cl.id
where year(c.fecha)=2020
group by c.id_cliente
) q;
import pandas as pd
def retornar_cantidad_registros_paises(url):
# tu código va acá
return (numero_registros_colombia, numero_registros_mexico)
retornar_cantidad_registros_paises('https://raw.githubusercontent.com/luisgomezes/bancolombia_capacitaciones_datascience/master/02_pandas_fundamentals/Fuentes_Consumo_Energia.csv')
def dividirDosNumeros(dividendo,divisor):
cociente = dividendo / divisor
modulo = dividendo % divisor
return cociente, modulo
def get_country_row_count():
df = pd.read_csv("Fuentes_Consumo_Energia.csv")
df_filter = df[(df["Entidad"] == "Colombia") | (df["Entidad"] == "México")]
return df_filter.shape[0]
SELECT * FROM customers WHERE age=24 AND name='mohammed';
def sumar_costos(precio):
#código
SELECT (COUNT(DISTINCT(cliente_id)) * 100) / (SELECT COUNT(DISTINCT(cliente_id)) FROM compra) AS 'Porcentaje que hizo compras en al menos 2 sucursales' FROM compra
GROUP BY cliente_id
HAVING COUNT(DISTINCT(sucursal_id)) > 1;
dicc['clave3'] = [1,5,9]
def ordena_diccionario(diccionario,clave,descendente=True):
if type(diccionario) is dict and clave in diccionario.keys():
for i in range(len(diccionario[clave])):
if descendente == True:
for j in range(len(diccionario[clave])-1):
if diccionario[clave][j] < diccionario[clave][j+1]:
for k in diccionario.keys():
aux = diccionario[k][j]
diccionario[k][j] = diccionario[k][j+1]
diccionario[k][j+1] = aux
else:
for j in range(len(diccionario[clave])-1):
if diccionario[clave][j] > diccionario[clave][j+1]:
for k in dicc
dicc = {'clave1':['c','a','b'],
'clave2':['z','y','x']}
ordenar_dict(dicc, 'clave2') # Devuelve {'clave1':['b','a','c'],
# 'clave2':['x','y','z']}
def ordenar_dict(diccionario, clave, descendente = True):
if not(isinstance(diccionario, dict)):
return None
if not(clave in diccionario.keys()):
return None
return {clave : sorted(diccionario[clave], reverse = descendente) for clave in diccionario.keys()}
def Exponente(numero, exponente):
return numero**exponente
SELECT sum(net_profit) FROM branches WHERE year=2019;
SELECT round(sum(distinct_stores)/count(total_stores)*100,2) FROM
(SELECT customer_id, count(distinct store_id) as distinct_stores, count(store_id) as total_stores FROM orders GROUP BY customer_id) AS aux;
def binario(num):
if num < 0:
return None
elif type(num) == float:
return None
else:
return bin(num)
binario(3)
SELECT branch_name, SUM(net_profit) AS total_profit
FROM profits
WHERE year = 2019
GROUP BY branch_name
ORDER BY total_profit DESC
LIMIT 1;
def DividirDosNumeros(dividendo, divisor):
return dividendo // divisor, dividendo % divisor
def can_multiply(a, b, c):
return a.shape[1] == b.shape[0] and b.shape[1] == c.shape[0]
def colombia_mexico_DF(path_to_file):
df = pd.read_csv(path_to_file)
df['Entity']
return 'TODO'
def ordenar_diccionario(diccionario, clave = '', descendente = True):
if type(diccionario) != dict or clave not in diccionario:
return None
if descendente:
return sorted(diccionario.items(), key=lambda x: x[1][clave], reverse = True)
else:
return sorted(diccionario.items(), key=lambda x: x[1][clave])
ordenar_diccionario({'a': {'edad': 19, 'nombre': 'Juan'}, 'b': {'edad': 25, 'nombre': 'Jorge'}}, 'nombre')
def estaOffline(usuarios, nombre):
for user in usuarios:
if user["nombre"] == nombre:
if user["online"] == True:
return False
else:
return True
def ordenamiento(numeros):
for i in range(len(numeros)):
for j in range(len(numeros)):
if numeros[i] < numeros[j]:
temp = numeros[j]
numeros[j] = numeros[i]
numeros[i] = temp
return numeros
numeros = [3,5,1,4,8,6,2]
ordenamiento(numeros)
def balance(s):
if len(s) % 2 != 0:
return False
opening = set('([{')
matches = set([ ('(',')'), ('[', ']'), ('{','}') ])
stack = []
for paren in s:
if paren in opening:
stack.append(paren)
else:
if len(stack) == 0:
return False
last_open = stack.pop()
if (last_open, paren) not in matches:
return False
return len(stack) == 0
print(balance("([)]" ))
def fun(df):
df_colombia = df.loc[df['Country'] == 'Colombia']
df_mexico = df.loc[df['Country'] == 'Mexico']
num_users_colombia = df_colombia['User'].count()
num_users_mexico = df_mexico['User'].count()
return (num_users_colombia, num_users_mexico)
SELECT sucursal, SUM(ventas)
FROM ventas
GROUP BY sucursal
ORDER BY ventas DESC
LIMIT 1;
def lista_tuplas(lista):
if type(lista) != list:
return None
tuplas = [] #inicia vacio
while len(lista) > 0:
elem = lista.pop() # saca el ultimo elemento
in_tupla = (elem, lista.count(elem))
tuplas.append(in_tupla)
return tuplas
ejemplo = [1,2,2,4,4,4,8]
lista_tuplas(ejemplo)
SELECT count(distinct(customers.id))*100/(select count(*) FROM customers) FROM customers inner join purchases on customers.id=purchases.customer_id inner join branches on purchases.branch_id=branches.id inner join customers on customers.id=purchases.customer_id where YEAR(purchases.created_at)=2020;
# Class QUEUE
class QUEUE:
def __init__(self):
self.data = []
def push(self, item):
self.data.append(item)
def pop(self):
return self.data.pop(0)
def peek(self):
return self.data[0]
def clear(self):
self.data.clear()
def length(self):
return len(self.data)
# List Person
person = [
{
"name": "Juan",
"age": 17,
"height": 170
},
{
"name": "Jose",
"age": 18,
"height": 160
},
{
"name": "Ana",
"age": 25,
"height": 152
},
{
"name": "Miguel",
"age": 22,
"height": 190
},
{
"name
def colmx(df, col):
colmx = df.loc[(df["Country"] == "Colombia") | (df["Country"] == "Mexico")]
return (len(colmx[colmx["Country"] == "Colombia"]), len(colmx[colmx["Country"] == "Mexico"]))
def triangle_area(base, height):
return base * height / 2
triangle_area(20, 4)
def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n-1):
# range(n) also work but outer loop will repeat one time more than needed.
# Last i elements are already in place
for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
def ordenar_diccionario(diccionario, clave, descendente = True):
if type(diccionario) != dict or clave not in diccionario:
return None
else:
ordenado = sorted(diccionario[clave])
if descendente:
return {clave: list(reversed(ordenado))}
else:
return {clave: ordenado}
imprimir_diccionario(ordenar_diccionario({"a":[1,2,3,4,5], "b": [6,7,8,9,10]},"a"))
def DividirDosNumeros(dividendo, divisor):
div = dividendo // divisor
mod = dividendo % divisor
return div, mod
class BinaryTree:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def insertaVal(self, data):
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insertaVal(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insertaVal(data)
else:
self.data = data
def buscaVal(self, lkpval):
if lkpval < self.data:
if self.left is None:
return str(lkpval)+" Not Found"
return self.left.buscaVal(lkpval)
elif lkpval > self.data:
if self.right is None:
return str(lkp
def vocal(a):
if len(a) > 1:
return "Dato incorrecto"
else:
if a in "aeiouAEIOU":
return "Es vocal"
else:
return "Dato incorrecto"
vocal("a")
def hydro_generation_for_europe(data):
energy_data = data[data.Entity == 'Europe']
return int(energy_data.Hydro_Generation_TWh.max())
hydro_generation_for_europe(energy_data)
SELECT COUNT(S.id) / (SELECT COUNT(DISTINCT C.id) FROM compra) * 100 as porcentaje
FROM sucursal S
INNER JOIN compra C ON C.id_sucursal = S.id
WHERE C.year = 2020
GROUP BY S.id
HAVING COUNT(S.id) = 1;
def actividadesencomun(persona1, persona2):
return list(set(persona1) & set(persona2))
def create_counter(a):
return lambda b: a + b if a != 0 and b != 0 else False
create_counter(2)(2)
def bin(x):
if type(x) == int and x >= -1 :
if x == 0 :
return 0
elif x == 1 :
return 1
else :
return bin(x // 2) * 10 + x % 2
else :
return None
bin(10)
class Queue:
def __init__(self, array=[]):
self.array = array
def empty(self):
return self.size() == 0
def size(self):
return len(self.array)
def enqueue(self, element):
return self.array.append(element)
def dequeue(self):
return self.array.pop(0)
def front(self):
return self.array[0]
def rear(self):
return self.array[-1]
def ordenar(diccionario, clave, descendente=True):
...
return diccionario_ordenado
SELECT * FROM customers WHERE age=24;
def objContains(obj, property, value):
for key in obj:
if obj[key] == value:
return True
elif type(obj[key]) is dict:
result = objContains(obj[key], property, value)
if result:
return result
return False
obj_contains({"key1": 1, "key2": {"key3": 2}}, "key3", 2)
SELECT sucursal.nombre, sum(ganancia.monto) FROM sucursal
INNER JOIN ganancia ON sucursal.id = ganancia.sucursal_id
INNER JOIN venta ON ganancia.venta_id = venta.id
INNER JOIN gasto ON venta.gasto_id = gasto.id
WHERE gasto.fecha >= "2019-01-01" AND gasto.fecha <= "2019-12-31"
GROUP BY sucursal.nombre
ORDER BY sum(ganancia.monto) DESC
LIMIT 1;
def add(a, b=0):
return a + b
add(1, 2)
def replace_all(text):
text = text.replace("1", "2")
text = text. replace("2", "1")
return text
def ordenar(diccionario, clave, descendente=True):
pass
def suma_todos_impares(array_int):
result = 0
for i in array_int:
if i % 2 != 0:
result += i
return result
suma_todos_impares([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
SELECT *
FROM cliente C
JOIN Tabla T ON C.cliente_id = T.cliente_id
JOIN sucursal S ON T.sucursal_id = S.sucursal_id
JOIN compra V ON T.compra_id = V.compra_id
WHERE V.anio = 2020;
SELECT ROUND(SUM(CASE WHEN COUNT(DISTINCT store_id)>=2 THEN 1 ELSE 0 END)*100.0/COUNT(*),2) AS percentage FROM orders WHERE YEAR(order_date)=2019;
fuentes_consumo = pd.read_csv("Fuentes_Consumo_Energia.csv")
# function that: Debes utilizar Pandas para ingestar en un objeto Dataframe el contenido del archivo provisto
"Fuentes_Consumo_Energia.csv".
Esta función debe informar la cantidad de registros cuya entidad sean Colombia o México retornando ese valor en un dato de tipo tupla (catidad de registros Colombia, catidad de registros México).
Pista: averiguar la funcion Shape
def cantidad_registros_mexico_colombia(df):
colombia_rows = df[df['Entidad'] == 'Colombia'].shape[0]
mexico_rows = df[df['Entidad'] == 'México'].shape[0]
return (colombia_rows, mexico_rows)
cantidad_registros_mex
SELECT COUNT(*) FROM cliente INNER JOIN compra ON cliente.cedula = compra.cliente_cedula WHERE compra.fecha >= '2019-01-01' AND compra.fecha <= '2019-12-31' GROUP BY cliente.cedula HAVING COUNT(DISTINCT compra.sucursal_id) >= 2;
def atender(queue, queue_atendidas, queue_espera):
while not queue.is_empty():
persona = queue.dequeue()
if persona['edad'] >= 18 and persona['altura'] > 150:
queue_atendidas.enqueue(persona)
else:
queue_espera.enqueue(persona)
def ordenar_diccionario(diccionario, clave, descendente=True):
try:
if type(diccionario) is not dict or clave not in diccionario.keys():
return None
else:
if descendente:
return sorted(diccionario.items(), key=lambda diccionario: diccionario[1])
else:
return sorted(diccionario.items(), key=lambda diccionario: diccionario[1], reverse=True)
except Exception:
return None
print(ordenar_diccionario({'clave1':['c','a','b'],
'clave2': ['d','e','f'],
'clave3': ['g','h','i']}, 'clave1'))
def full_name(first_name, last_name):
return first_name + " " + last_name
full_name("Heriberto", "Villarreal")
def sumarCostos(a):
return lambda b: b if a * b != 0 else False
class Queue:
def __init__(self, content=None, next=None):
self.content = content
self.next = next
def enqueue(self, content, next=None):
if self.content is None:
self.content = content
self.next = next
return
if self.next is None:
self.next = Queue(content, next)
return
self.next.enqueue(content, next)
return
def dequeue(self):
if self.content is None:
return None
if self.next is None:
content = self.content
self.content = None
self.next = None
return content
content = self.next.dequeue()
return content
def is_empty(self):
return self.content is None
def listaEnteros(inicio, tamanio):
return list(range(inicio, inicio + tamanio))
listaEnteros(10, 5)
def sumarCostos(precio):
def suma(precio2):
return precio + precio2
return suma
sumarCostos(0)(1)
class Animal:
def __init__(self, especie, color):
self.especie = especie
self.color = color
self.edad = 0
def cumplirAnios(self):
self.edad += 1
return self.edad
def crear_animal(especie, color):
return Animal(especie, color)
def objContains(obj, prop, value):
for key in obj:
if obj[key] == value:
return True
elif type(obj[key]) == type({}):
return objContains(obj[key], prop, value)
else:
continue
return False
objContains(objet, 'nombre', 'Bruno')
SELECT * FROM ventas
WHERE producto="PROD1" AND
( monto < (SELECT AVG(monto)-(3*STDDEV(monto)) FROM ventas)
OR monto > (SELECT AVG(monto)+(3*STDDEV(monto)) FROM ventas) )
def entidades(dataset):
"""
Cuenta las entidades diferentes que están presentes en el dataset.
"""
return len(set(dataset.ID))
def dataframe_energia():
df = pd.read_csv("./Fuentes_Consumo_Energia.csv", sep=";")
df_col = df[(df["Entidad"]=="Colombia")]
df_mex = df[(df["Entidad"]=="México")]
return (df_col.shape[0], df_mex.shape[0])
dataframe_energia()
def ordenar_diccionario(diccionario, clave, descendente=True):
if type(diccionario) != dict or clave not in diccionario:
return None
#creo una copia del diccionario para no mutarlo
dicc = diccionario.copy()
#obtengo la lista de valores de la clave del diccionario
#Ordeno esa lista
dicc[clave].sort(reverse=descendente)
#Creo una lista vacia
#Recorro el diccionario
for key in dicc:
if key != clave:
#Creo una lista vacia
l=[]
#Recorro la lista de la clave
for i in range(len(dicc[clave])):
#Obtengo el elemento en la posicion i-esima de la lista de la clave
#Obtengo el elemento en la posicion i-esima
np.arange(10)
def Ret_Pregunta06(n1,n2,n3):
'''
:param n3: array np.array
:param n2: array np.array
:param n1: array np.array
:return: Booleano
'''
try:
np.dot(n1,n2,n3)
return True
except:
return False
def Ret_Pregunta01():
df = pd.read_csv("Fuentes_Consumo_Energia.csv")
return df[df.Entity.isin(["Colombia","Mexico"])].shape
SELECT productName, (listPrice-buyPrice) AS ganancia FROM products;
def sumarCostos(n):
def sumador(m):
if n == 0 or m == 0:
return False
else:
return n + m
return sumador
SELECT (sales - costs) FROM products;
def suma(x):
def suma_interna(y):
return x + y
return suma_interna
resultado = suma(5)
print(resultado(8))
SELECT COUNT(cliente_id)/(SELECT COUNT(DISTINCT cliente_id) FROM compra) FROM compra GROUP BY cliente_id HAVING COUNT(DISTINCT sucursal_id) >= 2
def balance_check(s):
if len(s)%2!=0:
return False
opening = set('([{')
matches = set([ ('(',')'), ('[',']'), ('{','}') ])
stack = []
for paren in s:
if paren in opening:
stack.append(paren)
else:
if len(stack) == 0:
return False
last_open = stack.pop()
if (last_open,paren) not in matches:
return False
return len(stack) == 0
balance_check('[]')
balance_check('[](){([[[]]])}')
balance_check('()(){]}')
balance_check('[]{()')
def actividadesencomun (persona1, persona2):
return ['comer', 'dormir']
def esPrimo(num):
if (num<2):
return False
if (num==2):
return True
if (num%2==0):
return False
i=3
while (i*i<=num):
if (num%i==0):
return False
i=i+2
return True
def ListaRepetidos(lista):
return [(1,1),(2,2),(4,1)]
ListaRepetidos([1,2,2,4])
def atenderPacientes(pacientes, atendidas, espera):
for paciente in pacientes:
if paciente.getEdad() >= 18 and paciente.getAltura() > 150:
atendidas.enqueue(paciente)
else:
espera.enqueue(paciente)
return espera
SELECT COUNT(*), (SELECT COUNT(*) FROM customers WHERE channel='online' AND year BETWEEN 2019 and 2020)* 100 / COUNT(*) as porcentaje FROM customers
import numpy as np
def un_arange():
arange = np.arange(10)
return arange
un_arange()
SELECT count(*)/100 * (SELECT count(*) FROM customers WHERE channel='online' AND year BETWEEN '2019' AND '2020') FROM customers ;
def listaPrimos(desde, hasta):
lista_primos = []
for i in range(desde, hasta + 1):
if i > 1:
for j in range(2, i):
if (i % j) == 0:
break
else:
lista_primos.append(i)
return lista_primos
listaPrimos(1,7)
def dividirDosNumeros(dividendo,divisor):
cociente=dividendo//divisor
resto=dividendo%divisor
return cociente, resto
def Ret_Pregunta06(n1,n2,n3):
return n1.shape[1] == n2.shape[0] and n2.shape[1] == n3.shape[0]
def contar_repeticiones(lista):
if type(lista) != list:
return None
else :
lista_aux = lista.copy()
lista_aux = list(set(lista_aux))
lista_aux.sort()
contador = 0
lista_tuplas = []
for elem in lista_aux:
contador = 0
for elem2 in lista:
if elem2 == elem:
contador += 1
tupla = (elem, contador)
lista_tuplas.append(tupla)
return lista_tuplas
def ListaEnteros(inicio, tamanio):
lista = []
for i in range(tamanio):
lista.append(inicio+i)
return lista
ListaEnteros(1, 5)
def dec_to_bin(number):
if isinstance(number, int) and number >= 0:
return bin(number)[2:]
return None
import pandas as pd
def read_csv(filepath):
return pd.read_csv(filepath)
read_csv("data/sample.csv")
def ordenar(dicc, clave, descendente=True):
if type(dicc) != type({}) or clave not in dicc.keys():
return None
else:
if descendente:
return {k:sorted(v) for k,v in dicc.items()}
else:
return {k:sorted(v,reverse=True) for k,v in dicc.items()}
dicc = {"a": [1, 2, 3, 4, 5], "b": [1, 2, 3, 4, 5], "c": [1, 2, 3, 4, 5], "d": [1, 2, 3, 4, 5]}
print(ordenar(dicc, "c"))
lista = [1, 2, 3, 2, 3, 3]
contar_valores(lista)
# [(1, 1), (2, 2), (3, 3)]
def ordenar_diccionario(diccionario, clave, descendente=True):
if type(diccionario) is not dict or clave not in diccionario:
return None
if descendente:
return sorted(diccionario.items(), key=lambda item: item[1][clave], reverse=True)
return sorted(diccionario.items(), key=lambda item: item[1][clave], reverse=False)
import pandas as pd
def sum_max_column(file):
df = pd.read_csv(file)
return round(df['Maximo'].sum(), 4)
def get_records_by_country(data, country):
data_country = data[data.country == country]
return len(data_country)
get_records_by_country(countries, 'Mexico')
SELECT (COUNT(DISTINCT(cliente_id))*100)/COUNT(cliente_id) FROM compra WHERE fecha_compra BETWEEN '2020-01-01' AND '2020-12-31';
class QUEUE:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def enqueue(self, item):
self.items.insert(0,item)
def dequeue(self):
return self.items.pop()
def size(self):
return len(self.items)
def atender(queue):
atendidas = QUEUE()
enEspera = QUEUE()
for item in queue.items:
if item.edad >= 18 and item.altura > 150:
atendidas.enqueue(item)
else:
enEspera.enqueue(item)
return {
'Atendidas': atendidas,
'EnEspera': enEspera
}
atender(pacientes)
SELECT (count(channelName) * 100 / (SELECT COUNT(*) FROM orders)) AS percent FROM orders WHERE channelName='online' and YEAR(orderDate) BETWEEN 2019 AND 2020
def get_prime_numbers(desde, hasta):
primos = []
if (isinstance(desde, int) and isinstance(hasta, int)) and (desde > 0 and hasta > 0):
if desde > hasta:
return list()
for i in range(desde, hasta+1):
if is_prime(i):
primos.append(i)
return primos
return None
SELECT venta-compra AS ganancia FROM productos;
def count_missing(vec):
null_vec = pd.isnull(vec)
null_count = np.sum(null_vec)
return null_count
count_missing(data.Year)
def repe(lista):
tupla = []
for i in lista:
c = 0
for j in lista:
if i == j:
c += 1
tupla.append((i, c))
return tupla
repe([1,2,3,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1])
def count_repetition(lista):
if type(lista) == list:
return [(lista[i], lista.count(lista[i])) for i in range(len(lista)) if lista.count(lista[i]) > 1]
else:
return None
SELECT SUM(total_paid) FROM sales WHERE created_at >='2020-01-01' AND created_at <='2020-12-31';
SELECT COUNT(*) FROM customers;
def ordenar(diccionario, clave, descendente=True):
if type(diccionario) != type(dict()):
return None
if clave not in diccionario.keys():
return None
list_val = diccionario.values()
for item in list_val:
if type(item) != type(list()):
return None
list_val = sorted(list_val, key=lambda x: x[:1], reverse=descendente)
keys = diccionario.keys()
keys = sorted(keys)
new_dicc = {}
for i in range(len(list_val)):
new_dicc[keys[i]] = list_val[i]
return new_dicc
select count(*) as new_clients from customers where id_customer in (select id_customer from purchases where year(date_purchase) = 2020 and id_customer not in (select id_customer from purchases where year(date_purchase) = 2019));
'clave3':['2','5','1']}
def remplazar_linea(archivo, i, linea):
with open(archivo, 'r') as file:
lineas = file.readlines()
lineas[i] = linea
with open(archivo, 'w') as file:
file.writelines(lineas)
remplazar_linea('archivo.txt', 2, 'linea a reemplazar\n')
SELECT COUNT(*) * 100 / (SELECT COUNT(*) FROM customers WHERE online_order!=1) FROM customers WHERE online_order=1;
SELECT MAX(net_profit) FROM branches;
def isBalanced(str):
#your code
return false
def product(A, B, C):
return A.shape[1] == B.shape[0] and B.shape[1] == C.shape[0]
def ListaRepetidos(lista):
if type(lista) != list:
return None
lista = ListaRepetidos(lista.sort())
tupla = ()
for i in lista:
contador = 0
for j in lista:
if i == j:
contador += 1
tupla = tupla + (i, contador)
return tupla
def get_total_consumption():
return round(get_consumption_per_country('World', 2019)['Total'], 2)
select round(100*count(distinct customer)/(select count(distinct customer) from transactions),2) as "Porcentaje de clientes en al menos dos sucursales" from transactions;
SELECT COUNT(*) * 100.0 / (SELECT COUNT(*) FROM customers WHERE channel='online' AND YEAR(customer_since) BETWEEN 2019 AND 2020) as percentage FROM customers WHERE channel='online' AND YEAR(customer_since) BETWEEN 2019 AND 2020
def check_balance(txt):
if (txt.count('(') + txt.count('[') + txt.count('{')) != (txt.count(')') + txt.count(']') + txt.count('}')):
return False
if txt.count('(') == 0 and txt.count('[') == 0 and txt.count('{') == 0:
return True
if txt.count('(') > 0:
if txt.count('(') > txt.count(')'):
return False
else:
return check_balance(txt[txt.find(')')+1:])
if txt.count('[') > 0:
if txt.count('[') > txt.count(']'):
return False
else:
return check_balance(txt[txt.find(']')+1:])
if txt.count('{') > 0:
if txt.count('{') > txt.count('}'):
import pandas as pd
df = pd.read_csv('Fuentes_Consumo_Energia.csv')
df.head()
SELECT (SUM(CASE WHEN COUNT(sucursal_id) = 1 THEN 1 ELSE 0 END)*100)/COUNT(sucursal_id) AS total_clientes_uno_por_sucursal
FROM compra
GROUP BY sucursal_id
HAVING YEAR(fecha) = 2020;
def ListaRepetidos(lista):
pass
def actividadesencomun(persona1, persona2):
return []
SELECT sucursal.Sucursal, SUM(ventas.GananciaNeta) - SUM(gastos.Gastos) AS GananciaNeta
FROM ventas
JOIN gastos ON gastos.IdSucursal = ventas.IdSucursal
JOIN sucursal ON sucursal.IdSucursal = ventas.IdSucursal
GROUP BY sucursal.Sucursal
ORDER BY GananciaNeta DESC;
SELECT COUNT(DISTINCT(cliente)) * 100 / (SELECT COUNT(DISTINCT(cliente)) FROM compra) as porcentaje
FROM compra
WHERE YEAR(fecha) = 2020
GROUP BY sucursal;
def get_primes(desde, hasta):
primos = []
if type(desde) is not int or type(hasta) is not int or desde < 0 or hasta < 0:
return None
elif hasta < desde:
return primos
else:
for i in range(desde, hasta+1):
for j in range(2,i):
if i % j == 0:
break
else:
primos.append(i)
return primos
import pandas as pd
def obtener_max_sum(filepath):
df = pd.read_csv(filepath, encoding = "utf-8")
return round(df["MAX"].sum(),4)
obtener_max_sum("GGAL - Cotizaciones historicas.csv")
def add(a):
if a == 0:
return False
def addB(b):
return a + b
return addB
add(0)(0)
SELECT year, (ventas - compras) as ganancias
FROM tbl_name
WHERE year = 2019;
def dec_to_bin(a, b):
return a / b
dec_to_bin(1, 2)
import pandas as pd
d = pd.read_csv('https://raw.githubusercontent.com/carlosfab/curso_data_science_na_pratica/master/modulo_02/pandas/data/titanic-data-6.csv')
def contador(data):
return (data['Survived'][data['Country'] == 'Colombia'].count(), data['Survived'][data['Country'] == 'Mexico'].count())
contador(d)
def objContains(obj, key, value):
for k, v in obj.items():
if k == key and v == value:
return True
if type(v) == dict:
return objContains(v, key, value)
return False
objContains({'user': {'name': 'pepe'}}, 'name', 'pepe')
def resta(a, b):
return a - b
resta(10, 2)
SELECT id_customer, COUNT(DISTINCT id_customer) * 100 / (SELECT COUNT(DISTINCT id_customer) FROM sales) FROM sales WHERE year(created_at) = 2020 AND id_customer NOT IN (SELECT id_customer FROM sales WHERE year(created_at) = 2019) GROUP BY id_customer
def ListaRepetidos(lista):
if (type(lista) is list):
return [(lista[x], lista.count(lista[x])) for x in range(0, len(lista)) if lista.count(lista[x]) > 1]
else:
return None
def contador_de_elementos(lista):
if type(lista) == list:
return [(i, lista.count(i)) for i in set(lista)]
else:
return None
lista = [1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2]
contador_de_elementos(lista)
def ListaPrimos(desde, hasta):
if desde > hasta:
return []
return [x for x in range(desde, hasta+1) if is_prime(x)]
def is_prime(number):
i = 2
while i <= number / 2:
if number % i == 0:
return False
i += 1
return True
def objContains(obj, prop, value):
result = False
for k, v in obj.items():
if k == prop and v == value:
result = True
if type(v) == dict:
result = objContains(v, prop, value)
return result
obj = {"a" : {"b" : {"c" : {"d" : {"e" : {"f" : {"g" : 1}}}}}}}
objContains(obj, "e", 1)
def max_Hydro_Europe(file):
df = pd.read_csv(file)
df.columns = ["Entity", "Code", "Year", "Hydro_Generation_TWh"]
df.set_index("Year", inplace=True)
return df[df.Entity == 'Europe']["Hydro_Generation_TWh"].idxmax()
max_Hydro_Europe("Fuentes_Consumo_Energia.csv")
select month(fecha) 'Mes', sum(total) 'Venta 2020',
(select sum(total) from venta where year(fecha)=2019) 'Venta 2019',
(sum(total)-(select sum(total) from venta where year(fecha)=2019)) 'Diferencia'
from venta where year(fecha)=2020
group by month(fecha)
order by 'Diferencia' desc;
SELECT (sale-buy) AS ganancia FROM productos;
SELECT 100 * SUM(CASE WHEN num_branch >= 2 THEN 1 ELSE 0 END) / COUNT(*) AS pct_multi_branch FROM (
SELECT COUNT(*) AS num_branch FROM purchases WHERE purchase_date >= '2019-01-01' GROUP BY customer_id
) sub;
def cantidad_nodos_lista(lista):
actual = lista.getCabecera()
count = 0
while(actual != None):
actual = actual.getSiguiente()
count += 1
return count
def ordenar_diccionario(diccionario, clave='nombre', descendente=True):
if type(diccionario) is not dict:
return None
if clave not in diccionario.keys():
return None
for clave, valor in diccionario.items():
valor.sort(reverse=descendente)
return diccionario
diccionario = {'clave1':['c','a','b'],
'clave2':['b','a','c'],
'clave3':['a','c','b']}
print(ordenar_diccionario(diccionario, 'clave3'))
print(ordenar_diccionario(diccionario, 'clave3', False))
print(ordenar_diccionario(diccionario, 'clave2'))
print(ordenar_diccionario(diccionario, 'clave1'))
print(ordenar_diccionario
def balanceado(cadena):
if cadena == '()' or cadena == '[]' :
return True
else:
return False
print(balanceado('()'))
SELECT sucursal.nombre, SUM(ventas.venta)-SUM(gastos.monto) AS ganancia_neta
FROM sucursal
INNER JOIN ventas ON sucursal.IdSucursal = ventas.IdSucursal
INNER JOIN gastos ON sucursal.IdSucursal = gastos.IdSucursal
WHERE ventas.fecha>='2019-01-01' AND ventas.fecha<='2019-12-31'
GROUP BY sucursal.nombre
ORDER BY ganancia_neta DESC
LIMIT 1;
def full_name(first_name, last_name):
return first_name + " " + last_name
full_name("juan", "perez")
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
factorial(1)
factorial(2)
factorial(3)
factorial(4)
def Division(dividendo, divisor):
return dividendo // divisor, dividendo % divisor
import numpy as np
numeros = np.arange(10)
numeros
def cuantas_veces(lista):
if type(lista) != list:
return None
else:
lista_resultado = []
lista_ordenada = sorted(lista)
lista_ordenada_sin_repetidos = list(dict.fromkeys(lista_ordenada))
for i in lista_ordenada_sin_repetidos:
lista_resultado.append((i, lista_ordenada.count(i)))
return lista_resultado
def potencia(numero, elevar):
return numero ** elevar
potencia(2, 2)
SELECT
(SUM(CASE WHEN cant_suc=1 THEN 1 ELSE 0 END)/COUNT(*))*100 AS porcent_clientes_1_suc
FROM
(
SELECT
c.cliente_id,
COUNT(*) AS cant_suc
FROM compra
INNER JOIN sucursal s ON compra.sucursal_id=s.sucursal_id
INNER JOIN cliente c ON compra.cliente_id=c.cliente_id
WHERE DATE_PART('year', fecha_compra)=2020
GROUP BY c.cliente_id
ORDER BY cant_suc
) q1;
def dec_to_bin(number):
if number < 0:
return None
elif number == 0:
return '0'
elif number == 1:
return '1'
else:
return dec_to_bin(number//2) + dec_to_bin(number%2)
SELECT COUNT(*) AS total_clientes, 100*COUNT(DISTINCT p.sucursal)/COUNT(*) AS porcentaje
FROM clientes AS c LEFT JOIN compras AS p
ON c.id_cliente = p.id_cliente
WHERE YEAR(c.fecha_cliente) = 2019;
def ordenar_diccionario(diccionario, clave, descendente=True):
try:
if(type(diccionario) != dict):
return None
if(clave not in diccionario.keys()):
return None
if(len(diccionario.keys())<2):
return diccionario
new_dict = {}
new_dict[clave] = sorted(diccionario[clave], reverse=descendente)
for k in diccionario.keys():
if(k != clave):
new_dict[k] = diccionario[k]
return new_dict
except:
return None
def sort_dict(diccionario, clave, descendente=True):
if type(diccionario) is dict:
if clave in diccionario.keys():
dic = {} #diccionario vacio para almacenar los valores ordenados
if descendente:
aux = sorted(diccionario[clave], reverse=True)
else:
aux = sorted(diccionario[clave])
for i in range(len(aux)):
for key, values in diccionario.items():
for j in range(len(values)):
if values[j] == aux[i]:
if key in dic.keys():
dic[key].append(values[j])
else:
dic[key] = []
dic[key].append(values[j])
return dic
else:
return None
else:
return None
a = {"a":[1,2,3], "b":[
SELECT (SELECT COUNT(DISTINCT customer_id) FROM purchases WHERE YEAR(purchase_date) = 2019) / (SELECT COUNT(*) FROM customers) * 100 AS percentage FROM purchases LIMIT 1;
def objContains(obj, key, value):
if key in obj.keys():
if obj[key] == value:
return True
for v in obj.values():
if isinstance(v, dict):
if objContains(v, key, value):
return True
return False
objContains({'a': { 'b': {'c': {'d': 1} } } }, 'd', 1) #True
SELECT branch_name, SUM(net_profit)
FROM branch
WHERE year=2019
GROUP BY branch_name
ORDER BY SUM(net_profit) DESC
LIMIT 1;
SELECT (COUNT(*) * 100)
FROM customers
WHERE customer_id IN (SELECT customer_id
FROM transactions
WHERE transaction_channel = 'ONLINE'
AND transaction_date > '2019-01-01')
AND customer_id NOT IN (SELECT customer_id
FROM transactions
WHERE transaction_channel <> 'ONLINE'
AND transaction_date > '2019-01-01');
string = "{ [ ( ] ) }"
def is_balanced(string):
if string.count('(') != string.count(')'):
return False
if string.count('[') != string.count(']'):
return False
if string.count('{') != string.count('}'):
return False
return True
is_balanced(string)
def balance_check(s):
if len(s)%2 != 0:
return False
opening = set('([{')
matches = set([ ('(',')'), ('[',']'), ('{','}') ])
stack = []
for paren in s:
if paren in opening:
stack.append(paren)
else:
if len(stack) == 0:
return False
last_open = stack.pop()
if (last_open,paren) not in matches:
return False
return len(stack) == 0
balance_check('[](){([[[]]])}')
balance_check('()(){]}')
import pandas as pd
def max_hydro_gen(x):
data = pd.read_csv(x)
df = pd.DataFrame(data)
hyrdo = df[['YEAR', 'Hydro_Generation_TWh']]
return hyrdo[hyrdo['Hydro_Generation_TWh']==hyrdo['Hydro_Generation_TWh'].max()]['YEAR']
max_hydro_gen('Fuentes_Consumo_Energia.csv')
SELECT clientes.nombre, clientes.apellido, COUNT(compra.sucursal) AS canti_sucursales, COUNT(compra.sucursal)/7*100 AS porcentaje_clientes
FROM clientes
JOIN compra ON compra.id_cliente=clientes.id
GROUP BY clientes.nombre, clientes.apellido
HAVING canti_sucursales >= 2;
# Begin
def DividirDosNumeros(dividendo, divisor):
cociente = dividendo//divisor
resto = dividendo%divisor
return cociente, resto
DividirDosNumeros(10,3)
SELECT product_name,price-cost AS ganancia FROM products;
SELECT count(date) FROM orders WHERE channel = 'online' and extract(year from date) between 2019 and 2020;
def Ret_Pregunta06(n1,n2,n3):
if n1.shape[1]==n2.shape[0] and n2.shape[1]==n3.shape[0]:
return True
else:
return False
import numpy as np
def linspace_100(a, b):
return np.linspace(a, b, 100)
linspace_100(0, 9)
def count(lista):
if not isinstance(lista, list):
return None
if lista == []:
return []
resp = []
for i in lista:
count = 0
for j in lista:
if i == j:
count += 1
resp.append((i, count))
return resp
def cuentaNodos(lista):
return
def ListaEnteros(inicio, tamanio):
return []
def ListaRepetidos(lista):
if not isinstance(lista, list):
return None
res = []
for i in lista:
if i not in res:
res.append((i, lista.count(i)))
return res
SELECT ROUND(100 * (SELECT COUNT(*) FROM customers WHERE date >= '2019-01-01' and date <= '2020-01-01' and channel = 'online') / COUNT(*),2) as '% de pedidos por online' FROM customers;
def ListaEnteros(inicio, tamanio):
lista=[]
for i in range(inicio,inicio+tamanio):
lista.append(i)
return lista
ListaEnteros(10,5)
import numpy as np
def mult(a, b, c):
return a.shape[1] == b.shape[0] and b.shape[1] == c.shape[0]
SELECT COUNT(*) FROM customers WHERE channel_customer_type='online' AND created_at BETWEEN '2019-01-01' AND '2020-12-30';
def array():
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
return a
def ListaEnteros(inicio, tamanio):
lista = []
for num in range(inicio, inicio + tamanio):
lista.append(num)
return lista
def can_multiply(c, d, e):
return c.shape[1] == d.shape[0] == e.shape[1]
def cantidad_nodos(lista):
cantidad = 0
if lista.cabecera is None:
cantidad = 0
else:
actual = lista.cabecera
while actual is not None:
cantidad += 1
actual = actual.siguiente
return cantidad
def balanceado(error):
# Codigo
balanceado("[{()}]")
SELECT name, ganancia FROM customers WHERE ganancia>=1000;
def ListaPrimos(desde, hasta):
if type(desde) != type(1) or type(hasta) != type(1):
return None
if desde < 0 or hasta < 0:
return None
if hasta < desde:
return []
numbers = range(desde, hasta + 1)
primos = filter(is_prime, numbers)
return primos
def is_prime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
def count_nodes(list):
if list.getCabecera() is None:
return 0
if list.getCabecera().getSiguiente() is None:
return 1
aux = list.getCabecera()
cont = 0
while aux is not None:
cont += 1
aux = aux.getSiguiente()
return cont
def balance_check(s):
# check is even number of brackets
if len(s) % 2 != 0:
return False
# Set of opening brackets
opening = set('([{')
# Matching Pairs
matches = set([('(',')'),('[',']'),('{','}')])
# Use a list as a "Stack"
stack = []
# Check every parenthesis in string
for paren in s:
# If its an opening, append it to list
if paren in opening:
stack.append(paren)
else:
# Check that there are parentheses in Stack
if len(stack) == 0:
return False
# Check the last open parenthesis
last_open = stack.pop()
# Check if it has a closing match
if (last_open,paren) not in matches:
return False
return len(stack) == 0
def ListaRepetidos(lista):
if type(lista) != list:
return None
lista_sin_repeticiones = []
lista_con_repeticiones = []
for item in lista:
if item not in lista_sin_repeticiones:
lista_sin_repeticiones.append(item)
for item in lista_sin_repeticiones:
lista_con_repeticiones.append((item, lista.count(item)))
return lista_con_repeticiones
lista = [1,2,2,4]
def findColombiaMexico(dataframe):
df1 = dataframe[dataframe.ENTIDAD == 'COLOMBIA']
df2 = dataframe[dataframe.ENTIDAD == 'MEXICO']
return df1.shape, df2.shape
findColombiaMexico(df)
SELECT branch, SUM(comissions) FROM sales WHERE YEAR(date) = 2020 GROUP BY branch
def area(h, w):
return h * w
area(10,20)
count_years = df['Year'].count()
count_years
def greet(name):
return "Hola " + name
greet("Martin")
def ListaEnteros(inicio, tamanio):
return [i for i in range(inicio, inicio+tamanio)]
def binary(number):
try:
if number > -1 and type(number) == int:
return int(bin(number)[2:])
else:
return None
except:
return None
def sumareltipo(arr):
objeto_de_retorno = {}
for i in arr:
if i not in objeto_de_retorno:
objeto_de_retorno[i] = 0
objeto_de_retorno[i] += 1
return objeto_de_retorno
sumareltipo(['auto', 'moto', 'auto'])
SELECT sucursal, SUM(venta)-SUM(gasto) AS ganancia FROM sucursal, venta, gasto WHERE venta.sucursal = sucursal.id AND gasto.sucursal = sucursal.id AND venta.anyo = "2019" AND gasto.anyo = "2019" GROUP BY sucursal.id ORDER BY ganancia DESC LIMIT 1;
SELECT (COUNT(*) / (SELECT COUNT(*) FROM customers WHERE (channel=1) AND (purchase_date BETWEEN '2019-01-01' AND '2020-12-31'))) * 100 FROM customers WHERE (channel=1) AND (purchase_date BETWEEN '2019-01-01' AND '2020-12-31');
def ListaPrimos(desde, hasta):
lista = []
if isinstance(desde, int) and isinstance(hasta, int) and desde > 0 and hasta > 0:
if desde <= hasta:
for i in range(desde, hasta + 1):
if EsPrimo(i):
lista.append(i)
else:
return None
return lista
def hash(codigo_de_pais, nombre_de_pais, region):
return {
'codigo_de_pais': codigo_de_pais
'nombre_de_pais': nombre_de_pais
'region': region
}
hash('AR', 'Argentina', 'Latinoamerica')
def Ret_Pregunta06(n1, n2, n3):
return n1.shape[1] == n2.shape[0] and n2.shape[1] == n3.shape[0]
def orderDictionary(diccionario, clave, descendente=True):
if type(diccionario) is not dict or clave not in diccionario.keys():
return None
# get the key
key = diccionario[clave]
if not descendente:
key.reverse()
# order the dictionary
new_dict = {}
for k in diccionario.keys():
new_dict[k] = []
for v in key:
for i in range(len(diccionario[k])):
if diccionario[k][i] == v:
new_dict[k].append(v)
return new_dict
#tests
dicc = {'clave1':['c','a','b'],
'clave2':['casa','auto','barco'],
'clave3':[1,2,3]}
print(orderDictionary(dicc, 'clave1', True))
print(orderDictionary(dicc, 'clave3',
SELECT COUNT(distinct sucursal.id) as cantidad_de_compra_en_una_sucursal
FROM sucursal, cliente
JOIN compra as c on sucursal.id = c.sucursal_id
JOIN cliente as cli on c.cliente_id = cli.id
WHERE cli.id in
(SELECT cliente_id FROM compra WHERE YEAR(fecha)='2020');
SELECT
month(fecha_ventas) AS mes,
(SELECT SUM(precio*cantidad) FROM ventas WHERE month(fecha_ventas) = mes) -
(SELECT SUM(precio*cantidad) FROM compras WHERE month(fecha_compras) = mes) -
(SELECT SUM(valor) FROM gastos WHERE month(fecha_gastos) = mes) AS ingresos
FROM ventas WHERE year(fecha_ventas) = 2019
GROUP BY mes
ORDER BY ingresos DESC
LIMIT 1;
def ListaRepetidos(lista):
if(type(lista)==list):
lista.sort()
repeticiones = []
for i in range(len(lista)):
repeticiones.append(lista.count(lista[i]))
return list(zip(lista,repeticiones))
else:
return None
def conversion(x):
if type(x) == int and x >= 0:
return bin(x)[2:]
else:
return None
conversion(5)
def atender(pacientes):
enespera = Queue()
atendidas = Queue()
for paciente in pacientes
if paciente.edad >= 18 and paciente.altura > 150:
atendidas.add(paciente)
else:
enespera.add(paciente)
return atendidas, enespera
def error(error):
if "{" or "[" or "(" in error:
#Check if the error has a "}"
if "}" in error:
#Check if the error has a "]"
if "]" in error:
#Check if the error has a ")"
if ")" in error:
return True
else:
return False
else:
return False
else:
return False
else:
return False
print(error("{[(])}"))
def binary(n):
if n==0:
return ''
else:
return binary(n//2) + str(n%2)
binary(1/2)
SELECT * FROM customers WHERE age=24;
import pandas as pd
df = pd.read_csv('Fuentes_Consumo_Energia.csv', encoding = 'unicode_escape')
df.head()
def consulta_1():
return df.loc[df['Entity'] == 'Colombia']['Entity'].count(), df.loc[df['Entity'] == 'Mexico']['Entity'].count()
consulta_1()
SELECT * FROM customers WHERE year(fecha)=2019;
def f_lista(lista):
lista_final = []
if type(lista) != list:
return None
for x in lista:
lista_aux=[]
for y in lista:
if x == y:
lista_aux.append(y)
lista.remove(y)
lista_final.append(tuple(lista_aux))
return lista_final
def repetidos(lista):
tuplas = []
if type(lista) is list:
lista = list(set(lista))
lista.sort()
for item in lista:
tuplas.append((item, lista.count(item)))
else:
tuplas = None
return tuplas
def fuente_energia(df):
return df[(df.Entity == 'Colombia') | (df.Entity == 'Mexico')].shape[0]
SELECT COUNT(DISTINCT(cedula)) AS DISTINCT_CUSTOMERS, (COUNT(DISTINCT(cedula))/COUNT(cedula))*100 AS PERCENTAGE_DISTINCT_CUSTOMERS
FROM clientes
INNER JOIN compras
ON compras.cedula=clientes.cedula
WHERE YEAR(fecha) = 2019
def DividirDosNumeros(a, b):
return (a // b, a % b)
DividirDosNumeros(10, 3)
def sum(a):
def add(b):
return a + b
return add
def sum_cero(a):
if a == 0:
return False
def add(b):
return a + b
return add
sum_cero(0)(1)
SELECT COUNT(num_cliente) FROM clientes WHERE num_cliente IN (SELECT num_cliente FROM compra GROUP BY num_cliente HAVING COUNT(num_cliente)>1);
def convert_to_binary(number):
if not type(number) == int:
return None
if number < 0:
return None
return bin(number)
convert_to_binary(6)
def balanced(text):
lista_text = list(text)
aux = []
for l in lista_text:
if l == '(' or l == '[' or l == '{':
aux.append(l)
elif l == ')' or l == ']' or l == '}':
if len(aux) == 0:
return False
if l == ')' and aux[len(aux)-1] != '(':
return False
if l == ']' and aux[len(aux)-1] != '[':
return False
if l == '}' and aux[len(aux)-1] != '{':
return False
aux.pop()
return True
SELECT t1.total, t2.cantidad FROM
(
SELECT COUNT(*) total FROM (SELECT id_cliente FROM sucursal WHERE id_cliente IS NOT NULL GROUP BY id_cliente, id_sucursal HAVING COUNT(id_cliente) > 1) tabla1
) t1
CROSS JOIN
(
SELECT COUNT(*) cantidad FROM (SELECT id_cliente FROM sucursal WHERE id_cliente IS NOT NULL GROUP BY id_cliente) tabla2
) t2
def divide(a, b):
return a // b
def modulo(a, b):
return a % b
def division(a, b):
c = a // b
d = a % b
return c, d
division(5, 2)
def ordDicc(diccionario,clave,descendente=True):
if not isinstance(diccionario,dict):
return None
if clave not in diccionario.keys():
return None
lst = list(zip(diccionario[clave],*diccionario.values()))
lst.sort(reverse=descendente)
dicc = {clave: []}
for i in range(len(lst[0])-1):
dicc[list(diccionario.keys())[i+1]] = []
for i in range(len(lst)):
dicc[clave].append(lst[i][0])
for j in range(len(lst[0])-1):
dicc[list(diccionario.keys())[j+1]].append(lst[i][j+1])
return dicc
dicc = {
'ciudad':['Barcelona','Barcelona','Barcelona','Madrid','Mad
def dolar(euro):
return euro * 1.20
dolar(5)
def seleccion(lista):
for i in range(0, len(lista) - 1):
min = i
for j in range(i + 1, len(lista)):
if lista[j] < lista[min]:
min = j
lista[i], lista[min] = lista[min], lista[i]
return lista
seleccion([4, 3, 7, 2, 1])
def lista_repetidos(lista):
"""
Esta función recibe como argumento una lista y devuelve una lista de tuplas donde cada
tupla contiene un valor de la lista original y las veces que se repite. Los valores
de la lista original no deben estar repetidos.
Debe respetarse el orden original en el que aparecen los elementos.
En caso de que el parámetro no sea de tipo lista debe retornar nulo.
Recibe un argumento:
lista: Será la lista que se va a evaluar.
"""
if type(lista) != list:
return None
else:
lista_2 = []
for i in lista:
suma = 0
for j in lista:
if i == j:
suma = suma + 1
if suma != 1:
list
SELECT (sale_price - buy_price) as "ganancia" FROM products;
def dividirDosNumeros(dividendo, divisor):
return dividendo // divisor, dividendo % divisor
print(dividirDosNumeros(10,3))
def generate_total(price):
def calculate_total(total):
total += price
return total
return calculate_total
total = generate_total(100)
total(200)
select * from stores
where idstore = (select max(netprofit) from incomes)
def binar(numero):
if(type(numero) == int and numero >= 0):
return bin(numero)
return 0
binar(5)
def actividadesescomun(persona1, persona2):
comun = []
for actividad in persona1:
for actividad2 in persona2:
if actividad == actividad2:
comun.append(actividad)
return comun
def sumarCostos(costo):
def sumar(otro_costo):
if otro_costo == 0 or costo == 0:
return False
return costo + otro_costo
return sumar
suma = sumarCostos(15)
print(suma(5))
#Out 20
SELECT COUNT(channel) FROM customers WHERE channel='online' AND (birth_year='2019' OR birth_year='2020');
SELECT year,(sellprice-buyingprice) FROM clients WHERE year=2019;
SELECT * FROM branch WHERE sales = (SELECT MAX(sales) FROM branch);
#funciones
def area_rectangulo(base, altura):
area = base*altura
return area
area = area_rectangulo(10, 5)
print(area)
def total_consumption(df, entity, year):
total_consumption = round((df.loc[(df['Entity'] == entity) & (df['Year'] == year)]['Energy Supply']).sum(), 2)
return total_consumption
def convert_to_binary(number):
if(type(number) == int and number >= 0):
return bin(number)[2:]
else:
return None
def func1(lista):
if type(lista) == list:
lista = list(set(lista))
lista = list(enumerate(lista, start=1))
return lista
else:
return None
def lista_repetidos(lista):
if not isinstance(lista, list):
return None
if len(lista) == 0:
return []
lista_final = []
for item in lista:
if not item in lista_final:
lista_final.append(item)
return lista_final
def sumarCostos(precio):
return precio
suma = sumarCostos(15)
suma(5)
df = pd.read_csv('Fuentes_Consumo_Energia.csv')
df.head()
SELECT Sucursal, SUM(Precio*Cantidad) AS Venta
FROM ventas
GROUP BY Sucursal
ORDER BY Venta DESC LIMIT 1;
SELECT branches.branch_name, (SUM(sales.price) - SUM(expenses.amount)) AS ganancia
FROM sales
INNER JOIN branches ON sales.branch_id = branches.id
INNER JOIN expenses ON branches.id = expenses.branch_id
GROUP BY branches.branch_name
ORDER BY ganancia DESC
LIMIT 1;
def atender(fila, atendidas, espera):
pass
def ClaseAnimal(especie, color):
class Animal():
def __init__(self, especie, color):
self.edad = 0
self.especie = especie
self.color = color
def cumplir_anios(self):
self.edad += 1
return self.edad
return Animal(especie, color)
def getCantNodos():
cant = 0
aux = self.getCabecera()
while (aux != None):
cant = cant + 1
aux = aux.getProx()
return cant
def contar_valores(lista):
if type(lista)==list:
x = []
for i in range(0, len(lista)):
y = (lista[i], lista.count(lista[i]))
if y not in x:
x.append(y)
return x
else:
return None
SELECT ganancia FROM productos WHERE venta-compra;
def get_world_consumption(df):
return round(df.loc[(df.entity == 'World') & (df.year == 2019), 'consumption'].values[0], 2)
def sumar_costos(precio):
def sumar(precio_extra):
return precio_extra + precio
return sumar
import pandas as pd
def cant_registros(data):
cant_col = data[data['Entity']=='Colombia'].shape[0]
cant_mex = data[data['Entity']=='Mexico'].shape[0]
return (cant_col, cant_mex)
df = pd.read_csv('https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/ecdc/full_data.csv')
cant_registros(df)
def sumarCostos(a):
def closure(b):
if b == 0:
return False
return a + b
return closure
const suma = sumarCostos(15)
const suma2 = sumarCostos(0)
console.log(suma(5))
console.log(suma2(5))
def DividirDosNumeros(dividendo, divisor):
return dividendo // divisor, dividendo % divisor
a,b = DividirDosNumeros(10,3)
print(f'La división entera de 10 y 3 es {a}, y el resto de la división es {b}')
def decToBin(n):
if(isinstance(n, int)):
if (n > -1):
return bin(n)
else:
return None
else:
return None
def frac_bin(num, den):
# num, den = 1, 2
bin_num = ''
bin_den = ''
while num >= 1 or den >= 1:
# print(num)
# print(den)
if den % 2 == 0:
bin_den += '0'
else:
bin_den += '1'
if num % 2 == 0:
bin_num += '0'
else:
bin_num += '1'
num /= 2
den /= 2
return (bin_num, bin_den)
frac_bin(1, 2)
def Ret_Pregunta06(n1,n2,n3):
return n1.shape[1] == n2.shape[0] and n2.shape[1] == n3.shape[0]
def hydro_europe_max(df):
# your code here
return None
df = pd.read_csv('https://github.com/napoles-uach/Curso_Python_UACH/'+
'blob/master/Data/EnergyMixGeo.csv?raw=true')
hydro_europe_max(df)
SELECT
clientes.nombre,
clientes.cedula,
COUNT(compra.sucursal) AS numero_compras
FROM
clientes
INNER JOIN
compra ON clientes.cedula = compra.cedula
GROUP BY clientes.cedula
HAVING COUNT(compra.sucursal) > 1
def ListaRepetidos(lista):
if type(lista) != list:
print("Error")
return None
resp = []
for i in range(len(lista)):
if i == 0:
resp.append((lista[i], 1))
else:
for j in range(len(resp)):
if lista[i] == resp[j][0]:
resp[j] = (resp[j][0], resp[j][1]+1)
break
elif j == len(resp)-1:
resp.append((lista[i], 1))
return resp
SELECT sucursal
FROM sucursal, venta, gasto
WHERE venta.id=sucursal.id
AND gasto.id=sucursal.id
AND venta.year=2019
AND gasto.year=2019
SELECT year,sale-cost as gain FROM sales WHERE year=2019;
SELECT customer_id, count(DISTINCT sucursal_id) AS count
FROM compra
WHERE year(fecha) = 2020
GROUP BY customer_id
HAVING count = 1;
def conteo_paises():
return cantidad_colombia, cantidad_mexico
def es_binario(numero):
if type(numero) == int and numero >= 0:
return "{0:b}".format(numero)
else:
return None
Generate
More than just a code generator. A tool that helps you with a wide range of tasks. All in one place.
Function from Description
Text Description to SQL Command
Translate Languages
Generate HTML from Description
Code to Explanation
Fix invalid Code
Get Test for Code
Class from Description
Regex from Description
Regex to Explanation
Git Command from Description
Linux Command
Function from Docstring
Add typing to code
Get Language from Code
Time complexity
CSS from Description
Meta Tags from Description