Rotated Digits in Python

Rotated Digits in Python

circular rotation of number in python
rotated digits geeksforgeeks
rotate digits of a number in c
rotated digits leetcode
string rotation in python
right rotation array in python
array rotation in python
how to rotate a list in python

I have came across to the following question, my solution passed the initial input, but failed in the following test case. I wonder what I am missing.

The question is described as follows

X is a good number if after rotating each digit individually by 180 degrees, we get a valid number that is different from X. Each digit must be rotated - we cannot choose to leave it alone.

A number is valid if each digit remains a digit after rotation. 0, 1, and 8 rotate to themselves; 2 and 5 rotate to each other; 6 and 9 rotate to each other, and the rest of the numbers do not rotate to any other number and become invalid.

Now given a positive number N, how many numbers X from 1 to N are good?

Example:

Input: 10

Output: 4

Explanation:

There are four good numbers in the range [1, 10] : 2, 5, 6, 9. Note that 1 and 10 are not good numbers, since they remain unchanged after rotating.

class Solution(object):
    def rotatedDigits(self, N):
        """
        :type N: int
        :rtype: int
        """
        rotatedDigits = [2,5,6,9]
        count = 0
        isValid = False
        for i in range(1,N+1):
                for b in str(i):
                    if int(b) in rotatedDigits:
                        isValid = True
                    else:
                        isValid = False
                        break
                if isValid:
                    count +=1
        return count

Input: 857

Output: 68

Expected: 247


Your logic is incomplete. You are checking for the presence of the digits that rotate, which is correct. But the problem statement also says:

"the rest of the numbers do not rotate to any other number and become invalid"

Thus if the number contains any of the numbers 3, 4, or 7 it is invalid.

Even if you were to add in that check, your isValid flag is in the wrong place. It should be reset inside the for loop (not set outside of it).

Here's a version of your function that will work:

def rotatedDigits(N):
    """
    :type N: int
    :rtype: int
    """
    rotatedDigits = {'2','5','6','9'}
    badNumbers = {'3','4','7'}
    count = 0
    for i in range(1,N+1):
        flag1 = False  # use this to check if the number contains a rotating digit
        flag2 = True  # use this to check if the number contains a bad digit
        for b in str(i):
            if b in rotatedDigits:
                flag1 = True
            elif b in badNumbers:
                flag2 = False
                break

        if flag1 and flag2:
            count +=1
    return count

print(rotatedDigits(857))
#247

I also made made rotatedDigits and badNumbers sets of strings instead of lists of ints. Set lookups are faster than lists, and also this avoids casting to string and back to int.


Update: A more pythonic version using set operations:

def rotatedDigits(N):
    """
    :type N: int
    :rtype: int
    """
    rotatedDigits = {'2','5','6','9'}
    badNumbers = {'3','4','7'}
    count = 0
    for i in range(1,N+1):
        digits = set(str(i))
        count += 1 if (digits & rotatedDigits) and not(digits & badNumbers) else 0
    return count

Here we create a set of the characters in the number (digits) and use the & operator between sets to get the intersection. We increment count if the intersection between digits and rotatedDigits is not empty and the intersection of digits and badNumbers is empty.

The above function can be further condensed using sum, map, and a generator expression:

def rotatedDigits(N):
    """
    :type N: int
    :rtype: int
    """
    rotatedDigits = {'2','5','6','9'}
    badNumbers = {'3','4','7'}
    count = sum(1 if (x & rotatedDigits) and not (x & badNumbers) else 0 
                for x in map(lambda i: set(str(i)), range(1, N+1)))
    return count

Rotated Digits, Given an integer n, the task is to generate all the left shift numbers possible. A left shift number is a number that is generated when all the digits� Each digit must be rotated - we cannot choose to leave it alone. A number is valid if each digit remains a digit after rotation. 0, 1, and 8 rotate to themselves; 2 and 5 rotate to each other; 6 and 9 rotate to each other, and the rest of the numbers do not rotate to any other number and become invalid.


I would take a different approach by first checking for any of the invalid characters. Then verify that it does contain at least one of the rotating characters.

rotating = {'2','5','6','9'}
invalid = {'3','4','7'}

def rotated(N):
    X=set(str(N))
    if any(digit in X for digit in invalid):
        return False
    if any(digit in X for digit in rotating):
        return True
    return False

def checkall(N):
    count=0
    for i in range(1,N+1):
        if rotated(i): 
            count += 1
    return count

print(checkall(857))

Generate all rotations of a number, String slicing in Python to rotate a string Left (Or anticlockwise) rotate the given string by d elements (where d <= n). Print all possible combinations of the string by replacing '$' with any other digit from the string � Split the given string into� Given a user input list and given the rotation number. Our task is to rotate the list from the given rotation number. Example Input A= [2, 4, 5, 12, 90] rotation number=3 Output [ 90,12,2, 4, 5] Method1. Here we traverse each element in the list and insert the element at required places in the second list. Example


Whit this check

if int(b) in rotatedDigits:
    isValid = True
else:
    isValid = False
    break

You have missed numbers with digits: 0, 1, and 8. In given example they represented numbers that stay the same but they are valid You must miss all numbers with digits 3, 4 or 7.

String slicing in Python to rotate a string, Code in Python to rotate digits of a number to the right. Download source code at: �Duration: 0:49 Posted: May 18, 2018 Original list : [1, 4, 6, 7, 2] List after left rotate by 3 : [7, 2, 1, 4, 6] List after right rotate by 3(back to original) : [1, 4, 6, 7, 2] Method #3 : Using collections.deque.rotate() The collections module has deque class which provides the rotate() , which is inbuilt function to allow rotation.


# using dictionary :

def rotatedDigits(N: int):
    count=0
    d={0:0,1:1,2:5,3:-1,4:-1,5:2,6:9,7:-1,8:8,9:6}
    for i in range(1,N+1):
        l=list(str(i))
        res=[]
        for j in l:
            if d[int(j)]!=-1:
                res.append(str(d[int(j)]))
            else:break
        if len(res)==len(l) and int(''.join(res))!=i:
            count+=1
    return count

【LeetCode】788. Rotated Digits 解题报告(Python)_负雪明烛-CSDN , Given a positive number N, find out how many numbers from 1 to N are good numbers. Rotated Digits, String Problem, Algorithm & Data Structure. The generative process used to generate the datasets is the following: Pick a sample from the MNIST digit recognition dataset; Create a rotated version of the sample. The digits were rotated by an angle generated randomly between -\pi and \pi radians.


number rotate digits right in python, X is a good number if after rotating EACH digit individually by 180 degrees, we get a valid number that is different from X. A number is valid if each digit. Python program to right rotate a list by n. Given a list, right rotate the list by n position. Input : n = 2 List_1 = [1, 2, 3, 4, 5, 6] Output : List_1 = [5, 6, 1, 2, 3, 4] We get output list after right rotating (clockwise) given list by 2.


Rotated Digits | String Problem, Python: Rotate Number. import math. def rotate(n):. digs = int(math.log10(n)). return (10 ** digs) * (n % 10) + n // 10. Comment on gist. Sign in to comment or sign� Detection of a rotated image is difficult. I have written the code about rotating an image. [code]import cv2 import numpy #loading the image into a numpy array img = cv.imread(&#039;&lt;image path&gt;&#039;) #rotating the image rotated_90_clockwise = numpy.rot90


LeetCode – Rotated Digits (Java), So, multiply 5 with 100 to get 500(2 zeroes because, there are 3 digits. If t This program will help you in understanding rotation of digit in given number. Python Program to Find Sum of Digits of a Number using Recursion. This program to find the sum of digits in python allows the user to enter any positive integer. Then it divides the given number into individual digits and adds those individual (Sum) digits by calling the function recursively. Please refer to Python Recursion for further reference.