【每日一题20220420】字串计数

:mage:‍ 给定一个字符串,请编写一个函数,依次先后统计大写字母、小写字母、数字和特殊字符的个数。

【示例】
输入:*'&ABCDabcde12345
输出:[4,5,5,3]
解释:大写字母有4个(ABCD),小写字母有5个(abcde),数字有5个(12345),特殊字符有3个(*'&)

题目难度:简单
题目来源:CodeWars-Simple string characters

def solution(s: str)-> list:
    # your code here

assert solution("*'&ABCDabcde12345") == [4,5,5,3]
assert solution("bgA5<1d-tOwUZTS8yQ") == [7,6,3,2]
assert solution("@mw>0=QD-iAx!rp9TaG?o&M%l$34L.nbft") == [7,13,4,10]
    def solution(s: str)-> list:
        res = [0, 0, 0, 0]
        for c in s:
            if c.isupper():
                res[0]+=1
            elif c.islower():
                res[1] += 1
            elif c.isdigit():
                res[2] += 1
            else:
                res[3] += 1
        return res
1 个赞
import string
def solution(s: str)-> list:
    up, low, num, cha = 0, 0, 0, 0
    for i in s:
        if i in string.ascii_uppercase:
            up +=1
        elif i in string.ascii_lowercase:
            low +=1
        elif i in string.digits:
            num +=1
        elif i in string.punctuation:  #如果 空格 换行\t \n等不算的话,如果算的话就用else
            cha +=1
    return [up, low, num, cha]

assert solution("*'&ABCDabcde12345") == [4,5,5,3]
assert solution("bgA5<1d-tOwUZTS8yQ") == [7,6,3,2]
assert solution("@mw>0=QD-iAx!rp9TaG?o&M%l$34L.nbft") == [7,13,4,10]

\W 匹配非字母数字及下划线 你得把下划线的情况考虑进去

def solution(s: str)-> list:
a,b,c,d = 0,0,0,0
for i in s:
if i.isupper():
a += 1
elif i.islower():
b += 1
elif i.isdigit():
c += 1
else:
d += 1
return [a,b,c,d]

已更改,非常感谢 :hugs: :innocent:

    import re
    u, l, n, c = len(re.findall('[A-Z]',s)),\
                 len(re.findall('[a-z]',s)),\
                 len(re.findall('\d',s)),\
                 len(re.findall('[^a-zA-Z0-9]',s))
    return [u, l, n, c]
    return [len(re.findall(item, s)) for item in ('[A-Z]', '[a-z]', '\d', '[^a-zA-Z0-9]')]
class TestEveryDay():
    def solution(self, s:str) -> list:
        u, l, n, o = 0, 0, 0, 0
        try:
            for i in s:
                # 大写
                if i.isupper():
                    u += 1
                # 小写
                elif i.islower():
                    l += 1
                # 数字
                elif i.isdigit():
                    n += 1
                # 特殊字符
                else:
                    o += 1
        except Exception as e:
            print(e)
        return [u, l, n, o]

    def test_str(self):
        assert self.solution("*'&ABCDabcde12345") == [4, 5, 5, 3]
        assert self.solution("bgA5<1d-tOwUZTS8yQ") == [7, 6, 3, 2]
        assert self.solution("@mw>0=QD-iAx!rp9TaG?o&M%l$34L.nbft") == [7, 13, 4, 10]

def solution(s: str) → list:
# your code here
adlist = [0, 0, 0, 0]
for i in s:
if i.isupper():
adlist[0] += 1
elif i.islower():
adlist[1] += 1
elif i.isdigit():
adlist[2] += 1
else:
adlist[3] += 1
return adlist

assert solution("*’&ABCDabcde12345") == [4,5,5,3]
assert solution(“bgA5<1d-tOwUZTS8yQ”) == [7,6,3,2]
assert solution("@mw>0=QD-iAx!rp9TaG?o&M%l$34L.nbft") == [7,13,4,10]


def solution(s: str)-> list:
        result = [0]*4
        for i in s:
            if i.isupper():
                result[0]+=1
            elif i.islower():
                result[1] += 1
            elif i.isdecimal():
                result[2] += 1
            else:
                result[3] += 1
        return result
方法2
import re

def solution(s: str)-> list:
    patts= [re.compile(r'[A-Z]*'),re.compile(r'[a-z]*'),re.compile(r'\d*',re.ASCII),re.compile(r'[^A-Za-z0-9]*']
    return [len(''.join(i.findall(s))) for i in patts]
        

本人

/**
* 函数
**/
public class Kata {

    public static int[] Solve(String word) {
      //enjoy coding 
      int[] list = new int[4];
        for (int i = 0; i < word.length(); i++) {
            int w = word.charAt(i) - 0;
            if (w > 64 && w < 91) {
                list[0] += 1;
            } else if (w > 96 && w < 123) {
                list[1] += 1;
            } else if (w > 47 && w < 58) {
                list[2] += 1;
            }else {
                list[3]+=1;
            }

        }
        return list;
    }
}
/**
* 测试
**/

import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertArrayEquals;

public class SolutionTest {
    @Test
    public void testSomething() {
        assertArrayEquals(new int[]{1,18,3,2}, Kata.Solve("Codewars@codewars123.com"));
        assertArrayEquals(new int[]{8,6,3,2}, Kata.Solve("CbgA5<1d-tOwUZTS8yQ"));
        assertArrayEquals(new int[]{9,9,6,9}, Kata.Solve("P*K4%>mQUDaG$h=cx2?.Czt7!Zn16p@5H"));
        assertArrayEquals(new int[]{15,8,6,9}, Kata.Solve("RYT'>s&gO-.CM9AKeH?,5317tWGpS<*x2ukXZD"));
        assertArrayEquals(new int[]{10,7,3,6}, Kata.Solve("$Cnl)Sr<7bBW-&qLHI!mY41ODe"));
        assertArrayEquals(new int[]{7,13,4,10}, Kata.Solve("@mw>0=QD-iAx!rp9TaG?o&M%l$34L.nbft"));
    }
}
1 个赞

更多解法:

  • 第一种:
public class Kata {

    public static int[] Solve(String word) {
        int upperCase = (int) word.chars().filter(value -> Character.isUpperCase(value)).count();
        int lowerCase = (int) word.chars().filter(value -> Character.isLowerCase(value)).count();
        int number = (int) word.chars().filter(value -> Character.isDigit(value)).count();
        int specialChar = word.length() - (upperCase + lowerCase + number);
        return new int[]{upperCase, lowerCase, number, specialChar};
    }
}
  • 第二种
interface Kata {
  static int[] Solve(String word) {
    return new int[] {
        word.replaceAll("[^A-Z]", "").length(),
        word.replaceAll("[^a-z]", "").length(),
        word.replaceAll("[^0-9]", "").length(),
        word.replaceAll("[\\w]", "").length()
    };
  }
}
  • 第三种
public class Kata {
  public static int[] Solve(String word) {
    return new int[]{
            word.replaceAll("[^\\p{Upper}]", "").length(),
            word.replaceAll("[^\\p{Lower}]", "").length(),
            word.replaceAll("[^\\p{Digit}]", "").length(),
            word.replaceAll("[\\p{Alnum}]", "").length(),
    };
  }
}
  • 第四种
import java.util.Arrays;

public class Kata {

    public static int[] Solve(String word) {
        int[] sol = new int[4];
        String[] arr = word.split("");
        for (String x : arr){
            if (x.matches(".*[A-Z].*")){
                sol[0]++;
            }
            else if(x.matches(".*[a-z].*")){
                sol[1]++;
            }
            else if(x.matches(".*[0-9].*")){
                sol[2]++;
                }
            else if(x.matches(".*[!-@].*")){
                sol[3]++;
            }
        }
        return sol;
    }
}
def solution(s: str) -> list:
    lists = [0, 0, 0, 0]
    for i in s:
        if ord(i) in range(65, 91):
            lists[0] += 1
        elif ord(i) in range(97, 123):
            lists[1] += 1
        elif ord(i) in range(48, 58):
            lists[2] += 1
        else:
            lists[3] += 1
    return lists
def solution(s: str)-> list:
    patterns= [re.compile('[A-Z]'), re.compile('[a-z]'), re.compile(r'\d', re.ASCII), re.compile('[^a-zA-Z0-9_]')]
    return [len(i.findall(s)) for i in patterns]
1 个赞
def solution(s: str) -> list:
    upper = 0
    lower = 0
    digiter = 0
    other = 0
    for i in s:
        if i.isupper():
            upper += 1
        elif i.islower():
            lower += 1
        elif i.isdigit():
            digiter += 1
        else:
            other += 1
    return [upper, lower, digiter, other]


assert solution("*'&ABCDabcde12345") == [4, 5, 5, 3]
assert solution("bgA5<1d-tOwUZTS8yQ") == [7, 6, 3, 2]
assert solution("@mw>0=QD-iAx!rp9TaG?o&M%l$34L.nbft") == [7, 13, 4, 10]
def solution(s: str)-> list:
    # your code here
    a, b, c, d =0, 0, 0, 0
    for i in s:
        if i.isupper():
            a +=1
        elif i.islower():
            b +=1
        elif i.isdigit():
            c +=1
        else:
            d +=1
    return [a, b, c, d]    

assert solution("*'&ABCDabcde12345") == [4,5,5,3]
assert solution("bgA5<1d-tOwUZTS8yQ") == [7,6,3,2]
assert solution("@mw>0=QD-iAx!rp9TaG?o&M%l$34L.nbft") == [7,13,4,10]
def solution(s: str)-> list:
    a,b,c,d = 0,0,0,0
    for i in s:
        if i.isupper():
            a += 1
        elif i.islower():
            b += 1
        elif i.isdigit():
            c += 1
        else:
            d += 1
    li = [a, b, c, d]
    return li

assert solution("*'&ABCDabcde12345") == [4,5,5,3]
assert solution("bgA5<1d-tOwUZTS8yQ") == [7,6,3,2]
assert solution("@mw>0=QD-iAx!rp9TaG?o&M%l$34L.nbft") == [7,13,4,10]
def solution(s: str) -> list:
    upper_list = []
    lower_list = []
    int_list = []
    other_list = []
    for i in s:
        if i.isupper():
            upper_list.append(i)
        elif i.islower():
            lower_list.append(i)
        elif i.isdigit():
            int_list.append(i)
        else:
            other_list.append(i)
    return [len(upper_list), len(lower_list), len(int_list), len(other_list)]


assert solution("*'&ABCDabcde12345") == [4, 5, 5, 3]
assert solution("bgA5<1d-tOwUZTS8yQ") == [7, 6, 3, 2]
assert solution("@mw>0=QD-iAx!rp9TaG?o&M%l$34L.nbft") == [7, 13, 4, 10]