Hi I'm sort of new to programming and I would really appreciate some help with this problem.
I have a list of scores and I would like to create a function which divides each individual score by the calculated average of the whole list. The function should accept a list of scores as an argument and return a list with the modified scores.
Also, it should make use of a for loop and a return statement.
Here is a brief example of the list of scores I have:
13
22
33
42
25
(there are over 500 scores)
tbh, the wording of your question was a little confusing, but here's what you would do.
def scoreAvg(scores):
scoresSum = sum(scores)
scoresSum /= len(scores)
newScores = []
for i in scores:
i /= scoresSum
newScores.append(i)
return newScores
print(scoreAvg([13,22,33,42,25]))
You said you were pretty new to python, so I'll give you a rundown of what's happening here. Input 'scores' is a list containing our set of example scores (remember to enclose the input in square brackets). We find the sum of that list with sum() and the length with len(). We then begin a for loop to loop through the elements of scores, and divide each element by the avg, then append that value to a list we created earlier to hold the new scores. Now all we have to do is return that list with return newScores !
Hope I could help.
You can try the following code.
from __future__ import division #For decimal division.
''' Function (func) '''
def func(lst):
new_list = [] #Define an empty new list.
for i in range(len(lst)):
new_list += [ lst[i]*len(lst) / sum(lst) ]
return new_list
mylist = [13, 22, 33, 42, 25] #List you wish to enter.
mod_list = func(lst = mylist) #Modified list.
print mod_list #Prints output (mod_list).
>>>[0.48148148148148145, 0.8148148148148148, 1.2222222222222223, 1.5555555555555556, 0.9259259259259259]
In the above code, each element of new_list is element of input list (lst=mylist) divided by average of input list. One can obtain average by using the following: average = sum of input list / number of elements in input list. In python, the function len() gives you the number of items of an object (e.g. list). The function sum() gives you the sum elements of an object.
I hope this was helpful. Let me know if you have any questions. =)
Related
Sorry if I'm asking a stupid question.
So I'm studying Python and my homework is to find the lowest and highest number from list and then insert it into a tuple.
Right now this is the code I have (highlighted is my code):
import random
**def minimum_maximum(integer_list):
l.sort()
l = [l[0], l[-1]]
minimum_maximum = tuple(l)**
l = []
for i in range(random.randint(15,25)):
l.append(random.randint(-150,150))
print ("List:", l)
print ("Minimum and maximum:",minimum_maximum(l))
I can edit only the highlighted code. Right now the problem is "local variable 'l' referenced before assignment" which I tried to google, but I simply don't understand how to fix this. How can I make this work?
In your function, the input parameter is integer_list but you use l that is undefined:
def minimum_maximum(integer_list):
l.sort()
l = [l[0], l[-1]]
minimum_maximum = tuple(l)
Corrected version:
def minimum_maximum(integer_list):
l = sorted(integer_list) # using `sorted` to create a copy
return (l[0], l[-1]) # returning the tuple directly
NB. note that sorting the full list is not the most efficient method (although probably the shortest code). Ideally you should loop over the elements once and update the minimum and maximum as you go
A couple of problems:
Your function receives the parameter integer_list but instead of using it, you're using l.
You're trying to assign the result to a variable that is named the same way the function is (minimum_maximum). Instead just return the result.
Just for clarity, you can immediately return (integer_list[0], integer_list[-1])
You can use the min() and max() functions, which return the lowest and highest values of your list respectively:
def maximum_minimum(integer_list):
return (min(integer_list), max(integer_list))
So i'm studying recursion and have to write some codes using no loops
For a part of my code I want to check if I can sum up a subset of a list to a specific number, and if so return the indexes of those numbers on the list.
For example, if the list is [5,40,20,20,20] and i send it with the number 60, i want my output to be [1,2] since 40+20=60.
In case I can't get to the number, the output should be an empty list.
I started with
def find_sum(num,lst,i,sub_lst_sum,index_lst):
if num == sub_lst_sum:
return index_lst
if i == len(sum): ## finished going over the list without getting to the sum
return []
if sub_lst_sum+lst[i] > num:
return find_sum(num,lst,i+1,sub_lst_sum,index_lst)
return ?..
index_lst = find_sum(60,[5,40,20,20,20],0,0,[])
num is the number i want to sum up to,
lst is the list of numbers
the last return should go over both the option that I count the current number in the list and not counting it.. (otherwise in the example it will take the five and there will be no solution).
I'm not sure how to do this..
Here's a hint. Perhaps the simplest way to go about it is to consider the following inductive reasoning to guide your recursion.
If
index_list = find_sum(num,lst,i+1)
Then
index_list = find_sum(num,lst,i)
That is, if a list of indices can be use to construct a sum num using elements from position i+1 onwards, then it is also a solution when using elements from position i onwards. That much should be clear. The second piece of inductive reasoning is,
If
index_list = find_sum(num-lst[i],lst,i+1)
Then
[i]+index_list = find_sum(num,lst,i)
That is, if a list of indices can be used to return a sum num-lst[i] using elements from position i+1 onwards, then you can use it to build a list of indices whose respective elements sum is num by appending i.
These two bits of inductive reasoning can be translated into two recursive calls to solve the problem. Also the first one I wrote should be used for the second recursive call and not the first (question: why?).
Also you might want to rethink using empty list for the base case where there is no solution. That can work, but your returning as a solution a list that is not a solution. In python I think None would be a the standard idiomatic choice (but you might want to double check that with someone more well-versed in python than me).
Fill in the blanks
def find_sum(num,lst,i):
if num == 0 :
return []
elif i == len(lst) :
return None
else :
ixs = find_sum(???,lst,i+1)
if ixs != None :
return ???
else :
return find_sum(???,lst,i+1)
I'm trying to create a short script where 5 random numbers from an available list are selected and then each one is displayed. The problem I'm having is that the list to which I'm appending the results returns a list as well, not integers or strings. Here's the code:
def randomStar(self):
choice = [5,4,3]
probability = [0.1, 0.2, 0.7]
star = random.choices(choice, probability)
return star
multi = []
characters = []
for x in range(5):
star = randomStar(x)
multi.append(star)
x += 1
for star in multi:
characters.append(star)
print (characters)
print (multi)
Both multi and characters lists return:
['[3]', '[3]', '[3]', '[5]', '[3]']
So when I try to iterate through "Multi" list I still get lists. How can I get the values only? Or is the way I'm appending the numbers to the list incorrect?
Thanks.
They are lists because random.choices returns "a k sized list of elements".
Since there is only one element in the list, and this is what you are trying to return, you just want to write return star[0].
I have problem with dynamic substrings. I have list which can have 1000 elements, 100 elements or even 20. I want to make copy of that list, which will have elements from -10 to variable.
For example(pseudo-code):
L = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
variable = 12
print L[substring:variable]
>>> L = [2,3,4,5,6,7,8,9,10,12]
I can't figure out how make it correct. The point is that variable is always changing by one.
Here is my piece of code:
def Existing(self, Pages):
if(self.iter <= 10):
list = self.other_list[:self.iter]
else:
list = self.other_list[self.iter-10:self.iter]
result = 0
page = Pages[0]
list.reverse()
for blocks in Pages:
if(list.index(blocks) > result):
result = list.index(blocks)
page = blocks
return page
That method is looking for the element which has the farest index.
This part can be unclear. So assume that we have
list = [1,2,3,4,1,5,2,1,2,3,4]
Method should return 5, because it is the farest element. List has duplicates and .index() is returning index of the first element so i reverse list. With that code sometimes program returns that some element do not exist in List. The problem (after deep review with debbuger) is with substrings in self.other_list.
Could you help me with that problem? How to make it correct? Thanks for any advice.
EDIT: Because my problem is not clear enough (I was sure that it can be), so here are more examples.
Okay, so list Pages are list which cointains currently pages which are used. Second list "list" are list of all pages which HAS BEEN used. Method is looking for pages which are already used and choose that one which has been not used for the longest time. With word "use" I mean the index of element. What means the farest element? That one which the smallest index (remember about duplicates, the last duplicates means the real index).
So we have:
Pages = [1,3,5,9]
and
list = [1,2,5,3,6,3,5,1,2,9,3,2]
Method should return 5.
To sum up:
I'm looking for substring which give result:
With list =[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
For variable 12: [2,3,4,5,6,7,8,9,10,12]
for 13: [3,4,5,6,7,8,9,10,11,13]
ect :-)
I know that problem can be complicated. So i would aks you to focus only about substrings. :-) Thanks you very much!
If I understood your problem correctly you want to find the index of items from pages that is at minimum position in lst(taking duplicates in consideration).
So, for this you need to first reverse the list and then first the index of each item in pages in lst, if item is not found then return negative Infinity. Out of those indices you can find the max item and you'll get your answer.
from functools import partial
pages = [1,3,5,9]
lst = [1,2,5,3,6,3,5,1,2,9,3,2]
def get_index(seq, i):
try:
return seq.index(i)
except ValueError:
return float('-inf')
lst.reverse()
print max(pages, key=partial(get_index, lst))
#5
Note that the above method will take quadratic time, so it won't perform well for huge lists. If you're not concerned with some additional memory but linear time then you can use set and dict for this:
pages_set = set(pages)
d = {}
for i, k in enumerate(reversed(lst), 1):
if k not in d and k in pages_set:
d[k] = len(lst) - i
print min(d, key=d.get)
#5
Is there a quick and easy way that is not computationally expensive to overwrite an element in a list corresponding to an element in another list (of the same length)?
iterates = input("How many iterates: ")
trials = input("How many trials: ")
aggregateList = [iterates]
def function():
recordList = []
for i in range(iterates):
# math goes here
recordList.append()
aggregateList[i] += recordList[i]
for i in range(trials):
function()
The problem is coming from aggregateList[i] += recordList[i]Any ideas on something else that will work? Say the value in recordList[i] is 5 for the first "iteration", 5 for the second, 5 for the third, at this time aggregateList[i] should be 15.
I think you are looking for either:
aggregateList += recordList
or
aggregateList.append(recordList)
depending on whether you want your aggregate to be flat or nested.
And change aggregateList = [iterates] to aggregateList = [].
This is how I personally would implement it:
iterates = input("How many iterates: ")
trials = input("How many trials: ")
def function():
recordList = []
for i in range(iterates):
# math goes here
recordList.append()
return recordList
aggregateList = []
for i in range(trials):
aggregateList.append(function())
Or even:
def calculate (i): pass #math goes here
#nested:
aggregateList = [[calculate(i) for i in range(iterates)] for _ in range(trials)]
#flat:
aggregateList = [x for trial in ([calculate(i) for i in range(iterates)] for _ in range(trials)) for x in trial]
Let us assume you've have a list of lists (in a variable name lists). This would be after you have called your 'function()' function (not the greatest function name by the way) and collected your recordLists in a list.
trials = 3
lists = [[1,2,3],[4,5,6],[7,8,9]]
for i in range(trials):
aggregateList = [reduce(lambda x, y: x+y, [listn[i] for listn in lists]) for i in range(trials)]
print aggregateList
would output
[12, 15, 18]
which I think is the type of solution you are looking for.
reduce is a fun function from functional programming. It allows you to apply the anonymous function lambda continuously to items of a list and then return the accumulated value. So in this case, it is preforming (1+4)+7,(2+5)+8,(3+6)+9. The list we are applying reduce to is constructed through a comprehension to extract the i's from the lists inside lists. The call to reduce is wrapped inside another comprehension to return a list of the results.
So iterates is a number like 4, and trials another like 3.
aggregateList = [iterates]
now aggregateList = [4]. What's the purpose of that?
def function():
recordList = []
for i in range(iterates):
# math goes here
recordList.append()
what are you appending to recordList? That last line should produce an error like: append() takes exactly one argument (0 given)
aggregateList[i] += recordList[i]
what is i at this point? The last value of the above iteration, i.e. iterates-1 =3, or is supposed to be the trials iterator. How many items do you expect aggregateList to have at this point? As written I expect it to give an error: IndexError: list assignment index out of range.
for i in range(trials):
function()
What is 'the problem'? What error message or bad result were you getting?
I suspect you are more familiar with another language, and trying to apply its idioms to Python. Also, get the calculation working before worrying about efficiency. At some point, though you might want to use numpy which adds arrays, and the ability to do math on a whole array at once.