Python之神秘库(二)

NOW

不良少年·回归

当不良少年,是男人唯一的勋章,这是我们的人生信仰。

有的人是因为看到了才相信,而有的人是因为相信了才看见。

★★★★★

PREMIUM

COLLECTION

Nov 24

唯一摩尔斯密码

国际摩尔斯密码定义一种标准编码方式,将每个字母对应于一个由一系列点和短线组成的字符串, 比如: "a" 对应 ".-", "b" 对应 "-...", "c" 对应 "-.-.", 等等。

为了方便,所有26个英文字母对应摩尔斯密码表如下:

[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]

给定一个单词列表,每个单词可以写成每个字母对应摩尔斯密码的组合。例如,"cab" 可以写成 "-.-..--...",(即 "-.-." + "-..." + ".-"字符串的结合)。我们将这样一个连接过程称作单词翻译。

返回我们可以获得所有词不同单词翻译的数量。

#!@Author : Sanwat
#!@File : .py
import math
class Solution:
def uniqueMorseRepresentations(self, words):
"""
       :type words: List[str]
       :rtype: int
       方法一
       # Approach #2   用ord()函数求出a的ASCII值, chr() 是将ASCII值变为字符.  ord('a') = 97 ,   ord("A") = 65
       ref = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
       return len(set("".join(ref[ord(s) - 97] for s in word) for word in words))
       方法二
       axb = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
                "u", "v", "w", "x", "y", "z"]
       morse = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.",
                "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."]
       morse_a = dict(zip(axb, morse))
       temp=set()
       for i in words:
           temp_morse = []
           for j in i:
               temp_morse.append(morse_a[j])
           s = "".join(temp_morse)
           temp.add(s)
       return len(temp)
       方法三
       """
       ref = {'a':".-",
           "b":"-...",
           "c":"-.-.",
           "d":"-..",
           "e":".",
           "f":"..-.",
           "g":"--.",
           "h":"....",
           "i":"..",
           "j":".---",
           "k":"-.-",
           "l":".-..",
           "m":"--",
           "n":"-.",
           "o":"---",
           "p":".--.",
           "q":"--.-",
           "r":".-.",
           "s":"...",
           "t":"-",
           "u":"..-",
           "v":"...-",
           "w":".--",
           "x":"-..-",
           "y":"-.--",
           "z":"--.."}
res = []
for word in words:
s = ''
           for i in  word:
s+= ref.get(i)
res.append(s)
return len(set(res))

S=Solution()
print(S.uniqueMorseRepresentations(["gin", "zen", "gig", "msg"]))

Nov 25

机器人能否返回原点

在二维平面上,有一个机器人从原点 (0, 0) 开始。给出它的移动顺序,判断这个机器人在完成移动后是否在 (0, 0) 处结束。

移动顺序由字符串表示。字符 move[i] 表示其第 i 次移动。机器人的有效动作有 R(右),L(左),U(上)和 D(下)。如果机器人在完成所有动作后返回原点,则返回 true。否则,返回 false。

注意:机器人“面朝”的方向无关紧要。 “R” 将始终使机器人向右移动一次,“L” 将始终向左移动等。此外,假设每次移动机器人的移动幅度相同。

#!@Author : Sanwat
#!@File : .pyclass Solution:
class Solution:
def judgeCircle(self, moves):
"""
       :type moves: str
       :rtype: bool
       """
     a=moves.count('U')
b=moves.count ('D')
c=moves.count ('L')
d=moves.count('R')
if (a==b)&(c==d):
return  True
       else:
return False
SOL = Solution()
print(SOL.judgeCircle('UDLRLRUD'))

Nov 26

山脉数组的峰顶索引

实现函数 ToLowerCase(),该函数接收一个字符串参数 str,并将该字符串中的大写字母转换成小写字母,之后返回新的字符串。

我们把符合下列属性的数组 A 称作山脉:

A.length >= 3

存在 0 < i < A.length - 1 使得A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]

给定一个确定为山脉的数组,返回任何满足 A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1] 的 i 的值。

#!@Author : Sanwat
#!@File : .py
class Solution:
def peakIndexInMountainArray(self, A):
"""
       :type A: List[int]
       :rtype: int
       """
       for i in range(len(A)):
j=i+1
           if A[j]>A[i]:
i=i+1
           else:
break
       return i
S=Solution()
print(S.peakIndexInMountainArray([0,1,2,3,4,3]))

Nov 27

按奇偶排序数组2

给定一个非负整数数组 A, A 中一半整数是奇数,一半整数是偶数。

对数组进行排序,以便当 A[i] 为奇数时,i 也是奇数;当 A[i] 为偶数时, i 也是偶数。

你可以返回任何满足上述条件的数组作为答案。

#!@Author : Sanwat
#!@File : .py
class Solution:
def sortArrayByParityII(self, A):
"""
       :type A: List[int]
       :rtype: List[int]
       方法一
       M = []
       N = []
       for i in range(len(A)):
           if A[i] % 2 == 1:
               M.append(A[i])
           else:
               N.append(A[i])
       res = []
       for i in range(len(A)):
           if i % 2 == 0:
               res.append(N[i // 2])
           else:
               res.append(M[i // 2])
       return res
       方法二
       """
       A_len, i, j = len(A), 0, 1
       result = [0] * A_len
for a in A:
if a & 1 == 0:
result[i] = a
i += 2
       else:
result[j] = a
j += 2
       return result
S=Solution()
print(S.sortArrayByParityII([2,4,7,5]))

Nov 28

二叉树的最大深度

定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7]

    3
   / \
  9  20
    /  \
   15   7

返回它的最大深度 3 。

#!@Author : Sanwat
#!@File : .py
import math
class Solution:
def maxDepth(self, root):
"""
       :type root: TreeNode
       :rtype: int
       """
       if root is None:
return 0
       else:
l_deep = self.maxDepth(root.left)
r_deep = self.maxDepth(root.right)
return max(l_deep, r_deep) + 1
S=Solution()
print(S.maxDepth([3,9,20,null,null,15,7]))

Nov 29

数字补数

给定一个正整数,输出它的补数。补数是对该数的二进制表示取反。

注意:

给定的整数保证在32位带符号整数的范围内。

你可以假定二进制数不包含前导零位。

方法一:先转为二进制数,然后以他的长度全部取为1,在异或。

#!@Author : Sanwat
#!@File : .py
class Solution:
def findComplement(self, num):
"""
       :type num: int
       :rtype: int
       """
     a=bin (num)[2:]
b='1'*len(a)
c=int (b,2)
result= c^num
return result
S=Solution()
print(S.findComplement(39))

方法二:先转为二进制数,然后一个一个取反。

#!@Author : Sanwat
#!@File : .py
class Solution:
def findComplement(self, num):
"""
       :type num: int
       :rtype: int
       方法一
       a=bin (num)[2:]
       b='1'*len(a)
       c=int (b,2)
       result= c^num
       return result
       方法二:
       """
       a=bin (num)[2:]
b=''
       for i in a:
if(i=='1'):
b+='0'
          else:
b+='1'
       result = int (b,2)
return result
S=Solution()
print(S.findComplement(39))

Nov 29

翻转二叉树

翻转一棵二叉树。

示例:

输入:

     4

   /   \

  2     7

 / \   / \

1   3 6   9

输出:

     4

   /   \

  7     2

 / \   / \

9   6 3   1

#!@Author : Sanwat
#!@File : .py
#Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
        self.right = None
class Solution:
def invertTree(self, root):
"""
       :type root: TreeNode
       :rtype: TreeNode
       """
       if root==None:
return root
root.left, root.right = root.right, root.left
root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
return root

Nov 30

合并二叉树

给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。

你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,否则不为 NULL 的节点将直接作为新二叉树的节点。

输入: 

Tree 1                     Tree 2                  

          1                         2                             

         / \                       / \                            

        3   2                     1   3                        

       /                           \   \                      

      5                             4   7                  

输出: 

合并后的树:

     3

    / \

   4   5

  / \   \ 

 5   4   7

#!@Author : Sanwat
#!@File : .py
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
       self.right = None
class Solution(object):
def mergeTrees(self, t1, t2):
"""
       :type t1: TreeNode
       :type t2: TreeNode
       :rtype: TreeNode
       """
       if t1 is not None and t2 is not None:
t1.val += t2.val
t1.left = self.mergeTrees(t1.left, t2.left)
t1.right = self.mergeTrees(t1.right, t2.right)
elif t1 is None and t2 is not None:
t1 = t2
return t1
S=Solution()
a=TreeNode([2,3,4,5,6,7,8])
b=TreeNode([2,4,3,2,5,1,2])
print(S.mergeTrees(a,b))

往事如风,带走了如花的青春,吹散了满天的浮云。失去的,再也无法挽回;流走的,成为生命里的过往。当所有的波澜起伏风平浪静,我用闲适淡然面对余生。

懂得感悟,适时的敞开心扉,让久违的阳光的心,大大方方的沐浴在那片耀眼里,任风吹,任雨打,秉住一份虔诚,于清幽里,膜拜出遍地的香花满径。


★★★★★

REQUEST AN

APPOINTMENT

逐影棍法之平指转棍+抛棍

一个故事一首歌。

一个世界一个人。

小随笔积累大智慧

机器人作者:Sanwat江影

人类侍从:唐三少

 
 
 

猜你喜欢

转载自www.cnblogs.com/Sanwat/p/10115806.html
今日推荐