2015-02-06 48 views
-1

我的初始代码是Python 2.7.8中的一个基本计算器,但是现在我已经决定了我想包含一个函数,用户可以输入多个值。在Python中查找用户输入的重复值

一旦输入了这个函数,函数就可以运行用户刚刚输入的值存储到一个变量(函数参数)中,然后获知它们是否输入了重复值。现在,这些值在逗号分隔并插入进入一个列表并且函数运行。

我已经创建了一个函数,该函数已经将变量等同于用户键入算法时发生的'AlgorithmListEntry'的用户输入。

def findDuplicates(AlgorithmListEntry): 
       for i in len(range(AlgorithmListEntry)): 
        for j in len(1,range(AlgorithmListEntry)): 
         if AlgorithmListEntry[i]==AlgorithmListEntry[j]: 
          return True 
       return False 

凡函数查找参数以及范围,但是这并没有因为另一个错误的工作

for i in len(range(AlgorithmListEntry)): 
TypeError: range() integer end argument expected, got list. 

我现在收到错误

for i in len(AlgorithmListEntry):TypeError: 'int' object is not iterable 

为了便于查看我只插入了与我的问题相关的部分代码

i = True #starts outer while loop 
j = True #inner scientific calculations loop 

def findDuplicates(AlgorithmListEntry): 
      for i in len(AlgorithmListEntry): 
       for j in len(1(AlgorithmListEntry)): 
        if AlgorithmListEntry[i]==AlgorithmListEntry[j]: 
         return True 
      return False 


while i==True: 
    UserInput=raw_input('Please enter the action you want to do: add/sub or Type algorithm for something special: ') 
    scienceCalc=('Or type other to see scientific calculations') 

    if UserInput=='algorithm': 
     listEntry=raw_input('Please enter numbers to go in a list:').split(",") 
     AlgorithmListEntry = list(listEntry) 
     print AlgorithmListEntry 
     print "The program will now try to find duplicate values within the values given" 

     findDuplicates(AlgorithmListEntry) 
    #i = False 

问题

  1. 为什么我收到这两种错误的?

  2. 怎样才能在我的程序中成功实现这个功能?这样用户可以收到关于他们输入的值是否包含重复值的反馈?

+2

Doh,你真的需要清理你的代码,关于PEP8,希望很多人都愿意通读。严重的是,在你的缩进上工作,并且在'AlgorithmListEntry = list(listEntry)'中绑定列表的名字是可怕的:-)。 – 2015-02-06 20:40:50

回答

1

你做len(range(foo))代替range(len(foo))

range看起来是这样的:

range(end)    --> [0, 1, 2, ..., end-1] 
range(start, end)  --> [start, start+1, ..., end-1] 
range(start, end, step) --> [start, start+step, start+step*2, ..., end-1] 

len给出了一个序列的长度,所以len([1,2,3,4,5])5

len(range([1,2,3]))中断,因为range不能接受列表作为参数。

len([1,2,3])中断,因为它返回列表的长度作为整数,这是不可迭代的。这使得您的线路是这样的:

for i in 3: # TypeError! 

相反,你想使一个范围内尽可能多的数字,因为在AlgorithmListEntry元素。

for i in range(len(AlgorithListEntry)): 
    # do stuff 
+0

非常感谢你的工作和解决我的两个问题! – surjudpphu 2015-02-06 20:42:48