A question on making fractals with python using turtle and recursion - recursion

from turtle import *
def snowflake_side(length,levels):
if levels == 0:
forward(length)
return
length /= 3.0
snowflake_side(length, levels -1)
left(60)
snowflake_side(length, levels -1)
right(120)
snowflake_side(length, levels -1)
left(60)
snowflake_side(length, levels -1)
def create_snowflake():
pass
# create_snowflake()
snowflake_side(200,2)
mainloop()
this is my code so in this as you can see 2 variables levels and length are passed to the function
levels is 2 before the first recursive call and 1 before the second recursive call.I didn't reassign it so how can it be 1

You call it with levels = 2
snowflake_side( 200, 2 )
And during that function, it calls itself with the current levels (2) -1
snowflake_side( length, levels -1 )
https://en.wikipedia.org/wiki/Recursion

Related

How to optimize this recursion function?

This is really similar to Fibonacci Sequence problem. I understand the DP optimization with Fibonacci function using the for loop, but I'm having hard time to connect to this problem.
The recursion function I want to optimize is:
def cal(n):
if n <= 0:
return 1
else:
return cal(n-25)+cal(n-26)
Something like this may help:
(It's inspired by previous post)
from functools import cache
#cache
def cal(n):
if n <= 0:
return 1
else:
return cal(n-25) + cal(n-26)
print(cal(100))
The idea of a "for loop optimization" is that we calculate cal(0), cal(1), cal(2), ... consecutively. And when we want cal(n), we already have cal(n-25) and cal(n-26) stored in an array.
So, the following solution has linear complexity for non-negative n:
def cal(n):
mem = [1] # cal(0) is 1
for i in range(1, n + 1):
num = 1 if i - 25 < 0 else mem[i - 25]
num += 1 if i - 26 < 0 else mem[i - 26]
mem.append (num)
return mem[-1]
One can further optimize to make all the values cal(1), cal(2), ..., cal(n) globally available after calculating the last of them.

In Julia, a value accessed from a matrix failed to be used as an argument in a function

First, I have a function called permeability.
# permeabiliy function
# L is short for the Lable
mu_0 = 4 * pi * 10^(-7);
mu_r_core = 50;
mu_r_air = 1;
L = Int16;
function permeability(L)
if L in 1:4
if L !== 3
return mu = mu_r_air * mu_0
else
return mu = mu_r_core * mu_0
end
else
println("null") #print output in a new line
end
end
Then, I have a matrix called domain, which is shown below,
domain
2392-element Array{Int16,1}:
1
1
3
1
...
When I called permeability(domain[3]), the output is,
L = domain[3]
permeability(L)
the output is
1.2566370614359177e-6
However, when I simply called permeability(3),
permeability(3)
the output is
6.283185307179588e-5
So, it seems that the value passed from matrix domain is just "1", but in this case, domain[3] should be 3 and the result should be the same in these 2 cases.
Can someone please tell me where I was wrong?
The problem is that your array stores Int16 while 3 is an Int64. L!==3 requires L to be of the same type as 3 ie Int64. You wanted instead L!=3. Your confusion probably comes from the fact that != is the inverse of == while !== is the inverse of ===

How do I refactor this function in ELM?

I am trying to pick up functional programming and decided to start with Problem 1 on Project Euler: basically add all numbers less than 1000 divisible by 3 or 5 (link: a link).
This is the code that I have written. It outputs a list of factors of 3 or 5 (still need to figure out how to sum).
import Html exposing (text)
import Array
main =
text (
toString
[findSum_maxZ 3 5 1000]
)
findSum_maxZ x y max_z =
Array.filter isDivisible_x_or_y (Array.initialize max_z identity)
isDivisible_x_or_y x =
if x % 3 == 0 || x % 5 == 0 then True else False
My issue is that I reference 3 and 5 twice but I cannot call isDivisible with the additional parameters of the more abstract 'x' and'y'. My goal is to determine effective methods of removing these artificially mutable values so the end user only has to modify each input value once. Any advice?
I apologize if this question is dumb, there is not a lot of information on ELM available (especially compared to python, c, c++, java, etc which I have used) and I am still not fully comfortable with the functional programming jargon. Any and all help is appreciated.
The cool thing about ML languages is that you are pretty much free to build your own "dialect" to solve problems.
You can use currying to apply just the x and y arguments to your function, creating a new function where the supplied values are already set.
import Html exposing (text)
import Array
main = [findSum 3 5 1000]
|>toString
|>text
findSum x y maxZ =
let
isDivisibleByX = isDivisible x
isDivisibleByY = isDivisible y
in
Array.initialize maxZ identity
|>Array.filter isDivisibleByX
|>Array.filter isDivisibleByY
--as you can see, it is possible to use a list instead of creating
--new functions, it is up to you to check which abstraction works
--the best
isDivisible a b =
b % a == 0
You can also work with a single function, without resorting to currying:
import Html exposing (text)
import Array
main = [findSum 3 5 1000]
|>toString
|>text
findSum x y maxZ =
Array.initialize maxZ identity
|>Array.filter (\n-> isDivisible x n ) --or just (isDivisible x)
|>Array.filter (\n-> isDivisible y n)
isDivisible a b =
b % a == 0
If you want to filter the array with just one line, you can do this:
import Html exposing (text)
main = findSum 3 5 1000
|>toString
|>text
findSum x y maxZ =
let
divisibles = \n-> isDivisible x n && isDivisible y n
in
List.range 0 maxZ
|>List.filter divisibles
isDivisible a b =
b % a == 0
The most direct answer to your question is that you can have isDivisible_x_or_y take the two factors, and then use currying to pass the partially applied function to Array.filter.
That is, you can define isDivisible_x_or_y like this (I also removed the if True then True else False syntax and just return the expression directly):
isDivisible_x_or_y x y val =
val % x == 0 || val % y == 0
Currying is the ability to only supply some of the parameters to a function, and get back a function that takes the rest of the parameters. So, the type definition of isDivisible_x_or_y is Int -> Int -> Int -> Bool (that is, it takes in three Int values and returns a Bool). If we supply values for the x and y arguments (e.g. isDivisible_x_y 3 5), we now get a function with the type definition of Int -> Bool. This is the type expected by Array.filter.
You can see a working example at https://ellie-app.com/sdxWFL9ynka1
Another couple of notes:
List is much more common than Array in Elm. You would only use Array if you need to get items at specific indexes. Instead of Array.initialize, you can use List.range
Using the pipeline operator |> can often make your code a lot simpler to read. Instead of text (toString (getValue)), you have getValue |> toString |> text, which is now in the order that the operations occur, and doesn't have extra parenthesis. This whole program could be one simple pipeline (in a lot of scenarios putting everything into one pipeline can be excessive, though):
main =
List.range 0 max_z
|> List.filter (isDivisible_x_or_y 3 5)
|> toString
|> text
isDivisible_x_or_y x y val =
val % x == 0 || val % y == 0

Why does this recurring function fire twice per input?

When executing:
def guess(a..b) do
IO.puts "In rn = #{a}..#{b}"
guess(a..b, IO.getn("Is it greater than #{div(a + b, 2)} ? : ", 1) |> String.upcase == "Y")
end
def guess(a..b, true) do
guess(div(a + b, 2)..b)
end
def guess(a..b, false) do
guess(a..div(a + b, 2))
end
Results:
iex(1)> Test.guess(1..10)
1 In rn = 1..10
2 Is it greater than 5 ? : y
3 In rn = 5..10
4 Is it greater than 7 ? :
5 In rn = 5..7
6 Is it greater than 6 ? : n
7 In rn = 5..6
8 Is it greater than 5 ? :
9 In rn = 5..5
10 Is it greater than 5 ? : y
11 In rn = 5..5
12 Is it greater than 5 ? :
13 In rn = 5..5
14 Is it greater than 5 ? :
iex did not wait for user input on lines 4, 8, & 12 - after receiving an input, it appears to run through the loop twice.
Why might that be?
Solved:
Apparently, something weird happens with IO.getn when used in this manner - perhaps reading "Y" as a byte, and "enter" as a separate byte. Replacing IO.gets and no character count seems to fix the problem. Alternatively, isolating the getn method call might keep this issue from occurring.
You are correct. When in the terminal, IO.getn/1 only returns the bytes after you enter a new line, which means if you are reading byte per byte recursively, you are going to receive two bytes, one for the user command and another for the new line. IO.gets/1 is the way to go here.

Recursive method function that counts binary 1s of an integer

I want to write a recursive method function that takes a nonnegative integer n as input and returns the number of 1s in the binary representation on n. I am instructed to use the fact that this is equal to the number of 1s in the representation of n//2 (integer division), plus 1 if n is odd.
Usage:
>>> ones(0)
0
>>> ones(1)
1
>>> ones(14)
3
ok so this is the code I got so far, it still doesn't work though. it gives me 0 no matter what I input as n.
def numOnes(n):
# base case
if n==0:
print (0)
elif n ==1:
print (1)
# recursive case
else:
return numOnes(n//2)+numOnes(n%2)
Thank you
These elements you need to do it yourself:
if integer & 1 == 1: # & is the binary and. & 1 will give the lowest bit
# there is a 1 in the end
integer = integer // 2 # loose one bit in the end
# or
integer = integer >> 1 # loose one bit in the end
Tell me if you need more input.
Your code works for me:
>>> def numOnes(n):
# base case
if n==0:
return (0)
elif n == 1:
return (1)
# recursive case
else:
return numOnes(n//2)+numOnes(n%2)
>>> numOnes(0b1100011)
4
You use print instead of return for the two base cases. Fix that and it'll work:
In [2]: numOnes(15842)
Out[2]: 9
In [3]: bin(15842).count('1')
Out[3]: 9

Resources