Summing Integers and Floating-Point Numbers from Tokens

How can we calculate the sum of integers and floating-point numbers from a series of tokens?

We will use a Python program that reads a series of tokens from standard input and computes the sum of integers, sum of floating-point numbers (excluding integers), and the total number of tokens.

Answer:

The Python program below demonstrates how to process tokens and calculate the sum of integers, sum of floating-point numbers, and the total number of tokens:

Python Program:

def process_tokens(tokens):
    int_sum = 0
    float_sum = 0.0
    total_tokens = 0
    
    for token in tokens:
        total_tokens += 1
        
        if token.isdigit():
            int_sum += int(token)
        else:
            try:
                float_sum += float(token)
            except ValueError:
                pass
    
    return int_sum, float_sum, total_tokens

input_tokens = input("Enter a series of tokens: ").split()
integer_sum, float_sum, total_token_count = process_tokens(input_tokens)

print("Sum of integers:", integer_sum)
print("Sum of floating-point numbers:", float_sum)
print("Total number of tokens:", total_token_count)
    

This program prompts the user to enter a series of tokens and then calculates the sum of integers, the sum of floating-point numbers (excluding integers), and the total number of tokens in the input.

← Keep your app running smoothly understanding the importance of maintenance in the software development life cycle Auditing as a desirable approach in assessing it services →