Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Ok so I am struggling in this computer programming class, as I am totally new to computer programming. let me post my actual assignment and then see if anyone could help get me started with it.
assignment:
This Lab is Part 1 of building a type of fractal called a Lindenmayer system.
In this first part, you will just be implementing symple set of draw commands.
Write a program that takes 3 inputs:
1) Draw String: This must be a string of draw commands (see the table below).
2) Length: This must be an integer equal greater than 0 and less than or equal to 100. It defines the length variable used in some of the draw commands.
3) Angle: This must be a floating point number equal greater than 0.0 and less than or equal to 360.0. It defines the angle variable used in some of the draw commands.
Character Draw Commands
h
Draw a straight line segment length pixels long in the current heading.
f
Same as h
g
Move, without drawing, a straight line segment length pixels long in the current heading.
+
Turn the heading clockwise by angle.
Turn the heading counter-clockwise by angle.
A
Each of these color commands must change the turtle color to color that is different form the background and different from the other 5 color commands. Pick colors that you think look good together.
B
C
D
E
F
any other character
Ignore
So, that is the assignment, sorry it's so long. I have been reading my textbook, and unfortunately it gives very little info on how to actually do this assignment. It also didn't help that our professor showed us all these cool things fractals could do, but didn't actually tell us anything about how to do the assignment (don't ask me why?)
I am really at a loss as to how to even begin to code this thing, if someone could help me or at least point me in the right direction, at starting to go about coding for this stuff, it would really help me out. I don't expect anyone to do it all for me, just maybe help show me where to begin.
PS. There is one other thin our professor wrote that is probably important.
Now that you have the "if" statement at your command, you do need to check for bad input. If the user inputs bad data, print an error message and exit the program.
Your assignment seems simple to me so make sure you don't overthink it just because the professor showed you some strange sorcery! Yes fractals can do a lot of cool ( and complicated ) things but your professor is not asking you to do any super complex stuff. The first thing you want to do is look at the Official Python Tutorial. For this turtle assignment, you do not need to read all of the tutorial. Simply read the first four sections (up to the end of More Control Flow Tools) to get a good grasp on all the tools you'll need to do this assignment. I assume the main things you will need are functions and basic control flow statements so pay close attention to those parts.
The next thing you want to do is look at the documentation for the turtle module. Learn the basic commands, specifically turtle.up(), turtle.down() and how to move and rotate the turtle around on your screen. Think of your turtle as a "pen" that has an orientation and you have to tell that "pen" exactly what to do with Python commands. That should be more than enough to get you started on this assignment. Good luck to you and welcome to the world of programming. :)
Related
This question may be a little different, since I'm pretty much a noob at programming. I've recently started playing a Pokémon game, and I thought of an idea for a cool Python program that would be able to grab a color on a certain pixel to detect if a pokémon is shiny or not.
However, due to my very limited programming experience, I don't know what modules to use and how to use them.
So basically, here's what I want it to do:
Move the cursor to a certain pixel and click.
Detect the color of a certain pixel, and compare that to the desired color.
If it's not desirable, click a button and re-loop until it's desirable.
So, it's pretty obvious that we'll be needing a while loop, but can someone explain how to do the above three things in relatively simple terms? Thanks.
Try breaking down this list into actions and searching for answers to each action.
For example, 1 is performed by the user? So we don't have to program that.
For 2, we need to determine the location of the mouse when clicked and get the color under it.
For 3, compare the RGB values (or whatever) to the desired values for that pokemon. This is complicated because your program needs to figure out which pokemon it is checking against. There are probably pokemon where their regular color is another's shiny. Try breaking down this into even smaller problems :)
No guarantees that these links will be perfect, just trying to show how you need to break down the problem into smaller, workable chunks which you can address either directly in code or by searching for other people who have already solved those smaller problems.
I'm learning python and I'm not sure of understanding the following statement : "The function (including its name) can capture our mental chunking, or abstraction, of the problem."
It's the part that is in bold that I don't understand the meaning in terms of programming. The quote comes from http://www.openbookproject.net/thinkcs/python/english3e/functions.html
How to think like a computer scientist, 3 edition.
Thank you !
Abstraction is a core concept in all of computer science. Without abstraction, we would still be programming in machine code or worse not have computers in the first place. So IMHO that's a really good question.
What is abstraction
Abstracting something means to give names to things, so that the name captures the core of what a function or a whole program does.
One example is given in the book you reference, where it says
Suppose we’re working with turtles, and a common operation we need is
to draw squares. “Draw a square” is an abstraction, or a mental chunk,
of a number of smaller steps. So let’s write a function to capture the
pattern of this “building block”:
Forget about the turtles for a moment and just think of drawing a square. If I tell you to draw a square (on paper), you immediately know what to do:
draw a square => draw a rectangle with all sides of the same length.
You can do this without further questions because you know by heart what a square is, without me telling you step by step. Here, the word square is the abstraction of "draw a rectangle with all sides of the same length".
Abstractions run deep
But wait, how do you know what a rectangle is? Well, that's another abstraction for the following:
rectangle => draw two lines parallel to each other, of the same length, and then add another two parallel lines perpendicular to the other two lines, again of the same length but possibly of different length than the first two.
Of course it goes on and on - lines, parallel, perpendicular, connecting are all abstractions of well-known concepts.
Now, imagine each time you want a rectangle or a square to be drawn you have to give the full definition of a rectangle, or explain lines, parallel lines, perpendicular lines and connecting lines -- it would take far too long to do so.
The real power of abstraction
That's the first power of abstractions: they make talking and getting things done much easier.
The second power of abstractions comes from the nice property of composability: once you have defined abstractions, you can compose two or more abstractions to form a new, larger abstraction: say you are tired of drawing squares, but you really want to draw a house. Assume we have already defined the triangle, so then we can define:
house => draw a square with a triangle on top of it
Next, you want a village:
village => draw multiple houses next to each other
Oh wait, we want a city -- and we have a new concept street:
city => draw many villages close to each other, fill empty spaces with more houses, but leave room for streets
street => (some definition of street)
and so on...
How does this all apply to programmming?
If in the course of planning your program (a process known as analysis and design), you find good abstractions to the problem you are trying to solve, your programs become shorter, hence easier to write and - maybe more importantly - easier to read. The way to do this is to try and grasp the major concepts that define your problems -- as in the (simplified) example of drawing a house, this was squares and triangles, to draw a village it was houses.
In programming, we define abstractions as functions (and some other constructs like classes and modules, but let's focus on functions for now). A function essentially names a set of single statements, so a function essentially is an abstraction -- see the examples in your book for details.
The beauty of it all
In programming, abstractions can make or break productivity. That's why often times, commonly used functions are collected into libraries which can be reused by others. This means you don't have to worry about the details, you only need to understand how to use the ready-made abstractions. Obviously that should make things easier for you, so you can work faster and thus be more productive:
Example:
Imagine there is a graphics library called "nicepic" that contains pre-defined functions for all abstractions discussed above: rectangles, squares, triangles, house, village.
Say you want to create a program based on the above abstractions that paints a nice picture of a house, all you have to write is this:
import nicepic
draw_house()
So that's just two lines of code to get something much more elaborate. Isn't that just wonderful?
A great way to understand abstraction is through abstract classes.
Say we are writing a program which models a house. The house is going to have several different rooms, which we will represent as objects. We define a class for a Bathroom, Kitchen, Living Room, Dining Room, etc.
However, all of these are Rooms, and thus share several properties (# of doors/windows, square feet, etc.) BUT, a Room can never exist on it's own...it's always going to be some type of room.
It then makes sense to create an abstract class called Room, which will contain the properties all rooms share, and then have the classes of Kitchen, Living Room, etc, inherit the abstract class Room.
The concept of a room is abstract and only exists in our head, because any room that actually exists isn't just a room; it's a bedroom or a living room or a classroom.
We want our code to thus represent our "mental chunking". It makes everything a lot neater and easier to deal with.
As defined on wikipedia: Abstraction_(computer_science)
Abstraction tries to factor out details from a common pattern so that
programmers can work close to the level of human thought, leaving out
details which matter in practice, but are not exigent to the problem being
solved.
Basically it is removing the details of the problem. For example, to draw a square requires several steps, but I just want a function that draws a square.
Let's say you write a function which receives a bunch of text as parameter, then reads credentials in a config file, then connects to a SMTP server using those credentials and sends a mail using that text.
The function should be named sendMail(text), not parseTextReadCredentialsInFileConnectToSmtpThenSend(text) because it is more easy to represent what it does this way, to yourself and when presenting the API to coworkers or users... even though the 2nd name is more accurate, the first is a better abstraction.
In a simple sentence, I can say: The essence of abstraction is to extract essential properties while omitting inessential details. But why should we omit inessential details? The key motivator is preventing the risk of change.
The best way to to describe something is to use examples:
A function is nothing more than a series of commands to get stuff done. Basically you can organize a chunk of code that does a single thing. That single thing can get re-used over and over and over through your program.
Now that your function does this thing, you should name it so that it's instantly identifiable as to what it does. Once you have named it you can re-use it all over the place by simply calling it's name.
def bark():
print "woof!"
Then to use that function you can just do something like:
bark();
What happens if we wanted this to bark 4 times? Well you could write bark(); 4 times.
bark();
bark();
bark();
bark();
Or you could modify your function to accept some type of input, to change how it works.
def bark(times):
i=0
while i < times:
i = i + 1
print "woof"
Then we could just call it once:
bark(4);
When we start talking about Object Oriented Programming (OOP) abstraction means something different. You'll discover that part later :)
Abstraction: is a very important concept both in hardware and software.
Importance: We the human can not remember all the things all the times. For example, if your friend speaks 30 random numbers quickly and asks you to add them all, it won't be possible for you. Reason? You might not be able to keep all those numbers in mind. You might write those numbers on a paper even then you will be adding right most digits one by one ignoring the left digits at one time and then ignoring the right most digits at the other time having added the right most ones.
It shows that at one time we the human can focus at some particular issue while ignoring those which are already solved and moving focus towards what are left to be solved.
Ignoring less important thing and focusing the most important (for the time being and in particular context) is called Abstraction
Here is how abstraction works in programming.
Below is the world's famous hello world program in C language:
//C hello world example hello.c
#include <stdio.h>
int main()
{
printf("Hello world\n");
return 0;
}
This is the simplest and usually the first computer program a programmer writes. When you compile and run this program on command prompt, the output may appear like this:
Here are the serious questions
Computer only understands the binary code how was it able to run your English like code? You may say that you compiled the code to binary using compiler. Did you write compiler to make your program work? No. You needed not to. You installed GNU C compiler on your Linux system and just used it by giving command:
gcc -o hello hello.c
And it converted your English like C language code to binary code and you could run that code by giving command:
./hello
So, for writing an application in C program, you never need to know how C compiler converts C language code to binary code. So you used GCC compiler as an abstraction.
Did you write code for main() and printf() functions? No. Both are already defined by someone else in C language. When we run a C program, it looks for main() function as starting point of program while printf() function prints output on computer screen and is already defined in stdio.h so we have to include it in program. If both the functions were not already written, we had to write them ourselves just to print two words and computers would be the most boring machines on earth ever. Here again you use abstraction i.e. you don't need to know how printf prints text on monitor and all you need to know is how to give input to printf function so that it shows the desired output.
I did not expand the answer to abstraction of operating system, kernel, firmware and hardware for the sake of simplicity.
Things to remember:
While doing programming, you can use abstraction in a variety of ways to make your program simple and easy.
Example 1: You can use a constant to abstract value of PI 3.14159 in your program because PI is easy to remember than 3.14159 for the rest of program
Example 2: You can write a function which returns square of a given number and then anyone, including you, can use that function by giving it input as parameters and getting a return value from it.
Example 3: In an Object-oriented programming (OOP), like Java, you may define an object which encapsulates data and methods and you can use that object by invoking its methods.
Example 4: Many applications provide you API which you use to interact with that application. When you use API methods, you never need to know how they are implemented. So abstraction is there.
Through all the examples, you can realize the importance of abstraction and how it is implemented in programming. One key thing to remember is that abstraction is contextual i.e. keeps on changing as per context
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I'm going to be teaching some year 9 and 10 students Python soon and thought it would be cool to do some Project Euler type challenges with them. The first problem seems doable by them, but I think some of the others may be a bit over their head, or not require enough programming.
If anyone has a place to find some easy programming problems, or can think of any, can they please let me know.
edit: By year 9 and 10 I mean that they have been in school for 9 or 10 years. So about 13, 14, and 15 type age. Sorry for the confusion!
Oh I remember something I was taught in school! My IT teacher created a class in python which attributes created a mathematical sequence. The goal was to guess the formula behind this sequence using only python. Obviously, you couldn't look at the file with class, only import it in python. Maybe there's more math than programming here, but to solve this, students will have to learn how variables, namespaces (to find the variables), loops (to print those variables), and classes (which store those variables) work in python and this is more or less everything you need to know at first, in my opinion.
Ah, good times. We also used to play "hide and seek" in shell on IT lessons: the teacher would hide a file somewhere and leave some clues scattered around, and we had to find that file using text environment on linux :)
Get the right number :
The program chooses a random value betwen 1 an 100 then you have to guess.
It tells you if you are above or below.
My first scholar contact with programming really left a mark on me ;) The teacher provided us with a gui containing a sort of 2-d checkered board (let's pretend it was 20x20 cells). One of the cells contained a 'robot' and the programming interface basically exposed 3 methods: move forward, turn left, and check if the cell directly in front of the robot is a wall or open space. The game was then to 'program the robot' (teaching basic logic and loop constructs) to do all sorts of tasks like pass through every cell in the board. Later on, methods were added to the interface (to the original 3 methods) and 'objects' (not OOP, but .. other states the cells could occupy than just wall or empty) were added to the game. In the end the goals were for example for the robot to 'pick up' car parts and bring them to a 'car factory'. It was very nice IMHO to view programming as a game with 'scores' (least amount of cells required to achieve objective in this case) and I really promote Gamification http://en.wikipedia.org/wiki/Gamification in any school environment.
Cheers
Not sure how long you have to teach this, but Udacity's cs101 class has some pretty cool problems and starts from a pretty simple level. The course is free, and you may find some of the problems useful stand alone if you don't have time for the whole thing.
Finally if you run out of ideas for meaningful projects that are easy enough / quick enough in Python or decide to find something easier for part of the class then consider using Scratch, this is a fun visual programming language from MIT which allows you to use the constructs such as variables, loops, conditions etc. without worrying about syntax. This makes it nice and easy to create basic games / animations.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
So I've been thinking of creating a program similar to this in Python. The problem is that I know next to nothing about AI. Right now I'm reading up on genetic algorithms and neural networks and such, but there's a lot of things to absorb.
My largest problem now is I don't know how the entire thing is put together. So if anyone can tell me the general framework for a program like this, I'll be really grateful. For example, how the creatures can "see" things in their surroundings, the kind of "chromosomes" they have and how the environment is created.
Also, can anyone suggest suitable libraries for AIs, any engines, etc? I've been thinking of using neurolab, will that be a good idea?
Thanks!
Interestingly, I've created what you're describing, in Python.
Here's a pic:
The green dots are food, and the red ones are organisms that need to evolve and learn how to eat the food blocks.
The best source of inspiration and guidance for something like this is definitely Polyworld: youtube.com/watch?v=_m97_kL4ox0.
Another great example which helped me learn about backpropagation, which I suggest you should learn too, is here: arctrix.com/nas/python/bpnn.py.
Although this question is simply too vague to answer correctly, the general tip is that you first get a solid ground on how ANN's function, and then construct a program with this general algorithm:
Check for user input (should the camera move? should the program quit?)
For each organism:
Check if it is alive, etc.
Take input from the world
Evaluate its neural network
Apply the results to the physical body
Apply positive or negative feedback (as you'll see, it all comes down to this)
Update the world (you can use a physics engine)
Optionally, draw the world
For example, your input neurons could correspond with physical or visual stimulation. Is there something in front of me? Then set neuron X to 1, otherwise to 0.
And your output neurons could map into forces. Is neuron Y active? If so, apply an impulse to this organism's in this world cycle.
I also recommend that you don't use other people's libraries for your neural network computation, because this is a great way to actually learn how to implement them yourself. You could you Pygame for rendering, and PyBox2D for physics, though.
Now, about "seeing" other organisms... These problems are best solved when isolated. You need a good software design, that will enable you to divide the whole problem into many subproblems, which are easier to solve.
In general, seeing can be done by raycasting. Create a directional, normalized vector (where the length is 1 unit, that is, sqrt(x*x + y*y) == 1), and then scale it (x *= factor; y *= factor;). That way, you get a line that's stretching outwards. Before you scale it, you can then loop through all of the organisms in the world (you'll have to optimize this), and check if the vector is inside of them. If it is, calculate its length, and your organism has some information about its surroundings.
There are many simpler ways. For example, divide space around each organism into four quadrants, which four represent eyes (X - up, right, down, left of the organism). Then calculate the length from the organism to every other organism (optimize!). Find the closest organism. Find out in which quadrant it is. Voila, an active eye!
I hope I was helpful, but you'll have to be more precise and come back when you have an actual problem. Read the FAQ as well.
http://scikit-learn.org/ is a great resource (and framework) for you to learn about machine learning in python.
If you want to build a neural network, http://pybrain.org/ is a good framework.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
Are there any good up-to-date physics libraries for Python that are for Linux? I'm just getting into Python using PyGame, but PyGame's lack of a physics library isn't cool. I spent about two hours trying to find a good physics library but it's like trying to grab oil; I can't seem to do it.
I barely need a physics engine at all; all I want to do is program an object to 'jump' up and then fall back to the ground. There seems to be some simple collisions going on (which PyGame can handle, I think) but it's the actual jump calculation that's stumping me. If it turns out that there aren't any good ususable physics libraries, the problem seems simple enough that I might just try to find a basic acceleration equation and a gravity equation and try to apply those... I'd like to avoid having to do that, though.
Thanks for any help.
Pymunk is another promising one that you might want to take a look at.
Try pyODE, it is the python binding of open dynamic engine.
You can find more information here
The basic physics kinematic equations are all you need. Even though the questions was already answered, if I were you, I'd still do it by hand just because using a library seems like overkill. Start the equation for velocity:
velocity = initial velocity + (acceleration * time)
From there, we integrate to find position:
position = initial position + (initial velocity * time) + (acceleration * time^2)/2
Your jump is looking to calculate the y position of the character, so just use that equation to calculate y position and toy with initial velocity and acceleration. Standard acceleration due to gravity is -9.8 meters per second^2 (at least on the surface of the earth - it's different son different planets). Start with initial position whatever your character is at, or 0 if the ground is 0 to you.
So:
y = vt + (-4.9)t^2
Pick an initial velocity v value to provide the upward movement when the jump starts, and t should be the elapsed game time since he started jumping.
You only need one line of code to do this, no libraries necessary!
EDIT: dealing with what to do when you land.
So in the real world, acceleration is caused by unbalanced forces. Gravity is always acting on you, but when you're standing in the ground, it's being countered and canceled out by the "normal force" of the ground. As long as the ground you're standing on is strong enough to support your weight, the ground will push back up and counter gravity and you will not accelerate downward. So in your game, if you're not actually simulating forces, just change the acceleration from -9.8 to 0 when your character is touching the ground. If the ground is flat, your jump ends when position = initial position
According to the ODE website's installation instructions, the ODE package itself now contains Python bindings based on CPython; and the pyODE bindings are considered obsolete. Installation instructions are included in the above page.
By default this is for Python 2, but I was able to make this binding work with Python 3, too, with a minimum amount of work (Mac OS X). I could even run the tutorials.
This might be out of topic, but just for the record, here is what I had to change:
I had to change OpCode.h by uncommenting the #defines for sqrt, sin, cos, asin and acos (lines 33-37, file version: March 20, 2001). This is an ugly hack that I needed because without this ODE itself did not compile with double precision arithmetic, which one needs to use with the python bindings if we can trust the documentation on the ODE page.
I had to change setup.py by adding the following lines after line 18:
# bugfix: in Python3 read() returns bytes, which need to be converted
# to strings
try:
ode_cflags = [x.decode("utf-8") for x in ode_cflags]
ode_libs = [x.decode("utf-8") for x in ode_libs]
except:
# in Python2 we just continue
pass
To run the tutorials, in the demos directory I used
$ 2to3 -w *.py
That's it.