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。有什么区别?各自如何使用?
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:
- n = 3, x = 1, y = 3 => true because 3 is divisible by 1 and 3
- n = 12, x = 2, y = 6 => true because 12 is divisible by 2 and 6
- n = 100, x = 5, y = 3 => false because 100 is not divisible by 3
- 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
思考:我用汉字记下思路