This implementation looks like it is broken. It creates the dict d
, but it never puts anything into it, so the check n in d
will always return false. Thus that case will never come into play.
The calculated results in the recursive case should be inserted into the dictionary.
The correct code would be:
d = {} def fib(n): if n == 1 or n == 2: return 1 elif n in d: return d[n] else: f = fib(n - 1) + fib(n - 2) d[n] = f return f
print fib(5)
I've found this immensely helpful...http://www.pythontutor.com/visualize.html
I'm in 600x too...find it taking way more than '6-12 hours a week' I'm also on this problem (and also stuck). Good luck!
Yes, flat = []
is initialized every time, but that is a different flat
, in a different version of the function. Once it is built and returns, you're back to the previous nested_sum
with it's own flat
Try stepping through the code on PythonTutor again: http://www.pythontutor.com/visualize.html#code=def+nested_sum(nested_list)%3A%0A++++++++++++flat+%3D+%5B%5D%0A++++++++++++for+i+in+nested_list%3A%0A++++++++++++++++if+type(i)+%3D%3D+int%3A%0A++++++++++++++++++++flat.append(i)%0A++++++++++++++++els...
And pay attention to step 11 when a second nested_sum
is created, and a second flat
is created after that, which is then returned and appended to the flat
from the first function
Edit: To add more, whenever you recurse, set the current function aside in your head and start an entire new version of that function. When that function returns, pick up where you left off in the previous function.
When I was making first steps in programming, I went through FCC exercises and I remember looking at some of these problems for hours and hours. Sometimes it felt hopeless, but soon I realized that if I keep working on them, however long it takes, I will always find the solution. Always.
On the road there were concepts that now feel so obvious, so simple and basic, but took me a lot of time and work to grasp.
​
Btw, check this out. http://www.pythontutor.com/javascript.html#mode=edit
It plays through your code step-by step and shows the state.
The codes sorts the list of tuples in ascending order.
the .sort()
method accepts a parameter key=
a function that servers as key for the comparison. Well and the lambda
function, takes a element (tuple) from the list and returns the second element of the tuple, eg lambda ('English', 88) : 88
.
So the criteria by which the list is sorted in ascending order is the 2nd element of each tuple.
You can visualize code at this website, by the way.
Advocates of TDD (test drive development) would say you have the order wrong: tests should be written first (before the code to be tested, in fact).
Using a visualiser can also be very helpful.
I find this site helps with understanding recursive programs. Click Forward to step through the program:
If you're into hacking, or want to be, python seems to be the way to go. I've found quite a few resources to some cool vids, tutorials, apps that integrate 'learn python' and 'learn to hack' material pretty well.
(here are just some general tips)
treat your knowledge as TOOLS rather than knowledge. what steps does this program need to achieve its goal and HOW can i make it less repetitive? how can i use this to make it better?
learn how to tinker with your program. change small parts and experiment with how that changes your output. very good skill to have when debugging as well since by process of elimination you can know where things went wrong.
do not be afraid to ask questions, in fact i would ask as many questions as outrageously possible and i suggest you do the same. learn how to ask questions about things you don't yet have vocabulary for or understand.
also, this isnt advice but this is a great resource for when you want to see your code go step by step, although keep in mind you can't really use any inputting functions or you have to switch it out http://www.pythontutor.com/visualize.html#mode=edit
I think Python Tutor will be helpful here. Despite having Python in the name it has support for - - Python - Java - C - C++ - JavaScript - TypeScript - Ruby
Honestly it feels like a full time job in and of itself haha, but I just finished the first section, web development 101.
I have all the programming finished for that last project, I just need to decorate it with CSS now :}
I was stuck on two things so far for weeks at one point, literally. I absolutely cannot move on comfortably without fixing every problem I come across in the main curriculum. But I pushed through it! And having Python Tutor (works with JS, Ruby & more!) REALLY helped me when I got stuck on a coding problem.
Honestly I've run into some ridiculous shit I don't think I'll ever understand, but at some points they actually tell you that it's okay to not understand. The point of it is to familiarize yourself with the documentation and problem solving.
This is a very good suggestion. Learning to see what the code is doing is a very important part of learning to code. Early on it can be hard.
​
There are tools that can help with this. For big stuff nothing beats a full debugger. For something small like this a simply tool to visualize the Python can be very helpful.
Ya Kno what helps me out? Something I can visualize. Don't think your up to robots yet but maybe thisll help: http://www.pythontutor.com/visualize.html#mode=edit
It shows you how your code works and what your doing wrong. Perfect for trial and error learning ;)
By no means am have I really "learned" Python but I know enough now that I can use it at work. Something that took me years to really understand is that there's a big difference between understanding the programming syntax and understanding how to solve like a programmer. Many people suggest reading a book then go do a project but that's IMHO a big jump depending on your goal. It's better to understand the core concepts of programming (variables, loops, logic), then understand Python syntax and built-in modules, then work through coding questions that apply simple programming (sorting numbers is a big one). Python has so many built-in modules that you can do a huge amount of projects when the time comes https://pymotw.com/3/.
Something that helped me is stepping away from the computer and picking up a pen to draw out my logic my program or figuring how my current program works. http://www.pythontutor.com/ is a great resource for this, and great for debugging.
Once you have an idea how to complete simple tasks, going to a project becomes easier. The other issue is that if you're trying to learn Python by completing a project, you may end of with a mess of code that works but will not give you foundational experience for the next project. If I look at some of my old Python scripts when I first started, they are awful, no functions, just a copy/paste from Stackoverflow. A large part of why it was a mess is due to my lack of experience and knowledge.
Now I'm focusing my time learning through coding challenge sites (recently found www.codewars.com and it's not too difficult for a non-CS beginner) and writing code at work. If I write something crappy, everyone will see it and deny my pull request, but I get feedback how to improve.
As my friend told me, "learn by doing". Hope this helps.
pythontutor.com (Despite the name, it handles C++)
I recently started using this online tool, though it's not a tutorial, it will come in handy later! I find it really useful to plug code in and look at it step by step.. really helped demystify concepts that are usually 'behind the scenes' so to speak.
I'm not sure if it visualizes enough or in enough detail, but this site allows you to see code run.
> Despite the name, it does work for Java. Just change the language in the drop-down box.
May not visualize what you're looking for though.
Thanks! That totally makes sense.
I guess I wasn't really understanding the -(i+1) part because when I put the code in this visualizer: http://www.pythontutor.com/visualize.html#mode=display
The i variable was still showing as positive. Your explanation made a lot of sense.
While searching online, I also found that I could achieve the same thing to reverse a string with string[::-1].
Thanks again!
This is an improvement. Though I would have left the "if x <= 2 return false" at the top. I don't know if that's a stylistic difference with no basis in "Best Practices", it just feels right to me to keep base case stuff at the top.
To answer your question, it's going to go through every n and if nothing meets the condition laid out on line 2.5, then it will return True.
If you watch it move through [frame by frame](http://www.pythontutor.com/visualize.html#code=def+is_prime(x%29%3A%0A++++if+x%3E%3D2%3A%0A++++++++for+n+in+range(2,x%29%3A%0A++++++++++++if+x%25n+%3D%3D+0%3A%0A++++++++++++++++return+False%0A++++++++return+True%0A++++return+False%0A++++%0Ais_prim...) it might make more sense.
https://automatetheboringstuff.com/ --> doesn't require prior programming experience
http://www.pythontutor.com/ --> you can paste code in this site and visually see how program executes
https://python.zeef.com/alan.richmond --> lot of Python related links, see if you can find something to your liking
http://www.pythontutor.com/visualize.html
Check out this tool, type in some similar code and play around. You'll see that python maintains a set of 'frames' which contain variables and references which a function can access. Being able to visualize the scope of your variables can come in super handy when trying to understand these sorts of concepts.
Your a' concept is pretty close to what actually happens.
Paste your code into here to see what is really going on. It has to do with what assignment (=
) means in Python.
d = {}
means that d
now refers to a new, empty dictionary. What ever it used to refer to doesn't matter and may still be referred to by something else.
If your a visual learner you can use the python tutor to step through each step to see what is happening. I've included a link below. Paste your code from pastebin and run the code. Step through and see what is happening each step of the way. Then insert the solution and see the difference.
Yes that's basically correct, a generator is a function that can return multiple times using yield
and saves its state.
> I'm not sure the role the for loop plays and what the i is iterating over.
The for loop actually consumes the items returned using yield
until the generator returns at its end. With a while loop you would have to consume the items manually using next()
and handle StopIteration which is far more complicated.
Maybe it helps to run your code in http://www.pythontutor.com/visualize.html as that can show you the process of the program with every step, including the variable values etc etc.
Basically it loops both I and j to 0 And prints an x, then loops all the way through j until n-j-1 == I in the first instance is 0 so j must be 9. Therefore it will loop j to 9 printing a blank space each time.
I'm really shite at explaining, I've popped into python tutor for you. If you step through this carefully you can see what is happening.
A small hint since you are using bank spaces, change the the blank space to a ^, this way you can actually see it happening
Let me know if this helps.
Depending on what you're using, you might try debugging it to see if the variable name changes as you expect. VSCode and others can do this in the IDE, or you can try doing it in http://www.pythontutor.com/visualize.html#mode=edit
​
Debugging helps me figure out what's going wrong/right/etc a lot.
I'm a beginner too, what helped me the most are these few things:
Try Berkley 61A. It’s considered the intro class and is taught with Python. The reason I like it is because it teaches “computer science” fundamentals, not Python; the course just happens to use Python as the language. The course will introduce you to something called Python Tutor, http://www.pythontutor.com, it’s basically a web app that frames/debugs your entire code line by line. This really helped me. I would draw my code on paper in the same format as Python tutor at the start. If you do almost all of their assignments and don’t passively do the course this may help you; that was the trick for me.
Additionally I still struggle with Python. After learning Java, which is more verbose, Python became more clear. Python has so many features and there can be a lot going on underneath all the brevity of Python code. Java made those things more clear. Maybe that is an option.
Definitely practice, practice, practice. I use codewars.com with my students.
Also, try to learn the underlying principles for how programs work - like understanding memory allocation of variables, scope, how interpreter executes a program, etc. This tool: http://www.pythontutor.com/visualize.html can be useful for that. It shows what definitions are in memory at any point, what order things are getting executed, etc.
When you call a function, a new stack frame is created with its local variables specific to that frame. When you return
, you return to the previous frame where you left off.
See if this visualization helps (it's in Python, but the stack works much the same). Click «Forward», observe, and ignore the global frame.
I find the best way to understand code when struggling is to use a Python Visualiser.
So, I've taken the liberty of posting the code you shared into a visualiser, together with some sample data and a call, so you can step through it and see exactly what is happening. You might want to add an assignment of the referenced element just so you can see what is being referenced:
It depends on what exact visualizations you want.
There are tools like Python tutor (which, despite its name, has support for other languages) that let you visualize code execution. These can be really helpful for understanding recursion, or just programs that have a lot of aliasing going on.
Your friendly neighborhood debugger in your IDE can also be very handy. Though it's less visual, it's just as useful because it'll let you step through your code and observe the values of all your variables.
There's also IDEs like Tenacious C that focus on helping you visualize your memory and pointers.
Unfortunately I'm not sure of anything like the above for Go, but hopefully that will give you some places to look. I'd try a google search like "Visual Go debugger" or just "Go debugger" to get started.
Happy coding!
It's pretty complicated; you are either gonna have to use pencil and paper to understand it or check out this: www.pythontutor.com/visualize, then press Visualize Execution and keep pressing next.
Don't forget this amazing app! :)
​
http://www.pythontutor.com/javascript.html#mode=edit
​
Is there anything better than this to visualize JS code execution? VS Code debugger with the Chrome debug extension is nice, but your list needs web sites.
Hey,
This page is great when you are stuck like this on relatively short programs :
http://www.pythontutor.com/visualize.html#mode=edit
You can track step by step how your code behaves and find the problem.
The way I found to easily get my head around this is that when you write a_var = some_thing
(and a bunch of other 'assignment' operations) all you are doing is making the label on the left point to a location in memory where the actual some_thing
resides.
When you assign another label to your first one, eg b_var = a_var
all you are doing is pointing b_var
to some_thing
.
There's a great resource for watching this happen live in your code here: http://www.pythontutor.com/visualize.html#mode=edit
(As others have said, it helps people to read your code snippets if you format them - see the 'formatting help' button below the text entry window)
In python the loop is going to run between the numbers in the range. Then it's going to run whatever is in the loop that many times.
So your first for loop is going to run in range of (1 and 4) because size is 3 and you are doing
range(1, size + 1)
so it will run 3 times cuz it will run from 1 to right before the stop number
Now on the first loop of your outer for loop it's going to run the inner function however many times it needs which the first time line is going to be 1 and then after the inner loop runs it's desired number it will jump out and line will become 2 and then it will go back into the inner for loop and run it's desired amt of times. Rinse, wash and repeat those steps until the outer loop satisfies it's range
Alternately you may like http://www.pythontutor.com/visualize.html#mode=edit Throw your code in their and hit "visualize execution" to run through the code line by line
why do you think it would that result to nothing?
so after making a function, we need to call it if we want to use it like this:
cube(3)
A little sidenote, number
is called a parameter and 3
in this case is called the argument. We are passing the value 3 as an argument to our cube
function where this 3 will be stored into number. To test this out you could do print(number)
before you return anything to see what I mean.
Dont get too hung up on the names, they don't do anything special in these cases, they are written like that for readability purposes because we want to put on a single number in there, hence number
.
That's an excellent observation! Here's what it looks like visualized in Python Tutor. Can you tell me what the difference appears to be?
In case anyone reading this doesn't know about it, I suggest using PythonTutor for visualizing code step by step. It helps see what went wrong and exactly where.
The thing is, recursion
means that you need to make your function call itself again inside it. Be carefull and avoid infinite loops!
One of the most common examples of recursion is the factorial one:
def factorial(n): if n == 1: return n else: return n * factorial(n-1)
You should check it in here as to see a good representation of what it does.
For your excersice, you need to go through the list they give you, and decide if it is a list and does count as a list and get recursive, or not.
This isn't what you're looking for, but it's extremely helpful for learning what's going on in your code step by step.
http://www.pythontutor.com/visualize.html#mode=edit
I stumbled across this site when I was first learning python and it really helped me figure out the bugs in my beginner projects.
(Sorry if link isn't active, I'm on the mobile app)
Hi mate,
From my perspective, as a fellow Python newbie and reader of ATBSWP book, the basic concepts were relatively easy to get my head around. Alike you, I came across the practice programs after the first couple of chapters and it suddenly became a lot more daunting.
I believe that persistence is the key. I feel like I'm still making progress, albeit a lot slower than when I started. And, when you eventually conquer those little coding tasks, it feels like a huge victory (I was punching the air with joy today after I completed problems 1 & 2 on the first week of the MITx course on edX - although I've spent the past few hours struggling to complete problem 3).
You get it; I'm certain you do.
I haven't tried these yet, but here are some more Python tasks to help you practice. Try and use a range of resources - as others here have suggested.
Also, this gets posted a lot, but you can visualise code on this website. It's helped me on occasion when I've studied other peoples' code.
because return value of function f
is g
... which is also evident in <function f.<locals>.g
you can check out http://www.pythontutor.com/visualize.html#mode=display where you can copy paste this code and see flow of execution and variable values
your code works great in python when i do it. But i wanted to understand it so i put it into http://www.pythontutor.com/visualize.html#mode=edit . Why does python tutor print everything and my python on my computer return one list? (sorry for the dumb questions)
You should step through your code. Either use this, and eventually install an IDE so you can step and debug within the editor itself.
Or, you can use the trace module, but it's output is ugly.
And, what do you expect this to do? Go through it line by line, and "execute" it in your head like you're python. What do you expect the output or behavior to be once that line is executed?
usedBlock2
contains three references to the same list.
usedBlock2= [[None] * 3] * 3
is
tmp = [None, None, None] usedBlock2 = [tmp, tmp, tmp]
Which language are you coming from?
https://automatetheboringstuff.com/eval/3-3.html here is one example of how python evaluates; I recommend his course highly, free book and up to 15 videos for free as well, very useful resources side by side.
Here is another website where you can see how python evaluates everything, step by step.
this is your example, evaluating
If you don't "return search()" you are simply calling your search function and throwing away what it has returned (the true or false). So at the end, you will return false since that is your default. In a recursive function, which you've written, you need to return the results of the function back to itself so it can keep doing the search.
Maybe a visual will help? There's a website that lets you visualize your code (it's experimental for the C language, but I tried it and it works for this example.) Here's [the link to it](http://www.pythontutor.com/visualize.html#code=%0A++++%23include+%3Cstdio.h%3E%0A++++%23include+%3Cstdbool.h%3E%0A%0A++++bool+search(int+value,+int+values%5B%5D,+int+min,+int+max%29%0A++++%7B%0A+++++%0A++++++int+midpoint+%3D+(max%2Bmin%29/2%3B%0A+...) If you step through the execution (using the forward button under the code) you can see exactly what is happening.
This is the visualizer I use. It works for JS, Java, Python and Ruby and has the added bonus of shared sessions.
These are definitely a must for any beginner.
As /u/jedwarsol said, the problem you're getting is because you're removing elements as you're walking trough the array. The length of listy keeps changing, some you'll eventually encounter some bad behaviour with your while condition "while i < len(listy)". [Here's a link](http://www.pythontutor.com/visualize.html#code=listy+%3D+%5B3,4,5,6,7,8,9,10%5D%0D%0Ai+%3D+len(listy%29+-+1%0D%0Awhile+i+%3E%3D+0%3A%0D%0A++++current+%3D+listy%5Bi%5D%0D%0A++++if+current+%3C+7%3A%0D%0A++++++++listy.remove(current%29%0D%0A++++i+%3D...) to help you visualize how the correct version runs. You can go step-by-step through the running if it. Hope this helps!
[Here is a visualization. This is in Python, but it has the same semantics.](http://www.pythontutor.com/visualize.html#code=def+invert\(a%29%3A%0A++++temp+%3D+a%5B0%5D%0A++++a%5B0%5D+%3D+a%5B1%5D%0A++++a%5B1%5D+%3D+temp%0A++++%0Aarray+%3D+%5B1,+2%5D%0Aprint(array%29%0Ainvert(array%29%0Aprint(array%29&mode=edit&orig...)
As you can see, a
parameter inside the invert function "points to" the same object (array) that the array
variable on the outside points to.
Does that help?
for idx, e in enumerate(l): l[idx] = int(e)
Basically, enumerate() creates a generator that outputs a tuple, comprising the index of an element in a structure and the corresponding element. Calling list(enumerate(l)) would return all of the tuples that the generator would return in a list. Inside the loop, for each tuple, we cast the element to an integer and then overwrite the element in the list. [Forgive me if this sounds confusing, it still does to me and I've been doing this for 3 years!]
[Here](http://www.pythontutor.com/visualize.html#code=l+%3D+%5B%221%22,+%222%22,+%223%22%5D%0Afor+idx,+e+in+enumerate(l%29%3A%0A++++l%5Bidx%5D+%3D+int(e%29&mode=display&origin=opt-frontend.js&cumulative=false&heapPrimitives=false&text...) is a visualisation of what happens inside your loop - you can step through it and see the changes in real time.
It might help to visualize the different stack frames which each represent one of the "particular recursive call"s that you were talking about.
It's kind of like an onion... or similar nested structure. return
peels off one layer of the onion, and there are as many layers as you have recursive calls.
It looks like your best friend, as was mine, is going to be Python Tutor.
It shows you graphically what is going on line by line, for simple programs under 100 lines and no imports.
Check it out.
>>> >>> def cube(n): n**3
>>> cube(2) >>> a = cube(2) >>> a >>> print(a) None >>> >>> def cubicle(n): return n**3
>>> cubicle(2) 8 >>> a = cubicle(2) >>> a 8
besides that, return means return from the function. It doesn't read the next line, it stops cold and and passes the value to whatever is waiting for it. Although if you take a recursive function and run it in http://www.pythontutor.com/ , maybe that phrase 'stops cold' was not such a good choice. It stops further loops or recursions or progress to lines farther down in the function.
What is it that handles the value? I dunno, but I have not let ignorance stop me so far, so: If I had to guess, I'd say the interpreter assigns it a memory location and tells the calling function or statement where to find it. Looking forward to an answer on that one.
Nice catch. Also, there's a geohashing function, a reference to http://xkcd.com/426/
Also, the bold text is due to double underscore: __text__
becomes text. We're all learning something new today, huh.
It would probably be pragmatic to just use code formatting for code next time, eh? Quote:
import webbrowser webbrowser.open("http://www.pythontutor.com/visualize.html#mode=edit")
> go to shell, type
import TUTOR__
So, I knew about this, but never thought about how it happened. There has to be a module named antigravity
, and where are modules? I open python27/Lib, scroll down and holy crap, there it is. Except it's antigravity.pyc
. Just to make sure, I open that in an edit window and sure enough it's gibberish. Anybody but me wonder how compiled code has to have NUL
so many times? But that's not important now. Oh wait, right under the .pyc is antigravity.py. Let's open that and see all the complex machinery involved in getting the python shell to navigate the treacherous seas like brave Odysseus and somehow wrestle the os into submission and make it go to the internet and find this thing. I'm almost afraid to look. I cover my eyes and move out from directly in front of the monitor, click. No explosions, smoke detector didn't go off. Cautiously peek between fingers. I see....
If you don't already know, go take a look.
That is not what I expected.
But wait, it has to import a module, webbrowser and use its method,
.open('siteaddress')
So I go back to Lib, find webbrowser.py, take a look at that. In an initial glance-through I cannot claim to understand it, but it's pretty small for a module.
So
Ctrl+N from shell save as C:\Python27\Lib\TUTOR__.py '''then type''' import webbrowser webbrowser.open("http://www.pythontutor.com/visualize.html#mode=edit") go to shell, type import TUTOR
then type
import webbrowser
webbrowser.open("http://www.pythontutor.com/visualize.html#mode=edit")
go to shell, type import TUTOR__
and I still am amazed, it actually worked.
I just thought here in the beginners' sub there might be somebody else who could have a eureka moment over this.
edit: I do not know what activated the bold in that, I don't see any double asterisks. Somebody enlighten me
edit again: "it's". holy crap, I have been here too long.
Paste your code in here with just the first test routine
http://www.pythontutor.com/visualize.html#mode=edit
And hit "Visualize Execution"
Then hit forward to step through the code. Make sure the variables equal what you expect at each step (I think you'll see the issue quickly)
when you declare a function (with def
) you specify which parameters (which are variables inside the function) it will accept, those variables get their values when the function is called as the values that are passed to it.
in practice:
Python 2.7.3 (default, Mar 13 2014, 11:03:55) [GCC 4.7.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> # function declaration ... def my_function(has_a_parameter): ... # this code won't be executed until the function is called ... print "the variable is: %s" % has_a_parameter ... >>> # now we call it passing it some arguments ... my_function("foo") the variable is: foo >>> # again with a different value ... my_function("bar") the variable is: bar
try the Python Tutor it helps visualize the code while is running.
To get an understanding of what is happening try pasting the code here. It's a pretty good tool, and you can see what /r/indosauros explained, that the different x's are unrelated to each other.
Plug your code into http://www.pythontutor.com/visualize.html# and you'll see exactly when/why the loop exits. As explained by the other posts, it's because you're performing integer division. If you were to turn your input num_digits into a float for example, then indeed the while loop would never end. Try turning your last line into
print num_digits(float(710))
and plugging it all back into http://www.pythontutor.com/visualize.html#
and you'll see that instead of the 16 steps with integer 710 this tool reports > (stopped after 300 steps to prevent possible infinite loop)
when the float is used.
This is the type of problem you can visualize in PythonTutor. I had to cut the number of loops, but you will see what is happening.
Are you getting back an error? Forgive me if you have already done this, but usually just Googling the error will help point you in the right direction. There is also the course chatter, and testing bits of your code on sites like python tutor, and Replit which will actually help with multiple languages without publicly sharing your code.
Glad it helps. I've just made some small corrections to my typing.
You might also like to try a Python Visualizer where you can step through code a line at a time and see a visual representation of what is going on.
Can you give a sample program you tried and the error you are getting? Screenshot might help too.
You can also these online tools:
Next time it helps to use a visual debugger like http://www.pythontutor.com/visualize.html or inside your coding program like in Thonny or Pycharm, as then you can see what each part of the program is actually doing ;)
When I run it in http://www.pythontutor.com/visualize.html it shows it's ending up in the last few lines in select, at
while quantity != 0 and len(available) == 0: for i in near: if t[i - 1] == " ": available[0] = [pos,i] return i quantity -= 1
then in that part to actually return something,
if t[i - 1] == " ":
must be True (as the return statement is inside its clause). However in t
, which references board
, there is no space string... There are just
So maybe you meant to check for =="[ ]"
?
Because you are setting your counters to 0 for every character in s. What you meant to do was to set them to 0 before the loop, meaning it will just execute once before the characters are iterated.
In these cases it helps to use a visual debugger like http://www.pythontutor.com/visualize.html as then you can step through the code one line at a time and see what's going wrong.
I don't know if you're using one of the languages supported by this site, but it was an excellent tool in helping me understand recursion:
[http://www.pythontutor.com/](python tutor) is a good place to learn about python, and there's some free python courses on [https://www.codecademy.com/learn/learn-python](codeacademy) (although it's an old version of python, the concepts are mostly the same).
Anything specific you're wanting help with?
people already answer your question I just want to pass this tool along.
http://www.pythontutor.com/visualize.html#mode=edit, it'll help you with this situations in the future
> If the callback function is replacing what function inside the main function
"Replacing" is probably the wrong word. It isn't a text substitution.
> shouldn't the parameter value be the same?
It's important to distinguish between a parameter's *name* (such as "val1") and a parameter's *value* (such as 2). A variety of parameter names can all still refer to the same value.
let x = 2; let a = x; let val1 = a let duex = val1;
See also if this visualization helps. (Click next to step through the code.)
Run your code in http://www.pythontutor.com/visualize.html to see the effects of each line in the code visually while running it. Basically because
y = lambda x: x+2
before
return z(y)
thus makes z execute with
z(lambda x: x+2)
and in z,
return x(5)
means it will thus return 5 + 2 = 7. The rest is just a return path back to the print call, without affecting that value.
It helps to run your code in a visual debugger like http://www.pythontutor.com/visualize.html , as then you can watch the variables changes per step in the program.
> Why is the output [9, 8, 7, 8]?
Because the if i % 2 == 0:
only executes when i
is even (and thus its remainder when divided by 2 is 0). As your range runs from 1 to, but not including, 4, it means only when i
is 2, the
k[i+1] = i**3
statement is executed. That assigns 2**3
which is 8 to k[2+1]
which is k[3]
and the last value in k
(having 4 items). That's why the last item in k
then changes from 6 to 8.
> How is the above code different from the below code?
It just prints k
after the loop is done, while the first code snippet prints it during every loop run (as it's placed inside it).
The +=
syntax adds to a variable in-place each time it is executed.
You can also do *=
(multiplying your variable and set it to the result), /=
(division), and -=
(subtraction).
I feel like you'll find this useful. Python code execution visualized.
Beh credo tu non abbia idea di cosa stai parlando? Dipende dal comune il tipo di persona che dice che la memoria è allocated e deallocated, suggerisco questo sito:. http://www.pythontutor.com/cpp.html#mode=edit. Quando lo Stato sarà in grado di mettere le mani in pasta NON lo voglio e i più lo accettano.
Yep, that seems like a bug. Tried it from my phone and it wasn't playing nicely. I tried implementing a variation of your code over at Python Tutor and had no issues (apart from their page having less than ideal behavior on mobile)
Se vuoi vedere come la memoria è allocated e deallocated, suggerisco questo sito:
http://www.pythontutor.com/cpp.html#mode=edit
Si può usare con Python, C++/C, Java, etc ... io lo consiglio spesso ai miei studenti, specialmente per code così che è piccolino ma lo stesso un po’ complicato.
It appears a little complex but its not.
Lists start at 0, so if we look at a:
apple = 0
banana = 1
republic = 2
for i in range(len(a)) is 0, 1, 2 - each item in a
for j in range(i+1) will step back and remember that lists start at 0
So to get it to print, once, we need to do 0 + 1 = 1?
To get it to print twice, we need to do 1 + 1?
for j in range(i) (remember, i is 0, 1, 2) + 1 is (1,2,3)
And there we have our print once, twice, three times!
and the print statement is calling a by index;
so now we go back to lists start at 0, apple = 0, banana = 1, republic = 2.
We will go ahead and say;
print(a[0]) would print apple, print(a[1]) would print banana.
Any questions? maybe printing it will help visualize it?
here is the code if you want to run it yourself
and here is a walkthrough that shows you each step!
This is easy to spot if you run this in http://www.pythontutor.com/visualize.html
> but "while řádek <= 100:" doesn't work. I
It works fine, but you never reset radek to 1, so after
print("\n" + "1") # + "1" just for mark next line další = další +1
the outer loop restarts, it runs
while řádek <=100:
then radek is still 100, and thus the loop will be skipped.
position is a list of indexes, but
for i in string:
will iterate on the values, not the indexes. use enumerate for that
for idx, val in enumerate(string): if idx in position: string[idx] = reverse_vowels[idx]
Btw I found the error using http://www.pythontutor.com/visualize.html , I can advise to try that too to help you find other errors.
Something like this?:
It’s not so good looking like your pic but it’s definitely enough.
I haven’t found an extension for vscode. But you can paste your code in there.
I am new to this too so a colleague of mine advised me to use pythontutor to visualize my code line by line to see what happens, it is a bit easier for me now http://www.pythontutor.com/visualize.html#mode=edit
Hey this isn’t a YouTube channel but if your looking for a cool way to see how the code works http://www.pythontutor.com/visualize.html it shows you every step the program is doing. I’m a beginner and this has helped me with understanding why my code isn’t doing what I’d like it to do.
For your little snippet of code, continue
does absolutely nothing.
The reason 2, 3, and 4 are printed is because your print statement is under the first for loop (for i in range(0,3)). So the print statements occur when j = 2.
j will always be 2 before executing the print statement because 2 is the max in range(0,3)
So when j=2 it will exit the second for loop and go to the print statement
​
I recommend putting your code in here and visualizing it: http://www.pythontutor.com/visualize.html#mode=edit
>>> for i in range(0,3):
... print (i)
...
0
1
2
Hey,
You are iterating over the list AND modifying it at the same time. If you don't understand what impact it'll have, it will be best that you copy the list and iterate over the copied list.
To get your expected output, you have to modify your code as:
numbers = [1, 3, 4, 3, 5, 7, 4, 3, 4, 6, 7, 6, 5, 4, 5, 6, 7, 8, 9, 8, 5, 3, 2, 1] numbers2 = numbers[:] for potential_numbers in numbers2: number_of_number = numbers.count(potential_numbers) if number_of_number > 1: numbers.remove(potential_numbers) else: print('ok') print(numbers)
To get more idea about what's going wrong, you should paste your code on http://www.pythontutor.com/visualize.html#mode=edit and then click visualise execution.
True
and False
have the numerical value of 1
and 0
respectively. Here are a few print calls added to your python tutor example to demonstrate:
print(True == 1) print(False == 0)
print(True + True) print(True + False) print(True - True) print(True * False)
I struggled with Mario for a day or two I had an idea in my head but I couldn't make it work then I found the website below that steps through the code this is how I finally got it to work http://www.pythontutor.com/c.html#mode=edit P.S you need to declare the veribels as it can't use the cs50 librarys
Say we have 4 people in a group and we need to find the maximum age by just comparing 2 people at a time.
m = maximum(lst[1:])
basically means: save the maximum of the other people, which is the result of calling maximum()
on the other people, as the variable m
.
If it still doesn't click, run the code on http://www.pythontutor.com/visualize.html with for example
maximum([1, 2, 3, 4])
as the final line
The best tool for this kind of issues is to run the code in http://www.pythontutor.com/visualize.html, so for example with a convert_to_words('12')
underneath it. Then when you step through the code one line at a time, you see that it goes into this block
64 # Need to explicitly handle
65 # 10-19. Sum of the two digits
66 # is used as index of "two_digits"
67 # array of strings
68 if (ord(num[x]) - 48 == 1):
69 sum = (ord(num[x]) - 48 +
70 ord(num[x]) - 48);
71 print(two_digits[sum]);
72 return;
because the first digit is a 1, then uses a look up table to find the word by calculating the sum of both digits. This doesn't work properly because he does
69 sum = (ord(num[x]) - 48 + 70 ord(num[x]) - 48);
which both index [x]
and thus add the same digits together, being the first one (which was already established to be a 1) and thus it will always calculate 2 and then deduces the number must be 11...
You can do free python courses on Coursera. When you click on the enroll button for whatever one you select.. just scroll to the bottom and press "audit course". You kinda lose some perks like getting your assignment graded .. but its better than nothing lol. Plus you can receive help online through http://www.pythontutor.com/ (never tried it but our professor for 175 lists it on the resource list) or the many websites dedicated to CS questions. Good luck.
Please format your code in a coding block so we can see where your new lines and indents are (Google "format code in reddit") - it will make it easier and faster for us to help.
The while
statement is a looping function, the way you've got it set up, it will check your input against the conditions and while the condition is not satisfied, it will prompt you for another input.
On it's own, the if
function is only evaluated once.
If the sys.exit() is outside the if
statement (ie it's not indented and part of the true or false cases, then the sys.exit() will be the next thing to be processed directly after the evaluation of the if
statement.
The Python Tutor Vizualization could be helpful for your understanding here.
Paste your code in http://www.pythontutor.com/visualize.html and walk through it step by step. It will return True because
if inputstr[0] == inputstr[-1]:
is False, f
isn't equal to s
. To me that would mean it should return False
right?
Could you point me in the right direction for an answer on this one?
Why and how is python making -x an x? just tried visual python but it does not show. I would really like to become familiar with the inner workings of this behavior.
import pandas as pd
df = pd.DataFrame(dict( Content = ['String A', 'String B', 'Glasses C', 'String D', 'String E'], ))
start_i = df[df['Content'].str.startswith('Glasses')].index[0]
mynewdf = df.iloc[start_i:]
print(mynewdf)
It helps to run code you can't quite follow in http://www.pythontutor.com/visualize.html to let it execute step by step while you can watch the state of each variable.
Just to be clear here, an if
is not a loop. A loop repeats, that's why it's called a loop... An if
is just a block that executes if an expression evaluates to True.
In the code's case, the program does
if is_win(user, computer): return 'You won!'
meaning it will only return You won!' if the result if
is_win(user, computer)is evaluated to True. That
is_winis not a variable, it's a function (as it's defined using the
defkeyword). That function returns True when from another
if`:
if (player == 'r' and opponent == 's') or (player == 's' and opponent == 'p') \ or (player == 'p' and opponent == 'r'): return True
so if any of the expressions (connected by or
, meaning just one of them needs to be True) then then function will return True
. Causing the if
that called it to execute its block and
return 'You won!'
is being executed too
Python Tutor is great for looking at things like this. Here's your first example on python tutor, and here's your second example.
Go to each of those links and click Next to see a visualization of the data structures created by each example. In the first example a single dictionary is created, and then each element in the list points to that same dictionary. In the second example you're creating a new dictionary on each pass through the loop, so each item in the list points to a separate dictionary.
That's why the book uses language like "a variable is assigned to a value" rather than "a variable holds a value". It's a subtle difference, but an important one in understanding what's really happening with your data. This is a really good question, and your simple example at the beginning does a nice job of focusing on the core aspects of this issue.
Try the code samples on http://www.pythontutor.com/visualize.html there you can walk through the execution step by step. It will also show the recursive levels.
See https://i.imgur.com/HT4Zz88.gifv on how to use proper formatting.
You have to return a reference to the object of interest if you want to use/consume it outside of the function. If you just want to output it using print in the function and not use it outside of the function, go for it.
That is unless the function has mutated an object available in wider scope.
Keep in mind that in Python, variables do not hold any values but rather a reference (pointer) to some Python object held somewhere in memory at the discretion of the Python implementation you are using.
So, when you say return n
you are returning the reference n
holds to some object to whatever bit of code somewhere else made the call in the first place.
A good place to see this in action is using a Python Visualiser such as http://www.pythontutor.com/visualize.html#mode=edit