无法实现内部"for"循环



Java Code:

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();
}
}

蟒蛇代码:

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中创建了等效/预期的代码(

试试下面的代码

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)

最新更新