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