【Python刷题】2020/07/30


1. 第一题

You might know some pretty large perfect squares. But what about the NEXT one?

Complete the findNextSquare method that finds the next integral perfect square after the one passed as a parameter. Recall that an integral perfect square is an integer n such that sqrt(n) is also an integer.

If the parameter is itself not a perfect square then -1 should be returned. You may assume the parameter is positive.

findNextSquare(121) --> returns 144

findNextSquare(625) --> returns 676

findNextSquare(114) --> returns -1 since 114 is not a perfect

首先的思路:

from math import sqrt
def find_next_square(sq):
    # Return the next square if sq is a square, -1 otherwise
    number = sqrt(sq)
    
    if type(number) == int:
        return pow((number+1), 2)
    else:
        return -1

出现一个问题,如sq=4,sqrt(sq)=2.0,此时type返回的并不是整形,而是float

更改:

def find_next_square(sq):
    # Return the next square if sq is a square, -1 otherwise
    number = sqrt(sq)
    if number - int(number) == 0.0:
        return int(pow((number + 1), 2))
    else:
        return -1

第一题好简单,大神解法:

def find_next_square(sq):
    root = sq ** 0.5
    if root.is_integer():
        return (root + 1)**2
    return -1

另一个解法:

def find_next_square(sq):
    x = sq**0.5
    return -1 if x % 1 else (x+1)**2

大神法1和我的思路基本是一致的,看到:is_integer()的时候,我大概知道他的意思,追溯了一下:

    def is_integer(self, *args, **kwargs): # real signature unknown
        """ Return True if the float is an integer. """
        Pass

需要注意的是:此处判断的数,是float型数!

底下有个评论关于是用sqrt还是x**0.5的:

 As for the question, I think if you can solve a problem without importing additional libraries, that's the most 'effective' way to do it. math.sqrt(n) doesn't do it better. It's the same thing as n ** 0.5.

2. 第二题

Given an array of ones and zeroes, convert the equivalent binary value to an integer.

Eg: [0, 0, 0, 1] is treated as 0001 which is the binary representation of 1.

Examples:

Testing: [0, 0, 0, 1] ==> 1

Testing: [0, 0, 1, 0] ==> 2

Testing: [0, 1, 0, 1] ==> 5

Testing: [1, 0, 0, 1] ==> 9

Testing: [0, 0, 1, 0] ==> 2

Testing: [0, 1, 1, 0] ==> 6

Testing: [1, 1, 1, 1] ==> 15

Testing: [1, 0, 1, 1] ==> 11

However, the arrays can have varying lengths, not just limited to 4.

思路:

def binary_array_to_number(arr):
    x = 0
    size = len(arr)
    for i in range (size):
        if arr[i]:
            x += 2**(size-1-i)
    return x

也很简单

大神解法1:

def binary_array_to_number(arr):
    return int("".join(map(str, arr)), 2)

大神解法2:

def binary_array_to_number(arr):
    return sum(digit * 2**i for i, digit in enumerate(reversed(arr)))

3.第三题 

An isogram is a word that has no repeating letters, consecutive or non-consecutive. Implement a function that determines whether a string that contains only letters is an isogram. Assume the empty string is an isogram. Ignore letter case.

is_isogram("Dermatoglyphics" ) == true

is_isogram("aba" ) == false

is_isogram("moOse" ) == false # -- ignore letter case

我的思路是:先转为小写,然后统计每个字母出现的次数,如果出现了两次,则返回false,一次及以下返回true,我觉得困难在于,不知道如何统计对应的字母,没有写的出来。

大神解法1:

def is_isogram(string):
    return len(string) == len(set(string.lower()))

好家伙,一行搞定了

大神解法2:

def is_isogram(string):
    string = string.lower()
    for letter in string:
        if string.count(letter) > 1: return False
    return True

!我的思路果然也有人这么做,滑到下面看到了!

def is_isogram(string):
    #your code here
    char_dict = {}
    string = string.lower()
    
    for char in string:
        if char in char_dict:
            # increment count of this character
            char_dict[char] = char_dict[char] + 1
        else:
            char_dict[char] = 1
    
    # loop over the characters in dictionary, if any have
    # more than 1 found, this string is not an isogram, so break
    # the loop and function and return False.
    for key in char_dict:
        if char_dict[key] > 1:
            return False
            
    # If no duplicates were found in the loop directly above,
    # this must be an isogram, so return true!
    return True

仔细看了一下,我的问题出在键值对那里,我有点绕晕了,没有表达的好。

用蹩脚的英语感谢了一下!

4. 第四题

Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.

For example:

 persistence(39) => 3  # Because 3*9 = 27, 2*7 = 14, 1*4=4         # and 4 has only one digit.

 persistence(999) => 4 # Because 9*9*9 = 729, 7*2*9 = 126,       # 1*2*6 = 12, and finally 1*2 = 2.

 persistence(4) => 0     # Because 4 is already a one-digit number.

第四题也还好,解答如下:

def multiply(n):
    nn = str(n)
    size = len(nn)
    x = 1
    for i in range(size):
        x *= int(nn[i])
    return x

def persistence(n):
    # your code
    count = 0
    while n > 9:
        n = multiply(n)
        count += 1
    return count

不过我用了两个函数才勉强实现功能,总觉得str()和int()那里太繁琐了,不过也没想到好办法解决

大神解法1:

from functools import reduce
import operator
def persistence(n):
    i = 0
    while n>=10:
        n=reduce(operator.mul,[int(x) for x in str(n)],1)
        i+=1
    return i

大神解法2:

def persistence(n):
    n = str(n)
    count = 0
    while len(n) > 1:
        p = 1
        for i in n:
            p *= int(i)
        n = str(p)
        count += 1
    return count

5. 第五题

Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed (Just like the name of this Kata). Strings passed in will consist of only letters and spaces. Spaces will be included only when more than one word is present.

Examples: spinWords( "Hey fellow warriors" ) => returns "Hey wollef sroirraw" spinWords( "This is a test") => returns "This is a test" spinWords( "This is another test" )=> returns "This is rehtona test"

这题还好,恰好反转前面看大神解答里有reversed感觉正好就用上了!可惜恰恰相反,如果使用reversed在函数里,我报错为:<reversed object at 0x0000025A71EB82E8>,烦了好久,写了个切片法:

def reverse1(string):
    return string[::-1]

def spin_words(sentence):
    words_return = ''
    words = sentence.split(' ')
    for i in range(len(words)):
        if len(words[i]) >= 5:
            words[i] = reverse1(words[i])
    if len(words) == 1:
        words_return = words[0]
    else:
        words_return = ' '.join(words)
    return words_return

大神解法1:

def spin_words(sentence):
    return " ".join([x[::-1] if len(x) >= 5 else x for x in sentence.split(" ")])

大神解法2:

def spin_words(sentence):
    L = sentence.split()
    new = []
    for word in L:
        if len(word) >= 5:
            new.append(word[::-1])
        else:
            new.append(word)
    string = " ".join(new)
    return string

学习笔记:

第一题:

判断一个数是不是整数的方法:

  1. 关于.is_integer()的使用【float型的判断】
  2. X%1,这个感觉挺巧妙的
  3. int(sqrt(sq)) == sqrt(sq),1.0 = 1,这个判断是成立的,我数学真是白学了

关于平方开方

  1. 开方,sqrt,
  2. 平方,pow
  3. X**n 即,x的n次幂

第二题:

  1. map函数的使用:map(function, iterable, ...),把第一个函数,分别作用于后面的序列,此处的函数可以是自己定义的,也可以是自带的。
  2. Join函数的使用:str.join(sequence),使用str对sequence序列进行连接,当序列为字典的时候,只对键进行连接。列表里的元素需要是字符串。
  3. Int函数的使用:int(x,base),默认base是10,即常见的取整,如果是2,则是把x转换为2进制,3是转换为3进制。神奇,之前没接触过。
  4. enumerate函数的使用:enumerate(sequence, [start=0]),枚举sequence,可以规定start的起始数值,可以和for循环一起用,如:for i, element in enumerate(seq):,如果没有设置start,默认的话,i从0开始
  5. reversed函数的使用,reversed(seq),seq可以是字符串,元组和序列,和range,实现翻转的功能,原来是12345,输出就是54321,也翻车过,可以自己写个切片法来实现反转。 string[::-1]

第三题:

1.set(),创建集合,利用集合的单一性,可以删除重复的数据

2.str.count()函数的学习,str.count(sub, start= 0,end=len(string)),统计字符串里某个字符出现的次数,可选开始结束位置。

3.if string.count(letter) > 1: return False 实际上执行了if后面的语句,感觉很巧妙

第四题:

1.reduce()函数的使用,reduce(function, iterable[, initializer]),function可能只有两个输入,使用reduce可以实现多个输入(iterable)的累积,initializer规定了起始参数

2.operator.mul()函数的使用,operator库是一个算数和比较的库,参考此博客,mul实现乘的功能

3.对于字符串也可以使用for i in n的方法进行遍历,大神的方法二思路应该好好学习的

第五题:

还好,感觉是对前四题用到知识的一个汇总

 

简单的五个题目,从下午6点半写到了八点半,两个小时。我的天呐,真的是好不熟练啊~脑子经常短路。有的大神写法吧,确实短小精悍,不过我实在水平有限,一行代码确实是理解不来,emm,量力而行吧。

希望自己能坚持下去,反正没开学,时间耗的多一点也没关系的。

打怪升级了,哦耶~

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值