Python函数用于添加或减去数字的函数。

huangapple go评论84阅读模式
英文:

Python function to add or subtract digits of a number

问题

My problem is that I'm trying to write a function PlusMinus(num) which will read the integer being passed, and determine if it's possible to separate the digits of the integer with either a plus or minus sign to form an expression which evaluates to zero.

For example: if num is 35132 then it's possible to separate the digits the following way, 3 - 5 + 1 + 3 - 2, and this expression equals 0.

The function should return a string of the signs used, so for this example the program should return -++-. If it's not possible to get the digit expression to equal zero, it should return the string "not possible". If there are multiple ways to get the final expression to equal zero, it should return the one that contains more minus characters. For example: if num is 26712 the function should return -+-- and not +-+-.

Sample Test Cases:

Input: 199
Output: not possible

Input: 26712
Output: -+--

英文:

My problem is that I'm trying to write a function PlusMinus(num) which will read the integer being passed, and determine if it's possible to separate the digits of the integer with either a plus or minus sign to form an expression which evaluates to zero.

For example: if num is 35132 then it's possible to separate the digits the following way, 3 - 5 + 1 + 3 - 2, and this expression equals 0.

The function should return a string of the signs used, so for this example the program should return "-++-". If it's not possible to get the digit expression to equal zero, it should return the string "not possible". If there are multiple ways to get the final expression to equal zero, it should return the one that contains more minus characters. For example: if num is 26712 the function should return "-+--" and not "+-+-".

Sample Test Cases:

Input: 199
Output: not possible 

Input: 26712 
Output: -+--

My code:

num=int(input())
PlusMinus(num)
def PlusMinus(num):
    s=str(num)
    l=len(s)
    rs=''
    r=0
    if(l<2):
        print("not possible")
    else:
        for i in range(1,l):
            if i<2:
                r=int(s[0])-int(s[1])
                rs='-'
            else:
                if r<=0:
                    r=int(r)+int(s[i])
                    rs+='+'
                else:
                    r=int(r)-int(s[i])
                    rs+='-'
        if(r==0):
            print(rs)
        else:
            print("not possible")

答案1

得分: 2

这是一个有趣的问题。您的代码针对您在帖子中列出的测试用例有效,但在某些情况下逻辑会失效。例如,您的代码会尝试在当前总和大于0时添加减号,否则添加加号。这意味着如果我们尝试以下情况:

945

我们得到了正确的答案,然而如果我们尝试以下情况:

459
not possible

我们会得到一个错误的答案,因为明显地4 + 5 - 9 = 0,所以我们期望得到+-

我解决这个问题的方法是使用itertools.product生成所有可能的加法和减法组合,从---...开始,以+++...结束,并按顺序循环它们,如果找到解决方案则中断。这种蛮力解决方案也很简单,通过一些分析和启发式方法,我们可以消除一些解决方案,但它确实有效,并且将提供正确的答案。

代码:

import itertools

def PlusMinus(num):
    # 将我们的数字转换为字符串
    s = str(num)

    # 对于每种可能的操作组合:
    for op in itertools.product('-+', repeat=len(s)-1):
        # 如果应用后结果为0
        if apply_ops(s, op) == 0:
            # 返回操作作为字符串
            return ''.join(op)
    # 如果我们已经尝试了所有可能性,那么就不可能实现
    return 'not possible'

# 对字符串s应用一系列操作op
def apply_ops(s, op):
    # 将返回值设置为s的第一个数字
    rv = int(s[0])

    # 对于每个剩余的数字,根据操作进行增加或减少
    for i, n in enumerate(s[1:]):
        if op[i] == '+':
            rv += int(n)
        else:
            rv -= int(n)
    # 返回结果
    return rv

num = int(input())
print(PlusMinus(num))

测试:

945
--
459
+-
26712
-+--
199
not possible
英文:

This is a fun problem. Your code works for the test cases you've outlined in your post, but the logic falls down in some cases. For example, your code naively attempts to add a subtract sign if the current sum is greater than 0, and a plus sign if not. This means that if we try:

945
--

We get the correct answer, however if we try:

459
not possible

We get an incorrect answer, as clearly 4 + 5 - 9 = 0, so we expect to get +-.

My approach to the problem would be to use itertools.product to generate all possible combinations of plus and minus signs, starting with ---... and ending with +++..., and loop through them in order, breaking if we find a solution. This brute force solution is also naive, as with some analysis & heuristics, we could eliminate a fair few solutions, but it does work and will provide the correct answer.

Code:

import itertools

def PlusMinus(num):
    # make our num into a string
    s=str(num)
    
    # For each possible operations combination:
    for op in itertools.product('-+', repeat=len(s)-1):
        # If when applied, we make 0
        if apply_ops(s, op) == 0:
            # Return the operations as a string
            return ''.join(op)
    # If we've exhausted all possibilities, it's not possible
    return 'not possible'
    
# Apply a series of operations op to a string s
def apply_ops(s, op):
    # Set return val to the first digit of s
    rv = int(s[0])
    
    # For each remaining digit, either increment or decrement according to the
    # operation
    for i, n in enumerate(s[1:]):
        if op[i] == '+':
            rv += int(n)
        else:
            rv -= int(n)
    # Return result
    return rv
    
num=int(input())
print(PlusMinus(num))

Tests:

945
--
459
+-
26712
-+--
199
not possible

huangapple
  • 本文由 发表于 2020年1月3日 20:20:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/59578548.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定