I have the following functions to calculate two different things:
def LCM(X0, a, c, m, n): #Generates "n" numbers of random numbers# with given parameters.
X = []
X.append(X0)
for i in range(n):
X.append(float((a*X[i]+c) % m))
X[i] = X[i]/m
del X[0]
X[n-1] = X[n-1]/m
plt.hist(X)
plt.title("LCM Frequency Histogram")
plt.show()
print "For this example, the LCM generated a good quality uniform distribution."
print "However, it should be also noted that every 2000 generations,"
print "the numbers are repeated."
return X[:10] #Show only the first 10 values of the list.
def exponential(lambdavalue):
Z =[]
for i in range(10000):
Z.append(float(-(1/lambdavalue)*math.log(1-X[i])))
plt.hist(Z)
plt.title("Exponential Frequency Histogram")
plt.show()
return Z[:10] #Show only the first 10 values of the list.
In the first function, I calculate the variable X and in the second I find Z based on X and plot its histogram. I am not able to understand how I can pass the variable X to the second function. I am running following for the first function:
LCM(27, 17, 9, 10000, 10000)
and this for the second:
exponential(10)
I am also aware I can use some packages to make these things (LCM random generation and exp distr), however, I wanted to make something to practice.
Since you are returning the X values from the first function you could pass them to the second function as follows:
X = LCM(27, 17, 9, 10000, 10000)
Z = exponential(X, 10)
You just need to add an argument to exponential for the X values.
You need to pass the value returned from the LCM function into a variable so you do-
x = lcm(27, 17, 9, 10000, 10000)
And then you pass the value of x as an argument into the exponential function as -
x = exponential(10)
Another way is you can declare a global variable X=[ ] outside both your function and you can use them in both of your functions. Without passing it as an argument in the second.
You can use a global variable in other functions by declaring it as global in each function that assigns to it:
x = 0
def f():
x = 1
f()
print x #=>0
and expect 1. Instead, you need do declare that you intend to use the global x:
x = 0
def f():
global x
x = 1
f()
print x #=>1
I hope it will help you. Or at least get you closer to solution.
Related
Edit: Sorry guys, I meant to use the power function, not squaring, i hope this clears it up
I'm a new to python, and I'm trying to create a function that lets the user input x and y and will give the output of the powers of those numbers in a loop, so create_list(2,8) returns the list [1,2,4,8,16,32,64,128,256].
I have this code so far, but I feel like it's way off as it only allows for 1 input, whereas I'm looking for 2
import math
a=int(input())
while a<=10000:
print (a)
a=a*2
An example output of this is if a=4, output:
4
8
16
32
64
128
256
512
1024
2048
4096
8192
The previous answers already explain how to solve your question, here I explain how to create a function. Notice that for simple operation like power, you don't need import math. With the following code you define a function create_list(x, y) that takes as input 2 numbers x and y and gives your output, regardless of how they are passed to the function:
def create_list(x, y):
my_list = []
for i in range(y+1):
my_list.append(x**i)
return my_list
After that, you can call the create_list function by giving the numbers programmatically (maybe they are the results of previous operations), but if you want to give them explicitly by keyboard, use this code:
x = int(input())
y = int(input())
my_list = create_list(x,y)
print(my_list)
First, use the input() function twice to let the user input two numbers.
Use the formula square = x * x (instead of x*2) to calculate the square.
Iterate over all numbers between a and b by using the range(a, b) function.
Collect all square numbers in a list and print the list afterwards.
a = int(input())
b = int(input())
squares = []
for i in range(a, b):
square = i * i
squares.append(square)
print(squares)
The more pythonic way in one line:
squares = [i*i for i in range (a,b)]
print(squares)
a=int(input())
b=int(input())
def create_list(a,b):
return [a**i for i in range(b+1)]
print(create_list(a,b))
output for create_list(2,8)
[1, 2, 4, 8, 16, 32, 64, 128, 256]
You can use python pow function
import math
def get_powers(power, length):
return [int(math.pow(power, x)) for x in range(1, length + 1)]
power_input = int(input('power:'))
length_input = int(input('length:'))
print(get_powers(power_input, length_input))
run
power:3
length:5
[3, 9, 27, 81, 243]
[ x * x for x in range (int(input("lower bound")), int(input("upper bound")))]
The above is a list comprehension. It takes every element in range and accesses it through the variable x. The expression on the left is what will actually end up in the list. For example, putting x + 1 would result in storing a value 1 greater than x being stored.
Inputs are evaluated from left to right so you can directly put them in as the parameters to the range function.
The evaluation order is:
Call 'lower bound' input
Convert to int
As above for right input
Evaluate range
Run list comprehension
Lets suppose you have f(x)=x^2 and you want a series from k=1 to n of f(k). How would you enter it in python and print the result?
I tried doing this for n=10
n=10
def f(x):
return x^2
sum = 0
for k in range(1, n):
Sum = sum + f(k)
I don't know how to print it let alone whether I did it correctly.
I know you can represent a sum of k^2 as n(n+1)(2n+1)/6 but I am just using x^2 as an example.
First off sum is a builtin function so you should not use it as a variable name as python will simply let you overwrite the variable in the spirit of "we are all consenting adults here". Example
type(sum)
# <type 'builtin_function_or_method'>
sum = 0
type(sum)
# <type 'int'>
Now to your question. One way is to first generate the sequence and use the aforementioned sum function as the following examples show.
Generate the sequence using a so-called list comprehension to evaluate the function for each element in a range:
n = 5
def f(x):
return x*x
print([ f(i) for i in range(n)])
# [0, 1, 4, 9, 16]
print(sum([ f(i) for i in range(n)]))
# 30
Use the builtin map function to apply a function, either defined using def or lambda, on a range:
n = 10
f = lambda x: x*x
print(map(f, range(n)))
# [0, 1, 4, 9, 16]
# one line equivalent : print(map(lambda x: x*x, range(n)))
print(sum(map(f, range(n))))
# 30
Alternatively, you can follow your train of thought and use a simple loop and a variable:
n = 5
f = lambda x: x*x
s = 0
for i in range(n):
s += f(i)
print(s)
# 30
Finally, if speed/efficiency is a factor that you have to account for you can have a look at the numpy library. See for instance one of my answers on applying a funcion over a range.
I'm curious what x means when you look at this:
import random
for x in range(10):
print random.randint(1,101)
x itself has no special meaning, it simply (as a part of the for loop) provides a way to repeat
print random.randint(1,101)
10 times, regardless of the variable name (i.e., x could be, say, n).
In each iteration the value of x keeps increasing, but we don't use it. On the other hand, e.g.,
for x in range(3):
print(x)
would give
0
1
2
For x in range(3) simply means,
for each value of x in range(3), range(3) = 0,1,2
As it is range(3), the loop is looped three times and at each time, value of x becomes 0, then 1 and then 2
Here, x is just a variable name used to store the integer value of the current position in the range of loop and it iterates through out the range of a loop.
Like in for x in range(10):
x iterates 10 times and for instance in your for loop above, during the first iteration of the loop x = 1, then x=2 for the next iteration then, x= 3 and so on...
It is not neccessary to take x as a variable only you can take any variable name like i,a etc...
X is a variable name, so could be any name allowed by python for variable names. As a variable , it’s value will be different every time the loop circle ends, in this particular loop range(10) the value of x will start in 0 and next 1 , and next 2, until reach value of 10
so If you want to print a random int:
for x in range(10):
print(random.randint(x))
also, if it is python3.X, print(x) not print x, second is python2.X
I am coming from a short intro in C, and I was confused by the 'x' as well. For those coming from C,C++,C# etc.:
The 'x in range(10)' is the same thing as doing this in C:
for (x = 0; x < 10; x++)
I am a beginner at Python and I'm trying to use a while loop to sum up all of the squared n values in a given n value range.
Code:
def problem2(n):
x = 0
y = 0
while x < n:
y = (n**2)+y
x+=1
return y
For some reason, this equation returns the input number cubed.
Can someone explain why this happens and how to fix it?
You need to perform the ** on x, the value that is being incremented:
def problem2(n):
x = 0
count = 0
while x < n:
count += pow(x, 2)
x += 1
return count
You keep squaring the same number n, instead of the one being incremented x.
def sum_of_squares(n):
sum = 0
for x in range(0, n):
sum += x*x
return sum
You also don't really need the while loop, avoiding having to manually keep track of which variable is the counting variable and which one is the result variable (which is what you are confusing, as explained e.g. by #Ajax1234 in their answer).
It is a lot more Pythonic to use the built-in function sum, a generator expression and range:
def problem2(n):
return sum(x**2 for x in range(n))
This would be a lot more readable and better (unless of course you are being forced to use while).
Looks good. You're almost there.
It makes it the cube root because you add y to (n**2) everytime. Because you code runs until x !< n it runs n times. That means that you add n**2 to n**2*n.
That means that it gives 1(n**2)*(n-1)(n**2) which equals n(n**2) = n**3
Hope this was clear enough.
I made a program which displays a user-provided number of the fibonacci series. I wanted to format it into an indexed list, but I don't what could I use to do so. I found the enumerate() function, but seems it only works for premade lists, whereas mine is generated accordingly to the user.
Do I use a for loop to generate a variable along with the series, then put the variable in the for loop that prints the numbers, like so:
print("{0}. {1}".format(index_variable, wee(n)))
or am I going an entirely wrong road here?
def fib(n):
x = 0
y = 1
for i in range(n):
yield y
tmp = x
x = y
y += tmp
def main():
n = input('How many do you want: ')
for i, f in enumerate(fib(n)):
print("{0}. {1}".format(i, f)
Make a generator that yields the values you want and then pass that to enumerate