Python Kata(kyu 8 from codewars)

1 [Summation](数字)

Write a program that finds the summation of every number from 1 to num. The number will always be a positive integer greater than 0.

For example:

summation(2) -> 3
1 + 2

summation(8) -> 36
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8

def summation(num):
    return sum(range(1,num+1))
#range中包含的就是一段范围,直接sum求和
def summation(num):
    total = 0
    for i in range(0, num+1):
        total = total + i
    return total
#用for遍历,用i加和
def summation(num):
    #yurong
    return (1+num)*num/2

2 [Sum of positive](列表)

You get an array of numbers, return the sum of all of the positives ones.

Example [1,-4,7,12] => 1 + 7 + 12 = 20

Note: if there is nothing to sum, the sum is default to 0.

def positive_sum(arr):
    return sum(x for x in arr if x > 0)
#遍历取出所有正数,求和
def positive_sum(arr):
    sum = 0
    for i in arr:
        if i > 0:
            sum = sum + i
    return sum
##用for遍历,用i加和
def positive_sum(arr):
    #yurong
    sum = 0
    for i in range(len(arr)):
        if arr[i]>0:
            sum += int(arr[i])
        
    return sum

3 Counting "True"(布尔值)

We need a function that counts the number of "True" in the array (true means present).

a = [True, True, False, True, False, False,True]

def count_sheeps(a):
  return a.count(True)
#count 是个方法,可以指定括号里的内容
def count_sheeps(sheep):
#yurong
    a = [x for x in sheep if x == True]
    return len(a)

思考:此处为了计算True的个数,想到了count和len。有什么区别?各自如何使用?


image.png

4 Find the smallest integer in the array(列表)

Given an array of integers your solution should find the smallest integer.

For example:

Given [34, 15, 88, 2] your solution will return 2
Given [34, -345, -1, 100] your solution will return -345
You can assume, for the purpose of this kata, that the supplied array will not be empty.

def findSmallestInt(arr):
    return min(arr)
def findSmallestInt(arr):
    #sort array 
#sort是list的方法,没有返回值,只是立即修改列表顺序
#sorted是适用于所有可迭代对象的,建议用,有返回值
    arr.sort()
    return arr[0]
def find_smallest_int(arr):
    # yurong
    s = arr[0]
    for i in range(len(arr)):
        if arr[i] <= s:
            s = arr[i]
    return s

5 Is n divisible by x and y?(布尔值)

Create a function that checks if a number n is divisible by two numbers x AND y. All inputs are positive, non-zero digits.

Examples:

  1. n = 3, x = 1, y = 3 => true because 3 is divisible by 1 and 3
  2. n = 12, x = 2, y = 6 => true because 12 is divisible by 2 and 6
  3. n = 100, x = 5, y = 3 => false because 100 is not divisible by 3
  4. n = 12, x = 7, y = 5 => false because 12 is neither divisible by 7 nor 5
def is_divisible(n, x, y):
    return n % x == n % y == 0
#因为判断表达式本身就会回复布尔值
def is_divisible(n,x,y):
    #yurong
#如果只有“是""否”两种走向,可以用if else三目运算
    if n % x == 0 and n % y == 0:
        return True
    else:
        return False

6 Abbreviate a Two Word Name(0507看看join的示例)(字符串)

Description:

Write a function to convert a name into initials. This kata strictly takes two words with one space in between them.

The output should be two capital letters with a dot separating them.

It should look like this:

Sam Harris => S.H

Patrick Feeney => P.F

def abbrevName(name):
    first, last = name.upper().split(' ')

#以空格切片,批量,一起赋给两个变量first,last
#split 的输出是列表,join的输入是列表
    return first[0] + '.' + last[0]
def abbrev_name(name):
    #yurong
    a = name.find(" ")
    #取出空格的位置
    b = name[0:1]+"."+name[a+1:a+2]
    #取第一个字符。和空格后的第一个字符
    c = b.upper()
    #转换大写
    return c

7 Basic Mathematical Operations (turn str to operator)(字符串)

Your task is to create a function that does four basic mathematical operations.

The function should take three arguments - operation(string/char), value1(number), value2(number).
The function should return result of numbers after applying the chosen operation.

Examples
basic_op('+', 4, 7) # Output: 11
basic_op('-', 15, 18) # Output: -3
basic_op('*', 5, 5) # Output: 25
basic_op('/', 49, 7) # Output: 7

def basic_op(operator, value1, value2):
    return eval("{}{}{}".format(value1, operator, value2))
#format的功能和f字符串一样
def basic_op(operator, value1, value2):
#yurong
    a = str(value1)+ operator +str(value2)
#先拼接字符串
    return eval(a)
#eval() 函数用来执行一个字符串表达式,并返回表达式的值。

8 Convert number to reversed array of digits(0508 map函数怎么用)(数字,字符串)

Given a random non-negative number, you have to return the digits of this number within an array in reverse order.

Example:
348597 => [7,9,5,8,4,3]

def digitize(n):
    return list(map(int, str(n)[::-1]))
 #list(map(int, str(n) 相当于 [int(n) for i in str(n)]
def digitize(n):
    result = []
    while n >= 1:
        result.append(n%10)
#%10取余,得个位。//10取整,去掉最后一位。同理//100去掉最后两位
        n //= 10
    return result
def digitize(n):
#yurong
    a = str(n)[::-1]
#换成字符串并倒置
    b = [int(x) for x in a]
#迭代并换成int
    return b

9 A Needle in the Haystack(列表)

Can you find the needle in the haystack?

Write a function findNeedle() that takes an array full of junk but containing one "needle"

After your function finds the needle it should return a message (as a string) that says:

"found the needle at position " plus the index it found the needle, so:

find_needle(['hay', 'junk', 'hay', 'hay', 'moreJunk', 'needle', 'randomJunk'])

should return "found the needle at position 5"

def find_needle(haystack):
    return "found the needle at position " + str(haystack.index("needle"))
def find_needle(haystack):
#yurong
    a = haystack.index('needle')
    b = "found the needle at position {}".format(a)
    return b

10 Century From Year(数字)

Introduction

The first century spans from the year 1 up to and including the year 100, The second - from the year 101 up to and including the year 200, etc.

Task :
Given a year, return the century it is in.

Input , Output Examples :
1705 --> 18
1900 --> 19
1601 --> 17
2000 --> 20
Hope you enjoy it .. Awaiting for Best Practice Codes

Enjoy Learning !!!

def century(year):
    if year % 100 == 0:
        return year // 100
    else:
        return year // 100 +1
def century(year):
    return (year + 99) // 100
def century(year):
#yurong
    a = str(year)
    if a[-2:] == "00":
        return int(a[0:2])
    else:
        return year//100 +1

11 Square(n) Sum(列表)

Complete the square sum function so that it squares each number passed into it and then sums the results together.

For example, for [1, 2, 2] it should return 9 because 1^2 + 2^2 + 2^2 = 9.

def square_sum(numbers):
    return sum(x ** 2 for x in numbers)
def square_sum(numbers):
    return sum([x**2 for x in numbers])
def square_sum(numbers):
    return sum(map(lambda x: x**2,numbers))
def square_sum(numbers):
    #yurong
    x = [i**2 for i in numbers]
    y = sum(a for a in x)
    return y

12 Count of positives / sum of negatives(列表)

Given an array of integers.

Return an array, where the first element is the count of positives numbers and the second element is sum of negative numbers.

If the input array is empty or null, return an empty array.

Example
For input [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15], you should return [10, -65].

def count_positives_sum_negatives(arr):
    pos = sum(1 for x in arr if x > 0) #sum(1就是计数
    neg = sum(x for x in arr if x < 0)
    return [pos, neg] if len(arr) else []
#三目运算,先判断if成立,就走前面的条件,不成立就走else
#if,,,else,,,只有两条路的时候都可以考虑写三目运算表达式
def count_positives_sum_negatives(arr):
    #yurong
    if arr != []:
        a = [x for x in arr if x > 0]
        b = [x for x in arr if x < 0]
        return[len(a),sum(b)]
    else:
        return []

13 Fake Binary(字符串)

Given a string of digits, you should replace any digit below 5 with '0' and any digit 5 and above with '1'. Return the resulting string.

"15889923" --- "01111100"

def fake_bin(x):
    return ''.join('0' if c < '5' else '1' for c in x )

'0' if c < '5' else '1' 是一段三目运算,后面跟一个for循环遍历,对遍历的每一次,都应用一遍三目运算。字符串也可以遍历!


三目运算
def fake_bin(x):
    result = ''
    for i in x:
        if int(i) <= 4:
            result += "0"
        else:
            result += "1"
    return result
.join方法的使用

思考:我用汉字记下思路

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念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

推荐阅读更多精彩内容