blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
17a77522c49ec45a5a60e9d7e6fc1eb1ba94f774 | HDShaw/Runaway-Reservation-System-BST- | /binary_search_tree.py | 4,376 | 4.03125 | 4 | class tree_node(object):
def __init__(self,key = None, left = None, right = None):
self.key=key
self.left=left
self.right=right
class binary_search_tree(object):
def __init__(self,root=None):
self.root=root
def insert(self,key):
"""recursion way"""
self.root=self._insert(self.root, key)
def _insert(self,root,key):
if not root:
root=tree_node(key)
else:
if key<root.key:
root.left=self._insert(root.left,key)
elif key>root.key:
root.right=self._insert(root.right,key)
else:
print(key+"is already in tree")
return root
def delete(self,key):
self._delete(self.root,key)
def _delete(self,root,key):
if not root:
print("the bianry search tree does not exit")
return
else:
if key<root.key:
root.left=self._delete(root.left,key)
elif key>root.key:
root.right=self._delete(root.right,key)
elif root.left and root.right:
right_min=self._find_min(root)
root.key=right_min.key
root.right=self._delete(root.right,right_min.key)
elif root.left:
root=root.left
elif root.right:
root=root.right
else:
root=None
return root
def find_min(self):
return self._find_min(self.root)
def _find_min(self,root):
if not root.left:
return root
return self._find_min(root.left)
def find_max(self):
return self._find_max(self.root)
def _find_max(self,root):
if not root.right:
return root
return self._find_max(root.right)
def find(self,key):
return self._find(self.root,key)
def _find(self,root,key):
if not root:
print("sorry, the node is not found")
return
if key<root.key:
return self._find(root.left,key)
elif key>root.key:
return self._find(root.right,key)
else:
print("the node is found")
return root
def height(self):
return self._height(self.root)
def _height(self,root):
if not root:
return -1
left_height=self._height(root.left)
right_height=self._height(root.right)
if left_height>right_height:
return 1+left_height
else:
return 1+right_height
def subtree(self):
return self._subtree(self.root)
def _subtree(self,root):
if not root:
return 0
left_subtree=self._subtree(root.left)
right_subtree=self._subtree(root.right)
return 1+left_subtree+right_subtree
def inorder(self):
return self._inorder(self.root)
def _inorder(self,root):
if not root:
return
self._inorder(root.left)
print(root.key)
self._inorder(root.right)
def preorder(self):
return self._preorder(self.root)
def _preorder(self,root):
if not root:
return
print(root.key)
self._preorder(root.left)
self._preorder(root.right)
def postorder(self):
return self._postorder(self.root)
def _postorder(self,root):
if not root:
return
self._postorder(root.left)
self._postorder(root.right)
print(root.key)
def main():
import random
test = binary_search_tree()
print(type(test))
for i in random.sample([j for j in range(1, 100)], 5):
test.insert(i)
print('insert: ')
test.insert(78)
test.insert(101)
test.insert(14)
test.preorder()
test.inorder()
test.postorder()
print('height: ', test.height())
print('subtree: ', test.subtree())
print('min: ', test.find_min().key)
print('max: ', test.find_max().key)
print( 'delete: ')
test.delete(101)
test.delete(12)
test.preorder()
test.inorder()
test.postorder()
test.find(71)
test.find(78)
print('height: ', test.height())
print('count: ', test.subtree())
print('min: ', test.find_min().key)
print('max: ', test.find_max().key)
if __name__ == '__main__':
main()
|
eb79f7e79b9a79eeb8ebfb6d12b580516066b4da | elizabeth19-meet/yl1-201718 | /Project/ball.py | 1,213 | 3.859375 | 4 | from turtle import *
class Ball(Turtle):
def __init__(self, x, y, dx, dy, r, color):
Turtle.__init__(self)
self.penup()
self.x=x
self.y=y
self.dx = dx
self.dy = dy
self.r = r
self.color(color)
self.shape('circle')
self.goto(x, y)
self.shapesize(r/10)
self.color(color, color)
def move(self, screen_width, screen_height):
current_x = self.xcor()
new_x= current_x+self.dx
current_y = self.ycor()
new_y= current_y+self.dy
self.goto(new_x, new_y)
right_side_ball = new_x+self.r
left_side_ball = new_x-self.r
up_side_ball = new_y+self.r
down_side_ball = new_y-self.r
if up_side_ball>=screen_height:
self.dy=-self.dy
self.clear()
if left_side_ball<=-screen_width:
self.dx=-self.dx
self.clear()
if right_side_ball>=screen_width:
self.dx=-self.dx
self.clear()
if down_side_ball<=-screen_height:
self.dy=-self.dy
self.clear()
'''
player = Ball(0,0,100,500,10,'red')
flag = True
while flag:
player.move(700,700)
'''
|
be4dd527e96636ee178b150e160cbec28ac55082 | chowdhurynawaf/URI-SOLVE | /1154.py | 142 | 3.65625 | 4 | X = 0
Y = 0
Z = 0
while True:
Z = int(input())
if Z>0:
X = X+Z
Y = Y+1
else:
break
print("%.2f"%(X/Y))
|
6b58bc74a4169347f4c079516be12e6da439e8e0 | ArshanKhanifar/eopi_solutions | /src/vlad/problem_8_p_6_vlad.py | 1,831 | 3.8125 | 4 | from protocol.problem_8_p_6 import Problem8P6
from collections import deque
"""
THINGS TO NOTE ABOUT THIS PROBLEM
Problem 8.6var1 was trivial so was not explicitly done. You do exactly same thing as in this solution except every other
level you just pop instead of popleft (use a stack instead of queue)
Problem 8.6var2 was trivial so was not explicitly done. You do exactly same thing as in this solution except at the end
you reverse the result list using a linear algorithm with no memory requirement like solution to problem 7.2
I wonder if this problem can be solved using a different approach (like using a different search)
Problem 8.6var3 was trivial so was not explicitly done. You do exactly same thing as in this solution except after the
list is created for each level just take the average.
"""
class Problem8P6Vlad(Problem8P6):
def breadth_first_search(self, binary_tree):
return self.bfs_with_queue(binary_tree)
def bfs_with_queue(self, binary_tree):
# create a queue
dfs_list = []
if not binary_tree:
return dfs_list
node_queue = deque([binary_tree])
# use same queue for each level and keep emptying at the same time
# in the book solution they iterate over each queue element twice while I only do it once. Both solutions are
# still linear, but mine is slightly faster :P
while node_queue:
cur_level_list = []
for i in range(len(node_queue)):
cur_node = node_queue.popleft()
cur_level_list.append(cur_node.data)
if cur_node.left:
node_queue.append(cur_node.left)
if cur_node.right:
node_queue.append(cur_node.right)
dfs_list.append(cur_level_list)
return dfs_list
|
9c29eba38ae71213ccb6956476153b61c8f1415f | baieric/hackerRank | /leetcode/battleship_in_a_board.py | 641 | 3.515625 | 4 | # https://leetcode.com/problems/battleships-in-a-board/description/
class Solution(object):
def countBattleships(self, board):
"""
:type board: List[List[str]]
:rtype: int
"""
ships = 0
for x in range(len(board)):
row = board[x]
for y in range(len(row)):
if board[x][y] == 'X':
if y-1 >= 0 and board[x][y-1] == 'X':
continue
if x-1 >= 0 and board[x-1][y] == 'X':
continue
else:
ships = ships + 1
return ships
|
d7d2bf72d838557c0071f5760932312f501e6be1 | HariharanNandagopal/guviphy | /greatest of three number.py | 147 | 3.75 | 4 | a=input()
b=input()
c=input()
if(a>b) and (a>c):
print("1 st is big")
elif(b>a) and (b>c):
print("2nd one is big")
else:
print("third is big")
|
c72d56dc5144e3b87fca9bee754ad93705724752 | Palash51/Python-Programs | /Data Structures/xample/cpy_prime.py | 268 | 3.734375 | 4 | def selsort(a):
for i in range(len(a)):
m = min(a)
swap(a, i, m)
return a
def swap(arr, x, y):
#temp = 0
temp = arr[x]
arr[x] = arr[y]
arr[y] = temp
#return arr, x , y
a = [7, 5, 4, 2]
print selsort(a)
|
417642488986077f665b70df6e0ea6693a0a78e8 | goodgoodliving/3d-vision-semantic-localization | /code/images.py | 2,030 | 3.59375 | 4 | """
Module for loading the content from directory containing a sequence of timestamped images.
"""
import glob
import re
import numpy as np
from os.path import join, basename
def get_image_path_list(image_dir_path):
"""
Get a sorted list of paths of all images (files with file name pattern '*.jpg') in a given directory.
:param image_dir_path: Path to directory to scan for images
:returns: Sorted list of absolute paths to image files in the given directory
"""
return sorted(glob.glob(join(image_dir_path, '*.jpg')))#[50:-50] # TODO Undo
def get_image_names(image_dir_path):
"""
Get a sorted list of file names of all images (files with file name pattern '*.jpg') in a given directory.
:param image_dir_path: Path to directory to scan for images
:returns: Sorted list of file names of image files in the given directory
"""
image_paths = get_image_path_list(image_dir_path)
image_names = list([basename(path) for path in image_paths])
return image_names
def get_timestamps_from_images(image_names):
"""
Get the list of timestamps corresponding to the given list of image file names.
The timestamps are part of the file names of the images.
Examples for such file names:
img_CAMERA1_1261230001.080210_right.jpg
img_CAMERA1_1261230001.080210_left.jpg
:param image_names: List of image file names. Should be sorted, like the result from `get_image_names()`.
:returns: List of timestamps corresponding to the given list.
"""
pattern = re.compile('img_CAMERA1_(\d*.\d*)_(right|left).jpg')
result = []
for name in image_names:
match = pattern.match(name)
timestamp_str = match.group(1)
timestamp = float(timestamp_str)
result.append(timestamp)
assert(str(timestamp) in name)
# There should be one timestamp for each image
assert(len(result) == len(image_names))
# Timestamps need to be monotonic
assert(np.all(np.diff(np.array(result)) > 0))
return result
|
267f4deabb05214c0bd236f1abcbaf261bf4ccb0 | lucasbruscato/StretchingTimer | /helper.py | 993 | 3.609375 | 4 |
import os
import time
import datetime
######### change here #########
time_in_seconds = 35
###############################
exercises = [
'push up',
'lengthen the trunk down',
'lengthen the trunk to the right',
'lengthen the trunk to the left',
'stretch the right fist down',
'stretch the left fist down',
'stretch the right fist up',
'stretch the left fist up',
'lengthen the right leg',
'lengthen the left leg',
'lets enjoy the day'
]
os.system('say good morning, it is ' + str(datetime.datetime.now().hour) + ' e ' + str(datetime.datetime.now().minute))
os.system('say ' + exercises[0])
time.sleep(3)
for i in range(1, len(exercises)):
# print exercise and current time (in seconds)
for j in range(1, time_in_seconds):
print(exercises[i-1] + ' - ' + str(j))
time.sleep(1)
os.system('say ' + exercises[i])
os.system('say it is ' + str(datetime.datetime.now().hour) + ' e ' + str(datetime.datetime.now().minute))
|
b4591976d6bb1186dc8e2c3a71d03346aa9be598 | Yuvv/LeetCode | /0001-0100/0049-group-anagrams.py | 808 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : 0049-group-anagrams.py
# @Date : 2019/08/17
# @Author : Yuvv <yuvv_th@outlook.com>
from typing import List
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
d = dict()
for s in strs:
sorted_s = ''.join(sorted(s))
if sorted_s not in d:
d[sorted_s] = []
d[sorted_s].append(s)
result = list()
for v in d.values():
result.append(v)
return result
if __name__ == "__main__":
s = Solution()
print(s.groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))
print(s.groupAnagrams(['abab', 'baba', 'abba', 'ababa', 'babab', 'abbaa', '', '']))
print(s.groupAnagrams(["tao", "pit", "cam", "aid", "pro", "dog"]))
|
c72fae0c88fc3a896108cd5632463c5247c8b173 | betty29/code-1 | /recipes/Python/205126_Variant_property_allowing_one_functibe_used/recipe-205126.py | 2,356 | 3.53125 | 4 | class CommonProperty(object):
"""A more flexible version of property()
Saves the name of the managed attribute and uses the saved name
in calls to the getter, setter, or destructor. This allows the
same function to be used for more than one managed variable.
As a convenience, the default functions are gettattr, setattr,
and delattr. This allows complete access to the managed
variable. All or some of those can be overridden to provide
custom access behavior.
"""
def __init__(self, realname, fget=getattr, fset=setattr, fdel=delattr, doc=None):
self.realname = realname
self.fget = fget
self.fset = fset
self.fdel = fdel
self.__doc__ = doc or ""
def __get__(self, obj, objtype=None):
if obj is None:
return self
if self.fget is None:
raise AttributeError, "unreadable attribute"
return self.fget(obj, self.realname)
def __set__(self, obj, value):
if self.fset is None:
raise AttributeError, "can't set attribute"
self.fset(obj, self.realname, value)
def __delete__(self, obj):
if self.fdel is None:
raise AttributeError, "can't delete attribute"
self.fdel(obj, self.realname, value)
## Example of requiring password access to view selected attributes
class SecurityError(Exception): pass
def securitycheck(*args):
"Stub function. A real check should be a bit more thorough ;)"
return True
class Employee(object):
__authenticate = False
def __init__(self, name, dept, salary, age):
self.name=name
self.dept=dept
self._salary = salary
self._age = age
def authorize(self, userid, password):
if securitycheck(userid, password):
self.__authenticate = True
def passwordget(self, name):
if not self.__authenticate:
raise SecurityError, "Viewing secure data requires valid password"
return getattr(self, name)
salary = CommonProperty('_salary', passwordget, None, None, doc="Annual Salary")
age = CommonProperty('_age', passwordget, None, None, doc="Age as of 1 Jan 2003")
manager = Employee('Raymond', 'PySystemsGroup', 'ProBono', 38)
manager.authorize('Guido', 'omega5')
print manager.name
print manager.salary
|
60bd8139b3f279b9b3c8b0e3d8b37241c5e2a596 | KKosukeee/CodingQuestions | /LeetCode/199_binary_tree_right_side_view.py | 2,274 | 4.15625 | 4 | """
Solution for 199. Binary Tree Right Side View
https://leetcode.com/problems/binary-tree-right-side-view/
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
"""
Runtime: 40 ms, faster than 94.40% of Python3 online submissions for Binary Tree Right Side
View.
Memory Usage: 13.3 MB, less than 5.13% of Python3 online submissions for Binary Tree Right Side
View.
"""
# Time: O(n), Space: O(n)
def rightSideView(self, root):
"""
Given a binary tree, imagine yourself standing on the right side of it, return the values
of the nodes you can see ordered from top to bottom.
Example:
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:
1 <---
/ \
2 3 <---
\ \
5 4 <---
Args:
root: root node for a binary tree to begin with
Returns:
list<int>: an array contains all values that are seen from right side
"""
# If root is None, then return an empty array
if not root:
return []
# Initialize a result array
result = []
# Initialize a array which holds all nodes at a given level
level = [root]
# Loop while level array isn't empty
while level:
# Create a temporary level place holder
temp = []
# Assign right_most_node which will be the right most node at the end
right_most_node = None
# Loop for all nodes in level array
for node in level:
# Append it's left then it's right node
if node.left:
temp.append(node.left)
if node.right:
temp.append(node.right)
# Update right_most_node
right_most_node = node
# Append right_most_node to result array
if right_most_node:
result.append(right_most_node.val)
level = temp
# return the result array
return result
|
8239401a10c5471ba46d239a79409f83caa32050 | MengnanZoeZhou/LearnToProgramFundamentals | /Assignments/grade.py | 844 | 4.0625 | 4 | def read_grades(gradefile):
'''(file open for reading) -> list of float
Read and return the list of grades in the file.
Precondition: gradefile starts with a header that contains
no blank lines, then has a blank line, and then lines containing
a student number and a grade.
'''
# Skip over the header.
line = gradefile.readline()
while line != '\n':
line = gradefile.readline()
# Read the grades, accumulating them into a list.
grades = []
line = fradefile.readline()
while line != ''
# Now we have s string containing the infor for a single student.
# Find the last space and take everything after that space.
grade = [line.rfind(' ') + 1:] # grade is a string now.
grades.append(float(grade))
line = fradefile.readline()
return grades
|
d4732957153731bb76ae6d2881fb68ce5c52441c | Serendipity0618/python-practice | /zero_number_end2.py | 351 | 4.03125 | 4 | def factorial(n) :
product = 1
while n > 0:
product = product * n
n = n - 1
return product
n = input("Please input x:")
product = factorial(int(n))
print(product)
str = list(str(product))
#print(str)
i = -1
counter = 0
while int(str[i]) == 0:
counter = counter + 1
i = i - 1
print(counter)
|
418d9bce6e41fa47c99bf714be2baf2f0ae40b33 | kantel/nodebox-pyobjc | /examples/Extended Application/sklearn/examples/ensemble/plot_forest_importances.py | 2,601 | 4.25 | 4 | """
=========================================
Feature importances with forests of trees
=========================================
This examples shows the use of forests of trees to evaluate the importance of
features on an artificial classification task. The red bars are the feature
importances of the forest, along with their inter-trees variability.
As expected, the plot suggests that 3 features are informative, while the
remaining are not.
"""
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_classification
from sklearn.ensemble import ExtraTreesClassifier
# nodebox section
if __name__ == '__builtin__':
# were in nodebox
import os
import tempfile
W = 800
inset = 20
size(W, 600)
plt.cla()
plt.clf()
plt.close('all')
def tempimage():
fob = tempfile.NamedTemporaryFile(mode='w+b', suffix='.png', delete=False)
fname = fob.name
fob.close()
return fname
imgx = 20
imgy = 0
def pltshow(plt, dpi=150):
global imgx, imgy
temppath = tempimage()
plt.savefig(temppath, dpi=dpi)
dx,dy = imagesize(temppath)
w = min(W,dx)
image(temppath,imgx,imgy,width=w)
imgy = imgy + dy + 20
os.remove(temppath)
size(W, HEIGHT+dy+40)
else:
def pltshow(mplpyplot):
mplpyplot.show()
# nodebox section end
# Build a classification task using 3 informative features
X, y = make_classification(n_samples=1000,
n_features=10,
n_informative=3,
n_redundant=0,
n_repeated=0,
n_classes=2,
random_state=0,
shuffle=False)
# Build a forest and compute the feature importances
forest = ExtraTreesClassifier(n_estimators=250,
random_state=0)
forest.fit(X, y)
importances = forest.feature_importances_
std = np.std([tree.feature_importances_ for tree in forest.estimators_],
axis=0)
indices = np.argsort(importances)[::-1]
# Print the feature ranking
print("Feature ranking:")
for f in range(X.shape[1]):
print("%d. feature %d (%f)" % (f + 1, indices[f], importances[indices[f]]))
# Plot the feature importances of the forest
plt.figure()
plt.title("Feature importances")
plt.bar(range(X.shape[1]), importances[indices],
color="r", yerr=std[indices], align="center")
plt.xticks(range(X.shape[1]), indices)
plt.xlim([-1, X.shape[1]])
# plt.show()
pltshow(plt)
|
b49394ba3f4ce97fe89d500355ed70c50df49549 | SemieZX/InterviewBook | /代码/LinkedList/removeValue.py | 677 | 3.84375 | 4 |
# method 1
def removeValue1(head,num):
if head == None:
return None
stack = []
while head != None:
if head.val != num:
stack.append(head)
head = head.next
while stack:
stack[-1].next = head
head = stack.pop()
return head
# method 2
def removeValue2(head,num):
if head == None:
return head
while head != None and head.val == num:
head = head.next
# 找到第一个不是num的节点
pre = head
cur = head
while cur != None:
if cur.val == num:
pre.next = cur.next
else:
pre = cur
cur = cur.next
return head
|
c35d1bb018941a0e34663a3a6e32964b7101187c | parastuffs/INFOH410 | /TP_C/tp_c_template.py | 1,367 | 3.6875 | 4 | #!/usr/bin/python3
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import math
# You should install matplotlib for this code to work
# e.g. pip install matplotlib
# or https://matplotlib.org/users/installing.html
def q4():
"""
Q4 (c)
In this function, we initialize the positive and negative values,
and create the basis for plotting the figures.
Fore info about the plots visit:
https://matplotlib.org/index.html
"""
examples_p = [(6, 5), (5, 3), (4, 4)]
examples_n = [(1, 3), (2, 6), (9, 4), (5, 1), (5, 8)]
ax = plt.gca()
for x, y in examples_n:
ax.scatter(x, y, marker="_")
for x, y in examples_p:
ax.scatter(x, y, marker="+")
a, b, c, d = find_S(examples_p)
S_bound = patches.Rectangle((a, c), abs(a - b), abs(c - d), fill=False)
ax.add_patch(S_bound)
x, y, z, t = find_G((a, b, c, d), examples_n)
G_bound = patches.Rectangle((x, z), abs(x - y), abs(z - t), fill=False)
ax.add_patch(G_bound)
plt.show()
def find_S(p):
"""
Find the S boundary S = <a,b,c,d> where a <= x <= b and c <= y <= d
params:
p: list of positive training examples
"""
pass
def find_G(S, n):
"""
Find the G boundary, the biggest rectangle not containing any
negative example.
"""
pass
if __name__ == "__main__":
q4()
|
91288067ef5b7f53739f3bf929a5a592192e836d | senel-study/kosmo-3rd | /s.yoon/job interview/google_specialSort_answer.py | 166 | 3.921875 | 4 | def special_sort(s_list):
return [x for x in s_list if x < 0 ] + [x for x in s_list if x is 0] + [x for x in s_list if x > 0]
print(special_sort([-1,1,3,-2,2])) |
9308fc861d4b6c041e58a8f7a684f9b33166cead | reemahs0pr0/Daily-Coding-Problem | /Problem50 - Largest Set Consisiting of Multiples.py | 934 | 3.96875 | 4 | # Given a set of distinct positive integers, find the largest subset such that every pair of elements in the subset (i, j) satisfies either i % j = 0 or j % i = 0.
# For example, given the set [3, 5, 10, 20, 21], you should return [5, 10, 20]. Given [1, 3, 6, 24], return [1, 3, 6, 24].
def largest_set(l):
final_l = []
for i in range(len(l)):
if (l[i] in set(final_l)):
continue
else:
temp_l = []
temp_l.append(l[i])
for j in range(i+1, len(l)):
length = len(temp_l)
for k in range(length):
if (l[j] % temp_l[k] != 0):
break
if (l[j] % temp_l[k] == 0 and k == length-1):
temp_l.append(l[j])
if (len(temp_l) >= len(final_l)):
final_l = temp_l
temp_l = []
print(final_l)
l = [1, 3, 5, 6, 9, 10, 15, 20, 30, 40, 50]
largest_set(l) |
d9253fcd3d8275c340e665e74b6afcfe7fbf590b | shetty-shithil/python_code | /queue.py | 597 | 4.03125 | 4 | queue=list([])
n=1
while(n>=0):
print('1.Enter elements in queue')
print('2.Remove an element')
print('3.Print queue')
print('4.Print first element')
print('5.Print last elemnt')
print('6.Enter your choice:')
n=int(input())
if(n==1):
queue.append(input())
elif(n==2):
z=queue[-1]
queue.remove(queue[0])
print('The deleted element is',z)
elif(n==3):
print(queue)
elif(n==4):
print('The first element of queue is ',queue[0])
elif(n==5):
print('The last element of queue is ',queue[-1])
|
a0c1e73177c16d2b9f2ed0d39e4aea88f2f2838d | danRobot/ProyectoDise | /trayectoria.py | 5,614 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 12 19:52:53 2018
@author: mahou
"""
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
from numpy import pi
from scipy.interpolate import interp1d
from scipy import integrate
class Trayectoria():
def __init__(self,points=0,time=0,Path=np.array([0,0,0])):
self.n=points
self.t=time
self.P=Path
_=self.measure()
pass
def measure(self,n=0):
if(n==0):
n=self.n
self.L=-1
x0=self.P[0,0]
y0=self.P[0,1]
z0=self.P[0,2]
L=0
for p in (self.P[1:n]):
L=L+np.sqrt((p[0]-x0)**2+(p[1]-y0)**2+(p[2]-z0)**2)
x0=p[0]
y0=p[1]
z0=p[2]
pass
self.L=L
return self.L
def measure2(self):
self.L=-1
x0=self.P[0,0]
y0=self.P[0,1]
z0=self.P[0,2]
L=0
i=0
L1=np.zeros((self.n,))
for p in (self.P):
L=L+np.sqrt((p[0]-x0)**2+(p[1]-y0)**2+(p[2]-z0)**2)
x0=p[0]
y0=p[1]
z0=p[2]
L1[i]=L
i=i+1
pass
self.L1=L1
return L1
def createVel(self,d):
td=d*self.t
self.time=np.linspace(0,self.t,self.n)
#t1=self.time[0:int(self.n/2)]
#t2=self.time[int(self.n/2):self.n]
a=2/(self.t-td)
tr=(self.t-td)
ts=self.t-4*tr
tr2=3*tr+ts
"""sec=int(self.n/7)
self.time=np.concatenate([
np.linspace(0,2*tr,3*sec),
np.linspace(2*tr,0.75*tr2,sec),
np.linspace(0.75*tr2,self.t,3*sec)])"""
v1=1/(1+np.exp(-4*a*(self.time-tr)))
v2=1-1/(1+np.exp(-4*a*(self.time-tr2)))
v=v1*v2
Vmax=self.L/np.trapz(v,dx=self.time[2]-self.time[1])
self.v=Vmax*v
return self.time,self.v
def createVel2(self):
Vmax=np.pi*self.t/self.L
self.time=np.linspace(0,self.t,self.n)
a=1-((self.time-0.5*self.t)**2)/self.t
self.v=Vmax*np.sqrt(a)
return self.time,self.v
def assign(self):
V=np.zeros((self.n,3))
uv=np.zeros((self.n,3))
l2=[]
t2=[]
self.x=integrate.cumtrapz(self.v,self.time,initial=0)
fx=interp1d(self.x,self.time)
fv=interp1d(self.time,self.v)
for i in range(self.n):
if(i==(self.n-1)):
j=i
norm=np.linalg.norm(self.P[j]-self.P[i-1])
if(norm==0):
u=np.array([0,0,0])
else:
u=(self.P[j]-self.P[i-1])/norm
else:
j=i+1
norm=np.linalg.norm(self.P[j]-self.P[i])
if(norm==0):
u=np.array([0,0,0])
else:
u=(self.P[j]-self.P[i])/norm
pass
L0=self.L1[i]
if((L0-self.x[self.n-1])>0):
L0=self.x[self.n-1]
pass
ts=fx(L0)
Vi=fv(ts)
V[i,:]=u*Vi
uv[i,:]=u
l2.append(L0)
t2.append(ts)
pass
return V,uv,np.array(t2),np.array(l2)
pass
def createPath(Params,n,xi,xf,yi,yf):
t=np.linspace(-2*pi,-0.5,n,dtype=np.float64)
#X=np.abs(20+np.cos(t)+np.cos(2*t)+np.cos(4*t)+5*np.cos(6*t)+10*np.cos(8*t))
#Y=(np.sin(t)+np.sin(3*t)+np.sin(5*t)+np.sin(7*t)+np.sin(9*t))
#Z=np.abs(20+np.sin(t)+0.5*np.cos(2*t)+0.2*np.sin(3*t)+0.15*np.cos(5*t)+2*np.sin(7*t))
X=np.linspace(xi,xf,n,dtype=np.float64)
Y=np.linspace(yi,yf,n,dtype=np.float64)
Z=np.linspace(-1,1,n,dtype=np.float64)
#Z=-(Z-0.15)**2+0.15**2
Z=0.25*np.sqrt(1**2-Z**4)
#Z=1/(1+np.exp(-Z))
#X=2*np.cos(t)+0.5
#X=np.array(list(reversed(X)))
#Y=2*np.sin(t)+0.5
#Y=np.array(list(reversed(Y)))
#Z=X*Y
#ma=max(np.sqrt(X**2+Y**2+Z**2))*(np.sqrt(Params[0]**2+Params[1]**2+Params[2]**2))
maz=max(Z)/Params[2]
may=max(Y)/Params[1]
ma=max(X)/Params[0]
#X=X/ma
#Y=Y/may
#Z=Z/maz
shape=(n,1)
return np.concatenate([X.reshape(shape),Y.reshape(shape),Z.reshape(shape)],axis=1)
def createVel(d,tf,x,n):
td=d*tf
t=np.linspace(0,tf,n)
a=2/(tf-td)
tr=(tf-td)
ts=tf-4*tr
tr2=3*tr+ts
v1=1/(1+np.exp(-4*a*(t-tr)))
v2=1-1/(1+np.exp(-4*a*(t-tr2)))
v=v1*v2
Vmax=x/np.trapz(v,dx=t[2]-t[1])
v=Vmax*v
return t,v
def plot_colourline(fig,x,y,z,c):
#c = cm.jet((c-np.min(c))/(np.max(c)-np.min(c)))
ax = fig.gca(projection='3d')
for i in np.arange(len(x)-1):
ax.plot([x[i],x[i+1]], [y[i],y[i+1]],[z[i],z[i+1]], c=c[i])
return
def measure(X,Y,Z):
x0=X[0]
y0=Y[0]
z0=Z[0]
L=0
for x,y,z in zip(X[1:],Y[1:],Z[1:]):
L=L+np.sqrt((x-x0)**2+(y-y0)**2+(z-z0)**2)
x0=x
y0=y
z0=z
pass
return L
def assign(P,Vmag):
n=P.shape[0]
V=np.zeros((n,3))
uv=np.zeros((n,3))
for i in range(n):
if(i==(n-1)):
j=i
norm=np.linalg.norm(P[j]-P[i-1])
if(norm==0):
u=np.array([0,0,0])
else:
u=(P[j]-P[i-1])/norm
else:
j=i+1
norm=np.linalg.norm(P[j]-P[i])
if(norm==0):
u=np.array([0,0,0])
else:
u=(P[j]-P[i])/norm
pass
V[i,:]=u*Vmag[i]
uv[i,:]=u
pass
return V,uv
|
5ba5c5b5ab9d1e4e41da3611b75d9e226ab51d65 | arpithappu/python | /assignment1/q4.py | 117 | 3.734375 | 4 | n=int(input("enter anumber"))
sum=0
if n>0:
for i in range(1,n+1):
sum+=1/(i*i*i)
print(f"result:{sum}") |
314a4d115dd1b9d339038ed44269b50f2083cc4a | pranav-kural/Python-Practice | /example_logical_op.py | 276 | 3.921875 | 4 | # A = number of people living in the building
# B = eldest person living in the building
A = 10
B = "Simon"
eldestPerson = A and B
if eldestPerson != 0:
print("Name of the eldest person living in the building is", B)
else:
print("No one living in the building") |
4a293d8ff792467334e8616d9fd250127c22a5a9 | devinchugh/MS_Word-Functions | /main.py | 11,826 | 4.4375 | 4 | # CODES FOR VARIOUS PROGRAMS FOR STRINGS
print('Enter the string on which you wish to execute all the programs:')
print('At last press enter keeping the last line empty')
string = ''
temp = 'run'
while(temp == 'run'):
line = input()
string += line+' '
if line == '':
temp = 'stop'
lis = string.split()
# 1- PROGRAM TO COUNT THE TOTAL WORDS
print('1-The total number of words in the entered string are:', len(lis))
print('\n')
# 2- PROGRAM TO FIND THE WORDS BEGINNING WITH CAPITAL LETTER
cptl = []
for i in lis:
if ord(i[0]) > 64 and ord(i[0]) < 91:
cptl.append(i)
print('2-The words beginning with capital letters in the entered string are:', cptl)
print('\n')
# 3- PROGRAM TO FIND THE WORDS BEGINNING WITH SMALL LETTER
small = []
for i in lis:
if ord(i[0]) > 96 and ord(i[0]) < 123:
small.append(i)
print('3-The words beginning with small letters in the entered string are:', small)
print('\n')
# 4- PROGRAM TO FIND A PARTICUALAR WORD IS PRESENT IN ENTERED STRING OR NOT
find = input('4-Enter the word to be found:')
count = 0
for i in lis:
if find == i:
count += 1
if count != 0:
print('Yes, the word is present and its occurence is:', count)
else:
print('No, the word is not present')
print('\n')
# 5- PROGRAM TO REPLACE THE WORD
find = input('5-Enter the word to be replaced:')
count = 0
for i in lis:
if find == i:
count += 1
x = 0
if count != 0:
print('The entered word is present', count, 'times')
x = int(input('How many occurences of it you wish to replace:'))
replace = input('Enter the word by which it is to be replaced:')
else:
print('the word is not present')
string = ''
update = []
for i in lis:
update.append(i)
for i in range(x):
for j in range(len(update)):
if update[j] == find:
update[j] = replace
break
print('The updated string is:', ' '.join(update))
print('\n')
# 6- PROGRAM TO CAPITALISE THE WHOLE STRING
cptl = []
for i in lis:
str = ''
for j in i:
if ord(j) > 96 and ord(j) < 123:
str += chr(ord(j)-32)
else:
str += j
cptl.append(str)
print('The string with all the words in capital letters is:')
print(' '.join(cptl))
print('\n')
# 7- PROGRAM TO CHANGE CAPITAL LETTERS TO SMALL FOR THE WHOLE STRING
small = []
for i in lis:
str = ''
for j in i:
if ord(j) > 64 and ord(j) < 91:
str += chr(ord(j)+32)
else:
str += j
small.append(str)
print('The string with all the words in small letters is:')
print(' '.join(small))
print('\n')
# 8- PROGRAM TO ARRANGE THE WORDS OF THE STRING IN ASCENDING ORDER
words = []
for i in lis:
words.append(i)
for i in range(0, len(words)):
min = words[i]
temp = i
for j in range(i, len(words)):
if min > words[j]:
min = words[j]
temp = j
(words[i], words[temp]) = (words[temp], words[i])
print('The string with words arranged in ascending order is:')
print(' '.join(words))
print('\n')
# 9- PROGRAM TO ARRANGE THE WORDS OF THE STRING IN DESCENDING ORDER
for i in range(0, len(words)):
max = words[i]
temp = i
for j in range(i, len(words)):
if max < words[j]:
max = words[j]
temp = j
(words[i], words[temp]) = (words[temp], words[i])
print('The string arranged with words in descending order is:')
print(' '.join(words))
print('\n')
# 10-PROGRAM TO COUNT THE OCCURENCE OF EACH WORD
unq = []
countdic = {}
for i in lis:
if i not in unq:
unq.append(i)
for i in unq:
count = 0
for j in lis:
if i == j:
count += 1
countdic[i] = count
print('The dictionery with the count of occurence of every word is:')
print(countdic)
print('\n')
# 11-PROGRAM TO COUNT THE OCCURENCE OF EACH VOWEL
vowels = 'aeiou'
smstring = ''.join(small)
countvwl = {}
for i in vowels:
count = 0
for j in smstring:
if i == j:
count += 1
countvwl[i] = count
print('The count of the occurence of each vowel is:')
print(countvwl)
print('\n')
# 12-PROGRAM TO COUNT THE OCCURENCE OF EACH CONSONENT
countcon = {}
for i in range(ord('a'), ord('z')+1):
count = 0
for j in smstring:
if chr(i) in vowels:
break
elif chr(i) == j:
count += 1
if chr(i) not in vowels:
countcon[chr(i)] = count
print('The count of the occurence of each consonent is:')
print(countcon)
print('\n')
# 13- PROGRAM TO CHANGE LOWERCASE WORDS INTO UPPERCASE AND UPPERCASE WORDS TO LOWERCASE
newstr = ''
for i in lis:
temp = ''
for j in i:
if ord(j) >= ord('a') and ord(j) <= ord('z'):
temp += chr(ord(j)-32)
elif ord(j) >= ord('A') and ord(j) <= ord('Z'):
temp += chr(ord(j)+32)
else:
temp += j
newstr += temp+' '
print('The string with lowercase letters changed to uppercase and upper case letters changed to lowercase is:')
print(newstr)
print('\n')
# 14-PROGRAM TO REVERSE THE WHOLE PARAGRAPH
revstr = ''
for i in range(len(lis)-1, -1, -1):
revstr += lis[i]+' '
print('The whole paragraph in reverse order is:')
print(revstr)
print('\n')
# 15-PROGRAM TO REVERSE EACH WORD IN THE STRING
revword = ''
for i in lis:
temp = ''
for j in range(len(i)-1, -1, -1):
temp += i[j]
revword += temp+' '
print('The paragraph with all the words reversed is:')
print(revword)
print('\n')
# 16-PROGRAM TO REVERSE ONLY THOSE WORDS PRESENT AT EVEN INDEXES
reveven = ''
for i in range(0, len(lis)):
temp = ''
if i % 2 == 0:
for j in range(len(lis[i])-1, -1, -1):
temp += lis[i][j]
else:
temp += lis[i]
reveven += temp+' '
print('The paragraph with the words at even position reversed is:')
print(reveven)
print('\n')
# 17-PROGRAM TO REVERSE ONLY THOSE WORDS PRESENT AT ODD INDEXES
revodd = ''
for i in range(0, len(lis)):
temp = ''
if i % 2 != 0:
for j in range(len(lis[i])-1, -1, -1):
temp += lis[i][j]
else:
temp += lis[i]
revodd += temp+' '
print('The paragraph with the words at odd position reversed is:')
print(revodd)
print('\n')
# 18- PROGRAM TO REMOVE ALL THE SPACES FROM ENTERED STRING
spacefree = ''
for i in lis:
spacefree += i
print('The string with all the spaces removed from the entered string:')
print(spacefree)
print('\n')
# 19- PROGRAM TO MAKE A STRING WHICH ONLY CONTAINS WORDS AT EVEN POSITION
evenstr = ''
for i in range(len(lis)):
if i % 2 == 0:
evenstr += lis[i]+' '
print('The string with only the words at even position from entered string is:')
print(evenstr)
print('\n')
# 20- PROGRAM TO MAKE A STRING WHICH ONLY CONTAINS WORDS AT ODD POSITION
oddstr = ''
for i in range(len(lis)):
if i % 2 != 0:
oddstr += lis[i]+' '
print('The string with only the words at odd position from entered string is:')
print(oddstr)
print('\n')
# 21- PROGRAM TO SORT THE WORDS ACCORDING TO THEIR LENGTH
sortlis = []
for i in lis:
sortlis.append(i)
for i in range(len(sortlis)):
min = len(sortlis[i])
temp = i
for j in range(i, len(sortlis)):
if min > len(sortlis[j]):
min = len(sortlis[j])
temp = j
(sortlis[i], sortlis[temp]) = (sortlis[temp], sortlis[i])
print('The string with the words sorted according to their length is:')
print(' '.join(sortlis))
print('\n')
# 22- PROGRAM TO REMOVE VOWELS FROM THE ENTERED STRING
remvov = ''
vowels = 'aeiou'
for i in lis:
temp = ''
for j in i:
if j not in vowels:
temp += j
remvov += temp+' '
print('The string with all the vowels removed from entered string is:')
print(remvov)
print('\n')
# 23- PROGRAM TO SWAP THE ODD AND EVEN INDEXES WORDS
swaplis = []
for i in lis:
swaplis.append(i)
for i in range(0, len(lis)-1, 2):
(swaplis[i], swaplis[i+1]) = (swaplis[i+1], swaplis[i])
print('The string with the words at even indexes swapped with the words at odd indexes:')
print(' '.join(swaplis))
print('\n')
# 24- PROGRAM TO CHANGE A PARTICUALR WORD TO UPPERACASE TAKING USER INPUT
change = input('Enter the word that you want to change to uppercase:')
newstr = ''
for i in lis:
if i == change:
temp = ''
for j in i:
if ord(j) >= ord('a') and ord(j) <= ord('z'):
temp += chr(ord(j)-32)
else:
temp += j
newstr += temp+' '
else:
newstr += i+' '
print('The string with all the occurences of entered word changed to uppercase is:')
print(newstr)
print('\n')
# 25-PROGRAM TO PRINT THE WORD OCCURING MAXIMUM TIMES AND MINIMUM TIMES
wordcount = {}
uniqword = []
for i in lis:
if i not in uniqword:
uniqword.append(i)
for i in uniqword:
count = 0
for j in lis:
if i == j:
count += 1
wordcount[i] = count
max = 0
min = count
maxstr = ''
minstr = ''
for j in wordcount.values():
if j > max:
max = j
elif j < min:
min = j
for i in wordcount.keys():
if wordcount[i] == max:
maxstr += i+', '
elif wordcount[i] == min:
minstr += i+', '
maxstr = maxstr[:len(maxstr)-2]
minstr = minstr[:len(minstr)-2]
print('The words that occurs,', max, '(maximum times) are:')
print(maxstr)
print('\n')
print('The words that occurs,', min, '(minimum times) are:')
print(minstr)
print('\n')
# 26-PROGRAM TO REPLACE ALL OCCURENCES OF A PARTICULAR ALPHABET TO UPPERCASE
letter = input(
'Enter the letter which you want to change to uppercase(lowercase letter only):')
newlis = []
for i in lis:
temp = ''
for j in i:
if j == letter:
temp += chr(ord(j)-32)
else:
temp += j
newlis.append(temp)
print('The string with the entered letter changed to uppercase is:')
print(' '.join(newlis))
print('\n')
# 27- PROGRAM TO FIND THE WORD HAVING 'K' DISTINCT CHARACTERS
k = int(input('Enter the number to find the word having that much distinct characters:'))
find = []
for i in lis:
if len(i) < k:
pass
else:
count = 0
uniq = []
for j in i:
if j not in uniq:
uniq.append(j)
if len(uniq) == k:
find.append(i)
print('The words with the entered number of distinct characters is:')
print(', '.join(find))
print('\n')
# 28-PROGRAM TO COUNT THE FREQUENCY OF EACH CHARACTER IN THE STRING
countchr = {}
uniqchr = []
for i in lis:
for j in i:
if j not in uniqchr:
uniqchr.append(j)
for i in uniqchr:
count = 0
for j in lis:
for k in j:
if k == i:
count += 1
countchr[i] = count
print('The dictionery with the frequency of each character is:')
print(countchr)
print('\n')
# 29-PROGRAM TO FIND MAXIMUM AND MINIMUM OCCURING CHARACTER IN GIVEN STRING
max = 0
min = count
maxchr = ''
minchr = ''
for i in countchr.keys():
if countchr[i] > max:
max = countchr[i]
elif countchr[i] < min:
min = countchr[i]
for i in countchr.keys():
if countchr[i] == max:
maxchr += i+', '
elif countchr[i] == min:
minchr += i+', '
maxchr = maxchr[:len(maxchr)-2]
minchr = minchr[:len(minchr)-2]
print('The characters which occurs', max, '(maximum) times are:', maxchr)
print('\n')
print('The characters which occurs', min, '(minimum) times are:', minchr)
print('\n')
# 30- PROGRAM TO FIND AND PRINT THE SENTENCE WITH MAXIMUM NUMBER OF WORDS
lines = ' '.join(lis).split('.')
max = 0
for i in range(0, len(lines)):
if len(lines[i].split()) > max:
max = len(lines[i].split())
temp = i
print('The sentence having', max, '(maximum) words is:')
print(lines[temp])
print('\n')
print('\n')
print('THE END')
|
6815b68ebf82d0dfa1221d89acb092f4cadbb93f | vaibhav20325/school_practical | /Class11/q7.py | 167 | 3.578125 | 4 | h=int(input("Enter number of heads "))
l=int(input("Enter number of legs "))
a=int((l-2*h)/2)
b=h-a
print ("Number of rabbits is", a, "Number of chickens is", b)
|
276a25ef9628b579bdcc4c5148a5c2dbfb6b1029 | daniel-reich/ubiquitous-fiesta | /rSa8y4gxJtBqbMrPW_14.py | 94 | 3.609375 | 4 |
def lcm(n1, n2):
num = max(n1,n2)
while num%n1!=0 or num%n2!=0:
num+=1
return num
|
e8a09ad36b45339d5a4b3f0e35e1b447d603f48b | Arnold329/Game | /dice.py | 771 | 3.53125 | 4 | import random, pygame, time
pygame.init()
screen_width, screen_height = 100, 100
screen = pygame.display.set_mode((screen_width, screen_height))
def display_die(nums, x, y):
random_num = int(random.choice(nums))
die_face_to_display = pygame.image.load("./images/dice/die_" +str(random_num) + ".png")
screen.blit(die_face_to_display, (x, y))
pygame.display.update()
pygame.time.wait(500)
return random_num
def roll_dice(nums, x, y):
random_num = int(random.choice(nums))
rolls = 0
result = 0
running = True
while running:
while rolls < 8:
result = display_die(nums, x, y)
rolls += 1
return result
|
0b7b1d5fedc080022cd9caf3e07eed87559248ab | zhanxinl/self-teaching | /185apple_plan/mit-introduction to Computer Science and Programming in Python/hw/coursa/test.py | 426 | 3.5 | 4 |
s = 'abcbcd'
max_len=0
max_str=""
if len(s)==0 or len(s)==1:
max_len=len(s)
max_str=s
else:
n=1
start=0
end=1
while end<len(s):
if s[end-1]<=s[end]:
n+=1
end+=1
if n>=max_len:
max_str=s[start:end]
max_len=n
else:
start=end
end+=1
n=1
print(max_str + " and " + str(max_len))
|
c6bccec19209ed6c9e2d1f812b70a6457dc3c1b6 | supvolume/codewars_solution | /5kyu/pack_bagpack.py | 491 | 3.796875 | 4 | """ solution for Packing your backpack challenge
find maximum score to fit in bagpack with given capacity"""
# NOT FINISH
def pack_bagpack(scores, weights, capacity):
bagpack_list = list(zip(scores, weights))
bagpack_list.sort(reverse = True)
max_score = 0
total_cap = 0
for i in range(len(bagpack_list)):
if bagpack_list[i][1] + total_cap <= capacity:
max_score += bagpack_list[i][0]
total_cap += bagpack_list[i][1]
return max_score |
adca92958262cc3e25f99541be42eeebe51c5225 | anfernee84/Learning | /python/func2.py | 227 | 3.953125 | 4 | def positive():
print('Positive')
def negative():
print('Negative')
def test ():
a = int(input('Enter a digit:' ))
if a < 0:
negative()
else:
positive()
test () |
2df038ee4cd9471a94fbb8e86318ce31342966e8 | bhuvankaruturi/Python-Programs | /Python Regex/filter2.py | 1,247 | 3.546875 | 4 | import re
def RemoveDuplicates(matches):
uniqueList = []
duplicate = False
for i in range(0, len(matches)):
for j in range(0, len(uniqueList)):
if matches[i] == uniqueList[j]:
duplicate = True
if not duplicate:
uniqueList.append(matches[i])
duplicate = False
return uniqueList
def ReplaceStrings(uniqueList, source, target):
for i in range(0, len(uniqueList)):
uniqueList[i] = str(uniqueList[i]).replace(source, target)
return uniqueList
def WriteToFile(uniqueList, target, extension):
try:
fileToWrite = open('finalist-' + target + extension, 'w')
for value in uniqueList:
fileToWrite.writelines(value + '\n')
fileToWrite.close()
except(e):
print("something went wrong while writing to the file" + "\n" + e)
text = ''
filename = input('enter filename: ')
source = input('string to be replaced: ')
target = input('string to be substituted: ')
extension = input('output file extension: ')
try:
file = open(filename, 'r')
text = file.read()
file.close()
except:
print('Something went wrong')
regExpression = "CREATE VIEW [\w]* "
matches = re.findall(regExpression, text)
if matches:
WriteToFile(ReplaceStrings(RemoveDuplicates(matches), source, target), target, extension)
else:
print('no matches') |
0b6c9d4a75c9953ab7a30bcf07b9dea14be08943 | ggchappell/AdventOfCode2020 | /day15/solve-15b.py | 1,346 | 3.546875 | 4 | #!/usr/bin/env python3
# Advent of Code 2020
# Glenn G. Chappell
import sys # .stdin
import itertools # .count
# ======================================================================
# HELPER FUNCTIONS
# ======================================================================
def generate_numbers(start_list):
assert isinstance(start_list, list)
assert len(start_list) > 0
number_dict = {}
for n in itertools.count(0):
if n < len(start_list):
new_num = start_list[n]
else:
new_num = next_num
if new_num in number_dict:
next_num = n-number_dict[new_num]
else:
next_num = 0
number_dict[new_num] = n
yield new_num
# ======================================================================
# MAIN PROGRAM
# ======================================================================
# *** Process Input ***
line = sys.stdin.readline()
line = line.rstrip()
num_strs = line.split(",")
start_list = [ int(s) for s in num_strs ]
# *** Do Computation ***
index_of_value = 30000000
for i, num in enumerate(generate_numbers(start_list)):
if (i+1) <= 20 or (i+1) % 100000 == 0:
print(i+1, num)
if i+1 == index_of_value:
result = num
break
# *** Print Answer ***
print("-" * 60)
print(f"Answer: {result}")
|
c17262d53028457e9900bfa6b8142c25ede24fea | leannef/SENG265-Software-Development-Methods | /assignment_02/import math.py | 3,637 | 3.78125 | 4 | import math
'''
Purpose
Provide an exception class for Point and Line.
Exceptions
None
Preconditions
Message is a string.
'''
class Error(Exception):
def __init__(self, message):
self.message = message
'''
Purpose
Store a point as an x, y pair.
Provide functions to rotate, scale and translate the point.
Preconditions
After instantiation, a Point object is modified only by
rotate, scale and translate.
'''
class Point:
'''
Purpose
Create a Point instance from x and y.
Exceptions
Raise Error if x or y are not of type float.
Preconditions
None
'''
def __init__(self, x, y):
self.x = x
self.y = y
isfloat1 = float(x)
isfloat2 = float(y)
if isfloat1 != x:
raise Error('caught: Parameter "x" illegal.')
elif isfloat2 != y:
raise Error('caught: Parameter "y" illegal.')
'''
Purpose
Rotate counterclockwise, by a radians, about the origin.
Exceptions
Raise Error if a is not of type float.
Preconditions
None
'''
def rotate(self, a):
x0 = cos(a) * x - sin(a) * y
y0 = sin(a) * x + cos(a) * y
isfloat = float(a)
if isfloat != a:
raise Error('caught: Parameter "a" illegal.')
'''
Purpose
Scale point by factor f, about the origin.
Exceptions
Raise Error if f is not of type float.
Preconditions
None
'''
def scale(self, f):
x0 = f * x
y0 = f * y
isfloat = float(f)
if isfloat != f:
raise Error('caught: Parameter "f" illegal.')
'''
Purpose
Translate point by delta_x and delta_y.
Exceptions
Raise Error if delta_x, delta_y are not of type float.
Preconditions
None
'''
def translate(self, delta_x, delta_y):
x0 = x + delta_x
y0 = y + delta_y
isfloat1 = float(delta_x)
isfloat2 = float(delta_y)
if isfloat != delta_x:
raise Error('caught: Parameter "delta_x" illegal.')
elif isfloat2 != delta_y:
raise Error('caught: Parameter "delta_y" illegal.')
'''
Purpose
Round and convert to int in string form.
Exceptions
None
Preconditions
None
'''
def __str__(self):
isfloat = float(self)
if isfloat == self:
return int(float(self) + 0.5)
'''
Purpose
Store a Line as a pair of Point instances.
Provide functions to rotate, scale and translate the line.
Preconditions
After instantiation, a Line object is modified only by
rotate, scale and translate.
'''
class Line:
'''
Purpose
Create a Line instance from point0 and point1.
Exceptions
None
Preconditions
None
'''
def __init__(self, point0, point1):
point0 = Point._init_(point0,x,y)
point1 = Point._init_(point1,x,y)
self.point0 = point0
self.point1 = point1
line = Line(point0, point1)
'''
Purpose
Rotate counterclockwise, by a radians, about the origin.
Exceptions
Raise Error if a is not of type float.
Raise Error if self.point0 or self.points1 is not legal.
Preconditions
None
'''
def rotate(self, a):
line = Line(point0,point1)
line.rotate(a)
'''
Point.rotate(point0,a)
Point.rotate(point1,a)
'''
'''
Purpose
Scale point by factor f, about the origin.
Exceptions
Raise Error if f is not of type float.
Preconditions
None
'''
def scale(self, factor):
line = Line(point0,point1)
line.scale(factor)
'''
Purpose
Translate Line by delta_x and delta_y.
Exceptions
Raise Error if delta_x, delta_y are not of type float.
Preconditions
None
'''
def translate(self, delta_x, delta_y):
line = Line( point0, point1 )
line.translate(delta_x, delta_y)
'''
Purpose
Round and convert to int in string form.
Exceptions
None
Preconditions
None
'''
def __str__(self):
isfloat = float(self)
if isfloat == self
return int(float(self) + 0.5)
|
9e58f1338774738e438c683de67334e21c42f90d | wxiea/CS2302Lab4 | /main.py | 5,759 | 3.8125 | 4 | class BTree(object):
# Constructor
def __init__(self,item=[],child=[],isLeaf=True,max_items=5):
self.item = item
self.child = child
self.isLeaf = isLeaf
if max_items <3: #max_items must be odd and greater or equal to 3
max_items = 3
if max_items%2 == 0: #max_items must be odd and greater or equal to 3
max_items +=1
self.max_items = max_items
def FindChild(T,k):
# Determines value of c, such that k must be in subtree T.child[c], if k is in the BTree
for i in range(len(T.item)):
if k < T.item[i]:
return i
return len(T.item)
def InsertInternal(T,i):
# T cannot be Full
if T.isLeaf:
InsertLeaf(T,i)
else:
k = FindChild(T,i)
if IsFull(T.child[k]):
m, l, r = Split(T.child[k])
T.item.insert(k,m)
T.child[k] = l
T.child.insert(k+1,r)
k = FindChild(T,i)
InsertInternal(T.child[k],i)
def Split(T):
#print('Splitting')
#PrintNode(T)
mid = T.max_items//2
if T.isLeaf:
leftChild = BTree(T.item[:mid])
rightChild = BTree(T.item[mid+1:])
else:
leftChild = BTree(T.item[:mid],T.child[:mid+1],T.isLeaf)
rightChild = BTree(T.item[mid+1:],T.child[mid+1:],T.isLeaf)
return T.item[mid], leftChild, rightChild
def InsertLeaf(T,i):
T.item.append(i)
T.item.sort()
def IsFull(T):
return len(T.item) >= T.max_items
def Insert(T,i):
if not IsFull(T):
InsertInternal(T,i)
else:
m, l, r = Split(T)
T.item =[m]
T.child = [l,r]
T.isLeaf = False
k = FindChild(T,i)
InsertInternal(T.child[k],i)
def height(T):
if T.isLeaf:
return 0
return 1 + height(T.child[0])
def Search(T,k):
# Returns node where k is, or None if k is not in the tree
if k in T.item:
return T
if T.isLeaf:
return None
return Search(T.child[FindChild(T,k)],k)
def Print(T):
# Prints items in tree in ascending order
if T.isLeaf:
for t in T.item:
print(t,end=' ')
else:
for i in range(len(T.item)):
Print(T.child[i])
print(T.item[i],end=' ')
Print(T.child[len(T.item)])
def PrintD(T,space):
# Prints items and structure of B-tree
if T.isLeaf:
for i in range(len(T.item)-1,-1,-1):
print(space,T.item[i])
else:
PrintD(T.child[len(T.item)],space+' ')
for i in range(len(T.item)-1,-1,-1):
print(space,T.item[i])
PrintD(T.child[i],space+' ')
def SearchAndPrint(T,k):
node = Search(T,k)
if node is None:
print(k,'not found')
else:
print(k,'found',end=' ')
print('node contents:',node.item)
def Sortlist(T,L):
if T.isLeaf:
for i in range(len(T.item)):
L.append(T.item[i])#leaf
else:
for j in range(len(T.item)):
Sortlist(T.child[j], L)
L.append(T.item[j])#the node
Sortlist(T.child[len(T.item)], L)#all the leaf
return L
def MinAtDepth(T, d):
if T.isLeaf and d != 0:
return False
elif d == 0:
return T.item[0]
else:
return MinAtDepth(T.child[0], d-1)
def MaxAtDepth(T,d):
if T.isLeaf and d != 0:
return False
elif d == 0:
return T.item[-1]
else:
return MaxAtDepth(T.child[-1], d-1)
def NumOfNodes(T,d):
if T.isLeaf and d != 0:
return False
elif d == 0:
return 0
elif d != 0:
for i in range(len(T.item)+1):
return PrintHeight(T.child[i],d-1)+1
def PrintHeight(T,d):
if T.isLeaf and d != 0:
return False
elif d == 0:
print(T.item)
elif d == 1:
for i in range(len(T.item)+1):
print(T.child[i].item)
elif d != 0 or d != 1:
for i in range(len(T.item)+1):
PrintHeight(T.child[i],d-1)
"""
def NumofNode(T):
if IsFull(T):
return 0
else:
for i in range(len(T.item)):
return NumofNode(T.child[i]) + 1
"""
def NumofNode(T):
if T.isLeaf:
return 0
else:
count = 0
for i in range(len(T.item)):
count += 1+NumofNode(T.child[i])
return count
def NumofLeaves1(T):
if T.isLeaf:
return 1
else:
for i in range(len(T.item)):
return NumofLeaves(T.child[len(T.item)])
def KeyAtDepth(T, k):
# Returns node where k is, or None if k is not in the tree
if k in T.item:
return T
if T.isLeaf:
return None
return 1 + KeyAtDepth(T.child[len(T.item)], k)
#L = [30, 50, 10, 20, 60, 70, 100, 40, 90, 80, 110, 120, 1, 11, 3, 4, 5, 105, 115, 200, 2, 45, 6]
L = [20,50,78,23,54,95,7,55,23,44,15,74,110,120,152,236,204,153,54,78,91]
#L = [20,50,78,23,54]
T = BTree()
for i in L:
#print('Inserting', i)
Insert(T, i)
#PrintD(T, '')
#Print(T)
#print('\n####################################')
Print(T.child[0])
print(T.child[0].child[0].item)
for i in range(len(T.item)+1):
print(T.child[i].item)
print('height', height(T))
list = []
print(Sortlist(T, list))
print('minimum', MinAtDepth(T,1))
print('maximum ', MaxAtDepth(T,1))
#print(NumOfNodes(T,2))
PrintHeight(T,2)
print(NumofNode(T))
print(NumofLeaves(T))
print(KeyAtDepth(T,3))
|
a4e0fa9ca5f0fda5817b02889346b848d47240d2 | b-ark/lesson_5 | /Task1.py | 399 | 4.34375 | 4 | # Write a Python program to get the largest number from a list of random numbers with the length of 10
# Constraints: use only while loop and random module to generate numbers
from random import randint
random_list = []
counter = 0
while counter != 10:
random_list += [randint(0, 10)]
counter += 1
print(random_list)
max_number = max(random_list)
print('Largest number is ', max_number)
|
a61881ea17bd5331463bf4f551787b254383290c | eronekogin/leetcode | /2021/minimum_number_of_refueling_stops.py | 1,048 | 3.765625 | 4 | """
https://leetcode.com/problems/minimum-number-of-refueling-stops/
"""
from heapq import heappop, heappush
class Solution:
def minRefuelStops(
self,
target: int,
startFuel: int,
stations: list[list[int]]) -> int:
"""
Keep driving until no fuel left. Then take the maximum refuel from
the previous gas station. If we cannot reach to the current location,
the task is impossible.
"""
heap = []
refuledStops = prevLocation = 0
tank = startFuel
for currlocation, capacity in stations + [(target, float('inf'))]:
tank -= currlocation - prevLocation
while heap and tank < 0: # Must refuel now.
tank += -heappop(heap)
refuledStops += 1
if tank < 0:
# Don't have enough fuel to reach the current location.
return -1
heappush(heap, -capacity)
prevLocation = currlocation
return refuledStops
|
4f314b32a45fc1e1acc2e5f1b1adca304b9c7ec8 | kaalachor/Python-OOPS | /General_Decorator.py | 358 | 3.75 | 4 | # This decorator can decorate any function
# args will be the tuple of positional arguments.
# kwargs will be the dictionary of keyword arguments.
def works_for_all(func):
def inner(*args, **kwargs):
print("I can decorate any function")
return func(*args, **kwargs)
return inner
@works_for_all
def demo():
print('demo')
demo() |
86e6af527928f9d91539f47d81ec653c0eae8bec | diegohsales/EstudoSobrePython | /List Comprehensions.py | 568 | 4.25 | 4 | """
Set Comprehension
Lista = [1, 2, 3, 4, 5]
Set = {1, 2, 3, 4, 5}
#Exemplos
numeros = {num for num in range(1, 7)}
print(numeros)
#Outro exemplo
numeros = {x ** 2 for x in range(10)}
print(numeros)
#DESAFIO! O que pode ser feito para alterar na estrutura abaixo para gerar um dicionário ao invés de Set?
numeros = {x ** 2 for x in range(10)} #É só acrescentar um x e : na frente do outro x que ao imprimir vira um
dicionário:
print(numeros)
letras = {letra for letra in 'Geek University'} #Sem ordenação e sme repetição
print(letras)
"""
|
f577dc5bb8ceb984c52a4c6269b98800d0f46320 | maniraja1/Python | /proj1/Python-Test1/CodingInterview/stacks_queues/stacks_queues.py | 518 | 4.09375 | 4 |
# Stacks Using list
print("#"*20+"Stacks"+"#"*20)
stack = ["Amar", "Akbar", "Anthony"]
stack.append("Ram")
stack.append("Iqbal")
print(stack)
# Removes the last item
print(stack.pop())
print(stack)
# Removes the last item
print(stack.pop())
print(stack)
#Queues using list
print("#"*20+"Queues"+"#"*20)
stack = ["Amar", "Akbar", "Anthony"]
stack.append("Ram")
stack.append("Iqbal")
print(stack)
# Removes the first item
print(stack.pop(0))
print(stack)
# Removes the first item
print(stack.pop(0))
print(stack)
|
12631ccd1c9ac579d030121c5eee69fed4002b51 | DawnSeeker99/Uni-Stuff | /Hello World.py | 771 | 4.1875 | 4 | from math import ceil
while True:
try:
students = int(input('How many students are there? '))
if students > 0:
break
else:
print('Please enter a positive number.')
except ValueError:
print('Please enter a positive number')
while True:
try:
computers = int(input('How many computers are there in each lab? '))
if computers > 0:
break
else:
print('Please enter a positive number.')
except ValueError:
print('Please enter a positive number')
labs = ceil(students/computers)
if students > computers:
print('You need', labs, 'labs for all the students.')
elif computers >= students:
print('You need', labs, 'lab for all the students.')
|
98bdee7605dbf1b09df3dd0b446d0a0f6e1eff7d | dicao425/algorithmExercise | /LintCode/miniTwitter.py | 2,486 | 3.96875 | 4 | #!/usr/bin/python
import sys
'''
Definition of Tweet:
class Tweet:
@classmethod
def create(cls, user_id, tweet_text):
# This will create a new tweet object,
# and auto fill id
'''
class MiniTwitter:
def __init__(self):
# do intialization if necessary
self.order = 0
self.news_feed = {}
self.friends = {}
"""
@param: user_id: An integer
@param: tweet_text: a string
@return: a tweet
"""
def postTweet(self, user_id, tweet_text):
# write your code here
tweet = Tweet.create(user_id, tweet_text)
self.order += 1
if user_id not in self.news_feed:
self.news_feed[user_id] = [(self.order, tweet)]
else:
self.news_feed[user_id].insert(0, (self.order, tweet))
return tweet
"""
@param: user_id: An integer
@return: a list of 10 new feeds recently and sort by timeline
"""
def getNewsFeed(self, user_id):
# write your code here
feeds = []
if user_id in self.news_feed:
feeds = self.news_feed[user_id][:10]
if user_id in self.friends:
for f in self.friends[user_id]:
if f in self.news_feed:
feeds.extend(self.news_feed[f][:10])
feeds.sort(cmp=lambda x, y: cmp(x[0], y[0]), reverse=True)
return [i[1] for i in feeds[:10]]
"""
@param: user_id: An integer
@return: a list of 10 new posts recently and sort by timeline
"""
def getTimeline(self, user_id):
# write your code here
if user_id in self.news_feed:
return [i[1] for i in self.news_feed[user_id][:10]]
else:
return []
"""
@param: from_user_id: An integer
@param: to_user_id: An integer
@return: nothing
"""
def follow(self, from_user_id, to_user_id):
# write your code here
if from_user_id not in self.friends:
self.friends[from_user_id] = {to_user_id}
else:
self.friends[from_user_id].add(to_user_id)
"""
@param: from_user_id: An integer
@param: to_user_id: An integer
@return: nothing
"""
def unfollow(self, from_user_id, to_user_id):
# write your code here
if from_user_id not in self.friends:
return
self.friends[from_user_id].remove(to_user_id)
def main():
aa = Solution()
return 0
if __name__ == "__main__":
sys.exit(main()) |
67fdb7b386f622cad9e0cf7cdebaf3500cbb5255 | daniela-mejia/Python-Net-idf19- | /PhythonAssig/5-15-19 Assigment 12/pi.py | 729 | 3.578125 | 4 | import sys
from math import pi
def calcPi():
q, r, t, k, n, l = 1, 0, 1, 1, 3, 3
while True:
if 4*q+r-t < n*t:
yield n
nr = 10*(r-n*t)
n = ((10*(3*q+r))//t)-10*n
q *= 10
r = nr
else:
nr = (2*q+r)*l
nn = (q*(7*k)+2+(r*l))//(t*l)
q *= k
t *= l
l += 2
k += 1
n = nn
r = nr
number_of_places =str(input("Enter the number of decimal places you want to see: "))
fraser = calcPi()
length_of_pi = [fraser]
for number_of_places in fraser:
length_of_pi.append(str(number_of_places))
print("".join(length_of_pi)) |
cbbe30cb2d381086d6a619de9c2a2651f7b11d7f | gireevash/giree | /varshu.py | 108 | 3.75 | 4 | guvi = int(input(' '))
if(guvi % 4==0 and guvi % 100!=0 or guvi % 400==0):
print('yes')
else:
print('no')
|
59aef11625c67edeb838dae91c0e3328e9447601 | christopher-burke/warmups | /python/misc/partially_hidden_string.py | 1,311 | 4.53125 | 5 | #!/usr/bin/env python3
"""Partially Hidden String.
Create a function that takes a phrase and transforms each word
using the following rules:
* Keep first and last character the same.
* Transform middle characters into a dash -.
Source:
https://edabit.com/challenge/h9hp2vGKbHJBzN87i
"""
def hide_word(word, replace_char='-'):
"""Hide the word."""
return "".join([word[0], len(word[1:-1]) * replace_char, word[-1]])
def partially_hide(phrase):
"""Modify the phrase."""
return " ".join([hide_word(word) for word in phrase.split()])
def main():
"""Run sample partially_hide functions. Do not import."""
assert partially_hide('Harry went to fight the basilisk') == \
'H---y w--t to f---t t-e b------k'
assert partially_hide('She rolled her eyes') == \
'S-e r----d h-r e--s'
assert partially_hide('skies were so beautiful') == \
's---s w--e so b-------l'
assert partially_hide('red is not my color') == \
'r-d is n-t my c---r'
assert partially_hide('so many options') == \
'so m--y o-----s'
assert partially_hide('the orient express') == \
't-e o----t e-----s'
assert partially_hide('went to the post office') == \
'w--t to t-e p--t o----e'
print('Passed.')
if __name__ == "__main__":
main()
|
0580d8335ffcd9a6b6f8e77fb22ecb7eb97608ff | josephsurin/cp-practice | /ANZAC/2019/ANZAC Round 1 2019/j.py | 127 | 3.78125 | 4 | n = int(input())
print('1 2 b')
print('1 2 c')
for i in range(3, n+1):
print('b', i, 'c')
print('c', i, 'b')
print('b c a') |
49165b593f67df4d46984ba0aa76eec577262ca4 | gabriellaec/desoft-analise-exercicios | /backup/user_386/ch149_2020_04_13_20_02_10_955520.py | 818 | 3.78125 | 4 | salario=float(input('salario? :'))
dep=float(input('dependentes?: '))
if salario <= 1045:
INSS = 0.075*salario
if salario > 1045 and salario <= 2089.6:
INSS = 0.09*salario
if salario > 2089.6 and salario <= 3134.4:
INSS = 0.12*salario
if salario > 3134.4 and salario<= 6101.06:
INSS = 0.14*salario
if salario > 6101.06:
INSS = 671.12
final = salario - INSS - (dep*189.59)
if final <= 1903.98:
alíquota = 0
dedução = 0
if final > 1903.98 and final <= 2826.65:
alíquota = 0.075
dedução = 142.8
if final > 2826.65 and final <= 3751.05:
alíquota = 0.15
dedução = 354.8
if final > 3751.05 and final <= 4664.68:
alíquota = 0.225
dedução = 636.13
if final > 4664.68:
alíquota = 0.275
dedução = 869.36
IRRF = calc * alíquota - dedução
print(IRRF) |
47baeaf789ea3af71615976f722f4c2aec797eb5 | MuralidharanGanapathy/Hackerrank | /Swapcase.py | 100 | 4 | 4 | def swap_case(s):
s = "".join(c.lower() if c.isupper() else c.upper() for c in s)
return s
|
3bb189261e6c46a32cd61177027642fe93fc88b5 | coderTa/sets | /sets/sets_sum.py | 225 | 3.5 | 4 | array = [5, 7, 2, 3, 1, 0]
checked_set = set([])
for i in range(len(array)):
num = array[i]
complement = 7 - num
checked_set.add(complement)
if num in checked_set:
print(num, complement) |
4c57c692d3405a35b2b3784cbc94bbeefa0f1445 | Lanfear22/sqlite_emp | /Employees Table.py | 602 | 4.21875 | 4 | import sqlite3
conn = sqlite3.connect('employee.db')
c=conn.cursor()
c.execute("""CREATE TABLE Employees (
EMPLOYEE_ID INTEGER PRIMARY KEY,
FIRST_NAME STR,
LAST_NAME STR,
CURRENT_CONTRACT STR
)""")
c.execute("""INSERT INTO Employees (FIRST_NAME, LAST_NAME, CURRENT_CONTRACT)
VALUES ('Jane', 'Smith', 'OVHD')""")
# Commit table creation and data insertion
conn.commit()
# Select and Print Employees inserted that have the last name 'Smith', to see output
c.execute("SELECT * FROM Employees WHERE LAST_NAME='Smith'")
print(c.fetchall()) |
2cc4ae22ed55c44aaf7fa5521a093ef8e1757af4 | mendoza/hotcake | /Btree.py | 7,964 | 3.625 | 4 | from Node import Node
import bisect
import itertools
import operator
class BTree(object):
BRANCH = LEAF = Node
"""
Orden: como su palabra lo dice, el orden en el que basamos el arbol
"""
def __init__(self, order):
self.order = order
self._root = self._bottom = self.LEAF(self)
#Metodo que nos ayuda a llegar hasta un item en especifico , como la root con sus keys
def _path_to(self, item):
current = self._root
llaves = []
#Este getattr nos consigue que es nuestro atributo si es leaf, children etc
while getattr(current, "children", None):
index = bisect.bisect_left(current.contents, item)
#Realizamos un append a las llavez
llaves.append((current, index))
#tomamos el length para comparar si cumple con la propiedad
if index < len(current.contents) \
and current.contents[index] == item:
return llaves
current = current.children[index]
index = bisect.bisect_left(current.contents, item)
llaves.append((current, index))
present = index < len(current.contents)
present = present and current.contents[index] == item
#Hacemos un return de las llavez una vez verificado que cumple las propiedad
return llaves
#recibe data , y una lista
def _present(self, item, ancestors):
last, index = ancestors[-1]
return index < len(last.contents) and last.contents[index] == item
#Realizamos el insert a nuestro arbol
def insert(self, item):
# assignamos a current el root para revisar si podemos insertarlo ahi
current = self._root
#usamos la lista que trae y la mandamos a nuestro metodo a ordenarlo
ancestors = self._path_to(item)
node, index = ancestors[-1]
#Revisamos si es un hijo
while getattr(node, "children", None):
#al nodo sub la lista de sus hijos , dependiendo su condicion le hacemos split
node = node.children[index]
#como lo muestra el metodo hay un bisect que biseca la lista
index = bisect.bisect_left(node.contents, item)
#a la lista que traemos la hacemos un apend en el nodo , del data
ancestors.append((node, index))
node, index = ancestors.pop()
#finalmente hacemos el incert , mandando como parametro, indice, el data a aguardar y la litsa
node.insert(index, item, ancestors)
#Aqui realizamos nuestra funcion remove que recibe un dato como es logico
def remove(self, item):
#le asignamos nuevamente a curret la root principal
current = self._root
#recorremos la lista haciendo la llamada del meto
ancestors = self._path_to(item)
#Revisamos si existe ene nuestra lista
if self._present(item, ancestors):
#si es asi realizamos el pop de la lista ancestros
node, index = ancestors.pop()
#hace el remove correspondiente
node.remove(index, ancestors)
else:
#En caso de no esncontrarlo , de muestra un mensaje que dice que no encontro lo que deseaba eliminar
raise ValueError("%r not in %s" % (item, self.__class__.__name__))
#Nuestro metodo simplemente revisa si el item que recibe como parametro, esta contemplado en el arbol
def __contains__(self, item):
return self._present(item, self._path_to(item))
#Esta funcion es la que itera entre nuestras llavez y es nuestra recursiva
def __iter__(self):
#Recibe un nodo como parametro
def _recurse(node):
#Chequea si es hijo
if node.children:
#En caso de serlo , llama al item encontrado
for child, item in zip(node.children, node.contents):
for child_item in _recurse(child):
yield child_item
yield item
for child_item in _recurse(node.children[-1]):
yield child_item
else:
#Si no lo encuentra :
for item in node.contents:
yield item
for item in _recurse(self._root):
yield item
#Nuestro metodo realiza las operaciones llamando si es necesario a la recursiva
def __repr__(self):
def recurse(node, accum, depth):
accum.append((" " * depth) + repr(node))
for node in getattr(node, "children", []):
recurse(node, accum, depth + 1)
accum = []
recurse(self._root, accum, 0)
return "\n".join(accum)
#Sobrecarga de metodos propios del lenguaje
#Realiza la carga al arbol
@classmethod
def bulkload(cls, items, order):
tree = object.__new__(cls)
tree.order = order
#llama al meotod paara las hojas que es diferente al de las hijas o branches
leaves = tree._build_bulkloaded_leaves(items)
tree._build_bulkloaded_branches(leaves)
return tree
#A diferencia del metodo anterior este es llamado solo si es en una hoja el trabajo
def _build_bulkloaded_leaves(self, items):
#Definimos cual es nuestro orden minimo
minimum = self.order // 2
leaves, seps = [[]], []
#hace la validacion para saber si es posible que pueda realizar el trabajo , debe ser menor al orden-1
for item in items:
if len(leaves[-1]) < self.order:
leaves[-1].append(item)
else:
seps.append(item)
leaves.append([])
#Revisa la segunda condicion que le dice cual es el orden minimo, la propiedad
if len(leaves[-1]) < minimum and seps:
last_two = leaves[-2] + [seps.pop()] + leaves[-1]
leaves[-2] = last_two[:minimum]
leaves[-1] = last_two[minimum + 1:]
seps.append(last_two[minimum])
#Una vez ya con las validaciones pertinentes realiza el return
return [self.LEAF(self, contents=node) for node in leaves], seps
#Este metodo a diferencia del anterior es para nodos NO hojas y por lo tanto tendra contempladas llamadas recuersivas
def _build_bulkloaded_branches(self, (leaves, seps)):
#De igual manera definimos cual es el orden minimo
minimum = self.order // 2
#aqui guardamos cuantos niveles va sumando nuestro arbol
levels = [leaves]
while len(seps) > self.order + 1:
items, nodes, seps = seps, [[]], []
#Es el mismo proceso de las hojas , eso si identifica que son hojas
for item in items:
if len(nodes[-1]) < self.order:
nodes[-1].append(item)
else:
seps.append(item)
nodes.append([])
#Tambien hace la validacion normal , las de las propiedades que debes estar siempre contempladas
if len(nodes[-1]) < minimum and seps:
last_two = nodes[-2] + [seps.pop()] + nodes[-1]
nodes[-2] = last_two[:minimum]
nodes[-1] = last_two[minimum + 1:]
seps.append(last_two[minimum])
"""
offset: es donde va siendo recorrido nuestro arbol, nos da una posicion dentro de el
"""
offset = 0
#Enumera los nodos y va recorriendo lo que es el arbol para darle un valor
for i, node in enumerate(nodes):
children = levels[-1][offset:offset + len(node) + 1]
nodes[i] = self.BRANCH(self, contents=node, children=children)
offset += len(node) + 1
levels.append(nodes)
#por ultimo revisa el nodo NO hoja y manda sus hijos y sus niveles contemplados como parametros
self._root = self.BRANCH(self, contents=seps, children=levels[-1])
|
2353c72d946d288d288eaa9806cb106df09e4649 | jasonpea/DAD-PROJECT | /test/prob 1 bitch.py | 205 | 3.765625 | 4 | # NUMBER 1
s = int(input("please input number: "))
m = int(input("please input number: "))
l = int(input("please input number: "))
if 1 * s + 2 * m + 3 * l > 10:
print("Happy")
else:
print("Sad")
|
9c46d2ba4151ca3f906f486ba9091809f255fe8c | apag101/is210_lesson_06 | /task_01.py | 709 | 4.34375 | 4 | #!usr/bin/env python#
# -*- coding: utf-8 -*-
"""Even and Odds Function."""
import data
def evens_and_odds(numbers, show_evens = True):
"""Returns even or odd numbers.
Args:
numbers(numeric).
show_even(boolean, Default = True).
Returns:
Number: Returns a new list object.
Examples:
>>> evens_and_odds([1, 2, 3, 4], show_evens=False)
[1, 3]
>>> evens_and_odds([1, 2, 3, 4], show_evens=True)
[2, 4]
"""
enum = []
onum = []
num = []
for x in numbers:
if x % 2 == 0:
enum.append(x)
else:
onum.append(x)
if show_evens:
num = enum
else:
num = onum
return num
|
244d0f7b41acc7c25502ff38ce683259a784ecc5 | young8179/pythonClass | /python102/7-number-positive.py | 212 | 3.78125 | 4 | ## positive number
numbers = [10, 20, 30, -99, 50, -12, 87, 90, 1, 101, 9182691, 12, -11, 42]
positive_num = []
for number in numbers:
if number > 0:
positive_num.append(number)
print(positive_num) |
169e1942a7d2b96e7eccadb5aabf2c40ed7bfca7 | acarter881/exercismExercises | /grains/grains.py | 210 | 3.734375 | 4 | def square(number):
if number < 1 or number > 64: raise ValueError('Please enter a number greater than or equal to 1.')
return 2 ** (number - 1)
def total():
return sum((2 ** i for i in range(64))) |
134331caef5f33664b7147322ef2d39d9c349e63 | somanie1/Practicing-Python | /datetime.py | 3,071 | 4.21875 | 4 | """
days in month
"""
def days_in_month(year, month):
"""
days in month
"""
import datetime
if ((year % 4) == 0 and ((year % 100) != 0 or (year % 400) == 0)) and (month == 2):
return 29
elif (month == 2):
return 28
elif (month == 4) or (month == 6) or (month == 9) or (month == 11):
return 30
else:
return 31
date1 = datetime.date(year, month, 1)
date2 = datetime.date(year, month+1, 1)
delta = (date2 - date1)
return delta.days
print(days_in_month(2010, 6))
"""
is_valid
"""
def is_valid_date(year, month, day):
"""
is valid
"""
import datetime
"""
Inputs:
year - an integer representing the year
month - an integer representing the month
day - an integer representing the day
Returns:
True if year-month-day is a valid date and
False otherwise
"""
if (datetime.MINYEAR <= year <= datetime.MAXYEAR) and (1 <= month <= 12) and (1 <= day <= days_in_month(year, month)):
return True
else:
return False
print(is_valid_date(1998, 12, 2))
def days_between(year1, month1, day1, year2, month2, day2):
"""
Inputs:
year1 - an integer representing the year of the first date
month1 - an integer representing the month of the first date
day1 - an integer representing the day of the first date
year2 - an integer representing the year of the second date
month2 - an integer representing the month of the second date
day2 - an integer representing the day of the second date
Returns:
The number of days from the first date to the second date.
Returns 0 if either date is invalid or the second date is
before the first date.
"""
# date_first = is_valid_date(year1, month1, day1)
# date_second = is_valid_date(year2, month2, day2)
import datetime
if not(is_valid_date(year1, month1, day1)) and not(is_valid_date(year2, month2, day2)):
return 0
elif (year2, month2, day2) < (year1, month1, day1):
return 0
else:
return (datetime.date(year2, month2, day2) - datetime.date(year1, month1, day1)).days
print(days_between(2026, 1, 3, 2025, 6, 3))
def age_in_days(year, month, day):
"""
Inputs:
year - an integer representing the birthday year
month - an integer representing the birthday month
day - an integer representing the birthday day
Returns:
The age of a person with the input birthday as of today.
Returns 0 if the input date is invalid of if the input
date is in the future.
"""
import datetime
today = datetime.date.today()
birthday = datetime.date(year, month, day)
if (birthday != is_valid_date(year, month, day) and (birthday > today)):
return 0
else:
# age = today.year - birthday.year
age = today - birthday
return age.days
print(age_in_days(2019, 7, 5))
|
46981ad4de6e8a408302f80921a8290999cc512b | markstali/atividade-terminal-git | /code13.05.py | 2,854 | 4.25 | 4 | #01 - Dada a lista L = [5, 7, 2, 9, 4, 1, 3], escreva um programa que imprima as seguintes informações:
# a) tamanho da lista.
# b) maior valor da lista.
# c) menor valor da lista.
# d) soma de todos os elementos da lista.
# e) lista em ordem crescente.
# f) lista em ordem decrescente.
""" L = [5, 7, 2, 9, 4, 1, 3]
print('tamanho da lista',len(L))
print('maior valor da lista.',max(L))
print('menor valor da lista.', min(L))
print('soma de todos os elementos da lista', sum(L))
L.sort()
print('lista em ordem crescente.', L)
L.reverse()
print('lista em ordem decrescente.',L)
"""
#02 - Utilizando listas, faça um programa que faça 5 perguntas para uma pessoa sobre um crime. As perguntas são:
# "Telefonou para a vítima?"
# "Esteve no local do crime?"
# "Mora perto da vítima?"
# "Devia para a vítima?"
# "Já trabalhou com a vítima?"
# O programa deve no final emitir uma classificação sobre a participação da pessoa no crime.
# Se a pessoa responder positivamente a 2 questões ela deve ser classificada como "Suspeita",
# entre 3 e 4 como "Cúmplice" e 5 como "Assassino". Caso contrário, ele será classificado como "Inocente".
""" quest = []
print("Responda 1 para Sim e 0 para Não\n")
quest.append(int(input("Telefonou para a vítima?[1/0]: ")))
quest.append(int(input("Esteve no local do crime?[1/0]: ")))
quest.append(int(input("Mora perto da vítima?[1/0]: ")))
quest.append(int(input("Devia para a vítima?[1/0]: ")))
quest.append(int(input("Já trabalhou com a vítima?[1/0]: ")))
if sum(quest) == 2:
print("Suspeito")
elif sum(quest) == 3 or sum(quest) == 4:
print("Cumplice")
elif sum(quest) == 5:
print("Assassino")
else:
print("Inocente") """
# 1. Crie um código em Python que pede qual tabuada o usuário quer ver, em
# seguida imprima essa tabuada.
""" num = int(input("Qual tabuada deseja imprimir?: "))
for i in range(1,11):
print(f'{num} x {i} = ',num*i) """
# 2. Elaborar um programa para imprimir os números de 1 (inclusive) até 10
# (inclusive) em ordem decrescente.
""" for i in range(1,11):
print(i, end = ' ')
for C in range(10, 0, -1):
print(C, end = ' ') """
# 3. Faça um programa que leia o estado civil de 15 pessoas (Solteiro / Casado) e
# mostre ao final a quantidade de pessoas de cada estado civil.
""" estado_civil = []
for i in range(1, 16):
estado_civil.append(input('Qual seu estado civil?(Solteiro[s] / Casado[c]): \n'))
print('Solteiros = ',estado_civil.count('s'))
print('Casados = ',estado_civil.count('c')) """
# 4. Faça um algoritmo que imprima 10 vezes a frase: “Go Blue”.
""" for i in range(1,11):
print('Go Blue', end = ' ') """
# 5. Faça um programa que mostre os valores numéricos inteiros ímpares situados
# na faixa de 0 a 20.
""" for i in range(1, 21, 2):
print(i, end = ' ') """
|
735400d97ebbda97e93e60d66aff8d7545572418 | RafaelMuniz94/AjudandoBruninho | /Questao7.py | 924 | 4.03125 | 4 | # 7-Faça um programa que receba a temperatura média de cada mês do ano e armazene-as em uma lista.
# Após isto, calcule a média anual das temperaturas e mostre todas as temperaturas acima da média anual, e em que mês elas ocorreram
# (mostrar o mês por extenso: 1 – janeiro, 2 – fevereiro, . . .).
temperatura = []
meses = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho',
'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro']
media = 0
acimaMedia = {}
for i in range(len(meses)):
temperatura.append(
float(input('Informe a Temperatura media de ' + meses[i] + ':\n')))
media += temperatura[i]
media = media/len(meses)
for i in range(len(meses)):
if(temperatura[i] > media):
acimaMedia.update({meses[i]: temperatura[i]})
print('Media das temperaturas : Anual -> ' + str(media))
print('Meses com temperaturas acima da media: ' + str(acimaMedia))
|
ebc85a13de078710c7b6b15bda0bd646bf9887cd | Villager-B/Default-Algorithm-Python | /Radix/decimal_to_binary.py | 309 | 3.796875 | 4 | def main():
decimal = int(input("decimal : "))
q_list = []
while True:
r = decimal // 2
q = decimal % 2
q_list.append(str(q))
if r == 0:
break
decimal = r
print("binary : ", "".join(q_list[::-1]))
if __name__ == '__main__':
main()
|
ff92e0d54569282b11d916928c4770763f9e44ea | lpchambers/aoc19 | /day06/p1.py | 1,222 | 3.53125 | 4 | class Space:
def __init__(self, name):
self.name = name
self.children = []
self.parent = None
def set_parent(self, parent):
self.parent = parent
self.parent.children.append(self)
def cost(self):
if self.name == "COM":
return 0
if self.parent is None:
print(self.name)
return self.parent.cost() + 1
def chain(self):
if self.name == "COM":
return ["COM"]
return [self.name] + self.parent.chain()
def chainstr(self):
if self.name == "COM":
return "COM"
return self.name + " -> " + self.parent.chain()
with open('input') as f:
lines = f.readlines()
orbits = {} # Name to Space
lines_parse = [line.strip().split(')') for line in lines]
for parent, child in lines_parse:
if parent in orbits:
po = orbits[parent]
else:
po = Space(parent)
orbits[parent] = po
if child in orbits:
co = orbits[child]
else:
co = Space(child)
orbits[child] = co
co.set_parent(po)
print("P1:", sum(space.cost() for space in orbits.values()))
uchain = orbits["YOU"].chain()
schain = orbits["SAN"].chain()
for par in uchain:
if par in schain:
print("First common parent:", par)
break
print("P2:", orbits["YOU"].cost() + orbits["SAN"].cost() - (2*orbits[par].cost()) - 2)
|
ff0ca3e93238f9aa5297d0466e46ddead96a76b3 | jimjshields/python_learning | /think_python/other/most_common.py | 2,336 | 4.28125 | 4 | ### modules ###
import string # module that has string operations below
### functions ###
def process_file(filename): # function to build dictionary of words and frequencies for a file
hist = dict() # hist is the empty dictionary
fp = open(filename) # fp is the opened file
for line in fp: # running through each line in the opened file
process_line(line, hist) # process that line using the process_line function
return hist # returning the dictionary
def process_line(line, hist): # function to take a single line in a file, strip punctuation, and separate ('split') into strings
line = line.replace('-', ' ') # method to replace hyphens with spaces
for word in line.split(): # going through each separate string in the line, using the split method to separate the strings
word = word.strip(string.punctuation + string.whitespace) # strip method removes punctuation and whitespace
word = word.lower() # converts each word to lowercase
hist[word] = hist.get(word, 0) + 1 # if the word is in the dictionary, increase the count by one; if not, add it with a value of 0 (then add 1)
def most_common(hist): # function to build a list of tuples - the words and frequencies - and sorting in desc order
t = [] # empty list
for key, value in hist.items(): # for each key and value in the items of the dictionary
t.append((value, key)) # add the value, then the key, to the list (in a tuple - so they can be sorted)
t.sort(reverse=True) # sort desc
return t # return the list of sorted items
def print_most_common(hist, num=10): # function to print the most common num (if provided, else 10) words
t = most_common(hist) # setting t (separate from above t) equal to the above function run on the processed file
print 'The most common words are:' # a string
for freq, word in t[:num]: # going through the top num most frequent words
print word, '\t', freq # printing the word, a tab, and the frequency
### setting variables ###
hist1 = process_file('exposures.txt') # process this file, set it equal to hist (separate from above hist)
hist2 = process_file('text.txt')
### calling functions ###
print_most_common(hist1, 10)
print_most_common(hist2, 10) |
f5b85a5ee8bbdb010056af893f548367bf74e733 | DevKheder/PythonCrashCourse | /introducing-lists/3-1 names.py | 199 | 4.3125 | 4 | # making a list of friends' names
friends = ["kheder", "modar", "sandy", "amani"]
# now printing each name indvidually
print(friends[0].upper())
print(friends[1])
print(friends[2])
print(friends[3])
|
346aed3c0e2893acd565f89fe767cc06604f8fbb | sukant16/Leeter | /medium/remove_duplicates_from_sorted_array.py | 1,237 | 3.75 | 4 | '''
Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Approach:
1. Use Deque
2. iterator over the length, check if first element is lesser than the second,
if yes:
push it to the right
if same:
pop it from deque
continue till i < len
'''
from collections import deque
from typing import List
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
nums = deque(nums)
n = len(nums)
i = 0
while i < n:
if nums[0] == nums[1]:
nums.popleft()
else:
nums.append(nums.popleft())
i += 1
print(nums)
return len(nums)
def list_sol(self, nums):
n = len(nums)
current = 0
ix = 1
for i in range(1, n-1):
if nums[ix] != nums[i+1]:
nums[ix], nums[i+1] = nums[i+1], nums[i]
ix
if __name__ == '__main__':
sol = Solution()
print(sol.removeDuplicates([0,0,1,1,1,2,2,3,3,4]))
print(sol.removeDuplicates([1,1,2])) |
d51e08d55057c6816e1dabe9a3230cf13c848dc6 | StuartCowley/PythonExercises | /areacalculator.py | 595 | 4.28125 | 4 | # This program is for calculating the area of a given shape inputted by the user
print("The calculator is running")
name = input("Enter C for Circle or T for Triangle: ")
option = name
if option in "Cc":
radius = float(input("Input radius: "))
area = radius**2 * 3.141592
print("Area of circle is %.2f " % area)
elif option in "Tt":
base = float(input("Input base length: "))
height = float(input("Input height: "))
area = base * height * 0.5
print("Area of triangle is %.2f " % area)
else:
print("You have entered an invalid value")
print("Program is exiting")
|
b39dd060dfef90dbb5a2168236ac04fbe92528aa | smart8612/KMU_Python | /algorithm/Doomsday_Algorithm.py | 2,773 | 3.828125 | 4 | def isLeapYear(year):
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return True
else:
return False
def closer(target1, target2, value):
return target1 if abs(target1 - value) < abs(target2 - value) else target2
def closerSearch(sorted_ary, value):
try:
maxidx = len(sorted_ary) - 1
minidx = 0
while minidx <= maxidx:
mididx = int((maxidx + minidx) / 2)
if sorted_ary[mididx] > value:
maxidx = mididx - 1
elif sorted_ary[minidx] < value:
minidx = mididx + 1
elif sorted_ary[mididx] == value:
return sorted_ary[mididx]
return closer(sorted_ary[minidx], sorted_ary[maxidx], value)
except IndexError:
return sorted_ary[minidx - 1]
def whatDay(year, month, day):
conwaysList = [0, 6, 11.5, 17, 23, 28, 34, 39.5, 45, 51, 56, 62, 67.5, 73, 79, 84, 90, 95.5]
Days_At_Month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
DoomsDay_At_Month = [3, 28, 7, 4, 9, 6, 11, 8, 5, 10, 7, 12]
Day_At_Week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
Year = int(year)
Month = int(month)
Day = int(day)
if 1900 <= Year < 2000:
if isLeapYear(Year):
Days_At_Month[1] = 29
DoomsDay_At_Month[1] = 29
DoomsDay_At_Month[0] = 4
# Setting day at month if the year is leap Year
conwaysList = list(map(lambda x: x + 1900, conwaysList))
initYear = closerSearch(conwaysList, Year)
if type(initYear) == int:
doomsWeekDayIdx = 2 + (Year - initYear)
if isLeapYear(Year):
if initYear < Year:
doomsWeekDayIdx += 1
else:
if initYear < Year:
for i in range(initYear, Year):
if isLeapYear(i):
doomsWeekDayIdx += 1
elif initYear > Year:
for i in range(Year, initYear):
if isLeapYear(i):
doomsWeekDayIdx -= 1
if isLeapYear(initYear):
doomsWeekDayIdx -= 1
elif type(initYear) == float:
if int(initYear) == Year:
doomsWeekDayIdx = 1
elif initYear < Year:
doomsWeekDayIdx = 3 + int(Year - initYear)
elif initYear > Year:
doomsWeekDayIdx = 1 + int(Year - initYear)
# ----------------------------------------------------------
doomsMonthDay = DoomsDay_At_Month[Month - 1]
dayeval = Day - doomsMonthDay
answer = (doomsWeekDayIdx + dayeval) % 7
return answer
|
d0c7ed468562a89cf06db007ce851316331cf613 | fredcodee/get_emails | /scrapy2.py | 1,752 | 3.734375 | 4 | '''a simple python script to scrape emails from any website and other website linked to then prints out on terminal emails found and website it was gotten from
and also option to download and save as csv file '''
import requests
from bs4 import BeautifulSoup
import re
import csv
from time import sleep
print("email scraper by fredcode\nc'2019")
url = input(" type a website:")
mails = []
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
links = [n.get('href') for n in soup.find_all('a')]
links.append(url)
def get_emails(l):
print("pls wait.... running code")
for _link in l:
if(_link.startswith("http") or _link.startswith("www")):
data = requests.get(_link)
_emails = re.findall(r'([\d\w\.]+@[\d\w\.\-]+\.\w+)', data.text)
if _emails: # removing duplicates
_emails = list(dict.fromkeys(_emails))
mails.append((_emails, _link))
get_emails(links) # run code to print out
if len(mails) == 0:
print("no emails found")
sleep(5)
exit()
print(mails)
#extra feature to save to a csv file
ask_user = input("Do you want to save results to a csv file?\nReply with yes or no: ")
u_data=ask_user.lower()
if u_data == "yes":
print("saving you file ......")
name = url.split("//")
csv_file = open(name[-1].replace(".com/","ES"), 'w')
csv_writer = csv.writer(csv_file)
csv_writer.writerow(["Emails","Link"])
for i in mails:
emails= ",".join(i[0])
link = i[-1]
csv_writer.writerow([emails,link])
print("file downloaded")
csv_file.close()
else:
exit()
'''coded by fredcode - github[fredcodee]'''
|
d452255fc7008ca6274747c8ecae7d2779908a60 | Timothy-py/Python-Design-Patterns | /structural_design_patterns/flyweight_pattern.py | 2,907 | 3.53125 | 4 | import json
class Flyweight:
"""
The Flyweight stores a common portion of the state(intrinsic) that belongs to
multiple real business entities. The Flyweight accepts the rest of the state(extrinsic)
via its method parameters.
"""
def __init__(self, intrinsic=''):
self._intrinsic = intrinsic
def operation(self, extrinsic=''):
intrinsic = json.dumps(self._intrinsic)
extrinsic = json.dumps(extrinsic)
print(f"Flyweight: Displaying shared ({intrinsic}) and unique ({extrinsic}) state.", end='')
class FlyweightFactory:
"""
The Flyweight Factory creates and manages the Flyweight objects. It ensures that flyweights
are shared correctly. When the client requests a flyweight, that factory either returns
an existing instance or creates a new one, if it doesn't exist yet.
"""
_flyweights = dict()
def __init__(self, initial_flyweight=[]):
for state in initial_flyweight:
self._flyweights[self.get_key(state)] = Flyweight(state)
def get_key(self, state=dict()):
"""
returns a Flyweight's string hash for a given state.
"""
return "_".join(sorted(state))
def get_flyweight(self, shared_state=dict()):
"""
returns an existing Flyweight with a given state or creates a new one.
"""
key = self.get_key(shared_state)
if not self._flyweights.get(key):
print("FlyweightFactory: Can't find a flyweight, creating new one.")
self._flyweights[key] = Flyweight(shared_state)
else:
print("FlyweightFactory: Reusing existing flyweight.")
return self._flyweights[key]
def list_flyweights(self):
count = len(self._flyweights)
print(f"FlyweightFactory: I have {count} flyweights:")
print("\n".join(map(str, self._flyweights.keys())), end="")
def add_car_to_police_database(factory=FlyweightFactory, plates="", owner="", brand="", model="", color=""):
print("\n\nClient: Adding a car to database.")
flyweight = factory.get_flyweight([brand, model, color])
# The client code either stores or calculates extrinsic state and passes it to the flyweight's methods.
flyweight.operation([plates, owner])
if __name__ == '__main__':
"""
The client code usually creates a bunch of pre-populated flyweights in
the initialization stage of the population.
"""
factory = FlyweightFactory([
["Chevrolet", "Camero2018", 'Pink'],
['Mercedes Benz', 'C300', 'black'],
["Mercedes Benz", "C500", 'red'],
['BMW', 'M5', 'red'],
['BMW', 'X6', 'white'],
])
factory.list_flyweights()
add_car_to_police_database(factory, "CL234IR", 'Timothy', 'BMW', 'M5', 'red')
add_car_to_police_database(factory, "CL234IR", 'Timothy', 'BMW', 'X1', 'red')
print('\n')
factory.list_flyweights()
|
a5b8eda8d550a03319eb9202ff2885270ced78ac | muttakin-ahmed/leetcode | /PascalsTriangle.py | 1,183 | 3.96875 | 4 | def generate(self, numRows: int) -> List[List[int]]:
# The outer list
arr_out = []
for i in range(1, numRows+1):
# The inner list, initialized with 0
arr_in = [0] * i
# putting 1 to the either ends of this inner list
arr_in[0] = 1
arr_in[-1] = 1
# Extra calculation starts when the length of inner list > 2
if i > 2:
# we need the last inner list for this operation
prev = arr_out[-1]
# The operation will only run on the inner items of this list
for j in range(1, len(arr_in)-1):
# If the element is 0, we have to act
if arr_in[j] == 0:
arr_in[j] = prev[j-1] + prev[j]
# Finally, append the inner list to the outer list
arr_out.append(arr_in)
return arr_out
# Runtime complexity: O(numRows^2), as it is iterating a list of size numRows in a nested 2 layer loop.
# Space Complexity: Same as runtime, as the function is creating and returning a 2D list.
|
0ad0637af3d0dd74d2e942beb4ddf726f40a438a | jamestaylormath/MachineLearning | /Python/logistic_regression.py | 3,901 | 4.15625 | 4 | import numpy as np # linear algebra
import pandas as pd
import math
#Sticks a column of ones to the front of X
def insert_ones(X):
return np.c_[np.ones(X.shape[0]), X]
#Returns f_beta(X) (discussed in "Logistic Regression Explained" in Math folder)
def f(beta, X):
return 1/(1+np.exp(-np.sum(X*beta, axis=1)))
#Sets first component of vector to 0. Useful in calculating the gradient of the regularized loglikelihood
def first_component_to_zero(vector):
c = np.ones(vector.shape[0])
c[0] = 0
return vector*c
#loglikelihood function with the L2 penalty included
def loglikelihood(beta, X, Y, reg_lambda):
return (Y*np.log(f(beta,X)) + (1-Y)*np.log(1-f(beta,X))).sum() - reg_lambda*(beta**2)[1:].sum()
#Used for diagnostic purposes. Helps user view what's going on during the fitting process
def display_gradascent_info(step, learn, grad, beta, beta_change, likelihood, beta_new, likelihood_new):
print("step:", step)
print("learning rate:", learn)
print("gradient:", grad)
print("learn*grad:", learn*grad)
print("beta:", beta)
print("beta_change:", beta_change)
print("likelihood:", likelihood)
print("new beta:", beta_new)
print("new likelihood:", likelihood_new)
print('\n')
class LogisticRegression():
"""Logistic regression model whose coefficients are approximated using gradient ascent.
Parameters:
reg_lambda (float):
L2 regularization parameter (default is no L2 regularization).
learn (float):
Gradient ascent's initial learning rate.
precision (float):
Governs how much our coefficient (beta) estimates need to have stabilized before we
end the gradient ascent.
max_iters (int):
Maximum number of gradient ascent steps to perform before stopping.
"""
def __init__(self, reg_lambda = 0, learn = 0.5, precision = 0.001, max_iters = 1000):
self.reg_lambda = reg_lambda
self.learn = learn
self.precision = precision
self.max_iters = max_iters
self.beta = None
def fit(self, X, Y):
learn = self.learn #set learn = initial learning rate
beta_change = 1 #Initial value; just needs to be > precision
X = insert_ones(X)
self.beta = np.ones(X.shape[1]) #initial value of coefficient vector
likelihood = loglikelihood(self.beta, X, Y, self.reg_lambda) #Initial value of loglikelihood
can_stop = False #Can't stop gradient ascent yet, we've barely started!
step = 0
while step < self.max_iters and can_stop == False:
grad = (Y - f(self.beta,X)).T @ X - 2*self.reg_lambda*first_component_to_zero(self.beta)
beta_new = self.beta + learn*grad
beta_change = np.abs(beta_new - self.beta).max()
likelihood_new = loglikelihood(beta_new,X,Y,self.reg_lambda)
#display_gradascent_info(step, learn, grad, self.beta, beta_change,
# likelihood, beta_new, likelihood_new)
if (beta_change > self.precision) or (likelihood_new <= likelihood):
#beta hasn't stabilized or latest change to beta was a bad one
can_stop = False
else:
can_stop = True
if (likelihood_new > likelihood) or ((not math.isfinite(likelihood)) and math.isfinite(likelihood_new)):
#latest step was good...update beta, increase learning rate, and advance
learn *= 1.5
self.beta = beta_new
likelihood = likelihood_new
step += 1
else:
#latest step no bueno. Reduce learning rate and don't update beta
learn /= 2
def probabilities(self,X):
return f(self.beta, insert_ones(X))
|
100bf4fda4a528cb3129506398b110e8c934bca7 | vad2der/Python_examples | /brakets_validating.py | 1,319 | 3.859375 | 4 | """
Tiny app to check if a string has properly closed brakets or not.
"""
sample11 = "({[]})"
sample12 = "({}[])"
sample13 = "({})[]"
sample14 = "(){}[]"
sample21 = "({}[)]"
sample22 = "({}([]"
brakets = [["(",")"],["{","}"],["[","]"]]
def determine_opening_braket_type(opening_braket):
"""
returns closing braket of the same type as starting braket from input
"""
for b in brakets:
if opening_braket == b[0]:
return b[1]
def determine_closing_braket_type(closing_braket):
"""
returns closing braket of the same type as starting braket from input
"""
for b in brakets:
if closing_braket == b[1]:
return b[0]
def get_blocks(test):
queue = []
for ind in range(len(test)):
if determine_opening_braket_type(test[ind]) is not None:
queue.append(test[ind])
elif determine_closing_braket_type(test[ind]) is not None and determine_closing_braket_type(test[ind]) == queue[-1]:
queue.remove(determine_closing_braket_type(test[ind]))
return queue
def check(test):
if len(get_blocks(test)) == 0:
return "Valid"
else:
return "Invalid"
print (check(sample11))
print (check(sample12))
print (check(sample13))
print (check(sample14))
print (check(sample21)) |
7de765906585d25dfb1d5895e5931993c18d4f31 | marciooferraz/TestesPython | /TestesPython/TestesPython.py | 590 | 4.40625 | 4 | #Testes com variaveis e Inputs
#nome = input("Nome: ")
#print(nome.upper())
#Testes com metodos nos prints
mensagem = "o grande teste"
print(mensagem.find("t")) #Conta o número de caracteres até o valor parametizado
print(mensagem.count('a')) #Conta quantos caracteres = ao valor parametizado existem na string
print(mensagem.replace("grande", "pequeno")) #Substitui uma parte da string (1° parametro) pelo valor do 2° parametro
print(mensagem.capitalize()) #Alera a 1° letra da string para maiuscula
print(mensagem.upper()) #Altera os caracteres da string para maiusculos
|
9b585bf8796a14a973b4445971c2cf6ed0c2f3db | FaridWaid/sms2-praktikum-strukturdata | /Modul 5/2.py | 1,843 | 3.78125 | 4 | def binsearch(listData,key):
for a in range (1,len(listData)):
x = listData[a]
b=a-1
while b>=0 and x<=listData[b]:
listData[b+1]=listData[b]
b-=1
listData[b+1]=x
print(listData)
found=False
first= 0
last=len(listData)-1
more=[]
tengah = int
u = 0
while first<=last and not (found):
mid = (first+last)//2
if listData[mid]==key:
more.append(mid)
found = True
tengah = mid
elif key>listData[mid]:
first=mid+1
elif key<listData[mid]:
last=mid-1
u +=1
if found:
count = 1
check = True
while check == True:
if (tengah + count) <= (len(listData)-1):
if listData[tengah] == listData[tengah + count] and listData[tengah] == listData[tengah - count] :
more.append(tengah + count)
more.append(tengah - count)
count += 1
elif listData[tengah] == listData[tengah + count] and listData[tengah] != listData[tengah - count] :
more.append(tengah + count)
count += 1
elif listData[tengah] != listData[tengah + count] and listData[tengah] == listData[tengah - count] :
more.append(tengah - count)
count += 1
else:
check = False
else:
check = False
print ("Posisi Data = ",sorted(more))
print ("Jumlah Iterasi = ",count+u)
else:
print ("Posisi Data = Data tidak ada")
print ("Jumlah Iterasi = ",count+u)
a=[12,2,4,5,6,8,23,54,21,54,67,54,25,78,90,54,65,65,12,65,78,54,54,54]
binsearch(a,12)
|
a143f24a8eb40ad3858c87595ec7784ebf09ce31 | trowa88/python_machine_learning | /src/books/ch6/ngram-test.py | 679 | 3.578125 | 4 | def n_gram(s, num):
res = []
s_len = len(s) - num + 1
for i in range(s_len):
ss = s[i:i+num]
res.append(ss)
return res
def diff_n_gram(sa, sb, num):
a = n_gram(sa, num)
b = n_gram(sb, num)
r = []
cnt = 0
for i in a:
for j in b:
if i == j:
cnt += 1
r.append(i)
return cnt / len(a), r
a_t = '오늘 강남에서 맛있는 스파게티를 먹었다.'
b_t = '강남에서 먹었던 오늘의 스파게티는 맛있었다.'
# 2-gram
r2, word2 = diff_n_gram(a_t, b_t, 2)
print('2-gram:', r2, word2)
# 3-gram
r3, word3 = diff_n_gram(a_t, b_t, 3)
print('3-gram:', r3, word3)
|
a64b32ea2aa6df03cd2c6c34856a40229b27bbda | haotwo/pythonS3 | /day22/input_output.py | 263 | 3.734375 | 4 | # -*- coding:utf-8 -*-
#作者 :Lyle.Li
#时间 :2019/10/19 9:52
#文件 :input_output.py
# s ='Hello,Runoob'
# print(str(s))
#
# print(str(1/7))
for x in range(1,11):
print(repr(x).rjust(2),repr(x*x).rjust(3),end='')
print(repr(x*x*x).rjust(4))
|
89d635dee7df164288ed7035e04348e1da0200da | zioul123/VocalPitchModulator | /Utils.py | 10,430 | 4.21875 | 4 | import numpy as np
import librosa
import librosa.display
import matplotlib.pyplot as plt
from enum import IntEnum
#################################################################
# 3D to flattened array utilities
#################################################################
def flatten_3d_array(arr, i_lim, j_lim, k_lim):
"""Takes a 3d array, and returns a 1d array.
Args:
arr (list): A 3d array (i_lim, j_lim, k_lim)
i_lim (int): The length of the first dimension of arr
j_lim (int): The length of the second dimension of arr
k_lim (int): The length of the third dimension of arr
Returns:
A 1d list of length i_lim * j_lim * k_lim
"""
return [ arr[i][j][k]
for i in range(i_lim)
for j in range(j_lim)
for k in range(k_lim) ]
def flat_3d_array_idx(i, j, k, i_lim, j_lim, k_lim):
"""Used to get the index of flattened arrays as a 3d arrays.
This is used to access arrays that have been flattened
by flatten_3d_array.
Args:
i/j/k (int): The indices to access the array as arr[i][j][k]
i_lim (int): The length of the first dimension of arr
j_lim (int): The length of the second dimension of arr
k_lim (int): The length of the third dimension of arr
Returns:
An int representing the array index of the flattened array
that functions as the accessor to the index [i][j][k]
in the original 3d array.
"""
return i * j_lim * k_lim + j * k_lim + k
def flat_2d_array_idx(i, j, i_lim, j_lim):
"""Analogous to flat_array_idx, except for 2d arrays.
Args and Return:
See above.
"""
return i * j_lim + j
def nd_array_idx(idx, i_lim, j_lim, k_lim):
"""Used to get the 3d index from a flat array index.
This is the inverse of flat_array_idx.
Args:
idx (int): The index to access the flat array.
i_lim (int): The length of the first dimension of arr
j_lim (int): The length of the second dimension of arr
k_lim (int): The length of the third dimension of arr
Returns:
Three ints representing the i, j, k index to access the
original 3d array.
"""
return int(idx / (j_lim * k_lim)), \
int((idx % (j_lim * k_lim)) / k_lim), \
int(idx % (k_lim))
#################################################################
# Graphing utilities
#################################################################
def plot_ffts_spectrogram(ffts, sample_rate, file_name=None):
"""This function plots a spectrogram generated by stft
Args:
ffts (np.ndarray): An matrix of ffts, where the ffts[f, t]
provides the complex value of the fft at frequency bin f
at frame t.
sample_rate (int): The sample rate at which the stft was taken.
file_name (str): To be put into the title of the plot.
"""
plt.figure(figsize=(10, 4))
librosa.display.specshow(librosa.amplitude_to_db(np.abs(ffts), ref=np.max),
y_axis='linear', x_axis='time', sr=sample_rate)
plt.title('Power spectrogram{}'.format(
"" if file_name is None else " of {}".format(file_name)))
plt.colorbar(format='%+2.0f dB')
plt.tight_layout()
plt.show()
def plot_mel_spectrogram(mel_freq_spec, sample_rate, file_name=None):
"""This function plots a mel spectrogram generated by ffts_to_mel
Args:
mel_freq_spec (np.ndarray): An matrix of mel spectra, where the
mel_freq_spec[m, t] provides the value of the mel bin m at frame t.
sample_rate (int): The sample rate at which the stft was taken.
file_name (str): To be put into the title of the plot.
"""
plt.figure(figsize=(10, 4))
S_dB = librosa.power_to_db(mel_freq_spec, ref=np.max)
librosa.display.specshow(S_dB, x_axis='time', y_axis='mel', sr=sample_rate, fmax=sample_rate/2.0)
plt.colorbar(format='%+2.0f dB')
plt.title('Mel-frequency spectrogram of {}'.format(file_name))
plt.tight_layout()
plt.show()
def plot_mfcc(mfccs, sample_rate, file_name=None):
"""This function plots a mfcc generated by ffts_to_mel
Args:
mfccs (np.ndarray): An matrix of MFCC features, where
mfccs[m, t] provides the values of the MFCC feature m at frame t.
sample_rate (int): The sample rate at which the stft was taken.
file_name (str): To be put into the title of the plot.
"""
plt.figure(figsize=(10,4))
librosa.display.specshow(mfccs, x_axis='time')
plt.colorbar()
plt.title('MFCC')
plt.tight_layout()
plt.show()
def plot_loss_graph(loss_arr, val_loss_arr=None, acc_arr=None, val_acc_arr=None):
"""This function is used to plot the loss graph of the fit function.
Args:
loss_arr (list): An array of floats for training loss at each epoch.
val_loss_arr (list): An array of floats for validation loss at each epoch.
acc_arr (list): An array of floats for training accuracy at each epoch.
val_acc_arr (list): An array of floats for validation acc at each epoch.
"""
plt.figure(figsize=(15, 10))
plt.plot(loss_arr, 'r-', label='loss')
if val_loss_arr != None:
plt.plot(val_loss_arr, 'm-', label='val loss')
if acc_arr != None:
plt.plot(acc_arr, 'b-', label='train accuracy')
if val_acc_arr != None:
plt.plot(val_acc_arr, 'g-', label='val accuracy')
plt.title("Loss plot")
plt.xlabel("Epoch")
plt.legend(loc='best')
plt.show()
print('Training Loss before/after: {}, {}'
.format(loss_arr[0], loss_arr[-1]))
if val_loss_arr != None:
print('Validation Loss before/after: {}, {}'
.format(val_loss_arr[0], val_loss_arr[-1]))
if acc_arr != None:
print('Training accuracy before/after: {}, {}'
.format(acc_arr[0], acc_arr[-1]))
if val_acc_arr != None:
print('Validation accuracy before/after: {}, {}'
.format(val_acc_arr[0], val_acc_arr[-1]))
#################################################################
# Normalization utilities
#################################################################
class NormMode(IntEnum):
REAL_TO_ZERO_ONE = 0
NONNEG_TO_ZERO_ONE = 1
REAL_TO_NEG_ONE_ONE = 2
NEG_ONE_ONE_TO_ZERO_ONE = 3
class DenormMode(IntEnum):
ZERO_ONE_TO_REAL = 0
ZERO_ONE_TO_NONNEG = 1
NEG_ONE_ONE_TO_REAL = 2
ZERO_ONE_TO_NEG_ONE_ONE = 3
def normalize_rows(mat, norm_mode):
"""This function normalizes each row of mat, and returns the normalizing factors.
We normalize along the rows, so e.g.
[ [1, -5, 3 ], [ [0.2, -1, 0.6 ], [ 5,
[3, -3, 1 ], --> [1, -1, 0.333 ], and 3,
[-2, 4, 3 ] ] [-0.5, 1, .75 ] ] 4 ]
Example:
To retrieve the original rows, we can use:
normed_mat, scales = normalize_rows(mat, NormMode.REAL_TO_ZERO_ONE);
original_mat = denormalize_rows(normed_mat, DenormMode.ZERO_ONE_TO_REAL, scales)
And original_mat will be identical to mat.
Args:
mat (np.ndarray): An array of arrays where mat[r] is the rth row.
norm_mode(NormMode): Which normalization mode to use.
REAL_TO_ZERO_ONE: Normalize real values to [0, 1]
NONNEG_TO_ZERO_ONE: Normalize non-negative values to [0, 1]
REAL_TO_NEG_ONE_ONE: Normalize real values to [-1, 1]
NEG_ONE_ONE_TO_ZERO_ONE: Normalize [-1, 1] to [0, 1]
Returns:
normed_mat (np.ndarray): The normalized matrix.
norm_vec (np.array): A vector of factors, which can be used as a divisor to
normed_mat to retrieve the original matrix scale. Note that this
is only returned for modes other than NEG_ONE_ONE_TO_ZERO_ONE, where
there's no real scale involved.
"""
if norm_mode == NormMode.REAL_TO_ZERO_ONE:
normed_mat = librosa.util.normalize(mat, axis=1)
scale_factors = normed_mat[:, 0] / mat[:, 0]
return normed_mat / 2 + 0.5, scale_factors
if norm_mode == NormMode.REAL_TO_NEG_ONE_ONE or norm_mode == NormMode.NONNEG_TO_ZERO_ONE:
normed_mat = librosa.util.normalize(mat, axis=1)
scale_factors = normed_mat[:, 0] / mat[:, 0]
return normed_mat, scale_factors
if norm_mode == NormMode.NEG_ONE_ONE_TO_ZERO_ONE:
return mat / 2 + 0.5
def normalize(mat, scale_factors=None):
normed_mat = mat / np.max(mat)
scale_factors = normed_mat[:, 0] / mat[:, 0]
return normed_mat, scale_factors
def denormalize_rows(mat, denorm_mode, scale_factors=None):
"""This function denormalizes each row of mat, given an array of scale_factors.
We denormalize along the rows, so e.g.
[ [0.2, -1, 0.6 ], [ 5, [ [1, -5, 3 ],
[1, -1, 0.333 ], and 3, --> [3, -3, 1 ],
[-0.5, 1, .75 ] ] 4 ] [-2, 4, 3 ] ]
Example:
To retrieve the original rows, we can use:
normed_mat, scales = normalize_rows(mat, NormMode.REAL_TO_ZERO_ONE);
original_mat = denormalize_rows(normed_mat, scales, DenormMode.ZERO_ONE_TO_REAL)
And original_mat will be identical to mat.
Args:
mat (np.ndarray): An array of arrays where mat[r] is the rth row.
norm_mode(NormMode): Which normalization mode to use.
ZERO_ONE_TO_REAL: Denormalize values from [0, 1] to real
ZERO_ONE_TO_NONNEG: Denormalize values from [0, 1] to non-negative
NEG_ONE_ONE_TO_REAL: Denormalize values from [-1, 1] to real
ZERO_ONE_TO_NEG_ONE_ONE: Denormalize values from [0, 1] to [-1, 1]
scale_factors (np.array): The scale factors to denormalize each row by.
Returns:
normed_mat (np.ndarray): The normalized matrix
"""
if denorm_mode == DenormMode.ZERO_ONE_TO_REAL:
denormed_mat = np.array([ (mat[idx] * 2 - 1) / scale_factors[idx]
for idx in range(mat.shape[0]) ])
return denormed_mat
if denorm_mode == DenormMode.NEG_ONE_ONE_TO_REAL or denorm_mode == DenormMode.ZERO_ONE_TO_NONNEG:
denormed_mat = np.array([ mat[idx] / scale_factors[idx]
for idx in range(mat.shape[0]) ])
return denormed_mat
if denorm_mode == DenormMode.ZERO_ONE_TO_NEG_ONE_ONE:
return mat * 2 - 1
|
3bdd97e86dbe63b385faa73d0f4b42ca00a79340 | wzqwsrf/Leetcode | /Python/098 Validate Binary Search Tree.py | 1,954 | 3.96875 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
# Validate Binary Search Tree 308ms
"""
/**
* Given a binary tree, determine if it is a valid binary search tree (BST).
* Assume a BST is defined as follows:
* The left subtree of a node contains only nodes with keys less than the node's key.
* The right subtree of a node contains only nodes with keys greater than the node's key.
* Both the left and right subtrees must also be binary search trees.
* confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal,
where '#' signifies a path terminator where no node exists below.
Here's an example:
1
/ \
2 3
/
4
\
5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
*/
"""
"""
/*
* @author:wangzq
* @email:wangzhenqing1008@163.com
* @date:2014年07月11日12:15:30
* @url:https://oj.leetcode.com/problems/validate-binary-search-tree/
* 1、二叉搜索树的基本判断,左孩子比根值小,右孩子比根值大。
* 2、按照这个思路,默认的最大最小值是int的值范围。
* 3、递归判断,每次判断左右孩子的值和最大最小值的比较。
* 4、一直到根为空,递归结束。
* 具体参考http://blog.csdn.net/u013027996/article/details/37692581
*/
"""
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param root, a tree node
# @return a boolean
def isValidBST(self, root):
max_val = 2 ** 31
return self.dfs(root, -max_val, max_val)
def dfs(self, root, min_val, max_val):
if root is None:
return True
if root.val <= min_val or root.val >= max_val:
return False
return self.dfs(root.left, min_val, root.val) and self.dfs(root.right, root.val, max_val)
|
1e7263eb2e7be9b28401ce829d0dc4da2dce3936 | scMarth/Learning | /Leetcode/35_search_insert_position.py | 1,784 | 3.765625 | 4 | import math
def binary_search_call(arr, target):
l = 0
r = len(arr) - 1
while l < r:
mid = math.floor((l + r)/2)
print("l: {} ; m: {} ; r: {}".format(l, mid, r))
if arr[mid] == target:
return mid
elif arr[mid] < target:
l = mid + 1
else:
r = mid - 1
if arr[l] < target:
return l + 1
else:
return l
arr = range(0, 20)
target = 22
print(str(arr))
print("Target: {0}".format(target))
print("answer: " + str(binary_search_call(arr, target)))
print("")
target = 4
print("Target: {0}".format(target))
print("answer: " + str(binary_search_call(arr, target)))
print("")
target = -1
print("Target: {0}".format(target))
print("answer: " + str(binary_search_call(arr, target)))
print("")
target = 8
print("Target: {0}".format(target))
print("answer: " + str(binary_search_call(arr, target)))
print("")
target = 18
print("Target: {0}".format(target))
print("answer: " + str(binary_search_call(arr, target)))
print("")
target = 18.5
print("Target: {0}".format(target))
print("answer: " + str(binary_search_call(arr, target)))
print("")
target = 3.5
print("Target: {0}".format(target))
print("answer: " + str(binary_search_call(arr, target)))
print("")
arr = [1]
target = 1
print("Target: {0}".format(target))
print("answer: " + str(binary_search_call(arr, target)))
print("")
arr = [1, 3]
target = 4
print("Target: {0}".format(target))
print("answer: " + str(binary_search_call(arr, target)))
print("")
arr = [1, 3]
target = 0
print("Target: {0}".format(target))
print("answer: " + str(binary_search_call(arr, target)))
print("")
'''
Scrap:
binary saerch
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[1, 3]
0
l r m
0 1 0
''' |
e0aedef4f1ef9578ff59bc9a706779790c64de24 | Brodie-Pirovich/FOP_CovidTest | /FOP/FOP/personClass.py | 757 | 3.71875 | 4 | class person():
myClass = "Person"
def __init__(self, name, weight, dimensions, temp, cough, throat, resp):
self.name = name
self.weight = weight
self.dimensions = dimensions
self.temp = temp
self.cough = cough
self.throat = throat
self.resp = resp
def printit(self):
print("Name: ", self.name)
print("Temperature: ", self.temp)
print("DryCough: ", self.cough)
print("SourThroat: ", self.throat)
print("RespiratoryProblems: ", self.resp, "\n")
def getTemp(self):
return self.temp;
def getCough(self):
return self.cough
def getThroat(self):
return self.throat
def getResp(self):
return self.resp |
e424fdaf1fc2f8f39129bfff3411cb2f4298ef41 | agyenes/greenfox-exercises | /08a recursive_python/5.py | 344 | 4.28125 | 4 | # 5. We have a number of bunnies and each bunny has two big floppy ears.
# We want to compute the total number of ears across all the bunnies
# recursively (without loops or multiplication).
def bunny_ear_calculator(n):
if n <= 2:
return n * 2
else:
return 2 + bunny_ear_calculator(n-1)
print(bunny_ear_calculator(3))
|
68373247630435f99c172347aa28e27b0a5e1c6c | Syed-Azam/Challenges_of_the_day | /alphabet_dictionary.py | 250 | 3.828125 | 4 | # Challenge of the day
# Alphabet Dictionary in single line of code
# i.e. {1 = 'A', 2 = 'B'.................26 = 'Z'}
print(dict(zip([n for n in range(1,27)], [chr(c) for c in range(65,91)])))
# or
print({i+1:chr(i+65) for i in range(26)})
input() |
80a5b5cd615cd3aa98a65428cd54a34b1f7cbf9e | Vlados2810/DMI | /PYTHON/if.py | 426 | 3.875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
a=input("Lietotāj, lūdzu, ievadi vienu skaitli: ")
if a > 0:
print "Tu esi ievadījis pozitīvu skaitli"
elif a == 0:
print "Tu esi ievadījis nulli"
else:
print "Tu esi ievadījis negatīvu skaitli"
'''
a=input("Lietotāj, lūdzu, ievadi vienu skaitli: ")
if a > 0:
print "Tu esi ievadījis pozitīvu skaitli"
else:
print "Tu neesi ievadījis pozitīvu skaitli"
'''
|
d47c3977d779ad5eac4b7876c88d71773bb1f4b5 | sasiarivukalanjiam/python-learning | /fundamental/doc_strings.py | 607 | 3.59375 | 4 |
# Add two values and print the result
class doc_strings(object):
def add_it(self, a, b):
"""
Adds two value and returns the result
:param a:
:param b:
:return:
"""
c = a+b
return c
def print_message(self, value):
"""
gets a value and prints it
:param value:
:return:
"""
print("The sum is {0}".format(value))
if __name__ == '__main__':
d = doc_strings()
res = d.add_it(5,6)
d.print_message(res)
"""
outptut
The sum is 11
Process finished with exit code 0
"""
|
523e1a4d8e0a41a2438b48fe66649ffe6970c1b7 | asdra1v/python_homework | /homework01/Exercize03.py | 163 | 3.53125 | 4 | user_number = int(input("Введите число n: "))
un1 = int(f"{user_number}{user_number}")
un2 = int(f"{user_number}{un1}")
print(user_number + un1 + un2)
|
acd34f81e686830723714cc487a9b4def96f1180 | AJ3907/mergecsvs | /merge.py | 2,676 | 3.609375 | 4 | import csv
import os
import sys
def readCSV(csvFile):
res =[]
csvReader = csv.reader(csvFile)
for row in csvReader:
res.append(row)
return res
def getCommonColumnIndex(read,commonColumn):
commonColumnIndex = -1
l = len(read[0])
for i in range(0,l):
if (read[0][i] == commonColumn):
commonColumnIndex = i
if (commonColumnIndex == -1):
raise Exception("common Column doesn't exist")
return commonColumnIndex
def mapAllColumnsToCommonColumn(read,commonColumnIndex):
map={}
l = len(read)
for i in range(1,l):
key = read[i][commonColumnIndex]
if key not in map:
temp=[]
temp.append(read[i])
map[key]=temp
else:
print "duplicate rows are existing"
'''Handled duplicate rows by using list of list'''
map[key].append(read[i])
return map
def sameColumnsInBothCsv(read1,read2):
same=[]
l1=len(read1[0])
l2=len(read2[0])
for i in range(0,l1):
for j in range(0,l2):
if (read1[0][i]==read2[0][j]):
same.append(j)
return same
def merge(map1,map2,same,read1,read2):
res=[]
temp = read1[0]
for j in range(0,len(read2[0])):
if j not in same:
temp.append(read2[0][j])
res.append(temp)
for key in map2:
if key in map1:
p=len(map1[key])
q=len(map2[key])
for j in range(0,p):
for k in range(0,q):
temp=(map1[key][j][:])
for l in range(0,len(map2[key][k])):
if l not in same:
temp.append(map2[key][k][l])
res.append(temp)
#print res
return res
def get_csv_filenames(path):
suffix=".csv"
filenames=os.listdir(path)
return [ filename for filename in filenames if filename.endswith(suffix) ]
def mergeAll(listOfCsv,commonColumnName):
if(len(listOfCsv)==0):
raise Exception("No CSV files found!!")
f1 = open(listOfCsv[0])
read1 = readCSV(f1)
for i in range(1,len(listOfCsv)):
f2 = open(listOfCsv[i])
read2 = readCSV(f2)
commonColumnIndex1 = getCommonColumnIndex(read1,commonColumnName)
commonColumnIndex2 = getCommonColumnIndex(read2,commonColumnName)
map1=mapAllColumnsToCommonColumn(read1,commonColumnIndex1)
map2=mapAllColumnsToCommonColumn(read2,commonColumnIndex2)
same=sameColumnsInBothCsv(read1,read2)
read1=merge(map1,map2,same,read1,read2)
return read1
def writeOutputCsv(read):
with open('output.csv', 'wb') as fp:
writer = csv.writer(fp, delimiter=',')
writer.writerows(read)
# give path here, default is current directory
path = os.getcwd()
if (len(sys.argv)==1):
raise Exception("Please give the common Column Name in command line!")
commonColumnName = sys.argv[1]
listOfCsv = get_csv_filenames(path)
output=mergeAll(listOfCsv, commonColumnName)
writeOutputCsv(output)
|
78de255e59cd5b5f14de2562820ebfe9099cf5b1 | DreamerKing/learn-python | /sum-average.py | 254 | 4.0625 | 4 | #!/usr/bin/env python3
N = 10
sum = 0
count = 0
print("please input %d numbers:"% N)
while count < N:
number = float(input())
sum += number
count += 1
average = sum / count
print("N={} Sum={:.2f} Average={:.2f}".format(count, sum, average))
|
283bed7bc8a6d7c45462130a6b48633076c619f7 | SafonovMikhail/python_000577 | /000403StepPyThin/000403_02_02_Task_01_BreakContinue_other_02_20200105.py | 95 | 3.71875 | 4 | while True:
a = int(input())
if (a < 10): continue
if (a > 100): break
print(a) |
f1cc8f8f31c09dbd134e836d12a43399d5d035f9 | Jatin666/calculator | /cal.py | 588 | 4 | 4 | def add():
a=int(input("enter the first number: "))
b=int(input("enter the second number: "))
c=a+b
print(c)
return c
def subtract():
a = int(input("enter the first number: "))
b = int(input("enter the second number: "))
c = a - b
print(c)
return c
def multiply():
a = int(input("enter the first number: "))
b = int(input("enter the second number: "))
c = a * b
print(c)
return c
def divide():
a = int(input("enter the first number: "))
b = int(input("enter the second number: "))
c = a / b
print(c)
return c |
95e81e2b912866c0f24ab78b588b2769374c9071 | ashishiit/workspace | /LovePython/DecimaltoBinary.py | 653 | 3.640625 | 4 | '''
Created on Oct 26, 2016
@author: s528358
'''
# import string
class StackPython:
def __init__(self):
self.a = []
def Push(self,item):
self.a.append(item)
def Pop(self):
return self.a.pop()
def Peek(self):
return self.a[len(self.a)-1]
def IsEmpty(self):
return self.a == []
def Solution(self, num):
while num != 0:
item = num % 2
# print('item pushed = %d'%item)
self.Push(item)
num = num // 2
# print(self.a)
# print(self.a.reverse())
self.a.reverse()
print(self.a)
s = StackPython()
s.Solution(6) |
5795c53a22d0a4baaeb20c66153c0a8109afa77a | UncleBob2/MyPythonCookBook | /for loop types.py | 1,438 | 4.625 | 5 |
colors = ["red", "green", "blue", "purple"]
for color in colors:
print(color)
print(colors,"\n")
for i in colors:
print(i)
# For example, let’s say we’re printing out president names along with their numbers (based on list indexes).
# range of length
print("\nrange len indexes example")
presidents = ["Washington", "Adams", "Jefferson", "Madison", "Monroe", "Adams", "Jackson"]
for i in range(len(presidents)):
print("President {}: {}".format(i + 1, presidents[i]))
print("\nenumerate example")
#Python’s built-in enumerate function allows us to loop over a list and retrieve
# both the index and the value of each item in the list:
for num, name in enumerate(presidents, start=1):
print("President {}: {}".format(num, name))
#Here we’re looping over two lists at the same time using indexes
# to look up corresponding elements:
print("\nUse indexes to look something up in another list.")
colors = ["red", "green", "blue", "purple"]
ratios = [0.2, 0.3, 0.1, 0.4]
for i, color in enumerate(colors):
ratio = ratios[i]
print("{}% {}".format(ratio * 100, color))
#Python’s zip function allows us to loop over multiple lists at the same time without indexes:
print("\nUse zip instead of indexes to look something up in another list.")
colors = ["red", "purple", "green", "blue"]
ratios = [0.3, 0.1, 0.4, 0.2 ]
for color, ratio in zip(colors, ratios):
print("{}% {}".format(ratio * 100, color)) |
f0c3be8043c5974ac224d85c948478e9c772c723 | shuyirt/Leetcode | /0509_fibonacci_number.py | 461 | 3.5 | 4 | class Solution(object):
def fib(self, N):
"""
:type N: int
:rtype: int
"""
if N == 0 or N == 1:
return N
# list based
# l = [0, 1]
# for i in range(2, N+1):
# l.append(l[i-1] + l[i-2])
# return l[-1]
# variable based
a = 0
b = 1
for i in range(N - 1):
c = a
a = b
b = c + a
return b |
92ca38cc9a5635a114a1535224c4cdc4918f06c5 | otisscott/1114-Stuff | /Lab 5/binaryconverter.py | 411 | 3.875 | 4 | # Otis Scott
# CS - UY 1114
# 4 Oct 2018
# Homework 4
num = int(input("Enter a decimal number: "))
number = num
orig = num
count = 0
bin = ""
while num != 0:
num = num // 2
count += 1
for each in range(count - 1, -1, -1):
if (number - 2 ** each) >= 0:
bin += "1"
number -= 2 ** each
else:
bin += "0"
print("The binary representation of " + str(orig) + " is " + str(bin))
|
54d1b3bb4547132be9da6f100f71a0595efbbd45 | causelovem/4-course | /python 2017/dz5/task3_misha.py | 398 | 3.609375 | 4 | def comp(a, b):
if len(a) != len(b):
return 0
for i in range(len(a)):
if not((b[i] == a[i]) or (b[i] == "@")):
return 0
return 1
inp = input()
mask = input()
res = -1
for i in range(len(inp)):
if ((mask[0] == inp[i]) or (mask[0] == "@")) and (comp(inp[i:len(mask) + i], mask)):
res = inp.find(inp[i:len(mask) + i])
break
print(res)
|
29d66486ab9e0fffe88cc28d533e7e999adf5c96 | Manoji97/Data-Structures-Algorithms-Complete | /InterviewQuestions/Python/1_Arrays/2_ArrayPairSum.py | 449 | 3.828125 | 4 | '''
ex: pairSum([1, 3, 2, 2], 4)
output: (1, 3) and (2,2)
sum of Output should be equal to the number in input
'''
# For this method the Time Complexity is O(n)
def ArrayPairSum(lst, num):
length = len(lst)
if length < 2: return False
seen = set()
output = set()
for i in lst:
diff = num - i
if diff not in seen:
seen.add(i)
else:
output.add((min(i, diff), max(i, diff)))
return output
print(ArrayPairSum([1,3,2,2], 4)) |
d790776bd4bf0cc42da837dd894a252d97e45bfd | anaerobeth/dev-sprint2 | /palindrome.py | 1,040 | 4.25 | 4 | def first(word):
return word[0]
def last(word):
return word[-1]
def middle(word):
return word[1:-1]
#print first('biology')
#print last('biology')
#print middle('biology')
#print middle('hit')
#print middle('hi')
#print middle('a')
#print middle('')
#Type these functions into a file named palindrome.py and test them out.
#What happens if you call middle with a string with two letters?
#=> returns an empty string
#One letter?
#=> returns an empty string
#What about the empty string, which is written '' and contains no letters?
#=> returns an empty string
#Write a function called is_palindrome that takes a string argument and returns
#True if it is a palindrome and False otherwise.
#Remember that you can use the built-in function len to check the length of a string.
def is_palindrome(word):
if len(word) <=1:
return True
if first(word) != last(word):
return False
return is_palindrome(middle(word))
print is_palindrome('cat')
print is_palindrome('noon')
print is_palindrome('radar')
|
5324d423564c7de10ba3f2bb922cfb1061543851 | zgao92/STAT628_Module2_Group5 | /code/LSTM/LSTM_clean_data.py | 1,808 | 3.5625 | 4 | #python script to transform the test data into the matrix
#load the package
import sys
import pandas as pd
import numpy as np
import re
pd.options.mode.chained_assignment = None
test_data = pd.read_csv(sys.argv[1])
test_text = test_data.iloc[:,2]
from nltk.stem.wordnet import WordNetLemmatizer
lem = WordNetLemmatizer()
def noise_remove(review):
#only keep characters ! and ?
review = re.sub("\n", " ", review)
review = re.sub("!", " !", review)
review = re.sub("\?", " ?", review)
review = re.sub("[^a-zA-Z!?]", " ", review)
review = re.sub("[^a-zA-Z!?']", " ", review)
#change to lower case
review = review.lower()
#split words like isn't to is not
review = re.sub("n't"," not",review)
review = re.sub("n'"," not",review)
#remove the stop words
review = review.split()
#normalize the verb and noun
useful_review = [lem.lemmatize(word, "v") for word in review]
return " ".join(useful_review)
num_rows = len(test_text)
for i in range(num_rows):
test_text[i] = noise_remove(test_text[i])
#load feature names
feature_names = pd.read_csv("feature_names.csv",index_col=None)
feature_names = np.asarray(feature_names.iloc[:,1])
#produce feature matrix
word_matrix = np.zeros((num_rows,200))
for i in range(num_rows):
text = test_text[i].split()
for j in range(200):
if j < len(text):
word = text[j]
index = np.where(feature_names == word)[0]
if index.__len__() == 0:
word_matrix[i,j] = 0
else:
word_matrix[i,j] = index+1
else:
word_matrix[i,j] = 0
#save the result
word_matrix_df = pd.DataFrame(word_matrix)
word_matrix_df.to_csv(sys.argv[2])
|
345b75e60ba0c0c775a013e826e4b37d1a2abc32 | j42j/foundations | /pig_latin.py | 707 | 3.71875 | 4 | '''Pig Latin Translator
rules: if word begins with vowel, add "way" to the end of the word.
if word begins with consenant, removes all consenants until
reach first vowel, then add those consenants to the end of word,
then add "ay."'''
while True:
s = input('Enter word: ')
if s.isalpha():
break
else:
print("Please try again.")
vowels = ['a', 'i', 'e', 'o' ,'u', 'y']
sl = s.lower()
vowels_i = [sl.find(x) for x in vowels]
try:
i = min([x for x in vowels_i if x >= 0])
except ValueError:
print("This is not translatable.")
else:
if i == 0:
t = sl + 'way'
else:
t = sl[i:] + sl[:i] + 'ay'
print("Translation: {}".format(t))
|
383daeb888ab0748ebc5e9df45a983b998d1977f | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4138/codes/1637_2446.py | 372 | 3.71875 | 4 | s = int(input(" insira a senha: "))
a = s // 100000
b = s //10000 - (a * 10)
c = s // 1000 - ((a * 100) + (b * 10))
d = s // 100 - ((a * 1000) + (b *100) + (c * 10))
e = s // 10 - ((a * 10000) + (b *1000) + (c * 100) + (d * 10))
f = s % 10
sp = b + d + f
si = a + c + e
if (sp % si != 0):
mensagem = "senha invalida"
else:
mensagem = "acesso liberado"
print(mensagem) |
3b6eae090733e889c597c2ce4d7159d65feaa0ac | minccia/python | /python3/cursoguanabara/bhaskara.py | 626 | 3.59375 | 4 | # Progama para resolver a fórmula de Bhaskara e encontrar as raízes possíveis
coa = (int(input("Qual é o valor do coeficiente A?"))) # Coeficiente A
cob = (int(input("Qual é o valor do coeficiente B?"))) # Coeficiente B
coc = (int(input("Qual é o valor do coeficiente C?"))) # Coeficiente C
delta = ((cob**2)-4*coa*coc)**(1/2) # Delta/Discriminante
divisor = int((2*coa)) # Divisor
raiz_positiva = (((-cob+delta)/divisor)) # Primeira raíz possível
raiz_negativa = (((-cob-delta)/divisor)) # Segunda raíz possível
print("As raízes possíveis para os coeficientes dados são:")
print(raiz_positiva,raiz_negativa) |
459f867fd7c82b44f6bb052c3a4180a643513773 | MrJay10/Image-Processing | /Flash Light Detector.py | 2,177 | 3.6875 | 4 | from SimpleCV import *
cam = Camera() # Initialize Camera
img = cam.getImage() # get a sample image to know the screen size
display = Display() # Creates an object of Display Class
width, height = img.width, img.height # Gets width and height of the Image captured
screensize = width*height # initialize the screen size
threshold = 200 # If value of any pixel goes higher than this, it means light/blob is found in the stream
def onLayer():
newLayer = DrawingLayer(img.size()) # create a pseudo drawing layer
newLayer.circle((width/2, height/2), width/4, filled=True, color=Color.GREEN) # draw a circle at the center of display
newLayer.setLayerAlpha(75) # set transparency of circle
newLayer.setFontSize(20)
newLayer.text("Light Detected !", (width/2, height/2), color=Color.WHITE) # Display text on the screen
return newLayer
def offLayer():
newLayer = DrawingLayer(img.size())
newLayer.circle((width/2, height/2), width/4, filled=True, color=Color.RED)
newLayer.setLayerAlpha(75)
newLayer.setFontSize(20)
newLayer.text("No Source of Lights found !", (width/2, height/2), color=Color.WHITE)
return newLayer
while display.isNotDone(): # Keeps running till the user presses close button
img = cam.getImage() # Gets image from Camera
min_blob_size = 0.10*screensize # minimum blob size
max_blob_size = 0.80*screensize # maximum blob size
blobs = img.findBlobs(minsize=min_blob_size, maxsize=max_blob_size) # find blobs in the image
layer = offLayer() # by default, the layer will have no lights
if blobs: # but if any blob is found
avgcolor = np.mean(blobs[-1].meanColor()) # calculate the mean of rgb pixel value of blob
if avgcolor >= threshold: # and if it is greater than threshold value
layer = onLayer() # turn the layer to "on" mode
img.addDrawingLayer(layer) # add layer to the stream
img.show() # show the stream on display
if display.mouseLeft: # stop the streaming if user presses left mouse button
break
|
5972a40d079d603bea44a2f631b6bd3a146c30e9 | viszi/codes | /CodeWars/7kyu/Python/018-get-the-middle-character.py | 708 | 4.15625 | 4 | # https://www.codewars.com/kata/56747fd5cb988479af000028
# You are going to be given a word. Your job is to return the middle character of the word.
# If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters.
# Kata.getMiddle("test") should return "es"
# Kata.getMiddle("testing") should return "t"
def get_middle(s):
if len(s) % 2 == 0:
start = len(s) // 2 - 1
end = start + 2
else:
start = len(s) // 2
end = start + 1
return s[start:end]
print(get_middle("test"), "es")
print(get_middle("testing"), "t")
print(get_middle("middle"), "dd")
print(get_middle("A"), "A")
print(get_middle("of"), "of")
|
069b1e495218ed00a66b4638afcec5170ac15f99 | samrizky28/Manual-K-Fold-Cross-Validation | /KFoldCV_Manually.py | 1,473 | 3.53125 | 4 | import pandas as pd
import math
from sklearn.model_selection KFold
#X is the independent variable in the dataset
#y is the target variable
#n is the number of observations in the dataset
n=len(X)
#Let say we want to make 5-fold CV. It means, we are equivalent to doing a 20% separation of test data, then:
kf = KFold(n_splits=5)
train_cv = []
test_cv = []
for train, test in kf.split(X):
train_cv.append(train)
test_cv.append(test)
fold1 = math.ceil(0.2*n)
fold2 = math.ceil(0.4*n)
fold3 = math.ceil(0.6*n)
fold4 = math.ceil(0.8*n)
fold5 = n
#So splitting the dataset into training data and testing data becomes:
#1st fold
X_train_cv1 = X[fold1:n]
X_test_cv1 = X[test_cv[0][0]:fold1]
y_train_cv1 = y[fold1:n]
y_test_cv1 = y[test_cv[0][0]:fold1]
#2nd fold
X_train_cv2 = pd.concat([X[train_cv[1][0]:fold1], X[fold2:n]])
X_test_cv2 = X[fold1:fold2]
y_train_cv2 = pd.concat([y[train_cv[1][0]:fold1], y[fold2:n]])
y_test_cv2 = y[fold1:fold2]
#3rd fold
X_train_cv3 = pd.concat([X[train_cv[2][0]:fold2], X[fold3:n]])
X_test_cv3 = X[fold2:fold3]
y_train_cv3 = pd.concat([y[train_cv[2][0]:fold2], y[fold3:n]])
y_test_cv3 = y[fold2:fold3]
#4th fold
X_train_cv4 = pd.concat([X[train_cv[3][0]:fold3], X[fold4:n]])
X_test_cv4 = X[fold3:fold4]
y_train_cv4 = pd.concat([y[train_cv[3][0]:fold3], y[fold4:n]])
y_test_cv4 = y[fold3:fold4]
#5th fold
X_train_cv5 = X[train_cv[4][0]:fold4]
X_test_cv5 = X[fold4:fold5]
y_train_cv5 = y[train_cv[4][0]:fold4]
y_test_cv5 = y[fold4:fold5]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.