Reputation: 214
Learning Python 3 self guided. In C, I solved this problem using arrays of integers and comparing the array index to hard coded numbers. I'm having some difficulty porting this to Python 3.
Problem: Given a long integer, match the first two digits to a another set of digits.
number = 123456789
set1 = [21, 22, 23]
set2 = [11, 12, 19]
Intended Output
>>> Number is of type set2.
or
>>> Number is not in set1 or set2.
What I have been attempting to do is separate the first two digits (12) from number, and then do a comparison to each value in set1, and then set2. I starting doing this by converting number to a string and trying to use the cmp() function.
Since I am using python 3, cmp() is not a built in function, and this is where I got stuck. I started looking at different ways of implementing cmp(), and then started down a rabbit role reading documentation and posts. Finally decided just to ask my specific question.
My non-working, not-completed implementation is below. Still need to implement the proper number comparison through each element in each list. I feel like converting to a string isn't necessary, but I'm not sure exactly how else to do it.
number = 123456789
set1 = [21, 22, 23]
set2 = [11, 12, 19]
numberString = str(number)
numberType = "".join([numberString[0] + numberString[1])
if(cmp(numberType, set1) == 0):
return 1
elif(cmp(numberType, set2) == 0):
return 2
else:
return 0
Upvotes: 1
Views: 188
Reputation: 16147
It's just easier to slice strings in Python. So you can convert to str, take the first two digits, then convert back to int. Then you can simply us in
to check if it's in a list you have.
If you need it as a function, just define it, pass in the variable, and return the print string instead of printing.
number = 123456789
set1 = [21, 22, 23]
set2 = [11, 12, 19]
x = int(str(number)[:2])
if x in set1:
print('Number is of type set1.')
elif x in set2:
print('Number is of type set2.')
else:
print('Number is not in set1 or set2')
...
Number is of type set2.
Upvotes: 1