blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
b8249eb22ca2d1e4dec22d44de686846008854d7 | atomextranova/leetcode-python | /High_Frequency/Data Structures/Union Find/Number of Islands II/union_find.py | 1,656 | 3.875 | 4 | """
Definition for a point.
class Point:
def __init__(self, a=0, b=0):
self.x = a
self.y = b
"""
class Solution:
"""
@param n: An integer
@param m: An integer
@param operators: an array of point
@return: an integer array
"""
def numIslands2(self, n, m, operators):
# write your code here
self.initialize(n * m)
islands = set()
results = []
DIR = [(0, 1), (1, 0), (-1, 0), (0, -1)]
for operator in operators:
x, y = operator.x, operator.y
if (x, y) in islands:
results.append(self.size)
continue
islands.add((x, y))
self.size += 1
index = self.pos_to_index(x, y, m, n)
for dx, dy in DIR:
new_x = x + dx
new_y = y + dy
if (new_x, new_y) in islands:
new_index = self.pos_to_index(new_x, new_y, m, n)
self.union(index, new_index)
results.append(self.size)
return results
def initialize(self, count):
self.fathers = [i for i in range(count)]
self.size = 0
def pos_to_index(self, x, y, m, n):
return x * m + y
def find(self, i):
path = []
while self.fathers[i] != i:
path.append(i)
i = self.fathers[i]
for p in path:
self.fathers[p] = i
return i
def union(self, i, j):
if i == j:
return
a = self.find(i)
b = self.find(j)
if a != b:
self.fathers[a] = b
self.size -= 1
|
7b1775cc8f7e406e088de829126e3160b5404266 | carlosjoset/data-science-desafio | /1-modulo-Intro-Python/ciclos/desafios/sumatorias/calculadora.py | 1,123 | 4.03125 | 4 | # calculadora.py : Crear un programa que permita ingresar de 4 opciones, identificadas con un
# número (1: sumar, 2: restar, 3: multiplicar, 4: dividir). Luego el usuario debe ingresar 2 números, sobre
# los cuales se realice la operación escogida. El programa debe mostrar el resultado.
option = None
options = ['1', '2', '3', '4']
while option not in options:
print("Eliga una opción: \n")
print("\t1: sumar\n")
print("\t2: restar\n")
print("\t3: multiplicar\n")
print("\t4: dividir\n")
option = input("Ingrese la opción elegida: ")
number_1 = int(input("Ingrese el primero número: "))
number_2 = int(input("Ingrese el segundo número: "))
result = 0
if option == '1':
result = number_1 + number_2
elif option == '2':
result = number_1 - number_2
elif option == '3':
result = number_1 * number_2
elif option == '4':
try:
result = number_1 / number_2
except ZeroDivisionError:
result = None
print("No es posible dividir por 0")
if result != None:
print(f"El resultado es {result}")
# Ver online en: https://repl.it/@lporras/calculadorapy
|
99c4237a54103df0dfa9a6a3e6c54115b19c0904 | Villtord/python-course | /src/16 Scientific Libraries/03 Pandas/02_selection.py | 2,237 | 4 | 4 | import pandas as pd
import pylab as pl
pd.set_option('display.precision', 1)
pd.set_option('display.width', None) # None means all data displayed
pd.set_option('display.max_rows', None)
def inspect(item):
print()
print(item)
print(type(item))
print("------------------")
def main():
df = pd.read_csv("data/sample.csv",
skipinitialspace=True,
index_col=0)
print(df)
# some standard dataframe methods
# the index
inspect(df.index)
# the column headings
inspect(df.columns)
print(type(df.columns))
# the values of the dataset
inspect(df.values)
inspect(df.values[0])
inspect(df.values[0, 0])
print(list(df.index)) # convert index to a list
print(list(df.columns)) # convert columns to a list
# extracting a single column can create a new dataframe or a series
a = df[['County']] # list parameter => returns a dataset
print(f"{df[['County']]} returns: \n\t{type(a)}")
b = df['County'] # scalar parameter => returns a series
print(f"df['County'] returns: \n\t{type(b)}")
# using .loc
# loc uses the index of the dataset. A lot of datasets have an index of
# integers, but the index can be any data type, often str
# print 1 row
inspect(df.loc['Peter']) # loc uses index
# print several rows
inspect(df.loc['Peter':'Bill'])
# selecting rows and columns
inspect(df.loc[['Peter', 'Bill'], ['County', 'Height', 'Weight']])
inspect(df.loc[:, ['County', 'Gender']]) # all rows, some columns
inspect(df.loc[['Bill'], ['County']]) # 1 row, 1 column, two sets of []
inspect(df.loc['Bill', 'County']) # only 1 set of []
# remind ourselves of the complete dataframe
print(df)
# using iloc
# iloc uses the numerical index of the dataset, starting with item 0
inspect(df.iloc[3]) # select row 3 as series
inspect(df.iloc[[3, 6, 2, 4]]) # select multiple rows
inspect(df.iloc[3, 2]) # select row and column
# convert the index to a regular column
# the new index will be numerical
df.reset_index(inplace=True)
print(df)
main()
|
574f8500c2fda3cc81a14616d4b7a7ba7420c956 | gugajung/guppe | /fixação/Seção04/11-20/Sec04Ex13.py | 149 | 3.5 | 4 | velKMH = float(input("Entre com a Velocidade em KM/H :-> "))
velMilhas = velKMH / 1.6
print(f"E a velocidade em Milhas/hora :-> {velMilhas:.2f}")
|
f84b0f03e2af4b8e15c7aab4b09a52ca7ec13ac5 | MineRobber9000/perth | /perth/implementations.py | 456 | 3.640625 | 4 | class PerthError(Exception):
pass;
class Stack:
def __init__(self):
self.sp = -1
self.values = []
def __iter__(self):
return self
def pushVal(self,v):
self.values.append(v)
self.sp += 1
def popVal(self):
if self.sp == -1:
raise PerthError("Can't pop value from empty stack!")
ret = self.values.pop(self.sp)
self.sp -= 1
return ret
def next(self):
try:
return s.popVal()
except PerthError as e:
raise StopIteration
|
3c0f84d412ac77bf2bd092e956072e6ea92f280f | BreezeDawn/LeetCode | /first/字符串/简单/521. 最长特殊序列 Ⅰ.py | 291 | 3.515625 | 4 | class Num521(object):
def leetcode(self, a, b):
# 这是脑筋急转弯吧!
if a == b:
return -1
else:
return max(len(a), len(b))
def main():
tmp = Num521.leetcode("aba", "cdc")
print(tmp)
if __name__ == '__main__':
main()
|
fba0a32cea1970032ad2ac22d412e7457eb20e95 | CalicheCas/IS211_Assignment10 | /query_pets.py | 1,675 | 3.59375 | 4 | #! src/bin/python3
# -*- coding: utf-8 -*-
import sqlite3
def query_engine(con):
with con:
while True:
entry = int(input("Please enter a person ID: "))
if entry == -1:
break
cur = con.cursor()
cur.execute("SELECT * FROM person WHERE id=:id", {"id": entry})
data = cur.fetchone()
# If user is found
if data != None:
fn = data[1]
ln = data[2]
age = data[3]
print("{} {}, {} years old".format(fn, ln, age))
cur.execute("SELECT pet_id FROM person_pet WHERE person_id=:id", {"id": entry})
vals = cur.fetchall()
for p in vals:
pet_id = p[0]
cur.execute("SELECT * FROM pet WHERE id=:id", {"id": pet_id})
pet = cur.fetchone()
pname = pet[1]
breed = pet[2]
page = pet[3]
dead = pet[4]
if dead == 1:
print("{} {} owned {}, a {} that was {} years old.".format(fn, ln, pname, breed, page))
else:
print("{} {} owns {}, a {} that is {} years old.".format(fn, ln, pname, breed, page))
else:
print("Error, person not found")
if __name__ == '__main__':
conn = None
try:
conn = sqlite3.connect('pets.db')
except sqlite3.Error as error:
print("Failed to establish database connection. Error: {}".format(error))
query_engine(conn)
if conn:
conn.close()
|
55fcd6200732ecc00b950ac93c03ae1828b21d8f | dim4o/python-samples | /graph-algorithms/11-dijkstra-shortest-path-no-heap.py | 6,921 | 4.21875 | 4 | """
This is an intuitive implementation of Dijkstra shortest path algorithm without
minimum binary heap + map. It is not so effective but is easier to understand.
"""
class Graph:
""" An util data structure that represents a graph """
def __init__(self, edges, undirected=True):
self.edges_map = {}
self.adj_map = {}
self.vertices_set = set()
for edge in edges:
self.edges_map[(edge[0], edge[1])] = edge[2]
if undirected:
self.edges_map[(edge[1], edge[0])] = edge[2]
if edge[0] not in self.adj_map:
self.adj_map[edge[0]] = []
self.adj_map[edge[0]].append(edge[1])
if undirected:
if edge[1] not in self.adj_map:
self.adj_map[edge[1]] = []
self.adj_map[edge[1]].append(edge[0])
self.vertices_set.add(edge[0])
self.vertices_set.add(edge[1])
def get_weight(self, vertex1, vertex2):
""" Gets the weight of edge that starts with vertex1 and end with vertex2"""
return self.edges_map[(vertex1, vertex2)]
def get_adj_vertices(self, vertex):
""" Gets a list of all adjacent vertices of a given vertex """
return self.adj_map.get(vertex)
def get_all_vertices(self):
""" Gets a set from all vertices """
return self.vertices_set
graph_edges_1 = [
("A", "B", 6),
("A", "D", 1),
("B", "D", 2),
("B", "C", 5),
("B", "E", 2),
("C", "E", 5),
("D", "E", 1),
]
graph_edges_2 = [
("A", "B", 5),
("A", "D", 9),
("A", "E", 2),
("B", "C", 2),
("C", "D", 3),
("F", "D", 2),
("E", "F", 3),
]
def find_shortest_path(edges_list, start_vertex):
"""
Finds the shortest path from a vertex to all other vertices of graph using Dijkstra algorithm
:param edges_list: a list of edges represented as tuples: (vertex1, vertex2, weight)
:param start_vertex: the entry point of the algorithm
:return: a map with the final result in format { vertex: {'dist': dist, 'prev_vertex': prev} }
"""
# Preparation - init all data structures
graph = Graph(edges_list)
distances = {} # { vertex: {'dist': dist, 'prev_vertex': prev} }
visited_set = set()
unvisited_set = graph.get_all_vertices()
inf = float("inf")
result = {} # { vertex: {'dist': dist, 'prev_vertex': prev} }
# Populate distances: assigns infinity for all distances and 0 to the start vertex
vertices = graph.get_all_vertices()
for adj_vertex in vertices:
distances[adj_vertex] = {"dist": inf, "prev_vertex": None}
distances[start_vertex] = {"dist": 0, "prev_vertex": None}
# While the unvisited set is not empty repeat:
current_vertex = start_vertex
while unvisited_set:
adj_vertices = graph.get_adj_vertices(current_vertex)
# repeats for all adjacent vertices
for adj_vertex in adj_vertices:
# if the adjacent vertex is not visited and the calculated new distance
# is smaller than the old one - assign the smaller distance to the
# corresponding distance map value
if adj_vertex not in visited_set:
new_weight = distances[current_vertex]["dist"] + graph.get_weight(current_vertex, adj_vertex)
old_weight = distances[adj_vertex]["dist"]
if new_weight <= old_weight:
distances[adj_vertex]["dist"] = new_weight
distances[adj_vertex]["prev_vertex"] = current_vertex
# marks the current node as visited and removes it from unvisited set
visited_set.add(current_vertex)
unvisited_set.remove(current_vertex)
# removes the current node from distances map and add it to the result map
result[current_vertex] = distances.pop(current_vertex)
# if the unvisited set is not empty: assigns the vertex with minimum
# distance to the current node
if unvisited_set:
min_dist_item = min(distances.items(), key=lambda x: x[1]["dist"])
current_vertex = min_dist_item[0]
return result
def get_path_to(end, result):
path = []
curr = end
while True:
path.append(curr)
curr = result[curr]["prev_vertex"]
if not curr:
break
return list(reversed(path)), result[end]["dist"]
# the shortest path from "A" all other vertices
shortest_path_map = find_shortest_path(edges_list=graph_edges_1, start_vertex="A")
# prints the shortest path and distance form "A" to "C"
shortest_pat = get_path_to("C", shortest_path_map)
print(" -> ".join(shortest_pat[0]) + ", dist: {}".format(shortest_pat[1])) # A -> D -> E -> C, dist: 7
# the shortest path from "A" all other vertices
shortest_path_map = find_shortest_path(edges_list=graph_edges_2, start_vertex="A")
# prints the shortest path and distance form "A" to "D"
shortest_pat = get_path_to("D", shortest_path_map)
print(" -> ".join(shortest_pat[0]) + ", dist: {}".format(shortest_pat[1])) # A -> E -> F -> D, dist: 7
# for key, value in g.edges_map.items():
# print(key, value)
#
# for key, value in g.adj_map.items():
# print(key, value)
#
# print(g.get_weight("E", "D"))
#
# print(g.get_weight("B", "C"))
# print(g.get_weight("C", "B"))
#
# print(g.get_all_vertices())
#
# s = g.get_all_vertices()
#
# s.remove("B")
# print(s)
# print(g.edges_set.get())
#
# s = set()
# graph = (
# # A B C D E
# (0, 6, 0, 1, 0), # A
# (6, 0, 5, 2, 2), # B
# (0, 5, 0, 0, 5), # C
# (1, 2, 0, 0, 1), # D
# (0, 2, 5, 1, 0), # E
# )
#
# visited = []
# unvisited = []
# inf = float('inf')
# distances = {}
# result = []
# start_node = 0
#
# for i in range(0, len(graph)):
# distances[i] = inf
# unvisited.append(i)
#
# distances[start_node] = 0
#
# # print(distances)
# # print(unvisited)
#
#
# curr_node = start_node
#
# while True > 0:
#
# for next_node in range(0, len(graph[curr_node])):
#
# curr_edge_value = graph[curr_node][next_node]
#
# if curr_edge_value > 0 and next_node in unvisited:
# next_node_value = curr_edge_value + distances[curr_node]
#
# # print("distances", distances)
# # print("curr_node", curr_node)
# # print("next_node", next_node)
# if next_node_value <= distances[next_node]:
# distances[next_node] = next_node_value
#
# visited.append(curr_node)
# # print(curr_node)
# # print(unvisited)
# unvisited.remove(curr_node)
# result.append((curr_node, distances[curr_node]))
# distances.extract_min(curr_node)
#
# if len(unvisited) == 0:
# break
#
# min_pair = min(distances.items(), key=lambda x: x[1])
# print(distances.items())
# curr_node = min_pair[0]
#
# print("Result", result)
# # Result [(0, 0), (3, 1), (4, 2), (1, 3), (2, 7)]
|
9a5c7031c81722f2c910d31c5be7c1c2f4925caf | choroba/perlweeklychallenge-club | /challenge-181/lubos-kolouch/python/ch-1.py | 906 | 3.765625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def order_sentence(paragraph: str) -> str:
sentences = paragraph.split(".")
ordered = []
for sentence in sentences:
if sentence.strip() == "":
continue
words = sorted(sentence.split())
ordered.append(" ".join(words) + ".")
return " ".join(ordered)
# Tests
assert (
order_sentence("All he could think about was how it would all end.")
== "All about all could end he how it think was would."
)
assert (
order_sentence(
"There was still a bit of uncertainty in the equation, but the basics were there for anyone to see."
)
== "There a anyone basics bit but equation, for in of see still the the there to uncertainty was were."
)
assert (
order_sentence("The end was coming and it wasn't going to be pretty.")
== "The and be coming end going it pretty to was wasn't."
)
|
679ca0421f6e3536f2fd51cb68fa7977a66120b0 | alexlewis20/Sydney-property-adventure | /python/get_suburb_sales.py | 872 | 3.625 | 4 | import urllib
import os
import csv
CWD = os.getcwd()
def prep_name(suburb_human):
"""Convert human readable suburb name and convert for url."""
s = suburb_human.upper()
s = str.split(s)
s = '%20'.join(s)
return s
def save_csv(suburb, postcode):
"""Download and save the csv.
Save from NSW government website based on list of
suburbs file.
"""
base_url = "http://maps.six.nsw.gov.au/csv/current/suburb/"
full_url = base_url + prep_name(suburb) + "_" + str(postcode) + ".csv"
save_path = CWD + "/data/" + suburb + ".csv"
save = urllib.URLopener()
save.retrieve(full_url, save_path)
return save_path
with open("reference/suburbs_list.csv") as csvfile:
suburb_list = csv.reader(csvfile, delimiter=",")
for row in suburb_list:
print save_csv(row[0], row[1])
print("Complete")
csvfile.close()
|
0e8e9a7756b46806a2a2fc482c4aae591fb4b909 | L-iness/L3_Charpak_Theorie_Graphes | /deg.py | 986 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 7 17:27:46 2019
@author: tinou
"""
import numpy as np
import math
n = int(input("Taille du graphe: "))
m = np.zeros((n,n))
for i in range(n):
for j in range(n):
v = 2
while ((v != 0) and (v != 1)):
print("m[{0},{1}] = ".format(i,j), end=" ")
v = int(input())
#v = int(input("m[{0},{1}] = ".format(i,j)))
if ((v != 0) and (v != 1)):
print("La valeur doit être 0 ou 1")
else :
m[i,j] = int(v)
print('\n'.join([''.join(['{:2d}'.format(int(item)) for item in row]) for row in m]))
#degre
deg_in = np.zeros((n))
deg_out = np.zeros((n))
for i in range(n):
for j in range(n):
deg_in[i] += m[i,j]
deg_out[j] += m[i,j]
for i in range(n):
print(f"Sommet{i+1}: degre >= {int(deg_in[i])} degre <= {int(deg_out[j])}")
deg = np.zeros((n))
for i in range(n):
deg[i] = deg_in[i] + deg_out[i]
print
|
7d541289b7a2195f17a339d7ec75ecb8ecedc0cb | dezcalimese/nucamp-bootcamp | /1-Fundamentals/week5/workshop5.py | 2,068 | 4.28125 | 4 | import random
def guess_random_number(tries, start, stop):
random_number = random.randint(start, stop)
while tries != 0:
print("Number of tries remaining: ", tries)
guessing = int(input("Guess a number between 0 and 10: "))
if guessing == random_number:
print("You guessed the correct number!")
break
elif guessing < random_number:
print("Guess higher!")
tries -= 1
elif guessing > random_number:
print("Guess lower!")
tries -= 1
else:
break
print("You have failed to guess the number:", random_number)
guess_random_number(5, 0, 10)
def guess_random_num_linear(tries, start, stop):
random_number = random.randrange(start, stop)
print("The number for the program to guess is:", random_number)
print("Number of tries left:", tries)
for num in range(start, stop):
print("The program is guessing...", num)
if num == random_number:
print("The program has guessed the correct number!")
return
else:
tries -= 1
print("Number of tries left:", tries)
if tries == 0:
print("The program has failed to guess the correct number.")
return
guess_random_num_linear(5, 0, 10)
def guess_random_num_binary(tries, start, stop):
random_number = random.randrange(start, stop)
print("Random number to find:", random_number)
lower_bound = start
upper_bound = stop
while tries != 0:
pivot = (lower_bound + upper_bound) // 2
if pivot == random_number:
print("Found it!", random_number)
return
elif pivot > random_number:
print("Guessing higher!")
upper_bound = pivot - 1
tries -= 1
else:
print("Guessing lower!")
lower_bound = pivot + 1
tries -= 1
if tries == 0:
print("Your program failed to find the number.")
guess_random_num_binary(5, 0, 100)
|
b98cb0dde7f72a6aa01f0e4069a220cb40977b71 | FadelBerakdar/OSTpythonCourse | /Python3/04_RegularExpression/patternTest.py | 848 | 3.703125 | 4 | import re
"""
patternTest.py Allows the checking of various patterns and target strings
"""
while True:
pattern = input("Pattern: ")
if not pattern:
break
while True:
string = input("Target: ")
if not string:
break
mm = re.match(pattern, string)
if mm:
print("Match : matched {0!r}".format(string[mm.start():mm.end()]))
print("Match : groups:", mm.groups())
print("Match : gdict :", mm.groupdict())
else:
print("Match : no match")
ms = re.search(pattern, string)
if ms:
print("Search: matched {0!r}".format(string[ms.start():ms.end()]))
print("Search: groups:", ms.groups())
print("Search: gdict :", ms.groupdict())
else:
print("Search: no match")
|
110e4c4de294395815add00dfb5085da98e23cad | funandeasyprogramming/python_tutorial_for_beginners | /list/list.py | 1,046 | 4.28125 | 4 | # list
# 1. can hold various different data types
# 2. order is maintained
# 3. elements in the list are mutable
# list_one = ["Danny", 12, 4.2, 12, [1, 2, "three"]]
#
# print (list_one[4][2])
# print (list_one[:])
# print (list_one[:1])
# print (list_one[2:4])
# print (list_one[2])
# print (list_one[-1])
# print (list_one[-4:-1])
# print (list_one[1:5:2])
# list_one = list()
# list_one = ["Danny", 12, 4.2, 12, [1, 2, "three"]]
#
# list_one[7]
#
# list_one[4][2] = "four"
# print (list_one)
#
# list_one[2] = 5.2
# print (list_one)
#
# list_one[2:4] = [6.2, 15]
# print (list_one)
# list_one = ["Danny", 12, 4.2, 12, [1, 2, "three"]]
#
# # membership operator
# print ("three" in list_one[4])
#
# # len
# print (len(list_one[4]))
list_one = ["Danny", 12, 4.2, 12, [1, 2, "three"]]
# del
# del list_one[2]
# print (list_one)
# del list_one[:4]
# print (list_one)
# del list_one[4][1]
# print (list_one)
list_one = ["Danny", 12, 4.2, 12, [1, 2, "three"]]
list_two = [5, 6, 7]
print (list_one + list_two)
print (list_two * 3)
|
c97e9b39b1c0cd7d0d9f7c18f8d3b9b768fbdd02 | marcosvnl/exerciciosPythom3 | /ex101.py | 827 | 4.21875 | 4 | # Exercício Python 101: Crie um programa que tenha uma função chamada voto()
# que vai receber como parâmetro o ano de nascimento de uma pessoa,
# retornando um valor literal indicando se uma pessoa tem
# voto NEGADO, OPCIONAL e OBRIGATÓRIO nas eleições.
def voto(ano):
"""
Analize de permissão do voto no Brasil
:param ano: ano de nascimento
:return: se está em situação de NEGADO, OPCIONAL e OBRIGATÓRIO
"""
from datetime import date
atual = date.today().year
idade = atual - ano
if idade < 16:
return f'Com {idade} anos, não é permitido votar!'
elif 16 <= idade < 18 or idade > 65:
return f'Com {idade} anos, o voto é opcial!'
else:
return f'Com {idade} anos, é orbigatório votar!'
a = int(input('Ano de nascimento: '))
print(voto(a))
|
b6b45a63ed03f51a6ff0b0a70f24fba406a05fdf | pstorozenko/YP2018-PythonPodstawy | /Zajecia3/Grupa2/wstep.py | 957 | 3.6875 | 4 | # Zad 1
print(2 * 7 * 722287)
# Zad 2
b1 = int(input("Podaj długość 1. boku"))
b2 = int(input("Podaj długość 2. boku"))
b3 = int(input("Podaj długość 3. boku"))
if b1 + b2 > b3 and b2 + b3 > b1 and b1 + b3 > b2:
print("Odcinki", b1, b2, b3, "mogą tworzyć trójkąt")
# Zad 3
zespol = input("Jaki jest Twój ulubiony zespół?")
print("WIWAT", zespol.upper())
# Zad 4
imie = input("Jak masz na imię? ")
if imie.endswith("a") and imie.lower() != "kuba":
print("Dzień dobry Pani")
else:
print("Dzień dobry Panu")
# Zad 5
odp = input("Jak ma na nazwisko prowadzący zajęcia? ")
if odp.lower() == 'storożenko':
print("Tak jest!")
else:
print("Niestety zła odpowiedź")
# Zad 6
skala = input("Podaj z jakiej skali chcesz zmienić temperaturę C/F")
temp = int(input("Jaką temperaturę chcesz zamienić?"))
if skala == "C":
print("Temperatura w *F", temp*9/5 + 32)
else:
print("Temperatura w *C", (temp- 32)*5/9) |
f8e9d956b122cff2757939034f5f104789cdd250 | saravana14596/saro_python | /Learning/5nums.py | 112 | 3.828125 | 4 | l = []
n = 5
print("Enter 5 numbers:")
s = set()
while len(s)<5:
num = int(input())
s.add(num)
print(s)
|
536bb9a9ad9df366c8c98c499cdb3b8af586a16f | Villix-Main/Python-Portfolio | /src/PythonLessons/lambdas.py | 915 | 3.515625 | 4 | from functools import reduce
addFunc = lambda x, y: x + y
print(addFunc(5, 5))
strLenStripped = lambda str: len(str.strip())
print(strLenStripped(" DM"))
def send_to_database(data, endFunc):
print(f"Sending {data} to database...")
print("Sent data to database")
endFunc('passed')
name = ''
send_to_database("some stuff", lambda result: print(f"the result is {result}"))
points2D = [(1, 2), (15, 1), (5, -1), (10, 4)]
# points2D_sorted = sorted(points2D, key=lambda x: x[1])
points2D_sorted = sorted(points2D, key=lambda x: sum(x))
print(points2D)
print(points2D_sorted)
nums = [1, 2, 3, 4, 5]
nums2 = map(lambda x: x*3, nums)
print(list(nums2))
moreNums = [x*4 for x in nums]
print(moreNums)
# moreNums = filter(lambda x: x%2==0, nums)
moreNums = [x for x in nums if x%2==0]
print(moreNums)
nums = [2, 2, 3, 3]
product_a = reduce(lambda x,y: x*y, nums)
print(product_a)
|
e8df52caf6f6b9ef7e33fb662a25c138a5144e94 | rhoowd/simple_sim | /guiObjects.py | 3,129 | 3.53125 | 4 | # Simple_simulator guiObjects
# Wan Ju Kang
# Dec. 1, 2017
# ----------------------------------------------------------------
# Purpose of Simple Simulator guiObjects is to provide abstraction
# for the drawn target and drones on the Simple Simulator Canvas.
# To use guiObjects, make an instance and blit it on a surface.
# ----------------------------------------------------------------
import pygame
from math import cos, sin, pi
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
ORANGE = (255, 100, 0, 128)
BLUE = (0, 128, 255, 128)
class guiTarget():
def __init__(self, xi = 1, yi = 1, zi = 10, tr = 10):
# Take initial (x, y, z, radius) as argument
self.x = xi
self.y = yi
self.z = zi
self.tr = tr
self.a = None # Not used
self.name = "target"
# Label the target
self.color = ORANGE
self.fs = 15 # font size
self.font = pygame.font.SysFont(pygame.font.get_default_font(), self.fs)
self.text = "T"
self.label = self.font.render(self.text, True, BLACK)
def setup(self, sx = 20, sy = 20):
# Set up target's surface
self.sx = sx
self.sy = sy
self.surface = pygame.Surface((self.sx, self.sy), pygame.SRCALPHA)
self.surface = self.surface.convert_alpha()
class guiDrone():
def __init__(self, xi = 1, yi = 1, zi = 10, ai = 0, drone_id = 0):
# Take initial (x, y, z, yaw, drone_id) as argument
self.x = xi
self.y = yi
self.z = zi
self.a = ai
self.drone_id = drone_id
self.name = "drone" + str(drone_id)
# Label the drone
self.body_color = BLUE
self.eye_color = BLACK
self.fs = 15 # font size
self.font = pygame.font.SysFont(pygame.font.get_default_font(), self.fs)
self.text = str(drone_id)
self.label = self.font.render(self.text, True, BLACK)
# Misc.
self.eye_size = 0.4
def setup(self, sx = 25, sy = 25):
# Set up drone's surface
self.sx = sx
self.sy = sy
self.surface = pygame.Surface((self.sx, self.sy), pygame.SRCALPHA)
self.surface = self.surface.convert_alpha()
class guiCameraView():
def __init__(self, ci = (0, 0), si = 20, vx = 64, vy = 64, view_id = 0):
# Take initial dimensions of view screen and target position on camera view
self.center = ci
self.size = si
self.vx = vx
self.vy = vy
self.view_id = view_id
self.name = "view" + str(view_id)
# Label the camera view
self.fs = 20 # font size
self.font = pygame.font.SysFont(pygame.font.get_default_font(), self.fs)
self.text = "Drone " + str(view_id)
self.label = self.font.render(self.text, True, BLACK)
def setup(self, sx = 128, sy = 128):
# Set up camera view's surface
self.sx = sx
self.sy = sy
self.border_thickness = 5
self.border_color = (0, 0, 0, 128)
self.surface = pygame.Surface((self.sx, self.sy), pygame.SRCALPHA)
self.surface = self.surface.convert_alpha()
|
eac1d0d68fbca16018aaaaadff4538fcba5ccfd0 | radkovskaya/Algorithms | /les4/task1_1.py | 1,173 | 4.21875 | 4 | # Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран. Например, если введено число 3486, то надо вывести число 6843.
def func_var1(x):
n = x
count = 0
z = 0
while n > 0:
n = n // 10
count += 1
while count > 0:
a = x % 10
y = a * 10 ** (count - 1)
z += y
x = x // 10
count -= 1
return z
#100 loops, best of 5: 2.19 usec per loop - Трехзначное число
#100 loops, best of 5: 3.81 usec per loop - Шестизначное число
#100 loops, best of 5: 8.33 usec per loop - Десятизначное число
#100 loops, best of 5: 16.1 usec per loop - Двадцатизначное число
# Линейный алгоритм, сложность алгоритма возрастает пропорционально количеству цифр в числе. Время работы на десятизначном числе в 2 раза меньше, чем на двадцатизначном.
|
30656bb985a5012ffffe0b84dce70a605688314f | ByBogon/algorithms-python | /src/basic/combi.py | 566 | 3.765625 | 4 | """
n개의 서로 다른 원소에서 m개를 택하는 경우의 수
"""
from math import factorial as f
def combi(n, m):
return f(n) / (f(m) * f(n - m))
"""
재귀적 방법으로.
효율성 측면에서는 n이 커지면 함수가 여러번 호출 됨으로써, 효율적이지 않음.
그러나 사람이 생각하는 방식과 비슷해서 쓸모있는 경우가 많음.
"""
def combi_recursion(n, m):
if n == m:
return 1
elif m == 0:
return 1
else:
return combi_recursion(n - 1, m) + combi_recursion(n - 1, m - 1) |
2deaea5c93edbfe9d829565faf0cabc1aa057e53 | HeartingU/PythonEx | /pyEx/3/num-opration.py | 250 | 3.9375 | 4 | """
数字类型
"""
# 整形int
age = 18
print(type(age))
# 浮点型float
a = 1.2
print(type(a))
print(type(int(a)))
# 赋值运算
# 加:+=
# 减:-=
# 乘法*=
# 除法/=
n = 2
n = n + 1
print(n)
n = 2
n += 1
print(n)
|
40edeb22dc3e85b4201777f88a40d2b592fd1a51 | vikassry/pyWorkspace | /PE/source/find_LCM.py | 915 | 3.515625 | 4 | from prime_factors import generate_prime_factors_of, give_prime_numbers_upto
from functools import reduce
def get_all_prime_factors_of_numbers_for_range(start, limit):
return [generate_prime_factors_of(x) for x in range(start, limit+1)]
def get_highest_power_for(prime, primes_list):
highest_power = 0
for primes in primes_list:
count = primes.count(prime)
highest_power = highest_power<= count and count or highest_power
return highest_power
def find_lcm_for_range(start, end):
if start == end:
return start
lcm_dividers = []
prime_numbers = give_prime_numbers_upto(end+1)
all_prime_factors = get_all_prime_factors_of_numbers_for_range(start, end)
for prime in prime_numbers:
highest_number_of_factor = get_highest_power_for(prime, all_prime_factors)
lcm_dividers.append(prime ** highest_number_of_factor)
return reduce(lambda x,y : x * y, lcm_dividers)
# print(find_lcm_for_range(1, 20)) |
410b59b466a5769e26b7620d52485e33fcfa954a | GiseleViedenhelfen/ExerciciosPython | /pacote download/lista-exercicios/EX055.py | 751 | 3.828125 | 4 | #Faça um programa que leia o peso de cinco pessoas.
#No final, mostre qual foi o maior e o menor peso lidos.
maior = 0
menor = 0
#nesses casos percebo que sempre vai precisar atribuir valores
#ao que desejo pra ser possível fazer os if's dentro do laço...
for c in range(1, 6):
peso = float(input('Digite o seu peso em kg:'))
if c == 1: #se for a primeira pessoa
maior = peso
menor = peso
else: #se não for a primeira pessoa
if peso > maior:
maior = peso #se essa pessoa for mais pesada que a primeira, o peso dela é atribuído a 'maior'
elif peso < menor:
menor = peso #mesma ideia do anterior
print('O maior peso foi {:.1f}kg e o menor peso foi {:.1f}kg'.format(maior, menor)) |
b458e62954e2b867a93f7ad15ab45fa694567999 | Vinisha-Govind-Gomare/Python-Essentials-Day2-Assignment | /main.py | 214 | 4.15625 | 4 | number=int(input("Enter the number:"))
total= 0
value= 1
while(value<=number):
total=total+value
value=value+1
print("The Sum of natural numbers from 1 to {0}= {1}".format(number,total))
|
fb4870c31d229ee0b4e0e6aad099723193feccb6 | ctd1077/Blackjack | /BlackJack.py | 7,018 | 3.53125 | 4 | #!/usr/bin/env python3
# BlackJack Game
# By: Cambron Deatherage
import pandas as pd
import random
import time
suit = ['Hearts', 'Spades', 'Clubs', 'Diamonds']
cards = pd.Series(['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q',
'K', 'A'])
class Player():
'''Parent Class Player'''
def __init__(self):
self.score = 0
class HumanPlayer(Player):
'''Child Class HumanPlayer'''
def __init__(self):
Player.__init__(self)
def deal(self, lst):
deal = deal_Card(lst)
return deal
def point(self, card):
point = points(card)
self.score += point
return point
class Dealer(Player):
'''Child Class ComputerPlayer'''
def __init__(self):
Player.__init__(self)
def deal(self, lst):
deal = deal_Card(lst)
return deal
def point(self, card):
point = points(card)
self.score += point
return point
def new_deck():
'''A fucntion to create a new deck of cards'''
# deck = pd.concat({'Hearts':Hearts,'Spades':Spades,'Clubs':Clubs,
# 'Diamonds':Diamonds}, axis=1)
lst = []
return lst
def deal_Card(lst):
''' This function deals a card, one card at a time
and keeps track of cards played in a deck
With out all the Debugging print statements'''
global card
played = False
while played is False:
card = random.choice(cards)
select_suit = random.choice(suit)
tup = (select_suit, card)
if tup in lst:
played = False
if len(lst) > 51:
played = True
print('Deck is empty')
break
continue
else:
lst.append((select_suit, card))
played = True
break
return card, select_suit
def points(card):
''' This function decides if the card varible can be dtype of int
if so then the point value is the value of the card
if it is a str then it's a face card
if Ace then 11 points else all other face cards are 10 points'''
try:
card = int(card)
point = int(card)
except:
card = str(card)
if card == 'A':
point = 11
else:
point = 10
return point
class Game():
def __init__(self):
self.p1 = HumanPlayer()
self.p2 = Dealer()
self.player_cards = []
self.dealer_cards = []
def start_Game(self):
p1 = self.p1.deal(lst)
self.player_cards.append(p1)
self.p1.point(card)
time.sleep(2)
print('Player gets the first card: ', self.player_cards)
p2 = self.p2.deal(lst)
self.dealer_cards.append(p2)
self.p2.point(card)
time.sleep(2)
print('Dealer gets first card face down ')
p1 = self.p1.deal(lst)
self.player_cards.append(p1)
self.p1.point(card)
time.sleep(2)
print('Player gets the second card: ', p1)
p2 = self.p2.deal(lst)
self.dealer_cards.append(p2)
self.p2.point(card)
time.sleep(2)
print('Dealer gets second card: ', self.dealer_cards[1])
win = False
if self.p1.score == 22:
print('Two aces will be played as a soft hand:')
self.p1.score == 12
elif self.p1.score == 21:
print('BlackJack!')
print('Congradulations you win!')
win = True
time.sleep(2)
print('Your hand is : ', self.player_cards, 'for a total of ',
self.p1.score, 'points')
time.sleep(1)
print('The only card the Dealer shows is :', self.dealer_cards[1])
return win
def player_Round(self):
while self.p1.score <= 21:
time.sleep(1)
ans = input('Would you like another card? [Y]es or [N]o? ')
win = False
if ans == 'y':
p1 = self.p1.deal(lst)
self.p1.point(card)
self.player_cards.append(p1)
if self.p1.score <= 21:
print('Your card is: ', p1,)
print('Hand: ', self.player_cards, 'Total points',
self.p1.score)
win = False
continue
elif self.p1.score > 21:
print('Your card is: ', p1)
time.sleep(2)
print('Sorry you bust and dealer wins')
win = True
break
else:
break
return win
def dealer_Round(self):
print('Dealer shows his cards: ', self.dealer_cards)
game = True
if self.p2.score == 22:
time.sleep(2)
print('Two aces will be played as a soft hand for 12 points:')
self.p2.score == 12
elif self.p2.score == 21:
print('21! Dealer wins!')
game = False
win = True
while game is True:
if self.p2.score <= 16:
print('Dealer takes another card: ')
p2 = self.p2.deal(lst)
self.dealer_cards.append(p2)
self.p2.point(card)
time.sleep(2)
print('Dealers card is: ', p2)
game = True
win = False
continue
elif self.p2.score == 21:
time.sleep(2)
print('Dealer has 21 points')
print('Sorry you lose!')
game = False
win = True
break
# Try using just a else statement and see what happens
elif self.p2.score > 21:
time.sleep(2)
print('Dealer has bust!')
print('You Win!')
game = False
win = True
break
else:
time.sleep(2)
print('Dealer stays with ', self.p2.score, ' points')
win = False
break
return win
def wl(self):
if self.p1.score <= self.p2.score:
print('You Lose!')
else:
print('You Win!')
if __name__ == '__main__':
answer = input('Welcome to Blackjack!\n Would you like to play a game?\n\
Enter [Y]es or [N]o:')
answer = answer.upper()
while answer != 'N':
print('Good luck!\n')
lst = new_deck()
print('Dealer shuffles the deck\n')
game = Game()
game.start_Game()
win = game.player_Round()
if win is False:
win = game.dealer_Round()
if win is True:
print('Game Over!')
else:
game.wl()
else:
print('Game Over!')
answer = input('Would you like to play another game:')
answer = answer.upper()
if answer is 'N':
break
print('Thank you and have a great day.')
|
dd238cc984818ae7528c7736bcc4194fab513d4e | Oladejo/Ifecisrg-Assignment | /translator2.py | 4,959 | 3.984375 | 4 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
__author__ = 'group 8'
def checkWordInTheDictionary(word, dictionary):
for position in dictionary:
if word in dictionary[position]:
return dictionary[position][word], position
return None
def PositionOfWord(word):
return word[1]
# for the list of words in my dictionary
myDictionary = {'DET': {'the':'náà', 'that':'náà', 'A':'kan', 'a':'kan','my':'mi','i':'Mo', 'your':'yín','her':'rẹ̀'},
'AUX': {'will':'ni', 'is':'ni', 'was':'ni'},
'NOUN': {'olu':'Olú', 'sola':'Sola','bola':'Bọ́lá','man':'Okùnrin', 'babaloja':'Bàbálọ́jà',
'mango':'máńgòrò', 'yam':'iṣu','square':'Ojúde','trader':'Oníṣòwò','customer':'Oníbàárà',
'shop':'Ìsọ','cloth':'Aṣọ','basket':'Apẹ̀rẹ̀', 'butcher':'Alápatà', 'pepper':'ata',
'money':'Owó', 'sack':'Àpò', 'credit':'Àwìn', 'debtor':'Onígbèsè','carton':'Páálí',
'scale':'Òsùnwọ̀n', 'carrier':'Alábàárù', 'retailer':'Alátùntà', 'banana':'Ọ̀gẹ̀dẹ̀',
'way':'Ọ̀nà', 'path':'Ọ̀nà', 'claypot':'Ìkòkò','woman':'Obìnrin', 'market':'Ọjà',
'wares':'Ọjà','table':'tábìlì', 'shop':'Sọ́ọ̀bù', 'onion':'Àlùbọ́sà', 'tomatoes':'Tòmáàtì',
'paper':'Pépà','alum':'Álọ́ọ̀mù', 'bread':'Búrẹ́dì','Ìyá':'mother','Tola':'Tólá'},
'VERB': {'buy':'rà', 'ate':'jẹ', 'bought':'rà', 'sell':'tà', 'carry':'gbé','carried':'gbé',
'haggle':'ná','sit':'jókòó','sat':'jókòó', 'cut':'gé', 'arranged':'tò','portion':'lé',
'portioned':'lé', 'trek':'rìn', 'hawks':'kiri', 'credit': 'lawin','come':'wá',
'came':'wá','collect':'gba'},
'PREPOSITION': {'on':'sorí', 'behind':'Ẹ̀yìn', 'front':'iwájú', 'centre':'Àárín', 'beside':'Ẹ̀gbẹ́',
'of':' ', 'at':'si','to':''},
'ADJECTIVE': {'very':'dáradára', 'half':'Ìlàjì', 'white':'funfun','whole':'odidi', 'dark':'dúdú',
'unripe':'dúdú', 'very':'gan','four':'merin','reputable':'pataki'}
}
#step 1
def checkMeaning(text, data):
splitSentence = []
for value in text:
if checkWordInTheDictionary(value, myDictionary) is None:
print("Error!!! \n " + "Invalid sentence --> "
+ data + "\n" + "word: " + value + " is not in dictionary.")
exit()
else:
splitSentence.append(checkWordInTheDictionary(value, myDictionary))
return splitSentence
def convertSubject(text, data):
text = checkMeaning(text, data)
for i in range(len(text)-1):
word = text[i]
if PositionOfWord(word) == 'DET' and PositionOfWord(text[i + 1]) == 'ADJECTIVE':
text[i], text[i + 1] = text[i + 1], text[i]
for i in range(len(text)-1):
word = text[i]
if PositionOfWord(word) == 'DET' and PositionOfWord(text[i + 1]) == 'NOUN':
text[i], text[i + 1] = text[i + 1], text[i]
for i in range(len(text)-1):
word = text[i]
if PositionOfWord(word) == 'ADJECTIVE' and PositionOfWord(text[i + 1]) == 'NOUN':
text[i], text[i + 1] = text[i + 1], text[i]
return text
def convertVerb(text, data):
text = checkMeaning(text, data)
return text
#SVO
Predicate = []
Subject = []
Verb = []
Object = []
def parse(text, data):
checkMeaning(text, data)
v = False
b = text
for word in b:
if not v:
if word in myDictionary['DET'] or word in myDictionary['NOUN'] or word in myDictionary['ADJECTIVE']:
Subject.append(word)
elif word in myDictionary['VERB']:
Verb.append(word)
v = True
else:
if word in myDictionary['PREPOSITION']:
Predicate.append(word)
else:
Object.append(word)
SS = convertSubject(Subject, data)
VV = convertVerb(Verb, data)
OO = convertSubject(Object, data)
PP = convertVerb(Predicate, data)
outputsentence = []
for word in SS:
outputsentence.append(word[0] + " ")
for word in VV:
outputsentence.append(word[0] + " ")
for word in PP:
outputsentence.append(word[0] + " ")
for word in OO:
outputsentence.append(word[0] + " ")
cleanoutput = ''.join(outputsentence).strip() + '.'
print(cleanoutput)
def main():
#testing data
rawData = raw_input("Enter the sentence to translate: ")
data = rawData.lower()
sentence = data.split() #split is use to break in easy word
parse(sentence, data)
if __name__ == '__main__':
main()
|
f609363a66aafa84e88eddc6131ff3e6b0c79d90 | a-yasinsky/pythonAlgo | /searchSort/sorting.py | 1,956 | 3.828125 | 4 | def shortBubbleSort(alist):
exchanges = True
passnum = len(alist)-1
while passnum > 0 and exchanges:
exchanges = False
for i in range(passnum):
if alist[i]>alist[i+1]:
exchanges = True
temp = alist[i]
alist[i] = alist[i+1]
alist[i+1] = temp
passnum = passnum-1
alist=[20,30,40,90,50,60,70,80,100,110]
shortBubbleSort(alist)
print(alist)
def selectionSort(alist):
for fillslot in range(len(alist)-1,0,-1):
positionOfMax=0
for location in range(1,fillslot+1):
if alist[location]>alist[positionOfMax]:
positionOfMax = location
temp = alist[fillslot]
alist[fillslot] = alist[positionOfMax]
alist[positionOfMax] = temp
alist = [54,26,93,17,77,31,44,55,20]
selectionSort(alist)
print(alist)
def insertionSort(alist):
for index in range(1,len(alist)):
currentvalue = alist[index]
position = index
while position>0 and alist[position-1]>currentvalue:
alist[position]=alist[position-1]
position = position-1
alist[position]=currentvalue
alist = [54,26,93,17,77,31,44,55,20]
insertionSort(alist)
print(alist)
def shellSort(alist):
sublistcount = len(alist)//2
while sublistcount > 0:
for startposition in range(sublistcount):
gapInsertionSort(alist,startposition,sublistcount)
print("After increments of size",sublistcount,
"The list is",alist)
sublistcount = sublistcount // 2
def gapInsertionSort(alist,start,gap):
for i in range(start+gap,len(alist),gap):
currentvalue = alist[i]
position = i
while position>=gap and alist[position-gap]>currentvalue:
alist[position]=alist[position-gap]
position = position-gap
alist[position]=currentvalue
alist = [54,26,93,17,77,31,44,55,20]
shellSort(alist)
print(alist)
|
df63376560cdde0a5e9ad1f6437a31c1c2358494 | amrkhailr/python_traning- | /week4_func_if/exo4.py | 743 | 4.34375 | 4 | #Magic Dates The date June 10, 1960, is special because when it is written in the following format,
#the month times the day equals the year: 6/10/60 Design a program that asks the user to enter a month (in numeric form), a day, and a twodigit year.
#The program should then determine whether the month times the day equals the year.
#If so, it should display a message saying the date is magic. Otherwise, it should display a message saying the date is not magic.
Month = int(input('Please enter your month: '))
Date = int(input('Please enter your date: '))
Year = int(input('Please enter your year: '))
month_day = Month * Date
if month_day == Year:
print('The date is Magic')
else:
print('The date is not Magic')
|
7145dd2f15abf6c38b603a017364302cf4849777 | byungjinku/Python-Base | /08_셋/main.py | 494 | 3.984375 | 4 | # set : 중복된 데이터를 저장할 수 없다.
# 관리 기준이 없다.
# 순서가 없다.
set1 = {10, 20, 30, 40, 50}
print(type(set1))
# 비어있는 set 을 만들 때는 set 함수를
# 사용한다.
set2 = set()
print(type(set2))
# 중복된 데이터를 이용해 set을 만든다.
set3 = {50, 10, 20, 10, 20, 10, 30}
print('set3 :', set3)
# 추가
set3.add(40)
set3.add(50)
set3.add(60)
set3.add(20)
set3.add(10)
print('set3 :', set3)
|
50b70e7ab2ac2bc62e1bc57072aac46020ba9977 | daniel-reich/ubiquitous-fiesta | /X9CsA6955cKRApBNH_2.py | 469 | 3.8125 | 4 |
def longest_run(lst):
run = []
longestRun = 0
for num in lst:
if len(run) == 0:
run.append(num)
elif (run[-1]+1 == num or run[-1]-1 == num) and len(run) == 1:
run.append(num)
elif len(run)>1 and ((run[-1]+1 == num and run[-2]+2 == num) or (run[-1]-1 == num and run[-2]-2 == num)):
run.append(num)
else:
if longestRun < len(run):
longestRun = len(run)
run = [num]
return max([longestRun, len(run)])
|
03e3c7a9d0321f82a24e030adafc4aab88bc8f48 | divyanshAgarwal123/PythonProjects | /aptech learning/tuple7.py | 212 | 3.671875 | 4 | x=('p','a','c','f','d','j')
'''
x[2]='v'
x[3]='x'
x[4]='b'
'''
print(x)
x=('p','a','c','f','d','j','b','s','x','v','l')
print(x[1:4])
print(x[:-2])
print(x[-7])
print(x[:])
for i in x:
print(i)
print(len(x)) |
4377530c45d675db72a0b8628000a0a03b76b318 | Laxmivadekar/Lucky-function | /len of two parameters.py | 145 | 3.59375 | 4 | def fun(a,b):
if len(a)>len(b):
print(a)
else:
print(b)
fun('hello','welcome')
fun("sonu","monu")
fun('monu','sonu')
|
b843e6fb880e343d66d940ca92656bc7cadd38f1 | vamshi99k/python-programs | /exchangelist - Copy.py | 277 | 3.515625 | 4 | def exchangelist(list):
fh=[]
sh=[]
mid=len(list)//2
ln=len(list)
for i in list:
if i in range(0,mid):
fh.append(list[i])
if i in range(mid,ln):
sh.append(list[i])
shr=sh[::-1]
res=shr+fh
return res
list=[1,2,3,4,5,6,7]
print(exchangelist(list)) |
2d6873b92d20de4f9977c8d367cbf1a58917ee2d | olliec28/Python | /connnecting to github.py | 543 | 3.921875 | 4 | print ("Hello world")
x = 10
y = 5
z = 0
print("x add y = ", x + y)
x = 7
y = 8
z = 0
print("x add y = " + str(x + y))
x = 21
y = 9
z = 0
print("(x add y) multiplied by y ", (x + y) * y)
x = -32
y = 6
z = 0
print("x subtract y = ", x - y)
x = 34
y = 3
z = 0
print("x multiplied by y = ", x * y)
print ("x multiplied by y = " + str(x * y))
x = 21
y = 7
z = 0
print("x divided by y ", x / y)
x = 45
y = 6
z = 0
print("x modulus y =", x % y)
x = 45
y = 6
z = 0
print("x floor division y = ", x // y)
|
c73c12942581b5945672d274303879c34f23fc0a | MrHamdulay/csc3-capstone | /examples/data/Assignment_2/odncas001/question3.py | 235 | 4.15625 | 4 | import math
pi=2
denom=math.sqrt(2)
while 2/denom != 1:
pi = pi * 2/denom
denom = math.sqrt(2 + denom)
print("Approximation of pi:",round(pi,3))
x=eval(input("Enter the radius:\n"))
print("Area:",round(pi*(x**2),3)) |
e02d4ef87a144ba87592050002f2236ea20f11dc | vivekpisal/Problem_Solving | /MergeKSortedList.py | 1,593 | 3.984375 | 4 | class node:
def __init__(self,data):
self.data=data
self.next=None
class ll:
def __init__(self):
self.start=None
def insert(self,value):
if self.start==None:
self.start=node(value)
else:
temp=self.start
while(temp.next!=None):
temp=temp.next
temp.next=node(value)
def show(self):
if self.start==None:
print("List is empty")
else:
temp=self.start
while temp!=None:
print(temp.data,end=' ')
temp=temp.next
print()
def merge(self,a):
temp=self.start
for i in range(len(a)):
while(temp.next!=None):
temp=temp.next
temp.next=a[i].start
self.sort()
self.show()
def sort(self):
if self.start==None:
print("List is empty")
else:
temp=self.start
while temp!=None:
temp2=temp.next
while temp2!=None:
if temp.data>temp2.data:
temp.data,temp2.data=temp2.data,temp.data
else:
pass
temp2=temp2.next
temp=temp.next
a=ll()
b=ll()
d=ll()
#a object
a.insert(1)
a.insert(4)
a.insert(5)
#b object
b.insert(1)
b.insert(3)
b.insert(4)
#d object
d.insert(2)
d.insert(6)
b.merge((a,d))
|
23d7d87d9cf0825ba5f24cb3e357339d478bc26f | iamdarshanshah/python-basics | /oopConcepts/Inheritance/BMWUseCase.py | 1,330 | 4 | 4 | class BMW:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def start(self):
print("Starting the car")
def stop(self):
print("Stopping the car")
class ThreeSeries(BMW): # Inherit class BMW
def __init__(self, cruisControlEnabled, make, model, year):
# BMW.__init__(self, make, model, year) # Invoking parent class constructor
super().__init__(make, model, year) # Simpler way of invoking parent class constructor using super()
self.cruiseControlEnabled = cruisControlEnabled
def start(self): # Overriding methods
print('Starting 3 series using push start')
class FiveSeries(BMW): # Inherit class BMW
def __init__(self, parkingAssistEnabled, make, model, year):
BMW.__init__(self, make, model, year) # Invoking parent class constructor
self.parkingAssistEnabled = parkingAssistEnabled
def start(self):
super().start() # Invoking parent class method whithin child class
print('Starting 5 series using remote start')
threeseries = ThreeSeries(True, "BMW", "3series", "2021")
print(threeseries.cruiseControlEnabled)
print(threeseries.make)
print(threeseries.model)
print(threeseries.year)
print(threeseries.start())
print(threeseries.stop())
|
1115f65634f85c0790aa9a88c78a6805687db124 | vkbinfo/geektrust-cricket | /ps4_problem2/player.py | 1,385 | 3.9375 | 4 | import random
class Player:
"""Information about player and methods for playing a ball """
run_scored = 0
ball_played = 0
prob_list_of_shots = []
def __init__(self, info_dict):
"""
initializing player with its name and it's probability list
:param info_dict:
"""
self.name = info_dict['name']
self.prob_list = info_dict["prob_list"]
def set_probabilities_of_shot(self, prob_list_shots):
"""
stores information about the player, the probability from 0 to 99 for each shot and out
:param prob_list_shots: probability distribution of the player from 0 to 99
"""
self.prob_list_of_shots = prob_list_shots
def play_a_ball(self):
"""
current players plays on ball, and on the value of random value and probability of the player
We will get what player is going to play.
:return: returns from [0,1,2,3,4,5,6,7] , 0 means no run and 7 means out
"""
random_value = random.randint(0,99)
for x in range(len(self.prob_list_of_shots)):
range_tuple = self.prob_list_of_shots[x]
if range_tuple[0] <= random_value <= range_tuple[1]:
if x != 7:
self.run_scored = self.run_scored + x
self.ball_played = self.ball_played + 1
return x
|
0ec9776dc6c75ce9af657e113c51235b78d5e768 | ClodaghMurphy/dataRepresentation | /Week3/PY04testCSV.py | 594 | 3.84375 | 4 | import csv
#create a w=writeable csv file with this name in this directory
employee_file = open('employee_file.csv', mode='w')
employee_writer = csv.writer(employee_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
employee_writer.writerow(['John Smith', 'Accounting', 'November'])
employee_writer.writerow(['Erica Meyers, what', 'IT', 'March'])
employee_file.close()
#then check has it worked by inputting ls in the cmd - you can see a new csv file created, wow.
#cat employee_file.csv on the command line
#The cat command is used to concatenate files and print on the standard output. |
32ba3f98ce1e5c10badcaf21064680905322c27a | Ostlora/lesson_02 | /ex_03.py | 285 | 4.1875 | 4 | a = int(input ('Choose a month'))
if a == 1 or a == 2 or a == 12:
print ('Winter')
elif a == 3 or a == 4 or a == 5:
print ('Sping')
elif a == 6 or a == 7 or a == 8:
print ('Summer')
elif a == 9 or a == 10 or a == 11:
print ('Autumn')
else:
print ('Error') |
1700d1978daa91f8df880474ce99cdd20d4ea063 | darlcruz/python-challenge-solutions | /Darlington/phase-2/TUPLE/day 53 solution/qtn2.py | 552 | 4.65625 | 5 | # program to remove an item from a tuple.
tupledar = ('d','a','r','l')
print(tupledar)
#create a tuple
tuplex = "w", 3, "r", "s", "o", "u", "r", "c", "e"
print(tuplex)
#tuples are immutable, so you can not remove elements
#using merge of tuples with the + operator you can remove an item and it will create a new tuple
tuplex = tuplex[:2] + tuplex[3:]
print(tuplex)
#converting the tuple to list
listx = list(tuplex)
#use different ways to remove an item of the list
listx.remove("c")
#converting the tuple to list
tuplex = tuple(listx)
print(tuplex) |
9dc91d43022260d69e30ccdfe2a3cdefffe1ba51 | YuliiaShalobodynskaPXL/IT_essentials | /coursera_ex/koord.py | 345 | 3.65625 | 4 | x1 = int(input())
y1 = int(input())
x2 = int(input())
y2 = int(input())
if x1 > 0:
signX1 = 1
else:
signX1 = -1
if y1 > 0:
signY1 = 1
else:
signY1 = -1
if x2 > 0:
signX2 = 1
else:
signX2 = -1
if y2 > 0:
signY2 = 1
else:
signY2 = -1
if signX1 == signX2 and signY1 == signY2:
print('Yes')
else:
print('No')
|
15ebf325cce3719fa5a412152169fbaef101feca | loicdewit/cs451-practicals | /p01-feature-splits.py | 5,046 | 3.875 | 4 | # Decision Trees: Feature Splits
#%%
# Python typing introduced in 3.5: https://docs.python.org/3/library/typing.html
from typing import List, Optional
# As of Python 3.7, this exists! https://www.python.org/dev/peps/pep-0557/
from dataclasses import dataclass
# My python file (very limited for now, but we will build up shared functions)
from shared import TODO
#%%
# Let's define a really simple class with two fields:
@dataclass
class DataPoint:
temperature: float
frozen: bool
def secret_answer(self) -> bool:
return self.temperature <= 32
def clone(self) -> "DataPoint":
return DataPoint(self.temperature, self.frozen)
# Fahrenheit, sorry.
data = [
# vermont temperatures; frozen=True
DataPoint(0, True),
DataPoint(-2, True),
DataPoint(10, True),
DataPoint(11, True),
DataPoint(6, True),
DataPoint(28, True),
DataPoint(31, True),
# warm temperatures; frozen=False
DataPoint(33, False),
DataPoint(45, False),
DataPoint(76, False),
DataPoint(60, False),
DataPoint(34, False),
DataPoint(98.6, False),
]
def is_water_frozen(temperature: float) -> bool:
"""
This is how we **should** implement it.
"""
return temperature <= 32
# Make sure the data I invented is actually correct...
for d in data:
assert d.frozen == is_water_frozen(d.temperature)
def find_candidate_splits(datapoints: List[DataPoint]) -> List[float]:
"""
Iterative method to find the split points.
"""
midpoints = []
sorted_data = sorted(datapoints, key=lambda datapoint: datapoint.temperature)
for d in range(len(sorted_data)):
if d != len(sorted_data) - 1:
point1 = sorted_data[d].temperature
point2 = sorted_data[d + 1].temperature
midpoint = ((point2 - point1) / 2) + (point1)
midpoints.append(midpoint)
return midpoints
def gini_impurity(points: List[DataPoint]) -> float:
"""
The standard version of gini impurity sums over the classes:
"""
p_ice = sum(1 for x in points if x.frozen) / len(points)
p_water = 1.0 - p_ice
return p_ice * (1 - p_ice) + p_water * (1 - p_water)
# for binary gini-impurity (just two classes) we can simplify, because 1 - p_ice == p_water, etc.
# p_ice * p_water + p_water * p_ice
# 2 * p_ice * p_water
# not really a huge difference.
def impurity_of_split(points: List[DataPoint], split: float) -> float:
"""
Iterative method to split the data points into two arrays based on the split point provided
and return the gini impurity measure for that split point.
"""
smaller = []
bigger = []
sorted_data = sorted(points, key=lambda datapoint: datapoint.temperature)
index = 0
for d in range(len(sorted_data)):
if d != len(sorted_data) - 1:
if (
sorted_data[d].temperature < split
and sorted_data[d + 1].temperature > split
):
index = d + 1
break
smaller = sorted_data[:index]
bigger = sorted_data[index:]
return gini_impurity(smaller) + gini_impurity(bigger)
def impurity_of_split_rec(points: List[DataPoint], split: float) -> float:
"""
Recursive method wrapper to split the data points into two arrays based on the split point provided and return the gini impurity measure for that split point.
"""
print("Printing split: {}".format(split))
smaller = []
bigger = []
sorted_data = sorted(points, key=lambda datapoint: datapoint.temperature)
splitpoint = __impurity_of_split_rec(sorted_data, split, 0, len(sorted_data))
print("Printing splitpoint {}".format(splitpoint))
smaller = sorted_data[:splitpoint]
bigger = sorted_data[splitpoint:]
return gini_impurity(smaller) + gini_impurity(bigger)
def __impurity_of_split_rec(
points: List[DataPoint], split: float, left: int, right: int
) -> Optional[int]:
"""
"Private" recursive method called by impurity_of_split_rec to find the actual split.
It is basically a binary search procedure.
"""
assert left >= 0
assert right >= 0
mid = (right - left) // 2 + left
if left >= right:
return None
else:
temp1 = points[mid - 1].temperature
temp2 = points[mid].temperature
if temp1 < split and temp2 > split:
print("Printing midpoint: {}".format(mid))
return mid
elif temp1 < split and temp2 < split:
return __impurity_of_split_rec(points, split, mid, right)
else:
return __impurity_of_split_rec(points, split, left, mid)
if __name__ == "__main__":
print("Initial Impurity: ", gini_impurity(data))
print("Impurity of first-six (all True): ", gini_impurity(data[:6]))
print("")
for split in find_candidate_splits(data):
score = impurity_of_split_rec(data, split)
print("splitting at {} gives us impurity {}".format(split, score))
if score == 0.0:
break
|
96b262627bd48d9093098689af2ac1046be08bc1 | bekkam/safe-run | /model.py | 7,710 | 3.703125 | 4 | """Models and database functions for Running App."""
from flask_sqlalchemy import SQLAlchemy
from config import username, password
db = SQLAlchemy()
##############################################################################
# Model definitions
class User(db.Model):
"""User of SafeRun website."""
__tablename__ = "users"
user_id = db.Column(db.Integer, autoincrement=True, primary_key=True)
email = db.Column(db.String(64), nullable=False, unique=True)
password = db.Column(db.String(64), nullable=False)
def __repr__(self):
"""Provide helpful representation when printed."""
return "<User user_id=%s email=%s password=%s>" % (self.user_id, self.email, self.password)
def __init__(self, email, password):
self.email = email
self.password = password
@classmethod
def add(cls, email, password):
"""Add a new user to the database"""
new_user = User(email=email, password=password)
db.session.add(new_user)
db.session.commit()
@classmethod
def get_by_email(cls, some_email):
"""Return the user with the specified email from the database"""
return User.query.filter_by(email=some_email).first()
class Course(db.Model):
"""A course on a map"""
__tablename__ = "courses"
course_id = db.Column(db.Integer, autoincrement=True, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.user_id'))
course_name = db.Column(db.String(100))
add_date = db.Column(db.Date)
start_lat = db.Column(db.Float)
start_long = db.Column(db.Float)
end_lat = db.Column(db.Float)
end_long = db.Column(db.Float)
course_distance = db.Column(db.Float)
favorite = db.Column(db.Boolean)
polyline = db.Column(db.String(1500))
directions_text = db.Column(db.String(2000))
directions_distance = db.Column(db.String(200))
start_address = db.Column(db.String(100))
end_address = db.Column(db.String(100))
# Define relationship to user: a user has many routes
user = db.relationship("User", backref=db.backref("courses"))
def __init__(self, user_id, course_name, add_date, start_lat, start_long,
end_lat, end_long, course_distance, favorite, polyline,
directions_text, directions_distance, start_address,
end_address):
self.user_id = user_id
self.course_name = course_name
self.add_date = add_date
self.start_lat = start_lat
self.start_long = start_long
self.end_lat = end_lat
self.end_long = end_long
self.course_distance = course_distance
self.favorite = favorite
self.polyline = polyline
self.directions_text = directions_text
self.directions_distance = directions_distance
self.start_address = start_address
self.end_address = end_address
def __repr__(self):
"""Provide helpful representation when printed."""
return "<User user_id=%s, Course course_id=%s, course_name=%s, add_date=%s, start_lat=%s,start_long=%s, end_lat=%s, end_long=%s, course_distance=%s, favorite=%s, polyline=%s, directions_text=%s, directions_distance=%s, start_address=%s, end_address=%s>" % (self.user_id, self.course_id, self.course_name, self.add_date, self.start_lat, self.start_long, self.end_lat, self.end_long, self.course_distance, self.favorite, self.polyline, self.directions_text, self.directions_distance, self.start_address, self.end_address)
@classmethod
def get_all(cls):
"""Return all courses from the database"""
return Course.query.all()
@classmethod
def get_by_id(cls, course_id):
"""Return a course with a given id from the database"""
return Course.query.get(course_id)
@classmethod
def get_by_course_name(cls, search_term):
"""Return a course with a given name from the database"""
print Course.query.filter_by(course_name=search_term).first()
return Course.query.filter_by(course_name=search_term).first()
def add(self):
"""Add a new course to the database"""
new_course = Course(user_id=self.user_id, course_name=self.course_name,
add_date=self.add_date, start_lat=self.start_lat,
start_long=self.start_long, end_lat=self.end_lat,
end_long=self.end_long,
course_distance=self.course_distance,
favorite=self.favorite,
polyline=self.polyline,
directions_text=self.directions_text,
directions_distance=self.directions_distance,
start_address=self.start_address,
end_address=self.end_address
)
db.session.add(new_course)
db.session.commit()
# print "course added in model"
class Run(db.Model):
"""A course on a map, that user has run."""
__tablename__ = "runs"
run_id = db.Column(db.Integer, autoincrement=True, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.user_id'))
course_id = db.Column(db.Integer, db.ForeignKey('courses.course_id'))
run_date = db.Column(db.Date)
duration = db.Column(db.Integer)
# Define relationship to course: a course has many runs
course = db.relationship("Course", backref=db.backref("runs", order_by=run_id))
# Define relationship to user: a user has many runs
user = db.relationship("User", backref=db.backref("users"))
def __init__(self, user_id, course_id, run_date, duration):
self.user_id = user_id
self.course_id = course_id
self.run_date = run_date
self.duration = duration
def __repr__(self):
"""Provide helpful representation when printed."""
return "<Run_id=%s Course_id=%s run_date=%s duration=%s>" % (self.run_id, self.course_id, self.run_date, self.duration)
def add(self):
"""Add a new run to the database"""
new_run = Run(user_id=self.user_id, course_id=self.course_id, run_date=self.run_date,
duration=self.duration)
db.session.add(new_run)
db.session.commit()
# print "run added in model"
class Outage(db.Model):
"""A location on a map, corresponding to a streetlight outage."""
__tablename__ = "outages"
marker_id = db.Column(db.Integer, autoincrement=True, primary_key=True)
outage_lat = db.Column(db.String(20))
outage_long = db.Column(db.String(20))
def __repr__(self):
"""Provide helpful representation when printed."""
return "<marker_id=%s, outage_lat=%s, outage_long=%s>" % (self.marker_id, self.outage_lat, self.outage_long)
##############################################################################
# Helper functions
def connect_to_db(app):
"""Connect the database to our Flask app."""
# Configure to use PostgreSQL database
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://' + username + ':' + password + '@localhost/runningapp'
db.app = app
db.init_app(app)
def connect_to_test_db(app):
"""Connect a test database to our Flask app."""
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://' + username + ':' + password + '@localhost/testdb'
db.app = app
db.init_app(app)
if __name__ == "__main__":
# As a convenience, if we run this module interactively, it will leave
# you in a state of being able to work with the database directly.
from server import app
connect_to_db(app)
print "Connected to DB."
|
9fa7f5d45861723996b489211ed30209ac5a4bfd | CodedQuen/The-Python-Workbook-A-Brief-Introduction | /The-Python-Workbook-Solutions/Section 3/Ex77.py | 679 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun May 26 17:44:16 2019
@author: meyerhof
"""
def binary_to_decimal(binary):
decimal = 0
for i in range(len(binary)):
decimal = decimal + int(binary[i])* 2**(len(binary)- i - 1)
return decimal
binary = input("Ingrese el número binario que desea convertir: ")
i = 0
while i < len(binary):
if (binary[i] != "0") and (binary[i] != "1"):
print("El valor ingresado no es un número binario")
binary = input("Ingrese el número binario que desea convertir: ")
i = 0
else:
i = i+1
print(binary_to_decimal(binary))
|
8594da2a975cd58c9fe3b4a7fb3e04633201b89c | vasanth62/leetcode | /largest_rectangle/ans.py | 1,012 | 3.53125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import pdb
from pprint import *
'''
Given a binary matrix, find the maximum size rectangle binary-sub-matrix with all 1’s.
Input : 0 1 1 0
1 1 1 1
1 1 1 1
1 1 0 0
Output : 1 1 1 1
1 1 1 1
'''
def max_rect(inp):
max_vals = [[(0,0) for _ in range(len(inp[0]))] for _ in range(len(inp))]
for i, x in enumerate(inp):
for j, y in enumerate(x):
if y == 0:
max_vals[i][j] = (0, 0)
else:
row_val = 1
col_val = 1
if i:
row_val, r = max_vals[i-1][j]
row_val += 1
if j:
c, col_val = max_vals[i][j-1]
col_val += 1
max_vals[i][j] = (row_val, col_val)
pprint(max_vals)
inp = [
[ 0, 1, 1, 0],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 0, 0]
]
pprint(inp)
max_rect(inp)
|
563ae755d916f725ba1b9c805f80150f67cf5ca6 | SrikanthUS/Nifty_Index_Options_OIA | /NiftyOptionsOIA.py | 104,571 | 3.53125 | 4 | #!/usr/bin/env python
# coding: utf-8
# Project Title: Nifty Index Options Trading:
# Profiting from Open Interest Analysis of Options Chain
# In[1]:
#STEPS to execute the code
#1.) Install the required library.
#2.) Restart and Run All or Run Step by Step
#3.) Provide User Input
# to select the No of Strikes aroung ATM to be considered for Analysis.
#4.) Provide User Input
# to select the No of Levels Of "Open Interest" around the Close Price
# to be shown on the Chart.
#5.) Provide User Input
# to select the No of Levels Of "Change in Open Interest"
# around the Close Price to be shown on the Chart.
# In[ ]:
# # Load Library
# In[2]:
# Import Libraries for usage in project
import pandas as pd
from pandas_datareader import data as web
import matplotlib.pyplot as plt
from datetime import datetime
import plotly.graph_objects as go
get_ipython().run_line_magic('matplotlib', 'inline')
# In[ ]:
# In[ ]:
# # Functions
# LoadFiles(): There are two excel files that are used in the project. CapstoneNiftyData.xlsx and CapstoneNiftyOptionsData. These two files are loaded to the data frame, and the records are displayed.
# In[3]:
def LoadFiles():
# Read the excel file containing Nifty 50 Index Data
dataset1 = pd.read_excel('./NiftyData.xlsx')
nifty = pd.DataFrame(dataset1)
# Read the Base Data
# Data about Nifty Index is stored in the excel file NiftyData.xlsx
# Data about Nifty Index Options is stored in the excel file NiftyOptionsData.xlsx
# Read the file into Pandas DataFrame
dataset2 = pd.read_excel('./NiftyOptionsData.xlsx')
nifty_options = pd.DataFrame(dataset2)
return nifty,nifty_options
# In[ ]:
# GetUserInput() is going to capture the user input, select any number from 1-7 and press enter, as to how many strikes around the ATM price needs to be considered for analysis.
# Nifty Index Options has each strike of 50 points apart. So selecting 5 strikes means 250 points on either side of the ATM or spot price is considered for analysis. So ATM = 15000, then the strikes selected are 14750 - 15250.
#
# In[4]:
def GetUserInput():
# Obtain user Input
# The user can choose how many strikes on either side of the ATM Strike he wants the data to be analysed
print ('How many Strike to Consider for NIFTY50 Index Options from ATM? Enter 1-7:')
print ('1. 05 Strikes = 250 points')
print ('2. 10 Strikes = 500 points')
print ('3. 15 Strikes = 750 points')
print ('4. 20 Strikes = 1000 points')
print ('5. 25 Strikes = 1250 points')
print ('6. 30 Strikes = 1500 points')
print ('7. ALL Strikes')
ip = input('> ')
if ip == '1':
ip1 = 250
ip11 = 'You have selected 1. 05 Strikes = 250 points'
elif ip == '2':
ip1 = 500
ip11 = 'You have selected 2. 10 Strikes = 500 points'
elif ip == '3':
ip1 = 750
ip11 = 'You have selected 3. 15 Strikes = 750 points'
elif ip == '4':
ip1 = 1000
ip11 = 'You have selected 4. 20 Strikes = 1000 pointss'
elif ip == '5':
ip1 = 1250
ip11 = 'You have selected 5. 25 Strikes = 1250 points'
elif ip == '6':
ip1 = 1500
ip11 = 'You have selected 6. 30 Strikes = 1500 points'
elif ip == '7':
ip1 = 10000
ip11 = 'You have selected 7. ALL Strikes'
else:
pass
#print(ip11)
return ip1, ip11
# In[ ]:
# GetUserInput_Charts() is going to capture the user input, select any number from 1-7 and press enter. This considers the first highest Open Interest or first highest Change in Open Interest to the next four levels below. Select 1 if you want to analyse the first highest OI or COI level wrt the Close price of the underlying.
# In[5]:
def GetUserInput_IOCharts():
# Obtain user Input
# The user can choose how many Levels of Depth he wants the data to be analysed
print ('How many Levels of "NIFTY50 Index Options OI" do you want to View in the Chart? Enter 1-6:')
print ('1. High1 OI Level')
print ('2. High2 OI Level')
print ('3. High3 OI Level')
print ('4. High4 OI Level')
print ('5. High5 OI Level')
print ('6. ALL 1-5 OI Levels')
print ('7. High1, and High 2 OI Level')
ip = input('> ')
if ip == '1':
ip2 = 1
ip21 = 'You have selected 1. Highest OI Level'
elif ip == '2':
ip2 = 2
ip21 = 'You have selected 2. Higher OI Level'
elif ip == '3':
ip2 = 3
ip21 = 'You have selected 3. High3 OI Level'
elif ip == '4':
ip2 = 4
ip21 = 'You have selected 4. High4 OI Level'
elif ip == '5':
ip2 = 5
ip21 = 'You have selected 5. High5 OI Level'
elif ip == '6':
ip2 = 6
ip21 = 'You have selected 6. ALL 1-5 OI Level'
elif ip == '7':
ip2 = 7
ip21 = 'You have selected 7. High1, High2 OI Level'
#print(ip11)
return ip2, ip21
# In[6]:
def GetUserInput_COICharts():
# Obtain user Input
# The user can choose how many Levels of Depth he wants the data to be analysed
print ('How many Levels of "NIFTY50 Index Options COI" do you want to View in the Chart? Enter 1-6:')
print ('1. High1 COI Level')
print ('2. High2 COI Level')
print ('3. High3 COI Level')
print ('4. High4 COI Level')
print ('5. High5 COI Level')
print ('6. ALL 1-5 OI Levels')
print ('7. High1, and High 2 COI Level')
ip = input('> ')
if ip == '1':
ip2 = 1
ip21 = 'You have selected 1. Highest COI Level'
elif ip == '2':
ip2 = 2
ip21 = 'You have selected 2. Higher COI Level'
elif ip == '3':
ip2 = 3
ip21 = 'You have selected 3. High3 COI Level'
elif ip == '4':
ip2 = 4
ip21 = 'You have selected 4. High4 COI Level'
elif ip == '5':
ip2 = 5
ip21 = 'You have selected 5. High5 COI Level'
elif ip == '6':
ip2 = 6
ip21 = 'You have selected 6. ALL 1-5 COI Level'
elif ip == '7':
ip2 = 7
ip21 = 'You have selected 7. High1, High2 COI Level'
#print(ip11)
return ip2, ip21
# In[7]:
# MaxPain() function , captures the Max Pain details and displayed.
def MaxPain(nifty_options):
# extrace the MaxPain data from the base file
mxpn = nifty_options[['Date','ITM_OTM','Close','Strike', 'CALL_OI','PUT_OI']]
mxpn['MaxPain'] = mxpn['CALL_OI'] + mxpn['PUT_OI']
return mxpn
# In[8]:
# DailyRange() captures the Daily Range and other details and are displayed.
def DailyRange(nifty):
# extrace the MaxPain data from the base file
DailyRange = nifty[['Date' , 'Volume\n(x1000)','Daily Return','Daily Range','Gap Open','Daily Body']]
return DailyRange
# In[9]:
# MaxPain_Top1() captures the one Top Max Pain considering all the strikes for a day.
def MaxPain_Top1(mxpn, ui):
# Make calculations for Open Interest
# Shortlist Open Interest Data for CALL ITM and CALL OTM Options
data = mxpn#.set_index(['Close','Strike', 'CALL_OI','PUT_OI']).groupby(['Date'])['MaxPain'].nlargest(10000).reset_index()
# Shortlist the data based on user input
# Open Interest Data for CALL ITM and PUT OTM Options on either side of the ATM,
# based on the number of strikes the user has selected
#select_color = df.loc[df['Color'] == 'Green']
data = data.loc[data['Strike'] < data['Close']+ui]
data = data.loc[data['Strike'] > data['Close']-ui]
# Shortlist the data based on Top 5, Highest OpenInterest Values
# Shortlist Top 5, Highest OpenInterest Values for CALL ITM and CALL OTM Options on either side of the ATM,
mxpn = data.set_index(['Close','Strike', 'CALL_OI','PUT_OI']).groupby(['Date'])['MaxPain'].nlargest(1).reset_index()
# Change the Column Header for Column = 'Strike'
mxpn.rename(columns = {'Strike':'MaxPain_Strike'}, inplace = True)
return mxpn
# In[10]:
# MaxPain_IOTM_Top1() captures the one Top Max Pain considering all the strikes for a day separated by ITM and OTM.
def MaxPain_IOTM_Top1(mxpn, ui):
# Make calculations for Open Interest
# Shortlist Open Interest Data for CALL ITM and CALL OTM Options
data = mxpn#.set_index(['Close','Strike', 'CALL_OI','PUT_OI']).groupby(['Date','ITM_OTM'])['MaxPain'].nlargest(10000).reset_index()
# Shortlist the data based on user input
# Open Interest Data for CALL ITM and PUT OTM Options on either side of the ATM,
# based on the number of strikes the user has selected
#select_color = df.loc[df['Color'] == 'Green']
data = data.loc[data['Strike'] < data['Close']+ui]
data = data.loc[data['Strike'] > data['Close']-ui]
# Shortlist the data based on Top 5, Highest OpenInterest Values
# Shortlist Top 5, Highest OpenInterest Values for CALL ITM and CALL OTM Options on either side of the ATM,
mxpn = data.set_index([ 'Close','Strike', 'CALL_OI','PUT_OI']).groupby(['Date','ITM_OTM'])['MaxPain'].nlargest(1).reset_index()
# Change the Column Header for Column = 'Strike'
mxpn.rename(columns = {'Strike':'MaxPain_Strike'}, inplace = True)
return mxpn
# In[11]:
# MaxPain_Top5() captures the five Top Max Pain considering all the strikes for a day separated by ITM and OTM.
def MaxPain_Top5(mxpn, ui):
# Make calculations for Open Interest
# Shortlist Open Interest Data for CALL ITM and CALL OTM Options
data = mxpn#.set_index(['Close','Strike', 'CALL_OI','PUT_OI']).groupby(['Date','ITM_OTM'])['MaxPain'].nlargest(10000).reset_index()
# Shortlist the data based on user input
# Open Interest Data for CALL ITM and PUT OTM Options on either side of the ATM,
# based on the number of strikes the user has selected
#select_color = df.loc[df['Color'] == 'Green']
data = data.loc[data['Strike'] < data['Close']+ui]
data = data.loc[data['Strike'] > data['Close']-ui]
# Shortlist the data based on Top 5, Highest OpenInterest Values
# Shortlist Top 5, Highest OpenInterest Values for CALL ITM and CALL OTM Options on either side of the ATM,
mxpn = data.set_index(['Close','Strike', 'CALL_OI','PUT_OI']).groupby(['Date','ITM_OTM'])['MaxPain'].nlargest(5).reset_index()
# Change the Column Header for Column = 'Strike'
mxpn.rename(columns = {'Strike':'MaxPain_Strike'}, inplace = True)
return mxpn
# In[ ]:
# In[ ]:
# In[ ]:
# In[12]:
# Call_OI_Top5() captures the top five Open Interest strikes for Call and Put options.
def Call_OI_Top5(nifty_options, ui):
# Make calculations for Open Interest
# Shortlist Open Interest Data for CALL ITM and CALL OTM Options
test_coi_sample = nifty_options#.set_index(['Open', 'High', 'Low', 'Close','Strike']).groupby(['Date','ITM_OTM'])['CALL_OI'].nlargest(10000).reset_index()
#test_coi_sample.head(10)
# Shortlist the data based on user input
# Open Interest Data for CALL ITM and PUT OTM Options on either side of the ATM,
# based on the number of strikes the user has selected
#select_color = df.loc[df['Color'] == 'Green']
test_coi_sample = test_coi_sample.loc[test_coi_sample['Strike'] < test_coi_sample['Close']+ui]
test_coi_sample = test_coi_sample.loc[test_coi_sample['Strike'] > test_coi_sample['Close']-ui]
# Shortlist the data based on Top 5, Highest OpenInterest Values
# Shortlist Top 5, Highest OpenInterest Values for CALL ITM and CALL OTM Options on either side of the ATM,
test_coi = test_coi_sample.set_index(['Open', 'High', 'Low', 'Close','Strike']).groupby(['Date','ITM_OTM'])['CALL_OI'].nlargest(5).reset_index()
# Change the Column Header for Column = 'Strike'
test_coi.rename(columns = {'Strike':'Call_OI_Strike'}, inplace = True)
return test_coi
# In[13]:
# Put_OI_Top5() captures the top five Open Interest strikes for Call and Put options.
def Put_OI_Top5(nifty_options,ui):
# Make calculations for Open Interest
# Shortlist Open Interest Data for PUT OTM and PUT ITM Options
test_poi_sample = nifty_options#.set_index(['Open', 'High', 'Low', 'Close','Strike']).groupby(['Date','ITM_OTM'])['PUT_OI'].nlargest(10000).reset_index()
# Shortlist the data based on user input
# Open Interest Data for PUT OTM and PUT ITM Options on either side of the ATM,
# based on the number of strikes the user has selected
test_poi_sample = test_poi_sample.loc[test_poi_sample['Strike'] < test_poi_sample['Close']+ui]
test_poi_sample = test_poi_sample.loc[test_poi_sample['Strike'] > test_poi_sample['Close']-ui]
# Shortlist the data based on Top 5, Highest OpenInterest Values
# Shortlist Top 5, Highest OpenInterest Values for PUT OTM and PUT IM Options on either side of the ATM,
test_poi = test_poi_sample.set_index(['Open', 'High', 'Low', 'Close','Strike']).groupby(['Date','ITM_OTM'])['PUT_OI'].nlargest(5).reset_index()
# Change the Column Header for Column = 'Strike'
test_poi.rename(columns = {'Strike':'Put_OI_Strike'}, inplace = True)
return test_poi
# In[ ]:
# In[ ]:
# In[14]:
# Merge_CallPutOI() merges Call_OI_Top5 and Put_OI_Top5() , so that all details are available in one dataframe.
def Merge_Call_Put_OI(Call_OI_Top5, Put_OI_Top5):
#Drop the unwanted Columns that are not necessary for further processing
Call_OI_Top5.drop('ITM_OTM', inplace=True, axis=1)
Call_OI_Top5.drop('CALL_OI', inplace=True, axis=1)
#Drop the unwanted Columns that are not necessary for further processing
Put_OI_Top5.drop('Date', inplace=True, axis=1)
Put_OI_Top5.drop('ITM_OTM', inplace=True, axis=1)
Put_OI_Top5.drop('Open', inplace=True, axis=1)
Put_OI_Top5.drop('High', inplace=True, axis=1)
Put_OI_Top5.drop('Low', inplace=True, axis=1)
Put_OI_Top5.drop('Close', inplace=True, axis=1)
Put_OI_Top5.drop('PUT_OI', inplace=True, axis=1)
#Calculate the size of the table for CALL OI
#print(Call_OI_Top5.shape)
#print(Call_OI_Top5.shape[0])
a = Call_OI_Top5.shape[0]/10
a= int(a)
#print(a)
#print(Call_OI_Top5.shape[1])
b = Call_OI_Top5.shape[1]
b= int(b)
#print(b)
#Calculate the size of the table for PUT OI
#print(Put_OI_Top5.shape)
c = Put_OI_Top5.shape[0]/10
c= int(c)
#print(c)
#print(Put_OI_Top5.shape[1])
d = Put_OI_Top5.shape[1]
d= int(d)
#print(d)
# Rebuild the table
# transform the ranking of Strikes from vertical columns to horizontal rows for CALL OI
Call_OI_Top5 = pd.DataFrame(Call_OI_Top5.values.reshape(a,b*10),
columns=['Date_COTM1', 'Open_COTM1', 'High_COTM1', 'Low_COTM1', 'Close_COTM1', 'OI_COTM_Strike1',
'Date_COTM2', 'Open_COTM2', 'High_COTM2', 'Low_COTM2', 'Close_COTM2', 'OI_COTM_Strike2',
'Date_COTM3', 'Open_COTM3', 'High_COTM3', 'Low_COTM3', 'Close_COTM3', 'OI_COTM_Strike3',
'Date_COTM4', 'Open_COTM4', 'High_COTM4', 'Low_COTM4', 'Close_COTM4', 'OI_COTM_Strike4' ,
'Date_COTM5', 'Open_COTM5', 'High_COTM5', 'Low_COTM5', 'Close_COTM5', 'OI_COTM_Strike5' ,
'Date_CITM1', 'Open_CITM1', 'High_CITM1', 'Low_CITM1', 'Close_CITM1', 'OI_CITM_Strike1',
'Date_CITM2', 'Open_CITM2', 'High_CITM2', 'Low_CITM2', 'Close_CITM2', 'OI_CITM_Strike2' ,
'Date_CITM3', 'Open_CITM3', 'High_CITM3', 'Low_CITM3', 'Close_CITM3', 'OI_CITM_Strike3' ,
'Date_CITM4', 'Open_CITM4', 'High_CITM4', 'Low_CITM4', 'Close_CITM4', 'OI_CITM_Strike4' ,
'Date_CITM5', 'Open_CITM5', 'High_CITM5', 'Low_CITM5', 'Close_CITM5', 'OI_CITM_Strike5'])
# Rebuild the table
# transform the ranking of Strikes from vertical columns to horizontal rows for PUT OI
Put_OI_Top5 = pd.DataFrame(Put_OI_Top5.values.reshape(c,d*10),
columns=['OI_PITM_Strike1',
'OI_PITM_Strike2',
'OI_PITM_Strike3',
'OI_PITM_Strike4' ,
'OI_PITM_Strike5' ,
'OI_POTM_Strike1',
'OI_POTM_Strike2' ,
'OI_POTM_Strike3' ,
'OI_POTM_Strike4' ,
'OI_POTM_Strike5'])
# Merge the PUT OI data to the CALL OI main table
#result = pd.concat([df1, df3], axis=1, join='inner')
#display(result)
#test_option = pd.concat([test_coi, test_poi], axis=1, join='inner')
CallPut_OI_Top5 = pd.concat([Call_OI_Top5, Put_OI_Top5], axis=1, join='inner')
# Remove the dulplicate columns
CallPut_OI_Top5=CallPut_OI_Top5[[ 'Date_CITM1', 'Open_CITM1', 'High_CITM1', 'Low_CITM1', 'Close_CITM1',
'OI_COTM_Strike1','OI_COTM_Strike2', 'OI_COTM_Strike3', 'OI_COTM_Strike4' , 'OI_COTM_Strike5' ,
'OI_CITM_Strike1','OI_CITM_Strike2', 'OI_CITM_Strike3', 'OI_CITM_Strike4' , 'OI_CITM_Strike5' ,
'OI_PITM_Strike1','OI_PITM_Strike2', 'OI_PITM_Strike3', 'OI_PITM_Strike4' , 'OI_PITM_Strike5' ,
'OI_POTM_Strike1','OI_POTM_Strike2', 'OI_POTM_Strike3', 'OI_POTM_Strike4' , 'OI_POTM_Strike5'
]]
CallPut_OI_Top5.rename(columns = {'Date_CITM1':'Date'}, inplace = True)
CallPut_OI_Top5.rename(columns = {'Open_CITM1':'Open'}, inplace = True)
CallPut_OI_Top5.rename(columns = {'High_CITM1':'High'}, inplace = True)
CallPut_OI_Top5.rename(columns = {'Low_CITM1':'Low'}, inplace = True)
CallPut_OI_Top5.rename(columns = {'Close_CITM1':'Close'}, inplace = True)
return CallPut_OI_Top5
# In[15]:
# Merge_CallPutOI_MaxPain() merges Merge_CallPut_OI and MaxPain_Top5, so that all details are available in one dataframe.
def Merge_CallPutOI_MaxPain(Merge_Call_Put_OI, MaxPain_Top5, Daily_Range):
#Drop the unwanted Columns that are not necessary for further processing
MaxPain_Top5.drop('Date', inplace=True, axis=1)
MaxPain_Top5.drop('ITM_OTM', inplace=True, axis=1)
MaxPain_Top5.drop('Close', inplace=True, axis=1)
MaxPain_Top5.drop('CALL_OI', inplace=True, axis=1)
MaxPain_Top5.drop('PUT_OI', inplace=True, axis=1)
MaxPain_Top5.drop('MaxPain', inplace=True, axis=1)
#Calculate the size of the table for CALL OI
#print(Call_OI_Top5.shape)
#print(Call_OI_Top5.shape[0])
a = MaxPain_Top5.shape[0]/10
a= int(a)
#print(a)
#print(Call_OI_Top5.shape[1])
b = MaxPain_Top5.shape[1]
b= int(b)
#print(b)
# Rebuild the table
# transform the ranking of Strikes from vertical columns to horizontal rows for PUT OI
MaxPain_Top5 = pd.DataFrame(MaxPain_Top5.values.reshape(a,b*10),
columns=['MaxPain_OTM_Strike1',
'MaxPain_OTM_Strike2',
'MaxPain_OTM_Strike3',
'MaxPain_OTM_Strike4' ,
'MaxPain_OTM_Strike5' ,
'MaxPain_ITM_Strike1',
'MaxPain_ITM_Strike2' ,
'MaxPain_ITM_Strike3' ,
'MaxPain_ITM_Strike4' ,
'MaxPain_ITM_Strike5'])
# Merge the PUT OI data to the CALL OI main table
#result = pd.concat([df1, df3], axis=1, join='inner')
#display(result)
#test_option = pd.concat([test_coi, test_poi], axis=1, join='inner')
CallPutOI_MaxPain_Top5 = pd.concat([Merge_Call_Put_OI, MaxPain_Top5], axis=1, join='inner')
#Drop the unwanted Columns that are not necessary for further processing
Daily_Range.drop('Date', inplace=True, axis=1)
CallPutOI_MaxPain_Top5 = pd.concat([CallPutOI_MaxPain_Top5, Daily_Range], axis=1, join='inner')
return CallPutOI_MaxPain_Top5
# In[16]:
def COTM_PITM(nifty_options):
# Capture data of CALL and PUT Open Interest, and Change of Open Interest, both ITM and OTM
COTM_PITM = nifty_options.set_index(['Close' , 'CALL_OI', 'PUT_OI' ,'CALL_COI', 'PUT_COI']).groupby(['Date','ITM_OTM'])['Strike'].nsmallest(10000).reset_index()
#aa.head(10)
# Capture data of CALL and PUT Open Interest, and Change of Open Interest,
# this is data for CALL OTM and PUT ITM
#aa2=COTM_PITM
COTM_PITM.drop(COTM_PITM.loc[COTM_PITM['ITM_OTM']==1].index, inplace=True) # 0=OTM, 1=ITM
#Rename the columns
COTM_PITM.rename(columns = {'CALL_OI':'OI_CALL_OTM'}, inplace = True)
COTM_PITM.rename(columns = {'CALL_COI':'COI_CALL_OTM'}, inplace = True)
COTM_PITM.rename(columns = {'PUT_OI':'OI_PUT_ITM'}, inplace = True)
COTM_PITM.rename(columns = {'PUT_COI':'COI_PUT_ITM'}, inplace = True)
# obtain the total of the values for each column
#COTM_PITM=COTM_PITM.groupby(['Date']).sum().reset_index()
# drop unwanted columns
#COTM_PITM.drop('Date', inplace=True, axis=1)
#COTM_PITM.drop('Strike', inplace=True, axis=1)
COTM_PITM.drop('ITM_OTM', inplace=True, axis=1)
#COTM_PITM.drop('Close', inplace=True, axis=1)
return COTM_PITM
# In[ ]:
# In[17]:
def CITM_POTM(nifty_options):
# Capture data of CALL and PUT Open Interest, and Change of Open Interest,
# this is data for CALL ITM and PUT OTM
CITM_POTM = nifty_options.set_index(['Close' , 'CALL_OI', 'PUT_OI' ,'CALL_COI', 'PUT_COI']).groupby(['Date','ITM_OTM'])['Strike'].nlargest(10000).reset_index()
# get CALL OTM and PUT ITM Data
CITM_POTM.drop(CITM_POTM.loc[CITM_POTM['ITM_OTM']==0].index, inplace=True) # 1 in file is ITM, 0 is OTM
#Rename the Columns
CITM_POTM.rename(columns = {'CALL_OI':'OI_CALL_ITM'}, inplace = True)
CITM_POTM.rename(columns = {'CALL_COI':'COI_CALL_ITM'}, inplace = True)
CITM_POTM.rename(columns = {'PUT_OI':'OI_PUT_OTM'}, inplace = True)
CITM_POTM.rename(columns = {'PUT_COI':'COI_PUT_OTM'}, inplace = True)
#CITM_POTM.drop('Close', inplace=True, axis=1)
#CITM_POTM.drop('Strike', inplace=True, axis=1)
CITM_POTM.drop('ITM_OTM', inplace=True, axis=1)
return CITM_POTM
# In[ ]:
# In[18]:
def CallPut_OI_COI(COTM_PITM,CITM_POTM):
COTM_PITM.drop('Date', inplace=True, axis=1)
COTM_PITM.drop('Strike', inplace=True, axis=1)
#COTM_PITM.drop('ITM_OTM', inplace=True, axis=1)
COTM_PITM.drop('Close', inplace=True, axis=1)
#Combine the tables of CALL PUT ITM OTM top 5
#aa1 = pd.concat([aa1, aa2], axis=1, join='inner')
CallPut_OI_COI = pd.concat([CITM_POTM, COTM_PITM], axis=1, join='inner')
return CallPut_OI_COI
# In[ ]:
# In[19]:
def Call_COI_P_Top5(nifty_options, ui,Merge_CallPutOI_MaxPain):
# Make calculations for Change in Open Interest Positive
# Shortlist Open Change of Interest Data for CALL ITM and CALL OTM Options
test_ccoip_sample = nifty_options#.set_index(['Open', 'High', 'Low', 'Close','Strike']).groupby(['Date','ITM_OTM'])['CALL_COI'].nlargest(10000).reset_index()
# Shortlist the data based on user input
# Open Interest Data for CALL ITM and PUT OTM Options on either side of the ATM,
# based on the number of strikes the user has selected
#select_color = df.loc[df['Color'] == 'Green']
test_ccoip_sample = test_ccoip_sample.loc[test_ccoip_sample['Strike'] < test_ccoip_sample['Close']+ui]
test_ccoip_sample = test_ccoip_sample.loc[test_ccoip_sample['Strike'] > test_ccoip_sample['Close']-ui]
# or test111['Strike'] < test111['Close']+500]
# Shortlist the data based on Top 5, Highest 'Change in OpenInterest" Values
# Shortlist Top 5, Highest OpenInterest Values for CALL ITM and CALL OTM Options on either side of the ATM,
test_ccoip = test_ccoip_sample.set_index(['Open', 'High', 'Low', 'Close','Strike']).groupby(['Date','ITM_OTM'])['CALL_COI'].nlargest(5).reset_index()
# Change the Column Header for Column = 'Strike'
test_ccoip.rename(columns = {'Strike':'CallP_COI_Strike'}, inplace = True)
#test_ccoip1=test_ccoip
#Drop the unwanted Columns that are not necessary for further processing
test_ccoip.drop('Date', inplace=True, axis=1)
test_ccoip.drop('ITM_OTM', inplace=True, axis=1)
test_ccoip.drop('Open', inplace=True, axis=1)
test_ccoip.drop('High', inplace=True, axis=1)
test_ccoip.drop('Low', inplace=True, axis=1)
test_ccoip.drop('Close', inplace=True, axis=1)
test_ccoip.drop('CALL_COI', inplace=True, axis=1)
#Calculate the size of the table for CALL OI
#import numpy as np
#print (np.reshape(test.values,(3,10)))
#[['11' '12' '13' '14' '15']
#['21' '22' '23' '24' '25']]
print(test_ccoip.shape)
e = test_ccoip.shape[0]/10
e= int(e)
# print(e)
print(test_ccoip.shape[1])
f = test_ccoip.shape[1]
f= int(f)
#print(f)
# Rebuild the table
# transform the ranking of Strikes from vertical columns to horizontal rows for CALL OI
# Rebuild the table
# transform the ranking of Strikes from vertical columns to horizontal rows for PUT OI
test_ccoip = pd.DataFrame(test_ccoip.values.reshape(e,f*10),
#columns=['Date','Date2','Date3','Date4','Date5','Date6','Date7','Date8','Date9','Date10',
columns=['COI_P_COTM_Strike1',
'COI_P_COTM_Strike2',
'COI_P_COTM_Strike3',
'COI_P_COTM_Strike4',
'COI_P_COTM_Strike5',
'COI_P_CITM_Strike1',
'COI_P_CITM_Strike2',
'COI_P_CITM_Strike3',
'COI_P_CITM_Strike4',
'COI_P_CITM_Strike5'])
#test_ccoip2=test_ccoip
#test_ccoip.drop('Date', inplace=True, axis=1)
#test_ccoip.drop('Date2', inplace=True, axis=1)
#test_ccoip.drop('Date3', inplace=True, axis=1)
#test_ccoip.drop('Date4', inplace=True, axis=1)
#test_ccoip.drop('Date5', inplace=True, axis=1)
#test_ccoip.drop('Date6', inplace=True, axis=1)
#test_ccoip.drop('Date7', inplace=True, axis=1)
#test_ccoip.drop('Date8', inplace=True, axis=1)
#test_ccoip.drop('Date9', inplace=True, axis=1)
#test_ccoip.drop('Date10', inplace=True, axis=1)
# Merge the CALL COI data to the main table
#CallPut_OI_COI_MP
Merge_CallPutOI_MaxPain = pd.concat([Merge_CallPutOI_MaxPain, test_ccoip], axis=1, join='inner')
#display(Merge_CallPutOI_MaxPain)
#return test_ccoip, test_ccoip2, Merge_CallPutOI_MaxPain
return Merge_CallPutOI_MaxPain
# In[ ]:
# In[20]:
def Put_COI_N_Top5(nifty_options, ui,Merge_CallPutOI_MaxPain):
# Calculation for "Change in Open Interest" for PUT Options NEGATIVE VALUES
# Shortlist Change in Open Interest Data for CALL ITM and CALL OTM Options
test_pcoin_sample = nifty_options#.set_index(['Open', 'High', 'Low', 'Close','Strike']).groupby(['Date','ITM_OTM'])['PUT_COI'].nsmallest(5000).reset_index()
# Shortlist the data based on user input
# Open Interest Data for CALL ITM and PUT OTM Options on either side of the ATM,
# based on the number of strikes the user has selected
test_pcoin_sample = test_pcoin_sample.loc[test_pcoin_sample['Strike'] < test_pcoin_sample['Close']+ui]
test_pcoin_sample = test_pcoin_sample.loc[test_pcoin_sample['Strike'] > test_pcoin_sample['Close']-ui]
# or test111['Strike'] < test111['Close']+500]
# Shortlist the data based on Top 5, Highest 'Change in OpenInterest" Values
# Shortlist Top 5, Highest OpenInterest Values for CALL ITM and CALL OTM Options on either side of the ATM,
test_pcoin = test_pcoin_sample.set_index(['Open', 'High', 'Low', 'Close','Strike']).groupby(['Date','ITM_OTM'])['PUT_COI'].nsmallest(5).reset_index()
# Change the Column Header for Column = 'Strike'
test_pcoin.rename(columns = {'Strike':'PutN_COI_Strike'}, inplace = True)
#Drop the unwanted Columns that are not necessary for further processing
test_pcoin.drop('Date', inplace=True, axis=1)
test_pcoin.drop('ITM_OTM', inplace=True, axis=1)
test_pcoin.drop('Open', inplace=True, axis=1)
test_pcoin.drop('High', inplace=True, axis=1)
test_pcoin.drop('Low', inplace=True, axis=1)
test_pcoin.drop('Close', inplace=True, axis=1)
test_pcoin.drop('PUT_COI', inplace=True, axis=1)
#Calculate the size of the table for CALL OI
#import numpy as np
#print (np.reshape(test.values,(3,10)))
#[['11' '12' '13' '14' '15']
#['21' '22' '23' '24' '25']]
#print(test_pcoin.shape)
e = test_pcoin.shape[0]/10
e= int(e)
#print(e)
#print(test_pcoin.shape[1])
f = test_pcoin.shape[1]
f= int(f)
#print(f)
# Rebuild the table
# transform the ranking of Strikes from vertical columns to horizontal rows for CALL OI
# Rebuild the table
# transform the ranking of Strikes from vertical columns to horizontal rows for PUT OI
test_pcoin = pd.DataFrame(test_pcoin.values.reshape(e,f*10),
columns=['COI_N_PITM_Strike1',
'COI_N_PITM_Strike2',
'COI_N_PITM_Strike3',
'COI_N_PITM_Strike4',
'COI_N_PITM_Strike5',
'COI_N_POTM_Strike1',
'COI_N_POTM_Strike2',
'COI_N_POTM_Strike3',
'COI_N_POTM_Strike4',
'COI_N_POTM_Strike5'])
# Merge the PUT COI data to the main table
Merge_CallPutOI_MaxPain = pd.concat([Merge_CallPutOI_MaxPain, test_pcoin], axis=1, join='inner')
return Merge_CallPutOI_MaxPain
# In[ ]:
# In[21]:
def Put_COI_P_Top5(nifty_options, ui,Merge_CallPutOI_MaxPain):
# Calculation for "Change in Open Interest" for PUT Options POSITIVE VALUES
# Shortlist Change in Open Interest Data for CALL ITM and CALL OTM Options
test_pcoip_sample = nifty_options#.set_index(['Open', 'High', 'Low', 'Close','Strike']).groupby(['Date','ITM_OTM'])['PUT_COI'].nlargest(10000).reset_index()
# Shortlist the data based on user input
# Open Interest Data for CALL ITM and PUT OTM Options on either side of the ATM,
# based on the number of strikes the user has selected
#select_color = df.loc[df['Color'] == 'Green']
test_pcoip_sample = test_pcoip_sample.loc[test_pcoip_sample['Strike'] < test_pcoip_sample['Close']+ui]
test_pcoip_sample = test_pcoip_sample.loc[test_pcoip_sample['Strike'] > test_pcoip_sample['Close']-ui]
# or test111['Strike'] < test111['Close']+500]
# Shortlist the data based on Top 5, Highest 'Change in OpenInterest" Values
# Shortlist Top 5, Highest OpenInterest Values for PUT ITM and PUT OTM Options on either side of the ATM,
test_pcoip = test_pcoip_sample.set_index(['Open', 'High', 'Low', 'Close','Strike']).groupby(['Date','ITM_OTM'])['PUT_COI'].nlargest(5).reset_index()
# Change the Column Header for Column = 'Strike'
test_pcoip.rename(columns = {'Strike':'PUTP_COI_Strike'}, inplace = True)
#Drop the unwanted Columns that are not necessary for further processing
test_pcoip.drop('Date', inplace=True, axis=1)
test_pcoip.drop('ITM_OTM', inplace=True, axis=1)
test_pcoip.drop('Open', inplace=True, axis=1)
test_pcoip.drop('High', inplace=True, axis=1)
test_pcoip.drop('Low', inplace=True, axis=1)
test_pcoip.drop('Close', inplace=True, axis=1)
test_pcoip.drop('PUT_COI', inplace=True, axis=1)
#Calculate the size of the table for PUT COI
#import numpy as np
#print (np.reshape(test.values,(3,10)))
#[['11' '12' '13' '14' '15']
#['21' '22' '23' '24' '25']]
#print(test_pcoip.shape)
e = test_pcoip.shape[0]/10
e= int(e)
#print(e)
#print(test_pcoip.shape[1])
f = test_pcoip.shape[1]
f= int(f)
#print(f)
# Rebuild the table
# transform the ranking of Strikes from vertical columns to horizontal rows for CALL OI
# Rebuild the table
# transform the ranking of Strikes from vertical columns to horizontal rows for PUT OI
test_pcoip = pd.DataFrame(test_pcoip.values.reshape(e,f*10),
columns=['COI_P_PITM_Strike1',
'COI_P_PITM_Strike2',
'COI_P_PITM_Strike3',
'COI_P_PITM_Strike4',
'COI_P_PITM_Strike5',
'COI_P_POTM_Strike1',
'COI_P_POTM_Strike2',
'COI_P_POTM_Strike3',
'COI_P_POTM_Strike4',
'COI_P_POTM_Strike5'])
# Merge the CALL COI data to the main table
Merge_CallPutOI_MaxPain = pd.concat([Merge_CallPutOI_MaxPain, test_pcoip], axis=1, join='inner')
return Merge_CallPutOI_MaxPain
# In[ ]:
# In[22]:
def Call_COI_N_Top5(nifty_options, ui,Merge_CallPutOI_MaxPain):
# Calculation for "Change in Open Interest" for CALL Options NEGATIVE VALUES
# Shortlist Change in Open Interest Data for CALL ITM and CALL OTM Options
test_ccoin_sample = nifty_options#.set_index(['Open', 'High', 'Low', 'Close','Strike']).groupby(['Date','ITM_OTM'])['CALL_COI'].nsmallest(10000).reset_index()
# Shortlist the data based on user input
# Open Change of Interest Data for CALL ITM and PUT OTM Options on either side of the ATM,
# based on the number of strikes the user has selected
#select_color = df.loc[df['Color'] == 'Green']
test_ccoin_sample = test_ccoin_sample.loc[test_ccoin_sample['Strike'] < test_ccoin_sample['Close']+ui]
test_ccoin_sample = test_ccoin_sample.loc[test_ccoin_sample['Strike'] > test_ccoin_sample['Close']-ui]
# or test111['Strike'] < test111['Close']+500]
# Shortlist the data based on Top 5, Highest 'Change in OpenInterest" Values
# Shortlist Top 5, Highest OpenInterest Values for CALL ITM and CALL OTM Options on either side of the ATM,
test_ccoin = test_ccoin_sample.set_index(['Open', 'High', 'Low', 'Close','Strike']).groupby(['Date','ITM_OTM'])['CALL_COI'].nsmallest(5).reset_index()
# Change the Column Header for Column = 'Strike'
test_ccoin.rename(columns = {'Strike':'CallN_COI_Strike'}, inplace = True)
#Drop the unwanted Columns that are not necessary for further processing
test_ccoin.drop('Date', inplace=True, axis=1)
test_ccoin.drop('ITM_OTM', inplace=True, axis=1)
test_ccoin.drop('Open', inplace=True, axis=1)
test_ccoin.drop('High', inplace=True, axis=1)
test_ccoin.drop('Low', inplace=True, axis=1)
test_ccoin.drop('Close', inplace=True, axis=1)
test_ccoin.drop('CALL_COI', inplace=True, axis=1)
#Calculate the size of the table for CALL OI
#import numpy as np
#print (np.reshape(test.values,(3,10)))
#[['11' '12' '13' '14' '15']
#['21' '22' '23' '24' '25']]
#print(test_ccoin.shape)
e = test_ccoin.shape[0]/10
e= int(e)
#print(e)
#print(test_ccoin.shape[1])
f = test_ccoin.shape[1]
f= int(f)
#print(f)
# Rebuild the table
# transform the ranking of Strikes from vertical columns to horizontal rows for CALL OI
# Rebuild the table
# transform the ranking of Strikes from vertical columns to horizontal rows for PUT OI
test_ccoin = pd.DataFrame(test_ccoin.values.reshape(e,f*10),
columns=['COI_N_COTM_Strike1',
'COI_N_COTM_Strike2',
'COI_N_COTM_Strike3',
'COI_N_COTM_Strike4',
'COI_N_COTM_Strike5',
'COI_N_CITM_Strike1',
'COI_N_CITM_Strike2',
'COI_N_CITM_Strike3',
'COI_N_CITM_Strike4',
'COI_N_CITM_Strike5'])
# Merge the CALL COI data to the main table
Merge_CallPutOI_MaxPain = pd.concat([Merge_CallPutOI_MaxPain, test_ccoin], axis=1, join='inner')
return Merge_CallPutOI_MaxPain
# In[ ]:
# In[23]:
def Call_OI_ITM_Chart(Merge_CallPutOI_MaxPain,no_levels):
ip2=no_levels
# Draw Candle Chart along with Call ITM
fig2 = go.Figure(data=[go.Candlestick(x=Merge_CallPutOI_MaxPain['Date'],
open=Merge_CallPutOI_MaxPain['Open'],
high=Merge_CallPutOI_MaxPain['High'],
low=Merge_CallPutOI_MaxPain['Low'],
close=Merge_CallPutOI_MaxPain['Close'])])
fig2.update_layout(legend_title_text = "CALL ITM Open Interest",autosize=True,width=1000, height=800)
#fig2.update_layout(autosize=True,width=1000, height=800)
#fig2.update_layout(width=1000, height=800)
fig2.update_xaxes(title_text="Date")
fig2.update_yaxes(title_text="NIFTY50 Index Strike Price")
#fig2.Title( "CALL ITM Open Interest")
#plotly.graph_objects.layout.Title
#fig.data[0].marker.color = 'green'
fig2.update_yaxes(automargin=True)
if ip2 == 1:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_CITM_Strike1"],mode='lines',
line = {'color' : 'red'}, name='Call ITM OI High1'))
elif ip2 == 2:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_CITM_Strike2"],
line = {'color' : 'blue'},mode='lines',name='Call ITM OI High2'))
elif ip2 == 3:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_CITM_Strike3"],
line = {'color' : 'green'},mode='lines', name='Call ITM OI High3'))
elif ip2 == 4:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_CITM_Strike4"],
mode='lines', name='Call ITM OI High2'))
elif ip2 == 5:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_CITM_Strike5"],
mode='lines', name='Call ITM OI High1'))
elif ip2 == 6:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_CITM_Strike1"],mode='lines',
name='Call ITM OI Highest'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_CITM_Strike2"],
mode='lines',name='Call ITM OI Higher'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_CITM_Strike3"],
mode='lines', name='Call ITM OI High1'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_CITM_Strike4"],
mode='lines', name='Call ITM OI High2'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_CITM_Strike5"],
mode='lines', name='Call ITM OI High3'))
elif ip2 == 7:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_CITM_Strike1"],mode='lines',
line = {'color' : 'red'},name='Call ITM OI High1'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_CITM_Strike2"],
line = {'color' : 'blue'},mode='lines',name='Call ITM OI High2'))
fig2.show()
return
# In[ ]:
# In[24]:
def Call_OI_OTM_Chart(Merge_CallPutOI_MaxPain,no_levels):
ip2=no_levels
# Draw Candle Chart along with Call OTM
fig2 = go.Figure(data=[go.Candlestick(x=Merge_CallPutOI_MaxPain['Date'],
open=Merge_CallPutOI_MaxPain['Open'],
high=Merge_CallPutOI_MaxPain['High'],
low=Merge_CallPutOI_MaxPain['Low'],
close=Merge_CallPutOI_MaxPain['Close'])])
fig2.update_layout(legend_title_text = "CALL OTM Open Interest",autosize=True,width=1000, height=800)
#fig2.update_layout(autosize=True,width=1000, height=800)
#fig2.update_layout(width=1000, height=800)
fig2.update_xaxes(title_text="Date")
fig2.update_yaxes(title_text="NIFTY50 Index Strike Price")
#fig2.Title( "CALL ITM Open Interest")
#plotly.graph_objects.layout.Title
#fig.data[0].marker.color = 'green'
fig2.update_yaxes(automargin=True)
if ip2 == 1:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_COTM_Strike1"],mode='lines',
name='Call OTM OI High1'))
elif ip2 == 2:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_COTM_Strike2"],
mode='lines',name='Call OTM OI High2'))
elif ip2 == 3:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_COTM_Strike3"],
mode='lines', name='Call OTM OI High3'))
elif ip2 == 4:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_COTM_Strike4"],
mode='lines', name='Call OTM OI High2'))
elif ip2 == 5:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_COTM_Strike5"],
mode='lines', name='Call OTM OI High1'))
elif ip2 == 6:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_COTM_Strike1"],mode='lines',
name='Call OTM OI Highest'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_COTM_Strike2"],
mode='lines',name='Call OTM OI Higher'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_COTM_Strike3"],
mode='lines', name='Call OTM OI High1'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_COTM_Strike4"],
mode='lines', name='Call OTM OI High2'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_COTM_Strike5"],
mode='lines', name='Call OTM OI High3'))
elif ip2 == 7:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_COTM_Strike1"],mode='lines',
name='Call OTM OI High1'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_COTM_Strike2"],
mode='lines',name='Call OTM OI High2'))
fig2.show()
return
# In[ ]:
# In[25]:
def Put_OI_OTM_Chart(Merge_CallPutOI_MaxPain,no_levels):
ip2=no_levels
# Draw Candle Chart along with PUT OTM
fig2 = go.Figure(data=[go.Candlestick(x=Merge_CallPutOI_MaxPain['Date'],
open=Merge_CallPutOI_MaxPain['Open'],
high=Merge_CallPutOI_MaxPain['High'],
low=Merge_CallPutOI_MaxPain['Low'],
close=Merge_CallPutOI_MaxPain['Close'])])
fig2.update_layout(legend_title_text = "PUT OTM Open Interest",autosize=True,width=1000, height=800)
#fig2.update_layout(autosize=True,width=1000, height=800)
#fig2.update_layout(width=1000, height=800)
fig2.update_xaxes(title_text="Date")
fig2.update_yaxes(title_text="NIFTY50 Index Strike Price")
#fig2.Title( "CALL ITM Open Interest")
#plotly.graph_objects.layout.Title
#fig.data[0].marker.color = 'green'
fig2.update_yaxes(automargin=True)
if ip2 == 1:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_POTM_Strike1"],mode='lines',
name='Put OTM OI High1'))
elif ip2 == 2:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_POTM_Strike2"],
mode='lines',name='Put OTM OI High2'))
elif ip2 == 3:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_POTM_Strike3"],
mode='lines', name='Put OTM OI High3'))
elif ip2 == 4:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_POTM_Strike4"],
mode='lines', name='Put OTM OI High2'))
elif ip2 == 5:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_POTM_Strike5"],
mode='lines', name='Put OTM OI High1'))
elif ip2 == 6:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_POTM_Strike1"],mode='lines',
name='Put OTM OI Highest'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_POTM_Strike2"],
mode='lines',name='Put OTM OI Higher'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_POTM_Strike3"],
mode='lines', name='Put OTM OI High1'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_POTM_Strike4"],
mode='lines', name='Put OTM OI High2'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_POTM_Strike5"],
mode='lines', name='Put OTM OI High3'))
elif ip2 == 7:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_POTM_Strike1"],mode='lines',
name='Put OTM OI High1'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_POTM_Strike2"],
mode='lines',name='Put OTM OI High2'))
fig2.show()
return
# In[ ]:
# In[26]:
def Nifty_OHLC_Chart(Merge_CallPutOI_MaxPain):
# Plot the OHLC graph
#fig = px.line(test, x="Date_CITM1", y="Open_CITM1", title='OHLC Chart',color='Open_CITM1')
#fig = go.Figure(data=go.Scatter( x=test["Date_CITM1"], y=test["Open_CITM1"]))
fig2 = go.Figure()
fig2.update_layout(legend_title_text = "OHLC Graph for NIFTY 50 Index",autosize=True,width=1000, height=800)
#fig2.update_layout(autosize=True,width=1000, height=800)
#fig2.update_layout(width=1000, height=800)
fig2.update_xaxes(title_text="Date")
fig2.update_yaxes(title_text="NIFTY50 Index Strike Price")
#fig2.Title( "CALL ITM Open Interest")
#plotly.graph_objects.layout.Title
#fig.data[0].marker.color = 'green'
fig2.update_yaxes(automargin=True)
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["Open"], mode='markers', name='Open'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["High"], mode='lines', name='High'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["Low"], mode='lines', name='Low'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["Close"], mode='markers', name='Close'))
fig2.show()
return
# In[ ]:
# In[27]:
def CallPut_OI_OTM_Chart(Merge_CallPutOI_MaxPain,no_levels):
# Draw Candle Chart along with Call OTM and PUT OTM [COPO]
fig2 = go.Figure(data=[go.Candlestick(x=Merge_CallPutOI_MaxPain['Date'],
open=Merge_CallPutOI_MaxPain['Open'],
high=Merge_CallPutOI_MaxPain['High'],
low=Merge_CallPutOI_MaxPain['Low'],
close=Merge_CallPutOI_MaxPain['Close'])])
fig2.update_layout(legend_title_text = "CALL OTM, PUT OTM Open Interest",autosize=True,width=1000, height=800)
#fig2.update_layout(autosize=True,width=1000, height=800)
#fig2.update_layout(width=1000, height=800)
fig2.update_xaxes(title_text="Date")
fig2.update_yaxes(title_text="NIFTY50 Index Strike Price")
#fig2.Title( "CALL ITM Open Interest")
#plotly.graph_objects.layout.Title
#fig.data[0].marker.color = 'green'
fig2.update_yaxes(automargin=True)
#fig = go.Figure()
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_COTM_Strike5"],mode='lines',
name='Call OTM OI Highest'))
#fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_COTM_Strike2"],
# mode='lines',name='Call OTM OI Higher'))
#fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date_CITM1"], y=Merge_CallPutOI_MaxPain["OI_CITM_Strike3"],
# mode='markers', name='High1'))
#fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date_CITM1"], y=Merge_CallPutOI_MaxPain["OI_CITM_Strike4"],
# mode='markers', name='High2'))
#fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date_CITM1"], y=Merge_CallPutOI_MaxPain["OI_CITM_Strike5"],
# mode='markers', name='High3'))
1
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_POTM_Strike5"],
mode='lines', name='Put OTM OI Highest'))
#fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_POTM_Strike2"],
# mode='lines',name='Put OTM OI Higher'))
fig2.show()
return
# In[ ]:
# In[28]:
def Put_OI_ITM_Chart(Merge_CallPutOI_MaxPain,no_levels):
ip2=no_levels
# Draw Candle Chart along with PUT ITM
fig2 = go.Figure(data=[go.Candlestick(x=Merge_CallPutOI_MaxPain['Date'],
open=Merge_CallPutOI_MaxPain['Open'],
high=Merge_CallPutOI_MaxPain['High'],
low=Merge_CallPutOI_MaxPain['Low'],
close=Merge_CallPutOI_MaxPain['Close'])])
fig2.update_layout(legend_title_text = "PUT ITM Open Interest",autosize=True,width=1000, height=800)
#fig2.update_layout(autosize=True,width=1000, height=800)
#fig2.update_layout(width=1000, height=800)
fig2.update_xaxes(title_text="Date")
fig2.update_yaxes(title_text="NIFTY50 Index Strike Price")
#fig2.Title( "CALL ITM Open Interest")
#plotly.graph_objects.layout.Title
#fig.data[0].marker.color = 'green'
fig2.update_yaxes(automargin=True)
if ip2 == 1:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_PITM_Strike1"],mode='lines',
name='Put ITM OI High1'))
elif ip2 == 2:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_PITM_Strike2"],
mode='lines',name='Put ITM OI High2'))
elif ip2 == 3:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_PITM_Strike3"],
mode='lines', name='Put ITM OI High3'))
elif ip2 == 4:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_PITM_Strike4"],
mode='lines', name='Put ITM OI High2'))
elif ip2 == 5:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_PITM_Strike5"],
mode='lines', name='Put ITM OI High1'))
elif ip2 == 6:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_PITM_Strike1"],mode='lines',
name='Put ITM OI Highest'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_PITM_Strike2"],
mode='lines',name='Put ITM OI Higher'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_PITM_Strike3"],
mode='lines', name='Put ITM OI High1'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_PITM_Strike4"],
mode='lines', name='Put ITM OI High2'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_PITM_Strike5"],
mode='lines', name='Put ITM OI High3'))
elif ip2 == 7:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_PITM_Strike1"],mode='lines',
name='Put ITM OI High1'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["OI_PITM_Strike2"],
mode='lines',name='Put ITM OI High2'))
fig2.show()
return
# In[ ]:
# In[29]:
def Call_OI_ITM_Scatter_Chart(Merge_CallPutOI_MaxPain):
# Scatter Plot showing CALL ITM with respect to close price
#plt.scatter(nifty_options['Date'], nifty_options['CALL_OI'].astype(float)) #, nifty_options['PUT COI'])
plt.scatter(Merge_CallPutOI_MaxPain['Date'], Merge_CallPutOI_MaxPain['OI_CITM_Strike1'], color = 'red', label = "Call ITM OI Highest") #, nifty_options['PUT COI'])
plt.scatter(Merge_CallPutOI_MaxPain['Date'], Merge_CallPutOI_MaxPain['OI_CITM_Strike2'], color = 'blue', label = "Call ITM OI Higher") #, nifty_options['PUT COI'])
#plt.plot(test['Date_CITM1'], test['CALL_OI_ITM_Strike3'], color = 'green', label = "High 1") #, nifty_options['PUT COI'])
#plt.plot(test['Date_CITM1'], test['CALL_OI_ITM_Strike4'], color = 'yellow', label = "High 2") #, nifty_options['PUT COI'])
#plt.plot(test['Date_CITM1'], test['CALL_OI_ITM_Strike5'], color = 'cyan', label = "High 3") #, nifty_options['PUT COI'])
#plt.scatter(test['Date_CITM1'], test['Open_CITM1'], color = 'pink', label = "Highest") #, nifty_options['PUT COI'])
#plt.scatter(test['Date_CITM1'], test['High_CITM1'], color = 'red', label = "Highest") #, nifty_options['PUT COI'])
#plt.scatter(test['Date_CITM1'], test['Low_CITM1'], color = 'Green', label = "Highest") #, nifty_options['PUT COI'])
plt.scatter(Merge_CallPutOI_MaxPain['Date'], Merge_CallPutOI_MaxPain['Close'], color = 'black', label = "Close") #, nifty_options['PUT COI'])
#plt.scatter(test['Date_CITM1'], test['CALL_OI_OTM_Strike1'], color = 'blue', label = "Highest") #, nifty_options['PUT COI'])
#plt.plot(x, y, color='green', linestyle='dashed', linewidth = 3,
# marker='o', markerfacecolor='blue', markersize=12)
#plt.bar(left, height, tick_label = tick_label,
# width = 0.8, color = ['red', 'green'])
#plt.hist(ages, bins, range, color = 'green',
# histtype = 'bar', rwidth = 0.8)
plt.xlabel('Date')
plt.ylabel('Strike Price')
plt.title("CALL ITM OI Graph")
plt.legend()
plt.show()
return
# In[ ]:
# In[30]:
def OHLC_Chart_MaxPain(Merge_CallPutOI_MaxPain):
# Plot the OHLC graph and MaxPain
#fig = px.line(test, x="Date_CITM1", y="Open_CITM1", title='OHLC Chart',color='Open_CITM1')
#fig = go.Figure(data=go.Scatter( x=test["Date_CITM1"], y=test["Open_CITM1"]))
fig2 = go.Figure()
fig2.update_layout(legend_title_text = "ITM and OTM Max Pain Points",autosize=True,width=1000, height=800)
#fig2.update_layout(autosize=True,width=1000, height=800)
#fig2.update_layout(width=1000, height=800)
fig2.update_xaxes(title_text="Date")
fig2.update_yaxes(title_text="NIFTY50 Index Strike Price")
#fig2.Title( "CALL ITM Open Interest")
#plotly.graph_objects.layout.Title
#fig.data[0].marker.color = 'green'
fig2.update_yaxes(automargin=True)
#fig.add_trace(go.Scatter(x=MaxPain_IOTM_Top1["Date"], y=MaxPain_IOTM_Top1["Open"], mode='markers', name='Open'))
#fig.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=MaxPain_IOTM_Top1["High"], mode='lines', name='High'))
#fig.add_trace(go.Scatter(x=MaxPain_IOTM_Top1["Date"], y=MaxPain_IOTM_Top1["Low"], mode='lines', name='Low'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=MaxPain_IOTM_Top1["Close"], mode='lines', name='Close'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=MaxPain_IOTM_Top1["MaxPain_Strike"], mode='markers',name='ITM and OTM Max Pain Point '))
#fig.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=MaxPain_IOTM_Top1["High"], mode='lines', name='High'))
#fig.add_trace(go.Scatter(x=MaxPain_IOTM_Top1["Date"], y=MaxPain_IOTM_Top1["Low"], mode='lines', name='Low'))
#fig.add_trace(go.Scatter(x=MaxPain_IOTM_Top1["Date"], y=MaxPain_IOTM_Top1["Close"], mode='markers', name='Close'))
fig2.show()
return
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[31]:
def Put_COI_N_OTM_Chart(Merge_CallPutOI_MaxPain,no_levels):
ip2 = no_levels
# Draw Candle Chart along with Chaneg of OI for Call OTM Positive Values
fig2 = go.Figure(data=[go.Candlestick(x=Merge_CallPutOI_MaxPain['Date'],
open=Merge_CallPutOI_MaxPain['Open'],
high=Merge_CallPutOI_MaxPain['High'],
low=Merge_CallPutOI_MaxPain['Low'],
close=Merge_CallPutOI_MaxPain['Close'])])
fig2.update_layout(legend_title_text = "PUT OTM COI Negative",autosize=True,width=1000, height=800)
#fig2.update_layout(autosize=True,width=1000, height=800)
#fig2.update_layout(width=1000, height=800)
fig2.update_xaxes(title_text="Date")
fig2.update_yaxes(title_text="NIFTY50 Index Strike Price")
#fig2.Title( "CALL ITM Open Interest")
#plotly.graph_objects.layout.Title
#fig.data[0].marker.color = 'green'
fig2.update_yaxes(automargin=True)
if ip2 == 1:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_COTM_Strike1"],mode='lines',
name='Put OTM COI- High1'))
elif ip2 == 2:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_COTM_Strike2"],
mode='lines',name='Put OTM COI- High2'))
elif ip2 == 3:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_COTM_Strike3"],
mode='lines', name='Put OTM COI- High3'))
elif ip2 == 4:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_COTM_Strike4"],
mode='lines', name='Put OTM COI- High2'))
elif ip2 == 5:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_COTM_Strike5"],
mode='lines', name='Put OTM COI- High1'))
elif ip2 == 6:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_COTM_Strike1"],mode='lines',
name='Put OTM COI- High1'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_COTM_Strike2"],
mode='lines',name='Put OTM COI- High2'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_COTM_Strike3"],
mode='lines', name='Put OTM COI- High1'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_COTM_Strike4"],
mode='lines', name='Put OTM COI- High2'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_COTM_Strike5"],
mode='lines', name='Put OTM COI- High3'))
elif ip2 == 7:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_COTM_Strike1"],mode='lines',
name='Put OTM COI- High1'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_COTM_Strike2"],
mode='lines',name='Put OTM COI- High2'))
fig2.show()
return
# In[ ]:
# In[32]:
def Call_COI_P_OTM_Chart(Merge_CallPutOI_MaxPain,no_levels):
ip2 = no_levels
# Draw Candle Chart along with Chaneg of OI for Call OTM Positive Values
fig2 = go.Figure(data=[go.Candlestick(x=Merge_CallPutOI_MaxPain['Date'],
open=Merge_CallPutOI_MaxPain['Open'],
high=Merge_CallPutOI_MaxPain['High'],
low=Merge_CallPutOI_MaxPain['Low'],
close=Merge_CallPutOI_MaxPain['Close'])])
fig2.update_layout(legend_title_text = "CALL OTM COI Positive",autosize=True,width=1000, height=800)
#fig2.update_layout(autosize=True,width=1000, height=800)
#fig2.update_layout(width=1000, height=800)
fig2.update_xaxes(title_text="Date")
fig2.update_yaxes(title_text="NIFTY50 Index Strike Price")
#fig2.Title( "CALL ITM Open Interest")
#plotly.graph_objects.layout.Title
#fig.data[0].marker.color = 'green'
fig2.update_yaxes(automargin=True)
if ip2 == 1:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_COTM_Strike1"],mode='lines',
name='Call OTM COI+ High1'))
elif ip2 == 2:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_COTM_Strike2"],
mode='lines',name='Call OTM COI+ High2'))
elif ip2 == 3:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_COTM_Strike3"],
mode='lines', name='Call OTM COI+ High3'))
elif ip2 == 4:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_COTM_Strike4"],
mode='lines', name='Call OTM COI+ High2'))
elif ip2 == 5:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_COTM_Strike5"],
mode='lines', name='Call OTM COI+ High1'))
elif ip2 == 6:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_COTM_Strike1"],mode='lines',
name='Call OTM COI+ High1'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_COTM_Strike2"],
mode='lines',name='Call OTM COI+ High2'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_COTM_Strike3"],
mode='lines', name='Call OTM COI+ High1'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_COTM_Strike4"],
mode='lines', name='Call OTM COI+ High2'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_COTM_Strike5"],
mode='lines', name='Call OTM COI+ High3'))
elif ip2 == 7:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_COTM_Strike1"],mode='lines',
name='Call OTM COI+ High1'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_COTM_Strike2"],
mode='lines',name='Call OTM COI+ High2'))
fig2.show()
return
# In[ ]:
# In[33]:
def Call_COI_N_OTM_Chart(Merge_CallPutOI_MaxPain,no_levels):
ip2 = no_levels
# Draw Candle Chart along with Chaneg of OI for Call OTM NEGATIVE Values
fig2 = go.Figure(data=[go.Candlestick(x=Merge_CallPutOI_MaxPain['Date'],
open=Merge_CallPutOI_MaxPain['Open'],
high=Merge_CallPutOI_MaxPain['High'],
low=Merge_CallPutOI_MaxPain['Low'],
close=Merge_CallPutOI_MaxPain['Close'])])
fig2.update_layout(legend_title_text = "CALL OTM COI Negative",autosize=True,width=1000, height=800)
#fig2.update_layout(autosize=True,width=1000, height=800)
#fig2.update_layout(width=1000, height=800)
fig2.update_xaxes(title_text="Date")
fig2.update_yaxes(title_text="NIFTY50 Index Strike Price")
#fig2.Title( "CALL ITM Open Interest")
#plotly.graph_objects.layout.Title
#fig.data[0].marker.color = 'green'
fig2.update_yaxes(automargin=True)
if ip2 == 1:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_N_COTM_Strike1"],mode='lines',
name='Call OTM COI- High1'))
elif ip2 == 2:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_N_COTM_Strike2"],
mode='lines',name='Call OTM COI- High2'))
elif ip2 == 3:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_N_COTM_Strike3"],
mode='lines', name='Call OTM COI- High3'))
elif ip2 == 4:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_N_COTM_Strike4"],
mode='lines', name='Call OTM COI- High2'))
elif ip2 == 5:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_N_COTM_Strike5"],
mode='lines', name='Call OTM COI- High1'))
elif ip2 == 6:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_N_COTM_Strike1"],mode='lines',
name='Call OTM COI- High1'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_N_COTM_Strike2"],
mode='lines',name='Call OTM COI- High2'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_N_COTM_Strike3"],
mode='lines', name='Call OTM COI- High1'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_N_COTM_Strike4"],
mode='lines', name='Call OTM COI- High2'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_N_COTM_Strike5"],
mode='lines', name='Call OTM COI- High3'))
elif ip2 == 7:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_N_COTM_Strike1"],mode='lines',
name='Call OTM COI- High1'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_N_COTM_Strike2"],
mode='lines',name='Call OTM COI- High2'))
fig2.show()
return
# In[ ]:
# In[34]:
def Put_COI_P_OTM_Chart(Merge_CallPutOI_MaxPain,no_levels):
ip2 = no_levels
# Draw Candle Chart along with Chaneg of OI for PUT OTM Positive Values
fig2 = go.Figure(data=[go.Candlestick(x=Merge_CallPutOI_MaxPain['Date'],
open=Merge_CallPutOI_MaxPain['Open'],
high=Merge_CallPutOI_MaxPain['High'],
low=Merge_CallPutOI_MaxPain['Low'],
close=Merge_CallPutOI_MaxPain['Close'])])
fig2.update_layout(legend_title_text = "PUT OTM COI Positive",autosize=True,width=1000, height=800)
#fig2.update_layout(autosize=True,width=1000, height=800)
#fig2.update_layout(width=1000, height=800)
fig2.update_xaxes(title_text="Date")
fig2.update_yaxes(title_text="NIFTY50 Index Strike Price")
#fig2.Title( "CALL ITM Open Interest")
#plotly.graph_objects.layout.Title
#fig.data[0].marker.color = 'green'
fig2.update_yaxes(automargin=True)
if ip2 == 1:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_POTM_Strike1"],mode='lines',
name='Put OTM COI+ High1'))
elif ip2 == 2:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_POTM_Strike2"],
mode='lines',name='Put OTM COI+ High2'))
elif ip2 == 3:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_POTM_Strike3"],
mode='lines', name='Put OTM COI+ High3'))
elif ip2 == 4:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_POTM_Strike4"],
mode='lines', name='Put OTM COI+ High2'))
elif ip2 == 5:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_POTM_Strike5"],
mode='lines', name='Put OTM COI+ High1'))
elif ip2 == 6:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_POTM_Strike1"],mode='lines',
name='Put OTM COI+ High1'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_POTM_Strike2"],
mode='lines',name='Put OTM COI+ High2'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_POTM_Strike3"],
mode='lines', name='Put OTM COI+ High1'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_POTM_Strike4"],
mode='lines', name='Put OTM COI+ High2'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_POTM_Strike5"],
mode='lines', name='Put OTM COI+ High3'))
elif ip2 == 7:
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_POTM_Strike1"],mode='lines',
name='Put OTM COI+ High1'))
fig2.add_trace(go.Scatter(x=Merge_CallPutOI_MaxPain["Date"], y=Merge_CallPutOI_MaxPain["COI_P_POTM_Strike2"],
mode='lines',name='Put OTM COI+ High2'))
fig2.show()
return
# In[ ]:
# In[35]:
def Candle_Chart(Merge_CallPutOI_MaxPain):
#Draw Candle Chart for the given period
fig1 = go.Figure(data=[go.Candlestick(x=Merge_CallPutOI_MaxPain['Date'],
open=Merge_CallPutOI_MaxPain['Open'],
high=Merge_CallPutOI_MaxPain['High'],
low=Merge_CallPutOI_MaxPain['Low'],
close=Merge_CallPutOI_MaxPain['Close'])])
#fig1.update_layout(legend_title_text = "NIFTY")
fig1.update_layout(legend_title_text = "NIFTY 50 Index",autosize=True,width=1000, height=800)
#fig2.update_layout(autosize=True,width=1000, height=800)
#fig2.update_layout(width=1000, height=800)
fig1.update_xaxes(title_text="Date")
fig1.update_yaxes(title_text="NIFTY50 Index Strike Price")
#fig2.Title( "CALL ITM Open Interest")
#plotly.graph_objects.layout.Title
#fig.data[0].marker.color = 'green'
fig1.update_yaxes(automargin=True)
fig1.show()
return
# In[ ]:
# In[ ]:
# Analyse_COI(Merge_CallPutOI_MaxPain):
# The Change in Open Interest data will be analysed
# There are Six combinations of Call, Put, ITM, OTM, Positive and Negative COI
# values for the options Open Interest.
# All these details are merged with Merge_CallPutOI_MaxPain dataframe.
#
# In[36]:
def Analyse_COI(Merge_CallPutOI_MaxPain):
import numpy as np
a_a = Merge_CallPutOI_MaxPain[['Date']]
mt = Merge_CallPutOI_MaxPain
a_a['Delta_Close'] = np.where((mt['Close'] > mt['Close'].shift(1)) ,1,np.where((mt['Close'] < mt['Close'].shift(1)),-1,0))
a_a['Delta_COI_P_COTM_Strike1'] = np.where((mt['COI_P_COTM_Strike1'] > mt['COI_P_COTM_Strike1'].shift(1)),1,np.where((mt['COI_P_COTM_Strike1'] < mt['COI_P_COTM_Strike1'].shift(1)),-1,0))
a_a['Delta_COI_P_COTM_Strike2'] = np.where((mt['COI_P_COTM_Strike2'] > mt['COI_P_COTM_Strike2'].shift(1)),1,np.where((mt['COI_P_COTM_Strike2'] < mt['COI_P_COTM_Strike2'].shift(1)),-1,0))
a_a['Delta_COI_P_COTM_Strike3'] = np.where((mt['COI_P_COTM_Strike3'] > mt['COI_P_COTM_Strike3'].shift(1)),1,np.where((mt['COI_P_COTM_Strike3'] < mt['COI_P_COTM_Strike3'].shift(1)),-1,0))
a_a['Delta_COI_P_COTM_Strike4'] = np.where((mt['COI_P_COTM_Strike4'] > mt['COI_P_COTM_Strike4'].shift(1)),1,np.where((mt['COI_P_COTM_Strike4'] < mt['COI_P_COTM_Strike4'].shift(1)),-1,0))
a_a['Delta_COI_P_COTM_Strike5'] = np.where((mt['COI_P_COTM_Strike5'] > mt['COI_P_COTM_Strike5'].shift(1)),1,np.where((mt['COI_P_COTM_Strike5'] < mt['COI_P_COTM_Strike5'].shift(1)),-1,0))
a_a['Delta_COI_N_COTM_Strike1'] = np.where((mt['COI_N_COTM_Strike1'] > mt['COI_N_COTM_Strike1'].shift(1)),1,np.where((mt['COI_N_COTM_Strike1'] < mt['COI_N_COTM_Strike1'].shift(1)),-1,0))
a_a['Delta_COI_N_COTM_Strike2'] = np.where((mt['COI_N_COTM_Strike2'] > mt['COI_N_COTM_Strike2'].shift(1)),1,np.where((mt['COI_N_COTM_Strike2'] < mt['COI_N_COTM_Strike2'].shift(1)),-1,0))
a_a['Delta_COI_N_COTM_Strike3'] = np.where((mt['COI_N_COTM_Strike3'] > mt['COI_N_COTM_Strike3'].shift(1)),1,np.where((mt['COI_N_COTM_Strike3'] < mt['COI_N_COTM_Strike3'].shift(1)),-1,0))
a_a['Delta_COI_N_COTM_Strike4'] = np.where((mt['COI_N_COTM_Strike4'] > mt['COI_N_COTM_Strike4'].shift(1)),1,np.where((mt['COI_N_COTM_Strike4'] < mt['COI_N_COTM_Strike4'].shift(1)),-1,0))
a_a['Delta_COI_N_COTM_Strike5'] = np.where((mt['COI_N_COTM_Strike5'] > mt['COI_N_COTM_Strike5'].shift(1)),1,np.where((mt['COI_N_COTM_Strike5'] < mt['COI_N_COTM_Strike5'].shift(1)),-1,0))
a_a['Delta_COI_P_CITM_Strike1'] = np.where((mt['COI_P_CITM_Strike1'] > mt['COI_P_CITM_Strike1'].shift(1)),1,np.where((mt['COI_P_CITM_Strike1'] < mt['COI_P_CITM_Strike1'].shift(1)),-1,0))
a_a['Delta_COI_P_CITM_Strike2'] = np.where((mt['COI_P_CITM_Strike2'] > mt['COI_P_CITM_Strike2'].shift(1)),1,np.where((mt['COI_P_CITM_Strike2'] < mt['COI_P_CITM_Strike2'].shift(1)),-1,0))
a_a['Delta_COI_P_CITM_Strike3'] = np.where((mt['COI_P_CITM_Strike3'] > mt['COI_P_CITM_Strike3'].shift(1)),1,np.where((mt['COI_P_CITM_Strike3'] < mt['COI_P_CITM_Strike3'].shift(1)),-1,0))
a_a['Delta_COI_P_CITM_Strike4'] = np.where((mt['COI_P_CITM_Strike4'] > mt['COI_P_CITM_Strike4'].shift(1)),1,np.where((mt['COI_P_CITM_Strike4'] < mt['COI_P_CITM_Strike4'].shift(1)),-1,0))
a_a['Delta_COI_P_CITM_Strike5'] = np.where((mt['COI_P_CITM_Strike5'] > mt['COI_P_CITM_Strike5'].shift(1)),1,np.where((mt['COI_P_CITM_Strike5'] < mt['COI_P_CITM_Strike5'].shift(1)),-1,0))
a_a['Delta_COI_N_CITM_Strike1'] = np.where((mt['COI_N_CITM_Strike1'] > mt['COI_N_CITM_Strike1'].shift(1)),1,np.where((mt['COI_N_CITM_Strike1'] < mt['COI_N_CITM_Strike1'].shift(1)),-1,0))
a_a['Delta_COI_N_CITM_Strike2'] = np.where((mt['COI_N_CITM_Strike2'] > mt['COI_N_CITM_Strike2'].shift(1)),1,np.where((mt['COI_N_CITM_Strike2'] < mt['COI_N_CITM_Strike2'].shift(1)),-1,0))
a_a['Delta_COI_N_CITM_Strike3'] = np.where((mt['COI_N_CITM_Strike3'] > mt['COI_N_CITM_Strike3'].shift(1)),1,np.where((mt['COI_N_CITM_Strike3'] < mt['COI_N_CITM_Strike3'].shift(1)),-1,0))
a_a['Delta_COI_N_CITM_Strike4'] = np.where((mt['COI_N_CITM_Strike4'] > mt['COI_N_CITM_Strike4'].shift(1)),1,np.where((mt['COI_N_CITM_Strike4'] < mt['COI_N_CITM_Strike4'].shift(1)),-1,0))
a_a['Delta_COI_N_CITM_Strike5'] = np.where((mt['COI_N_CITM_Strike5'] > mt['COI_N_CITM_Strike5'].shift(1)),1,np.where((mt['COI_N_CITM_Strike5'] < mt['COI_N_CITM_Strike5'].shift(1)),-1,0))
a_a['Delta_COI_P_POTM_Strike1'] = np.where((mt['COI_P_POTM_Strike1'] > mt['COI_P_POTM_Strike1'].shift(1)),1,np.where((mt['COI_P_POTM_Strike1'] < mt['COI_P_POTM_Strike1'].shift(1)),-1,0))
a_a['Delta_COI_P_POTM_Strike2'] = np.where((mt['COI_P_POTM_Strike2'] > mt['COI_P_POTM_Strike2'].shift(1)),1,np.where((mt['COI_P_POTM_Strike2'] < mt['COI_P_POTM_Strike2'].shift(1)),-1,0))
a_a['Delta_COI_P_POTM_Strike3'] = np.where((mt['COI_P_POTM_Strike3'] > mt['COI_P_POTM_Strike3'].shift(1)),1,np.where((mt['COI_P_POTM_Strike3'] < mt['COI_P_POTM_Strike3'].shift(1)),-1,0))
a_a['Delta_COI_P_POTM_Strike4'] = np.where((mt['COI_P_POTM_Strike4'] > mt['COI_P_POTM_Strike4'].shift(1)),1,np.where((mt['COI_P_POTM_Strike4'] < mt['COI_P_POTM_Strike4'].shift(1)),-1,0))
a_a['Delta_COI_P_POTM_Strike5'] = np.where((mt['COI_P_POTM_Strike5'] > mt['COI_P_POTM_Strike5'].shift(1)),1,np.where((mt['COI_P_POTM_Strike5'] < mt['COI_P_POTM_Strike5'].shift(1)),-1,0))
a_a['Delta_COI_N_POTM_Strike1'] = np.where((mt['COI_N_POTM_Strike1'] > mt['COI_N_POTM_Strike1'].shift(1)),1,np.where((mt['COI_N_POTM_Strike1'] < mt['COI_N_POTM_Strike1'].shift(1)),-1,0))
a_a['Delta_COI_N_POTM_Strike2'] = np.where((mt['COI_N_POTM_Strike2'] > mt['COI_N_POTM_Strike2'].shift(1)),1,np.where((mt['COI_N_POTM_Strike2'] < mt['COI_N_POTM_Strike2'].shift(1)),-1,0))
a_a['Delta_COI_N_POTM_Strike3'] = np.where((mt['COI_N_POTM_Strike3'] > mt['COI_N_POTM_Strike3'].shift(1)),1,np.where((mt['COI_N_POTM_Strike3'] < mt['COI_N_POTM_Strike3'].shift(1)),-1,0))
a_a['Delta_COI_N_POTM_Strike4'] = np.where((mt['COI_N_POTM_Strike4'] > mt['COI_N_POTM_Strike4'].shift(1)),1,np.where((mt['COI_N_POTM_Strike4'] < mt['COI_N_POTM_Strike4'].shift(1)),-1,0))
a_a['Delta_COI_N_POTM_Strike5'] = np.where((mt['COI_N_POTM_Strike5'] > mt['COI_N_POTM_Strike5'].shift(1)),1,np.where((mt['COI_N_POTM_Strike5'] < mt['COI_N_POTM_Strike5'].shift(1)),-1,0))
a_a['Delta_COI_P_PITM_Strike1'] = np.where((mt['COI_P_PITM_Strike1'] > mt['COI_P_PITM_Strike1'].shift(1)),1,np.where((mt['COI_P_PITM_Strike1'] < mt['COI_P_PITM_Strike1'].shift(1)),-1,0))
a_a['Delta_COI_P_PITM_Strike2'] = np.where((mt['COI_P_PITM_Strike2'] > mt['COI_P_PITM_Strike2'].shift(1)),1,np.where((mt['COI_P_PITM_Strike2'] < mt['COI_P_PITM_Strike2'].shift(1)),-1,0))
a_a['Delta_COI_P_PITM_Strike3'] = np.where((mt['COI_P_PITM_Strike3'] > mt['COI_P_PITM_Strike3'].shift(1)),1,np.where((mt['COI_P_PITM_Strike3'] < mt['COI_P_PITM_Strike3'].shift(1)),-1,0))
a_a['Delta_COI_P_PITM_Strike4'] = np.where((mt['COI_P_PITM_Strike4'] > mt['COI_P_PITM_Strike4'].shift(1)),1,np.where((mt['COI_P_PITM_Strike4'] < mt['COI_P_PITM_Strike4'].shift(1)),-1,0))
a_a['Delta_COI_P_PITM_Strike5'] = np.where((mt['COI_P_PITM_Strike5'] > mt['COI_P_PITM_Strike5'].shift(1)),1,np.where((mt['COI_P_PITM_Strike5'] < mt['COI_P_PITM_Strike5'].shift(1)),-1,0))
a_a['Delta_COI_N_PITM_Strike1'] = np.where((mt['COI_N_PITM_Strike1'] > mt['COI_N_PITM_Strike1'].shift(1)),1,np.where((mt['COI_N_PITM_Strike1'] < mt['COI_N_PITM_Strike1'].shift(1)),-1,0))
a_a['Delta_COI_N_PITM_Strike2'] = np.where((mt['COI_N_PITM_Strike2'] > mt['COI_N_PITM_Strike2'].shift(1)),1,np.where((mt['COI_N_PITM_Strike2'] < mt['COI_N_PITM_Strike2'].shift(1)),-1,0))
a_a['Delta_COI_N_PITM_Strike3'] = np.where((mt['COI_N_PITM_Strike3'] > mt['COI_N_PITM_Strike3'].shift(1)),1,np.where((mt['COI_N_PITM_Strike3'] < mt['COI_N_PITM_Strike3'].shift(1)),-1,0))
a_a['Delta_COI_N_PITM_Strike4'] = np.where((mt['COI_N_PITM_Strike4'] > mt['COI_N_PITM_Strike4'].shift(1)),1,np.where((mt['COI_N_PITM_Strike4'] < mt['COI_N_PITM_Strike4'].shift(1)),-1,0))
a_a['Delta_COI_N_PITM_Strike5'] = np.where((mt['COI_N_PITM_Strike5'] > mt['COI_N_PITM_Strike5'].shift(1)),1,np.where((mt['COI_N_PITM_Strike5'] < mt['COI_N_PITM_Strike5'].shift(1)),-1,0))
a_a['Match_COI_P_COTM_Strike1'] = a_a.Delta_Close.eq(a_a.Delta_COI_P_COTM_Strike1.shift(1))
a_a['Match_COI_P_COTM_Strike2'] = a_a.Delta_Close.eq(a_a.Delta_COI_P_COTM_Strike2.shift(1))
a_a['Match_COI_P_COTM_Strike3'] = a_a.Delta_Close.eq(a_a.Delta_COI_P_COTM_Strike3.shift(1))
a_a['Match_COI_P_COTM_Strike4'] = a_a.Delta_Close.eq(a_a.Delta_COI_P_COTM_Strike4.shift(1))
a_a['Match_COI_P_COTM_Strike5'] = a_a.Delta_Close.eq(a_a.Delta_COI_P_COTM_Strike5.shift(1))
a_a['Match_COI_N_COTM_Strike1'] = a_a.Delta_Close.eq(a_a.Delta_COI_N_COTM_Strike1.shift(1))
a_a['Match_COI_N_COTM_Strike2'] = a_a.Delta_Close.eq(a_a.Delta_COI_N_COTM_Strike2.shift(1))
a_a['Match_COI_N_COTM_Strike3'] = a_a.Delta_Close.eq(a_a.Delta_COI_N_COTM_Strike3.shift(1))
a_a['Match_COI_N_COTM_Strike4'] = a_a.Delta_Close.eq(a_a.Delta_COI_N_COTM_Strike4.shift(1))
a_a['Match_COI_N_COTM_Strike5'] = a_a.Delta_Close.eq(a_a.Delta_COI_N_COTM_Strike5.shift(1))
a_a['Match_COI_P_CITM_Strike1'] = a_a.Delta_Close.eq(a_a.Delta_COI_P_CITM_Strike1.shift(1))
a_a['Match_COI_P_CITM_Strike2'] = a_a.Delta_Close.eq(a_a.Delta_COI_P_CITM_Strike2.shift(1))
a_a['Match_COI_P_CITM_Strike3'] = a_a.Delta_Close.eq(a_a.Delta_COI_P_CITM_Strike3.shift(1))
a_a['Match_COI_P_CITM_Strike4'] = a_a.Delta_Close.eq(a_a.Delta_COI_P_CITM_Strike4.shift(1))
a_a['Match_COI_P_CITM_Strike5'] = a_a.Delta_Close.eq(a_a.Delta_COI_P_CITM_Strike5.shift(1))
a_a['Match_COI_N_CITM_Strike1'] = a_a.Delta_Close.eq(a_a.Delta_COI_N_CITM_Strike1.shift(1))
a_a['Match_COI_N_CITM_Strike2'] = a_a.Delta_Close.eq(a_a.Delta_COI_N_CITM_Strike2.shift(1))
a_a['Match_COI_N_CITM_Strike3'] = a_a.Delta_Close.eq(a_a.Delta_COI_N_CITM_Strike3.shift(1))
a_a['Match_COI_N_CITM_Strike4'] = a_a.Delta_Close.eq(a_a.Delta_COI_N_CITM_Strike4.shift(1))
a_a['Match_COI_N_CITM_Strike5'] = a_a.Delta_Close.eq(a_a.Delta_COI_N_CITM_Strike5.shift(1))
a_a['Match_COI_P_POTM_Strike1'] = a_a.Delta_Close.eq(a_a.Delta_COI_P_POTM_Strike1.shift(1))
a_a['Match_COI_P_POTM_Strike2'] = a_a.Delta_Close.eq(a_a.Delta_COI_P_POTM_Strike2.shift(1))
a_a['Match_COI_P_POTM_Strike3'] = a_a.Delta_Close.eq(a_a.Delta_COI_P_POTM_Strike3.shift(1))
a_a['Match_COI_P_POTM_Strike4'] = a_a.Delta_Close.eq(a_a.Delta_COI_P_POTM_Strike4.shift(1))
a_a['Match_COI_P_POTM_Strike5'] = a_a.Delta_Close.eq(a_a.Delta_COI_P_POTM_Strike5.shift(1))
a_a['Match_COI_N_POTM_Strike1'] = a_a.Delta_Close.eq(a_a.Delta_COI_N_POTM_Strike1.shift(1))
a_a['Match_COI_N_POTM_Strike2'] = a_a.Delta_Close.eq(a_a.Delta_COI_N_POTM_Strike2.shift(1))
a_a['Match_COI_N_POTM_Strike3'] = a_a.Delta_Close.eq(a_a.Delta_COI_N_POTM_Strike3.shift(1))
a_a['Match_COI_N_POTM_Strike4'] = a_a.Delta_Close.eq(a_a.Delta_COI_N_POTM_Strike4.shift(1))
a_a['Match_COI_N_POTM_Strike5'] = a_a.Delta_Close.eq(a_a.Delta_COI_N_POTM_Strike5.shift(1))
a_a['Match_COI_P_PITM_Strike1'] = a_a.Delta_Close.eq(a_a.Delta_COI_P_PITM_Strike1.shift(1))
a_a['Match_COI_P_PITM_Strike2'] = a_a.Delta_Close.eq(a_a.Delta_COI_P_PITM_Strike2.shift(1))
a_a['Match_COI_P_PITM_Strike3'] = a_a.Delta_Close.eq(a_a.Delta_COI_P_PITM_Strike3.shift(1))
a_a['Match_COI_P_PITM_Strike4'] = a_a.Delta_Close.eq(a_a.Delta_COI_P_PITM_Strike4.shift(1))
a_a['Match_COI_P_PITM_Strike5'] = a_a.Delta_Close.eq(a_a.Delta_COI_P_PITM_Strike5.shift(1))
a_a['Match_COI_N_PITM_Strike1'] = a_a.Delta_Close.eq(a_a.Delta_COI_N_PITM_Strike1.shift(1))
a_a['Match_COI_N_PITM_Strike2'] = a_a.Delta_Close.eq(a_a.Delta_COI_N_PITM_Strike2.shift(1))
a_a['Match_COI_N_PITM_Strike3'] = a_a.Delta_Close.eq(a_a.Delta_COI_N_PITM_Strike3.shift(1))
a_a['Match_COI_N_PITM_Strike4'] = a_a.Delta_Close.eq(a_a.Delta_COI_N_PITM_Strike4.shift(1))
a_a['Match_COI_N_PITM_Strike5'] = a_a.Delta_Close.eq(a_a.Delta_COI_N_PITM_Strike5.shift(1))
a_a_coi = a_a
a_a_coi1 = ["Match_COI_P_COTM_Strike1", "Match_COI_P_COTM_Strike2", "Match_COI_P_COTM_Strike3", "Match_COI_P_COTM_Strike4","Match_COI_P_COTM_Strike5",
"Match_COI_P_CITM_Strike1", "Match_COI_P_CITM_Strike2", "Match_COI_P_CITM_Strike3", "Match_COI_P_CITM_Strike4","Match_COI_P_CITM_Strike5",
"Match_COI_P_POTM_Strike1", "Match_COI_P_POTM_Strike2", "Match_COI_P_POTM_Strike3", "Match_COI_P_POTM_Strike4","Match_COI_P_POTM_Strike5",
"Match_COI_P_PITM_Strike1", "Match_COI_P_PITM_Strike2", "Match_COI_P_PITM_Strike3", "Match_COI_P_PITM_Strike4","Match_COI_P_PITM_Strike5",
"Match_COI_N_COTM_Strike1", "Match_COI_N_COTM_Strike2", "Match_COI_N_COTM_Strike3", "Match_COI_N_COTM_Strike4","Match_COI_N_COTM_Strike5",
"Match_COI_N_CITM_Strike1", "Match_COI_N_CITM_Strike2", "Match_COI_N_CITM_Strike3", "Match_COI_N_CITM_Strike4","Match_COI_N_CITM_Strike5",
"Match_COI_N_POTM_Strike1", "Match_COI_N_POTM_Strike2", "Match_COI_N_POTM_Strike3", "Match_COI_N_POTM_Strike4","Match_COI_N_POTM_Strike5",
"Match_COI_N_PITM_Strike1", "Match_COI_N_PITM_Strike2", "Match_COI_N_PITM_Strike3", "Match_COI_N_PITM_Strike4","Match_COI_N_PITM_Strike5"]
coi_analysis = (a_a_coi[a_a_coi1] == True).sum()
return coi_analysis #, a_a_coi, a_a_coi1
# In[ ]:
# Analyse_OI(Merge_CallPutOI_MaxPain):
# The Change in Open Interest data will be analysed
# There are four combinations of Call, Put, ITM and OTM
# values for the options Open Interest.
# All these details are merged with Merge_CallPutOI_MaxPain dataframe.
# In[37]:
def Analyse_OI(Merge_CallPutOI_MaxPain):
import numpy as np
a_a = Merge_CallPutOI_MaxPain[['Date']]
mt = Merge_CallPutOI_MaxPain
a_a['Delta_Close'] = np.where((mt['Close'] > mt['Close'].shift(1)) ,1,np.where((mt['Close'] < mt['Close'].shift(1)),-1,0))
a_a['Delta_OI_COTM_Strike1'] = np.where((mt['OI_COTM_Strike1'] > mt['OI_COTM_Strike1'].shift(1)),1,np.where((mt['OI_COTM_Strike1'] < mt['OI_COTM_Strike1'].shift(1)),-1,0))
a_a['Delta_OI_COTM_Strike2'] = np.where((mt['OI_COTM_Strike2'] > mt['OI_COTM_Strike2'].shift(1)),1,np.where((mt['OI_COTM_Strike2'] < mt['OI_COTM_Strike2'].shift(1)),-1,0))
a_a['Delta_OI_COTM_Strike3'] = np.where((mt['OI_COTM_Strike3'] > mt['OI_COTM_Strike3'].shift(1)),1,np.where((mt['OI_COTM_Strike3'] < mt['OI_COTM_Strike3'].shift(1)),-1,0))
a_a['Delta_OI_COTM_Strike4'] = np.where((mt['OI_COTM_Strike4'] > mt['OI_COTM_Strike4'].shift(1)),1,np.where((mt['OI_COTM_Strike4'] < mt['OI_COTM_Strike4'].shift(1)),-1,0))
a_a['Delta_OI_COTM_Strike5'] = np.where((mt['OI_COTM_Strike5'] > mt['OI_COTM_Strike5'].shift(1)),1,np.where((mt['OI_COTM_Strike5'] < mt['OI_COTM_Strike5'].shift(1)),-1,0))
a_a['Delta_OI_CITM_Strike1'] = np.where((mt['OI_CITM_Strike1'] > mt['OI_CITM_Strike1'].shift(1)),1,np.where((mt['OI_CITM_Strike1'] < mt['OI_CITM_Strike1'].shift(1)),-1,0))
a_a['Delta_OI_CITM_Strike2'] = np.where((mt['OI_CITM_Strike2'] > mt['OI_CITM_Strike2'].shift(1)),1,np.where((mt['OI_CITM_Strike2'] < mt['OI_CITM_Strike2'].shift(1)),-1,0))
a_a['Delta_OI_CITM_Strike3'] = np.where((mt['OI_CITM_Strike3'] > mt['OI_CITM_Strike3'].shift(1)),1,np.where((mt['OI_CITM_Strike3'] < mt['OI_CITM_Strike3'].shift(1)),-1,0))
a_a['Delta_OI_CITM_Strike4'] = np.where((mt['OI_CITM_Strike4'] > mt['OI_CITM_Strike4'].shift(1)),1,np.where((mt['OI_CITM_Strike4'] < mt['OI_CITM_Strike4'].shift(1)),-1,0))
a_a['Delta_OI_CITM_Strike5'] = np.where((mt['OI_CITM_Strike5'] > mt['OI_CITM_Strike5'].shift(1)),1,np.where((mt['OI_CITM_Strike5'] < mt['OI_CITM_Strike5'].shift(1)),-1,0))
a_a['Delta_OI_POTM_Strike1'] = np.where((mt['OI_POTM_Strike1'] > mt['OI_POTM_Strike1'].shift(1)),1,np.where((mt['OI_POTM_Strike1'] < mt['OI_POTM_Strike1'].shift(1)),-1,0))
a_a['Delta_OI_POTM_Strike2'] = np.where((mt['OI_POTM_Strike2'] > mt['OI_POTM_Strike2'].shift(1)),1,np.where((mt['OI_POTM_Strike2'] < mt['OI_POTM_Strike2'].shift(1)),-1,0))
a_a['Delta_OI_POTM_Strike3'] = np.where((mt['OI_POTM_Strike3'] > mt['OI_POTM_Strike3'].shift(1)),1,np.where((mt['OI_POTM_Strike3'] < mt['OI_POTM_Strike3'].shift(1)),-1,0))
a_a['Delta_OI_POTM_Strike4'] = np.where((mt['OI_POTM_Strike4'] > mt['OI_POTM_Strike4'].shift(1)),1,np.where((mt['OI_POTM_Strike4'] < mt['OI_POTM_Strike4'].shift(1)),-1,0))
a_a['Delta_OI_POTM_Strike5'] = np.where((mt['OI_POTM_Strike5'] > mt['OI_POTM_Strike5'].shift(1)),1,np.where((mt['OI_POTM_Strike5'] < mt['OI_POTM_Strike5'].shift(1)),-1,0))
a_a['Delta_OI_PITM_Strike1'] = np.where((mt['OI_PITM_Strike1'] > mt['OI_PITM_Strike1'].shift(1)),1,np.where((mt['OI_PITM_Strike1'] < mt['OI_PITM_Strike1'].shift(1)),-1,0))
a_a['Delta_OI_PITM_Strike2'] = np.where((mt['OI_PITM_Strike2'] > mt['OI_PITM_Strike2'].shift(1)),1,np.where((mt['OI_PITM_Strike2'] < mt['OI_PITM_Strike2'].shift(1)),-1,0))
a_a['Delta_OI_PITM_Strike3'] = np.where((mt['OI_PITM_Strike3'] > mt['OI_PITM_Strike3'].shift(1)),1,np.where((mt['OI_PITM_Strike3'] < mt['OI_PITM_Strike3'].shift(1)),-1,0))
a_a['Delta_OI_PITM_Strike4'] = np.where((mt['OI_PITM_Strike4'] > mt['OI_PITM_Strike4'].shift(1)),1,np.where((mt['OI_PITM_Strike4'] < mt['OI_PITM_Strike4'].shift(1)),-1,0))
a_a['Delta_OI_PITM_Strike5'] = np.where((mt['OI_PITM_Strike5'] > mt['OI_PITM_Strike5'].shift(1)),1,np.where((mt['OI_PITM_Strike5'] < mt['OI_PITM_Strike5'].shift(1)),-1,0))
a_a['Match_OI_COTM_Strike1'] = a_a.Delta_Close.eq(a_a.Delta_OI_COTM_Strike1.shift(1))
a_a['Match_OI_COTM_Strike2'] = a_a.Delta_Close.eq(a_a.Delta_OI_COTM_Strike2.shift(1))
a_a['Match_OI_COTM_Strike3'] = a_a.Delta_Close.eq(a_a.Delta_OI_COTM_Strike3.shift(1))
a_a['Match_OI_COTM_Strike4'] = a_a.Delta_Close.eq(a_a.Delta_OI_COTM_Strike4.shift(1))
a_a['Match_OI_COTM_Strike5'] = a_a.Delta_Close.eq(a_a.Delta_OI_COTM_Strike5.shift(1))
a_a['Match_OI_CITM_Strike1'] = a_a.Delta_Close.eq(a_a.Delta_OI_CITM_Strike1.shift(1))
a_a['Match_OI_CITM_Strike2'] = a_a.Delta_Close.eq(a_a.Delta_OI_CITM_Strike2.shift(1))
a_a['Match_OI_CITM_Strike3'] = a_a.Delta_Close.eq(a_a.Delta_OI_CITM_Strike3.shift(1))
a_a['Match_OI_CITM_Strike4'] = a_a.Delta_Close.eq(a_a.Delta_OI_CITM_Strike4.shift(1))
a_a['Match_OI_CITM_Strike5'] = a_a.Delta_Close.eq(a_a.Delta_OI_CITM_Strike5.shift(1))
a_a['Match_OI_POTM_Strike1'] = a_a.Delta_Close.eq(a_a.Delta_OI_POTM_Strike1.shift(1))
a_a['Match_OI_POTM_Strike2'] = a_a.Delta_Close.eq(a_a.Delta_OI_POTM_Strike2.shift(1))
a_a['Match_OI_POTM_Strike3'] = a_a.Delta_Close.eq(a_a.Delta_OI_POTM_Strike3.shift(1))
a_a['Match_OI_POTM_Strike4'] = a_a.Delta_Close.eq(a_a.Delta_OI_POTM_Strike4.shift(1))
a_a['Match_OI_POTM_Strike5'] = a_a.Delta_Close.eq(a_a.Delta_OI_POTM_Strike5.shift(1))
a_a['Match_OI_PITM_Strike1'] = a_a.Delta_Close.eq(a_a.Delta_OI_PITM_Strike1.shift(1))
a_a['Match_OI_PITM_Strike2'] = a_a.Delta_Close.eq(a_a.Delta_OI_PITM_Strike2.shift(1))
a_a['Match_OI_PITM_Strike3'] = a_a.Delta_Close.eq(a_a.Delta_OI_PITM_Strike3.shift(1))
a_a['Match_OI_PITM_Strike4'] = a_a.Delta_Close.eq(a_a.Delta_OI_PITM_Strike4.shift(1))
a_a['Match_OI_PITM_Strike5'] = a_a.Delta_Close.eq(a_a.Delta_OI_PITM_Strike5.shift(1))
a_a_oi=a_a
a_a1 = ["Match_OI_COTM_Strike1", "Match_OI_COTM_Strike2", "Match_OI_COTM_Strike3", "Match_OI_COTM_Strike4","Match_OI_COTM_Strike5",
"Match_OI_CITM_Strike1", "Match_OI_CITM_Strike2", "Match_OI_CITM_Strike3", "Match_OI_CITM_Strike4","Match_OI_CITM_Strike5",
"Match_OI_POTM_Strike1", "Match_OI_POTM_Strike2", "Match_OI_POTM_Strike3", "Match_OI_POTM_Strike4","Match_OI_POTM_Strike5",
"Match_OI_PITM_Strike1", "Match_OI_PITM_Strike2", "Match_OI_PITM_Strike3", "Match_OI_PITM_Strike4","Match_OI_PITM_Strike5"]
oi_analysis = (a_a_oi[a_a1] == True).sum()
return oi_analysis , a_a_oi, a_a1
# In[ ]:
# In[ ]:
# In[ ]:
# # Main Program Starts
# In[38]:
# Load Data to Dataframes
# Read the Base Data
# Data about Nifty Index is stored in the excel file CapstoneNiftyData.xlsx
# and loaded to the "nifty" DataFrame
# Data about Nifty Index Options is stored in the excel file CapstoneNiftyOptionsData.xlsx
# and loaded to the "nifty_options" DataFrame
nifty, nifty_options=LoadFiles()
# In[39]:
# Display the Features and Observations of nifty df
nifty.head()
# In[40]:
# Confirm the number of Features and Observations in nifty df
nifty.shape
# In[41]:
# Confirm the Features in nifty df
nifty.dtypes
# In[ ]:
# In[42]:
# Display the Features and Observations of nifty_options df
nifty_options.head()
# In[43]:
# Confirm the number of Features and Observations in nifty_optiopns df
nifty_options.shape
# In[44]:
# Confirm the Features in nifty_options
nifty_options.dtypes
# In[ ]:
# This is going to capture the user input, select any number from 1-7 and press enter, as to how many strikes around the ATM price needs to be considered for analysis.
#
# Nifty Index Options has each strike of 50 points apart.
#
# So selecting 5 strikes means 250 points on either side of the ATM or spot price is considered for analysis.
# So ATM = 15000, then the strikes selected are 14750 - 15250.
#
# In[45]:
# Obtain user Input
# The user can choose how many strikes on either side of the ATM Strike
# he wants the data to be analysed
#('1. 05 Strikes = 250 points')
#('2. 10 Strikes = 500 points')
#('3. 15 Strikes = 750 points')
#('4. 20 Strikes = 1000 points')
#('5. 25 Strikes = 1250 points')
#('6. 30 Strikes = 1500 points')
#('7. ALL Strikes')
ui, uip = GetUserInput()
print(ui)
print(uip)
# In[46]:
# Calculate Max Pain data Point and display
mxpn = MaxPain(nifty_options)
mxpn.head()
# In[47]:
mxpn.shape
# In[ ]:
# In[ ]:
# In[48]:
# Calculate Daily Range and other data Point and display
Daily_Range = DailyRange(nifty)
Daily_Range.head()
# In[49]:
Daily_Range.shape
# In[50]:
Daily_Range.dtypes
# In[ ]:
# In[51]:
# MaxPain_Top1() captures the one Top Max Pain considering all the strikes for a day.
MaxPain_Top1 = MaxPain_Top1(mxpn, ui)
MaxPain_Top1.head()
# In[52]:
MaxPain_Top1.tail()
# In[53]:
MaxPain_Top1.shape
# In[ ]:
# In[ ]:
# In[54]:
# MaxPain_IOTM_Top1() captures the one Top Max Pain considering all the strikes
# for a day separated by ITM and OTM.
MaxPain_IOTM_Top1 = MaxPain_IOTM_Top1(mxpn, ui)
MaxPain_IOTM_Top1.head()
# In[55]:
MaxPain_IOTM_Top1.shape
# In[ ]:
# In[ ]:
# In[56]:
# MaxPain_Top5() captures the five Top Max Pain considering all the strikes
# for a day separated by ITM and OTM.
MaxPain_Top5 = MaxPain_Top5(mxpn, ui)
MaxPain_Top5.head()
# In[57]:
MaxPain_Top5.shape
# In[ ]:
# In[ ]:
# In[58]:
# Call_OI_Top5() captures the top five Open Interest strikes for Call options.
Call_OI_Top5= Call_OI_Top5(nifty_options,ui)
Call_OI_Top5.head()
# In[59]:
Call_OI_Top5.shape
# In[ ]:
# In[60]:
# Put_OI_Top5() captures the top five Open Interest strikes for Put options.
Put_OI_Top5 = Put_OI_Top5(nifty_options,ui)
Put_OI_Top5.head()
# In[61]:
Put_OI_Top5.shape
# In[ ]:
# In[62]:
# • CallPut_OI_Top5() captures the top five Open Interest strikes for Call and Put options.
Merge_Call_Put_OI = Merge_Call_Put_OI(Call_OI_Top5, Put_OI_Top5)
Merge_Call_Put_OI.head()
# In[63]:
Merge_Call_Put_OI.shape
# In[ ]:
# In[ ]:
# In[64]:
# Merge_CallPutOI_MaxPain() merges CallPut_OI_Top5 and MaxPain_Top5,
# so that all details are available in one dataframe.
Merge_CallPutOI_MaxPain = Merge_CallPutOI_MaxPain(Merge_Call_Put_OI, MaxPain_Top5, Daily_Range)
Merge_CallPutOI_MaxPain.head()
# In[65]:
Merge_CallPutOI_MaxPain.shape
# In[66]:
Merge_CallPutOI_MaxPain.dtypes
# In[ ]:
# In[ ]:
# # Visualization of Open Interest Data
# In[ ]:
# In[67]:
# Visualise the Nifty Candle Chart for the given period
Candle_Chart(Merge_CallPutOI_MaxPain)
# In[ ]:
# This is going to capture the user input,
# select any number from 1-7 and press enter.
# This considers the first highest Open Interest to the next four levels below.
# Select 1 if you want to Plot the first highest OI level wrt the Close price of the underlying.
#
# Select 2 if you want to Plot the second highest OI level wrt the Close price of the underlying.
#
# Select 7 if you want to Plot the First and second highest OI level wrt the Close price of the underlying.
# In[68]:
# Capture user Input to view the number of OI Levels in the chart
no_levels_oi,ip21 = GetUserInput_IOCharts()
print(ip21)
# In[ ]:
# In[69]:
# Draw Candle Chart along with Call ITM OI
Call_OI_ITM_Chart(Merge_CallPutOI_MaxPain,no_levels_oi)
# In[ ]:
# In[70]:
# Draw Candle Chart along with Call OTM OI
Call_OI_OTM_Chart(Merge_CallPutOI_MaxPain,no_levels_oi)
# In[ ]:
# In[71]:
# Draw Candle Chart along with Put OTM OI
Put_OI_OTM_Chart(Merge_CallPutOI_MaxPain,no_levels_oi)
# In[ ]:
# In[72]:
# Draw Candle Chart along with PUT ITM OI
Put_OI_ITM_Chart(Merge_CallPutOI_MaxPain,no_levels_oi)
# In[ ]:
# In[73]:
# Draw Candle Chart along with Call OTM PUT OTM OI
CallPut_OI_OTM_Chart(Merge_CallPutOI_MaxPain,no_levels_oi)
# In[ ]:
# In[74]:
# Plot the OHLC graph for Nifty
Nifty_OHLC_Chart(Merge_CallPutOI_MaxPain)
# In[ ]:
# In[75]:
# Plot the Scatter diagram for Call ITM OI
Call_OI_ITM_Scatter_Chart(Merge_CallPutOI_MaxPain)
# In[ ]:
# In[76]:
# Plot the OHLC graph and MaxPain
OHLC_Chart_MaxPain(Merge_CallPutOI_MaxPain)
# In[ ]:
# # CHANGE IN OPEN INTEREST
# There are SIX combinations of Call, Put, ITM, OTM, Positive and Negative COI values, for the options Change in OT.
#
# All these details are merged with Merge_CallPutOI_MaxPain dataframe.
# In[ ]:
# In[77]:
# Gather data for Call Change of Open Interest values
Merge_CallPutOI_MaxPain = Call_COI_P_Top5(nifty_options,ui,Merge_CallPutOI_MaxPain)
Merge_CallPutOI_MaxPain.head(10)
# In[78]:
Merge_CallPutOI_MaxPain.dtypes
# In[79]:
Merge_CallPutOI_MaxPain.shape
# In[ ]:
# In[ ]:
# In[80]:
# Calculation for "Change in Open Interest" for CALL Options NEGATIVE VALUES
# Shortlist Change in Open Interest Data for CALL ITM and CALL OTM Options
Merge_CallPutOI_MaxPain = Call_COI_N_Top5(nifty_options, ui,Merge_CallPutOI_MaxPain)
Merge_CallPutOI_MaxPain.head()
# In[81]:
Merge_CallPutOI_MaxPain.shape
# In[ ]:
# In[ ]:
# In[82]:
# Calculation for "Change in Open Interest" for PUT Options POSITIVE VALUES
# Shortlist Change in Open Interest Data for CALL ITM and CALL OTM Options
Merge_CallPutOI_MaxPain = Put_COI_P_Top5(nifty_options, ui,Merge_CallPutOI_MaxPain)
Merge_CallPutOI_MaxPain.head()
# In[ ]:
# In[83]:
Merge_CallPutOI_MaxPain.shape
# In[ ]:
# In[84]:
# Calculation for "Change in Open Interest" for PUT Options NEGATIVE VALUES
# Shortlist Change in Open Interest Data for CALL ITM and CALL OTM Options
Merge_CallPutOI_MaxPain = Put_COI_N_Top5(nifty_options, ui,Merge_CallPutOI_MaxPain)
Merge_CallPutOI_MaxPain.head()
# In[85]:
Merge_CallPutOI_MaxPain.shape
# In[ ]:
# In[ ]:
# In[ ]:
# # Visualization of Change of OI Data
# In[86]:
no_levels_coi,ip21 = GetUserInput_COICharts()
print(ip21)
# In[ ]:
# In[87]:
Call_COI_P_OTM_Chart(Merge_CallPutOI_MaxPain,no_levels_coi)
# In[ ]:
# In[88]:
# Draw Candle Chart along with Chaneg of OI for Call OTM NEGATIVE Values
Call_COI_N_OTM_Chart(Merge_CallPutOI_MaxPain,no_levels_coi)
# In[ ]:
# In[89]:
Put_COI_P_OTM_Chart(Merge_CallPutOI_MaxPain,no_levels_coi)
# In[ ]:
# In[90]:
Put_COI_N_OTM_Chart(Merge_CallPutOI_MaxPain,no_levels_coi)
# In[ ]:
# In[ ]:
# # Analysis and Results Prediction
# In[ ]:
# Analyse_OI() analyses the OI details of how it compares to the todays "Close" wrt previous days OI Strike.
#
# For each level of OI strike for CALL , PUT, ITM and OTM are analysed wrt Close.
#
# If the OI predicts the next days Close level correctly, then OI is able to predict the trend for the next day. Each such True values are compared to the total transaction period and the percentage success rate is gathered. Higher the Percentage better is the predictable power of OI.
#
# In[91]:
# Analyse the Open Interest Data for Call Put ITM and OTM
oi_analysis,a,b = Analyse_OI(Merge_CallPutOI_MaxPain)
# In[92]:
# Probability Number for the Open Interest for 82 Trading Days
oi_analysis
# In[93]:
oi_analysis.shape
# In[94]:
oi_analysis.dtypes
# In[95]:
oi_analysis
# In[96]:
a
a1=a
a1
# In[97]:
adf = pd.DataFrame(a, columns=['Match_OI_COTM_Strike1','Match_OI_COTM_Strike2','Match_OI_COTM_Strike3','Match_OI_COTM_Strike4','Match_OI_COTM_Strike5',
'Match_OI_POTM_Strike1','Match_OI_POTM_Strike2','Match_OI_POTM_Strike3','Match_OI_POTM_Strike4','Match_OI_POTM_Strike5',
'Match_OI_CITM_Strike1','Match_OI_CITM_Strike2','Match_OI_CITM_Strike3','Match_OI_CITM_Strike4','Match_OI_CITM_Strike5',
'Match_OI_PITM_Strike1','Match_OI_PITM_Strike2','Match_OI_PITM_Strike3','Match_OI_PITM_Strike4','Match_OI_PITM_Strike5'])
adf
# In[98]:
adf.shape
# In[99]:
adf1=adf.sum()
adf1
# In[100]:
adf['tool_sum'] = adf[['Match_OI_COTM_Strike1', 'Match_OI_COTM_Strike2', 'Match_OI_COTM_Strike3']].sum(1)
#adf2=adf[adf==True].count(axis=0) # df[df==True].count(axis=0) #.value_counts()
adf
# In[101]:
adf1=pd.DataFrame(adf1,columns=['a'])
adf1
# In[ ]:
# In[ ]:
# In[ ]:
# In[102]:
# Plot the Results of Open Interest Analysis
#coi_analysis.plot.hist()
oi_analysis.plot.bar(stacked=True);
# Result Interpretation
# A value of 30 means that this Level has 30 times out of 82 transactions
# got the correct prediction.
#
# 82 is the number of trading days that we have considered here.
#
# This translates to a Probability of Success = 30/82 = 36.58%
# In[ ]:
# In[ ]:
# In[103]:
coi_analysis = Analyse_COI(Merge_CallPutOI_MaxPain)
# In[104]:
# Probability Number for the Change of Open Interest for 82 Trading Days
coi_analysis
# In[105]:
# Plot the Results of Change of Open Interest Analysis
#coi_analysis.plot.hist()
coi_analysis.plot.bar(stacked=True);
# In[ ]:
# Result Interpretation
# A value of 45 means that this Level has 45 times out of 82 transactions
# got the correct prediction.
#
# 82 is the number of trading days that we have considered here.
#
# This translates to a Probability of Success = 45/82 = 54.87%
# Result Interpretation
#
# Any value above ZERO means that the TREND Prediction is not RANDOM.
#
# So using "Open Intrest Data", it is possible to Predict the Trend of the Underlying.
#
# So using "Change of Open Intrest Data", it is possible to Predict the Trend of the Underlying.
#
# CONCLUSION:
# Using "NIFTY 50 Index Options Open Intrest" Data,
# it is possible to Predict the Trend of the Underlying.
#
#
#
|
a122ea2b3ce98e94a4d01e71fec488efeb01c53d | syurskyi/Python_Topics | /045_functions/008_built_in_functions/zip/_exercises/templates/015_zip() in Python.py | 564 | 3.84375 | 4 | # # Python code to demonstrate the working of
# # zip()
#
# # initializing lists
# name _ "Manjeet" "Nikhil" "Shambhavi" "Astha" # list
# roll_no _ 4 1 3 2 # list
# marks _ 40 50 60 70 # list
#
# # using zip() to map values
# mapped _ z_ ? ? ?
#
# # converting values to print as set
# mapped _ se. ?
#
# # printing resultant values
# print The zipped result is : *; e.._**
# print ?
#
#
# # The zipped result is : {('Shambhavi', 3, 60), ('Astha', 2, 70),
# # ('Manjeet', 4, 40), ('Nikhil', 1, 50)}
#
|
295edbbc221b1928e1ef33b6dc730a0b78abf3ef | pavlenko-aa/geek_python | /lesson08/hw08_1.py | 826 | 3.609375 | 4 | class Data:
@staticmethod
def make_int(param):
date = []
for el in param.split("-"):
date.append(int(el))
return date
@classmethod
def val_data(cls, param):
date = cls.make_int(param)
if int(date[0]) < 1 or int(date[0]) > 31:
print("Дата введена неверно.")
return
if int(date[1]) < 1 or int(date[1]) > 12:
print("Месяц введен неверно.")
return
if int(date[2]) < 1:
print("Год введен неверно.")
return
print(f"Вы ввели все верно. Ваша дата: {param}")
user_data = input("Введите дату в формате ДД-ММ-ГГГГ: ")
Data.make_int(user_data)
Data.val_data(user_data) |
704c5b527cc6d1e116eaf858bcc7ced0a9c72b33 | patrickleweryharris/code-snippets | /python/search_closet.py | 1,004 | 4.21875 | 4 | def search_closet(items, colour):
""" (list of str, str) -> list of str
items is a list containing descriptions of the contents of a closet where
every description has the form 'colour item', where each colour is one word
and each item is one or more word. For example:
['grey summer jacket', 'orange spring jacket', 'red shoes', 'green hat']
colour is a colour that is being searched for in items.
Return a list containing only the items that match the colour.
>>> search_closet(['red summer jacket', 'orange spring jacket', 'red shoes', 'green hat'], 'red')
['red summer jacket', 'red shoes']
>>> search_closet(['red shirt', 'green pants'], 'blue')
[]
>>> search_closet([], 'mauve')
[]
"""
i = 0
coloured_items = []
while i < len(items):
splitted = items [i].split()
if colour in splitted [0]:
coloured_items.append(items [i])
i += 1
return coloured_items
|
e5f861e6b97fa656bf672da731da514a468eb925 | atriekak/LeetCode | /solutions/2. Add Two Numbers.py | 1,176 | 3.90625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
#Time Complexity: O(m + n)
#Space Complexity: O(1)
#where, m and n are the lengths of l1 and l2, respectively
carryover = 0
head = pointer = ListNode(-1)
while l1 or l2 or carryover:
if l1 and l2:
temp = l1.val + l2.val + carryover
l1 = l1.next
l2 = l2.next
elif l1:
temp = l1.val + carryover
l1 = l1.next
elif l2:
temp = l2.val + carryover
l2 = l2.next
else:
temp = carryover
pointer.next = ListNode(temp % 10)
pointer = pointer.next
carryover = temp // 10
return head.next
|
ca4479d1759117938cf194e4d3425d9362771058 | cham0919/Algorithm-Python | /프로그래머스/힙/디스크_컨트롤러.py | 1,745 | 3.53125 | 4 | import heapq
from collections import deque
"""
https://programmers.co.kr/learn/courses/30/lessons/42627?language=python3
"""
jobsList = [
[[0, 3], [1, 9], [2, 6]],
[[24, 10], [18, 39], [34, 20], [37, 5], [47, 22], [20, 47], [15, 34], [15, 2], [35, 43], [26, 1]]
]
returnList = [
9,
74
]
def solution1(jobs):
queue = []
jobs.sort(key=lambda x : x[0])
total = 0
currentJobIdx = 0
currentTime = 0
while currentJobIdx < len(jobs) or len(queue) > 0:
for i in range(currentJobIdx, len(jobs)):
if jobs[i][0] <= currentTime:
heapq.heappush(queue, jobs[i])
currentJobIdx += 1
else:
break
queue.sort(key=lambda x : x[1])
if len(queue) == 0:
currentTime += 1
continue
else:
job = heapq.heappop(queue)
currentTime += job[1]
total += (currentTime-job[0])
return total//len(jobs)
def solution(jobs):
tasks = deque(sorted([(x[1], x[0]) for x in jobs], key=lambda x: (x[1], x[0])))
q = []
heapq.heappush(q, tasks.popleft())
current_time, total_response_time = 0, 0
while len(q) > 0:
dur, arr = heapq.heappop(q)
current_time = max(current_time + dur, arr + dur)
total_response_time += current_time - arr
while len(tasks) > 0 and tasks[0][1] <= current_time:
heapq.heappush(q, tasks.popleft())
if len(tasks) > 0 and len(q) == 0:
heapq.heappush(q, tasks.popleft())
return total_response_time // len(jobs)
for j, r in zip(jobsList, returnList):
result = solution1(j)
if result == r:
print("성공")
else:
print("실패")
|
ee3ee32222271ef85d22d2746706788bdd6157a0 | BelkisDursun/class2-functions-week04 | /4.6reading_number.py | 893 | 3.953125 | 4 | def reading_number(x):
"""Writes readings of numbers between 10 and 100."""
reading1 = ['', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']
reading2 = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']
reading3 = ['Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen',
'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen']
if x.isnumeric() == False:
return 'Wrong input'
if int(x) not in range(10, 100):
return 'Pay attention to the number you entered!!'
for a in range(1, 10):
if int(x)//10 == (a+1):
for i in range(0, 10):
if int(x) % 10 == i:
return reading1[a]+' '+reading2[i]
for b in range(0, 10):
if int(x) % 10 == b:
return reading3[b]
print(reading_number(x=input('Enter a number ')))
|
50ef3aa3266944717d905d034ec66a57d76d9817 | smritta10/PythonTraining_Smritta | /Assignment2_Task2/PyTask2_Ex9_part2.py | 324 | 3.875 | 4 | # Exercise 9
import random
random_number = random.randint(1,101)
answer = ''
while answer!= 'no':
number = int(input("Enter your guess between 1-100: "))
if number == random_number:
print('You won')
break
else:
print('Do you want to continue:')
answer = input()
continue
|
a8a59b2fd356c692d0dec8cdf1aacef65c2e1368 | trung-hn/Project-Euler | /Solution/Problem_63.py | 589 | 3.890625 | 4 | # The 5-digit number, 16807=7(5), is also a fifth power. Similarly, the 9-digit number, 134217728=8(9), is a ninth power.
# How many n-digit positive integers exist which are also an nth power?
# ANSWER: 48
number_set=set()
def calculation(n):
for a in range(1,n+1):
for b in range(1,n+1):
temp=a**b
if b== len(str(temp)):
number_set.add(temp)
print("%d**%d="%(a,b),temp)
calculation(20)
print("--------------------------------------------\n\
Total number of integers satisfying the requirement:",len(number_set))
|
1384a621d88e512be4cb2ee3c292180a37fb44ba | jsarraga/LeetCode | /reorder_data_in_log_files.py | 968 | 3.625 | 4 | def reorderLogFiles(logs):
digits = []
letters = []
ans = []
for string in logs:
# split strings into seperate words
newString = string.split()
# categorize into digits or letter lists
if newString[1].isalpha():
# move the identifier to end of string for the letters so we can sort later
letters.append(" ".join(newString[1:]) + " " + newString[0])
else:
# keep digits in original order. Just append them to digits list
digits.append(" ".join(newString))
# sort letter list alphabetically
letters.sort()
for l in letters:
# split strings into word lists
l = l.split()
# move identifier to the front of the string and append to new list
ans.append(" ".join((l[-1:] + l[:-1])))
return ans + digits
logs = ["dig1 8 1 5 1","let1 art can","dig2 3 6","let2 own kit dig","let3 art zero"]
reorderLogFiles(logs) |
32359f56254e959fb9ff9c74b67a37cd5d63e8b2 | speyermr/xai16 | /xai16/lexer.py | 1,409 | 3.515625 | 4 | def lex_block(block):
lines = block.splitlines()
return lex(lines)
def lex(lines):
# Our return values:
assembly = []
label_map = {}
source_map = {}
# Some labels appear on the line before so we need to track this
label = None
for ii, line in enumerate(lines):
tokens = tokenize(line)
# Empty line
if tokens == []:
continue
# The first token is a label if it ends in ':'
if tokens[0][-1] == ':':
label = tokens[0][:-1]
tokens = tokens[1:]
# Empty line (after parsing the label)
if tokens == []:
continue
# Consume whatever label we have (either from this line, or the
# previous one.)
address = 2 * len(assembly)
if label:
label_map[label] = address
assembly.append(tokens)
source_map[address] = ii
label = None
return assembly, label_map, source_map
def tokenize(line):
r = []
for token in line.split(' '):
# Handle multiple spaces between tokens
if token == '':
continue
# Ignore everything after "//", either as a token or at the start of a
# token.
if token[0:2] == '//':
break
# Strip suffixed commas
if token[-1] == ',':
token = token[:-1]
r.append(token)
return r
|
59daa2f8a42c584b876645a773129ec00e1a5b28 | humyPro/play_python | /map_reduce.py | 898 | 3.9375 | 4 | #!/use/bin/env python
#-*- coding:utf-8 -*-
#生成一个列表
l=[x for x in range(10)]
#print(l)
#平方函数
def f(x):
return x*x
#map函数
r=map(f,l)
r=list(r)
print(r)
#函数2
def f2(x,y):
return x+y
print('reduce')
#reduce方法
from functools import reduce
r=reduce(f2,r)
print(r)
#利用map/reduce实现字符串转数字
#str2int
def fn(x,y):
return x*10+y
def char2num(x):
digits={'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5,
'6': 6, '7': 7, '8': 8, '9': 9}
return digits[x]
def str2int(str):
return reduce(fn,map(char2num,str))
i=str2int('123431')
print(i+1)
#利用map()函数,把用户输入的不规范的英文名字,
#变为首字母大写,其他小写的规范名字
def normalize(name):
return name[0].upper()+name[1:len(name)].lower()
#测试
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)
|
36f3e10faf24eb8cd087faed679c5f1717b263cc | HelloTheWholeWorld/leetCode-python | /array/01.py | 524 | 3.59375 | 4 | from typing import List, Optional
class Solution:
def twoSum(self, nums: List[int], target: int) -> Optional[List[int]]:
res_table = {value : index for index, value in enumerate(nums)}
for i, value in enumerate(nums):
if target-value in res_table and i != res_table[target-value]:
return [i, res_table[target-value]]
return None
def main():
a = [3,2,4]
target = 6
temp = Solution()
print(temp.twoSum(a, target))
if __name__ == '__main__':
main()
|
94321bd49ff8fa0b2aa105fc65f053fd1c062472 | jbgoonucdavis/Portfolio_sample | /ECS32B_6.py | 4,507 | 3.671875 | 4 | # Jack Goon
# 914628387
# ECS 32B A06 Jackson
# Homework Assignment 6
# PROBLEM 1
# Using the buildHeap method, write a sorting function that can sort a list in O(nlogn) time.
# The following code is from the book. I use any applicable methods, as suggested in the homework assignment pdf
# where the professor says "Use the code given in the textbook as your foundation"
class BinHeap:
def __init__(self):
self.heapList = [0]
self.currentSize = 0
def percUp(self,i):
while i // 2 > 0:
if self.heapList[i] < self.heapList[i // 2]:
tmp = self.heapList[i // 2]
self.heapList[i // 2] = self.heapList[i]
self.heapList[i] = tmp
i = i//2
def insert(self,k):
self.heapList.append(k)
self.currentSize = self.currentSize + 1
self.percUp(self.currentSize)
def percDown(self,i):
while (i * 2) <= self.currentSize:
mc = self.minChild(i)
if self.heapList[i] > self.heapList[mc]:
tmp = self.heapList[i]
self.heapList[i] = self.heapList[mc]
self.heapList[mc] = tmp
i = mc
def minChild(self,i):
if i * 2 + 1 > self.currentSize:
return i * 2
else:
if self.heapList[i*2] < self.heapList[i*2+1]:
return i * 2
else:
return i * 2 + 1
def delMin(self):
retval = self.heapList[1]
self.heapList[1] = self.heapList[self.currentSize]
self.currentSize = self.currentSize - 1
self.heapList.pop()
self.percDown(1)
return retval
def buildHeap(self,alist):
i = len(alist) // 2
self.currentSize = len(alist)
self.heapList = [0] + alist[:]
while (i > 0):
self.percDown(i)
i = i - 1
# Function that combines methods from heap class to sort any given list (alist)
def heapSort(alist):
# STEP 1 - Heapify
x = BinHeap()
x.buildHeap(alist)
# STEP 2 - Sort
while x.currentSize > 0:
x.heapList[1], x.heapList[x.currentSize] = x.heapList[x.currentSize],x.heapList[1] # Swap first and last items
x.currentSize -= 1 # reduce size of heap
x.percUp(x.currentSize) # bring up any smaller items from bottom, if applicable
x.percDown(1) # bring down any large items from top, if applicable
return x.heapList[1:] # return heap, exclude the 0 added for convenience
# PROBLEM 2
# 2a
# FORMAT:
# City processed [queue, adding all adjacent to city processed]
# Presented in order, top to bottom
# [Frankfurt]
# Frankfurt [Mannheim Wurzburg Kassel]
# Mannheim [Wurzburg Kassel Karlsruhe]
# Wurzburg [Kassel Karlsruhe Erfurt Nurnberg]
# Kassel [Karlsruhe Erfurt Nurnberg Munchen]
# Karlsruhe [Erfurt Nurnberg Munchen Augsburg]
# Erfurt [Nurnberg Munchen Augsburg]
# Nurnberg [Munchen Augsburg Stuttgart]
# Munchen [Augsburg Stuttgart]
# Augsburg [Stuttgart]
# Stuttgart
# Order: Frankfurt, Mannheim, Wurzburg, Kassel, Karlsruhe, Erfurt, Nurnberg, Munchen, Augsburg Stuttgart
# 2b
# [Frankfurt]
# Frankfurt [Mannheim, Wurzburg, Kassel]
# Mannheim [Wurzburg, Kassel, Karlsruhe]
# Wurzburg [Kassel, Karlsruhe, Nurnberg, Erfurt]
# Kassel [Karlsruhe, Nurnberg, Erfurt, Munchen]
# Karlsruhe [Nurnberg, Erfurt, Munchen, Augsburg]
# Nurnberg [Erfurt, Munchen, Augsburg, Stuttgart]
# Erfurt [Munchen, Augsburg, Stuttgart]
# Munchen [Augsburg, Stuttgart]
# Augsburg [Stuttgart]
# Stuttgart
# Order: Frankfurt, mannheim, Wurzburg, Kassel, Karsruhe, Nurnberg, Erfurt, Munchen, Augsburg, Stuttgart
# 2c - Using leftmost edge
# City processed [stack, adding all adjacent to city processed]
# Frankfurt [Mannheim, wurzburg, kassel]
# Mannheim [Karsruhe wurzburg kassel]
# Karlsruhe [Augsburg wurzburg kassel]
# Augsburg [ Munchen Wurzburg kassel ]
# Munchen [ Nurnberg Kassel Wurzburg kassel]
# Nurnberg [Wurzburg Stuttgart Kassel Wurzburg kassel]
# Wurzberg [Erfurt Stuttgart Kassel Wurzburg kassel]
# Erfurt [Stuttgart Kassel Wurzburg kassel]
# Stuttgart [Kassel Wurzburg kassel]
# Kassel
# Order: Frankfurt Mannheim Karlsruhe Augsburg Munchen Nurnberg Wurzberg Erfurt Stuttgart kassel
# 2d - Using the same process as in 2c
# Order: Frankfurt Mannheim Karlsruhe Augsburg Wurzburg Nurnberg Stuttgart Erfurt Kassel Munchen
|
2a4cee25636217567f8add9b8edd7dbed2e3b519 | SrMarcelo/URI-Python | /Iniciante/1042.py | 706 | 3.6875 | 4 | def ordena_numeros(numeros: list):
for i in range(1, len(numeros)):
posicaoAnterior = i - 1
while posicaoAnterior >= 0:
posicaoAtual = posicaoAnterior + 1
if numeros[posicaoAtual] < numeros[posicaoAnterior]:
numeros[posicaoAnterior], numeros[posicaoAtual] = numeros[posicaoAtual], numeros[posicaoAnterior]
else:
break
posicaoAnterior -= 1
if __name__ == "__main__":
entradas = [int(entrada) for entrada in input().split()]
entradasOriginal = tuple(entradas)
ordena_numeros(entradas)
for num in entradas:
print(num)
print()
for num in entradasOriginal:
print(num)
|
e7c69e2f5e1dd00466c15c08570c074df0e466de | msstate-acm/ACM-ICPC-2015 | /Grid.py | 1,516 | 3.75 | 4 | class Node:
def __init__(self, distance):
self.distance = int(distance)
self.neighbors = []
self.position = None
self.parent = None
def add(self, other):
self.neighbors.append(other)
def addToQ(self, Q):
for n in self.neighbors:
if n not in Q and n != self.parent:
n.parent = self
Q.append(n)
def __repr__(self):
return str(self.distance) + str(self.position)
def BFS(Q):
while Q:
e = Q.pop(0)
if e.position == goalPosition:
return e
e.addToQ(Q)
return -1
h, w = list(map(int, input().split()))
grid = []
for _ in range(h):
grid.append(list(map(Node, input())))
for row in range(h):
for col in range(w):
n = grid[row][col]
n.position = (row,col)
if n.distance == 0:
continue
if row - n.distance >= 0:
n.add(grid[row - n.distance][col])
if row + n.distance < h:
n.add(grid[row + n.distance][col])
if col + n.distance < w:
n.add(grid[row][col + n.distance])
if col - n.distance >= 0:
n.add(grid[row][col - n.distance])
root = grid[0][0]
goalPosition = (h-1, w-1)
Q = []
root.addToQ(Q)
goal = BFS(Q)
if goal == -1:
print(-1)
exit()
parent = goal.parent
pathLength = 0
while parent is not None:
pathLength += 1
parent = parent.parent
print(pathLength)
|
490ddf491c8fc2e1d7f37a6bc96140292459a901 | eaamankwah/Fundamentals-of-Computing | /Course1-An-Introductionto-Interactive-Programming-in-Python1/03-mini-project_Stopwatch.py | 1,848 | 3.84375 | 4 | # template for "Stopwatch: The Game"
# implement simplegui
import simplegui
# define global variables
current = 0 # time
count = 0
wins = 0
stop = False
message = ''
# define event handlers for buttoms; "Start", "Stop" and "Reset".
def start_button_handler():
global stop
stop = True
timer.start()
def reset_button_handler():
global current, count, wins, stop
current = 0
count = 0
wins = 0
stop = False
timer.stop()
def stop_button_handler():
global count, wins, stop
if stop:
stop = False
count = count + 1
if current % 10 == 0:
wins = wins +1
timer.stop()
# define helper function format that converts time
# in tenths of seconds into formatted string A:BC.D
def format(t):
global message
a = int(t // 600) # the amount of minutes in that number
b = int(t - a*600)//100 # the amount of tens of seconds
c = int(t - a*600 - b*100)//10 # the amount of seconds in excess of tens of seconds
d = t % 10 # the amount of the remaining tenths of seconds
message = str(a) + ":" + str(b) + str(c) + "." + str(d)
return message
pass
# define event handler for timer
def tick():
global current
current += 1
# define draw handler
def draw(c):
global message
c.draw_text(format(current), (100, 125), 48, "White")
score = str(wins)+"/"+str(count)
c.draw_text(score, (135,30), 30, "Red")
# create frame
frame = simplegui.create_frame("Stopwatch: The Game", 250, 250)
timer = simplegui.create_timer(100, tick)
# register event handlers
frame.add_button("Start", start_button_handler, 100)
frame.add_button("Stop", stop_button_handler, 100)
frame.add_button("Reset", reset_button_handler, 100)
frame.set_draw_handler(draw)
# start frame
frame.start()
# Please remember to review the grading rubric
|
af809b4bef8343e28191f94a64f04fc6dd2cb5aa | lh6210/cs61a | /practice/sec2.7.py | 4,247 | 4.25 | 4 |
from math import gcd, atan, cos, sin, sqrt
class Number:
"""This class requires the Number objects have a add and mul methods, but doesn't define them.
Moreover, it does not have an __init__ method.
The purpose of Number is to serve as a superclass of various specific number classes.
"""
def __add__(self, other):
return self.add(other)
def __mul__(self, other):
return self.mul(other)
class Rational(Number):
def __init__(self, numer, denom):
g = gcd(numer, denom)
self.number = numer // g
self.denom = denom // g
def __repr__(self):
return 'Rational({0}, {1})'.format(self.number, self.denom)
def add(self, other):
nx, dx = self.number, self.denom
ny, dy = other.number, other.denom
return Rational(nx * dy + ny * dx, dx * dy)
def mul(self, other):
numer = self.numer * other.numer
denom = self.denom * other.denom
return Raitonal(numer, denom)
class Ratio:
def __init__(self, n, d):
self.numer = n
self.denom = d
def __repr__(self):
return 'Ratio({0}, {1})'.format(self.numer, self.denom)
def __str__(self):
return '{0}/{1}'.format(self.numer, self.denom)
def __add__(self, other):
if isinstance(other, int):
n = self.numer + self.denom * other
d = self.denom
elif isinstance(other, Ratio):
n = self.numer * other.denom + self.denom * other.numer
d = self.denom * other.denom
elif isinstance(other, float):
return float(self) + other
g = gcd(n, d)
return Ratio(n // g, d // g)
def __float__(self):
return self.numer/self.denom
def gcd(n, d):
while n != d:
n, d = min(n, d), abs(n - d)
return n
class Account:
interest = 0.01
def __init__(self, account_holder):
self.holder = account_holder
self.balance = 0
def __bool__(self):
return self.balance != 0
def __str__(self):
return self.holder + "\'s account"
class CheckingAccount(Account):
def __init__(self, account_holder):
self.holder = account_holder
self.balance = 0
@property
def interest(self):
return Account.interest * 2
def adder(n):
def addN(k):
return k + n
return addN
class Adder:
def __init__(self, n):
self.n = n
def __call__(self, k):
return self.n + k
class Celsius:
def __init__(self, degree = 0):
self._degree = degree
def to_fahrenheit(self):
return (self._degree * 1.8) + 32
def get_temperature(self):
return self._degree
def set_temperature(self, d):
if d < -273.15:
raise ValueError('Temperature below -273.15 is not possible.')
self._degree = d
class Person:
def __init__(self, firstname, lastname):
self.first = firstname
self.last = lastname
@property
def fullname(self):
return self.first + ' ' + self.last
@fullname.setter
def fullname(self, name):
firstname, lastname = name.split()
self.first = firstname
self.last = lastname
@property
def email(self):
return '{}.{}@email.com'.format(self.first, self.last)
class Complex(Number):
def add(self, other):
return ComplexRI(self.rel + other.rel, self.img + other.img)
def mul(self, other):
return ComplexMA(self.mag * other.mag, self.amp + other.amp)
class ComplexRI(Complex):
def __init__(self, rel, img):
self.rel = rel
self.img = img
def __repr__(self):
return "ComplexRI(" + str(self.rel) + ", " + str(self.img) + ")"
@property
def mag(self):
return sqrt(self.rel ** 2 + self.img ** 2)
@property
def amp(self):
return atan2(self.img, self.rel)
class ComplexMA(Complex):
def __init__(self, m, a):
self.mag = m
self.amp = a
def __repr__(self):
return "ComplexMA( " + str(self.mag) + ", " + str(self.amp) + ")"
@property
def real(self):
return self.mag * math.cos(self.amp)
@property
def img(self):
return self.mag * math.sin(self.amp)
|
a71d818bf07023aec01e336eadc0c99ab5ccf09b | ShinjiKatoA16/icpcFinal2018 | /prob_b.py | 1,968 | 3.5625 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
'''
ICPC Final 2018: Problem B: Comma Sprinkler
'''
import sys
from collections import defaultdict
def sprinkle(strs):
'''
strs: List of str
return: None (update strs)
'''
prev_word = None
words_before = defaultdict(set)
words_after = defaultdict(set)
before_comma = defaultdict(lambda: False)
after_comma = defaultdict(lambda: False)
for word in strs:
if word[-1] == '.' or word[-1] == ',':
cur_word = word[:-1]
suffix = word[-1]
else:
cur_word = word
suffix = ''
if prev_word:
words_before[cur_word].add(prev_word)
words_after[prev_word].add(cur_word)
if suffix == ',':
before_comma[cur_word] = True
if suffix == '.': prev_word = None
else: prev_word = cur_word
#print('words before:', words_before)
#print('words after:', words_after)
#print('before comma:', before_comma)
bc_new = before_comma.copy()
while True:
ac_new = dict()
for prev_word in bc_new:
for next_word in words_after[prev_word]:
if not after_comma[next_word]:
ac_new[next_word] = True
after_comma[next_word] = True
#print('ac_new:', ac_new)
bc_new = dict()
for next_word in ac_new:
for prev_word in words_before[next_word]:
if not before_comma[prev_word]:
bc_new[prev_word] = True
before_comma[prev_word] = True
#print('bc_new:', bc_new)
if not bc_new:
break
#print('after comma:', after_comma)
#print('before comma:', before_comma)
for idx in range(len(strs)):
word = strs[idx]
if before_comma[word]:
strs[idx] = word + ','
strs = sys.stdin.readline().split()
sprinkle(strs)
print (' '.join(strs))
|
d8a1dd84e6b2eb03983838a9d4e9ff53ce5c9ca0 | prateekrk/DSA_C_Python | /Stacks/stack.py | 867 | 3.9375 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
class Stack:
def __init__(self):
self.top=None
def push(self,data):
newNode=Node(data)
newNode.next=self.top
self.top=newNode
def isEmpty(self):
return self.top==None
def pop(self):
current=self.top
temp=current
current=current.next
self.top=current
del(temp)
def stackElements(self):
current=self.top
if(self.isEmpty()):
print("Stack is empty")
return
while(current):
print(current.data," ")
current=current.next
if __name__=="__main__":
s=Stack()
s.push(5)
s.push(4)
s.push(3)
s.push(2)
s.push(1)
s.stackElements()
s.pop()
print("after pop:")
s.stackElements() |
86dc4c9c4cea597bbb05c9536c5619566cdd38f6 | Aelaiig/Computor_V1 | /tools.py | 1,130 | 3.703125 | 4 | import re
def simplifier(equation):
equ = re.sub(r"(^|[\=\+\-])\s*(\d+(?:\.\d+)?)\s*\*?\s*X\s*\^?\s*(\d+)\s*(?=[\+\-\=]|$)", r"\1 \2 * X^\3 ", equation) # NXN || N*XN || NX^N => N * X^N
simple = re.sub(r"(^|[ +=-])(\d+(?:(\.\d+)?))($|[ ][^\*])", r" \2 * X^0\4", equ) # case X alone
simple2 = re.sub(r"([\+\-\=]|^)\s*[X]([\s*]|$)", r"\1 1 * X^1 ", simple) # case N alone
simple3 = re.sub(r"([^\*]|^)([ ]|^)([X][\^])", r"\1 1 * \3", simple2) # case X^N
return simple3
def ft_ftoa(number):
ret = str(number)
ln = len(ret)
check = ret[ln - 2:]
if check == ".0":
return ret[:ln - 2]
return ret
def ft_round(x) :
s = str(x)
j = s.find(".")
if j == -1 :
return(x)
round = s[:j + 5]
return (float(round))
# sqrt: x = (x + x/delta)/2 Algorithme de Babylone, Méthode de Héron
def sqrt(x, delta, prevResult, i):
if (i < 1000): # to avoid too long calcul
i += 1
x = (x + delta / x)/2
if x == prevResult:
return (ft_round(x))
else:
return sqrt(x, delta, x, i)
else:
return (ft_round(x))
|
cdc20f5c0342a3396195c64a0f29bd40535502de | shivam-kislay/Calender-Print | /Calendar_Print.py | 3,380 | 4.4375 | 4 | # Program to take month and year as user input and print the calendar.
# Done By: Shivam Kislay 119220420
# Creation Date: 16-10-2019
# Function to determine if the entered year is a leap year.
# returns true if the year is leap else false
def is_leap(year):
divby4 = year % 4 == 0
divby100 = year % 100 == 0
divby400 = year % 400 == 0
return divby4 and (not divby100 or divby400)
# Function to return the number of days present in the month.
def num_days(month, year):
# Assign number to their respective months
Jan, March, May, July, Aug, Oct, Dec = 1, 3, 5, 7, 8, 10, 12
April, June, Sept, Nov = 4, 6, 9, 11
# Set variable thirty_days as true if month is equal to the below mentioned condition
thirty_days = (month == Sept) or (month == April) or (month == June) or (month == Nov)
# Set variable thirty_one_days as true if month is equal to the below mentioned condition
thirty_one_days = (month == Jan) or (month == March) or (month == May) or (month == Aug) or (month == Oct) \
or (month == Dec) or (month == July)
if thirty_days:
return 30
elif thirty_one_days:
return 31
elif is_leap(year):
return 29
else:
return 28
# Function to Evaluate month and year and return the identifier for the start day of the month.
# e.g. 0 for Sunday, 1 for Monday, ......, 6 for Saturday
def start_day(month, year):
total_days = 0
year_counter = 2000
month_counter = 1
# logic to calculate total number of days between the mentioned month, year and 1, 1, 2000.
for yy in range(year_counter, year + 1):
for mm in range(month_counter, 13):
if mm == month and yy == year:
break
days = num_days(mm, yy)
total_days = total_days + days
# We add 6 to the total number of days because 1/1/2000 was Saturday.
# Positional Value of Saturday is 6
return (total_days + 6) % 7
# Function to Print the Calendar in the Standard Calendar Format
def print_calendar(day, number_of_days):
# loop to print calendar from the second row onwards
while day <= number_of_days:
# print("\n")
print('')
# loop to print the days with each day padded with 3 spaces each.
for k in range(7):
print("%3s" % day, end="")
day = day + 1
if day > number_of_days:
break
# Parent function to evaluate the start position of the month and print the calendar..
# ..of the given month and year
def cal(month, year):
# List to hold The week days. With [0] as Su and so on
week = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
# loop to print the Calendar Header
for w in week:
print("%3s" % w, end="")
print("")
# Function Call to return the starting position of each month.
month_start_pos = start_day(month, year)
date = 1
# Loop to fill the first day till the month start day with blanks
for i in range(month_start_pos):
print(" ", end="")
# loop to print the first row of the calendar
for j in range(month_start_pos, 7):
print("%3d" % date, end="")
date = date + 1
# Function call to print the calendar
print_calendar(date, num_days(month, year))
|
06b661716191d62c5e12b4beba18388d0a0df333 | nidhip2/Final-Project-IS452-GoogleAPI | /google_api.py | 2,319 | 3.703125 | 4 | from flask import Flask, render_template, jsonify # Imorting the flask framework and returns json object and one renders HTMl object .
import requests # Importing the request package for script
from api_key import key # Importing the API key value from the key file.
app = Flask(__name__) #Here we are creating the flask app import the flask.
searchtext_url = "https://maps.googleapis.com/maps/api/place/textsearch/json" #API url for text search taken from API google developers guide object type is json
detailstext_url = "https://maps.googleapis.com/maps/api/place/details/json" # API url for place details taken from API google developers guide
@app.route("/", methods=["GET"]) # here we are using the GET mothod to fetch details and used app.route
def retreive(): # Funtion defined
return render_template('search_page.html') # the route on the render_template returns the search page
@app.route("/sendRequest/<string:query>") # The send request will take in the query
def results(query):
print(query) # test
# here we create a payload object where keys and values of the data is being sent over.
# same way we create a request object
search_payload = {"key":key, "query": query} # at payload the mandatory parameters are key = api key and query i.e a text string on which search needs to be performed.
search_request = requests.get(searchtext_url, params=search_payload) # we are sending it to search url and params value is the value in search payload . This will give output as response
search_json = search_request.json() # This will convert the above returned value in the Json format.
print(search_json) # test print
place_id = search_json["results"][0]["place_id"] # For the URL to search in the JSON extracted we take the oth index of result and in that the place_id
# The same things are performed for the second API url .
details_payload = {"key":key, "placeid":place_id}
details_response = requests.get(detailstext_url, params=details_payload)
details_json = details_response.json()
print(details_json)
url = details_json["result"]["url"] # The url is returned from the JSOn
print(url)
return jsonify({'result': url})
if __name__ == "__main__": # THis commands says that start the webserver
app.run(debug=True)
|
b3147ec2bf5fbfba45d9858379dec5625c99557a | jinzhe-mu/muwj_python_hm | /01_python基础/m_10_课后练习.py | 649 | 3.890625 | 4 | """
需求:
在控制台依次提示用户输入:姓名、公司、职位、电话、邮箱
按照以下格式输出:
**************************************************
公司名称
姓名 (职位)
电话:电话
邮箱:邮箱
**************************************************
"""
name = input("请输入姓名:")
company = input("请输入公司的名称:")
title = input("请输入职位:")
phone = input("请输入电话:")
email = input("请输入邮箱:")
print("*" * 50)
print("%s" % company)
print()
print(" %s(%s)" % (name, title))
print()
print("电话%s" % phone)
print("邮箱:%s" % email)
print("*" * 50)
|
152a42902e6de1182b4bc7694497b28d2041e7ab | mathalaichandar/mc-hr-learn | /ds/hr-ds-ar-02.py | 1,034 | 3.5625 | 4 | #!/bin/python3
import sys
def splitArr(arr, a):
end = len(arr[0])
print("array length: " + str(len(arr[0])))
if len(arr) == 2:
return 0
else:
temp = []
print("End: " + str(end))
print(len(arr))
for i in range(0, len(arr) - 2):
temp.extend(arr[i][0+i:3+i])
temp.append(arr[i+1][1+i])
temp.extend(arr[i+2][0+i:3+i])
a.append(temp)
temp = []
print(len(a))
return a.append(splitArr(arr[1:],a))
def splitArr1(arr):
a = []
for i in range(0, len(arr) - 2):
temp = []
for j in range(0, len(arr[0]) - 2):
temp.extend(arr[i][0+j:3+j])
temp.append(arr[i+1][1+j])
temp.extend(arr[i+2][0+j:3+j])
a.append(sum(temp))
temp = []
return a
arr = []
for arr_i in range(6):
arr_t = [int(arr_temp) for arr_temp in input().strip().split(' ')]
arr.append(arr_t)
print(arr[1:])
new_arr = []
ar = splitArr1(arr)
print(max(ar))
|
8441b0b25d220a1da337669b91f49bafe9bb406f | quanghieu-vu/outofstock | /my_utils.py | 1,606 | 3.5625 | 4 | def load_data_from_csv(csv_file, users_to_i = {}, items_to_i = {}):
"""
Loads data from a CSV file located at `csv_file`
where each line is of the form:
display_id, ad_id, clicked, event_doc_id, ad_doc_id
Initial mappings from user and item identifiers
to integers can be passed using `users_to_i`
and `items_to_i` respectively.
This function will return a data array consisting
of (user, item) tuples, a mapping from user ids to integers
and a mapping from item ids to integers.
"""
data = []
if len(users_to_i.values()) > 0:
u = max(users_to_i.values()) + 1
else:
u = 0
if len(items_to_i.values()) > 0:
i = max(items_to_i.values()) + 1
else:
i = 0
total_item = 0
input_file = open(csv_file, "r")
line = input_file.readline().strip()
while 1:
line = input_file.readline().strip()
if line == '':
break
total_item += 1
if total_item % 5000000 == 0:
print('Finished {} items...'.format(total_item))
display_id, ad_id, clicked, event_doc_id, ad_doc_id = line.split(",")
if int(clicked) == 1:
if not users_to_i.has_key(event_doc_id):
users_to_i[event_doc_id] = u
u += 1
if not items_to_i.has_key(ad_doc_id):
items_to_i[ad_doc_id] = i
i += 1
data.append((users_to_i[event_doc_id], items_to_i[ad_doc_id]))
input_file.close()
return data, users_to_i, items_to_i
|
032df4bccc94b8f371bfd2821bbcd597fe5ea28c | katochayush/automative_mailing_system.py | /pythonproject.py | 2,221 | 3.5 | 4 | import pandas as pd
import smtplib as sm
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
#READ THE EMAILS FROM EXCEL FILE
data=pd.read_excel("Employees_Details.xlsx")
#print(type(data))
email_col=data.get("Employee_Email")
list_of_emails=list(email_col)
print(list_of_emails)
try:
server=sm.SMTP("smtp.gmail.com",587)
server.starttls()
server.login("nainageorge04@gmail.com","Naina@04")
from_="nainageorge04@gmail.com"
to_=list_of_emails
message=MIMEMultipart("alternative")
message['Subject']="Hello, this is Ayushi George! Have a nice Day!"
message['from']="nainageorge04@gmail.com"
html='''
<html>
<head>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
</head>
<body>
<p>These are the MY ACHIEVEMENTS :</p>
<h2>ACHIEVEMENTS</h2>
<table>
<tr>
<th>DATE</th>
<th>YEAR</th>
<th>ACTIVITY</th>
</tr>
<tr>
<td>17 January 2021</td>
<td>FIRST YEAR</td>
<td>HACKATHON TEAM LEADER</td>
</tr>
<tr>
<td>8 Feburary 2021</td>
<td>FIRST YEAR </td>
<td>BAGGED 4TH POSITION IN DEBATE COMPETITION</td>
</tr>
<tr>
<td>23 January 2021</td>
<td>FIRST YEAR</td>
<td>E-MEET WITH MANEKA GANDHI</td>
</tr>
<tr>
<td>25 January 2021 </td>
<td>FIRST YEAR</td>
<td>PAID CONTENT WRITING INTERNSHIP</td>
</tr>
<tr>
<td>26 January 2021 </td>
<td>FIRST YEAR</td>
<td>SOCIAL MEDIA MARKETING INTERNSHIP</td>
</tr>
<tr>
<td>31 January 2021 </td>
<td>SECOND YEAR</td>
<td>CLASS REPRESENTATIVE</td>
</tr>
</table>
</body>
</html>
'''
text=MIMEText(html,"html")
message.attach(text)
server.sendmail(from_,to_,message.as_string())
print("Message has been send to the emails .")
except exeption as e :
print(e)
|
7ac89eda73604202987f3ab60dd9d7994fd207d1 | hannahrjiang/createSpotifyPlaylist | / create_playlist.py | 922 | 3.640625 | 4 | from spotify import Spotify
from youtube import Youtube
def main():
sp = Spotify()
yt = Youtube()
yt_playlist_id = input("Enter youtube playlist id: ")
spotify_playlist_name = input("Enter a name for your spotify playlist: ")
spotify_playlist_id = sp.create_playlist(spotify_playlist_name)
songs = yt.get_songs_from_playlist(yt_playlist_id)
for song in songs:
song_uri = sp.get_song_uri(song.artist, song.title)
if not song_uri:
print(f"{song.artist} - {song.title} was not found!")
continue
was_added = sp.add_song_to_playlist(song_uri, spotify_playlist_id)
if was_added:
print(f'{song.artist} - {song.title} was added to playlist.')
total_songs_added = sp._num_playlist_songs(spotify_playlist_id)
print(f'Added {total_songs_added} songs out of {len(songs)}')
if __name__ == "__main__":
main() |
c260ed9f2b2b318548bda4afa57d473671117a13 | SUTDNLP/ZPar | /scripts/tools/zpar/countfeature.py | 348 | 3.515625 | 4 | import re
g_reHeader = re.compile(r'^[A-Za-z0-9]+ ([0-9]+)$')
def countfeature(path):
file = open(path)
count = 0
for line in file:
match = g_reHeader.match(line[:-1])
if match:
count += int(match.group(1))
file.close()
return count
if __name__ == '__main__':
import sys
print countfeature(sys.argv[1])
|
c15c1e0f72cdfb62a5b911dc98fd1c5b4f003781 | kryvokhyzha/examples-and-courses | /some-ml-examples/ipython-minibook-master/chapter4/gui.py | 627 | 3.671875 | 4 | """Basic GUI example with PyQt."""
from PyQt4 import QtGui
class HelloWorld(QtGui.QWidget):
def __init__(self):
super(HelloWorld, self).__init__()
# create the button
self.button = QtGui.QPushButton('Click me', self)
self.button.clicked.connect(self.clicked)
# create the layout
vbox = QtGui.QVBoxLayout()
vbox.addWidget(self.button)
self.setLayout(vbox)
# show the window
self.show()
def clicked(self):
msg = QtGui.QMessageBox(self)
msg.setText("Hello World !")
msg.show()
window = HelloWorld()
|
d0fc29ce8b3d6b60628fdd158e8fa06f27f92014 | KatiePawlik/DatabaseProject | /src/models/MedicalVisit.py | 1,161 | 3.53125 | 4 | class MedicalVisit:
randomId = 0
'''
Model which stores a medical visit record. A medical visit is an instance
where a patient consulted a doctor for any reason.
patient(User) - Patient that attended this vist
doctor(Doctor) - Doctor that attended to this visit
init(None,patient,doctor) - Create object from random values
init(visitId, None, None) - Create object with database lookup
init(visitId, patient, doctor) - Create object from values
'''
def __init__(self, visitId=None, notes = None, patient=None, doctor=None):
if (visitId == None):
# "Create self from random values
self.id = MedicalVisit.randomId
MedicalVisit.randomId += 1
self.patient = patient
self.doctor = doctor
self.notes = "Patient Chart information. Maybe some symptoms?"
elif (patient == None or doctor == None):
# Get visit from database or cache
self.id = visitId
else:
self.id = visitId
self.patient = patient
self.doctor = doctor
self.notes = notes
|
8d29f06536be8f395cfd9a386f595de753189bb5 | geraldo1993/CodeAcademyPython | /Conditionals & Control Flow/This and That (or This, But Not That!).py | 1,080 | 3.515625 | 4 | '''Boolean operators aren't just evaluated from left to right. Just like with arithmetic operators, there's an order of operations for boolean operators:
not is evaluated first;
and is evaluated next;
or is evaluated last.
For example, True or not False and False returns True. If this isn't clear, look at the Hint.
Parentheses () ensure your expressions are evaluated in the order you want. Anything in parentheses is evaluated as its own unit.
Instructions
Assign True or False as appropriate for bool_one through bool_five.
Set bool_one equal to the result of False or not True and True
Set bool_two equal to the result of False and not True or True
Set bool_three equal to the result of True and not (False or False)
Set bool_four equal to the result of not not True or False and not True
Set bool_five equal to the result of False or not (True and True)'''
bool_one = False or not True and True
bool_two = False and not True or True
bool_three = True and not (False or False)
bool_four = not not True or False and not True
bool_five = False or not (True and True)
|
bec8990e38dde23c863f222761457dcdb3ef585c | MikeCalabro/euler-everywhere | /Py-Solutions/Problem-02.py | 619 | 3.8125 | 4 | # By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
# Creates a list of Fibonacci numbers below a certain limit number
def fib_maker(limit):
fib_arr = [1,2]
while fib_arr[-1] + fib_arr[-2] <= limit:
fib_arr.append(fib_arr[-1] + fib_arr[-2])
return fib_arr
# Creates an array of all the even elements of the fib list made above and sums them up
def even_fib_summer(fib_list):
return sum([i for i in fib_list if i % 2 == 0])
def main():
print(even_fib_summer(fib_maker(4000000)))
if __name__ == "__main__":
main()
|
247163c7bd6687403d9488d650c6150c18de1f46 | flaskur/leetcode | /explore/recursion/generate_trees.py | 920 | 3.703125 | 4 | # Given an integer n, generate all structurally unique bst that store values 1 to n.
# You probably need a outer for loop. No idea how to do this.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def generateTrees(self, n: int) -> List[TreeNode]:
if n == 0:
return [[]]
def helper(start: int, end: int) -> List[TreeNode]:
trees = []
if start < end:
trees.append(None)
return trees
if start == end:
trees.add(TreeNode(start))
return trees
left = []
right = []
for i in range(start, end + 1):
left = helper(start, i - 1)
right = helper(i + 1, end)
for current_left in left:
for current_right in right:
root = TreeNode(i)
root.left = current_left
root.right = current_right
trees.append(root)
return trees
return helper(1, n) |
8fdb9375b0f2602d87a7f9ba7cdd00bae10f31d9 | TamizhselvanR/marana-coder | /Python-problems/basics/number-conv/oct-dec.py | 187 | 3.703125 | 4 | # Octal to Decimal Conversion
hex = list('515')
ans = 0
for i in range(len(hex)):
dig = hex.pop()
ans += int(dig) * pow(8, i)
print(ans)
# Inbuilt Method
print(int('515', 8))
|
b45d5dfe8804a38b50fd7e5e200c7672bb6cc7c2 | db3124/bigdata_maestro | /Python/Py_projects/chap08/code02_str2_copy.py | 245 | 3.53125 | 4 | inStr = input('문자열을 입력하세요: ')
# new = ''
# for i in range(len(inStr)):
# new += inStr[len(inStr)-1-i]
#
# print(new)
# =================================
for i in range(-1, -(len(inStr)+1), -1):
print(inStr[i], end='') |
7fbeb11d8b0af971caa55b9abc0f99a88df954dc | josefloresgabriel/Exercicios-in-python | /Exercícios do curso em video/Exercício 53.py | 188 | 4.03125 | 4 | f = str(input('Digite uma frase: ')).strip().replace(' ', '')
fn = f[::-1]
print(f, fn)
if f == fn:
print('A frase É um PALINDROMO!')
else:
print('A frase NÃO é um PALINDROMO!') |
9a53d54a1c0cfe64c5c7a8f20b5ed8dc4f7f85b6 | Lucas-Guimaraes/Reddit-Daily-Programmer | /Easy Problems/341-350/343easy.py | 1,264 | 3.71875 | 4 | #https://www.reddit.com/r/dailyprogrammer/comments/7hhyin/20171204_challenge_343_easy_major_scales/
#Solfege index, chromatic scale
sol_idx = {'Do': 0, 'Re': 1, 'Mi': 2, 'Fa': 3, 'So': 4, 'La': 5, 'Ti': 6}
chrom_scale = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
def note(key, sol):
idx = sol_idx[sol]
cur = chrom_scale.index(key)
major_steps = [2, 2, 1, 2, 2, 2, 0]
major_lst = []
for i in range(7):
if cur > 11:
cur -= 12
major_lst.append(chrom_scale[cur])
cur += major_steps[i]
if idx+1 == len(major_lst):
return major_lst[-1]
#Input
print("Welcome to note!")
print("Give a key and a solfege (Do, Re, Mi, Fa, So, La, Ti)")
print("And this will return the result.")
print("\n~*~----------------~*~\n")
#Run code
theory = True
while theory:
n = raw_input()
if n.lower() == 'q':
break
key, sol = n.split()
key, sol = key.upper(), sol.capitalize()
if key in chrom_scale and sol in sol_idx.keys():
print(note(key, sol))
print("Press enter to exit")
#Test case:
#print(note("C", "Do"))
#print(note("C", "Re"))
#print(note("C", "Mi"))
#print(note("D", "Mi"))
#print(note("A", "Fa")) |
3addff1cf31f1d003499633aeb46ba5b006b76dd | avillaamil/Reading-WritingElectronicText | /gooetry/cut_up2.py | 414 | 3.53125 | 4 | import sys
import random
article = list()
for line in open('miami.txt'):
# strip the lines of carriage returns etc
line = line.strip()
# add this data to the set
article.append(line)
random.shuffle(article)
comments = list()
for line in open('miami_comment.txt'):
line2 = line.strip()
comments.append(line2)
random.shuffle(comments)
for line, line2 in zip(article, comments):
print line, line2 |
b75269bb20f41b42a364bad524ed761cffc651df | drewavis/mpl_python | /intro_to_python/guess_game.py | 443 | 4.125 | 4 | # let's guess a number between 1 and 10
import random
print "Let's play a game!"
print "I'm thinking of a number between 1 and 10, can you guess it?"
secret_number = random.randint(1,10)
# print "the secret number is: {0}".format(secret_number)
guess = input("Enter a number: ")
print "You guessed: {}".format(guess)
if guess == secret_number:
print "You win!"
else:
print "You lose! It was: {}".format(secret_number)
|
1af62ed807c10a73ad37bc41cd20888bcda8441d | crumjo/Structures-Project4 | /zorkoween.py | 10,601 | 3.5 | 4 | #! /usr/bin/env python3
#READ ME!!!
#okay so I updated alot, I updated all monster and weapons class with a
#constructer to make the right type of monster or weapon. I made a
#constructer for player. I made the neighborhood and I don't think its a
#2d array but it should work. I made a game method to be called at start
#that will initiate player and neighborhood and fill it with houses and houses
#with monsters. I want to clean this up though would it be possible to make files
#for monsters and weapons seperately? We still need to read from command line or
#gui to make it so the player moves from house to house and attacks. And we
#need to make sure edge cases our covered. Also im sorry if the if statements arent
#right. I left comments where stuff is kinda funky and I know that updating the
#monster isn't right. Maybe we should do a turn command? We also need a method for
#monsters to attack.
from observe import Observable
from observe import Observer
import random
class Monster(Observable):
name = ""
health = -1
attack = -1
def get_health(self):
return self.health
def get_name(self):
return self.name
def get_attack(self):
return self.attack
def update_health(self, dmg):
self.health = self.health - dmg
class Vampire(Monster):
def Vampire(self):
name = "Vampire"
health = random.randint(100, 200)
attack = random.randint(10, 20)
class Ghoul(Monster):
def Ghoul(self):
name = "Ghoul"
health = random.randint(40, 80)
attack = random.randint(15, 30)
class Zombie(Monster):
def Zombie(self):
name = "Zombie"
health = random.randint(50, 100)
attack = random.randint(0, 10)
class Werewolf(Monster):
def Werewolf(self):
name = "Werewolf"
health = 200
attack = random.randint(0, 40)
class Person(Monster):
def Person(self):
name = "Person"
health = 100
attack = -1
class House(Observer):
def update(self):
print "Monster Updated."
class Neighborhood(object):
def __init__(self, number):
self.neighborhood = [number][number]
def place_house(self, x , y, house):
self.neighborhood[x][y] = house
def get_house(self, x, y)
return self.neighborhood[x][y]
class Player(object):
def player():
health = random.randint(100, 125)
attack = random.randint(10, 20)
inventory = []
for i in range(0, 9):
temp = random.randint(1, 4)
if temp == 1:
print("Hershey Kisses")
item = HersheyKisses
inventory.add(item)
if temp == 2:
print ("Sour Straws")
item = SourStraws()
inventory.add(item)
if temp == 3:
print ("Chocolate Bars")
item = ChocolateBars()
inventory.add(item)
if temp == 4:
print ("Nerd Bombs")
item = NerdBombs()
inventory.add(item)
def update_p_health(self, dmg):
self.health = self.health - dmg
def get_p_health(self):
return self.health
def get_p_attack(self):
return self.attack
class Weapon(object):
name = ""
attack = 0.0
uses = 0
def get_name(self):
return self.name
def get_attack(self):
return self.attack
def get_uses(self):
return self.uses
def update_use(self):
self.uses = self.uses - 1
class HersheyKisses(Weapon):
def kisses(self):
name = "Hershey Kisses"
attack = 1
uses = 1
class SourStraws(Weapon):
def sour_straws(self):
name = "Sour Straw"
attack = random.uniform(1, 1.75)
uses = 2
class ChocolateBars(Weapon):
def choc_bar(self):
name = "Chocolate Bar"
attack = random.uniform(2, 2.4)
uses = 4
class NerdBombs(Weapon):
def nerd_bomb(self):
name = "Nerd bomb"
attack = random.uniform(3.5, 5)
uses = 1
class game():
def main(self, argsv):
#argsv = zorkoween.py main int
#split args v
edge = argsv[2]
#builds neighborhood
#should this be its own helper method??
Neighborhood caldesac = Neighborhood(edge)
#builds houses in neighborhood
for r in range(0,edge - 1):
for c in range(0,edge - 1):
house = House()
temp = random.randint(0,9)
for x in range(0, temp):
random = random.randint(0, 4)
if random == 0:
print("Vampire")
monster = Vampire()
house().add_observer(monster)
if random == 1:
print("Ghoul")
monster = Ghoul()
house().add_observer(monster)
if random == 2:
print ("Zombie")
monster = Zombie()
house().add_observer(monster)
if random == 3:
print ("Werewolf")
monster = Werewolf()
house().add_observer(monster)
if random == 4:
print ("Person")
monster = Person()
house().add_observer(monster)
caldesac.placehouse(r,c)
#intiates player
you = new player()
#this is where you are at! postion x,y in the neigborhood
x_position = 0;
y_position = 0;
#c_house is the current house you are in
c_house = caldesac.get_house(x_position, y_position)
#I think this is right
def movement(self, direction):
#if to check if move is valid
#then moves
if direction == "east":
#this is gonna move you east if able
if x_direction is not 0:
print ("You are in a new house to the left!")
x_direction = x_direction - 1
c_house = culdesac.get_house(x_position, y_position)
if direction == "north":
#this is gonna move you west if able
if x_direction is not 0:
print ("You are in a new house to the north!")
y_direction = y_direction - 1
c_house = culdesac.get_house(x_position, y_position)
if direction == "west":
#this is gonna move you west if able
if x_direction is not edge:
print ("You are in a new house to the west!")
x_direction = x_direction + 1
c_house = culdesac.get_house(x_position, y_position)
if direction == "south":
#this is gonna move you west if able
if x_direction is not edge:
print ("You are in a new house to the south!")
y_direction = y_direction + 1
c_house = culdasac.get_house(x_position, y_position)
#you attack entire house, pass in house at caldasac[x][y]
#passes in weapon to see if monster is affected and figure out dmg
#needs case checking if the item is in your inventory
#if muiltiple instance of a weapon is in inventory need to make sure
#only that one is updated :/
def attack(self, house, weapon):
damage = player.get_p_attack() * weapon.get_attack()
residents = house.get_monsters()
for x in residents:
if weapon.get_name == "Nerd bomb":
weapon.update_use()
if x.get_name == "Ghoul":
x.update_health(attack*5)
#this should be position in array and monster in that spot
house.update_monster(x, x)
else:
x.update_health(attack)
#this should be position in array and monster in that spot
house.update_monster(x, x)
if weapon.get_name == "Chocolate Bar":
weapon.update_use()
if x.get_name == "Vampire" || "Werewolf":
x.update_health(0)
#this should be position in array and monster in that spot
house.update_monster(x, x)
else:
x.update_health(attack)
#this should be position in array and monster in that spot
house.update_monster(x, x)
if weapon.get_name == "Sour Straw":
weapon.update_use()
if x.get_name == "Werewolf":
x.update_health(0)
#this should be position in array and monster in that spot
house.update_monster(x, x)
elif x.get_name == "Zombie":
x.update_health(attack*2)
#this should be position in array and monster in that spot
house.update_monster(x, x)
else:
x.update_health(attack)
#this should be position in array and monster in that spot
house.update_monster(x, x)
if weapon.get_name == "Hershey Kisses":
x.update_health(attack)
#this should be position in array and monster in that spot
house.update_monster(x, x)
if __name__ == '__main__':
culdesac = Neighborhood(3, 3)
for i in range(0,2):
house = House()
temp = random.randint(0,9)
for j in range(0, temp):
random = random.randint(0, 4)
if random == 0:
print("Vampire")
vampire = Monster()
house().add_observer(vampire)
if random == 1:
print("Ghoul")
ghoul = Monster()
house().add_observer(ghoul)
if random == 2:
print ("Zombie")
zombie = Monster()
house().add_observer(zombie)
if random == 3:
print ("Werewolf")
werewolf = Monster()
house().add_observer(werewolf)
if random == 4:
print ("Person")
person = Monster()
house().add_observer(person)
|
edc047a9fa9316f55d29a4db34c0f9611a4bd9fc | RickGroeneweg/UvAAxelrod | /country.py | 1,859 | 3.609375 | 4 | from .enums import random_action
import numpy as np
class Country:
"""
stores country hypterparamters, but also state from the simulation
"""
def __init__(self, name, m, location, e, i, sqrt_area):
# Variables that stay the same during simulations
self.name = name
self.m = m
self.e = e
self.i = i
self.location = location
self.sqrt_area = sqrt_area
self.self_reward = None
# State variables, not yet initialized since that will be done in the tournament
self.fitness = None
self.fitness_history = []
# private attributes, they should only be changed with `change_strategy`
self._strategy = None
self._evolution = []
def __str__(self):
return f'<{self.name}>'
def __repr__(self):
return f'<{self.name}>'
def change_strategy(self, round_num, strategy):
"""
parameters:
- round_num: int, round number when the change occured
- strategy: new strategy that the country adopts
side effects:
- set self._strategy to the new strategy
- appends self.evolution
"""
self._strategy = strategy
self._evolution.append((round_num, strategy))
def select_action(self, selfmoves, othermoves, noise_threshold):
r = np.random.uniform()
if r < noise_threshold:
# there is a chance of {noise_threshold} that this action will
# be randomly selected
return random_action()
else:
return self._strategy(selfmoves, othermoves)
def get_current_strategy(self):
"""
returns:
- current strategy
"""
return self._strategy
|
be7b2c36262f474fd6c68dddf250276059cce3b5 | cczhong11/Leetcode-contest-code-downloader | /Questiondir/756.pour-water/756.pour-water_133967205.py | 850 | 3.578125 | 4 | class Solution(object):
def pourWater(self, heights, V, K):
"""
:type heights: List[int]
:type V: int
:type K: int
:rtype: List[int]
"""
for v in range(V):
# print v
i = K
fill = K
done = False
while i > 0 and heights[i] >= heights[i - 1]:
if heights[i] > heights[i - 1]:
fill = i - 1
i -= 1
# print fill
if fill == K:
i = K
while i < len(heights) - 1 and heights[i] >= heights[i + 1]:
if heights[i] > heights[i + 1]:
fill = i + 1
i += 1
heights[fill] += 1
# print fill
# print heights
return heights |
c7c6bb20607b23eb1a78961056206a4e694d4c3c | ThomasP1234/DofE | /Week 13 (DiceGame)/2 Player Dice Game.py | 4,697 | 3.9375 | 4 | # Author: Thomas Preston
import random
import json
authorisedPlayers = ["Tom", "John", "Bob", "Dave"]
def getAuthorisedPlayers():
global player1
player1 = input('Who is player one? ')
global player2
player2 = input('Who is player two? ')
if player1 not in authorisedPlayers or player2 not in authorisedPlayers:
print('Unauthorised to play')
exit()
dicePossibility = [1, 2, 3, 4, 5, 6]
p1Score = 0
p2Score = 0
rounds = 5
getAuthorisedPlayers()
print('The rules are:')
print('• The points rolled on each player’s dice are added to their score.')
print('• If the total is an even number, an additional 10 points are added to their score.')
print('• If the total is an odd number, 5 points are subtracted from their score.')
print('• If they roll a double, they get to roll one extra die and get the number of points rolled added to their score.')
print('• The score of a player cannot go below 0 at any point.')
print('• The person with the highest score at the end of the 5 rounds wins.')
print('• If both players have the same score at the end of the 5 rounds, they each roll 1 die and whoever gets the highest score wins (this repeats until someone wins).')
while rounds > 0:
rounds = rounds - 1
input('Press enter to roll the 2 dice each')
player1dice1 = random.choice(dicePossibility)
player1dice2 = random.choice(dicePossibility)
player2dice1 = random.choice(dicePossibility)
player2dice2 = random.choice(dicePossibility)
# print(player1dice1, player1dice2, player2dice1, player2dice2)
_player1Score = player1dice1 + player1dice2
_player2Score = player2dice1 + player2dice2
p1Score = p1Score + _player1Score
p2Score = p2Score + _player2Score
print('{0} rolled a {1} and a {2}'.format(player1, player1dice1, player1dice2))
print('{0} rolled a {1} and a {2}'.format(player2, player2dice1, player2dice2))
if player1dice1 == player1dice2:
print('{0} has rolled a double, you get a bonus die'.format(player1))
input('Press enter to roll')
player1dice3 = random.choice(dicePossibility)
print('You rolled a {0}, its been added straight to your score'.format(player1dice3))
p1Score = p1Score + player1dice3
if player2dice1 == player2dice2:
print('{0} has rolled a double, you get a bonus die'.format(player2))
input('Press enter to roll')
player2dice3 = random.choice(dicePossibility)
print('You rolled a {0}, its been added straight to your score'.format(player2dice3))
p2Score = p2Score + player2dice3
oddOrEven = _player1Score % 2
if oddOrEven == 1:
# odd
p1Score = p1Score - 5
else:
# even
p1Score = p1Score + 10
if p1Score < 0:
p1Score = 0
oddOrEven = _player2Score % 2
if oddOrEven == 1:
# odd
p2Score = p2Score - 5
else:
# even
p2Score = p2Score + 10
if p2Score < 0:
p2Score = 0
print("{2}'s Score: {0}\t\t\t{3}'s Score: {1}".format(p1Score, p2Score, player1, player2))
if p1Score > p2Score:
print('{0} Wins'.format(player1))
elif p2Score > p1Score:
print('{0} Wins'.format(player2))
else:
print('Equal Score - Bonus Round')
print('1 dice, highest wins')
while True:
input('Press enter to roll the 2 dice each')
player1dice1 = random.choice(dicePossibility)
player2dice1 = random.choice(dicePossibility)
print('{0} rolled a {1} and a {2}'.format(player1, player1dice1, player1dice2))
print('{0} rolled a {1} and a {2}'.format(player2, player2dice1, player2dice2))
if player1dice1 > player2dice1:
print('{0} Wins'.format(player1))
break
elif player2dice1 > player1dice1:
print('{0} Wins'.format(player2))
break
else:
print('Equal - redo')
continue
filename = "HighScores.json"
def add_score(playerName, score):
newScore = {"name": playerName, "score": score}
HighScores.append(newScore)
fi = open(filename, "r")
High = fi.read()
HighScores = json.loads(High)
add_score(player1, p1Score)
add_score(player2, p2Score)
# print(json.dumps(highscores, indent=4))
sorted_highscores = sorted(HighScores, key=lambda x: x["score"], reverse=True)
# print(json.dumps(sorted_highscores, indent=4))
highscoretable = sorted_highscores[:5]
print('')
print('Highscores:')
for entry in highscoretable:
print("{0} = {1}".format(entry["name"], entry["score"]))
# print(json.dumps(highscoretable, indent=4))
# print(highscoretable)
with open(filename, 'w') as outfile:
json.dump(highscoretable, outfile) |
9a7fec9f67ae2b745dc2d86dc7f1c9c86a6928ec | hanjiwon1/pythonDjango | /d02/ex02/beverages.py | 1,177 | 4 | 4 | #!/usr/bin/env python3
# coding: utf-8
class HotBeverage:
def __init__(self, price = 0.30, name = "hot beverage"):
self.price = price
self.name = name
def description(self):
return "Just some hot water in a cup."
def __str__(self):
return f"name : {self.name}\nprice : {self.price:.2f}\ndescription : {self.description()}"
class Coffee(HotBeverage):
def __init__(self):
self.name = "coffee"
self.price = 0.40
def description(self):
return "A coffee, to stay awake."
class Tea(HotBeverage):
def __init__(self):
self.name = "tea"
self.price = 0.30
def description(self):
return "Just some hot water in a cup."
class Chocolate(HotBeverage):
def __init__(self):
self.name = "chocolate"
self.price = 0.50
def description(self):
return "Chocolate, sweet chocolate..."
class Cappuccino(HotBeverage):
def __init__(self):
self.name = "cappuccino"
self.price = 0.45
def description(self):
return "Un po’ di Italia nella sua tazza!"
def beverages():
hb = HotBeverage()
print(hb)
co = Coffee()
print(co)
te = Tea()
print(te)
ch = Chocolate()
print(ch)
ca = Cappuccino()
print(ca)
if __name__ == '__main__':
beverages() |
f71cc3f4f48474db3808b01fd457409f02c4e874 | Jacquesvdberg92/SoloLearn-Python-3-Tutorial | /04. Exeptions & Files/01. Execptions/Exceptions/Exceptions.py | 949 | 4.375 | 4 | # Exceptions
# You have already seen exceptions in previous code.
# They occur when something goes wrong, due to incorrect code or input.
# When an exception occurs, the program immediately stops.
# The following code produces the ZeroDivisionError exception by trying to divide 7 by 0.
num1 = 7
num2 = 0
print(num1/num2)
#ZeroDivisionError: division by zero
# Different exceptions are raised for different reasons.
# Common exceptions:
# ImportError: an import fails;
# IndexError: a list is indexed with an out-of-range number;
# NameError: an unknown variable is used;
# SyntaxError: the code can't be parsed properly;
# TypeError: a function is called on a value of an inappropriate type;
# ValueError: a function is called on a value of the correct type, but with an inappropriate value.
# Python has several other built-in exceptions, such as ZeroDivisionError and OSError.
# Third-party libraries also often define their own exceptions.
|
b5b4b09ec0510470ba447b1e2cd4ec172a5f9bf3 | GongFuXiong/leetcode | /old/t20191017_intersection/intersection.py | 1,301 | 4 | 4 | #!/usr/bin/env python
# encoding: utf-8
'''
@author: KM
@license: (C) Copyright 2013-2017, Node Supply Chain Manager Corporation Limited.
@contact: yangkm601@gmail.com
@software: garner
@time: 2019/10/17
@url:https://leetcode-cn.com/problems/intersection-of-two-arrays/
@desc:
349. 两个数组的交集
给定两个数组,编写一个函数来计算它们的交集。
示例 1:
输入: nums1 = [1,2,2,1], nums2 = [2,2]
输出: [2]
示例 2:
输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [9,4]
说明:
输出结果中的每个元素一定是唯一的。
我们可以不考虑输出结果的顺序。
'''
import math
class Solution:
def intersection(self, nums1, nums2):
nums1 = set(nums1)
nums2 = set(nums2)
new_nums = []
for num1 in nums1:
if num1 in nums2:
new_nums.append(num1)
return new_nums
if __name__ == "__main__":
solution = Solution()
print("--------1-------")
nums1 = [1,2,2,1]
nums2 = [2,2]
res=solution.intersection(nums1,nums2)
print("res:{0}".format(res))
print("--------2-------")
nums1 = [4,9,5]
nums2 = [9,4,9,8,4]
res=solution.intersection(nums1,nums2)
print("res:{0}".format(res))
|
b383ea732e760828c027104f515a2ebdc9b2af94 | sasazlat/UdacitySolution-ITSDC | /data_structure/other_data_structures.py | 5,563 | 4.25 | 4 |
# coding: utf-8
# # Other Data Structures [optional]
#
# The purpose of this notebook is to show you some of the many other data
# structures you can use without going into too much detail. You can learn
# more by reading [documentation from Python's collections
# library](https://docs.python.org/3.3/library/collections.html).
# ## 1. Tuples
#
# The only standard library data structure that we haven't discussed. The
# tuple is an immutable (unchangeable) sequence of Python objects.
#
# The tuple is very similar to a list. You can read more about it in the
# [Python tuple
# documentation](https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences)
# In[ ]:
# tuples are created with (parentheses)
my_tuple = (1,2,3)
print(my_tuple)
print(type(my_tuple))
# In[ ]:
# elements can be accessed just like they are with lists.
print(my_tuple[0])
print(my_tuple[1])
print(my_tuple[2])
# In[ ]:
# there are some things you can't do with tuples
# due to them being immutable.
my_tuple[1] = 4
# In[ ]:
# but there are also some things you CAN do with tuples
# that you can't do with lists...
t1 = ('a','b','c')
t2 = (1, 2, 3)
set_of_tuples = set()
set_of_tuples.add(t1)
set_of_tuples.add(t2)
print(set_of_tuples)
# In[ ]:
L1 = ['a','b','c']
L2 = [1, 2, 3]
set_of_lists = set()
set_of_lists.add(L1)
set_of_lists.add(L2)
print(set_of_lists)
# ## 2. Namedtuple
#
# Very similar to a tuple except the fields can be named as well! I use
# namedtuples when I want to use `object.property` notation but don't want to
# define a full class.
# In[ ]:
# named tuple's need to be imported from the collections library
from collections import namedtuple
# here we define Point as a new type of thing.
# It has properties x and y.
Point = namedtuple("Point", ["x", "y"])
# here we actually instantiate a point
p1 = Point(5, -3)
print(p1)
# In[ ]:
# there are two ways to access the fields in a point...
# ... by position
print(p1[0])
print(p1[1])
# In[ ]:
# ... or by name
print(p1.x)
print(p1.y)
# ## 3. Counter
# Often we want to count how many times something occurs. The code below
# demonstrates how to use a `Counter` to count the number of occurrences of
# various characters in a string.
# In[ ]:
from collections import Counter
string = "the quick brown fox jumped over the lazy dog"
character_counter = Counter()
for character in string:
character_counter[character] += 1
character_counter.most_common()
# It looks like this string had 8 spaces, 4 e's, 4 o's, etc...
# In[ ]:
# something that's nice about counters is that they don't throw
# an error if you try to access a key that isn't there. Instead
# they return 0.
# how many capital A's are in the string above?
print(character_counter["A"])
# In[ ]:
# but how many lowercase a's?
print(character_counter["a"])
# ## 4. defaultdict
#
# A default dict is best explained by example. Let's go back to the "three
# boxes of tickets" example from earlier.
# In[ ]:
TICKET_BOXES = {
"low" : [],
"medium" : [],
"high" : []
}
unfiled_tickets = [{
"priority" : "high",
"description" : "slammed on brakes"
},
{
"priority" : "low",
"description" : "windshield chipped"
},
{
"priority" : "low",
"description" : "failed to use turn signal"
}
,
{
"priority" : "medium",
"description" : "did not come to complete stop at stop sign"
}]
def file_ticket(ticket):
priority = ticket['priority']
TICKET_BOXES[priority].append(ticket)
for ticket in unfiled_tickets:
file_ticket(ticket)
print(TICKET_BOXES)
# In[ ]:
# so far so good! But what if we try to file a ticket
# with a priority "highest" (as we saw in Jira)?
new_ticket = {
"priority" : "highest",
"description": "vehicle crashed!"
}
file_ticket(new_ticket)
# In[ ]:
# as expected, we get a key error... one way to fix this
# is as follows
def file_ticket_fixed(ticket):
priority = ticket['priority']
# new code
if priority not in TICKET_BOXES:
TICKET_BOXES[priority] = []
TICKET_BOXES[priority].append(ticket)
file_ticket_fixed(new_ticket)
print(TICKET_BOXES)
# In[ ]:
# OR we can use a "defaultdict"
from collections import defaultdict
TICKET_BOXES = defaultdict(list) # notice the argument of list...
def file_ticket(ticket):
priority = ticket['priority']
TICKET_BOXES[priority].append(ticket)
for ticket in unfiled_tickets:
file_ticket(ticket)
file_ticket(new_ticket)
print(TICKET_BOXES)
# When you try to access a key that doesn't exist, defaultdict adds that key to
# the dictionary and associates a **default** value with it (in this case a
# list).
#
# If you want to learn more you can read the [documentation on
# defaultdict](https://docs.python.org/3.3/library/collections.html#collections.defaultdict)
# ## 5. Other data structures from `collections`
# In[ ]:
from collections import deque, OrderedDict
# In[ ]:
d = deque([4,5,6])
print(d)
# In[ ]:
d.append(7)
print(d)
# In[ ]:
d.appendleft(3)
print(d)
# In[ ]:
last = d.pop()
print("last element was", last)
print("now d is", d)
# In[ ]:
first = d.popleft()
print("first element was", first)
print("now d is", d)
# In[ ]:
# # # # #
# In[ ]:
od = OrderedDict()
# In[ ]:
od['a'] = 1
od['b'] = 2
od['c'] = 3
# In[ ]:
# as the name implies, an OrderedDict is a dictionary that
# keeps track of the order in which elements were added.
print(od)
|
50bc6bd3b6b5621e5fa8a068389167d74f6fcbc2 | yashvkirloskar/HExIt | /HexUI.py | 5,784 | 3.875 | 4 | # Code for UI taken from https://github.com/royalbird/Hex-Game
# UI built by Raman Gupta and Rohan Gulati from Netaji Subhas Institute Of Technology
# All game rule implementations built from scratch
# Icon made by Freepik from www.flaticon.com
from __future__ import print_function
# For python3/python2 compatability
try:
import Tkinter as tk
from Tkinter import *
except ModuleNotFoundError:
import tkinter as tk
from tkinter import *
import array
from sys import stdout
from collections import namedtuple
from math import *
from time import sleep
from VectorHex import *
import numpy as np
# Introduction to the game-------------------------------------------------------------------------------------------------------------
"""This is a two player Hex Game. In this game the player has to build a bridge from his side to his other side of
the hex paralellogram, players take turn alternatively,the one who builds first wins. A player can place his stone at
any empty place.As soon as an unbroken chain of stones connects two opposite sides of the board, the game ends
declaring the winner of the game. This game was invented by Piet Hein. It is a win or lose game proved by
John Nash an independent inventor of this game.
"""
GRID_SIZE = 5
IMG_SIZE = 35
XPAD = 40
YPAD = 40
WIN_HEIGHT = 2 * YPAD + GRID_SIZE * IMG_SIZE + 100
WIN_WIDTH = 2 * XPAD + (3 * GRID_SIZE - 1) * IMG_SIZE
class gameGrid():
def __init__(self, frame):
self.frame = frame
self.temp = PhotoImage(file="blue_hex.gif")
self.black = PhotoImage(file="black_hex.gif")
self.white = PhotoImage(file="white_hex.gif")
self.widgets = [[None for i in range(GRID_SIZE)] for j in range(GRID_SIZE)]
self.drawGrid()
self.p1 = np.random.choice(['random'])
print ("P1 is ", self.p1)
if self.p1 == 'ai':
self.p2 = 'random'
else:
self.p2 = np.random.choice(['ai', 'human'])
self.p2 = 'ai'
print ("P2 is " + self.p2)
if (self.p1 == 'ai'):
print ("Click a tile to make the ai play")
self.playInfo = VectorHex(GRID_SIZE, p1=self.p1, p2=self.p2)
self.frame.configure(background="yellow")
def aiMove(self):
print ("Enter aiMove")
turn, move = self.playInfo.ai_move()
self.toggleColor(self.widgets[move // GRID_SIZE][move % GRID_SIZE], turn)
if self.playInfo.winner is not None:
winner = ""
if turn == 1:
winner = " 1 ( White ) "
else:
winner += " 2 ( Black ) "
self.display_winner(winner)
print ("Click on any button to start another game.")
def drawGrid(self):
for yi in range(0, GRID_SIZE):
xi = XPAD + yi * IMG_SIZE
for i in range(0, GRID_SIZE):
l = Label(self.frame, image=self.temp)
l.pack()
l.image = self.temp
l.place(anchor=NW, x=xi, y=YPAD + yi * IMG_SIZE)
l.bind('<Button-1>', lambda e: self.on_click(e))
self.widgets[yi][i] = l
xi += 1.5 * IMG_SIZE
def getCoordinates(self, widget):
row = (widget.winfo_y() - YPAD) / IMG_SIZE
col = (widget.winfo_x() - XPAD - row * IMG_SIZE) / (1.5 * IMG_SIZE)
return int(row), int(col)
def toggleColor(self, widget, turn = None):
if turn is None:
if self.playInfo.turn == 1:
widget.config(image=self.white)
widget.image = self.white
else:
widget.config(image=self.black)
widget.image = self.black
else:
if turn == 1:
widget.config(image=self.white)
widget.image = self.white
else:
widget.config(image=self.black)
widget.image = self.black
def display_winner(self, winner, turn=None):
winner_window = Tk()
winner_window.wm_title("Winner")
frame = Frame(winner_window, width=300, height=40)
frame.pack()
label = Label(frame,text = "Winner is Player : " + winner )
label.pack()
label.place(anchor=tk.NW, x = 20, y = 20)
def on_click(self, event):
if self.playInfo.winner is not None:
self.restart()
if self.playInfo.turn == 1 and (self.p1 == 'ai' or self.p1 == 'random'):
self.aiMove()
return
if self.playInfo.turn == 2 and (self.p2 == 'ai' or self.p2 == 'random'):
self.aiMove()
return
if event.widget.image != self.temp:
return
self.toggleColor(event.widget)
coord = self.getCoordinates(event.widget)
self.playInfo.player_move(coord)
if self.playInfo.winner is not None:
winner = ""
if self.playInfo.turn == 1:
winner = " 1 ( White ) "
else:
winner += " 2 ( Black ) "
self.display_winner(winner)
print ("Click on any button to start another game.")
def restart(self):
self.drawGrid()
p1 = np.random.choice(['ai', 'human'])
self.playInfo = VectorHex(GRID_SIZE, p1=p1, p2='human' if p1 == 'ai' else 'ai')
class gameWindow:
def __init__(self, window):
self.frame = Frame(window, width=WIN_WIDTH, height=WIN_HEIGHT)
self.frame.pack()
self.gameGrid = gameGrid(self.frame)
def main():
print ("Rules:")
print ("White plays first")
print ("Black is trying to get from top row to bottom.")
print ("White is trying to get from left to right.")
window = Tk()
window.wm_title("Hex Game")
gameWindow(window)
window.mainloop()
main() |
c9c9e7805e7b2d99003e0c82655e2bd05d024826 | icterguru/DrLutchClass | /cs150/Projects/matrixtrans.py | 1,045 | 3.515625 | 4 | import sys
from scanner import *
def createMatrix(size):
if size == 0:
return []
else:
return [0] + createMatrix(size - 1)
def printGrid(gridlist):
for row in gridlist:
print (str(row)+"\n")
def nrows(g):
return len(g)
def ncols(g):
return len(g[0])
def printMatrix(g):
for i in range(0,nrows,1):
for j in range(0,ncols,1):
print("The original matrix is:",g[i][j])
print('')
print('')
def printMatrixTranspose(g):
for j in range(0,ncols,1):
for i in range(0,nrows,1):
print("The transposed matrix is:",g[i][j])
print('')
print('')
def readInput(filename,grid):
s = Scanner(filename)
r = s.readtoken()
while r != "":
r = int(r)
c = s.readint()
v = s.readint()
grid[r][c]=v
r = s.readtoken()
s.close()
def main():
grid = createMatrix(5)
for i in range(4):
grid[i] = createMatrix(5)
readInput(sys.argv[1],grid)
printMatrixTranspose(g)
main()
|
99dbdd493f874f9e776e6c51e90ad60fd139bf13 | niki4/leetcode_py3 | /medium/1604_alert_using_same_key-card_three_or_more_times_in_a_one_hour_period.py | 3,042 | 4.0625 | 4 | """
LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card,
the security system saves the worker's name and the time when it was used. The system emits an alert if
any worker uses the key-card three or more times in a one-hour period.
You are given a list of strings keyName and keyTime where [keyName[i], keyTime[i]] corresponds to a person's
name and the time when their key-card was used in a single day.
Access times are given in the 24-hour time format "HH:MM", such as "23:51" and "09:49".
Return a list of unique worker names who received an alert for frequent keycard use. Sort the names in
ascending order alphabetically.
Notice that "10:00" - "11:00" is considered to be within a one-hour period, while "22:51" - "23:52" is not
considered to be within a one-hour period.
Example:
Input:
keyName = ["daniel","daniel","daniel","luis","luis","luis","luis"],
keyTime = ["10:00","10:40","11:00","09:00","11:00","13:00","15:00"]
Output: ["daniel"]
Explanation: "daniel" used the keycard 3 times in a one-hour period ("10:00","10:40", "11:00").
"""
import collections
from typing import List
class Solution:
"""
Time complexity: O(m*KlogK)
Not sure if I calculated complexity correctly. The overall algorithm is about splitting first unique names
and find related times for each name. m in big O represents that set of unique names.
Then for each name we sort related times in asc order (having K in big O denoting subset of times related
to that particular name, we need KlogK to sort each times subset).
Finally, use sliding window to find adjacent triples which makes an alert (hint: we can easily make
timestamp by eliminating ":" symbol, then converting result value to int).
"""
def parse_time(self, time_: str) -> int:
""" Makes int representation of time, e.g. 12:30 -> 1230 """
return int(time_[:2] + time_[3:])
def alertNames(self, keyName: List[str], keyTime: List[str]) -> List[str]:
alerted = []
visits = collections.defaultdict(list)
for i in range(len(keyName)):
visits[keyName[i]].append(keyTime[i])
for name in visits:
visits[name].sort()
for i in range(2, len(visits[name])):
p2_ts, p1_ts, curr_ts = [self.parse_time(t) for t in visits[name][i-2:i+1]]
if curr_ts-100 <= p2_ts <= p1_ts <= curr_ts:
alerted.append(name)
break
return sorted(alerted)
if __name__ == '__main__':
solutions = [Solution()]
tc = (
(["daniel","daniel","daniel","luis","luis","luis","luis"], ["10:00","10:40","11:00","09:00","11:00","13:00","15:00"], ["daniel"]),
(["alice","alice","alice","bob","bob","bob","bob"], ["12:01","12:00","18:00","21:00","21:20","21:30","23:00"], ["bob"]),
)
for sol in solutions:
for key_names, key_times, exp_result in tc:
assert sol.alertNames(key_names, key_times) == exp_result
|
79467e8b6c9ddce36e2da3ee6819f3670707518e | poojaps22/Python | /day1.py | 9,165 | 4.1875 | 4 | '''
print('Hello Python')
print("Welcome!!!")
#Single Line comment
print('''A
B
C
D
E''')
'''
Multi Line
Comment
'''
#integer
x=10
y=5
z=x+y
print(z)
#float
x=10.5
y=5.3
z=x+y
print(z)
#Octal
z=0o123
print(z)
#Hexa Decimal
x=0x123AB
print(x)
x=12.4
y=2.7
print(x+y)
print(x-y)
print(x*y)
print(x/y)
#floor division
print(x//y)
#power
print(x**y)
#mod
print(x%y)
a=12
b=8
print('Sum is..',(a+b))
a=12
b=9
c=a>b
print(c)
d=False
print(d)
a='Hello Dear'
b="Welcome!!!!"
c='''This is
multi line string'''
print(a,b,c)
x='Hello'
#immutable
x+'python'
print(x)
a='Hello \n Hi \t Bye'
print(a)
a='This is python code'
print(a[0]) #T
print(a[0:5]) #0-4
print(a[3:]) #3 index onwards
#reverse string
print(a[::-1])
#multi time
print(a*3)
print(len(a))
print(max(a)) #y
print(min(a)) #space
print(a.count('code'))
a='this is My coding Python'
print(a.capitalize())
print(a.title())
print(a.upper())
print(a.lower())
print(a.swapcase())
a='hello'
print(a.islower())
print(a.isupper())
w='a1234'
print(w.isalnum())
r='with'
print(r.isalpha())
d='123'
print(d.isnumeric())
print(a.center(40,'*'))
print(a.find('e')) #1
p='*'
s=["w","t","p","s"]
print(p.join(s))
d='this is is my code'
print(d.split())
s='this \t python \t java'
#tab size change to 20 char
print(s.expandtabs(20))
print(s.startswith('t')) #true
print(s.endswith('t')) #false
a,b,c,d=32,'abc',True,90.3
print(a)
print(b)
print(c)
print(d)
print(type(a))
print(type(b))
print(type(c))
print(type(d))
a='123'
b='54'
print(a+b)
print(int(a)+int(b))
x=89
y=9
print(x+y)
print(str(x)+str(y))
x=12
y=5
z=x+y
print('sum..',z)
del z
#print('sum..',z)
x=[32,54.8,'abc',True,91,False]
print(x)
print(x[2])
print(x[1:4]) #1-3
#no of element
print(len(x))
#update
x[0]=90000
print(x)
#delete
del x[1]
print(x)
x=[[32,54,54],['a','b','c'],[32.54,32,54]]
print(x)
x=[54,12,65,89,90,32]
print(max(x))
print(min(x))
print(len(x))
x=['a','b','p','d','c','m']
#append at end
x.append('test')
print(x)
#insert
x.insert(3, 'xyz')
print(x)
s=['as','ps','as','kr','rr']
#count the elements
print(s.count('as'))
r=['x','y','z']
print(s.extend(r))
print(s)
#1
print(s.index('ps'))
#get last element and remove
print(s.pop())
print(s)
#reverse
s.sort()
s.reverse()
print(s)
s=[90,43,6,1,49,9]
t=sorted(s)
#still same
print(s)
#new list sorted
print(t)
t=sorted(s,reverse=True)
print(s)
print(t)
empdata={'empno':101,
'name':'Ravi',
'salary':90000}
print(empdata)
print(empdata['name'])#Ravi
empdata['salary']=130000
print(empdata)
del empdata['name']
print(empdata)
empdata1={'empno':101,
'name':'Ravi',
'salary':90000,
'name':'Anuj'}
print(empdata1)
s={'empno':101,
'name':'Ravi',
'salary':78000,
'city':'pune'}
print(s.keys())
print(s.values())
print(s.get('grade'))
#N/A in place of None
print(s.get('grade','N/A'))
a={'grade':'a','leaves':40}
#after s...a will be appended
s.update(a)
print(s)
a=s.copy()
print(a)
a=['name','city','age']
d=dict.fromkeys(a)
print(d)
r=dict.fromkeys(a,10)
print(r)
#clear
a.clear()
print(a) #blank
s=(21,54,'abc',43.6,True)
#s[1]=3200
#del s[2]
s={32,54,51,54,90}
print(s)
f={'apple','mango','grapes','apple'}
print(f)
f.add('banana')
print(f)
f.remove('mango')
print(f)
import math
print(abs(-90)) #90
print(math.ceil(89.6)) #90
print(math.floor(89.6)) #89
print(math.pow(5,5))
print(math.sqrt(25)) #5
print(max(54,23,654,76))
print(min(54,23,654,76))
print(math.sin(60))
print(math.cos(60))
print(math.tan(60))
print(math.pi)
n=input('Enter your Name please.....')
print('Thanks.....',n)
x=int(input('Enter number.....'))
y=int(input('Enter number.....'))
print(x+y)
x=float(input('Enter number.....'))
y=float(input('Enter number.....'))
print(x+y)
x=float(input('Enter number.....'))
if x>=0:
print('Positive')
else:
print('Negative')
'''x=int(input('Enter number.....'))
y=int(input('Enter number.....'))
if x>y:
print(x,'is big..')
else:
print(y,'is big..')
'''
'''Input sale of shop...give discount of 15%
(sale>10000) else discount of 10%. Print final price..
Input 20000
Output now bill...17000
'''
x=float(input('Enter Sale of shop.....'))
if x>10000:
dis=x*0.15
else:
dis=x*0.10
f=x-dis
print(f)
'''Input a name and check it is palindrome or not'''
x=input('Enter Name.....')
if x==x[::-1]:
print('Palindrome')
else:
print('Not Palindrome')
x=int(input('Enter number.....'))
s='Valid' if x>10 else 'Invalid'
print(s)
x=int(input('Enter number.....'))
y=int(input('Enter number.....'))
if x>10 and y>10:
print('Ok')
else:
print('Not Ok')
x=int(input('Enter number.....'))
if x%2==0 or x%5==0:
print('Valid')
else:
print('Not Valid')
y=int(input('Enter number.....'))
if not y==10:
print('Ok')
else:
print('Not Ok')
s='this is my code'
d=input('Enter letter..')
if d in s:
print('letter found')
else:
print('letter not found')
'''we have a list of cities....input a city from user
and check it is present or not'''
c=['delhi','chennai','pune']
a=input('City....')
if a in c:
print('Error..')
else:
c.append(a)
print(c)
x=int(input('Enter number'))
if x>0:
print('+ ve')
elif x<0:
print('- ve')
else:
print('zero..')
c=input('Country..')
if c=='india':
x=int(input('Age...'))
if x>=18:
print('Vote')
else:
print('Cannot Vote')
else:
print('Not Indian')
x=int(input('Number...'))
if x>10:
pass #null operation
else:
print('Not Ok')
for i in range(1,11,2):
print(i)
for i in range(10,0,-1):
print(i)
for i in range(1,11):
print(i)
for i in range(11):
print(i)
else:
print('end for')
s='my code in python'
for x in s:
print('letter..',x)
a=['ard','pop','rtt','qww']
for x in a:
print('Value..',x)
i=1
while i<=10:
print(i)
i=i+1
else:
print('End While')
def Hello():
print('Hi')
print('Hello')
print('Ends')
print('First')
Hello()
print('Second')
Hello()
#Value pass
#a & b are formal parameters
def calc(a,b):
print(a+b)
print(a-b)
print(a*b)
print(a/b)
#calc(90,4)
#calc(40,4)
#calc(30,4)
x=int(input('Enter number'))
y=int(input('Enter number'))
#x & y are actual parameters
calc(x,y)
def fact(x):
f=1
while x>=1:
f=f*x
x=x-1
return f
r=int(input('Enter number'))
d=fact(r)
print('Fact...',d)
'''create a fun in which i will pass a list of empno...
it return a dictionary containing all empno
as values with key empno'''
def fun(e):
d={'empno':e}
return d
e=[101,102,103,104]
print(fun(e))
def fun(t):
d={} #blank dictionary
d['empno']=t
return d
a=[101,102,103,104]
s=fun(a)
print(s)
def show(empno,name,city):
print('EmpNo..',empno)
print('Name..',name)
print('City..',city)
show(101,'raj','pune')
show(city='delhi',empno=102,name='amit')
show(name='ravi',city='pune',empno=103)
def details(name='test',age=0,salary=0):
print('Name..',name)
print('Age..',age)
print('Salary..',salary)
details('raj',28,89000)
details()
details('amit',29)
details(salary=39000)
details(salary=41000,age=24)
def showdata(*x):
print('show data')
for m in x:
print('Value..',m)
showdata(10)
showdata(32,43)
showdata(32,43,43)
showdata(12,43,43,54)
showdata('ay',43,'xyx',80)
'''create fun that accept n no of value return sum of them'''
def fun(*n):
s=0
for m in n:
s=s+m
return s
print(fun(10,20,30,40))
#call by reference
def change(d):
d.append(1000)
r=[21,43,65,675,76]
change(r)
print(r)
def hi():
global a
print(a)
a='Hello'
print(a)
a='My Python'
hi()
#lambda function
Hi=lambda x:x+5
print(Hi(90))
add=lambda a,b:a+b
print(add(10,20))
#Generator function
def basicgen():
yield 'a'
yield 'b'
yield 'c'
x=basicgen()
#print(x)
print(next(x))
print(next(x))
print(next(x))
def basicgenone(x):
for a in range(x):
yield a
f=basicgenone(10)
print(next(f))
print(next(f))
print(next(f))
#Comprehensions
x=[12,4,5,7,8,12,14,5,7]
y=[var for var in x if var%2==0]
print(y)
'''
|
f4e1f5331212c155329abbbf0c591d764ce09557 | PMiskew/Year9DesignCS4-PythonPM | /In Class Files/SubStringDemo04.py | 503 | 4.25 | 4 | #This program will show how to effectivly use substring
#Prompt the User for their first name and their last name
#Input
fName = input("What is your first: ")
lName = input("What is your last name: ")
#Process
result = fName[0] + "." + lName
#Create a code name by using letters of their first and last name
lenlName = len(lName) #Generate the length of last name
codeName = fName[0] + fName[1] + fName[2] + "." + lName[2] + lName[4]
#Output
print("Hi "+result)
print("Your code name is: "+codeName) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.