Python TypeError: 'float' object cannot be interpreted as an integer - python-3.4

My code:
for i in range( 3.3, 5 ):
print( i )
The above code have to print:
3.300000
4.300000
but the interpreter of Python 3.4.0 printed the following error:
TypeError: 'float' object cannot be interpreted as an integer

range() works with integers not floats, but you can build your own range generator which will do what you want:
def frange(start, stop, step=1):
i = start
while i < stop:
yield i
i += step
for i in frange(3.3, 5) will give you the desired result.
Note though, that frange will, unlike range but like xrange, return a generator rather than a list.

Related

How to use vector as argumant in odeint scipt

this is My Code:
Ue=2.16
#Ta=np.random.randint(20,30,24)
Ta=34
A=3
C=1000*750*0.15
h=6
Gc=h*A
def C001(T,t,Ue,A,C,Gc,Ta):
T1,T2=T
dTdt=[
(Ue*A*(T2-T1)+Gc*(Ta-T1))/C,
(Ue*A*(T1-T2)+Gc*(Ta-T2))/C]
return dTdt
Ts=[25,25] #initial conditions
t=np.linspace(0,24,24)*3600 #integration interval
result=odeint(C001,Ts,t,args=(Ue,A,C,Gc,Ta))
fig , ax=plt.subplots()
ax.plot(t/3600,result[:,1],color='tab:red')
ax.grid()
ax.set_xlabel('Time (Hours)'
The problem is :
whene i try to replace Ta with np array so it is integrated with time t i get an error of
"The array return by func must be one-dimensional, but got ndim=2." even though the vector t and Ta has the same shape (24,)

N long tuple as optional argument

I would like to have an N long tuple as an optional argument of a function but I do not know how to provide a N long default value:
function create_grid(d::Int64, n::Tuple{Vararg{Int64, N}}; xmin::Tuple{Vararg{Float64, N}}) where N
I understand xmin should be declared with a default value such as xmin::Tuple{Vararg{Float64, N}}::0., but this is evidently wrong as it is defaulting to a Float instead of Tuple. How can I state I want a N long tuple as optional argument defaulting to (eg.) 0. for all the elements if the argument is not provided explicitly?
Here it is - you just provide the default as a one element tuple:
function somefun(d::Int64, n::Tuple{Vararg{Int64, N}}; xmin::Tuple{Vararg{Float64, N}}=(0.0,)) where N
println("d=$d n=$n xmin=$xmin")
end
To understand how it works just note that:
Tuple{Vararg{Int, 2}} == typeof((2,2))
#and
Tuple{Vararg{Int, 1}} == typeof((2,))
so you needed 1-element tuple as a default.
Let's test it:
julia> somefun(4,(4,))
d=4 n=(4,) xmin=(0.0,)
This works as expected.
Finally, note that providing a 2-element tuple as the second argument without the third one will throw an error because the sizes do not match:
julia> somefun(4,(4,5))
ERROR: MethodError: no method matching #somefun#1(::Tuple{Float64}, ::typeof(somefun), ::Int64, ::Tuple{Int64,Int64})
If you want to workaround this you need another constructor:
function somefun(d::Int64, n::Tuple{Vararg{Int64, N}}; xmin::Tuple{Vararg{Float64, N}}= tuple(zeros(length(n))...)) where N
println("d=$d n=$n xmin=$xmin")
end
Testing:
julia> somefun(4,(4,5))
d=4 n=(4, 5) xmin=(0.0, 0.0)

Using invalid character "²" for squared. Extend Julia syntax with custom operators

In my equations we have many expressions with a^2, and so on. I would like to map "²" to ^2, to obtain something like that:
julia> a² == a^2
true
The above is not however a legal code in Julia. Any idea on how could I implement it ?
Here is a sample macro #hoo that does what you requested in a simplified scenario (since the code is long I will start with usage).
julia> x=5
5
julia> #hoo 3x² + 4x³
575
julia> #macroexpand #hoo 2x³+3x²
:(2 * Main.x ^ 3 + 3 * Main.x ^ 2)
Now, let us see the macro code:
const charsdict=Dict(Symbol.(split("¹²³⁴⁵⁶⁷⁸⁹","")) .=> 1:9)
const charsre = Regex("[$(join(String.(keys(charsdict))))]")
function proc_expr(e::Expr)
for i=1:length(e.args)
el = e.args[i]
typeof(el) == Expr && proc_expr(el)
if typeof(el) == Symbol
mm = match(charsre, String(el))
if mm != nothing
a1 = Symbol(String(el)[1:(mm.offset-1)])
a2 = charsdict[Symbol(mm.match)]
e.args[i] = :($a1^$a2)
end
end
end
end
macro hoo(expr)
typeof(expr) != Expr && return expr
proc_expr(expr)
expr
end
Of course it would be quite easy to expand this concept into "pure-math" library for Julia.
I don't think that there is any reasonable way of doing this.
When parsing your input, Julia makes no real difference between the unicode character ² and any other characters you might use in a variable name. Attempting to make this into an operator would be similar to trying to make the suffix square into an operator
julia> asquare == a^2
The a and the ² are not parsed as two separate things, just like the a and the square in asquare would not be.
a^2, on the other hand, is parsed as three separate things. This is because ^ is not a valid character for a variable name and it is therefore parsed as an operator instead.

Evaluate expression with local variables

I'm writing a genetic program in order to test the fitness of randomly generated expressions. Shown here is the function to generate the expression as well a the main function. DIV and GT are defined elsewhere in the code:
function create_single_full_tree(depth, fs, ts)
"""
Creates a single AST with full depth
Inputs
depth Current depth of tree. Initially called from main() with max depth
fs Function Set - Array of allowed functions
ts Terminal Set - Array of allowed terminal values
Output
Full AST of typeof()==Expr
"""
# If we are at the bottom
if depth == 1
# End of tree, return function with two terminal nodes
return Expr(:call, fs[rand(1:length(fs))], ts[rand(1:length(ts))], ts[rand(1:length(ts))])
else
# Not end of expression, recurively go back through and create functions for each new node
return Expr(:call, fs[rand(1:length(fs))], create_single_full_tree(depth-1, fs, ts), create_single_full_tree(depth-1, fs, ts))
end
end
function main()
"""
Main function
"""
# Define functional and terminal sets
fs = [:+, :-, :DIV, :GT]
ts = [:x, :v, -1]
# Create the tree
ast = create_single_full_tree(4, fs, ts)
#println(typeof(ast))
#println(ast)
#println(dump(ast))
x = 1
v = 1
eval(ast) # Error out unless x and v are globals
end
main()
I am generating a random expression based on certain allowed functions and variables. As seen in the code, the expression can only have symbols x and v, as well as the value -1. I will need to test the expression with a variety of x and v values; here I am just using x=1 and v=1 to test the code.
The expression is being returned correctly, however, eval() can only be used with global variables, so it will error out when run unless I declare x and v to be global (ERROR: LoadError: UndefVarError: x not defined). I would like to avoid globals if possible. Is there a better way to generate and evaluate these generated expressions with locally defined variables?
Here is an example for generating an (anonymous) function. The result of eval can be called as a function and your variable can be passed as parameters:
myfun = eval(Expr(:->,:x, Expr(:block, Expr(:call,:*,3,:x) )))
myfun(14)
# returns 42
The dump function is very useful to inspect the expression that the parsers has created. For two input arguments you would use a tuple for example as args[1]:
julia> dump(parse("(x,y) -> 3x + y"))
Expr
head: Symbol ->
args: Array{Any}((2,))
1: Expr
head: Symbol tuple
args: Array{Any}((2,))
1: Symbol x
2: Symbol y
typ: Any
2: Expr
[...]
Does this help?
In the Metaprogramming part of the Julia documentation, there is a sentence under the eval() and effects section which says
Every module has its own eval() function that evaluates expressions in its global scope.
Similarly, the REPL help ?eval will give you, on Julia 0.6.2, the following help:
Evaluate an expression in the given module and return the result. Every Module (except those defined with baremodule) has its own 1-argument definition of eval, which evaluates expressions in that module.
I assume, you are working in the Main module in your example. That's why you need to have the globals defined there. For your problem, you can use macros and interpolate the values of x and y directly inside the macro.
A minimal working example would be:
macro eval_line(a, b, x)
isa(a, Real) || (warn("$a is not a real number."); return :(throw(DomainError())))
isa(b, Real) || (warn("$b is not a real number."); return :(throw(DomainError())))
return :($a * $x + $b) # interpolate the variables
end
Here, #eval_line macro does the following:
Main> #macroexpand #eval_line(5, 6, 2)
:(5 * 2 + 6)
As you can see, the values of macro's arguments are interpolated inside the macro and the expression is given to the user accordingly. When the user does not behave,
Main> #macroexpand #eval_line([1,2,3], 7, 8)
WARNING: [1, 2, 3] is not a real number.
:((Main.throw)((Main.DomainError)()))
a user-friendly warning message is provided to the user at parse-time, and a DomainError is thrown at run-time.
Of course, you can do these things within your functions, again by interpolating the variables --- you do not need to use macros. However, what you would like to achieve in the end is to combine eval with the output of a function that returns Expr. This is what the macro functionality is for. Finally, you would simply call your macros with an # sign preceding the macro name:
Main> #eval_line(5, 6, 2)
16
Main> #eval_line([1,2,3], 7, 8)
WARNING: [1, 2, 3] is not a real number.
ERROR: DomainError:
Stacktrace:
[1] eval(::Module, ::Any) at ./boot.jl:235
EDIT 1. You can take this one step further, and create functions accordingly:
macro define_lines(linedefs)
for (name, a, b) in eval(linedefs)
ex = quote
function $(Symbol(name))(x) # interpolate name
return $a * x + $b # interpolate a and b here
end
end
eval(ex) # evaluate the function definition expression in the module
end
end
Then, you can call this macro to create different line definitions in the form of functions to be called later on:
#define_lines([
("identity_line", 1, 0);
("null_line", 0, 0);
("unit_shift", 0, 1)
])
identity_line(5) # returns 5
null_line(5) # returns 0
unit_shift(5) # returns 1
EDIT 2. You can, I guess, achieve what you would like to achieve by using a macro similar to that below:
macro random_oper(depth, fs, ts)
operations = eval(fs)
oper = operations[rand(1:length(operations))]
terminals = eval(ts)
ts = terminals[rand(1:length(terminals), 2)]
ex = :($oper($ts...))
for d in 2:depth
oper = operations[rand(1:length(operations))]
t = terminals[rand(1:length(terminals))]
ex = :($oper($ex, $t))
end
return ex
end
which will give the following, for instance:
Main> #macroexpand #random_oper(1, [+, -, /], [1,2,3])
:((-)([3, 3]...))
Main> #macroexpand #random_oper(2, [+, -, /], [1,2,3])
:((+)((-)([2, 3]...), 3))
Thanks Arda for the thorough response! This helped, but part of me thinks there may be a better way to do this as it seems too roundabout. Since I am writing a genetic program, I will need to create 500 of these ASTs, all with random functions and terminals from a set of allowed functions and terminals (fs and ts in the code). I will also need to test each function with 20 different values of x and v.
In order to accomplish this with the information you have given, I have come up with the following macro:
macro create_function(defs)
for name in eval(defs)
ex = quote
function $(Symbol(name))(x,v)
fs = [:+, :-, :DIV, :GT]
ts = [x,v,-1]
return create_single_full_tree(4, fs, ts)
end
end
eval(ex)
end
end
I can then supply a list of 500 random function names in my main() function, such as ["func1, func2, func3,.....". Which I can eval with any x and v values in my main function. This has solved my issue, however, this seems to be a very roundabout way of doing this, and may make it difficult to evolve each AST with each iteration.

Transposition Cipher returning wrong results

This is the source code I got from https://inventwithpython.com/hacking
import math, pyperclip
def main():
myMessage = 'Cenoonommstmme oo snnio. s s c'
myKey = 8
plaintext = decryptMessage(myKey, myMessage)
print(plaintext + '|')
pyperclip.copy(plaintext)
def decryptMessage(key, message):
numOfColumns = math.ceil(len(message) / key)
numOfRows = key
numOfShadedBoxes = (numOfColumns * numOfRows) - len(message)
plaintext = [''] * int(numOfColumns)
col = 0
row = 0
for symbol in message:
plaintext[col] += symbol
col += 1
if (col == numOfColumns) or (col == numOfColumns - 1 and row >= numOfRows - numOfShadedBoxes):
col = 0
row += 1
return ''.join(plaintext)
if __name__ == '__main__':
main()
What this Should be returning is
Common sence is not so common.|
What im getting back is
Coosmosi seomteonos nnmm n. c|
I cant figure out where the code is failing to send back the phrase
The code is OK. The problem is that you're using the wrong version of Python. As the 'Installation' chapter of that website says:
Important Note! Be sure to install Python 3, and not Python 2. The
programs in this book use Python 3, and you’ll get errors if you try
to run them with Python 2. It is so important, I am adding a cartoon
penguin telling you to install Python 3 so that you do not miss this
message:
You are using Python 2 to run the program.
The result is incorrect because the program depends on a feature that behaves differently in Python 2 than in Python 3. Specifically, dividing two integers in Python 3 produces a floating-point result but in Python 2 it produces a rounded-down integer result. So this expression:
(len(message) / key)
produces 3.75 in Python 3 but produces 3 in Python 2, and therefore this expression:
math.ceil(len(message) / key)
produces 4 (3.75 rounded up is 4) in Python 3 but produces 3 (3 rounded up is 3) in Python 2. This means that your numOfColumns is incorrect and therefore the decryption procedure produces an incorrect result.
You can fix this specific issue by changing (len(message) / key) to (float(len(message)) / key) to force Python 2 to treat that calculation as a floating-point division that will give the desired 3.75 result. But the real solution is to switch to using Python 3, because these differences in behaviour between Python 3 and Python 2 are just going to keep causing trouble as you proceed through the rest of the book.

Resources