How to multiply 2 values in list of (3) numbers and letters - python-3.x

I have a list(or it can be a dictionary):
A = [
['soda',9,3],
['cake',56,6],
['beer',17,10],
['candies',95,8],
['sugar',21,20]
]
And i need to find a multiply of last 2 values in each sublist and sum up this:
9*3+56*6+17*10+95*8+21*20
How can i do this?

It's a very basic question and has a really simple answer. Until you are sure that the format is the same, the following code will help you:
result = 0
for sub_list in A:
result += sub_list[-1] * sub_list[-2]
The result variable will store the result you want. sub_result is one of the sublists in A in each iteration.
sub_list[-1] is the last element of sub-list and `sub_list[-2] is the element before that.

Related

Shortest code to return current index number in string in 'for n in 'word': loop

I have a question about strings. I thought that this code:
for n in 'banana':
print(n)
would return this:
0
1
2
3
4
5
But, of course, it doesn't. It returns the value at each position in the string, not the position number. In order for me to understand this better, I thought it might help to write the simplest possible program to achieve the output I thought I'd get:
count = 0
for n in 'banana':
print(count)
count += 1
This works, but surely there's a more direct way to access the position number that the current iteration is looking at? Can't see any methods that would achieve this directly though.
These are all equivalent:
i = 0
for n in 'banana':
print(i)
i += 1
for i, w in enumerate('banana'):
print(i)
for i in range(len('banana')):
print(i)
print(*range(len('banana')), sep='\n')
As posted in the other answer, enumerate() works:
for idx, character in enumerate('myword'):
print(f"Index={idx} character={character}")
It is worth pointing out that in this Python treats strings as arrays. When you have "abc"[0] it will return a. And, similarly, when you say 'give me each element in some array' it will simply give you the element, not the index of that element - which would be counterintuitive.

for loop doesn't itterate through all the data? [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 1 year ago.
data = [1, 2, 3, 4, 5]
for x in data:
print(x)
if data.count(x) < 2:
data.remove(x)
Hello Guys,
so I am currently working through py.checkio.org and am at a point where I have to remove all the numbers that are unique in a list.
When I run my code without the if statement I get an output counting from 1 to 5. But once I run the for loop with the if statement the for loop only runs through the data for every second number and my output is 1 3 5. Can anyone please tell me what is happening here?
While the from #Stef and #0x5453 are both relevant to your problem. The comment from #ConnorTJ is patently wrong. The remove function does not remove the item at the index but the first occurrence of the item.
To answer your question, about what's going on here, let[s examine your code:
The first pass through the value of x is 1
You print the value of x
You then test to see if the number of occurrences of x is less than 2
Since the answer is yes, you proceed to remove the item from the list.
The second pass through the list the For loop picks up the next value in the list (at index 1) which is now the value 3
You print the value 3
You check to see if the count of 3 is less than 2
Since the count is less you remove that item from the list.
This process than continues
Simple solution, use filter()
Construct an iterator from those elements of iterable for which function returns true
it returns a list of the list items that the function returned true for.
example:
x = [1,1,2,2,3,4]
x = filter(lambda f: (x.count(f)<2), x)
x = list(x)
print(x)
or in short: print(list(filter(lambda f: (x.count(f)>=2),x)))
output is [1,1,2,2]

How to subtract adjacent items in list with unknown length (python)?

Provided with a list of lists. Here's an example myList =[[70,83,90],[19,25,30]], return a list of lists which contains the difference between the elements. An example of the result would be[[13,7],[6,5]]. The absolute value of (70-83), (83-90), (19-25), and (25-30) is what is returned. I'm not sure how to iterate through the list to subtract adjacent elements without already knowing the length of the list. So far I have just separated the list of lists into two separate lists.
list_one = myList[0]
list_two = myList[1]
Please let me know what you would recommend, thank you!
A custom generator can return two adjacent items at a time from a sequence without knowing the length:
def two(sequence):
i = iter(sequence)
a = next(i)
for b in i:
yield a,b
a = b
original = [[70,83,90],[19,25,30]]
result = [[abs(a-b) for a,b in two(sequence)]
for sequence in original]
print(result)
[[13, 7], [6, 5]]
Well, for each list, you can simply get its number of elements like this:
res = []
for my_list in list_of_lists:
res.append([])
for i in range(len(my_list) - 1):
# Do some stuff
You can then add the results you want to res[-1].

Get the value of a list that produces the maximum value of a calculation

I apologize if this is a duplicate, I tried my best to find an existing question but was unsuccessful.
Recently, I've run into a couple of problems where I've needed to find the element in a list that produces the max/min value when a calculation is performed. For example, a list of real numbers where you want to find out which element produces the highest value when squared. The actual value of the squared number is unimportant, I just need the element(s) from the list that produces it.
I know I can solve the problem by finding the max, then making a pass through the list to find out which values' square matches the max I found:
l = [-0.25, 21.4, -7, 0.99, -21.4]
max_squared = max(i**2 for i in l)
result = [i for i in l if i**2 == max_squared]
but I feel like there should be a better way to do it. Is there a more concise/one-step solution to this?
This will return you just the element which gives the max when squared.
result = max(l, key = lambda k: k**2)
It does not get much better if you need the value in a list f.e. to see how often it occures. You can remeber the source element as well if you do not need that:
l = [-0.25, 21.4, -7, 0.99, -21.4]
max_squared = max( (i**2, i) for i in l) # remeber a tuple, with the result coming first
print(max_squared[1]) # print the source number (2nd element of the tuple)
Output:
21.4
Your calculation does only return the first occurence of abs(24.1) because max only returns one value, not two - if you need both, you still need to do:
print( [k for k in l if abs(k) == max_squared[1]])
to get
[21.4,-21.4]

choose one list. choose the one whose nth element is the smallest. Python 3

I have two lists. I have to choose one. I have to choose the one with the smallest nth element. So I can choose the smallest element easy with min, but how do I back track it to the list itself. Have literally no idea how to solve this presumably easy problem.
a = [2,45,1,56]
b= [0,23,3,87]
Which list has the smallest element at position 2? The answer here is list a.
In case I wasnt clear, the program sould be able to solve this task for any pair of lists.
Here is a very simple snippet that does what you want, but you might want to check for the size of the arrays, in case the index is out of range.
def choose_smallest(a, b, i):
if len(a) >= i or len(b) >= i:
return 0 # do whatever you want here
if a[i] < b[i]:
return a
else:
return b
Also notice that both nth elements in your array can have the exact same value... In this example array b will be returned, but you can change that behaviour if needed.
EDIT
Added array length check
According to your example, here is a sample code you can try. You can change the code as per your requirement.
a = [2,45,1,56]
b = [0,23,3,87]
n= int(input('Enter element number: ')) # n starts from zero to length of list - 1
if a[n] > b[n]:
print('List b has smaller nth element')
elif a[n] < b[n]:
print('List a has smaller nth element')
else:
print('Both lists have equal nth element')

Resources