Home > front end >  Can someone explain why isdigit() isn't working with this project and how can i make this happe
Can someone explain why isdigit() isn't working with this project and how can i make this happe

Time:12-06

I want to know if person got full point like 5/5 in all exams, i will append key to a list.

# dictionary could be larger
dicti = {'John': ['5/5', '50/50', '10/10', '10/10']}
liste = []
def f():
    for key, value in dicti.items():
        count = 0
        for i in value:
            if i.isdigit(): # kkk
                count  = 1
        if len(value) == count:
            liste.append(key)
    print(liste)
f()
# I realized in # kkk part doesn't see 5/5 as a digit.
# How can i make this happen?

CodePudding user response:

'5/5' is a string, and isdigit() method will only return True if all of characters are digits. It is not because of '/'. On the other hand, Python doesn't evaluate the content of the string. It is an object itself ! (I do not recommend to use eval to evaluate that string if that is what you intend to do)

Instead you can check that yourself by writing a small helper function which checks too see if he/she gets a complete score or not:

dicti = {
    'John': ['5/5', '50/50', '10/10', '10/10'],
    'test_person': ['5/5', '49/50']
}

def is_full(x):
    left, right = x.split('/')
    return left == right

lst = []
for k, v in dicti.items():
    if all(is_full(grade) for grade in v):
        lst.append(k)

print(lst)

output:

['John']

CodePudding user response:

You should write list elements in value of dictionary as integer numbers of string type. For example instead of writing '10/10' you should write '1'. so this would be work properly.

CodePudding user response:

Try this. Note following code adds the name into the list even if the student has gotten full marks once.

dicti = {'John': ['5/5', '50/50', '10/10', '10/10']}
fullMarks = ['5/5', '50/50', '10/10', '10/10'];
names = []; # an empty list to add names whose marks are full

def f():
    for keys,values in dicti.items():
        for value in values: # looping through the value list inside the list
            if(value in fullMarks): # if the full marks are in the list (even one time)
                names.append(keys); # adding the name into the empty list
                break; # don't loop further
f()
print(names);

CodePudding user response:

I think a quite elegant solution would imply the using of regular expressions:

import re

dicti = {'John': ['5/5', '50/50', '10/10', '10/10'], 'Paul': ['4/5', '50/50', '10/10', '10/10']}
def f():
    liste = [key for key, value in dicti.items() if all([re.match("(\d )/\\1", v) for v in value])]
    print(liste)
f()

OUTPUT

['John']

Basically, "(\d )/\\1" matches when the number before and after the slash are the same, i.e. full mark is achieved, however you want to express it.

  • Related