A rotation of a number n is constructed by shifting digits from one end of the number to the other. For example, 1234 rotated once to the right is 4123. If you continue rotating this number to the right, you get 3412, 2341, and finally 1234 again.
Note that zeros are preserved when rotating. So 250 rotated once is 25, and rotated twice is 502.
With this in mind, write the function isRotation(x, y)
which takes two non-negative integers x
and y
, and returns True
if x is a rotation of y or y is a rotation of x, and False
otherwise.
Here is my code so far:
def counter(n):
count = 0
while n > 0:
count = 1
n //= 10
return count
def isRotation(x, y):
if counter(x) == 0:
if y == 0:
return True
return False
if x == y:
return True
c = counter(x)
for n in range(counter(x)):
if counter(x) != c:
rightest = x // 10 ** 0 % 10
fm = (rightest * 10 ** (counter(x)))
v2 = fm (x//10)
x = v2
if v2 == y:
return True
if x < 100:
rightest = x // 10 ** 0 % 10
fm = (rightest * 10 ** (counter(x)))
v1 = fm (x//10)
x = v1
if v1 == y:
return True
rightest = x // 10 ** 0 % 10
fm = (rightest * 10 ** (counter(x)-1))
v = fm (x//10)
x = v
if v == y:
return True
return False
# isRotation(6616, 66160) returns False instead of True
CodePudding user response:
There seems to be a lot of complexity in your solution, consider this:
import math
def is_rotation(x, y):
t, f = x, 10 ** math.floor(math.log10(x)) if x else 0
while True:
if t == y:
return True
t = t // 10 t % 10 * f
if t == x:
return False
print(is_rotation(1234, 4123))
print(is_rotation(1234, 2341))
print(is_rotation(1234, 1234))
print(is_rotation(1234, 4321))
print(is_rotation(1234, 12345))
print(is_rotation(1234, 0))
print(is_rotation(0, 1234))
Result:
True
True
True
False
False
False
False
CodePudding user response:
You did not explicitly ask a question, but because I'm not a bot, I can make a reasonable inference from your comment at the end of your code (# isRotation(6616, 66160) returns False instead of True
that you are implicitly asking what the problem is with your code.
StackOverflow article "How do I write a good answer?" prescribes to "Make sure your answer provides that – or at least a viable alternative." I don't know what the problem is with your code; therefore, I provide a viable alternative
below:
def Rotations(a):
a_str = str(a)
L = len(a_str)
my_list = [a]
for i in range(L):
a_str = a_str[-1] a_str[0:-1]
my_list.append(int(a_str))
return my_list
def isRotation(x, y):
return (x in Rotations(y)) or (y in Rotations(x))