Say that you have a file and the list of numbers like

10 20 16 17 82 93 87

How could I add/subtract/ or multiply these individually?

Dani AI

Generated

As pointed out, the first step is getting the file data into a numeric sequence. Using the sample line from ("10 20 16 17 82 93 87") as input, common tasks are best handled with Python built-ins and small helpers so parsing and arithmetic are separated. The snippets below operate on any iterable of numbers (so they can be reused regardless of how the file is read).

def total(nums):
    return sum(nums)

def product(nums):
    import math
    try:
        return math.prod(nums)   # Python 3.8+
    except AttributeError:
        from functools import reduce
        import operator
        return reduce(operator.mul, nums, 1)

def running_sum(nums):
    from itertools import accumulate
    return list(accumulate(nums))

def running_product(nums):
    from itertools import accumulate
    import operator
    return list(accumulate(nums, operator.mul))

def successive_subtract(nums):
    it = iter(nums)
    try:
        result = next(it)
    except StopIteration:
        return 0
    for n in it:
        result -= n
    return result

Notes and practical tips: use streaming accumulation (update an accumulator inside a loop) for very large files to avoid building a full list. For decimal or financial data prefer Decimal or Fraction to avoid float rounding. If input may contain commas, stray text or locale formatting, sanitize tokens and handle conversion errors with try/except. For older Python versions use the reduce fallback shown; for large numeric arrays consider NumPy for elementwise operations. 's edit hint suggests clarifying the exact input format up front — that determines whether simple whitespace split is enough or more robust parsing is needed.

Recommended Answers

All 2 Replies

for line in open("file"):
    nums = [int(x) for x in line.split()]
    # nums now contains a list of integer
    # you can add/subtract/multiply by traversing the list

edit: new topic

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.