text
stringlengths 37
1.41M
|
---|
# -*- coding: utf-8 -*-
"""
Created on Mon May 4 09:47:46 2015
@author: liran
"""
class A:
@staticmethod
def st():
print "static"
def __init__(self,num):
self.__num = num
print "A"
def f1(self):
print self.__num
class B(A):
def __init__(self,num,size):
A.__init__(self,num)
self.__size=size
print "B"
#a1=A()
A.st()
B.st()
b1=B(2,3)
b1.f1()
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed May 17 17:20:38 2017
@author: parallels
"""
# Using the generator pattern (an iterable)
class firstn(object):
def __init__(self, n):
self.n = n
self.num, self.nums = 0, []
def __iter__(self):
#self.num, self.nums = 0, []
return self
# Python 3 compatibility
def __next__(self):
return self.next()
def next(self):
if self.num < self.n:
cur, self.num = self.num, self.num+1
return cur
else:
raise StopIteration()
sum_of_first_n1 = sum(firstn(1000000))
# a generator that yields items instead of returning a list
def firstnfun(n):
num = 0
while num < n:
yield num
num += 1
sum_of_first_n2 = sum(firstnfun(1000000))
# Note: Python 2.x only
# using a non-generator
sum_of_first_n3 = sum(range(1000000))
# using a generator
sum_of_first_n4 = sum(xrange(1000000))
doubles = [2 * n for n in range(50)] # list
doubles = (2 * n for n in range(50)) # gen
doubles = list(2 * n for n in range(50)) #list
# Note: Python 2.x only
#s = sum(xrange(1000000))
#p = product(xrange(1000000))
|
# Python 2 version
# Code for reading in the date */
date = raw_input("Please enter date (DD/MM/YYYY): ")
d,m,y = date.split('/')
d = int(d)
m = int(m)
y = int(y)
"""
Add Your Code Here: to adjust the values of
d, m and y under certain circumstances
d contains the day
m contains the month
y contains the year
"""
z = 1 + d + (m * 2) + (3 * (m + 1) // 5) + y + y//4 - y//100 + y//400
z %= 7
days = ["Sun","Mon","Tues","Wednes","Thurs","Fri","Satur"]
print days[z]+'day'
|
#!/usr/bin/python
Belgium = 'Belgium,10445852,Brussels,737966,Europe,1830,Euro,Catholicism,Dutch,French,German'
items = Belgium.split(',')
print '-' * len(Belgium)
print ':'.join(items)
#print items[1] + items[3]
print int(items[1]) + int(items[3])
print '-' * len(Belgium)
"""Well I have this large quantity of string, a hundred and twenty-two
thousand *miles* of it to be exact, which I inherited.
Due to bad planning, the hundred and
twenty-two thousand miles is in three inch lengths.
So it's not very useful."""
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri May 12 11:49:31 2017
@author: parallels
"""
#
#class First(object):
# def __init__(self):
# print "first"
# def ff1(self):
# return 1
#
#class Second(First):
# def __init__(self):
# super(First, self).__init__()
# print "second"
# def ff1(self):
# return 2
#
#class Third(First):
# def __init__(self):
# super(First, self).__init__()
# print "third"
# def ff1(self):
# return 3
#
##########################################
# super instead of className to call all classes when mulitple inheritance
#
###############################################
class First(object):
def __init__(self):
super(First, self).__init__()
print ("first")
class Second(object):
def __init__(self):
super(Second, self).__init__()
print ("second")
class Third(First, Second):
def __init__(self):
super(Third, self).__init__()
print ("that's it")
f = Third()
class A(object):
def __init__(self):
print('Running A.__init__')
super(A,self).__init__()
class B(A):
def __init__(self):
print('Running B.__init__')
############################## C is not called !!! -> commen out for fix
super(B,self).__init__()
########################################
#A.__init__(self)
class C(A):
def __init__(self):
print('Running C.__init__')
super(C,self).__init__()
#A.__init__(self);
class D(B,C):
def __init__(self):
print('Running D.__init__')
super(D,self).__init__()
# B.__init__(self)
# C.__init__(self)
foo=D()
|
# -*- coding: utf-8 -*-
class Rectangle:
def __init__(self,width,height):
self.__width = width
self.__height = height
def __PrintHeader(self):
print("******************************************")
def Print(self):
self.__PrintHeader()
print("Recangle Width:" + str(self.__width) +
" Height:" + str(self.__height))
a = Rectangle(10,20)
a.Print()
a.__PrintHeader() # error
a.__height = -80 # new attribute
a.Print()
|
class Invoker(object):
def __init__(self):
self._subscribers = []
def __add__(self,subscriber):
self._subscribers.append(subscriber)
return self
def __sub__(self,subscriber):
if(subscriber in self._subscribers):
self._subscribers.remove(subscriber)
return self
def Invoke(self,message,exclude=None):
for s in self._subscribers:
if(s!=exclude):
s(message)
def handler1(message):
print ("handler1 got:" + message)
def handler2(message):
print ("handler2 got:" + message)
def handler3(message):
print ("handler3 got:" + message)
def handler4(message):
print ("handler4 got:" + message)
class A(object):
def __init__(self,val):
self.__val=val
def handler5(self,message):
print ("handler1 got:" + message + " with " + str(self.__val))
inv = Invoker()
a1 = A(10)
a2 = A(20)
inv+=a1.handler5
inv+=a2.handler5
inv+=handler1
inv+=handler2
inv+=handler3
inv+=handler1
inv+=handler4
inv.Invoke("Hi all")
print("********")
inv-=(handler1)
inv-=(handler1)
inv.Invoke("Hello all",handler1)
|
from Country import Country
countries = []
# Question 1a, implement a constructor
for line in open('country.txt') :
countries.append(Country(line))
# Question 1b, implement a printit method
for country in countries:
country.printit()
# Question 1c, implement string overloading
print country
# Question 1d, implement a getter function for population
print country,
print country.population
# Question 1e, overload + and -
print "Before:",countries[20].population
countries[20] += 10
print "After adding 10:",countries[20].population
countries[20] = countries[20] - 3
print "After subtracting 3:",countries[20].population
print
# Check that the __add__ worked
first = countries[0]
Neverland = first + 100
if Neverland.population == first.population:
print "Your __add__ did not do a deepcopy!"
elif Neverland.population == first.population + 100:
print "Congratulations, your __add__ worked!"
else:
print "Your __add__ needs some attention!"
# If time allows:
# Question 1f, overload the == operator
here = countries.index('Sweden')
sweden = countries[here]
print sweden,here
# Question 1g, amend the __str__ to format the name and population
sweden += 42
print sweden
print sweden + 4
print sweden - 3
|
'''
To create a program to check whether two words/sentences are
anagrams of each other or not.
'''
def anagram_check(s1,s2):
s1 = "".join(s1.lower().split())
s2 = "".join(s2.lower().split())
if len(s1) != len(s2):
return False
d1 = {}
d2 = {}
for i in s1:
try:
d1[i] += 1
except:
d1[i] = 1
for i in s2:
try:
d2[i] += 1
except:
d2[i] = 1
if d1==d2:
return True
else:
return False
def anagram_check2(s1,s2):
s1 = s1.replace(" ","").lower()
s2 = s2.replace(" ","").lower()
return sorted(s1) == sorted(s2)
from nose.tools import assert_equal
class AnagramTest(object):
def test(self,sol):
assert_equal(sol('go go go','gggooo'),True)
assert_equal(sol('abc','cba'),True)
assert_equal(sol('hi man','hi man'),True)
assert_equal(sol('aabbcc','aabbc'),False)
assert_equal(sol('123','1 2'),False)
print('ALL TEST CASES PASSED')
# Run Tests
t = AnagramTest()
t.test(anagram_check)
t.test(anagram_check2)
|
'''
Alternate implementation of BFS.
'''
graph = { 'A' : set(['B','C']),
'B' : set(['A','D','E']),
'C' : set(['A','F']),
'D' : set(['B']),
'E' : set(['B','F']),
'F' : set(['C','E'])
}
def bfs(graph,start):
visited = set()
queue = [start]
while queue:
vertex = queue.pop(0)
if vertex not in visited:
visited.add(vertex)
queue.extend(graph[vertex] - visited)
return visited
def bfs_paths(graph,start,goal):
queue = [(start,[start])]
while queue:
(vertex,path) = queue.pop(0)
for next in graph[vertex] - set(path):
if next == goal:
yield path + [next]
else:
queue.append((next,path+[next]))
print(bfs(graph,'A'))
print(list(bfs_paths(graph,'A','F')))
|
'''
Given an array of values and a target sum, check wether the given sum is possible
to be made from the subset of the given elements.
For example:
arr = [1,3,5]
tar = 4
ANSWER => True
tar = 2
ANSWER => False
'''
from numpy import array
def subsetsum(arr,val):
'''
arr : <int> array
val : <int> target value
RETURNS => <bool> if it is possible or not
'''
dp = [[None] * (val + 1) for _ in range(len(arr) + 1)]
for i in range(len(arr) + 1):
for j in range(val + 1):
if i == 0:
dp[i][j] = False
if j == 0:
dp[i][j] = True
for i in range(1,len(arr)+1):
for j in range(1,val+1):
if j < arr[i-1]:
dp[i][j] = dp[i-1][j]
else:
dp[i][j] = dp[i-1][j] or dp[i-1][j-arr[i-1]]
print("The dp array is: ")
print(array(dp))
return dp[len(arr)][val]
arr = [1,3,5]
print()
print("For target = 0, answer is =>",subsetsum(arr,0))
print()
print("For target = 2, answer is =>",subsetsum(arr,2))
print()
print("For target = 4, answer is =>",subsetsum(arr,4))
print()
|
'''
Given a string, find all the permutations of the string using recursion.
'''
def permutation(s):
out = []
if len(s) <=1 :
out = [s]
else:
for i,letter in enumerate(s):
for perm in permutation(s[:i]+s[i+1:]):
out += [letter+perm]
return out
print(permutation("1234"))
|
'''
Given an array of elements, count the number of subarrays with a given sum.
For example:
'''
def countSubarraySum(arr,k):
values = dict()
values[0] = 1
currsum = 0
count = 0
for i in arr:
currsum += i
if currsum - k in values:
count += values[currsum-k]
if currsum in values:
values[currsum] += 1
else:
values[currsum] = 1
return count
arr = [3,4,7,2,-3,1,4,2]
k = 7
print("The answer for value ",k," is => ",countSubarraySum(arr,k))
|
'''
Given an array of integer elements, form 2 subsets such
that the difference between those two array is minimum.
For example:
arr = [1,6,11,5]
subsets = [1,11],[5,6]
diff = 1 => minimum difference
'''
from numpy import array
'''
The main approach to this problem is that,
we have to minimize s1 - s2. So, we are given
s2 - s1 = k
s2 + s1 = total sum of the array
so if we check all the possible sums till the sum of
the array, and from the middle of that, check if any
subset sum is available, it would result in the min.
subset difference.
For example:
dp[-1] = [1,2,3,4,5,6,7,8,9,10]
[T,T,T,T,F,T,T,T,T,T]
if s1 = 5, definitely s2 = 5, because s1 + s2 = 10
but there is no subset with sum = 5, so we go to 4,
as s1 = 4, s2 = 6, min diff is 2. Any other number
will only give difference bigger than this number.
'''
def minimumSubsetSum(arr):
total = sum(arr)
allSums = subsetSum(arr,total)
print("The last row of the dp table is: ")
print(allSums)
mid = len(allSums)//2
if mid * 2 == total and allSums[mid]:
return 0
else:
for i in range(mid-1,-1,-1):
if allSums[i]:
return total - 2*i
def subsetSum(arr,val):
dp = [[None] * (val + 1) for _ in range(len(arr) + 1)]
for i in range(len(arr) + 1):
for j in range(val+1):
if i == 0:
dp[i][j] = False
if j == 0:
dp[i][j] = True
for i in range(1,len(arr) + 1):
for j in range(1,val + 1):
if j < arr[i-1]:
dp[i][j] = dp[i-1][j]
else:
dp[i][j] = dp[i-1][j-arr[i-1]] or dp[i-1][j]
return dp[-1]
print()
arr = [1,6,11,5]
print("The answer to array ",arr," is => ",minimumSubsetSum(arr))
print()
arr= [1,2,3,4,5,6,7,8,9,10]
print("The answer to array ",arr," is => ",minimumSubsetSum(arr))
print()
arr = [1,9,2,7,5,6,4,8,3]
print("The answer to array ",arr," is => ",minimumSubsetSum(arr))
print()
arr = [1,3,12,11,8,7,2,9,10,19]
print("The answer to array ",arr," is => ",minimumSubsetSum(arr))
print()
|
'''
Write a function to reverse a Linked List in place.
The function will take in the head of the list as
input and return the new head of the list.
'''
class Node:
def __init__(self,value):
self.value = value
self.nextnode = None
# Not Inplace
def reverse(head):
placeholder = head
temp = list()
while head.nextnode != None:
temp.append(head.value)
head = head.nextnode
temp.append(head.value)
temp = temp[::-1]
head = placeholder
for value in temp:
head.value = value
head = head.nextnode
return placeholder
# Inplace
def reverse2(head):
cur = head
pre, nxt = None, None
while cur:# watch out
nxt = cur.nextnode
cur.nextnode = pre
pre = cur
cur = nxt
return pre #watch out
pass
# Create a list of 4 nodes
a = Node(1)
b = Node(2)
c = Node(3)
d = Node(4)
# Set up order a,b,c,d with values 1,2,3,4
a.nextnode = b
b.nextnode = c
c.nextnode = d
print(a.value)
print(a.nextnode.value)
print(b.nextnode.value)
print(c.nextnode.value)
reverse(a)
print(a.value)
print(a.nextnode.value)
print(b.nextnode.value)
print(c.nextnode.value)
print("*"*10)
# Create a list of 4 nodes
a = Node(1)
b = Node(2)
c = Node(3)
d = Node(4)
# Set up order a,b,c,d with values 1,2,3,4
a.nextnode = b
b.nextnode = c
c.nextnode = d
print(a.value)
print(a.nextnode.value)
print(b.nextnode.value)
print(c.nextnode.value)
reverse2(a)
print(d.value)
print(d.nextnode.value)
print(c.nextnode.value)
print(b.nextnode.value)
|
# Name Jesse Coyle
# Date 1/18/2020
# File tile.py
# Desc definitions for tiles
class Terrain:
def __init__(self, id, name, ascii, energy):
# Note(Jesse): member integer that identifies this specific Obstacle
# 0 _cannot be valid_
self.id = id # Research(Jesse): We might not need the id
self.name = name # Note(Jesse): In case we want to tell the user
self.ascii = ascii # Note(Jesse): The singular ascii character that will be represented on the map
self.energy = energy # Note(Jesse): Energy spent on navigating tile
class Obstacle:
def __init__(self, id, name, ascii, energy):
# Note(Jesse): member integer that identifies this specific Obstacle
# 0 _can be valid_ in the event there is no obstacle on the tile
self.id = id # Research(Jesse): We might not need the id
self.name = name # Note(Jesse): For use in the store... in case we want to mention what tool goes to what obstacle?
self.ascii = ascii # Note(Jesse): The singular ascii character that will be represented on the map
self.energy = energy # Note(Jesse): Energy spent on removing obstacle
class Tiles:
terrain = []
obstacles = []
def add_terrain(self, name, ascii, energy):
id = len(self.terrain) + 1
terrain = Terrain(id, name, ascii, energy)
self.terrain.append(terrain)
def add_obstacle(self, name, ascii, energy):
id = len(self.obstacles) + 1
obstacle = Obstacle(id, name, ascii, energy)
self.obstacles.append(obstacle)
|
# a tuple that stores the months of the year, from that tuple
# create another tuple with just the summer months (May, June, July),
# print out the summer months one at a time.
months = ("January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December")
summer = months [4:7]
for month in summer:
print (month)
|
# avg2.py
# A simple program to average two exam scores
# Illustrates use of multiple input
print("This program computes the average of two exam scores")
score1,score2=input("Enter two scores seperated by a comma :")
average= (score1+score2)/2
print("The average of the scores is :",average)
|
def printinfo(arg1,*vartuple):
print "Output is:"
print arg1
for var in vartuple:
print var
return
printinfo(10)
printinfo(70,60,50)
|
import time
ticks=time.time()
print "Number of ticks since 12:00am jan1,1970:",ticks
localtime=time.localtime(time.time())
print "Local current time:",localtime
localtime=time.asctime(time.localtime(time.time()))
print "Local current time:",localtime
import calendar
cal=calendar.month(2018,7)
print "Here is the calendar"
print cal
|
"""
Introduction to storing functions in variables
"""
import unittest
def surprise():
return 'SURPRISE!'
# TODO 1) Change what is assigned into the func_1 variable so test_1 will pass
func_1 = None
# TODO 2) Change the return statement below so that test_2 will pass
def pizza_surprise():
return None
# TODO 3) Implement the birthday_surprise function so that test_3 will pass
def birthday_surprise(years_old):
return None
# TODO 4) Implement the surprise_guests function so that test_3 will pass
# *HINT* You will have to add input parameters to the function
def surprise_guests():
return None
# ================== DO NOT MODIFY THE CODE BELOW ============================
class WriteClassesTests(unittest.TestCase):
def test_1(self):
self.assertEqual('SURPRISE!', func_1())
def test_2(self):
func_2 = pizza_surprise
self.assertEqual("SURPRISE, here's a pizza!", func_2())
def test_3(self):
func_3 = birthday_surprise
self.assertEqual('SURPRISE, Happy 1st birthday!!!', func_3(1))
self.assertEqual('SURPRISE, Happy 2nd birthday!!!', func_3(2))
self.assertEqual('SURPRISE, Happy 3rd birthday!!!', func_3(3))
self.assertEqual('SURPRISE, Happy 38th birthday!!!', func_3(38))
def test_4(self):
guests = ['Jerry', 'Summer', 'Yusef']
expected_message = guests[0] + ' says ' + 'SURPRISE!\n'
expected_message += guests[1] + ' says ' + 'SURPRISE!\n'
expected_message += guests[2] + ' says ' + 'SURPRISE!\n'
self.assertEqual(expected_message, surprise_guests(surprise, guests))
expected_message = guests[0] + ' says ' + "SURPRISE, here's a pizza!\n"
expected_message += guests[1] + ' says ' + "SURPRISE, here's a pizza!\n"
expected_message += guests[2] + ' says ' + "SURPRISE, here's a pizza!\n"
self.assertEqual(expected_message, surprise_guests(pizza_surprise, guests))
if __name__ == '__main__':
unittest.main()
|
a=int(input('Enter'))
b=int(input('Enter'))
print('Mul of two values:-',a*b)
|
def ctof(celcius):
if celcius < -273.15:
return "Too low temperature"
else:
return celcius*9/5 + 32
temperatures=[10,-20,-289,100]
file = open("ctof.txt", "w")
for temp in temperatures:
if type((ctof(temp))) == float:
file.write(str(ctof(temp)) + "\n")
file.close()
|
# Wykorzystując kod przygotowany do tego zadania, zamień klasy na namedtuple.
# class Ojciec:
# def __init__(self, imie, nazwisko, data_ur):
# self.imie = imie
# self.nazwisko = nazwisko
# self.data_ur = data_ur
from collections import namedtuple
Ojciec = namedtuple('Ojciec', ['imie', 'nazwisko', 'data_ur'])
o = Ojciec(imie="Jacek", nazwisko='Kowalski', data_ur='2018-23-01')
print(o)
print(o.imie)
|
# Napisz prosty konwerter walut, który na wejściu przyjmie stringa składającego się z:
# kwoty, waluty wejściowej, słówka kluczowego "to" i kwoty wyjściowej.
# Użyj następujących kursów: 1 PLN to 1000 USD, 1 PLN to 4505 EURO, 1 PLN to 100 JPY
# Załóż, że konwersje są wykonywane tylko z lub do PLNów.
# Dla zaawansowanych: przeliczaj wszystkie waluty między sobą (PLN, USD, EURO, JPY)
# Przykład:
# input: "2 PLN to USD" output: "2000 USD"
# input "15 USD to PLN" output: "0.015 PLN"
kursUSD = 1000
kursEURO = 4505
kursJPY = 100
def konwerter(my_string):
cut_string = my_string.split()
if cut_string[1] == "PLN":
waluta = cut_string[3]
if waluta == "USD":
pln = float(cut_string[0]) * kursUSD
elif waluta == "EURO":
pln = float(cut_string[0]) * kursEURO
elif waluta == "JPY":
pln = float(cut_string[0]) * kursJPY
else:
return "Błędne dane wejściowe"
return "{} {}".format(pln, waluta)
else:
waluta = cut_string[1]
if waluta == "USD":
pln = float(cut_string[0]) / kursUSD
elif waluta == "EURO":
pln = float(cut_string[0]) / kursEURO
elif waluta == "JPY":
pln = float(cut_string[0]) / kursJPY
else:
return "Błędne dane wejściowe"
return "{} PLN".format(pln)
print(konwerter("2 PLN to USD"))
print(konwerter("15 USD to PLN"))
print(konwerter("15 JPY to PLN"))
|
"""Not Missing Docstring"""
import math
import random
import this
def nic_nie_robie():
"""
funkcja kompletnie do niczego nie potrzebna
:return:
"""
our_pi = math.pi
random.randint(0, int(our_pi))
return this
def podzielna(liczba, podzielna_przez):
"""
:param liczba:
:param podzielna_przez:
:return: True/False
"""
return liczba % podzielna_przez == 0
def ugly(liczba):
"""
funkcja brzydkiej liczby ;)
:param liczba:
:return: True/False
"""
if liczba == 1:
return True
for i in [2, 3, 5]:
if podzielna(liczba, i):
return True
return False
print(ugly(11))
print(ugly(12))
def time(czas, jednostka):
"""
:param czas:
:param jednostka:
:return: coś tam z czasem
"""
hour, minute, second = czas.split(':')
hour = int(hour)
minute = int(minute)
second = int(second)
if jednostka == 'second':
return hour * 3600 + minute * 60 + second
elif jednostka == 'minute':
return hour * 60 + minute + round(second / 60, 2)
return hour + round(minute / 60, 2) + round(second / 3600, 2)
print(time('01:15:59', 's'))
print(time('01:15:59', 'm'))
print(time('01:15:59', 'h'))
def flatten(arr):
"""
Docstring for function 'flatten'
:param arr:
:return:
"""
result = []
for element in arr:
if isinstance(element, list):
flatten(element)
else:
result.append(element)
return result
def flatten_nr(arr):
"""
Docstring for function 'flatten_nr'
:param arr:
:return:
"""
rr2 = []
while True:
element = arr.pop()
if not isinstance(element, list):
rr2.append(element)
else:
arr = element
if not arr:
break
return rr2[::-1]
print(flatten([[[[[[[[[['a'], 'b']]], 'c']]], 'd']], 'e']))
print(flatten_nr([[[[[[[[[['a'], 'b']]], 'c']]], 'd']], 'e']))
def weird_power(num):
"""
Docstring for weird_power
:param num:
:return:
"""
return num ** 2, num ** 3
def calculate(afun, data1):
"""
Docstring for calculate
:param afun:
:param data1:
:return:
"""
return afun(weird_power(data1))
CONSTANT_A = [3]
def sum_a(whatever):
"""
Docstring for sum_a
:param whatever:
:return: number
"""
return sum(whatever)
MY_B = sum_a(CONSTANT_A)
MY_C = calculate(MY_B, CONSTANT_A)
print(MY_C)
def sorted_a(whatever):
"""
Docstring for sorted_a
:param whatever:
:return: sorted whatever
"""
return sorted(whatever)
MY_D = sorted_a(CONSTANT_A)
MY_F = calculate(MY_D, CONSTANT_A)
print(MY_F)
def power_2(number):
"""
Docstring for power_2
:param number:
:return:
"""
return (number + 0.5 * number) ** 2
print(power_2(3))
DATA = [(9, 0), (1, 2), (3, 4)]
SORTED_DATA = sorted(DATA, key=lambda a: a[0], reverse=False)
MAX_DATA = max(DATA)
MIN_DATA = min(DATA)
FILTERED_DATA = list(filter(lambda a: sum(a) > 5, DATA))
INSIDE = {'a': {'a': {'a': {'a': {'a': {'a': {'a': {'a': {'a': {'a': 1}}}}}}}}}}
INSIDE2 = {'a': {'a': {'a': {'a': {'a': {'a': INSIDE}}}}}}
print({'a': {'a': {'a': {'a': {'a': {'a': {'a': INSIDE2}}}}}}})
|
def palindrome(string): # Defined Function to check if string is palindrome or not
# Here the string and its reversed string is compared if equal then return True otherwise False
# Here Slicing concept is used, The entire string is reversed by putting [ : : -1]
if string == string[::-1]:
return True
else:
return False
s = "aabbaa"
print(palindrome(s)) # Function is called by providing input string
s = "abdcb"
print(palindrome(s)) # Function is called by providing input string
|
#Implement the class SubrectangleQueries which receives a rows x cols
#rectangle as a matrix of integers in the constructor and supports two methods:
#1. updateSubrectangle(int row1, int col1, int row2, int col2, int newValue)
#Updates all values with newValue in the subrectangle whose upper left
#coordinate is (row1,col1) and bottom right coordinate is (row2,col2).
#2. getValue(int row, int col)
#Returns the current value of the coordinate (row,col) from the rectangle.
class SubrectangleQueries:
def __init__(self, rectangle: List[List[int]]):
self.rectangle = rectangle
def updateSubrectangle(self, row1: int, col1: int, row2: int, col2: int, newValue: int) -> None:
for i in range(row1, row2+1):
for j in range(col1, col2+1):
self.rectangle[i][j]=newValue
return self.rectangle
def getValue(self, row: int, col: int) -> int:
return self.rectangle[row][col]
|
#!/home/francisco/Projects/Pycharm/py-binary-trees-draw/venv/bin/python
# -*- coding: utf-8 -*-
from node import Node
class AVLTree:
def __init__(self):
self.root = None
self.leaf = Node(None)
self.leaf.height = -1
self.nodes_dict_aux = {}
self.nodes_dict = {}
def insert(self, key):
"""
Insert key values in tree
:param key: numeric.
:return: self.nodes_height_dict a dict where keys are tuple (parent, height) and values are the children.
"""
node = Node(key)
node.left = self.leaf
node.right = self.leaf
if not self.root:
self.root = node
else:
current = self.root
parent = current
while current:
if current == self.leaf:
break
node.height += 1
parent = current
if node.key < current.key:
current = current.left
elif node.key > current.key:
current = current.right
elif node.key == current.key:
return False
node.parent = parent
if node.key < parent.key:
parent.left = node
else:
parent.right = node
self._calculate_height(node)
self._fix_violation(node)
self._recovery_nodes_dict()
return self.nodes_dict
return None
def walk_in_order(self, node=None):
"""
Walking tree in pre-order.
:param node: node object.
"""
if not node:
node = self.root
if node != self.leaf:
self.walk_in_order(node.left)
fb = node.left.height - node.right.height
if node.parent:
print('{0}\t{1}\t{2}\t{3}\t{4}\t{5}'.format(node.key, node.parent.key, node.left.key, node.right.key,
node.height, fb))
else:
print('{0}\t{1}\t{2}\t{3}\t{4}\t{5}'.format(node.key, None, node.left.key, node.right.key,
node.height, fb))
self.walk_in_order(node.right)
def walk_pos_order(self, node=None):
"""
Walking tree in pos-order.
:param node: node object.
"""
if not node:
node = self.root
if node != self.leaf:
self.walk_pos_order(node.right)
if node.parent:
print('{0}\t{1}\t{2}\t{3}\t{4}'.format(node.key, node.parent.key, node.left.key, node.right.key,
node.height, ))
else:
print('{0}\t{1}\t{2}\t{3}\t{4}'.format(node.key, None, node.left.key, node.right.key, node.height))
self.walk_pos_order(node.left)
def search(self, value):
"""
Search the node object that key is equal for given value.
:param value: numeric.
:return: node object.
"""
current = self.root
while current and value != current.key:
if not current.key:
return False
if current.key > value:
current = current.left
else:
current = current.right
return current
def minimum(self, node=None):
"""
Search the minimum key in subtree that start from given node.
:param node: node object.
:return: node object.
"""
if not node:
node = self.root
while node.left != self.leaf:
node = node.left
return node
def maximum(self, node=None):
"""
Search the maximum key in subtree that start from given node.
:param node: node object.
:return: node object.
"""
if not node:
node = self.root
while node.right != self.leaf:
node = node.right
return node
def successor(self, value):
"""
Find the largest value in the tree directly above the given value.
:param value: numeric.
:return: object node.
"""
current = self.search(value)
if not current:
return False
elif current.right != self.leaf:
node = self.minimum(current.right)
return node
node = current.parent
while node and current == node.right:
current = node
node = current.parent
if not node:
return self.maximum()
return node
def predecessor(self, value):
"""
It finds in the tree the lowest value directly below the given number.
:param value: numeric.
:return: node object.
"""
current = self.search(value)
if not current:
return False
elif current.left != self.leaf:
node = self.maximum(current.left)
return node
node = current.parent
while node and current == node.left:
current = node
node = current.parent
if not node:
return self.minimum()
return node
def remove(self, value):
"""
Remove node where key is equal of given value.
:param value: numeric
"""
node = self.search(value)
if node == self.root:
return self._remove_root()
elif node.left == self.leaf and node.right == self.leaf:
return self._remove_if_leaf(node)
elif (node.left == self.leaf) ^ (node.right == self.leaf):
return self._remove_if_one_child(node)
else:
return self._remove_if_two_children(node)
def _remove_if_leaf(self, node):
remove_key = node.key
parent = node.parent
if parent.left == node:
parent.left = self.leaf
else:
parent.right = self.leaf
self._calculate_height(parent)
self._fix_violation(parent)
self._recovery_nodes_dict()
del node
return remove_key, None
def _remove_if_one_child(self, node):
remove_key = node.key
if node.parent.left == node:
if node.right == self.leaf:
node.parent.left = node.left
else:
node.parent.left = node.right
else:
if node.right == self.leaf:
node.parent.right = node.left
else:
node.parent.right = node.right
node.left.parent = node.parent
node.right.parent = node.parent
self._calculate_height(node.parent)
self._fix_violation(node.parent)
self._recovery_nodes_dict()
del node
return remove_key, None
def _remove_if_two_children(self, node):
remove_key = node.key
successor = self.successor(node.key)
if successor == node.right:
if node == node.parent.left:
node.parent.left = successor
else:
node.parent.right = successor
successor.parent = node.parent
successor.left = node.left
successor.left.parent = successor
else:
if node == node.parent.left:
node.parent.left = successor
else:
node.parent.right = successor
successor.parent.left = successor.right
successor.left = node.left
successor.right = node.right
node.right.parent = successor
node.left.parent = successor
successor.parent = node.parent
self._calculate_height(node.parent)
self._fix_violation(node.parent)
self._recovery_nodes_dict()
del node
return remove_key, successor.key
def _remove_root(self):
remove_key = self.root.key
successor = None
if self.root.left == self.leaf and self.root.right == self.leaf:
self.root = None
elif (self.root.left == self.leaf) ^ (self.root.right == self.leaf):
if self.root.left != self.leaf:
self.root = self.root.left
else:
self.root = self.root.right
self.root.parent = None
else:
successor = self.successor(self.root.key)
if successor == self.root.right:
successor.parent = None
successor.left = self.root.left
self.root.left.parent = successor
self.root = successor
else:
if successor.right:
successor.right.parent = successor.parent
successor.parent.left = successor.right
successor.left = self.root.left
successor.right = self.root.right
self.root.left.parent = successor
self.root.right.parent = successor
successor.parent = None
self.root = successor
self._calculate_height(self.root)
self._fix_violation(self.root)
self._recovery_nodes_dict()
if successor:
return remove_key, successor.key
else:
return remove_key, None
def _recovery_nodes_dict(self):
# Because fixing the violations mess up the heights of each node we have to first create a dict where the
# keys are the parents and the values are a list of tuples with the childs and their heights.
self.nodes_dict_aux = {} # a dict where keys are parent and values is tuples with child and ir height.
self._make_nodes_dict_aux()
self.nodes_dict = {} # a dict where keys are tuple with parent and chid height and values is tuples
# with child.
self._make_nodes_dict()
def _make_nodes_dict_aux(self, node=None, flag=0):
"""
Recursion function to create dict where the keys are the parents and the values are a list of tuples with the
childs and their heights.
:param node: node object.
:param flag: integer who indicate if node is left or right child.
"""
if not node:
node = self.root
if node != self.root and node != self.leaf:
height = self._calculate_real_height(node)
if not (node.parent.key in self.nodes_dict_aux):
self.nodes_dict_aux[node.parent.key] = [None, None]
self.nodes_dict_aux[node.parent.key][flag] = (node.key, height)
if node != self.leaf:
self._make_nodes_dict_aux(node.left, 0)
self._make_nodes_dict_aux(node.right, 1)
def _make_nodes_dict(self):
for key in self.nodes_dict_aux:
nodes = self.nodes_dict_aux[key]
if nodes[0] and nodes[1]:
_, height = min(nodes, key=lambda x: x[:][1])
# print(nodes[0][0], nodes[1][0], height)
self.nodes_dict[key, height] = [nodes[0][0], nodes[1][0]]
else:
if nodes[0]:
height = nodes[0][1]
self.nodes_dict[key, height] = [nodes[0][0], None]
else:
height = nodes[1][1]
self.nodes_dict[key, height] = [None, nodes[1][0]]
def _calculate_real_height(self, node):
"""
Calculate real height in tree of given node.
:param node: node object.
:return: numeric.
"""
height = 0
current = node
while current != self.root:
height += 1
current = current.parent
return height
def _calculate_height(self, node):
"""
Calculate left and right height of node.
:param node: node object.
"""
current = node
while current:
current.height = max(current.left.height, current.right.height) + 1
current = current.parent
def _fix_violation(self, node):
"""
Verify if is necessary rotate the node.
:param node: node object.
"""
flag = False
previous = node
current = node.parent
while current:
fb1 = current.left.height - current.right.height
fb2 = previous.left.height - previous.right.height
if fb1 >= 2 and fb2 >= 0:
self._rotate_right(current)
flag = True
break
if fb1 <= -2 and fb2 <= 0:
self._rotate_left(current)
flag = True
break
if fb1 >= +2 and fb2 <= 0:
self._rotate_left(previous)
self._rotate_right(current)
flag = True
break
if fb1 <= -2 and fb2 >= 0:
self._rotate_right(previous)
self._rotate_left(current)
flag = True
break
previous = current
current = current.parent
return flag
def _rotate_left(self, x):
"""
Rotate node to left.
:param x: node object.
"""
y = x.right # define y
x.right = y.left # x right now igual y left
y.left.parent = x # y left now is x left
y.parent = x.parent # y parent is x parent
if x == self.root: # if x is root now y is root
self.root = y
elif x == x.parent.left:
x.parent.left = y # if x is the left child, then y is the left child
else:
x.parent.right = y # if x is the right child, then y is the right child
y.left = x # y left now is x
x.parent = y # x parent now is y
x.height -= 2
self._calculate_height(x)
def _rotate_right(self, x):
"""
Rotate node to right.
:param x: node object.
"""
y = x.left
x.left = y.right
y.right.parent = x
y.parent = x.parent
if x == self.root: # if x is root now y is root
self.root = y
elif x == x.parent.left:
x.parent.left = y # if x is the left child, then y is the left child
else:
x.parent.right = y # if x is the right child, then y is the right child
y.right = x
x.parent = y
x.height -= 2
self._calculate_height(x)
if __name__ == '__main__':
bt = AVLTree()
print('node\tparent\tleft\tright\theight\tfb')
print('***********************************************')
# bt.insert(11)
# bt.insert(2)
# bt.insert(14)
# bt.insert(1)
# bt.insert(7)
# bt.insert(15)
# bt.insert(5)
# bt.insert(8)
# bt.insert(4)
# bt.walk_in_order()
# print('***********************************************')
# print(bt.nodes_dict)
# print('***********************************************')
bt.insert(44)
bt.insert(17)
bt.insert(78)
bt.insert(32)
bt.insert(50)
bt.insert(88)
bt.insert(48)
bt.insert(62)
bt.insert(84)
bt.insert(92)
bt.insert(80)
bt.insert(82)
bt.walk_in_order()
print('***********************************************')
print(bt.nodes_dict)
print('***********************************************')
bt.remove(32)
print('remove 32')
print('node\tparent\tleft\tright\theight\tfb')
print('***********************************************')
bt.walk_in_order()
print('***********************************************')
print(bt.nodes_dict)
print('***********************************************')
bt.remove(84)
print('remove 84')
print('node\tparent\tleft\tright\theight\tfb')
print('***********************************************')
bt.walk_in_order()
print('***********************************************')
print(bt.nodes_dict)
print('***********************************************')
bt.remove(82)
print('remove 82')
print('node\tparent\tleft\tright\theight\tfb')
print('***********************************************')
bt.walk_in_order()
print('***********************************************')
print(bt.nodes_dict)
print('***********************************************')
# bt.insert(4)
# bt.insert(2)
# bt.insert(6)
# bt.insert(1)
# bt.insert(3)
# bt.insert(5)
# bt.insert(15)
# bt.insert(7)
# bt.insert(16)
# bt.insert(14)
# bt.bt_draw()
# bt.insert(10)
# bt.insert(5)
# bt.insert(16)
# bt.insert(2)
# bt.insert(8)
# bt.insert(1)
# bt.bt_draw()
|
# Implement a class to hold room information. This should have name and
# description attributes.
class Room:
def __init__(self, name, description):
self.name = name
self.description = description
self.n_to = None
self.s_to = None
self.e_to = None
self.w_to = None
self.item = []
def __repr__(self):
returnString = f"---------------\n\n{self.name}\n\n {self.description}\n\n---------------"
returnString += f"\n\n[{self.get_exit()}]\n\n"
return returnString
def get_direction(self, direction):
"""This function points the player to the inputted direction """
if direction in ["n", "N"]:
return self.n_to
elif direction in ["s", "S"]:
return self.s_to
elif direction in ["w", "W"]:
return self.w_to
elif direction in ["e", "E"]:
return self.e_to
else:
return None
def get_exit(self):
exits = ["Only Available Directions are --->"]
if self.n_to is not None:
exits.append("n")
if self.s_to is not None:
exits.append("s")
if self.e_to is not None:
exits.append("e")
if self.w_to is not None:
exits.append("w")
return ", ".join(exits)
|
name="tarena"
pwd="123456"
i=3
while i>0:
n = input("请输入用户名")
p = input("请输入密码")
if name==n and pwd==p:
break
i-=1
print("输入错误,请重新输入")
if i==0:
print("3次机会已经用完")
print("欢迎您回来")
|
str1=input("请输入几个字,判断是不是回文:")
a=str1[::1]
b=str1[::-1]
if a==b:
print(str1,"是回文")
else:
print("不是回文")
|
import random
random_number = random.randint(0, 100)
print('Welcome to the Guessing Game Challenge! \n\n'
'The program will randomly pick an integer number between 1 and 100. \n'
'The user must then guess what this number is in the least amount of \n'
'guesses as possible. After each guess, the program will indicate how \n'
'close or far the user\'s guess is from the actual number. \n')
# list to keep all of the guesses made
user_guesses = [0]
while True:
guess = input('Enter a number between 1 and 100: ')
# check that input is an integer
try:
is_guess_int = int(guess)
except ValueError:
print('Invalid input.')
continue
# check that input is between 1 and 100
if int(guess) < 1 or int(guess) > 100:
print("The number entered is out of bounds.")
continue
# if user guesses the correct number
if int(guess) == random_number:
print('You guessed it! The correct number was ' + str(random_number) + '!\n'
'You took ' + str(len(user_guesses)) + ' guesses total.')
break
# first guess of game
if user_guesses[0] == 0:
if abs(int(guess) - random_number) <= 10:
# guess is within 10 numbers from the actual number
print('Your first guess is close to the actual number!')
user_guesses[0] = int(guess)
continue
elif abs(int(guess) - random_number) > 10:
# guess is further than 10 numbers away from actual number
print('Your first guess is far from the actual number!')
user_guesses[0] = int(guess)
continue
else:
# every guesses after first
user_guesses.append(int(guess))
if abs(user_guesses[-2] - random_number) >= abs(int(guess) - random_number):
# current guess is closer than previous guess
print('Your next guess is closer!')
continue
elif abs(user_guesses[-2] - random_number) < abs(int(guess) - random_number):
# current guess is further than previous guess
print('Your next guess is further!')
continue
pass
|
import nltk, pickle
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
import string
'''
A class to allow for a Majority Votes Classifier System
The result with the most votes is returned as the classifier's answer
'''
class MajorityVotesClassifier(nltk.classify.api.ClassifierI):
def __init__(self, classifiers):
super(MajorityVotesClassifier, self).__init__()
self.__classifiers = classifiers
def labels(self):
return list()
'''
Classifies the given data based on the results of all three classifiers
'''
def classify(self, data):
votes = []
for classifier in self.__classifiers:
vote = classifier.classify(data)
votes.append(vote)
# The predicted value is the one that has more votes
return max(set(votes), key=votes.count)
'''
A method to allow for accessing of a saved model.
Unpickles the model and makes it available as an object
'''
def ReadModel(modelFilename):
return pickle.load(open(modelFilename, 'rb'))
'''
A method to extract features from the text
'''
def get_features(text):
words = []
# Tokenize the question as a sentence and then tokenize the sentence into words
sentences = nltk.sent_tokenize(text.translate(None, string.punctuation))
for sentence in sentences:
words = words + nltk.word_tokenize(sentence)
# Normalize/cast all words to lowercase
words = [i.lower() for i in words]
# Obtain & format bigram combinations from the sentence
bigrams = nltk.bigrams(words)
bigrams = ["%s %s" % (i[0], i[1]) for i in bigrams]
# Obtain & format trigram combinations from the sentence
trigrams = nltk.trigrams(words)
trigrams = ["%s %s %s" % (i[0], i[1], i[2]) for i in trigrams]
# Calculate the average word length in the sentence
wlSum = 0
for word in words:
wlSum = wlSum + len(word)
averageWordLength = []
if len(words) != 0:
averageWordLength.append(wlSum/len(words))
else:
averageWordLength.append(0)
# combine the length, bigrams, & trigrams
features = bigrams + trigrams + averageWordLength
# Return those features as a dictionary
features = dict([(i, True) for i in features])
return features
'''
A method to plot a confusion Matrix for a classifier
'''
def PlotConfusionMatrix( \
confusionMatrix,
classifier,
title='Confusion matrix',
cmap=plt.cm.Blues
):
plt.imshow( \
confusionMatrix,
interpolation='nearest',
cmap=cmap
)
# Feature creation/addition for the Confusion Matrix
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classifier.labels()))
plt.xticks(tick_marks, classifier.labels(), rotation=45)
plt.yticks(tick_marks, classifier.labels())
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.show()
'''
A method to evaluate classifier's accuracy on a test set and create a confusion matrix
'''
def EvaluateClassifier(classifier, testSet, testLabeledData, possibleClassifications):
print("Classifier's accuracy values:")
onTestSetAccuracy = nltk.classify.accuracy(classifier, testSet)
print("\tOn test set = {}".format(onTestSetAccuracy))
# List to store the cases where the algorithm made a mistake
errorCases = []
enCount = 0
frCount = 0
geCount = 0
itCount = 0
spCount = 0
enRight = 0
geRight = 0
frRight = 0
itRight = 0
spRight = 0
# plotting Confusion Matrix
y_test, y_pred = [], []
for (tag, transcriptions) in testLabeledData.items():
# Find errors
for transcription in transcriptions:
guess = classifier.classify(get_features(transcription))
# Increment our overall count for each language (and our correct count if we correctly classified it)
if tag == "en-GB":
enCount = enCount + 1
if guess == tag:
enRight = enRight + 1
elif tag == "fr-FR":
frCount = frCount + 1
if guess == tag:
frRight = frRight + 1
elif tag == "de-DE":
geCount = geCount + 1
if guess == tag:
geRight = geRight + 1
elif tag == "it-IT":
itCount = itCount + 1
if guess == tag:
itRight = itRight + 1
elif tag == "es-DO":
spCount = spCount + 1
if guess == tag:
spRight = spRight + 1
if guess is None or tag is None: continue
y_pred.append(possibleClassifications.index(guess))
y_test.append(possibleClassifications.index(tag))
if guess != tag:
caseDescription = "question {0} prediction:{1}, real: {2}".format(transcription, guess, tag)
errorCases.append(caseDescription)
print("\n\t-----TAG ACCURACY-----")
print("\t\tEnglish = " + str(enRight / enCount))
print("\t\tFrench = " + str(frRight / frCount))
print("\t\tGerman = " + str(geRight / geCount))
print("\t\tItalian = " + str(itRight / itCount))
print("\t\tSpanish = " + str(spRight / spCount))
# Create the confusion matrix
cm = confusion_matrix(y_test, y_pred)
np.set_printoptions(precision=2)
print('\n\nConfusion matrix, without normalization for the Classifier\n')
print(cm)
plt.figure()
PlotConfusionMatrix(cm, classifier)
return errorCases
|
from datetime import date
class Year:
def __init__(self, name, start_calendar_year):
self.name = name
self.start_date = date(month=6, day=1, year=start_calendar_year)
self.end_date = date(month=5, day=31, year=start_calendar_year + 1)
def __repr__(self):
return '<Year {}>'.format(self.name)
def __contains__(self, date):
return date >= self.start_date and date <= self.end_date
class Years:
_all_years = [Year(name, start_year)
for name, start_year
in [('1G', 2013),
('2G', 2014),
('3G', 2015),
('4G', 2016),
('5G', 2017),
('6G', 2018),
('3B', 2019),
('4B', 2020), ]]
@staticmethod
def year_names():
return [y.name for y in Years._all_years][::-1]
@staticmethod
def get(date):
for year in Years._all_years:
if date in year:
return year.name
else:
return 'Unnamed Year ({})'.format(date.year)
|
#!/usr/bin/python3
# Implement PKCS#7 padding
# A block cipher transforms a fixed-sized block (usually 8 or 16 bytes) of plaintext into ciphertext.
# But we almost never want to transform a single block; we encrypt irregularly-sized messages.
#
# One way we account for irregularly-sized messages is by padding, creating a plaintext that is an
# even multiple of the blocksize. The most popular padding scheme is called PKCS#7.
#
# So: pad any block to a specific block length, by appending the number of bytes of padding to the end
# of the block. For instance,
#
# "YELLOW SUBMARINE"
# ... padded to 20 bytes would be:
#
# "YELLOW SUBMARINE\x04\x04\x04\x04"
from Crypto.Util.Padding import pad
if __name__ == "__main__":
input = b'YELLOW SUBMARINE'
print(pad(input, 20, 'pkcs7'))
|
# I found this approach simpler and easier to understand for people dreading the DP approach. So take a look.
# Approach: From centre expand outward till you find longest substring for each of the characters in the string.
# Traverse the whole string once and for each character, consider it as the centre of palindrome string and expand the window outward.
# Continue expanding outward till the substring is palindrome.
# Update the max length of palindrome strings found till now and the result as well.
# P.S: In order to handle even length substrings, we need to consider 2 characters at once to be the centre and then expand outward.
class Solution:
def longestPalindrome(self, s: str) -> str:
# #Brute force
# max_len = 0
# res = ''
# for i in range(len(s)):
# for j in range(i + 1, len(s)):
# curr = s[i:j+1]
# if curr == curr[::-1]:
# if len(curr)>max_len:
# res = curr
# max_len = len(curr)
# if res=='':
# return s[0]
# return res
#Expand from center (outward)
res = '' #
max_len = 0
for i in range(len(s)): #Traverse the whole string O(n)
#odd length substrings
l, r = i, i #Fix the left and right pointers to current index
while l >= 0 and r < len(s) and s[l] == s[r]: #Till the substring is palindrome, expand outward
curr_len = r - l + 1
if curr_len > max_len: #If length of current palindrome string is bigger than past strings, update the max length and result
res = s[l:r + 1]
max_len = curr_len
l -= 1 #Expand outward
r += 1
#Repeat the same for even length substrings!!
#even length substrings
l, r = i, i+1
while l >= 0 and r < len(s) and s[l] == s[r]:
curr_len = r - l + 1
if curr_len > max_len:
res = s[l:r + 1]
max_len = curr_len
l -= 1
r += 1
return res
|
#!/usr/bin/env python
#-*- coding: utf-8 -*-
__author__ = 'znlccy [email protected]'
class ShowDict(object):
'''该类用于展示字典的使用方法'''
def __init__(self):
self.spiderMan = self.createDict() #创建字典
self.insertDict(self.spiderMan) #插入元素
self.modifyDict(self.spiderMan) #修改元素
self.operationDict(self.spiderMan) #字典操作
self.deleteDict(self.spiderMan) #删除元素
def createDict(self):
print(u"创建字典: ")
print(u"执行命令 spiderMan = { 'name':'Peter', 'sex':'male', 'nation':'USA', 'college':'MIT'}")
spiderMan = { 'name':'Peter', 'sex':'male', 'nation':'USA', 'college':'MIT'}
self.showDict(spiderMan)
return spiderMan
def showDict(self, spiderMan):
print(u'显示字典')
print(u'spiderMan = ')
print(spiderMan)
print('\n')
def insertDict(self, spiderMan):
print(u"字典中添加键age,值为31")
print(u"执行命令spiderMan['age'] = 31")
spiderMan['age'] = 31
self.showDict(spiderMan)
def modifyDict(self, spiderMan):
print(u"从字典中修改键'college'值为'Empire State University'")
print(u"执行命令 spiderMan['college'] = 'Empire State University'")
spiderMan['college'] = 'Empire State University'
self.showDict(spiderMan)
def operationDict(self, spiderMan):
print(u"字典的其他操作方法")
print(u"###################################")
print(u"显示字典的所有键,keyList = spiderMan.keys()")
keyList = spiderMan.keys()
print(u"keyList = ")
print(keyList)
print('\n')
print(u"显示字典所有键的值, valueList = spiderMan.values()")
valueList = spiderMan.values()
print(u"valueList = ")
print(valueList)
print('\n')
print(u"显示字典所有的键和值的元组, itemList = spiderMan.items()")
itemList = spiderMan.items()
print(u"itemList = ")
print(itemList)
print('\n')
print(u"取字典中键为college的值,college = spiderMan.get('college')")
college = spiderMan.get('college')
print(u"college = %s" %college)
print('\n')
def deleteDict(self, spiderMan):
print(u"删除字典中键为Nation的值")
print(u"执行命令 del(spiderMan['Nation'])")
del(self.spiderMan['nation'])
self.showDict(spiderMan)
print(u"清空字典中所有的值")
print(u"执行命令 spiderMan.clear()")
self.spiderMan.clear()
self.showDict(spiderMan)
print(u"删除字典")
print(u"执行命令 del(spiderMan)")
del(spiderMan)
print(u"显示spiderMan")
try:
self.showDict(spiderMan)
except NameError:
print(u"spiderMan未被定义")
if __name__ == '__main__':
sd = ShowDict()
|
import time
from Queue import PriorityQueue
import itertools
class Solver:
def __init__(self, problem, algorithm):
self.num_visited = 0
self.algorithm = algorithm
self.problem = problem
self.max_mem = -1
def solve(self):
result = None
start = time.time()
print 'Algoritmo:', self.algorithm
if self.algorithm == 'BFS':
result = self.BFS()
elif self.algorithm == 'IDFS':
result = self.IDFS()
elif self.algorithm == 'UCS':
result = self.UCS()
elif self.algorithm == 'A* 0':
result = self.ASTAR(0)
elif self.algorithm == 'A* 1':
result = self.ASTAR(1)
print 'Nodos visitados:', self.num_visited
print 'Nodos na memoria:', self.max_mem
print 'Tempo total:', time.time() - start, 'segundos'
print 'Resultado:', result
print
def BFS(self):
queue = [[self.problem.tabuleiro, ""]]
visitados = []
while queue:
self.num_visited += 1
if self.max_mem < len(queue):
self.max_mem = len(queue)
node, caminho = queue.pop(0)
visitados.append(node)
if self.problem.testeObjetivo(node):
return caminho
for suc, move in self.problem.sucessores(node):
if suc not in visitados:
queue.append([suc, caminho + move])
def DLS(self, profundidade_maxima):
queue = [[self.problem.tabuleiro, ""]]
visitados = []
while queue:
self.num_visited += 1
if self.max_mem < len(queue):
self.max_mem = len(queue)
node, caminho = queue.pop(len(queue) - 1)
visitados.append(node)
if self.problem.testeObjetivo(node):
return caminho
for suc, move in self.problem.sucessores(node):
if suc not in visitados:
if len(caminho) <= profundidade_maxima:
queue.append([suc, caminho + move])
def IDFS(self):
for i in itertools.count():
result = self.DLS(i)
if result:
return result
def UCS(self):
queue = PriorityQueue()
queue.put([0, self.problem.tabuleiro, ''])
visitados = []
while queue:
self.num_visited += 1
if self.max_mem < queue.qsize():
self.max_mem = queue.qsize()
custo, node, caminho = queue.get_nowait()
visitados.append(node)
if self.problem.testeObjetivo(node):
return caminho
for suc, move in self.problem.sucessores(node):
if suc not in visitados:
queue.put([custo + 1, suc, caminho + move])
def heuristic_manhattan(self, tab):
tabuleiro = tab[::-1]
for i in range(0, len(tabuleiro) - 1):
if tabuleiro[i] == 0:
x = divmod(i, self.problem.n)
if x:
return int(x[0] + x[1])
return 0
def heuristic_full_manhattan(self, tab):
total = 0
matriz = []
for i in range(self.problem.n):
matriz.append(tab[i * self.problem.n: i * self.problem.n + self.problem.n])
for f in self.problem.final:
for i in range(self.problem.n):
for j in range(self.problem.n):
num = i * i + j + i + 1
num = num if num != self.problem.n * self.problem.n else 0
if f == num:
num = matriz[i][j] - 1 if matriz[i][j] != 0 else self.problem.n * self.problem.n - 1
x, y = divmod(num, self.problem.n)
total += abs(x - i) + abs(y - j)
return total / 2
def ASTAR(self, heuristic):
queue = PriorityQueue()
queue.put([0, self.problem.tabuleiro, ''])
visitados = []
while not queue.empty():
self.num_visited += 1
if self.max_mem < queue.qsize():
self.max_mem = queue.qsize()
custo, node, caminho = queue.get_nowait()
visitados.append(node)
if self.problem.testeObjetivo(node):
return caminho
for suc, move in self.problem.sucessores(node):
if suc not in visitados:
if heuristic == 1:
queue.put([self.heuristic_manhattan(suc) + custo + 1, suc, caminho + move])
else:
queue.put([self.heuristic_full_manhattan(suc) + custo + 1, suc, caminho + move])
|
def generate_concept_HTML(concept_title, concept_notes):
html_part_1 = '''
<div class="concept">
<div class="concept-title">
''' + concept_title
html_part_2 = '''
</div>
<div class="concept-notes">
''' + concept_notes
html_part_3 = '''
</div>
</div>'''
full_html = html_part_1 + html_part_2 + html_part_3
return full_html
def get_title(concept):
start_location = concept.find('TITLE:')
end_location = concept.find('NOTES:')
title = concept[start_location+7 : end_location-1]
return title
def get_notes(concept):
start_location = concept.find('NOTES:')
notes = concept[start_location+7 :]
return notes
def get_concept_by_number(text, concept_number):
counter = 0
while counter < concept_number:
counter = counter + 1
next_concept_start = text.find('TITLE:')
next_concept_end = text.find('TITLE:', next_concept_start + 1)
if next_concept_end >= 0:
concept = text[next_concept_start:next_concept_end]
else:
next_concept_end = len(text)
concept = text[next_concept_start:]
text = text[next_concept_end:]
return concept
TEST_TEXT = """TITLE: Computers
NOTES: Computers can be programmed to do anything we want as long as we can correctly
write out the program telling it what to do.
TITLE: Programs
NOTES: A program is a specific number of steps the computer can follow to do as requested.
Games, websites, simple apps are examples of programs.
TITLE: Python
NOTES: Python is a programming language that programmers can use to tell a computer what to
do. When python code is ran it interprets the code and makes it a list of instructions the
computer can follow.
TITLE: Grammar
NOTES: Now grammar in programming isn't the same as we would think. However, programming
does have its correct and incorrect situations. We have to be exactly correct for a computer
to understand what we want otherwise it won't run at all.
TITLE: Variables
NOTES: A way for programmers to give names for values in python.
Assigning variables is simple. To assign the value Anthony to the variable my_name the code
ooks like this:
my_name = 'Anthony'
It is important that you think of the equal sign as "is the same as" and not an equal sign
like in arithmetic. Variables are useful because it allows programmers to make the data
easier to read and understand. Another important fact is using quotation marks around a
number makes it a string instead of an integer. This changes the outcome of the code you
are inputting and gives a completely different answer.
"""
def generate_all_html(text):
current_concept_number = 1
concept = get_concept_by_number(text, current_concept_number)
all_html = ''
while concept != '':
title = get_title(concept)
notes = get_notes(concept)
concept_html = generate_concept_HTML(title, notes)
all_html = all_html + concept_html
current_concept_number = current_concept_number + 1
concept = get_concept_by_number(text, current_concept_number)
return all_html
print generate_all_html(TEST_TEXT)
|
# testing purposes to find real cost
from collections import deque
def bfs(puzzle):
queue = deque()
seen = set()
queue.append(puzzle.get_state())
queue.append(None)
seen.add(puzzle.get_state())
cost = 0
while True:
top = queue.popleft()
if top is None:
cost += 1
queue.append(None)
continue
puzzle.set_state(top)
if puzzle.is_current_state_goal():
break
for child in puzzle.get_current_state_children():
if child in seen:
continue
seen.add(child)
queue.append(child)
return cost
|
"""
Using the iterative parsing to process the map file and
find out not only what tags are there, but also how many, to get the
feeling on how much of which data you can expect to have in the map.
Fill out the count_tags function. It should return a dictionary with the
tag name as the key and number of times this tag can be encountered in
the map as value.
"""
import xml.etree.cElementTree as ET
import pprint
def count_tags(filename):
count_tags = {}
for event, elem in ET.iterparse(filename):
if elem.tag not in count_tags:
count_tags[elem.tag] = 1
else:
count_tags[elem.tag] += 1
return count_tags
tags = count_tags('new-york_new-york.osm')
pprint.pprint(tags)
|
import datetime
class Horaire():
"""
Save only hours and minutes.
Provide some counts.
Take silently count of passed day
"""
def __init__(self, h=0, m=0):
self.h, self.m = h, m
self.days = 0 # incremented when a day pass
self._normalize()
def __add__(self, othr):
"""
add to another Horaire object.
return a new object in all cases.
"""
assert(isinstance(othr, Horaire))
return Horaire(self.h + othr.h, self.m + othr.m)
def __eq__(self, othr):
"""
Return True iff othr have the same h and m
attributes
"""
return self.h == othr.h and self.m == othr.m
def __str__(self):
return str(self.h) + ':' + str(self.m)
def add_minutes(self, minutes):
"""
Return new Horaire object that have minutes more minutes.
"""
return self + Horaire(m=minutes)
def is_after(self, othr):
"""
Return True iff self is after (more hour, more minutes) othr,
or equal to it.
"""
assert(isinstance(othr, Horaire))
if self.h > othr.h:
return True
elif self.h == othr.h and self.m >= self.h:
return True
return False
def is_before(self, othr):
"""
Return True iff self is before (less hour, less minutes) othr,
or equal to it.
"""
assert(isinstance(othr, Horaire))
if self.h < othr.h:
return True
elif self.h == othr.h and self.m <= self.h:
return True
return False
def _normalize(self):
"""
normalize self for have at most 24h and 59mn
"""
self.h += self.m // 60
self.m %= 60
self.days += self.h // 24
self.h %= 24
def as_minutes(self):
"""Return self as an amount of minutes (integer)"""
return self.h * 60 + self.m
@staticmethod
def from_server_dialect(server_dialect):
"""
from given time format (returned by server):
2015-03-18T04:44:00+00:00
creat and return a new Horaire object
"""
time = datetime.datetime.strptime(server_dialect, '%Y-%m-%dT%H:%M:%S+00:00')
return Horaire(h=time.hour, m=time.minute)
@staticmethod
def from_schedules_dialect(schedules_dialect):
"""
from given time format (used by schedules):
44:00:00
creat and return a new Horaire object
"""
time = datetime.datetime.strptime(schedules_dialect, '%H:%M:%S')
return Horaire(h=time.hour, m=time.minute)
def to_server_dialect(self, day, month, year):
"""
return self in this time format (expected by server for move):
2015-03-18 04:44:00
"""
# TODO use arrow module for add self.day to day properly
return datetime.datetime(year=year, month=month, day=self.days+day, hour=self.h, minute=self.m).strftime('%d %b %H:%M:%S %Y')
if __name__ == '__main__':
h1 = Horaire(4, 30)
h2 = Horaire(4, 30)
assert((h1 + h2) == Horaire(9, 0))
print(h1.as_minutes())
print(h1.to_server_dialect(2, 11, 2015))
print(Horaire.from_server_dialect('2015-03-18T04:44:00+00:00'))
print(Horaire.from_schedules_dialect('04:44:05'))
# here are defined many useless functions
def add_minutes(travel_time, minutes):
"""
Wait for a datetime like
HH:MM:SS
and add the given integer minutes as minutes
finally, return the new time
"""
travel_time = datetime.datetime.strptime(datetime.datetime.strptime(travel_time, '%Y-%m-%d %H:%M:%S').strftime('%H:%M:%S'), '%H:%M:%S')
minutes = datetime.datetime.strptime(str(minutes), '%M')
minutes = datetime.timedelta(hours=minutes.hour, minutes=minutes.minute, seconds=minutes.second)
#print(minutes, minutes.__class__)
#print(travel_time, travel_time.__class__)
#print(minutes + travel_time)
return minutes + travel_time
def date_to_minute(travel_time):
"""
Wait for a datetime like
HH:MM:SS
and return this date in minute
"""
travel_time = datetime.datetime.strptime(datetime.datetime.strptime(travel_time, '%Y-%m-%d %H:%M:%S').strftime('%H:%M:%S'), '%H:%M:%S')
return travel_time.hour*60 + travel_time.minute
def minute_to_date(minutes):
"""
Take integer as minute number
Return an equivalent datetime like
HH:MM:SS
"""
travel_time = datetime.datetime.strptime(datetime.datetime.strptime(travel_time, '%H:%M:%S').strftime('%H:%M:%S'), '%H:%M:%S')
return travel_time.hour*60 + travel_time.minute
|
# Ces programmes sont sous licence CeCILL-B V1.
# Voici un programme qui résout l'équation du second degré
# a x^2 + b x + c = 0
from math import sqrt
a = float(input())
b = float(input())
c = float(input())
# Test du coefficient dominant
if a == 0.0:
print("Pas une équation du second degré")
else:
# Calcul du discriminant
delta = b * b - 4 * a * c;
# Affichage des solutions
if delta < 0.0:
print("Pas de solution")
elif delta == 0.0:
print("Une solution :",- b / (2 * a))
else:
print("Deux solutions : ",end="")
print((- b - sqrt(delta)) / (2 * a),end="")
print(" et ",end="")
print((- b + sqrt(delta)) / (2 * a))
|
"""
Operadores Lógicos
and, or, not
in e not in
"""
#
# In[2]: a = 2
# In[3]: b = 2
# In[4]: c = 3
#
# In[5]: a == b and b < c
# Out[5]: True
# Int[6]: a == b or b < c
# Out[6]: True
#
# Int[7]: not a == b and not b < c
# (Verdadeiro e False) = False
# comparacao1 and comparacao
# Verdadeiro ou Verdadeiro
# comp1 OR comp2
#
# a = 2
# b = 3
#
# if not b > a:
# print('B é maior do que A.')
# else:
# print('A é maior do que B.')
# a = ''
# b = 0
#
# if not a:
# print('Por favor, preencha o valor de A.')
# nome = 'Anna Karolina'
# if 'a' in nome:
# print("Existe")
# else:
# print("Não existe.")
#
# if 'asdas' not in nome:
# print("Executei.")
# else:
# print("Existe o texto.")
usuario = input('Nome de usuário: ')
senha = input('Senha do usuário: ')
usuario_bd = 'anna'
senha_bd = '123456'
if usuario == usuario and senha_bd == senha:
print('Você está logado no sistema.')
else:
print('Usuário ou senha inválidos.')
|
"""
Operadores Relacionais - Aula 12
== igualdade > maior que
>= maior que ou igual a
< menor que
<= menor que ou igual a
!= dirente
"""
# Os operadores relacionais são feitos justamente para realizar comparações entre coisa certo
# Desses aqui qualquer um desses operadores sempre que eles forem executados a expressao vai inteira e vai retornar um valor booleano
# print(2 == 2) # utilizando dois sinais de iguais a dois pensando seguinte sempre que utilizar um sinal de igual, afirmando que dois é igual a dois.
# num_1 = 2 # int
# num_2 = 2 # int
#
# expressao = (num_1 == num_2)
#
# print(expressao)
# var_1 = 'Luiz'
# var_2 = 'Otávio'
#
# expressao = (var_1 != var_2)
#
# print(expressao)
nome = input('Qual o seu nome? ')
idade = input('QUal a sua idade? ')
idade = int(idade)
idade_menor = 20 # muito jovem
idade_maior = 30 # passou da idade
# Limite para pegar empréstimo
idade_limite = 18
if idade >= idade_menor and idade <= idade_maior:
print(f'{nome} pode pegar o empréstimo.')
else:
print(f'{nome} Não pode pegar o empréstimo.')
|
"""
Funções (def) em Python - *args **kwargs
Word argumentos
Os argumentos posso utilizar dentro das funções
Eu chamo a função e coloco o nome da função e passo os argumentos citando o valor do 2 a 1.
Uma coisa que eu não posso fazer aqui por exemplo se eu tivesse mais um argumento aqui por exemplo A6, só que se ta vendo aqui que o Pai já está gerando erro aqui pra mim, isso está acontecendo por aqui, é o seguinte a partir do momento padrão a partir do momento que o certo um valor padrão para o argumento os proximos que vem depois dele tambem precisam de um padrão.
O argumento que eu quero que ela retorna pq ela retorna e eu posso utilizar um ou mais argumento se eu quiser por exemplo eu quero que ela retorne um nome ou A6 aqui e ai se eu der um print ela vai ter uma
"""
# def func(a1, a2, a3, a4, a5, nome=None, a6=None):
# print(a1, a2, a3, a4, a5, nome, a6)
# return nome, a6
# func(1, 2, 3, 4, 5, nome='Luiz', a6='5')
# print(var[0], var[1])
# def func(*args):
# print(args)
# print(args[0])
# print(args[-1])
# print(len(args))
# func(1, 2, 3, 4, 5)
# n1, n2, *n = lista
# print(*lista, sep='-')
# def func(*args, **kwargs):
# for v in args:
# print(args)
# print(kwargs['nome'], kwargs['sobrenome'])
# nome = kwargs.get('nome')
# print(nome)
def func(*args, **kwargs):
print(args)
idade = kwargs.get('idade')
if idade is not None:
print(idade)
else:
print('Idade não existe.')
lista = [1,2,3,4,5]
lista2 = [10, 20, 30, 40, 50]
func(*lista, *lista2, nome='Luiz', sobrenome='Miranda', idade=30)
|
"""
Basicamente pra treinar unir as coisas que a gente aprendeu ate nesse momento
A gente vai utilizar os laços formam a estrutura de repetiçao
"""
print('Texto explicativo.')
print()
perguntas = {
'Pergunta 1': {
'pergunta': 'Quanto e 2+2? ',
'resposta': {'a': '1', 'b': '4', 'c': '5',},
'resposta_certa': 'b',
},
'Pergunta 2': {
'pergunta': 'Quanto e 3*2? ',
'respostas': {'a': '4', 'b': '10', 'c': '6',},
'resposta_certa': 'c',
},
}
print()
respostas_certas = 0
for pk, pv in perguntas.items():
print(f'{pk}: {pv["pergunta"]}')
print('Respostas: ')
print('Respostas: ')
for rk, rv in pv['respostas'].items():
print(f'[{rk}]: {rv}')
resposta_usuario = input('Sua resposta: ')
if resposta_usuario == pv['resposta_certa']:
print('EHHHHHHH!!! Voce acertou!!!!')
respostas_certas += 1
else:
print('IXIII!! Voce errou!!!')
qtd_perguntas = len(perguntas)
porcentagem_acerto = respostas_certas / qtd_perguntas * 100
print(f'Voce acertou {respostas_certas} respostas.')
print(f'Sua porcentagem de acerto foi de {porcentagem_acerto}%.')
|
Precedência dos Operadores Aritméticos
Assim como aprendemos na matemática, operadores têm uma certa precedência que pode ser alterada usando os parênteses (como descrito na aula anterior).
Abaixo, segue uma lista mais precisa de quais operadores tem maior prioridade na hora de realizar contas mais complexas (de maior para menor precedência).
( n + n ) - Os parênteses têm a maior precedência, contas dentro deles são realizadas primeiro
** - Depois vem a exponenciação
* / // % - Na sequência multiplicação, divisão, divisão inteira e módulo
+ - - Por fim, soma e subtração
Contas com operadores de mesma precedência são realizadas da esquerda para a direita.
Observação: existem muito mais operadores do que estes em Python e todos eles também têm precedência, você pode ver a lista completa em https://docs.python.org/3/reference/expressions.html#operator-precedence (sempre utilize a documentação oficial como reforço caso necessário).
Caso tenha dúvidas, faça testes com números. Por exemplo, olhe para essa conta e tente decifrar como chegar no resultado: 2 + 5 * 3 ** 2 - (23.5 + 23.5) (o resultado é 0.0). Para isso você precisa realizar as contas com maior precedência primeiro.
|
# def funcao(args, arg2):
# return arg * arg2
#
# var = funcao(2, 2)
# print(var)
lista = [
['P1', 13],
['P2', 6],
['P3', 7],
['P4', 50],
['P5', 8],
]
print(sorted(lista, key=lambda i: i[0], reverse=True))
print(lista)
"""
esses dois numeros multiplicados na tela
"""
|
"""
add (adiciona), update (atualiza), clear, discard
union | (une)
intersection & (todos os elementos presentes nos dois sets)
difference - (elementos apenas no set da esquerda)
symmetric_difference (elementos que estao nos dois sets)
"""
l1 = ['Luiz', 'Joao', 'Maria']
l2 = ['Joao', 'Maria', 'Maria',
'Luiz', 'Luiz',]
if set(l1) == set(l2):
print('L1 e igual a L2')
else:
print('L1 e diferente de L2')
|
"""
Planetary Gravity Calculator
Given the dimensions of several planets and an object's mass,
calculate the amount of force exerted on an object's surface
using Newton's Law of Universal Gravitation:
F = G * ((M1 * M2) / D)
Example:
Input:
Object mass = 100 kg
Number of planets = 4
List of planets (name, radius (m), and avg density (kg/m^3)) =
Tantalus, 3104500, 5009
Reach, 7636500, 4966
Circumstance, 4127000, 4132
Tribute, 2818000, 4358
Output:
Weight of object on each planet (in Newtons) =
Tantalus: 434.467 N
Reach: 1059.536 N
Circumstance: 476.441 N
Tribute: 343.117 N
"""
import argparse
import math
# Gravitational constant
G = float("6.67e-11")
class Planet(object):
def __init__(self, name, radius, density):
self.name = name
self.radius = radius
self.density = density
self.volume = (4 * math.pi * math.pow(self.radius, 3)) / 3
self.mass = self.volume * self.density
def calc_force(self, obj_mass):
return float(G * ((obj_mass * self.mass) / math.pow(self.radius, 2)))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Program that calculates the gravitational'
'pull on an object of mass M on a number N'
'of given planets.')
parser.add_argument('-f', '--file', action='store', default=None, dest='input',
help='Optional text file containing data for each planet.')
args = parser.parse_args()
planet_objects = []
object_mass = 0
if args.input is None:
object_mass = int(raw_input('Object mass (in kg): '))
num_planets = int(raw_input('Number of planets: '))
for i in range(0, num_planets):
planet_name = raw_input('Planet name ({}/{}): '.format(i+1, num_planets))
planet_radius = int(raw_input('Planet radius ({}/{}): '.format(i+1, num_planets)))
planet_density = int(raw_input('Planet density ({}/{}): '.format(i+1, num_planets)))
planet_objects.append(Planet(planet_name, planet_radius, planet_density))
print "\n"
print "=====Weight of object of mass M on each given planet====="
for p in planet_objects:
print "{}:\t{} N".format(p.name, p.calc_force(object_mass))
else:
object_mass = int(raw_input('Object mass (in kg): '))
with open(args.input, 'r') as f:
for line in f:
try:
planet_name, planet_radius, planet_density = line.split(',')
planet_objects.append(Planet(planet_name, float(planet_radius), float(planet_density)))
except ValueError:
pass
print "\n"
print "=====Weight of object of mass M on each given planet====="
for p in planet_objects:
print "{0}:\t{1:.3f} N".format(p.name, p.calc_force(object_mass))
|
"""
Given a number of card decks, determine the probability that
a blackjack hand will be dealt by the dealer.
"""
import random
def getIntRange(low, high, prompt="", errmsg=""):
if prompt == "":
prompt = "Please enter the number of decks (%d-%d): " % (low, high)
if errmsg == "":
errmsg = "Please enter a valid integer (%d-%d): " % (low, high)
good_input = False
n = 0
while not good_input:
input = raw_input(prompt)
try:
n = int(input)
if str(n) == input and n >= low and n <= high:
good_input = True
except:
pass
if not good_input:
print errmsg
return n
n = getIntRange(1, 10)
suits = ['C', 'D', 'H', 'S']
values = {'A': 11, '2': 2, '3': 3, '4': 4, '5': 5,
'6': 6, '7': 7, '8': 8, '9': 9, '10': 10,
'J': 10, 'Q': 10, 'K': 10}
deck = []
for suit in suits:
for value in values:
deck.append((suit, value))
total_decks = deck * n
random.shuffle(total_decks)
count = 0
num_hands = len(total_decks) / 2
stop_hand = len(total_decks) - 1
for i in range(0, stop_hand, 2):
card1, card2 = total_decks[i], total_decks[i + 1]
display = "%s%s %s%s" % (card1[1], card1[0], card2[1], card2[0])
if values[card1[1]] + values[card2[1]] == 21:
display += " -Blackjack!"
count += 1
print display
percent = float(count) / float(num_hands) * 100
if count == 0:
print("There were no blackjacks.")
elif count >= 1:
print "After %i hands there were %i blackjacks at %i" % (num_hands, count, percent) + "%"
|
"""
Given a number of potential jobs/workers, assign jobs to workers
based on unique skill matches. My solution didn't work, but I've
included the most elegant solution presented on Reddit.
"""
def my_solution():
num_jobs_workers = int(raw_input("How many jobs/workers? "))
job_input_count = num_jobs_workers
worker_input_count = num_jobs_workers
avail_jobs = []
avail_workers = {}
while job_input_count > 0:
job = raw_input("Please enter a job (%s left): " % job_input_count)
avail_jobs.append(job)
job_input_count -= 1
while worker_input_count > 0:
worker = raw_input("Please enter a worker followed by skill "
"list (%s left): " % worker_input_count)
name, skills = worker.split(' ', 1)
skill_list = skills.split(',')
avail_workers[name] = skill_list
worker_input_count -= 1
for jobs in avail_jobs:
for worker, skill in avail_workers.iteritems():
if job in skill:
print "%s\t%s" % (worker, jobs)
avail_jobs.remove(job)
def elegant_solution():
from itertools import product
jobs = {}
worker = ' '
while worker:
worker, sep, skills = input().strip().partition(' ')
if skills:
jobs[worker] = {skill.strip() for skill in skills.split(',')}
for name, job in zip(jobs, next(x for x in product(*jobs.values()) if len(x) == len(set(x)))):
print(name + ' ' + job)
|
print("|--- 欢迎进入通讯录程序 ---|")
print("|--- 1:查询联系人资料 ---|")
print("|--- 2:插入新的联系人 ---|")
print("|--- 3:删除已有联系人 ---|")
print("|--- 4:退出通讯录程序 ---|")
contacts = {'闫':'1','帅':'2','舟':'3'}
while 1:
instr = int(input('\n请输入相关得代码指令:'))
if instr == 1:
name = input('请输入联系人姓名:')
if name in contacts:
print(name + ':'+ contacts[name])
else:
print('你输入的联系人不再通讯录里')
if instr == 2:
name = input('请输入联系人姓名:')
if name in contacts:
print('你输入得姓名已经存在于通讯录里面-->>',end='')
print(name +':' + contacts[name])
if input('是否修改用户资料(YEZ/NO);') =='YES':
contacts[name] = input("请输入用户电话:")
else:
contacts[name] = input('请输入用户联系电话:')
if instr == 3:
name = input('请输入联系人姓名:')
if name in contacts:
del(contacts[name])
else:
print('您输入得联系人不存在。')
if instr == 4:
break
print('|--- 感谢使用通讯录程序 ---|')
|
import copy
import buscas
import expansaoJogo
import time
print("-----------------------------")
print("--------JOGO DOS 8 ----------")
print("-----------------------------")
#time.sleep(1)
continuar = 1
print("Esse jogo pode ser resolvido através de buscas de Inteligência Artificial")
while(continuar == 1):
#time.sleep(2)
print("Antes de tudo, qual tabuleiro inicial deseja utilizar?")
print("Opção 1:")
print("[2, 8, 1]")
print("[0, 4, 3]")
print("[7, 6, 5]")
#time.sleep(1)
print("Opção 2:")
print("[1, 3, 4]")
print("[8, 6, 2]")
print("[7, 0, 5]")
#time.sleep(1)
print("Opção 3:")
print("[2, 8, 3]")
print("[1, 6, 4]")
print("[7, 0, 5]")
esc = int(input("\nInforme a sua escolha"))
if(esc == 1):
configInicial = [[2,8,1],[0,4,3],[7,6,5],[0,None],[0, 0]]
elif(esc == 2):
configInicial = [[1,3,4],[8,6,2],[7,0,5],[0,None],[0, 0]]
elif(esc == 3):
configInicial = [[2,8,3],[1,6,4],[7,0,5],[0,None],[0, 0]]
else:
print("Opção Inválida")
break
print("O tabuleiro ficou configurado da seguinte forma:")
expansaoJogo.mostraTabuleiro(configInicial)
configInicial[4][0] = buscas.pecasFora(configInicial)
configInicial[4][1] = buscas.Manhattan(configInicial)
#time.sleep(1)
print("As buscas disponíveis para resolução são: Busca Cega em Largura ou Busca Heurística com A-Estrela")
print("Para continuar, informe qual algoritmo deseja para a busca")
print("1: Busca em Largura")
print("2: Busca Utilizando A-Estrela com Heurística de Peças fora do Lugar?")
print("3: Busca utilizando A-Estrela com Heurística de Distância de Manhattan?")
op = int(input('Informe uma opção:'))
if(op==1):
buscas.buscaLargura(configInicial)
elif(op==2):
buscas.buscaAestrelaPecas(configInicial)
elif(op==3):
buscas.buscaAestrelaManhattan(configInicial)
else:
print("Opção Inválida")
break
print("--------------")
esc2 = int(input("\nDeseja verificar a resolução com outra configuração? (1 p/ sim, 0 p/ não)"))
if(esc2 == 1):
continuar = 1
elif(esc2 == 0):
continuar = 0
print("\n Até mais o/")
break
|
import numpy as np
import csv
import pandas as pd
import os
import pandas as pd
import queue
import threading
import datetime
import time
csv.field_size_limit(1000000000)
def count_csv_rows(csv_file_name):
"""This function is to get the row number of a csv file."""
with open(csv_file_name) as csvfile:
reader = csv.DictReader(csvfile)
i = 0
for row in reader:
i += 1
return i
def divide_lager_csv(csv_file_name, output_file_path, column1_name, column2_name, row_num_each_file=150000):
"""This function is to divide a lager csv file into multiple flies with a specified size."""
with open(csv_file_name) as csvfile:
reader = csv.DictReader(csvfile)
i = 0
rows = []
for row in reader:
rows.append(row)
if (i%row_num_each_file) == (row_num_each_file-1):
with open(output_file_path+'piece'+str(int(i/row_num_each_file))+'.csv', 'w', newline='') as f:
csv_writer = csv.DictWriter(f, [column1_name, column2_name])
csv_writer.writeheader()
csv_writer.writerows(rows)
rows = []
i += 1
if len(rows) > 0:
with open(output_file_path+'piece'+str(int(i/row_num_each_file))+'.csv', 'w', newline='') as f:
csv_writer = csv.DictWriter(f, [column1_name, column2_name])
csv_writer.writeheader()
csv_writer.writerows(rows)
def get_file_paths_from_folder(folder, extensions=["csv"]):
file_paths = []
for extension in extensions:
file_glob = glob.glob(folder+"/*."+extension) #不分大小写
file_paths.extend(file_glob) #添加文件路径到file_paths
return file_paths
def get_data_from_csv(csv_file_name, column1_name, column2_name, start_index=0, len=None):
"""This function is to return sequence data from a csv file."""
column1 = []
column2 = []
#train = pd.read_csv(csv_file_name)
with open(csv_file_name) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
column1.append(row[column1_name])
column2.append(row[column2_name])
return column1, column2
def get_data_from_pieces(csv_piece_path_or_data, column1_name, column2_name, start_point=None,
data_len=150000, piece_len=150000, total_len=629145480,
descending=True): # in test
"""This function is to return a data piece from train csv pieces.
Note that if csv_piece_path is not a path, it needs to be a list (array) of all data."""
column1 = []
column2 = []
iterative = True
if start_point == None:
start_point = np.random.randint(0, total_len-data_len)
iterative = False
if type(csv_piece_path_or_data) != type("str"):
return csv_piece_path_or_data[:data_len], csv_piece_path_or_data[:data_len]
data = pd.read_csv(csv_piece_path_or_data+'piece'+str(int(start_point/piece_len))+'.csv')
column1 = data[column1_name].values[(start_point%piece_len):]
column2 = data[column2_name].values[(start_point%piece_len):]
if column1.shape[0] <= data_len:
data = pd.read_csv(csv_piece_path_or_data+'piece'+str(int(start_point/piece_len)+1)+'.csv')
column1 = np.concatenate((column1, data[column1_name].values[:data_len-column1.shape[0]]),axis=0)
column2 = np.concatenate((column2, data[column2_name].values[:data_len-column2.shape[0]]),axis=0)
return column1[:data_len], column2[:data_len]
class batch_queue:
"""This class is for a batch queue with multiple threads for fast sampling."""
def __init__(self, batch_size, column1_name, column2_name, on_cloud, csv_piece_path,
thread_num=4, X_preprocessor=None, Y_preprocessor=None, use_lager_csv=False):
"""define a data queue and some threads, and start the threads.
Note that X_preprocessor is a fuction with one input X,
but Y_preprocessor has two inputs X and y"""
self.data_queue = queue.Queue(maxsize=thread_num*100)
self.batch_size = batch_size
self.csv_piece_path = csv_piece_path
self.X_preprocessor = X_preprocessor
self.Y_preprocessor = Y_preprocessor
self.column1_name = column1_name
self.column2_name = column2_name
self.cache_thread = []
thread_num += on_cloud*4
self.lager_csv_data = None
if use_lager_csv == True:
self.lager_csv_data = pd.read_csv(csv_piece_path)
for i in range(thread_num) :
self.cache_thread.append(threading.Thread(target=self.batch_adder))
self.cache_thread[i].daemon = True
self.cache_thread[i].start()
def add_batch(self):
"""add a batch to the queue"""
batch_X = []
batch_y = []
for i in range(self.batch_size):
if self.lager_csv_data == None:
X, Y = get_data_from_pieces(self.csv_piece_path, self.column1_name, self.column2_name)
else:
X, Y = get_data_from_pieces(self.lager_csv_data, self.column1_name, self.column2_name)
if self.X_preprocessor != None:
X = self.X_preprocessor(X)
y = Y[-1]
if self.Y_preprocessor != None:
y = self.Y_preprocessor(X, y)
batch_X.append(X)
batch_y.append(y)
self.data_queue.put([batch_X, batch_y])
def batch_adder(self):
"""always add batches if the queue is not full"""
while True:
self.add_batch()
def get_batch(self):
"""get a batch"""
return self.data_queue.get()
def get_multi_batch_as_one(self, multiple):
"""get a customized large batch containing multiple batches"""
batch_X = []
batch_y = []
for i in range(multiple):
X, y = self.data_queue.get()
batch_X.extend(X)
batch_y.extend(y)
return batch_X, batch_y
class batch_queue_V2:
"""This class is modified from the class above for combined models.
Note that this class has many points (such as raw input, which can be just a data piece) to imporve."""
def __init__(self, on_cloud, raw_batch_adder, adder_args=(), adder_num=1,
X_preprocessor=None, Y_preprocessor=None, preprocessor_num=1, queue_size_multiple=100):
# cache raw data
self.raw_data_queue = queue.Queue(maxsize=adder_num*queue_size_multiple)
self.raw_batch_adder = raw_batch_adder
self.adder_args = adder_args
self.batch_adder_threads = []
self.adder_num = adder_num + (on_cloud*4)
self.queue_size_multiple = queue_size_multiple
for i in range(adder_num):
self.batch_adder_threads.append(threading.Thread(target=self.batch_adder_thread))
self.batch_adder_threads[i].daemon = True
self.batch_adder_threads[i].start()
# calculate and cache samples
self.sample_queue = queue.Queue(maxsize=adder_num*queue_size_multiple)
self.X_preprocessor = X_preprocessor
self.Y_preprocessor = Y_preprocessor
self.preprocessor_threads = []
for i in range(preprocessor_num):
self.preprocessor_threads.append(threading.Thread(target=self.preprocessor_thread))
self.preprocessor_threads[i].daemon = True
self.preprocessor_threads[i].start()
def batch_adder_thread(self):
while True:
self.raw_data_queue.put(self.raw_batch_adder(adder_args[1]))
def preprocessor_thread(self):
X_buffer = []
Y_buffer = []
while True:
data = self.raw_data_queue.get()
X_buffer.extend(data[0])
Y_buffer.extend(data[1])
if len(X_buffer) == self.adder_num*self.queue_size_multiple:
batch_size = len(data[0])
if self.X_preprocessor == None:
sample_data = X_buffer
else:
sample_data = self.X_preprocessor(X_buffer)
if self.Y_preprocessor == None:
sample_labels = Y_buffer
else:
sample_labels = self.Y_preprocessor(X_buffer, Y_buffer)
for i in range(self.adder_num*self.queue_size_multiple):
self.sample_queue.put([sample_data[i*batch_size:(i+1)*batch_size],
[sample_labels[i*batch_size:(i+1)*batch_size]]])
X_buffer = []
Y_buffer = []
def get_batch(self):
"""get a sample batch"""
return self.sample_queue.get()
class batch_queue_V3:
"""This class is modified from the class above for combined models.
Note that adder_args is a parameter dictionary of RNN_starter's creat_X(),
that is, adder_args[0] is whole raw data.
raw_data_adder:a function used to add data pieces to a dada queue,
it's input is a list of data pieces.
segment_preprocessor:a dada preprocessor used to preprocess data in
the dada queue and add a list of batches to a
sample queue.
segment_input_len:input length of segment_preprocessor"""
def __init__(self, on_cloud, raw_data_adder, adder_args=(), adder_num=4,
segment_preprocessor=None, segment_input_len=32*15, segment_output_len=30, preprocessor_num=1,
queue_size_multiple=100, watch_dog=None):
self.watch_dog = watch_dog
# cache raw data
self.adder_num = adder_num + (on_cloud*4)
self.raw_data_queue = queue.Queue(maxsize=self.adder_num*queue_size_multiple)
self.raw_data_adder = raw_data_adder
self.adder_args = adder_args
self.data_adder_threads = []
self.queue_size_multiple = queue_size_multiple
for i in range(self.adder_num):
self.data_adder_threads.append(threading.Thread(target=self.data_adder_thread))
self.data_adder_threads[i].daemon = True
self.data_adder_threads[i].start()
# calculate and cache samples
if segment_preprocessor == None:
self.sample_queue = self.raw_data_queue
else:
self.sample_queue = queue.Queue(maxsize=segment_output_len)
self.segment_preprocessor = segment_preprocessor
self.segment_input_len = segment_input_len
self.preprocessor_threads = []
for i in range(preprocessor_num):
self.preprocessor_threads.append(threading.Thread(target=self.preprocessor_thread))
self.preprocessor_threads[i].daemon = True
self.preprocessor_threads[i].start()
def data_adder_thread(self):
"""thread of the raw_batch_adder"""
while True:
data_batch = self.raw_data_adder(*self.adder_args)
for data in data_batch:
self.raw_data_queue.put(data)
def preprocessor_thread(self):
"""thread of the segment_preprocessor"""
buffer = []
while True:
buffer.append(self.raw_data_queue.get())
if len(buffer) == self.segment_input_len:
batch_list = self.segment_preprocessor(buffer)
for batch in batch_list:
self.sample_queue.put(batch)
buffer.clear()
def get_batch(self, is_array_output=True):
"""get a sample batch"""
if is_array_output == False:
return self.sample_queue.get()
attribute_list = self.sample_queue.get()
array_list = []
for attributes in attribute_list:
array_list.append(np.array(attributes))
return array_list
def check_and_print(self, text):
"""feed the wathcdog if it exists, otherwise just print the text."""
if self.watch_dog != None:
self.watch_dog.feeding(text)
else:
print(text)
class generator_generator:
"""This class is used for generating generators sharing the same data queue.
Note that the parameter definition is from a certain context (RNN_starter)."""
def __init__(self, data, raw_data_adder, segment_preprocessor, on_cloud, min_index=0, max_index=None,
batch_size=16, n_steps=150, step_length=1000):
if max_index is None:
max_index = len(data) - 1
self.data_queue = batch_queue_V3(on_cloud, raw_data_adder,
(data, min_index, max_index, batch_size, n_steps, step_length),
segment_preprocessor=segment_preprocessor)
def generator(self):
while True:
#get a cached batch
sample_batch = self.data_queue.get_batch()
yield sample_batch[0], sample_batch[1]
def get_frequency_feature(input, window_size=None, mutil_dimension=False):
if (window_size==None) or (window_size>=len(input)):
return np.abs(np.fft.rfft(input))
output = []
for i in range(len(input)-window_size+1):
result = np.abs(np.fft.rfft(input[i:i+window_size]))
if mutil_dimension == False:
output.append(np.mean(result))
else:
output.append(result)
return np.array(output)
import zipfile
def zipDir(dirpath,outFullName):
"""
压缩指定文件夹
:param dirpath: 目标文件夹路径
:param outFullName: 压缩文件保存路径+xxxx.zip
:return: 无
"""
zip = zipfile.ZipFile(outFullName,"w",zipfile.ZIP_DEFLATED)
for path,dirnames,filenames in os.walk(dirpath):
# 去掉目标跟路径,只对目标文件夹下边的文件及文件夹进行压缩
fpath = path.replace(dirpath,'')
for filename in filenames:
zip.write(os.path.join(path,filename),os.path.join(fpath,filename))
zip.close()
"""
def g():
input = [np.sqrt(2)/2, 1, np.sqrt(2)/2, 0, np.sqrt(2)/-2, -1, np.sqrt(2)/-2, 0]
output = np.fft.rfft(input)
frequency = np.abs(output)
print(frequency)
"""
class watchdog:
"""This is a watchdog class used for avoiding out-of-control on the cloud (and also logging)."""
def __init__(self, food_path, on_cloud, log_path=None):
self.food_path = food_path
self.on_cloud = on_cloud
self.log_path = log_path
self.counting = 0
if on_cloud==True:
with open(food_path, "a") as f:
print("enable watch dog")
#thread = threading.Thread(target=self.watch_thread)
#thread.daemon = True
#thread.start()
else:
print("disable watch dog")
def feeding(self, added_text=None, quiet=True):
"""stop the running code if food is not here"""
if self.on_cloud == True:
try:
with open(self.food_path, "r") as f:
if quiet:
pass
elif self.log_path != None:
with open(self.log_path, "a") as f:
print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), file=f)
if added_text != None:
print(added_text, file=f)
print("", file=f)
else:
print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
if added_text != None:
print(added_text)
print("")
except:
os._exit(1)
def interval_feeding(self, interval, added_text=None):
"""feed the dog in intervals"""
self.counting += 1
if self.counting % interval == 0:
self.feeding(added_text)
def watch_thread(self):
"""automatically watch"""
while True:
time.sleep(5)
self.feeding("auto feeding")
def install_package_offline(pack_path):
"""creat a thread to install a needed package offline"""
thread = threading.Thread(target=os.system, args=("pip install "+pack_path,))
thread.daemon = True
thread.start()
return thread
def package_installer(package_names):
"""install needed packages"""
for package_name in package_names:
os.popen("pip install --upgrade "+package_name).read()
def install_packages(package_names):
"""creat a thread to install needed packages"""
thread = threading.Thread(target=package_installer, args=(package_names,))
thread.daemon = True
thread.start()
return thread
def unzip_in_same_folder(file_path):
os.popen("unzip -d "+os.path.splitext(file_path)[0]+" "+file_path).read()
def load_flie(input_path_name, output_path, unzip=False):
"""load training and test data"""
os.popen("cp "+input_path_name+" "+output_path).read()
if unzip == True:
thread = threading.Thread(target=unzip_in_same_folder, args=(output_path,))
thread.daemon = True
thread.start()
return thread
return None
import sys
import importlib
def satellite_thread(watch_dog, subwork_names=[], outout_file_path_name=None, second_delay=4):
"""set this before running on the cloud"""
if len(subwork_names) != 0:
subwork_list = list(np.zeros(len(subwork_names)))
else:
subwork_list = []
while True:
try:
if outout_file_path_name != None:
output = open(outout_file_path_name, 'a')
sys.stdout = output
time.sleep(second_delay)
sys.stdout.close()
sys.stderr.flush()
else:
time.sleep(second_delay)
sys.stdout.flush()
sys.stderr.flush()
watch_dog.feeding()
# try to run subwork
for i in range(len(subwork_names)):
try:
subwork = importlib.import_module(name)
if subwork_list[i] != 0:
subwork_list[i] = threading.Thread(target=subwork.main, args=(0,))
subwork_list[i].daemon = True
subwork_list[i].start()
except:
subwork_list[i] = 0
except:
os._exit(None)
def on_cloud_print_setting(saving_path, on_cloud, subwork_names=[], outout_file_path_name=None):
# creat a satellite thread
watch_dog = watchdog(saving_path+"food", on_cloud)
thread = threading.Thread(target=satellite_thread,
args=(watch_dog, subwork_names, outout_file_path_name))
thread.daemon = True
thread.start()
return thread
class batch_generator_V2:
"""this class is used to generate a data batch from all raw data"""
def __init__(self, raw_csv_path_name):
self.float_data = pd.read_csv(raw_csv_path_name,
dtype={"acoustic_data": np.int16, "time_to_failure": np.float64}).values
def get_raw_batch(self, data=None, min_index=0, max_index=None,
batch_size=32, n_steps=150, step_length=1000):
"""get a random batch. Note that input data is all of training data"""
if data is None:
data = self.float_data
if max_index is None:
max_index = len(data)-1
# Pick indices of ending positions
rows = np.random.randint(min_index + n_steps * step_length, max_index, size=batch_size)
#rows = np.ones([batch_size], np.int)*150000
# Initialize samples and targets
raw_sample_data = []
sample_labels = []
for j, row in enumerate(rows):
raw_sample_data.append(data[(row - n_steps * step_length):row, 0])
sample_labels.append(data[row - 1, 1])
return raw_sample_data, sample_labels
import glob
def submission_blending(csv_path, output_file_path_name):
"""output a combined submission file of multiple submission files in csv_path"""
# load csv files
csv_list = []
file_glob = glob.glob(csv_path+"/*.csv") #不分大小写
for file_path in file_glob:
csv_list.append(pd.read_csv(file_path, index_col='seg_id', dtype={"time_to_failure": np.float64}))
csv_list[0]['time_to_failure'] = csv_list[0]['time_to_failure']/len(csv_list)
for csv_ in csv_list[1:]:
csv_list[0]['time_to_failure'] += csv_['time_to_failure']/len(csv_list)
csv_list[0].to_csv(output_file_path_name)
def weighted_submission_blending(csv_path_name_list, weight_list, output_file_path_name):
"""output a combined submission file of multiple submission files in csv_path"""
# load csv files
csv_list = []
for file_path in csv_path_name_list:
csv_list.append(pd.read_csv(file_path, index_col='seg_id', dtype={"time_to_failure": np.float64}))
# weight output
weight_count = np.sum(weight_list)
csv_list[0]['time_to_failure'] = csv_list[0]['time_to_failure']*weight_list[0]/weight_count
for i in range(len(csv_list[1:])):
csv_list[0]['time_to_failure'] += csv_list[i+1]['time_to_failure']*weight_list[i+1]/weight_count
csv_list[0].to_csv(output_file_path_name)
# denoising
from numpy.fft import *
import pandas as pd
import pywt
from statsmodels.robust import mad
import scipy
from scipy import signal
from scipy.signal import butter, deconvolve
import warnings
warnings.filterwarnings('ignore')
SIGNAL_LEN = 150000
SAMPLE_RATE = 4000
def maddest(d, axis=None):
"""
Mean Absolute Deviation
"""
return np.mean(np.absolute(d - np.mean(d, axis)), axis)
def high_pass_filter(x, low_cutoff=1000, SAMPLE_RATE=SAMPLE_RATE):
"""
From @randxie https://github.com/randxie/Kaggle-VSB-Baseline/blob/master/src/utils/util_signal.py
Modified to work with scipy version 1.1.0 which does not have the fs parameter
"""
# nyquist frequency is half the sample rate https://en.wikipedia.org/wiki/Nyquist_frequency
nyquist = 0.5 * SAMPLE_RATE
norm_low_cutoff = low_cutoff / nyquist
# Fault pattern usually exists in high frequency band. According to literature, the pattern is visible above 10^4 Hz.
sos = butter(10, Wn=[norm_low_cutoff], btype='highpass', output='sos')
filtered_sig = signal.sosfilt(sos, x)
return filtered_sig
def denoise_signal(x, wavelet='db4', level=1):
"""
1. Adapted from waveletSmooth function found here:
http://connor-johnson.com/2016/01/24/using-pywavelets-to-remove-high-frequency-noise/
2. Threshold equation and using hard mode in threshold as mentioned
in section '3.2 denoising based on optimized singular values' from paper by Tomas Vantuch:
http://dspace.vsb.cz/bitstream/handle/10084/133114/VAN431_FEI_P1807_1801V001_2018.pdf
"""
# Decompose to get the wavelet coefficients
coeff = pywt.wavedec(x, wavelet, mode="per")
# Calculate sigma for threshold as defined in http://dspace.vsb.cz/bitstream/handle/10084/133114/VAN431_FEI_P1807_1801V001_2018.pdf
# As noted by @harshit92 MAD referred to in the paper is Mean Absolute Deviation not Median Absolute Deviation
sigma = (1/0.6745) * maddest(coeff[-level])
# Calculate the univeral threshold
uthresh = sigma * np.sqrt(2*np.log(len(x)))
coeff[1:] = (pywt.threshold(i, value=uthresh, mode='hard') for i in coeff[1:])
# Reconstruct the signal using the thresholded coefficients
return pywt.waverec(coeff, wavelet, mode='per')
# function of downloading image
import urllib
from PIL import Image
from io import BytesIO
def DownloadImage(key_url, out_dir):
(key, url) = key_url
filename = os.path.join(out_dir, '%s.jpg' % key)
if os.path.exists(filename):
print('Image %s already exists. Skipping download.' % filename)
return
try:
response = urllib.request.urlopen(url)
except:
print('Warning: Could not download image %s from %s' % (key, url))
return
try:
pil_image = Image.open(BytesIO(response.read()))
except:
print('Warning: Failed to parse image %s' % key)
return
try:
pil_image_rgb = pil_image.convert('RGB')
except:
print('Warning: Failed to convert image %s to RGB' % key)
return
try:
pil_image_rgb.save(filename, format='JPEG', quality=90)
except:
print('Warning: Failed to save image %s' % filename)
return
# feature generator from masterpiece1
def features(x, y, seg_id):
with open(context.saving_path+'logs.txt', 'a') as f:
print("start to get features at " + str(seg_id), file=f)
feature_dict = dict()
feature_dict['target'] = y
feature_dict['seg_id'] = seg_id
# create features here
# numpy
# lists with parameters to iterate over them
percentiles = [1, 5, 10, 20, 25, 30, 40, 50, 60, 70, 75, 80, 90, 95, 99]
hann_windows = [50, 150, 1500, 15000]
spans = [300, 3000, 30000, 50000]
windows = [10, 50, 100, 500, 1000, 10000]
borders = list(range(-4000, 4001, 1000))
peaks = [10, 20, 50, 100]
coefs = [1, 5, 10, 50, 100]
lags = [10, 100, 1000, 10000]
autocorr_lags = [5, 10, 50, 100, 500, 1000, 5000, 10000]
# basic stats
feature_dict['mean'] = x.mean()
feature_dict['std'] = x.std()
feature_dict['max'] = x.max()
feature_dict['min'] = x.min()
# basic stats on absolute values
feature_dict['mean_change_abs'] = np.mean(np.diff(x))
feature_dict['abs_max'] = np.abs(x).max()
feature_dict['abs_mean'] = np.abs(x).mean()
feature_dict['abs_std'] = np.abs(x).std()
# geometric and harminic means
feature_dict['hmean'] = stats.hmean(np.abs(x[np.nonzero(x)[0]]))
feature_dict['gmean'] = stats.gmean(np.abs(x[np.nonzero(x)[0]]))
# k-statistic and moments
for i in range(1, 5):
feature_dict['kstat_' + str(i)] = stats.kstat(x, i)
feature_dict['moment_' + str(i)] = stats.moment(x, i)
for i in [1, 2]:
feature_dict['kstatvar_' +str(i)] = stats.kstatvar(x, i)
# aggregations on various slices of data
for agg_type, slice_length, direction in product(['std', 'min', 'max', 'mean'], [1000, 10000, 50000], ['first', 'last']):
if direction == 'first':
feature_dict[agg_type + '_' + direction + '_' + str(slice_length)] = x[:slice_length].agg(agg_type)
elif direction == 'last':
feature_dict[agg_type + '_' + direction + '_' + str(slice_length)] = x[-slice_length:].agg(agg_type)
feature_dict['max_to_min'] = x.max() / np.abs(x.min())
feature_dict['max_to_min_diff'] = x.max() - np.abs(x.min())
feature_dict['count_big'] = len(x[np.abs(x) > 500])
feature_dict['sum'] = x.sum()
feature_dict['mean_change_rate'] = calc_change_rate(x)
# calc_change_rate on slices of data
for slice_length, direction in product([1000, 10000, 50000], ['first', 'last']):
#for slice_length, direction in product([50000], ['first', 'last']):
if direction == 'first':
feature_dict['mean_change_rate_' + direction+ '_' + str(slice_length)] = calc_change_rate(x[:slice_length])
elif direction == 'last':
feature_dict['mean_change_rate_' + direction+ '_' + str(slice_length)] = calc_change_rate(x[-slice_length:])
# percentiles on original and absolute values
for p in percentiles:
feature_dict['percentile_' + str(p)] = np.percentile(x, p)
feature_dict['abs_percentile_' + str(p)] = np.percentile(np.abs(x), p)
feature_dict['trend'] = add_trend_feature(x)
feature_dict['abs_trend'] = add_trend_feature(x, abs_values=True)
feature_dict['mad'] = x.mad()
feature_dict['kurt'] = x.kurtosis()
feature_dict['skew'] = x.skew()
feature_dict['med'] = x.median()
feature_dict['Hilbert_mean'] = np.abs(hilbert(x)).mean()
for hw in hann_windows:
feature_dict['Hann_window_mean_' + str(hw)] = (convolve(x, hann(hw), mode='same') / sum(hann(hw))).mean()
feature_dict['classic_sta_lta1_mean'] = classic_sta_lta(x, 500, 10000).mean()
feature_dict['classic_sta_lta2_mean'] = classic_sta_lta(x, 5000, 100000).mean()
feature_dict['classic_sta_lta3_mean'] = classic_sta_lta(x, 3333, 6666).mean()
feature_dict['classic_sta_lta4_mean'] = classic_sta_lta(x, 10000, 25000).mean()
feature_dict['classic_sta_lta5_mean'] = classic_sta_lta(x, 50, 1000).mean()
feature_dict['classic_sta_lta6_mean'] = classic_sta_lta(x, 100, 5000).mean()
feature_dict['classic_sta_lta7_mean'] = classic_sta_lta(x, 333, 666).mean()
feature_dict['classic_sta_lta8_mean'] = classic_sta_lta(x, 4000, 10000).mean()
# exponential rolling statistics
ewma = pd.Series.ewm
for s in spans:
feature_dict['exp_Moving_average_'+ str(s) + '_mean'] = (ewma(x, span=s).mean(skipna=True)).mean(skipna=True)
feature_dict['exp_Moving_average_'+ str(s) + '_std'] = (ewma(x, span=s).mean(skipna=True)).std(skipna=True)
feature_dict['exp_Moving_std_' + str(s) + '_mean'] = (ewma(x, span=s).std(skipna=True)).mean(skipna=True)
feature_dict['exp_Moving_std_' + str(s) + '_std'] = (ewma(x, span=s).std(skipna=True)).std(skipna=True)
feature_dict['iqr'] = np.subtract(*np.percentile(x, [75, 25]))
feature_dict['iqr1'] = np.subtract(*np.percentile(x, [95, 5]))
feature_dict['ave10'] = stats.trim_mean(x, 0.1)
# tfresh features take too long to calculate, so I comment them for now
feature_dict['abs_energy'] = feature_calculators.abs_energy(x)
feature_dict['abs_sum_of_changes'] = feature_calculators.absolute_sum_of_changes(x)
feature_dict['count_above_mean'] = feature_calculators.count_above_mean(x)
feature_dict['count_below_mean'] = feature_calculators.count_below_mean(x)
feature_dict['mean_abs_change'] = feature_calculators.mean_abs_change(x)
feature_dict['mean_change'] = feature_calculators.mean_change(x)
feature_dict['var_larger_than_std_dev'] = feature_calculators.variance_larger_than_standard_deviation(x)
feature_dict['range_minf_m4000'] = feature_calculators.range_count(x, -np.inf, -4000)
feature_dict['range_p4000_pinf'] = feature_calculators.range_count(x, 4000, np.inf)
for i, j in zip(borders, borders[1:]):
feature_dict['range_'+ str(i) +'_' + str(j)] = feature_calculators.range_count(x, i, j)
feature_dict['ratio_unique_values'] = feature_calculators.ratio_value_number_to_time_series_length(x)
feature_dict['first_loc_min'] = feature_calculators.first_location_of_minimum(x)
feature_dict['first_loc_max'] = feature_calculators.first_location_of_maximum(x)
feature_dict['last_loc_min'] = feature_calculators.last_location_of_minimum(x)
feature_dict['last_loc_max'] = feature_calculators.last_location_of_maximum(x)
for lag in lags:
feature_dict['time_rev_asym_stat_'+str(lag)] = feature_calculators.time_reversal_asymmetry_statistic(x, lag)
for autocorr_lag in autocorr_lags:
feature_dict['autocorrelation_' + str(autocorr_lag)] = feature_calculators.autocorrelation(x, autocorr_lag)
feature_dict['c3_' + str(autocorr_lag)] = feature_calculators.c3(x, autocorr_lag)
for coeff, attr in product([1, 2, 3, 4, 5], ['real', 'imag', 'angle']):
feature_dict['fft_'+str(coeff)+'_'+attr] = list(feature_calculators.fft_coefficient(x, [{'coeff': coeff, 'attr': attr}]))[0][1]
feature_dict['long_strk_above_mean'] = feature_calculators.longest_strike_above_mean(x)
feature_dict['long_strk_below_mean'] = feature_calculators.longest_strike_below_mean(x)
feature_dict['cid_ce_0'] = feature_calculators.cid_ce(x, 0)
feature_dict['cid_ce_1'] = feature_calculators.cid_ce(x, 1)
for p in percentiles:
feature_dict['binned_entropy_'+str(p)] = feature_calculators.binned_entropy(x, p)
feature_dict['num_crossing_0'] = feature_calculators.number_crossing_m(x, 0)
for peak in peaks:
feature_dict['num_peaks_' + str(peak)] = feature_calculators.number_peaks(x, peak)
for c in coefs:
feature_dict['spkt_welch_density_' + str(c)] = list(feature_calculators.spkt_welch_density(x, [{'coeff': c}]))[0][1]
feature_dict['time_rev_asym_stat_' + str(c)] = feature_calculators.time_reversal_asymmetry_statistic(x, c)
# statistics on rolling windows of various sizes
for w in windows:
x_roll_std = x.rolling(w).std().dropna().values
x_roll_mean = x.rolling(w).mean().dropna().values
feature_dict['ave_roll_std_' + str(w)] = x_roll_std.mean()
feature_dict['std_roll_std_' + str(w)] = x_roll_std.std()
feature_dict['maxx_roll_std_' + str(w)] = x_roll_std.max()
feature_dict['min_roll_std_' + str(w)] = x_roll_std.min()
for p in percentiles:
feature_dict['percentile_roll_std_' + str(p)] = np.percentile(x_roll_std, p)
feature_dict['av_change_abs_roll_std_' + str(w)] = np.mean(np.diff(x_roll_std))
feature_dict['av_change_rate_roll_std_' + str(w)] = np.mean(np.nonzero((np.diff(x_roll_std) / x_roll_std[:-1]))[0])
feature_dict['abs_max_roll_std_' + str(w)] = np.abs(x_roll_std).max()
feature_dict['ave_roll_mean_' + str(w)] = x_roll_mean.mean()
feature_dict['std_roll_mean_' + str(w)] = x_roll_mean.std()
feature_dict['max_roll_mean_' + str(w)] = x_roll_mean.max()
feature_dict['min_roll_mean_' + str(w)] = x_roll_mean.min()
for p in percentiles:
feature_dict['percentile_roll_mean_' + str(p)] = np.percentile(x_roll_mean, p)
feature_dict['av_change_abs_roll_mean_' + str(w)] = np.mean(np.diff(x_roll_mean))
feature_dict['av_change_rate_roll_mean_' + str(w)] = np.mean(np.nonzero((np.diff(x_roll_mean) / x_roll_mean[:-1]))[0])
feature_dict['abs_max_roll_mean_' + str(w)] = np.abs(x_roll_mean).max()
return feature_dict
# as above
def get_features(x, y, seg_id):
x = pd.Series(x)
x_denoised = data_processing.high_pass_filter(x, low_cutoff=10000, SAMPLE_RATE=4000000)
x_denoised = data_processing.denoise_signal(x_denoised, wavelet='haar', level=1)
x_denoised = pd.Series(x_denoised)
zc = np.fft.fft(x)
realFFT = pd.Series(np.real(zc))
imagFFT = pd.Series(np.imag(zc))
zc_denoised = np.fft.fft(x_denoised)
realFFT_denoised = pd.Series(np.real(zc_denoised))
imagFFT_denoised = pd.Series(np.imag(zc_denoised))
main_dict = self.features(x, y, seg_id)
r_dict = self.features(realFFT, y, seg_id)
i_dict = self.features(imagFFT, y, seg_id)
main_dict_denoised = self.features(x_denoised, y, seg_id)
r_dict_denoised = self.features(realFFT_denoised, y, seg_id)
i_dict_denoised = self.features(imagFFT_denoised, y, seg_id)
for k, v in r_dict.items():
if k not in ['target', 'seg_id']:
main_dict['fftr_' + str(k)] = v
for k, v in i_dict.items():
if k not in ['target', 'seg_id']:
main_dict['ffti_' + str(k)] = v
for k, v in main_dict_denoised.items():
if k not in ['target', 'seg_id']:
main_dict['denoised_' + str(k)] = v
for k, v in r_dict_denoised.items():
if k not in ['target', 'seg_id']:
main_dict['denoised_fftr_' + str(k)] = v
for k, v in i_dict_denoised.items():
if k not in ['target', 'seg_id']:
main_dict['denoised_ffti_' + str(k)] = v
return main_dict
def delete_csv_space_bar(input_csv_path_name, output_csv_path_name):
"""delete all space bars in the input csv"""
csv_file = pd.read_csv(input_csv_path_name)
print(csv_file.head())
csv_file.dropna()
print(csv_file.head())
csv_file.to_csv(output_csv_path_name, index=False)
def feature_filter(features, feature_importance , threshold=30):
"""filter features by importance"""
returned_features = pd.DataFrame(index=features.index)
for i in range(len(features.columns)):
right_lines = feature_importance[feature_importance["feature"]==features.columns[i]]
if np.mean(right_lines.loc[:,'importance']) > threshold:
a = features[features.columns[i]]
returned_features = pd.concat([returned_features, features[features.columns[i]]], axis=1)
return returned_features
on_cloud = False
try:
import on_PC
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib.colors import LightSource
from matplotlib import cm
import matplotlib as mpl
class feature_saver:
def __init__(self, output_path, cmap='viridis', lu=256):
self.output_path = output_path
self.viridis = cm.get_cmap(cmap, lu)
def save_feature_as_2Dimage(self, data, min_threshold, max_threshold, label):
"""
This function is to show or save a colormap.
"""
fig, ax = plt.subplots(1, 1, figsize=(6, 3)) #Originally there has a parameter constrained_layout
#in the example, but it does work locally.
psm = ax.pcolormesh(data, cmap=self.viridis, rasterized=True, vmin=min_threshold, vmax=max_threshold)
fig.colorbar(psm, ax=ax)
#plt.show()
plt.savefig(self.output_path+str(label)+".jpg")
plt.clf()
import random
from example.commons import Faker
from pyecharts import options as opts
from pyecharts.charts import Bar3D
from pyecharts_snapshot.main import make_a_snapshot
class feature_saver_3D:
"""This is a class for saving features as a 3D colormap"""
def __init__(self, output_path, light_source=[0, 0], rstride=1, cstride=1,
linewidth=0, antialiased=False, shade=False):
self.output_path = output_path
self.ls = LightSource(light_source[0], light_source[0])
self.rstride = rstride
self.cstride = cstride
self.linewidth = linewidth
self.antialiased = False
self.shade = False
def save_feature_as_3Dimage(self, data_array, output_file_name):
"""
This function is to show or save a 3D colormap.
"""
column_len = int(np.sqrt(data_array.shape[0]))
y = column_len
x = data_array.shape[0]//y
if (data_array.shape[0]%y) != 0:
x += 1
x, y = np.meshgrid(np.arange(0, x, 1), np.arange(0, y, 1))
pad = np.zeros([x.shape[0]*x.shape[1]-data_array.shape[0]])
#random.seed(999)
#random.shuffle(data_array)
z = np.concatenate([data_array, pad])
z = np.reshape(z, x.shape)
x = np.reshape(x, [-1, 1])
y = np.reshape(y, [-1, 1])
z = np.reshape(z, [-1, 1])
data_xyz = np.concatenate([y, x, z], 1)
bar3d = Bar3D()
bar3d.add('', data_xyz, xaxis3d_opts=opts.Axis3DOpts(type_="value", min_=np.min(x), max_=np.max(x)),
yaxis3d_opts=opts.Axis3DOpts(type_="value", min_=np.min(y), max_=np.max(y)),
zaxis3d_opts=opts.Axis3DOpts(type_="value", min_=1))
bar3d.set_global_opts(visualmap_opts=opts.VisualMapOpts(max_=1),
title_opts=opts.TitleOpts(title="Bar3D-基本示例"))
bar3d.render()
make_a_snapshot('render.html', self.output_path+output_file_name)
"""
fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))
# To use a custom hillshading mode, override the built-in shading and pass
# in the rgb colors of the shaded surface calculated from "shade"
#norm = mpl.colors.Normalize(vmin=min_threshold, vmax=max_threshold)
#rgb = self.ls.shade(z, cmap=cm.get_cmap('gist_earth'), vert_exag=0.1, blend_mode='soft', norm=norm)
ax.plot_surface(x, y, z, facecolors=rgb, rstride=self.rstride, cstride=self.cstride,
linewidth=self.linewidth, antialiased=False, shade=False)
color_list = []
for i in range((x.shape[0]*x.shape[1]//5)+1):
color_list.extend(['r', 'g', 'm', 'y', 'k'])
color_list = color_list[:x.shape[0]*x.shape[1]]
ax.bar3d(x.ravel(), y.ravel(), 0, 0.5, 0.5, z.ravel(), zsort='average')#, color=color_list)
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])
'''
fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(x, y, z, rstride=0.01, cstride=0.01, cmap=cm.viridis)
'''
ax.view_init(elev=60, azim=240)
fig.savefig(self.output_path+output_file_name, dpi=200)
clip_image(self.output_path+output_file_name, self.output_path+output_file_name,
[320, 150], [960, 790])
plt.show()
fig.clf()
"""
def save_feature_as_images():
"""for testing"""
saver=feature_saver("D:/Backup/Documents/Visual Studio 2015/LANL-Earthquake-Prediction/master_data_graphs/")
for i in range(10000):
a, b = get_data_from_pieces(traning_csv_piece_path, csv_data_name, csv_time_name)
add = np.zeros([(388*388)-150000], int)
a = np.concatenate((a, add), axis=0)
a = a.reshape([388, 388])
saver.save_feature_as_image(a, -50, 50, b[-1])
def save_features_as_3Dimages(feature_csv, feature_importance, output_path, importance_threshold=2,
data_offset=1, data_multiple=1/100):
"""get features for DCNN"""
feature_csv = feature_filter(feature_csv, feature_importance, importance_threshold)
saver=feature_saver_3D(output_path)
for i in range(len(feature_csv)):
data = (feature_csv.iloc[i,:]+data_offset) * data_multiple
saver.save_feature_as_3Dimage(data, str(i)+'.jpg')
from skimage import io
def clip_image(input_path_name, output_path_name, output_first_corner, output_last_corner):
"""cut an image with the same center and a specified size ratio"""
img=io.imread(input_path_name)
img = img[output_first_corner[1]:output_last_corner[1], output_first_corner[0]:output_last_corner[0], :]
io.imsave(output_path_name, img)
except:
on_cloud = True
|
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 12 15:25:22 2018
@author: Anuj Rohilla
"""
#importing the required modules
import cv2
import numpy as np
#creating a blank screen
rect = np.zeros((300,300), dtype = "uint8")
#creating rectangle in the previously created blank screen
cv2.rectangle(rect, (25,25),(275,275), (255,255,255), -1)
#creating another blank screen
circle = np.zeros((300,300), dtype = "uint8")
#creating a cricle in the blank screen
cv2.circle(circle, (150,150), 150, (150,150,150),-1)
#Bitwise AND between circle and rect screen
bit_and = cv2.bitwise_and(circle, rect)
#displaying the ANDED image
cv2.imshow("Bitwise AND", bit_and)
#Bitwise AND between circle and rect screen
bit_or = cv2.bitwise_or(circle, rect)
#displaying the ORED image
cv2.imshow("Bitwise OR", bit_or)
#Bitwise AND between circle and rect screen
bit_xor = cv2.bitwise_xor(circle, rect)
#displaying the XORED image
cv2.imshow("Bitwise XOR", bit_xor)
#taking NOT of rect screen
bit_not = cv2.bitwise_not(rect)
#displaying the NOT image
cv2.imshow("Bitwise NOT", bit_not)
cv2.waitKey(0)
|
from types import List
class Solution:
def search(self, nums: List[int], target: int) -> int:
low = 0
high = len(nums) - 1
while low <= high:
middle = (low + high) // 2
if target == nums[middle]:
return middle
elif target < nums[middle]:
high = middle - 1
else:
low = middle + 1
return -1
|
"""
Contém as implementações de arquiteturas de CNN.
[LeNet5] - CNN inspirada na arquitetura de LeCun [1], com algumas
alterações nas funções de ativação, padding e pooling.
[1] http://yann.lecun.com/exdb/publis/pdf/lecun-01a.pdf
"""
# importar os pacotes necessários
from keras.models import Sequential
from keras.layers.core import Flatten
from keras.layers.core import Dense
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D
from keras.layers.core import Activation
class LeNet5(object):
"""
Arquitetura LeNet5 com pequenas alterações.
Com foco no reconhecimento de dígitos, esta CNN é composta
por uma sequência contendo os seguintes layers:
INPUT => CONV => POOL => CONV => POOL => FC => FC => OUTPUT
"""
@staticmethod
def build(width, height, channels, classes):
"""
Constroi uma CNN com arquitetura LeNet5.
:param width: Largura em pixel da imagem.
:param height: Altura em pixel da imagem.
:param channels: Quantidade de canais da imagem.
:param classes: Quantidade de classes para o output.
:return: Cnn do tipo LeNet5.
"""
inputShape = (height, width, channels)
model = Sequential()
model.add(Conv2D(6, (5, 5), padding="same",
input_shape=inputShape))
model.add(Activation("relu"))
model.add(MaxPooling2D((2,2)))
model.add(Conv2D(16, (5, 5)))
model.add(Activation("relu"))
model.add(MaxPooling2D((2,2)))
model.add(Flatten())
model.add(Dense(120))
model.add(Activation("relu"))
model.add(Dense(84))
model.add(Activation("relu"))
model.add(Dense(classes))
model.add(Activation("softmax"))
return model
|
# Taller 2
# Procesamiento de imagenes y visión
# Manuela Bravo Soto
# IMPORTACIONES
import numpy as np # Del módulo numpy
import cv2 # Del módulo opencv-python
import math # Del módulo math
#CLASE imageShape
class imageShape:
# CONSTRUCTOR
# Recibe como parámetros el ancho y el alto de la imagen
def __init__(self, width, height):
self.width = width # Se guarda el ancho de la imagen en self
self.height = height # Se guarda el ancho de la imagen en self
# Se crea una imagen negra cuyas dimensiones corresponden a las ingresadas por el usuario
# Si no se genera ninguna figura, la imagen es un fondo negro
self.shape = np.zeros((self.height, self.width), np.uint8)
self.name = 'Image' # Se crea el nombre de la imagen
# MÉTODO PARA GENERAR FIGURA
def generateShape(self):
# Se crea una imagen negra cuyas dimensiones corresponden a las ingresadas por el usuario
# Se vuelve a crear para generar una nueva imagen si se llama dos veces el método
self.shape = np.zeros((self.height, self.width), np.uint8)
self.shape = cv2.cvtColor(self.shape, cv2.COLOR_GRAY2BGR) # Se convierte la imagen del espacio de color gris al espacio de color BGR para generar la figura a color
self.rand = np.random.randint(0, 4, None) # Se genera un número aleatorio uniformemente distribuido entero que toma los valores desde 0 hasta 3
# Si el número aleatorio es 0 se obtiene un triángulo equilatero
if self.rand == 0:
self.lado = min(self.height, self.width)/2 # El lado de la figura será la mitad del mínimo entre las dimensiones del fondo
self.altura = math.sqrt((self.lado)**2-(self.lado/2)**2) # Se calcula la altura del triángulo con pitágoras
self.vert1 = (int(self.width/2 - self.lado/2), int(self.height/2 + self.altura/2)) # Se ubica el punto de la esquina inferior izquierda del triángulo en el plano para que esté centrado en el fondo de la imagen
self.vert2 = (int(self.width/2 + self.lado/2), int(self.height/2 + self.altura/2)) # Se ubica el punto de la esquina inferior derecha del triángulo en el plano para que esté centrado en el fondo de la imagen
self.vert3 = (int(self.width/2), int(self.height/2 - self.altura/2)) # Se ubica la punta del triángulo en el plano para que esté centrado en el fondo de la imagen
self.color = (255, 255, 0) # Se identifica el color cyan de la figura
self.triangle = np.array([self.vert1, self.vert2, self.vert3]) # Se crea un arreglo con los puntos de los vértices del triángulo
self.shape = cv2.drawContours(self.shape, [self.triangle], 0, self.color, -1) # Se dibujan los contornos sobre el fondo negro entre los puntos de los vértices del triángulo y se rellena la figura de color cyan
self.name = 'triangle' # Se le asigna el nombre de triángulo a la figura
# Si el número aleatorio es 1 se obtiene un cuadrado
elif self.rand == 1:
self.lado = min(self.height, self.width)/2 # El lado de la figura será la mitad del mínimo entre las dimensiones del fondo
self.startPoint = (int(self.width/2-self.lado/2), int(self.height/2-self.lado/2)) # Se obtienen las coordenadas de inicio del cuadrado para que esté centrado en el fondo de la imagen
self.endPoint = (int(self.width/2+self.lado/2), int(self.height/2+self.lado/2)) # Se obtienen las coordenadas de finalización del cuadrado para que esté centrado en el fondo de la imagen
self.color = (255, 255, 0) # Se identifica el color cyan de la figura
self.shape = cv2.rectangle(self.shape, self.startPoint, self.endPoint, self.color, -1) # Se dibuja un rectángulo sobre el fondo negro descrito entre las coordenadas de inicio y de fin, y se rellena la figura de color cyan
self.rotate = cv2.getRotationMatrix2D((self.width//2, self.height//2), 45, 1) # Se genera una matriz de rotación en 2D, que rota el punto central 45°
self.shape = cv2.warpAffine(self.shape, self.rotate, (self.width, self.height)) # A partir de la matriz de rotación, ee rota 45° el cuadrado generado sobre su punto central
self.name = 'square' # Se le asigna el nombre de cuadrado a la figura
# Si el número aleatorio es 2 se obtiene un rectangulo
elif self.rand == 2:
self.lado_horizontal = self.width/2 # El lado horizontal de la figura será la mitad del ancho del fondo
self.lado_vertical = self.height/2 # El lado vertical de la figura será la mitad del alto del fondo
self.startPoint = (int(self.lado_horizontal - self.lado_horizontal/2), int(self.lado_vertical - self.lado_vertical/2)) # Se obtienen las coordenadas de inicio del cuadrado para que esté centrado en el fondo de la imagen
self.endPoint = (int(self.lado_horizontal + self.lado_horizontal/2), int(self.lado_vertical + self.lado_vertical/2)) # Se obtienen las coordenadas de finalización del cuadrado para que esté centrado en el fondo de la imagen
self.color = (255, 255, 0) # Se identifica el color cyan de la figura
self.shape = cv2.rectangle(self.shape, self.startPoint, self.endPoint, self.color, -1) # Se dibuja un rectángulo sobre el fondo negro descrito entre las coordenadas de inicio y de fin, y se rellena la figura de color cyan
# Si la longitud ingresada por el usuario del ancho y alto del fondo son iguales, la figura generada será un cuadrado
if self.lado_horizontal == self.lado_vertical:
self.name = 'square' # Se le asigna el nombre de cuadrado a la figura
# De lo contrario, será un rectángulo
else:
self.name = 'rectangle' # Se le asigna el nombre de rectangulo a la figura
# Si el número aleatorio es 3 se obtiene un circulo
elif self.rand == 3:
self.center = (int(self.width/2), int(self.height/2)) # El punto central del circulo será la mitad de las dimensiones del fondo
self.radius = int(min(self.width, self.height)/4) # El radio del circulo será la cuarta parte del mínimo entre las dimensiones del fondo
self.color = (255, 255, 0) # Se identifica el color cyan de la figura
self.shape = cv2.circle(self.shape, self.center, self.radius, self.color, -1) # Se dibuja un circulo sobre el fondo negro en el punto central con el radio calculado, y se rellena la figura de color cyan
self.name = 'circle' # Se le asigna el nombre de circulo a la figura
# MÉTODO QUE MUESTRA LA FIGURA POR 5 SEGUNDOS
# Si no se generó ninguna figura, muestra el fondo negro generado en el constructor con el nombre de 'Image'
def showShape(self):
cv2.imshow(self.name, self.shape) # Mostrar la imagen con el nombre de la imagen correspondiente
cv2.waitKey(5000) # Mostrar en pantalla la imagen por 5 segundos
# MÉTODO QUE RETORNA LA IMAGEN GENERADA Y EL NOMBRE
def getShape(self):
return self.shape, self.name
# MÉTODO QUE CLASIFICA LA FIGURA GENERADA
def whatShape(self):
self.shape_gray = cv2.cvtColor(self.shape, cv2.COLOR_BGR2GRAY) # Se convierte la imagen del espacio de color BGR al espacio de color gris
self.ret, self.shape_threshold = cv2.threshold(self.shape_gray, 150, 255, cv2.THRESH_BINARY) # Se binariza la imagen utilizando un umbral de 150
self.shape_threshold_not = cv2.bitwise_not(self.shape_threshold) # Se realiza un NOT lógico a la imagen binarizada
self.contours, self.hierarchy = cv2.findContours(self.shape_threshold_not, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) # Se encuentran los contornos de la imagen binarizada luego de aplicar el NOT lógico
# Para cada contorno se aproxima el polígono y se dibuja dicho contorno sobre la imagen BGR
for self.idx in self.contours:
self.shape_approx = cv2.approxPolyDP(self.idx, 0.01*cv2.arcLength(self.idx, True), True) # Se aproxima cada contorno al perímetro del polígono para obtener los vértices de la figura de contorno cerrado
# Si la cantidad de vértices es 3, se clasifica como un triángulo
if len(self.shape_approx) == 3:
return 'triangle' # Retorna un string con el nombre de tipo de figura resultante
# Si la cantidad de vértices es 4, se clasifica como un rectangulo o un cuadrado
elif len(self.shape_approx) == 4:
self.horizontal = self.shape_approx[2][0][0]-self.shape_approx[3][0][0] # Se calcula la longitud del lado horizontal de la figura
self.vertical = self.shape_approx[3][0][1]-self.shape_approx[0][0][1] # Se calcula la longitud del lado vertical de la figura
# Si el lado vertical y horizontal de la figura son diferentes en su longitud, la figura se clasifica como un rectangulo
if self.horizontal != self.vertical:
return 'rectangle' # Retorna un string con el nombre de tipo de figura resultante
# De lo contrario, la figura se clasifica como un cuarado
else:
return 'square' # Retorna un string con el nombre de tipo de figura resultante
# Si la cantidad de vértices es mayor a 4, se clasifica como un circulo
elif len(self.shape_approx) > 4:
return 'circle' # Retorna un string con el nombre de tipo de figura resultante
|
import sys
import math
def quicksort_count_first(seq):
def sort(seq, begin, end):
if begin >= end:
return 0
p, m = begin, begin
for i in range(begin+1, end):
if seq[i] < seq[p]:
seq[i], seq[m+1] = seq[m+1], seq[i]
m += 1
seq[m], seq[p] = seq[p], seq[m]
left = sort(seq, begin, m)
right = sort(seq, m+1, end)
return end - begin - 1 + left + right
return sort(seq, 0, len(seq))
def quicksort_count_final(seq):
def sort(seq, begin, end):
if begin >= end:
return 0
seq[begin], seq[end-1] = seq[end-1], seq[begin]
p, m = begin, begin
for i in range(begin+1, end):
if seq[i] < seq[p]:
seq[i], seq[m+1] = seq[m+1], seq[i]
m += 1
seq[m], seq[p] = seq[p], seq[m]
left = sort(seq, begin, m)
right = sort(seq, m+1, end)
return end - begin - 1 + left + right
return sort(seq, 0, len(seq))
def quicksort_count_median(seq):
def median(seq, begin, end):
length = end - begin
middle = begin + (length + 1) / 2 - 1
values_by_index = {seq[begin]: begin, seq[middle]: middle, seq[end-1]: end-1}
sor = sorted(values_by_index.keys())
return values_by_index[sor[1]]
def sort(seq, begin, end):
if begin >= end - 1:
return 0
p = median(seq, begin, end)
seq[begin], seq[p] = seq[p], seq[begin]
p, m = begin, begin
for i in range(begin+1, end):
if seq[i] < seq[p]:
seq[i], seq[m+1] = seq[m+1], seq[i]
m += 1
seq[m], seq[p] = seq[p], seq[m]
left = sort(seq, begin, m)
right = sort(seq, m+1, end)
return end - begin - 1 + left + right
return sort(seq, 0, len(seq))
if __name__ == '__main__':
with open(sys.argv[1]) as input_file:
numbers = [int(number) for number in input_file.readlines()]
print 'comparisons when pivot is first number: {}'.format(
quicksort_count_first(numbers[:]))
print 'comparisons when pivot is first number: {}'.format(
quicksort_count_final(numbers[:]))
print 'comparisons when pivot is median number: {}'.format(
quicksort_count_median(numbers[:]))
|
def merge_sort(seq):
if len(seq) < 2:
return seq
middle = len(seq) / 2
left = merge_sort(seq[:middle])
right = merge_sort(seq[middle:])
i, l, r = 0, 0, 0
while l < len(left) and r < len(right):
if left[l] < right[r]:
seq[i] = left[l]
l += 1
else:
seq[i] = right[r]
r += 1
i += 1
while l < len(left):
seq[i] = left[l]
l += 1
i += 1
while r < len(right):
seq[i] = right[r]
r += 1
i += 1
return seq
|
import matplotlib.pyplot as plt
# The slices will be ordered and plotted counter-clockwise.
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
explode = (0, 0, 0, 0) # explode a slice if required
plt.pie(sizes, explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True)
#draw a circle at the center of pie to make it look like a donut
centre_circle = plt.Circle((0,0),0.75,color='black', fc='white',linewidth=1.25)
fig = plt.gcf()
fig.gca().add_artist(centre_circle)
# Set aspect ratio to be equal so that pie is drawn as a circle.
plt.axis('equal')
plt.show()
|
'''
Реализовать функцию, принимающую несколько параметров, описывающих данные пользователя: имя, фамилия, год рождения,
город проживания, email, телефон. Функция должна принимать параметры как именованные аргументы.
Реализовать вывод данных о пользователе одной строкой
'''
def user_description(name, surname, birthday='', city='', email='', phone=''):
return f'New user: {name} {surname}, birthday:{birthday}, city:{city}, email:{email}, phone:{phone}'
name = input('input name: ')
surname = input('input surname: ')
birthday = input('input birthday: ')
city = input('input city: ')
email = input('input email: ')
phone = input('input phone: ')
print(user_description(name=name, surname = surname, birthday = birthday, email = email, city = city, phone = phone))
|
from random import randint
# BankAccount class creation
class BankAccount:
# BankAccount instance variables
def __init__(self, full_name, account_number, routing_number, balance):
self.full_name = full_name
self.account_number = account_number
self.routing_number = routing_number
self.balance = 0
# ------------------ Methods ------------------
def deposit(self, amount):
"""Deposit user-defined amount"""
print(f"Current balance: ${self.balance}")
self.balance += amount
print(f"Amount Deposited: ${amount}")
self.balance -= atmUsageFee
print(f"ATM fee: ${atmUsageFee}")
print(f"New balance: ${self.balance}")
print("\n")
return self.balance
def withdraw(self, amount):
"""Withdraw user-defined amount or subtract $10 on overdraft"""
print(f"Current balance: ${self.balance}")
if amount > self.balance:
self.balance -= 10
print(f"Insufficient funds to withdraw ${amount}")
print(f"Overcharge fee: $10")
print(f"New balance: ${self.balance}")
print("\n")
else:
self.balance -= amount
print(f"Amount Withdrawn: ${amount}")
self.balance -= atmUsageFee
print(f"ATM fee: ${atmUsageFee}")
print(f"New Balance: ${self.balance}")
print("\n")
def get_balance(self):
"""Returns user's current balance"""
print(f"You currently have an account balance of: ${self.balance}")
print("\n")
return self.balance
def add_interest(self):
"""Adds 1 month's interest to user's balance, calculated from current balance at rate of 0.00083"""
print(f"Current balance: ${self.balance}")
interest = self.balance * 0.00083
self.balance += round(interest, 2)
print(f"Interest: ${round(interest, 2)}")
print(f"New balance: ${self.balance}")
print("\n")
def print_receipt(self):
"""Print's user's account information, censors first 4 digits of acc. number"""
account_num_to_string = str(self.account_number)
print(f"Account Holder: {self.full_name}")
print(f"Account number: ****{account_num_to_string[-4:]}")
print(f"Routing number: {self.routing_number}")
print(f"Balance: ${self.balance}")
print("\n")
# Called to create an 8 digit account number
def createAccNum():
"""8 digit account number generator"""
acc_num = ""
for i in range(8):
acc_num += str(randint(0, 9))
return int(acc_num)
# ------------------ ATM Functions ------------------
# Deposit function for atmOptions
def deposit():
"""Selects from list of known users and runs deposit method"""
while True:
user = input("Input name: ")
acc_num = int(input("Input account number: "))
if user == Tom.full_name and acc_num == Tom.account_number:
print("\n")
Tom.deposit(
float(input(f"Hello {Tom.full_name}. Input deposit amount: $")))
break
elif user == Bob.full_name and acc_num == Bob.account_number:
print("\n")
Bob.deposit(
float(input(f"Hello {Bob.full_name}. Input deposit amount: $")))
break
elif user == Hubert.full_name and acc_num == Hubert.account_number:
print("\n")
Hubert.deposit(
float(input(f"Hello {Hubert.full_name}. Input deposit amount: $")))
break
else:
print("\n")
print("No matching user found")
continue
print("Exiting ATM")
# Withdraw function for atmOptions
def withdraw():
"""Selects from list of known users and runs withdrawal method"""
while True:
user = input("Input name: ")
acc_num = int(input("Input account number: "))
if user == Tom.full_name and acc_num == Tom.account_number:
print("\n")
Tom.withdraw(
float(input(f"Hello {Tom.full_name}. Input withdrawal amount: $")))
break
elif user == Bob.full_name and acc_num == Bob.account_number:
print("\n")
Bob.withdraw(
float(input(f"Hello {Bob.full_name}. Input withdrawal amount: $")))
break
elif user == Hubert.full_name and acc_num == Hubert.account_number:
print("\n")
Hubert.withdraw(
float(input(f"Hello {Hubert.full_name}. Input withdrawal amount: $")))
break
else:
print("\n")
print("No matching user found")
continue
print("Exiting ATM")
# Balance function for atmOptions
def balance():
"""Selects from list of known users and runs get_balance method"""
while True:
user = input("Input name: ")
acc_num = int(input("Input account number: "))
if user == Tom.full_name and acc_num == Tom.account_number:
print("\n")
Tom.get_balance()
break
elif user == Bob.full_name and acc_num == Bob.account_number:
print("\n")
Bob.get_balance()
break
elif user == Hubert.full_name and acc_num == Hubert.account_number:
print("\n")
Hubert.get_balance()
break
else:
print("\n")
print("No matching user found")
continue
print("Exiting ATM")
# Account details function for atmOptions
def accDetails():
"""Selects from list of known users and runs get_balance method"""
while True:
user = input("Input name: ")
acc_num = int(input("Input account number: "))
if user == Tom.full_name and acc_num == Tom.account_number:
print("\n")
Tom.print_receipt()
break
elif user == Bob.full_name and acc_num == Bob.account_number:
print("\n")
Bob.print_receipt()
break
elif user == Hubert.full_name and acc_num == Hubert.account_number:
print("\n")
Hubert.print_receipt()
break
else:
print("\n")
print("No matching user found")
continue
print("Exiting ATM")
# Decides which function to call on the input account
def atmOptions():
while True:
option_selected = int(input(
"Enter an option\n\n1) Deposit\n2) Withdraw\n3) Current Balance\n4) Account Details\n\nOption selected: "))
if option_selected == 1:
print("Deposit selected")
print("--------------------\n")
deposit()
break
elif option_selected == 2:
print("Withdrawal selected")
print("--------------------\n")
withdraw()
break
elif option_selected == 3:
print("Current Balance selected")
print("--------------------\n")
balance()
break
elif option_selected == 4:
print("Account details selected")
print("--------------------\n")
accDetails()
break
else:
print("Invalid option")
print("--------------------\n")
continue
# ------------------ Testing methods ------------------
# Initialize 3 users with predefined BankAccount variables
Tom = BankAccount("Tom Hanks", createAccNum(), 1111111111, 0)
Bob = BankAccount("Bob Ross", createAccNum(), 22222222, 0)
Hubert = BankAccount("Hubert Blaine Wolfeschlegelsteinhausenbergerdorffvoralternwarengewissenhaftschaferswessenschaftswarenwohlgefutternundsorgfaltigkeitbeschutzenvorangreifendurchihrraubgierigfiends Sr.", createAccNum(), 33333333, 0)
atmUsageFee = 2
# Give each account a starting balance so test methods and functions can be called
Tom.balance = 100
Bob.balance = 200
Hubert.balance = 300
# Experimenting below with try/except in below method calls. I am aware of the poor implementation.
#Tom method calls
# try:
# Tom.deposit(float(input(f"Hello {Tom.full_name}. Input deposit amount: $")))
# Tom.withdraw(float(input(f"Hello {Tom.full_name}. Input withdrawal amount: $")))
# Tom.get_balance()
# Tom.add_interest()
# Tom.print_receipt()
# except ValueError:
# print("Invalid input")
# # Bob method calls
# try:
# Bob.deposit(float(input(f"Hello {Bob.full_name}. Input deposit amount: $")))
# Bob.withdraw(float(input(f"Hello {Bob.full_name}. Input withdrawal amount: $")))
# Bob.get_balance()
# Bob.add_interest()
# Bob.print_receipt()
# except ValueError:
# print("Invalid input")
# # Hubert method calls
# try:
# Hubert.deposit(float(input(f"Hello {Hubert.full_name}. Input deposit amount: $")))
# Hubert.withdraw(float(input(f"Hello {Hubert.full_name}. Input withdrawal amount: $")))
# Hubert.get_balance()
# Hubert.add_interest()
# Hubert.print_receipt()
# except ValueError:
# print("Invalid input")
# Run ATM simulation - uncomment to use
print(Tom.account_number)
atmOptions()
|
# crop_by_percent_value.py
import os
from PIL import Image
import argparse
# TODO: 4.2 centre square/rectangle crop by user-determined percentage (crop to 50%/70%) crp_p
def crop_by_percent(w_percent, h_percent, source, destination=''):
"""
crop the image by given pixels precentage
usage: crop_by_percent_value.py [-w --wdth] [-h --hgth] [-s --src] [-d --dest] [-h --help]
# Inputs:
w_pixel : percent of width, images width will be cropped
h_pixel : pecent of height, images height will be cropped
source : path to the folder containing images
destination : path to the folder to place resize images
# Functionality :
Takes all images in the given source and crop as per given perecent
values of width and height
for example, the image is of size 100 X 100 and pixel values are w_pixel = 10%
and h_pixel = 20%, new size of the image will be 90 X 80 cropped from center
"""
# Validations
if source == None or source == '':
raise ValueError(f"Invalid Source")
if not isinstance(source, str):
raise TypeError(f"Invalid Source {source}")
if not isinstance(w_percent, int):
raise TypeError(f"Invalid width % value {w_percent}")
if not isinstance(h_percent, int):
raise TypeError(f"Invalid height % value {h_percent}")
if not os.path.isdir(source):
raise ValueError(f"Source {source} has to be folder path")
if (destination == '' or destination == None) and os.path.isdir(source): # source and destination are same folders
destination = source
if not os.path.isdir(destination):
raise ValueError(f"Destination {destination} in not a folder path")
if w_percent <= 0 or w_percent>=100:
raise ValueError(f"Width percentage value should be greater than 0 and less than 100")
if h_percent <= 0 or h_percent>=100:
raise ValueError(f"Height percentage value should be greater than 0 and less than 100")
cropped_files = []
failed_files = []
filenames = os.listdir(source)
for fl in filenames:
file, extension = os.path.splitext(fl)
if extension not in {'.png','.jpeg','.jpg'}: # Check for image files in folder
print(f"Can't crop {fl}")
failed_files.append(fl)
continue
try:
img = Image.open(os.path.join(source, fl))
w, h = img.size # Get size of image
w_pixel = int(w*w_percent/100)
h_pixel = int(h*h_percent/100)
# Setting the points for cropped image
left = int(w/2 - w_pixel/2)
top = int(h/2 - h_pixel/2)
right = int(left + w_pixel)
bottom = int(top + h_pixel)
# Cropped image of above dimension
# (It will not change orginal image)
img = img.crop((left, top, right, bottom))
img.save(os.path.join(destination, fl))
img.close()
cropped_files.append(fl)
print(f'Image {fl} cropped successfully')
except OSError:
print(f'Cannot resize image')
# For permission related errors
except PermissionError:
print("Operation not permitted.")
if len(failed_files) == len(filenames):
print(f'no files to resize')
return True
elif len(cropped_files) > 0:
return True
else:
return False
if __name__ == '__main__':
print(f'Loading from command line crop_by_percent_value.py: __name__ = {__name__}')
# get code, source, destination, recentage from arguments
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-w', '--width', type= int, help='Enter the % value of width to be center cropped')
parser.add_argument('-ht', '--height', type= int, help='Enter the % value of height to be center cropped')
parser.add_argument('-s', '--src', type= str, help='Enter the absolute path of input folder')
parser.add_argument('-d', '--dest', type= str, help='Enter the absolute path of output folder')
args = parser.parse_args()
if args.src is not None and args.width is not None and args.height is not None:
crop_by_percent(w_percent = args.width, h_percent = args.height, source = args.src, destination = args.dest)
else:
print('Invalid arguments passed, please check help')
else:
print(f'Loading crop_by_percent_value.py: __name__ = {__name__}')
|
# I want to see if i can make a multi input chatbot with the small knowledge that i have.
def chat_bot1():
print("Hello and welcome")
response_1 = input("How are you?")
if response_1 == "Fine":
print("That is great")
print("What are you doing today?")
response_2 = input("Are you working?")
if response_2 == "Yes":
print("Ok")
elif response_2 == "No":
print("Ok let us talk")
elif response_1 == "Not bad":
print("Ok that is good")
else:
print("Please respomd with either fine or Not bad")
print("Hello and welcome to our prototype chat bot, valid respones are Fine, Not bad, Yes, and No. please try to keep your responses with in this capitalization")
chat_bot1()
|
class Solution(object):
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
cd = {} # Dictionary to track history of number seen in same column
grid = {} # Dictionary to track history of number seen in same grid
cur_grid = -1
for k in range(1,10): # Value of these dictionaries will be list for each column/grid position from 1 to 9
cd[str(k)] = []
grid[k] = []
for r in range(len(board)):
rd = {} # Dictionary to track history of number seen in same row
for c in range(len(board[0])):
n = board[r][c]
# Determine correct grid number we are in
if r<3:
if c<3: cur_grid = 1
elif c<6: cur_grid = 2
else: cur_grid = 3
elif r<6:
if c<3: cur_grid = 4
elif c<6: cur_grid = 5
else: cur_grid = 6
else:
if c<3: cur_grid = 7
elif c<6: cur_grid = 8
else: cur_grid = 9
if n!=".":
if n in rd or c in cd[n] or n in grid[cur_grid]: # If number was seen in same row or column or grid, then its not valid sudoku
return False
rd[n] = 1 # Update number was seen in current row
cd[n].append(c) # Update number was seen in current column
grid[cur_grid].append(n) # Update number was seen in current grid
return True
|
# Recursive implementation
class Solution(object):
def combo(self, n, ans, s=0, c=0, p=""):
if c==n: # All starting parantheses have been closed with equal numbers of valid closing parantheses for current permutation
ans.append(p) # Append latest calulated permutation to final answer list
return
if s<n: # New starting parantheses can be added to start permutation
self.combo(n, ans, s+1, c, p+"(")
if c<s: # New closing parantheses can be added to catch up with starting parantheses count
self.combo(n, ans, s, c+1, p+")")
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
ans = []
self.combo(n, ans)
return ans
|
l = list()
n = int(input())
def function(l, n):
l = [i for i in range(n) if i % 3 == 0 or i % 5 == 0]
return sum(l)
print(function(l, n))
|
"""
647. Palindromic Substrings
Medium
Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different substrings even they consist of
same characters.
Example 1:
Input: "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".
Example 2:
Input: "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
Note:
The input string length won't exceed 1000.
"""
class Solution:
def countSubstrings(self, s):
# 状态定义:dp[i][j] i->j的字符串是否是回文串
# 状态转移:dp[i][j]={if i==j:True, if j<i:不管 if i<j:{if s[i] != s[j]:False,否则:
# if j-i<= 2 or dp[i+1][j-1]=True}}
N = len(s)
count = 0
dp = [[False for _ in range(N)] for _ in range(N)]
for i in range(N,-1,-1):
for j in range(i,N):
if i == j or (s[i] == s[j] and (j-i<=2 or dp[i+1][j-1]==True)):
dp[i][j] = True
count += 1
return count
|
"""
740. Delete and Earn
Medium
Given an array nums of integers, you can perform operations on the array.
In each operation, you pick any nums[i] and delete it to earn nums[i] points. After, you must delete every element
equal to nums[i] - 1 or nums[i] + 1.
You start with 0 points. Return the maximum number of points you can earn by applying such operations.
Example 1:
Input: nums = [3, 4, 2]
Output: 6
Explanation:
Delete 4 to earn 4 points, consequently 3 is also deleted.
Then, delete 2 to earn 2 points. 6 total points are earned.
Example 2:
Input: nums = [2, 2, 3, 3, 3, 4]
Output: 9
Explanation:
Delete 3 to earn 3 points, deleting both 2's and the 4.
Then, delete 3 again to earn 3 points, and 3 again to earn 3 points.
9 total points are earned.
Note:
The length of nums is at most 20000.
Each element nums[i] is an integer in the range [1, 10000].
"""
class Solution:
def deleteAndEarn(self, nums):
N = max(nums)
# 对于数字重复出现的情况,设置一个字典记录删除该数能得多少分
num_count = [0] * (N+1)
for num in nums:
num_count[num] += num
# dp[i][j] i表示当前的元素 j表示删除该元素1(得分) 或者 被别相邻的元素删除0(不得分)
dp = [[0 for _ in range(2)] for _ in range(N+1)]
for i in range(1,N+1):
# 当前不得分,可能前一个得分,也可能不得分,选最大
dp[i][0] = max(dp[i-1][0], dp[i-1][1])
# 当前得分,前一个必不得分
dp[i][1] = dp[i-1][0]+num_count[i]
return max(dp[N][0], dp[N][1])
s = Solution()
print(s.deleteAndEarn([2, 2, 3, 3, 3, 4]))
|
import re
def check(filename, empty_sep_mode):
"""
Ensures the numbering and title are separated from each other with a dash and not with a dot or not separated at all.
This assumes numbering is already done, as numbering handler is called before this.
Setting empty_sep_mode to True makes separators be no characters.
"""
if not empty_sep_mode:
if check_correct_dash(filename):
return filename
else:
if check_correct_empty(filename):
return filename
new_filename = filename
new_filename = check_dash(new_filename, empty_sep_mode)
new_filename = check_empty(new_filename, empty_sep_mode)
new_filename = check_dot(new_filename, empty_sep_mode)
new_filename = check_space(new_filename, empty_sep_mode)
if new_filename == filename:
print("Separator isn't valid, but no action could be done.")
print("Do you want to give the file a new name manually?")
response = input("(Y/N) > ")
if response.lower() == "y":
print("Enter new filename, EXCLUDING extension!")
print("If the song has any features, you don't need to fix them.")
new_filename = input("Enter new filename, EXCLUDING extension >")
elif response.lower() == "n":
print("Skipping separator check for this file.")
return new_filename
dash_pattern = re.compile(r"\d\d - .*")
empty_pattern = re.compile(r"^(\d\d[^\d. -].*)|(\d\d \d.*)$")
dot_pattern = re.compile(r"\d\d\. .*")
space_pattern = re.compile(r"\d\d [^-]+")
# checks if separator is correct already
def check_correct_dash(filename):
# check if it already uses dash separators, if so then end function
if dash_pattern.match(filename):
print("Separator is valid")
return True
return False
def make_empty_sep(trackno, trackname):
return trackno + (" " if (trackname[0].isdigit()) else "") + trackname
def make_dash_sep(trackno, trackname):
trackno + " - " + trackname
def check_dash(filename, empty_sep_mode):
if empty_sep_mode and dash_pattern.match(filename):
print("Separator is a dash, replacing with an empty separator")
trackno = filename[0:2]
trackname: str = filename[5:]
return make_empty_sep(trackno, trackname)
return filename
def check_correct_empty(filename):
if empty_pattern.match(filename):
print("Separator is valid")
return True
return False
# "12Name.flac" or "12 22.flac"
def check_empty(filename: str, empty_sep_mode):
if not empty_sep_mode and empty_pattern.match(filename):
print("Empty separator, replacing with a dash")
trackno = filename[0:2]
trackname = filename[2:].lstrip()
return trackno + " - " + trackname
return filename
# check if filename uses dots (i.e. "12. Title.flac")
def check_dot(filename, empty_sep_mode):
if dot_pattern.match(filename):
print("Separator is a dot")
trackno = filename[0:2]
trackname = filename[4:]
return make_dash_sep(trackno, trackname) if not empty_sep_mode else make_empty_sep(trackno, trackname)
return filename
# check if filename uses a single space
def check_space(filename, empty_sep_mode):
if space_pattern.match(filename):
print("Single space separator")
trackno = filename[0:2]
trackname = filename[3:]
return make_dash_sep(trackno, trackname) if not empty_sep_mode else make_empty_sep(trackno, trackname)
return filename
|
import numpy as np
def letter_to_vector(character):
if ord(character) < 97 or ord(character) > 122:
raise Exception('Must be ascii lowercase letter')
vector_matrix = np.eye(26)
index = ord(character) - 97
vector = vector_matrix[index]
return np.array(vector)
def vector_to_letter(vector):
index = int(np.argmax(vector))
return chr(ord('a') + index)
if __name__ == '__main__':
print(type(letter_to_vector('b')))
print(vector_to_letter(letter_to_vector('a')))
|
#!/usr/bin/python
from math import sqrt,fmod
def multipliers(number):
s = int(sqrt(number))
r = []
for a in xrange(2,s+1):
while fmod(number,a) == 0:
r.append(a)
number = number / a
return r
def equation(a, b, c):
r = []
d = b**2-4*a*c
if d>0:
r.append((-b+sqrt(d))/(2*a))
r.append((-b-sqrt(d))/(2*a))
elif d == 0:
r.append(-b/2*a)
return r
def simple(number):
s = int(sqrt(number))
for a in xrange(2,s+1):
if fmod(number,a) == 0:
return "No"
return "Yes"
# atm uses only 100, 50, 20, 10, 5 and 1 notes.
def atm(summ):
banknot = {100:0, 50:0, 20:0, 10:0, 5:0, 1:0}
keys = banknot.keys()
keys.sort()
keys.reverse()
for key in keys:
count = 0
while summ>=key:
summ -= key
count += 1
banknot[key] = count
b_str = ''
for key in keys:
b_str += str(key) + ' => ' + str(banknot[key]) + '\n'
return b_str
print multipliers(30030)
print equation(2, 19, 35) # 2x^2 + 19x + 35 = 0
print simple(11)
print atm(287)
|
#1. Create a greeting for your program.
print("Welcome to the band name generator.")
#2. Ask the user for the city that they grew up in.
city = input("Which city did your grow up in?")
print(city)
#3. Ask the user for the name of a pet.
pet = input("What is the name of a pet?")
#4. Combine the name of their city and pet and show their band name.
print(" Your band name could be " + city +"" + pet)
|
# coding=utf-8
import sys
import time
import warnings
import drawing as dr
# Constants
# Константы
accuracy = 0.1 ** 20
# Coefficients of a polynomial
# Коэффициенты полинома
coefficients = [1, 3, -24, 10, 13]
# The polynomial at the point
# Полином в точке
def f(point, a=coefficients):
result = 0
power = len(a)
for n in range(0, power):
result += a[n] * point ** (power - n - 1)
return result
# Разностное уравнение (из полинома выражаем х в максимальной степени)
# При каждом вызове нужно сместить коэффициенты приближения
# TODO Rename
def x_max_degree(_coefficients, _approximation):
# print(_approximation)
# print(_coefficients)
result = 0
length = len(_approximation)
for n in range(length):
# print(n)
result += _approximation[n] * _coefficients[n + 1]
return -result / _coefficients[0]
# принимает: начальное приближение, коэффициенты, номер итерации
# возращает: корень и количество итераций, за которое он найден
def bernoulli_approximation(_coefficients, _approximation, _iteration):
# print(_coefficients)
# print(_approximation)
# print(_iteration)
x_last = x_max_degree(_coefficients, _approximation)
max_root = x_last / _approximation[0]
print(max_root)
print(f(max_root))
print(max_root)
if abs(f(max_root)) <= accuracy:
return max_root, _iteration
else:
_approximation = [x_last] + _approximation[:-1]
return bernoulli_approximation(_coefficients, _approximation, _iteration + 1)
# принимает: коэффициенты полинома, корень
# возращает: новые коэффициенты полинома
def gornor_schema(_coefficients, root):
new_coefficients = [_coefficients[0]]
length = len(_coefficients) - 2
for n in range(length):
new_coefficients.append(root * new_coefficients[n] + _coefficients[n + 1])
return new_coefficients
# 2 steps: 1) approximation of max|root| 2) creation new polynomial coefficients
# принимает: начальное приближение, коэффициенты
def bernoulli_method_interface(_coefficients, _approximation):
# print(_coefficients)
# print(_approximation)
roots = []
iterations = []
length = len(_approximation)
for k in range(length):
# 1) approximation of max|root|
temp = bernoulli_approximation(_coefficients, _approximation, 0)
print()
print(temp)
print()
roots.append(temp[0])
iterations.append(temp[1])
# 2) creation new polynomial coefficients
_coefficients = gornor_schema(_coefficients, temp[0])
_approximation.remove(_approximation[0]) # delete one approximation
return roots, iterations
if __name__ == "__main__":
dr.build_function(f,
coefficients,
"Первая функция системы",
)
dr.show_plot()
print(bernoulli_method_interface(coefficients, [2, 2, 2, 2]))
# mpl.bar_chart(
# [20, 35, 30, 35, 27],
# ["Бернулли", "test 2", "test 3", "test 4", "test 5"],
# "Производительность",
# "Методы",
# "Миллисекунды",
# graph_params=[0, 51, 5]
# )
# start = time.time()
# end = time.time()
# print('{:f}'.format(end - start))
|
def urlify(char_list, str_length):
num_of_spaces = 0
for i in range(str_length):
if char_list[i] == ' ':
num_of_spaces += 1
total_length = str_length + num_of_spaces * 2
for i in range(str_length-1, -1, -1):
total_length -= 1
if char_list[i] == ' ':
char_list[total_length] = '0'
char_list[total_length - 1] = '2'
char_list[total_length - 2] = '%'
total_length -= 2
else:
char_list[total_length] = char_list[i]
return char_list
def validate_urlify(string, true_length):
# RHS of the comparison is the easiest and probably the pythonic way to do this problem
# Implemented urlify just to do it in place as thats what the author expects us to understand
return ''.join(urlify(list(string), true_length)) == test.strip().replace(' ', '%20')
if __name__ == '__main__':
test = 'saran sas tt '
assert validate_urlify(test, 12)
test = 'saran'
assert validate_urlify(test, 5)
|
import numpy as np
from random import shuffle
import scipy.sparse
def softmax_loss_naive(theta, X, y, reg):
"""
Softmax loss function, naive implementation (with loops)
Inputs:
- theta: d x K parameter matrix. Each column is a coefficient vector for class k
- X: m x d array of data. Data are d-dimensional rows.
- y: 1-dimensional array of length m with labels 0...K-1, for K classes
- reg: (float) regularization strength
Returns:
a tuple of:
- loss as single float
- gradient with respect to parameter matrix theta, an array of same size as theta
"""
# Initialize the loss and gradient to zero.
J = 0.0
grad = np.zeros_like(theta)
m, dim = X.shape
#############################################################################
# TODO: Compute the softmax loss and its gradient using explicit loops. #
# Store the loss in J and the gradient in grad. If you are not #
# careful here, it is easy to run into numeric instability. Don't forget #
# the regularization term! #
#############################################################################
for i in xrange(m):
for k in xrange(theta.shape[1]):
temp = theta.T.dot(X[i])
maxVal = temp[np.argmax(temp)]
P = np.exp(theta[:, k].T.dot(X[i]) - maxVal) / np.sum(np.exp(theta.T.dot(X[i]) - maxVal))
# P = np.exp(theta[:, k].T.dot(X[i])) / np.sum(np.exp(theta.T.dot(X[i])))
J -= int(y[i] == k) * np.log(P) / m
grad[:, k] -= X[i] * (int(y[i] == k) - P) / m
J += reg * np.sum(theta * theta) / (2 * m)
grad += reg * theta / m
#############################################################################
# END OF YOUR CODE #
#############################################################################
return J, grad
def softmax_loss_vectorized(theta, X, y, reg):
"""
Softmax loss function, vectorized version.
Inputs and outputs are the same as softmax_loss_naive.
"""
# Initialize the loss and gradient to zero.
J = 0.0
grad = np.zeros_like(theta)
m, dim = X.shape
#############################################################################
# TODO: Compute the softmax loss and its gradient using no explicit loops. #
# Store the loss in J and the gradient in grad. If you are not careful #
# here, it is easy to run into numeric instability. Don't forget the #
# regularization term! #
#############################################################################
matrix = X.dot(theta)
matrix -= np.max(matrix)
matrix = np.exp(matrix)
matrix /= np.sum(matrix, axis=1)[:,None]
label = np.array(range(theta.shape[1]))
Y = (np.ones((X.shape[0], theta.shape[1])) * label).T
L = (Y == y).T
J = -np.sum(np.log(matrix[L == 1])) / m + reg * np.sum(theta * theta) / (2 * m)
grad = -X.T.dot(L - matrix) / m + reg * theta / m
#############################################################################
# END OF YOUR CODE #
#############################################################################
return J, grad
|
#STRING FORMATTING::
a = int(input("ENTER FIRST VALUE::"))
b = int(input("ENTER SECOND VALUE::"))
c = int(input("ENTER THIRD VALUE::"))
avg = (a+b+c)/3
print(f"AVERAGE OF THREE VALUES YOU ENTERED IS::{avg}")#this is string formatting
#STRING INDEXING::
language="python"
#INDEX VALUE OF EACH CHARACTER IS AS FOLLOWS::
#p=0 or -6
#y=1 or -5
#t=2 or -4
#h=3 or -3
#o=4 or -2
#n=5 or -1
#IF WE WANT TO PRINT ANY PARTICULAR CHARACTER OF A STRING ::
print(language[4])
#IF WE WANT TO PRINT LAST CHARACTER OF A STRING AND WE DON'T KNOW THE SIZE OF STRING THEN WE CAN SIMPLY DO THIS::
print(language[-1])
#STRING SLICING::
#IF WE WANT TO PRINT MORE THAN ONE CHARACTER OF A PARTICULAR STRING THEN WE USE STRING SLICING
print(language[0:3])#it will print language[0],[1],[2] asstarting value is included and the end value is excluded
print("python"[0:3])#above statement and this one are same and will provide the same output
print("python"[:])#it will print the whole string
print("python"[1:])#it will print characters from 1 index value to end
print("python"[:4])#it will print characters from starting to 3 index value
#STEP ARGUMENTS IN STRING SLICING::
#IT IS USED WHEN WE HAVE TO SKIP CHARACTERS IN A PERFECT SEQUENCE
print("computer"[0:5:1])#here step is 1 which will give the same output as [0:5},step of 1 means we don't need to skip any value
print("computer"[0:6:2])#here step is 2 which will print the characters from index value 0 to 5 with skipping one character after each character
print("computer"[0::3])#here is no end index value mentioned so it will print till end with skipping 2 characters after each character
#IF WE WANT TO PRINT STRING FROM THE BACK THEN SIMPLY WE CAN DO AS FOLLOWS::
print("computer"[4::-1])#step of -1 we have to skip previous value but here is step of -1 which means we do not have to skip any value but only we have to go back or reverse
print("computer"[-1::-1])#it will print full reverse string
#WE CAN ALSO PRINT FULL REVERSE STRING AS::
print("computer"[::-1])
|
#WE CAN ASSIGN VALUES TO MORE THAN ONE VARIABLES SIMULTANEOUSLY IN A SINGLE LINE
a,b = 6,4
print(a,b)
c,d,e,f = "d","v","c","p"
print(c,d,e,f)
name,age = "DHRUV","20"
print("HELLO "+name+" YOUR AGE IS "+age)
x=y=z=1
#DECLARING MORE THAN ONE VALUES IN A SINGLE LINE
print(x+y+z)
|
# Udacity Data Analyst Nanodegree
# Technical Interview
# Lesson 3. Searching and Sorting
# Quiz: Binary Search Practice
"""You're going to write a binary search function.
You should use an iterative approach - meaning
using loops.
Your function should take two inputs:
a Python list to search through, and the value
you're searching for.
Assume the list only has distinct elements,
meaning there are no repeated values, and
elements are in a strictly increasing order.
Return the index of value, or -1 if the value
doesn't exist in the list."""
def binary_search(input_array, value):
n1 = 0
n2 = len(input_array) - 1
while n1 <= n2:
n = (n2 + n1) / 2
if value < input_array[n]:
n2 = n - 1
elif input_array[n] < value:
n1 = n + 1
else:
return n
return -1
test_list = [1,3,9,11,15,19,29]
test_val1 = 25
test_val2 = 15
print binary_search(test_list, test_val1)
print binary_search(test_list, test_val2)
# Quiz: REcursion Practice
"""Implement a function recursivly to get the desired
Fibonacci sequence value.
Your code should have the same input/output as the
iterative code in the instructions."""
def get_fib(position):
if position == 0:
return 0
if position == 1:
return 1
return get_fib(position-1) + get_fib(position-1)
# Test cases
print get_fib(9)
print get_fib(11)
print get_fib(0)
# iterative
def get_fib2(position):
if position == 0:
return 0
if position == 1:
return 1
p = 2
first, second = 0, 1
next = first + second
while p < position:
p += 1
first = second
second = next
next = first + second
return next
"""Implement quick sort in Python.
Input a list.
Output a sorted list."""
def quicksort(array):
n = len(array)
if n <= 1:
return array
else:
p = n -1
i = 0
while i < p:
if array[i] > array[p]:
temp = array[i]
array[i], array[p-1], array[p] = array[p-1], array[p], temp
p -= 1
else:
i += 1
return quicksort(array[0:p]) + quicksort(array[p:])
test = [21, 4, 1, 3, 9, 20, 25, 6, 21, 14]
print quicksort(test)
|
#!/bin/python3
"""
This is a subject for the security testing lecture.
The program accepts arithmetic expressions and prints the result of calculating the expression.
"""
import pyparsing as pp
import operator, sys
def BNF(decorate):
"""This function returns the parser for the language of arithmetic expressions. """
# function to perform calculations on the AST
def fnumberFunc(s, loc, tok):
text = "".join(tok)
return float(text)
def op(s, loc, tok):
v = tok[0]
for i in range(1, len(tok), 2):
v = tok[i](v, tok[i+1])
return v
def factorOp(s, loc, tok):
if "-" == tok[0]:
return - tok[1]
return tok[0]
# the grammar itself
point = pp.Literal( "." )
e = pp.CaselessLiteral( "E" )
fnumber = pp.Combine( pp.Word( "+-" + pp.nums, pp.nums ) +
pp.Optional( point + pp.Optional( pp.Word( pp.nums ) ) ) +
pp.Optional( e + pp.Word( "+-"+pp.nums, pp.nums ) ) )
fnumber.setParseAction(decorate("float", fnumberFunc))
plus = pp.Literal( "+" ).setParseAction(decorate("+", lambda s, loc, tok: operator.add))
minus = pp.Literal( "-" ).setParseAction(decorate("-", lambda s, loc, tok: operator.sub))
mult = pp.Literal( "*" ).setParseAction(decorate("*", lambda s, loc, tok: operator.mul))
div = pp.Literal( "/" ).setParseAction(decorate("/", lambda s, loc, tok: operator.truediv))
lpar = pp.Literal( "(" ).suppress()
rpar = pp.Literal( ")" ).suppress()
addop = plus | minus
multop = mult | div
expr = pp.Forward()
factor = (pp.Optional("-") + ( fnumber | lpar + expr + rpar ) ).setParseAction(decorate("factor", factorOp))
term = (factor + pp.ZeroOrMore( multop + factor)).setParseAction( decorate("term", op ))
expr << (term + pp.ZeroOrMore( addop + term )).setParseAction(decorate("expr", op))
return expr
def check(str):
result = BNF(lambda n, x: x).parseFile(str)[0]
print("Result: ", result)
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: arithmetic.py <file>")
exit(1)
check(sys.argv[1])
|
## IMPORTS
from room import Room
from player import Player
from item import Money
from item import Food
# Declare all the rooms
room = {
'outside': Room("Outside Cave Entrance",
"North of you, the cave mount beckons"),
'foyer': Room("Foyer", """Dim light filters in from the south. Dusty
passages run north and east."""),
'overlook': Room("Grand Overlook", """A steep cliff appears before you, falling
into the darkness. Ahead to the north, a light flickers in
the distance, but there is no way across the chasm."""),
'narrow': Room("Narrow Passage", """The narrow passage bends here from west
to north. The smell of gold permeates the air."""),
'treasure': Room("Treasure Chamber", """You've found the long-lost treasure
chamber! Sadly, it has already been completely emptied by
earlier adventurers. The only exit is to the south."""),
}
# Link rooms together
room['outside'].n_to = room['foyer']
room['foyer'].s_to = room['outside']
room['foyer'].n_to = room['overlook']
room['foyer'].e_to = room['narrow']
room['overlook'].s_to = room['foyer']
room['narrow'].w_to = room['foyer']
room['narrow'].n_to = room['treasure']
room['treasure'].s_to = room['narrow']
# Create Items
gold_small = Money('Money - S', 'Small Pile of Gold', 15, 'Gold Coins')
gold_medium = Money('Money - M', 'Medium Pile of Gold', 50, 'Gold Coins')
gold_large = Money('Money - L', 'Large Pile of Gold', 100, 'Gold Coins')
print('!!! XXX !!!',gold_small)
print('!!! XXX !!!',gold_medium)
print('!!! XXX !!!',gold_large)
carrot = Food('Carrot', 'Crunchy and good for you', '14 pounds', 3)
taco_softShell = Food('Taco', 'FREE TACO OMG!!!!!!!!...oh its shoft shell...', '3 soft shell', 1000)
taco_hardShell = Food('Taco', 'FREE TACO OMG!!!!!!!!...AND ITS A REAL TACO SHELL', '3 hard shell', 5000)
print('!!! XXX !!!',carrot)
print('!!! XXX !!!',taco_softShell)
print('!!! XXX !!!',taco_hardShell)
# Add Items to Rooms
room['outside'].items = [gold_small, carrot]
room['foyer'].items = [carrot]
room['overlook'].items = [gold_large, taco_hardShell]
room['narrow'].items = [taco_softShell]
room['treasure'].items = [carrot]
#
# Main
#
# DEFINE DIRECTIONAL MOVEMENTS
movement = ['n','s','e','w',]
# Make a new player object that is currently in the 'outside' room.
newPlayer = Player('Reed', room['outside'])
# print(newPlayer)
# Write a loop that:
#
# * Prints the current room name
# * Prints the current description (the textwrap module might be useful here).
# * Waits for user input and decides what to do.
#
# If the user enters a cardinal direction, attempt to move to the room there.
# Print an error message if the movement isn't allowed.
#
# If the user enters "q", quit the game.
# --- *** --- #
# --- *** --- #
## --- REPL --- ##
# WELCOME
welcomeMessage = f'Welcome to the game {newPlayer.name}!\n'
print(welcomeMessage)
while True:
# Check player status
print(newPlayer)
# USER PROMPT
playerAction = input( 'Please choose a direction in which you would like to go: \n'
'Your current movement options are: North = "n", South = "s", East = "e", West = "w". \n'
'Quit: "q"')
# USER INPUT CONDITIONAL
if playerAction == 'q':
exit()
elif playerAction in movement:
newPlayer.move_player(playerAction)
else:
print(f'\n'
'Please choose a valid direction \n'
'Valid Options: "n", "s", "e", "w", or "q"'
)
|
class Node:
def __init__(self):
self.children = []
self.depth = 0
self.value = 0
class ORNode(Node):
def __init__(self, s=None):
Node.__init__(self)
self.s = s
def __str__(self):
descendant = ""
for c in self.children:
c.depth += self.depth + 1
descendant += str(c)
return self.depth * "---" + "OR(" + str(self.s) + ")\n" + descendant
class ANDNode(Node):
def __init__(self, a=None):
Node.__init__(self)
self.a = a
def __str__(self):
descendant = ""
for c in self.children:
c.depth += self.depth + 1
descendant += str(c)
return self.depth * "---" + "AND(" + str(self.a) + ")\n" + descendant
|
organisms = int(input("Enter the initial number of organisms: "))
rateOfGrowth = int(input("Enter the rate of growth: "))
numOfHours = int(input("Enter the number of hours to achieve the rate of growth: "))
totalHours = int(input("Enter the total hours of growth: "))
while numOfHours <= totalHours:
organisms=organisms*rateOfGrowth
numOfHours=numOfHours+numOfHours
print("\nThe total population is ",organisms)
|
class Film:
def __init__(self,name,award,year):
self.name = name
self.award = award
self.year = year
def __str___(self):
return f'name={self.name}\taward={self.award}\tyear={self.year}'
class BaseScraper:
# Should return a dict where keys are full names of festivals and values are lists of films of type Film defined above for each festtival
def scrape():
pass
|
import csv
def createStudentsList():
with open('Students.csv', 'rb') as csvfile:
studentreader = csv.reader(csvfile, delimiter=',')
for row in studentreader:
addStudent(row)
csvfile.close()
class student(object):
def f(self):
data = {
'fname' : 'firstname',
'$fname': lambda x : data.update({'fname': x}),
'lname' : 'lastname',
'$lname': lambda x : data.update({'lname': x}),
'age' : -1,
'$age' : lambda x : data.update({'age' : x}),
'major' : 'undeclared',
'$major': lambda x : data.update({'major': x}),
'mt1' : -1,
'$mt1' : lambda x : data.update({'mt1' : x}),
'mt2' : -1,
'$mt2' : lambda x : data.update({'mt2' : x}),
'final' : -1,
'$final': lambda x : data.update({'final' : x})
}
def returnListFormat(self):
return [self.run('major'),self.run('fname'), self.run('lname'),self.run('age'),self.run('mt1'),self.run('mt2'), self.run('final')]
def cf(self, d):
if d in data:
return data[d]
elif d == 'returnListFormat':
return returnListFormat(self)
else:
return None
return cf
run = f(1)
class econ_student(student): # showcases polymorphism
def f(self):
data = {
'major': 'Economics',
'$major': lambda x : data.update({'major' : x})
}
def cf(self, d):
if d in data:
return data[d]
else:
return super(econ_student, self).run(d)
return cf
run = f(1)
class business_student(student): # showcases polymorphism
def f(self):
data = {
'major': 'Business',
'$major': lambda x : data.update({'major' : x})
}
def cf(self, d):
if d in data:
return data[d]
else:
return super(business_student, self).run(d)
return cf
run = f(1)
students = []
s1 = student
e1 = econ_student
b1 = business_student
def addStudent(rowdata):
(major, fname, lname, age, mt1, mt2, final) = rowdata
if major == "Undeclared":
new_student = s1()
elif major == "Economics":
new_student = e1()
elif major == "Business":
new_student = b1()
else:
# row has error in data
return
new_student.run('$fname')(fname)
new_student.run('$lname')(lname)
new_student.run('$age')(age)
new_student.run('$mt1')(mt1)
new_student.run('$mt2')(mt2)
new_student.run('$final')(final)
students.append(new_student.run('returnListFormat'))
return
def returnAllStudents():
return students
def returnAllBusinessStudents():
return [i for i in students if i[0] == 'Business']
|
#TowerofHanoiEasy.py
def towh(k):
if k==1:
return 1
else:
return(2*towh(k-1)+1)
def tow_o_h(k,a,c,temp):
if k==0:
return
else:
tow_o_h(k-1,a,temp,c)
print "Move ",k,"from",a,"to",c," "
tow_o_h(k-1,temp,c,a)
if __name__ == '__main__':
t = int(raw_input())
for i in range(0,t):
b = int(raw_input())
if b==1:
print "1"
print "Move 1 from A to C"
else:
print towh(b)
tow_o_h(b,'A','C','B')
|
class Node:
def __init__(self,data):
self.data = data
self.next = None
class Linkedlist:
def __init__(self,node):
self.head = node
if __name__ == '__main__':
n = Node(100)
h = Linkedlist(n)
second = Node(200)
n.next = second
third = Node(500)
second.next = third
while(h.head!=None):
print h.head.data
h.head = h.head.next
|
#quick_sort.py
#Non Permutative way
def quick_sort(A):
quick_sort2(A,0,len(A)-1)
def quick_sort2(A,low,hi):
if low < hi:
p = partition(A,low,hi)
quick_sort2(A,low,p-1)
quick_sort2(A,p+1,hi)
def partition(A,low,hi):
pivotIndex = get_pivot(A,low,hi)
pivotValue = A[pivotIndex]
A[pivotIndex],A[low] = A[low],A[pivotIndex]
border = low
for i in range(low,hi+1):
if A[i] < pivotValue:
border+=1
A[border],A[i] = A[i],A[border]
A[border],A[low] = A[low],A[border]
return border
def get_pivot(A, low, hi):
mid = (hi + low) // 2
s = sorted([A[low], A[mid], A[hi]])
if s[1] == A[low]:
return low
elif s[1] == A[mid]:
return mid
return hi
if __name__ == "__main__":
lis_t= [1,6,4,3,2,9,7,5,0]
quick_sort(lis_t)
print lis_t
|
#Arraybasedqueue.py
class ArrayQueue:
DefaultSize = 10
def __init__(self):
self._data = [None]*ArrayQueue.DefaultSize
self._size = 0
self._front = 0
def __len__(self):
return self._size
def is_empty(self):
return self._size==0
def first(self):
if self.is_empty():
raise Empty('Queue is Empty')
return self._data[self._front]
def dequeue(self):
if self.is_empty():
raise Empty('Queue is Empty')
answer = self._data[self._front]
self._data[self._front] = None
self._front = (self._front+1)%len(self._data)
self._size = 1
return answer
def enqueue(self,p):
if self._size==len(self._data):
self._resize = (2*self._data)
avail = (self._front + self._size)%len(self._data)
self._data[avail] = p
self._size+=1
def resize(self,ope):
old = self._data
self._data = [None]*ope
walk = self._front
for k in range(len(self._data)):
self._data[k] = old[walk]
walk = (walk+1)%len(old)
self._front = 0
# Operation
# Running Time
# Q.enqueue(e)
# O(1)∗
# Q.dequeue( )
# O(1)∗
# Q.first( )
# O(1)
# Q.is empty()
# O(1)
# len(Q)
# O(1)
|
#Reverse_string.py
#Still has to be refined
def revstr(S,low,high):
if low<high:
return [S[high],revstr(S,low+1,high-1),S[low]]
if __name__ == '__main__':
Str = "Revannth"
St = " ".join(map(str,revstr(Str,0,len(Str)-1)))
print St
|
#!/usr/bin/python
import re
import sys
def printUsage():
print "Usage: inputFile outputFile options"
print "options is either append [-append=number] or replace [-replace=index,number]"
print "for example:"
print " input.txt output.txt -append=0.25"
print "will read input.txt and append 0.25 to every line and write the result to output.txt"
print " input.txt output.txt -replace=0,10.57"
print "will read input.txt and replace the first column (index 0) with the value 10.57 and write the result to output.txt"
def getArguments():
if (len(sys.argv) != 4):
printUsage()
quit()
return sys.argv[1:] # remove program name
def convert():
inputFilename, outputFilename, operation = getArguments()
if (inputFilename == outputFilename):
print "Error: input and output files cannot be the same!"
printUsage()
quit()
inputFile = open(inputFilename, 'r')
outputFile = open(outputFilename, 'w')
if (operation.find("replace=") >=0):
values = operation.split("=")[1].split(",")
if (len(values) != 2):
printUsage()
quit()
replace(inputFile, outputFile, values[0], values[1])
elif (operation.find("append=")):
value = operation.split("=")[1]
append(inputFile, outputFile, value)
def replace(inputFile, outputFile, index, value):
indexValue = int(index)
for line in inputFile:
numbers = line.split(" ")
if (len(numbers) <= indexValue or indexValue < 0):
print "Error: index (%s) must be in the range of the current number of items (%d) on the following line:" % (indexValue, len(numbers))
print line
print numbers
quit()
numbers[indexValue] = value
modifiedLine = ' '.join(numbers)
outputFile.write(modifiedLine)
def append(inputFile, outputFile, value):
for line in inputFile:
line = line.replace("\n", "")
line = line + " " + str(value) + "\n"
outputFile.write(line)
if __name__ == "__main__":
convert()
|
"""
希尔排序:
希尔排序(Shell Sort)是插入排序的一种。也称缩小增量排序,是直接插入排序算法的一种更高效的改进版本。
希尔排序是非稳定排序算法。该方法因DL.Shell于1959年提出而得名。 希尔排序是把记录按下标的一定增量分组,对每组使用直接插入排序算法排序;
随着增量逐渐减少,每组包含的关键词越来越多,当增量减至1时,整个文件恰被分成一组,算法便终止。
思路:
希尔排序是插入排序的改进,所以还是安装插入排序写
但是进行比较时,引入了gab值
最优时间复杂度:根据步长序列的不同而不同
最坏时间复杂度:O(n2)
稳定想:不稳定 (因为存在分组)
希尔排序通过将比较的全部元素分为几个区域来提升插入排序的性能。这样可以让一个元素可以一次性地朝最终位置前进一大步。
然后算法再取越来越小的步长进行排序,算法的最后一步就是普通的插入排序,但是到了这步,需排序的数据几乎是已排好的了(此时插入排序较快)。
"""
list_raw = [56, 13, 24, 87, 34, 12, 44]
def shell_sort2(listName):
n = len(listName)
gab = n // 2
while gab > 0:
for i in range(gab, n):
while i >= gab:
if listName[i] < listName[i-gab]:
listName[i], listName[i-gab] = listName[i-gab], listName[i]
i -= gab
gab //= 2
return listName
print(shell_sort2(list_raw))
|
class Entrada:
def __init__(self):
self.estados = 0
self.simbolosentrada = 0
self.simbolosfita = 0
self.numTransicoes = 0
self.listEstados = list()
self.alfabetoentrada = list()
self.alfabetofita = list()
self.transicoes = list()
self.fita = ""
linha = input().split(' ')
self.estados = int(linha[0])
self.simbolosentrada = int(linha[1])
self.simbolosfita = int(linha[2])
self.numTransicoes = int(linha[3])
#print("Numero de estados: ", self.estados)
#print("Numero de simbolos de entrada: ", self.simbolosentrada)
#print("Numero de simbolos da fita ", self.simbolosfita)
#print("Numero de transicoes: ", self.numTransicoes)
self.listEstados = input().split(' ')
#print("Estados : ", self.listEstados)
self.alfabetoentrada = input().split(' ')
#print("Alfabeto entrada: ", self.alfabetoentrada)
self.alfabetofita = input().split(' ')
#print("Alfabeto fita: ", self.alfabetofita)
for i in self.alfabetoentrada:
contem = False
for j in self.alfabetofita:
if j == i:
contem = True
if contem == False:
raise Exception ('Entrada invalida', 'Alfabeto da entrada nao esta contida no alfabeto da maquina!')
for i in range(self.numTransicoes):
linha = input().replace('(',"").replace(')',"").split('=')
self.transicoes.append(linha[0].split(','))
self.transicoes.append(linha[1].split(','))
#print("Transicoes: ", self.transicoes)
for i in self.transicoes:
for j in i:
contem = False
if j != '/':
for k in self.alfabetofita:
if j == k or j == '/' or j == 'D' or j == 'E':
contem = True
for k in self.listEstados:
if j == k:
contem = True
if contem == False:
print(j)
raise Exception ('Entrada invalida', 'Transicoes com alfabeto diferente da suportada!')
self.fita = input()
#print("Entrada da fita: ", self.fita)
for i in list(self.fita):
contem = False
for j in self.alfabetoentrada:
if i == j:
contem = True
if contem == False:
raise Exception ('Entrada invalida', 'Entrada da fita com alfabeto diferente da suportada!')
|
#list
fruit = list()
print(fruit)
fruit = []
print(fruit)
fruit = ["Apple", "Orange", "Pear"]
print(fruit)
#toridasi
fruit.append("Baanana")
fruit.append("Peach")
print("fruit = ", fruit)
print("fruit_0 = ", fruit[0])
print(fruit[1])
print(fruit[2])
#append
random =[]
random.append(True)
random.append(100)
random.append(1.1)
random.append("Hello")
print("random = ", random)
#henkoukanou
colors = ["blue", "green", "yellow"]
colors[2] = "red"
print("colors = ", colors)
#pop
item = colors.pop()
print("item = ", item) #pop sarerumono
print("colors= ", colors)
#in
print("green" in colors) #True
print("black" not in colors) #True
#len
print(len(colors))
#plus
colors1 = ["blue", "green", "yellow"]
colors2 = ["orange", "pink", "black"]
print("colors1 = ", colors1, "colors2 = ", colors2)
print("(colors1 + colors2) = ", colors1 + colors2)
|
user_seconds = int(input('Введите количество секунд: '))
hour = user_seconds // 3600
seconds = user_seconds % 60
minute = int(user_seconds - (hour * 3600) - seconds) // 60
print(f'Время {hour}:{minute}:{seconds}')
|
#WAP to take input of sequence of comma-seprated numbers and generate a list and a tuple like :-
# ['1','2','3']
#('1','2','3')
values=input()
list=values.split(",") #looked for a way to split "," on the internet found this split function
tuple=tuple(list) #used the hint from the mail
print (list)
print (tuple)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.