I'm new to programming and Python is my first language of choice to learn. I think it's generally very easy and logical and maybe that's why this minor understanding-issue is driving me nuts...
Why is "i" often used in learning material when illustrating the range function?
Using a random number just seems more logical to me when the range function is dealing with numbers..
Please release me from my pain.
A little extra help!
Asking why we use i is kinda like asking why so many people user the letter x in math problems. It is mostly because i is just a very easy variable to use to represent the current increment in a loop.
I also think you are confused about the place of i in a loop. When you use a range loop you are saying that you want to count one by one from one number until you hit another. Typically it would look like this
for i in range(0, 5):
This means I want to count from 0-4 and set ito the current loop I am currently on.
A great way to test this.
for i in range(0, 5):
print("i currently equals: ", i)
The result will be
i currently equals: 0
i currently equals: 1
i currently equals: 2
i currently equals: 3
i currently equals: 4
In your question you ask why don't you set i to a number and it is because you can not use numbers as variable names. Python can not accept what you are asking, but if it could it would look like this
for 54 in range(0, 5):
print(54)
Try reading up a little more on what variables are and how to properly use them in programming.
https://en.wikibooks.org/wiki/Think_Python/Variables,_expressions_and_statements
Lastly good luck in your pursuit to become a programmer! Coding is one of the most exciting things in this world to many of us and I hope one day you will feel the same!
i is used across nearly all programming languages to indicate a counting variable for a iteration loop.
Answered here.
i and j have typically been used as subscripts in quite a bit of math for quite some time (e.g., even in papers that predate higher-level languages, you frequently see things like "Xi,j", especially in things like a summation).
When they designed Fortran, they (apparently) decided to allow the same, so all variables starting with "I" through "N" default to integer, and all others to real (floating point). For those who've missed it, this is the source of the old joke "God is real (unless declared integer)".
Most people seem to have seen little reason to change that. It's widely known and understood, and quite succinct. Every once in a while you see something written by some psychotic who thinks there's a real advantage to something like:
for (int outer_index_variable=0; outer_index_variable < 10; outer_index_variable++) for (int inner_index_variable=0; inner_index_variable < 10; inner_index_variable++) x[outer_index_variable][inner_index_variable] = 0;
Thankfully this is pretty rare though, and most style guides now point out that while long, descriptive variable names canbe useful, you don't always need them, especially for something like this where the variable's scope is only a line or two of code.
Related
hey everyone I need your help for my programming course, I am pursuing my undergraduate degree in psychology.
The question is:
The python application you will develop will receive the mathematical operation that the user wants to calculate and print the result on the screen.
This process will continue until the user enter "Done".
The application will terminate when the user enters the end.
Conditions and restructions:
1)you will operate with positive integers
2)only 4 operations will be used
3)remember the priority of the operation
4)you will use "*" as a cross
5)no brackets will be used
6)it is forbiddento use an external module
7)you are not responsible for the user's incorrect entries
8)bulit-in functions you can only use the following:
int
float
range
print
input
len
str
max
min
you can use all functions of list and str data structure.
there are some things to be considered:
since you write, no modules are allowed, I assume, this should only run in the CLI. This will make the exercise incredibly easier, since GUI and Python are a Love-Hate-Realionship of its own.
Assuming I understood your assign right, the user will type a list of expressions like "1*2+3/4-5" for example, typing "Done" will indicate, that these should processed and the result should be printed, right? If the User types end, the script will stop working.
Also, you will only have to handle positives, this also, and the fact that you don't have to validate the user entries, makes it very easy. I won't give you a full solution, since you should learn something with this assignment, but here are some hints, that may nudge you in the right direction.
Hints:
The input will be in a string, so handling strings will be a main task. You should look up the documentation to know, in what ways you can manipulate strings. Also have a closer look at helper functions like split, if you have the word Done more than one time in the string.
Strings are in fact just lists of letters, punctuation and numbers.
Since strings are just a list, you won't have a neatly stored 22 in there, it will be a [2][2] surrounded by an operation or the words Done or end. You will have to go through your string, break it up in smaller parts, and then from there on, call functions to do whatever there is to do.
Keep in mind, that there are literally millions of ways to achieve what you have to do, if you aren't familiar with programming, keep it simple, break it up in smaller steps and then just proceed through the exercise.
Hope this will help you. If it helped you or gave you a hint in the right direction, I would appreciate an upvote.
Have fun coding.
I'm learning Python and I built a TicTacToe game. I'm now writing unit tests and improving my code. I was advised to make a while loop in my turn function and use the following bools, but I don't know why. I can see some reason to why this makes sense, but because of how new I am I couldn't even explain why it makes any sense to me. Can someone explain why this would make more sense than another combination of bools?
print(TTTGame.player + "'s TURN!")
print('pick a number 1 through 9')
position = int(input()) - 1
valid = False<<<<<<<<<<<<<<<<<<<<<<False
while not valid:<<<<<<<<<<<<<<<<<<<<<<<<<<<Not
try:
position = int(input('pick a spot'))
except (ValueError):
print('pick a number 1 though 9')
x = TTTGame.board[position]
if x == '-':
TTTGame.board[position] = TTTGame.player
else:
print('Cant Go There!')
TTTGame.board[position] = TTTGame.player
valid = True<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<True
Based on the code you provided I would have to try to work backwards to create a worse example, and without seeing what you did initially that may cause more confusion than it would help. A fair number of the things I mention are subjective to each developer, but the principles tend to be commonly agreed upon to some degree (especially in python).
That being said I will try to explain why this pattern is optimal:
Intuitiveness: When reading this code and looking from the outside I can tell that you are doing validation, primarily this is because just reading the code as plain English I see you are assuming the input to be invalid (valid == False) and won't leave the loop until it has been validated (valid == True). Even without the additional context of knowing it was a tic-tac-toe game I can immediately tell by reading the code this is the case.
Speed: In terms of how long it takes to complete this function, it will terminate as soon as the input is valid as opposed to some other ways of doing this that require more than one check.
Pythonic: In the python community there is an emphasis on 'pythonic' code, basically this means that there are ways of doing things that are common across various types of python code. In this case there are many patterns of validating input (using for loops, terminating conditions, seperate functions etc.), but again because of how this is written I would be able to debug it without having to necessarily know your whole codebase. This also means if you see a similar chunk of code in a large project, you are more likely to recognize what's happening. It follows the principles of the zen of python in that you are being explicit, while maintaining readability, errors are not passing silently and you are keeping it simple.
There's an algorithm currently driving me crazy.
I've seen quite a few variations of it, so I'll just try to explain the easiest one I can think about.
Let's say I have a project P:
Project P is made up of 4 sub projects.
I can solve each of those 4 in two separate ways, and each of those modes has a specific cost and a specific time requirement:
For example (making it up):
P: 1 + 2 + 3 + 4 + .... n
A(T/C) Ta1/Ca1 Ta2/Ca2 etc
B(T/C) Tb1/Cb1 etc
Basically I have to find the combination that of those four modes which has the lowest cost. And that's kind of easy, the problem is: the combination has to be lower than specific given time.
In order to find the lowest combination I can easily write something like:
for i = 1 to n
aa[i] = min(aa[i-1],ba[i-1]) + value(a[i])
bb[i] = min(bb[i-1],ab[i-1]) + value(b[i])
ba[i] = min(bb[i-1],ab[i-1]) + value(b[i])
ab[i] = min(aa[i-1],ba[i-1]) + value(a[i])
Now something like is really easy and returns the correct value every time, the lowest at the last circle is gonna be the correct one.
Problem is: if min returns modality that takes the last time, in the end I'll have the fastest procedure no matter the cost.
If if min returns the lowest cost, I'll have the cheapest project no matter the amount of time taken to realize it.
However I need to take both into consideration: I can do it easily with a recursive function with O(2^n) but I can't seem to find a solution with dynamic programming.
Can anyone help me?
If there are really just four projects, you should go with the exponential-time solution. There are only 16 different cases, and the code will be short and easy to verify!
Anyway, the I'm pretty sure the problem you describe is the knapsack problem, which is NP-hard. So, there will be no exact solution that's sub-exponential unless P=NP. However, depending on what "n" actually is (is it 4 in your case? or the values of the time and cost?) there may be a pseudo-polynomial time solution. The Wikipedia article contains descriptions of these.
I think the best way to form this question is with an example...so, the actual reason I decided to ask about this is because of because of Problem 55 on Project Euler. In the problem, it asks to find the number of Lychrel numbers below 10,000. In an imperative language, I would get the list of numbers leading up to the final palindrome, and push those numbers to a list outside of my function. I would then check each incoming number to see if it was a part of that list, and if so, simply stop the test and conclude that the number is NOT a Lychrel number. I would do the same thing with non-lychrel numbers and their preceding numbers.
I've done this before and it has worked out nicely. However, it seems like a big hassle to actually implement this in Haskell without adding a bunch of extra arguments to my functions to hold the predecessors, and an absolute parent function to hold all of the numbers that I need to store.
I'm just wondering if there is some kind of tool that I'm missing here, or if there are any standards as a way to do this? I've read that Haskell kind of "naturally caches" (for example, if I wanted to define odd numbers as odds = filter odd [1..], I could refer to that whenever I wanted to, but it seems to get complicated when I need to dynamically add elements to a list.
Any suggestions on how to tackle this?
Thanks.
PS: I'm not asking for an answer to the Project Euler problem, I just want to get to know Haskell a bit better!
I believe you're looking for memoizing. There are a number of ways to do this. One fairly simple way is with the MemoTrie package. Alternatively if you know your input domain is a bounded set of numbers (e.g. [0,10000)) you can create an Array where the values are the results of your computation, and then you can just index into the array with your input. The Array approach won't work for you though because, even though your input numbers are below 10,000, subsequent iterations can trivially grow larger than 10,000.
That said, when I solved Problem 55 in Haskell, I didn't bother doing any memoization whatsoever. It turned out to just be fast enough to run (up to) 50 iterations on all input numbers. In fact, running that right now takes 0.2s to complete on my machine.
I am aware that languages like Prolog allow you to write things like the following:
mortal(X) :- man(X). % All men are mortal
man(socrates). % Socrates is a man
?- mortal(socrates). % Is Socrates mortal?
yes
What I want is something like this, but backwards. Suppose I have this:
mortal(X) :- man(X).
man(socrates).
man(plato).
man(aristotle).
I then ask it to give me a random X for which mortal(X) is true (thus it should give me one of 'socrates', 'plato', or 'aristotle' according to some random seed).
My questions are:
Does this sort of reverse inference have a name?
Are there any languages or libraries that support it?
EDIT
As somebody below pointed out, you can simply ask mortal(X) and it will return all X, from which you can simply pick a random one from the list. What if, however, that list would be very large, perhaps in the billions? Obviously in that case it wouldn't do to generate every possible result before picking one.
To see how this would be a practical problem, imagine a simple grammar that generated a random sentence of the form "adjective1 noun1 adverb transitive_verb adjective2 noun2". If the lists of adjectives, nouns, verbs, etc. are very large, you can see how the combinatorial explosion is a problem. If each list had 1000 words, you'd have 1000^6 possible sentences.
Instead of the deep-first search of Prolog, a randomized deep-first search strategy could be easyly implemented. All that is required is to randomize the program flow at choice points so that every time a disjunction is reached a random pole on the search tree (= prolog program) is selected instead of the first.
Though, note that this approach does not guarantees that all the solutions will be equally probable. To guarantee that, it is required to known in advance how many solutions will be generated by every pole to weight the randomization accordingly.
I've never used Prolog or anything similar, but judging by what Wikipedia says on the subject, asking
?- mortal(X).
should list everything for which mortal is true. After that, just pick one of the results.
So to answer your questions,
I'd go with "a query with a variable in it"
From what I can tell, Prolog itself should support it quite fine.
I dont think that you can calculate the nth solution directly but you can calculate the n first solutions (n randomly picked) and pick the last. Of course this would be problematic if n=10^(big_number)...
You could also do something like
mortal(ID,X) :- man(ID,X).
man(X):- random(1,4,ID), man(ID,X).
man(1,socrates).
man(2,plato).
man(3,aristotle).
but the problem is that if not every man was mortal, for example if only 1 out of 1000000 was mortal you would have to search a lot. It would be like searching for solutions for an equation by trying random numbers till you find one.
You could develop some sort of heuristic to find a solution close to the number but that may affect (negatively) the randomness.
I suspect that there is no way to do it more efficiently: you either have to calculate the set of solutions and pick one or pick one member of the superset of all solutions till you find one solution. But don't take my word for it xd