Getting a random choice from an array - python-3.x

I tried using the random.choice command and it seems to not work.
The Wolf has already been assigned to mob
class Wolf(Character):
def __init__(self):
super().__init__(name="wolf",hp=7,atk=6,df=4,inventory={},spells=
{"bite": randint(3,6)},exp=8)
c = random.choice(mob.spells)
spower = mob.spells[c]
ad = mob.atk / hero.df
damage = ad * spower
damage = int(round(damage))

random.choice wont work because you are passing a dictionary and it expects something that can be indexed using integer indices. Choosing randomly from a dictionary could work if the keys are integers.
d = {'a': 10, 'b': 20}
random.choice(d)
The above code will fail, but this will work:
d = {1: 10, 0: 20}
random.choice(d)
Its not magic, it works because the code in random.choice chooses a random integer between 0 and len(obj) and return the object at that index. The code below will never work:
d = {-1: 10, 2: 20}
random.choice(d)
And this will work sometimes:
d = {'a': 10, 0: 20}
random.choice(d)
It doesnt make any sense to find a random index in a dictionary.
For getting a random key in a dictionary do this:
d = {'a': 10, -1: 20, 90: -90}
random_key = random.choice(list(d))
In your case, the code will be:
c = random.choice(list(mob.spells))

Related

How to retrieve the target value key for a target value that is contained within a dictionary of lists of values without using a for loop?

I have the following dictionary. Each key contains a list of unique values:
d = {1:[10,11,12],2:[13,14],3:[15,16,17,18],4:[19],5:[20]}
I want to return the key for specified target value as per the example below (this does return the desired result).
keys = list(d.keys())
values_lst = list(d.values())
target_value = 20
for i,values in enumerate(values_lst):
if target_value in values:
index = i
keys[index]
5
However, is there a way to achieve this result without deploying the for loop (at least explicitly). The solution that I have does not feel particularly pythonic.
Thanks!
There always must be a loop somewhere, but you can do it with an one-liner:
d = {1: [10, 11, 12], 2: [13, 14], 3: [15, 16, 17, 18], 4: [19], 5: [20]}
target_value = 20
key = next(k for k, v in d.items() if target_value in v)
print(key)
Prints:
5
A more Pythonic solution, but still with an explicit for:
index = -1
for key, values in d.items():
if target_value in values:
index = key
break
print(d[index])
This may be more readable than a one-liner (as in the other answer), but YMMV.

How to find highest number from the vector provided?

Say, a dictionary is provided with certain values.
How to find the highest number ?
Input
d1 = {1: 1, 2: 6, 3: 7, 4: 1, 5: 3}
vector = 5
d1 = {1: 1, 2: 6, 3: 7, 4: 1, 5: 3}
vector = 5
l1 = list(td.values())
Based on vector value, it should print output.
vector is 5, so sum of the dict-values to form vector is 3,1,1
Corresponding keys are 5,4,1
so, the output should be 541 but slight change here.
Since value '1' is associated with multiple keys, it should pick up highest key,
so, output should be 544 instead of 541 (For above input, to brief about combinations without considering '1+1+1+1+1' to '44444')
Another example
d1 = {1: 1, 2: 6, 3: 7, 4: 1, 5: 3}
vector = 7
Possible combinations:
3 # --> Key of 7
21 # --> Key of 6 & 1 (6+1 = 7)
24 # --> Key of 6 & 1 (6+1 = 7)
12 # --> Key of 1 & 6 (1+6 = 7)
42 # --> Key of 1 & 6 (1+6 = 7)
Output : 42 (Highest number)
Another
d1 = {1:9,2:4,3:2,4:2,5:6,6:3,7:2,8:2,9:1}
vector = 5
here, it would be 1+2+2 (988).
But, '1' can also be added 5 times to form vector 5,
which would be '99999'
Since #Patrick Artner requested for minimal reproducible example, posting this though doesn't work as expected.
from itertools import combinations
def find_sum_with_index(l1, vector):
index_vals = [iv for iv in enumerate(l1) if iv[1] < target]
for r in range(1, len(index_vals) + 1):
for perm in combinations(index_vals, r):
if sum([p[1] for p in perm]) == target:
yield perm
d1 = {1: 1, 2: 6, 3: 7, 4: 1, 5: 3}
vector=5
l1=list(d1.values())
for match in find_sum_with_index(l1, vector):
print(dict(match))
Is there any specific algorithm to be chosen for these kind of stuffs ?
Similar to the other answer but allowing repeatedly using the same keys to get the max number of keys which values sum up to vector:
d1 = {1: 1, 2: 6, 3: 7, 4: 1, 5: 3}
vector = 7
#create a dict that contains value -> max-key for that value
d2 = {}
for k,v in d1.items():
d2[v] = max(d2.get(v,-1), k)
def mod_powerset(iterable,l):
# uses combinations_with_replacement to allow multiple usages of one value
from itertools import chain, combinations_with_replacement
s = list(set(iterable))
return chain.from_iterable(combinations_with_replacement(s, r) for r in range(l))
# create all combinations that sum to vector
p = [ s for s in mod_powerset(d1.values(),vector//min(d1.values())+1) if sum(s) == vector]
print(p)
# sort combinations by length then value descending and take the max one
mp = max( (sorted(y, reverse=True) for y in p), key=lambda x: (len(x),x))
# get the correct keys to be used from d2 dict
rv = [d2[num] for num in mp]
# sort by values, biggest first
rv.sort(reverse=True)
# solution
print(''.join(map(str,rv)))
Original powerset - see itertools-recipes.
There are some steps involved, see documentation in comments in code:
d1 = {1: 1, 2: 6, 3: 7, 4: 1, 5: 3}
vector = 7
# create a dict that contains value -> sorted key-list, used to get final keys
from collections import defaultdict
d2 = defaultdict(list)
for k,v in d1.items():
d2[v].append(k)
for k,v in d2.items():
d2[k] = sorted(v, reverse=True)
from itertools import chain, combinations
def powerset(iterable):
"see itertools: powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
# create all combinations that sum to vector
p = [ s for s in powerset(d1.values()) if sum(s) == vector]
# sort combinations by length then value descending and take the max one
mp = max( (sorted(y, reverse=True) for y in p), key=lambda x: (len(x),x))
# get the correct keys to be used from d2 dict
rv = []
for num in mp:
rv.append(d2[num][0])
# remove used key from list
d2[num][:] = d2[num][1:]
# sort by values, biggest first
rv.sort(reverse=True)
# solution
print(''.join(map(str,rv)))
For powerset - see itertools-recipes.

Get value that from another defaultdict and update the original dict

Basically, I am trying to extract the values from one dictionary and update the value in another dictionary. I have four lists as follows:
a = [1,1,2,3,4,5]
b = [0,3,0,5,6,0]
c = [2,3,4,5,6,5]
d = [20,30,40,50,60,70]
So I use a defaultdict to store key,value pairs for a,b like:
one = defaultdict(list)
for k, v in zip(a, b):
one[k].append(v)
two = defaultdict(list)
for k, v in zip(c, d):
two[k].append(v)
Essentially, b is linked to c so I am trying to extract the values in the two dictionary and then update
the values in the one dictionary
So in the end one would look like {1: 30, 3: 50, 4: 60}
This is my code:
three = defaultdict(list)
for k, v in one.items():
if v in two.keys():
newvalue = two[v].values()
three[k].append(newvalue)
But I am now getting an error at line if v in two.keys(): as unhashable type: 'list'. I'm so lost, all
I want to do is use the values from one dictionary and then use those values to find the keys (which are the values
from the other table) and then get those corressponding values.
You are creating a dictionary of list in the beginning:
one = defaultdict(list)
for k, v in zip(a, b):
one[k].append(v)
[output] : defaultdict(list, {1: [0, 3], 2: [0], 3: [5], 4: [6], 5: [0]})
two = defaultdict(list)
for k, v in zip(c, d):
two[k].append(v)
[output] : defaultdict(list, {2: [20], 3: [30], 4: [40], 5: [50, 70], 6: [60]})
Therefore when calling k,v in one.items(), you are getting a key and a list.
Simply switch to iterate through the list , and you should be good to go
three = defaultdict(list)
for k, v in one.items():
for value in v:
if value in two.keys():
newvalue = two[value]
three[k].append(newvalue)
However I'm getting this output :
defaultdict(list, {1: [[30]], 3: [[50, 70]], 4: [[60]]})
Which sounds reasonable to me, but it is not your expected one, can you please explain ?
Let's try know with dic comprehension
output = { k : two[v_2] for k,v in one.items() for v_2 in v}
[output] : {1: [30], 2: [], 3: [50, 70], 4: [60], 5: []}
Request to sum :
Of course, multiple ways of doing it , the quickest is again with dict_comprehension and sum
output_sum = {k: sum(v) for k,v in output.items()}

Fast bit string generation given indices

Here a is a list, for example [34, 52, 57].
The function takes in this list and creates a bit string of length 64, where every index is a 0 except at the given indices.
So it would look like [0,0,....1,...1,..1,..0,0,0] where only at indices [34, 52, 57] we have ones.
def bit_string_gen(a):
bit_string = []
for key, value in enumerate(range(64)):
if key in a:
bit_string.append(1)
else:
bit_string.append(0)
return bit_string
Is there a better way to do this, maybe using lambda or map or itertools instead of enumerate.
The problem with your approach is that you:
use an if statement for every bit; and
use the in test which can be rather expensive.
A beter method can be:
def bit_string_gen(a):
bit_string = [0]*64
for value in a:
bit_string[value] = 1
return bit_string
So here you iterate only over the values of a, and you set these bits to 1.
Nevertheless it is a bit weird to encode this with a list of ints. A more compact way to do this is to encode this binary on an integer. For instance by using:
def bit_string_gen(a):
bit_string = 0
for value in a:
bit_string |= 1 << value
return bit_string
So in the last case if you set the bits like in your sample input, you obtain:
>>> bin(bit_string_gen([34, 52, 57]))
'0b1000010000000000000000010000000000000000000000000000000000'
>>> hex(bit_string_gen([34, 52, 57]))
'0x210000400000000'
If you're looking for a solution using map/lambda, here's a one-liner:
map(lambda x: 1 if x in [34, 52, 57] else 0, range(0, 64))

Counter class extension

I am having a problem finding an elegant way to create a Counter() class that can:
Feed in arbitrary number of keys and return a nested dictionary based on this list of keys.
Increment for this nested dictionary is arbitrary as well.
For example:
counter = Counter()
for line in fin:
if a:
counter.incr(key1, 1)
else:
counter.incr(key2, key3, 2)
print counter
Ideally I am hoping to get the result looks like: {key1 : 20, {key2 : {key3 : 40}}}. But I am stuck in creating this arbitrary nested dictionary from list of keys. Any help is appreciated.
you can subclass dict and create your own nested structure.
here's my attempt at writing such class :
class Counter(dict):
def incr(self, *args):
if len(args) < 2:
raise TypeError, "incr() takes at least 2 arguments (%d given)" %len(args)
curr = self
keys, count = args[:-1], args[-1]
for depth, key in enumerate(keys, 1):
if depth == len(keys):
curr[key] = curr.setdefault(key, 0) + count
else:
curr = curr.setdefault(key, {})
counter = Counter()
counter.incr('key1', 1)
counter.incr('key2', 'key3', 2)
counter.incr('key1', 7)
print counter #{'key2': {'key3': 2}, 'key1': 8}
There are two possibilities.
First, you can always fake the nested-keys thing by using a flat Counter with a "key path" made of tuples:
counter = Counter()
for line in fin:
if a:
counter.incr((key1,), 1)
else:
counter.incr((key2, key3), 2)
But then you'll need to write a str-replacement—or, better, a wrapper class that implements __str__. And while you're at it, you can easily write an incr wrapper that lets you use exactly the API you wanted:
def incr(self, *args):
super().incr(args[:-1], args[-1])
Alternatively, you can build your own Counter-like class on top of a nested dict. The code for Counter is written in pure Python, and the source is pretty simple and readable.
From, your code, it looks like you don't have any need to access things like counter[key2][key3] anywhere, which means the first is probably going to be simpler and more appropriate.
The only type of value that can exist in a Counter object is an int, you will not be able to represent a nested dictionary with a Counter.
Here is one way to do this with a normal dictionary (counter = {}). First, to update increment the value for a single key:
counter[key1] = counter.setdefault(key1, 0) + 1
Or for an arbitrary list of keys to create the nested structure:
tmp = counter
for key in key_list[:-1]:
tmp = tmp.setdefault(key, {})
tmp[key_list[-1]] = tmp.setdefault(key_list[-1], 0) + 1
I would probably turn this into the following function:
def incr(counter, val, *keys):
tmp = counter
for key in keys[:-1]:
tmp = tmp.setdefault(key, {})
tmp[keys[-1]] = tmp.setdefault(keys[-1], 0) + val
Example:
>>> counter = {}
>>> incr(counter, 1, 'a')
>>> counter
{'a': 1}
>>> incr(counter, 2, 'a')
>>> counter
{'a': 3}
>>> incr(counter, 2, 'b', 'c', 'd')
>>> counter
{'a': 3, 'b': {'c': {'d': 2}}}
>>> incr(counter, 3, 'b', 'c', 'd')
>>> counter
{'a': 3, 'b': {'c': {'d': 5}}}

Resources