Discovering all numbers within a specific range that conclude with particular digits

Seeking out numbers within a specific range that end with particular digits is my current quest.

Consider the following examples:

  1. Identify all numbers up to 15 that end with 5. The expected result would be 2, as both 5 and 15 fulfill this criteria.

  2. Determine all numbers up to 125 that conclude with 12. This should also yield a result of 2, since both 12 and 112 meet this requirement.

I initially utilized brute-force code:

def findnumber(n, m):
    count = 0
    for i in range(1, m+1):
        if i%10**len(str(n)) == n:
            count += 1
    return count

print(findnumber(5,15))

However, I am now looking to enhance the efficiency of this code.

  • The valid values are: 1 <= n, m <= 10**9

Answer №1

Modified based on the recommendation of Tomerikoo, utilizing the floordiv operator:

def find_number(n, m):
    base = 10 ** len(str(n))
    count = m // base
    if m % base >= n:
        count += 1
    return count

Answer №2

Presented below is a highly effective general algorithm: with a simple assumption that, for instance, n equals 7 and m equals 39, we only need to validate the numbers 7, 17, 27 as they are incremented by 10 which is calculated through offset = 10 ** (total digits of n).

The following code demonstrates this:

def calculate(n, m):
    count   = 0
    number  = n
    length  = len(str(n))
    offset  = 10 ** length
    
    while number <= m:
        count += 1
        number += offset

    return count


>>> calculate(7, 16)
1
>>> calculate(7, 19)
2
>>> calculate(7, 29)
3
>>> calculate(7, 129)
13
>>> calculate(7, 1129)
113

This method proves to be efficient in terms of minimizing computational operations.

Answer №3

def find_number(n, m):
  counter = 0
  
  #Finding the first number that ends with n allows for faster computation
  found_the_first = False
  first_num = 1
  while(not found_the_first):
      if first_num % 10 == n:
          found_the_first = True
          break
      first_num += 1
  
  for j in range(first_num, m + 1, 10):
        counter += 1
  return counter

print(find_number(2, 20))

Answer №4

This method is much simpler and does not require any iteration.

In a sequence of 10 numbers, there will be one number that ends with the letter m, as shown here:

1 2 3 4 5 6 7 8 9 10 | 11 12 13 14 15

def find_specific_number(n, m):
    n_digits = 0
    n_copy = n
    while n_copy != 0:
        n_digits += 1
        n_copy //= 10

    digits = 10 ** n_digits
    count = m // digits
    if m % digits >= n:
        count += 1
    return count

print(find_specific_number(5, 15))
print(find_specific_number(35, 1400))

# Output:
# 2
# 14

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a Name Error while trying to call a function that was previously defined within the code

I am currently working on a Rectangle Class in Python to determine if two rectangles are touching at the corners. This task is part of the final exercise in chapter 16 of openbookproject's course. Link to source The issue I am facing revolves around ...

TCP allows files to be transferred without needing to close the socket

I developed a basic TCP server - client file sharing system, but I've encountered an issue where it only works when the socket is closed in the client script. I attempted to eliminate the 's.close' command from the client python script, whi ...

Guide on adding a text in the middle of two other texts when displaying in Python

Could you please show me how to add " 's " to the first string when printing out two strings called word1 and word2? word1 = "king" word2 = "cross" print(word1+word2) ...

Set up the RefControl extension with the help of the Selenium WebDriver

I have successfully implemented this addon with selenium. However, I am unsure how to adjust the settings of addons in selenium. from selenium.webdriver.firefox.firefox_profile import FirefoxProfile from selenium.webdriver.firefox import webdriver profil ...

Quick explanation of the concept of "matrix multiplication" using Python

I am looking to redefine matrix multiplication by having each constant represented as another array, which will be convolved together instead of simply multiplying. Check out the image I created to better illustrate my concept: https://i.stack.imgur.com/p ...

Python is used to fine-tune OpenAI models and the result is a null model

I am attempting to fine-tune an OpenAI GPT-3 model using Python with the following code snippet: #upload training data upload_response = openai.File.create( file=open(file_name, "rb"), purpose='fine-tune' ) file_id = upload_respons ...

What is the best approach for handling a column in Pandas that is labeled as "NA"?

I am encountering a problem with the data in my spreadsheet that shows as "NA" when I try to read it using Pandas. The issue is that "NA" (which stands for "North America" in my case) gets converted to "NaN" during the process. Does this mean that "NA" is ...

A simple lambda expression shortcut technique for sorting elements in Python

I have a functional code snippet but it's quite messy: a = 0 for k in keys: a = a + 1 if a == 1: k1 = k if a == 2: k2 = k if a == 3: k3 = k ...

How can I store a date from a calendar using tkcalendar in Python?

I'm looking to save the selected dates from a calendar to variables. I found this code, but I'm unsure of how to save the date. import tkinter as tk from tkinter import ttk from tkcalendar import Calendar def example1(): def print_sel(): ...

Transferring a list of decimal numbers from a Python server to another using Flask and the requests library

I am working on a project that involves periodically sending an Array of doubles from a Python service to another. Despite being a newcomer to Python, I have delved into topics like Flask and requests. Below is a basic code example that I put together jus ...

Launching a web service on my Google App Engine platform

We developed a basic application and successfully ran it locally using GoogleAppEngineLauncher (GAEL). After that, we deployed the application to our appid with GAEL again, and everything was working smoothly. Next, we created a web service. We tested it ...

Using Python 3.6.1 to display a string in a readable format with special characters included

Currently, I am working on a small Django 1.1 app and have encountered an issue related to Python while using commands to manage data retrieval and categorization flow. Additionally, I want to generate a summary using a third command. My development enviro ...

choose an array consisting of spark structures

I'm facing a challenging issue as part of a complex problem I'm working on. Specifically, I'm stuck at a certain point in the process. To simplify the problem, let's assume I have created a dataframe from JSON data. The raw data looks ...

What is the reason behind the success of list comprehension within this particular class for certain methods while failing for others?

As a research scientist, I am developing a custom Python 3.7 class named MyList(). This class is designed to provide additional methods for manipulating list objects without the need to create new objects. For instance, after initializing foo = MyList() wi ...

Transposing a vector using Numpy

Is there a way to transpose a vector using numpy? I've been attempting the following: import numpy as np center = np.array([1,2]) center_t = np.transpose(center) Despite my efforts, this method doesn't seem to be working. Are there any other wa ...

Error: Unable to convert empty string to hexadecimal integer value for int() function

When attempting to execute the script below, I keep running into this error. array.append([int(h[i:i + 2], 16) for i in (0, 2, 4)]) Can you help me spot where my code is going wrong? ...

Challenges encountered while executing a loop using Selenium in Python code

I need to scrape data from the following website . My task involves selecting "Rio de Janeiro" in the 'Estado' field. Entering an empty value in the 'Nome' field. Performing a search. Once the table results are displayed, cli ...

Automate the process of interacting with Instagram buttons by utilizing selenium

Recently started dabbling in Python and attempting to create an Instagram bot using selenium. I'm struggling to make the code progress past the login button and 'not now' button. from time import sleep from selenium import webdriver browse ...

accumulated total for the current month and year

I'm struggling to figure out how to calculate the cumulative total for month-to-date (MTD) and year-to-date (YTD). Can someone please assist me in obtaining this result? Any help would be greatly appreciated. ...

Newbie Python Programmer: How to Send Selenium WebElement Object to PHP

I am currently exploring the possibility of extracting data from a website and then passing it for use in PHP. After researching various methods, one suggestion that stood out to me was to serialize the Python data before transferring it. However, I seem ...