Python Kata(kyu7 from codewars)

Vowel Count

Description:

Return the number (count) of vowels in the given string.

We will consider a, e, i, o, u as vowels for this Kata (but not y).

The input string will only consist of lower case letters and/or spaces.

def get_count(input_str):
    return sum(1 for i in input_str if i in "aeiouAEIOU")
#sum(1 for遍历)就是求个数
#if i in "aeiouAEIOU"是判断条件
def get_count(input_str):
    #yurong
#把符合条件的字符拿出来成立新list,并对其len求个数
    a = [a for a in input_str if a in ['a','e','i','o','u']]
    return len(a)

Mumbling(需要重新思考,用汉字写下思路)

accum("abcd") -> "A-Bb-Ccc-Dddd"
accum("RqaEzty") -> "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"
accum("cwAt") -> "C-Ww-Aaa-Tttt"

capitalize()和title()

def accum(s):
    return '-'.join(c.upper() + c.lower() * i for i, c in enumerate(s))
# enumerate 既能遍历元素,又能返回元素的位置
def accum(s):
    return '-'.join((a * i).title() for i, a in enumerate(s, 1))
# enumerate(s, 1) : 遍历元素,第一个元素序号是1不是0
def accum(s):
#yurong from steven's thought
#把字符串拆出来,append进list里,join组合新的字符串
    li = []
    for i in range(len(s )):
        b = s[i]*(i+1)
        li.append(b.capitalize())
    return "-".join(li)
#我一开始的错误答案:
def accum(s):
#yurong: THIS IS WRONG
#思路:遍历输入的字符串,取出每一位*该位的位置得到小字符串,并首字母大写,最后用“-”join链接
#错误原因:找位置的时候用了find。find只会返回第一次搜索的位置。所以过长的字符串,后面的字符位置会出错
    low = s.lower()
    b = "-".join((a * (1+low.find(f'{a}'))).capitalize() for a in low)
    return b
def accum(s):
#yurong
#按照错误答案的思路,把引用位置从find改成了enumerate
#join的输入是list
    low = s.lower()
    b = "-".join([(a * (1+i)).capitalize() for i, a in enumerate(low)])
    return b

Disemvowel Trolls

remove all of the vowels from the trolls' comments

r example, the string "This website is for losers LOL!" would become "Ths wbst s fr lsrs LL!".

def disemvowel(s):
    for i in "aeiouAEIOU":
        s = s.replace(i,'')
#字符串本身是不可变类型,通过反复把s赋值给自己,改变s
    return s
def disemvowel(str):
#yurong
    x = [i for i in str if i not in "aeiouAEIOU"]
    return "".join(x)

Highest and Lowest

high_and_low("1 2 3 4 5") # return "5 1"
high_and_low("1 2 -3 4 5") # return "5 -3"
high_and_low("1 9 3 4 -5") # return "9 -5"

def high_and_low(numbers):
  numbers = [int(c) for c in numbers.split(' ')]
  return f"{max(numbers)} {min(numbers)}"
def high_and_low(s):
#yurong
    a = s.split(" ")
    x = [int(i) for i in a]
    return(" ".join([str(max(x)),str(min(x))]))
#或者
    return("{e} {f}".format(e=max(x),f=min(x)))
#或者
    e,f = max(x),min(x)
    return(f'{e} {f}')

Square Every Digit

you are asked to square every digit of a number and concatenate them.

For example, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1.

Note: The function accepts an integer and returns an integer

def square_digits(num):
    ret = ""
    for x in str(num):
        ret += str(int(x)**2)
    return int(ret)
def square_digits(num):
#yurong
    a = [str(int(i)**2) for i in str(num)]
    b = ""
    for j in range(len(a)):
        b += a[j]
        
    return int(b)
def square_digits(num):
#yurong
#字符串的拼接 join
    a = [str(int(i)**2) for i in str(num)]
    return int("".join(a))

Descending Order

Description:
Your task is to make a function that can take any non-negative integer as an argument and return it with its digits in descending order. Essentially, rearrange the digits to create the highest possible number.

Examples:
Input: 42145 Output: 54421

Input: 145263 Output: 654321

Input: 123456789 Output: 987654321

def descending_order(num):
#yurong
    a = [int(i) for i in str(num)]
    a.sort(reverse = True)
    
    return int("".join(str(i) for i in a))

Get the Middle Character

You are going to be given a word. Your job is to return the middle character of the word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters.

Examples:

Kata.getMiddle("test") should return "es"

Kata.getMiddle("testing") should return "t"

Kata.getMiddle("middle") should return "dd"

Kata.getMiddle("A") should return "A"

def get_middle(s):
   return s[(len(s)-1)/2:len(s)/2+1]
def get_middle(s):
#Python divmod() 函数接收两个数字类型(非复数)参数,返回一个包含商和余数的元组(a // b, a % b)。
    index, odd = divmod(len(s), 2)
    return s[index] if odd else s[index - 1:index + 1]
def get_middle(s):
    i = (len(s) - 1) // 2
    return s[i:-i] or s
def get_middle(s):
    x = int(len(s)/2)
    return s[x] if len(s)%2!=0 else s[x-1:x+1]
def get_middle(s):
    #yurong
    a = len(s)
    if a%2 == 0:#even
        return s[int(a/2-1):int(a/2+1)]
    else:#odd
        return s[int(a/2-0.5)]

Isograms

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

def is_isogram(string):
#set返回去重复后的集合对象
#set是集合对象,独立于list,str等等的集合对象
    return len(string) == len(set(string.lower()))
def is_isogram(string):
    string = string.lower()
    for letter in string:
        if string.count(letter) > 1: return False
    return True
def is_isogram(s):
    #yurong
#return 意味着整个函数的结束,所以最终的return一定不在for 循环里,一定在for循环全部跑完之后,跟for循环同等缩进量。
    str = s.lower()
    for i in range(len(str)):
        if str.count(str[i]) >= 2:
            return False
    return True

You're a square!

In mathematics, a square number or perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself.
Examples
-1 => false
0 => true
3 => false
4 => true
25 => true
26 => false

def is_square(n):    
    return n >= 0 and (n**0.5) % 1 == 0
#或者    
    return n >= 0 and (n**0.5)-int(n**0.5) == 0
#当return的是布尔值时,就可以考虑return 表达式
def is_square(n):    
    if n>=0:
        if int(n**.5)**2 == n:
            return True
    return False
import math
def is_square(n):
    #yurong
    #负数直接returnfalse
    #26的开方是5.几几一个无限小数。所以如果开方没有小数部分,即开方等于int开方,就说明符合条件
#用了太多if,不好
    if n<0: return False
    a = math.sqrt(n)
    b = int(math.sqrt(n))

    if a - b == 0: return True
    
    return False 

Shortest Word

Simple, given a string of words, return the length of the shortest word(s).

String will never be empty and you do not need to account for different data types.

    test.assert_equals(find_short("bitcoin take over the world maybe who knows perhaps"), 3)
    test.assert_equals(find_short("turns out random test cases are easier than writing out basic ones"), 3)
    test.assert_equals(find_short("lets talk about javascript the best language"), 3)
    test.assert_equals(find_short("i want to travel the world writing code one day"), 1)
def find_short(s):
    # yurong
    li = s.split(" ")
    a = [len(i) for i in li]
    return min(a)

Complementary DNA

In DNA strings, symbols "A" and "T" are complements of each other, as "C" and "G". You have function with one side of the DNA (string, except for Haskell); you need to get the other complementary side. DNA strand is never empty or there is no DNA at all (again, except for Haskell).

DNA_strand ("ATTGC") # return "TAACG"

DNA_strand ("GTAT") # return "CATA"

pairs = {'A':'T','T':'A','C':'G','G':'C'}
def DNA_strand(dna):
    return ''.join([pairs[x] for x in dna])
#调用键,得到值,join组合值为新字符串 
def DNA_strand(dna):
    ref = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'}
    a = [ref[i] for i in dna]
    return "".join(a)
def DNA_strand(dna):
    #yurong
    a = [i for i in dna]
    for j in range(len(a)):
        if a[j] == "A":
            a[j] = "T"
            continue
        if a[j] == "T":
            a[j] = "A"
            continue
        if a[j] == "C":
            a[j] = "G"
            continue
        else:
            a[j] = "C"
        
    return "".join(a)
    # code here
区别

两个list合并dict

字典遍历
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,458评论 6 513
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,030评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,879评论 0 358
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,278评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,296评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,019评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,633评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,541评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,068评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,181评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,318评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,991评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,670评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,183评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,302评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,655评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,327评论 2 358

推荐阅读更多精彩内容