matrix couple input from a user - python

"so i just started to learn python, now am against a real problem abt matrix i want to create a matrix by using an input from the user something like that : [[x,y],[x,y],[x,y],[x,y]],the first obvious solution is that to insert an array with 1D to a matrix on axis=0 but something went wrong with the dimensions on the console and also idk which function i use (like i said am new so looping through functions without knowing one of them really frustrated me)
so if anyone know how to do, and a speciallly the rules to append and insert to an array or a matrix without geeting some dimensional error would be very helpfull and thnx for ur time "

You could use a while loop that asks for user input until enough inputs have been passed through.
x = input('Enter x and y values (Ex. x,y): ')
lis, val = [], []
while 'n' not in x:
val = x.split(',')
lis.append(val)
x = input('Enter x and y values (Ex. x,y): ') # stop loop by typing n
print(lis)
To end the loop just type 'n'.

Related

Storing data with Python arrays (HAR-RV Credit Risk model implementation)

that's my first time here at Stack and I'm on my first days with Python.
I'm dealing with the HAR-RV model, trying to run this equation but having no success at all to store my operations on the array
Here what I'm trying to calculate:
r_[t,i] = Y_[t,i] - Y_[t,i-1]
https://cdn1.imggmi.com/uploads/2019/8/30/299a4ab026de7db33c4222b30f3ed70a-full.png
Im using the first relation here, where "r" means return and "Y" the stock prices
t = 10 # daily intervals
i = 30 # number of days
s = 1
# (Here I've just created some fake numbers, intending to simulate some stock prices)
Y = abs(np.random.random((10,30)) + 1)
# initializing my return array
return = np.array([])
# (I also tried to initialize it as a Matrix before..) :
return = np.zeros((10,30))
# here is my for loop to store each daily return at its position on the "return" Array. I wanted an Array but got just "() size"
for t in range(0,9):
for i in range(1,29):
return = np.array( Y.item((t,i)) - Y.item((t,i-1)) )
... so, I was expecting something like this:
return = [first difference, second difference, third difference...]
how can I do that ?
first don't use return as a variable name in python as it is a python keyword (it signifies the result of a function). I have changed your variable return to ret_val.
You are wanting to make a change at each position in your array, so make the following change to your for loop:
for t in range(0,10):
for i in range(1,30):
ret_val[t][i] = Y[t][i] - Y[t][i-1]
print(ret_val)
This is saying to change the value at index ret_val[t][i] with the result of subtracting the values at that specific index in Y. You should see an array of the same shape when you print.
Also, the range function in python does not include the upper number. So when you say, for i in range(0,9) you are saying to include numbers 0-8. For your array, you'll want to do for i in range(0,10) to include all values in your array. Correspondingly, you'll want to do the same for i in range(1,30).

Shannon Diversity Program: basic questions

I am a biology student trying to get into programming and have some issue with a basic index calculator I am trying to write for a research project. I need a program that will prompt the user to input data points one at a time, perform the proper calculation (-1*(x*ln(x))) on each data point, and enter that new calculated value into an array. Once the user inputs 'done', I would like the program to sum the array values and return that index value.
This is what I have. I am very new so apologies for any blaring mistakes. Any points in the right direction are very appreciated.
import math
print('This program calculates a Shannon Diversity '
'Index value for a set of data points entered by the user.'
' when prompted enter a species number value,then press enter. '
'COntinue until all data points have been entered. '
'Upon completion, enter the word done.')
def Shannonindex():
index = []
entries = 1,000,000
endKey = 'done'
for i in range(entries):
index = [input("Enter a value: ")]
if index != endKey:
entry = p
p = -1*(x*ln(x))
index.append(p)
else Sindex = sum(index)
return Sindex
print('Your Shannon Diversity Value is: ", Sindex)
There are a huge number of problms here.
You need to get your variables straight.
You're trying to use index to mean both the list of values, and the input string. It can't mean both things at once.
You're trying to use x without defining it anywhere. Presumably it's supposed to be the float value of the input string? If so, you have to say that.
You're trying to use p to define entry before p even exists. But it's not clear what entry is even useful for, since you never use it.
You also need to get your control flow straight.
What code is supposed to run in that else case? Either it has to include the return, or you need some other way to break out of the loop.
You also need to get your types straight. [input(…)] is going to give you a list with one element, the input string. It's hard to imagine what that would be useful for. You can't compare that list to 'done', or convert it to a float. What you want is just the input string itself.
You can't just guess at what functions might exist. There's no function named ln. Look at the docs for Built-in Functions, the math module, and anything else that looks like it might be relevant to find the function you need.
1,000,000 is not a number, but a tuple of three numbers.
You can write 1_000_000, or just 1000000.
But it's not clear why you need a limit in the first place. Why not just loop forever until the enter done?
You've defined a function, but you never call it, so it doesn't do any good.
So, let's sort out these problems:
import math
def Shannonindex():
index = []
endKey = 'done'
while True:
value = input("Enter a value: ")
if value != endKey:
x = float(value)
p = -1 * (x * math.log(x))
index.append(p)
else:
Sindex = sum(index)
return Sindex
Sindex = Shannonindex()
print('Your Shannon Diversity Value is: ", Sindex)
There are still many ways you could improve this:
Add some error handling, so if the user typos 13.2.4 or 1O, it tells them to try again instead of bailing out on the whole thing.
You don't actually need to build a list, just keep a running total.
If you reverse the sense of the if/else it will probably be more readable.
You're not actually calculating the Shannon diversity index. That's not the sum of -x ln x, it's the sum of -p ln p where each p is the proportion of x / sum(all x). To handle that, you need to keep all the raw x values in a list, so you can convert that to a list of p values, so you can sum those.
import math
index = []
for i in range(1,100000):
val = input("Enter a value: ")
if val =='done':
break
else:
x = int(val)
p = -1*(x*math.log(x))
index.append(p)
print ("The value of index is %s:"%index)
=================================================
This is the simplified form of your code, since you are new to python.
This might help you get the values stored in a list and calculate it until you type done.

How to add or subtract as many matrices as you wish in python

I have been searching all over the internet and I can't seem to find how to answer my homework question. The user should enter matrices and indicate whether the matrices are to be added or subtracted. You should be able to add or subtract as many matrices as you wish without having to re-enter the previous solution. I am a beginner with python and am not sure how to go about this. All I have so far is
#Ask the user to input a matrix
print ('Enter your row one by one (pressing enter between each row).
To terminate, enter an empty row.')
M = []
#Allow them to determine dimensions
while True:
r = input ('Next row > ')
if not r.strip (): # Empty input
break
M.append(list(map(int, r.split())))
#Display the matrix
print('M =', M)

solve equations using multiple values of x

I need help on the fallowing: Lets say you ask the user for an ecuation it can be anything, for illustrating this example lets the the user choose this one:
x**5+3, and he also needs to assign any value of x, so it will look like this:
write the equation:
write the value of x you want to calculate:
my question is: how can you modify the x in the equation the user gave first to assign the value he wants to calculate?? in other worlds how can I make python calculate x**5+2, for x= any input value??
It looks like you want the user to enter an equation with variables and the value for the variable. And you want your code to evaluate the user input equation with user input value for the variable in the equation. Sounds like a candidate for eval():
In [185]: equation = 'x ** 5 + 2'
In [186]: x = 3
In [187]: eval(equation)
Out[187]: 245
Another example:
In [188]: equation = '(x + 99) * 2'
In [189]: x = 1
In [190]: eval(equation)
Out[190]: 200
Since in the above demonstration, equation is a string, it might as well be a user input. When you ask the user to input for the equation, store it in a variable (variable equation here). Then when you ask them for a value for the variables in the equation, cast it to int and just do a eval(equation) in your code.
Your question is hard to decipher, but if I understand correctly, you're talking about writing a function. Try the following:
def f(x):
return x**5 + 2
And you may use the function for any value of x, e.g., f(2).
This is relativity easily to do if you look up each piece of the puzzle (or coding problem in this case).
First you need user input:
x_string = input("Enter an x value: ")
Then you need to convert the input String into an integer:
x = int(x_string)
Finally you need to calculate the value and print it out:
results = x**5 + 2
print results
You seem to be new to Python, so I highly recommend looking up some tutorials (like this one).

Python - Table of Values Equation

I'm trying to make a program where you input the Slope, Y-Intercept, the minimum X and maximum X and then it will put a table of values that prints the "y" of each "x" essentially. I know I would have to use a for loop that uses the range function to take the range of the numbers they input so it will display that many items but I'm not sure what to do to make this work.
choice4=input("Slope (x): ")
choice5=input("Y-Intercept: ")
choice6=input("Minimum (x): ")
choice7=input("Maximum (x): ")
print("")
for items in range(int(choice6),int(choice7)):
print ((int(choice4) * x) + int(choice5))
You are almost there. The immediate issue is that you've called your loop variable items but then refer to it as x.
On a related note, you definitely want to give clearer names to your variables.
There are several smaller issues:
range() will exclude the final value, so you may need to account for that.
Instead of doing the same string-to-int conversions over and over again, you might want to do them just once.

Categories

Resources