text stringlengths 37 1.41M |
|---|
import turtle
import winsound
wn = turtle.Screen()
wn.title("Welcome to Pong Game")
wn.bgcolor("black")
wn.setup(width=800, height=600)
wn.tracer(0) # Basically stops the window from updating as we want manually, the game loop to update,
# also it speeds up the ga... |
"""Project “Quiz generator”
Write a program that will generate question for guessing countrie’s capital with 4 options of answers
1. Read content of file countries.txt and create a dictionary with country as it’s key and capital as value
2. Use random module (import random) in order to get country and it’s capital,usin... |
#2. Scrieti o functie generator care sa lucreze ca functia enumerate (yield)
import random
def fn1():
for i in range(100):
yield i, random.randrange(555)
x = fn1()
print(x)
print(next(x))
print(list(x)) |
#4. Scrieti un program care sa afiseze toti divizorii unui numar intreg.
divizori = []
x = int(input("introduceti numarul intreg: "))
for i in range(1,x+1):
if x % i == 0:
divizori.append(i)
print(divizori) |
from bs4 import BeautifulSoup
import json
import os
import re
import requests
from typing import List
def get_url(ticker: str, period: int) -> str:
"""
Compile the url for Historical Data from Yahoo Finance for Jan 1, 2020 to March 31, 2021. Frequency set to Daily.
:param str ticker: without ^ or other s... |
class Emp:
def __init__(self, name, dept, loc, sal):
self.name = name
self.dept = dept
self.loc = loc
self.sal = sal
self.count = 0
def __iter__(self):
return self
def __next__(self):
self.count += 1
if self.count == 1:
return se... |
#Functions are Objects in python
def Outer(message):
a = 10
b = 80
def inner():
c=30
ans = a +b + c
print("------ Answer is =",ans)
print("inner locals::", locals())
print("outer locals::", locals())
return inner
fnptr1 = Outer("hai bye")
fnptr2 = Outer("hai bye")... |
#!/usr/bin/env python
# coding: utf-8
# ### Problem Statement
#
# Given an input string, return all permutations of the string in an array.
#
# **Example 1:**
# * `string = 'ab'`
# * `output = ['ab', 'ba']`
#
# **Example 2:**
# * `string = 'abc'`
# * `output = ['abc', 'bac', 'bca', 'acb', 'cab', 'cba']`
#
# In[36... |
def rearrange_digits(input_list):
"""
Rearrange Array Elements so as to form two number such that their sum is maximum.
Args:
input_list(list): Input List
Returns:
(int),(int): Two maximum sums
"""
#at least two numbers are required for determining the problem
if not input_lis... |
def sort_012(input_list):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
input_list(list): List to be sorted
"""
#if list is none or of length 1 return as it is
if not input_list or len(input_list) == 1:
return input_list
... |
# coding=utf-8
"""Advent of Code 2017, Day 18, Part 2"""
with open("input.txt") as f:
instructions = [x.split(" ") for x in f.read().rstrip("\n").split("\n")]
class Program:
"""
An instance of a Program.
"""
def __init__(self, program_number):
self.registers = dict.fromkeys([instruction[... |
# In this file, training of the model is performed. Import all the necessary
# module from keras. Create a training generator and validation generator.
# Initialise the model and add the layers to the network. Compile and start
# training the model. Run the training for 10 epochs and save the model. Also
# save the his... |
homeworkmarks = [10, 6, 6, 7, 5, 0, 2, 4]
#positions 0 1 2 3 4 5 6 7
position = 0
totalmarks = 0
while position <=len(homeworkmarks)-1:
totalmarks += homeworkmarks[position]
position += 1
average = str(int(totalmarks)/(len(homeworkmarks)-1))
print("The total marks are: " + str(totalmarks))
... |
# 19、 定义一个学生类,实例属性有name(姓名),age(年龄),提示用户分别输入3个学生信息(姓名以及年龄),
# 根据用户输入的信息创建3个学生对象,将这3个学生对象存入列表,遍历列表删除年龄小于18岁的学生对象,
# 最后输出列表中剩余的学生信息
# 示例如下:
class Student(object):
list = []
def __init__(self):
self.name = input("请输入学生姓名:")
self.age = int(input("请输入学生年龄:"))
self.dict = {}
de... |
def parse(fn):
with open(fn) as f:
lines = [line.rstrip() for line in f]
width = len(lines[0])
height = len(lines)
trees = set()
for y, line in enumerate(lines):
for x, char in enumerate(line):
if char == '#':
trees.add((x, y))... |
import re
import sys
def parse(f):
foodRx = re.compile(r"([a-z ]+) \(contains ([a-z, ]+)\)")
for line in f:
ingredients, allergens = foodRx.match(line).groups()
yield set(ingredients.split()), set(allergens.split(", "))
def identifyAllergens():
identifiedIngredients = set()
potential... |
"""
Mocks out led device hardware
"""
from logging import getLogger
from unittest.mock import Mock
_LOGGER = getLogger("mock matrix")
class Matrix:
"""
A mock for an led matrix device
"""
_width = 32
_height = 8
_mode = "1"
def __init__(self):
_LOGGER.info("Created mock led matri... |
import string
def is_isin_valid(string_isin):
"""
Checks a given ISIN for validity
reference to: https://en.wikipedia.org/wiki/International_Securities_Identification_Number
reference to: http://code.activestate.com/recipes/498277-isin-validator/
:param string_isin: ISIN to be checked
:return:... |
def has_negatives(a):
"""
YOUR CODE HERE
"""
# Dictionary for values
vals = {}
# Iterate through numbers in a
for num in a:
# Check if the absolute value of num is in vals
if abs(num) in vals:
# Increment the value associated with abs(a)
vals[abs(num)... |
# coding=utf-8
"""
A module for a predefined set of basic predicates.
A predicate is a condition - They take two arguments and return either True
or False. The left side, `value`, is the value being compared currently, the
value the current set of rules is being applied to. The right side,
`comparable`, is the compar... |
from math import *
from Verification import *
def Base_Converter():
a = int(input('Nombre à convertir: '))
start = a
base = int(input("Base d\'entrée : "))
base2 = int(input("Base de sortie : "))
d = 0
if base <= 10 and base2 <= 10 and base != 0 and base2 != 0 and base != 1 and base2 != 1: # ... |
## 1. Booleans ##
cat = True
dog = False
print(type(cat))
## 2. Boolean Operators ##
print(cities)
first_alb = (cities[0] == "Albuquerque")
second_alb = (cities[1] == "Albuquerque")
last_element_index = len(cities) - 1
first_last = (cities[0] == cities[last_element_index])
## 3. Booleans with "Greater Than" ##
pri... |
## Imports
from core import *
from queue import *
import sys
## Variables initialization
gridDijskra = [[-1] * gridSizeX for _ in range(gridSizeY)]
queue = None
finish = False;
first = True
## Method to generate the queue for the Dijkstra algorithm
def dijkstragen(i,j):
global queue
queue = Queue(0)
queue... |
txt = input("Hello, and welcome to my world. My name is Walter. What is your age?: ")
ageCast = int(txt)
print(f"{type(ageCast)}") |
#Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
#If d(a) = b and d(b) = a, where a b, then a and b are an amicable pair and each of a and b are called amicable numbers.
#
#For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; t... |
# 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
# Find the sum of all numbers which are equal to the sum of the factorial of their digits.
# Note: as 1! = 1 and 2! = 2 are not sums they are not included.
import math
result = 0
for i in range (0,10000001):
sums = 0
for j in range (0,len(str(i)))... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# 地址:http://www.runoob.com/python/python-exercise-example6.html
def fib(n):
a, b = 1, 1
for i in range(n - 1):
a, b = b, a + b
# print(a)
return a
print(fib(15))
|
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# 地址:http: //www.runoob.com/python/python-exercise-example80.html
# 知识点:逆向思维
num = int(input("输入猴子的数目:"))
def fn(n):
if n == num:
return 4 * x # 最后剩的桃子的数目
else:
return fn(n + 1) * 5 / 4 + 1
x = 1
while 1:
count = 0
for i in range(1, n... |
string1 = 123.45
print("{:.4f}".format(string1))
# 123.4500
# Python 语句是“{: 数字的格式}.format(要转换格式的数字)”
print("{:6>d}".format(100))
#执行结果
# (空格)(空格)(空格)100
date_demo = [
"2021-03-18",
"21-3-18",
"2021-12-21",
"2021-3-8",
"21-3-1",
]
for dd in date_demo:
# 拆分日期
year, month, day = dd.split('... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Content:even odd
# 地址:http: //www.runoob.com/python/python-exercise-example76.html
def even(n):
sum = 0.0
for i in range(2, n + 1, 2):
sum += 1.0 / i
return sum
def odd(n):
sum = 0.0
for i in range(1, n + 1, 2):
sum += 1.0 / i
... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# 地址:http: //www.runoob.com/python/python-exercise-example78.html
# if __name__ == "__main__":
# person = {"li": 18, "wang": 50, "zhang": 20, "sun": 22}
# m = "li"
# for key in person.keys():
# if person[m] < person[key]:
# m = key
# pr... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Content:逆序输出
# 地址:http: //www.runoob.com/python/python-exercise-example29.html
# num = list(input("输入一个最多5位的数字:"))
num = list("12345")
print("num的位数为:{}".format(len(num)))
num.reverse()
print("逆序输出为:", end=" ")
for i in range(len(num)):
print(num[i], end="")
|
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# 地址:http: //www.runoob.com/python/python-exercise-example99.html
if __name__ == "__main__":
import string
fp = open("test1.txt")
a = fp.read()
fp.close()
fp = open("test2.txt")
b = fp.read()
fp.close()
fp = open("test3.txt", "w")
l =... |
import math
def digits_sum():
two_pow = str(int(math.pow(2, 1000)))
sum = 0
for i in two_pow:
sum += int(i)
print(sum)
if __name__ == '__main__':
digits_sum() |
import math
def findlargestprime():
current = 600851475143
sqruted = int(math.sqrt(current))
retVal = 0
for i in range(2, sqruted):
if current % i == 0:
retVal = i
while (current % i) == 0:
current /= i
if current < sqruted:
break
... |
''' Emily Armstrong
CSC 383
Final Project: Maze Game
The player is trying to find his/her around Ireland through a simple maze.
In order to win, he/she must collect the 3 pints of Guinness scattered
across the maze and head to the exit. The player only has 40 seconds to do so.
If the timer hits 0 before this, the... |
import urllib3
from bs4 import BeautifulSoup
http = urllib3.PoolManager()
# specify the url
quote_page = 'https://fivethirtyeight.com/features/should-travelers-avoid-flying-airlines-that-have-had-crashes-in-the-past/'
# query the website and return the html to the variable ‘page’
page = http.request('POST', quote_pa... |
import numpy as np
x = np.array([[1,2],[3,4]], dtype=np.float64)
y = np.array([[5,6],[7,8]], dtype=np.float64)
print x + y
print np.add(x, y)
print x - y
print np.subtract(x, y)
print x * y
print np.multiply(x, y)
print x / y
print np.divide(x, y)
print np.sqrt(x)
|
#1.1
#Implement an algorithm to determine if a string has all unique characters. what if you cannot use additional data structures?
def is_unique(input_str):
set_input_str = set([i for i in input_str])
if len(set_input_str) == len(input_str):
return True
return False
print(is_unique('abcd'))
#True
print(is_unique... |
class Reverse:
def __init__(self , Texto):
self.txt = Texto
self.res = ""
self.cifradoAnterior = ""
def cifra(self,txtnew):
self.cifradoAnterior = self.res
self.res = txtnew[::-1]
return self.res
def front(self ,caracter):
self.cifradoAnterior = se... |
"""動的計画法に使用するRooted Binary Treeのpython実装。
このツリーでは個々のList要素に対して拾う(左側と呼称)-拾わない(右側と呼称)と
決定した場合についての組み合わせをBinary Treeとして再帰的に表現する。
当然、対象のList要素を拾った場合に重量オーバーになる場合はそれ以上の左側の評価は
無駄なので、拾わない(右側)場合のツリーのみを評価対象として再帰を続けていく。
一度導出したツリーの構造が他の部分でも導出されることが十分に予想されるので
max_value_fastでは使う/使わないにかかわらず一度導出したツリー構造をキャッシュすることで
高... |
"""ナップサック問題で使用するItemクラスとそれにまつわる関数の定義"""
class Item(object):
"""ナップサックに詰める対象の品物"""
def __init__(self, n, v, w):
"""初期化。weightについては割り算の分母になるのと質量なので0以下の値は入れない"""
self.name = n
self.value = v
self.weight = w
self.density = v/w
@property
def weight(self):
ret... |
def isPrime(target):
"""簡単な素数判定。素数ならTrue、素数でなければFalseを返す"""
for n in range(2, target):
if target%n == 0:
return False
return True
#リスト内包(単純な演算)
simple = [x**2 for x in range(1, 6)]
print(simple)
#リスト内包(条件によるデータ抽出:素数の2乗をリストに抽出)
onlyPrime = [x**2 for x in range(2, 11) if isPrime(x)]
prin... |
"""グラフ最適化問題を解くためのノードなどの基本構造を定義する"""
class Node(object):
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
class Edge(object):
def __init__(self, src, dest):
"""srcとdestはどちらもNodeであるものとする"""
self.src = src
self.dest = dest
de... |
"""ランダムウォークに登場する酔っ払いを表すオブジェクト"""
import random
class Drunk(object):
def __init__(self, name = None):
self.name = name
def __str__(self):
if self.name != None:
return self.name
return 'Anonymous'
class UsualDrunk(Drunk):
def take_step(self):
step_choices = [(0,1),(0,-1),(1,0),(-1,0)]
... |
# Przykład prostej funckji
def simple_function():
print('Hello world!')
print('Wikipedia')
simple_function()
# Instrukcja return
def myfunction():
return 3+3
print(myfunction())
# Argumenty
def add(x, y):
return x + y
print(add(2, 3))
# Docstring
def my_function():
"""Dokumentacja funkcji""... |
'''
This file contains various functions to create game menu buttons and text.
'''
import pygame, sys, Game
from pygame.locals import *
pygame.init()
testRed = (255,0,0)
baseRed = (200,0,0)
black = (0,0,0)
#The main surface for the menu
mainSurface = pygame.display.set_mode ((800, 860), 0, 32)
#Fun... |
import sys
import random
score = 0
def input_words():
sentence_input = input("Please, input your sentence: ")
return [sentence_input.split(), sentence_input]
def play_again():
play_again=input("Do you want to play again (Yes/No): ").upper()
if (play_again.upper()=="YES"):
main()
else... |
import time
class Clock(object):
"""用来控制调用不至于过度频繁的计时器"""
def __init__(self, min_tick_interval=0.1):
self.last_tick = time.time()
self.interval = min_tick_interval
def tick(self):
now = time.time()
if now - self.last_tick < self.interval:
return False
e... |
#!/usr/bin/env python
"""A Python server that listens for specific requests made from the `chatListener` HTML's scripts, then acts on them.
"""
import time
from http.server import BaseHTTPRequestHandler
from urllib import parse
from pynput.keyboard import Key, Controller
import threading
# This will be call... |
def reformatting_str(s):
#take only the words in string, then join them together
#with only a single space between them
s = s.split()
news = " ".join(s)
#print
print(news.title())
s = input('Please type a random string: ')
n = 0
for e in s:
if e != " ":
n += 1
break
if n == 1... |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 8 08:59:46 2019
@author: lopez
"""
'''
while loop, find ma height
'''
v0 = 5 # meters per sec
g = 9.81
n = 2000
X= 1000 # for github use
# time steps
# time
import numpy as np
a_t = np.linspace(0,1,n) # we created an array
# computations
y = v0*a_... |
#!/usr/bin/python
# Each new term in the Fibonacci sequence is generated by adding the previous
# two terms. By starting with 1 and 2, the first 10 terms will be:
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
# By considering the terms in the Fibonacci sequence whose values do not exceed
# four million, find the sum of t... |
#!/usr/bin/python
# It was proposed by Christian Goldbach that every odd composite number can be
# written as the sum of a prime and twice a square.
# 9 = 7 + 2*1^2
# 15 = 7 + 2*2^2
# 21 = 3 + 2*3^2
# It turns out that the conjecture was false.
# What is the smallest odd composite that cannot be written as the sum ... |
#!/usr/bin/python
# The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes
# and concatenating them in any order the result will always be prime. For
# example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four
# primes, 792, represents the lowest sum for a set of four primes... |
#!/usr/bin/python
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a^2 + b^2 = c^2
# For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
for b in xrange(1, 1000):
a = (1000000.0 - 2000 *... |
#!/usr/bin/python
# The first two consecutive numbers to have two distinct prime factors are:
# 14 = 2 * 7
# 15 = 3 * 5
# The first three consecutive numbers to have three distinct prime factors are:
# 644 = 2^2 * 7 * 23
# 645 = 3 * 5 * 43
# 646 = 2 * 17 * 19.
# Find the first four consecutive integers to have four... |
RANK = 0
COUNTRY = 1
RATING = 2
BYEAR = 3
def open_file(filename):
#Returns a file_stream
try:
file_stream = open(filename, 'r')
return file_stream
except FileNotFoundError:
return None
def create_player_dict(file_stream):
#Returns a dict for player where each entry is a pl... |
####Conditions and Loopsclick to expand
#Marlon Aldair Arciniega sanchez
#Given: Two positive integers a and b (a<b<10000).
#Return: The sum of all odd integers from a through b, inclusively.
a=int(input("introduce a: "))
b=int(input("introduce b: "))
suma=0
for i in range (a, b+1):
if i%2==1: #elig... |
"""
dict = {}
dict = dict(arg)
dict = {}.fromkeys(arg)
copy clear
get
setdefault
items/iteritems,keys iterkeys values/itervalues
pop popitem
update
has_key
"""
class DictTest(object):
def __init__(self):
print "init"
def test(self):
print "test dict begin"
d = {"key": "value", "key1":"... |
################################# List Comprehension Applications ########################################
# Example - 1:
# Task- 1: Capitalize the names of the numeric variables in the "car_crashes" dataset and add "NUM" to the beginning.
# Note: Non-numeric names should also be upper case.
# Expecte... |
class DNAtoRNA (str):
"""
Converts DNA sequence to RNA sequence.
"""
def transcribe(self, DNAseq):
'''Convert Thymine to Uracil.'''
RNAseq = DNAseq.replace('T', 'U')
print (RNAseq)
def main():
DNAseq = input('Input DNA sequence:')
newSeq = DNAtoRNA()
newSeq.transcrib... |
# Mr Miyagi project
# Ask for user input and depending on the response, mr Miyagi will respond.
## prompt user for input
## Evaluate each input and print the appropriate responses
# Follow these rules:
# - every time you ask a question --> Mr. Miyagi responds with
# --> 'questions are wi... |
# If functions
# Control flow
# While loops are also part of control flow
# Syntax
# if <condition> :
# block of code
# elif <condition>
# block of code
# else:
# block of code
age = int(input('How old are you?'))
if age < 21 and age >= 18 :
print('Sorry you can vote but not drink.')
elif age >= 21:
... |
import os
import csv
budget_data = os.path.join("..", "PyBank", "Resources", "Budget_Data.csv")
total_mths = []
net_total = []
#Open budget_data
with open(budget_data, 'r')as fin_analysis:
#Read budget_data
csv_reader = csv.reader(fin_analysis, delimiter = ',')
csv_header = next(csv_reader)
for r... |
from blackjack.deck import Shoe
from blackjack.player import Player
from blackjack.dealer import Dealer
from blackjack.interface import*
class Game:
"""
Have the methods for going through a turn. When initialized it
runs through the game loop. It interacts with the deck, player and dealer
class, and ... |
import os
import time
suit_sym_str = "♥♠♦♣"
alt_sym_str = suit_sym_str[::-1]
def border_print():
"""Print border to seperate text."""
print(suit_sym_str * 10)
print(alt_sym_str * 10)
def start_game():
"""A way to introduce the game"""
os.system("clear")
print(suit_sym_str * 10)
print(a... |
"""
simulate a dice roll, return the result as a json object
this implementation takes the number of dice and the number of the sides
of the dice as a parameter
"""
from flask import Flask, jsonify, request
import random
app = Flask(__name__)
def _roll(num_dice, sides):
"""return the dice n times """... |
import os
import csv
import pandas as pd
csvpath = os.path.join("resources/budget_data.csv")
with open(csvpath,'r',newline='') as csv_file:
csv_reader = csv.DictReader(csv_file)
total_months = 0
total_amt = 0
previous_month = 0
differences = []
dates = []
for row in csv_reader:
if... |
print("Hola Mundo....Como estan!!")
a=50
b=5
print("Suma:", (a+b))
print("Resta:", (a-b))
print("Multiplicacion:", (a*b))
print("Division:", (a/b)) |
"""
=======================================
Receiver Operating Characteristic (ROC)
=======================================
Example of Receiver Operating Characteristic (ROC) metric to evaluate
classifier output quality.
ROC curves typically feature true positive rate on the Y axis, and false
positive rate on the X a... |
#Ask the user's name and greet them
name = input("What is your name?")
print("Hello, {}!".format(name))
#Ask the user for number of hours spent online for each of the past 7 days
for i in range(1, 8):
hours = input("How many hours did you spend online on day {}?".format(i))
print(hours)
|
# Ask user for login details and give them 3 tries
PASSWORD = "ekki-ekki-ekki"
for i in range(3):
guess = input("Password: ").strip().lower()
if guess == PASSWORD: # If correct
print("Correct, authorisation complete.")
break
else: #If incorrect
print("Incorrect")
else: #If incorrect 3... |
print("------- Loop #1 --------")
i = 1
while i <= 128:
print(i)
i *= 2
print("------- Loop #2 --------")
i = 6
while i <= 21:
print(i)
i += 3
print("------- Loop #3 --------")
i = 10
while i >= 1:
print(i)
i -= 1
print("------- Loop #4 --------")
i = 100
while i >= 0:
print(i)
... |
#Student lists
students_present = ["tommy", "dahlia", "manaia", "isaac", "jamila", "britt", "patrick", "jessika", "chantal", "rocio"]
students_absent = ["iliana", "olympia", "juan", "kelsey"]
#Print out students present:
for student in students_present:
print(student)
#Print number of students present
pr... |
#Print 3 times table
i = 1
while i <= 12:
print("3 x {} = {}".format(i, i * 3))
i += 1
|
#Names list
name_string = "Becky Steve Thomas Rachel Bob Tom Miguel Hone Anahera Wei-ling"
#Split the names into a list on spaces (default)
names_list = name_string.split()
print(names_list)
#Create a string with items on new lines (you don't need \n)
item_string = """water
computer
school
network
hammer
... |
word = input("Enter a word: ")
# Changing to lower case
word = word.lower()
print(word)
# Strip spaces and print
word = word.strip()
print(word)
# Change to title case and print
word = word.title()
print(word)
# Change to upper case and print
word = word.upper()
print(word)
|
#Set up the variable that will run the loop
response = "no"
#Repeat loop until we are there!
while response != "yes":
response = input("Are we there yet?")
print("Yay!")
|
score = 30
#Ask the next question
answer = input("What is the name of Saturn's largest moon?")
answer = answer.strip().lower()
#Check if answer is correct and add or remove points
if answer == "titan":
print("That is correct, you get 10 points!")
score += 10
elif answer == "ganymede":
print("You're ... |
print("A computer programmer can earn 6 figures!")
print('She looked up and yelled "Watch out! You\'ll break it!"')
number = input("What's your favorite number?")
print("Your favorite number is: {}".format(number))
|
#Force the user to enter a valid number
while True:
try:
height = float(input("Enter your height in metres: "))
break
except ValueError:
print("Please enter a valid height in metres e.g. 1.65")
|
from abc import ABC, abstractmethod
from library.Node import Node
class World(ABC):
def __init__(self, name, initialState = None):
self.name = name
if initialState is None:
self.state = {}
else:
self.state = initialState
self.nodes = {... |
# import pygame library
import pygame
# import our Paddle class
from paddle import Paddle
from ball import Ball
from brick import Brick
pygame.init()
# define colors used
WHITE = (255, 255, 255)
DARKBLUE = (36, 90, 190)
LIGHTBLUE = (0, 176, 240)
RED = (255, 0, 0)
ORANGE = (255, 100, 0)
YELLOW = (255, 255, 0)
# set va... |
import json
from pprint import pprint
from collections import Counter
import os
input_filename = 'meeting.txt'
output_filename1 = 'output1.txt'
output_filename2 = 'output2.txt'
class ZoomChallenge():
def __init__(self, input_filename, output_filename1, output_filename2):
self.input_filename = input_file... |
class Problem6(object):
def square_difference(self):
answer = 0
for x in self.numbers:
answer += x
answer = answer**2
for x in self.numbers:
answer -= x**2
return answer
def __init__(self, numbers):
self.numbers = numbers
|
class Problem5(object):
def smallest_multiples(self):
answer = 0
# First value that is divisible by 20 and 19.
result = 380
while answer == 0:
if self.divisible(result):
answer = result
# Minimum increment given data set.
result ... |
from string import ascii_uppercase as letters
from string import digits
import random
def getRandomName():
random.seed()
name = ""
for i in range(0, 2):
name += random.choice(letters)
for i in range(0, 3):
name += random.choice(digits)
return name
class Robot(object):
def __in... |
import math
class ComplexNumber(object):
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
def __eq__(self, other):
return self.real == other.real and self.imaginary == other.imaginary
def __add__(self, other):
return ComplexNumber(self.real... |
class Allergies(object):
allergies = [
'eggs',
'peanuts',
'shellfish',
'strawberries',
'tomatoes',
'chocolate',
'pollen',
'cats'
]
def __init__(self, score):
self.lst = [allergen for i, allergen in enumerate(self.allergies) if (score &... |
#!/usr/bin/env python3
import sys
import os
import filecmp
OUTPUT_DIR = "recv"
MAX_BYTES = 1000
try:
file_name = sys.argv[1]
except IndexError as e:
print("You must input a filename to copy as the first argument")
sys.exit()
# check if the recv directory exists, create it if it does not
if not os.path.e... |
from time import strftime
import sqlite3
conn = sqlite3.connect('events.db')
c = conn.cursor()
def create_table():
c.execute('CREATE TABLE IF NOT EXISTS eventsToPlot(event_name TEXT, datestamp TEXT, event_description TEXT)')
#user_first_name = raw_input("What is your first name?")
create_table()
def welcome():
... |
#!/usr/bin/env python
################################################################################
#
# Author: Andrew Peterson
#
# Class: ECE2500
#
# Description: This python file creates a terminal game of minesweeper
#
################################################################################
import... |
import csv
import matplotlib.pyplot as plt
import random
# load irist dataset and put it into test set and training set
def loadDataset(Trainingfilename,Testfilename, trainingSet=[], testSet=[]):
##trainset section
with open(Trainingfilename, 'rt') as csvfile:
next(csvfile)
lines = csv.reade... |
"""
Module containing the k-armed bandit problem
Complete the code wherever TODO is written.
Do not forget the documentation for every class and method!
We expect all classes to follow the Bandit abstract object formalism.
"""
# -*- coding: utf-8 -*-
import numpy as np
class Bandit(object):
"""
Abstract concep... |
class Node():
def __init__(self,d, n=None):
self.data = d
self.next = n
def get_next(self):
return self.next
def set_next(self, n):
self.next = n #set next node
def get_data(self):
return self.data
def set_data(self,d):
self.data = d
class Linkedl... |
__author__ = 'Karl Tiirik'
import datetime
class EstPerson(object):
def __init__(self, gender, birth_date, nth_baby):
self.gender = gender
self.birth_date = birth_date
self.code = calc_code(gender, birth_date, nth_baby)
def __str__(self):
return "%s, %s, %s" % (self.code, self... |
""" To check if password is of length 10, one digit, one upper case and one lower case letter."""
def checkPassword(data: str) -> bool:
upper_fl = False
lower_fl = False
digit_fl = False
if len(data) < 10:
return False
else:
for c in data:
if c.isupper():
... |
from itertools import combinations
def primes_sieve(limit, primality=None, smallest=2):
if primality is None:
primality = [True] * limit # Initialize the primality list
primality[0] = primality[1] = False
for (i, isprime) in enumerate(primality):
if isprime:
... |
def myMap(function, iterable):
result = []
for i in iterable:
result.append(function(i))
return result
def myfunc(a):
return len(a)
x = myMap(myfunc, ('apple', 'banana', 'cherry'))
print(x) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.