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']
Related
I have a list of tuples:
countries = [('Netherlands','31'),
('US','1'),
('Brazil','55'),
('Russia','7')]
Now, I want to find the index of the list, based on the first item in the tuple.
I have tried countries.index('Brazil'), I would like the output to be 2. But instead, that returns a ValueError:
ValueError: 'Brazil' is not in list
I am aware that I could convert this list into a pd DataFrame and then search for a pattern match within the first column. However, I suspect there is a faster way to do this.
You can use enumerate() to find your index:
Try:
idx = next(i for i, (v, *_) in enumerate(countries) if v == "Brazil")
print(idx)
Prints:
2
The task is:
User enters a number, you take 1 number from the left, one from the right and sum it. Then you take the rest of this number and sum every digit in it. then you get two answers. You have to sort them from biggest to lowest and make them into a one solid number. I solved it, but i don't like how it looks like. i mean the task is pretty simple but my code looks like trash. Maybe i should use some more built-in functions and libraries. If so, could you please advise me some? Thank you
a = int(input())
b = [int(i) for i in str(a)]
closesum = 0
d = []
e = ""
farsum = b[0] + b[-1]
print(farsum)
b.pop(0)
b.pop(-1)
print(b)
for i in b:
closesum += i
print(closesum)
d.append(int(closesum))
d.append(int(farsum))
print(d)
for i in sorted(d, reverse = True):
e += str(i)
print(int(e))
input()
You can use reduce
from functools import reduce
a = [0,1,2,3,4,5,6,7,8,9]
print(reduce(lambda x, y: x + y, a))
# 45
and you can just pass in a shortened list instead of poping elements: b[1:-1]
The first two lines:
str_input = input() # input will always read strings
num_list = [int(i) for i in str_input]
the for loop at the end is useless and there is no need to sort only 2 elements. You can just use a simple if..else condition to print what you want.
You don't need a loop to sum a slice of a list. You can also use join to concatenate a list of strings without looping. This implementation converts to string before sorting (the result would be the same). You could convert to string after sorting using map(str,...)
farsum = b[0] + b[-1]
closesum = sum(b[1:-2])
"".join(sorted((str(farsum),str(closesum)),reverse=True))
I am relatively new to Python. I wrote this code in Python (3.x) to solve a problem which involves an undirected graph.
The expected output of the program should print the node which occurs in the kth position from the list of neighbouring nodes of after they are sorted in descending order (based on the value of the node) but if two values are same then the node which comes first when sorted in ascending order of their indices is printed.
If no such node exists then -1 is printed.
n, m, k = input().strip().split(' ')
n, m, k = [int(n), int(m), int(k)]
node_values = list(map(int, input().split(' ')))
d = {}
for i in range(n+1):
d[i] = []
for i in range(m):
x, y = input().strip().split(' ')
x, y = [int(x), int(y)]
d[x].append(y)
d[y].append(x)
for key, value in d.items():
if key != 0:
if k <= len(value):
new_list = sorted(value, key=lambda x: node_values[x-1], reverse=True)
print(new_list[k-1])
else:
print(-1)
Here, I am sorting using sort(), providing the key as the value from node_values. But I am confused about adding the second condition (if the values are same then sort them according to the ascending order of their indices).
What am I doing wrong here? Also is it a better choice to use a parallel list for representing the graph over using dictionary?
The lambda function used to sort can return a tuple, which in your case would be formed as the node values and the index of the node.
sorted(value, key=lambda x: (node_values[x-1], x), reverse=True)
But you want a different order: descending for the node values and ascending for the indices. This can be achieved by sorting in descending order the negative value of the indices: x<y => -y < -x. So you can use this lamba function:
sorted(value, key=lambda x: (node_values[x-1], -x), reverse=True)
I assumed 'x' is the index of your node but this is not really clear for me.
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])
a = ['also', 'akin', 'akee','ague', 'aero', 'anes','here','beer','bute', 'byre', 'came', 'case', 'doze', 'down', 'drek', 'drew', 'dyes', 'fret', 'freo']
i = 'e'#i is user guess input
dic = {}
for item in a:
key = ''
for chr in item:
if chr == i:
key += i
else:
key += '-'
if key not in dic:
dic[key] = []
dic[key].append(item)
print(dic)
c = max(k for k, v in dic.items())
d = max(v for k, v in dic.items())
print('\nmax key:',c)
print('\nmax value:',d)
Output:
{'---e': ['ague', 'bute', 'byre', 'came', 'case', 'doze'], '--ee': ['akee'], '----': ['also', 'akin', 'down'], '-e-e': ['here'], '-ee-': ['beer'], '--e-': ['anes', 'drek', 'drew', 'dyes', 'fret', 'freo'], '-e--': ['aero']}
max key: -ee-
max value: ['here']
In the above example, a is a list of words. When the user guess a letter, for example 'e', the program iterates through each word in the list. Replace any letter that is not 'e' to a dash '-'.
I tried to map that result into a dictionary to keep track of the each group of words that where letter 'e' occurs in the same position.
Now, i want to retrieve the group of words(or key) with the largest number of words. Judging by the output, i'm not doing that because key'-e--' has the largest number of words.
I've also tried
max(dic.keys())
max(dic)
dic.get(max(dic.keys()))
Am i not fully understand the concept of max key and values for a dictionary?
Please suggest how i can fix this.
Thanks
In your question, the notion of max means being associated with the largest list., or being the largest list
max(dic.keys(), key=lambda x: len(dic[x]))
Will give you the maximum of dic's keys
Also,
sorted(dic.items(), key=lambda x:len(x[1]), reverse=True)
(in this example, lambda (x, y): len(y) works in python 2, not sure about python 3)
Will output a list of key, value tuples sorted by number of matches:
[('---e', ['ague', 'bute', 'byre', 'came', 'case', 'doze']), ('--e-', ['anes', 'drek', 'drew', 'dyes', 'fret', 'freo']), ('----', ['also', 'akin', 'down']), ('-e-e', ['here']), ('--ee', ['akee']), ('-e--', ['aero']), ('-ee-', ['beer'])]
Edit, no lambda
Without using a lambda, you'd be using a regular function:
def myMax(value_tuple):
key, value = value_tuple
return len(value)
and using it like so:
max(dic.items(), key=myMax)
Retrieve max key:
max(MyDictionary.keys(), key=type).
Retrieve max value:
max(MyDictionary.values(), key=type)
Replace type with the key type in both cases. i.e int
Hope it helps.