Finding the middle of a list - python

So I am trying to find the median of the list "revenues" which will be named "base_revenue".
Comments:
#Assume that revenues always has an odd number of members
#Write code to set base_revenue = midpoint of the revenue list
#Hint: Use the int and len functions
revenues = [280.00, 382.50, 500.00, 632.50, 780.00]
{def findMiddle(revenues):
middle = float(len(revenues))/2
if middle % 2 != 0:
return revenues[int(middle - .5)]
else:
return (revenues[int(middle)], revenues[int(middle-1)])}
I'm getting invalid syntax. The median function itself works, but maybe there is a more efficient way to do it.

Hint: the answer to this is far simpler than you've made it. You can even do it in a single line, unless your instructor specifically requires you to define a function.
You're told the list will always have an odd number of items; all you need is the index of the middle item. Remember that in Python, indices start at 0. So, for instance, a list of length 5 will have its middle element at index 2. A list of length 7 will have its middle element at index 3. Notice a pattern?
Your assignment also reminds you about len(), which finds the length of something (such as a list), and int(), which turns things (if possible) into integers. Notably, it turns a floating-point number into the the closest integer at or below it (a "floor" function); for instance it turns 2.5 into 2.
Can you see how you might put those together to programmatically find the midpoint index?

Related

Python - Need help understanding () vs [] when used with length

I'm new to Python and I'm messing around with this and I don't really know why when I change the brackets to parenthesis I get an error, or why I can't just use len(text - 1).
I'm looking at this code:
def reverse(text):
result = ""
length = len(text)
for i in text:
result += text[length - 1]
length -= 1
return result
Any help with understanding this is greatly appreciated!
Thanks!
You can't use text - 1 because that doesn't make sense; you cannot take 1 from a string.
Now, as for len(...) this is a function so has () for the call rather than []. You pass it the thing you want the length of.
text[length - 1] is indexing into the string, at a position, and follows the list syntax for indexing or sub-scripting.
When you use len(text - 1) you try to subtract int (1) from str (text). It is insupported operation in python (and moreover, impossible). To get a part of string you need you must use text[length - 1].
Python Parentheses
Parentheses play many different roles in Python these are some of the main roles they play:
The mathematical role:
Python parentheses act like parentheses in math as they are at the top of the Python Priority Precedence
This means that this:
>>> 3 + 4 * 2
returns:
12
Whereas with parentheses:
>>> (3 + 4) * 2
returns:
14
But that's not all, their priority also expands to Boolean expressions:
for example:
False and False or True and True
evaluates to True as and is executed before or. However, if you add some parentheses:
False and (False or True) and True
It evaluates to False as the or is executed before the and
Tuple
In python, when you put something in a tuple you use () notation.
Functions
When you declare or call a function you always need to add the parentheses after the function name. Think of them as a basket to put the arguments in. If you forget them the Python interpreter will think that you are calling a variable for example:
list
This is a variable called list and does nothing special
list() #Empty basket
This, however, is a call to a function as there is a "basket"
Square Brackets
Square Brackets also have quite a few roles:
Lists
In python, you use square brackets if you want to declare a list instead of a tuple.
List comprehension
List comprehension is actually pretty complicated so read this for more information but just know that it uses square brackets
Looking up
The main use of square brackets is to look up a value inside a list, tuple, or dictionary. Think of it like the google search bar: you write what you want and it tells you what it has. For example:
tuple = (2, 4)
if you want to get 4 you will need to look up the 2nd value of the tuple:
tuple[1] #The first value is 0
Slicing
Slicing is simply the idea of taking only certain parts of a list (or tuple, dictionary or even string). Here is an explanation by Greg Hewgill (https://stackoverflow.com/a/509295/7541446):
There is also the step value, which can be used with any of the above:
a[start:end:step] # start through not past end, by step
The key point to remember is that the :end value represents the first
value that is not in the selected slice. So, the difference beween end
and start is the number of elements selected (if step is 1, the
default).
The other feature is that start or end may be a negative number, which
means it counts from the end of the array instead of the beginning.
So:
a[-1] # last item in the array a[-2:] # last two items in the
array a[:-2] # everything except the last two items
Python is kind to the programmer if there are fewer items than you ask
for. For example, if you ask for a[:-2] and a only contains one
element, you get an empty list instead of an error. Sometimes you
would prefer the error, so you have to be aware that this may happen.
I hope this provided useful insight to explaining the difference between parentheses and square brackets.
This means that in your question len() is a function where you are putting text inside the basket. However, when you call text[length-1] you are looking up the value at position length-1
The python builtin function len() returns the length in numbers of the object in argument e.g
temp = [1, 2, 3, 4]
length = len(temp)
then the len() will return 4 in this case. but if someone write
length = len(temp-1)
then
temp-1
is not a valid object, therefor you cannot use it.
The reason you can't do len(text-1) is because text is a string type you are trying to reverse, and being a string you cannot combine it with numbers(unless they are a string, but thats a different story) without getting an error. Therefore you do len(text)-1 because len(text) would equal the length of whatever the text is(lets say four), and then you can subtract 1 from 4 because 4 is an integer.
The reason you need brackets and not parentheses when you are doing text[length-1] is because in python trying to get a single value out of a string requires the use of string[] and putting a position in the string inside the []. You use partakes to call functions like print(string) or len(text), so putting text(length-1) would create an error that basically says the program doesn't have a function named "text" and it doesn't know what to do.
Hope this helps. Tell me if you have any more questions.

How would I have my code remove the lowest integer?

def calc_average(scores)
x = scores[1:]
return (sum(x) / float(len(x)))
Here is some code that is supposed to find the average of a list of numbers, but not count the lowest. I'm not sure how to find the lowest number in the list, remove it from it, and then find the average of that. Can anyone help? Thanks! (The lowest number isn't always the first number in the list, that's the mistake I made...)
You don't have to literally remove the item from the list; you can just remove it from the calculation.
def calc_average(scores)
return (sum(scores) - min(scores)) / float(len(x) - 1)
I would sort the list then romove the first element.
a = [ 3,2,6,3,8,7,2,1]
a.sort()
a = a[1:]
print a
print float(sum(a))/len(a)
The benefit of doing it this way, even though it is more work for just removing the single lowest value is that it is salable. Let's say you wanted to remove the lowest 2 or three values, that would be easy once you have the list sorted.
You can use the min() function to find the smallest value of a list, and then you can remove the value with the list.remove() function.
Check this out for reference https://docs.python.org/2/library/functions.html#min or https://docs.python.org/3.6/library/functions.html#min
You could use
return float((sum(scores) - min(scores))) / (len(scores) - 1)
That finds the sum of all the scores, then removes the smallest score, before dividing by the number of scores after the removal.
Note there is no error-checking here, so this will not work properly for a list of length zero or one. That float() is there to ensure floating point division in Python 2.x. This uses the full speed of Python functions, but it does loop over the scores twice. A hand-coded function would be faster in looping only once but would slow down again in executing multiple commands.

Weird behaviour of find() function (python2.7) [duplicate]

find('asdf','') finds an empty string in 'asdf' hence it returns 0.
Similarly, find('asdf','',3) starts to search for the string at index position 3 and hence return 3.
Since the last index is 3, find('asdf','',4) should return -1 but it returns 4 and starts to return -1 only if the starting index is more than or equal to (last_index)+2. Why is this so?
Because "asdf" without its first four characters still does contain "". A harder check comes into play when the index exceeds the length of the string, but having an index equal to the string is equivalent to "".find().
Here is how it works:
0 a 1 s 2 d 3 f 4
When you use 'asdf'.find(sub), it searches those five positions, labeled 0, 1, 2, 3, and 4. Those five. Those five. No more and no less. It returns the first one where 'asdf'[pos:pos+len(sub)] == sub. If you include the start argument to find, it starts at that position. That position. Not one less, not one more. If you give a start position greater than the greatest number in the list of positions, it returns -1.
In other words, the answer is what I already repeated in a comment, quoting another question answer:
The last position [for find] is after the last character of the string
Edit: it seems your fundamental misunderstanding relates to the notion of "positions" in a string. find is not returning positions which you are expected to access as individual units. Even if it returns 4, that doesn't mean the empty string is "at" position 4. find returns slice starts. You are supposed to slice the string starting at the given position.
So when you do 'asdf'.find('', 4), it starts at position 4. It finds the empty string there because 'asdf'[4:4+len('')]==''. It returns 4. That is how it works.
It is not intended that str.find has a one-to-one mapping between valid indexes into the actual string. Yes, you can do tons of other indexing like 'asdf'[100:300]. That is not relevant for find. What you know from find is that 'asdf'[pos:pos+len(sub)] == sub. You do not know that every possible index that would return '' will be returned by find, nor are you guaranteed that the number returned by find is a valid index into the string if you searched for an empty string.
If you have an actual question about some use of this functionality, then go ahead and ask that as a separate question. But you seem to already know how find works, so it's not clear what you're hoping to gain from this question.

Insert number to a list

I have an ordered dictionary like following:
source =([('a',[1,2,3,4,5,6,7,11,13,17]),('b',[1,2,3,12])])
I want to calculate the length of each key's value first, then calculate the sqrt of it, say it is L.
Insert L to the positions which can be divided without remainder and insert "1" after other number.
For example, source['a'] = [1,2,3,4,5,6,7,11,13,17] the length of it is 9.
Thus sqrt of len(source['a']) is 3.
Insert number 3 at the position which can be divided exactly by 3 (eg. position 3, position 6, position 9) if the position of the number can not be divided exactly by 3 then insert 1 after it.
To get a result like folloing:
result=([('a',["1,1","2,1","3,3","4,1","5,1","6,3","7,1","11,1","13,3","10,1"]),('b',["1,1","2,2","3,1","12,2"])]
I dont know how to change the item in the list to a string pair. BTW, this is not my homework assignment, I was trying to build a boolean retrival engine, the source data is too big, so I just created a simple sample here to explain what I want to achive :)
As this seems to be a homework, I will try to help you with the part you are facing problem with
I dont know how to change the item in the list to a string pair.
As the entire list needs to be updated, its better to recreate it rather than update it in place, though its possible as lists are mutable
Consider a list
lst = [1,2,3,4,5]
to convert it to a list of strings, you can use list comprehension
lst = [str(e) for e in lst]
You may also use built-in map as map(str,lst), but you need to remember than in Py3.X, map returns a map object, so it needs to be handled accordingly
Condition in a comprehension is best expressed as a conditional statement
<TRUE-STATEMENT> if <condition> else <FALSE-STATEMENT>
To get the index of any item in a list, your best bet is to use the built-in enumerate
If you need to create a formatted string expression from a sequence of items, its suggested to use the format string specifier
"{},{}".format(a,b)
The length of any sequence including a list can be calculated through the built-in len
You can use the operator ** with fractional power or use the math module and invoke the sqrt function to calculate the square-root
Now you just have to combine each of the above suggestion to solve your problem.

Data Structures - lists

This is homework but the lesson gives me the answer already. I'm having trouble putting the words from the answer to the line of code
#Calculate all the primes below 1000
result = [1]
candidates = range(3, 1000)
base = 2
product = base
while candidates:
while product < 1000:
if product in candidates:
candidates.remove(product)
product = product + base
result.append(base)
base = candidates[0]
product = base
del candidates[0]
result.append(base)
print result
This is a version of "The Sieve of Erastothenes."
This is the explanation that was given to me.
New things in this example…
The built-in function range actually returns a list that can be used like all other lists. (It includes the first index, but not the last.) A list can be used as a logic variable. If it is not empty, then it is true — if it is empty, then it is false. Thus, while candidates means “while the list named candidates is not empty” or simply “while there are still candidates”. You can write if someElement in someList to check if an element is in a list. You can write someList.remove(someElement) to remove someElement from someList. You can append an element to a list by using someList.append(something). Actually, you can use + too (as in someList = someList+[something]) but it is not as efficient. You can get at an element of a list by giving its position as a number (where the first element, strangely, is element 0) in brackets after the name of the list. Thus someList[3] is the fourth element of the list someList. (More on this below.) You can delete variables by using the keyword del. It can also be used (as here) to delete elements from a list. Thus del someList[0] deletes the first element of someList. If the list was [1,2,3] before the deletion, it would be [2,3] afterwards.
Before going on to explaining the mysteries of indexing list elements, I will give a brief explanation of the example.
This is a version of the ancient algorithm called “The Sieve of Erastothenes” (or something close to that). It considers a set (or in this case, a list) of candidate numbers, and then systematically removes the numbers known not to be primes. How do we know? Because they are products of two other numbers.
We start with a list of candidates containing numbers [2..999] — we know that 1 is a prime (actually, it may or may not be, depending on who you ask), and we wanted all primes below 1000. (Actually, our list of candidates is [3..999], but 2 is also a candidate, since it is our first base). We also have a list called result which at all times contains the updated results so far. To begin with, this list contains only the number 1. We also have a variable called base. For each iteration (“round”) of the algorithm, we remove all numbers that are some multible of this base number (which is always the smallest of the candidates). After each iteration, we know that the smallest number left is a prime (since all the numbers that were products of the smaller ones are removed — get it?). Therefore, we add it to the result, set the new base to this number, and remove it from the candidate list (so we won’t process it again.) When the candidate list is empty, the result list will contain all the primes. Clever, huh?
What I don't understand is where they say, 'we remove all numbers that are some multiple of this base number.' Where is that in the line of code? Can someone explain line by line what the program is doing? I am a newb at this trying to understand the mechanics on each line of code and why. Thanks for any assistance.
At the start of each of the while candidates: loops, product equals base. Then in that loop you have another loop, while products < 1000. At the end of this loop you increment product by base. So product goes through each multiple of base. You then remove all the values of product which is where you "remove multiples of the base number".
Basically what the program is doing is:
...
set product to base
for each candidate
for each multiple of base, referred to as 'product'
remove product from candidates
set base to new value
reset product to new base
...

Categories

Resources