text stringlengths 37 1.41M |
|---|
"""
Write a program that takes an integer and sets the nth bit in binary representation of that integer
"""
def setBit(n,k):
print(bin(n))
#We simply shift one by K bits
a = 1 << k
print(a)
#Now, all we have to do is or the n and the a, this will give the new integer obtained after setting th... |
str1 = input("Enter the string:\t")
map1 = {}
list1 = []
for i in str1:
if i in map1:
list1.append(i)
else:
map1[i] = 1
print("THe duplicate characters are:\t",list1) |
class TrieNode:
def __init__(self):
## Initialize this node in the Trie
self.children = {}
self.is_word = False
pass
def insert(self, char):
if char not in self.children:
self.children[char] = TrieNode()
pass
def suffixes(self, suff... |
str1 = input("Enter the string:\t")
print("The string is "+str1) |
def stock(list1):
max1 = 0
buy_day = 0
sell_day = 0
for i in range(0,len(list1)):
for j in range(i+1,len(list1)):
temp = list1[j] - list1[i]
if temp > max1:
max1 = temp
buy_day = i
sell_day = j
print("Buy Dat... |
"""break statement will break out of the loop"""
x=int(input('how many candies do you want:'))
av=10
i=1
while i <=x:
if i>av:
break
print ('candy')
i+=1
print("bye")
"""continue statement is to skip the next comment line but stays with in the loop"""
x=int(input("print till with number:"))
for i i... |
#output using print statement
print("hello")
#we also use end= to create a format for our output
print("greek",end=" ")
print("kevin")
#sep is used to seperate the values
print("10","9","8",sep='-') |
# -*- coding: UTF-8 -*-
"""PyRamen Homework Starter."""
# Import libraries
import csv
from pathlib import Path
# Set file paths for menu_data.csv and sales_data.csv
menu_filepath = Path("Resources/menu_data.csv")
sales_filepath = Path("Resources/sales_data.csv")
report_filepath = Path("Resources/sales_report.txt")
... |
print("Hello world!");
name = input('please input your name:')
print(name, end='.')
print('hello', 'nice to meet you!', sep=',')
print(19**9)
a = ["Hello", "How are ya?", "Hi!"]
b = open("Greedy.txt",'+wt')
b.write(a[1])
|
import math
Data1 = [70,64,69,72,62,71,54,68,65,77] # use this to input data
Data2 = [79.98, 80.04, 80.02, 80.03, 80.03, 80.04, 80.04,79.97, 80.05, 80.03, 80.02, 80, 80.02]
Data = [80.02, 79.94, 79.97, 79.98, 79.97, 80.03, 79.95, 79.97]
def averge(Data):
sum = 0
for i in Data:
sum += i
a... |
def change(aint,alis,adic):
aint = 0
alis.append(4)
adict = {'apple':'34kg','blanana':'43kg','peach':'45kg','watermelon':'46kg'}
print('In the changing:')
print('aint: ',aint)
print('alis: ',alis,' ;alist: ',alist);
print('adic: ',adict,' ;adict: ',adict)
aint = 1
alist = [3]
adi... |
class Person():
'''Represents a person
Args:
name (str) : the name of the player
age (int) : the name of the player
'''
def __init__(self, name: str, age: int) -> None:
'''Person has name and age'''
self.name = name
self.age = age |
import unittest
from lottery import spin_lottery
class LotteryTest(unittest.TestCase):
def test_selected_numbers_only_10_by_default(self):
self.assertEqual(
len(spin_lottery()), 10
)
def test_selected_numbers_are_integers(self):
selected_numbers = spin_lottery()
s... |
#Lewis Travers
#18/11/2014
#calculating pay
def calculate_basic_pay (hours,pay):
total = hours * pay
return total
def calculate_overtime_pay (hours,pay):
overtime_pay = (hours - 40) * (pay * 1.5)
basic_pay = 40 * pay
total = overtime_pay + basic_pay
return total
def calculate_to... |
#Lewis Travers
#28/11/2014
#sort function
def get_numbers():
x = int(input("Please enter a number for x: "))
y = int(input("Please enter a number for y: "))
return x, y
def sort_function(x, y):
if x > y:
return y, x
else:
return x, y
def print_numbers(x, y):
if... |
import random, sys, time
start_time = time.time()
nums_to_days = {
0: "Noneday",
1: "Mon",
2: "Tue",
3: "Wed",
4: "Thu",
5: "Fri",
6: "Sat",
}
days_to_nums = {
"sun": 0,
"mon": 1,
"tue": 2,
"wed": 3,
"thu": 4,
"fri": 5,
"sat": 6,
}
if len(sys.argv) == 1:
y... |
from enum import Enum
from aenum import MultiValueEnum
class Weekday(Enum):
"""Weekdays
Used to identify weekly repeating lessons. Starting with `monday`
according to the python documentation (see `date.weekday()`)
"""
monday = 0
tuesday = 1
wednesday = 2
thursday = 3
friday = 4
... |
from tkinter import *
# input
# first widget that always have to be. Creates root window
root = Tk()
e = Entry(root,width =50,bg='green')
#attributes
#border width
e.pack()
#default text in input
e.insert(0,"Enter your name")
#get what is in input
e.get()
#After clicking button , text in input is displayed
def my... |
# combine all the pre-vision together
import random
# int-check function
def intcheck(question,low,high):
valid = False
error = "Whoops! Please enter an integer "
while not valid:
try:
response = int(input(question))
if low <= response <= high:
return respons... |
# -*- coding: utf-8 -*-
class A(object):
"""
Class A.
"""
a = 0
b = 1
def __init__(self):
self.a = 2
self.b = 3
def test(self):
print ('a normal func.')
@staticmethod
def static_test(self):
print ('a static func.')
@classmethod
def class... |
from abc import ABC, abstractmethod
class Hero(ABC):
@abstractmethod
def attack(self):
pass
def equip(self, weapon):
self.weapon = weapon
class IronMan(Hero):
def attack(self):
print(f"钢铁侠用{self.weapon}发起攻击!")
class SpiderMan(Hero):
def attack(self):
print(f"蜘蛛... |
from maekawa import maekawa_enter, wait_for_votes, my_rank
"""
@author: Huy Nguyen
- Source:
+https://www.coursera.org/learn/cloud-computing-2/lecture/GMHYN/2-4-maekawas-algorithm-and-wrap-up
- Let's assume we have reliable unicast for this implementation.
- i := my_rank
- Explanation a... |
# import the necessary packages
import argparse
import imutils
import cv2
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="Path to the image")
args = vars(ap.parse_args())
# load the image and show it
image = cv2.imread(args... |
str1 = input('Enter string')
str2 = str1[0].isupper()
print(str2)
|
# 1. Из всех методов списка (list) выбрать 5 тех, которые по вашему мнению используются чаще всего и написать их через запятую с параметрами
lst = []
lst.append(self, object)
lst.pop(self, index)
lst.sort(self, key, reverse)
lst.count(self, object)
lst.copy(self)
# 2. Из всех методов словарей (dict) выбрать 5 тех, кот... |
'''example program in how to use the tkinter checkbutton widget'''
from tkinter import *
# **** Functions ****
def display():
check_value = check_control.get()
value_label.config(text=str(check_value))
# **** Create window ****
root = Tk()
root.geometry("300x200")
root.title("Tkinter Check Button Example")
... |
# file_io_10 append file
with open("new_text_file.txt","a") as file:
# "a" - Append - Opens a file for appending, creates the file if it does not exist
file.write("Hello World!")
|
# example program for using tkinter's spinbox widget
from tkinter import *
# **** Functions ****
def display():
selection = choice_sb.get()
display_label.config(text=str(selection))
# **** Create window ****
root = Tk()
root.geometry("300x200")
root.title("Tkinter Spin Box Example")
# **** Add window con... |
'''example program for creating a window'''
from tkinter import *
# **** Create window ****
root = Tk()
root.geometry("300x200")
root.title("Tkinter window example")
# **** Run window loop ****
root.mainloop()
|
'''example program for using tkinter's option menu widget'''
from tkinter import *
# **** Functions ****
def display():
selected = option_control.get()
display_label.config(text=selected)
# **** Create Window ****
root = Tk()
root.geometry("300x200")
root.title("Tkinter Option Menu Example")
# **** Add co... |
#coding =utf8
from sys import argv
script,user_name= argv
prompt='>'
print "Hi %s, I'm the %s script." %(user_name,script)
print "I'd like to ask you a few questions."
print "Do you like me %s ?" %user_name
likes=raw_input(prompt)
print "Where do you live %s" %user_name
lives=raw_input(prompt)
print "What kind of co... |
import math
def is_prime(num):
isprime=True
if num>2:
for i in range(2,int(math.sqrt(num)+1),1):
pass
if num%i==0:
isprime=False
if num<=0 or num==1:
isprime=False
if num==2:
isprime=True
return isprime
print is_prime(2) |
import pickle as pick
class Clock:
def __init__(self,hours = 0,minutes = 0,seconds = 0):
self.hours = hours
self.minutes = minutes
self.seconds = seconds
def addTime(self,hours = 0,minutes = 0,seconds = 0):
if seconds + self.seconds >= 60:
self.minutes += ((seconds ... |
#def dodaj(a,b):
# return a+b
dodaj = lambda a,b: a+b
print(dodaj(10,20))
lista = [dodaj(x,y) for x,y in ([10,10],[11,13])]
print(lista)
print((lambda a,b:a**3+3*a-b**2)(10,20))
#Domknięcia
def make_incrementor(n):
return lambda x: x+n
f = make_incrementor(100)
print(f(11))
lista = sorted(range(-3,12),key... |
def dodaj(a :int = 0,b :int = 0) -> str:
return str(a+b)
print(dodaj(5))
print(dodaj.__name__)
innaFunkcja = dodaj
print(innaFunkcja(5,1))
def generatorFunkcji(bezZmian,czyUpper):
def powielTekst(text,ileRazyPowtorzyc = 1):
return text * ileRazyPowtorzyc
def powielTekstUpper(text:str, ileRazyPow... |
#Solving the 1st challenge
#http://www.pythonchallenge.com/pc/def/0.html
def first_challenge():
num: int = 2
return f'{num ** 38}'
def new_url():
url = "http://www.pythonchallenge.com/pc/def/0.html"
url = url.replace("0", first_challenge())
print(f'paste this result as http url browser:\n{url}')
... |
"""
Simple async example using Tornado:
Tornado accepts a GET request @ '/?url=' and returns the URL requested
"""
import tornado.ioloop
import tornado.web
import tornado.httpclient
import validators
def get_errors():
return {
'missing': 'Please pass url as a parameter',
'invalid': 'Please pass ... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
''' Demonstrates some basic functions for writing to the display.
These examples need to be run on a raspberry pi and GPIO needs to be installed
(hint: `pip install --user GPIO`).
Caveats:
The PI must have the serial GPIO pins enabled (enable_uart=1 in
/boot/config.tx... |
# Affine Cipher Breaker
# http://inventwithpython.com/codebreaker (BSD Licensed)
import pyperclip, affineCipher, detectEnglish, cryptomath
SILENT_MODE = False
def main():
# You might want to copy & paste this text from the source code at
# http://invpy.com/affineBreaker.py
myMessage = 'H RZPEDYBO NZDKW W... |
#!/usr/bin/python3
'''
Recursive function that queries the Reddit API
and returns a list containing the
titles of all hot articles for a given subreddit.
'''
import itertools
import requests
def recurse(subreddit, hot_list=[], after=None, count=0):
'''
Recursivly return list count
of hot articles
'''
... |
favorite_numbers = {
"alice":[1,2,3],
"ben":[4,5,6],
"wang":[7,8,9],
}
for key,values in favorite_numbers.items():
print("These are the favorite numbers for: " + key.title())
for value in values:
print(str(value))
print("\n") |
# Import declarations go here
import pandas
import random
import xlrd
# Title: realloc.py
# Authors: Harsha Cheemakurthy, Anna Robbins
# Hack the Crisis Sweden 2020
# open spreadsheets to extract data
pd1 = pandas.read_excel('Sample_unemployment_Stockholm_30.xlsx')
pd2 = pandas.read_excel('Sample_job_openi... |
n=input("enter the number")
i=1
l=list()
while(len(l)<int(n)):
li=list(str(i))
#print(li)
while '9' in li:
i=i+1
li=list(str(i))
l.append(i)
print(i)
i=i+1
print("nth term",l[-1]) |
s=input("")
l=[]
s.split()
print(s)
s[0][0]=s[0][0].upper()
s[0][0]=s[1][0].upper()
print([0][0],[1][0])
|
if(i==20):
for s in l:
if(s==5 | s==10 ):
t.append(s)
if(d==10 ):
t.append(d)
else:
print('f')
exit()
break |
# Import_libraries
import matplotlib.pyplot as plt
import numpy as np
from math import *
# Set range
N = np.arange(200).tolist()
val = np.zeros(200)
X = input('Input Equation for x(n): ')
def F(n):
return eval(X)
for n in range(200):
val[n] = F(n)
# Input values of x and y
x = np.sin(val)
y = ... |
import operator
class Stack:
def __init__(self):
self.stack = []
def push(self, value):
self.stack.append(value)
def pop(self):
if self.size() > 0:
return self.stack.pop()
else:
return None
def size(self):
return len(self.stack)
def ... |
class Student:
def __init__(self, n):
self.name = n
self.scores = []
def add_score(self, score):
self.scores.append(score)
def avg_score(self):
if self.scores:
avg = sum(self.scores) / len(self.scores)
print(f"Avg score: {avg}")
else:
print("No Scores Available Yet") |
def list_to_number(digits):
result = ""
for number in digits:
result += str(number)
return result
def main():
print(list_to_number([1, 2, 3]))
if __name__ == '__main__':
main()
|
import copy
class CashDesk:
def __init__(self, money={100: 0, 50: 0, 20: 0, 10: 0, 5: 0, 2: 0, 1: 0}):
self.money = money
self.total_amount = 0
def take_money(self, amount):
for sum in amount:
self.money[sum] += amount[sum]
def total(self):
for cash in self.m... |
from count_substrings import count_substrings
def count_vowels(str):
vowels = ['a', 'e', 'i', 'o', 'u', 'y', 'A', 'E', 'I', 'O', 'U', 'Y']
result = 0
for character in vowels:
result += count_substrings(str, character)
return result
def main():
print(count_vowels("Theistareykjarbunga"))
... |
base = input("Enter a base:")
expo = input("Enter an exponent:")
result = base ** expo
print "{} to the power of {} = {}".format(base, expo, result)
|
import os
import csv
import argparse
import sys
import re
def argument_parser():
parser = argparse.ArgumentParser(description="Splitting CSV with input file, output file and row limits")
parser.add_argument("-i", "--input", help="Input File Name", type=str, required=True)
parser.add_argument("-o", "--output", help=... |
# PersonEx 클래스를 구성하시오
# 속성으로 name, age가 존재한다
# 액션(함수)로 getName, getAge 가 존재한다.
# name과 age는 생성자에서 초기화 된다.
##################################################
# 파이썬의 모든 클래스의 수퍼 클래스(근본 클래스)는
# Object 존재함
class PersonEx:
# 멤버변수
name = None
age = None
# 생성자
def __init__(self,name,age):
self.name ... |
'''
2. 여러개 데이터 (연속 데이터, 시퀀스 데이터)
- 튜플 :
(),
순서가 있다,인덱스 존재,값의 중복 신경 안씀
값을 여러개 묶는다에 의미를 둔다. 값변경불가
함수에서 리턴할때
'''
tu = ()
print(tu, type(tu),len(tu))
tu = tuple()
print(tu, type(tu),len(tu))
##########################################################################
tu = (1)
print(tu, type(tu))
# 값이 1개인... |
#Autor: Eduardo Roberto Müller Romero
# Una compañía aplica cierto descuento al comprar n cantidad de paquetes de software, el programa calcula descuento y total
def calcularPago(x):
'''
La función recibe un valor y basándose en el, decide si se aplica un descuento, que descuento se aplica y además
calcula el... |
import csv
new_contacts = [] # This list is for all new contacts.
new_validated = [] # This list is for old contacts, who have been validated since the last export.
emails = []
# This is the value that represents if the contact has been previously validated.
NOT_VALIDATED = "0"
'''
FUNCTION DEFINITIONS
'''
de... |
""" Node is defined as
class node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
"""
def check_binary_search_tree_(root):
node_queue = []
root.max = 10001
root.min = -1
node_queue.append(root)
while node_queue:
cur_node = node_queue.pop(0)... |
class Printer:
def __init__(self,maufacturer):
self.maufacturer=maufacturer
def print(self,personlist):
for i in personlist:
print(i.name,i.address)
print("printed from %s printer" % self.maufacturer)
class Person:
def __init__(self,name,address):
... |
class Printer:
def __init__(self,maufacturer):
self.maufacturer=maufacturer
def print(self,person):
print ("%s 's address is %s " % (person.name, person.address))
print(person.name)
print(person.address)
print("Printed From %s printer" % self.maufacturer)
class Person:
def... |
#!/bin/python3
import sys
import os
import datetime as dt
import inspect
# Add log function and inner function implementation here
def log(function):
def printlog(*args, **kwdargs):
str_template = "Accessed the function -'{}' with arguments {} {}".format(function.__name__,args,kwdargs)
print(str... |
temp=0
list=[1,20,100,50,30,80]
listleng=len(list)
for i in range(0,listleng-1):
for x in range(0,listleng-1):
if(list[x]>list[x+1]):
temp=list[x]
list[x]=list[x+1]
list[x+1]=temp
print(list)
|
#store datas on mysql
import mysql.connector
def login():
user = input('Please input user name: ')
password = input('Please input password: ')
try:
#Try login.
conn = mysql.connector.connect(user = user, password = password)
except mysql.connector.errors.ProgrammingError as e:
print('Er... |
"""
Author: Joshua Jansen Van Vueren
Desc: Class describing an object which contains climate and temperature data
"""
class ClimateRecord(object):
def __init__(self, string):
s = self.splitCSVIntoArray(string)
self.date = s[0]
self.actualMinTemp = int(s[1])
self.actualMaxTemp = in... |
#name = input('What is your name?')
#print(str.upper(str('hello ' + name)))
#print('Your name has' + str(len(name)) + 'letters in it! Awesome!')
user_input = int(input("Enter a number:"))
result = user_input * user_input
print(result )
|
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 9 10:25:09 2018
@author: shuli
"""
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if len(s) % 2 != 0:
return False
opening = ['(','[','{']
matches = [('(',')'),('[',']'),('{... |
class Solution:
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
n = len(nums) - k
nums[:] = nums[n:] + nums[:n]
if __name__ == '__main__':
a = Solution()
nums = [1,2,3,... |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 15 17:28:19 2018
@author: shuli
"""
class Solution:
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
if x == 0 or x == 1:
return x
left,right = 1,x
while left < right:
mid = (left + ... |
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 11 18:27:44 2018
@author: shuli
"""
class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if target in nums:
return nums.index(target)
left... |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 10 10:58:12 2018
@author: shuli
"""
class Solution:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
if nums == []:
return 0
i = 0
while i < len(nu... |
from character import *
from random import randint, choice
"""
In this simple RPG game, the hero fights somebody. He has the options to:
1. fight an enemy
2. do nothing - in which case the enemy will attack him anyway
3. flee
"""
"""
Character classes:
hero, medic, shadow, wizard, zombie, goblin, rhino, jackie
"""
d... |
def translate(lord)
lordex = 0
for letter in name:
if letter.lower() in "aiu":
letter = "o"
lord += letter
elif letter.lower() in "oy":
letter = "i"
lord += letter
elif letter.lower() in "h":
letter = "u"
... |
from random import randint
numero_aleatorio = randint(1, 101)
contador = 0
while True:
contador += 1
numero_secreto = input("Adivinhe o numero secreto de 1 a 100: ")
if numero_secreto == "sair":
print("Sair")
break
numero_secreto = int(numero_secreto)
if numero_secreto > numero_ale... |
#this file is for accessing the text file and making a new one
#removed because requirements say no global variables; can be retrieved by calling getLines(f, []) to return the lines
#lines = list()
#inputTxt = open("input.txt", "r")
#getLines recursively retrieves lines
def getLines(f, lst):
line = f.readline()
... |
def processLine(line, linePointer):
lineParts = line.split()
function = lineParts[0]
result = 0
linePointer = linePointer + 1
if function == 'calc':
operation = lineParts[1]
int1 = int(lineParts[2])
int2 = int(lineParts[3])
print(f'[{linePointer - 1}] calculate {ope... |
operator_list = ["+", "-", "/", "*", "q"]
print("Byl spuštěn program Kalkulačka, který umožnuje sčítaní, odečítání, násobení a dělení")
print("Program Vás nejprve vyzve pro zadání čísla, následně Vás vyzve pro zadání matematického operátoru (+,-,*,/), poté k dalšímu číslu")
print("Pokud zadáte matematický operátor jako... |
from typing import NamedTuple
from collections import namedtuple
task = []
# title, done - True/False
Task = namedtuple("Task", "title status")
# task = Task("Posekat zahradu", False)
# task[0]
# task[1]
# task.title
# task.status
def show_menu():
print("Menu: (pro výběr stiskněte danou klávesu)")
print(... |
def div(x, y):
try:
return (x/y, False)
except ZeroDivisionError:
return (None, True)
print("1", div(3, 2))
print("2", div(14, 0))
while True:
a = input ("cislo")
b = input ("cislo")
try:
result = int(a) / b
print (f"vysledek {result}")
except ZeroDivisionErro... |
"""
http://codingbat.com/prob/p197466
Given an int n, return the absolute difference between n and 21, except return
double the absolute difference if n is over 21.
diff21(19) → 2
diff21(10) → 11
diff21(21) → 0
"""
def diff21(n):
diff = 21 - n
if n > 21:
return diff * -2
return diff
if __nam... |
point1 = list(map(float, input("Enter x and y coordinate: ").split()))
point2 = list(map(float, input("Enter x and y coordinate: ").split()))
dist = (((point2[0] - point1[0]) ** 2 + (point2[1] - point1[1]) ** 2) ** 0.5)
print(dist) |
"""
JADS 2020 Data-Driven Food Value Chain course
Introduction to Sensors
Lunar Lander Micropython Exercise
"""
# ------------------------ Objective of the game -------------------------------------
# this game simulates a lunar landing module (LLM) landing on the moon
# you are the pilot and need to c... |
import sqlite3
class database:
id=""
def __init__(self,databaseName = "database",table="users",numberOfColumn=2,columns=None):
self.databaseName=databaseName
self.openDatabase(self.databaseName)
if not(self.tableFound(table)):
print("done")
self.createTa... |
import numpy as np
def common_subgraph(A, B, nodes_list_A, nodes_list_B, directed=False):
"""
Retrievs the common sub graph of two networks.
Given the adjacency matrices of two networks and their nodes lists it finds
the nodes in common and consequentely the edges.
Parameters
----------
... |
class Example:
def __init__(self):
print("You have choosen to view an example. To advance each step press enter.\nIn the example we will use the polynomial: 2x^4 + x^3 - 19x^2 -9x +9\n\n")
input("")
print("First you will find the factors of the leading coefficient: q = +-1, +-2")
in... |
import pandas as pd
import numpy as np
#reads the file and creates pandas dataframe
excel_file=R"xxxxx.xlsx"
data = pd.read_excel(excel_file, converters={'HTS':str}, index_col=None)
#creates dataframe without rows that have 'Free' in the EIF column
data_2=data[data['EIF'] !='Free']
#drop two unneeded colum... |
class Grafo:
def __init__(self, nome_arquivo = None):
self.vizinhos = {}
self.vertices = []
self.n = 0
self.m = 0
if nome_arquivo is not None:
self.carregar_do_arquivo(nome_arquivo)
def add_vertice(self, v):
if v not in self.vertices:
self.vizinhos[v] = []
self.vertices.append(v)
... |
def pay_off_debt_in_a_year(balance, annualInterestRate):
monthlyInterestRate = annualInterestRate / 12
updatedBalanceEachMonth = balance
monthlyPaymentLowerBound = balance / 12
monthlyPaymentUpperBound = (balance * (1 + monthlyInterestRate) ** 12) / 12
minimumMonthlyPayment = (monthlyPaymentUpperBou... |
#!/usr/bin/env python
import argparse
import hashlib
def hashthings(words, outfile, alg, verbose):
print('[*] Using the {0} algorithm').format(alg)
for word in words:
word = word.strip()
if word == '':
continue
else:
hsh = hashlib.new(alg, word).hexdigest()
if verbose == True:
print('[*] {0} {1}'... |
import hashlib # Generate MD5 hashes
__version__ = "0.1"
supportedHashes = ["sha256", "md5"]
def generateHash(data, hashtype):
if hashtype == "md5":
hash = hashlib.md5(data)
elif hashtype == "sha256":
hash = hashlib.sha256(data)
else:
raise ValueError
return hash... |
# CamJam EduKit 1 – Basics
# Worksheet 7 – Traffic Lights – Solution
# Import Libraries
import os
import time
from gpiozero import LED, Button, Buzzer
# Set up variables for the LED, Buzzer and switch pins
green = LED(24)
yellow = LED(23)
red = LED(18)
buzzer = Buzzer(22)
button = Button(25)
# Define a function for... |
class Node:
def __init__(self, data):
self.data = data
self.left = self.right = None
class BinarySearchTree:
def __init__(self):
self.root = None
def find(self, key):
"""
:param key:
:return:
"""
self.__find(self)
def __find(self, root... |
from bs4 import BeautifulSoup
import requests
topic = input("Enter topic : ")
response = requests.get("https://en.wikipedia.org/wiki/"+topic)
soup = BeautifulSoup(response.text,"lxml")
t = soup.find_all('h1')
text=""
for i in range(0,len(t)):
text+=t[i].text
print(text) |
import numpy as np
import pandas as pd
class HomeTemperature(object):
"""Home temperature.
"""
def __init__(self, T_heating, k_home_external, k_heater_on, k_heater_off, k_home_heater, t_step, engine=None):
self.T_heating = T_heating
self.k_home_external = k_home_external
self.k_hea... |
import tkinter as tk
from tkinter import*
h = 400
w = 400
root = tk.Tk()
root.geometry("250x400+300+300")
root.resizable(0,0)
root.title('Calculator')
A = 0
val = ''
operator = ''
data = StringVar()
lbl = tk.Label(
root,
font = ('Verdana',22),
anchor = 'se',
textvariable = data,
background = 'w... |
def solve_task1(file_name):
required_bag = "shiny gold bag"
bags_contained_by = read_file(file_name)
bags_can_contain = get_bags_can_contain(required_bag, bags_contained_by)
return len(bags_can_contain)
def read_file(file_name):
bags_contained_by = {}
with open(file_name, "r") as f:
for... |
from collections import Counter
import random
import itertools
import numpy as np
#important functions
def cardValue(card):
"""
CardValue retrieves the actual integer value of the card
@date 9/12/2017
@param card is the inputed card that we are trying to convert to an integer
... |
import discord
from discord.ext import commands
import random
# commands.Bot(command_prefix = '.')
# discort.Client()
client = commands.Bot(command_prefix = '.')
# print when bot is ready
@client.event
async def on_ready():
print("bot is ready")
# on member join prints members name and joined
@client.event
async de... |
# Alexander Harris
# Network Programming, CS325
# Homework 4, Simple Web Server
# Spring 2017
# Professor Tony Mullen
# To test run the program, download use python3 and execute the WebServer.py code on the server side machine.
# Issue this command :
# $ python3 WebServer.py
#
# Next we need to send a request for a... |
import time
###### Fibonacci ######
#Funcion:
def sucesion(num):
a = 0
b= 1
c=0
print(0)
for r in range(num):
print(c)
c = a+b
a = b
b = c
time.sleep(0.5)
#'Main':
print("Bienvenido a la Sucesión de Fibonacci.")
while True:
num = ... |
#Pythagorean Sequence in Python
# Copyright © 2019, Sai K Raja, All Rights Reserved
def Pythagorean_Theorem(a, b):
if a > 0 and b > 0:
return a**2 + b**2
elif a < 0 or b < 0:
print("Cannot use negative values in Pythagorean Theorem")
for i in range (1):
print(Pythagorean_Theorem(3, 6))
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.