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.
Related
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 1 year ago.
Improve this question
I am an engineering student and I have to turn in projects that run code for simulations. The calculations are all carried out in Python, but the derivations/ setup is done on paper and included in the report. I sometimes find myself copying and pasting code for repeat graphs or numerical simulations, so I want to write functions for these (trying to be better about DRY).
When writing functions to do these things, I'm worried that I'm "hiding" to much of the code behind the functions. For example, this function would plot two simulations differing only by tolerance level. This would be used to check for convergence in a numerical simulation of an ode.
def plot_visual_convergence_check(odefunc, time, reltol):
sol_1 = solve_ivp(odefunc, time, (0,0), rtol=reltol)
sol_2 = solve_ivp(odefunc, time, (0,0), rtol=reltol/100)
plt.text('rtol is...')
plt.text('rtol for the increased tolerance is...')
plt.plot(<both plots together>)
return plt.show()
Here, all the business with running solve_ivp for two scenarios that only differ by relative tolerance and plotting them is wrapped up into one. I don't imagine that people would want the specifics, just the output and the confirmation that "yes" the simulation has converged. I even write both rtol's on the graph to be more clear about what values were used without showing the code.
Is wrapping these types of operations up okay (because I think it looks cleaner that way), or would it be better as an engineer to have everything laid out for everyone to see without them having to scroll over to the function definition?
In my experience the dry principle is more important when writing libraries and code that you want to reuse. However my experience is that if you want to make a report then sometimes making things to dry can actually make things harder to maintain. I.e. sometimes you want to be able to change an individual graph/plot/piece of data in one place without it affecting the rest of the report. It takes a bit of practice and experience to find out what works best for you. In this particular use case be less focussed on following the DRY rule then when writing a library or an application.
Additionally if I had to make such a report and the situation would allow it. I would make in in a Jupyter notebook. Here you can nicely mix code with text and graphical output.
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 1 year ago.
Improve this question
I've been coding for a few months now making simple scripts and a few bigger projects but I have never been able to wrap my head around when to actually use classes. It may be that my programs are to small to benefit from them but I just don't understand. Whenever I look up videos about it there is always the same kind of examples. When you have for example a student and you want to store information about it. But I don't understand how this could be implemented in a program. Can someone give an example on when it's useful to use a class and why it is better than not.
Example of student class:
class Student():
def __init__(self, name, grade, gender):
self.name = name
self.grade = grade
self.gender = gender
John = Student("John", "A", "Man")
Classes don't appeal when you are coding small programs. But say you are working on a game using the Pygame module, Classes would come in handy. For example, creating an in-game character using Class definitely makes life easier, as it packs all the information and properties into it. On the contrary, making changes to a game programmed using procedure-oriented code would be extremely hard and annoying. Not to mention the length of the code, you also have to clearly state every possible outcome and event. In short, Class is a beneficial means exclusively available to Object-Oriented-Programming, which is why it is a high-level programming language. Class may not be necessary in many cases, but is still an excellent tool to make your code shorter and easier to read and amend.
Yes. I am very mush interested in classes and objects. And I can tell you use of classes and objects would really help you so much and reduce the lines of codes.
First of all, you should know where to use objects. Suppose, we have to create a game, then definitely we will have some objects in it (these are images that we perceive), but in addition to it there are more properties of an object, like on canvas, its x and y coordinates which change over time, when the object moves. And also, image of that object is itself a property of it.
For example, in Super Mario, you would see Mario as the main character and it is an object in terms of programming. Mario is an object with various properties and methods. What properties and methods? On the canvas (for drawing the image), it has x & y coordinates as I said earlier and in addition to this it has an image, width and height of the image, the methods (functions) like move right, move left, jump etc.
In short, you can say an object as a collection of properties (variables) and methods(functions).
Objects really help in organising all the codes. And more than that, classes help. Classes are templates for creating objects. See, in Super Mario, there are many enemies (I don't know what comes the first time brown one) and turtles and many others. You can notice that all of them have the same image(appearance), properties (size and shape), methods(movements) etc. All of them behave the same way.
So how to create many enemies of one type... Do we copy and paste the codes of object and change their properties (their coordinates are different in the game)? There we use classes... We define the properties and methods of objects that we want, by using variables and then pass different values to the class and create hundreds of objects of the same type.
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 8 years ago.
Improve this question
I've started following PEP-8 strictly, because I thought I should at least try it before just picking and choosing the things I like.
However, there seems to be a conflict. They strongly recommend limiting each line to 79 characters, yet they strongly recommend that method and variable names use_underscores_between_words.
On a typical line, where you're nested in a
class ->
method ->
loop ->
conditional ->
my_var_name += do_some_function(some_parameter, another_parameter)
you already have 79 - 16 = 63 characters to work with, and you're wasting 6 on just underscores. So the line above is already too long and it's actually pretty short.
It seems productivity would suffer if I have to count characters so often, or split a rudimentary line like this onto several lines.
I understand that now it says "if your team agrees, use 99", but it seems this should be the standard, or rather that camelCaseVars should be the standard since we like short lines so much.
My issue with coding standards-compliant Python is that I can't seem to write any code without either using cryptic names, or violating the line length or naming convention. I could post my code here to show you my specific issues, but my example above represents the issue I'm having with my code.
Which ideal is less important? Clear names, short lines, or using_underscores?
UPDATE: while no one actually suggested this, I'm getting the feeling that using less descriptive / function and variable names is actually what is tacitly being asked of me. I know people would say "of course not, just wrap your lines", but in practice, it seems to be a mix of "use very short names" and "wrap lines", but stick to 80.
I think that's what people have done, but I think on the business project level, where productivity is king, teams have just thrown out that rule and jumped to 120. For now, I think I'll just stick to 79 with lots of (imho) ugly line wraps, and feel comforted by the thought of me being able to view 2 files side by side on a small monitor.
Python Zen says:
Flat is better than nested.
Therefore consider decreasing a nesting of your code by code decomposition - make the code less nested by extracting some parts into separate methods or functions. And you'll always have enough horizontal space in your editor.
Update
For the nested loops with conditions you can also decrease the nesting level by the decomposition.
For example you can change this code:
class MyClass(BaseClass):
def my_method():
for item in self.my_collection:
if item.numeric_property % 2:
self.my_property = item.other_property + item.age * self.my_coefficient
self.do_other_stuff()
to this one:
class MyClass(BaseClass):
def my_method():
"""People see what happen because of clear names"""
self.process_my_collection()
self.do_other_stuff()
def process_my_collection():
"""People see what happen because of clear names.
They probably don't even need to read your math from
process_my_collection_item(item) at all.
And you make the code more flat as well.
"""
for item in self.my_collection:
self.process_my_collection_item(item)
def process_my_collection_item(item):
"""The most people don't need to read these calculations every time
since they just know it's working and tested
but they'd like to work with methods above frequently:
"""
if not item.numeric_property % 2:
return
self.my_property = item.other_property + item.age * self.my_coefficient
As you can see I divided one method to a few simple operations and made it less nested.
Your goal should be to write code that is easy to understand.
Generally speaking, adhering to PEP8 gets you a step closer to that goal. If the nature of your code and/or your team is such that camelcase works better, by all means use camelcase.
That being said, if you think it is import to save six characters for what you perceive is a typical line, maybe that is telling you that your typical lines are nested too deep, and there's a better solution than to change naming conventions.
Use underscores, it's what everyone expects.
-However- the 79 character limit is one of the more easily set aside recommendations. My team uses pep8 with 119 character lines, but the vast majority of our lines are under 80 characters anyway.
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. :)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm trying to come up with a good coding problem to ask interview candidates to solve with Python.
They'll have an hour to work on the problem, with an IDE and access to documentation (we don't care what people have memorized).
I'm not looking for a tough algorithmic problem - there are other sections of the interview where we do that kind of thing. The point of this section is to sit and watch them actually write code. So it should be something that makes them use just the data structures which are the everyday tools of the application developer - lists, hashtables (dictionaries in Python), etc, to solve a quasi-realistic task. They shouldn't be blocked completely if they can't think of something really clever.
We have a problem which we use for Java coding tests, which involves reading a file and doing a little processing on the contents. It works well with candidates who are familiar with Java (or even C++). But we're running into a number of candidates who just don't know Java or C++ or C# or anything like that, but do know Python or Ruby. Which shouldn't exclude them, but leaves us with a dilemma: On the one hand, we don't learn much from watching someone struggle with the basics of a totally unfamiliar language. On the other hand, the problem we use for Java turns out to be pretty trivial in Python (or Ruby, etc) - anyone halfway competent can do it in 15 minutes. So, I'm trying to come up with something better.
Surprisingly, Google doesn't show me anyone doing something like this, unless I'm just too dumb to enter the obvious search term. The best idea I've come up with involves scheduling workers to time slots, but it's maybe a little too open-ended. Have you run into a good example? Or a bad one? Or do you just have an idea?
I've asked candidates to write code to implement bowling scoring before, which is readily comprehensible but contains enough wrinkles that most people have to iterate their approach a couple times to cover all the edge cases.
A lot of the problems at http://www.streamtech.nl/site/problem+set, which are taken from ACM competitions, are also suitable for your use. I used them to familiarize myself with python syntax and language features. A lot amount to straightforward application of standard data structures; some are more focused on algorithmic issues. If you sort through them I'm sure you'll find several that fit your needs.
I can recommend to you Checkio.org
You can always just give them a few more questions on top of the Java one, like ask them to do the Java task, then ask them to define a class, then ask them to do FizzBuzz. That should be about as rigorous as your Java task.
Don't be afraid to ask a series of questions. Maybe you can even ask them to write a few one-liners to make sure they get the finer points of Python (write a list comprehension, how do you define a lambda, etc.)
Here's a question I answered on SO recently that might be the start of something suitable:
Given a string "O João foi almoçar :)
.", split it into a list of words.
You must strip all punctuation except
for emoticons. Result for example:
['O','João', 'foi', 'almoçar', ':)']
I've tidied up the question a bit. See the original linked above along with my answer. It tests a number of things, and there are different ways of tackling the problem. They can also get a half-solution out that first disregards the emoticons and punctuation aspect. Just finding the emoticons is another sub-problem that can be solved separately. And so on...
You could extend it to asking about emoticons adjacent to other punctuation, adjacent emoticons, overlapping emoticons, defining emoticons in :) form but also searching for those of the form :-). You could also turn it into a frequency count problem instead of just splitting to somewhat line up with your Java question.
I also suggest searching through the python+interview-questions questions posted on SO. There are some good ones, and you may even want to broaden your search to skim all interview-questions posts if you have time.
I don't know about Python specifically, but I found that interview questions which involve recursion are a very effective filter. I have asked candidates to produce all the permutations of a string (and think about how to test it), and I have been asked to pseudo-code the Longest Common Subsequence.