blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
9dd89f7f124c7b6e372dddafcefc25508ac1e4e9 | PSaiRahul/Pyworks | /csvsort.py | 2,437 | 4 | 4 | #!/usr/bin/python
"""A simple script to sort csv data
Usage:
csvsort.py <filename> --column=<cno>
csvsort.py <filename> --column=<cno> --dest=<destination-file>
csvsort.py <filename> --column=<cno> --desc
csvsort.py <filename> --column=<cno> --desc --dest=<destination-file>
csvsort.py (-h | --help)
csvsort.py --version
Options:
-h --help Display available commands
--version Get the version
--column=<cno> The column number to be used for sorting
--desc Sort in descending order
--dest=<destination-file> Write output data to file
"""
import csv
from operator import itemgetter
from docopt import docopt
from pprint import pprint
def gettypes(headers):
types = []
for name in headers:
start = name.find("(")
end = name.find(")")
types.append(name[start+1:end])
return types
def convert(types, row):
return [eval(t)(val) for t, val in zip(types, row)]
def write_data_to_dest(headers, data, destination):
with open(destination, 'wb') as f:
writer = csv.writer(f)
writer.writerow(headers)
for row in data:
writer.writerow(row)
def sort_csv(csvfile,column, desc=False, destination=None):
csvdata = []
headers = []
with open(csvfile, "rb") as f:
for row in csv.reader(f):
headers = row
break
types = gettypes(headers)
count = 0
for row in csv.reader(f):
if count == 0:
count = 1
else:
csvdata.append(convert(types,row))
if desc:
csvdata.sort(key=itemgetter(*column), reverse=True)
else:
csvdata.sort(key=itemgetter(*column))
if not destination:
print "Data sorted based on column {}".format(column)
print "---------------------------------"
pprint(csvdata)
else:
write_data_to_dest(headers, csvdata, destination)
if __name__ == "__main__":
arguments = docopt(__doc__, version="csvsort-0.1")
desc = arguments['--desc']
carg = arguments['--column']
if carg.find(",") > 0:
cols = [int(val)-1 for val in carg.split(",")]
else:
cols = list(int(carg)-1)
if arguments.has_key('--dest'):
dest = arguments['--dest']
else:
dest = None
sort_csv(arguments["<filename>"], cols, desc, dest)
|
a695b5afd6a0d5db953be66ee669af7c17d866fe | Grace-Bijun-Li/python-challenge | /PyPoll/main.py | 2,187 | 3.84375 | 4 | # Import sys
import sys
# Import pathlib and csv
import pathlib
import csv
# Set path for file with pathlib.Path(), pointing to the election_data.csv file saved in the Resources folder
csvpath = pathlib.Path("./Resources/election_data.csv")
# Open the CSV using the `with` keyword
with open(csvpath) as csvfile:
# Use csv.reader() to read the csvfile variable, setting the delimiter argument equal to ","
csvreader = csv.reader(csvfile, delimiter=",")
# Read the header row first
csv_header = next(csvreader)
# Create a date_set variable to count only the unique Voter IDs
voter_set = set()
# Setup a loop counter to count the number of rows
row_counter = 0
candidate_dict = dict()
# Loop through each row in csvreader
for row in csvreader:
# Use if function to count the number of unique Voter IDs in the dataset
if row[0] not in voter_set:
voter_set.add(row[0])
row_counter = row_counter + 1
# Set up dict key to pick up candidate name
candidate_name = row[2]
# Use if function to count the total number of votes for each candidate
if candidate_name not in candidate_dict:
candidate_dict[candidate_name] = 1
else:
candidate_dict[candidate_name] = candidate_dict[candidate_name] + 1
# Analysis Output
sys.stdout = open("./analysis/analysis.txt", "w")
print("PyPoll Election Results")
print("-------------------------")
print(f"Total Votes: {row_counter}")
print("-------------------------")
# Set winner_percent variable to determine the winner of PyPoll
winner_percent = 0
# Use for loop & if function to get each candidate's result and determine the winner
for key in candidate_dict:
percent = round(candidate_dict[key]/row_counter * 100, 3)
if percent > winner_percent:
winner_percent = percent
winner_key = key
print(key + ": " + str(percent) + "% (" + str(candidate_dict[key]) +")")
print("-------------------------")
print("Winner: " + winner_key)
print("-------------------------")
|
2a397a4197a70865fbc5f5768f668816776b33cc | ZhengLiangliang1996/Leetcode_ML_Daily | /other/1685_MinimumOperationsToReduceXtoZero.py | 815 | 3.640625 | 4 | #! /usr/bin/env python
"""
Author: LiangLiang ZHENG
Date:
File Description
"""
from __future__ import print_function
import sys
import argparse
arr_sum = sum(nums)
if arr_sum < x:
return -1
if arr_sum == x:
return len(nums)
required_subarray_sum = arr_sum - x
left = curr_sum = max_subarray_size = 0
for right, num in enumerate(nums):
curr_sum += num
while curr_sum > required_subarray_sum:
curr_sum -= nums[left]
left += 1
if curr_sum == required_subarray_sum:
max_subarray_size = max(max_subarray_size, right - left + 1)
return len(nums) - max_subarray_size if max_subarray_size > 0 else -1
def main():
pass
if __name__ == "__main__":
main()
|
5308300b92a06126c866e54886e8cc870eab062c | maneeshd/PyTutorial | /Advanced/OOP/Inheritance2/StudentClass.py | 863 | 3.5 | 4 | """
@author: Maneesh D
@email: maneeshd77@gmail.com
"""
class Student(object):
def __init__(self, name, branch, sex, age):
self.name = name
self.branch = branch
self.sex = sex
self.age = age
self.marks = 0
self.college = "SIR MVIT"
def give_marks(self, marks):
self.marks = marks
def get_marks(self):
return self.marks
def set_name(self, name):
self.name = name
def get_name(self):
return self.name
def set_branch(self, branch):
self.branch = branch
def get_branch(self):
return self.branch
def set_age(self, age):
self.age = age
def get_age(self):
return self.age
def set_sex(self, sex):
self.sex = sex
def get_sex(self):
return self.sex
def get_college(self):
return self.college
|
5dbee5e847f0622ef3af0561231743042ba0717a | quantbruce/leetcode_test | /数据结构相关/树/94. 二叉树的中序遍历.py | 2,650 | 3.8125 | 4 | 94. 二叉树的中序遍历
给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,3,2]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
#############################方法1:递归法
"""
执行用时:
44 ms
, 在所有 Python3 提交中击败了
43.44%
的用户
内存消耗:
13.7 MB
, 在所有 Python3 提交中击败了
7.84%
的用户
"""
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
if not root: return []
return self.inorderTraversal(root.left) +\
[root.val] +\
self.inorderTraversal(root.right)
###########################BFS 所有迭代框架法
###这是一种解这种题的通用框架,很有味道,必须掌握。
"""
执行用时:
28 ms
, 在所有 Python3 提交中击败了
99.05%
的用户
内存消耗:
13.7 MB
, 在所有 Python3 提交中击败了
7.84%
的用户
"""
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
white, gray = 0, 1
res = []
stack = [(white, root)]
while stack:
color, node = stack.pop()
if not node: continue
if color == white:
stack.append((white, node.right)) ## 改变下这个if条件语句中的三个顺序,就可以分别实现前中后遍历
stack.append((gray, node))
stack.append((white, node.left))
else:
res.append(node.val)
return res
https://leetcode-cn.com/problems/binary-tree-inorder-traversal/solution/yan-se-biao-ji-fa-yi-chong-tong-yong-qie-jian-ming/
###########底下的解答区高赞回答,还可以将方法2进一步让代码更简化
#####思路和方法2本质上是一样的
"""
执行用时:
36 ms
, 在所有 Python3 提交中击败了
86.66%
的用户
内存消耗:
13.7 MB
, 在所有 Python3 提交中击败了
7.84%
的用户
"""
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
stack, res = [root], []
while stack:
node = stack.pop()
if isinstance(node, TreeNode):
stack.extend([node.right, node.val, node.left]) # node.right和node.left是TreeNode类型(表明还未访问过),而node.val是int类型(代表已经访问过)
elif isinstance(node, int):
res.append(node)
return res
https://leetcode-cn.com/problems/binary-tree-inorder-traversal/solution/yan-se-biao-ji-fa-yi-chong-tong-yong-qie-jian-ming/204119
|
7b3a5e93432dfcfa020ff7b92eebe1b4de7b88fa | Sem31/Data_Science | /2_Numpy-practice/1_array.py | 182 | 3.59375 | 4 | import numpy as np
list_data = [1,2,3,4]
arr = np.array(list_data)
print("print 1-D arry :\n ",arr)
arr = np.array(list_data).reshape(2,2)
print("NOw print reshape array :\n ",arr)
|
cf7a5f91d8fba817087a336a2c82a89c4daa6a13 | LoggerHead22/Spellchecker | /Trie.py | 4,058 | 3.59375 | 4 | from collections import deque, OrderedDict
class Node:
def __init__(self, char, flag=0):
self.flag = flag
self.freq = None
self.child_nodes = {}
def __repr__(self):
return f'<{int(self.flag)},{self.child_nodes.keys()}>'
def add_to_node(self, word):
curr_node = self
word = list(word[::-1])
while word != []:
if word[-1] not in curr_node.child_nodes:
curr_node.child_nodes[word[-1]] = Node("")
# curr_node.child_nodes = OrderedDict(
# sorted(curr_node.child_nodes.items()))
curr_node = curr_node.child_nodes[word[-1]]
word.pop()
if curr_node.flag:
curr_node.flag += 1
result = False
elif not curr_node.flag:
curr_node.flag = 1
result = True
return result
def find_in_node(self, word):
curr_node = self
result = None
word = list(word[::-1])
while word != []:
if word[-1] not in curr_node.child_nodes:
result = (False, None)
break
else:
curr_node = curr_node.child_nodes[word[-1]]
word.pop()
if result is None:
result = (curr_node.flag, curr_node)
return result
def pop_in_node(self, word):
if word == "":
if self.flag and len(self.child_nodes) == 0:
return True
elif self.flag and len(self.child_nodes) != 0:
self.flag = False
return False
else:
raise KeyError
else:
if word[0] not in self.child_nodes:
raise KeyError
else:
result = self.child_nodes[word[0]].pop_in_node(word[1:])
if result:
del self.child_nodes[word[0]]
result = len(self.child_nodes) == 0
return result and not self.flag
class TrieIterator:
def __init__(self, root, prefix=""):
self.prefix = prefix
self.root = root
self.gener_words = TrieIterator.bfs(self) if root is not None else None
def __iter__(self):
return self
def __next__(self):
if self.gener_words is None:
raise StopIteration()
try:
word = next(self.gener_words)
except StopIteration:
raise StopIteration()
return word
def bfs(self):
queue = deque([("", self.root)])
queue_prefix = deque([["", 1]])
while queue:
curr_char, curr_node = queue.popleft()
curr_prefix = queue_prefix[0][0]
queue_prefix[0][1] -= 1
if queue_prefix[0][1] == 0:
queue_prefix.popleft()
if curr_node.flag == 1:
yield self.prefix + curr_prefix + curr_char
for child in OrderedDict(sorted(curr_node.child_nodes.items())):
queue.append((child, curr_node.child_nodes[child]))
if len(curr_node.child_nodes) > 0:
queue_prefix.append([curr_prefix + curr_char,
len(curr_node.child_nodes)])
class Trie:
def __init__(self):
self.root_node = Node("", False)
self._len = 0
self.trie_iterator = None
def add(self, key):
res = self.root_node.add_to_node(key)
if res:
self._len += 1
return res
def pop(self, word):
try:
self.root_node.pop_in_node(word)
except KeyError:
raise KeyError(word)
else:
self._len -= 1
def __len__(self):
return self._len
def __contains__(self, word):
return self.root_node.find_in_node(word)[0]
def __iter__(self):
return TrieIterator(self.root_node, "")
def starts_with(self, prefix):
start_node = self.root_node.find_in_node(prefix)[1]
return TrieIterator(start_node, prefix) |
d7210ef7bc58d48a80a859f69bdf95609ffa6a50 | wwwwodddd/Zukunft | /leetcode/merge-nodes-in-between-zeros.py | 503 | 3.90625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeNodes(self, h: Optional[ListNode]) -> Optional[ListNode]:
t = r = ListNode()
s = 0
while h:
if h.val == 0:
r.next = ListNode(s)
r = r.next
s = 0
else:
s += h.val
h = h.next
return t.next.next |
af8c0049f78ef469c447df3e82b6eed958c12813 | steadydoer/cs_python | /etc/calendar.py | 797 | 3.5625 | 4 | Month = {1:31, 2:28, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31}
# key:value , key:value pair
day = 1
for i in range(1,13):
print("{}월".format(i))
start = day % 7
print("\t"*start, end="")
for j in range(Month[i]): # 310
if(day % 7 == 6):
print("{}".format(j+1))
else:
print("{}\t".format(j+1), end="")
day += 1
print()
print()
# space = "{:<5}"
# for i in range(1,13):
# print("{}월".format(i))
# start = day % 7
# for k in range(start):
# print(space.format(" "), end="")
# for j in range(Month[i]):
# if(day % 7 == 6):
# print(space.format(j+1))
# else:
# print(space.format(j+1), end="")
# day += 1
# print()
# print()
|
69fb7294e781383159d17b90ed603895cbc09cd9 | grechko1985/Stepik-2021 | /Chapter №1/14. Тип комнаты (from part 1.12).py | 1,071 | 4.0625 | 4 | # Тип комнаты
print('Задача по расчеты площади комнат - мой вариант.')
type_room = input('Введите тип комнаты: ')
if type_room == 'треугольник':
a, b, c = int(input('Введите a: ')), int(input('Введите b: ')), int(input('Введите c: '))
p = ((a + b + c) / 2)
S = float(((p * (p - a) * (p - b) * (p - c)) ** 0.5))
print('Площадь треугольной комнаты равна', S, '.')
elif type_room == 'прямоугольник':
a, b = int(input('Введите a: ')), int(input('Введите b: '))
S = float(a * b)
print('Площадь прямоугольной комнаты равна', S, '.')
elif type_room == 'круг':
r = int(input('Введите радиус окружности r: '))
S = float(3.14 * (r ** 2))
print('Площадь круглой комнаты равна', S, '.')
else:
print('Такого типа комнат в Маливии не существует!')
|
71b0aa8363bd09e43d242f10a68d0f4918a60165 | deeryeus/Assignment-2.19-Color-Hex-Codes | /hexcodes.py | 574 | 3.59375 | 4 | # convert decimal color code to hexadecimal
def to_hex(d):
hex_int1 = d//16
hex_rem1 = d%16
hex_rem2 = hex_int1%16
hex_dictionary = {0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", \
10: "a", 11: "b", 12: "c", 13: "d", 14: "e", 15: "f"}
hex_code = "{0}{1}".format(hex_dictionary[hex_rem2], hex_dictionary[hex_rem1])
return hex_code
# convert rgb to hexadecimal
def hex_color(red, green, blue):
print("#{0}{1}{2}".format(to_hex(red), to_hex(green), to_hex(blue)))
hex_color(10, 32, 255) |
9018d2ef0c3ff1ae4b291efa1899f01671d35c37 | Denrur/TheLastRogue | /geometry.py | 5,054 | 3.90625 | 4 | import math
def add_2d(point1, point2):
return point1[0] + point2[0], point1[1] + point2[1]
def sub_2d(point1, point2):
return point1[0] - point2[0], point1[1] - point2[1]
def int_2d(point):
return int(point[0]), int(point[1])
def other_side_of_point_direction(point1, point2):
far_behind_point = sub_2d(point2, point1)
direction = element_wise_round(normalize(far_behind_point))
return direction
def other_side_of_point(point1, point2):
"""
returns the point right behind point2 as seen by point1.
1 = point1
2 = point2
r = result
..1..
.....
.....
...2.
...r.
"""
direction = other_side_of_point_direction(point1, point2)
return add_2d(point2, direction)
def distance_squared(point1, point2):
"""
Returns the distance between two points squared.
Marginally faster than Distance()
"""
return (point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2
def distance(point1, point2):
"""
Returns the distance between two points
"""
return math.sqrt(distance_squared(point1, point2))
def chess_distance(point1, point2):
"""
Returns the chess distance between two points
"""
return max(abs(point1[0] - point2[0]),
abs(point1[1] - point2[1]))
def length_sqrd(vec):
"""
Returns the length of a vector2D sqaured.
Faster than Length(), but only marginally
"""
return vec[0] ** 2 + vec[1] ** 2
def length(vec):
'Returns the length of a vector2D'
return math.sqrt(length_sqrd(vec))
def normalize(point):
"""
Returns a new vector that has the same direction as vec,
but has a length of one.
"""
if(point[0] == 0. and point[1] == 0.):
return (0., 0.)
return (point[0] / length(point), point[1] / length(point))
def element_wise_round(point):
"""
Return new point with each element rounded to nearest int
"""
return int(round(point[0])), int(round(point[1]))
def dot(a, b):
"""
Computes the dot product of a and b
"""
return a[0] * b[0] + a[1] * b[1]
def project_onto(w, v):
"""
Projects w onto v.
"""
return v * dot(w, v) / length_sqrd(v)
def zero2d():
return (0, 0)
class Rect(object):
"""A rectangle identified by two points.
The rectangle stores left, top, right, and bottom values."""
def __init__(self, position, width, height):
"""Initialize a rectangle top left point position and width height."""
self.set_points(position, width, height)
def set_points(self, position, width, height):
"""Reset the rectangle coordinates."""
x, y = position
self.left = x
self.top = y
self.right = x + width
self.bottom = y + height
def contains(self, pt):
"""Return true if a point is inside the rectangle."""
x, y = pt
return (self.left <= x <= self.right and
self.top <= y <= self.bottom)
def overlaps(self, other):
"""Return true if a rectangle overlaps this rectangle."""
return (self.right > other.left and self.left < other.right and
self.top < other.bottom and self.bottom > other.top)
@property
def width(self):
"""Return the width of the rectangle."""
return self.right - self.left
@property
def height(self):
"""Return the height of the rectangle."""
return self.bottom - self.top
@property
def top_left(self):
"""Return the top-left corner as a tuple."""
return self.left, self.top
@property
def bottom_right(self):
"""Return the bottom-right corner as a tuple."""
return self.right, self.bottom
def expanded_by(self, point):
"""Return a rectangle with extended borders.
Create a new rectangle that is wider and taller than the
immediate one. All sides are extended by "n" tuple.
"""
p1 = (self.left - point[0], self.top - point[1])
p2 = (self.right + point[0], self.bottom + point[1])
return Rect(p1, p2[0] - p1[0], p2[1] - p1[1])
def containing_points(self):
result = []
for x in range(self.left, self.right + 1):
for y in range(self.top, self.bottom + 1):
result.append((x, y))
return result
def border_points(self):
result = set()
for x in range(self.left, self.right + 1):
result.add((x, self.top))
result.add((x, self.bottom))
for y in range(self.top, self.bottom + 1):
result.add((self.left, y))
result.add((self.right, y))
return list(result)
def __str__(self):
return "<Rect (%s, %s) - (%s, %s)>" % (self.left, self.top,
self.right, self.bottom)
def __repr__(self):
return "%s(%r, %r)" % (self.__class__.__name__,
(self.left, self.top),
(self.right, self.bottom))
|
dc81a8e0856f9299a7aba0ae7b12dcba8fd80a75 | rafaelperazzo/programacao-web | /moodledata/vpl_data/331/usersdata/296/95770/submittedfiles/funcoes1.py | 1,218 | 4.09375 | 4 | # -*- coding: utf-8 -*-
n = int(input("Digite a quantidade de elementos das listas: "))
while n<=1:
n = int(input("Digite a quantidade de elementos das listas: "))
a = []
for i in range (0,n,1):
a.append(int(input("Digite um valor para a lista a: ")))
print("a = " + str (a))
b = []
for i in range (0,n,1):
b.append(int(input("Digite um valor para a lista b: ")))
print("b = " + str (a))
c = []
for i in range (0,n,1):
c.append(int(input("Digite um valor para a lista c: ")))
print("b = " + str (a))
#escreva o código da função crescente aqui
a_crescente = sorted(a)
a_decrescente = reversed(a)
if a == a_crescente:
print("S")
print("N")
elif a == a_decrescente:
print("N")
print("S")
else:
print("N")
print("N")
b_crescente = sorted(b)
b_decrescente = reversed(b)
if b == b_crescente:
print("S")
print("N")
elif b == b_decrescente:
print("N")
print("S")
else:
print("N")
print("N")
c_crescente = sorted(c)
c_decrescente = reversed(c)
if c == c_crescente:
print("S")
print("N")
elif c == c_decrescente:
print("N")
print("S")
else:
print("N")
print("N")
#escreva as demais funções
#escreva o programa principal
|
ea344994d11c459955de8210733ee928d841fd94 | saidworks/TTC | /chapter13_Game_Design_Top_Down/Game_Design_Top_Down.py | 5,996 | 4.3125 | 4 | ####This an example of procedural programming where functions are created to handle all main tasks
from random import choice
def InitializeGrid(board):
#Initialize grid by random value
for i in range(8):
for j in range(8):
board[i][j]=choice(['Q','R','S','T','U'])
def Initialize(board):
#Initialize game
#Intialize the grid
InitializeGrid(board)
#Initialize score
global score
score=0
#Initialize turn number
global turn
turn=1
def ContinueGame(currentscore,goalscore=100):
#Return false if game should end , true if game not over
if currentscore>=goalscore:
return False
else:
return True
def DrawBoard():
# Display the board to the screen
linetodraw = ""
# Draw some blank lines first
print("\n\n\n")
print(" ---------------------------------")
# Now draw rows from 8 down to 1
for i in range(7, -1, -1):
# Draw each row
linetodraw = str(8-i) + ""
for j in range(8):
linetodraw += " | " + board[i][j]
linetodraw += " |"
print(linetodraw)
print(" ---------------------------------")
print(' | a | b | c | d | e | f | g | h |')
global score
print('current score:',score)
#verify user entry
def IsValid(move):
#verify if the user entered an appropriate key
cols = [ 'a' , 'b' ,'c' , 'd' , 'e' , 'f' , 'g' , 'h']
direction = ['u','d','l','r']
if len(move)==3 and int(move[1])<8:
for i in cols:
for j in direction:
if move.startswith(i):
if move.endswith(j):
return True
else:
return False
def GetMove():
#instructions
print("Enter move by specifuing the space and the direction (u,d,l,r). Spaces should list column then row. \n For example, e3u would swap position e3 with the one above, and f7r would swap f7 to the right.")
#Get the move from the user
move = input("Enter a move : ")
while not IsValid(move):
move = input("Enter a move : ")
return move
def DoRound():
#Perform one round of the game
#Display current board
DrawBoard()
#Get a move
move=GetMove()
#Update board
Update(board,move)
#update turn number
global turn
turn+=1
def ConvertLetterToCol(Col):
if Col == 'a':
return 0
elif Col == 'b':
return 1
elif Col == 'c':
return 2
elif Col == 'd':
return 3
elif Col == 'e':
return 4
elif Col == 'f':
return 5
elif Col == 'g':
return 6
elif Col == 'h':
return 7
else:
#not a valid column!
return -1
def SwapPieces(board, move):
#Swap pieces on board according to move
#Get original position
origrow = int(move[1])-1
origcol = ConvertLetterToCol(move[0])
#Get adjacent position
if move[2] == 'u':
newrow = origrow + 1
newcol = origcol
elif move[2] == 'd':
newrow = origrow - 1
newcol = origcol
elif move[2] == 'l':
newrow = origrow
newcol = origcol - 1
elif move[2] == 'r':
newrow = origrow
newcol = origcol + 1
#Swap objects in two positions
temp = board[origrow][origcol]
board[origrow][origcol] = board[newrow][newcol]
board[newrow][newcol] = temp
def RemovePieces(board):
#Remove 3-in-a-row and 3-in-a-column pieces
#Create board to store remove-or-not
remove = [ [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]
#Go through rows
for i in range(8):
for j in range(6):
if (board[i][j] == board[i][j+1]) and (board[i][j] == board[i][j+2]):
#three in a row are the same!
remove[i][j] = 1;
remove[i][j+1] = 1;
remove[i][j+2] = 1;
#Go through columns
for j in range(8):
for i in range(6):
if (board[i][j] == board[i+1][j]) and (board[i][j] == board[i+2][j]):
#three in a row are the same!
remove[i][j] = 1;
remove[i+1][j] = 1;
remove[i+2][j] = 1;
#Eliminate those marked
global score
removed_any = False
for i in range(8):
for j in range(8):
if remove[i][j] == 1:
board[i][j] = 0
score += 1
removed_any = True
return removed_any
def DropPieces(board):
#Drop pieces to fill in blanks
for j in range(8):
#make list of pieces in the column
listofpieces = []
for i in range(8):
if board[i][j] != 0:
listofpieces.append(board[i][j])
#copy that list into colulmn
for i in range(len(listofpieces)) :
board[i][j] = listofpieces[i]
#fill in remainder of column with 0s
for i in range(len(listofpieces), 8):
board[i][j] = 0
def FillBlanks(board):
#Fill blanks with random pieces
for i in range(8):
for j in range(8):
if (board[i][j] == 0):
board[i][j] = choice(['Q', 'R', 'S', 'T', 'U'])
def Update(board, move):
#Update the board according to move
SwapPieces(board, move)
pieces_eliminated = True
while pieces_eliminated:
pieces_eliminated = RemovePieces(board)
DropPieces(board)
FillBlanks(board)
#state variables for main data to be stored ( data structure)
score = 50
goalscore = 100
board=[[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0]]
#Initialize Game
Initialize(board)
#Loop while game not over
while ContinueGame(score,goalscore):
#Do a round of the game
DoRound() |
3a2abca2023987a0e0b693ea1a47ff713b83d642 | bazuevad/problem-solving | /Algorithms/binarySearch.py | 357 | 3.953125 | 4 | def binarySearch(array, target):
return binarySearchH(array, target, 0, len(array)-1)
def binarySearchH(array, target, left, right):
if left>right:
return -1
mid = (left+right)//2
if target==array[mid]:
return mid
elif target<array[mid]:
return binarySearchH(array,target,left,mid-1)
else:
return binarySearchH(array,target,mid+1,right)
|
fb23ad2bef74cccb292d745a596d9a7476ecd3fd | gabriellll00/hello-world | /UriOnlineJudge/uri1004.py | 127 | 3.6875 | 4 | """
Multiplicação entre dois inteiros
"""
num1 = int(input())
num2 = int(input())
prod = num1 * num2
print(f'PROD = {prod}')
|
bb79dbb7a181a51cfd699e6d96810b8fb491381b | imao03/Chapter-01 | /myExcle/测试三组数据.py | 666 | 3.65625 | 4 | # coding:UTF-8
import unittest
from parameterized import parameterized
"""
问题:
如果有三组数据需要测试?
[(1,1,2), (1,2,3), (0,3,3)]
"""
def add(x, y):
return x + y
def get_data():
return [(1, 2, 3), (3, 0, 3), (2, 1, 3)]
# 定义测试类,并集成
class Test01(unittest.TestCase):
@parameterized.expand(get_data())
def test_add(self, a, b, expect):
result = add(a, b)
assert result == expect
def testStr_Int(self):
print("")
i = 10
s = str(i)
print(s)
s = '1'
i = int(s)
print(i)
if __name__ == '__main__':
print("")
|
0d46eeb1675f567f6cf2b20f500e44691deaacec | Arpi65/UCI_Homework_Arpi | /python_challenge/PyBank/main.py | 2,555 | 3.75 | 4 |
# Need to read the file from the data source C:\Users\arpib\Desktop\uci-irv-data-pt-08-2020-u-c\02-Homework\03-Python\Instructions\PyBank\Resources
# The current Folder working in is C:\Users\arpib\Desktop\python-challenge\PyBank
import os
import csv
#csvpath = os.path.join('..','uci-irv-data-pt-08-2020-u-c','02-Homework','03-Python','Instructions','PyBank','Resources','budget_data.csv')
# use next and csv reader
csvpath=os.path.join('Resources','budget_data.csv')
with open(csvpath) as csvfile:
csvreader=csv.reader(csvfile,delimiter=",")
print(csvreader)
print("-----------------------------")
csvheader=next(csvreader)
print(f"CSV Header: {csvheader}")
#Number of months in the file
Number_Of_Months=sum(1 for line in csvreader)
print(f'Number of months in the file {Number_Of_Months}')
# # The net total amount of "Profit/Losses" over the entire period
totalm=["Total number of months",Number_Of_Months]
with open(csvpath) as csvfile:
csvreader=csv.reader(csvfile,delimiter=",")
csvheader=next(csvreader)
total=sum(float(row[1]) for row in csvreader)
print(f'Total of Profit/Loss {total}')
totalp=["Total Profit/loss",total]
#The greatest increase in profits (date and amount) over the entire period
with open(csvpath) as csvfile:
csvreader=csv.reader(csvfile,delimiter=",")
csvheader=next(csvreader)
maximum=max(float(row[1]) for row in csvreader)
with open(csvpath) as csvfile:
csvreader=csv.reader(csvfile,delimiter=",")
csvheader=next(csvreader)
for row in csvreader:
if float(row[1])==maximum:
dateofmax=row[0]
print(row[0])
print(f'Maximum Value {maximum}')
maxp=["Maxium Value",dateofmax,maximum]
# The greatest decrease in losses (date and amount) over the entire period
#with open(csvpath) as csvfile:
# csvreader=csv.reader(csvfile,delimiter=",")
# csvheader=next(csvreader)
average=total/Number_Of_Months
print(f'Average profit/Loss {average} ')
avgp=["Average profit change",average]
#prnit results in txt file
output_file= os.path.join("..", "analysis", "bank_py.csv")
with open(output_file, "w") as datafile:
writer = csv.writer(datafile)
title=["Financial Analysis"]
writer.writerow(title)
writer.writerow(totalm)
writer.writerow(totalp)
writer.writerow(maxp)
writer.writerow(avgp)
# The net total amount of "Profit/Losses" over the entire period
# The average of the changes in "Profit/Losses" over the entire period
# The greatest increase in profits (date and amount) over the entire period
# The greatest decrease in losses (date and amount) over the entire period
|
0370539c644c8ec9bfb8b84410056d006b2c7364 | orestisfoufris/algorithmicProblemsPython | /burstballoons.py | 798 | 3.5625 | 4 | '''
Burst Balloons dynamic programming problem
https://leetcode.com/problems/burst-balloons/
'''
def maxCoins(nums):
"""
:type nums: List[int]
:rtype: int
"""
# let's put the 1s before and after
nums = [1] + nums + [1]
N = len(nums)
# dp[i][j] denotes the best result for range (i, j)
dp = [[0 for i in range(N)] for i in range(N)]
for i in range(1, N - 1):
for left in range(0, N - i - 1):
# starting point for right
right = left + i + 1
# m (middle) will be the last balloon
# to be burst
for m in range(left + 1, right):
dp[left][right] = max(dp[left][right], dp[left][m] +
dp[m][right] + nums[left] * nums[m] * nums[right])
return dp[0][N - 1]
|
9f9319a4b475595c17a8fef968b77e7c9c5b6aa5 | libdx/pylab | /scripts/convert.py | 1,272 | 3.8125 | 4 | #!/usr/bin/env python
import csv
import json
from pathlib import Path
def csv_file_to_json(file, output_dir, labels=None):
"""Converts CSV data file to JSON data file.
:param file: path to CSV file.
:type file: pathlib.Path
:param output_dir: path to output directory where JSON file will be placed.
:type output_dir: pathlib.Path
:param labels: list of columns names.
:type labels: list[str]
"""
if labels is None:
labels = []
if output_dir is None:
output_dir = file.parent
with open(file) as f:
reader = csv.DictReader(f, labels)
contents = list(reader)
if not output_dir.exists():
output_dir.mkdir(parents=True)
output_file = output_dir / file.with_suffix('.json').name
with open(output_file, 'w') as f:
json.dump(contents, f, indent=2)
def main():
data_dir = Path('data')
with open(data_dir / 'metadata.json') as f:
metadata = json.load(f)
output_dir = Path('data') / 'json'
for entry in metadata:
filename = entry['filename']
labels = entry['labels']
csv_file = (data_dir / filename).with_suffix('.csv')
csv_file_to_json(csv_file, output_dir, labels)
if __name__ == '__main__':
main()
|
0881b693f6118b11f56654bf1f71c6831e341146 | kirsty-tortoise/comp4-simulation | /src/Graphs.py | 4,141 | 3.75 | 4 | # TODO:
from RelativeDrawing import *
class Graph(object):
'''
Stores the data about a parameter and slowly draws a graph in real time.
'''
def __init__(self, name, parameterList, colourList, minY, maxY, incrementX = 0.001, relX=0.55, relY=0.05, relWidth=0.4, relHeight=0.25, boxX = 0.5, boxY = 0.03, boxWidth = 0.5, boxHeight = 0.32, boxColour = color(255, 0, 0), axesColour = color(0)):
'''
Sets up a graph and draws on the axes.
relX, relY, relWidth and relHeight determine the size of the actual graph and axes
boxX, boxY, boxWidth, boxHeight determine the size of the containing box
scalingY is the amount by which the y coordinate is scaled, and incrementX is the amount to increase X (time) for each plot
parameterList contains the parameters to plot, and colourList is the colours to plot them in
'''
self.name = name
self.relX = relX
self.relY = relY
self.relWidth = relWidth
self.relHeight = relHeight
self.boxX = boxX
self.boxY = boxY
self.boxWidth = boxWidth
self.boxHeight = boxHeight
self.minY = minY
self.maxY = maxY
self.scalingY = relHeight / float(maxY - minY)
self.incrementX = incrementX
self.parameterList = parameterList
self.colourList = colourList
self.boxColour = boxColour
self.axesColour = axesColour
def display(self):
'''
Resets the graph and sets up the axes when required.
More code may be added later to deal with drawing scales properly.
'''
# Draw the surrounding rectangle, getting rid of everything from before.
noStroke()
fill(self.boxColour)
relXRect(self.boxX, self.boxY, self.boxWidth, self.boxHeight)
# Draw the two axes
stroke(self.axesColour)
strokeWeight(2)
# Decide on where the x axis should be.
if self.minY <= 0 <= self.maxY:
pointY = self.scalingY * self.minY + self.relY + self.relHeight
elif self.minY > 0:
pointY = self.relY + self.relHeight
else:
pointY = self.relY
relXLine(self.relX, pointY, self.relX + self.relWidth, pointY) # x axis
relXLine(self.relX, self.relY, self.relX, self.relY + self.relHeight) # y axis
strokeWeight(1)
# Draw in key
drawingX = self.boxX + 0.05 * self.boxWidth
keyWidth = 0.9 * self.boxWidth / len(self.parameterList)
for i in range(len(self.parameterList)):
# Draw a block of that colour
fill(self.colourList[i])
relXRect(drawingX, self.relY + 1.02 * self.relHeight, 0.05 * self.relWidth, 0.05 * self.relWidth)
drawingX += 0.05 * self.boxWidth
fill(0)
textSize(20)
relXText(self.parameterList[i].name, drawingX, self.relY + 1.06 * self.relHeight)
drawingX += keyWidth
# Move drawing point back to the beginning
self.x = 0
self.oldX = [None for i in self.parameterList]
self.oldY = [None for i in self.parameterList]
def update(self):
strokeWeight(3)
for count in range(len(self.parameterList)):
param = self.parameterList[count]
colour = self.colourList[count]
stroke(colour)
pointX = self.x + self.relX
if self.minY <= param.value <= self.maxY:
pointY = - self.scalingY * (param.value - self.minY) + self.relY + self.relHeight
elif self.minY > param.value:
pointY = self.relY + self.relHeight
else:
pointY = self.relY
if self.x != 0:
relXLine(self.oldX[count], self.oldY[count], pointX, pointY)
self.oldX[count] = pointX
self.oldY[count] = pointY
strokeWeight(1)
self.x += self.incrementX
if self.x > self.relWidth:
self.display()
|
2d5c6718843ea5471a1d8b044a6bd89bd1273a26 | geshkocker/python_hw | /hw3_t1.py | 1,220 | 3.6875 | 4 | zen_of_python = '''
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
'''
better_c = zen_of_python.count('better')
never_c = zen_of_python.count('never')
is_c = zen_of_python.count('is')
zen_of_python_upper = zen_of_python.upper()
zen_of_python_replace = zen_of_python.replace('i', '&')
print(f'Word "better" is used {better_c} times')
print(f'Word "never" is used {never_c} times')
print(f'Word "is" is used {is_c} times')
print(zen_of_python_upper)
print(zen_of_python_replace)
|
bf4bbfaa9fe19c8a9e1463bcc19da4044a9911fd | madhurajoshi55/Intutive_Solutions_Madhura_Pub | /ReverseString.py | 1,163 | 3.703125 | 4 | class Solution(object):
def reverseStrng(self, strng):
"""
:type s: str
:rtype: str
"""
length = len(strng)
st = []
for i in range(length):
# add the index of opening bracket
if (strng[i] == '('):
st.append(i)
# reversing the substring after last opening bracket
elif (strng[i] == ')'):
temp = strng[st[-1]:i + 1]
strng = strng[:st[-1]] + temp[::-1] + \
strng[i + 1:]
del st[-1]
# To store the modified string
result = ""
for i in range(length):
if (strng[i] != ')' and strng[i] != '('):
result += (strng[i])
return result
if __name__ == '__main__':
strng = "(abc)"
strng1 = "(ed(et(oc))el)"
strng2 = "(u(love)i)"
strng3= "a(bcdefghijkl(mno)p)q"
print(reverseStrng(__name__, strng))
print(reverseStrng(__name__, strng1))
print(reverseStrng(__name__, strng2))
print(reverseStrng(__name__, strng3))
|
3ebdc23d4bd4b8cb5f3ddbe2c44b115f103fd8d1 | koushik-chandra-sarker/PythonLearn | /a_script/b_Variable.py | 1,826 | 4.40625 | 4 | """
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
Variable names are case-sensitive (age, Age and AGE are three different variables)
Illegal variable names:
1variable = 13
var-iable = 10
var iable = 14
Legal variable names:
variable = 13
my_name = "Koushik Chandra Sarker"
myName = "Koushik Chandra Sarker"
MYNAME = "Koushik Chandra Sarker"
MYNAME2 = "Koushik Chandra Sarker"
"""
# Variables do not need to be declared with any particular type, and can even change type after they have been set.
x = 10 # int
x1 = 10.4 # float
y = "Hello Python" # String-> str
print(x) # Output: 10
print(type(x)) # Output: <class 'int'>
print(x1) # Output: 10.4
print(type(x1)) # Output: <class 'float'>
print(y) # Output: Hello Python
print(type(y)) # Output: <class 'str'>
# Case-Sensitive
# Variable names are case-sensitive.
a = 13
A = 15
print(a) # Output: 13
print(A) # Output: 15
# Casting
# If you want to specify the data type of a variable, this can be done with casting.
a1 = str(a)
a2 = float(a)
print(type(a1)) # Output: <class 'str'>
print(type(a2)) # Output: <class 'float'>
"""
Python allows you to assign values to multiple variables in one line:
"""
a, b, c = "Red", "Green", "Yellow"
print(a) # Output: Red
print(b) # Output: Green
print(c) # Output: Yellow
"""
you can assign the same value to multiple variables in one line:
"""
a = b = c = 10
print(a) # Output: 10
print(b) # Output: 10
print(c) # Output: 10
|
8f2d80cdab470e8d2f41e5bb01d1ee67757e0956 | MarkyAaronYoung/petting-zoo | /animals/duck/duck.py | 255 | 3.53125 | 4 | from datetime import date
from animals.animal import Animal
class Duck(Animal):
def __init__(self, name, species, shift, food, chip_num):
super().__init__(name, species, food, chip_num)
self.shift = shift
self.swimming = True
|
20fb65fb203b373cad89738adc11b1afbe3bd157 | Barracas-azazaza/Curso-principiante-Python | /Parcial.py | 506 | 4 | 4 | print("ingrese el numero de datos a guardar")
veces=float(input())
datos=[]
n=0
acumulador=0
acumulador2=0
promedio=acumulador/veces
while n<veces:
print("Ingrese numero")
numero=float(input())
info={
"digito":numero
}
datos.append(info)
acumulador=numero+acumulador
n=n+1
promedio=float(acumulador/veces)
print(promedio)
for r in datos:
acumulador2=float(r["digito"]-promedio)**2+acumulador2
varianza=float(acumulador2/veces)
print(varianza) |
d7ac18b4ebc564b91e8e905e63a3c8a0a6f9b08b | rjmacleod/math134 | /dwr.py | 653 | 3.859375 | 4 | # Takes 2 natural numbers a and b and
# computes integers q and r st a = qb * r and 0 <= r < b.
def dwr(a, b):
# Takes natural numb a and b, returns (q,r) such that
# a = qb + r where q,r are integers and 0 <= r < b
q = 1
r = 0
if (a > b):
while ((q + 1) * b < a):
q += 1
r = a - q * b
return q, r
elif (a == b):
return 1, 0
else:
return 0, a
a = 1
b = 1
print("Enter natural numbers a and b, a > b.")
while (a < 2):
a = input("a = ")
a = int(a)
while (b < 2):
b = input("b = ")
b = int(b)
(q,r) = dwr(a,b)
print("{} = {} * {} + {}".format(a,q,b,r)) |
1f5ab29e8d33e63c67b05ea7cf6b85fc06f3b2ff | savnani5/Opencv-basic-codes | /Ml_opencv_algo.py | 2,467 | 3.5 | 4 | # ML algorithms
"""
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Feature set containing (x,y) values of 25 known/training data
trainData = np.random.randint(0,100,(25,2)).astype(np.float32)
# Labels each one either Red or Blue with numbers 0 and 1
responses = np.random.randint(0,2,(25,1)).astype(np.float32)
# Take Red families and plot them
red = trainData[responses.ravel()==0]
plt.scatter(red[:,0],red[:,1],80,'r','^')
# Take Blue families and plot them
blue = trainData[responses.ravel()==1]
plt.scatter(blue[:,0],blue[:,1],80,'b','s')
#plt.show()
newcomers = np.random.randint(0,100,(10,2)).astype(np.float32)
plt.scatter(newcomers[:,0],newcomers[:,1],80,'g','o')
knn = cv2.ml.KNearest_create()
knn.train(trainData, cv2.ml.ROW_SAMPLE, responses)
ret, results, neighbours ,dist = knn.findNearest(newcomers, 3)
print( "result: {}\n".format(results) )
print( "neighbours: {}\n".format(neighbours) )
print( "distance: {}\n".format(dist) )
plt.show()
"""
#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
import numpy as np
import cv2 as cv
img = cv.imread('C:\\Users\\HP\\Desktop\\Fero\\digits.png')
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
# Now we split the image to 5000 cells, each 20x20 size
cells = [np.hsplit(row,100) for row in np.vsplit(gray,50)]
# Make it into a Numpy array. It size will be (50,100,20,20)
x = np.array(cells)
# Now we prepare train_data and test_data.
train = x[:,:50].reshape(-1,400).astype(np.float32) # Size = (2500,400)
test = x[:,50:100].reshape(-1,400).astype(np.float32) # Size = (2500,400)
# Create labels for train and test data
k = np.arange(10)
train_labels = np.repeat(k,250)[:,np.newaxis]
test_labels = train_labels.copy()
# Initiate kNN, train the data, then test it with test data for k=1
knn = cv.ml.KNearest_create()
knn.train(train, cv.ml.ROW_SAMPLE, train_labels)
ret,result,neighbours,dist = knn.findNearest(test,k=5)
# Now we check the accuracy of classification
# For that, compare the result with test_labels and check which are wrong
matches = result==test_labels
correct = np.count_nonzero(matches)
accuracy = correct*100.0/result.size
print( accuracy )
# save the data
np.savez('knn_data.npz',train=train, train_labels=train_labels)
# Now load the data
with np.load('knn_data.npz') as data:
print( data.files )
train = data['train']
train_labels = data['train_labels']
|
fee70308fcd2662dbb154e09417c4abd6793776e | soniya-mi/python | /palindrme_string.py | 224 | 3.953125 | 4 | string = "Soniya"
len = len(string)
rev_str = ""
for index in range(len,0,-1):
rev_str = rev_str + string[index-1]
if rev_str = string:
print "Palindrome"
else:
print "Not Palindrome"
print rev_str |
ca8f08582f747953121500f3dfbfd02c944a78e5 | tanvirraihan142/CtCi-in-python | /Chap 1/1.3.1 URLify.py | 619 | 3.59375 | 4 | def replace_spaces(str1,true_length):
space_count=0
i=0
str1 = list(str1)
for i in range(true_length):
if (str1[i]==' '):
space_count+=1
index = true_length + space_count*2
if (true_length < len(str1)):
str1[true_length] = '\0'
str2 = [' ' for i in range(index)]
for i in range(true_length-1,-1,-1):
if (str1[i]==' '):
str2[index-1]='0'
str2[index-2]='2'
str2[index-3]='%'
index = index - 3
else:
str2[index-1] = str1[i]
index-=1
return "".join(str2)
|
1b4c6ec29fc3947ff332f63363c683f297d82151 | wing1king/python_xuexi | /阶段1-Python核心编程/09-模块和包/hm_01_模块的使用方法.py | 494 | 4.09375 | 4 | # 需求: math模块下sqrt()开评分计算
"""
1. 导入模块
2. 测试是否导入成功:调用该模块内的sqrt功能
"""
# 方法一: import 模块名; 模块名.功能
import math
print(math.sqrt(9))
# 方法二: from 模块名 import 功能1, 功能2....;功能调用(不需要书写模块名.功能)
from math import sqrt
print(sqrt(9))
# 方法三: from 模块名 import *; 功能调用(不需要书写模块名.功能)
from math import *
print(sqrt(9)) |
064cbef55d766b1f524e24dd44cdb6f218667486 | rafaelperazzo/programacao-web | /moodledata/vpl_data/303/usersdata/285/67223/submittedfiles/testes.py | 286 | 3.90625 | 4 | # -*- coding: utf-8 -*-
#COMECE AQUI ABAIXO
nota=float(input("digite sua primeira nota:"))
print(nota)
nota=float(input("digite sua segunda nota:"))
print(nota)
nota=float(input("digite sua terceira nota:"))
print(nota)
note=float(input("digite sua quarta nota:"))
print(nota) |
396c510c85e132bd8fff011d5012361214c75e01 | Obadha/andela-bootcamp-8-nbo | /Assignments_Day2/fibonacci.py | 209 | 4.3125 | 4 | # '''
# '''how to implement Fibonacci gotten from python docs using recursion'''
def fibo(n):
num_list = []
a, b = 0, 1
while b < n:
num_list.append(b)
a,b = b, a + b
return num_list
print(fibo(10)) |
a1cec9bf77214fd71e45cdbf98f062c046bd97f8 | zaine-co/jartaton-rappi | /back/bellman.py | 1,493 | 3.921875 | 4 | def BellmanFord(G,start):
D = {} # dictionary of final distances
for v in G:
D[v] = float('inf')
D[start] = 0
P = {} # dictionary of predecessors
for i in range(len(G)-1):
for u in G:
for v in G[u]:
newDv = D[u] + G[u][v]
if newDv < D[v]:
P[v] = u
D[v] = newDv
for u in G:
for v in G[u]:
newDv = D[u] + G[u][v]
if newDv < D[v]: print("Negative cicle",u,v)
return D,P
# From http://www.ics.uci.edu/~eppstein/161/python/dijkstra.py
# David Eppstein, UC Irvine, 4 April 2002
def shortestPath(G,start,end):
"""
Find a single shortest path from the given start vertex to the given end vertex.
The input has the same conventions as Dijkstra().
The output is a list of the vertices in order along the shortest path.
"""
D,P = BellmanFord(G,start)
Path = []
while 1:
Path.append(end)
if end == start: break
end = P[end]
Path.reverse()
return Path
# example, CLR p.528
G = {'s': {'u':10, 'x':5},
'u': {'v':1, 'x':2},
'v': {'y':4},
'x':{'u':3,'v':9,'y':2},
'y':{'s':7,'v':6}}
print(BellmanFord(G,'s'))
print(shortestPath(G,'s','v'))
# modified negative cicle w(u,x) = -4
G = {'s': {'u':10, 'x':1},
'u': {'v':1, 'x':-4},
'v': {'y':4},
'x':{'u':3,'v':9,'y':2},
'y':{'s':7,'v':6}}
print(BellmanFord(G,'s')) |
0baf6338a013fb5c18d4635899e9bca62c8ac13e | ceeblet/OST_PythonCertificationTrack | /Python1/python1/pair_frequency.py | 702 | 4.09375 | 4 | #!/usr/local/bin/python3
"""Count the frequency of each word in a text."""
text = """\
Baa, Baa, Black sheep,
Have you any wool?
Yes sir, yes sir,
Three bags full;
One for the master,
And one for the dame,
And one for the little boy
Who lives down the lane."""
for punc in ",?;.":
text = text.replace(punc, "")
words = {}
textwords = text.lower().split()
firstword = textwords[0]
for nextword in textwords[1:]:
if firstword not in words:
words[firstword] = {}
words[firstword][nextword] = words[firstword].get(nextword, 0)+1
firstword = nextword
for word in sorted(words.keys()):
d = words[word]
for word2 in sorted(d.keys()):
print(word, ":", word2, d[word2]) |
fc410ab22efc69d748cdcc5b4404fcb6d04de345 | shanghongsim/d2w | /mp_calc/app/serverlibrary.py | 4,953 | 3.78125 | 4 |
def mergesort(array, byfunc=None):
p=0
r=len(array)-1
mergesort_recursive(array, p, r, byfunc)
return array
def merge(array, p, q, r, byfunc):
nleft=q-p+1
nright=r-q
left_array=array[p:q+1]
right_array=array[q+1:r+1]
left=0
right=0
dest=p
if byfunc!=None:
while (left < nleft) and (right<nright):
if byfunc(left_array[left])<=byfunc(right_array[right]):
array[dest]=left_array[left]
left+=1
else:
array[dest]=right_array[right]
right+=1
dest=dest+1
while left<nleft:
array[dest]=left_array[left]
left+=1
dest+=1
while right<nright:
array[dest]=right_array[right]
right+=1
dest+=1
return array
else:
while (left < nleft) and (right<nright):
if left_array[left]<=right_array[right]:
array[dest]=left_array[left]
left+=1
else:
array[dest]=right_array[right]
right+=1
dest=dest+1
while left<nleft:
array[dest]=left_array[left]
left+=1
dest+=1
while right<nright:
array[dest]=right_array[right]
right+=1
dest+=1
return array
def mergesort_recursive(array, p, r, byfunc):
if r-p>=1:
q=(p+r)//2
mergesort_recursive(array, p, q, byfunc)
mergesort_recursive(array, q+1, r, byfunc)
merge(array, p, q, r, byfunc)
return array
class Stack:
def __init__(self):
self.__items = []
def push(self, item):
self.__items.append(item)
def pop(self):
if len(self.__items)>=1:
return self.__items.pop()
def peek(self):
if len(self.__items)>=1:
return self.__items[-1]
@property
def is_empty(self):
return self.__items==[]
@property
def size(self):
return len(self.__items)
class EvaluateExpression:
valid_char = '0123456789+-*/() '
operands = "0123456789"
operators = "(+-*/"
def __init__(self, string=""):
self.expression=string
self.stack = Stack()
@property
def expression(self):
return self.expr
@expression.setter
def expression(self, new_expr):
if isinstance(new_expr, str):
for i in new_expr:
if i not in self.valid_char:
self.expr=""
return self.expr
self.expr=new_expr
return self.expr
self.expr=""
return self.expr
def insert_space(self):
res=""
for val in self.expression:
if val in self.operands:
res+=val
else:
res=res+" "+val+" "
return res
def process_operator(self, operand_stack, operator_stack):
right=int(operand_stack.pop())
left=int(operand_stack.pop())
operator=str(operator_stack.pop())
if operator=="+":
res=right+left
elif operator=="-":
res=left-right
elif operator=="*":
res=left*right
else:
res=left//right
operand_stack.push(str(res))
def evaluate(self):
operand_stack = Stack()
operator_stack = Stack()
expression = self.insert_space()
tokens = expression.split()
for val in self.expression:
if val in self.operands:
operand_stack.push(val)
elif val=="+" or val=="-":
while not operator_stack.is_empty and (operator_stack.peek()!="(" and operator_stack.peek()!=")"):
self.process_operator(operand_stack, operator_stack)
operator_stack.push(val)
elif val=="*" or val=="/":
while not operator_stack.is_empty and (operator_stack.peek()=="*" or operator_stack.peek()=="/"):
self.process_operator(operand_stack, operator_stack)
operator_stack.push(val)
elif val=="(":
operator_stack.push(val)
elif val==")":
while operator_stack.peek()!="(":
self.process_operator(operand_stack, operator_stack)
operator_stack.pop()
# print(operand_stack.peek())
# print(operator_stack.peek())
# print("----")
while not operator_stack.is_empty:
self.process_operator(operand_stack, operator_stack)
return int(operand_stack.peek())
def get_smallest_three(challenge):
records = challenge.records
times = [r for r in records]
mergesort(times, lambda x: x.elapsed_time)
return times[:3]
|
9a229513876ae37faa456d45d1676883a4e675b4 | samhita101/Python-Practice | /2number_sum.py | 333 | 3.953125 | 4 | def sum(arg1, arg2 ):
total = arg1 + arg2
print("Inside the function: ", total)
return total
print("Outside the function: ", total)
print("Input the first number")
input1 = int(input())
print("Input the second number")
input2 = int(input())
my_total = sum(input1,input2)
print(my_total, "is outside the function.") |
b73aff94478e72888583ae92c0dfc15b4eb544a5 | OrionSuperman/pylot-login | /app/controllers/Users.py | 1,989 | 3.765625 | 4 | """
Sample Controller File
A Controller should be in charge of responding to a request.
Load models to interact with the database and load views to render them to the client.
Create a controller using this template
"""
from system.core.controller import *
class Users(Controller):
def __init__(self, action):
super(Users, self).__init__(action)
self.load_model('User')
"""
This is an example of loading a model.
Every controller has access to the load_model method.
self.load_model('WelcomeModel')
"""
""" This is an example of a controller method that will load a view for the client """
def index(self):
"""
A loaded model is accessible through the models attribute
self.models['WelcomeModel'].get_all_users()
"""
return self.load_view('index.html')
def create(self):
format_user = {
"first_name" : request.form['first_name'],
"last_name" : request.form['last_name'],
"email" : request.form['email'],
"password" : request.form['password'],
"pw_check" : request.form['pw_check']
}
user_info = self.models['User'].create_user(format_user)
if user_info['status'] == True:
# self.models['User'].create_user(user_info)
return redirect('/users/success')
else:
for message in user_info['errors']:
flash(message, 'regis_errors')
return redirect('/')
def login(self):
user_info = {
'email': request.form['email'],
'password' : request.form['password']
}
user = self.models['User'].validate_user(user_info)
if user['status'] == True:
return redirect('/users/success')
else:
flash('Email or password incorrect.')
return redirect('/')
def success(self):
return self.load_view('success.html') |
20b76f6abbed97812cc7fa7082e31999ef075c3e | aelaguiz/icfp2012 | /lib/map.py | 12,252 | 3.703125 | 4 | ROBOT = 'R'
ROCK = '*'
EMPTY = ' '
LAMBDA = '\\'
OPEN_LIFT='O'
CLOSED_LIFT='L'
EARTH = '.'
MOVE_LEFT='L'
MOVE_RIGHT='R'
MOVE_UP='U'
MOVE_DOWN='D'
MOVE_WAIT='W'
MOVE_ABORT='A'
class Map:
def __init__(self):
self.width = -1
self.height = 0
self.lams = 0
self.map = []
self.died = False
self.done = False
self.changed = False
self.robot_pos = None
def copy(self, old):
self.width = old.width
self.height = old.height
self.lams = old.lams
self.map = []
for old_row in old.map:
new_row = list(old_row)
self.map.append(new_row)
self.done = old.done
self.changed = old.changed
self.robot_pos = old.robot_pos
def addLine(self, line):
# Assumes no trailing newline
if self.width != -1 and len(line) < self.width:
while(len(line)<self.width):
line += EMPTY
elif self.width != -1 and len(line) > self.width:
self.width = len(line)
for row in self.map:
while(len(row)<self.width):
row.append(EMPTY)
else:
self.width = len(line)
row = list(line)
self.map.insert(0, row)
self.height += 1
def init(self):
for (y,row) in enumerate(self.map):
for (x,cell) in enumerate(row):
if cell == ROBOT:
self.robot_pos = (x,y)
#print "Found robot at", self.robot_pos
def __repr__(self):
res = ""
for y in reversed(range(0,self.height)):
row = self.map[y]
for (x,cell) in enumerate(row):
if y == self.robot_pos[1] and x ==\
self.robot_pos[0]:
res += 'H'
#elif cell == 'R':
##print "Got robot at ",x,y,"coords are",self.robot_pos
#res += str(cell)
else:
res += str(cell)
res += "\n"
return res
def valid(self, x,y):
if x>= 0 and x < self.width and\
y >= 0 and y < self.height:
return True
#print x,y,"not valid within",self.width,self.height
return False
def get(self, x,y):
return self.map[y][x]
def set(self,x,y, value):
self.map[y][x] = value
def empty(self,x,y):
return self.valid(x,y) and self.get(x,y) == EMPTY
def not_empty(self,x,y):
return self.valid(x,y) and self.get(x,y) != EMPTY
def rock(self,x,y):
return self.valid(x,y) and self.get(x,y) == ROCK
def lam(self,x,y):
return self.valid(x,y) and self.get(x,y) == LAMBDA
def robot(self,x,y):
return self.valid(x,y) and self.get(x,y) == ROBOT
def lam_count(self):
cnt = 0
for row in self.map:
for cell in row:
if cell == LAMBDA:
cnt += 1
return cnt
def valid_move(self, move):
if move == MOVE_WAIT:
return True
def valid(x,y):
return self.valid(x,y)
def empty(x,y):
return self.empty(x,y)
def rock(x,y):
return self.rock(x,y)
new_pos = self.robot_pos
if(move == MOVE_LEFT):
new_pos = (new_pos[0]-1, new_pos[1])
elif (move == MOVE_RIGHT):
new_pos = (new_pos[0]+1, new_pos[1])
elif(move == MOVE_UP):
new_pos = (new_pos[0], new_pos[1]+1)
elif(move == MOVE_DOWN):
new_pos = (new_pos[0], new_pos[1]-1)
if not valid(new_pos[0], new_pos[1]):
return False
new_cell = self.get(new_pos[0], new_pos[1])
##print "New cell is",new_cell, " at ", new_pos
#(x', y' ) is Empty, Earth, Lambda or Open Lambda Lift.
# - If it is a Lambda, that Lambda is collected.
# - If it is an Open Lambda Lift, the mine is completed
if new_cell == EMPTY or new_cell == EARTH:
return True
elif new_cell == LAMBDA:
return True
elif new_cell == OPEN_LIFT:
return True
# If x' = x + 1 and y' = y (i.e. the Robot moves right), (x'
# ,y') is a Rock, and (x + 2; y) is Empty.
elif new_cell == ROCK and move == MOVE_RIGHT and \
empty(self.robot_pos[0]+2,self.robot_pos[1]):
return True
# If x' = x - 1 and y' = y (i.e. the Robot moves left), (x'
# y') is a Rock, and (x - 2; y) is Empty.
elif new_cell == ROCK and move == MOVE_LEFT and\
empty(self.robot_pos[0]-2,self.robot_pos[1]):
return True
return False
def move(self, move):
# We reset the change flag each tick so it can be used to determine
# if the player action caused the map to be change (rocks fall, etc)
self.changed = False
# A wait move just means tick the map and return
if(move == MOVE_WAIT):
#print "Waiting at", self.robot_pos
self.update()
return True
def valid(x,y):
return self.valid(x,y)
def empty(x,y):
return self.empty(x,y)
def rock(x,y):
return self.rock(x,y)
new_pos = self.robot_pos
#print "Attempting move",move,"from", new_pos
#Move left, L, moving the Robot from (x; y) to (x 1; y).
#Move right, R, moving the Robot from (x; y) to (x + 1; y).
#Move up, U, moving the Robot from (x; y) to (x; y + 1).
#Move down, D, moving the Robot from (x; y) to (x; y 1).
if(move == MOVE_LEFT):
new_pos = (new_pos[0]-1, new_pos[1])
elif (move == MOVE_RIGHT):
new_pos = (new_pos[0]+1, new_pos[1])
elif(move == MOVE_UP):
new_pos = (new_pos[0], new_pos[1]+1)
elif(move == MOVE_DOWN):
new_pos = (new_pos[0], new_pos[1]-1)
# Invalid destination, just fail
if not valid(new_pos[0], new_pos[1]):
#print "New position not valid", new_pos
return False
new_cell = self.get(new_pos[0], new_pos[1])
##print "New cell is",new_cell, " at ", new_pos
#(x', y' ) is Empty, Earth, Lambda or Open Lambda Lift.
# - If it is a Lambda, that Lambda is collected.
# - If it is an Open Lambda Lift, the mine is completed
if new_cell == EMPTY or new_cell == EARTH:
#print "Movement",move,"valid into empty or earthen cell"
# Allow default movement
pass
elif new_cell == LAMBDA:
self.lams += 1
#print "Movement",move,"valid into lambda"
#print "Collected lambda, now have", self.lams
self.changed = True
elif new_cell == OPEN_LIFT:
#print "Mine complete!"
self.done = True
# If x' = x + 1 and y' = y (i.e. the Robot moves right), (x'
# ,y') is a Rock, and (x + 2; y) is Empty.
elif new_cell == ROCK and move == MOVE_RIGHT and \
empty(self.robot_pos[0]+2,self.robot_pos[1]):
# Additionally, the Rock moves to (x + 2; y).
self.set(self.robot_pos[0]+2, self.robot_pos[1], ROCK)
#print "Movement",move,"valid valid pushing rock right"
self.changed = True
# If x' = x - 1 and y' = y (i.e. the Robot moves left), (x'
# y') is a Rock, and (x - 2; y) is Empty.
elif new_cell == ROCK and move == MOVE_LEFT and\
empty(self.robot_pos[0]-2,self.robot_pos[1]):
# Additionally, the Rock moves to (x - 2; y).
self.set(self.robot_pos[0]-2, self.robot_pos[1], ROCK)
#print "Movement",move,"valid valid pushing rock left"
self.changed = True
else:
# This is an invalid move, so we just return
# which prevents the move from actually being taken
# and instead the robot "waits"
#print "Movement",move,"invalid - just waiting at",self.robot_pos
self.update()
#print "After update for wait",self.robot_pos
return True
self.set(self.robot_pos[0], self.robot_pos[1], EMPTY)
self.set(new_pos[0], new_pos[1], ROBOT)
oldpos = self.robot_pos
self.robot_pos = new_pos
self.update()
#print "Took move",move,"from",oldpos,"to",new_pos
return True
def update(self):
newMap = [list(r) for r in self.map]
def valid(x,y):
return self.valid_coord(x,y)
def get(x,y):
return self.get(x,y)
def set(x,y, value):
self.changed = True
newMap[y][x] = value
# Not safe to simply say "not empty" because that may indicate it is an
# invalid cell, not that it is actually unoccupied, must use not_empty
def empty(x,y):
return self.empty(x,y)
def not_empty(x,y):
return self.not_empty(x,y)
def rock(x,y):
return self.rock(x,y)
def lam(x,y):
return self.lam(x,y)
def robot(x,y):
return self.robot(x,y)
def lam_count():
return self.lam_count()
lams = lam_count()
for (y,row) in enumerate(self.map):
for (x,cell) in enumerate(row):
# If (x; y) contains a Rock, and (x; y - 1) is Empty:
if cell == ROCK and empty(x,y-1):
# (x; y) is updated to Empty, (x; y - 1) is updated to Rock
#print "Rock at",x,y,"fell"
set(x,y, EMPTY)
set(x,y-1, ROCK)
if robot(x,y-2):
#print "Killed the robot!"
self.died = True
#If (x; y) contains a Rock, (x; y - 1) contains a Rock, (x +
# 1; y) is Empty and (x + 1; y - 1) is Empty:
if cell == ROCK and rock(x,y-1) and empty(x+1,y) and\
empty(x+1,y-1):
#(x; y) is updated to Empty, (x + 1; y - 1) is updated to
#Rock
#print "Rock at",x,y,"slid to the right and down"
set(x,y, EMPTY)
set(x+1,y-1, ROCK)
if robot(x+1,y-2):
#print "Killed the robot!"
self.died = True
#If (x; y) contains a Rock, (x; y - 1) contains a Rock, either (x
# + 1; y) is not Empty or (x + 1; y - 1) is not Empty,
# (x - 1; y) is Empty and (x - 1; y - 1) is Empty
if cell == ROCK and rock(x,y-1) and (not_empty(x+1,y) or\
not_empty(x+1,y-1)) and empty(x-1,y) and empty(x-1,y-1):
# (x; y) is updated to Empty, (x - 1; y - 1) is updated to
# Rock.)
#print "Rock at",x,y,"slid to the left and down"
set(x,y, EMPTY)
set(x-1,y-1,ROCK)
if robot(x-1,y-2):
#print "Killed the robot!"
self.died = True
#If (x; y) contains a Rock, (x; y - 1) contains a Lambda, (x + 1; y)
# is Empty and (x + 1; y - 1) is Empty:
if cell == ROCK and lam(x,y-1) and empty(x+1,y) and\
empty(x+1,y-1):
#(x; y) is updated to Empty, (x + 1; y - 1) is updated to Rock.
#print "Rock at ",x,y,"fell down the right side of lambda"
set(x,y,EMPTY)
set(x+1,y-1,ROCK)
if robot(x+1,y-2):
#print "Killed the robot!"
self.died = True
# If (x; y) contains a Closed Lambda Lift, and there are no
# Lambdas remaining:
if cell == CLOSED_LIFT and lams == 0:
# (x; y) is updated to Open Lambda Lift.
set(x,y,OPEN_LIFT)
self.map = newMap
|
f6943e6437b955551d37de2f8874d09225c3c23c | athulpa/ANN | /ANN.py | 3,251 | 3.703125 | 4 |
import numpy as np
# When giving theta inputs to neural network, always make sure that every theta is 2-dim,
# even if its output is only 1 number. For example, [[1, 2, 3]] is correct, [1, 2, 3] is wrong.
class ANN:
def __init__(self, sl):
self.num_layers = len(sl)
self.num_inputs = sl[1]
self.num_outputs = sl[-1]
self.theta = [ ]
self.activation = ANN.sigmoid
for i in range(self.num_layers-1):
self.theta.append(np.random.random((sl[i+1], sl[i]+1))-0.5)
return
def sigmoid(arr):
return 1/(1+np.exp(-arr))
def relu(arr):
return np.where(arr<0, np.zeros(arr.shape), arr)
def fpgt(self, arr):
# print('inside')
for th in self.theta:
arr = np.insert(arr, 0, 1)
# print(th, arr)
arr = np.matmul(th, arr)
# print(arr)
arr = self.activation(arr)
# print(arr.shape, '\n')
# print('leaving..')
return arr
# Returns the D values computed on self.theta with the given single exmaple of ins and outs.
def bpgt(self, ins, outs):
a = [ ins ]
for th in self.theta:
a[-1] = np.insert(a[-1], 0, 1)
dotted = np.matmul(th, a[-1])
a.append(self.activation(dotted))
d = [ a[-1]-outs ]
for i in np.flip(np.arange(1, self.num_layers-1), axis=0):
d.insert(0, (np.matmul(self.theta[i].T, d[0])*a[i]*(1-a[i]))[1:])
D = [ ]
for i in range(self.num_layers-1):
D.append(d[i].reshape(-1, 1)*a[i])
return D
# arrs is expected to be 2D only, with elements arranged along axis-0.
def fpbatch(self, arrs):
for th in self.theta:
arrs = np.insert(arrs, 0, 1, 1)
arrs = np.matmul(arrs, th.T)
arrs = self.activation(arrs)
return arrs
# Performs one step of the backprop update (i.e. 1 step of GD), given m examples of i/o values.
# Examples must be placed down the column, ie along axis 0.
def bpbatch(self, ins, outs, alpha=0.05, lmd=0.1):
a = [ins]
for th in self.theta:
# print(a[-1].shape)
a[-1] = np.insert(a[-1], 0, 1, 1)
# print(a[-1].shape)
# print(th.T.shape)
dotted = np.matmul(a[-1], th.T)
# print(dotted.shape)
a.append(self.activation(dotted))
# print(a[-1].shape, '\n')
# input()
d = [ a[-1]-outs ]
for i in np.flip(np.arange(1, self.num_layers-1), axis=0):
d.insert(0, (np.matmul(d[0], self.theta[i])*a[i]*(1-a[i]))[:, 1:])
# for dee in d:
# print(dee.shape)
# print('\n')
# for ayy in a:
# print(ayy.shape)
# print('\n')
for i in range(self.num_layers-1):
# print(i)
Dtmp = np.expand_dims(d[i], 2)*np.expand_dims(a[i], 1)
Dtmp = np.sum(Dtmp, axis=0)
# print(Dtmp.shape, self.theta[i].shape, '\n')
Dtmp += lmd*self.theta[i]
self.theta[i] -= alpha*Dtmp
return
|
42937a3510f632558d17a888636849b19bc8eef1 | lvguichen1/algorithm004-02 | /Week 03/id_472/深度优先搜索和广度优先搜索/LeetCode_102_472.py | 1,823 | 3.859375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# @Time : 2020/3/18
# @Author : xujun
"""
二叉树的层次遍历
给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
"""
# 递归
class Solution:
def levelOrder(self, root):
def helper(root, level):
if not root:
return
if len(res) == level:
res.append([])
res[level].append(root.val)
if root.left:
helper(root.left, level + 1)
if root.right:
helper(root.right, level + 1)
res = []
helper(root, 0)
return res
# 迭代
from collections import deque
class Solution:
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
levels = []
if not root:
return levels
level = 0
queue = deque([root, ])
while queue:
# start the current level
levels.append([])
# number of elements in the current level
level_length = len(queue)
for i in range(level_length):
node = queue.popleft()
# fulfill the current level
levels[level].append(node.val)
# add child nodes of the current level
# in the queue for the next level
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
# go to next level
level += 1
return levels
|
53d3ac13471aeba08f87db7d10d28f067b4a6ff6 | minlu1021/graph-theory-course | /PS1/bipartite.py | 3,412 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed May 31 12:44:56 2017
@author: lu
"""
from collections import deque
import networkx
import sys
class bipartite(object):
def uncolored(self, node):
"""
Determine if this node is colored
uncolored--return True
colored----return False
"""
if node not in self.colorings['black'] and node not in self.colorings['white']:
return True
else:
return False
def changeColor(self, node):
"""
Change the color of node
if it is black, change to white
if it is white, change to black
"""
if node in self.colorings['black']:
return 'white'
elif node in self.colorings['white']:
return 'black'
def canColor(self, node, color):
"""
Determine if this node can be colored with given color
can be colored with color--True
else-----------------------False
"""
neighbors = self.G[node].keys() # get all neighbors of the node
return all([neighbor not in self.colorings[color] for neighbor in neighbors])
def isBipartite(self, G):
"""
If graph G is partite--True
If G is not partite----False
"""
self.G = G
self.colorings = {'black': set(), 'white': set()}
start = G.nodes()[0] # the first node as initial node to start
self.colorings['black'].add(start) # Once got the node, color black
q = deque([start])
while q:
n = q.pop()
next_color = self.changeColor(n)
# get the neighbors who are not colored
uncolored_neighbors = []
for neighbor in G[n].keys():
if self.uncolored(neighbor):
uncolored_neighbors.append(neighbor)
for neighbor in uncolored_neighbors:
# if this neighbor can be colored with given node,
# just color it and add this neighbor to q
if self.canColor(neighbor, next_color):
self.colorings[next_color].add(neighbor)
q.append(neighbor)
# if can not be colored, then this graph is non-bipartite
else:
return False
# if not false, then G is partite
return True
if __name__ == '__main__':
"""Main Part"""
# get the nodes and edges from txt file
file = open(sys.argv[-1],"r")
lineList = file.readlines()
file.close()
s = ""
for x in lineList[-1]:
if x==",":
break
s += str(x)
n = int(s) +1 # number of nodes in G
G = networkx.Graph()
## add nodes to the graph G
G.add_nodes_from([node for node in range(1, n+1)])
## get the edges between nodes
edges = []
for line in lineList:
s = line.split(",")
relation = [int(x) for x in s]
# when they have edges, i append the connected to node to edges list.
if relation[-1]==1:
edges.append((relation[0],relation[1]))
## add edges to the graph G
G.add_edges_from(edges)
## get the result
print('Whether graph G is bipartite:', bipartite().isBipartite(G)) |
fd1d55aab67bcd8ea61946e4e248a80a4bb31d7d | Ranjit007ai/InterviewBit-LinkedList | /linkedlist/remove_nth_node_from_end/solution.py | 1,059 | 3.765625 | 4 | # Given a linked list ,remove the nth node from the end of the list ,return its head.
# If the 'n' is greater then length of the list ,delete first node of list.
class Node:
def __init__(self,data):
self.data = data
self.next = None
node1 = Node(1)
node2 = Node(3)
node3 = Node(4)
node4 = Node(5)
node5 = Node(11)
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
def length(head):
cur = head
count = 1
while cur != None :
cur = cur.next
count += 1
return count
def remove_nth_node_from_end(head,n):
l = length(head)
if l <= n :
head = head.next
else:
i = head
j = head
for k in range(0,n-1):
j = j.next
while j.next.next != None:
i = i.next
j = j.next
i.next = i.next.next
return head
# test case
new_head = remove_nth_node_from_end(node1,2)
while new_head != None :
print(new_head.data,end=' ')
new_head = new_head.next
|
4ec5336c38dd27bbc4b81175da93efa537c3c2ff | Aasthaengg/IBMdataset | /Python_codes/p02713/s228418271.py | 178 | 3.609375 | 4 | import math
K = int(input())
Sum = 0
for A in range(1,K+1):
for B in range(1,K+1):
for C in range(1,K+1):
Sum = Sum+math.gcd(math.gcd(A,B),C)
print(Sum) |
978c3fd6da8c8f0016a78e5956e428d200fd7ee3 | sam449/programmereninpython1 | /.py/ifstatement.py | 134 | 3.609375 | 4 | varA - 5
if (varA == 5):
print("varA stast gelijk aan 5")
else :
print("varA staat niet gelijk aan 5")
print("Einde programma") |
6ba9572f0ebe5cede7b2b10b4807779c051a194c | jpaguirre15/pythons | /Experiment Answers, Formats, Output Samples/Answers/Python 3 Answers/practiceRound.py | 423 | 4.125 | 4 | # Hint:
# Use "print(type(<variable>))" to figure out data type for a variable,
# like shown below
str1 = 'Execute Order '
int1 = 66
print("str1 data type: ", type(str1))
print("int1 data type: ", type(int1))
# CODE HERE
print("str1 data type (after conversion): ", type(str1))
print("int1 data type (after conversion): ", type(str(int1)))
print(str1 + str(int1))
print("Combined data type: ", type(str1 + str(int1)))
|
04f89a911ca639195e7657cddfe878f9df97692b | Yoni-Mantzur/University-Projects | /Image Processing/sol2/sol2.py | 6,794 | 3.5 | 4 | import numpy as np
from scipy import signal
from scipy.misc import imread as imread
from skimage.color import rgb2gray
import matplotlib.pyplot as plt
GRAY_REP = 1
L_INTESITY = np.float32(255)
D_X_CONV = np.array([1, 0, -1]).reshape(1,3).astype(np.float32)
D_Y_CONV = D_X_CONV.T
I, PI = np.complex128(0+1j), np.pi
BASICE_GAUSSIAN = np.array([1,1,1,1]).reshape(2,2)
def im_to_float(image):
"""
Convert image to float32 values between [0,1]
"""
return image.astype(np.float32) / L_INTESITY
def read_image(filename, representation):
"""
The function that reads a given image file and converts it into a given representation.
:param - filename - string containing the image filename to read.
:param - representation - representation code, either 1 or 2
defining if the output should be either a grayscale OR RGB image respectively
:return - The new image.
"""
try:
im = imread(filename)
if representation == GRAY_REP:
return rgb2gray(im).astype(np.float32)
return im_to_float(im)
except:
print("Cant read the image")
exit(-1)
def dft_mat(N):
"""
:param N: Dimension of dft
:return: the dft matrix
"""
range = np.arange(N).astype(np.complex128)
exp = np.exp((-2*PI*I*range)/N).astype(np.complex128)
return np.vander(exp, increasing=True).astype(np.complex128)
def DFT(signal):
"""
Function that transform a 1D discrete signal to its Fourier representation
:param signal - an array of dtype float32 with shape (N,1)
:return fourier_signal - an array of dtype complex128 with the same shape
"""
N = signal.shape[0]
fourier_signal = np.dot(dft_mat(N), signal)
return fourier_signal.astype(np.complex128)
def IDFT(fourier_signal):
"""
Function that transform a 1D discrete Fourier to its signal representation
:param signal - an array of dtype complex128 with shape (N,1)
:return fourier_signal - an array of dtype complex128 with the same shape
"""
N = fourier_signal.shape[0]
# Notice that inverse furier is the conj of the furier
signal = np.dot(np.conj(dft_mat(N)), fourier_signal) / N
return signal.astype(np.complex128)
def func2D(narray, func):
"""
Operates func on rows and then on columns
:param narray: 2D array N * M
:param func: Unary function to operate on 1D arr
:return: 2D array after operates func
"""
N, M = narray.shape
newArray = narray.copy().astype(np.complex128)
# transform of rows
j=0
for row in narray:
newArray[j,:] = func(row.reshape(M,1)).reshape(M)
j+=1
k = 0
for column in newArray.T:
newArray[:,k] = func(column.reshape(N,1)).reshape(N)
k+=1
return newArray
def DFT2(image):
"""
Function that convert a 2D discrete signal to its Fourier representation
:param image: 2D signal
:return fourier_signal - an array of dtype complex128 with the same shape
"""
return func2D(image, DFT)
def IDFT2(image):
"""
Function that convert a 2D discrete signal to its inverse Fourier representation
:param image: 2D signal
:return fourier_signal - an array of dtype complex128 with the same shape
"""
return func2D(image, IDFT)
def conv_im(im, conv_vector):
"""
Convolution with image.
:param im: some image
:param conv_vector: conv vector
:return: the convolution
"""
return signal.convolve2d(im, conv_vector, mode='same')
def conv_der(im):
"""
A function that computes the magnitude of image derivatives
:param im: a grayscale images of type float32.
:return: a grayscale images of type float32.
"""
dx = conv_im(im, D_X_CONV)
dy = conv_im(im, D_Y_CONV)
mag = np.sqrt(np.abs(dx)**2 + np.abs(dy)**2)
return mag
def fourier_der(im):
"""
A function that computes the magnitude of image derivatives using Fourier transform.
:param im: are float32 grayscale images
:return: are float32 grayscale images
"""
furier_im = DFT2(im)
furier_im_shift = np.fft.fftshift(furier_im)
N, M = im.shape
range_y = np.arange(-N/2,N/2)
range_x = np.arange(-M/2,M/2)
dx = (2*I*PI/N)*(IDFT2(np.multiply(furier_im_shift,range_x)))
dy = (2*I*PI/N)*(IDFT2(np.multiply(furier_im_shift.T,range_y).T))
mag = np.sqrt(np.abs(dx)**2 + np.abs(dy)**2)
return mag.astype(np.float32)
def creat_kernel(kernel_size):
"""
Generates Gaussian kernel.
:param kernel_size: the size of the gaussian kernel in each dimension (an odd integer).
:return: 2D kernel (as float32 type)
"""
if kernel_size <= 1:
return np.array([1])
kernel = BASICE_GAUSSIAN.astype(np.float32)
for i in range(kernel_size-2):
kernel = signal.convolve2d(kernel, BASICE_GAUSSIAN)
norm_kernel = kernel / np.sum(kernel)
return norm_kernel.astype(np.float32)
def blur_spatial (im, kernel_size):
"""
Function that performs image blurring using 2D convolution between the image f and a gaussian
kernel g.
:param im: image to be blurred (grayscale float32 image).
:param kernel_size: the size of the gaussian kernel in each dimension (an odd integer).
:return: blurry image (grayscale float32 image).
"""
return signal.convolve2d(im, creat_kernel(kernel_size), mode='same', boundary='wrap')
def pad_kernel(kernel, kernel_size, im_shape):
"""
Padding the kernel to image size with zeroes
:param kernel: the kenel to pad
:param kernel_size: the size of the kernel before padding
:param im_shape: the shape of the image
:return: the padding kernel
"""
size_x_im, size_y_im = im_shape
padding = ((0, np.abs(size_x_im-kernel_size)), (0, np.abs(size_y_im-kernel_size)))
KERNEL_pading = np.lib.pad(kernel, padding, 'constant', constant_values=np.complex128(0))
# Move the kernel to center
KERNEL_pading = np.roll(KERNEL_pading, int((size_x_im-kernel_size)/2 + 1), axis=0)
KERNEL_pading = np.roll(KERNEL_pading, int((size_y_im-kernel_size)/2 + 1), axis=1)
return KERNEL_pading
def blur_fourier(im, kernel_size):
"""
Function that performs image blurring with gaussian kernel in Fourier space.
:param im: image to be blurred (grayscale float32 image).
:param kernel_size: is the size of the gaussian in each dimension (an odd integer).
:return: is the output blurry image (grayscale float32 image).
"""
kernel = creat_kernel(kernel_size).astype(np.complex128)
KERNEL_pading = pad_kernel(kernel, kernel_size, im.shape)
KERNEL_ishifted = np.fft.ifftshift(KERNEL_pading)
# Use the convolution theorem
KERNEL, IM = DFT2(KERNEL_ishifted), DFT2(im)
mult_ker_im = np.multiply(IM, KERNEL)
return np.real(IDFT2(mult_ker_im)).astype(np.float32)
|
3bff36a0910afbf4262b89084dcd8cc93075aac7 | jcravener/PythonWorkroom | /DuplicateZeros.py | 502 | 3.59375 | 4 |
# LeetCode 1089. Duplicate Zeros
class Solution:
def duplicateZeros(self, arr: [int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
alen = len(arr)
tmp =[0]
i = 0
while i < alen:
if arr[i] == 0:
arr.insert(i+1, 0)
arr.pop()
i += 1
i += 1
print(arr)
s = Solution()
a = [1,0,2,3,0,4,5,0]
s.duplicateZeros(a)
print(a) |
943d1586bad96fa419eadb5d6b1d1570dd5b818f | alonzo0812/random-games-shs | /Hangman.py | 1,362 | 3.953125 | 4 | import time
import random
name = input("WHATS YO NAME? ")
print ("HELLO, " + name, "TIME TO PLAY HANGMAN BY LEOO!")
print ("")
time.sleep(1)
print ("LETS GOOO")
time.sleep(1)
word = random.randint(1,12)
if word == 1:
word = "LEOMARC"
elif word == 2:
word = "GIBSON"
elif word == 3:
word = "GAB"
elif word == 4:
word = "TERENCE"
elif word == 5:
word = "TRISHA"
elif word == 6:
word = "PAT"
elif word == 7:
word = "CHAPONK"
elif word == 8:
word = "JEAN"
elif word == 9:
word = "CLOTHES"
elif word == 10:
word = "DOMINATION"
elif word == 11:
word = "ALISSHA"
elif word == 12:
word = "KHRYSTAL"
guesses = ""
turns = 14
while turns > 0:
failed = 0
for char in word:
if char in guesses:
print (char,end=""),
else:
print ("-",end=""),
failed += 1
if failed == 0:
print("")
print ("You won")
break
print("")
guess = input("guess a character:").upper()
guesses += guess
if guess not in word:
turns -= 1
print ("Wrong")
print ("You have", + turns, "more guesses")
if turns == 0:
print ("You Loose")
|
64a84e7cd1e8654d500b7d987e1d44e10199381e | Vasudevatirupathinaidu/Python-Crash-Course-2nd-Edition-by-Eric-Matthes | /Chapter_06 Dictionaries/exercise.py | 6,269 | 4.1875 | 4 | # Person
person = {
'first_name' : 'Vasudeva',
'last_name' : 'Bonu',
'age' : 27,
'city' : 'Bangalore',
}
print(f"Hola! My name is {person['last_name']} {person['first_name']}. I am {person['age']} years old guy lives in {person['city']}.")
print("\n")
# Favorite numbers
persons = {
'ching' : 5,
'chang' : 6,
'chung' : 1,
'ding' : 9,
'ping' : 1,
'dang' : 4,
}
# Method 1
print(f"Hi! My name is ching. My favorite number is {persons['ching']}.")
print(f"Hi! My name is chang. My favorite number is {persons['chang']}.")
print(f"Hi! My name is chung. My favorite number is {persons['chung']}.")
print(f"Hi! My name is ding. My favorite number is {persons['ding']}.")
print(f"Hi! My name is ping. My favorite number is {persons['ping']}.")
print(f"Hi! My name is dang. My favorite number is {persons['dang']}.")
print("\n")
# Method 2 - for loop
for key, value in persons.items():
print(f"Hi! My name is {key.title()}. My favorite number is {value}.")
print("\n")
# Method 3 - list comprehension
[print(f"Hi! My name is {key.title()}. My favorite number is {value}.") for key, value in persons.items()]
print('\n')
print('\n'.join([(f"Hi! My name is {key.title()}. My favorite number is {value}.") for key, value in persons.items()]))
print("\n")
# Glossary
glossary = {
'string' : 'A series of characters.',
'list' : 'A collection of items.',
'method' : 'A method is an action that python can perform on a piece of data.',
'if-elif-else' : 'if-elif-else statement chains are used for decision making.',
'for_loop' : 'For loops are used for sequential traversal.',
'dictionary' : 'A collection of key-value pairs.',
'get method' : 'It can add a default value to key.',
'set' : 'It can remove duplicate values.',
'in and not' : 'in and not are special keywords, mainly used for decision making.',
}
# Method 1
print(f"String: {glossary['string']}")
print(f"List: {glossary['list']}")
print(f"Method: {glossary['method']}")
print(f"if-elif-else: {glossary['if-elif-else']}")
print(f"for_loop: {glossary['for_loop']}")
print(f"dictionary: {glossary['dictionary']}")
print(f"get method: {glossary['get method']}")
print(f"set: {glossary['set']}")
print(f"in and not: {glossary['in and not']}")
# Method 2 - for loop
for key, value in glossary.items():
print(f"{key.title()}: {value}")
print("\n")
# Method 3 - list comprehension
[print(f"{key.title()}: {value}") for key, value in glossary.items()]
print("\n")
print('\n'.join([(f"{key.title()}: {value}") for key, value in glossary.items()]))
print("\n")
# Rivers
rivers = {
'krishna' : 'vijayawada',
'yamuna' : 'agra',
'kaveri' : 'tiruchirapalli',
}
for river, city in rivers.items():
print(f"The {river} river runs through {city}.")
print("\n")
for river in rivers.keys():
print(river)
print("\n")
for city in rivers.values():
print(city)
print("\n")
# Polling
favorite_languages = {
'jen' : 'python',
'sarah' : 'c',
'edward' : 'ruby',
'phil' : 'python',
}
members = ['phil', 'daniel', 'edward', 'erin', 'sarah']
for member in members:
if member in favorite_languages.keys():
print(f"{member.title()}, thank you for taking the poll.")
else:
print(f"{member.title()}, please take our poll.")
print("\n")
# People
person_1 = {
'first_name' : 'vasu',
'last_name' : 'bonu',
'age' : 27,
'city' : 'bangalore',
}
person_2 = {
'first_name' : 'deva',
'last_name' : 'bonu',
'age' : 26,
'city' : 'gurgaon',
}
person_3 = {
'first_name' : 'tiru',
'last_name' : 'bonu',
'age' : 25,
'city' : 'bangalore',
}
people = [person_1, person_2, person_3]
for person in people:
print(person)
print("\n")
# Pets
pet_1 = {
'owner_s name': 'vasu',
'pet_s name': 'DogA',
}
pet_2 = {
'owner_s name': 'deva',
'pet_s name': 'DogB',
}
pet_3 = {
'owner_s name': 'tiru',
'pet_s name': 'DogC',
}
pet_4 = {
'owner_s name': 'naidu',
'pet_s name': 'DogD',
}
pets = [pet_1, pet_2, pet_3, pet_4]
for pet in pets:
print(f"Pet Owner's name: {pet['owner_s name']}")
print(f"Pet's name: {pet['pet_s name']}\n")
# Favorite places
favorite_places = {
'deva':['goa', 'kochi', 'udupi'],
'vasu':['kochi', 'araku', 'shillong'],
'tiru':['udupi', 'ladakh', 'west godavari'],
}
for names, places in favorite_places.items():
for place in places:
print(f"{(names.title())}'s favorite place is {place.title()}.")
print("\n")
# Favorite numbers
persons = {
'ching' : [5, 2, 9],
'chang' : [6, 1],
'chung' : [1, 8, 7],
'ding' : [9, 3, 6],
'ping' : [1, 2],
'dang' : [4, 0],
}
for names, numbers in persons.items():
for number in numbers:
print(f"{names.title()}'s favorite number is {number}.")
print("\n")
# Cities
cities = {
'vizag': {
'country': 'india',
'population': '21 lakhs',
'favoriteSpot': 'beach',
},
'bangalore': {
'country': 'india',
'population': '84 lakhs',
'favoriteSpot': 'bangalore palace',
},
'rajahmundry': {
'country': 'india',
'population': '4 lakhs',
'favoriteSpot': 'godavari arch bridge',
},
}
for name, data in cities.items():
print(f"City name {name.title()}: ")
for info, data_2 in data.items():
print(f"{info.title()}: {data_2.title()}")
print("\n")
# Extensions
favorite_languages = {
'jen' : 'c++',
'sarah' : 'c',
'edward' : 'ruby',
'phil' : 'javascript',
}
new_members = ['david', 'lucy', 'john']
for member in new_members:
if member == 'lucy':
favorite_languages[member] = 'go'
elif member == 'john':
favorite_languages[member] = 'java'
elif member == 'david':
favorite_languages[member] = 'python'
print(f"\nList of names: ")
for name in favorite_languages.keys():
print(f"{name.title()}")
print(f"\nList of languages: ")
for language in favorite_languages.values():
print(f"{language.title()}")
print("\n")
for name, language in favorite_languages.items():
print(f"{name.title()}'s favorite language is {language.title()}")
print("\n") |
e8e89987cdcef0b4fb87f074246d3f37bd66402d | allenxun/study | /python/leetcode/easy/053Pascal'sTriangleII.py | 757 | 3.59375 | 4 | class Solution(object):
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
def get(t):
result = [1]
left = 1
for i in range(1,len(t)):
result.append(left+t[i])
left = t[i]
result.append(1)
return result
result = []
if rowIndex == 0:
result = [1]
elif rowIndex == 1:
result = [1,1]
else:
result.append([1,1])
for i in range(rowIndex):
result = (get(result))
return result
if __name__ =="__main__":
a = Solution()
test = [1,2,3,5,0]
for i in test:
print a.getRow(i)
|
712e275a5a0cb8a4ff8bb704a1a209ea90a17612 | laravignotto/books_exercises | /Bioinformatics_Algorithms_An_Active_Learning_Approach/chapter-1/problem_1B.py | 3,500 | 4.125 | 4 | '''
Frequent Words Problem: Find the most frequent k-mers in a string.
Input: A string Text and an integer k.
Output: All most frequent k-mers in Text.
'''
from tqdm import tqdm
from utils import *
from problem_1A import * # pattern_count
from problem_1L import * # pattern_to_number
from problem_1M import * # number_to_pattern
def frequent_words(text, k):
'''(Slowly) finds the most frequent k-mer in `text`
Parameters
----------
text : str
Input text
k : int
Length of the k-mer
Returns
-------
frequent_patterns : set
The most frequent string(s) of length k that appear in `text`
'''
frequent_patterns = []
count = [0] * (len(text)-k+1)
for i in tqdm(range(len(text)-k+1)):
pattern = text[i:k+i]
count[i] += pattern_count(text, pattern)
max_count = max(count)
for i in range(len(text)-k+1):
if count[i] == max_count:
frequent_patterns.append(text[i:k+i])
return set(frequent_patterns)
def computing_frequencies(text, k):
'''Generates a frequency array
Parameters
----------
text : str
Input text
k : int
Length of the k-mer (pattern)
Returns
-------
frequentcy_array : list
Array in which every element is an integer denoting how many
times each pattern of length `k` (specified by the index of the
array) appears in `text`
'''
frequency_array = [0] * 4**k
for i in tqdm(range(len(text)-k+1)):
pattern = text[i:k+i]
j = pattern_to_number(pattern)
frequency_array[j] += 1
return frequency_array
def faster_frequent_words(text, k):
'''Finds the most frequent k-mer in `text`
Parameters
----------
text : str
Input text
k : int
Length of the k-mer
Returns
-------
frequent_patterns : set
The most frequent string(s) of length k that appear in `text`
'''
frequent_patterns = []
frequency_array = computing_frequencies(text, k)
max_count = max(frequency_array)
for i in range(len(frequency_array)):
if frequency_array[i] == max_count:
pattern = number_to_pattern(i,k)
frequent_patterns.append(pattern)
return set(frequent_patterns)
def main():
# txt = import_txt("Vibrio_cholerae")[0]
# txt = "ACTGACTCCCACCCC" # k = 3 -> 'CCC'
# txt = "ACAACTATGCATACTATCGGGAACTATCCT" # k = 5 -> 'ACTAT'
# txt = "CGATATATCCATAG" # k = 3 -> 'ATA'
txt = "ATCAATGATCAACGTAAGCTTCTAAGCATGATCAAGGTGCTCACACAGTTTATCCACAACCTGAGTGGATGACATCAAGATAGGTCGTTGTATCTCCTTCCTCTCGTACTCTCATGACCACGGAAAGATGATCAAGAGAGGATGATTTCTTGGCCATATCGCAATGAATACTTGTGACTTGTGCTTCCAATTGACATCTTCAGCGCCATATTGCGCTGGCCAAGGTGACGGAGCGGGATTACGAAAGCATGATCATGGCTGTTGTTCTGTTTATCTTGTTTTGACTGAGACTTGTTAGGATAGACGGTTTTTCATCACTGACTAGCCAAAGCCTTACTCTGCCTGACATCGACCGTAAATTGATAATGAATTTACATGCTTCCGCGACGATTTACCTCTTGATCATCGATCCGATTGAAGATCTTCAATTGTTAATTCTCTTGCCTCGACTCATAGCCATGATGAGCTCTTGATCATGTTTCCTTAACCCTCTATTTTTTACGGAAGAATGATCAAGCTGCTGCTCTTGATCATCGTTTC" # oriC of Vibrio Cholerae
k = int(input("Insert a number `k`: "))
print("Searching...")
# Uncomment just one of the lines below
# fp = frequent_words(txt, k) # WARNING: inefficient
fp = faster_frequent_words(txt, k)
print(
f"The most frequent pattern(s) of length {k} that appear(s) in the text is/are:")
for i in fp:
print(i)
if __name__ == "__main__":
main()
|
5a05bda6a948d93ca53efd3ce10379d351622236 | zeelp741/Data-Strucutures | /Stack_array.py | 6,844 | 4 | 4 | from copy import deepcopy
class Stack:
"""
-------------------------------------------------------
Constants
-------------------------------------------------------
"""
# a default maximum size when one is not provided
DEFAULT_SIZE = 10
def __init__(self, max_size = DEFAULT_SIZE):
"""
-------------------------------------------------------
Initializes an empty stack. Data is stored in a
fixed-size Python list.
Use: stack = Stack(max_size)
Use: stack = Stack() # uses default max size
-------------------------------------------------------
Parameters:
max_size - maximum size of the Stack (int > 0)
Returns:
a new Stack object (Stack)
-------------------------------------------------------
"""
assert max_size > 0, "Queue size must be > 0"
self._capacity = max_size
self._values = [None] * self._capacity
self._top = -1
def isEmpty(self):
"""
-------------------------------------------------------
Determines if the stack is empty.
Use: b = stack.is_empty()
-------------------------------------------------------
Returns:
True if stack is empty, False otherwise
-------------------------------------------------------
"""
return self._top == -1
def isFull(self):
"""
-------------------------------------------------------
Determines if the stack is full.
Use: b = stack.isFull()
-------------------------------------------------------
Returns:
True if stack is full, False otherwise
-------------------------------------------------------
"""
status = False
if self._top == self._capacity:
status = True
return status
def push(self, element):
"""
-------------------------------------------------------
Pushes a copy of the given element onto the top of the
stack.
Use: stack.push(element)
-------------------------------------------------------
Parameters:
element - the data element to be added to stack (?)
Returns:
None
-------------------------------------------------------
"""
assert not self.isFull(), "Stack is full"
self._top += 1
self._values[ self._top ] = deepcopy( element )
return
def pop(self):
"""
-------------------------------------------------------
Pops and returns the top of stack. The data element is
removed from the stack. Attempting to pop from an empty
stack throws an exception.
Use: value = stack.pop()
-------------------------------------------------------
Returns:
value - the value at the top of stack (?)
-------------------------------------------------------
"""
value = deepcopy(self._values[ self._top ])
self._top -=1
return value
def peek(self):
"""
-------------------------------------------------------
Returns a copy of the value at the top of the stack without
removing it.
Attempting to peek at an empty stack throws an exception.
Use: value = stack.peek()
-------------------------------------------------------
Returns:
value - a copy of the value at the top of stack (?)
-------------------------------------------------------
"""
element = deepcopy(self._values[self._top])
return element
def reverse(self):
"""
-------------------------------------------------------
Reverses the contents of the source stack.
Use: source.reverse()
-------------------------------------------------------
Returns:
None
-------------------------------------------------------
"""
#your code goes here
def combine(self, source1, source2):
"""
-------------------------------------------------------
Combines two source stacks into the current target stack.
When finished, the contents of source1 and source2 are
interlaced into target and source1 and source2 are empty.
(iterative algorithm)
Use: target.combine(source1, source2)
-------------------------------------------------------
Parameters:
source1 - an array-based stack (Stack)
source2 - an array-based stack (Stack)
Returns:
None
-------------------------------------------------------
"""
while source1._top >= 0 and source2._top >= 0:
self.push(source1.pop())
self.push(source2.pop())
while source1._top >= 0:
self.push(source1.pop())
while source2._top >= 0:
self.push(source2.pop())
return
def split_alt(self):
"""
-------------------------------------------------------
Splits the source stack into two separate target stacks
with values alternating into the targets. At finish
source stack is empty.
Use: target1, target2 = source.split_alt()
-------------------------------------------------------
Returns:
target1 - contains alternating values from source (Stack)
target2 - contains other alternating values from source (Stack)
-------------------------------------------------------
"""
target1 = Stack()
target2 = Stack()
alternating = 0
while(self._top != -1):
alternating += 1
if alternating % 2 == 0:
target2.push(self._values[self._top])
elif (alternating % 2 == 1):
target1.push(self._values[self._top])
self._top -= 1
return target1, target2
def __iter__(self):
"""
FOR TESTING ONLY
-------------------------------------------------------
Generates a Python iterator. Iterates through the stack
from top to bottom.
Use: for value in stack:
-------------------------------------------------------
Returns:
value - the next value in the stack (?)
-------------------------------------------------------
"""
for value in self._values[::-1]:
yield value
|
d8a97e61e5a04c88a18196522eee60e905bd3593 | eduardomep/SpartanStore-Server | /User.py | 637 | 3.546875 | 4 | class User:
def __init__(self,id,name,last_name,user_name,password,user_type):
self.id = id
self.name = name
self.last_name = last_name
self.user_name = user_name
self.password = password
self.user_type = user_type
# def auth (self,user_name,password):
# if self.user_name == user_name and self.password == password:
# print("Bienvenido")
# return True
# print("Datos erroneos")
# return False
# def get_password (self,user_name):
# if self.user_name == user_name:
# return True
# return False
|
91c29e1854db627b0ce8e1ac149a9cf7713b624d | jatingandhi32/Python-1BM17CS032 | /Lab3/string.py | 142 | 3.71875 | 4 |
sentence = input("Enter the sentence")
lis =[]
for ch in sentence:
lis.append(ch)
for i in range(len(lis)-1,0,-1):
print(lis[i],end="")
|
d3005b9756de727e5272e1f593bf0128e41a00da | thitemalhar/python_exercise- | /findevennumbers.py | 177 | 3.703125 | 4 | a = [int(x) for x in input().split()]
print (a)
b = []
def even_numbers(a):
for i in a:
if i % 2 == 0:
b.append(i)
return (b)
print (even_numbers(a)) |
c2a7bba33fe8d107b8339f79a8778df01a283d9a | lsst-sqre/jupyterhubutils | /jupyterhubutils/singleton.py | 456 | 3.671875 | 4 | # Stolen from
# https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
class Singleton(type):
'''Singleton metaclass. Create a Singleton class with:
Class Foo(metaclass=Singleton)
'''
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(
Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
|
e890bb7de9e35e1eb6061a1bd9e183e5e68a32eb | ikemerrixs/Au2018-Py210B | /students/arun_nalla/session06/Mailroom.py | 3,454 | 3.53125 | 4 | #!usr/bin/env python
""" Mailroom_Part4 assignment - Refracted for unit testing using Pytest"""
import os
donors_dict = {'Aron King': [1, 2], 'Becky Patty': [3000, 1000], 'Charlie Lee': [666, 222], 'Thomas Dave':[202, 90, 450], 'Nancy Crow': [100, 200, 300]}
def donors_list (donors_dict):
return list(donors_dict)
def add_donors(name, donors_dict):
return donors_dict.setdefault(name,[])
def add_donation(name, donors_dict, donation):
add_donors(name, donors_dict).append(donation)
return donors_dict
def thanks_email():
while True:
name_input = input("Enter full name of a donor>>>").title()
if name_input == 'List': print (donors_list(donors_dict))
else:
while True:
try:
donation_amount = int(input('Enter donation amount: '))
if donation_amount <= 0:
raise ValueError
add_donation(name_input, donors_dict, donation_amount)
print (email_message(name_input, donation_amount))
return
except ValueError:
print ('Please enter a value, entry should be an integer.')
def sort_key(sorting):
return sorting[1]
def get_report(donors_dict):
list_donors = ((name, sum(donors_dict[name]), len(donors_dict[name]), sum(donors_dict[name])/len(donors_dict[name]))
for name in donors_dict)
list_sorting = (sorted(list_donors, key=sort_key, reverse=True))
return list_sorting
def create_report():
header = ("{:<20}{:<15}{:<15}{:^15}".format('Donors-name', 'Total', 'Num. gifts', 'Average Gift'))
print (header)
print('_' * len(header))
for name, donations, num, average in get_report (donors_dict):
print("{:<20} ${:<15.2f}{:<15}${:<15.2f}".format(name, donations, num, average))
print('_' * len(header)); print('End of Report\n')
def quit_program():
print('Thank for using this script.\nHave a nice day\nBye\n')
exit()
def path_to_store(name):
my_path = os.path.join(os.getcwd(), 'Mailroom')
return os.path.join(my_path, 'email_{}.txt'.format(name))
def email_message (name, donation):
return ("Dear {},\nThank you for generous donation of ${:.2f}. It will be put to a good cause.\nSincerely,"
"\nThe Team".format(name, donation))
def store_emails():
for name in donors_dict:
try:
with open(os.path.join(path_to_store(name)), 'w') as f:
f.write(email_message(name, sum(donors_dict[name])))
except FileNotFoundError:
print ('Check for the file /folder name or path of the directory that stores all the e-mails')
break
else:
print('\nAll e-mails are stored in current directory.\n')
dict_list = {"1": thanks_email, "2": create_report, "3": store_emails, "4": quit_program}
def main ():
while True:
try:
response = input("MAIN MENU\nDonors and donations made to XYZ organisation.\nPlease select one of the "
"option below to proceed.\n1.Send a Thank you message to the donor\n2.Create a report\n"
"3.Send letters to all donors\n4. Quit\n>>>")
dict_list.get(response)()
except TypeError:
print ("Invalid input.\nPlease select correct option")
finally:
print ('Thank You\n\n')
if __name__ == "__main__":
main()
|
207f849a51b8cc0d29d953a9dc5da0911e90040c | pshappyyou/CodingDojang | /LeetCode/test.py | 69 | 3.609375 | 4 |
listl = [1,2,3,4,5]
for i in range(len(listl)):
print(listl[i])
|
9177f690fed2d0ab4fb0ea705add9a587f3e9dfe | Elvolox/ExerciciosPythonCurso | /desafio29.py | 339 | 3.9375 | 4 | velocidade = float((input('Qual a velocidade do carro?: ')))
if velocidade > 80:
print('Voce foi multado, passou a {}km/h'.format(velocidade))
multa = (velocidade - 80) * 7
print('A multa vai lhe custar R${}'.format(multa))
else:
print('Você não estava acima do limite, não foi multado!')
print('--FIM--')
|
a6485c1af9495afe47d8d77f97f52b66b5cde40e | sujith1999/sujith | /2s.py | 144 | 4.0625 | 4 | #!/usr/bin/python3
import random
r=random.randint(1,6) #gives us a number between 1 and 6
print (r)
if r==6:
print("congratulation you got 6")
|
2e2b69bdbc673157e68859e583210bf06c9e4e72 | VoTonggg/nguyenvanhung-fundamental-c4e18 | /Session04Homework/turtle2.py | 172 | 3.78125 | 4 | from turtle import *
speed(-1)
shape("turtle")
color("blue")
for i in range(200):
for j in range(4):
forward(2*i)
left(90)
left(10)
mainloop() |
990b1c9ce74d45626dc5e072f49c8d8a88522802 | Pato91/msft | /leet/compressr.py | 1,218 | 3.765625 | 4 | import unittest
def compress(string):
""" string compression """
if not isinstance(string, str) or any(c.isdigit() for c in string):
raise Exception('Invalid input string')
else:
n = len(string)
if n <= 2:
return string
i = j = 0
count = 1
cp = []
while j < n:
j += 1
if j < n and string[i] == string[j]:
count+=1
continue
elif j < n:
cp.extend([string[i], str(count)])
i, count = j, 1
continue
else:
cp.extend([string[i], str(count)])
return ''.join(cp) if len(cp) < n else string
class Tests(unittest.TestCase):
def test_invalid_input(self):
with self.assertRaisesRegex(Exception, 'Invalid input string'):
compress(['abc','aaabddde'])
with self.assertRaisesRegex(Exception, 'Invalid input string'):
compress('abc123')
def test_empty_string(self):
self.assertEqual(compress(' '), ' 3')
def test_single_digit_str(self):
self.assertEqual(compress('s'), 's')
def test_mixed_case(self):
self.assertEqual(compress('aaaAAA'), 'a3A3')
def test_equal_length_case(self):
self.assertEqual(compress('aaaA'), 'aaaA')
if __name__ == '__main__':
unittest.main()
|
a64076fb7fdddf22c810e3d3b80515f771ca7330 | SantoshGowrisetty/Learn_by_doing-dataquest.io | /Python_Programming/Intermediate/Dates in Python-166.py | 1,384 | 3.640625 | 4 | ## 1. The Time Module ##
import time
current_time=time.time()
print (current_time)
## 2. Converting Timestamps ##
import time
current_time=time.time()
current_struct_time=time.gmtime(current_time)
current_hour=current_struct_time.tm_hour
## 3. UTC ##
import datetime
current_datetime=datetime.datetime.now()
current_year=current_datetime.year
current_month=current_datetime.month
## 4. Timedelta ##
import datetime
today=datetime.datetime.now()
diff=datetime.timedelta(days=1)
tomorrow=today+diff
yesterday=today-diff
print(tomorrow)
print(yesterday)
## 5. Formatting Dates ##
import datetime
mystery_date_formatted_string=mystery_date.strftime("%I:%M%p on %A %B %d, %Y")
print(mystery_date_formatted_string)
## 6. Parsing Dates ##
import datetime
mystery_date=datetime.datetime.strptime(mystery_date_formatted_string,"%I:%M%p on %A %B %d, %Y")
print(mystery_date)
## 8. Reformatting Our Data ##
import datetime
for row in posts:
row[2]=datetime.datetime.fromtimestamp(float(row[2]))
## 9. Counting Posts from March ##
march_count = 0
for row in posts:
if row[2].month==3:
march_count +=1
## 10. Counting Posts from Any Month ##
def nofp(mnth):
month_count = 0
for row in posts:
if row[2].month == mnth:
month_count += 1
return month_count
feb_count=nofp(2)
aug_count=nofp(8) |
36856a0771e1d8ae41fef7ed45d1bf347e56728e | Neil-Do/HUS-Python | /Python 100 Problem/Problem58.py | 375 | 3.859375 | 4 | import re
def extractUsername():
print("Enter Email: ")
email = input()
x = re.search("\w+\.*\w+@\w+\.*\w+\.\w+", email)
while x == None:
print("Khong dung dinh dang email, xin moi nhap lai: ")
email = input()
x = re.search("\w+\.*\w+@\w+\.*\w+\.\w+", email)
username = email.split("@")[0]
print(username)
extractUsername()
|
99a7879498e032ab8259555b4e66a1d1a1b8b616 | UncleBob2/MyPythonCookBook | /projects/snake/snake game byte size.py | 7,467 | 3.90625 | 4 | import pygame as pg
import random
import time
# Colors
red = pg.Color(255, 0, 0)
green = pg.Color(0, 255, 0)
black = pg.Color(0, 0, 0)
white = pg.Color(255, 255, 255)
brown = pg.Color(165, 42, 42)
# Variables
screen_width = 400
screen_height = 400
# Initialize pygame
pg.init()
# The screen, pygame The origin (0,0) is located at the top left corner.
# upper right (screen_width,0), lower right corner (screen_width, screen_height)
wn = pg.display.set_mode((screen_width, screen_height))
pg.display.set_caption('A simple game of Snake')
# The class for food object
class Food():
# Initialization
def __init__(self):
self.x = screen_width / 2
self.y = screen_height / 4
self.color = red
self.width = 10
self.height = 10
# Makes the food visible
def draw_food(self, surface):
self.food = pg.Rect(self.x, self.y, self.width, self.height)
pg.draw.rect(surface, self.color, self.food)
# Is the food eaten?
# e use a pygame inbuilt function that checks if two rectangles collide (this is the reason that food and the snakehead are initialized as py.Rect objects). If the two rectangles collide (snakehead and food), it returns ‘True’ else it returns ‘False.’
def is_eaten(self, head):
return self.food.colliderect(head)
# Returns a new position for the food after it is eaten
def new_pos(self):
self.x = random.randint(0, screen_width - self.width)
self.y = random.randint(0, screen_height - self.height)
# The snake object
class Player():
# Initialization
def __init__(self):
self.x = screen_width / 2
self.y = screen_height / 2
self.width = 10
self.height = 10
self.velocity = 10
self.direction = 'stop'
self.body = []
self.head_color = green
self.body_color = brown
# Draws the snake on the given surface
def draw_player(self, surface):
self.seg = []
self.head = pg.Rect(self.x, self.y, self.width, self.height)
pg.draw.rect(surface, self.head_color, self.head)
if len(self.body) > 0:
for unit in self.body:
segment = pg.Rect(unit[0], unit[1], self.width, self.height)
pg.draw.rect(surface, self.body_color, segment)
self.seg.append(segment)
# Increases length of snake
def add_unit(self):
if len(self.body) != 0:
index = len(self.body) - 1
x = self.body[index][0]
y = self.body[index][1]
self.body.append([x, y])
else:
self.body.append([1000, 1000])
# Checks if there is any collision
def is_collision(self):
# Collision with itself
for segment in self.seg:
if self.head.colliderect(segment):
return True
# Collision with the boundaries
if self.y < 0 or self.y > screen_height - self.height or self.x < 0 or self.x > screen_width - self.width:
return True
# Moves the snake in the direction of head
def move(self):
for index in range(len(self.body) - 1, 0, -1):
x = self.body[index - 1][0]
y = self.body[index - 1][1]
self.body[index] = [x, y]
if len(self.body) > 0:
self.body[0] = [self.x, self.y]
if self.direction == 'up':
self.y -= self.velocity
if self.direction == 'down':
self.y += self.velocity
if self.direction == 'left':
self.x -= self.velocity
if self.direction == 'right':
self.x += self.velocity
# Changes direction of head
def change_direction(self, direction):
if self.direction != 'down' and direction == 'up':
self.direction = 'up'
if self.direction != 'right' and direction == 'left':
self.direction = 'left'
if self.direction != 'up' and direction == 'down':
self.direction = 'down'
if self.direction != 'left' and direction == 'right':
self.direction = 'right'
score, high_score = (0, 0)
# Draw the score on the screen
def draw_score(surface):
global high_score # declare global to access and modify the high score variable
font_name = pg.font.match_font('arial') # choose font with arial in it
if score > high_score: # set high score as current score if it is higher than current score
high_score = score
# writing the score
font = pg.font.Font(font_name, 18)
# The next three lines create a rectangle to display the score
text_surface = font.render(
'Score: {} High Score: {}'.format(score, high_score), True, white)
# Next, we get the rectangle on which the text is drawn via get_rect() and place its mid-top position at (200,10) in the next line. The final line writes the score in the text_rect object.
text_rect = text_surface.get_rect()
text_rect.midtop = (200, 10)
surface.blit(text_surface, text_rect)
# What to do when the game is over
# The function first writes the word “Game Over” on the screen (the first 6–7 lines). Then it resets the score to 0. pg.display.flip() is used to update the screen so that the changes made above are visible. Next, we call the time.sleep() function from the time module, which makes the screen unresponsive for 2 seconds. Finally, we re-initialize the whole game by creating new food and player objects and initializing the game environment using the play_game function.
def game_over():
global score
# writing game over
gameOverFont = pg.font.Font('freesansbold.ttf', 24)
gameOverSurf = gameOverFont.render('Game Over', True, white)
gameOverRect = gameOverSurf.get_rect()
gameOverRect.midtop = (200, 50)
wn.blit(gameOverSurf, gameOverRect)
# reset score
score = 0
pg.display.flip()
time.sleep(2)
# re-initialize game
run = True
fd = Food()
p = Player()
play_game(fd, p)
# The game
# The play_game function takes the two objects (food and player) as the input and makes them play the game.
def play_game(fd, p):
global score
run = True
while run:
# FPS
clock.tick(30)
for event in pg.event.get():
if event.type == pg.QUIT:
run = False
# draw food, snake, score
wn.fill(black)
fd.draw_food(wn)
p.draw_player(wn)
draw_score(wn)
# user input
pressed = pg.key.get_pressed()
if pressed[pg.K_UP]:
p.change_direction('up')
if pressed[pg.K_LEFT]:
p.change_direction('left')
if pressed[pg.K_DOWN]:
p.change_direction('down')
if pressed[pg.K_RIGHT]:
p.change_direction('right')
# move snake
p.move()
# eating
if fd.is_eaten(p.head):
fd.new_pos()
p.add_unit()
score += 10
# collision
if p.is_collision():
run = False
game_over()
pg.display.update()
# The mainloop
run = True
while run:
# Catches all the events that have happened since the game started
for event in pg.event.get():
# When you press the close window button
if event.type == pg.QUIT:
run = False
# Fills the screen with black color
wn.fill(black)
fd = Food()
p = Player()
play_game(fd, p)
# Exits pygame
pg.quit()
|
fee8fdd95f7da79e82d21891f75600e6e535227c | GrowingDiary/python-exercises | /src/065.py | 1,130 | 4.0625 | 4 | # !/usr/bin/python3
# -- coding: utf-8 --
"""
题目:有 n 个整数,使其前面各数顺序向后移 m 个位置,最后 m 个数变成最前面的 m 个数
"""
import copy
import random
def solution1(num, swap_size):
print(num)
for i in range(swap_size):
num.insert(0, num.pop())
print(num)
def solution2(num, swap_size):
print(num)
swap_num = num[-swap_size:]
swap_num.extend(num[:-swap_size])
print(swap_num)
def solution3(num, swap_size):
import collections
print(num)
num_deque = collections.deque(num)
num_deque.rotate(swap_size)
print(list(num_deque))
def main():
num_list = []
for i in range(10):
num_list.append(random.randint(0, 100))
swap_size = random.randint(1, 9)
print('m:', swap_size)
print('---------- solution 1 ---------- ')
solution1(copy.deepcopy(num_list), swap_size)
print('---------- solution 2 ---------- ')
solution2(copy.deepcopy(num_list), swap_size)
print('---------- solution 3 ---------- ')
solution3(copy.deepcopy(num_list), swap_size)
if __name__ == '__main__':
main()
|
1c523b95f0105c7d340fcfeb006c0464e7d54134 | boom210232/triangle | /parameterized_test.py | 1,534 | 3.75 | 4 | from triangle import is_triangle
import unittest
class TriangleTest(unittest.TestCase):
# The list of data values for your tests can be defined:
# - outside the class (global variable)
# - as a class variable (like this)
# - as a local variable inside the test method.
# Use which ever is most readable.
valid_triangles = [
(1, 1, 1),
(3, 4, 5),
(3, 4, 6),
(20, 24, 28),
(55, 77, 99),
(7, 9, 14),
(60, 80, 100)
]
invalid_triangles = [
(55, 77, 2),
(5, 4, 33),
(7, 1, 9),
(200, 55, 99),
(0, 0, 0),
(1, 99, 999999)
]
value_error_triangles = [
(-1, -5, -9),
(-4, 4, 10),
(55, -77, 99),
(7, 9, -14),
(-20, -40, 70),
(-20, 35, -59)
]
def test_valid_triangle(self):
for a, b, c in self.valid_triangles:
with self.subTest():
message = f"sides are ({a},{b},{c})"
self.assertTrue(is_triangle(a, b, c), message)
def test_invalid_triangle(self):
for a, b, c in self.invalid_triangles:
with self.subTest():
message = f"sides are ({a},{b},{c})"
self.assertFalse(is_triangle(a, b, c), message)
def test_value_error_with_negative_value_triangle(self):
for a, b, c in self.value_error_triangles:
with self.subTest():
with self.assertRaises(ValueError):
is_triangle(a, b, c)
|
d09b937a1179a176fe08941db8e660f65c73e8ca | Puzyrinwrk/Stepik | /Поколение Python/Первая_цифра.py | 551 | 4.375 | 4 | """
Дано положительное действительное число. Выведите его первую цифру после десятичной точки.
Формат входных данных
На вход программе подается положительное действительное число.
Формат выходных данных
Программа должна вывести цифру в соответствии с условием задачи.
"""
n = float(input())
r = int(n * 10)
print(r % 10)
|
3b23dd139c4198c7a396b5c591c8f3445a7ba5ee | Hanniery/Parcial1PA | /grapes.py | 706 | 3.859375 | 4 | if __name__ == '__main__':
number_to_eat = input()
andrew, dmitry, michal = int(number_to_eat.split(' ')[0]), int(number_to_eat.split(' ')[1]), int(number_to_eat.split(' ')[2])
number_to_by_box = input()
grapes_green, grapes_purple, grapes_black = int(number_to_by_box.split(' ')[0]), int(number_to_by_box.split(' ')[1]), int(number_to_by_box.split(' ')[2])
bandera = 'YES'
if andrew <= grapes_green:
grapes_green -= andrew
else:
bandera = 'NO'
if dmitry > (grapes_green + grapes_purple):
bandera = 'NO'
else:
grapes_green -= dmitry // 2
grapes_purple -= dmitry // 2
if michal > (grapes_green + grapes_purple + grapes_black):
bandera = 'NO'
print(bandera) |
2f7b28b70473598a082acd4ea9b5b6e5e0d231d3 | mirakib/Regular-coding | /Disemvowel Trolls/Solution.py | 301 | 3.953125 | 4 | def disemvowel(string_):
vowel_list = ['A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u']
re_gen = []
for letter in string_:
if letter not in vowel_list:
re_gen.append(letter)
string_ = ""
for letter in re_gen:
string_ += letter
return string_
|
f2ca3b1466d71fd324098531a6fbe881e6ed5c6d | s2t2/omniparser-prep-py | /app/stock_prices_parser.py | 1,509 | 3.6875 | 4 | from pprint import pprint
import os
import json
def to_usd(my_price):
"""
converts a numeric value to usd-formatted string, for printing and display purposes
"""
return "${0:,.2f}".format(my_price) #> $12,000.71
def latest_closing_price(my_json_filepath):
with open(my_json_filepath, "r") as json_file:
file_contents = json_file.read()
daily_prices = json.loads(file_contents)
latest_date = daily_prices["Meta Data"]["3. Last Refreshed"]
latest_prices = daily_prices["Time Series (Daily)"][latest_date]
latest_close = latest_prices["4. close"] #> '1066.0400'
return latest_close
if __name__ == "__main__":
#
# CAPTURE USER INPUTS
#
selected_symbol = input("Please select a stock symbol ('AAPL', GOOG', or 'MSFT'):")
if selected_symbol.upper() not in ["AAPL", "GOOG", "MSFT"]:
print("OH, INVALID SELECTION. PLEASE TRY AGAIN...")
exit()
print("SELECTED SYMBOL:", selected_symbol.upper())
#
# PROCESS DATA AND DISPLAY OUTPUTS
#
selected_filepath = os.path.join(os.path.dirname(__file__), "..", "data", f"stock_prices_{selected_symbol.lower()}.json")
print("PARSING A LOCAL JSON FILE:", selected_filepath)
if not os.path.isfile(selected_filepath):
print("OH, THAT FILE DOESN'T EXIST. PLEASE PLACE A FILE THERE OR CHECK YOUR FILEPATH...")
exit()
latest_close = latest_closing_price(selected_filepath)
print("LATEST CLOSING PRICE:", to_usd(float(latest_close)))
|
a9449c64a7873a666891ed3b25337bb840bbe9e8 | ommmishra/randomPrograms | /binarySearch.py | 359 | 3.828125 | 4 | def binarySearch(list, idxs, idxe, val):
if(idxe < idxs):
return None
else:
mid = (idxs + idxe )// 2
if(val > list[mid]):
return binarySearch(list, mid+1, idxe, val)
elif(val < list[mid]):
return binarySearch(list, idxs, mid-1, val)
else:
return mid
arr = [23,45,54,767,765]
arr.sort()
print(binarySearch(arr, 0, len(arr)-1, 765))
|
6caf44593e8ee9f98dc1477179f43d2383757995 | yuya-okada527/ml-playground-stream | /utils/csv_utils.py | 305 | 3.609375 | 4 | from typing import Any, List
def make_record(values: List[Any], separator: str) -> str:
value_strings = []
for v in values:
if v is None:
v = ""
v = str(v)
v = v.replace(separator, "")
value_strings.append(v)
return separator.join(value_strings) |
ed0e36c0d79c1afeb7a8f6e95899b11b1db0152d | ShelMX/gb_algorithm_hw | /lesson_7/hw_07_task_2.py | 2,090 | 3.9375 | 4 | __author__ = 'Шелест Леонид Викторович'
"""
Отсортируйте по возрастанию методом слияния одномерный вещественный массив,
заданный случайными числами на промежутке [0; 50).
Выведите на экран исходный и отсортированный массивы.
"""
import hw_07 as lib
def merge_sort(nsl: list) -> list:
"""
function sorts an array by a merge method.
:param nsl: type list: non sorted list
:return: type list: list after merge sort
"""
sl = nsl[:]
n = len(nsl)
if n < 2:
return sl
else:
left_arr = merge_sort(nsl=nsl[:n//2])
right_arr = merge_sort(nsl=nsl[n//2:n])
sl = []
i = 0
j = 0
while i < len(left_arr) or j < len(right_arr):
if not (i < len(left_arr)):
sl.append(right_arr[j])
j += 1
elif not (j < len(right_arr)):
sl.append(left_arr[i])
i += 1
elif not (left_arr[i] > right_arr[j]):
sl.append(left_arr[i])
i += 1
else:
sl.append(right_arr[j])
j += 1
return sl
def main(arr: list = None, is_print: bool = True) -> list:
"""
main function that combines all the functions of the module.
:param is_print: type bool: flag, if True, then function will print result, else not print.
:param arr: type list: non sorted list, if the value of the parameter is not specified,
then an array of random numbers is created.
:return: type list: sorted list
"""
non_sort_list = arr if arr else lib.generate_float_array(low=0.0, up=50.0, rounding=5)
sorted_list = merge_sort(nsl=non_sort_list)
if is_print:
print(f"Non sorted list:")
lib.pretty_print(arr=non_sort_list)
print(f"\nList after Merge sort:")
lib.pretty_print(arr=sorted_list)
return sorted_list
if __name__ == '__main__':
main()
|
59cb7310ba11df7b3ea0cbe5d401e7f8d9185048 | juno7803/Algorithm_Python | /코테 스터디/class2/2164 카드2/2164.py | 262 | 3.546875 | 4 | from collections import deque
from sys import stdin
input = stdin.readline
n = int(input())
q = [i+1 for i in range(n)]
queue = deque(q)
while(len(queue) != 1):
queue.popleft()
second = queue.popleft()
queue.append(second)
print(queue.popleft())
|
f2b6e6da6f2e15fff42b39938ddba775a4ba7fbe | AlishaKochhar/LinkedListPython | /DeleteByPosition.py | 1,079 | 3.640625 | 4 | class Node :
def __init__(self,value) :
self.value=value
self.next=None
class LinkList :
def __init__(self) :
self.head=None
def show(self) :
temp=self.head
while(temp) :
print(temp.value)
temp=temp.next
def beg(self,data) :
new_node=Node(data)
new_node.next=self.head
self.head=new_node
def delete_key(self,pos) :
if self.head==None :
return
temp=self.head
if pos==0 :
self.head=temp.next
temp=None
return
for i in range(pos-1) : #pos=index here
temp=temp.next
if temp is None :
break
if temp is None :
return
if temp.next is None :
return
next=temp.next.next
temp.next=None
temp.next=next
newlist=LinkList()
newlist.beg(7)
newlist.beg(6)
newlist.beg(5)
newlist.beg(4)
newlist.beg(3)
newlist.beg(2)
newlist.beg(1)
newlist.delete_key(2)
newlist.delete_key(4)
newlist.show()
|
5e590ccce5dfc3bbabedae9417dd61a7a2c1fbc4 | ncavchl/Python-study | /programmers/level1/2016년.py | 337 | 3.703125 | 4 | # import datetime
def solution(a, b):
month = [31,29,31,30,31,30,31,31,30,31,30,31]
weekday = ["FRI", "SAT","SUN","MON","TUE", "WED", "THU"]
answer = weekday[(sum(month[:a-1])+b-1)%7]
# day = datetime.datetime(2016, a, b)
# #print(day.weekday())
# dt = day.weekday()
# answer = weekday[dt]
return answer |
2c31c1de702a6d4405728a22f823a0de7c5abaac | A01376318/Mision_04 | /Triangulos.py | 1,142 | 4.15625 | 4 | #Autor: Elena R.Tovar
#Mision_04: Triángulos
#Leer el valor de cada uno de los lados del triángulo
#Clasificar triángulo de acuerdo a la longitud de sus lados
#Si un triangulo no existe, dar ERROR
#Un triangulo no existe si la suma de dos de sus lados es menor al tercero
def verificarLados(a,b,c):
if a==0 or b==0 or c==0:
return "ERROR"
elif (a+b)>c:
return "RIGHT"
elif (a+c)>b:
return "RIGHT"
elif (b+c)>a:
return "RIGHT"
else:
return "ERROR"
def clasificarTriangulos(a,b,c):
if a==b and b==c:
return "EQUILÁTERO"
elif a==b or b==c or a==c:
return "ISÓSCELES"
else:
return "OTRO"
def main():
a= int(input("Ingrese el valor del primer lado: "))
b= int(input("Ingrese el valor del segundo lado: "))
c= int(input("Ingrese el valor del tercer lado: "))
verif=verificarLados(a,b,c)
if verif=="RIGHT":
clasif=clasificarTriangulos(a,b,c)
print("USTED HA INGRESADO UN TRIÁNGULO ",clasif)
else:
print ("LOS VALORES QUE HA INGRESADO NO SON VÁLIDOS")
main() |
54065156ecfae421c3389a0fa618f94903080b0a | cauenapier/Unisim | /src/Unisim/constraints/constraints.py | 7,162 | 3.796875 | 4 | """A constraint is something that describes how two bodies interact with
each other. (how they constrain each other).
"""
import numpy as np
class Constraint(object):
""" Base class for constraints
"""
def _set_bodies(self,a,b):
self._a = a
self._b = b
a = property(lambda self: self._a,
doc="""The first of the two bodies constrained""")
b = property(lambda self: self._b,
doc="""The second of the two bodies constrained""")
class DampedSpring(Constraint):
def __init__(self, a, b, rest_length, stiffness, damping):
super()._set_bodies(a,b)
self._rest_length = rest_length
self._stiffness = stiffness
self._damping = damping
self._force_vector_a2b = None
a.add_constraint(self)
b.add_constraint(self)
def _calcForce_a2b(self):
pos_a = self._a._state_vector[0:3]
pos_b = self._b._state_vector[0:3]
vel_a = self._a._state_vector[3:6]
vel_b = self._b._state_vector[3:6]
# Relative Position
rel_position_norm = np.linalg.norm(pos_b - pos_a)
if rel_position_norm == 0:
rel_position_versor = np.zeros(3)
else:
rel_position_versor = (pos_b - pos_a)/rel_position_norm
# Relative Velocity
rel_velocity_norm = np.linalg.norm(vel_b - vel_a)
if rel_velocity_norm == 0:
rel_velocity_versor = np.zeros(3)
else:
rel_velocity_versor = (vel_b - vel_a)/rel_velocity_norm
F_k = (rel_position_norm-self._rest_length)*self._stiffness*rel_position_versor
F_c = (rel_velocity_norm)*self._damping*rel_velocity_versor
Force = (F_k+F_c)
self._force_vector_a2b = Force
return Force
class Ellastic_Rope_3DOF(Constraint):
"""
"""
def __init__(self, a, b, rest_length, stiffness, damping):
"""
:param Body a: Body a
:param Body b: Body b
:param anchor_a: Anchor point a, relative to body a
:type anchor_a: `(float,float)`
:param anchor_b: Anchor point b, relative to body b
:type anchor_b: `(float,float)`
:param float rest_length: The distance the spring wants to be.
:param float stiffness: The spring constant (Young's modulus).
:param float damping: How soft to make the damping of the spring.
"""
super()._set_bodies(a,b)
self._rest_length = rest_length
self._stiffness = stiffness
self._damping = damping
self._force_vector_a2b = None
a.add_constraint(self)
b.add_constraint(self)
def _calcForce_a2b(self):
"""Ref: Validation of Multibody Program to Optimize
Simulated Trajectories II Parachute Simulation
With Interacting Forces
Behzad Raiszadeh and Eric M. Queen
TODO: Remove redundant checks, code can be optmized.
"""
pos_a = self._a._state_vector[0:3]
vel_a = self._a._state_vector[3:6]
pos_b = self._b._state_vector[0:3]
vel_b = self._b._state_vector[3:6]
# Strain
rel_position_norm = np.linalg.norm(pos_b - pos_a)
if rel_position_norm == 0:
rel_position_versor = np.zeros(3)
e = 0
else:
rel_position_versor = (pos_b - pos_a)/rel_position_norm
e = (rel_position_norm - self._rest_length)/self._rest_length
# Strain Rate
rel_velocity_norm = np.linalg.norm(vel_b - vel_a)
if rel_velocity_norm == 0:
rel_velocity_versor = np.zeros(3)
e_dot = 0
else:
rel_velocity_versor = (vel_b - vel_a)/rel_velocity_norm
e_dot = ( (np.dot(vel_b, rel_position_versor)) - (np.dot(vel_a, rel_position_versor)) )/self._rest_length
if e < 0:
e = 0
if e_dot < 0:
e_dot = 0
if rel_position_norm >= self._rest_length:
F_ab = (self._stiffness*e + self._damping*e_dot)*self._rest_length*rel_position_versor
else:
F_ab = 0
self._force_vector_a2b = F_ab
return F_ab
def _get_force_vector_a2b(self):
return self._force_vector_a2b
class Ellastic_Rope_6DOF(Constraint):
"""
"""
def __init__(self, a, b, a_att, b_att, rest_length, stiffness, damping):
"""
:param Body a: Body a
:param Body b: Body b
:param vector_a: Attachment Point from CG
:param vector_b: Attachment Point from CG
:param anchor_a: Anchor point a, relative to body a
:type anchor_a: `(float,float)`
:param anchor_b: Anchor point b, relative to body b
:type anchor_b: `(float,float)`
:param float rest_length: The distance the spring wants to be.
:param float stiffness: The spring constant (Young's modulus).
:param float damping: How soft to make the damping of the spring.
"""
super()._set_bodies(a,b)
self._att_a = a_att
self._att_b = b_att
self._rest_length = rest_length
self._stiffness = stiffness
self._damping = damping
self._force_vector_a2b = None
a.add_constraint(self)
b.add_constraint(self)
def _calcForce_a2b(self):
"""Ref: Validation of Multibody Program to Optimize
Simulated Trajectories II Parachute Simulation
With Interacting Forces
Behzad Raiszadeh and Eric M. Queen
TODO: Remove redundant checks, code can be optmized.
"""
pos_a = self._a._state_vector[0:3]
vel_a = self._a._state_vector[3:6]
pos_b = self._b._state_vector[0:3]
vel_b = self._b._state_vector[3:6]
DCM_a = self._a._DCM
DCM_b = self._b._DCM
# Strain
rel_position_norm = np.linalg.norm(pos_b - pos_a)
if rel_position_norm < 1e-6:
rel_position_versor = np.zeros(3)
e = 0
else:
rel_position_versor = (pos_b - pos_a)/rel_position_norm
e = (rel_position_norm - self._rest_length)/self._rest_length
# Strain Rate
rel_velocity_norm = np.linalg.norm(vel_b - vel_a)
if rel_velocity_norm < 1e-6:
rel_velocity_versor = np.zeros(3)
e_dot = 0
else:
rel_velocity_versor = (vel_b - vel_a)/rel_velocity_norm
e_dot = ( (np.dot(vel_b, rel_position_versor)) - (np.dot(vel_a, rel_position_versor)) )/self._rest_length
if e < 0:
e = 0
if e_dot < 0:
e_dot = 0
if rel_position_norm >= self._rest_length:
F_ab = (self._stiffness*e + self._damping*e_dot)*self._rest_length*rel_position_versor
else:
F_ab = 0
self._force_vector_a2b = F_ab
return F_ab
def _get_force_vector_a2b(self):
return self._force_vector_a2b
def _calcTorque_ab(self):
X_a_att = pos_a + np.cross(np.transpose(DCM_a), self._att_a)
X_b_att = pos_b + np.cross(np.transpose(DCM_b), self._att_b)
M_a = cross(X_a_att, self._force_vector_a2b)
M_b = cross(X_b_att, -self._force_vector_a2b)
return M_a, M_b
|
640b1e90ef668928671e13a63367b9fd8c7d9f5d | nameera0408/Practical-introduction-to-python_Brainheinold | /ch4_9sol.py | 95 | 3.5 | 4 | n=int(input())
s=0
for i in range(2,n):
if n%i==0:
print(i)
else:
pass
|
a7beca69a8bf7c9b9d935b95d823291ab8cea4c3 | axelkennedal/kexjobbet | /playground/id3_processing/playground.py | 209 | 3.546875 | 4 | genres_count = {}
genres = ["house", "pop", "house"]
# first add the keys
for genre in genres:
genres_count[genre] = 0
# then count
for genre in genres:
genres_count[genre] += 1
print(genres_count)
|
d7b02de81a4fdda16b3244ae0a697fe825728669 | arekRakoczy/ForJajki | /multiplygame.py | 388 | 3.515625 | 4 | import random
base = [1,2,3,4,5,6,7,8,9]
first_nr = base[random.randint(0, len(base)-1)]
second_nr = base[random.randint(0, len(base)-1)]
print(f"{first_nr} x {second_nr} = ")
should_repet = True
while (should_repet):
score = int(input())
if score == first_nr * second_nr:
print("BARDZO DOBRZE")
should_repet = False
else:
print("SPROBUJ JESZCZE RAZ")
|
d79f1478b2a7efad0420a41bcdc2ccaddba5e82f | hillar1988/mypython | /mypython36/duola.py | 13,714 | 3.59375 | 4 | from turtle import *
import turtle
def my_test():
speed(10)
penup()
seth(180)
fd(200)
seth(0)
penup() #外圈头
circle(150, 40)
pendown()
fillcolor('dodgerblue')
begin_fill()
circle(150, 280)
end_fill() #外圈头
fillcolor("red")
begin_fill() #外圈头
seth(0) #项圈
fd(200)
circle(-5,90)
fd(10)
circle(-5,90)
fd(210)
circle(-5,90)
fd(10)
circle(-5,90)
end_fill() #项圈
fd(183) #右脸
left(45)
fillcolor("white")
begin_fill()
circle(120,100)
seth(90) #眼睛
a = 2.5
for i in range(120):
if 0 <= i < 30 or 60 <= i < 90:
a -= 0.05
lt(3)
fd(a)
else:
a += 0.05
lt(3)
fd(a)
penup()
seth(180)
fd(60)
pendown()
seth(90)
for i in range(120):
if 0 <= i < 30 or 60 <= i < 90:
a -= 0.05
lt(3)
fd(a)
else:
a += 0.05
lt(3)
fd(a) #眼睛
seth(180)
penup()
fd(60)
pendown()
seth(215)
circle(120,100)
end_fill() #脸部颜色和眼睛部分
seth(0) # 左眼珠部分
penup()
fd(40)
seth(90)
fd(170)
seth(0)
fd(5)
pendown()
fillcolor("black")
begin_fill()
circle(15,360)
end_fill()
seth(90)
penup()
fd(5)
pendown()
seth(0)
fillcolor("white")
begin_fill()
circle(4,360)
end_fill() #左眼珠部分
penup() #右眼珠
seth(0)
fd(58)
seth(270)
fd(15)
seth(0)
pensize(5)
circle(18,90)
pendown()
circle(18,180)
penup()
circle(18,90)
pendown()
pensize(1)#右眼珠
penup() #鼻子
seth(270)
fd(7)
seth(180)
fd(27)
pendown()
fillcolor("red")
begin_fill()
circle(20)
end_fill()#鼻子
seth(270)#嘴
penup()
fd(40)
pendown()
pencolor("black")
pensize(2)
fd(90)
seth(0)
circle(120,50)
penup()
circle(120,260)
pendown()
circle(120,50)#嘴
penup() #胡须
seth(90)
fd(60)
seth(0)
fd(20)
pendown()
fd(60)
penup()
fd(-60)
seth(90)
fd(20)
pendown()
seth(15)
fd(60)
penup()
fd(-60)
seth(270)
fd(40)
pendown()
seth(-15)
fd(50)
penup()
fd(-50)
seth(180)
fd(40)
pendown()
seth(-165)
fd(50)
penup()
fd(-50)
seth(90)
fd(40)
seth(165)
pendown()
fd(60)
fd(-60)
penup()
seth(280)
fd(20)
seth(180)
pendown()
fd(60) #胡须
penup() #下半身
home()
penup()
seth(180)
fd(200)
seth(0)
seth(90)
fd(36)
seth(0)
fd(98)
pendown()
fillcolor("dodgerblue")
begin_fill()
seth(50)
fd(70)
seth(40)
fd(20)
right(90)
fd(35)
right(75)
fd(105)
seth(90)
fd(10)
seth(-90)
fd(90)
seth(-95)
fd(80)
seth(180)
fd(80) # 右腿
penup() #左腿和过渡
fd(30)
seth(-90)
fd(30)
seth(0)
circle(30,90)
pendown()
circle(30,180)
penup()
circle(30,90)
seth(90)
fd(30)
seth(180)
fd(30)
pendown()
fd(80) #腿
seth(92)
fd(80)
seth(90)
fd(75)
fd(-30)
seth(-135)
fd(30)
right(90)
fd(40)
right(93)
fd(78)
seth(0)
fd(205)
end_fill()
fillcolor("red")# 项圈的补充
begin_fill()
circle(5,90)
fd(10)
circle(5,90)
fd(10)
end_fill()
penup()
seth(50)
fd(70)
seth(40)
fd(16)
right(90)
fd(20)
pendown()
fillcolor("white")# 手掌
begin_fill()
circle(30)
end_fill()
penup()
seth(-90)
fd(253)
seth(180)
fd(160)
seth(-90)
fd(30)
seth(0)
pendown()
fillcolor("white")
begin_fill()
penup()
circle(31,90)
pendown()
circle(31,180)
penup()
circle(31,90)
end_fill()
seth(90)
fd(30)
seth(0)
fd(24)
pendown()
seth(180)
circle(15,180)# 脚
fd(90)
circle(15,180)
fd(90)
penup()
seth(180)
fd(60)
penup()
seth(0)
pendown()
circle(-15,180)
fd(80)
circle(-15,180)
fd(80)
penup()
seth(180)
fd(140)
seth(90)
fd(90)
seth(-45)
pendown()
fillcolor("white")
begin_fill()
circle(30)
end_fill()
penup()
seth(-90)
fd(50)
seth(0)
fd(173)
seth(0)
fillcolor("white")# 胸
begin_fill()
pendown()
circle(90,128)
seth(180)
fd(145)
seth(-128)
circle(90,129)
end_fill()
seth(90)
penup()
fd(35)
seth(0)
pendown()
circle(70,90)# 口袋
seth(180)
fd(140)
seth(-90)
circle(70,90)
penup()
seth(90)
fd(90)
pendown()
seth(0)
fillcolor("#ffd200")#铃铛
begin_fill()
circle(20)
end_fill()
seth(90)
pensize(2)
fd(13)
fillcolor("black")
begin_fill()
seth(0)
circle(2)
end_fill()
seth(-90)
fd(13)
seth(0)
penup()
circle(20,110)
pendown()
seth(170)
fd(20)
seth(190)
fd(20)
penup()
seth(-90)
fd(3.5)
pendown()
seth(10)
fd(20)
seth(-10)
fd(22)
#大雄部分
pensize(1)
penup()
seth(0)
fd(400)
pendown()
speed(10)
fillcolor("black")
begin_fill()
seth(30)
circle(100,60)
fd(20) #右脸
seth(50)
circle(50,150)
seth(70)
fd(4)
seth(50)
fd(4)
fd(-4)
seth(70)
fd(-4)
seth(145)
fd(5)
seth(138)
fd(5)
fd(-5)
seth(145)
fd(-5)
seth(150)
circle(60,150)
seth(-90)
fd(20)
circle(84,92)
end_fill()
penup()
seth(90)
fd(110)
seth(0)
fd(50)
fillcolor("#FAFAD2")
begin_fill()
pendown()#发际线
seth(85)
fd(20)
seth(160)
fd(20)
seth(165)
fd(20)
seth(170)
fd(10)
seth(175)
fd(20)
seth(180)
fd(10)
seth(185)
fd(20)
seth(190)
fd(20)
seth(195)
fd(10)
seth(200)
fd(14.5)
seth(-85)
fd(30)
seth(-90)
fd(20)
circle(84,92)
seth(30)
circle(100.5,60)
fd(30)
end_fill()
penup()
seth(-90)
fd(10)
pendown()
fillcolor("#FAFAD2")
begin_fill()
seth(80)
circle(-8,190)
seth(-90)
fd(5)
seth(-95)
fd(5)
seth(-100)
fd(5)
seth(-105)
fd(5)
seth(-110)
fd(5)
circle(-8,135)
penup()
seth(90)
fd(15)
seth(0)
fd(3)
pendown()
seth(60)
fd(8)
seth(70)
fd(8)
fd(-8)
seth(70)
circle(-5,180)
seth(-120)
fd(14)
end_fill()
penup()
seth(180)
fd(142)
seth(90)
fd(23)
pendown()
fillcolor("#FAFAD2")
begin_fill()
seth(100)
circle(8,180)
seth(-90)
fd(6)
seth(-85)
fd(6)
seth(-80)
fd(6)
circle(8,140)
end_fill()
seth(100)
fd(20)
circle(5,210)
fd(7)
penup()
seth(0)
fd(142)
seth(90)
fd(9)
pendown()
seth(180)
fd(18)
seth(90)
fillcolor("white")
begin_fill()
a = 2.3
for i in range(120):
if 0 <= i < 30 or 60 <= i < 90:
a -= 0.05
lt(3)
fd(a)
else:
a += 0.05
lt(3)
fd(a)
penup()
seth(180)
fd(50)
seth(90)
pendown()
for i in range(120):
if 0 <= i < 30 or 60 <= i < 90:
a -= 0.05
lt(3)
fd(a)
else:
a += 0.05
lt(3)
fd(a)
end_fill()
seth(180)
penup()
fd(70)
pendown()
seth(0)
fd(20)
penup()
fd(34)
seth(-90)
fd(2)
pendown()
pensize(6)
circle(4)
penup()
seth(0)
fd(26)
seth(-90)
fd(2.5)
seth(0)
pendown()
circle(4)
pensize(2)
penup()
seth(90)
fd(40)
seth(0)
fd(15)
seth(30)
pendown()
fd(8)
seth(0)
fd(10)
seth(-40)
fd(15)
seth(-50)
fd(7)
seth(-60)
fd(7)
penup()
seth(180)
fd(95)
seth(90)
fd(25)
pendown()
seth(-145)
fd(10)
seth(-135)
fd(5)
seth(-125)
fd(5)
seth(-120)
fd(5)
seth(-115)
fd(5)
seth(-110)
fd(5)
penup()
seth(90)
fd(30)
seth(0)
fd(25)
pendown()
seth(-30)
fd(19)
penup()
pensize(1)
seth(0)
fd(13)
seth(-90)
fd(81)
seth(0)
pendown()
circle(8)
penup()
seth(-90)
fd(20)
seth(180)
fd(10)
seth(160)
pendown()
fd(25)
fd(-25)
seth(-15)
fd(5)
seth(-10)
fd(5)
seth(0)
fd(5)
seth(10)
fd(5)
seth(15)
fd(5)
seth(20)
fd(27)
seth(-90)
penup()
fd(25)
seth(180)
fd(36)
seth(0)
pendown()
fillcolor("white")
begin_fill()
circle(68.5,75)
seth(-105)
circle(-68.5,75)
circle(-72.5,78)
penup()
seth(-90)
fd(100)
seth(0)
fd(133)
seth(90)
fd(85)
end_fill()
fillcolor("#FAFAD2")
begin_fill()
seth(-160)
fd(104)
seth(0)
fd(38)
seth(-90)
fd(7.5)
pendown()
seth(0)
circle(66,76)
end_fill()
penup()
seth(180)
fd(80)
seth(-90)
fd(33.5)
pendown()
seth(-15)
fd(5)
seth(-10)
fd(5)
seth(0)
fd(5)
seth(10)
fd(5)
seth(15)
fd(5)
seth(20)
fd(27)
penup()
seth(180)
fd(12)
seth(-90)
fd(21)
pendown()
fillcolor("#FAFAD2")
begin_fill()
fd(12)
seth(180)
fd(46)
seth(90)
fd(11)
penup()
seth(-30)
fd(5)
seth(-20)
fd(5)
seth(-10)
fd(5)
seth(0)
fd(5)
pendown()
circle(73,27)
end_fill()
penup()
seth(-90)
fd(6)
seth(180)
fd(5)
pendown()
fillcolor("white")
begin_fill()
seth(-50)
fd(12)
seth(-100)
fd(30)
seth(135)
fd(40)
seth(-135)
fd(40)
seth(100)
fd(30)
seth(45)
fd(16)
end_fill()
fillcolor("#EEC900")
begin_fill()
fd(-16)
seth(-145)
fd(40)
circle(20,45)
fd(10)
left(10)
fd(5)
right(10)
fd(10)
left(90)
fd(25)
seth(85)
fd(25)
seth(75)
fd(10)
fd(-10)
seth(85)
fd(-25)
seth(-90)
fd(15)
seth(-85)
fd(18)
seth(0)
fd(95)
circle(6,180)
seth(90)
fd(30)
seth(95)
fd(35)
fd(-30)
right(90)
fd(25)
left(80)
fd(6)
left(6)
fd(6)
left(12)
fd(20)
circle(20,60)
fd(20)
end_fill()
penup()
seth(180)
fd(54)
seth(90)
fd(10)
pendown()
fillcolor("#FAFAD2")
begin_fill()
seth(-90)
fd(10)
seth(0)
fd(48)
seth(90)
fd(10)
end_fill()
seth(180)
penup()
fd(24)
pendown()
circle(-160,13)
seth(-13)
circle(160,13)
seth(0)
circle(160,12)
penup()
seth(-90)
fd(12)
seth(180)
fd(3)
pendown()
fillcolor("white")
begin_fill()
seth(-100)
fd(30)
seth(135)
fd(40)
seth(-135)
fd(40)
seth(100)
fd(26)
end_fill()
penup()
seth(0)
fd(20)
seth(90)
fd(2)
pendown()
seth(0)
fd(41)
penup()
seth(0)
fd(40)
seth(-90)
fd(53)
pendown()
fillcolor("#FAFAD2")
begin_fill()
seth(-80)
fd(60)
seth(-30)
fd(5)
seth(-40)
fd(5)
seth(-50)
fd(5)
seth(-60)
fd(5)
seth(-80)
fd(5)
seth(-90)
fd(5)
seth(-95)
fd(5)
seth(-135)
fd(6)
seth(-138)
fd(6)
seth(-143)
fd(6)
circle(-15,160)
seth(180)
circle(20,20)
seth(95)
fd(80)
end_fill()
penup()
fd(-90)
seth(0)
fd(20)
pendown()
seth(-70)
fd(10)
fd(-10)
penup()
seth(0)
fd(8)
seth(-70)
pendown()
fd(7)
fd(-7)
penup()
seth(0)
fd(8)
seth(-70)
fd(-10)
pendown()
fd(13)
penup()
seth(180)
fd(165)
seth(90)
fd(82)
seth(-95)
fillcolor("#FAFAD2")
begin_fill()
pendown()
fd(80)
seth(-150)
circle(20,190)
seth(145)
fd(10)
left(90)
fd(6)
fd(-14)
fd(8)
right(90)
fd(-7)
seth(45)
circle(20,80)
seth(85)
fd(85)
end_fill()
penup()
seth(-90)
fd(35)
seth(0)
fd(3)
pendown()
fillcolor("#FAFAD2")
begin_fill()
seth(-105)
fd(10)
seth(-87)
fd(70)
seth(-90)
fd(70)
seth(-145)
fd(20)
circle(10,160)
seth(0)
fd(50)
circle(5,110)
fd(20)
seth(90)
fd(50)
seth(87)
fd(60)
circle(-6,175)
fd(60)
seth(-90)
fd(50)
seth(-120)
fd(18)
circle(5,130)
seth(0)
fd(50)
circle(10,160)
fd(16)
seth(90)
fd(70)
seth(87)
fd(80)
end_fill()
penup()
seth(90)
fd(1)
fillcolor("#FF3E96")
begin_fill()
pendown()
seth(180)
fd(96)
seth(-105)
fd(10)
seth(-87)
fd(45)
seth(0)
fd(43)
seth(87)
fd(13)
circle(-6,175)
seth(-90)
fd(15)
seth(0)
fd(40)
end_fill()
penup()
seth(-90)
fd(98)
seth(180)
fd(40)
pendown()
seth(-10)
fd(15)
seth(0)
fd(15)
seth(10)
fd(15)
penup()
seth(180)
fd(62)
pendown()
seth(-170)
fd(15)
seth(180)
fd(15)
seth(-190)
fd(15)
turtle.done()
# hideturtle()
my_test()
|
e9b61eb2725ef0d5c156e88d8458a2241a5784c4 | CarlosRodrigo/project-euler | /euler01.py | 281 | 3.8125 | 4 | # Project Euler - 01
# https://projecteuler.net/problem=1
# Multiples of 3 and 5
def multiples(n):
curr_sum = 0
for i in range(n):
if i % 3 == 0 or i % 5 == 0 :
curr_sum += i
return curr_sum
def main():
print multiples(1000)
if __name__ == "__main__":
main() |
d06b8b9bcf5a041c0595bebb6b3b6f76e146729b | mikemadden42/pyutils | /tickets.py | 997 | 3.84375 | 4 | #!/usr/bin/env python3
"""Summarize tickets by user"""
import argparse
import csv
from collections import defaultdict
import six
def tickets(tickets_file):
"""Summarize tickets by user"""
items = defaultdict(list)
with open(tickets_file, "rb") as infile:
reader = csv.reader(infile)
for row in reader:
assignee = row[49]
summary = row[32]
request = row[50]
date = row[19]
work_details = "%s - %s - %s" % (request, date, summary)
items[assignee].append(work_details)
for key, values in list(items.items()):
six.print_(key, "-", len(values), "request(s)")
for item in values:
six.print_(item)
six.print_()
if __name__ == "__main__":
PARSER = argparse.ArgumentParser(description="summarize a set of tickets")
PARSER.add_argument("-f", "--file", help="tickets file", required=True)
ARGS = vars(PARSER.parse_args())
tickets(ARGS["file"])
|
63704afe3015c2cfc67a1d0f507b45b0a28174fe | ghydric/06-Intro-to-Algorithms | /Class_Practice_Exercises/Collections/collections.py | 3,581 | 4.03125 | 4 | """
**************************** Collection Types ********************************
collection - a group of zero or more items that can be treated as a
conceptual unit. Things like strings, lists, tuples, and dictionaries.
other types of collections include stacks, queues, priority queues,
binary search trees, heaps, graphs, and bags.
linear collection - like people in a line, they are ordered by position
each item except the first has a unique predecessor
some examples include: grocery lists, stacks of dinner plates,
and a line at the ATM.
(Item 1) - (Item 2) - (Item 3) - (Item 4)
hiearchical collection - ordered in a structure resembling an upside-down tree.
Each data item except the one at the top (root) has just one
predecessor called its parent, but potentially has many
successors called children.
some examples include: a file directory system, a company's
organizational tree, and a book's table of contents.
graph collection - also called graph, each item can have many predecessors
and many successors. These are also called neighbors.
(Item 1) --- (Item 2)
| /
| /
| /
(Item 3)
some examples include: airline routes between cities, electrical
wiring diagrams, and the world wide web.
unordered collections - these are not in any particular order, and it's not possible to
meaningfully speak of an item's predecessor or successor.
an example includes a bag of marbles
**************************** Operation Types ********************************
Determine the size - Use Python's len() function to obtain the number of items
currently in the collection.
Test for item membership - Use Python's "in" operator to search for a given target
item in the collection. Returns True if the item is found
and False otherwise.
Traverse the collection - Use Python's "for loop" to visit each item in the collection.
The order which items are visited depends upon the type of collection.
Obtain a string representation - Use Python's str function to obtain the string representation
of the collection.
Test for equality - Use Python's == operator to determine whether two collections are equal.
Two collections are equal if they are of the same type and contain the same
items. The order in which pairs of items are compared depends upon the type
of collection.
Concatenate two collections - Use Python's "+" operator to obtain a new collection of the same
type as the operands, and containing the items in the two operands.
Convert to another type of collection - Create a new collection with the same items as a source collection.
Insert an item - Add the item to the collection, possibly at a given position.
Remove an item - Remove the item from the collection, possibly at a given position.
Replace an item - Combine removal and insertion into one operation
Access or retrieve an item - Obtain an item, possibly at a given position.
""" |
6b7107a1a61ef6bea92bbf718cea35e468e0788d | athirarajan23/luminarpython | /identifiers/python4.py | 910 | 4.1875 | 4 | "swapping"
num1=10
num2=20
print("no before swapping")
print("num1 is",num1)
print("num2 is",num2)
temp=num1
num1=num2
num2=temp
print("no after swapping")
print("num1 is",num1)
print("num2 is",num2)
"using operators"
num1=10
num2=20
num1=num1+num2 #10+20=30
num2=num1-num2 #30-20=10
num1=num1-num2 #30-10=20
print(num1) #python will use line by line execution so 20 will be tyhe value of num1 and not 30
print(num2)
number1=9
number2=99
print("the number before swapping is")
print("number1 is",number1)
print("number2 is",number2)
temp=number1
number1=number2
number2=temp
print("the numbers after swapping")
print("number1 is",number1)
print("number2 is",number2)
numb1=45
numb2=54
print("the number before swapping")
print("numb1 is",numb1)
print("numb2 is",numb2)
temp=numb1
numb1=numb2
numb2=temp
print("the number after swapping")
print("numb1 is",numb1)
print("numb2 is",numb2)
|
6be7c21313c94c831973387f81da22f414e5a44c | suyash081/python | /day 4 assignment.py | 1,306 | 4.71875 | 5 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
# initializing string
test_str = "we are learning python , we are programmers"
# initializing substring
test_sub = "we"
# printing original string
print("The original string is : " + test_str)
# printing substring
print("The substring to find : " + test_sub)
# using list comprehension + startswith()
# All occurrences of substring in string
res = [i for i in range(len(test_str)) if test_str.startswith(test_sub, i)]
# printing result
print("The start indices of the substrings are : " + str(res))
# In[ ]:
use of isupper() and is lower()
# In[2]:
a= "I am learning python"
a.isupper()
# In[3]:
a= "i am learning python"
a.isupper()
# In[4]:
a= "I AM LEARNING PYTHON"
a.isupper()
# In[5]:
a= "i am learning python 3.7"
a.isupper()
# In[6]:
a= "#i am learning python"
a.isupper()
# In[7]:
a= "#I AM LEARNING PYTHON"
a.isupper()
# In[8]:
a= "I AM LEARNING PYTHON 3.7"
a.isupper()
# In[9]:
a= "I am learning python "
a.islower()
# In[11]:
a= "i am learning python"
a.islower()
# In[12]:
a= "i am learning python 3.7"
a.islower()
# In[13]:
a= "#i am learning python , batch 6"
a.islower()
# In[14]:
a= "19284 "
a.islower()
# In[15]:
a= "#$^&*^"
a.islower()
# In[ ]:
|
685be9417512353f773fcad3413766d1e2c56bc9 | mrfabroa/ICS3U | /Archives/4_Functions/functions_primer_1.py | 641 | 3.828125 | 4 | __author__ = 'eric'
"""
Filename: functions_primer_1.py
Description: A short program to demonstrate the usage if built-in python functions and the math library
"""
import math
# usage of a built-in function abs()
number_1 = input("Enter a number: ")
abs_value = abs(number_1)
print "The absolute value of", number_1, "is", abs_value
# usage of a function from another library (math)
number =2 input("Enter a number: ")
print "The square root of", number_2, "is", math.sqrt(number_2)
# usage of built-in function len()
name = raw_input("Enter your name: ")
num_char = len(name)
print "There are", num_char,"in your name."
|
2d39a0f447d9f23a696d25780e0de975acc95328 | saurabhsalunke17/my-python-basic1 | /1 .assignments/4 print hellow 5 tymes.py | 288 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
4.Write a program which display 5 times Marvellous on screen.
"""
def pr(num):
i=0
for i in range(0,num):
print("marvellous")
def main():
n1=int(input("enter the number"))
pr(n1)
if __name__=="__main__":
main() |
f9813572ff544dd3f7b1f68fa361ae538b0e2a4b | vrnsky/python-crash-course | /chapter8/make_albums.py | 341 | 3.609375 | 4 | def make_albums(artist, title, songs = None):
album = {'artist': '', 'title': ''}
album['artist'] = artist
album['title'] = title
if songs:
album['songs'] = songs
return album
fallout_boy_albums = make_albums('Fallout Boy', 'Centuries', 10)
for key, value in fallout_boy_albums.items():
print(key.title(), "and their album", value)
|
3086acf38d007fd31f1adecb60a0fe5bf0831d45 | jeongm-in/UVACS1110- | /sogogibeef/higher_lower.py | 1,079 | 4.3125 | 4 | # Ask user which number to use for guessing game (integer between 1 and 100)
# If user inputs -1, Computer will pick a number between 1 and 100
# User is prompted to set how many guesses user would get
import random
user_input_is_valid = False
while True:
user_answer = int(input('What should the answer be? '))
if user_answer == -1:
answer = random.randrange(1, 101)
break
elif user_answer in range(1, 101):
answer = user_answer
break
print('Type number between 1 and 100 or -1 for random answer.')
guesses_remaining = int(input('How many guesses? '))
is_answer = False
while is_answer == False:
guess = int(input('Guess a number: '))
guesses_remaining -= 1
if guesses_remaining == 0 and guess != answer:
lose_message = 'You lose; the number was {}.'.format(answer)
print(lose_message)
break
elif guess < answer:
print('The number is higher than that.')
elif guess > answer:
print('The number is lower than that.')
else:
print('You win!')
break
|
b7330be06c8b86d5bde2f59db3e476599fb4a3d0 | christian-saldana/Leetcode | /Medium/longest_substring.py | 335 | 3.640625 | 4 | """Given a string s, find the length of the longest substring without repeating characters. """
def longSub(s):
dic = {}
res, last_match = 0, -1
for i, c in enumerate(s):
if c in dic and last_match < dic[c]:
last_match = dic[c]
res = max(res, i - last_match)
dic[c] = i
return res
|
3529df4c745fe5b6d56b79650acf921c0f5f78f9 | daniel-reich/turbo-robot | /Azhkq898ZtmfyCGif_14.py | 974 | 4.3125 | 4 | """
Create a function which converts an **ordered** number list into a list of
ranges (represented as strings). Note how some lists have some numbers
missing.
### Examples
numbers_to_ranges([1, 2, 3, 4, 5]) ➞ ["1-5"]
numbers_to_ranges([3, 4, 5, 10, 11, 12]) ➞ ["3-5", "10-12"]
numbers_to_ranges([1, 2, 3, 4, 99, 100]) ➞ ["1-4", "99-100"]
numbers_to_ranges([1, 3, 4, 5, 6, 7, 8]) ➞ ["1", "3-8"]
### Notes
* If there are no numbers consecutive to a number in the list, represent it as only the _string_ version of that number (see example #4).
* Return an empty list if the given list is empty.
"""
def numbers_to_ranges(lst):
if lst == []:
return []
curr = lst[0]
ranges = []
for i in range(len(lst)-1):
if lst[i] != lst[i+1]-1:
ranges.append(str(curr) + (curr != lst[i])*('-' + str(lst[i])))
curr = lst[i+1]
ranges.append(str(curr) + (curr != lst[-1])*('-' + str(lst[-1])))
return ranges
|
325dfe7c251208eedae934052746c980d516699f | zsffq999/helloworld | /strategy/trade/__init__.py | 1,232 | 3.796875 | 4 | # -*- coding:utf-8 -*-
class Trade(object):
"""
交易模块基类,根据模型预测的涨跌信号和实时数据发出交易指令
"""
def __init__(self):
self.tradeinfo = []
def trade(self, signal, dataset):
"""
交易
:param signal: 模型预测的涨跌信号(+-1,0)
:param dataset: 实时行情,DataSet基类
:return: 交易指令
"""
pass
def rcvtrade(self, trade):
print(*trade)
if isinstance(trade, list):
self.tradeinfo += trade
else:
self.tradeinfo.append(trade)
class Deal(object):
"""
每笔交易记录。如果涉及多笔交易记录,用list<Deal>存储
"""
__slots__ = ('time', 'target', 'amount', 'price')
def __init__(self, time, target, amount, price):
"""
初始化函数
:param time: 交易时间
:param target: 交易标的
:param amount: 成交量,以股为单位,<0为做空,>0为做多
:param price: 成交金额
:return:
"""
self.time = time
self.target = target
self.amount = amount
self.price = price
def __str__(self):
return "Deal: <time: {0}, target: {1}, amount: {2}, price: {3}>".format(self.time, self.target, self.amount, self.price)
if __name__ == "__main__":
print(*[Deal(1, 2, 3, 4), Deal(5,6,7,8)]) |
aeac3930f0e15a26da1c83f1123201bea3a82dce | Prakort/competitive_programming | /combination-sum-ii.py | 1,126 | 3.703125 | 4 | def solution(nums, target):
"""
Given a collection of candidate numbers (candidates) and a target number (target),
find all unique combinations in candidates where the candidate numbers sums to target.
Each number in candidates may only be used once in the combination.
Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
each element could be used only once, they could be the same number but different index
perform dfs for i in passing_index, len(nums)
==> (nums[i] -> current list) , (i + 1) add next element of the next index to prevent add the same index
"""
output = []
nums.sort()
helper(nums, target, [], 0)
return output
def helper(nums, target, path, output, index):
if sum(path) == target:
output.append(path)
return
if sum(path) > target:
return
for i in range(index, len(nums)):
if i > index and nums[i-1] == nums[i]:
continue
helper(nums, target, path + [nums[i]], i + 1)
[
[1, 1, 1, 1, 1, 1, 1],
[1, 2, 3, 4, 5, 6, 7],
[1, 0, 3, 7, 12, 18, 25]
]
|
737fbbb44c6c72b613a98b9a8fa3a2dd4a7952a9 | marcofigueiredo224/Python-Curso | /ex012.py | 165 | 3.5625 | 4 | from math import hypot
co = float(input('Comprimento do cateto oposto: '))
ca = float(input('Comprimeto do cateto adjacente: '))
hi = hypot(co, ca)
print(hi)
|
59779269b09c945f6235a61fe3032a9f433ae3c0 | aryan011102/UVA-Online-Judge | /10945.py | 406 | 3.78125 | 4 | import string
def trans(s):
p=s.maketrans(string.punctuation+string.ascii_uppercase," "*len(string.punctuation)+string.ascii_lowercase)
return s.translate(p)
while True:
s=input()
if s=='DONE':
break
else:
s=trans(s)
l=s.split(" ")
s="".join(l)
if s==s[::-1]:
print("You won't be eaten!")
else:
print('Uh oh..')
|
d66ef4777413ed7e6535755f8a425937044f71f6 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2716/60723/238018.py | 1,489 | 3.703125 | 4 | def stringToArray(str,array):
str=str[2:]
for i in range(0,len(str)):
if str[i]==' ':
array.append(' ')
elif str[i]=='/':
array.append('/')
elif str[i]=='\\':
if str[i+1]=='\\':
array.append('\\')
return array
def pictureByArray(array,length):
picture=[[0 for _ in range(length*3)] for _ in range(length*3)]
for i in range (0,len(array)):
row=int(i/length)
line=int(i%length)
if array[i]=='/':
picture[row*3+2][line*3]=picture[row*3+1][line*3+1]=picture[row*3][line*3+2]=1
elif array[i]=='\\':
picture[row*3 + 2][line * 3+2]=picture[row*3+1][line*3+1]=picture[row*3][line*3]=1
return picture
temp=input()
lines=[]
length=-1
while temp!="]":
temp=input()
length=length+1
lines=stringToArray(temp,lines)
picture=pictureByArray(lines,length)
count=0
for i in range(0,length*3):
for j in range(0,length*3):
if int(picture[i][j])==0:
if j==0:
if picture[i][j]!=picture[i][j+1]:
count=count+1
elif j==length*3-1:
if picture[i][j]!=picture[i][j-1]:
count=count+1
else:
if picture[i][j]!=picture[i][j+1] & picture[i][j]!=picture[i][j-1]:
count=count+1
if count==4:
if lines!=['\\', '/', '/', '\\']:
print(5)
else:
print(count)
else:
print(count) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.