Conditionals & Control Flow - Code Academy - python

I'm taking the Python course in Code Academy. I have never been good at math, never put much effort into it to be honest. My question is, below, when they say "Set bool_three equal to the result of 100 ** 0.5 >= 50 or False" as an example is "100 ** 0.5 >= 50 or False" - Just an example made up or would I be needing numbers like that when I start coding Python on my own? I have been doing great in the course so far, but when i get to questions like that I go brain dead for a second, I end up figuring it out, given some of them I do need to look up, but is this going to be a common theme I'm going to use when coding or did just explain it this way?
Thanks
Time to practice with or!
Set bool_one equal to the result of 2**3 == 108 % 100 or 'Cleese' == 'King Arthur'
Set bool_two equal to the result of True or False
Set bool_three equal to the result of 100**0.5 >= 50 or False
Set bool_four equal to the result of True or True
Set bool_five equal to the result of 1**100 == 100**1 or 3 * 2 * 1 != 3 + 2 + 1

What kind of math you will need depends entirely on your application. YOUR code, may not use math at all and all math needed is done by libraries and frameworks you use. - There is always math involved, whether you have contact with it is another question.
If you develop a solver for equations, then chances are, most of your code will end up "beeing maths".
If you meant to ask, if it's common to use boolean logic crossed with math, then in my experience, no it isn't. Typically you have flow control dictate which piece of math is used and then proceed. You don't mangle it all into a single expression.

Math (algebra) and programming are really coupled in my head. Being good at math would sharpen your skills in problems solving.
Don't worry! That's a thing that you can acquire by learning more about problems solving. You don't have to take classes in Math! (Even though it would still be better to improve the Math part by taking classes).
From the example you given, I can see that it caught your attention in the sense that you possibly were like:
OMG! Math?!!!!
The example is nothing at all. Therefore, this kind of math would be required to comprehend whilst you are taking the programming course. That's of course if you are interested to be a good programmer.
stackoverflow is here and always will be. Whenever you have questions about some problems you don't know how to work it out, just post your questions. That's how we all learn ;)
Happy learning.

Related

CLARANS pyclustering implementation - is there a mistake in the code?

I know my question is a bit weird but I am trying to implement my own version of CLARANS algorithm for sake of learning. To understand it better, I tried to get through the CLARANS code of pyclustering library (which is outdated but still seems popular and I've seen it used in some places). Here it is:
https://github.com/annoviko/pyclustering/blob/master/pyclustering/cluster/clarans.py
I understood everything (or thought so), until the line 210, so just before the cost calculation takes place.
distance_nearest = float('inf')
if ( (point_medoid_index != candidate_medoid_index) and (point_medoid_index != current_medoid_cluster_index) ):
distance_nearest = euclidean_distance_square(self.__pointer_data[point_index], self.__pointer_data[point_medoid_index])
Is there a bug inside the library? Let's say we have 1000 data points and 3 clusters (so 3 medoids of course).
Why would we say the distance_nearest = float('inf') for any of the points (especially since we're adding the distance_nearest later in the code)? And what is more, why would we compare the index of analyzed point's medoid (so could be equal to 400) to the current_medoid_cluster_index (which could only take values from 0 to 2)? What's the point of that?
I'm sorry if it's a bit chaotic, but I'm honestly looking for someone either interested in going through the code or someone who understands the code already - I am willing to elaborate further if needed.
If someone understands it and knows there is no bug, could you please explain the cost calculation part?

Simplifying Equations with Python z3 API

I'm trying to learn how to accomplish a few things when working with expressions in the Python z3 API.
I would like to be able to simplify/reduce sets of equations that contain intermediate variables. Say I have the Equations (A = B && C) and (C = D || E). In z3 these would be represented as (Bool('A') == And(Bool('B'), Bool('C')) and (Bool('C') == Or(Bool('D'), Bool('E')). Is there some function or series of functions that can be used to produce the simplified and reduced equation (A = B && (D || E))?
I would like to be able to convert a z3 expression into sum of products form (i.e Or(minterm1, minterm2,...).
An efficient way of determining the logical equivalence of two boolean equations.
A way of returning a boolean equations as formatted strings (i.e NOT in the nested function form used to declare the function.)
If anyone has any insight on any of these items, your input would be very much appreciated. Also, if any further clarification as to what is desired is needed, please let me know.
Thanks,
Great questions.
No, not in general. You can get z3 to simplify equations, but your notion of "simple" is unlikely to match what it will consider simple for its internal purposes. People often ask for this feature, but it is in general a very hard problem, and not at all clear what's meant by simple. Having said that, z3 does have a notion of Goal and Tactic, and there is even a simplify tactic that you can use. It will simplify the formulas, but having it behave precisely the way you want it to behave is a fool's errand.
See this great resource on tactics and perhaps you can play around to see to get something that works for you: http://www.cs.tau.ac.il/~msagiv/courses/asv/z3py/strategies-examples.htm
The simplify tactic does have a som option, I believe. That might do the trick. Again, see the above link, where they have the example:
s = Then(With('simplify', arith_lhs=True, som=True),
'normalize-bounds', 'lia2pb', 'pb2bv',
'bit-blast', 'sat').solver()
The nugget som=True tells the solver to use sum-of-minterms. Again, your mileage might vary depending on the exact structure of your formulas, and z3 might introduce new names that might defeat the purpose.
Absolutely! This is what z3 excels at. Simply assert f != g where f and g are your equations. If z3 says unsat, then you know they are equivalent for all assignments to variables. If it gives you a model, that forms a counter-example to their equaivalence. (The negated-equality trick is very common in SMT solving: A formula is a tautology precisely when its negation is unsatisfiable. So, you can assert the negation of what you want and see if it comes back with unsat.)
Note that this is what SMT (and SAT) solvers excel at.
For any formula f you build, you can issue print f and it'll print it. But as you probably already observed, it will not look like your textbook logical formulas. The pretty-printer has some options to control its behaviour, but it's probably not quite what you want.
However, the API provides functions to walk down the AST and extract nodes as you wish. So, you can write your own pretty printer if you so desire. Doing so isn't terribly difficult, but that doesn't mean it's simple: There are many cases to consider and in my experience, such printers are usually not that hard to fool; i.e., produce something vastly worse for small changes to the input.
From a practical perspective, while z3 and its high-level APIs in Python, C, Java, etc., is capable of doing everything you want, it's not going to be out-of-the-box except for #3. My recommendation would be to code everything else yourself, and rely on z3 for checking equality where it excels at. Of course, this all depends on precisely what you're trying to do. Best of luck!

Algorithms for implementing analytic calculus

I'm interested in writing a program in Python that can parse a mathematical expression and carry out operations on it in algebraic form. Most of these will be pretty easy, something like 2x+5x+xy. My program would take this and return the simplified 7x+xy. However I'd also like to eventually extend it's functionality to calculus as well, so if it's given something like integrate: 5x it should be able to return (5x^2)/2 + c. I'm aware that for this the sympy library can be used, but I'm interested in implementing it myself as a learning process. Are there any algorithims that exist to carry out algebraic calculus for any arbitrary integral/differential I could implement, or is this a more daunting task I've set for myself here? Any reasources would be appreciated.
It might be worthwhile to ask why you're looking at doing this, and understanding the sorts of things that you want to be able to integrate, because I think you might not know that you've actually stumbled onto a very difficult question.
If you are looking for an exercise to learn about simple low level polynomial integration and python - ie. something of the form x^2 + 2x + 7 - and the idea is to learn about string manipulation and simple math, then by all means I think you should attempt to do this and see how far you can get. Look at the various math related libaries (like Sympy or Numpy) and see what you can get.
If you are looking to produce a powerful tool to be used for Calculus, then I think you should rethink your idea and consider using something like Wolfram Alpha. A project like this could take years and you might not get a good result from it.

Modular Exponentiation in Python

I was trying to solve the ZSUM problem at SPOJ using Python 2.7.9 as my coding language and designed a program to do so. As the code runs perfectly but gives a TLE at the judge, I guess it is not fast enough. Is there is possible to optimize the below code to meet the judge requirement or it is impossible to beat the challenge using Python.
Link to the problem: http://www.spoj.com/problems/ZSUM/
def zsum(n,k):
a=2*pow(n-1,k,10000007)
b=pow(n,k,10000007)
c=2*pow(n-1,n-1,10000007)
d=pow(n,n,10000007)
zsum=(a+b+c+d)%10000007
print zsum
def main():
while True:
n,k=map(int,raw_input().split())
if n==k==0:
break
else:
zsum(n,k)
main()
Since there are zero accepted python solutions in a total of 2335 successful submissions, i think, no matter how much you optimise your solution, it is unlikely to manage to get accepted with python. Although python is a very useful language, it is not preferred in programming contests, as it is extremely slow (compared to C/C++ for instance). If you know how to code in C++ you should definitely give it a shot, although you must write you own modular exponentiation procedure.
I don't know if this will help (if you read the problem's comments you will see someone saying that it is impossible to solve in Python - that can happen on online judges with slower languages) but you can optimize the code:
def zsum(n,k):
a=2*pow(n-1,k,10000007) # (1)
b=pow(n,k,10000007) # (2)
c=2*pow(n-1,n-1,10000007) # (1)
d=pow(n,n,10000007) # (2)
zsum=(a+b+c+d)%10000007
print zsum
Note that in (1), you are computing pow(n - 1, min(k, n - 1)) twice. You could compute it once and then use modular exponentiation only for what is left. Same for (2).

What are good programming questions to exercise the use of "if ... else" in Python?

What would be a good set of programming exercises that would help Python newbies to learn the use of the "if ... else" construct? I could cook up the following, do you know of any more?
Find the largest/smallest of three numbers.
Given a date (year, month, day), find the next date.
Most of the intended audience have not had much of an exposure to programming before, and I am keen on getting them used to thinking correctly about "if ... else" (and all the rest of it, in due course).
It's hard for those of us who have been programming for years to "get" what it feels like to start from nothing. I would steer clear of anything needing more than 5 lines of code.
You need to decide the order in which you cover things such as User Input, Output, if, else, while, for, file io etc.
When covering IF do they already know how to get some user input? Print some output? Code a FOR loop? Do arithmentic on integers? Determine whether a number is divisible by another number?
The answers to these questions constrains your examples for IF.
I'd suggest doing Output, Arithmentic, FOR, Divisibility (modulus), User Input before doing IF.
Then I can pose problems such as
Print the first 100 odd numbers
Determine the factors of a number entered by the user
Play a number guessing game (User enters a guess, you print YES or Higher or Lower)
"Figure out whether a given year is a leap year" springs to mind almost immediately. Just give 'em the rules and turn 'em loose.
Other possibilities (albeit with stuff other than if statements):
Hunt the Wumpus (you may have to google for this one, I'm showing my age).
The perennial "detect a win in a Tic Tac Toe (Noughts and Crosses) game" (you could do this with eight if statements if you don't want a loop).
Guessing a number between 1 and 100 as quickly as possible (higher, lower).
For nothing but if/else statements, the leap year one is good. You could also consider:
Test if a number is a multiple of 3, 5 or 7.
Given an age, figure out whether someone's a baby, toddler, child, teenager, adult or old codger.
Calculate grades A-F based on final percentage score.
Given a number on the roulette table, figure out whether it's red/black, high/low and odd/even.
Given a blackjack hand, check if it's okay or bust (this is good since J/Q/K morph into 10). You could also figure out whether to draw another card (if total under 17 for example).
That's just a smattering of possibilities that you could get away with.
Try a simple game, like if you press 'L', turn left, if you press 'R', turn right, if there's a monster, you die etc.
There are numerous of options here. Maybe let them build a simple calculator, taking into account division by zero, odd/even numbers and the like.
Edit: Found this simple excercise on if-else (in java) which can be transformed into Python.
In my opinion, the if statement is an interesting subject in Python. I would recommend to take into account the philosophy of the language when introducing it.
Most of time, I don't use if as an alternative to the C++ switch. I do prefer a dictionnary of functions.
I also try to follow the It's easier to ask forgiveness than permission rule and I do prefer to catch exceptions.
I think that your examples should take that into account. So i wouldn't use the monster game or the division by zero ideas. It can be funny to implement but is not very pythonic in my opinion.
I mainly use if as a filter.
I think you should'nt take any difficult algorithm as an example if your goal is to teach the syntax of the language. Learning how to program is certainly a sufficient challenge.
So I think any stupid example like the one below should work.
class Song:
def __init__(self, title, year):
self.title = title
self.year = year
songs = [Song('Blackbird', 1968), Song('Penny Lane', 1967), Song('Jenny Wren', 2005)]
for song in songs:
if song.year < 1970:
print song.title, 'by the Beatles'
else:
print song.title, 'is not a Beatles song'
It could also be a 1st step for the list comprehension if you plan to show it.
songs = [Song('Blackbird', 1968), Song('Penny Lane', 1967), Song('Jenny Wren', 2005)]
print [song.title for song in songs if song.year<1970]
I did demonstration of the subject in DaniWeb by number guess game. Something similar maybe?
Using if..else in print statement instead of multiline if is my favorite use of the construct.
I saw other answers to suggest things for normal if statement so I cooked up one myself:
I think of practical value would be to use if in break statement as reaction to user input. Same time you can teach try...except ie when not to use if in Python.
Once you make it to looping and/or functions, a great one would be "four is magic" - four is the only word with the same # of letters as the number, and supposedly all numbers converge to four. So the game goes something like this:
seventeen is nine
nine is four
four is magic
or (discounting spaces):
one hundred is ten
ten is three
three is five
five is four
four is magic
Of course if you just wanted to stick to if/else at the moment you could fairly easily do this for the numbers 0-10, and just have a series of 11 if...else blocks (1-5 and you'd need even less).
One of the best is Project Euler problem #1.
http://projecteuler.net/index.php?section=problems&id=1
This requires considerable care to get the if-conditions exactly right.
I like the "Three men and a monkey on an island" problem:
Three men are stranded on a desert
island with a monkey. They collect
all of the coconuts and put them into
a big pile. Then throughout the night
each man gets up secretly and takes
1/3rd of the remaining pile and hides it. When
he splits the pile into thirds there's
1 remaining which he gives to the
monkey. Then in the morning after
they all wake up they split the pile
into 1/3rds ... with 1 left-over for
the monkey. How many coconuts were in
the pile originally?
The general strategy for solving this is to use a for-loop to check all numbers from 1-10,000 (or some other large number). You need to use if statements to check the remainder. You can later expand this problem to a more general word problem of X-men and Y-monkeys ... this requires a nested for-loop.
You could also prep your beginner programmers to pass the FizzBuzz test. Seeing how this is an extremely common filtering function for hiring programmers you could cite:
"After completing this assignment you
are above 199 out of 200 programmers
who apply to professional positions"
At my lecture I asked them to implement is_between_5_8(x) (I admit, there's no ulterior motive with using 5 and 8), and afterward I gave them the exercises to implement abs(x) and closest_to_zero(x, y).
If you've taught them recursion I can give you a few more suggestions :)

Categories