Compare values stored in variables, then print the variable name [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have tried to use the max code but it printed out the largest number not the variable name.
a=3
b=4
c=7
d=6
e=8
max(a,b,c,d,e)
this is the code I've tried but it printed 8 instead of e.
forgot to add that my values for a b c etc came from a loop so im not suppose to know their values myself...

You need to use a dictionary or a named tuple to do something like that.
>>> my_list = {'a': 1, 'b': 2, 'c': 3}
>>> max(my_list, key=my_list.get)
'c'
Let me know if there are any other methods.

Try this
dct={'a':3 ,'b':4 ,'c':7 ,'d':6 ,'e':8}
for i, j in dct.iteritems():
if j == max(dct.values()):
print i

From this question, there seems to be a way to retrieve the name of your variable (see caveat below before using):
a = 3
b = 4
c = 7
d = 6
e = 8
m = max(a, b, c, d, e)
for k, v in list(locals().items()):
if v is m:
v_as_str = k
break
v_as_str
output:
'e'
Caveat:
This may work if you can be sure that there are no other (unrelated) variables with the same value as the max of a to e
somewhere in your code, and appearing earlier in the locals.
Thanks to #D.Everhard & #asongtoruin in the comments

Related

New to programming, help in sum of matrix using for loop [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Anyone pls help me in program to find out sum of elements in matrix using for loop.
This is my code.
a = [[1,2,3],[1,2,3],[1,2,3]]
total = 0
sha = np.shape(a)
for i in range(sha[0]):
for j in range(sha[1]):
total= total+a[i,j]
return total
Simply use sum
a = [[1,2,3],[1,2,3],[1,2,3]]
sum([sum(i) for i in a])
As it is nested list (list inside a list) you can refer to the following
a=[[1,2],[2,3],[4,5]]
total=0
for i in a:
total+=sum(i)
print(total)
a = [[1,2,3],[1,2,3],[1,2,3]]
Sum = 0
sha = np.shape(a)
for r in range(len(sha)):
for c in range(len(sha)):
sum = sum + a[r][c]
print(Sum)
Sum is looped and calculated for r->row and c-> column

Tuple into list to find max value and if there is a duplicate [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I am creating a function that takes any quantity of numbers, and tell you what is the max value or if there is a tie for largest. I am wondering what I could do to simplify what I have.
def max_num(*args):
nums = []
nums_1 = []
nums.append(args)
i = 0
while i < len(nums[0]):
nums_1.append(nums[0][i])
i += 1
c = max(nums_1)
nums_1.remove(c)
if c in nums_1:
print("It's a tie!")
else:
print(c)
max_num(-10, 0, 10, 10)
So when I initially make a list with the arguments given, it gives me a tuple inside the list. This is why I create a new list to dissect the tuple into separate values. I have the feeling that wasn't necessary, and that there is a much simpler way to do this. Any advice would be great.
Just get the max, and count how many times it appears in your data:
def max_num(*args):
maxi = max(args)
if args.count(maxi) == 1:
print(maxi)
else:
print('Tie')
max_num(2, 5, 1)
#5
max_num(2, 5, 1, 5)
#Tie

Python numeric values for letters in string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I am having trouble solving the following question,
Q: Given a string find out the total sum of all the numbers.
Values are as A-1, B-10, C-100, D-1000, E-10000.
Ex. DDBC. Answer is 1000+1000+10+100 = 2110.
There are lots of ways to go about this.
Here's one idea:
Make a lookup that maps letters to the their values. Something like:
import string
lookup = {s: 10**i for i,s in enumerate(string.ascii_uppercase)}
Lookup will be a dictionary like:
{
'A': 1,
'B': 10,
'C': 100,
'D': 1000,
'E': 10000,
'F': 100000,
...
}
With that you can use a comprehension and take the sum:
>> s = "DDBC"
>> sum(lookup[l] for l in s)
2110
This, of course, assumes your string is all uppercase, like the example you posted.
just deduce the power of 10 by the position of the letter:
s = "DDBC"
result = sum(10**(ord(c)-ord('A')) for c in s)
result: 2110
You can filter out lowercase letters & other chars easily, but that complexifies a little bit:
result = sum(10**(ord(c.upper())-ord('A')) for c in s if c.isalpha())
Try searching the string, and every instance of that letter occurring causes you to add to total.
For instance:
total = 0
input_string = input()
for i in len(input_string):
if input_string[i] == "A":
total += 1
and then you can repeat that for the other instances of the other characters.
Hope I helped!

The digits of a number in ascending order. (comparing) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
cc = input('Input the number: ')
b = str(cc)
c = []
for digit in b:
c.append (int(digit))
csort = c.sort(key=int)
c == csort #??
I need to say True or False if the number is in ascending order or not.
My code do not print True or False, why?
You should not use key=int in c.sort(key=int) as c is already a list of ints due to you creating it via c.append(int(digit)).
However the key issue is that c.sort() is in-place and as such returns None, instead use sorted which returns a sorted list:
csort = sorted(c)
And then you can print the boolean result of the comparsion via:
print c == csort

Python: How to print position and value of list element? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a list which includes infinite an unknown number of elements (I don't have control on the length of the list or the type of values)
a = [x, y, z ...]
where x = 1, y = 9, z = 'Hello' ...
And I would like to loop over list "a" and print all the elements' names and values.
I hope if I can implement something like that:
for i in a:
print i $i
I would like to have output as:
x 1
y 9
z Hello
from itertools import cycle # an infinite repeating set
my_infinite = cycle(["a","b","c"])
a=1,b=4,c=99
for val in my_infinite:
print val, globals()[val]
maybe ... its aweful and hackey but it might work
Something like this:
import string
for a, b in zip(string.ascii_lowercase, xrange(1, 27)):
print a, b
You should use a dictionary:
a = {'x': 1, 'y': 2}
for i in a:
print i, a[i]

Categories