无法实现内部“for”循环

2024-09-25 00:31:30 发布

您现在位置:Python中文网/ 问答频道 /正文

Java代码:

public class PrintDuplicates {

    Scanner sc = new Scanner(System.in);
    String ch;

    public void getUserInput() {
        System.out.print("Enter the string or number: "+System.lineSeparator());
        ch = sc.next();
    }

    public void findDuplicates() {
        for(int x=0; x<ch.length(); x++) {
            for(int y=x+1; y<ch.length(); y++) {
                if(ch.charAt(x)==ch.charAt(y)) {
                    System.out.println("Duplicates: "+ch.charAt(x));
                }
            }
        }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        PrintDuplicates obj = new PrintDuplicates();
        obj.getUserInput();
        obj.findDuplicates();
    }

}

Python代码:

ch = None

def getUserInput():
    global ch
    ch = input("Enter the string OR number: ")

def findDuplicates():
    for x in ch:
        ###NEED HELP with the following part of Python code (next 3 lines)
        for ____ in ch:
            if(_____):
                print("Duplicate: %d" %x)
getUserInput()
findDuplicates()

问题陈述:基本上,我希望在字符串中找到重复项并将其打印在屏幕上 (注意:为了便于参考,我用java创建了等效/预期的代码)


Tags: the代码inobjforpublicchsystem
1条回答
网友
1楼 · 发布于 2024-09-25 00:31:30

请尝试下面的代码

ch = None

def getUserInput():
    global ch
    ch = input("Enter the string OR number: ")

def findDuplicates():
    for x in range(len(ch)):
        for y in range(x+1, len(ch)):
            if(ch[x]==ch[y]):
                print("Duplicate: %s" %ch[x])
getUserInput()
findDuplicates()

如果需要,可以避免多个for循环

def findDuplicates():
    for x in (i for i in set(s) if s.count(i)>1):
        print("Duplicate: %s" % x)

相关问题 更多 >