Comparing Digits in an Integer in Python

Comparing digits in a list to an integer, then returning the digits

#Creating a list
my_numbers = []
r = range(5)
for i in r:
try:
my_numbers.append(int(input("Enter a number: ")))
except:
print( 'You must enter an integer' )
r.append(i)

#Finding sum
Total = sum(my_numbers)

#Finding the average
Average = Total/5
print ("The average is: ")
print (Average)
print ("The numbers greater than the average are: ")
print ([x for x in my_numbers if x>Average])

I'm sure that you would finally have succeeded in your code even if nobody hadn't answered.

My code is in fact to point out that you should foresee that entries could be non-integer and then to put instruction managing errors of entry.

The basic manner here is to use try except

Note the way I add i to r each time an error occurs in order to make up for the element of r that has been consumed.

how to compare two number to find number of corresponding different digits

I wasn't clear in the question that If you want to return total number of different digits or number of different digits per item in the list arr. So I am assuming that you want to return total number of different digits.

If you sum both the numbers(algebraic sum), then the sum of two corresponding digits is 1 if and only if the two digits are different and this fact can be used to count number of different digits as shown below

def count_different(arr, b):
diff_digits = 0
for i in arr:
diff_digits += str(int(i)+int(b)).count('1')
return diff_digits

in case you want to return number of different digits for each item in arr them append each count in the list and return a list.

def count_different(arr, b):
diff_digits = 0
l = []
for i in arr:
diff_digits += str(int(i)+int(b)).count('1')
l.append(diff_digits)
return l

Comparing numbers and dates in Python

The type of number is string but the type of day is int.
You need to change the type of one of this variables.
Replace number == day by int(number) == day or number == str(day)



Related Topics



Leave a reply



Submit