Start from zero codewars kata Use lambda to return function? !!

What is codewars kata

In a nutshell, it's a dojo where you can train your programming. It may be said that it is an overseas version of AtCoder ~~ Well, I didn't know how to use AtCoder, so I haven't done it ~~ Personally, it suits my skin better than AtCoder

Trigger

After reading this article, I decided to try it, and started about 3 days ago. Advice from a 19-year-old software developer girl

I try to solve at least 5 Code Wars Kata a day. CodeWars is your best friend, not only when you're just starting out, but when you've been coding for years! The problem solving methods provided by CodeWars are always very informative, and you can greatly improve your syntax simply by scrolling through the solutions provided by others. Another big advantage is that when you go to a coding interview, you're often asked questions that are very similar to what CodeWars asks.

That's why I went to the problem immediately But after all it's an article for myself If you are interested, I recommend you to access codewars kata

Question 1

Your goal in this kata is to implement a difference function, which subtracts one list from another and returns the result.
Create a function that subtracts the contents of one list from another
It should remove all values from list a, which are present in list b.
Subtract all the functions in list b
Example)
array_diff([1,2],[1]) == [2]
If a value is present in b, all of its occurrences must be removed from the other:
If there are multiple numbers in b, subtract them all
array_diff([1,2,2,2,3],[2]) == [1,3]

My answer

def array_diff(a, b):
    return [a1 for a1 in a if a1 not in b]

I think I was able to answer a little smartly ...?

By the way, other people's answers are ... Best Practice

def array_diff(a, b):
    return [x for x in a if x not in b]

Exactly together! !! !! I wonder if I got used to writing kata on the third day

Problem 2

Make a diamond! !! !! !! I saw the figures 1, 3, 5, 7 ... It seems to make a function to make diamonds of each size.

Jamie is a programmer, and James' girlfriend. She likes diamonds, and wants a diamond string from James. Since James doesn't know how to make this happen, he needs your help.

Task
You need to return a string that looks like a diamond shape when printed on the screen, using asterisk (*) characters. Trailing spaces should be removed, and every line must be terminated with a newline character (\n).

Return null/nil/None/... if the input is an even number or negative, as it is not possible to print a diamond of even or negative size.

Examples
A size 3 diamond:

 *
***
 *
...which would appear as a string of " *\n***\n *\n"

A size 5 diamond:

  *
 ***
*****
 ***
  *
...that is: " *\n ***\n*****\n ***\n *\n"

My answer

def diamond(n):
    # Make some diamonds!
    if n%2 ==0 or n <1:
        return None

    ans=''
    for i in range(1,n+1,2):
        ans += '{}{}\n'.format(' '*((n-i)//2) ,'*'*i)
    for i in range(n-2,0,-2):
        ans += '{}{}\n'.format(' '*((n-i)//2) ,'*'*i)
    return ans

The code is not beautiful, but the output is too beautiful and I am satisfied

Best Practice

def diamond(n):
    if n > 0 and n % 2 == 1:
        diamond = ""
        for i in range(n):
            diamond += " " * abs((n/2) - i)
            diamond += "*" * (n - abs((n-1) - 2 * i))
            diamond += "\n"
        return diamond
    else:
        return None

I'm using abs (n / 2- i) well and omitting the cases I did, it's smart

later

def diamond(n):
    if not n%2 or n<1: return None
    d = [" "*i+"*"*(n-2*i)+"\n" for i in range(n/2,0,-1)]
    return ''.join(d) + "*"*n + "\n" + ''.join(d[::-1])

Make a half diamond and use it properly depending on whether you trace it from the top or the bottom. This is also smart

Problem 3

You have an array of numbers.
Give a string
Your task is to sort ascending odd numbers but even numbers must be on their places.
Sort only odd numbers, leave even numbers as they are
Zero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it.
Zero is an even number, if it is an empty array, return is also an empty array
Example

sort_array([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4]

My answer

def sort_array(ar):
    # Return a sorted array.
    odd = sorted([a for a in ar if a%2 ==1])
    even = [a for a in ar if a%2 ==0]
    
    flg = [a%2 for a in ar]
    
    ans = []
    od = 0
    ev = 0
    for i in range(len(ar)):
        if flg[i]:
            ans.append(odd[od])
            od +=1
        if not flg[i]:
            ans.append(even[ev])
            ev+=1
    return ans

I couldn't think of a good method, so I obediently divided it into odd and even numbers.

Best Practice

def sort_array(arr):
  odds = sorted((x for x in arr if x%2 != 0), reverse=True)
  return [x if x%2==0 else odds.pop() for x in arr]

After creating odds, I regenerate the array with for x in arr Isn't x if x% 2 == 0 difficult with even processing?

list.pop () can retrieve & delete the last element of the array With list.pop (0) you can do the same with the first element ʻElse odds.pop ()` can retrieve & delete the last element of the odd array By putting it in the for statement, you can see it one by one in ascending order ... smart

Example
odds=[5,3,1]
print('get:',odds.pop(),',odd:',odds)
==> get: 1 ,odd: [5, 3]

Problem 4

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
10 or less, 3,If you list multiples of 5, 3,5,6,9 and sum is 23
Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in.
Find the sum
Note: If the number is a multiple of both 3 and 5, only count it once.
Note:If it is a multiple of either, it will be counted once

My answer

def solution(number):
  return sum([x for x in range(0,number,3)]+[x for x in range(0,number,5)]) - sum([x for x in range(0,number,15)])

The simplest? Sum of multiples of 3 + Sum of multiples of 5-15 Sum of multiples of 15

Best Practice

def solution(number):
    return sum(x for x in range(number) if x % 3 == 0 or x % 5 == 0)

Sum of numbers divisible by 3 or 5 This is also simple

Problem 5

This time we want to write calculations using functions and get the results. Let's have a look at some examples: Make a guy to calculate. For example ...

seven(times(five())) # must return 35
four(plus(nine())) # must return 13
eight(minus(three())) # must return 5
six(divided_by(two())) # must return 3
Requirements:

There must be a function for each number from 0 ("zero") to 9 ("nine")
There must be a function for each of the following mathematical operations: plus, minus, times, dividedBy (divided_by in Ruby and Python)
Each calculation consist of exactly one operation and two numbers
The most outer function represents the left operand, the most inner function represents the right operand
Divison should be integer division. For example, this should return 2, not 2.666666...:

--Functions are 0-9 --Add, subtract, divide, multiply --Calculation always has two numbers and one operator --The numbers on the outside are on the left and the numbers on the inside are on the right. --Division is truncated

By the way, I made a mistake in 7kyu and chose the 5kyu problem, which is overwhelmingly more difficult than usual. The answer is an unbearable chord. .. .. Oh, this isn't worth reading

def zero(num = 0.5): #your code here
    if num == 0.5:
        return 0    
    return clac(0,num[0],num[1])
def one(num = 0.5): #your code here
    if num == 0.5:
        return 1    
    return clac(1,num[0],num[1])
def two(num =0.5): #your code here
    if num == 0.5:
        return 2   
    return clac(2,num[0],num[1])
def three(num = 0.5): #your code here
    if num == 0.5:
        return 3   
    return clac(3,num[0],num[1])
def four(num = 0.5): #your code here
    if num == 0.5:
        return 4   
    return clac(4,num[0],num[1])
def five(num = 0.5): #your code here
    if num == 0.5:
        return 5   
    return clac(5,num[0],num[1])
def six(num = 0.5): #your code here
    if num == 0.5:
        return 6   
    return clac(6,num[0],num[1])
def seven(num = 0.5): #your code here
    if num == 0.5:
        return 7   
    return clac(7,num[0],num[1])
def eight(num = 0.5): #your code here
    if num == 0.5:
        return 8   
    return clac(8,num[0],num[1])
def nine(num = 0.5): #your code here
    if num == 0.5:
        return 9   
    return clac(9,num[0],num[1])

def plus(num): #your code here
    return [num,1]
def minus(num): #your code here
    return [num,2]
def times(num): #your code here
    return [num,3]
def divided_by(num): #your code here
    return [num,4]

def clac(a,b,operation):
    if operation ==1:
        return a + b
    if operation ==2:
        return a - b
    if operation ==3:
        return a * b
    if operation ==4:
        return a // b

And this is the best practice answer

def zero(f = None): return 0 if not f else f(0)
def one(f = None): return 1 if not f else f(1)
def two(f = None): return 2 if not f else f(2)
def three(f = None): return 3 if not f else f(3)
def four(f = None): return 4 if not f else f(4)
def five(f = None): return 5 if not f else f(5)
def six(f = None): return 6 if not f else f(6)
def seven(f = None): return 7 if not f else f(7)
def eight(f = None): return 8 if not f else f(8)
def nine(f = None): return 9 if not f else f(9)

def plus(y): return lambda x: x+y
def minus(y): return lambda x: x-y
def times(y): return lambda  x: x*y
def divided_by(y): return lambda  x: x/y

...? ?? ?? What a cool

I will read it def zero(f = None): return 0 if not f So far, it's a basic structure that I should have been able to do, remorse (it's embarrassing to publish the fucking code)

else f(0) ...? ?? ?? Nanikore This takes a function as an argument. I didn't know I could do that. Moreover, using lambda.

def plus(y): return lambda x: x+y ... Apparently Kimo is like lambda

Let's take a slow look at seven (times (five ())) as an example.

First, seven (times (five ())) Will be seven (times (5)) Next, because the return value of times (5) is lambda x: x + y

def f(x):
 return x * 5

Returns a function that

And since we are f (7) for that function, the return value will be 35.

It took me a long time to read this far

After all 5kyu is still difficult. .. ..

Recommended Posts

Start from zero codewars kata Use lambda to return function? !!
How to use return
How to use Python lambda
How to use the zip function
How to use SWIG from waf
[Lambda] [Python] Post to Twitter from Lambda!
Code wars kata starting from zero
How to use python zip function
Make SikuliX's click function easier to use
Reinforcement learning to learn from zero to deep
[TF] How to use Tensorboard from Keras
[python] How to use __command__, function explanation
I want to use jar from python
From Attention of Zero Tsuku 2 to Transformer
How to access RDS from Lambda (python)
Lambda function to take AMI backup (python)
[Road to intermediate Python] Use lambda expressions