python


Lambda function asks for input twice,


I am working on a rather complicated math project using python but keep getting stuck with one problem:
a = lambda x: input('Function in terms of x')
This works until I have to run a command like:
z = a(n)
Every time this is done it asks for an input again so I get a console that looks like:
Function in terms of x:
Function in terms of x:
I know that I should theoretically be able to get around with the following:
func = input('Function: ')
a = lambda x: func
This creates another problem: x isn't defined in the outer scope, so I added sympy symbols like so:
x = sym.Symbol('x')
func = input('Function: ')
a = lambda x: func
but then running a command like this results in something weird:
Function: 5*x +1
>>>a(10)
5*x + 1
I think this is because lambda doesn't work with sympy, but I can't think of another way to get around the problem... Thank You for any help.
The full code is as follows; the function asks for the first input at line 18, and then at line 50 where it isn't supposed too. I believe that this has to do with the fact that I use the lambda function twice.
import matplotlib.pyplot as plt
import os
import time
from mpl_toolkits.mplot3d import axes3d
from sympy import *
import numpy as np
import tkinter as tk
from colorama import init, Fore, Back, Style
import mpmath
def main():
"""
Handling for Range and function
"""
rng = raw_input('Minimum, Maximum: ').split(',')
rng = [float(rng[i]) for i in range(2)]
a = lambda x: input('Function of x: ') # function a is the main polynomial#
"""
2 Dimensional Graph
"""
two_d_x = np.arange(rng[0], rng[1], abs(rng[1] - rng[0]) / 100)
two_d_y = a(two_d_x)
fig1 = plt.figure()
ax1 = fig1.add_subplot(221)
print [np.amin(two_d_x), np.amax(two_d_x), np.amin(two_d_y), np.amax(two_d_y)]
ax1.axis([np.amin(two_d_x), np.amax(two_d_x), np.amin(two_d_y), np.amax(two_d_y)])
ax1.plot(two_d_x, two_d_y, 'r-')
ax1.set_title(r'$\mathit{f(x)}\in \mathbb{R}^2$')
ax1.set_xlabel(r'$\mathit{x}$')
ax1.set_ylabel(r'$\mathit{y}$')
ax1.grid()
ax1.spines['left'].set_position('zero')
ax1.spines['right'].set_color('none')
ax1.spines['bottom'].set_position('zero')
ax1.spines['top'].set_color('none')
ax1.spines['left'].set_smart_bounds(True)
ax1.spines['bottom'].set_smart_bounds(True)
plt.gca().set_aspect('equal', adjustable='box')
ax1.xaxis.set_ticks_position('bottom')
ax1.yaxis.set_ticks_position('left')
"""
Quiver Plot of Function
"""
ax2 = fig1.add_subplot(222)
u, v = np.meshgrid(np.arange(rng[0], rng[1], 1),
np.arange(rng[0], rng[1], 1))
### u+vj -> w+rjf
print False
output = a(u + (v * 1j))
print False
w = output.real
r = output.imag
ax2.axis([np.amin(w) * 1.1, np.amax(w) * 1.1, np.amin(r) * 1.1, np.amax(r) * 1.1])
distance = np.sqrt(((w - u) ** 2) + ((r - v) ** 2))
quiver_plot = ax2.quiver(u, v, w, r, distance, angles='xy', scale_units='xy', scale=1, cmap=plt.cm.jet)
plt.colorbar(quiver_plot, cmap=plt.cm.jet)
ax2.set_title(r'$\mathit{f(x)}\in \mathbb{C}^2$')
ax2.set_xlabel(r'$\mathit{rl}$')
ax2.set_ylabel(r'$\mathit{im}$')
ax2.grid()
ax2.spines['left'].set_position('zero')
ax2.spines['right'].set_color('none')
ax2.spines['bottom'].set_position('zero')
ax2.spines['top'].set_color('none')
ax2.spines['left'].set_smart_bounds(True)
ax2.spines['bottom'].set_smart_bounds(True)
plt.gca().set_aspect('equal', adjustable='box')
ax2.xaxis.set_ticks_position('bottom')
ax2.yaxis.set_ticks_position('left')
plt.show()
main_program_loop = True
while main_program_loop == True:
print '| Quandri 1.0 | by: Boolean Designs\n'
main()
stay_loop_tp = True
while stay_loop_tp != False:
stay_loop_tp = raw_input("Would you like to continue using this program <yes/no>? ")
if stay_loop_tp == 'yes' or stay_loop_tp == 'y':
os.system('cls')
stay_loop_tp = False
elif stay_loop_tp == 'no' or stay_loop_tp == 'n':
print 'Exiting Quandri...'
time.sleep(1)
exit()
stay_loop_tp = False
else:
print "Improper Input."
time.sleep(2)
os.system('cls')
The sympy lib has support for parsing and evaluating expression:
import sympy
from sympy.parsing.sympy_parser import parse_expr
x = sympy.Symbol('x')
expression_string = input("Function: ")
expr = parse_expr(expression_string)
expr.evalf(subs={x:10})
see this http://docs.sympy.org/dev/modules/parsing.html
and this How to calculate expression using sympy in python
Edit: Thomas Kühn's answer is good, but in python2.7 raw_input must be used
f = raw_input("Function: ")
a = lambda x:eval(f)
print(a(10))
I don't know, if it is advisable to do something like this, but here is some code that works for me on python 3.5:
func = input('Function: ')
a = lambda x: eval(func)
print(a(10))
calling this script with python, I get:
Function: x+1
11

Related Links

How to plot arbitrarily many subplots in matplotlib?
i want your help abut program to run automatically every 12 hours
How to create a form for website, without requiring a data-model - Odoo v9 community
Qt setStyleSheet which kind of fonts can I use?
Python matching items accross dataframes
How to add colours to my python code
Flask - Getting a 304 status for my external .css file
User Domains for Office Online
Python - Django - Sum values of a list, too slow
Selenium - Select fields won't save via Remote Webdrive
Find blocks (and their sizes) of same consecutive elements in Pandas
With python dataframes add column of counts of rows that meet condition to each row that meets it
Pandas pivot_table with aggfunc works differently on little different data
`ndimage.distance_transform_bf` transforms the wrong elements?
Generate random words with different lengths
Error in alpha beta prunning algorithm in python

Categories

HOME
sql-server
signalr
system-verilog
jasmine
fparsec
windows-store-apps
jscript
sbt-assembly
ext.net
sequelize.js
urlencode
spring-cloud-contract
jboss7.x
flann
mongodb-query
sign
python-unicode
alfresco-share
jcl
ng2-dragula
spring-test
badge
auditing
onesignal
rhmap
xilinx-ise
helper
pygooglechart
red-black-tree
google-drive-realtime-api
reactivemongo
office365connectors
zero
readfile
initializer
jquery-multidatespicker
infusionsoft
android-preferences
cgo
rkt
proof
slidesjs
mbaas
nuget-server
butterknife
paas
manifest.mf
firepath
windows-nt
asynccallback
difference
function-fitting
file-diffs
eyeql
castle-windsor-3
ytplayerview
digits
git-checkout
code-first-migrations
magento-1.12
android-search
proximity
scala-2.11
google-admin-audit-api
code-testing
spdy
coin-flipping
picat
data-generation
anjuta
xenocode
arangodb-php
leptonica
execvp
vmware-server
cgimageref
dynamics-ax-2009
resgen
pep8
graph-coloring
process-monitor
transitive-closure-table
marmalade-edk
cbcentralmanager
radchart
redirectstandardoutput
selectonemenu
mysql-error-1045
ajax.beginform
scraperwiki
easygui
posting
junit3
.app
hadoop-plugins
boost-date-time
grooveshark
pci-bus
microsoft.ink
longjmp

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App