<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
python package to handle RPN calculation.
RPN: Reverse Polish Notation
"""

from __future__ import division, print_function
import decimal
import math

decimal.getcontext().prec = 20


class Rpn(object):
    """Class to handle RPN calculation.

    Parameters
    ----------
    istr : str
        String of rpn expression.
    delimiter : str
        Delimiter of *istr*.

    Examples
    --------
    >>> from rpn import Rpn
    >>> rpnstr = '10 1 2 + sin *'
    >>> rpnins = Rpn(rpnstr)
    >>> result = rpnins.solve()
    1.4112000805986722
    >>> # or:
    >>> result = Rpn.solve_rpn(rpnstr)
    """
    def __init__(self, istr, delimiter=None):
        self.opslist = istr.lower().replace('pi',str(math.pi)).split(delimiter)
        self.opslist.reverse()

        oprts = ['+', '-', '*', '/', 'sin', 'cos', 'tan', 'sqrt']
        opfun = [self.fadd, self.fsub, self.fmul, self.fdiv,
                 self.fsin, self.fcos, self.ftan, self.fsqrt]
        self.opdic = dict(zip(oprts, opfun))

    def fadd(self):
        a = float(self.tmpopslist.pop())
        b = float(self.tmpopslist.pop())
        return b + a

    def fsub(self):
        a = float(self.tmpopslist.pop())
        b = float(self.tmpopslist.pop())
        return b - a

    def fmul(self):
        a = float(self.tmpopslist.pop())
        b = float(self.tmpopslist.pop())
        return  b * a

    def fdiv(self):
        a = float(self.tmpopslist.pop())
        b = float(self.tmpopslist.pop())
        if a == 0:
            print("The dividend must not be zero.")
        return b / a

    def fsin(self):
        a = float(self.tmpopslist.pop())
        return math.sin(a)

    def fcos(self):
        a = float(self.tmpopslist.pop())
        return math.cos(a)

    def ftan(self):
        a = float(self.tmpopslist.pop())
        return math.tan(a)

    def fsqrt(self):
        a = float(self.tmpopslist.pop())
        if a < 0:
            print('Input of sqrt must be a positive number.')
        return math.sqrt(a)

    def __str__(self):
        return ' '.join(reversed(self.opslist))

    @classmethod
    def solve_rpn(cls, istr):
        """Solve rpn expression.

        USAGE: solve_rpn(rpnstr)
        
        Parameters
        ----------
        rpnstr : str
            String o rpn expression.

        Returns
        -------
        ret : float
            Calculated result.
        """
        return cls(istr).solve()

    def solve(self):
        """Solve rpn expression, return None if not valid."""
        popflag = True
        self.tmpopslist = []
        while len(self.opslist) > 1:
            while popflag:
                try:
                    op = self.opslist.pop()
                    self.tmpopslist.append(op)
                    try:
                        float(op)
                    except:
                        popflag = False
                except IndexError:
                    return None
            try:
                oprt = self.tmpopslist.pop()
                tmpr = self.opdic[oprt]()
            except (IndexError, ValueError, KeyError, ZeroDivisionError):
                return None
            self.opslist.append('{result:.20f}'.format(result = tmpr))

            popflag = True

        try:
            return float(self.opslist[0])
        except:
            return None
                

def solve_rpn(istr):
    """Solve rpn expression.

    USAGE: solve_rpn(rpnstr)
    <commit_msg>Update solve to handle operations w/o returns.<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
python package to handle RPN calculation.
RPN: Reverse Polish Notation
"""

from __future__ import division, print_function
import decimal
import math

decimal.getcontext().prec = 20


class Rpn(object):
    """Class to handle RPN calculation.

    Parameters
    ----------
    istr : str
        String of rpn expression.
    delimiter : str
        Delimiter of *istr*.

    Examples
    --------
    >>> from rpn import Rpn
    >>> rpnstr = '10 1 2 + sin *'
    >>> rpnins = Rpn(rpnstr)
    >>> result = rpnins.solve()
    1.4112000805986722
    >>> # or:
    >>> result = Rpn.solve_rpn(rpnstr)
    """
    def __init__(self, istr, delimiter=None):
        self.opslist = istr.lower().replace('pi',str(math.pi)).split(delimiter)
        self.opslist.reverse()

        oprts = ['+', '-', '*', '/', 'sin', 'cos', 'tan', 'sqrt',
                 'pop', 'swap']
        opfun = [self.fadd, self.fsub, self.fmul, self.fdiv,
                 self.fsin, self.fcos, self.ftan, self.fsqrt,
                 self.fpop, self.fswap,
        ]
        self.opdic = dict(zip(oprts, opfun))

    def fadd(self):
        a = float(self.tmpopslist.pop())
        b = float(self.tmpopslist.pop())
        return b + a

    def fsub(self):
        a = float(self.tmpopslist.pop())
        b = float(self.tmpopslist.pop())
        return b - a

    def fmul(self):
        a = float(self.tmpopslist.pop())
        b = float(self.tmpopslist.pop())
        return  b * a

    def fdiv(self):
        a = float(self.tmpopslist.pop())
        b = float(self.tmpopslist.pop())
        if a == 0:
            print("The dividend must not be zero.")
        return b / a

    def fsin(self):
        a = float(self.tmpopslist.pop())
        return math.sin(a)

    def fcos(self):
        a = float(self.tmpopslist.pop())
        return math.cos(a)

    def ftan(self):
        a = float(self.tmpopslist.pop())
        return math.tan(a)

    def fsqrt(self):
        a = float(self.tmpopslist.pop())
        if a < 0:
            print('Input of sqrt must be a positive number.')
        return math.sqrt(a)

    def fpop(self):
        self.tmpopslist.pop()
        return None

    def fswap(self):
        a = self.tmpopslist.pop()
        b = self.tmpopslist.pop()
        self.tmpopslist.append(a)
        self.tmpopslist.append(b)
        return None

    def __str__(self):
        return ' '.join(reversed(self.opslist))

    @classmethod
    def solve_rpn(cls, istr):
        """Solve rpn expression.

        USAGE: solve_rpn(rpnstr)
        
        Parameters
        ----------
        rpnstr : str
            String o rpn expression.

        Returns
        -------
        ret : float
            Calculated result.
        """
        return cls(istr).solve()

    def solve(self):
        """Solve rpn expression, return None if not valid."""
        popflag = True
        self.tmpopslist = []
        while True:
            while popflag:
                try:
                    op = self.opslist.pop()
                    self.tmpopslist.append(op)
                    try:
                        float(op)
                    except:
                        popflag = False
                except IndexError:
                    return None
            try:
                oprt = self.tmpopslist.pop()
                tmpr = self.opdic[oprt]()
            except (IndexError, ValueError, KeyError, ZeroDivisionError):
                return None
            if tmpr is not None:
                self.opslist.append('{result:.20f}'.format(result=tmpr))
            if len(self.tmpopslist) > 0 or len(self.opslist) > 1:
                popflag = True
            else:
                break

        try:
            return float(self.opslist[0])
        except:
            return None
                

def solve_rpn(istr):
    """Solve rpn expression.

    USAGE: solve_rpn(rpnstr)
    
{'fraction_non_alphanumeric': 0.1296074517631404, 'fraction_numerical': 0.008117099135063206, 'mean_word_length': 1.5495251017639078, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 42, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2676058', 'n_tokens_mistral': 2415, 'n_tokens_neox': 2297, 'n_words': 542}