Start a new Kumite
AllAgda (Beta)BF (Beta)CCFML (Beta)ClojureCOBOL (Beta)CoffeeScriptCommonLisp (Beta)CoqC++CrystalC#D (Beta)DartElixirElm (Beta)Erlang (Beta)Factor (Beta)Forth (Beta)Fortran (Beta)F#GoGroovyHaskellHaxe (Beta)Idris (Beta)JavaJavaScriptJulia (Beta)Kotlinλ Calculus (Beta)LeanLuaNASMNim (Beta)Objective-C (Beta)OCaml (Beta)Pascal (Beta)Perl (Beta)PHPPowerShell (Beta)Prolog (Beta)PureScript (Beta)PythonR (Beta)RacketRaku (Beta)Reason (Beta)RISC-V (Beta)RubyRustScalaShellSolidity (Beta)SQLSwiftTypeScriptVB (Beta)
Show only mine

Kumite (ko͞omiˌtā) is the practice of taking techniques learned from Kata and applying them through the act of freestyle sparring.

You can create a new kumite by providing some initial code and optionally some test cases. From there other warriors can spar with you, by enhancing, refactoring and translating your code. There is no limit to how many warriors you can spar with.

A great use for kumite is to begin an idea for a kata as one. You can collaborate with other code warriors until you have it right, then you can convert it to a kata.

Ad
Ad

A friend had showed this too me a couple of days ago on TeleHack.com (which you all should check out). It uses lambda to print the numbers in the fibonacci sequence.

#To print a specific term in the sequence
f = lambda a, b: (a lambda: f(b, a + b))
g = f(0, 1)

n = int(input('What term?: '))

for i in range(1, n):
    g = g[1]()
    print(g[0])

#To print the sequence upto this term
f = lambda a, b: (a lambda: f(b, a + b))
g = f(0, 1)

n = int(input('What term?: '))

for i in range(1, n):
    g = g[1]()
    print(g[0]) #Simply just tabbing this into the for loop

This is my stock API trading bot that I created in python to paper trade the stocks that I have chosen and at what quantity I would like.

import alpaca_trade_api as tradeapi
import time

print("\033c")

def time_to_market_close():
    clock = api.get_clock()
    return (clock.next_close - clock.timestamp).total_seconds()


def wait_for_market_open():
    clock = api.get_clock()
    if not clock.is_open:
        print("Market opens: " + str(clock.next_open))
        print()
        print("Sleeping...")
        time_to_open = (clock.next_open - clock.timestamp).total_seconds()
        time.sleep(round(time_to_open))

key = "my_key"
sec = "my_sec_key"

url = "https://paper-api.alpaca.markets"

api = tradeapi.REST(key, sec, url, api_version='v2')

account = api.get_account()

print(account.status)

while True:
    a = time_to_market_close()
    wait_for_market_open()
    if a > 120:
        n = 0
        symbols = ["FB", "AAPL", "GOOG"]
        stockqty = ["30", "50", "20"]
        percent = 0.5
        percentN = 0 - percent
        count = 0
        while True:
            n = 0
            for i in range(len(symbols)):
                barset = api.get_barset(symbols[n], "minute",)
                symbols_bars = barset[symbols[n]]
                minute_open = symbols_bars[0].o
                minute_open2 = symbols_bars[-1].o
                percent_change = (minute_open2 - minute_open) / minute_open * 100

                try:
                    position = api.get_position(symbols[n])
                    print(f"Current balance: ${account.equity}")
                    print(f"You have {position.qty} shares of " + symbols[n])
                except:
                    api.submit_order(
                                symbol=symbols[n],
                                qty="1",
                                side="buy",
                                type="market",
                                time_in_force="day"
                            )
                    time.sleep(10)
                    position = api.get_position("AAPL")
                    print(f"Current balance: ${account.equity}")
                    print(f"You have {position.qty} shares of " + symbols[n])
                    
                time1 = str(time)

                if int(round(percent_change, 2)) >= percent and int(position.qty) == (int(stockqty[n]) + 1):
                    api.submit_order(
                                symbol=symbols[n],
                                qty=stockqty[n],
                                side="sell",
                                type="market",
                                time_in_force="day"
                            )
                    update = open("Mupdates.txt", "a")
                    update.write("MSherman sold " + stockqty[n] + " of " + symbols[n] + " for " + minute_open + " each.")
                    update.close()

                    print("MSherman sold " + stockqty[n] + " of " + symbols[n] + " for " + minute_open + " each.")
                    print()

                elif int(round(percent_change, 2) <= percentN and int(position.qty) == 1:
                    api.submit_order(
                                symbol=symbols[n],
                                qty=stockqty[n],
                                side="buy",
                                type="market",
                                time_in_force="day",
                            )
                    update = open("Mupdates.txt", "a")
                    update.write("MSherman bought " + stockqty[n] + " of " + symbols[n] + " for " + minute_open + " each.")
                    update.close()

                    print("MSherman bought " + stockqty[n] + " of " + symbols[n] + " for " + minute_open + " each.")
                    print()
                    
                n += 1
                time.sleep(10)

        updates = open("Mupdates.txt", "r")
        lines = upadtes.readlines()
        for line in lines:
            count += 1
            print(f"Line {count}: " + line.strip())
        wait_for_market_open()
Mathematics
Algorithms
Logic
Numbers
Data Types

"""
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.

Find the sum of all the multiples of 3 or 5 below 1000
"""

mylist = range(1000)


def multiple(arg):
    return sum(list(filter(lambda x: (x % 3 == 0 or x % 5 == 0) and x != 0, arg)))


print(multiple(mylist))
Mathematics
Algorithms
Logic
Numbers
Data Types

"""
Write a Python class to find a pair of elements next to each other (indices of the two numbers)
from a given array whose sum equals a specific target number.
Example:
Input: numbers= [5, 20, 10, 40, 50, 60, 70, 45, 5, 45], target=50
Output: [(2, 3), (7, 8), (8, 9)] (index)
"""

from itertools import combinations

array = [5, 20, 10, 40, 50, 60, 70, 45, 5, 45]
target = 50


def search(a, t):
    zip_a = list(zip(a[0::], a[1::]))
    s = set()
    combi = list(combinations(a, 2))
    for i in range(len(combi)):
        if sum(combi[i]) == t:
            s.add(combi[i])
    return [(i, i + 1) for i in range(len(zip_a)) if zip_a[i] in s]


class Py_solution:
    pair = staticmethod(search)


print(Py_solution().pair(array, target))
Mathematics
Algorithms
Logic
Numbers
Data Types

"""
Write a Python function that prints out the first n rows of Pascal's triangle.
Note : Pascal's triangle is an arithmetic and geometric figure first imagined by Blaise Pascal.

Example: Pascal's triangle for 8 first iteration steps
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
"""

number = 8
tab = number * 8


def pair_elements(args):
    pairs = []
    for i in range(len(args) - 1):
        pairs.append([args[i], args[i + 1]])
    return pairs


def pascal(n):
    array = [1]
    print(str(array).center(tab))
    array = [1, 1]
    print(str(array).center(tab))
    i = 1
    while i <= n-2:
        new_array = [1, 1]
        pairs = pair_elements(array)

        for index in range(1, len(array)):
            new_array.insert(index, sum(pairs[index - 1]))

        print(str(new_array).center(tab))
        array = new_array[:]
        i += 1


pascal(number)
Mathematics
Algorithms
Logic
Numbers
Data Types

"""
Write a Python program to calculate the average value of the numbers in a given tuple of tuples.
Original Tuple:
((10, 10, 10, 12), (30, 45, 56, 45), (81, 80, 39, 32), (1, 2, 3, 4))
Average value of the numbers of the said tuple of tuples:
[30.5, 34.25, 27.0, 23.25]
Original Tuple:
((1, 1, -5), (30, -15, 56), (81, -60, -39), (-10, 2, 3))
Average value of the numbers of the said tuple of tuples:
[25.5, -18.0, 3.75]
"""

my_tuple = ((10, 10, 10, 12), (30, 45, 56, 45), (81, 80, 39, 32), (1, 2, 3, 4))


def average(tuples):
    output_list = []
    for item in zip(*tuples):
        output_list.append(sum(item)/len(item))
    return output_list


print(f"\nAverage value: {average(my_tuple)}")
Dictionary
Data Structures
Data Types

"""
Write a Python program to create a dictionary grouping a sequence of key-value pairs into a dictionary of lists.
Original list:
[('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
Grouping a sequence of key-value pairs into a dictionary of lists:
{'yellow': [1, 3], 'blue': [2, 4], 'red': [1]}
"""

mylist = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]


def group(lst):
    dic = {}
    for i in lst:
        if i[0] not in dic:
            dic[i[0]] = [i[1]]
        else:
            dic[i[0]] = [*dic[i[0]], i[1]]
    return dic


print(group(mylist))
Dictionary
Data Structures

"""
Write a Python program to convert more than one list to nested dictionary.
Original strings:
keys = ['S001', 'S002', 'S003', 'S004']
names = ['Kate', 'Toni', 'Dany', 'Sam']
ages = [23, 15, 89, 69]
Nested dictionary:
[{'S001': {'Kate': 23}}, {'S002': {'Toni': 15}},
{'S003': {'Dany': 89}}, {'S004': {'Sam': 69}}]
"""

keys = ['S001', 'S002', 'S003', 'S004']
names = ['Kate', 'Toni', 'Dany', 'Sam']
ages = [23, 15, 89, 69]


def nested_dic(k, n, a):
    return [{key: {name: age}} for (key, name, age) in zip(k, n, a)]



print(nested_dic(k=keys, n=names, a=ages))
Data Types
Dictionary
Data Structures

"""
Write a Python program to filter persons based on the height.
Original Dictionary:
dic = {'Max': 175, 'Alan': 180, 'Peter': 190, 'Kay': 165}
Not greater than 180:
{'Max': 175, 'Alan': 180, 'Kay': 165}
"""

dic = {'Max': 175, 'Alan': 180, 'Peter': 190, 'Kay': 165}
max_height = 180


def filter_height(d, m):
    return {k: v for k, v in d.items() if v <= m}


print(filter_height(dic, max_height))

"""
What do the Pyramids of Giza and Da Vinci’s Mona Lisa have in common with Twitter and Pepsi?
Quick answer: They are all designed using the Golden Ratio.
The Golden Ratio is a mathematical ratio. It is commonly found in nature, and when used in a design,
it fosters organic and natural-looking compositions that are aesthetically pleasing to the eye.
Many processes in nature can be described by the Fibonacci. and the quotient
of successive elements of the Fibonacci sequence result in the golden ratio also associated with beauty

Putting it as simply as we can (eek!), the Golden Ratio
(also known as the Golden Section, Golden Mean, Divine Proportion or Greek letter Phi)
exists when a line is divided into two parts and the longer part (a) divided by the smaller part (b)
is equal to the sum of (a) + (b) divided by (a), which both equal 1.618.... with endless decimals
The larger the numbers in the Fibonacci sequence that are used for the quotient, the more accurate the result

Write a Programm that calculates the golden ratio from the Fibonacci sequence
giving as input the largest number in the Fibonacci sequence to be used for the quotient
Hint: create first a class Fibonacci that iterate over the sequence
then create another class Golden_ratio that inherits from Fibonacci

Example Input:
n = 9
Example output:
Fibonacci sequence for 9 as the largest Number in the sequence
1 1 2 3 5 8 13 21 34
Golden Ratio approach:
1.000000
2.000000
1.500000
1.666667
1.600000
1.625000
1.615385
1.619048
1.617647
"""

n = 9


class Fibonacci:
    def __init__(self, max_n):
        self.Max_n = max_n
        self.N = 0
        self.A = 0
        self.B = 0

    def __iter__(self):
        self.N = 0
        self.A = 0
        self.B = 1
        return self

    def __next__(self):
        if self.N < self.Max_n:
            self.N += 1
            self.A, self.B = self.B, self.A + self.B
            return self.A
        else:
            raise StopIteration
            
class Golden_ratio(Fibonacci):
    def __next__(self):
        Fibonacci.__next__(self)
        return self.B / self.A


print(f"Fibonacci sequence for {n} as the largest Number in sequence")
for f in Fibonacci(n):
    print(f, end=" ")
print("\nGolden Ratio approach:")
for g in Golden_ratio(n):
    print(f"{g:.6f}")