How to use the max array - python-3.x

maxPrice = 0
for item in cont["price_usd"]:
if(item[1] > maxPrice):
maxPrice = (item[1])
print (maxPrice)
I'm trying to find the max price in an array, and I'm trying to use the max() method to make my code simpler. cont["price_usd"] is a list of [amount_coins, price] and I'm trying to compare all of the prices.
I tried doing this:
list = cont["price_usd"]:
max(list)
but I don't know how to express that I only want the second subitem in each item.

Use map() and max()
prices = list(map(lambda x: x[1], cont["price_usd"]))
maxPrice = max(prices)
print(maxPrice)
The map function here uses the lambda function lambda x: x[1] to take each element of cont["price_usd"], extract the element at index 1, and then put that into a list. Then we call max to find the largest value in that list.

You should use the key keyword of the max function:
maxPrice = max(cont["price_usd"], key=lambda e: e[1])[1]

Related

How a Python code to store integer in list and then find the sum of integer stored in the List

List of integer value passed through input function and then stored in a list. After which performing the operation to find the sum of all the numbers in the list
lst = list( input("Enter the list of items :") )
sum_element = 0
for i in lst:
sum_element = sum_element+int(i)
print(sum_element)
Say you want to create a list with 8 elements. By writing list(8) you do not create a list with 8 elements, instead you create the list that has the number 8 as it's only element. So you just get [8].
list() is not a Constructor (like what you might expect from other languages) but rather a 'Converter'. And list('382') will convert this string to the following list: ['3','8','2'].
So to get the input list you might want to do something like this:
my_list = []
for i in range(int(input('Length: '))):
my_list.append(int(input(f'Element {i}: ')))
and then continue with your code for summation.
A more pythonic way would be
my_list = [int(input(f'Element {i}: '))
for i in range(int(input('Length: ')))]
For adding all the elements up you could use the inbuilt sum() function:
my_list_sum = sum(my_list)
lst=map(int,input("Enter the elements with space between them: ").split())
print(sum(lst))

Python: Sort list using substring

I am tying to sort a list of urls on the basis of a keyword. I have tried cmp and key argument, but none is working for me.
l = ['KFC/l1', 'KFC/l2', 'KFC/p1', 'KFC/p2']
def match_score(sentence):
some_pos = sentence.find('p')
text_pos = sentence.find('l')
return abs(text_pos - some_pos)
images.sort(key = lambda x: match_score(x))
The above is not working while my expected result is, sort by 'p1'
['KFC/p1', 'KFC/p2', 'KFC/l1', 'KFC/l2']
Thanks
If your key is always the last 2 characters in the pattern character-int, sorted reverse alphabetically, then by the int ascending, you could use this:
sorted_l = sorted(l, key = lambda x: (x[-2], -int(x[-1])), reverse=True)
which gives:
['KFC/p1', 'KFC/p2', 'KFC/l1', 'KFC/l2']

Python losing track of index location in for loop when my list has duplicate values

I'm trying to iterate over pairs of integers in a list. I'd like to return pairs where the sum equals some variable value.
This seems to be working just fine when the list of integers doesn't have repeat numbers. However, once I add repeat numbers to the list the loop seems to be getting confused about where it is. I'm guessing this based on my statements:
print(list.index(item))
print(list.index(item2))
Here is my code:
working_list = [1,2,3,4,5]
broken_list = [1,3,3,4,5]
def find_pairs(list, k):
pairs_list = []
for item in list:
for item2 in list:
print(list.index(item))
print(list.index(item2))
if list.index(item) < list.index(item2):
sum = item + item2;
if sum == k:
pair = (item, item2)
pairs_list.append(pair)
return pairs_list
### First parameter is the name is the list to check.
### Second parameter is the integer you're looking for each pair to sum to.
find_pairs(broken_list, 6)
working_list is fine. When I run broken_list looking for pairs which sum to 6, I'm getting back (1,5) but I should also get back (3,3) and I'm not.
You are trying to use list.index(item) < list.index(item2) to ensure that you do not double count the pairs. However, broken_list.index(3) returns 1 for both the first and second 3 in the list. I.e. the return value is not the actual index you want (unless the list only contains unique elements, like working_list). To get the actual index, use enumerate. The simplest implementation would be
def find_pairs(list, k):
pairs_list = []
for i, item in enumerate(list):
for j, item2 in enumerate(list):
if i < j:
sum = item + item2
if sum == k:
pair = (item, item2)
pairs_list.append(pair)
return pairs_list
For small lists this is fine, but we could be more efficient by only looping over the elements we want using slicing, hence eliminating the if statement:
def find_pairs(list, k):
pairs_list = []
for i, item in enumerate(list):
for item2 in list[i+1:]:
sum = item + item2
if sum == k:
pair = (item, item2)
pairs_list.append(pair)
return pairs_list
Note on variable names
Finally, I have to comment on your choice of variable names: list and sum are already defined by Python, and so it's bad style to use these as variable names. Furthermore, 'items' are commonly used to refer to a key-value pair of objects, and so I would refrain from using this name for a single value as well (I guess something like 'element' is more suitable).

python: max value in a dictionary with 2 keys

I have a dictionary D set up as D={('a','b'):['1000','5','.3'], ('c','d'):['2000','8','-.8']} where ('a','b') and ('c','d') are the keys. I am having trouble finding the maximum of the first values in the lists. So in using max(D) I need it to return ('c','d'). Keep in mind my list is hundreds of pairings. I just need to have the max() function be able to recognize the first value '2000' and '1000' and find the maximum of those. Any help or suggestions would be greatly appreciated.
python max function takes a key that you can use to define your function or lambda.
D={('a','b'):['1000','5','.3'], ('c','d'):['2000','8','-.8']}
res=max(D.items(), key=lambda k: int(k[1][0]))
print(res[0])
output:
('c', 'd')
Explanation:
In the code above, k will be the nth item/value pair as a tuple of your dictionary D. For first item k is (('a','b'),['1000','5','.3']). Then int(k[1][0]) returns 1000. We need to convert to int otherwise max will do string comparison.
Online link for above code: http://ideone.com/qmZvs8
You need to iterate through the dictionary, converting the first value's item to an int, and saving them for later:
first_values = []
for val in D.values():
first_values.append(int(val[0]))
print(max(first_values))
Taking your question literally, the max of '2000', '1000', etc is produced as follows
mx = max(val[0] for val in D.values())
or
from operator import itemgetter
mx = max(D.values(), key=itemgetter(0))[0
or
mx = max(D.values(), key=lambda val: val[0])[0]
Interpreting your question to mean max of 2000, 1000, etc (int('2000'), int('1000')
mx = max(int(val[0]) for val in D.values())
Interpreting your question a bit more, to include wanting the key with the max first value:
mxpair = max(d.items(), key=lambda item: int(item[1][0]))
key, mx = mxpair[0], mxpair[1][0])

For loops python that have a range

So I'm writing a python code and I want to have a for loop that counts from the the 2nd item(at increment 1). The purpose of that is to compare if there are any elements in the list that match or are included in the first element.
Here's what I've got so far:
tempStr = list500[0]
for item in list500(1,len(list500)):
if(tempStr in item):
numWrong = numWrong - 1
amount540 = amount540 - 1
However the code doesn't work because the range option doesn't work for lists. Is there a way to use range for a list in a for loop?
You can get a subset of the list with the code below.
tempStr = list500[0]
for item in list500[1:]:
if(tempStr in item):
numWrong = numWrong - 1
amount540 = amount540 - 1
The [1:] tells Python to use all elements of the array except for the first element. This answer has more information on list slicing.
Use a function:
search_linear(mainValues, target)
This is the algorithm you are looking for: http://en.wikipedia.org/wiki/Linear_search
All you need to do is set the starting point equal to +1 in order to skip your first index, and than use array[0] to call your first index as the target value.
def search_linear(MainValues, Target):
result = []
for w in Target:
if (search_linear(MainValues, w) < 0):
result.append(w)
return result

Resources