How could the script be modified to get the minimum value of pow(), which is 0?
p = {'a': pow(x,y) for x in range(3) for y in range(3)}
a = p['a']
print(a)
TY
How could the script be modified to get the minimum value of pow(), which is 0?
p = {'a': pow(x,y) for x in range(3) for y in range(3)}
a = p['a']
print(a)
TY
Instead of using a dictionary where you keep overwriting the a
entry, use a set that stores all the unique values. Then call min
to get the minimum value in the set.
min({pow(x,y) for x in range(3) for y in range(3)})
The set doesn’t really add anything here, as you make at least as many comparisons during set creation as you save by reducing the number of items to compare at the end. The simplest approach seems to me just to use a generator expression:
a = min(pow(x,y) for x in range(3) for y in range(3))
The speed doesn’t seem to be a factor unless you have many more than 9 values to compute and compare, but it seems cleaner not to create a set or dict when it doesn’t buy you anything.
I was so focused on removing the dict key that I didn’t think about removing the unnecessary structure entirely .
@effigies @facelessuser Thanks…
One more dumb question: How would you only print the true value?
Ideal output:
C = dict(A = min({pow(x,y) for x in range(3) for y in range(3)}), B= max({pow(x,y) for x in range(3) for y in range(3)}))
for x in range(C['A'],C['B']):
if x == 2:
print('True')
# break
else:
print('False')
I don’t really understand. Do you mean just:
for x in range(C['A'],C['B']):
if x == 2:
print('True')
Or do you want to print True
if it’s in the range, but print False
if it’s not?
What’s the actual goal of what you’re doing? It’s hard to determine from the snippets you’re asking about. From what I’m seeing, I would probably go with something like the following:
vals = [pow(x, y) for x in range(3) for y in range(3)]
mn, mx = min(vals), max(vals)
two_in_range = mn <= 2 < mx
print(two_in_range) # If you want to print "True" or "False"
I would create the list because you need to iterate over it twice to get both the min and max. (You could also sort and take the first and last values.) And then instead of looping, you can just do a comparison so see if 2 is between the minimum and maximum. Now you have a boolean value, and you can do anything you like with it, such as put it in an if
statement or a call to print()
.
Now if this is an exercise and you’re trying to do it with a for
loop, you could do:
for x in range(mn, mx):
if x == 2:
print('True')
else:
print('False')
I personally find very little need for the for/else
construct, so I would not write this code normally, but it is worth knowing about this as you will occasionally run across it.