how to display a stack of 5 blocks using recursive function? - python-3.x

I am doing an exercise with recursive function and I don't quite get it. I need to update a function
def draw_stack(screen, x, y, height):
draw_block (screen, x, y)
In this function it should display a stack of 5 blocks in the screen anchored at the location x= 100, y =200.
How can I start this function? Can someone please explain how can I start my code?

def draw_stack(screen, x, y, height):
draw_block (screen, x, y)
for x in range(5): # This loop will run 5 times
draw_stack(screen, 100, 200, 50)# This will run your function. You need to specify functions arguments.
I if you want to change values while running loop you can to this:
for x in range(5): # This loop will run 5 times
draw_stack(screen, 100, 200+x, 50)# you can add or multiple any arg by x

Related

how do I make a for loop understand that I want it to run i for all values inside x. x being a defined array

My code right now is as it follows:
from math import *
import matplotlib.pyplot as plt
import numpy as np
"""
TITLE
"""
def f(x,y):
for i in range(len(x)):
y.append(exp(-x[i]) - sin (pi*x[i]/2))
def ddxf(x,y2):
for i in range(len(x)):
y2.append(-exp(-x[i]) - (pi/2)*cos(pi*x[i]/2))
y = []
y2 = []
f(x, y)
x = np.linspace(0, 4, 100)
plt.title('Graph of function x')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.plot(x, y, 'g')
plt.grid(True)
plt.show()
x0 = float(input("Insert the approximate value of the first positive root: "))
intMax = 100
i = 0
epsilon = 1.e-7
while abs(f(x0,y)) > epsilon and i < intMax:
x1 = x0 - (f(x0))/(ddxf(x0))
x0 = x1
i += 1
print (i)
print (x1)
I get this error when running the program. it seems that (len(x)) cannot be used if x isnt a string. which doesn't make sense to me. if the array has a len and isn't infinite, why (len(x)) cant read his length? anyway, please help me. hope I made myself clear
Regarding the error: You are using x before defining it. In your code, you first use f(x, y) and only after that you actually define what x is (namely x = np.linspace(0, 4, 100)). You probably want to swap these two lines to fix the issue.
Regarding the question in the title: len(x) should be fine to get the length of a list. However, in Python you don't need to go through a list like that. You can instead use for element_name in list_name: This will essentially go through list_name element by element and make it available to you with the name element_name.
There is also something called list comprehensions in Python - you might want to take a look at those and see whether you can apply it to your code.

Pass a variable into a for range loop and then grow the value?

In Turtle graphics I'm trying to create a series of boxes, one within the next. My main question is how does one pass values into a for i in range(4): loop and have the values increase or decrease by a value? Here, I've created two boxes but I'd like to make the second smaller and fit in the first?
import turtle as t
def block(x, y, length, scale):
for i in range(2):
t.up()
t.goto(x,y)
t.down()
for i in range(4):
t.forward(length * scale)
t.right(90)
block(100, 100, 100, 1)
t.mainloop()
You need to make your starting x and y coordinates and side length variables, change them every time through the loop, and move the turtle every time. Something like this:
import turtle as t
x = 100
y = 100
side = 100
decrease = 10
num_rect = 2
for i in range (num_rect):
t.up()
t.goto(x, y)
t.down()
for i in range(4):
t.forward(side)
t.right(90)
x += decrease / 2
y -= decrease / 2
side -= decrease
t.mainloop()

How are the values being determined in this basic Python class?

I am new to Python and to OOP concept. I was doing a EdX course and came across this code. I have modified it a little bit here. But I need to understand what exactly is happening here.
Question-1: Why does print(baba.x) give 7 but not 3?
Question-2: What does print(X) (capital X) do here? In getX and init I am using 'x' and not 'X'. So where does print(X) get its value from? It seems it is getting this value from the X=7 assignment. But isn't that assignment happening outside of the method getX and also outside of the class Weird. So why is getX able to access X=7 value?
I have searched on scope in Python, but was getting too complicated for me.
class Weird(object):
def __init__(lolo, x, y):
lolo.y = y
lolo.x = x
def getX(baba,x):
print (baba.x)
print (x)
print (X)
X = 7
Y = 8
w1 = Weird(X, Y)
print(w1.getX(3))
The output of the above code is:
7
3
7
None
Read What is the purpose of the word 'self', in Python?
class Weird(object):
def __init__(self, x, y):
self.y = y
self.x = x
def getX(self,x):
print (self.x) # this is the x value of this instance
print (x) # this is the x value you provide as parameter
print (X) # this might read the global X
X = 7
Y = 8
w1 = Weird(X, Y) # this sets w1.x to X (7) and w1.y to Y (8)
print(w1.getX(3)) # this provides 3 as local x param and does some printing

Jupyter notebook randomly stops utilizing all CPU cores

I am currently doing a simple regression task (No ML libraries involved, just my own code) for a homework assignment. The problem is Jupyter sometimes uses 95%+ of my CPU (this is good, I have a 8600k which i would like to utilize) but often decides not to use any extra thread at all and remains at a steady 20% usage. My feedback loop gets increased 6 times over just because of this.
I have looked around for any jupyter related settings that might be relevant but found none. Is there any explanation for this problem?
EDIT:
Here's the code i'm currently using. The data passed is a 30000x36 np array. I don't know how jupyter parallels this but hey, it does it sometimes.
def hyp(theta, X):
return X.dot(theta)
def cost_function(theta,X,Y):
return (1.0 / ( 2 * X.shape[0] ) ) * np.sum( (hyp(theta, X) - Y ) ** 2 )
def derivative_cost_function(theta, X, Y):
e = hyp(theta, X) - Y
return (1.0 / X.shape[0]) * X.T.dot(e)
def GradientDescent(X, Y, maxniter=400000):
nexamples = float(X.shape[0])
thetas = np.ones(X.shape[1],)
alpha = 0.001
print("Before:", cost_function(thetas, X, Y))
print_iter = 100
for i in range (maxniter):
dtheta = derivative_cost_function(thetas, X, Y)
thetas = thetas - alpha * dtheta
if i % print_iter == 0:
print(i, cost_function(thetas, X, Y))
print("After:", cost_function(thetas, X, Y))
return thetas
This looks more like a numpy issue than a jupyter issue. Take a look at https://roman-kh.github.io/numpy-multicore/ to make numpy use more cores.

How to handle a varying number of parameters on a function?

I'm trying to construct a code that gives a square's area and a rectangle's area with the same function, but I'm either running into missing positional argument error or something more exotic with whatever I do and I was flabbergasted by the potential solutions out there as I'm only a very basic level of python coder.
The biggest question is what kind of format should area() function be in order for me to be able to have it assume y is None if it's not given.
def area(x, y):
return x * x if y is None else x * y #Calculate area for square and rectangle
def main():
print("Square's area is {:.1f}".format(area(3))) #Square
print("Rectangle's area is {:.1f}".format(area(4, 3))) #Rectangle
main()
Do it like so:
def area(x, y=None):
return x * x if y is None else x * y #Calculate area for square and rectangle
By giving a default value, you may pass 1 less argument and it will be set to the default.

Resources