Ad
Code
Diff
  • def even_or_odd(n):
        return 'Even' if n % 2 == 0 else 'Odd'
    • def even_or_odd(n):
    • return 'Even' if n ^ 1 == n + 1 else 'Odd'
    • return 'Even' if n % 2 == 0 else 'Odd'

This is the McCarthy 91 function. It's pretty cool see if you can reduce it any further.

McCarthy 91 Function info: https://en.wikipedia.org/wiki/McCarthy_91_function

def f(n): return n - 10 if n > 100 else f(f(n + 11))

If you're just going to print the output then.

Code
Diff
  • def multiplica(a, b): print(a * b)
    multiplica(4, 5)
    • def multiplica(a, b):
    • c = a * b
    • return c
    • print(multiplica(4, 5))
    • def multiplica(a, b): print(a * b)
    • multiplica(4, 5)

Just a simple FizzBuzz funtion that all you have to do is change 3 with fizz and 5 with buzz in (i % 3 == 0) and (i % 5 == 0).

And for the people who do not understand what an 'iteration' is or what a for loop does. A for loop such as: 'for i in range(10)' will loop through the code you put inside the loop 10 times. You can also change it to such as 'for i in range(2, 9)' to be more specific with your numbers. Another option is to do something like 'for i in range(1, 10, 2)' will increment by '2' each time instead of the defualt of '1'.

In this example 'for i in range(1, seq + 1)' we are adding one to 'seq' since the range() function only goes upto the numebr below the one you input. So we have to add one since we are incrementing by one.

And just in case I just boggled your mind even more about iterating, you should check out https://www.geeksforgeeks.org/python-range-function/ for a better explanation than mine.

Code
Diff
  • def fizz_buzz(fizz, buzz, seq):
        for i in range(1, seq + 1):
            print('Fizz' * (i % fizz == 0) + 'Buzz' * (i % buzz == 0) or i)
        return '' #Gets rid of 'None' at the end of iterating
        
    • def fizz_buzz(fizz, buzz, seq):
    • ... # your code
    • for i in range(1, seq + 1):
    • print('Fizz' * (i % fizz == 0) + 'Buzz' * (i % buzz == 0) or i)
    • return '' #Gets rid of 'None' at the end of iterating

Heck you could even do this.

Code
Diff
  • muliplica = lambda a, b: print(a * b)
    muliplica(4, 5)
    
    • def multiplica(a, b):
    • return a * b
    • print(multiplica(4, 5))
    • muliplica = lambda a, b: print(a * b)
    • muliplica(4, 5)

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()

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