text
stringlengths 37
1.41M
|
---|
class InvSet:
"""
Inverse Set: a set which contains all values _except_ those specified.
Interoperable with builtin `set` and `frozenset` classes wherever possible.
Is not iterable: how would you iterate all values??
"""
def __new__(self, iterable=()):
if isinstance(iterable, InvSet):
return set(iterable._excluded)
return super().__new__(self)
def __init__(self, iterable=()):
self._excluded = set(iterable)
def __contains__(self, value):
return value not in self._excluded
def __invert__(self):
return set(self._excluded)
def __sub__(self, other):
return InvSet(self._excluded | other)
def __rsub__(self, other):
return other & self._excluded
def __and__(self, other):
return other - self._excluded
def __rand__(self, other):
return self & other
def __or__(self, other):
return InvSet(self._excluded - other)
def __ror__(self, other):
return self | other
def __xor__(self, other):
return InvSet(self._excluded ^ other)
def __rxor__(self, other):
return self ^ other
def __lt__(self, other):
if isinstance(other, (set, frozenset)):
return False
if not isinstance(other, type(self)):
return NotImplemented
return self._excluded > other._excluded
def __gt__(self, other):
if isinstance(other, (set, frozenset)):
return self._excluded.isdisjoint(other)
if not isinstance(other, type(self)):
return NotImplemented
return self._excluded < other._excluded
def __le__(self, other):
return self < other or self == other
def __ge__(self, other):
return self > other or self == other
def isdisjoint(self, other):
if isinstance(other, InvSet):
return False
return not any(value in self for value in other)
def __repr__(self):
return f"{type(self).__name__}({self._excluded})"
def __eq__(self, other):
if not isinstance(other, type(self)):
return NotImplemented
return self._excluded == other._excluded
def copy(self):
return InvSet(self._excluded)
def add(self, elem):
self._excluded.discard(elem)
def remove(self, elem):
if elem in self._excluded:
raise KeyError(elem)
self._excluded.add(elem)
def discard(self, elem):
self._excluded.add(elem)
# ---
import pytest
def test_cloney():
s = {3, 4}
inv = InvSet(s)
s.add(5)
assert inv == InvSet({3, 4})
def test_in():
assert 2 in InvSet({3, 4})
def test_not_in():
assert 3 not in InvSet({3, 4})
def test_negate():
values = {1, 2, 3}
invset = InvSet(values)
assert ~invset == values
@pytest.mark.parametrize("left,right,expected", [
({1, 2, 3}, InvSet({1, 2, 4}), {1, 2}),
(InvSet({1, 2, 4}), {1, 2, 3}, InvSet({1, 2, 3, 4})),
(InvSet({1, 2}), InvSet({2, 3}), {3}),
])
def test_sub(left, right, expected):
assert left - right == expected
@pytest.mark.parametrize("left,right,expected", [
({1, 2, 3}, InvSet({1, 2, 4}), {3}),
(InvSet({4, 5, 6}), {5, 6, 7, 8}, {7, 8}),
(InvSet({4, 5, 6}), InvSet({6, 7, 8}), InvSet({4, 5, 6, 7, 8})),
])
def test_and(left, right, expected):
assert left & right == expected
@pytest.mark.parametrize("left,right,expected", [
({1, 2, 4}, InvSet({1, 2, 3}), InvSet({3})),
(InvSet({4, 5, 6}), {5, 6, 7, 8}, InvSet({4})),
(InvSet({4, 5, 6}), InvSet({6, 7, 8}), InvSet({6})),
])
def test_or(left, right, expected):
assert left | right == expected
@pytest.mark.parametrize("left,right,expected", [
(InvSet({1, 2, 3}), {2, 3}, True),
(InvSet({1, 2, 3}), {2, 4}, False),
# can't really monkeypatch `set` :(
# ({2, 3}, InvSet({1, 2, 3}), True),
# ({2, 4}, InvSet({1, 2, 3}), False),
(InvSet({1, 2, 3}), InvSet({3, 4, 5}), False),
])
def test_isdisjoint(left, right, expected):
assert left.isdisjoint(right) == expected
@pytest.mark.parametrize("left,right,expected", [
({1, 2, 4}, InvSet({1, 2, 3}), InvSet({3, 4})),
(InvSet({4, 5, 6}), {5, 6, 7, 8}, InvSet({4, 7, 8})),
(InvSet({4, 5, 6}), InvSet({6, 7, 8}), {4, 5, 7, 8}),
])
def test_xor(left, right, expected):
assert left ^ right == expected
@pytest.mark.parametrize("left,right,expected", [
(InvSet({1, 2}), InvSet({3, 4}), False),
(InvSet({1, 2, 3, 4}), InvSet({2, 3}), True),
(InvSet({1, 2, 3}), InvSet({2, 3, 4}), False),
(InvSet({1, 2}), {3, 4}, False),
({3, 4}, InvSet({1, 2}), True),
(InvSet({1, 2}), InvSet({1, 2}), False),
])
def test_lt(left, right, expected):
assert (left < right) == expected
@pytest.mark.parametrize("left,right,expected", [
(InvSet({3, 4}), InvSet({1, 2}), False),
(InvSet({2, 3}), InvSet({1, 2, 3, 4}), True),
(InvSet({2, 3, 4}), InvSet({1, 2, 3}), False),
(InvSet({1, 2}), {3, 4}, True),
({3, 4}, InvSet({1, 2}), False),
(InvSet({1, 2}), InvSet({1, 2}), False),
])
def test_gt(left, right, expected):
assert (left > right) == expected
@pytest.mark.parametrize("left,right,expected", [
(InvSet({1, 2}), InvSet({3, 4}), False),
(InvSet({1, 2, 3, 4}), InvSet({2, 3}), True),
(InvSet({1, 2, 3}), InvSet({2, 3, 4}), False),
(InvSet({1, 2}), {3, 4}, False),
({3, 4}, InvSet({1, 2}), True),
(InvSet({1, 2}), InvSet({1, 2}), True),
])
def test_lte(left, right, expected):
assert (left <= right) == expected
@pytest.mark.parametrize("left,right,expected", [
(InvSet({3, 4}), InvSet({1, 2}), False),
(InvSet({2, 3}), InvSet({1, 2, 3, 4}), True),
(InvSet({2, 3, 4}), InvSet({1, 2, 3}), False),
(InvSet({1, 2}), {3, 4}, True),
({3, 4}, InvSet({1, 2}), False),
(InvSet({1, 2}), InvSet({1, 2}), True),
])
def test_gte(left, right, expected):
assert (left >= right) == expected
def test_copy():
inv1 = InvSet({1, 2, 3})
inv2 = inv1.copy()
assert inv1 is not inv2
assert inv1 == inv2
inv2.discard(4)
assert inv1 != inv2
@pytest.mark.parametrize("invset,value,expected", [
(InvSet({1, 2}), 2, InvSet({1})),
(InvSet({1, 2}), 3, InvSet({1, 2})),
])
def test_add(invset, value, expected):
invset.add(value)
assert invset == expected
def test_remove():
inv = InvSet({1, 2})
inv.remove(3)
assert inv == InvSet({1, 2, 3})
def test_bad_remove():
inv = InvSet({1, 2})
with pytest.raises(KeyError):
inv.remove(2)
@pytest.mark.parametrize("invset,value,expected", [
(InvSet({1, 2}), 2, InvSet({1, 2})),
(InvSet({1, 2}), 3, InvSet({1, 2, 3})),
])
def test_discard(invset, value, expected):
invset.discard(value)
assert invset == expected
@pytest.mark.parametrize("fn", [
lambda: InvSet({1, 2}) - 5,
lambda: 5 - InvSet({1, 2}),
lambda: InvSet({1, 2}) & 5,
lambda: 5 & InvSet({1, 2}),
lambda: InvSet({1, 2}) | 5,
lambda: 5 | InvSet({1, 2}),
lambda: InvSet({1, 2}) ^ 5,
lambda: 5 ^ InvSet({1, 2}),
lambda: InvSet({1, 2}) < 5,
lambda: 5 < InvSet({1, 2}),
lambda: InvSet({1, 2}) > 5,
lambda: 5 > InvSet({1, 2}),
lambda: InvSet({1, 2}) <= 5,
lambda: 5 <= InvSet({1, 2}),
lambda: InvSet({1, 2}) >= 5,
lambda: 5 >= InvSet({1, 2}),
])
def test_operator_type_error(fn):
with pytest.raises(TypeError) as exc:
fn()
|
def longest_palindrome(string):
if not string:
return 0
string_list = list('#{}#'.format('#'.join(string)))
p = [0 for _ in string_list]
m = n = c = r = 0
for i, elem in enumerate(string_list[1:], 1):
print p
if i > r:
p[i] = 0
m = i - 1
n = i + 1
else:
i_mirror = c * 2 - i
if p[i_mirror] < r - i:
p[i] = p[i_mirror]
m = -1 # fixme
else:
p[i] = r - i
n = r + 1
m = i * 2 - n
# Actually expand that palindrome
while m >= 0 and n < len(string_list) and string_list[m] == string_list[n]:
p[i] += 1
m -= 1
n += 1
if i + p[i] > r:
c = i
r = i + p[i]
c, ln = max(enumerate(p), key=lambda (x, y): y)
return ''.join(x for x in string_list[c - ln: c + ln + 1] if x != '#')
print longest_palindrome("cabcbabcbabcba")
|
import functools
class ExplainableResult:
"""
Object to fetch the result from an iterator, and optionally the explanation for that result.
See `yields_why` for usage.
"""
def __init__(self, iterator):
try:
self.result = next(iterator)
except StopIteration as exc:
self.result = exc.value
self._explain = None
self._iterator = iterator
def explain(self):
try:
return self._explain
except AttributeError:
try:
next(self._iterator)
except StopIteration as exc:
self._explain = exc.value
else:
raise RuntimeError("generator didn't stop") from None
return self._explain
def yields_why(fn):
"""
Decorator to wrap results from a generator function as `ExplainableResult`s.
This function should either `yield` a single result followed by the
`return` of an explanation, or should simply `return` a single result.
The results are returned as a `ExplainableResult`. The results are exposed
via `result`, and the explanations are _only_ loaded when `explain()` is called.
"""
@functools.wraps(fn)
def anon(*args, **kwargs):
return ExplainableResult(fn(*args, **kwargs))
return anon
if __name__ == '__main__':
@yields_why
def is_prime(num):
i = 2
while i * i <= num:
if num % i == 0:
yield False
break
i += 1
else:
return True
print("Ok fetchin explanation for", num, "starting at", i)
original_num = num
prime_factors = []
while i * i <= num:
while num % i == 0:
prime_factors.append(i)
num //= i
i += 1
if num != 1:
prime_factors.append(num)
return f"{original_num} is divisible by {', '.join(map(str, prime_factors))}"
is_51_prime = is_prime(51)
print(is_51_prime.result)
print(is_51_prime.explain())
print()
is_53_prime = is_prime(53)
print(is_53_prime.result)
print(is_53_prime.explain())
print()
is_3127_prime = is_prime(3127)
print(is_3127_prime.result)
print(is_3127_prime.explain())
|
# -*- coding: utf-8 -*-
class Field(object):
def __init__(self,pos,propert='empty'):
self.dic = {'empty':0,'dirt':1,'obstacle':2,'wall':3}
self.pos = pos
self.property = self.dic[propert]
self.visited = False
def setProperty(self,propert):
self.property = self.dic[propert]
def fieldVisited(self):
self.visited = True
def isVisited(self):
return self.visited
def isWall(self):
return self.property == 3
def isObst(self):
return self.property == 2
def isDirt(self):
return self.property == 1
def getField(self,pos):
if pos == self.pos:
return self
return None
def getPos(self):
return self.pos
def getProperty(self):
return self.property
def __contains__(self,item):
return item.pos == self.pos and self.property == item.property and self.visited == item.visited
def __str__(self):
return str(self.pos) + " " + str(self.property)
|
#!env /usr/bin/python
def add(a,b):
print(f"ADDING {a} + {b}")
return a+b
def substract(a,b):
print(f"SUBSTRACTING {a} - {b}")
return a-b
def multiply(a,b):
print(f"MULTIPLYING {a}*{b}")
return a*b
def divide(a,b):
print(f"DIVIDING {a}/{b}")
return a/b
print("Let's do some math with just functions!")
age = add(30,5)
height = substract(78,4)
weight = multiply(90,2)
iq = divide(100,2)
print(f"Age: {age},Height: {height}, Weight: {weight}, IQ: {iq}")
# A puzzle for the extra credit, type it in anyway.
print("Here is a puzzle.")
what = add(age,substract(height,multiply(weight,divide(iq,2))))
print("That becomes: ", what, "Can you do it by hand?")
print("Operatin: ", age+height-weight*iq/2);
|
# 变量和名字
# 给变量 cars 赋值
cars = 100
# 给变量 space_in_a_car 赋值
space_in_a_car = 4.0
# 给变量 drivers 赋值
drivers = 30
# 给变量 passengers 赋值
passengers = 90
# 计算 cars - drivers 的值
cars_not_driven = cars - drivers
# 给变量 cars_driven 赋 drivers 的值
cars_driven = drivers
# 计算 cars_driven * space_in_a_car 的值
carpool_capacity = cars_driven * space_in_a_car
# 计算 passengers / cars_driven 的值
average_passengers_per_car = passengers / cars_driven
print("There are", cars, "cars available.")
print("There are only", drivers, "drivers available.")
print("There will be", cars_not_driven, "empty cars today.")
print("we can transport", carpool_capacity, "people today.")
print("we have", passengers, "to carpool today.")
print("we need to put about", average_passengers_per_car, "in each car.")
|
# 阅读文件
# open():用于打开一个文件,创建一个 file 对象
# read():用于从文件读取指定的字节数,如果未给定或为负则读取所有。
# 导入 sys 的 argv 模块
from sys import argv
# 获取文件名
script, filename = argv
# 打开一个文件
txt = open(filename)
# 打印
print(f"Here's your file {filename}:")
# 读取文件字节数
print(txt.read())
# 打印
# print("Type the filename again:")
# # 用户输入
# file_again = input("> ")
#
# # 打开一个文件
# txt_again = open(file_again)
#
# # 读取文件字节数
# print(txt_again.read())
|
directions = ("south", "north", "west", "east", "center")
verbs = ("go", "kill", "eat", "run", "tell", "shoot", "sing", "love")
stops = ("the", "in", "of", "to", "via")
nouns = ("bear", "princess", "MissHei", "tiger", "dragon")
stuff = input("> ")
words = stuff.split()
sentence = []
for word in words:
if word in directions:
sentence.append(word)
elif word in verbs:
sentence.append(word)
elif word in stops:
sentence.append(word)
elif word in nouns:
sentence.append(word)
if not sentence:
print("输入错误!")
else:
print(sentence)
|
# Program to grab a file and alphabetize its contents, creating a new .txt file
# with everything alphabetized.
name = input('Enter name of file to be alphabetized:') # Input function in python prints out a statement for the user to read, then allows them to input characters, which is returned as a string.
# Variable declaration in Python is done simply by [name of variable] = [data of variable]. This is unlike most other programming languages,
#which need a type declaration before the name of the variable or setting its data.
with open(name) as f: # Opening a file requires the name in the form of a string. There is the option to specify whether one is reading or writing, but
#leaving the second argument blank (ie not specifying at all) will make it default to read-only. It is considered better to put the usage of a
#file in a with statement, so it will close when the statement is finished regardless of errors.
a = f.read() # 'a' is now a copy of the file object, which can be edited in this form.
aList = sorted(a) # aList is a sorted, alphabetically and by case, list of the file.
try: # A code block intended to remove newline characters and whitespaces from the list of characters.
while True: # 'while True:' is an infinite loop, which is not exactly "good programming practice", but in the event
#that one needs a program to continuously iterate unless an error occurs, it works. Since I use 'try:' instead of
#just having the infinite loop, if a ValueError exception is caught, then the loop terminates. This is akin to,
#perhaps, setting a while loop with a condition of throwing an error, but that isn't a possibility- at least
#in Python.
aList.remove('\n')
except ValueError:
pass
try:
while True:
aList.remove(' ')
except ValueError:
pass
aFinal = ''.join(aList) # aFinal is the joined string of aList, making it the alphabetical version of the file, without newlines or whitespaces.
if '.txt' in name:
name = name.replace('.txt', '_alphabetized.txt') # Replaces the ".txt" extension with the "_alphabetized.txt" extension to differentiate it from the old file.
with open(name, 'x') as fA: # I create a file to write to.
fA.write(aFinal) # Writes the alphabetized contents of the original file to the new file.
print("Alphabetization successful!")
input() # Waits for input in order to close.
|
#Social Computing CS522
#Programming Assignment #7
#(Submission Deadline: 5th November 2020)
#Note: The functions given in the assignment are based on link prediction.
#If there is any query related to assignment you should ask at least 48 hours before the deadline, no reply would be given in case you ask during the last 48 hours.
#Please avoid asking any syntax related queries, if you feel anything given can lead to an error, you may change it but make sure the desired output does not change.
#Kindly do not delete any test cases given in the program.
import pandas as pd
import networkx as nx
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix
#Implement the following functions for finding features of each edge
#Compute page rank for all the given nodes in G using inbuilt function
def get_page_rank(G,nodes):
#Your code
pr = nx.pagerank(G)
pr1 = []
for i in nodes:
pr1.append(pr[i])
return pr1
#Find whether there is an edge from B to A, if there is an edge from A to B, for every edge in G
def do_follow_back(G,source_nodes,dest_nodes):
#Your code
foll_back = []
for i in range(len(source_nodes)):
foll_back.append(G.has_edge(dest_nodes[i], source_nodes[i]))
return foll_back
#Find the number of followers of each node
def find_num_foll(G,nodes):
#Your code
foll_count = []
for i in nodes:
foll_count.append(G.in_degree(i))
return foll_count
#Find the number of followee of each node
def find_num_fole(G,nodes):
#Your code
fole_count = []
for i in nodes:
fole_count.append(G.out_degree(i))
return fole_count
#Find the common number of followers for each pair of nodes connected through an edge.
def find_num_comm_foll(G,source_nodes,dest_nodes):
#Your code
num_of_source_nodes = len(source_nodes)
comm_foll_count = []
for i in range(num_of_source_nodes):
a1 = set([j for j in G.predecessors(source_nodes[i])])
a2 = set([j for j in G.predecessors(dest_nodes[i])])
comm_foll_count.append(len(list(a1 & a2)))
return comm_foll_count
#Find the common number of followee for each pair of nodes connected through an edge.
def find_num_comm_fole(G,source_nodes,dest_nodes):
#Your code
n = len(source_nodes)
comm_fole_count = []
for i in range(n):
a1 = set([j for j in G.successors(source_nodes[i])])
a2 = set([j for j in G.successors(dest_nodes[i])])
comm_fole_count.append(len(list(a1 & a2)))
return comm_fole_count
#Do not make any change in the code given below when submitting it, I will be executing this code on Windows platform , so please take care
#Please print your entry number, for example replace <Entry number> by 2014csz0001, Kindly do not delete this statement.
print('2018csb1070')
#Loading dataset
#The File contains pair of source node and destination node representing an edge, where an edge from A to B means A follows B
#The class assigned as 1 indicates actual edges and 0 as missing edges
df=pd.read_csv(r'graph_link_prediction_dataset.csv')
#Constructing graph
source_nodes=list(df['Source'].values)
dest_nodes=list(df['Destination'].values)
edge_list=list(zip(source_nodes,dest_nodes))
G=nx.DiGraph()
G.add_edges_from(edge_list)
print(nx.info(G))
#Extracting features
#Page Rank
source_pr=get_page_rank(G,source_nodes)
dest_pr=get_page_rank(G,dest_nodes)
#Follows_backs
foll_back=do_follow_back(G,source_nodes,dest_nodes)
#Number of followers
source_foll_count=find_num_foll(G,source_nodes)
dest_foll_count=find_num_foll(G,dest_nodes)
#Number of followee
source_fole_count=find_num_fole(G,source_nodes)
dest_fole_count=find_num_fole(G,dest_nodes)
#Number of common followers and followees
comm_foll_count=find_num_comm_foll(G,source_nodes,dest_nodes)
comm_folle_count=find_num_comm_fole(G,source_nodes,dest_nodes)
df['source_pr']=source_pr
df['dest_pr']=dest_pr
df['foll_back']=foll_back
df['source_foll_count']=source_foll_count
df['dest_foll_count']=dest_foll_count
df['source_fole_count']=source_fole_count
df['dest_fole_count']=dest_fole_count
df['comm_foll_count']=comm_foll_count
df['comm_folle_count']=comm_folle_count
#The below code is for training and testing a machine learning model using the features computed above
#Since this is not a machine learning course, so do not break your head for the below code.
#No paramter tuning or model selection is being done. If you feel you may try for yourself, but make sure you do not change the code as far as assigment submission is concerned.
X=df[['source_pr','dest_pr','foll_back','source_foll_count','dest_foll_count','source_fole_count','dest_fole_count','comm_foll_count','comm_folle_count']].to_numpy()
Y=df[['Class']].to_numpy()
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.25, random_state=20)
lr=LogisticRegression(random_state=20,solver='lbfgs')
lr.fit(X_train, Y_train.ravel())
print(confusion_matrix(lr.predict(X_test).ravel(), Y_test.ravel()))
'''
Expected Output
2014csz0014
Name:
Type: DiGraph
Number of nodes: 50107
Number of edges: 70648
Average in degree: 1.4099
Average out degree: 1.4099
[[8495 738]
[ 250 8179]]
'''
'''
Important Notes:
1)Your file should be named as scomp_asg07_<Your entry number>.py. For example if your entry number is 2014csz0001, your file name should be scomp_asg07_2014csz0001.py. (use only small letters)
2) Make sure you do not copy the code neither from internet nor from any other student.
3) Strictly follow the guidelines given regarding the unimplemented functions and use only Python3.
4) No marks will be given in case of syntactical errors, logical errors of any kind.
5)Please do not submit the csv file, only the template filled with functions code should be submitted
5) Your .py file will be executed directly on the command prompt, so do take care of that.
'''
|
# Each new term in the Fibonacci sequence is generated by adding the previous
# two terms. By starting with 1 and 2, the first 10 terms will be:
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
# By considering the terms in the Fibonacci sequence whose values do not
# exceed four million, find the sum of the even-valued terms.
N = 31 # This is the last index term before 4 million. (Fib(31) = 3524578.
Fib = [1, 2]
for i in range(1, N):
Fib.append(Fib[i] + Fib[i-1])
print(Fib[N])
print(sum(filter(lambda x: x % 2 == 0, Fib)))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 31 20:50:50 2021
@author: lesliecastelan
Professor: Hangjie Ji
Discussion: 3B
"""
#%%
class Node:
"""Node class for individual units within LinkedList class
Has next member function, therefore for usage within singly linked
lists. Of special importance: has __eq__ method
"""
def __init__(self,data=None):
self.data =data
self.next = None
def __str__(self):
return str(self.data)
def __repr__(self):
return repr(self.data)
def __eq__(self,other):
"""
Enables comparison of node data to a value
"""
return self.data == other
class LinkedList:
"""Singly linked list class called LinkedList.
Methods to note: append, len, __getitem__, __setitem__, add
"""
def __init__(self, data=None):
current_node = Node(data)
if current_node == None: #if this is the case, have to adjust self.first
#to real node in append
self.first= current_node
self.last= current_node
self.n=0
else:
self.first= current_node
self.last= current_node
#print("self.last in linked list:", self.last)
self.n=0
self.n = self.n +1
#print("self.n in Linked Lisg method:", self.n)
def append(self,data):
"""Creates new node and appends to end of LinkedList
Takes in data and creates new node from that.
"""
new_node= Node(data)
#print("New_node:" ,new_node)
#print("self.last:", self.last)
#print("self.first", self.first)
#print("self.first.next:", self.first.next)
#print("self.last.next:", self.last.next)
if self.n ==1:
self.first.next = new_node
#print("self.first.next after setting to new_node:", self.first.next)
#print("if n=1 self.last.next before changing last to new node:" ,self.last.next)
self.last =new_node #do not have to manually change self.last.next to None
#print("if n=1 self.last.next after changing:", self.last.next)
self.n +=1
#print("counter at end:", self.n)
else:
self.last.next= new_node
#print("Self.last.next:" ,self.last.next)
self.last=new_node
#print("after making last new node, self.last is:", self.last)
#print("self.last.next after changing self.last to new node:", self.last.next)
self.n +=1
#print("counter at end:", self.n)
def __iter__(self):
# print("iterator called")
self.current_iter= self.first #reset to the first node
return self.generator()
#def __next__(self):
# if self.current_iter == None:
# raise StopIteration
# counter= self.current_iter
#self.current_iter = self.current_iter.next
#return counter
def generator(self): #raise error
for i in range(0, self.n):
counter = self.current_iter
yield counter
self.current_iter=self.current_iter.next
if i >= self.n:
raise IndexError
def __len__(self):
return self.n
def __str__(self):
"""Allows for LinkedList to be printed out with arrows
in between.
"""
node =self.first
linked_list= "["
while (node != None): #make sure node not at end
if node.next == None: #stop right before end
linked_list += str(node)
break
linked_list += str(node) + "->"
node = node.next
linked_list += "]"
return linked_list #return concatendated string
def __repr__(self):
node =self.first
linked_list= "["
while (node != None):
if node.next == None:
linked_list += str(node)
break
linked_list += str(node) + "->"
node = node.next
linked_list += "]"
return linked_list
def __getitem__(self, index): #how do I get this to not return a value if IndexError
if index >= self.n:
raise IndexError("List index out of range")
node=self.first
counter =0
while( counter < index):
node=node.next
counter +=1
return str(node)
def __setitem__(self,index, value):
if index >= self.n: #or should it be just greater than?
raise IndexError("List index out of range")
node=self.first
counter =0
while( counter < index):
node=node.next
counter +=1
node.data= value
def __add__(self, other):
""" Allows adding new node to LinkedList using + operator """
new_linked_list=LinkedList(self.first.data)
#print(type(new_linked_list))
i= self.first.next
#print(i)
while (i != None):
new_linked_list.append(i.data)
#print(new_linked_list)
i = i.next
#print(i)
#print("Self:", self)
new_linked_list.append(other)
#print("After appending other to new_linked_list:", self)
#print("New linked list:", new_linked_list)
return new_linked_list
#n= Node(10)
#print(repr(n))
#print(str(n))
#print(n)
#a=LinkedList(0)
#a.append(1)
#a.append(2)
#print("7 points if this works")
#for n in a:
# print(n)
#print("2 points if this works")
#for n in a:
# print(n)
#print("")
#print("3 points if both of these work")
#for n in a:
# if n == 2:
# break
# else:
# print(n)
#print("")
#for n in a:
# if n == 2:
# break
# else:
# print(n)
#print("")
#a.append(3)
#a.append(4)
#a.append(5)
#a.append(6)
#a.append(7)
#a.append(8)
#print("1 points if this works")
#print(len(a))
#print("")
#print("1 points if this works")
#print(str(a))
#print("")
#print("1 points if this works")
#print(repr(a))
#print("")
#print("1 points each. That is, 2 points if the output of the next line is correct")
#print("before a[5] was:", a[5])
#a[5] = 20
#print("after, a[5] is now:", a[5])
#print("")
#print("2 points for correct operation of +")
#a+9 # doesn't modify a
#print(a)
#a = a+9 # appends 9 to a
#print(a)
#print("")
#print("1 points for raising correct IndexError")
#try:
# print(a[999])
# a[999]=10
#except IndexError as e:
# print(e)
#%%
|
#1
with open('gregor.txt') as f:
for line in f:
print(line, end='')
#2
def dict_to_file(d, filename):
with open(filename, 'w') as f:
for k, v in d.items():
print(k, file=f)
print(v, file=f)
#3
def dict_from_file(filename):
d = {}
with open(filename) as f:
while True:
try:
k = f.readline()
v = f.readline().strip()
if k !='' and v !='':
d[int(k)] = v
else:
return d
except ValueError:
print(f'{k} is not an integer')
#4
def append_files(a, b, c):
with open(a) as f_a, open(b) as f_b, open(c, 'a') as f_c:
print(f_a.read(), file=f_c, end='')
print(f_b.read(), file=f_c, end='')
#5
def sum_file(filename):
with open(filename) as f:
return sum(map(int, f.read().split()))
#6
def copy_file(a, b):
with open(a) as f_in, open(b, 'w') as f_out:
print(f_in.read(), file=f_out, end='')
#7
def is_full_stop(s):
return s == '.'
def stats_from_file(f):
lines = 0
characters = 0
words = 0
sentences = 0
histogram = {}
for line in f:
lines += 1
characters += len(line)
words += len(line.split())
sentences += len(list(filter(is_full_stop, line)))
for x in line:
current = 0
if x in histogram:
current = histogram[x]
histogram[x] = current + 1
return (lines, characters, words, sentences, histogram)
def stats_from_filename(filename):
with open(filename) as f:
return stats_from_file(f)
gregor_stats = stats_from_filename('gregor.txt')
#8
import string
def cleansplit(line):
return [s.strip(string.punctuation).lower() for s in line.split()]
def is_full_stop(s):
return s == '.'
def stats_from_file(f):
lines = 0
characters = 0
words = 0
sentences = 0
histogram = {}
word_histogram = {}
for line in f:
lines += 1
characters += len(line)
words += len(line.split())
sentences += len(list(filter(is_full_stop, line)))
for x in line:
current = 0
if x in histogram:
current = histogram[x]
histogram[x] = current + 1
for x in cleansplit(line):
current = 0
if x in word_histogram:
current = word_histogram[x]
word_histogram[x] = current + 1
return (lines, characters, words, sentences, histogram, word_histogram)
def stats_from_filename(filename):
with open(filename) as f:
return stats_from_file(f)
gregor_stats = stats_from_filename('gregor.txt')
#9
import string
def cleansplit(line):
return [s.strip(string.punctuation).lower() for s in line.split()]
def search_word(filename, word):
lines = []
with open(filename) as f:
lines = f.readlines()
words = map(cleansplit, lines)
for n, ws in enumerate(words):
if word in ws:
print(f'{n}: ', end='')
print(lines[n], end='')
#10
def top(filename):
lines = []
with open(filename) as f:
lines = f.readlines()
while len(lines) > 0:
for l in lines[:5]: print(l, end='')
lines = lines[5:]
enter = input()
|
#Q1
def sorted_words(s):
l = s.split()
l.sort()
return l
#Q2
def sorted_words(s):
return sorted(s.split())
#Q3
def setify(l):
l2 = []
for x in l:
if x not in l2: l2.append(x)
return l2
#Original from chapter 4
def histogram(l):
unique = setify(l)
for x in unique:
print(str(x) + ' appears ' + str(l.count(x)) + ' times.')
#With sorting
def histogram(l):
unique = sorted(setify(l))
for x in unique:
print(str(x) + ' appears ' + str(l.count(x)) + ' times.')
#Q4
def strip_leading_spaces(l):
while len(l) > 0 and l[0] == ' ':
del l[0]
def remove_spaces(s):
l = list(s)
strip_leading_spaces(l)
l.reverse()
strip_leading_spaces(l)
l.reverse()
return ''.join(l)
#Q5
def remove_spaces(s):
return ' '.join(s.split())
#Q6
def clip(x):
if x > 10:
return 10
elif x < 1:
return 1
else:
return x
def clip_list(l):
return list(map(clip, l))
#Q7
def is_palindromic(s):
return s == s[::-1]
def palindromes(l):
return list(filter(is_palindromic, l))
def palindromic_numbers_in(x, y):
ps = palindromes(list(map(str, list(range(x, y)))))
return list(map(int, ps))
#With iterators
def is_palindromic(s):
return s == s[::-1]
def palindromes(l):
return filter(is_palindromic, l)
def palindromic_numbers_in(x, y):
ps = palindromes(map(str, range(x, y)))
return list(map(int, ps))
#Q8
def clip_list(l):
return [clip(x) for x in l]
#Q9
def palindromic_numbers_in(x, y):
strings = map(str, range(x, y))
return [int(x) for x in strings if is_palindromic(x)]
def palindromic_numbers_in(x, y):
return [int(x) for x in map(str, range(x, y)) if is_palindromic(x)]
|
def print_stats(l):
print(str(min(l)) + ' up to ' + str(max(l)))
def print_stats(l):
minimum = min(l)
maximum = max(l)
print(f'{minimum} up to {maximum}')
def print_stats(l):
print(f'{min(l)} up to {max(l)}')
def print_powers(n):
for x in range(1, n):
print(f'{x} {x ** 2} {x ** 3} {x ** 4} {x ** 5}')
def print_powers(n):
for x in range(1, n):
print(f'{x:5d} {x ** 2:5d} {x ** 3:5d} {x ** 4:5d} {x ** 5:5d}')
def print_powers(n):
f = open('powers.txt', 'w')
for x in range(1, n):
print(f'{x:5d} {x ** 2:5d} {x ** 3:5d} {x ** 4:5d} {x ** 5:5d}', file=f)
f.close()
def print_powers(n):
with open('powers.txt', 'w') as f:
for x in range(1, n):
print(f'{x:5d} {x ** 2:5d} {x ** 3:5d} {x ** 4:5d} {x ** 5:5d}',
file=f)
|
import math
#1
def round(x):
c = math.ceil(x)
f = math.floor(x)
if c - x <= x - f:
return c
else:
return f
#2
def between(a, b):
x0, y0 = a
x1, y1 = b
return ((x0 + x1) / 2, (y0 + y1) / 2)
#3
def parts(x):
if x < 0:
a, b = parts(-x)
return (-a, b)
else:
return (math.floor(x), x - math.floor(x))
#4
def star(x):
i = math.floor(x * 50)
if i == 50: i = 49
print(' ' * (i - 1) + '*')
#5
def plot(f, a, b, dy):
pos = a
while pos <= b:
star(f(pos))
pos += dy
|
import math
def divisors(n):
if n < 2:
return set()
if n == 2:
return set([1])
limit = math.ceil(math.sqrt(n))
divisors = set()
for d in range(2, limit + 1):
if (n % d == 0):
divisors.add(d)
m = n // d
divisors.add(m)
divisors.add(1)
return divisors
|
#! python3
def main():
a = 999
maximum = [0, 0, 0]
while a != 99:
b = a
while b != 99:
n = a * b
if is_palindrome(n) and n > maximum[2]:
maximum = [a, b, n]
b -= 1
a -= 1
return maximum[2]
def is_palindrome(num):
val = str(num)
for f, r in zip(val, val[::-1]):
if not f == r:
return False
return True
if __name__ == '__main__':
print(main())
# 906609
|
import random, turtle, tkinter
def guess_game():
def color(guess_x,guess_y,randvalue_x,randvalue_y):
turtle.setpos(guess_x,guess_y)
turtle.fillcolor(guess)
turtle.begin_fill()
turtle.circle(100)
turtle.end_fill()
turtle.setpos(randvalue_x,randvalue_y)
turtle.fillcolor(randvalue)
turtle.begin_fill()
turtle.circle(100)
turtle.end_fill()
print("GUESS THE COLOR FROM THE LIST PROVIDED\n")
print(colors)
print("\nLet's Start The Game")
print("(There are only 3 chances)\n")
guess_x=-250
guess_y=50
randvalue_x=-250
randvalue_y=-200
for i in range(1,4):
print("Enter your guess: ")
guess=input().capitalize()
input_screen = turtle.Turtle()
turtle.setup(width=750, height=600)
input_screen.screen.bgcolor("black")
turtle.title("COLOR GUESS")
turtle.pen(pencolor=None)
turtle.hideturtle()
randvalue=random.choice(colors)
color(guess_x,guess_y,randvalue_x,randvalue_y)
if (guess==randvalue):
print("Your guess is right! \nYOU WON ")
print("THANK YOU")
break
else:
if(i==3):
print("Sorry, You lost!\n")
print("Enter '1' to try again")
tryagain=int(input())
if(tryagain==1):
turtle.clear()
guess_game()
else:
print("THANK YOU")
exit()
print("\nOhh Sorry\nYou are left with '" +str(3-i)+ "' chance/s\n")
guess_x += 250
randvalue_x += 250
colors= ['Blue','Red','Orange','Violet','Green','Yellow','White','Aqua','Gray','Pink','Brown','Purple','Maroon','Indigo','Magenta','Silver','Gold']
guess_game()
|
from tabuleiro import Tabuleiro
import random
import datetime
import os
# Quebra Cabeça 8 peças
class Puzzle:
def __init__(self, posicoes, objetivo):
self.posicoes = posicoes
self.objetivo = objetivo
self.tabuleiro = Tabuleiro(posicoes, self.objetivo)
self.visitados = []
self.paraVisitar = []
self.tabuleiroFinal = self.algoritimoA()
def printBacktrack(self):
tAnterior = self.tabuleiroFinal.copy()
caminho = ""
quebraLinha = 0
while tAnterior.ponteiro != "":
posicaoZero = tAnterior.getPosicaoZero()
mv = []
caminho += tAnterior.ponteiro
if quebraLinha == 10:
caminho += "\n"
quebraLinha = 0
else:
caminho += " "
quebraLinha += 1
if tAnterior.ponteiro == "↓":
mv = [posicaoZero[0] - 1, posicaoZero[1]]
elif tAnterior.ponteiro == "↑":
mv = [posicaoZero[0] + 1, posicaoZero[1]]
elif tAnterior.ponteiro == "←":
mv = [posicaoZero[0], posicaoZero[1] + 1]
elif tAnterior.ponteiro == "→":
mv = [posicaoZero[0], posicaoZero[1] - 1]
aux = tAnterior.troca(posicaoZero, mv)
for visitado in self.visitados:
if visitado.tabuleiro == aux:
tAnterior = visitado.copy()
print(caminho[::-1])
def algoritimoA(self):
visitados = self.visitados
paraVisitar = self.paraVisitar
paraVisitar.append(self.tabuleiro)
while paraVisitar[0].corretos != 9:
print("nó atual: ")
paraVisitar[0].printTabuleiro()
print("Qtd corretos: " + str(paraVisitar[0].corretos))
os.system('cls' if os.name == 'nt' else 'clear')
folhas = paraVisitar[0].mover()
for folha in folhas:
if folha.tabuleiro not in map(lambda e: e.tabuleiro, visitados) and folha not in map(lambda e: e.tabuleiro, paraVisitar):
paraVisitar.append(folha)
visitados.append(paraVisitar[0])
paraVisitar.remove(paraVisitar[0])
paraVisitar.sort(key = lambda e: e.corretos, reverse = True)
self.visitados = visitados
self.paraVisitar = paraVisitar
return paraVisitar[0]
def main():
x = [0, 1, 2, 3, 4, 5, 6, 7, 8]
random.shuffle(x)
padraoBr = "%d/%m/%Y %H:%M:%S"
horainicio = datetime.datetime.now()
puzzle = Puzzle([x[0:3], x[3:6], x[6:9]], [[0, 1, 2], [3, 4, 5], [6, 7, 8]])
horaFinal = datetime.datetime.now()
print("Tabuleiro inicial: ")
puzzle.tabuleiro.printTabuleiro()
print("Caminho: ")
puzzle.printBacktrack()
print("Tabuleiro final: ")
puzzle.tabuleiroFinal.printTabuleiro()
print("Tempo de inicio: " + str(horainicio.strftime(padraoBr)))
print("Tempo de conclusão: " + str(horaFinal.strftime(padraoBr)))
print("Tempo de conclusão: " + str(horaFinal - horainicio))
if __name__ == "__main__":
# execute only if run as a script
main()
|
#Given two points, p1 and p2, check if p1 is clockwise from p2 with respect from the origin.
#this uses the cross product of 2d vectors and the fact that the sign of the result of that product
#will tell us whether p1 is clockwise from p2 or not.
#this algorithm comes from the computational geometry section of CLRS.
#class to define the concept of point
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def compute_xproduct(p1, p2):
return p1.x*p2.y - p2.x*p1.y
#returns true if clockwise, otherwise false
def clockwise(p1,p2):
return compute_xproduct(p1, p2) > 0
p1 = Point(2,3)
p2 = Point(3,1)
print(clockwise(p1,p2))
p1 = Point(-5,2)
p2 = Point(-4,-2)
print(clockwise(p1,p2))
|
"""Program that outputs one of at least four random, good fortunes."""
__author__ = "730395734"
# The randint function is imported from the random library so that
# you are able to generate integers at random.
#
# Documentation: https://docs.python.org/3/library/random.html#random.randint
#
# For example, consider the function call expression: randint(1, 100)
# It will evaluate to an int value >= 1 and <= 100.
from random import randint
random_integer: int = randint(1, 100)
print("Your fortune cookie says...")
if random_integer > 75:
print("You have a secret admirer!")
else:
if random_integer == 9:
print("Run.")
else:
if random_integer < 50:
print("The greatest risk is not taking one.")
else:
print("You already know the answer to the questions lingering inside your head.")
print("Now, go spread positive vibes!")
|
# Author: Liam Hooks [email protected]
def represent( letter ):
if letter == "A":
return 4.0
elif letter == "A-":
return 3.67
elif letter == "B+":
return 3.33
elif letter == "B":
return 3.0
elif letter == "B-":
return 2.67
elif letter == "C+":
return 2.33
elif letter == "C":
return 2.0
elif letter == "D":
return 1.0
else:
return 0.0
letter1 = input("Enter your course 1 letter grade: ")
gradePoint1 = represent(letter1)
credit1 = float(input("Enter your course 1 credit: "))
print(f"Grade point for course 1 is: {gradePoint1}")
letter2 = input("Enter your course 2 letter grade: ")
gradePoint2 = represent(letter2)
credit2 = float(input("Enter your course 2 credit: "))
print(f"Grade point for course 2 is: {gradePoint2}")
letter3 = input("Enter your course 3 letter grade: ")
gradePoint3 = represent(letter3)
credit3 = float(input("Enter your course 3 credit: "))
print(f"Grade point for course 3 is: {gradePoint3}")
gpa = ((gradePoint1 * credit1) + (gradePoint2 * credit2) + (gradePoint3 * credit3)) / (credit1 + credit2 + credit3)
print(f"Your GPA is: {gpa}")
|
# -*- coding:utf-8 -*-
"""
一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。
"""
"""
题目分析,假设f[i]表示在第i个台阶上可能的方法数。逆向思维。如果我从第n个台阶进行下台阶,下一步有2中可能,
一种走到第n-1个台阶,一种是走到第n-2个台阶。所以f[n] = f[n-1] + f[n-2].
那么初始条件了,f[0] = f[1] = 1。
所以就变成了:f[n] = f[n-1] + f[n-2], 初始值f[0]=1, f[1]=1,目标求f[n]。
"""
class Solution:
def jumpFloor(self, number):
# write code here
if number == 1 or number == 2:
return number
first = 1
second = 2
for i in range(3, number + 1):
out = first + second
first = second
second = out
return out
if __name__ == '__main__':
Solution = Solution()
print(Solution.jumpFloor(5))
|
string, substring = (input().strip(), input().strip())
print(sum([ 1 for i in range(len(string)-len(substring)+1)
if string[i:i+len(substring)] == substring]))
|
import json
from difflib import get_close_matches
data = json.load(open("data.json"))
def translate(_word):
_word=_word.lower()
if _word in data:
return data[_word]
elif _word.title() in data:
return data[_word.title()]
elif len(get_close_matches(_word,data.keys())) > 0:
yn = input("Did you mean %s instead? Enter Y if yes, or N if no: " % get_close_matches(_word,data.keys())[0])
if yn.lower() == "y":
return data[get_close_matches(_word,data.keys())[0]]
elif yn.lower() == "n":
return "The word doesn't exist. Please double ckeck it"
else:
return "We didn't understand your entry."
else:
return "The word doesn't exist. Please double check it"
word= input("Enter word: ")
output = translate(word)
if type(output) == list:
for item in output:
print(item)
else:
print(output)
|
def Average(string):
list_of_string = list(string.split(" "))
Total = 0
for num in list_of_string:
integer = int(num)
Total += integer
print(Total/len(list_of_string))
Average("12 11 2 6 7 10")
|
def insertionSort(arr, index):
tmp_val = arr[index]
j = index - 1
while j >= 0 and arr[j] > tmp_val:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = tmp_val
len_arr = int(input())
arr = [int(x) for x in input().split()]
for i in range(1,len_arr,1):
insertionSort(arr, i)
print(' '.join([str(a) for a in arr]))
|
BOARD_SIZE = 7
def check_for_horizontal_win(board):
for row in range(BOARD_SIZE):
start_column = 0
end_column = 4
while end_column != BOARD_SIZE + 1:
board_slice = board[row][start_column : end_column]
piece_set = set(board_slice)
if len(piece_set) == 1 and next(iter(piece_set)) != "___":
return True
start_column += 1
end_column += 1
return False
def check_for_vertical_win(board):
# rotate board 90 degrees
rotated_board = []
for i in range(BOARD_SIZE):
new_row = []
for j in range(BOARD_SIZE):
new_row.append(board[j][i])
rotated_board.append(new_row)
# on the rotated board, all wins that would have previously been vertical are now horizontal
return check_for_horizontal_win(rotated_board)
def check_for_left_diagonal_win(board):
rows_to_check = [-1, 0, 1, 2]
columns_to_check = [0, 1, 2, 3]
end_column = max(columns_to_check)
for row in range(BOARD_SIZE - len(rows_to_check) + 1):
rows_to_check = list(map(lambda x : x + 1, rows_to_check))
columns_to_check = [0, 1, 2, 3]
end_column = max(columns_to_check)
while end_column != BOARD_SIZE:
positions_to_check = list(zip(rows_to_check, columns_to_check))
values_on_diagonal = set(map(lambda pos : board[pos[0]][pos[1]], positions_to_check))
if len(values_on_diagonal) == 1 and next(iter(values_on_diagonal)) != "___":
return True
columns_to_check = list(map(lambda x : x + 1, columns_to_check))
end_column = max(columns_to_check)
return False
def check_for_right_diagonal_win(board):
rows_to_check = [-1, 0, 1, 2]
columns_to_check = [3, 2, 1, 0]
end_column = max(columns_to_check)
for row in range(BOARD_SIZE - len(rows_to_check) + 1):
rows_to_check = list(map(lambda x : x + 1, rows_to_check))
columns_to_check = [3, 2, 1, 0]
end_column = max(columns_to_check)
while end_column != BOARD_SIZE:
positions_to_check = list(zip(rows_to_check, columns_to_check))
values_on_diagonal = set(map(lambda pos : board[pos[0]][pos[1]], positions_to_check))
if len(values_on_diagonal) == 1 and next(iter(values_on_diagonal)) != "___":
return True
columns_to_check = list(map(lambda x : x + 1, columns_to_check))
end_column = max(columns_to_check)
return False
def check_for_win(board):
return check_for_horizontal_win(board) or check_for_vertical_win(board) or check_for_left_diagonal_win(board) or check_for_right_diagonal_win(board)
|
#Newton-Raphson method to find a real root of an equation***********
from __future__ import division, print_function
import numpy as np
import math
x0=input ('enter the initial approx')
tol=input('enter the tolarence value')
n=range(100)
print("itr, x")
f= lambda x: 3*x-math.cos(x)-1
df=lambda x: 3+math.sin(x)
for i in n:
x1=x0-(f(x0)/df(x0))
if abs(x1-x0)>tol:
print (i,x1)
x0=x1
i=i+1
else:
break
|
import random
import string
import sys
from threading import Timer
def text_captcha():
"""
It generates a captcha and asks user to verify within 9 seconds.
"""
captcha = string.ascii_lowercase + string.ascii_uppercase + \
"".join([str(i) for i in range(0, 10)])
captcha_random = ''
while len(captcha_random) < 10:
char = random.choice(captcha)
captcha_random += char
time = Timer(9, timeout)
print("Captcha: " + captcha_random)
time.start()
user_input = input("Enter the characters in Captcha: ")
verify(user_input, captcha_random, time)
time.cancel()
def timeout():
"""
It tells users that time has run out and provides users options.
:return: presents users options to either quit or try again after timeout.
"""
print("Timeout. \nPlease type 'quit' to quit or 'try' to try again.")
def verify(input: str, captcha: str, time: Timer):
"""
A helper function for text_captcha. It checks if the user input matches the
given captcha and executes according to the options presented after timeout.
:param time: timer object from text_captcha
:param input: the input of the user
:param captcha: the random captcha that was created in text_captcha
"""
if input == captcha and time.is_alive():
print("Verified as human!")
elif input == "quit":
sys.exit("The program has ended.")
elif input == "try":
text_captcha()
elif input != captcha:
print("Prove you're a human because your previous "
"input didn't match Captcha.")
text_captcha()
if __name__ == '__main__':
text_captcha()
|
i = 0
while i == 0:
print("")
n1 = input ("Type in 1st number. Type 'end' to end -> ")
if n1 == "end":
print("ended")
print()
break
print("+")
print("-")
print("x")
print("%")
op = input ("Select Operation. Type 'end' to end-> ")
if op == "end":
print("ended")
print()
break
n2 = input ("Type in 2nd number. Type 'end' to end -> ")
if n2 == "end":
print("ended")
print()
break
if op == "+":
print(float(n1)+float(n2))
elif op == "-":
print(float(n1)-float(n2))
elif op == "x":
print(float(n1)*float(n2))
elif op == "%":
print(float(n1)/float(n2))
else:
print("Operation not valid")
print()
|
go = 0
while go == 0:
import math
def palindrome(s):
mid = math.floor(len(s)/2)
x = len(s)
for i in range (mid):
j = -(i+1)
if s[i] != s[j]:
return False
return True
userInput = input ("Type in word. Type 'end' to end. ")
if userInput == "end":
print("ended")
print()
break
elif palindrome(userInput):
print("Yes. Palindrome")
else:
print("No. Not Palindrome")
|
y = input ("enter a number")
y = int (y)
i= 0
for c in range (y):
i = i+c+1
print (i)
|
import tkinter as tk
window = tk.Tk()
car = tk.PhotoImage(file="car1.png",width=280,height=140)
img = tk.Label(master=window,image=car)
img.pack(side=tk.TOP)
f = tk.Frame(bg="navy")
f.pack()
lbl=tk.Label(master = f,text= "Can you drive?",width=35,height=10,font = ("Arial", 10),fg="Orange",bg="Navy")
lbl.pack()
lbl=tk.Label(master = f,text= "Enter your age.",width=35,height=3,font = ("Arial", 10),fg="Orange",bg="Grey")
lbl.pack()
Ent=tk.Entry(width=5)
Ent.pack()
def onClick (event):
x = Ent.get()
x = int(x)
if x >= 16:
lbl1 = tk.Label(bg="green",text="Get a license and then you can drive!",font = ("Arial", 10),width=35,height=3)
lbl1.pack()
elif x < 16:
lbl2 = tk.Label(bg="red",text="Sorry, you can't drive yet.",font = ("Arial", 10),width=35,height=3)
lbl2.pack()
else:
lbl3 = tk.Label(bg="blue",text="What you entered was not valid. Try again.",font = ("Arial", 10),width=35,height=3)
lbl3.pack()
Btn=tk.Button(width=20,text="Click to see answer!")
Btn.pack()
Btn.bind("<Button-1>",onClick)
window.mainloop()
|
# coding: utf-8
import pandas as pd
# read excel file and return first 2 rows
path=r'Test.xlsx'
df=pd.read_excel(path)
df.head(3)
# filter the records
df1=df[df['discharge_disposition_id']!="Expired"]
# save the preProcess to the new file
writer_noExpired=pd.ExcelWriter('noExpired.xlsx',engine='xlsxwriter')
df1.to_excel(writer_noExpired,index=True,sheet_name='noExpired_diabetes.csv')
writer_noExpired.save()
# return the number of new file
num_rows=len(df1)
print "Number of no expired records is %d" %num_rows
|
while True:
alhpa = input()
if alhpa != 'q':
print(alhpa)
else:
print(alhpa)
break
|
'''
문제
두 정수 A와 B를 입력받은 다음, A×B를 출력하는 프로그램을 작성하시오.
'''
# solution
num1, num2 = map(int, input().split())
print(num1*num2)
|
# 비효율적인 소수 판별 알고리즘
# 2 부터 X - 1 까지의 모든 자연수로 나누었을때 나누어 떨어지는 수가 하나라도 있으면 소수 아님
# 소수 판별 함수 - 시간복잡도 O(x)
def is_prime_number(x):
# 2부터 (x - 1)까지의 모든 수를 확인하며
for i in range(2, x):
# x가 해당 수로 나누어 떨어진다면
if x % i == 0:
return False # 소수 아님
return True # 소수임
# 모든 자연수로 나눈다는 것은 비효율적이기 때문에 제곱근 까지만(가운데 약수) 확인하는 알고리즘
import math
# 소수 판별 알고리즘 - 시간복잡도 O(x^1/2)
def is_prime_number2(x):
# 2부터 x의 제곱근 까지의 모든 수를 확인하며
for i in range(2, int(math.sqrt(x) + 1)):
# x가 해당 수로 나누어 떨어진다면
if x % i == 0:
return False # 소수 아님
return True # 소수임
|
"""
문제
두 정수 A와 B가 주어졌을 때, A와 B를 비교하는 프로그램을 작성하시오.
"""
num1, num2 = map(int, input().split())
if num1 > num2:
print('>')
elif num1 == num2:
print('==')
else:
print('<')
|
"""
You are given a non-empty array of arrays. Each subarray holds three integers and represents a disk. These integers denote each disk's width, depth, and height, respectively. Your goal is to stack up the disks and to maximize the total height of the stack. A disk must have a strictly smaller width, depth, and height than any other disk below it. Write a function that returns an array of the disks in the final stack, starting with the top disk and ending with the bottom disk. None that you cannot rotate disks; in other words, the integers in each subarray must represent [width, depth, height] at all times. Assume that there will only be one stack with the greatest total height.
"""
def max_disk_stack(disks):
pass
#test
disks = [
[2, 1, 2],
[3, 2, 3],
[2, 2, 8],
[2, 3, 4],
[1, 2, 1],
[4, 4, 5],
]
expected = [[2, 1, 2], [3, 2, 3], [4, 4, 5]]
assert max_disk_stack(disks) == expected
print('OK')
|
"""
Given an array of positive integers representing coin denominations and a
single non-negative integer representing a target amount of money, implement a
function that returns the smallest number of coins needed to make change for
that target amount using the given coin denominations. Nonte that an
unlimited amount of coins is at your disposal. If it is impossible to make
change for the target amount, return -1.
"""
def min_number_of_coins(n, denoms):
pass
# test
assert min_number_of_coin(7, [1, 5, 10]) == 3
print("OK")
|
"""
Write a class from a suffix-trie-like data structure. The class should have a "root" property set to be root node of the trie. The class should support creation froma a string and the searching of strings. The creation method will be called when the class is instantiated and shuld populate the root property of the class. Note that every string added to the trie should end with the special "endSymbol" chracter *
"""
class SuffixTrie:
def __init__(self, string):
self.root = {}
self.endSymbol = "*"
self.populateSuffixTrieFrom(string)
def populateSuffixTrieFrom(self, string):
if len(string) == 0:
return
for idx in range(len(string)):
self.add_substring(string, idx)
def add_substring(self, string, idx):
current = self.root
for char in string[idx:]:
if char not in current:
current[char] = {}
current = current[char]
current[self.endSymbol] = True
def contains(self, string):
current = self.root
for char in string:
if char in current:
current = current[char]
else:
return False
return True if self.endSymbol in current else False
|
"""
You are given a two-dimensiona array(matrix) of potentially unequal height and
width containing letters.
This matrix repreents a boggle board. You are also given a list of words. Write
a fucntion that returns an array of all the words contained in the boggle
board. A word is constructed in the boggle board by connecting adjacent
(horizontal, vertical or diagonal) letters, without using any single letter at
a given position more than once.
While words can of course have repeated letters, those repetead letters mus
come from different positions in the boggle board in order for the word to be
contained in the board. Nonte that two or more words are allowed to overlap and
use the same letters in the boggle board.
"""
def boggle_board(board, words):
# Write your code here.
final_words = {}
visited = [[False for el in row] for row in board]
tree = Tree()
for word in words:
tree.add(word)
for row in range(len(board)):
for col in range(len(board[0])):
explore_neighbor(row, col, board, tree.root, visited, final_words)
return list(final_words.keys())
def explore_neighbor(row, col, board, tree, visited, final_words):
if visited[row][col]:
return
char = board[row][col]
if char not in tree:
return
next_node = tree[char]
if '*' in next_node:
final_words[next_node['*']] = True
visited[row][col] = True
neighbors = get_neighbors(row, col, board)
for neigh in neighbors:
explore_neighbor(neigh[0], neigh[1], board, next_node, visited, final_words)
visited[row][col] = False
def get_neighbors(row, col, board):
neighbors = []
width = len(board[0])
height = len(board)
if row > 0 and col > 0:
neighbors.append([row - 1, col - 1])
if row > 0:
neighbors.append([row - 1, col])
if row > 0 and col < width - 1:
neighbors.append([row - 1, col + 1])
if col > 0:
neighbors.append([row, col - 1])
if col < width -1:
neighbors.append([row, col + 1])
if row < height - 1 and col > 0:
neighbors.append([row + 1, col - 1])
if row < height -1:
neighbors.append([row + 1,col])
if row < height -1 and col < width -1:
neighbors.append([row + 1, col + 1])
return neighbors
class Tree:
def __init__(self):
self.root = {}
self.end_symbol = '*'
def add(self, word):
cur_node = self.root
for char in word:
if char not in cur_node:
cur_node[char] = {}
cur_node = cur_node[char]
cur_node[self.end_symbol] = word
board = [
['t', 'h', 'i', 's', 'i', 's', 'a'],
['s', 'i', 'm', 'p', 'l', 'e', 'x'],
['b', 'x', 'x', 'x', 'x', 'e', 'b'],
['x', 'o', 'g', 'g', 'l', 'x', 'o'],
['x', 'x', 'x', 'D', 'T', 'r', 'a'],
['R', 'E', 'P', 'E', 'A', 'd', 'x'],
['x', 'x', 'x', 'x', 'x', 'x', 'x'],
['N', 'O', 'T', 'R', 'E', '-', 'P'],
['x', 'x', 'D', 'E', 'T', 'A', 'E'],
]
words = ['this', 'is', 'not', 'a', 'simple', 'boggle',
'board', 'test', 'REPEATED', 'NOTRE-PEATED']
output = ['this', 'is', 'a', 'simple', 'boggle',
'board', 'NOTRE-PEATED']
result = boggle_board(board, words)
output_set = set(output)
assert len(output) == len(result)
for res in result:
assert res in output_set
print('OK')
|
"""
Given an array of positive integers representing coin denominations and a
single non-negative integer representing a target amount of money, impolement a
function that returns the number of ways to make change for that target amount
using the given coin denominations. Note that an unlimited amount of coins is
at your disposal.
"""
def number_of_ways_to_make_change(amount, denoms):
pass
assert number_of_ways_to_make_change(6, [1, 5]) == 2
print("OK")
|
from abc import ABC, abstractmethod
from collections import defaultdict
from random import choice, random
from pprint import pformat
import numpy as np
class Agent(ABC):
""" Base Agent """
def __init__(self, action_space):
self.action_space = action_space
@abstractmethod
def act(self, observation):
pass
@abstractmethod
def learn(self, prev_observation, action, next_observation, reward):
pass
class Random(Agent):
""" Random Agent """
def act(self, *args):
return self.action_space.sample()
def learn(self, *args):
pass
class QLearning(Agent):
""" QLearning Agent """
learning_rate = 0.3
discount_factor = 0.7
def __init__(self, action_space):
super().__init__(action_space)
self.qtable = defaultdict(self._default_action_qs)
def _default_action_qs(self):
return np.array([0.0 for _ in range(self.action_space.n)])
def _best_action(self, observation):
""" Returns the best action and its q value for this observation"""
action_qs = self.qtable[observation]
action = choice(
np.where(np.isclose(action_qs, action_qs.max()))[0]
) # Randomly break ties
return action, action_qs[action]
def act(self, observation):
"""
Best action given this observation?
"""
action, _ = self._best_action(observation)
return action
def learn(self, prev_observation, action, next_observation, reward):
"""
prev_observation: s
action: a
next_observation: s(t+1)
reward: r
Q(s,a) <-- Q(s,a) + α * (r + γ * maxQ(s(t+1),a) - Q(s,a))
"""
old_q = self.qtable[prev_observation][action]
_, optimal_next_q = self._best_action(next_observation)
temporal_difference = (
QLearning.discount_factor * optimal_next_q + reward - old_q
)
self.qtable[prev_observation][action] = (
old_q + QLearning.learning_rate * temporal_difference
)
def __str__(self):
s = "QLearning {\n"
for k, v in self.qtable.items():
s += f"\t{k}:\t{v}\n"
s += "}"
return s
|
#!./venv/bin/python
# ------------------------------------------------------------------------------
# Copyright (c) 2019. Anas Abu Farraj
# ------------------------------------------------------------------------------
"""Movie Name Manager app
Enter 'a' to add movie, 'l' to list movie, 'f' to find movie, and 'q' to quit.
Tasks:
TODO [x]: Decide where to store movies
TODO [x]: What is the format of a movie?
TODO [x]: Show a user interface and get user input
TODO [x]: Allow user to add movies
TODO [x]: List all movies to user
TODO [x]: Find a movie
TODO [x]: Allow the user to stop running the program
"""
def menu():
"""Show a user interface and get user input."""
user_message = "\nEnter 'a' to add movie, " \
"'l' to list movie, " \
"'f' to find movie, " \
"and 'q' to quit: "
user_input = input(user_message)
while user_input != 'q':
if user_input == 'a':
add_movie()
elif user_input == 'l':
list_movie()
elif user_input == 'f':
find_movie()
else:
print('Unknown command, please try again')
user_input = input(user_message)
print('Listing movies before quitting:')
list_movie()
def add_movie():
"""Add a movie to a list."""
movie_name = input('Enter movie name: ')
movie_director = input('Enter director: ')
movie_year = input('Enter movie year: ')
MOVIES.append({'name': movie_name, 'director': movie_director, 'year': movie_year})
def list_movie():
"""List all stored movies in the list."""
if not MOVIES:
print('No stored movies yet')
for movie in MOVIES:
print(f"{movie['name']} ({movie['year']}) - Director by '{movie['director']}'")
def find_movie():
"""Finds a movie."""
keyword = input('Enter the movie detail: ').casefold()
for movie in MOVIES:
found = [
keyword in movie['name'].casefold(), keyword in movie['director'].casefold(),
keyword in movie['year'].casefold()
]
if any(found):
print(
f"{movie['name']} ({movie['year']}) - Director by '{movie['director']}'")
print('Not found')
MOVIES = []
if __name__ == '__main__':
# Initial stored movies for testing.
MOVIES = [{
'name': 'Harry Potter',
'director': 'David Fischer',
'year': '2008'
}, {
'name': 'The matrix',
'director': 'Peter David',
'year': '1998'
}]
list_movie()
menu()
|
import math
input = 34000000
def present_number(house, primes):
divisors = get_divisors2(house, primes)
# print(house, divisors)
return sum([d * 10 for d in divisors])
# Naive implementation
def get_divisors(n):
i = 1
d = [n]
while i <= n / 2:
if n % i == 0:
d.append(i)
i = i + 1
return d
def get_divisors2(n, primes):
return divisors(factorize(n, primes))
# Sieve of Eratosthenes
# Code by David Eppstein, UC Irvine, 28 Feb 2002
# http://code.activestate.com/recipes/117119/
def gen_primes():
""" Generate an infinite sequence of prime numbers.
"""
# Maps composites to primes witnessing their compositeness.
# This is memory efficient, as the sieve is not "run forward"
# indefinitely, but only as long as required by the current
# number being tested.
#
D = {}
# The running integer that's checked for primeness
q = 2
while True:
if q not in D:
# q is a new prime.
# Yield it and mark its first multiple that isn't
# already marked in previous iterations
#
yield q
D[q * q] = [q]
else:
# q is composite. D[q] is the list of primes that
# divide it. Since we've reached q, we no longer
# need it in the map, but we'll mark the next
# multiples of its witnesses to prepare for larger
# numbers
#
for p in D[q]:
D.setdefault(p + q, []).append(p)
del D[q]
q += 1
def get_primes(upto):
g = gen_primes()
s = []
n = next(g)
while n <= upto:
s.append(n)
n = next(g)
return s
# From here https://stackoverflow.com/a/12422030/119071
def factorize(n, primes):
factors = []
for p in primes:
if p * p > n:
break
i = 0
while n % p == 0:
n //= p
i += 1
if i > 0:
factors.append((p, i))
if n > 1:
factors.append((n, 1))
return factors
def divisors(factors):
div = [1]
for (p, r) in factors:
div = [d * p ** e for d in div for e in range(r + 1)]
return div
primes = get_primes(int(math.sqrt(input)))
if __name__ == "__main__":
print("Starting")
part = "b"
if part == "a":
for i in range(1, input):
pn = present_number(i, primes)
if pn > input:
print(i, pn)
break
else:
# Part b
excluded = set()
factor_counter = dict()
for i in range(1, input):
ds = get_divisors2(i, primes)
for d in ds:
if d not in excluded:
v = factor_counter.get(d, 0)
factor_counter[d] = v + 1
if v == 50:
excluded.add(d)
pn = sum([d * 11 for d in ds if d not in excluded])
if i % 1000 == 0:
print(i, pn)
if pn > input:
print(i, pn)
break
|
class graph():
def __init__(self,n):
self.vertex={}
self.n=n
def add_edge(self,from_v,to_v):
if from_v not in self.vertex.keys():
self.vertex[from_v]=[to_v]
else:
self.vertex[from_v].append(to_v)
def detect_cycle(self):
#0-white, 1-gray, 2-black
visited=[False]*(self.n)
stack=[False]*(self.n)
for i in self.vertex.keys():
if visited[i]==False:
if self.check_cycle_rec(visited,stack,i)==True:
return True
return False
def check_cycle_rec(self,visited,stack,current):
visited[current]=True
stack[current]=True
if current in self.vertex.keys():
for k in self.vertex[current]:
if stack[k]==True:
return True
elif visited[k]==False:
if self.check_cycle_rec(visited,stack,k)==True:
return True
stack[current]=False
return False
if __name__=='__main__':
g=graph(6)
g.add_edge(0,1)
g.add_edge(0,2)
g.add_edge(1,2)
g.add_edge(3,0)
g.add_edge(3,4)
g.add_edge(4,5)
g.add_edge(5,3)
print(g.detect_cycle())
|
# Creating a Tuple
id = (1, 2, 3, 4)
name = ("sam", "sandy", "sharma", "sharmaJi")
age = (22, 23, 25, 20)
salary = (2500, 2500, 2500, 2500)
tuples = (id,name,age,salary)
print(f'Creating a tuples', tuples)
# Indexing is same as list
# Accessing element
# Top level
print(f'accessing elements top level: ', tuples[1])
# Sub level
print(f'accessing elements sub level: ', tuples[1][2])
# Slicing
print(f'Slicing of a tuple: ', tuples[0:3])
# Built in functions
# length of tuple
print(f'Length of a tuple: ', len(tuples))
# Minimum
marks = (32, 12, 15, 17, 21)
print(f'prints minimum from a tuple: ', min(marks))
# Maximum
print(f'prints minimum from a tuple: ', max(marks))
# Combing two tuple
print(f'Concatenate tuple: ', tuples + marks)
|
import torch
import torch.nn as nn
import torch.nn.functional as F
num_classes = 2
# define the CNN architecture
class Net(nn.Module):
### TODO: choose an architecture, and complete the class
def __init__(self):
super(Net, self).__init__()
## Define layers of a CNN
self.conv1 = nn.Conv2d(3, 32, 3, stride=2, padding=1)
self.conv2 = nn.Conv2d(32, 64, 3, stride=2, padding=1)
self.conv3 = nn.Conv2d(64, 128, 3, padding=1)
# pool
self.pool = nn.MaxPool2d(2, 2)
# fully-connected
self.fc1 = nn.Linear(7*7*128, 500)
self.fc2 = nn.Linear(500, num_classes)
# drop-out
self.dropout = nn.Dropout(0.3)
def forward(self, x):
## Define forward behavior
x = F.relu(self.conv1(x))
x = self.pool(x)
x = F.relu(self.conv2(x))
x = self.pool(x)
x = F.relu(self.conv3(x))
x = self.pool(x)
# flatten
x = x.view(-1, 7*7*128)
x = self.dropout(x)
x = F.relu(self.fc1(x))
x = self.dropout(x)
x = self.fc2(x)
return x
|
import os
def rename_files():
# 1) get file names for a folder
dir_path = os.getcwd() + "/prank/"
file_list = os.listdir(dir_path);
#print(file_list)
# 2) for each file, rename filename.
try:
#print(os.name)
for file in file_list:
os.rename(dir_path+file, dir_path+file.strip("0123456789"))
except OSError as e:
print(e)
rename_files()
|
# Multiples of 3 and 5
## Problem 1
"""
If we list all the natural numbers below 10 that are multiples of 3 or 5, we
get 3, 5, 6, and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
def multiples(threshold):
seq = (i for i in range(threshold) \
if i % 3 == 0 or i % 5 == 0)
return sum(seq)
ceiling = int(input('Enter ceiling number >>> '))
print(f"Multiples of 3 and 5 below {ceiling}: {multiples(ceiling)}")
|
import argparse
def encrypT(key):
ascii_value = 0
crypt = ''
for letter in key:
if ord(letter) >=120:
ascii_value = ord(letter)-23
crypt += chr(ascii_value)
else:
ascii_value = ord(letter)+3
crypt += chr(ascii_value)
return crypt
def decrypT(key):
ascii_value = 0
crypt_rev = ''
for letter in key:
if ord(letter) <=100:
ascii_value = ord(letter)+23
crypt_rev += chr(ascii_value)
else:
ascii_value = ord(letter)-3
crypt_rev += chr(ascii_value)
return crypt_rev
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--encrypt", '-e', help="set output encrypt")
parser.add_argument("--decrypt", '-d', help="set output decrypt")
args = parser.parse_args()
if args.encrypt:
print(f"Encrypt: {encrypT(args.encrypt)}")
elif args.decrypt:
print(f"Decrypt: {decrypT(args.decrypt)}")
|
'''
Problem:
Create a function that takes a string (without spaces) and a word list, cleaves the string into words based on the list, and returns the correctly spaced version of the string (a sentence).
If a section of the string is encountered that can't be found on the word list, return "Cleaving stalled: Word not found"
From: https://edabit.com/challenge/FWh2fGH7aRWALMf3o
'''
def cleave(string, lst):
|
import wikipedia
class WikiAPI:
"""
Class used to communicate with Wikipedia API
...
Methods
-------
search(string)
Returns wikipedia search titles (string)
get_search_result(string)
Returns the summary, url and title of the wikipedia search based on
"search" method result.
If Wikipedia encounters en error, the string 'error' is returned.
"""
def __init__(self):
# Sets Wikipedia language
wikipedia.set_lang("fr")
def search(self, string):
return wikipedia.search(string)
def get_search_result(self, string):
print('[WIKIAPI] : ' + string)
try:
search = self.search(string)
# Select the first search result
page = wikipedia.page(search[0])
result = {
'summary': page.summary,
'url': page.url,
'title': page.title
}
except wikipedia.exceptions.WikipediaException:
print('Une erreur est survenue')
result = 'error'
except IndexError:
print('Index introuvable')
result = 'error'
return result
|
class Solution(object):
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
nums = [int(i) for i in str(num)]
result = reduce(lambda x, y: x + y, nums)
if result >= 10:
result = self.addDigits(result)
return result
if __name__ == '__main__':
print(Solution().addDigits(38))
|
#!/usr/bin/env python
# encoding: utf-8
# Definition for binary tree with next pointer.
class TreeLinkNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.next = None
class Solution:
# @param root, a tree link node
# @return nothing
def connect(self, root):
"""
有点像层序遍历
"""
if root is None:
return
levels = [[root]]
self.level_connect(levels)
def level_connect(self, levels):
while levels:
level = levels.pop(0)
new_level = []
while level:
node = level.pop(0)
if len(level):
node.next = level[0]
if node.left:
new_level.append(node.left)
if node.right:
new_level.append(node.right)
if new_level:
levels.append(new_level)
|
from typing import List
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
if not matrix:
return
n = len(matrix)
m = len(matrix[0])
# 记录第一行第一列是否存在需要变化的可能
y = False
for i in range(n):
if matrix[i][0] == 0:
y = True
x = False
for j in range(m):
if matrix[0][j] == 0:
x = True
# 处理刨除第一行第一列的值
for i in range(1, n):
for j in range(1, m):
if matrix[i][j] == 0:
matrix[0][j] = 0
matrix[i][0] = 0
for i in range(n):
for j in range(m):
if matrix[0][j] == 0 or matrix[i][0] == 0:
matrix[i][j] = 0
if y:
for i in range(n):
matrix[i][0] = 0
if x:
for j in range(m):
matrix[0][j] = 0
if __name__ == '__main__':
# _input = [
# [1, 1, 1],
# [1, 0, 1],
# [1, 1, 1]
# ]
# _input = [
# [0, 1, 2, 0],
# [3, 4, 5, 2],
# [1, 3, 1, 5]
# ]
_input = [[1, 1, 1], [0, 1, 2]]
Solution().setZeroes(_input)
print(_input)
|
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 24 10:38:18 2018
@author: DAMI
"""
import csv
import re
with open ("dates.txt") as out:
reader = csv.reader(out)
text = out.readlines()
formatted_dates = []
for j in text:
regex2 = re.findall(r'\d{2}[/-]\d{2}[/-]\d{2,4}',str(j)) or re.findall(r'(?:\d{2} )(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]* (?:\d{2}, )?\d{4}',str(j))
if regex2 == []:
pass
else:
formatted_dates.append(regex2)
print(formatted_dates)
|
annual_salary = int(input("What is your annual salary? "))
portion_saved = float(input("What percent of your annual salary will be saved? "))
total_cost = int(input("How much does your dream home cost? "))
portion_down_payment = total_cost * float(input("What percentage of the total cost of the house do you need for the down payment? "))
current_savings = 0
r = float(input("What is your expected annual rate of return? "))
num_months = 0
while current_savings < portion_down_payment:
current_savings = (current_savings + (current_savings * (r/12))) + ((annual_salary / 12) * portion_saved)
num_months = num_months + 1
if current_savings >= portion_down_payment:
print("It will take you " + str(num_months) + " months to save up for the down payment for your house.")
|
number=int(input("Enter a number: "));
if number % 4 == 0:
print("multiple of 4")
if number%2==0:
print("Even")
else:
print("Odd")
num = int(input("Give me a number "))
check = int(input("Give me a number "))
if num % 2 == 0:
print("Even")
else:
print("Odd")
if num % check == 0:
print("divides evenly")
else:
print("doesnt divide evenly")
|
import random
a = random.randint(1, 9)
kiek=0;
while True:
inpt=input("Guess the number:")
if inpt=="exit":
break
if inpt.isnumeric():
if a==int(inpt):
print("Corect, you did",kiek,"guesses")
print("Play again")
a = random.randint(1, 9)
kiek=0;
else:
kiek += 1
if int(inpt)>a:
print("To high")
else:
print("To low")
else:
print("Enter the number or exit")
|
numbers = []
for i in range(5):
numbers.append(int(input("Please enter a number")))
current = 0
for i in range(5):
print("Number: {:<3}".format(numbers[current]))
current = current + 1
print("The first number is {}".format(numbers[0]))
print("the last number is {}".format(numbers[4]))
print("the smalles number is {}".format(min(numbers)))
print("The largest number is {}".format(max(numbers)))
print("The average of the numbers {}".format(sum(numbers)/5))
|
#Source: https://pimylifeup.com/raspberry-pi-humidity-sensor-dht22/
#Importing Packages
import Adafruit_DHT
#Intializing Temperature and Humidity Sensor
DHT_SENSOR = Adafruit_DHT.DHT22
DHT_PIN = 4
#Repeat
while True:
#Read humidity and temperature
humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)
if humidity is not None and temperature is not None:
#Print measurements and store into a string
print("Temp={0:0.1f}*C Humidity={1:0.1f}%".format(temperature, humidity))
else:
#If no data was retrieved blink Red LED to represent a error
print("Failed to retrieve data from humidity sensor")
|
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: Fazil Smm
#
# Created: 21-06-2017
# Copyright: (c) Fazil Smm 2017
# Licence: <your licence>
#-------------------------------------------------------------------------------
def main():
t=[]
a=int(raw_input("Enter the number of terms:"))
b=0
c=0
for a in range(0,a):
b = int(raw_input("Enter the value"))
t.append(b)
c +=b
print(c)
if __name__ == '__main__':
main()
|
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: Fazil Smm
#
# Created: 20-06-2017
# Copyright: (c) Fazil Smm 2017
# Licence: <your licence>
#-------------------------------------------------------------------------------
def main():
a = int(input("Enter the number"))
r = 0
while(a>0):
r = r*10
r = r + (a % 10)
a = a/10
print("the Reverse number is %d"%r)
if __name__ == '__main__':
main()
|
def splictArr(arr,j,k):
for i in range(0,k):
x = arr[0]
for j in range(0,n-1):
arr[j]=arr[j+1]
arr[n-1]=x
arr=[12,10,5,6,53,37]
n=len(arr)
position=2
splictArr(arr,n,position)
for i in range(0,n):
print(arr[i],end=' ')
|
import string
LISTA_SIMBOLOS = list(string.digits) + list(string.ascii_uppercase)
def converter_entre_bases(base_a,base_b,numero_base_a):
"""função de conversão genérica"""
numero_decimal = converter_base_x_decimal(base_a,numero_base_a)
if(base_b == 10) return numero_decimal
numero_base_b = converter_decimal_base_(base_b,numero_decimal)
return numero_base_b
def converter_base_x_decimal(base,numero):
""" função que converte e retorna um número da base x para decimal"""
retorno = 0
expoente = 0
retorno = 0
for i in range(len(numero)-1, -1,-1):
numero_dec = LISTA_SIMBOLOS.index(numero[i]) #valor a ser convertido da string
retorno += numero_dec * (base ** expoente)
expoente += 1
return retorno
def converter_decimal_base_x(base,numero):
"""função que converte e retorna um número da base decimal para uma base x"""
retorno = 0
expoente = 0
retorno = ''
while(numero > 0):
resto = numero % base
digito_b = LISTA_SIMBOLOS[resto]
retorno = f'{digito_b}{retorno}'
numero //= base
return retorno
base = int(input('Insira a base >> '))
if base <= 1:
print('A base inserida tem que ser maior que 1')
else:
if(base > len(LISTA_SIMBOLOS)):
print('Este algoritmo não suporta uma base tão grande de representação ')
else:
numero = input('Insira o número >> ')
base2 = int(input('Insira a base que deseja converter >> '))
if base2 <= 1:
print('A base inserida tem que ser maior que 1')
else:
print(f'{numero} convertido da base {base} para a base {base2} é : {converter_entre_bases(base,numero,base2)}')
|
class Conjunto:
def __init__(self):
self.elementos = []
def gerar_conjunto_partes(self):
lista_elementos = self.elementos.copy()
tamanho = len(lista_elementos)
subconjunto = []
for i in range(2**tamanho):
for k in range(tamanho):
if i&1<<k:
subconjunto.append(lista_elementos[k])
lista_elementos.append(subconjunto)
subconjunto = []
print(lista_elementos)
def adicionar_elemento(self, item):
if item not in self.elementos:
self.elementos.append(item)
def remover_elemento(self,item):
if item in self.elementos:
self.elementos.pop(item)
c = Conjunto()
c.adicionar_elemento('a')
c.adicionar_elemento('b')
c.adicionar_elemento('c')
c.adicionar_elemento(1)
c.gerar_conjunto_partes();
|
"""
Napoleon choosed a city for Advertising his company's product. There are streets in that city. Each day he travels one street. There are buildings in a street which are located at points . Each building has some height(Say meters). Napoleon stands at point . His height is . Now Napoleon starts communicating with the people of each building. He can communicate with people of a particular building only if he can see that building. If he succeed to communicate with any particular building then his boss gives him . i.e. if he communicates with buildings in a day, then he will earn
. Now Napoleon wants to know his maximum Earning for each day.
Note: All the points are on Strainght Line and Napoleon is always standing at point 0.
Input:
First line of input contains an integer
, denoting no of streets in the city.
Details for each street is described in next two lines.
First line contains two integers and denoting no of buildings in the Street and earning on communicating with a building.
Second line contains integers, denoting height of building.
Output:
Print Lines, each containing maximum earning in street.
"""
"""---SOLUTION---"""
streets = int(input())
i = 0
while i < streets:
n, r = [int(x) for x in input().split()]
heights = list(map(int, input().strip().split()))[:n]
j = 1
profit = 1
max = heights[0]
while j < n:
if heights[j] > max:
profit += 1
max = heights[j]
j += 1
print(r * profit)
i += 1
|
"""
Vikas is given a bag which consists of numbers (integers) blocks,Vikas has to organize the numbers again in the same order as he has inserted it into the bag, i.e. the first number inserted into the bag by Vikas should be picked up first followed by other numbers in series. Help Vikas to complete this work in O(n) time complexity with the condition to use one extra bag to complete the work (assume that the bags are compact and is in the form of a stack structure and has the same width as that of the number blocks and is large enough to fill the bag to the top and the number taken from bag is in reverse order).
Hint: You may use the concept of Stacks.
SAMPLE INPUT
input: 15 21 39 390 392 380.
SAMPLE OUTPUT
output: 15 21 39 390 392 380.
"""
"""---SOLUTION---"""
n = input().split()
if (len(n) < 4):
n[0] = "output"
else:
n[0] = "output:"
print(*n)
|
"""
Tic Tac Toe Player
"""
import math
import copy
X = "X"
O = "O"
EMPTY = None
def initial_state():
"""
Returns starting state of the board.
"""
return [[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]]
def player(board):
"""
Returns player who has the next turn on a board.
"""
if board == initial_state(): # X starts in initial state
return 'X'
else:
turn = 0
for row in board:
for j in row:
if j == 'X':
turn = turn + 1
elif j == 'O':
turn = turn - 1
if turn == 1:
return 'O'
else:
return 'X'
def actions(board):
"""
Returns set of all possible actions (i, j) available on the board.
"""
actions = set() # creating the action set
i = 0
for row in board:
j = 0
for cell in row:
if cell == EMPTY:
actions.add((i, j))
j = j + 1
i = i + 1
return actions
def result(board, action):
"""
Returns the board that results from making move (i, j) on the board.
"""
try:
if action not in actions(board):
raise ValueError
new_board = copy.deepcopy(board)
turn = player(board) # returns 'X' or 'O'
new_board[action[0]][action[1]] = turn
return new_board
except ValueError as e:
print('Action not compatible with board!')
raise Exception
def winner(board):
"""
Returns the winner of the game, if there is one.
"""
# check each row
for row in board:
if row.count('X') == 3 or row.count('O') == 3:
return row[0]
# check each column
for col_no in [0,1,2]:
count = 0
j = 0
col = (board[0][col_no], board[1][col_no], board[2][col_no])
if col.count('X') == 3 or col.count('O') == 3:
return col[0]
# Check each diagonal
d1 = [board[0][0], board[1][1], board[2][2]]
if d1.count('X') == 3:
return 'X'
elif d1.count('O') == 3:
return 'O'
d2 = [board[0][2], board[1][1], board[2][0]]
if d2.count('X') == 3:
return 'X'
elif d2.count('O') == 3:
return 'O'
return None # No winner identified after all checks
def terminal(board):
"""
Returns True if game is over, False otherwise.
"""
# Check if winner
if winner(board) in ('X', 'O'):
return True
# If no winner, check if board is filled
for row in board:
for cell in row:
if cell == EMPTY:
return False # I.e. there is at least one more cell to fill
return True # Assume terminal state if board was filled but no winner
def utility(board):
"""
Returns 1 if X has won the game, -1 if O has won, 0 otherwise.
"""
if winner(board) == 'X':
return 1
elif winner(board) == 'O':
return -1
else:
return 0
def max_value_alpha_beta(board, alpha, beta):
""" Returns max value of possible moves, and best move (i,j)"""
if terminal(board):
return [utility(board), None, None]
v = float("-inf")
for action in actions(board):
v0 = v
v = max(v, min_value_alpha_beta(result(board, action),alpha,beta)[0])
if not v == v0:
max_action = action #Will adjust the max_action at least once
if v >= beta:
max_action = action
return [v, max_action]
if v>alpha:
alpha=v
return [v, max_action]
def min_value_alpha_beta(board,alpha,beta):
""" Returns min value of possible moves, and best move (i,j)"""
if terminal(board):
return [utility(board), (None, None)] # No action specified since terminal value
v = float("inf")
for action in actions(board):
v0 = v
v = min(v, max_value_alpha_beta(result(board, action),alpha,beta)[0])
if not v == v0:
min_action = action
if v<=alpha:
min_action = action
return [v,min_action]
if v<beta:
beta=v
return [v, min_action]
def minimax(board):
"""
Returns the optimal action for the current player on the board.
"""
if player(board) == 'X': # Want to maximize utility
best_action = max_value_alpha_beta(board,-2,2)
else:
best_action = min_value_alpha_beta(board,-2,2)
return best_action[1]
|
# -*- coding:utf-8 -*-
class Graph:
def __init__(self, vertex_count: int) -> None:
self.adj = [[] for _ in range(vertex_count)]
def add_edge(self, s: int, t: int, w: int) -> None:
edge = Edge(s, t, w)
self.adj[s].append(edge)
def __len__(self) -> int:
return len(self.adj)
class Vertex:
def __init__(self, v: int, dist: int) -> None:
self.id = v
self.dist = dist
def __gt__(self, other) -> bool:
return self.dist > other.dist
def __repr__(self) -> str:
return str((self.id, self.dist))
class Edge:
def __init__(self, source: int, target: int, weight: int) -> None:
self.s = source
self.t = target
self.w = weight
class VertexPriorityQueue:
def __init__(self) -> None:
self.vertices = []
def get(self) -> Vertex:
return heapq.heappop(self.vertices)
def put(self, v: Vertex) -> None:
self.vertices.append(v)
self.update_priority()
def empty(self) -> bool:
return len(self.vertices) == 0
def update_priority(self) -> None:
heapq.heapify(self.vertices)
def __repr__(self) -> str:
return str(self.vertices)
def dijkstra(g: Graph, s: int, t: int) -> int:
size = len(g)
pq = VertexPriorityQueue() # 节点队列
in_queue = [False] * size # 已入队标记
vertices = [ # 需要随时更新离s的最短距离的节点列表
Vertex(v, float('inf')) for v in range(size)
]
predecessor = [-1] * size # 先驱
vertices[s].dist = 0
pq.put(vertices[s])
in_queue[s] = True
while not pq.empty():
v = pq.get()
if v.id == t:
break
for edge in g.adj[v.id]:
if v.dist + edge.w < vertices[edge.t].dist:
# 当修改了pq中的元素的优先级后:
# 1. 有入队操作:触发了pq的堆化,此后出队可以取到优先级最高的顶点
# 2. 无入队操作:此后出队取到的顶点可能不是优先级最高的,会有bug
# 为确保正确,需要手动更新一次
vertices[edge.t].dist = v.dist + edge.w
predecessor[edge.t] = v.id
pq.update_priority() # 更新堆结构
if not in_queue[edge.t]:
pq.put(vertices[edge.t])
in_queue[edge.t] = True
for n in print_path(s, t, predecessor):
if n == t:
print(t)
else:
print(n, end=' -> ')
return vertices[t].dist
def print_path(s: int, t: int, p: List[int]) -> Generator[int, None, None]:
if t == s:
yield s
else:
yield from print_path(s, p[t], p)
yield t
from queue import PriorityQueue
@dataclass
class Edge:
start_id: int
end_id: int
weight: int
@dataclass(order=True)
class Vertex:
distance_to_start = float("inf")
vertex_id: int
class Graph:
def __init__(self, num_vertices: int):
self._num_vertices = num_vertices
self._adjacency = [[] for _ in range(num_vertices)]
def add_edge(self, from_vertex: int, to_vertex: int, weight: int) -> None:
self._adjacency[from_vertex].append(Edge(from_vertex, to_vertex, weight))
def dijkstra(self, from_vertex: int, to_vertex: int) -> None:
vertices = [Vertex(i) for i in range(self._num_vertices)]
vertices[from_vertex].distance_to_start = 0
visited = [False] * self._num_vertices
predecessor = [-1] * self._num_vertices
q = PriorityQueue()
q.put(vertices[from_vertex])
visited[from_vertex] = True
while not q.empty():
min_vertex = q.get()
if min_vertex.vertex_id == to_vertex:
break
for edge in self._adjacency[min_vertex.vertex_id]:
next_vertex = vertices[edge.end_id]
if min_vertex.distance_to_start + edge.weight < next_vertex.distance_to_start:
next_vertex.distance_to_start = min_vertex.distance_to_start + edge.weight
predecessor[next_vertex.vertex_id] = min_vertex.vertex_id
if not visited[next_vertex.vertex_id]:
q.put(next_vertex)
visited[next_vertex.vertex_id] = True
path = lambda x: path(predecessor[x]) + [str(x)] if from_vertex != x else [str(from_vertex)]
print("->".join(path(to_vertex)))
|
# -*- coding:utf-8 -*-
'''
109. Convert Sorted List to Binary Search Tree
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted linked list: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
0
/ \
-3 9
/ /
-10 5
'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def sortedListToBST(self, head):
"""
:type head: ListNode
:rtype: TreeNode
"""
if head:
pre = None
slow = fast = head
while fast and fast.next:
pre = slow
slow = slow.next
fast = fast.next.next
root = TreeNode(slow.val)
if pre:
pre.next = None
root.left = self.sortedListToBST(head)
root.right = self.sortedListToBST(slow.next)
return root
'''
110. Balanced Binary Tree
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
3
/ \
9 20
/ \
15 7
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]:
1
/ \
2 2
/ \
3 3
/ \
4 4
Return false.
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def dfs(p):
if not p:
return 0
left = dfs(p.left)
right = dfs(p.right)
if left == -1 or right == -1:
return -1
if abs(left - right) > 1:
return -1
return 1 + max(left, right)
if dfs(root) == -1:
return False
return True
'''
111. Minimum Depth of Binary Tree
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its minimum depth = 2.
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
left, right = self.minDepth(root.left), self.minDepth(root.right)
if (not left) and (not right):
return 1
if not left:
return right + 1
if not right:
return left + 1
return min(left, right) + 1
'''
112. Path Sum
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution(object):
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if root:
queue = deque([(root, root.val)])
while queue:
p, s = queue.popleft()
left, right = p.left, p.right
if left:
queue.append((p.left, s + p.left.val))
if right:
queue.append((p.right, s + p.right.val))
if not left and not right and s == sum:
return True
return False
return False
'''
113. Path Sum II
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
Return:
[
[5,4,11,2],
[5,8,4,5]
]
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
def dfs(root, s, path, res):
if root:
path.append(root.val)
s -= root.val
left = dfs(root.left, s, path, res)
right = dfs(root.right, s, path, res)
if not left and not right and s == 0:
res.append(path + [])
path.pop()
return True
res = []
dfs(root, sum, [], res)
return res
|
# -*- coding:utf-8 -*-
'''
95. Unique Binary Search Tree
Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n.
Example:
Input: 3
Output:
[
[1,null,3,2],
[3,2,null,1],
[3,1,null,null,2],
[2,1,3],
[1,null,2,null,3]
]
Explanation:
The above output corresponds to the 5 unique BST's shown below:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
def clone(root, offset):
if root:
newRoot = TreeNode(root.val + offset)
left = clone(root.left, offset)
right = clone(root.right, offset)
newRoot.left = left
newRoot.right = right
return newRoot
if not n:
return []
dp = [[]] * (n + 1)
dp[0] = [None]
for i in range(1, n + 1):
dp[i] = []
for j in range(1, i + 1):
for left in dp[j - 1]:
for right in dp[i - j]:
root = TreeNode(j)
root.left = left
root.right = clone(right, j)
dp[i].append(root)
return dp[-1]
'''
96. Unique Binary Search Tree
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Example:
Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
'''
class Solution(object):
def _numTrees(self, n):
"""
:type n: int
:rtype: int
"""
dp = [0] * (n + 1)
dp[0] = dp[1] = 1
for i in range(2, n + 1):
for j in range(1, i + 1):
dp[i] += dp[j - 1] * dp[i - j]
return dp[-1]
def numTrees(self, n):
ans = 1
for i in range(1, n + 1):
ans = ans * (n + i) / i
return ans / (n + 1)
'''
97. Interleavig String
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
Example 1:
Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
Output: true
Example 2:
Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
Output: false
'''
class Solution(object):
def isInterleave(self, s1, s2, s3):
"""
:type s1: str
:type s2: str
:type s3: str
:rtype: bool
"""
d = {}
s3 = list(s3)
if len(s1) + len(s2) != len(s3):
return False
def dfs(s1, i, s2, j, d, path, s3):
if (i, j) in d:
return d[(i, j)]
if path == s3:
return True
if i < len(s1):
if s3[i + j] == s1[i]:
path.append(s1[i])
if dfs(s1, i + 1, s2, j, d, path, s3):
return True
path.pop()
d[(i+1, j)] = False
if j < len(s2):
if s3[i + j] == s2[j]:
path.append(s2[j])
if dfs(s1, i, s2, j + 1, d, path, s3):
return True
path.pop()
d[(i, j+1)] = False
return False
return dfs(s1, 0, s2, 0, d, [], s3)
|
# -*- coding:utf-8 -*-
# 迪杰斯特拉算法适用于带权重的有向无环图(权重非负)
# graph["a"] = {}
# graph["a"]["fin"] = 1
# graph["b"] = {}
# graph["b"]["a"] = 3
# graph["b"]["fin"] = 5
# graph["fin"] = {} ←------终点没有任何邻居
# infinity = float("inf")
# costs = {}
# costs["a"] = 6
# costs["b"] = 2
# costs["fin"] = infinity
# parents = {}
# parents["a"] = "start"
# parents["b"] = "start"
# parents["fin"] = None
def dijstra(start, target, graph):
costs, parents = init_costs(graph, start, target), init_parents(graph, start, target)
node = find_lowest_cost_node(costs) # ←------在未处理的节点中找出开销最小的节点
while node: # ←------这个while循环在所有节点都被处理过后结束
cost = costs[node]
neighbors = graph[node]
for n in neighbors.keys(): # ←------遍历当前节点的所有邻居
new_cost = cost + neighbors[n]
if costs[n] > new_cost: # ←------如果经当前节点前往该邻居更近,
costs[n] = new_cost # ←------就更新该邻居的开销
parents[n] = node # ←------同时将该邻居的父节点设置为当前节点
processed.add(node) # ←------将当前节点标记为处理过
node = find_lowest_cost_node(costs) # ←------找出接下来要处理的节点,并循环
def find_lowest_cost_node(costs):
lowest_cost = float("inf")
lowest_cost_node = None
for node in costs: # ←------遍历所有的节点
cost = costs[node]
if cost < lowest_cost and node not in processed: # ←------如果当前节点的开销更低且未处理过,
lowest_cost = cost # ←------就将其视为开销最低的节点
lowest_cost_node = node
return lowest_cost_node
def init_costs(graph, start, target):
costs = {}
for node in range graph[start].keys():
costs[node] = graph[start][node]
if costs.get(target, None) is None:
costs[target] = float("inf")
return costs
def init_parents(graph, start, target):
parents = {}
for node in range graph[start].keys():
parents[node] = start
if parents.get(target, None) is None:
parents[target] = None
return parents
# 啊哈 P152
def warshal():
for k in range(k):
for i in range(n):
for j in range(n):
if e[i][j] > e[i][k] + e[k][j]:
e[i][j] = e[i][k] + e[k][j]
# Bellman-Ford 解决负权边 啊哈 P163 优化队列P171 对比P177
def bellman():
for k in range(n-1):
for i in range(m):
if dis[v[i]] > dis[u[i]] + w[i]:
dis[v[i]] = dis[u[i]] + w[i]
|
# -*- coding:utf-8 -*-
'''
4. Median of Two Sorted Arrays
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
Example:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
'''
class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
a, b = sorted((nums1, nums2), key=len)
m, n = len(a), len(b)
after = (m + n - 1) / 2
lo, hi = 0, m
while lo < hi:
i = (lo + hi) / 2
if after-i-1 < 0 or a[i] >= b[after-i-1]:
hi = i
else:
lo = i + 1
i = lo
nextfew = sorted(a[i:i+2] + b[after-i:after-i+2])
return (nextfew[0] + nextfew[1 - (m+n)%2]) / 2.0
'''
5. Longest Palindromic Substring
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Input: "cbbd"
Output: "bb"
'''
class Solution:
def longestPalindrome(self, s):
# Transform S into T.
# For example, S = "abba", T = "^#a#b#b#a#$".
# ^ and $ signs are sentinels appended to each end to avoid bounds checking
T = '#'.join('^{}$'.format(s))
n = len(T)
P = [0] * n
C = R = 0
for i in range (1, n-1):
P[i] = (R > i) and min(R - i, P[2*C - i]) # equals to i' = C - (i-C)
# Attempt to expand palindrome centered at i
while T[i + 1 + P[i]] == T[i - 1 - P[i]]:
P[i] += 1
# If palindrome centered at i expand past R,
# adjust center based on expanded palindrome.
if i + P[i] > R:
C, R = i, i + P[i]
# Find the maximum element in P.
maxLen, centerIndex = max((n, i) for i, n in enumerate(P))
return s[(centerIndex - maxLen)/2: (centerIndex + maxLen)/2]
'''
6. ZigZag Conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
(you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
'''
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1 or numRows >= len(s):
return s
L = [''] * numRows
index, step = 0, 1
for x in s:
L[index] += x
if index == 0:
step = 1
elif index == numRows -1:
step = -1
index += step
return ''.join(L)
"""
7. Reverse Integer
Given a 32-bit signed integer, reverse digits of an integer.
Example:
Input: 123
Output: 321
Input: -123
Output: -321
Input: 120
Output: 21
"""
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
sign = x < 0 and -1 or 1
x = abs(x)
ans = 0
while x:
ans = ans * 10 + x % 10
x /= 10
return sign * ans if ans <= 0x7fffffff else 0
|
# -*- coding:utf-8 -*-
def insert_sort(lists):
'''
插入排序
Best: O(n)
Average: O(n^2)
Worst: O(n^2)
'''
count = len(lists)
for i in range(1, count):
key = lists[i]
j = i - 1
while j >= 0:
if lists[j] > key:
lists[j + 1] = lists[j]
lists[j] = key
j -= 1
return lists
def shell_sort(lists):
'''
希尔排序
Best: O(nlog(n))
Average: O(nlog(n)^2)
Worst: O(nlog(n)^2)
'''
count = len(lists)
step = 2
group = count / step
while group > 0:
for i in range(0, group):
j = i + group
while j < count:
k = j - group
key = lists[j]
while k >= 0:
if lists[k] > key:
lists[k + group] = lists[k]
lists[k] = key
k -= group
j += group
group /= step
return lists
def bubble_sort(lists):
'''
冒泡排序
Best: O(n)
Avergae: O(n^2)
Worst: O(n^2)
'''
count = len(lists)
for i in range(0, count):
for j in range(i + 1, count):
if lists[i] > lists[j]:
lists[i], lists[j] = lists[j], lists[i]
return lists
def quick_sort(lists, left, right):
'''
快速排序
Best: O(nlog(n))
Average: O(nlog(n))
Worst: O(n^2)
'''
if left >= right:
return lists
key = lists[left]
low = left
high = right
while left < right:
while left < right and lists[right] >= key:
right -= 1
lists[left] = lists[right]
while left < right and lists[left] <= key:
left += 1
lists[right] = lists[left]
lists[right] = key
quick_sort(lists, low, left - 1)
quick_sort(lists, left + 1, high)
return lists
'''
def quicksort(seq):
if len(seq) <= 1:
return seq
lo, pi, hi = partition(seq)
return quicksort(lo) + [pi] + quicksort(hi)
def partition(seq):
pi, seq = seq[0], seq[1:]
lo = [x for x in seq if x <= pi]
hi = [x for x in seq if x > pi]
return lo, pi, hi
'''
def select_sort(lists):
'''
选择排序
Best: O(n^2)
Average: O(n^2)
Worst: O(n^2)
'''
count = len(lists)
for i in range(0, count):
min = i
for j in range(i + 1, count):
if lists[min] > lists[j]:
min = j
lists[min], lists[i] = lists[i], lists[min]
return lists
def adjust_heap(lists, i, size):
lchild = 2 * i + 1
rchild = 2 * i + 2
max = i
if i < size / 2:
if lchild < size and lists[lchild] > lists[max]:
max = lchild
if rchild < size and lists[rchild] > lists[max]:
max = rchild
if max != i:
lists[max], lists[i] = lists[i], lists[max]
adjust_heap(lists, max, size)
def build_heap(lists, size):
for i in range(0, (size/2))[::-1]:
adjust_heap(lists, i, size)
def heap_sort(lists):
'''
堆排序
Best: O(nlog(n))
Average: O(nlog(n))
Worst: O(nlog(n))
'''
size = len(lists)
build_heap(lists, size)
for i in range(0, size)[::-1]:
lists[0], lists[i] = lists[i], lists[0]
adjust_heap(lists, 0, i)
def merge(left, right):
i, j = 0, 0
result = []
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result += left[i:]
result += right[j:]
return result
def merge_sort(lists):
'''
归并排序
Best: O(nlog(n))
Average: O(nlog(n))
Worst: O(nlog(n))
'''
if len(lists) <= 1:
return lists
num = len(lists) / 2
left = merge_sort(lists[:num])
right = merge_sort(lists[num:])
return merge(left, right)
import math
def radix_sort(lists, radix=10):
'''
基数排序
Best: O(nk)
Average: O(nk)
Worst: O(nk)
'''
k = int(math.ceil(math.log(max(lists), radix)))
bucket = [[] for i in range(radix)]
for i in range(1, k+1):
for j in lists:
bucket[j/(radix**(i-1)) % (radix**i)].append(j)
del lists[:]
for z in bucket:
lists += z
del z[:]
return lists
def timsort(the_array):
'''
timsort
Best: O(n)
Averagr: O(nlog(n))
Worst: O(nlog(n))
Python中的sorted()方法
'''
runs, sorted_runs = [], []
l = len(the_array)
new_run = [the_array[0]]
for i in range(1, l):
if i == l-1:
new_run.append(the_array[i])
runs.append(new_run)
break
if the_array[i] < the_array[i-1]:
if not new_run:
runs.append([the_array[i-1]])
new_run.append(the_array[i])
else:
runs.append(new_run)
new_run = []
else:
new_run.append(the_array[i])
for each in runs:
sorted_runs.append(insert_sort(each))
sorted_array = []
for run in sorted_runs:
sorted_array = merge(sorted_array, run)
print sorted_array
def bucket_sort(seq):
'''
桶排序
Best: O(n+k)
Average: O(n+k)
Worst: O(n^2)
'''
biggest = 0
for number in seq:
if number > biggest:
biggest = number
buckets = []
buckets.append([]) * (biggest / 10 + 1)
for number in seq:
buckets[number / 10].append(number)
for index, bucket in enumerate(buckets):
#Using quicksort to sort individual buckets
buckets[index] = quick_sort(bucket)
new_list = [number for number in bucket for bucket in buckets]
return new_list
def counting_sort(array):
'''
计数排序
Best: O(n+k)
Average: O(n+k)
Worst: O(n+k)
'''
maxval = max(array)
m = maxval + 1
count = [0] * m
for a in array:
count[a] += 1
i = 0
for a in range(m):
for c in range(count[a]):
array[i] = a
i += 1
return (array,count)
|
# -*- coding:utf-8 -*-
def binary_search(array, target):
first = 0
last = len(array) - 1
while first <= last:
i = first + (last - first) / 2
if array[i] == target:
return i
elif array[i] > target:
last = i - 1
elif array[i] < target:
first = i + 1
return -1
|
print "Largest Number Exercise"
# Print the largest number in the list
num_list = [10, 24, 4, 14, 35, 31, 18]
big_num = num_list[0]
for num in num_list:
if num > big_num:
big_num = num
print big_num
|
print "Sum the Numbers Exercise"
# Given a list of numbers, print their sum.
num_list = [1, 2, 3, 4, 5, 6]
sum = 0
for num in num_list:
sum += num
print sum
|
fruits = ["Grapefruit", "Longan", "Orange", "Apple", "Cherry"]
for idx, val in enumerate(fruits, start= 1):
print("index is %d and value is %s" % (idx, val))
|
a = {1, 2, 3, 4}
b = {1, 3, 5, 7}
c = a | b
d = a - b
print("a is", a)
print("b is", b)
print("a | b is", c)
print("a - b is", d)
ab = []
ac = []
ad = []
for n in range(20):
ab.append(n)
x = range(3, 13)
for n in x:
ac.append(n)
y = range(2, 51, 3)
for n in y:
ad.append(n)
print(ab)
print(ac)
print(ad)
|
W1 = ['Moday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
W2 = ['Saturday', 'Sunday']
W3 = W1 + W2
W4 = W1 + W2
W5 = W1 + W2
W6 = W1 + W2
W5.reverse()
W4.sort()
print("Weekday are", W1)
print("Days are", W2)
print("Sorted days are", W3)
print("Sorted days are", W4)
print("Reverse days are", W5)
print("The last two days of list days are", W6[-2:])
|
while True:
num = int(input("Enter an integer:"))
number = num
find = num % 2
if num < 0:
False
elif num >= 99:
break
elif find == 1:
False
else:
print(number)
|
num = int(input("Enter a number to find the factorial:"))
number = num
total = 1
while num > 0:
total = total * (num)
num -= 1
print("Factorial of", number, "is", total)
|
"""
Algoritmo responsavel por criar realizar busca em profundidade
"""
from Pilha import Pilha
class Busca_Em_Profundidade:
def __init__(self, inicio, objetivo):
self.inicio = inicio
self.inicio.visitado = True
self.objetivo = objetivo
#fronteira armazena pilha de cidades que serão visitadas
self.fronteira = Pilha(10000)
self.fronteira.empilhar(inicio)
self.achou = False
def buscar(self):
topo = self.fronteira.getTopo()
if topo == self.objetivo :
self.achou = True
print("Objetivo {}" .format(self.objetivo.nome), "foi alcançado apartir de {}" .format(self.inicio.nome))
else:
print("Topo: {}".format(topo.nome))
for adjacente in topo.adjacentes:
if self.achou == False:
self.fronteira.empilhar(adjacente.cidade)
Busca_Em_Profundidade.buscar(self)
#print("Desempilhou: {}" .format(self.fronteira.desempilhar().nome))
from Mapa import Mapa
mapa = Mapa()
profundidade = Busca_Em_Profundidade(mapa.portoUniao, mapa.canoinhas)
profundidade.buscar()
|
x = int(input("Insert the numerator: "))
y = int(input("Insert the denomiator: "))
if x%y == 0:
print(x, " is divisible by ", y)
else:
print("No! ", x, " is not divisible by ", y)
|
for x in range(1,10):
for y in range(1,10):
print("%4d" % (x*y), end="")
print()
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
actual_date, actual_month, actual_year = map(int, input().split())
expected_date, expected_month, expected_year = map(int, input().split())
if (actual_year, actual_month, actual_date) <= (expected_year, expected_month, expected_date):
print(0)
elif (actual_year, actual_month) == (expected_year, expected_month):
print(15 * (actual_date - expected_date))
elif actual_year == expected_year:
print(500 * (actual_month - expected_month))
else:
print(10000)
|
def main():
for integer in range(1, 101):
print("%-7i%-13s%-13s" % (integer, bin(integer), hex(integer)))
return
if __name__ == "__main__":
main()
|
from math import sqrt
def basel(n):
# Compute the sum of 1 / k ** 2 for k=1 to n.
total = 0
for k in range(1, n + 1):
total += 1 / (k ** 2)
return total
def main():
print("%-13s%-13s%-13s" % ("n", "sum", "sqrt(6*sum)"))
for n in range(1, 100001, 1000):
print("%-13f%-13f%-13f" % (n, basel(n), sqrt(6 * basel(n))))
return
if __name__ == "__main__":
main()
|
"""
"""
class QwickSort:
def partition(data, low, high):
pivot = data[(low + high) // 2]
i = low - 1
j = high + 1
while True:
i += 1
while data[i] < pivot:
i += 1
j -= 1
while data[j] > pivot:
j -= 1
if i >= j:
return j
data[i], data[j] = data[j], data[i]
def sort(data):
def _sort(items, low, high):
if low < high:
split_index = QwickSort.partition(items, low, high)
_sort(items, low, split_index)
_sort(items, split_index + 1, high)
_sort(data, 0, len(data) - 1)
return data
print(QwickSort.sort([1,35,6,1,2,3]))
|
num_estados = int(input('Ingrese numero de estados: '))
num_trans = int(input('Ingrese numero de transiciones: '))
Estados = []
Transiciones = []
for i in range(num_estados):
if(i == 0):
print('Introduce estado inicial: ')
Estados.append(input())
else:
print('Introduce estado :')
Estados.append(input())
for i in range(num_trans):
print('Introduce Transicion:')
Transiciones.append(input())
print(Estados)
print(Transiciones)
filas = num_estados
columnas = num_trans
tabla = [[0 for x in range(num_trans)] for y in range(num_estados)]
for i in range(num_trans):
tabla[i][0] = Transiciones[i]
for i in range(num_estados):
tabla[0][i] = Estados[i]
print(tabla)
|
def get_file_contents(file_path):
"""
Reads the contents of a single-line txt file.
:param file_path: A string representing the path of the file
:return: A string containing the contents of the file
"""
file = open(file_path, 'r')
new_sequence = file.read()
file.close()
return new_sequence
def update_frequencies(old_frequencies, new_sequence):
"""
Updates a list of nucleotide frequencies to reflect the addition of a new sequence's nucleotides.
:param old_frequencies: A list of frequency tuples
:param new_sequence: A string representing a DNA sequence
:return: An updated list of frequency tuples
"""
num_a = old_frequencies[0][1]
num_c = old_frequencies[1][1]
num_t = old_frequencies[2][1]
num_g = old_frequencies[3][1]
for x in range(len(new_sequence)):
if new_sequence[x] == "A":
num_a += 1
elif new_sequence[x] == "C":
num_c += 1
elif new_sequence[x] == "T":
num_t += 1
elif new_sequence[x] == "G":
num_g += 1
return [('A', num_a), ('C', num_c), ('T', num_t), ('G', num_g)]
def main():
"""
Just some sample behavior based on the README. Feel free to try your own.
"""
old_frequencies = [("A", 20), ("C", 23), ("T", 125), ("G", 4)]
# new_sequence = "ACCCGTTA"
new_sequence = get_file_contents("dna_sequence.txt")
new_frequencies = update_frequencies(old_frequencies, new_sequence)
print(new_frequencies)
# DO NOT WRITE CODE BELOW THIS LINE
if __name__ == '__main__':
main()
|
points = [{"x":-1,"y":-1}]
def setup():
size(800,600)
def draw():
s = 10
for i in range(100):
x = int(random(width))
y = int(random(height))
point = {
"x": x,
"y": y
}
pex = False
# for p in points:
# px = p.get("x")
# py = p.get("y")
# if (x >= px and x < px+s and y >= py and y < py+s):
# pex = True
# break
if pex == False:
points.append(point)
r = random(255)
g = random(255)
b = random(255)
w = random(255)
a = 100
noStroke()
if ((x >= 0 and x < 10) or (x <= width and x > width-20) or (y >= 0 and y < 10) or (y <= height and y > height-20)):
c = color(0, a)
#stroke(255)
elif ((x > width/2 - 10 and x < width / 2 + 10) or (y > height/2 - 10 and y < height/2 + 10)):
if w < 150:
w += 100
c = color(w, a)
#stroke(0)
elif ((x > width/2 and x < width) and (y >=0 and y < height/2)):
randomInt = int(random(2))
if randomInt == 0:
c = color(w, a)
else:
if (r < 100):
r += 100
c = color(r, 0,0, a)
#stroke(0)
else:
c = color(r,g,b, a)
fill(c)
rect(x,y, s,s)
|
#accessing elements from a tuple using position and finding value
i=0;
myTuple=("red","yellow","black");
print(myTuple);
y=int(input("Which element would you like to access? Enter position"));
print(myTuple[y-1]);
#accessing elements from a tuple using value and finding position
i=0;
myTuple=("red","yellow","black");
print(myTuple);
z=input("Which element would you like to access? Enter value");
for i in range(0,3):
if(myTuple[i]== z):
print("element "+z+" is in postition:");
print(i);
#assigning values to different lists
k=0;
myList=[1,2,3,4,5];
print(myList);
a=int(input("How many elements would you like to insert"));
while(k<a):
x=int(input("Which element would you like input"));
myList.append(x);
k=k+1;
print(myList);
#Deleting different dictionary elements
c="y";
myDict={"A":"Apple","B":"Bat","C":"Cat","D":"Dog"};
print(myDict);
while(c=="y"):
b=input("Enter which element to delete");
del myDict[b];
c=input("would you like to delete again? if so enter y else n");
print(myDict);
|
"""
spiral.py
------------
Create helical plunges and spirals.
"""
import numpy as np
import networkx as nx
from . import graph
from . import polygons
from . import constants
def offset(polygon, step):
"""
Create a spiral inside a polygon by offsetting the
polygon by a step distance and then interpolating.
Parameters
-----------
polygon : shapely.geometry.Polygon object
Source geometry to create spiral inside of
step : float
Distance between each step of the curve
Returns
----------
spiral : (n, 2) float
Points representing a spiral path
contained inside polygon
"""
g, offset = polygons.offset_graph(polygon, step)
# make sure offset polygon graph topology supports this
assert graph.is_1D_graph(g)
# make sure polygons don't have interiors
assert all(len(v.interiors) == 0 for v in offset.values())
# starting point for each section of curve
start = None
# store a sequence of (m,2) float point curves
path = []
# root node is index 0
nodes = list(nx.topological_sort(g))
# loop through nodes in topological order
for i in range(len(nodes) - 1):
# get the polygons we're looking at
a = offset[nodes[i]]
b = offset[nodes[i + 1]]
# create the spiral section between a and b
curve = polygons.interpolate(a, b, start=start)
# make sure the next section starts where this
# section of the curve ends
start = curve[-1]
# store the curve in the main sequence
path.append(curve)
# stack to a single (n,2) float list of points
path = np.vstack(path)
# check to make sure we didn't jump on any step
# that would indicate we did something super screwey
gaps = (np.diff(path, axis=0) ** 2).sum(axis=1).max()
assert gaps < 1e-3
return path
def archimedean(
radius_start,
radius_end,
step,
center=None,
close=False,
point_start=None,
angle_start=None,
arc_res=None):
"""
Construct an Archimedean Spiral from radius and
per-revolution step.
The equation of an Archimedean Spiral is:
r = K * theta
Parameters
------------
radius_start : float
Starting radius of the spiral
radius_end : float
Maximum radius of the spiral
step : float
The distance to step between each full revolution
close : bool
Do a full revolution at the final radius or not
angle_start : float or None
Start at an angle offset or not
arc_res : float or None
The angular size of each returned arc
Returns
------------
points : (n, 3, 2) float
Three-point arcs forming an Archimedean Spiral
"""
if radius_start > radius_end:
sign = 1
else:
sign = -1
# the spiral constant
# evaluated from: step = K * 2 * pi
K = step / (np.pi * 2)
# use our constant to find angular start and end
theta_start = radius_start / K
theta_end = radius_end / K
# if not passed set angular resolution
if arc_res is None:
arc_res = constants.default_arc
arc_count = int(np.ceil((
abs(theta_end - theta_start)) / arc_res))
# given that arcs will share points how many
# points on the helix do we need
arc_index, point_count = arc_indexes(arc_count)
assert arc_index.max() == point_count - 1
# create an array of angles
theta = np.linspace(theta_start, theta_end, point_count)
# use the spiral equation to generate radii
radii = theta * K
# make sure they match
assert np.isclose(radii[0], radius_start)
assert np.isclose(radii[-1], radius_end)
# do offset AFTER radius calculation
if angle_start is not None:
theta += (angle_start - theta_start)
# convert polar coordinates to 2D cartesian
points = np.column_stack(
(np.cos(theta), np.sin(theta))) * radii.reshape((-1, 1))
if close:
# get indexes of arcs required to close
close_idx, close_ct = arc_indexes(
int(np.ceil((np.pi * 2) / arc_res)))
# the additional angles needed to close
# we are cutting off the first point as its a duplicate
t_close = np.linspace(theta[-1],
theta[-1] + np.pi * 2 * sign,
close_ct)[1:]
# additional points to close the arc
closer = np.column_stack((
np.cos(t_close), np.sin(t_close))) * radii[-1]
assert len(closer) == close_ct - 1
assert len(points) == point_count
# stack points with closing arc
points = np.vstack((points, closer))
# add the additional points to the count
point_count += close_ct - 1
# add the additional arc indexes
arc_index = np.vstack((
arc_index, arc_index[-1][-1] + close_idx))
assert len(points) == point_count
# max index of arcs should correspond to points
assert arc_index[-1][-1] == point_count - 1
if center is not None:
points += center
# convert sequential points into three point arcs
arcs = points[arc_index]
if constants.strict:
# check all arcs to make sure the correspond
for a, b in zip(arcs[:-1], arcs[1:]):
assert np.allclose(a[2], b[0])
if point_start is not None:
a, b = np.clip(
(point_start[:2] - center[:2]) / radius_start,
-1.0, 1.0)
assert np.isclose(a, np.cos(angle_start), atol=1e-3)
assert np.isclose(b, np.sin(angle_start), atol=1e-3)
return arcs
def helix(radius,
height,
pitch,
center=None,
arc_res=None,
epsilon=1e-8,
return_angle=False):
"""
Create an approximate 3D helix using 3-point circular arcs.
Parameters
------------
radius : float
Radius of helix
height : float
Overall height of helix
pitch : float
How far to advance in Z for every rotation
arc_res : None or float
Approximately how many radians should returned arcs span
epsilon : float
Threshold for zero
Returns
--------------
arcs : (n, 3, 3) float
Ordered list of 3D circular arcs
"""
if np.abs(height) < epsilon:
arcs = np.array([], dtype=np.float64)
if return_angle:
return arcs, 0.0
return arcs
# set a default arc size if not passed
if arc_res is None:
arc_res = constants.default_arc
# total angle we're traversing
angle = (np.pi * 2.0 * height) / pitch
# how many arc sections will result, making sure to ceil
arc_count = int(np.ceil(angle / arc_res))
arc_index, point_count = arc_indexes(arc_count)
# we're doing 3-point arcs
theta = np.linspace(0.0, angle, point_count)
# Z is linearly ramping for every point
z = np.linspace(0.0, height, len(theta))
# convert cylindrical to cartesian
cartesian = np.column_stack(
(np.cos(theta), np.sin(theta), z))
# multiply XY by radius
cartesian[:, :2] *= radius
if center is not None:
cartesian[:, :2] += center
else:
center = [0, 0, 0]
# now arcs are 3 cartesian points
arcs = cartesian[arc_index]
if return_angle:
# return the final angle
helix_end = theta[-1] % (np.pi * 2)
vec = arcs[-1][-1][:2] - center[:2]
# norm of arc should be close to radius
assert np.isclose(np.linalg.norm(vec), radius, rtol=1e-3)
# check to make sure the angle is accurate
a, b = np.clip(vec / radius, -1.0, 1.0)
ac, bc = np.cos(helix_end), np.sin(helix_end)
assert np.isclose(a, ac, atol=1e-3)
assert np.isclose(b, bc, atol=1e-3)
return arcs, helix_end
return arcs
def arc_indexes(arc_count):
"""
Parameters
-----------
count : int
Number of arcs
Returns
----------
arc_index : (n, 3) int
Indexes of arcs sharing common points
points_count : int
Number of range points
Examples
----------
0 1 2 3 4 5 6
*--*--x--*--x--*--*
[[0,1,2],[2,3,4],[4,5,6]]
arc_count:3, point_count=7
0 1 2
*--*--*
[[0,1,2]] 3
arc_count:1 point_count=3
0 1 2 3 4 5 6 7 8 9 10 11 12
*--*--x--*--x--*--x--*--x--*--x--*--x
[[0,1,2],[2,3,4],[4,5,6],[6,7,8],[8,9,10],[10,11,12]]
arc count: 6, point_count: 13
"""
# given that arcs will share points how many
# points on the helix do we need
point_count = (2 * arc_count) + 1
# use index wangling to generate that from counts
arc_index = np.arange(point_count - 1).reshape((-1, 2))
arc_index = np.column_stack((
arc_index, arc_index[:, 1] + 1))
assert arc_index[-1][-1] == point_count - 1
assert arc_index.max() == (point_count - 1)
return arc_index, point_count
|
import cs50
# This program requests input from the user on how much change is owed.
# It then calculates the minimum number of coins required to provide the change.
def main():
while True:
print("How much change do I owe you?")
change = cs50.get_float()
if change>0:
break
# Converts the amount of change into dollars and round to the nearest
# whole integer. Doing this will prevent errors from imprecise decimals
# in float values.
cents = round(change * 100)
q = 25
d = 10
n = 5
p = 1
# Start with the coin of largest value (quarter = q) and work your way down
# to the smallest value (penny = p).
count = cents // q
cents = cents % q
count += cents // d
cents = cents % d
count += cents // n
cents = cents % n
count += cents // p
cents = cents % p
print(count)
if __name__ == "__main__":
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.