Introducci贸n

1

El Zen de Python

Conjuntos

2

Sets

3

Modificando conjuntos

4

Operaciones con conjuntos

5

Playgrounds: Elimina elementos duplicados usando conjuntos

Comprehensions

6

List Comprehension

7

Dictionary Comprehension

8

Dictionary Comprehension: condition

9

Playgrounds: Crea una lista usando List Comprehension

10

Lists vs. Tuples vs. Sets

Funciones

11

Funciones

12

Funciones: return

13

Par谩metros por defecto y m煤ltiples returns

14

El scope

15

Refactor game

16

Playgrounds: Tienda de Tecnolog铆a

17

Funciones an贸nimas: lambda

18

Higher order function: una funci贸n dentro de otra funci贸n

19

Map

20

Map con diccionarios

21

Reto: map con inmutabilidad

22

Playgrounds: Multiplica todos los elementos por dos

23

Filter

24

Playgrounds: Retorna solo palabras de 4 letras y m谩s

25

Reduce

M贸dulos

26

M贸dulos

27

Mis propios m贸dulos

28

M贸dulos como scripts: __name__ y __main__

29

Paquetes

30

Playgrounds: Calcular la suma de todas las compras

Manipulaci贸n de archivos y errores

31

Iterables

32

Errores en Python

33

Manejo de excepciones

34

Playgrounds: Captura la excepci贸n: ZeroDivisionError

35

Leer un archivo de texto

36

Escribir en un archivo

37

Leer un CSV

38

Playgrounds: Lee un CSV para calcular el total de gastos

Gr谩ficas en Python

39

Creando una gr谩fica

40

Reto: graficando la poblaci贸n de un pa铆s

41

Reto: graficando la poblaci贸n mundial

Pr贸ximos pasos

42

隆Conoce otros proyectos de este curso!

43

Reconoce tu proceso y certif铆cate

44

Toma el Curso de PIP y Entornos Virtuales con Python

No tienes acceso a esta clase

隆Contin煤a aprendiendo! 脷nete y comienza a potenciar tu carrera

Playgrounds: Lee un CSV para calcular el total de gastos

38/44

Aportes 276

Preguntas 3

Ordenar por:

驴Quieres ver m谩s aportes, preguntas y respuestas de la comunidad?

o inicia sesi贸n.

Aporto mi soluci贸n:

def read_csv(path):
   with open(path, 'r') as csvfile:      
      total = sum(int(r[1]) for r in csv.reader(csvfile))
      return total

response = read_csv('./data.csv')
print(response)

Hola, dejo una soluci贸n utilizando la funci贸n de orden superior reduce:

import csv
import functools

def read_csv(path):
   # Tu c贸digo aqu铆 馃憞
   with open(path) as csvfile:
      reader = csv.reader(csvfile, delimiter=',')
      data = list()
      for line in reader:
         data.append(int(line[1]))
   total = functools.reduce(lambda x,y: x+y, data)
   return total

response = read_csv('./data.csv')
print(response)

Mi soluci贸n, creo que queda m谩s eficiente haciendo la l贸gica de la suma directamente en vez de convertir los datos a lista para despu茅s usar la funci贸n ya incluida

import csv

def read_csv(path):
   sum = 0
   with open(path, 'r') as csvfile:
      reader = csv.reader(csvfile)
      for data_set in reader:
         sum += int(data_set[1])
   return sum
   
sum_csv = read_csv('./data.csv')
print(sum_csv)

Aqui es donde se pone bueno todo esto, las diferentes respuestas de todos ustedes me molan

Espero que les sirva:

import csv

def read_csv(path):
   with open(path, 'r') as csvfile:
      reader = csv.reader(csvfile, delimiter= ",")
      dic = { j: k for j,k in reader}
      total = 0
      for valor in dic.values():
         total += int(valor)
      
      return int(total)
response = read_csv('./data.csv')
print(response)

Aqui mi solucion al reto:

def read_csv(path):
   total = 0
   with open(path, 'r', encoding='utf-8') as f:
      data = csv.reader(f)
      for _, val in data:
         total += int(val)

   return total

Aqu铆 les comparto mi soluci贸n:

import csv

def read_csv(path):
   with open(path, 'r') as csvfile:
      reader = csv.reader(csvfile, delimiter=',')
      total = [int(row[1]) for row in reader]
   return sum(total)

response = read_csv('./data.csv')
print(response)

my solucion

import csv

def read_csv(path):
   # Tu c贸digo aqu铆 馃憞
   with open (path,"r") as csvfile:
      reader = csv.reader(csvfile,delimiter=",") 
      total_num=[]        
      for row in reader:     
         total_num.append(int(row[1]))  
        
     
   total= sum(total_num)     
   
   return total

response = read_csv('./data.csv')
print(response)

Aporto mi soluci贸n:

import csv

def read_csv(path):
   # Tu c贸digo aqu铆 馃憞
   total = 0
   with open(path, 'r') as csvfile:
      reader = csv.reader(csvfile, delimiter=',')
      for row in reader:
         total += int(row[1])
   return total

response = read_csv('./data.csv')
print(response)

Este ejercicio me pareci贸 perfecto para aplicar la funci贸n reduce aprendida en clases anteriores

import csv
import functools

def read_csv(path):
   with open(path) as csvfile:
      reader = csv.reader(csvfile, delimiter = ',')
      total = functools.reduce(lambda acc, row: acc + int(row[1]), reader, 0)
      return total

response = read_csv('./data.csv')
print(response)
import csv

def read_csv(path):
   # Tu c贸digo aqu铆 馃憞
   with open(path, 'r') as archivoCSV:
      archivo = csv.reader(archivoCSV, delimiter = ',')
      total = sum(int(fila[1]) for fila in archivo)
   return total

response = read_csv('./data.csv')
print(response)

Aqu铆 mi soluci贸n. Muy complicada creo en mi opinion jejeje

import csv

def run():
    def read_csv(path):
        with open(path, "r") as file:
            reader = csv.reader(file, delimiter=",")
            dicty = {x:y for x,y in reader}
            return dicty
    dicty = read_csv("./data.csv")
    print(dicty)
    result = int(dicty["Administration"]) + int(dicty["Marketing"]) + int(dicty["Purchasing"]) + int(dicty["Human Resources"]) + int(dicty["Shipping"]) + int(dicty["IT"]) + int(dicty["Public Relations"]) + int(dicty["Sales"]) + int(dicty["Executive"]) + int(dicty["Finance"])
    print(f"El precio total es {result}") 

if __name__ == "__main__":
    run()
import csv

def read_csv(path):
   # Tu c贸digo aqu铆 馃憞
   with open(path, 'r') as csv_file:
      reader = csv.reader(csv_file)
      # print(reader)
      total = sum(int(r[1]) for r in reader)
   return total

response = read_csv('./data.csv')
print(response)
import csv

def read_csv(path):
   total = 0
   with open(path, 'r') as csvfile:
      reader = csv.reader(csvfile, delimiter=',')
      for row in reader:
         total += int(row[1])
   return total

response = read_csv('./data.csv')
print(response)

Quise ponerle un encabezado a la data del archivo csv y trabajar con ello:

import csv

def read_csv(path):
       with open(path, 'r') as csvfile:
        data = []
        for row in csvfile:
            row = row.rstrip('\n')
            columns = row.split(',')
            area = columns[0]
            expenses = int(columns[1])
            data.append({
                'Area': area,
                'Expenses': expenses
            })
            expenses = sum(list(map(lambda item: item['Expenses'], data)))
        return expenses
           
if __name__ == '__main__':
    data = read_csv('./data2.csv')
    print(data)
import csv

def read_csv(path):
   lista=[]
   with open(path,"r") as file :
      reader = csv.reader(file,delimiter = ",")
      header = ["Area", "Gasto"]
      for linea in reader:
         iterable=zip(header,linea)
         dic = {key:valor for (key,valor) in iterable}
         lista.append(dic)
   gastos = [lis["Gasto"] for lis in lista]
   gastos = list(map(lambda x : int(x),gastos))
   total = sum(gastos)
   return total

response = read_csv('./data.csv')
print(response)
Mi soluci贸n fue esta: ```js import csv def read_csv(path): # Tu c贸digo aqu铆 馃憞 my_list = [] with open(path, 'r') as csvfile: reader = csv.reader(csvfile, delimiter=',') for item in reader: my_list.append(int(item[1])) total = sum(my_list) return total response = read_csv('./data.csv') print(response) ```
```python import csv def read_csv(path): total = 0 with open(path, 'r') as file: csv_reader = csv.reader(file) for row in csv_reader: total += int(row[1]) return total response = read_csv('./data.csv') print(response) ```
![](https://static.platzi.com/media/user_upload/image-c7382749-9430-424f-8b46-a410899aab75.jpg)
creo que una soluci贸n optima y que ademas no utiliza for es esta ```python import csv def read_csv(path): # Tu c贸digo aqu铆 馃憞 total = 0 with open(path,'r') as file: reader = csv.reader(file, delimiter=',') total += sum(int(header[1]) for header in reader) return total response = read_csv('./data.csv') print(response) ```
```python import csv def read_csv(path): # Tu c贸digo aqu铆 馃憞 with open(path, 'r') as csvfile: reader = csv.reader(csvfile,delimiter=',') sum = { key: value for key, value in reader} total = 0 for valor in sum.values(): total += int(valor) return int(total) response = read_csv('./data.csv') print(response) ```

Esta fue mi solucion aplicando un reduce

import csv
import functools


def read_csv(path):
   with open(path, 'r') as csvfile:
      reader = csv.reader(csvfile, delimiter=',')
      total = functools.reduce(
         lambda counter, item: counter + int(item[1]),
         reader, 
         0
      )
      return total

response = read_csv('./data.csv')
print(response)
Compa帽eros, esta fue mi soluci贸n: ```js import csv def read_csv(path): # Tu c贸digo aqu铆 馃憞 total = 0 with open(path, 'r') as csvfile: reader = csv.reader(csvfile, delimiter = ',') lista = list(reader) for i in range(len(lista)): total = total + int(lista[i][-1]) return total response = read_csv('./data.csv') print(response) ```import csv def read\_csv(path):聽 聽# Tu c贸digo aqu铆 馃憞聽 聽total = 0聽 聽with open(path, 'r') as csvfile:聽 聽 聽 reader = csv.reader(csvfile, delimiter = ',')聽 聽 聽 lista = list(reader)聽 聽 聽 for i in range(len(lista)):聽 聽 聽 聽 聽total = total + int(lista\[i]\[-1])聽 聽return total response = read\_csv('./data.csv')print(response)
Esta fue mi soluci贸n ```js import csv def read_csv(path): # Tu c贸digo aqu铆 馃憞 total=0 with open(path,"r") as csvfile: reader=csv.reader(csvfile, delimiter=",") for x in reader: x[1]=int(x[1]) total+=x[1] return total response = read_csv('./data.csv') print(response) ```import csv def read\_csv(path):聽 聽# Tu c贸digo aqu铆 馃憞聽 聽total=0聽 聽with open(path,"r") as csvfile:聽 聽 聽 reader=csv.reader(csvfile, delimiter=",")聽 聽 聽 for x in reader:聽 聽 聽 聽 聽x\[1]=int(x\[1])聽 聽 聽 聽 聽total+=x\[1]聽 聽return total response = read\_csv('./data.csv')print(response)
# Importar el m贸dulo csv para trabajar con archivos CSV
import csv

# Definir una funci贸n para leer un archivo CSV y calcular la suma de la segunda columna
def read_csv(path):

	# Abrir el archivo CSV en modo lectura ('r')
	with open(path, 'r') as csv_file:

    	    	# Utilizar csv.reader para leer las filas del archivo
    	    	# y sumar los valores de la segunda columna (铆ndice 1)
    	    	total = sum(int(row[1]) for row in csv.reader(csv_file))

    	    	# Devolver el resultado de la suma
    	    	return total

# Llamar a la funci贸n con el path del archivo CSV y almacenar el resultado en 'response'
total_gastos = read_csv('./data.csv')

# Imprimir el resultado obtenido al leer y procesar el archivo CSV
print(total_gastos)

Me pareci贸 complejo pero viendo sus respuestas no estaba tan complejo 馃様馃槗

Excelente reto. Mi solucion



```js import csv def read_csv(path): # Tu c贸digo aqu铆 馃憞 with open(path) as file: return sum([int(line[1]) for line in csv.reader(file)]) response = read_csv('./data.csv') print(response) ```
import csv
import functools

def read_csv(path):
   with open(path, 'r') as data_csv:
      reader = csv.reader(data_csv, delimiter=',')
      diccionario = dict(reader)
      valores = diccionario.values()
      valores_int  = list(map(int, valores))
      suma = functools.reduce(lambda a , b: a + b, valores_int)
      print(suma)
      total = suma
      return total
     
response = read_csv('./data.csv')
print(response)

Mi soluci贸n usando las funciones map() y filter()

Esto hice: ```python import csv def read_csv(path): # Tu c贸digo aqu铆 馃憞 with open(path, 'r') as csvfile: reader = csv.reader(csvfile, delimiter=',') total = 0 for i in reader: total += int(i[1]) return total response = read_csv('./data.csv') print(response) ```
Esta es mi soluci贸n del Playgrounds, espero a alguien le sirva de ayuda. ```python import csv def read_csv(path): total = 0 with open(path, "r") as csv_file: reader = csv.reader(csv_file, delimiter=",") for i in reader: total += int(i[1]) return total response = read_csv('./data.csv') print(response) ```
Una peque帽a variante: ```js import csv from functools import reduce def read_csv(path): with open(path, 'r') as file: read_file = csv.reader(file) dict = {key: value for key, value in read_file} return reduce(lambda c, i: int(c) + int(i) ,dict.values()) response = read_csv('./data.csv') print(response) ```import csv from functools import reduce def read\_csv(path):聽 聽with open(path, 'r') as file:聽 聽 聽 read\_file = csv.reader(file)聽 聽 聽 dict = {key: value for key, value in read\_file}聽 聽 聽 return reduce(lambda c, i: int(c) + int(i) ,dict.values()) response = read\_csv('./data.csv')print(response)
```js data = [] def read_csv(path): with open(path, "r") as file: for line in file: data.append(int(line.split(",")[1])) return sum(data) response = read_csv('./data.csv') print(response) ```Hice un enfoque diferente sin usar el modulo de csv.
Mi soluci贸n:import csv def read\_csv(path):聽 聽# Tu c贸digo aqu铆 馃憞聽 聽total = 0 聽 聽with open(path, 'r') as csvfile:聽 聽 聽 reader = csv.reader(csvfile, delimiter=',')聽 聽 聽 for row in reader:聽 聽 聽 聽 聽total += int(row\[1])聽 聽聽 聽return total response = read\_csv('./data.csv')print(response) ```python import csv def read_csv(path): # Tu c贸digo aqu铆 馃憞 total = 0 with open(path, 'r') as csvfile: reader = csv.reader(csvfile, delimiter=',') for row in reader: total += int(row[1]) return total response = read_csv('./data.csv') print(response) ```
Aport贸 mi humilde soluci贸n: ![](https://static.platzi.com/media/user_upload/image-00e615d4-33d8-46e6-961e-d10838237bab.jpg)![]()

Esta fue mi soluci贸n:

def read_csv(path):
   total = 0
   with open('./data.csv', 'r') as file:
      reader = csv.reader(file, delimiter=',')
      for line in reader:
         #print(line)
         total += int(line[1])
   return total 
Mi soluci贸n: ```python import csv def read_csv(path): with open(path, 'r+') as file: reader = csv.reader(file, delimiter=',') total = 0 for i in reader: total += int(i[1]) return total response = read_csv('./data.csv') print(response) ```
![](https://static.platzi.com/media/user_upload/image-2e0d6eab-bf7e-46d8-b52a-4d890c843014.jpg)
import csvimport functools def read\_csv(path):聽 聽# Tu c贸digo aqu铆 馃憞聽 聽with open(path,'r') as f:聽 聽 聽 r = csv.reader(f,delimiter = ',')聽 聽 聽 total = functools.reduce(lambda x,y:x\[1]+y\[1],r)聽 聽#total = 0聽 聽 聽 return total response = read\_csv('./data.csv')print(response)
Hola. aporto mi soluci贸n![](file:///C:/Users/loper/OneDrive/Desktop/solucion_.jpg)![](https://static.platzi.com/media/user_upload/kE3yaxH%20-%20Imgur-e93ef491-47b3-405c-8bd4-f7c34e713f9c.jpg)![](https://imgur.com/a/S8Zm4ru)![]()![](file:///C:/Users/loper/OneDrive/Desktop/solucion.png)![](file:///C:/Users/loper/OneDrive/Desktop/solucion.png)![](file:///C:/Users/loper/OneDrive/Desktop/solucion.png)
import csv

def read_csv(path):
   # Tu c贸digo aqu铆 馃憞
   with open(path, 'r') as csvfile:      
      total = sum(int(r[1]) for r in csv.reader(csvfile))
      return total

response = read_csv('./data.csv')
print(response)

Mi aporte

import csv

def read_csv(path):
   # Tu c贸digo aqu铆 馃憞
   total = 0
   with open(path, 'r') as csvfile:
      reader = csv.reader(csvfile, delimiter = ',')
      for line in reader:
         total += int(line[1])
   return total

response = read_csv('./data.csv')
print(response)
```js import csv, functools def read_csv(path): with open(path, 'r') as csvfile: reader = csv.reader(csvfile, delimiter = ',') header = ['area', 'gasto'] total = 0 for row in reader: iterable = zip(header, row) # combina dos listas en tuplas area_dict = {key:value for key,value in iterable} # dictionary comprehension total += int(area_dict['gasto']) return total if __name__=='__main__': response = read_csv('data.csv') print(response) ```import csv, functools def read\_csv(path):聽 聽 with open(path, 'r') as csvfile:聽 聽 聽 聽 reader = csv.reader(csvfile, delimiter = ',')聽 聽 聽 聽 header = \['area', 'gasto']聽 聽 聽 聽 total = 0聽 聽 聽 聽 for row in reader:聽 聽 聽 聽 聽 聽 iterable = zip(header, row) # combina dos listas en tuplas聽 聽 聽 聽 聽 聽 area\_dict = {key:value for key,value in iterable} # dictionary comprehension聽 聽 聽 聽 聽 聽 total += int(area\_dict\['gasto'])聽 聽 聽 聽 return total聽 聽 聽 聽 if \_\_name\_\_=='\_\_main\_\_':聽 聽 response = read\_csv('data.csv')聽 聽 print(response)

Muchachos aporto mi solucion al problema :}
def read_csv(path):
total = 0
with open(path,鈥榬鈥) as csvfile:
reader = csv.reader(csvfile, delimiter=鈥,鈥)
data = []
nums = []
country_dict = {key:value for key,value in reader}
valores = country_dict.values()
lista_de_valores = list(valores)
for i in range(0,4):
nums.append(lista_de_valores[i])
resultado = sum(map(int, nums))
return resultado

response = read_csv(鈥.import csv/data.csv鈥)
print(response)

Quiero aclarar que el chat fue de suma importancia para imprimir el dict que nos lleva a la clave valor de todos los datos, aprecio sus aportes!

```python import csv import functools def suma(val1,val2): return val1 + val2 def read_csv(path): with open(path,'r') as f: reader = csv.reader(f,delimiter=',') results = functools.reduce(suma,[int(i[1]) for i in reader]) print(results) return results response = read_csv('./data.csv') print(response) ```aqui esta mi respuesta usando list comprehension y la funcion reduce()
import csv

def read_csv(path):
#Tucodigo aqu铆:
    total = 0
    with open(path, "r") as csvFile:
        reader = csv.reader(csvFile) 
        for data in reader:
            total += int(data[1])
    return total

response = read_csv('./data.csv')
print(response)
import csv

def read_csv(path):
    total = 0  
    try:
        with open(path, 'r') as csvfile:
            reader = csv.reader(csvfile, delimiter=',') 
            header = next(reader)  
            for row in reader:
               
                gasto_anual = int(row[1])
                total += gasto_anual  

    except FileNotFoundError:
        print(f'El archivo {path} no existe.')
    except csv.Error as e:
        print(f'Error al leer el archivo {path}: {e}')

    return total

if __name__ == '__main__':
    response = read_csv('./data.csv')  # Llamamos a la funci贸n con la ruta del archivo CSV
    print(response)  # Imprimimos el total de gastos de la empresa

1299

Les comparto aca mi soluci贸n:

import csv

def read_csv(path):
   with open(path, 'r') as csvfile:      
      reader = csv.reader(csvfile, delimiter=",")
      lista = []
      for row in reader:
         lista.append(int(row[1]))

      total = sum(lista)
   return total

response = read_csv('./data.csv')
print(response)

Esta es mi soluci贸n

import csv
import functools
def read_csv(path):
   # Tu c贸digo aqu铆 馃憞
   with open(path, 'r') as csvfile:
      filter_reader = functools.reduce(lambda counter, item: counter + item,list(map(lambda i:int(i),list((map(lambda item:item[1], list(csv.reader(csvfile, delimiter=','))))))))          
   return filter_reader

response = read_csv('./data.csv')
print(response)
import csv

def read_csv(path):
   with open(path,'r') as csvfile:
      reader=csv.reader(csvfile,delimiter=',')
      data=[]
      for row in reader:
         data.append(int(row[1]))
    
   total = sum(data)
   return total

response = read_csv('./data.csv')
print(response)

Mi soluci贸n original:

import csv

def read_csv(path):
   with open(path, 'r') as csvfile:
      reader = csv.reader(csvfile, delimiter=',')  
      total = 0

      for row in reader:
         total += int(row[1])
      return total
      
response = read_csv('./data.csv')
print(response)

despu茅s de ver comentarios:

import csv

def read_csv(path):
   with open(path, 'r') as csvfile:
      reader = csv.reader(csvfile, delimiter=',')  
      total = sum(int(row[1]) for row in reader)

      return total

response = read_csv('./data.csv')
print(response)

Mis soluci贸n, en parte inspirada en un comentario que v铆, pero me pareci贸 mejor desglosarlo para entender bien que es lo que estaba ocurriendo. Dejo comentarios por si a alguien le sirve como a mi

import csv

def read_csv(path):
   # Tu c贸digo aqu铆 馃憞

   #primero que todo debo traer el archivo
   with open(path, 'r') as CSV_file:

      #creo el lector del csv
      reader = csv.reader(CSV_file, delimiter=',') 
      #esto me trae cada fila del archivo como una lista
      
      #extraigo los montos; list comprehension
      montos = [int(monto[1]) for monto in reader]
      #verifico que me traiga una lista de los montos (int)
      # print(montos)

      #sumo esos valores 
      suma_montos = sum(montos)
      return suma_montos

response = read_csv('./data.csv')
print(response)

import csv
import functools

def read_csv(path):
with open(path) as csvfile:
reader = csv.reader(csvfile, delimiter=鈥,鈥)
data = list()
for line in reader:
data.append(int(line[1]))
total = functools.reduce(lambda x,y: x+y, data)
return total

response = read_csv(鈥./data.csv鈥)
print(response)

Comparto mi soluci贸n

import csv

def read_csv(path):
   valores = []
   with open(path,"r") as csvfile:
      reader = csv.reader(csvfile)
      valores = list(int(i[1]) for i in reader)
   total = sum(valores)
   return total
response = read_csv('./data.csv')
print(response)

aqui la solucion mas simple que se me ocurrio:

import csv

def read_csv(path):
   with open(path, 'r') as csvfile:
      reader = csv.reader(csvfile, delimiter=',')
      total = 0
      for row in reader:
         total = total + int(row[1])
   return total

response = read_csv('./data.csv')
print(response)

Mi solucion:

import csv

def read_csv(path):
   # Tu c贸digo aqu铆 馃憞
   with open (path , 'r') as archivo:
       # Crea un objeto lector CSV
    lector_csv = csv.reader(archivo)    
    total = 0
    # Itera sobre las filas del archivo CSV
    for fila in lector_csv:
        total = total + int(fila[1])
   return total

response = read_csv('./data.csv')
print(response)

Utilizando reduce:

import csv
import functools

def read_csv(path):
   with open(path, 'r') as csv_file:
      total = functools.reduce(lambda contador, item: contador + int(item[1]), csv.reader(csv_file), 0)
      return total

response = read_csv('./data.csv')
print(response)

Mi aporte:

import csv

def read_csv(path):
   # Tu c贸digo aqu铆 馃憞
   with open(path, 'r') as csvfile:
      reader = csv.reader(csvfile, delimiter = ',')
      try:
         total = 0   
         while True:
            data = next(reader)
            total += int(data[1])    
      except StopIteration:
         pass
   return total

response = read_csv('./data.csv')
print(response)

Aqui otra manera de hacerlo.
Un tanto simplificada. Muy parecida al antertior.

import csv

def read_csv(path):
   # Tu c贸digo aqu铆 馃憞
   with open(path,'r') as csvfile:
      lectura = csv.reader(csvfile,delimiter=',')
      numbers = []
      for row in lectura:
        numbers.append(int(row[1]))
   return total = sum(numbers)   

response = read_csv('./data.csv')
print(response)

Esta fue mi soluci贸n a la prueba

import csv

def read_csv(path):
   # Tu c贸digo aqu铆 馃憞
   total = 0
   with open(path) as file:
      reader = csv.reader(file)
      for row in reader:
         total += int(row[1])
   return total

response = read_csv('./data.csv')
print(response)

Aporto mi respuesta:

import csv

def read_csv(path):
   total = 0
   with open(path,'r') as file:
      for line in file:
         total += int(line.rsplit(',',1)[1])
   return total

response = read_csv('./data.csv')
print(response)

Comparto mi aporte, la verdad me cost贸 mucho entender c贸mo aplicarlo, pero al final sirvi贸 para repasar sobre la comprensiones de listas.

Les recomiendo no pasar m谩s de 30 minutos resolvi茅ndolo solos, si exceden ese tiempo, les sugiero ver las respuestas, para aclarar ideas, y m谩s que nada realizar un repaso, despu茅s intenta crear tu propia soluci贸n y ser谩 m谩s f谩cil, recuerden que lo primordial es aprender.

Yo comparto la m铆a:

import csv
from functools import reduce

def read_csv(path):
   # Tu c贸digo aqu铆 馃憞
   total = 0
   with open(path, 'r') as csvfile:
      reader = csv.reader(csvfile, delimiter=',')
      figures = [int(x[1]) for x in reader]
      total = reduce(lambda x, y : x + y, figures) 
      

   return total

response = read_csv('./data.csv')
print(response)

Aporte

import csv

def read_csv(path):
   with open(path,'r') as csvfile:
      r=csv.reader(csvfile,delimiter=',')
      data=[int(row[1]) for row in r]          
   total = sum(data)
   return total

response = read_csv('./data.csv')
print(response)
import csv

def read_csv(path):
    with open(path,'r') as csvfile:
        return sum([float(row[1]) for row in csv.reader(csvfile)])
    


response = read_csv('./data1.csv')
print(response)
import csv
import functools

def read_csv(path):
   with open(path, 'r') as cvsfile:
      reader = csv.reader(cvsfile, delimiter=',')
      return functools.reduce(lambda acc, item: acc + int(item[1]), list(reader), 0)

response = read_csv('./data.csv')
print(response)

Mi soluci贸n:

import csv

def read_csv(path):

   with open(path,'r') as csvfile:
      reader = csv.reader(csvfile,delimiter = ',')
      data = {key:value for key,value in reader}
      numbers = [int(number) for number in data.values()]
      total = sum(numbers)
   
   return total

response = read_csv('./data.csv')
print(response)

Aporto mi humilde soluci贸n:

import csv

def read_csv(path):
   total = 0
   with open(path, 'r') as csvfile:
      reader = csv.reader(csvfile)
      for i in reader:
         total += int(i[1])
   return total

response = read_csv('./data.csv')
print(response)

Aporto mi soluci贸n 馃槂

import csv

def read_csv(path):
   total = 0
   with open(path, 'r') as csv_file:
      reader = list(csv.reader(csv_file))
      for row in reader:
         total += int(row[1])
   return total

response = read_csv('./data.csv')
print(response)```

Mi soluci贸n:

import csv

def read_csv(path):
   # Tu c贸digo aqu铆 馃憞
   with open(path, 'r+') as f:
      reader = list(csv.reader(f, delimiter=','))
      data = [int(row[1]) for row in reader]
      
   total = sum(data)
   return total

response = read_csv('./data.csv')
print(response)

Qu茅 tal este 馃槃

import csv

def read_csv(path):
   # Tu c贸digo aqu铆 馃憞
   total = 0
   with open(path, 'r') as csvfile:
      reader = csv.reader(csvfile)
      for datos in reader:
         total += int(datos[1])
   return total

response = read_csv('./data.csv')
print(response)

Este es mi c贸digo:

import csv

def read_csv(path):
   # Tu c贸digo aqu铆 馃憞
   with open(path, "r") as csvfile:
      total = 0
      reader = csv.reader(csvfile, delimiter=",")  
      for row in reader:
         total += int(row[1])
   return total

response = read_csv('./data.csv')
print(response)

My solution:

import csv
from functools import reduce
def read_csv(path):
   # Tu c贸digo aqu铆 
   with open(path) as file:
      reader = csv.reader(file, delimiter = ',');
      total = reduce(lambda count, row: int(row[1]) + count, list(reader), 0)
      return total

response = read_csv('./data.csv')
print(response)

Comparto mi soluci贸n, s茅 que no es la m谩s eficiente por lo que valoro mucho leer despu茅s la soluci贸n de quienes lo lograron en menos pasos.

import csv

def read_csv(path):
   total = 0
   with open(path, 'r') as csvfile:
      reader = csv.reader(csvfile, delimiter=',')
      reader = list(reader)
      gastos = []
      for i in range(len(reader)):
         gastos.append(int(reader[i][1]))
      total=sum(gastos)
   return total

response = read_csv('./data.csv')
print(response)

Aporto mi soluci贸n

import csv

def read_csv(path):
with open(path, 鈥榬鈥) as csvfile:
reader = csv.reader(csvfile, delimiter=鈥,鈥)
diccionario = dict(reader)

lista = []
total = 0
for i in diccionario.values():
  lista.append(int(i))
  
  total = sum(lista)
return total

response = read_csv(鈥./data.csv鈥)
print(response)

import csv

def read_csv(path):
   # Tu c贸digo aqu铆 馃憞
   with open(path) as f:
      fc = csv.reader(f,delimiter=',')
      header = ['Rubro','Costo']
      
      content = []
      total = 0
      for row in fc:
         iterable = zip(header, row)
         dicc = {key:value for key, value in iterable}
         
         total += int(dicc['Costo'])
      

      

      

   
   return total

response = read_csv('./data.csv')
print(response)
import csv

def read_csv(ruta):
    total = 0

    with open(ruta, 'r') as csvfile:
        reader = csv.reader(csvfile)
        next(reader)  # Saltar la primera fila de encabezado
        for row in reader:
            total += int(row[1])  # Sumar el total de gastos de cada fila

    return total

response = read_csv('./data.csv')
print(response)

test_case_1

test_case_2

test_case_3

隆Felicidades, todas las pruebas pasaron!

Mi soliucion.

import csv

def read_csv(path):
   # Tu c贸digo aqu铆 馃憞
   with open(path, 'r') as file:
      read = csv.reader(file, delimiter= ',')
      total = 0
      for row in read:
         # print(row)
         total += int(row[1]) 
      # print(total)
   return total

response = read_csv('./data.csv')
print(response)

Mi soluci贸n:

import csv

def read_csv(path):
   # Tu c贸digo aqu铆 馃憞
  with open(path, 'r') as csvfile:
    reader = csv.reader(csvfile, delimiter= ',')
    total = 0
    for row in reader:
      cost = int(row[1])
      total += cost
    return total

response = read_csv('./Playgrounds/data.csv')
print(response)

Esta mi soluci贸n:

import csv

def read_csv(path):
   # Tu c贸digo aqu铆 馃憞
   total = 0
   suma_gastos = 0
   with open(path, 'r') as csvfile:
      reader = csv.reader(csvfile, delimiter=',')
      header = ['Area','Gastos']
      data = []
      for row in reader:
         iterable = zip(header, row)
         data_dict = dict(iterable)
         data.append(data_dict)
   
   for dato in data:
    suma_gastos += int(dato['Gastos'])  
   return suma_gastos

response = read_csv('./data.csv')
print(response)

Aqui mi solucion:
.
.
.
.
.
.
.
.
.

import csv

def read_csv(path):
   # Tu c贸digo aqu铆 馃憞
   total = 0
   with open(path, 'r') as csvfile:
      reader = csv.reader(csvfile, delimiter=',')
      for row in reader:
         total += int(row[1])
   return total

Dejo mi aporte:

import csv

def read_csv(path):
   # Tu c贸digo aqu铆 馃憞
   with open(path, 'r') as csvdata:
      return sum(float(row[1]) for row in csv.reader(open(path), delimiter=','))

response = read_csv('./data.csv')
print(response)

Esta es mi soluci贸n.

import csv

def read_csv(path):
   # Tu c贸digo aqu铆 馃憞
   with open(path, 'r') as csvfile:
      
      reader = csv.reader(csvfile, delimiter = ",")
      gastos = []  # para acumular gastos
      
      for row in reader:
         gastos.append(int(row[1]))  # acumulando los gastos
   
   total = sum(gastos)  # suma de los gastos acumulados
   return total

response = read_csv('./data.csv')
print(response)
import csv
def read_csv(path):
  with open(path, 'r') as csvfile:
    reader = csv.reader(csvfile, delimiter =',')
    total = 0
    for row in reader:
      total += int(row[1])
  return total
if __name__ == "__main__":
  response = read_csv('./data.csv')
  print(response)
import csv

def read_csv(path): 
   with open(path,'r') as csvfile:
      a = []
      reader = csv.reader(csvfile,delimiter=',')
      reader = list(reader)
      for i in reader:
         a.append(int(i[1]))
   total = sum(a)
   return total

response = read_csv('./data.csv')
print(response)

Mi solucion:

import csv
import functools

def read_csv(path):
   total = 0
   with open('./data.csv', 'r') as csv_file:
      reader = csv.reader(csv_file, delimiter=',')

      for row in reader:
         total += int(row[1])

   return total

response = read_csv('./data.csv')
print(response)
import csv

def read_csv(path):
   gastos =[]
   with open(path, "r") as cvsfile:
      reader = csv.reader(cvsfile, delimiter = ",")
      for x, y in reader:
         gastos.append(int(y))
      
   total = sum(gastos)
   return total

response = read_csv('./data.csv')
print(response)

my respuesta:

import csv

def read_csv(path):
   # Tu c贸digo aqu铆 馃憞
   with open(path,'r') as csvfile:
      reader = csv.reader(csvfile, delimiter= ',')
      total = 0
      for row in reader:
        num = int(row[1])
        total += num
   return total
response = read_csv('./data.csv')
print(response)

Mi solucion:

import csv

def read_csv(path) :

   # Tu c贸digo aqu铆 馃憞
   with open(path, 'r') as csvfile:
      read=csv.reader(csvfile, delimiter=',')
      summ=[]
      for it in read:
         suma = int(it[1])
         summ.append(suma)
   total = sum(summ)
   return total

response = read_csv('./data.csv')
print(response)

.
.
.
.
.
.
.
.
.
.
.

import csv

def read_csv(path):
   # Tu c贸digo aqu铆 馃憞
   total = 0

   with open(path, 'r') as csv_file:
      csv_reader = csv.reader(csv_file)
        
      for row in csv_reader:
         # La primera columna contiene el nombre del 谩rea y la segunda columna contiene el total de gastos
         expenses = int(row[1])
         total += expenses

   return total

response = read_csv('./data.csv')
print(response)


Este ejercisio me parecio perfecto para hacerlo con list comprehension

def read_csv(path):
   # Tu c贸digo aqu铆 馃憞
   with open(path) as archivo:
      documento = csv.reader(archivo, delimiter=",")
      # print(next(documento)) 
      # Output: ['Administration', '200']
      gastos = [int(fila[1]) for fila in documento] 
      # print(gastos) 
      # Output: [200, 201, 114, 203, 121, 103, 204, 145, 100, 108]
      total = sum(gastos)
      return total
response = read_csv('./data.csv')
print(response)
import csv

def read_csv(path):
   with open(path, 'r') as csv_file:
    reader = csv.reader(csv_file, delimiter = ',')
    total = 0
    for row in reader:
      cost = int(row[1])
      total =  cost +  total
   return total

response = read_csv('./data.csv')
print(response)```

Este ejercicio no era tan dificil como realmente se puede pensar, la pr谩ctica es su mejor aliado en la programaci贸n, a continuaci贸n dejo mi soluci贸n:

import csv

def read_csv(path):
   # Tu c贸digo aqu铆 馃憞
   total = 0
   with open(path, 'r') as csvfile:
      reader = csv.reader(csvfile, delimiter=',')
      for row in reader:
         total += int(row[1])
   
   return total

response = read_csv('./data.csv')
print(response)

Comparto mi soluci贸n, me encantar铆a recibir retroalimentaci贸n del grupo:

Aporto mi soluci贸n:

import csv

def read_csv(path):
   # Tu c贸digo aqu铆 馃憞
   with open(path,'r') as f_csv:
      reader = csv.reader(f_csv,delimiter=',')
      data = []
      for row in reader:
         data.append(int(row[1]))
   total = sum(data)
   return total

response = read_csv('./data.csv')
print(response)
undefined