Critique of code on a problem

Hi all, looking for some critique of the way I solved a particular problem. Particularly, if there is a way to do it better. I’m posting the problem and my solution below. If you don’t mind, can you post more efficient ways of solving it and why it is more efficient than the way I solved it? Thank you so much!

#What is the total number of birds counted on sites with codes beginning with C?


data_sites_and_birds_counted = [['A1', 28], ['A2', 32], ['A3', 1], ['A4', 0],
        ['A5', 10], ['A6', 22], ['A7', 30], ['A8', 19],
		['B1', 145], ['B2', 27], ['B3', 36], ['B4', 25],
		['B5', 9], ['B6', 38], ['B7', 21], ['B8', 12],
		['C1', 122], ['C2', 87], ['C3', 36], ['C4', 3],
		['D1', 0], ['D2', 5], ['D3', 55], ['D4', 62],
		['D5', 98], ['D6', 32]]

counter = 0
for n in data_sites_and_birds_counted:
	if n[0][0] == 'C':
		counter = counter + 1
print(counter)

It looks like you are counting not number of birds, but actually number of sites.

One approach would be to create an empty list
Loop through main list checking if the inner list index 0 starts with C
If it does append index 1 to empty list
Then get a sum of the empty list

1 Like

Okay. I redid the exercise. And I’d like to ask the same question. Is there a more efficient way to the write this? I think this is pretty good because I’m asking directly for an element (‘C’) and searching for just that element.

data = [['A1', 28], ['A2', 32], ['A3', 1], ['A4', 0],
        ['A5', 10], ['A6', 22], ['A7', 30], ['A8', 19],
		['B1', 145], ['B2', 27], ['B3', 36], ['B4', 25],
		['B5', 9], ['B6', 38], ['B7', 21], ['B8', 12],
		['C1', 122], ['C2', 87], ['C3', 36], ['C4', 3],
		['D1', 0], ['D2', 5], ['D3', 55], ['D4', 62],
		['D5', 98], ['D6', 32]]

birds = []
let = 'C'

for n in data:
	if let in n[0]:
		birds.append(n[1])
	result = sum(birds)
print(result)
		

Yes, there is a way without creating birds list and without using sum and append

You can just use simple counter, like you did in the first version, just slightly change this line:

1 Like

One way:

data = [['A1', 28], ['A2', 32], ['A3', 1], ['A4', 0],
        ['A5', 10], ['A6', 22], ['A7', 30], ['A8', 19],
		['B1', 145], ['B2', 27], ['B3', 36], ['B4', 25],
		['B5', 9], ['B6', 38], ['B7', 21], ['B8', 12],
		['C1', 122], ['C2', 87], ['C3', 36], ['C4', 3],
		['D1', 0], ['D2', 5], ['D3', 55], ['D4', 62],
		['D5', 98], ['D6', 32]]

total = 0
for birds in data:
    if birds[0].startswith('C'):
        total += birds[1]
print(f'Total Birds for C is {total}')

And if you want all

from tabulate import tabulate
data_sites_and_birds_counted = [['A1', 28], ['A2', 32], ['A3', 1], ['A4', 0],
        ['A5', 10], ['A6', 22], ['A7', 30], ['A8', 19],
		['B1', 145], ['B2', 27], ['B3', 36], ['B4', 25],
		['B5', 9], ['B6', 38], ['B7', 21], ['B8', 12],
		['C1', 122], ['C2', 87], ['C3', 36], ['C4', 3],
		['D1', 0], ['D2', 5], ['D3', 55], ['D4', 62],
		['D5', 98], ['D6', 32]]

# Create data variable. Easier to type the the long one
data = data_sites_and_birds_counted

# Create an empty dict to hold key, value data
# Create a counter variable to hold bird count
# Create empty list to use for getting total count per site
adict = {}
counter = 0
vals = []

# Create the key, values for our dict
# Key will be the letters A-D
# Value will be an empty list
for i in range(len(data)): # Get the length of data
    letter = data[i][0][:1] # Get the letter of site using string slice
    if letter not in adict.keys(): # Check if the letter is already in the dict if not set the key
        adict[letter] = [] # Set letter value to empty list
    if data[i][0].startswith(letter): # If the the starts with letter append the counts for that site
        adict[letter].append(data[i][1])

# Loop through the dict to append totals
for key, value in adict.items():
    vals.append(sum(value))
    counter += sum(value)

# List comp to get the headers for list display
headers = [f'Station: {key.strip()}' for key in adict.keys()]

headers.append('All Stations') # Adding header for total count of all stations
vals.append(sum(vals)) # Getting total of all stations

# Using tabulate for display
print(tabulate([vals], headers, tablefmt='fancy_grid', numalign='center'))

print()

# Print out data without using tabulate
data = dict(zip(headers, vals))
for k, v in data.items():
    print(k, v)

output:

Station: A 142
Station: B 313
Station: C 248
Station: D 252
All Stations 955

Yes, I’ll work with this. It’s much more challenging.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.