Hi, I’m quite new to programming. But I am aware that there’s this thing called “efficient code”. For this practice problem, I’ve came up with two solutions. My concern is, in terms of efficiency which one is more efficient ? I don’t have a full grasp of understanding how the computer stores this or something.
And also, any tips to keep in mind when thinking about the efficiency of your code ? Like for instance, in one of the lessons here at dataquest where they tackled about using multiple ‘ifs’. If we use ‘if’ multiple times, the computer will check the result multiple times as well even though we satisfy the first ‘if’.
My two code solution for this practice problem is stated below.
def check_unique_values(csv_filename, col_name):
from csv import reader
file = open(csv_filename)
read = reader(file)
data = list(read)
column = data[0]
rows = data[1:]
if col_name not in column:
return None
information = dict()
if col_name in column:
for i in rows:
information[i[column.index(col_name)]] = information.get(i[column.index(col_name)], 0) + 1
if len(information) == len(data)-1:
return True
elif len(information) != len(data)-1:
return False
print(check_unique_values('users.csv','email'))
def check_unique_values(csv_filename, col_name):
from csv import reader
file = open(csv_filename)
read = reader(file)
data = list(read)
column = data[0]
rows = data[1:]
for x in rows:
if col_name in column and col_name not in information:
information[col_name] = [x[column.index(col_name)]]
elif col_name in information and col_name in column:
information[col_name].append(x[column.index(col_name)])
else:
return None
if len(set(information[col_name])) == (len(data)-1):
return True
else:
return False