简体   繁体   中英

how to check if two numbers in a list are the same in Python

I have a little problem with some coding. This is my code:

def sites(x):
    r = []
    sum = 0
    i = 0
    modulo = []
    som = 0
    j = 0
    while i < len(x):
        sum = int(float(x[i])) + (i + 1)
        r.append(sum)
        i = i + 1
    while j < len(x):
        som = r[j] % len(x)
        modulo.append(som)
        j = j + 1
    return modulo

If I for example fill in sites("321") this code will give me the list [1, 1, 1]. What I want to do is check if there are numbers in this list that are the same. I was thinking about something like:

if modulo[0] != modulo[1] != modulo[2]:
    print "valid"
else:
    print "invalid"

This only works when the input in sites is three digits long. I've been brainstorming on how to use a while loop that checks every digit.

All help is very welcome.

You can use a set to remove any dups and check the length after against the original list:

if len(set(modulo)) == len(modulo): # if lengths are  equal we have no duplicate nums
     print "valid"
else:
      print "Invalid"

If you just want to avoid adding dups keep a set of all nums seen and check before adding:

seen = set()
if num not in seen: add it

I would also avoid using sum as a variable name as it shadows the builtin python sum function.

You can also use enumerate , range and you don't need to declare variables in python:

def sites(x):
    r = []
    modulo = []
    ln = len(x)
    for i,ele in enumerate(x):
        sm = int(float(ele)) + (i + 1)
        r.append(sm)
    for j in range(ln):
        som = r[j] % ln
        modulo.append(som)
    return modulo

Or better again use list comprehensions :

def sites(x):
    ln = len(x)
    r = [int(float(ele)) + (i + 1) for i,ele in enumerate(x)]
    modulo = [r[j] % ln for j in range(ln)]
    return modulo

So I know you got your answer, but I just wanted to chime in and show a more optimized approach to your issue. This will allow you to not loop through the string more than once, and if it's invalid, you might not even stop early.

You can create a generator and loop through it adding to a seen list if the value is not already in the list:

gen = ((int(float(ele)) + (i + 1)) % len(x) for i,ele in enumerate(x))
seen = set() 
for i in gen:
    if i in seen:
        print 'invalid'
        break
    seen.add(i)
else:
    print 'valid'

This has the added benefit of not creating an additional 1-2 lists in memory which could be a problem if your initial string/list is very large.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM