美文网首页
553. Optimal Division

553. Optimal Division

作者: 腹黑君 | 来源:发表于2017-09-23 20:47 被阅读0次

    Given a list of positive integers, the adjacent integers will perform the float division. For example, [2,3,4] -> 2 / 3 / 4.

    However, you can add any number of parenthesis at any position to change the priority of operations. You should find out how to add parenthesis to get the maximum result, and return the corresponding expression in string format. Your expression should NOT contain redundant parenthesis.

    Output: "1000/(100/10/2)"
    Explanation:
    1000/(100/10/2) = 1000/((100/10)/2) = 200
    However, the bold parenthesis in "1000/((100/10)/2)" are redundant, 
    since they don't influence the operation priority. So you should return "1000/(100/10/2)". 
    
    Other cases:
    1000/(100/10)/2 = 50
    1000/(100/(10/2)) = 50
    1000/100/10/2 = 0.5
    1000/100/(10/2) = 2```
    这题的意思就是在之间都是除法的情况下,通过括号取得这个序列的最大值
    只有一种情况,只有X0/(X1/X2/X3...)才是最大
    即
    ```class Solution(object):
        def optimalDivision(self, nums):
            """
            :type nums: List[int]
            :rtype: str
            """
            num = map(str,nums)
            if len(nums) <= 2:
                return '/'.join(num)
            else:
                return '{}/({})'.format(num[0],'/'.join(num[1:])) ```
    注意两个用法,第一个是join函数
    ```join():    连接字符串数组。将字符串、元组、列表中的元素以指定的字符(分隔符)连接生成一个新的字符串
    #对序列进行操作(分别使用' '与':'作为分隔符)
      
    >>> seq1 = ['hello','good','boy','doiido']
    >>> print ' '.join(seq1)
    hello good boy doiido
    >>> print ':'.join(seq1)
    hello:good:boy:doiido
      
      
    #对字符串进行操作
      
    >>> seq2 = "hello good boy doiido"
    >>> print ':'.join(seq2)
    h:e:l:l:o: :g:o:o:d: :b:o:y: :d:o:i:i:d:o
      
      
    #对元组进行操作
      
    >>> seq3 = ('hello','good','boy','doiido')
    >>> print ':'.join(seq3)
    hello:good:boy:doiido
      
      
    #对字典进行操作
      
    >>> seq4 = {'hello':1,'good':2,'boy':3,'doiido':4}
    >>> print ':'.join(seq4)
    boy:good:doiido:hello
      
      
    #合并目录
      
    >>> import os
    >>> os.path.join('/hello/','good/boy/','doiido')
    '/hello/good/boy/doiido'```
    
    
    一个是format格式化:
    
    ```>>>"{} {}".format("hello", "world")    # 不设置指定位置,按默认顺序
    'hello world'
     
    >>> "{0} {1}".format("hello", "world")  # 设置指定位置
    'hello world'
     
    >>> "{1} {0} {1}".format("hello", "world")  # 设置指定位置
    'world hello world'
    print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com"))
     
    # 通过字典设置参数
    site = {"name": "菜鸟教程", "url": "www.runoob.com"}
    print("网站名:{name}, 地址 {url}".format(**site))
     
    # 通过列表索引设置参数
    my_list = ['菜鸟教程', 'www.runoob.com']
    print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是可选的
    
    转义{}
    print ("{} 对应的位置是 {{0}}".format("runoob"))
    

    相关文章

      网友评论

          本文标题:553. Optimal Division

          本文链接:https://www.haomeiwen.com/subject/otchextx.html