Automatically give lambda arguments - python-3.x

Say I don't know in advance how many arguments my lambda function will take. Let's say I code something which asks the user how many arguments I want:
num = input('How many args? ')
num = float(num)
Say, the user inputs 4. How would I then do something like this in a function?
func=lambda x,y,z,t : eval(string)
Automatically -- I must stress. I need to have Python give 4 dummy variables in this case to the lambda function (I happened to denote it x,y,z,t as the dummies) just because I've specified num = 4. The user will specify the function of x,y,z,t with a string such as "x+y+z+t". Is this possible?

Here's a working version, I didn't use a function at all, I just used exec to dynamically define variable names so the eval will work then:
var_names = ["x", "y", "z", "t"]
arg_num = int(input('How many args? '))
for i in range(arg_num):
exec(var_names[i] + "=" + input(var_names[i] + "= "))
print(eval(input("provide func ")))

Related

How to concatenate a string using a for loop n times?

I have a variable = "v". I would like to concatenate to this variable as many v as input by the user. So, if the user enters 10, the output would be vvvvvvvvv. Although I have it working as defined, I'm not sure if this is the right approach because I have to use a for loop to concatenate as many v as required to the original variable created in step 1 and then print the variable from step 1.
This is what I have so far:
Create a variable equal to the string "v";
Ask how many ‘waves’ the user would like printed;
Using a for loop, concatenate as many v as necessary to the variable created in step 1;
After the loop has been completed, print the variable from step 1.
variable = "v"
waves = int(input("How many waves would you like to print?: "))
for i in range(waves):
print(variable, end="")
yes i think your answer is correct. also you can use like this
variable = "v"
waves = int(input("How many waves would you like to print?: "))
print(variable*waves)
try this
You could use a for loop to accumulate more of the variable
variable = "v"
waves = int(input("How many waves would you like to print?: "))
for i in range(waves-1):
variable+="v"
print(variable)
Or you could more directly increase the variable to the appropriate length without looping.
variable = "v"
waves = int(input("How many waves would you like to print?: "))
variable*=waves
print(variable)

How do I achieve this following function only using while loop?

I'm currently working on this problem that ask me to generate an arrow pattern using loops function that looks something like this:
"How many columns? 3"
*
*
*
*
*
I know I can do this with for loop(probably more efficient too), but that is not what I aimed for. I wanted to achieve this only using while loop.
I have some ideas:
1. I set up a control variable and an accumulator to control the loop
2. I then write 2 separate loops to generate the upper and lower part of the pattern. I was thinking about inserting the space before the asterisks using method like this:
(accumulator - (accumulator - integer)) * spaces.
#Ask the user how many column and direction of column
#they want to generate
Keep_going = True
Go = 0
while keep_going:
Column_num = int(input("How many columns? "))
if Column_num <= 0:
print("Invalid entry, try again!")
else:
print()
Go = 1
#Upper part
while Keep_going == True and Go == 1:
print("*")
print(""*(Column_num - (Column_num - 1) + "*")
...but I soon realized it wouldn't work because I don't know the user input and thus cannot manually calculate how many spaces to insert before asterisks. Now everything on the internet tells me to use for loop and range function, I could do that, but I think that is not helpful for me to learn python since I couldn't utilize loops very well yet and brute force it with some other method just not going to improve my skills.
I assume this is achievable only using while loop.
#Take your input in MyNumber
MyNumber = 5
i = 1
MyText = '\t*'
while i <=MyNumber:
print(MyText.expandtabs(i-1))
i = i+1
i = i-1
while i >=1:
print(MyText.expandtabs(i-1))
i = i-1
Python - While Loop
Well first you have to understand that a while loop loops until a requirement is met.
And looking at your situation, to determine the number of spaces before the * you should have an ongoing counter, a variable that counts how many spaces are needed before you continue. For example:
###Getting the number of columns###
while True:
number=int(input('Enter number of rows: '))
if number<=0:
print('Invalid')
else:
###Ending the loop###
break
#This will determine the number of spaces before a '*'
counter=0
#Loops until counter equals number
while counter!=number:
print(" "*counter + "*")
#Each time it loops the counter variable increases by 1
counter=counter+1
counter=counter-1
#Getting the second half of the arrow done
while counter!=0:
counter=counter-1
print(" "*counter + "*")
Please reply if this did not help you so that i can give a more detailed response

Beginner python - simple Pounds to Kilos

The instructions are very simple, but I am struggling none the less. We have learned very few things in this class so far, so I am looking for a very simplistic answer.
The instructions are as follows "Write a Python program that will prompt the user to enter a weight in pounds, then
convert it to kilograms and output the result. Note, one pound is .454 kilograms"
What i have so far is
print("Pounds to Kilos. Please Enter value in pounds.")
x=input('Pounds: ')
float(x)
print(x * .454)
You are converting the variable x's value to the float, but not assigning it to anything. So, the real value which x variable holds never changed. You did not edit the x variable in fact. You can try something like this;
print("Pounds to Kilos. Please Enter value in pounds.")
x=float(input('Pounds: '))
print(x * .454)
However, using functions in that nested manner is not recommended. Instead, initialize a new variable to hold the new float-converted value;
print("Pounds to Kilos. Please Enter value in pounds.")
x = input('Pounds: ')
x_float = float(x)
print(x_float * .454)
Going from your code example I would do something like this.
print("Pounds to Kilos. Please Enter value in pounds.")
x = float(input('Pounds: '))
print(x * 0.454, "kg")
EDIT
Maybe instead of having the calculation in the print() statement I add a separate variable for it, including the advise about float from the other solution.
print("Pounds to Kilos. Please Enter value in pounds.")
x = (input('Pounds: '))
kg = float(x) * 0.454
print(kg, "kg")
Explanation: First you ask the user's weight using input command, then you can print a message saying converting to kgs.. (it's optional). create a new variable called weight_kgs to convert the user's input to a float, then multiply the input by 0.45. after that convert the weight_kgs variable to a string once again by making a new variable called final_weight, so that you can join the input by user to a string. At the end print a message telling the user's weight. print("you weight is " + final_weight)
```
weight_lbs = input("enter your weight(lbs): ")
print("converting to kgs...")
weight_kgs = float(weight_lbs) * 0.45
final_weight = str(weight_kgs)
print("your weight is " + final_weight + "kgs") # line 5
```
I hope you got it.

Taking input as much as the given number in python 3

I have been trying/looking for this problem and decided to ask.
I want a simple program that gets an integer as input first of all.
a = int(input())
Then, the program will take input as much as the given number, a.
You may want to use a for loop to repeatedly get input from the user like so:
a = int(input("How many numbers do you want to enter? "))
numbers = list() #Store all the numbers (just in case you want to use them later)
for i in range(a):
temp_num = int(input("Enter number " + str(i) + ": "))
numbers.append(temp_num)

Strrep not working in Matlab to make String into function

Hello I am new to MATLAB , I wanted to know how can I make my string into function . I want to access the function as a string from user in standard Matlab format (e.g exp(-10*X)-sin(pi*X)-2*tanh(X) ) Here X is the variable. Then I want to replace 'X' with 'low' and 'high' variables to calculate value of function at these limits. I have used 'strrep' for this purpose. I am getting the following errors
1)Undefined function or variable 'X'.
2) I cannot see whether 'X' was replaced with 'low' and 'high'.
Any help will be truly appreciated.
Below is my code.
high=input('Upper Limit of the Interval : ');
low=input('\nLower Limit of the interval : ');
usr_funct=input('Enter The Function in standard Matlab Format.\nEnter "X" for the
variable and * for multiply \n'); % Example exp(-10*X)-sin(pi*X)-2*tanh(X);
middle = (low+high)/2;
Flow =strrep(usr_funct, 'X', 'low');
Fhigh =strrep(usr_funct, 'X', 'high');
sprintf('Flow '); % This was to check if 'X' was replaced with 'low'. It is not printing anything
Use:
usr_funct=input('Enter The Function...', 's');
This will return the entered text as a MATLAB string, without evaluating expressions.
I think that you are looking for the eval function. That will evaluate a string as matlab code.
Here is an example:
str = 'exp(-10*X)-sin(pi*X)-2*tanh(X)' ; % let str be your math expression
high = 10; % Ask the user
low = -5; % Ask the user
% Now we evaluate for High and Low
X = low; % We want to evaluate for low
ResultLow = eval(str); % That will return your value for X = low
X = high; % We want to evaluate for low
ResultHigh = eval(str); % That will return your value for X = high
1) Undefined function or variable 'X'
If you look at the documentation for input, it says that by default, it evaluates the expression. You need to add a second argument of 's' for it to just save a string.
2) I cannot see whether 'X' was replace with 'low' and 'high'
You should type sprintf(Flow) instead of sprintf('Flow'). The latter will just output "Flow" onto the screen while the former will output the value of Flow.
Finally, the eval function may be of use later on when you actually want to evaluate your expression.

Resources