blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
9fcae71930edcd89c155e87502e173e4c36186bc | darth-c0d3r/letterboxd-lists | /util.py | 1,621 | 3.578125 | 4 | import requests
from bs4 import BeautifulSoup
def get_soup(link):
"""
Get the soup for the HTML from link using requests.
"""
page = requests.get(link)
return BeautifulSoup(page.content, 'html.parser')
def get_films_on_page(link, page_no):
"""
return the list of films on current page
"""
all_films = []
# get the elements containing films
soup = get_soup(link+"page/%d"%(page_no))
list_elements = soup.find_all(class_="film-poster")
# iterate over all the elements
for film in list_elements:
all_films.append(film.img.get('alt'))
return all_films
def get_all_films(link):
"""
return a list of all the films in a list
"""
all_films = []
# start from the first page
page_no = 1
while True:
# get films on the current page
films_on_page = get_films_on_page(link, page_no)
# if the page doesn't have any films
if len(films_on_page) == 0:
break
all_films += films_on_page
page_no += 1
return set(all_films)
def get_all_urls(filename):
"""
return all the URLs from filename
"""
# get all the lines from filename
file = open(filename)
all_lines = file.readlines()
file.close()
# init empty list
urls = []
# iterate over all lines
for line in all_lines:
# skip an empty line
if len(line.strip()) == 0:
continue
# skip commented out line
if line[0] == '#':
continue
urls.append(line.strip())
return urls
def union(lists):
"""
return the union of all the lists in 'lists'
"""
return set([]).union(*lists)
def intersection(lists):
"""
return the intersection of the lists in 'lists'
"""
return lists[0].intersection(*lists)
|
9e3e68424aabe6d77977a831d893b679bbb084a2 | Herrizq/Color-game | /main.py | 2,720 | 3.625 | 4 | from tkinter import *
import random
root = Tk()
#int, str etc.
Colors = ["red", "green", "blue", "pink", "orange", "yellow", "black", "grey","magenta"]
score_number = IntVar()
score_number.set(0)
time_num = IntVar()
time_num.set(60)
#Commands
def change(x):
global text
if time_num.get() == 60:
root.after(1000, timer)
if enter.get() == text['foreground']:
score_number.set(score_number.get()+1)
print(score_number.get())
score = Label(root, text="Score : " + str(score_number.get()), font=(12))
score.grid(row=1, column=0, columnspan=3)
text.destroy()
text = Label(root, text=random.sample(Colors, 1)[0], font=(12))
text.grid(row=2, column=0, columnspan=3)
text.config(foreground=random.sample(Colors, 1)[0])
else:
text.destroy()
text = Label(root, text=random.sample(Colors, 1)[0], font=(12))
text.grid(row=2, column=0, columnspan=3)
text.config(foreground=random.sample(Colors, 1)[0])
enter.delete(0, END)
def timer():
global time
if time_num.get() == 0:
time = Label(root, text="Game Over!", font = (12))
time.grid(row=3, column=0)
enter = Entry(root, state=DISABLED)
enter.grid(row=4, column=1)
else:
time.destroy()
time_num.set(time_num.get() - 1)
root.after(1000, timer)
time = Label(root, text="Time left: " + str(time_num.get()), font = (12))
time.grid(row=3, column=0)
def restart():
time.destroy()
time_num.set(61)
score_number.set(0)
score = Label(root, text="Score : " + str(score_number.get()), font=(12))
score.grid(row=1, column=0, columnspan=3)
enter = Entry(root)
enter.grid(row=4, column=1)
root.after(1000, timer)
#Display instruction
instruction = Label(root, text = "Write name of color that you can see.", font = (40))
instruction.grid(row = 0, column = 0, columnspan = 3)
#Display color
text = Label(root, text = random.sample(Colors, 1)[0], font = (12))
text.grid(row = 2, column = 0, columnspan = 3)
text.config(foreground = random.sample(Colors,1)[0])
#Enter an answear
enter = Entry(root)
enter.grid(row = 4, column = 1)
enter.bind("<Return>", (lambda event: change(enter.get())))
#Score
score = Label(root, text = "Score : " + str(score_number.get()), font =(12))
score.grid(row = 1, column = 0, columnspan =3 )
#Timer
time = Label(root, text = "Time left: " + str(time_num.get()), font = (12))
time.grid(row = 3, column = 0,columnspan =3)
#Restart
restart = Button(root, text = "Restart", command =restart)
restart.grid(row =5, column = 0)
root.mainloop() |
bfea92143c2df4029288b4c781a8bfce28832891 | brandonharris177/Computer-Architecture | /coding_challange.py | 668 | 4.65625 | 5 | # Given the following array of values, print out all the elements in reverse order, with each element on a new line.
# For example, given the list
# [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
# Your output should be
# 0
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
# 10
# You may use whatever programming language you'd like.
# Verbalize your thought process as much as possible before writing any code. Run through the UPER problem solving framework while going through your thought process.
def print_reverse(array):
for value in range(1, len(array)+1):
print(array[-value])
array = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
print_reverse(array)
|
6f664e1c5ac800f0a4e3c6c174cbe2bfa0e21add | michaelcwatts123/InterviewPrep | /LeetCode/maxProduct.py | 951 | 3.625 | 4 | # Given an integer array, find three numbers whose product is maximum and output the maximum product.
class Solution:
def maximumProduct(self, nums: List[int]) -> int:
if(max(nums) < 0 or min(nums) >= 0):
total = max(nums)
nums[nums.index(total)] = -sys.maxsize
for i in range(2):
total *= max(nums)
nums[nums.index(max(nums))] = -sys.maxsize
return total
else:
min1 = min(nums)
nums[nums.index(min1)] = 0
min2 = min(nums)
nums[nums.index(min2)] = 0
maxNum = max(nums)
nums[nums.index(maxNum)] = 0
max1 = max(nums)
nums[nums.index(max1)] = 0
max2 = max(nums)
nums[nums.index(max2)] = 0
if((min1*min2) > (max1*max2)):
return (min1*min2*maxNum)
else:
return (maxNum*max1*max2) |
a7cb31b0ccf4a751365c9606771eef628de341ea | kreno911/python-tools | /comma.py | 456 | 3.84375 | 4 | #!/usr/bin/python
# Add commas to long #s
## Usage: ./comma.py 123456
## returns: 123,456
import os, sys
# Number needs to be a string, not an int (int not iterable)
def comma(number):
e = list(number)
for i in range(len(e))[::-3][1:]:
e.insert(i+1,",")
return "".join(e)
if len(sys.argv) < 1:
print("Please enter a number!")
sys.exit(11)
number = sys.argv[1]
print (comma(number))
|
7ec121d75584a283e0de357a898898b3fefcfb7f | amoran0861/ProgramArchive | /rivers.py | 485 | 4.21875 | 4 | #Aidan Moran
#Print rivers and their locations
def RiverList():
rivers = {
"USA": "Mississippi River",
"Brazil": "Amazon River",
"China": "Yangtze"
}
for place in rivers.keys():
print(rivers[place], "is in", place)
print("Locations:")
for place in rivers.keys():
print(place)
print("Rivers:")
for place in rivers.keys():
print(rivers[place])
def main():
RiverList()
main()
input("Press enter to exit")
|
010614d8cdd0dac48cea9c50856008095a08c951 | uriberger/reserach_methods_in_software_engineering | /char_ind_to_str.py | 1,410 | 3.96875 | 4 | """ The function receives a mapping of char->list of indices. It should build the implied string.
For example: if the input is:
'g' -> [2]
'd' -> [0]
'o' -> [1]
The output should be 'dog'.
Features tested:
- List and dictionary comprehension vs. loops
"""
def long_char_ind_to_str(char_to_ind_dic):
ind_to_char_dic = {}
for key, val in char_to_ind_dic.items():
for ind in val:
if not ind in ind_to_char_dic:
ind_to_char_dic[ind] = []
ind_to_char_dic[ind].append(key)
for char_list in ind_to_char_dic.values():
assert len(char_list) <= 1
key_list = list(ind_to_char_dic.keys())
key_list.sort()
res_str = ""
for key in key_list:
cur_char = ind_to_char_dic[key][0]
res_str = res_str + cur_char
return res_str
def short_char_ind_to_str(char_to_ind_dic):
ind_to_char_dic = {
val: [x for x in char_to_ind_dic.keys() if val in char_to_ind_dic[x]]
for val in range(max([max(y) for y in char_to_ind_dic.values()]) + 1)
}
assert max([len(x) for x in ind_to_char_dic.values()]) == 1
return "".join([x[0] for x in ind_to_char_dic.values()])
# example_dic = {'a' : [0,4], 'v' : [1,4], 'o' : [2,6], 'c' : [3], 'd' : [5]}
example_dic = {"a": [0, 4], "v": [1], "o": [2, 6], "c": [3], "d": [5]}
print(short_char_ind_to_str(example_dic))
print(long_char_ind_to_str(example_dic))
|
917ac9e099b3d7b932b1b18bae166e8828b09e26 | JohnCetera/Python-Programs | /try, except - practice.py | 458 | 4.21875 | 4 | hours = input("total hours worked: ")
rate = input("pay rate: ")
try:
hr = float(hours)
rt = float(rate)
if hours <= str(40):
pay = hr * rt
print(pay)
elif hours >= str(40):
base_pay = float(40 * rt)
overtime = int(hr - 40)
overtime_rate = int(rt * 1.5)
overtime_pay = int(base_pay + (overtime * overtime_rate))
print(overtime_pay)
except:
print("enter a numerical value")
input() |
ffe9ade759225b05c684dd0096c2624863c8388d | fredzs/Python-Mp3TagSpider | /Utility/ListFunc.py | 415 | 3.5 | 4 | #
class ListFunc(object):
@staticmethod
def compare_2_lists(list1, list2):
compare_result = False
if len(list1) == len(list2) > 0:
for item in list1:
if item.lower() in [i.lower() for i in list2]:
continue
else:
break
else:
compare_result = True
return compare_result
|
4554afec1fbc9dfb87c9206093597b019e4b3958 | adamwinzdesign/Sprint-Challenge--Data-Structures-Python | /ring_buffer/ring_buffer.py | 978 | 3.53125 | 4 | class RingBuffer:
def __init__(self, capacity):
self.capacity = capacity
self.data = []
self.oldest = 0
def append(self, item):
# if current length of self.data is less than the provided capacity, simply add that item to data
if len(self.data) < self.capacity:
self.data.append(item)
else:
# if current length of self.data is equal to the provided capacity, remove the oldest item, then insert the new item where the oldest item had been
self.data.remove(self.data[self.oldest])
self.data.insert(self.oldest, item)
# determine if we need to increment oldest or reset it to 0
if self.oldest == self.capacity -1:
self.oldest = 0
else:
self.oldest += 1
def get(self):
for i in self.data:
if self.data == None:
self.data.remove(self.data[i])
return(self.data)
|
e9227166aa61957df852b87682a09891a40309ac | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/bob/fe6e1e28feed47d88a81f1e42ee77aa3.py | 402 | 3.6875 | 4 | class Bob:
"""A teenager."""
def hey(self, statement):
"""Communicate with Bob."""
statement = statement.strip()
if not statement:
return "Fine. Be that way!"
if statement.isupper():
return "Woah, chill out!"
elif statement.endswith('?'):
return "Sure."
elif statement:
return "Whatever."
|
df14696a460a3d2be10b009e44b4181631eb163b | Mureke/Advent-of-code | /2020/day_3/day3_1.py | 663 | 3.53125 | 4 |
if __name__ == '__main__':
with open('data.txt', 'r') as f:
lines = [line.strip() for line in f.readlines()]
total_width = len(lines[0])
total_height = len(lines)
height = 0
width = 0
answer = 0
while height < total_height:
try:
if lines[height][width] == '#':
answer += 1
except IndexError as e:
print('Index Error: ')
print(width)
print(height)
width += 3
height += 1
if width >= total_width:
width -= total_width
print(answer)
|
056615a7cac4d1b22fff3c786a459b9cc2e20d20 | 404-html/coursework | /Extreme Computing/EXC-CW1-stuff/task4-reducer.py | 386 | 3.5 | 4 | #!/usr/bin/python
import sys
prevline = ""
linecount = 0
#Basically same stuff in task 2
for line in sys.stdin:
line = line.strip()
if (prevline != line):
if linecount > 0:
print("{0}\t{1}".format(prevline,linecount))
prevline = line
linecount = 1
else:
linecount = linecount + 1
print("{0}\t{1}".format(prevline,linecount))
|
36eb1a8f833c5f7006d2aed10112c424df30e41b | mdallow97/InterviewPrep | /Arrays/matrix_spiral.py | 674 | 3.578125 | 4 | # matrix_spiral.py
def matrixSpiral(matrix):
result = []
while matrix:
# go right
for item in matrix.pop(0):
result.append(item)
if not matrix or not matrix[0]:
break
# go down
i = len(matrix[0])-1
for j in range(len(matrix)):
result.append(matrix[j].pop(i))
if not matrix:
break
# go left
for item in reversed(matrix.pop(len(matrix)-1)):
result.append(item)
if not matrix or not matrix[0]:
break
# go up
current_index = len(result)
for j in range(len(matrix)):
result.insert(current_index, matrix[j].pop(0))
return result
print(matrixSpiral([[1,11],[2,12],[3,13],[4,14],[5,15],[6,16],[7,17],[8,18],[9,19],[10,20]]))
|
c24776f4330ee2ec2db63413e9ec3ead2b3157c2 | pb0528/codelib | /Python/lesson/range_test.py | 240 | 3.703125 | 4 | #Range(begin,end,step) 范围内按照补偿递增 按照[,)方式递增
for i in range(1,100):
print(i)
for i in range(100,0,-1):
print(i)
#while 与C++大致相似
sum,num = 0,2
while num<100:
sum+=num
num+=2
print(sum) |
a1c9585367e48719ed7e048a42264140ed78e68d | frontendcafe/py-study-group | /ejercicios/CodeWars/AmitSna/are_arrow_functions_odd.AmitSna.py | 114 | 3.515625 | 4 | odds = lambda nums: [num for num in nums if num%2==1]
def odds(nums):
return [num for num in nums if num%2==1]
|
d49308677232fe4ac4a45ec769035bddbffbd26d | roque-brito/ICC-USP-Coursera | /icc_pt1/exe_extras/objetos_na_memoria_ex1.py | 2,196 | 3.984375 | 4 | # lista de temperaturas
# Qual o dia das temperaturas mais baixa e mais alta:
def MinMax(temperaturas):
print('A menor temperatra do mê foi: ', minima(temperaturas), '°C')
print('A maior temperatra do mê foi: ', maxima(temperaturas), '°C')
def minima(temps):
min = temps[0]
i = 0
while i < len(temps):
if temps[i] < min:
min = temps[i]
i += 1
return min
def maxima(temps):
max = temps[0]
i = 0
while i < len(temps):
if temps[i] > max:
max = temps[i]
i += 1
return max
def teste_pontual(temp, valor_esperado):
valor_calculado = minima(temp)
if minima(temp) != valor_esperado:
print('Valor errado para array', temp)
print('Valor esperado: ', valor_esperado, 'Valor calculado: ', valor_calculado)
# ============================ INICIANDO TESTES ================================
from random import randint
def crie_matriz(i_linhas, j_colunas, n):
''' (int, int, valor) -> matriz(lista de listas)
Cria e retorna uma matriz com "i" linhas e "j" colunas
em que cada elemento é igual ao valor dado.
'''
# Cria matriz vazia:
matriz = []
for i in range(i_linhas):
# Cria a linha "i" - a linha já contém as colunas:
# Cria uma lista (linha) vazia:
linha = []
for j in range(j_colunas):
linha += [randint(-15,50)]
# Inserir a linha criada na matriz -> "matriz recebe linha":
matriz += [linha]
return(matriz)
A = crie_matriz( 5, 30, 0) # 5 testes | 30 valores (30 dias) | entrada == 0
print('Matriz de "zeros" = lista de listas => ', A)
def imprime_matriz(A):
n_linhas = len(A)
n_colunas = len(A[0])
for i in range(n_linhas):
for j in range(n_colunas):
T_mín = min(A[i])
T_máx = max(A[i])
linha = A[i][j]
print(linha)
return(T_mín, T_máx
)
imprime_matriz(A)
dados_testes = []
def testa_minima(T_mín, T_máx, ):
print('[Iniciando os testes]')
print('[Teste finalizado]')
|
2c1bd67e90dce07adcee512e6a8a989f2742508a | shahramg92/Class-Exercises | /Week-1/Python-Exercises-1/madlib.py | 146 | 4.15625 | 4 | name = input("What is your name?")
subject = input("What is your favorite subject?")
print("{0}'s favorite subject is {1}".format(name, subject))
|
01483b5d0688a0c92474c6a46483a260ef863881 | ceuity/algorithm | /boj/python/1978.py | 436 | 3.53125 | 4 | if __name__ == '__main__':
n = int(input())
prime_list = list(map(int, input().split()))
count = 0
flag = 0
if n == len(prime_list):
for i in prime_list:
if i == 1:
continue
for j in range(1, i + 1):
if i % j == 0:
flag += 1
if flag == 2:
count += 1
flag = 0
print(count)
|
bcec382d31e81523e3388b3b999584cde8b536d6 | rpotter12/learning-python | /section3: python statements/3-whileLoops.py | 591 | 4.03125 | 4 | # while loops will continue to execute a block of code while some conditions remains true
# a while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition
# SYNTAX
# while some_boolean_condition:
# code
x=0
while x<5:
print(f'x: {x}')
x=x+1
# print the values 5 times
else:
print('x is greater than 5')
print('\n\n')
# break - the break keyword stops the loop
# continue - the continue keyword goes to the top of the closest enclosing loop
# pass - does nothing
a=[1,2,3,4,5]
for item in a:
pass
print("end")
|
ee3c84095a4fb5fb2fe454f4a40a6cd207935aac | Lmineor/Sword-to-Offer | /bin/22.py | 368 | 3.546875 | 4 | class Node:
def __init__(self,data,_next = None):
self.data = data
self._next = _next
def __repr__(self):
return str(self.data)
def ChainTable(Head,index):
num = []
root = Head
while root:
num.append(root)
root = root._next
if index > len(num):
return False
else:
return num[-index]
|
0ef5ab05c9bd487301a5d0bd404f5dc1d356106d | Ewenwan/Algorithms-2 | /Cantor expansion/应用_字符串比大小.py | 1,287 | 3.5625 | 4 | """
现在有"abcdefghijkl”12个字符,将其所有的排列中按字典序排列,给出任意一种排列,说出这个排列在所有的排列中是第几小的?
eg:
input:
第一行有一个整数n(0<n<=10000);
随后有n行,每行是一个排列;
3
abcdefghijkl
hgebkflacdji
gfkedhjblcia
output:
输出一个整数m,占一行,m表示排列是第几位;
1
302715242
260726926
"""
from functools import reduce
# 阶乘计算1
def factorial(n):
return reduce(lambda x,y: x*y, (x for x in range(1, n+1)), 1)
# 阶乘计算2
def PermutationNumber(num):
count = 1
for i in range(1, num + 1):
count = count * i
return count
# 需要计算康托展开的字符串首字母所在的索引位置
def FirstCharPosition(instr):
clist = []
for c in instr:
clist.append(c)
clist.sort()
return clist.index(instr[0])
# 计算康托展开值
def Compare(instr):
if len(instr) == 1:
return 1
return FirstCharPosition(instr) * PermutationNumber(len(instr) - 1) + Compare(instr[1:])# 回归迭代
if __name__ == "__main__":
number = int(input().strip())
list = []
for i in range(number):
list.append(raw_input().strip())
for i in range(number):
print (Compare(list[i]))
|
02c308555c43402f2e16cec5ad7af2124e216ffb | bolod/bioEuler | /src/OLD/BioTree.py | 2,418 | 3.546875 | 4 | class BioTree():
def __init__(self, bio_node, parent=None):
self.bio_node = bio_node
self.parent = parent
if (bio_node != None):
self.left = BioTree(None)
self.right = BioTree(None)
def __repr__(self):
return str([str(value) for value in self.vectorialize()])
def is_empty(self):
return self.bio_node == None
def has_childs(self):
return not self.is_empty() and self.left != None and self.right != None
def set_node(self, bio_node):
self.bio_node = bio_node
return self
def set_left(self, bio_tree):
self.left = bio_tree
bio_tree.parent = self
return self.left
def set_right(self, bio_tree):
self.right = bio_tree
bio_tree.parent = self
return self.right
def set_parent(self, parent):
self.parent = parent
return self.parent
def get_level(self):
if(self.parent == None):
return 0
else:
return 1 + self.parent.get_level()
def get_node(self):
return self.bio_node
def get_left(self):
return self.left
def get_right(self):
return self.right
def get_parent(self):
return self.parent
def vectorialize(self):
vector = []
tree = [self]
while tree:
node = tree.pop(0)
if(node.get_node() != None):
vector.append(node.get_node())
if (node.has_childs()):
tree.extend([node.get_left(), node.get_right()])
return vector
def switch(self, bio_tree, distance):
if (not(self.has_childs() and bio_tree.has_childs())):
return
(left1, right1) = (self.get_left(), self.get_right())
(left2, right2) = (bio_tree.get_left(), bio_tree.get_right())
dl1l2 = distance(left1.get_node().get_value(), left2.get_node().get_value())
dr1r2 = distance(right1.get_node().get_value(), right2.get_node().get_value())
dr1l2 = distance(right1.get_node().get_value(), left2.get_node().get_value())
dl1r2 = distance(left1.get_node().get_value(), right2.get_node().get_value())
if (dl1l2 + dr1r2 > dr1l2 + dl1r2):
bio_tree.set_left(right1)
bio_tree.set_right(left1)
left1.switch(left2, distance)
right1.switch(right2, distance)
|
2976abf84df765e48f3fe44b07131d77c0ac175d | syurskyi/Python_Topics | /095_os_and_sys/examples/ITVDN Python Essential 2016/00-read_file.py | 804 | 3.9375 | 4 | """Пример открытия файла для чтения"""
def read_file(fname):
"""Функция для чтения файла fname
и вывода его содержимого на экран
"""
# Открытие файла для чтения
file = open(fname, 'r')
# Вывод названия файла
print('File ' + fname + ':')
# Чтение содержимого файла построчно
for line in file:
# Вывод строки s. Перевод строки в файле сохраняется в строке, поэтому
# выводим без дополнительного перевода строки.
print(line, end='')
# Закрытие файла
file.close()
if __name__ == '__main__':
read_file('data/file.txt') |
a5d4f12f5fd533109924ce58b7bc18835e868693 | Samboy218/6903-Tools | /AES/encrypt.py | 2,246 | 3.671875 | 4 | #Author: Will Johnson
#Date: 11/20/18
#project: AES tool
#Use Case: Encrypt/Decrypt large strings with AES
#!/usr/bin/python
import sys
import bitWise
import binConv
#substitutes a matrix of bytes with another matrix of bytes
#This function can be changed. It just has to do the inverse of
#the sub bytes in the decrypt file
#Think S box (the one I did here is very weak)
def sub_bytes(pt):
ctL = []
for bit in pt:
if bit == '0':
ctL.append('1')
elif bit == '1':
ctL.append('0')
ct = ''.join(ctL)
return ct
#Mixes the columns of a given byte matrix around.
#This function can be changed. It just has to do the opposite of
#the one in the decrypt file
def mix_cols(pt):
ptList = list(pt)
ctList = []
col1 = []
col2 = []
col3 = []
col4 = []
cols = [col1, col2, col3, col4]
for x in range(len(pt)):
cols[x % 4].append(ptList[x])
for y in range(len(col1)):
ctList.append(cols[3][y])
ctList.append(cols[2][y])
ctList.append(cols[1][y])
ctList.append(cols[0][y])
return ''.join(ctList)
#Shifts rows of a byte matrix by given AES standards
def shift_rows(pt):
row1 = []
row2 = []
row3 = []
row4 = []
ptList = list(pt)
for x in range(len(pt)):
if(x < 32):
row1.append(ptList[x])
elif(x < 64):
row2.append(ptList[x])
elif(x < 96):
row3.append(ptList[x])
elif(x < 128):
row4.append(ptList[x])
row1s = ''.join(row1)
row2s = bitWise.shift_left(''.join(row2), 8)
row3s = bitWise.shift_left(''.join(row3), 16)
row4s = bitWise.shift_left(''.join(row4), 24)
return row1s + row2s + row3s + row4s
#encrypts one AES block
#takes a plaintext pt, and a key
#returns a ciphertext CT
def encrypt_block(pt, key):
#convert pt to binary
ptb = binConv.text_to_bits(pt)
#generate the round keys, convert them to binary
round_keys = bitWise.key_expansion(key)
round_keys_b = []
for key in round_keys:
keyb = binConv.text_to_bits(key)
round_keys_b.append(keyb)
#pre transformation
working_ct = bitWise.xor(round_keys_b[0], ptb)
#10 Rounds of encryption
for x in range(10):
working_ct = sub_bytes(working_ct)
working_ct = shift_rows(working_ct)
if(x < 9):
working_ct = mix_cols(working_ct)
working_ct = bitWise.xor(round_keys_b[x], working_ct)
ct = working_ct
return ct
|
7ac2e2a9f5dfe686b7046b5e44267dfc00f2c06b | naraekwon/CodingInterviewMastery | /ds_algos_primer/python/heaps.py | 4,617 | 4.375 | 4 | """
Title: Heap Solutions
This file contains the template for the Heap exercisess in the DS & Algos
Primer. If you have not already attempted these exercises, we highly
recommend you complete them before reviewing the solutions here.
"""
from queue import PriorityQueue
from typing import List
"""
Exercise 1.1: Implement a min heap
"""
class MinHeap:
"""
Constructor
"""
def __init__(self):
# INSERT YOUR SOLUTION HERE
"""
Insert an item into the heap
Time Complexity:
Space Complexity:
"""
def insert(self, x: int):
# INSERT YOUR SOLUTION HERE
"""
Get the smallest value in the heap
Time Complexity:
Space Complexity:
"""
def peek(self) -> int:
# INSERT YOUR SOLUTION HERE
"""
Remove and return the smallest value in the heap
Time Complexity:
Space Complexity:
"""
def pop(self) -> int:
# INSERT YOUR SOLUTION HERE
"""
Get the size of the heap
Time Complexity:
Space Complexity:
"""
def size(self) -> int:
# INSERT YOUR SOLUTION HERE
"""
Convert the heap data into a string
Time Complexity:
Space Complexity:
"""
def __str__(self):
# INSERT YOUR SOLUTION HERE
"""
The following are some optional helper methods. These are not required
but may make your life easier
"""
"""
Get the index of the parent node of a given index
Time Complexity:
Space Complexity:
"""
def _parent(self, i: int) -> int:
# INSERT YOUR SOLUTION HERE
"""
Get the index of the left child of a given index
Time Complexity:
Space Complexity:
"""
def _left_child(self, i: int) -> int:
# INSERT YOUR SOLUTION HERE
"""
Swap the values at 2 indices in our heap
Time Complexity:
Space Complexity:
"""
def _swap(self, i: int, j: int):
# INSERT YOUR SOLUTION HERE
"""
Starting at index i, bubble up the value until it is at the correct position
in the heap
Time Complexity:
Space Complexity:
"""
def _bubbleUp(self, i: int):
# INSERT YOUR SOLUTION HERE
"""
Starting at index i, bubble down the value until it is at the correct
position in the heap
Time Complexity:
Space Complexity:
"""
def _bubbleDown(self, i: int):
# INSERT YOUR SOLUTION HERE
"""
Exercise 1.2: Given an array of integers, determine whether the array represents
a valid heap
Time Complexity:
Space Complexity:
"""
def is_valid(heap: List[int]) -> bool:
# INSERT YOUR SOLUTION HERE
"""
Exercise 2.1: Given a list of integers, use a heap to find the largest value in
the list.
Use the Python PriorityQueue type
Time Complexity:
Space Complexity:
"""
def find_max(arr: List[int]) -> int:
# INSERT YOUR SOLUTION HERE
"""
Exercise 2.2: Given a list of integers, use a heap to sort the list.
Use the Python PriorityQueue type
Time Complexity:
Space Complexity:
"""
def heap_sort(arr: List[int]) -> List[int]:
# INSERT YOUR SOLUTION HERE
"""
Exercise 2.3: Find the k-th largest element in a stream of integers
"""
class KthLargest:
"""
Constructor
Time Complexity:
Space Complexity:
"""
def __init__(self, k: int, nums: List[int]):
# INSERT YOUR SOLUTION HERE
"""
Add the next value in the stream
Time Complexity:
Space Complexity:
"""
def add(self, val: int) -> int:
# INSERT YOUR SOLUTION HERE
"""
Exercise 2.4: Find the k closest points to the origin
Time Complexity:
Space Complexity:
"""
def k_closest(points: List[List[int]], k: int) -> List[List[int]]:
# INSERT YOUR SOLUTION HERE
"""
Exercise 3.1: Find the median of a data stream
"""
class MedianFinder:
"""
Constructor
Time Complexity:
Space Complexity:
"""
def __init__(self):
# INSERT YOUR SOLUTION HERE
"""
Add the next number from the stream
Time Complexity:
Space Complexity:
"""
def add_num(self, num: int) -> None:
# INSERT YOUR SOLUTION HERE
"""
Get the median
Time Complexity:
Space Complexity:
"""
def find_median(self) -> float:
# INSERT YOUR SOLUTION HERE
"""
Simple node class
"""
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
"""
Exercise 3.2: Merge k sorted lists
Time Complexity:
Space Complexity:
"""
def merge_k_lists(lists: List[ListNode]) -> ListNode:
# INSERT YOUR SOLUTION HERE
# Test Cases
if __name__ == '__main__':
# ADD YOUR TEST CASES HERE
|
722bbcd33295b622712cdbb37f4ac3532da0da47 | firoza90/leetcode | /linked_list_reverse.py | 806 | 4.125 | 4 | """
https://leetcode.com/problems/reverse-linked-list/
Given the head of a singly linked list, reverse the list, and return the reversed list.
"""
from linked_list import ListNode, createList
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head:
return head
ptr = head
pptr = None
while ptr:
temp = ptr.next
ptr.next = pptr
pptr = ptr
ptr = temp
head = pptr
return head
def test_reverseList(self):
tests = [[1,2,3,4,5], [1,2], []]
for test in tests:
print(test)
l = createList(test)
l = self.reverseList(l)
if l:
l.toString()
else:
print("Empty list")
|
523c53d9120b52c29b4b34230256a225b3b7ea47 | lxjthu/uband-python-s1 | /homeworks/B21562/homework-14item/homework08.py | 1,222 | 3.78125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# @author: xxx
def main():
tup = (1,2,3,4)
#取值
print tup[2]#记得这里要打中括号[],和列表一样下标从0开始,不能同时取两个0,1,想要同时取多个值只能用切片
# 切片
print tup[0:1]#切片左边是闭区间,右边是开区间,即右边的实际取值会比写出来的下标少一位
print tup[2:]#右边什么都不写,默认取到最后一位
print tup[:3]#左边什么都不写,默认从第一位开始数
# 是否存在某值
print (1 in tup) #存在,则打印ture
print (5 in tup) #不存在,则打印false
if 1 in tup:
a,b,c,d=(1,2,3,5) #可以利用元祖直接给多个变量赋值
print a,b,c,d
if not 5 in tup:
a,b,c,d=(7,9,3,2)
print a,b,c,d
# 赋值
x,y,z,q=tup
print x+y,y+z,z+q
# 遍历
for item in tup:
print item
print "enumerate-------"
for index,item in enumerate(tup):
print index+item
# 花式报错
# 不支持 1)插入 2)修改 3) 删除
print "---------"
try:
#tup.append(9)#插入失败
#tup[2]=6#修改失败
del tup[0] #删除失败
except Exception, e:
print e
if __name__ == '__main__':
main()
|
bc992a4c79d7a6f3886e7078baabf10bff455cb8 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_118/1949.py | 1,630 | 3.734375 | 4 | import math
from time import time, clock
INPUT_FILE = "./input3.txt"
RESULT = ""
fair_cache = {}
square_cache = {}
def is_fair(number):
return number == int(str(number)[::-1])
def is_fair_cached(number):
if number in fair_cache:
return fair_cache[number]
fair_cache[number] = is_fair(number)
return fair_cache[number]
def is_square_cached(number):
if number in square_cache:
return square_cache[number]
square_cache[number] = is_square(number)
return square_cache[number]
def is_square(number):
root = math.sqrt(number)
if math.modf(root)[0] == 0.0 and is_fair(int(root)):
return True
return False
if __name__ == "__main__":
# input file
lines = [line.strip() for line in open(INPUT_FILE) if line.strip()]
print "Total entries: ", lines[0]
print "Total lines: ", len(lines)
curPos = 1
# read boards
for boardNum in xrange(int(lines[0])):
RESULT += "Case #" + str(boardNum + 1) + ": "
dimensions = lines[curPos].split()
curPos += 1
start = long(dimensions[0])
end = long(dimensions[1])
print "Dimensions ["+ dimensions[0] + ", " + dimensions[1] + "]"
count = 0
pos = start
start_time = time()
# only consider palindromes
while pos != end + 1:
if is_fair(pos) and is_square(pos):
count += 1
pos += 1
print "Took ", time() - start_time, "seconds"
RESULT += str(count)
RESULT += "\n"
#print
#print "==================================="
#print RESULT
#print "==================================="
output = open('./output3.txt','w')
output.write(RESULT)
output.close() |
39e1a9ebad70ba5a060ae7e279af91ec35941b32 | Pluppo/pynet-lessons | /examples/time_test.py | 186 | 3.828125 | 4 | #! /usr/bin/env python3.6
import time
start_time = time.time()
#Test:
time.sleep(1.2)
elapsed_time = time.time() - start_time
print('Time elapsed: {} seconds'.format(elapsed_time))
|
caae45f27d2c652abdbe3bc9ef3bfb60b2c87f22 | bh107/bohrium | /bridge/bh107/bh107/util.py | 574 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
========================
Useful Utility Functions
========================
"""
import operator
import functools
def total_size(shape):
"""Returns the total size of the values in `shape`"""
return 0 if len(shape) == 0 else functools.reduce(operator.mul, shape, 1)
def get_contiguous_strides(shape):
"""Returns a new strides that corresponds to a contiguous traversal of shape"""
stride = [0] * len(shape)
s = 1
for i in reversed(range(len(shape))):
stride[i] = s
s *= shape[i]
return tuple(stride)
|
3433b72eab28b3ae2d520572593548d611a84717 | nirmal2209/HackerRank | /Python/16) Numpy/Array Mathematics.py | 1,556 | 3.84375 | 4 | """
Basic mathematical functions operate element-wise on arrays. They are available both as operator overloads and as functions in the NumPy module.
import numpy
a = numpy.array([1,2,3,4], float)
b = numpy.array([5,6,7,8], float)
print a + b #[ 6. 8. 10. 12.]
print numpy.add(a, b) #[ 6. 8. 10. 12.]
print a - b #[-4. -4. -4. -4.]
print numpy.subtract(a, b) #[-4. -4. -4. -4.]
print a * b #[ 5. 12. 21. 32.]
print numpy.multiply(a, b) #[ 5. 12. 21. 32.]
print a / b #[ 0.2 0.33333333 0.42857143 0.5 ]
print numpy.divide(a, b) #[ 0.2 0.33333333 0.42857143 0.5 ]
print a % b #[ 1. 2. 3. 4.]
print numpy.mod(a, b) #[ 1. 2. 3. 4.]
print a**b #[ 1.00000000e+00 6.40000000e+01 2.18700000e+03 6.55360000e+04]
print numpy.power(a, b) #[ 1.00000000e+00 6.40000000e+01 2.18700000e+03 6.55360000e+04]
"""
import numpy as np
array_A = list()
array_B = list()
n, m = [int(i) for i in input().strip().split()]
for elements in range(n):
np.array(array_A.append(list(map(int, input().strip().split()))))
for elements in range(n):
np.array(array_B.append(list(map(int, input().strip().split()))))
print(np.add(array_A, array_B))
print(np.subtract(array_A, array_B))
print(np.multiply(array_A, array_B))
print(np.floor_divide(array_A, array_B))
print(np.mod(array_A, array_B))
print(np.power(array_A, array_B))
|
f476f22cffb67b686135728a49db035225e82b86 | Lmineor/Sword-to-Offer | /bin/38.py | 524 | 3.6875 | 4 | def Permutation(string,i):
if string == None:
return
if string[i] == '\n':
print(''.join(string[:i]))
else:
for j in range(i,len(string)-1):
string[j],string[i] = string[i],string[j] #将前面的字符依次与后面进行交换
Permutation(string,i+1)
string[j],string[i] = string[i],string[j] #固定第一个字母对交换完成后的后面的数组进行排列
s = 'abc'
string = list(s+'\n')
Permutation(string,0)
|
8693e877aeee9e5214174782d619e4efef6c6e45 | PJC-1/data_structures_and_algorithms_in_python | /Data_Structures/Linked_List/sort_linked_list.py | 885 | 3.953125 | 4 | class Node:
def __init__(self, value):
self.value = value
self.next = None
def __repr__(self):
return str(self.value)
class SortedLinkedList:
def __init__(self):
self.head = None
def append(self, value):
"""
Append a value to the Linked List in ascending sorted order
Args:
value(int): Value to add to Linked List
"""
if self.head is None:
self.head = Node(value)
return
if value < self.head.value:
node = Node(value)
node.next = self.head
self.head = node
return
node = self.head
while node.next is not None and value >= node.next.value:
node = node.next
new_node = Node(value)
new_node.next = node.next
node.next = new_node
return None
|
87f35c3e2f979316f9e9398f4e39145daa47be3e | MarkMeretzky/Python-INFO1-CE9990 | /monkey1.py | 1,130 | 3.9375 | 4 | """
monkey1.py
Demonstrate how they programmed before they invented lists.
"""
import sys
while True:
try:
year = input("Please type a year: ")
except EOFError:
sys.exit(0)
try:
year = int(year)
except ValueError:
print(f"Sorry, {year} is not an integer.")
continue
remainder = year % 12 #remainder is an integer in the range 0 to 11 inclusive
if remainder == 0:
animal = "monkey"
elif remainder == 1:
animal = "rooster"
elif remainder == 2:
animal = "dog"
elif remainder == 3:
animal = "pig"
elif remainder == 4:
animal = "rat"
elif remainder == 5:
animal = "ox"
elif remainder == 6:
animal = "tiger"
elif remainder == 7:
animal = "hare"
elif remainder == 8:
animal = "dragon"
elif remainder == 9:
animal = "snake"
elif remainder == 10:
animal = "horse"
elif remainder == 11:
animal = "sheep"
else:
print("bad remainder", remainder)
sys.exit(1)
print(f"{year} was the year of the {animal}.")
|
54a999f95764e416c5b0ecd6637fc93b36ebc7ac | lxw15337674/Language_learning | /python/basic_gramma/IO/serialize.py | 1,448 | 4.09375 | 4 | #serialize (序列化)
"""变量从内存中变成可存储或传输的过程称之为序列化
序列化之后,就可以把序列化后的内容写入磁盘,或者通过网络传输到别的机器上。
反过来,把变量内容从序列化的对象重新读到内存里称之为反序列化,即unpickling。
Python提供了pickle模块来实现序列化。"""
import pickle
d = dict(name='bob',age=20,score=88)
print(pickle.dumps(d))
"""pickle.dumps()方法方法把任意对象序列化成一个bytes,然后,就可以把这个bytes写入文件。
或者用另一个方法pickle.dump()直接把对象序列化后写入一个file-like Object:"""
f = open('D:\dump.txt','wb')#wb write bytes
pickle.dump(d,f)
f.close()
"""当我们要把对象从磁盘读到内存时,可以先把内容读到一个bytes,然后用pickle.loads()方法反序列化出对象,
也可以直接用pickle.load()方法从一个file-like Object中直接反序列化出对象。
我们打开另一个Python命令行来反序列化刚才保存的对象:"""
f = open('D:\pickle.txt','rb')#rb read bytes
d = pickle.load(f)
f.close()
print(d)
"""变量的内容又回来了,
Pickle的问题和所有其他编程语言特有的序列化问题一样,就是它只能用于Python,
并且可能不同版本的Python彼此都不兼容,因此,只能用Pickle保存那些不重要的数据,不能成功地反序列化也没关系。"""
|
e40840c3cd2944a69adefd48829117eca6ab84bc | PdxCodeGuild/class_emu | /Code/Larry/python/lab11_v3_simple_calculator.py | 1,751 | 4.28125 | 4 | # filename: lab11_v3_simple_calculator.py
'''
Lab 11: Simple Calculator
Let's write a simple REPL (read evaluate print loop) calculator that can handle addition, subtraction, multiplication,
and division. Ask the user for an operator and each operand. Don't forget that input returns a string,
which you can convert to a float using float(user_input) where user_input is the string you got from input.
Version 3 (optional)
Allow the user to enter a full arithmetic expression and use eval to evaluate it.
'''
while True:
# User input: Ask for an operator and an operand (int, float)
user_arith_exp = input("Enter a full arithmetic expression, e.g. 3+4 (x+y)(x-y)(x*y)(x/y): ")
# Use eval to evaluate it
result = eval(user_arith_exp)
# Check if the float ends with in (x.0, x.00, etc). if True, round it off
# Source: https://stackoverflow.com/questions/16995249/how-to-see-if-a-number-ends-in-0
if int(result) == result and isinstance(result, float):
result = round(result)
# Print the result
print(f"\nResult: {user_arith_exp} = {result}")
# Ask if user wants to keep performing operations (and set answer to lowercase)
play_again = input("\nDo you want to keep performing operations? (yes)(no)(done): ").lower()
if play_again == "no" or play_again == "done": # if user types "no" or "done"
print("Goodbye!\n") # print 'Goodbye!'
break # break out of while loop
# Alternate method for lines 30-32
# if play_again == "yes": # alternate method to "play again"
# continue # if user types "yes", continue, starting at the top of the while loop
# print("Goodbye!\n") # if user types anything else, print 'Goodbye!'
# break # then, break out of while loop
|
851eac30fa710a86684ac28dcd38d3ff0e5ca966 | gabrielavirna/python_data_structures_and_algorithms | /my_work/ch10_design_techniques_&_strategies/dijkstra_shortest_path_greedy.py | 4,870 | 4.125 | 4 | """
Dijkstra's shortest path algorithm
-----------------------------------
- a greedy algorithm; it finds the shortest distance from a source to all other nodes or vertices in a graph.
The worst-case running time: O(|E| + |V| log |V|), where |V| is the number of vertices and |E| is the number of edges.
"""
# Dijkstra - finding the shortest path algorithm
#################################################
# begin with a dictionary representation of the table (table enables tracking the changes in the graph)
# Each key in the dictionary maps to a list.
# [1st index of the list - stores the shortest distance from the source A, 2nd index - stores the previous node]
table = dict()
table = {'A': [0, None],
'B': [float("inf"), None],
'C': [float("inf"), None],
'D': [float("inf"), None],
'E': [float("inf"), None],
'F': [float("inf"), None]}
# DISTANCE: references the shortest path column's index, PREVIOUS_NODE: references the previous node column's index
DISTANCE = 0
PREVIOUS_NODE = 1
INFINITY = float("inf")
def find_shortest_path(graph, table, origin):
visited_nodes = []
current_node = origin
starting_node = origin
while True:
# obtain the current node in the graph we want to investigate
adjacent_nodes = graph[current_node]
# find out whether all the adjacent nodes of current_node have been visited
if set(adjacent_nodes).issubset(set(visited_nodes)):
pass
else:
# returns the nodes that have not been visited
unvisited_nodes = set(adjacent_nodes).difference(set(visited_nodes))
for vertex in unvisited_nodes:
distance_from_starting_node = get_shortest_distance(table, vertex)
if distance_from_starting_node == INFINITY and current_node == starting_node:
# get the value (distance) of the edge between vertex and current_node
total_distance = get_distance(graph, vertex, current_node)
else:
# sum(distance from the starting node to current_node, distance between current_node and vertex)
total_distance = get_shortest_distance(table, current_node) + get_distance(graph, current_node, vertex)
# if total distance < the existing data in the shortest distance column in our table
if total_distance < distance_from_starting_node:
# update the row
set_shortest_distance(table, vertex, total_distance)
set_previous_node(table, vertex, current_node)
visited_nodes.append(current_node)
# If all nodes have been visited, exit the while loop.
if len(visited_nodes) == len(table.keys()):
break
# fetch the next node to visit
current_node = get_next_node(table, visited_nodes)
return current_node
# returns the value stored in the 0th index of the table, which
# stores the shortest distance from the starting node up to vertex
def get_shortest_distance(table, vertex):
shortest_distance = table[vertex][DISTANCE]
return shortest_distance
# finds the distance between any two nodes
def get_distance(graph, first_vertex, second_vertex):
return graph[first_vertex][second_vertex]
def set_shortest_distance(table, vertex, new_distance):
table[vertex][DISTANCE] = new_distance
# When we update the shortest distance of a node, we update its previous node
def set_previous_node(table, vertex, previous_node):
table[vertex][PREVIOUS_NODE] = previous_node
# finds the minimum value in the shortest distance column from the starting nodes using the table.
def get_next_node(table, visited_nodes):
unvisited_nodes = list(set(table.keys()).difference(set(visited_nodes)))
# assumed to be the smallest in the shortest distance column of table
assumed_min = table[unvisited_nodes[0]][DISTANCE]
min_vertex = unvisited_nodes[0]
for node in unvisited_nodes:
# If a lesser value is found, update the min_vertex
if table[node][DISTANCE] < assumed_min:
assumed_min = table[node][DISTANCE]
min_vertex = node
# returns min_vertex as the unvisited vertex or node with the smallest shortest distance from the source.
return min_vertex
# The adjacency list for the diagram and table:
# The nested dictionary holds the adjacent nodes and the distance.
graph = dict()
graph['A'] = {'B': 5, 'D': 9, 'E': 2}
graph['B'] = {'A': 5, 'C': 2}
graph['C'] = {'B': 2, 'D': 3}
graph['D'] = {'A': 9, 'F': 2, 'C': 3}
graph['E'] = {'A': 2, 'F': 3}
graph['F'] = {'E': 3, 'D': 2}
# To print the table
shortest_distance_table = find_shortest_path(graph, table, 'A')
for k in sorted(shortest_distance_table):
print("{} - {}".format(k, shortest_distance_table[k])) |
a41d39d67fcc8e3922a916d9acea42a69e5dbc90 | YashCK/Python_Basics | /String_Slices.py | 825 | 4.28125 | 4 | # String Index
# Python indexes the characters of a string, every index is associated with a unique character.
# For instance, the characters in the string ‘python’ have indices:
# The 0th index is used for the first character of a string. Try the following:
s = "Hello Python"
print(s) # prints whole string
print(s[0]) # prints "H"
print(s[1]) # prints "e"
# String Slicing
# Given a string s, the syntax for a slice is: s[ startIndex : pastIndex ]
print(s[0:8])
# The startIndex is the start index of the string. pastIndex is one past the end of the slice.
# If you omit the first index, the slice will start from the beginning. If you omit the last index, the slice will go to the end of the string. For instance:
print(s[:2]) # prints "He"
print(s[2:4]) # prints "ll"
print(s[6:]) # prints "Python"
|
37b6bfab93d848acc859149990719e002eee5d71 | thomas-vanderwal/Python_101 | /Section_2/time_module.py | 370 | 3.859375 | 4 | import time
#ctime function will convert a time in seconds since the epoch is a string representing local time
print(time.ctime())
print(time.ctime(1384112639))
#sleep function allows us to suspend execution of scripts a given number of seconds
for x in range(5):
time.sleep(2)
print('Slept for 2 seconds')
print(time.time())
print(time.ctime(time.time()))
|
b70c5290c73dc3cf2562a5db81a8d0be05956997 | NikeSmitt/python_main_course | /hw1/task3.py | 2,142 | 3.875 | 4 | # 3. Узнайте у пользователя число n. Найдите сумму чисел n + nn + nnn.
# Например, пользователь ввёл число 3. Считаем 3 + 33 + 333 = 369
def task3_amend(user_input):
value = int(user_input)
result = 0
candidate = 0
for n in range(3):
candidate *= 10
candidate += value
result += candidate
return result
# можно просто форматированием строки
# return f"{value + (value*10 + value) + (value * 100 + (value*10 + value))}"
def task3(user_input):
value = int(user_input)
sum_result = 0
candidate = 0 # элемент ряда (3,33,333)
for i in range(value):
# увеличиваем разряд (т.е 3 -> 30)
candidate *= 10
# добавляется единицы (т.е. 30 -> 33)
candidate += value
sum_result += candidate
return sum_result
# для себя покрыл тестами
def test_task3():
# тестируем до 9 включительно
# формируем строки для тестов потом копируем из консоли
# for value in range(1,10):
# s = f"{value}"
# for i in range(2,value+1):
# s += ' + '
# s += f'{value}' * i
# print(s)
tests_results = [0,
1,
2 + 22,
3 + 33 + 333,
4 + 44 + 444 + 4444,
5 + 55 + 555 + 5555 + 55555,
6 + 66 + 666 + 6666 + 66666 + 666666,
7 + 77 + 777 + 7777 + 77777 + 777777 + 7777777,
8 + 88 + 888 + 8888 + 88888 + 888888 + 8888888 + 88888888,
9 + 99 + 999 + 9999 + 99999 + 999999 + 9999999 + 99999999 + 999999999]
for i, test in enumerate(tests_results):
if task3(str(i)) != test:
print(f'Test {i} failed')
return
print('Tests OK!')
if __name__ == '__main__':
# test_task3()
# print(task3('3'))
print(task3_amend('3'))
|
1b42a099f5cd26c5183ba169f363c1de74242702 | Lei-Tin/OnlineCourses | /edX/MIT 6.00.1x Materials/n^c and c^n.py | 237 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 14 21:11:55 2021
@author: ray-h
"""
from time import sleep
c = 2
n = 0
while True:
n += 1
print('c^n = ' + str(c**n))
print('n^c = ' + str(n**c))
sleep(1) |
ba0f3a2c609a3700739962f9342112f11bd2eba1 | glredig/bioinformatics | /gc_count.py | 696 | 3.65625 | 4 | def gc_count():
"""Basic GC Count function """
a = 0
t = 0
g = 0
c = 0
type = raw_input("Please enter the data entry type (1=txt file, 2=direct entry): ")
if type == "1":
filename = raw_input("Please enter the path to the txt file: ")
file = open(filename, "r")
dna = file.read()
else:
dna = raw_input("Please enter the DNA string: ")
dna = list(dna)
for i in range(len(dna)):
if dna[i] == "A":
a += 1
elif dna[i] == "T":
t += 1
elif dna[i] == "G":
g += 1
elif dna[i] == "C":
c += 1
else:
print "Invalid character, %s" % (dna[i])
if type == "1":
file.close()
print "A: %s, T: %s, G: %s, C: %s" % (a, t, g, c)
return a, t, g, c
gc_count()
|
c8e33907b8a4cc5f92122e8f36e54c0827e71660 | amittewari31/Python | /Web Development/Python/Regular expression.py | 985 | 3.78125 | 4 | import re
patterns = ['term1', 'term2']
text = 'this is the string with term1, and not the other'
for pattern in patterns:
print('I am searching for ', pattern)
if re.search(pattern, text):
print('MATCH')
else:
print('DID NOT MATCH')
# ===============================================================================================
# ===============================================================================================
text = 'test me'
match = re.search('test', text)
print(match)
print(match.start())
print(match.end())
# ===============================================================================================
split_term = '@'
mail = 'user@gmail.com'
match = re.split(split_term, mail)
print(match)
# ===============================================================================================
print(re.findall('match', 'i am tested for match string here'))
print(re.findall('match', 'i am tested for match string here, match me')) |
63ae812001a1cc2884be9d2aa936baed893b16df | SimeonTsvetanov/Coding-Lessons | /SoftUni Lessons/Python Development/Python Fundamentals June 2019/Problems and Files/12. EXAM PREPARATION/Exam Preparation 1/01. Sino the Walker.py | 2,415 | 4.40625 | 4 | """
Basics OOP Principles
Check your solution: https://judge.softuni.bg/Contests/Practice/Index/967#0
SUPyF Exam Preparation 1 - 01. Sino the Walker
Problem:
Sino is one of those people that lives in SoftUni. He leaves every now and then,
but when he leaves he always takes a different route, so he needs to know how much time it will take for him to go home.
Your job is to help him with the calculations.
You will receive the time that Sino leaves SoftUni, the steps taken and time for each step, in seconds.
You need to print the exact time that he will arrive at home in the format specified.
Input / Constraints
• The first line will be the time Sino leaves SoftUni in the following format: HH:mm:ss
• The second line will contain the number of steps that he needs to walk to his home.
This number will be an integer in range [0…2,147,483,647]
• On the final line you will receive the time in seconds for each step.
This number will be an integer in range [0…2,147,483,647]
Output
• Print the time of arrival at home in the following format:
o Time Arrival: {hours}:{minutes}:{seconds}
• If hours, minutes or seconds are a single digit number, add a zero in front.
• If, for example, hours are equal to zero, print a 00 in their place. The same is true for minutes or seconds.
• Time of day starts at 00:00:00 and ends at 23:59:59
Examples:
Input:
12:30:30
90
1
Output:
Time Arrival: 12:32:00
Input:
23:49:13
5424
2
Output:
Time Arrival: 02:50:01
"""
from datetime import datetime, timedelta
start_time = datetime.strptime(input(), "%H:%M:%S")
added_time = timedelta(seconds=(float(input()) * float(input())))
end_time = ((start_time + added_time).time())
print(f"Time Arrival: {end_time}")
# Another Option from different person, as mine will generate a problem with larger int's then the sys.max size:
"""
def convert(seconds):
seconds = seconds % (24 * 3600)
hour = seconds // 3600
seconds %= 3600
minutes = seconds // 60
seconds %= 60
return "%02d:%02d:%02d" % (hour, minutes, seconds)
if __name__ == '__main__':
time = input()
steps = int(input())
seconds_step = int(input())
h, m, s = time.split(':')
sec = (int(h)*3600) + (int(m)*60) + int(s)
sec_home = sec + (steps*seconds_step)
print(f'Time Arrival: {convert(sec_home)}')
"""
|
54a343d7282facc42d64bfcc73f301ddbac9480a | rafaelperazzo/programacao-web | /moodledata/vpl_data/59/usersdata/149/40379/submittedfiles/testes.py | 97 | 3.796875 | 4 | # -*- coding: utf-8 -*-
import math
i=int(input('digite i:'))
while i<10:
print(i)
i=i+1
|
92f699c3be6b158af1c30931e0303d71614fc715 | stormchasingg/leetcode-desktop | /fibonacci.py | 601 | 3.546875 | 4 | # generator for fibonacci & Yanghui triangles
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
return 'done'
def triangles():
n = 0
yield [1]
prev = [1, 1]
yield prev
while n < 100:
res = [1] * (n + 3)
for i in range(len(res)):
if i == 0 or i == len(res) - 1:
res[i] = 1
else:
res[i] = prev[i-1] + prev[i]
prev = res
yield res
n = n + 1
return 'done'
def triangles1():
res = [1]
while True:
yield res
res = [1] + [res[i-1] + res[i] for i in range(1, len(res))] + [1]
|
58c5c1784498c9b1c805cc5cba1a601ba9d1bc0c | kyoder17/pythonIQT | /lab3e_fibonacci.py | 616 | 4.03125 | 4 | """
CPT Klye Yoder
Lab3e Fibonacci
07 Sept 2018
"""
def fib(c):
if c<=1:
return c
else:
return fib(c-1)+fib(c-2)
n=raw_input("Enter a number for Fibonacci ")
while(True):
try:
n=int(n)
break
except ValueError:
n=raw_input("Please enter an integer: ")
print "\nIterative"
a=0
b=1
if n==0:
print n
elif n==1:
print n
else:
print 0
print 1
for i in range(n-1):
temp=a+b
a=b
b=temp
print temp
print "\nRecursive"
while(True):
for i in range(n+1):
print(fib(i))
break
|
3c2f853503beabbdcd8290ece996e804f6e0fb48 | fqx9904/Python_Game_Autoplay_Strategy--CSC148 | /Labs/lab2/grade.py | 3,614 | 3.953125 | 4 | """
grade module
"""
from typing import Any
class GradeEntry:
"""Represent a general entry with student grade information.
course_id - a course iddentifier in which the grade earned
weight - credit weight of the course
grade - no value until we know whether numeric or letter value is used
"""
course_id: str
course_weight: float
grade: None
def __init__(self, course_id: str, weight: float, grade=None) -> None:
"""Initialize a new grade entry.
"""
self.course_id = course_id
self.grade = grade
self.weight = weight
def __eq__(self, other: Any) -> bool:
"""Return whether self is equivalent to other.
"""
return type(self) == type(other) and self.course_id == other.course_id and self.weight == other.weight and \
self.grade == other.grade
def __str__(self) -> str:
"""Return a string representation of a grade entry.
"""
return "{}: Weight:{}, Grade:{}".format(self.course_id, self.weight, self.grade)
def generate_points(self) -> float:
"""return a float numebr which is the grade earned of the course.
"""
raise NotImplementedError("Subclass needed")
class LetterGradeEntry(GradeEntry):
"""Represent a grade entry with letter grade.
letter_grade - a grade represented by {A, B, C, D, E, F} and suffix {+, -}
"""
letter_grade: str
table = {'A+': 4.0, 'A': 4.0, 'A-': 3.7, 'B+': 3.3, 'B': 3.0, 'B-': 2.7, 'C+': 2.3, 'C': 2.0, 'C-': 1.7,
'D+': 1.3, 'D': 1.0, 'D-': 0.7, 'F': 0.0}
def __init__(self, course_id: str, weight: float, grade: str) -> None:
"""Initialize a new letter grade entry.
"""
GradeEntry.__init__(self, course_id, weight, grade)
self.grade = grade
def generate_points(self) -> float:
"""return a float numebr which is the grade earned of the course.
"""
return self.table[self.grade]
class NumericGradeEntry(GradeEntry):
"""Represent a grade entry with letter grade.
num_grade - a grade represented by {A, B, C, D, E, F} and suffix {+, -}
"""
num_grade: int
table = {4.0: [85, 100], 3.7: [80, 84], 3.3: [77, 79], 3.0: [73, 76], 2.7: [70, 72], 2.3: [67, 69], 2.0: [63, 66],
1.7: [60, 62], 1.3: [57, 59], 1.0: [53, 56], 0.7: [50, 52]}
def __init__(self, course_id: str, weight: float, grade: int) -> None:
"""Initialize a new numeric grade entry.
"""
GradeEntry.__init__(self, course_id, weight, grade)
self.grade = round(grade)
def generate_points(self) -> float:
"""return a float numebr which is the grade earned of the course.
"""
if self.grade < 50:
return 0.0
for p in self.table:
if self.grade in range(self.table[p][0], self.table[p][1] + 1):
return p
if __name__ == '__main__':
from grade import LetterGradeEntry, NumericGradeEntry
grades = [NumericGradeEntry('csc148', 0.5, 87), NumericGradeEntry('mat137', 1.0, 76),
LetterGradeEntry('his450', 0.5, 'B+')]
for g in grades:
# Use appropriate ??? methods or attributes of g in format
print('Weight: {}, grade: {}, points: {}'.format(g.weight, g.grade, g.generate_points()))
# Use methods or attributes of g to compute weight times points
total = sum([g.weight * g.generate_points() for g in grades]) # using each g in grades
# sum up the credits
total_weight = sum([g.weight for g in grades])
print('GPA = {}'.format(total / total_weight))
|
bfb7f6bb209dcf90a2dc2c320b48f462d3de14b4 | quocphan95/np-trend-detection | /activations.py | 649 | 4.28125 | 4 | import numpy as np
"""
Activation functions
Each class contains 2 class function:
calc: calculate the output from the input
derivative: calculate the derivative of the output w.r.t the input
"""
class Relu:
@classmethod
def calc(x):
return (x>0).astype(np.int32) * x
@classmethod
def derivative(x):
return (x>0).astype(np.int32)
class Tanh:
@classmethod
def calc(x):
return np.tanh(x)
@classmethod
def derivative(x):
return (1 - Tanh.calc(x)**2)
if __name__ == "__main__":
x = np.random.randn(3,3)
y = relu(x)
print(y)
x = relu_derivative(y)
print(x)
|
ee96c539fdaad60c066a17cf98d8e3beb6c3ce3a | vamshireddy08/python-practice-programs | /build_in_functions.py | 1,001 | 3.625 | 4 | def count_match_index(l):
inc=0
for count,val in enumerate(l):
if count==val:
inc=inc+1
print inc
count_match_index([0,2,2,1,5,5,6,10])
def d_list(l):
d={}
for count,ele in enumerate(l):
d[ele]=count
print d
d_list(['a','b','c'])
def concatenate(l1,l2,connector):
con=[]
ans=[]
con.append(connector)
l=len(l1)
con=con*l
list= zip(l1,con,l2)
for ele in list:
ans.append(''.join(ele))
print ans
concatenate(['A','B'],['a','b'],'-')
def word_lengths(phrase):
list=phrase.split(' ')
lengths= map(lambda word:len(word) , list)
print lengths
word_lengths("how long are the words in this phrase")
def digits_to_num(digits):
print reduce(lambda x,y:x*10 +y ,digits)
digits_to_num([3,4,3,2,1])
def filter_words(word_list,letter):
print filter(lambda x: x[0]==letter ,word_list)
l=['hello','are','cat','hi','dog','ham','go','to','heart' ]
filter_words(l,'h')
|
948f1fe483d51b3cf21fb95c33ee6b11e40511f6 | xyzhangaa/ltsolution | /MultiplyStrings.py | 638 | 3.703125 | 4 | ###Given two numbers represented as strings, return multiplication of the numbers as a string.
###Note: The numbers can be arbitrarily large and are non-negative.
# Time: O(m * n)
# Space: O(m + n)
def MultiplyStrings(A,B):
if A == '0' or B=='0':
return '0'
A = A[::-1]
B = B[::-1]
arr = [0 for _ in range(len(A)+len(B))]
for i in range(len(A)):
for j in range(len(B)):
arr[i+j] += int(A[i])*int(B[j])
res = []
for i in range(len(arr)):
carry = arr[i]//10
digit = arr[i]%10
if i < len(arr)-1:
arr[i+1] += carry
res.insert(0,str(digit))
while res[0] == '0' and len(res)>1:
del res[0]
return ''.join(res)
|
377e320020ac0816d64a13bcbcb1900ef73710ae | jinammaheta/python | /practicals/11.py | 338 | 3.5 | 4 | import math
a,b,c=map(int,input("Enter Coefficients a,b,c\n").split())
d=(b*b)-(4*a*c)
if d==0:
print("Both roots are same")
r=-b/2*a
print("Root is:r={}".format(r))
if d<0:
print("No Roots")
if d>0:
r1=(-b+math.sqrt(d))/2*a
r2=(-b-math.sqrt(d))/2*a
print("Roots are:r1={} , r2={}".format(r1,r2))
|
8597d1f6c96c30fef134e75566e112b259a33157 | lettucemaster666/Python3_Bootcamp | /control_flow.py | 3,178 | 4.40625 | 4 | """
Purpose
--------
Introduction to Control Flow
Summary
-------
Introduces if, elif, else statements to control conditions of code.
Operators will be introduced in evaluating true or false of the control flow statements.
Structure of condition statement
--------------------------------
if something_is_true:
execute code
if something_is_false:
code will not executute
elif something_else_is_true: # You can specify multiple elif statements between if and else
code will execute
else:
code will not execute because elif is executed
if something_is_false:
code will not executute
elif something_else_is_false: # You can specify multiple elif statements between if and else
code will not execute
else:
code will execute
Types of operators
------------------
[+] or
[+] == (equal)
[+] != (not equal)
[+] and
[+] not
[+] <, >, <=, >= (comparisons)
Other
-----
[+] in has 2 purpose:
1.Used to check if a value is present is a sequence (list, range, string, dictionary, etc).
2.Used in iterate through a sequence in a for loop.
Exercises
---------
Exercises for "or"
[+] True or True #Evaluates to True
[+] True or False #Evaluates to True
[+] False or False #Evaluates to False
[+] 1 < 2 or 3 < 1 #Evaluates to True
[+] 3 < 1 or 1 > 6 #Evaluates to False
[+] 1 == 1 or 1 < 2 #Evaluates to True
Exercises for "==":
[+] 1 == 1 #Evaluates to True
[+] "hi" == "hi" #Evaluates to True
Exercises for "!=":
[+] 1 != 1 #Evaluates to False
[+] 1 != 2 #Evaluates to True
[+] "hi" != "ho" #Evaluates to True
Excersises for "and":
[+] 1 == 1 and 2 > 1 #Evaluates to True
[+] 1 == 1 and 2 < 1 #Evaluates to False
[+] "m" in "meow" and True #Evaluates to True
Excerises for "not":
[+] "m" not in "dog" #Evaluates to True
[+] 2 not in [1,2,3,4] #Evaluates to False
Excerises for "<, >, <=, >=":
[+] 3 < 2 #Evaluates to False
[+] 2 > 1 #Evaluates to True
[+] 2 <= 2 #Evaluates to True
[+] 1 >= 0 #Evaluates to True
"""
#Example 1: ice cream flavours
#This example prints out "My ice cream is vanilla flavoured. Creamy delicious!".
my_flavour = "vanilla"
if my_flavour == "chocolate":
print("My ice cream is " + my_flavour + " flavoured. Yum and delicious!")
elif my_flavour == "strawberry":
print("My ice cream is " + my_flavour + " flavoured. Reddy delicious!")
elif my_flavour == "vanilla":
print("My ice cream is " + my_flavour + " flavoured. Creamy delicious!")
else:
print("I will just eat the cone then")
#Example 2: simple math
#This example prints out "0 < 2 is True".
if 0 > 2:
print("0 > 2 is False")
elif 0 < 2:
print("0 < 2 is True")
else:
print("There is no correct answer")
#Example 3: a house in neighbourhood
#This example prints "Like son like father!".
family_1 = ["father", "mother", "son", "daughter"]
if "doggo" in family_1:
print("Who is a good boi?")
elif "son" in family_1:
print("Like son like father!")
else:
print("Happy fam")
|
f8cd435bb4eb1f693117ddec64c25f1d41f744f4 | rm-hull/charlotte | /sweetie.py | 464 | 3.515625 | 4 | #!/usr/bin/env python
import wiringPy
import time
wiringPy.setup()
for pin in range(0,8):
wiringPy.pin_mode(pin, 1)
wiringPy.digital_write_byte(255)
print "whats your name?"
name = raw_input()
print "hello " + name
doubles = [1,2,4,8,16,32,64,128]
snooze = 0.1
while (True):
for no in doubles:
wiringPy.digital_write_byte(no)
time.sleep(snooze)
doubles.reverse()
#for no in range (0,256):
# wiringPy.digital_write_byte(no)
# time.sleep(0.0625)
|
0e82f387cb38568a32084f8236f291119d6274e9 | aayush-bhardwaj/CodeTo500 | /Code001_SwapCase.py | 1,139 | 4.0625 | 4 | #DAY04_21DEC2016_Code001.py
'''
NOTES :
1. help(str.istitle()) - The terminal help opens up
2. istitle() - Check if a string is camel case
3. upper() - convert to upper case
4. lower() - convert to lower case
5. isupper() - check if a string is in uppercase
6. islower() - check if a string is in lowercase
7. split a string into an array
word = "aayush bhardwaj"
list = [y for y in word.split(" ")]
list = ["aayush","bhardwaj"]
8. split a string into a character array
word = "aayush"
list = list(word)
list = ['a','a','y','u','s','h']
'''
#QUES
'''
You are given a string . Your task is to swap cases. In other words, convert all lowercase letters to uppercase letters and vice versa.
eg.
aayush BHARDWAJ
AAYUSH bhardwaj
URL : https://www.hackerrank.com/challenges/swap-case
'''
def swap_case(s):
l = list(s)
res = ""
for item in l:
if(item.isupper() == True):
res += item.lower()
elif(item.islower() == True):
res += item.upper()
else:
res += item
return res
if __name__ == '__main__':
s = raw_input()
result = swap_case(s)
print result |
bb981155f8617643edcc6cb37e86705390ff34ae | mfisher29/innovators_class | /Class6/application1/lesson006.py | 7,497 | 3.9375 | 4 | print("Going through the data structure....")
import json
json_file = 'death.data'
contents = open(json_file,'r').read()
json_data = json.loads(contents)
columns = json_data['meta']['view']['columns']
column_names = [col['name'] for col in columns]
data_columns={col["name"]:col for col in columns if col.has_key("tableColumnId")}
data = {}
for d in json_data['data']:
for k,v in zip(column_names,d):
default_key = data.get(k,[])
default_key.extend([v])
data[k] = default_key
prompt = """
Let's re-use the previous analysis by re-producing both data_columns and data.
data_columns brings in metadata information. Data brings in the column-based
version of the data. We can still loop through json_data['data'] if we want to
access rows.
"""
raw_input(prompt)
for indice, col in zip(range(0,len(column_names)),column_names):
print(indice, col)
for d in json_data['data'][0:51]:
print(d[8:])
prompt = """
Before we get deeper into the analysis, we should have a quick overview of the data.
A quick way of accomplishing this is to print the columns (with their positional number)
and 50 or so rows (data points). We can start making conjecture this way!
"""
raw_input(prompt)
data = {}
for d in json_data['data']:
for k,v in zip(column_names[8:],d[8:]):
default_key = data.get(k,[])
default_key.extend([v])
data[k] = default_key
prompt = """
Based on the previous overview, we realize that the first 8 columns are not useful.
We decide to limit the data to the last 6 columns for further analysis (conveniently
stored in data).
"""
raw_input(prompt)
unique_values = {k:list(set(v)) for k,v in data.iteritems()}
for k,v in unique_values.iteritems():
print(k, len(v))
prompt = """
Another technique we can use to get a sense of the data is to go through each column
and list how many unique set of values exist. Typically data can be divided into
two categories: descriptions and metrics. Descriptions are "human" categorization
of data. An example would be states (50 categories). Metrics on the other hand
are based on measurements or actual counts. The variation should be larger!
"""
raw_input(prompt)
for k,v in unique_values.iteritems():
if len(v) < 100:
print
print("*****************")
print("*. " + k )
print("*****************")
v.sort()
for l in v:
print l
print
prompt = """
Let's look at columns with less than 100 unique values. These are most likely categories.
They also fit the screen better and can be seen at a glance.
"""
raw_input(prompt)
print
print("Let's pick 3 valeus for State, Cause and Year....")
print
print("State:")
print("United States")
print
print("Cause Name:")
print("All Causes")
print
print("Year:")
print("2015")
print
for d in json_data['data']:
row = d[8:]
year, cause, state, deaths = row[0],row[2],row[3], row[-2]
if (year == "2015" and cause == "All Causes" and state == "United States"):
print("How many deaths in total in the US:")
print(deaths)
print("We can also analyze this by year!")
raw_input("continue...")
print
print("Let's define some filters....")
print
print("State:")
print("United States")
print
print("Cause Name:")
print("All Causes")
print
print("By Year:")
total = 0
for d in json_data['data']:
row = d[8:]
year, cause, state, deaths = row[0], row[2],row[3], row[-2]
if (cause == "All Causes" and state == "United States"):
print(str(year) + ": " + str(deaths))
total += int(deaths)
print
print("Yearly summaries:")
print("Total above for 17 years is: %s" % total)
print("Average is: " + str(total/17))
raw_input("continue...")
print
year_total_deaths={}
cancer_total_deaths={}
for d in json_data['data']:
row = d[8:]
year, cause, state, deaths = row[0], row[2],row[3], row[-2]
if (cause == "All Causes" and state == "United States"):
year_total_deaths[year] = deaths
if (cause == "Cancer" and state == "United States"):
cancer_total_deaths[year] = deaths
print("year totals by year:")
print(year_total_deaths)
print("cancer totals by year:")
print(cancer_total_deaths)
print
prompt = """
Let's do something a bit more interesting! Wouldn't it be cool
to find out what percent of deaths are cancer related!
To do this, we first need to get the total deaths by year.
Then, we need to get total cancer deaths by years.
We can than divide: "cancer deaths" / "total deaths"
Before we can do that, we need to test some assumptions!
"""
raw_input(prompt)
unique_years = set(year_total_deaths.keys())
unique_cancers = set(cancer_total_deaths.keys())
print
if(len(unique_cancers.symmetric_difference(unique_years)) == 0):
print("No")
else:
print("Yes")
prompt = """
We need to make sure that every year in death totals has a data
point in cancer deaths. If one of the years is missing, we
will have to handle the "bad" data. Luckily, the data is complete.
Every year is present in both total deaths and cancer deaths!
"""
raw_input(prompt)
cancer_table = []
for year in unique_years:
total_death = year_total_deaths[year]
cancer_death = cancer_total_deaths[year]
year, cancer_death, total_death= int(year), int(cancer_death), int(total_death)
cancer_rate = round(100 * cancer_death / float(total_death),2)
cancer_table.append([year, cancer_death,total_death,cancer_rate])
cancer_table.sort(key=lambda x: x[0])
print
print ("year,cancer,total,percent".split(","))
for row in cancer_table:
print(row)
prompt = """
We finally produce summarized output for cancer death rates.
The final "table" called cancer table has 4 columns:
year
total deaths
cancer deaths
cancer rate
We can now ask questions about cancer rate by year!
"""
raw_input(prompt)
cancer_table.append([1998,500000,2500000,20.00])
cancer_table.append([2018,600000,2700000,22.22])
json.dumps(cancer_table,indent=4)
cancer_table.sort(key=lambda x: x[0])
print
print ("year,cancer,total,percent".split(","))
for row in cancer_table:
print(row)
prompt = """
Now a good question? What if we wanted to add
two new data points we just found out about.
Let's say data came in for 1998 and 2018:
[1998,500000,2500000,20.00]
[2018,600000,2700000,22.22]
We can just append this to the cancer table
and quickly filter by year!
"""
raw_input(prompt)
tree_top = {}
tree_top["yearly"] = {}
tree_top["yearly"]["data"] = cancer_table
print(json.dumps(tree_top, indent=4))
prompt = """
Let's create our own json file. Let's call
it cancer.json and have it contain our
cancer table as data points.
The first step is to create a top-level dict.
We can than add dictionaries to it to describe
the hierarcy. In the above case, one hierarchy
is:
"yearly" => "data" => <cancer table>
Let's add some extra information!
"""
raw_input(prompt)
meta = ["year","cancer_death","total_death","percent"]
tree_top["yearly"]["meta"] = meta
print(json.dumps(tree_top, indent=4))
prompt = """
One thing that might be valuable is metadata.
Let's put the column names in meta.
"yearly" => "meta" => <column names>
I think this makes for a great cancer.json document
that can be used by us or others.
"""
raw_input(prompt)
to_json = open('cancer.json','w')
to_json.write(json.dumps(tree_top, indent=4))
to_json.close()
from_json = open('cancer.json','r')
json_contents = from_json.read()
print(json_contents)
prompt = """
Let's finally write the file to disk for more
permanent storage (disk instead of memory).
Let's call it cancer.json.
To confirm this, we can read the contents
of the file and print them to the screen.
"""
raw_input(prompt)
|
e7cfdb32b49e498d4a12596555801b6ef78f54f5 | sunjiebin/s12 | /week7/02类组合使用.py | 2,010 | 3.71875 | 4 | #!/usr/bin/env python
# Python version: python3
# Auther: sunjb
'''我们可以直接在构造函数里面将一个实例化的对象传进去,
这样就相当于实现了类的继承,这对于多个参数不同的函数继承
是很有用的'''
class School(object):
def __init__(self,name,addr):
self.name=name
self.addr=addr
self.students=[]
self.teacher=[]
self.staffs=[]
def enroll(self,stu_obj):
print('为学员%s办理入学手续'%stu_obj.name)
self.students.append(stu_obj)
def hire(self,staff_obj):
print('%s机构为老师%s办理入职手续'%(self.name,staff_obj.name))
self.staffs.append(staff_obj)
class SchoolMember(object):
def __init__(self,name,age,sex):
self.name=name
self.age=age
self.sex=sex
def tell(self):
pass
class Teacher(SchoolMember):
'''这里我们将school_obj传进来'''
def __init__(self,name,age,sex,salary,course,school_obj):
#SchoolMember.__init__(name,age,sex)
'''比如在Teacher类里面,我们既想把SchoolMember继承,又想继承
School,而SchoolMember和School两者的参数有不一样,那么这时候
用super就没法完成两个类的继承了,这时候就可以用将实例化的类
传进来的方式解决'''
super(Teacher,self).__init__(name,age,sex)
''''定义类变量school'''
self.school=school_obj
self.salary=salary
self.course=course
def tell(self):
print('''
----info of teacher----
name:%s age:%s sex:%s salary:%s course:%s
'''%(self.name,self.age,self.sex,self.salary,self.course))
s1=School('hafool','beijing')
'''在实例化Teacher时,将s1传递进去,s1是一个已经实例化的School'''
t1=Teacher('sun',18,'F',2000,'linux',s1)
t1.tell()
s1.hire(t1)
'''这时候,就可以通过t1来调用School类里面的函数了,相当于实现了类的继承'''
t1.school.enroll(t1)
#s1.enroll(t1) |
69b0d44bc5e428139e13160dc4721e62a780c5d8 | tafarib1/python-caveiratech | /aula5.py | 228 | 3.921875 | 4 | numero = input('coloque o numero de pessoas da festa:')
pessoas = 0
lista = []
while pessoas <= int(numero):
pessoa = input('coloque o nome de quem vai: ')
pessoas += 1
lista.append(pessoa)
for i in lista: print(i) |
47e8e9dde6d1aa16abcf9fe5e569e446bb010568 | sofiadurkan1/ITF-Fundamentals | /python/class_notes/2021_05_24_FILES/reading_files.py | 2,279 | 3.953125 | 4 | """
import os
os.system("cls")
my_file = open("first_file.txt") # this syntax opens a 'txt' file
print(type(my_file))
print()
print(my_file)
my_file.close()
"""
"""
import os
os.system("cls")
my_fie = open("fishes.txt", 'r')
print(my_fie.read()) # displays the entire text content
my_fie.close()
"""
"""
my_file = open("fishes.txt", 'r')
print(my_file.read(33))
print(my_file.read(25))
print()
my_file.close()
"""
"""
my_file = open("fishes.txt", 'r')
print(my_file.read(3))
print()
print(my_file.read(5))
print()
my_file.seek(0)
print(my_file.read(8))
my_file.close()
"""
"""
my_file = open("fishes.txt", 'r')
print(my_file.read(6))
print("cursor is at", my_file.tell())
print()
print(my_file.read(7))
print("cursor is at", my_file.tell())
print()
my_file.seek(0)
print("cursor is at", my_file.tell())
print()
print(my_file.read(8))
print("cursor is at", my_file.tell())
print()
current_position = my_file.tell()
print("this is the result of current position of cursor : ", current_position)
print()
new_position = current_position - 3
print(my_file.seek(new_position))
print("cursor is at, i mean 3 letter before", my_file.tell())
my_file.close()
"""
"""
my_file = open("rumi.txt", 'r')
print(my_file.read())
my_file.close()
"""
"""
my_file = open("rumi.txt", 'r')
print(my_file.read(35))
print(my_file.read(13))
print(my_file.tell())
my_file.seek(15)
print(my_file.read(20))
my_file.close()
"""
"""
sea = open("fishes.txt", 'r')
print(sea.readline()) # displays the first line of the text
print(sea.readline()) # displays the second line
print(sea.readline()) # each time it goes to the new line
sea.close()
"""
"""
sea = open("fishes.txt", 'r')
print(sea.readline(13))
print(sea.readline(13))
print(sea.readline(13))
print(sea.readline(13))
sea.close()
"""
"""
sea = open("fishes.txt", 'r')
print(sea.readlines())
sea.close()
"""
"""
sea = open("fishes.txt", 'r')
print(sea.readline())
print(sea.readlines())
sea.close()
"""
"""
sea = open("fishes.txt", 'r')
print(type(sea.readlines()))
sea.close()
"""
"""
sea = open("fishes.txt", 'r')
for line in sea:
print(line)
sea.close()
"""
|
280a6e7ba31047f5cd1eab441fed2f3a313681c4 | DevanshiPatel12/PythonAssignmentCA2020 | /Task-6/Qn-2.py | 517 | 4.34375 | 4 | # Define a class named Shape and its subclass Square.
# The Square class has an init function which takes a length as argument.
# Both classes have an area function which can print the area of the shape where Shape’s area is 0 by default.
class Shape:
Area = 0
def Area(self):
return 0
class Square(Shape):
def __init__(self, Length):
self.Length = Length
def Area(self):
Area = self.Length * self.Length
print("Area of Square is : ", Area)
S1 = Square(5)
S1.Area() |
c7e09631a54d836401b15228f1312e388fb0d86b | anishmarathe007/Assignment | /test_palindrome.py | 713 | 3.765625 | 4 | import unittest
from palindrome import isPalindrome, reverseString
class TestPalindrome(unittest.TestCase):
def test_for_revFunction(self):
self.assertEqual(reverseString('anish'),'hsina')
self.assertEqual(reverseString('1'),'1')
self.assertEqual(reverseString('12321'),'12321')
self.assertEqual(reverseString('aba'),'aba')
def test_for_isPalindrome(self):
self.assertEqual(isPalindrome('abc'),0)
self.assertEqual(isPalindrome('abcba'),1)
self.assertEqual(isPalindrome('123454321'),1)
self.assertEqual(isPalindrome('-1'),0)
self.assertEqual(isPalindrome('0'),1)
if __name__ == '__main__':
unittest.main()
|
6a7a9a5315bd6ea7387985f7a1de98f6febe6a8a | muhammad-masood-ur-rehman/Skillrack | /Python Programs/zigzag-pattern-start-with-base-program-in-python.py | 946 | 4 | 4 | ZigZag Pattern - Start with Base Program in Python
ZigZag Pattern - Start with Base: Two positive integer values X and Y are passed as input to the program. The program must print the output based on X and Y values as shown in the Example Input/Output section.
Boundary Condition(s):
1 <= X, Y <= 1000
Input Format:
The first line contains the value of X and Y separated by a space.
Output Format:
The X lines contain the desired pattern.
Example Input/Output 1:
Input:
5 11
Output:
11 12 13 14 15
20 19 18 17 16
21 22 23 24 25
30 29 28 27 26
31 32 33 34 35
Example Input/Output 2:
Input:
6 12
Output:
12 13 14 15 16 17
23 22 21 20 19 18
24 25 26 27 28 29
35 34 33 32 31 30
36 37 38 39 40 41
47 46 45 44 43 42
a,b=map(int,input().split())
for i in range(1,a+1):
if i%2!=0:
for j in range(1,a+1):print(b,end=' ');b+=1
else:
p=[]
for j in range(1,a+1):p.append(b);b+=1
print(*p[::-1],end=' ')
print()
|
0b297be71b7e9b9e721445781bf984d35faaff68 | Krokette29/LeetCode | /Python/4. Median of Two Sorted Arrays.py | 4,176 | 4.15625 | 4 | class Solution:
"""
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
"""
def findMedianSortedArrays(self, nums1: [int], nums2: [int]) -> float:
"""
Using sorted() in Python.
"""
nums = nums1 + nums2
nums = sorted(nums)
if len(nums) % 2 == 1:
return nums[(len(nums) + 1) // 2 - 1]
else:
return (nums[len(nums) // 2] + nums[len(nums) // 2 - 1]) / 2
def findMedianSortedArrays2(self, nums1: [int], nums2: [int]) -> float:
"""
Create a sorted array by adding the minimum of each list.
Time: O(m+n)
Space: O(m+n)
"""
# create a sorted array
sorted_array = []
while nums1 or nums2:
if not nums1:
sorted_array.append(nums2[0])
del nums2[0]
elif not nums2:
sorted_array.append(nums1[0])
del nums1[0]
else:
if nums1[0] < nums2[0]:
sorted_array.append(nums1[0])
del nums1[0]
else:
sorted_array.append(nums2[0])
del nums2[0]
# return the median
if len(sorted_array) % 2 == 1:
return sorted_array[len(sorted_array) // 2]
else:
return (sorted_array[len(sorted_array) // 2 - 1] + sorted_array[len(sorted_array) // 2]) / 2
def solution1(self, nums1: [int], nums2: [int]) -> float:
"""
Binary Search
Time: O(log(min(m+n)))
Space: O(1)
"""
m, n = len(nums1), len(nums2)
# otherwise taking half of the array will exceed the length of the other array
if m > n:
m, n, nums1, nums2 = n, m, nums2, nums1
i_min, i_max = 0, len(nums1)
half_length = (m + n) // 2
# loop until two pointers be equal (in fact i_min will not greater than i_max)
while i_min <= i_max:
# update i_middle and j_middle
i_middle = (i_min + i_max) // 2
j_middle = half_length - i_middle
# if i_middle = 0 means all numbers in nums1 belong to the right part, no need for updating middle pointers
if i_middle > 0 and nums1[i_middle - 1] > nums2[j_middle]:
i_max = i_middle - 1
# if i_middle = m means all numbers in nums1 belong to the left part, no need for updating middle pointers
elif i_middle < m and nums1[i_middle] < nums2[j_middle - 1]:
i_min = i_middle + 1
else:
# first calculate right_min
# because the length of the right part could be 1 more thant left part, then just return right_min
# be careful about the boundary cases (i_middle or j_middle on the rightmost position)
if i_middle == m:
right_min = nums2[j_middle]
elif j_middle == n:
right_min = nums1[i_middle]
else:
right_min = min(nums1[i_middle], nums2[j_middle])
if (m + n) % 2 == 1:
return right_min
# if (m + n) % 2 == 0, then we need also left_max
# also be careful about the two boundary cases
if i_middle == 0:
left_max = nums2[j_middle - 1]
elif j_middle == 0:
left_max = nums1[i_middle - 1]
else:
left_max = max(nums1[i_middle - 1], nums2[j_middle - 1])
return (left_max + right_min) / 2
def main():
solution = Solution()
nums1 = [1, 2, 3]
nums2 = [4, 5, 6]
res = solution.solution1(nums1, nums2)
print(res)
if __name__ == '__main__':
main()
|
1f88005cef7d4943688f6beb2776d50a9004ace0 | jeff-ceiling-zero/git-demo | /fizzbuzz.py | 493 | 3.828125 | 4 |
def generate_list_of_numbers():
return range(1, 100)
def num_to_fizz_string(number):
if number % 3 == 0 and number % 5 == 0:
return 'FizzBuzz'
if number % 3 == 0:
return 'Fizz'
if number % 5 == 0:
return 'Buzz'
return str(number)
def run_fizz_buzz():
numbers = generate_list_of_numbers()
for number in numbers:
num_str = num_to_fizz_string(number)
print(num_str)
if __name__ == '__main__':
run_fizz_buzz()
|
d6fc864140420cd4ceae915368b91b687d7950c4 | nalwayv/bitesofpy | /bite_119/bite_119.py | 1,187 | 4.09375 | 4 | """
Bite 119. Xmas tree generator
"""
from typing import List
def generate_xmas_tree(rows=10) -> List[str]:
"""Generate a xmas tree of stars (*) for given rows (default 10).
Each row has row_number*2-1 stars, simple example: for rows=3 the
output would be like this (ignore docstring's indentation):
*
***
*****
Paramiters:
-----------
rows (int):
number of rows to draw
Returns:
--------
List[str]
"""
gen_tree = []
for i in range(1, rows+1):
# blanks
for j in range(i, rows):
gen_tree.append(' ')
# stars
for k in range(i * 2 - 1):
gen_tree.append('*')
# end of line
gen_tree.append('\n')
return ''.join(gen_tree[:-1])
if __name__ == "__main__":
print(generate_xmas_tree(3))
print(len(generate_xmas_tree().split('\n')) == 10)
print(len(generate_xmas_tree(5).split('\n')) == 5)
print(len(generate_xmas_tree(20).split('\n')) == 20)
print(generate_xmas_tree(3).count('*') == 9)
print(generate_xmas_tree(5).count('*') == 25)
print(generate_xmas_tree(20).count('*') == 400)
|
71c4cc9fbac92125e33c56541860764f2343701b | BRGoss/Treasure_PyLand | /Puzzles/Completed/reverse_words.py | 406 | 4.4375 | 4 | #DESCRIPTION: Reverse the words in a sentence rather than all letters
#ALGORITHM: Define a function called split_words that takes a string
# as its input. The output is the inputs words put in reverse
# order.
#Example: Input = 'A long long time ago' Output = 'ago time long long A'
def split_words(sentence):
words=' '.join(string.split(sentence,' ')[::-1])
return words
|
851e575ed87159b3a755753d4d07fb2dfd42dce3 | garne041/phData_interview | /source_code.py | 16,749 | 3.640625 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, recall_score,\
precision_score, accuracy_score, f1_score, confusion_matrix, roc_auc_score
import seaborn as sns
"""Problem Statement
Client: Tax firm looking to sell tax preparation software
Data: Two years of customer information and record whether they were able to
sell successfully to each customer.
Goal: They want to understand this data and build a model to predict if they
will be able to successfully sell their software to a given individual.
Approach:
1. Exploratory data analysis to identify features that contribute to a
successful sale (successful_sell == 'yes')
2. Two classification models to predict whether a sale would be successful
or not
"""
"""Exploratory Data Analysis
Uninformative features and duplicate records will be deleted.
Checked class balance/imbalance in target column 'successful_sell'
Analysis will focus on the following identifable features:
- Age
- Day of the week (dow)
- Employment status
- Marriage status
- Month
- School level
Any interesting unidentifiable features that arise during modeling will be
revisited and explored.
"""
#Loading and reading data
df = pd.read_csv("project_data.csv")
print(df.info())
# There were 41188 customer records over the last two years.
''' Uninformative feature found and deleted:
There appears to be a low number of values for c8, so it's probably not
informative to the successful_sell column. It has been deleted from the dataset.
'''
no_c8_val = df['c8'].isnull().sum()
no_c8 = df['c8'].isnull().sum()/len(df['c8'])
print('Number of null c8 values: {} \nPercentage of Null c8 Values: {}%'.format(no_c8_val, 100*np.round(no_c8, 3)))
df = df.drop('c8', axis = 1)
"""Checking for duplicates"""
print("Length of duplicated records: ",len(df[df.duplicated()]))
#There are no duplicate rows. So no records were deleted.
"""Checking for target class imbalance in 'successful_sale' column """
print(pd.concat([df['successful_sell'].value_counts(), df['successful_sell'].value_counts(normalize=True)], keys = ['Counts', 'Record_%'], axis = 1),'\n\n')
#The classes are highly imbalanced.
"""Aggregations Performed on Successful Sales
Approach:
1. Current customer target: total in the record
2. Ideal customer market: only those who have succesful sales
Implementation:
1. Map successful sell columns to floats
2. Pandas.groupby mean() --> Ratio of successful sales
3. Pandas.groupby sum() --> Total number of successful sales"""
#Mapped successful sell columns to floats
df['successful_sell']=df['successful_sell'].map({'yes':1, 'no':0})
"""Employment - Successful Sale Relationship"""
print("Employment - Successful Sale Relationship")
print("Current Customer Market - Employment")
print(pd.concat([df['employment'].value_counts(), df['employment'].value_counts(normalize=True)], keys = ['Counts', 'Normalized_counts'], axis = 1),'\n\n')
print("Ideal Customer Market - Employment")
#Employment aggregation
emp_group =df.groupby(by = 'employment', axis=0, as_index = False)
emp_group.successful_sell.mean().sort_values('successful_sell', ascending = False).reset_index(drop = True)
#Number of successful sales per employment value
emp_count = emp_group.successful_sell.sum()
#Ratio of successful sales per employment value
emp_mean = emp_group.successful_sell.mean()
emp_df = pd.concat([emp_count, 100*np.round(emp_mean.iloc[:,1], 3)], axis = 1)
emp_df.columns = ['Employment', 'Count', 'Percentage']
#Sorted by ratio of successful sales per employment value
emp_df=emp_df.sort_values(by='Percentage', axis = 0, ascending = False)
print(emp_df)
"""Marriage Status - Successful Sale Relationship"""
print("\n\nMarriage - Successful Sale Relationship")
print("Current Customer Market - Marriage Status")
print(pd.concat([df['marriage-status'].value_counts(), df['marriage-status'].value_counts(normalize=True)], keys = ['Counts', 'Normalized_counts'], axis = 1),'\n\n')
#Marriage group aggregation
marriage_group =df.groupby(by = 'marriage-status', axis=0, as_index = False)
print("Ideal Customer Market - Marriage Status")
#Number of successful sales per marriage status value
marriage_count = marriage_group.successful_sell.sum()
#Ratio of successful sales per marriage status value
marriage_mean = marriage_group.successful_sell.mean()
#Sorted by ratio of successful sales per marriage status value
print(pd.concat([marriage_count, 100*np.round(marriage_mean.iloc[:,1],3)], axis = 1))
"""DOW - Successful Sale Relationship"""
print("\n\nDOW - Successful Sale Relationship")
print("Current Customer Market - DOW")
print(pd.concat([df['dow'].value_counts(), df['dow'].value_counts(normalize=True)], keys = ['Counts', 'Normalized_counts'], axis = 1),'\n\n')
#DOW group aggregation
dow_group =df.groupby(by = 'dow', axis=0, as_index = False)
print("Ideal Customer Market - DOW")
#Number of successful sales per DOW status value
dow_count = dow_group.successful_sell.sum()
#Ratio of successful sales per DOW status value
dow_mean = dow_group.successful_sell.mean()
#Sorted by ratio of successful sales per DOW status value
print(pd.concat([dow_count, dow_mean.iloc[:,1]], axis = 1))
#There appears to be no appreciable difference of sales performance across dow values
print("\n\nSchool - Successful Sale Relationship")
print("Current Customer Market - School")
print(pd.concat([df['school'].value_counts(), df['school'].value_counts(normalize=True)], keys = ['Counts', 'Normalized_counts'], axis = 1),'\n\n')
print("Ideal Customer Market - School")
#Employment aggregation
school_group =df.groupby(by = 'school', axis=0, as_index = False)
school_group.successful_sell.mean().sort_values('successful_sell', ascending = False).reset_index(drop = True)
#Number of successful sales per employment value
school_count = school_group.successful_sell.sum()
#Ratio of successful sales per employment value
school_mean = school_group.successful_sell.mean()
school_df = pd.concat([school_count, 100*np.round(school_mean.iloc[:,1], 3)], axis = 1)
school_df.columns = ['Employment', 'Count', 'Percentage']
#Sorted by ratio of successful sales per employment value
school_df=school_df.sort_values(by='Percentage', axis = 0, ascending = False)
print(school_df)
n4_group =df.groupby(by = 'n4', axis=0, as_index = False)
print('\n\nPercentage of n4 Data Points')
print(df['n4'].value_counts(normalize=True),'\n\n')
#More than 96% of n4 values are the same. Since n4 appears to be an uninformative feature, it will be dropped from further analysis.
df = df.drop('n4', axis = 1)
"""Month - Successful Sale Relationship"""
print("\n\nMonth - Successful Sale Relationship")
print("Current Customer Market - Month")
print(pd.concat([df['month'].value_counts(), df['month'].value_counts(normalize=True)], keys = ['Counts', 'Normalized_counts'], axis = 1),'\n\n')
print("Ideal Customer Market - Month")
#month aggregation
month_group =df.groupby(by = 'month', axis=0, as_index = False)
month_group.successful_sell.mean().sort_values('successful_sell', ascending = False).reset_index(drop = True)
#Number of successful sales per month value
month_count = month_group.successful_sell.sum()
#Ratio of successful sales per month value
month_mean = month_group.successful_sell.mean()
month_df = pd.concat([month_count, 100*np.round(month_mean.iloc[:,1], 3)], axis = 1)
month_df.columns = ['Month', 'Count', 'Percentage']
#Sorted by ratio of successful sales per month value
month_df=month_df.sort_values(by='Percentage', axis = 0, ascending = False)
print(month_df)
"""Age
Does a successful sale depend on age of the client?
To make age usable for the describe method, the age was changed from int to float.
"""
df['age'] = df['age'].astype(float)
print('\nAge Statistics of Current Market')
print(df['age'].describe())
print('\nAge Statistics of Ideal Market')
print(df[df['successful_sell']==1]['age'].describe())
#Age distribution plots
age_yes=df['age'][df['successful_sell']==1]
age_no=df['age'][df['successful_sell']==0]
sns.distplot(age_no, label = 'No', bins = 20)
sns.distplot(age_yes, label = 'Yes', bins = 20)
plt.xlabel('Age (years)')
plt.ylabel('Density')
plt.title('Impact of Age on Successful Sells')
plt.legend(prop = {'size':12})
plt.savefig("Age_Analysis.png")
plt.show()
'''n5
Does the presence of n5 change whether your customers buy or not?
The n5 factor doesn't appear to be different whether people buy or not.
'''
#n5
n5_yes=df['n5'][df['successful_sell']==1]
n5_no=df['n5'][df['successful_sell']==0]
sns.distplot(n5_no, label = 'No')
sns.distplot(n5_yes, label = 'Yes')
plt.title('Impact of n5 on Successful Sales')
plt.xlabel('n5')
plt.ylabel('Density')
plt.legend(prop = {'size':12})
plt.savefig('n5_populations.png')
plt.show()
"""Sting to Numeric Value Conversion.
Reason: scikit-learn models require numerical value inputs"""
# Gathering unique values to gauge feature engineering stategies for the strings.
for each in df.columns:
print(each, df[each].unique())
""" Converting String Values to Numerical Features
Features dataset (df_features) mapping
Conversion to imply numerical order
- b1: yes = 1, no = 0
- b2: yes = 1, no = 0, NaN = -1
- c10: yes = 1, no = 0
- c3: True = 1, False = 0, unknown = -1
- c4: new = 1, old = 0
- dow (day of the week): mon = 0, tues = 1, wed = 2, thurs = 3, fri = 4
- month: jan = 0, feb = 1, ... nov = 10, dec = 12
- school: 5 - a decent amount = 5, 5 - a lot = 5, 2 - a little bit = 2, 4 - average amount = 4, 3 - a bit more = 3, 1 - almost none = 1, 0 - none = 0, NaN = -1
"""
df_features = df.copy().drop('successful_sell', axis = 1)
df_features['b1'] = df['b1'].map({'yes':1, 'no':0, '-1':-1})
df_features['b2'] = df['b2'].fillna(-1).map({'yes':1, 'no':0, -1:-1})
df_features['c10'] = df['c10'].map({'yes':1, 'no':0})
df_features['c3'] = df['c3'].map({'True':1, 'False':0, 'unknown':-1})
df_features['c4'] = df['c4'].map({'new':1, 'old':0})
df_features['dow'] = df['dow'].map({'mon':0, 'tues':1, 'wed':2, 'thurs':3, 'fri':4}).fillna(-1)
#Month map
months = {'jan':0, 'feb':1, 'mar':2, 'apr':3, 'may':4, 'jun':5, 'jul':6, 'aug':7, 'sep':8, 'oct':9, 'nov':10, 'dec':11}
df_features['month']=df_features['month'].map(months)
#School map
schools = {'5 - a decent amount': 5, '5 - a lot':5, '2 - a little bit':2, '4 - average amount': 4, '3 - a bit more':3, '1 - almost none':1, '0 - none':0}
df_features['school'] = df_features['school'].map(schools).fillna(-1)
'''String Features Conversion II - Without Order
- Marriage-status
- Employment
Any NaN marriage-status values were converted to unknown. Both the marriage status and employment
columns were one-hot encoded in order to generate numerical features without implying order. This
expanded the feature space to 35.'''
#Marriage status and Employment will be one hot decoded, since there is no order
df_features['marriage-status'] = df_features['marriage-status'].fillna('unknown')
df_features = pd.get_dummies(df_features, columns = ['marriage-status', 'employment'])
#df_features.info()
"""Preparing Training, Testing, and Validation Datasets
1. Splitting featurespace into training/test/validation datasets
2. Scaling the data to zero mean and unit variance"""
X = df_features
y = df.successful_sell
#Two sequential splits to produce a 60/20/20 training/test/validation split.
"""Since the target classes are so imbalanced, the stratify flag is used in the train_test_split function
to replicate the same imbalance for the models."""
#First split: Splits 20% of the data into validation dataset
X_model, X_val, y_model, y_val = train_test_split(X, y, train_size = 0.8, stratify=y)
#Second split: Splits the remaining into training and test
X_train, X_test, y_train, y_test = train_test_split(X_model, y_model, train_size = 0.75, stratify=y_model)
print('The training dataset contains {} samples or {}% of the entire dataset.'.format(X_train.shape[0], 100*np.round(X_train.shape[0]/X.shape[0], 3)))
print('The test dataset contains {} samples or {}% of the entire dataset.'.format(X_test.shape[0], 100*np.round(X_test.shape[0]/X.shape[0], 3)))
print('The validation dataset contains {} samples or {}% of the entire dataset.'.format(X_val.shape[0], 100*np.round(X_val.shape[0]/X.shape[0], 3)))
#Scaling the feature dataset to zero mean and unit variance
scaler=StandardScaler().fit(X_train)
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)
X_val = scaler.transform(X_val)
#Model 1: Random Forest Classifier
print('Model #1 (Random Forest Classifier) Results')
clf = RandomForestClassifier()
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
y_pred_train = clf.predict(X_train)
print("Random Forest Classifier Results on Test Data")
print(classification_report(y_test, y_pred))
print("Recall: ",recall_score(y_test, y_pred))
print("Precision: ", precision_score(y_test, y_pred))
print("Confusion Matrix: ", confusion_matrix(y_test, y_pred))
print("Accuracy: ", accuracy_score(y_test, y_pred))
print("F1: ", f1_score(y_test, y_pred))
print("AUC: ", roc_auc_score(y_test, y_pred))
print('\nRandom Forest Classifier on Training Data Results')
print(classification_report(y_train, y_pred_train))
print("Recall: ",recall_score(y_train, y_pred_train))
print("Precision: ", precision_score(y_train, y_pred_train))
print("Confusion Matrix: ", confusion_matrix(y_train, y_pred_train))
print("Accuracy: ", accuracy_score(y_train, y_pred_train))
print("F1: ", f1_score(y_train, y_pred_train))
print("AUC: ", roc_auc_score(y_train, y_pred_train))
print('\nRandom Forest Classifier on Validation Data Results')
y_pred_val = clf.predict(X_val)
print(classification_report(y_val, y_pred_val))
print("AUC: ", roc_auc_score(y_train, y_pred_train))
"""Feature Importances from Random Forest Classifier"""
# Create list of top most features based on importance
feature_names = X_model.columns
feature_imports = clf.feature_importances_
most_imp_features = pd.DataFrame([f for f in zip(feature_names,feature_imports)], columns=["Feature", "Importance"]).nlargest(10, "Importance")
most_imp_features.sort_values(by="Importance", inplace=True)
indices = np.argsort(feature_imports)[::-1]
# Print the feature importance and feature name in descending order from highest to lowest importance values.
print("Feature ranking:")
for f in range(5):
print("%d. "% (f+1) + feature_names[indices[f]] +" (%f)" % (feature_imports[indices[f]]))
#Plotting the feature importances
plt.barh(range(len(most_imp_features)), most_imp_features.Importance, align='center', alpha=0.8)
plt.yticks(range(len(most_imp_features)), most_imp_features.Feature, fontsize=14)
plt.xlabel('Gini Importance')
plt.title('Most important features - Random Forest')
plt.savefig('RF_feature_import.png')
plt.show()
'''The most important feature was c10. So I dedicated this section to explore this feature.'''
# Importance of c10
c10_group =df.groupby(by = 'c10', axis=0, as_index = False)
c10_means = c10_group.successful_sell.mean()
c10_means.columns = ['c10', 'Sell %']
c10_counts = c10_group.successful_sell.count()
c10_counts.columns = ['c10', 'Counts']
print('Statistics of c10 Feature:')
print(pd.concat([c10_counts, c10_means.iloc[:,1]], axis = 1))
# # Model 2 : Logistic Regression
print('Model #2 (Logistic Regression) Results')
clf_log = LogisticRegression()
clf_log.fit(X_train, y_train)
y_pred_log = clf_log.predict(X_test)
y_pred_train_log = clf_log.predict(X_train)
print("Logistic Regression Results on Test Data")
print(classification_report(y_test, y_pred_log))
print("Recall: ",recall_score(y_test, y_pred_log))
print("Precision: ", precision_score(y_test, y_pred_log))
print("Confusion Matrix: ", confusion_matrix(y_test, y_pred_log))
print("Accuracy: ", accuracy_score(y_test, y_pred_log))
print("F1: ", f1_score(y_test, y_pred_log))
print("AUC: ", roc_auc_score(y_test, y_pred_log),'\n\n\n')
print("Logistic Regression Results on Training Data")
print(classification_report(y_train, y_pred_train_log))
print("Recall: ",recall_score(y_train, y_pred_train))
print("Precision: ", precision_score(y_train, y_pred_train_log))
print("Confusion Matrix: ", confusion_matrix(y_train, y_pred_train_log))
print("Accuracy: ", accuracy_score(y_train, y_pred_train_log))
print("F1: ", f1_score(y_train, y_pred_train_log))
print("AUC: ", roc_auc_score(y_train, y_pred_train_log),'\n\n\n')
print("Logistic Regression Results on Validation Data")
y_pred_val_log = clf.predict(X_val)
print(classification_report(y_val, y_pred_val_log))
|
4b43f9ec035c211a09d94bc6d73f894cefe082d0 | abiraja2004/IntSys-Sentiment-Summary | /optimization/mcmc_optimize.py | 2,152 | 3.734375 | 4 | import numpy as np
'''
See: https://en.wikipedia.org/wiki/Stochastic_tunneling, which can be performed
by correct choice of f and accept_prob_func
f(X, s), where X is a matrix whose rows are inputs, returns y, s',
where y[i] = f(X[i], s[i]), and s'[i] is the "state" of f (s can be None
if not needed by f) given for the f evaluating on the X[i]. If S is None,
f then f treates it as if it were its first evaluation
neighbors_func(X) returns a list of neighbors of X such that the ith
element of the output is a random neighbor of X[i]
returns S so that the optimization can be restarted later
from the output X and that S without issue
'''
def optimize(X, f, neighbors_func, accept_prob_func, k_max, S_0 = None):
f_X, S = f(X, S_0)
for k in range(0, k_max):
X_prime = neighbors_func(X)
f_X_prime, S_prime = f(X_prime, S)
X_prime_accept_probs = accept_prob_func(f_X, f_X_prime)
probs = np.random.rand(X_prime_accept_probs.shape[0])
where_accepted = np.where(probs <= X_prime_accept_probs)
X[where_accepted] = X_prime[where_accepted]
if S is not None and S_prime is not None:
S[where_accepted] = S_prime[where_accepted]
f_X[where_accepted] = f_X_prime[where_accepted]
if k % 100 == 0:
print("f_X on iteration " + str(k) + ": " + str(f_X))
return X, S
if __name__ == "__main__":
'''
Below implements vanilla Metropolis Hastings
(Described in "Idea" section here:
https://en.wikipedia.org/wiki/Stochastic_tunneling)
to minimize f(X)
'''
BETA = 10.0
def f(X, S):
return np.sum(np.square(X), axis = 1).astype(np.float32), None
def neighbors_func(X):
cols = np.random.randint(0, X.shape[1], size = X.shape[0])
out = X.copy()
out[:,cols] += np.random.randint(-1,2,size = out.shape[0])
return out
def accept_prob_func(f_X, f_X_prime):
out = np.exp(-BETA * (f_X_prime - f_X))
out[np.where(out > 1)] = 1
return out
X = np.random.randint(-20, 21, size = (5, 100))
optimize(X, f, neighbors_func, accept_prob_func, 100000, S_0 = None)
|
e92bcae027bd4a65f022242f5eb8e7453a7477f1 | aqing1987/s-app-layer | /udacity/ml-engineer-basic/accessing-file-and-network/scripting/read-write-files/test-read-with-int.py | 289 | 3.609375 | 4 | # if you pass the read method an integer argument, it will read up to that
# number of characters, output all of them, and keep the 'window' at that
# position ready to read on.
with open('./camelot.txt', 'r') as song:
print(song.read(2))
print(song.read(8))
print(song.read()) |
c3211b35fe1e4c519995604650626f2d4c3ccd90 | Legolas1086/bug_bounty | /find_previous_better/find_previous_better.py | 555 | 3.546875 | 4 | def previousBest(n,ranks):
stack = []
previous_greater = []
for i in range(n):
while stack:
if stack[-1] > ranks[i]:
previous_greater.append(stack[-1])
break
else:
stack.pop()
if not stack:
previous_greater.append(-1)
stack.append(ranks[i])
for i in previous_greater:
print(i,end=" ")
if __name__=="__main__":
n = int(input())
ranks = list(map(int,input().rstrip().split()))
previousBest(n,ranks) |
1df8704a6a1def80be918990bab83752c3338e87 | frestea09/latihan-python-november | /src/inputBilanganRill.py | 372 | 3.78125 | 4 | from __future__ import print_function
def main():
bilanganPertama = float(input('Bilangan Pertama : '))
bilanganKedua = float(input('Bilangan Kedua : '))
hasil = bilanganPertama * bilanganKedua
print('Bilangan Pertama : %f'%bilanganPertama)
print('Bilangan Kedua : %f'%bilanganKedua)
print('Hasil : %f'%hasil)
if __name__ == '__main__':
main() |
6964db8c6a407006d1aea29c1833598ee7196e15 | MineRobber9000/aaf_elo | /predict.py | 397 | 3.765625 | 4 | import forecast
team = input("Team?: ")
opponent = input("Opponent?: ")
winner,confidence = forecast.forecast(team,opponent)
if not winner:
print("I expect a tie!")
elif winner==team:
print("The {} are gonna blow the {}'s socks off!".format(team,opponent))
else:
print("The {} are gonna blow the {}'s socks off!".format(opponent,team))
print("Confidence: {:.2%}".format(confidence))
|
be8aa89d4d7b2526493012c4eb35486bff5e58fb | maleks93/Python_Problems | /prblm_56.py | 2,337 | 3.78125 | 4 | # https://leetcode.com/problems/merge-intervals/description/
# Time complexity: O( N*log(N) )
# Space complexity: O( N )
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[List[int]]
"""
temp = self.sort(intervals) # sort the intervals with elements left element i.e. ele[0]
#intervals.sort(key = lambda x : x[0])
#temp = intervals
result = [] # final result
ind = 0
while(ind <= len(temp)-1): # iterate over sorted intervals
if len(result) > 0 and result[-1][1] >= temp[ind][0]: # if overlapping with last element in result
result.append([result[-1][0],max(temp[ind][1], result[-1][1])])
result.pop(-2)
ind += 1
elif ind == len(temp)-1: # final element
result.append(temp[ind])
break
elif temp[ind][1] >= temp[ind+1][0]: # overlapping adjacent elements
result.append([temp[ind][0],max(temp[ind][1], temp[ind+1][1])])
ind += 2
else: # non overlapping element
result.append(temp[ind])
ind += 1
return result
def sort(self, arr): # sort function to sort by 0th index of an element i.e. ele[0]
if arr == None: # merge sort
return None
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_sort = self.sort(arr[:mid])
right_sort = self.sort(arr[mid:])
ind_left = 0
ind_right = 0
result = []
while(ind_left < len(left_sort) and ind_right < len(right_sort)):
if (left_sort[ind_left][0] < right_sort[ind_right][0]):
result.append(left_sort[ind_left])
ind_left += 1
else:
result.append(right_sort[ind_right])
ind_right += 1
if ind_left < len(left_sort):
result += left_sort[ind_left:]
if ind_right < len(right_sort):
result += right_sort[ind_right:]
return result
|
ce313252b917a9bdc2f9391a69887f0204b1eb6c | developersage/PythonProjects | /password-manager-start/main.py | 4,093 | 3.578125 | 4 | from tkinter import *
from tkinter import messagebox
from random import choice, randint, shuffle
from pyperclip import copy
import json
import string
import pandas as pd
# try:
# df = pd.read_csv("data.csv")
# except FileNotFoundError:
# df = pd.DataFrame(columns=["Website", "Email/Username", "Password"])
# df.to_csv("data.csv", index=False)
# ---------------------------- PASSWORD GENERATOR ------------------------------- #
letters = string.ascii_letters
numbers = string.digits
symbols = string.punctuation
def pw_gen():
password_list = [choice(letters) for _ in range(randint(8, 10))]
password_list += [choice(symbols) for _ in range(randint(2, 4))]
password_list += [choice(numbers) for _ in range(randint(2, 4))]
shuffle(password_list)
password = "".join(password_list)
copy(password)
entry_pw.delete(0, END)
entry_pw.insert(0, password)
# ---------------------------- SAVE PASSWORD ------------------------------- #
def save():
website = entry_web.get()
email = entry_user.get()
password = entry_pw.get()
new_data = {
website: {
"email": email,
"password": password,
}
}
if website and email and password:
is_ok = messagebox.askokcancel(title=website, message=f"These are the details entered: \nEmail: {email} "
f"\nPassword: {password} \nIs it okay to save?")
if is_ok:
# a_list = [website, email, password]
# a_series = pd.Series(a_list, index=df.columns)
# df.loc[len(df.index)] = a_series
# df.to_csv("data.csv", index=False)
try:
with open("data.json", "r") as data_file:
data = json.load(data_file)
except FileNotFoundError:
with open("data.json", "w") as data_file:
json.dump(new_data, data_file, indent=4)
else:
data.update(new_data)
with open("data.json", "w") as data_file:
json.dump(data, data_file, indent=4)
finally:
entry_web.delete(0, END)
entry_pw.delete(0, END)
else:
messagebox.showwarning(title="Password Manager", message="Please fill in all of the entries.")
# ---------------------------- SEARCH DATA ------------------------------- #
def search():
website = entry_web.get().title()
try:
with open("data.json", "r") as data_file:
data = json.load(data_file)
email = data[website]["email"]
password = data[website]["password"]
except FileNotFoundError:
messagebox.showerror(title="Error", message="No Data File Found.")
except KeyError:
messagebox.showerror(title="Error", message="No details for the website exists.")
else:
messagebox.showinfo(title=website, message=f"Email: {email} \nPassword: {password}")
# ---------------------------- UI SETUP ------------------------------- #
window = Tk()
window.title("Password Manager")
window.config(padx=50, pady=50)
canvas = Canvas(width=200, height=200)
lock_img = PhotoImage(file="logo.png")
canvas.create_image(100, 100, image=lock_img)
canvas.grid(row=0, column=1)
label_web = Label(text="Website: ")
label_user = Label(text="Email/Username: ")
label_pw = Label(text="Password: ")
entry_web = Entry(width=21)
entry_web.insert(0, "Google")
entry_user = Entry(width=35)
entry_user.insert(0, "sangdo719@gmail.com")
entry_pw = Entry(width=21)
button_search = Button(text="Search", width=10, command=search)
button_gen = Button(text="Generate Password", width=14, command=pw_gen)
button_add = Button(text="Add", width=35, command=save)
label_web.grid(row=1, column=0)
label_user.grid(row=2, column=0)
label_pw.grid(row=3, column=0)
entry_web.grid(row=1, column=1)
entry_user.grid(row=2, column=1, columnspan=2)
entry_pw.grid(row=3, column=1)
button_search.grid(row=1, column=2)
button_gen.grid(row=3, column=2)
button_add.grid(row=4, column=1, columnspan=2)
window.mainloop() |
07bef416f4aa3426157b69dfda6d31b7ba553028 | jw1121/RestCRUD | /market/sqlite.py | 1,267 | 3.53125 | 4 | import sqlite3
class MarketModel(object):
def __init__(self, database="../docs/market.db"):
self.database = database
self.conn = sqlite3.connect(self.database)
self.cur = self.conn.cursor()
def insertMarket(self, data):
sql_str = ("INSERT INTO market({0}) VALUES('{1}')").format(data[0], data[1])
print(sql_str)
self.cur.execute(sql_str, "") # Parameter is not optional
self.conn.commit()
self.conn.close()
return True
def getMarket(self, id):
self.cur.execute("select * from market where FMID = :FMID", {'FMID': id})
data = self.cur.fetchone()
self.conn.close()
return data.__str__()
def updateMarket(self, data):
sql_str = ("UPDATE market SET {0} WHERE = {1}").format(data[0], data[1])
print(sql_str)
self.cur.execute(sql_str, "") # Parameter is not optional
self.conn.commit()
self.conn.close()
return True
def deleteMarket(self, data):
sql_str = ("DELETE FROM market WHERE {0} = {1}").format(data[0], data[1])
print(sql_str)
self.cur.execute(sql_str, "") # Parameter is not optional
self.conn.commit()
self.conn.close()
return True
|
7e5a5e63755b4a9e24bfb7d8a0ac7d1c04f5c27e | LeoImenes/SENAI | /1 DES/FPOO/Exercicios1/10.py | 174 | 3.75 | 4 | a=int(input("Digite o valor da área a ser revestida em m²: "))
v=13
m=0.37
p=a/m
t=p*v
print("Será necessario {} kg de pedra mineira e custará {:.2f} reais".format (p,t)) |
517de7e19a8fa1ac38f9b25365564799d1633b99 | jinxinbo/base-model | /pycode set/4/U_smart.py | 142 | 3.578125 | 4 | def cal(sum,*args):
print(type(args))
print(args)
for i in args:
sum=sum+i**2
return sum
asum=cal(2,2,3,4)
print(asum) |
01732a9444f6c59679d4f2f07da649ee5013290e | henokalem/teamge | /user/josh/currentlyUseless/Turnout.py | 1,836 | 3.71875 | 4 | import RPi.GPIO as GPIO
import time
# Class for controlling
class Turnout:
# Constructor
def __init__(self, turnout_id, straight_pin_num, turn_pin_num):
self.turnout_id = turnout_id
self.straight_pin_num = straight_pin_num
self.turn_pin_num = turn_pin_num
self.current_state = "straight"
# set up the initial GPIO pin outputs
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(self.straight_pin_num, GPIO.OUT)
GPIO.output(self.straight_pin_num, GPIO.LOW)
GPIO.setup(self.turn_pin_num, GPIO.OUT)
GPIO.output(self.turn_pin_num, GPIO.LOW)
# Put the turnout in the straight state
def activateStraight(self):
if self.current_state == "straight":
print("Turnout is already in the 'straight' state")
else:
self.current_state = "straight"
print("Putting turnout in 'straight' state")
self.__activateRelay(self.straight_pin_num)
# Put the turnout in the turned state
def activateTurn(self):
if self.current_state == "turn":
print("Turnout is already in the 'turned' state")
else:
self.current_state = "turn"
print("Putting turnout in 'turn' state")
self.__activateRelay(self.turn_pin_num)
# send the signal to activate the correct pin on the pi
def __activateRelay(self, pin_num, time_delay=0.3):
#Activate the pin for the duration of the time delay, then shut off
GPIO.output(pin_num, GPIO.HIGH)
print ("pin: " + str(pin_num), "state: HIGH, time: ", time.time())
time.sleep(time_delay)
GPIO.output(pin_num, GPIO.LOW)
print ("pin: " + str(pin_num), "state: LOW, time: ", time.time())
time.sleep(time_delay) #necessary?
|
68c67d60e3f398e1678a325dab5066073a00f2c6 | shraysidubey/pythonScripts | /DFS.py | 933 | 3.71875 | 4 | class Graph:
def __init__(self,node):
self.graph = []
for i in range(node):
self.graph.append([])
def addEdge(self,source,destination):
self.graph[source].append(destination)
def DFS(self,s):
print("DFS")
visited = [False] * (len(self.graph))
stack = []
stack.append(s)
visited[s] = True
while len(stack) > 0:
s = stack.pop(len(stack)-1)
print(s, end = " ")
for i in self.graph[s]:
if visited[i] == False:
stack.append(i)
visited[i] = True
def print(self):
for i in self.graph:
print(i)
S = Graph(7)
S.addEdge(0,1)
S.addEdge(0,2)
S.addEdge(1,2)
S.addEdge(2,0)
S.addEdge(2,3)
S.addEdge(1,5)
S.addEdge(0,3)
S.addEdge(2,5)
S.addEdge(1,4)
S.addEdge(4,1)
S.addEdge(4,5)
S.addEdge(5,2)
S.addEdge(5,3)
S.DFS(2)
S.print()
|
4406ce6ab7eacce83daa6ad6a8696db8a41c510c | FrankUSA2015/Leetcode-algorithm | /Valid Parentheses.py | 965 | 3.953125 | 4 | # -*- coding: utf-8 -*-
#题目见:https://leetcode-cn.com/problems/valid-parentheses/
#解答思路:
# https://leetcode-cn.com/problems/valid-parentheses/solution/zhu-bu-fen-xi-tu-jie-zhan-zhan-shi-zui-biao-zhun-d/
#解法:
# 利用入栈和出栈的方法,实现对括号的比较。
#学到的知识:
# 可以利用list来模拟栈,出栈用list自带的函数pop(),入栈用append()
# i in str_dict,可以判断i这个关键词是否在字典中。
class Solution:
def isValid(self, s) -> bool:
stack = []
str_dict = {")":"(","]":"[","}":"{"}
for i in s:
if stack and (i in str_dict):
if str_dict[i] == stack[-1]:
stack.pop()
else:
return False
else:
stack.append(i)
if len(stack)==0:
return True
else:
return False
nn = Solution()
cc = "([)]"
print(nn.isValid(cc)) |
09a53f4fe5c9c0cefef0a648f180100090854e84 | Farheen2302/ds_algo | /algorithms/dp/word_break.py | 1,630 | 3.984375 | 4 | # Refer :
# http://www.geeksforgeeks.org/dynamic-programming-set-32-word-break-problem/
def check_word(dictionary, word):
if len(word) == 0:
return True
for i in range(len(word)):
prefix = word[:i + 1]
suffix = word[i + 1:len(word)]
if prefix in dictionary and check_word(dictionary, suffix):
return True
return False
# Memoization approach
def memo_check_word(dictionary, word, result):
if len(word) == 0:
return True
if word in result:
return result[word]
for i in range(len(word)):
prefix = word[:i + 1]
suffix = word[i + 1:len(word)]
if prefix in dictionary and memo_check_word(dictionary, suffix, result):
result[word] = True
return True
result[word] = False
return False
def dp_check_word(dictionary, word):
bol_arr = [False] * len(word)
for i in range(len(word)):
if bol_arr[i] is False and word[:i + 1] in dictionary:
bol_arr[i] = True
if bol_arr[i]:
if i == len(word) - 1:
return True
for j in range(i + 1, len(word)):
if bol_arr[j] is False and word[i + 1:j + 1] in dictionary:
bol_arr[j] = True
if j == len(word) - 1 and bol_arr[j] is True:
print(bol_arr)
return True
print(bol_arr)
return False
print(check_word(['i', 'like', 'sam', 'sung', 'samsung', 'mobile', 'ice',
'cream', 'icecream', 'man', 'go', 'mango'], 'ilikesamsung'))
print(memo_check_word(['i', 'like', 'sam', 'sung', 'samsung', 'mobile', 'ice',
'cream', 'icecream', 'man', 'go', 'mango'], 'ilikeapple', {}))
print(dp_check_word(['i', 'like', 'sam', 'sung', 'samsung', 'mobile', 'ice',
'cream', 'icecream', 'man', 'go', 'mango'], 'ilikesamsung'))
|
084662764764b78c4e5da745c991bd4ee8e3b0c3 | nnhamoinesu22/Python-Challenge | /PyPoll/main.py | 1,579 | 3.609375 | 4 | import os
import csv
election_data = os.path.join('02-Homework','03-Python','Instructions','PyPoll', 'Resources', 'election_data.csv')
election_data_csv = "election_data.csv"
#election_analysis = os.path.join("analysis", "election_analysis.txt")
total_votes = 0
candidate_name = ""
candidate_votes = {}
candidate_percentages ={}
winner_votes = 0
winner = ""
with open(election_data, newline = "") as election_data_csv :
election_data_csv_reader = csv.reader(election_data_csv, delimiter = ",")
next(election_data_csv_reader)
for row in election_data_csv_reader:
total_votes = total_votes + 1
candidate_name = row[2]
if candidate_name in candidate_votes:
candidate_votes[candidate_name] = candidate_votes[candidate_name] + 1
else:
candidate_votes[candidate_name] = 1
# percentage and winner
for person, vote_count in candidate_votes.items():
candidate_percentages[person] = '{0:.0%}'.format(vote_count / total_votes)
if vote_count > winner_votes:
winner_votes = vote_count
winner = person
# results
dashline = "-------------------------"
#print("---------------------")
print("Election Results")
print(dashline)
print(f"Total Votes: {total_votes}")
print(dashline)
for person, vote_count in candidate_votes.items():
print(f"{person}: {candidate_percentages[person]} ({vote_count})")
print(dashline)
print(f"Winner: {winner}")
print(dashline)
# Print the results and export the data to our text file
#with open(election_analysis, "w") as txt_file:
#txt_file.write(output)
|
5d9d903093addac7fb833abde3624228b6e12890 | jeremypedersen/pythonBootcamp | /code/class5/dictionary_functions.py | 422 | 4.4375 | 4 | # You create a new dictionary like this
d = {}
# You can add new items like this
d['bananas'] = 5
d['apples'] = 2
d['oranges'] = 'we have no oranges'
print(d)
# You can use regular functions like "len", "min", and "max"
# like you did for lists, but remember these functions will
# look at the KEYS (item names) in the dictionary, not their
# VALUES. This is important!
print( max(d) )
print( min(d) )
print( len(d) )
|
039797c9cb7273d832bb35561c9d408d8dfb91d3 | kira-Developer/python | /062_Function_Scope.py | 386 | 3.9375 | 4 | # --------------------
# -- Function Scope --
# --------------------
x = 1 # global Scope
def one():
global x
x = 2
print(f'print variable from function scope {x}')
def two():
x = 4
print(f'print variable form function scope {x}')
print(f'print variable from global scope {x}')
one()
two()
print(f'print variable from global scope after one function is call {x}') |
75f203ba0dda0ca8b08b67a584a1dab618a6dfc1 | pratikgchaudhari/python-demo | /testing/test_cities.py | 550 | 3.59375 | 4 | import unittest
from city_functions import get_formatted_name
class NamesTestCase(unittest.TestCase):
"""Tests for 'city_functions.py'. """
def test_city_country(self):
formatted_name = get_formatted_name("New York","United States")
self.assertEqual(formatted_name,"New York, United States")
def test_city_country_population(self):
formatted_name = get_formatted_name("New York","United States",8550405)
self.assertEqual(formatted_name,"New York, United States - Population 8550405")
unittest.main() |
12b57a9c20f6d14d2cd1b53cd1bd7d49e3b20f34 | UA83/LibrarySystemCA2 | /mixed.py | 922 | 3.703125 | 4 | from Book import Book
list_of_book = [Book('10', 'Python BG', '2019', '123456789123', 'Ulisses Alves'),
Book('20', 'Python MT', '2018', '987654321987', 'Stephanie Enders'),
Book('30', 'Python AA', '2019', '143567833456', 'Suki Dog')]
#display all books
#add book
id, title, year, isbn, author = '22', 'new book', '2000', '777777777777', 'Marvel'
list_of_book.append(Book(id, title, year, isbn, author))
#for b in list_of_book:
# print(b)
to_search = '20001'
x = Book.find_book(list_of_book, str(to_search))
if not x:
print('no found')
else:
for b in x:
print(b)
#search book
#delete book
# [1] Display Users
# [2] Add User
# [3] Delete USer
# [4] Search User
# [5] Add Book
# [6] Borrow Book
# [7] Delete Book
# [8] Display Books
# [9] Return Book
# [10] Search Book
# [11] Add Periodical
# [12] Delete Periodical
# [13] Display Periodicals
# [14] Search Periodical
|
d298ac5f9a020affa54bb08bcc55c837d7d31ad9 | fernandoseguim/python_excript | /instruction_break.py | 210 | 3.765625 | 4 | print("Início da execução do laço")
i = 0
while(i < 10):
i = i + 1
if (i % 2 == 0):
continue
print("o número %d é impar" %i)
else:
print("else")
print("fim da execução laço") |
adfeef6dddf767359953a830abdf46f27add4862 | nhatsmrt/AlgorithmPractice | /LeetCode/205. Isomorphic Strings/Solution.py | 609 | 3.71875 | 4 | class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
# Time and Space Complexity: O(N)
bimap = Bimap()
for i in range(len(s)):
if not bimap.put(s[i], t[i]):
return False
return True
class Bimap:
def __init__(self):
self.forward, self.backward = {}, {}
def put(self, first, second):
if self.forward.get(first, second) == second and self.backward.get(second, first) == first:
self.forward[first] = second
self.backward[second] = first
return True
return False
|
5448334fd7a1312cd047ccc3ce4d6d930ba3e15b | h-ohsaki/dtnsim | /dtnsim/mobility/levywalk.py | 2,056 | 3.578125 | 4 | #!/usr/bin/env python3
#
# A mobility class for Levy walk.
# Copyright (c) 2011-2015, Hiroyuki Ohsaki.
# All rights reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import random
import math
from dtnsim.mobility.rwp import RandomWaypoint
from dtnsim.vector import Vector as V
def pareto(scale, shape):
"""Generate a random variable following the Pareto distribution with
parameters SCALE and SHAPE. Note that the mean of the Pareto distribution
is given by SHAPE * SCALE / (SHAPE - 1)."""
# https://en.wikipedia.org/wiki/Pareto_distribution#Random_sample_generation
return scale / random.uniform(0, 1) ** (1 / shape)
class LevyWalk(RandomWaypoint):
def __init__(self, scale=100, shape=1.5, *kargs, **kwargs):
# NOTE: must be assigned before calling __init__
self.scale = scale
self.shape = shape
super().__init__(*kargs, **kwargs)
def goal_coordinate(self):
"""Randomly choose the goal in the field so that the distance from the
current coordinate follows Pareto distribution."""
length = pareto(self.scale, self.shape)
theta = random.uniform(0, 2 * math.pi)
goal = self.current + length * V(math.cos(theta), math.sin(theta))
# FIXME: the goal coordinate is simply limited by the field boundaries.
# A node should *bounce back* with the boundaries.
x = max(0, min(goal[0], self.width))
y = max(0, min(goal[1], self.height))
return V(x, y)
|
80962f364c29a47d2b388d727562152b121a48f3 | nosaj-xqr/leetcode | /110. 平衡二叉树.py | 870 | 3.765625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
'''
讨论区题解分析:
1、使用self.res创建全局变量
2、之所以要新定义一个函数,是因为此函数要用来返回最大值,保证递归的正常执行,而最终结果为布尔值,要根据递归过程中的结果来判定,
这也是为什么设置全局变量的用意
'''
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
self.res = True
def compare(root):
if not root:
return 0
left=compare(root.left) + 1
right=compare(root.right) + 1
if abs(left-right) > 1:
self.res = False
return max(left,right)
compare(root)
return self.res
|
a979c04321718921ed62645d3ab4084ee417d12d | jiaweiyu2009/flightServiceApp | /test.py | 1,602 | 3.75 | 4 | class Flight:
def __init__(self, fid=-1, dayOfMonth=0, carrierId=0, flightNum=0, originCity="", destCity="", time=0, capacity=0, price=0):
self.fid = fid
self.dayOfMonth = dayOfMonth
self.carrierId = carrierId
self.flightNum = flightNum
self.originCity = originCity
self.destCity = destCity
self.time = time
self.capacity = capacity
self.price = price
def toString(self):
return "ID: {} Day: {} Carrier: {} Number: {} Origin: {} Dest: {} Duration: {} Capacity: {} Price: {}\n".format(
self.fid, self.dayOfMonth, self.carrierId, self.flightNum, self.originCity, self.destCity, self.time, self.capacity, self.price)
class Itinerary:
# one-hop flight
def __init__(self, time, flight1, flight2=Flight()): # the second one could be empty flight
self.flights = []
self.flights.append(flight1)
self.flights.append(flight2)
self.time = time
def itineraryPrice(self):
price = 0
for f in self.flights:
price += f.price
return price
def numFlights(self):
if(self.flights[1].fid == -1):
return 1
else:
return 2
def dayOfItinerary(self):
return self.flights[0].dayOfMonth
def getFlight1(self):
return self.flights[0]
def getFlight2(self):
return self.flights[1]
def main():
a = Flight(12, 54, 67, 23, "o", "d", 25, 30, 22)
b = Flight()
c = Itinerary(a.time, a)
print(c.getFlight2().fid)
if __name__ == "__main__":
main()
|
1cb682f05f7f70673a557db097c8d9feb9fef7bf | tobinSen/python01 | /python01/myFirstPython.py | 653 | 4.5 | 4 | """
1.定义变量
语法:变量名 = 变量值
2.使用变量
3.看变量的特点
"""
# 定义变量:存储数据TOM
my_name = 'TOM'
print(my_name)
# 定义变量
schoolName = '黑马程序员,我唉Python'
print(schoolName)
"""
1.验证数据到底是什么类型
"""
num1 = 1
num2 = 2.2
# int
print(type(num1))
# float
print(type(num2))
# str 单引号和双引号都可以
a = 'hello world'
print(type(a))
b = True
print(type(b))
c = [1, 2, 3, 4]
print(type(c))
# tuple -->元组
d = (1, 2, 3, 4)
print(type(d))
# set --> 集合
e = {1, 2, 3, 4}
print(type(e))
# dict -->字典 (键值对)
f = {'name': 'TOM', 'age': 18}
print(type(f))
|
e3ac8af3d1df8ad76f2882be2357e105a4132948 | zkevinbai/LPTHW | /ex48.py | 413 | 4.34375 | 4 | stuff = raw_input('> ')
words = stuff.split()
first_word = ('verb', 'go')
second_word = ('direction', 'north')
third_word = ('direction', 'west')
sentence = [first_word, second_word, third_word]
"""This is just an example, but that's basically the end result.
You want to take raw input from the user, carve it into words with split,
analyze those words to identify their type, and finally make a sentence.
"""
|
9a98ec2cb098dc9ff3443897032599504a4c8223 | austburn/advent-of-code-17 | /4/anagrams.py | 997 | 4 | 4 | import sys
def anagram(a, b):
if len(a) != len(b):
return False
matches = 0
for letter in a:
try:
b.index(letter)
except ValueError:
return False
else:
matches += 1
return matches == len(a)
def has_anagrams(phrase):
for i, p in enumerate(phrase):
for x in range(len(phrase)-1, i, -1):
if anagram(p, phrase[x]):
return True
return False
def valid_passcodes(codes):
num_valid_passcodes = 0
for code in codes:
phrase = code.split()
phrase_set = set(phrase)
if len(phrase) == len(phrase_set):
if not has_anagrams(phrase):
num_valid_passcodes += 1
return num_valid_passcodes
if __name__ == '__main__':
if len(sys.argv) != 2:
print('Usage:')
print('\tpython anagrams.py input.txt')
else:
with open(sys.argv[1]) as f:
print(valid_passcodes(f.readlines()))
|
f734417e2b85abbc67197a34d7b2c5d1f38421cd | saubhagyav/100_Days_Code_Challenge | /DAYS/Day20/Sort_Dictionary_Keys_and_Values_List.py | 275 | 3.859375 | 4 | def Sort_Keys_and_Values(Test_dict):
return {key: sorted(Test_dict[key]) for key in sorted(Test_dict)}
Test_dict = {'Code': [7, 6, 3],
'Challenge': [2, 10, 3],
'is': [19, 4], 'Best': [18, 20, 7]}
print(Sort_Keys_and_Values(Test_dict))
|
00092bc605bd33fd1fde3539a2e94bc72754ea92 | Flood1993/ProjectEuler | /p108.py | 3,147 | 3.53125 | 4 | # yn + xn = xy
# given some n, how do we calculate how many solutions are there?
# n = xy / (x+y)
# Let's say n = 4
# there are 3 solutions
# 5,20
# 6,12
# 8,8
# x, y, n >= 0
# n=6. how many solutions?
# how many x, y, exist so that x*y/(x+y) == 6?
# x*y must be a multiple of n
# How many are there for n=7?
# I have to start with k=8, up to 15
# 7 = 8*1 / (8+1)
# 7 = 8*2 / (8+2)
# 7 = 8*4 / (8+4)
# given n, go from i=n+1, 2*n+1, and then, while not n*(x+y) <= x*y
# n*(x+y) = x*y
# given n and x, the value of y is
# nx + ny = xy
# nx = xy - ny
# nx = y(x - n)
# y = nx(x-n)
def sols(n):
result = 0
for x in range(n + 1, 2*n + 1):
y = n*x // (x-n)
if (x+y)*n == x*y:
result = result + 1
return result
print(sols(4))
# i = 30
# while True:
# sol_count = sols(i)
# # print(i, sol_count)
# if sol_count >= 1000:
# print('Found solution:', i)
# break
# i = i + 30
# if i > 10**6:
# break
x = 2*3
print(x, sols(x))
x = 2*3*5
print(x, sols(x))
x = 2*3*5*7
print(x, sols(x))
x = 2*3*5*7*11
print(x, sols(x))
x = 2*3*5*7*11*13
print(x, sols(x))
x = 2*3*5*7*11*13*17
print(x, sols(x))
x=502320
print(x, sols(x))
# for i in range(277198, 200000, -2):
# s = sols(i)
# if s >= 1000:
# print(i, s)
# break
# 502320 is not the solution either, even though it has more than 1000
# 120 32, 2**3 * 3 * 5, seems to be 4 * 2 * 2 =
# 128 8, 2**7 = 8 -> 7 + 1
# 300 38, 2**2 * 3 * 5**2
# 498960 -> 1094, 2 * 2 * 2 * 2 * 3 * 3 * 3 * 3 * 5 * 7 * 11, 2**4 * 3**4 * 5 * 7 * 11 5 primes
# 510510 -> 1094, 2 * 3 * 5 * 7 * 11 * 13 * 17, 2 * 3 * 5 * 7 * 11 * 13 * 17 7 primes
# 502320 -> 1094, 2 * 2 * 2 * 2 * 3 * 5 * 7 * 13 * 23 2**4 * 3 * 5 * 7 * 13 * 23 6 primes
# 371280 -> 1094, 2 * 2 * 2 * 2 * 3 * 5 * 7 * 13 * 17
# 327600 -> 1013, 2 * 2 * 2 * 2 * 3 * 3 * 5 * 5 * 7 * 13
# 277200 -> 1013, 2 * 2 * 2 * 2 * 3 * 3 * 5 * 5 * 7 * 11
x = 2 * 2 * 2 * 2 * 3 * 3 * 5 * 5 * 7 * 11
print(x, sols(x))
x = 2 * 2 * 2 * 2 * 2 * 2 * 3 * 3 * 5 * 7 * 11
print(x, sols(x))
for two_exp in range(0, 7):
twos = 2**two_exp
if twos >= 277200:
break
for three_exp in range(0, 7):
threes = 3**three_exp
if twos*threes >= 277200:
break
for five_exp in range(0, 7):
fives = 5**five_exp
if twos*threes*fives >= 277200:
break
for seven_exp in range(0, 7):
sevens = 7**seven_exp
if twos*threes*fives*sevens >= 277200:
break
for eleven_exp in range(0, 7):
elevens = 11**eleven_exp
if twos*threes*fives*sevens*elevens >= 277200:
break
for thirteen_exp in range(0, 7):
cand = twos*threes*fives*sevens*elevens*13**thirteen_exp
if cand >= 277200:
break
s = sols(cand)
if s >= 1000:
print(cand, s)
|
30f651179204f233190ebdbd7b79dd62678db72c | Krenair/cryptopals | /set2/challenge9.py | 306 | 3.75 | 4 | def pad(pt, block_length):
padding_length = block_length - (len(pt) % block_length)
return pt + (padding_length * chr(padding_length).encode('ascii'))
if __name__ == "__main__":
input = b"YELLOW SUBMARINE", 20
output = pad(*input)
print('output', output)
print('len', len(output))
|
76268472a17fe750a6406dfc5a05165e3055b489 | vikramlance/Python-Programming | /Leetcode/problems/problem0102_binary_tree_level_order_traversal.py | 1,198 | 4.09375 | 4 | """
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
"""
from collections import deque
class solution:
def bfs(self, arr):
result = []
temp_queue = deque()
temp_queue.append(arr[0])
i = 0
while temp_queue:
current_level_list = []
curr_size_temp_queue = len(temp_queue)
for j in range(curr_size_temp_queue):
current_node = temp_queue.popleft()
# add children of current node to queue
current_level_list.append(current_node)
if (2 * i + 1) < len(arr) and arr[2 * i + 1]:
temp_queue.append(arr[2 * i + 1])
if (2 * i + 2) < len(arr) and arr[2 * i + 2]:
temp_queue.append(arr[2 * i + 2])
i += 1
result.append(current_level_list)
return result
arr = [3, 9, 20, None, None, 15, 7]
test = solution()
print(test.bfs(arr))
|
fe20f74ca7e554b8f23166297c379a59a822d0e3 | lshicks13/adventofcode2019 | /day3.py | 1,880 | 3.625 | 4 |
#Read in the directions from the file and separate them into 2 paths
def get_paths(txtfile):
with open(txtfile) as f:
f = f.read().splitlines()
path1 = f[0].split(',')
path2 = f[1].split(',')
return path1, path2
# Get all the points from the given paths
def get_points(path):
step = 1
i = j = k = 0
points = {}
while i < len(path):
x = y = 0
direction = path[i][:1]
distance = int(path[i][1:])
if direction == 'R':
x = 1
elif direction == 'L':
x = -1
elif direction == 'U':
y = 1
elif direction == 'D':
y = -1
for _ in range(distance):
j += x
k += y
points[step] = (j,k)
step += 1
i += 1
return points
# Get the shared points from the paths
def get_intersections(pts1, pts2):
sh_pts = {}
for a in pts1:
for b in pts2:
if pts1[a] == pts2[b]:
sh_pts[a + b] = pts1[a]
min_key = min(sh_pts.keys())
sh_pts = list(sh_pts.values())
return sh_pts, min_key
# Get the manhattan distance for each of the shared points
# and return the shortest distance
def manhattan_distance(pts):
i = 0
mdist = {}
while i < len(pts):
mdist[i] = abs(0 - int(pts[i][0])) + abs(0 - int(pts[i][1]))
i += 1
smd = list(mdist.values())
md = min(smd)
return md
def main():
path1, path2 = get_paths('paths2.txt')
pts1 = get_points(path1)
#print('this is path 1 pts\n', pts1)
pts2 = get_points(path2)
#print('this is path 2 pts\n', pts2)
shrd_pts, min_key = get_intersections(pts1,pts2)
print('Intersecting Points:\n', shrd_pts)
print('Manhattan Distance:\n', manhattan_distance(shrd_pts))
print('Fewest Combined Steps to Intersection:\n', min_key)
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.