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 |
|---|---|---|---|---|---|---|
b62bbb3645ca5728cb7dea90bb172a157a3b6084 | blguru20/PythonBasics | /PythonPractice/while/whileloop.py | 121 | 3.703125 | 4 | lst = [1,2,9,3,7];
index = 0;
product = 1;
while index < len(lst) :
product*=lst[index];
index+=1;
print(product);
|
3fff6117197d24bffcbaeead68772a9e5b628f4d | ywcmaike/OJ_Implement_Python | /leetcode/543. 二叉树的直径.py | 1,037 | 3.90625 | 4 | # author: weicai ye
# email: yeweicai@zju.edu.cn
# datetime: 2020/7/27 上午9:51
# 给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。
#
#
#
# 示例 :
# 给定二叉树
#
# 1
# / \
# 2 3
# / \
# 4 5
# 返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。
#
#
#
# 注意:两结点之间的路径长度是以它们之间边的数目表示。
#
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/diameter-of-binary-tree
# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
from typing import List
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
if __name__ == "__main__":
pass |
0021c7548aaa3d61685fc364ded25f607cde193b | TonsOfFunn/Py7h0n | /TCP/TCP_Server.py | 1,054 | 3.53125 | 4 | import socket
import threading
# constants
BIND_IP = "127.0.0.1"
BIND_PORT = 9999
# create server socket object from socket class
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# bind server socket object with IP(public host) & PORT
server.bind((BIND_IP, BIND_PORT))
# server socket object listens up to 5 connect requests
server.listen(5)
# display bound IP & PORT
print("[*] Listening on %s:%d" % (BIND_IP, BIND_PORT))
# this is our client-handling thread
def handle_client(client_socket):
# print out what the client sends
request = client_socket.recv(1024)
print("[*] Received: %s" % request)
# send back a packet
client_socket.send("ACK!")
# close client_socket object connection
client_socket.close()
# main()
while True:
client, addr = server.accept()
print("[*] Accepted connection from: %s:%d" % (addr[0], addr[1]))
# spin up our client thread to handle incoming data
client_handler = threading.Thread(target=handle_client, args=(client,))
client_handler.start()
|
db19cfcb078c465e52473648face80e1c17888e7 | DuDaria/Homework_backend | /lesson_5/hw05_hard.py | 3,616 | 4.40625 | 4 | # Задание-1:
# Матрицы в питоне реализуются в виде вложенных списков:
# Пример. Дано:
matrix = [[1, 0, 8],
[3, 4, 1],
[0, 4, 2]]
print("matrix:")
for line in matrix:
print(line)
# Выполнить поворот (транспонирование) матрицы
# Пример. Результат:
# matrix_rotate = [[1, 3, 0],
# [0, 4, 4],
# [8, 1, 2]]
# Суть сложности hard: Решите задачу в одну строку
# Решение
rotate_matrix = list(map(list, zip(*matrix)))
print("rotate_matrix:")
for line in rotate_matrix:
print(line)
# Задание-2:
# Найдите наибольшее произведение пяти последовательных цифр в 1000-значном числе.
# Выведите произведение и индекс смещения первого числа последовательных 5-ти цифр.
# Пример 1000-значного числа:
import re
number = """
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450"""
number = re.sub("\n", '', number)
list_number = []
for i in range(0, len(number)-4):
num_from_5 = list((number)[i:i+5])
num = 1
for x in num_from_5:
num *= int(x)
list_number.append(num)
print("Наибольшее произведение пяти последовательных цифр = {}".format(max(list_number)))
# Задание-3 (Ферзи):
# Известно, что на доске 8×8 можно расставить 8 ферзей так, чтобы они не били
# друг друга. Вам дана расстановка 8 ферзей на доске.
# Определите, есть ли среди них пара бьющих друг друга.
# Программа получает на вход восемь пар чисел,
# каждое число от 1 до 8 — координаты 8 ферзей.
# Если ферзи не бьют друг друга, выведите слово NO, иначе выведите YES.
coords_queens = [[1, 7], [2, 4], [3, 2], [4, 8], [5, 6], [6, 1], [7, 3], [8, 5]]
n = 8
for i in coords_queens:
x = i[0]
y = i[1]
x = []
y = []
for i in range(n):
new_x, new_y = x, y
x.append(new_x)
y.append(new_y)
correct = True
for i in range(n):
for j in range(i + 1, n):
if x[i] == x[j] or y[i] == y[j] or abs(x[i] - x[j]) == abs(y[i] - y[j]):
correct = False
if correct:
print('NO')
else:
print('YES')
|
2797a9b5b41196c943df61f7367180c47d12b4fe | markabhiroop/Mark-2 | /sum.py | 75 | 3.859375 | 4 | n=int(input(""))
sum=0
for num in range(1,1+n):
sum=sum+num
print(sum)
|
3897e9175ff40d3708a06b1968f8a871a42359b4 | SamarQuadri/Game | /code.py | 1,115 | 3.765625 | 4 | import random
while True:
user_inp = int(input("Give a input. Press '1' for stone, '2' for paper and '3' for scissor.\n"))
comp_inp = random.randrange(1, 4)
if user_inp == 1:
if comp_inp == 1:
print(f"You: Stone\nComputer: Stone.\nIts a draw")
elif comp_inp == 2:
print(f"You: Stone\nComputer: Paper.\nComputer won")
elif comp_inp == 3:
print(f"You: Stone\nComputer: Scissor.\nYou won.")
elif user_inp == 2:
if comp_inp == 1:
print(f"You: Paper\nComputer: Stone.\nYou won")
elif comp_inp == 2:
print(f"You: Paper\nComputer: Paper.\nIts a draw")
elif comp_inp == 3:
print(f"You: Paper\nComputer: Scissor.\nComputer won")
elif user_inp == 3:
if comp_inp == 1:
print(f"You: Scissor\nComputer: Stone.\nComputer won")
elif comp_inp == 2:
print(f"You: Scissor\nComputer: Paper.\nYou won")
elif comp_inp == 3:
print(f"You: Scissor\nComputer: Scissor.\nIts a draw")
else:
print(f"Please input a correct number") |
10691e286b7bc0d35374355e5d7e1df353bd787f | eltonjncorreia/praticando-python | /soma-numeros.py | 203 | 3.921875 | 4 | n1=int(input("Hello, Informe um numero para somar"))
n2=int(input("Hello, sou eu novamente, digite mais um numero"))
s=n1+n2
print("Olá, vamos ver o resultado de {} + {} que soma: {}".format(n1,n2,s)) |
cea58645860eca3e1b84f1d3992f0c716f3ac572 | adafruit/circuitpython | /tests/basics/builtin_getattr.py | 615 | 3.625 | 4 | class A:
var = 132
def __init__(self):
self.var2 = 34
def meth(self, i):
return 42 + i
a = A()
print(getattr(a, "var"))
print(getattr(a, "var2"))
print(getattr(a, "meth")(5))
print(getattr(a, "_none_such", 123))
print(getattr(list, "foo", 456))
print(getattr(a, "va" + "r2"))
# test a class that defines __getattr__ and may raise AttributeError
class B:
def __getattr__(self, attr):
if attr == "a":
return attr
else:
raise AttributeError
b = B()
print(getattr(b, "a"))
print(getattr(b, "a", "default"))
print(getattr(b, "b", "default"))
|
69062f784da3178e4d381a8724e6fafe71707fd7 | OwainWilliams/Python | /MoshHamedaniCourse/random.py | 183 | 3.6875 | 4 | import random
for i in range(3):
print(random.random())
print(random.randint(10,20))
members = ['Tony', 'Hulk', 'Steve', 'Natasha', 'Thor']
print(random.choice(members))
|
ae6a889a0c104ae52a999061944726fd016d107e | sebasgarri/Python | /Unidad 2/Ejercitario 2/Ejercicio4.py | 173 | 4.1875 | 4 | """Escribir un programa que visualice en pantalla los números pares entre 1 y 25 """
for x in range(26):
if x%2==0:
print(x)
else:
print("")
|
b5eb6798e91e5c3ac92c2d8d1df6e72af403a2d0 | najarvis/PyAssemble | /main.py | 6,230 | 3.734375 | 4 | import sys
memory = []
pointer = 0x00
registers = {0x00: 0,
0x01: 0,
0x02: 0,
0x03: 0} # Registers A - D
FLAG_FINISHED = False
def NOP():
global pointer, memory
pointer += 0x01
def ADD():
""" Add a value to a register
Syntax: ADD [value] [register]
"""
global pointer, memory, registers
registers[memory[pointer + 0x02]] += memory[pointer + 0x01]
pointer += 0x03
def SUB():
""" Subtract a value to a register
Syntax: SUB [value] [register]
"""
global pointer, memory, registers
registers[memory[pointer + 0x02]] -= memory[pointer + 0x01]
pointer += 0x03
def GET():
""" Get value from a register, put in memory location
Syntax: GET [register] [memory location]
"""
global pointer, memory, registers
memory[memory[pointer + 0x02]] = registers[memory[pointer + 0x01]]
pointer += 0x03
def MOV():
""" SET [value] [memory address]"""
global pointer, memory, registers
memory[memory[pointer + 0x02]] = memory[pointer + 0x01]
pointer += 0x03
def OUT():
""" OUT [memory address] """
global pointer, memory, registers
print( chr( memory[memory[pointer + 0x01]] ), end='')
pointer += 0x02
def END():
global pointer, memory, FLAG_FINISHED
FLAG_FINISHED = True
def JMP():
""" Moves the pointer to a point in memory.
Syntax: JMP [memory address]
"""
global pointer, memory
pointer = memory[pointer + 0x02]
def JEZ():
""" Jump if register is 0
Syntax: JEZ [register] [Jump location]
"""
global pointer, memory, registers
if registers[memory[pointer + 0x01]] == 0:
pointer = memory[pointer + 0x02]
return
pointer += 0x03
def JNZ():
""" Jump if register is NOT 0
Syntax: JNZ [register] [jump location]
"""
global pointer, memory, registers
if registers[memory[pointer + 0x01]] != 0:
pointer = memory[pointer + 0x02]
return
pointer += 0x03
def SWP():
""" Swap value of two registers
Syntax: SWP [register from] [register to]
"""
global pointer, memory, registers
tmp = registers[memory[pointer + 0x02]]
registers[memory[pointer + 0x02]] = registers[memory[pointer + 0x01]]
registers[memory[pointer + 0x01]] = tmp
pointer += 0x03
def SLR():
""" Shift left value in a register
Syntax: SLR [amount] [register]
"""
global pointer, memory, registers
registers[memory[pointer + 0x02]] = registers[memory[pointer + 0x02]] << memory[pointer + 0x01]
pointer += 0x03
def SRR():
""" Shift right value in a register
Syntax: SLR [amount] [register]
"""
global pointer, memory, registers
registers[memory[pointer + 0x02]] = registers[memory[pointer + 0x02]] >> memory[pointer + 0x01]
pointer += 0x03
def INT():
""" Print out a value as a decimal integer
Syntax: INT [memory address]
"""
global pointer, memory
print(memory[memory[pointer + 0x01]], end='')
pointer += 0x02
def run(program="alphabet.pas"):
global pointer, memory, FLAG_FINISHED
memory = [0x00 for i in range(0x100)]
pointer = 0x00
command_map = {0x00: NOP,
0x01: OUT,
0x02: ADD,
0x03: SUB,
0x04: MOV,
0x05: JMP,
0x06: JEZ,
0x07: JNZ,
0x08: GET,
0x09: SWP,
0x0a: SLR,
0x0b: SRR,
0x0c: INT,
0xff: END}
# memory = load_program(""" $ Alphabet Printer Program
# 02 1a 00 $ ADD 26 A Register A Keeps track of how many letters we have left
# 02 41 01 $ ADD 'A' B Register B keeps track of what letter we are on
# 08 01 f0 $ GET B f0
# 01 f0 $ OUT f0
# 03 01 00 $ SUB 1 A
# 02 01 01 $ ADD 1 B
# 07 00 06 $ JNZ A 06
# ff $ END
# """)
#memory = load_program_file("alphabet.pas")
memory = load_program_file(program)
print()
pretty_print_memory()
print()
FLAG_FINISHED = False
print("Code Output:")
while not FLAG_FINISHED:
#print(command_map[memory[pointer]].__name__)
command_map[memory[pointer]]()
if pointer == len(memory):
FLAG_FINISHED = True
print()
print("DONE")
print()
pretty_print_memory()
print()
def load_program(program: str):
memory = [0x00 for i in range(0x100)]
input_list = list(program)
program_list = []
COMMENT_FLAG = False
for bit in input_list[:]:
if bit == '$':
COMMENT_FLAG = True
if bit == '\n':
COMMENT_FLAG = False
if bit not in '0123456789abcdef' or COMMENT_FLAG:
#print(bit, end='')
pass
else:
program_list.append(bit)
# Don't want to overflow the memory!
if len(program_list) > len(memory):
raise ValueError
# Changes ['0', 'f', '1', '4', 'b', '1', '5', '3' ...] into ['0f', '14', 'b1', '53', ...]
final_list = ["".join(program_list[i:i+2]) for i in range(0, len(program_list), 2)]
for bit_index in range(len(final_list)):
memory[bit_index] = int(final_list[bit_index], 16)
return memory
def load_program_file(filename: str):
program_string = ""
with open(filename, 'r') as program_file:
program_string = "".join(program_file.read())
print(program_string)
return load_program(program_string)
def pretty_print_memory():
global memory, registers
print ("CURRENT MEMORY")
for i in range(len(memory)):
print('{0:5}'.format('0x' + hex(memory[i])[2:].zfill(2)), end=' ')
if (i + 1) % 0x10 == 0:
print()
print()
print("REGISTERS")
print("A: " + str(registers[0x00]))
print("B: " + str(registers[0x01]))
print("C: " + str(registers[0x02]))
print("D: " + str(registers[0x03]))
if __name__ == "__main__":
if len(sys.argv) > 1:
run(sys.argv[1])
else:
run()
|
f2f81c4a4c23188a51d9883b85170a7aa179020f | marcodotcastro/youtube-v10.0 | /bubblesorts/python/classes/bubble.py | 305 | 3.78125 | 4 | class Bubble:
def __init__(self, arr):
self.arr = arr
def sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr |
f038d98b4a9203a494bfd057ba67c6a1ef4b2c55 | angiereyes99/coding-interview-practice | /easy-problems/RemoveVowels.py | 771 | 3.765625 | 4 | class Solution:
def approach1(self, s: str) -> str:
newWrd = ""
for ch in s:
if (ch == 'A' or ch == 'a' or ch == 'E' or ch == 'e'
or ch == 'I' or ch == "i" or ch == "O" or ch == "o"
or ch == 'U' or ch == "u"):
pass
else:
newWrd = newWrd + ch
return newWrd
def approach2(self, s: str) -> str:
vowels = ('A', 'a', 'E', 'e', 'I', 'i', 'O', 'o', 'U', 'u')
for i in s:
for i in vowels:
s = s.replace(i, "")
return s
if __name__ == "__main__":
sol = Solution()
word = "Apple"
print(sol.approach1(word))
word2 = "AngELO REyes I am"
print(sol.approach2(word2)) |
b2c1e70f5dc88538e7ebf4b604a2826ccd15d105 | raj13aug/Python-learning | /Course/4-functions/debug.py | 315 | 3.9375 | 4 | def multiply(*numbers):
total = 1
for number in numbers:
total *= number
return total # debug the code
print("start")
print(multiply(1, 2, 3))
#Break point apply for code : press f9
#continous to execute the code: f10
#show the variable the problem : f11
shift + f11 -->
|
20959cbf33effcb01c07f176ab936bf77562e94a | bushschool/CS_CW | /ScoringTheGame/Tutorials/CamelGame.py | 4,127 | 4.125 | 4 | import random
def instructions():
print 'Welcome to Camel!'
print 'You have stolen a camel to make your way across the great Mobi desert.'
print 'The natives want their camel back and are chasing you down! Survive your'
print 'desert trek and out run the natives.'
Camel()
def Camel():
milesTraveled = 0
thirst = 0
camelTiredness = 0
nativeDistance = 20
drinksLeft = 3
done = False
oasisNumber = random.randint(0,19)
while done == False:
print 'A: Drink from your canteen.'
print 'B: Ahead moderate speed.'
print 'C: Ahead full speed.'
print 'D: Stop for the night.'
print 'E: Status check.'
print 'Q: Quit.'
print ' '
choice = raw_input('Select an option: A, B, C, D, E, or Q: ')
choice = choice.upper()
print ' '
MaybeOasis = random.randint(0,19)
if MaybeOasis == oasisNumber:
print 'You have found an Oasis. Your water has been refilled'
print ' '
drinksLeft = 3
thirst = 0
camelTiredness = 0
if choice == 'A':
if drinksLeft > 0:
drinksLeft = drinksLeft - 1
thirst = 0
print 'Drinks left in your canteen: ', drinksLeft
print ' '
else:
print 'None left.. Try something else'
print ' '
elif choice == 'B':
distanceB = random.randint(5,12)
milesTraveled = milesTraveled + distanceB
camelTiredness = camelTiredness + 1
thirst = thirst + 1
nativeDistance = nativeDistance - random.randint(7,14) + distanceB
print 'you traveled ', distanceB, ' miles'
print ' '
elif choice == 'C':
distanceC = random.randint(10,20)
camelTiredness = camelTiredness + random.randint(1,3)
milesTraveled = milesTraveled + distanceC
thirst = thirst + 1
nativeDistance = nativeDistance - random.randint(7,14) + distanceC
print 'you traveled ', distanceC, ' miles'
print ' '
elif choice == 'D':
camelTiredness = 0
nativeDistance = nativeDistance - random.randint(7,14)
print 'The camel is happy and energized'
print ' '
elif choice == 'E':
print 'Miles traveled: ', milesTraveled
print 'Drinks left in canteen: ', drinksLeft
print 'The natives are ', nativeDistance, ' miles behind you.'
print ' '
elif choice == 'Q':
done = True
elif choice not in ['A','B','C','D','E','Q']:
"Next time, please choose one of the options."
print ' '
if camelTiredness > 5 and camelTiredness <= 8:
print 'Your camel is tired. If you do not rest him soon, he will die.'
print ' '
elif camelTiredness > 8:
print 'You overworked your camel and he died.'
print ' '
print 'Game Over'
done = True
if thirst > 4 and thirst <=6 and done == False:
print 'You are thirsty. If you do not drink from your canteen soon, you will die.'
print ' '
elif thirst > 6 and done == False:
print 'You died of thirst.'
print ' '
print 'Game Over'
done = True
if nativeDistance <= 0 and done == False:
print 'The natives caught you!'
print ' '
print 'Game Over'
done = True
elif nativeDistance < 10 and done == False:
print 'the natives are getting close'
print ' '
if milesTraveled >= 200:
print 'You Win!'
done = True
if done == True:
playAgain()
def playAgain():
print ' '
userChoice = raw_input('Would you like to play again? ')
userChoice = userChoice.upper()
if userChoice == 'YES':
Camel()
elif userChoice == 'NO':
print 'Bye'
instructions()
|
cbc60c5ae9a807827dc881ff25bab52d33af8b6e | azindyr/azindyr | /ex031.py | 553 | 3.78125 | 4 | from time import sleep
print('=' * 15, 'Exercício 31', '=' * 15)
print('A passagem será calculada da seguinte forma: até 200km será cobrado R$0,50 por km, '
'acima disso o preço por km é R$0,45')
km = float(input('Digite a distância(em km) da viagem: '))
passagem = km * 0.50
print('Calculando preço...')
sleep(1.5)
if km > 200:
passagem = km * 0.45
print('Como a viagem é maior do que 200 km, o valor da passagem fica R${:.2f}.'.format(passagem))
else:
print('O valor da passagem é R${:.2f}.'.format(passagem))
|
d200594792094888426ca7ca33926d65060e794b | tocoloko/liquid | /controller/util.py | 656 | 3.5 | 4 | import pandas as pd
class util:
def dict_to_pd(datas, code):
price = []
size = []
code = []
for data in datas:
price.append(float(data['price']))
size.append(float(data['size']))
code.append(code)
vals = pd.DataFrame([price, size, code]).T
vals.columns = ["price", "size", "code"]
return vals
def list_to_pd(datas):
price = []
size = []
for data in datas:
price.append(data[0])
size.append(data[1])
vals = pd.DataFrame([price, size]).T
vals.columns = ["price", "size"]
return vals |
fac465476c987c11071d45b1c87bd742cefa5ef1 | Teed21/Excel_Planner | /ExcelPlanner.py | 13,714 | 3.515625 | 4 | # Written and Developed by: Tyler Wright
# Date started: 02/05/2019
# Date when workable: 03/21/2019
# Last Updated: 04/26/2019
"""
This class file is meant to operate as a median between ExcelReader and ExcelWriter.
It will handle multiple CP values, instead of handling simply one run-through. It will also
help keep track of any data specific to the overall request.
This class also creates individual CPs based on information pulled from ExcelReader. These CPs
should then be stored in a list, later to be called upon to conglomerate their information into
something that ExcelWriter can read and understand.
This class also hosts a GUI. The desired outcome is to have this be a much easier interface to
use and understand. Notes will be displayed in a text box for the user to watch and monitor the
program to make sure everything is working as planned. -- This was not added. Deemed unnecessary.
Find out how to put spaces between stations in new file.
"""
import ExcelReader
import ExcelWriter
import ExcelCP
class ExcelPlanner:
def __init__(self, excel_file):
# This variable is the excel file name to open.
self.excel_file = excel_file
# This if statement helps skip the constructor if need be. - Mainly used to write to new excel file.
if excel_file == "new":
print("Creating new excel file...")
else:
# This variable is the object that controls all information from ExcelReader.py that is necessary to
# mediate everything in this class file. Opening the excel file, getting the text data, etc.
self.excel_reader_obj = ExcelReader.ExcelReader(excel_file)
# This variable is a global workbook. It is meant to be used throughout the class as a way to
# reference the workbook opened for the current task of copying from and pasting to a new workbook/file.
self.glb_workbook = self.excel_reader_obj.create_workbook()
# This variable grabs the relevant sheet.
self.glb_sheet = self.excel_reader_obj.create_worksheet(self.glb_workbook)
# This variable grabs the relevant text data from the sheet.
self.glb_data = self.excel_reader_obj.read_excel_document(self.glb_sheet)
# This global variable holds all format information for the data sheet.
self.glb_format_data = self.excel_reader_obj.get_excel_format_data()
# These lists are meant for putting spaces in between CP stations in the new Excel file.
self.space_text = ["", "", "", "", "", "", "", "", "", "", "", ""]
self.space_format = [["regular", ["Top"]], ["regular", ["Top"]], ["regular", ["Top"]], ["regular", ["Top"]],
["regular", ["Top"]], ["regular", ["Top"]], ["regular", ["Top"]], ["regular", ["Top"]],
["regular", ["Top"]], ["regular", ["Top"]], ["regular", ["Top"]], ["regular", ["Top"]]]
# This function gets all codeline information and combines it into one.
def get_codeline_info(self):
codeline_text = self.excel_reader_obj.copy_codeline_text_info(self.glb_data)
codeline_format = self.excel_reader_obj.copy_codeline_format_info(self.glb_format_data)
return [codeline_text, codeline_format]
# This function checks if a CP exists before appending to any lists or permanent data structures.
# This will cleanse any non-sense in regards to invalid CP names in later data.
def check_if_cp_exists(self, cp_name):
is_cp = self.excel_reader_obj.find_cp(self.glb_data, cp_name)
return is_cp
# This function returns all possible cp names in the selected excel file.
def get_cp_names(self):
cp_names = self.excel_reader_obj.get_cp_names()
return cp_names
# This function passes over a list of CPs required to be copied over to a new sheet. Getting all relevant
# information from them and storing it in a large list.
# When processing this list, remember to count whether or not this is a "full change" with a strike-out and bold
# version of the station. This is important for copying old and new text and format information later on.
def get_cp_cords(self, cp_list):
list_of_cp_cords = []
list_of_cp_names = []
for cp in cp_list:
list_of_cp_cords.append(self.excel_reader_obj.find_cp(self.glb_data, cp))
list_of_cp_names.append(self.excel_reader_obj.get_cp_name())
return list_of_cp_cords, list_of_cp_names
# Creates a CP object by using the coordinates from get_all_cp_information and processing information from
# ExcelReader based on those coordinates.
def create_cp_object(self, coordinates, cp_name, occurrences):
# Collect data from collect_data_about_cp - this will set the class var "rows" for each coordinate.
# This will help produce relevant information (text and formatting) for each CP.
self.excel_reader_obj.collect_data_about_cp(self.glb_data, coordinates)
# Get CP name.
cp_name = cp_name
# Get CP coordinates
cp_coordinates = coordinates
# Get CP station address
cp_station_address = self.excel_reader_obj.get_station_address()
# Set rows for specific CP
rows = self.excel_reader_obj.get_station_rows()
# Copy station text for specific CP
cp_text_data = self.excel_reader_obj.copy_cp_station(self.glb_data, rows)
# Copy station font/format for specific CP
cp_font_data = self.excel_reader_obj.copy_cp_station_font_info(rows, self.glb_sheet)
if occurrences == 1:
text_list_bold = []
format_list_bold = []
iteration = 0
for row in range(len(cp_text_data)):
iteration += 1
# Catch blank spot meant to separate differing CPs.
if len(cp_text_data[row]) <= 1 and "" in cp_text_data[row]:
# Split at one occurrence.
break
# Append strike_rows to new list.
text_list_bold.append(cp_text_data[row])
# Adding blank spacing to text list.
text_list_bold.append(self.space_text)
iteration = 0
for row in range(len(cp_font_data)):
iteration += 1
# Catch blank spot meant to separate differing CPs.
if len(cp_font_data[row]) <= 1 and "" in cp_font_data[row]:
# Split at one occurrence.
break
# Append strike_rows to new list.
format_list_bold.append(cp_font_data[row])
# Adds a blank in the format list to line up with the text lists.
format_list_bold.append(self.space_format)
# Setting font type to 's' for single.
font_type = "s"
# Create cp object.
cp_object = ExcelCP.ExcelCP(cp_name, cp_coordinates, font_type, cp_station_address, "N/A",
"N/A", text_list_bold, format_list_bold)
elif occurrences == 2:
# Setting font type to 'b' for both.
font_type = "b"
# Setting lists to split information into.
text_list_strike = []
text_list_bold = []
format_list_strike = []
format_list_bold = []
iteration = 0
# For every row in the cp_text_data.
for row in range(len(cp_text_data)):
iteration += 1
# Catch blank spot meant to separate differing CPs.
if len(cp_text_data[row]) <= 1 and "" in cp_text_data[row]:
# Split at one occurrence.
break
# Append strike_rows to new list.
text_list_strike.append(cp_text_data[row])
# This line ensures that there are spaces between all CPs in the new Excel file.
# Append a blank to new bold list, ensuring spaces between CPs.
text_list_strike.append(self.space_text)
# Appends the rest of the main cp text data into the last list.
for row in range(iteration, len(cp_text_data)):
text_list_bold.append(cp_text_data[row])
# This line ensures that there are spaces between all CPs in the new Excel file.
# Append a blank to new bold list, ensuring spaces between CPs.
text_list_bold.append(self.space_text)
iteration = 0
# For every row in the cp_text_data.
for row in range(len(cp_font_data)):
iteration += 1
# Catch blank spot meant to separate differing CPs.
if len(cp_font_data[row]) <= 1 and "" in cp_font_data[row]:
# Split at one occurrence.
break
# Append strike_rows to new list.
format_list_strike.append(cp_font_data[row])
# Adds a blank in the format list to line up with the text lists.
format_list_strike.append(self.space_format)
# Appends the rest of the main cp font data into the last list.
for row in range(iteration, len(cp_font_data)):
format_list_bold.append(cp_font_data[row])
# Adds a blank in the format list to line up with the text lists.
format_list_bold.append(self.space_format)
# Create cp object.
cp_object = ExcelCP.ExcelCP(cp_name, cp_coordinates, font_type, cp_station_address, text_list_strike,
format_list_strike, text_list_bold, format_list_bold)
else:
print("Occurrences in ExcelPlanner.create_cp_object not set.")
cp_object = ""
return cp_object
# This function helps create multiple CP objects based on coordinates and cp names.
# Returns a list of all objects for later use.
def get_all_cp_information(self, list_of_cp_cords, list_of_cp_names):
# This list will hold all objects created from this function. This is to be returned at the end of function.
list_of_cp_objects = []
iteration = 0
# This will go through each pair of coordinates and find relevant data for each CP.
# This will produce either one CP record, or two if one is strike-through and one is bold.
for cords in list_of_cp_cords:
# Will find if there is only one occurrence of CP. If so, only send through one list of information.
if len(cords) <= 1:
# print("One occurrence of CP")
list_of_cp_objects.append(self.create_cp_object(cords, list_of_cp_names[iteration], 1))
else:
list_of_cp_objects.append(self.create_cp_object(cords, list_of_cp_names[iteration], 2))
iteration += 1
# Resetting list of rows class variable in ExcelReader - prevents issue where rows keep incrementing for
# each cp in the list thrown through. It messes up code inside ExcelReader for whatever reason and I can't
# be bothered to find out why it's happening. This is the quick and dirty solution.
del self.excel_reader_obj.list_of_rows[:] # This sets the list to a blank string.
return list_of_cp_objects
# This function will "format" all the CP information into the standardized COMPANY_NAME practices.
# Then it will write to the new excel file.
def process_and_write_all_cp_information(self, combined_information, new_file):
# Write to new excel file.
# ExcelWriter object to write to new excel file.
writer = ExcelWriter.ExcelWriter(combined_information[0], combined_information[1], new_file)
writer.write_to_excel()
return 0
# This function returns two lists of the combined cp information, text and formatting.
def return_combined_lists(self, list_of_cp_objects):
# Main lists to send to ExcelWriter
strike_text_list = []
strike_format_list = []
bold_text_list = []
bold_format_list = []
# Put all strike text and bold text together respectively.
for cp in list_of_cp_objects:
if cp.get_font_type() == "s" and "N/A" in cp.get_text_list_strike() \
and "N/A" in cp.get_format_list_strike():
bold_text_list += cp.get_text_list_bold()
bold_format_list += cp.get_format_list_bold()
elif cp.get_font_type() == "b" and "N/A" not in cp.get_text_list_strike() \
and "N/A" not in cp.get_format_list_strike():
strike_text_list += cp.get_text_list_strike()
strike_format_list += cp.get_format_list_strike()
bold_text_list += cp.get_text_list_bold()
bold_format_list += cp.get_format_list_bold()
else:
print("cp font_type variable not set correctly.")
# Combine text lists and format lists together for writing.
codeline_info = self.get_codeline_info()
combined_text = codeline_info[0] + bold_text_list + strike_text_list
combined_formatting = codeline_info[1] + bold_format_list + strike_format_list
return [combined_text, combined_formatting]
|
73fceddde3ac875ef9b51a60d5d13056299d139c | amitsng7/Leetcode | /Insertion Sort in Python.py | 730 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 30 11:29:31 2017
@author: Amit
"""
#Insertion Sort
def insertionSort(n):
input = n
for i in range(1, len(input)):
if input[i-1] > input[i]:
a=input[i]
input[i] = input[i-1]
input[i-1] = a
for j in reversed(range(1, i)):
if(input[j]<input[j-1]):
b=input[j-1]
input[j-1] = input[j]
input[j] = b
print(input)
insertionSort([14,33,27,10,5,35])
#or
def insertion(a):
for j in range(1,len(a)):
key=a[j]
i=j-1
while(i>=0 and a[i]>key):
a[i+1]=a[i]
i=i-1
a[i+1]=key
print(a)
insertion([5,4,3,2,1,6]) |
016c0b52ef50c631ad267c3e8f39e7573bc1a0f8 | DimitarPetrov77/py-course | /LoopsDemos/LoopsDemos/LeftAndRightSum.py | 310 | 3.640625 | 4 | n = int(input())
leftSum = 0
rightSum = 0
for i in range(1, 2*n+1):
currentNum = int(input())
if i <= n:
leftSum += currentNum
else:
rightSum += currentNum
if leftSum == rightSum:
print("Yes, sum = " + str(leftSum))
else:
print("No, diff = " + str(abs(leftSum-rightSum))) |
1c2a7e4a193045c0c13f3c46fbac20195afe7507 | Vith-MCB/Phyton---Curso-em-Video | /Cursoemvideo/Exercícios UFV/Lista 1/exer09 - Soma dos quadrados.py | 235 | 4 | 4 | import math
n1 = int(input('Informe um número: '))
n2 = int(input('Outro número: '))
n3 = int(input('Um terceiro número: '))
somaq = (pow(n1,2))+(pow(n2,2))+(pow(n3,2))
print('A soma dos quadrados dos números é: {}'.format(somaq)) |
0321f5fbea2c1fecbf4daa1d7ee86d4d4cb0d481 | laodearissaputra/algorithm-req-bithealth | /sorting/quicksort.py | 555 | 3.53125 | 4 | # python quicksort.py
def partition(data, esq, dir, pivot):
while(esq <= dir):
while(data[esq] < pivot):
esq+=1
while(data[dir] > pivot):
dir-=1
if(esq <= dir):
data[esq], data[dir] = data[dir], data[esq] # Swap
esq+=1
dir-=1
return esq
def quick_sort(data, esq, dir):
if(esq >= dir):
return
pivot = data[ int((esq + dir) / 2)]
index = partition(data, esq, dir, pivot)
quick_sort(data, esq, index-1)
quick_sort(data, index, dir)
|
1ec2296acd7b58e988fee435ca102db218de2166 | arapodaca96/proactive | /python/practice/character_input/main.py | 438 | 3.890625 | 4 | name = raw_input('Enter your name: ')
name = name[0].upper() + name[1:]
target_age = int(raw_input('Enter your target age: '))
current_age = int(raw_input('Enter your current age: '))
years_to_target_age = target_age - current_age
current_year = 2019
final_year = current_year + years_to_target_age
print name + ', you will be ' + str(target_age) + ' years old in ' + str(years_to_target_age) + ' years (in ' + str(final_year) + ')!'
|
fb447f47aa03f73744ff12558e53045317302bc7 | usfbelhadj/holbertonschool-higher_level_programming | /0x0B-python-input_output/2-read_lines.py | 413 | 3.9375 | 4 | #!/usr/bin/python3
'''read_lines Function'''
def read_lines(filename="", nb_lines=0):
'''read_lines: Reading lines
filename: Name of the file
nb_lines: Number Of The Line
'''
with open(filename, 'r', encoding='utf-8') as f:
if nb_lines <= 0:
print(f.read(), end='')
else:
for line in range(nb_lines):
print(f.readline(), end='')
|
7c7786c5424338fdc2845c296095c4022bcf2ba6 | Sewmini-18/python-programs | /min_max.py | 557 | 3.734375 | 4 | # find the minimum and maximum number
seq = []
# number inputs
n = int(input("Enter number of inputs : "))
for i in range(0, n):
nlist = int(input())
seq.append(nlist) # adding the inputs to the list
max = seq[0]
min = seq[0]
for i in range(1, n):
if max < seq[i]:
max = seq[i]
if min < seq[i]:
min = min
else:
max = max
min = seq[i]
print('max =' , max) # maximum number
print('min =' , min) # minimum number
|
f263cc94c9180b541cd21ffee3abfff202fd5519 | Audarya07/Daily-Flash-Codes | /Week6/Day2/Solutions/Python/prog4.py | 202 | 3.640625 | 4 | for i in range(5):
cnt=0
for j in range(5):
if i>j:
print(" ",end=" ")
cnt+=1
else:
print((i+cnt)*cnt,end=" ")
cnt+=1
print()
|
2fbf647b3730249393b2f2a0bf8d376f05a29ebe | kotprotiv/learn_python | /lesson2/ask_user.py | 532 | 3.5 | 4 | answers = {"привет": "И тебе привет!"
,"как дела": "Лучше всех"
,"пока": "Увидимся"}
def get_answer(question):
return answers.get(question.lower(), 'Я не понял!')
def ask_user():
while True:
user_input = input('Скажи что-нибудь: ')
answer = get_answer(user_input)
print(answer)
if answer == 'Увидимся':
break
try:
ask_user()
except KeyboardInterrupt:
print('\nКак жаль, что вы уходите!') |
20fcf56ba09e280d1d2c3557c39c39df7625c3bc | opentechschool-zurich/py-co-learning | /20-min-projects/underscore-capitalize/ale/main.py | 272 | 4.15625 | 4 | word = 'this_is_the_word'
output = ''
last_was_underscore = False
for c in word:
if c == '_':
last_was_underscore = True
elif last_was_underscore:
output += c.upper()
last_was_underscore = False
else:
output += c
print(output)
|
35fc55d5d78a0a833ae0e32c32978e8834a72724 | MoritzWillig/GenieInAGanzzahlAddierer | /src/datatypes/Boolean/BooleanType.py | 1,006 | 3.6875 | 4 | from ..DataType import DataType
from .BooleanInstance import BooleanInstance
class BooleanType(DataType):
def __init__(self):
super().__init__()
pass
def get_name(self):
return "boolean"
def create_instance(self):
return BooleanInstance(self)
def create_instance_with_value(self, value):
instance = self.create_instance()
instance.set_value(value)
return instance
def create_instance_with_config(self, value_str, config):
if value_str is not None:
value_str = value_str.lower()
if value_str == "true":
value = True
elif value_str == "false":
value = False
else:
raise Exception("Invalid boolean string")
else:
value = config["default"]
if not isinstance(value, bool):
raise Exception("Default value is not boolean")
return self.create_instance_with_value(value)
|
81fe89bcf9474fe03e14230a0c2ddc1ebe35ce82 | FAndersson/polynomials_on_simplices | /polynomials_on_simplices/calculus/error_measures.py | 2,293 | 3.8125 | 4 | """Functionality for computing the error between exact and approximate values."""
def absolute_error(x0, x):
"""
Compute absolute error between a value `x` and its expected value `x0`.
:param x0: Expected value.
:param x: Actual value.
:return: Absolute error between the actual and expected value.
:rtype: float
"""
return abs(x0 - x)
def relative_error(x0, x, zero_tol=1e-5):
"""
Compute relative error between a value `x` and its expected value `x0`.
:param x0: Expected value.
:param x: Actual value.
:param zero_tol: If x0 is smaller than this value, the absolute error is returned instead.
:return: Relative error between the actual and expected value.
:rtype: float
.. rubric:: Examples
>>> abs(relative_error(0.1, 0.4) - 3) < 1e-10
True
>>> abs(relative_error(0.4, 0.1) - 0.75) < 1e-10
True
For small values the absolute error is used
>>> abs(relative_error(1e-6, 1e-6 + 1e-12) - 1e-12) < 1e-20
True
"""
if abs(x0) > zero_tol:
return absolute_error(x0, x) / abs(x0)
return absolute_error(x0, x)
def relative_error_symmetric(x1, x2, zero_tol=1e-5):
r"""
Compute relative error between two values `x1` and `x2`.
.. note::
The :func:`relative_error` function is not symmetric, i.e. in general
`relative_error(a, b) != relative_error(b, a)`, which makes sense when comparing to a reference value. However
when just checking the error between two values (without one of them being more correct than the other) it makes
more sense with a symmetric error, which is what this function returns.
.. math:: \varepsilon = \frac{|x_1 - x_2|}{\max(|x_1|, |x_2|)}.
:param x1: First value.
:param x2: Second value.
:param zero_tol: If max(abs(x1), abs(x2)) is smaller than this value, the absolute error is returned instead.
:return: Relative error between the two values.
:rtype: float
.. rubric:: Examples
>>> relative_error_symmetric(0.1, 0.2)
0.5
>>> relative_error_symmetric(0.1, 0.2) == relative_error_symmetric(0.2, 0.1)
True
"""
denom = max(abs(x1), abs(x2))
if denom > zero_tol:
return absolute_error(x1, x2) / denom
return absolute_error(x1, x2)
|
332f2c289e9926b9d9f9fe19b56e8440696a20c1 | Darkcacht/Letni | /funcion2.py | 380 | 3.5625 | 4 | #! /usr/bin/python
#! coding: utf-8
import os
clear = lambda: os.system('clear')
clear()
salir = 2
while salir != 1:
def bisiesto():
a = input("Dime el año: ")
if a % 4 == 0 and a % 100 != 0 or a % 400 == 0:
print "El año",a,"es bisiesto."
else:
print "El año",a,"no es bisiesto."
salir = input("Desea salir del programa?:\n1.Si\n2.No\n-->")
bisiesto() |
ac5807601d45d4f350e0b0efb8cd2c7395d5eb3d | DDan7/CoffeeMachine | /Problems/Palindrome/task.py | 396 | 4.125 | 4 | user_input = input()
def palindrome(a):
backward = a[::-1]
if backward == a:
print("Palindrome")
else:
print("Not palindrome")
palindrome(user_input)
# def palindrome(a):
# backward = ''
# for i in a:
# backward += i
# if backward == a:
# print("Palindrome")
# else:
# print("Not palindrome")
#
#
# palindrome(user_input)
|
fe550073e2d99af768e06f6119ae16c3b7a70aae | terrantsh/Python-- | /first/hello.py | 658 | 3.953125 | 4 | #-*- coding = utf-8 -*-
#@Time : 2020/4/15 21:47
#@Author : Shanhe.Tan
#@File : hello.py
#@Software : PyCharm
#my first python program
print("hello world") #comment
'''
comment
a = 10
print("This is :", a)
'''
'''
#format output
age = 18
print("My age is %d \r\n" %age)
age += 1
print("My age is %d \r\n" %age)
age += 1
print("My age is %d \r\n" %age)
print("www","baidu","com", sep=".")
'''
'''
password = input("password:")
print("The password is ",password)
print(type(password))
print("the number is %s" %password)
'''
a = int("123")
print(type(a))
b = a + 100
print(b)
c = int(input("input:"))
print("input number: %d" %c) |
9182973acd9e8cd9d5d7a21b845af199c90613c4 | redundnt/InterviewPractice | /PracticeProblems/Cracking/RecursionDP/p6.py | 780 | 3.78125 | 4 | hanoiCounter = 0
def h( fst,snd,thrd, height):
global hanoiCounter
hanoiCounter += 1
show(fst,snd,thrd)
if height == 1:
assert len(thrd) == 0 or fst[-1] < thrd[-1]
thrd.append(fst.pop())
else:
h(fst,thrd,snd,height - 1) # Move height-1 tower to snd
thrd.append(fst.pop())
h(snd,fst,thrd, height - 1) # Move snd tower to thrd
def show(s,m,l):
print "s|",
print ",".join([str(x) for x in s])
print "m|",
print ",".join([str(x) for x in m])
print "l|",
print ",".join([str(x) for x in l])
print
def test(n=1):
global hanoiCounter
hanoiCounter = 0
a = range(n)[::-1]
b = []
c = []
h(a,b,c,n)
print "hanoiCounter = ", hanoiCounter
assert c == range(n)[::-1]
|
30a029edbfa9feb2e1125f89184e8e76c2f17bfb | ArielGobbato/Curso_Python | /2- Variables y Operadores/2-5- Operadores Lógicos.py | 370 | 3.96875 | 4 | # Operadores lógicos BOOLEANOS
# BOOLEANOS
# and "Y" (multipliación lógica)
# or "O" (suma lógica)
# not (negador cambia los operadores anteriores)
# PRIORIDAD
# 1 NOT
# 2 AND
# 3 OR
a = 10
b= 12
c= 13
d = 10
resultado = ((a>b)or(a<c))and((a==c)or(a>=b))
print(resultado)
a = 10
b= 12
c= 13
d = 10
resultado = ((a>=b)or(a<c))or((a==c)or(a>=b))
print(resultado) |
5d0f0c5361d286b000371ca6c54b35ebabcfdb32 | OsProgramadores/op-desafios | /desafio-11/RecursiveError/python/Get_prime.py | 372 | 3.703125 | 4 | """função para gerar lista de numeros primos"""
def get_prime(limit: int):
"""retorna todos os numeros primos de 2 ate limit usando Crivo de Eratóstenes"""
_primes = []
for _num in range(2,limit+1, 1):
for _prime in _primes:
if _num % _prime == 0:
break
else:
_primes.append(_num)
return _primes
|
b77af661f65c384ff41dca0b21dd46fc167f5283 | liampboyle/FizzBuzz-Python | /fizzbuzz.py | 362 | 3.78125 | 4 | ## Liam Boyle
## 17 Jan 2012
## my five minute python solution to the fizz buzz test
## this would have been done in 2 min but it took me a sec to remember
## python syntax, I've been spending too much time in C++ I guess
for i in range (1, 101):
if i%3==0 and i%5==0:
print "FizzBuzz"
elif i%5==0:
print "Buzz"
elif i%3==0:
print "Fizz"
else:
print i
|
696c25f638794aca04e42a5c65c85782680bc462 | danielsimonebeira/cesusc-lista1 | /exe4.py | 699 | 4.0625 | 4 | # 4 - Faça um programa que receba um valor que é o valor pago, um segundo valor que
# é o preço do produto e retorne o troco a ser dado.
class Caixa:
def dar_troco(self, valor, produto):
if valor > produto:
troco = valor - produto
print('O troco é de R$ {}'.format(troco))
elif valor == produto:
print('Não é necessario dar troco.')
else:
cobrar = produto - valor
print("Valor é inferior ao preço do produto. Falta R$ {} para completar".format(cobrar))
caixa = Caixa()
pagar = float(input('Valor recebido: '))
preco_produto = float(input('Preço do produto: '))
caixa.dar_troco(pagar, preco_produto)
|
1c7bcde14ce4d41fc4be9d52641f2816689aaa78 | Aasthaengg/IBMdataset | /Python_codes/p03210/s916138087.py | 79 | 3.671875 | 4 | x = int(input()); y = [3,5,7]
if x in y:
print('YES')
else:
print('NO') |
963d1306a72ef1036187171ffde45257e20ce404 | TanviBagwe/ENC2020P1 | /Session35A.py | 757 | 3.71875 | 4 | import pandas as pd
import matplotlib.pyplot as plt
# https://seaborn.pydata.org/tutorial.html
import seaborn as sns
table = pd.read_csv("soccerdata.csv")
print(table)
print(table.head())
print(table.head(10))
# print(table["Name"])
print(table.Name)
# sns.countplot(y=table.Nationality, palette="Set2")
# sns.countplot(x="Age", data=table)
# sns.countplot(x="Nationality", data=table)
# plt.show()
# Case Study : Find the GoalKeeper who is best to stop the kicks :)
# Let us create some weights
w1 = 1
w2 = 2
w3 = 3
w4 = 4
table["BEST_GK"] = (w1*table.GK_Kicking + w2*table.GK_Diving + w3*table.GK_Positioning + w4*table.GK_Reflexes)
print(table["BEST_GK"])
sortedData = table.sort_values("BEST_GK")
print(sortedData)
print(sortedData.tail(10)) |
89ea73b827f504db5ad45d4ca18443e39bba5230 | gmsardane/Twitter_python | /gms_frequency.py | 858 | 3.53125 | 4 | import sys
import json
"""
Usage: ipython frequency.py <tweet_file>
"""
def read_tweets(tweet_file):
tweets = []
for line in open(tweet_file):
try:
tweets.append(json.loads(line).get('text',''))
except:
pass
return tweets
def getwords(tweets):
words = []
for tweet in tweets:
for word in tweet.split():
words.append(word)
return list(set(words))
def getwordcount(tweets, word): #total word count in all tweets
counts = 0.
for tweet in tweets:
if word in tweet.split():
counts = counts+1.
return counts
def main():
tweets = read_tweets(sys.argv[1])
words = getwords(tweets)
num_words = len(words)
for word in words:
print word, getwordcount(tweets, word)/num_words
if __name__ == '__main__':
main()
|
3c957a57041ddc91781aea578d81d672f1390dd6 | Ezooon/myProjects | /BlockBuilder/src/BlockBuilder/Window.py | 12,637 | 3.53125 | 4 | ## @file Window.py
# @author Andrew Lucentini, Christopher DiBussolo
# @brief Implements the window visible to the user and game mechanics of BlockBuilder.
# This code follows the PEP 8 Coding Style
# @date 12/4/2018
# BlockBuilder imports
import Constants
from World import *
from Function import *
from Block import *
# Pyglet and additional imports
from pyglet.window import key, mouse
import math
## @brief Inherited window object from pyglet library. Creates the window that displays BlockBuilder as well as defines game mechanics
class Window(pyglet.window.Window):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.exclusive = True # Whether or not the window exclusively captures the mouse.
self.flying = False # When flying gravity has no effect and speed is increased.
self.strafe = [0, 0] # First element is -1 when moving forward, 1 when moving back, and 0
# otherwise. The second element is -1 when moving left, 1 when moving
# right, and 0 otherwise.
self.position = (0, 0, 0) # Current (x, y, z) position in the world
self.rotation = (0, 0) # Determines degrees of rotation with respect to the ground
self.sector = None # Which sector the player is currently in.
self.reticle = None # The crosshairs at the center of the screen.
self.dy = 0 # Velocity in the y (upward) direction.
self.inventory = [GRASS, BRICK, SAND, STONE] # A list of blocks the player can place
self.block = self.inventory[0] # The current block that the user can place
self.num_keys = [ # Convenience list of num keys.
key._1, key._2, key._3, key._4, key._5,
key._6, key._7, key._8, key._9, key._0]
self.World = World(self.position) # Instance of the World
self.label = pyglet.text.Label('', font_name='Arial', font_size=18, # The label that is displayed in the top left of the canvas.
x=10, y=self.height - 10, anchor_x='left', anchor_y='top',
color=(0, 0, 0, 255))
pyglet.clock.schedule_interval(self.update, 1.0 / Constants.TICKS_PER_SEC) # Schedules the `update()` method to be called, and the frequency to be called.
## @brief Determines if the mouse is exclusive to the pyglet window.
# @param exclusive A Boolean value
def setExclusiveMouse(self, exclusive):
super(Window, self).set_exclusive_mouse(exclusive)
self.exclusive = exclusive
## @brief Get the line of sight vector in the world.
# @return The line of sight vector as a 3-tuple.
def getSightVector(self):
x, y = self.rotation
m = math.cos(math.radians(y)) # y ranges from -90 to 90, or -pi/2 to pi/2, so m ranges from 0 to 1
dy = math.sin(math.radians(y))
dx = math.cos(math.radians(x - 90)) * m
dz = math.sin(math.radians(x - 90)) * m
return (dx, dy, dz)
## @brief Get the current velocity vector of the player in the x, z, and y direction.
# @return The current velocity of the player in the x, z, and y vectors as a 3-tuple.
def getMotionVector(self):
if any(self.strafe):
x, y = self.rotation
strafe = math.degrees(math.atan2(*self.strafe))
y_angle = math.radians(y)
x_angle = math.radians(x + strafe)
if self.flying:
m = math.cos(y_angle)
dy = math.sin(y_angle)
if self.strafe[1]: # Moving left or right
dy = 0.0
m = 1
if self.strafe[0] > 0: # Moving back
dy *= -1
dx = math.cos(x_angle) * m
dz = math.sin(x_angle) * m
else:
dy = 0.0
dx = math.cos(x_angle)
dz = math.sin(x_angle)
else:
dy = 0.0
dx = 0.0
dz = 0.0
return (dx, dy, dz)
## @brief The method that will be constantly be called by the pyglet clock.
# Most of the motion logic lives in this this method.
# @param dt The time since the last call (1/TICKS_PER_SEC).
def update(self, dt):
self.World.process_queue()
sector = sectorize(self.position)
if sector != self.sector:
self.World.changeSector(self.sector, sector)
if self.sector is None:
self.World.process_entire_queue()
self.sector = sector
m = 8
dt = min(dt, 0.2)
for _ in range(m):
self._update(dt / m)
# Private implementation of update mathod. Home of most motion logic
def _update(self, dt):
speed = Constants.FLYING_SPEED if self.flying else Constants.WALKING_SPEED # Distance covered this tick.
d = dt * speed
dx, dy, dz = self.getMotionVector()
dx, dy, dz = dx * d, dy * d, dz * d # New position in space, before accounting for gravity.
if not self.flying: # Gravity logic
self.dy -= dt * Constants.GRAVITY
self.dy = max(self.dy, -Constants.TERMINAL_VELOCITY)
dy += self.dy * dt
x, y, z = self.position # Collision detection
x, y, z = self.Collision((x + dx, y + dy, z + dz), Constants.PLAYER_HEIGHT)
self.position = (x, y, z)
## @brief Determines if a player is colliding with a block in the world.
# @param position The player position as a 3-tuple (x, z, y).
# @param height The player height.
# @return A 3-tuple of the player's new position after taking collisions into account.
def Collision(self, position, height):
pad = 0.25
p = list(position)
np = normalize(position)
for face in Constants.FACES: # Check all surrounding blocks
for i in range(3): # Check each dimension independently
if not face[i]:
continue
d = (p[i] - np[i]) * face[i] # How much overlap you have with this dimension.
if d < pad:
continue
for dy in range(height): # Check each height
op = list(np)
op[1] -= dy
op[i] += face[i]
if tuple(op) not in self.World.blockSet:
continue
p[i] -= (d - pad) * face[i]
if face == (0, -1, 0) or face == (0, 1, 0): # You are colliding with the ground or ceiling, so stop falling / rising
self.dy = 0
break
return tuple(p)
## @brief Method inherited by pyglet Window object to determine what occurs when the
# mouse is clicked.
# @param x A float representing the x position on the screen of the mouse click.
# @param y A float representing the y position on the screen of the mouse click.
# @param button The button that is pressed.
# @param modifiers Any buttons that change the functionality of the click.
def on_mouse_press(self, x, y, button, modifiers):
if self.exclusive:
vector = self.getSightVector()
block, previous = self.World.hitTest(self.position, vector, Constants.MAX_DISTANCE)
if (button == mouse.RIGHT):
if previous:
self.World.addBlock(previous,self.position,self.block )
elif button == mouse.LEFT and block:
texture = self.World.blockSet[block]
if texture != STONE:
self.World.removeBlock(block)
else:
self.setExclusiveMouse(True)
## @brief Method inherited by pyglet Window object to determine what occurs when the
# mouse is moved.
# @param x Rotation amount in x-drection.
# @param y Rotation amount in y-direction.
# @param dx The speed of the mouse on the screen in the x-direction.
# @param dy The speed of the mouse on the screen in the y-direction.
def on_mouse_motion(self, x, y, dx, dy):
if self.exclusive:
m = 0.15
x, y = self.rotation
x, y = x + dx * m, y + dy * m
y = max(-90, min(90, y))
self.rotation = (x, y)
## @brief Method inherited by pyglet Window object to determine what occurs when keys are pressed.
# @param symbol The key that is pressed
# @param modifiers Other buttons that modify the functionality of the key that is pressed.
def on_key_press(self, symbol, modifiers):
if symbol == key.W:
self.strafe[0] -= 1
elif symbol == key.S:
self.strafe[0] += 1
elif symbol == key.A:
self.strafe[1] -= 1
elif symbol == key.D:
self.strafe[1] += 1
elif symbol == key.SPACE:
if self.dy == 0:
self.dy = Constants.JUMP_SPEED
elif symbol == key.ESCAPE:
self.setExclusiveMouse(False)
elif symbol == key.TAB:
self.flying = not self.flying
elif symbol in self.num_keys:
index = (symbol - self.num_keys[0]) % len(self.inventory)
self.block = self.inventory[index]
## @brief Method inherited by pyglet Window object to determine what occurs when keys are released.
# @param symbol The key that is released
# @param modifiers Other buttons that modify the functionality of the key that is released.
def on_key_release(self, symbol, modifiers):
if symbol == key.W:
self.strafe[0] += 1
elif symbol == key.S:
self.strafe[0] -= 1
elif symbol == key.A:
self.strafe[1] += 1
elif symbol == key.D:
self.strafe[1] -= 1
## @brief Draws the recticle on the screen.
def draw_reticle(self):
glColor3d(0, 0, 0)
self.reticle.draw(GL_LINES)
## @brief Draws the label in the top left corner of the window.
def draw_label(self):
x, y, z = self.position
self.label.text = '%02d (%.2f, %.2f, %.2f)' % (
pyglet.clock.get_fps(), x, y, z)
self.label.draw()
## @brief Resize the rectile when resizing the window.
# @param The width of the pyglet window.
# @param The height of the pyglet window.
def on_resize(self, width, height):
# reticle
if self.reticle:
self.reticle.delete()
x, y = self.width // 2, self.height // 2
n = 10
self.reticle = pyglet.graphics.vertex_list(4,
('v2i', (x - n, y, x + n, y, x, y - n, x, y + n))
)
## @brief Necessary method to enable openGL to draw in 2D.
def set_2d(self):
width, height = self.get_size()
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0, width, 0, height, -1, 1)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
## @brief Necessary method to enable openGL to draw in 3D.
def set_3d(self):
width, height = self.get_size()
glEnable(GL_DEPTH_TEST)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(65.0, width / height, 0.1, 60.0)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
x, y = self.rotation
glRotatef(x, 0, 1, 0)
glRotatef(-y, math.cos(math.radians(x)), 0, math.sin(math.radians(x)))
x, y, z = self.position
glTranslatef(-x, -y, -z)
## @brief Method inherited by pyglet Window object to determine what will
# be drawn on each clock cycle.
def on_draw(self):
self.clear()
self.set_3d()
glColor3d(1, 1, 1)
self.World.batch.draw()
self.draw_focused_block()
self.set_2d()
self.draw_reticle()
self.draw_label()
## @brief Outlines the block that is being looked at by the player.
def draw_focused_block(self):
vector = self.getSightVector()
block = self.World.hitTest(self.position, vector, Constants.MAX_DISTANCE)[0]
if block:
x, y, z = block
vertex_data = cubeVertices(x, y, z, 0.51)
glColor3d(0, 0, 0)
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
pyglet.graphics.draw(24, GL_QUADS, ('v3f/static', vertex_data))
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) |
a288250975e57e6cf2517c1b62eb889ba43708c1 | zdravkob98/Python-Advanced-September-2020 | /Lab Modules/fibonccimodule.py | 263 | 3.90625 | 4 | def create_fibonacci(count):
fibonacci = []
n1 = 0
n2 = 1
fibonacci.append(n1)
fibonacci.append(n2)
for _ in range(count - 2):
result = n1 + n2
n1 = n2
n2 = result
fibonacci.append(n2)
return fibonacci |
fb1c16cce8084d8e38504119040f5f61c9e755cb | Namrajp/python-fundamentals | /dictionary.py | 871 | 3.828125 | 4 | # Dictionary is collection of name value pair,similar to objects in js
# Create dict
person = {
'first_name': 'John',
'last_name': 'Doe',
'age': 30
}
#print(person, type(person))
# Use constructor
person2 = dict(first_name='Sara', last_name='Williams')
#print(person2, type(person2))
# Get value
#print(person['first_name'])
#print(person.get('last_name'))
# Add key/value
person['phone'] = '555-555-555'
# Get dict keys
# print(person.keys())
# Get dict items
#print(person.items())
#print(person.keys())
# Copy dict is similar to spread in js
person2 = person.copy()
person2['city'] = 'Boston'
# Remove item
del(person['age'])
person.pop('phone')
# Clear
person.clear()
print(person)
# Get length
print(len(person2))
# List of dict
people = [
{'name': 'Nitin', 'age': 3},
{'name': 'Nirvan', 'age': 1}
]
print(people[1]['age']) |
12a2581259b9d78c7cbd2b17f09f6303b244327d | rob-kistner/modern-python | /orig_py_files/dicts_accessing.py | 1,078 | 3.71875 | 4 | from modules.printutils import *
big_banner("""
Dictionaries:
Accessing Individual Values
""")
instructor = {
"name": "Colt",
"owns_dog": True,
"num_courses": 4,
"favorite_language": "Python",
"is_hilarious": False,
44: "my favorite number"
}
val = instructor['name']
expected(
"""Accessing a single value of a dict:
instructor['name']
""",
val
)
val = instructor[44]
expected(
'instructor[44]',
val
)
val = instructor['owns_dog']
expected(
'instructor["owns_dog"]',
val
)
property = "owns_dog"
val = instructor[property]
expected(
"""accessing by passing in a variable
property = 'owns_dog'
instructor[property]
""",
val
)
banner("Exercise: Accessing Data in a Dictionary")
# ----------------------------------------
artist = {
"first": "Neil",
"last": "Young",
}
full_name = artist["first"] + ' ' + artist["last"]
print(full_name)
# note: this also works, even though the course
# didn't allow me to do it...
full_name = f'{artist["first"]} {artist["last"]}'
print(full_name)
|
28b95094a8c8b009ad64a71fb1bab0572e39ad20 | QuinnFargen/CodeWarKata | /6_Weight for weight.py | 1,487 | 3.796875 | 4 |
# My friend John and I are members of the "Fat to Fit Club (FFC)".
# John is worried because each month a list with the weights of members is
# published and each month he is the last on the list which means he is the heaviest.
# I am the one who establishes the list so I told him:
# "Don't worry any more, I will modify the order of the list".
# It was decided to attribute a "weight" to numbers.
# The weight of a number will be from now on the sum of its digits.
# For example 99 will have "weight" 18, 100 will have "weight" 1 so in the list 100 will come before 99.
# Given a string with the weights of FFC members in normal order can you give this string ordered by "weights" of these numbers?
# Test.it("Basic tests")
# Test.assert_equals(order_weight("103 123 4444 99 2000"), "2000 103 123 4444 99")
# Test.assert_equals(order_weight("2000 10003 1234000 44444444 9999 11 11 22 123"), "11 11 2000 10003 22 123 1234000 44444444 9999")
strng = '103 123 4444 99 2000'
strng = '11 11 2000 22 10003 123 1234000 44444444 9999' #should equal
# '11 11 2000 10003 22 123 1234000 44444444 9999'
def root(num):
ln =[int(d) for d in str(num)]
return sum(ln)
def order_weight(strng):
A = sorted(strng.split())
W = [ int(w) for w in A ]
R = [ root(w) for w in W]
R2 = sorted(R)
O = [R2.index(i) for i in R]
W2 = [x for _,x in sorted(zip(O,W))]
return ' '.join([ str(w) for w in W2 ])
order_weight(strng)
|
f30b32340ceb97b59ac3573ccd79b99ad8dafcf0 | cam-rod/checkcryption | /crypterCore/crypter.py | 7,804 | 4.53125 | 5 | """This module handles the encryption of decryption of data."""
import re
class Crypter:
"""This class generates the encryption key, calls the correct function, and returns the text.
Arguments:
- password: hashed (scrambled) version of the password, used to generate the encryption key
- text: in plaintext (for encryption) or encrypted (for decryption) depending on the request
Other variables:
- encryption_key: directly instructs the program how to encrypt the data (hashed and salted)
Returns:
- the encrypted (after encryption) or plaintext data (after decryption)."""
def __init__(self, password, text):
"""Initializes the variables."""
self.password = password
self.text = text
self._encryption_key = None
@property
def encryption_key(self): # Stored as property to allow other areas to call key
"""Returns the encryption key."""
return self._encryption_key
@encryption_key.setter
def encryption_key(self, value):
"""This function generates the encryption key."""
if value:
nums = [] # Individual numbers in encryption key
salt = [] # Salted numbers to be added to e
print("Generating encryption key...")
for i in self.password[0:4]: # 1st-4th characters of the password
if re.match(r'[Nr(Dc.V]', i):
nums.append(0)
elif re.match(r'[QnJeZak]', i):
nums.append(1)
elif re.match(r'[i7*zHuy]', i):
nums.append(2)
elif re.match(r'[SF[jhR3x]', i):
nums.append(3)
elif re.match(r'[pYo#5wU]', i):
nums.append(4)
elif re.match(r'[bT0gKA2]', i):
nums.append(5)
elif re.match(r'[@XvI8s1]', i):
nums.append(6)
elif re.match(r'[)OdlLqC]', i):
nums.append(7)
elif re.match(r'[/,W4tPB9]', i):
nums.append(8)
else:
nums.append(9)
for i in self.password[4:8]: # 5th-8th characters of the password
if re.match(r'[Aiy5oXt]', i):
nums.append(0)
elif re.match(r'[.ceDkUQ1]', i):
nums.append(1)
elif re.match(r'[HvaNxJ@]', i):
nums.append(2)
elif re.match(r'[qB\]g*L6]', i):
nums.append(3)
elif re.match(r'[Gs0ZOdbp]', i):
nums.append(4)
elif re.match(r'[lw,92nM]', i):
nums.append(5)
elif re.match(r'[ETf/z7(I]', i):
nums.append(6)
elif re.match(r'[uCFSPYh]', i):
nums.append(7)
elif re.match(r'[3R#!8Km]', i):
nums.append(8)
else:
nums.append(9)
for i in self.password[8:12]: # 9th-12th characters of the password
if re.match(r'[Fw9@#oS]', i):
nums.append(0)
elif re.match(r'[P4hXqaJ]', i):
nums.append(1)
elif re.match(r'[]CgHzBR]', i):
nums.append(2)
elif re.match(r'[7,eQtLm]', i):
nums.append(3)
elif re.match(r'[Dp1U83(]', i):
nums.append(4)
elif re.match(r'[csfT.kZi]', i):
nums.append(5)
elif re.match(r'[MYn5/vW]', i):
nums.append(6)
elif re.match(r'[Ky!NGu0V]', i):
nums.append(7)
elif re.match(r'[O[)IlbE]', i):
nums.append(8)
else:
nums.append(9)
# Begin salting, first quartet
if (nums[3] - nums[1]) < (nums[2] + nums[0]):
if nums[2] > nums[3]:
if (nums[0] + nums[1] + nums[2] + nums[3]) >= 12:
salt.append(0)
else:
salt.append(6)
elif nums[1] == 4:
salt.append(7)
else:
salt.append(1)
elif ((nums[0] + nums[3]) % 2) == 0:
salt.append(5)
else:
salt.append(8)
# Begin salting, second quartet
if (nums[7] % 3) == 0:
if (nums[5] - nums[4]) > nums[6]:
salt.append(2)
elif ((nums[7] * nums[5])+nums[6]) > (nums[6] * 4):
salt.append(4)
elif (nums[4] + 5) > (nums[7] + 2):
salt.append(9)
else:
salt.append(7)
elif (nums[5] + 2) >= 7:
if nums[4] < 8:
salt.append(3)
else:
salt.append(0)
else:
salt.append(6)
# Begin salting, third quartet
if (nums[8] - nums[11] + nums[10]) > nums[9]:
if (((nums[10] + nums[9]) or (nums[10] - nums[11])) % 2) == 0:
salt.append(7)
elif nums[10] == (nums[8] or nums[9] or nums[11]):
salt.append(2)
else:
salt.append(4)
elif (nums[9] <= nums[11]) or (nums[10] <= nums[11]):
if nums[10] == (2 or 5 or 7 or 8):
salt.append(1)
elif nums[8] * 2 >= 9:
salt.append(5)
else:
salt.append(3)
else:
if nums[8] < 6:
salt.append(9)
else:
salt.append(8)
# Begin salting, all numbers
salt.append((nums[4] - nums[0] + (nums[7] + (nums[8] - nums[5]))
* nums[1] + ((nums[11] + nums[9] + nums[6]) - (nums[2] + nums[0]) * 5)
- nums[3] + nums[10]) % 10)
# Salting the encryption key
nums.insert(2, salt[0])
nums.insert(9, salt[1])
nums.insert(11, salt[2])
nums.insert(7, salt[3])
for i in range(len(nums)): # int to str converter
nums[i] = str(nums[i])
self._encryption_key = ''.join(nums) # The encryption key
del nums
del salt
print('Encryption key generated!')
else:
pass # Request denied by program
def encrypter(self):
"""This encrypts the text."""
key = lambda num: int(self._encryption_key[num]) # Return the numeric value from the key
text = self.text
for pair in range(len(text)):
# All equations with multiplication add a value to prevent multiplying by 0
text[pair] = int(str(text[pair])[:4] + self._encryption_key[7]
+ str(text[pair])[4:]) # Salting
text[pair] *= int(self._encryption_key[15]
+ self._encryption_key[1]) + 3 # ex.: *int('3'+'0') -> *30
text[pair] += 200 * (key(8) - key(3))
text[pair] -= 15
text[pair] -= (key(6) * key(12)) + key(0)
text[pair] *= (13 * key(13)) + 2
text[pair] -= key(2) - key(4) - key(5) + key(11)
text[pair] += key(10) * key(9)
text[pair] *= (key(14) ** 2) + 1
text = [str(p) for p in text] # Convert list to string and join
new_text = '/'.join(text)
return new_text # Return as string for writing to file
|
5679922871517ccae27d2926a9f2f68502ba4e9b | kibanana/Study-Python-With | /yewon/ch03_problem.py | 196 | 3.6875 | 4 | # 1
# 'need'
# 2
i = 0
while True:
i += 1
if i > 5: break
print('*' * i)
# 3
A = [70,60,55,75,95,90,80,80,85,100]
total = 0
for i in A:
total += i
average = total / len(A)
print(average) |
d198ed352455669851a97d1642352865b3bca648 | AngelValAngelov/Python-Advanced-Exercises | /Lists as Stacks and Queues - Exercise/06. Balanced Parentheses.py | 589 | 4.09375 | 4 | def balanced_parentheses():
dict = {
"{": "}",
"[": "]",
"(": ")"
}
stack_open = list()
text = input()
for element in text:
if element in "{[(":
stack_open.append(element)
elif stack_open and element in dict.values():
current = stack_open[-1]
if dict[current] == element:
stack_open.pop()
else:
return "NO"
else:
return "NO"
if not stack_open:
return "YES"
print(balanced_parentheses())
|
6d8ca4a28dfdc8a6a703c8dc8d8652981fe10238 | jorgeromeromg2/Python | /mundo1/ex033.py | 350 | 3.890625 | 4 | reta1 = float(input('Digite a primeira reta: '))
reta2 = float(input('Digite a segunda reta: '))
reta3 = float(input('Digite a terceira reta: '))
if (reta1 + reta2 > reta3) and (reta2 + reta3 > reta1) and (reta1 + reta3 > reta2):
print('Possui condição para ser um triângulo.')
else:
print('Não possui condição para ser um triângulo.') |
f2dfdc7a4fd685a5e2130dd016ef89a08c154933 | tyl1024/TutorProjects | /luckyNumber.py | 632 | 3.765625 | 4 | '''
Created on Feb 15, 2020
@author: 1024t
'''
from collections import Counter
num = Counter("777") #input
print(num)
#input = enter a num: ex('1776')
#amount = Counter(str(input))
#print(amount) dictionary output
#find key ID for our lucky num and print that out
#____________________________
#luck numbers are 6 and 8
#ex... 65 is lucky, 81 is lucky, 66 is lucky, and 88 is lucky, 46 is lucky and 98 is lucky but 68 and 1668 are unlucky
# two lucky numbers and if the number contains both lucky numbers, it is unlucky
num = input("Enter a num:")
amount = Counter((num))
print(amount)
|
11e8bbe1354f627d6200dc843d9113d2493f358e | fabiocaccamo/python-benedict | /tests/core/test_invert.py | 2,900 | 3.75 | 4 | import unittest
from benedict.core import invert as _invert
class invert_test_case(unittest.TestCase):
"""
This class describes an invert test case.
"""
def test_invert_with_unique_values(self):
i = {
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5,
}
o = _invert(i)
r = {
1: ["a"],
2: ["b"],
3: ["c"],
4: ["d"],
5: ["e"],
}
self.assertEqual(o, r)
def test_invert_with_flat_unique_values(self):
i = {
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5,
}
o = _invert(i, flat=True)
r = {
1: "a",
2: "b",
3: "c",
4: "d",
5: "e",
}
self.assertEqual(o, r)
def test_invert_with_multiple_values(self):
i = {
"a": 1,
"b": 2,
"c": 3,
"d": 1,
"e": 2,
"f": 3,
}
o = _invert(i)
self.assertTrue("a" and "d" in o[1])
self.assertTrue("b" and "e" in o[2])
self.assertTrue("c" and "f" in o[3])
def test_invert_with_list_values(self):
i = {
"a": [
"x",
"y",
"z",
],
"b": [
"c",
"d",
"e",
],
}
o = _invert(i)
r = {
"x": ["a"],
"y": ["a"],
"z": ["a"],
"c": ["b"],
"d": ["b"],
"e": ["b"],
}
self.assertEqual(o, r)
ii = _invert(o)
# self.assertEqual(i_back, i)
self.assertTrue("a" in ii)
self.assertTrue("b" in ii)
self.assertEqual(len(ii.keys()), 2)
self.assertTrue("x" in ii["a"])
self.assertTrue("y" in ii["a"])
self.assertTrue("z" in ii["a"])
self.assertEqual(len(ii["a"]), 3)
self.assertTrue("c" in ii["b"])
self.assertTrue("d" in ii["b"])
self.assertTrue("e" in ii["b"])
self.assertEqual(len(ii["b"]), 3)
def test_invert_with_tuple_values(self):
i = {
"a": (
"x",
"y",
"z",
),
"b": (
"c",
"d",
"e",
),
}
o = _invert(i)
r = {
"x": [
"a",
],
"y": [
"a",
],
"z": [
"a",
],
"c": [
"b",
],
"d": [
"b",
],
"e": [
"b",
],
}
self.assertEqual(o, r)
|
a771ee9d43acf861d9e46e5155398b5bf568e907 | rowan-smith/CP1404-Practicals | /prac_05/count_words.py | 471 | 3.90625 | 4 | def main():
word_counts = {}
# sentence = "this is a collection of words of nice words this is a fun thing it is".split(sep=" ")
sentence = input("Text: ").split(sep=" ")
for word in sentence:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
for word in sorted(word_counts.keys()):
print("{:{}} = {}".format(word, len(max(word_counts, key=len)), word_counts[word]))
main()
|
e84a3b488ac47ee95186509e444db3bbe1d158a7 | Parkyunhwan/BaekJoon | /21_05/SecondWeek/P_Lv2_오픈채팅방.py | 494 | 3.53125 | 4 | def solution(record):
answer = []
dic = dict()
record_arr = []
for rec in record:
rec = rec.split(" ")
record_arr.append([rec[0], rec[1]])
if len(rec) > 2:
dic[rec[1]] = rec[2]
for rec in record_arr:
action, uid = rec
if action == 'Enter':
answer.append(dic[uid] + "님이 들어왔습니다.")
elif action == 'Leave':
answer.append(dic[uid] + "님이 나갔습니다.")
return answer |
943ce83e94875c7949464f81ec82e557a1b6a52c | bfontaine/previewer | /previewer/text.py | 1,962 | 3.515625 | 4 | # -*- coding: UTF-8 -*-
import textwrap
def fit_width(text, font, width, max_lines=None):
if not text:
return text
w, _ = font.getsize(text)
# easy case
if w <= width:
return text
pt_w, _ = font.getsize(".")
width_pt = int(width / float(pt_w))
wrapped = None
wrap_width = width_pt
while w > width:
wrap_width -= 1
lines = textwrap.wrap(text, width=wrap_width,
max_lines=max_lines,
placeholder="...",
break_long_words=False)
too_long_word = False
for l in lines:
if len(l) > wrap_width:
too_long_word = True
break
# one of the lines doesn't fit: keep the first one and truncate it if
# necessary
if too_long_word:
text = lines[0]
while w > width:
text = textwrap.shorten(text, wrap_width, placeholder="...")
w, _ = font.getsize(text)
wrap_width -= 1
return text
wrapped = "\n".join(lines)
w, _ = font.getsize(lines[0])
return wrapped
def fit_height(text, font, height):
_, line_height = font.getsize("A")
spacing = 4
# Find highest X such as
# X*line_height + (X-1)*spacing <= height
# X*line_height + X*spacing - spacing <= height
# X*line_height + X*spacing <= height + spacing
# X*(line_height+spacing) <= height + spacing
# X <= (height + spacing) / (line_height + spacing)
lines_count = int((height + spacing) / float(line_height + spacing))
lines = text.split("\n")
if len(lines) > lines_count:
text = "%s..." % ("\n".join(lines[:lines_count]))[:-3]
return text
def fit_text(text, font, width, height, max_lines=None):
text = fit_width(text, font, width, max_lines)
text = fit_height(text, font, height)
return text
|
2a55587d1899dd912f3105637a5cc51ab9cba7a6 | bernasteros/Higher-Lower-Game | /main.py | 3,052 | 3.984375 | 4 | from csv import reader as read
from random import choice as pick
from os import system, name
from art import logo, vs
def clear():
# for windows
if name == 'nt':
_ = system('cls')
# for mac and linux(here, os.name is 'posix')
else:
_ = system('clear')
def initialize_topics(dict_file):
"""Generates and returns the dictionary from a csv-file (style 'topic';full number"""
with open(dict_file, newline='') as trendlist:
dict_reader = read(trendlist, delimiter=';')
topics = {}
for row in dict_reader:
topics[row[0]] = int(row[1])
return topics
def select_answer():
"""Gives the player the choice to choose 'A' or 'B' and returns the result"""
choice = ""
while choice != "a" and choice != "b":
choice = input(
"\nThe search number is...\n\n(A) higher ➕👍 \n(B) lower ➖👎\n > ").lower()
if choice != "a" and choice != "b":
print("Please only pick 'A' or 'B' !")
return choice
def pick_topic(topic_dict):
"""Picks a random topic from the dictionary displays the name and returns a single key"""
choice = pick(list(topic_dict))
return choice
def compare_numbers(topic1, topic2, topic_dict):
"""Takes 2 topics and compares the number in the dictionary provided"""
first_number = topic_dict[topic1]
second_number = topic_dict[topic2]
print("'{}'\n ca. {}k searches".format(topic1, first_number))
print(vs)
print("'{}'".format(topic2))
answer = select_answer()
if answer == "a" and second_number >= topic_dict[topic1]:
print("CORRECT!\n'{}'\nca. {}k searches !".format(
topic2, second_number))
go_on = input("Hit Enter for next round or 'N' for retire: ").lower()
if go_on != "n":
clear()
return True
else:
return False
elif answer == "b" and topic_dict[topic2] <= topic_dict[topic1]:
print("CORRECT!\n'{}'\nca. {}k searches !".format(
topic2, topic_dict[topic2]))
go_on = input("Hit Enter for next round or 'N' for retire: ").lower()
if go_on != "n":
clear()
return True
else:
return False
else:
print("WRONG!\n'{}'\nca. {}k searches !".format(
topic2, topic_dict[topic2]))
return False
print(logo)
print(
"Welcome to the Higher-Lower-Game\nGuess the popularity of Google-search topics!\n"
)
while input("Start a new Game? (y/n)\n> ").lower() != "n":
clear()
print(logo)
game = True
gamedict = initialize_topics('google_trends.csv')
score = -1
first_topic = pick_topic(gamedict)
while game:
clear()
print(logo)
score += 1
new_topic = pick_topic(gamedict)
game = compare_numbers(first_topic, new_topic, gamedict)
first_topic = new_topic
print("Game Over, your end score is {}\n".format(score))
print("Thank you for dropping by :)\n Good bye, and take care.")
|
7585d32e14b7343805e96d4ebaa18000c57e1328 | switalskiadam/sudokuSolver | /sudokuSolver.py | 805 | 3.59375 | 4 |
test_array = [[[[3, 4, 5], [7, 6, 9], [2, 1, 8]],
[[6, 8, 9], [4, 2, 1], [5, 7, 3]],
[[2, 1, 7], [8, 5, 3], [9, 4, 6]]],
[[[9, 6, 3], [2, 4, 8], [1, 5, 7]],
[[4, 7, 2], [3, 1, 5], [8, 6, 9]],
[[8, 5, 1], [9, 7, 6], [3, 2, 4]]],
[[[1, 9, 4], [5, 8, 7], [6, 3, 2]],
[[5, 2, 8], [6, 3, 4], [7, 9, 1]],
[[7, 3, 6], [1, 9, 2], [4, 8, 5]]]]
print('===========================================')
print('|| ' + t + ' ||')
def printChunk(chunk):
"""Converts list of 3 into a board like print"""
l = str(chunk).replace(',',' |').replace('[','').replace(']','')
return str(l)
t = []
for c in test_array[0][0]:
s = printChunk(c)
t.append(s)
t = str(t).replace(',',' || ').replace('\'','').replace('[','').replace(']','')
print(t)
for i in test_array:
for s in i:
print(s)
|
61a1e7fce19cf2f10aa4c3ca479856dad02ff4ac | pythonBJN/ufc-camp- | /Projects/magic 8 ball.py | 1,530 | 3.84375 | 4 | # guessing game
#beckett Nikitas
from gpiozero import Button
from time import sleep
l=Button(4)
r=Button(17)
print(" say your question aloud and click a button")
while True:
if r.is_pressed:
print("the outcome looks good")
break
if l.is_pressed:
print("the outcome looks bad")
break
sleep(2)
print(" say your question aloud and click a button")
while True:
if l.is_pressed:
print(" yes")
break
if r.is_pressed:
print(" no")
break
sleep(2)
print(" say your question aloud and click a button")
while True:
if r. is_pressed:
print(" it is not likely")
break
if l.is_pressed:
print(" it is likely")
break
sleep(2)
print(" say your question aloud and click a button")
while True:
if l.is_pressed:
print("no Way!")
break
if r.is_pressed:
print(" yessssssssssss!")
break
sleep(2)
print(" say your question aloud and click a button")
while True:
if r.is_pressed:
print("it will happen!")
break
if l.is_pressed:
print("it will not happen")
break
slepp(2)
print(" say your question aloud and click a button")
while True:
if r.is_pressed:
print("im sorry what did you say!")
break
if l.is_pressed:
print("please say that again please")
break
wait(5)
print("thank you for asking THE BEST THE GLORIUS MAGIC 8888888 BALLLLLL!!!!!!!!! please ask again sooooon!") |
96ee04a3c18a1a6918a374d1c5bc8e9d0e036240 | Kaktus994/Algorithms | /Partition function Q/q.py | 943 | 3.75 | 4 | from math import sqrt
from functools import lru_cache
class Q:
@lru_cache()
def calculate_q(n):
"""
Q partitioning function
"""
if n == 0:
return 1
else:
sum_upper_limit = int(sqrt(n))
temp_sum = sum((-1)**(k + 1) * Q.calculate_q(n - k**2) for k in range(1, sum_upper_limit + 1))
return Q.check_s(n) + 2 * temp_sum
def check_s(n):
"""
Check if n is in dict and get result
"""
temp_dict = Q.calculate_s(n)
if n in temp_dict:
return (-1)**temp_dict[n]
else:
return 0
def calculate_s(n):
result_dict = {}
j = 0
minus_part = -1
while minus_part <= n:
j_first = 3 * j**2
plus_part = (j_first + j) // 2
minus_part = (j_first - j) // 2
result_dict[plus_part] = j
result_dict[minus_part] = j
j += 1
return result_dict
@staticmethod
def q(n):
return Q.calculate_q(n) - 1
"""
Test
"""
if __name__ == "__main__":
for i in range(1, 101):
print(i, "->", Q.q(i))
|
a6f4c44ee469fa45d74ebae7fc98ff326bfe450b | gangadharsingh/20186074_CSPP-1 | /cspp1-assignments/m22/assignment3/tokenize.py | 809 | 4.125 | 4 | '''
Write a function to tokenize a given string and return a dictionary with the frequency of
each word
'''
import re
def clean_string(string):
'''clean string
'''
return re.sub('[^ a-zA-Z0-9]', '', string)
def tokenize(string):
'''tokenizing the string
'''
dic_new = {}
for i in string:
dic_new[i] = dic_new.get(i, 0) + 1
return dic_new
def main():
'''tokenizw the input
'''
inp = int(input())
str_new = []
for i in range(inp):
lis_new = input().split()
str_new.append(lis_new)
str_clean = []
cnt = 0
while cnt < len(str_new):
for i in range(len(str_new[cnt])):
str_clean.append(clean_string(str_new[cnt][i])+'')
cnt += 1
print(tokenize(str_clean))
if __name__ == '__main__':
main()
|
a4840cf19b876f335a0c4c08714bd2eea54b97ae | mangrisano/ProjectEuler | /euler7.py | 596 | 3.765625 | 4 | # By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
# What is the 10 001st prime number?
#
# Answer: 104743
def problem(number):
count = 1
value = 3
if number == 1:
return 2
else:
while True:
if is_prime(value):
count += 1
if count == number:
return value
value += 2
def is_prime(number):
for i in range(2, int(round(number**0.5)) + 1):
if not (number % i):
return False
return True
print(problem(6))
|
e5b0ca32969dd5197d160e3376f0a67420439e21 | lollipop190/Data-Science-Project | /Classification/java_cpp_clearComments.py | 1,532 | 3.546875 | 4 |
def java_clear(filename):
file = ''
multiline_comments = False
with open('../parser/' + filename ,encoding='utf-8') as f:
for line in f.readlines():
if multiline_comments:
if '*/' in line:
multiline_comments = False
if not line.split('*/')[1].isspace():
line = line.split('*/')[1]
else:
line = ''
else:
line = ''
continue
if line == '\n':
line = ''
elif '//' in line:
line = line.split('//')[0]
if not line.isspace() and line != '':
line += '\n'
else:
line = ''
elif '/*' in line and '*/' in line:
first_part = line.split('/*')[0]
second_part = line.split('*/')[1]
line = first_part + second_part
elif '/*' in line:
multiline_comments = True
if not line.split('/*')[0].isspace():
line = line.split('/*')[0] + '\n'
else:
line = ''
elif '*/' in line:
multiline_comments = False
if not line.split('*/')[1].isspace():
line = line.split('*/')[1]
else:
line = ''
# print(line,sep='')
file += line
return file |
3972ba385430866968cda9a746b04a8c6716f4e4 | renukadeshmukh/Leetcode_Solutions | /1002_FindCommonCharacters.py | 1,379 | 4.15625 | 4 | '''
1002. Find Common Characters
Given an array A of strings made only from lowercase letters, return a list of
all characters that show up in all strings within the list (including duplicates).
For example, if a character occurs 3 times in all strings but not 4 times, you
need to include that character three times in the final answer.
You may return the answer in any order.
Example 1:
Input: ["bella","label","roller"]
Output: ["e","l","l"]
Example 2:
Input: ["cool","lock","cook"]
Output: ["c","o"]
Note:
1 <= A.length <= 100
1 <= A[i].length <= 100
A[i][j] is a lowercase letter
'''
'''
ALGORITHM:
1. Maintain count of each character in each word.
2. Take minimum of all occurance counts for each character and add the character
to result array minimum times.
RUNTIME COMPLEXITY: O(M*N) for N words with average length M
SPACE COMPLEXITY: O(26 * N) = O(N)
'''
class Solution(object):
def commonChars(self, A):
"""
:type A: List[str]
:rtype: List[str]
"""
char_map = {}
for i in range(len(A)):
for c in A[i]:
if c not in char_map:
char_map[c] = [0] * len(A)
char_map[c][i] += 1
result = []
for c in char_map:
count = min(char_map[c])
result.extend([c] * count)
return result
|
3e56d57fb2005567e2787deed13e1947a033b2a6 | yadav-vikas/python-object-oriented-programming | /encapsulation.py | 712 | 4.5625 | 5 | #encapsulation is used to restrict access to methods and variables
#This prevents data from direct modification.
# to make private attributes we use "_" or "__" as prefix.
class computer:
def __init__(self):
#defining the private attribute
self.__maxprice=900
def sell(self):
print("selling price={}".format(self.__maxprice))
def setMaxPrice(self,price):
self.__maxprice=price
#instance of class computer
device=computer()
device.sell()
#updated price
device.__maxprice=1000
device.sell()
#but the price didnt change from 900 to 1000
#using setMaxPrice() function
device.setMaxPrice(1000)
device.sell()
#price change from 900 to 1000 |
f1102a6f30f464ebe55acf85bc63b240f5e0a45a | zhangyu345293721/leetcode | /src/leetcodepython/list/merge_two_sorted_lists_21.py | 2,266 | 3.640625 | 4 | # encoding='utf-8'
'''
/**
* This is the solution of No. 21 problem in the LeetCode,
* the website of the problem is as follow:
* https://leetcode-cn.com/problems/merge-two-sorted-lists
* <p>
* The description of problem is as follow:
* ==========================================================================================================
* 将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
* <p>
* 示例:
* <p>
* 输入:1->2->4, 1->3->4
* 输出:1->1->2->3->4->4
* <p>
* 来源:力扣(LeetCode)
* ==========================================================================================================
*
* @author zhangyu (zhangyuyu417@gmail.com)
*/
'''
from list.list_node import ListNode
class Solution:
def merge_two_lists(self, l1: ListNode, l2: ListNode) -> ListNode:
'''
合并两个链表
Args:
l1: l1链表
l2: l2链表
Returns:
合并后的链表
'''
node = ListNode(-1)
head = node
while l1 and l2:
if l1.val <= l2.val:
node.next = l1
l1 = l1.next
else:
node.next = l2
l2 = l2.next
node = node.next
if not l1:
node.next = l2
if not l2:
node.next = l1
return head.next
def merge_two_lists_2(self, l1: ListNode, l2: ListNode) -> ListNode:
'''
合并两个链表
Args:
l1: l1链表
l2: l2链表
Returns:
合并后的链表
'''
if not l1:
return l2
if not l2:
return l1
if l1.val <= l2.val:
l1.next = self.merge_two_lists_2(l1.next, l2)
return l1
else:
l2.next = self.merge_two_lists_2(l1, l2.next)
return l2
if __name__ == '__main__':
list_node = ListNode()
l1 = list_node.create_list_node_array([1, 2, 4])
l2 = list_node.create_list_node_array([1, 3, 4, 5])
solution = Solution()
result = solution.merge_two_lists_2(l1, l2)
print(result.val)
assert result.val == 1
|
710f2e94b8ae0009429a4c0503e6bbdacf365db5 | briantaylorjohnson/python-practice | /name.py | 2,053 | 4.3125 | 4 | # Chapter 2
name = "ada lovelace"
print(name.title()) # Title case
print(name.upper()) # Upper case
print(name.lower()) # Lower case
first_name = "tom"
last_name = "thumb"
full_name = f"{first_name} {last_name}" # F-strings
print(full_name.title())
print(f"Hello there, {full_name.title()}!") # F-strings in print function
message = f"My name is {name.title()}." # F-strings in variable
print(message)
print("Python")
print("\tPython") # Adding a tab
print("\nPython\n") # Adding a new line
print("Languages:\nPython\nC\nJavaScript\n") # Adding new lines
print("Languages:\n\tPython\n\tC\n\tJavaScript\n") # Adding new lines and tabs
favorite_language = "Python " # Whitespace on right side
print(favorite_language)
print(favorite_language.rstrip()) # Whitespace on right side stripped in output
favorite_language = favorite_language.rstrip() # Whitespace on right side stripped in variable
print(favorite_language)
favorite_language = " Python3 " # Whitespace on both sides
print(favorite_language.rstrip()) # Whitespace on right side stripped
print(favorite_language.lstrip()) # Whitespace on left side stripped
print(favorite_language.strip()) # Whitespace on both sides stripped
print("\n\n")
addition = 2 + 3 # Addition
print(addition)
subtraction = 2 - 3 # Subtraction
print(subtraction)
multiplication = 9 * 9 # Multiplication
print(multiplication)
division = 9 / 4 # Division
print(division)
exponents = 9 ** 2 # Exponents
print(exponents)
exponents = 9 ** 3 # Exponents
print(exponents)
order_of_ops = ((9 * 8) / 2) ** 2 # Order of Operations
print(order_of_ops)
floats = 0.2 + 0.1 # Watch out for floats and lots of decimal places
print(floats)
universe_age = 14_000_000_000 # Using underscores to make big numbers more readable
print(universe_age)
x, y, z = 0, 1, 2 # Assigning values to more than one variable in a single line
print(x)
print(y)
print(z)
MAX_CONNECTIONS = 5000 # Using all caps to indicate a constant in Python is a common practice
print(MAX_CONNECTIONS)
import this # Displays "The Zen of Python" by Tim Peters
|
9077b5a187bbcf871fb8292af0f5033378197ff7 | Aasthaengg/IBMdataset | /Python_codes/p02419/s727008088.py | 254 | 3.71875 | 4 | import sys
count = 0
w = ""
w = raw_input()
while 1 :
adding = map(str,raw_input().split())
for i in adding:
if i == 'END_OF_TEXT':
print count
sys.exit()
if i.lower() == w:
count += 1 |
387ca8a89f471d27a1ad372e59fc4475ba0a0a2e | dazzul94/python_basic | /20190825/vending_machine.py | 922 | 3.875 | 4 | '''
자동판매기는 고객으로부터 투입된 돈과 물건값을 입력받는다.
거스름돈을 출력하는 프로그램을 작성하시오. (물건값은 100단위)
ex)
투입한 돈: 5000원
물건 값 : 2600원
거스름돈 : 2400원
=> 1000원 지폐: 2
500원 : 0
100원 : 4
'''
money = int(input("돈을 넣어주세요: ")) # 10000원
price = int(input("물건값을 선택해주세요. ")) # 물건값
change = money - price # 2600원
p1000 = change // 1000 # 천원짜리(p1000)
c500 = ( change % 1000 ) // 500 # 500원짜리(c500)
c100 = ( ( change % 1000) % 500 ) // 100 # 100원짜리(c100)
print("천원짜리는 {}개, 오백원짜리는 {}개, 백원짜리는 {}개입니다.".format( p1000, c500, c100))
print("천원짜리는 %s개, 오백원짜리는 %s개, 백원짜리는 %s개입니다." %(p1000, c500, c100)) |
5acf498426801502f9a40c0bf302c2cd54e84c2f | 571019070/pycharm | /Condition模式生产者消费者.py | 1,633 | 3.703125 | 4 | import threading
import random
import time
gMoney = 10000
gCondition = threading.Condition
gTotalTimes = 10
gTime = 0
class Producer (threading.Thread):
def run (self):
global gMoney
global gTime
while True:
money = random.randint(100, 1000)
gCondition.acquire()
if gTime >= gTotalTimes:
gCondition.release()
break
gMoney += money
print('%s生产了%d元钱,剩余%d元钱' % (threading.current_thread(), money, gMoney))
gTime += 1
gCondition.notify_all()
gCondition.release()
time.sleep(1)
class Consumer (threading.Thread):
def run (self):
global gMoney
while True:
money = random.randint(100, 1000)
gCondition.acquire()
while gMoney < money:
if gTime >= gTotalTimes:
gCondition.release()
return
print('%s准备消费%d元钱,剩余%d元钱,不足!' % (threading.current_thread(), money, gMoney))
gCondition.wait()
gMoney -= money
print('%s消费了%d元钱, 剩余%d元钱' % (threading.current_thread(), money, gMoney))
gCondition.release()
time.sleep(1)
def main():
for x in range(3):
t = Consumer(name="消费者线程%d" %x)
t.start()
for x in range(5):
t = Producer(name="生产者线程%d" %x)
t.start()
if __name__ == '__main__':
main()
|
e41b7fbe2aa2bbd512f53f07c6c76352480f2eff | PraghadeshManivannan/Python | /loop/sum of first and last digit of a number.py | 227 | 3.703125 | 4 | n = int(input("Enter the number:"))
m = n
c = 0
while n> 0:
n = n//10
c += 1
d = c - 1
e =((m % 10) + (m // (10 ** d)))
print("The sum of first digit=",(m // (10 ** d)),"and the last digit=",m % 10,"is",e)
|
93b2a081c64535ab1dbcc3572986172499ad319d | kveola13/python_exercies | /exercises/exercise_12.py | 243 | 3.765625 | 4 | def print_first_and_last(list):
first_and_last = [list[0], list[len(list) - 1]]
return first_and_last
def main():
test_list = [5, 10, 15, 20, 25]
print(print_first_and_last(test_list))
if __name__ == '__main__':
main()
|
5a8e671d7556f0e32a04b2a50606556bcec5058a | Preksha1998/python | /phonenumber_module/format_ph.py | 360 | 3.96875 | 4 | #convert input to phone nmber format
#to get timezone for phone number
import phonenumbers
from phonenumbers import timezone
ph_no = phonenumbers.parse("+923096161117")#parsing string to ph.no.
#this will print the country code and national number.
print(ph_no)
tz = timezone.time_zones_for_number(ph_no)#give the time zone for the parsed ph.no.
print(tz) |
507d021e4f83d9c615722de368fea9e88e0b44b7 | lilsweetcaligula/sandbox-codewars | /solutions/python/67.py | 165 | 3.625 | 4 | def anagrams(word, candidates):
wordSortedChars = sorted(word)
return [candidate for candidate in candidates if sorted(wordSortedChars) == sorted(candidate)] |
499d9574db5fb87ed70506a9d62b1f5dffb2afd5 | NevssZeppeli/my_ege_solutions | /Программы Хирьянова/урок 48/ege2.py | 305 | 4.15625 | 4 | for x in range(2):
for y in range(2):
for z in range(2):
for w in range(2):
#f = ((not x or z) and (not z or w)) or (y ==(x or z))
f = (x <= z) and (z <= w) or (y == (x or z))
if f == 0:
print(x, y, z, w)
|
c239db4931617e020810150d0dc8335cf0014bc6 | vsahal/python_Udemy_Course | /recursion/reverseStr.py | 230 | 3.9375 | 4 | def reverseStr(s):
if len(s) == 1:
return s[-1]
else:
return s[-1] + reverseStr(s[:-1])
#another way to do this
def reverseStr1(s):
if len(s) == 1:
return s[0]
else:
return reverseStr1(s[1:]) + s[0]
|
d603cb4eaf9c879ddf87117a8790dfd326700915 | ja-howell/Kattis | /cold-puterscience/cold-puterscience.py | 154 | 3.671875 | 4 | days = input()
days = int(days)
coldDays = 0
temps = input().split()
for i in temps:
if int(i) < 0:
coldDays = coldDays + 1
print(coldDays)
|
87a1fe07295ac742d46cee2a36d5d1e896804c45 | Sarthak-Singhania/Work | /Class 12/Queue menudriven.py | 754 | 3.765625 | 4 | l=[]
def enqueue():
global l
l.append(int(input('Enter:')))
def diqueue():
global l
l.pop(0)
def peek():
global l
print(l[0])
def display():
global l
print(l)
while True:
option=(int(input('\n\t\t1)Enqueue\n\t\t2)Diqueue\n\t\t3)Peek\n\t\t4)Display\n\n\t\tEnter the option number:')))
if option==1:
enqueue()
elif option==2:
diqueue()
if len(l)==0:
print('Stack is underflow')
elif option==3:
if len(l)!=0:
peek()
else:
print('Stack is underflow')
elif option==4:
if len(l)!=0:
display()
else:
print('Stack is underflow')
if input('Do you want to continue(y/n)?')=='n':
break |
732795139a9b3492d6cb9ed3897e89d473e24d56 | GabrielAnguita/dibujosPython | /tortuga2.py | 516 | 3.5625 | 4 | import math
import turtle
fred = turtle.Turtle()
sc = turtle.Screen()
sc.reset()
sc.setworldcoordinates(0,-1.5,360,1.5)
fred.color("white")
turtle.bgcolor("black")
bob = turtle.Turtle()
bob.color("white")
duda = turtle.Turtle()
luly = turtle.Turtle()
luly.color("white")
duda.color("white")
for angle in range(1000):
yf = math.sin(math.radians(angle))
yb = math.cos(math.radians(angle))
fred.goto(angle,yf)
bob.goto(angle,yb)
duda.goto(angle,-yf)
luly.goto(angle,-yb)
wn.exitonclick() |
689107c5bdfacfa7f2ea72a6b8102ae6473b2e5b | harrypotter0/competitive-programming | /Contests/Others/Hackon Feb/prob5.py | 545 | 3.640625 | 4 | import math
def readInts():
return list(map(int, raw_input().split()))
def readInt():
return int(input())
def readIntsindex0():
return list(map(lambda x: int(x) - 1, input().split()))
test = readInt()
for _ in range(test):
X1, Y1, R1 = readInts()
X2, Y2, R2 = readInts()
d = math.sqrt(((X2 - X1) ** 2) + ((Y2 - Y1) ** 2))
if d < abs(R1 - R2):
if R1 > R2:
print 'C1CC2'
else:
print 'C2CC1'
elif d == (R1 - R2):
print 'C2~C1'
else:
print 'NOT SATISFIED'
|
29dbc52b56f1495c3adace7a3e36af7c6e2fe3be | stonecoder19/machine_learning | /linear_regression_scratch.py | 1,175 | 3.546875 | 4 | import numpy as np
from sklearn.linear_model import LinearRegression
X = np.array([[3],[2],[1]])
Y = np.array([8,6,4])
alpha = 0.1
weights = np.ones((1, 2))
def add_bias(X):
return np.hstack((np.ones((X.shape[0],1)),X))
def batch_gradient_descent(X,Y,num_iter=1000):
X = add_bias(X)
weights = np.zeros(X.shape[1])
for _ in xrange(num_iter):
y_hat = np.dot(weights,X.T)
errors = Y - y_hat
gradient = np.dot(errors,X)
weights = weights + alpha * gradient
print(weights)
return weights
def stochastic_gradient_descent(X,Y,num_iter=1000):
X = add_bias(X)
weights = np.zeros(X.shape[1])
for _ in xrange(num_iter):
for idx,row in enumerate(X):
y_hat = np.dot(weights,row.T)
error = Y[idx] - y_hat
gradient = error * row
weights = weights + alpha * gradient
print(weights)
return weights
print("Stochastic gradient descent",stochastic_gradient_descent(X,Y))
print("Batch gradient descent", batch_gradient_descent(X,Y))
model = LinearRegression()
model.fit(X,Y)
print(model.predict(np.array([[5]])))
|
ad32ea9f2e03c8eb69ec609c33c23301b306d202 | xiangkangjw/interview_questions | /company_interview_questions/dropbox.py | 451 | 3.6875 | 4 | def isFrenemy(n, frenemy, x, y, relation):
if len(relation) < 1:
return 1
level = set()
level.add(x)
while len(relation)>0:
r = relation[0]
newLevel = set()
for i in level:
for j in range(n):
if frenemy[i][j] == r:
newLevel.add(j)
relation = relation[1:]
level = newLevel
return y in level
print isFrenemy(2, ["-F","F-"], 0, 1, "F")
|
548ab346a8fc16bf52b20bccc7607c8112e3a2c9 | marufaytekin/hackerrank | /Words.py | 200 | 4.25 | 4 | """
find all possible words from given characters
"""
import itertools
def all_words(letters):
for word in itertools.permutations(letters):
print word, ''.join(word)
all_words("cat")
|
761f3af531f60f59c34e71c0cbf54647d961cc6f | nicolas4d/Data-Structures-and-Algorithms-Using-Python | /listing/printListRecursion.py | 169 | 3.984375 | 4 | # Print the contents of a linked list using recursion.
# O(n)
def printList( node ):
if node is not None :
printList( node.next )
print( node.data )
|
268a5ad22b505dfb76b0303249f7244ebddd19d4 | Xuhen17/Python_Basic | /lesson7/less7_task3.py | 3,900 | 3.546875 | 4 | # 3) Реализовать программу работы с органическими клетками, состоящими из ячеек. Необходимо создать класс
# Клетка. В его конструкторе инициализировать параметр, соответствующий количеству ячеек клетки (целое число).
# В классе должны быть реализованы методы перегрузки арифметических операторов: сложение (__add__()),
# вычитание (__sub__()), умножение (__mul__()), деление (__truediv__()).
# Данные методы должны применяться только к клеткам и выполнять увеличение, уменьшение, умножение и целочисленное
# (с округлением до целого) деление клеток, соответственно.
# Сложение. Объединение двух клеток. При этом число ячеек общей клетки должно равняться сумме ячеек исходных
# двух клеток.
# Вычитание. Участвуют две клетки. Операцию необходимо выполнять только если разность количества ячеек двух клеток
# больше нуля, иначе выводить соответствующее сообщение.
# Умножение. Создается общая клетка из двух. Число ячеек общей клетки определяется как произведение количества ячеек
# этих двух клеток.
# Деление. Создается общая клетка из двух. Число ячеек общей клетки определяется как целочисленное деление количества
# ячеек этих двух клеток.
# В классе необходимо реализовать метод make_order(), принимающий экземпляр класса и количество ячеек в ряду.
# Данный метод позволяет организовать ячейки по рядам.
# Метод должен возвращать строку вида *****\n*****\n*****..., где количество ячеек между \n равно переданному аргументу.
# Если ячеек на формирование ряда не хватает, то в последний ряд записываются все оставшиеся.
class Cell:
def __init__(self, num_cell):
self.number = int(num_cell)
def __add__(self, other):
return print(f'Итог сложения: {self.number + other.number}')
def __sub__(self, other):
return print(f'Итог вычитания: {self.number - other.number}') if self.number > other.number else print(
f'Вычитание приведёт к исчезновению клетки')
def __mul__(self, other):
return print(f'Итог умножения: {self.number * other.number}')
def __truediv__(self, other):
return print(f'Итог деления первой клетки на вторую: {self.number // other.number}')\
if self.number >= other.number else print(
f'Итог деления второй клетки на первую: {other.number // self.number}')
def make_order(self, num_row):
return print("".join(
["*" * num_row + "\n" if i < self.number // num_row else "*" * (self.number % num_row) for i in
range(self.number // num_row + 1)]))
c1 = Cell(28)
c2 = Cell(8)
(c1 + c2)
(c1 - c2)
(c1 * c2)
(c1 / c2)
(c1.make_order(8))
|
557d95d3bbf7b32a8fa1f17c3cb5512e7e9bf6cc | itsolutionscorp/AutoStyle-Clustering | /assignments/python/wc/src/1541.py | 208 | 3.8125 | 4 | import re
def word_count(phrase):
counts = {}
matches = re.findall('\S+', phrase)
for match in matches:
if match not in counts:
counts[match] = 1
else:
counts[match] += 1
return counts
|
a640e8319a8837657e0d47fd4b2001690b0f2117 | chaoswork/leetcode | /063.UniquePathsII.py | 1,534 | 4.03125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Author: Chao Huang (huangchao.cpp@gmail.com)
Date: Tue Feb 27 17:01:16 2018
Brief: https://leetcode.com/problems/unique-paths-ii/description/
Follow up for "Unique Paths":
Now consider if some obstacles are added to the grids. How many unique
paths would there be?
An obstacle and empty space is marked as 1 and 0 respectively in the grid.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[
[0,0,0],
[0,1,0],
[0,0,0]
]
The total number of unique paths is 2.
Note: m and n will be at most 100.
"""
import sys
class Solution(object):
def uniquePathsWithObstacles(self, obstacleGrid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
n = len(obstacleGrid)
if n == 0:
return 0
m = len(obstacleGrid[0])
if m == 0:
return 0
count = [[1 - obstacleGrid[i][j] for j in range(m)] for i in range(n)]
for i in range(0, n):
for j in range(0, m):
if i == 0 and j == 0:
continue
if obstacleGrid[i][j] == 1:
count[i][j] = 0
else:
left = count[i - 1][j] if i > 0 else 0
top = count[i][j - 1] if j > 0 else 0
count[i][j] = left + top
# for item in count:
# print item
return count[n - 1][m - 1]
sol = Solution()
a = [
[1]
]
print sol.uniquePathsWithObstacles(a)
|
a6f0717c99c36903312673e5622ec68804119bf8 | VladSemiletov/python_algorithms | /Task_5/5_2.py | 1,124 | 3.75 | 4 | from collections import defaultdict
def function_1(num_1, num_2):
def_dict = defaultdict(list)
def_dict[num_1] = list(num_1)
def_dict[num_2] = list(num_2)
def_dict['sum'] = list(hex(int(num_1, 16) + int(num_2, 16))[2:])
def_dict['multiplication'] = list(hex(int(num_1, 16) * int(num_2, 16))[2:])
return f'{num_1} + {num_2} = {"".join(def_dict["sum"])}\n' \
f'{num_1} * {num_2} = {"".join(def_dict["multiplication"])}\n' \
f'{def_dict[num_1]} + {def_dict[num_2]} = {def_dict["sum"]}\n' \
f'{def_dict[num_1]} * {def_dict[num_2]} = {def_dict["multiplication"]}'
print(f'{function_1.__name__}\n{function_1("A2", "C4F")}')
print('=' * 60)
class HexNumber:
def __init__(self, num):
self.num = num
def __add__(self, other):
return list(hex(int(self.num, 16) + int(other.num, 16))[2:])
def __mul__(self, other):
return list(hex(int(self.num, 16) * int(other.num, 16))[2:])
number_1 = HexNumber('A2')
number_2 = HexNumber('C4F')
print(f'Сложение: {number_1 + number_2}')
print(f'Умножение: {number_1 * number_2}') |
bffb7ea89b5ebfbdae690af8f13d476ad4856083 | tripti-naithani/talentSprint-WE-bootcamp-I | /practice/13thJune/evenfibonacci.py | 632 | 3.8125 | 4 | def generate_fibonacci(limit):
prev1 = 1
prev2 = 2
curr = 0
fibonacci = [1, 2]
while (1):
curr, prev1, prev2 = calculate_previous(curr, prev1, prev2)
if(curr < limit):
fibonacci.append(curr)
else:
break
return fibonacci
def calculate_previous(curr, prev1, prev2):
curr = prev1 + prev2
prev1 = prev2
prev2 = curr
return curr, prev1, prev2
def sumOf_evenFibonacci(fibonacci_seq):
return sum([number for number in fibonacci if number % 2 == 0])
fibonacci = generate_fibonacci(4000000)
print(sumOf_evenFibonacci(fibonacci))
|
7f082dc4753f6a5921a57239514ca4a11772971d | snpardy/notes-to-trello | /notes_to_trello/parser.py | 3,217 | 3.765625 | 4 | import re
class Parser():
'''A class containing regex tags that we're interested in to facilitate parsing of files.'''
# Regex for parsing notes file
tags = {
'scanned' :'<!-- scanned for trello -->\n',
'open_task' : '@TASK|@TODO',
'close_task' : '@END|\n',
'due_date' : '@due',
'white_space': '\s'
}
def __init__(self, custom_tags=None):
# add any custom tags provided by user
if custom_tags:
pipe = '|'
for key in self.tags:
if key in custom_tags:
self.tags[key] = pipe.join(self.tags[key], custom_tags[key])
# for k, v in self.tags.items():
# self.tags[k] = re.compile(v)
def parse_file(self, path):
'''Extracts tasks from file at @param path.'''
# List of cards that have been identified in the file
cards = []
if path.endswith('.md'):
with open(path, 'r') as f:
if not re.search(self.tags['scanned'], f.readline()):
# this file hasn't been scanned before
contents = f.read()
while contents:
# Find another card
match = re.search(tags['open_task'], contents)
if match:
# we've found a new card
card = {} # dict to hold extracted card information
start_card = match.span()[1]
contents = contents[start_card:]
match_end = re.search(tags['close_task'], contents)
if match_end:
end_card = match_end.span()[0]
else:
raise Exception("Expect close task tag but file ended.")
card_text = contents[:end_card]
due_date_match = re.search(tags['due_date'], card_text)
if due_date_match:
# this card contains a due date, let's add it to our card dict
due_date = card_text[due_date_match.span()[1]:]
end_due_date = re.search(tags['white_space'], due_date)
due_date = due_date[:end_due_date.span()[0]]
if re.seach('\\d{4}-\\d{2}-\\d{2}', due_date):
card['due'] = due_date
else:
# due date does not meet ISO 8601 formatting
print("Skipping due date [{}] in file '{}' as does not follow ISO8601 formatting".format(due_date, path))
raise Exception('dev break: need how does due date interact with the card name? \
Do we assume the name is over when we hit the duedate?')
# prepend the 'scanned' tag to the file
f.seek(0, 0)
f.write(tags['scanned'] + f.read())
|
b20ca7cf18a61e8fb3cc3f48fe6a11cdf50b69ac | fangqiangchen/newproject | /imooc_python2020/Chapter01/string_use.py | 329 | 3.6875 | 4 | # coding:utf-8
info = 'python是一个非常有魅力的语言'
result = '魅力' in info
print(result)
result = '语言' not in info
print(result)
info2 = 'python is a good code'
print(max(info2))
print(min(info2))
info3 = '天气好 要多锻炼身体'
info4 = '多锻炼身体 身体会变得更好'
print(info3 + info4) |
c2aeb0adae10306854080e0def2ef4938039420b | auroprit182/DS-ALGO | /sorting/InsertionSort.py | 382 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
Implementation of Insertion sort in python
"""
def insertionsort(a):
for i in range(1,len(a)):
key = a[i]
j=i-1
while(j>=0 and a[j]>key):
a[j+1]=a[j]
j=j-1
a[j+1]=key
# test insertion sort
a = [6,5,3,1,8,7,2,4]
insertionsort(a)
print(a)
|
5c6d36f67f4c76b2d645063cddd13666d5e1d385 | huowolf/python-demo | /src/fun_advance/ret_fun.py | 882 | 3.59375 | 4 | def lazy_sum(*args):
def sum():
ax=0
for n in args:
ax=ax+n
return ax
return sum
#返回的函数并没有立刻执行,而是直到调用了f()才执行
f=lazy_sum(1,2,3,4)
print(f)
print(f())
def count():
fs=[]
for i in range(1,4):
def f():
return i*i
fs.append(f)
#返回了新创建的3个函数对象
return fs
#print(count()[0]())
f1,f2,f3=count()
print(f1())
print(f2())
print(f3())
#返回闭包时牢记一点:返回函数不要引用任何循环变量,或者后续会发生变化的变量。
def count2():
def f(j):
def g():
return j*j
return g
fs=[]
for i in range(1,4):
fs.append(f(i)) # f(i)立刻被执行,因此i的当前值被传入f()
return fs
f1,f2,f3=count2()
print(f1())
print(f2())
print(f3()) |
005fc653db8303149848b7ea69bd952ba43fce2a | deepaksharran/Python | /dictemptyornot.py | 104 | 3.90625 | 4 | d={1:2}
list1=list(d)
print(list1)
if not list1:
print("empty")
else:
print("not empty")
|
7cc8b560e446ce8ec7ee3ccfd08d557ffbe4e937 | HonniLin/leetcode | /tree/235.Lowest-Common-Ancestor-of-a-Binary-Search-Tree.py | 1,211 | 3.890625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""
:desc Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
:way
1/Start traversing the tree from the root node.
2/If both the nodes p and q are in the right subtree, then continue the search with right subtree starting step 1.
3/If both the nodes p and q are in the left subtree, then continue the search with left subtree starting step 1.
4/If both step 2 and step 3 are not true, this means we have found the node which is common to node p's and q's subtrees. and hence we return this common node as the LCA.
"""
par = root.val
p_v = p.val
q_v = q.val
if p_v > par and q_v > par:
return self.lowestCommonAncestor(root.right, p, q)
elif p_v < par and q_v < par:
return self.lowestCommonAncestor(root.left, p, q)
else:
return root
|
f3b4ab2a6782f896b7cd6606301334cc41c68093 | kronosapiens/foundations | /datastructures/hash.py | 3,320 | 3.8125 | 4 | import linkedlist
class dict(object):
'''Python dict implementation (hash table)
Objectives:
O(1) lookup (average case)
O(1) write (average case)
O(n) lookup (worst case)
O(n) write (worst case)
No implicit memory allocation
Implementation rules:
- Nodes cannot have None content, EXCEPT for first node at idx=i.
>>> mydict = dict()
>>> mydict.set('cat', 'meow')
>>> mydict.get('cat')
'meow'
>>> mydict.set('cat', 'purr')
>>> mydict.get('cat')
'purr'
>>> mydict.get('dog')
Traceback (most recent call last):
KeyError: "Key 'dog' not found!"
>>> mydict.set('dog', 'woof')
>>> mydict.get('dog')
'woof'
>>> mydict.size == len(mydict.data)
True
'''
def __init__(self, size=50):
self.size = size
self.data = [None for _ in xrange(size)] # Initialize to "fixed" width
def set(self, key, value):
raise NotImplemented() # See implementations below
def get(self, key):
raise NotImplemented() # See implementations below
def _get_index(self, key):
return hash(key) % self.size
##############################
### LINKED LIST IMPLEMENTATION
##############################
# [node|->](key, value)
def set(self, key, value):
node = self._get_sublist(key)
# If first node at idx=i
if not node.has_content:
node.content = (key, value)
return
# If existing nodes at idx=i
last = None
while node is not None:
if self._check_key(node, key):
node.content = (key, value)
return
last = node
node = node.next
last.next = linkedlist.node((key, value))
def get(self, key):
node = self._get_sublist(key)
while node is not None:
if self._check_key(node, key):
return self._get_value(node)
else:
node = node.next
raise KeyError('Key \'{}\' not found!'.format(key))
def _get_sublist(self, key):
idx = self._get_index(key)
if self.data[idx] is None:
self.data[idx] = linkedlist.node()
return self.data[idx]
def _check_key(self, node, key):
if node.has_content:
k, v = node.content
return k == key
def _get_value(self, node):
k, v = node.content
return v
########################
### ARRAY IMPLEMENTATION
########################
# def set(self, key, value):
# subarray = self._get_subarray(key)
# for i in xrange(len(subarray)):
# k,v = subarray[i]
# if k == key:
# subarray[i] = (key, value)
# return
# subarray.append((key, value))
# def get(self, key):
# subarray = self._get_subarray(key)
# for k, v in subarray:
# if k == key:
# return v
# raise KeyError('Key \'{}\' not found!'.format(key))
# def _get_subarray(self, key):
# idx = self._get_index(key)
# if self.data[idx] is None:
# self.data[idx] = []
# return self.data[idx]
if __name__ == "__main__":
import doctest
doctest.testmod() |
eb906b7e96fd958250a723111dd4584c1bac5951 | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/PYTHON_PRAC/leetcode/Suffix_Trie_Construction.py | 937 | 3.984375 | 4 | class SuffixTrie:
def __init__(self, string):
self.root = {}
self.endSymbol = "*"
self.populateSuffixTrieFrom(string)
def populateSuffixTrieFrom(self, string):
for i in range(len(string)):
self.insertSubstringStartingAt(i, string)
def insertSubstringStartingAt(self, i, string):
node = self.root
for j in range(i, len(string)):
letter = string[j]
if letter not in node:
node[letter] = {}
node = node[letter]
node[self.endSymbol] = True
def contains(self, string):
node = self.root
for letter in string:
print(node, letter)
if letter not in node:
return False
node = node[letter]
return self.endSymbol in node
if __name__ == "__main__":
string = "babc"
trie = SuffixTrie(string)
print(trie.contains("abc"))
|
80ef5338b36b2cba36e0339a0d9b0b011c5efa96 | krishnabojha/Insight_workshop_Assignment3 | /Question41.py | 159 | 4.4375 | 4 | ####### convert tuple to string
tuple_value=tuple(input('Enter element of tuple separated by space : ').split())
print("Output String : "+''.join(tuple_value)) |
3434cd288269be94c2cd68058abb7de83ffb2f78 | infinite-Joy/programming-languages | /python-projects/algo_and_ds/group_people_based_on_size_union_find.py | 3,298 | 3.71875 | 4 | """
https://leetcode.com/problems/group-the-people-given-the-group-size-they-belong-to/
Input: groupSizes = [3,3,3,3,3,1,3]
Output: [[5],[0,1,2],[3,4,6]]
Explanation:
Other possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]].
what can be done is that people can be grouped if there are the same group size. and if both left and right groups have not exceeded their groupings.
so for all the new ids, try joining with one of the previous components. if am able to join then there its fine. else will create a new set out of this
===================================
time complexity with path compression: O((m+n)(logn)) so there is an additional n component here for the forloop
this would be n2logn and for the amortised case it would be n2
space complexity is O(n)
"""
class UnionFind:
def __init__(self, size):
self.size = size
self.sz = [1 for _ in range(size)]
self.root_pointer = [i for i in range(size)]
self.num_components = size
self.comps = {i: [i] for i in range(size)}
def __repr__(self):
return "UF size: {}, sz: {}, root_pointer: {}, num_components: {}, comps: {}".format(self.size, self.sz, self.root_pointer, self.num_components, self.comps)
def __str__(self):
return repr(self)
def find(self, p, rps):
if rps is None:
rps = self.root_pointer
if rps[p] == p:
return p
rps[p] = self.find(rps[p], rps)
return rps[p]
def connected(self, p, q):
return self.root_pointer[p] == self.root_pointer[q]
def union(self, p, q, group_sizes):
if self.connected(p, q) is True:
return
root1 = self.root_pointer[p]
root2 = self.root_pointer[q]
component_lost = None
if (
group_sizes[p] > self.sz[root1] and
group_sizes[q] > self.sz[root2] and
group_sizes[p] == group_sizes[q] and
group_sizes[p] >= self.sz[root1] + self.sz[root2]
):
if self.sz[root1] < self.sz[root2]:
component_lost = root1
self.sz[root2] += self.sz[root1]
self.comps[root2].extend(self.comps[root1])
self.root_pointer[root1] = root2
else:
component_lost = root2
self.sz[root1] += self.sz[root2]
self.comps[root1].extend(self.comps[root2])
self.root_pointer[root2] = root1
self.num_components -= 1
if component_lost is not None:
del self.comps[component_lost]
return True
def main(group_sizes):
size = len(group_sizes)
disjoint_sets = UnionFind(size)
#__import__('pdb').set_trace()
for i in range(size):
curr_comp_size = disjoint_sets.num_components
new_comp_size = disjoint_sets.num_components
j = 0
components = list(disjoint_sets.comps.keys())
while curr_comp_size == new_comp_size and j < len(components):
q = components[j]
disjoint_sets.union(i, q, group_sizes)
j += 1
new_comp_size = disjoint_sets.num_components
print(disjoint_sets)
return [list(v) for _, v in disjoint_sets.comps.items()]
print(main([3,3,3,3,3,1,3]))
|
f4a7179215b7ac77dc35b3e6a22b94db70e161d7 | phucla0122/word-list-and-word-histogram-using-dictionary-in-Python | /build_word_list_final.py | 2,873 | 4.375 | 4 | """
SYSC 1005 A Fall 2018
Case study: iterative, incremental development of a function that uses
Python's str, list, and set types.
"""
import string
# For information about the string module, type help(string) at the shell
# prompt, or browse "The Python Standard Library", Section "Built-in Types",
# Subsection "Text Sequence Type - str" in the Python 3.7 documentation
# (available @ python.org).
def build_word_list(filename):
""" (str) -> list of str
Return a list of all the distinct words in the specified file,
sorted in ascending order.
>>> word_list = build_word_list('sons_of_martha.txt')
>>> word_list
>>> len(word_list) # How many different words are in the file?
"""
infile = open(filename, "r")
word_set = set()
for line in infile:
# Split each line into a list of words.
# By default, the split method removes all whitespace; e.g.,
# ' Hello, world! '.split() returns this list:
#
# ['Hello,', 'world!']
#
# and not:
#
# [' Hello,', ' world! ']
#
# Notice that the punctuation marks have not been removed.
word_list = line.split()
# For each word, first remove any leading or trailing punctuation,
# then convert the the word to lower case.
#
# Examples:
# 'Hello,'.strip(string.punctuation) returns 'Hello'.
# 'Hello'.lower() returns 'hello'.
for word in word_list:
word = word.strip(string.punctuation).lower()
# This statement is equivalent to:
# word = word.strip(string.punctuation)
# word = word.lower()
# Don't save any empty strings that were created when the
# punctuation marks were removed.
# For example, if word is bound to a hyphen, '-',
# word.strip(string.punctuation) yields the empty string, ''.
if word != '':
# Storing the words in a set discards any duplicates.
word_set.add(word)
# Now build the list of distinct words.
word_list = list(word_set)
# or,
# word_list = []
# for word in word_set:
# word_list.append(word)
# Sort the list into ascending order.
word_list.sort()
return word_list
if __name__ == '__main__':
word_list = build_word_list('sons_of_martha.txt')
print(word_list)
# individual words are extracted by splitting the text file into separate line and go through each line to split
# each individua words then remove its punctuation and put it into lowercase letter. Then put it into a list to ensure
# no duplicate are stored in the list and convert that set to a list. Then use sort to sort it into ascending order
# going from a-z |
53d470b6c656d6c4c2054ca759f8c5fb9ba3bbf3 | abriggs914/Coding_Practice | /Python/Salary/operators.py | 477 | 3.8125 | 4 | from enum import Enum
class Operators(Enum):
def __new__(cls, *args, **kwds):
value = len(cls.__members__) + 1
obj = object.__new__(cls)
obj._value_ = value
return obj
def __init__(self, n, f):
self.n = n
self.f = f
ADDITION = "+", lambda a, b: a + b
SUBTRACTION = "-", lambda a, b: a - b
MULTIPLICATION = "*", lambda a, b: a * b
DIVISION = "/", lambda a, b: a / b
POWER = "^", lambda a, b: a ** b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.