blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
32b885cb28b5d02b0671f08143f2bc9cbd41da71 | ArmandoCarrillo91/Platzi | /Cursos/basic_python/break_continue.py | 520 | 3.65625 | 4 | def run():
# for contador in range(1000):
# if contador % 2 != 0:
# continue
# print(contador)
# for i in range(10000):
# print(i)
# if i == 5668:
# break
# texto = input('Esccribe un Texto: ')
# for letra in texto:
# if letra == 'o':
# break
# print(letra)
for i in range(6):
if i == 5:
print('Figaroooo')
break
print('Galileo')
if __name__ == '__main__':
run() |
0adc5de808e6c03f240ca745e39b417bb84d5b1d | zhagyilig/AdvancePy | /03-深入类和对象/class_method.py | 1,350 | 3.703125 | 4 | # -*- encoding: utf-8 -*-
'''
@Author : ericzhang
@Version : python3.6
@File : class_methid.py
@Time : 2019/11/10 21:59:40
@Desc : 类方法、静态方法、实例方法
@Docs :
'''
class Data:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
# 实例方法
def tomorrow(self):
self.day += 1
# 静态方法
@staticmethod
def data_static_parse(data_str):
year, month, day = data_str.split('-')
return Data(year, month, day)
# 类方法
@classmethod
def data_class_parsr(cls, data_str):
year, month, day = data_str.split('-')
return cls(year, month, day)
def __str__(self):
return '{}/{}/{}'.format(self.year, self.month, self.day)
if __name__ == '__main__':
new_day = Data(2019, 11, 10)
print(new_day)
# 在外面解析合适的格式再传入类中
# 2019-11-10
data_str = '2019-11-10'
year, month, day = data_str.split('-')
print(year, month, day)
new_day = Data(year, month, day)
print(new_day)
# 使用staticmothod完成初始化
new_day = Data.data_static_parse(data_str)
print(new_day)
# 使用classmothod完成初始化
new_day = Data.data_class_parsr(data_str)
print(new_day)
|
6e30b8cc3a87012ef061e574dcc674ca3c150dae | xia0m/LPTHW-Next | /Trees/DFS_pre_order.py | 2,286 | 3.75 | 4 | class Node(object):
def __init__(self, value=None):
self.value = value
self.left = None
self.right = None
def get_value(self):
return self.value
def set_value(self, value):
self.value = value
def set_left_child(self, node):
self.left = node
def set_right_child(self, node):
self.right = node
def get_left_child(self):
return self.left
def get_right_child(self):
return self.right
def has_left_child(self):
return self.left is not None
def has_right_child(self):
return self.right is not None
class Tree():
def __init__(self, value):
self.root = Node(value)
def get_root(self):
return self.root
tree = Tree("F")
tree.get_root().set_left_child(Node("B"))
tree.get_root().set_right_child(Node("G"))
tree.get_root().get_left_child().set_left_child(Node("A"))
tree.get_root().get_left_child().set_right_child(Node("D"))
tree.get_root().get_left_child().get_right_child().set_left_child(Node("C"))
tree.get_root().get_left_child().get_right_child().set_right_child(Node("E"))
tree.get_root().get_right_child().set_right_child(Node("I"))
tree.get_root().get_right_child().get_right_child().set_left_child(Node("H"))
# def post_order(tree):
# visit_order = list()
# if tree is None:
# return []
# root = tree.get_root()
# if root.has_left_child():
# post_order_traverse(root.get_left_child(), visit_order)
# if root.has_right_child():
# post_order_traverse(root.get_right_child(), visit_order)
# visit_order.append(root.get_value())
# return visit_order
# def post_order_traverse(node, visit_order):
# if node.has_left_child():
# post_order_traverse(node.get_left_child(), visit_order)
# if node.has_right_child():
# post_order_traverse(node.get_right_child(), visit_order)
# visit_order.append(node.get_value())
# return
def pre_order(tree):
visit_order = list()
root = tree.get_root()
def traverse(node):
if node:
visit_order.append(node.get_value())
traverse(node.get_left_child())
traverse(node.get_right_child())
traverse(root)
return visit_order
print(pre_order(tree))
|
edb6c962043125d6390f063973e2d73463508436 | andyc1997/Data-Structures-and-Algorithms | /Advanced-Algorithms-and-Complexity/Week1/stock_charts.py | 6,745 | 4.34375 | 4 | # python3
from queue import Queue
# Task. You’re in the middle of writing your newspaper’s end-of-year economics summary, and you’ve decided
# that you want to show a number of charts to demonstrate how different stocks have performed over the
# course of the last year. You’ve already decided that you want to show the price of n different stocks,
# all at the same k points of the year.
# A simple chart of one stock’s price would draw lines between the points (0, price[0]), (1, price[1]), . . . , (k−
# 1, price[k - 1]), where price[i] is the price of the stock at the i-th point in time.
# Input Format. The first line of the input contains two integers n and k — the number of stocks and the
# number of points in the year which are common for all of them. Each of the next n lines contains k
# integers. The i-th of those n lines contains the prices of the i-th stock at the corresponding k points
# in the year.
# Output Format. Output a single integer — the minimum number of overlaid charts to visualize all the
# stock price data you have.
class DirectedGraph: # a directed graph object, use adjacency matrix to store the relation
def __init__(self, stock_data):
self.data = stock_data
self.n = len(stock_data) # n <= 100 in this problem, using adjacency matrix costs little memory!
self.adj_list = [[0]*self.n for _ in range(self.n)]
def compare(self, i, j): # a function to compare two stocks, i and j. If all elements of stock i are strictly smaller than those of stock j, return True
stock_1, stock_2 = self.data[i], self.data[j]
for (p_1, p_2) in zip(stock_1, stock_2):
if p_1 >= p_2:
return False
return True
def build_graph(self): # a function to fill the adjacency matrix
for i in range(self.n):
for j in range(self.n):
if i != j:
if self.compare(i, j):
self.adj_list[i][j] = 1
class Edge: # an edge object, see airline.py
def __init__(self, u, v, capacity):
self.u = u
self.v = v
self.capacity = capacity
self.flow = 0
class FlowGraph: # a network object, see airline.py
def __init__(self, n):
self.edges = []
self.graph = [[] for _ in range(n)]
def add_edge(self, from_, to, capacity):
forward_edge = Edge(from_, to, capacity)
backward_edge = Edge(to, from_, 0)
self.graph[from_].append(len(self.edges))
self.edges.append(forward_edge)
self.graph[to].append(len(self.edges))
self.edges.append(backward_edge)
def size(self):
return len(self.graph)
def get_ids(self, from_):
return self.graph[from_]
def get_edge(self, id):
return self.edges[id]
def add_flow(self, id, flow):
self.edges[id].flow += flow
self.edges[id ^ 1].flow -= flow
def update_residual_graph(graph, X, edges, prev, from_, to):
while to != from_:
graph.add_flow(edges[to], X)
to = prev[to]
return graph
def reconstruct_path(graph, from_, to, prev, edges): # see airline.py
result = []
X = 10000 + 1
while to != from_:
result.append(to)
X = min(X, graph.get_edge(edges[to]).capacity - graph.get_edge(
edges[to]).flow)
to = prev[to]
return [from_] + [u for u in reversed(result)], X, edges, prev
def find_a_path(graph, from_, to): # see airline.py
dist = [False] * graph.size()
dist[from_] = True
prev = [None] * graph.size()
edges = [None] * graph.size()
q = Queue()
q.put(from_)
while not q.empty():
u = q.get()
for id in graph.get_ids(u):
to_edge_v = graph.get_edge(id)
v = to_edge_v.v
flow = to_edge_v.flow
capacity = to_edge_v.capacity
if (dist[v] == False) and (
flow < capacity):
q.put(v)
dist[v] = True
prev[v] = u
edges[v] = id
if dist[to] == True:
return reconstruct_path(graph, from_, to, prev, edges)
else:
return [], 0, [], []
def max_flow(graph, from_, to): # Standard implementation of Edmonds-Karp algorithm, see airline.py
flow = 0
while True:
path, X, edges, prev = find_a_path(graph, from_, to)
if len(path) == 0:
return flow
flow += X
graph = update_residual_graph(graph, X, edges, prev, from_, to)
return flow
class StockCharts:
def read_data(self): # read input
n, k = map(int, input().split())
stock_data = [list(map(int, input().split())) for i in range(n)]
return stock_data
def write_response(self, result): # write output
print(result)
def min_charts(self, stock_data):
# Idea: If stock[i] > stock[j] for all elements, then these two stocks can be put together in the same chart
# Let there be a bipartite graph of two set of vertices of size n.
# We can draw a line to connect a pair of vertices only if stock[i] in left hand side > stock[j] in right hand side
# Simple cases:
# If stock[i] > stock[j] and stock[j] > stock[k] (which automatically implies stock[i] > stock[k] , then there are three matches and all of them can be put into a single chart
# If stock[i] > stock[j] and stock[k] > stock[j] but stock[k] !> stock[i], then there are two matches in the bipartite graph
# So, n - number of matches = number of chart needed
n = len(stock_data) # n = number of stocks in total
dag = DirectedGraph(stock_data) # Initialize the directed graph
dag.build_graph() # Build adjacency matrix
network = FlowGraph(2*(n + 1)) # Initialize the network
source, sink, capacity = 0, 2*n + 1, 1 # Let source has index 0, sink has index 2*n + 1, capacity is 1 for each edge
for i in range(1, n + 1):
network.add_edge(source, i, 1) # add edges from source to stock[i]
for j in range(n + 1, 2*n + 1):
if dag.adj_list[i - 1][j - (n + 1)] == 1: # if stock[i] > stock[j] at all time point, add edges from stock[i] to stock[j]
network.add_edge(i, j, 1)
for j in range(n + 1, 2*(n + 1)): # add edges from stock[j] to sink
network.add_edge(j, sink, 1)
return n - max_flow(network, source, sink) # the maxflow is the maximum number of stocks
def solve(self):
stock_data = self.read_data()
result = self.min_charts(stock_data)
self.write_response(result)
if __name__ == '__main__':
stock_charts = StockCharts()
stock_charts.solve()
|
6c8514cd8de14acd6324f6d692915aeff8060de4 | yyxt11/Leetcodes | /树结构/98.验证二叉树搜索树.py | 898 | 3.90625 | 4 | #确保左边子节点恒小于当前节点和父节点的值, 右边子节点恒大于当前节点和父节点的值
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
def search(root:TreeNode,lowbonde = float('-inf'),highbonde = float('inf')):
if root is None:
return True
else:
if root.val <= lowbonde or root.val >= highbonde:
return False
#recall
elif not search(root.left,lowbonde,root.val):
return False
elif not search(root.right,root.val,highbonde):
return False
return True
return search(root)
|
9f9806894d0c369a462ce21f7c540216d2e4cfa4 | tnfranco/courses | /Java/Login.py | 253 | 4.09375 | 4 | usuario = input("Digite o nome do seu usuario: ")
senha = input("Digite sua senha: ")
while senha == usuario:
print("Senha nao pode ser igual ao usuario")
usuario = input("Digite o nome do seu usuario: ")
senha = input("Digite sua senha: ")
|
53879e9fe3a6705e8aba7ee98ec52443cebb2950 | pandas-dev/pandas | /pandas/tests/arithmetic/common.py | 4,362 | 3.609375 | 4 | """
Assertion helpers for arithmetic tests.
"""
import numpy as np
import pytest
from pandas import (
DataFrame,
Index,
Series,
array,
)
import pandas._testing as tm
from pandas.core.arrays import (
BooleanArray,
NumpyExtensionArray,
)
def assert_cannot_add(left, right, msg="cannot add"):
"""
Helper to assert that left and right cannot be added.
Parameters
----------
left : object
right : object
msg : str, default "cannot add"
"""
with pytest.raises(TypeError, match=msg):
left + right
with pytest.raises(TypeError, match=msg):
right + left
def assert_invalid_addsub_type(left, right, msg=None):
"""
Helper to assert that left and right can be neither added nor subtracted.
Parameters
----------
left : object
right : object
msg : str or None, default None
"""
with pytest.raises(TypeError, match=msg):
left + right
with pytest.raises(TypeError, match=msg):
right + left
with pytest.raises(TypeError, match=msg):
left - right
with pytest.raises(TypeError, match=msg):
right - left
def get_upcast_box(left, right, is_cmp: bool = False):
"""
Get the box to use for 'expected' in an arithmetic or comparison operation.
Parameters
left : Any
right : Any
is_cmp : bool, default False
Whether the operation is a comparison method.
"""
if isinstance(left, DataFrame) or isinstance(right, DataFrame):
return DataFrame
if isinstance(left, Series) or isinstance(right, Series):
if is_cmp and isinstance(left, Index):
# Index does not defer for comparisons
return np.array
return Series
if isinstance(left, Index) or isinstance(right, Index):
if is_cmp:
return np.array
return Index
return tm.to_array
def assert_invalid_comparison(left, right, box):
"""
Assert that comparison operations with mismatched types behave correctly.
Parameters
----------
left : np.ndarray, ExtensionArray, Index, or Series
right : object
box : {pd.DataFrame, pd.Series, pd.Index, pd.array, tm.to_array}
"""
# Not for tznaive-tzaware comparison
# Note: not quite the same as how we do this for tm.box_expected
xbox = box if box not in [Index, array] else np.array
def xbox2(x):
# Eventually we'd like this to be tighter, but for now we'll
# just exclude NumpyExtensionArray[bool]
if isinstance(x, NumpyExtensionArray):
return x._ndarray
if isinstance(x, BooleanArray):
# NB: we are assuming no pd.NAs for now
return x.astype(bool)
return x
# rev_box: box to use for reversed comparisons
rev_box = xbox
if isinstance(right, Index) and isinstance(left, Series):
rev_box = np.array
result = xbox2(left == right)
expected = xbox(np.zeros(result.shape, dtype=np.bool_))
tm.assert_equal(result, expected)
result = xbox2(right == left)
tm.assert_equal(result, rev_box(expected))
result = xbox2(left != right)
tm.assert_equal(result, ~expected)
result = xbox2(right != left)
tm.assert_equal(result, rev_box(~expected))
msg = "|".join(
[
"Invalid comparison between",
"Cannot compare type",
"not supported between",
"invalid type promotion",
(
# GH#36706 npdev 1.20.0 2020-09-28
r"The DTypes <class 'numpy.dtype\[datetime64\]'> and "
r"<class 'numpy.dtype\[int64\]'> do not have a common DType. "
"For example they cannot be stored in a single array unless the "
"dtype is `object`."
),
]
)
with pytest.raises(TypeError, match=msg):
left < right
with pytest.raises(TypeError, match=msg):
left <= right
with pytest.raises(TypeError, match=msg):
left > right
with pytest.raises(TypeError, match=msg):
left >= right
with pytest.raises(TypeError, match=msg):
right < left
with pytest.raises(TypeError, match=msg):
right <= left
with pytest.raises(TypeError, match=msg):
right > left
with pytest.raises(TypeError, match=msg):
right >= left
|
394b17d841707da8dc2b13c48581e250dd69390b | NagahShinawy/problem-solving | /pynative/3_ifelse_forloop/ex_7.py | 316 | 3.9375 | 4 | """
Exercise 7: Print the following pattern using for loop
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1
"""
for i in range(5, 0, -1):
for j in range(i, 0, -1):
print(j, end=" ")
print()
print("#" * 30)
n = 5
k = 5
for i in range(0, n + 1):
for j in range(k - i, 0, -1):
print(j, end=" ")
print()
|
9dcf1d1e3d13782fd1a5788fafcd64b3b6cfeba6 | codeepicure/python-bootcamp | /09 - Secret Auction/main.py | 643 | 4.03125 | 4 | from replit import clear
from art import logo
#HINT: You can call clear() to clear the output in the console.
print(logo)
user_bids = {}
no_more_users = False
while not no_more_users:
name = input("What is your name? ")
bid = int(input("What is your bid? "))
user_bids[name] = bid
has_more_users = input("Are there other users? 'yes/no' ")
no_more_users = True if has_more_users != 'yes' else False;clear()
winner = ""
win_bid = 0
for user in user_bids:
if(user_bids[user] > win_bid):
win_bid = user_bids[user]
winner = user
print(f"The winner of the auction is {winner} with a winning bid of {win_bid}") |
aed22b4b26a44135f1c665ea3ecae379177aef0c | phlalx/algorithms | /leetcode/274.h-index.python3.py | 416 | 3.765625 | 4 | # TAGS array
# can we do without a sort?
def hindex(citations):
citations.sort(reverse=True)
i = 0
n = len(citations)
while i < n and citations[i] >= i + 1:
i = i + 1
return i
class Solution:
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
if not citations:
return 0
return hindex(citations)
|
5bd177fa807b68a4399669242ff90d17ef0374e0 | Mystified131/DAPSupplementalCode | /Lists2.py | 414 | 4.125 | 4 | #Here I set up the three lists
alst = [1, 5, 6, 8, 7, 6, 3]
blst = ["bear", "cat", "shark"]
clst = [1.2, 3.6, 3.42]
#Here I create a new list
finlst = []
#Here I loop through each list, adding the elements to the new list
for elem in alst:
finlst.append(elem)
for elem2 in blst:
finlst.append(elem2)
for elem3 in clst:
finlst.append(elem3)
#Here I print the contents of the new list
print(finlst) |
fe38966903cc139b6f2f3c7b31eaa55ccc171bf1 | jtannas/intermediate_python | /slots_magic.py | 1,539 | 4.4375 | 4 | """
10. __slots__ Magic
In Python every class can have instance attributes. By default Python
uses a dict to store an object’s instance attributes. This is really
helpful as it allows setting arbitrary new attributes at runtime.
However, for small classes with known attributes it might be a
bottleneck. The dict wastes a lot of RAM. Python can’t just allocate
a static amount of memory at object creation to store all the
attributes. Therefore it sucks a lot of RAM if you create a lot of
objects (I am talking in thousands and millions). Still there is a way
to circumvent this issue. It involves the usage of __slots__ to tell
Python not to use a dict, and only allocate space for a fixed set of
attributes. Here is an example with and without __slots__:
"""
# Without slots
class MyClass1(object):
def __init__(self, name, identifier):
self.name = name
self.identifier = identifier
self.set_up()
def set_up(self):
pass
# With slots
class MyClass2(object):
__slots__ = ['name', 'identifier']
def __init__(self, name, identifier):
self.name = name
self.identifier = identifier
self.set_up()
def set_up(self):
pass
#: In essence, it is telling Python that the class will take up a fixed
#: amount of space and that it can optimize memory around that fixed
#: amount.
#: Some people have reported RAM savings of 40 to 50% using this.
#: Side note from author: You may want to give PyPy a try. It does all
#: these optimizations by default.
|
5787e2b352c4a64b4ced2adaa169b8cd52effb94 | crypdick/btree | /btreenode.py | 5,840 | 3.796875 | 4 | class BTreeNode(object) :
'''represents a node in a B-tree, containing q < p references to child nodes
and a key-pointer pair between each pair of references:
... | child i | key i, ptr i | child i+1 | key i+1, ptr i+1 | ...
In the picture,
child node ref i refers to the root of a tree of nodes whose keys are <= key i
child node ref i+1 refers to the root of a tree of nodes whose keys are > key i and <= key i+1
key i is the value of a data column,
ptr i is an integer or string representing the location of a data record
Note: This Python implementation uses references to nodes instead of pointers to nodes.
In a leaf node each node reference is None.'''
def __init__(self, p) :
self.p = p
self.q = 0
self.childKeyPtrs = list() # contains tuples (child i, (key i, ptr i))
self.rightChild = None
self.parent = None
def setRightChild(self, rightChild):
self.rightChild = rightChild
def getRightChild(self):
return self.rightChild
def setParent(self, node):
self.parent = node
def getParent(self):
return self.parent
def isOverfull(self) :
return (q>=p)
def isLeaf(self) :
return (self.rightChild is None)
def insertDown(self, keyPtr) :
'''Searches for the leaf node to insert a new key-pointer pair into, and does the insertion.
Returns None, or a reference to the new root if one is created.'''
# if this node is a leaf, insert the pair (node ref, (key, pointer))
if self.isLeaf():
if self.q == 0: #if node is empty, just inset key_ptr
self.childKeyPtrs = self.childKeyPtrs.append((None,keyPtr))
self.q += 1
else: #if node has other keys
#loop through keys to find right position
# for i in range(q+1):
#
# if keyPtr[0] > self.childKeyPtrs[i][1][0] and i < q:
# continue
# else:
# self.childKeyPtrs = self.childKeyPtrs.insert(i,(None,keyPtr))
# self.q += 1
if keyPtr[0] < self.childKeyPtrs[0][1][0]:
self.childKeyPtrs = self.childKeyPtrs.insert(0,(None,keyPtr))
if keyPtr[0] < self.childKeyPtrs[1][1][0]:
self.childKeyPtrs = self.childKeyPtrs.insert(i,(None,keyPtr))
# if after insertion this node is overfull:
if self.isOverfull():
# if this node is root (and leaf!), call insertRoot()
if self.getParent() == None:
return self.insertRoot()
# if this node is not root
# insert the rightmost key-pointer pair into this node's parent
# with insertUp(None, key-ptr, rightChild)
# and fix this node's references
else:
right_most_keyPtr = self.childKeyPtrs[-1][1]
return self.insertUp(None,right_most_keyPtr,self.getRightChild)
else:
return None
# if this node has children, insert the key-ptr pair into the correct child and recurse
else:
#loop through all keys to locate correct child
for i in range(q+1):
if keyPtr[0] > self.childKeyPtrs[i][1][0] and i < q:
continue
else:
if i > q:
child = self.getRightChild
child.insertDown(keyPtr)
else:
child = self.childKeyPtrs[i][0]
child.insertDown(keyPtr)
return # None or return value of insertRoot, insertUp, or insertDown
def insertUp(self, leftNode, keyPtr, rightNode) :
'''Inserts a key-pointer pair into a node.
Typically called by an overfull child or sibling.
Returns None, or a reference to the new root if one is created.'''
#This method isn't making any sense to me since it pushes the right-most
#key-ptr pair up to the parent and not the middle key-ptr pair
# insert the leftNode-keyPtr tuple into the list at the correct index
# replace the child in the next list element, or the rightChild, with rightNode
# if this node is overfull
# if this node is not root, insert the rightmost key-pointer pair into this node's parent
# if this node is root, call insertRoot()
return # None or return value of insertRoot, insertUp, or insertDown
def insertRoot(self):
'''Called when this node is root and overfull, creates a new parent/root node and
a sibling node to contain half the entries.
Returns a reference to the new root.'''
# create a new parent/root node and a new sibling node
# set the return value
new_root = BTreeNode(self.p)
new_sibling = BTreeNode(self.p)
# move this node's middle key-pointer pair into the parent
# with insertUp(self, key-ptr, sibling)
# and fix this node's references
middle_keyptr = self.childKeyPtrs[self.p//2][1]
self.insertUp(self,middle_keyptr,new_sibling)
self.childKeyPtrs = self.childKeyPtrs[0]
# give this node's right child to the sibling
# give the right half of this node's child-key-pointer tuples to the sibling
# with calls to insertUp(child, key-ptr, None)
#i
# make the root the parent of this node and its sibling.
new_sibling.setParent(new_root)
self.setParent(new_root)
return # reference to new root
|
84d9a29b4b28a287f5dff164a25b2e28b27d3bd3 | danield309/cs1.1-bank-account | /BankAccount.py | 2,062 | 4.125 | 4 | # bank account class
class BankAccount:
def __init__(self, full_name, account_number, routing_number, balance):
self.full_name = full_name
self.account_number = account_number
self.routing_number = routing_number
self.balance = balance
# deposit method
def deposit(self, amount):
self.balance += amount
print(f"Amount deposited: ${amount}")
# withdraw method
def withdraw(self, amount):
self.balance -= amount
print(f"Amount withdrawn: ${amount}")
if amount > self.balance:
print("Insufficient funds.")
self.balance -= 10
# balance method
def get_balance(self):
print(f"Balance: ${self.balance}")
# add interest method
def add_interest(self):
balance = self.balance
interest = balance * 0.00083
self.balance = self.balance + interest
# print receipt method
def print_receipt(self):
stars = []
for i in str(self.account_number):
stars.append("*")
hide_accountnum = str(self.account_number)
stars[len(stars)-1] = hide_accountnum[len(stars)-1]
stars[len(stars)-2] = hide_accountnum[len(stars)-2]
stars[len(stars)-3] = hide_accountnum[len(stars)-3]
stars[len(stars)-4] = hide_accountnum[len(stars)-4]
acc_stars = ""
acc_stars = acc_stars.join(stars)
print(self.full_name)
print(f"Account No.: {acc_stars}")
print(f"Routing No.: {self.routing_number}")
print(f"Balance: {self.balance}")
# bank account 1
daniel_account = BankAccount("Daniel Duque", 490281789, 1982331, 7000)
daniel_account.deposit(5000)
daniel_account.print_receipt()
# bank account 2
travis_account = BankAccount("Travis Scott", 914253880, 8982331, 5300)
travis_account.get_balance()
travis_account.withdraw(5301)
travis_account.print_receipt()
# bank account 3
aubrey_account = BankAccount("Aubrey Graham", 666666666, 7982331, 100000)
aubrey_account.add_interest()
aubrey_account.print_receipt()
|
8bdc54a4132656ea67d24c419965fab0358879aa | shapovalovdev/AlgorythmsAndDataStructures | /src/LinkedList/linked_list_sum.py | 1,059 | 4.1875 | 4 | from src.LinkedList.linked_list_realization import LinkedList, Node
def sum_equal_lists(List1, List2):
#check if List1 or List2 is Linked list if not return
if type(List1) is not LinkedList or type(List2) is not LinkedList:
raise Exception("Types of parameters are not linked list. ")
return
#check if some the lists are empty
if List1.head is None or List2.head is None:
raise Exception("Lists should not be empty")
return
#check if lists are not equal
if List1.len() != List2.len():
raise Exception("Lists are not equal. Try again")
return
#create new list with sum of every element
sum_list= LinkedList()
node1=List1.head
node2=List2.head
while node1 is not None:
if type(node1.value) is not int or type(node2.value) is not int:
raise Exception("Lists have not integer values")
return
n=Node(node1.value+node2.value)
sum_list.add_in_tail(n)
node1=node1.next
node2=node2.next
return sum_list
|
9068b68e3a098f8ac8685f4f240306bfae738bad | pirate765/bridgelabzbootcamp | /day1/nosuchmethod.py | 201 | 3.75 | 4 | class MyClass:
"This is my custom class"
a = 10
def func(self):
print('Hello', self.a)
obj1 = MyClass()
print(obj1)
print(obj1.func())
print(obj1.func2())
# print(MyClass.a)
# print(obj1.func())
|
562b810ac10c047df807426b78452123ef995336 | eselyavka/python | /leetcode/solution_99.py | 1,965 | 3.765625 | 4 | import unittest
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution(object):
def recoverTree(self, root):
"""
:type root: TreeNode
:rtype: None Do not return anything, modify root in-place instead.
"""
arr = []
curr = root
stack = []
while True:
if curr is not None:
stack.append(curr)
curr = curr.left
elif stack:
node = stack.pop()
arr.append(node.val)
curr = node.right
else:
break
sorted_arr = sorted(arr)
n = len(arr)
swap_from, swap_to = None, None
for i in range(n):
if arr[i] != sorted_arr[i]:
swap_from = sorted_arr[i]
swap_to = arr[i]
q = [root]
while q:
node = q.pop()
if node.val == swap_to:
node.val = swap_from
elif node.val == swap_from:
node.val = swap_to
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
class TestSolution(unittest.TestCase):
def test_recoverTree(self):
root = TreeNode(1)
root.left = TreeNode(3)
root.left.right = TreeNode(2)
solution = Solution()
solution.recoverTree(root)
arr = []
curr = root
stack = []
while True:
if curr is not None:
stack.append(curr)
curr = curr.left
elif stack:
node = stack.pop()
arr.append(node.val)
curr = node.right
else:
break
self.assertListEqual(arr, [1, 2, 3])
if __name__ == '__main__':
unittest.main()
|
d780813480c20b2f1c1dc546bf58b29adbe3ca54 | arcogelderblom/AppliedAI | /Week_5/6.2.py | 16,850 | 4.1875 | 4 | """
Genotype is a list/array of 24 items, with the first 6 being A, the next 6 being B and so on. Each item can be a 1 or
a 0.
The fitness will be calculated by calculating the lift. The higher the fitness the better the individual.
Mutation will happen on 4 spots. Every input for the lift function gets mutated. A random gene gets selected and changed
from 1 to 0 or the other way around.
The formula that we will use for lift is as follows:
lift = (A - B)^2 + (C + D)^2 - (A - 30)^3 - (C - 40)^3
"""
import random
def create_population(amount, listLength, minValue, maxValue):
"""
Create a population
:param amount: amount of individuals in the population
:param listLength: needed for create_individual
:param minValue: needed for create_individual
:param maxValue: needed for create_individual
:return: returns a list of individual, a population
"""
return [create_individual(listLength, minValue, maxValue) for x in range(amount)]
def create_individual(listLength, minValue, maxValue):
"""
Create a individual based on a few constraints
:param listLength: length of the created genotype
:param minValue: minimal value a gene can have
:param maxValue: maximal value a gene can have
:return: returns a list with values representing an individual
"""
return [random.randint(minValue, maxValue) for x in range(listLength)]
def get_abcd(individual):
"""
Individual consists of 4 variables encoded as a binary. This function extracts the variables and returns them as a
base 10 integer
:param individual: list of 0 and 1 representing the individual
:return: returns a list of the variables easy for slicing: [a, b, c, d]
"""
a, b, c, d = [individual[x:x+6] for x in range(0, len(individual), 6)]
a = int("".join(str(number) for number in a), 2)
b = int("".join(str(number) for number in b), 2)
c = int("".join(str(number) for number in c), 2)
d = int("".join(str(number) for number in d), 2)
return [a, b, c, d]
def fitness(individual):
"""
Calculate fitness of an individual based on the formula for lift
lift = (A - B)^2 + (C + D)^2 - (A - 30)^3 - (C - 40)^3
:param individual: list representing an individual
:return: fitness as a number, higher is better
"""
a, b, c, d = get_abcd(individual)
return ((a - b) ** 2) + ((c + d) ** 2) - ((a - 30) ** 3) - ((c - 40) ** 3)
def sort_generation(population):
"""
Get the population and return a sorted one based on how they perform on the fitness function
:param population: population to sort
:return: returns a sorted population
"""
fitnessList = []
for individual in population:
fitnessList.append(fitness(individual))
return [individual for fit, individual in reversed(sorted(zip(fitnessList, population)))]
def create_new_generation(population, keepBestAmount):
"""
Create a new generation by inverting one random gene in the genotype per variable that is represented
:param population: expects an list of the current generation ordered by fitness, the best are first, worst are last
:param keepBestAmount: amount of 'best' that you want to keep, the rest gets mutated
:return: returns the new generation
"""
for i in range(len(population[keepBestAmount:])):
sliced = [population[i+keepBestAmount][x:x+6] for x in range(0, len(population[i+keepBestAmount]), 6)]
tmp = []
for variable in sliced:
index = random.randint(0, len(sliced)-1)
if variable[index] == 0:
variable[index] = 1
else:
variable[index] = 0
tmp += variable
population[i+keepBestAmount] = tmp
return population # individuals are now mutated so just return the new generation
population = create_population(1000, 24, 0, 1)
amountOfGenerations = 100
for generation in range(amountOfGenerations):
population = sort_generation(population)
population = create_new_generation(population, 10)
population = sort_generation(population) # sort generation so we can take the best 10
print("The best individual is: {} with a fitness of: {}".format(population[0], fitness(population[0]))) # index 0 because of the sorted population
"""
After running the algorithm a 100 times the average of the max lift is: 97022.32
There is a difference between the results of about 2000. This is not a lot since the values go almost to 100000. So
this is about 2% Furthermore, it stands out that a and c almost always are 0 while b and d are changing.
The results of 100 times running are as follows:
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0] with a fitness of: 98333
The best individual is: [0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1] with a fitness of: 96650
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1] with a fitness of: 96981
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1] with a fitness of: 95969
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1] with a fitness of: 97221
The best individual is: [0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0] with a fitness of: 96809
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1] with a fitness of: 96965
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0] with a fitness of: 96636
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1] with a fitness of: 97290
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0] with a fitness of: 98200
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0] with a fitness of: 97548
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0] with a fitness of: 97280
The best individual is: [0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1] with a fitness of: 95874
The best individual is: [0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0] with a fitness of: 95900
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0] with a fitness of: 96904
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1] with a fitness of: 97273
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1] with a fitness of: 96537
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0] with a fitness of: 97173
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1] with a fitness of: 98450
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0] with a fitness of: 97469
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1] with a fitness of: 97058
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0] with a fitness of: 97736
The best individual is: [0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0] with a fitness of: 96128
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1] with a fitness of: 97625
The best individual is: [0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1] with a fitness of: 96490
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0] with a fitness of: 97085
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0] with a fitness of: 97760
The best individual is: [0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0] with a fitness of: 96625
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1] with a fitness of: 97506
The best individual is: [0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1] with a fitness of: 97178
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0] with a fitness of: 96945
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0] with a fitness of: 96904
The best individual is: [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1] with a fitness of: 95082
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1] with a fitness of: 95441
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1] with a fitness of: 96650
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1] with a fitness of: 97322
The best individual is: [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1] with a fitness of: 96079
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0] with a fitness of: 97389
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1] with a fitness of: 98690
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0] with a fitness of: 96513
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1] with a fitness of: 95561
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1] with a fitness of: 97653
The best individual is: [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0] with a fitness of: 95148
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1] with a fitness of: 97849
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0] with a fitness of: 96945
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0] with a fitness of: 98200
The best individual is: [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0] with a fitness of: 95624
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1] with a fitness of: 96626
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1] with a fitness of: 98565
The best individual is: [0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1] with a fitness of: 96733
The best individual is: [0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1] with a fitness of: 96274
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0] with a fitness of: 96517
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0] with a fitness of: 96017
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1] with a fitness of: 96850
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0] with a fitness of: 96620
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0] with a fitness of: 97344
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1] with a fitness of: 97849
The best individual is: [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1] with a fitness of: 95338
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1] with a fitness of: 98085
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0] with a fitness of: 97425
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0] with a fitness of: 95165
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0] with a fitness of: 97857
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1] with a fitness of: 97506
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0] with a fitness of: 97161
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0] with a fitness of: 96840
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0] with a fitness of: 97389
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1] with a fitness of: 98325
The best individual is: [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1] with a fitness of: 95591
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1] with a fitness of: 97409
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0] with a fitness of: 97736
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1] with a fitness of: 96941
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1] with a fitness of: 98105
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0] with a fitness of: 98569
The best individual is: [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0] with a fitness of: 95685
The best individual is: [0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1] with a fitness of: 96506
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1] with a fitness of: 96941
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1] with a fitness of: 96850
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0] with a fitness of: 96413
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1] with a fitness of: 97370
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1] with a fitness of: 97857
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0] with a fitness of: 97344
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0] with a fitness of: 98208
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1] with a fitness of: 97025
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0] with a fitness of: 98333
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1] with a fitness of: 98450
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1] with a fitness of: 98218
The best individual is: [0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1] with a fitness of: 96234
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0] with a fitness of: 96204
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1] with a fitness of: 97857
The best individual is: [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1] with a fitness of: 95993
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1] with a fitness of: 97778
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1] with a fitness of: 97370
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0] with a fitness of: 95961
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0] with a fitness of: 97068
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1] with a fitness of: 97613
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1] with a fitness of: 97058
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1] with a fitness of: 96834
The best individual is: [0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0] with a fitness of: 97053
The best individual is: [0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1] with a fitness of: 96650
The best individual is: [0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1] with a fitness of: 95874
"""
|
70aaab72bc3bc85794d4fda30d589184f3368935 | 1769258532/python | /py_core/day5/day1/d19.py | 440 | 3.703125 | 4 | #-*-coding:utf-8 -*-
#!/usr/bin/python3
# @Author:liulang
'''
for in 循环
'''
test_datas = [ 1 , 2, 3, 4 ]
# for i in test_datas: # in 列表,元组
# if i == 3:
# break #完全跳出循环
# print(i)
for i in test_datas: # in 列表,元组
if i == 3:
continue # 终止本次循环,接着执行下一次迭代
print(i)
# i = 0
#
# while i < 4 :
# print(test_datas[i])
# i += 1
|
037f1246d1fbc7ffb57eb13f058dc1d8271abc03 | mh70cz/py | /misc/t_and_t/default_val_dict.py | 1,079 | 3.875 | 4 | """ Using get() to return a default value from a Python dict
keywords: disctionary, default_value, lefpad, padleft, string_format
based on: https://dbader.org/blog/python-dict-get-default-value
"""
name_for_userid = {
382: "Alice",
950: "Bob",
590: "Dilbert"
}
ids_to_greet = [382, 999]
def non_pythonic_get(userid):
""" verbose, dictionary is accessed twice"""
if userid in name_for_userid:
return "Hi %s!" % name_for_userid[userid]
else:
return "Hi there!"
def pythonic_get(userid):
""" standard """
return "Hi %s!" % name_for_userid.get(userid, "there")
for uid in ids_to_greet:
print((str(uid) + " non pythonic, old string format: ").ljust(40)
+ str(non_pythonic_get(uid)))
print("{:<40}".format(str(uid) + " non pythonic, new string format: ")
+ str(non_pythonic_get(uid)))
print((str(uid) + " pythonic, old string format: ").ljust(40)
+ str(pythonic_get(uid)))
print("{:<40}".format(str(uid) + " pythonic, new string format: ")
+ str(pythonic_get(uid)))
|
9cd9d932fa246692c485172aaec6f7d2b7fd07b4 | AlexisPin/TP_CS-DEV | /penduConsole/Pendu.py | 4,794 | 3.625 | 4 |
#Alexis PINCEMIN
#30/11/2020
#Jeu du Pendu version console
#Lien gitbub https://github.com/AlexisPin/TP_CS-DEV
import random
#on ouvre le fichier contenant la liste de tout les mots / le fichier est dans le même répertoire que le code
continuer_partie = True
while continuer_partie:
# varibales utiles
words = []
error = 0
wordList = []
myWordList = []
bodyItems = [' \n -----','|','O', ' /', '|', '\\', '/', '\\']
myBody = ['', '', '', '', '', '', '', '']
# but : on choisi un mot aleatoire et on crée les variables nécessaires
# sorties : word : mot choisi aléatoirement, wordList : liste des lettres de word ,
# myWordList : liste qui contient les lettres trouvés par le joueur utile pour détecter si le joueur à gagné
# letters : lettres déjà utilisé ici première lettre du mot
def wordChoice() :
allWords = open("words.txt", "r")
allWordsSort = sorted(allWords)
allWords.close()
for oneWord in allWordsSort:
words.append(oneWord.rstrip('\n'))
word = random.choice(words)
# on créer une liste avec les letters du mot choisi aléatoirement
for x in word:
wordList.append(x)
# on donne déjà la première letter
letters = [wordList[0]]
# on créer une liste vide de la longueur de word qui sert à afficher le mot au fur et à mesure qu'on trouve les letters
for _ in word:
myWordList.append("")
return word,wordList,myWordList,letters
word,wordList,myWordList,letters = wordChoice()
# but : vérifie si la letter est déjà utilisé,
# entrée : letters : liste des lettres utilisés,
# sorties : alreadyUse : varibales booléenne, letter : lettre choisie , letters : liste des lettres utilisés
def checkAlreadyUse(letters): #vérifie si la letter est déjà utilisé
alreadyUse = False
if letter in letters:
alreadyUse = True
print('lettre déjà proposé')
else:
letters.append(letter) # liste qui nous permet de stocker les letters utilisé
return alreadyUse,letter,letters
# but : afficher le mot en cours de recherche,
# entrée : letters : liste des lettres utilisés,
def wordToFind(letters):
for (index, i) in enumerate(word):
if i in letters:
myWordList[index] = i # on complète au fur et à mesure la liste du joueur
print(i, end=" ")
else:
print("_", end=" ")
# but : gérer le nombre d'erreur du joueur,
# entrée : error : nombre d'erreur type : entier,
# sorties : error : nombre d'erreur type : entier,
def inscreaseError(error):
if letter not in word and alreadyUse == False:
myBody[error] = bodyItems[error]
error += 1
print('Il vous reste {} tentative(s)'.format(8 - error))
if error == 8:
print(' \n -----')
print(' | |')
print(' | O')
print(' | /|\\')
print(' | / \\')
print('_|_')
print('Perdu ! Le mot qui fallait trouvé était {}'.format(word))
return error
# but : vérifier la validité de la lettre
# sortie : letter : lettre choisie par le joueur type str
def checkLetter():
letter = input('Choisissez une lettre : ')
letter = letter.lower()
if not letter.isalpha(): #vérifie sur letter est une lettre de a-z
print("Letter non valide.")
return checkLetter()
else:
return letter
while error < 8:
print('{}'.format(myBody[0]))
print(' | {}'.format(myBody[1]))
print(' | {}'.format(myBody[2]))
print(' | {}{}{}'.format(myBody[3], myBody[4], myBody[5]))
print(' | {} {}'.format(myBody[6], myBody[7]))
print('_|_')
# on place ici la première letter
wordToFind(letters)
letter = checkLetter()
alreadyUse,letter,letters = checkAlreadyUse(letters)
# on parcours la liste contenant les letter du mot et on verifie si elles sont dans les letters utilisé
wordToFind(letters)
# si on écrit le mot directement on gagne ou on compare les deux listes celle du joueur et celle du mot défini au début
if len(letter) > 1 and letter == word or myWordList == wordList:
print('Vous avez gagné !')
break
error = inscreaseError(error)
quitter = input("Souhaitez-vous quitter le jeu (o/n) ? ")
if quitter == "o" or quitter == "O":
print("Vous avez quittez le jeu.")
continuer_partie = False
else :
continuer_partie = True
|
00e1eb6cd027002dc208c6c171c31fafea11b7f7 | ABCmoxun/AA | /AB/linux2/day14/code/raise.py | 519 | 3.71875 | 4 | # raise.py
# 此示例示意raise语句的用法
# 以下示意其它语言中不用异常机制,用返回值方式返回错误问题
def make_except(n):
# 假设n必须是 0~100之间的数
print("begin...")
if n > 100: # 传过的来参数无效,怎么告诉调用者呢?
return -1
if n < 0:
return -2
print("end")
return 0
value = int(input("请输入一个整数:"))
r = make_except(value)
if r < 0:
print("发生错误")
else:
print("程序正常完成")
|
590f7625baa96553fd28a68dd170f44445ca2851 | Pranay2309/Python_Programs | /unity matrix.py | 214 | 3.671875 | 4 | x=[[7,12,17],
[18,45,19],
[65,14,13]]
y=[[0,0,0],
[0,0,0],
[0,0,0]]
for i in range(len(x)):
for j in range(len(x[i])):
y[i][j]=x[i][j]//x[i][j]
for r in y:
print(r)
|
b37ff95d5249f8ff913f382a7767f0e79c51fb70 | brarajit18/Credit-Card-Fraud-Detection | /analyzeData2.py | 25,424 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
Credit card fraud detection
This notebook will test different methods on skewed data. The idea is to compare if preprocessing techniques work better when there is an overwhelming majority class that can disrupt the efficiency of our predictive model.
You will also be able to see how to apply cross validation for hyperparameter tuning on different classification models. My intention is to create models using:
Logistic Regression
We also want to have a try at anomaly detection techniques, but I still have to investigate a bit on that, so any advise will be appreciated!
"""
"""
OVERALL SCENARIO:
Clearly the data is totally unbalanced!!
This is a clear example where using a typical accuracy score to evaluate our classification algorithm. For example, if we just used a majority class to assign values to all records, we will still be having a high accuracy, BUT WE WOULD BE CLASSIFYING ALL "1" INCORRECTLY!!
There are several ways to approach this classification problem taking into consideration this unbalance.
Collect more data? Nice strategy but not applicable in this case
Changing the performance metric:
Use the confusio nmatrix to calculate Precision, Recall
F1score (weighted average of precision recall)
Use Kappa - which is a classification accuracy normalized by the imbalance of the classes in the data
ROC curves - calculates sensitivity/specificity ratio.
Resampling the dataset
Essentially this is a method that will process the data to have an approximate 50-50 ratio.
One way to achieve this is by OVER-sampling, which is adding copies of the under-represented class (better when you have little data)
Another is UNDER-sampling, which deletes instances from the over-represented class (better when he have lot's of data)
"""
# import libraries
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
"""
Approach
We are not going to perform feature engineering in first instance. The dataset has been downgraded in order to contain 30 features (28 anonamised + time + amount).
We will then compare what happens when using resampling and when not using it. We will test this approach using a simple logistic regression classifier.
We will evaluate the models by using some of the performance metrics mentioned above.
We will repeat the best resampling/not resampling method, by tuning the parameters in the logistic regression classifier.
We will finally perform classifications model using other classification algorithms.
"""
# loading the dataset
data = pd.read_csv("creditcard.csv")
data.head()
# find the target classes
count_classes = pd.value_counts(data['Class'], sort = True).sort_index()
count_classes.plot(kind = 'bar')
plt.title("Fraud class histogram")
plt.xlabel("Class")
plt.ylabel("Frequency")
# setting our input and target variables
# also apply the resampling
# Normalising the amount column. The amount column is not in line
# with the anonimised features.
from sklearn.preprocessing import StandardScaler
data['normAmount'] = StandardScaler().fit_transform(data['Amount'].reshape(-1, 1))
data = data.drop(['Time','Amount'],axis=1)
data.head()
"""
2. Assigning X and Y. No resampling.
"""
# extracting the training and testing data
X = data.ix[:, data.columns != 'Class']
y = data.ix[:, data.columns == 'Class']
"""
3. Resampling.
As we mentioned earlier, there are several ways to resample skewed data. Apart from under and over sampling, there is a very popular approach called SMOTE (Synthetic Minority Over-Sampling Technique), which is a combination of oversampling and undersampling, but the oversampling approach is not by replicating minority class but constructing new minority class data instance via an algorithm.
In this notebook, we will use traditional UNDER-sampling. I will probably try to implement SMOTE in future versions of the code, but for now I will use traditional undersamplig.
The way we will under sample the dataset will be by creating a 50/50 ratio. This will be done by randomly selecting "x" amount of sample from the majority class, being "x" the total number of records with the minority class.
"""
# Number of data points in the minority class
number_records_fraud = len(data[data.Class == 1])
fraud_indices = np.array(data[data.Class == 1].index)
# Picking the indices of the normal classes
normal_indices = data[data.Class == 0].index
# Out of the indices we picked, randomly select "x" number (number_records_fraud)
random_normal_indices = np.random.choice(normal_indices, number_records_fraud, replace = False)
random_normal_indices = np.array(random_normal_indices)
# Appending the 2 indices
under_sample_indices = np.concatenate([fraud_indices,random_normal_indices])
# Under sample dataset
under_sample_data = data.iloc[under_sample_indices,:]
X_undersample = under_sample_data.ix[:, under_sample_data.columns != 'Class']
y_undersample = under_sample_data.ix[:, under_sample_data.columns == 'Class']
# Showing ratio
print("Percentage of normal transactions: ", len(under_sample_data[under_sample_data.Class == 0])/len(under_sample_data))
print("Percentage of fraud transactions: ", len(under_sample_data[under_sample_data.Class == 1])/len(under_sample_data))
print("Total number of transactions in resampled data: ", len(under_sample_data))
#Splitting data into train and test set. Cross validation will be used
# when calculating accuracies.
from sklearn.cross_validation import train_test_split
# Whole dataset
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size = 0.3, random_state = 0)
print("Number transactions train dataset: ", len(X_train))
print("Number transactions test dataset: ", len(X_test))
print("Total number of transactions: ", len(X_train)+len(X_test))
# Undersampled dataset
X_train_undersample, X_test_undersample, y_train_undersample, y_test_undersample = train_test_split(X_undersample
,y_undersample
,test_size = 0.3
,random_state = 0)
print("")
print("Number transactions train dataset: ", len(X_train_undersample))
print("Number transactions test dataset: ", len(X_test_undersample))
print("Total number of transactions: ", len(X_train_undersample)+len(X_test_undersample))
from sklearn.cross_validation import train_test_split
# Whole dataset
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size = 0.3, random_state = 0)
print("Number transactions train dataset: ", len(X_train))
print("Number transactions test dataset: ", len(X_test))
print("Total number of transactions: ", len(X_train)+len(X_test))
# Undersampled dataset
X_train_undersample, X_test_undersample, y_train_undersample, y_test_undersample = train_test_split(X_undersample
,y_undersample
,test_size = 0.3
,random_state = 0)
print("")
print("Number transactions train dataset: ", len(X_train_undersample))
print("Number transactions test dataset: ", len(X_test_undersample))
print("Total number of transactions: ", len(X_train_undersample)+len(X_test_undersample))
"""
Logistic regression classifier - Undersampled data
We are very interested in the recall score, because that is the metric that will help us try to capture the most fraudulent transactions. If you think how Accuracy, Precision and Recall work for a confusion matrix, recall would be the most interesting:
Accuracy = (TP+TN)/total
Precision = TP/(TP+FP)
Recall = TP/(TP+FN)
As we know, due to the imbalacing of the data, many observations could be predicted as False Negatives, being, that we predict a normal transaction, but it is in fact a fraudulent one. Recall captures this.
Obviously, trying to increase recall, tends to come with a decrease of precision. However, in our case, if we predict that a transaction is fraudulent and turns out not to be, is not a massive problem compared to the opposite.
We could even apply a cost function when having FN and FP with different weights for each type of error, but let's leave that aside for now.
"""
from sklearn.linear_model import LogisticRegression
from sklearn.cross_validation import KFold, cross_val_score
from sklearn.metrics import confusion_matrix,precision_recall_curve,auc,roc_auc_score,roc_curve,recall_score,classification_report
# Very ad-hoc function to print K_fold_scores
def printing_Kfold_scores(x_train_data,y_train_data):
fold = KFold(len(y_train_data),5,shuffle=False)
# Different C parameters
c_param_range = [0.01,0.1,1,10,100]
results_table = pd.DataFrame(index = range(len(c_param_range),2), columns = ['C_parameter','Mean recall score'])
results_table['C_parameter'] = c_param_range
# the k-fold will give 2 lists: train_indices = indices[0], test_indices = indices[1]
j = 0
for c_param in c_param_range:
print('-------------------------------------------')
print('C parameter: ', c_param)
print('-------------------------------------------')
print('')
recall_accs = []
for iteration, indices in enumerate(fold,start=1):
# Call the logistic regression model with a certain C parameter
lr = LogisticRegression(C = c_param, penalty = 'l1')
# Use the training data to fit the model. In this case, we use the portion of the fold to train the model
# with indices[0]. We then predict on the portion assigned as the 'test cross validation' with indices[1]
lr.fit(x_train_data.iloc[indices[0],:],y_train_data.iloc[indices[0],:].values.ravel())
# Predict values using the test indices in the training data
y_pred_undersample = lr.predict(x_train_data.iloc[indices[1],:].values)
# Calculate the recall score and append it to a list for recall scores representing the current c_parameter
recall_acc = recall_score(y_train_data.iloc[indices[1],:].values,y_pred_undersample)
recall_accs.append(recall_acc)
print('Iteration ', iteration,': recall score = ', recall_acc)
# The mean value of those recall scores is the metric we want to save and get hold of.
results_table.ix[j,'Mean recall score'] = np.mean(recall_accs)
j += 1
print('')
print('Mean recall score ', np.mean(recall_accs))
print('')
best_c = results_table.loc[results_table['Mean recall score'].idxmax()]['C_parameter']
# Finally, we can check which C parameter is the best amongst the chosen.
print('*********************************************************************************')
print('Best model to choose from cross validation is with C parameter = ', best_c)
print('*********************************************************************************')
return best_c
# call the function for k-fold assessment
best_c = printing_Kfold_scores(X_train_undersample,y_train_undersample)
# Create a function to plot a fancy confusion matrix
import itertools
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=0)
plt.yticks(tick_marks, classes)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
#print("Normalized confusion matrix")
else:
1#print('Confusion matrix, without normalization')
#print(cm)
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, cm[i, j],
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
# Predictions on test set and plotting confusion matrix
"""
We have been talking about using the recall metric as our proxy of how effective our predictive model is. Even though recall is still the recall we want to calculate, just bear mind in mind that the undersampled data hasn't got a skewness towards a certain class, which doesn't make recall metric as critical.
"""
# Use this C_parameter to build the final model with the whole training dataset and predict the classes in the test
# dataset
lr = LogisticRegression(C = best_c, penalty = 'l1')
lr.fit(X_train_undersample,y_train_undersample.values.ravel())
y_pred_undersample = lr.predict(X_test_undersample.values)
# Compute confusion matrix
cnf_matrix = confusion_matrix(y_test_undersample,y_pred_undersample)
np.set_printoptions(precision=2)
print("Recall metric in the testing dataset: ", cnf_matrix[1,1]/(cnf_matrix[1,0]+cnf_matrix[1,1]))
# Plot non-normalized confusion matrix from small data chunk
class_names = [0,1]
plt.figure()
plot_confusion_matrix(cnf_matrix
, classes=class_names
, title='Confusion matrix')
plt.show()
# let's apply the model we fitted and test it on the whole data
# Use this C_parameter to build the final model with the whole training dataset and predict the classes in the test
# dataset
lr = LogisticRegression(C = best_c, penalty = 'l1')
lr.fit(X_train_undersample,y_train_undersample.values.ravel())
y_pred = lr.predict(X_test.values)
# Compute confusion matrix
cnf_matrix = confusion_matrix(y_test,y_pred)
np.set_printoptions(precision=2)
print("Recall metric in the testing dataset: ", cnf_matrix[1,1]/(cnf_matrix[1,0]+cnf_matrix[1,1]))
# Plot non-normalized confusion matrix
class_names = [0,1]
plt.figure()
plot_confusion_matrix(cnf_matrix
, classes=class_names
, title='Confusion matrix')
plt.show()
"""
Still a very decent recall accuracy when applying it to a much larger and skewed dataset!
"""
"""
We can start to be happy with how initial approach is working.
Plotting ROC curve and Precision-Recall curve.
I find precision-recall curve much more convenient in this case as our problems relies on the "positive" class being more interesting than the negative class, but as we have calculated the recall precision, I am not going to plot the precision recall curves yet.
AUC and ROC curve are also interesting to check if the model is also predicting as a whole correctly and not making many errors
"""
# ROC CURVE
lr = LogisticRegression(C = best_c, penalty = 'l1')
y_pred_undersample_score = lr.fit(X_train_undersample,y_train_undersample.values.ravel()).decision_function(X_test_undersample.values)
fpr, tpr, thresholds = roc_curve(y_test_undersample.values.ravel(),y_pred_undersample_score)
roc_auc = auc(fpr,tpr)
# Plot ROC
plt.title('Receiver Operating Characteristic')
plt.plot(fpr, tpr, 'b',label='AUC = %0.2f'% roc_auc)
plt.legend(loc='lower right')
plt.plot([0,1],[0,1],'r--')
plt.xlim([-0.1,1.0])
plt.ylim([-0.1,1.01])
plt.ylabel('True Positive Rate')
plt.xlabel('False Positive Rate')
plt.show()
"""
Explanaton of graph above:
An additional comment that would be interesting to do is to initialise multiple undersampled datasets and repeat the process in loop. Remember that, to create an undersample data, we randomly got records from the majority class. Even though this is a valid technique, is doesn't represent the real population, so it would be interesting to repeat the process with different undersample configurations and check if the previous chosen parameters are still the most effective. In the end, the idea is to use a wider random representation of the whole dataset and rely on the averaged best parameters.
"""
"""
Logistic regression classifier - Skewed data
Having tested our previous approach, I find really interesting to test the same process on the skewed data. Our intuition is that skewness will introduce issues difficult to capture, and therefore, provide a less effective algorithm.
To be fair, taking into account the fact that the train and test datasets are substantially bigger than the undersampled ones, I believe a K-fold cross validation is necessary. I guess that by splitting the data with 60% in training set, 20% cross validation and 20% test should be enough... but let's take the same approach as before (no harm on this, it's just that K-fold is computationally more expensive)
"""
best_c = printing_Kfold_scores(X_train,y_train)
# Use this C_parameter to build the final model with the whole training dataset and predict the classes in the test
# dataset
lr = LogisticRegression(C = best_c, penalty = 'l1')
lr.fit(X_train,y_train.values.ravel())
y_pred_undersample = lr.predict(X_test.values)
# Compute confusion matrix
cnf_matrix = confusion_matrix(y_test,y_pred_undersample)
np.set_printoptions(precision=2)
print("Recall metric in the testing dataset: ", cnf_matrix[1,1]/(cnf_matrix[1,0]+cnf_matrix[1,1]))
# Plot non-normalized confusion matrix
class_names = [0,1]
plt.figure()
plot_confusion_matrix(cnf_matrix
, classes=class_names
, title='Confusion matrix')
plt.show()
"""
Before continuing... changing classification threshold.
We have seen that by undersampling the data, our algorithm does a much better job at detecting fraud. I wanted also to show how can we tweak our final classification by changing the thresold.
Initially, you build the classification model and then you predict unseen data using it.
We previously used the "predict()" method to decided whether a record should belong to "1" or "0".
There is another method "predict_proba()".
This method returns the probabilities for each class. The idea is that by changing the threshold to assign a record to class 1, we can control precision and recall.
"""
# Let's check this using the undersampled data (best C_param = 0.01)
lr = LogisticRegression(C = 0.01, penalty = 'l1')
lr.fit(X_train_undersample,y_train_undersample.values.ravel())
y_pred_undersample_proba = lr.predict_proba(X_test_undersample.values)
thresholds = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]
plt.figure(figsize=(10,10))
j = 1
for i in thresholds:
y_test_predictions_high_recall = y_pred_undersample_proba[:,1] > i
plt.subplot(3,3,j)
j += 1
# Compute confusion matrix
cnf_matrix = confusion_matrix(y_test_undersample,y_test_predictions_high_recall)
np.set_printoptions(precision=2)
print("Recall metric in the testing dataset: ", cnf_matrix[1,1]/(cnf_matrix[1,0]+cnf_matrix[1,1]))
# Plot non-normalized confusion matrix
class_names = [0,1]
plot_confusion_matrix(cnf_matrix
, classes=class_names
, title='Threshold >= %s'%i)
"""
Analysis of graphs above
The pattern is very clear: the more you lower the required probability to put a certain in the class "1" category, more records will be put in that bucket.
"""
"""
About the following code:
This implies an increase in recall (we want all the "1"s), but at the same time, a decrease in precision (we misclassify many of the other class).
Therefore, even though recall is our goal metric (do not miss a fraud transaction), we also want to keep the model being accurate as a whole.
There is an option I think could be quite interesting to tackle this. We could assing cost to misclassifications, but being interested in classifying "1s" correctly, the cost for misclassifying "1s" should be bigger than "0" misclassifications. After that, the algorithm would select the threshold which minimises the total cost. A drawback I see is that we have to manually select the weight of each cost... therefore, I will leave this know as a thought.
Going back to the threshold changing, there is an option which is the Precisio-Recall curve. By visually seeing the performance of the model depending on the threshold we choose, we can investigate a sweet spot where recall is high enough whilst keeping a high precision value.
"""
# Investigate Precision-Recall curve and area under this curve
from itertools import cycle
lr = LogisticRegression(C = 0.01, penalty = 'l1')
lr.fit(X_train_undersample,y_train_undersample.values.ravel())
y_pred_undersample_proba = lr.predict_proba(X_test_undersample.values)
thresholds = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]
colors = cycle(['navy', 'turquoise', 'darkorange', 'cornflowerblue', 'teal', 'red', 'yellow', 'green', 'blue','black'])
plt.figure(figsize=(5,5))
j = 1
for i,color in zip(thresholds,colors):
y_test_predictions_prob = y_pred_undersample_proba[:,1] > i
precision, recall, thresholds = precision_recall_curve(y_test_undersample,y_test_predictions_prob)
# Plot Precision-Recall curve
plt.plot(recall, precision, color=color,
label='Threshold: %s'%i)
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.ylim([0.0, 1.05])
plt.xlim([0.0, 1.0])
plt.title('Precision-Recall example')
plt.legend(loc="lower left")
##PROPOSED CLASSIFICATION MODEL
from sklearn.naive_bayes import MultinomialNB
from sklearn.svm import LinearSVC
import numpy as np
import warnings
warnings.filterwarnings("ignore")
from sklearn.metrics import confusion_matrix
from sklearn.preprocessing import MinMaxScaler
import pandas as pd
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_absolute_error
rotation = 1
#Apply MinMax scaler
scaler = MinMaxScaler()
scaler.fit(X_train_undersample.values)
X_train1 = scaler.transform(X_train_undersample.values)
X_test1 = scaler.transform(X_test_undersample.values)
y_train1 = y_train_undersample.values.ravel()
y_test1 = y_test_undersample.values.ravel()
raw_data = {'classifier_name' : ['NB','KNN','SVM'], 'precision': [0.0, 0.0, 0.0], 'recall' : [0.0, 0.0, 0.0], 'f1err' : [0.0, 0.0, 0.0], 'accuracy' : [0.0, 0.0, 0.0], 'TP' : [0, 0, 0], 'TN' : [0, 0, 0], 'FP' : [0, 0, 0], 'FN' : [0, 0, 0]}
Overall_results = pd.DataFrame(raw_data, columns = ['classifier_name', 'precision', 'recall', 'f1err', 'accuracy', 'TP', 'TN', 'FP', 'FN','MAE','RAE'])
#Naive Bayes
classifier = MultinomialNB()
classifier.fit(X_train1, y_train1)
labels = classifier.predict(X_test1)
print("Naive Bayes Results:")
cm = confusion_matrix(labels,y_test1)
TN = cm[0,0]
FP = cm[0,1]
FN = cm[1,0]
TP = cm[1,1]
accuracy = float(TP+TN)/(TP+FP+FN+TN)
precision = float(TP) / (TP+FP)
recall = float(TP) / (TP+FN)
f1err = 2 * (float (precision * recall) / (precision + recall))
#print(cm)
#print(str(accuracy*100) + "%")
iiddx = 0
Overall_results['precision'][iiddx]=precision
Overall_results['recall'][iiddx]=recall
Overall_results['f1err'][iiddx]=f1err
Overall_results['accuracy'][iiddx]=accuracy
Overall_results['TP'][iiddx]=TP
Overall_results['TN'][iiddx]=TN
Overall_results['FP'][iiddx]=FP
Overall_results['FN'][iiddx]=FN
Overall_results['MAE'][iiddx]=mean_absolute_error(labels,y_test1)
# KNN CLassifier
classifier = KNeighborsClassifier(n_neighbors=3)
classifier.fit(X_train1, y_train1)
labels = classifier.predict(X_test1)
print("KNN Results:")
cm = confusion_matrix(labels,y_test1)
TN = cm[0,0]
FP = cm[0,1]
FN = cm[1,0]
TP = cm[1,1]
accuracy = float(TP+TN)/(TP+FP+FN+TN)
precision = float(TP) / (TP+FP)
recall = float(TP) / (TP+FN)
f1err = 2 * (float (precision * recall) / (precision + recall))
#print(cm)
#print(str(accuracy*100) + "%")
iiddx = 1
Overall_results['precision'][iiddx]=precision
Overall_results['recall'][iiddx]=recall
Overall_results['f1err'][iiddx]=f1err
Overall_results['accuracy'][iiddx]=accuracy
Overall_results['TP'][iiddx]=TP
Overall_results['TN'][iiddx]=TN
Overall_results['FP'][iiddx]=FP
Overall_results['FN'][iiddx]=FN
Overall_results['MAE'][iiddx]=mean_absolute_error(labels,y_test1)
print (Overall_results)
fname = 'Overall_results_'+str(rotation)+'.csv'
Overall_results.to_csv(fname, index=False, header=False)
# SVM CLassifier
classifier = LinearSVC()
classifier.fit(X_train1, y_train1)
labels = classifier.predict(X_test1)
print("SVM Results:")
cm = confusion_matrix(labels,y_test1)
TN = cm[0,0]
FP = cm[0,1]
FN = cm[1,0]
TP = cm[1,1]
accuracy = float(TP+TN)/(TP+FP+FN+TN)
precision = float(TP) / (TP+FP)
recall = float(TP) / (TP+FN)
f1err = 2 * (float (precision * recall) / (precision + recall))
#print(cm)
#print(str(accuracy*100) + "%")
iiddx = 2
Overall_results['precision'][iiddx]=precision
Overall_results['recall'][iiddx]=recall
Overall_results['f1err'][iiddx]=f1err
Overall_results['accuracy'][iiddx]=accuracy
Overall_results['TP'][iiddx]=TP
Overall_results['TN'][iiddx]=TN
Overall_results['FP'][iiddx]=FP
Overall_results['FN'][iiddx]=FN
Overall_results['MAE'][iiddx]=mean_absolute_error(labels,y_test1)
print (Overall_results)
fname = 'Overall_results_'+str(rotation)+'.csv'
Overall_results.to_csv(fname, index=False, header=False) |
9a91f5e25b27cbd52e827d324ef3dd064dd4d1ec | jeffbulmer/DnDStuff | /Goblinator/SkillSet.py | 2,631 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 10 15:44:47 2017
@author: jeff
"""
from random import randint
import math
class SkillSet:
def __init__(self, possibleSkills):
self.skills = {}
self.populateSkills(possibleSkills)
def populateSkills(self, possibleSkills):
for i in possibleSkills:
self.skills[i] = [possibleSkills[i], 0]
def getSkills(self):
return self.skills
def assignSkills(self, points, init, attr):
panic = 0
while points > 0:
#select skill to modify
addAttr = randint(0,len(self.skills)-1)
skill = self.skills[self.skills.keys()[addAttr]]
maxV = attr[skill[0]]
#determine modifier
mod = randint(1,5)
#determine incentive
#skill assignment incentivizes putting points into
#useful skills that correspond to attributes
#which the goblin possesses.
incentive = math.floor(maxV/2);
if(maxV > 1):
if init:
incentive += 1
else:
incentive -= 1
else:
incentive -= 2
if(skill[1] > maxV):
incentive -= 1
elif(skill[1] < maxV):
incentive += 1
if(skill[0].lower == 'smarts' or skill[0].lower == 'agility'):
incentive += 1
incentive += maxV - (mod+skill[1]-1)
#modify skill
check = randint(0,maxV)
#print("Skill: " + str(self.skills.keys()[addAttr]))
#print("Incentive = " + str(incentive))
#print("Check = " + str(check))
#print("Mod = " + str(mod))
if incentive >= check or panic >= 5:
if panic == 5:
panic = 0;
cost = 0;
for i in range(0,mod):
currV = skill[1]
currCost = 0
if (currV + 1) > 5:
break;
if (currV >= maxV) or (currV == 0 and not init):
currCost = 2
else:
currCost = 1
cost += currCost
if points - cost < 0:
break;
skill[1] += 1
points -= cost
else:
panic += 1 |
6c78d7b69c798c835dc21edc1b17b06c3e58baa0 | oscarEDA1/EDA1 | /practica11/ejerc8.py | 1,368 | 3.828125 | 4 | # Medición y gráficas de los tiempos de ejecución
importar matplotlib . pyplot como plt
de mpl_toolkits . mplot3d import Axes3D
importar al azar
del tiempo de importación tiempo
desde programa5 import insertSort
desde programa6 import quicksort
datos = [ ii * 100 para ii en el rango ( 1 , 21 )]
tiempo_is = []
tiempo_qs = []
para ii en datos :
lista_is = aleatorio . muestra ( rango ( 0 , 10000000 ), ii )
lista_qs = lista_is . copia ()
t0 = tiempo ()
insertSort ( lista_is )
tiempo_is . agregar ( round ( time () - t0 , 6 ))
t0 = tiempo ()
clasificación rápida ( lista_qs )
tiempo_qs . agregar ( round ( time () - t0 , 6 ))
print ( "Tiempos parciales de ejecución en insert sort {} [s]" . format ( tiempo_is ))
print ( "Tiempos parciales de ejecución en clasificación rápida {} [s]" . format ( tiempo_qs ))
fig , ax = plt . subtramas ()
#ax = plt.subplots (111)
hacha . plot ( datos , tiempo_is , label = "insert sort" , marker = "*" , color = "r" )
hacha . plot ( datos , tiempo_qs , label = "clasificación rápida" , marcador = "o" , color = "b" )
hacha . set_xlabel ( "Datos" )
hacha . set_ylabel ( "Tiempo" )
hacha . cuadrícula ( verdadero )
hacha . leyenda ( loc = 2 )
plt . título ( "Tiempos de ejecución [s] inser sort" )
plt . show () |
378e7e5fa5f71cc81d58f3bbd1a561108fe68365 | bishalpokharel325/python7am | /fourthday conditionalandloops/ecommerce.py | 3,181 | 4.25 | 4 | print("------------WELCOME TO E-COMMERCE WEBSITE----------")
print("Here are our products and their selling prices:")
print("SN Products Price")
print("---------------------------\n")
print("1 Dell 50000")
print("2 Mac 150000")
print("3 Tosiba 65000")
print("----------------------------")
"""!Defining no of different quantities of products user want to buy in three variables."""
dell=int(input("Enter no. of dell laptops you want to buy:"))
mac=int(input("Enter no. of Mac laptops you want to buy:"))
tosiba=int(input("Enter no. of Tosiba laptops you want to buy:"))
subtotal=dell*50000+mac*150000+tosiba*65000
location=input("Enter your address (ktm/bkt/ltp):")
deliverycharge=0
packcost=0
taxamount=0
total=0
grandtotal=0
if location=="ktm" or location=="bkt" or location=="ltp":
print("For making a purchase, You can choose two options:")
print("1. Either to be delivered at home.")
print("2. Or your will pick up the product yourself.")
print("Note: our home delivery charge is Rs. 1000")
print("Do you want to your products to be delivered at home? (Y or N)")
choice=input()
if choice=="Y" or choice=="y":
deliverycharge=1000
print("Our packaging services:")
print("----------------------------")
print("1. normal packaging: Rs. 1000")
print("2. Packaging with laptop bags: Rs. 2500")
print("3. packaging as gift: Rs. 5000")
print("---------------------------")
packaging=int(input("Enter your packaging option(1/2/3):"))
if packaging==1:
packcost=1000
if packaging==2:
packcost=2500
if packaging==3:
packcost=5000
total=subtotal+deliverycharge+packcost
if location=="ktm":
taxamount=0.13*total
grandtotal=total+taxamount
print("Your cost details:")
print("----------------------------------------------------------------------------")
print("SN Description quantity rate amount Remarks")
print("----------------------------------------------------------------------------")
print(f"1 Dell {dell} 50000 {dell*50000} ")
print(f"2 Mac {mac} 150000 {mac*150000} ")
print(f"3 Tosiba {tosiba} 65000 {tosiba * 65000} ")
print("--------------------------------------------------------------------------")
print(f" Sub-Total: Rs.{subtotal}")
print(f" packaging fees: Rs.{packcost}")
print(f" delivery charges: Rs.{deliverycharge}")
print(f" Total Cost: Rs.{total}")
print(f" VAT(13% of total): Rs.{taxamount}")
print(f"------------------------------------------------------------------------")
print(f" Grand Total: Rs.{grandtotal}")
print("-------------------------------------------------------------------------")
else:
print("Sorry, Our service is limited only in kathmandu valley.") |
8cdd9fdfa9be8e7b1e0479b3ba36c22cb3b34a2c | meenakshi25jan/python_assignment | /assign16.py | 604 | 4.125 | 4 | """
16.Take the input from the user for(Total number of people, toatl number of busses, Number of seats for bus). Based on the input
Deside whether there is su
fficient busses or not and give solution for how many extra busses required.
"""
import math
tp=input("Enter total number of people:")
tb=input("Enter total number of buses:")
ns=input("Enter number of seats in one bus:")
def sufbus(tp,tb,ns):
if tp==tb*ns:
print "sufficient bus are avaliable"
else:
br=(float(tp)/float(ns))-tb
print "Number of bus required is ", math.ceil(br)
sufbus(tp,tb,ns)
|
d50e395e05c5b6486ff5463c6f21e295540cc947 | basu-sanjana1619/database_files | /create_table.py | 539 | 3.8125 | 4 | import sqlite3
con = sqlite3.connect('IT_company.db')
cur = con.cursor()
cur.execute('''DROP TABLE IF EXISTS Employee''')
cur.execute('''CREATE TABLE Employee(
name TEXT,
emp_ID INTEGER)''')
#[IF NOT EXISTS] option will create a table if table does not exist
cur.execute('''CREATE TABLE IF NOT EXISTS Department(
dep_name TEXT,
dep_ID INTEGER)''')
#commit and save the changes
con.commit()
#close the connection
con.close()
|
4f6ec68e46e3768b1f585a2a3fa3d2f1273dc9bd | landry-ming/leetcode_python | /Tree/offer34_二叉搜索树的后序遍历.py | 2,097 | 3.96875 | 4 | """
后序遍历:左子树 + 右子树 + 根节点
二叉搜索树:左子树所有节点的值<根节点, 右子树所有节点的值>根节点,其左右子树也是二叉搜索树
递归分治:
根据递归, 判断所有子树的正确性。
递归终止条件:当i>=j,说明此子树的节点数量<=1,无需判别正确性, 直接返回True
递推工作:
1. 划分左右子树, 遍历后序遍历的[i,j]的元素, 寻找第一个大于根节点的节点, 索引为m, 此时左右子树的区间为[i, m-1], [m, j-1], 根节点索引为j
2. 判断是否为二叉搜索树, 左子树区间[i, m-1]中的所有节点都应<postorder[j], 而第 1.划分左右子树 步骤已经保证左子树区间的正确性,因此只需要判断右子树区间即可。
右子树区间 [m, j-1][m,j−1] 内的所有节点都应 >> postorder[j]postorder[j] 。实现方式为遍历,当遇到 \leq postorder[j]≤postorder[j] 的节点则跳出;则可通过 p = jp=j 判断是否为二叉搜索树。
返回值:
所有子树都需正确才可判定正确,因此使用 与逻辑符 \&\&&& 连接。
p = jp=j : 判断 此树 是否正确。
recur(i, m - 1)recur(i,m−1) : 判断 此树的左子树 是否正确。
recur(m, j - 1)recur(m,j−1) : 判断 此树的右子树 是否正确。
"""
class Solution:
def verifyPostorder(self, postorder: List[int]) -> bool:
def dfs(i, j):
if i >= j:
return True
p = i
while postorder[p] < postorder[j]:
p += 1
m = p
while postorder[p] > postorder[j]:
p += 1
return p == j and dfs(i, m-1) and dfs(m ,j-1)
return dfs(0, len(postorder)-1)
时间复杂度 O(N^2): 每次调用 recur(i,j)recur(i,j) 减去一个根节点,因此递归占用 O(N)O(N) ;最差情况下(即当树退化为链表),每轮递归都需遍历树所有节点,占用 O(N)O(N) 。
空间复杂度 O(N) : 最差情况下(即当树退化为链表),递归深度将达到N。
|
c6021b00af713e70ec08955078caba153b177acf | lucasbezerra06/Exercicios | /exe045.py | 530 | 3.734375 | 4 | from random import randint
from time import sleep
op = int(input('''1 - pedra
2 - papel
3 - tesoura: '''))
jokenpo = ('Pedra', 'Papel', 'Tesoura')
oppc = randint(1, 3)
print('JO')
sleep(1)
print('KEN')
sleep(1)
print('PO')
if 0 > op > 3:
print('opção invalida')
else:
print('-='*10)
print('{} X {}'.format(jokenpo[op-1], jokenpo[oppc-1]))
print('-='*10)
if op == oppc:
print('Empate')
elif op-oppc == (-2) or op-oppc == 1:
print('Você venceu!')
else:
print('Você perdeu!')
|
2357b9b27ad38511b7ab5ad75c580c4c365eb5dd | Jiawei-Wang/LeetCode-Study | /528. Random Pick with Weight.py | 2,579 | 3.859375 | 4 | # 暴力解:将每个元素的下标以它的weight的数量加入一个list,从list中随机取一个返回
# space超标
class Solution:
def __init__(self, w: List[int]):
self.w = w
self.weight = []
for i in range(len(self.w)):
self.weight += [i] * self.w[i]
def pickIndex(self) -> int:
index = random.randint(0, len(self.weight)-1)
return self.weight[index]
# Your Solution object will be instantiated and called as such:
# obj = Solution(w)
# param_1 = obj.pickIndex()
# built in
class Solution:
def __init__(self, w):
self.w = w
def pickIndex(self):
return random.choices(range(len(self.w)), weights=self.w)[0]
"""
choice() method returns a randomly selected element from the specified sequence,返回的是一个只有一个元素的list
If a weights sequence is specified, selections are made according to the relative weights
"""
# built in
class Solution:
def __init__(self, w):
self.w = list(itertools.accumulate(w))
# 将w中两两元素相加,然后返回一个值,然后再拿这个值和下一个元素相加,返回另一个值
# 所以最后会得到[w[0], w[0]+w[1], w[0]+w[1]+w[2], etc]
# 举例:
# import itertools
# a = [1,2,3,4]
# for item in itertools.accumulate(a):
# print(item):1,3,6,10
def pickIndex(self):
return bisect.bisect_left(self.w, random.randint(1, self.w[-1]))
# 从w最后一个元素的值(即w[0]+w[1]+w[2]+etc)中随机取一个数字,然后找到该数字在w中(如果要进行插入操作)应该存在的最左边的位置
# 举例
# w = [1,2,3,4]
# 新的w = [1,3,6,10]
# 随机取5, 则应当返回2
# 将上面的built in换成正常代码
# accumulated freq sum + binary search
class Solution:
def __init__(self, w: List[int]):
self.w = w
self.n = len(w)
for i in range(1,self.n):
w[i] += w[i-1]
self.s = self.w[-1]
def pickIndex(self):
seed = random.randint(1,self.s)
l,r = 0, self.n-1
while l<r:
mid = (l+r)//2
if seed <= self.w[mid]:
r = mid
else:
l = mid+1
return l
# 还有一个更优化的答案:
# https://leetcode.com/problems/random-pick-with-weight/discuss/671439/Python-Smart-O(1)-solution-with-detailed-explanation |
ce169b8caa488199f9f9db67075eb578125e4bbe | liubei90/leetcode | /405.数字转换为十六进制数.py | 1,473 | 3.703125 | 4 | #
# @lc app=leetcode.cn id=405 lang=python3
#
# [405] 数字转换为十六进制数
#
# https://leetcode-cn.com/problems/convert-a-number-to-hexadecimal/description/
#
# algorithms
# Easy (50.68%)
# Likes: 76
# Dislikes: 0
# Total Accepted: 12.5K
# Total Submissions: 24.7K
# Testcase Example: '26'
#
# 给定一个整数,编写一个算法将这个数转换为十六进制数。对于负整数,我们通常使用 补码运算 方法。
#
# 注意:
#
#
# 十六进制中所有字母(a-f)都必须是小写。
# 十六进制字符串中不能包含多余的前导零。如果要转化的数为0,那么以单个字符'0'来表示;对于其他情况,十六进制字符串中的第一个字符将不会是0字符。
# 给定的数确保在32位有符号整数范围内。
# 不能使用任何由库提供的将数字直接转换或格式化为十六进制的方法。
#
#
# 示例 1:
#
#
# 输入:
# 26
#
# 输出:
# "1a"
#
#
# 示例 2:
#
#
# 输入:
# -1
#
# 输出:
# "ffffffff"
#
#
#
# @lc code=start
class Solution:
def toHex(self, num: int) -> str:
if num == 0:
return '0'
# 负数转换为二进制补码
if num < 0:
num = 2**32 + num
hex_arr = list('0123456789abcdef')
res = []
while num != 0:
i = num & 15
res.append(hex_arr[i])
num = num >> 4
res.reverse()
return ''.join(res)
# @lc code=end
|
d6412139b348989b01130ace9357a3e0f8665126 | Alcogu/Master-Python | /12-Modulos/main.py | 917 | 3.640625 | 4 | """
Son funcionalidades ya hechas para reutilizar.
"""
#Importar modulo propio
#primera forma
"""
import mimodulo
print(mimodulo.holaMundo("Peluchito"))
print(mimodulo.calculadora(3,5, True))
"""
#Segunda Forma
#from mimodulo import * importa todo
from mimodulo import holaMundo
#print(holaMundo("Peluchito"))
# Modulo Fechas
import datetime
#print(datetime.date.today())
fechacompleta = datetime.datetime.now()
"""
print(fechacompleta)
print(fechacompleta.year)
print(fechacompleta.day)
print(fechacompleta.month)
"""
fechapersonalizada = fechacompleta.strftime("%d/%m/%Y, ")
#print("Mi fecha personalizada", fechapersonalizada)
#Modulo Matematicas
import math
print("Pi es: ", math.pi)
print("Raiz cuadrada de 10: ", math.sqrt(5))
print("Redondear: ", math.floor(6.1545521))
print("Redondear: ", math.ceil(6.1545521))
import random
print("Número aleatorio entre 50 a 100 = ", random.randint(50, 100)) |
b34cca6ba3c28de26e833f5a562a6209884120d6 | pariamahmoudi/GN.Portal.Odoo | /Addons/gn_portal_parnian/distance.py | 1,650 | 4 | 4 | def iterative_levenshtein(s, t, costs=(1, 1, 1)):
"""
iterative_levenshtein(s, t) -> ldist
ldist is the Levenshtein distance between the strings
s and t.
For all i and j, dist[i,j] will contain the Levenshtein
distance between the first i characters of s and the
first j characters of t
costs: a tuple or a list with three integers (d, i, s)
where d defines the costs for a deletion
i defines the costs for an insertion and
s defines the costs for a substitution
"""
rows = len(s)+1
cols = len(t)+1
deletes, inserts, substitutes = costs
dist = [[0 for x in range(cols)] for x in range(rows)]
# source prefixes can be transformed into empty strings
# by deletions:
for row in range(1, rows):
dist[row][0] = row * deletes
# target prefixes can be created from an empty source string
# by inserting the characters
for col in range(1, cols):
dist[0][col] = col * inserts
for col in range(1, cols):
for row in range(1, rows):
if s[row-1] == t[col-1]:
cost = 0
else:
cost = substitutes
dist[row][col] = min(dist[row-1][col] + deletes,
dist[row][col-1] + inserts,
dist[row-1][col-1] + cost) # substitution
for r in range(rows):
#print(dist[r])
pass
return dist[row][col]
print(iterative_levenshtein('hey you', 'hey you'))
print(iterative_levenshtein('hey you there', 'hey you')) |
15307d63373622f4d3052c38c22bdfb65a2f4dfa | jvs--/rl | /cliff_walk.py | 9,833 | 3.546875 | 4 | #!/opt/local/bin/python2.7
# An implementation of Q-learning and SARSA on the cliff walk environment based
# on [Sutton & Barto, 1998]'s exmaple 6.6.
#
# Written by:
# github.com/jvs-- May 2014
import numpy as np
import matplotlib.pyplot as plt
import random
import pprint
################################################################################
### LEARNING METHODS ###
################################################################################
def Q_learning(agent, env, episodes, alpha=0.1, gamma=0.9):
stats = [] # for book keeping how much reward was gained in each episode
Q = init_Q(env.states) # Initialize Q arbitrarily
for episode in xrange(episodes):
accumulated_reward = 0 # for book keeping of the reward
s = env.start
while not s in env.goals:
# Choose a from s using Q, take action, observe reward, next state
(a, s_, reward) = agent.take_action(env, s, Q)
Q[s][a] = Q[s][a] + alpha * (reward + gamma * max(Q[s_].values()) - Q[s][a])
s = s_
accumulated_reward += reward
print "FOUND GOAL!"
stats.append((episode, accumulated_reward))
return (Q, stats)
def SARSA(agent, env, episodes, alpha=0.1, gamma=0.9):
stats = [] # for book keeping how much reward was gained in each episode
Q = init_Q(env.states) #Initialize Q arbitrarily
for episode in xrange(episodes):
accumulated_reward = 0 # for book keeping of the reward
s = env.start
#Choose a from s using policy derived from Q (eg greedy)
a = agent.best_action(s, Q)
while not s in env.goals:
#Take action a and observe r, s'
(a, s_, reward) = agent.take_action(env, s, Q)
a_ = agent.best_action(s_, Q)
#Choose a' form s' using policy derived from Q (eg greedy)
Q[s][a] = Q[s][a] + alpha * (reward + gamma * Q[s_][a_] - Q[s][a])
s = s_
a = a_
accumulated_reward += reward
print "FOUND GOAL!"
stats.append((episode, accumulated_reward))
return (Q, stats)
### Utility functions
def init_Q(states):
Q = {}
for state in states:
Q[state] = {'down': 0, 'up': 0, 'left': 0, 'right': 0}
return Q
def states_from_grid(grid):
states = []
for i, lst in enumerate(grid):
for j, entry in enumerate(lst):
if grid[i][j] != "#":
states.append((i,j))
return states
### Class definitions
class Experiment:
"""Runs agent on environment and displays reward statistics.
Arguments:
env -- the environment to run on
agent -- the agent
nr_episodes --- how many episodes to run"""
def __init__(self, env, agent, nr_episodes):
self.env = env
self.agent = agent
self.episodes = nr_episodes
def run(self):
# Let the agent learn on the provided environment
(Q, stats) = agent.learn(self.env, self.episodes)
# Print the learned Q function and reward statistics
# Uncomment if you don't wanna see the clutter
pp = pprint.PrettyPrinter(indent=2)
pp.pprint(stats)
pp.pprint(Q)
# Plot reward statistics
plt.plot(stats)
plt.show()
class Env:
"""The environment modeled as a Markov decision process. We
assume a perfect model of the world. Thus states, actions, transition
function and immediate reward function are known.
Arguments:
states -- states of the mdp
goals -- a subset of the states defining which are goals states
actions -- possible actions
transitions -- P(s'|s,a) a function that defines transitionprobabilities
reward -- r(s,a,s') a function defining the immediate reward
"""
def __init__(self, grid, states, start, terminals, cliff):
self.grid = grid
self.states = states
self.start = start
self.goals = terminals
self.cliff = cliff
def show(self):
for line in self.grid:
print line
print ""
def on_grid(self, state):
# ** In this implementation we should never even get into a stituation
# where requested states are outside the dimensions of the grid
#print "Is ", str(state), " on the grid?"
assert ( (state[0] < len(grid) and state[1] < len(grid[0]) ) and
(state[0] >= 0 and state[1] >= 0) )
# Since we start from inside the grid walls define the boundaries of the
# world and are not walkable.
if self.grid[state[0]][state[1]] == "#":
#print "no."
return False
else:
#print "yes."
return True
def R(self, state):
"""Reward function for the cliff environment."""
if state in self.goals:
return 100
elif state in cliff:
return -100
else:
return -1
def T(self, state, action):
"""A transition-function for the cliff environment. Substitute your
own for other environments and tasks."""
# Otherwise same as normal grid transitions
if not self.on_grid(state):
log = str(state) + " is not a valid position on the grid."
raise Exception(log)
if state in cliff:
# Reset to start state when fallen into cliff
return self.start
direction = action
if direction == "up":
newpos = (state[0]-1, state[1])
elif direction == "down":
newpos = (state[0]+1, state[1])
elif direction == "left":
newpos = (state[0], state[1]-1)
elif direction == "right":
newpos = (state[0], state[1]+1)
else:
log = str(direction) + " is not a valid direction."
raise Exception(log)
# Show attempted move
#print "Try moving from ", str(state), direction," to ", newpos
if self.on_grid(newpos):
new_state = newpos
else:
new_state = state # if invalid just stay were you are
return new_state
class Agent:
"""An agent with eps greedy action selection and learns using a supplied
learning method
Arguments:
actions -- possible actions the agent can take
learning_method -- learning method (eg. Q-learning)
"""
def __init__(self, actions, learning_method):
self.actions = actions
self.state = ()
self.Q = []
self.learning_method = learning_method
def learn(self, env, episodes):
return self.learning_method(self, env, episodes)
def take_action(self, env, state, Q):
# Given the current state select an action according to Q
# and try to transition using this action and observe the new state
#action = self.select_random() # random action selection
action = self.select_epsilon_greedy(state, Q) # greedy action selection
new_state = env.T(state, action)
print action, " ", new_state
self.state = new_state
#return the new state and reward receives from the environment
return (action, new_state, env.R(new_state))
### Action selection methods ###
def select_epsilon_greedy(self, state, Q, eps=0.1):
if random.random() < eps:
action = random.choice(self.actions) # With prob. eps choose random
else:
action = self.best_action(state, Q) # Otherwise choose best action
return action
def select_random(self):
return random.choice(self.actions) # random action selection for testing
def best_action(self, state, Q):
best = 0
best_action = random.choice(self.actions) # init randomly
for action in Q[state]:
curr = Q[state][action]
if curr > best:
best = curr
best_action = action
return best_action
if __name__ == '__main__':
### Set up environment, agent and experiment to run###
episodes = 500 # Number of episodes to run experiment
actions = ['up', 'down', 'left', 'right'] # Possible actions to take
# Defining a cliff world
# This grid is moslty for visualisation on commandline except for the
# walls '#' which are actually used to test world boundaries but they could
# as well be defines down below as an extra variable like goals and cliff.
grid = [['#','#','#','#','#','#','#','#','#','#','#','#','#','#'],
['#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','#'],
['#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','#'],
['#',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','#'],
['#','A','U','U','U','U','U','U','U','U','U','U','G','#'],
['#','#','#','#','#','#','#','#','#','#','#','#','#','#']]
states = states_from_grid(grid)
goals = [(4, 12)]
start = (4,1)
cliff = [(4,2), (4,3), (4,4), (4,5), (4,6), (4,7), (4,8), (4,9), (4, 10), (4,11)]
# Init environment
env = Env(grid, states, start, goals, cliff)
env.show() # Let's take a look at our world
### Init agent with Q_learning as learning strategy and run experiment ###
agent = Agent(actions, Q_learning)
experiment = Experiment(env, agent, episodes)
experiment.run()
### Set up agent with SARSA as learning strategy and run experiment ###
agent = Agent(actions, SARSA)
experiment = Experiment(env, agent, episodes)
experiment.run()
|
a28a3cf535cf4cf1e9382e9414b213d17c9dd1ed | subinYoun/python-basics | /Lambda Express.py | 163 | 3.640625 | 4 | def add(a, b):
return a+b
#일반적인 add() 메서드 사용
print(add(3,7))
#람다 표현식으로 구현한 add()메서드
print((lambda a, b: a+b)(3, 7)) |
7db1fadd942d3460c4ff29d6078a167e9177582b | stacygo/2021-01_UCD-SCinDAE-EXS | /08_Statistical-Thinking-in-Python-1/08_ex_2-10.py | 644 | 3.8125 | 4 | # Exercise 2-10: The standard deviation and the variance
import numpy as np
versicolor_petal_length = [4.7, 4.5, 4.9, 4., 4.6, 4.5, 4.7, 3.3, 4.6, 3.9, 3.5, 4.2, 4., 4.7,
3.6, 4.4, 4.5, 4.1, 4.5, 3.9, 4.8, 4., 4.9, 4.7, 4.3, 4.4, 4.8, 5.,
4.5, 3.5, 3.8, 3.7, 3.9, 5.1, 4.5, 4.5, 4.7, 4.4, 4.1, 4., 4.4, 4.6,
4., 3.3, 4.2, 4.2, 4.2, 4.3, 3., 4.1]
# Compute the variance: variance
variance = np.var(versicolor_petal_length)
# Print the square root of the variance
print(np.sqrt(variance))
# Print the standard deviation
print(np.std(versicolor_petal_length))
|
4c683a97b45606897563b12ead45911c089d34cd | dxmahata/codinginterviews | /leetcode/swap_nodes_in_pairs.py | 1,016 | 3.984375 | 4 | '''
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in
the list, only nodes itself can be changed.
URL: https://leetcode.com/problems/swap-nodes-in-pairs/
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param {ListNode} head
# @return {ListNode}
def swapPairs(self, head):
if head == None or head.next == None:
return head
else:
temp = head
while temp != None and temp.next != None:
self.swapData(temp, temp.next)
temp = temp.next.next
return head
def swapData(self,node1,node2):
tempNode = node1.val
node1.val = node2.val
node2.val = tempNode
|
93b0e864fa4e825fe7d28fd4e0e0ce5ae780d181 | PdxCodeGuild/class_redmage | /code/scott/python/lab06_passgen.py | 1,503 | 4.15625 | 4 | #lab6_passgen.py
#import random and string to source characters and to randomly choose from them
import random
import string
# priming
usercaps = ""
userlower = ""
usersym = ""
capstring = string.ascii_uppercase
lowerstring = string.ascii_lowercase
symstring = string.punctuation
password = ""
# collecting desired values
while usercaps == "":
usercaps = input("How many capital letters do you want in your password? (enter a number or 'none'): ")
if usercaps == "none":
break
else:
usercaps = int(usercaps)
while userlower == "":
userlower = input("How many lowercase letters do you want in your password? (enter a number or 'none'): ")
if userlower == "none":
break
else:
userlower = int(userlower)
while usersym == "":
usersym = input("How many special characters do you want in your password? (enter a number or 'none'): ")
if usersym == "none":
break
else:
usersym = int(usersym)
# randomly selecting from the right list
if usercaps != "none":
for i in range(abs(usercaps)):
password = password + random.choice(capstring)
if userlower != "none":
for i in range(abs(userlower)):
password = password + random.choice(lowerstring)
if usersym != "none":
for i in range(abs(usersym)):
password = password + random.choice(symstring)
password = list(password)
random.shuffle(password)
pass_string = "".join(password)
print(f"Your new password is {pass_string}") |
effabe997cec338c4697fb36b3dbd38e443caf7d | BrunoCruzIglesias/Python | /Pacote Download/Ex039_12_Alistamento_Militar.py | 1,531 | 4.15625 | 4 | #programa que leia o ano de nascimento de um jovem e informe:
# Se ele ainda vai se alistar no serviço militar
# Se é a hora de se alistar
# Se já passou o tempo do alistamento
# O programa tb deverá mostrar o tempo que falta ou tempo q passou para o alistamento
import datetime
# from datetime import date
# ano_nasc = int(input('Digite o ano do seu nascimento (Ex: 1988): '))
# ano_atual = date.today().year
# calculo = ano_atual - ano_nasc
# if ano_atual - ano_nasc == 18:
# print('Você está com {} anos, está no tempo certo de se alistar'.format(calculo))
# elif ano_atual - ano_nasc < 18:
# print('Você está com {} anos, ainda falta(m) {} ano(s) para o alistamento.'.format(calculo, (18 - calculo)))
# elif ano_atual - ano_nasc > 18:
# print('Você está com {} anos, já passou/passaram {} ano(s) do alistamento'.format(calculo, (calculo - 18)))
#Jeito do professor
from datetime import date
atual = date.today().year
nasc = int(input('Ano de nascimento: '))
idade = atual - nasc
print('Quem nasceu em {} tem {} anos em {}.'.format(nasc, idade, atual))
if idade == 18:
print('Você tem que se alistar imediatamente')
elif idade < 18:
saldo = 18 - idade
print('Ainda falta(m) {} ano(s) para o alistamento'.format(saldo))
ano = atual + saldo
print('Seu alistamento será em {}.'.format(ano))
elif idade > 18:
saldo = idade - 18
print('Você já deveria ter se alistado há {} ano(s).'.format(saldo))
ano = atual - saldo
print('Seu alistamento foi em {}.'.format(ano))
|
c680f88f1ebcdd6fe33614387c41502786cb43ff | maliksh7/Data-Structure-and-Algorithms-in-Python | /Practice Codes/hashmaps.py | 1,630 | 3.6875 | 4 | class Hashmap:
def __init__(self):
self.size = 10
self.map = [None] * self.size
def _get_hashed(self,key):
if type(key) == int:
return key % self.size
if type(key) == str:
return len(key) % self.size
if type(key) == tuple:
return len(key) % self.size
def add(self,key,value):
key_hash = self._get_hashed(key)
key_value = [ key,value]
if self.map[key_hash] is None:
self.map[key_hash] = [key_value]
return True
else:
#checkin for update ...
for pair in self.map[key_hash]:
if pair[0] = key:
pair[1] = value
return True
self.map[key_hash].append(key_value)
return True
def get(self,key):
key_hash = self._get_hashed(key)
if self.map[key_hash] is not None:
for pair in self.map[key_hash]:
if pair[0] == key:
return pair[1]
raise keyError(str(key))
def delete(self,key):
key_hash = self._get_hashed(key)
if self.map[key_hash] is None:
raise keyError(str(key))
for pair in range(0,len(self.map[key_hash])):
if self.map[key_hash][i][0] == key:
self.map[key_hash].pop(i)
return True
def __str__(self):
ret = ""
for i,item in enumerate(self.map):
if item is not None:
ret += str(i) + ":" + str(item) + "\n"
return ret
if __name__ == '__main__':
h = Hashmap()
h.add(1 , "one")
h.add(2 , "two")
h.add("blah" , "blah-blah")
h.add("Hello" , "World")
h.add(("saad","mak","been"), "bawa")
print(h)
h.delete(2)
h.delete(("saad","mak","been"))
print(h)
|
fb2b0ad06a5c75df8db6c92d6c79040797ade439 | victorffernandes/Classes_Homework | /Swap_217031107.py | 348 | 3.96875 | 4 |
try:
x = int(input("Insira o primeiro valor: "))
y = int(input("Insira o segundo valor: "))
print("X: ", x, end="\n")
print("Y: ", y)
aux = x
x = y
y = aux
print("\n")
print("X: ", x, end="\n")
print("Y: ", y)
except ValueError:
print("Valor não pode ser convertido para número! Tente novamente!")
|
a4a069a9c965f34ebdab52ed9dbe56bab514d450 | Edward-Becerra/Cuemby-Backend-Test | /algorithm.py | 1,472 | 3.984375 | 4 | """
Escriba un programa para verificar si una matriz se puede dividir en una posición
tal que la suma del lado izquierdo de la división sea igual a la suma del
lado derecho.
"""
from random import randint
print("Digite el tamaño del arreglo : ")
t = int(input())
# list_1=[randint(1,10) for i in range(t)]
list_1 = []
for i in range(t):
valor = int(input("Ingrese un valor entero: "))
list_1.append(valor)
print(f"Su arreglo es: {list_1}")
list_1.sort()
listLeft = list_1.copy()
listRight = list_1.copy()
def sumarLista(lista):
suma = 0
for num in lista:
suma += num
return suma
def canBeSplitted(lista: list): # ->int
resultado = 0
sumLista = sumarLista(lista)
if sumLista % 2 == 0:
suma_izq = sumLista // 2
terminado = False
while not terminado:
if sumarLista(listLeft) != suma_izq:
listLeft.pop()
if sumarLista(listRight) != suma_izq:
cont = 0
listRight.pop(cont)
cont += 1
else:
terminado = True
print("************* izquierda ***********")
print(listLeft)
print("************* derecha *************")
print(listRight)
resultado = 1
return resultado
else:
print("No es posible....")
return resultado
print(
f"El resultado de intentar dividir el arreglo en dos partes es: \n{canBeSplitted(list_1)}"
)
|
36e939e2939b66c707719dc088b0e60ac2968f40 | carljhn/Assignment-3-PLD-BSCOE-1-6 | /moneyv2.py | 594 | 3.984375 | 4 | import math
def _money():
money=int(input("You have an amount of: "))
return money
def aplprc():
apl_price=int(input("An apple costs: "))
return apl_price
def maxapls():
max_apls=int(money/apl_price)
return max_apls
def getTotal():
total=apl_price * max_apls
return total
def getChange():
change=money-total
return change
def display(max_apls, change):
print(f"You can buy {max_apls} apples and your change is {change} pesos.")
money=_money()
apl_price=aplprc()
max_apls=maxapls()
total=getTotal()
change=getChange()
display(max_apls, change) |
01a6f1d35b173fcfe7587537deb3b2771ed82955 | mguomanila/programming_tests | /lesson11/count_semiprimes.py | 3,828 | 4.03125 | 4 | '''
CountSemiprimes
Count the semiprime numbers in the given range [a..b]
A prime is a positive integer X that has exactly two distinct divisors: 1 and X. The first few prime integers are 2, 3, 5, 7, 11 and 13.
A semiprime is a natural number that is the product of two (not necessarily distinct) prime numbers. The first few semiprimes are 4, 6, 9, 10, 14, 15, 21, 22, 25, 26.
You are given two non-empty arrays P and Q, each consisting of M integers. These arrays represent queries about the number of semiprimes within specified ranges.
Query K requires you to find the number of semiprimes within the range (P[K], Q[K]), where 1 ≤ P[K] ≤ Q[K] ≤ N.
For example, consider an integer N = 26 and arrays P, Q such that:
P[0] = 1 Q[0] = 26
P[1] = 4 Q[1] = 10
P[2] = 16 Q[2] = 20
The number of semiprimes within each of these ranges is as follows:
(1, 26) is 10,
(4, 10) is 4,
(16, 20) is 0.
Write a function:
def solution(N, P, Q)
that, given an integer N and two non-empty arrays P and Q consisting of M integers, returns an array consisting of M elements specifying the consecutive answers to all the queries.
For example, given an integer N = 26 and arrays P, Q such that:
P[0] = 1 Q[0] = 26
P[1] = 4 Q[1] = 10
P[2] = 16 Q[2] = 20
the function should return the values [10, 4, 0], as explained above.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [1..50,000];
M is an integer within the range [1..30,000];
each element of arrays P, Q is an integer within the range [1..N]; P[i] ≤ Q[i].
'''
from timeit import timeit
from random import randrange as r
def sieve(n):
sieve = [1] * (n+1)
sieve[0] = sieve[1] = 0
i = 2
while i*i <= n:
if sieve[i]:
k = i*i
while k <= n:
sieve[k] = 0
k += i
i += 1
return sieve
def array_factor(n):
F = [0] * (n+1)
i = 2
while i*i <= n:
if F[i] == 0:
k = i*i
while k <= n:
if F[k] == 0:
F[k] = i
k += i
i += 1
return F
def factorization(x,F):
prime_factors = []
while F[x] > 0:
prime_factors += [F[x]]
_,x = divmod(x,F[x])
prime_factors += [x]
return prime_factors
def factorization2():
def semi_primes(n,x,y):
primes = sieve(n)
f = array_factor(n)
a = set()
print(primes)
print(f)
print(my_sieve4(n))
for i in range(len(primes)):
if primes[i] and i >= x and i <= y:
b = factorization(i,f)
print(x,y,i,b)
for num in b:
a.add(num)
return len(a)
def my_sieve4(n):
sievex = sieve(n)
sievev = [a for a in range(n+1)]
ar = []
for i in range(len(sievex)):
if sievex[i]:
ar.append(sievev[i])
else: ar.append(0)
return ar
def soln1(N, P, Q):
# write your code in Python 3.6
m = len(P)
mm = len(Q)
if m != mm: raise AssertionError
#m_min = 1
#m_max = 3*10**4
#if m != len(Q) or m < m_min or m > m_max: raise AssertionError
#n_min = 1
#n_max = 5*10**4
#if N < n_min or N > n_max: raise AssertionError
a = []
for i in range(m):
if P[i] > Q[i]: raise AssertionError
a.append(semi_primes(N,P[i],Q[i]))
return a
def soln2(N,P,Q):
m = len(P)
mm = len(Q)
if m != mm: raise AssertionError
for i in range(m):
if __name__ == '__main__':
n_min = 1
n_max = 5*10**4
m_max = 3*10**4
N = r(n_min,n_max)
n_mid = N//2
P = [r(n_min,n_mid) for a in range(N)]
Q = [r(n_mid,N) for a in range(N)]
a = timeit('soln2(N, P, Q)',number=10**0,globals=locals())
b = soln2(26, [1, 4, 16], [26, 10, 20])
|
0f6ad330cc4cd190ad0604c48cfb106ec61051cd | NPettyjohn/Python | /Python_Fundamentals/multiples_sum_average.py | 343 | 4.25 | 4 |
# Multiples example.
# Print odd numbers 1 to 1000.
for i in range(1,1000):
if i % 2 != 0:
print i
# Print multiples of 5 from 5 to 1,000,000.
for i in range(5,1000000):
if i % 5 == 0:
print i
# Sum list example.
a = [1, 2, 5, 10, 255, 3]
for i in a:
print i
# Average list example.
print sum(a)/float(len(a))
|
f8eae1a655787d1738f1ec1c0f2316e2d6fd414f | noahvendrig/imgclassifier1 | /split_video.py | 1,348 | 3.78125 | 4 | '''
Using OpenCV takes a mp4 video and produces a number of images.
Requirements
----
You require OpenCV 3.2 to be installed.
Run
----
Open the main.py and edit the path to the video. Then run:
$ python main.py
Which will produce a folder called data with the images. There will be 2000+ images for example.mp4.
'''
import cv2
import numpy as np
import os
folder_list = ["data", "analysis_img", "proc_vid"]
for folder in folder_list:
try:
if not os.path.exists(folder):
os.makedirs(folder)
except OSError:
print ('Error: Creating directory of data: '+folder)
# Playing video from file:
cap = cv2.VideoCapture('example1.mp4')
try:
if not os.path.exists('data'):
os.makedirs('data')
except OSError as e:
print ('Error: Creating directory of data')
currentFrame = 0
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
if(ret == False):
break
# Saves image of the current frame in jpg file
name = './data/frame' + str(currentFrame).zfill(5) + '.jpg'
print ('Creating...' + name)
cv2.imwrite(name, frame)
# To stop duplicate images
currentFrame += 1
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
#cap = cv2.VideoCapture('video.mp4')
|
fbd40f17ede701ed1ea8bc88edd2690d7bf22901 | LeonOram/Files | /test_data_exercise.py | 784 | 4.125 | 4 | ##def get_test_results():
## test_results = []
## for test in range(3):
## test_results.append(int(input("Please enter a score: ")))
## return test_results
def average_test_result(results):
total = 0
for test in results:
test=int(test)
total += test
average = total/len(results)
return average
def display_average_result(average):
print("your average test result is: {0}".format(average))
def main():
with open("test_data.txt",mode="r",encoding="utf-8") as test_file:
#test_results = get_test_results()
test_results=[]
for line in test_file:
test_results.append(line)
average = average_test_result(test_results)
display_average_result(average)
if __name__ == "__main__":
main()
|
8b2d65b6e37940aa8c5d8b3105ef96891e17f377 | emirot/hackerrank | /algo/ChalengeExample/mergeSort/mergeSort.py | 728 | 3.78125 | 4 | __author__ = 'nolanemirot'
def merge(leftA, rightB):
result = []
ia = 0
ib = 0
while ia < len(leftA) and ib < len(rightB):
if leftA[ia] <= rightB[ib] :
result.append(leftA[ia])
ia+=1
else:
result.append(rightB[ib])
ib+=1
if leftA:
result.extend(leftA[ia:])
if rightB:
result.extend(rightB[ib:])
return result
def mergeSort(arr):
if len(arr) <= 1:
return arr
middle = int(len(arr) / 2)
left = arr[:middle]
right = arr[middle:]
left = mergeSort(left)
right = mergeSort(right)
return merge(left,right)
if __name__ == '__main__':
print(mergeSort([4,3,2,4,5,6,7,9,78,54,23,43])) |
c7ef57c151c4cb58686607d1dd209a02a8db9a80 | chaudharymanishkumar/Network-lab | /mono.py | 1,048 | 4.09375 | 4 | #Mono Alphabetic cipher Encryption and Decryption
#MKChaudhary
#26nov'19
monoalpha_cipher = {
'a': 'm',
'b': 'n',
'c': 'b',
'd': 'v',
'e': 'c',
'f': 'x',
'g': 'z',
'h': 'a',
'i': 's',
'j': 'd',
'k': 'f',
'l': 'g',
'm': 'h',
'n': 'j',
'o': 'k',
'p': 'l',
'q': 'p',
'r': 'o',
's': 'i',
't': 'u',
'u': 'y',
'v': 't',
'w': 'r',
'x': 'e',
'y': 'w',
'z': 'q',
' ': ' ',
}
def encryption(message):
encrypted_message=[]
for letter in message:
encrypted_message.append(monoalpha_cipher.get(letter,letter))
return ''.join(encrypted_message)
def decryption(message):
decrypted_message=[]
inverse_monoalpha_cipher={}
for key,value in monoalpha_cipher.iteritems():
inverse_monoalpha_cipher[value]=key
for letter in message:
decrypted_message.append(inverse_monoalpha_cipher.get(letter,letter))
return ''.join(decrypted_message)
message = raw_input("Enter the text:-")
en_data=encryption(message)
print en_data
print decryption(en_data)
|
c200be9d452f550b8e6081834c1acc3370c8df3d | hsiangyi0614/X-Village-2018-Exercise | /Lesson03-Python-Basic-two/exercise4.py | 204 | 3.9375 | 4 | #Exercise1: N^X
def number(n):
def power(x):
return n ** x
return power
n = int(input("input a number : "))
m = number(n)
x=int(input("input a power : "))
print(n,"的",x,"次方 :",m(x)) |
9700cef64df665b88ed748eeaec645f501c0a0b5 | KumarAmbuj/GEEKSFORGEEKS-DYNAMIC-PROGRAMING | /93.LARGEST SUM CONTIGUOUS ARRAY.py | 352 | 3.78125 | 4 | def findlargestsum(arr):
maxendinghere=0
maxsumsofar=0
for i in range(len(arr)):
maxendinghere+=arr[i]
if maxendinghere>maxsumsofar:
maxsumsofar=maxendinghere
elif maxendinghere<0:
maxendinghere=0
print(maxsumsofar)
a = [-2, -3, 4, -1, -2, 1, 5, -3]
findlargestsum(a) |
9f68b66bc65ae53090f8f7ec2925f154cc73de6f | remintz/programacaoemcasa | /exercicios/lista_aula_2/exercicio_4.py | 293 | 4.21875 | 4 | """
(Exercício de while ou for) Faça um programa que leia 3 números usando input e mostre a soma e a média deles.
"""
soma = 0.0
for i in range(3):
numero = float(input(f'Informe o número {i+1}: '))
soma = soma + numero
print(f'A soma é {soma}')
print(f'A média é {soma / 3}')
|
ab8a1c6802074aca2b185b57b8e08445bcf1f00d | ckallum/Daily-Coding-Problem | /solutions/#075.py | 959 | 3.75 | 4 | from collections import deque
from copy import copy
def get_len(x):
return len(x)
def longest_subsequence(numbers):
subsequences = [[numbers[0]]]
for num in numbers[1:]:
additional_sequences = []
for index, subsequence in enumerate(subsequences):
if num > max(subsequence):
subsequences[index].append(num)
else:
temp = copy(subsequence)
while num <= temp[len(temp) - 1]:
temp.pop()
temp.append(num)
if temp not in (subsequences and additional_sequences):
additional_sequences.append(temp)
subsequences.extend(additional_sequences)
subsequences = list(sorted(subsequences, key=get_len))[::-1]
return len(subsequences[0])
def main():
assert longest_subsequence([0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]) == 6
if __name__ == '__main__':
main()
|
50a4e105a56210a23276ae2244129cfb448cbb8b | andyyang777/PY_LC | /67_AddBinary.py | 1,317 | 3.75 | 4 | # Given two binary strings, return their sum (also a binary string).
#
# The input strings are both non-empty and contains only characters 1 or 0.
#
# Example 1:
#
#
# Input: a = "11", b = "1"
# Output: "100"
#
# Example 2:
#
#
# Input: a = "1010", b = "1011"
# Output: "10101"
#
#
# Constraints:
#
#
# Each string consists only of '0' or '1' characters.
# 1 <= a.length, b.length <= 10^4
# Each string is either "0" or doesn't contain any leading zero.
#
# Related Topics Math String
# 👍 2110 👎 291
# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
def addBinary(self, a: str, b: str) -> str:
M,N = len(a), len(b)
if M < N:
a = "0" * (N-M) + a
else:
b = "0" * (M-N) + b
stack1 = list(a)
stack2 = list(b)
res = ""
carry = 0
while stack1 and stack2:
s1, s2 = stack1.pop(),stack2.pop()
cursum = int(s1) + int(s2) + carry
if cursum >= 2:
cursum %= 2
carry = 1
else:
carry = 0
res = str(cursum) + res
if carry:
res = "1" + res
return res
# leetcode submit region end(Prohibit modification and deletion)
|
a7180da0486bcd21c2984cbd2f3f33a8fbcfcd1d | aalicav/Exercicios_Python | /ex040.py | 403 | 3.921875 | 4 | n1 = float(input('Digite a sua primeira nota :'))
n2 = float(input('Digite a sua segunda nota:'))
media = (n1+n2)/2
if media < 5:
print('A sua média é {:.1f} e você foi reprovado'.format(media))
elif 5.0 <= media <= 6.9:
print('A sua média é {:.1f} e você está de recuperação'.format(media))
elif media >= 7:
print('A sua média é {:.1f} e você está aprovado'.format(media))
|
c2a952c22f65a07cfdc0e6ae8d12452a3d443c6a | BerryHN/DJH-Python | /data structure/day3.py | 1,350 | 3.796875 | 4 | # coding:utf-8
from pythonds.basic.stack import Stack
class StacToQueue(object):
def __init__(self):
self.stack_one = Stack()
self.stack_two = Stack()
def enqueue(self, item):
self.stack_one.push(item)
def dequeue(self):
if self.stack_two.isEmpty():
while not self.stack_one.isEmpty():
self.stack_two.push(self.stack_one.pop())
return self.stack_two.pop()
def size(self):
return len(self.stack_one) + len(self.stack_two)
def isEmpty(self):
return self.size() == 0
class Dequeue(object):
def __init__(self):
self.items = []
def enqueueFront(self, item):
self.items.insert(0, item)
def dequeueRear(self):
return self.items.pop()
def enqueueRear(self, item):
self.items.append(item)
def dequeueFront(self):
return self.items.pop(0)
def size(self):
return len(self.items)
def isEMpty(self):
return self.items == []
def palchecker(string):
chardequeue = Dequeue()
for ch in string:
chardequeue.enqueueFront(ch)
while not chardequeue.isEMpty():
front = chardequeue.dequeueFront()
rear = chardequeue.dequeueRear()
if front != rear:
return False
return True
if __name__ == '__main__':
queue = StacToQueue()
for x in range(5):
queue.enqueue(x)
for x in range(5):
print(queue.dequeue())
print("回文判断:")
print(palchecker("123321"))
print(palchecker("124561"))
|
fc80afeb2b951fd1c173d6500da211b7e650e791 | niavivek/Python_programs | /all_files/HW4/HW4_extra_NiaVivek.py | 946 | 3.546875 | 4 | """
For extra credit, write an additional program to automatically generate the top 10 books catalog.txt from this web page (top 100 EBooks yesterday): <a href="http://www.gutenberg.org/browse/scores/top" target="_blank">http://www.gutenberg.org/browse/scores/top</a>
"""
"""
http://docs.python-guide.org/en/latest/scenarios/scrape/
"""
from lxml import html
import requests
page = requests.get('http://www.gutenberg.org/browse/scores/top')
tree = html.fromstring(page.content)
#This will create a list of buyers:
top_list = tree.xpath('//*[text()="Top 100 EBooks yesterday"]/..//ol')[2].text_content()
#This will create a list of prices
#prices = tree.xpath('//span[@class="item-price"]/text()')
#type(top_list)
all_list = top_list.split("\n")
with open('catalogtest.txt','w') as test_file:
test_file.write(top_list)
# for i in range(1,10):
# test_file.write(all_list[i])
# print('Book : ', i, all_list[i])
#print('Prices: ', prices) |
49221d5d6ff43301acd0f6dcc59932b68a7b4d40 | Toyosie/Employee-attrition-prediction-files | /wrangling_datasets.py | 1,071 | 3.796875 | 4 | #Data wrangling
#importing libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
#importing datasets and saving them as a csv file
dataset = pd.ExcelFile('study_problem.xlsx')
sheet1 = dataset.parse('Existing employees')
sheet1.to_csv('Existing_employees.csv', sep=',')
print(sheet1.head())
sheet2 = dataset.parse('Employees who have left')
sheet2.to_csv('Ex_employees.csv', sep=',')
print(sheet2.head())
#adding a new column to the datasets in order to merge them and know which employees have left and which ones have not
#sheet1['left_company'] = 0 #value '0' stands for not left
#sheet1.info()
#sheet2['left_company'] = 1 # value '1' stands for left
#sheet2.info()
#merge sheet1 and sheet 2 together for easy exploration
#data = pd.concat([sheet2,sheet1],ignore_index=True)
#data.to_csv('data.csv')
#print(data.head(10))
#after tweaking the data dataset using excel
emp_dataset = pd.read_csv('data.csv')
print(emp_dataset.info())
|
257ddd700fe20f653b3da73f1e8757e099e8249d | PauloLima87/CEVP_Desafios | /Desafio 40 - Média.py | 397 | 3.9375 | 4 | n1 = float(input('1ª Nota: '))
n2 = float(input('2ª Nota: '))
if (n1+n2)/2 >= 7:
print(f'\n{"PARABÈNS! VOCÊ FOI APROVADO":=^80}\n\nSua Média final foi: {(n1+n2)/2}')
elif (n1+n2)/2 >= 5 and (n1+n2)/2 <= 6.9:
print(f'\n{"VOCÊ ESTA DE RECUPERAÇÃO":=^80}\n\nSua Média final foi: {(n1+n2)/2}')
else:
print(f'\n{"VOCÊ ESTA REPROVADO":=^80}\n\nSua Média final foi: {(n1+n2)/2}')
|
78ff41e3d7ec171b967160fc6553cb9ed6df5099 | dlingerfelt/DSC-510-Fall2019 | /May_DSC510_Assignment3.py | 2,086 | 4.28125 | 4 | #May_DSC510_Assignment3.py
#Name: Brandon May
#Date: 9/8/19
#Course: DSC 510 - Introduction to Programming
#Descr: Purpose is to quote pricing for feet of fiber optic cable for the May company using conditional statements and booleans.
print('Welcome to the May Company')
companyname = input('What is your company name?\n')
print('Thank you for quoting your price with us', companyname)
try:
cablefeet = float((input('How many feet of fiber optic cable are you requesting to be installed?\n'))) #designating we want this as a float
except:
print('Please provide a numerical value.\n')
cablefeet = float((input('How many feet of fiber optic cable are you requesting to be installed?\n')))
#exception statement if someone enters in a non-numerical value.
#designating the different formulas for calculation as variables
cablecost1=float((cablefeet)*0.87) #$0.87 per foot up to 250 feet
cablecost2=float((cablefeet)*0.70) #$0.70 per foot up to 500 feet
cablecost3=float((cablefeet)*0.50) #$0.50 per foot greater than 500 feet
if float(cablefeet) <= 0:
print('Error. Please try again.') #want the program to end if entering a negative or zero value.
elif float(cablefeet) > 0 and float(cablefeet)<= 250.0:
print('Attached is an invoice from the May company for', companyname, 'for', cablefeet, 'feet of fiber optic cable which will cost $',cablecost1,'\n')
print('Thank you for your business!\n')
#invoice printout for up to 250 feet but >0
elif float(cablefeet) > 250.0 and cablefeet <= 500.0:
print('Attached is an invoice from the May company for', companyname, 'for', cablefeet, 'feet of fiber optic cable which will cost $',cablecost2,'\n')
print('Thank you for your business!\n')
#invoice printout for between 250 and 500 feet
elif float(cablefeet) > 500.0:
print('Attached is an invoice from the May company for', companyname, 'for', cablefeet, 'feet of fiber optic cable which will cost $',cablecost3,'\n')
print('Thank you for your business!\n')
#invoice printout for >500 feet
|
dba9a759594cf2cc9d1d40a4778c6c5c9e5d6b47 | RaghuA06/CCC-Canadian-Computing-Contest-Problems | /Waterloo J1 2015.py | 363 | 4.125 | 4 | # Raghu Alluri
# Special Day is February 18th
month = int(input())
day = int(input())
year = [month, day]
if year[0] > 2:
print('After')
elif year[0] < 2:
print('Before')
elif year[0] == 2 and year[1] == 18:
print('Special')
elif year[0] == 2 and year[1] > 18:
print('After')
elif year[0] == 2 and year[1] < 18:
print('Before')
|
793036a5518d464b386d9119aeccb6174b963e76 | Lum1naT/python | /practice/list_less_than_7.py | 182 | 3.640625 | 4 | import sys
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
result = []
for val in a:
if(val < 7):
if val not in result:
result.append(val)
print(*str(result))
|
0da5ec7be37f1bc134895b20bacb6d1acaa55d62 | zaman13/Particle-Swarm-Optimization-PSO-using-Python | /Code/pso_2D_animation_v1.py | 7,809 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 11 17:48:18 2020
@author: Mohammad Asif Zaman
Particle swarm optimization code
- General code, would work with fitness function of any dimensions (any no. of parameters)
- Vectorized fast code. Only one for loop is used to go over the iterations. Calculations
over all the dimensions and particles are done using matrix operations.
- One function call per iteration.
Tested in python 2.7.
"""
from __future__ import print_function
import time
import math
import numpy as np
import pylab as py
from matplotlib import animation, rc
from IPython.display import HTML
from matplotlib import pyplot as plt
plt.rcParams.update({'font.size': 14})
# Control parameters
w = 0.5 # Intertial weight
c1 = 2.0 # Weight of searching based on the optima found by a particle
c2 = 2.0 # Weight of searching based on the optima found by the swarm
v_fct = 0.02
Np = 60 # population size (number of particles)
D = 2 # dimension (= no. of parameters in the fitness function)
max_iter = 200 # maximum number of iterations
xL = np.zeros(D) - 15 # lower bound (does not need to be homogeneous)
xU = np.zeros(D) + 15 # upper bound (does not need to be homogeneous)
delta = 0.025
xplt = yplt = np.arange(xL[0], xU[0], delta)
X, Y = np.meshgrid(xplt, yplt)
V1 = np.exp(-3*np.square(.3*Y-.9) - 3*np.square(.3*X-1.2))
V2 = np.exp(-4*np.square(.3*Y-2.1) - 4*np.square(.3*X+1.2))
V3 = np.exp(-2*np.square(.25*Y+1) - 2*np.square(.25*X+2))
V4 = np.exp(-2*np.square(.5*Y-1.2) - 2*np.square(.5*X-2.4))
V6 = np.exp(-2*np.square(.2*Y+1.4) - 4*np.square(.2*X-1.2))
V5 = np.sin(np.square(.1*X)) + np.sin(np.square(.15*Y))
F_plt = 1.4*V1 + 0.6*V2 + 0.9*V3 - V4 + 0.05*V5 + 0.8*V6
# Fitness function. The code maximizes the value of the fitness function
def fitness(x):
# x is a matrix of size D x Np
# The position of the entire swarmp is inputted at once.
# Thus, one function call evaluates the fitness value of the entire swarm
# F is a vector of size Np. Each element represents the fitness value of each particle in the swarm
V1 = np.exp(-3*np.square(.3*x[1,:]-.9) - 3*np.square(.3*x[0,:]-1.2))
V2 = np.exp(-4*np.square(.3*x[1,:]-2.1) - 4*np.square(.3*x[0,:]+1.2))
V3 = np.exp(-2*np.square(.25*x[1,:]+1) - 2*np.square(.25*x[0,:]+2))
V4 = np.exp(-2*np.square(.5*x[1,:]-1.2) - 2*np.square(.5*x[0,:]-2.4))
V5 = np.sin(np.square(.13*x[0,:])) + np.sin(np.square(.15*x[1,:]))
V6 = np.exp(-2*np.square(.2*x[1,:]+1.4) - 4*np.square(.2*x[0,:]-1.2))
# multimodal test function
F_mult = 1.4*V1 + 0.6*V2 + 0.9*V3 - V4 +0.05*V5 + 0.8*V6
return F_mult
pbest_val = np.zeros(Np) # Personal best fintess value. One pbest value per particle.
gbest_val = np.zeros(max_iter) # Global best fintess value. One gbest value per iteration (stored).
pbest = np.zeros((D,Np)) # pbest solution
gbest = np.zeros(D) # gbest solution
gbest_store = np.zeros((D,max_iter)) # storing gbest solution at each iteration
x = np.random.rand(D,Np) # Initial position of the particles
v = np.zeros((D,Np)) # Initial velocity of the particles
x_store = np.zeros((max_iter,D,Np))
# Setting the initial position of the particles over the given bounds [xL,xU]
for m in range(D):
x[m,:] = xL[m] + (xU[m]-xL[m])*x[m,:]
# Function call. Evaluates the fitness of the initial swarms
fit = fitness(x) # vector of size Np
pbest_val = np.copy(fit) # initial personal best = initial fitness values. Vector of size Np
pbest = np.copy(x) # initial pbest solution = initial position. Matrix of size D x Np
# Calculating gbest_val and gbest. Note that gbest is the best solution within pbest
ind = np.argmax(pbest_val) # index where pbest_val is maximum.
gbest_val[0] = np.copy(pbest_val[ind]) # set initial gbest_val
gbest = np.copy(pbest[:,ind])
print("Iter. =", 0, ". gbest_val = ", gbest_val[0])
print("gbest_val = ",gbest_val[0])
x_store[0,:,:] = x
# Loop over the generations
for iter in range(1,max_iter):
r1 = np.random.rand(D,Np) # random numbers [0,1], matrix D x Np
r2 = np.random.rand(D,Np) # random numbers [0,1], matrix D x Np
v_global = np.multiply(((x.transpose()-gbest).transpose()),r2)*c2*(-1.0) # velocity towards global optima
v_local = np.multiply((pbest- x),r1)*c1 # velocity towards local optima (pbest)
v = w*v + v_local + v_global # velocity update
x = x + v*v_fct # position update
fit = fitness(x) # fitness function call (once per iteration). Vector Np
# pbest and pbest_val update
ind = np.argwhere(fit > pbest_val) # indices where current fitness value set is greater than pbset
pbest_val[ind] = np.copy(fit[ind]) # update pbset_val at those particle indices where fit > pbest_val
pbest[:,ind] = np.copy(x[:,ind]) # update pbest for those particle indices where fit > pbest_val
# gbest and gbest_val update
ind2 = np.argmax(pbest_val) # index where the fitness is maximum
gbest_val[iter] = np.copy(pbest_val[ind2]) # store gbest value at each iteration
gbest = np.copy(pbest[:,ind2]) # global best solution, gbest
gbest_store[:,iter] = np.copy(gbest) # store gbest solution
print("Iter. =", iter, ". gbest_val = ", gbest_val[iter]) # print iteration no. and best solution at each iteration
x_store[iter,:,:] = x
# Plotting
py.close('all')
py.figure(1)
py.plot(gbest_val)
py.xlabel('iterations')
py.ylabel('fitness, gbest_val')
py.figure(2)
py.plot(gbest_store[1,:],'r')
py.xlabel('iterations')
py.ylabel('gbest[1,iter]')
#py.figure()
#py.plot(x_store[0,0,:],x_store[0,1,:],'o')
#py.xlim(xL[0],xU[0])
#py.ylim(xL[1],xU[1])
#
#py.figure()
#py.plot(x_store[max_iter-1,0,:],x_store[max_iter-1,1,:],'o')
#py.xlim(xL[0],xU[0])
#py.ylim(xL[1],xU[1])
fig = plt.figure()
ax = plt.axes(xlim=(xL[0], xU[0]), ylim=(xL[1],xU[1]),xlabel = 'x', ylabel= 'y')
#line, = ax.plot([], [], lw=2,,markersize = 9, markerfacecolor = "#FDB813",markeredgecolor ="#FD7813")
line1, = ax.plot([], [], 'o',color = '#d2eeff',markersize = 3, markerfacecolor = '#d2eeff',lw=0.1, markeredgecolor = '#0077BE') # line for Earth
time_template = 'Iteration = %i'
time_string = ax.text(0.05, 0.9, '', transform=ax.transAxes,color='white')
#ax.get_xaxis().set_ticks([]) # enable this to hide x axis ticks
#ax.get_yaxis().set_ticks([]) # enable this to hide y axis ticks
# initialization function: plot the background of each frame
def init():
line1.set_data([], [])
im2 = ax.contourf(X,Y,F_plt,40, cmap = 'plasma')
# fig.colorbar(im2, ticks=[0, .3, .6, 1])
time_string.set_text('')
return line1, time_string
# animation function. This is called sequentially
def animate(i):
# Motion trail sizes. Defined in terms of indices. Length will vary with the time step, dt. E.g. 5 indices will span a lower distance if the time step is reduced.
line1.set_data(x_store[i,0,:], x_store[i,1,:]) # marker + line of first weight
# contourf(X,Y,F_plt)
time_string.set_text(time_template % (i))
return line1, time_string
v_fps = 20.0
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=max_iter, interval=1000.0/v_fps, blit=True)
anim.save('pso_slow_animation.mp4', fps=v_fps, extra_args=['-vcodec', 'libx264'])
|
295454baba1d84032add0b4f5e0f18388202c081 | giridhararao/new | /string without repeated.py | 145 | 3.515625 | 4 | i=input()
b=[]
c=[]
for j in range(0,len(i)):
b.append(i[j])
e=[]
for j in b:
if j not in e:
e.append(j)
print("".join(e))
|
83a720ab2fb445e5036ff56220d91ed1423f0d35 | glenonmateus/ppe | /secao7/counter.py | 1,522 | 4.03125 | 4 | """
Módulo Collections - Counter (contador)
Collection -> High-performance Container Datetypes
Counter -> Recebe um interável como parâmetro e cria um objeto do tipo collection counter que é parecido
com um dicionário, contendo como chave o elemento da lista passada como parâmetro e como valor a quantidade
de ocorrências desse elemento.
# Exemplo 1
# Podemos utilizar qualquer iterável, aqui usamos uma lista
lista = [1, 1, 1, 2, 2, 3, 3, 3, 1, 1, 2, 2, 4, 4, 5, 5, 5, 5, 3, 45, 45, 66, 66, 43, 34]
# Utilizando o Counter
res = Counter(lista)
print(type(res))
print(res)
# Veja que, para cada elemento da lista, o Counter criou um chave e colocou como valor a quantidade de ocorrências.
# Exemplo 2
print(Counter('Geek University'))
"""
# Realizando o import
from collections import Counter
# Exemplo 3
texto = """A Wikipédia é um projeto de enciclopédia colaborativa, universal e multilíngue estabelecido na internet sob
o princípio wiki. Tem como propósito fornecer um conteúdo livre, objetivo e verificável, que todos possam editar e
melhorar. O projeto é definido pelos princípios fundadores. O conteúdo é disponibilizado sob a licença Creative
Commons BY-SA e pode ser copiado e reutilizado sob a mesma licença — mesmo para fins comerciais — desde que
respeitando os termos e condições de uso."""
palavras = texto.split()
# print(palavras)
res = Counter(palavras)
print(res)
# Encontrando as 5 palavras com mais ocorrência no texto
print(res.most_common(5))
|
82ef0d5d2cb66dd44d213af05dea38e0b1991b62 | robertggovias/robertgovia.github.io | /python/cs241/w10/list/list.py | 3,000 | 4.59375 | 5 | fish = ['barracuda','cod','devil ray','eel']
fish.append('flounder')
print("append: ", fish)
fish.insert(0,"anchovi")
print("inserted achovi: ", fish)
more_fish = ['goby','herring','ide','kissing gourami']
fish.extend(more_fish)
print("extended a new list: ", fish)
fish.remove('kissing gourami')
print("removed kissing gourami: ",fish)
print(fish.pop(3))
print("pop index 3 (devil ray): ", fish)
print("take the index of an item of the list (herring): ",fish.index('herring'))
copy_of_fish = fish.copy()
print("copy of the list: ",copy_of_fish)
fish.reverse()
print("The list ordered backward: ",fish)
fish.append("cod")
how_many = fish.count("cod")
print("The amount of times that 'cod' appear on the list: ",how_many)
fish_ages = [1,2,4,3,2,1,1,2]
print("How many times a fish with age one we have: ",fish_ages.count(1))
fish_ages.sort()
print("Ordered list of fish's ages: ",fish_ages)
fish.clear()
print("There is no thing on the list: {}\nDid you see?".format(fish))
print("More about lists, the second part:\n---------------------------------------------------------------------------------------------\n Accessing Characters by Positive Index Number")
ss = "Sammy Shark!"
th5 = ss[4]
print("The fifth letter of frase 'Sammy Shark': {}".format(th5))
print("\nAccessing Characters by Negative Index Number")
th_4 = ss[-4]
print("The fourth last letter of frase 'Sammy Shark': {}".format(th_4))
print("\nSlicing Strings")
sliced = ss[6:11]
print("Elements from the 7th to 11th, this is sliced: ", sliced)
sliced_first = ss[:5]
sliced_last = ss[7:]
print("Taking everything from the end, {}\n and everything from the begining {}".format(sliced_first,sliced_last))
print("\nAlso with negative numbers")
sliced_negative = ss[-6:-1]
print("but takes from the last word, like from the right", sliced_negative)
print("\nSpecifying Stride while Slicing Strings")
each_second = ss[:11:2]
print("Now, each pair indexed letter: ", each_second)
inversed = ss[::-1]
print("An interesting way to print backward with each negative number (in that order)",inversed)
how_many_items = len(ss)
print('\nHow long or how many letters the word "{}" has?\n {}'.format(ss,how_many_items))
print("\nYes, we have str.count para contar cuantas veces aparece una palabra")
likes = "Sammy likes to swim in the ocean, likes to spin up servers, and likes to smile."
print("how many likes the frase :{}".format(likes))
print(likes.count("likes"))
print("\nReturn the index of a word, finding it")
print("which number is the 'm' on Sammy",ss.find("m"))
print('\nYes, again str. returns, now with finds')
print("which number is the first 'likes' on the frase\n",likes.find("likes"))
print("\nStarting to find at a especifinc index")
secondLike = likes.find("likes",likes.find("likes")+len("likes")+1)
print("which number is the second 'likes' on the frase\n",secondLike)
print("find also works with rage (the third parameter( , ,x)) from backward if the parameter is negative")
print(likes.find("likes", 40, -6))
|
b8caf72ce03c9851ac38d5d35bf63601af83e8d8 | urstkj/Python | /math/pi.py | 988 | 3.890625 | 4 | #!/usr/local/bin/python
#-*- coding: utf-8 -*-
# PI = 4 * (1 / 1 - 1 / 3 + 1 / 5 - 1 / 7 + ...)
def pi(n):
i = 0
num = 1.0
sum = 0
while i < n:
sum += (-1) ** i * (1.0 / num)
i += 1
num += 2
return sum * 4
def pi_new(n):
y = n * 2
list1 = [1 / x for x in range(1, y, 4)]
list2 = [-1 / x for x in range(3, y, 4)]
return (sum(list1) + sum(list2)) * 4
def pi_new2(n):
list = [(-1) ** (x + 1) * (1.0 / (x * 2 - 1)) for x in range(1, n)]
return sum(list) * 4
NUM = 1000000
i = NUM
print("calculating...using pi")
while i <= NUM + 10:
print(("n: " + str(i) + " -> pi: " + str(pi(i))))
i += 1
print("done.")
i = NUM
print("calculating...using pi_new")
while i <= NUM + 10:
print(("n: " + str(i) + " -> pi: " + str(pi_new(i))))
i += 1
print("done.")
i = NUM
print("calculating...using pi_new2")
while i <= NUM + 10:
print(("n: " + str(i) + " -> pi: " + str(pi_new2(i))))
i += 1
print("done.")
|
2c4374b1aca3c59fe38134b9aa040fd668b3f70c | rcalix1/Deep-learning-ML-and-tensorflow | /TensorFlow2.0/general_examples/basics/activation_functions.py | 3,578 | 3.5 | 4 | ## activation functions
#############################################################
import numpy as np
import tensorflow as tf
#############################################################
X = np.array([1, 1.4, 2.5])
w = np.array([0.4, 0.3, 0.5])
#############################################################
def net_input(X, w):
return np.dot(X, w)
############################################################
def logistic(z):
return 1.0 / ( 1.0 + np.exp(-z) )
#############################################################
def logistic_activation(X, w):
z = net_input(X, w)
return logistic(z)
#############################################################
print('P(y=1|x) = %.3f' % logistic_activation(X, w) )
#############################################################
## now multi-class
## W: shape=(,)
## dot(X, W) = [1 x 4] * [4 x 3] = [1 x 3]
W = np.array( [[ 1.1, 1.2, 0.8, 0.4],
[ 0.2, 0.4, 1.0, 0.2],
[ 0.6, 1.5, 1.2, 0.7]] )
A = np.array( [[1, 0.1, 0.4, 0.6]])
z = np.dot(W, A[0])
y_probas = logistic(z)
print( 'Net input: \n', z )
print( 'Output units: \n', y_probas)
#############################################################
## or the correct way to do this
print("***********************************************")
print("or the correct way with transpose ...")
W_transpose = np.transpose(W)
z_tra = np.dot(A, W_transpose)
y_probas_tra = logistic(z)
print( 'Net input: \n', z_tra )
print( 'Output units: \n', y_probas_tra)
#############################################################
## pick the max val
y_class = np.argmax(z, axis=0) ## selects index of max value
print(y_class)
y_class = np.argmax(z_tra[0], axis=0) ## selects index of max value
print(y_class)
#############################################################
## the softmax
## softmax = (e**z) / sum(e**z)
def softmax(z):
return np.exp(z) / np.sum( np.exp(z) )
#############################################################
y_probas_softmax = softmax(z)
print("softmax results")
print(y_probas_softmax)
print(np.sum(y_probas_softmax))
#############################################################
## now in tensorflow
print(z)
z_tensor = tf.expand_dims(z, axis=0)
print(z_tensor)
#############################################################
## softmax
z_tensor_softmax = tf.keras.activations.softmax(z_tensor)
print("softmax ")
print(z_tensor_softmax)
#############################################################
## tanh
z_tensor_tanh = tf.keras.activations.tanh(z_tensor)
print("tanh [-1, +1]")
print(z_tensor_tanh)
#############################################################
## sigmoid
z_tensor_sigmoid = tf.keras.activations.sigmoid(z_tensor)
print("sigmoid range [0, 1]")
print(z_tensor_sigmoid)
#############################################################
## RELU
## RELU improves on the vanishing gradients problem
## weights are not learned efficiently
## relu --> theta(z) = max(0, z)
## RELU is still non-linear
z_tensor_relu = tf.keras.activations.relu(z_tensor)
print("relu range [0, +infinity]")
print(z_tensor_relu)
############# other example
print("***********************************************")
other_z = np.array([1.76, -2.4, 1.46])
other_z_tensor = tf.expand_dims(other_z, axis=0)
print(other_z_tensor)
z_tensor_relu = tf.keras.activations.relu(other_z_tensor)
print("relu range [0, +infinity]")
print(z_tensor_relu)
#############################################################
print("<<<<<<<<<<<<<<<<<DONE>>>>>>>>>>>>>>>>>>")
|
6fffbb8fa7bdb216cc4b9af704dda445d8039658 | antweer/learningcode | /intro2python/plotting/playagain2.py | 305 | 3.859375 | 4 | #!/usr/bin/env python3
def playagain():
while True:
answer = input("Do you want to play again(Y or N)?").lower()
if answer == "y":
return True
break
elif answer == "n":
return False
break
else:
print("Invalid input.")
continue
if __name__ == "__main__":
print(playagain())
|
f6a11e69e348eac50c8dc2d0a498f20f9634ca05 | osmansanteliz/Python | /bucleFor.py | 379 | 3.859375 | 4 | semana = ['lunes', 'martes', 'miercoles', 'jueves', 'viernes']
for dia in semana:
print(dia)
cantidad = int(input('Digite la Cantidad de Personas:\n'))
nombre = []
salario = []
for x in range(cantidad):
nom = str(input('Ingrese su Nombre:\n'))
nombre.append(nom)
sueldo = float(input('Ingrese su Salario:\n'))
salario.append(sueldo)
print(nombre) |
17f05cbb35179a2373cc47591b7d325f8d798617 | AnishHemmady/Data-Struct-Python | /quicksrt.py | 758 | 3.640625 | 4 | '''
Quicksort
'''
import pdb
def partn(a,strt,end):
#pdb.set_trace()
pivt=a[end]
k=strt
for m in range(strt,end):
if a[m]<=pivt:
a[m],a[k]=a[k],a[m]
k+=1
a[k],a[end]=a[end],a[k]
return k
def quicksort(inp,strty,endy):
#pdb.set_trace()
if strty<endy:
indx=partn(inp,strty,endy)
quicksort(inp,strty,indx-1)
quicksort(inp,indx+1,endy)
return inp
arry=[2,1,0,8,9,4,3]
print quicksort(arry,0,len(arry)-1)
'''
O(N)
'''
def k_smllst(arry,strty,endy,fnd):
if fnd>0 and fnd<=endy-strty+1:
indx=partn(arry,strty,endy)
if indx-strty==fnd-1:
return arry[indx]
elif indx-strty>fnd-1:
return k_smllst(arry,strty,indx-1,fnd)
else:
return k_smllst(arry,indx+1,endy,fnd-indx+strty-1)
print k_smllst(arry,0,len(arry)-1,6) |
9a5197e465ea046034438fb9c7ce74814b26be43 | green-fox-academy/Komaxor | /week2/tue/tic_tac_toe.py | 5,679 | 3.953125 | 4 | p1 = " "
p2 = " "
p3 = " "
p4 = " "
p5 = " "
p6 = " "
p7 = " "
p8 = " "
p9 = " "
mark = " "
# draws map
def draw_map(p1, p2, p3, p4, p5, p6, p7, p8, p9):
for i in range (0, 9):
if i == 1:
print(" " + p1 + " | " + p2 + " | " + p3 + " ")
elif i == 4:
print(" " + p4 + " | " + p5 + " | " + p6 + " ")
elif i == 7:
print(" " + p7 + " | " + p8 + " | " + p9 + " ")
elif i == 2 or i == 5:
print("_____|_____|_____")
else:
print(" | | ")
#player input
def x_input(p1, p2, p3, p4, p5, p6, p7, p8, p9):
while True:
try:
x = int(input("Which row do you want to place your figure: 1, 2 or 3? "))
except ValueError:
print("That is definitely not 1, 2 or 3!")
continue
if x > 3:
print("1, 2 or 3?")
continue
else:
return x
def x_validate():
x = x_input(p1, p2, p3, p4, p5, p6, p7, p8, p9)
if x == 1:
print("Great!")
x = 3
elif x == 2:
print("Awesome!")
x = 9
elif x == 3:
print("Cool!")
x = 15
return x
def y_input(p1, p2, p3, p4, p5, p6, p7, p8, p9):
while True:
try:
y = int(input("Which column do you want to place your figure: 1, 2 or 3? "))
except ValueError:
print("That is definitely not 1, 2 or 3!")
continue
if y > 3:
print("1, 2 or 3?")
continue
else:
return y
def y_validate():
y = y_input(p1, p2, p3, p4, p5, p6, p7, p8, p9)
if y == 1:
print("Excellent!")
y = 2
elif y == 2:
print("You rock!")
y = 5
elif y == 3:
print("Superb!")
y = 8
return y
#switch players
def change_turn(player1_turn):
player1_turn = not player1_turn
return player1_turn
def change_mark(player1_turn):
if player1_turn:
mark = "X"
else:
mark = "O"
return mark
#place mark
def place_mark(p1, p2, p3, p4, p5, p6, p7, p8, p9, mark):
mark = change_mark(player1_turn)
while True:
x = x_validate()
y = y_validate()
if x == 3 and y == 2:
if p1 != " ":
print("That is already taken! Try again!")
continue
else:
p1 = mark
break
elif x == 3 and y == 5:
if p2 != " ":
print("That is already taken! Try again!")
continue
else:
p2 = mark
break
elif x == 3 and y == 8:
if p3 != " ":
print("That is already taken! Try again!")
continue
else:
p3 = mark
break
elif x == 9 and y == 2:
if p4 != " ":
print("That is already taken! Try again!")
continue
else:
p4 = mark
break
elif x == 9 and y == 5:
if p5 != " ":
print("That is already taken! Try again!")
continue
else:
p5 = mark
break
elif x == 9 and y == 8:
if p6 != " ":
print("That is already taken! Try again!")
continue
else:
p6 = mark
break
elif x == 15 and y == 2:
if p7 != " ":
print("That is already taken! Try again!")
continue
else:
p7 = mark
break
elif x == 15 and y == 5:
if p8 != " ":
print("That is already taken! Try again!")
continue
else:
p8 = mark
break
elif x == 15 and y == 8:
if p9 != " ":
print("That is already taken! Try again!")
continue
else:
p9 = mark
break
return(p1, p2, p3, p4, p5, p6, p7, p8, p9)
#check for win
def win(p1, p2, p3, p4, p5, p6, p7, p8, p9, game_over):
if p1 == p2 == p3 != " " or p4 == p5 == p6 != " " or p7 == p8 == p9 != " " or p1 == p4 == p7 != " " or p2 == p5 == p8 != " " or p3 == p6 == p9 != " " or p1 == p5 == p9 != " " or p3 == p5 == p7 != " ":
if player1_turn:
game_over = True
print("Player 1 won! YAAAY")
else:
game_over = True
print("Player 2 won! Congratulations!")
return game_over
#the game
while True:
print("Mark: Welcome to the Tic-Tac-Toe game! Let's play!")
player1_turn = True
game_over = False
draw_map(p1, p2, p3, p4, p5, p6, p7, p8, p9)
for i in range (0,9):
if i % 2 == 0:
print("Player 1's turn!")
else:
print("Player 2's turn!")
(p1, p2, p3, p4, p5, p6, p7, p8, p9) = place_mark(p1, p2, p3, p4, p5, p6, p7, p8, p9, mark)
draw_map(p1, p2, p3, p4, p5, p6, p7, p8, p9)
game_over = win(p1, p2, p3, p4, p5, p6, p7, p8, p9, game_over)
if game_over == True:
break
if i == 8:
print("No more places! It is a tie!")
break
player1_turn = change_turn(player1_turn)
restart = str(input("Play again? "))
if restart.lower().startswith("y"):
p1 = " "
p2 = " "
p3 = " "
p4 = " "
p5 = " "
p6 = " "
p7 = " "
p8 = " "
p9 = " "
mark = " "
continue
else:
print("Bye")
break
|
9774c03b170eb9e2c1ae8994db74758ed96c3eb1 | Galyndo/MetodosNumericos | /numpyMatrices.py | 1,716 | 4.25 | 4 | import numpy as np
# Python no posee un tipo incorporado de datos para manejar matrices
# por lo que en general se utilizan listas de listas para el manejo
# de matrices
A = [[1, 4, 5, 12],
[-5, 8, 9, 0],
[-6, 7, 11, 19]]
# NOTA: Se debe recordar que las listas en Python inician en el índice 0
# Imprimir la matriz
print("A = ", A)
# Imprimir la segunda fila
print("A[1] = ", A[1])
# Tercer elemento de la segunda fila
# Se maneja [fila][columna]
print("A[1][2] = ", A[1][2])
# También hay que recordar que se puede utilizar índices negativos
# Último elemento de la primera fila
print("A[0][-1] = ", A[0][-1])
#%%
# Asignar una columna de la matriz a una lista
# Se genera una lista vacía
columna = []
# Ahora se recorre sobre toda la lista
for fila in A:
# Añadir los valores a la lista generada
columna.append(fila[2])
# Observar que sucede si se imprime la variable fila
print(fila)
print("3er columna = ", columna)
#%%
# Esto indica que se puede recorrer sobre toda la matriz o revisar elemento
# por elemento
for fila in A:
for columna in fila:
print(" * ", columna)
#%%
# Convertir a un arreglo numpy y del tipo flotante
A2 = np.array(A, dtype = float)
# Verificar
type(A2)
# Así ya se puede hacer operaciones
A3 = A2 + A2
print(A3)
print("")
# Ahora mostrar una de las filas
print(A3[0])
print("")
# Mostrar una de las columnas
print(A3[:,0])
print("")
# Una forma de obtener una submatriz
print(A3[1:3, 1:3])
print("")
# Generar un vector
B = np.array([0, 1, 2])
B2 = np.array([0, 1, 2, 3])
# Añadirlo como vector columna a la matriz
A4 = np.c_[A2, B]
# Mostrar
print(A4)
|
e36eb18ba505173792da5770f1ef72a687b1e9cb | iamkissg/nowcoder | /algorithms/coding_interviews/09_frog_jump_1_recursively.py | 490 | 3.78125 | 4 | # -*- coding:utf-8 -*-
"""运行超时:您的程序未能在规定时间内运行结束,请检查是否循环有错或算法复杂度过大。"""
class Solution:
def jumpFloor(self, number):
# write code here
if number == 1:
return 1
elif number == 2:
return 2
elif number > 2:
return self.jumpFloor(number-1)+self.jumpFloor(number-2)
if __name__ == "__main__":
sol = Solution()
print(sol.jumpFloor(10)) |
355c8c71fa7dc56b3eaa13b14210abaffb51ee59 | Hrushikesh-github/python_notes | /get_set_has_attr.py | 442 | 4.375 | 4 | class Person:
age = 23
name = 'Adam'
person = Person()
print('Person has age?:', hasattr(person, 'age'))
print('Person has salary?:', hasattr(person, 'salary'))
#The hasattr() method returns true if an object has the given named attribute and false if it does not.
#hasattr(object, name)
print('Person age is', getattr(person,'age'))
setattr(person,'gender','male')
print("gender is ",getattr(person,'gender'))
print(person.gender)
|
da5fde616d15e19edec3ee8a608491898f86511b | VictorCastao/Curso-em-Video-Python | /Desafio79.py | 401 | 3.9375 | 4 | print('=' * 12 + 'Desafio 79' + '=' * 12)
resp = 'S'
lista = []
while resp == 'S':
a = int(input("Digite um valor: "))
if a in lista:
print("Número não adicionado (já existente na lista)!")
else:
lista.append(a)
print("Número adicionado!")
resp = input("Deseja continuar[S/N]? ").strip().upper()
lista.sort()
print(f"Os números digitados foram:\n{lista}")
|
7696e7389a5128fb879f398c87c5adb2771e2fb6 | vladcipariu91/DSA-Problems | /chapter_3/graphs/dfs_iterative.py | 1,361 | 3.734375 | 4 | class GraphNode(object):
def __init__(self, val):
self.value = val
self.children = []
def add_child(self, new_node):
self.children.append(new_node)
def remove_child(self, del_node):
if del_node in self.children:
self.children.remove(del_node)
class Graph(object):
def __init__(self, node_list):
self.nodes = node_list
def add_edge(self, node1, node2):
if (node1 in self.nodes and node2 in self.nodes):
node1.add_child(node2)
node2.add_child(node1)
def remove_edge(self, node1, node2):
if (node1 in self.nodes and node2 in self.nodes):
node1.remove_child(node2)
node2.remove_child(node1)
node0 = GraphNode(0)
node1 = GraphNode(1)
node2 = GraphNode(2)
node3 = GraphNode(3)
graph = Graph([node0, node1, node2, node3])
graph.add_edge(node0, node1)
graph.add_edge(node1, node2)
graph.add_edge(node1, node3)
graph.add_edge(node2, node3)
def dfs_search(root_node, search_value):
visited = []
stack = [root_node]
while len(stack) > 0:
current_node = stack.pop()
visited.append(current_node)
if current_node.value == search_value:
return current_node
for child in current_node.children:
if child not in visited:
stack.append(child)
|
cf29c017e640284c93c5e14c1aa46340d15b79ee | armandyam/euler_projects | /py/euler_24.py | 685 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "Ajay Rangarajan, Jeyashree Krishnan"
__email__ = "rangarajan, [email protected]"
import numpy as np
import math as math
from decimal import *
import itertools
dig = 10
a = list(itertools.permutations(range(dig), dig))
print a[999999]
"""
A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
012 021 102 120 201 210
What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
"""
|
576fdece59690fceb8c5f0e93724f1809d7aead0 | spuliz/Python | /test2/codeacademy.py | 258 | 3.5625 | 4 | my_list = [i**2 for i in range(1,11)]
# Generates a list of squares of the numbers 1 - 10
f = open("output.txt", "w")
for item in my_list:
f.write(str(item) + "\n")
f.close()
# with
with open("text.txt", "w") as my_file:
my_file.write("Success!")
|
0dca16f2c1c7968c346377d1d886224d24110f36 | cph-ms782/pythonSemProject | /utils/old/PDFutils.py | 1,082 | 3.5 | 4 | import PyPDF2
def read_pdf(address):
"""
convert data into text
TODO lav open with ressources så den lukker ressourcen selv
Done- merge to pageObjects til een med mergePage, https://pythonhosted.org/PyPDF2/PageObject.html#PyPDF2.pdf.PageObject
"""
# creating a pdf file object
pdfFileObj = open(address, "rb")
# creating a pdf reader object
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
if pdfReader==-1:
print("Couldn't find file")
return False
# printing number of pages in pdf file
print("pdfReader.numPages", pdfReader.numPages)
# lav een eller flere page objects
counter=2
if pdfReader.numPages==1:
pageObj = pdfReader.getPage(0)
else:
pageObj = pdfReader.getPage(0)
while counter <= pdfReader.numPages:
pageObjTemp = pdfReader.getPage(counter-1)
pageObj.mergePage(pageObjTemp)
counter+=1
# extracting text from page
data = pageObj.extractText()
# closing the pdf file object
pdfFileObj.close()
return data |
8875103ae20b8817f92ad8acfcdcfeed15dff846 | erx00/modified-lsb | /lsb.py | 1,912 | 3.828125 | 4 | from utils import str_to_binary, binary_to_str
from utils import int_to_binary, binary_to_int
def encode_lsb(image, message):
"""
Converts the input message into binary and encodes it
into the input image using the least significant bit
algorithm.
:param image: (ndarray) cover image (supports grayscale
and RGB)
:param message: (str) message
:return: (ndarray) stego image
"""
message += '<EOS>'
bits = str_to_binary(message)
nbits = len(bits)
if len(image.shape) == 2:
image = image.reshape((image.shape[0], image.shape[1], 1))
nrows, ncols, nchannels = image.shape
for i in range(nrows):
for j in range(ncols):
for c in range(nchannels):
pos = ncols * nchannels * i + nchannels * j + c
if pos < nbits:
b = int_to_binary(int(image[i, j, c]))
b.set(bits[pos], -1)
image[i, j, c] = binary_to_int(b)
else:
return image
return image
def decode_lsb(image):
"""
Decodes message from input image using the least
significant bit algorithm.
:param image: (ndarray) stego image (supports grayscale
and RGB)
:return: (str) message
"""
if len(image.shape) == 2:
image = image.reshape((image.shape[0], image.shape[1], 1))
nrows, ncols, nchannels = image.shape
bits, message = [], ""
for i in range(nrows):
for j in range(ncols):
for c in range(nchannels):
bits.append(int_to_binary(int(image[i, j, c]))[-1])
pos = ncols * nchannels * i + nchannels * j + c
if pos % 8 == 7:
message += binary_to_str(bits)
bits = []
if message[-5:] == '<EOS>':
return message[:-5]
return message
|
d325c9bbcc2408ee6012032326bb7fa34c5df072 | ziadawn/codeguild-class | /Python Assignments/Week 1 Python/lab7-random-password.py | 752 | 3.859375 | 4 | '''
lab 7, a code that generates a random password, of N length input by user, from a bucket of characters and special characters
other variation to try:
asking how many of each kind of things I need (capitals, numbers, special characters
'''
import random
#these are split so I could ask for each part separately, but is overkill as currently written
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyz0123456789'
special_characters = '!@#$%&'
bucket = alphabet + special_characters #combines above strings
pw_need = input("How many characters do you need? ")
pw_need = int(pw_need) #convert string to int
i = 0
n = pw_need
password = '' #empty variable
while i < n:
password += random.choice(bucket)
i = i + 1
print(password) |
6aaff990c7f8c7ae33248225d6937fd7cd45ba63 | ncux/Python---2017-August | /List Comprehensions Example 3.py | 122 | 3.75 | 4 | letters = 'abcd'
numbers = range(4)
myList = [(letter,number) for letter in letters for number in numbers]
print(myList)
|
81948d7d010e7b7bdbe91f9490dd14cdbdf2d500 | mayur2402/python | /pattern.py | 751 | 3.890625 | 4 | '''
accept input from user and display below pattern
input : 4 4
output : * * * # 1,1 1,2 1,3 1,4 2 3 4 5
* * # * 2,1 2,2 2,3 2,4 3 4 5 6
* # * * 3,1 3,2 3,3 3,4 4 5 6 7
# * * * 4,1 4,2 4,3 4,4 5 6 7 8
'''
class Pattern:
def __init__(self,Row,Col):
self.Row = Row
self.Col = Col
def Display_Pattern(self):
for i in range(self.Row):
for j in range(self.Col):
if(i+j != self.Col-1):
print("*\t",end = "")
else:
print("#\t",end = "")
print("\n")
iRow = int(input("\nHow many rows\t"))
iCol = int(input("\nHow many columns\t"))
if(iRow != iCol or iRow == 0 or iCol ==0):
print("Error : Invalid Argument")
else:
Pobj = Pattern(iRow,iCol)
Pobj.Display_Pattern()
|
5ced3d1534c13dbefa2865702f940496c8019cb5 | alexanderfranca/keggimporter | /keggimporter/AnendbFileSystem.py | 6,681 | 3.734375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
import shutil
import pprint
class AnendbFileSystem:
def fileExists( self, file_path=None ):
"""
Test if the file path exists.
Args:
file_path(str): Path of the file.
Returns:
(boolean)
"""
try:
if os.path.exists( file_path ):
return True
else:
return False
except:
print( 'Could not test the file' )
def directoryExists( self, directory_path=None ):
"""
Test if the directory exists.
Args:
directory_path(str): Path of the directory.
Returns:
(boolean)
"""
try:
if os.path.exists( directory_path ):
return True
else:
return False
except:
print( 'Could not test the directory.' )
def isDirectory( self, directory_path ):
"""
Test if the path is a valid directory.
Args:
directory_path(str): Path of the directory.
Returns:
(boolean)
"""
try:
if os.path.isdir( directory_path ):
return True
else:
return False
except:
print( 'Coult not test if directory is valid.' )
def isFile( self, file_path=None ):
"""
Test if the path is actual a file.
Args:
file_path(str): File path.
Returns:
(boolean)
"""
try:
if os.path.isfile( file_path ):
return True
else:
return False
except:
print( "Could not test the file." )
def isValidFile( self, file_path=None ):
"""
Validates if the file exists and it's a valid file.
Args:
file_path(str): File path.
Returns:
(boolean)
"""
if self.isFile( file_path ) and self.fileExists( file_path ):
return True
else:
raise IOError("File " + file_path + " doesn't exist, you don't have permission or not even it's a file.")
def isValidDirectory( self, directory_path=None ):
"""
Validates if the directory exists and it's a valid directory.
Args:
directory_path(str): The directory path.
Returns:
(boolean)
"""
if self.isDirectory( directory_path ) and self.directoryExists( directory_path ):
return True
else:
return False
def openFile( self, file_path=None, mode='r'):
"""
Opens a file an return its handle.
Args:
file_path(str): File Path.
mode(str): File mode ('r' = reading, 'a' = append, 'w' = writing )
Returns:
(file): File handle of the opened file.
"""
try:
f = open( file_path, mode )
return f
except:
print( 'Could not open the file: ' + file_path )
def openFileForReading( self, file_path=None ):
"""
Opens a file for reading.
Args:
file_path(str): File path.
Returns:
(file): File handle.
"""
if self.isValidFile( file_path ):
return self.openFile( file_path, 'r' )
else:
raise IOError( "File " + file_path + " couldn't be opened." )
def openFileForWriting( self, file_path=None ):
"""
Opens a file for writing.
Args:
file_path(str): File path.
Returns:
(file): File handle.
"""
return self.openFile( file_path, 'w' )
def openFileForAppend( self, file_path=None ):
"""
Opens a file for append.
Args:
file_path(str): File path.
Returns:
(file): File handle.
"""
return self.openFile( file_path, 'a' )
def closeFile( self, file_handle=None ):
"""
Simply closes a file handle.
Args:
file_handle(file): File handle to be closed.
Returns:
(boolean)
"""
# make sure the file is really closed. Is that really opened? That kind of stuff.
try:
file_handle.close()
return True
except:
print( 'Could not close the file.' )
def removeFile( self, file_path=None ):
"""
Remove a file.
Args:
file_path(str): File path.
Returns:
(boolean)
"""
if self.isValidFile( file_path ):
try:
os.remove( file_path )
return True
except:
print( 'Could not remove the file.' )
else:
print( 'Invalid file to be removed.' )
return False
def purgeAndCreateFile( self, file_path=None ):
"""
Create a file but remove previous created (if exists).
Args:
file_path(str): File path.
Returns:
(file)
"""
if self.isValidFile( file_path ):
self.removeFile( file_path )
f = self.openFileForAppend( file_path )
return f
else:
return False
def removeDirectory( self, directory_path=None ):
"""
Remove a directory.
Args:
directory_path(str). The directory path.
Returns:
(boolean)
"""
if self.isValidDirectory( directory_path ):
try:
shutil.rmtree( directory_path )
return True
except:
print( 'Could not remove the directory: ' + directory_path )
else:
return False
def getDirectoryName( self, path=None ):
"""
Return the directory path of a file path.
Args:
path(str): Full path of some file.
Returns:
(str): The directory path without the file name.
"""
if self.isValidFile( path ):
return os.path.dirname( path )
else:
return None
def getFileName( self, path=None ):
"""
Return the name of file from a full path.
Args:
path(str): Full path of some file.
Returns:
(str): The file name from the path.
"""
if self.isValidFile( path ):
return os.path.basename( path )
else:
return None
|
1ce086e01bd0d711bef2c1b5fa5a8d866c4a7955 | huozhiwei/PyQt5_RapidDevolpment | /Chapter02/py202str.py | 324 | 3.640625 | 4 | # -*- coding: utf-8 -*-
dss='hello pyqt5'
print('dss',dss)
#1
print('\n#1')
s2=dss[1:];print('s2,',s2)
s3=dss[1:3];print('s3,',s3)
s4=dss[:3];print('s4,',s4)
#2
print('\n#2')
s2=dss[-1];print('s2,',s2)
s3=dss[1:-2];print('s3,',s3)
dn=len(dss);print('dn,',dn)
#3
print('\n#3')
print('s2+s3,',s2+s3)
print('s3*2,',s3*2)
|
9b8f8f3d41e6da194338c052f94c286fc7cd4081 | Pythonyte/python-oops | /advance_formattings.py | 403 | 3.71875 | 4 | # formatting numbers
for i in range(9,11):
print('Num is {:02}'.format(i))
print('Num is {:04}'.format(i))
# format decimal precisons
pi = 3.1415667777
print('pi is {:.2f}'.format(pi))
# add commas in large numbers
money_in_bank = 100000000000000
print('Total money: {:,}'.format(money_in_bank))
"""
Num is 09
Num is 0009
Num is 10
Num is 0010
pi is 3.14
Total money: 100,000,000,000,000
""" |
ce7bc4cecf5a520b88057e42f4bccd82eb344b20 | SalihTasdelen/Hackerrank_Python | /String_Formatting.py | 319 | 4.125 | 4 | def print_formatted(number):
# your code goes here
for i in range(number):
#put i + 1 while right adjusting with the width of bin version
print('{0:>{w}d} {0:>{w}o} {0:>{w}X} {0:>{w}b}'.format(i + 1, w=len(bin(number))-2))
if __name__ == '__main__':
n = int(input())
print_formatted(n)
|
6c06a1055fcf093bc6a2e63cd3074cd98b055f2f | DIceEvYo/CECS274 | /MaxStack.py | 1,505 | 3.703125 | 4 | from Interfaces import Stack
import SLLStack
class MaxStack(Stack) :
def __init__(self):
#O(1)
self.stack = SLLStack.SLLStack()
self.maximum = None
def max(self) ->object:
'''
Returns the max element
O(1)
'''
return self.maximum
def push(self, x : object) :
'''
push: Insert an element in the tail of the stack
Inputs:
x: Object type, i.e., any object
O(1)
'''
if(self.maximum == None) or (x > self.maximum):
self.maximum = x
self.stack.push(x)
def pop(self) -> object:
'''
pop: Remove the last element in the stack
Returns: the object of the tail if it is no empty
O(1) for Pop
O(n) for finding new Max val
'''
t = self.stack.pop()
try:
if(self.maximum == t):
if(self.stack.size() != 0):
self.maximum = 0
u = self.stack.head
for i in range (0, self.stack.size()):
if((self.maximum == None) or (u.x > self.maximum)):
self.maximum = u.x
u = u.next
except: return t
return t
def size(self) -> int:
#Returns size of stack, time should be O(1)
return self.stack.size()
|
7033de535e7cda47ad485c8fd95a485373ebf219 | dimitriacosta/python-examples | /automate_the_boring_stuff/try_catch.py | 256 | 4.0625 | 4 | #!/usr/bin/env python
print('How many cats do you have?')
cats = input()
try:
if int(cats) >= 4:
print('That is a lot of cats.')
else:
print('That is not that many cats.')
except ValueError:
print('You did not enter a number.')
|
37c296e3c76ae1bde23d9731d91feb779ada7821 | irving2/leetcode | /leetcode/976. Largest Perimeter Triangle.py | 1,509 | 3.59375 | 4 | #!/usr/bin/env python
# coding=utf-8
# Project: leetcode
# Author : [email protected]
# Date : 2019/5/13
class Solution(object):
def largestPerimeter(self, A):
"""
:type A: List[int]
:rtype: int
"""
# def quick_sort(a):
# right=[]
# left=[]
# if len(a)<2:
# return a
# for e in a[1:]:
# if e>=a[0]:
# right.append(e)
# if e<a[0]:
# left.append(e)
# return quick_sort(left)+[a[0]]+quick_sort(right)
# A = quick_sort(A)
#
# curr_d = []
# while True:
# if len(curr_d)<3:
# if len(A)==0:
# break
# curr_d.append(A.pop())
# continue
# if curr_d[0]<curr_d[1]+curr_d[2]:
# return sum(curr_d)
# else:
# curr_d.pop(0)
# return 0
A=sorted(A,reverse=True)
for i,x in enumerate(A[:-2]):
if x<A[i]+A[i+1]:
return sum(A[i:i+2])
return 0
if __name__ == '__main__':
def quick_sort(a):
right = []
left = []
if len(a)<2:
return a
for e in a[1:]:
if e >= a[0]:
right.append(e)
if e < a[0]:
left.append(e)
return quick_sort(left) + [a[0]] + quick_sort(right)
print(quick_sort([3,2,5,7,1]))
|
ab227a639994b342bae7fff18bf12e4a32f5f0e5 | Navron4500/CoursesLearning | /Coding Ninjas/Classes_Files/OOPs/OOPS_1/Public_Private_Modifier_OOPS_1.py | 947 | 3.640625 | 4 |
class Student:
__passingPercentage = 40
def __init__(self,name,age=15,percentage=80):
self.__name = name
self.age = age
self.percentage = percentage
def studentDetails(self):
print("Name = ", self.__name)
print("Age =" , self.age)
print("Percentage = ", self.percentage)
def isPassed(self):
if self.percentage > Student.passingPercentage:
print("Student is passed")
else:
print("Student is not passed")
@staticmethod
def welcomeToSchool():
print("Hey! Welcome To School")
s1 = Student("Parikh")
#print(s1.__name)
#print(s1.age)
s1.age = 20
print(Student._Student__passingPercentage)
s1.studentDetails()
# s1.name = "Ankush"
# s1.age = 20
# print(s1.name)
# print(s1.age)
#s1.studentDetails()
# s1.isPassed()
# s2 = Student("Varun",26,90)
# s1.studentDetails()
# s2.studentDetails()
# s1.studentDetails()
# Student.studentDetails(s1)
# s1.isPassed()
# s1.welcomeToSchool()
#class_name.function(object_name) |
09101436a73fd02820be56dffb8878e6ecd021f9 | Zap123/REST-Lights-Out-Puzzle | /app/cellgame.py | 623 | 3.515625 | 4 | class Cellgame:
def __init__(self):
pass
def move(self, cell, grid):
cells_to_change = [cell] + cell.neighbours_cells(grid)
self.invert_cells(cells_to_change)
@classmethod
def invert_cells(cls, cells):
for cell in cells:
cell.state = 1 - cell.state
def is_game_over(self, grid):
array = []
for i in range(grid.height):
array.append([])
for j in range(grid.width):
ijl = grid.get_cell(i, j)
if ijl.state != 1:
return False
return True
|
315a592ea7ba9fcc4a8bf404c467430e62239143 | bendevera/DS-Unit-3-Sprint-2-SQL-and-Databases | /module4-acid-and-database-scalability-tradeoffs/join_practice.py | 975 | 3.890625 | 4 | import sqlite3
conn = sqlite3.connect("chinook.db")
curs = conn.cursor()
num_tracks = "SELECT COUNT(*) FROM tracks;"
print(f"Num tracks: {curs.execute(num_tracks).fetchone()[0]}")
# what tracks are in the most playlists? (top 10)
query = """
SELECT tracks.Name, albums.Title, COUNT(pt.TrackId)
FROM playlist_track as pt
LEFT JOIN tracks
ON tracks.TrackId = pt.TrackId
LEFT JOIN albums
ON tracks.AlbumId = albums.AlbumId
GROUP BY pt.TrackId
ORDER BY 2 DESC
LIMIT 10;
"""
print("--- MOST POPULAR TRACKS ---")
track_popularity = curs.execute(query).fetchall()
for track in track_popularity:
print(track)
# number of albums per artist
query = """
SELECT artists.Name, COUNT(DISTINCT albums.AlbumId)
FROM albums
LEFT JOIN artists
ON artists.ArtistId = albums.ArtistId
GROUP BY albums.ArtistId
ORDER BY 2 DESC
LIMIT 10;
"""
print("--- MOST ALBUMS PER ARTIST ---")
album_count = curs.execute(query).fetchall()
for artist in album_count:
print(artist)
curs.close() |
20801658f0d60d187416f4e2ec2e1e06ed5b3939 | zeromtmu/practicaldatascience.github.io | /2016/tutorial_final/77/scraper.py | 4,819 | 3.53125 | 4 |
# coding: utf-8
# # Web Scraper (45 pts)
# In[2]:
# setup library imports
import io, time, json
import requests
from bs4 import BeautifulSoup
def retrieve_html(url):
"""
Return the raw HTML at the specified URL.
Args:
url (string):
Returns:
status_code (integer):
raw_html (string): the raw HTML content of the response, properly encoded according to the HTTP headers.
"""
# Write solution here
r = requests.get(url)
return (r.status_code, r.content)
pass
def authenticate(config_filepath):
"""
Create an authenticated yelp-python client.
Args:
config_filepath (string): relative path (from this file) to a file with your Yelp credentials
Returns:
client (yelp.client.Client): authenticated instance of a yelp.Client
"""
# Write solution here
with io.open(config_filepath) as cred:
creds = json.load(cred)
auth = Oauth1Authenticator(**creds)
client = Client(auth)
return client
pass
# In[4]:
def yelp_search(client, query):
"""
Make an authenticated request to the Yelp API.
Args:
query (string): Search term
Returns:
total (integer): total number of businesses on Yelp corresponding to the query
businesses (list): list of yelp.obj.business.Business objects
"""
# Write solution here
resp = client.search(query)
return resp.total, resp.businesses
pass
def all_restaurants(client, query):
"""
Retrieve ALL the restaurants on Yelp for a given query.
Args:
query (string): Search term
Returns:
results (list): list of yelp.obj.business.Business objects
"""
# Write solution here
params = {
'category_filter': 'restaurants',
'offset':0
}
resp = client.search(query, **params)
respObj = resp.businesses
respTotal = resp.total
offset = len(resp.businesses)
params['offset'] = offset
while offset < respTotal:
resp = client.search(query, **params)
respObj = respObj + resp.businesses
offset = offset + len(resp.businesses)
params['offset'] = offset
time.sleep(2)
return respObj
pass
def parse_api_response(data):
"""
Parse Yelp API results to extract restaurant URLs.
Args:
data (string): String of properly formatted JSON.
Returns:
(list): list of URLs as strings from the input JSON.
"""
# Write solution here
pjson = json.loads(data)
urls = []
for i in pjson['businesses']:
urls.append(str(i['url']))
return urls
pass
def parse_page(html):
"""
Parse the reviews on a single page of a restaurant.
Args:
html (string): String of HTML corresponding to a Yelp restaurant
Returns:
tuple(list, string): a tuple of two elements
first element: list of dictionaries corresponding to the extracted review information
second element: URL for the next page of reviews (or None if it is the last page)
"""
# Write solution here
reviews = []
soup = BeautifulSoup(html, 'html.parser')
for r in soup.find_all("div", itemprop="review"):
rev = {}
#rev["review_id"] = r['data-review-id']
rev["user_id"] = r.find_next("meta", itemprop="author")['content']
rev["rating"] = float(r.find_next("meta", itemprop="ratingValue")['content'])
rev["date"] = r.find_next("meta", itemprop="datePublished")['content']
rev["text"] = r.find_next("p", itemprop="description").get_text().encode('utf-8')
reviews.append(rev)
nextpage = None
pagination = soup.find("div", {"class" : "arrange_unit page-option current"})
if pagination != None:
nextpage = pagination.find_next("a", {"class" : "available-number pagination-links_anchor"})
if nextpage != None:
nextpage = nextpage['href']
return (reviews, nextpage)
pass
def extract_reviews(url):
"""
Retrieve ALL of the reviews for a single restaurant on Yelp.
Parameters:
url (string): Yelp URL corresponding to the restaurant of interest.
Returns:
reviews (list): list of dictionaries containing extracted review information
"""
# Write solution here
allreviews = []
parseurl = url
while True:
response = retrieve_html(parseurl)
#print response[1]
if response[0] == 200:
root = parse_page (response[1])
allreviews = allreviews + root[0]
if root[1] != None:
parseurl = root[1]
else:
break
else:
break
return allreviews
pass
|
f843797d4f34a57af799317b1a61602340aa3436 | LintangWisesa/ML_Sklearn_MultivariateRegression | /0_2varRegression.py | 702 | 3.8125 | 4 | # multivariate linear regression
# linear regression with multiple variables
# y = m1x1 + m2x2 + b
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
dataRumah = {
'luas': [2600, 3000, 3200, 3600, 4000],
'kamar': [3, 4, 1, 3, 5],
'harga': [550000, 565000, 610000, 595000, 760000]
}
df = pd.DataFrame(dataRumah)
print(df)
# ==============================
from sklearn import linear_model
model = linear_model.LinearRegression()
# training
model.fit(df[['luas', 'kamar']], df['harga'])
# slope m1 & m2
print(model.coef_)
# intercept b
print(model.intercept_)
# ==============================
# prediction utk luas: 3200, kamar: 2
print(model.predict([[3600, 3]])) |
cca42ac741b6699275a82ef6f10e2453cb5c75eb | n4rzzzls/textReadability | /Source/text_parser.py | 597 | 3.71875 | 4 | from nltk import sent_tokenize, word_tokenize, pos_tag
def text_parsing(raw_text: str) -> dict:
"""
Transforms raw text into sentence and word tokens, tags them.
:param raw_text: raw text from input file
:return: a dictionary of raw text word, sentence tokens and tags.
"""
word_token = []
sent_token = sent_tokenize(raw_text)
for x in sent_token:
word_token += word_tokenize(x)
tagged = pos_tag(word_token)
return dict(
raw_text=raw_text,
word_tokens=word_token,
sentence_tokens=sent_token,
tagged=tagged
)
|
36a1b1d5af43284d6a7e207381f18b36c4af5415 | hassanbazari/python-practice-book | /anandology_chapter_2/2prb21_split_line.py | 440 | 3.859375 | 4 | #program to slice the line in a text file at a specific size
import sys
filename = sys.argv[1]
Size=sys.argv[2]
size=int(Size)
lines = []
with open(filename) as f:
lines = f.readlines()
for line in lines:
splitline = [line[i:i+size] for i in range(0, len(line), size)] #split line at specific size
x=splitline[-1] # select the last piece of list
splitline[-1]=x[:-1] #remove \n at the end
for i in splitline:
print (i)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.