I have the following code:
my_list = [1, 3, 5, 6, 10, 40, 2, 3, 9, 80, 23, 22]
def multiplied128 ():
for num in my_list:
val = num
ans = val*128
highest = (ans)
if ans > highest:
highest = ans
return(highest)
print(multiplied128())
I need to have code where if the answer is greater than the answer already stored in highest, it is overwritten. With the final return being just the highest result, in this case it would be the 11th result.
You need a few things:
Make sure to move the highest variable outside the loop. If not, it would be replaced each time the loop runs, and you never find out what is the highest value in your list.
And the second, which might not be completely necessary in your case, but it might be helpful, is to use float("-inf") as the first assigning value to the highest variable. This makes sure that you have not ignored any element in your list (there might have been negative values in the list, too)
Make sure that return is out of the for loop and at the end of the function.
Here is what I have come up with:
my_list = [1, 3, 5, 6, 10, 40, 2, 3, 9, 80, 23, 22]
def multiplied128 ():
highest = float("-inf")
for num in my_list:
val = num # This is not necessary. You can simply replace `num` with `val` in the for loop itself.
ans = val*128
if ans > highest:
highest = ans
return(highest)
print(multiplied128())
Output
10240
The output is as it should be: The highest value in your list is 80. Mutliplying this number by 128 results in 10240.
To find the highest number you should create a variable to store the highest result so far and compare to it every new result.
Here I defined the variable highest before the loop and set its value to 0
I'm not sure why you're doing the multiply by 128 but I left it there for you.
my_list = [1, 3, 5, 6, 10, 40, 2, 3, 9, 80, 23, 22]
def multiplied128():
highest = 0
for num in my_list:
ans = num*128
if ans > highest:
highest = ans
return highest
print(multiplied128())
BTW, the same result can be achieved with the built-in function max:
print(128*max(my_list))
Related
I would like to write a piece of code which calculates the sum of the elements in each row of a list and returns a new list of the row sums. For example
def row_sums(square):
square = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]
print(row_sums(square))
This would give the output of [10, 26, 42, 58] As the sum of the first row equals 10, sum of the second row equals 26 and so on. However I would like to NOT use the built in sum function to do this. How would I go about doing this? Thanks in advance.
A simple piece of code for calculating the sum of the elements in each row of a list.
square = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]
su=[sum(i) for i in square]
print (su)
Output:
[10, 26, 42, 58]
If you really cant use the sum() function, here is a function to sum the rows, I've written it explicitly to show the steps but it would be worth looking at list comprehensions once you understand what is going on:
def row_sums(square):
# list to store sums
output = []
# go through each row in square
for row in square:
# variable to store row total
total = 0
# go through each item in row and add to total
for item in row:
total += item
# append the row's total to the output list
output.append(total)
# return the output list
return output
This can then be used as such:
square = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]
row_totals = row_sums(square)
EDIT:
In answer to your comment, I'd do something like this:
def sum_columns(square):
# as before have a list to store the totals
output = []
# assuming your square will have the same row length for each row
# get the number of columns
num_of_columns = len(square[0])
# iterate over the columns
for i in xrange(0, num_of_columns):
# store the total for the column (same as before)
total = 0
# for each row, get the value for the column and add to the column total
# (value at index i)
for row in square:
total += row[i]
# append the total to the output list
output.append(total)
# return the list of totals
return output
Write your own sum function...
The module functools has a useful reduce function that you can use to write your own sum function. If you are comfortable with lambda functions you could do it this way:
lst = [0,1,2,3,4,5]
which would give sum(lst) as 15. However your own sum function with reduce may look something like:
from functools import reduce
reduce(lambda x,y: x + y, l)
which woudld also give 15. You should be able to write the rest yourself (i.e it within another list working on rows).
You can also do it with comprehension and reduce:
[reduce(lambda x, y: x + y, item) for item in square]
You can add that lines to your existent function:
result = []
for row in square: # iterates trough a row
line = 0 #stores the total of a line
for num in row: #go trough every number in row
line += num #add that number to the total of that line
result.append(line) #append to a list the result
print(result) #finally return the total of every line sum's in a list
Well at a certain point you have to use the sum-function (either as sum() or "+") but you could use map like
list(map(sum, square))
Suppose I have a list:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
I want to write a program that prints out all the elements of the list that are less than 10.
Actually its pretty simple I got this program but, I need to do it in a single line and I've no idea how to do that. Need some help with this.
print [x for x in a if x < 10]
Take a further look at lambda functions, I feel this is what you are looking for.
So in order to print something out of a list that is less than 10 In the same line, first you need to create a list:
numbers = []
loop through every single element of the list
for i in a:
And then you need a If statement to check if the element is less than 10
if i < 10:
Append the number to the list
numbers.append(str(i))
Join the results together:
result = " ".join(numbers)
And lastly printing it out
print(result)
And if you combine everything together, this is what you should get:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
numbers = []
for i in a:
if i < 10:
numbers.append(str(i))
result = " ".join(numbers)
print(result)
The result should be:
1 1 2 3 5 8
I need to build up a counting function starting from a dictionary. The dictionary is a classical Bag_of_Words and looks like as follows:
D={'the':5, 'pow':2, 'poo':2, 'row':2, 'bub':1, 'bob':1}
I need the function that for a given integer returns the number of words with at least that number of occurrences. In the example F(2)=4, all words but 'bub' and 'bob'.
First of all I build up the inverse dictionary of D:
ID={5:1, 2:3, 1:2}
I think I'm fine with that. Then here is the code:
values=list(ID.keys())
values.sort(reverse=True)
Lk=[]
Nw=0
for val in values:
Nw=Nw+ID[val]
Lk.append([Nw, val])
The code works fine but I do not like it. The point is that I would prefer to use a list comprehension to build up Lk; also I really ate the Nw variable I have used. It does not seems pythonic at all
you can create a sorted array of your word counts then find the insertion point with np.searchsorted to get how many items are to either side of it... np.searchsorted is very efficient and fast. If your dictionary doesn't change often this call is basically free compared to other methods
import numpy as np
def F(n, D):
#creating the array each time would be slow if it doesn't change move this
#outside the function
arr = np.array(D.values())
arr.sort()
L = len(arr)
return L - np.searchsorted(arr, n) #this line does all the work...
what's going on....
first we take just the word counts (and convert to a sorted array)...
D = {"I'm": 12, "pretty": 3, "sure":12, "the": 45, "Donald": 12, "is": 3, "on": 90, "crack": 11}
vals = np.arrau(D.values())
#vals = array([90, 12, 12, 3, 11, 12, 45, 3])
vals.sort()
#vals = array([ 3, 3, 11, 12, 12, 12, 45, 90])
then if we want to know how many values are greater than or equal to n, we simply find the length of the list beyond the first number greater than or equal to n. We do this by determining the leftmost index where n would be inserted (insertion sort) and subtracting that from the total number of positions (len)
# how many are >= 10?
# insertion point for value of 10..
#
# | index: 2
# v
# array([ 3, 3, 11, 12, 12, 12, 45, 90])
#find how many elements there are
#len(arr) = 8
#subtract.. 2-8 = 6 elements that are >= 10
A fun little trick for counting things: True has a numerical value of 1 and False has a numerical value of 0. SO we can do things like
sum(v >= k for v in D.values())
where k is the value you're comparing against.
collections.Counter() is ideal choice for this. Use them on dict.values() list. Also, you need not to install them explicitly like numpy. Sample example:
>>> from collections import Counter
>>> D = {'the': 5, 'pow': 2, 'poo': 2, 'row': 2, 'bub': 1, 'bob': 1}
>>> c = Counter(D.values())
>>> c
{2: 3, 1: 2, 5: 1}
I want to update the list used in the for loop statement as it is being appended with new values within the loop.I know this code wont update the list but I am not able to find a way to do so. I hope to required output might explain it better
INPUT
list=[1,2,3]
count=0
for x in list:
if int(len(list))>10:
break
else:
count=count+1
x=x+10
if x>3:
list=list+[x]
print "list = %r" %list
print "count = %r" %count
OUTPUT
list = [1, 2, 3, 11, 12, 13]
count = 3
Required OUTPUT
list = [1, 2, 3, 11, 12, 13, 21, 22, 23, 31]
count = 10
I suggest you use a while loop instead of a for, which saves the need of the break keyword :
l=[1,2,3]
count = len(l) # There are already len(l) elements in the list
pos = 0
while len(l) < 10:
count += 1
x = l[pos]
l.append(x+10)
pos += 1
print "list = %r" %l
print "count = %r" %count
Which gives the output :
list = [1, 2, 3, 11, 12, 13, 21, 22, 23, 31]
count = 10
Also, you can notice that i renamed the list variable to l, to prevent any confusion between the type list and the variable itself.
I used append to add elements at the end of the list.
Hope it'll be helpful.
two problems here:
first: the if x>3: test. (Why did you include that?)
second when you have a for statement, it loops on the values present initially only.
This should work:
l = [1,2,3]
count = 0
while len(l) < 10:
l.append(l[count]+10)
count += 1
I would like to remove elements which are multiples of 5 from a list.
In my code below "######" I tried >> number_list.pop(i) and it showed index out of range error. I also tried >> return number_list.pop(i) and it only seems to remove the first number which is 25. Codes in main() is given and I need to complete the function. I could easily do it by creating another list and store the numbers that are not multiples of 5 however it appears that I have to use the given list "numbers" to figure it out. I would be appreciated if I can get some help with this coding. Thank you.
ps. using python 3.5
def main():
numbers = [25, 5, 9, 10, 15, 8]
print(numbers)
remove_multiples(numbers, 5) # remove multiples of 5
print("Numbers left", numbers)
def remove_multiples(number_list, multiples_of):
for i in range(len(number_list)):
if number_list[i] % multiples_of == 0:
###################
return number_list
main()
def remove_multiples(number_list, multiples_of):
pivot = 0
for i,value in enumerate(number_list):
if value % multiples_of != 0:
number_list[pivot] = value
pivot += 1
del number_list[pivot:]
return number_list
move the available element to front, and delete the rest
def main():
numbers = [25, 5, 9, 10, 15, 8]
print(numbers)
remove_multiples(numbers, 5) # remove multiples of 5
print("Numbers left", numbers)
def remove_multiples(number_list, multiples_of):
for i in number_list:
if i % multiples_of == 0:
number_list.remove(i)
return number_list
main()
Hope that's what you're looking for.
Removing an element from a list you're currently iterating over is never a good idea.
Instead, create and return a new list without the unnecessary elements using list comprehension:
def remove_multiples(number_list, multiples_of):
return [num for num in number_list if num % multiples_of != 0]
print remove_multiples([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 2)
>> [1, 3, 5, 7, 9]