-1

I have tried and google the solution for below mentioned code but unfortunately I didn't get anything regarding this.

Don't change the logic pleaseConvert it into list comprehension. I Have tried list comprehension. I'm bit far from getting output.But due to syntactical error, I'm getting failure. Thanks in advance.

data = "abc@#123"
t=tuple(data)
flag=0
print(t)
alpha=[]
digit=[]
spl_chr=[]
for i in t:
    if i.isnumeric():
        i=int(i)
        if type(i)==type(flag):
            digit.append(i)
    elif type(i)==type(data) and i.isalpha():
        alpha.append(i)
    else:
        spl_chr.append(i)
dic={}
dic["alphabets"]=alpha
dic["digits"]=digit
dic["symbols"]=spl_chr
print(dic)

1 Answers1

0

My take:

import re
import itertools


def char_class(c):
    if re.match(r'[a-z]', c, re.IGNORECASE):
        return c, 'alphabets'
    elif re.match(r'[0-9]', c):
        return c, 'digits'
    else:
        return c, 'symbols'

data = "abc@#123"

dic = {
   k: list(e[0] for e in v) for k, v in itertools.groupby((char_class(c) for c in data), key=lambda e: e[1])
}

print(dic)

Of course, if your assignment prevents you from using SPL modules, you can always use language built-ins only:

dic = {
    'alphabets': list(
        set(c for c in data if c.isalpha())
    ),
    'digits': list(
        set(c for c in data if c.isnumeric())
    ),
    'symbols': list(
        set(c for c in data if not (c.isalpha() or c.isnumeric()))
    ),
}
slouchart
  • 72
  • 6
  • Hi thanks @slouchart but as i have already mentioned don't change logic .... because it is restricted for me to use inbuilt function. – Shivani Goyal Dec 29 '22 at 19:34
  • Well, `itertools` and `re` are modules from the Standard Library hence almots "built-in" but whatever. With only builtins. Let's go. – slouchart Dec 30 '22 at 10:17
  • Hi @slouchart one of youtuber helped me to solve this issue. PF link of the video https://youtu.be/X7lhmt46Vu8 – Shivani Goyal Jan 04 '23 at 17:12