blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
2c9ee26b6423019db6701ce06d63e6b2f8fd1a9e | najarvis/DatabaseResearchCode | /test_mongo.py | 2,768 | 3.953125 | 4 | """Basic contact book program"""
from pymongo import MongoClient
def get_phone(user):
"""Extracts a phone number from a user dictionary and returns it as a string"""
phone_dict = user.get('phone_num')
if phone_dict is not None:
return "{}-{}".format(phone_dict.get('area'), phone_dict.get('num'))
return "ERROR"
def valid_phone(number):
"""Checks if a string is a valid phone number"""
return len(number) == 12 and \
number.count("-") == 2 and \
number[0:3].isdecimal() and \
number[4:7].isdecimal() and \
number[8:].isdecimal()
def run():
"""Main method. Loops infinitely and handles user input."""
client = MongoClient()
db = client.MongoDBSurvivalGuideExamples
users = db.users
while True:
# Basic menu.
print("1: Find User")
print("2: Insert User")
print("3: Remove User")
print("0: Exit")
intent = input("What would you like to do?: ")
# Find
if intent == "1":
user = input("Which User?: ")
# Search for a single user to see if they get a perfect match.
# We could use a library like fuzzywuzzy to check for close
# matches, but it's not super necessary in this case.
found_user = users.find_one({"name": user})
if found_user is not None:
print("Name: ", found_user.get('name'))
print("Phone Number: ", get_phone(found_user))
else:
print(user, "not found")
# Insert
elif intent == "2":
name = input("Name?: ")
if name in users.distinct("name"):
print(name, "already in the database")
continue
number = input("Phone Number? (format: XXX-XXX-XXXX): ")
if valid_phone(number) and name != "":
# Splitting up the phone number string into its components
area, num = number.split("-")[0], number[number.find("-")+1:]
# Insert the user into the database.
users.insert({"name": name, "phone_num": {"area": area, "num": num}})
print("User:", name, "inserted ")
# Remove
elif intent == "3":
name = input("Who would you like to remove?: ")
status = users.delete_one({"name": name})
if status.deleted_count == 1:
print(name, "removed successfully.")
else:
print(name, "not found")
# Exit
elif intent == "0":
print("Goodbye.")
break
else:
print("Unknown option:", intent)
print()
if __name__ == "__main__":
run()
|
76d8c678a8d779b495d2eae58d00dd425ad5874e | andre23arruda/pythonCeV | /Aula12.py | 3,691 | 4 | 4 | import datetime
import random
# ==================== DESAFIO 36 ======================== #
print('VAI COMPRAR UM CASA?')
casa = int(input('Digite o valor da casa: '))
salario = int(input('Digite seu salario: '))
anos = int(input('Digite em quantos anos pretende pagar: '))
prestacao = casa/(12*anos)
if prestacao>0.3*salario:
print('Emprestimo negado :(')
else:
print('Voce vai comprar sua casa sim ;)')
# ======================= DESAFIO 37 ======================== #
print('\nCONVERSÃO DE BASES')
numero = int(input('Digite um numero:'))
base = int(input('Deseja converter para qual base?\nEntre com: \n1 - Binario\n2 - Octal \n3 - Hexadecimal\n'))
lista_numero = [bin(numero),oct(numero),hex(numero)]
lista = ['binario','octal','hexadecimal']
if base == 1:
print('O numero {} é igual a {} em {}'.format(numero,lista_numero[0],lista[0]))
elif base == 2:
print('O numero {} é igual a {} em {}'.format(numero,lista_numero[1],lista[1]))
else:
print('O numero {} é igual a {} em {}'.format(numero, lista_numero[2], lista[2]))
# ========================== DESAFIO 38 ========================= #
print('\nCONFERIR NUMEROS')
n1 = int(input('Digite o primeiro numero: '))
n2 = int(input('Digite o segundo numero: '))
if n1>n2:
print('{} é maior que {}'.format(n1,n2))
elif n1 < n2:
print('{} é maior que {}'.format(n2, n1))
else:
print('Os numeros sao iguais')
# ======================= DESAFIO 39 ============================ #
print('\nALISTAMENTO')
ano = int(input('Em qual ano voce nasceu?'))
ano_atual = datetime.date.today().year
if ano_atual - ano == 18:
print('Está na hora de alistar')
elif ano_atual - ano < 18:
print('Faltam {} anos para se alistar'.format(18 -(ano_atual-ano)))
else:
print('Voce se alistou ha {} anos'.format(ano_atual-ano-18))
# =================== DESAFIO 40 ===================== #
print('\n SITUAÇÃO DO ALUNO')
n1 = int(input('Entre com a primeira nota: '))
n2 = int(input('Entre com a segunda nota: '))
media = (n1+n2)/2
if media < 5:
print('Aluno reprovado')
elif media>=5 and media <= 6.9:
print('Aluno de recuperação')
else:
print('Aluno aprovado')
# ======================== DESAFIO 41 ==================== #
print('\nCATEGORIA NATAÇÃO')
ano = int(input('Digite o ano de nascimento: '))
ano_atual = datetime.date.today().year
if ano_atual - ano <= 9:
print('Categoria: MIRIM')
elif ano_atual - ano >9 and ano_atual - ano <= 14:
print('Categoria: INFANTIL')
elif ano_atual - ano > 14 and ano_atual - ano <= 19:
print('Categoria: JUNIOR')
elif ano_atual - ano >19 and ano_atual - ano <= 20:
print('Categoria: SENIOR')
else:
print('Categoria: MASTER')
# ========================= DESAFIO 42 ============================ #
a = int(input('Digite o valor do lado a: '))
b = int(input('Digite o valor do lado b: '))
c = int(input('Digite o valor do lado c: '))
if a<b+c and b<a+c and c<a+b:
if a == b and b == c:
print('Triangulo equilatero')
elif (a==b and b != c) or (a==c and c !=b) or (c==b and b != a):
print('Triangulo isosceles')
elif (a!=b and a!=c and b!=c):
print('Trianculo escaleno')
else:
print('Nao é triangulo')
# ================= DESAFIO 45 ====================== #
print('LETS PLAY')
lista = [1,2,3]
pc = random.choice(lista)
usuario = int(input('Pedra, Papel ou Tesoura?\n1 - Pedra\n2 - Papel\n3 - Tesoura'))
if usuario - pc == 0:
print('O PC jogou {}\nEmpatou'.format(pc))
elif (usuario - pc == -1) or (usuario - pc == 2):
print('O PC jogou {}\nVoce Perdeu'.format(pc))
elif (usuario - pc == 1) or (usuario - pc == -2):
print('O PC jogou {}\nVoce Ganhou'.format(pc))
print('FIM DE JOGO')
|
637bf5bd13b4b2a8aea861b48507f5038d1aa335 | caleb-1212/ministry | /file_functions.py | 476 | 3.71875 | 4 | import os
# Ensures that a directory exists, it creates it if necessary
def ensure_dir(dir):
if not os.path.exists(dir):
os.makedirs(dir)
# Creates a file and writes the string into it
def writeStringToFile(fileName, contentStr):
file = open(fileName,"w")
file.write(contentStr)
# File closing is handled automaticaly (so the docs say!)
file.close() # But I'm not entirely sure about that... :)
def readFile(fileName):
return open(fileName, 'r').read()
|
01e555636656384332367f963f239957d0918fbc | impradeeparya/python-getting-started | /array/PascalTriangle.py | 880 | 3.765625 | 4 | class PascalTriangle(object):
def binomial_coefficient(self, line, index):
# C(n r) = n!/((n-r)! * r!)
n_factorial = 1
for number in range(1, line + 1):
n_factorial = n_factorial * number
n_r_factorial = 1
for number in range(1, (line - index) + 1):
n_r_factorial = n_r_factorial * number
r_factorial = 1
for number in range(1, index + 1):
r_factorial = r_factorial * number
return n_factorial / (n_r_factorial * r_factorial)
def generate(self, numRows):
triangle = []
for row in range(numRows):
row_elements = []
for column in range(row + 1):
row_elements.append(int(self.binomial_coefficient(row, column)))
triangle.append(row_elements)
return triangle
print(PascalTriangle().generate(5))
|
0cad813e776d034d231a8fd207c34bce5bc6aa28 | cmbrooks/APCS | /python/matrixmath.py | 3,024 | 3.828125 | 4 | #Scalar Addition ~~ WORKS
def add (A, p):
result = [[0 for x in range(len(A))] for x in range(len(A[0]))]
if checkMat(A) == True:
print "Number of Rows: " + str(len(A))
print "Number of Columns: " + str(len(A[0]))
for i in range(0, len(A)):
for j in range(0, len(A[i])):
result[i][j] = A[i][j] + p
print str(i) + " and " + str(j)
else:
print "The input A is an invalid matrix"
return result
#Scalar Addition
def add (p, A):
# result = {}{}
if checkMat(A) == True:
for i in A:
for j in A[i]:
result[i][j] = A[i][j] + p
else:
print "The input A is an invalid matrix"
return result
#Scalar Multiplication
def mult (A, p):
# result = {}{}
if checkMat(A) == True:
for i in A:
for j in A[i]:
result[i][j] = A[i][j] * p
else:
print "The input A is an invalid matrix"
return result
#Scalar Multiplication
def mu3lt (p, A):
# result = {}{}
if checkMat(A) == True:
for i in A:
for j in A[i]:
result[i][j] = A[i][j] * p
else:
print "The input A is an invalid matrix"
return result
#Matrix addition
def add (A, B):
# result = {}{}
if sameSize(A, B) == True:
for i in A:
for j in A[i]:
result[i][j] = A[i][j] + B[i][j]
else:
print "A and B cannot be added together"
return result
#Matrix Multiplication
def mult (A, B):
# result = {}{}
if checkMat(A) == True and checkMat(B) == True and canMult(A, B):
multSum = 0
for i in A:
for j in A[i]:
for k in A[i]:
multSum += (A[i][j] * B[i][j])
result[i][j] = multSum
multSum = 0
else:
print "A and B cannot be multiplied"
return result
#Checks to make sure A is a valid matrix
def checkMat (A):
# bool result = False
i = 0
while i < len(A):
if len(A[i]) == len(A[0]):
result = True
else:
result = False
break
i += 1
if result == True:
print "Matrix is valid"
else:
print "Matrix is invalid"
return result
#Checks to see if two matrices are the same dimensions
def sameSize (A, B):
# bool result = False
if checkMat(A) == True and checkMat(B) == True:
if len(A) == len(B) and len(A[0]) == len(B[0]):
result = True
else:
result = False
return result
#Checks to see if two matrices can be multiplied
def canMult (A, B):
# bool result = False
if checkMat(A) == True and checkMat(B) == True and len(A[0]) == len(B):
result = True
else:
result = False
return result
### Main Function ###
print "hello world"
A = [[1,3,5],
[3,8,3],
[1,9,3]]
p = 2
resultArray = add (A, p)
for i in A:
for j in A[i]:
print ("\t" + resultArray[i][j])
print "\n"
|
85c30ce8ef7215062cc5d117a53768ba868c3e81 | Ariussssss/leetcode | /for-fun/gift-count.py | 1,455 | 3.59375 | 4 | """
评分分数不同
每个分数有他的礼物
打得比小的多
最少有多少个礼物
"""
def smallHeap(arr, root=None):
left = 2 * root + 1
right = left + 1
length = len(arr)
small = root
if left < length and arr[small] > arr[left]:
small = left
if right < length and arr[small] > arr[right]:
small = right
if small != root:
arr[root], arr[small] = arr[small], arr[root]
def buildSmallHeap(arr):
end = int(len(arr) / 2)
for x in range(end, -1, -1):
smallHeap(arr, x)
def gift_count(score_list):
last = None
gift_sum = 0
gift_level = 1
# res = {}
for x in range(0, len(score_list)):
buildSmallHeap(score_list)
tmp = last
last = score_list.pop(0)
if tmp and tmp != last:
gift_level += 1
gift_sum += gift_level
# if last in res:
# res[last] += gift_level
# else:
# res[last] = gift_level
# print(res)
return gift_sum
import unittest
class TestSolution(unittest.TestCase):
def test_filter_str(self):
fn = gift_count
self.assertEqual(fn([9]), 1)
self.assertEqual(fn([9, 9]), 2)
self.assertEqual(fn([9, 9, 8]), 5)
self.assertEqual(fn([9, 7, 8]), 6)
self.assertEqual(fn([9, 9, 7, 8]), 9)
self.assertEqual(fn([9, 9, 7, 8,1,23,54,76,564,1,23,543]), 55)
if __name__ == '__main__':
unittest.main()
|
89e5bdb099b970ffc93e3c03db11bd8c01368a23 | FatChicken277/holbertonschool-higher_level_programming | /0x0A-python-inheritance/100-my_int.py | 559 | 3.890625 | 4 | #!/usr/bin/python3
"""This module contains a class MyInt that inherits from int
"""
class MyInt(int):
"""class MyInt that inherits from int
Arguments:
int -- int
"""
def __eq__(self, other):
"""[summary]
Arguments:
other -- other
Returns:
not equal
"""
return super().__ne__(other)
def __ne__(self, other):
"""[summary]
Arguments:
other -- other
Returns:
equal
"""
return super().__eq__(other)
|
7a1794023d7eeb023c4f9d85fa1d35dd63f88617 | UtkarshBhardwaj123/Commit-Ur-Code | /Day - 4/Rohan-Saini.py | 298 | 3.734375 | 4 | def check(s_1, s_2):
s_1 += s_1
if (s_1.count(s_2) != 0):
print("YES") # Now Rajat Become Happy.
else:
print("NO")
for i in range(int(input())):
s_1 = input()
s_2 = input()
if len(s_1) == len(s_2):
check(s_1, s_2)
else:
print("NO")
|
e18f804bf10298f005c634ba34781ffe67576ac5 | Rafiul-Islam/Data-Structure-And-Algorithms | /Data Structures/Tree/BST.py | 3,026 | 3.859375 | 4 | class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class BST:
def __init__(self):
self.root = None
def insert_data(self, data, current_node):
if self.root is None:
new_node = Node(data)
self.root = new_node
return
else:
if current_node is None:
current_node = Node(data)
elif data > current_node.data:
current_node.right = self.insert_data(data, current_node.right)
else:
current_node.left = self.insert_data(data, current_node.left)
return current_node
def search_data(self, data, current_node):
if current_node is None:
return False
elif data == current_node.data:
return True
elif data > current_node.data:
return self.search_data(data, current_node.right)
else:
return self.search_data(data, current_node.left)
def find_min_value(self, current_node):
min_value = current_node.data
while current_node is not None:
min_value = current_node.data
current_node = current_node.left
return min_value
def delete_data(self, data, current_node):
if current_node is None:
return current_node
elif current_node.data > data:
current_node.left = self.delete_data(data, current_node.left)
elif current_node.data < data:
current_node.right = self.delete_data(data, current_node.right)
else:
if current_node.left is None and current_node.right is None:
current_node = None
elif current_node.left is None:
current_node = current_node.right
elif current_node.right is None:
current_node = current_node.left
else:
current_node.data = self.find_min_value(current_node.right)
current_node.right = self.delete_data(current_node.data, current_node.right)
return current_node
def in_order_traversal(self, current_node):
if current_node is None:
return
self.in_order_traversal(current_node.left)
print(current_node.data, end=' ')
self.in_order_traversal(current_node.right)
bst = BST()
bst.insert_data(15, bst.root)
bst.insert_data(10, bst.root)
bst.insert_data(20, bst.root)
bst.insert_data(25, bst.root)
bst.insert_data(8, bst.root)
bst.insert_data(12, bst.root)
bst.insert_data(11, bst.root)
bst.insert_data(9, bst.root)
bst.insert_data(2, bst.root)
bst.in_order_traversal(bst.root)
print()
# print('Exist' if bst.search_data(8, bst.root) else 'Not Exist')
# print('Exist' if bst.search_data(14, bst.root) else 'Not Exist')
# print('Min Value:', bst.find_min_value(bst.root))
bst.delete_data(10, bst.root)
bst.in_order_traversal(bst.root)
print()
bst.delete_data(20, bst.root)
bst.in_order_traversal(bst.root)
|
03d707fa03cf1bd56bbe3cf0530be1bdb8547390 | pfreisleben/Blue | /Modulo1/Aula 08 - Listas /listas.py | 135 | 3.6875 | 4 | lista = [1, 2, 3, 4, 5, 6]
lista2 = [1, 2, 3, [4, 5]]
print(lista[0])
print(lista[2:4])
print(lista[1] + lista[4])
print(lista2[3][0])
|
223678ab3366c5eaa46a0fee06c84a08e177a8d6 | CodecoolBP20172/pbwp-1st-si-game-inventory-RichardSzombat | /gameInventory.py | 3,604 | 3.828125 | 4 | # This is the file where you must work. Write code in the functions, create new functions,
# so they work according to the specification
import operator
from pathlib import Path
import os.path
import os
import csv
from collections import Counter
mylist = list()
inv = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12, }
dragon_loot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
exporting = "export_inventory.csv"
importing = "test_inventory.csv"
# Displays the inventory.
def display_inventory(inventory):
print("Inventory : ")
for item in inventory:
print(inventory[item], item)
print("Total number of items : " + str(sum(inventory.values())))
# Adds to the inventory dictionary a list of items from added_items.
def add_to_inventory(inventory, added_items):
for item in added_items:
if item in inventory.keys():
inventory[item] += 1
else:
inventory[item] = 1
return inventory
# Takes your inventory and displays it in a well-organized table with
# each column right-justified. The input argument is an order parameter (string)
# which works as the following:
# - None (by default) means the table is unordered
# - "count,desc" means the table is ordered by count (of items in the inventory)
# in descending order
# - "count,asc" means the table is ordered by count in ascending order
def print_table(inventory, order=None):
while True:
if order is None:
sorted_inventory = inventory.items()
break
if order == "count,asc":
sorted_inventory = sorted(
inventory.items(), key=operator.itemgetter(1), reverse=False)
break
if order == "count,desc":
sorted_inventory = sorted(
inventory.items(), key=operator.itemgetter(1), reverse=True)
break
else:
continue
print("Inventory : ")
c = ("{:>8} {:>15}".format("Count", "Item name"))
print(c)
print(len(c) * "-")
for key, value in sorted_inventory:
print("{:>8} {:>15}".format(value, key))
print(len(c) * "-")
print("Total number of items : " + str(sum(inventory.values())))
return inventory.items()
# Imports new inventory items from a file
# The filename comes as an argument, but by default it's
# "import_inventory.csv". The import automatically merges items by name.
# The file format is plain text with comma separated values (CSV).
def import_inventory(inventory, filename):
with open(filename) as imported_items:
reader = csv.reader(imported_items)
mylist = list(reader)
for items in mylist:
for word in items:
if word == "":
break
if word[-2:] == "\n":
word = word[:-2]
if word in inventory.keys():
inventory[word] += 1
else:
inventory[word] = 1
# Exports the inventory into a .csv file.
# if the filename argument is None it creates and overwrites a file
# called "export_inventory.csv". The file format is the same plain text
# with comma separated values (CSV).
def export_inventory(inventory, filename):
c=Counter(inventory)
c=sorted(c.elements())
with open(filename, 'w') as f:
fWriter=csv.writer(f)
fWriter.writerow(c)
pass
#display_inventory(inv)
add_to_inventory(inv, dragon_loot)
import_inventory(inv, "import_inventory.csv")
print_table(inv,"count,desc")
export_inventory(inv, "export_inventory.csv")
|
fa036d1fca1693f827f8c129ac3b2a8ec396ae76 | cryoMike90s/Daily_warm_up | /Basic_Part_I/ex_118_bytearray.py | 214 | 3.796875 | 4 | """Write a Python program to create a bytearray from a list."""
def bytearray_from_list(lista:list):
return print(bytearray(" ".join(lista), 'utf-16'))
lista = ["a","dupa","hehe"]
bytearray_from_list(lista) |
d5e86c8cacdb71567a506fafbd0672d29814dcc9 | alexwaweru/Algorithm-Design-and-Analysis | /selection_sort.py | 306 | 3.59375 | 4 | def selection_sort(list1):
n = len(list1)
for i in range(n-2):
min_idx = i
for j in range(n-1):
if list1[j] < list1[i]:
min_idx = j
temp = list1[min_idx]
list1[min_idx] = list1[i]
list1[i] = temp
return list1
|
268bbd92ab5c59b2a42d1f608d0881e7205e1ff1 | Nkaka23dev/data-structure-python | /general/prime_numbers.py | 149 | 3.640625 | 4 | def prime(num1,num2):
for i in range(num1,num2+1):
if num1>1 and num2>1:
if i%2!=0:
print(i)
prime(900,1000) |
9e0b210e4c2a78f5a3a9ae25820c28d3553abee4 | a-tal/nagaram | /nagaram/scrabble.py | 4,618 | 4.15625 | 4 | """Scrabble related functions, score counters, etc."""
import os
def letter_score(letter):
"""Returns the Scrabble score of a letter.
Args:
letter: a single character string
Raises:
TypeError if a non-Scrabble character is supplied
"""
score_map = {
1: ["a", "e", "i", "o", "u", "l", "n", "r", "s", "t"],
2: ["d", "g"],
3: ["b", "c", "m", "p"],
4: ["f", "h", "v", "w", "y"],
5: ["k"],
8: ["j", "x"],
10: ["q", "z"],
}
for score, letters in score_map.items():
if letter.lower() in letters:
return score
else:
raise TypeError("Invalid letter: %s", letter)
def word_score(word, input_letters, questions=0):
"""Checks the Scrabble score of a single word.
Args:
word: a string to check the Scrabble score of
input_letters: the letters in our rack
questions: integer of the tiles already on the board to build on
Returns:
an integer Scrabble score amount for the word
"""
score = 0
bingo = 0
filled_by_blanks = []
rack = list(input_letters) # make a copy to speed up find_anagrams()
for letter in word:
if letter in rack:
bingo += 1
score += letter_score(letter)
rack.remove(letter)
else:
filled_by_blanks.append(letter_score(letter))
# we can have both ?'s and _'s in the word. this will apply the ?s to the
# highest scrabble score value letters and leave the blanks for low points.
for blank_score in sorted(filled_by_blanks, reverse=True):
if questions > 0:
score += blank_score
questions -= 1
# 50 bonus points for using all the tiles in your rack
if bingo > 6:
score += 50
return score
def blank_tiles(input_word):
"""Searches a string for blank tile characters ("?" and "_").
Args:
input_word: the user supplied string to search through
Returns:
a tuple of:
input_word without blanks
integer number of blanks (no points)
integer number of questions (points)
"""
blanks = 0
questions = 0
input_letters = []
for letter in input_word:
if letter == "_":
blanks += 1
elif letter == "?":
questions += 1
else:
input_letters.append(letter)
return input_letters, blanks, questions
def word_list(sowpods=False, start="", end=""):
"""Opens the word list file.
Args:
sowpods: a boolean to declare using the sowpods list or TWL (default)
start: a string of starting characters to find anagrams based on
end: a string of ending characters to find anagrams based on
Yeilds:
a word at a time out of 178691 words for TWL, 267751 for sowpods. Much
less if either start or end are used (filtering is applied here)
"""
location = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
"wordlists",
)
if sowpods:
filename = "sowpods.txt"
else:
filename = "twl.txt"
filepath = os.path.join(location, filename)
with open(filepath) as wordfile:
for word in wordfile.readlines():
word = word.strip()
if start and end and word.startswith(start) and word.endswith(end):
yield word
elif start and word.startswith(start) and not end:
yield word
elif end and word.endswith(end) and not start:
yield word
elif not start and not end:
yield word
def valid_scrabble_word(word):
"""Checks if the input word could be played with a full bag of tiles.
Returns:
True or false
"""
letters_in_bag = {
"a": 9,
"b": 2,
"c": 2,
"d": 4,
"e": 12,
"f": 2,
"g": 3,
"h": 2,
"i": 9,
"j": 1,
"k": 1,
"l": 4,
"m": 2,
"n": 6,
"o": 8,
"p": 2,
"q": 1,
"r": 6,
"s": 4,
"t": 6,
"u": 4,
"v": 2,
"w": 2,
"x": 1,
"y": 2,
"z": 1,
"_": 2,
}
for letter in word:
if letter == "?":
continue
try:
letters_in_bag[letter] -= 1
except KeyError:
return False
if letters_in_bag[letter] < 0:
letters_in_bag["_"] -= 1
if letters_in_bag["_"] < 0:
return False
return True
|
3bdc1d05fa08767e70ed1678fde95475c1e36aa5 | jjti/euler | /Done/52.py | 1,079 | 3.75 | 4 | import utils
"""
Permuted multiples
Problem 52
It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.
Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.
"""
def split_map(n):
"""Create a dictionary between an integer and it's digit counts
ex: split_map(8199) = {'8': 1, '1': 1, '9': 2}
"""
split_n = utils.split(n)
MAP = {}
for m in split_n:
if m in MAP:
MAP[m] += 1
else:
MAP[m] = 0
return MAP
def maps_same(m, n):
"""Compare two digit count maps
return whether the digit counts in the two maps are the same
"""
for k in n.keys():
if k not in m or m[k] is not n[k]:
return False
return True
ans = -1
i = 1
while ans < 0:
i += 1
# test 2 - 6 multipliers
i_m = split_map(i)
for j in range(2, 7):
j_m = split_map(i * j)
if not maps_same(i_m, j_m):
break
if j == 6:
ans = i
print i
|
a521b1d9a959401706622576f4a495e1037d72bb | NPencheva/Python_Advanced_Preparation | /03_multidimensional_lists/2021.02_multidimensional_lists_exercises/03_Maximum Sum.py | 1,583 | 3.84375 | 4 | from sys import maxsize
number_of_rows, number_of_columns = [int(x) for x in input().split()]
matrix = []
for row_index in range(number_of_rows):
row = [int(y) for y in input().split()]
matrix.append(row)
max_3x3_square_sum = -maxsize
starting_row = 0
starting_column = 0
for row_index in range(number_of_rows - 2):
for column_index in range(number_of_columns - 2):
square_3x3_sum = (matrix[row_index][column_index]
+ matrix[row_index][column_index + 1]
+ matrix[row_index][column_index + 2]
+ matrix[row_index + 1][column_index]
+ matrix[row_index + 1][column_index + 1]
+ matrix[row_index + 1][column_index + 2]
+ matrix[row_index + 2][column_index]
+ matrix[row_index + 2][column_index + 1]
+ matrix[row_index + 2][column_index + 2]
)
if square_3x3_sum > max_3x3_square_sum:
max_3x3_square_sum = square_3x3_sum
starting_row = row_index
starting_column = column_index
print(f"Sum = {max_3x3_square_sum}")
matrix_3x3 = [matrix[starting_row][starting_column:starting_column + 3],
matrix[starting_row + 1][starting_column:starting_column + 3],
matrix[starting_row + 2][starting_column:starting_column + 3]]
for index in range(len(matrix_3x3)):
row_str = [str(x) for x in matrix_3x3[index]]
final_row = " ".join(row_str)
print(final_row)
|
3361f966a3ea45d6134aa5e35e2d9a7984f8e6c8 | bruhmentomori/python | /lek1.py | 200 | 3.71875 | 4 | print("hej på er i ee17")
firstName = "William"
lastName = "Lannerblad"
#dateOfBirth = 20000518
age = 19
teacher = True
print(firstName , lastName + str(age) + str(teacher))
print(dateOfBirth + " ") |
7e169df5ec7f0f24a7fa2c42cc350a14d1727be0 | jahosh/coursera | /algorithms1/assignment1/practice_ds/quickunion/quickunion.py | 1,078 | 3.578125 | 4 | from typing import Tuple
class QuickUnion:
def __init__(self, size: int) -> None:
self.size = size
self.storage = [i for i in range(size)]
def _check_indicies(self, a: int, b: int) -> None:
if a > self.size or b > self.size:
raise Exception("""
Index ouit of range error. Please check index of
a or b and try again.
""")
def _get_roots(self, a: int, b: int) -> Tuple[int, int]:
a_root = a
b_root = b
while (
self.storage[a_root] != a_root
or self.storage[b_root] != b_root
):
a_root = self.storage[a_root]
b_root = self.storage[b_root]
return (a_root, b_root)
def is_connected(self, a: int, b: int) -> bool:
self._check_indicies(a, b)
a_root, b_root = self._get_roots(a, b)
return a_root == b_root
def union(self, a: int, b: int) -> None:
self._check_indicies(a, b)
a_root, b_root = self._get_roots(a, b)
self.storage[b_root] = a_root
|
0b4d40692b1d4d74c5f9ca1bda24afe6975ecf63 | MamaD33R/Python-Projects | /Web Page Generator/WebPageGen.py | 1,152 | 3.59375 | 4 |
import webbrowser
import tkinter as Tk
from tkinter import *
window = Tk()
# GUI resizable window
window.title("Web Page Generator")
window.geometry('600x350')
# label details of program
lbl = Label(window, text="Greetings! Go ahead and get started!", font=("Arial Bold", 15))
lbl.grid(row=1, column=4, pady=20, padx=20)
lbl2 = Label(window, text="HTML Text Here: ")
lbl2.grid(row=2, column=2)
# the entry textbox for the body text
txt = Entry(window,width=50)
txt.grid(column=4, row=6, padx=20, pady=15)
# button to submit the new text to generated webpage
btn1 = Button(window, text="CREATE", bg="lightgreen", command=lambda:CREATE())
btn1.grid(column=4, row=7, padx=5, pady=5)
# the function to generate the html body text and open in new tab
def CREATE():
entryText = txt.get()
htmlCode = "<!DOCTYPE html><head><title>Generated Webpage</title></head><body> {} </body></html>".format(entryText)
f = open("webpage.html", "w")
f.write(htmlCode)
f.close()
webbrowser.open_new_tab("C:/Users/space/OneDrive/Documents/GitHub/Python-Projects/Web Page Generator/webpage.html")
if __name__ == "__main__":
window.mainloop()
|
03becef898404e7f974ca88d5e5404033196b047 | wangjiaxin1100/PythonAutoTest | /Course/Chapter9/die.py | 289 | 3.578125 | 4 | from random import randint
class Die():
"""定义一个色子"""
def __init__(self):
self.sides = 6
def roll_die(self):
number = randint(1,self.sides)
print(number)
die = Die()
die.roll_die()
die.sides = 10
die.roll_die()
die.sides = 20
die.roll_die() |
2ac1bfdf70fef9cd8e2889a77956d90c3bab67d5 | joaohfgarcia/python | /uniesp_p2/lista1_6.py | 810 | 3.953125 | 4 |
def calculaNotas(valor):
notas100 = int(valor/100)
valor = valor - 100*notas100
notas50 = int(valor/50)
valor = valor - 50*notas50
notas20 = int(valor/20)
valor = valor - 20*notas20
notas10 = int(valor/10)
valor = valor - 10*notas10
notas5 = int(valor/5)
print ("Notas de R$ 100: ", notas100)
print ("Notas de R$ 50: ", notas50)
print ("Notas de R$ 20: ", notas20)
print ("Notas de R$ 10: ", notas10)
print ("Notas de R$ 5: ", notas5)
def main():
saque = float(input ("Digite o valor do saque (Mín: R$10,00 Máx: R$600,00):"))
while saque < 10 or saque > 600:
print ("Valor inválido")
saque = float(input ("Digite o valor do saque (Mín: R$10,00 Máx: R$600,00):"))
calculaNotas(saque)
main() |
acd0a496bcbb0e404bd46af96080c466df5a342e | jdferreira/hackerrank | /Practice/Algorithms/02 Implementation/queens-attack-2.py | 1,206 | 4.09375 | 4 | #!/usr/bin/env python3
DIRECTIONS = [
( 1, 0),
( 1, 1),
( 0, 1),
(-1, 1),
(-1, 0),
(-1, -1),
( 0, -1),
( 1, -1),
]
def get_tuple(convert=int):
return tuple(convert(i) for i in input().split())
def move(here, direction):
return tuple(h + d for h, d in zip(here, direction))
def get_possible_squares(n, queen, obstacles):
# print('QUEEN = {}'.format(queen))
# print('OBSTACLES = {}'.format(obstacles))
# A function to detect squares on the outside of the board
def is_inside(point):
return all(1 <= coord <= n for coord in point)
res = 0
for direction in DIRECTIONS:
# print('DIR = {}'.format(direction))
here = queen
while True:
here = move(here, direction)
# print('HERE = {}'.format(here))
if is_inside(here) and here not in obstacles:
res += 1
else:
# print('NOT ANY MORE!')
break
return res
if __name__ == '__main__':
n, k = get_tuple()
queen = get_tuple()
obstacles = {get_tuple() for _ in range(k)}
print(get_possible_squares(n, queen, obstacles))
|
912472c51112c443bd3a846e6e921edb851fdbed | nmm6025/Homework4 | /main.py | 3,971 | 4.25 | 4 | # Author: Nick McCuch [email protected]
grade1 = input("Enter your course 1 letter grade: ")
course1 = input("Enter your course 1 credit: ")
if grade1 == "A" or grade1 == "a":
gradepoint1 = float(4.0)
print(f"Grade point for course 1 is: {gradepoint1}")
elif grade1 == "A-" or grade1 == "a-":
gradepoint1 = float(3.67)
print(f"Grade point for course 1 is: {gradepoint1}")
elif grade1 == "B+" or grade1 == "b+":
gradepoint1 = float(3.33)
print(f"Grade point for course 1 is: {gradepoint1}")
elif grade1 == "B" or grade1 == "b":
gradepoint1 = float(3.0)
print(f"Grade point for course 1 is: {gradepoint1}")
elif grade1 == "B-" or grade1 == "b-":
gradepoint1 = float(2.67)
print(f"Grade point for course 1 is: {gradepoint1}")
elif grade1 == "C+" or grade1 == "c+":
gradepoint1 = float(2.33)
print(f"Grade point for course 1 is: {gradepoint1}")
elif grade1 == "C" or grade1 == "c":
gradepoint1 = float(2.0)
print(f"Grade point for course 1 is: {gradepoint1}")
elif grade1 == "D" or grade1 == "d":
gradepoint1 = float(1.0)
print(f"Grade point for course 1 is: {gradepoint1}")
elif grade1 == "F" or grade1 == "f":
gradepoint1 = float(0.0)
print(f"Grade point for course 1 is: {gradepoint1}")
else:
print(f"Grade point for course 1 is: {float(0.0)}")
grade2 = input("Enter your course 2 letter grade: ")
course2 = input("Enter your course 2 credit: ")
if grade2 == "A" or grade2 == "a":
gradepoint2 = float(4.0)
print(f"Grade point for course 2 is: {gradepoint2}")
elif grade2 == "A-" or grade2 == "a-":
gradepoint2 = float(3.67)
print(f"Grade point for course 2 is: {gradepoint2}")
elif grade2 == "B+" or grade2 == "b+":
gradepoint2 = float(3.33)
print(f"Grade point for course 2 is: {gradepoint2}")
elif grade2 == "B" or grade2 == "b":
gradepoint2 = float(3.0)
print(f"Grade point for course 2 is: {gradepoint2}")
elif grade2 == "B-" or grade2 == "b-":
gradepoint2 = float(2.67)
print(f"Grade point for course 2 is: {gradepoint2}")
elif grade2 == "C+" or grade2 == "c+":
gradepoint2 = float(2.33)
print(f"Grade point for course 2 is: {gradepoint2}")
elif grade2 == "C" or grade2 == "c":
gradepoint2 = float(2.0)
print(f"Grade point for course 2 is: {gradepoint2}")
elif grade2 == "D" or grade2 == "d":
gradepoint2 = float(1.0)
print(f"Grade point for course 2 is: {gradepoint2}")
elif grade2 == "F" or grade2 == "f":
gradepoint2 = float(0.0)
print(f"Grade point for course 2 is: {gradepoint2}")
else:
print(f"Grade point for course 2 is: {float(0.0)}")
grade3 = input("Enter your course 3 letter grade: ")
course3 = input("Enter your course 3 credit: ")
if grade3 == "A" or grade3 == "a":
gradepoint3 = float(4.0)
print(f"Grade point for course 3 is: {gradepoint3}")
elif grade3 == "A-" or grade3 == "a-":
gradepoint3 = float(3.67)
print(f"Grade point for course 3 is: {gradepoint3}")
elif grade3 == "B+" or grade3 == "b+":
gradepoint3 = float(3.33)
print(f"Grade point for course 3 is: {gradepoint3}")
elif grade3 == "B" or grade3 == "b":
gradepoint3 = float(3.0)
print(f"Grade point for course 3 is: {gradepoint3}")
elif grade3 == "B-" or grade3 == "b-":
gradepoint3 = float(2.67)
print(f"Grade point for course 3 is: {gradepoint3}")
elif grade3 == "C+" or grade3 == "c+":
gradepoint3 = float(2.33)
print(f"Grade point for course 3 is: {gradepoint3}")
elif grade3 == "C" or grade3 == "c":
gradepoint3 = float(2.0)
print(f"Grade point for course 3 is: {gradepoint3}")
elif grade3 == "D" or grade3 == "d":
gradepoint3 = float(1.0)
print(f"Grade point for course 3 is: {gradepoint3}")
elif grade3 == "F" or grade3 == "f":
gradepoint3 = float(0.0)
print(f"Grade point for course 3 is: {gradepoint3}")
else:
print(f"Grade point for course 3 is: {float(0.0)}")
GPA = ((float(course1) * float(gradepoint1) + float(course2) * float(gradepoint2)) + (float(course3) * float(gradepoint3)) / ((float(course1) + float(course2) + float(course3))))
print(f"Your GPA is: {GPA}") |
4d9b74ab539885e6d1d667b7fc4b9cc8c839c793 | hasanunl/Hierarchical-Clustering-in-Python-Training | /hc_training.py | 1,246 | 3.515625 | 4 |
#Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#Importing the mall dataset with pandas
dataset = pd.read_csv('Mall_Customers.csv')
X = dataset.iloc[:,[3,4]].values
# Using the dendrogram to find the optimal number of clusters
import scipy.cluster.hierarchy as sch
dendrogram = sch.dendrogram(sch.linkage(X,method = 'ward'))
plt.title('Dendrogram')
plt.xlabel('customers')
plt.ylabel('Euclidean distances')
plt.show()
# Fitting hierarchical clustering to the mall dataset
from sklearn.cluster import AgglomerativeClustering
hc = AgglomerativeClustering(n_clusters = 5, affinity = 'euclidean',linkage = 'ward')
y_hc = hc.fit_predict(X)
#Visualing the clusters
plt.scatter(X[y_hc == 0,0],X[y_hc == 0,1], s = 100 ,c='red',label = 'Careful')
plt.scatter(X[y_hc == 1,0],X[y_hc == 1,1], s = 100 ,c='blue',label = 'Standard')
plt.scatter(X[y_hc == 2,0],X[y_hc == 2,1], s = 100 ,c='green',label = 'Target')
plt.scatter(X[y_hc == 3,0],X[y_hc == 3,1], s = 100 ,c='cyan',label = 'Careless')
plt.scatter(X[y_hc == 4,0],X[y_hc == 4,1], s = 100 ,c='magenta',label = 'Sensible')
plt.title('Clusters of clients')
plt.xlabel('Annual Income (k$) ')
plt.ylabel('Spending Score (1-100)')
plt.legend()
plt.show()
|
fae4c1488518b5b0af4424e52b792f856eb1dc9c | yeboahd24/Python201 | /competitive programming/problem5.py | 840 | 4.34375 | 4 | #!usr/bin/env/python3
# Python program to find the smallest and second smallest elements
import sys
def print2Smallest(arr):
# There should be atleast two elements
arr_size = len(arr)
if arr_size < 2:
print('Invalid Input')
return
first = second = sys.maxsize
for i in range(0, arr_size):
# If current element is smaller than first then
# Update both first and second
if arr[i] < first:
second = first
first = arr[i]
# If arr[i] is in between first and second then update second
elif (arr[i] < second and arr[i] != first):
second = arr[i]
if (second == sys.maxsize):
print('No second smallest element')
else:
print(f'The smallest element is: {first} and the second smallest element is: {second}')
# Test Case
arr = [12, 13, 1, 10, 34, 1]
print(print2Smallest(arr)) |
a2b3384b5e04e99f794c2a4dfd836cdca902fb05 | rathoddilip/InheritanceUsingPython | /single_inheritance.py | 268 | 3.640625 | 4 | class Father:
fatherName = ""
def father(self):
return self.fatherName
class Son(Father):
def parents(self):
print("Father name :", self.fatherName)
if __name__ == '__main__':
s1 = Son()
s1.fatherName = "RAM"
s1.parents()
|
6350846861ea3cef8cf10674c79c8522a0e7f036 | rohit2219/python | /bloomberg3.py | 2,691 | 3.90625 | 4 | import copy
class Node():
def __init__(self, inpToNode):
self.data = inpToNode
self.next = None
self.random = None
class linList():
def __init__(self):
self.head = None
def insertNode(self, inpData):
if self.head == None:
tempNode = Node(inpData)
self.head = tempNode
self.head.next = None
else:
tempNode = Node(inpData)
tempNode.next = self.head
self.head = tempNode
def travelList(self):
curNode = self.head
while curNode != None:
print('list data:', curNode.data)
curNode = curNode.next
def reverseList(self):
print('revresal linked list')
prevNode = None
curNode = self.head
nextNode = self.head.next
print(curNode.data, nextNode.data, prevNode)
i = 0
while curNode != None:
curNode.next = prevNode
tempNode = nextNode
self.head = curNode
prevNode = curNode
if nextNode != None:
nextNode = nextNode.next
curNode = tempNode
return
def insertNodeObj(self, inpNode):
inpNode.next = self.head
self.head = inpNode
return
def copyLinList(self):
copyListObj=linList()
curNode = self.head
copyNode = copy.copy(self.head)
print(copyNode,self.head)
copyListObj.head = copyNode
copyListObj.head.next=None
print('########')
copyListObj.travelList()
print('########')
while curNode is not None:
curNode = curNode.next
if curNode is None:
break;
print('curNode:',curNode.data)
copyNode = copy.copy(curNode)
copyListObj.insertNodeObj(copyNode)
return copyListObj
def addLinLists(head1, head2):
curNode1 = head1
curNode2 = head2
resList = linList()
carryDigit = 0
sumDigit = 0
while curNode1 != None or curNode2 != None:
sumDigit = curNode1.data + curNode2.data + carryDigit
if sumDigit > 10:
sumDigit = sumDigit % 10
carryDigit = 1
else:
carryDigit = 0
resList.insertNode(sumDigit)
if carryDigit != 0:
resList.insertNode(1)
return
# h
# 1>>2>>3
# p<<c
# list1=linList()
##This is 32
# list1.insertNode(2)
# list1.insertNode(3)
# list1.travelList()
##This is 45
list2 = linList()
list2.insertNode(5)
list2.insertNode(4)
list2.travelList()
# time.sleep(5)
#list2.reverseList()
# list2.travelList()
list2Copy=list2.copyLinList()
list2Copy.travelList() |
5a0df33c1898a7c95d25754ed5dc3387854c7eac | murtekbey/python-temel | /4-donguler/for-demo.py | 2,801 | 3.9375 | 4 | sayilar = [1,3,5,7,9,12,19,21]
###################################################################################################################################
# 1. Sayılar listesindeki hangi sayılar 3'ün katıdır ?
for sayi in sayilar: # liste içerisindeki elemanları tek tek dolaşır.
if sayi%3==0:
print(sayi)
###################################################################################################################################
# 2. Sayılar listesinde sayıların toplamı kaçtır ?
toplam = 0 #
for sayi in sayilar: # liste içerisindeki elemanları tek tek dolaşır.
toplam += sayi # toplam = 0 'ı burda toplamın içerisine atıyoruz. bir sonraki dönüşünde toplamın aldığı yeni değerle birlikte bir sonraki sayıyı toplucak.
# 0+1=1, 1+3=4, 4+5=9, 9+7=16, 16+9=25, 25+12=37, 37+19=56, 56+21=77 <--- Sonucuna ulaşır.
print('Toplam: ',toplam)
###################################################################################################################################
# 3. Sayılar listesindeki tek sayıların karesini alınız.
# for sayi in sayilar: # liste içerisindeki elemanları tek tek dolaşır.
# if (sayi%2==1):
# print(sayi**2)
###################################################################################################################################
# # 4. Şehirlerden hangileri en fazla 5 karakterlidir ?
sehirler = ['Kocaeli','İstanbul','Ankara','İzmir','Rize']
for sehir in sehirler: # liste içerisindeki elemanları tek tek dolaşır.
if (len(sehir) <= 5):
print(sehir)
###################################################################################################################################
# 5. Ürünlerin fiyatları toplamı nedir?
urunler = [
{'name':'samsung S6', 'price':'3000'},
{'name':'samsung S7', 'price':'4000'},
{'name':'samsung S8', 'price':'5000'},
{'name':'samsung S9', 'price':'6000'},
{'name':'samsung S10', 'price':'7000'}
]
toplam = 0
for urun in urunler: # liste içerisindeki elemanları tek tek dolaşır.
fiyat = int(urun['price']) # price keyine karşılık gelen value bilgisini int'e çevirdik ki toplama işlemini yapabilelim.
toplam += fiyat
print('Ürünlerin Toplam Fiyatı: ',toplam) # print komutunu en dışarıya almazsak her for döngüsü ile dolaştığında toplama işlemini tek tek yazdırır.
###################################################################################################################################
# 6. Ürünlerden fiyatı en fazla 5000 olan ürünleri gösteriniz ?
for urun in urunler: # liste içerisindeki elemanları tek tek dolaşır.
if int(urun['price']) <= 5000:
print(urun['name']) # print komutu içerde olmalı ki if koşulunu bize sağlasın.
|
76b6e7d11907193dff7133c19174c00d633feef0 | gayathri-kannanv/Python-logics | /sum_prime.py | 242 | 3.984375 | 4 | max=int(input("ENTER THE MAXIMUM VALUE OF THE RANGE:"))
sum=0
for i in range (1,max):
if i>1:
for j in range (2,i):
if i%j==0:
break;
else:
sum=sum+i
print("THE SUM OF PRIME NUMBERS IN THE GIVEN RANGE IS: ",sum)
|
f060a3f48fa098831a9082dad0ba39a855e5b7a8 | Mohican-Bob/CIT-228 | /Chapter10/guest_book.py | 1,067 | 3.90625 | 4 | """
userName = input("What is you user name? (q to quit)")
with open("Chapter10/userName.txt", "a") as userFile:
while userName != "q":
userName += "\n"
userFile.write(userName)
input("What is you user name? (q to quit)")"""
import os
import random
filename = "Chapter10/guests.txt"
#deleting the file if it exists
if os.path.exists(filename):
os.remove(filename)
#creating a new file
rooms = []
with open(filename,"w") as guestFile:
guests = input("Please enter your name? (q to quit)")
while guests != 'q':
number=random.randint(1,30)
while number in rooms:
number=random.randint(1,30)
print(f"{guests} you will sleep in room# {number}")
rooms.append(number)
guests+=", room# " + str(number) + "\n"
guestFile.write(guests)
guests = input("Please enter your name? (q to quit)")
#reading from the new file
with open(filename) as guestFile:
print("----------------guest and room assigned-----------\n")
for line in guestFile:
print(line)
|
4299c9080958a439ffb5efe719295d8a8e477b8c | gear106/leetcode | /7. Reverse Integer.py | 575 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 15 20:27:31 2018
@author: GEAR
"""
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
x_reverse = 0
if x < 0:
x = int(str(abs(x))[::-1])
x_reverse = -x
else:
x = int(str(x)[::-1])
x_reverse = x
if x_reverse > 2**31 - 1 or x_reverse < -2**31:
return 0
else:
return x_reverse
s = Solution()
x = -120
print(s.reverse(x))
|
27bb7b5f8cfad804de0266ac6845501250c41b32 | swapnilnandedkar/Python-Assignment | /Assignment1/Assignment1_8.py | 410 | 4.28125 | 4 | # 8. Write a program which accept number from user and print that number of “*” on screen.
# Input : 5 Output : * * * * *
def DisplayStarPattern(Number):
for counter in range(Number):
print("*", end=" ")
def main():
print("Enter Number to print * pattern")
Number = int(input())
DisplayStarPattern(Number)
print()
if __name__ == "__main__":
main()
|
e70cad28df82f15c6815287ce245c18449a0cbdf | kavinyao/Pure | /lcs.py | 1,197 | 3.765625 | 4 | # Code from: http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_subsequence#Python
def LCS(X, Y):
m = len(X)
n = len(Y)
# An (m+1) times (n+1) matrix
C = [[0] * (n+1) for i in range(m+1)]
for i in range(1, m+1):
for j in range(1, n+1):
if X[i-1] == Y[j-1]:
C[i][j] = C[i-1][j-1] + 1
else:
C[i][j] = max(C[i][j-1], C[i-1][j])
return C
# from dragnet
def check_inclusion(x, y):
"""Given x, y (formatted as input to longest_common_subsequence)
return a vector v of True/False with length(x)
where v[i] == True if x[i] is in the longest common subsequence with y"""
if len(y) == 0:
return [False] * len(x)
c = LCS(x, y)
i = len(x)
j = len(y)
ret = []
while i > 0 or j > 0:
if i > 0 and j > 0 and x[i-1] == y[j-1]:
ret.append(True)
i -= 1
j -= 1
else:
if j > 0 and (i == 0 or c[i][j-1] >= c[i-1][j]):
j -= 1
elif i > 0 and (j == 0 or c[i][j-1] < c[i-1][j]):
ret.append(False)
i -= 1
ret.reverse()
return ret
|
0295ee51ca523c683e7e563109def2e3517e176a | darvat/ProgramozasAlapjai | /elagazasok-if-szerkezet/source.py | 434 | 3.5 | 4 | szepVagyok = True
if szepVagyok:
print("Tudom, hogy szep vagy")
print("de lehetsz meg szebb")
else:
print("csunya vagy")
print("de lehetsz meg szep")
felesegekSzama = 1
if felesegekSzama < 1:
print("meg nem ert el a vegzet")
elif felesegekSzama == 1:
print("ismered a dorgest")
elif felesegekSzama == 2:
print("ketto jobb mint egy?")
else:
print("poligamia rulez")
print("ez itt az if szerkezet utan van")
|
b148ce412d17e42ce3efbb822dc3b48bd99bfd22 | RodiMd/Python | /Insure.py | 322 | 4.0625 | 4 | #How Much Insurance
#should ensure your property for atleast 80 percent of the cost
#to replace it
costToReplace = input('Enter the amount it would cost to replace it ')
def minInsurance():
amountToInsure = 0.8 * float(costToReplace)
print ('amount to insure is %.2f' %amountToInsure)
minInsurance()
|
f63bb312de7cd3e8e9d1eee48023cee01a143acf | dchartor/hackerrank | /counting_valleys.py | 239 | 3.5 | 4 | def countingValleys(n, s):
level = 0
valleys = 0
for i in s:
if i == 'D':
level -= 1
if level == -1:
valleys += 1
if i == 'U':
level += 1
return valleys
|
944033cf667d3455ce265e1b494bc7d562b09d24 | parkchu/python-study | /clock/Untitled.py | 148 | 3.6875 | 4 | import turtle as t
def draw(a):
t.fd(100)
t.lt(a)
b = 120
for x in range(7):
draw(b)
if x == 2:
b = 90
t.circle(50)
|
eec8e994de795229924ee993216993b051d6d350 | SobuleacCatalina/Rezolvarea-problemelor-IF-WHILE-FOR | /problema_6_IF_WHILE_FOR.py | 617 | 3.9375 | 4 | """
Se dă numărul natural n. Să se compare sumele S1 și S2,unde:
a)S1=1**3+2**3+...+n**3 și S2=(1+2+...+n)**2;
b)S1=3(1**2+2**2+...+n**2) și S2=n**3+n**2+(1+2+...+n)
"""
n=int(input("Introdu numărul: "))
s1a=0
s1b=0
s2a=0
s2b=0
s2=0
s1=0
s2i=0
for i in range(1,n+1):
s1a+=i**3
for i in range(1,n+1):
s2+=i
s2a=s2**2
if s1a>s2a:
print("a)S1>S2")
elif s1a<s2a:
print("a)S1<S2")
else:
print("a)S1=S2")
for i in range(1,n+1):
s1+=i**2
s1b=s1*3
for i in range(1,n+1):
s2i+=i
s2b=s2i+n**3+n**2
if s1b>s2b:
print("b)S1>S2")
elif s1b<s2b:
print("b)S1<S2")
else:
print("b)S1=S2") |
e122441d78fd99ad6652ca25f1a2db5091edce19 | soumitra9/Binary-Search-4 | /intersection2arrays.py | 2,140 | 3.609375 | 4 | # Time Complexity : Add - O(mlogm + n logn)
# Space Complexity :O(1)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
'''
1. Sorting both arrays and then using 2 pointers
2. If value is same add it to reult and move both pointer
3. If value not same move away from low value
4. When either pointer overflows, stop!
'''
from collections import defaultdict
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
if len(nums1) < 1 or len(nums2)<1:
return
nums1.sort()
nums2.sort()
i, j = 0, 0
result = []
while i<len(nums1) and j < len(nums2):
if nums1[i] == nums2[j]:
result.append(nums1[i])
i += 1
j += 1
elif nums1[i] < nums2[j]:
i += 1
else:
j += 1
return result
# Hashmap solution
# Time Complexity : Add - O(m)
# Space Complexity :O(n)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
'''
1. put all values of any array(amaller or bigger) with thier frequencies in hashmap
2. Iterate thry the other array while checking the frequeency if it is > 0
3. If freq is > 0, add the value to result and decrease frequency
'''
from collections import defaultdict
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
if len(nums1) < 1 or len(nums2)<1:
return
if len(nums1) <= len(nums2):
smaller = nums1
bigger = nums2
else:
smaller = nums2
bigger = nums1
hash_ = defaultdict(lambda : 0)
for i in smaller:
hash_[i] += 1
result = []
for i in bigger:
if i in hash_ and hash_[i] > 0:
result.append(i)
hash_[i] -= 1
return result
|
2ef3a03d62f17fc3ab893256ef23151502b12894 | lkkliukeke/PythonExcel | /pymysqlcreat.py | 1,097 | 3.515625 | 4 | import MySQLdb
import mysql.connector
#打开数据库
db = MySQLdb.connect('localhost','root','admin123',"test")
crr = db.cursor()
sql = """insert into tests(name, age, sex) values ('张三3',17,'女')"""
# print(sql)
try:
crr.execute(sql)
db.commit()
except:
db.rollback()
db.close()
#创建一个游标对象
# cur = db.cursor()
#使用execute()方法执行sql,如果表存在则删除
# cur .execute("drop tests if exists name")
#添加
# sql = """insert into tests(name,age,sex) VALUES('张三2','12','男')"""
# print('success')
#添加表
# sql = """create table test2(
# name varchar (20),
# age varchar (20),
# sex varchar (10)
# )"""
#sql查询
# sql = """select * from test where name='张三'"""
# try:
# print('1')
# cur.execute(sql)
# db.commit()
# print('1')
# except:
# db.rollback()
#使用预处理语句创建表
# sql = """CREATE TABLE TEST1 (
# FIRST_NAME CHAR(20) NOT NULL,
# LAST_NAME CHAR(20),
# AGE INT,
# SEX CHAR(1),
# INCOME FLOAT )"""
# cur.execute(sql)
# print('2')
# db.close() |
d40673fbbfd7a6140df34d4a7300f25c27bf9efc | shortpoet/cs_washu_bootcamp | /week14homework/static/js/data.py | 333 | 3.59375 | 4 | import json
from pprint import pprint
with open('data.json') as f:
data = json.load(f)
cityList = []
for x in data:
for k, v in x.items():
if k == 'city':
#print(v)
cityList.append(v)
citySet = set(cityList)
uniqueCities = list(citySet)
citySort = uniqueCities.sort()
print(uniqueCities)
|
a9774f401cea5f731d4f7939b389d7e2c243fb3b | deepcpatel/data_structures_and_algorithms | /Graph/find_city_with_smalles_number_of_neighbours.py | 1,963 | 3.59375 | 4 | # Link: https://leetcode.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/
# Approach: Apply Floyd-Warshall algorithm to find distance between each node in the graph. Now calculate number of nodes within given threshold distance for each node and return the one with smallest
# number of neigbours within distance.
class Solution(object):
def floyd_warshall(self, distanceThreshold):
N = len(self.node_dist)
for k in range(N):
for i in range(N):
for j in range(N):
d_new, d_old = self.node_dist[i][k]+self.node_dist[k][j], self.node_dist[i][j]
if d_new < self.node_dist[i][j]:
self.node_dist[i][j] = d_new
# Incrementing number of neighbours within a distance threshold
if d_new <= distanceThreshold and d_old > distanceThreshold:
self.min_dist_nodes[i] += 1
def findTheCity(self, n, edges, distanceThreshold):
self.node_dist, self.min_dist_nodes = [[float('inf')]*n for i in range(n)], [0]*n # Stores distance between nodes
min_n, min_idx = float('inf'), -1
for i in range(n):
self.node_dist[i][i] = 0
# Filling node distance
for e in edges:
i, j, dist = e[0], e[1], e[2]
self.node_dist[i][j], self.node_dist[j][i] = dist, dist
if dist <= distanceThreshold:
self.min_dist_nodes[i] += 1
self.min_dist_nodes[j] += 1
self.floyd_warshall(distanceThreshold)
# Finding the node with minimum neighbours
for i in range(n):
if self.min_dist_nodes[i] <= min_n:
min_n = self.min_dist_nodes[i]
min_idx = i
return min_idx |
f0c7ea46d2777ae75badfde5c49b316a448a8468 | ThanushaK/session15_statistics1 | /Statistics1.py | 650 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 2 11:56:08 2019
@author: thanusha
"""
import numpy as np #importing numpy library
#import scipy.stats
#import matplotlib.pyplot as plt
# 1
x= [1550,1700,900,850,1000,950] #given list of numbers
std=np.std(x) #standard deviation from numpy library
print("Standard deviation is {:.2f}" .format(std)) #print the standard deviation result with two decimals after point
#2
x = [3,21,98,203,17,9] #given list of numbers
variance = np.var(x) #variance from numpy library
print("variance is {:.2f}" .format(variance))
|
24429329b4ade990e34388039bdcbb3bb520cfa8 | cz495969281/2019_- | /Project/day5/01-bs4创建和调试.py | 973 | 3.78125 | 4 | from bs4 import BeautifulSoup
html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1"><!-- Elsie --></a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
#通过BeautifulSoup创建对象
#相当于xpath的根元素的对象
#自动补全标签
#bs4底层解析使用lxml默认的解析器
#自己指定解析器
soup = BeautifulSoup(html,'lxml')
#可以直接执行标签名称提取
# print(soup.title.string)
#如果有2个相同的标签,默认只获取第一个
print(soup.p)
#打印标签内容
# print(soup.prettify()) |
8375286eb88e35db374511ece3bd8894f082ee49 | Vibhuti12354/first-project | /first code.py | 248 | 3.59375 | 4 |
#%%
file="demo.txt"
word="hello"
c=0
with open(file,'r')as f:
for line in f:
words=line.split()
for i in words:
if(i==word):
c=c+1
print("occurence of word",word)
print(c)
# %%
|
43590da819ba83cccc4ec9d64bb06cf59fb34abb | navnoorsingh13/GW2019PA2 | /venv/Session3.py | 636 | 4.21875 | 4 | # Controller : Logic by which you will solve problem
"""
1. Operators
2. Conditional Constructs | if/else
3. Loops / Iterations
"""
# Arithmetic Operators : +, -, *, /, %, //, **
dish1 = 100
dish2 = 200
bill = dish1 + dish2
print("Bill is:",bill)
# Assume taxes to be 5%
taxes = .05 * bill
print("Taxes :",taxes)
totalBill = bill + taxes
print("Total Bill:",totalBill)
num1 = 10
num2 = 3
# num3 = num1 ** num2
# num3 = num1 / num2
# num3 = num1 // num2
num3 = num1 % num2 # Remainder
print("num3 is:",num3)
number = 149
# data = number % 100
data = number//100
print(data)
# HW: Add digits of a number 1 + 4 + 9 = 14
|
66ee22f38fb881626d849cf5bbf740f1619c13b7 | angrajlatake/100-days-to-code | /day10-function.py | 1,216 | 4.28125 | 4 |
#change name from any case to title case(first letter in capital)
def format_name(fname,lname):
fname = fname.title()
lname = lname.title()
return f"{fname} {lname}"
fname = input("What is your first name?")
lname = input("What is your last name?")
print(format_name(fname,lname))
# USE THE LEAP YEAR CALENDAR FROM THE PREVIOUS EXERCISE AND CREATE PROGRAM WHERE IT GIVE YOU DAY OF THE MONTH IF THE YEAR IS PROVIDED
# copied the program from day3
#check leap year program
#if the number is divisible by 4 except for the number which is divisible by 100 unless it is also divisible by 400
def check_leap(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
else:
return True
else:
return False
def days_in_month(year,month):
month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if check_leap(year):
month_days[1] = 29
days = month_days[month-1]
return days
year = int(input("Enter a year: "))
month = int(input("Enter a month: "))
days = days_in_month(year, month)
print(f"There are {days} days in that month")
|
c1e04a7f9f402368a71e5550e505bdbdefbec9d9 | sassafras13/coding-interview | /problems/chapter_03/p01_three_in_one_soln.py | 2,967 | 4.3125 | 4 | # source: https://github.com/careercup/CtCI-6th-Edition-Python/blob/master/chapter_03/p01_three_in_one.py
# Their solution appears to be similar to mine
# use a list to store three stacks
# use a second list to keep track of the sizes of each stack
# the push and pop methods are standard, there are no surprises in how they work
# compared to a normal stack
# I actually don't get how this implementation addresses some of the hints given in the book?
# like what about the circular nature of the indexing?
# or the fact that we could cleverly allocate space to different size stacks?
class MultiStack:
def __init__(self, stack_size, number_of_stacks):
self.number_of_stacks = number_of_stacks
self.array = [0] * (stack_size * self.number_of_stacks)
self.sizes = [0] * self.number_of_stacks
self.stack_size = stack_size
def push(self, value, stack_num):
self._assert_valid_stack_num(stack_num) # clever to include a check on stack_num
if self.is_full(stack_num):
raise StackFullError(f"Push failed: stack #{stack_num} is full")
# check that stack is not full
self.sizes[stack_num] += 1 # increment the size of the stack that was pushed to
self.array[self.index_of_top(stack_num)] = value # add the value to the stack
def pop(self, stack_num):
self._assert_valid_stack_num(stack_num)
if self.is_empty(stack_num):
raise StackEmptyError(f"Cannot pop from empty stack #{stack_num}")
# these custom errors are classes that inherit from the Exception class
# or the ValueError class
value = self.array[self.index_of_top(stack_num)]
self.array[self.index_of_top(stack_num)] = 0
self.sizes[stack_num] -= 1
return value
def peek(self, stack_num):
self._assert_valid_stack_num(stack_num)
if self.is_empty(stack_num):
raise StackEmptyError(f"Cannot peek at empty stack #{stack_num}")
return self.array[self.index_of_top(stack_num)]
def is_empty(self, stack_num):
self._assert_valid_stack_num(stack_num)
return self.sizes[stack_num] == 0
def is_full(self, stack_num):
self._assert_valid_stack_num(stack_num)
return self.sizes[stack_num] == self.stack_size
def index_of_top(self, stack_num):
self._assert_valid_stack_num(stack_num)
offset = stack_num * self.stack_size
return offset + self.sizes[stack_num] - 1
def _assert_valid_stack_num(self, stack_num):
if stack_num >= self.number_of_stacks:
raise StackDoesNotExistError(f"Stack #{stack_num} does not exist")
class MultiStackError(Exception):
"""multistack operation error"""
class StackFullError(MultiStackError):
"""the stack is full"""
class StackEmptyError(MultiStackError):
"""the stack is empty"""
class StackDoesNotExistError(ValueError):
"""stack does not exist"""
|
f1c796d107b4d933b3b9272d4ad950feb37d269d | VerityG/tmskurs | /homework2/zad2math.py | 668 | 3.75 | 4 | import math
def teorCos():
cosa = math.cos(((a ** 2) + (c ** 2) - (b ** 2)) / (2 * a * c))
cosb = math.cos(((a ** 2) + (b ** 2) - (c ** 2)) / (2 * a * b))
cosc = math.cos(((b ** 2) + (c ** 2) - (a ** 2)) / (2 * c * b))
print(cosa, cosb, cosc)
print(math.degrees(cosa), math.degrees(cosb), math.degrees(cosc))
return a, b, c
a = int(input('Введите длинну стороны '))
b = int(input('Введите длинну стороны '))
c = int(input('Введите длинну стороны '))
if a < b + c and b < a + c and c < a + b:
print('Есть такой')
teorCos()
else:
print('Нет такого')
|
740717db1a8828569cd3127754440936d2ba9804 | antony10291029/lxfpyanswer | /32debug.py | 820 | 3.890625 | 4 | # -*- coding: utf-8 -*-
def foo(s):
n = int(s)
print('>>> n = %d' % n)
return 10 / n
def main():
foo('0')
#main()
#可以用print来打印调试信息,确认程序的错误信息
def foo(s):
n = int(s)
assert n != 0,'n is zero!'
return 10 / n
def main():
foo('0')
#main()
#assert是断言的意思是断言后面跟的内容如果满足,则什么都不做,否则抛出错误,显示后半段内容
#此处n=0的话,则断言不成立,那么执行n is zero
import logging
import pdb
logging.basicConfig(level = logging.DEBUG)
#pdb.set_trace()
s = '0'
n = int(s)
logging.info('n = %d' % n)
print(10 / n)
#logging输出错误的信息
#插入pdb.set_trace()插入断点
s = '0'
n = int(s)
print(10/n)
#pdb可以单步执行代码,按n单步执行代码,按p可以显示变量
|
1a34911569dd448030c0e75a5dae46a1a477ce63 | dm36/interview-practice | /hacker_rank/insert_node.py | 280 | 3.734375 | 4 | def insertNodeAtPosition(head, data, position):
count = 0
node = head
while count < position - 1:
node = node.next
count += 1
temp = node.next
current_node = SinglyLinkedListNode(data)
node.next = current_node
current_node.next = temp
|
2a3532f7a65a750971b6cb5ff0047e65e56ba8d8 | momchilantonov/SoftUni-Programming-Basics-With-Python-April-2020 | /While-Loop/While-Loop-Lab/06_max_number.py | 218 | 3.734375 | 4 | import sys
numbers = int(input())
count = 0
max_num = -sys.maxsize
while count != numbers:
new_number = int(input())
count += 1
if new_number > max_num:
max_num = new_number
print(f'{max_num}')
|
c76d1e0a558d0e2acf9558fd686b362caa941454 | Botxan/Ada-labs | /lab1/python/ordenar_dos_numeros_2/ordenar_dos_numeros_2.py | 265 | 4.0625 | 4 | num1 = int(input("Introduzca el primer número: "))
num2 = int(input("Introduzca el segundo número: "))
assert num1 > 0
assert num2 > 0
if (num1 > num2):
num1 = num1 + num2
num2 = num1 - num2
num1 = num1 - num2
print(f'{num1} <= {num2}') |
4dc0419892df9fca078ca1f03a4a349473e8a86c | Silvia-man/test- | /python习题/仅菜鸟上的/62.py | 380 | 3.796875 | 4 | # 62.题目:查找字符串。
sStr1 = 'abcdefg'
sStr2 = 'cde'
print (sStr1.find(sStr2))
'''
find()方法语法:
str.find(str, beg=0, end=len(string))
参数
str -- 指定检索的字符串
beg -- 开始索引,默认为0。
end -- 结束索引,默认为字符串的长度。
返回值
如果包含子字符串返回开始的索引值,否则返回-1。
'''
|
b0f21da13fed786cb7bfe3c6547131fb3eb0cfa9 | bunshue/vcs | /_4.python/__code/Python邁向領航者之路_超零基礎/ch9/ch9_20.py | 415 | 3.6875 | 4 | # ch9_20.py
# 建立內含字串的字典
sports = {'Curry':['籃球', '美式足球'],
'Durant':['棒球'],
'James':['美式足球', '棒球', '籃球']}
# 列印key名字 + 字串'喜歡的運動'
for name, favorite_sport in sports.items( ):
print("%s 喜歡的運動是: " % name)
# 列印value,這是串列
for sport in favorite_sport:
print(" ", sport)
|
f9f726b94bb1ffc2aafd125dafb9837dc84708f0 | jury16/Python_Course | /Homework #7.py | 2,862 | 3.609375 | 4 | #convert inch to cm
def inch_cm(a):
return f'{2.54 * a} cm'
#convert cm to inch
def cm_inch(a):
return f' {(0.39 * a):.2f} inch'
#convert miles to km
def miles_km(a):
return f' {(1.60934 * a):.2f}'
#convert km to miles
def km_miles(a):
return f' {(0.621371 * a):.2f}'
#convert pound to kg
def pound_kg(a):
return f' {(0.453592 * a):.2f}'
#convert kg to pound
def kg_pound(a):
return f' {(2.20462 * a):.2f}'
#convert ounce to grams
def ounce_gram(a):
return f' {(28.3495 * a):.2f}'
#convert gram to ounce
def gram_ounce(a):
return f' {(0.035274 * a):.2f}'
#convert gallon to litre
def gallon_litre(a):
return f' {(3.78541 * a):.2f}'
#convert litre to gallon
def litre_gallon(a):
return f' {(0.2641720524 * a):.2f}'
#convert pint to litre
def pint_litre(a):
return f' {(3.78541 * a):.2f}'
#convert litre to pint
def litre_pint(a):
return f' {(0.2641720524 * a):.2f}'
print('#####Converot#####')
print('1 - Convert inch to cm')
print('2 - Convert cm to inch')
print('3 - Convert miles to km')
print('4 - Convert km to miles')
print('5 - Convert pound to kg')
print('6 - Convert kg to pound')
print('7 - Convert ounce to grams')
print('8 - Convert grams to ounce')
print('9 - Convert gallon to litre')
print('10 - Convert litre to gallon')
print('11 - Convert pint to litre')
print('12 - Convert litre to pint')
print(' 0 - Exit')
number_convertor = int(input('Input number of converter: '))
while number_convertor:
number = int(input('Input number: '))
if number_convertor == 1:
print(f'{number} inch is {inch_cm(number)} cm\n')
elif number_convertor == 2:
print(f'{number} cm is {cm_inch(number)} inch\n')
elif number_convertor == 3:
print(f'{number} mile is {miles_km(number)}\n')
elif number_convertor == 4:
print(f'{number} km is {km_miles(number)} mile\n')
elif number_convertor == 5:
print(f'{number} pound is {pound_kg(number)} kg\n')
elif number_convertor == 6:
print(f'{number} kg is {kg_pound(number)} pound\n')
elif number_convertor == 7:
print(f'{number} ounce is {ounce_gram(number)} gram\n')
elif number_convertor == 8:
print(f'{number} gram is {gram_ounce(number)} ounce\n')
elif number_convertor == 9:
print(f'{number} gallon is {gallon_litre(number)} litre\n')
elif number_convertor == 10:
print(f'{number} litre is {litre_gallon(number)} gallon\n')
elif number_convertor == 11:
print(f'{number} pint is {pint_litre(number)} litre\n')
elif number_convertor == 12:
print(f'{number} litre is {litre_pint(number)} pint\n')
else:
print('Number convertor is not valid')
number_convertor = int(input('Input number of converter: '))
|
e3192d33bc7dc09ece087ae98a0eab40e5788178 | chenzhiyuan0713/Leetcode | /Easy/Q23.py | 914 | 3.625 | 4 | """
1732. 找到最高海拔
有一个自行车手打算进行一场公路骑行,这条路线总共由 n + 1 个不同海拔的点组成。自行车手从海拔为 0 的点 0 开始骑行。
给你一个长度为 n 的整数数组 gain ,其中 gain[i] 是点 i 和点 i + 1 的 净海拔高度差(0 <= i < n)。请你返回 最高点的海拔 。
示例 1:
输入:gain = [-5,1,5,0,-7]
输出:1
解释:海拔高度依次为 [0,-5,-4,1,1,-6] 。最高海拔为 1 。
示例 2:
输入:gain = [-4,-3,-2,-1,4,3,2]
输出:0
解释:海拔高度依次为 [0,-4,-7,-9,-10,-6,-3,-1] 。最高海拔为 0 。
"""
class Solution:
def largestAltitude(self, gain) -> int:
result = [0]
for index in range(len(gain)+1):
result.append(sum(gain[:index]))
print(result)
return max(result)
answer = Solution()
print(answer.largestAltitude([44]))
|
8bb1574974ba158bfd32d35748c08a3ae00c0e6c | mohitsaroha03/The-Py-Algorithms | /src/3.1Array/rearrange array alternately.py | 997 | 4.5 | 4 | # Link: https://www.geeksforgeeks.org/rearrange-array-maximum-minimum-form/
# Python program to rearrange an array in minimum
# maximum form
# Prints max at first position, min at second position
# second max at third position, second min at fourth
# position and so on.
def rearrange(arr, n):
# Auxiliary array to hold modified array
temp = n*[None]
# Indexes of smallest and largest elements
# from remaining array.
small,large =0,n-1
# To indicate whether we need to copy rmaining
# largest or remaining smallest at next position
flag = True
# Store result in temp[]
for i in range(n):
if flag is True:
temp[i] = arr[large]
large -= 1
else:
temp[i] = arr[small]
small += 1
flag = bool(1-flag)
# Copy temp[] to arr[]
for i in range(n):
arr[i] = temp[i]
return arr
# Driver program to test above function
arr = [1, 2, 3, 4, 5, 6]
n = len(arr)
print("Original Array")
print(arr)
print("Modified Array")
print(rearrange(arr, n)) |
a388a345a51db839c86cc3c36c6a54e10a4e7fd3 | crispto/algorithm | /test2.py | 812 | 3.609375 | 4 | class Node:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def width(root):
"""
1 1
1 2
/
2
1 3
/
2
# \
3
\ 4
"""
if not root:
return 0
lr = [0,0]
width_help(root, 0, lr)
return lr[1] - lr[0] +1
def width_help(root, pos, lr):
if not root:
return
if pos < lr[0]:
lr[0] = pos
if pos > lr[1]:
lr[1] = pos
if root.left:
width_help(root.left, pos-1, lr)
if root.right:
width_help(root.right, pos+1, lr)
if __name__ == "__main__":
a = Node(1)
print(width(a))
b = Node(2)
c = Node(3)
a.left = b
print(width(a))
b.right = c
d = Node(4)
c.right = d
print(width(a))
|
a3238401ea1118cb3022578c502d6bafba1277d4 | sobriquette/interview-practice-problems | /Pramp/countPaths.py | 1,013 | 3.578125 | 4 | class SolutionDP:
def num_paths_to_sq(self, i, j, memo):
if i < 0 or j < 0:
return 0
elif i < j:
return 0
elif i == 0 and j == 0:
return 1
elif memo[i][j] != -1:
return memo[i][j]
else:
memo[i][j] = self.num_paths_to_sq(i, j - 1, memo) + self.num_paths_to_sq(i - 1, j, memo)
print("i: {}, j: {}, val: {}".format(i, j, memo[i][j]))
return memo[i][j]
def num_of_paths_to_dest(self, n):
memo = [[-1 for _ in range(n)] for _ in range(n)]
return self.num_paths_to_sq(n - 1, n - 1, memo)
class SolutionIter:
def num_of_paths_to_dest(self, n):
if n == 1:
return 1
last_row = [1 for _ in range(n)]
curr_row = [0 for _ in range(n)]
for j in range(1, n):
for i in range(1, n):
if i == j:
curr_row[i] = last_row[i]
else:
curr_row[i] = curr_row[i - 1] + last_row[i]
print("cr: {} | i: {} | j: {}".format(curr_row, i, j))
last_row = curr_row
print("lr: ", last_row)
return curr_row[n - 1]
s = SolutionIter()
s.num_of_paths_to_dest(5) |
752aba60a28b09b5f28de295a39b54442d0d76e9 | FranklinA/CoursesAndSelfStudy | /PythonScript/PythonBasico/operadores.py | 187 | 3.71875 | 4 |
def sumar(numero1,numero2):
return numero1+numero2
valor=sumar(5,5)
print "El resultado de la FUNCION sumar es ",sumar(5,5)
print "El resultado de la VARIABLE valor es igual ",valor
|
df5eb1d452b7bfd4e748e7e1616c2aa9ee088bb4 | yuktha-05/Python-Coding | /Python_programs/leapyear.py | 149 | 4.1875 | 4 | year = int(input("Enter any year : "))
if((year%4==0 and year%100 != 0) or(year%400 == 0)):
print("Leap Year")
else:
print("Not a Leap Year")
|
330ece901042386a3f185b511d29c85024d86841 | yiyuhao/DataStructureAndAlgorithm | /algorithm/sort/heap_sort.py | 768 | 3.71875 | 4 | def sort(lst):
"""采用大顶堆排序"""
def siftdown(elems, e, begin, end):
p, c = begin, begin * 2 + 1
while c < end:
if c + 1 < end and elems[c + 1] > elems[c]:
c += 1
if e > elems[c]:
break
else:
elems[p] = elems[c]
p, c = c, c * 2 + 1
elems[p] = e
end = len(lst)
# 构建堆
for i in range(end // 2, -1, -1):
siftdown(lst, lst[i], i, end)
# 排序
for i in range((end - 1), 0, -1):
# 队首元素替换队尾
e = lst[i]
lst[i] = lst[0]
siftdown(lst, e, 0, i)
return lst
if __name__ == '__main__':
l = [4, 5, 3, 6, 7, 9, 11, 0, 2, 1, 8]
print(sort(l))
|
e2bcea129e1520daf1ec6ace72ca268eb9067ced | baichen7788/test | /CurveFitting.py | 586 | 3.671875 | 4 | #Curve fitting( m is number of data points, n is degree of curve fitting)
import numpy as np
def CurveFit(x,y,n):
m=len(x)
x,y=np.array(x),np.array(y)
A=np.zeros((n+1,n+1))
B=np.zeros(n+1)
for row in range(n+1):
for col in range(n+1):
if row==col==0:
A[row,col]=m
continue
A[row,col]=np.sum(x**(row+col))
B[row]=np.sum(x**row*y)
return np.linalg.solve(A,B) # output is coefficient of the curve fitting equation
x=np.arange(6)
y=[2,8,14,28,39,62]
CurveFit(x,y,2) |
e012b519aa48e6351c1bb038cf290fb9500a96fb | DrRhythm/PythonNetworking | /week_2/exercise2.py | 660 | 4.125 | 4 | #!/usr/bin/python
# Create a list of 5 IPs
ip_list = ["10.1.2.4", "172.16.15.9", "154.69.45.26", "10.5.7.1", "10.7.96.5"]
print(ip_list)
# use append to add an ip to the end of the list
ip_list.append("192.65.8.2")
print(ip_list)
# user extend to add two more ips to the end
new_ips = ["192.168.1.1", "192.168.1.2"]
ip_list.extend(new_ips)
print(ip_list)
# print the list, print the first ip and print the last ip
print(ip_list[0])
print(ip_list[-1])
# use pop to remove the first and last ip in the list
ip_list.pop(0)
ip_list.pop(-1)
# update the first ip in the list to 2.2.2.2, print out the new first ip
ip_list.insert(0, "2.2.2.2")
print(ip_list[0]) |
52f8de17f41a628aba737c48658088e51d938092 | Shantti-Y/Algorithm_Python | /chap03/prac02.py | 991 | 3.765625 | 4 | # Linear Search (Standardized way)
def search(a, n, key):
st_num = []
st_ele = []
for i in range(n):
st_num.append(str("{0}".format(i)))
st_ele.append(str("{0:02d}".format(a[i])))
st_num = " ".join(st_num)
st_ele = " ".join(st_ele)
print(" | {0}".format(st_num))
print("---+--{0}".format("----" * n))
for i in range(n):
print(" | {0}{1}{2}".format((" " * i), "*", (" " * (n - i))))
print(" {0}| {1}".format(i, st_ele))
if(a[i] == key):
return i
return -1
# Main Function
print("I'm gonna search a key you input in a linear method with a sentiel law")
print("Number of elements :")
nx = int(input())
ar = []
for i in range(nx):
print("x[{0}] :".format(i))
x = int(input())
ar.append(x)
print("The key :")
ky = int(input())
idx = search(ar, nx, ky)
if(idx == -1):
print("Failed searching {0}".format(ky))
else:
print("{0} is in x[{1}]".format(ky, idx))
|
6b1444c8ead0884dcc20da8d4f303b6f15ed6f3e | siddharthrajaraja/WordCloud | /file1.py | 929 | 3.5625 | 4 | import numpy as np
import re
import json
count_Words={}
def createDictionary(l):
for i in range(0,len(l)):
if l[i].lower() not in count_Words:
count_Words[l[i].lower()]=1
else:
count_Words[l[i].lower()]+=1
all_strings=[]
if __name__=="__main__":
with open('output.txt','r',encoding='utf-8') as f:
for x in f.readlines():
arr=x.split(',')
for i in range(0,len(arr)):
line_String=arr[i].split(' ')
for j in range(0,len(line_String)):
if re.match(r'^[a-zA-Z]{3,}$',line_String[j]):
all_strings.append(line_String[j])
createDictionary(all_strings)
#print(count_Words)
f=open('finally_dictionary.json','w')
f.write(json.dumps(count_Words))
print("Ended") |
dd45ea99e1e5520f5328e73f3a6d86c1de6b4dd8 | dalerxli/PSO_Simulation | /pso.py | 3,839 | 3.640625 | 4 | '''
Paper referred: Particle Swarm Optimization: A Tutorial
PSO : Particle Swarm Optimizer
For the objective function: |(0.07*i - 10)**3 - 8*i + 500|, which has a local minima and a global minima.
Requires optimization along a single dimension.
'''
'''
v(t+1) = w*v(t) + c1*r1*[p_best(t) - x(t)] + c2*r2*[g_best(t) - x(t)] : For each particle
x(t+1) = x(t) + v(t+1) : For each particle
0.8 < w < 1.2 => w = 1
0 < c1, c2 < 2 => c1 = c2 = 2
0 < r1, r2 < 1
velocity clamping: vmax = k * (xmax - xmin) / 2; 0.1 < k < 1.0 => k = 0.5
'''
import matplotlib.pyplot as plt, random
def function(values):
output = []
for i in values:
output.append(abs((0.07*i - 10)**3 - 8*i + 500))
return output
def near_minima(values, offset):
output = 0
for i in values:
#326.038 is the actual value at which objective function is 0(cheked using a grapher)
if abs(i-326.038) < offset:
output += 1
return output
#define initial parameters for the PSO
w = 0;c1 = c2 = 2; k = 0.5; xmax = 500; xmin = 0
vmax = k * (xmax - xmin)/2
max_iter = 500
no_particles = 100
values_x = [] #position of each point
velocity = [] #velocity of each point
p_best_x = [] #personal_best of each point x_val
g_best_x = random.randrange(xmin, xmax) #global best x_value
#assign random positions and velocities to the particles
for i in range(no_particles):
values_x.append(random.uniform(xmin, xmax + 1))
velocity.append(random.randrange(-vmax, vmax))
p_best_x = values_x[::]
#initial plot settings
plt.axis([0, 500, 0, 1200])
plt.ion()
plt.plot(values_x, function(values_x), 'rx')
plt.title('PSO Simulation')
plt.ylabel('objective function = |(7/100x - 10)^3 - 8x +500|')
plt.text(450, 1300, "Total particles : 100")
plt.text(450, 1250, "Near minima(5%): 100")
plt.text(2, 1300, "Number of iterations: 0")
plt.text(2, 1250, "Global minima : " + str(g_best_x))
plt.xlabel('x')
plt.show()
plt.plot(range(500), function(range(500)), 'g', linewidth = 0.5)
for j in range(max_iter):
#clear previous plot and plot curve
plt.gcf().clear()
plt.axis([0, 500, 0, 1200])
plt.title('PSO Simulation')
plt.ylabel('objective function = |(7/100x - 10)^3 - 8x +500|')
plt.xlabel('x')
plt.text(450, 1300, "Total particles : 100")
plt.text(450, 1250, "Near minima(5%): " + str(near_minima(values_x,25)))
plt.text(-80, 1300, "Number of iterations: " + str(j))
plt.text(-80, 1250, "Global minima : " + str(g_best_x))
plt.plot(range(500), function(range(500)), 'g', linewidth = 0.5)
#calculate fitness of the particles
fitness = function(values_x)
p_best_y = function(p_best_x)
#update personal best for each particle
for i in range(no_particles):
if fitness[i] < p_best_y[i]:
p_best_x[i] = values_x[i]
#update global best for each particle
min_value, min_index = min( (v, i) for i, v in enumerate(p_best_y) )
if [min_value] < function([g_best_x]):
g_best_x = p_best_x[min_index]
#for each iteration,
for i in range(no_particles):
r1, r2 = random.random(), random.random()
#calculate new velocity and set it in the [min, max] range
velocity[i] = w*velocity[i] + c1*r1*(p_best_x[i] - values_x[i]) + c2*r2*(g_best_x - values_x[i])
if velocity[i] > vmax: velocity[i] = vmax
if velocity[i] < -vmax: velocity[i] = -vmax
#calculate new positions and set it in the [min, max] range
values_x[i] = values_x[i] + velocity[i]
if values_x[i] > xmax: values_x[i] = xmax
if values_x[i] < xmin: values_x[i] = xmin
#plot new particle positions
for i in range(no_particles):
plt.plot(values_x, function(values_x), 'rx')
plt.pause(0.2)
print (g_best_x)
#prevent plot from closing
while True:
plt.pause(0.05)
|
0afa56935e964d423088829055647ed2c371bd1a | thaolinhnp/Python_Fundamentals | /PYBai_07_project/ex03_List_for.py | 136 | 3.5625 | 4 | lst_SoNguyen=[3,5,7,9]
tong = 0
for item in lst_SoNguyen:
# print(item)
tong += item
tongDaySo = sum(lst_SoNguyen)
print('end') |
b9f3192e0217490551ed6ac1c97d6a9bdf19593b | yz5308/Python_Leetcode | /Algorithm-Easy/190_Reverse_Bits.py | 1,259 | 3.78125 | 4 | class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
b = bin(n)[:1:-1]
return int(b + '0'*(32-len(b)), 2)
def reverseBits1(self, n):
result = 0
for i in range(32):
result <<= 1
result |= n & 1
n >>= 1
return result
def reverseBits2(self, n):
string = bin(n)
if '-' in string:
string = string[:3] + string[3:].zfill(32)[::-1]
else:
string = string[:2] + string[2:].zfill(32)[::-1]
return int(string, 2)
if __name__ == '__main__':
print(Solution().reverseBits(1))
"""
Time Complexity = O(log(n))
Space Complexity = O(1)
Reverse bits of a given 32 bits unsigned integer.
Example:
Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
Input: 43261596
Output: 964176192
Explanation: 43261596 represented in binary as 00000010100101000001111010011100,
return 964176192 represented in binary as 00111001011110000010100101000000.
Not only fully understand with the result.
"""
|
aa9280b1fa00ac3d109ed13e78f5fb5339887f79 | mehzabeen000/loop_python | /sum(12-421).py | 145 | 3.921875 | 4 | counter=12
sum=0
while counter<=421:
sum=sum+counter
counter+=1
print(sum)
#we have to print the sum of numbers from 12 to 421.
|
01d27f13efdc04b50efd5e17d3e1e5c05def92b3 | Thetvdh/FastTyping | /main.py | 2,919 | 3.53125 | 4 | import sys
import time
import string
import random
import pandas as pd
import matplotlib.pyplot as plt
def trainer(sentences_dict):
data = {}
for key, value in sentences_dict.items():
start_time = time.time()
input1 = input(value['sentence'] + " ")
runtime = round((time.time() - start_time), 2)
if value['sentence'] == input1 and runtime < value['time']:
data[key] = [True, runtime]
else:
data[key] = [False, runtime]
return data
def generate_sentences(num_sentences):
data = {}
for i in range(1, num_sentences + 1):
data["Level" + str(i)] = {"sentence": generate_strings(i), "time": i+0.5}
return data
def generate_strings(length):
letters = string.ascii_letters
digits = string.digits
output = ""
for i in range(1, length + 1):
output += random.choice(letters + digits)
return output
def format_value(formatter):
new = {}
for key, value in formatter.items():
if value[0]:
new[key] = ["Correct", value[1]]
else:
new[key] = ["Incorrect", value[1]]
return new
def line_graph(frame):
choice = input("\nWould you like to have a line graph of your results? Y/N ")[0].lower()
font1 = {'family': 'serif', 'color': 'blue', 'size': 20}
if choice == 'y':
x_points = []
y_points = []
for key, value in frame.items():
x_points.append(key)
y_points.append(value[1])
plt.plot(x_points, y_points, marker='o')
plt.xlabel("Level", fontdict=font1)
plt.ylabel("Time Taken", fontdict=font1)
plt.title("Time Taken per Level graph", fontdict=font1)
plt.show()
print("Goodbye!")
sys.exit()
def graph_bar(frame):
choice = input("\nWould you like to have a bar chart of your results? Y/N ")[0].lower()
if choice == 'y':
x = ["correct", "incorrect"]
num_correct = 0
num_incorrect = 0
for key, value in frame.items():
if value[0]:
num_correct += 1
else:
num_incorrect += 1
y = [num_correct, num_incorrect]
plt.bar(x, y)
plt.show()
line_graph(frame)
sys.exit()
else:
line_graph(frame)
if __name__ == '__main__':
while True:
try:
number_sentences = int(input("How many strings would you like to test yourself against?"))
sentences = generate_sentences(number_sentences)
results = trainer(sentences)
formatted = format_value(results)
dataframe = pd.DataFrame(formatted, index=["Result", "TimeTaken"])
pd.set_option("display.max_rows", None, "display.max_columns", None)
print(dataframe)
graph_bar(results)
except ValueError:
print("Please enter a number instead")
|
20d6c0ec72415f62df2bfcce0ef4d8a02aa8beaa | NewMike89/Python_Stuff | /Ch.1 & 2/bday_err.py | 148 | 4.15625 | 4 | # Michael Schorr
# 2/19/19
# general program to convert an INTEGER to work with STRINGS.
age = 28
msg1 = "Happy " + str(age) + "th Birthday!"
print(msg1)
|
e64c9ecd3937f4e211717fb33d581d723fa668dc | vasilypht/mathematical-pendulum | /pendulum.py | 1,608 | 3.546875 | 4 | import pygame as pg
import const
import math
class Pendulum(pg.Surface):
def __init__(self, size=(200, 200), length=200) -> None:
"""
Initialization
:param size: The size of the area on which the sphere will be drawn.
:param length: Length of "thread".
"""
pg.Surface.__init__(self, size=size)
self.length = length
self.g = 1200
self.dt = 1/60
self.a = 0
self.v = 0
self.phi = 2*math.pi / 3
self.x1 = size[0] // 2
self.y1 = size[1] // 3
self.__calculate()
self.__draw()
self.coff = self.g/self.length
self.speed = 0.000005
self.coff = 1.0
def update(self) -> None:
"""
Angle recalculation.
"""
self.fill(const.WHITE)
if self.phi != 0:
self.a = -(self.g/self.length) * math.sin(self.phi)
self.v += self.a * self.dt
self.phi += self.v * self.dt
self.__calculate()
self.__draw()
self.phi *= self.coff
self.coff -= self.speed
def __calculate(self):
self.x2 = self.x1 + self.length * math.cos(self.phi + math.pi / 2)
self.y2 = self.y1 + self.length * math.sin(self.phi + math.pi / 2)
def __draw(self) -> None:
"""
Drawing a pendulum.
"""
self.line = pg.draw.line(
self,
const.SLATEBLUE,
(self.x1, self.y1),
(self.x2, self.y2)
)
self.circle = pg.draw.circle(self, const.GREEN, (self.x2, self.y2), 9)
|
142e82bbe801570c5f1ce5e0ea0fd794aa04c59f | meisnehb/99-CapstoneProject-201920 | /src/shared_gui.py | 31,815 | 3.640625 | 4 | """
Capstone Project. Code to run on a LAPTOP (NOT the robot).
Constructs and returns Frame objects for the basics:
-- teleoperation
-- arm movement
-- stopping the robot program
This code is SHARED by all team members. It contains both:
-- High-level, general-purpose methods for a Snatch3r EV3 robot.
-- Lower-level code to interact with the EV3 robot library.
Author: Your professors (for the framework and lower-level code)
and Hannah Meisner and Alyssa Taylor.
Winter term, 2018-2019.
"""
import tkinter
from tkinter import ttk
from PIL import ImageTk
from PIL import Image
import time
# import shared_gui_delegate_on_robot
dismiss = False
def get_teleoperation_frame(window, mqtt_sender):
"""
Constructs and returns a frame on the given window, where the frame
has Entry and Button objects that control the EV3 robot's motion
by passing messages using the given MQTT Sender.
:type window: ttk.Frame | ttk.Toplevel
:type mqtt_sender: com.MqttClient
"""
# Construct the frame to return:
frame = ttk.Frame(window, padding=10, borderwidth=5, relief="ridge")
frame.grid()
# Construct the widgets on the frame:
frame_label = ttk.Label(frame, text="Teleoperation")
left_speed_label = ttk.Label(frame, text="Left wheel speed (0 to 100)")
right_speed_label = ttk.Label(frame, text="Right wheel speed (0 to 100)")
left_speed_entry = ttk.Entry(frame, width=8)
left_speed_entry.insert(0, "100")
right_speed_entry = ttk.Entry(frame, width=8, justify=tkinter.RIGHT)
right_speed_entry.insert(0, "100")
forward_button = ttk.Button(frame, text="Forward")
backward_button = ttk.Button(frame, text="Backward")
left_button = ttk.Button(frame, text="Left")
right_button = ttk.Button(frame, text="Right")
stop_button = ttk.Button(frame, text="Stop")
# Grid the widgets:
frame_label.grid(row=0, column=1)
left_speed_label.grid(row=1, column=0)
right_speed_label.grid(row=1, column=2)
left_speed_entry.grid(row=2, column=0)
right_speed_entry.grid(row=2, column=2)
forward_button.grid(row=3, column=1)
left_button.grid(row=4, column=0)
stop_button.grid(row=4, column=1)
right_button.grid(row=4, column=2)
backward_button.grid(row=5, column=1)
# Set the button callbacks:
forward_button["command"] = lambda: handle_forward(
left_speed_entry, right_speed_entry, mqtt_sender)
backward_button["command"] = lambda: handle_backward(
left_speed_entry, right_speed_entry, mqtt_sender)
left_button["command"] = lambda: handle_left(
left_speed_entry, right_speed_entry, mqtt_sender)
right_button["command"] = lambda: handle_right(
left_speed_entry, right_speed_entry, mqtt_sender)
stop_button["command"] = lambda: handle_stop(mqtt_sender)
return frame
def get_arm_frame(window, mqtt_sender):
"""
Constructs and returns a frame on the given window, where the frame
has Entry and Button objects that control the EV3 robot's Arm
by passing messages using the given MQTT Sender.
:type window: ttk.Frame | ttk.Toplevel
:type mqtt_sender: com.MqttClient
"""
# Construct the frame to return:
frame = ttk.Frame(window, padding=10, borderwidth=5, relief="ridge")
frame.grid()
# Construct the widgets on the frame:
frame_label = ttk.Label(frame, text="Arm and Claw")
position_label = ttk.Label(frame, text="Desired arm position:")
position_entry = ttk.Entry(frame, width=8)
raise_arm_button = ttk.Button(frame, text="Raise arm")
lower_arm_button = ttk.Button(frame, text="Lower arm")
calibrate_arm_button = ttk.Button(frame, text="Calibrate arm")
move_arm_button = ttk.Button(frame,
text="Move arm to position (0 to 5112)")
blank_label = ttk.Label(frame, text="")
# Grid the widgets:
frame_label.grid(row=0, column=1)
position_label.grid(row=1, column=0)
position_entry.grid(row=1, column=1)
move_arm_button.grid(row=1, column=2)
blank_label.grid(row=2, column=1)
raise_arm_button.grid(row=3, column=0)
lower_arm_button.grid(row=3, column=1)
calibrate_arm_button.grid(row=3, column=2)
# Set the Button callbacks:
raise_arm_button["command"] = lambda: handle_raise_arm(mqtt_sender)
lower_arm_button["command"] = lambda: handle_lower_arm(mqtt_sender)
calibrate_arm_button["command"] = lambda: handle_calibrate_arm(mqtt_sender)
move_arm_button["command"] = lambda: handle_move_arm_to_position(
position_entry, mqtt_sender)
return frame
def get_control_frame(window, mqtt_sender):
"""
Constructs and returns a frame on the given window, where the frame has
Button objects to exit this program and/or the robot's program (via MQTT).
:type window: ttk.Frame | ttk.Toplevel
:type mqtt_sender: com.MqttClient
"""
# Construct the frame to return:
frame = ttk.Frame(window, padding=10, borderwidth=5, relief="ridge")
frame.grid()
# Construct the widgets on the frame:
frame_label = ttk.Label(frame, text="Control")
quit_robot_button = ttk.Button(frame, text="Stop the robot's program")
exit_button = ttk.Button(frame, text="Stop this and the robot's program")
# Grid the widgets:
frame_label.grid(row=0, column=1)
quit_robot_button.grid(row=1, column=0)
exit_button.grid(row=1, column=2)
# Set the Button callbacks:
quit_robot_button["command"] = lambda: handle_quit(mqtt_sender)
exit_button["command"] = lambda: handle_exit(mqtt_sender)
return frame
def get_drive_system_frame(window, mqtt_sender):
# Construct the frame to return:
frame = ttk.Frame(window, padding=10, borderwidth=5, relief="ridge")
frame.grid()
# Construct the widgets on the frame:
frame_label = ttk.Label(frame, text="Drive System")
time_button = ttk.Button(frame, text="Go Straight (Time)")
inches_button = ttk.Button(frame, text="Go Straight (Inches)")
encoder_button = ttk.Button(frame, text='Go Straight (Encoder)')
speed_label = ttk.Label(frame, text="Speed")
inches_label = ttk.Label(frame, text="Inches")
time_label = ttk.Label(frame, text="Time")
inches_entry = ttk.Entry(frame, width=8)
speed_entry = ttk.Entry(frame, width=8)
seconds_entry = ttk.Entry(frame, width=8)
blank_label = ttk.Label(frame, text="")
# Grid the widgets:
frame_label.grid(row=0, column=1)
speed_label.grid(row=1, column=1)
inches_label.grid(row=1, column=2)
time_label.grid(row=1, column=0)
inches_entry.grid(row=2, column=2)
speed_entry.grid(row=2, column=1)
seconds_entry.grid(row=2, column=0)
blank_label.grid(row=3, column=1)
time_button.grid(row=4, column=0)
inches_button.grid(row=4, column=2)
encoder_button.grid(row=4, column=1)
# Set the Button callbacks:
time_button["command"] = lambda: handle_timeStraight(seconds_entry, speed_entry, mqtt_sender)
inches_button["command"] = lambda: handle_inchesStraight(inches_entry, speed_entry, mqtt_sender)
encoder_button["command"] = lambda: handle_encoderStraight(inches_entry, speed_entry, mqtt_sender)
return frame
def get_beeps_tones(window, mqtt_sender):
# Construct the frame to return:
frame = ttk.Frame(window, padding=10, borderwidth=5, relief="ridge")
frame.grid()
# Construct the widgets on the frame:
frame_label = ttk.Label(frame, text="Beep and Tone")
num_of_beeps_label = ttk.Label(frame, text="Number of Beeps:")
num_of_beeps_entry = ttk.Entry(frame, width=8)
num_of_beeps_button = ttk.Button(frame, text="Number of Beeps")
freq_label = ttk.Label(frame, text='Frequency')
freq_entry = ttk.Entry(frame, width=8)
duration_label = ttk.Label(frame, text='Duration')
duration_entry = ttk.Entry(frame, width=8)
play_button = ttk.Button(frame, text="Play Tone")
phrase_label = ttk.Label(frame, text='Desired Phrase:')
phrase_entry = ttk.Entry(frame, width=8)
phrase_button = ttk.Button(frame, text="Speak")
blank_label1 = ttk.Label(frame, text="")
blank_label2 = ttk.Label(frame, text="")
blank_label3 = ttk.Label(frame, text="")
# Grid the widgets:
frame_label.grid(row=0, column=1)
num_of_beeps_label.grid(row=1, column=0)
freq_label.grid(row=5, column=0)
duration_label.grid(row=5, column=2)
phrase_label.grid(row=1, column=2)
num_of_beeps_entry.grid(row=2, column=0)
freq_entry.grid(row=6, column=0)
duration_entry.grid(row=6, column=2)
phrase_entry.grid(row=2, column=2)
blank_label1.grid(row=4, column=0)
blank_label2.grid(row=8, column=0)
blank_label3.grid(row=2, column=1)
num_of_beeps_button.grid(row=3, column=0)
play_button.grid(row=6, column=1)
phrase_button.grid(row=3, column=2)
# Set the Button callbacks:
num_of_beeps_button["command"] = lambda: handle_beep(num_of_beeps_entry, mqtt_sender)
play_button["command"] = lambda: handle_tone(freq_entry, duration_entry, mqtt_sender)
phrase_button["command"] = lambda: handle_speech(phrase_entry, mqtt_sender)
return frame
def get_sensor_frame(window, mqtt_sender):
# Construct the frame to return:
frame = ttk.Frame(window, padding=10, borderwidth=5, relief="ridge")
frame.grid()
# Construct the widgets on the frame:
frame_label = ttk.Label(frame, text="Sensors and Camera")
color_label = ttk.Label(frame, text="Color Number/Name:")
color_entry = ttk.Entry(frame, width=8)
color_button = ttk.Button(frame, text="Forward")
camera_label = ttk.Label(frame, text="Camera:")
cw_button = ttk.Button(frame, text="CW")
ccw_button = ttk.Button(frame, text='CCW')
prox_label = ttk.Label(frame, text="Distance (Inches):")
prox_entry = ttk.Entry(frame, width=8)
prox_button = ttk.Button(frame, text="Forward")
# Grid the widgets:
frame_label.grid(row=0, column=1)
color_label.grid(row=1, column=0)
camera_label.grid(row=1, column=1)
prox_label.grid(row=1, column=2)
color_entry.grid(row=2, column=0)
prox_entry.grid(row=2, column=2)
color_button.grid(row=4, column=0)
cw_button.grid(row=3, column=1)
ccw_button.grid(row=4, column=1)
prox_button.grid(row=4, column=2)
# Doing stuff with buttons and boxes
color_button['command'] = lambda: handle_color_stop(mqtt_sender, color_entry)
cw_button['command'] = lambda: handle_cw_camera(mqtt_sender)
ccw_button['command'] = lambda: handle_ccw_camera(mqtt_sender)
prox_button['command'] = lambda: handle_proxy_forward(mqtt_sender, prox_entry)
return frame
def get_proximity_tone_frame(window, mqtt_sender):
# Construct the frame to return:
frame = ttk.Frame(window, padding=10, borderwidth=5, relief="ridge")
frame.grid()
# Construct the widgets on the frame:
frame_label = ttk.Label(frame, text="Increasing Frequency")
freq_entry = ttk.Entry(frame, width=8)
rate_entry = ttk.Entry(frame, width=8)
forward_button = ttk.Button(frame, text="Forward")
freq_label = ttk.Label(frame, text="Starting Frequency")
rate_label = ttk.Label(frame, text="Rate of Change")
# Grid the widgets:
frame_label.grid(row=0, column=1)
freq_label.grid(row=1, column=0)
freq_entry.grid(row=2, column=0)
rate_label.grid(row=1, column=2)
rate_entry.grid(row=2, column=2)
forward_button.grid(row=3, column=1)
# Doing stuff with buttons and boxes
forward_button['command'] = lambda: m2_handle_proximity_tone(mqtt_sender, freq_entry, rate_entry)
return frame
def get_proximity_beep_frame(window, mqtt_sender):
frame = ttk.Frame(window, padding=10, borderwidth=5, relief="ridge")
frame.grid()
frame_label = ttk.Label(frame, text="Beep Proximity")
pause_entry = ttk.Entry(frame, width=8)
multiplier_entry = ttk.Entry(frame, width=8)
forward_button = ttk.Button(frame, text='Forward')
frame_label.grid(row=0, column=1)
pause_entry.grid(row=1, column=0)
multiplier_entry.grid(row=1, column=1)
forward_button.grid(row=1, column=2)
forward_button['command'] = lambda: handle_proximity_beep(mqtt_sender, pause_entry, multiplier_entry)
return frame
###############################################################################
###############################################################################
# The following specifies, for each Button,
# what should happen when the Button is pressed.
###############################################################################
###############################################################################
###############################################################################
# Handlers for Buttons in the Teleoperation frame.
###############################################################################
def handle_forward(left_entry_box, right_entry_box, mqtt_sender):
print('Forward')
l = left_entry_box.get()
r = right_entry_box.get()
mqtt_sender.send_message("forward", [l, r])
"""
Tells the robot to move using the speeds in the given entry boxes,
with the speeds used as given.
:type left_entry_box: ttk.Entry
:type right_entry_box: ttk.Entry
:type mqtt_sender: com.MqttClient
"""
def handle_backward(left_entry_box, right_entry_box, mqtt_sender):
print('Backward')
l = int(left_entry_box.get()) * -1
r = int(right_entry_box.get()) * -1
mqtt_sender.send_message("forward", [l, r])
"""
Tells the robot to move using the speeds in the given entry boxes,
but using the negatives of the speeds in the entry boxes.
:type left_entry_box: ttk.Entry
:type right_entry_box: ttk.Entry
:type mqtt_sender: com.MqttClient
"""
def handle_left(left_entry_box, right_entry_box, mqtt_sender):
print("Left")
l = int(left_entry_box.get()) * 0.5
r = int(right_entry_box.get())
mqtt_sender.send_message("forward", [l, r])
"""
Tells the robot to move using the speeds in the given entry boxes,
but using the negative of the speed in the left entry box.
:type left_entry_box: ttk.Entry
:type right_entry_box: ttk.Entry
:type mqtt_sender: com.MqttClient
"""
def handle_right(left_entry_box, right_entry_box, mqtt_sender):
print("Right")
l = int(left_entry_box.get())
r = int(right_entry_box.get()) * 0.5
mqtt_sender.send_message("forward", [l, r])
"""
Tells the robot to move using the speeds in the given entry boxes,
but using the negative of the speed in the right entry box.
:type left_entry_box: ttk.Entry
:type right_entry_box: ttk.Entry
:type mqtt_sender: com.MqttClient
"""
def handle_stop(mqtt_sender):
print("Stop")
mqtt_sender.send_message('stop')
"""
Tells the robot to stop.
:type mqtt_sender: com.MqttClient
"""
###############################################################################
# Handlers for Buttons in the DriveSystem frame.
###############################################################################
def handle_timeStraight(seconds_entry, speed_entry, mqtt_sender):
print()
sec = int(seconds_entry.get())
s = int(speed_entry.get())
mqtt_sender.send_message('straight_time', [sec, s])
def handle_inchesStraight(inches_entry, speed_entry, mqtt_sender):
print()
i = int(inches_entry.get())
s = int(speed_entry.get())
mqtt_sender.send_message('straight_inches', [i, s])
def handle_encoderStraight(inches_entry, speed_entry, mqtt_sender):
print()
i = int(inches_entry.get())
s = int(speed_entry.get())
mqtt_sender.send_message('straight_encoder', [i, s])
###############################################################################
# Handlers for Buttons in the BeepsAndTones frame.
###############################################################################
def handle_beep(num_of_beeps_entry, mqtt_sender):
print()
n = int(num_of_beeps_entry.get())
mqtt_sender.send_message('beep_number_of_times', [n])
def handle_tone(freq_entry, duration_entry, mqtt_sender):
print()
f = int(freq_entry.get())
d = int(duration_entry.get())
mqtt_sender.send_message('tone', [f, d])
def handle_speech(phrase_entry, mqtt_sender):
print()
p = phrase_entry.get()
mqtt_sender.send_message('speech', [p])
###############################################################################
# Handlers for Buttons in the ArmAndClaw frame.
###############################################################################
def handle_raise_arm(mqtt_sender):
print("Raise")
mqtt_sender.send_message('raise_arm')
"""
Tells the robot to raise its Arm until its touch sensor is pressed.
:type mqtt_sender: com.MqttClient
"""
def handle_lower_arm(mqtt_sender):
print('Lower')
mqtt_sender.send_message('lower_arm')
"""
Tells the robot to lower its Arm until it is all the way down.
:type mqtt_sender: com.MqttClient
"""
def handle_calibrate_arm(mqtt_sender):
print('Calibrate that Boi')
mqtt_sender.send_message('calibrate_arm')
"""
Tells the robot to calibrate its Arm, that is, first to raise its Arm
until its touch sensor is pressed, then to lower its Arm until it is
all the way down, and then to mark taht position as position 0.
:type mqtt_sender: com.MqttClient
"""
def handle_move_arm_to_position(arm_position_entry, mqtt_sender):
print('Move Arm to Position')
pos = int(arm_position_entry.get())
mqtt_sender.send_message('arm_pos', [pos])
"""
Tells the robot to move its Arm to the position in the given Entry box.
The robot must have previously calibrated its Arm.
:type arm_position_entry ttk.Entry
:type mqtt_sender: com.MqttClient
"""
###############################################################################
# Handlers for sensors
###############################################################################
def handle_color_stop(mqtt_sender, color_entry):
c = color_entry.get()
print('Forward until not color:', c)
mqtt_sender.send_message('color_stop', [c])
def handle_cw_camera(mqtt_sender):
print("Spin clockwise to object")
mqtt_sender.send_message('cw_camera')
def handle_ccw_camera(mqtt_sender):
print("Spin counter-clockwise to object")
mqtt_sender.send_message('ccw_camera')
def handle_proxy_forward(mqtt_sender, proxy_entry):
d = float(proxy_entry.get())
print("Go forward until:", d, 'inches away')
mqtt_sender.send_message('proxy_forward', [d])
###############################################################################
# Handlers for sensors
###############################################################################
def handle_proximity_beep(mqtt_sender, pause_entry, multiplier_entry):
p = float(pause_entry.get())
m = float(multiplier_entry.get())
print("Baseline pause is", p, "with multiplier", m)
mqtt_sender.send_message('proximity_beep', [p, m])
def m2_handle_proximity_tone(mqtt_sender, freq_entry, rate_entry):
f = float(freq_entry.get())
r = float(rate_entry.get())
print('Start frequency is', f, 'rate of change is', r)
mqtt_sender.send_message('m2_proxy_tone', [f, r])
###############################################################################
# Handlers for Buttons in the Control frame.
###############################################################################
def handle_quit(mqtt_sender):
print('Quit')
mqtt_sender.send_message('quit')
"""
Tell the robot's program to stop its loop (and hence quit).
:type mqtt_sender: com.MqttClient
"""
def handle_exit(mqtt_sender):
print('Exit')
handle_quit(mqtt_sender)
exit()
"""
Tell the robot's program to stop its loop (and hence quit).
Then exit this program.
:type mqtt_sender: com.MqttClient
"""
###############################################################################
# M1 Sprint 3 Codes (Individual GUI, Tests, Functions)
###############################################################################
def get_m1_frame(window, mqtt_sender):
frame = tkinter.Frame(window, borderwidth=5, relief="ridge", background='blue')
frame.grid()
# Buttons
harch_button = ttk.Button(frame, text="MARCH!")
harch_button['command'] = lambda: handle_march(mqtt_sender, main_entry)
face_button = ttk.Button(frame, text="FACE!")
face_button['command'] = lambda: handle_face(mqtt_sender, main_entry)
halt_button = ttk.Button(frame, text="HALT!")
halt_button['command'] = lambda: handle_halt(mqtt_sender)
cover_button = ttk.Button(frame, text='COVER!')
cover_button['command'] = lambda: handle_cover(mqtt_sender)
hua_button = ttk.Button(frame, text="HUA!")
hua_button['command'] = lambda: handle_hua(mqtt_sender)
meme_button = ttk.Button(frame, text="MEME")
meme_button['command'] = lambda: handle_meme(mqtt_sender)
dismissed_button = ttk.Button(frame, text='Dismiss')
dismissed_button['command'] = lambda: handle_dismiss(mqtt_sender)
report_button = ttk.Button(frame, text='Report')
report_button['command'] = lambda: handle_report(mqtt_sender)
branch_button = ttk.Button(frame, text='Best military branch?')
branch_button['command'] = lambda: handle_branch(mqtt_sender)
# Labels
entry_label = ttk.Label(frame, text='Enter command:')
# Entry Boxes
main_entry = ttk.Entry(frame)
# Grid Everything
entry_label.grid(row=0, column=0)
main_entry.grid(row=1, column=0)
harch_button.grid(row=1, column=1)
face_button.grid(row=1, column=2)
cover_button.grid(row=3, column=3)
hua_button.grid(row=4, column=1)
halt_button.grid(row=1, column=3)
dismissed_button.grid(row=5, column=0)
report_button.grid(row=5, column=1)
meme_button.grid(row=4, column=2)
branch_button.grid(row=5, column=3)
return frame
def get_m1_descriptions(window, mqtt_sender):
frame = ttk.Frame(window, padding=10, borderwidth=5, relief="ridge")
frame.grid()
march_label = ttk.Label(frame, text='Commands for MARCH!')
march_label.grid(row=0, column=0)
forward_label = ttk.Label(frame, text='forward: Cadet robo goes forward until a safety or halt is called')
forward_label.grid(row=1, column=0)
column_label = ttk.Label(frame, text='column right/left: Turns cadet robo 90 degrees while marching forward.')
column_label.grid(row=2, column=0)
column_half_label = ttk.Label(frame, text='column half right/left: Turns cadet robo 45 degrees while marching forward.')
column_half_label.grid(row=3, column=0)
paces_forward_label = ttk.Label(frame, text='(number) paces forward: Cadet robo goes those number of paces forward')
paces_forward_label.grid(row=4, column=0)
to_the_rear_label = ttk.Label(frame, text='to the rear: While marching forward, cadet robo spins 180 degrees to march'
'opposite direction.')
to_the_rear_label.grid(row=5, column=0)
blank_label = ttk.Label(frame, text='')
blank_label.grid(row=6, column=0)
face_label = ttk.Label(frame, text='Commands for FACE!')
face_label.grid(row=7, column=0)
right_left_label = ttk.Label(frame, text='right/left: Turns cadet robo 90 to right or left while stationary')
right_left_label.grid(row=8, column=0)
about_label = ttk.Label(frame, text='about: Turns cadet robo 180 degrees stationary')
about_label.grid(row=9, column=0)
return frame
def handle_halt(mqtt_sender):
print("HALT!")
print('FLIGHT HALT WHAT?')
mqtt_sender.send_message('halt')
def handle_march(mqtt_sender, main_entry):
entry = main_entry.get()
if entry[2] == 'p': # Paces Forward
print(entry[0], "PACES FORWARD")
mqtt_sender.send_message('paces_forward', entry[0])
else:
if len(entry) >= 11:
if entry[0] == 't':
print("TO THE REAR")
mqtt_sender.send_message('to_the_rear')
elif entry[7] == 'l':
print("COLUMN LEFT")
s = 'left'
mqtt_sender.send_message('column', [s])
elif entry[7] == 'r':
s = 'right'
print("COLUMN RIGHT")
mqtt_sender.send_message('column', [s])
elif entry[7] == 'h':
if entry[12] == 'r':
s = 'right'
print("COLUMN HALF RIGHT")
mqtt_sender.send_message('column_half', [s])
elif entry[12] == 'l':
s = 'left'
print("COLUMN HALF LEFT")
mqtt_sender.send_message('column_half', [s])
elif entry[0] == 'f': # Forward
print("FORWARD")
mqtt_sender.send_message('forward_march')
print(" HARCH!")
def handle_face(mqtt_sender, main_entry):
entry = main_entry.get()
if entry[0] == 'r':
print("RIGHT")
s = 'right'
mqtt_sender.send_message('face', [s])
elif entry[0] == 'l':
print("LEFT")
s = 'left'
mqtt_sender.send_message('face', [s])
elif entry[0] == 'a':
print("ABOUT")
s = 'about'
mqtt_sender.send_message('face', [s])
print(" HACE!")
def handle_hua(mqtt_sender):
print("HUA!")
mqtt_sender.send_message('hua')
def handle_cover(mqtt_sender):
print("COVER!")
mqtt_sender.send_message('cover')
def handle_report(mqtt_sender):
print('REPORT!')
mqtt_sender.send_message('report')
def handle_meme(mqtt_sender):
global dismiss
if dismiss == True:
mqtt_sender.send_message('song')
else:
print("You cannot meme until you have been dismissed.")
def handle_dismiss(mqtt_sender):
print("Cadet robo has been relieved of his duties for the day.")
global dismiss
dismiss = True
def handle_branch(mqtt_sender):
print("AIR POWER")
mqtt_sender.send_message('find_superior_branch')
###############################################################################
# M2 Sprint 3 Codes (Individual GUI, Tests, Functions)
###############################################################################
def get_m2_marching_frame(window, mqtt_sender):
# Construct the frame to return:
frame = ttk.Frame(window, padding=10, borderwidth=5, relief="ridge")
frame.grid()
# Construct the widgets on the frame:
frame_label = ttk.Label(frame, text="Marching")
forward_march_button = ttk.Button(frame, text="Forward March")
column_left_button = ttk.Button(frame, text="Column Left")
column_right_button = ttk.Button(frame, text="Column Right")
halt_button = ttk.Button(frame, text="Halt")
double_time_button = ttk.Button(frame, text='Double Time')
# Grid the widgets
frame_label.grid(row=0, column=1)
forward_march_button.grid(row=3, column=1)
column_left_button.grid(row=4, column=0)
halt_button.grid(row=5, column=1)
column_right_button.grid(row=4, column=2)
double_time_button.grid(row=4, column=1)
# Set the button callbacks:
forward_march_button["command"] = lambda: handle_m2_forward_march(mqtt_sender)
halt_button["command"] = lambda: handle_m2_halt(mqtt_sender)
column_right_button["command"] = lambda: handle_m2_column_right(mqtt_sender)
column_left_button["command"] = lambda: handle_m2_column_left(mqtt_sender)
double_time_button["command"] = lambda: handle_m2_double_time(mqtt_sender)
return frame
def get_m2_salute_frame(window, mqtt_sender):
frame = ttk.Frame(window, padding=10, borderwidth=5, relief="ridge")
frame.grid()
# Construct the widgets on the frame:
frame_label = ttk.Label(frame, text="Salute")
present_arms_button = ttk.Button(frame, text="Present Arms")
order_arms_button = ttk.Button(frame, text="Order Arms")
# Grid the widgets
frame_label.grid(row=0, column=1)
present_arms_button.grid(row=3, column=0)
order_arms_button.grid(row=3, column=3)
# Button Callbacks
present_arms_button["command"] = lambda: handle_m2_present_arms(mqtt_sender)
order_arms_button["command"] = lambda: handle_m2_order_arms(mqtt_sender)
return frame
def get_m2_af_morale_frame(window, mqtt_sender):
# Construct the frame to return:
frame = ttk.Frame(window, padding=10, borderwidth=5, relief="ridge")
frame.grid()
# Construct the widgets on the frame:
frame_label = ttk.Label(frame, text="Air Force Morale")
af_song_button = ttk.Button(frame, text="AF Song")
airmans_creed_button = ttk.Button(frame, text="Airman's Creed")
blank_label = ttk.Label(frame, text='')
# Grid the widgets
frame_label.grid(row=0, column=1)
af_song_button.grid(row=2, column=0)
airmans_creed_button.grid(row=2, column=2)
blank_label.grid(row=1, column=1)
# Set the button callbacks:
af_song_button["command"] = lambda: handle_m2_af_song(mqtt_sender)
airmans_creed_button["command"] = lambda: handle_m2_airmans_creed(mqtt_sender)
return frame
def get_m2_sensor_frame(window, mqtt_sender):
# Construct the frame to return:
frame = ttk.Frame(window, padding=10, borderwidth=5, relief="ridge")
frame.grid()
# Construct the widgets on the frame:
frame_label = ttk.Label(frame, text="Sensors")
color_button = ttk.Button(frame, text="Find Color")
find_button = ttk.Button(frame, text="Find Object")
inches_label = ttk.Label(frame, text="How Far is the Object?")
color_label = ttk.Label(frame, text="What Color Do You Want?")
inch_entry = ttk.Entry(frame, width=8)
c_entry = ttk.Entry(frame, width=8)
# Grid the widgets
frame_label.grid(row=0, column=1)
color_button.grid(row=5, column=0)
find_button.grid(row=5, column=2)
color_label.grid(row=2, column=0)
inch_entry.grid(row=4, column=2)
inches_label.grid(row=2, column=2)
c_entry.grid(row=4, column=0)
# Set the button callbacks:
color_button["command"] = lambda: handle_m2_color_sense(mqtt_sender, c_entry)
find_button["command"] = lambda: handle_m2_find_object(mqtt_sender, inch_entry)
return frame
def handle_m2_forward_march(mqtt_sender):
print('Forward Harch!')
mqtt_sender.send_message('m2_forward_march')
def handle_m2_halt(mqtt_sender):
print('Halt!')
mqtt_sender.send_message('m2_halt')
def handle_m2_double_time(mqtt_sender):
print('Double Time')
mqtt_sender.send_message('m2_double_time')
def handle_m2_column_right(mqtt_sender):
print('Column Right')
mqtt_sender.send_message('m2_column_right')
def handle_m2_column_left(mqtt_sender):
print('Column Left')
mqtt_sender.send_message('m2_column_left')
def handle_m2_present_arms(mqtt_sender):
print('Present Arms')
mqtt_sender.send_message('m2_present_arms')
def handle_m2_order_arms(mqtt_sender):
print('Order Arms')
mqtt_sender.send_message('m2_order_arms')
def handle_m2_af_song(mqtt_sender):
print('Wild Blue Yonder!')
mqtt_sender.send_message('m2_af_song')
def handle_m2_airmans_creed(mqtt_sender):
print('Airmans Creed')
mqtt_sender.send_message('m2_airmans_creed')
def handle_m2_color_sense(mqtt_sender, c_entry):
print('Finding Colors')
c = c_entry.get()
mqtt_sender.send_message('m2_color_sense', [c])
def handle_m2_find_object(mqtt_sender, inch_entry):
print('Finding Object')
i = int(inch_entry.get())
mqtt_sender.send_message('m2_find_object', [i]) |
ccc340a673369c61e7dfb2e399244fc966cca561 | YangXinNewlife/LeetCode | /easy/shuffle_string_1528.py | 442 | 3.546875 | 4 | # -*- coding:utf-8 -*-
__author__ = 'yangxin_ryan'
"""
Solutions:
题意是给字符串重新排序,
排序的顺序就是给定的indices,
直接数组转字符串即可
"""
class ShuffleString(object):
def restoreString(self, s: str, indices: List[int]) -> str:
length = len(indices)
result = [-1] * length
for i in range(length):
result[indices[i]] = s[i]
return "".join(result)
|
45c4c2e27fb5a8c43a792d8eb31d2ce9724f1b1d | gabrielwai/Exercicios-em-Python | /ordenando jogos de loteria pelos valores sorteados.py | 1,156 | 3.5625 | 4 | import random
import operator
jogos = dict()
lista = list()
lista1 = list()
for c in range(0, 4):
jogos['nome'] = 'jogador' + str((c + 1))
for j in range(0, 6):
while True:
n = random.randint(1, 60)
print(f'{lista1} ; {n}')
if n not in lista1:
lista1.append(n)
break
jogos['valor'] = lista1.copy()
lista1.clear()
lista.append(jogos.copy())
print(jogos)
jogos.clear()
print(jogos)
print(lista)
print(lista1)
print(len(lista))
for c in range(len(lista)):
print(f'{lista[c]["nome"]} => {lista[c]["valor"]}')
lista[c]['valor'].sort()
print()
for c in range(len(lista)):
print(f'{lista[c]["nome"]} => {lista[c]["valor"]}')
lista[c]['valor'] = lista[c]['valor'][0]
print(lista,end='\n...\n')
#sorted(lista, key=operator.itemgetter(lista["valores"]))
#print(sorted(lista, key=operator.itemgetter()))
lista1.clear()
for c in range(len(lista)):
lista1.append(lista[c]['valor'])
print(lista1)
lista1.sort()
print(lista1)
print(lista['nome'].index(lista1[0]))
for c in range(len(lista)):
print(F'{lista.index(lista1[0])} = {lista1[0]}')
|
b772799f884f494f263325c8f6572987761bce90 | jennyfer250113/practica-2 | /ejercicio3.py | 136 | 3.640625 | 4 | a = int(input(u"ingrese nùmero de filas"))
b = int(input(u"ingrese nùmero de columnas"))
if matriz:
matriz = a * b
print(matriz) |
75235576c941a4d0e4d3aed5657b2cf40fbef5d8 | SR0-ALPHA1/hackerrank-tasks | /path_bw_2_nodes_bin_tree.py | 1,009 | 4 | 4 | #!/usr/bin/python
# given 2 nodes of a binary tree, find number of nodes
# on the path between the two nodes
###
### DID NOT FINISH
### NEED MORE TIME TO COMPLETE
###
class Node:
def __init__(self, data):
self.data = data
def search(self, data, cnt=0):
if(self.data != data):
cnt+=1
cnt += self.left.search(data, cnt)
if -1 == this_cnt: cnt += self.right.search(data, cnt)
if -1 == this_cnt: return 0 # node doesn't exist
else:
return cnt
in_node1 = Node(4)
in_node2 = Node(3)
def find_number_of_nodes(in_node1, in_node2):
cnt = 0
if in_node1.data > in_node2.data:
cur_node = in_node1
dest_node = in_node2
elif in_node1.data < in_node2.data:
cur_node = in_node1
dest_node = in_node2
else:
# in_node1 == in_node2
return 0
# find common parent
while cur_node > dest_node:
cur_node = cur_node.parent
cnt+=1
|
fd818bb127ac71d926addb524e1115a4048caa6a | jakehoare/leetcode | /python_1001_to_2000/1026_Maximum_Difference_Between_Node_and_Ancestor.py | 1,222 | 3.859375 | 4 | _author_ = 'jake'
_project_ = 'leetcode'
# https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/
# Given the root of a binary tree, find the maximum value V for which there exists different
# nodes A and B where V = |A.val - B.val| and A is an ancestor of B.
# A node A is an ancestor of B if either: any child of A is equal to B, or any child of A is an ancestor of B.
# Recursive helper function tracks the max and min values seen along the current path from the root.
# The max and min values are updated at each node, returning the max difference after any leaf.
# Recurse left and right with the updated max and min and return the biggest difference from either subtree.
# Time - O(n)
# Space - O(n)
class Solution(object):
def maxAncestorDiff(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def helper(node, min_val, max_val):
if not node:
return max_val - min_val
min_val = min(node.val, min_val)
max_val = max(node.val, max_val)
return max(helper(node.left, min_val, max_val), helper(node.right, min_val, max_val))
return helper(root, float("inf"), float("-inf"))
|
db74516576a42cb00f2f6f10acee4472b69f1f85 | ka10ryu1/activation_func | /func.py | 848 | 3.59375 | 4 | #!/usr/bin/env python3
# -*-coding: utf-8 -*-
#
help = '便利機能'
#
import os
def argsPrint(p, bar=30):
"""
argparseの parse_args() で生成されたオブジェクトを入力すると、
integersとaccumulateを自動で取得して表示する
[in] p: parse_args()で生成されたオブジェクト
[in] bar: 区切りのハイフンの数
"""
print('-' * bar)
args = [(i, getattr(p, i)) for i in dir(p) if not '_' in i[0]]
for i, j in args:
if isinstance(j, list):
print('{0}[{1}]:'.format(i, len(j)))
[print('\t{}'.format(k)) for k in j]
else:
print('{0}:\t{1}'.format(i, j))
print('-' * bar)
def getFilePath(folder, name, ext):
if not os.path.isdir(folder):
os.makedirs(folder)
return os.path.join(folder, name + ext)
|
82f9f4797d32390bade47e3784ae680f5819bc2a | mattfemia/datacamp | /intermediatepython_ds/dictionaries.py | 553 | 3.828125 | 4 |
# List strategy to connect two data sets (Order matters)
pop = [30.55, 2.77, 39.21]
countries = ["afghanistan", "albania", "algeria"]
ind_alb = countries.index("albania")
print(ind_alb)
print(pop[ind_alb])
# Dictionary strategy (Order doesn't matter)
world = {"afghanistan": 30.55, "albania": 2.77, "algeria":39.21}
print(world["albania"])
print(world.keys()) # prints out all of the keys
world["sealand"]= 0.000027 # Appending dict
print(world)
print("sealand" in world) # Check to see if key is in dict
del(world["sealand"])
print(world)
|
1f8b9086ca824debb48d7d0811f1db3185ea1e27 | yeraygit/repositorio | /1_tutorias/4_listas.py | 1,418 | 4.5625 | 5 | '''
* Es una estructura de datos que nos permite almacenar gran catidad de valores.
* Es Equivalente a los arrays en otros lenguajes.
* Se pueden expandir dinamicamente añadiendo nuevos elementos (poderoso)
'''
# indices 0 1 2 3 4
elementos = [1, 2.5, 'Aprendiendo python', [5,6] ,True]
'''
print(elementos[:])
print(elementos[-2])
print(elementos[0:3]) # print(elementos[:3]) es lo mismo
print(elementos[2:4])
print(elementos[2:])
elementos2 = [1,True]
elementos3 = elementos + elementos2
print(elementos3[:])
print(elementos2*2)
print(len(elementos))
'''
for elemento in elementos:
print(elemento)
dic = {'key':'elemento'}
elementos.append(dic)
print("__________-------------------___________")
for elemento in elementos:
print(elemento)
print("___________-------------------___________")
elementos.extend([False,10.5])
for elemento in elementos:
print(elemento)
print("___________-------------------___________")
elementos.remove(1)
for elemento in elementos:
print(elemento)
print("___________-------------------___________")
elementos.insert(2,4)
for elemento in elementos:
print(elemento)
print("___________-------------------___________")
indice = elementos.index("Aprendiendo python")
print(indice)
print("___________-------------------___________")
count_elements = elementos.count("otro elemento")
print(count_elements)
|
a29ec2f3fadd4b47dd83c7b14a79c54f1ad46310 | lucasp0927/python_numerical_project | /src/homeworks/30/ps12.py | 2,141 | 3.546875 | 4 | #-*-coding:utf-8-*-
#Problem 11
#Name:Yu-Yi Kuo, Cheung Hei Ya
#Collaborators:
#Time:3:00
import numpy as np
def gaussElimin(a,b):
"""Solves [a]{x} = {b} by Gauss elimination.
USAGE:
x = gaussElimin(a,b)
INPUT:
a -numpy array (n*n)
b -numpy array (n*1)
OUTPUT:
x -numpy array (n*1)
"""
n=b.size
a=np.float64(a.copy())
b=np.float64(b.copy())
for k in range(0,n-1):
for i in range(k+1,n):
c=a[i,k]/a[k,k]
for j in range(k+1,n):
a[i,j]=a[i,j]-c*a[k,j]
b[i,0]=b[i,0]-c*b[k,0]
x=np.zeros((n,1))
x[n-1,0]=b[n-1,0]/a[n-1,n-1]
for i in range(n-2,-1,-1):
sum=b[i,0]
for j in range(i,n):
sum=sum-a[i,j]*x[j,0]
x[i,0]=sum/a[i,i]
return x
def LUdecomp(a):
""" LU decomposition: [L][U] = [a].
USAGE:
a = LUdecomp(a)
INPUT
a -numpy array (n*n)
OUTPUT
a -numpy array (n*n)
The returned matrix [a]=[L\U] contains [U] in the upper triangle
and the nondiagonal terms of [L] in the lower triangle.
"""
n=int(np.sqrt(a.size))
a=np.float64(a.copy())
for k in range(0,n-1):
for i in range(k+1,n):
c=a[i,k]/a[k,k]
a[i,k]=c
for j in range(k+1,n):
a[i,j]=a[i,j]-c*a[k,j]
return a
def LUsolve(a,b):
"""Solves [L][U]{x} = b, where [a] = [L\U] is the matrix
returned from LUdecomp.
USAGE:
x = LUsolve(a,b)
INPUT:
a -numpy array (n*n)
b -numpy array (n*1)
OUTPUT
x -numpy array (n*1)
"""
a=np.float64(a.copy())
b=np.float64(b.copy())
LU=LUdecomp(a)
n=b.size
y=np.zeros((n,1))
x=np.zeros((n,1))
y[0,0]=b[0,0]
for i in range(1,n):
sum = b[i,0]
for j in range(0,i):
sum=sum-LU[i,j]*y[j,0]
y[i,0]=sum
x[n-1,0]=y[n-1,0]/LU[n-1,n-1]
for i in range(n-2,-1,-1):
sum=y[i,0]
for j in range(i,n):
sum=sum-LU[i,j]*x[j,0]
x[i,0]=sum/LU[i,i]
return x
|
53d7ec40465ac4970b97b0c8a7635c639d04f365 | cryjun215/c9-python-getting-started | /python-for-beginners/04 - String variables/format_strings.py | 366 | 4.375 | 4 | # 사용자에게 이름과 성을 입력 받습니다.
first_name = input('What is your first name? ')
last_name = input('What is your last name? ')
# capitalize 함수는 다음과 같은 문자열을 리턴합니다.
# 첫 글자는 대문자이고 나머지 단어는 소문자
print ('Hello ' + first_name.capitalize() + ' ' \
+ last_name.capitalize())
|
64c37106f6846fc1ac1cf6f919b8bf2a5d0426bb | mpant84/pynet_ons | /madhur_exercise4.py | 188 | 3.5625 | 4 | #!/usr/bin/env python
ip_addr = raw_input("Please enter an IP addr? ")
octets = ip_addr.split(".")
print ("{:<12} {:<12} {:<12} {:<12}".format(octets[0],octets[1],octets[2],octets[3]))
|
1d6a63e6c5f3fc1089ccaededec8dcc9bf742195 | kumalee/python-101 | /part-2/shapes/parallelogram_5.py | 1,491 | 3.734375 | 4 | #! /usr/bin/python
# encoding: utf-8
import math
class Shape(object):
def __init__(self, width, height):
self.length = width, height
def setLength(self, width, height):
self.length = width, height
def getLength(self):
return self.length
def getName(self): pass
def getDeg(self):
return 0
def getArea(self):
return self.length[0] * self.length[1] * math.sin(math.radians(self.getDeg()))
@classmethod
def isSame(cls, shape1, shape2):
return shape1.getLength() == shape2.getLength() and \
shape1.getDeg() == shape2.getDeg() and \
shape1.getName() == shape2.getName()
class Parallelogram(Shape):
def __init__(self, width, height, deg):
Shape.__init__(self, width, height)
self.deg = deg
def setDeg(self, deg):
self.deg = deg
def getDeg(self):
return self.deg
def getName(self):
return 'Parallelogram'
class Rectangle(Shape):
def getDeg(self):
return 90
def getName(self):
return 'Rectangle'
class Sqaure(Shape):
def __init__(self, width):
self.length = width, width
def setLength(self, width):
self.length = width
def getDeg(self):
return 90
def getName(self):
return 'Sqaure'
po = Parallelogram(10, 20, 15)
ro = Rectangle(50, 50)
so = Sqaure(50)
so2 = Sqaure(50)
print Shape.isSame(so,ro)
print Shape.isSame(so,po)
print Shape.isSame(so,so2)
|
c3d7bd5263646afda5efadf099dd7108f2e7705c | nazhimkalam/Data-Science-Course | /Seaborn/lecture_02.py | 1,834 | 3.59375 | 4 | # CATEGORICAL PLOT
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
tips = sns.load_dataset('tips')
print(tips.head())
# sns.barplot(x='sex', y='total_bill', data=tips) # by default the estimate is set to the aggregate function of calculating the mean
# sns.barplot(x='sex', y='tip', data=tips, estimator=np.std) # we set the estimator function into standard deviation
#
# sns.countplot(x='sex', data=tips)# for countplot the y axis is by default set to count which represents the number of elements which is set for the x-axis
#
# sns.boxplot(x='day', y='total_bill', data=tips)
# sns.boxplot(x='day', y='total_bill', data=tips, hue='smoker') # we can use hue and add another category to show some distribution
#
# sns.violinplot(x='day', y='total_bill', data=tips)
# sns.violinplot(x='day', y='total_bill', data=tips, hue='smoker', split=True)# in violinplot also we can use hue but there is something special we can combine half of both the graphs given when hue is used by split to make it easier to see and read
# sns.stripplot(x='day', y='total_bill', data=tips)
# sns.stripplot(x='day', y='total_bill', data=tips, hue='sex', split=True)
# sns.swarmplot(x='day', y='total_bill', data=tips)# swarmplot is where the striplot gets the shape of a violinplot
# we can merge a striplot and violinplot to analyse data
# sns.violinplot(x='day', y='total_bill', data=tips)
# sns.swarmplot(x='day', y='total_bill', data=tips, color='black')# swarmplot is where the striplot gets the shape of a violinplot
# factor plot a General plot method where you can use it to build any plot
# sns.factorplot(x='day', y='total_bill', data=tips, kind='violin')
# sns.factorplot(x='day', y='total_bill', data=tips, kind='bar')
# sns.factorplot(x='day', y='total_bill', data=tips, kind='strip')
plt.show() |
0b09963ffdc533117857cc8b0ba8c74d12ab45bf | bala4rtraining/python_programming | /python-programming-workshop/set/2.pythonsetadd.py | 224 | 3.859375 | 4 |
# An empty set.
items = set()
# Add three strings.
items.add("cat")
items.add("dog")
items.add("tiger")
items.add("tiger")
items.add("cow")
#animal = input("give an domestic animal name")
#items.add(animal)
print(items)
|
a49c5a30c9964f9628ce430272c8c47dd667868a | shtakai/cd-python | /pylot/semirestful/app/controllers/Products.py | 2,106 | 3.84375 | 4 | """
Sample Controller File
A Controller should be in charge of responding to a request.
Load models to interact with the database and load views to render them to the client.
Create a controller using this template
"""
from system.core.controller import *
from time import strftime
import datetime
import string
import random
class Products(Controller):
def __init__(self, action):
super(Products, self).__init__(action)
"""
This is an example of loading a model.
Every controller has access to the load_model method.
self.load_model('WelcomeModel')
"""
self.load_model('Product')
""" This is an example of a controller method that will load a view for the client """
def index(self):
result = self.models['Product'].get_products()
if not result['status']:
flash("failed getting products")
return self.load_view('index.html', products=result['products'])
def new(self):
return self.load_view('new.html')
def create(self):
result = self.models['Product'].create_product(request.form)
if not result['status']:
for message in result['messages']:
flash(message)
else:
flash('Created Product')
return redirect('/')
def show(self, id):
result = self.models['Product'].get_product(id)
return self.load_view('show.html', product=result['product'])
def edit(self, id):
result = self.models['Product'].get_product(id)
return self.load_view('edit.html', product=result['product'])
def update(self, id):
result = self.models['Product'].update_product(id, request.form)
if not result['status']:
for message in result['messages']:
flash(message)
else:
flash('Updated Product')
return redirect('/')
def destroy(self):
result = self.models['Product'].destroy_product(request.form)
flash('Removed Product Successfully')
return redirect('/')
|
54cc16249d3ef4ff1058ebb4bdd6f6c095ab5e69 | pycoder682/easyhash | /sha224encrypt.py | 256 | 3.515625 | 4 | import hashlib
import time
word = input('Enter what you want hashed in sha224 here: ')
enc = word.encode('utf-8')
hash1 = hashlib.sha3_224(enc.strip()).hexdigest()
print('The sha224 hashed result is: ' + str(hash1))
time.sleep(10)
quit() |
2fc7ed6895ac53ddce3e8cb7d364b87b3b9bb9b5 | JonathanGamaS/hackerrank-questions | /python/capitalize.py | 828 | 4.1875 | 4 | """
You are asked to ensure that the first and last names of people begin with a capital letter in their passports. For example, alison heck should be capitalised correctly as Alison Heck.
Ex: alison heck -> Alison Heck
Given a full name, your task is to capitalize the name appropriately.
"""
import os
def solve(s):
b = ""
count = 0
for i in range(0,len(s)):
if i == 0:
x = s[i].upper()
b += x
elif s[i] == ' ':
b += s[i]
count = 1
elif count == 1:
x = s[i].upper()
b += x
count = 0
else:
b += s[i]
return b
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
result = solve(s)
print(result)
fptr.write(result + '\n')
fptr.close() |
c27b4c97fc4865745cd358dbec8a8b7129850314 | sweetherb100/python | /interviewBit/Strings/04_pretty_json.py | 3,811 | 3.5625 | 4 | # print("AAAA\t sgjdkgdlj \nd asdjgkgl")
'''
Pretty print a json object using proper indentation.
Every inner brace should increase one indentation to the following lines.
Every close brace should decrease one indentation to the same line and the following lines.
The indents can be increased with an additional ‘\t’
Example 1:
Input : {A:"B",C:{D:"E",F:{G:"H",I:"J"}}}
Output :
{
A:"B",
C:
{
D:"E",
F:
{
G:"H",
I:"J"
}
}
}
Example 2:
Input : ["foo", {"bar":["baz",null,1.0,2]}]
Output :
[
"foo",
{
"bar":
[
"baz",
null,
1.0,
2
]
}
]
[] and {} are only acceptable braces in this case.
Assume for this problem that space characters can be done away with.
Your solution should return a list of strings, where each entry corresponds to a single line. The strings should not have “\n” character in them.
'''
### solution shouldnt have \n but just list of strings and each element represents the line
class Solution:
# @param A : string
# @return a list of strings
def prettyJSON(self, A):
result = []
temp=""
indentcnt = 0
### DONT FORGET TO APPEND INDENTCNT FOR EVERY RESULT APPEND
for i in range(len(A)):
if A[i] in ('[', '{'):
if temp != "" : #not emptyd
result.append('\t'*indentcnt +temp)
temp="" #reset
result.append('\t'*indentcnt + A[i])
indentcnt += 1
elif A[i] in (']', '}'):
if temp != "": # not empty
result.append('\t'*indentcnt +temp)
temp = "" # reset
indentcnt -= 1
result.append('\t'*indentcnt + A[i])
elif A[i] == ',': #after comma, character or { can come next. For now, I assumed that the character would come put didn't consider {
if temp != "": #not empty
result.append('\t'*indentcnt+ temp +A[i])
temp="" #reset
else: #CASE }, (BUT THIS WAS NOT MENTIONED AS THE EXAMPLE...)
result[-1] = result[-1]+A[i] #change directly maybe because it is reference?!
else: # just character
temp+=A[i]
return result
solution = Solution()
# print(solution.prettyJSON("{\"id\":100,\"firstName\":\"Jack\",\"lastName\":\"Jones\",\"age\":12}"))
ls = solution.prettyJSON("[\"foo\", {\"bar\":[\"baz\",null,1.0,2]}]")
for i in range(len(ls)):
print(ls[i])
# print(solution.prettyJSON2("{\"id\":100,\"firstName\":\"Jack\",\"lastName\":\"Jones\",\"age\":12}"))
# string1 = "aaaa" + "\n"*2 + "\t" * 3 + "ccc"
# print(string1)
'''
def prettyJSON2(self, st):
# ans is list of string to print
ans = []
line = ''
# no of tab required
tab = 0
for s in st:
# to avoid empty lines
line = line.strip()
if s in ['{', '[', '}', ']', ]:
if line:
ans.append('\t' * tab + line)
# append is after decreasing tab count
if s in ['}', ']']:
tab -= 1
ans.append('\t' * tab + s)
if s in ['{', '[']:
tab += 1
line = ''
continue
if s in [',']:
line += s
# if only comma, then it should be in previous line
if line == ',':
ans[-1] += s
elif line:
ans.append('\t' * tab + line)
line = ''
else:
line += s
return ans
''' |
4adbbc26f25be224bab4658952321dff0e1e0f07 | qihong007/leetcode | /2020_03_05.py | 1,848 | 4 | 4 | '''
Given an image represented by an N x N matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?
Example 1:
Given matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
Rotate the matrix in place. It becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
Example 2:
Given matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
Rotate the matrix in place. It becomes:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]
执行用时 :20 ms, 在所有 Python 提交中击败了78.79% 的用户
内存消耗 :11.7 MB, 在所有 Python 提交中击败了100.00%的用户
'''
class Solution(object):
def rotate(self, matrix):
length = len(matrix)
for i in range(0, length):
bian = length-1-i
if (i < length-1-i):
for j in range(i, length-i-1):
k = length-1-i-i
if i == j:
m1 = matrix[i][j]
m2 = matrix[j][bian]
m3 = matrix[bian][bian]
m4 = matrix[bian][j]
matrix[i][j] = m4
matrix[j][bian] = m1
matrix[bian][bian] = m2
matrix[bian][i] = m3
else:
m1 = matrix[i][j]
m2 = matrix[j][bian]
m3 = matrix[bian][length-1-j]
m4 = matrix[length-1-j][i]
matrix[i][j] = m4
matrix[j][bian] = m1
matrix[bian][length-1-j] = m2
matrix[length-1-j][i] = m3
|
68900eeabc166831d274e8a399d8b336413b9140 | PoorPorter1/JSteg | /unhide.py | 4,412 | 4.15625 | 4 | # Hi,
# This photo has a message embedded in it.
# As a hint, I have given the code of how I have encoded it.
# I have also defined all the functions that you will need to decode the image
# You just need to come up with the logic of decoding it.
# It is your job to complete the unhide() function.
# Sorry if this is too tough/easy for you :P I have never set questions for anyone before
# If you want I can just send you the solution! :)
# General intructions:
# 0) Download and install PIL :P
# Don't worry you don't need to know anything about PIL. That part is already taken care of
# 1) Start following the code from if __name__ == '__main__' block (meh you already know this)
# The first three lines which are commented out show how I used the hide() function to encode the message
# 2) You only need to write a part of unhide().
# Use the functions defined in functions.py to help you out.
# You won't need to define any other functions
# 3) This is not any standard encryption algorithm. I don't even think this can be classified as encryption.
# Don't waste time thinking about what you studied in crypto class. Unless you studied 'Steganography'.
# Don't worry though; it is not a standard encryption algorithm for a reason: It is extremely easy to decode :P
# Hint: Think about pixel manipulation :)
# The hash function is only used to check if you have decoded the full/correct message
# You won't be able to decode the message using any function in the Crypto/hashlib library.
# Just use the functions I have already defined
# I have almost written the unhide function as well :P
# You just have to write 3 lines of code :P
# Happy birthday Nidhz!
from PIL import Image
import functions # Use the functions inside this file. You will need only these functions
import sanity_check # This will be of no use to you
# This is just for me to check if you have decoded the correct/complete messsage :)
def encode(hexcode, digit):
hexcode = hexcode[:-1] + digit # Hint: This changes LSB of every pixel
return hexcode
def decode(hexcode):
return hexcode[-1]
def hide(filename, message):
img = Image.open(filename) # Meh
binary = functions.str2bin(message) + '1111111111111110' # 1111111111111110 bit pattern marks the end of the message
# So suppose I want to store 'blah' the binary version will be: '11000100110110001100001011010001111111111111110'
# ie: the last 16 bits will always be 1111111111111110
img = img.convert('RGBA')
if img.mode in ('RGBA'): # Sanity check
data = img.getdata() # list of tuples containing RGB values as its first three elements
newData = [] # Modidified image pixels
digit = 0
temp = ''
for item in data:
if (digit < len(binary)):
newpix = encode(functions.rgb2hex(item[0],item[1],item[2]),binary[digit]) # item[0], item[1], item[2] correspond to the RGB values
# encode will only return data if some condition is met
r, g, b = functions.hex2rgb(newpix)
newData.append((r,g,b,255))
digit += 1
else:
newData.append(item)
img.putdata(newData) # Overwriting image with new pixels
img.save(filename, "PNG")
return True
return False
def unhide(filename):
img = Image.open(filename)
binary = '' # binary will store the decoded message in binary form
img = img.convert('RGBA')
if img.mode in ('RGBA'): # Sanity check
data = img.getdata()
for item in data:
hidden_digit = decode(functions.rgb2hex(item[0],item[1],item[2]))
# Remove the print statement
# Store the retrieved data in a string
# Return the string from here
# return "Write your code here and remove this line"
binary = binary + hidden_digit
if (binary[-16:] == '1111111111111110'):
return functions.bin2str(binary[:-16])
else:
return False
if __name__ == '__main__':
# For hiding data
# fh = open('text.txt', 'r')
# s = fh.read()
# hide_check = hide('budday.png', s)
# The part that you have to write:
# Return the entire message as a single string
s = unhide('budday.png')
# You don't need to change this. This is for me to check if you got it right
if s is not False and sanity_check.check(s):
print s
elif s is False:
print "bapchufied: Something went wrong from the start"
else:
print "bapchufied: Wrong/incomplete message decoded"
# fh.close()
|
a58dfb27e779435d35cef18bf0195ca7fc3663eb | CityQueen/bbs1 | /Abgaben - HBF IT 19A/20191128/count Joshua Pfeifer.py | 183 | 3.578125 | 4 | t1 = str(input("Bitte gebe einen Text ein: "))
z1 = str(input("Bitte gebe ein Welches Zeichen du zählen willst: "))
z2 = t1.count(z1)
print("Das Zeichen", z1, "gibt es", z2, "mal") |
9b4348ee3f6e765b4a6e6699ea06772b3d74b5b1 | KristofferFJ/PE | /problems/unsolved_problems/test_283_integer_sided_triangles_for_which_the__areaslashperimeter_ratio_is_integral.py | 646 | 4.09375 | 4 | import unittest
"""
Integer sided triangles for which the area/perimeter ratio is integral
Consider the triangle with sides 6, 8 and 10. It can be seen that the perimeter and the area are both equal to 24.
So the area/perimeter ratio is equal to 1.
Consider also the triangle with sides 13, 14 and 15. The perimeter equals 42 while the area is equal to 84.
So for this triangle the area/perimeter ratio is equal to 2.
Find the sum of the perimeters of all integer sided triangles for which the area/perimeter ratios are equal to positive integers not exceeding 1000.
"""
class Test(unittest.TestCase):
def test(self):
pass
|
3ae19bf77907c357d66b8809888a06bb3f1e444e | marydawod/Replit | /main.py | 4,396 | 4.28125 | 4 | from GPA import foo
#imports the def foo(letter_grade) from GPA.py to main.py
#In this marking period, there will be three homework grades, two quiz grades, and one test grade.
print("WELCOME TO THE PYTHON CALCULATOR!!\n\n\tThe Python Calculator calculates your grade point average as well as category averages for sections including tests, quizzes, and homework! \n\n\tBy inserting the grade(s) per category, the Python Calculator will provide the average grade you will have received and proceeds to take each of the category averages and calculate them together in order to provide your grade point average.\n\n")
questions = ["What is your name? \n\t", "What grade are you in? \n\t", "What is your age? \n\t", "What year will you graduate? \n\t"]
for x in questions:
input(x)
print("\nNow we will be calculating your average assignments and we'll assign a grade for it. After that, you will receive a letter grade for the class, which will be utilized to figure out your final GPA! Lets start! \n\nFor the categories that you will be asked, please write clearly and put it in singular form (ex: Project, Test, Quiz, etc.).")
category__1 = str(input("\tEnter your first category: "))
#Asks the user to put in three category__1 grades.
#1
category1 = int(input("\tEnter "+category__1+" 1: "))
#2
category11 = int(input("\tEnter "+category__1+" 2: "))
#3
category111 = int(input("\tEnter "+category__1+" 3: "))
print(" ")
category__2 = str(input("\tEnter your second category: "))
#Asks the user to put in three grades.
#1
category2 = int(input("\tEnter "+category__2+" 1: "))
#2
category22 = int(input("\tEnter "+category__2+" 2: "))
#3
category222 = int(input("\tEnter "+category__2+" 3: "))
print(" ")
category__3 = str(input("\tEnter your third category: "))
#Asks the user to put in their category__3 grades.
#1
category3 = int(input("\tEnter "+category__3+" 1: "))
#2
category33 = int(input("\tEnter "+category__3+" 2: "))
#3
category333 = int(input("\tEnter "+category__3+" 3: "))
print(" ")
#This averages out the three Homework grades, and multiplies the average by the percentage.
averagecategory1 = (category1+category11+category111)/(3.0)
category_1 = (0.15*averagecategory1)
print("\nYour average "+category__1+" grade is a "+str(category_1)+"%, after multiplying it by 0.15, since it is graded as 15% in this class.")
#This averages out the two Quiz grades, and multiplies the average by the percentage.
averagecategory2 = (category2+category22+category222)/3.0
averagecategory3 = (category3+category33+category333)/3.0
#Calculates the quizzes, test, and has a final grade
category_2 = (float)(0.35*(averagecategory2))
print("\nYour average "+category__2+" grade is a "+str(category_2)+"%, after multiplying it by 0.35, since it is graded as 35% in this class.")
category_3 = (float)(0.50*(averagecategory3))
print("\nYour average "+category__3+" grade is a "+str(category_3)+"%, after multiplying it by 0.50, since it is graded as 50% in this class.")
grade = (float)(category_1+category_2+category_3)
print("Your grade is "+(str(round(grade, 2)))+"%")
#----------------------------------------------------------------------------------#
letter_grade = ""
if(grade > 100):
print("Grade above 100 are invalid")
#90 to 100 constitutes an A.
elif(grade <= 100 and grade > 89):
print("You received an A! You're doing great and keep up the good work!")
letter_grade = "A"
#80 to 89 constitutes a B.
elif(grade <= 89 and grade > 79):
print("You received a B. You're working really hard, and you're close to an A!")
letter_grade = "B"
#70 to 79 constitutes a C.
elif(grade <= 80 and grade > 69):
print("You received a C. Tutoring is available.")
letter_grade = "C"
#60 to 69 constitutes a D.
elif(grade <= 69 and grade > 59):
print("You received a D. It's time to hit the books.")
letter_grade = "D"
#0 to 59 constitutes an F.
elif(grade <= 59 and grade >= 0):
print("You received a F. Try studying next time.")
letter_grade = "F"
#You can't have a negative grade :)
elif(grade < 0):
print("Grades below 0 are invalid")
#----------------------------------------------------------------------------------#
pi = (foo(letter_grade))
print(pi)
#class Grade:
# def find(letter):
# print(str(letter))
#y = str(letter_grade)
#print(y)
#print("After rechecking your GPA, it is confirmed that the following is your GPA:")
#pii = Grade()
#pii.find((y)) |
7d6403c1ad8388f32de82dffbc0b0218548a4dae | justellie/py4e | /ultimo_reto_curso1.py | 612 | 3.90625 | 4 | #TIENES QUE ESTAR PENDIENTE DE LOS ESPACIOS PORQUE ESA VAINA SI IMPORTA COÑO !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
acum=0
mayor=None
menor=None
while True:
print("ingrese numero o done para salir:")
inp=input()
if inp=='done':
break
try:
inp=int(inp)
except :
print('Invalid input')
inp=input()
inp=int(inp)
if mayor==None:
mayor=inp
elif inp>mayor:
mayor=inp
if menor==None:
menor=inp
elif menor>inp:
menor=inp
acum+=inp
print('acumulado', acum)
print('mayor',mayor)
print('menor', menor) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.