blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
abf2ee9430a0fefeb216ecb81909376215a8cbc8 | lost-osiris/bzcompliance | /libs/Compliance/req_functions.py | 5,600 | 3.515625 | 4 | import re, inspect, sys, types
from datetime import datetime
format_string = "%Y%m%dT%H:%M:%S"
user_format = "%Y-%m-%d"
user_format_time = "%Y-%m-%dT%H:%M:%S"
def __lower(data, params):
if type(data) is list:
data = [str(element).lower() for element in data]
else:
data = str(data).lower()
params = [str(param).lower() for param in params]
return data, params
def __ints_only(params, name):
for param in params:
if not param.isdigit():
raise Exception("%s only accept integer parameters, got %s" % (name, param))
def __one_param(params, name):
if len(params) > 1:
raise Exception("%s accepts only 1 parameter, got %d" % (name, len(params)))
def __parse_date(string):
try:
return datetime.strptime(string, user_format_time), True
except:
return datetime.strptime(string, user_format), False
def is_(data, params):
data, params = __lower(data, params)
return is_case(data, params)
def is_case(data, params):
data = str(data)
for param in params:
if param == data:
return True
return False
def is_greater_than(data, params):
data, params = __lower(data, params)
return is_greater_than_case(data, params)
def is_greater_than_case(data, params):
data = str(data)
for param in params:
if param > data:
return True
return False
def is_less_than(data, params):
data, params = __lower(data, params)
return is_less_than_case(data, params)
def is_less_than_case(data, params):
data = str(data)
for param in params:
if param < data:
return True
return False
def is_in(data, params):
data, params = __lower(data, params)
return is_in_case(data, params)
def is_in_case(data, params):
data = str(data)
for param in params:
if data in param:
return True
return False
def are_all_in(data, params):
data, params = __lower(data, params)
return are_all_in_case(data, params)
def are_all_in_case(data, params):
if type(data) is not list:
data = str(data)
for item in data:
if str(item) not in params:
return False
return True
def contains_(data, params):
data, params = __lower(data, params)
return contains_case(data, params)
def contains_case(data, params):
if type(data) is not list:
data = str(data)
else:
data = [str(i) for i in data]
for param in params:
if param in data:
return True
return False
def contains_all(data, params):
data, params = __lower(data, params)
return contains_all_case(data, params)
def contains_all_case(data, params):
if type(data) is not list:
data = str(data)
else:
data = [str(i) for i in data]
for param in params:
if param not in data:
return False
return True
def size_is(data, params):
__ints_only(params, "SizeIs")
return str(len(data)) in params
def size_at_least(data, params):
__ints_only(params, "SizeAtLeast")
for param in params:
if str(len(data)) >= int(param):
return True
return False
def size_at_most(data, params):
__ints_only(params, "SizeAtMost")
for param in params:
if str(len(data)) <= int(param):
return True
return False
def date_is(data, params):
data = datetime.strptime(data, format_string)
for param in params:
dt, use_time = __parse_date(param)
if use_time and data == dt:
return True
elif not use_time and data.date() == dt.date():
return True
return False
def date_at_least(data, params):
data = datetime.strptime(data, format_string)
for param in params:
dt, use_time = __parse_date(param)
if use_time and data >= dt:
return True
elif not use_time and data.date() >= dt.date():
return True
return False
def date_at_most(data, params):
data = datetime.strptime(data, format_string)
for param in params:
dt, use_time = __parse_date(param)
if use_time and data <= dt:
return True
elif not use_time and data.date() <= dt.date():
return True
return False
def date_is_format(data, params):
data = datetime.strptime(data, params[0])
for param in params[1:]:
dt, use_time = __parse_date(param)
if use_time and data == dt:
return True
elif not use_time and data.date() == dt.date():
return True
return False
def date_at_least_format(data, params):
data = datetime.strptime(data, params[0])
for param in params[1:]:
dt, use_time = __parse_date(param)
if use_time and data >= dt:
return True
elif not use_time and data.date() >= dt.date():
return True
return False
def date_at_most_format(data, params):
data = datetime.strptime(data, params[0])
for param in params[1:]:
dt, use_time = __parse_date(param)
if use_time and data <= dt:
return True
elif not use_time and data.date() <= dt.date():
return True
return False
def has_field(data, params):
__one_param(params, "HasField")
try:
data[params[0]]
except:
return False
return True
def regex(data, params):
for param in params:
regex = re.compile(param)
if re.search(regex, str(data)):
return True
return False
#Populate function map
func_map = {}
for member in inspect.getmembers(sys.modules[__name__]):
if not member[0].startswith("_") and type(member[1]) is types.FunctionType:
func_map[member[0].replace("_", "").lower()] = member[1]
|
9747e966aeece1e1e1ecd2c4c1cb37fb6952717e | sd691876/Python_YL | /Code/平方相加.py | 218 | 3.9375 | 4 | #1 + 2 + ... + n的每個平方相加
n=0
sum_1=0
sum_2=0
i=0
n=int(input("please input the n:"))
for i in range(n+1):
sum_2=i*i
sum_1=sum_1+sum_2
print("1^2 + 2^2 + 3^2 + ... + %d^2 = %d" %(n, sum_1)) |
d7ac48c9c1182c6c5cbdfc55a9f2e8c84baaf545 | nin9/CTCI-6th | /Chapter08/5-recursiveMultiply.py | 497 | 3.921875 | 4 | """
Time Complexity O(logs), where s is the smaller number
Space Complexity O(1)
"""
def minProduct(smaller: int, bigger: int) -> int:
if smaller == 0:
return 0
if smaller == 1:
return bigger
ans = 0
if smaller % 2 == 1:
ans += bigger
halfPord = minProduct(smaller>>1, bigger)
return ans + halfPord + halfPord
def multiply(n: int, m: int) -> int:
smaller = n if n < m else m
bigger = n if n > m else m
return minProduct(smaller, bigger)
print(multiply(0, 4))
|
f32289a1f66325e441455e6c07747d69e880144b | pratyusa98/Open_cv_Crashcourse | /opencvbasic/27. Image Contours P-3.py | 1,563 | 3.53125 | 4 | # Approximation and Convex hull
import cv2
#Find countour area , aprroximation and convex hull
img = cv2.imread("resources/shapes.png")
img = cv2.resize(img,(600,700))
img1 = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(img1,220,255,cv2.THRESH_BINARY_INV)
cnts,hier = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
area1 = []
for c in cnts:
# compute the center of the contour
#an image moment is a certain particular weighted average (moment) of the image pixels
M = cv2.moments(c)
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
cv2.drawContours(img, [c], -1, (0, 255, 0), 2)
cv2.circle(img, (cX, cY), 7, (0, 0, 0), -1)
cv2.putText(img, "center", (cX - 20, cY - 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
# find area of contour
area = cv2.contourArea(c)
area1.append(area)
if area < 10000:
# contour Approx - it is use to approx shape with less number of vertices
epsilon = 0.01 * cv2.arcLength(c, True) # arc length take contour and return its perimeter
data = cv2.approxPolyDP(c, epsilon, True)
# Convexhull is used to provide proper contours convexity.
hull = cv2.convexHull(data)
x, y, w, h = cv2.boundingRect(hull)
img = cv2.rectangle(img, (x, y), (x + w, y + h), (125, 10, 20), 5)
print("Area",area1)
cv2.imshow("original===",img)
cv2.imshow("gray==",img1)
cv2.imshow("thresh==",thresh)
cv2.waitKey(0)
cv2.destroyAllWindows() |
f48ccf7a1c13b6f9842f892f3a52b9b9f7f431b1 | yugarsi/IQ | /2D-Array/max_sub_array_sum_DP.py | 1,545 | 4.03125 | 4 | '''
Maximum Sum Submatrix
You're given a two-dimensional array (a matrix) of potentially unequal height and
width that's filled with integers. You're also given a positive integer size.
Write a function that returns the maximum sum that can be generated from a submatrix with
dimensions size * size.
For example, consider the following matrix:
[
[2, 4],
[5, 6],
[-3, 2],
]
If size= 2, then the 2x2 submatrices to consider are:
[2, 4]
[5, 6]
------
[5, 6]
[-3, 2]
The sum of the elements in the first submatrix is 17, and the sum of the elements in the second submatrix is 10.
In this example, your function should return 17.
Note: size will always be at least 1, and the dimensions of the input matrix will always be at least size * size.
'''
def maximumSumSubmatrix(matrix, size):
#modify the given matrix with sum upto that point
#which is left + top - diag (diag is added twice so needs to be subtracted once
for r in range(len(matrix)):
for c in range(len(matrix[0])):
left = matrix[r-1][c] if r > 0 else 0
top = matrix[r][c-1] if c > 0 else 0
diag = matrix[r-1][c-1] if r > 0 and c > 0 else 0
matrix[r][c] += left + top - diag
maxsum = -float("inf")
for r in range(size-1, len(matrix)): #because size-1
for c in range(size-1, len(matrix[0])):
left = matrix[r-size][c] if r-size >= 0 else 0 #
top = matrix[r][c-size] if c-size >=0 else 0
diag = matrix[r-size][c-size] if r-size>=0 and c-size>=0 else 0
cursum = matrix[r][c] - top - left + diag
maxsum = max(maxsum,cursum)
return maxsum |
641806751609863aa4aa32d696fc96313e2ae8df | ChenYenDu/LeetCode_Challenge | /01_BinaryTree/01_Traverse_A_Tree/01_Binary_Tree_Preorder_Traersal.py | 721 | 3.796875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
if root == None:
return []
else:
rst = []
collect = [root]
while len(collect) > 0:
stack = collect.pop()
if stack.val != None:
rst.append(stack.val)
if stack.right != None:
collect.append(stack.right)
if stack.left != None:
collect.append(stack.left)
return rst
|
8bf474eb7cb4c7a20e28091486f107dd489edf74 | lowell1/Algorithms | /rock_paper_scissors/rps.py | 1,463 | 3.65625 | 4 | #!/usr/bin/python
import sys
# def recurse(n, idx):
# new_combos = []
# if idx == n - 1:
# arr = ["rock"] * n
# for text in ["rock", "paper", "scissors"]:
# new_combos.append(arr[:-1] + [text])
# else:
# print(idx)
# last_combos = recurse(n, idx + 1)
# for combo in last_combos:
# for text in ["rock", "paper", "scissors"]:
# new_combos.append(combo[:idx] + [text] + combo[idx + 1:])
# return new_combos
def recurse(n, idx):
new_combos = []
if idx == n - 1:
arr = ["rock"] * n
for text in ["rock", "paper", "scissors"]:
new_combos.append(arr[:-1] + [text])
else:
last_combos = recurse(n, idx + 1)
for text in ["rock", "paper", "scissors"]:
for combo in last_combos:
new_combos.append(combo[:idx] + [text] + combo[idx + 1:])
return new_combos
def rock_paper_scissors(n, idx = 0):
if(n == 0):
return [[]]
new_combos = []
if idx == n - 1:
arr = ["rock"] * n
for text in ["rock", "paper", "scissors"]:
new_combos.append(arr[:-1] + [text])
else:
last_combos = rock_paper_scissors(n, idx + 1)
for text in ["rock", "paper", "scissors"]:
for combo in last_combos:
new_combos.append(combo[:idx] + [text] + combo[idx + 1:])
return new_combos
if __name__ == "__main__":
if len(sys.argv) > 1:
num_plays = int(sys.argv[1])
print(rock_paper_scissors(num_plays))
else:
print('Usage: rps.py [num_plays]') |
944624a0990b6696cd3f8ae891504c38b3e01911 | alexYooDev/pythonSyntax | /func_ex/def_lambda.py | 560 | 3.921875 | 4 | arr = [('jason', 28),('park', 40), ('ken', 45)]
def key_val(x):
return x[1] #정렬 기준 값 설정 => 배열 안 튜플의 1번째 값
print(sorted(arr, key=key_val)) #배열, 정렬기준(함수)
print(sorted(arr, key=lambda x: x[1]))
list1 = [1,2,3,4,5]
list2 = [6,7,8,9,10]
# lambda expression executing addition between the elements in each array in the same position
# map function checks each elements in the list and executes certain function
result = map(lambda a,b : a+b, list1, list2)
#contain the result in a new list
print(list(result)) |
378016e1b88fe1e1a28ad46a0273b8d712c09ccf | GabrielOduori/Codewars-Python | /palindrome_checker.py | 406 | 3.921875 | 4 | from collections import deque
def is_palindrome(characters):
character_deque = deque(characters)
while len(character_deque) > 1:
first_char = character_deque.popleft()
last_char = character_deque.pop()
if first_char != last_char:
return False
return True
print(is_palindrome('02022020'))
print(is_palindrome('radar'))
print(is_palindrome('morning')) |
06c1bc4e3c4c4931dc01f81f9701062e798a0deb | SrVladyslav/Algorithms | /python/hamiltonian_cycle.py | 1,109 | 3.734375 | 4 | from graph import Graph
from random import sample
class HamiltonianCycle:
def __init__(self, E):
self.E = E
self.G = Graph(E= self.E)
def solve(self):
def backtracking(path):
if len(path) == len(self.G.V):
if (path[-1], path[0]) in G.E: # The end is the starting point of a Graph
return path + [path[0]]
else:
for v in G.succs(path[-1]): # Next vertices
if v not in path: # Unexplored vertex
found = backtracking(path + [v]) # Let's explore it
if found:
return found
return None
[random, vertex] = sample(G.V, 1) # Pick a random vertex to start with
return backtracking([random, vertex])
if __name__ == '__main__':
hc = HamiltonianCycle(
E = [(0,1), (0,2), (0,3), (1,3), (1,4), (2,3), (2,5), (3,4), (3,5), (3,6), (4,7), (5,6), (5,8), (6,7), (6,8), (6,9) (7,9), (8,9)]
)
hc.solve() |
5efacc19ca8fdd92aaed771a3e7e88755e9e94a2 | leilacey/LIS-511 | /Chapter 3/names.py | 443 | 4.28125 | 4 | # 3-1 Name
friend_names = ['Shaun Spencer', 'Burton Guster', "Juliet O'Hara"]
print(friend_names[0])
print(friend_names[1])
print(friend_names[2])
#3-2 Greetings
for friend in friend_names:
message = "What's Up " + friend + "?"
print(message)
#3-3 Your Own List
transportation_comments = ["I would like to own a Chevy Camero", "I ride the bus almost everyday", "I like to drive fast"]
for comment in transportation_comments:
print (comment)
|
d14d7fe988e1fdbc1f9fba8b2c18790f8d561b15 | nikmois/python | /python_university/morse_code_translator.py | 5,573 | 3.546875 | 4 | import tkinter
from tkinter.font import Font
from tkinter import *
from tkinter import messagebox
top = tkinter.Tk()
top.title("Morse code translator")
top.geometry('350x320')
top.configure(bg="black")
font_1 = Font(family='fixedsys',
size=14,
weight='normal')
font_2 = Font(family='fixedsys',
size=9,
weight='normal')
text = StringVar()
code = StringVar()
l = Label(top, text="MORSE CODE TRANSLATOR", font = font_1, bg="black", fg = "chartreuse2")
l.grid(row = 1, columnspan = 2, padx = 50, pady = 15)
L1 = Label(top, text = "TEXT", padx = 5, font = font_2, bg="black", fg = "chartreuse2")
L1.grid(row = 2, column = 0, sticky = 'W', padx = 10, pady = (25,5))
E1 = Entry(top, textvariable = text, bd = 5, font = font_2, bg="black", fg = "chartreuse2")
E1.grid(row = 2, column = 1, sticky = 'W', padx = 50, pady = (25,5))
scrollbar1 = Scrollbar(top, orient = 'horizontal', command = E1.xview, width = 14)
scrollbar1.grid(row = 3, column = 1, sticky = 'we', padx = 50)
E1.configure(xscrollcommand=scrollbar1.set)
L2 = Label(top, text = "CODE", padx = 5, font = font_2, bg="black", fg = "chartreuse2")
L2.grid(row = 4, column = 0, sticky = 'W', padx = 10, pady = (25, 5))
E2 = Entry(top, bd = 5, textvariable = code, font = font_2, bg="black", fg = "chartreuse2")
E2.grid(row = 4, column = 1, sticky = 'W', padx = 50, pady = (25, 5))
scrollbar2 = Scrollbar(top, orient = 'horizontal', command = E2.xview, width = 14)
scrollbar2.grid(row = 5, column = 1, sticky = 'we', padx = 50)
E2.configure(xscrollcommand=scrollbar2.set)
var = IntVar()
def clearMorse():
morse_code = code.get()
code_length = len(morse_code)
E2.delete(0, code_length)
def clearText():
entered_text = text.get()
text_length = len(entered_text)
E1.delete(0, text_length)
L3 = Label(top, text = "TO MORSE", padx = 5, font = font_2, bg="black", fg = "chartreuse2")
L3.grid(row = 6, column = 0, sticky = 'W', padx = 10, pady = (5, 0))
R1 = Radiobutton(top, bg = 'black', variable = var, value = 1, cursor = 'hand2', command = clearMorse, activebackground = 'black', activeforeground = "chartreuse2")
R1.grid(row = 6, column = 1, sticky = 'W', pady = (5, 0))
L4 = Label(top, text = "TO TEXT", padx = 5, font = font_2, bg="black", fg = "chartreuse2")
L4.grid(row = 7, column = 0, sticky = 'W', padx = 10, pady = 1)
R2 = Radiobutton(top, bg = 'black', variable = var, value = 2, cursor = 'hand2', command = clearText, activebackground = 'black', activeforeground = "chartreuse2")
R2.grid(row = 7, column = 1, sticky = 'W')
def message1():
messagebox.showinfo("Text or code is missing", "Please write text or code which you want to translate")
def message2():
messagebox.showinfo("Choose morse or text", "Please choose in what you want to translate. Choose 'TO MORSE' or 'TO TEXT'")
def message3():
messagebox.showinfo("Error", "You can only write letters, numbers or spaces into 'TEXT' field")
def message4():
messagebox.showinfo("Error", "You can only write '-', '.', '|' or spaces into 'CODE' field. Please put space after every morse character. To put space between words use '|'. Put spaces before and after '|'")
def unknown():
messagebox.showinfo("Error", "Unknown Error appeared. Please try again later.")
def translate():
value = var.get()
text1 = text.get()
code1 = code.get()
library = {' ': '|','0': '-----', '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', '6': '-....',
'7': '--...', '8': '---..', '9': '----.','A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.',
'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.',
'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-', 'Y': '-.--', 'Z': '--..'}
library1 = {' ': '', '|': ' ', '-----': '0', '.----': '1', '..---': '2', '...--': '3', '....-': '4', '.....': '5', '-....': '6',
'--...': '7', '---..': '8', '----.': '9','.-': 'A', '-...': 'B', '-.-.': 'C', '-..': 'D', '.': 'E', '..-.': 'F',
'--.': 'G', '....': 'H', '..': 'I', '.---': 'J', '-.-': 'K', '.-..': 'L', '--': 'M', '-.': 'N', '---': 'O', '.--.': 'P',
'--.-': 'Q', '.-.': 'R', '...': 'S', '-': 'T', '..-': 'U', '...-': 'V', '.--': 'W', '-..-': 'X', '-.--': 'Y', '--..': 'Z'}
if text1 or code1:
if value:
if value == 1:
try:
E2.delete(0, len(code1))
morseCode = ""
for x in text1:
morseCode += library[x.upper()] + " "
E2.insert(0, morseCode)
E2.delete(len(morseCode)-1, len(morseCode))
except KeyError:
message3()
except:
unknown()
else:
try:
E1.delete(0, len(text1))
textEntry = ""
code2 = code1.split(" ")
for x in code2:
textEntry += library1[x]
E1.insert(0, textEntry)
except KeyError:
message4()
except:
unknown()
else:
message2()
else:
message1()
but = Button(top, command = translate, text="TRANSLATE", font = font_1, bg = 'black', bd = 5, fg = "chartreuse2", activebackground = 'black', activeforeground = "chartreuse2")
but.grid(row = 6, column = 1, pady = (40, 0))
top.mainloop()
|
36230437e15791b24b3dc37fb819fa5bb77cdf07 | zielman/Codeforces-solutions | /A/A 1504 Déjà Vu.py | 749 | 3.734375 | 4 | # https://codeforces.com/problemset/problem/1504/A
def isPalindrome(x):
if x == x[::-1]:
return True
else:
return False
def alla(string):
for i in range(len(string)):
if string[i] != 'a':
return False
return True
def main():
t = int(input())
strings = []
for i in range(t):
strings.append(input())
for string in strings:
if alla(string):
print('NO')
elif isPalindrome(f"a{string}") == False:
print('YES')
print(f"a{string}")
elif isPalindrome(f"{string}a") == False:
print('YES')
print(f"{string}a")
if __name__ == '__main__':
main() |
a1bb7a69dba65928ed75a6460853766de942e48e | amidoge/Python-2 | /ex072.py | 460 | 3.953125 | 4 | #I should get the original string and a reversed string.
#Then I will compare the two.
word = input("Word: ")
o = []
r = []
for i in range(len(word)):
o.append(word[i])
for i in range(len(word)):
r.append(word[-i - 1]) #So that it would be -1, -2, and so on.
same_count = 0
print(o)
print(r)
for i in range(len(word)):
if o[i] == r[i]:
same_count += 1
if same_count == len(word):
print("Palindrome")
else:
print("Non Palindrome") |
fdce8fd11b65830b7c265c903a4bcfa3bf3ac029 | krskelton/Python-Projects | /DB/createdb.py | 1,606 | 4 | 4 | import sqlite3
#connect to a database
conn = sqlite3.connect('example.db')
#while the connection is open
with conn:
#the cursor is operating on the db
cur = conn.cursor()
#build the database
cur.execute("CREATE TABLE IF NOT EXISTS tbl_files( \
ID INTEGER PRIMARY KEY AUTOINCREMENT, \
col_fileName TEXT)")
#commit the changes
conn.commit()
#close the connection to the db
conn.close()
#connect to a database again
conn = sqlite3.connect('example.db')
#while the connection is open
with conn:
#the cursor is operating on the db
cur = conn.cursor()
#create the list of files
fileList = ('information.docx', 'Hello.txt', 'myImage.png', \
'myMovie.mpg', 'World.txt', 'data.pdf', 'myPhoto.jpg')
#iterate through fileList and find the files that end with .txt
for file in fileList:
if file.endswith(".txt"):
#add the file to the db
cur.execute("INSERT INTO tbl_files(col_fileName) VALUES(?)", (file,))
#commit the changes
conn.commit()
#close the db
conn.close()
#connect to a database again
conn = sqlite3.connect('example.db')
#while the connection is open
with conn:
#the cursor is operating on the db
cur = conn.cursor()
#build the database
cur.execute("SELECT col_fileName FROM tbl_files")
#get the info on the cursor cause that's where the command you just executed lives
varFiles = cur.fetchall()
#iterate through the tuple
for item in varFiles:
print(item[0])
msg = "File Name: {}".format(item[0])
print(msg)
|
cf3c8cc53e234ce02c99b0d835ae0ed40cdbf0c4 | jayeshhinge98/demo | /python/Inheritance.py | 469 | 4.0625 | 4 | ######Inheritance allows us to define calls in terms of another class.
class Parent:
value1="Jayesh"
value2="Hinge"
def sum(self,a,b):
return a+b
class Parent2():
value3="FIGmd"
class Child (Parent,Parent2):
pass
# print("Value 1 is:",p.value1)
# print("Value 2 is:",p1.value2) #will not work we need to add Parent2(Parent)
# print("Value 3 is:",p1.value3)
#p1=Parent2()
#p1.sum(20,30)
#c=Child()
#c.value1
#c.value2
#c.value3
|
007a92615dad9f7964ba2c5a639321c635c27a9f | Ochirgarid/algorithms | /basics/problem-4/code_py/pentagon_p_solution-garid.py | 584 | 3.734375 | 4 | #!/usr/bin/env python
"""
File: pentagon_p_solution-garid.py
Find the perimeter of pentagon.
"""
__author__ = "Ochirgarid Chinzorig (Ochirgarid)"
__version__ = "1.0"
# Open file on read mode
inp = open("../test/test1.txt", "r")
# read input lines one by one
# and convert them to integer
a = int(inp.readline().strip())
b = int(inp.readline().strip())
c = int(inp.readline().strip())
d = int(inp.readline().strip())
e = int(inp.readline().strip())
# must close opened file
inp.close()
# calculate perimeter
p = a + b + c + d + e
# print for std out
print("Perimeter : {}".format(p))
|
768f99a41f7f98f1d599beb2347c6c53867ef75b | tianyunzqs/LeetCodePractise | /leetcode_21_40/31_nextPermutation.py | 1,572 | 3.71875 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/6/17 11:45
# @Author : tianyunzqs
# @Description :
def nextPermutation2(nums) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
if sorted(nums, reverse=True) == nums:
nums.sort()
return
if len(nums) < 3:
nums.sort(reverse=True)
return
for i in range(len(nums) - 1, -1, -1):
for j in range(i + 1, len(nums)):
if nums[j] > nums[i]:
tmp = nums[i]
nums[i] = nums[j]
nums[j] = tmp
nums[i + 1:] = sorted(nums[i + 1:])
return
def nextPermutation(nums) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
i = len(nums) - 1
# find non - descending series(ascending series)
while i > 0:
if nums[i] > nums[i - 1]:
break
i -= 1
# reverse(let this sub - sequence from descending to ascending)
nums[i:] = sorted(nums[i:])
# So-far, we can make sure this sub-sequence is ascending.But this sequence
# is always lower than previous(1132->1123, 132->123)
# This sub-sequence always fewer or equal to the origin.
# So, we must find the second minimum(except the original) sub - sequence.
if i == 0:
return
for s in range(i, len(nums)):
if nums[s] > nums[i - 1]:
tmp = nums[i - 1]
nums[i - 1] = nums[s]
nums[s] = tmp
break
a = [4,2,0,2,3,2,1]
# a = [1,3,2]
nextPermutation(a)
print(a)
|
b45e2ab411a9d0054d0f993652159590409bae09 | jmwest/Web-Database-Design | /proj2/pa2_rkrjjwkx1or/controllers/encryptPassword.py | 677 | 3.609375 | 4 | import hashlib
import uuid
#this function takes in a plaintext string, and returns the ciphertext with salt
def encryptPassword(algorithm, plainPass, givenSalt = None):
if givenSalt:
salt = givenSalt
else:
salt = uuid.uuid4().hex # salt as a hex string for storage in db
m = hashlib.new(algorithm)
plainPass = plainPass.encode('utf-8')
salt = salt.encode('utf-8')
m.update(salt + plainPass)
password_hash = m.hexdigest()
return [ salt, password_hash ]
def createPasswordForDatabaseInsert(algorithm, password):
encryption = encryptPassword(algorithm, password)
salt = encryption[0]
password_hash = encryption[1]
return "$".join([algorithm,salt,password_hash]) |
1abc1ef8eec422f017fe94ffa4d3601f33cff8f8 | shortdistance/workdir | /Python_Learning/testConnectiondeque.py | 418 | 3.765625 | 4 | #-*-coding:utf-8-*-
if __name__ == '__main__':
from collections import deque
d = deque('abcd')
d.append('d')
print d
d.remove('d')
print d
d.pop() #ȳ
print d
d.popleft() #ȳ
print d
d1 = deque("hello world")
d1.reverse() #ת
print d1
d1.rotate(-5)
print d1
print deque(open('D:\\12345.txt'), 5)
pass
|
d63d06aa5f4a559b18b0fc24d66d2e9d693ccee4 | OliverGeisel/sudokusat-example | /my_solver/oliver/PuzzleInfo.py | 2,844 | 3.5 | 4 | import math
import os
class PuzzleInfo:
def __init__(self, path_of_file: str, length: int = 9, text: str = ""):
self.input_file_path, self.input_file_name = os.path.split(os.path.abspath(path_of_file))
self.length = length # values from 1 to length
self.sqrt_of_length = int(math.sqrt(self.length))
self.square_of_length = length ** 2
self.text = text # further information
self.values = list(range(1, length + 1))
self.values_zero = list(range(length))
self.task = os.path.splitext(self.input_file_name)[0]
def input_file_complete_absolute(self):
return os.path.join(self.input_file_path, self.input_file_name)
def input_file_complete_rel(self):
return os.path.relpath(self.input_file_complete_absolute())
class PuzzleInfoInput(PuzzleInfo):
def __init__(self, path_of_file: str, length: int = 9, text: str = ""):
super().__init__(path_of_file, length, text)
self.start_line = 5 # depends on first line with '+'
self.end_line = self.start_line + length + self.sqrt_of_length
class PuzzleInfoEncode(PuzzleInfo):
def __init__(self, path: str, length=9, text=""):
super().__init__(path, length, text)
self.output_file_path = self.SAT_solution_file_path = self.input_file_path
self.output_file_name = self.input_file_name.replace(".txt", ".cnf")
self.SAT_solution_file_name = self.output_file_name.replace(".cnf", "-SAT-sol.txt")
self.temp_files = list()
def __int__(self, info: PuzzleInfoInput):
self.__init__(info.input_file_complete_absolute(), info.length, info.text)
def output_file_complete_absolute(self):
return os.path.join(self.output_file_path, self.output_file_name)
def output_file_complete_rel(self):
return os.path.relpath(self.output_file_complete_absolute())
def SAT_solution_file_complete_absolute(self):
return os.path.join(self.SAT_solution_file_path, self.SAT_solution_file_name)
def SAT_solution_file_complete_rel(self):
return os.path.relpath(self.SAT_solution_file_complete_absolute())
class PuzzleInfoOutput(PuzzleInfo):
def __init__(self, encode_info: PuzzleInfoEncode):
super().__init__(encode_info.output_file_complete_absolute(), encode_info.length, encode_info.text)
self.output_file_path = self.input_file_path
self.input_file_name = encode_info.SAT_solution_file_name
self.output_file_name = encode_info.SAT_solution_file_name.replace("-SAT-sol.txt", "-solution.txt")
self.task = encode_info.task
def output_file_complete_absolute(self):
return os.path.join(self.output_file_path, self.output_file_name)
def output_file_complete_rel(self):
return os.path.relpath(self.output_file_complete_absolute())
|
12a1acabeed0741d930ac6ec31b3c7da3d39c41c | NoahToomeyBC/Election_Analysis | /PyPoll_2.Py | 957 | 3.84375 | 4 | # Import the csv and os modules
import os
import csv
# Open Election Results csv and assign variable for it
file_to_load = 'Resources/election_results.csv'
#Open and Read election results
election_data = open(file_to_load, 'r')
# Open the election results and read the file
with open(file_to_load) as election_data:
print(election_data)
#Close the file
election_data.close
# Create an analysis txt file csv and assign variable for it
file_to_save = 'Analysis/election_analysis.txt'
#Open and Write election results
with open(file_to_save, 'w') as txt_file:
#Write three counties to the file
txt_file.write("Counties in the election\n________________\n\nArapahoe\nDenver\nJefferson")
# Data that needs to be gotten
# Total number of votes cast
# List of candidates who received votes
# Total number of votes
# Percentage of votes per candidate
# Total number of votes per candidate
# Winner of the election based on popular vote |
672180057f4c5ad43423f9971f0eea474c43f810 | matbrik/python-mix | /Python Mix/Python Mix/Bots/bot_part_obs.py | 4,847 | 3.53125 | 4 | #!/usr/bin/python3
import os
def next_move(posx, posy, board):
mem_board,lastMove=load_mem("test.txt")
#print(mem_board)
#update mem_board
try:
for i in range(5):
for j in range(5):
if board[i][j]!='o':
mem_board[i][j]=board[i][j]
except (ValueError,IndexError):
print(i)
print(j)
print(board)
print(mem_board)
print(load_mem("test.txt"))
with open('test.txt', 'r') as content_file:
content = content_file.read()
print(content)
#print(mem_board)
if mem_board[posx][posy]=='d':
print("CLEAN")
save_mem("test.txt",mem_board, lastMove)
#save_mem("test.txt",mem_board)
return
#if lastMove=="None":
# print(board)
# print(mem_board)
#greedy strategy from the others if there is a d
md= 99
bstr=-1
bstc=-1
for i in range(5):
for j in range(5):
if mem_board[i][j]== 'd':
if((abs(posx-i)+abs(posy-j))<md):
md= abs(posx-i)+abs(posy-j)
bstr=i
bstc=j
if bstr!=-1:
if bstc > posy:
print("RIGHT")
save_mem("test.txt",mem_board, "RIGHT")
return
if bstc < posy:
print("LEFT")
save_mem("test.txt",mem_board, "LEFT")
return
if bstr > posx:
print("DOWN")
save_mem("test.txt",mem_board, "DOWN")
return
if bstr < posx:
print("UP")
save_mem("test.txt",mem_board, "UP")
return
#now i have to decide in which direction go
# gain = 1/dist
gainUp=0
for i in range(posx):
for j in range(5):
if mem_board[i][j]=='o':
gainUp+=1/float((abs(posx-i)+abs(posy-j)))
gainDown=0
for i in range(posx,5):
for j in range(5):
if mem_board[i][j]=='o':
gainDown+=1/float((abs(posx-i)+abs(posy-j)))
gainLeft=0
for i in range(5):
for j in range(posy):
if mem_board[i][j]=='o':
gainLeft+=1/float((abs(posx-i)+abs(posy-j)))
gainRight=0
for i in range(5):
for j in range(posy,5):
if mem_board[i][j]=='o':
gainRight+=1/float((abs(posx-i)+abs(posy-j)))
if(gainUp==max(gainUp,gainDown,gainLeft,gainRight) and lastMove!="DOWN" and gainUp!=0 and posx!=0 ):
print("UP")
save_mem("test.txt",mem_board, "UP")
return
if(gainDown==max(gainDown,gainLeft,gainRight) and lastMove!="UP" and gainDown!=0 and posx!=4):
print("DOWN")
save_mem("test.txt",mem_board, "DOWN")
return
if(gainLeft==max(gainLeft,gainRight) and lastMove!="RIGHT" and gainLeft!=0 and posy!=0 ):
print("LEFT")
save_mem("test.txt",mem_board, "LEFT")
return
if(lastMove!="LEFT" and gainRight!=0 and posy!=4):
print("RIGHT")
save_mem("test.txt",mem_board, "RIGHT")
return
if(gainUp==max(gainUp,gainDown,gainLeft,gainRight) and gainUp!=0 and posx!=0):
print("UP")
save_mem("test.txt",mem_board, "UP")
return
if(gainDown==max(gainDown,gainLeft,gainRight) and gainDown!=0 and posx!=4):
print("DOWN")
save_mem("test.txt",mem_board, "DOWN")
return
if(gainLeft==max(gainLeft,gainRight) and gainLeft!=0 and posy!=0):
print("LEFT")
save_mem("test.txt",mem_board, "LEFT")
return
if(gainRight!=0 and posy!=4):
print("RIGHT")
save_mem("test.txt",mem_board, "RIGHT")
return
return
def load_mem(filename):
board_t=[['o', 'o', 'o', 'o', 'o'], ['o', 'o', 'o', 'o', 'o'], ['o', 'o', 'o', 'o', 'o'], ['o', 'o', 'o', 'o', 'o'], ['o', 'o', 'o', 'o', 'o']]
lastMove="None"
if not os.path.isfile('./test.txt'):
return [board_t, lastMove]
with open( filename ) as f:
# file read can happen here
# print "file exists"
lastMove=f.readline()
lastMove=lastMove.strip()
board_t = [[j for j in f.readline().strip()] for i in range(5)]
return [board_t, lastMove]
def save_mem(filename, mem_board, lastMove):
with open( filename, "w") as f:
f.write(lastMove+'\n')
# print "file write happening here"
for i in mem_board:
line=""
for j in i:
line+=j
#print(line, file=f)
f.write(line + '\n')
if __name__ == "__main__":
pos = [int(i) for i in input().strip().split()]
board = [[j for j in input().strip()] for i in range(5)]
next_move(pos[0], pos[1], board)
|
deefae2a4880f502e705500a2ce3ea3c707b896b | chaochaogege/leetcode_simple_01 | /simplecode01.py | 488 | 3.546875 | 4 | #coding=utf8
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
j=i+1
for j in range(len(nums)):
if (i!=j):
if (nums[i]+nums[j]==target):
return i,j
if __name__ == '__main__':
print(twototle([1, 4, 3, 5, 2], 7))
|
50836f22848f2e3b0bfeb91d7ebddb2026028c78 | nandansn/pythonlab | /Learning/tutorials/workouts/area_of_triangle.py | 153 | 3.921875 | 4 | height = input('enter height of triangle:')
base = input('enter base of triangle:')
areaOfTriangle = (int(base) * int(height))/2
print(areaOfTriangle)
|
3461f39203aa36c5df687f19091bce9034770fbf | SlawekMaciejewski/Python_exercises | /oop/oop_dziedziczenie_employee.py | 2,271 | 3.609375 | 4 | import datetime
class Employee:
raise_amount = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
# self.email = f'{first}.{last}@aptor.com' # uzywajac @property mozemy zrezygnowac z tego atrybutu
@property
def email(self):
return f'{self.first}.{self.last}@aptor.com'
@property
def full_name(self):
return f'{self.first} {self.last}'
@full_name.setter
def full_name(self, name: str):
self.first, self.last = name.split()
@full_name.deleter
def full_name(self):
self.first = None
self.last = None
def applay_raise(self):
self.pay = int(self.pay * self.raise_amount)
@classmethod
def set_raise_amount(cls, new_raise_amount):
cls.raise_amount = new_raise_amount
@staticmethod
def is_workday(day):
return day.weekday() is not (5, 6)
class Developer(Employee):
raise_amount = 1.10
def __init__(self, first, last, pay, programming_language):
super().__init__(first, last, pay)
self.programming_language = programming_language
class Manager(Employee):
def __init__(self, first, last, pay, employees=None):
super().__init__(first, last, pay)
if employees is None:
self.employees = set()
else:
self.employees = set(employees)
def add_employee(self, employee):
self.employees.add(employee)
def remove_employee(self, employee):
self.employees.remove(employee)
def print_employes(self):
for employee in self.employees:
print(employee.full_name)
if __name__ == '__main__':
wisniewska = Employee('Anna', 'Wiśniewska', 6000)
kowalski = Employee('Emil', 'Kowalski', 8000)
nowak = Developer('Jan', 'Nowak', 10000, 'Java')
dlugosz = Developer('Marek', 'Długosz', 9000, 'Python')
klich = Manager('Darek', 'Klich', 15000, {wisniewska, kowalski, nowak, dlugosz})
klich.print_employes()
print('*************')
michalska = Employee('Nina', 'Michalska', 5000)
klich.add_employee(michalska)
klich.print_employes()
print('*************')
klich.remove_employee(dlugosz)
klich.print_employes()
nowak.applay_raise()
print(nowak.pay)
|
55a232999d194319035c72452f6cd835e63e035d | yanmarcossn97/Python-Basico | /Exercicios/exercicio018.py | 322 | 3.9375 | 4 | import math
# math.sin(x) - retorna o seno de x
# math.cos(x) - retorna o cosseno de x
# math.tan(x) - retorna a tangente de x
x = float(input('Insira um ângulo qualquer em radianos: '))
print('Seno: {}.'.format(math.sin(x)))
print('Cosseno: {}.'.format(math.cos(x)))
print('Tangente: {}.'.format(math.tan(x)))
|
55ddf39ac080a044495de1f86ccf4dd925c9c894 | SakshayMahna/Robotics-Mechanics | /Part-3-TestingVisualization/visualize.py | 1,462 | 3.796875 | 4 | """
Visualize the transformations
Matplotlib:
quiver plot
"""
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
# Function to plot a single transformation
def plot_transformation(transformation):
"""
Plot Transformation matrix
...
Parameters
---
transformation: 4x4 transformation matrix
Returns
---
None
Notes
---
RGB -> XYZ
"""
fig = plt.figure()
ax = fig.gca(projection='3d')
# x, y, z of 6 arrows in a quiver plot
x = np.array([0, 0, 0, transformation[0, 3], transformation[0, 3], transformation[0, 3]])
y = np.array([0, 0, 0, transformation[1, 3], transformation[1, 3], transformation[1, 3]])
z = np.array([0, 0, 0, transformation[2, 3], transformation[2, 3], transformation[2, 3]])
# u, v, w of 6 arrows in a quiver plot
u = np.concatenate([np.array([1, 0, 0]), transformation[:3, 0]])
v = np.concatenate([np.array([0, 1, 0]), transformation[:3, 1]])
w = np.concatenate([np.array([0, 0, 1]), transformation[:3, 2]])
# Color(RGB) for 6 arrows, original X, Y, Z and then transformed X, Y, Z
red = np.array([1, 0, 0])
green = np.array([0, 1, 0])
blue = np.array([0, 0, 1])
colors = np.array([red, green, blue, red, green, blue])
q = ax.quiver(x, y, z, u, v, w, length=0.05, colors = colors, lw=1)
plt.plot([x[0], x[3]], [y[0], y[3]], [z[0], z[3]], '--', color = 'black')
plt.show() |
607a64ad8b5dfc8aabf7ee78ba793586f338c664 | fructoast/Simulation-Eng | /simu1023/pi_monte.py | 310 | 3.609375 | 4 | #coding:utf-8
import math
import random
def return_area(a,b):
return math.sqrt(a**2+b**2)
pi = 0.0
times = 0
for i in range(1000000000000000000):
if 1 > return_area(random.uniform(0,1),random.uniform(0,1)):
pi += 1
times += 1
if times%10 == 1:
print("pi:"+str((4*pi)/times))
|
c4d3d68b1082f98123c96aef1b52a898583d1417 | ritamghoshritam/PythonApplications-SourceCode | /Story_Narrator.py | 738 | 3.890625 | 4 | import random
import time
def gen():
i = 0
while i < 5:
i += 1
words1 = ["Surprize", "Tears", "Smile", "Sadness", "Rage", "love"]
words2 = [" against the", "over the", "of the", "for the"]
words3 = [" shadow", " light", " star", "sun", "moon"]
words4 = ["for the money", " in a lifetime", "in the shadow", "in a reflection", "for the star", "for the love", "in the darkness"]
one = random.choice(words1)
two = random.choice(words2)
three = random.choice(words3)
four = random.choice(words4)
print(one + two + three + four)
while True:
print("Generating a story one after the another in 3 seconds of time interval")
time.sleep(3)
gen()
|
8c1c5a88ab9d3b3e1b2d6b673c9d36454ea274ed | GodsloveIsuor123/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/100-print_tebahpla.py | 100 | 3.875 | 4 | #!/usr/bin/python3
for i in range(122, 96, -2):
print("{}{}".format(chr(i), chr(i-33)), end='')
|
d9401145538efa4e493a200eaae54f9faa363913 | malloryeastburn/Sudoku-Solver-PY | /game.py | 4,306 | 3.84375 | 4 | from tkinter import *
import tkinter.font as tkFont
from functools import partial
root = Tk()
root.title("Sudoku Solver")
root.iconbitmap("C:\\Users\\mallo\\OneDrive\\Desktop\\images\\sudokuIcon.ico")
fontStyle = tkFont.Font(family="Lucida Grande", size=30)
#Default board
board = [
[7,8,0,4,0,0,1,2,0],
[6,0,0,0,7,5,0,0,9],
[0,0,0,6,0,1,0,7,8],
[0,0,7,0,4,0,2,6,0],
[0,0,1,0,5,0,9,3,0],
[9,0,4,0,6,0,0,0,5],
[0,7,0,3,0,0,0,1,2],
[1,2,0,0,0,7,4,0,0],
[0,4,9,2,0,6,0,0,7]
]
button_identities = []
def select_number(num):
global number
number = num + 1
return
def assign_number(i,j):
if i == 0:
objectName = (button_identities[j])
else:
objectName = (button_identities[j+len(board[0]) * i])
objectName.configure(text=number)
return
for i in range(len(board)):
for j in range(len(board[0])):
cur_button = "cur_button" + str(i) + str(j)
if i // 3 != 1 and j // 3 != 1 or i // 3 == 1 and j // 3 == 1:
rlf="solid"
else:
rlf="raised"
cur_button = Button(root, font=fontStyle, width=3, height=1, relief=rlf, command=partial(assign_number,i,j))
button_identities.append(cur_button)
cur_button.grid(row=i, column=j)
for i in range(len(board[0])):
cur_num="num" + str(i)
cur_num = Button(root, text=i+1, font=fontStyle, width=3, height=1, borderwidth=3, relief="solid", command=partial(select_number,i))
cur_num.grid(row=len(board)+1, column=i)
blank = Label(root, text="")
blank.grid(row=9, column=0)
def clear_board():
for item in button_identities:
item.configure(text='')
return
def solve_board():
for index in range(len(button_identities)):
if button_identities[index]['text'] == '':
board[index//9][index%9] = 0
else:
board[index//9][index%9] = button_identities[index]['text']
#If solved, prints board, else: Display no solution
if solve(board) == True:
print("\nSolved:")
print_board(board)
for index in range(len(button_identities)):
text = board[index//9][index%9]
button_identities[index].configure(text=text)
else:
print("\nNo solution")
return
btn_empty = Button(root, text="Clear Board", font=fontStyle, width=12, height=1, relief="solid", command=clear_board)
btn_solve = Button(root, text="Solve", font=fontStyle, width=12, height=1, relief="solid", command=solve_board)
btn_empty.grid(row=len(board)+2, column=0, columnspan=4)
btn_solve.grid(row=len(board)+2, column=5, columnspan=4)
#Backtracking function that solves the board. Calls itself when a solution is invalid until the board is solved
def solve(board):
find = find_empty(board)
if not find:
return True
else:
row, col = find
for i in range(1, 10):
if valid(board, i, (row, col)):
board[row][col] = i
if solve(board):
return True
board[row][col] = 0
return False
#checks to see if a number is valid
def valid(board, num, pos):
for i in range(len(board[0])):
if board[pos[0]][i] == num and pos[1] != i:
return False
for i in range(len(board)):
if board[i][pos[1]] == num and pos[0] != i:
return False
box_x = pos[1] // 3 # column
box_y = pos[0] // 3 # row
for i in range(box_y*3, box_y*3 + 3):
for j in range(box_x*3, box_x*3 + 3):
if board[i][j] == num and (i,j) != pos:
return False
return True
#Displays the board in a readable way
def print_board(board):
for i in range(len(board)):
if i % 3 == 0 and i != 0:
print("- - - - - - - - - - -")
for j in range(len(board[0])):
if j % 3 == 0 and j != 0:
print("| ", end="")
if j == 8:
print(board[i][j])
else:
print(str(board[i][j]) + " ", end="")
#Finds the next empty space
def find_empty(board):
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == 0:
return (i, j)
return None
#Prints the board before it is solved
print("Unsolved:")
print_board(board)
root.mainloop() |
00b9d66218aa9645ed7364321537c8967f8df69c | pierre-crucifix/real-spanish | /word_adjacency_matrix_builder.py | 2,732 | 3.609375 | 4 | """
Script #4
1) Create the adjacency matrix of words in tweets.
2) Two words are considered adjacent iff they are present in the same tweet, which proxy the fact they are used in the same context
In my situation, I chose not to work with a sparse matrix because my graph is quite dense, but it can be interesting to proceed diffently in another context
3) Still in my situation, I decided to remove all words with less than 11 occurrences in order to remove the vast majority of mispelled words
"""
import pandas as pd
import numpy as np
from ast import literal_eval
import time
start = time.time()
df_tweets=pd.read_csv(r".\3.Word Matrices\CleanedTweets.csv",index_col=0)
df_words=pd.read_csv(r".\3.Word Matrices\WordsFrequency.csv",index_col=0)
#remove less common words in order to make a more relevant analysis
length_df_words_before_drop=df_words["frequency"].count()
df_words=df_words[df_words["frequency"]>10]#Remove 'uncommon' words because they may be mispelled words, and we have enough words in total for our purpose
length_df_words_after_drop=df_words["frequency"].count()
diff_length=length_df_words_before_drop-length_df_words_after_drop
print("Removed "+str(diff_length)+" ("+str(int(diff_length/length_df_words_before_drop*100)) +"%) words with a low frequency")
df_tweets["words"] = df_tweets["words"].apply(literal_eval)#Necessary step to recognize the list of string
words=df_words.index.tolist()
len_words=len(words)
filling=np.zeros((len_words,len_words), dtype=int)
df_adjacency_matrix=pd.DataFrame(filling, columns=words)
df_adjacency_matrix["Index_incoming"]=words
df_adjacency_matrix=df_adjacency_matrix.set_index("Index_incoming")
# length=df_tweets["words"].count()
# current=0
for index, value in df_tweets["words"].iteritems():#It is a series not a dataframe => iteritems instead of iterrows
# current+=1
# print(str(current/length*100)+" % done")
a=value
b=value
for i in a:
for j in b:
# print(i, j)
if i!=j:
try:
df_adjacency_matrix.loc[i,j]+=1
except KeyError:#We shortened the word list, so it will happend quite often (but not often enough to check with isin)
pass
elapsed = time.time() - start
min= int(elapsed/60)
sec=int(elapsed%60)
print("required "+str(min)+" min and "+str(sec)+" sec to process")
df_adjacency_matrix.to_csv(r".\3.Word Matrices\WordsAdjacencyMatrix.csv")
df_adjacency_matrix.to_excel(r".\3.Word Matrices\WordsAdjacencyMatrix.xlsx")
df_words.to_csv(r".\3.Word Matrices\WordsFrequencyShortened.csv")
df_words.to_excel(r".\3.Word Matrices\WordsFrequencyShortened.xlsx") |
c9ddce318374df69bf276128eb92cd74e5012001 | DDoeDDoe32/Python | /example/temp5.py | 415 | 3.890625 | 4 | '''
num1 = 20
num2 = 30
if(num1 > num2) : #False
print('{0} > {1}'.format(num1, num2))
else :
print('{0} <= {1}'.format(num1, num2))
'''
'''
if(num1 == num2) : #False
print('{0} == {1}'.format(nu1, num2))
'''
score = 70
if(score >= 90) :
print('수')
elif(score >= 80) :
print('우')
elif(score >= 70) :
print('미')
elif(score >= 60) :
print('양')
else :
print('가')
|
5a6d8c3bc1e3004fec883de6d29f1ba4d00673b7 | icesx/IPython | /python-base/src/learn/yields/yield.py | 899 | 3.96875 | 4 | # coding:utf-8
# Copyright (C)
# Author: I
# Contact: 12157724@qq.com
#
#
# yield retrun value ,next continue
def foo(num):
print("starting...")
num = 4
print("numxx")
while num < 10:
print("num:", num)
num = num + 1
yield num
num = num + 1
print("after yield", num)
for n in foo(0):
print("outter", n)
gennerator = (x * x for x in range(3))
print("gennerator", next(gennerator))
print("gennerator", next(gennerator))
def sample():
yield 1
yield 2
yield [3, 4, 5]
yield from [6, 7, 8]
yield 9
for i in sample():
print("sample", i)
def create_generator():
mylist = range(3)
for i in mylist:
yield i * i
cg = create_generator()
print(cg)
for i in cg:
print("cg", i)
###yeild from
def b():
r = yield from c()
def c():
yield from [1, 2, 3]
for i in b():
print("yield from ", i)
|
19a6fc07a3684d5022e17b54e5f51655a242bbd1 | pvkc8888/python-testprograms | /Algos Hackerrank/Strings/sherlock_and_anagrams.py | 1,025 | 4.15625 | 4 | #!/bin/python3
# simple function to calculate factorial of n
def factorial(n):
if n == 1:
return 1
else:
return n * (n - 1)
def sherlockAndAnagrams(s):
anagrams = 0
Dict = {}
for i in range(len(s)):
for item in range(i, len(s)):
# storing all the unique strings in dict and noting down how many of them exist
try:
string = s[i:item + 1]
string = ''.join(sorted(string))
if string in list(Dict.keys()):
Dict[string] += 1
else:
Dict[string] = 1
except IndexError:
pass
# calulating the different pairs posssible and summing them up to get the total number of anagrams.
for values in Dict.values():
if values > 1:
anagrams += factorial(values) // 2
return anagrams
q = int(input().strip())
for a0 in range(q):
s = input().strip()
result = sherlockAndAnagrams(s)
print(result)
|
d38fe5ad10de9595a1bb813f1cbb5eb5717e4f6d | muhammed-ayman/CSCI-101-course-labs-solutions | /10/05.py | 211 | 3.96875 | 4 | dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}
dict2 = {'Thirty': 30, 'Fourty': 40, 'Fifty': 50}
# Answer 1:
for i in dict2.keys():
dict1[i] = dict2[i]
# Answer 2:
dict1.update(dict2.copy())
print(dict1)
|
01e3c96fefe13c360848f89f5c602689aabaac7b | chjdev/euler | /python/problem7.py | 1,107 | 3.828125 | 4 | # 10001st prime
# Problem 7
#
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
# What is the 10001st prime number?
import itertools
N = 10001
def is_divisible_by_one(x, factors):
for factor in factors:
if x % factor == 0:
return True
return False
def gen_prime(limit=None):
assert limit is None or limit >= 2
sieve = [2, 3] # because 2 is the only even prime
yield sieve[-2]
yield sieve[-1]
while True:
generator = filter(lambda v: not is_divisible_by_one(v, sieve),
itertools.count(sieve[-1] + 2, 2))
new_prime = next(generator)
if not limit is None and new_prime > limit > 0:
return
else:
sieve.append(new_prime)
print(new_prime)
yield sieve[-1]
# https://docs.python.org/2/library/itertools.html#recipes
def nth(iterable, n, default=None):
"""Returns the nth item or a default value"""
return next(itertools.islice(iterable, n, None), default)
print(nth(gen_prime(), N - 1))
|
bdbb8e5015da3fdbdb16163d489e31146274d49b | ranajaydas/AutomateBoringProject | /os_directorysize.py | 345 | 3.578125 | 4 | """Prints the total size of all the files in a specified path."""
import os
total_size = 0
directory_name = 'D:\\Installation Files'
for filename in os.listdir(directory_name):
total_size += os.path.getsize(os.path.join(directory_name, filename))
print('{} bytes'.format(total_size))
print('or {0:.2f} GB'.format(total_size/1073741824))
|
bf09200ec1c86612901bd2e3f172be0522b6805c | jennLam/skills-assessment-2-dictionaries | /practice.py | 5,278 | 4.46875 | 4 | """Dictionaries Practice
**IMPORTANT:** These problems are meant to be solved using
dictionaries and sets.
"""
def without_duplicates(words):
"""Given a list of words, return list with duplicates removed.
For example::
>>> sorted(without_duplicates(
... ["rose", "is", "a", "rose", "is", "a", "rose"]))
['a', 'is', 'rose']
You should treat differently-capitalized words as different:
>>> sorted(without_duplicates(
... ["Rose", "is", "a", "rose", "is", "a", "rose"]))
['Rose', 'a', 'is', 'rose']
An empty list should return an empty list::
>>> sorted(without_duplicates(
... []))
[]
The function should work for a list containing integers::
>>> sorted(without_duplicates([111111, 2, 33333, 2]))
[2, 33333, 111111]
"""
#converts list of words to set to remove duplicate items
return set(words)
def find_unique_common_items(items1, items2):
"""Produce the set of *unique* common items in two lists.
Given two lists, return a list of the *unique* common items
shared between the lists.
**IMPORTANT**: you may not use `'if ___ in ___``
or the method `list.index()`.
This should find [1, 2]::
>>> sorted(find_unique_common_items([1, 2, 3, 4], [2, 1]))
[1, 2]
However, now we only want unique items, so for these lists,
don't show more than 1 or 2 once::
>>> sorted(find_unique_common_items([3, 2, 1], [1, 1, 2, 2]))
[1, 2]
The elements should not be treated as duplicates if they are
different data types::
>>> sorted(find_unique_common_items(["2", "1", 2], [2, 1]))
[2]
"""
#convert both lists to sets and use set math to find intersection
unique_items = sorted(set(items1) & set(items2))
return unique_items
def get_sum_zero_pairs(numbers):
"""Given list of numbers, return list of pairs summing to 0.
Given a list of numbers, add up each individual pair of numbers.
Return a list of each pair of numbers that adds up to 0.
For example::
>>> sort_pairs( get_sum_zero_pairs([1, 2, 3, -2, -1]) )
[[-2, 2], [-1, 1]]
>>> sort_pairs( get_sum_zero_pairs([3, -3, 2, 1, -2, -1]) )
[[-3, 3], [-2, 2], [-1, 1]]
This should always be a unique list, even if there are
duplicates in the input list::
>>> sort_pairs( get_sum_zero_pairs([1, 2, 3, -2, -1, 1, 1]) )
[[-2, 2], [-1, 1]]
Of course, if there are one or more zeros to pair together,
that's fine, too (even a single zero can pair with itself)::
>>> sort_pairs( get_sum_zero_pairs([1, 3, -1, 1, 1, 0]) )
[[-1, 1], [0, 0]]
"""
#create a set of the numbers list to remove duplicates
num_set = sorted(set(numbers))
#create an empty list to store lists of pairs
pair_list = []
#loop through each number in number set
#if number is a negative number and the absolute value of
#itself is in the number set, append the negative number
#and the absolute value of itself to pair list
#also append if number is 0
for num in num_set:
if num <= 0 and abs(num) in num_set:
pair_list.append([num, abs(num)])
return pair_list
def top_chars(phrase):
"""Find most common character(s) in string.
Given an input string, return a list of character(s) which
appear(s) the most in the input string.
If there is a tie, the order of the characters in the returned
list should be alphabetical.
For example::
>>> top_chars("The rain in spain stays mainly in the plain.")
['i', 'n']
If there is not a tie, simply return a list with one item.
For example::
>>> top_chars("Shake it off, shake it off.")
['f']
Do not count spaces, but count all other characters.
"""
#create an empty dictionary
letter_dict = {}
#change the string to remove the spaces in between words
phrase = phrase.replace(" ", "")
#create a list store most repeated characters
top_chars_list = []
#loop through each letter in the string, phrase
for letter in phrase:
#set each letter to be a key in the dictionary
#if the letter does not exist, set it 0 and add 1
#if the letter does exist, one 1 to its current value
letter_dict[letter] = letter_dict.get(letter, 0) + 1
#loop through each key and value in dictionary tuples
for key, value in letter_dict.items():
#if the value is the max value in the dicttionary values
if value is max(letter_dict.values()):
#append the key to the top chars list
top_chars_list.append(key)
#sort top chars list
top_chars_list.sort()
return top_chars_list
#####################################################################
# You can ignore everything below this.
def sort_pairs(l):
# Print sorted list of pairs where the pairs are sorted. This is
# used only for documentation tests. You can ignore it.
return sorted(sorted(pair) for pair in l)
if __name__ == "__main__":
print
import doctest
if doctest.testmod().failed == 0:
print "*** ALL TESTS PASSED ***"
print
|
8c196d966789f4081db21fd70bc0a799499e251e | adyadyat/pyprojects | /hw/day1/day1_hw1.py | 363 | 3.953125 | 4 | for i in range(1, 21):
if i % 10 == 0:
print(i, end='')
print("#", end='')
else:
if i % 5 == 0:
print("#", end='')
print(i, end='')
else:
if i % 3 == 0:
print(i, end='')
print("*", end='')
else:
if i % 2 == 0:
print(i, end='')
print("+", end='')
if i % 2 == 1:
print(i, end='')
print("-", end='')
print() |
d263a7cb6f1d135b6ab0c387ff4a6c5e51bee1b1 | nancyrs22/python-class | /clase3.py | 676 | 3.953125 | 4 | def main():
edad = int(input("que edad tiene: "))
#IF - ELSE
if(edad > 18):
print("mayor de edad")
else:
print("menor de edad")
if(edad > 18):
if(edad < 60):
print("puede hacer servicio militar")
else:
print("es demasiado viejo para el servicio militar")
else:
print("es demasiado joven para el servicio militar")
#ELIF
pais = input("de que pais eres: ")
if(pais =="mex"):
print("es mexicano")
elif(pais =="per"):
print("es peruano")
elif(pais == "arg"):
print("eres argentino")
else:
print("eres de un pais desconocido")
main()
|
86ca33bcf9b925d9fc44f3fab6d2792180242ac1 | reisdima/redes_socket | /tcp/client.py | 1,080 | 3.578125 | 4 | import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 3030
BUFFER_SIZE = 1024
print("==================================================")
print('Propriedades do servidor:')
print('Porta do servidor: {}'.format(TCP_PORT))
print('Ip do servidor: {}'.format(TCP_IP))
print('Tamanho do buffer (número de bytes): {}'.format(BUFFER_SIZE))
print("==================================================")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((TCP_IP, TCP_PORT))
except:
print("Não foi possível se conectar com o servidor.")
exit()
while True:
try:
print("==================================================")
print("Digite uma mensagem...")
mensagem = input().encode()
if mensagem == b'exit()':
s.close()
break
s.send(mensagem)
print("Aguardando mensagem do servidor...")
data = s.recv(BUFFER_SIZE)
print ("Mensagem recebida do servidor: ", data.decode())
except:
print("Conexao interrompida com o servidor")
s.close()
break
|
da5459de9ac7c4756bb34e8b07da855a25cd798d | thakur-nishant/Coding-Challenges | /MatrixRoatation.py | 379 | 3.6875 | 4 | def matrixRotation(A):
if not A:
return A
if not A[0]:
return A
row = len(A)
col = len(A[0])
result = [[0 for i in range(row)] for j in range(col)]
for i in range(col):
for j in range(row):
result[i][row -j -1] = A[j][i]
return result
A = [[1,2,3],
[4,5,6],
[7,8,9]
]
x = matrixRotation(A)
print(x)
|
1c14edbb0b0c0f3f3e4678460916283b8b53334e | rossi2018/DataCamp_Exercises | /08Loops/exercise1.py | 118 | 3.765625 | 4 | #Can you tell how many printout the following while loop will do?
x=1
while x<4:
print(x)
x=x+1
#Its 3 times |
c105905de4cef0e9f52455e43e4aadd8f9462a71 | MomusChao/Python | /75Set.issubset().py | 435 | 3.96875 | 4 | #75 Set.issubset()
# if set is a subset of set2? Return Bool
#set.issubset(set2)
cities01 = {'Taipei', 'Tokyo','New York'}
print(cities01,'\n',sep="")
cities02 = {'Hanoi'}
print(cities02,'\n',sep="")
Ans01 = cities02.issubset(cities01)
print(Ans01,'\n',sep="")
print("====================")
print(cities01,'\n',sep="")
cities03 = {'Taipei'}
print(cities03,'\n',sep="")
Ans02 = cities03.issubset(cities01)
print(Ans02,'\n',sep="")
|
9c1e5a0fecf163f22855ca414c303b813257f10c | Ardhra123/Python-Programming | /number of words.py | 175 | 4.0625 | 4 | fname = input("Enter the element: ")
num_words = 0
for line in f:
words = line.split()
num_words += len(words)
print("Number of words:")
print(num_words)
|
c1edc883b1819a26c14309d8e2aa9cd58b346844 | iszhangli/Learning | /FluentPython/14_可迭代的对象,迭代器和生成器/01_迭代.py | 1,824 | 3.921875 | 4 | # !/usr/bin/env python
# -*- coding:utf-8 -*-
# name: 01_迭代
# author: li zhang
# date: 2019/11/25
# 迭代器模式: 按需一次获取一个数据项
# 加入了yield关键字,这个关键字用于构建生成器
# 迭代器用于从集合中取出元素,生成器生成不存在的数据
# 在python中,所有的集合都可以迭代
import re
import reprlib
RE_WORD = re.compile('\w+') # w匹配非特殊字符,+ 匹配一次或者多次
print(RE_WORD)
class Sentence(object):
def __init__(self, text):
self.text = text
self.words = RE_WORD.findall(text)
print('words:', self.words)
def __getitem__(self, item):
return self.words[item]
def __len__(self):
return len(self.words)
def __repr__(self): # 转换成供解释器可以解释的格式
return 'Sentence(%s)' % reprlib.repr(self.text)
s = Sentence('The time has come, the Walrus said')
print(s)
for word in s:
print(word)
print(s[0])
# 解释器可以迭代的原因是iter函数,
# 1. 检查对象是否实现了iter方法,如果实现了就调用它,获取一个迭代器
# 2. 如果没有实现iter, 但是实现了getitem方法,python会创建一个迭代器
# 任何python序列可迭代的原因是实现了 getitem方法
# 可迭代的对象和迭代器的对比
# python从可迭代的对象中获取迭代器
s = 'ABC'
it = iter(s)
# while True:
# print(next(it))
# python 内部会处理for循环和其他迭代上下文中的stop iteration
s3 = Sentence('Pig and Peper')
it = iter(s3)
for i in it:
print(i)
print(it)
# Iterator.__iter__ 方法的实现方式是
# 返回实例本身, 所以传入迭代器无法还原已经耗尽的迭代器
print('next', next(it))
print(list(it)) # next一次后,it迭代器中少了被迭代的部分 |
e9609f52bb57028e1f7d34677c5b7ff68f72afa5 | 1264799190/1803 | /14day/4.计算机.py | 265 | 3.78125 | 4 | def jisuanji(i,w,q):
if q == '+':
print(i+w)
elif q == '-':
print(i-w)
elif q == '*':
print(i*w)
elif q == '/':
print(i/w)
i = float(input('请输入一个数字'))
w = float(input('请输入一个数字'))
q = input('请输入+—×/')
jisuanji(i,w,q)
|
fe4049b3418974eafa727557bd1880b921018d22 | papibenjie/tuto-python-fr | /tp/recode-liste.py | 662 | 3.90625 | 4 | # Ces fonctions simples doivent etre recoder
# fonctions sur les listes
# Les fonction suivantes sont deja disponible dans python ! (max, min, sum)
# Il faut recoder les fonctions
def maxi(liste):
# cette fonction retourne le nombre maximum de la liste
return 0
def mini(liste):
# cette fonction retourne le nombre minimum de la liste
return 0
def total(liste):
# cette fonction retourne le total de la liste
return 0
if __name__ == '__main__':
l = [1, 4, 6, 3, 2, 4]
print("max: {0} = {1}".format(maxi(l), max(l)))
print("min: {0} = {1}".format(mini(l), min(l)))
print("tot: {0} = {1}".format(total(l), sum(l)))
|
1021573b29f9dd4ab93e2fe50432ad72f764e39d | pedr0diniz/cevpython | /PythonExercícios/ex065 - Maior e Menor valores.py | 1,145 | 4.03125 | 4 | # DESAFIO 065 - Crie um programa que leia VÁRIOS NÚMEROS inteiros pelo teclado. No final da execução, mostre a MÉDIA
#ENTRE TODOS os valores e qual foi o MAIOR e o MENOR valores lidos. O programa deve perguntar ao usuário se ele quer
#ou não CONTINUAR a digitar valores.
from math import inf
n = soma = cont = maior = 0
menor = inf
controle = 'S'
controle2 = ' '
while controle == 'S':
n = float(input('Digite um número: '))
soma += n
cont += 1
if n > maior:
maior = n
if n < menor:
menor = n
controle = str(input('Deseja somar mais números? [S/N] ')).strip().upper()[0]
controle2 = controle #atualizo o controle2 para ele validar a condição abaixo sem estar preso ao valor da última iteração
while controle not in 'SsNn' and controle2 not in 'SsNn':
controle2 = str(input('Opção inválida! Digite S para SIM ou N para NÃO: ')).strip().upper()[0]
controle = controle2 #atualizo o controle para ele retomar o loop
print('Você digitou {} números e a média entre eles é igual a {}!'.format(cont, soma/cont))
print('O menor e o maior número são, respectivamente, {} e {}.'.format(menor, maior)) |
e63ff59047f9d80cabe1a6375c2b8b5c436313b5 | Craig-Sperlazza/pandas | /4_aggregate_stats.py | 1,064 | 4.03125 | 4 | import pandas as pd
df = pd.read_csv('modified_pokemon.csv')
# for index, value in df.iterrows():
# print(index, value)
#print(df.head(10))
#print(df.tail(10))
# Example: Average of all the pokemon stats for a certain type, grouped by type
print(df.groupby(['Type 1']).mean())
#Example 2: Do the same thing but sort by highest defense
print(df.groupby(['Type 1']).mean().sort_values('Defense', ascending=False))
#Example 2: Do the same thing but sort by highest attack
print(df.groupby(['Type 1']).mean().sort_values('Attack', ascending=False))
# .mean(), .sum(), .count() are the most common aggregate statistics----sum makes no sense here just an fyi
print(df.groupby(['Type 1']).sum().sort_values('Attack', ascending=False))
#.count()
#print(df.groupby(['Type 1']).count())
#The above looks sloppy. But you can add a count column and then total it and then bring back only the count column grouped by Type
#You can also use subtypes to group them further
df['Count'] = 1
df_sort = df.groupby(['Type 1', 'Type 2']).count()['Count']
print(df_sort)
|
b1b2a5652d5673d705a1fe1755fd67a2906c667b | momandine/Hidden-Markov-Models | /emission_probs.py | 6,665 | 3.75 | 4 | """Class that stores the number of counts for each word, and for each
unigram, bigram and trigram tag pattern. It also calculates and stores
the emission probability of a word given a tag."""
from collections import defaultdict
class EmissionProbEmitter(object):
def __init__(self, source_file=None):
#Check for source file name
if source_file is None:
self.srcname = self.get_sourcename()
else:
self.srcname = source_file
#Dictionaries
self.word_emm_probs = defaultdict(dict)
self.word_counts = defaultdict(dict)
self.unigram_counts = defaultdict(int)
self.bigram_counts = defaultdict(int)
self.trigram_counts = defaultdict(int)
def get_sourcename(self):
""" FUNCTION: get_sourcename
ARGUMETNS: self
Gets user input for the filename of the source file (should
be of the same form as gene.counts). Checks for valid file and
if invalid prompts again"""
valid_file = False
while not valid_file:
print "Please supply a valid filename for the source file."
file_name = raw_input('> ')
try:
valid_file = file(file_name)
except IOError:
pass
return file_name
def get_counts_from_file(self):
""""FUNCTION: get_coutns_from_file
ARGUMETNS: self
Generates the dictionaries word_counts, unigram_counts bigram_counts
and trigram_counts, if not already generated. Calls get_sourcename if
necessary"""
if self.word_counts:
print "Already counted"
else:
with open(self.srcname) as src:
#Step through file and identify record type
for line in src:
parts = line.split()
#Count for a single word-tag combo
if parts[1] == 'WORDTAG':
count, _, tagtype, name = parts
#Check to see if word has already been recorded
self.word_counts[name][tagtype] = count
#Unigram, bigram, or trigram count
else:
count = parts[0]
seqtype = parts[1]
parts[-1] = parts[-1]
args = tuple(parts[2:]) #Make list into tuple so it can be hashed
#Add to relevent dict. The key is a tuple with all tag types
#in sequence
if seqtype == '1-GRAM':
self.unigram_counts[args] = count
elif seqtype == '2-GRAM':
self.bigram_counts[args] = count
else:
self.trigram_counts[args] = count
def calculate_word_probs(self):
""" FUCNTION: calculate_word_prob
ARGUMETNGS: self
Generates the dictionary of signle word probabilities. """
#Check that file has been analyzed
if not self.word_counts:
self.get_counts_from_file()
#Check for previous execution
if self.word_emm_probs:
print "Probabilities already computed"
else:
for word in self.word_counts:
for tag in self.word_counts[word]:
count = self.word_counts[word][tag]
totalcount = self.unigram_counts[(tag,)]
prob = float(count)/float(totalcount)
self.word_emm_probs[word][tag] = prob
def emission_prob(self, word, tag):
""" FUNCTION: emission_prob
ARGUMETNS: self
word - word ot look up emission probability of
tagtype - tag to be analyzes"""
return self.word_emm_probs[word].get(tag, 0)
def best_tag(self, word):
""" FUNCTION: best_tag
ARGUMENTS: self
word - word to find the best unigram tag for
Given word and no other info, find the most probable tag"""
tagdict = self.word_emm_probs.get(word, self.word_counts['_RARE_'])
return max(tagdict.keys(), key=lambda x: tagdict[x])
def basic_tagger(self, devfile, destfile):
""" FUNCTION: basic_tagger
ARGUMENTS: self
defile - the file to be tagged
destfile - the file to write tagged version to
Writes to destfile with defile and tag determined by best_tag"""
with open(devfile) as dev:
with open(destfile, 'w') as dest:
#Step through each line
for line in dev:
word = line.strip() #Strip newline
if word == '': #Case of blank like
dest.write('\n')
else:
dest.write(word + ' ' + self.best_tag(word) + '\n')
def third_tag_prob(self, tag1, tag2, tag3):
if not self.word_counts:
self.get_counts_from_file()
bi_count = self.bigram_counts[(tag1, tag2)]
tri_count = self.trigram_counts[(tag1, tag2, tag3)]
if tri_count == 0:
return None
return float(tri_count)/float(bi_count)
def viterbi_tagger(self, devfile, destfile):
#Note to self; better to put io stuff in separate function
#Also probably shouldn't have the tagging algroithms in the class.
with open(devfile) as dev:
with open(destfile, 'w') as dest:
mem = ('*', '*')
for line in dev:
word = line.strip()
if word == '':
mem = ('*', '*')
dest.write('\n')
else:
if word in self.word_counts:
word_eff = word
else:
word_eff = '_RARE_'
possible_tags = self.word_counts[word_eff].keys()
#max with function version
maxtag = max(possible_tags, key= lambda tag: \
self.third_tag_prob(mem[0], mem[1], tag) * \
self.emission_prob(word_eff, tag))
dest.write(word + ' ' + maxtag + '\n')
mem = (mem[1], maxtag)
|
38f922afabf52f5b5053f176c4fbe15eeb7a8e3a | cdamiansiesquen/Trabajo05Damian.Carrillo. | /Boleta 10.py | 738 | 3.734375 | 4 | # Boleta 10
#INPUT
cliente=input("nombre del cliente")
precio_de_piano=int(input("ingrese el precio de piano"))
precio_de_saxofon=int(input("ingrese el precio de saxofon"))
precio_de_bateria=int(input("ingrese el precio de bateria"))
# Processing
total=(precio_de_piano+precio_de_saxofon+precio_de_bateria)
#OUPUT
print("#####################################")
print("# VENTA DE INTRUMENTOS - MANUELITO ")
print("#####################################")
print("#")
print("cliente:",cliente)
print("precio de piano es s/.:",precio_de_piano)
print("precio de saxofon es s/.:",precio_de_saxofon)
print("precio de bateria es s/.:",precio_de_bateria)
print("precio total: s/. ", total)
print("#####################################")
|
b6bd2f31a247ae2ae89bc7929164046900b85903 | NKcell/leetcode | /229. Majority Element II
/_229.py | 720 | 3.625 | 4 | class Solution:
def majorityElement(self, nums):
if not nums:
return nums
nums.sort()
res = list()
i = 0
l = len(nums)//3
while i<=(2*l+1):
if len(nums)<=i+l:
break
if nums[i] == nums[i+l]:
res.append(nums[i])
i = i+l+1
else:
i+=1
return list(set(res))
def majorityElement1(self, nums):
import collections
ctr = collections.Counter()
for n in nums:
ctr[n] += 1
if len(ctr) == 3:
ctr -= collections.Counter(set(ctr))
return [n for n in ctr if nums.count(n) > len(nums)/3] |
849f98c85d8daebd0ec853429a943603d386be9c | koneil612/Python-Exercises | /Python301Function.py | 1,437 | 3.890625 | 4 | ###### Hello function
# name=raw_input("what is your name? ")
#
# def hello(name):
# return "Hello " + name
#
# hello(name)
##### y = x+1 function
# import matplotlib.pyplot as plot
#
# def f(x):
# return x + 1
# xs = range(-3, 4)
# ys = []
# for x in xs:
# ys.append(f(x))
#
# plot.plot(xs,ys)
# plot.show()
#####Square of x
# import matplotlib.pyplot as plot
# def f(x):
# return x ** 2
# xs = range(-100, 100)
# ys = []
# for x in xs:
# ys.append(f(x))
#
# plot.plot(xs,ys)
# plot.show()
# ######## ODD OR EVEN
# import matplotlib.pyplot as plot
# def f(x):
# if x % 2 == 0:
# return 1
# else:
# return -1
# xs = range(-5, 5)
# ys = []
# for x in xs:
# ys.append(f(x))
#
# plot.bar(xs, ys)
# plot.show()
# ######## SIN
# import matplotlib.pyplot as plot
# import math
#
# def f(x):
# return math.sin(x)
#
# xs = range(-5, 5)
# ys = []
# for x in xs:
# ys.append(f(x))
#
# plot.plot(xs, ys)
# plot.show()
# ######## SIN part 2 (cleaning it up)
# import matplotlib.pyplot as plot
# import math
# from numpy import arange
#
# def f(x):
# return math.sin(x)
#
# xs = arange(-5, 6, 0.1)
# ys = []
# for x in xs:
# ys.append(f(x))
#
# plot.plot(xs, ys)
# plot.show()
# ####Degree Conversion
import matplotlib.pyplot as plot
def f(x):
return Fah == (Cel * 1.8) + 32.
xs = range(-5, 5)
ys = []
for x in xs:
ys.append(f(x))
plot.plot(xs, ys)
plot.show()
|
75b8522d58823548591472884d8e6abde74c4892 | henrikemx/PycharmProjects | /exercicios-cursoemvideo-python3-mundo1/Exercícios/Ex035_Guanabara.py | 580 | 4.21875 | 4 | # Enunciado: desenvolva um programa que leia o comprimento de 3 retas e diga ao usuário se elas podem, ou não, formar um triangulo
# Solução apresentada pelo Guanabara..
print("-="*20)
print("Analizador de Triangulos")
print("-="*20)
r1 = float(input('\nInforme o comprimento da reta 1: '))
r2 = float(input('Informe o comprimento da reta 2: '))
r3 = float(input('Informe o comprimento da reta 3: '))
if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2:
print('\nOs segmentos podem gerar um triangulo.')
else:
print('\nOs segmentos não podem formar um triangulo.')
|
c7c6daf981f34f095a11f72e27da3c94b179651d | jabbalaci/Bash-Utils | /add_new_desktop_icon.py | 1,369 | 4.25 | 4 | #!/usr/bin/env python3
"""
A simple script that helps you create a desktop icon under Ubuntu.
Usage:
------
* put it into the folder ~/Desktop , enter ~/Desktop and launch it
* answer the questions and it'll create a launcher
* a launcher icon will appear on the Desktop
Author: Laszlo Szathmary (jabba.laci@gmail.com), 2022
"""
import os
import readline
TEMPLATE = """
[Desktop Entry]
Version=1.0
Type=Application
Terminal=false
Icon[en_US]={icon}
Exec={exe}
Name[en_US]={name}
Comment[en_US]={name}
Name={name}
Comment={name}
Icon={icon}
""".strip()
def main():
print(TEMPLATE)
print()
icon = "..."
inp = input("Icon's path (press ENTER to skip): ").strip()
if inp:
icon = inp
#
exe = input("Exe's path: ").strip()
if ' ' in exe:
exe = f'"{exe}"'
name = input("Short name that'll appear under the desktop icon: ").strip()
print()
result = TEMPLATE.format(icon=icon, exe=exe, name=name)
fname = f"{name}.desktop"
if os.path.isfile(fname):
print(f"# {fname} already exists")
print()
print(result)
else:
with open(fname, "w") as to:
to.write(result)
os.system(f'chmod u+x "{fname}"')
#
print(f"# {fname} was created")
#
##############################################################################
if __name__ == "__main__":
main()
|
bceb1ab9f08a4738ef9934d3fd20a04f7feb2407 | 3nippo/system_of_equations_solving_methods | /tests/test_matrix.py | 597 | 3.640625 | 4 | import context
from matrix import Matrix
m1 = [ 4, 2, 3, 2,
0, 8, 7, 6,
13, 15, 11, 15]
m2 = [8, 1, 1,
5, 3, 4,
7, 2, 7,
3, 4, 8]
res = [ 69, 24, 49,
107, 62, 129,
301, 140, 270]
A = Matrix(3, 4, elems=m1)
B = Matrix(4, 3, elems=m2)
Res = Matrix(3, elems=res)
print(A)
print()
print(A[0])
print()
print(A[0][0])
print()
print(B)
print()
print(A * B)
print()
print(Res)
print()
print(A + B.transpose())
print()
print(Matrix(0))
print()
print(Matrix(0).shape())
print()
Res[0] = [1, 1] # should throw an exception as wrong row is assigned
|
16dd4eb3be11a7d5c81727f365169706778530f4 | Prathmesh-Salunkhe/PracticeProgramming | /Dynamic_programming/dp_countsubsetdiff.py | 551 | 3.515625 | 4 | def countSubsetDifference(arr,total,diff,n,sum1 = 0):
if diff == total - 2*sum1:
return 1
if n <= 0 :
return 0
count = 0
count += countSubsetDifference(arr,total,diff,n-1,sum1 + arr[n]) + countSubsetDifference(arr,total,diff,n-1,sum1)
return count
if __name__ == '__main__':
n = int(input())
arr = []
for i in range(n):
value = int(input())
arr.append(value)
diff = int(input())
total =sum(arr)
print(countSubsetDifference(arr,total,diff, len(arr) - 1)) |
e2a1c08ab8f04a9c3b646b96851af5a051c62e4d | nsimsofmordor/PythonProjects | /Projects/AutomateTheBoringStuff/Part_2/PatternMatching/isPhoneNumber.py | 1,317 | 4.25 | 4 | # isPhoneNumber.py
# Say you want to find a phone number in a string
# You know the pattern is: ###-###-####
def isPhoneNuber(text):
if len(text) != 12: # is it 12 chars?
return False
for i in range(0, 3): # are the first 3 chars nums?
if not text[i].isdecimal():
return False
if text[3] != '-': # is there a hyphen on the 4th char
return False
for i in range(4, 7): # are the 3 chars after the hyphen a num?
if not text[i].isdecimal():
return False
if text[7] != '-': # is there a hyphen preceding them?
return False
for i in range(8, 12): # are the last 4 digits a number?
if not text[i].isdecimal():
return False
return True
# Testing a valid number with an invalid one
# cell = '203-535-4864'
# print(f'{cell} is a phone number:')
# print(isPhoneNuber(cell))
# print('Moshi Moshi is a phone number: ')
# print(isPhoneNuber('Moshi Moshi'))
# Use case:
message = 'Call my cell at 415-555-1011 tomorrow, if not try my work number at 313-978-8837'
for i in range(len(message)):
chunk = message[i:i+12] # take possible chunks of 12 chars - {[0-12], [1-13], [2-14] ...}
if isPhoneNuber(chunk): # if chunk contains a valid number, print
print(f'Phone number found: {chunk}')
print("Done")
|
bdcb699117259dd1e4e725dad03ba85c5fdb55e2 | Tirklee/python3-demo | /T2_11 Python 交换变量 2.py | 275 | 3.53125 | 4 | # -*- coding: UTF-8 -*-
# Filename : test.py
# author by : www.runoob.com
# 用户输入
x = input('输入 x 值: ')
y = input('输入 y 值: ')
# 不使用临时变量
x, y = y, x
print('交换后 x 的值为: {}'.format(x))
print('交换后 y 的值为: {}'.format(y)) |
bd7e7ea2d52530fb032f7e4fac2991d15e5cbbba | willgoshen/CTCI-with-Python | /1-2-permutations.py | 275 | 3.984375 | 4 | def permutations(s1, s2):
sorted_s1 = sorted(s1)
sorted_s2 = sorted(s2)
if sorted_s1 == sorted_s2:
return "'{}' is a permutation of '{}'".format(s1, s2)
return "'{}' is not a permutation of '{}'".format(s1, s2)
print(permutations("this", "histy")) |
31fb5eaa4d699d356110498cbdbec6aed0057da9 | ballib/Forritun1 | /assignment 6 (strings)/dæmi6.py | 176 | 3.8125 | 4 | a_str = input("Enter last name, first name: ")
name = a_str.split(","+" ")
fname = name[1]
fletter = fname[0]
lname = name[0]
print(fletter.capitalize()+'.',lname.capitalize()) |
ede6cc2bfd094dbd682386abfff24e346515a878 | UlvacMoscow/InitialTasks | /bubble_sort.py | 477 | 3.984375 | 4 | before_sort_list = [78, 45, 55, 11, -5, 9]
def bubble_sort(my_list):
last_item = len(my_list) - 1
for z in range(0, last_item):
for x in range(0, last_item - z):
print(my_list)
if my_list[x] > my_list[x + 1]:
my_list[x], my_list[x + 1] = my_list[x + 1], my_list[x]
return my_list
print('before sort list', before_sort_list)
after_sort_list = bubble_sort(before_sort_list)
print('after sort list', after_sort_list) |
b195259246424078508425061224a3d2283a4ae5 | OldTruckDriver/Chexer | /ChexerBattle/Chexers-master/random_player/utils.py | 1,705 | 3.640625 | 4 | # The minimum and maximum coordinates on the q and r axes
MIN_COORDINATE = -3
MAX_COORDINATE = 3
# Delta values which give the corresponding cells by adding them to the current
# cell
MOVE_DELTA = [(0, 1), (1, 0), (-1, 1), (0, -1), (-1, 0), (1, -1)]
JUMP_DELTA = [(delta_q * 2, delta_r * 2) for delta_q, delta_r in MOVE_DELTA]
def all_cells():
"""
generate the coordinates of all cells on the board.
"""
ran = range(MIN_COORDINATE, MAX_COORDINATE + 1)
return [(q, r) for q in ran for r in ran if -q-r in ran]
ALL_CELLS = all_cells()
def generate_cells(cell, delta_pairs):
"""
generate a list of cells by adding delta values
"""
return [(cell[0] + delta_q, cell[1] + delta_r)
for delta_q, delta_r in delta_pairs]
def moveable_cells(curr_cell, occupied):
"""
moveable_cells are cells next to the current_cell with nothing occupied
"""
neighbours = generate_cells(curr_cell, MOVE_DELTA)
return [cell for cell in neighbours
if cell in ALL_CELLS and cell not in occupied]
def jumpable_cells(curr_cell, occupied):
"""
jumpable_cells are cells that are one cell apart from the current cell
and cells in the middle must be occupied by either a block or a piece
"""
generated_cells = generate_cells(curr_cell, JUMP_DELTA)
jumpable = []
for cell in generated_cells:
if cell in ALL_CELLS and cell not in occupied:
middle_cell = tuple(map(lambda x, y: (x + y) // 2, curr_cell, cell))
if middle_cell in ALL_CELLS and middle_cell in occupied:
jumpable.append(cell)
return jumpable |
d62d8f3817abf2e777256f57d7ede66d8852056e | LeakyBucket/LPTHW | /ex11/ex11.3.py | 238 | 3.5 | 4 | color = raw_input('What is your color? ')
home = raw_input('Where do you live? ')
job = raw_input('What do you do? ')
name = raw_input('What is your name? ')
print "Hello %s, the %s from %s who really likes %s" % (name, job, home, color) |
b03ee6a6e6e96cf91d0a0bea6638759db6cf9b57 | Beelzenef/pyMemories | /tomarNum.py | 516 | 3.984375 | 4 | #!/usr/bin/env python
def obtenerNumValido(minimo, maximo):
valido = False;
numero = 0;
while not valido:
try:
numero = input("¡Dame un número! ");
if int(numero) in range(minimo, maximo):
valido = True;
else:
print("Tu numero no está en el rango permitido...");
except:
print("Dato no válido, intentalo otra vez...");
print("Tu numero es válido, ¡procede!");
return numero;
|
50ee1b4779fe424424124767a0ba175064abaf68 | blackbat13/matura_inf | /cwiczenia/rekurencja/fibbonaci.py | 418 | 3.828125 | 4 | def fib_rek(n):
if n <= 2:
return 1
if n > 2:
return fib_rek(n - 1) + fib_rek(n - 2)
def fib_iter(n):
i = 3
tab = [0, 1, 1]
while i <= n:
tab.append(tab[i-1] + tab[i-2])
i += 1
return tab[n]
number = int(input("Podaj liczbę: "))
result = fib_rek(number)
print("Wynik rekurencyjny:", result)
result2 = fib_iter(number)
print("Wynik iteracyjny:", result2)
|
9cfb4f453135d8b72b58cb1453c1fbb3191eb1cd | hippke/Projekt-Euler | /142.py | 947 | 3.5625 | 4 | from math import sqrt
import math
def isp(i):
if i < 0:
return False
else:
root = math.sqrt(i)
if int(root + 0.5) ** 2 == i:
return True
else:
return False
# Create list of perfect squares
squarelist = []
for i in range(1000):
squarelist.append(i ** 2)
#print squarelist
#Find the smallest x + y + z with integers x > y > z > 0 such that x + y, x - y, x + z, x - z, y + z, y - z are all perfect squares.
# Find x, y for x+y and x-y as perfect squares
for x in range(5000):
print x
for y in range(x):
if x > y and isp(x + y) and isp(x - y):
for z in range(y):
if x > y > z > 0 and isp(x + z) and isp(x - z) and isp(y + z) and isp(y - z):
print x, y, z
print x + y, x - y, x + z, x - z, y + z, y - z
break
# x + y
# x + z
# x - y
# x - z
# y + z
# y - z
|
d42a9515647bda4064fbfbebf004c3d43b211b5e | adichamoli/LeetCodeProblems | /005 - All Elements in Two Binary Search Trees/Solution2.py | 993 | 3.8125 | 4 | '''48 / 48 test cases passed. Status: Accepted
Runtime: 308 ms Memory Usage: 17.6 MB'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def treeToList(self, root: TreeNode) -> List[int]:
stack = []
lis = []
current = root
while stack or current:
if current:
stack.append(current)
current = current.left
else:
current = stack.pop()
lis.append(current.val)
current = current.right
return lis
def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:
list1 = self.treeToList(root1)
list2 = self.treeToList(root2)
list3 = list1+list2
return(sorted(list3))
|
0d9688f0f2e7d9dbf3e8015aac5a1bbda8a57f28 | stroodle96/DSpython | /FunctionsS.py | 6,605 | 4.5625 | 5 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 5 17:19:33 2018
@author: John Stewart
FUNCTIONS
"""
#%%
# This program demonstrates a function.
# First, we define a function named message.
def message():
print('I am Arthur')
print('King of the Britons')
# Call the message function.
message()
#%%
# This program has two functions. First we
# define the main function.
def main():
print('I have a message for you.')
message()
print('Goodbye!')
# Next we define the message function.
def message():
print('I am Arthur')
print('King of the Britons.')
# Call the main function.
main()
#%%
"""
This will cause an error! WHY?
"""
# Definition of the main function.
def main():
get_name()
print('Hello', name) # This causes an error!
# Definition of the get_name function.
def get_name():
name = input('Enter your name: ')
# Call the main function.
main()
#%%
# This program demonstrates an argument being
# passed to a function.
def main():
value = 5
show_double(value)
# The show_double function accepts an argument
# and displays double its value.
def show_double(number):
result = number * 2
print(result)
# Call the main function.
main()
#%%
# This program demonstrates a function that accepts
# two arguments.
def main():
print('The sum of 12 and 45 is')
show_sum(12, 45)
# The show_sum function accepts two arguments
# and displays their sum.
def show_sum(num1, num2):
result = num1 + num2
print(result)
# Call the main function.
main()
#%%
"""
Python can use keyword arguments. When a function argument is passed to a function, within the
function it is passed to, it is called a parameter. In addition to matching function arguments
and parameters, python allows for writing an argument in this format:
parameter_name=value
An argument written with this syntax is known as a kwyword argument.
"""
# This program demonstrates keyword arguments.
def main():
# Show the amount of simple interest using 0.01 as
# interest rate per period, 10 as the number of periods,
# and $10,000 as the principal.
show_interest(rate=0.01, periods=10, principal=10000.0)
# The show_interest function displays the amount of
# simple interest for a given principal, interest rate
# per period, and number of periods.
def show_interest(principal, rate, periods):
interest = principal * rate * periods
print('The simple interest will be $', \
format(interest, ',.2f'), \
sep='')
# Call the main function.
main()
#%%
# This program demonstrates passes two strings as
# keyword arguments to a function.
def main():
first_name = input('Enter your first name: ')
last_name = input('Enter your last name: ')
print('Your name reversed is')
reverse_name(last=last_name, first=first_name)
def reverse_name(first, last):
print(last, first)
# Call the main function.
main()
#%%
# This program demonstrates passing two string
# arguments to a function.
def main():
first_name = input('Enter your first name: ')
last_name = input('Enter your last name: ')
print('Your name reversed is')
reverse_name(first_name, last_name)
def reverse_name(first, last):
print(last, first)
# Call the main function.
main()
#%%
# This program demonstrates what happens when you
# change the value of a parameter.
def main():
value = 99
print('The value is', value)
change_me(value)
print('Back in main the value is', value)
def change_me(arg):
print('I am changing the value.')
arg = 0
print('Now the value is', arg)
# Call the main function.
main()
#%%
# This program demonstrates keyword arguments.
def main():
# Show the amount of simple interest using 0.01 as
# interest rate per period, 10 as the number of periods,
# and $10,000 as the principal.
show_interest(rate=0.01, periods=10, principal=10000.0)
# The show_interest function displays the amount of
# simple interest for a given principal, interest rate
# per period, and number of periods.
def show_interest(principal, rate, periods):
interest = principal * rate * periods
print('The simple interest will be $', \
format(interest, ',.2f'), \
sep='')
# Call the main function.
main()
#%%
# This program demonstrates passes two strings as
# keyword arguments to a function.
def main():
first_name = input('Enter your first name: ')
last_name = input('Enter your last name: ')
print('Your name reversed is')
reverse_name(last=last_name, first=first_name)
def reverse_name(first, last):
print(last, first)
# Call the main function.
main()
#%%
# Create a global variable.
my_value = 10
# The show_value function prints
# the value of the global variable.
def show_value():
print(my_value)
# Call the show_value function.
show_value()
#%%
# Create a global variable.
number = 0
def main():
global number
number = int(input('Enter a number: '))
show_number()
def show_number():
print('The number you entered is', number)
# Call the main function.
main()
"""
Comment out the "global number line
"""
#%%
"""
ACTIVITY#1
A company pays a quaterly bonus to its workiers along with retirement benefits
in the form 5% of each employees gross pay. Both go to the employees retirement
plan. Write a progam that calculates the company's contribution to an employee's
retirement account for the year. Use 2 functions and call them.
Get the eimployee's annual gross pay.
Get the total amount of bonuses paid to the employee.
Calculate and display the contribution for gross pay.
Calculate and display the contribution for bonuses.
"""
#%%
def main():
global bonus_pay, bonus_bonus, retirement_pay, total_pay
company_percent = 0.05
grosspay = int(input('What is your annual Gross Pay? '))
bonus = int(input('How much did you get in bonuses? '))
bonus_pay = grosspay * company_percent
bonus_bonus = bonus * company_percent
retirement_pay = bonus_pay + bonus_bonus
total_pay = grosspay + bonus
display()
def display():
print('Your businesses contribution for you retirement account is $', retirement_pay)
print('Your pay before business contributes is $', total_pay)
main()
|
c5c6f6e623e5dba608bede8bc7707e3f98a62e60 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2585/60774/267473.py | 524 | 3.84375 | 4 | start = input()
end = input()
flag = True
if(end == 'RXXLRrXXL'):
print(False)
elif(end == 'XRLXXRXLX'):
print(False)
elif(end == 'RXXLRXXXL'):
print(False)
else:
i = 0
while(i < len(start)):
if(start[i] != end[i]):
if(i == len(start) - 1):
flag = False
elif(start[i:i + 2] == 'RX' or start[i:i + 2] == 'XL'):
i = i + 2
else:
flag = False
break
else:
i = i + 1
print(flag) |
eab91e02e29b1db616bab055fc3cb9e87cb9bf69 | DouglasOrr/Snippets | /pendulum/pendulum.py | 2,728 | 3.921875 | 4 | import math
class Simulation:
"""Runs a simple inverted pendulum simulation."""
def __init__(self, noise):
"""Noise should be callable with the current time, return the torque."""
# constants
self.mom_mass_1 = 0.1
self.mom_mass_2 = 1.0
self.damping = 0.01
self.dt = 1.0 / 1000
self.noise = noise
self.max_controller_torque = 10
self.g = 10.0
# simulation variables
self.t = 0.0
self.theta = 0.0
self.dtheta_dt = 0.0
def step(self, controller):
"""Advance the simulation by a single timestep.
Controller should be callable, and return the torque."""
# calculate
c = controller(self.theta, self.dtheta_dt, self.mom_mass_1, self.mom_mass_2, self.g, self.dt)
controller_torque = min(self.max_controller_torque, max(-self.max_controller_torque, c))
noise_torque = self.noise(self.t)
gravity_torque = self.g * self.mom_mass_1 * math.sin(self.theta)
damping_torque = -self.damping * self.dtheta_dt
d2theta_dt2 = (controller_torque + noise_torque + gravity_torque + damping_torque) / self.mom_mass_2
# update
self.theta += self.dtheta_dt * self.dt / 2
self.dtheta_dt += d2theta_dt2 * self.dt
self.theta += self.dtheta_dt * self.dt / 2
self.theta = (self.theta + math.pi) % (2*math.pi) - math.pi
self.t += self.dt
class ManualControl:
def __init__(self, constant, auto_control):
self.constant = constant
self.auto_control = auto_control
self.control = 0
def __call__(self, theta, dtheta_dt, mom_mass_1, mom_mass_2, g, dt):
return (self.constant * self.control) + self.auto_control(theta, dtheta_dt, mom_mass_1, mom_mass_2, g, dt)
class ProportionalControl:
def __init__(self, constant):
self.constant = constant
def __call__(self, theta, dtheta_dt, mom_mass_1, mom_mass_2, g, dt):
return -self.constant * theta
class SineNoise:
def __init__(self, strength_fn, components):
self.strength_fn = strength_fn
self.frequency_components = [(2 * math.pi / period, amplitude) for (period, amplitude) in components]
def __call__(self, t):
noise = sum([amplitude * math.sin(frequency * t) for (frequency, amplitude) in self.frequency_components])
return self.strength_fn(t) * noise
if __name__ == '__main__':
control = ProportionalControl(10)
simulation = Simulation(SineNoise(
lambda t: 0.5 + t / 20,
[(0.73, 1), (2, 1), (2.9, 0.5), (13, 0.5)])
)
for i in range(0, 20000):
simulation.step(control)
if i % 1000 == 0:
print(simulation.theta)
|
cd681953ee8af063acdf5afd216b4e58e3b65735 | Art83/python_bioinformatics | /subsrt_search.py | 325 | 4 | 4 | '''
Looking for substring in a string with find
'''
def substr_search(genome, substring):
if genome.find(substring) is not -1:
print("Yes")
else:
print("No")
def main():
genome = input()
substring = input()
substr_search(genome, substring)
if __name__ == "__main__":
main()
|
d11d0e5bf25a83fa63cdb1a8e2765495b559a7c5 | UndeadHibari/Yunque_Spiders | /Python基础/List.py | 820 | 4.1875 | 4 | # 有序,0开始
# 列表是最常用的Python数据类型,它可以作为一个方括号内的逗号分隔值出现。
# 列表的数据项不需要具有相同的类型
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
# 访问list元素
print("list1[2]:",list1[2])
print("list2[1:3]:",list2[1:3]) #含左不含右,便于计算长度:3-1=2,下标1开始的2个元素
# 更新列表
list3.append("e")
list3.append("e")
print(list3)
list3.remove('e') #移除指定元素,有重复也只移除一个
del list3[1] #按照索引删除元素
print(list3)
# 操作
print(len(list2)) #长度
print(list1+list2) #组合
print(list1 * 4) #重复
print(2 in list2) #查找元素
for i in list2:
print(i) #迭代 |
5f8060bb0f6d878aac8ee54d9bdd0e192822a702 | csoriano1618/BuildingDestruction | /src/lib/parseparameters.py | 1,106 | 3.71875 | 4 |
def parse_parameters(parameters, default_parameters):
'''
Given a dictionary of default parameters, parse a custom dictionary of
parameters, being a subgroup of all default parameters, add the faulting
parameters with default values to the user custom dictionary of parameters.
i.e.
>>> parameters = {'value_1': 2, 'value_3': 5}
>>> default_parameters = {'value_1': 1, 'value_2': 2, 'value_3': 3, 'value_4': 4}
>>> parsed_parameters = parse_parameters(parameters, default_parameters)
>>> sorted(parsed_parameters.items(), key = lambda parameter: parameter[0])
[('value_1', 2), ('value_2', 2), ('value_3', 5), ('value_4', 4)]
'''
parsed_parameters = {}
for key in default_parameters.keys():
if(key in parameters.keys()):
parsed_parameters[key] = parameters[key]
else:
parsed_parameters[key] = default_parameters[key]
return parsed_parameters
def test():
import doctest
from lib import parseparameters
doctest.testmod(parseparameters, verbose = True)
if __name__ == "__main__":
test() |
94031b93a8301eaa787421b80e529c2f748c1ede | alex-dsouza777/Python-Basics | /Chapter 2 - Variables & Data Types/07_pr_avg.py | 152 | 4.03125 | 4 | #Average of two numbers
a = input("Enter first number:")
b = input("Enter second number:")
a = int(a)
b = int(b)
avg = (a+b)/b
print("Avgerage is:",avg) |
a1c5bbf7dba14fde0c5789ca03f8114e0ce52780 | danny237/Python-Assignment | /Data types/smallest_num.py | 336 | 4.28125 | 4 | #program to find largest number from list
def largest_number(list1):
smallest_num = list1[0]
for i in range(len(list1)-1):
if smallest_num > list1[i+1]:
smallest_num = list1[i+1]
return smallest_num
# list
list1 = [1,2,3,4,10]
# function call
largest_num = largest_number(list1)
print(largest_num) |
3a480a24ad9fa9ea7c2584808165483c7d6e9834 | LyaminVS/2021_Lyamin_infa | /turtle2/ex22.py | 876 | 3.5 | 4 | import turtle
inp = list(input())
turtle.shape('turtle')
turtle.speed(0)
n = 0
f = open('/Users/vasilij/pylabs/pythonProject/nums')
numbers = [line for line in f]
f.close()
turtle.penup()
turtle.goto(-300, 0)
turtle.pendown()
for j in range(len(numbers)):
numbers[j] = numbers[j].split(',')
for k in range(len(numbers[j])):
numbers[j][k] = float(numbers[j][k])
for i in inp:
n = 0
for elem in numbers[int(i)]:
if (elem == -1):
turtle.penup()
n -= 1
elif (elem == -2):
turtle.pendown()
n -= 1
elif (n % 2 == 0):
if (elem == -3):
turtle.forward(2 * 10 * 2 ** (0.5))
else:
turtle.forward(2 * elem)
else:
turtle.right(elem)
n += 1
turtle.penup()
turtle.forward(2 * 20)
turtle.pendown()
|
92e32b68a9632e6eff186b98b6d65201030e98a2 | pauloricardo-ggs/Python | /ClínicaME/Pessoa.py | 868 | 3.59375 | 4 | import Endereco as e
class Pessoa():
def __init__(self):
self.nome = ""
self.rg = ""
self.cpf = ""
self.anoNasc = 0
self.mesNasc = 0
self.sexo = ""
self.endereco = e.endereco()
def cadastrar(self):
self.nome = input("Entre com o nome: ")
self.rg = input("Entre com o RG: ")
self.cpf = input("Entre com o CPF: ")
self.anoNasc = int(input("Entre com o ano de nascimento: "))
self.mesNasc = int(input("Entre com o mês de nascimento: "))
self.sexo = input("Informe o sexo:")
self.endereco.cadastrar_endereco()
def exibir(self):
print(self.nome)
print(self.rg)
print(self.cpf)
print(self.anoNasc)
print(self.mesNasc)
print(self.sexo)
self.endereco.exibir_endereco() |
1b97b98f9927b8794da2c932c6ebd4597ccbd943 | Egorshve/Esercizi-informatica | /es27pag73.py | 345 | 3.6875 | 4 | giorno=1
veicoli=0
segnale=1
while True:
print("Giorno: ",giorno)
veicoli+=int(input("Inserire numero veicoli transitati: "))
segnale=int(input("Se vuoi continuare schiaccia 1,altrimenti 0: "))
giorno+=1
if segnale==0:
giorno-=1
break
print()
print("In",giorno,"giorni sono transitati",veicoli) |
b2d8b7c1960e47005f151b6c916d9d4e4af80a43 | Hewish8/TechnicalAssessment | /Dashboard.py | 2,124 | 3.53125 | 4 | import plotly as py
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import plotly.graph_objs as go
import mysql.connector
from random import seed
from random import random
def plot_map(Year):
#Connect to MySQL
WHRdb = mysql.connector.connect(
host = "localhost",
user = "root",
passwd = "",
database = "World_Happiness_Report")
year = str(Year)
#Get the countries and Scores DATASET
if(year == "2016" or year =="2017"):
query = "SELECT Country, HappinessScore FROM `" + year + "`"
#print(query)
#Execute the query
mycursor = WHRdb.cursor()
mycursor.execute(query)
dataset = mycursor.fetchall()
if(year == "2018" or year =="2019"):
query = "SELECT CountryOrRegion, Score FROM `" + year + "`"
#print(query)
#Execute the query
mycursor = WHRdb.cursor()
mycursor.execute(query)
dataset = mycursor.fetchall()
#Creating lists of the following
Country = []
HappinessScore = []
HappinessStatus = []
count = 0
for r in dataset:
Country.append(r[0]) # r[0] is score
HappinessScore.append(r[1]) #r[1] is score
#Set Happiness Status
if(r[1]>5.6):
Status = 'Green'
elif(r[1]>=2.6 and r[1] <=5.6 ):
Status = "Amber"
elif(r[1] <2.6):
Status = "Red"
HappinessStatus.append(Status)
#print(len(Country))
#print(len(HappinessScore))
#print(len(HappinessStatus))
#Generate randon values for z
# seed random number generator
seed(1)
z=[]
# generate random numbers between 0-1
for _ in range(len(Country)):
value = random()
z.append(value)
#print(len(z))
data = dict(type = 'choropleth',
locations = Country,
locationmode = 'country names',
colorscale = 'Jet',
text = HappinessStatus ,
z = HappinessScore,
colorbar = {'title': 'Score Colorbar'})
title = 'World Happiness Score ' + year
layout = dict(title= title,
geo={'scope': 'world'})
choromap = go.Figure(data = [data], layout = layout)
choromap.show()
if __name__ == "__main__":
for year in range(2016,2020):
plot_map(year)
|
0daf3ab2b027a351f7f1d2dac089014b48d7583e | zhangwei725/PythonBase | /day02/流程控制if.py | 1,095 | 3.828125 | 4 | # name = input('请输入用户名')
# if name == 'admin':
# print('尊敬管理员用户您好!!! 欢迎来到 xxx上线了')
# money = 10
# if money > 0:
# print('有钱真好!!!')
# print('您需要什么样的服务')
# else:
# print('滚!!!没钱还想来吃饭!!!')
# print('程序结束')
# 如果有苹果就买两斤苹果,
# 没有苹果就买一个西瓜
# 如果都没有你就不要回来了
apple = 1
xigua = 0
if apple:
print('xxx 买了两斤苹果,回家了!!!')
elif xigua:
print('xxx 买了一个西瓜!!!')
else:
print('喂 110吗!!! 我犯错了!!!')
1> 第一题
# 如果是管理登录输出能增删改查
# 如果是普通用户输出 能查
# 如果是游客 提示权限不够
# 其他情况 去注册
2 > 输入一个数 如果是偶数则输出
3> 判断分数是否在合理的范围 0 100
4 > 输入一个数 判断是否是7的倍数,如果是则输出这个数 否则输出这个数不是7的倍数
5 输入有个数 根据分数输出成绩的好坏 90分 优秀 80 良好 60 及格 其他情况,请把你家长叫来
|
9dcda3befdfeb1b478687f75fd17783489316a5a | shivamvats/sandbox | /python/closure.py | 280 | 3.703125 | 4 |
def makeClosure(a, b):
d = 1
def closure(c):
"""The nested function must use the variables from the outer scope to \
be turned into a closure."""
print(a + b + c)
return closure
if __name__ == "__main__":
fn = makeClosure(1, 2)
fn(3)
|
e2c1552cb5ed88acd0b5612787f4a03adb3afe90 | NobuyukiInoue/LeetCode | /Problems/0400_0499/0475_Heaters/Project_Python3/Heaters.py | 2,366 | 3.671875 | 4 | # coding: utf-8
import os
import sys
import time
class Solution:
def findRadius(self, houses, heaters):
"""
:type houses: List[int]
:type heaters: List[int]
:rtype: int
"""
houses.sort()
heaters.sort()
radius = 0
i = 0
for house in houses:
while i < len(heaters) and heaters[i] < house:
i += 1
if i == 0:
radius = max(radius, heaters[i] - house)
elif i == len(heaters):
return max(radius, houses[-1] - heaters[-1])
else:
radius = max(radius, min(heaters[i]-house, house-heaters[i-1]))
return radius
def findRadius_work(self, houses, heaters):
"""
:type houses: List[int]
:type heaters: List[int]
:rtype: int
"""
radius_min = [sys.maxsize]*len(houses)
for i in range(len(houses)):
for he in heaters:
radius = abs(he - houses[i])
if radius < radius_min[i]:
radius_min[i] = radius
radius = 0
for temp in radius_min:
if temp > radius:
radius = temp
return radius
def main():
argv = sys.argv
argc = len(argv)
if argc < 2:
print("Usage: python {0} <testdata.txt>".format(argv[0]))
exit(0)
if not os.path.exists(argv[1]):
print("{0} not found...".format(argv[1]))
exit(0)
testDataFile = open(argv[1], "r")
lines = testDataFile.readlines()
for temp in lines:
temp = temp.strip()
if temp == "":
continue
print("args = {0}".format(temp))
loop_main(temp)
# print("Hit Return to continue...")
# input()
def loop_main(temp):
var_str = temp.replace("[[","").replace("]]","").rstrip()
flds = var_str.split("],[")
houses = [int(val) for val in flds[0].split(",")]
heaters = [int(val) for val in flds[1].split(",")]
print("houses = {0}".format(houses))
print("heaters = {0}".format(heaters))
sl = Solution()
time0 = time.time()
result = sl.findRadius(houses, heaters)
time1 = time.time()
print("result = {0}".format(result))
print("Execute time ... : {0:f}[s]\n".format(time1 - time0))
if __name__ == "__main__":
main()
|
fe4d2b5077e45c9e8b045e5e89a06e04e337589c | Alex-GCX/multitask | /coroutine/iterator-base.py | 1,828 | 3.90625 | 4 | from collections.abc import Iterable
import time
class MyList(object):
"""自定义一个可迭代对象"""
def __init__(self):
self.content = list()
def add(self, item):
self.content.append(item)
def __iter__(self):
# 1.要使一个对象是可迭代对象,必须实现__iter__方法
# 2.要使一个对象迭代时能每次都返回一个值,必须让__iter__返回一个迭代器对象
# 创建迭代器对象
myiterator = MyIterator(self)
return myiterator
class MyIterator(object):
"""自定义一个迭代器,必须实现__iter__方法和__next__方法"""
def __init__(self, mylist_obj):
self.mylist = mylist_obj
self.current = 0
def __iter__(self):
pass
def __next__(self):
"""每次迭代时返回的值实际是通过__next__方法返回的"""
# 1.定义一个下标current,每次调用时+1,用来实现每次调用__next__时,返回下一个值
# 2.注意判断下标current自增时是否会越界,若越界则手动抛出StopIteration异常
# 外层for循环迭代时,若遇到StopIteration异常,则会停止迭代
if self.current == len(self.mylist.content):
raise StopIteration
value = self.mylist.content[self.current]
self.current += 1
return value
def main():
my_list = MyList()
my_list.add(11)
my_list.add(22)
my_list.add(33)
print('my_list是不是可迭代对象:', isinstance(my_list, Iterable))
my_list_iterator = iter(my_list)
print('my_list返回的迭代器为:', my_list_iterator)
print('my_list的下一个值为:', next(my_list_iterator))
for i in my_list:
print(i)
time.sleep(1)
if __name__ == '__main__':
main()
|
2fabb03f0f6b0b297245354782e650380509424b | klim1286/PythonBasics | /unit1-1.py | 394 | 3.984375 | 4 | y = 10
x = 'Тишь да гладь'
print(f'Текст:{x}')
print(f'Число:{y}')
a1 = input('Введите первое число: ')
a2 = input('Введите второе число: ')
b1 = input('Введите первую строку: ')
b2 = input('Введите вторую строку: ')
print(f'Вы ввели числа: {a1}/{a2}')
print(f'Вы ввели строки: {b1} / {b2}')
|
e7131752981f6c5ae0a4a7d86e2a57991f73a8f0 | paxosglobal/dsert | /dsert/__init__.py | 4,067 | 3.5 | 4 |
def assert_valid_dict(to_validate, known_contents={}, known_types={}, excluded_fields=[]):
"""
Take a dict to_validate and validate all known known + unknown fields,
while skipping any excluded_fields
Details of inputs:
- known_contents is a dict with the exact key/value pairs expected in to_validate
- known_types is a dict of the exact key combined with the *type* of value that is expected
- excluded fields is a list of the fields who value type is unknown
"""
assert type(to_validate) is dict, to_validate
assert type(known_contents) is dict, known_contents
assert type(known_types) is dict, known_types
assert type(excluded_fields) in (list, set, tuple), excluded_fields
# Be sure we're not missing any fields
to_validate_keys_set = set(to_validate.keys())
known_contents_set = set(known_contents.keys())
unknown_fields_set = set(known_types.keys())
excluded_fields_set = set(excluded_fields)
missing_keys_set = to_validate_keys_set - unknown_fields_set - excluded_fields_set - known_contents_set
if missing_keys_set:
err_msg = 'Keys for {missing_keys_dict} not in '
err_msg += 'known_contents keys ({known_contents}), '
err_msg += 'known_types keys ({known_types}), '
err_msg += 'nor excluded_fields ({excluded_fields}).'
err_msg = err_msg.format(
missing_keys_dict={x: to_validate[x] for x in missing_keys_set},
known_contents=list(known_contents_set),
known_types=list(unknown_fields_set),
excluded_fields=list(excluded_fields_set),
)
raise KeyError(err_msg)
excluded_fields_not_in_original_dict = excluded_fields_set - to_validate_keys_set
if excluded_fields_not_in_original_dict:
err_msg = '{} not in {}'.format(excluded_fields_not_in_original_dict, excluded_fields)
raise KeyError(err_msg)
# Be sure every field we're expecting we get back correctly
for known_field_to_return, known_value_to_return in known_contents.items():
if known_field_to_return not in to_validate:
err_msg = 'Expected field `{known_field_to_return}` (`{known_value_to_return}`)'
err_msg += ' not in dict: {to_validate}'
err_msg = err_msg.format(
known_field_to_return=known_field_to_return,
known_value_to_return=known_value_to_return,
to_validate=to_validate,
)
raise KeyError(err_msg)
if known_value_to_return != to_validate[known_field_to_return]:
err_msg = 'Expected `{known_value_to_return}` as value for key '
err_msg += '`{known_field_to_return}` but got `{supplied_dict_field}`'
err_msg += '\n to_validate: {to_validate}'
err_msg += '\n known_contents: {known_contents}'
err_msg = err_msg.format(
known_value_to_return=known_value_to_return,
known_field_to_return=known_field_to_return,
supplied_dict_field=to_validate[known_field_to_return],
to_validate=to_validate,
known_contents=known_contents,
)
raise ValueError(err_msg)
# Be sure the fields we don't know are of the correct types
for field_to_return, field_type in known_types.items():
# required fields must be a type (TODO: support more general plugins)
if type(field_type) is not type:
raise TypeError('{} is not of type'.format(field_type))
if field_to_return not in to_validate:
err_msg = '{} not in {}'.format(field_to_return, to_validate)
raise KeyError(err_msg)
# Check the type of the field returned
if type(to_validate[field_to_return]) is not field_type:
err_msg = '{} is not {}:\n{} in {}'.format(
type(to_validate[field_to_return]),
field_type,
field_to_return,
to_validate,
)
raise ValueError(err_msg)
|
eb89530dd50252f836d13ae02cc01be52046536b | frankymosutro/bedupython | /clase 03/lista-de-personas.py | 1,234 | 4.0625 | 4 | #/usr/bin/env python
# -*- coding: utf-8 -*-
#Definicion de objetos o clases
class Persona():
"""definicion dle objeto persona"""
def __init__ (self, nombre, a_paterno, edad):
"""constructo de la clase persona"""
self.nombre = nombre
self.a_paterno = a_paterno
self.edad = edad
@property
def edad_real(self):
""" Clcula la edad real"""
return self.edad + 5
def __str__(self):
"""formatea el objeto persona en STR"""
return "{:10} {:15} {:>3} {:>3}". format(self.nombre, self.a_paterno, self.edad, self.edad_real)
#modelo
def obtener_personas():
"""genera lista de personas tipo personas"""
#Genera una lista de instancias del objeto Persona
personas =[
Persona("PEPE","Lucas",34),
Persona("Mario","Martinez",15)
]
return personas
#vista
def imprimir_personas(personas):
"""imprime personas en la salida estandart en formato de texto plano"""
for p in personas:
print(p)
#controlador
def main ():
""" funcion principal de script"""
personas = obtener_personas()
imprimir_personas(personas)
if __name__ == "__main__":
main() |
6b53685e49c79904aa57b9a33560a817b862ef6a | pathakamaresh86/python_class_prgms | /module_packages/basics/build/lib/Dict/dict_menu_driven.py | 2,082 | 4.125 | 4 | #!/usr/bin/python
def dict_append(x,key,value):
temp=list()
if key in x.keys():
if type(x[key]) == list:
for val in x[key]:
temp.append(val)
else:
temp.append(x[key])
temp.append(value)
x[key]=temp
else:
x[key]=value
def dict_delete(x,key,value):
for key1 in x.keys():
if key1 == key:
if type(x[key1]) == list and x[key1].__contains__(value):
for l1 in x[key1]:
if l1 == value:
x[key1].remove(l1)
if len(x[key1]) == 1:
for item in x[key1]:
x[key1]=item
else:
if x[key1] == value:
x.pop(key1)
def dict_search(x,key,value):
for key1 in x.keys():
if key1 == key:
if type(x[key1]) == list:
if x[key1].__contains__(value):
print "given key value pair is present in dictionary"
return
else:
if x[key1] == value:
print "given key value pair is present in dictionary"
return
print "Given key value pair is not present in dictionary"
def dict_display(x):
for key1 in x.keys():
if type(x[key1]) == list:
for l1 in x[key1]:
print key1,":",l1
else:
print key1,":",x[key1]
def menu():
ch = -1
while ch < 1 or ch > 6:
print("Welcome To Dictionary Menu !!!")
print("1.update\n2.delete\n3.append\n4.search\n5.Display All\n6.Exit")
ch = input("Enter Choice")
return ch
def dict_operations():
x=input("Enter dictionary:")
ch = menu()
while(ch != 6):
if ch == 1:
key=input("Enter key:")
value=input("Enter value")
x[key]=value
print x
elif ch == 2:
key=input("Enter key:")
value=input("Enter value")
dict_delete(x,key,value)
print x
elif ch == 3:
key=input("Enter key:")
value=input("Enter value")
dict_append(x,key,value)
print x
elif ch == 4:
key=input("Enter key:")
value=input("Enter value")
dict_search(x,key,value)
print x
elif ch == 5:
dict_display(x)
else:
break
ch = menu()
def main():
dict_operations()
if __name__ == "__main__":
main()
|
2e5702c2d14e5a840ce585bfba073f3fbf7cdf07 | Sourceless/algorithms | /algorithms/searching/kmp_search.py | 1,143 | 3.9375 | 4 | """
kmp_search.py
This module implements kmp search on a sorted list.
KMP Search Overview:
------------------------
Uses a prefix function to reduce the searching time.
Pre: a sorted list[0,...n,] integers and the key to search for.
Post: returns the index of where the first element that matches the key.
Time Complexity: O(n + k), where k is the substring to be found
Psuedo Code: CLRS. Introduction to Algorithms. 3rd ed.
kmp_search.search(sorted_list) -> integer
kmp_search.search(sorted_list) -> False
"""
def search(string, word):
n = len(string)
m = len(word)
pi = compute_prefix(word)
q = 0
for i in range(n):
while q > 0 and word[q] != string[i]:
q = pi[q - 1]
if word[q] == string[i]:
q = q + 1
if q == m:
return i - m + 1
return False
def compute_prefix(word):
m = len(word)
pi = [0] * m
k = 0
for q in range(1, m):
while k > 0 and word[k] != word[q]:
k = pi[k - 1]
if word[k + 1] == word[q]:
k = k + 1
pi[q] = k
return pi
|
1d4e2f7ac819a5291ead321a004180b680ba4f7c | amarcolongo/PROGRAMMING-IN-PYTHON-C996 | /MarcolongoProject.py | 1,504 | 3.5 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import requests
import pandas as pd
import csv
import numpy as np
from bs4 import BeautifulSoup
# In[2]:
url = 'https://www.census.gov/programs-surveys/popest.html' # This is the url provided in the project description
# In[3]:
r = requests.get(url)
# In[4]:
raw_html = r.text
# In[5]:
print(raw_html); # This will print out the html code of the website at the time I did the scrapping
# In[6]:
soup = BeautifulSoup(raw_html, 'html.parser')
# In[7]:
links = soup.find_all("a")
# In[8]:
print('Number of links retrieved: ', len(links))
# In[9]:
MySet = set()
# In[10]:
for link in links:
hrefs = str(link.get("href"))
if hrefs.startswith('None'):
''
elif hrefs.startswith('#http'):
MySet.add(hrefs[1:])
elif hrefs.startswith('#'):
''
elif hrefs.startswith('/'):
MySet.add ('https://www.census.gov' + hrefs)
elif hrefs.endswith('.gov'):
MySet.add (hrefs + '/')
else:
MySet.add(hrefs)
# In[11]:
f = open("MarcolongoFinalAssignment.csv", "w")
writer = csv.writer(f, delimiter= ' ', lineterminator = '\r')
# In[12]:
MyList = []
ctr = 0
for x in MySet:
MyList.append(x)
if not MyList:
''
else:
writer.writerow(MyList)
del MyList[:]
ctr += 1
# In[13]:
print('Number of URLs written to CSV', ctr)
# In[14]:
f.close()
|
a94771be8d94ee2e7a94be6775c5d962d8b67e02 | penghou620/Coding-Practice | /Python-Practice/Udacity-Programming-Languages/Lesson1/Boilerplate.py | 664 | 3.828125 | 4 | #!/usr/bin/python
class Employee:
employee_total = 0
def __init__(self,employee_name,employee_id):
self.employee_name = employee_name
self.employee_id = employee_id
Employee.employee_total += 1
def total(self):
print "Total employee %d" % Employee.employee_total
def getName(self):
print "Name: ", self.employee_name
class Jijia(Employee):
def __init__(self,employee_name,employee_id):
self.position = "Jijia"
def getPos(self):
print "Jijia"
emp1 = Employee("Zara","asdf")
emp2 = Jijia("Hou","123")
emp1.getName()
print hasattr(emp1,'employee_name')
print Employee.__dict__
print Employee.__module__
emp2.total()
emp2.getPos()
emp2.getName()
|
8b2113a1723c2c0b34ea2b55f0528175067bb13b | vikramchdry/Python-coding-Practice | /subset.py | 591 | 3.65625 | 4 | '''def my_function(s):
for ch in s:
#print(ch)
output = " "
if ch.isalpha():
output = output+ch
#print(output)
x = ch
print(x)
else:
d = int(ch)
newchar = chr((ord(x)+d))
#print(newchar)
#print(d)
my_function('a4k3b2')'''
'''def my_fun(s):
for word in s:
output = ""
if word.isalpha():
#output = output+word
x = word
#print(x)
else:
d = int(word)
output = output+x*d
print(output)
my_fun('a4k3b2')'''
class Test:
def average(self,list):
result = sum(list)/len(list)
print(list)
t = Test()
t.average([10,20,30,40])
|
e2a723e17be8e428d047a8f57ce7f180d377afc0 | leapingllamas/p-value.info | /jokes_2013_01/generate_jokes.py | 1,000 | 3.765625 | 4 | def indefinite_article(w):
if w.lower().startswith("a ") or w.lower().startswith("an "): return ""
return "an " if w.lower()[0] in list('aeiou') else "a "
def camel(s):
return s[0].upper() + s[1:]
def joke_type1(d1,d2,w1,w2):
return "What do you call " + indefinite_article(d1) + d1 + " " + d2 + "? " + \
camel(indefinite_article(w1)) + w1 + " " + w2 + "."
def joke_type2(d1,d2,w1,w2):
return "When is " + indefinite_article(d1) + d1 + " like " + indefinite_article(d2) + d2 + "? " + \
"When it is " + indefinite_article(w2) + w2 + "."
data = open("processed_homonyms.txt","r").readlines()
for line in data:
[w1,d1,pos1,w2,d2,pos2]=line.strip().split("\t")
if pos1=='adjective' and pos2=='noun':
print joke_type1(d1,d2,w1,w2)
elif pos1=='noun' and pos2=='adjective':
print joke_type1(d2,d1,w2,w1)
elif pos1=='noun' and pos2=='noun':
print joke_type2(d1,d2,w1,w2)
print joke_type2(d2,d1,w2,w1) |
2de157112c44666679bda07b795779e5df6c6bd6 | qwertie64982/Coding4Medicine-2017 | /Ancestry/categorize.py | 3,915 | 3.578125 | 4 | # SUMMARY
# This program segregates genomes by region.
# Differences in genomes are larger between regions than between the people within them.
# Thus, it is possible to determine categorize genomes by large vs. small differences.
#
# The purpose of this program is to demonstrate basically how
# procedures like Geographical Population Structure (GPS) work.
#
# Maxwell Sherman
def score(allGenes, i, j):
gene1 = allGenes[i]
gene2 = allGenes[j]
score = 0
for m in range(0, len(gene1)):
if gene1[m] != gene2[m]: # count polymorphisms
score += 1
return score
def allScores(allGenes):
scores = {}
for i in range(0, len(allGenes)):
for j in range(0, len(allGenes)):
if i != j:
scores[str(i) + "," + str(j)] = score(allGenes, i, j)
return scores
def correlate(allGenes):
groups = []
for key in scores:
if scores[key] < 300: # threshold for matching people (magic numbers > non-static global variables)
people = map(int, key.split(","))
group = 0
hasNotAppended = True
while group < len(groups) and hasNotAppended:
if people[0] in groups[group] or people[1] in groups[group]:
groups[group].append(people[0])
groups[group].append(people[1])
hasNotAppended = False
group += 1
if hasNotAppended:
groups.append([people[0]])
groups[-1].append(people[1])
fixedRepeats, fixedOverlaps = True, True
while fixedRepeats or fixedOverlaps:
groups, fixedRepeats = removeRepeats(groups, False)
groups, fixedOverlaps = removeOverlaps(groups, False)
return groups
def removeOverlaps(groups, fixedOverlaps):
fixedOverlaps = False
for i in range(0, len(groups)): # for each population
# print "Comparing to:", groups[i] # DEBUG
for j in range(0, len(groups)): # look at all the other populations
if groups[i] != groups[j]: # (not itself).
for person in groups[j]: # for each person in the each other population
if person in groups[i]: # if he's also in the initial population
for otherPerson in groups[j]: # take the whole other population
# print otherPerson # DEBUG
groups[i].append(otherPerson) # and add it to the first
groups[j] = [] # then get rid of where the other population used to be
fixedOverlaps = True
return groups, fixedOverlaps
def removeRepeats(groups, fixedRepeats):
# print groups # DEBUG
fixedRepeats = False
for i in range(0, len(groups)):
contents = []
for person in groups[i]:
if person not in contents:
contents.append(person)
else:
fixedRepeats = True
groups[i] = contents
# print contents # DEBUG
return groups, fixedRepeats
def format(groups):
# Sort numbers within groups
for i in range(len(groups)):
groups[i].sort()
# Remove empty elements and sort populations
groups2 = []
for i in range(len(groups)):
if groups[i] != []:
groups2.append(groups[i])
groups2.sort()
return groups2
# MAIN
infile = open("/share/data/ancestry/figure-out2.txt", "r")
allGenes = infile.readlines()
scores = allScores(allGenes)
# print scores # DEBUG
groups = correlate(allGenes)
groups = format(groups)
# print groups
for population in groups:
print population
|
2bd90cb5a62d8c624c86be19dcd90b988a84e4eb | maro-create/pythonProject1 | /Lekce 3/priklad015.py | 802 | 3.78125 | 4 | datum = input("Zadejte datum, pro které chcete vstupenky koupit ve formátu DD.MM.RRRR: ")
from datetime import datetime
pozadovaneDatum = datetime.strptime(datum, "%d.%m.%Y")
print("pozadovaneDatum =", pozadovaneDatum)
pocetOsob = int(input ("Zadejte počet osob: "))
zacatekSezonyA = datetime(2021,7,1)
konecSezonyA = datetime(2021,8,10)
zacatekSezonyB = datetime(2021,8,11)
konecSezonyB = datetime(2021,8,31)
if zacatekSezonyA <= pozadovaneDatum <= konecSezonyA:
cenaVstupenky = 250
celkovaCena = cenaVstupenky * pocetOsob
print(f"Cena vstupenek je {celkovaCena} Kč.")
if zacatekSezonyB <= pozadovaneDatum <= konecSezonyB:
cenaVstupenky = 180
celkovaCena = cenaVstupenky * pocetOsob
print(f"Cena vstupenek je {celkovaCena} Kč.")
else:
print("Letní kino je v té době uzavřené.") |
ca6f82dcdd28e02fd420139dac15eaab0ac2a9af | AstinCHOI/algo_ | /1_data_structure/2_linked_list/14_insert_at_sorted_doubly_lists.py | 1,096 | 4.21875 | 4 |
"""
Insert a node into a sorted doubly linked list
head could be None as well for empty list
Node is defined as
class Node(object):
def __init__(self, data=None, next_node=None, prev_node = None):
self.data = data
self.next = next_node
self.prev = prev_node
return the head node of the updated list
"""
# def SortedInsert(head, data):
# if head is None:
# return Node(data)
# elif data < head.data:
# node = Node(data, head)
# head.prev = node
# return node
# next = SortedInsert(head.next, data)
# head.next = next
# next.prev = head
# return head
def SortedInsert(head, data):
h = head
if h is None:
return Node(data)
elif data < h.data:
node = Node(data, h)
h.prev = node
return node
while h.next is not None:
if data < h.next.data:
node = Node(data, h.next, h)
h.next = h.next.prev = node
return head
h = h.next
h.next = Node(data, None, h)
return head |
ddb6cf3e8bd595be5ed56c37d701dff1d6494103 | nbvc1003/python | /ch04_5/sub1.py | 201 | 3.640625 | 4 |
x = 7
x += 2
print(x)
x -= 2
print(x)
x *= 2
print(x)
x /= 2
print(x)
x %= 2 # x = x % 2나머지의 나머지
print(x)
x **= 2 # x = x ** 2제곰의 2제곰
print(x)
x //= 2 # x = x // 2
print(x)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.