Open Side Menu Go to the Top
Register
Programming homework and newbie help thread Programming homework and newbie help thread

09-10-2015 , 11:12 PM
Quote:
Originally Posted by Roonil Wazlib
I'm sure there are better ways of figuring it out like e i pi says, just using a formula of some sort instead of iterating over every single permutation.
I was thinking of the "diet problem" where you minimize total cost of food but still meet some minimum vitamin/nutrient conditions. It doesn't really apply to your problem though they're sort of related.
Programming homework and newbie help thread Quote
09-11-2015 , 10:09 AM
Quote:
Originally Posted by Roonil Wazlib
Also, it doesn't quite feel right using removeFood with an anonymous new instance of each food subtype, so that's probably wrong, too.
Yeah, that looked weird at first glance.

What I would do is stop using subclasses for each food type and just add a name data member to the food class. Then you can implement removeFood like so:

Code:
public void removeFood(String foodName) {
  for (Food f:foods) {
    if (f.getName().equals(foodName)) {
      foods.remove(f);
    }
  }
}
Working with only one class type will also simplify your nested loop. There really is no reason to subclass an object if the only purpose of the subclass is to distinguish between instances.

Last edited by Wolfram; 09-11-2015 at 10:38 AM.
Programming homework and newbie help thread Quote
09-11-2015 , 10:58 AM
another good point

mind you, i was particularly sleep deprived when i wrote this, and did no pre-planning whatsoever.
Programming homework and newbie help thread Quote
09-12-2015 , 11:51 PM
Food problem has strong similarities to the "knapsack problem". I spent some time a while back looking at efficient solutions for it but they were a bit tricky so I wound up just implementing it the dumb and slow way that becomes untenable once you get to 20-something items.
Programming homework and newbie help thread Quote
09-13-2015 , 01:19 AM
It sounds like "knapsack" and no, there are no known efficient and exhaustive solutions for it as it is NP-complete.
Programming homework and newbie help thread Quote
09-16-2015 , 12:35 AM
I'm completing Pset 6 from MIT OCW 6.00SC with Python 2.7. When I call runSimulation, I get intermittent KeyError messages(traceback included):

http://dpaste.com/01SFB9N

The text before the the traceback indicates that runSimulation called by showPlot2 completed successfully for the first five rooms and then failed for the sixth. In other tests, I get KeyError after 2 or 3 calls to runSimulation. The function inputs are the same for all tries. Here is my full code:

http://dpaste.com/3XV61BD

What is causing intermittent KeyError in cleanTileAtPosition?

Also, besides this thread, where is the best place to ask about programming homework questions?
Programming homework and newbie help thread Quote
09-16-2015 , 05:10 AM
Quote:
Originally Posted by Jeff W
I'm completing Pset 6 from MIT OCW 6.00SC with Python 2.7. When I call runSimulation, I get intermittent KeyError messages(traceback included):

http://dpaste.com/01SFB9N

The text before the the traceback indicates that runSimulation called by showPlot2 completed successfully for the first five rooms and then failed for the sixth. In other tests, I get KeyError after 2 or 3 calls to runSimulation. The function inputs are the same for all tries. Here is my full code:

http://dpaste.com/3XV61BD

What is causing intermittent KeyError in cleanTileAtPosition?

Also, besides this thread, where is the best place to ask about programming homework questions?
I did a quick look, how does the variable animate get set to True.

This code
Code:
animate = False
if animate == True :
   import ps6_visualize
implies to me that animate is getting set outside of runSimulation. Is that correct? I will look more closely when I have more time.
Programming homework and newbie help thread Quote
09-16-2015 , 05:25 AM
Quote:
Originally Posted by adios
I did a quick look, how does the variable animate get set to True.

This code
Code:
animate = False
if animate == True :
   import ps6_visualize
implies to me that animate is getting set outside of runSimulation. Is that correct? I will look more closely when I have more time.
You can just ignore animate and all associated code lines. It's an optional visualization module and it's only True if I set it to True manually.
Programming homework and newbie help thread Quote
09-16-2015 , 11:59 AM
Quote:
Originally Posted by Jeff W
You can just ignore animate and all associated code lines. It's an optional visualization module and it's only True if I set it to True manually.
In showPlot2
Code:
room_trials = {}
...
room_trials[temp] = runSimulation(num_robots, speed, width, height, min_coverage, num_trials, robot_type)
in runSimulatio
Code:
trials = 0
...
trials += 1
...
return trials
Doesn't look right to me in that this is the way you are returning a dictionary entry. This stackoverflow link might shed some light. I am not a python expert at all but how do we know what the keys are for your dictionary room_trials? I guess the key could be NULL and it just has many values. Not sure that is what you want and I don't know how numpy handles that kind of dictionary input.

Returning a Dictionary in Python

Last edited by adios; 09-16-2015 at 12:13 PM.
Programming homework and newbie help thread Quote
09-16-2015 , 01:19 PM
It looks like the sim is succeeding on all six, but you have a off-by-one error on line 333, so you are running one extra simulation, which is using whatever variables were left over from a previous run, and those are throwing an error.
Programming homework and newbie help thread Quote
09-16-2015 , 04:57 PM
by the way, to prevent the off-by-one error from happening again, use unpacking:

http://stackoverflow.com/questions/7...o-lists-tuples

using range(len(x) - 1) is "unpythonic." It isn't bad to know this convention and be aware of it, especially when moving to other languages, but in Python, you just don't do this stuff. range() should be used for generating a list of numbers. Everything else is undesirable, and has a better option in Python.

Also, note that everything in Python is an object. There are a lot of parts of Python that will bite you in the ass when you are dealing with state and objects, so just be aware of what you are mutating, how, and why.
Programming homework and newbie help thread Quote
09-16-2015 , 06:40 PM
Quote:
Originally Posted by daveT
It looks like the sim is succeeding on all six, but you have a off-by-one error on line 333, so you are running one extra simulation, which is using whatever variables were left over from a previous run, and those are throwing an error.
Code:
for i in range(len(room_list)):
Quote:
For loops

Usage in Python

When do I use for loops?
For loops are traditionally used when you have a piece of code which you want to repeat n number of times. As an alternative, there is the WhileLoop, however, while is used when a condition is to be met, or if you want a piece of code to repeat forever, for example -

For loop from 0 to 2, therefore running 3 times.


for x in range(0, 3):
print "We're on time %d" % (x)
Python Wiki

I think the for loop is ok plus he suspected that too and thus his print statements that followed.
Programming homework and newbie help thread Quote
09-16-2015 , 09:17 PM
Quote:
Originally Posted by adios
In showPlot2
Code:
room_trials = {}
...
room_trials[temp] = runSimulation(num_robots, speed, width, height, min_coverage, num_trials, robot_type)
in runSimulatio
Code:
trials = 0
...
trials += 1
...
return trials
Doesn't look right to me in that this is the way you are returning a dictionary entry. This stackoverflow link might shed some light. I am not a python expert at all but how do we know what the keys are for your dictionary room_trials? I guess the key could be NULL and it just has many values. Not sure that is what you want and I don't know how numpy handles that kind of dictionary input.
Hmm, I'm not sure what you mean. temp is assigned a tuple from the room list. room_trials[temp] = runSimulation(...) assigns the tuple to a key and assigns the integer return value of runSimulation to the value of the key.

Anyway, the error is occuring here afaict:

Code:
File "C:/Python27/Source/ps6/ps6.py", line 88, in cleanTileAtPosition
    if self.tile_status[x, y] == False: #Dirty
KeyError: (49.0, 4.0)
Afaict, a KeyError is being generated because that key isn't being found in self.tile_status, but the confusing part is that sometimes a given simulation with fixed inputs completes successfully and sometimes it generates a KeyError.
Programming homework and newbie help thread Quote
09-17-2015 , 05:25 AM
Quote:
Originally Posted by Jeff W
Hmm, I'm not sure what you mean. temp is assigned a tuple from the room list. room_trials[temp] = runSimulation(...) assigns the tuple to a key and assigns the integer return value of runSimulation to the value of the key.
Ok I see what the keys are.
Quote:
Anyway, the error is occurring here afaict:

Code:
File "C:/Python27/Source/ps6/ps6.py", line 88, in cleanTileAtPosition
    if self.tile_status[x, y] == False: #Dirty
KeyError: (49.0, 4.0)
Afaict, a KeyError is being generated because that key isn't being found in self.tile_status, but the confusing part is that sometimes a given simulation with fixed inputs completes successfully and sometimes it generates a KeyError.
Instead of initializing room_list with entries like (20,20) try (20.0, 20.0). I would do that for all of them. I wouldn't use keys like that but that is me.

Last edited by adios; 09-17-2015 at 05:45 AM.
Programming homework and newbie help thread Quote
09-17-2015 , 05:59 AM
I am worried about type conversions by the interpretor. Real numbers like 4.0 don't lend themselves to exact matches in something like a key look up. Integers like 4 do though and I realize Python is not strongly typed but "under the hood" it is. I realize you are using floor() though. You might try prints before and after floor.
Programming homework and newbie help thread Quote
09-18-2015 , 05:23 AM
Quote:
Originally Posted by adios
I am worried about type conversions by the interpretor. Real numbers like 4.0 don't lend themselves to exact matches in something like a key look up. Integers like 4 do though and I realize Python is not strongly typed but "under the hood" it is. I realize you are using floor() though. You might try prints before and after floor.
I think you're right that something is going wrong after I truncate the float to an int with math.floor. I just tried using int() instead of math.floor() and I have the same problem. The program works fine for thousands of trials before randomly failing at different points. To me, this suggests a bug in the interpreter but I'm just a newb. I tried to post this on stackexchange but they closed my post and said "code troubleshooting questions are off-topic here".

Oh well, the program is done except for the bug, I just can't run large numbers of trials for the last section without the error.
Programming homework and newbie help thread Quote
09-18-2015 , 06:13 PM
Quote:
Originally Posted by Jeff W
I think you're right that something is going wrong after I truncate the float to an int with math.floor. I just tried using int() instead of math.floor() and I have the same problem. The program works fine for thousands of trials before randomly failing at different points. To me, this suggests a bug in the interpreter but I'm just a newb. I tried to post this on stackexchange but they closed my post and said "code troubleshooting questions are off-topic here".

Oh well, the program is done except for the bug, I just can't run large numbers of trials for the last section without the error.
I actually like this code, logic looks good. I've got another idea.

Code:
       
        x = int(math.floor(pos.getX()))
        y = int(math.floor(pos.getY()))
Programming homework and newbie help thread Quote
09-19-2015 , 11:59 PM
Quote:
Originally Posted by adios
I actually like this code, logic looks good. I've got another idea.

Code:
       
        x = int(math.floor(pos.getX()))
        y = int(math.floor(pos.getY()))
I tried this, but I still get the KeyError, lol.

P.S. Can anyone tell me if MIT screwed up their problem specifications here(6.00SC Pset 8):

Quote:
Each ResistantVirus instance in the viruses list should be initialized with the following
parameters:

• resistances , The virus’s genetic resistance to drugs in the experiment =
{guttagonol:False}
Code:
    def reproduce(self, popDensity, activeDrugs):

        """
        If the virus particle is not resistant to any drug in activeDrugs,
        then it does not reproduce.
So, the model instantiates every ResistantVirus with no resistances and then the reproduce method never lets the Viruses reproduce. Wtf? There is a specification for virus offspring to become resistant through random mutations, but random mutation code can never be accessed.

Here is the full source code/problem specification fwiw:

http://dpaste.com/3X7A9JT

Last edited by Jeff W; 09-20-2015 at 12:19 AM.
Programming homework and newbie help thread Quote
10-06-2015 , 06:06 AM
Hi friends!

have a silly little concurrent programming question

Code:
#include <stdio.h>
#include <omp.h>

static long num_steps = 100000000;
double step;
double excecutionTime;
#define PAD 8
int main()
{
	double pi  = 0.0;
	double sum[4][PAD];
	sum[0][0] = 0.0;
	sum[1][0] = 0.0;
	sum[2][0] = 0.0;
	sum[3][0] = 0.0;
	step = 1.0/(double) num_steps;
	double timeStart = omp_get_wtime();

	#pragma omp parallel num_threads(4)
	{	
		int i;
		double x;
		int ID = omp_get_thread_num();
 		for (i = ID; i<num_steps;i=i+4)
		{
			x = (i+0.5)*step;
			sum[ID][0] = sum[ID][0] + 4.0/(1.0+x*x);
		}
	}
	double totalsum = sum[0][0]+sum[1][0]+sum[2][0]+sum[3][0];
	pi = step * totalsum;

	double timeFinish = omp_get_wtime();
	excecutionTime = timeFinish-timeStart;
	printf("pi = %f \n",pi);
	printf("executiontime = %fs \n",excecutionTime);
}
this is a quick little parallel implementation of the openmp "helloworld" and estimating pi by summing the integral of 4/(1+x^2) between 0 and 1

i've ran a serial implementation 10 times as well as this one, how come the serial implementation's execution time stayed at 1.2s all 10 times where as the parallel implementation went between 0.4s-0.9s(yeah, its faster, but the time it takes jumps all over the place). is there anyway to make the execution time more "stable"? did i do something wrong/or is there any important concepts that i'm missing?

i don't mind if u just give me a wikipedia page to read =)
Programming homework and newbie help thread Quote
10-06-2015 , 04:35 PM
Quote:
Originally Posted by CyberShark93
Hi friends!

have a silly little concurrent programming question

Code:
#include <stdio.h>
#include <omp.h>

static long num_steps = 100000000;
double step;
double excecutionTime;
#define PAD 8
int main()
{
	double pi  = 0.0;
	double sum[4][PAD];
	sum[0][0] = 0.0;
	sum[1][0] = 0.0;
	sum[2][0] = 0.0;
	sum[3][0] = 0.0;
	step = 1.0/(double) num_steps;
	double timeStart = omp_get_wtime();

	#pragma omp parallel num_threads(4)
	{	
		int i;
		double x;
		int ID = omp_get_thread_num();
 		for (i = ID; i<num_steps;i=i+4)
		{
			x = (i+0.5)*step;
			sum[ID][0] = sum[ID][0] + 4.0/(1.0+x*x);
		}
	}
	double totalsum = sum[0][0]+sum[1][0]+sum[2][0]+sum[3][0];
	pi = step * totalsum;

	double timeFinish = omp_get_wtime();
	excecutionTime = timeFinish-timeStart;
	printf("pi = %f \n",pi);
	printf("executiontime = %fs \n",excecutionTime);
}
this is a quick little parallel implementation of the openmp "helloworld" and estimating pi by summing the integral of 4/(1+x^2) between 0 and 1

i've ran a serial implementation 10 times as well as this one, how come the serial implementation's execution time stayed at 1.2s all 10 times where as the parallel implementation went between 0.4s-0.9s(yeah, its faster, but the time it takes jumps all over the place). is there anyway to make the execution time more "stable"? did i do something wrong/or is there any important concepts that i'm missing?

i don't mind if u just give me a wikipedia page to read =)
Not really that familiar with openMP. The serial implementation time consistency is easy to explain, you were running on one core. The varying times running in parallel hard to say. Windows or Linux, running natively or virtually, number of cores your system has would be all questions that I would have. This is where knowledge of OpenMP would come in handy, can you specify something called processor affinity for your threads? I think Windows/Linux have a thread pool for each core and I'm guessing that OpenMP attempts to use that to run in parallel. If you only have two cores then two threads have to share a core. Interesting post though.

Btw you can do this kind thing using C++ 11 with their thread class and new memory model without OpenMP.

Last edited by adios; 10-06-2015 at 04:41 PM.
Programming homework and newbie help thread Quote
10-07-2015 , 08:15 AM
Okay face palm reveal time

I had background programmes running xD
Programming homework and newbie help thread Quote
10-07-2015 , 09:37 AM
Quote:
Originally Posted by CyberShark93
Okay face palm reveal time

I had background programmes running xD
LOL that would be a good reason why.
Programming homework and newbie help thread Quote
10-09-2015 , 09:50 PM
hi. totally new to ruby and new to oop in general coming from C.
here is the question:

Question 4:
Create a class named person with a name and an age.
Use the initialize() method.
Use attr_accessor to create the get and set methods.

Firstly I don't understand why I'm being asked to use both these in the same class. separately they seem to be doing the same but toegether im getting an error and missing the point.
Code:
class Person
  attr_accessor :name
  attr_accessor :age

  def initialize(newage, newname)
    @newage = newage
    @newname = newname
  end

  def display
    puts "I am aged #{@newage} and my name is #{@newname}"
  end
end



p1 = Person.new
p1.name = "Dennis"
p1.age = "60"
puts p1.name
puts p1.age

p2 = Person.new('21', 'Tim')
p2.display
Programming homework and newbie help thread Quote
10-09-2015 , 10:41 PM
The initialize method doesn't define new variables, it is there to set values on the instance variables you already created. Your attr_accessor statements created instance variables called @name and @age. Just change @newage to @age and @newname to @name in the initialize and the display and you're good to go.

Edit: Being new to OOP you probably don't understand the point of using attr_accessor. The idea is that it is bad practice to directly expose variables in classes, because variables are always implementation details and implementation should be abstracted away. For instance, later you might decide to store the person's date of birth instead of age, since that will allow calculating their age dynamically based on the current date. If other code was directly accessing the "age" variable, that change would break that code. Since you're using an accessor though, you can simply change the accessor so that it translates DOB to age and vice versa. Any client code that is using your class need not be aware that the implementation has changed.

Last edited by ChrisV; 10-09-2015 at 10:47 PM.
Programming homework and newbie help thread Quote
10-10-2015 , 05:11 AM
The 'new' added actually was me trying a quick fix first to understand later....


It's still not working though. The error is the same:
`initialize': wrong number of arguments (0 for 2) (ArgumentError)


because when i define initialize() and display() and leave out attr_acccessor altogether and create my
p2 instance, it's fine; there's no error passing when i create my p2 instance as it were..

And it's also fine if I leave out those and only use attr_accessor
and create my p1.instance.. where i can set p1.name etc

Thanks for the explanation. I believe I already get that but I'm confused as to why I would use both initialise and attr_accessor in the same class just yet.
when I'm only trying to create person instances with name and age for now.
In other words; whats the advantage of :


p1.name = "Dennis"
p1.age = "60"

over

p2 = Person.new('21', 'Tim')
Programming homework and newbie help thread Quote

      
m