we have an assignment to write 10 or so python programs and i've gotten all but 2 so far. the ones im stumped on are:
But that obviously doesnt work
The other one is more complex
Any help on either would be amazing <3
I could figure out how to write a better exp function, but this one is ridiculous and I cant figure out the loop. What I have so far:For this part of the assignment, you will write a function to evaluate the mathematical exponential function, ex. Your Python function will be called badexp(x), because it really won't work very well, at least for some values of x.
Using the badexp formula:
term[i+1] = term[i] * x / (i + 1)
For your badexp function, you will certainly need to write a loop, but because of equation (7), you will not need to write a loop inside a loop (a "doubly-nested loop").
To write badexp, make a sum of the terms in the mathematical formula, starting with i = 0. You can't keep going forever, so stop as soon as adding a new term to the sum doesn't change the sum. That will certainly happen eventually, because for large i the terms become very small.
Code:
def badexp(x): i = 0 term1 = 0 term2 = x / (i + 1) while term1 != term2: term2 = term1 * x / (i + 1) print term2
The other one is more complex
My attempt so far:This function takes two parameters, url and line_number. It returns the first word in the line_numberth line of url. Line numbers are to be counted from 1, not from 0.
A "word" is defined as a sequence of alphabetic characters — letters — and you must find the first word by looking at the characters in the line one by one. Python strings have a function isalpha that will help you here. Your function must return None if line_number is not positive or is greater than the number of lines in url, or if there are no words in the line.
This function is harder to write. You will need more than one loop, at the very least.
Code:
def first_word(url, line_number): i = 1 if line_number > lines(url): return None if line_number <= 0: return None while i <= line_number: stream = urlopen(url) line = stream.readline() #line = url if line[0] == ' ': return None word1 = '' x = 0 while line[x] != ' ': word1 += line[x] x = x + 1 print word1 i = i + 1