How do you approach this problem and break it down.
I've seen problems like this solved by looping through the file twice, because they answer one question at a time...
But I'm hoping there is something out there that can teach the general process of breaking down the problem, identifying loops, identifying generalizable code, and anything else that needs to happen before your code can work.
# assuming file with $100\n$200\n$23\n$50 etc.
linenum_vals = []
with open('numbers.txt') as input_file:
for i, line in enumerate(input_file):
try:
linenum_vals.append([i, float(line[:-1][1:])])
except ValueError:
print("Not a number value on line", i)
total = 0
for i in linenum_vals:
total += i[1]
half = total/2.0
for p in range(len(linenum_vals)):
if linenum_vals[p][1] == half:
print("Half of total found on line", linenum_vals[p][0])
break
else:
if linenum_vals[p-1][1] < half and linenum_vals[p][1] > half:
print("Half of total in between lines", p-1, p)
break
else:
if p+1 != len(linenum_vals):
if linenum_vals[p][1] < half and linenum_vals[p+1][1] > half:
print("Half of total in between lines", p, p+1)
break
print("Half of total wasn't found in the file.") # probably because the list of values isn't in order
What way would you do it? I feel like I'm missing something.I don't have any specific implementation - or if this idea would even work - but I do think sorting the lines first might be of help toward a better solution (I could be completely wrong on this). As well as tackling the totaling and checking from both ends of the list.
You'd have to keep track of everything, of course, in order to know at the end where in the -real list- (unsorted) the half-way total point is at. If this idea has any merit at least.
At the end, return the highest key in the dictionary for your total, and then run a reduce that returns the first key/value pair that is >= half the total
solving a problem: write a program that does (some open-ended business problem). Or generalize the socket listener so that it works on any platform, OS, hardware, network configuration, etc.
A coder might do great on confined problem space, but when you ask them to write a larger program they dont normally know how to design it. This isn't just true of bootcamp coders though. Tons of CS grads wouldn't do any better. Otherwise FizzBuzz would have never been a thing.
- When you have multiple layers of "companies" ( in a single table: Company) and every company has employees (table: Employee).
Request:
- List all company employees that have a random company as mother company, including their childs, all layers deep.
So you create a optional integer parentCompanyId on the Company for the inheritance ( that's easy)
How would you go further?
- You may not use a recursion of sql Queries (or in code) to procedurally get the parentCompany or "child companies" of all layers deep.
- You may change the database ( and you may use joins also)