Whats the better way of doing this - python

I've only been coding in python for a month and I tried making something that searches for duplicates in a user made list...
List = []
count = 0
Val = 0
usernum = int(input("How many numbers are in your list: "))
for i in range(0, usernum):
values = int(input("What is the number on the list: "))
List.append(values)
for i in range(0, len(List)):
if List[i] == List[Val]:
print("There are duplicates")
count += 1
if count == len(List):
Val += 1
continue

Your code does not work for various reasons:
You're missing your main variable: the list. Add it like this
List = []
BTW: List with a capital L is not an awesome choice, but still a much better choice than list with a lower case L which could cause all kinds of problems.
With that added, enter 1 and 1 and you'll find that even for a single number it will print "There are duplicates". That is because you compare
List[i] == List[Val]
where both i and Val are 0. The item compares against itself. That must no be the case.
All the if-logic is weird. It's unclear to me what you wanted to achieve. A common approach would be a nested loop in order to compare each item against each following item. Note how j starts at i+1
for i in range(0, len(List)):
for j in range(i+1, len(List)):
if List[i] == List[j]:
print("There are duplicates")
An even better approach would be to not implement that yourself at all but use other techniques like
if len(set(List)) < len(List):
print("There are duplicates")
where set() will give you the unique numbers only. If numbers have been removed because they were not unique (aka. duplicate), that set will have less numbers than the list.

Related

Compare two lists from user input, item by item, and return the larger value between the lists

I have no prior knowledge of python or programming and learning as I go. Below is what I am working with and I'm just unsure how to go about this.
Write a function that takes two lists of floats as input. The lists must be the same length, and you can rely on users always properly giving lists of identical length. The function should determine the number of items in the first list that are greater than the corresponding item in the second list (i.e. is the item at position 5 in the first list bigger than the item at position 5 in the second list). The number of values in the first list that are bigger should be returned as an integer (so if no items in the first list are bigger than the corresponding items in the second list return 0, if 5 items are bigger than their corresponding item in the second list, return 5).
list_1 = []
list_2 = []
# asking number of elements to put in list_1
num_1 = int(input("Enter number of elements in list_1: "))
# iterating till num to append elements in list
for i in range(1, num_1 + 1):
ele = int(input("Enter elements: "))
list_1.append(ele)
# print maximum element
print("Largest element is:", max(list_1))
# asking number of elements to put in list_2
num_2 = int(input("Enter number of elements in list_2: "))
# iterating till num to append elements in list
for i in range(1, num_2 + 1):
ele = int(input("Enter elements: "))
list_2.append(ele)
# print maximum element
print("Largest element is:", max(list_2))
I figure this is completely wrong as I am suppose to compare each item by item in the two lists. Any tips? Thank you!
Your code correctly gets the user input, so I will talk about the task after that.
(But you could write for i in range(1, num_1 + 1): instead of for i in range(num_1):. In a python idiom, people would even write for _ in range(num_1):.)
The idea is to make a variable counter that is initially 0. Looping over the two lists simultaneously, we increment the counter when the condition (an element in list_1 is greater than the corresponding element in list_2).
The most basic code that implement this would be the following:
list_1 = [1,3,5,7]
list_2 = [6,4,2,0]
count = 0
for i in range(len(list_1)):
if list_1[i] > list_2[i]:
count += 1 # add one
print(count) # 2
This might be what the assignment is looking for. But people usually dislike to see the pattern for ... in range(len(...)):. A slightly more pythonic way is to use zip:
count = 0
for x, y in zip(list_1, list_2):
if x > y:
count += 1
Better yet, in my opinion, is to use list (or generator) comprehension instead of the explicit for:
count = sum(x > y for x, y in zip(list_1, list_2))

Equality of dynamically changing variable counts

I am a newbie in Python so I made a code that checks multiple long numbers and finds which digits of the numbers are common.
print('Counts:')
count = int(input())
print('Lengths:')
nm_len = int(input())
numbers = []
print('Input numbers:')
numbers = [int(input()) for i in range(count)]
print('Numbers stored!')
print(numbers)
for n in range(count):
globals()['nm%s' % n] = [int(d) for d in str(numbers[n])]
print('Same numbers:')
for j in range(nm_len):
if nm0[j] == nm1[j] == nm2[j]:
print(j+1,'. number is same')
The program just works fine except for the last part which is the equality checking. With this code, it works if you input 3 for the counts at the first step but does not work if you but more or less than 3.
Is there any way to make the last if equality work dynamically? I mean if I input for example 5 for the counts at the first step, then the program will know it and makes the if just like nm0[j] == nm1[j] == nm2[j] == nm3[j] == nm4[j].
Perhaps you can start here. It seems silly to ask for the number of digits, especially if you don't enforce that. We just keep everything as a list. Very general purpose.
count = int(input("How many: "))
print('Input numbers:')
numbers = [int(input()) for _ in range(count)]
print('Numbers stored!')
print(numbers)
nm = [str(n) for n in numbers]
print('Same digits:')
for i,x in enumerate(zip(*nm)):
if all(x[0] == j for j in x):
print('Digit', i+1,'is the same')
Don't use globals(). Except in very specialized circumstances, it is never the right answer.

I can't get count to work in my Python code

I'm trying to create a code that will print every number in a range set by the user, and then identify how many numbers in that range are odd numbers and how many are even.
I've tried a few different formats, but I'm very much a beginner and can't seem to nail down where I'm going wrong. I'm trying to keep the code as simple as possible.
for i in range(x,y+1):
print(i)
range = (x,y+1)
count_odd = 0
count_even = 0
for n in range:
if n%2==0:
count_even = count_even+1
else:
count_odd = count_odd+1
print("Number of even numbers :",count_even)
print("Number of odd numbers :",count_odd)
Currently when I run this, even numbers always comes to 0 and odd to 2.
On line 4 you have:
range = (x,y+1)
This is the tuple (x, y+1) not the range between them. So when you loop through it you are only looping through those two numbers. I assume in your case they are both odd. I would recommend removing that line and starting your second for loop like this:
for n in range(x, y + 1):
range is a builtin function, which returns an iterable from [start, end). You likely want something like:
count_odd = 0
count_even = 0
for n in range(x,y+1):
if n % 2 == 0:
count_even = count_even + 1
else:
count_odd = count_odd + 1
print("Number of even numbers :", count_even)
print("Number of odd numbers :", count_odd)
There's no point for a loop. If your range consists of even elements, then half of values is even and half is odd. If it consists og odd elements and starts from odd value then half+1 is odd and half-1 is even. It starts with even value then it's opposite.

optimize the python for loop

I have a problem where I need to find the number of unique numbers. No digits in the number would have been repeated.
Number like 11, 1123, 41124 wont qualify.
Numbers should be 1234, 12, or 987 like these would qualify.
My code works fine. But when the range go beyond 10^6. The code takes lots of time to execute. How can I optimize the same.
for i in xrange(10000000):# pow(10, n) 10, 100, 10000,...
j = str(i)
if j != j[::-1]:
for k in range(len(j)):
if j.count(j[k]) == 1:
if k == len(j)-1:
count += 1
#print j
else:
break
if len(j) == 1:
count += 1
print count
You are going about this in possibly the least efficient way possible, and the longer the number gets, the longer it will take. Your code should look more like this:
for i in xrange(10000000):
j = str(i)
if len(set(j)) == len(j):
count += 1
# print j
print count
This takes advantage of the fact a Python set can't contain duplicates (duplicates are eliminated). So, if the length of the set of the digits in the number is the same as the length of the original string of digits, we know no digits were duplicated.
You can even write it in one line:
print sum(len(set(j)) == len(j) for j in (str(i) for i in xrange(10000000)))
Others have suggested collections.counter which is useful if you want to know which digits were duplicated.

How can I continue the for loop of the outer side?

def countPrimes(self, n):
if n <= 1:
return 0
if n == 2:
return 1
count = 0
counted = [2, ]
for num in xrange(3, n+1, 2):
for c in counted:
if num % c == 0:
continue
count += 1
counted.append(num)
return count
I am writing a code for the solution of primes counting problems. I used counted as an array storing for primes that have been examined and use them for the examination for the next prime. I tried using continue to drop out the inner for loop then count += 1 and counted.append(num) would not be executed once the num is found not a valid prime. However, I met implementing problem here, as the continue statement would take me to another c instead of another num.
If I understand your question correctly, you want to know how to break the inner c loop, avoid the other code, and continue with another num. Like the other answers, you want to make use of break with some smart booleans. Here's what the loop might look like:
for num in xrange(3, n+1, 2):
next_num = False
for c in counted:
if num % c == 0:
next_num = True
break
if next_num:
continue
count += 1
counted.append(num)
This way, if you encounter a num that is divisible by c, you break out of the inner c loop, avoid adding num to the counted list.
It doesn't make a ton of sense to accumulate a count and a list of primes as you go. Introduces the chance for a mismatch somewhere. I've massaged the code a bit, with some more descriptive variable names. It's amazing how clear names can really make the algorithm make more sense. (At least for me it does)
def primesUpTo(n):
primes = []
if n > 1:
primes.append(2)
for candidate in xrange(3, n+1, 2):
for prime in primes:
candidate_is_prime = candidate % prime
if not candidate_is_prime: # We're done with this inner loop
break
if candidate_is_prime:
primes.append(candidate)
return primes
print len(primesUpTo(100))
Try using break instead of continue. See the documentation here. Basically break takes you out of the smallest enclosing loop, spitting you back into your higher-level loop for its next iteration. On the other hand, continue just jumps you on to the next iteration of the smallest closing loop, so you wouldn't go out to the higher-level loop first.

Categories