python练习(八)

来源:互联网 发布:单片机连接摄像头 编辑:程序博客网 时间:2024/06/06 14:25

  • Fizz Buzz
    • 题目
    • 思路
    • 解答
    • 答案
      • 负数的位于
  • Hamming Distance
    • 题目
    • 思路
    • 解答
    • 答案
  • Heaters
    • 题目
    • 思路
    • 解答
    • 答案
  • Largest Palindrome Product
    • 题目
    • 思路
    • 解答
    • 答案
      • 解释

注意,答案只是代表是他人写的代码,正确,但不一定能通过测试(比如超时),列举出来只是它们拥有着独到之处,虽然大部分确实比我的好

Fizz Buzz

题目

Write a program that outputs the string representation of numbers from 1 to n.

But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.

思路

有点像那个数七的游戏啊,数三五版的

解答

最开始忘写return函数了,还在奇怪为什么没有输出

class Solution(object):    def fizzBuzz(self, n):        """        :type n: int        :rtype: List[str]        """        l=[""]*n        for i in range(n):            if not (i+1)%3:                l[i] += "Fizz"            if not (i+1)%5:                l[i] += "Buzz"            if l[i] == "":                l[i] = str(i+1)        return l   

30%。。。

答案

def fizzBuzz(self, n):    return['FizzBuzz'[i%-3&-4:i%-5&8^12]or`i`for i in range(1,n+1)]

啥?虽然能猜到里边内容会是什么,不过咋实现的呢
因为感觉负数的位于运算不太对啊,第一个数显然是想0&-4=0 ,其它=-4,可1&4,2&4不也是0 吗,负数怎么算。第二个就更别提了。
反正数也不多,自己动手算了一下
第一个不说了。
第二个除了 0&8=0,其余的都=8
然后8^12=4,0^12=12
原来12不爆啊

负数的位于

补码的表示方法是:
正数的补码就是其本身
负数的补码是在其原码的基础上, 符号位不变, 其余各位取反, 最后+1. (即在反码的基础上+1)
位于:
按位与运算是按照数据的内部二进制形式进行运算的。若是两个负数,则是按二进制补码形式进行按位与。所得结果若用有符号整型变量存储,则内部形式仍看作二进制补码。如果用格式符%d输出,输出结果为十进制真值(不应该称为十进制原码)。

def fizzBuzz(self, n):    return ['Fizz' * (not i % 3) + 'Buzz' * (not i % 5) or str(i) for i in range(1, n+1)]

好懂多了版

是比我的快了一点点(我82ms)(这个75ms)

我扫了一眼java的,都是4ms,3ms ??????

Hamming Distance

题目

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, calculate the Hamming distance.

Note:
0 ≤ x, y < 231.

Example:

Input: x = 1, y = 4

Output: 2

Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
? ?

The above arrows point to positions where the corresponding bits are different.

思路

看着这个例子我也不知道在说什么

扫了眼别人写的代码才理解到底要干啥

比较两个数在二进制情况下不同位的个数

不就是异或之后1的个数喽
话说怎么数

解答

class Solution(object):    def hammingDistance(self, x, y):        """        :type x: int        :type y: int        :rtype: int        """        return bin(x^y).count('1')

搜了下数一的方法,答案差不多就出来了

答案

同样的代码别人能比我快倍(40+)与(20+)

ans = 0while x or y:  ans += (x % 2) ^ (y % 2)  x /= 2  y /= 2return ans

不使用的bin的方法

Heaters

题目

Winter is coming! Your first job during the contest is to design a standard heater with fixed warm radius to warm all the houses.

Now, you are given positions of houses and heaters on a horizontal line, find out minimum radius of heaters so that all houses could be covered by those heaters.

So, your input will be the positions of houses and heaters seperately, and your expected output will be the minimum radius standard of heaters.

Note:
Numbers of houses and heaters you are given are non-negative and will not exceed 25000.
Positions of houses and heaters you are given are non-negative and will not exceed 10^9.
As long as a house is in the heaters’ warm radius range, it can be warmed.
All the heaters follow your radius standard and the warm radius will the same.
Example 1:
Input: [1,2,3],[2]
Output: 1
Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.
Example 2:
Input: [1,2,3,4],[1,4]
Output: 1
Explanation: The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed.

思路

如何下手呢?
先试半径1,再试半径2,怕不是要超时
sort,找最大差值?

解答

还能这样给的?
[1,5]
[2]
那我整个体系都崩盘了啊
应该是判断两个list中的最大。。。呃不对。。。最小。。。怎么说呢,

class Solution(object):    def findRadius(self, houses, heaters):        """        :type houses: List[int]        :type heaters: List[int]        :rtype: int        """        smin = 0        for i in houses:            s=float('inf')            for h in heaters:                s = min(s,abs(h-i))                #if h > (s+i):break            smin = max(s,smin)                  return smin

果然超时了。
那句加注释的话是因为加上去以后反而不对了。

答案

def findRadius(self, houses, heaters):    heaters.sort()    return max(min(abs(house - heater)                   for i in [bisect.bisect(heaters, house)]                   for heater in heaters[i-(i>0):i+1])               for house in houses)

。。。

def findRadius(self, houses, heaters):    heaters = sorted(heaters) + [float('inf')]    i = r = 0    for x in sorted(houses):        while x >= sum(heaters[i:i+2]) / 2.:            i += 1        r = max(r, abs(heaters[i] - x))    return r

嗯。。。

Largest Palindrome Product

题目

Find the largest palindrome made from the product of two n-digit numbers.

Since the result could be very large, you should return the largest palindrome mod 1337.

Example:

Input: 2

Output: 987

Explanation: 99 x 91 = 9009, 9009 % 1337 = 987

Note:

The range of n is [1,8].

思路

好像题目还是不太好理解
唔,对于那两个数字没有要求的,对于回文数有要求,不应该从那两个数下手

解答

class Solution(object):    def largestPalindrome(self, n):        """        :type n: int        :rtype: int        """        i = 10**n - 1        l = 10**(n-1)        imax = i*i        x = imax + 1        while True:            x -= 1            if str(x) == str(x)[::-1]:                for m in xrange(l,i+1):                    if x%m == 0 and x/m <= i and x/m >= l :                        return x%1337

代码在3的时候由于自己zz出问题了
代码在4的时候由于range直接超内存了,但是我又不知道如何将xrange输出的数字倒序。。。不得不使用另一种丑陋的代码了
代码在5的时候超时了
时运不济,命途多舛

答案

讨论里倒是没多少用python的
这道题的答案是石乐志吧

class Solution(object):    def largestPalindrome(self, n):        """        :type n: int        :rtype: int        """        return [9, 9009, 906609, 99000099, 9966006699, 999000000999, \                    99956644665999, 9999000000009999][n - 1] % 1337
        ans = [0,9,987,123,597,677,1218,877,475]        return ans[n]

扯淡就先到这吧

class Solution(object):    def largestPalindrome(self, n):        """        :type n: int        :rtype: int        """           if n==1:            return 9        p = 10 ** n        for i in xrange(1,p):            a=p-i            b = int(str(a)[::-1])                        k = (i**2) - 4 * b            if k<0:                continue            import math            ksqrt = int(math.sqrt(k))            if ksqrt**2!=k:                continue            t = i+ksqrt            if t%2!=0:                continue            else:                return (a*p + b)%1337  

话说看到了另外一种倒序方式,堪比直接读list的速度

class Solution(object):    def largestPalindrome(self, n):        if n==1: return 9        if n==2: return 987        for a in xrange(2, 9*10**(n-1)):            hi=(10**n)-a            lo=int(str(hi)[::-1])            if a**2-4*lo < 0: continue            if (a**2-4*lo)**.5 == int((a**2-4*lo)**.5):                return (lo+10**n*(10**n-a))%1337

另一款堪比读list的速度

解释

我使用了以下方法。我们来表示最大的回文产品palindrome = M * L。对于N> 1,该坐标具有偶数位数,并且可以表示为和:palindrome = upper * 10^N + lower我们可以预期M和L接近10 ^ N,并且我们可以将它们表示为M = 10^N - i,L = 10^N - j因此palindrome = (10^N - i) * (10^N - j) = 10^N * (10^N - (i + j)) + i * j如果我们假设i * 10 ^ N(对于N> 1,这个假设证明是正确的),我们可以用以下方式表示上下:upper = 10^N - (i + j)lower = i * j这是可以解决的方程组,如果我们知道上下。我们来表示ij的和a = i + j。它可以计算为a = 10^N - upper。因为下面的j = a - i方程可以被重写为lower = a * i - i * i这是可以使用教科书的标准方法解决的二次方程因为i^2 - a*i - lower = 0(不是i^2 - a*i + lower = 0吗)这样,(i-a/2)^2 = (4*lower-a^2)/2(这里应该是(i-a/2)^2 = (a^2-4*lower)/4吧?)所以,当且仅当(4*lower-a^2)/2是一些整数的平方,可以降低i^2 - a*i - lower = 0具有整数结果。所以我(a^2-4*lo)^.5 == int((a^2-4*lo)^.5)用来检查。

花了好久查找资料,寻找解释,终于
大概是利用数学的方法使抽出特征值,需要查找的数字长度及数量大幅减少,以减少时间

去tm的easy

原创粉丝点击