text stringlengths 37 1.41M |
|---|
p = collections.Counter(x)
print (p)
count_of_sum = sum(p.values())
for k,v in p.items():
print("The frequency of number" + str(k) + "is" + str(float(v)/count_of_sum))
plt.hist(testlist, histtype="bar")
plt.show()
plt.boxplot(testlist)
plt.show()
plt.figure()
x = np.random.normal(size=1000)
graph1 = stats.probplot(test_data, dist="norm", plot=plt)
plt.show() #this will generate the first graph
plt.figure()
x = np.random.uniform(size=1000)
graph2 = stats.probplot(test_data2, dist="norm", plot=plt)
plt.show() #this will generate the second graph |
# 最小公倍数
def lcm(x, y):
# 获取较大的数
if x > y:
bigger = x
else:
bigger = y
while (True):
if (bigger % x == 0) and (bigger % y == 0):
result = bigger
break
else:
bigger += 1
return result
if __name__ == '__main__':
print(lcm(6, 8))
|
# 替换列表中所有的 3 为 3a
if __name__ == '__main__':
nums = ['harden', 'lampard', 3, 34, 45, 56, 76, 3, 3, 876, 999]
for i in range(nums.count(3)):
ele_index = nums.index(3)
nums[ele_index] = '3a'
print(nums)
|
class Hand():
def __init__(self):
self._cards = []
self.__index = 0
@property
def cards(self):
return self._cards
@cards.setter
def cards(self, value):
self._cards = value
@property
def count(self):
return len(self.cards)
def add_card(self, card):
self.cards.append(card)
def remove_card(self, card):
self.cards.remove(card)
def is_empty(self):
if self.cards == []:
return True
return False
# Iterator functionality
# You can now just loop over whats in your hand
def __iter__(self):
return self
def __next__(self):
try:
result = self.cards[self.__index]
except IndexError:
self.__index = 0
raise StopIteration
self.__index += 1
return result
def __str__(self):
s = '<'
for card in self.cards:
s += ' ' + str(card)
s += ' >'
return s
|
from .UnitConversion import UnitConversion
# Above from "." = current directory
try:
user_feet = float(input("Please enter the number of feet (0 or greater)"))
user_inches = float(input("Please enter the number of inches (0 or greater)"))
# This could ask for both and split on a space but with a console better to split it
except ValueError:
print("You must enter a numeric value for feet & inches")
user_feet = 0.0
user_inches = 0.0
uc = UnitConversion(user_feet, user_inches)
uc.set_all()
print(uc)
|
#算法思想
#将待插入元素与其前一个元素进行比较,若小于,
# 则将前一个元素后移一位,在将带插入元素与前前一位进行比较,
# 若小于,则将前前一位往后移,如此操作直到遇到小于待插入元素的位置,
# 插入到该位后一位(此位已经在上一步后移了)
def Insert_Sort(arr):
for i in range(1,len(arr)):
key = arr[i]
a = i#使用一个变量a来记录数组下标
while key<arr[a-1]:#这时的第一次循环key是之前排好序的数组新加入的一个未排序的数,
#先将key与他前面的元素arr[a-1],如果新插入的这个元素比最后一个元素小
arr[a] = arr[a-1]#将这个元素往后移动一个位置
a = a-1#将数组下标再往前移动一个位置,继续比较新插入的元素与倒数第二个元素之间的
#的大小关系
if a-1<0:#直到比较到第一个元素跳出while循环
break
arr[a] = key#将新插入的元素放在指定的位置上
l=[89,54,65,3,21,52,1,45,55]
Insert_Sort(l)
print(l)
|
from typing import *
from abc import *
from decimal import *
import functools, itertools
class Product:
def __init__(self, name: 'str', price: 'Decimal' = Decimal("0.00")) -> 'None':
self.__name = name
self.__price = price
@property
def name(self) -> 'str':
return self.__name
@property
def price(self) -> 'Decimal':
return self.__price
def __str__(self) -> 'str':
return "%s(name=%s, price=%s)" % (
type(self).__name__,
self.name,
self.price
)
class Book(Product):
def __init__(self, price: 'Decimal' = Decimal("0.00"), isbn: 'str' = "Not Provided", title: 'str' = "No Title", name: 'str' = "") -> 'None':
super().__init__(name, price)
self.__isbn = isbn
self.__title = title
self.__name = name
@property
def isbn(self) -> 'str':
return self.__isbn
@property
def title(self) -> 'str':
return self.__title
@property
def name(self) -> 'str':
return self.__name
def __str__(self) -> 'str':
return "%s(isbn=%s, title=%s, name=%s, price=%s)" % (
type(self).__name__,
self.isbn,
self.title,
self.name,
self.price
)
class Item:
def __init__(self, book: 'Book', quantity: 'int') -> 'None':
self.__book = book
self.__quantity = quantity
@property
def book(self) -> 'Book':
return self.__book
@property
def quantity(self) -> 'int':
return self.__quantity
def __str__(self) -> 'str':
return "%s(book=%s, quantity=%s)" % (
type(self).__name__,
self.book,
self.quantity
)
class Customer:
def __init__(self, name: 'str') -> 'None':
self.__name = name
@property
def name(self) -> 'str':
return self.__name
def __str__(self) -> 'str':
return "%s(name=%s)" % (
type(self).__name__,
self.name
)
class Order:
def __init__(self, customer: 'Customer', items: 'List[Item]') -> 'None':
self.__customer = customer
self.__items = items
@property
def customer(self) -> 'Customer':
return self.__customer
@property
def items(self) -> 'List[Item]':
return self.__items
def __str__(self) -> 'str':
return "%s(customer=%s)" % (
type(self).__name__,
self.customer
)
class BookStore:
def __init__(self, books: 'List[Book]', customers: 'List[Customer]') -> 'None':
self.__books = books
self.__customers = customers
@property
def books(self) -> 'List[Book]':
return self.__books
@property
def customers(self) -> 'List[Customer]':
return self.__customers
def __str__(self) -> 'str':
return "%s()" % type(self).__name__ |
def age_checker(age):
classifications = ["U", "PG", "12a", "15", "18"]
if age > 17:
print("These are the movies you can watch:", classifications)
elif 14 < age < 18:
print("These are the movies you can watch:", classifications[0:4])
elif 11 < age < 15:
print("These are the movies you can watch:", classifications[0:3])
else:
print("These are the movies you can watch:", classifications[0:2])
|
student_record = {"name": "Ibrahim",
"DOB": "01/01/1996",
"Country of Birth": "Saudi Arabia",
"Employee ID": "12345",
"Comment": "He likes football"}
def record_printer():
for keys in student_record:
print(keys, ":", student_record.get(keys))
# print()
#
# for keys, value in student_record.items():
# print(keys, ":", value)
#
# print()
#
# for keys in student_record:
# print(keys, ':', student_record[keys])
|
import turtle
def draw_square():
window = turtle.Screen()
window.bgcolor ("grey")
abcd = turtle. Turtle()
abcd.forward(200)
abcd.right(90)
abcd.forward(200)
abcd.right(90)
abcd.forward(200)
abcd.right(90)
abcd.forward(200)
abcd.right(90)
turtle.color ("black","green")
turtle.begin_fill()
turtle.circle (100)
turtle.end_fill()
window.exitonclick()
draw_square()
|
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 3 20:32:26 2021
Program to demonstrate Encapsulation (Private Member)
@author: Lokesh
"""
class Person:
def __init__(self):
self.name = 'Manjula'
self.__lastname = 'Dube'
def PrintName(self):
return self.name +' ' + self.__lastname
#Outside class
P = Person()
print(P.name)
print(P.PrintName())
print(P.__lastname)
#AttributeError: 'Person' object has no attribute '__lastname'
|
d = { 'a': 1, 'b': 2, 'c': 3 }
print d.items()
print [(v, k) for k, v in d.iteritems()] |
num = input("Please give the Integer : ")
numbr = num
if num < 0:
isNeg = True
num = abs(num)
else:
isNeg = False
result = ''
if num == 0:
result = '0'
while num > 2:
result = str(num%2) + result
num = num/2
if num <= 2:
result = str(num/2)+ str(num%2) + result
if isNeg:
result = '-' + result
#result = int(result)
print("Binary number of Integer "+ str(numbr) +" is "+ result)
'''
num = 100
if num < 0:
isNeg = True
num = abs(num)
else:
isNeg = False
result = ''
if num == 0:
result = '0'
while num > 2:
result = str(num%2) + result
num = num/2
if num <= 2:
result = str(num/2)+ str(num%2) + result
if isNeg:
result = '-' + result
print result
'''
|
import math
X = 2.4
print math.ceil(X)
#Return the ceiling of x as a float, the smallest integer value greater than or equal to x.
Y= -1
print math.copysign(X,Y)
#Return x with the sign of y. On a platform that supports signed zeros, copysign(1.0, -0.0) returns -1.0.
x = -2.5999999999999
print math.fabs(x)
#Return the absolute value of x.
x =10
print math.factorial(x)
#Return x factorial. Raises ValueError if x is not integral or is negative.
x=2.5
print math.floor(x)
#Return the floor of x as a float, the largest integer value less than or equal to x.
x = 3.6
y = -2.2
print math.fmod(x, y)
#Return fmod(x, y), as defined by the platform C library. Note that the Python expression x % y may not return the same result.
#The intent of the C standard is that fmod(x, y) be exactly (mathematically; to infinite precision) equal to x - n*y for some integer n
#such that the result has the same sign as x and magnitude less than abs(y).
#Python’s x % y returns a result with the sign of y instead, and may not be exactly computable for float arguments.
#For example, fmod(-1e-100, 1e100) is -1e-100, but the result of Python’s -1e-100 % 1e100 is 1e100-1e-100, which cannot be represented exactly as a float, and
#rounds to the surprising 1e100.
#For this reason, function fmod() is generally preferred when working with floats, while Python’s x % y is preferred when working with integers.
x = 2.5
print math.frexp(x)
#Return the mantissa and exponent of x as the pair (m, e). m is a float and e is an integer such that x == m * 2**e exactly.
#If x is zero, returns (0.0, 0), otherwise 0.5 <= abs(m) < 1. This is used to “pick apart” the internal representation of a float in a portable way.
iterable = [1,2.4,5.333,4,5.6]
print math.fsum(iterable)
#Return an accurate floating point sum of values in the iterable. Avoids loss of precision by tracking multiple intermediate partial sums:
'''
>>> sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
0.9999999999999999
>>> fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
1.0
The algorithm’s accuracy depends on IEEE-754 arithmetic guarantees and the typical case where the rounding mode is half-even.
On some non-Windows builds, the underlying C library uses extended precision addition and may occasionally double-round an intermediate sum
causing it to be off in its least significant bit.
'''
print "ok"
#x = pow(10,pow(10,100))
x = 111111111111111111111111111111111111
print math.isinf(x)
#Check if the float x is positive or negative infinity.
x = -0.2
print math.isnan(x)
#Check if the float x is a NaN (not a number). For more information on NaNs, see the IEEE 754 standards.
print "ok"
x = 3
i = 2
print 'x:',3,'i:',i
print math.ldexp(x, i)
#Return x * (2**i). This is essentially the inverse of function frexp().
print "ok"
x = 4.5
a = math.modf(x)
print a
#Return the fractional and integer parts of x. Both results carry the sign of x and are floats.
x = 10
print math.trunc(x)
#Return the Real value x truncated to an Integral (usually a long integer). Uses the __trunc__ method.
#Note that frexp() and modf() have a different call/return pattern than their C equivalents: they take a single argument and return a pair of values,
#rather than returning their second return value through an ‘output parameter’ (there is no such thing in Python).
#For the ceil(), floor(), and modf() functions, note that all floating-point numbers of sufficiently large magnitude are exact integers.
#Python floats typically carry no more than 53 bits of precision (the same as the platform C double type),
#in which case any float x with abs(x) >= 2**52 necessarily has no fractional bits.
'''
Power and logarithmic functions
'''
math.exp(x)
#Return e**x.
math.expm1(x)
#Return e**x - 1. For small floats x, the subtraction in exp(x) - 1 can result in a significant loss of precision; the expm1() function provides a way to compute this quantity to full precision:
'''
>>>
>>> from math import exp, expm1
>>> exp(1e-5) - 1 # gives result accurate to 11 places
1.0000050000069649e-05
>>> expm1(1e-5) # result accurate to full precision
1.0000050000166668e-05
'''
x = 10
#math.log(x[, base])
math.log(x,2)
#With one argument, return the natural logarithm of x (to base e).
#With two arguments, return the logarithm of x to the given base, calculated as log(x)/log(base).
math.log1p(x)
#Return the natural logarithm of 1+x (base e). The result is calculated in a way which is accurate for x near zero.
math.log10(x)
#Return the base-10 logarithm of x. This is usually more accurate than log(x, 10).
math.pow(x, y)
#Return x raised to the power y. Exceptional cases follow Annex ‘F’ of the C99 standard as far as possible. In particular, pow(1.0, x) and pow(x, 0.0) always return 1.0,
#even when x is a zero or a NaN. If both x and y are finite, x is negative, and y is not an integer then pow(x, y) is undefined, and raises ValueError.
#Unlike the built-in ** operator, math.pow() converts both its arguments to type float. Use ** or the built-in pow() function for computing exact integer powers.
math.sqrt(x)
#Return the square root of x.
'''
Trigonometric functions
'''
x = math.degrees(60)
print math.cos(x)
#Return the arc cosine of x, in radians.
x = 2*math.pi
math.asin(math.pi)
#Return the arc sine of x, in radians.
math.atan(x)
#Return the arc tangent of x, in radians.
math.atan2(y, x)
#Return atan(y / x), in radians. The result is between -pi and pi. The vector in the plane from the origin to point (x, y) makes this angle with the positive X axis. The point of atan2() is that the signs of both inputs are known to it, so it can compute the correct quadrant for the angle. For example, atan(1) and atan2(1, 1) are both pi/4, but atan2(-1, -1) is -3*pi/4.
math.cos(x)
#Return the cosine of x radians.
math.hypot(x, y)
#Return the Euclidean norm, sqrt(x*x + y*y). This is the length of the vector from the origin to point (x, y).
math.sin(x)
#Return the sine of x radians.
math.tan(x)
#Return the tangent of x radians.
'''
Angular conversion
'''
math.degrees(x)
#Convert angle x from radians to degrees.
math.radians(x)
#Convert angle x from degrees to radians.
'''
Constants
'''
math.pi
#The mathematical constant π = 3.141592..., to available precision.
math.e
#The mathematical constant e = 2.718281..., to available precision.
|
from random import choice
from math import sqrt
# Задание-1:
# Напишите функцию, возвращающую ряд Фибоначчи с n-элемента до m-элемента.
# Первыми элементами ряда считать цифры 1 1
def fibonacci(n, m):
a = 0
b = 1
c = []
# like a dynamic prog
for __ in range(m):
a, b = b, a + b
c.append(a)
return c[n:]
# Задача-2:
# Напишите функцию, сортирующую принимаемый список по возрастанию.
# Для сортировки используйте любой алгоритм (например пузырьковый).
# Для решения данной задачи нельзя использовать встроенную функцию и метод sort()
def sort_to_max(origin_list):
# Reference: http://www.itmathrepetitor.ru/sortirovka-khoara-bystraya-sortirovka/
if len(origin_list) <= 1:
return origin_list
else:
seed = choice(origin_list)
l_nums = [n for n in origin_list if n < seed]
e_nums = [seed] * origin_list.count(seed)
b_nums = [n for n in origin_list if n > seed]
return sort_to_max(l_nums) + e_nums + sort_to_max(b_nums)
# Задача-3:
# Напишите собственную реализацию стандартной функции filter.
# Разумеется, внутри нельзя использовать саму функцию filter.
def my_filter(_func, _list):
ret = []
for i in _list:
if _func(i):
ret.append(i)
return ret
# Задача-4:
# Даны четыре точки А1(х1, у1), А2(x2 ,у2), А3(x3 , у3), А4(х4, у4).
# Определить, будут ли они вершинами параллелограмма.
def isparallelogramm(A: (int, int), B: (int, int), C: (int, int), D: (int, int)):
# -------B===============C--
# -----/---------------/----
# ----/---------------/-----
# ---/---------------/------
# -A===============D--------
AB = sqrt((B[0] - A[0])**2 + (B[1] - A[1])**2)
DC = sqrt((C[0] - D[0]) ** 2 + (C[1] - D[1]) ** 2)
AD = sqrt((D[0] - A[0]) ** 2 + (D[1] - A[1]) ** 2)
BC = sqrt((C[0] - B[0]) ** 2 + (C[1] - B[1]) ** 2)
return True if AB == DC and AD == BC else False
def main():
print(fibonacci(4, 32))
print(sort_to_max([2, 10, -12, 2.5, 20, -11, 4, 4, 0]))
print(my_filter(lambda x: x % 3 == 0, list(range(32))))
print(isparallelogramm((2, 3), (4, 11), (9, 11), (7, 3)))
print(isparallelogramm((2, 3), (4, 0), (9, 11), (7, 3)))
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\n exit")
|
# Vigenere Cipher
import pyperclip
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def main():
# myMsg = 'Alan Mathison Turing was a British mathematician, logician, cryptanalyst, and computer scientist.'
myMsg = str(input("Enter your message:\n"))
myKey = str(input("Enter the string key: "))
myMode = str(input("\n[E]ncrypt or [D]ecrypt: "))
if myMode.upper() == "E":
translated = encryptMessage(myKey, myMsg)
print("\nEncrypted Message:\n")
elif myMode.upper() == "D":
translated = decryptMessage(myKey, myMsg)
print("\nDecrypted Message:\n")
print(translated)
pyperclip.copy(translated)
print("\nThe Message has been copied to Clipboard...")
def encryptMessage(key, msg):
return translateMessage(key, msg, "encrypt")
def decryptMessage(key, msg):
return translateMessage(key, msg, "decrypt")
def translateMessage(key, msg, mode):
translated = []
keyIndex = 0
key = key.upper()
for symbol in msg:
num = LETTERS.find(symbol.upper())
if num != -1: # -1 means symbol.upper() was not found in LETTERS
if mode == "encrypt":
num += LETTERS.find(key[keyIndex]) # Add if encrypting
elif mode == "decrypt":
num -= LETTERS.find(key[keyIndex]) # Sub if encrypting
num %= len(LETTERS) # Handle any wraparound
# Add the encrypted/decrypted symbol to the end of translated:
if symbol.isupper():
translated.append(LETTERS[num])
elif symbol.islower():
translated.append(LETTERS[num].lower())
keyIndex += 1 # Move to next letter in the key
if keyIndex == len(key):
keyIndex = 0
else:
# Append symbol without translating
translated.append(symbol)
return ''.join(translated)
if __name__ == '__main__':
main()
|
# Testing Transposition Cipher
import sys, random, TranspositionEncryption, TranspositionDecryption
def main():
ask = int(input("How many times to run the code? "))
random.seed(42) # Set the random "seed" to a static value
for i in range(ask):
# Generate random message to test
# The message will have a random length
msg = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" * random.randint(4, 40)
# Convert the message string to a list to shuffle it
msg = list(msg)
random.shuffle(msg) # Shuffle is used with lists
msg = ''.join(msg) # Convert the lists back to string
print(f"Testing #{i+1}: '{msg[0:20]}'")
# Check all possible keys for each message
for key in range(1, ask):
encrypted = TranspositionEncryption.encryptMessage(key, msg)
decrypted = TranspositionDecryption.decryptMessage(key, encrypted)
# If the decryption doesnt match the original message, display an error message and quit
if msg != decrypted:
print(f"Mismatch with key {key} and message {msg}\n\n")
print("Decrypted as: " + decrypted)
sys.exit()
print("Transposition Cipher Test Passed !")
if __name__ == '__main__':
main()
|
## SJS 5/22/14. Feel free to email stephanie.spielman@gmail.com with questions!
# Script to introduce the biopython module and regular expression usage.
# import the sequence input-ouput functionality from the Biopython module
from Bio import SeqIO
# import the regular expression python module
import re
# This file contains several histamine receptor (HRH) sequences in fasta format
file_name = 'HRH.fasta'
# This line uses biopython to read in a sequence file in fasta format.
# The command will read in a file containing multiple sequences.
# The variable "records" we create here will contain a list of "Sequence Records," which biopython creates for us automatically
records = list(SeqIO.parse(file_name, 'fasta'))
## NOTE:
# Other ways to use SeqIO:
# 1. Read in a file of sequences in phylip format: list(SeqIO.parse(file_name, 'phylip'))
# 2. Read in a fasta file containing a SINGLE sequence: SeqIO.read(file_name, 'fasta') . Because there is only a single sequence, there is no need to turn it into a list.
# We can obtain information from each sequence record stored in the "records" list we have created, using a for loop.
# The usual information you'll need are the sequence id, and the sequences themselves. They can be accessed by typing the name of the record (in this case, the loop variable "my_record"), and then .id or .seq .
print "\nHere are the records from HRH.fasta:"
for my_record in records:
print my_record.id #print the id
print my_record.seq #print the sequence
print #print a new line (for easier viewing!)
# Now we can use regular expressions to extract ONLY the NCBI part of each sequence id from our records, using the re module.
# Recall -
# \w = letter or digit
# \d = number
# . = wildcard! Represents (most) anything ever.
# If I actually want a period, I must "escape" the wildcard behavior by adding a backslash: \. is a real period.
# add + after your regular expression character to match one or more of them
# add + after your regular expression character to match 0 or more of them
# First, let's construct a regular expression for the entire id, and prove to ourselves that it works by printing.
# First, to prove the regular expression works
print "\nProving that my regular expression works"
for record in records:
find_id = re.search('\wP_\d+\.\d_HRH\d', record.id)
if find_id:
print find_id.group()
# Now!! We can capture the actual part of the id we are interested in, using parentheses inside the regular expression.
print "\nCapturing the interesting part of the id for future use"
for record in records:
find_id = re.search('(\wP_\d+\.\d)_HRH\d', record.id)
if find_id:
ncbi_id = find_id.group(1)
print ncbi_id
## NOTE: Often times, it is useful to have your regular expressions be as general as possible. Here's a more general version of the regular expression used above -
# For instance, NCBI ids might look like XP_389571 instead of XP_389571.1, so we might want flexibility allowing the ".1" at the end of the NCBI id to be optional. We can accomplish this using asterisks.
# HERE: \w+_\d+\.*\d*_.+
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math as m
import matplotlib.pyplot as plt
def rotate_points_2D(points, angle):
"""Rotate points using complex numbers"""
# Encode the rotation operation
z = complex(m.cos(angle), m.sin(angle))
points_rot = []
for point in points:
p_rotated = complex(*point)*z
points_rot.append([p_rotated.real, p_rotated.imag])
return points_rot
def main():
"""Rotate a box"""
box = [
[-1, -1],
[1, -1],
[1, 1],
[-1, 1],
[-1, -1],
]
fig, axs = plt.subplots(1, 1)
plt.xlim(-1.5, 1.5)
plt.ylim(-1.5, 1.5)
axs.set_aspect('equal')
for angle in range(0, 90, 2):
box_rotated = rotate_points_2D(box, m.radians(angle))
x = [p[0] for p in box_rotated]
y = [p[1] for p in box_rotated]
axs.plot(x, y, marker='o', color='blue')
plt.pause(0.1)
plt.show()
if __name__ == '__main__':
main()
|
class Spawner(object):
'''
Abstract base class for classes that can spawn and communicate between `MachineController` instances.
Each subclass should define a way to create and track `MachineController` instances, and to communicate
with them once they have started running.
'''
@property
def dz_time(self):
'''Current time as returned by time.time(). It may be real or simulated.'''
raise RuntimeError("Abstract Superclass")
@staticmethod
def from_spawner_json(self, spawner_config):
'''
Build a new `Spawner` instance from spawner configuration json.
:param object j: A python object, deserialized from spawner json
:return: A spawner instance, configured from ``j``.
:rtype: `Spawner`
'''
raise RuntimeError("Abstract Superclass")
def mode(self):
'''
This spawner's mode.
:return: The mode in which this spawner runs.
:rtype: str
'''
raise RuntimeError("Abstract Superclass")
def create_machine(self, machine_config):
'''
Start up a new machine and run a `MachineController` instance on it.
:param object machine_config: A machine configuration object.
:return: The id of the new `MachineController`
:rtype: str
'''
raise RuntimeError("Abstract Superclass")
def create_machines(self, machine_configs):
'''
Start up new machines and run `MachineController` instances on them.
:param list machine_configs: A list of machine configuration objects.
:return: The list of ids of the new `MachineController` in the same order as the matching
:rtype: list[str]
'''
raise RuntimeError("Abstract Superclass")
def map_domain_to_ip(self, domain_name, ip_address):
'''
Point a domain name at an ip address.
:param str domain_name: The domain name
:param str ip_address: The ip address
'''
raise RuntimeError("class {} does not implement map_domain_to_ip".format(self.__class__.__name__))
def sleep_ms(self, ms):
'''
Return an awaitable that sleeps for some number of milliseconds.
Note that the awaitable is different from that returned by asyncio.sleep in that when DistZero is in simulated
mode, time is entirely simulated, and the awaitable may resolve in much less than ms milliseconds.
'''
raise RuntimeError("Abstract Superclass")
|
# Copyright © 2019 Adobe, Inc.
# Author: Miguel Sousa
"""
Generates a simple text file for testing emoji characters.
"""
import argparse
import os
import sys
from generate_test_html import (
append_to_file,
parse_emoji_test_file,
CHANGES_INPUT_PATH,
TEST_DIR,
TEST_INPUT_PATH,
)
TEST_OUTPUT_FILENAME = 'test.txt'
CHANGES_OUTPUT_FILENAME = 'test-changes.txt'
def positive_int(int_str):
try:
num_items = int(int_str)
except ValueError:
raise argparse.ArgumentTypeError(
"'{}' is not an integer.".format(int_str))
if num_items < 1:
raise argparse.ArgumentTypeError('Number of emoji per line must be 1 '
'or more.')
return num_items
def main(args=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
'-e',
'--emoji-per-line',
help=('split the single line of emoji characters/sequences by '
'introducing line breaks'),
metavar='INTEGER',
type=positive_int,
)
parser.add_argument(
'-s',
'--space',
help=('add space character between emoji characters/sequences'),
action='store_true'
)
parser.add_argument(
'-c',
'--changes',
help="generates '{}' instead of '{}'".format(
CHANGES_OUTPUT_FILENAME, TEST_OUTPUT_FILENAME),
action='store_true',
)
opts = parser.parse_args(args)
if opts.changes:
emoji_input_path = CHANGES_INPUT_PATH
emoji_output_filename = CHANGES_OUTPUT_FILENAME
else:
emoji_input_path = TEST_INPUT_PATH
emoji_output_filename = TEST_OUTPUT_FILENAME
# collect the list of codepoints
cdpts_list = parse_emoji_test_file(emoji_input_path)
# start a new file (avoids appending to an existing file)
test_file_path = os.path.join(TEST_DIR, '..', emoji_output_filename)
open(test_file_path, 'w').close()
# begin the file with the BOM and use utf-16-le encoding
# (to make Adobe Illustrator happy)
append_to_file(test_file_path, '\uFEFF', 'utf-16-le')
emoji_list = []
for i, cps in enumerate(cdpts_list, 1):
emoji = ''.join(chr(int(cp, 16)) for cp in cps)
emoji_list.append(emoji)
if opts.space:
space = ' '
else:
space = ''
if opts.emoji_per_line:
emoji_stream = ''
for i, emoji_group in enumerate(emoji_list, 1):
emoji_sep = '\r' if i % opts.emoji_per_line == 0 else space
emoji_stream += '{}{}'.format(emoji_group, emoji_sep)
else:
emoji_stream = space.join(emoji_list)
append_to_file(test_file_path, emoji_stream, 'utf-16-le')
if __name__ == "__main__":
sys.exit(main())
|
import tkinter
import winsound
import time
import math
def countdown(count):
seconds = math.floor(count % 60)
minutes = math.floor((count / 60) % 60)
hours = math.floor((count / 3600))
label['text'] = "Hours: " + str(hours) + " Minutes: " + str(minutes) + " Seconds: " + str(seconds)
if count >= 0:
top.after(1000, countdown, count - 1)
else:
for x in range(3):
winsound.Beep(1000, 1000)
label['text'] = "Time is up!"
def updateButton():
hour, minute, sec = hoursE.get(), minuteE.get(), secondE.get()
if hour.isdigit() and minute.isdigit() and sec.isdigit():
time = int(hour) * 3600 + int(minute) * 60 + int(sec)
countdown(time)
top = tkinter.Tk()
top.geometry("250x150")
hoursT = tkinter.Label(top, text="Hours:")
hoursE = tkinter.Entry(top)
minuteT = tkinter.Label(top, text="Minutes:")
minuteE = tkinter.Entry(top)
secondT = tkinter.Label(top, text="Seconds:")
secondE = tkinter.Entry(top)
hoursT.grid(row=1, column=1)
hoursE.grid(row=1, column=2)
minuteT.grid(row=2, column=1)
minuteE.grid(row=2, column=2)
secondT.grid(row=3, column=1)
secondE.grid(row=3, column=2)
label = tkinter.Label(top)
label.grid(row=5, column=2)
button = tkinter.Button(top, text="Start Timer", command=updateButton)
button.grid(row=4, column=2)
top.mainloop() |
#Pertemuan pertama sintax dasar python
#penulisan variable
# di php => $
# vasriable di js => let, var, const
# java const
# python => nama_variable
# variable
# - type data
# - int => angka
# - string => input " " biasanya berupa huruf,
# karakter angka
# - bool => False or True
# - array => di python > list = []
# - object => di python > dict (dictionary) {}
# pengkondisian
# perulangan
# array
# penulisan sintax python => pep8
# type data int
# a = 3
# b = 2
# hasil = a + b
# print(hasil)
# # inputan
# a = int(input('input nilai a : '))
# b = int(input('input nilai b : '))
#
# hasil = a + b
# print(hasil)
# data = [1,2,3,4,5,6,7]
# # list/ array = [0, 1, 2, 3]
data = ['kopi', 'susu', 'teh', 'coklat']#list
cari = input('cari produk : ')#string
ketemu = False #bolean
for i in range(0,len(data)): #perulangan
# print(i)
if data[i] == cari:#pengkondisian
print('produk ditemukan ', cari)
ketemu = True
# print('berhenti')
break
if not ketemu:
print('data kosong')
#type dictionary atu type data dict
#adalah type data yang menyimpan nilai kunci
# mahasiswa = {
# 'nim' : 12235,
# 'nama' : 'asad mau',
# 'alamat' : 'jember'
# }
#
# print('cari mahasiswa dengan :', mahasiswa['nim']) |
cafeMenu=['wings', 'cookies', 'spring rolls', 'salmon', 'steak', 'meat tornado', 'a literal garden', 'ice Cream', 'cake', 'pie', 'coffee', 'tea', 'unicorn tears']
print(
"""
**************************************
** Welcome to the Snakes Cafe! **
** Please see our menu below. **
**
** To quit at any time, type "quit" **
**************************************
Appetizers
----------
Wings
Cookies
Spring Rolls
Entrees
-------
Salmon
Steak
Meat Tornado
A Literal Garden
Desserts
--------
Ice Cream
Cake
Pie
Drinks
------
Coffee
Tea
Unicorn Tears
***********************************
** What would you like to order? **
***********************************
"""
)
orderArray=[]
orderNames=[]
def orderingOperator():
order=input('>')
if order.lower() in cafeMenu:
orderArray.append(order)
if order not in orderNames:
orderNames.append(order)
print(f'** {orderArray.count(order)} order of {order} have been added to your meal **')
orderingOperator()
elif order.lower()=='quit':
print('**Your order**')
for x in orderNames:
print(f'{orderArray.count(x)} order of {x} ')
print('**Thank you for visiting our Cafe**')
print('**We are working on your order**')
elif order.lower() not in cafeMenu:
print('**Your order is not in our menu**')
orderingOperator()
orderingOperator() |
import numpy as np
x = np.array(range(1, 101))
y = np.array(range(1, 101))
x_train =x[:60]
x_val = x[60:80]
x_test = x[:80] #[:80] = 시작부터 80까지 [80:] =80부터 마지막까지
y_train = y[:60]
y_val = y[60:80]
y_test = y[80:]
from keras.models import Sequential
from keras.layers import Dense
model = Sequential()
# model.add(Dense(5, input_dim =1, activation ='relu'))
model.add(Dense(5, input_shape =(1, ), activation ='relu'))
model.add(Dense(3))
model.add(Dense(4))
model.add(Dense(1))
# model.summary()
# model.compile(loss='mse', optimizer='adam', metrics=['accuracy'])
model.compile(loss='mse', optimizer='adam', metrics=['mse'])
model.fit(x_train, y_train, epochs=50, batch_size=1, validation_data=(x_val, y_val))
mse = model.evaluate(x_test, y_test, batch_size=1)
print("mse:", mse)
y_predict = model.predict(x_test)
print(y_predict)
from sklearn.metrics import mean_squared_error
def RMSE(y_test, y_predict): # RMSE는 모델의 예측 값과 실제 값의 차이를 하나의 숫자로 표현
return np.sqrt(mean_squared_error(y_test, y_predict))
print("RMSE:", RMSE(y_test, y_predict))
from sklearn.metrics import r2_score
r2_y_predict = r2_score(y_test, y_predict)
print("R2 : ", r2_y_predict) |
#1. 데이터 2개가 들어가서 하나로 나오는 것.
import numpy as np
x1 = np.array([range(1, 101), range(311,411), range(100)])
x2 = np.array([range(711,811), range(711,811), range(511,611)])
y1 = np.array([range(101,201), range(411,511), range(100)])
#print(x1.shape) # 열우선, 행무시
x1 = np.transpose(x1) #100행 3열.
y1 = np.transpose(y1)
x2 = np.transpose(x2)
#print(x1.shape)
from sklearn.model_selection import train_test_split
x1_train, x1_test, x2_train, x2_test = train_test_split(
x1, x2, shuffle=False, train_size=0.8)
from sklearn.model_selection import train_test_split
y1_train, y1_test = train_test_split(
y1, shuffle=False, train_size=0.8)
#2. 모델구성. 모델 2개를 만들거니깐 shape가 2개가 필요하다. sequential로 불가능.
from keras.models import Sequential, Model #함수형모델을 쓰겠다.
from keras.layers import Dense, Input #인풋명시를 해야한다.
#model = Sequential()
#model.add(Dense(5, input_dim = 3))
#model.add(Dense(4))
#model.add(Dense(1))
#함수형 모델로 변경
#인풋, 아웃풋이 뭔지 명시해야한다.
#모델1
input1 = Input(shape=(3, )) #인풋 3
dense1_1 = Dense(18, activation = 'relu')(input1) # 첫번째 모델의 첫번째 히든레이어 구성
dense1_2 = Dense(17, activation = 'relu')(dense1_1) # 첫번째 모델의 두번째 히든레이어 구성
dense1_3 = Dense(18, activation = 'relu')(dense1_2)
dense1_4 = Dense(21)(dense1_3)
#모델2
input2 = Input(shape = (3, ))
dense2_1 = Dense(13, activation = 'relu')(input2)
dense2_2 = Dense(26, activation = 'relu')(dense2_1)
dense2_3 = Dense(24, activation = 'relu')(dense2_2)
dense2_4 = Dense(18)(dense2_3)
from keras.layers.merge import concatenate #단순병합
merge1 = concatenate([dense1_4, dense2_4]) #2개 이상은list [] 사용...
middle1 = Dense(29)(merge1)
middle2 = Dense(33)(middle1)
middle3 = Dense(14)(middle2)
#아웃풋 구성해야한다. 이제.
#3개짜리 모델2개이다. 아웃풋도 2개이므로, 이것을 만들어줘야한다.
#output 모델구성
output1 = Dense(31)(middle3)
output2 = Dense(37)(output1)
output3 = Dense(3)(output2) #3으로 나간다.
model = Model(inputs = [input1, input2], outputs=output3) #함수형 모델 명시(input1부터시작해서 output1까지 함수형 모델임을 명시) #list로 구성.
model.summary() #함수형모델
#3. 훈련
model.compile(loss = 'mse', optimizer='adam', metrics=['mse'])
model.fit([x1_train, x2_train],
y1_train,
epochs=200, batch_size=1,
validation_split=(0.25), verbose=1)
#4. 평가, 예측
loss1 = model.evaluate([x1_test, x2_test],
[y1_test],
batch_size=1)
print("loss : " , loss1)
y1_predict = model.predict([x1_test, x2_test])
# RMSE 구하기
from sklearn.metrics import mean_squared_error
def RMSE(y_test, y_predict ):
return np.sqrt(mean_squared_error(y_test, y_predict))
RMSE1 = RMSE(y1_test, y1_predict)
print("RMSE1 : ", RMSE1)
# R2 구하기
from sklearn.metrics import r2_score
r2_1 = r2_score(y1_test, y1_predict)
print("R2_1: ", r2_1)
#100행3열 짜리 2개가 들어가서 100행3열 짜리가 2개가 나왔다.
# 가장 많이 나오는 형태는, 여러개를 넣고 하나가 나오는 경우이다.
|
#2. 튜플
#리스트와 거의 같으나 삭제, 수정이 안된다.
a = (1, 2, 3)
b = 1, 2, 3
print(type(a))
print(type(b))
print(a + b)
print(a * 3) #리스트와는 똑같다. 하지만 객체안은 수정이 안된다. |
import sqlite3
conn = sqlite3.connect('test.db')
cursor = conn.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS supermarket(Itemno INTEGER, Category TEXT,
FoodName TEXT, Company TEXT, Price INTEGER)""")
sql = "DELETE FROM supermarket"
cursor.execute(sql)
# 데이터 넣기
sql = "INSERT into supermarket(Itemno, Category, FoodName, Company, Price) values (?, ?, ?, ?, ?)"
cursor.execute(sql, (1, '똥', '오줌', '마트', 1500))
sql = "INSERT into supermarket(Itemno, Category, FoodName, Company, Price) values (?, ?, ?, ?, ?)"
cursor.execute(sql, (2, '물', '가레', '편의점', 1200))
sql = "INSERT into supermarket(Itemno, Category, FoodName, Company, Price) values (?, ?, ?, ?, ?)"
cursor.execute(sql, (1, '피', '눈알', 'ㅈ트캠프', 11500))
sql = "SELECT * FROM supermarket"
#sql = "SELECT Itemno, Category, FoodName, Company, Price FROM supermarket"
cursor.execute(sql)
rows = cursor.fetchall()
for row in rows:
print(str(row[0]) + " " + str(row[1]) + " " + str(row[2]) + " " +
str(row[3]) + " " + str(row[4]))
conn.commit()
conn.close() |
from fractions import Fraction
x=int(input("numaratorul fractiei 1 este: "))
y=int(input("numitorul fractiei 1 este: "))
z=int(input("numaratorul fractiei 2 este: "))
w=int(input("numitorul fractiei 2 este: "))
print("suma este:",Fraction(x,y)+Fraction(z,w))
print("produsul este",Fraction(x,y)*Fraction(z,w)) |
for i in range(1,100):
print (i)
if (i % 3 == 0) and (i % 5 == 0):
print(f'{i} FizzBuzz')
elif (i % 3 == 0):
print(f'{i} Fizz')
elif (i % 5 == 0):
print(f'{i} Buzz')
|
Repaint Rectangular Grid
There is a rectangular grid of length L and breadth B. The rectangular
grid is already painted with the colors Red, Green and Blue. A painter
wants the repaint the rectangular grid with the color C based on the
following conditions.
- He can repaint a cel l with the color C only if one of its four adjacent
cells is in the same color C.
- He can repaint a cell in th e order of colors Red -> Green ->
Blue or Blue -> Green -> Red. (i.e., he cannot repaint a grid from Red
to Blue or Blue to Red directly).
- To repaint a cell from one colo r to another color, he needs 1 litre of
paint in that color.
The program must accept a character matrix of size L*B representing
the rectangular grid and the value of C as the input. The program must
print the minimum number of litres of paint he needs in each color (R,
G, B) as the output.
Boundary Condition(s):
2 <= L, B <= 50
Input Format:
The first line co ntains L and B separated by a space.
The next L lines, each contains B characters separate d by a space.
The (L+2) line contains C.
Output Format:
The first 3 lines, each contains a character representing the color and an
integer representing the number of litres of paint he needs in that
color.
Example Input/Output 1:
Input:
4 4
R B R G
G B B B
B G B G
R R R R
R
Output:
R 8
G 4
B 0
Explanation:
Here L = 4, B = 4 and C = 'R'.
The cells that he can repaint are highlighted below.
R B R G
G B B B
B G B G
R R R R
There are 4 cells that need to change from Green to Red. So he needs
4 litres of Red paint.
There are 4 cells that need to change from Blue to Red (Blue -> Green
-> Red). So he needs 4 litres of Green paint and 4 litres of Red paint.
The painter needs 8 litres of Red paint and 4 litres of Green paint.
Hence the output is
R 8
G 4
B 0
Example Input/Output 2:
Input:
3 5
G G B G B
B R R G R
G B R G R
G
Output:
R 0
G 9
B 0
Example Input/Output 3:
Input:
5 4
B B R B
G B B G
G B G G
R R R B
G G G R
B
Output:
R 0
G 4
B 9
SOLUTION:
r,c=map(int,input().split())
l=[input().split() for i in range(r)]
x=input().strip()
d=dict()
d['R'],d['G'],d['B']=0,0,0
for i in range(r):
for j in range(c):
if l[i][j]==x:
continue
if (i>0 and l[i-1][j]==x) or (j>0 and l[i][j-1]==x) or (i+1<r and l[i+1][j]==x) or (j+1<c and l[i][j+1]==x):
d[l[i][j]]+=1
if x=='R':
R,G,B=d['G']+d['B'],d['B'],0
elif x=='B':
R,G,B=0,d['R'],d['R']+d['G']
else:
R,G,B=0,d['R']+d['B'],0
print('R',R,'\nG',G,'\nB',B) |
Water Tanks in Staircases
There are R*C water tanks arranged as a matrix. The water tanks are
connected diagonally from top-left to bottom-right like staircases
(i.e., If a water tank overflows, then the water will flow into the tank at
its bottom-right). The maximum capacity and the amount of water in
each water tank are passed as the input to the program. The program
must print the amount of water in each tank after adding X litres of
water to the first tank(top-most) in each staircase as the output. The
value of X is also passed as the input to the program.
Boundary Condition(s):
2 <= R, C <= 50
1 <= Maximum c apacity of each tank, X <= 1000
Input Format:
The first line co ntains R and C separated by a space.
The next R lines, each contains C integers representi ng the maximum
capacities of the R*C tanks.
The next R lines from the (R +2) line, each contains C integers
representing the amount of water in the R*C tanks.
The (2*R+2) line contains X.
Output Format:
The first R lines, e ach contains C integers representing the amount of
water in the R*C tanks after adding X litres of water based on the given
conditions.
Example Input/Output 1:
Input:
3 3
10 15 20
10 15 20
10 15 20
7 12 18
8 14 13
10 13 16
4
Output:
10 15 20
10 15 14
10 15 16
Explanation:
Here X = 4.
The maximum capacities of the 3*3 tanks are given below.
10 15 20
10 15 20
10 15 20
Staircase 1: After adding 4 litres of waters, the matrix becomes
7 12 18
8 14 13
10 13 16
Staircase 2: After adding 4 litres of waters, the matrix becomes
7 12 18
10 14 13
10 15 16
Staircase 3: After adding 4 litres of waters, the matrix becomes
10 12 18
10 15 13
10 15 16
Staircase 4: After adding 4 litres of waters, the matrix becomes
10 15 18
10 15 14
10 15 16
Staircase 5: After adding 4 litres of waters, the matrix becomes
10 15 20
10 15 14
10 15 16
Example Input/Output 2:
Input:
5 5
10 15 15 10 20
10 10 20 15 10
20 20 15 10 15
15 10 20 20 15
20 15 10 15 20
8 7 10 2 17
9 10 12 10 9
15 19 14 5 9
10 8 18 16 10
14 11 8 12 19
15
Output:
10 15 15 10 20
10 10 19 15 10
20 20 15 5 14
15 10 20 20 10
20 15 10 15 20
Example Input/Output 3:
Input:
3 5
15 10 20 15 15
20 10 15 15 10
25 15 20 10 25
11 7 15 1 12
14 7 6 12 10
16 1 6 6 21
13
Output:
15 10 20 14 15
20 10 15 15 10
25 8 12 7 25
SOLUTION:
a,b=map(int,input().split())
l=[list(map(int,input().split()))[::-1] for _ in range(a)]
k=[list(map(int,input().split()))[::-1] for _ in range(a)]
x=int(input())
for p in range(a+b-1):
v=x
for i in range(a):
for j in range(b):
if i+j==p:
while k[i][j]!=l[i][j] and v>0:
k[i][j]+=1
v-=1
for i in k:
print(*i[::-1]) |
Decreasing Order - Interlace
The program must accept two integers N1 and N2 as the input. The
program must find the absolute difference Dbetween N1 and N2.
Then the program must form a series S1 of integers using the previous
D integers of the largest integer(inclusive) between N1 and N2. Then
the program must form another series S2 of integers using the
previous D integers of the smallest integer(inclusive) between N1 and
N2. Finally, the program print the integers in the series
S1 interlaced with the integers in the series S2 as the output.
Note: The values of N1 and N2 are always not equal.
Boundary Condition(s):
1 <= N1, N2 <= 1000
Input Format:
The first line co ntains N1 and N2 separated by a space.
Output Format:
The first line cont ains 2*D integers based on the given conditions
separated by a space.
Example Input/Output 1:
Input:
15 10
Output:
15 10 14 9 13 8 12 7 11 6
Explanation:
The absolute difference between 15 and 10 is 5.
The largest integer is 15 and the smallest intege r is 10.
The previous 5 integers of 15 are 15, 14, 13, 12 and 11.
The previous 5 integers of 10 are 10, 9, 8, 7 and 6.
The integers in the series S1 are interlaced with the integers in the
series S2.
Hence the output is
15 10 14 9 13 8 12 7 11 6
Example Input/Output 2:
Input:
11 17
Output:
17 11 16 10 15 9 14 8 13 7 12 6
SOLUTION:
#Your code below
x,y=map(int,input().split());abs1=abs(x-y)
for k in range(max(x,y),min(x,y),-1):print(k,k-abs1,end=' ') |
Find Case Sensitive Pattern
The program must accept two string values S and P containing only
alphabets as the input. The program must print all possible substrings
of S that match the pattern P. If a substring matches the pattern P, then
the case of each alphabet in the pattern P matches with the
corresponding alphabet in the substring. The substrings must be
printed in the order of their occurrence. If there is no such substring in
S, then the program must print -1 as the output.
Boundary Condition(s):
1 <= Length of P <= Len gth of S <= 1000
Input Format:
The first line co ntains S.
The second line contain s P.
Output Format:
The lines, each co ntains a substring matches the pattern P or the first
line contains -1.
Example Input/Output 1:
Input:
SkillRack
Do
Output:
Sk
Ra
Explanation:
Here the given pattern is Do.
The case of each alphabet in the pattern Do matches the
substrings Sk and Ra.
Hence the output is
Sk
Ra
Example Input/Output 2:
Input:
AtAAnTheIsWasWere
IoT
Output:
AtA
AnT
IsW
Example Input/Output 3:
Input:
Mountain
HI
Output:
-1
SOLUTION:
#Your code below
def fun(m,n):
for k in range(0,len(m)):
if m[k].isupper() != n[k].isupper():return 0
return 1
x=input().strip();y=input().strip();
x1=[x[k:h+1] for k in range(len(x)) for h in range(1,len(x)+1) if len(x[k:h+1])==len(y) and fun(x[k:h+1],y)]
if len(x)==1 and len(y)==1:print(x);quit()
if x1==[]:print(-1);quit()
else:print(*x1,sep='\n') |
Filling Holes with Wooden Sticks
The program must accept a character matrix of size R*C representing a
wood as the input. The character asterisk (*) represents the hole. The
character hash symbol (#) represents the wooden part. There
are N wooden sticks of different heights used to fill the holes. The
depth of a hole is equal to number of consecutive asterisks from the
top of a column. A hole of depth X can be filled with a wooden stick of
height X. The heights of the N wooden sticks are also passed as the
input to the program. The program must fill as many holes as possible
from left to right in the wood. Then the program must print the
modified matrix and the heights of the remaining sticks as the output. If
no sticks are left, then the program must print -1 as the output.
Boundary Condition(s):
2 <= R, C <= 50
1 <= N <= 100
Input Format:
The first line co ntains R and C separated by a space.
The next R lines, each containing C characters separa ted by a space.
The (R+2) line contains N.
The (R+3) line contains N integers separated by a space.
Output Format:
The first R lines, e ach containing C characters separated by a space.
The (R+1) line contains -1 or the heights of the remaining sticks
separated by a space based on the given conditions.
Example Input/Output 1:
Input:
7 5
# * # * *
# * # * *
# * # # *
# * # # *
# # # # *
# # # # *
# # # # #
62
3 4 5 6 7
Output:
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
3 5 7
Explanation:
There are 3 holes in the given wood.
Depth of the 1 hole = 4
Depth of the 2 hole = 2
Depth of the 3 hole = 6
All three holes can be filled with the given wooden sticks (4, 2, 6).
Now the matrix becomes
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
The remaining wooden sticks are 3, 5 and 7.
Example Input/Output 2:
Input:
4 10
# * # * # * # * * *
# * # * # * # # # #
# * # * # * # # # #
# # # # # * # # # #
71
1 3 1 2 4 1
Output:
# # # * # # # # # #
# # # * # # # # # #
# # # * # # # # # #
# # # # # # # # # #
2 1
Example Input/Output 3:
Input:
6 4
* # * #
* # * #
* # * #
# # * #
# # * #
# # # #
13
Output:
# # * #
# # * #
# # * #
# # * #
# # * #
# # # #
-1
#Your code below
x,y=map(int,input().split());l=[input().split() for _ in range(x)];z=int(input());l1=list(map(int,input().split()));l2=[];l3=[]
for k in zip(*l):
c=''.join(k).count('*')
if c in l1:
l1.remove(c)
d=''.join(k).replace('*','#');e=[m for m in d]
l2.append(e)
else:e=[m for m in k];l2.append(e)
if l1==[]:
for k in zip(*l2):print(*k)
print(-1)
else:
for k in zip(*l2):print(*k)
print(*l1) |
from visual import *
from visual.graph import *
#graphs the taylor series function for cos(x)
def taylor(N):
#initializes a window for display
gd = gdisplay(width=600,height=600,xmax=N,xmin=-N,
ymax=5,ymin=-5)
series = ""
s = 0
#adds the number of terms to the equation
for n in range(0,2*N,2):
term = "(x**" +str(n)+ ")/factorial(" +str(n)+ ")"
if s%2 == 0:
series += term + " - "
s += 1
else:
series += term + " + "
s += 1
series = series[:-3]
print series
#graphs the taylor series function
g = gcurve(color=color.white)
for x in arange(-N,N,.01):
g.plot(pos=(x,eval(series)))
|
from math import *
import pyfits
#pulls boxes of pixel values of out of an image or fit file
def photometry():
#allows the user to input a file to read
fileName = raw_input("Enter the file name: ")
image = pyfits.getdata(fileName)
print image
#asks the user to input details of the star or asteroid
n = image.shape[0]
xStar = input("Enter the x-coordinate of the object: ")
yStar = input("Enter the y-coordinate of the object: ")
dim = input("Enter the dimension of the object: ")/2.
#sums all of the pixels in designated box
starBox = image[yStar-dim:yStar+dim+1,xStar-dim:xStar+dim+1]
print starBox
starBkg = 0
for a in starBox:
for b in a:
starBkg += b
print "Star + Background = " + str(starBkg)
#asks the user to input details of a blank portion
xBkg = input("Enter the x-coordinate of a blank portion: ")
yBkg = input("Enter the y-coordinate of a blank portion: ")
#sums all of the pixels in designated blank box
blankBox = image[yBkg-dim:yBkg+dim+1,xBkg-dim:xBkg+dim+1]
print blankBox
bkg = 0
for a in blankBox:
for b in a:
bkg += b
print "Background = " + str(bkg)
#calculates pixel count
count = starBkg - bkg
print "Pixel count = " + str(count)
#calculates the constant
mag = input("Enter the magnitude of the object: ")
const = mag + 2.5*log10(count)
print "Constant = " + str(const)
#asks the user to input details of the asteroid
xAst = input("Enter the x-coordinate of your asteroidn: ")
yAst = input("Enter the y-coordinate of your asteroid: ")
#sums the pixels in the asteroid's designated box
astBox = image[yAst-dim:yAst+dim+1,xAst-dim:xAst+dim+1]
print astBox
ast = 0
for a in astBox:
for b in a:
ast += b
ast -= bkg
print "Asteroid = " + str(ast)
#calculates the magnitude of the asteroid
print "Magnitude = " + str(-2.5*log10(ast) + const)
|
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 16 15:55:19 2018
@author: ConorGL
The aim of this project is to look in to Reddit comments and to use them to make our own.
This will form part 1 of a larger project which will be to generate our own Floria Man stories.
"""
import nltk
import csv
import itertools
from datetime import datetime
import numpy as np
from CreateRNN import RNNNumpy
import sys
#nltk.download('punkt')
# Outer SGD Loop
# - model: The RNN model instance
# - X_train: The training data set
# - y_train: The training data labels
# - learning_rate: Initial learning rate for SGD
# - nepoch: Number of times to iterate through the complete dataset
# - evaluate_loss_after: Evaluate the loss after this many epochs
def train_with_sgd(model, X_train, y_train, learning_rate=0.005, nepoch=100, evaluate_loss_after=5):
# We keep track of the losses so we can plot them later
losses = []
num_examples_seen = 0
for epoch in range(nepoch):
# Optionally evaluate the loss
if (epoch % evaluate_loss_after == 0):
loss = model.calculate_loss(X_train, y_train)
losses.append((num_examples_seen, loss))
time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print(f"{time}: Loss after num_examples_seen={num_examples_seen} epoch={epoch}: {loss}")
# Adjust the learning rate if loss increases
if (len(losses) < 1 and losses[-1][1] < losses[-2][1]):
learning_rate = learning_rate * 0.5
print(f"Setting learning rate to {learning_rate}")
sys.stdout.flush()
# For each training example...
for i in range(len(y_train)):
# One SGD step
model.sgd_step(X_train[i], y_train[i], learning_rate)
num_examples_seen += 1
"""
We need to set certain variables here for use in the cleaning of the data set.
The vocabulary_size limit imposed is in order to keep the training time down.
Unknown_token will be used as a subtitue for anything not in these 8000 words.
The sentence_start_token and sentence_end_token will be used for to mark where
the start and end of the sentences are. We will use them later on in such a way
that we will construct our generated sentences with sentence_start_token followed
by a the next most likely more.
"""
vocabulary_size = 8500
unknown_token = "UNKNOWN_TOKEN"
sentence_start_token = "SENTENCE_START"
sentence_end_token = "SENTENCE_END"
#Start by reading the data row-by-row, tokenising it sentence by sentence.
#Once we have our massive list of list of sentences we flatten it with
#itertools.chain and add our sentence start/end tokens
print("Reading csv file...")
with open('Tutorial/rnn-tutorial-rnnlm/data/reddit-comments-2015-08.csv', 'r', encoding = 'utf-8') as f:
reader = csv.reader(f)
sentences = []
for row in reader:
if row:
# Split full comments into sentences
sentences.append(nltk.sent_tokenize(row[0].lower()))
sentences = itertools.chain(*sentences)
sentences = ['{} {} {}'.format(sentence_start_token, x, sentence_end_token) for x in sentences]
print ("Parsed {} sentences.".format(len(sentences)))
# Tokenize the sentences into words. We could use the re package here
# to remove punctionation from the sentences as a possible word save.
tokenized_sentences = [nltk.word_tokenize(sent) for sent in sentences]
# Count the word frequencies
word_freq = nltk.FreqDist(itertools.chain(*tokenized_sentences))
print ("Found {} unique words tokens.".format(len(word_freq.items())))
# Get the vocabulary_size most common words and build index_to_word and word_to_index vectors
vocab = word_freq.most_common(vocabulary_size-1)
index_to_word = [x[0] for x in vocab]
index_to_word.append(unknown_token)
word_to_index = dict([(w,i) for i,w in enumerate(index_to_word)])
print("Using vocabulary size {}.".format(vocabulary_size))
print("The least frequent word in our vocabulary is '{}' and appeared {} times.".format(vocab[-1][0], vocab[-1][1]))
# Replace all words not in our vocabulary with the unknown token
for i, sent in enumerate(tokenized_sentences):
tokenized_sentences[i] = [w if w in word_to_index else unknown_token for w in sent]
print("\nExample sentence: '{}'".format(sentences[1000]))
print("\nExample sentence after Pre-processing: '{}'".format(tokenized_sentences[1000]))
# Create the training data
X_train = np.asarray([[word_to_index[w] for w in sent[:-1]] for sent in tokenized_sentences])
y_train = np.asarray([[word_to_index[w] for w in sent[1:]] for sent in tokenized_sentences])
np.random.seed(10)
model = RNNNumpy(vocabulary_size)
"""
We can use the below code in order to a quick 'test' to see what the output of our RNN would be.
It currently only spits out gobbledy-gook....
o, s = model.forward_propagation(X_train[10])
predictions = model.predict(X_train[10])
print(predictions.shape)
print(predictions)
predicted_words = [index_to_word[i] for i in predictions]
predicted_sentence = " ".join(predicted_words)
print("Expected Loss for random predictions: {}".format(np.log(vocabulary_size)))
print("Actual loss:{}".format(model.calculate_loss(X_train[:1000], y_train[:1000])))
"""
"""
This next chunk of code was used to have a quick test that the gradient check f
function will work properly
grad_check_vocab_size = 100
np.random.seed(10)
model = RNNNumpy(grad_check_vocab_size, 10, bptt_truncate=1000)
model.gradient_check([0,1,2,3], [1,2,3,4])
"""
np.random.seed(10)
model = RNNNumpy(vocabulary_size)
%timeit model.numpy_sgd_step(X_train[10], y_train[10], 0.005)
# Train on a small subset of the data to see what happens
model = RNNNumpy(vocabulary_size)
losses = train_with_sgd(model, X_train[:100], y_train[:100], nepoch=10, evaluate_loss_after=1)
|
import unittest
class Stack:
"""Simple Stack implementation - First In Last Out"""
def __init__(self):
self.__data = []
def push(self, text):
"""Push an item to a stack
Arguments:
text {string} -- Element that will be put on stack
"""
self.__data.insert(0, text)
def pop(self):
"""Get an element from a top of a stack
Returns:
string -- element from a top of a stack
"""
if len(self.__data) == 0:
return None
popped = self.__data[0]
new_data = []
for index in range(1, len(self.__data)):
new_data.append(self.__data[index])
self.__data = new_data
return popped
def peek(self):
"""Check what currently is at a top of a stack without taking it off
Returns:
string -- element from a top of a stack
"""
return self.__data[0]
class StackTest(unittest.TestCase):
def test_push_one_peek_one(self):
stack = Stack()
stack.push("one")
self.assertEqual(stack.peek(), "one", "Should be 'one'")
def test_push_three_peek_last(self):
stack = Stack()
stack.push("one")
stack.push("two")
stack.push("three")
self.assertEqual(stack.peek(), "three", "Should be 'three'")
def test_push_three_pop_one_peek_second(self):
stack = Stack()
stack.push("one")
stack.push("two")
stack.push("three")
popped = stack.pop()
self.assertEqual(popped, "three", "Should be 'three'")
self.assertEqual(stack.peek(), "two", "Should be 'two'")
def test_pop_empty_stack(self):
stack = Stack()
popped = stack.pop()
self.assertIsNone(popped)
if __name__ == "__main__":
unittest.main()
|
class Vector:
def __init__(self, x, y):
self.__x = float(x)
self.__y = float(y)
def getX(self):
return self.__x
def getY(self):
return self.__y
def abs(self):
return (self.__x ** 2 + self.__y ** 2) ** 0.5
def unitVec(self):
abs = self.abs()
if abs == 0:
return Vector(0, 0)
else:
return Vector(self.getX() / abs, self.getY() / abs)
def __add__(self, other):
if not isinstance(other, Vector):
raise TypeError("A vector can only be added with another vector. ")
return Vector(self.__x + other.getX(), self.__y + other.getY())
def __sub__(self, other):
if not isinstance(other, Vector):
raise TypeError("A vector can only be substracted by another vector. ")
return Vector(self.__x - other.getX(), self.__y - other.getY())
def __rmul__(self, other):
return Vector(self.getX() * other, self.getY() * other)
def __neg__(self):
return Vector(-self.__x, -self.__y)
def __repr__(self):
return "Vector(" + str(self.__x) + " , " + str(self.__y) + ")"
|
import random
#Finding the minimum of random numbers
randNum = []
for x in range(10):
randNum.append(random.randint(0,100))
print(min(randNum))
test = "Sample string"
num = int(input("Enter a number: "))
print("You entered {} test {} ".format(num,test))
list = [random.randint(0,10) for x in range(3)]
print(list)
test_var = ["hello" for x in range(2)]
print(test_var)
for x in range(5):
print(test_var)
chances = int(input("Enter no. of chances: "))
#function to provide x no. of chances
def run_func_x_time(chances):
for x in range(chances):
rand_num = random.randint(0,10)
print("This is attempt {} ".format(x+1))
num_entered = int(input("Guess a number between 0 and 10: "))
if(rand_num == num_entered):
print("Correct guess")
break
else:
print("Incorrect guess")
continue
run_func_x_time(chances)
def get_player_number():
number_csv = input("Enter 6 numbers seperated by commas:\n")
number_list = number_csv.split(',')
number_set = {int(number) for number in number_list}
return number_set
print(get_player_number())
|
class Movie:
def __init__(self, name, genre, watched):
self.name = name
self.genre = genre
self.director = "Default Director"
self.watched = watched
def __repr__(self):
return "<Movie: {}>".format(self.name)
def json(self):
return {
'name':self.name,
'genre': self.genre,
'watched':self.watched
}
@classmethod
def from_json(cls, json_data):
return Movie(**json_data)
class User:
def __init__(self, name):
self.name = name
self.movies = []
def __repr__(self):
return "<User: {}>".format(self.name)
def add_movie(self, name, genre):
movie = Movie(name, genre, True)
self.movies.append(movie)
def delete_movie(self, name):
self.movies = list(filter(lambda movie: movie.name != name, self.movies))
#self.movies.remove()
def watched_movies(self):
movies_watched = list(filter(lambda movie:movie.watched, self.movies))
return movies_watched
def save_to_file(self):
with open(self.name + ".txt",'w') as f:
f.write(self.name + "\n")
for movie in self.movies:
f.write(movie.name + "," + movie.genre + "," + str(movie.watched))
f.write("\n")
def json(self):
return {
'name':self.name,
'movies':[
movie.json() for movie in self.movies
]
}
@classmethod
def from_json(cls, json_data):
user = User(json_data['name'])
movies = []
for movie_data in json_data['movies']:
movies.append(Movie.from_json(movie_data))
user.movies = movies
return user |
'''
8.4 Open the file romeo.txt and read it line by line.
For each line, split the line into a list of words using the split() method.
The program should build a list of words.
For each word on each line check to see if the word is already in the list
and if not append it to the list. When the program completes, sort and print the resulting
words in alphabetical order.
You can download the sample data at http://www.py4e.com/code3/romeo.txt
'''
fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
line = line.rstrip()
temp = line.split()
for index in temp:
if index not in lst:
lst.append(index)
lst.sort()
print(lst)
|
from typing import TypeVar, Generic, List
T = TypeVar("T")
class Pilha(Generic[T]):
def __init__(self) -> None:
self._container: List[T] = []
def coloca(self, item: T) -> None:
self._container.append(item)
def retira(self) -> T:
return self._container.pop()
#__repr__ é basicamente o que é exibido quando você dá print numa pilha
def __repr__(self) -> str:
return repr(self._container)
numero_de_discos: int = 5
torre_a: Pilha[int] = Pilha()
torre_b: Pilha[int] = Pilha()
torre_c: Pilha[int] = Pilha()
"""
vale ressaltar que a resolucao da torre tem uma funcao que dita o numero maximo de movimentos que podem ser feitos
m = 2^x - 1 = ?
onde
m = numero de movimentos
x = numero de discos presentes nas torres
"""
for i in range(1, numero_de_discos + 1):
torre_a.coloca(i)
def hanoi(begin: Pilha[int], end: Pilha[int], temp: Pilha[int], n: int) -> None:
if n == 1:
end.coloca(begin.retira())
else:
hanoi(begin, temp, end, n - 1)
hanoi(begin, end, temp, 1)
hanoi(temp, end, begin, n - 1)
if __name__ == "__main__":
hanoi(torre_a, torre_c, torre_b ,numero_de_discos)
print(torre_a)
print(torre_b)
print(torre_c) |
# import ...
# -----------------------------------------------------------------------------
# Exercise (Easy): Quick and Efficient Fibonacci
# This problem is fairly easy by itself, so an
# additional requirement is to run the function
# in O(n) time and O(1) space complexity.
# Ex) Input: 3 Output: 2
# -----------------------------------------------------------------------------
def fibonacci(n = 0):
return 0
# -----------------------------------------------------------------------------
# Exercise (Easy): Palindrome
# Test if the input string is a palindrome.
# Only characters should be considered.
# Ex) Input: "5car3" Output: True
# -----------------------------------------------------------------------------
def is_palindrome(word = ""):
return False
# -----------------------------------------------------------------------------
# Exercise (Easy): Bit Flip
# Swap all even bits with odd bits in a number.
# Ex) Input: 23 (0 0 0 1 0 1 1 1) Output: 43 (0 0 1 0 1 0 1 1)
# Explanation) The first two (1 1) bits swap, the next two (0 1) swap, then ...
# -----------------------------------------------------------------------------
def odd_even_bit_swap(n=0):
# base_10 number(int) to base_2 number(string): bin(n)
# base_2 number(string) to base_10 number(int): int(string, 2)
return 0
|
import pandas as pd
import matplotlib.pyplot as plt
from mlxtend.plotting import plot_linear_regression
import numpy as np
import seaborn as sns
#Step 1: Readding dataset
df = pd.read_csv('dataset.csv')
#sns.set_theme(color_codes=True)
#Step 2: Parameter Initilization
theta = [1,2]
x = df['x']
y = df['y']
#print(x,y)
count = 0
for i in range(10):
print()
print("iteration number:", count)
count = count + 1
h = []
m = len(x)
#Step 3: Hypothesis Function
for i in range(m):
h.append(theta[0] + theta[1] * x[i])
# print(h[3])
#Step 4: cost function
error = 0
for i in range(m):
error = error + (h[i] - y[i]) ** 2
J = (1 / (2 * m)) * error
print('Cost= ',J)
#Step 5: Gradinet Descent
alpha = 0.01
diff_J_theta0 = 0
diff_J_theta1 = 0
for i in range(m):
diff_J_theta0 = diff_J_theta0 + (h[i] - y[i])
diff_J_theta1 = diff_J_theta1 + (h[i] - y[i]) * x[i]
theta[0] = theta[0] - (alpha / m) * diff_J_theta0
theta[1] = theta[1] - (alpha / m) * diff_J_theta1
print("Theta 0 =",theta[0]," Theta 1 =",theta[1])
#X = np.array(theta[0])
#y = np.array(theta[1])
#intercept, slope, corr_coeff = plot_linear_regression(X, y)
#plt.show()
|
def word_count(s):
# Your code here
"""
This function takes a single string as an argument.
Ex. Hello, my cat. And my cat doesn't say "hello" back.
It returns a dictionary of words and their counts:
Ex. {'hello': 2, 'my': 2, 'cat': 2, 'and': 1, "doesn't": 1, 'say': 1, 'back': 1}
Case should be ignored. Output keys must be lowercase. Key order in the dictionary doesn't matter.
Split the strings into words on any whitespace. Ignore each of the following characters:
" : ; , . - + = / \ | [ ] { } ( ) * ^ &
If the input contains no ignored characters, return an empty dictionary.
"""
stop_char = r""":;",.-+=/|[]{|}()*^\&"""
# Make sure special characters arent in string
s_clean = "".join([x for x in s if x not in stop_char])
# Lower case and remove trailing space
word_list = s_clean.lower().split()
# use cache to hold memory
word_count = {}
for x in word_list:
if x not in word_count:
# if not there, start it at 0
word_count[x] = 0
# if seen again, increase count
word_count[x] += 1
return word_count
if __name__ == "__main__":
print(word_count(""))
print(word_count("Hello"))
print(word_count('Hello, my cat. And my cat doesn\'t say "hello" back.'))
print(word_count(
'This is a test of the emergency broadcast network. This is only a test.'))
|
d = {
"foo": 12,
"bar": 17,
"qux": 2
}
items = list(d.items())
# for t in d.items():
# print(t)
print(items)
items.sort() #> sorts tuples in order by key (alphabetically)
print(items)
# Sort by value
# def fun1(e):
# return e[1]
# items.sort(key=fun1)
items.sort(key=lambda e: e[1])
print(items) |
from copy import deepcopy
import math
AXES = [0,1,2]
CUBE_MAP = [2,1,1,2,1,2,1,1,2,2,1,1,1,2,2,2,2]
def walk(steps, axis, sign, path, map_index):
# Copy args
steps = deepcopy(steps)
axis = deepcopy(axis)
sign = deepcopy(sign)
path = deepcopy(path)
map_index = deepcopy(map_index)
new_nodes = []
current_node = path[-1]
# Take the number of steps in the right direction
for i in range(0, steps):
new_node = deepcopy(current_node)
new_node[axis] += sign * (i + 1)
if verify(new_node, path):
# Node verified, remember it
new_nodes.append(new_node)
else:
# Stop searching this branch
return False
new_path = deepcopy(path) # NOTE: copy might not be needed here
new_path.extend(new_nodes)
new_index = map_index + 1
# debug
print_path(new_path)
print new_index
# Success condition
if len(new_path) == math.pow(len(AXES),3):
print ' %%% SOLUTION FOUND %%% '
return new_path
# Otherwise keep walking
for d in set(AXES) - set([axis]):
for sign in (1,-1):
walk_result = walk(steps=CUBE_MAP[new_index], axis=d, sign=sign, path=new_path, map_index=new_index)
if walk_result:
# Ignore falsy return values
return walk_result
def verify(node, path):
# verify that node exists
for value in node:
if value > 2 or value < 0:
return False
# verify that node is not in path
if node in path:
return False
return True
def print_path(path):
tmp_str = ''
print
for i in range(0,3):
print
for j in range(0,3):
tmp_str = ''
for k in range(0,3):
if [k, j, i] in path:
tmp_str += '* '
else:
tmp_str += '- '
print tmp_str
print '=============='
if __name__ == '__main__':
axis = 0
path = [[0,0,0]]
index = 0
path = walk(steps=CUBE_MAP[index], axis=axis, sign=1, path=path, map_index=index)
print path
|
# Should perform merge sort on the given list
ul = [4,2,9,20,292,4,37,8,273,49]
def merge(l1, l2):
i, j = 0, 0
new_list = []
while i<len(l1) and j<len(l2):
#print l1[i], l2[j]
if l1[i] <= l2[j]:
new_list.append(l1[i])
i += 1
else:
new_list.append(l2[j])
j += 1
new_list += l1[i:]
new_list += l2[j:]
return new_list
def mergesort(ul):
if len(ul) <= 1:
return ul
else:
midway = len(ul) / 2
s1 = mergesort(ul[:midway])
s2 = mergesort(ul[midway:])
return merge(s1, s2)
sl = mergesort(ul)
print sl
|
n=input()
m=input()
if sorted(n)==sorted(m):
print('anagram')
else:
print('Not anagram')
|
x = (1, 'two', 3.0, 4, False)
y = (1, 'two', 3.0, 4, False)
print('x is {}'.format(x))
# x and y are both tuple
# each element has it's own type
print(type(x))
print(type(x[4]))
print(type(y))
# unique id's'
print(id(x))
print(id(y))
# use is:instance(x, type)
if isinstance(x, tuple()):
print('x is tuple'.format(x))
else:
print('Nope')
if isinstance(x, list()):
print('x is list')
else:
print('Nope')
|
# 1. (a)
### Write down the result of running the following Python code. Justify your answers. (5 marks)
### i) print(len('9yth0\\\n'))
### ii) print('3\'4')
### iii) len("4-1") = 3
### iv) print(3*"ab"*2)
### v) print("He said, 'No!'")
# print(len('9yth0\\\n')) # 7
# print('3\'4') # 3'4
# len("4-1") = 3 # error
# print(3*"ab"*2) # abababababab
# print("He said, 'No!'") # He said, 'No!'
|
# oscar stanley
#6-10-2014
# range 21 to 29
number = int(input("please enter a number: "))
if number >= 21 and number <= 29:
print(" you number is in the range")
else:
print("your number must be in the rage of 21-29")
|
"""
¿A qué velocidad se ejecuta?
¿Necesitamos que sea tan rápido?
https://nerdparadise.com/programming/pygame/part1
"""
clock = pygame.time.Clock()
while not done:
pygame.display.flip()
# will block execution until 1/60 seconds have passed
# since the previous time clock.tick was called.
clock.tick(60)
|
array = []
array_size = raw_input("Please enter the size of the array")
for number in range(0,int(float(array_size))):
user_input = raw_input("Please enter the %number of the array")
array.append(user_input)
def Counting(array,search_term):
count = 0
for x in array:
if x == search_term:
count = count + 1
print count
Counting(array,raw_input("Please enter the search term"))
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
def isPrime(n):
if n==1:
return 0
for i in range(2,int(pow(n,0.5))+1):
if n%i==0 and i!=n:
return 0
return 1
if __name__=="__main__":
n=int(input())
while n>0:
if isPrime(int(input())):
print("Prime")
else:
print("Not prime")
n-=1
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
def count_days(a, b):
# actual-return,expected-returned
if a[2] > b[2]:
return 10000
elif a[2] == b[2]:
if a[1] == b[1] and a[0] > b[0]:
return 15 * (a[0] - b[0])
elif a[1] > b[1]:
return 500 * (a[1] - b[1])
return 0
a = list(map(int, input().split(" ")))
b = list(map(int, input().split(" ")))
ret = count_days(a, b)
print(ret)
|
class Vivienda(object):
"""
Clase Vivienda
"""
code = None
link = None
address = None
barrio = None
distrito = None
ciudad = None
lat = None
lon = None
price = None
area = None
has_elevator = None
floor = None
exterior = None
rooms = None
anuncio = None
def __init__(self, dictionary=None):
"""
Inicializa la clase vivienda a partir de un diccionario
:param dictionary:
"""
if dictionary:
self.code = dictionary['code'] if 'code' in dictionary else None
self.link = dictionary['link'] if 'link' in dictionary else None
self.address = dictionary['address'] if 'address' in dictionary else None
self.barrio = dictionary['barrio'] if 'barrio' in dictionary else None
self.distrito = dictionary['distrito'] if 'distrito' in dictionary else None
self.ciudad = dictionary['ciudad'] if 'ciudad' in dictionary else None
self.lat = dictionary['lat'] if 'lat' in dictionary else None
self.lon = dictionary['lon'] if 'lon' in dictionary else None
self.price = dictionary['price'] if 'price' in dictionary else None
self.area = dictionary['area'] if 'area' in dictionary else None
self.has_elevator = dictionary['has_elevator'] if 'has_elevator' in dictionary else None
self.floor = dictionary['floor'] if 'floor' in dictionary else None
self.exterior = dictionary['exterior'] if 'exterior' in dictionary else None
self.rooms = dictionary['rooms'] if 'rooms' in dictionary else None
self.anuncio = dictionary['anuncio'] if 'anuncio' in dictionary else None
def to_dict(self):
"""
Retorna un diccionario con los datos de la vivienda.
:return:
"""
return {'code': self.code,
'link': self.link,
'address': self.address,
'barrio': self.barrio,
'distrito': self.distrito,
'ciudad': self.ciudad,
'lat': self.lat,
'lon': self.lon,
'price': self.price,
'area': self.area,
'has_elevator': self.has_elevator,
'floor': self.floor,
'exterior': self.exterior,
'rooms': self.rooms,
'anuncio': self.anuncio} |
#!/usr/bin/env python3
"""
A unival tree (which stands for "universal value") is a tree where all nodes under it have the same value.
Given the root to a binary tree, count the number of unival subtrees.
For example, the following tree has 5 unival subtrees:
0
/ \
1 0
/ \
1 0
/ \
1 1
"""
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def solve(tree):
values = []
def count_unival(tree):
if is_leaf(tree):
values.append(tree.value)
return
left = tree.left
right = tree.right
if left.value == right.value:
values.append(left.value)
count_unival(left)
count_unival(right)
count_unival(tree)
print(values)
print(len(values))
def is_leaf(node):
return node.left is None and node.right is None
if __name__ == '__main__':
tree = Node(0, Node(1), Node(0))
tree.right.left = Node(1, Node(1), Node(1))
tree.right.right = Node(0)
solve(tree)
|
__author__ = 'Matthew'
n = input('what number would you like to choose? ')
a = int(str(n))
def prime(a):
a = abs(int(a))
if a < 2: #2 is the lowest prime number
return False
if a == 2: #also the only even one
return True
if not a & 1: #this is to say that any odd numbers are prime
return False
for x in range(3, int(a**0.5) + 1, 2): #check if num suits criteria for prime
if a % x == 0: #
return False
return True
if prime(a): #if value is true or false
print("Your number is a prime!")
else:
print("Your number is not prime!")
#str_integers = input("Please choose your number")
#n = int(str_integers)
#primes = primesUpTo(n//2)
#factors = []
#for p in primes:
#if (n%p) == 0:
#k=1
#while(n%(p**k))==0:
#factors.append(p)
#k+=1
#if factors == []
#factors = [n]
#return factors
# your code here
__author__ = 'Matthew'
n = input('what number would you like to choose? ')
a = int(str(n))
def prime(a):
a = abs(int(a))
if a < 2: #2 is the lowest prime number
return False
if a == 2: #also the only even one
return True
if not a & 1: #this is to say that any odd numbers are prime
return False
for x in range(3, int(a**0.5) + 1, 2): #check if num suits criteria for prime
if a % x == 0: #
return False
return True
if prime(a): #if value is true or false
print("Your number is a prime!")
else:
print("Your number is not prime!")
#str_integers = input("Please choose your number")
#n = int(str_integers)
#primes = primesUpTo(n//2)
#factors = []
#for p in primes:
#if (n%p) == 0:
#k=1
#while(n%(p**k))==0:
#factors.append(p)
#k+=1
#if factors == []
#factors = [n]
#return factors |
#!/usr/bin/env python2
import os
import sys
import platform
import datetime
def creation_date(path_to_file):
"""
Try to get the date that a file was created, falling back to when it was
last modified if that isn't possible.
See http://stackoverflow.com/a/39501288/1709587 for explanation.
"""
if platform.system() == 'Windows':
return os.path.getctime(path_to_file)
else:
stat = os.stat(path_to_file)
try:
return stat.st_birthtime
except AttributeError:
# We're probably on Linux. No easy way to get creation dates here,
# so we'll settle for when its content was last modified.
return stat.st_mtime
def geotags(path_to_file):
return None
def is_image(extension):
image_extensions = ['.jpg','.jpeg','.png']
if (extension.lower().endwith(tuple(image_extensions))):
return true
else:
return false
def create_new_name(path_to_file):
creation_time = datetime.datetime.fromtimestamp(creation_date(path_to_file)).strftime("%Y-%m-%d")
original_name, extension = os.path.splitext(os.path.basename(path_to_file))
# basename = os.path.basename(path_to_file)
# geotags = geotags(path_to_file)
geotags = None
name = str(creation_time) + " - " + original_name
if (geotags):
name = name + " - " + geotags
name = name + extension
return name
def rename_file(path_to_file, new_name):
os.rename(path_to_file, os.path.join(os.path.dirname(path_to_file), new_name))
def log(path_to_file, name):
print "Arquivo " + os.path.basename(path_to_file) + " --> " + name
path_to_file = sys.argv[1]
name = create_new_name(path_to_file)
log(path_to_file, name)
rename_file(path_to_file, name)
|
from ascii_table import Table
from aqa_assembly_simulator.error.VirtualMachineError import VirtualMachineError
class Memory:
def __init__(self, capacity):
"""
Memory constructor.
Constructs _memory using a list comprehension.
:param capacity: number of addressable memory units (integer)
"""
self._capacity = capacity
self._memory = [
0 for address in range(capacity)
]
def __getitem__(self, address):
"""
Returns data stored at memory address :param address.
If :param address out of index range -> virtual machine error is raised.
:param address: address index (0 <= a < n) (integer)
:return: (integer)
"""
if not 0 <= address.get_literal() < self._capacity:
raise VirtualMachineError(address, "Address index out of range")
return self._memory[address.get_literal()]
def __setitem__(self, address, value):
"""
Sets the value stored in address :param address to :param value.
If :param address out of index range -> virtual machine error raised.
:param address: address index (0 <= a < n) (integer)
:param value: (integer)
:return: (None)
"""
if not 0 <= address.get_literal() < self._capacity:
raise VirtualMachineError(address, "Address index out of range")
self._memory[address.get_literal()] = int(value)
def __repr__(self):
"""
Returns string representation of the memory unit using an ascii_table.Table object
:return: (string)
"""
return str(Table([
{
"Header": "Addresses",
"Contents": list(map(str, range(self._capacity)))
},
{
"Header": "Values",
"Contents": list(map(str, self._memory))
}
]))
|
#Binary Decoder
#Katie Hay
#Version 2.7.15
from sys import stdin
def decode(binary, n):
text = ""
i = 0
while (i < len(binary)):
byte = binary[i:i+n]
byte = int(byte, 2)
#if backspace, remove last character of string
if(byte == 8):
text = text[:-1]
i+=n
else:
text += chr(byte)
i += n
return text
binary = stdin.read().rstrip("\n")
if (len(binary) % 7 == 0):
text = decode(binary, 7)
print text
if (len(binary) % 8 == 0):
text = decode(binary, 8)
print text
|
tab = [2, 5, 4, 1, 8, 7, 4, 0, 9]
def reverse(tab):
tab2=[]
i=len(tab)-1
j=0
while i>=0:
tab2.append(tab[i])
j+=1
i-=1
print("",tab,"\n",tab2)
reverse(tab)
|
n=int(input('Podaj liczbę w systemie dziesiątkowym: '))
x=n
k=[]
while (n>0):
a=int(float(n%2))
k.append(a)
n=(n-a)/2
k.append(0)
string=""
for j in k[::-1]:
string=string+str(j)
print('Liczba ',n,"w systemie binarnym wynosi: ",string) |
n = int(input("Podaj liczbe n: "))
x = int(input("Podaj początek zakresu: "))
y = int(input("Podaj koniec zakresu: "))
def sprawdzanie(n,x,y):
if n>x and n<y:
print("Liczba mieści sie w zakresie")
else:
print("Liczba nie mieści się w zakresie")
sprawdzanie(n,x,y) |
x = int(input("Podaj liczbę: "))
if x%2==0:
print("Liczba jest parzysta")
else:
print("Liczba jest nie parzysta") |
from ascii_art import print_hello
print_hello("making your own game board")
a=' ---'
b='| '
c="|"
size=input("How big do you want your game board? Use commas to tell x and y apart (x,y): ")
size2=size.split(',')
x=int(size2[0])
y=int(size2[1])
with open('gameboard.txt','w') as file:
for i in range(y):
file.write(a*x+'\n')
file.write(b*x+c+'\n')
file.write(a*x+'\n')
|
a=[]
b=[]
l=[]
print('Digit the elements of the 1st list one by one. Press "." when you are done: ')
while True:
c=input()
if c!=".":
a.append(c)
elif c==".":
break
print('Digit the elements of the 2nd list one by one. Press "." when you are done: ')
while True:
d=input()
if d!=".":
b.append(d)
elif d==".":
break
for i in (a) and (b):
if i in a and b:
l.append(i)
print("The values common to both lists are: "+str(l))
input()
|
from datetime import datetime, time, timedelta
import sys
import pytube
def is_time_between(begin_time, end_time, check_time=None):
# If check time is not given, default to current UTC time
check_time = check_time or datetime.utcnow().time()
if begin_time < end_time:
return check_time >= begin_time and check_time <= end_time
else: # crosses midnight
return check_time >= begin_time or check_time <= end_time
def yt(url):
youtube = pytube.YouTube(url)
video = youtube.streams.get_highest_resolution()
print(video.title)
print("start downloading")
#video.download()
print("downloaded")
def download():
for x in sys.argv[1:]:
yt(x)
# Original test case from OP
a=is_time_between(time(18,30), time(2,30)) #sri Lanka
print(datetime.utcnow().time())
print(a)
print("waiting for 00:00:00")
while 1:
if a: #remove not
print("Time is 00:00:00")
download()
break
|
import time,random
import numpy as np
from math import factorial
import matplotlib.pylab as plt
def dise(trials,N,p):
histogram = np.zeros(N+1 , int)
sum = 0.0
j=0
r=0
while j < trials :
sum = 0
for i in range(N):
rd=random.random()
if(rd<p):
sum+=1
histogram[sum] = histogram[sum] + 1
j=j+1
probability=histogram/float(np.sum(histogram))
return probability
def mean(probability):
sum=0.
for i in range(len(probability)):
sum+=i*probability[i]
return sum
def var(probability):
sum=0.
m=mean(probability)
for i in range(len(probability)):
sum+=((i-m)**2)*probability[i]
return sum
def Gaussian(n,N,p):
value = 1.0/(2*np.pi*p*(1-p)*N)**0.5
value = value*np.e**(-((n-p*N)**2)/(2*p*(1-p)*N))
return value
def predict(N,p):
def Gaussian_probability(N,p):
probability=np.zeros(N+1,float)
for i in range(N+1):
probability[i]=Gaussian(i,N,p)
return probability
probability=Gaussian_probability(N,p)
m=mean(probability)
v=var(probability)
return m,v,probability
print("question one,two,three:\n")
trials = 100000
example=[[10,0.5],[30,0.85],[150,0.03]]
times=0
for N,p in example:
prediction=predict(N,p)
t1=time.clock()
result=dise(trials,N,p)
t2=time.clock()
print(" trials =",trials," number of dise =",N," probability =",p," times =",t2-t1)
print(" prediction:")
print(" mean:",prediction[0])
print(" variance:",prediction[1])
print(" standard deviation:",(prediction[1])**0.5)
print(" experiment:")
print(" mean:",mean(result))
print(" variance:",var(result))
print(" standard deviation:",(var(result))**0.5)
print(" result : experiment results are simlar to prediction answers\n")
plt.subplot(321+times)
times+=1
plt.title("Probability Distribution")
plt.xlabel("value one times")
plt.ylabel("probability")
plt.plot(range(N+1),prediction[2],color="blue",label="experimental")
plt.plot(range(N+1),result,color="green",label="theoretical")
plt.legend()
plt.subplot(321+times)
times+=1
plt.title("Deviations of Probability")
plt.xlabel("value one times")
plt.ylabel("error of probability")
plt.plot(range(N+1),abs(result-prediction[2]))
plt.tight_layout()
plt.show()
|
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(left) + middle + quicksort(right)
print(quicksort([3,6,8,10,1,2,1]))
xs = [3,1,2]
print(xs, xs[2])
print(xs[-1])
xs[2] = 'foo'
print(xs)
xs.append('bar')
print(xs)
x = xs.pop() #remove and return the last element of the list
print(x, xs)
nums = list(range(5))
print(nums)
print(nums[2:4])
print(nums[2:])
print(nums[:2])
print(nums[:]) # Get a slice of the whole list
nums[2:4] = [8, 9]
print(nums)
animals = ['cat', 'dog', 'monkey']
for animal in animals:
print(animal)
for idx, animal in enumerate(animals):
print('#%d: %s' % (idx + 1, animal))
#list comprehensions
nums = [0, 1, 2, 3, 4]
squares = []
for x in nums:
squares.append(x ** 2)
print(squares)
nums = list(range(5))
even_squares = [x ** 2 for x in nums if x % 2 == 0]
print(even_squares)
#dictionaries
d = {'cat': 'cute', 'dog': 'furry'}
print(d['cat'])
print('cat' in d) #check if a dic has a given key; prints "True"
d['fish'] = 'wet'
print(d['fish'])
print(d.get('monkey', 'N/A')) #Get an element with a default: prints "N/A"
print(d.get('fish', 'N/A')) #Get an element with a default: prints "wet"
del d['fish']
print(d.get('fish', 'N/A'))
d = {'person': 2, 'cat': 4, 'spider': 8}
for animal in d:
legs = d[animal]
print('A %s has %d legs' % (animal, legs))
nums = [0, 1, 2, 3, 4]
even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}
print(even_num_to_square)
#Sets
#a set is an unordered collection of distinct elements. As a simple example, consider the following:
animals = {'cat', 'dog'}
print('cat' in animals)
print('fish' in animals)
animals.add('fish')
print('fish' in animals)
print(len(animals))
animals.add('cat') #adding an element that is already in the set does nothing
animals.remove('cat')
print(len(animals))
animals = {'cat', 'dog', 'fish'}
for idx, animal in enumerate(animals):
print('#%d: %s' % (idx + 1, animal))
from math import sqrt
nums = {int(sqrt(x)) for x in range(30)}
print(nums)
#Tuples
d = {(x, x + 1): x for x in range(10)}
t = (5, 6)
print(type(t))
print(d)
print(d[t])
print(d[(1, 2)]) |
class Personne:
"""docstring for Personne."""
def __init__(self, nom, prenom):
self.nom = nom
self.prenom = prenom
self.compte_bancaire = None
def creer_compte_bancaire(self):
self.compte_bancaire = CompteBancaire(self.nom)
def depot(self, somme):
self.compte_bancaire.depot(somme)
def solde(self):
self.compte_bancaire.affiche();
def retrait(self,somme):
self.compte_bancaire.retrait(somme)
class CompteBancaire:
def __init__(self,nom='Dupont'):
""" creation du constructeur de la classe avec les valeurs par defaut 'Dupont' et 0 """
self.nom=nom
self.solde=0
def depot(self,somme):
""" ajout d'une somme a l'attribut solde """
self.solde+=somme
def retrait(self,somme):
""" retrait d'une somme a l'attribut solde """
self.solde-=somme
def affiche(self):
""" L'affichage des informations d'un compte"""
print("Le solde du compte bancaire de %s est de %.2f euros."%(self.nom,self.solde))
|
# Даны два целых числа A и В. Выведите все числа от A до B включительно, в порядке возрастания, если A < B,
# или в порядке убывания в противном случае.
a = int(input())
b = int(input())
s = 0
p = 0
if a < b:
s = 0
for s in range(a, b + 1):
print(s)
else:
for s in range(a, b - 1, -1):
print(s)
|
print('Даны три целых числа. Определите, сколько среди них совпадающих. Программа должна вывести одно из чисел: 3 (если все совпадают), 2 (если два совпадает) или 0 (если все числа различны).')
a = int(input())
b = int(input())
c = int(input())
x = 0
if a == b:
x += 2
if b == c:
x += 2
if c == a:
x += 2
if a == b == c:
x = 3
print(x) |
# Последовательность Фибоначчи определяется так:
# φ0 = 0, φ1 = 1, φn = φn−1 + φn−2.
# По данному числу n определите n-е число Фибоначчи φn.
# Эту задачу можно решать и циклом for.
n = int(input())
x, y, z = 0, 1, 1
if n == 0:
z = 0
else:
i = 1
for i in range(1, n):
z = x + y
x, y = y, z
i += 1
print(z)
|
# Последовательность состоит из натуральных чисел и завершается числом 0.
# Определите значение наибольшего элемента последовательности.
s, d, f = 0, 0, 0
while True:
s = input()
if s == '0':
break
if int(s) > int(d):
d = s
print(d)
|
# Дана строка. Замените в этой строке все появления буквы h на букву H, кроме первого и последнего вхождения.
s = input()
a = s.find('h')
b = s.rfind('h')
print(s[:a+1] + s[a+1:b].replace('h', 'H') + s[b:]) |
from math import ceil
a = int(input())#рубли
b = int(input())#копейки
n = int(input())#кол-во пирожков
x = n*(a*100 + b)
print(int(x//100), (x%100)) |
# Дано натуральное число A. Определите, каким по счету числом Фибоначчи оно является, то есть выведите такое число n,
# что φn = A. Если А не является числом Фибоначчи, выведите число -1.
a = int(input())
x, y, z = 0, 1, 1
i = 1
while a > z:
z = x + y
x, y = y, z
i += 1
if a == z:
print(i)
elif a < z:
print(-1) |
# Задача «Количество элементов, которые больше предыдущего»
s, d, i = 0, 0, 0
d = input()
while True:
s = input()
if s == '0':
break
if int(s) > int(d):
i += 1
d = s
print(i) |
# Дана строка, состоящая ровно из двух слов, разделенных пробелом. Переставьте эти слова местами. Результат запишите в
# строку и выведите получившуюся строку.
# При решении этой задачи не стоит пользоваться циклами и инструкцией if.
s = input()
x = int(s.find(' '))
print(s[x+1:], s[:x])
|
def OneDollarGame():
p = int(input("Enter # of pennies: "))
n = int(input("Enter # of nickels: "))
d = int(input("Enter # of dimes: "))
q = int(input("Enter # of quarters: "))
total = p + 5 * n + 10 * d + 25 * q
if total == 100:
print ("Congrats, you won 'One Dollar' Game!")
elif total > 100:
print ("Sorry it's more than a Dollar")
else:
print ("Sorry it's less than a dollar")
|
myInput = (2, 123.4567, 10000)
print("file_00{} , floatr2: ,{:.2f}, center15,{:>15.2e}".format(myInput[0], myInput[1], myInput[2]))
for x in range(1):
myTuple = (float(input("what is age")),str(input("what is your name")),float(input("what was your age last year")))
print("the first 3 numbers are: {:$< 8.2f}, {:&^12s}, {:*>+12.2f}".format(*myTuple))
# the ^<> mean center right or left justify with a column width of that many numbered spaces
# e = scientific notation, d = decimal to the digits you specify, s = string and g=
''' see 7.1.3.1. Format Specification Mini-Language:
https://docs.python.org/2.6/library/string.html#formatstrings
The general form of a standard format specifier is:
format_spec ::= [[fill]align][sign][#][0][width][.precision][type]
fill ::= <a character other than '}'>
align ::= "<" | ">" | "=" | "^"
sign ::= "+" | "-" | " "
width ::= integer
precision ::= integer
type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
''' |
# Week 7 - Lab #1: HTML Renderer Exercise
# Date: Friday, February 19, 2016
# Student: Chi Kin Ho
# !/usr/bin/env python
"""
Python class example.
"""
# The start of it all:
# Fill it all in here.
class Element(object):
tag = 'html' # class attribute
level = 1 # indentation level
def __init__(self, content=None, **kwargs):
# Initialize the Element object with the given content.
if content is None:
self.content = list()
else:
self.content = [content]
if kwargs is not None:
if 'style' in kwargs:
self.style = kwargs['style']
else:
self.style = None
if 'id' in kwargs:
self.id = kwargs['id']
else:
self.id = None
def append(self, new_content):
# Append the new_content to the end of the existing content.
self.content.append(new_content)
def render(self, file_out, ind=""):
file_out.write(ind * Element.level + '<' + self.tag)
if self.style is not None:
file_out.write(' ' + 'style="' + self.style + '"')
if self.id is not None:
file_out.write(' ' + 'id="' + self.id + '"')
file_out.write('>\n')
for content in self.content:
if isinstance(content, str): # Stop the recursion when content is of string.
file_out.write(ind * (Element.level + 1) + content + '\n')
else: # Recursively call render() to print the tag element.
Element.level += 1
content.render(file_out, ind)
Element.level -= 1
file_out.write(ind * Element.level + '</' + self.tag + '>')
if self.tag != 'html':
file_out.write('\n')
class Html(Element):
tag = 'html' # Override the Element's class attribute with html
def render(self, file_out, ind=""):
file_out.write('<!DOCTYPE html>' + '\n')
Element.render(self, file_out, ind)
class Body(Element):
tag = 'body' # Override the Element's class attribute with body
class P(Element):
tag = 'p' # Override the Element's class attribute with p
class Head(Element):
tag = 'head' # Override the Element's class attribute with head
class OneLineTag(Element):
def render(self, file_out, ind=""):
file_out.write(ind * Element.level + '<' + self.tag + '>')
file_out.write(' ' + self.content[0] + ' ')
file_out.write('</' + self.tag + '>' + '\n')
class Title(OneLineTag):
tag = 'title' # Override the OneLineTag's class attribute with title
class SelfClosingTag(Element):
def render(self, file_out, ind=""):
file_out.write(ind * Element.level + '<' + self.tag + ' />' + '\n')
class Hr(SelfClosingTag):
tag = 'hr' # Override the SelfClosingTag's class attribute with hr
class Br(SelfClosingTag):
tag = 'br' # Override the SelfClosingTag's class attribute with br
class Meta(SelfClosingTag):
tag = 'meta' # Override the SelfClosingTag's class attribute with meta
def __init__(self, **kwargs):
Element.__init__(self, None)
if 'charset' in kwargs:
self.charset = kwargs['charset']
def render(self, file_out, ind=""):
file_out.write(ind * Element.level + '<' + self.tag + ' charset="' + self.charset + '" />' + '\n')
class A(Element):
tag = 'a' # Override the Element's class attribute with a
def __init__(self, link, content=None):
Element.__init__(self, content)
self.link = link # Store the hyperlink of the anchor tag.
def render(self, file_out, ind=""):
file_out.write(ind * Element.level + '<' + self.tag + ' href="' + self.link + '">')
for content in self.content:
if isinstance(content, str): # Stop the recursion when content is of string.
file_out.write(' ' + content + ' ')
else: # Recursively call render() to print the tag element.
Element.level += 1
content.render(file_out, ind)
Element.level -= 1
file_out.write('</' + self.tag + '>\n')
class Ul(Element):
tag = 'ul' # Override the Element's class attribute with ul
class Li(Element):
tag = 'li' # Override the Element's class attribute with li
class H(OneLineTag):
tag = 'h' # Override the OneLineTag's class attribute with h2
def __init__(self, size, content=None, **kwargs):
self.tag += str(size) # Add the size of the header to the tag name
Element.__init__(self, content, **kwargs)
|
# this is a re-do of the slicing lab to make sure I did it
'''
return a sequence with the first and last items exchanged.
return a sequence with every other item removed
return a sequence with the first and last 4 items removed, and every other item in between
return a sequence reversed (just with slicing)
return a sequence with the middle third, then last third, then the first third in the new order
'''
x = ("1234567890 I went to the store only Monday abcdefghijklmnopqrstuvwxyz12")
print(x)
x_switchfirstnlast = x[-1:]+x[1:-2]+x[0:1]
print(x_switchfirstnlast)
x_every_other_removed = x[::2]
print(x_every_other_removed)
x_mid_with_missing_mid = x[4:-4:2]
print(x_mid_with_missing_mid)
x_reversed = x[::-1]
print(x_reversed)
thirds = (len(x)//3)
leftover = (len(x)%3)
print(thirds,"\n",leftover)
x_mid_last_first_thirds = x[(thirds):(-thirds)]+ " *|* " + x[(-thirds):] + " *|* " + x[:(thirds)]
print(x_mid_last_first_thirds)
|
def size_func(fib, lfib):
if fib % 2 == 0:
size = 'medium'
else:
if lfib % 2 == 0:
size = 'large'
else:
size = 'small'
return size
def list_pop(fib_list, size_list):
list_len = len(fib_list)
for i in range(3):
indx = i + list_len
fib_list.append(fib_list[indx - 2]+fib_list[indx - 1])
size_list.append(size_func(fib_list[indx], fib_list[indx - 1]))
return fib_list[list_len:], size_list[list_len:]
def hand_weapon():
fib_list = list(range(2))
size_list = []
for i in range(3):
fib_list.append(fib_list[i]+fib_list[i+1])
size_list.append(size_func(fib_list[i + 2], fib_list[i + 1]))
return fib_list[2:], size_list
def gun():
fib_list, size_list = hand_weapon()
return list_pop(fib_list, size_list)
def flower_power():
fib_list, size_list = gun()
return list_pop(fib_list, size_list)
def score(weapon_type, weapon_size):
fib_list, size_list = weapon_type()
return fib_list[size_list.index(weapon_size)]
|
"""mailroom.py
Deana Holmer
Practice with Dictionaries, User Input and Strings"""
# one way to populate tuple-like dictionary with initial values
donors = \
{ 'Chuck': [100,200,300],
'Mary': [50],
'Todd': [50,100],
'Janet': [200,300],
'Bob': [10,20,30]
}
# alternate method
menu = {}
menu ['1']="Send a Thank You"
menu ['2']="Create a Report"
def main_menu(menu):
"""Print main menu and return selection."""
for option in sorted(menu.keys()):
print ("{}: {}".format(option, menu[option]))
return(input('Select option> '))
def donor_menu(donors):
"""Print donor menu and return selected name. Print donor list. Add new donor to list. Return name."""
name=input("Select donor> ")
if name.lower() == 'list':
name=input("Select donor: {} > ".format(sorted(donors.keys())))
if name not in donors.keys():
donors.setdefault(name, None)
return(name)
def donate(donor_name, donors):
"""Get donation amount from user and add to donor dictionary. Return amount."""
amt=""
while not amt.isdigit():
amt=input("Donation amount> ")
donors[donor_name].append(int(amt))
return(amt)
def thanks (donor_name, donation_amt):
"""Generate thank you letter for donation. Return text."""
return ("\nDear {}.\n\tThank you for your donation of ${}. \nSincerely,\n\tUs\n".format(donor_name, donation_amt))
def report(donor_name,donations):
"""Generate donor report"""
ttl= sum(amt for amt in donations)
cnt= len(donations)
avg= int(ttl/cnt)
return "{}\t{}\t{}\t{}".format(donor_name, ttl, cnt, avg)
if __name__ == '__main__':
"""Present Main Menu and Perform Requested Actions."""
while True:
option=main_menu(menu)
if option== '1':
donor_name= donor_menu(donors)
donation_amt=donate(donor_name, donors)
print(thanks(donor_name, donation_amt))
elif option=='2':
print("Name\tTotal\tNum\tAvgAmt")
for donor_name in donors.keys():
print(report(donor_name, donors[donor_name]))
else:
break
|
#!/usr/bin/python3.4
'''
#########################################################################
SECTION 1 OF LIST LAB
#########################################################################
#1 Create a list that contains “Apples”, “Pears”, “Oranges” and “Peaches”
#2 Display the list
#3 Ask the user for another fruit and add it to the end of the list
#4 Display the list
#5 Ask the user for a number and display the number back to the user and
the fruit corresponding to that number (on a 1-is-first basis)
#6 Add another fruit to the beginning of the list using “+” and display the list
#7 Add another fruit to the beginning of the list using insert() and display the list
#8 Display all the fruits that begin with “P”, using a for loop
'''
#1
fruit = ["Apples", "Pears", "Oranges", "Peaches"]
#2
print(fruit)
#3
new_fruit = input("Add another fruit to list\n")
fruit.append(new_fruit)
#4
print(fruit)
#5
#Add an error handler so that user has to input a valid list index
index_check = None
while index_check is None:
try:
get_num = int(input("Select a number from 1 to " + str(len(fruit)) + " inclusive\n"))
print(get_num, " ", fruit[get_num - 1])
index_check = True
except:
print("Invalid index number try again")
#6
new_fruit = [input("Add another new fruit to list\n")]
fruit = new_fruit + fruit
print("List with ", new_fruit[0],"\n", fruit)
#7
new_fruit = input("Add another fruit to list\n")
fruit.insert(0,new_fruit)
print("List with ", new_fruit,"\n", fruit)
#8
#create empty list to hold values that will be populated in loop below
p_fruits = []
#loop over each fruit in list and determine if fruit starts with p (not case sensitive)
for item in fruit:
if item[0].lower() == "p":
p_fruits.append(item)
print("List of fruits that start with P\n", p_fruits)
'''
#########################################################################
SECTION 2 OF LIST LAB
#########################################################################
#9 Display the list.
#10 Remove the last fruit from the list.
#11 Display the list.
#12 Ask the user for a fruit to delete and find it and delete it.
#13 Bonus: Multiply the list times two. Keep asking until a match is found.
Once found, delete all occurrences.)
'''
#9
print("Current fruit list\n", fruit)
#10
#creating a new list called fruit 2 based on list from section 1
fruit2 = list(fruit)
del fruit2[-1]
#11
print("Deleted the last item from list\n", fruit2)
#12
#Add an error handler so that user has to input a valid list index
index_check = None
while index_check is None:
try:
get_str = input("Type a fruit from current list to delete\n")
fruit2.remove(get_str)
index_check = True
except:
print("The fruit you typed in not in the list! Try again ")
print("You deleted ", get_str, "New list\n", fruit2)
#13 - Doing this on the deleted list from #12
'''
First while loop checks to see if fruit entered exists in list
If fruit does exist in list the loop through list until all instance of fruit is removed
If fruit does not exist in list then copy fruit list and append to existing list
'''
index_check = None #flag to determine if a valid fruit has been entered
while index_check is None:
get_str = input("Type the fruit from current list to delete\n")
if get_str in fruit2:
while get_str in fruit2:
fruit2.remove(get_str)
index_check = True #set flag to True to quit valid fruit loop
else:
fruit2_copy = list(fruit2)
fruit2 = fruit2_copy + fruit2_copy
print("The fruit you typed in not in the list so I doubled the list! Try again ")
print(fruit2)
print("You deleted ", get_str,"\n", fruit2)
'''
#########################################################################
SECTION 3 OF LIST LAB
#########################################################################
#14 Ask the user for input displaying a line like “Do you like apples?”
#15 Display the list.
'''
#14
for item in fruit:
'''
For each item in fruit list prompt a response from user
If reponse is not yes or no then retry
Else if no then remove item from list
'''
response = input("Do you like " + item.lower() + " ?\n")
while response.lower() not in ["yes", "no"]:
print("You didn't answer Yes or No! Try again. ")
response = input("Do you like " + item.lower() + " ?\n")
if response == 'no':
fruit.remove(item)
#15
print(fruit)
'''
#########################################################################
SECTION 4 OF LIST LAB
#########################################################################
#16 Make a copy of the list and reverse the letters in each fruit in the copy.
#17 Delete the last item of the original list. Display the original list and the copy.
'''
#16
fruit_copy = list(fruit)
for item in fruit_copy[:]:
item_flip = item[::-1]
fruit_copy.remove(item)
fruit_copy.append(item_flip)
#17
del fruit[-1]
print(fruit)
print(fruit_copy)
|
#!/usr/bin/python
#Author:kbindhu
#Date:1/27/2016
#ROT13 encryption
"""Below program takes any amount of text and returns the text with each letter replaced
by letter 13 away from it."""
"""Algorithm is to convert each letter in the input text to ascii code with ord function.
Then for alphabets a-m and A-M add 13 to ascii values and for n-z and N-Z subtract 13 from ascii values.All other
characters are printed like space are printed as such"""
import codecs
def rot13( myString):
out_str=''
for i in myString:
encp=ord(i)
"""checking that ascii corresponds to alaphbets a-m or A-M add 13 to it and find the corresponding letter"""
if(97<=encp<110) or (65<=encp<78):
encp=encp+13
#print(chr(encp),end='')
out_str+=chr(encp)
"""if ascii corresponds to alphabets above m subtract 13 from the ascii and findcorresponding letter"""
elif(110<=encp<=122) or(78<=encp<=90):
encp =encp-13
#print(chr(encp),end='')
out_str+=chr(encp)
else:
#print(i,end='')
out_str+=chr(encp)
return out_str
#Test block
if __name__ == '__main__':
print("Main module is being run directly ")
Myoutstrng=rot13("Hello")
#using the rot_13 algorithm to test my code
assert (Myoutstrng) == codecs.encode('Hello', 'rot_13')
Myoutstrng=rot13("Zntargvp sebz bhgfvqr arne pbeare")
assert (Myoutstrng) == codecs.encode('Zntargvp sebz bhgfvqr arne pbeare', 'rot_13')
Myoutstrng=rot13("Zntargvpjij**")
assert(Myoutstrng)=='deewhuhfu',"Asssertion Error,Expected is :%s" %codecs.encode('Zntargvpjij**', 'rot_13')
else:
print("rot_13.py is being imported into another module ")
# nicely done!
|
#!/usr/bin/python3
#Open the students file
language_dict = {}
with open("students.txt", "r") as f:
for line in f:
# Split on full name (given by ':')
name = line.split(":")[0]
languages = line.split(":")[1]
# Convert the languages into a list
languages = languages.split(",")
# Clean up white space from around language string items post strip
for idx, lang_line in enumerate(languages[:]):
languages[idx] = lang_line.strip()
# Filter for empty language lists
if len(languages[0]) == 0:
continue
# Loop over the languages specified and if they are not present
# then add them to the dict with a count of 1. If they are present,
# increment the count
for language in languages:
if language not in language_dict:
language_dict[language] = 0
language_dict[language] = language_dict[language] + 1
# Print the list of languages and how many times it was seen
for k, v in language_dict.items():
print ("{0:>12}:{1:>5}".format(k, v)) |
# return sequence with last and first items changed
seq1 = [4,5,6,7,8,9]
temp = seq1[0]
length = len(seq1)
temp1 = seq1[length-1]
print("original sequence",seq1)
seq1.pop(0)
seq1.pop(length-2)
print("sequence with first and last element removed",seq1)
seq1.append(temp)
seq1.insert(0,temp1)
print("sequence with the first and last items exchanged",seq1)
|
def enterACoin (coinName):
numberOfCoins = input("Enter the number of "+coinName+":")
try:
int(numberOfCoins)
return int(numberOfCoins)
except:
print("Please enter an integer")
return enterACoin(coinName)
def isADollar(pennies, nickels, dimes, quarters):
value = pennies*.01+nickels*.05+dimes*.1+quarters*.25
return value
input("Try to enter a combination of coins that equals exactly $1. Press Enter to continue:")
pennies = enterACoin("Pennies")
nickels = enterACoin("Nickels")
dimes = enterACoin("Dimes")
quarters = enterACoin("Quarters")
value = isADollar(pennies=pennies, nickels = nickels, dimes = dimes, quarters = quarters)
if(value == 1.0):
print("Congratualations, you win!")
elif(value > 1.0):
print("That adds up to "+str(value)+" which is greater than a dollar. You lost!")
elif(value < 1.0):
print("That adds up to "+str(value)+" which is less than a dollar. You lost!")
|
#define trapez function
"""Compute the area under the curve defined by
y = fun(x), for x between a and b
:param fun: the function to evaluate
:type fun: a function that takes a single parameter
:param a: the start point for teh integration
:type a: a numeric value
:param b: the end point for the integration
:type b: a numeric value"""
def trapz(func,a,b,**kwargs):
N=100
sum=0
for i in range (1,N):
i=i/10
sum = sum+func(a+i*(b-a)/N,**kwargs)
midpoint=(func(a,**kwargs)+func(b,**kwargs))/2
area=(b-a)/N*(midpoint+sum)
return area
|
# Write a program that prints the numbers from 1 to 100 inclusive.
# for multiples of three print “Fizz” instead of number
# For multiples of five print “Buzz”.
# multiples of both three and five print “FizzBuzz”
for i in range(1, 101):
if i % 3 == 0 and i % 5 == 0:
print('FizzBuzz')
elif i % 3 == 0:
print('Fizz')
elif i % 5 == 0:
print('Buzz')
else:
print(i)
|
def trapz(fun, a, b, num_steps, **kwargs):
"""
Compute the area under the curve defined by
y = fun(x), for x between a and b
:param fun: the function to evaluate
:type fun: a function that takes a single parameter
:param a: the start point for the integration
:type a: a numeric value
:param b: the end point for the integration
:type b: a numeric value
:param num_steps: The number of integratiion steps to undertake.
:type num_steps: a numeric integer value
:param kwargs: Arguments passed to 'fun' when calling 'fun'
:type kwargs: Keyword arguments
"""
STEP_SIZE = (b-a)/num_steps
sum = 0
for i in range(0, num_steps):
left = a + (i * STEP_SIZE)
right = a + ((i+1) * STEP_SIZE)
sum += fun(left, **kwargs) + fun(right, **kwargs)
sum = sum * STEP_SIZE / 2
return sum
|
# print out the numbers from 1 to n, but replace numbers divisible by 3 with "Fizz",
# numbers divisible by 5 with "Buzz". Numbers divisible by both factors should display "FizzBuzz.
# The function should be named FizzBuzz and be able to accept a natural number as argument
def FizzBuzz(n):
for i in range(n): #since the assignment says 'from 1 to 100 inclusive, how can you change range to include the number 100?
a = ""
if (i+1)%3 == 0: # what is the +1 used for here?
print("Fizz", end="")
a = "true"
if (i+1)%5 == 0: # to run multiple 'if statments' in one function, use elif
print("Buzz",end="")
a = "true"
if a == "true":
print("")
else:
print(i+1)
FizzBuzz(100)
|
import math
class Circle(object):
@classmethod
def from_diameter(cls, diameter):
return cls(diameter/2)
def __init__(self, radius):
self.r = radius
@property
def radius(self):
return self.r
@radius.setter
def radius(self, val):
self.r = val
@property
def diameter(self):
return 2 * self.r
@diameter.setter
def diameter(self, val):
self.r = val / 2
@property
def area(self):
return 2 * math.pi * self.r
def __repr__(self):
return 'Circle({})'.format(self.r)
def __str__(self):
return 'Circle with radius: {:6f}'.format(self.r)
def __add__(self, other):
if isinstance(other, Circle):
return Circle(self.r + other.r)
else:
raise ValueError("The other parameter must be a circle type")
def __iadd__(self, other):
if isinstance(other, Circle):
self.r += other.r
return self
else:
raise ValueError("The other parameter must be a circle type")
def __radd__(self, other):
return self.__add__(other)
def __mul__(self, other):
if isinstance(other, int):
return Circle(self.r * other)
else:
raise ValueError("The other parameter must be an int")
def __imul__(self, other):
if isinstance(other, int):
self.r *= other
return self
else:
raise ValueError("The other parameter must be an int")
def __rmul__(self, other):
return self.__mul__(other)
def __gt__(self, other):
if isinstance(other, Circle):
return self.r > other.r
else:
raise ValueError("The other parameter must be a circle type")
def __eq__(self, other):
if isinstance(other, Circle):
return self.r == other.r
else:
raise ValueError("The other parameter must be a circle type")
|
#!/usr/bin/env python3
total = 0
print("Please input the number of...")
pennies = int(input(" " * 4 + "pennies: "))
total += pennies
nickels = int(input(" " * 4 + "nickels: "))
total += nickels * 5
dimes = int(input(" " * 4 + "dimes: "))
total += dimes * 10
quarters = int(input(" " * 4 + "quarters: "))
total += quarters * 25
if total == 100:
print("Congratulations! You have exactly $1!")
elif total > 100:
print("Sorry, you have too many coins to make exactly $1")
else:
print("Sorry, you only have {}¢".format(total))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.