blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
b6e45e076c4669ec1785bb440fe980d9ccdaf4a5 | manigadi123/Mycoding | /reverse a number.py | 358 | 4.125 | 4 | # Python Program to Reverse a Number using While loop
Number = int(input("Please Enter any Number: "))
Reverse = 0
while(Number > 0): #5>0
Reminder = Number %10
Reverse = (Reverse *10) + Reminder
Number = Number //10
print("\n Reverse of entered number is = %d" %Reverse)
x=123
b=str(x)
print b
print b[::-1]
|
039f4c2db4cda52304b8d5df2e368a5ea6390730 | ezor1/asn1tools | /asn1tools/compiler.py | 5,300 | 3.546875 | 4 | """Compile ASN.1 specifications to Python objects that can be used to
encode and decode types.
"""
from .parser import parse_string, convert_type_tokens
from .codecs import ber, der, per, uper
class Specification(object):
"""This class is used to encode and decode ASN.1 types found in an
ASN.1 specification.
Instances of this class are created by the factory functions
:func:`~asn1tools.compile_file()`,
:func:`~asn1tools.compile_string()` and
:func:`~asn1tools.compile_dict()`.
"""
def __init__(self, modules):
self._modules = modules
self._types = {}
try:
for module_name in modules:
types = modules[module_name]
for type_name in types:
if type_name in self._types:
raise RuntimeError()
self._types[type_name] = types[type_name]
except RuntimeError:
self._types = None
@property
def types(self):
"""A dictionary of all types in the specification, or ``None`` if a
type name was found in two or more modules.
"""
return self._types
@property
def modules(self):
"""A dictionary of all modules in the specification.
"""
return self._modules
def encode(self, name, data):
"""Encode given dictionary `data` as given type `name` and return the
encoded data as a bytes object.
>>> foo.encode('Question', {'id': 1, 'question': 'Is 1+1=3?'})
b'0\\x0e\\x02\\x01\\x01\\x16\\x09Is 1+1=3?'
"""
return self._types[name].encode(data)
def decode(self, name, data):
"""Decode given bytes object `data` as given type `name` and return
the decoded data as a dictionary.
>>> foo.decode('Question', b'0\\x0e\\x02\\x01\\x01\\x16\\x09Is 1+1=3?')
{'id': 1, 'question': 'Is 1+1=3?'}
"""
return self._types[name].decode(data)
def _compile_any_defined_by_type(type_, choices):
type_['choices'] = {}
for key, value in choices.items():
tokens = ['Dummy', '::=', [], value, []]
type_['choices'][key] = convert_type_tokens(tokens)
def _compile_any_defined_by_choices(specification,
any_defined_by_choices):
for location, choices in any_defined_by_choices.items():
module_name = location[0]
type_names = location[1:-1]
member_name = location[-1]
types = specification[module_name]['types']
if len(type_names) == 0:
_compile_any_defined_by_type(types[member_name], choices)
else:
for type_name in type_names:
types = types[type_name]
for member in types['members']:
if member['name'] != member_name:
continue
_compile_any_defined_by_type(member, choices)
break
def compile_dict(specification, codec='ber', any_defined_by_choices=None):
"""Compile given ASN.1 specification dictionary and return a
:class:`~asn1tools.compiler.Specification` object that can be used
to encode and decode data structures with given codec
`codec`. `codec` may be one of ``'ber'``, ``'der'``, ``'per'`` and
``'uper'``.
>>> foo = asn1tools.compile_dict(asn1tools.parse_file('foo.asn'))
"""
codecs = {
'ber': ber,
'der': der,
'per': per,
'uper': uper
}
try:
codec = codecs[codec]
except KeyError:
raise ValueError("unsupported codec '{}'".format(codec))
if any_defined_by_choices:
_compile_any_defined_by_choices(specification,
any_defined_by_choices)
return Specification(codec.compile_dict(specification))
def compile_string(string, codec='ber', any_defined_by_choices=None):
"""Compile given ASN.1 specification string and return a
:class:`~asn1tools.compiler.Specification` object that can be used
to encode and decode data structures with given codec
`codec`. `codec` may be one of ``'ber'``, ``'der'``, ``'per'`` and
``'uper'``.
>>> with open('foo.asn') as fin:
... foo = asn1tools.compile_string(fin.read())
"""
return compile_dict(parse_string(string),
codec,
any_defined_by_choices)
def compile_file(filename, codec='ber', any_defined_by_choices=None):
"""Compile given ASN.1 specification file or a list of files and return a
:class:`~asn1tools.compiler.Specification` object that can be used
to encode and decode data structures with given codec
`codec`. `codec` may be one of ``'ber'``, ``'der'``, ``'per'`` and
``'uper'``.
>>> foo = asn1tools.compile_file('foo.asn')
or
>>> foo = asn1tools.compile_file(['file1','file2,...])
"""
try:
with open(filename, 'r') as fin:
return compile_string(fin.read(),codec,any_defined_by_choices)
except:
f_str = _cat_file(filename)
return compile_string(f_str,codec,any_defined_by_choices)
def _cat_file(file_list):
f_str = ""
for file in file_list:
with open(file,'r') as fin
f = += fin.read()
return f_str
|
b801ade17b153ff6c0fa04888ca0d7cf2c37a612 | y0ssi10/leetcode | /python/palindrome_linked_list/solution.py | 436 | 4 | 4 | # Problem:
# Given a singly linked list, determine if it is a palindrome.
#
# Example:
# Input: 1->2->2->1
# Output: true
#
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
arr = []
while head is not None:
arr.append(head.val)
head = head.next
return arr == arr[::-1]
|
be6b3746850c938298108ae4bd6000320db6dd22 | CORREAves/MyCodes | /python/ProcessScheduler/GraficoGantt.py | 1,124 | 4.09375 | 4 | # listaProcessosGantt será uma lista de listas de tempo ocioso, em sobrecarga ou em execução.
# cada lista de listaProcessosGantt aponta para uma lista de um processo, na ordem em que o processo foi criado.
# cada lista de tempo do processo terá os valores:
# 0 - ocioso (quando o tempo de chegada ainda não foi alcançado), 1 - em execução, 2 - sobrecarga e 3 - em espera
# o gráfico de gantt será impresso segundo esses valores
# Exemplo: processo[0] = [0,1,1,2,3,3,3,1,1] irá imprimir:
# processo 0: ||X---||
# é necessário imprimir assim para que saia a execução por linha de processo
def imprime_gantt(listaProcessosGantt):
count = 0
for tempoProcesso in listaProcessosGantt:
print('processo ', count)
for t in range(len(tempoProcesso)):
if tempoProcesso[t] == 1:
print('|', end="")
elif tempoProcesso[t] == 2:
print('X', end="")
elif tempoProcesso[t] == 0:
print(' ', end="")
elif tempoProcesso[t] == 3:
print('-', end="")
count = count + 1
print('')
|
1a78849e1de34cf289e80d6e29f212cf6a52ac87 | init-fun/data-structure-in-7days | /StackandQueue/Stack/Stack__using_linkedlist.py | 1,629 | 4 | 4 | class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
class StackLinkedlist:
def __init__(self):
self.head = None
def is_empty(self):
return self.head == None
def size(self):
count = 0
if self.head is None:
return count
cnode = self.head
while cnode:
count += 1
cnode = cnode.next
print(f"Total nodes : {count}")
return
def push(self, new_data):
if self.head is None:
self.head = Node(new_data)
return
new_node = Node(new_data, self.head)
self.head = new_node
return
def pop(self):
if self.head is None:
print("Underflow")
return
popped_item = self.head.data
self.head = self.head.next
return popped_item
def peek(self):
if self.head is None:
print("Stack is empty")
return
print("peek : ", self.head.data)
return self.head.data
def display(self):
if self.head is None:
print("Stack is empty")
return
cnode = self.head
while cnode:
print(f"{cnode.data}", end=" > ")
cnode = cnode.next
print()
return
myStack = StackLinkedlist()
myStack.display()
print(f"Is stack is empty? : {myStack.is_empty()}")
myStack.push(1)
myStack.push(2)
myStack.display()
print(f"Popped item : {myStack.pop()}")
myStack.display()
myStack.peek()
myStack.size()
print(f"Is stack is empty? : {myStack.is_empty()}") |
ea8348affc2664b7250cdb83990038e42fca1fa4 | carlhinderer/python-exercises | /daily-coding-problems/problem431.py | 681 | 3.625 | 4 | # Problem 431
# Medium
# Asked by Nest
#
# Create a basic sentence checker that takes in a stream of characters and
# determines whether they form valid sentences. If a sentence is valid, the
# program should print it out.
#
# We can consider a sentence valid if it conforms to the following rules:
#
# 1. The sentence must start with a capital letter, followed by a lowercase
# letter or a space.
#
# 2. All other characters must be lowercase letters, separators (,,;,:) or
# terminal marks (.,?,!,‽).
#
# 3. There must be a single space between each word.
#
# 4. The sentence must end with a terminal mark immediately following a word.
# |
6ecc409361efb02d4879c9ea22697e42a84f51e0 | abhikbanerjee/Python_DataStructures_Interviews | /interview_questions/strings_iterators/length_longest_substring.py | 577 | 3.5 | 4 |
def lengthOfLongestSubstring(s: str) -> int:
if len(s) == 0:
return 0
if len(s.strip()) == 0 or len(s) == 1:
return 1
st = {}
max_substr_len = 0
running_count = 0
i = 0
while i < len(s):
if not s[i] in st:
st[s[i]] = i
running_count += 1
else:
if i != len(s) - 1:
max_substr_len = max(max_substr_len, running_count)
i = st[s[i]] + 1
running_count = 1
st.clear()
st[s[i]] = i
i += 1
return max_substr_len if running_count < max_substr_len else running_count
# str = "abcb"
str = "abcbacde"
print(lengthOfLongestSubstring(str))
|
db996676b7f3328930713ee4d0e240bd953eddbd | blee1710/DataStructurePractice | /Sorting/selection_sort.py | 448 | 4.03125 | 4 | # Selection sort implementation
numbers = [3,53,65,1,321,54,76,43,2,4,66]
# Time: O(n^2) || Space: O(1)
def selectionSort(array):
length = len(array)
for x in range(length):
minimum = x
temp = array[x]
for j in range(x+1, length):
if array[j] < array[minimum]:
minimum = j
array[x] = array[minimum]
array[minimum] = temp
selectionSort(numbers)
print(numbers) |
6c53ec9fd4e4119f07f53d5bccf4c82b8ecf9264 | yehongyu/acode | /2019/dfs/all_paths_from_source_to_target_1020.py | 1,325 | 3.8125 | 4 | class Solution:
"""
@param graph: a 2D array
@return: all possible paths from node 0 to node N-1
"""
def helper(self, graph, res, path, visited, start, target):
if start == target:
res.append(path[0:])
for next in graph[start]:
if visited[next] == 0:
path.append(next)
visited[next] = 1
self.helper(graph, res, path, visited, next, target)
visited[next] = 0
path.pop(-1)
def allPathsSourceTarget_Visit(self, graph):
# Write your code here
n = len(graph)
visited = [0] * n
res = []
path = [0]
visited[0] = 1
self.helper(graph, res, path, visited, 0, n-1)
return res
def helper_rec(self, graph, res, path, start, target):
path.append(start)
if start == target: res.append(path[0:])
else:
for next in graph[start]:
self.helper_rec(graph, res, path, next, target)
path.pop(-1)
def allPathsSourceTarget(self, graph):
n = len(graph)
res = []
path = []
self.helper_rec(graph, res, path, 0, n-1)
return res
s = Solution()
graph = [[1,2],[3],[3],[]]
res = s.allPathsSourceTarget(graph)
for l in res:
print(l)
|
0f1175f665158e1a02c2e892356a86a57ada27de | Simander/python3-blackjack | /Card.py | 651 | 3.515625 | 4 | class Card:
cardCount = 0
colourNames = ['hearts', 'diamonds', 'spades', 'clubs']
valueNames = ['ace', '2', '3', '4', '5', '6','7', '8', '9', 'knight', 'queen', 'king']
def __init__ (self, colour, value):
self.colour = colour
self.value = value
@classmethod
def getColourName(cls, colour):
return cls.colourNames[colour];
@classmethod
def getValueName(cls, value):
return cls.valueNames[value];
def toString(self):
return Card.getValueName(self.value) + ' of ' + Card.getColourName(self.colour)
|
40fde19ff31d9d0c2623d6475b72799716e169ca | kunalt4/AlgorithmsandDataStructuresCoursera | /Algorithmic Toolbox/week2_algorithmic_warmup/1_fibonacci_number/fibonacci.py | 274 | 3.734375 | 4 | # Uses python3
def calc_fib(n):
if n == 0:
return 0
elif n == 1:
return 1
fib_list = []
fib_list.append(0)
fib_list.append(1)
for i in range(2,n+1):
fib_list.append(fib_list[i-1] + fib_list[i-2])
return fib_list[-1]
n = int(input())
print(calc_fib(n))
|
257d01f4489bebdaebdbde2db6b1efa4b31c20b7 | siddhantshukla-10/SEE-SLL | /1/1a/app2.py | 395 | 3.875 | 4 | li = input("Enter space separated integers").split()
arr = [int(i) for i in li]
print("Maximum",max(arr))
print("Minimum",min(arr))
inp = int(input("Enter a number to be inserted"))
arr.append(inp)
print(arr)
inp = int(input("Enter a number to be deleted"))
arr.remove(inp)
print(arr)
inp=int(input("Enter a number to be searched"))
if inp in arr:
print("Present")
else:
print("Not Present")
|
8e8f17f7a47a4db6b51d0eca8c648239724180ae | Thcamposmartins/Ex_init_Py | /ex0016.py | 263 | 4.03125 | 4 | tupla = (
'1', 'um', '2', 'dois', '3', 'tres', '4', 'quatro', '5', 'cinco', '6', 'seis', '7', 'sete', '8', 'oito', '9', 'nove',
'10', 'dez')
num = int(input('Digite um numero: '))
pos=(num+num)-1
if num <= 10:
print(f'O numero digitado foi o : {tupla[pos]}')
|
d725cb16d75693dad1c24ba9b2d0cba96c6dceb8 | lukeolson/cs450-f20-demos | /demos/upload/optimization/Conjugate Gradient Parallel Tangents as Krylov Subspace Method.py | 6,103 | 3.640625 | 4 | #!/usr/bin/env python
# coding: utf-8
# ### Conjugate Gradient: the Krylov subspace method for Convex Quadratic Optimization $\def\b#1{\boldsymbol{ #1}}\def\B#1{\boldsymbol{ #1}}$
#
# Conjugate gradient can be thought of as a Krylov subspace method for the quadratic optimization problem $\min(f(\b x)$ where
# $$f(\b x)= \frac{1}{2}\b x^T\b A \b x + \b c^T \b x$$
# and $\b A$ is symmetric positive definite (this makes the problem convex).
#
# In this demo, we compare the result of conjugate gradient to an explicitly constructed Krylov subspace.
#
# We start by picking a random $\b A$ and $\b c$:
# In[17]:
import numpy as np
import numpy.linalg as la
import scipy.optimize as sopt
n = 32
# make A a random SPD matrix
Q = la.qr(np.random.randn(n, n))[0]
A = Q @ (np.diag(np.random.rand(n)) @ Q.T)
c = np.random.randn(n)
# pick number of steps of CG to execute
k = 10
# define quadratic objective function
def f(x):
return .5*np.inner(x, A @ x) + np.inner(c,x)
# ### Quadratic Programming using Arnoldi
#
# First, we form a Krylov subspace using Arnoldi iteration on $\b A$ with starting guess $\b c$, then select the minima via
# $$\B x_k = -||\B c||_2\B Q_k \B T_k^{-1} \B e_1 ,$$
# which is a minimizes within this Krylov subspace since
# \begin{align*}
# \min_{\B x \in \mathcal{K}_k(\B A, \B c)} f(\B x) &= \min_{\B y \in \mathbb{R}^k} f(\B Q_k \B y) \\
# &=\min_{\B y \in \mathbb{R}^k} \B y^T \B Q_k \B A \B Q_k \B y + \B c^T \B Q_k \B y \\
# &= \min_{\B y \in \mathbb{R}^k} \B y^T \B T_k \B y + ||\B c||_2\B e_1^T \B y.
# \end{align*}
#
# In[18]:
# initialize Krylov subspace, taking first column as c/||c||_2
Q = np.zeros((n,k))
T = np.zeros((k,k))
x_kr = np.zeros((n,k))
Q[:,0] = c / la.norm(c)
for i in range(1,k+1):
# perform Arnoldi iteration
u = A @ Q[:,i-1]
for j in range(0,i):
T[j,i-1] = np.inner(Q[:,j],u)
u = u - T[j,i-1]*Q[:,j]
if i<k:
T[i,i-1] = la.norm(u)
Q[:,i] = u/T[i,i-1]
# compute and store new best minimizer of f(x)
if i>0:
# compute approximate minima x_kr as -||\b c||_2\b Q \b T^{-1} \b e_1
e1 = np.zeros(i)
e1[0] = la.norm(c)
x_kr[:,i-1] = - Q[:,:i] @ la.solve(T[:i,:i],e1)
print(f(x_kr[:,i-1]), "= min_{ x_kr in Krylov subspace of dimension ", i,"} f(x_kr)")
# ### Nonlinear Programming using Parallel Tangents for Quadratic Objective
#
# Next, we implement Conjugate Gradient using the parallel tangents method, which is general to arbitrary nonlinear objective functions (but the convergence and optimality properties are only true for a convex quadratic objective function).
#
# The parallel tangent method performs two line minimizations at each iteration:
# * Perform a step of steepest descent to generate $\B{\hat{x}}_{k}$ from $\B x_k$.
# * Generate $\B x_{k+1}$ by minimizing over the line passing through $\B x_{k-1}$ and $\B{\hat{x}}_{k}$.
#
# To initialize the parallel tangents method, we use the two first approximate minima obtained from the Krylov subspace method above. Subsequent iterates are then reproduced exactly!
# In[28]:
# perform conjugate gradient by parallel tangents method
x_cg_pp = np.zeros((n, k))
x_cg_pp[:,0] = x_kr[:,0]
x_cg_pp[:,1] = x_kr[:,1]
# perform CG method via parallel tangents method
for i in range(2,k):
x = x_cg_pp[:,i-1]
# define function for steepest descent, based on current iterate x and grad_f(x)
# can use local variables within function
def f_1d(a):
return f(x + a*(A@x+c))
# solve for best steepest descent step using golden section search and form x_hat
a = sopt.golden(f_1d)
x_hat = x + a * (A@x+c)
# define function for extrapolation, based on last iterate x_cg_pp[:,i-2] and x_hat (the solution of steepest descent)
# can use local variables within function
def g_1d(a):
return f(x_hat + a*(x_hat - x_cg_pp[:,i-2]))
# solve for best extrapolation using golden section search and update x
a = sopt.golden(g_1d)
x = x_hat + a*(x_hat - x_cg_pp[:,i-2])
# store CG iterate as next column of x_cg_pp
x_cg_pp[:,i] = x
print(f(x), " = f( conjugate gradient parallel tangents iterate", i, ")")
# ### Quadratic Programming by Conjugate Gradient
#
# The 1D line minimizations in the parallel tangents method can be solved analytically given a quadratic objective, so the parallel tangents implementation can be transformed to use a couple of matrix vector products in place of the two golden section searches.
# In[30]:
# perform CG method via matrix-vector products
x_cg_mv = np.zeros((n, k))
x_cg_mv[:,0] = x_kr[:,0]
x_cg_mv[:,1] = x_kr[:,1]
# this implementation mimics parallel tangents implementation,
# one of the matrix vector products can in fact be avoided
for i in range(2,k):
x = x_cg_mv[:,i-1]
# compute gradient
g = A@x + c
# compute explicit equation for optimal step size for steepest descent
a = - np.inner(g,g)/np.inner(g, A@g)
# update x
x_hat = x + a * g
# determine new optimization direction
d = x_hat - x_cg_mv[:,i-2]
# compute explicit equation for optimal step size in direction d = x_hat - x_{k-1}
a = - np.inner(g,d)/np.inner(d, A@d)
#update x
x = x_hat + a * d
# store CG iterate as next column of x_cg_mv
x_cg_mv[:,i] = x
print(f(x), " = f( conjugate gradient matrix vector product iterate", i, ")")
# It can be shown that each step of Conjugate gradient causes an update $\b s_k = \b x_{k+1} - \b x_k$ that is $\b A$-conjugate ($\b A$-orthogonal) to the previous, i.e. $\b s_i^T\b A \b s_{i-1}$:
# In[34]:
for i in range(2,k):
print(np.inner(x_cg_mv[:,i]-x_cg_mv[:,i-1],A @ (x_cg_mv[:,i-1]-x_cg_mv[:,i-2])))
# In fact $\b s_i^T \b A \b s_j= 0$ if $i\neq j$.
# In[39]:
print((x_cg_mv[:,1:]-x_cg_mv[:,:-1]).T @ A @ (x_cg_mv[:,1:]-x_cg_mv[:,:-1]))
# This fact permits a further optimization of the conjugate gradient iteration, resulting in only 1 matrx-vector product (the resulting work-efficient method can be found in many textbooks, papers, and on wikipedia).
# In[ ]:
|
5cc3011ee2e7ef2bb1fc15a6cca4e99033a5d9ee | tushar-borole/code-challenges | /diagonal_sum.py | 1,130 | 4.1875 | 4 | # Given a square matrix of size , calculate the absolute difference between the sums of its diagonals.
#
# Input Format
#
# The first line contains a single integer, . The next lines denote the matrix's rows, with each line containing space-separated integers describing the columns.
#
# Output Format
#
# Print the absolute difference between the two sums of the matrix's diagonals as a single integer.
#
# Sample Input
#
# 3
# 11 2 4
# 4 5 6
# 10 8 -12
# Sample Output
#
# 15
# Explanation
#
# The primary diagonal is:
# 11
# 5
# -12
#
# Sum across the primary diagonal: 11 + 5 - 12 = 4
#
# The secondary diagonal is:
# 4
# 5
# 10
# Sum across the secondary diagonal: 4 + 5 + 10 = 19
# Difference: |4 - 19| = 15
#!/bin/python
import sys
n = int(raw_input().strip())
a = []
for a_i in xrange(n):
a_temp = map(int,raw_input().strip().split(' '))
a.append(a_temp)
first_diagonal=0
second_diagonal = 0
highest_matrix=n-1
for next in xrange(n):
first_diagonal += a[next][next]
second_diagonal += a[next][highest_matrix-next]
print abs(first_diagonal - second_diagonal) |
b2987bc90d057d88982c7203de4a1b0a7c0ff006 | riCoYanG-byte/leetcode | /binary tree/No116_node_next.py | 1,369 | 4.25 | 4 | import collections
# similar question like zigzag
class Solution:
def connect(self, root: 'Node') -> 'Node':
if not root:
return root
# Initialize a queue data structure which contains
# just the root of the tree
Q = collections.deque([root])
# Outer while loop which iterates over
# each level
while Q:
# Note the size of the queue
size = len(Q)
# Iterate over all the nodes on the current level
for i in range(size):
# Pop a node from the front of the queue
node = Q.popleft()
# This check is important. We don't want to
# establish any wrong connections. The queue will
# contain nodes from 2 levels at most at any
# point in time. This check ensures we only
# don't establish next pointers beyond the end
# of a level
if i < size - 1:
node.next = Q[0]
# Add the children, if any, to the back of
# the queue
if node.left:
Q.append(node.left)
if node.right:
Q.append(node.right)
# Since the tree has now been modified, return the root node
return root
|
d2dd20a9e542abeaa2181d737978651d78453d6c | stacykutyepov/python-cp-cheatsheet | /educative/linkedlists/convertIntToBin.py | 283 | 3.578125 | 4 | from stack import Stack
# Return string of binary
def convert_int_to_bin(dec_num):
sk = []
rtn = ""
if dec_num == 0:
return 0
while dec_num > 0:
bn = dec_num % 2
sk.append(bn)
dec_num = dec_num // 2
while sk:
rtn = rtn + str(sk.pop())
return rtn |
2bcd091eb3fd5b87179f78cc5edf9babdb496bed | shenqiti/leetcode | /96. Unique Binary Search Trees.py | 2,039 | 3.96875 | 4 | '''
96. Unique Binary Search Trees
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
DP, catalan number
By:shenqiti
2019/8/13
'''
class Solution(object):
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
dp = [0 for _ in range(n + 1)]
dp[0] = 1
dp[1] = 1
for i in range(2, n + 1):
for j in range(i):
dp[i] += dp[j] * dp[i - j - 1]
return dp[-1]
dd = Solution()
n = 3
result = dd.numTrees(n)
print(result)
# class Solution(object):
# def numTrees(self, n):
# T = [1, 1, 2] + [0]*(n - 2)
# for m in range(3, n + 1):
# for i in range(m):
# T[m] += T[i] * T[m - 1 - i]
# return T[n]
#
# """
# Faster version below takes advantage of symmetry (half as many iterations)
# """
# def numTreesFaster(self, n):
# T = [1, 1, 2] + [0]*(n - 2)
# for m in range(3, n + 1):
# mid, remainder = divmod(m, 2)
# for i in range(mid):
# T[m] += T[i] * T[m - 1 - i]
# T[m] *= 2
# if remainder: T[m] += T[mid] * T[mid]
# return T[n]
'''
The pattern is simply:
T(0) = 1 (defined for convenience)
T(1) = 1 (number of binary search trees possible with one node)
T(2) = 2 (number of binary search trees possible with two nodes)
T(3) = T(0)*T(2) + T(1)*T(1) + T(2)*T(0) (1st term: lowest number is root, 2nd term: middle number is root, 3rd term: biggest number is root)
T(4) = T(0)*T(3) + T(1)*T(2) + T(2)*T(1) + T(3)*T(0)
T(5) = T(0)*T(4) + T(1)*T(3) + T(2)*T(2) + T(3)*T(1) + T(4)*T(0)
'''
'''
The total number of BSTs is described by the function: (2n)! / ((n+1)! n!)
class Solution(object):
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
return factorial(2 * n) / (factorial(n+1) * factorial(n))
def factorial(n):
return 1 if n == 0 else n * factorial(n-1)
'''
|
0ba24f67140304a6f7720ffd8f3fffab09a23233 | smohapatra1/scripting | /python/practice/day43/quiz1.py | 66 | 3.609375 | 4 | count = 0
for x in range(2,5):
count = count + x
print(count)
|
a5044f7981e05012c58562e5797f19cee09764cf | tulku/trello-zap | /trello_zap/requests.py | 1,120 | 3.703125 | 4 |
class Request(object):
""" Represents a request of a product. """
def __init__(self):
self.backend_object = None
self.amount = None
self.name = None
self.due = None
self.impossible = False
self.due = None
def set(self, name, amount, obj):
self.name = name
self.amount = amount
self.backend_object = obj
def mark_impossible(self):
self.impossible = True
def set_due(self, due):
self.due = due
def __str__(self):
return " Resquest for {} of {}".format(self.name, self.amount)
class Requests(object):
def __init__(self):
self.requests = []
self.total = 0
def append(self, name, amount, obj):
self.total += amount
r = Request()
r.set(name, amount, obj)
self.requests.append(r)
def get_total(self):
return self.total
def get_requests(self):
for r in self.requests:
yield r
def __str__(self):
s = "["
for r in self.requests:
s += str(r) + ", "
return (s + "]")
|
8e4394e8d5bd4a41de7861b3a81113e83a7a887a | anilkumar0470/git_practice | /Terralogic_FRESH/regular_expressions/reg_exp_sub_replace.py | 1,035 | 4.125 | 4 | """
#replacing the pattern by using sub method
import re
str1 = 'purple alice.b--abc@gmail.com, blah monkey bob@gmail.com blah dishwasher'
#re.sub(pattern,replacement,str)--returns new string with all replacements
# \1 is group(1) for before @and it will replace nothing
# \2 is group(2) for after @ and it will replace nothing if we specifiy
print re.sub(r'([\w\.-]+)@([\w\.-]+)',r'\1@yahoo.com',str1)
"""
#assignment for replacing the pattern
#str = " dob: 10/03/2016 loc : btm joined: 12/03/2017"
#output ="dob :2016 loc :btm joined :2017"
"""
import re
str = "dob=12/7/1993 loc@btm joined:12/03/2016"
str = re.sub(r'([\w.]+):([\d/\d/\d-]+)',r'\1:2016',str)
print re.sub(r'([\w.]+)=([\d/\d/\d-]+)',r'\1=1993',str)
"""
import re
str2 = 'purple alice.b--abc@gmail.com, blah monkey bob_test@gmail.com blah dishwasher'
output = re.sub('([\w\.\_\-]+)@([\w\.\_\-]+)',r'test@\2',str2)
print(str2)
print (output)
#search/match/findall -- pattern, text
# sub pattern -- replaced string , string
# #
#
#print re.sub(r'([\w\-.]+)@([\w\.-]+)',r'\1@anil.com',str2) |
60c77605027535bef7b1f7418c363bfe833f3cc9 | akinahmet/python | /Number_Guessing_Game.py | 796 | 3.75 | 4 | import random
import time
print ("""
*************************
SAYI TAHMİN OYUNU
1-100 ARASI SAYI TAHMİN ET
*************************
""")
rastgelesayı = random.randint(1,100)
tahminhakkı = 7
while True:
tahmin=int(input ("Tahmininiz:"))
if (tahmin<rastgelesayı):
print ("Sorgulanıyor...")
time.sleep(1)
print ("sayıyı yükselt")
tahminhakkı-=1
elif (tahmin>rastgelesayı):
print ("Sorgulanıyor...")
time.sleep(1)
print ("sayıyı düşür")
tahminhakkı-=1
else:
print("Sorgulanıyor...")
time.sleep(1)
print("Tebrikler", rastgelesayı)
break
if (tahminhakkı==0):
print ("tahmin hakkınız bitti...")
print ("sayımız:", rastgelesayı)
|
b40d61538882a214c9aef9171add39ded5b790fd | saketvikram/algorithms-ds-in-python | /sorting/selectionSort.py | 433 | 3.71875 | 4 | def selectionSort(array):
leftpointer = 0
array_len = len(array) - 1
while leftpointer < array_len:
minpointer = leftpointer
for index in range(leftpointer+1, array_len+1):
if array[index] < array[minpointer]:
minpointer = index
swapElements(array, leftpointer, minpointer)
leftpointer += 1
return array
def swapElements(array, i, j):
array[i], array[j] = array[j], array[i]
|
4fba8865f46597abff778e63bccf77de1b190fb9 | SMAshhar/Temp-Ashhar1 | /HTML CSS/my-smarter-site/Testing.py | 969 | 3.84375 | 4 | class Navi():
def __init__(self, x, y):
self.x = x
self.y = y
def newPos(self, x1, y1):
self.x = x1
self.y = y1
dot = Navi(0,3)
import numpy as np
a = [[0,0,0,1,0,0,0,0,0,0],
[0,1,1,1,1,1,1,1,1,0],
[0,1,0,0,0,0,1,0,1,0],
[0,1,1,1,0,1,1,0,1,0],
[0,1,0,1,0,1,0,0,1,0],
[0,1,1,1,1,1,0,1,1,0],
[0,0,0,0,0,1,0,0,0,0],
[0,1,0,1,0,1,0,0,1,0],
[0,1,1,1,1,1,1,1,1,0],
[0,0,0,0,0,0,0,1,0,0]]
while dot.x != 9 and dot.y != 9:
if a[dot.x + 1][dot.y] == 1 and a[dot.x][dot.y - 1] != 1 and a[dot.x][dot.y + 1] != 1:
dot.x += 1
print(a[dot.x][dot.y])
elif a[dot.x + 1][dot.y] != 1 and a[dot.x][dot.y - 1] != 1 and a[dot.x][dot.y + 1] == 1:
dot.y += 1
print(a[dot.x][dot.y])
elif a[dot.x + 1][dot.y] != 1 and a[dot.x][dot.y - 1] == 1 and a[dot.x][dot.y + 1] != 1:
dot.y -= 1
print(a[dot.x][dot.y])
|
b10697b2ad82faf368106afd292e5eee1f750c9c | DevPpl/LetsUpgrade-Python-Essentials | /Day 2/Question 4.py | 607 | 4.1875 | 4 | print('Questions 4. Tuple and explore default methods.')
tple = ('this', 'is', 'a', 'tuple')
print(tple)
# 1 index() - Searches the tuple for a specified value and returns the position of where it was found
address = tple.index('is')
print(address)
# 2 count() - Returns the number of times a specified value occurs in a tuple
numb = tple.count('a')
print(numb)
# 3 len() - return the length of the tuple
print(len(tple))
# 4 min() - return item from the tuple with max value.
tple2 = (4, 6, 9, 2, 3)
print(min(tple2))
# 5 max() - Returns item from the tuple with max value.
print(max(tple2)) |
b37365ab350ecf38e40e6009fe0228ee25024f62 | askanium/pycodealizer | /src/pycodealizer/walkers.py | 1,218 | 3.515625 | 4 | import ast
import os
class DirWalker(object):
def __init__(self, root_dir: str):
self.root_dir = root_dir
def walk(self):
"""Walks the subdirectories and files in the root directory."""
return self.scan_directory(self.root_dir)
def scan_directory(self, dir_name: str):
"""Scan a specific directory.
:param dir_name The directory name to scan for python files.
"""
for dirpath, dirnames, filenames in os.walk(dir_name):
# print(dirpath, dirnames, filenames)
for filename in filenames:
if filename.endswith(('.py', '.pyw')):
filepath = os.path.join(dirpath, filename)
yield filepath
for dirname in dirnames:
self.scan_directory(os.path.join(dirpath, dirname))
class ModuleWalker(object):
"""Walks along the children of an `ast.Module` node."""
@staticmethod
def walk(tree_root: ast.Module):
"""Yield the immediate children of the `ast.Module` node.
:param tree_root: The root of the abstract syntax tree to parse.
"""
for child in ast.iter_child_nodes(tree_root):
yield child
|
fc961616d6b71ea3285f5f797f6f93b6095ef196 | mx11Code/pythoncode | /python/06.py | 808 | 3.875 | 4 | # 1, 2, 1+2=3, 2+3=5, 3+5=8,
# n! = n * (n-1)!
# def factorial(n):
# val = 1
# for i in range(1, n+1):
# val = val * i
# return val
#
# val1 = factorial(4)
# print(val1)
#
#
def factorial1(n):
if n == 0:
return 1
return n * factorial1(n - 1)
val1 = factorial1(100)
print(val1)
# def sum(n):
# if n == 0:
# return 0
# return n + sum(n-1)
#
# sum1 = sum(100)
# print(sum1)
d = {}
def fibonacci(n):
if n in d:
return d[n]
if n == 1:
return 1
if n == 2:
return 2
val = fibonacci(n - 1) + fibonacci(n - 2)
d[n] = val
return val
print(fibonacci(100))
def fibonacci2(n):
fn = [0, 1, 2]
for i in range(3, n + 1):
fn.append(fn[i - 1] + fn[i - 2])
return fn[n]
print(fibonacci2(100))
|
caf3b0c1a46bb7a6669923621fd055a2186f92cf | akaliutau/cs-problems-python | /problems/bfs/Solution1631.py | 1,210 | 3.859375 | 4 | """ You are a hiker preparing for an upcoming hike. You are given efforts, a 2D
array of size rows x columns, where efforts[row][col] represents the effort
of cell (row, col). You are situated in the top-left cell, (0, 0), and you
hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e.,
0-indexed). You can move up, down, left, or right, and you wish to find a
route that requires the minimum effort. A route's effort is the maximum
absolute difference in efforts between two consecutive cells of the route.
Return the minimum effort required to travel from the top-left cell to the
bottom-right cell.
Input: efforts =
[
[1,2,2],
[3,8,2],
[5,3,5]
]
Output: 2
Explanation: The route of [1,3,5,3,5] has a maximum absolute difference of 2
in consecutive cells. This is better than the route of [1,2,2,2,5], where the
maximum absolute difference is 3.
IDEA (similar to 1102):
As a result all cells in queue will be prioritized by min effort on the top => optimal
[not necessary the shortest] path
explicit greedy approach - we are trying the effortless paths first
"""
class Solution1631:
pass
|
cdb39505ee523ebfc985997c7ce2af161e5439ab | rohitpawar4507/W3school | /Lambda/lambda_1.py | 146 | 3.53125 | 4 |
nums = [3,4,5,1,4,2,8,9,0,6]
evens = list(filter(lambda n:n%2==0,nums))
doubles = list(map(lambda n:n+2,evens))
print(evens)
print(doubles) |
4894e6610bf1c6782680c694a45f0428a2de4481 | KIYONOx/How_to_use_the_Keras_model | /model_build_save.py | 2,190 | 3.546875 | 4 | import sys
import numpy as np
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
# MNIST dataset load
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# before:28 x 28 :[two-dimensional] array x 60,000
# after :784 : [one-dimensional] array x 60,000(256 : 0 〜 1 normalized )
X_train = X_train.reshape(60000, 784).astype('float32') / 255
X_test = X_test.reshape(10000, 784).astype('float32') / 255
# before:0 〜 9 number x 60,000
# after :one-hot x 60,000
# - 0 : [1,0,0,0,0,0,0,0,0,0]
# - 1 : [0,1,0,0,0,0,0,0,0,0]
# ...
Y_train = np_utils.to_categorical(y_train, 10)
Y_test = np_utils.to_categorical(y_test, 10)
# Sequential
model = Sequential()
# hidden layer 1
# - node:512
# - input:784
# - activating function:relu
# - dropout:0.2
model.add(Dense(512, input_dim=784))
model.add(Activation('relu'))
model.add(Dropout(0.2))
# hidden layer 2
# - node:512
# - activating function:relu
# - dropout:0.2
model.add(Dense(512))
model.add(Activation('relu'))
model.add(Dropout(0.2))
# output layer
# - node:10
# - activating function:softmax
model.add(Dense(10))
model.add(Activation('softmax'))
# summary output
model.summary()
# learning setting
# - target function:categorical_crossentropy
# - optimized algorithm:rmsprop
model.compile(loss='categorical_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
# training
# - batch size:128
# - repeat count:20
model.fit(X_train, Y_train,
batch_size=128,
nb_epoch=20,
verbose=1,
validation_data=(X_test, Y_test))
# evaluation
score = model.evaluate(X_test, Y_test, verbose=0)
print('Test loss :', score[0])
print('Test accuracy :', score[1])
#model save
model_json_str = model.to_json()
open('mnist_mlp_model.json', 'w').write(model_json_str)
model.save_weights('mnist_mlp_weights.h5');
from keras.models import model_from_json
# model load
model = model_from_json(open('mnist_mlp_model.json').read())
# weights result load
model.load_weights('mnist_mlp_weights.h5') |
a489434bcae062ccfadb8a6227d6f8eb61034d8d | Sammyalhashe/CSC_Course_Work | /leftRotation.py | 331 | 3.53125 | 4 | def array_left_rotation(a, k):
new_array = [0] * len(a)
for i in range(len(a)):
new_array[i - k] = a[i]
return new_array
#n, k = map(int, input().strip().split(' '))
#a = list(map(int, input().strip().split(' ')))
a, k = [1, 2, 3, 4, 5, 6, 7, 8], 3
answer = array_left_rotation(a, k)
print(*answer, sep=' ')
|
eb37cdbc9195867cf93e97fc7893a1cd1334c29d | raul-f/algorithms | /python/project-euler/0005_smallest-multiple/helpers.py | 1,964 | 3.921875 | 4 | from typing import List
#########################
#
# Prime-related functions
#
#########################
def get_factors(input_num: int) -> List[int]:
factors: List[int] = []
if input_num >= 2:
number: int
for number in range(2, input_num):
if number in factors:
return sorted(factors)
if input_num % number == 0:
factors.extend([number, int(input_num / number)])
return sorted(factors)
else:
return []
def get_pivots(upper_boundary: int) -> List[int]:
pivots: List[int] = []
for number in range(2, upper_boundary):
if number ** 2 > upper_boundary:
return pivots
elif len(get_factors(number)) == 0:
pivots.append(number)
def remove_multiples_of(factor: int, number_set: List[int]) -> List[int]:
output_set: List[int] = []
for number in number_set:
if number % factor != 0 or number == factor:
output_set.append(number)
return output_set
def get_primes_lesser_than(upper_boundary: int) -> List[int]:
primes: List[int] = list(range(2, upper_boundary))
pivots = get_pivots(upper_boundary)
# print(pivots)
pivot: int
for pivot in pivots:
primes = remove_multiples_of(pivot, primes)
return primes
#########################
#
# Factorization functions
#
#########################
def get_maximum_exponents(primes: List[int], upper_limit: int) -> List[List[int]]:
exponents: List[List[int]] = []
exponent: int = 1
prime: int
for prime in primes:
while prime ** exponent <= upper_limit:
exponent += 1
exponents.append([prime, exponent - 1])
exponent = 1
return exponents
def get_number_from_factorization(factorization: List[List[int]]) -> int:
composite: int = 1
for [factor, exponent] in factorization:
composite *= factor ** exponent
return composite
|
ca1bc83458a686a0b9db2256a0a7735e6e2e7cd2 | venterachallenge/Langley_Dev_Challenge | /transform.py | 2,747 | 3.59375 | 4 | '''
Ben Langley
October 24th, 2018
Ventera Dev Challenge
Description: This file reads in the JSON in data.json, transforms it
per the details in the README and saves the new json to data-transformed.json
For more details on how to use this file please consult the read me
Note: If in the future there are multiple types of transforms, the given functions
should be abstrated to a class. This file can then contain multiple classes for
different transformations which can be loaded by external files on as needed basis
'''
import json
import JSONHelper
'''
Takes in customer JSON object in the old format and returns
just the customerID to be used in the new format
customer - the JSON customer details
returns the customerID
'''
def _transformCustomer(customer):
return customer["id"]
'''
Takes in order JSON object in the old format and returns a new
JSON object called details which is a list of order details
order - the JSON order details
returns the newly formated details as JSON
'''
def _transformOrder(order):
transformed_items = [] # List of transformed items in the order
# Iterate over each item in the order
for item, item_data in order.items():
# Transform the item
transformed_item_data = {}
transformed_item_data["item"] = item
transformed_item_data["quantity"] = item_data["quantity"]
transformed_item_data["price"] = item_data["price"]
transformed_item_data["revenue"] = item_data["quantity"] * item_data["price"]
# Append the transformed item to the list
transformed_items.append(transformed_item_data)
return transformed_items
'''
Public function to transform the input json into the new format an save
to the outputfile
inputJSONfile - the input JSON file of the old format
default: "data.json"
outputJSONfile - the output JSON file to save new format
default: "transformed.json"
returns the transformed data dictionary
'''
def transform(inputJSONfile="data.json", outputJSONfile="transformed.json"):
# Get the data
data = JSONHelper.getJSON(inputJSONfile)
# Transform the data
transformed_data = [] # list of the transformed data items
# Loop over each item in the data and transform
for item in data:
transformed_item = {} # the current item to be transformed
transformed_item["id"] = item["id"]
transformed_item["vendor"] = item["vendor"]
transformed_item["date"] = item["date"]
transformed_item["customerID"] = _transformCustomer(item["customer"])
transformed_item["details"] = _transformOrder(item["order"])
# Append the transformed item to the data list
transformed_data.append(transformed_item)
# Save the data
JSONHelper.saveAsJSON(transformed_data, outputJSONfile)
return transformed_data
# For DEBUG
#transform() |
4fd23a80a0e467dc3ec6f31e8435ce8613eacbf1 | chendingyan/My-Leetcode | /剑指offer-python/FindNumsAppearOnce.py | 1,630 | 3.609375 | 4 | # -*- coding:utf-8 -*-
# 一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
# 我这道题的做法 很直接 但我觉得应该考察的不是这个
# 经过寻找,我发现这道题考察的是位运算 bit manipulation
# 一个数字和自己异或一次会变成0。
class Solution:
# 返回[a,b] 其中ab是出现一次的两个数字
def FindNumsAppearOnce1(self, array):
# write code here
if array == []:
return []
list1= []
for i in array:
if hash(i) in list1:
print('1111')
list1.pop(list1.index(hash(i)))
else:
list1.append(hash(i))
return list1
def FindNumsAppearOnce2(self, array):
if len(array)<2:
return None
temp = array[0]
for i in array[1:]:
temp = temp ^ i
if temp == 0:
return None
index = self.findindex(temp)
num1, num2 = 0,0
for i in array:
if self.Bitis1(index, i):
num1 = num1 ^ i
else:
num2 = num2 ^i
return [num1, num2]
def findindex(self,num):
index = 0
while (num & 1) == 0:
index += 1
num = num >> 1
return index
def Bitis1(self, index, num):
num = num >> index
return num & 1
# 7 = 2+4+1 = 0111
# 4 = 0100
# 4 ^ 7 = 0011 = 3 0011&1 = 0
a = [1,2,3,1,2,4,7,5,5,3]
sol = Solution()
ans = sol.FindNumsAppearOnce2(a)
print(ans) |
1ad74c705f21e8164090fccf8f04206398fd41c4 | MNandaNH/MNandaNH | /For_s/crear_lista.py | 325 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 20 09:18:33 2021
@author: franc
"""
def crealista(n):
lista=[ ]
for i in range(n): #tange puede ser(variable inicial, maxima y saltos)
lista.append(i)
return lista
resultado=crealista(30) #número de elementos de la lista
print (resultado)
|
3237a78e85e6d8894275e5c51f3cf881d30d15ea | Hannibal404/COL100-Assignment | /COL100 Assignment/pgm.py | 6,575 | 3.53125 | 4 | # name: File path of the pgm image file
# Output is a 2D list of integers
from math import sqrt
def readpgm(name):
image = []
with open(name) as f:
lines = list(f.readlines())
if len(lines) < 3:
print("Wrong Image Format\n")
exit(0)
count = 0
width = 0
height = 0
for line in lines:
if line[0] == '#':
continue
if count == 0:
if line.strip() != 'P2':
print("Wrong Image Type\n")
exit(0)
count += 1
continue
if count == 1:
dimensions = line.strip().split(' ')
print(dimensions)
width = dimensions[0]
height = dimensions[1]
count += 1
continue
if count == 2:
allowable_max = int(line.strip())
if allowable_max != 255:
print("Wrong max allowable value in the image\n")
exit(0)
count += 1
continue
data = line.strip().split()
data = [int(d) for d in data]
image.append(data)
return image
# img is the 2D list of integers
# file is the output file path
def writepgm(img, file):
with open(file, 'w') as fout:
if len(img) == 0:
pgmHeader = 'p2\n0 0\n255\n'
else:
pgmHeader = 'P2\n' + \
str(len(img[0])) + ' ' + str(len(img)) + '\n255\n'
fout.write(pgmHeader)
line = ''
for i in img:
for j in i:
line += str(j) + ' '
line += '\n'
fout.write(line)
def avg_filter(image):
avim = []
for i in image:
avim.append(i[:])
i = 1
while i < len(image)-1:
j = 1
while j < len(image[0])-1:
avim[i][j] = (image[i-1][j-1]+image[i-1][j]+image[i-1][j+1]+image[i][j-1] +
image[i][j]+image[i][j+1]+image[i+1][j-1] + image[i+1][j]+image[i+1][j+1])//9
j += 1
i += 1
return avim
def edge_det(image):
x1 = [[0 for i in range(len(image[0])+2)]]
grad = [[0 for i in range(len(image[0])+2)] for j in range(len(image)+2)]
hdif = [[0 for i in range(len(image[0])+2)] for j in range(len(image)+2)]
vdif = [[0 for i in range(len(image[0])+2)] for j in range(len(image)+2)]
for i in range(len(image)):
x1.append([0]+image[i][:]+[0])
x1.append([0 for i in range(len(image)+2)])
for i in range(1, len(x1)-1):
for j in range(1, len(x1[0])-1):
hdif[i][j] = x1[i-1][j-1] - x1[i-1][j+1] + \
(2*(x1[i][j-1]-x1[i][j+1])) + x1[i+1][j-1] - x1[i+1][j+1]
vdif[i][j] = x1[i-1][j-1] - x1[i+1][j-1] + \
(2*(x1[i-1][j]-x1[i+1][j])) + x1[i-1][j+1] - x1[i+1][j+1]
grad[i][j] = int(sqrt((hdif[i][j]**2) + (vdif[i][j]**2)))
M = 0
for i in range(len(x1)):
M = max(M, max(grad[i]))
for i in range(len(x1)):
for j in range(len(x1[0])):
grad[i][j] = (grad[i][j]*255)//M
g1 = []
for i in range(1, len(grad)-1):
g1.append(grad[i][1:len(grad[i])-1])
return g1
def MinEnergyPath(im):
x = edge_det(im)
final = []
for i in im:
final.append(i[:])
MinEnergy = [[0 for i in range(len(x[0]))]for j in range(len(x))]
for i in range(len(x[0])):
MinEnergy[0][i] = x[0][i]
for i in range(1, len(x)):
for j in range(1, len(x[0])-1):
MinEnergy[i][j] = x[i][j] + \
min(MinEnergy[i-1][j-1], MinEnergy[i-1]
[j], MinEnergy[i-1][j+1])
MinEnergy[i][0] = x[i][0] + min(MinEnergy[i-1][0], MinEnergy[i-1][1])
MinEnergy[i][-1] = MinEnergy[i][-1] = x[i][-1] + \
min(MinEnergy[i-1][-2], MinEnergy[i-1][-1])
minen = min(MinEnergy[-1])
ml = [[]for i in range(len(MinEnergy))]
for j in range(len(MinEnergy[-1])):
if MinEnergy[-1][j] == minen:
final[-1][j] = 255
ml[-1].append(j)
i = len(MinEnergy)-1
while i > 0:
for j in ml[i]:
if j == 0:
if len(MinEnergy[i]) > 1:
m = min(MinEnergy[i-1][j], MinEnergy[i-1][j+1])
if MinEnergy[i-1][j] == m:
final[i-1][j] = 255
if j not in ml[i-1]:
ml[i-1].append(j)
if MinEnergy[i-1][j+1] == m:
final[i-1][j+1] = 255
if j+1 not in ml[i-1]:
ml[i-1].append(j+1)
else:
final[i-1][j] = 255
ml[i-1].append(j)
elif 0 < j < len(MinEnergy)-1:
m = min(MinEnergy[i-1][j-1], MinEnergy[i-1]
[j], MinEnergy[i-1][j+1])
if MinEnergy[i-1][j-1] == m:
final[i-1][j-1] = 255
if j-1 not in ml[i-1]:
ml[i-1].append(j-1)
if MinEnergy[i-1][j] == m:
final[i-1][j] = 255
if j not in ml[i-1]:
ml[i-1].append(j)
if MinEnergy[i-1][j+1] == m:
final[i-1][j+1] = 255
if j+1 not in ml[i-1]:
ml[i-1].append(j+1)
else:
m = min(MinEnergy[i-1][j], MinEnergy[i-1][j-1])
if MinEnergy[i-1][j] == m:
final[i-1][j] = 255
if j not in ml[i-1]:
ml[i-1].append(j)
if MinEnergy[i-1][j-1] == m:
final[i-1][j-1] = 255
if j-1 not in ml[i-1]:
ml[i-1].append(j-1)
i -= 1
return final
########## Function Calls ##########
# test.pgm is the image present in the same working directory
x = readpgm('finlena.pgm')
writepgm(avg_filter(x), 'avglena.pgm')
writepgm(edge_det(x), 'edgelena.pgm')
writepgm(MinEnergyPath(x), 'minpathlena.pgm')
# x is the image to output and test_o.pgm is the image output in the same working directory
writepgm(x, 'test_olena.pgm')
###################################
|
094ee3c85e0bcb8de8f7c83bdf47e92578a933e2 | vishal-chillal/assignments | /new_tasks_23_june/46_solutions/43_anagram_words.py | 2,151 | 4.1875 | 4 | #43.An anagram is a type of word play,the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once; e.g., orchestra = carthorse. Using the word list at http://www.puzzlers.org/pub/wordlists/unixdict.txt, write a program that finds the sets of words that share the same characters that contain the most words in them.
def get_words_from_file(file_name):
'''
assuming that the input file will have only one word per line.
'''
word_list = []
try:
with open(file_name,"r") as fp:
word_list = fp.read().split('\n')
except Exception as e:
print e
return word_list
# def find_anagram(char_dict,word):
# anagram_list = {}
# if len(word) != 1:
# for char in word:
# tmp_lst = set(filter(lambda x:x.count(char) == word.count(char) and len(x) == len(word) ,char_dict[char]))
# if anagram_list == {}:
# anagram_list = tmp_lst
# else:
# anagram_list = anagram_list.intersection(tmp_lst)
# return anagram_list
# def create_dict(word_list):
# char_dict = {}
# for word in word_list:
# for char in word:
# if char not in char_dict:
# char_dict[char] = {word}
# else:
# char_dict[char].add(word)
# return char_dict
def anagram():
word_list = get_words_from_file("unixdict.txt")
anagram_word_lst = {}
for word in word_list:
sorted_word = "".join(sorted(word))
try:
anagram_word_lst[sorted_word].append(word)
except KeyError:
anagram_word_lst[sorted_word] = [word]
cnt = 0
for _, anagram_list in anagram_word_lst.items():
if len(anagram_list) > 1:
cnt += 1
print anagram_list
print cnt
# if word not in anagram_word_lst:
# lst = find_anagram(char_dict, word)
# if len(lst) > 2:
# print lst, word
# anagram_word_lst.update(lst)
# print anagram_word_lst
if __name__ == "__main__":
anagram()
|
e9bb66acd89cb203f2d10f77c5cbe3d3feac4078 | OlehPalanskyi/Python | /Dz3/Dz3_5.py | 2,439 | 4.3125 | 4 | '''
Написать функцию принимающую имя фигуры (квадрат, треугольник, ромб), ее размерность и рисует эту фигуру на экран.
'''
SYMBOL = '*'
def graph_builder(request):
if request == 'квадрат':
square_side = 10
for i in range(1, square_side + 1):
print(SYMBOL * square_side)
elif request == 'треугольник':
triangle_side = 10
for i in range(1, triangle_side + 1):
if i % 2 != 0:
space_length = (triangle_side - i) // 2
print(' ' * space_length + SYMBOL * i + ' ' * space_length)
elif request == 'ромб':
romb_length = 7
for i in range(1, romb_length + 1):
if i % 2 != 0:
space_length = (romb_length - i) // 2
print(' ' * space_length + SYMBOL * i)
for i in range(romb_length - 1, 0, -1):
if i % 2 != 0:
space_length = (romb_length - i) // 2
print(' ' * space_length + SYMBOL * i)
elif request == 'елочка':
start_point = 2
n = 10
triangle_height = n // 2
if n % 2 != 0:
triangle_height = (n + 1) // 2
start_point = 1
next_point = start_point
for j in range(3):
start_point = next_point
if j == 0:
for i in range(triangle_height):
print(' ' * ((n - start_point) // 2) + '*' * start_point)
if i < triangle_height - 1:
start_point += 2
else:
start_point += 2
for i in range(1, triangle_height):
print(' ' * ((n - start_point) // 2) + '*' * start_point)
if i < triangle_height - 1:
start_point += 2
elif request == 'лесинка':
for i in range(10):
print(' ' * i * 2 + '*' * i * 2)
print(' ' * i * 2 + '*' * i * 2)
else:
print('ошибочный ввод')
# начало основной программы
user_input = input('Введите имя фигуры для отрисовки (квадрат, треугольник, ромб, лесинка, елочка): ').lower()
graph_builder(user_input) |
3344aadb529982ef60e0f72200221a0fcfbb7bf3 | ASKJR/URI-judge | /Python/1551.py | 362 | 3.890625 | 4 | '''
Problem: Frase Completa
URI Online Judge | 1551
Solution developed by: Alberto Kato
'''
N = int(input())
for i in range(0, N):
phraseLen = len(set(input().replace(",", "").replace(" ", "")))
if phraseLen >= 26:
print("frase completa")
elif phraseLen >= 13:
print("frase quase completa")
else:
print("frase mal elaborada")
|
7bbfbda7741adc47f9d193fbe562990857eaa90f | ZackStone/python-para-informatica-exercicios | /src/3_3.py | 537 | 3.921875 | 4 | # coding: utf-8
# Exercício 3.3 Escreva um programa que solicite um valor entre 0.0 e 1.0. Se o
# valor está fora do intervalo imprima um erro. Se o valor está entre 0.0 e 1.0,
# imprima um conceito de acordo com a tabela a seguir:
from decimal import *
try:
p = Decimal(input('Digite uma pontuação: '))
if p >= Decimal('0.9'): print('A')
elif p >= Decimal('0.8'): print('B')
elif p >= Decimal('0.7'): print('C')
elif p >= Decimal('0.6'): print('D')
else: print('F')
except:
print('Pontuação Ruim')
|
6864e3bf060214bf880f4edf9f405ca8770cc3ce | allan-2stars/Templa-Auto | /DS.py | 2,646 | 3.546875 | 4 | def get_standard_deviation_sample(myList, myMean):
sum = 0
listCount = len(myList)
for i in myList:
sum = sum + (i - myMean) ** 2
return (sum / (listCount - 1)) ** (1/2)
def get_standard_deviation(myList, myMean):
sum = 0
listCount = len(myList)
for i in myList:
sum = sum + (i - myMean) ** 2
return (sum / listCount) ** (1/2)
def get_mean(myList):
return sum(myList) / len(myList)
def get_MAD(myList, myMean):
sum = 0
listCount = len(myList)
for i in myList:
sum = sum + abs(i - myMean)
return sum / listCount
myList = [5,4,6,39]
myMean = get_mean(myList)
print("Mean number:", myMean)
myStdDeviationSample = get_standard_deviation_sample(myList, myMean)
print("Standard Sample Deviation:", myStdDeviationSample)
myStdDeviation = get_standard_deviation(myList, myMean)
print("Standard Deviation:", myStdDeviation)
myMAD = get_MAD(myList, myMean)
print("MAD:", myMAD)
''' DS below '''
# pairs = [('a', 1), ('b', 2), ('c', 3)]
# letters, numbers = zip(*pairs)
# print(letters, numbers)
# from matplotlib import pyplot as plt
# years = [1950, 1960, 1970, 1980, 1990, 2000, 2010]
# gdp = [300.2, 543.3, 1075.9, 2862.5, 5979.6, 10289.7, 14958.3]
# # create a line chart, years on x-axis, gdp on y-axis
# plt.plot(years, gdp, color='green', marker='o', linestyle='solid')
# # add a title
# plt.title("Nominal GDP")
# # add a label to the y-axis
# plt.ylabel("Billions of $")
# plt.show()
# movies = ["Annie Hall", "Ben-Hur", "Casablanca", "Gandhi", "West Side Story"]
# num_oscars = [5, 11, 3, 8, 10]
# # bars are by default width 0.8, so we'll add 0.1 to the left coordinates
# # so that each bar is centered
# xs = [i + 0.1 for i, _ in enumerate(movies)]
# # plot bars with left x-coordinates [xs], heights [num_oscars]
# plt.bar(xs, num_oscars)
# plt.ylabel("# of Academy Awards")
# plt.title("My Favorite Movies")
# # label x-axis with movie names at bar centers
# plt.xticks([i + 0.5 for i, _ in enumerate(movies)], movies)
# plt.show()
# from bokeh.plotting import figure, output_file, show
# # prepare some data
# x = [1, 2, 3, 4, 5]
# y = [6, 7, 2, 4, 5]
# # output to static HTML file
# output_file("lines.html")
# # create a new plot with a title and axis labels
# p = figure(title="simple line example", x_axis_label='x', y_axis_label='y')
# # add a line renderer with legend and line thickness
# p.line(x, y, legend="Temp.", line_width=2)
# # show the results
# show(p)
def vector_add(v, w):
"""adds corresponding elements"""
return [v_i + w_i
for v_i, w_i in zip(v, w)]
newSum = vector_add([1, 2],
[2, 3])
print(newSum) |
5ade9defd7e54bd9de37bdfdd4cfc3438cecaafe | morningred88/data-structure-algorithms-in-python | /Array/linear-search.py | 411 | 4.0625 | 4 | # linear search O(n), to get the maximal and minimal number
numbers = [2, 6, 7.8, 9, 10, -12, 10.5]
# Get maxmimal number from the array
max = numbers[0]
for num in numbers:
if num > max:
max = num
print('The maximal number is ' + str(max))
# Get the minimal number from the array
min = numbers[0]
for num in numbers:
if num < min:
min = num
print('The maximal number is ' + str(min))
|
da4bcd426fb8001abfa711b43a0edae0d6e2d70c | flyfire/Programming-Notes-Code | /Python/Python3-Base/10_File/store_user.py | 714 | 3.828125 | 4 | import os
import json
file_name = "user.json"
def get_user_name():
if os.path.exists(file_name) and os.path.isfile(file_name):
with open(file_name, 'r') as user_file:
return json.load(user_file)
def store_user_name(user_name):
with open(file_name, 'w') as user_file:
json.dump(user_name, user_file)
def get_new_name():
user_name = ""
while not user_name:
user_name = input("请输入姓名")
return user_name
def main():
user_name = get_user_name()
if user_name:
print("welcome back, %s" % user_name)
else:
user_name = get_new_name()
print("i will remember your name")
store_user_name(user_name)
main()
|
d536e049635bdcebbd45a832a26c3d2b3d30272c | Lalit554/mycode | /cert_project/alta3research-pythoncert01.py | 25,093 | 3.8125 | 4 | """
Created on Sat May 1 10:41:45 2021
@author: Lalit Patil
@Description: Python Basics Certification Project
"""
####!/usr/bin/env python3
import datetime
from datetime import date
from os import path
import re
import requests
import pprint
import operator
import json
import pyexcel
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('Agg')
def get_observation_dates():
''' Prompt user to enter a date range (maximum of 7 days) to be used to download asteroid observation data.
Validate entered observation dates, date range values and that range does not exceed 7 days.
Return validated "Observation From Date" and "Observation To Date".
Usage : get_observation_dates()
Parameters : None
Returns :
from_date ==> Start of Observation Date
to_date ==> End of Observation Date
'''
while True:
while True: #*** Ensure user enters a valid date as "FROM" date ***
from_date = input("Enter Observation FROM Date (YYYY-MM-DD) : ")
if len(from_date.strip()) == 10:
year,month,day = from_date.split("-")
isValidDate = True
try:
frdate=datetime.date(int(year),int(month),int(day))
if frdate >= date.today():
print("'FROM' Date must be prior to today, please try again ...")
isValidDate = False
except ValueError :
isValidDate = False
print("Invalid Date entered, please try again ...")
if isValidDate : break
while True: #*** Ensure user enters a valid date as "TO" date ***
to_date = input("Enter Observation TO Date (YYYY-MM-DD) : ")
if len(to_date.strip()) == 10:
year,month,day = to_date.split("-")
isValidDate = True
try:
todate=datetime.date(int(year),int(month),int(day))
if todate >= date.today() or todate < frdate: #*** Validate "from" date is less than "to" date ***
print("' TO ' Date must be prior to today and after 'FROM' Date, please try again ...")
isValidDate = False
except ValueError :
isValidDate = False
print("Invalid Date entered, please try again ...")
if isValidDate : break
# convert "FROM" date entered by user into date format
year,month,day = from_date.split("-")
fdt = datetime.date(int(year),int(month),int(day))
# convert "TO" date entered by user into date format
year,month,day = to_date.split("-")
tdt = datetime.date(int(year),int(month),int(day))
if (tdt - fdt).days in range(0,8) : #*** Validate date range is no more than 7 days ***
return from_date, to_date
break
else :
print("Invalid Date range / exceeds 7 days, please try again ...")
#****
def download_nasa_json():
''' Prompt user to enter a date range (maxium of 7 days) to be used to download asteroid observation data.
Download asteroid observation data from api.nasa.gov using DEMO_KEY for the specifed date range
and save the JSON output to "asteriod_data.json" file in current directory/folder.
Usage : download_nasa_json(sdt,tdt)
Parameters :
sdt = FROM Observation Date (YYYY-MM-DD)
tdt = TO Observation Date (YYYY-MM-DD)
Returns : None
'''
(sdt,tdt)=get_observation_dates() # Get Date range from user
Uri="https://api.nasa.gov/neo/rest/v1/feed?start_date="+sdt+"&end_date="+tdt+"&api_key=DEMO_KEY"
r = requests.get(Uri).json()
json_file=open("asteroid_data.json","w")
for json_line in json.dumps(r,indent=2) :
json_file.write(json_line)
json_file.close()
json_file=open("asteroid_data.json","r")
json_data=json.load(json_file)
json_file.close()
if json_data.get("element_count") == 0:
print("No Data found for specified Date Range !!!\n")
#****
def parse_dict_and_create_exceldata():
''' parse downloaded JSON file ("asteroid_data.json") and create following lists based on keys and values in dictionary "near_earth_objects"
a) List of Unique Asteroid Objects and related inforamtion ==> "astroid_info []"
b) List of Asteroid Objects and related information by Date ==> "astroid_uniq_info []"
c) Observation Date List ==> "Date_List []"
Usage : parse_dict_and_create_exceldata()
Parameters : None
Returns :
astroid_info[] ==> List of Asteroids and related information by Date. Same Asteroid could exist for multiple observation dates.
astroid_uniq_info[] ==> List of Unqiue Asteroids and related information regardless of observation date.
Date_List[] ==> List of Observation Dates for which Asteroid information is available in astroid_info[] and astroid_uniq_info[]
'''
data = json.load(open("asteroid_data.json","r"))
Aster_Objs = { "near_earth_objects" : data.get("near_earth_objects") }
#data.pop("links")
#data.pop("element_count")
astroid_info = []
astroid_uniq_info = []
Date_List = []
astroid_data = []
for (RootKey,ValueDict) in Aster_Objs.items(): # root-level dictionary
#print(RootKey)
for Observ_Date in ValueDict.keys(): # Loop for each Date
#print(Observ_Date)
Date_List.append(Observ_Date)
for Astroid_List in ValueDict.values(): # Asteriod Information for each Date
for idx in range(0,len(Astroid_List)):
Astroid_Link = Astroid_List[idx].get("links").get("self")
Astroid_id = Astroid_List[idx].get("id")
Astroid_Neo_Ref_ID = Astroid_List[idx].get("neo_reference_id")
Astroid_name = Astroid_List[idx].get("name")
Astroid_nasa_jpl_url = Astroid_List[idx].get("nasa_jpl_url")
Astroid_magnitude_h = Astroid_List[idx].get("absolute_magnitude_h")
Astroid_est_diam_km_min = Astroid_List[idx].get("estimated_diameter").get("kilometers").get("estimated_diameter_min")
Astroid_est_diam_km_max = Astroid_List[idx].get("estimated_diameter").get("kilometers").get("estimated_diameter_max")
Astroid_est_diam_m_min = Astroid_List[idx].get("estimated_diameter").get("meters").get("estimated_diameter_min")
Astroid_est_diam_m_max = Astroid_List[idx].get("estimated_diameter").get("meters").get("estimated_diameter_max")
Astroid_est_diam_miles_min = Astroid_List[idx].get("estimated_diameter").get("miles").get("estimated_diameter_min")
Astroid_est_diam_miles_max = Astroid_List[idx].get("estimated_diameter").get("miles").get("estimated_diameter_max")
Astroid_est_diam_feet_min = Astroid_List[idx].get("estimated_diameter").get("feet").get("estimated_diameter_min")
Astroid_est_diam_feet_max = Astroid_List[idx].get("estimated_diameter").get("feet").get("estimated_diameter_max")
Astroid_is_pot_hazardous = Astroid_List[idx].get("is_potentially_hazardous_asteroid")
Astroid_close_approach_date = Astroid_List[idx].get("close_approach_data")[0].get("close_approach_date")
Astroid_close_approach_date_full = Astroid_List[idx].get("close_approach_data")[0].get("close_approach_date_full")
Astroid_epoch_date_close_approach = Astroid_List[idx].get("close_approach_data")[0].get("epoch_date_close_approach")
Astroid_rel_velo_km_sec = Astroid_List[idx].get("close_approach_data")[0].get("relative_velocity").get("kilometers_per_second")
Astroid_rel_velo_km_hr = Astroid_List[idx].get("close_approach_data")[0].get("relative_velocity").get("kilometers_per_hour")
Astroid_rel_velo_miles_hr = Astroid_List[idx].get("close_approach_data")[0].get("relative_velocity").get("miles_per_hour")
Astroid_miss_dist_astronm = Astroid_List[idx].get("close_approach_data")[0].get("miss_distance").get("astronomical")
Astroid_miss_dist_lunar = Astroid_List[idx].get("close_approach_data")[0].get("miss_distance").get("lunar")
Astroid_miss_dist_km = Astroid_List[idx].get("close_approach_data")[0].get("miss_distance").get("kilometers")
Astroid_miss_dist_miles = Astroid_List[idx].get("close_approach_data")[0].get("miss_distance").get("miles")
Astroid_orbiting_body = Astroid_List[idx].get("close_approach_data")[0].get("orbiting_body")
Astroid_is_senrty_obj = Astroid_List[idx].get("is_sentry_object")
astroid_data = {"Date" : Observ_Date ,
"links" : Astroid_Link ,
"id" : Astroid_id ,
"neo_reference_id" : Astroid_Neo_Ref_ID ,
"name" : Astroid_name ,
"nasa_jpl_url" : Astroid_nasa_jpl_url ,
"absolute_magnitude_h" : Astroid_magnitude_h ,
"min_est_km_diameter" : Astroid_est_diam_km_min ,
"max_est_km_diameter" : Astroid_est_diam_km_max ,
"min_est_m_diameter" : Astroid_est_diam_m_min ,
"max_est_m_diameter" : Astroid_est_diam_m_max ,
"min_est_miles_diameter" : Astroid_est_diam_miles_min ,
"max_est_miles_diameter" : Astroid_est_diam_miles_max ,
"min_est_feet_diameter" : Astroid_est_diam_feet_min ,
"max_est_feet_diameter" : Astroid_est_diam_feet_max ,
"is_potentially_hazardous" : Astroid_is_pot_hazardous ,
"close_approach_date" : Astroid_close_approach_date ,
"epoch_date_close_approach" : Astroid_epoch_date_close_approach ,
"close_approach_date_full" : Astroid_close_approach_date_full ,
"relative_velocity_km_per_sec" : Astroid_rel_velo_km_sec ,
"relative_velocity_km_per_hr" : Astroid_rel_velo_km_hr ,
"relative_velocity_miles_per_hr" : Astroid_rel_velo_miles_hr ,
"miss_distance_in_astro_units" : Astroid_miss_dist_astronm ,
"miss_distance_in_lunar_units" : Astroid_miss_dist_lunar ,
"miss_distance_in_km_units" : Astroid_miss_dist_km ,
"miss_distance_in_miles_units" : Astroid_miss_dist_miles ,
"orbiting_body" : Astroid_orbiting_body ,
"is_sentry_object" : Astroid_is_senrty_obj }
astroid_info.append(astroid_data)
Uniq_loaded = "N"
for aptr in range(0,len(astroid_uniq_info)):
if astroid_uniq_info[aptr].get("id") == Astroid_id:
#print(f"Astroid_id = {Astroid_id} already loaded !!")
Uniq_loaded = "Y"
break
if Uniq_loaded == "N":
astroid_uniq_info.append(astroid_data)
if astroid_data :
return True, astroid_info, astroid_uniq_info, Date_List
else: return False , astroid_info, astroid_uniq_info, Date_List
#****
def list_Hazardous_Asteroids(ADict,NonEmptyDict):
''' Read [Unique List] of Asteroids and related observation data extracted from api.nasa.gov.
Print list of Asteroids which are deemed "Hazardous"
Usage : list_Hazardous_Asteroids(ADict,NonEmptyDict)
Parameters :
ADict = Dictionary containing unique list of asteroids and related observation data
NonEmptyDict = Empty Status of "ADict" dictionary (True/False)
Returns : None
'''
if not NonEmptyDict :
print("\n\nAsteroid Information file is missing or empty !!!\n")
else:
Hazardous_Asteroid_Found="N"
#print(type(ADict))
for idx in range(0,len(ADict)):
h_ctr = 0 # Count Hazardours Asteroids
#print("{}. Name = {} is potentially Hazardous {}".format(idx,ADict[idx].get("name"),ADict[idx].get("is_potentially_hazardous")))
if ADict[idx].get("is_potentially_hazardous"):
h_ctr += 1
if h_ctr == 1 :
print("\n")
print("************************************************")
print("******* List of Hazardous Astroids *********")
print("************************************************")
#print("\n\n")
print("Sr.No. Astroid Id Astroid_Name ")
print("------ ---------- -----------------------------")
print("{}. {} {}".format(h_ctr,ADict[idx].get("id"),ADict[idx].get("name")))
else:
print("{}. {} {}".format(h_ctr,ADict[idx].get("id"),ADict[idx].get("name")))
Hazardous_Asteroid_Found = "Y"
if Hazardous_Asteroid_Found == "N":
print("No Hazardous Asteroids found !!!")
print("\n\n")
#****
def list_top_5_largest_asteroids(ADict,NonEmptyDict):
''' Read [Unique List] of Asteroids and related observation data extracted from api.nasa.gov.
Print list of top 5 largest Asteroids
Usage : list_top_5_largest_asteroids(ADict,NonEmptyDict)
Parameters :
ADict = Dictionary containing unique list of asteroids and related observation data
NonEmptyDict = Empty Status of "ADict" dictionary (True/False)
Returns : None
'''
if not NonEmptyDict :
print("\n\nAsteroid Information file is missing or empty !!!\n")
else:
SortedADict = sorted(ADict, key = lambda i: i['absolute_magnitude_h'], reverse=True)
print("\n")
print("*********************************************************")
print("******* List of Top 5 Largest Asteroids *************")
print("*********************************************************")
#print("\n\n")
print("Sr.No. Astroid Id Astroid_Name Magnitude_h")
print("------ ---------- ----------------------------- -----------")
for idx in range(0,5) :
print("{}. {}\t {}\t {}".format(idx+1,SortedADict[idx].get("id"),SortedADict[idx].get("name").strip(),SortedADict[idx].get("absolute_magnitude_h")))
print("\n\n")
#****
def get_magnitude_crieria():
''' Prompt user to enter a criteria to filter Asteroids by.
Validate entered criteria and Return validated criteria comparison operator and comparison value.
Usage : get_magnitude_crieria()
Parameters : None
Returns :
Mag_H ==> {VALUE} to compare with Asteroid's Absolute Magnitude H
Compare_Operator ==> {COMPARISON OPERATOR} to be used to perform the comparison
Possible values are :
">"
"<"
">="
"<="
"="
"!="
'''
ops = ['>' , '<' , '>=' , '<=' , '=' , '!=' , '<>' , '==' ]
Compare_operator = ""
Meg_H = ""
while Compare_operator not in ops:
Compare_operator=input(f"\n\nEnter a valid comparison opertor {ops} : ")
while not Meg_H.replace('.','').isnumeric() :
Meg_H=input("Enter Absolute Magnitude (H) value to use for comparision : ")
print("\n\n")
return Meg_H,Compare_operator
#****
def filter_by_magnitude(ADict,Mag,criteria,NonEmptyDict):
''' Read [Unique List] of Asteroids and related observation data extracted from api.nasa.gov.
Print list of Asteroids which satisfy the user query criteria of Asteroid's absolute magnitude (H).
Usage : filter_by_magnitude(ADict,Mag,criteria,NonEmptyDict)
Parameters :
ADict = Dictionary containing unique list of asteroids and related observation data
Mag = Asteroid's Absolute Magnitude (H)
criteria = comparison operator to be used to compare Asteroid's absolute magnitude (H) with "Mag" parameter.
Acceptable parameter /argument values are :
">"
"<"
">="
"<="
"="
"!="
NonEmptyDict = Empty Status of "ADict" dictionary (True/False)
Returns : None
'''
ops = {'>' : operator.gt , '<' : operator.lt, '>=' : operator.ge, '<=' : operator.le, '=' : operator.eq, '!=' : operator.ne, '<>' : operator.ne, '==' : operator.eq}
if not NonEmptyDict :
print("\n\nAsteroid Information file is missing or empty !!!\n")
else:
print("\n")
print("************************************************************************************")
print("**************** List of Asteroids with magnitude {} {} ***********************".format(criteria,Mag))
print("************************************************************************************")
print("Sr.No. Astroid Id Astroid_Name Magnitude_h")
print("------ ---------- ----------------------------- -----------")
ctr=0
for idx in range(0,len(ADict)):
if ops[criteria](float(ADict[idx].get("absolute_magnitude_h")),float(Mag)):
ctr += 1
print("{}. {}\t {}\t {}".format(ctr,ADict[idx].get("id"),ADict[idx].get("name").strip(),ADict[idx].get("absolute_magnitude_h")))
print("\n\n")
#****
def bar_chart(ADict,DL,NonEmptyDict):
''' Plot a bar chart for "Hazardous" vs. "Non Hazardous" asteroid counts by observation date and save it to a file "Asteroid_bar_chart.png"
Usage : filter_by_magnitude(ADict,DL,NonEmptyDict)
Parameters :
ADict = Dictionary containing list of asteroids and related observation data by observation dates
DL = List of Observation Dates
NonEmptyDict = Empty Status of "ADict" dictionary (True/False)
Returns : None
'''
if not NonEmptyDict :
print("\n\nAsteroid Information file is missing or empty !!!\n")
else:
N = len(DL)
Hazardous_Count = []
Non_Hazardous_Count = []
for idx in range(0,N):
Hazardous_Count.append(0)
Non_Hazardous_Count.append(0)
max_ytick = 0
for idx in range(0,len(ADict)):
for DL_ctr in range(0, len(DL)):
if ADict[idx].get("Date") == DL[DL_ctr]:
break
if ADict[idx].get("is_potentially_hazardous"):
Hazardous_Count[DL_ctr] += 1
else:
Non_Hazardous_Count[DL_ctr] += 1
if (Hazardous_Count[DL_ctr] > max_ytick) : max_ytick = Hazardous_Count[DL_ctr]
if (Non_Hazardous_Count[DL_ctr] > max_ytick) : max_ytick = Non_Hazardous_Count[DL_ctr]
print("Hazardous_Count = ",Hazardous_Count)
print("Non_Hazardous_Count = ",Non_Hazardous_Count)
ind = np.arange(N)
#width = 0.8 #if only 2 dates
width = 1.6 / N #if 7 dates
HCnt = []
NHCnt = []
for idx in range(0,N):
HCnt.append(Hazardous_Count[idx])
NHCnt.append(Non_Hazardous_Count[idx])
p1 = plt.bar(ind, HCnt, width)
p2 = plt.bar(ind, NHCnt, width, bottom=Hazardous_Count)
# Describe the table metadata
plt.ylabel("Asteroid Count")
plt.title("Asteroid Count Summary by Day")
plt.autoscale()
plt.xticks(ind, DL, fontsize='xx-small')
#plt.yticks(np.arange(0, 50, 5)) #if only 2 dates
plt.yticks(np.arange(0, max_ytick, int(max_ytick/10)))
plt.legend((p1[0], p2[0]), ("Hazardous Count", "Non Hazardous Count"))
# display the graph
# plt.show() # you can try this on a Python IDE with a GUI if you'd like
plt.savefig("Asteroid_bar_chart.png")
print("\nBar chart saved to 'Asteroid_bar_chart.png' file\n")
#****
def main():
''' Asteroid Data Analysis program.
(a) Extract Asteroid Data from api.nasa.gov for up to 7 days
(b) Parse and store asteroid data extracted in JSON file for analysis
Usage : python3 alta3research-pythoncert01.py
Parameters : None
Returns : None
'''
print("*************************************************")
print("***** Welcome to Asteriod Exploration *****")
print("*************************************************")
print("( !! Limit you exploration to only seven days !! )\n")
errmsg=""
Data_Found = False
Astroid_Dict = []
Uniq_Astroid_Dict = []
DateLst = []
#print("File Size = {}".format(path.getsize("asteroid_data.json")))
if path.exists("asteroid_data.json") and path.getsize("asteroid_data.json") >= 448 :
(Data_Found,Astroid_Dict,Uniq_Astroid_Dict,DateLst) = parse_dict_and_create_exceldata()
if not Data_Found :
errmsg = "\n\nAsteroid Information file is EMPTY, choose option '1' to download data first !!!\n"
else:
Data_Found = True
else:
errmsg = "\n\nAsteroid Information file NOT FOUND, choose option '1' to download data first !!!\n"
if not Data_Found :
print(errmsg)
while True:
print("\n")
print("(1) : Download Astroid Data from api.nasa.gov (max 7 days)")
print("(2) : Convert Astroid Info to Excel - Astroid_Info.xls")
print("(3) : List Hazardous Astroid Names")
print("(4) : Top 5 largest Asteroids")
print("(5) : Query Asteroids by magnitude")
print("(6) : Bar Chart of Hazardous Asteroids")
print("(7) : Change Date Selection")
print("(Q) : Quit")
opt_list = [ '1', '2', '3', '4', '5', '6', '7', 'Q' ]
user_opt = input("Enter Option Number (1-7,Q) >>> ").strip().upper()
if user_opt not in opt_list :
print("\nInvalid Option, please try again ...")
elif user_opt == '1':
download_nasa_json()
(Data_Found,Astroid_Dict,Uniq_Astroid_Dict,DateLst) = parse_dict_and_create_exceldata()
elif user_opt == '2':
pyexcel.save_as(records=Astroid_Dict, dest_file_name='Astroid_Info.xls')
print("\nAsteroid Data downloded to excel file 'Astroid_Info.xls'\n")
elif user_opt == '3':
list_Hazardous_Asteroids(Uniq_Astroid_Dict,Data_Found)
elif user_opt == '4':
list_top_5_largest_asteroids(Uniq_Astroid_Dict,Data_Found)
elif user_opt == '5':
(Asize,Acriteria)=get_magnitude_crieria()
filter_by_magnitude(Uniq_Astroid_Dict,Asize,Acriteria,Data_Found)
elif user_opt == '6':
bar_chart(Astroid_Dict,DateLst,Data_Found)
elif user_opt == '7':
download_nasa_json()
(Data_Found,Astroid_Dict,Uniq_Astroid_Dict,DateLst) = parse_dict_and_create_exceldata()
elif user_opt == 'Q' :
break
#****
if __name__ == "__main__":
main()
|
57cfb2a0d723a1036477915cfcea22c4516a955a | a19camoan/Ejercicios_Programacion_Python | /EstructurasSecuencialesPython/12.py | 1,252 | 4.40625 | 4 | from math import sqrt
#Exportamos sqrt para poder calcular raíces cuadradas.
'''
Pide al usuario dos pares de números x1,y2 y x2,y2, que representen dos puntos en el plano. Calcula y muestra la distancia entre ellos.
Autor: Andrés Castillero Moriana.
Fecha: 09/10/2021
Algoritmo:
Variables:
x1 (real): Introducido por el usuario. La coordenada x del primer punto la cual usaremos para calcular la distancia.
y1 (real): Introducido por el usuario. La coordenada y del primer punto la cual usaremos para calcular la distancia.
x2 (real): Introducido por el usuario. La coordenada x del segundo punto la cual usaremos para calcular la distancia.
y2 (real): Introducido por el usuario. La coordenada y del segundo punto la cual usaremos para calcular la distancia.
'''
x1=float(input("Introduzaca la coordenada x del primer punto: "))
y1=float(input("Introduzaca la coordenada y del primer punto: "))
x2=float(input("Introduzaca la coordenada x del segundo punto: "))
y2=float(input("Introduzaca la coordenada y del segundo punto: "))
#Esta variable es prescindible pero la usaré para simplificar el print.
dist = round(sqrt((x2-x1)**2 + (y2-y1)**2), 3)
print("La distancia entre los 2 puntos es de:", dist, "u") |
f0822bbd652bce513afd6a2d5011b08c4a5b5d47 | JackeviciusR/Maximal-Palindrome | /maximalPalindrome.py | 1,208 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 21 13:14:38 2020
@author: Rokas
"""
import numpy as np
import math
# SPAUSDINIMUS REIKIA UZKOMENTUOTI, NES SULETINA IR 30 TESTU NEPRAEINA, O TIK 26
def maximalPalindrome(s):
s_list = list(s)
#print(s_list)
s_list.sort()
#print('>', s_list)
unique_list = list(set(s_list))
unique_list.sort()
#print('>>', unique_list)
odd_letter = []
letter_times = []
half_pol_left = []
s_arr = np.array(s_list)
#print(s_arr)
for unique in unique_list:
ind_letter = np.where(s_arr == unique)
times = len(ind_letter[0])
if times%2 == 1:
odd_letter.append(unique)
letter_times.append(unique)
if times > 1:
half_pol_left.extend(list(unique * (times//2))) # 3//2=1
half_pol_right = sorted(half_pol_left, reverse = True)
if len(odd_letter) > 0:
palindrome = half_pol_left + list(odd_letter[0]) + half_pol_right
else:
palindrome = half_pol_left + half_pol_right
palindrome_last = "".join(palindrome)
#print(palindrome_last)
return palindrome_last
|
e37b45a7e9b31a9d0885479b09dc3b667d407787 | chebrolurp/Algo | /recursion.py | 436 | 4.25 | 4 | #find the factorial and of a number and n th fibonacci
n = int(raw_input("enter the number", ))
def factorial(n):
if n == 2 or n == 1:
return n
elif n>2:
return n*factorial(n-1)
else:
print "enter a positive number"
def fibonacci(n):
if n <= 2 :
return 1
else:
return (fibonacci(n-1) + fibonacci(n-2))
x = factorial(n)
y = fibonacci(n)
print("factorial = "+str(x))
print(str(n) + "th fibonacci number is "+ str(y))
|
5da58a7853341300496a5407516e85a150854d1f | deep110/aoc-solutions | /2021/day08/solution.py | 436 | 3.515625 | 4 | from os import path
with open(path.join(path.dirname(__file__), "input.txt")) as f:
ms = f.readlines()
def part1():
outputs = list(map(lambda x: x.strip().split("|")[1].strip().split(" "), ms))
num_times = 0
for out in outputs:
num_times += sum(map(lambda x : len(x) < 5 or len(x) == 7, out))
return num_times
def part2():
pass
print("Part1 solution: ", part1())
print("Part2 solution: ", part2())
|
3de9083c7fd7259661fe92d68e724ade34e38761 | alex-1q84/leetcode | /python/src/leetcode/basic_algorithm/search_in_rotated_sorted_array.py | 689 | 3.625 | 4 | # 202203101845
# https://leetcode-cn.com/problems/search-in-rotated-sorted-array/
# 整数数组 nums 按升序排列,数组中的值 互不相同 。
# 在传递给函数之前,nums在预先未知的某个下标k(0<=k<nums.length)上进行了旋转,使数组变为[nums[k],nums[k+1],...,nums[n-1],nums[0],nums[1],...,nums[k-1]](下标从0开始计数)。例如,[0,1,2,4,5,6,7]在下标3处经旋转后可能变为[4,5,6,7,0,1,2]。
# 给你旋转后的数组nums和一个整数target,如果nums中存在这个目标值target,则返回它的下标,否则返回-1。
from typing import List
class Solution:
def search(self, nums: List[int], target: int) -> int:
|
616ee9dce51ca0a5a9203051a9c244adb90e10e7 | DanielHuang000/PythonGameProgramming | /Previous_works/Can_I_Use_That_Pic.py | 2,297 | 4.09375 | 4 | #This program ask the users several questions to determin if the user are able to use the picture he or she found.
a = input("Did you take or create the image yourself? ")
if a == 'yes':
b = input('Was the picture you created an original idea?')
if b == 'yes':
print('Yes!')
elif b == 'no':
print('No!')
else:
print('When in doubt, do your research to find out if you copied an idea.'
' Otherwise, dont use the picture for anything other than limited personal use.')
elif a == 'no':
c = input('Are you using the image for personal, non-profit, educational, research, or scholarly purposes'
' and are you using the image sparingly, only for limited purposes? ')
if c == 'yes':
print('Yes!')
elif c == 'no':
d = input('Are you transforming or repurposing the image to create a new purpose or meaning? ')
if d == 'yes':
print('Yes!')
elif d == 'no':
e = input('Are you publishing the image in a fact-based context or publication that benefits the public as a whole'
' (such as in a news source where it is important that people see the image)? ')
if e == 'yes':
print('Probably')
elif e == 'no':
f = input('Would it be considered impossible to obtain permission from the original source? ')
if f == 'yes':
print('Yes!')
elif f == 'no':
print('Will you be using the inage for personal or commerical gain?'
'(If you answered "No" to all the fair use questions,'
' the use of your image would most likely be considered for personal or commercial gain.)')
g = input('Is the image in the public domain or protected by creative commons agreements? ')
if g == 'yes':
print('Yes!')
elif g == 'no':
h = input('Did you purchase the image or obtain permission from the original source? ')
if h == 'yes':
print('Yes!')
elif h == 'no':
print('No!')
|
514570de0ab0971358eefc8608d38ba9eb9e1f24 | sange15308/shiyanlou-code | /jump7.py | 117 | 3.640625 | 4 | i=0
while i<100:
i+=1
if i%7==0:
continue
elif i%10==7:
continue
elif i//10==7:
continue
else:
print(i)
|
3171b71bf679a1a02ffc2dcad267b66e7dc083ea | amaciej/Python | /Zadania3/Comparison/zad2.py | 256 | 3.734375 | 4 | #!/usr/bin/env python3
def number():
zero = 0
num = input("Podaj dowolną liczbę ")
num = int(num)
if num and not zero:
print("wpisałeś: {}".format(num))
else:
print("Wpisałeś liczbę równą zero")
number()
|
6258fde955224573445d0731a4b11b80bb544568 | tekete111011/python-learning | /05/05_4.py | 152 | 4.15625 | 4 | def fibonacci(N):
if N==1:
return 1
elif N==0:
return 0
else:
return fibonacci(N-1)+fibonacci(N-2)
n=int(input())
print(fibonacci(n)) |
394e216bd587abe9eacec40f882a5c49801dc64f | carmoreno1/MentoringDataAnalisis_Week2 | /answers.py | 2,391 | 3.78125 | 4 | import itertools as it
class Exercises():
def __init__(self):
self.MIN_DRIVING_AGE = 18
self.VALID_COLORS =['blue', 'yellow', 'red']
self.text = ''
def is_able_to_drive(self):
try:
name = input("Write your name: ")
age = int(input("Write your age: "))
print(f"{name} is allowed to drive") if age >= self.MIN_DRIVING_AGE else print(f"{name} is not allowed to drive")
except ValueError as e:
print(f"An error has happened {e}")
def check_color(self):
try:
while self.text != 'quit':
self.text = input("Write a color: ").lower()
if self.text == 'quit':
print("bye")
break
elif self.text in self.VALID_COLORS:
print(self.text)
else:
print("Not a valid color")
except Exception as e:
print(f"An error has happened {e}")
def zen_python(self):
zen_text = """
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
"""
try:
zen_list = list(it.chain(zen_text))
for index, item in enumerate(it.chain(zen_text)):
if item.lower() in 'aeiou':
zen_list[index] = '*'
print(''.join(zen_list))
except Exception as e:
print(f"An error has happened {e}")
if __name__ == '__main__':
exercises = Exercises()
# exercises.is_able_to_drive()
# exercises.check_color()
# exercises.zen_python() |
bb194f1655c49f1bd080b32417f7d735e98e27f0 | jpriggs/HackerRank | /Challenges/Algorithms/Warmup/Time Conversion.py | 648 | 3.9375 | 4 | ##################################################################################################
# Given a time in 12-hour AM/PM format, convert it to military (24-hour) time.
#
# A single string containing a time in 12-hour clock format (i.e. hh:mm:ssAM or hh:mm:ssPM), where
# 01 ≤ hh ≤ 12 and 00 ≤ mm, ss ≤ 59. Convert and print the given time in -hour format, where
# 00 ≤ hh ≤ 23.
#
# Coded by: Jason Rigdon
##################################################################################################
#!/bin/python3
import sys
from time import strptime, strftime
print(strftime("%H:%M:%S", strptime(input(), "%I:%M:%S%p")))
|
fa1a00a9a8ca48465fc2caeb799f9c56949ce1cf | alexbook00/CSCI-3104 | /Take-home Final/Final_Q4.py | 687 | 3.828125 | 4 | def valleys(arr):
quarter=(len(arr))//4
ret=[]
ret.append(findValleys(arr,0,quarter-1))
ret.append(findValleys(arr,3*quarter,len(arr)-1))
if len(ret)>0:
return min(ret)
else:
return # no valley
def findValleys(arr,p,r):
if p<=r:
mid=p+(r-p)//2
if arr[mid]<arr[mid-1] and arr[mid]<arr[mid+1]:
return arr[mid] # valley found
elif arr[mid]>arr[mid-1]:
return findValleys(arr,p,mid)
else:
return findValleys(arr,mid,r)
else:
return
if __name__=='__main__':
arr=[10,7,6,2,11,15,20,19,18,17,15,8,6,5,4,3,5,8,9,11]
print(valleys(arr))
|
6508606e651ef755875dcf26cb67e1955150cc9e | ki-ARA-sh/Algorithms_Tutorial | /_042_displacement/tmp.py | 148 | 3.609375 | 4 |
def merge(left):
for i in range(len(left)):
left[i] = 0
return -1
n = 11
a = [1 for i in range(n)]
mid = n // 2
merge(a)
print(a) |
ea4fb2fdd483ca4ab6d5c83663bf52a8d55eb245 | samrao1997/project_euler | /pr077.py | 730 | 3.90625 | 4 | """
It is possible to write ten as the sum of primes in exactly five different ways:
7 + 3
5 + 5
5 + 3 + 2
3 + 3 + 2 + 2
2 + 2 + 2 + 2 + 2
What is the first value which can be written as the sum of primes in over five thousand different ways?
"""
primes = [
2,
3,
5,
7,
11,
13,
17,
19,
23,
29,
31,
37,
41,
43,
47,
53,
59,
61,
67,
71,
73,
79,
]
L, target = 5000, 11
while True:
ways = [1] + [0] * target
for p in primes:
for i in range(p, target + 1):
ways[i] += ways[i - p]
if ways[target] > L:
break
target += 1
print("First value written as the sum of primes \nin over", L, "ways:", target) |
e147988ba67b29b2146c81a3523dcd5654bf2968 | sukhesai/algorithms_and_data_structures | /algorithms and ds/inversions.py | 669 | 3.625 | 4 | import math
def mergesort(a, p, r):
if p < r:
q = p + (r - p)//2
n1 = mergesort(a, p, q)
n2 = mergesort(a, q + 1, r)
n3 = merge(a, p, q, r)
return n1 + n2 + n3
else:
return 0
def merge(a, p, q, r):
la = list(a[p:q + 1]) + [math.inf]
ra = list(a[q + 1:r + 1]) + [math.inf]
i = 0
j = 0
n = 0
n1 = q - p + 1
for k in range(p, r + 1):
if la[i] <= ra[j]:
a[k] = la[i]
i += 1
else:
a[k] = ra[j]
j += 1
n += (n1 - i)
return n
arr = [1, 5, 2, 7, 33, 7, 4, 2, 9]
n = mergesort(arr, 0, len(arr) - 1)
print(n)
|
d2b707589992ba817da18fdbbcb5665a8e17752b | SatyamJindal/Competitive-Programming | /codeforces/Xenia and Bit Operation.py | 930 | 3.65625 | 4 | def build(node,start,end,a,tree):
if(start==end):
tree[node]=a[start]
else:
mid=(start+end)>>1
build(node<<1,start,mid,a,tree)
build(node<<1|1,mid+1,end,a,tree)
tree[node]=tree[node<<1]|tree[node<<1|1]
def update(node,start,end,a,tree,p,b):
if(start==end):
tree[node]=b
a[p]=b
else:
mid=(start+end)>>1
if(p>=start and p<=mid):
update(node<<1,start,mid,a,tree,p,b)
else:
update(node<<1|1,mid+1,end,a,tree,p,b)
tree[node]=tree[node<<1]|tree[node<<1|1]
n,m=map(int,input().split(" "))
a=list(map(int,input().split(" ")))
tree=[0]*(4*(2**n))
build(1,0,2**n-1,a,tree)
if(n!=1):
tree[1]=tree[2]^tree[3]
for I in range(m):
p,b=map(int,input().split(" "))
update(1,0,(2**n)-1,a,tree,p-1,b)
if(n!=1):
tree[1]=tree[2]^tree[3]
print(tree[1])
|
2504ad5c5b160d1824f480451f33e01577e64aac | nbvc1003/python | /ch10/deamon2.py | 444 | 3.828125 | 4 | # while True 에서 '대박' 출력 1초휴식
# 메인에서 사건 10회출력 1초 휴식
# 메인이 끝나면 쓰레드도 종료
import threading, time
class ThreadEx1(threading.Thread):
def run(self) -> None :
i = 0
while True:
i += 1
print('대박', i)
time.sleep(1)
th = ThreadEx1()
th.daemon = True
th.start()
for j in range(10):
print("사건 ", j)
time.sleep(1)
|
cba2a0dc6af6d719edd67ede0473710a87410c3f | brpadilha/exercicioscursoemvideo | /Desafios/Desafio 025.py | 208 | 4.03125 | 4 | #ler um nome e ver se tem Silva no nome
nome=str(input('Digite seu nome: ')).strip()
n=nome.lower().find('silva')
if n==-1:
print('Seu nome não tem Silva.')
else:
print('Seu nome tem Silva.')
|
3285c3d12cf4cae5f73ff27c81f35e76a3f00a92 | curest0x1021/Python-Django-Web | /Woodall_Robert/Assignments/bubble_sort.py | 659 | 3.875 | 4 | import random
import datetime
def bubble_sort(list):
start = datetime.datetime.now()
for i in range(len(list)):
for j in range(len(list) - 1):
if (list[j] > list[j + 1]):
(list[j], list[j + 1]) = (list[j + 1], list[j]) # tuple swap
end = datetime.datetime.now()
return end - start
# create list of random values
sampleList = []
for index in range(100):
sampleList.append(random.randint(0, 10001))
print('sampleList before bubble_sort():\n' + str(sampleList))
executionTime = bubble_sort(sampleList)
print('\nsampleList after bubble_sort():\n' + str(sampleList))
print('\ntotal execution time (hh:mm:ss.microsecs): ' + str(executionTime))
|
9e9e527922d11bf1b1c5be86472b1879a5ed3614 | VarshaSLalapura/PythonAndML | /5-MachineLearningInGeneral/3-SVM-BreastCancerDataUCI/26-SVMFromScratch1.py | 1,246 | 3.5625 | 4 | import numpy as np
from matplotlib import pyplot as plt
from matplotlib import style
style.use('ggplot')
# define a "class" called Support_Vector_Machine
# define the init method with visualization being True
# color
# while True, fig = plt.figure()
# .ax = plt.fig.add_subplot(1,1,1)
# define fit method
# define predict method
# it has decision boundary equation : W.X + b , np.sign(), np.dot, np.array
# return classification
class SupportVectorMachine:
def __init__(self,visualization):
self.visualization = visualization
self.color = {'r': 1, 'k': -1}
if visualization:
self.fig = plt.figure()
self.ax = plt.fig.add_subplot(1,1,1)
# train
def fit(self,data):
pass
# predict
def predict(self, features):
# sign (W.X + b)
# classification = np.sign((np.dot(np.array(features),W )+b))
classification = np.sign(np.dot(np.array(features), self.W) + self.b)
return classification
# create the data dictionary in 2 D, one set for +1 and other set for -1
data_dict = {'r': [[1, 7], [2, 8], [3, 8]],
'k': [[5, 1], [6, -1], [7, 3]]}
# for group in data_dict:
# for data in data_dict[group]:
# print(data)
|
464d093325627385398a4a195999731efa57b740 | jdanray/leetcode | /maskPII.py | 543 | 3.5625 | 4 | # https://leetcode.com/problems/masking-personal-information/
class Solution(object):
def maskPII(self, s):
def maskEmail(s):
s = s.lower()
name, domain = s.split("@")
return name[0] + "*****" + name[-1] + "@" + domain
def maskPhone(s):
sep = {"+", "-", "(", ")", " "}
num = "".join(c for c in s if c not in sep)
res = "***-***-" + str(num[-4:])
if len(num) == 10:
return res
else:
return "+" + ("*" * (len(num) - 11)) + "*-" + res
if "@" in s:
return maskEmail(s)
else:
return maskPhone(s)
|
178dadce9c9fa0e80028b91aeb4801d6c6418153 | Advancedouh/leetcode | /editor/cn/[206]反转链表.py | 1,198 | 4 | 4 | # 反转一个单链表。
#
# 示例:
#
# 输入: 1->2->3->4->5->NULL
# 输出: 5->4->3->2->1->NULL
#
# 进阶:
# 你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
# Related Topics 链表
# 👍 1349 👎 0
# leetcode submit region begin(Prohibit modification and deletion)
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
pre = None
cur = head
while (cur):
# 暂存反转节点下一个节点
next = cur.next
#反转链表
cur.next = pre
# 更新pre节点
pre = cur
# 更新当前节点
cur = next
return pre
# leetcode submit region end(Prohibit modification and deletion)
if __name__ == "__main__":
a1 = ListNode(1)
a2 = ListNode(2)
a3 = ListNode(3)
a4 = ListNode(4)
a5 = ListNode(5)
a1.next=a2
a2.next=a3
a3.next=a4
a4.next=a5
res = Solution().reverseList(a1)
while res:
print(res.val)
res=res.next
|
0871f061d87afd616fe7c53735057f3966761a43 | kemingy/daily-coding-problem | /src/intersect_list.py | 1,608 | 3.875 | 4 | # Given two singly linked lists that intersect at some point, find the
# intersecting node. The lists are non-cyclical.
class LinkNode:
def __init__(self, value):
self.value = value
self.next = None
class LinkList:
def __init__(self, values):
if not values:
self.head = None
self.head = LinkNode(values[0])
current = self.head
for v in values[1:]:
current.next = LinkNode(v)
current = current.next
current.next = None
def display(self):
p = self.head
print('LinkList values:', end=' ')
while p:
print(p.value, end=' ')
p = p.next
print()
@property
def length(self):
count = 0
p = self.head
while p:
p = p.next
count += 1
return count
def intersect_point(x, y):
len_x, len_y = x.length, y.length
p_x, p_y = x.head, y.head
if len_x > len_y:
p_x = p_x.next
len_x -= 1
if len_y > len_x:
p_y = p_y.next
len_y -= 1
while p_x != p_y:
p_x = p_x.next
p_y = p_y.next
return p_x.value if p_x else None
if __name__ == '__main__':
x = LinkList([1, 3, 5])
y = LinkList([2, 4])
intersect = LinkList([7, 8, 9])
for link in [x, y]:
p = link.head
while p.next:
p = p.next
p.next = intersect.head
link.display()
print('Intersect value: {}'.format(intersect_point(x, y)))
|
120a2077c7c7711cb1075132fd1ea772e9770c41 | felipemjribeiro/hackerrankIAPUCLP | /Python If-Else.py | 583 | 3.953125 | 4 | #!/bin/python
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(raw_input().strip())
if(n % 2) != 0: #If is odd, print Weird
print ("Weird")
elif n >= 2 and n <= 5: #If is even and in the inclusive range of to , print Not Weird
print ("Not Weird")
elif n >= 6 and n <= 20: #If is even and in the inclusive range of to , print Weird
print ("Weird")
elif n > 20: #If is even and greater than , print Not Weird
print ("Not Weird") |
554730e66b6b8daca1e7c83d498ea02b5bb9be99 | dfarfel/QA_Learning_1 | /List/list_task_21.py | 166 | 3.625 | 4 | import random
ran_num=random.randrange(1000,9999)
user_num=int(input("Guess the number: "))
while user_num!=ran_num:
user_num = int(input("Guess the number: "))
|
0a692706f6bea33c62656ae97e22d3c46f4ae164 | zaighumg20/CSCE-204 | /Exercises/Feb16/rainbow.py | 460 | 3.828125 | 4 | import turtle
turtle.setup(575,575)
pen = turtle.Turtle()
pen.speed(0)
pen.pensize(5)
pen.hideturtle()
#make a tuple to hold the color of the rainbow
colors =("violet", "indigo", "blue", "green", "yellow", "orange", "red")
arcLength = 200
counter = 0
for color in colors:
pen.up()
pen.setpos(-arcLength/2, counter * 10 )
pen.down()
pen.color(color)
pen.setheading(60)
pen.circle(-arcLength,120)
counter += 1
turtle.done() |
e378a26122f1a69416f0b0f4475791447682fcaa | hamdea98/- | /اضواء.py | 3,118 | 3.703125 | 4 | from turtle import*
import math
def k1():#Enemy Key Commands
enemy.left(90)
enemy.forward(10)
enemy.right(90)
def k2():
enemy.left(90)
enemy.backward(10)
enemy.right(90)
def k3():#Yertle Key Commands
yertle.left(90)
yertle.forward(10)
yertle.right(90)
def k4():
yertle.left(90)
yertle.backward(10)
yertle.right(90)
def k5():
a=bullet_red()
a.speed(10)
a.forward(400)
collision= math.sqrt(math.pow(a.xcor()-yertle.xcor(),2)+math.pow(a.ycor()-yertle.ycor(),2))
if(collision<10):
text=enemy.write("Game Over", align="center" , font=("Arial", 16, "normal"))
a.hideturtle()
def k6():
a=bullet_blue()
a.speed(10)
a.forward(400)
collision= math.sqrt(math.pow(a.xcor()-yertle.xcor(),2)+math.pow(a.ycor()-yertle.ycor(),2))
if(collision<10):
text=enemy.write("Game Over", align="center" , font=("Arial", 16, "normal"))
a.hideturtle()
def collision(a, b):
collision= math.sqrt(math.pow(a.xcor()-b.xcor(),2)+math.pow(a.ycor()-b.ycor(),2))
if(collision<5):
print("Bottom Player Wins")
print("Game Over")
def bullet_red():
bullet=Turtle("circle")#Description For Bullet
bullet.color("red")
bullet.penup()
bullet.goto(enemy.pos())
bullet.setheading(180)
bullet.right(90)
return bullet
def bullet_blue():
bullet=Turtle("circle")#Description For Bullet
bullet.color("blue")
bullet.penup()
bullet.goto(yertle.pos())
bullet.setheading(180)
bullet.right(90)
return bullet
ops = Screen()
ops.setup(500, 500)
ops.onkey(k1, "a")#Enemy
ops.onkey(k2, "d")#Enemy
ops.onkey(k3, "Left")#Yertle
ops.onkey(k4, "Right")#Yertle
ops.onkey(k5, "w")#Shoot(Enemy)
ops.onkey(k6, "Up")#Shoot(Enemy)
ops.listen()
checkpoint_1=Turtle(shape="circle")#Turtle Description for Checkpoint 1
checkpoint_1.color("red")
checkpoint_1.setheading(180)
checkpoint_1.right(90)
checkpoint_1.penup()
checkpoint_1.setx(-220)
checkpoint_1.sety(230)
checkpoint_1.speed(0)
#_____________________________
checkpoint_2=Turtle(shape="circle")#Turtle Description for Checkpoint 2
checkpoint_2.color("red")
checkpoint_2.setheading(180)
checkpoint_2.right(90)
checkpoint_2.penup()
checkpoint_2.setx(220)
checkpoint_2.sety(230)
checkpoint_2.speed(0)
#____________________________
runner=Turtle(shape="turtle")#Turtle Description for Checkpoint 2
runner.color("yellow")
while(runner!=collision):
runner.penup()
runner.goto(checkpoint_1.pos())
runner.goto(checkpoint_2.pos())
runner.speed(0)
#_____________________________
enemy=Turtle(shape="turtle")#Turtle Description for Player 1
enemy.color("red")
enemy.setheading(180)
enemy.right(90)
enemy.penup()
enemy.setx(-20)
enemy.sety(-200)
enemy.speed(0)
#_____________________________
yertle = Turtle(shape="turtle")#Turtle Description for Player 2
yertle.color("blue")
yertle.setheading(180)
yertle.right(90)
yertle.penup()
yertle.setx(20)
yertle.sety(-200)
yertle.speed(0)
|
c4e6d57882f24da62bbeaf4ccedf669ee107b99b | LuukHendriks99/Python | /Les 5/pe5_1.py | 234 | 3.578125 | 4 | def convert(waarde):
return waarde * 1.8 + 32
def table(x):
print('{0:6}{1:10}'.format(' C', ' F'))
for waarde in x:
print('{0:6.2f}{1:10}'.format(convert(waarde), waarde))
table(range(-30, 41, 10))
|
68dafeb35ab23d4dd24635c4b42242be0915ca43 | Vantime03/Python-Full-Stack-Course | /Python/practice_list/problem3_practice_list.py | 405 | 4.15625 | 4 | '''
Problem 3
Write a function that takes a list of numbers, and returns True if there is an even number of even numbers.
eveneven([5, 6, 2]) → True
eveneven([5, 5, 2]) → False
'''
ls1 = [5, 6, 2, 4, 6]
ls2 = [5, 5, 2]
def is_list_even(ls1):
count = 0
for i in ls1:
if i%2 == 0:
count += 1
return count % 2 == 0
def main():
print(f"{is_list_even(ls1)}")
main() |
6ef76f3b70128dda7582a040aa53c0ca6686f4d0 | UzairJ99/PythonLeetCode | /maxHeap.py | 2,841 | 4.1875 | 4 | class MaxHeap:
def __init__(self, items=[]):
#we don't use the first index because of left/right child index calculations
self.heap = [0]
for i in items:
self.heap.append(i)
self.floatUp(len(self.heap)-1)
#insert into heap
def push(self, data):
#add to list
self.heap.append(data)
#move up the heap
self.floatUp(len(self.heap)-1)
#check the max element
def peek(self):
#check if top of heap exists
if self.heap[1]:
return self.heap[1]
else:
return False
#remove the max element
def pop(self):
if len(self.heap) > 2:
#swap largest and smallest element
self.swap(1, len(self.heap)-1)
#returns last element in list aka largest value
max = self.heap.pop()
#move the element back into place
self.bubbleDown(1)
elif len(self.heap) == 2:
max = self.heap.pop()
else:
max = False
return max
#swap index values
def swap(self, i, j):
self.heap[i], self.heap[j] = self.heap[j], self.heap[i]
#shift an element up the heap
def floatUp(self, index):
parent = index//2
if index <= 1:
return
elif self.heap[index] > self.heap[parent]:
#swap
self.swap(index, parent)
#repeat float up until the element is at it's appropriate location
self.floatUp(parent) #parent is the new index
#shift an element down the heap
def bubbleDown(self, index):
leftChild = index*2
rightChild = index*2+1
largest = index
#determine which child to swap with
if len(self.heap) > rightChild:
#if the current element is larger than both the children we don't need to bubble down
if self.heap[index] > self.heap[leftChild] and self.heap[index] > self.heap[rightChild]:
return
elif self.heap[leftChild] > self.heap[rightChild]:
largestChild = leftChild
print("largest child:" , self.heap[largestChild])
else:
largestChild = rightChild
print("largest child:" , self.heap[largestChild])
#needed in the case where there is only one child (must be left child)
elif len(self.heap) == rightChild:
if self.heap[index] > self.heap[leftChild]:
return
else:
largestChild = leftChild
else:
return
#swap values
self.swap(largest, largestChild)
#bubbleDown the new largestChild value
self.bubbleDown(largestChild)
|
f820d854e0fbef0ca317b4b0bc67ac9d0afc8d5b | chelseyh485/ciss441 | /a2/a2.py | 1,925 | 3.890625 | 4 | import json
import csv
import sqlite3
import sys
db_file = 'fifa.db'
conn = sqlite3.connect(db_file)
def create_fifa_table():
"""
Here i am creating the table for my data.
"""
c = conn.cursor()
sql_str = """
create table if not exists fifa (
id integer primary key autoincrement,
Name text,
Age text,
Nationality text,
Club text
);
"""
c.execute(sql_str)
conn.commit()
def process_csv_file():
c = conn.cursor()
with open('data3/fifa.csv', 'r') as csvfile:
# parse csv file pointer into hero_stream
fifa_stream = csv.DictReader(csvfile, delimiter=',', quotechar='"')
# interate over hero_stream to process.
for r_ct, fifa_data_row in enumerate(fifa_stream):
fifa_name = fifa_data_row['Name']
fifa_age = fifa_data_row['Age']
fifa_nationality = fifa_data_row['Nationality']
fifa_club = fifa_data_row['Club']
# only show the first 20 rows.
if r_ct <= 50:
strsql = """
insert into fifa ( Name, Age, Nationality, Club) values (
'{fifa_name}',
'{fifa_age}',
'{fifa_nationality}',
'{fifa_club}'
);
""".format(
fifa_name=fifa_name,
fifa_age=fifa_age,
fifa_nationality=fifa_nationality,
fifa_club=fifa_club
)
c.execute(strsql)
conn.commit()
# only show the first 20 rows.
if r_ct <= 20:
print(r_ct, fifa_name, fifa_age, fifa_nationality, fifa_club)
def main():
print('Creating a Fifa DB from a csv file.')
create_fifa_table()
process_csv_file()
if __name__ == "__main__":
main()
|
4414111c4d40696c3725fd4b98bba60779fc4783 | srth21/Data-Structures-Implementations-and-Applications | /Heap/arrayHeap.py | 2,995 | 3.703125 | 4 | '''
1. complete except for the last level
2. max or min heap
3. root at arr[0]
4. for the ith node :
arr[(i-1)/2]-> parent
arr[2*i+1]-> left child
arr[2*i+2]-> right child
Operations ( Min heap )
1. getMinimum() : O(1)
2. extractMinimum : removes the minimum element from the heap
needs to call heapify. O(logN)
3. decreaseKey : decrease the value and then maybe heapify O(logN)
4. insert() : O(logN)
5. delete(k) : O(logN)
decrease key(k,-inf)
heapify()
extractMin()
'''
class heap:
def __init__(self,n):
self.size=n
arr=[float('inf')]*n
self.arr=arr
self.currSize=0
def leftChild(self,i):
return (2*i)+1
def rightChild(self,i):
return (2*i)+2
def parent(self,i):
return (i-1)//2
def getMinimum(self):
return self.arr[0]
def heapify(self,i):
l=self.leftChild(i)
r=self.rightChild(i)
#print(l,r)
#print("here")
#print(self.arr[l],self.arr[r])
smallest=i
if(l<self.size and self.arr[l]<self.arr[i]):
smallest=l
if(r<self.size and self.arr[r]<self.arr[smallest]):
smallest=r
if(smallest!=i):
temp=self.arr[i]
self.arr[i]=self.arr[smallest]
self.arr[smallest]=temp
self.heapify(smallest)
def insert(self,key):
if(self.currSize==self.size):
print("heap full.")
else:
self.arr[self.currSize]=key
self.currSize+=1
i=self.currSize-1
while(i!=0 and self.arr[self.parent(i)]>self.arr[i]):
temp=self.arr[i]
self.arr[i]=self.arr[self.parent(i)]
self.arr[self.parent(i)]=temp
i=self.parent(i)
def decreaseKey(self,i,newVal):
self.arr[i]=newVal
#print(self.arr)
while(i!=0 and self.arr[self.parent(i)]>self.arr[i]):
temp=self.arr[i]
self.arr[i]=self.arr[self.parent(i)]
self.arr[self.parent(i)]=temp
i=self.parent(i)
#print(self.arr)
def extractMin(self):
#print(self.arr,self.currSize)
if(self.currSize==0):
print("heap empty.")
return
if(self.currSize==1):
self.currSize-=1
return self.arr[0]
#print("here")
#print(self.arr,self.currSize)
root=self.arr[0]
self.arr[0]=self.arr[self.currSize-1]
self.arr[self.currSize-1]=float('inf')
self.currSize-=1
#print(self.arr)
#print("calling heapify")
self.heapify(0)
return root
def delete(self,i):
self.decreaseKey(i,-1000000)
#print(self.arr)
self.extractMin()
#print(self.arr)
def replaceMin(self,key):
root=self.arr[0]
self.arr[0]=key
if(root<key):
self.heapify(0)
return root
'''
heap=heap(10)
#print(heap.currSize,heap.size)
heap.insert(10)
heap.insert(12)
heap.insert(11)
heap.insert(9)
heap.insert(18)
heap.insert(4)
print(heap.arr,heap.currSize)
heap.delete(0)
print(heap.arr,heap.currSize)
print(heap.getMinimum())
heap.delete(0)
print(heap.arr)
print(heap.getMinimum())
heap.insert(10)
heap.insert(12)
heap.insert(11)
heap.insert(9)
heap.insert(18)
heap.insert(4)
heap.insert(100)
print(heap.arr,heap.currSize)''' |
57379d291c2548ec62d6b502ff6a65bdaab3413c | wxke/LeetCode-python | /507 完美数.py | 537 | 3.53125 | 4 | 完美数
class Solution:
def checkPerfectNumber(self, num):
"""
:type num: int
:rtype: bool
"""
if num <2:
return False
import math
q = int(math.sqrt(num))
# print(q)
sum1 = 0
for i in range(1,q+1):
if num % i ==0:
# print(i,num//i)
sum1 += i
sum1 += num // i
if sum1 - num == num:
return True
return False
|
00939abed18ddaa5b5224548d5fadfb778bc958c | QueerDeer/ALLRGB_SOUND | /allrgb_cipher/hilbert.py | 2,003 | 3.6875 | 4 | class Hilbert:
"""Multi-dimensional Hilbert space-filling curve.
"""
def __init__(self, n):
"""Create an n-dimensional Hilbert space-filling curve.
"""
self.n = n
self.mask = (1 << n) - 1
def encode(self, index):
"""Convert index to coordinates of a point on the Hilbert curve.
"""
# Compute base-n digits of index.
digits = []
while True:
index, digit = divmod(index, self.mask + 1)
digits.append(digit)
if index == 0:
break
# Start with largest hypercube orientation that preserves
# orientation of smaller order curves.
vertex, edge = (0, -len(digits) % self.n)
# Visit each base-n digit of index, most significant first.
coords = [0] * self.n
for digit in reversed(digits):
# Compute position in current hypercube, distributing the n
# bits across n coordinates.
bits = self.subcube_encode(digit, vertex, edge)
for bit in range(self.n):
coords[bit] = (coords[bit] << 1) | (bits & 1)
bits = bits >> 1
# Compute orientation of next sub-cube.
vertex, edge = self.rotate(digit, vertex, edge)
return tuple(coords)
def subcube_encode(self, index, vertex, edge):
h = self.gray_encode(index)
h = (h << (edge + 1)) | (h >> (self.n - edge - 1))
return (h & self.mask) ^ vertex
def rotate(self, index, vertex, edge):
v = self.subcube_encode(max((index - 1) & ~1, 0), vertex, edge)
w = self.subcube_encode(min((index + 1) | 1, self.mask), vertex, edge)
return (v, self.log2(v ^ w))
def gray_encode(self, index):
return index ^ (index >> 1)
def log2(self, x):
y = 0
while x > 1:
x = x >> 1
y = y + 1
return y
|
2ae1f5fbf625899bf45a6452f0a8ca497eb8e37a | ivan1991king/Python-Coursera | /week 1/дробная часть.py | 190 | 3.5625 | 4 | S = input()
pos1 = S.find('f')
print(pos1)
if pos1 != -1:
print(pos1, end=' ')
pos2 = S.rfind('f')
if pos2 != pos1:
print(pos2)
if pos1 == -1 and pos2 == -1:
print('')
|
f094b8ef6dc1ff523240c41099368c11758e8507 | antonio00/blue-vscode | /MODULO 01/AULA 06/aula06_Ex03.py | 493 | 3.71875 | 4 | def somaImposto():
taxaImposto = float(input('Qual a taxa de imposto em %: '))
custo = float(input('Qual custo bruto do Produto R$:'))
realCusto = custo *(taxaImposto/100) + custo
margemVenda = float(input('Qual Margem de venda em % : '))
precoVenda = realCusto *(margemVenda/100)
print(f'Este produto tem: {taxaImposto:.2f}% de imposto ')
print(f'O custo real é de: R${realCusto:.2f}')
print(f'O seu preço de venda é: R${precoVenda:.2f}')
somaImposto()
|
9cf28e524d597d508dff036f3a7cc2bcfdf401bf | EnriqueSPR/flower_image_classifier | /st_flower_app.py | 3,103 | 3.859375 | 4 |
import streamlit as st
from PIL import Image
import tensorflow as tf
import time
def process_image(img, img_size=(299, 299)):
"""
This function is used to pre-process any chosen picture by the user
to the appropriate format that the model accepts.
Parameters:
img: The input Image, opened using the PIL library
img_size: Defaults to (299, 299) because it is the size that the
model accepts
Returns:
An Image array that is ready to be fed into the model.
"""
# reshapes the image
image = ImageOps.fit(img, img_size, Image.ANTIALIAS)
# converts the image into numpy array
image = np.asarray(image)
# converts image from BGR color space to RGB
img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
img_resize = (cv2.resize(img, dsize=img_size, interpolation=cv2.INTER_CUBIC))/255.
img_reshape = img_resize[np.newaxis,...]
return img_reshape
def top_3_predictions(array, class_list):
inx = array[0].argsort()[-3:][::-1] # getting the indexes of the top 3 predictions in descending order
top_1 = array[0][inx[0]]*100
top_2 = array[0][inx[1]]*100
top_3 = array[0][inx[2]]*100
class_1 = class_list[inx[0]]
class_2 = class_list[inx[1]]
class_3 = class_list[inx[2]]
return print("Top 1 Prediction: With {:5.2f}% probability is a picture of {}.\nTop 2 Prediction: With {:5.2f}% probability is a picture of {}.\nTop 3 Prediction: With {:5.2f}% probability is a picture of {}.".format(top_1, class_1, top_2, class_2, top_3, class_3))
def prediction_result(model, image_data):
"""
The function that returns the prediction result from the model
Parameters:
model: The model to be used to classify
image_data: Image array that is returned by the process_image function
Returns --> Dictionary with class and accuracy values
"""
# Mapping prediction results to the Flower type
list_flowers = ['roses', 'daisy', 'dandelion', 'sunflowers', 'tulips']
pred_array = model.predict(image_data)
return top_3_predictions(pred_array, list_flowers)
st.set_option('deprecation.showfileUploaderEncoding', False)
st.title("Flower Classifier")
st.write("This app can predict flowers from five categories: Daisy, Rose, Sunflower, Tulip and Dandelion")
st.write("Disclaimer: May not always give correct prediction!")
st.write("Made by: Rupak Karki")
st.markdown("[rupakkarki.com.np](https://www.rupakkarki.com.np)")
img = st.file_uploader("Please upload Image", type=["jpeg", "jpg", "png"])
# Display Image
st.write("Uploaded Image")
try:
img = Image.open(img)
st.image(img) # display the image
img = process_image(img)
# Prediction
model = tf.keras.models.load_model("my_flower_model.h5")
prediction = prediction_result(model, img)
# Progress Bar
my_bar = st.progress(0)
for percent_complete in range(100):
time.sleep(0.05)
my_bar.progress(percent_complete + 1)
# Output
st.write("# Flower Type: {}".format(prediction["class"]))
st.write("With Accuracy:", prediction["accuracy"],"%")
except AttributeError:
st.write("No Image Selected")
|
07a60d2ad50701278c388b02158bead288d23f67 | meghakashyap/File | /count_the_line.py | 114 | 3.5 | 4 | file=open("demo.txt","r")
a=file.readlines()
i=0
while i<len(a):
i+=1
print(i)
file.close()
#count the line |
e34fe901c858c2ce040037fa1e2577b45316f5d4 | khlee12/python-leetcode | /medium/244.Shortest_Word_Distance_II.py | 1,212 | 3.6875 | 4 | # 244. Shortest Word Distance II
# https://leetcode.com/problems/shortest-word-distance-ii/
# https://leetcode.com/problems/shortest-word-distance-ii/discuss/67028/Java-Solution-using-HashMap
class WordDistance:
def __init__(self, words: 'List[str]'):
self.word_pos = {}
for i in range(len(words)):
if words[i] in self.word_pos.keys():
self.word_pos[words[i]].append(i)
else:
pos = [i]
self.word_pos[words[i]] = pos
def shortest(self, word1: 'str', word2: 'str') -> 'int':
# 求两个数组元素的最小值
pos1 = self.word_pos[word1]
pos2 = self.word_pos[word2]
g_min_distance = sys.maxsize
i = 0
j = 0
while i < len(pos1) and j < len(pos2):
if pos1[i] < pos2[j]:
g_min_distance = min(g_min_distance, pos2[j]-pos1[i])
i += 1
else:
g_min_distance = min(g_min_distance, pos1[i]-pos2[j])
j += 1
return g_min_distance
# Your WordDistance object will be instantiated and called as such:
# obj = WordDistance(words)
# param_1 = obj.shortest(word1,word2)
|
98fe2a0cb3f11563d33ad33ab021d14b1103b603 | fiabot/Connect-four | /connect4_v1.py | 6,891 | 3.828125 | 4 | #goal: find the ratio of offense to deffense in a game of connect 4
import random
from operator import itemgetter
from copy import deepcopy
import pygame
#note in board[a][b] a is rows from the top and b is columns from the left
#ps COLUMNS ARE VERTICAL and ROWS ARE HORAZONTAL
class GamePlay:
def __init__(self):
self.board = [[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],[0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,]]
#a function that takes a column numer and adds the move
#returns new board and row number
def add_play (self,col,board,player):
copy = deepcopy(board)
row_num = 5
placed = False
for i in range(0,6):
if copy[row_num][col] == 0:
copy[row_num][col] = player
placed = True
if placed:
return (copy,row_num)
row_num -= 1
return "too many players in row"
#checks to see if there is a winner
def check_win(self,board,piece):
#check for horazontal win
if not isinstance(board, str):
for i in range(6):
#print(i)
#win 1, start with first piece to the left
if board[i][0] == piece and board[i][1] == piece and board[i][2] == piece and board[i][3] == piece:
return "Winner"
#win 2, start with second piece to the left
if board[i][1] == piece and board[i][2] == piece and board[i][3] == piece and board[i][4] == piece:
return "Winner"
#win 3, start with third piece to the left
if board[i][2] == piece and board[i][3]== piece and board[i][4] == piece and board[i][5] == piece:
return "Winner"
#win 4, start with forth piece to the left
if board[i][3] == piece and board[i][4] == piece and board[i][5] == piece and board[i][6] == piece:
return "Winner"
#check for vertical win
for i in range(7):
#win 1, start with first piece to the top
if board[0][i] == piece and board[1][i] == piece and board[2][i] == piece and board[3][i] == piece:
return "Winner"
#win 2, start with second piece to the top
if board[1][i] == piece and board[2][i] == piece and board[3][i] == piece and board[4][i] == piece:
return "Winner"
#win 3, start with third piece to the top
if board[2][i] == piece and board[3][i]== piece and board[4][i] == piece and board[5][i] == piece:
return "Winner"
#check for positive diagonal win
for i in range(4):
start= 3
for g in range(3):
if board[start][i] == piece and board[start-1][i+1] == piece and board[start-2][i+2] == piece and board[start-3][i+3] == piece:
return "Winner"
start += 1
#check for negitve diagonal win
for i in range(4):
start= 0
for g in range(3):
if board[start][i] == piece and board[start+1][i+1] == piece and board[start+2][i+2] == piece and board[start+3][i+3] == piece:
return "Winner"
start += 1
else: return None
# returns a list of moves available
def moves_avail(self,board):
copy = deepcopy(board)
moves = []
for i in range(7):
play = self.add_play(i,copy,1)
if not play == "too many players in row":
moves.append(i)
if moves == []:
return "no moves available"
else: return moves
# returns true if opponent can win next turn
def opp_wins(self,board,piece,opp):
for i in range(7):
copy = deepcopy(board)
play = self.add_play(i,copy,opp)
if play == "too many players in row":
return False
copy = play[0]
if self.check_win(copy,opp) == "Winner":
return True
else: return False
"""class HumanPlayer:
def __init__(self, piece = 2, opp= 1):
self.piece = piece
self.opp = opp
def pick_move(self, board):
game = GamePlay()
copy = deepcopy(board)
moves = game.moves_avail(copy)
print(board[0])
print(board[1])
print(board[2])
print(board[3])
print(board[4])
print(board[5])
if moves == "no moves available":
print("no moves available")
return "no moves available"
play = input("Choose a column:")
play = int(play)
if play > 6:
while play > 6:
print("Not a Valid Column, please enter a number between 0-6")
play = input("Choose a Column:")
if game.add_play(play,board,self.piece) == "too many players in row":
while game.add_play(play,board,self.piece) == "too many players in row":
print("invalid move please choose again")
play = input("Choose a column:")
play = int(play)
return(play) """
"""board = [[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,]]
display = Display()
display.draw_board(board)
game = GamePlay(display)
AI = ComputerAI()
human = HumanPlayer(2,1,display)
game.play_game(board, AI, human)
board_copy = deepcopy(board)
fake_board = [[],[],[],[],[],[]]
fake_board[0] = [0,0,0,1,0,0,0]
fake_board[1] = [0,0,0,2,0,0,0]
fake_board[2] = [0,0,0,2,0,0,0]
fake_board[3] = [0,0,0,2,0,0,0]
fake_board[4] = [0,0,0,1,0,0,0]
fake_board[5] = [2,2,1,1,0,0,0]
##print(best_rand(fake_board,1,2))
#print(moves_avail(fake_board))
#print(offensive(fake_board,1,2))
#print(dig_moves(1,2,False))
#print(board)
#print(best_rand(fake_board,1,2))
win_1 = 0
win_2 = 0
tie = 0
##for i in range(5):
## game = (play_game(board,offense,deffense))
## if game == 1:
## win_1 += 1
## elif game == 2:
## win_2 += 1
## elif game == 0:
## tie += 1
## game = (play_game(board,deffense,offense))
## if game == 1:
## win_2 += 1
## elif game == 2:
## win_1 += 1
## elif game == 0:
## tie += 1
## print(win_1)
## print(win_2)
##
##print("offense:" + str(win_1))
##print("deffense:" + str(win_2))
##print("Tie:" + str(tie))
##'
print("You are player number 2")
game = GamePlay()
AI = RandomTrialAI()
score = game.play_game(board,player_play,player_play)
if score == 1:
print("Player 1 won")
elif score == 2:
print("Player 2 won")
else:
print ("tie")"""
|
7da5e688d4169d73c064dc91c1b132c56abcbff9 | Pandeyjidev/All_hail_python | /DSA_MadeEasy/stacks/stack_class.py | 848 | 3.84375 | 4 | # Using Lists
class stack(object):
def __init__(self):
self.content = []
def push(self, data):
return self.content.append(data)
def pop(self):
return self.content.pop()
def Top(self):
if len(self.content) > 0:
return self.content[-1]
else:
return 0
def size(self):
return len(self.content)
def isEmpty(self):
return self.size() <= 0
def find_min(self):
return min(self.content)
def print_stack(self):
print(self.content)
if __name__ == '__main__':
st = stack()
st.push(5)
st.push(4)
st.push(3)
st.push(2)
st.push(1)
st.print_stack()
st.pop()
print(st.size())
print(st.Top())
print(st.find_min())
st.print_stack()
print(st.isEmpty()) |
e4948cfdd62106c0609f7ed5abbd1ca5fd096cb5 | dwierdguy/Bankacount | /Bankaccount.py | 2,431 | 3.953125 | 4 | import datetime
import pytz
class Bank(object):
def __init__(self, name, balance):
self.name = name
self.balance = balance
self.transaction_time = []
print(f'\nAccount created for {self.name} and credited with Rs.{self.balance}')
def new_deposit(self, amount):
try:
if amount > 0:
self.balance += amount
date = datetime.date.today()
time = datetime.time
self.transaction_time.append((datetime.datetime.utcnow().strftime('%B %d %Y - %H:%M:%S'), amount, 1, self.balance))
print(f'\nAccount credited with Rs.{amount} and new balance is Rs.{self.balance}')
else:
print('\nPlease provide cash more than Rs.0')
except TypeError:
pass
def check_balance(self):
print(f'Your account is left with : Rs.{self.balance}')
def withdraw(self, amount):
if amount > self.balance:
print("You don't have enough cash")
else:
self.balance -= amount
self.transaction_time.append((datetime.datetime.utcnow().strftime('%B %d %Y - %H:%M:%S'), amount, 0, self.balance))
print(f'Your account is left with : {self.balance}')
def statement(self):
tran_time = ''
transaction = ''
for n in self.transaction_time:
tran_time = n[0]
transaction = n[1]
credit = n[2]
balance = n[3]
if credit == 1:
print(f"Date : {tran_time}, Amount Debited : Rs.{transaction}, New Balance : {balance}")
else:
print(f"Date : {tran_time}, Amount Credited : Rs.{transaction}, New Balance : {balance}")
print("Let's create an account first")
name = input("Enter your name : ")
person1 = Bank(name, 0)
ch = ''
while ch != 5:
try:
ch = int(input("1.Cash Deposit \n2.Cash Withdrawl \n3.Check Balance \n4.Statement \n5.Quit\n"))
if ch == 1:
n = int(input(f'Enter the Cash you want to deposit : Rs.'))
person1.new_deposit(n)
elif ch == 2:
n = int(input('How much do you want to withdraw ? \nRs.'))
person1.withdraw(n)
elif ch == 3:
person1.check_balance()
elif ch == 4:
person1.statement()
except ValueError:
print('Please enter the valid options!\n')
|
bf514310d8f900b13ff97c1ee8eb6192ea3df5ea | jtoumey/prePostProcessLib | /openFoamLib/logTools.py | 982 | 3.65625 | 4 | class LogFile:
"""Encapsulates the log file and allows parsing and modification.
Instantiate with the log file name.
"""
def __init__(self, log_file_handle_):
self.log_file_handle = log_file_handle_
def readLogFileKey(self, key_):
"""Read a specific key from the log.
Return a record containing each line containing the key
"""
record = []
log_file = open(self.log_file_handle, 'r')
for line in log_file:
if key_ in line:
record.append(line)
return (record)
def parseRunTime(self):
# The idea here would be to get Time, ExecutionTime, and ClockTime entries
# and make some calculations
# 1. read exclusively 'Time' key--standalone
# 2. Make assumptions about the log file and equate each 'Time' entry to a corresponding 'ExecutionTime' entry
time_entries = self.readLogFileKey('Time')
print (time_entries)
|
3b226ebf67f85bc4a33b854607624271e53230ab | mahinsagotra/Python | /NumPy/accessing.py | 647 | 4.03125 | 4 | import numpy as np
a = np.array([[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14]])
print(a)
print(a.shape)
# Get a specific element [r,c]
print(a[1][5])
print(a[1][-1])
# Get a specific row
print(a[0, :])
# Get a specific column
print(a[:, 2])
# Getting a little fancy [startindex:endindex:stepsize]
print(a[0, 1:6:2])
print(a[0, 1:-1:2])
# Change
a[1, 5] = 20
print(a[1, 5])
print(a)
a[:, 2] = 5
print(a)
a[:, 2] = [1,2]
print(a)
# 3-D
b= np.array([[[1,2],[3,4]],[[5,6],[7,8]]])
print(b)
#Getting a specific element (work outside in)
print(b[0,1,1])
print(b[0,1,:])
print('///////')
print(b[:,1,:])
b[:,1,:] = [[9,9],[8,8]]
print(b) |
533a390c5a992d5df2dade9bedaa99079b6ee602 | Cristofer-Zapata/UPS-TRABAJOS-PYTHON | /github/Guión 1.py | 209 | 3.734375 | 4 | print ("Años bisiestos")
fecha = int(input("Escriba el año y le diré es bisiesto: "))
if fecha %400== 0 or (fecha % 100 != 0 and fecha % 4 == 0):
print("verdadero. ")
else:
print("falso. ")
|
1a1723f662930bae1452ca7bc46c01a141356bfa | Nithanth/Graduate-Algorithm- | /Priority_Queues/UnsortedPriorityQueue.py | 1,245 | 4.0625 | 4 | from Priority_Queues import PriorityQueueBase
def Empty():
pass
class UnsortedPriorityQueue(PriorityQueueBase):
def _find_min(self):
""" Return Position of item with minimum key """
if self.is_empty():
raise Empty('Priority queue is empty')
small=self._data.first()
walk=self._data.after(small)
while walk is not None:
if walk.element()< small.element():
small=walk
walk=self._data.after(walk)
return small
def __init__(self):
""" create a new empty Priority Queue. """
self._data=PositionalList()
def __len__(self):
""" return the number of items in the priority queue """
return len(self._data)
def add(self, key, value):
""" add a key-value pair """
self._data.add_last(self._Item(key, value))
def min(self):
""" return but do not remove (k,v) tuple with minimun key """
p=self._find_min()
item=p.element()
return (item._key, item._value)
def remove_min(self):
""" remove and return (k,v) tuple with minimun key. """
p=self._find_min()
item=self._data.delete(p)
return (item._key, item._value)
|
265d231e3ee1aac8f961a762093651ce880e2f0b | laiw3n/leetcode | /2.py | 1,530 | 3.71875 | 4 | #coding: utf8
# 一个比较简单的模拟,就按照人类思维做就ok了。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if (not l1):
return l2
if (not l2):
l1
if ((not l1) and (not l2)):
return None
ans = ListNode((l1.val + l2.val) % 10)
carry = (l1.val + l2.val) / 10
node1 = l1
node2 = l2
nodeAns = ans
while (l1.next or l2.next):
if l1.next:
l1 = l1.next
temp1 = l1.val
else:
temp1 = 0
if l2.next:
l2 = l2.next
temp2 = l2.val
else:
temp2 = 0
tempAns = (carry + temp1 + temp2) % 10
carry = (carry + temp1 + temp2) / 10
newNodeAns = ListNode(tempAns)
nodeAns.next = newNodeAns
nodeAns = newNodeAns
if (carry > 0):
nodeAns.next = ListNode(carry)
return ans
# l11 = ListNode(2)
# l12 = ListNode(4)
# l13 = ListNode(3)
# l11.next = l12
# l12.next = l13
#
# l21 = ListNode(5)
# l22 = ListNode(6)
# l23 = ListNode(6)
# l21.next = l22
# l22.next = l23
#
# print Solution().addTwoNumbers(l11,l21).next.next.next.next
|
323c831a3b5a9d0b3c96e7d7af346726fd6aaf5a | rafaelperazzo/programacao-web | /moodledata/vpl_data/34/usersdata/78/13715/submittedfiles/moedas.py | 360 | 3.53125 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
a=int(input('digite o valor de a:'))
b=int(input('digite o valor de b:'))
c=int(input('digite o valor de c:'))
na=0
nb=0
cont=0
while n<=c//a:
nb=(c-na*a)//b
if na*a+nb*b==c:
cont=cont+1
brak
else:
na=na+1
if cont>0:
print(na)
print(nb)
else:
print('N')
|
847c627ea971877ee1234bd401c2284d52fc99eb | Nikoletazl/Advanced-Python | /labs/tuples_sets/students_grades.py | 530 | 4.09375 | 4 | n = int(input())
students_records = {}
def avg(values):
return sum(values) / len(values)
for _ in range(n):
name, grade_sting = input().split()
grade = float(grade_sting)
if name not in students_records:
students_records[name] = []
students_records[name].append(grade)
for name, grades in students_records.items():
average_grade = avg(grades)
grade_string = " ".join(str(f"{x:.2f}") for x in grades)
print(f"{name} -> {grade_string} (avg: {average_grade:.2f})")
|
21bff9f36f1bd48dac1d304518e37e05a34d0b7f | Jeremy277/exercise | /pytnon-month01/month01-class notes/day03-fb/demo08.py | 143 | 3.71875 | 4 | '''
规定循环次数的循环
'''
count = 0
while count < 3:
dol = int(input('请输入美元:'))
print(dol * 6.9)
count += 1 |
e049916aef1b9efadc069f29150ad220ab20a427 | ojhermann-ucd/HackerRank | /DijkstraShortestReach2/solution_1.py | 3,408 | 4.25 | 4 | # IMPORTS
from collections import defaultdict
# MERGE SORT
def remove_first_entry_of_dict(d):
"""
This function removes, by popping, the first element in a Python dictionary
"""
key = next(iter(d))
value = d[key]
d.pop(next(iter(d)))
return [key, value]
def merge(d_1, d_2):
"""
This function is one part of an implementation of mergesort for Python dictionaries
"""
# create the return object
d_return = {}
# get the latest stop until one dict is empty
while len(d_1) > 0 and len(d_2) > 0:
# create the traverse objects
key_1, key_2 = next(iter(d_1)), next(iter(d_2))
# put the lowest time in first
if d_1[key_1] < d_2[key_2]:
d_return[key_1] = d_1[key_1]
del d_1[key_1]
else:
d_return[key_2] = d_2[key_2]
del d_2[key_2]
# add remaining elements
while len(d_1) > 0:
item = next(iter(d_1))
d_return[item] = d_1[item]
del d_1[item]
while len(d_2) > 0:
item = next(iter(d_2))
d_return[item] = d_2[item]
del d_2[item]
# return
return d_return
def merge_sort(d_return):
"""
This function is the second part of an implementation of mergesort for Python dictionaries
"""
# objects
d_1 = {}
d_2 = {}
length = len(d_return)
middle = int(length / 2)
# split the data into two parts
if len(d_return) > 1:
for i in range(0, middle, 1):
next_item = next(iter(d_return))
d_1[next_item] = d_return[next_item]
del d_return[next_item]
for i in range(middle, length, 1):
next_item = next(iter(d_return))
d_2[next_item] = d_return[next_item]
del d_return[next_item]
# recursion
d_1 = merge_sort(d_1)
d_2 = merge_sort(d_2)
# sorting
d_return = merge(d_1, d_2)
# return
return d_return
# D_GRAPH
def add_to_graph(d_graph, x, y, r):
# d_graph[x][y]
if y in d_graph[x]:
d_graph[x][y] = min(d_graph[x][y], r)
else:
d_graph[x][y] = r
# d_graph[y][x]
if x in d_graph[y]:
d_graph[y][x] = min(d_graph[y][x], r)
else:
d_graph[y][x] = r
def sort_connections(d_graph):
for x in d_graph:
d_graph[x] = merge_sort(d_graph[x])
# DIJKSTRA
def all_other_nodes(d_graph, s):
return [x for x in d_graph if x != s]
def find_next_node(d_graph, visited_set, path):
current_node = path[0][-1]
for node in d_graph[current_node]:
if node not in visited_set:
return node
return -1
def update_paths(d_graph, visited_set, path_dict, current_path, path_id, current_node):
for node in d_graph[current_node]:
if node not in visited_set:
path_id += 1
def dijkstra(d_graph, s, e):
visited_set = set()
path_dict = defaultdict(list)
current_node = s
path_index = 0
path_dict[path_index] = [[current_node], 0]
while e not in visited_set:
# mark that we've visited
visited_set.add(current_node)
# find the next closest node
next_node = find_next_node(d_graph, visited_set, )
if __name__ == '__main__':
for case in range(int(input().strip())):
# create the dictionary
d_graph = defaultdict(dict)
# collect the data
for edge in range(int(input().strip().split()[1])):
data = [int(x) for x in input().strip().split()]
add_to_graph(d_graph, data[0], data[1], data[2])
# get the starting point
s = int(input().strip())
# sort d_graph
sort_connections(d_graph)
# # generate the graph
# d_graph = defaultdict(dict)
# print(d_graph)
# print("")
# add_to_graph(d_graph, 1, 2, 3)
# print(d_graph)
# print("")
# add_to_graph(d_graph, 1, 2, 2)
# print(d_graph)
# print("") |
0f7ffcc7cca29d5a219ae6df06fa14214268d7fb | alejandrozeb/python-django | /curso/2-fundamentos/25-persona.py | 1,013 | 4.5 | 4 | """ Existe muchas formas de instanciar un objeto veremos la forma mas basica"""
class Persona:
#pass #pasara el proceso y creara una èrsona vacia
#atributos
def __init__(self, nombre, edad): #contructor
self.nombre = nombre #se crea el atributo
self.edad = edad
#modificar los valores
Persona.nombre = "Alejandro"
Persona.edad = 85
#Acceder a los valores
print(Persona.nombre, " ", Persona.edad)
#la identacion es exactamente igual a los bloques de codigo
#python esta creando el objeto de manera implicita
#Creando un objeto
persona = Persona("Alejandro", 90)
print(persona.nombre)
print(persona.edad)
print(id(persona))#direccion de memoria
#se debe crear objetos a partir del constructor
#creacion de un segundo objeto
persona2 = Persona('Alejandro2', 25)
print(persona2.nombre)
print(persona2.edad)
print(id(persona2))#direccion de memoria
#los dos objetos se encuentran en una diferente direccion de memoria, estos objetos son independientes con sus propios punteros |
b11e32468dda515133231e952e90b28aaebde646 | dinosaurz/ProjectEuler | /id015.py | 358 | 3.71875 | 4 | from math import factorial
import time
# Using the combination formula the answer is easy to find
# C(n, r) = n! / (r! * (n - r)!)
def main():
start = time.time()
n, r = 40, 20
print (factorial(n) / (factorial(r) * factorial(n - r))),
print "found in %s seconds" % (time.time() - start)
if __name__ == '__main__':
main()
|
edd1587f25443cbac824b744990157a83129ccb7 | FaisalWant/python_Assignments | /sqRoot_newton_rhalpson.py | 198 | 3.546875 | 4 | #square root using NewtonRalphson
epsilon =0.01
k=24.0
guess= k/2.0
while abs(guess*guess-k) >=epsilon:
guess= guess-(((guess**2)-k)/(2*guess))
print ('square root of', k, 'is about ', guess)
|
cd52330ace48dffaf87384d281d9585b82fa2172 | AK-171261/python-datastructures-programs | /sort_dict.py | 996 | 4.3125 | 4 | '''
Ways to sort list of dictionaries by values in Python – Using lambda function/Using itemgetter
'''
lis = [{"name": "Nandini", "age": 20},
{"name": "Manjeet", "age": 20},
{"name": "Nikhil", "age": 19}]
# Method-1
for obj in sorted(lis, key=lambda x: (x["age"], x["name"])):
print(obj)
# {'name': 'Nikhil', 'age': 19}
# {'name': 'Manjeet', 'age': 20}
# {'name': 'Nandini', 'age': 20}
# Method-2
res = sorted(lis, key=lambda x: (x["age"], x["name"]))
print(res)
# [{'name': 'Nikhil', 'age': 19}, {'name': 'Manjeet', 'age': 20}, {'name': 'Nandini', 'age': 20}]
# Method-3
from operator import itemgetter
res = sorted(lis, key=itemgetter('age', 'name'), reverse=True)
print(res)
# [{'name': 'Nandini', 'age': 20}, {'name': 'Manjeet', 'age': 20}, {'name': 'Nikhil', 'age': 19}]
'''
Ways to sort dictionaries by values in Python – Using lambda function
'''
dict1 = {1: 1, 2: 9, 3: 4}
res = sorted(dict1.items(), key=lambda x: x[1])
print(res)
# [(1, 1), (3, 4), (2, 9)]
|
5cfcdda6186819cdabd414fd085b4547b328764e | vladmer27/My-python-lessons- | /3.var.py | 588 | 3.65625 | 4 | #git pull - check status
#*** example of the thermostat***
# current tempretature of room
current_temp = 26
# заданное значение диапазона температуры
min_temp = 10
max_temp = 25
# параметр "люди есть или нет"
#h = true = люди есть
#h = false = людей нет
h = True
# the logic of thermostat
if current_temp < min_temp and not h:
print (f"heating turned on until {min_temp}")
elif current_temp < max_temp and h:
print (f"heating turned on until {max_temp}")
else:
print ("heating turned off")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.