Home > Mobile >  How to separate numbers within the same string, using the character as a separator, and printing the
How to separate numbers within the same string, using the character as a separator, and printing the

Time:10-10

How to separate numbers within the same string, using the character as a separator, and printing them at the end

The solution should be: 2, 4, 5, 8, 5, 2, 7, 2.5, 54, 1, 99, 2, 4, 24, 31

class Solution:
    data = [2, 4, 5, 'red', 8, 5, 'green', 2, '7', 2.5, 'purple54', '1car99',
            '2 air 4', 'a24car31']

CodePudding user response:

So based on your question I am assuming that you want to take a list of objects, and return all number values that are contained within each individual object in the list.

Let's start by obtaining all numbers within just one object.

For example with,

word = '1car99'

We are looking to obtain a list of result = [1, 99]

The approach we will take is by starting with a string, currentValue = '' and iterating over the length of our word continuing to check if our currentValue word[i] is a valid number. If at any moment it is no longer a number, we will add currentValue to result, reset currentValue = '' and continue looking for numbers in the remaining length of the object. Once we have finished iterating over the object, we will add any final valid currentValue to our list as well.

We will need to setup a couple functions for this solution,

Function to check if the value is a valid number or not

def isNumber(self, value):
    try:
        float(value)
        return True
    except:
        return False

Function to add num to our list of nums

def addValueToList(self, num, lst):
    # Check to see if the value should be added as a float or int
    if float(num) == int(float(num)):
        lst.append(int(num))
    else:
        lst.append(float(num))

Now we can use our aforementioned algorithm and these two functions together to obtain our result for one string object.

Function to return all numbers inside of string value

def getNumbersFromString(self, string):
    result = []
    currentNum = ''
    # Loop through all characters in string of data
    for i in range(len(string)):
        # We check if our currentNum is still a number after adding next character
        if not self.isNumber(currentNum   string[i]):
            if (currentNum != ''):
                self.addValueToList(currentNum, result)
            currentNum = ''
        # Else we add the character to currentNum
        else:
            currentNum  = string[i]
    # Our string have been iterated over, check if remaining currentNum is not ''
    if currentNum != '':
        self.addValueToList(currentNum, result)
    return result

Finally, we just need to iterate over all objects in our list of data, call the getNumbersFromString() method for each of them, and add the results to our numbers list.

Function to return all numbers inside a list of data

def getAllNumbersInsideList(self, dataList):
    numbers = []
    # Loop through all dataValues in data set
    for dataValue in dataList:
        # Add number results for dataValue to our numbers list
        numbers  = self.getNumbersFromString(str(dataValue))
    return numbers

Lastly, let's create a function to obtain our results and print them out to the console.

Function to get numbers and print them out based on self.data

def printOutNumbers(self):
    print(self.getAllNumbersInsideList(self.data))

CodePudding user response:

Using generator function with regex we have the following.

Code

def get_numbers(data):
    for value in data:
        if isinstance(value, int) or isinstance(value, float):
            yield value                       # current value is a number, so yield it
        elif (p:=re.findall(r"\d ", value)):  # regex to get numbers from string
            for s in p:                       # iteratively yield each number from string
                yield int(s)

Usage

print(list(get_numbers(data)))
>>> [2, 4, 5, 8, 5, 2, 7, 2.5, 54, 1, 99, 2, 4, 24, 31]
  • Related