I could be completely wrong here with how to go about this, but basically I need to at first create a dictionary of names with empty lists of values for a race.
contestants = {[("Alice", []),("Dennis", []), ("Bob", []), ("Eva", []), ("Clare", [])]}
I'm assuming that is it how I do it ^^
and then I need to be able to append the values to the empty lists and sort the the positions based upon the overall score.
{'Dennis': [4, 4, 4, 4, 4, 5], 'Alice': [2, 2, 2, 1, 1, 2], 'Bob': [3, 3, 3, 3, 2, 1], 'Eva': [5, 5, 5, 5, 3, 3], 'Clare': [1, 1, 1, 2, 5, 4]}
Above are the score that each player has had and it has also been sorted for them.
def seriesscores(racescores):
contestants = {[("Alice", []),("Dennis", []), ("Bob", []), ("Eva", []), ("Clare", [])]}
contestants.append(racescores[1])
return contestants
I have currently been testing this code above and it keep displaying a error like this:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in seriesscores
TypeError: unhashable type: 'list'
All I'm looking for right now is a way to append the scores to the empty lists, I assume I could just sort it then with this code:
return sorted(contestants, key=lambda x: (sum(x[1])))
Am I on the correct track?
Try this:
contestants = {"Alice": [], "Dennis": [], "Bob": [], "Eva": [], "Clare": []}
Instead of this:
contestants = {[("Alice", []),("Dennis", []), ("Bob", []), ("Eva", []), ("Clare", [])]}
Also, what exactly is in racescores argument? I guess you may want to do something like this:
for key, value in enumerate(racescores):
contestants[key] += value
But I am guessing and without data format in racescores I can't really help you more.
Related
I am trying to use list splicing to rotate a value in a list but I can't figure out why my brackets are not closing. the issue in question is on line 3. It is throwing an invalid syntax error saying that "[" is not closed
code is below
def rotate_list(data, amount):
result = []
result.append(data = [amount:])
return result
print(rotate_list([1,2,3,4,5,6,7,8,9],5)) # [5, 6, 7, 8, 9, 1, 2, 3, 4]
print(rotate_list([1,2,3,4,5,6,7,8,9],9)) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
[amount:] is not syntactically correct, as you are missing the list in which to iterate. Try rewriting your function as
def rotate_list(data, amount):
return data[amount:] + data[:amount]
I have a dictionary in python with several lists, and what I try to do is get a list of tuples (or lists) where the lists are grouped with the same elements regardless of whether they are ordered. For example:
dict_1 = {
"pv_0": [1, 2, 3, 4, 5],
"pv_1": [2, 4, 6, 8, 10],
"pv_2": [1, 3, 5, 7, 9],
"pv_3": [3, 4, 1, 2, 5],
"pv_4": [2, 3, 4, 5, 6],
"pv_5": [3, 4, 5, 6, 2],
"pv_6": [1, 2, 3, 5, 4],
"pv_7": [5, 9, 7, 3, 1],
"pv_8": [2, 4, 6, 8, 10],
"pv_9": [1, 3, 5, 6, 7],
}
I wish to obtain the following result:
Result = [
("pv_0", "pv_3", "pv_6"),
("pv_2", "pv_7"),
("pv_1", "pv_8"),
("pv_4", "pv_5"),
("pv_9"),
]
How do I solve this problem?
from operator import itemgetter
from itertools import groupby
# create a new dictionary where the value is a hashed immutable set
d = {k: hash(frozenset(v)) for k, v in dict_.items()}
{'pv_0': -3779889356588604112,
'pv_1': 2564111202014126800,
'pv_2': 777379418226018803,
'pv_3': -3779889356588604112,
'pv_4': 8713515799959436501,
'pv_5': 8713515799959436501,
'pv_6': -3779889356588604112,
'pv_7': 777379418226018803,
'pv_8': 2564111202014126800,
'pv_9': -6160949303479789752}
first = itemgetter(0) # operator to grab first item of iterable
second = itemgetter(1) # operator to grab second item of iterable
[list(map(first, v)) for _, v in groupby(sorted(d.items(), key=second), key=second)]
[['pv_9'],
['pv_0', 'pv_3', 'pv_6'],
['pv_2', 'pv_7'],
['pv_1', 'pv_8'],
['pv_4', 'pv_5']]
The final list comprehension grabs all the key/value pairs from the dictionary and sorts them by the value. It then passes that in to the groupby function from itertools and tells it to group by the value of the dictionary. The output of this is then fed in to a map function which grabs the first item from each pair in the group which would be the corresponding key.
From what I can tell, you want a tuple of keys where each value is the same.
def get_matching_keys(data: dict) -> list:
# first, make everything a set
for key in data:
data [key] = set (data [key]) # makes order irrelevant
results = []
duplicates = []
for key, value in data.items():
if key in duplicates: continue # we already did this
result = [key]
duplicates.append (key)
for key2, value2 in data.items():
if key == key2: continue # skip the same key
else:
if value == value2:
result.append (key2)
duplicates.append (key2) # make sure we don't do it again
results.append (result)
return results
Having this python code
edges = [(0, [3]), (1, [0]), (2, [1, 6]), (3, [2]), (4, [2]), (5, [4]), (6, [5, 8]), (7, [9]), (8, [7]), (9, [6])]
graph = {0: [3], 1: [0], 2: [1, 6], 3: [2], 4: [2], 5: [4], 6: [5, 8], 7: [9], 8: [7], 9: [6]}
cycles = {}
while graph:
current = graph.iteritems().next()
cycle = [current]
cycles[current] = cycle
while current in graph:
next = graph[current][0]
del graph[current][0]
if len(graph[current]) == 0:
del graph[current]
current = next
cycle.append(next)
def traverse(tree, root):
out = []
for r in tree[root]:
if r != root and r in tree:
out += traverse(tree, r)
else:
out.append(r)
return out
print ('->'.join([str(i) for i in traverse(cycles, 0)]))
Traceback (most recent call last):
File "C:\Users\E\Desktop\c.py", line 20, in <module>
current = graph.iteritems().next()
AttributeError: 'dict' object has no attribute 'iteritems'
I also tried itervalues, iterkeys... but that does not work
How to modify code?
You are using Python 3; use dict.items() instead.
The Python 2 dict.iter* methods have been renamed in Python 3, where dict.items() returns a dictionary view instead of a list by default now. Dictionary views act as iterables in the same way dict.iteritems() do in Python 2.
From the Python 3 What's New documentation:
dict methods dict.keys(), dict.items() and dict.values() return “views” instead of lists. For example, this no longer works: k = d.keys(); k.sort(). Use k = sorted(d) instead (this works in Python 2.5 too and is just as efficient).
Also, the dict.iterkeys(), dict.iteritems() and dict.itervalues() methods are no longer supported.
Also, the .next() method has been renamed to .__next__(), but dictionary views are not iterators. The line graph.iteritems().next() would have to be translated instead, to:
current = next(iter(graph.items()))
which uses iter() to turn the items view into an iterable and next() to get the next value from that iterable.
You'll also have to rename the next variable in the while loop; using that replaces the built-in next() function which you need here. Use next_ instead.
The next problem is that you are trying to use current as a key in cycles, but current is a tuple of an integer and a list of integers, making the whole value not hashable. I think you wanted to get just the next key instead, in which case next(iter(dict)) would give you that:
while graph:
current = next(iter(graph))
cycle = [current]
cycles[current] = cycle
while current in graph:
next_ = graph[current][0]
del graph[current][0]
if len(graph[current]) == 0:
del graph[current]
current = next_
cycle.append(next_)
This then produces some output:
>>> cycles
{0: [0, 3, 2, 1, 0], 2: [2, 6, 5, 4, 2], 6: [6, 8, 7, 9, 6]}
When ever I am trying to import a file named "tttnums.py" I always get this error:
Traceback (most recent call last):
File "C:/Users/Marcsegal/Dropbox/Programs/ttt finished.py", line 1, in <module>
import tttnums
RuntimeError: maximum recursion depth exceeded during compilation
This is the contents of tttnums.py:
tttSets = [
[7, 1, 4, 0, 3, 2, 8, 6, 5, 'L']
[0, 6, 5, 4, 2, 8, 1, 3, 7, 'W']
[2, 8, 0, 5, 6, 7, 4, 3, 1, 'W']
(continued with 40317 more lists)
]
I assume the reason I got this error is because I have so many lists in the file (40320 to be exact). How do I fix this error?
If the whole content of tttnums.py is just that data structure, it makes much more sense to store it in a plain text or .json file and just read it than to import it as a .py file.
I am fairly new to python and am trying to figure out how to duplicate items within a list. I have tried several different things and searched for the answer extensively but always come up with an answer of how to remove duplicate items, and I feel like I am missing something that should be fairly apparent.
I want a list of items to duplicate such as if the list was [1, 4, 7, 10] to be [1, 1, 4, 4, 7, 7, 10, 10]
I know that
list = range(5)
for i in range(len(list)):
list.insert(i+i, i)
print list
will return [0, 0, 1, 1, 2, 2, 3, 3, 4, 4] but this does not work if the items are not in order.
To provide more context I am working with audio as a list, attempting to make the audio slower.
I am working with:
def slower():
left = Audio.getLeft()
right = Audio.getRight()
for i in range(len(left)):
left.insert(????)
right.insert(????)
Where "left" returns a list of items that are the "sounds" in the left headphone and "right" is a list of items that are sounds in the right headphone. Any help would be appreciated. Thanks.
Here is a simple way:
def slower(audio):
return [audio[i//2] for i in range(0,len(audio)*2)]
Something like this works:
>>> list = [1, 32, -45, 12]
>>> for i in range(len(list)):
... list.insert(2*i+1, list[2*i])
...
>>> list
[1, 1, 32, 32, -45, -45, 12, 12]
A few notes:
Don't use list as a variable name.
It's probably cleaner to flatten the list zipped with itself.
e.g.
>>> zip(list,list)
[(1, 1), (-1, -1), (32, 32), (42, 42)]
>>> [x for y in zip(list, list) for x in y]
[1, 1, -1, -1, 32, 32, 42, 42]
Or, you can do this whole thing lazily with itertools:
from itertools import izip, chain
for item in chain.from_iterable(izip(list, list)):
print item
I actually like this method best of all. When I look at the code, it is the one that I immediately know what it is doing (although others may have different opinions on that).
I suppose while I'm at it, I'll just point out that we can do the same thing as above with a generator function:
def multiply_elements(iterable, ntimes=2):
for item in iterable:
for _ in xrange(ntimes):
yield item
And lets face it -- Generators are just a lot of fun. :-)
listOld = [1,4,7,10]
listNew = []
for element in listOld:
listNew.extend([element,element])
This might not be the fastest way but it is pretty compact
a = range(5)
list(reduce(operator.add, zip(a,a)))
a then contains
[0, 0, 1, 1, 2, 2, 3, 3, 4, 4]
a = [0,1,2,3]
list(reduce(lambda x,y: x + y, zip(a,a))) #=> [0,0,1,1,2,2,3,3]