I want to make this program do the summation of something with their input. My code thus far
def summation():
start = int(raw_input("Start value of n?: "))
end = int(raw_input("End value of n?: "))
eqn = lambda n: raw_input("Equation?: ")
sum = 0
for i in range(start , end + 1):
sum += eqn(i)
return sum
print summation() # start will be 1, end will be 5 , equation will be n + 1. Should print 20
I get the error that I can't add an integer and a string together so is there any way to make the raw_input for equation not a string. Like instead of it being 'n + 1', I want it to be n + 1.
You could use input instead of raw_input, but this isn't really a good idea, since every time eqn is called it will call a input and prompt you for the equation.
A better method is to store the equation beforehand (using raw_input), and then use eval in the lambda function. Something like:
def summation():
start = int(raw_input("Start value of n?: "))
end = int(raw_input("End value of n?: "))
fx = raw_input("Equation: ")
eqn = lambda n: eval(fx)
sum = 0
for i in range(start , end + 1):
sum += eqn(i)
return sum
print summation()
Don't you need to surround your raw_input in your eqn variable with an int()?
I use python 3, but that should fix your problems.
Related
The input format is:
6
1
2 5
2 7
2 9
1
1
Input:
First line contains an integer Q, the number of queries. Q lines follow.
A Type-1 ( Customer) Query, is indicated by a single integer 1 in the line.
A Type-2 ( Chef) Query, is indicated by two space separated integers 2 and C (cost of the package prepared) .
I want to read the input from stdin console and here is my code
n = int(input())
stack1 = []
for i in range(n):
x = input()
x = int(x)
if x == 2:
y = input()
stack1.append(y)
elif x == 1:
length = len(stack1)
if length > 0:
print(stack1.pop())
else:
print("No Food")
I have tried x,y = raw_input().split() this statement also fails because sometimes input has single value. Let us know how to read the defined input from stdin ???
Use len() to find length of string based on that change your stdin.
n = int(input())
for i in range(n):
s = input()
if(len(s) > 1):
x,y = s.split()
x = int(x)
else:
x = int(s)
print(x)
Cheers.
I have written a code to find approximated sum of an exponential function, which should run iteration till N-1 terms, then return the iteration no, sum, abs error and relative error for each iteration step.
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import math
N = input ("Please enter an integer at which term you want to turncate your summation")
x = input ("please enter a number for which you want to run the exponential summation e^{x}")
function= math.exp(x)
exp_sum = 0.0
abs_err = 0.0
rel_err = 0.0
for n in range (0, N):
factorial = math.factorial(n)
power = x**n
nth_term = power/factorial
exp_sum = exp_sum + nth_term
abs_err = abs(function - exp_sum)
rel_err = abs(abs_err)/abs(function)
print "The exponential function which has %d-term expansion, returns the approximated sum to be %.16f." % (n, exp_sum)
print "This approximated sum has an absolute error to be %.25f" % abs_err
print "and a relative error to be %.25f" % rel_err
right now, it actually looks silly printing values at each iteration and it only looks good till a few iteration, my plan is to get the output as a table with proper column headings (iteration, sum, abs err, rel err) in the terminal after I execute the .py file.
also I wish to save a .txt file of the output, if anyone has idea how to do that in python, I would very much appreciate the help and thanks.
You might use a pretty_table() function in order to pretty print tabular data, like this:
def pretty_table(rows, column_count, column_spacing=4):
aligned_columns = []
for column in range(column_count):
column_data = list(map(lambda row: row[column], rows))
aligned_columns.append((max(map(len, column_data)) + column_spacing, column_data))
for row in range(len(rows)):
aligned_row = map(lambda x: (x[0], x[1][row]), aligned_columns)
yield ''.join(map(lambda x: x[1] + ' ' * (x[0] - len(x[1])), aligned_row))
This little function, given a list of rows and the number of columns, will yield pretty-formatted table data, line by line. You can even adjust the spacing between columns if you wish.
In your particular code, you may do the following:
# At first, contains just the header columns.
rows = [['Term', 'Exponential sum', 'Absolute error', 'Relative error']]
for n in range (0, N):
factorial = math.factorial(n)
power = x**n
nth_term = power/factorial
exp_sum = exp_sum + nth_term
abs_err = abs(function - exp_sum)
rel_err = abs(abs_err)/abs(function)
rows.append((str(n), str(exp_sum), str(abs_err), str(rel_err)))
for line in pretty_table(rows, 4):
print(line)
For an input of N = 10, X = 5, this code outputs:
Term Exponential sum Absolute error Relative error
0 1.0 147.413159103 0.993262053001
1 6.0 142.413159103 0.959572318005
2 18.5 129.913159103 0.875347980517
3 39.3333333333 109.079825769 0.734974084703
4 65.375 83.0381591026 0.559506714935
5 91.4166666667 56.9964924359 0.384039345167
6 113.118055556 35.295103547 0.237816537027
7 128.619047619 19.7941114835 0.13337167407
8 138.307167659 10.1059914438 0.0680936347218
9 143.68945657 4.72370253291 0.0318280573062
If you want to redirect it into a file, do this instead of the last for loop:
with open('my_file.txt', 'w') as output:
for line in pretty_table(rows, 4):
print >> output, line
Please help me why on executing the below program an error coming on m variable
x=int(input("Enter first number"))
y=int(input("Enter second number"))
def multiplication():
m=x*y
print("Multiplication result"m)
In Python 2, you should accept user inputs with raw_input(): Check this.
x=int(raw_input("Enter first number"))
y=int(raw_input("Enter second number"))
Please follow a proper indentation plan with python:
Also, you did not accept the variables while defining your function, and learn how to use print:
def multiplication(x, y):
m = x * y
print "Multiplication result: %d" % m
Finally, to call this function, use:
multiplication(x, y)
x=int(raw_input("enter first number"))
os=raw_input("Enter the sign of what you wanna do +,-,/,*")
y=int(raw_input("enter second number"))
You can also do like this if you want to keep it in functions.
def input_function():
x = int(raw_input("Enter first number"))
y = int(raw_input("Enter second number"))
return x,y
def multiplication():
x,y = input_function()
m = x * y
print "Multiplication result", m
multiplication()
Or like this, in one function. But it doesn't look so pretty.
def multiplication(x,y):
m = x * y
print "Multiplication result",m
multiplication(int(raw_input('Enter first number')),int(raw_input('Enter second number')))
def r():
v = int(input("voltage: "))
i = int(input("current: "))
resistance = v*i
return(resistance,'ohms')
I'm having an issue with this piece of code I wrote. I'm trying to convert an integer input and print an output with its equivalent in binary base. For example for 5 it should drop an output of '101' however it just prints '10' like if it doesn't take into account the last digit. Please any comments would be greatly appreciated
T = raw_input()
for i in range(0, int(T)):
n = raw_input()
dec_num = int(n)
cnv_bin = ''
while dec_num//2 > 0:
if dec_num%2 == 0:
cnv_bin += '0'
else:
cnv_bin += '1'
dec_num = dec_num//2
print cnv_bin[::-1]
while dec_num//2 > 0:
should be:
while dec_num > 0:
The first time through the loop, 5//2==2, so it continues.
The second time through the loop, 2//2==1, so it continues.
The third time, 1//2==0 and the loop quits without handling the last bit.
Also, you can just do the following to display a number in binary:
print format(dec_num,'b')
Format string version:
print '{0} decimal is {0:b} binary.'.format(5)
Why not use the build-in function bin()?
eg:
bin(5)
output
0b101
If you don't want the prefix(0b), you can exclude it.
bin(5)[2:]
hope to be helpful!
import math
def roundup(n):
return math.ceil(n)
D = eval(input("Enter The Decimal Value: "))
n = roundup(math.log2(D+1))-1
bi = 0
di = D
qi = 0
i = n
print("Binary Value:",end = " ")
while(i>=0):
qi = math.trunc(di/2**i)
bi = qi
print(bi,end = "")
di = di - bi*(2**i)
i = i-1
Please could you help me by figuring out what is the wrong with my code.
I am trying to write a program that generates random walks in two dimensions and that determines statistics about the position of the walker after 500 steps when the number of walks is 1000, the max step size is 0.9, and the separation between the two positions is 0.001.
import math
import random
import time
print "RANDOM WALKS ANALYSIS IN ONE DIMENSION"
NOFW_ = 1000 #The number of walks
NOFS_= 500 #The number of steps in each walk
MSS_ = 0.9 # The maximum step size[m]
SOFP_ = 0.001 # The separation of positions considered equal[m]
print " Number of walks: %3g"% NOFW_
print " Number of steps in each Walk: %3g"% NOFS_
print " Maximum step size: %3g"% MSS_,"m"
print "Separation of positions considered equal: %3g"% SOFP_,"m"
print
print "Please wait while random walks are generated and analyzed..."
print "Date:" + time.ctime()
print
def initialPosition():
return (0.0, 0.0)
def distance(posA, posB):
"""Calculates the distance between two positions posA and posB"""
distance = math.sqrt((posB[0] - posA[0])**2 + (posB[1] - posA[1])**2)
return distance
def printstats(description, numbers):
minimum_value_ = min(numbers)
numbers.sort()
Tenth_percentile = abs(0.10*len(numbers) + 0.5)
Mean_value_ = (1./float(len(numbers))*sum(numbers))
A = 0
for values in numbers:
B = distance(values, Mean_value_)
B = B**2
A = B + A
Standard_deviation = math.sqrt((1./(len(numbers)-1))*A)
Newposition_ = int(0.90*(len(numbers) + 0.5))
Ninetieth_percentile =numbers[Newposition_]
maximum_value_ = max(numbers)
print "Analysis for"""+ description
print "Minimum value: %9.1f" % minimum_value_
print "10th percentile: %7.1f" % Tenth_percentile
print "Mean value: %12.1f" % Mean_value_
print "Standard deviation: %4.1f" % Standard_deviation
print "90th percentile: %7.1f" % Ninetieth_percentile
print "Maximum value: %9.1f" % maximum_value_
list_1 = [minimum_value_, Tenth_percentile, Mean_value_, Standard_deviation, Ninetieth_percentile,maximum_value_]
return list_1
def takeStep(prevPosition, maxStep):
x = random.random()
y = random.random()
minStep = -maxStep
Z = random.random()*2*math.pi
stepsize_ = random.random()*0.9
Stepx= stepsize_*math.cos(Z)
Stepy= stepsize_*math.sin(Z)
New_positionx = prevPosition[0] + Stepx
New_positiony = prevPosition[1] + Stepy
return (New_positionx, New_positiony)
Step_100 = []
Step_500 = []
count_list = []
for walk in range(NOFW_):
Step1 = []
Position = (0.0,0.0)
count = 0
for step in range(NOFS_):
Next_Step_ = takeStep(Position, MSS_)
for word in Step1:
if distance(Next_Step_, word) <= SOFP_:
count +=1
position = Next_Step_
Step1.append(Next_Step_)
Step_100.append(Step1[-1])
Step_500.append(Step1[-1])
count_list.append(count)
Step_100 = printstats("distance from start at step 100 [m]", Step_100)
Step_500 = printstats("distance from start at step 500 [m]", Step_500)
count_list = printstats("times position revisited", count_list)
Your problem is here
Mean_value_ = (1./float(len(numbers))*sum(numbers))
sum() is supposed to get some numbers but your variable numbers is actually containing some tuples of 2 values
You may want to define your own sum function for tuples of 2 numbers, or to sum the first values and second values separately