blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
ea54fc55ca5f69eb2952c369b4f107d15cd78902 | daxata/assignment_1 | /daxata.py | 489 | 3.65625 | 4 | Python 3.4.0 (v3.4.0:04f714765c13, Mar 16 2014, 19:24:06) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> P = 5500 #pricipal amount (initial investment)
>>> r = 6.2 #annual nominal interest rate (as a decimal)
>>> n = 3 #number of times the interest is compounded per year
>>> t = 5 #number of years
>>> ci = P*((1+(r/n))**(n*t))
>>> print (" The compound interest, A = ", ci)
The compound interest, A = 109739070884.36275
>>>
|
66964f525117475a750ce2144f48c97df6d2ec5c | trault14/Intro_TensorFlow | /Classification_Fully_Connected.py | 3,958 | 3.671875 | 4 | import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from libs import datasets
from libs import utils
"""
==== DESCRIPTION OF THE NETWORK ====
This fully connected neural network is trained to classify
images that each represent the drawing of a number from
0 to 9. The input to the network is an image of 28x28 pixels
(784 input neurons). The output is a 10-digit one-hot encoding
containing the probability that the network associates to
each possible label for classifying the input image.
Supervised learning is used here, as the cost function compares
the predicted output with the true output by means of a
cross entropy function.
"""
# ==== GATHERING THE DATA ====
ds = datasets.MNIST(split=[0.8, 0.1, 0.1])
# The input is the brightness of every pixel in the image
n_input = 28 * 28
# The output is the one-hot encoding of the label
n_output = 10
# ==== DEFINITION OF THE NETWORK ====
# First dimension is flexible to allow for both batches
# and singles images to be processed
X = tf.placeholder(tf.float32, [None, n_input])
Y = tf.placeholder(tf.float32, [None, n_output])
# Connect the input to the output with a linear layer.
# We use the SoftMax activation to make sure the outputs
# sum to 1, making them probabilities
Y_predicted, W = utils.linear(
x=X,
n_output=n_output,
activation=tf.nn.softmax,
name='layer1')
# Cost function. We add 1e-12 (epsilon) to avoid reaching 0,
# where log is undefined.
cross_entropy = -tf.reduce_sum(Y * tf.log(Y_predicted + 1e-12))
optimizer = tf.train.AdamOptimizer(0.001).minimize(cross_entropy)
# Output. The predicted class is the one weighted with the
# highest probability in our regression output :
predicted_y = tf.argmax(Y_predicted, 1)
actual_y = tf.argmax(Y, 1)
# We can measure the accuracy of our network like so.
# Note that this is not used to train the network.
correct_prediction = tf.equal(predicted_y, actual_y)
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
# ==== TRAINING THE NETWORK ====
sess = tf.Session()
sess.run(tf.global_variables_initializer())
batch_size = 50
n_epochs = 5
previous_validation_accuracy = 0
for epoch_i in range(n_epochs):
for batch_xs, batch_ys in ds.train.next_batch():
sess.run(optimizer, feed_dict={X: batch_xs, Y: batch_ys})
# Get an estimation of the new accuracy of the network, using the validation data set :
valid = ds.valid
# If the validation accuracy reaches a threshold, or if it starts decreasing,
# stop training to avoid over fitting
validation_accuracy = sess.run(accuracy, feed_dict={X: valid.images, Y: valid.labels})
print("Epoch {} ".format(epoch_i) + "validation accuracy : {}".format(validation_accuracy))
if (validation_accuracy - previous_validation_accuracy) < 0:
break
previous_validation_accuracy = validation_accuracy
# Run a test with the test data set to get a confirmation of the accuracy
# of the network, and then start using it to classify unlabeled images
test = ds.test
print("Test accuracy : {}".format(sess.run(accuracy, feed_dict={X: test.images, Y: test.labels})))
# ==== INSPECTING THE NETWORK ====
# We first get the graph that we used to compute the network
g = tf.get_default_graph()
# And we inspect everything inside of it
print([op.name for op in g.get_operations()])
# Get the weight matrix by requesting the output of the corresponding tensor
W = g.get_tensor_by_name('layer1/W:0')
# Evaluate the value of tensor W
W_arr = np.array(W.eval(session=sess))
print(W_arr.shape)
# Let's now visualize every neuron (column) of the weight matrix
fig, ax = plt.subplots(1, 10, figsize=(20, 3))
for col_i in range(10):
ax[col_i].imshow(W_arr[:, col_i].reshape((28, 28)), cmap='coolwarm')
plt.show()
# ==== USING THE NETWORK ====
# Inject a single image into the network and review the prediction
sess.run(predicted_y, feed_dict={X: [ds.X[3]]})
plt.imshow(ds.X[3].reshape((28, 28)))
plt.show()
|
58f5520908c4d928039bf471e575e6f9c5826734 | oliviamriley/class | /Algo/hw/hw4/q3.py | 208 | 3.765625 | 4 | #!/usr/bin/env python
def find_min(A):
#base case
if(len(A) == 2):
if A[0] < A[1]:
return A[0]
else if A[1] <= A[0]:
return A[1]
for i in range(len(A)):
|
359f1658650f9444ee0ef8ddced0d5b4e1fb9487 | Kalpesh14m/Python-Basics-Code | /Basic Python/28 OS Module.py | 1,330 | 4.4375 | 4 | """
The main purpose of the OS module is to interact with your operating system. The primary use I find for it is to create folders, remove folders, move folders, and sometimes change the working directory. You can also access the names of files within a file path by doing listdir(). We do not cover that in this video, but that's an option.
The os module is a part of the standard library, or stdlib, within Python 3. This means that it comes with your Python installation, but you still must import it.
"""
#Sample code using os:
import os
import time
# # All of the following code assumes you have os imported.
# # Because it is not a built-in function, you must always import it.
# # It is a part of the standard library, however, so you will not need to download or install it separately from your Python installation.
#
# #Get your current working directory
# curDir = os.getcwd()
# print(curDir)
# #Time.sleep(seconds)
# time.sleep(2)
# # To make a new directory:
# os.mkdir('newDir')
#
# # To change the name of, or rename, a directory:
# # os.rename('newDir','newDir2')
#
# #To remove a directory:
# os.rmdir('newDir2')
#With the os module, there are of course many more things we can do.
#In many scenarios, however, the os module is actually becoming outdated, as there is a superior module to get the job done.
|
3abea91c0a753cd9740555dcc6b1c5c3fc71d184 | prusinski/NU_REU_git_NZP | /python_plot.py | 406 | 3.703125 | 4 | %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
#plot exponential curve from 0 to 2pi
t = np.linspace(0,2*np.pi,100)
plt.plot(t,np.exp(t),'m', label = 'Exponential Curve')
plt.title('Plot of $e^x$')
plt.xlabel('t (s)')
plt.ylabel('$y(t)$')
plt.legend()
plt.grid()
plt.text(2.5,0.25,'This is a \nExponential Curve!', fontsize = 16)
plt.text(1,-0.5,'Cool!', fontsize = 16)
plt.show()
|
d4c4fef207761af41536ea218a940089d13e18c0 | Alihasnat10/Algorithms-and-Data-Structures | /Picking Number.py | 469 | 3.65625 | 4 | def pickingNumbers(a):
# Write your code here
a.sort()
ans = []
count = []
for i in range(len(a)):
ans = []
for j in range(i, len(a)):
if abs(a[i] - a[j]) <= 1:
ans.append(a[j])
else:
break
count.append(len(ans))
return max(count)
if __name__ == '__main__':
a = [1,2,2,3,1,2]
result = pickingNumbers(a)
print(str(result) + '\n')
|
1ad1f406136227258ad9a2c78b5fa9b7e020a33f | luokeke/selenium_python | /python_doc/Python基础语法/4.程序的控制结构/条件判断及组合.py | 705 | 3.921875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/11/27 17:35
# @Author : liuhuiling
print()
'''
条件判断,比较运算符
操作符 数学符号 描述
< < 小于
<= <= 小于等于
>= >= 大于等于
> > 大于
== = 等于
!= ≠ 不等于
条件组合,保留字
操作符及使用 描述
x and y 两个条件x和y的逻辑与
x or y 两个条件x和y的逻辑或
not x 条件x的逻辑非
'''
guss = eval(input("请输入猜的数据:"))
if guss>99 or guss <99:
print("猜错了")
else:
print("猜对了") |
99d500ac3750c696f56c168722feb70db3a6e671 | MysteriousSonOfGod/python-3 | /basic/multi/threading4.py | 1,772 | 3.625 | 4 | import time
import threading
import concurrent.futures
def do_something(seconds=1):
print(f'Sleeping {seconds} second(s)...')
time.sleep(seconds)
return 'Done Sleeping...'
# 1. Using threading
start = time.perf_counter()
threads = []
for _ in range(10):
t = threading.Thread(target=do_something, args=[1.5])
t.start()
threads.append(t)
for thread in threads:
thread.join()
finish = time.perf_counter()
print(f'Finished in {round(finish-start, 2)} second(s)')
start = time.perf_counter()
with concurrent.futures.ThreadPoolExecutor() as executor:
f1 = executor.submit(do_something, 1)
f2 = executor.submit(do_something, 1)
print(f1.result())
print(f2.result())
finish = time.perf_counter()
print(f'Finished in {round(finish-start, 2)} second(s)')
# 2. Using concurrent & sumbit
start = time.perf_counter()
with concurrent.futures.ThreadPoolExecutor() as executor:
results = [executor.submit(do_something, 1) for _ in range(10)]
for f in concurrent.futures.as_completed(results):
print(f.result())
finish = time.perf_counter()
print(f'Finished in {round(finish-start, 2)} second(s)')
start = time.perf_counter()
with concurrent.futures.ThreadPoolExecutor() as executor:
secs = [5,4,3,2,1]
results = [executor.submit(do_something, sec) for sec in secs]
for f in concurrent.futures.as_completed(results):
print(f.result())
finish = time.perf_counter()
print(f'Finished in {round(finish-start, 2)} second(s)')
# 3. Using concurrent & map
start = time.perf_counter()
with concurrent.futures.ThreadPoolExecutor() as executor:
secs = [5,4,3,2,1]
results = executor.map(do_something, secs)
for result in results:
print(result)
finish = time.perf_counter()
print(f'Finished in {round(finish-start, 2)} second(s)')
|
cdf9415cdd7af7b3225d01cc7cd2b65e6db6a15a | slottwo/cursoemvideo-python3-m3-exe | /#106(helper).py | 780 | 3.984375 | 4 | # Exercício Python 106: Faça um mini-sistema que utilize o Interactive Help do Python. O usuário vai digitar o
# comando e o manual vai aparecer. Quando o usuário digitar a palavra 'FIM', o programa se encerrará. Importante: use
# cores.
# Situação:
def titulo(tit: str, color: str):
w = len(tit) + 4
print(color, end='')
print("~"*w)
print(tit.center(w))
print("~"*w)
print("\033[m", end='')
def ajuda(cmd):
print("\033[0:32:40m", end='')
help(cmd)
print("\033[m", end='')
ler_cmd()
def ler_cmd():
titulo("Sistema de Ajuda PyHELP", "\033[1:30:42m")
cmd = input("Função ou biblioteca: ")
if cmd.upper() == "FIM":
titulo("Tchau!", "\033[1:30:41m")
exit()
else:
ajuda(cmd)
ler_cmd()
|
aab6e0a41308a5f752fa53c7709059fc5caa8dff | ckitagawa/Algorithms-And-DataStructures | /python_algorithms_data_structures/rbtree.py | 11,353 | 3.546875 | 4 | import queue
global RED, BLACK
RED = 0
BLACK = 1
class RBNode(object):
def __init__(self, key, value, left=None, right=None, parent=None, color=RED):
self.key = key
self.value = value
self.lchild = left
self.rchild = right
self.parent = parent
self.grandparent = None
self.uncle = None
self.sibling = None
if self.parent:
if self.parent.parent:
self.grandparent = self.parent.parent
if self.grandparent:
if self.parent == self.grandparent.lchild:
self.uncle = self.grandparent.rchild
else:
self.uncle = self.grandparent.lchild
if self == self.parent.lchild:
self.sibling = self.parent.rchild
else:
self.sibling = self.parent.lchild
self.color = color
def __str__(self):
return str(self.key)
def toggle_color(self):
if self.color == RED:
self.color = BLACK
else:
self.color = RED
def has_lchild(self):
return self.lchild
def has_rchild(self):
return self.rchild
def is_lchild(self):
return self.parent and self.parent.lchild == self
def is_rchild(self):
return self.parent and self.parent.rchild == self
def is_root(self):
return not self.parent
def is_leaf(self):
return not (self.lchild or self.rchild)
def has_children(self):
return self.lchild or self.rchild
def has_both_children(self):
return self.lchild and self.rchild
def update_node(self, key, value, left, right):
self.key = key
self.value = value
self.lchild = left
self.rchild = right
if self.has_lchild():
self.lchild.parent = self
if self.has_rchild():
self.rchild.parent = self
def update_parentage(self, parent):
self.parent = parent
self.grandparent = None
self.uncle = None
self.sibling = None
if self.parent:
if self.parent.parent:
self.grandparent = self.parent.parent
if self.grandparent:
if self.parent == self.grandparent.lchild:
self.uncle = self.grandparent.rchild
else:
self.uncle = self.grandparent.lchild
if self == self.parent.lchild:
self.sibling = self.parent.rchild
else:
self.sibling = self.parent.lchild
class RBT(object):
def __init__(self):
self.root = None
self.size = 0
def __len__(self):
return self.size
def insert(self, key, value):
if self.root:
self._insert(key, value, self.root)
else:
self.root = RBNode(key, value)
self._insert_case1(self.root)
self.size += 1
def _insert(self, key, value, node):
if key < node.key:
if node.has_lchild():
self._insert(key, value, node.lchild)
else:
node.lchild = RBNode(key, value, parent=node)
self._insert_case1(node.lchild)
elif key > node.key:
if node.has_rchild():
self._insert(key, value, node.rchild)
else:
node.rchild = RBNode(key, value, parent=node)
self._insert_case1(node.rchild)
else:
raise KeyError("attempted to insert duplicate key")
def _insert_case1(self, node):
if not node.parent:
node.toggle_color()
else:
self._insert_case2(node)
def _insert_case2(self, node):
if node.parent.color == BLACK:
return
else:
self._insert_case3(node)
def _insert_case3(self, node):
if node.uncle != None and node.uncle.color == RED:
node.uncle.toggle_color()
node.parent.toggle_color()
node.grandparent.toggle_color()
self._insert_case1(node.grandparent)
else:
self._insert_case4(node)
def _insert_case4(self, node):
if node == node.parent.rchild and node.parent == node.grandparent.lchild:
self._rotate_left(node.parent)
node = node.lchild
elif node == node.parent.lchild and node.parent == node.grandparent.rchild:
self._rotate_right(node.parent)
node = node.rchild
self._insert_case5(node)
def _insert_case5(self, node):
print(node)
node.parent.color = BLACK
node.grandparent.color = RED
if node == node.parent.lchild:
self._rotate_right(node.grandparent)
else:
self._rotate_left(node.grandparent)
def _rotate_left(self, node):
pivot = node.rchild
tmp = pivot.lchild
pivot.lchild = node
node.rchild = tmp
pivot.update_parentage(node.parent)
if pivot.has_rchild():
pivot.rchild.update_parentage(pivot)
if pivot.rchild.has_lchild():
pivot.rchild.lchild.update_parentage(pivot.rchild)
if pivot.rchild.has_rchild():
pivot.rchild.rchild.update_parentage(pivot.rchild)
node.update_parentage(pivot)
if node.has_lchild():
node.lchild.update_parentage(node)
if node.lchild.has_lchild():
node.lchild.lchild.update_parentage(node.lchild)
if node.lchild.has_rchild():
node.lchild.rchild.update_parentage(node.lchild)
if node.has_rchild():
node.rchild.update_parentage(node)
if node.rchild.has_lchild():
node.rchild.lchild.update_parentage(node.lchild)
if node.rchild.has_rchild():
node.rchild.rchild.update_parentage(node.lchild)
if pivot.parent == None:
self.root = pivot
def _rotate_right(self, node):
pivot = node.lchild
tmp = pivot.rchild
pivot.rchild = node
node.lchild = tmp
pivot.update_parentage(node.parent)
if pivot.has_lchild():
pivot.lchild.update_parentage(pivot)
if pivot.lchild.has_lchild():
pivot.lchild.lchild.update_parentage(pivot.lchild)
if pivot.lchild.has_rchild():
pivot.lchild.rchild.update_parentage(pivot.lchild)
node.update_parentage(pivot)
if node.has_lchild():
node.lchild.update_parentage(node)
if node.lchild.has_lchild():
node.lchild.lchild.update_parentage(node.lchild)
if node.lchild.has_rchild():
node.lchild.rchild.update_parentage(node.lchild)
if node.has_rchild():
node.rchild.update_parentage(node)
if node.rchild.has_lchild():
node.rchild.lchild.update_parentage(node.lchild)
if node.rchild.has_rchild():
node.rchild.rchild.update_parentage(node.lchild)
if pivot.parent == None:
self.root = pivot
def __setitem__(self, key, value):
self.insert(key, value)
def find(self, key):
if self.root:
res = self._find(key, self.root)
if res:
return res.value
else:
return None
else:
raise Exception("no root node")
def _find(self, key, node):
if not node:
return None
elif node.key == key:
return node
elif key < node.key and node.has_lchild():
return self._find(key, node.lchild)
elif key > node.key and node.has_rchild():
return self._find(key, node.rchild)
def __getitem__(self, key):
return self.find(key)
def __contains__(self, key):
if self._find(key, self.root):
return True
return False
def delete(self, key):
if self.size > 1:
toremove = self._find(key, self.root)
if toremove:
if toremove.has_both_children():
toremove = self.__relocate(toremove)
if toremove.has_children():
self._delete_one_child(toremove)
else:
if toremove == toremove.parent.rchild:
if toremove.parent.has_lchild():
toremove.parent.lchild.sibling = None
toremove.parent.rchild = None
else:
if toremove.parent.has_rchild():
toremove.parent.rchild.sibling = None
toremove.parent.lchild = None
self.size -= 1
else:
raise KeyError("key not in tree")
elif self.size == 1 and self.root.key == key:
self.root = None
self.size -= 1
else:
raise Exception("no root node")
def __delitem__(self, key):
self.delete(key)
def __relocate(self, node):
s = self.__successor(node)
s.key, s.value, node.key, node.value = node.key, node.value, s.key, s.value
return s
def __successor(self, node):
s = None
if node.has_rchild():
s = self.__fmin(node.rchild)
else:
if node.parent:
if node.is_lchild():
s = node.parent
else:
node.parent.rchild = None
s = self.__successor(node.parent)
node.parent.rchild = self
return s
def __fmin(self, node):
current = node
while current.has_lchild():
current = current.lchild
return current
def _delete_one_child(self, node):
if node.has_lchild():
child = node.lchild
r = False
else:
child = node.rchild
r = True
child.value, child.key, child.color, node.key, node.value, node.color = node.key, node.value, node.color, child.value, child.key, child.color
if child.color == BLACK:
if node.color == RED:
node.color = BLACK
else:
self._delete_case1(node)
if r:
node.rchild = None
if node.has_lchild():
node.lchild.sibling = None
else:
node.lchild = None
if node.has_rchild():
node.rchild.sibling = None
def _delete_case1(self, node):
if node.parent != None:
self._delete_case2(node)
def _delete_case2(self, node):
if node.sibling:
if node.sibling.color == RED:
node.parent.color = RED
node.sibling.color = BLACK
if node == node.parent.lchild:
self._rotate_left(node.parent)
else:
self._rotate_right(node.parent)
self._delete_case3(node)
def _delete_case3(self, node):
if node.sibling:
if node.sibling.has_both_children():
if node.parent.color == BLACK and node.sibling.color == BLACK and node.sibling.lchild.color == BLACK and node.sibling.rchild.color == BLACK:
node.sibling.color = RED
_delete_case1(node.parent)
else:
self._delete_case4(node)
def _delete_case4(self, node):
if node.parent.color == RED and node.sibling.color == BLACK and node.sibling.lchild.color == BLACK and node.sibling.rchild.color == BLACK:
node.sibling.color = RED
node.parent.color = BLACK
else:
self._delete_case5(node)
def _delete_case5(self, node):
if node == node.parent.lchild and node.sibling.rchild == BLACK:
node.sibling.color = RED
node.sibling.lchild = BLACK
self._rotate_right(node.sibling)
elif node == node.parent.rchild and node.sibling.lchild == BLACK:
node.sibling.color = RED
node.sibling.rchild = BLACK
self._rotate_left(node.sibling)
self._delete_case6(node)
def _delete_case6(self, node):
node.sibling.color = node.parent.color
node.parent.color = BLACK
if node == node.parent.lchild:
node.sibling.rchild.color = BLACK
self._rotate_left(node.parent)
else:
node.sibling.lchild.color = BLACK
self._rotate_right(node.parent)
# This is a transversal
def DFS(self, ttype=0):
self.type = ttype
if self.root:
self.nodes = []
if self.root.has_children():
self._depth_recurse(self.root)
else:
self.nodes.append(self.root.key)
return self.nodes
else:
return None
def _depth_recurse(self, node):
# Preorder
if self.type == 0:
self.nodes.append(node.key)
if node.has_lchild():
if not node.lchild.key in self.nodes:
self._depth_recurse(node.lchild)
# Inorder
if self.type == 1:
self.nodes.append(node.key)
if node.has_rchild():
if not node.rchild.key in self.nodes:
self._depth_recurse(node.rchild)
# Postorder
if self.type == 2:
self.nodes.append(node.key)
return
def BFS(self):
q = queue.Queue()
nodes = []
q.enqueue(self.root)
while q.head:
current = q.dequeue()
nodes.append(current.key)
if current.has_lchild():
q.enqueue(current.lchild)
if current.has_rchild():
q.enqueue(current.rchild)
return nodes
if __name__ == "__main__":
tree = RBT()
for i in ['j','f', 'a', 'd', 'w', 'h', 'n', 'o', 'k' ]:
tree[i] = 0
print(tree.DFS())
print(tree.BFS())
# if __name__ == "__main__":
# mytree = BST()
# mytree[3]="red"
# mytree[4]="blue"
# mytree[6]="yellow"
# mytree[2]="at"
# print(mytree.find(6))
# print(mytree[2])
# mytree.delete(4)
# print(mytree[6])
# print(mytree[4])
|
c860c1f1c4ddeb99e540b3e526287b5c6c166b93 | vignesh787/PythonDevelopment | /Week11Lec5.py | 196 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 19 07:50:19 2021
@author: Vignesh
"""
a = 10
b = 20
'''
if a < b :
small = a
else:
small = b
'''
small = a if a < b else b
print(small) |
7c3f19fa73e05e78f6496bcc609b1658718da321 | yubi5co/python-practice | /Python_basic/2.2day/07. 문자열, 슬라이싱.py | 824 | 4.0625 | 4 | # 문자열
sentence = 'hello world'
print(sentence)
sentence2 = "hello human"
print(sentence2)
sentence3 = '''
it's funny programming
and easy language!!'''
print(sentence3)
# 슬라이싱
주민번호 = '990120-1234567'
print('성별 :' +주민번호[7]) # []: 번호의 위치 (순서는 왼쪽에서 오른쪽으로, 0부터이다.)
print('년 :' +주민번호[0:2]) # [0:2]: 0부터2직전값 까지(0~1)
print('월 :' +주민번호[2:4])
print('일 :' +주민번호[4:6])
print('생년월일 :' + 주민번호[:6]) # [:6]: 처음부터 6직전까지(0~5)
print('뒤 7자리 :' + 주민번호[7:]) # [7:]: 7부터 끝까지(7~)
print('뒤 7자리 (뒤에서 부터) :'+주민번호[-7:]) # 맨 뒤에 7번째부터 끝까지 |
8a4746e88d01215419422b19daa94af4e8a21b88 | itchenfei/leetcode | /304. 二维区域和检索 - 矩阵不可变/python_solution_1.py | 905 | 3.578125 | 4 | # 给定 matrix = [
# [3, 0, 1, 4, 2],
# [5, 6, 3, 2, 1],
# [1, 2, 0, 1, 5],
# [4, 1, 0, 1, 7],
# [1, 0, 3, 0, 5]
# ]
#
# sumRegion(2, 1, 4, 3) -> 8
# sumRegion(1, 1, 2, 2) -> 11
# sumRegion(1, 2, 2, 4) -> 12
# 上图子矩阵左上角 (row1, col1) = (2, 1) ,右下角(row2, col2) = (4, 3),该子矩形内元素的总和为 8。
class NumMatrix:
def __init__(self, matrix):
self.matrix = matrix
def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:
cnt = 0
matrix_rows = self.matrix[row1: row2+1]
for row in matrix_rows:
cnt += sum(row[col1: col2 + 1])
return cnt
if __name__ == '__main__':
matrix = [
[3, 0, 1, 4, 2],
[5, 6, 3, 2, 1],
[1, 2, 0, 1, 5],
[4, 1, 0, 1, 7],
[1, 0, 3, 0, 5]
]
NumMatrix(matrix).sumRegion(2, 1, 4, 3) |
29deca3f01fb54a7f253006676f3b374bf60050f | Stevvie5/csc401 | /csc401_homework3.py | 1,621 | 3.859375 | 4 |
sample_data = [
'Laaibah,208.10,10',
'Arnold,380.999,9',
'Sioned,327.01,1',
'Shayaan,429.50,2',
'Renee,535.29,4'
]
def print_columns(data):
print('Name Cost Items Total')
for words in data:
word = words.split(",")
print('{:20}{:6.2f} {:6} {:6.2f}'.format(words[0:4], float(word[1]), int(word[2]),float(word[1])*int(word[2])))
def scan_for(file_name, word):
'''print the number of occurences of a target
word in specified file.'''
infile = open(file_name, 'r')
content = infile.read()
infile.close()
text = str.maketrans('.!?', 3*' ')
content = content.translate(text)
content = content.split()
print(f'The word {word} appears {content.count(word)} times in {file_name}')
def calc_tax(in_file_name, out_file_name):
with open(in_file_name, 'r') as infile, open(out_file_name, 'w') as outfile:
lines = infile.readlines()
for line in lines:
tax_amount ='{:6.2f}'.format((float(line.split()[1]))*(float(line.split()[2])))
outfile.write(str(tax_amount)+"\n")
# --------------------------------------------
# STOP! Do not change anything below this line
# The code below makes this file 'self-testing'
# --------------------------------------------
def show_file(file_name):
with open(file_name, 'r') as result_file:
print(result_file.read())
if __name__ == "__main__":
import doctest
doctest.testfile('csc401_homework3_test.txt', verbose = True, optionflags=doctest.NORMALIZE_WHITESPACE)
|
b5025d44ff83b51bf94bab019631ae86304229a4 | misbahmehmood/Python | /number slicing with module.py | 183 | 3.5625 | 4 | import random
def first_last6(nums):
if nums[0]==6 or nums[-1] == 6:
return True
else:
return False
list= random.sample(range(0,50),5)
print(first_last6(list)) |
9b98954eca57ddd280e325689adb90d3c5bdeaaf | dcryptOG/pyclass-notes | /4_functions/3_function_practice.py | 10,937 | 3.890625 | 4 | # WARMUP SECTION:
# LESSER OF TWO EVENS: Write a function that returns the lesser of two given numbers if both numbers are even, but returns the greater if one or both numbers are odd
# lesser_of_two_evens(2,4) --> 2
# lesser_of_two_evens(2,5) --> 5
def even_odds(a, b):
if a % 2 == 0 and b % 2 == 0:
return min(a, b)
else:
return max(a, b)
print(even_odds(3, 9))
# ANIMAL CRACKERS: Write a function takes a two-word string and returns True if both words begin with same letter
test_string = 'Hello you'
# def str_two(st):
# words = st.split()
# if words[0][0].lower() == words[1][0].lower():
# return True
# else:
# return False
# print('What', str_two('fuck Fuck'))
def animal_crackers(text):
wordlist = text.split()
return wordlist[0][0] == wordlist[1][0]
print(animal_crackers('fuck Fuck'))
# animal_crackers('Levelheaded Llama') --> True
# animal_crackers('Crazy Kangaroo') --> False
# def animal_crackers(text):
# pass
# animal_crackers('Levelheaded Llama')
# animal_crackers('Crazy Kangaroo')
def twentys(x1, x2):
nums = [x1, x2]
return sum(nums) == 20 or 20 in nums
# MAKES TWENTY: Given two integers, return True if the sum of the integers is 20 or if one of the integers is 20. If not, return False
def add(x1, x2):
if (x1 + x2) == 20 or x1 == 20 or x2 == 20:
return True
else:
return False
def makes_twenty(n1, n2):
return (n1+n2) == 20 or n1 == 20 or n2 == 20
print(add(10, 20))
# makes_twenty(20,10) --> True
# makes_twenty(12,8) --> True
# makes_twenty(2,3) --> False
# def makes_twenty(n1,n2):
# pass
# makes_twenty(20,10)
# makes_twenty(2,3)
def yodaz(init):
words = init.split()
return ' '.join(words[::-1])
# LEVEL 1 PROBLEMS
# OLD MACDONALD: Write a function that capitalizes the first and fourth letters of a name
st = 'helloyou'
def caps(st):
if len(st) > 3:
return st[:3].capitalize() + st[3:].capitalize()
else:
return 'String too short'
print(caps(st))
# ! MASTER YODA: Given a sentence, return a sentence with the words reversed
# todo FINISH DIS ONE NOW
# master_yoda('I am home') --> 'home am I'
# master_yoda('We are ready') --> 'ready are We'
# Note: The .join() method may be useful here. The .join() method allows you to join together strings in a list with some connector string.
# For example, some uses of the .join() method:
# sen = 'I am home'
# words = sen.split()
# new = words.pop()
# words.insert(0, new)
def yoda(sen):
words = sen.split()
words.insert(0, words.pop())
return ' '.join(words)
# ! better returns string
def master_yoda(text):
return ' '.join(text.split()[::-1])
print(yoda('I am home'))
# >>> "_0_".join(['a','b','c'])
# >>> 'a_0_b_0_c'
# This means if you had a list of words you wanted to turn back into a sentence, you could just join them with a single space string:
# >>> " ".join(['Hello','world'])
# >>> "Hello world"
# def master_yoda(text):
# pass
# master_yoda('I am home')
# master_yoda('We are ready')
# ! ALMOST THERE: Given an integer n, return True if n is within 10 of either 100 or 200
# almost_there(90) --> True
# almost_there(104) --> True
# almost_there(150) --> False
# almost_there(209) --> True
def almost(n):
return abs(n) in range(90, 111) or abs(n) in range(190, 211)
def almost_there(n):
return ((abs(100 - n) <= 10) or (abs(200 - n) <= 10))
# LEVEL 2 PROBLEMS
# FIND 33:
# ! Given a list of ints, return True if the array contains a 3 next to a 3 somewhere.
# has_33([1, 3, 3]) → True
# has_33([1, 3, 1, 3]) → False
# has_33([3, 1, 3]) → False
# new = list(enumerate(lst))
def adj3(nums):
for i in range(len(nums)-1):
if nums[i] == 3 and nums[i+1] == 3:
return True
return False
def has_33(nums):
for i in range(0, len(nums)-1):
# nicer looking alternative in commented code
# return nums[i] == 3 and nums[i+1] == 3
return nums[i:i+2] == [3, 3]
# * i+2 because it stops @ but doesn't include i+2
print(adj3([1, 3, 3, 1, 2, 3]), 'nice')
# x = lst.index()
# i for i in enumerate(lst):
# if lst.count(3) > 1:
# for lst
# return lst.index(3, 0, stop)
# has_33([1, 3, 3])
# has_33([1, 3, 1, 3])
# has_33([3, 1, 3])
# ! PAPER DOLL: Given a string, return a string where for every character in the original there are three characters
def extra(str):
result = ''
for char in str:
result += char*3
return result
print(extra('MMMiiissssssiiippppppiii'))
cs = 'mississippi'
print(''.join([c*3 for c in cs]))
# paper_doll('Hello')
# paper_doll('Mississippi')
# print(extra('hello')
# paper_doll('Mississippi') --> 'MMMiiissssssiiippppppiii'
# numbers = [2.5, 3, 3, 4, -5]
# numbers.remove(3)
# print(numbers)
# ! BLACKJACK: Given three integers between 1 and 11, if their sum is less than or equal to 21, return their sum. If their sum exceeds 21 and there's an eleven, reduce the total sum by 10. Finally, if the sum (even after adjustment) exceeds 21, return 'BUST'
# print('numbers', numbers)
# start parameter is not provided
# numbersSum = sum(numbers)
# print(numbersSum)
# start = 10
# numbersSum = sum(numbers, 10)
# print(numbersSum)
# blackjack(5,6,7) --> 18
# blackjack(9,9,9) --> 'BUST'
# blackjack(9,9,11) --> 19
#! more complete uses lists of nums and prepares for multiple 11sw
def blackjack(nums):
amt = sum(nums)
if amt > 21 and nums.count(11) > 0:
while amt > 21 and nums.count(11) > 0:
nums.remove(11)
nums.append(1)
amt = sum(nums)
return"Total: {}".format(amt)
if amt > 21 and nums.count(11) == 0:
return "BUST: {}".format(amt)
if amt <= 21:
return "Total: {}".format(amt)
# blackjack(5,6,7)
# blackjack(9,9,9)
# def blackjack(a, b, c):
# if sum((a, b, c)) <= 21:
# return sum((a, b, c))
# elif sum((a, b, c)) <= 31 and 11 in (a, b, c):
# return sum((a, b, c)) - 10
# else:
# return 'BUST'
nums = [11, 11, 10]
print(blackjack(nums))
# ! SUMMER OF '69: Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 9 (every 6 will be followed by at least one 9). Return 0 for no numbers.
# summer_69([1, 3, 5]) --> 9
# summer_69([4, 5, 6, 7, 8, 9]) --> 9
# summer_69([2, 1, 6, 9, 11]) --> 14
def summer69(arr):
total = 0
add = True
for num in arr:
while add:
if num != 6:
total += num
break
else:
add = False
while not add:
if num != 9:
break
else:
add = True
break
return total
arr = [2, 1, 6, 1, 3, 9, 11]
print(summer69(arr))
# summer_69([1, 3, 5])
# summer_69([4, 5, 6, 7, 8, 9])
# print(sum([4, 5, 6, 7, 8, 9][0:2]))
# summer_69([2, 1, 6, 9, 11])
# *CHALLENGING PROBLEMS
# !SPY GAME: Write a function that takes in a list of integers and returns True if it contains 007 in order
# TODO FIND FIRST ZERO,
# arr = [1, 7, 2, 0, 4, 5, 0, 2]
# x = 0
# arr[x:].index(0)
# print(arr.index(0) > 0)
# todo if second zero SET RANGE
# print('hi', arr[4:].index(0))
# todo IF 7 AFTER RANGE PRINT TRUE
def spy007(arr):
if 2 <= arr.count(0):
if 0 <= arr[arr.index(0)+1:].index(0) < arr[arr.index(0)+1:].index(7):
return True
else:
return False
else:
return False
# ?
def mi6(arr):
for i in range(len(arr)-1):
if arr[i] == 0 and arr[i+1] == 0 and arr[i+2] == 7:
return True
return False
def spy_game(nums):
code = [0, 0, 7, 'x']
for num in nums:
if num == code[0]:
code.pop(0) # code.remove(num) also works
return len(code) == 1
print(spy_game([1, 0, 2, 4, 0, 5, 7]), 'sy')
#! find indexes of first two zeros
# spy_game([1,2,4,0,0,7,5])
# spy_game([1,0,2,4,0,5,7])
# spy_game([1,7,2,0,4,5,0])
# ! COUNT PRIMES: Write a function that returns the number of prime numbers that exist up to and including a given number
# count_primes(100) --> 25
def count_primes(num):
primes = [2]
x = 3
if num < 2: # for the case of num = 0 or 1
return 0
while x <= num:
for y in range(3, x, 2): # test all odd factors up to x-1
if x % y == 0:
x += 2
break
else:
primes.append(x)
x += 2
print(primes)
return len(primes)
# for y in range(3, x, 2): # test all odd factors up to x-1
#! faster version
def primes2(num):
primes = [2]
x = 3
if num < 2:
return 0
while x <= num:
for y in primes: # use the primes list!
if x % y == 0:
x += 2 # all odds
break
else:
primes.append(x)
x += 2
print(primes)
return len(primes)
lower = 1
upper = 10
# ! Prime is a number that is only divisible by 1 and ITSELF
# * in terms of whole numbers
# uncomment the following lines to take input from the user
# lower = int(input("Enter lower range: "))
# upper = int(input("Enter upper range: "))
def primes3(num):
x = 3
primes = [2]
if num < 2:
return 0
while x <= num:
for i in primes:
if (x % i) == 0:
x += 2
break
else:
primes.append(x)
x += 2
return primes
# By convention, 0 and 1 are not prime.
print(primes3(20))
# def count_primes(num):
# pass
# count_primes(100)
# ! CHECK IF NUM PRIME
def is_prime(a):
# return all(a % i !=0 for i in range(2, a))
return all(a % i for i in range(2, a))
# * a return of 0 is false so dont need a!=0
print(is_prime(5), 'is prime')
print(11 % 6)
################
#! Function return every other letter capitalize string
def foo(s):
ret = ""
i = True # capitalize
# ! i = True EQUIV i = 1
# i = 1
for char in s:
if i:
ret += char.lower()
else:
ret += char.upper()
if char != ' ':
i = not i
return ret
def myfunc10(str):
ret = ""
i = 0
for c in str:
if(i % 2 == 0):
ret += c.lower()
else:
ret += c.upper()
i += 1
return ret
x = "seMi Long StRing WiTH COMPLetely RaNDOM CasINg"
print(myfunc10(x))
print(foo('gkvkafdsgjg'))
x = x.split()
# ! print alphabet big letter
print(x)
def print_big(letter):
patterns = {1: ' * ', 2: ' * * ', 3: '* *', 4: '*****',
5: '**** ', 6: ' * ', 7: ' * ', 8: '* * ', 9: '* '}
alphabet = {'A': [1, 2, 4, 3, 3], 'B': [5, 3, 5, 3, 5], 'C': [
4, 9, 9, 9, 4], 'D': [5, 3, 3, 3, 5], 'E': [4, 9, 4, 9, 4]}
for pattern in alphabet[letter.upper()]:
print(patterns[pattern])
print_big('a')
|
a17a28135088fbac292437a7a95b328d7059ac72 | yxnga/compsci | /TASK 1/programming challenge 1/PYTHON.py | 169 | 3.859375 | 4 | timest = int(input("which timest?: "))
howm = int(input("how many?: "))
for i in range(1,howm+1):
product = i * timest
print(timest, "times", i, "equals", product)
|
7a252c15b4993f6696f8478f4fc11b003e084a98 | huitianbao/Python_study | /exe3advanced/09_function_exercises/sec_two.py | 433 | 3.734375 | 4 | #coding:utf8
import string
def func(name,callback=None):
if isinstance(name,str):
if callback==None:
return name.capitalize()
else:
return callback(name)
else:
print('输入有误,请重新输入')
assert func('lilei')=='Lilei'
# assert func('lilei',str.upper())=='LILEI
#此方法 string.upper python 2 有用,Python 3 没用
print(func('lilei',string.upper)) |
7284449524becd7d1a2a1c0c3d083d86d08796e4 | jorgeluisrocha/neural-networks | /perceptron.py | 2,223 | 3.9375 | 4 | """
AUTHOR: jorgeluisrocha
LAST UPDATED: 10-22-2016
This file in its current conception is to create a Perceptron object and
has two functions which allows it to learn how to behave like an OR gate and
an AND gate.
"""
from random import choice
from numpy import array, dot, random
from pylab import plot, ylim
class Perceptron:
def __init__(self):
## Create random weights for all inputs.
self.w = random.rand(3)
self.errors = [] ## Contain lists of errors
self.eta = 0.2 ## Learning rate
self.n = 100 ## Number of iterations
def ORGate(self, A, B):
## Create a lambda function for the step function in a perceptron.
unit_step = lambda x: 0 if x < 0 else 1
## Here is the training data for what an OR gate represents.
training_data = [
(array([0,0,1]), 0),
(array([0,1,1]), 1),
(array([1,0,1]), 1),
(array([1,1,1]), 1),
]
for i in range(self.n):
x, expected = choice(training_data)
result = dot(self.w, x)
error = expected - unit_step(result)
self.errors.append(error)
self.w += self.eta * error * x
data = array([A, B, 1])
result = dot(data, self.w)
print("{}: {} -> {}".format(data[:2], result, unit_step(result)))
def ANDGate(self, A, B):
## Create a lambda function for the step function in a perceptron.
unit_step = lambda x: 0 if x < 0 else 1
## Here is the training data for what an AND gate represents.
training_data = [
(array([0,0,1]), 0),
(array([0,1,1]), 0),
(array([1,0,1]), 0),
(array([1,1,1]), 1),
]
for i in range(self.n):
x, expected = choice(training_data)
result = dot(self.w, x)
error = expected - unit_step(result)
self.errors.append(error)
self.w += self.eta * error * x
data = array([A, B, 1])
result = dot(data, self.w)
print("{}: {} -> {}".format(data[:2], result, unit_step(result)))
|
eeaf574809ac76ba710e4349488f37604195c9b0 | jaredparmer/ThinkPythonRepo | /metathesis.py | 594 | 3.796875 | 4 | # these functions solve exercise 12.3 of Allen Downey's _Think Python_ 2nd ed.
from dict_fns import load_words_dict
from anagram_sets import signature, anagram_dict
def metathesis_pairs(d):
for anagrams in d.values():
for word1 in anagrams:
for word2 in anagrams:
if word1 < word2 and word_distance(word1, word2) == 2:
print(word1, word2)
def word_distance(word1, word2):
count = 0
for c1, c2 in zip(word1, word2):
if c1 != c2:
count += 1
return count
d = anagram_dict()
metathesis_pairs(d)
|
def2b8d3cb6044f0d11df046f56a3fee1a7b1d30 | cappe/DataAnalysis | /exercise_3/code/exercise_3.py | 6,407 | 3.515625 | 4 | import csv
import numpy as np
import math
import operator
from scipy import stats
def loadDataset(filename):
with open(filename, 'rb') as csvfile:
lines = csv.reader(csvfile)
dataset = list(lines)
normalized_data = []
for col in range(6):
column = []
for row in range(len(dataset)):
dataset[row][col] = float(dataset[row][col])
column.append(dataset[row][col])
normalized_column = stats.zscore(column)
for row in range(len(dataset)):
dataset[row][col] = normalized_column[row]
return dataset
# Calculates the euclidean distance between the two instances
def euclideanDistance(instance1, instance2, length):
distance = 0
for x in range(length):
distance += pow((instance1[x] - instance2[x]), 2)
return math.sqrt(distance)
# Returns a list of the closest neighbors for the given k
def getNeighbors_leave_one(dataset, testInstance, k, test_instance_row):
distances = []
length = 3
for row in range(len(dataset)):
if row != test_instance_row:
dist = euclideanDistance([testInstance[3], testInstance[4], testInstance[5]], [dataset[row][3], dataset[row][4], dataset[row][5]], length)
distances.append((dataset[row], dist))
distances.sort(key=operator.itemgetter(1))
neighbors = []
for x in range(k):
neighbors.append(distances[x][0])
return neighbors
def getNeighbors_leave_three(dataset, testInstance, k, round):
distances = []
length = 3
for row in range(len(dataset)):
if row < round or row > round + 2:
dist = euclideanDistance([testInstance[3], testInstance[4], testInstance[5]], [dataset[row][3], dataset[row][4], dataset[row][5]], length)
distances.append((dataset[row], dist))
distances.sort(key=operator.itemgetter(1))
neighbors = []
for x in range(k):
neighbors.append(distances[x][0])
return neighbors
# Returns the majority vote of the closest neighbors
def getResponse(neighbors):
c_average = []
cd_average = []
pb_average = []
for row in range(len(neighbors)):
c_average.append(neighbors[row][0])
cd_average.append(neighbors[row][1])
pb_average.append(neighbors[row][2])
c_average = np.mean(c_average)
cd_average = np.mean(cd_average)
pb_average = np.mean(pb_average)
return [c_average, cd_average, pb_average]
def Cindex(actual_values, predictions):
n = 0
h_num = 0
for i in range(0, len(actual_values)):
t = actual_values[i]
p = predictions[i]
for j in range(i+1, len(actual_values)):
nt = actual_values[j]
np = predictions[j]
if (t != nt):
n += 1
if (p < np and t < nt) or (p > np and t > nt):
h_num += 1
elif (p < np and t > nt) or (p > np and t < nt):
h_num = h_num
elif (p == np):
h_num += 0.5
c_index = h_num / n
return c_index
def construct_mean_value(testInstances):
testInstance_mean = [testInstances[0][0], testInstances[0][1], testInstances[0][2]]
for col in range(3, len(testInstances)+3):
column = []
for row in range(len(testInstances)):
column.append(testInstances[row][col])
testInstance_mean.append(np.mean(column))
return testInstance_mean
def leave_one_out():
dataset = loadDataset('Water_data.csv')
best_k_c_total = 0
best_k_cd = 0
best_k_pb = 0
best_c_index_c_total = 0
best_c_index_cd = 0
best_c_index_pb = 0
for k in range(1, 100):
predictions_c_total = []
predictions_cd = []
predictions_pb = []
actual_values_c_total = []
actual_values_cd = []
actual_values_pb = []
for row in range(0, 201):
testInstance = dataset[row]
neighbors = getNeighbors_leave_one(dataset, testInstance, k, row)
result = getResponse(neighbors)
predictions_c_total.append(result[0])
predictions_cd.append(result[1])
predictions_pb.append(result[2])
actual_values_c_total.append(testInstance[0])
actual_values_cd.append(testInstance[1])
actual_values_pb.append(testInstance[2])
c_index_c_total = Cindex(actual_values_c_total, predictions_c_total)
c_index_cd = Cindex(actual_values_cd, predictions_cd)
c_index_pb = Cindex(actual_values_pb, predictions_pb)
if (c_index_c_total > best_c_index_c_total):
best_c_index_c_total = c_index_c_total
best_k_c_total = k
if (c_index_cd > best_c_index_cd):
best_c_index_cd = c_index_cd
best_k_cd = k
if (c_index_pb > best_c_index_pb):
best_c_index_pb = c_index_pb
best_k_pb = k
print ''
print ''
print 'Results for leave one out:'
print '------------------------------------------------'
print 'C-index (c_total): ' + repr(best_c_index_c_total) + ' when k: ' + repr(best_k_c_total)
print 'C-index (Cd): ' + repr(best_c_index_cd) + ' when k: ' + repr(best_k_cd)
print 'C-index (Pb): ' + repr(best_c_index_pb) + ' when k: ' + repr(best_k_pb)
def leave_three_out():
dataset = loadDataset('Water_data.csv')
best_k_c_total = 0
best_k_cd = 0
best_k_pb = 0
best_c_index_c_total = 0
best_c_index_cd = 0
best_c_index_pb = 0
for k in range(1, 100):
predictions_c_total = []
predictions_cd = []
predictions_pb = []
actual_values_c_total = []
actual_values_cd = []
actual_values_pb = []
round = 0
while (round < 201):
testInstance = construct_mean_value([dataset[round], dataset[round+1], dataset[round+2]])
neighbors = getNeighbors_leave_three(dataset, testInstance, k, round)
result = getResponse(neighbors)
predictions_c_total.append(result[0])
predictions_cd.append(result[1])
predictions_pb.append(result[2])
actual_values_c_total.append(testInstance[0])
actual_values_cd.append(testInstance[1])
actual_values_pb.append(testInstance[2])
round += 3
c_index_c_total = Cindex(actual_values_c_total, predictions_c_total)
c_index_cd = Cindex(actual_values_cd, predictions_cd)
c_index_pb = Cindex(actual_values_pb, predictions_pb)
if (c_index_c_total > best_c_index_c_total):
best_c_index_c_total = c_index_c_total
best_k_c_total = k
if (c_index_cd > best_c_index_cd):
best_c_index_cd = c_index_cd
best_k_cd = k
if (c_index_pb > best_c_index_pb):
best_c_index_pb = c_index_pb
best_k_pb = k
print ''
print ''
print 'Results for leave three out:'
print '------------------------------------------------'
print 'C-index (c_total): ' + repr(best_c_index_c_total) + ' when k: ' + repr(best_k_c_total)
print 'C-index (Cd): ' + repr(best_c_index_cd) + ' when k: ' + repr(best_k_cd)
print 'C-index (Pb): ' + repr(best_c_index_pb) + ' when k: ' + repr(best_k_pb)
print ''
print ''
leave_one_out()
leave_three_out() |
cb5ab0a8d40a039c71364a5b6e0d541b303d4b8a | hocinebib/Projet_Court_H-H | /src/comp_plot.py | 909 | 3.765625 | 4 | #! /usr/bin/python3
"""
plot two lists of values
"""
from matplotlib import pyplot as plt
def compare_plot(lst_rsa, lst_pjct, res_lst):
"""
Plot the accessibility values obtained by our program and the ones
given by naccess
Arguments :
lst_rsa : list of naccess residus accessibility
lst_pjct : list of our residus accessibility
res_lst : list of residu names
"""
compare = []
for i in range(len(lst_rsa)-(len(lst_rsa)-len(lst_pjct))):
compare.append(abs(lst_rsa[i]-lst_pjct[i]))
plt.plot(lst_rsa, label="Naccess result")
plt.plot(lst_pjct, label="Our result")
plt.plot(compare, label="Difference")
plt.xticks(range(len(lst_rsa)), res_lst)
plt.xlabel("Residus")
plt.ylabel("Accessibility")
plt.legend()
plt.show()
if __name__ == "__main__":
import comp_plot
print(help(comp_plot))
|
eef616e6a1f35932a96686634155918277dab3ef | hoylemd/hutils | /python/packages/Unix/hutils/numberLists.py | 476 | 3.890625 | 4 | # hutils.numberLists module
import random
import math
# function to generate a list of random integers
def generateInts(num_numbers, lower, upper):
# calculate the range
list_range = upper - lower
# seed the random number generator
random.seed()
#initialize the list
new_list = list()
# generate the random ints
for i in range(num_numbers):
newNumber = int(math.floor((random.random() * list_range)
+ lower))
new_list.append(newNumber)
return new_list |
eec3b4a10688888a233bfb7afd6dfb010d6ad3ce | zcgu/leetcode | /codes/23. Merge k Sorted Lists.py | 653 | 3.828125 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
from heapq import *
hp = []
for node in lists:
if node:
heappush(hp, (node.val, node))
h = ListNode(0)
p = h
while hp:
p.next = heappop(hp)[1]
p = p.next
if p.next:
heappush(hp, (p.next.val, p.next))
return h.next |
c3a18ea98e13eceef42a4e6e015fae9885b10bb3 | jocoder22/PythonDataScience | /DataFrameManipulation/stack_unstack.py | 963 | 3.890625 | 4 | import pandas as pd
#################### Stack and Unstack
# Unstack users by 'weekday': byweekday
byweekday = users.unstack(level='weekday')
# Print the byweekday DataFrame
print(byweekday)
# Stack byweekday by 'weekday' and print it
print(byweekday.stack(level='weekday'))
# Unstack users by 'city': bycity
bycity = users.unstack(level='city')
# Print the bycity DataFrame
print(bycity)
# Stack bycity by 'city' and print it
print(bycity.stack(level='city'))
# Stack 'city' back into the index of bycity: newusers
newusers = bycity.stack(level='city')
# Swap the levels of the index of newusers: newusers
newusers = newusers.swaplevel(0, 1)
# Print newusers and verify that the index is not sorted
print(newusers)
# Sort the index of newusers: newusers
newusers = newusers.sort_index()
# Print newusers and verify that the index is now sorted
print(newusers)
# Verify that the new DataFrame is equal to the original
print(newusers.equals(users))
|
e60c61c4414148f4586500828a71aa5429b0d013 | shanbumin/py-beginner | /012-tuple/demo03/main.py | 1,515 | 3.890625 | 4 | # 元组的应用场景
#打包和解包操作。
# 打包
a = 1, 10, 100
print(type(a), a) # <class 'tuple'> (1, 10, 100)
# 解包
i, j, k = a
print(i, j, k) # 1 10 100
# 在解包时,如果解包出来的元素个数和变量个数不对应,会引发ValueError异
#有一种解决变量个数少于元素的个数方法,就是使用星号表达式,
# 我们之前讲函数的可变参数时使用过星号表达式。
# 有了星号表达式,我们就可以让一个变量接收多个值,代码如下所示。
# 需要注意的是,用星号表达式修饰的变量会变成一个列表,列表中有0个或多个元素。
# 还有在解包语法中,星号表达式只能出现一次。
a = 1, 10, 100, 1000
i, j, *k = a
print(i, j, k) # 1 10 [100, 1000]
i, *j, k = a
print(i, j, k) # 1 [10, 100] 1000
*i, j, k = a
print(i, j, k) # [1, 10] 100 1000
*i, j = a
print(i, j) # [1, 10, 100] 1000
i, *j = a
print(i, j) # 1 [10, 100, 1000]
i, j, k, *l = a
print(i, j, k, l) # 1 10 100 [1000]
i, j, k, l, *m = a
print(i, j, k, l, m) # 1 10 100 1000 []
#需要说明一点,解包语法对所有的序列都成立,这就意味着对字符串、列表以及我们之前讲到的range函数返回的范围序列都可以使用解包语法。大家可以尝试运行下面的代码,看看会出现怎样的结果。
a, b, *c = range(1, 10)
print(a, b, c)
a, b, c = [1, 10, 100]
print(a, b, c)
a, *b, c = 'hello'
print(a, b, c)
|
a18d804b3bc24c3f7b4e4c3ae5272dc75ad8acb5 | iCodeIN/data_structures | /dynamic_programming/target_ways.py | 453 | 3.671875 | 4 | import collections
def findTargetSumWays(A, S):
count = collections.Counter({0: 1})
for x in A:
step = collections.Counter()
for y in count:
step[y + x] += count[y]
step[y - x] += count[y]
count = step
print(step)
return count[S]
if __name__=='__main__':
# a list of non negative integers, list all the ways it equals target S
print(findTargetSumWays(A=[1, 1, 1, 1, 1], S=3)) |
8cd7080aabdd298cb339ccd673eb4696316092b0 | pololee/oj-leetcode | /companies/affirm/expression_evaluation.py | 1,737 | 3.875 | 4 | import unittest
from functools import reduce
class ExpressionEvaluation:
def evaluate(self, s):
if not s:
return 0
return self.evaluateUtil(s.split(' '))
def evaluateUtil(self, array):
if not array:
return 0
size = len(array)
i = 0
operator = ''
nums = []
while i < size:
if array[i] == '(':
left = i
i = self.rightBracket(array, left)
numTmp = self.evaluateUtil(array[left+1:i])
nums.append(numTmp)
elif array[i] in ('add', 'mul'):
operator = array[i]
else:
nums.append(int(array[i]))
i += 1
if not nums:
return 0
if operator == 'add':
return sum(nums)
elif operator == 'mul':
return reduce((lambda x, y: x * y), nums)
return nums[-1]
def rightBracket(self, array, left):
right = left + 1
size = len(array)
cnt = 1
while right < size and cnt > 0:
if array[right] == '(':
cnt += 1
elif array[right] == ')':
cnt -= 1
right += 1
return right - 1
class ExpressionEvaluationTest(unittest.TestCase):
def testEvaluate(self):
s1 = "( )"
s2 = "( add )"
s3 = "( mul )"
s4 = "( add 1 2 ( mul 3 4 5 ) 6 )"
sol = ExpressionEvaluation()
self.assertEqual(0, sol.evaluate(s1))
self.assertEqual(0, sol.evaluate(s2))
self.assertEqual(0, sol.evaluate(s3))
self.assertEqual(69, sol.evaluate(s4))
if __name__ == "__main__":
unittest.main()
|
4d340841b4d895e9c38e87cf9b38b127f8ffef09 | yayshine/pyQuick | /google-python-exercises/basic/wordcount.py | 2,751 | 4.3125 | 4 | #!/usr/bin/python -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
"""Wordcount exercise
Google's Python class
The main() below is already defined and complete. It calls print_words()
and print_top() functions which you write.
1. For the --count flag, implement a print_words(filename) function that counts
how often each word appears in the text and prints:
word1 count1
word2 count2
...
Print the above list in order sorted by word (python will sort punctuation to
come before letters -- that's fine). Store all the words as lowercase,
so 'The' and 'the' count as the same word.
2. For the --topcount flag, implement a print_top(filename) which is similar
to print_words() but which prints just the top 20 most common words sorted
so the most common word is first, then the next most common, and so on.
Use str.split() (no arguments) to split on all whitespace.
Workflow: don't build the whole program at once. Get it to an intermediate
milestone and print your data structure and sys.exit(0).
When that's working, try for the next milestone.
Optional: define a helper function to avoid code duplication inside
print_words() and print_top().
"""
import sys
def dictionizeFile(filename):
"""Returns a word/count dict for this filename"""
countDict = {}
f = open(filename, 'rU')
for line in f:
line = line.lower()
line = line.split()
for word in line:
if countDict.get(word):
countDict[word] += 1
else:
countDict[word] = 1
f.close()
return countDict
def print_words(filename):
"""Prints one '<word> <count>' per line, sorted by words"""
countDict = dictionizeFile(filename)
count = sorted(countDict.keys())
for word in count:
print word, countDict[word]
def countSort(tuple):
"""Used to do custom sorting for the word counts"""
return tuple[1]
def print_top(filename):
"""Prints the top 20 most used words in the form of '<word> <count>'"""
countDict = dictionizeFile(filename)
top = sorted(countDict.items(), key=countSort, reverse=True)
for item in top[:20]:
print item[0], item[1]
# This basic command line argument parsing code is provided and
# calls the print_words() and print_top() functions which you must define.
def main():
if len(sys.argv) != 3:
print 'usage: ./wordcount.py {--count | --topcount} file'
sys.exit(1)
option = sys.argv[1]
filename = sys.argv[2]
if option == '--count':
print_words(filename)
elif option == '--topcount':
print_top(filename)
else:
print 'unknown option: ' + option
sys.exit(1)
if __name__ == '__main__':
main()
|
8bf496aa75e60eb1c0dc150a896f81ad65776309 | ironsketch/pythonSeattleCentral | /tests/QUIZ6/MichelleBerginQuiz6.py | 1,157 | 3.9375 | 4 | # Importing random
from random import randint
# Using random to pick a number 1 or 0
def flipCoin():
flip = randint(0,1)
return flip
# Using flipCoin multiple times and adding up the total of heads
def flipCoins(n):
counter = 0
for i in range (n):
flip = flipCoin()
if flip == 1:
counter += 1
return counter
# Using random to pick a number 1 - 6
def rollDie():
roll = randint(1,6)
return roll
# Using rollDie multiple times and adding up the dice total
def rollDice(n):
counter = 0
for i in range (n):
roll = rollDie()
counter += roll
return counter
# Using the previous functions to create a tuple of the results
# side by side
def tossAndRoll(n):
tup = ()
flip = flipCoins(n)
roll = rollDice(n)
tup = flip,roll
return tup
# Finally putting them into a dictionary to see the frequency of each
# Toss and roll together
def tossAndRollRepeat(n,m):
both = {}
for i in range (m):
tup = tossAndRoll(n)
if tup in both:
both[tup] += 1
else:
both[tup] = 1
print(both)
tossAndRollRepeat(5,500)
|
3252f20d479d10a4abe864bb34cd41815e6b285c | rprouse/python-for-dotnet | /ch03-lang/l05_generators.py | 282 | 3.859375 | 4 | def main():
for n in fibonacci():
if(n > 1000):
break
print(n, end=', ')
def fibonacci():
current, nxt = 0, 1
while True:
current, nxt = nxt, nxt + current
yield current
if __name__ == '__main__':
main() |
c9b0749c5c726729cf5419234d15c5118bb11b6f | ladosamushia/PHYS639 | /Projectile/Projectile_Mikelobe.py | 2,743 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 4 13:28:41 2018
@author: Mikelobe
"""
import numpy as np
import matplotlib.pyplot as plt
#Simple Projectile Motion
x0=0 #initial position
y0=0
t0=0 #initial time
v0y=200 #initial velocity
v0x=60
tfin=100
Nsteps=1000000
Fx=0 #force in x
Fy=-9.8 #force in y
m=1 #mass
t=np.linspace(t0,tfin,Nsteps+1)
x=np.zeros(Nsteps+1)
x[0]=x0
y=np.zeros(Nsteps+1)
y[0]=y0
vx=np.zeros(Nsteps+1)
vx[0]=v0x
vy=np.zeros(Nsteps+1)
vy[0]=v0y
dt=(tfin-t0)/Nsteps #slight changes in time
for i in range(1,Nsteps+1): #loop for projectile motion
x[i]=x[i-1]+vx[i-1]*dt
vx[i]=vx[i-1]+(Fx/m)*dt
y[i]=y[i-1]+vy[i-1]*dt
vy[i]=vy[i-1]+(Fy/m)*dt
if y[i]<0: #how the loop knows when to stop
print('Total time', i*dt) #print max value of time
break
plt.plot(x,y,'g.') #plot the loop
print('max in x=',np.max(x),'max in y=',np.max(y)) #print max values of x and y
#Air Resistance
t=np.linspace(t0,tfin,Nsteps+1)
x=np.zeros(Nsteps+1)
x[0]=x0
y=np.zeros(Nsteps+1)
y[0]=y0
vx=np.zeros(Nsteps+1)
vx[0]=v0x
vy=np.zeros(Nsteps+1)
vy[0]=v0y
dt=(tfin-t0)/Nsteps
for i in range(1,Nsteps+1):
x[i]=x[i-1]+vx[i-1]*dt
vx[i]=vx[i-1]+(Fx/m)*dt
y[i]=y[i-1]+vy[i-1]*dt
vy[i]=vy[i-1]+(Fy/m)*dt
Fx=-0.0004*vx[i-1]**2
Fy=-9.8-(0.0004*vy[i-1]**2)
if y[i]<0:
print('Total time', i*dt)
break
plt.plot(x,y,'b.')
print('max in x=',np.max(x),'max in y=',np.max(y))
#Change in Air Resistance
t=np.linspace(t0,tfin,Nsteps+1)
x=np.zeros(Nsteps+1)
x[0]=x0
y=np.zeros(Nsteps+1)
y[0]=y0
vx=np.zeros(Nsteps+1)
vx[0]=v0x
vy=np.zeros(Nsteps+1)
vy[0]=v0y
dt=(tfin-t0)/Nsteps
for i in range(1,Nsteps+1):
x[i]=x[i-1]+vx[i-1]*dt
vx[i]=vx[i-1]+(Fx/m)*dt
y[i]=y[i-1]+vy[i-1]*dt
vy[i]=vy[i-1]+(Fy/m)*dt
Fx=-((0.0004*vx[i-1]**2)*(1-(0.000022*y[i-1]))**(2.5))
Fy=-9.8-((0.0004*vy[i-1]**2)*(1-(0.000022*y[i-1]))**(2.5))
if y[i]<0:
print('Total time', i*dt)
break
plt.plot(x,y,'y.')
print('max in x=',np.max(x),'max in y=',np.max(y))
#Changes in Gravity
t=np.linspace(t0,tfin,Nsteps+1)
x=np.zeros(Nsteps+1)
x[0]=x0
y=np.zeros(Nsteps+1)
y[0]=y0
vx=np.zeros(Nsteps+1)
vx[0]=v0x
vy=np.zeros(Nsteps+1)
vy[0]=v0y
dt=(tfin-t0)/Nsteps
for i in range(1,Nsteps+1):
x[i]=x[i-1]+vx[i-1]*dt
vx[i]=vx[i-1]+(Fx/m)*dt
y[i]=y[i-1]+vy[i-1]*dt
vy[i]=vy[i-1]+(Fy/m)*dt
Fx=-((0.0004*vx[i-1]**2)*(1-(0.000022*y[i-1]))**(2.5))
Fy=-9.8-((0.0004*vy[i-1]**2)*(1-(0.000022*y[i-1]))**(2.5))
if y[i]<0:
print('Total time', i*dt)
break
plt.plot(x,y,'r.')
print('max in x=',np.max(x),'max in y=',np.max(y)) |
2e6d1343abc058926c7d187de59ac3c75e1285a5 | Modester-mw/assignmentQ2 | /main.py | 1,712 | 4.0625 | 4 | Question 2
In plain English and with the Given-required-algorithm table write a guessing game where the user has to guess a secret number. After every guess the program tells the user whether their number was too large or too small. At the end the number of tries needed should be printed. It counts only as one try if they input the same number multiple times consecutively.
Given
We are writing a program for a number guessing game.
The secret number is an integer.
The program displays a message after every guess saying whether the number was too large or too small.
The program counts and records the number of unique guesses made.
The program congratulates the user once the secret number is guessed correclty.
Required
Write a guessing game(program).
Guess a secret number for such as”4”.
To write a program that tells the user whether the number guessed is too large or too small.
Write a program that prints the number of tries made..
Create the program such that it counts one try when the user guesses the same number multiple times consecutively.
Algorithm
Let the range where the secret number lies be from 1 to 50.
We guess the value “15” as the secret number.
Assign the value 15 to variable X such that X = 15.
The user requested to guess the number from 1 to 50.
If the # guessed is <15 the program tells the user the number is “too small”.
If the user guesses a # >15 the program says the number is “too large”.
If the user guesses X == 15 then the program congratulates the user for winning the game.
When a user wins the game, the program counts the number of tries made and prints them.
The game is over once the user guesses the number correctly.
|
1f15caa57a11a7b2db5345fdc76c84cb13124437 | Srinjana/CC_practice | /ALGORITHM/DP/catalannum.py | 1,445 | 4.03125 | 4 | # Catalan numbers are a sequence of natural numbers that occurs in many interesting counting problems like following.
# Count the number of expressions containing n pairs of parentheses which are correctly matched. For n = 3, possible expressions are ((())), ()(()), ()()(), (())(), (()()).
# Count the number of possible Binary Search Trees with n keys (See this)
# Count the number of full binary trees (A rooted binary tree is full if every vertex has either two children or no children) with n+1 leaves.
# Given a number n, return the number of ways you can draw n chords in a circle with 2 x n points such that no 2 chords intersect.
# See this for more applications.
# The first few Catalan numbers for n = 0, 1, 2, 3, … are 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, …
# can be solved using recursive formula [SUMATION{for i in range(0,n+1)}(Ci *C(n-i))]
# RECURSIVE
def catalan(n):
if n <= 1:
return 1
res = 0
for i in range(n):
res += catalan(i) * catalan(n-i-1)
return res
def DynamicCatalan(n):
if (n == 0 or n == 1):
return 1
# Table to store results of subproblems
catalan = [0]*(n+1)
catalan[0] = 1
catalan[1] = 1
for i in range(2, n + 1):
for j in range(i):
catalan[i] += catalan[j] * catalan[i-j-1]
# Return last entry
return catalan[n]
# Driver Code
for i in range(10):
print (catalan(i))
print(DynamicCatalan(i))
|
e11e9d9e39602863c996b12b296a67333c9a557d | bohdi2/euler | /problem59_cache_plus_brute_force.py | 1,744 | 3.9375 | 4 | #!/usr/bin/env python3
from itertools import cycle
import string
def read_cipher(filename):
"""returns a list of integers"""
with open(filename, "r") as filestream:
data = []
for line in filestream:
data += [int(s) for s in line.split(",")]
return data
def ints_to_string(l):
return "".join(map(chr, l))
def split_cipher(cipher):
return cipher[0::3], cipher[1::3], cipher[2::3]
def decode(key, cipher):
return ints_to_string([key ^ n for n in cipher])
def validate(text):
return all(c in string.printable for c in text)
def create_cache(encoded):
"""Creates a dictionary of xor -> decoded string"""
cache = {}
for k in range(128):
decoded = decode(k, encoded)
if validate(decoded):
cache[k] = decoded
return cache
def key_generator(c1, c2, c3):
"""returns a 3-tuple (xor, decode), (xor, decode), (xor, decode)"""
for a in c1.items():
print(a[0])
for b in c2.items():
for c in c3.items():
yield a, b, c # Changed to be a tuple
return
def decode2(key, cipher):
keys = cycle(key)
return ints_to_string([next(keys) ^ n for n in cipher])
def main():
cipher = read_cipher("p059_cipher.txt")
c1 = create_cache(cipher[0::3])
c2 = create_cache(cipher[1::3])
c3 = create_cache(cipher[2::3])
print(len(c1), len(c2), len(c3))
#print("c1 %s" % c1)
for key in key_generator(c1, c2, c3):
#print("key")
#print(key)
s = [c for t in zip(key[0][1], key[1][1], key[2][1]) for c in t]
ss = ''.join(s)
if "the " in ss:
print("%s: %s " % (key, ss))
if __name__ == "__main__":
main()
|
1aae9a3907db23fb19eec8cbd544e12798122264 | Jas1028/Assignment3 | /Function#2.py | 1,789 | 4.15625 | 4 |
def GetHowManyApplesYouWantToBuy():
NumberOfAppleFunc = int(input("An apple cost 20 pesos each. How many apple/s do you prefer to buy? "))
return NumberOfAppleFunc
def GetTotalAmountOfApplesYouNeedToPay(PreferredAppleF, PriceOfAppleF):
AmountOfAppleFunc = int(PreferredAppleF*PriceOfAppleF)
return AmountOfAppleFunc
def GetHowManyOrangesYouWantToBuy():
NumberOfOrangeFunc = int(input("An orange cost 25 pesos. How many orange/s do you prefer to buy? "))
return NumberOfOrangeFunc
def GetTotalAmountOfOrangesYouNeedToPay(PreferredOrangeF, PriceOfOrangeF):
AmountOfOrangeFunc = int(PreferredOrangeF*PriceOfOrangeF)
return AmountOfOrangeFunc
def GetTotalAmountOfApplesAndOranges(TotalOfAppleF, TotalOfOrangeF):
GeneralTotal = int(TotalOfAppleF) + (TotalOfOrangeF)
return GeneralTotal
def DisplayOutput(TotalOfAppleF, TotalOfOrangeF, TotalAmountF):
print(f"The amount of apple is {TotalOfAppleF} and the amount of orange is {TotalOfOrangeF}. ")
print(f"The total amount is {TotalAmountF}.")
# STEPS
# ask how many apples you want to buy and save to variable.
PreferredApple = GetHowManyApplesYouWantToBuy()
# display the amount of apple and save to variable
PriceOfApple = 20
TotalOfApple = GetTotalAmountOfApplesYouNeedToPay(PreferredApple, PriceOfApple)
# ask how many oranges you want and save to variable
PreferredOrange = GetHowManyOrangesYouWantToBuy()
# dispay the amount of orange and save to variable
PriceOfOrange = 25
TotalOfOrange = GetTotalAmountOfOrangesYouNeedToPay(PreferredOrange, PriceOfOrange)
# display the total amount and save the variable
TotalAmount = GetTotalAmountOfApplesAndOranges(TotalOfApple, TotalOfOrange)
# display the output
DisplayOutput(TotalOfApple, TotalOfOrange, TotalAmount)
|
cfc2466d3e88b83f9a46c04a50e4fa37b1747d76 | QuentinDuval/PythonExperiments | /graphs/RedundantConnection2_Hard.py | 4,594 | 3.953125 | 4 | """
https://leetcode.com/problems/redundant-connection-ii
In this problem, a rooted tree is a directed graph such that, there is exactly one node (the root)
for which all other nodes are descendants of this node, plus every node has exactly one parent,
except for the root node which has no parents.
The given input is a directed graph that started as a rooted tree with N nodes (with distinct values 1, 2, ..., N),
with one additional directed edge added. The added edge has two different vertices chosen from 1 to N,
and was not an edge that already existed.
The resulting graph is given as a 2D-array of edges. Each element of edges is a pair [u, v] that represents
a directed edge connecting nodes u and v, where u is a parent of child v.
Return an edge that can be removed so that the resulting graph is a rooted tree of N nodes.
If there are multiple answers, return the answer that occurs last in the given 2D-array.
"""
from collections import defaultdict
from typing import List
class Solution:
def findRedundantDirectedConnection(self, edges: List[List[int]]) -> List[int]:
"""
If there is a double parent for a node:
- one of the edge from one of these parent is good
- the other one might be good as well (or disconnect the graph)
Example:
a -> b <- e
| ^
v |
c -> d
'b' has two parents, but only (e,b) can be removed:
- no other letter than 'a' can be the root
- because we enter the cycle via 'a'
There might be cases in which there are no double parent for each nodes.
In such cases, we have a cycle:
a <- d -> e
| ^
v |
b -> c
Which edge to remove in the cycle is not important, all of these are equivalent.
- We can remove (a, b) => root will be 'b'
- We can remove (d, a) => root will be 'a'
- Etc
There are also cases in which there are no cycle, just 2 parents.
All of this is accounted below, beats 90%.
"""
nodes = set()
graph = defaultdict(list) # To find the cycle
igraph = defaultdict(list) # To find incoming edges
for u, v in edges:
graph[u].append(v)
igraph[v].append(u)
nodes.add(u)
nodes.add(v)
for start_node in nodes:
# If a node has two parents
if len(igraph[start_node]) >= 2:
# Either it comes from a cycle => eliminate the edge that is in the cycle
cycle = self.find_cycle(graph, set(), start_node)
if cycle:
for node in cycle:
if len(igraph[node]) >= 2:
for parent in igraph[node]:
if parent in cycle:
return [parent, node]
# Or it does not matter which edge to remove => choose the last one in the list
else:
highest_index = -1
for parent in igraph[start_node]:
index = edges.index([parent, start_node])
highest_index = max(highest_index, index)
return edges[highest_index]
# If there are no nodes with two parents
discovered = set()
for start_node in nodes:
if start_node in discovered:
continue
# Find a cycle
cycle = self.find_cycle(graph, discovered, start_node)
if cycle:
# Remove the last edge in the list that is in the cycle
last_edge = None
for u, v in edges:
if u in cycle and v in cycle:
last_edge = [u, v]
return last_edge
return None
def find_cycle(self, graph, discovered, start_node):
on_stack = set()
to_visit = [('visit', start_node)]
discovered.add(start_node)
while to_visit:
step, node = to_visit.pop()
if step == 'pop':
on_stack.remove(node)
else:
on_stack.add(node)
to_visit.append(('pop', node))
for neighbor in graph[node]:
if neighbor in on_stack:
return on_stack
if neighbor not in discovered:
to_visit.append(('visit', neighbor))
discovered.add(neighbor)
return set()
|
a89c86fec687e86b16746ffeccd4f396077bc616 | debryc/LPTHW | /ex11.py | 502 | 3.90625 | 4 | # print question and add comma to prevent new line after printing
print "How old are you?",
# initialize variable age as whatever someone inputs
age = raw_input()
print "How tall are you?",
height = raw_input()
print "How much do you weigh?",
weight = raw_input()
# print inputs
print "So, you're %r old, %r tall and %r heavy." % (
age, height, weight)
# using %r prints '5\'5"' instead of 5'5" because the escape key is
# needed in programming to allow printing ' instead of closing the string. |
96b1d5be314b1f77217556502c92eb7babdc0907 | jeanniton-mnr/cs50 | /pset6/credit/credit.py | 2,149 | 4.15625 | 4 |
# This program test if a credit card number is valid
# Author: Jeanniton Monero
# email: jeanniton.mnr@gmail.com
# website: jeanniton.me
def main():
card_number = None
card_number_str = None
card_len = None
total = None
# Get card number
print("Number: ", end="")
card_number = (int)(input())
# Get string representation of card number
card_number_str = str(card_number)
# Number of digit of card
card_len = len(card_number_str)
# Initialize `total` to zero (0)
total = 0
# Multiply each second/other digit by two (2) and
# add those products' digit together.
# NB: Starting at the last second digit
i = card_len - 2
while i >= 0:
digit = int(card_number_str[i])
# Decrement `i` to two (2) step
i -= 2
# Multiply digit by two (2)
prod = digit * 2
# Add product to `total`
rest = prod - 10
if rest >= 0:
total += rest
total += 1
else:
total += prod
# Let reset the variable `i`
i = None
# Now let's add the `total` of the digits that weren't multiplied by 2 to the `total`:
i = card_len - 1
while i >= 0:
digit = int(card_number_str[i])
total += digit
# Decrement `i` to two (2) step
i -= 2
# Let reset the variable `i`
i = None
# Check to see if the CC number is valid and in the appropriate range
if total % 10 == 0:
# Check AMEX CC
if (card_number >= 340000000000000 and card_number < 350000000000000) or (card_number >= 370000000000000 and card_number < 380000000000000):
print("AMEX")
# Check MASTERCARD CC
elif card_number >= 5100000000000000 and card_number < 5600000000000000:
print("MASTERCARD")
# Check VISA CC
elif (card_number >= 4000000000000 and card_number < 5000000000000) or (card_number >= 4000000000000000 and card_number < 5000000000000000):
print("VISA")
# No CC match: Print INVALID
else:
print("INVALID")
else:
print("INVALID")
if __name__ == "__main__":
main() |
a70e8bc4b728daa4715ce36085e663c1f77d9d58 | Serwach/SnakeGame | /snake5.py | 2,542 | 3.84375 | 4 | '''
Snake Game Part 5
'''
import curses
from curses import KEY_RIGHT, KEY_LEFT, KEY_DOWN, KEY_UP
from random import randint
WIDTH = 35
HEIGHT = 20
MAX_X = WIDTH - 2
MAX_Y = HEIGHT - 2
SNAKE_LENGTH = 5
SNAKE_X = SNAKE_LENGTH + 1
SNAKE_Y = 3
TIMEOUT = 100
class Snake(object):
REV_DIR_MAP = {
KEY_UP: KEY_DOWN, KEY_DOWN: KEY_UP,
KEY_LEFT: KEY_RIGHT, KEY_RIGHT: KEY_LEFT,
}
def __init__(self, x, y, window):
self.body_list = []
self.hit_score = 0
self.timeout = TIMEOUT
for i in range(SNAKE_LENGTH, 0, -1):
self.body_list.append(Body(x - i, y))
self.body_list.append(Body(x, y, '0'))
self.window = window
self.direction = KEY_RIGHT
self.last_head_coor = (x, y)
self.direction_map = {
KEY_UP: self.move_up,
KEY_DOWN: self.move_down,
KEY_LEFT: self.move_left,
KEY_RIGHT: self.move_right
}
@property
def score(self):
return 'Score : {}'.format(self.hit_score)
class Body(object):
def __init__(self, x, y, char='='):
self.x = x
self.y = y
self.char = char
@property
def coor(self):
return self.x, self.y
class Food(object):
#0 Erase all of food object
#1 Initalize the Food
def __init__(self, window, char='&'):
#2 choose random postion for food whenever its Initalized Boiiii
self.x = randint(1, MAX_X)
self.y = randint(1, MAX_Y)
#3 here, we are just satifying the arguments, and setting the food character
self.char = char
self.window = window
#4 Make Render Function
def render(self):
#5 This is using addstr, which is part of Curses Programing in Python, see https://docs.python.org/2/howto/curses.html
''' Because this is all going to be animated in the terminal via Curses, we use addstr to display the & character
The addstr() function takes a Python string as the value to be displayed,
while the addch() functions take a character, which can be either a Python string of length 1 or an integer
If it is a string, your limited to displaying characters between 0 and 255 0 and 255
in summary, this is adding food coordinates and character in string format when rendered '''
self.window.addstr(self.y, self.x, self.char)
#6 reset method, chooses new random coordinates when reset
def reset(self):
self.x = randint(1, MAX_X)
self.y = randint(1, MAX_Y)
|
ad93327b2baf0cf732802ade88d9ab85d61f0c5a | JPGITHUB1519/Web-Development-Udacity | /Lessons/Lesson 4- User Accounts and Security/verifying_hashed.py | 543 | 3.6875 | 4 | import hashlib
def hash_str(s):
return hashlib.md5(s).hexdigest()
def make_secure_val(s):
return "%s|%s" % (s, hash_str(s))
# -----------------
# User Instructions
#
# Implement the function check_secure_val, which takes a string of the format
# s,HASH
# and returns s if hash_str(s) == HASH, otherwise None
def check_secure_val(h):
###Your code here
lista = h.split('|')
if hash_str(lista[0]) == lista[1] :
return lista[0]
return None
print check_secure_val("hola,4d186321c1a7f0f354b297e8914ab240")
|
f63ce71f552ad28b64c25176e8b202885006c065 | Dvk2002/Algo | /t4.py | 535 | 4.1875 | 4 | #Пользователь вводит две буквы. Определить, на каких местах алфавита они стоят,
# и сколько между ними находится букв.
A = input('Введите первую букву : ')
B = input('Введите вторую букву : ')
a = ord(A)
b = ord(B)
print(f' Место первой буквы : {a - 96}')
print(f' Место второй буквы : {b - 96}')
print(f' Количество букв : {abs(a-b) - 1}')
|
f0ac3b8164669bed3090669eb7b8f2963044129d | hrithikguy/ProjectEuler | /p60.py | 1,944 | 3.8125 | 4 | import math
import numpy as np
#print "hi"
def is_prime(n):
if n == 2 or n == 3: return True
if n < 2 or n%2 == 0: return False
if n < 9: return True
if n%3 == 0: return False
r = int(n**0.5)
f = 5
while f <= r:
if n%f == 0: return False
if n%(f+2) == 0: return False
f +=6
return True
prime_list = []
for n in range(1, 10000):
if is_prime(n) == 1:
prime_list.append(n)
pair_list = set()
for i in prime_list:
for j in prime_list:
if j > i:
if is_prime(int(str(i) + str(j))) == 1 and is_prime(int(str(j) + str(i))) == 1:
pair_list.add((i,j))
print "pairs done"
print pair_list
triple_list = set()
for i in pair_list:
for j in prime_list:
if j > i[1] and is_prime(int(str(i[0]) + str(j))) == 1 and is_prime(int(str(j) + str(i[0]))) == 1:
if is_prime(int(str(i[1]) + str(j))) == 1 and is_prime(int(str(j) + str(i[1]))) == 1:
triple_list.add((i[0], i[1], j))
print "triples done"
print triple_list
quadruple_list = set()
for i in triple_list:
for j in prime_list:
if j > i[2] and is_prime(int(str(i[0]) + str(j))) == 1 and is_prime(int(str(j) + str(i[0]))) == 1:
if is_prime(int(str(i[1]) + str(j))) == 1 and is_prime(int(str(j) + str(i[1]))) == 1:
if is_prime(int(str(i[2]) + str(j))) == 1 and is_prime(int(str(j) + str(i[2]))) == 1:
quadruple_list.add((i[0], i[1], i[2], j))
print "quadruples done"
print quadruple_list
quintuple_list = set()
for i in quadruple_list:
for j in prime_list:
if j >i[3] and is_prime(int(str(i[0]) + str(j))) == 1 and is_prime(int(str(j) + str(i[0]))) == 1:
if is_prime(int(str(i[1]) + str(j))) == 1 and is_prime(int(str(j) + str(i[1]))) == 1:
if is_prime(int(str(i[2]) + str(j))) == 1 and is_prime(int(str(j) + str(i[2]))) == 1:
if is_prime(int(str(i[3]) + str(j))) == 1 and is_prime(int(str(j) + str(i[3]))) == 1:
quintuple_list.add((i[0], i[1], i[2], i[3], j))
print "quintuples done"
print quintuple_list
|
71958355fc594b8d7268ce25e17401e8f167206e | topherCantrell/countdown | /src/app_count.py | 1,800 | 3.890625 | 4 | import datetime
import time
import hardware
def int_to_string(value,pad_to,pad_char='*'):
ret = str(value)
while len(ret)<pad_to:
ret = pad_char+ret
return ret
def show_date(date):
now_month = int_to_string(date.month,2,'0')
now_day = int_to_string(date.day,2,'0')
now_year = int_to_string(date.year,4,'0')
#
now_hour = int_to_string(date.hour,2,'0')
now_minute = int_to_string(date.minute,2,'0')
now_second = int_to_string(date.second,2,'0')
hardware.set_digits(now_month+now_day+now_year)
time.sleep(5)
hardware.set_digits(now_hour+now_minute+now_second)
time.sleep(5)
date = datetime.datetime.now()
show_date(date)
# This is the target date
date = date.replace(year=2020,month=3,day=6,hour=9,minute=0,second=0,microsecond=0)
show_date(date)
while True:
# This is now
now = datetime.datetime.now()
# Total number of seconds until target
delta = date-now
delta = int(delta.total_seconds())
total_seconds = delta
#print(total_seconds)
# Days, hours, minutes, seconds
delta_seconds = delta % 60
delta = int(delta/60)
delta_minutes = delta % 60
delta = int(delta/60)
delta_hours = delta % 24
delta = int(delta/24)
delta_days = delta
#print('days='+str(delta_days),'hours='+str(delta_hours),'mins='+str(delta_minutes),'secs='+str(delta_seconds))
# Update the display
#display = str(total_seconds)
display = int_to_string(delta_days,2,'0') + int_to_string(delta_hours,2,'0') + int_to_string(delta_minutes,2,'0') + int_to_string(delta_seconds,2,'0')
hardware.set_digits(display)
# Wait for changes
time.sleep(0.5) # Wait for changes (Nyquist rate)
|
adc3327fe24e67694446fd98f023306cafd012d2 | bang103/MY-PYTHON-PROGRAMS | /WWW.CSE.MSU.EDU/STRINGS/Cipher.py | 2,729 | 4.25 | 4 | #http://www.cse.msu.edu/~cse231/PracticeOfComputingUsingPython/
#implements encoding as well as decoding using a rotation cipher
#prompts user for e: encoding d: decoding or q: Qui
import sys
alphabet="abcdefghijklmnopqrstuvwxyz"
print "Encoding and Decoding strings using Rotation Cipher"
while True:
output=list()
inp=raw_input("Input E to encode, D to decode and Q to quit---> ")
if inp.lower()=="e": #encode
while True: #input rotation
inp2=raw_input("Input the rotation: an integer between 1 and 25 ---> ")
if inp2.isdigit()== False:
print " !!Error: Non digits!! The roatation is a whole number between 1 and 25"
elif int(inp2)>=1 and int(inp2)<=25:
rotation=int(inp2)
break
else:
print " Error! The roatation is a whole number between 1 and 25"
cipher = alphabet[rotation:]+ alphabet[:rotation]
instring=raw_input("Input string to be encoded---> ")
for char in instring:
if char in alphabet:
index=alphabet.find(char)
output.append(cipher[index])
else:
output.append(char)
outputstring = "".join(output)
print "The encoded string---> ",outputstring
elif inp.lower()=="d": #decode and find rotation
instring=raw_input( "Enter string to be decoded---> ")
word=raw_input( "Enter a word in the original(decoded) string ---> ")
rotation=0
found=False
for char in alphabet:
output=list()
rotation +=1
cipher=alphabet[rotation:]+alphabet[:rotation]
#decode encoded text with current rotation
for ch in instring:
if ch not in cipher:
output.append(ch)
elif ch in cipher:
index=cipher.find(ch)
output.append(alphabet[index])
outputstring="".join(output)
if word in outputstring: #IMPORTANT: This statement works only if we join the list into a string
found=True
break
else: continue
if found == True:
print "The rotation is %d"%(rotation)
print "The decoded string is ---> ", outputstring
else:
print "Cannot be decoded with rotation cipher: try another sentence"
elif inp.lower()=="q":
print "Bye! See you soon"
break
|
af43fea1a343914f64648e16b378f6ebccb38ad4 | poojan14/Python-Practice | /8.py | 626 | 3.671875 | 4 | def Average(StuDict,Student):
s=0
for i in StuDict:
if i==Student:
l=StuDict.get(i)
break
for ch in l:
num=eval(ch)
s+=num
avg=s/len(l)
avg="{:.2f}".format(avg) #to round off upto 2 decimal places
return avg
def main():
StuDict={}
N=int(input())
for i in range(N):
lst=[]
IString=input()
l=IString.split()
k=l[0]
lst.extend([l[1],l[2],l[3]])
StuDict.update({k:lst})
#print(StuDict)
stu=input()
avg=Average(StuDict,stu)
print(avg)
if __name__=='__main__':
main()
|
08a4a90a8b71a1ac791139f0752181f8fd74f8aa | mmrahman-utexas/pycharm_code_backup | /Test/test2.py | 212 | 4.03125 | 4 | x = [int(x) for x in input("Enter the coordinates here: ").split()]
if (x[3]-x[1])/(x[2]-x[0])==(x[7]-x[5])/(x[6]-x[4]):
print("The two lines are parallel")
else:
print("The two lines are intersecting")
|
3540c5d93e9534ee89849e621b2dead5e4cfb544 | ivenpoker/Python-Projects | /Projects/Online Workouts/w3resource/Basic - Part-I/program-20.py | 1,031 | 4.375 | 4 | #!/usr/bin/env python3
##############################################################################
# #
# Program purpose: Given a string, returns sames string with a defined #
# number of repetitions. #
# Program Author : Happi Yvan <ivensteinpoker@gmail.com> #
# Creation Date : July 14, 2019 #
# #
##############################################################################
# URL: https://www.w3resource.com/python-exercises/python-basic-exercises.php
def larger_string(_str, n):
result = ""
for i in range(n):
result = result + _str
return result
if __name__ == "__main__":
user_str = input("Enter a string: ")
str_rep = int(input("Enter number of repetitions: "))
print("New string is: {}".format(larger_string(user_str, str_rep))) |
8d0b5646430c634d06a518d55aedb3233a55f10f | shifalik/practice | /shifali/files_io.py | 6,448 | 4.09375 | 4 | '''
Created on Feb 22, 2018
@author: shifa
'''
#FILES I/O
#----------------------------------------------------------
#printing to screen
print("Python is a really great languge", "isn't it?")
print()
#----------------------------------------------------------
#Reading Keyboard Input
#input()
#reads data from keyboard as a string
print("Say something:")
a = input()
print(a)
print()
#----------------------------------------------------------
#the input function
#input([prompt]) function assumes that the input is a vaild
#python expression and returns the evaluated result to you
x = input("something:")
print(x)
x = input("something:")
print(x)
print()
#----------------------------------------------------------
#OPEN function
#open() is python's built-in function
#this function creates a file object
#SYNTAX
# file object = open(file_name [, access_mode][, buffering])
#file_name --> name of your file
#access_mode --> determines the mode the file has to be
#opened in(read/write/append/etc)
#it is a optional parameter and the default file access
#mode is read (r)
#buffering --> if value is 0 then no buffering
# if value is 1 then line buffering is performed
# while accessing a file
# if value is x>1 then buffering action is
# performed with the indicated buffer size
# if value is negative, the buffer size is the
# system default
#r (is default) opens a file to read only
#rb opens in binary format
#r+ opens files for reading and writing
#rb+ opens files read/write in binary
#w opens a file to write only/overwrites/creates new
#w+ opens file for writing and reading/overwrites/creates new
#wb+ does above in binary
#a opens file for appending/creates new file for writing
#ab opens file for appending in binary/creates for writing
#a+ opens a file for appending/reading or creates for read/write
#ab+ appending/reading in binary or creates for read/write
#----------------------------------------------------------
#file object attributes
#once a file is opened, you have on file object
#file.closed
#returns true if file is closed
#file.mode
#returns access mode with which file was opened
#file.name
#returns name of the file
fo = open("foo.txt", "wb")
print("name of file:", fo.name)
print("closed or not:", fo.closed)
print("opening mode:", fo.mode)
fo.close()
print()
#self
hi = open("test1.py", "r")
print("name of file:", hi.name)
hi.close()
print()
#--------------------------------------------------------
#the close() method
#flushes any unwritten info and closes the file object
#python automatically closes a file when the ref object
#of a file is reassigned to another file
#SYNTAX
#fileObject.close()
fo = open("foo.txt", "wb")
print("Name of file: ", fo.name)
fo.close()
print()
#--------------------------------------------------------
#Reading and Writing Files
#the write() method writes any string to an open file
#SYNTAX
#fileObject.write(string)
fo = open("foo.txt", "w")
fo.write("Python is a great language. \nYeah its great!!\n")
fo.close()
#if i open file foo.txt
#yes it says it there
#--------------------------------------------------------
#read() method
#reads a string from an open file
#SYNTAX
#fileObject.read([count])
#the passed parameter is the number of bytes to be read
#from the opened file
fo = open("foo.txt", "r+")
str1 = fo.read(10)
print("Read String is:", str1)
fo.close()
#if the count is missing, then it tries to read as much
#as possible, maybe until the end of the file
print()
#---------------------------------------------------------
#File Positions
#tell() method tells you the current position within the
#file or the next read/write position
#seek(offset[,from]) method changes the file position
#offset tells the number of bytes to be moved
#from tells the reference position from where the bytes
#are to be moved
#from = 0, start from beginning of file
fo = open("foo.txt", "rt")
str1 = fo.read(10)
print("Read string is:", str1)
position = fo.tell()
print("Current file position:", position)
position = fo.seek(0,0)
str1 = fo.read(10)
print("Again read string is:", str1)
fo.close()
print()
#---------------------------------------------------------
#Renaming and Deleting Files
#os is a built in module that provides methods to help
#to perform file-processing operations
#need to import os first
#rename() method
#takes two arguments
#current file name and new filename
#SYNTAX
#os.rename(current_file_name, new_file_name)
#import os
#os.rename("test1.txt", "test2.txt")
#---------------------
#below self
# test = open("test1.txt", "w")
# print("Name of file:", test.name)
# test.close()
#os.rename("test1.txt", "test2.txt")
#self no work
#test1 = open("test2.txt", "w")
#print("Name of file:", test1.name)
#test1.close()
print()
#--------------------------------------------------------
#remove() method
#to delete files by supplying the name of the file
#to be deleted as the argument
#SYNTAX
#os.remove(file_name)
#import os
#os.remove("text2.txt")
print()
#--------------------------------------------------------
#Directories
#uses the os module to CREATE/REMOVE/CHANGE DIRECTORIES
#-------------------------------------------
#mkdir() method
#creates directories in the current directory
#SYNTAX
#os.mkdir("newdir")
#import os
#os.mkdir("test")
#-------------------------------------------
#chdir() method
#change the current directory
#the argument is the name of the new
#current directory that you want
#SYNTAX
#os.chdir("newdir")
#import os
#os.chdir("/home/newdir")
#--------------------------------------------
#getcwd() method
#displays the current working directory
#SYNTAX
#os.getcwd()
import os
a = os.getcwd()
print("Location of current working directory:")
print(a)
#gives location of current directory
#---------------------------------------------
#rmdir() method
#deletes the directory
#before removing, all contents should be removed
#SYNTAX
#os.rmdir('dirname')
#import os
#os.rmdir("/temp/test")
#it is required to give fully qualified name
#of the directory
#otherwise it would search for that directory
#in the current directory
#----------------------------------------------
#FILE AND DIRECTORY RELATED METHODS
#there are other file object methods and
#OS object methods
#long list to manipulate/process files and directories
|
879ae3f64a092631a29a4de798618ea6042114bc | aparnamaleth/CodingPractice | /Geeks4Geeks/StackasQueue.py | 384 | 3.9375 | 4 | class Stack:
def __init__(self,n):
self.q1 = []
self.q2 = []
def push(self, data):
self.q1.append(data)
print("pushing",data)
def pop(self):
n = len(self.q1)
for i in range(n):
for i in range(n-1):
self.q1.append(self.q1.pop(0))
self.q2.append(self.q1.pop(0))
return self.q2
stack = Stack(3)
stack.push(10)
stack.push(20)
stack.push(30)
print stack.pop()
|
dacdad6563791818f23d1a9dd892c9be20522756 | Kimuksung/algorithm | /kakao/kakao_winter_01.py | 449 | 3.625 | 4 | def solution(board, moves):
answer = 0
arr = []
for move in moves:
for doll in board:
if doll[move-1] != 0:
arr.append(doll[move-1])
doll[move-1]=0
break
arr_len=len(arr)
if arr_len>=2:
if arr[arr_len-1] == arr[arr_len-2]:
arr.pop()
arr.pop()
answer = answer+2
return answer |
6be95036c0541b308fc9acccfb634d3fba14c29e | ALMTC/Logica-de-programacao | /TD4/05.py | 169 | 3.625 | 4 | def tempo(x):
return x/3600.0
k=0
for i in range(10):
print'Digite o tempo gasto(em segundos) na terefa',i
k=k+input()
print 'Tempo em horas:',tempo(k) |
66448a6e7731095859bff07c5c7b6e83d314f5ed | wojtez/ThePythonWorkbook | /025.UnitOfTime2.py | 1,325 | 4.375 | 4 | # In this exercise you will reverse the process described in the previous
# exercise. Develop a program that begins by reading a number of seconds
# from the user. Then your program should display the equivalent amount of
# time in the form D:HH:MM:SS, where D, HH, MM, and SS represent days,
# hours, minutes and seconds respectively. The hours, minutes and seconds
# should all be formatted so that they occupy exactly two digits, with a
# leading 0 displayed if necessary.
#add amout of seconds in days, hours, minutes
secondPerDays = 86400
secondPerHours = 3600
secondPerMinutes = 60
#input data r
seconds = int(input('Enter number of seconds: '))
#first receive days and rest of seconds asign to next line
days = seconds / secondPerDays
seconds = seconds % secondPerDays
#than receive hours and rest of the seconds asign to next line
hours = seconds / secondPerHours
seconds = seconds % secondPerHours
#than receive minutes and the rest of of the second asign to next line
minutes = seconds / secondPerMinutes
seconds = seconds % secondPerMinutes
# %02d - special format which tell Python to format the integer using 2
# digits adding the leading 0 if necessary
print(" %02d"%days,": %02d"%hours,": %02d"%minutes,": %02d"%seconds)
print('D %02d' % days,'h %02d' % hours,'m %02d' % minutes,'s %02d' % seconds)
|
bb204f79cb7e06f7c93d10d5562ac76b9da8f2dc | kakshat04/LearnGIT | /UnitTest_Learn.py | 1,047 | 3.59375 | 4 | import unittest
from Calculate_Test import *
from math import pi
class TestCal(unittest.TestCase):
def setUp(self):
self.x = TestCalculate(10, 5)
def tearDown(self):
pass
def test_add(self):
self.assertEqual(self.x.addition, 15)
def test_sub(self):
# x = TestCalculate(5,2)
self.assertEqual(self.x.subtract(), 5)
def test_mul(self):
# x = TestCalculate(5,2)
self.assertEqual(self.x.multiply(), 50)
def test_div(self):
# x = TestCalculate(6,2)
self.assertEqual(self.x.divide(2), 5)
self.assertRaises(ValueError, self.x.divide, 0)
def test_mod(self):
self.assertEqual(modulus(10,2), 0)
with self.assertRaises(ValueError):
modulus(10, 0)
def test_area(self):
area = TestArea(2)
self.assertAlmostEqual(area.circle(), pi * 2**2)
def test_valueError(self):
area = TestArea(0)
self.assertRaises(ValueError, area.circle)
if __name__ == '__main__':
unittest.main() |
d35760887808a715470c86b1ff65efa53235bde3 | lindaandiyani/Catatan-Modul-satu | /list,tuple dan set.py | 1,692 | 3.609375 | 4 | x =[(1,['a','b','c'],3),
(4,5,6)
]
x[0][1][2] ='andi' #semua yang ada di list bisa di ubah/diedit untuk tuple hanya bisa di count sama index
x[0][1].append('d')
print(x)
y=(1,2,3,)
# print(dir(y))
a= [1,2,3,1,2,3]
b= (1,2,3,1,2,3)
print(60*'=')
# SET/HIMPUNAN
# 1. no indexing
# 2. duplicate element not allowed
# 3. set mutable, tapi elemen2nya immutable
c = {1,2,3,1,2,3}
# c['2'] = 'budi' #ini tidak bisa
c.add('a') #menambahkan satu elemen saja. coba lihat beda outputnya
c.add(('c','d','e')) #ketika diprint set c urutannya akan acak karena indexing tidak berpeagruh
c.update('andi')
c.update([6,7,8])
c.update({'z','budi'})
print('budi' in c) #cek apakah ada didalama element
c.remove('budi') #menghilangkan budi
c.discard('linda') #jika men-discard sesuatu yang tidak ada diset tidak akan eror, berbeda dgn remove
print(c)
c.pop() #sepertinya menghilangkan elemen paling depan
# c.clear() #set masih ada tapi elemennya ksong
# del.c #menghilangan set
print(c)
# print(list(set(a))) #untuk mengubah list/tuple kedalam set bisa begtupun sebaliknya
print (60*'-')
a= list('abcdef')
b= list('bcdfgh')
a=set(a)
b=set(b)
print(a.intersection(b)) #irisan
print(b.intersection(a))
print(a & b) #irisan juga
print(b & a)
print(a.union(b)) #gabungan
print(b.union(a))
print(a | b) #gabungan
print(b|a)
print(a.difference(b)) #selisih anggota set A yang tidak ada di B
print(b.difference(a))
print(a - b )
print(b - a)
print(a.symmetric_difference(b)) #kebalikan dari irisan. anggotanya semua anggota a dan b kecuali irisan
print(b.symmetric_difference(a))
print(a^b)
print(b^a)
# FROZEN SET
x = set([1,2,3])
y = frozenset([1,2,3])
x.remove(2)
# y.add(2)
print(x)
print(y)
|
a0af2f8bec31ad46d3369233995455827cdce043 | kqg13/LeetCode | /Heaps/topKFrequent.py | 750 | 3.78125 | 4 | # Medium heap problem 347: Top K Frequent Elements
# Given a non-empty array of integers, return the k most frequent elements.
# Example:
# Input: nums = [1, 1, 1, 2, 2, 3], k = 2 Output: [1,2]
from collections import Counter
from heapq import nlargest
class Solution:
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
# O(NlogK)
count = Counter(nums) # Creates dictionary in O(N)
print(count)
return nlargest(k, count.keys(), key=lambda x: count[x]) # O(NlogK), note: key=get also works
nums1 = [1, 1, 1, 2, 2, 3]
k1 = 2
print(Solution().topKFrequent(nums1, k1))
# closed mouths don't get fed
# compromising safety
|
c3d5b6c73574c902b58aac1157926956acb36ed5 | ixkungfu/lotm | /python/scripts/re.py | 544 | 4.5625 | 5 | import re
re_string = '{{(.*?)}}'
some_string = 'this is a string with {{words}} embedded in {{curly brackets}} \
to show an {{example}} of {{regular expressions}}'
# uncompile
for match in re.findall(re_string, some_string):
print 'MATCH->', match
# compile
re_obj = re.compile('{{(.*?)}}')
for match in re_obj.findall(some_string):
print 'MATCH->', match
re_obj = re.compile(r'\bt.*?e\b')
print re_obj.findall('time tame tune tint tire')
re_obj = re.compile('\bt.*?e\b')
print re_obj.findall('time tame tune tint tire')
|
a7a77c1a7d241a12adef5ee7d852ad671e37a577 | shellytang/intro-cs-python | /01_week2_simple_programs/char-search-recursive.py | 731 | 4.21875 | 4 | # check if a letter is in an alpha sorted string using bisection search
def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
# base case: if string is empty, we did not find match
if aStr == '':
return False
middleIndex = len(aStr)//2
middleChar = aStr[middleIndex]
# base case: if middle character is the match
if char == middleChar:
return True
elif char > middleChar:
aStr = aStr[(middleIndex+1):]
return isIn(char, aStr)
else:
aStr = aStr[:middleIndex]
return isIn(char, aStr)
return isIn(char, aStr)
print(isIn('b', 'aabdejlmruuvv')) |
644635e8421be4ab3e101ab892e69af1425a3f5b | MateuszMazurkiewicz/CodeTrain | /InterviewPro/2020.01.17/task.py | 1,007 | 3.90625 | 4 | '''
Given a non-empty array where each element represents a digit of a non-negative integer, add one to the integer. The most significant digit is at the front of the array and each element in the array contains only one digit. Furthermore, the integer does not have leading zeros, except in the case of the number '0'.
Example:
Input: [2,3,4]
Output: [2,3,5]
'''
class Solution():
def plusOne(self, digits):
current_index = -1
to_add = 1
while to_add:
if current_index == -1 * len(digits) - 1:
digits.insert(0, 0)
current_index = -1 * len(digits)
digits[current_index] = (digits[current_index] + 1) % 10
if digits[current_index] == 0:
to_add = 1
current_index -= 1
else:
to_add = 0
return digits
num = [2, 9, 9]
print(Solution().plusOne(num))
# [3, 0, 0]
num = [9, 9, 9]
print(Solution().plusOne(num)) |
9b3d18f82cf990077a6a56e8bcf3bf804a45a739 | shadykhatab/python-tutorilas- | /170_code_challenges/40_code_challenge_solution.py | 668 | 4.3125 | 4 | """
write a function that capitalizes the first and fourth letters of a name
ex:
capitalize("macdonald") --> MacDonald
"""
# solution 1
def capitalize(name):
first_letter = name[0]
in_between = name[1:3]
fourth_letter = name[3]
rest = name[4:]
return first_letter + in_between + fourth_letter + rest
result = capitalize("macdonald")
print(result)
result = capitalize("macarthur")
print(result)
# solution 2
def capitalize(name):
first_half = name[:3]
second_half = name[3:]
return first_half.capitalize() + second_half.capitalize()
result = capitalize("macdonald")
print(result)
result = capitalize("macarthur")
print(result)
|
1b6a5bef4975a0b86a5ae01263b0387202102940 | RaphaelCoelhof3/Python-.coursera. | /Semana2/Opcional/Exerc3_sem2_opc.py | 398 | 4.125 | 4 | numero = int(input("Digite um número inteiro: "))
unidade = numero % 10
print("O dígito da unidade é:",unidade)
numero_sem_unid = numero // 10
decimal_do_numero = numero_sem_unid % 10
print("O dígito das dezenas é:",decimal_do_numero)
numero_sem_decimal = numero // 100
centezimal_do_numero = numero_sem_decimal % 10
print("O dígito da centena é:",centezimal_do_numero)
|
8bc68401433360091e67c4514ef6d3b746072161 | Sahithipalla/pythonscripts | /for.py | 662 | 3.90625 | 4 | my_list=[1,2,3,4,5,6,7,8,9,10]
for asdf in my_list:
print(asdf)
my_list=[1,2,3,4,5,6]
list_sum=0
for num in my_list:
list_sum=list_sum+num
print(list_sum)
my_list=[1,2,3,4,5]
for num in my_list:
if num%2!=0:
print(num)
my_list=[1,2,3,4,5,6,7,8,9]
for num in my_list:
if num%2!=0:
print("even numbers{}".format(num))
else:
print("odd numbers{}".format(num))
my_list="Hello world"
for letters in my_list:
print("python")
t=(1,2,3,4,5)
for num in t:
print(num)
list=[(1,2),(4,5),(2,6)]
for items in list:
print(items)
d={'a':2,'b':4,'c':6}
for items in d.items():
print(items)
|
9e6c0ab429e9dc9fdb63a683b079707f91c57c58 | rafaelperazzo/programacao-web | /moodledata/vpl_data/126/usersdata/159/29447/submittedfiles/ap2.py | 785 | 4.125 | 4 | # -*- coding: utf-8 -*-
a=int(input('Digite a:'))
b=int(input('Digite b:'))
c=int(input('Digite c:'))
d=int(input('Digite d:'))
if a>=b and a>=c and a>=d:
print(a)
if b<=c and b<=d:
print(b)
elif c<=b and c<=d:
print(c)
elif d<=b and d<=c:
print(d)
if b>=a and b>=c and b>=d:
print(b)
if a<=c and a<=d:
print(a)
elif c<=a and c<=d:
print(c)
elif d<=a and d<=c:
print(d)
if c>=b and c>=a and c>=d:
print(c)
if b<=a and b<=d:
print(b)
elif a<=b and a<=d:
print(a)
elif d<=b and d<=a:
print(d)
if d>=b and d>=c and d>=a:
print(d)
if b<=c and b<=a:
print(b)
elif c<=b and c<=a:
print(c)
elif a<=b and a<=c:
print(a) |
b2fe83532d6d928b2f217ee82a64c430c4111b56 | BakJungHwan/Exer_algorithm | /Programmers/Level2/digit_reverse(jpt)/digit_reverse.py | 208 | 3.6875 | 4 | # _*_ coding: Latin-1 _*_
def digit_reverse(n):
return [int(c) for c in str(n)[::-1]]
# Ʒ Ʈ ڵԴϴ.
print(" : {}".format(digit_reverse(12345))); |
4f00bb86f4ae37c85175e813e0728f7556bf7b2f | lovishagumber/assignment | /assingment2.py | 375 | 3.828125 | 4 | #Q1 print anything
print("i am lovisha")
#Q2 join two string
print("acad"+"view")
#Q3 print values of x,y,z
x=2
y=3
z=4
print(x,y,z)
#Q4 print let's get started
print("let\'s get started")
#Q5
s="acadview"
course="python"
fee=5000
print("hi you are in %s, your course is %s and fee is %d" %(s,course,fee))
#Q6
name="tony stark"
salary=1000000
print("%s %d" %(name,salary))
|
44916092a8dc31400d478184814be464a6aab48c | JamesMedeiros/Python | /media_de _10.py | 134 | 3.625 | 4 | n = 1
soma =0
while n <= 10:
x = int(input("digite %dº numero: "%n))
soma = soma + x
n = n + 1
print ("media : %4.2f" %(soma/10))
|
1bc68ebf2cb554269219028e7a4d761e2995f5a3 | tom-010/brutal_coding | /coverage_delete/pet-project copy/fib.py | 257 | 3.5625 | 4 |
def fib(n):
if n < 0:
print("error")
if n <= 2:
return 1
counter = 0
for i in range(1, 20):
counter += i
return counter
def sum(a, b):
print(a)
print(b)
return a + b
def sub(a, b):
return a - b |
164a4aff3b53ff8448d30d73626b920b27961f03 | Marino4ka/Exchange | /abacus.py | 535 | 3.5 | 4 | def print_abacus(value):
answer = ''
string = '|00000*****|'
len_number = len(str(value))
while len_number != 10:
len_number = len_number + 1
answer += (string[0:-1] + ' ' + string[-1] + '\n')
len_number = len(str(value))
new_value = str(value)[::-1]
while len_number != 0:
len_number = len_number - 1
number_value = int(str(new_value)[len_number]) + 1
answer += (string[0:-number_value] + ' ' + string[-number_value:]+ '\n')
print (answer)
print_abacus(123) |
334ae4cf87ac15eead0e9c3c1be9ca2ec86b80ff | ww35133634/chenxusheng | /ITcoach/sixstar/基础班代码/15_面向对象/lx_08_创建对象传参.py | 3,182 | 4.125 | 4 | """
演示创建对象传参
"""
# class Man:
# # 成员变量的定义
# def __init__(self): # 对象本身
# self.gender = None
# self.name = None
# self.place = None
# # 成员方法
# def myself(self): # 成员方法去调用成员变量(公有变量)
# print('我是:%s,性别是:%s,我来自:%s,我为中国加油!' %(self.name,self.gender,self.place))
#
# man1 = Man()
# man1.name = '简自豪'
# man1.gender = '男性'
# man1.place = '湖北'
# man1.myself()
#
# man2 = Man()
# man2.name = '史森明'
# man2.gender = '男性'
# man2.place = '湖南'
# man2.myself()
# 类变量 类方法
# class Man:
# # 成员(实例)变量的定义 self代表的是对象本身 创建对象之后去执行
# def __init__(self,name,gender,place): # 对象本身
# self.gender = gender
# self.name = name
# self.place = place
# # 成员(实例)方法
# def myself(self): # 成员方法去调用成员变量(公有变量)
# print('我是:%s,性别是:%s,我来自:%s,我为中国加油!' %(self.name,self.gender,self.place))
#
# man1 = Man('简自豪','男性','湖北') # 传参 init方法的调用
# man1.myself()
#
# man2 = Man('史森明','男性','湖南')
# man2.myself()
"""
我是:简自豪,性别是:男性,我来自:湖北,我为中国加油!
我是:史森明,性别是:男性,我来自:湖南,我为中国加油!
"""
# 类变量 类方法 成员变量:1.类变量(类),2.实例对象(对象)
# class Man: # 男人的类模板 跟类直接相关,不随着对象的改变而发生的变量
# # 类变量
# gender = '男性'
# # 成员(实例)变量的定义 self代表的是对象本身 创建对象之后去执行
# def __init__(self,name,gender,place): # 对象本身
# self.gender = gender
# self.name = name
# self.place = place
# # 成员(实例)方法
# def myself(self): # 成员方法去调用成员变量(公有变量)
# print('我是:%s,性别是:%s,我来自:%s,我为中国加油!' %(self.name,self.gender,self.place))
#
# man1 = Man('简自豪','男性','湖北') # 传参 init方法的调用
# man1.myself()
#
# man2 = Man('史森明','男性','湖南')
# man2.myself()
class Man: # 中国人的模板
# 类变量 > 不会随着对象的改变而发生改变
country = '中华人民共和国'
# 实例变量 > 会随着对象的改变而发生改成
def __init__(self,name,gender):
self.name = name
self.gender = gender
# 实例方法 > 随着对象的改变而发生改变的发生
def myself(self):
print('我是:%s,我是一个:%s,我为中国加油' %(self.name,self.gender))
man1 = Man('简自豪','男性') # init方法被自动调用
# 调用类变量 1.类名.变量名 2.对象名.变量名(不推荐)
# print(Man.country)
# 修改类变量 1.类名.变量名 = 值 成功的进行的修改
Man.country = '中国'
# 对象名.变量名 = 值
man1.country = '中华人民共和国家' # >>> 添加该对象私有变量,,,
man2 = Man('史森明','男性')
print(Man.country)
|
ad382322807bae8292d2fde33f5f9872cad026e4 | firerycon/2016_Python_Test | /module2_more_python/sphinx_example/src/m2_args.py | 1,095 | 4.0625 | 4 | import sys
import argparse
# 取得參數最原始的方法 list
print('raw arguments = ' + str(sys.argv), end='\n\n')
# 使用 Python 內建的參數解析
parser = argparse.ArgumentParser()
# Positional argument(給參數時會依照順序填入,如果沒有提供會報錯)
# 使用 type = 可以指定要轉換成什麼樣的型態(預設是字串)
# help = 可以指定使用 -h 印出幫助訊息時,針對該參數顯示的說明
parser.add_argument('square', help="display a square of a give number", type=int)
# Opetional arguments(可以提供可以不提供的參數,也可以接收值)
# action='store_true' 自動存為 True or False
parser.add_argument('-v', '--verbose', help='increase output verbosity', action='store_true')
parser.add_argument('-c', '--cube', help='display a cube of a give number', type=int)
# 解析參數並取得結果
args = parser.parse_args()
# 使用參數結果物件
print('square result = ' + str(args.square**2))
if args.verbose:
print("verbosity turned on")
if args.cube:
print('cube result = ' + str(args.cube**3)) |
1952e98e9266d3e84eba2c0f8b93a3367817403a | khush-01/Python-codes | /HackerRank/Mathematics/Fundamentals/Medium/Summing the N series.py | 108 | 3.546875 | 4 | mod = 10 ** 9 + 7
for _ in range(int(input())):
n = int(input())
print((n % mod) * (n % mod) % mod)
|
03852842cb4ab3d970d5dc4266db3ec415ad31c8 | yeos60490/algorithm | /leetcode/medium/add_two_numbers.py | 841 | 3.78125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
#print(l1)
sum_value = l1.val + l2.val
carry = int(sum_value/10)
current = int(sum_value%10)
result = ListNode(current)
l3 = result
while l1.next or l2.next or carry:
l1 = l1.next if l1.next != None else ListNode(0)
l2 = l2.next if l2.next != None else ListNode(0)
sum_value = l1.val + l2.val + carry
carry = int(sum_value/10)
current = int(sum_value%10)
l3.next = ListNode(current)
l3 = l3.next
return result
|
4aca83bdf3f3cf232cff6326ce0448a6dfde494a | iam-amitkumar/BridgeLabz | /DataStructureProgram/Problem13_PrimeAnagramStack.py | 1,452 | 4.03125 | 4 | """Adding the Prime Numbers that are Anagram in the Range of
0 1000 in a Stack using the LinkedList and Print the Anagrams
in the Reverse Order.
@author Amit Kumar
@version 1.0
@since 09/01/2019
"""
# importing important modules
from DataStructureProgram.Stack import *
# this function checks whether the given two parameters are anagram or not
def is_anagram(str1, str2):
if sorted(str1) == sorted(str2): # comparing both the strings after sorting
return True # return True if both the strings are anagram
else:
return False # return False if the strings are not anagram
s1 = Stack() # creating the object of the class Stack to use all the methods of that class
arr = [] # initializing empty list
i = 2
# adding all the prime numbers to the list
while i < 1000:
j = 2
flag = 0
while j < i:
if i % j == 0:
flag = 1
j += 1
if flag == 0:
arr.append(str(i)) # appending value in the list
i += 1
# pushing all the anagram pair of the list in the stack
i = 0
while i < len(arr):
j = i + 1
while j < len(arr):
if is_anagram(arr[i], arr[j]): # checking whether the numbers passed to the function is anagram or not
s1.push(arr[i]) # if both numbers are anagram then pushing both the numbers in the stack
s1.push(arr[j])
j += 1
i += 1
s1.display() # printing the stack after pushing all the anagrams in the stack
|
2fee99cb34d796e297aac3f2eecd1af8a15482ed | tutejadhruv/Datascience | /Next.tech/Analyzing-Text-Data/solution/tokenizer.py | 1,373 | 4.25 | 4 | '''
Tokenization is the process of dividing text into a set of meaningful pieces. These pieces are called tokens. For example, we can divide a chunk of text into words, or we can divide it into sentences. Depending on the task at hand, we can define our own conditions to divide the input text into meaningful tokens. Let's take a look at how to do this.
'''
import nltk
nltk.download('punkt')
text = "Are you curious about tokenization? Let's see how it works! We need to analyze a couple of sentences with punctuations to see it in action."
# Sentence tokenization
from nltk.tokenize import sent_tokenize
sent_tokenize_list = sent_tokenize(text)
print("\nSentence tokenizer:")
print(sent_tokenize_list)
# Create a new word tokenizer
from nltk.tokenize import word_tokenize
print("\nWord tokenizer:")
print(word_tokenize(text))
# # Create a new punkt word tokenizer Error importing
# from nltk.tokenize import WordPunctTokenizer
# word_punct_tokenizer = WordPunctTokenizer()
# print("\nPunkt word tokenizer:")
# print(word_punct_tokenizer.tokenize(text))
# If you want to split these punctuations into separate tokens, then we need to use WordPunct Tokenizer:
# Create a new WordPunct tokenizer
from nltk.tokenize import WordPunctTokenizer
word_punct_tokenizer = WordPunctTokenizer()
print("\nWord punct tokenizer:")
print(word_punct_tokenizer.tokenize(text))
|
76779e3a91d5c7d4ccf9b7125027b4e51dd9b962 | FR0GM4N/Algorithm | /_basic/2차원 배열 연습.py | 497 | 3.96875 | 4 | a = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
]
# 2차원 리스트 출력 1
for i in range(len(a)): # 가로행 길이 (3)
for j in range(len(a[0])): # 세로열 길이 (4)
print(a[i][j], end=' ')
print()
# 1 2 3 4
# 5 6 7 8
# 9 10 11 12
# 2차원 리스트 출력 2
for i in range(len(a)):
for j in range(len(a[0])):
print('%3d ' % a[i][j], end='') # 3칸 떨어져서 출력됨
print()
# 1 2 3 4
# 5 6 7 8
# 9 10 11 12 |
07c121ef770d37bc413bd19734ba7c1bb96a8a51 | Kevinxu99/NYU-Coursework | /CS-UY 1134/HW/HW2/lab3q3b.py | 331 | 3.875 | 4 | def square_root(num):
n=num*10000
left=100
right=n
while(right-left>1):
mid=(left+right)//2
print(left," ",right)
if(mid**2>n):
right=mid
elif(mid**2<n):
left=mid
elif(mid**2==n):
return mid
return (left/100)
print(square_root(1000))
|
25c5340e9c7521e850fbc2e696d196f116b360d1 | Lekhaa13297/Codekata | /character.py | 234 | 4.03125 | 4 | r=input("enter the string")
le=len(r)
c=0
for i in r:
if i.isalpha():
print("%s is a character"%(i))
c=c+1
else:
print("%s is not a character"%(i))
if c==le:
print("all are characters")
else:
print("all are not characters")
|
3190d35822f19d8c0d24c7a323262e6a059d1c78 | sneharnair/Trees-3 | /Problem-2_Symmetric_tree.py | 1,333 | 4.125 | 4 | # APPROACH 1: RECURSION (WITH NO INORDER)
# Time Complexity : O(n), n: number of nodes of the tree
# Space Complexity : O(lg n) or O(h) - h: height of the tree, space taken up by the recursive stack
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : None
#
#
# Your code here along with comments explaining your approach
# 1. Initially, I pass root's hildren to the recursive way
# 2. Each time, I compare both the roots. If not equal or any of them is empty -> False
# 3. Else, I go left on one side and right on the other side AND right on one side and left on the other side.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if root is None:
return True
return self.helper(root.left, root.right)
def helper(self, root1, root2):
if root1 is None and root2 is None:
return True
if (root1 is None or root2 is None) or (root1.val != root2.val):
return False
return self.helper(root1.left, root2.right) and self.helper(root1.right, root2.left)
|
0751c9354d55301ddf84967f5e7874e2540a41a4 | Khushbulohiya/DataStructures | /Strings_Array/mergesort.py | 691 | 3.859375 | 4 | #!usr/bin/python
def mergesort(alist):
print ("Splitting", alist)
if len(alist) > 1:
middle = len(alist)/2
left = alist[:middle]
right = alist[middle:]
mergesort(left)
mergesort(right)
i = 0
j = 0
k = 0
while i < len(left) and j < len(right):
if left[i] > right[j]:
alist[k] = right[j]
k = k + 1
j = j + 1
else:
alist[k] = left[i]
k = k + 1
i = i + 1
while i < len(left):
alist[k] = left[i]
k = k + 1
i = i + 1
while j < len(right):
alist[k] = right[j]
k = k + 1
j = j + 1
print ("Merging " , alist)
alist = [1, 9, 4, 2, 0, 6, 7, 18, 16, 10, 3, 20, 11, 12, 15, 5, 19, 8, 17, 14, 13]
mergesort(alist)
print (alist) |
5f796f9e72d54055b168882fdebbda33802926b7 | chenpengcode/Leetcode | /search/540_singleNonDuplicate.py | 1,172 | 3.765625 | 4 | from typing import List
class Solution:
def singleNonDuplicate(self, nums: List[int]) -> int:
lo = 0
hi = len(nums) - 1
while lo < hi:
mid = lo + (hi - lo) // 2
halves_are_even = (hi - mid) % 2 == 0
if nums[mid + 1] == nums[mid]:
if halves_are_even:
lo = mid + 2
else:
hi = mid - 1
elif nums[mid - 1] == nums[mid]:
if halves_are_even:
hi = mid - 2
else:
lo = mid + 1
else:
return nums[mid]
return nums[lo]
def singleNonDuplicate_2(self, nums: List[int]) -> int:
n = len(nums)
left, right = 0, n - 1
while left < right:
mid = (left + right) // 2
if mid % 2 == 1:
mid -= 1
if nums[mid] == nums[mid + 1]:
left = mid + 2
else:
right = mid
return nums[left]
if __name__ == '__main__':
nums = [1, 1, 2, 3, 3]
solution = Solution()
print(solution.singleNonDuplicate(nums))
|
18657ce5d1a0e0d19caf231a87ce86fe58536f93 | yanghaotai/leecode | /leetcode/704.二分查找.py | 722 | 3.984375 | 4 | '''
704. 二分查找
难度 简单
给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。
示例 1:
输入: nums = [-1,0,3,5,9,12], target = 9
输出: 4
解释: 9 出现在 nums 中并且下标为 4
示例2:
输入: nums = [-1,0,3,5,9,12], target = 2
输出: -1
解释: 2 不存在 nums 中因此返回 -1
'''
def search(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
for i in nums:
if target == i:
return nums.index(i)
else:
return -1
nums = [-1,0,3,5,9,12]
target = 9
print(search(nums, target)) |
44f635907f80799f8d4e6908d261ebc92156e4da | jspruyt/spark_devnet_code | /tropo_mission_test.py | 528 | 3.671875 | 4 |
say("Hello, welcome to the language selector version 7")
result = ask("please press 1 for French, 2 for Italian, 0 for english", {
"choices": "[1 DIGITS]",
"terminator": "#",
"mode": "dtmf"})
log("the language of your choice:" + result.value)
say("you chose " + result.value)
if int(result.value) == 0:
say("Hello my friend", {voice: "Karen"})
elif int(result.value) == 1:
say("Bonjour mon ami", {voice: "Aurelie"})
elif int(result.value) == 2:
say("Bongiorno Principe", {voice: "Federica"})
else:
hangup()
hangup() |
894fe78edc4fb9cd49af0cc131f9995724724c30 | acneuromancer/problem_solving_python | /basic_data_structures/stacks/stack_example.py | 391 | 3.78125 | 4 | from Stack import Stack
s = Stack()
print('\nInitial size of the stack: ', s.size())
print('\nTest whether the stack is empty: ', s.is_empty())
s.push("Apple")
s.push(True)
s.push(6.31448)
s.push(10)
print('\nPeek into the stack: ', s.peek())
print('\nSize of the stack: ', s.size())
print('\nPop all items from the stack:')
while not s.is_empty():
print(s.pop(), end=" ")
print()
|
ad31705235f979e8f216bfcb0eabc9e8552157b9 | cristiano250/pp1 | /02-ControlStructures/#02-ControlStructures - zad. 44.py | 245 | 3.53125 | 4 | #02-ControlStructures - zad. 44
a=int(input("Podaj limit prędkości (km/h): "))
b=int(input("Podaj prędkość samochodu (km/h): "))
if b-a<=10:
print("Mandat wynosi:",(b-a)*5,"zł")
else:
print("Mandat wynosi:",50+((b-a)-10)*15,"zł") |
676c13054ebe36f2ac9c95bab6f28a8764cf1f11 | beerfleet/udemy_tutorial | /Oefeningen/uDemy/bootcamp/lots_of_exercises/range_in_list.py | 824 | 3.671875 | 4 | """
Write a function called range_in_list which accepts a list and
start and end indices, and returns the sum of the values between
(and including) the start and end index.
If a start parameter is not passed in, it should default to zero.
If an end parameter is not passed in, it should default to the last
value in the list. Also, if the end argument is too large, the sum
should still go through the end of the list.
"""
def range_in_list(lijst, start_index = 0, stop_index = 0):
if not stop_index:
stop_index = len(lijst)
return sum(lijst[start_index:stop_index + 1])
print(range_in_list([1,2,3,4],0,100))
'''
range_in_list([1,2,3,4],0,2) # 6
range_in_list([1,2,3,4],0,3) # 10
range_in_list([1,2,3,4],1) # 9
range_in_list([1,2,3,4]) # 10
range_in_list([1,2,3,4],0,100) # 10
range_in_list([],0,1) # 0
''' |
159643866d779d6566aed82ed51993c26f51ac78 | kkyaruek/project-euler | /python3/test_prime.py | 943 | 3.96875 | 4 | from math import sqrt
from time import time
def is_prime(n):
if n <= 1:
return False
if n != 2 and n % 2 == 0:
return False
for i in range(3, int(sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
# sieve of eratosthenes
def find_primes(start, end):
sieve = [True] * (end + 1)
for i in range(3, int(sqrt(end)) + 1, 2):
if not sieve[i]:
continue
for j in range(i * 2, end + 1, i):
sieve[j] = False
prime = []
if start <= 2 and end >= 2:
prime.append(2)
for i in range(3, len(sieve), 2):
if sieve[i] == True and i >= start:
prime.append(i)
return prime
def test():
assert is_prime(32416190071) == True
assert is_prime(4) == False
assert find_primes(1, 10) == [2, 3, 5, 7]
if __name__ == '__main__':
start = time()
test()
print("Execution time:", time() - start)
|
c028225024835858e7a0a6a6b0dd922e1bee9b0c | Emma-2016/introduction-to-computer-science-and-programming | /lecture08.py | 4,432 | 3.84375 | 4 | #Iterative exponent
def exp1(a, b):
ans = 1
while (b > 0):
ans *= a
b -= 1
return ans
#2 + 3b; when b =10, it is 32;when b=100, it is 302;when b=1000, it is 3002
#care about the rate of growth as size of problem grows, that is how much bigger does this get as I make the problem bigger
#Asymptotic notation - the limit as the size of the problem gets bigger
#big O is an upper limit to the growth of a function as the input get bigger
#f(x)∈O(n^2) - the f(x) is bounded above, there is upper limit on it, that this grows no faster than quadratic in n, n squared.
#x is input; n measure the size of x
#recursive exponent
def exp2(a, b):
if b == 1:
return a
else:
return a * exp2(a, b-1)
#one test, one substract, one multiplication, that is 3 steps and plus t(b-1)
#t(b) = 3 + t(b-1)
# = 3 + 3 + t(b-2)
# = 3k + t(b-k)
#b-k == 1; 3(b-1) + t(1) = 3b - 1 ∈O(b) linear;
#a ** b = (a * a) ** (b/2) #b is even
#a ** b = a * (a ** (b-1)) #b is odd
# =a * ((a * a) ** ((b-1)/2)) #then b is even again
def exp3(a, b):
if b == 1:
return a
if (b / 2) * 2 == b:
return exp3(a * a, b/2)
else:
return a * exp3(a, b-1)
#b is even, a test(b == 1), a division, a multiplication, a test(==), and then a divide(b/2) and a square.
#6 steps; then when b is even, t(b) = 6 + t(b/2)
#b is odd, a test(b == 1), a division, a multiplication, a test(==), and a subtract, and a multiplication;
#so that is 6+t(b-1), and then b is even, so the total is 12 + t((b-1)/2)
#no matter b is even or odd, it can represent in this way: t(b) = 12 + t(b/2)
#t(b) = 12 + t(b/2) = 12 + 12 + t(b/4) = 12k + t(b/2^k) #这时b不是减1,而是一半一半地减去的;
#b/2^k #k = logb
#O(logb) #b is the changing input, not k
#reduce the complex in half
def g(n, m):
for i in n:
for j in m:
x += 1
return x
#O(m * n)
def Towers(size, fromStack, toStack, spareStack):
if size == 1:
print 'Move disk from ', fromStack, 'to', toStack
else:
Towers(size-1, fromStack, spareStack, toStack)
Towers(1, fromStack, toStack, spareStack)
Towers(size-1, spareStack, toStack, spareStack)
# T(n) = 1 + T(1) + 2T(n-1) = 3 + 2T(n-1) = 3 + 2 * 3 +4T(n-2) = 3 + 2 * 3 + 4 * 3 + 8T(n-3)
# = 3*(1+2+4+ ... +2^(k-1)) + 2^n *(n-1)
#O(2^n) exponential
#this recursive call had two sub-problems
#linear algorithms tend to be things where at one pass-through, you reduce the problem by a constant amount, by 1;
#log algorithms where you cut the size of the problem down by some multiplicative factor.
#Quadratic algorithm tend to have this doubly-nested, triply-nested things are likely to be quadratic or cubic algorithms.
#exponent algorithm when reduce the problem of one size into two or more sub-problem of a smaller size.
def search(s, e):
answer = None
i = 0
numCompute = 0
while i < len(s) and answer == None:
numCompute += 1
if e == s[i]:
answer = True
elif e < s[i]:
answer = False
i += 1
print answer, numCompute
#In the worest case, O(len(s)), even though e in the first half of the list
def biSearch(s, e, first, last):
print first, last
if (last - first) < 2: return s[first] == e or s[last] == e
mid = fisrt + (last - first)/2
if s[mid] == e: return True
if s[mid] > e: return biSearch(s, e, first, mid - 1)
return biSearch(s, e, mid + 1, last)
def search1(s, e)
print (s, e, 0, len(s)-1)
print 'Search complete'
#how long it take to access the n-th element?
#random access, as long as knowing the location, it takes a constant amout of time to get to that point.
#if I knew the lists were made of just integers, it's be reaaly easy to figure it out(the beginning + 4i unit). Another way of saying it is, this takes constant amount of time to figure out where to look
#it takes constant amount of time to get there.
#so in fact I could treat indexing into a list being a basic operation.
#however in general list?
#linked-list, the time it takes will be linear in the length of the list
#an alternative is to have each one of the successive cells in memory point off to the actual value, which will take up some arbitrary amout of memory.
#this is constant access;
#in python, most implementation in python use this way of storing list;
#we have to be careful what is a primitive step
|
5805f3aba5e449d97af68ecd615191a1834d3466 | 0xb00d1e/AoC-2020 | /9/solution.py | 1,257 | 3.515625 | 4 | def part1():
input_data = load_data()
invalid_number = find_invalid_number(input_data)
print(f'Answer - Part1: {invalid_number}')
def part2():
input_data = load_data()
invalid_number = find_invalid_number(input_data)
numbers = find_numbers_in_sum(input_data, invalid_number)
numbers.sort()
print(f'Answer - Part2: {numbers[0] + numbers[-1]}')
def find_numbers_in_sum(input_data, invalid_number):
for i, outer_value in enumerate(input_data):
for j, inner_value in enumerate(input_data, start=1):
window = input_data[i:j]
if sum(window) == invalid_number:
return window
def find_invalid_number(input_data):
for i, value in enumerate(input_data):
if i < 25:
continue
previous_slice = input_data[i-25:i]
if not any_two_sum_to(previous_slice, value):
return value
def any_two_sum_to(numbers, value):
for number in numbers:
compliment = value - number
if compliment in numbers:
return True
return False
def load_data():
with open('input') as f:
data = f.read()
return [int(l.strip()) for l in data.splitlines()]
if __name__ == '__main__':
part1()
part2()
|
10346e9e8a68b82fd8da4230c6f53cf4cae93cd3 | solankidhairya77/dhairya | /d2.py | 254 | 3.640625 | 4 | aa = "Hello Eric would you like to learn some Python today?"
print(aa)
bb = "dhairya solanki"
print(bb.upper())
print(bb.title())
print(bb.lower())
cc= " \t Albert Einstein once said, \n “A person who never made a mistake never tried anything new."
print(cc)
|
bfe9ca0f4372fc7c05cbbb0a4ca1880e6be32fc7 | AasthaGoyal/Rock-Paper-Scissor-Game- | /(c).py | 248 | 3.6875 | 4 | import os
import sys
string = input("Enter a string:")
string.strip(" ")
i=0
while(string):
while(string[i]==" "):
#if(string[i]==" "):
j =i
break
for k in range(0,j):
print(string[k])
|
bd89b8b9e1582fcbe70fdbe239fbf411cb188fbe | bulutharunmurat/hackerrank | /Dictionaries&Hashmaps/countTriplets.py | 454 | 3.609375 | 4 | arr = [1, 2, 2, 4]
r = 2
arr2 = [1, 3, 9, 9, 27, 81]
r2 = 3
arr3 = [1, 5, 5, 25, 125]
r3 = 5
from collections import defaultdict
def countTriplets(lst, ratio):
v2 = defaultdict(int)
v3 = defaultdict(int)
count = 0
for k in lst:
count += v3[k]
v3[k * ratio] += v2[k]
v2[k * ratio] += 1
return count
print(countTriplets(arr, r))
print(countTriplets(arr2, r2))
print(countTriplets(arr3, r3))
#SCORE = 100
|
a8bc411483bd9b2fc4b383bda40d802a589cf6c6 | green-fox-academy/Atis0505 | /week-04/day-03/fibonacci/fibonacci.py | 353 | 4.21875 | 4 | def fibonacci_counter(int_index):
if int_index == None:
return None
else:
if type(int_index) is not int:
return 0
if int_index == 0:
return 0
elif int_index == 1:
return 1
else:
return fibonacci_counter(int_index-1) + fibonacci_counter(int_index-2)
|
0d96e943254c004be51980b6bf163a093537870b | ajityadav924/pandas-practice2 | /housingPd.py | 604 | 3.71875 | 4 | import pandas as pd
df=pd.read_csv("Housing.csv")
#print(df)
print(df.head()) #to print 1^st 5 rows
print(df.tail()) #to print last 5 rows
print(df[20:30]) #to print the rows between 20 to 30
print(df.dtypes)
print(df['bedrooms'].describe())
print(df['price'].mean())
print(df['price'].head(50).mean())
print(df['price'].mean())
print(df[['lotsize','price','bedrooms']])
print(df.groupby('bedrooms')[['price']].mean())
a=df.groupby('bedrooms').mean()
print(a)
df_sub=df[df['lotsize']<6000]
print(df_sub.mean())
|
f0ea590195b012d386066010a46d6e026ae9d156 | kcarollee/Problem-Solving | /Python/1110.py | 389 | 3.5625 | 4 | class Cycle:
def __init__(self, N):
self._n = N
self._cycle = 1
def cycleThru(self):
if self._n > 9:
a, b = self._n // 10, self._n % 10
elif self._n <= 9:
a, b = 0, self._n
while 10 * b + (a + b) % 10 != self._n:
self._cycle += 1
a, b = (10 * b + (a + b) % 10) // 10, (10 * b + (a + b) % 10) % 10
return self._cycle
n = int(input())
print(Cycle(n).cycleThru())
|
1468c2627d445e483cb80d0f18c4b7eec3a0f50c | acneuromancer/problem_solving_python | /graphs_2/Graph.py | 1,662 | 3.59375 | 4 | class Vertex(object):
def __init__(self, key):
self.key = key
self.neighbours = {}
def add_neighbour(self, neighbour, weight = 0):
self.neighbours[neighbour] = weight
def __str__(self):
return '{} neighbours: {}'.format(
self.key,
[x.key for x in self.neighbours]
)
def get_connections(self):
return self.neighbours.keys()
def get_weight(self, neighbour):
return self.neighbours[neighbour]
class Graph(object):
def __init__(self):
self.verticies = {}
def add_vertex(self, vertex):
self.verticies[vertex.key] = vertex
def get_vertex(self, key):
try:
return self.verticies[key]
except KeyError:
return None
def __contains__(self, key):
return key in self.verticies
def add_edge(self, from_key, to_key, weight = 0):
if from_key not in self.verticies:
self.add_vertex(Vertex(from_key))
if to_key not in self.verticies:
self.add_vertex(Vertex(to_key))
self.verticies[from_key].add_neighbour(self.verticies[to_key], weight)
def get_verticies(self):
return self.verticies.keys()
def __iter__(self):
return iter(self.verticies.values())
g = Graph()
for i in range(6):
g.add_vertex(Vertex(i))
print(g.verticies)
g.add_edge(0, 1, 5)
g.add_edge(0, 5, 2)
g.add_edge(1, 2, 4)
g.add_edge(2, 3, 9)
g.add_edge(3, 4, 7)
g.add_edge(3, 5, 3)
g.add_edge(4, 0, 1)
g.add_edge(5, 4, 8)
g.add_edge(5, 2, 1)
for v in g:
for w in v.get_connections():
print('{} -> {}'.format(v.key, w.key)) |
b71fd0e5cd1d6233d89059fdaf5f98462a58d691 | lastosellie/202003_platform | /한누리/04_algorithm_basic/mergesort.py | 814 | 4.09375 | 4 |
def sort(l_list, r_list):
list = []
while len(l_list) > 0 or len(r_list) > 0:
if len(l_list) > 0 and len(r_list) > 0:
if l_list[0] > r_list[0]:
list.append(r_list[0])
r_list = r_list[1:]
else:
list.append(l_list[0])
l_list = l_list[1:]
elif len(l_list) > 0:
list.append(l_list[0])
l_list = l_list[1:]
elif len(r_list) > 0:
list.append(r_list[0])
r_list = r_list[1:]
return list
def mergesort(list):
length = len(list)
if length <= 1:
return list
mid = length // 2
l_list = mergesort(list[:mid])
r_list = mergesort(list[mid:])
return sort(l_list, r_list)
list = [6,8,3,9,10,1,2,4,7,5]
print(mergesort(list))
|
e86181c7db47e9d90152b8061e8037306b111507 | Ankita2426/python | /python.123/practisessss.py | 204 | 3.71875 | 4 | def bubblesort(a):
n = len(a)
for i in range(n-1,0,-1):
for j in range(i):
if a[j]<a[j+1]:
a[j+1],a[j]=a[j],a[j+1]
a = [1,56,7,4,0,98,7]
bubblesort(a)
print(a)
|
4140224710e26d421c34a8a734818707ca20fdde | paramita2302/algorithms | /iv/Linkedlist/remove_duplicates_sorted_list.py | 982 | 3.8125 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def make_list(A):
head = ListNode(A[0])
ptr = head
for i in A[1:]:
ptr.next = ListNode(i)
ptr = ptr.next
return head
def display(head):
L = []
while head.next:
L.append(head.val)
head = head.next
L.append(head.val)
print(L)
class Remove():
# @param A : head node of linked list
# @return the head node in the linked list
def delete_duplicates(self, A):
ret = A
ptr = ret
while A:
if A.next:
if A.next.val == A.val:
A = A.next
continue
ret.next = A.next
A = A.next
ret = ret.next
return ptr
A = [1, 1, 2, 3, 3, 4]
A = [1, 1, 2, 3, 3, 4, 4, 4, 4]
head = make_list(A)
display(head)
a = Remove()
rev = a.delete_duplicates(head)
display(rev)
|
febe57623d228ad4e62557341662adc168cdbf64 | Coolman6564/python_learning | /mcb.pyw | 2,132 | 3.59375 | 4 | #! python3
# mcb.pyw - Saves and loads pieces of text to the clipboard.
# Usage: py.exe mcb.pyw save <keyword> - saves clipboard to keyword.
# py.exe mcb.pyw delete <keyword> - Deletes a keyword from the list.
# py.exe mcb.pyw delete all - Deletes ALL keywords from the list.
# py.exe mcb.pyw <keyword> - Loads keyword to clipboard.
# py.exe mcb.pyw list - Loads all keywords to clipboard.
import shelve
import pyperclip
import sys
mcbShelf = shelve.open("mcb")
# Save clipboard content.
if len(sys.argv) == 3 and sys.argv[1].lower() == 'save':
# Clipboard content is saved to shelf file at the key as the keyword.
# Key is located/given at sys.argv[2]
mcbShelf[sys.argv[2]] = pyperclip.paste()
elif len(sys.argv) == 3 and (sys.argv[1].lower == 'delete' and sys.argv[2].lower() == 'all'):
# Want to delete ALL keywords
for keyword in list(mcbShelf.keys()):
del mcbShelf[keyword]
print("ALL KEYWORDS DELETED!!!")
elif len(sys.argv) == 3 and sys.argv[1].lower() == 'delete':
# Want to delete the specified keyword ONLY!!
if sys.argv[2] in mcbShelf:
del mcbShelf[sys.argv[2]]
else:
print("Keyword not found!!")
elif len(sys.argv) == 2:
# List keywords OR load content...
if sys.argv[1].lower() == 'list':
# List keywords
pyperclip.copy(str(list(mcbShelf.keys())))
# Also print list to terminal for usefulness
print(str(list(mcbShelf.keys())))
elif sys.argv[1] in mcbShelf:
# then its a keyword and we want to load it into the clipboard
pyperclip.copy(mcbShelf[sys.argv[1]])
else:
print("Keyword not found!")
else:
# If the syntax from the command line isn't correct, print the usage to term
print("""Usage: py.exe mcb.pyw save <keyword> - saves clipboard to keyword.
py.exe mcb.pyw delete <keyword> - Deletes a keyword from the list.
py.exe mcb.pyw delete all - Deletes ALL keywords from the list.
py.exe mcb.pyw <keyword> - Loads keyword to clipboard.
py.exe mcb.pyw list - Loads all keywords to clipboard.""")
mcbShelf.close() |
4fe8170e11af47366522ebe93da07c7f90f35cbc | hpylieva/algorithms | /FillingLinkedList.py | 430 | 3.96875 | 4 | from LinkedList import ListNode
if __name__ == '__main__':
dummyHead = ListNode(0)
a = dummyHead
for i in [2, 4, 3]:
a.next = ListNode(i)
a = a.next
# dummyHead.next now is a linked list with values 2,4,3
# analogy
l = [0, []]
c = l
print(f'l: {l}, c: {c}')
c[1] = [2, []]
c = c[1]
print(f'l: {l}, c: {c}')
c[1] = [3, []]
c = c[1]
print(f'l: {l}, c: {c}')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.