text stringlengths 37 1.41M |
|---|
dic = {}
n = int(input())
for i in range(n):
palavra, adjetivo = input().split()
dic[palavra] = adjetivo
frase = input().split()
for palavra in frase:
if palavra in dic:
print(dic[palavra])
#https://pt.stackoverflow.com/q/346650/101
|
def funcao():
return int(input('insira um número:'))
tupla = (funcao(), funcao(), funcao(), funcao())
print(tupla.count(9))
print(tupla)
#https://pt.stackoverflow.com/q/339514/101
|
frase = input("Escreva uma frase: ")
frase = frase.upper().replace(' ','')
print("\n", frase)
#https://pt.stackoverflow.com/q/340130/101
|
entrada = input("A B C").split()
A, B, C = int(entrada[0]), int(entrada[1]), int(entrada[2])
if A >= 1 and A <= 300 and B >= 1 and B <= 300 and C >= 1 and C <= 300:
pass
else:
raise ValueError("Deu Erro")
entrada = input("Qual a altura e largura").split()
H, L = int(entrada[0]), int(entrada[1])
if H >= 1 and H <= 250 and L >= 1 and L <= 250:
pass
else:
raise ValueError("Deu Erro")
if (A and B) > (H and L) or (A and C) > (H and L) or (B and C) > (H and L):
print ("N")
else:
print("S")
#https://pt.stackoverflow.com/q/454645/101
|
import collections
numeros = [5, 3, 1, 2, 3, 4, 5, 5, 5]
repetidos = collections.Counter(numeros)
print(repetidos[5])
#https://pt.stackoverflow.com/q/176255/101
|
i = 1 #inicializador
while i < 10: #verifica a condição
print(i) #o corpo, a ação
i += 2 #o passo de "incremento"
i = 10 #inicializador
while i > 0: #verifica a condição
print(i) #o corpo, a ação
i -= 1 #o passo de "incremento"
for i in range(1, 10, 2):
print(i)
for i in range(10, 1, -1):
print(i)
#https://pt.stackoverflow.com/q/50649/101
|
for x in range(11): if x % 2 == 0: print(x)
[print(x) for x in range(11) if x % 2 == 0]
#https://pt.stackoverflow.com/q/463390/101
|
from random import choice
minusculas = "abcdefgh"
maiusculas = "ABCDEFGH"
senha = []
pos = 0
while pos < 8:
senha.append(choice(maiusculas))
senha.append(choice(minusculas))
pos += 1
print(''.join(senha))
#https://pt.stackoverflow.com/q/461052/101
|
#secret number game where user guesses between 1 and 10
import random #imports random module for random number generation
secret_num = random.randint(1,10) #generates random in in range 1-10
guess = input("I'm thinking of a number between 1 and 10. Guess!!! " ) #asks user for input
guess_num = 5 #This is the number of guesses the user has to get the answer right
while int(guess) != int(secret_num): #loops runs while the user's guess does not equal the random secret number.
guess_num = guess_num - 1 #takes a guess away for each loop
if int(guess) > int(secret_num): #here's what happens if the guess is too high
guess = input("Too high. Try again! ")
print("You have " + str(guess_num)+ " guesses left.")
elif int(guess) < int(secret_num): #here's what happens if the guess is too low
guess = input("Too low. Try again! ")
print("You have " + str(guess_num)+ " guesses left.")
print("Congrats! You win!") #displays only when user's guess is == random secret number
|
# Write a function f(x) that returns the sin of x. Hint: there is a sin function in the math module. Plot it from -5 to 5 in increments of 1
from matplotlib import pyplot
import math
def f(x):
return math.sin(x)
def run():
xs = list(range(-5, 6))
ys = []
for x in xs:
ys.append(f(x))
pyplot.plot(xs, ys)
pyplot.show()
if __name__ == "__main__":
run()
|
#Various exercies with Python loops
# print numbers between 1 and 10
for number in range (1, 10):
print(number)
#same as above with prompt of start and end
startfrom = input('Start from: ')
endon = input('End on: ')
x = int(startfrom)
y = int(endon)
for number in range (x,y):
print(number)
#print each odd number between 1 and 10 inclusive
odd_numbers = []
for number in range (1, 10):
if number % 2 != 0:
print(number)
#print a 5 by 5 sqare of * characters
x = '*****'
count = 0
while count < 5:
print(x)
count = count + 1
#print a ___ by ___ square of *; ask user for ___
userinput = input('Enter a value: ')
count = 0
y = '*'
userinput = int(userinput)
display = userinput * y
while count < userinput:
print(display)
count = count + 1
#print a box and ask user for h and w
height = int(input('Enter height: '))
width = int(input('Enter width: '))
count = 0
y = '*'
while count < height:
if count == 0:
print(y * height)
if count != 0 or count != height-1:
print (y + (' ' * width + y))
if count == height-1:
print(y * height)
count = count + 1
#print a triangle
height = 10
for i in range (height, 0, -1):
print (i * ' ' + (height + 1 - i) * '*')
|
#promt user for file name, read file and print to screen
file_read = open(input('name of file?'), 'r')
contents = file_read.read()
file_read.close()
print(contents)
|
#Nested dictionary exercices
ramit = {
'name': 'Ramit',
'email': 'ramit@gmail.com',
'interests': ['movies', 'tennis'],
'friends': [
{
'name': 'Jasmine',
'email': 'jasmine@yahoo.com',
'interests': ['photography', 'tennis']
},
{
'name': 'Jan',
'email': 'jan@hotmail.com',
'interests': ['movies', 'tv']
}
]
}
#python expression that gets email addy of Ramit
addy = ramit.get('email',)
print(addy)
#python expression that gets first of Ramit's interest
print(ramit.get('interests')[0])
#gets email addy of Jasmine
print(ramit.get('friends')[0]['email'])
#get for second of Jan's interest
print(ramit.get('friends')[1]['interests'][1])
#letter histogram counts for 'banana'
word = 'banana'
counts = {}
for char in word:
if char not in counts:
counts[char]=1
else:
counts[char]+=1
print(counts) |
# import the pygame module, and the
# sys module for exiting the window we create
import pygame, sys
# import some useful constants
from pygame.locals import *
DIRT = 0
GRASS = 1
WATER = 2
COAL = 3
# color
BLACK = (0, 0, 0)
BROWN = (153, 76, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# useful game dimentions
TILE_SIZE = 40
MAP_WIDTH = 5
MAP_HEIGHT = 5
# a list representing our tilemap
tilemap = [
[GRASS, COAL, DIRT,DIRT,WATER],
[WATER, WATER, GRASS,COAL,GRASS],
[COAL, WATER, GRASS,DIRT,GRASS],
[WATER, DIRT, DIRT,DIRT,DIRT],
[WATER, COAL, GRASS,DIRT,GRASS],
[DIRT, COAL, WATER,GRASS,WATER]
]
colors = {
DIRT: BROWN,
GRASS: GREEN,
WATER: BLUE,
COAL: BROWN
}
# initialise the pygame module
pygame.init()
# create a new drawing surface, width=300, height=300
DISPLAYSURF = pygame.display.set_mode((MAP_WIDTH * TILE_SIZE, MAP_HEIGHT * TILE_SIZE))
# give the window a caption
pygame.display.set_caption('My First Game')
# loop (repeat) forever
while True:
# get all the user events
for event in pygame.event.get():
print(event)
# if the user wants to quit
if event.type == QUIT:
# end the game and close the window
pygame.quit()
sys.exit()
for row in range(MAP_HEIGHT):
for column in range(MAP_WIDTH):
pygame.draw.rect(DISPLAYSURF, colors[tilemap[row][column]],
(column * TILE_SIZE, row * TILE_SIZE, TILE_SIZE, TILE_SIZE))
# update the display
pygame.display.update()
|
number = 0
while number < 5:
print(number)
number = number + 1
print('Ended!')
|
my_list = [1, 2, 3, 11, 14, 18, 23, 28, 29]
number_less_than_0 = my_list[0:3]
number_less_than_20 = my_list[3: 6]
number_less_than_30 = my_list[6:]
print(number_less_than_0)
print(number_less_than_20)
print(number_less_than_30)
|
name = 'Luiz Otavio'
age = 32
height = 1.80
is_greater_than_18 = age > 18
weight = 80
bmi = weight / height ** 2
print(name, 'is', age, 'years old and his BMI is', bmi, sep=' ')
print(f'{name} is {age} years old and his BMI is {bmi:.2f}')
print('{} is {} years old and his BMI is {:.2f}'.format(name, age, bmi))
print('{n} is {a} years old and his BMI is {b:.2f}'.format(n=name, a=age, b=bmi))
|
from functools import reduce
from data import products, people, numbers
sum_of_numbers = reduce(lambda accumulator, item: accumulator + item, numbers, 0)
print(sum_of_numbers)
average_of_numbers = reduce(lambda accumulator, item: accumulator + item, numbers, 0) / len(numbers)
print(average_of_numbers)
sum_of_prices = reduce(lambda accumulator, item: accumulator + item['price'], products, 0)
print(sum_of_prices)
average_of_prices = reduce(lambda accumulator, item: accumulator + item['price'], products, 0) / len(products)
print(f'{average_of_prices:.2f}')
sum_of_ages = reduce(lambda accumulator, item: accumulator + item['age'], people, 0)
print(sum_of_ages)
average_of_ages = reduce(lambda accumulator, item: accumulator + item['age'], people, 0) / len(people)
print(f'{average_of_ages:.2f}')
|
my_dictionary = dict(
first_key='First value',
second_key='Second value'
)
my_dictionary['third_key'] = 'Third value'
print(my_dictionary)
print(my_dictionary['first_key'])
print(my_dictionary['second_key'])
print(my_dictionary['third_key'])
|
from data import people
names = map(lambda person: person['name'], people)
print(list(names))
ages = map(lambda person: person['age'], people)
print(list(ages))
|
first_set = {1, 2, 3, 4, 8}
second_set = {3, 4, 5, 6, 7}
third_set = first_set - second_set
print(third_set)
third_set = first_set.difference(second_set)
print(third_set)
|
from abc import ABC, abstractmethod
class Account(ABC):
def __init__(self, agency, account_number, balance):
self._agency = agency
self._account_number = account_number
self._balance = balance
@property
def agency(self):
return self._agency
@property
def account_number(self):
return self._account_number
@property
def balance(self):
return self._balance
@balance.setter
def balance(self, value):
if not isinstance(value, (int, float)):
raise ValueError('Balance must be numeric')
self._balance = value
def deposit(self, value):
if not isinstance(value, (int, float)):
raise ValueError('Deposit amount must be numeric')
self._balance += value
self.details()
def details(self):
print(f'Agency: {self.agency}')
print(f'Account number: {self.account_number}')
print(f'Balance: {self.balance}')
print('#' * 50)
@abstractmethod
def withdraw(self, value):
pass
|
class Bank:
def __init__(self):
self.agencies = [1111, 2222, 3333]
self.customers = []
self.accounts = []
def insert_customer(self, customer):
self.customers.append(customer)
def insert_account(self, account):
self.accounts.append(account)
def authenticate(self, customer):
if customer not in self.customers:
return
if customer.account not in self.accounts:
return
if customer.account.agency not in self.agencies:
return
return True
|
questions = {
'First Question': {
'question': 'How much is 2 + 2?',
'answers': { 'a': '1', 'b': '4', 'c': '5' },
'correct_answer': 'b'
},
'Second question': {
'question': 'How much is 3 * 2?',
'answers': { 'a': '4', 'b': '10', 'c': '6' },
'correct_answer': 'c'
}
}
correct_answers = 0
for question_key, question_value in questions.items():
print(f'{question_key}: {question_value.get("question")}')
print('\tAnswers: ')
for response_key, response_value in question_value.get('answers').items():
print(f'\t{response_key}: {response_value}')
user_response = input('Your response: ')
if user_response == question_value['correct_answer']:
correct_answers += 1
print('You got the answer right')
else:
print('You got the answer wrong')
amount_of_questions = len(questions)
percentage_correct_answers = correct_answers / amount_of_questions * 100
print(f'You got {correct_answers} questions right')
print(f'Your hit percentage was {percentage_correct_answers}%')
|
text = 'Python'
for index, letter in enumerate(text):
print(f'{index} = {letter}')
|
from data import products
def increase_price(product):
product['price'] = round(product['price'] * 1.05, 2)
return product
new_products = map(increase_price, products)
for product in new_products:
print(product)
|
from contextlib import contextmanager
@contextmanager
def open_file(filename, mode):
try:
file = open(filename, mode)
print('Opening file')
yield file
finally:
print('Closing file')
file.close()
with open_file('object-oriented-programming/context-manager/my_file.txt', 'w') as file:
file.write('First line\n')
file.write('Second line\n')
file.write('Third line')
|
import pygame
import random
# Set up how the enemy thinks
class Enemy():
# Enemy constructor function
def __init__(self, x , y, speed, size):
#Make the Enemy's variables
self.x = x
self.y = y
self.pic = pygame.image.load("../assets/mos.png")
self.speed = speed
self.size = size
# Shrink enemy pic
self.pic = pygame.transform.scale(self.pic, (int(self.size*1.25), self.size))
# Flip the pic if the Enemy is moving left
if self.speed < 0:
self.pic = pygame.transform.flip(self.pic, True, False)
# Enemy Update Function
def update(self, screen):
self.x += self.speed
screen.blit(self.pic, (self.x, self.y))
# Start the game
pygame.init()
game_width = 1920
game_height = 1080
screen = pygame.display.set_mode((game_width, game_height))
clock = pygame.time.Clock()
running = True
background = pygame.image.load("../assets/background.png")
player = pygame.image.load("../assets/bird.png")
player_x = 15
player_y = 30
player_speed = 7
player_size = 50
player_facing_left = False
#Enemy spawning timer variables
enemy_timer_max = 40
enemy_timer = enemy_timer_max
# Make enemy array
enemies = []
# Everything under 'while running' will be repeated over and over again
while running:
# Makes the game stop if the player clicks the X or presses esc
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
running = False
# Check to see what keys user is pressing
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
player_y -= player_speed
if keys[pygame.K_a]:
player_x -= player_speed
player_facing_left = True
if keys[pygame.K_s]:
player_y += player_speed
if keys[pygame.K_d]:
player_x += player_speed
player_facing_left = False
if keys [pygame.K_SPACE]:
player_size += 2
if keys [pygame.K_k]:
player_size -= 2
screen.blit(background, (0, 0))
# Spawn a new Enemy whenever enemy_timer hits 0
enemy_timer -= 1
if enemy_timer <= 0:
new_enemy_y = random.randint(0, game_height)
new_enemy_speed = random.randint(1, 6)
new_enemy_size = random.randint(player_size/2, player_size*2)
if random.randint(0, 1) == 0:
enemies.append(Enemy(-new_enemy_size*2, new_enemy_y, new_enemy_speed, new_enemy_size))
else:
enemies.append(Enemy(game_width, new_enemy_y, -new_enemy_speed, new_enemy_size))
enemy_timer = enemy_timer_max
# Update all enemies
for enemy in enemies:
enemy.update(screen)
player_small = pygame.transform.scale(player, (int(player_size*1.25), player_size))
if player_facing_left:
player_small = pygame.transform.flip(player_small, True, False)
screen.blit(player_small, (player_x, player_y))
pygame.display.flip()
clock.tick(1000)
pygame.display.set_caption("FPS: " + str(clock.get_fps()))
|
from sklearn import datasets,svm,metrics
import matplotlib.pyplot as plt
digits = datasets.load_digits()
#Task - a 认识数据集
images_and_labels = list(zip(digits.images, digits.target))
# for every element in the list
for index, (image, label) in enumerate(images_and_labels[:8]):
# initialize a subplot of 2X4 at the i+1-th position
plt.subplot(2, 4, index + 1)
# Don't plot any axes
plt.axis('off')
# Display images in all subplots
plt.imshow(image, cmap=plt.cm.gray_r,interpolation='nearest')
# Add a title to each subplot
plt.title('Training: ' + str(label))
plt.show()
#Task - b 注释已给程序
# To apply a classifier on this data, we need to flatten the image, to
# turn the data in a (samples, feature) matrix:
n_samples = len(digits.images) #获取数据维度
data = digits.images.reshape((n_samples, -1)) #将数据维度改成(样本数*64)
# Create a classifier: a support vector classifier
classifier = svm.SVC(gamma=0.001) #gamma是1/(2*σ^2) gamma越大支持向量越少,这个值会影响训练速度
# We learn the digits on the first half of the digits
classifier.fit(data[:n_samples // 2], digits.target[:n_samples // 2]) #训练SVM
# Now predict the value of the digit on the second half:
expected = digits.target[n_samples // 2:] #将数据对半分用作训练和预测
predicted = classifier.predict(data[n_samples // 2:])
print("Classification report for classifier %s:\n%s\n"
% (classifier, metrics.classification_report(expected, predicted)))
print("Confusion matrix:\n%s" % metrics.confusion_matrix(expected, predicted)) #对角线上是预测正确数量 其他的是判断错成其他数字数量
images_and_predictions = list(zip(digits.images[n_samples // 2:], predicted)) #观察预测分类对应关系
for index, (image, prediction) in enumerate(images_and_predictions[:4]):
plt.subplot(2, 4, index + 5)
plt.axis('off')
plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
plt.title('Prediction: %i' % prediction)
plt.show()
#Task - c 用KNN对手写数据集分类并识别,讨论k变化时分类性能变化
#Task - d 用SVM分类,对比最佳KNN性能好坏 |
"""
Author: Jake Wachs
User object
12/7/2019
"""
import json
class User:
def __init__(self):
"""
Instantiate User object, default constructor
"""
print('Instantiating new user object')
def setUsername(self, n):
"""
Setter for name
"""
self.username = n
def getUsername(self):
"""
Getter for name
"""
return self.username
def setPassword(self, p):
"""
Setter for password
"""
self.password = p
def getPassword(self):
"""
Getter for password
"""
return self.password
def encryptPassword(self):
"""
Encrypts the password returns string
"""
print('FIXME') # FIXME: add encryption to app!
def setPassHash(self, hash):
"""
Setter for password hash
"""
self.passHash = hash
def getPassHash(self):
"""
Getter for password hash
"""
return self.passHash;
def setEmail(self, email):
"""
Setter for user email
"""
self.email = email
def getEmail(self):
"""
Getter for user email
"""
return self.email
def getDict(self):
"""
Converts class to dictionary and jsonify's
"""
user_dict = {
"username": self.username,
"email": self.email,
"passHash": self.password
}
return user_dict
def insertDB(self, collection):
"""
Inserts object's info to database
"""
dict = self.getDict()
# print(dict)
collection.insert_one(dict)
|
#creating a dictionary for keys and integers and there squares as values.
numbers = {
"1": 1**2,
"2": 2**2,
"3": 3**2,
"4": 4**2,
"5": 5**2,
"6": 6**2,
"7": 7**2,
"8": 8**2,
"9": 9**2,
"10": 10**2,
"11": 11**2,
"12": 12**2,
"13": 13**2,
"14": 14**2,
"15": 15**2,
}
for key, value in numbers . items ():
print("The square of: " + str(key) +" is: " + str (value))
|
class Game:
def __init__(self, home, away):
self.home = home
self.away = away
from sportsreference.nfl.boxscore import Boxscores
games_today = Boxscores(9, 2019)
# Prints a dictionary of all matchups for week 1 of 2017
print(games_today.games)
#games_today.game
stef = games_today._boxscores
week = "9"
year = "2019"
numberOfGames = len(stef[week+'-'+year])
games = []
for i in range(numberOfGames):
home = stef['9-2019'][i]['home_name']
away = stef['9-2019'][i]['away_name']
game = Game(home,away)
games.append(game)
tester = 5 |
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name:
Description :
Author : ianchen
date:
-------------------------------------------------
Change Activity:
2017/11/22:
-------------------------------------------------
"""
import datetime
def getYesterday():
today = datetime.date.today()
oneday = datetime.timedelta(days=92)
yesterday = today - oneday
return yesterday,today
# 输出
y,t=getYesterday()
print(y,t)
y=y.strftime("%Y%m%d")
t=t.strftime("%Y%m%d")
print(y,t)
pass
# def get_now_time():
# now = datetime.datetime.now()
# thisyear = int(now.year)
# thismon = int(now.month)
# thisday = int(now.day)
# thishour = int(now.hour)
# thisminute = int(now.minute)
# thissecond = int(now.second)
# return thisyear, thismon, thisday, thishour, thisminute, thissecond
#
#
# def get_year_and_month(n=0):
# '''
# get the year, month, days from today before or after n months
# '''
# now = datetime.datetime.now()
# thisyear, thismon, thisday, thishour, thisminute, thissecond = get_now_time()
# totalmon = thismon+n
#
# if(n>=0):
# if(totalmon<=12):
# days = str(get_days_of_month(thisyear,totalmon))
# totalmon = add_zero(totalmon)
# return (thisyear, totalmon, days, thishour, thisminute, thissecond, thisday)
# else:
# i = totalmon/12
# j = totalmon%12
# if(j==0):
# i-=1
# j=12
# thisyear += i
# days = str(get_days_of_month(thisyear,j))
# j = add_zero(j)
# return (str(thisyear),str(j),days, thishour,thisminute, thissecond, thisday)
# else:
# if((totalmon>0) and (totalmon<12)):
# days = str(get_days_of_month(thisyear,totalmon))
# totalmon = add_zero(totalmon)
# return (thisyear,totalmon,days, thishour, thisminute, thissecond, thisday)
# else:
# i = totalmon/12
# j = totalmon%12
# if(j==0):
# i-=1
# j=12
# thisyear +=i
# days = str(get_days_of_month(thisyear,j))
# j = add_zero(j)
# return (str(thisyear),str(j),days, thishour, thisminute, thissecond, thisday)
#
# def get_days_of_month(year,mon):
# return calendar.monthrange(year, mon)[1]
#
# def add_zero(n):
# '''
# add 0 before 0-9
# return 01-09
# '''
# nabs = abs(int(n))
# if (nabs < 10):
# return "0" + str(nabs)
# else:
# return nabs
#
#
# def get_today_months(n=0):
# year, mon, d, hour, minute, second, day = get_year_and_month(n)
# arr = (year, mon, d, hour, minute, second, day)
# print(arr)
# if (int(day) < int(d)):
# arr = (year, mon, day, hour, minute, second)
# return "-".join("%s" % i for i in arr)
#
# get_today_months(-3) |
import math
def parseFile(file):
numbers = []
with open(file) as f:
for line in f:
numbers.append(int(line))
return numbers
def findNumbersWithSum(numbers, target_sum, total_numbers, chosen=None):
if chosen is None:
chosen = []
sum_so_far = sum(chosen)
if len(chosen) + 1 == total_numbers:
# Last level
for number in numbers:
if sum_so_far + number == target_sum:
result = chosen[:]
result.append(number)
return result
return None
for i in range(len(numbers)):
number = numbers[i]
result = findNumbersWithSum(numbers[i+1:], target_sum, total_numbers, chosen=[*chosen, number])
if result:
return result
def main():
numbers = parseFile('./input.txt')
result = findNumbersWithSum(numbers, 2020, 3)
product = 1
for number in result:
product *= number
print(product)
if __name__ == "__main__":
main() |
age = int(input("What is your age?: "))
if age <= 1:
print("You are an infant.")
elif 2 < age < 13:
print("You are a child.")
elif 13 <= age < 20:
print("You are a teenager.")
else:
print("You are an adult.")
|
class ListIterator():
def __init__(self, collection = []):
self.collection = collection
self.cursor = 0
def current(self):
if self.cursor < len(self.collection):
return self.collection[self.cursor]
def next(self):
if len(self.collection) >= self.cursor + 1:
self.cursor += 1
def has_next(self):
has = len(self.collection) >= self.cursor + 1
if not has: self.cursor = 0
return has
def add(self, item):
self.collection += [item]
class Pupil:
def __init__(self, name):
self.name = name
self.data = {"math" : [], "prog" : [], "lit" : []}
def add_score(self, subj, score):
self.data[subj].append(score)
def __repr__(self):
return self.name + " " + str(self.data)
class Class:
def __init__(self, name, class_list = []):
self.name = name
self.class_list = class_list
def __repr__(self):
return "Номер класса: " + self.name + "; Список учеников: " + str(self.class_list)
class Teacher:
def __init__(self, name, subj):
self.name = name
self.subj = subj
self.teacher_class_list = []
def add_score_pupil(self, score, pupil):
pupil.add_score(self.subj, score)
def add_score_class_dict(self, class_num, score_dict):
for pupil_work in score_dict:
for pupil in class_num.class_list:
if pupil.name == pupil_work:
pupil.add_score(self.subj, score_dict[pupil_work])
def create_class_list(self, class_list):
self.teacher_class_list += (class_list)
def __repr__(self):
return self.name
class Administrator:
def __init__(self, classes_num):
self.classes_num = classes_num
def pupil_eval(self, pupil):
mean = {}
for subj in pupil.data:
scores = pupil.data[subj]
if scores:
avg = sum(scores) / len(scores)
mean[subj] = avg
return mean
def class_eval(self, class_num):
mean = {}
for pupil in class_num.class_list:
pupil_avg = self.pupil_eval(pupil)
for subj in pupil_avg:
mean[subj] = mean.get(subj, []) + [pupil_avg[subj]]
for subj in mean:
mean[subj] = sum(mean[subj]) / len(mean[subj])
return mean
def teacher_eval(self, teacher):
self.teacher_eval_list = []
self.final_list = []
for class_num in teacher.teacher_class_list:
for pupil in class_num.class_list:
if teacher.subj in pupil.data:
self.teacher_eval_list += pupil.data[teacher.subj]
for item2 in self.teacher_eval_list:
self.final_list.append(item2)
self.teacher_mean_grade = sum(self.final_list) / len(self.final_list)
return self.teacher_mean_grade
pupil1 = Pupil("Petya Ivanov")
pupil2 = Pupil("Anton Sidorov")
pupil3 = Pupil("Sveta Petrova")
pupil4 = Pupil("Nina Svetlova")
class1 = Class("10", [pupil1, pupil2])
class2 = Class("11", [pupil3, pupil4])
lists = ListIterator()
lists.add(class1)
lists.add(class2)
print("Заполнили классный журнал:")
while lists.has_next():
print("\t" + str(lists.current()))
lists.next()
teacher1 = Teacher("Antonina Lvovna", "math")
teacher2 = Teacher("Taras Petrovich", "lit")
teacher1.add_score_pupil(5, pupil1)
teacher1.add_score_pupil(4, pupil2)
teacher1.add_score_pupil(4, pupil3)
teacher2.add_score_pupil(3, pupil2)
teacher2.add_score_pupil(3, pupil3)
teacher2.add_score_pupil(5, pupil4)
teacher1.add_score_class_dict(class1, {"Petya Ivanov" : 5, "Sveta Petrova" : 2})
teacher1.add_score_class_dict(class2, {"Sveta Petrova" : 5, "Nina Svetlova" : 3})
print("\nПоставили ученикам оценки:")
while lists.has_next():
print("\t" + str(lists.current()))
lists.next()
administrator1 = Administrator(["10", "11"])
teacher1.create_class_list([class1, class2])
teacher2.create_class_list([class1, class2])
teacher2_eval = float(administrator1.teacher_eval(teacher2))
print("\nОцениваем работу учителя:")
while lists.has_next():
print("\t" + str(lists.current()))
lists.next()
print("Средняя оценка ", teacher2, ": " , "{:.2f}".format(teacher2_eval))
|
# Aufgabe 1
# Vervollständige die Funktion shortest_word(): Ihr sollen mehrere Strings übergeben
# werden (KEINE Liste von Strings!), von denen sie den String mit den wenigsten Zeichen zurückliefert.
def shortest_word(*nameslist):
short_name = nameslist[0]
for name in nameslist:
if len(name) < len(short_name):
short_name = name
return short_name
print(shortest_word("Max", "Moritz", "Monika", "Tim", "Jo"))
# Aufgabe 2
# a. Sortiere die Tupel in der Liste tupels aufsteigend nach ihrer Summe!
# Hinweis: Schreibe dazu zuerst eine normale Funktion und löse die Aufgabe
# anschließend nochmal mit einer lambda-Funktion.
# normale Funktion
tupels = [(10, 2), (4, 1), (0, 17), (3, 3), (5, 7), (11, 3)]
def tupels_key(sum):
return sum[0] + sum [1]
tupels.sort(key=tupels_key)
print(tupels)
# lambda Funktion
tupels = [(10, 2), (4, 1), (0, 17), (3, 3), (5, 7), (11, 3)]
tupels.sort(key = lambda n: n[0] + n[1])
print(tupels)
# b. Sortiere die Liste names mit Namen nach dem Nachnamen. Du kannst annehmen, dass alle Namen
# in der Liste nur einen Vornamen enthalten. Das Format der Namen ist immer "Vorname Nachname".
# Überlege dir dazu zuerst, wie du den Nachnamen ermittelst und schreibe dann die entsprechende
# Funktion, die du der .sort()- Funktion übergibst.
# normale Funktion
names = ["Elif Else", "Sebastian Klarnamen", "Anna Boa", "Anton Adel", "Conny Coder", "Anne Wortmann", "Willy Cordes"]
def names_key(abc):
return abc.split()[1]
names.sort(key = names_key)
print(names)
# lambda Funktion
names = ["Elif Else", "Sebastian Klarnamen", "Anna Boa", "Anton Adel", "Conny Coder", "Anne Wortmann", "Willy Cordes"]
names.sort(key = lambda n: n.split()[1])
print(names)
#c. Sortiere die Liste sentences absteigend nach der Anzahl der Wörter, die ein Element aus
# sentences jeweils enthält. Du kannst annehmen, dass in den Sätzen alle Wörter ordnungsgemäß
# mit Leerzeichen voneinander getrennt sind. :-) Überlege dir dazu zuerst, wie du die Anzahl
# Wörter in einem Satz ermitteln kannst.
# normal function
sentences = ["Sie liefen weiter den Strand entlang.", "Der Hund bellte laut.", "Er rutschte aus.", "Sie lachte."]
def s_key(sent):
# morge complex way
# counter = 0
# for s in sentences:
# sentences.find(" ")
# counter += 1
# return counter
#smart way
return len(sent.split())
sentences.sort(key = s_key, reverse = True)
print(sentences)
# lambda function
sentences = ["Sie liefen weiter den Strand entlang.", "Der Hund bellte laut.", "Er rutschte aus.", "Sie lachte."]
sentences.sort(key = lambda sent: len(sent.split()), reverse = True)
print(sentences)
# Zusatzaufgabe
# Verändere den folgenden Code so, dass die Liste l nicht mehr innerhalb der Funktion make_row()
# überschrieben wird. Die Liste, die make_row() ausgibt, soll also identisch mit der bisherigen
# sein. l soll aber am Ende in seiner ursprünglichen Form ausgegeben werden.
l = ["o", "x", "o"]
def make_row(row):
row_new = row.copy()
row_new[2] = "x"
print(row_new)
make_row(l)
print(l) |
"""
Once the data is imported use Pandas to do the following:
- Clean and Scrub the data as required
- Identify the Top 5 customers based on $ spent
- Identify the Top 3 products being sold
- Daily trend of sales per products (data and graph)
- Daily trend of sales per customer (data and graph)
- Average sales per day by product (qty) (data and Graph)
- Average sales per day by $(data and Graph)
- Average sales per day by customer on $ spent(data and Graph)
"""
import sys
import datetime
import pandas as pd
import sqlite3 as sql
from sqlite3 import Error
if len(sys.argv) != 3:
print("please provide start date and end date in the format mm-dd-yyyy")
quit()
startDateString = sys.argv[1]
# print(startDateString)
endDateString = sys.argv[2]
# print(endDateString)
try:
myStartDate = datetime.datetime.strptime(startDateString,"%Y-%m-%d")
except ValueError as e:
print(e)
print("Please Enter proper StartDate in yyyy-mm-dd format")
quit()
try:
myEndDate = datetime.datetime.strptime(endDateString,"%Y-%m-%d")
except ValueError as e:
print(e)
print("Please Enter proper EndDate in yyyy-mm-dd format")
quit()
# print(myStartDate)
# print(myEndDate)
fileNameBase = "-SalesData.csv"
filenameList = []
for index in range(myStartDate.day, myEndDate.day+1):
name = str(myStartDate.year) + "-" + myStartDate.strftime("%m") + "-" + str(0) + str(index) + fileNameBase
filenameList.append(name)
print(filenameList)
# Process the files
for file in filenameList:
try:
dataFile = pd.read_csv(file)
for index,row in dataFile.iterrows():
tuples = (row[0], row[1], row[2],row[3])
print(tuples)
except FileNotFoundError:
continue
customer = pd.read_csv('CustomerData.csv')
|
i=0
while i<7:
print("*"*i)
i=i+1
j=5
while j>0:
print("*"*j)
j=j-1
print() |
#coding=utf-8
#读文件
file=open('D:\\1.txt','r')
#print(file)
for i in file:
print(i)
file.close()
#写文件
str1='一切都是最好的安排'
file=open('D:\\2.txt','w')
file.write(str1)
file.close()
print('执行完毕')
#追加文件
file=open('D:\\2.txt','a')
file.write('\n come on baby!!!')
file.close()
print('追加完毕')
|
#coding=utf-8
#直接访问
li=['heygor','ladeng','o8ma']
print(li)
#遍历访问
for i in li:
print(i)
#成员访问
print('heygor' in li)
print('*****************8888')
li=[1,2,3]
print(li[0])
print(li[-2])
#print(li[5])
print(li[:-1])
print(li[1:])
print(li[1:2])
print('*****************8888')
li=[1,2,3]
li2=[4,5,6]
print(li+li2)
print('*****************8888')
li=[1,2,3]
print(li)
li[2]=100
print(li)
li[-1]=30
print(li)
print('*****************8888')
li=['a','b','c']
print(li)
del li[1]
print(li)
|
#coding=utf-8
def sum(a,b):
jisuan=a+b
return jisuan
s=sum(20,30)
print(s)
print('----------------------')
def re(a,b):
a*=10
b*=10
return a,b
num=re(3,5)
print(num)
print(type(num))
print('----------------------')
r1,r2=re(3,4)
print(r1,r2)
print(type(r1))
print(type(r2))
|
#coding=utf-8
def test():
n=1
print('first')
yield n
n+=1
print('second')
yield n
n+=1
print('third')
yield n
a=test()
print('next one')
print(next(a))
print('next one')
print(next(a))
print('next one')
print(next(a))
print('next one')
print(next(a))
|
n=int(input("Enter the number"))
sum=0
while(n>0):
reminder=n%10
sum=sum+reminder
n=n//10
print("the sum of digits",sum)
|
n=int(input("Enter a number1:")
m=int(input("Enter a number2:")
c=n-m
if(c%2==0):
print("the difference is even")
else:
print("the difference is odd")
|
numb1=int(input("Enter a number1"))
numb2=int(input("Enter a number2"))
numb3=int(input("Enter a number3"))
if(numb1>numb2)&(numb1>numb3):
print("the number 1 is greatest")
elif(numb2>numb3)&(numb2>numb1):
print("the number 2 is greatest")
else:
print("the number 3 is greatest")
|
str1=input()
if (len(str1%3==0):
m=len(str1)//3
print(str1[:m-1]+'*'+'*'+str1[m+1:])
else:
m=len(str1)//3
print(str1[:m]+'*'+str1[m+1:])
|
import cv2
import numpy as np
'''In order to add
the color functionality'''
Custom_Image_1=np.zeros((500,500,3),np.uint8)
'''
Function for drawing the line
1st=The file which is Custom_Image_1 for our case
2nd= Starting Point
3rd= Ending Point
4th=Color(red for our case)
5th= Thickness
'''
cv2.line(Custom_Image_1,(1,1),(Custom_Image_1.shape[1],Custom_Image_1.shape[0]),(0,0,255),3)
cv2.rectangle(Custom_Image_1,(0,0),(20,15),(255,0,0),cv2.FILLED)
cv2.circle(Custom_Image_1,(70,70),10,(0,255,0),7)
cv2.putText(Custom_Image_1,"Hello World",(400,400),cv2.FONT_ITALIC,0.5,(255,255,255),3)
print(Custom_Image_1)
cv2.imshow("Custom_Image",Custom_Image_1) #Will display red colour
cv2.waitKey(0) |
from GameState import *
from random import randint
from OpponentAI import MinimaxAI
next = False
while not next:
userInput = input("Want to go first? (y/n)\n")
if userInput == "y":
next = True
first = True
if userInput == "n":
next = True
first = False
game_state = State("O") if first else State("X")
def next_move():
print("Where would you like to move next? ", end="")
while True:
tile = input("Choose a tile from 0 to 8.\n")
try:
tile = int(tile)
if 0 <= tile <= 8:
try:
game_state.o_move(tile=tile)
return
except ValueError:
print("That tile is already occupied! ", end="")
else:
print("That is not a valid tile. ", end="")
except ValueError:
print("That is not a valid tile. ", end="")
opponent = MinimaxAI()
if not first:
# The optimal first turn is always to choose a corner.
# To speed things up, the opponent will choose a random
# corner instead of minimaxing the first turn.
corners = [0, 2, 6, 8]
game_state.x_move(corners[randint(0,3)])
# Run game
while not game_state.winner():
game_state.print()
next_move()
if not game_state.winner():
opponent.take_turn(game_state)
winner = game_state.winner()
if winner == "Draw":
print("\033[1mIt's a draw!\033[0m")
elif winner == "X":
print("\033[1mSorry, you lost!\033[0m")
elif winner == "O":
print("\033[1mYou won? Did you cheat?\033[0m") |
def main():
#write your code below this line
longest_name = ''
longest_name_len = 0
sum_of_years = 0
year_count = 0
while True:
line = input()
if line == '':
break
data = line.split(",")
name = data[0]
name_len = len(name)
year = int(data[1])
year_count += 1
sum_of_years += year
if name_len > longest_name_len:
longest_name = name
longest_name_len = name_len
average = sum_of_years / year_count
print("Longest name: " + longest_name)
print("Average of the birth years: " + str(average))
if __name__ == '__main__':
main()
|
import read
from dateutil import parser
df = read.load_data()
def hour_parser(date):
parsed_date = parser.parse(date)
return parsed_date.hour
hour_count = df["submission_time"].apply(hour_parser).value_counts()
print(hour_count)
for hour, count in hour_count.items():
print("{0}: {1}".format(hour, count), end=", ") |
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 7 13:57:29 2020
@author: primi
"""
import pandas as pd
import time
df = pd.read_csv('glassdoor_data.csv')
# remove missing values in salary section
df.dropna(subset=['Salary Estimate'], inplace=True) # remove missing values in salary section
# distinguise salary based on per hour and employeer provided salary
df['Hourly_salary'] = df['Salary Estimate'].apply(lambda x: 1 if 'per hour' in x.lower() else 0)
df['Employer_provided_salary'] = df['Salary Estimate'].apply \
(lambda x: 1 if 'employer provided salary:' in x.lower() else 0)
# Salary column contains many negative numbers so remove these rows as salary should be integer
df=df[df['Salary Estimate']!='-1']
# remove (Glassdoor est.) from salary column
salary = df['Salary Estimate'].apply(lambda x: x.split('(')[0])
# remove K and $ from salary
delete_k_ = salary.apply(lambda x : x.replace('K' ,'').replace('$' ,''))
# remove pr hour and employeer provided salary from salary
delete_hr_eps = delete_k_.apply(lambda x: x.lower().replace('per hour','').replace('employer provided salary:',''))
df['min_salary'] = delete_hr_eps.apply(lambda x: int(x.split('-')[0]))
df['max_salary'] = delete_hr_eps.apply(lambda x: int(x.split('-')[1]))
df['avg_salary'] = (df.min_salary+df.max_salary)/2
#company name should be text only
df['company_txt'] = df.apply(lambda x: x['Company Name'] if x['Rating'] <0 else x['Company Name'][:-3], axis = 1)
# get state field from locaton column
df['state'] = df['Location'].apply(lambda x: x.split(',')[1])
df.state.value_counts()
# los angeles is city so get its state CA
df['state'] = df.state.apply(lambda x: 'CA' if x.strip().lower() == 'los angeles' else x.strip())
df.state.value_counts()
df['same_state'] = df.apply(lambda x: 1 if x.Location == x.Headquarters else 0, axis = 1)
# get age of company fromcurrent year
year = int(time.strftime("%Y"))
df['age'] = df.Founded.apply(lambda x: x if x <1 else year - x)
# remove first unnamed column
df = df.drop(['Unnamed: 0'], axis =1)
#parsing of job description
df['Python'] = df['Job Description'].apply(lambda x: 1 if 'python' in x.lower() else 0)
df['R'] = df['Job Description'].apply(lambda x: 1 if 'r studio' in x.lower() or 'r-studio' in x.lower() else 0)
df['SQL'] = df['Job Description'].apply(lambda x: 1 if 'sql' in x.lower() else 0)
df['Spark'] = df['Job Description'].apply(lambda x: 1 if 'spark' in x.lower() else 0)
df['AWS'] = df['Job Description'].apply(lambda x: 1 if 'aws' in x.lower() else 0)
df['Tableau'] = df['Job Description'].apply(lambda x: 1 if 'tableau' in x.lower() else 0)
df['PowerBi'] = df['Job Description'].apply(lambda x: 1 if 'power bi' in x.lower() or 'powerbi' in x.lower() or 'power-bi' in x.lower() else 0)
df['Excel'] = df['Job Description'].apply(lambda x: 1 if 'excel' in x.lower() else 0)
df.columns
df.to_csv('glassdoor_data_cleaned.csv',index = False) |
#! usr/bin/env python3
input_list = [2, 5, 1, 153, 15, 20, 13, 200, 10]
def div_by_five(num):
if num % 5 == 0:
return True
else:
return False
# Create a generator
div_5_gen = (li for li in input_list if div_by_five(li))
# normal
for li in div_5_gen:
print(li)
# one liner
[print(li) for li in div_5_gen]
|
#! usr/bin/env python3
names = ["John", "Toby", "Rachel", "Sam"]
for name in names:
# Fancy
print(" ".join(["Hey,", name]))
print(", ".join(names))
|
import random
import sys
# This Roll class is subclassing the int class, that way it can be treated like
# an int in almost all cases, but we retain what the roll is so we can print it
# properly
class Roll(int):
def __new__(cls, *args):
values = list(args)
value = reduce(lambda x, y: x + y, values)
obj = super(Roll, cls).__new__(cls, value)
obj.values = values
return obj
def is_doubles(self):
return len(self.values) == 2 and len(set(self.values)) == 1
def __str__(self):
return ', '.join([str(v) for v in self.values])
def roll_dice(n_dice, n_sides=6):
values = []
for _ in xrange(n_dice):
values.append(int(random.random() * n_sides) + 1)
return Roll(*values)
def roll_one_die():
return roll_dice(n_dice=1)
def roll_two_dice():
return roll_dice(n_dice=2)
# This is an abstract class that represents some way of communicating with the
# player over text. Subclasses should implement tell and ask.
class InputOutput(object):
def ask(self, _msg):
# Meant to be implemented by subclass
pass
def ask_int(self, msg):
while True:
res = self.ask(msg)
try:
n = int(res)
except ValueError:
self.tell("I can't understand that\n")
continue
return n
def ask_yn_question(self, msg, commands=None):
if commands is None:
commands = {}
response = [False]
yes = [False]
def answer_yes():
yes[0] = True
response[0] = True
def answer_no():
yes[0] = False
response[0] = True
commands['yes'] = answer_yes
commands['no'] = answer_no
while not response[0]:
self.ask_cmd(msg, commands)
return yes[0]
def ask_cmd_until_done(self, msg, commands):
done = [False]
def finish():
done[0] = finish
assert 'done' not in commands
commands['done'] = finish
while not done[0]:
self.ask_cmd(msg, commands)
def ask_cmd(self, msg, commands, default=None):
assert '' not in commands, 'Empty string is not a valid command'
if default:
assert default in commands, '%s not a valid option' % default
commands[''] = commands[default]
# Sort and replace empty string with <RETURN>
options = list(commands.keys())
if default:
options.remove(default)
options.remove('')
options.append(default + ' (default)')
options = sorted(options)
while True:
res = self.ask(msg)
if res == '?':
self.tell("Valid inputs are: " + ', '.join(options) + '\n')
continue
found = []
for cmd, cb in commands.iteritems():
# fuzzy match.
if cmd.lower().startswith(res.lower()):
found.append(cb)
# exact match, remove others and go with this.
if cmd.lower() == res.lower():
found = [cb]
break
if not found or len(found) > 1:
self.tell('Illegal response: "{}".'.format(res) +
" Use '?' to get a list of valid answers\n")
else:
found[0]()
break
def tell(self, _msg):
# Meant to be implemented by subclasses
pass
class CliInputOutput(InputOutput):
def ask(self, msg):
return raw_input(msg)
def tell(self, msg):
sys.stdout.write(msg)
|
# American Flag
# Aiden Dow
# 9/27/2019 - Revised 12/21/2020
import datetime
import graphics as g
def main():
# Initialize window
win = g.GraphWin("America the Beautiful", 760, 400)
win.setCoords(0, 0, 1.9, 1)
# Draw stripes
stripeWidth = 0.0769
stripeColor = "red"
nextY = 0
for stripe in range(13):
p1 = g.Point(0, nextY)
p2 = g.Point(1.9, nextY + stripeWidth)
r = g.Rectangle(p1, p2)
r.setFill(stripeColor)
r.draw(win)
nextY += stripeWidth
if stripeColor == "red":
stripeColor = "white"
else:
stripeColor = "red"
# Draw blue square in corner
p1 = g.Point(0, 1)
p2 = g.Point(0.76, 1-0.5385)
r = g.Rectangle(p1, p2)
r.setFill("blue")
r.draw(win)
# Create initial star
t = 1
x1 = 0.0633
y1 = t-0.0538+(0.0616/2)
p1 = g.Point(x1, y1)
x2 = 0.0633-(0.0616/10)
y2 = t-0.0538+(0.0616/5)
p2 = g.Point(x2, y2)
x3 = 0.0633-(0.0616/2)
p3 = g.Point(x3, y2)
x4 = 0.0633-(0.0616/5)
y4 = t-0.0538-(0.0616/15)
p4 = g.Point(x4, y4)
x5 = 0.0633-(0.0616/3)
y5 = t-0.0538-(0.0616/2)
p5 = g.Point(x5, y5)
y6 = t-0.0538-(0.0616/5)
p6 = g.Point(x1, y6)
x7 = 0.0633+(0.0616/3)
p7 = g.Point(x7, y5)
x8 = 0.0633+(0.0616/5)
p8 = g.Point(x8, y4)
x9 = 0.0633+(0.0616/2)
p9 = g.Point(x9, y2)
x10 = 0.0633+(0.0616/10)
p10 = g.Point(x10, y2)
star = g.Polygon(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10)
star.setFill("white")
star.draw(win)
# Clone star for second set
s2 = star.clone()
s2.move(0.0633, -0.0538)
s2.draw(win)
# Draw first set of stars
for x in range(1, 6):
star = star.clone()
yStar = star
for y in range(1, 5):
yStar = yStar.clone()
yStar.move(0, -0.0538 * 2)
yStar.draw(win)
star.move(0.0633 * 2, 0)
star.draw(win)
yStar = star
for y in range(1, 5):
yStar = yStar.clone()
yStar.move(0, -0.0538 * 2)
yStar.draw(win)
# Draw second set of star
for x in range(1, 5):
s2 = s2.clone()
yStar = s2
for y in range(1, 4):
yStar = yStar.clone()
yStar.move(0, -0.0538 * 2)
yStar.draw(win)
s2.move(0.0633 * 2, 0)
s2.draw(win)
yStar = s2
for y in range(1, 4):
yStar = yStar.clone()
yStar.move(0, -0.0538 * 2)
yStar.draw(win)
win.getMouse()
main()
print("Aiden Dow")
print(datetime.datetime.now()) |
# Changing bases
# This program converts a base 10 number into another base specified by the user using a recursive function
# Aiden Dow
# 12/13/2019 - Revised 12/21/2020
import datetime
def baseConvert(num, base):
"""Convert a number into a different base"""
digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if num == 0:
return ""
else:
return baseConvert(num // base, base) + " " + digits[num % base]
def main():
print("This program converts a base 10 number into another base")
cont = True
while cont:
print()
num = int(input("What number to convert (larger than 0): "))
base = int(input("Which base to convert into(between 2 and 26): "))
print(f"The resulting digits are {baseConvert(num, base)}")
cont = input("Calculate another number[Yn]? ").strip().lower() != "n"
if __name__ == "__main__":
main()
print()
print("Aiden Dow")
print(datetime.datetime.now()) |
# Car vs. Goats
# A guess-the-door game demonstrating the Monty Hall problem
# Aiden Dow
# 11/20/2019 - Revised 12/16/2020
import datetime
from random import randrange
from graphics import GraphWin, Button, Point, Text
from time import sleep
def getDoorPick(win, buttons):
"""Waits for a click in b1, b2, or b3 and returns the number of the door clicked"""
choice = None
while choice == None:
pt = win.getMouse()
for button in buttons:
if button.clicked(pt):
choice = button
choiceNum = int(choice.getText()[-1])
return choiceNum
def showGoat(selected, carDoor, messageBox, buttons):
"""Shows the player a door that is not the car and deactivates it."""
goat = randrange(1, 4)
# If the random number is invalid, generate a new one and check it.
while goat == carDoor or goat == selected:
goat = randrange(1, 4)
buttons[goat-1].deactivate()
messageBox.setText("Well, there is a goat at door {}.\nWhich door should I open?".format(goat))
def checkWin(selectedDoor, carDoor, messageBox):
"""Find whether player won or lost"""
if selectedDoor == carDoor:
messageBox.setText("Congratulations! You have won a car")
else:
messageBox.setText("That's a goat.\nThe car was at Door {}".format(carDoor))
def main():
#set up interface
win = GraphWin("Find the Car - Avoid the Goats", 350, 225)
win.setCoords(0, 0.75, 3.25, 3.25)
b1 = Button("Door 1", Point(0.25, 2.25), Point(1, 1))
b1.activate()
b2 = Button("Door 2", Point(1.25, 2.25), Point(2, 1))
b2.activate()
b3 = Button("Door 3", Point(2.25, 2.25), Point(3, 1))
b3.activate()
buttons = [b1, b2, b3]
for button in buttons:
button.draw(win)
mess = Text(Point(1.625, 2.75), "Find the Car: Avoid the Goats")
mess.setStyle("bold")
mess.draw(win)
sleep(2)
# Initialize the variables
secret = randrange(1, 4)
mess.setText("Select a door")
# Player chooses door, computer reveals goat behind another door.
selected = getDoorPick(win, buttons)
showGoat(selected, secret, mess, buttons)
# Player chooses final door, find out whether win or lose
selected = getDoorPick(win, buttons)
checkWin(selected, secret, mess)
win.getMouse()
win.close()
print("Aiden Dow")
print(datetime.datetime.now())
if __name__ == '__main__': main()
|
# Write a program, which find all the numbers between 100 and 500
# such that each digit of the number is odd and then print the numbers.
# For example, 111 is the first number between 100 and 500 which all the digits are odd.
# you may want to use for loop, and list to program this task)
num1 = 100
num_list = []
while num1 <= 500: # while loop will execute until num1 is greater than or equal to 500
hundreds_digit = num1 // 100 # will produce the hundreds digit of num1
tens_digit = (num1 % 100) // 10 # will produce the tens digit of num1
ones_digit = num1 % 10 # will produce the ones digit of num1
hundreds_test = hundreds_digit % 2 # test to see if hundreds digit is even
tens_test = tens_digit % 2 # test to see if tens digit is even
ones_test = ones_digit % 2 # test to see if ones digit is even
# bool statements set to false for each digit test
hundreds_bool = False
tens_bool = False
ones_bool = False
# if the mod of each digit is not equal to zero, the bool test will be set to true (tests each digit)
if hundreds_test != 0:
hundreds_bool = True
else:
hundreds_bool = False
if tens_test != 0:
tens_bool = True
else:
tens_bool = False
if ones_test != 0:
ones_bool = True
else:
ones_bool = False
# if all digits are odd, add num1 to num_list
if ones_bool == True and tens_bool == True and hundreds_bool == True:
list.append(num_list, num1)
num1 = num1 + 1
else:
num1 = num1 + 1
print("The list of numbers between 100 and 500 in which each digit is odd:")
print(num_list) # print number list with all numbers in each digit
|
from timeit import default_timer as timer
def exec_time(func):
def wrapper(*args):
start = timer()
func(*args)
end = timer()
result = end = start
return result
return wrapper
# да се качи без долното в джъдж
@exec_time
def loop(start, end):
total = 0
for x in range(start, end):
total += x
return total
print(loop(1, 10000000))
|
""" Mesh module.
"""
from __future__ import absolute_import
from __future__ import print_function
import numpy as np
import array
from itertools import islice
import mimpy.mesh.mesh_cython as mesh_cython
import mimpy as mimpy
from six.moves import map
from six.moves import range
from six.moves import zip
def tb(s):
""" Encodes strings for compatibility
with Python 3.
"""
return s.encode()
class variable_array():
""" The class is an efficient reprenstation of variable
lenght two dimensional arrays. It can represent
basic data types such as ints and floats and allows variable
lengths on entries. That is:
a[0] = [1, 2, 3, 4,]
a[1] = [1, 2, 3, 4, 5, 6, 7]
Internally, the data is stored is a 1-d array, with a
separate array indicating the offset and data lenth:
data = [1, 2, 3, 4, 1, 2, 3, 4, 5, 6, 7]
offset = [[0, 4], [5, 7]]
The structure allows the user to modify the entries
as well as extend the data as needed.
"""
def __init__(self, dtype=np.dtype('d'), size=(2, 2), dim = 1):
self.pointer_capacity = size[0]
self.data_capacity = size[1]
self.dim = dim
self.dtype = dtype
self.pointers = np.empty(shape=(self.pointer_capacity, 2),
dtype=np.dtype("i"))
if self.dim == 1:
self.data = np.empty(shape = (self.data_capacity),
dtype=self.dtype)
else:
self.data = np.empty(shape = (self.data_capacity, self.dim),
dtype=self.dtype)
self.number_of_entries = 0
self.next_data_pos = 0
def __del__(self):
del self.pointers
del self.data
def set_pointer_capacity(self, capacity):
""" Sets the maximum number of entries in
the data structure.
:param int capacity: Number of expected entries.
:return: None
"""
self.pointer_capacity = capacity
self.pointers.resize((self.pointer_capacity, 2), refcheck = False)
def set_data_capacity(self, capacity):
""" Sets the maximum number of entries in
the data structure.
:param int capacity: Total data entries.
:return: None
"""
self.data_capacity = capacity
if self.dim == 1:
self.data.resize((self.data_capacity), refcheck=False)
else:
self.data.resize((self.data_capacity, self.dim), refcheck=False)
def new_size(self, size, minimum = 1000):
""" Calculates the new size of the array
given the old in case there is a need
for extending the array.
:param int size: Old data size.
:param int minimum: Sets minimum new data size.
:return: New data structure size.
:rtype: int
"""
return max(size+size/2+2, minimum)
def add_entry(self, data):
""" Adds new data to end of the list.
:param dtype data: Generic data to be added. Usually\
either scalar type (float, int ...) or ndarray type.
:return: Index of the new entry.
:rtype: int
"""
if self.number_of_entries < len(self.pointers):
self.pointers[self.number_of_entries, 0] = self.next_data_pos
self.pointers[self.number_of_entries, 1] = len(data)
else:
new_array_size = self.new_size(len(self.pointers), len(data))
self.pointers.resize((new_array_size, 2),
refcheck=False)
self.pointers[self.number_of_entries, 0] = self.next_data_pos
self.pointers[self.number_of_entries, 1] = len(data)
if len(self.data) > self.next_data_pos+len(data):
self.data[self.next_data_pos:self.next_data_pos+len(data)] = data
else:
if self.dim == 1:
self.data.resize(self.new_size(len(self.data)),
refcheck=False)
else:
self.data.resize((self.new_size(len(self.data)), self.dim),
refcheck=False)
self.data[self.next_data_pos:self.next_data_pos+len(data)] = data
self.next_data_pos = len(data)+self.next_data_pos
self.number_of_entries += 1
return self.number_of_entries-1
def get_entry(self, index):
""" Return entry.
"""
if index > self.number_of_entries:
raise IndexError("No entry with index " +str(index))
(pos, length) = self.pointers[index]
return self.data[pos:pos+length]
def __getitem__(self, index):
"""Overloaded get index function.
"""
return self.get_entry(index)
def __setitem__(self, index, value):
""" Overloaded setting function.
"""
self.set_entry(index, value)
def __len__(self):
""" Returns number of entries.
"""
return self.number_of_entries
def set_entry(self, index, data):
""" Changes existing entry to new data.
The new entry can be larger than old, but might cause
wasted memory.
"""
(pos, length) = self.pointers[index]
if length >= len(data):
self.data[pos:pos+len(data)] = data
self.pointers[index, 1] = len(data)
else:
if len(self.data) > self.next_data_pos+len(data):
self.data[self.next_data_pos:
self.next_data_pos+len(data)] = data
else:
if self.dim == 1:
self.data.resize(self.new_size(len(self.data)),
refcheck=False)
self.data[self.next_data_pos:
self.next_data_pos+len(data)] = data
else:
self.data.resize(self.new_size((len(self.data)), self.dim),
refcheck=False)
self.data[self.next_data_pos:
self.next_data_pos+len(data)] = data
self.pointers[index, 0] = self.next_data_pos
self.pointers[index, 1] = len(data)
self.next_data_pos += len(data)
class Mesh:
""" The **Mesh** class is a common representation of polygonal
meshes in Mimpy. In addition to the mesh data structure,
it provides commonly used mesh functions as such
calculating volumes and centroids as well as basic visualization.
The **Mesh** class serves as base implementation,
with the specific mesh types (such as hexahedra,
tetrahedra and Voronoi) inherting from it.
"""
def __init__(self):
# List of points used to construct mesh faces.
# Each point coordinate is prepresented by
# a Numpy array.
self.points = np.empty(shape=(0, 3), dtype=np.dtype('d'))
self.number_of_points = 0
# List of mesh faces, each face is represented by the
# a list of points. In 2D, it's a list of pairs of poitns.
# In 3D, it's an ordered list of points that make up the
# polygon.
self.faces = variable_array(dtype=np.dtype('i'))
# Face normals.
self.face_normals = np.empty(shape=(0, 3), dtype=np.dtype('d'))
# Area of mesh face.
self.face_areas = np.empty(shape=(0), dtype=np.dtype('d'))
# The centroid of face.
self.face_real_centroids = np.empty(shape=(0, 3))
# Dict that maps faces to the cells
# they are in.
self.face_to_cell = np.empty(shape=(0, 2), dtype=np.dtype('i'))
# A point on the plane of the face that is used
# to build the MFD matrix R. This point does
# not have to be on the face itself.
self.face_shifted_centroids = np.empty(shape=(0, 3))
self.has_face_shifted_centroid = False
self.has_cell_shifted_centroid = False
self.has_alpha = False
self.boundary_markers = []
self.boundary_descriptions = []
# Hash from face marker => [[face index, face normal orientation]]
self.boundary_faces = {}
# List of cells. Each cell is made up of a list
# of faces.
self.cells = variable_array(dtype=np.dtype('i'))
# For each cell, a list of bools indicating
# whether the normal in self.face_normals
# is in or out of the cell.
self.cell_normal_orientation = variable_array(dtype=np.dtype('i'))
# Cell Volumes.
self.cell_volume = np.empty(shape=(0), dtype=np.dtype('d'))
# List of cell centroids.
self.cell_real_centroid = np.empty(shape=(0, 3), dtype=np.dtype('d'))
# Points used inside the cell used
# to build the MFD matrix R.
self.cell_shifted_centroid = np.empty(shape=(0, 3), dtype=np.dtype('d'))
self.cell_k = np.empty(shape=(0, 9))
# Tags cells depending on which domain
# they belong to (for fractures and
# multi-domain problems)
self.cell_domain = np.empty(shape=(0), dtype=int)
self.cell_domain_tags = set([0])
self.dim = 3
# dict: {face_index: (cell_index, face_orientation), ...}
# Allows Dirichlet boundaries to be set implicitly
# based on pressure of cells.
self.dirichlet_boundary_pointers = {}
self.periodic_boundaries = []
# Faces designated as no flow, meant for
# interior boundary conditions not to be
# set by user.
self.internal_no_flow = []
# dict: {face_index: (lagrange_index, orientation)}
# Allows dirichlet boundaries to point to
# lagrange multipliers for domain decomposition.
# A lagrange multiplier is a face identicial
# to the one pointing to it, but not associated
# with any cells.
self.face_to_lagrange_pointers = {}
# dict: lagrange_index: [(face_index_1, orientation), ...], ...}
# Points a lagrange multiplier to faces associated
# with it. Is treated like a forcing function.
self.lagrange_to_face_pointers = {}
# dict: {cell_index: [(face_index_1, orientation), ...], ...}
# Allows source terms to be set implicitly
# based on fluxes at other faces.
self.forcing_function_pointers = {}
# Lowest order term coef
# List: [alpha1, alpha2, ...]
self.cell_alpha = []
self.is_using_alpha_list = False
self.gravity_vector = None
self.gravity_acceleration = 9.8
def add_point(self, new_point):
""" Takes a Numpy array
representing the cartesian point coodrinates,
and appends the point to the end of the point list.
Returns the index of the new point.
:param ndarray new_point: New point to be added to mesh.
:return: Index of new point.
:rtype: int
"""
if self.number_of_points < len(self.points):
self.points[self.number_of_points] = new_point
self.number_of_points += 1
else:
new_array_size = (len(self.points)+len(self.points)/2+1, 3)
self.points.resize(new_array_size, refcheck=False)
self.points[self.number_of_points] = new_point
self.number_of_points += 1
return self.number_of_points-1
def get_point(self, point_index):
""" Takes a point index and returns
a Numpy array of point coodrinates.
:param int point_index:
:return: The the point coordinates.
:rtype: ndarray
"""
return self.points[point_index]
def get_number_of_points(self):
""" Returns the total number of points.
:return: Total number of points in mesh.
:rtype: int
"""
return self.number_of_points
def _memory_extension(self, size):
""" Function for finding size of memory
extension jumps.
"""
return size+size/2+1
def add_face(self, list_of_points):
""" Takes a list of point indices, and
appends them to the list of faces
in the mesh. The point indices must
be oriented in a clockwise direction
relative to the face normal. In 2D, a
face is represnted by two points.
Returns the index of the new face.
:param list list_of_points: List of point indices\
making up the new face.
:return: Index of new face.
:rtype: int
"""
new_face_index = self.faces.add_entry(list_of_points)
if len(self.face_normals)-1 < new_face_index:
new_size = self._memory_extension(len(self.face_normals))
self.face_normals.resize((new_size, 3), refcheck=False)
if len(self.face_areas)-1 < new_face_index:
new_size = self._memory_extension(len(self.face_areas))
self.face_areas.resize(new_size, refcheck=False)
if len(self.face_real_centroids)-1 < new_face_index:
new_size = self._memory_extension(len(self.face_real_centroids))
self.face_real_centroids.resize((new_size, 3), refcheck=False)
if len(self.face_to_cell)-1 < new_face_index:
new_size = self._memory_extension(len(self.face_to_cell))
self.face_to_cell.resize((new_size, 2))
self.face_to_cell[new_face_index:, :] = -1
if self.has_face_shifted_centroid:
if len(self.face_shifted_centroids)-1 < new_face_index:
new_size = self._memory_extension(
len(self.face_shifted_centroids))
self.face_shifted_centroids.resize((new_size, 3),
refcheck=False)
return new_face_index
def set_face(self, face_index, points):
""" Sets a new set of points for a given face_index.
:param int face_index: Face index of face to be set.
:param list points: New list of points making up face.
:return: None
"""
self.faces[face_index] = points
def remove_from_face_to_cell(self, face_index, cell_index):
""" Removes the cell_index from face_to_cell map
at for face_index.
:param int face_index: Face index.
:param int cell_index: Cell index.
:return: None
"""
if self.face_to_cell[face_index, 0] == cell_index:
self.face_to_cell[face_index, 0] = -1
elif self.face_to_cell[face_index, 1] == cell_index:
self.face_to_cell[face_index, 1] = -1
else:
raise Exception("cell_index " + str(cell_index)+
" not found in face_to_cell for "+
str(face_index))
def add_to_face_to_cell(self, face_index, cell_index):
""" Adds cell_index to face_to_cell map
at face_index.
:param int face_index: The face index.
:param int cell_index: The cell index that will be associated\
with the face.
"""
if self.face_to_cell[face_index, 0] == -1:
self.face_to_cell[face_index, 0] = cell_index
elif self.face_to_cell[face_index, 1] == -1:
self.face_to_cell[face_index, 1] = cell_index
else:
raise Exception("cell_index " + str(cell_index)+
" could not be added to "+
str(face_index))
def duplicate_face(self, face_index):
""" Creates new face with all the properties
of the face_index, and adds the face to the
bottom of the face list. The function
returns the new face index.
:param int face_index: Face index to be duplicated.
:return: Face index of new duplicated face.
:rtype: int
"""
# Proper duplication requires duplicating
# all the properties fo the face.
new_index = self.add_face(self.get_face(face_index))
self.set_face_area(new_index, self.get_face_area(face_index))
return new_index
def get_face(self, face_index):
""" Given a face index, returns the
list of point indices that make
up the face.
:param int face_index: Face index.
:return: List of points making up face.
:rtype: ndarray('i')
"""
return self.faces[face_index]
def get_number_of_face_points(self, face_index):
""" Returns the number of points that make
up a given face.
:param int face_index: Face index.
:return: Number of point making up the face.
:rtype: int
"""
return len(self.faces[face_index])
def get_number_of_faces(self):
""" Returns the total number of faces
in the mesh. This corresponds to the
number of velocity degrees of freedom.
:return: Total number of faces in the mesh.
:rtype: int
"""
return self.faces.number_of_entries
def get_number_of_cell_faces(self, cell_index):
""" Returns the number of faces for cell_index
:param int cell_index: Cell index.
:return: Number of faces in cell.
:rtype: int.
"""
return len(self.cells[cell_index])
def get_face_to_cell(self, face_index):
""" Get list of cells connected with
face_index.
:param int face_index: Face index.
:return: List of cell indices connected to the face.
:rtype: list
"""
f_to_c = list(self.face_to_cell[face_index])
f_to_c = [x for x in f_to_c if x >= 0]
return f_to_c
# Sets the face shifted centroid to the intersection
# of the line joining the two face centroids and the
# face between them. Used for forcing a TPFA type
# method to the matrix.
def set_face_shifted_to_tpfa_all(self):
for face_index in range(len(self.faces)):
cells = self.get_face_to_cell(face_index)
if (len(cells)==2):
cent1 = self.get_cell_real_centroid(cells[0])
cent2 = self.get_cell_real_centroid(cells[1])
vector = cent2 - cent1
vector /= np.linalg.norm(vector)
d = np.dot((self.get_face_real_centroid(face_index) - cent1),
self.get_face_normal(face_index))
denom = np.dot(vector, self.get_face_normal(face_index))
d /= denom
intersection_point = d*vector+cent1
self.set_face_shifted_centroid(face_index, intersection_point)
else:
self.set_face_shifted_centroid(face_index,
self.get_face_real_centroid(face_index))
def is_line_seg_intersect_face(self, face_index, p1, p2):
""" Returns True if the line segment
intersects with a face.
:param int face_index: Face index.
:param ndarray p1: Coorindates of first point.
:param ndarray p2: Coorindates of second point.
:return: True if line segments intersects face.
:rtype: bool
"""
vector = p2 - p1
vector /= np.linalg.norm(vector)
d = np.dot((self.get_face_real_centroid(face_index) - p1),
self.get_face_normal(face_index))
denom = np.dot(vector, self.get_face_normal(face_index))
if abs(denom) < 1e-10:
pass
else:
d /= denom
length = np.linalg.norm(p1-p2)
if d <= length+1.e-8 and d > 0.+1.e-8:
intersection_point = d*vector+p1
direction = np.zeros(len(self.get_face(face_index)))
normal = self.get_face_normal(face_index)
current_point = self.get_point(self.get_face(face_index)[-1])
for (local_index, next_point_index) in \
enumerate(self.get_face(face_index)):
next_point = self.get_point(next_point_index)
face_vec = next_point - current_point
check_vec = current_point - intersection_point
direction[local_index] = np.dot(np.cross(face_vec,
check_vec),
normal)
current_point = next_point
if (direction>0.).all():
return True
elif (direction<0.).all():
return True
else:
return False
def initialize_cells(self, number_of_cells):
""" Initialize cell data structure
for known number of cells.
"""
raise NotImplementedError
def load_mesh(self, input_file):
""" Loads mesh from mms file.
:param file intput_file: Mesh file (mms).
:return: None
"""
version = next(input_file)
date = next(input_file)
name = next(input_file)
comments = next(input_file)
next(input_file)
next(input_file)
for line in input_file:
line_split = line.split()
if line_split[0] == "POINTS":
number_of_points = int(line_split[1])
self.number_of_points = number_of_points
self.points = np.loadtxt(islice(input_file, number_of_points))
elif line_split[0] == "FACES":
number_of_faces = int(line_split[1])
self.faces.number_of_entries = number_of_faces
current_line = next(input_file)
n_data_entries = int(current_line)
self.faces.data = np.loadtxt(islice(input_file, n_data_entries),
dtype=np.dtype('i'))
current_line = next(input_file)
n_pointers = int(current_line)
self.faces.pointers = np.loadtxt(islice(input_file, n_pointers),
dtype=np.dtype('i'))
elif line_split[0] == "FACE_NORMALS":
number_of_faces = int(line_split[1])
self.face_normals = np.loadtxt(islice(input_file,
number_of_faces))
elif line_split[0] == "FACE_AREAS":
number_of_faces = int(line_split[1])
self.face_areas = np.loadtxt(islice(input_file,
number_of_faces))
elif line_split[0] == "FACE_REAL_CENTROIDS":
number_of_faces = int(line_split[1])
self.face_real_centroids = np.loadtxt(islice(input_file,
number_of_faces))
elif line_split[0] == "FACE_SHIFTED_CENTROIDS":
self.has_face_shifted_centroid = True
number_of_faces = int(line_split[1])
self.face_shifted_centroids = np.loadtxt(
islice(input_file, number_of_faces))
elif line_split[0] == "FACE_TO_CELL":
number_of_faces = int(line_split[1])
self.face_to_cell = np.loadtxt(
islice(input_file, number_of_faces))
elif line_split[0] == "CELLS":
number_of_cells = int(line_split[1])
self.cells.number_of_entries = number_of_cells
current_line = next(input_file)
n_data_entries = int(current_line)
self.cells.data = np.loadtxt(islice(input_file, n_data_entries),
dtype=np.dtype('i'))
current_line = next(input_file)
n_pointers = int(current_line)
self.cells.pointers = np.loadtxt(islice(input_file, n_pointers),
dtype=np.dtype('i'))
elif line_split[0] == "CELL_NORMAL_ORIENTATION":
number_of_cells = int(line_split[1])
self.cell_normal_orientation.number_of_entries = \
number_of_cells
current_line = next(input_file)
n_data_entries = int(current_line)
self.cell_normal_orientation.data = \
np.loadtxt(islice(input_file, n_data_entries),
dtype=np.dtype('i'))
current_line = next(input_file)
n_pointers = int(current_line)
self.cell_normal_orientation.pointers = \
np.loadtxt(islice(input_file, n_pointers),
dtype=np.dtype('i'))
elif line_split[0] == "CELL_VOLUMES":
number_of_entries = int(line_split[1])
self.cell_volume = np.loadtxt(islice(input_file,
number_of_entries))
elif line_split[0] == "CELL_REAL_CENTROIDS":
number_of_entries = int(line_split[1])
self.cell_real_centroid = np.loadtxt(islice(input_file,
number_of_entries))
elif line_split[0] == "CELL_SHIFTED_CENTROIDS":
number_of_entries = int(line_split[1])
self.cell_shifted_centroid = np.loadtxt(
islice(input_file, number_of_entries))
elif line_split[0] == "CELL_K":
number_of_cells = int(line_split[1])
self.cell_k = np.loadtxt(islice(input_file, number_of_cells))
elif line_split[0] == "BOUNDARY_MARKERS":
number_of_boundary_markers = int(line_split[1])
for line_index in range(number_of_boundary_markers):
current_line = next(input_file)
line_split = current_line.split()
entries = [int(x) for x in line_split]
boundary_marker = entries.pop(0)
self.add_boundary_marker(boundary_marker, "FROMFILE")
while entries:
self.add_boundary_face(boundary_marker,
entries.pop(0),
entries.pop(0))
elif line_split[0] == "DIRICHLET_BOUNDARY_POINTERS":
number_of_pointers = int(line_split[1])
for line_index in range(number_of_pointers):
current_line = next(input_file)
line_split = current_line.split()
key = int(line_split[0])
cell_index = int(line_split[1])
orientation = int(line_split[2])
self.set_dirichlet_face_pointer(key,
orientation,
cell_index)
elif line_split[0] == "INTERNAL_NO_FLOW":
number_of_faces = int(line_split[1])
for line_index in range(number_of_faces):
current_line = next(input_file)
line_split = current_line.split()
face_index = int(line_split[0])
orientation = int(line_split[1])
self.internal_no_flow.append([face_index, orientation])
elif line_split[0] == "FORCING_FUNCTION_POINTERS":
number_of_cells = int(line_split[1])
for line_index in range(number_of_cells):
current_line = next(input_file)
line_split = current_line.split()
cell_index = int(line_split[0])
entries = list(map(int, line_split[1:]))
face_list = []
orientation_list = []
while entries:
face_list.append(entries.pop(0))
orientation_list.append(entries.pop(0))
self.set_forcing_pointer(cell_index,
face_list,
orientation_list)
elif line_split[0] == "FACE_TO_LAGRANGE_POINTERS":
number_of_pointers = int(line_split[1])
for line_index in range(number_of_pointers):
current_line = next(input_file)
line_split = current_line.split()
face_index = int(line_split[0])
lagrange_index = int(line_split[1])
orientation = int(line_split[2])
self.set_face_to_lagrange_pointer(face_index,
orientation,
lagrange_index)
elif line_split[0] == "LAGRANGE_TO_FACE_POINTERS":
number_of_pointers = int(line_split[1])
for line_index in range(number_of_pointers):
current_line = next(input_file)
line_split = current_line.split()
lagrange_index = int(line_split[0])
face_index = int(line_split[1])
orientation = int(line_split[2])
self.set_lagrange_to_face_pointers(lagrange_index,
face_index,
orientation)
def save_cell(self, cell_index, output_file):
""" Saves individual cell in mms format.
:param int cell_index: Cell index.
:param file output_file: File to output cell to.
:return: None
"""
glob_to_loc_points = {}
temp_mesh = self.__class__()
current_cell = []
current_cell_orientations = []
for (face_index, orientation) in zip(self.get_cell(cell_index),
self.get_cell_normal_orientation(cell_index)):
current_face = []
for point_index in self.get_face(face_index):
if point_index in glob_to_loc_points:
current_face.append(glob_to_loc_points[point_index])
else:
current_point = self.get_point(point_index)
local_index = temp_mesh.add_point(current_point)
glob_to_loc_points[point_index] = local_index
current_face.append(local_index)
new_face_index = temp_mesh.add_face(current_face)
temp_mesh.set_face_area(new_face_index,
self.get_face_area(face_index))
temp_mesh.set_face_normal(new_face_index,
self.get_face_normal(face_index))
current_centroid = self.get_face_real_centroid(face_index)
temp_mesh.set_face_real_centroid(new_face_index, current_centroid)
current_cell.append(new_face_index)
current_cell_orientations.append(orientation)
temp_mesh.add_cell(current_cell, current_cell_orientations)
temp_mesh.set_cell_k(0, self.get_cell_k(cell_index))
temp_mesh.set_cell_volume(0, self.get_cell_volume(cell_index))
current_centroid = self.get_cell_real_centroid(cell_index)
temp_mesh.set_cell_real_centroid(0, current_centroid)
temp_mesh.save_mesh(output_file)
def save_mesh(self, output_file):
""" Saves mesh file in mms format.
:param file output_file: File to save mesh to.
"""
output_file.write(b"this is just a test\n")
output_file.write(tb(str(mimpy.__version__)+"\n"))
output_file.write(b"date\n")
output_file.write(b"name\n")
output_file.write(b"comments\n")
output_file.write(b"#\n")
output_file.write(b"#\n")
## Points
output_file.write(b"POINTS ")
output_file.write(tb(str(len(self.points))+"\n"))
np.savetxt(output_file, self.points)
## Faces
output_file.write(b"FACES ")
output_file.write(tb(str(self.get_number_of_faces())+"\n"))
output_file.write(tb(str(len(self.faces.data))+"\n"))
np.savetxt(output_file, self.faces.data, fmt='%i')
output_file.write(tb(str(len(self.faces.pointers))+"\n"))
np.savetxt(output_file, self.faces.pointers, fmt="%i %i")
output_file.write(b"FACE_NORMALS ")
output_file.write(tb(str(len(self.face_normals))+"\n"))
np.savetxt(output_file, self.face_normals)
output_file.write(b"FACE_AREAS ")
output_file.write(tb(str(self.get_number_of_faces())+"\n"))
for face_index in range(self.get_number_of_faces()):
output_file.write(tb(str((self.get_face_area(face_index)))+"\n"))
output_file.write(b"FACE_REAL_CENTROIDS ")
output_file.write(tb(str(self.get_number_of_faces())+"\n"))
for face_index in range(self.get_number_of_faces()):
current_centroid = self.get_face_real_centroid(face_index)
output_file.write(tb(str(current_centroid[0])+" "))
output_file.write(tb(str(current_centroid[1])+" "))
output_file.write(tb(str(current_centroid[2])+"\n"))
if self.has_face_shifted_centroid:
output_file.write(b"FACE_SHIFTED_CENTROIDS ")
output_file(tb(str(self.get_number_of_faces())+"\n"))
for face_index in range(self.get_number_of_faces()):
output_file.write(
tb(str(self.get_face_real_centroid(face_index)+"\n")))
output_file.write(b"FACE_TO_CELL ")
output_file.write(tb(str(len(self.face_to_cell))+"\n"))
np.savetxt(output_file, self.face_to_cell, fmt="%i %i")
output_file.write(b"CELLS ")
output_file.write(tb(str(self.get_number_of_cells())+"\n"))
output_file.write(tb(str(len(self.cells.data))+"\n"))
np.savetxt(output_file, self.cells.data, fmt='%i')
output_file.write(tb(str(len(self.cells.pointers))+"\n"))
np.savetxt(output_file, self.cells.pointers, fmt="%i %i")
output_file.write(b"CELL_NORMAL_ORIENTATION ")
output_file.write(tb(str(self.get_number_of_cells())+"\n"))
output_file.write(tb(str(len(self.cell_normal_orientation.data))+"\n"))
np.savetxt(output_file,
self.cell_normal_orientation.data, fmt='%i')
output_file.write(
tb(str((len(self.cell_normal_orientation.pointers)))+"\n"))
np.savetxt(output_file,
self.cell_normal_orientation.pointers,
fmt="%i %i")
output_file.write(b"CELL_VOLUMES ")
output_file.write(tb(str(len(self.cell_volume))+"\n"))
np.savetxt(output_file, self.cell_volume)
output_file.write(b"CELL_REAL_CENTROIDS ")
output_file.write(tb(str(len(self.cell_real_centroid))+"\n"))
np.savetxt(output_file, self.cell_real_centroid)
if self.has_cell_shifted_centroid:
output_file.write(b"CELL_SHIFTED_CENTROIDS ")
output_file.write(tb(str(len(self.cell_shifted_centroid))+"\n"))
np.savetxt(ouptut_file, self.cell_shifted_centroid)
output_file.write(b"CELL_K ")
output_file.write(tb(str(len(self.cell_k))+"\n"))
np.savetxt(output_file, self.cell_k)
output_file.write(b"BOUNDARY_MARKERS ")
output_file.write(tb(str(len(self.boundary_markers))+"\n"))
for marker_index in self.boundary_markers:
output_file.write(tb(str(marker_index)+" "))
for (face_index, face_orientation) in\
self.get_boundary_faces_by_marker(marker_index):
output_file.write(
tb(str(face_index)+" "+str(face_orientation)+" "))
output_file.write(b"\n")
output_file.write(b"DIRICHLET_BOUNDARY_POINTERS ")
output_file.write(tb(str(len(list(
self.dirichlet_boundary_pointers.keys())))+"\n"))
for key in self.dirichlet_boundary_pointers:
cell_index, orientation = self.dirichlet_boundary_pointers[key]
output_file.write(
tb(str(key)+" "+str(cell_index)+" "+str(orientation)+"\n"))
output_file.write(b"INTERNAL_NO_FLOW ")
output_file.write(tb(str(len(self.internal_no_flow))+"\n"))
for [face_index, orientation] in self.internal_no_flow:
output_file.write(tb(str(face_index)+" "+str(orientation)+"\n"))
output_file.write(b"FORCING_FUNCTION_POINTERS ")
output_file.write(
tb(str(len(list(self.forcing_function_pointers.keys())))+"\n"))
for cell_index in self.forcing_function_pointers:
output_file.write(tb(str(cell_index)+" "))
for face_index, orientation in \
self.forcing_function_pointers[cell_index]:
output_file.write(tb(str(face_index)+" "+str(orientation)+" "))
output_file.write(b"\n")
output_file.write(b"FACE_TO_LAGRANGE_POINTERS ")
output_file.write(
tb(str(len(list(self.face_to_lagrange_pointers.keys())))+"\n"))
for key in self.face_to_lagrange_pointers:
lagrange_index, orientation = self.face_to_lagrange_pointers[key]
output_file.write(
tb(str(key)+" "+str(lagrange_index)+" "+str(orientation)+"\n"))
output_file.write(b"LAGRANGE_TO_FACE_POINTERS ")
output_file.write(
tb(str(len(list(self.lagrange_to_face_pointers.keys())))+"\n"))
for key in self.lagrange_to_face_pointers:
face_index, orientation = self.lagrange_to_face_pointers[key]
output_file.write(
tb(str(key)+" "+str(face_index)+" "+str(orientation)+"\n"))
output_file.close()
def set_cell_faces(self, cell_index, faces):
""" Sets the cell faces.
:param int cell_index: Cell index.
:param list faces: Faces making up cell.
:return: None
"""
self.cells[cell_index] = faces
for face_index in faces:
if cell_index not in self.face_to_cell[face_index]:
self.add_to_face_to_cell(face_index, cell_index)
def set_cell_orientation(self, cell_index, orientation):
""" Sets the cell orientation of faces.
:param int cell_index: Cell index.
:paramt list orientation: List of new cell face orientations.
:return: None
"""
self.cell_normal_orientation[cell_index] = orientation
def add_cell(self,
list_of_faces,
list_of_orientations):
""" Adds a new cell to the mesh. A cell is represented
by a list of face indices. The function also
takes in a list of orientations of the same length
as the list_of_faces. These represent the direction
of the face normals relative to the cell: (1) points in,
(-1) points out.
Returns the index of the new cell.
:param list list_of_faces: List of face indices making up new cell.
:param list list_of_orientations: List consisting of 1s and -1s\
indicating whether normals are pointing out (1) or in (-1) of cell.
:return: New cell index.
:rtype: int
"""
new_cell_index = self.cells.add_entry(list_of_faces)
self.cell_normal_orientation.add_entry(list_of_orientations)
if len(self.cell_volume)-1<new_cell_index:
new_size = self._memory_extension(len(self.cell_volume))
self.cell_volume.resize(new_size, refcheck=False)
if len(self.cell_k)-1<new_cell_index:
new_size = self._memory_extension(len(self.cell_k))
self.cell_k.resize((new_size, 9), refcheck=False)
for face_index in list_of_faces:
if self.face_to_cell[face_index][0] == -1:
self.face_to_cell[face_index][0] = new_cell_index
elif self.face_to_cell[face_index][1] == -1:
self.face_to_cell[face_index][1] = new_cell_index
else:
raise Exception("setting face "+str(face_index)+" to cell "+
str(new_cell_index)+" already set"+
" to two cells "+
str(self.face_to_cell[face_index]))
if len(self.cell_domain)-1<new_cell_index:
new_size = self._memory_extension(len(self.cell_domain))
self.cell_domain.resize(new_size, refcheck=False)
if len(self.cell_real_centroid)-1<new_cell_index:
new_size = self._memory_extension(len(self.cell_real_centroid))
self.cell_real_centroid.resize((new_size, 3))
if self.has_alpha:
self.cell_alpha.append(None)
len(self.cell_shifted_centroid)
if self.has_cell_shifted_centroid:
if len(self.cell_shifted_centroid)-1<new_cell_index:
new_size = self._memory_extension(
len(self.cell_shifted_centroid))
self.cell_shifted_centroid.resize((new_size, 3))
return new_cell_index
def get_cell(self, cell_index):
""" Given a cell_index, it returns the list of faces
that make up that cell.
:param int cell_index: Cell index of interest.
:return: List of faces making up cell.
:rtype: list
"""
return self.cells[cell_index]
def get_cell_normal_orientation(self, cell_index):
""" Given a cell index, returns a list of face
orientations for that cell.
:param int cell_index: Index of cell.
:return: List of faces orientations in cell. The\
list is made up of 1s and -1s, 1 if the corresponding\
face normal is pointing out of the cell, and -1 if the\
corresponding face normal is pointing into the cell.
:rtype: list
"""
return self.cell_normal_orientation[cell_index]
def get_number_of_cells(self):
""" Returns total number of cells in mesh.
:return: Number of cells in mesh.
:rtype: int
"""
return len(self.cells)
def set_cell_real_centroid(self, cell_index, centroid):
""" Sets the array of the cell centroid.
:param int cell_index: Index of cell.
:param ndarray centroid: New cell centroid.
:return: None
"""
self.cell_real_centroid[cell_index] = centroid
def get_cell_real_centroid(self, cell_index):
""" Returns array of the cell centroid
"""
return self.cell_real_centroid[cell_index]
def get_all_cell_real_centroids(self):
""" Returns list of all cell centroids.
:return: List of all the cell centroids.
:rtype: ndarray
"""
return self.cell_real_centroid[:self.get_number_of_cells()]
def get_all_cell_shifted_centroids(self):
""" Returns list of all cell centroids.
:return: List of all shifted cell centroid.
:rtype: ndarray
"""
return self.cell_shifted_centroid[:self.get_number_of_cells()]
def set_cell_shifted_centroid(self, cell_index, centroid):
""" Sets the shifted centroid for cell_index.
:param int cell_index: Index of cell.
:param ndarray centroid: Shifted centroid point.
:return: None
"""
self.cell_shifted_centroid[cell_index] = centroid
def use_face_shifted_centroid(self):
""" Sets whether a shifted face centroid will be used
for mesh.
"""
self.has_face_shifted_centroid = True
def is_using_face_shifted_centroid(self):
""" Returns if shifted face centroids are used
and set in mesh.
:return: Whether face shifted centroids are set
and used.
:rtype: bool
"""
return self.has_face_shifted_centroid
def use_cell_shifted_centroid(self):
""" Sets whether a shifted cell centroid will be used
for mesh.
"""
self.has_cell_shifted_centroid = True
def is_using_cell_shifted_centroid(self):
""" Returns if shifted face centroids are used
and set in mesh.
:return: Whether cell shifted centroids are set
and used.
:rtype: bool
"""
return self.has_cell_shifted_centroid
def get_cell_shifted_centroid(self, cell_index):
""" Returns the shifted cell centroid for cell_index.
:param int cell_index: Index of cell.
:return: Cell shifted point.
:rtype: ndarray
"""
return self.cell_shifted_centroid[cell_index]
def set_cell_volume(self, cell_index, volume):
""" Sets cell volume for cell_index.
:param int cell_index: Index of cell.
:param float volume: New volume to be set for cell.
:return: None
"""
self.cell_volume[cell_index] = volume
def get_cell_volume(self, cell_index):
""" Returns cell volume for cell_index.
"""
return self.cell_volume[cell_index]
def set_cell_k(self, cell_index, k):
""" Set cell permeability tensor K
(Numpy matrix) for cell_index.
"""
self.cell_k[cell_index] = k.reshape((1, 9))
def get_cell_k(self, cell_index):
""" Return permeability tensor k
(Numpy matrix) for cell_index.
"""
return self.cell_k[cell_index].reshape((3, 3))
def get_all_k_entry(self, i, j):
""" Returns a list of all K[i, j].
"""
return self.cell_k[:self.get_number_of_cells(), i*3+j]
def get_all_k(self):
""" Returns a list of all cell
permeability tensors.
"""
return self.cell_k
def use_alpha(self):
""" Activates the ability to set the
alpha parameter for each cell.
"""
self.has_alpha = True
def set_alpha_by_cell(self, alpha, cell_index):
""" Set alpha (float) for cell_index.
"""
self.cell_alpha[cell_index] = alpha
def get_alpha_by_cell(self, cell_index):
""" Returns alpha (float) for cell_index.
"""
return self.cell_alpha[cell_index]
def set_face_real_centroid(self, face_index, centroid):
""" Sets face centroid for face_index.
"""
self.face_real_centroids[face_index] = centroid
def get_face_real_centroid(self, face_index):
""" Returns face centroid.
"""
return self.face_real_centroids[face_index]
def set_face_shifted_centroid(self, face_index, centroid):
""" Sets face shifted centroid.
"""
self.face_shifted_centroids[face_index] = centroid
def get_face_shifted_centroid(self, face_index):
""" Return face shifted centroid coordinates.
"""
return self.face_shifted_centroids[face_index]
def set_face_area(self, face_index, area):
""" Sets face area (float) for face_index.
"""
self.face_areas[face_index] = area
def get_face_area(self, face_index):
""" Return area of face.
"""
return self.face_areas[face_index]
def set_face_normal(self, face_index, normal):
""" Set face normal (array) to face_index.
"""
self.face_normals[face_index] = normal
def get_face_normal(self, face_index):
""" Return face normal for face_index.
"""
return self.face_normals[face_index]
def set_boundary_markers(self, boundary_markers, boundary_descriptions):
""" Initialize the mesh boundary labeling. Each marker
can represent a single boundary face or a group
of faces.
boundary_markers: List of integers.
boundary_descriptions: List of strings describing
the face groups.
"""
self.boundary_markers = boundary_markers
self.boundary_descriptions = boundary_descriptions
for marker in boundary_markers:
self.boundary_faces[marker] = []
def add_boundary_marker(self, boundary_marker, boundary_description):
""" Add a new boundary marker.
:param int boundary_marker: New boundary marker index.
:param str boundary_description: Text describing
the boundary marker.
"""
self.boundary_markers.append(boundary_marker)
self.boundary_descriptions.append(boundary_description)
self.boundary_faces[boundary_marker] = []
def create_new_boundary_marker(self, boundary_description):
""" Creates new boundary marker and assures
that the index is unique. Returns the
index of the new boundary marker.
"""
new_index = len(self.boundary_markers)
self.boundary_markers.append(new_index)
self.boundary_descriptions.append(boundary_description)
self.boundary_faces[new_index] = []
return new_index
def has_boundary_marker(self, boundary_marker):
""" Returns true if boundary_marker exists.
"""
return boundary_marker in self.boundary_markers
def get_boundary_markers(self):
""" Returns a list of all boundary markers.
"""
return self.boundary_markers
def get_boundary_description(self, boundary_marker):
""" Returns the boundary description for
boundary_marker.
"""
return self.boundary_descriptions[boundary_marker]
def add_boundary_face(self,
boundary_marker,
face_index,
face_orientation):
""" Assign face_index to a certain boundary_marker grouping.
the face_orientation indicates whether the normal of that
face points in (-1) or out (1) of the cell the face
belongs to.
A face should never be associated with more than one marker.
:param int boundary_marker: Boundary marker index.
:param int face_index: Index of face.
:param int face_orientation: Orientation of face normal\
relative to the domain. (1) if pointing out, (-1) if\
if pointing in.
:return: None
"""
self.boundary_faces[boundary_marker].append([face_index,
face_orientation])
def set_boundary_faces(self,
boundary_marker,
face_orientation_list):
""" Takes a boundary_marker index, and sets the entire list
of tuples for that boundary marker.
:param int boundary_marker: Boundary marker to be set.
:param list face_orienation_list: A list of tuples of the form\
[face_index, orientation] to be associated with the\
indicated boundary marker.
:return: None
"""
self.boundary_faces[boundary_marker] = face_orientation_list
def get_boundary_faces_by_marker(self, boundary_marker):
""" Returns a list of all the faces associated with a boundary_marker.
:param int boundary_marker: Boundary marker index.
:return: List of tupes [face_index, orientation] associated with\
boundary_marker.
:rtype: list
"""
return self.boundary_faces[boundary_marker]
def is_boundary_face(self, face_index, markers):
""" Returns True if face_index belongs to
any of the markers.
"""
for boundary_marker in markers:
for face in self.boundary_faces[boundary_marker]:
if face_index == face[0]:
return True
return False
def find_boundary_marker(self, face_index, markers):
""" Returns the boundary marker containing
face_index.
"""
for boundary_marker in markers:
for face in self.boundary_faces[boundary_marker]:
if face_index == face[0]:
return boundary_marker
def set_boundary_face_orientation(self, face_index, new_orientation):
""" Set orientation for face_index.
"""
for bm in self.boundary_markers:
for face in self.boundary_faces[bm]:
if face_index == face[0]:
face[1] = new_orientation
def get_number_of_boundary_faces(self):
""" Returns number of faces on the boundary
of the domain.
"""
number_of_boundary_faces = 0
for boundary_marker in self.boundary_markers:
number_of_boundary_faces += \
len(self.boundary_faces[boundary_marker])
return number_of_boundary_faces
def add_internal_no_flow(self, face_index, face_orientation):
""" Sets face as interior no flow boundary condition.
:param int face_index: Face index to be set as internal no-flow.
:param int face_orientation: Orientation of face relative to the\
domain, (1) for pointing out, (-1) for pointing in.
"""
self.internal_no_flow.append([face_index, face_orientation])
def get_internal_no_flow(self):
""" Returns list of faces set as
internal no flow condition.
"""
return self.internal_no_flow
def set_dirichlet_face_pointer(self,
face_index,
face_orientation,
cell_index):
""" Sets the value of a Dirichlet boundary to
value of cell pressure for cell_index.
This approach is used for coupling fractures
with a reservoir.
"""
# The function adds a zero entry to the
# dirichlet_boundary_values dict. This
# allows the MFD code to build the matrix
# correctly, and doesn't effect the right-hand
# side of the problem.
self.dirichlet_boundary_pointers[face_index] = \
(cell_index, face_orientation)
def get_dirichlet_pointer_faces(self):
""" Returns all the faces with Dirichlet
values set by pointing to a cell.
"""
return list(self.dirichlet_boundary_pointers.keys())
def set_face_to_lagrange_pointer(self,
face_index,
face_orientation,
lagrange_index):
""" Sets face to dirichlet type boundary pointing to
lagrange multiplier.
"""
# The function adds a zero entry to the
# dirichlet_boundary_values dict. This
# allows the MFD code to build the matrix
# correctly, and doesn't effect the right-hand
# side of the problem.
self.face_to_lagrange_pointers[face_index] = \
(lagrange_index, face_orientation)
def get_all_face_to_lagrange_pointers(self):
""" Returns all face indices that are
pointing to a lagrange multiplier.
"""
return list(self.face_to_lagrange_pointers.keys())
def get_face_to_lagrange_pointer(self, face_index):
""" Returns the lagrange multiplier index
and the face normal orientation.
"""
return self.face_to_lagrange_pointers[face_index]
def set_lagrange_to_face_pointers(self,
lagrange_index,
face_index,
orientation):
""" Sets the lagrange multiplier to the source faces
in order to impose zero flux across the boundary.
"""
self.lagrange_to_face_pointers[lagrange_index] = \
zip(face_index, orientation)
def get_all_lagrange_to_face_pointers(self):
""" Returns all lagrange face indices that
point to fluxes.
"""
return list(self.lagrange_to_face_pointers.keys())
def get_lagrange_to_face_pointers(self, lagrange_index):
""" Returns the faces the lagrange_index face
points too.
"""
return self.lagrange_to_face_pointers[lagrange_index]
def get_dirichlet_pointer(self, face_index):
""" Returns the cell_index for
which the Dirichlet boundary will be set
implicitly.
"""
return self.dirichlet_boundary_pointers[face_index]
def set_periodic_boundary(self,
face_index_1,
face_orientation_1,
face_index_2,
face_orientation_2):
""" Sets a periodic boundary condition, connecting
face 1 with face 2. This ammounts to creating a single
lagrange multiplier shared by the faces. The MFD class would
impose continuity of both the pressure and the flux
for the periodic conditions.
"""
lagrange_index_1 = self.duplicate_face(face_index_1)
self.periodic_boundaries.append((face_index_1,
face_orientation_1,
face_index_2,
face_orientation_2,
lagrange_index_1,))
def set_forcing_pointer(self,
cell_index,
face_indices,
face_orientations):
""" Sets the value of the forcing function
implicity as the sum of the fluxes from list
of faces. This approach is used for coupling
fractures with a reservoir.
"""
# The function adds a zero entry to the
# cell_forcing_function dict. This
# allows the MFD code to build the matrix
# correctly, and doesn't effect the right-hand
# side of the problem.
# If the forcing function is set later on
# (in case of well for example), it
# becomes additive to the source term
# for that cell.
self.forcing_function_pointers[cell_index] = \
list(zip(face_indices, face_orientations))
def get_forcing_pointer_cells(self):
""" Returns cell indices with forcing function
pointers.
"""
return list(self.forcing_function_pointers.keys())
def get_forcing_pointers_for_cell(self, cell_index):
""" Returns list of pointers (face_indices)
for cell_index.
"""
return self.forcing_function_pointers[cell_index]
def set_cell_domain(self, cell_index, domain):
""" Sets cell domain identifier
for cell_index.
"""
self.cell_domain[cell_index] = domain
self.cell_domain_tags.add(domain)
def get_domain_tags(self):
""" Returns list of all domain tags.
"""
return list(self.cell_domain_tags)
def get_cell_domain(self, cell_index):
""" Returns cell domain identifier
for cell_index.
"""
return self.cell_domain[cell_index]
def get_cell_domain_all(self):
""" Returns list containing
all cell_domain tags.
"""
return self.cell_domain[:self.get_number_of_cells()]
def get_cells_in_domain(self, domain):
""" Returns all cells with domain tag.
"""
cells_in_domain = []
for cell_index in range(self.get_number_of_cells()):
if self.cell_domain[cell_index] == domain:
cells_in_domain.append(cell_index)
return cells_in_domain
def set_gravity_vector(self, gravity_vector):
""" Set vector indicating gravity acceleration direction.
"""
self.gravity_vector = gravity_vector
def get_gravity_vector(self):
""" Returns gravity vector (down direction)
"""
return self.gravity_vector
def get_gravity_acceleration(self):
""" Returns the gravity acceleration constant.
"""
return self.gravity_acceleration
def find_basis_for_face(self, face_index):
""" Finds two non collinear vectors
in face to serve as basis for plane.
"""
face = self.get_face(face_index)
for i in range(len(face)):
v1 = self.get_point(face[i+1]) - self.get_point(face[i])
v2 = self.get_point(face[i]) - self.get_point(face[i-1])
v2 /= np.linalg.norm(v2)
v1 /= np.linalg.norm(v1)
if 1.-abs(v1.dot(v2)) > 1.e-6:
return (v1, v2, face[i])
raise Exception("Couldn't compute basis for face " + str(face_index))
def find_face_normal(self, face_index):
""" Finds the face normal based on
rotation around the face boundary.
Assumes the face is planar.
"""
face = self.get_face(face_index)
for i in range(len(face)):
v1 = self.get_point(face[i+1]) - self.get_point(face[i])
v2 = self.get_point(face[i]) - self.get_point(face[i-1])
new_face_normal = np.cross(v2, v1)
if np.linalg.norm(new_face_normal) >1.e-10:
new_face_normal /= np.linalg.norm(new_face_normal)
return new_face_normal
raise Exception("Couldn't compute normal for face " + str(face_index))
def find_centroid_for_coordinates(self, face_index, coordinates):
""" Computes centroid calculation for a 3D polygon based on
two coordinates of the polygon.
"""
C_1 = 0.
C_2 = 0.
area = 0.
index_1 = coordinates[0]
index_2 = coordinates[1]
current_face = self.get_face(face_index)
for index in range(len(current_face)):
current_point = self.get_point(current_face[index])
if index == len(current_face)-1:
next_point = self.get_point(current_face[0])
else:
next_point = self.get_point(current_face[index+1])
C_1 += ((current_point[index_1]+next_point[index_1])*
(current_point[index_1]*next_point[index_2]-
next_point[index_1]*current_point[index_2]))
C_2 += ((current_point[index_2]+next_point[index_2])*
(current_point[index_1]*next_point[index_2]-
next_point[index_1]*current_point[index_2]))
area += current_point[index_1]*next_point[index_2]
area -= next_point[index_1]*current_point[index_2]
area /= 2.
C_1 /= 6.*area
C_2 /= 6.*area
return (area, C_1, C_2)
def find_face_centroid(self, face_index):
""" Returns centroid coordinates for face_index.
This function assumes planarity of the face.
and is currently intended for use with three dimensional
meshes.
The function returns the area of the face, as well
as the x, y, z coordinates of its center.
"""
(v1, v2, origin_index) = self.find_basis_for_face(face_index)
polygon = [np.array(self.get_point(x))
for x in self.get_face(face_index)]
assert(np.linalg.norm(v2) >1.e-12)
assert(np.linalg.norm(v1) >1.e-12)
v1 = v1/np.linalg.norm(v1)
v_temp = np.cross(v1, v2)
v2 = np.cross(v_temp, v1)
if np.linalg.norm(v2)< 1.e-10:
v2 = polygon[-2]-polygon[-1]
v_temp = np.cross(v1, v2)
v2 = np.cross(v_temp, v1)
v2 = v2/np.linalg.norm(v2)
origin = self.get_point(origin_index)
transposed_polygon = [x - origin for x in polygon]
polygon_projected_v1 = [np.dot(x, v1) for x in transposed_polygon]
polygon_projected_v2 = [np.dot(x, v2) for x in transposed_polygon]
polygon_projected = list(zip(polygon_projected_v1,
polygon_projected_v2))
area = self.compute_polygon_area(polygon_projected)
centroid_x = 0.
centroid_y = 0.
N = len(polygon_projected)
for i in range(N-1):
centroid_x += ((polygon_projected[i][0]+
polygon_projected[i+1][0])*
(polygon_projected[i][0]*
polygon_projected[i+1][1]-
polygon_projected[i+1][0]*
polygon_projected[i][1]))
centroid_y += ((polygon_projected[i][1]+
polygon_projected[i+1][1])*
(polygon_projected[i][0]*
polygon_projected[i+1][1]-
polygon_projected[i+1][0]*
polygon_projected[i][1]))
centroid_x += ((polygon_projected[N-1][0]+
polygon_projected[0][0])*
(polygon_projected[N-1][0]*
polygon_projected[0][1]-
polygon_projected[0][0]*
polygon_projected[N-1][1]))
centroid_y += ((polygon_projected[N-1][1]+
polygon_projected[0][1])*
(polygon_projected[N-1][0]*
polygon_projected[0][1]-
polygon_projected[0][0]*
polygon_projected[N-1][1]))
centroid_x = centroid_x/(6.*area)
centroid_y = centroid_y/(6.*area)
centroid_3d_x = 0.
centroid_3d_y = 0.
centroid_3d_z = 0.
centroid_3d_x += polygon[0][0]
centroid_3d_y += polygon[0][1]
centroid_3d_z += polygon[0][2]
centroid_3d_x += centroid_x * v1[0]
centroid_3d_y += centroid_x * v1[1]
centroid_3d_z += centroid_x * v1[2]
centroid_3d_x += centroid_y * v2[0]
centroid_3d_y += centroid_y * v2[1]
centroid_3d_z += centroid_y * v2[2]
centroid = np.array([centroid_3d_x, centroid_3d_y, centroid_3d_z])
return (abs(area), centroid)
def compute_polygon_area(self, polygon, dims = [0, 1]):
""" Computes the area of a polygon. A polygon is
represented by a list of Numpy array coordinates
going around the polygon. The optional parameter
*dims* represents which two coordinates to use
when the polygon is in 3D space.
"""
current_x = dims[0]
current_y = dims[1]
area = 0.
N = len(polygon)
for i in range(N-1):
area += (polygon[i][current_x]*polygon[i+1][current_y]-
polygon[i+1][current_x]*polygon[i][current_y])
area += (polygon[N-1][current_x]*polygon[0][current_y]-
polygon[0][current_x]*polygon[N-1][current_y])
area *= .5
# The function returns the absolute value of the area.
return area
def find_volume_centroid_all(self):
""" Computes the cell centroids and volumes
for all the cells in the mesh.
"""
## This is based on the code and
## paper by Brian Mirtich.
zero3 = np.zeros(3)
for cell_index in range(self.get_number_of_cells()):
self.set_cell_volume(cell_index, 0.)
self.set_cell_real_centroid(cell_index, zero3)
mesh_cython.all_cell_volumes_centroids(
self.cells.pointers,
len(self.cells),
self.cells.data,
self.cell_normal_orientation.data,
self.points,
self.cell_volume,
self.cell_real_centroid,
self.faces.pointers,
len(self.faces),
self.faces.data,
self.face_normals,
self.face_to_cell)
def find_volume_from_faces(self, face_list, orientation_list):
""" Calculates volume and centroid of cell
based on list of faces and face orientations relative
to the cell.
"""
volume = 0.
centroid = np.zeros(3)
for (face_index, face_orientation) in zip(face_list, orientation_list):
current_normal = self.get_face_normal(face_index)*face_orientation
if (abs(current_normal[0]) > abs(current_normal[1])) and \
(abs(current_normal[0]) > abs(current_normal[2])):
C = 0
elif abs(current_normal[1])>abs(current_normal[2]):
C = 1
else:
C = 2
A = (C+1)%3
B = (A+1)%3
P1 = 0.
Pa = 0.
Pb = 0.
Paa = 0.
Pab = 0.
Pbb = 0.
if face_orientation > 0:
points = self.get_face(face_index)
next_points = list(points[1:])+list(points[:1])
else:
next_points = self.get_face(face_index)
points = list(next_points[1:])+list(next_points[:1])
for (point_index, next_point_index) in zip(points, next_points):
a0 = self.get_point(point_index)[A]
b0 = self.get_point(point_index)[B]
a1 = self.get_point(next_point_index)[A]
b1 = self.get_point(next_point_index)[B]
da = a1-a0
db = b1-b0
a0_2 = a0*a0
a0_3 = a0_2*a0
b0_2 = b0*b0
b0_3 = b0_2*b0
a1_2 = a1*a1
C1 = a1 + a0
Ca = a1*C1 + a0_2
Caa = a1*Ca + a0_3
Cb = b1*(b1 + b0) + b0_2
Cbb = b1*Cb + b0_3
Cab = 3.*a1_2 + 2.*a1*a0 + a0_2
Kab = a1_2 + 2*a1*a0 + 3*a0_2
P1 += db*C1
Pa += db*Ca
Paa += db*Caa
Pb += da*Cb
Pbb += da*Cbb
Pab += db*(b1*Cab + b0*Kab)
P1 /= 2.0
Pa /= 6.0
Paa /= 12.0
Pb /= -6.0
Pbb /= -12.0
Pab /= 24.0
first_point = self.get_point(self.get_face(face_index)[0])
w = -current_normal.dot(first_point)
k1 = 1./current_normal[C]
k2 = k1*k1
k3 = k2*k1
Fa = k1*Pa
Fb = k1*Pb
Fc = -k2*(current_normal[A]*Pa + current_normal[B]*Pb + w*P1)
Faa = k1*Paa
Fbb = k1*Pbb
Fcc = k3*((current_normal[A]*current_normal[A])*Paa+
2*current_normal[A]*current_normal[B]*Pab+
(current_normal[B]*current_normal[B])*Pbb+
w*(2.*(current_normal[A]*Pa+current_normal[B]*Pb)+w*P1))
if A == 0:
volume += current_normal[0]*Fa
elif B == 0:
volume += current_normal[0]*Fb
else:
volume += current_normal[0]*Fc
centroid[A] += current_normal[A]*Faa
centroid[B] += current_normal[B]*Fbb
centroid[C] += current_normal[C]*Fcc
centroid /= volume*2.
return (volume, centroid)
def find_volume_centroid(self, cell_index):
""" Returns the volume and centroid for a 3D cell_index.
Based on code and paper by Brian Mirtich.
"""
face_list = self.get_cell(cell_index)
orientation_list = self.get_cell_normal_orientation(cell_index)
return self.find_volume_from_faces(face_list, orientation_list)
def output_vector_field(self,
file_name,
vector_magnitudes = [],
vector_labels = []):
""" Outputs vector data in the vtk format. The vector
field can be processed using the glyph filter in
Paraview. The function takes a list of vector
magnitudes that are associated with each face
normal.
"""
output = open(file_name +".vtk",'wb')
print("# vtk DataFile Version 1.0", file=output)
print("MFD output", file=output)
print("ASCII", file=output)
print("DATASET UNSTRUCTURED_GRID", file=output)
print("POINTS", self.get_number_of_faces() , "float", file=output)
for face_index in range(self.get_number_of_faces()):
current_point = self.get_face_real_centroid(face_index)
print(current_point[0], end=' ', file=output)
print(current_point[1], end=' ', file=output)
print(current_point[2], file=output)
print(" ", file=output)
print("CELLS", self.get_number_of_faces(), end=' ', file=output)
print(self.get_number_of_faces()*2, file=output)
for face_index in range(self.get_number_of_faces()):
print("1", face_index + 1, file=output)
print(" ", file=output)
print("CELL_TYPES" , self.get_number_of_faces(), file=output)
for index in range(self.get_number_of_faces()):
print("1", file=output)
print(" ", file=output)
print("POINT_DATA", self.get_number_of_faces(), file=output)
print(" ", file=output)
for data_index in range(len(vector_labels)):
print("VECTORS", vector_labels[data_index], "float", file=output)
for face_index in range(len(vector_magnitudes[data_index])):
current_vector = vector_magnitudes[data_index][face_index]*\
self.get_face_normal(face_index)
print(current_vector[0], end=' ', file=output)
print(current_vector[1], end=' ', file=output)
print(current_vector[2], file=output)
print(" ", file=output)
def output_cell_normals(self, file_name, cell_index):
""" Outputs the normals over the cell in the outward direction.
The function is intended for checking the correct orientation of cell.
"""
output = open(file_name +".vtk",'wb')
number_of_faces = len(self.get_cell(cell_index))
print("# vtk DataFile Version 1.0", file=output)
print("MFD output", file=output)
print("ASCII", file=output)
print("DATASET UNSTRUCTURED_GRID", file=output)
print("POINTS", number_of_faces , "float", file=output)
for face_index in self.get_cell(cell_index):
centroid = self.get_face_real_centroid(face_index)
print(centroid[0], end=' ', file=output)
print(centroid[1], end=' ', file=output)
print(centroid[2], file=output)
print(" ", file=output)
print("CELLS", number_of_faces, end=' ', file=output)
print(number_of_faces*2, file=output)
for index in range(number_of_faces):
print("1", index+1, file=output)
print(" ", file=output)
print("POINT_DATA", number_of_faces, file=output)
print(" ", file=output)
print("VECTORS", "OUT_NORMAL", "float", file=output)
face_list = self.get_cell(cell_index)
orientation_list = self.get_cell_normal_orientation(cell_index)
for (face_index, orientation) in zip(face_list, orientation_list):
normal = self.get_face_normal(face_index)
print(normal[0]*orientation, end=' ', file=output)
print(normal[1]*orientation, end=' ', file=output)
print(normal[2]*orientation, file=output)
print(" ", file=output)
def output_vtk_faces(self,
file_name,
face_indices,
face_values = [],
face_value_labels = []):
""" Outputs in vtk format the faces in face_indices.
"""
output = open(file_name +".vtk",'wt')
print("# vtk DataFile Version 2.0", file=output)
print("# unstructured mesh", file=output)
print("ASCII", file=output)
print("DATASET UNSTRUCTURED_GRID", file=output)
print("POINTS", self.get_number_of_points(), "float", file=output)
for point_index in range(self.get_number_of_points()):
point = self.get_point(point_index)
print(point[0], point[1], point[2], file=output)
total_polygon_points = 0
for face_index in face_indices:
total_polygon_points += \
self.get_number_of_face_points(face_index)+1
print("CELLS", len(face_indices), file=output)
print(total_polygon_points, file=output)
for face_index in face_indices:
current_face = self.get_face(face_index)
print(len(current_face), end=' ', file=output)
for point in current_face:
print(point, end=' ', file=output)
print("\n", end=' ', file=output)
print("CELL_TYPES", len(face_indices), file=output)
for face_index in face_indices:
print(7, file=output)
if face_values:
print("CELL_DATA", len(face_indices), file=output)
for (entry, entryname) in zip(face_values, face_value_labels):
print("SCALARS", entryname, "double 1", file=output)
print("LOOKUP_TABLE default", file=output)
for value in entry:
print(value, file=output)
output.close()
def output_vtk_mesh(self,
file_name,
cell_values=[],
cell_value_labels=[]):
""" Base implementation for producing
vtk files for general polyhedral meshes.
"""
output = open(file_name +".vtk",'wb')
print("# vtk DataFile Version 2.0", file=output)
print("# unstructured mesh", file=output)
print("ASCII", file=output)
print("DATASET UNSTRUCTURED_GRID", file=output)
print("POINTS", self.get_number_of_points(), "float", file=output)
for point_index in range(self.get_number_of_points()):
point = self.get_point(point_index)
print(point[0], point[1], point[2], file=output)
total_polygon_points = 0
for cell_index in range(self.get_number_of_cells()):
for face_index in self.get_cell(cell_index):
total_polygon_points += \
self.get_number_of_face_points(face_index)+1
total_polygon_points += 2
print("CELLS", self.get_number_of_cells(), end=' ', file=output)
print(total_polygon_points, file=output)
for cell_index in range(self.get_number_of_cells()):
number_of_entries = len(self.get_cell(cell_index))
for face_index in self.get_cell(cell_index):
number_of_entries += self.get_number_of_face_points(face_index)
number_of_entries += 1
print(number_of_entries, end=' ', file=output)
print(len(self.get_cell(cell_index)), end=' ', file=output)
for face_index in self.get_cell(cell_index):
current_face = self.get_face(face_index)
print(len(current_face), end=' ', file=output)
for point in current_face:
print(point, end=' ', file=output)
print("\n", end=' ', file=output)
print("CELL_TYPES", self.get_number_of_cells(), file=output)
for cell_index in range(self.get_number_of_cells()):
print(42, file=output)
if cell_values:
print("CELL_DATA", self.get_number_of_cells(), file=output)
for (entry, entryname) in zip(cell_values, cell_value_labels):
print("SCALARS", entryname, "double 1", file=output)
print("LOOKUP_TABLE default", file=output)
for value in entry:
print(value, file=output)
output.close()
def find_cell_near_point(self, point, condition = lambda x: True):
""" Returns cell whose centroid is closest
to a given point. Condition is an optional function
to avoid cells with certain conditions (e.g. too small).
Condition takes in cell_index.
"""
closest_cell = 0
min_distance = np.linalg.norm(self.get_cell_real_centroid(0)-point)
for cell_index in range(1, self.get_number_of_cells()):
if condition(cell_index):
cell_centroid = self.get_cell_real_centroid(cell_index)
new_distance = np.linalg.norm(cell_centroid-point)
if new_distance < min_distance:
closest_cell = cell_index
min_distance = new_distance
return closest_cell
def subdivide_by_domain(self, cells):
""" Takes a collection of cells, and
seperates them from the rest of the domain
using lagrange multipliers at the sub-domain
boundary.
"""
lagrange_faces = []
for cell_index in cells:
for face_index in self.get_cell(cell_index):
neighboring_cells = self.face_to_cell[face_index]
if len(neighboring_cells)> 1:
cell1, cell2 = neighboring_cells
if cell1 == cell_index:
if cell2 not in cells:
lagrange_faces.append(face_index)
if cell2 == cell_index:
if cell1 not in cells:
lagrange_faces.append(face_index)
for face_index in lagrange_faces:
(cell1, cell2) = self.face_to_cell[face_index]
if cell1 in cells:
other_cell = cell2
else:
other_cell = cell1
new_face_index = self.add_face(self.get_face(face_index))
lagrange_face_index = self.add_face(self.get_face(face_index))
self.set_face_normal(new_face_index,
self.get_face_normal(face_index))
self.set_face_normal(lagrange_face_index,
self.get_face_normal(face_index))
self.set_face_real_centroid(new_face_index,
self.get_face_real_centroid(face_index))
self.set_face_real_centroid(lagrange_face_index,
self.get_face_real_centroid(face_index))
self.set_face_area(new_face_index,
self.get_face_area(face_index))
self.set_face_area(lagrange_face_index,
self.get_face_area(face_index))
self.add_boundary_face(100, new_face_index, 1)
self.add_boundary_face(100, face_index, 1)
faces_list = list(self.get_cell(other_cell))
local_face_index_in_other = faces_list.index(face_index)
new_cell_faces = self.get_cell(other_cell)
new_cell_faces[local_face_index_in_other] = new_face_index
def find_domain_faces(self, domain):
""" Identifies the faces on the boundary
of the domain.
"""
boundary_faces = []
boundary_orientation = []
for cell_index in self.get_cells_in_domain(domain):
cell_cell_normal = \
zip(self.get_cell(cell_index),
self.get_cell_normal_orientation(cell_index))
for (face_index, orientation) in cell_cell_normal:
neighboring_cells = self.face_to_cell[face_index]
if len(neighboring_cells)> 1:
cell1, cell2 = neighboring_cells
if cell1 == cell_index:
if cell2 not in self.get_cells_in_domain(domain):
boundary_faces.append(face_index)
boundary_orientation.append(orientation)
if cell2 == cell_index:
if cell1 not in self.get_cells_in_domain(domain):
boundary_faces.append(face_index)
boundary_orientation.append(orientation)
return (boundary_faces, boundary_orientation)
def construct_polygon_from_segs(self, segments):
""" Takes point pairs and constructs a single polygon
from joining all the ends. The pairs are identified
by directly comparing the point locations.
"""
## Start by setting the first point.
current_segments = list(segments)
new_face = [current_segments[0][0]]
point_to_match = current_segments[0][1]
current_segments.pop(0)
while len(current_segments)>0:
to_be_removed = None
hits = 0
for (index, segment) in enumerate(current_segments):
if np.linalg.norm(self.get_point(point_to_match)-
self.get_point(segment[0])) < 1.e-7:
new_face.append(segment[0])
to_be_removed = index
next_point_to_match = segment[1]
hits += 1
elif np.linalg.norm(self.get_point(point_to_match)-
self.get_point(segment[1])) < 1.e-7:
new_face.append(segment[1])
to_be_removed = index
next_point_to_match = segment[0]
hits += 1
try:
assert(hits == 1)
except:
for seg in current_segments:
print(self.get_point(seg[0]), self.get_point(seg[1]))
raise Exception("Faild at constructing polygon from segments")
current_segments.pop(to_be_removed)
point_to_match = next_point_to_match
return new_face
def divide_cell_by_plane(self, cell_index, point_on_plane, plane_normal):
""" Divides given cell into two cells
based on a plane specified by a point on the plane
and the plane normal.
"""
current_cell = self.get_cell(cell_index)
interior_face_segments = []
face_segments_to_be_added = {}
for face_index in current_cell:
face = self.get_face(face_index)
new_face_1 = []
new_face_2 = []
face_offset = list(face[1:]) + [face[0]]
intersection_switch = True
for (point_index, next_point_index) in zip(face, face_offset):
if intersection_switch:
new_face_1.append(point_index)
else:
new_face_2.append(point_index)
p1 = self.get_point(point_index)
p2 = self.get_point(next_point_index)
vector = p2 - p1
vector /= np.linalg.norm(vector)
d = np.dot((point_on_plane - p1), plane_normal)
denom = np.dot(vector, plane_normal)
if abs(denom) < 1e-10:
pass
else:
d /= denom
length = np.linalg.norm(p1-p2)
if d <= length+1.e-8 and d > 0.-1.e-8:
new_point_index = self.add_point(d*vector+p1)
new_face_1.append(new_point_index)
new_face_2.append(new_point_index)
if intersection_switch:
interior_face_segments.append([new_point_index])
else:
interior_face_segments[-1].append(new_point_index)
intersection_switch = not intersection_switch
if len(new_face_2) > 0:
self.set_face(face_index, new_face_1)
assert(len(new_face_1)>2)
(face_1_area,
face_1_centroid) = self.find_face_centroid(face_index)
self.set_face_real_centroid(face_index, face_1_centroid)
self.set_face_area(face_index, face_1_area)
new_face_index = self.add_face(new_face_2)
(face_area,
face_centroid) = self.find_face_centroid(new_face_index)
self.set_face_real_centroid(new_face_index, face_centroid)
self.set_face_area(new_face_index, face_area)
self.set_face_normal(new_face_index,
self.get_face_normal(face_index))
faces = self.get_cell(cell_index)
self.set_cell_faces(cell_index, list(faces)+[new_face_index])
cell_orientations = self.get_cell_normal_orientation(cell_index)
local_face_index = \
list(self.get_cell(cell_index)).index(face_index)
if self.is_boundary_face(face_index,
self.get_boundary_markers()):
boundary_marker = \
self.find_boundary_marker(face_index,
self.get_boundary_markers())
self.add_boundary_face(boundary_marker,
new_face_index,
cell_orientations[local_face_index])
self.set_cell_orientation(
cell_index,
np.array(list(cell_orientations)+
[cell_orientations[local_face_index]]))
cell_next_door = list(self.get_face_to_cell(face_index))
cell_next_door.remove(cell_index)
if len(cell_next_door) == 1:
next_door_faces = self.get_cell(cell_next_door[0])
next_door_local_face_index = \
list(next_door_faces).index(face_index)
next_door_faces = list(next_door_faces)+[new_face_index]
next_door_orientations = \
self.get_cell_normal_orientation(cell_next_door[0])
next_door_orientations = list(next_door_orientations) + \
[next_door_orientations[next_door_local_face_index]]
next_door_orientations = np.array(next_door_orientations)
self.set_cell_faces(cell_next_door[0], next_door_faces)
self.set_cell_orientation(cell_next_door[0],
next_door_orientations)
if cell_next_door[0] in face_segments_to_be_added:
face_segments_to_be_added[cell_next_door[0]]+= \
[interior_face_segments[-1]]
else:
face_segments_to_be_added[cell_next_door[0]]= \
[interior_face_segments[-1]]
if cell_index in face_segments_to_be_added:
interior_face_segments += face_segments_to_be_added[cell_index]
if len(interior_face_segments) > 0:
new_face = self.construct_polygon_from_segs(interior_face_segments)
for i in range(1):
v1 = self.get_point(new_face[i+1]) - self.get_point(new_face[i])
v2 = self.get_point(new_face[i]) - self.get_point(new_face[i-1])
new_face_normal = np.cross(v2, v1)
new_face_normal /= np.linalg.norm(new_face_normal)
new_face_index = self.add_face(new_face)
(face_area, face_centroid) = self.find_face_centroid(new_face_index)
self.set_face_real_centroid(new_face_index, face_centroid)
self.set_face_area(new_face_index, face_area)
new_face_normal = self.find_face_normal(new_face_index)
self.set_face_normal(new_face_index, new_face_normal)
faces_for_cell_1 = []
faces_for_cell_2 = []
normals_for_cell_1 = []
normals_for_cell_2 = []
for face_index in self.get_cell(cell_index):
current_center = self.get_face_real_centroid(face_index)
plane_to_center = point_on_plane - current_center
if np.dot(plane_to_center, plane_normal) > 0.:
faces_for_cell_1.append(face_index)
local_face_index = \
list(self.get_cell(cell_index)).index(face_index)
face_normal = self.get_cell_normal_orientation(cell_index)
face_normal = face_normal[local_face_index]
normals_for_cell_1.append(face_normal)
else:
faces_for_cell_2.append(face_index)
local_face_index = \
list(self.get_cell(cell_index)).index(face_index)
face_normal = self.get_cell_normal_orientation(cell_index)
face_normal = face_normal[local_face_index]
normals_for_cell_2.append(face_normal)
faces_for_cell_1.append(new_face_index)
faces_for_cell_2.append(new_face_index)
if np.dot(new_face_normal, plane_normal)>0.:
normals_for_cell_1.append(1)
normals_for_cell_2.append(-1)
else:
normals_for_cell_1.append(-1)
normals_for_cell_2.append(1)
self.set_cell_faces(cell_index, faces_for_cell_1)
self.set_cell_orientation(cell_index, normals_for_cell_1)
(cell_volume, cell_centroid) = self.find_volume_centroid(cell_index)
self.set_cell_real_centroid(cell_index, cell_centroid)
self.set_cell_volume(cell_index, cell_volume)
for face_index in faces_for_cell_2:
if cell_index in self.face_to_cell[face_index]:
self.remove_from_face_to_cell(face_index, cell_index)
new_cell_index = self.add_cell(faces_for_cell_2,
normals_for_cell_2)
(cell_volume, cell_centroid) = self.find_volume_centroid(new_cell_index)
self.set_cell_volume(new_cell_index, cell_volume)
self.set_cell_real_centroid(new_cell_index, cell_centroid)
self.set_cell_k(new_cell_index, self.get_cell_k(cell_index))
return new_cell_index
def build_frac_from_faces(self, faces, width = .0001):
""" Takes a list of face indices, and
extrudes them into cells.
"""
connections = []
non_connected_edges = []
for face in faces:
non_connected_edges.append([])
for local_edge_index in range(len(self.get_face(face))):
non_connected_edges[-1].append(local_edge_index)
for local_face_index in range(len(faces)):
current_face_points = list(self.get_face(faces[local_face_index]))
current_face_points.append(current_face_points[0])
for local_point_index in range(len(current_face_points)-1):
point_1 = \
self.get_point(current_face_points[local_point_index])
point_2 = \
self.get_point(current_face_points[local_point_index+1])
for local_face_index_2 in range(local_face_index+1,
len(faces)):
current_face_points_2 = \
list(self.get_face(faces[local_face_index_2]))
current_face_points_2.append(current_face_points_2[0])
for local_point_index_2 in range(len(current_face_points_2)-1):
point_1_2 = self.get_point(current_face_points_2[local_point_index_2])
point_2_2 = self.get_point(current_face_points_2[local_point_index_2+1])
if np.linalg.norm(abs(point_1-point_1_2)+abs(point_2-point_2_2))< 1.e-12:
connections.append([local_face_index,
local_face_index_2,
local_point_index,
local_point_index+1,
local_point_index_2,
local_point_index_2+1,
1])
if local_point_index in non_connected_edges[local_face_index]:
non_connected_edges[local_face_index].remove(local_point_index)
if local_point_index_2 in non_connected_edges[local_face_index_2]:
non_connected_edges[local_face_index_2].remove(local_point_index_2)
if np.linalg.norm(abs(point_2-point_1_2)+abs(point_1-point_2_2))< 1.e-12:
connections.append([local_face_index,
local_face_index_2,
local_point_index,
local_point_index+1,
local_point_index_2,
local_point_index_2+1,
0])
if local_point_index in non_connected_edges[local_face_index]:
non_connected_edges[local_face_index].remove(local_point_index)
if local_point_index_2 in non_connected_edges[local_face_index_2]:
non_connected_edges[local_face_index_2].remove(local_point_index_2)
##Find edges that have more than two connections
multiple_connection_indices = []
multiple_connection_groups = []
for (connection_index, connection) in enumerate(connections):
first_face = self.get_face(faces[connection[0]])
point1 = self.get_point(first_face[connection[2]])
point2 = self.get_point(first_face[connection[3]%len(first_face)])
multiple_connection_groups.append([])
for remote_connection_index in range(connection_index+1, len(connections)):
if remote_connection_index not in multiple_connection_indices:
remote_connection = connections[remote_connection_index]
first_face_remote = self.get_face(faces[remote_connection[0]])
point1_remote = self.get_point(first_face_remote[remote_connection[2]])
point2_remote = self.get_point(first_face_remote[remote_connection[3]%len(first_face_remote)])
if np.linalg.norm(abs(point1-point1_remote)+abs(point2-point2_remote))< 1.e-10 or\
np.linalg.norm(abs(point2-point1_remote)+abs(point1-point2_remote))< 1.e-10:
if len(multiple_connection_groups[-1]) == 0:
multiple_connection_groups[-1].append(connection_index)
multiple_connection_groups[-1].append(remote_connection_index)
multiple_connection_indices.append(connection_index)
multiple_connection_indices.append(remote_connection_index)
else:
multiple_connection_groups[-1].append(remote_connection_index)
multiple_connection_indices.append(remote_connection_index)
multiple_connection_groups = [x for x in multiple_connection_groups if len(x)>0]
new_multiple_connection_groups = []
## Switch from connection index to actual connections
for group in multiple_connection_groups:
new_multiple_connection_groups.append([])
for connection_index in group:
new_multiple_connection_groups[-1].append(list(connections[connection_index]))
multiple_connection_groups = new_multiple_connection_groups
connections_without_multiple = []
for connection_index in range(len(connections)):
if connection_index not in multiple_connection_indices:
connections_without_multiple.append(connections[connection_index])
subface_connections = []
## For multiple connections, the joining faces must be divided
## to two, a top and a bottom face.
for group in multiple_connection_groups:
done_faces = []
for connection in group:
current_face = connection[0]
full_face = self.get_face(faces[current_face])
point1 = self.get_point(full_face[connection[2]])
point2 = self.get_point(full_face[connection[3]%len(full_face)])
current_centroid = self.get_face_real_centroid(faces[current_face])
home_vector = current_centroid-(point1+point2)/2.
home_vector /= np.linalg.norm(home_vector)
norm1 = self.get_face_normal(faces[current_face])
max_top_angle = -999
max_top_connection_index = None
max_bot_angle = -999
max_bot_connection_index = None
for (connection_index, connection2) in enumerate(group):
if connection2[0] == current_face:
full_face_2 = self.get_face(faces[connection2[1]])
point1_2 = self.get_point(full_face_2[connection2[4]])
point2_2 = self.get_point(full_face_2[connection2[5]%len(full_face_2)])
centroid_2 = self.get_face_real_centroid(faces[connection2[1]])
current_vector = centroid_2-(point1_2+point2_2)/2.
current_vector /= np.linalg.norm(current_vector)
top_angle = np.dot(home_vector, current_vector)
if np.dot(current_vector, norm1) > 0.:
bottom_angle = -top_angle
top_angle += 2
else:
bottom_angle = top_angle+2
top_angle = -top_angle
if top_angle > max_top_angle:
max_top_angle = top_angle
max_top_connection_index = connection_index
if bottom_angle > max_bot_angle:
max_bot_angle = bottom_angle
max_bot_connection_index = connection_index
face2_top = group[max_top_connection_index][1]
face2_bot = group[max_bot_connection_index][1]
if ((current_face, 'TOP')) not in done_faces:
subface_connections.append(group[max_top_connection_index]+['TOP'])
done_faces.append((current_face, 'TOP'))
if group[max_top_connection_index][6] == 0:
done_faces.append((face2_top, 'TOP'))
else:
done_faces.append((face2_top, 'BOT'))
if ((current_face, 'BOT')) not in done_faces:
subface_connections.append(group[max_bot_connection_index]+['BOT'])
done_faces.append((current_face, 'BOT'))
if group[max_bot_connection_index][6] == 0:
done_faces.append((face2_bot, 'BOT'))
else:
done_faces.append((face2_bot, 'TOP'))
connections = connections_without_multiple
## Loop through all the connections, and find out which
## faces are to contribute to the normal calculation.
for connection in connections:
## The two faces already there
face_1 = connection[0]
face_2 = connection[1]
faces_for_point_1 = set([(connection[0], 0),
(connection[1], connection[6])])
faces_for_point_2 = set([(connection[0], 0),
(connection[1], connection[6])])
## Loop through all the connections, and find overlap
## between the local point indices.
for remote_connection in connections:
if remote_connection[0] == face_1 and \
remote_connection[1] == face_2:
pass
else:
if remote_connection[0] == face_1:
if connection[2] in remote_connection[2:4]:
faces_for_point_1.add((remote_connection[1],
remote_connection[6]))
if connection[3] in remote_connection[2:4]:
faces_for_point_2.add((remote_connection[1],
remote_connection[6]))
if remote_connection[1] == face_1:
if connection[2] in remote_connection[4:6]:
faces_for_point_1.add((remote_connection[0],
remote_connection[6]))
if connection[3] in remote_connection[4:6]:
faces_for_point_2.add((remote_connection[0],
remote_connection[6]))
if remote_connection[0] == face_2:
if connection[4] in remote_connection[2:4]:
if connection[6] == 1:
faces_for_point_1.add((remote_connection[1],
remote_connection[6]^connection[6]))
else:
faces_for_point_2.add((remote_connection[1],
remote_connection[6]^connection[6]))
if connection[5] in remote_connection[2:4]:
if connection[6] == 1:
faces_for_point_2.add((remote_connection[0],
remote_connection[6]^connection[6]))
else:
faces_for_point_1.add((remote_connection[0],
remote_connection[6]^connection[6]))
if remote_connection[1] == face_2:
if connection[4] in remote_connection[4:6]:
if connection[6] == 1:
faces_for_point_1.add((remote_connection[1],
remote_connection[6]^connection[6]))
else:
faces_for_point_2.add((remote_connection[1],
remote_connection[6]^connection[6]))
if connection[5] in remote_connection[4:6]:
if connection[6] == 1:
faces_for_point_2.add((remote_connection[0],
remote_connection[6]^connection[6]))
else:
faces_for_point_1.add((remote_connection[0],
remote_connection[6]^connection[6]))
connection += [faces_for_point_1, faces_for_point_2]
## Loop through all the connections, and find out which
## faces are to contribute to the normal calculation.
for connection in subface_connections:
## The two faces already there
face_1 = connection[0]
face_2 = connection[1]
faces_for_point_1 = set([(connection[0], 0),
(connection[1], connection[6])])
faces_for_point_2 = set([(connection[0], 0),
(connection[1], connection[6])])
connection += [faces_for_point_1, faces_for_point_2]
# Build the faces.
new_faces = []
## Maps the cells to the walls that make them.
## The cells are identified by the index of the
## generating face.
face_to_walls = {}
top_points = []
bot_points = []
mid_points = []
for face in range(len(faces)):
face_to_walls[face] = []
top_points.append([-1]*len(self.get_face(faces[face])))
bot_points.append([-1]*len(self.get_face(faces[face])))
mid_points.append([-1]*len(self.get_face(faces[face])))
for connection in connections:
norm1 = np.zeros(3)
for (local_face_index, orientation) in connection[7]:
if orientation == 0:
norm1 += self.get_face_normal(faces[local_face_index])
else:
norm1 -= self.get_face_normal(faces[local_face_index])
norm2 = np.zeros(3)
for (local_face_index, orientation) in connection[8]:
if orientation == 0:
norm2 += self.get_face_normal(faces[local_face_index])
else:
norm2 -= self.get_face_normal(faces[local_face_index])
norm1 /= np.linalg.norm(norm1)
norm2 /= np.linalg.norm(norm2)
width1 = width
full_face = self.get_face(faces[connection[0]])
point1 = -width1*norm1+self.get_point(full_face[connection[2]])
point2 = -width1*norm2+self.get_point(full_face[connection[3]%len(full_face)])
point3 = width1*norm2+self.get_point(full_face[connection[3]%len(full_face)])
point4 = width1*norm1+self.get_point(full_face[connection[2]])
point_1_index = self.add_point(point1)
point_2_index = self.add_point(point2)
point_3_index = self.add_point(point3)
point_4_index = self.add_point(point4)
new_face_index = self.add_face([point_1_index,
point_2_index,
point_3_index,
point_4_index,])
(area, centroid) = self.find_face_centroid(new_face_index)
current_face_normal = self.find_face_normal(new_face_index)
self.set_face_normal(new_face_index, current_face_normal)
self.set_face_real_centroid(new_face_index, centroid)
if self.has_face_shifted_centroid:
self.set_face_shifted_centroid(new_face_index, centroid)
self.set_face_area(new_face_index, area)
face_to_walls[connection[0]].append((new_face_index, 1))
face_to_walls[connection[1]].append((new_face_index, -1))
top_points[connection[0]][connection[2]] = point_4_index
top_points[connection[0]][connection[3]%
len(self.get_face(faces[connection[0]]))]=point_3_index
bot_points[connection[0]][connection[2]]=point_1_index
bot_points[connection[0]][connection[3]%
len(self.get_face(faces[connection[0]]))]=point_2_index
if connection[6] == 0:
top_points[connection[1]][connection[5]%
len(self.get_face(faces[connection[1]]))]=point_4_index
top_points[connection[1]][connection[4]]=point_3_index
bot_points[connection[1]][connection[5]%
len(self.get_face(faces[connection[1]]))]=point_1_index
bot_points[connection[1]][connection[4]]=point_2_index
else:
bot_points[connection[1]][connection[4]]=point_4_index
bot_points[connection[1]][connection[5]%
len(self.get_face(faces[connection[1]]))]=point_3_index
top_points[connection[1]][connection[4]]=point_1_index
top_points[connection[1]][connection[5]%
len(self.get_face(faces[connection[1]]))]=point_2_index
new_faces.append(new_face_index)
## Build the subfaces.
for connection in subface_connections:
norm1 = np.zeros(3)
for (local_face_index, orientation) in connection[8]:
if orientation == 0:
norm1 += self.get_face_normal(faces[local_face_index])
else:
norm1 -= self.get_face_normal(faces[local_face_index])
norm2 = np.zeros(3)
for (local_face_index, orientation) in connection[8]:
if orientation == 0:
norm2 += self.get_face_normal(faces[local_face_index])
else:
norm2 -= self.get_face_normal(faces[local_face_index])
norm1 /= np.linalg.norm(norm1)
norm2 /= np.linalg.norm(norm2)
width2 = width + .4*width
if connection[7] == 'TOP':
full_face = self.get_face(faces[connection[0]])
point1 = self.get_point(full_face[connection[2]])
point2 = self.get_point(full_face[connection[3]%len(full_face)])
point3 = width2*norm2+self.get_point(full_face[connection[3]%len(full_face)])
point4 = width2*norm1+self.get_point(full_face[connection[2]])
elif connection[7] == 'BOT':
full_face = self.get_face(faces[connection[0]])
point1 = -width2*norm1+self.get_point(self.get_face(faces[connection[0]])[connection[2]])
point2 = -width2*norm2+self.get_point(full_face[connection[3]%len(full_face)])
point3 = self.get_point(full_face[connection[3]%len(full_face)])
point4 = self.get_point(full_face[connection[2]])
point_1_index = self.add_point(point1)
point_2_index = self.add_point(point2)
point_3_index = self.add_point(point3)
point_4_index = self.add_point(point4)
new_face_index = self.add_face([point_1_index,
point_2_index,
point_3_index,
point_4_index,])
(area, centroid) = self.find_face_centroid(new_face_index)
current_face_normal = self.find_face_normal(new_face_index)
self.set_face_normal(new_face_index, current_face_normal)
self.set_face_real_centroid(new_face_index, centroid)
if self.has_face_shifted_centroid:
self.set_face_shifted_centroid(new_face_index, centroid)
self.set_face_area(new_face_index, area)
face_to_walls[connection[0]].append((new_face_index, 1))
face_to_walls[connection[1]].append((new_face_index, -1))
if connection[7] == 'TOP':
mid_points[connection[0]][connection[2]]=point_1_index
mid_points[connection[0]][connection[3]%
len(self.get_face(faces[connection[0]]))]=point_2_index
top_points[connection[0]][connection[3]%
len(self.get_face(faces[connection[0]]))]=point_3_index
top_points[connection[0]][connection[2]]=point_4_index
elif connection[7] == 'BOT':
bot_points[connection[0]][connection[2]]=point_1_index
bot_points[connection[0]][connection[3]%
len(self.get_face(faces[connection[0]]))]=point_2_index
mid_points[connection[0]][connection[2]]=point_4_index
mid_points[connection[0]][connection[3]%
len(self.get_face(faces[connection[0]]))]=point_3_index
if connection[7] == 'TOP':
if connection[6] == 0:
top_points[connection[1]][connection[5]%
len(self.get_face(faces[connection[1]]))]=point_4_index
top_points[connection[1]][connection[4]%
len(self.get_face(faces[connection[1]]))]=point_3_index
mid_points[connection[1]][connection[5]%
len(self.get_face(faces[connection[1]]))]=point_1_index
mid_points[connection[1]][connection[4]%
len(self.get_face(faces[connection[1]]))]=point_2_index
else:
bot_points[connection[1]][connection[4]]=point_4_index
bot_points[connection[1]][connection[5]%
len(self.get_face(faces[connection[1]]))]=point_3_index
mid_points[connection[1]][connection[4]]=point_1_index
mid_points[connection[1]][connection[5]%
len(self.get_face(faces[connection[1]]))]=point_2_index
if connection[7] == 'BOT':
if connection[6] == 0:
mid_points[connection[1]][connection[5]%
len(self.get_face(faces[connection[1]]))]=point_4_index
mid_points[connection[1]][connection[4]]=point_3_index
bot_points[connection[1]][connection[5]%
len(self.get_face(faces[connection[1]]))]=point_1_index
bot_points[connection[1]][connection[4]]=point_2_index
else:
mid_points[connection[1]][connection[4]]=point_4_index
mid_points[connection[1]][connection[5]%
len(self.get_face(faces[connection[1]]))]=point_3_index
top_points[connection[1]][connection[4]%
len(self.get_face(faces[connection[1]]))]=point_1_index
top_points[connection[1]][connection[5]%
len(self.get_face(faces[connection[1]]))]=point_2_index
new_faces.append(new_face_index)
for (local_face_index, face) in enumerate(non_connected_edges):
for point1 in face:
global_face_index = faces[local_face_index]
point2 = (point1+1)%len(self.get_face(global_face_index))
new_face_points = []
norm = self.get_face_normal(global_face_index)
width1 = width
if bot_points[local_face_index][point1] == -1:
new_point = -width1*norm+self.get_point(self.get_face(global_face_index)[point1])
point_1_index = self.add_point(new_point)
bot_points[local_face_index][point1] = point_1_index
else:
point_1_index = bot_points[local_face_index][point1]
new_face_points.append(point_1_index)
if bot_points[local_face_index][point2] == -1:
new_point = -width1*norm+self.get_point(self.get_face(global_face_index)[point2])
point_2_index = self.add_point(new_point)
bot_points[local_face_index][point2] = point_2_index
else:
point_2_index = bot_points[local_face_index][point2]
new_face_points.append(point_2_index)
if mid_points[local_face_index][point2] != -1:
new_face_points.append(mid_points[local_face_index][point2])
if top_points[local_face_index][point2] == -1:
new_point = width1*norm+self.get_point(self.get_face(global_face_index)[point2])
point_3_index = self.add_point(new_point)
top_points[local_face_index][point2] = point_3_index
else:
point_3_index = top_points[local_face_index][point2]
new_face_points.append(point_3_index)
if top_points[local_face_index][point1] == -1:
new_point = width1*norm+self.get_point(self.get_face(global_face_index)[point1])
point_4_index = self.add_point(new_point)
top_points[local_face_index][point1] = point_4_index
else:
point_4_index = top_points[local_face_index][point1]
new_face_points.append(point_4_index)
if mid_points[local_face_index][point1] != -1:
new_face_points.append(mid_points[local_face_index][point1])
new_face_index = self.add_face(new_face_points)
current_face_normal = self.find_face_normal(new_face_index)
self.set_face_normal(new_face_index, current_face_normal)
(area, centroid) = self.find_face_centroid(new_face_index)
self.set_face_real_centroid(new_face_index, centroid)
if self.has_face_shifted_centroid:
self.set_face_shifted_centroid(new_face_index, centroid)
self.set_face_area(new_face_index, area)
if np.dot(current_face_normal, centroid -self.get_face_real_centroid(global_face_index))> 0.:
self.add_internal_no_flow(new_face_index, 1)
else:
self.add_internal_no_flow(new_face_index, -1)
face_to_walls[local_face_index].append((new_face_index, 1))
new_faces.append(new_face_index)
## Adds the top and bottom faces.
for local_face_index in range(len(faces)):
new_face_points = top_points[local_face_index]
new_face_index = self.add_face(new_face_points)
face_to_walls[local_face_index].append((new_face_index, 1))
self.add_internal_no_flow(new_face_index, 1)
(area, centroid) = self.find_face_centroid(new_face_index)
current_face_normal = self.find_face_normal(new_face_index)
self.set_face_normal(new_face_index, current_face_normal)
self.set_face_real_centroid(new_face_index, centroid)
if self.has_face_shifted_centroid:
self.set_face_shifted_centroid(new_face_index, centroid)
self.set_face_area(new_face_index, area)
new_faces.append(new_face_index)
new_face_points = bot_points[local_face_index]
new_face_index = self.add_face(new_face_points)
face_to_walls[local_face_index].append((new_face_index, -1))
self.add_internal_no_flow(new_face_index, 1)
(area, centroid) = self.find_face_centroid(new_face_index)
current_face_normal = self.find_face_normal(new_face_index)
self.set_face_normal(new_face_index, current_face_normal)
self.set_face_real_centroid(new_face_index, centroid)
if self.has_face_shifted_centroid:
self.set_face_shifted_centroid(new_face_index, centroid)
self.set_face_area(new_face_index, area)
new_faces.append(new_face_index)
# Duplicate reservoir face for interior dirichlet boundary.
for face in face_to_walls:
top_res_face_index = faces[face]
if self.face_to_cell[top_res_face_index, 0] >= 0 and \
self.face_to_cell[top_res_face_index, 1] >= 0 :
bot_res_face_index = self.add_face(list(self.get_face(top_res_face_index)))
self.set_face_area(bot_res_face_index, self.get_face_area(top_res_face_index))
self.set_face_normal(bot_res_face_index, self.get_face_normal(top_res_face_index))
self.set_face_real_centroid(bot_res_face_index,
self.get_face_real_centroid(top_res_face_index))
if self.has_face_shifted_centroid:
self.set_face_shifted_centroid(bot_res_face_index,
self.get_face_real_centroid(top_res_face_index))
bottom_cell = self.face_to_cell[top_res_face_index, 1]
new_cell_faces = array.array('i', self.get_cell(bottom_cell))
local_face_index_in_cell = list(new_cell_faces).index(top_res_face_index)
new_cell_faces[local_face_index_in_cell] = bot_res_face_index
top_cell_index = self.face_to_cell[top_res_face_index, 0]
local_top_face_index_in_cell = list(self.get_cell(top_cell_index)).index(top_res_face_index)
top_res_face_orientation = \
self.get_cell_normal_orientation(top_cell_index)[local_top_face_index_in_cell]
self.remove_from_face_to_cell(top_res_face_index, bottom_cell)
self.set_cell_faces(bottom_cell, new_cell_faces)
else:
raise Exception("Face on boundary encountered")
new_cell_index = self.add_cell(array.array('i', [x[0] for x in face_to_walls[face]]),
array.array('i', [x[1] for x in face_to_walls[face]]))
self.set_cell_domain(new_cell_index, 1)
(volume, centroid) = self.find_volume_centroid(new_cell_index)
self.set_cell_volume(new_cell_index, volume)
self.set_cell_real_centroid(new_cell_index, centroid)
if self.has_cell_shifted_centroid:
self.set_cell_shifted_centroid(new_cell_index, centroid)
self.set_cell_k(new_cell_index, np.eye(3)*1.)
self.set_forcing_pointer(new_cell_index,
[top_res_face_index, bot_res_face_index],
[top_res_face_orientation, -top_res_face_orientation])
self.set_dirichlet_face_pointer(top_res_face_index,
top_res_face_orientation,
new_cell_index)
self.set_dirichlet_face_pointer(bot_res_face_index,
-top_res_face_orientation,
new_cell_index)
self.output_vtk_faces("new_faces", new_faces)
def build_mesh(self):
""" Base class function for constructing the mesh.
"""
raise NotImplementedError
|
def look_up_word_value(words):
"""
---------------------------------------------------------------------
DESCRIPTION
Translates the word (string) array into a floating-point value array.
---------------------------------------------------------------------
PARAMETERS
words (string array): The array of words to convert into a floating-
point value array.
---------------------------------------------------------------------
"""
the_dictionary = {}
word_num = 0
the_list_of_words = open("C:/YourShortListOfWords.txt", "r")
the_text_within = the_list_of_words.read()
for line in the_text_within.split('\n'):
# print(line+":"+str(word_num))
the_dictionary[line] = word_num
word_num = word_num + 1
looked_up_array = []
for word in words:
looked_up_array.append(int(the_dictionary[word]))
# print(looked_up_array)
real_looked_up_array = []
for word_val in looked_up_array:
real_looked_up_array.append(word_val / 10000)
return real_looked_up_array
def look_up_word_for_value(word_values):
"""
---------------------------------------------------------------------
DESCRIPTION
Translates the floating-point value array into a word (string) array.
---------------------------------------------------------------------
PARAMETERS
wordvalues (floating-point value array): The array of floating-point
values to convert into a word (string) array.
---------------------------------------------------------------------
"""
word_list_here = []
the_list_of_words_here = open("C:/YourShortListOfWords.txt", "r")
the_word_list_within = the_list_of_words_here.read()
for line in the_word_list_within.split('\n'):
word_list_here.append(line)
output_word_list_here = []
for word_value in word_values:
output_word_list_here.append(word_list_here[int(word_value * 10000)])
return output_word_list_here
def is_valid_word_array(words_to_check):
"""
---------------------------------------------------------------------
DESCRIPTION
Checks if the words in the word (string) array are part of the
dictionary.
---------------------------------------------------------------------
PARAMETERS
words_to_check (string array): The array of words to check for in the
dictionary.
---------------------------------------------------------------------
"""
valid = True
try:
look_up_word_value(words_to_check)
except:
valid = False
return valid
def add_word_to_dictionary(word_to_add):
"""
---------------------------------------------------------------------
DESCRIPTION
Adds a word to the dictionary file, if it does not already exist.
---------------------------------------------------------------------
PARAMETERS
word_to_add (string): The word to add to the dictionary.
---------------------------------------------------------------------
"""
list_of_exist_words = open("C:/YourShortListOfWords.txt", "r")
existing_words = list_of_exist_words.read()
not_taken = True
for ExistLine in existing_words.split('\n'):
if ExistLine.lower() == word_to_add:
not_taken = False
if not_taken:
ready_to_add = open("C:/YourShortListOfWords.txt", "a")
ready_to_add.write("\n" + word_to_add.lower())
def pad_word_array(word_array_to_pad, input_size):
"""
---------------------------------------------------------------------
DESCRIPTION
Pads the word array with ^ to reshape it to the network's input size,
or trims it if necessary. Otherwise, leaves it unchanged.
---------------------------------------------------------------------
PARAMETERS
word_array_to_pad (string array): The word array to pad.
input_size (integer): The input size the neural network expects.
---------------------------------------------------------------------
"""
if len(word_array_to_pad) > input_size:
return word_array_to_pad[0:input_size]
elif len(word_array_to_pad) == input_size:
return word_array_to_pad
elif len(word_array_to_pad) < input_size:
padded_word_array = word_array_to_pad
for PadChar in range(input_size - len(word_array_to_pad)):
padded_word_array.append("^")
return padded_word_array
def easy_convert_sentence_to_values(sentence_array, input_size):
"""
---------------------------------------------------------------------
DESCRIPTION
Converts the array of sentences to an array of word value arrays. If
necessary, they might be padded.
---------------------------------------------------------------------
PARAMETERS
sentence_array (string array): The sentence array to convert.
input_size (integer): The input size the neural network expects.
---------------------------------------------------------------------
"""
arr_of_token_wrd_arrs = []
# Tokenizes each sentence in arr_of_token_wrd_arrs
import nltk
for SentenceToTokenize in sentence_array:
arr_of_token_wrd_arrs.append(pad_word_array(nltk.word_tokenize(SentenceToTokenize), input_size))
# Checks the validity of arr_of_token_wrd_arrs, extending the dictionary if necessary
for WordArray in arr_of_token_wrd_arrs:
for Word in WordArray:
if is_valid_word_array([Word]):
print(Word + " is a valid word.")
else:
add_word_to_dictionary(Word)
# Converts arr_of_token_wrd_arrs to an array of word value arrays
arr_of_wrd_val_arrs = []
for WordArrayToConvert in arr_of_token_wrd_arrs:
arr_of_wrd_val_arrs.append(look_up_word_value(WordArrayToConvert))
return arr_of_wrd_val_arrs
'''
#Keras Example Below
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.optimizers import SGD
import numpy as np
#The idea here is to output only one of the inputs (remove redundancy).
#For some reason, the outputs I got had similar values (so the outputs started with the same letter) when the dictionary file
#contained a long list of alphabetically-arranged words.
#I would appreciate it if anyone can help fix this bug.
#Here is the input data
X = np.array(EasyConvertSentenceToValues(["code code","program program","pet pet"],9))
#Here is the output data
y = np.array(EasyConvertSentenceToValues(["code","program","pet"],1))
model = Sequential()
model.add(Dense(8, input_dim=9))
model.add(Activation('tanh'))
model.add(Dense(6))
model.add(Activation('sigmoid'))
model.add(Dense(1))
model.add(Activation('sigmoid'))
sgd = SGD(lr=0.1)
model.compile(loss='binary_crossentropy', optimizer=sgd)
model.fit(X, y, batch_size=1, nb_epoch=100)
print(model.predict_proba(X))
for whatever in model.predict_proba(X).tolist():
for theThing in whatever:
print(LookUpWordForValue([round(theThing,1000)]))
'''
|
print("--- 아르바이트 급여 계산 프로그램 ---")
print("--- 2021년 최저시급은 8720원입니다 ---")
print("")
mywage = 0
totalwage = 0
basic = int(input("시급을 입력하세요: "))
print("")
print("[시급]")
print("*** 주간근무 :", basic, "원 ***")
print("*** 야간근무 : 주간 시급 * 1.5 ***")
print("")
while True:
select = input("주간근무 or 야간근무를 입력하세요 - - - >")
worktime = int(input("근무 시간을 입력해 주세요 - - - >"))
insurance = input("공제할 항목 소득세 or 4대보험 고르세요: ")
print("")
if worktime >= 15:
plus = int(input("주휴수당이 발생하였습니다. 하루 일급을 입력해주세요: "))
print("")
if select == '주간근무' and insurance == '소득세':
mywage = basic*worktime+plus
totalwage = mywage-mywage*0.033
elif select == '주간근무' and insurance == '4대보험':
mywage = (basic*worktime+plus)
totalwage = mywage-mywage*0.0913
elif select == '야간근무' and insurance == '소득세':
mywage = basic*worktime*1.5+plus
totalwage = mywage-mywage*0.033
else:#추가
mywage = basic*worktime*1.5+plus
totalwage = mywage-mywage*0.0913
print(worktime, "시간 동안",select,"에 일을 한 급여는 ",mywage, "입니다.")
print("보험료를 공제한 급여는 ",totalwage, "입니다.")
else:
if select == '주간근무' and insurance == '소득세':
mywage = basic*worktime
totalwage = mywage-mywage*0.033
elif select == '주간근무' and insurance == '4대보험':
mywage = (basic*worktime)
totalwage = mywage-mywage*0.0913
elif select == '야간근무' and insurance == '소득세':
mywage = basic*worktime*1.5
totalwage = mywage-mywage*0.033
else:#추가
mywage = basic*worktime*1.5
totalwage = mywage-mywage*0.0913
print(worktime, "시간 동안",select,"에 일을 한 급여는 ",mywage, "입니다.")
print("보험료를 공제한 급여는 ",totalwage, "입니다.")
print("")
print("끝!")
break
|
#fibonacci numbers
def fibonacci(N):
count = 1
i = 0
j = 1
if N == 0:
return 0
else:
while count != N:
temp = i + j
i = j
j = temp
count += 1
return j
num = 30
print(fibonacci(num)) |
import random
num_rand = random.randint(0,100) # a number between 0 and 99
cont = 6 # chances
adm = True # for while exit
while adm :
resp_user = int(input("Guess a number between 0 to 100 > "))
cont -= 1
if resp_user > num_rand :
print("Your number is higher, Try again :(")
print("You have {} attempts".format(cont))
if cont == 0 :
print("Your attempts are over :(\nThe number was {}".format(num_rand))
adm = False
elif resp_user < num_rand :
print("Your number is lower ,try again :(")
print("You have {} attempts".format(cont))
if cont == 0 :
print("Your attempts are over :(\nThe number was {}".format(num_rand))
adm = False
elif resp_user == num_rand :
print("############################")
print("Congratulations! You Won! :D\nThe number was {}.".format(num_rand))
print("############################")
adm = False
|
from bs4 import BeautifulSoup as bs
import re
html_doc="""
<html>
<head>
<title>
The Dormouse's story
</title>
</head>
<body>
<p class="title">
<b>
The Dormouse's story
</b>
</p>
<p class="story">
Once upon a time there were three little sisters; and their names were
<a class="sister" href="http://example.com/elsie" id="link1">
Elsie
</a>
,
<a class="sister" href="http://example.com/lacie" id="link2">
Lacie
</a>
and
<a class="sister" href="http://example.com/tillie" id="link2">
Tillie
</a>
; and they lived at the bottom of a well.
</p>
<p class="story">
...
</p>
</body>
</html>
"""
soup = bs(html_doc,"html.parser")
print(soup.title.string)
for x in soup.find_all(re.compile("^b")):
print(x.name)
#输出文档中所有的A标签中的href=HTTP://example.com/的网址
data = soup.find_all("a",href=re.compile("^http://example.com/"))
print(data) |
import random
a = random.randint(1,9)
guess = int(input("请输入一个数值,与改随机数比较:"))
while guess != a:
if guess > a:
print("大了")
elif guess < a:
print("小了")
guess = int(input("猜错了,再给你一次机会:"))
if guess == a:
print("你真厉害,猜对了")
else:
if guess > a:
print("你猜大了")
else:
print("你猜小了")
print("游戏结束") |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
*******
Bad CSV
*******
Convert bad a badly formatted CSV to a good one.
This is using the function of the table file to
convert the CSV in a correct manner.
"""
import six
from csv_tools import table
__author__ = "Daniel Melichar"
__copyright__ = "Copyright 2015"
__credits__ = ["Daniel Melichar"]
__license__ = "GPL"
__version__ = "1.0"
__maintainer__ = "Daniel Melichar"
__email__ = "dmelichar@student.tgm.ac.at"
__status__ = "Deployed"
def bad_csv(f, **kwargs):
"""
Convert a CSV into a new CSV by normalizing types and correcting for other anomalies.
:param f: Badly formatted CSV-File
:type f: File
"""
tab = table.Table.from_csv(f, **kwargs)
o = six.StringIO()
output = tab.to_csv(o)
output = o.getvalue()
o.close()
return output |
"""
Author: David Thong Nguyen
Date Created: Nov 15th, 2013
Date Modified: Nov 17th, 2013
- tested random damage multiplier [8,9]
- decided multiplier's optimal range: [8,10]
--> Damage is quite balanced
NEXT OBJECTIVES:
+ add evasion system/check accuracy
"""
import random
import math
def normalHit(attacker,target):
damage = physDamage(attacker,target)
if critHit(attacker,target) == True:
damage = int(round((damage*attacker.CRITDMG),0))
print("\n",attacker.name," inflicts ",damage,\
" damage on ",target.name,"!",sep="")
print("It's a critical hit!")
else:
print("\n",attacker.name," inflicts ",damage,\
" damage on ",target.name,"!",sep="")
if damage > 0:
target.HP -= damage
elif damage <= 0:
print(attacker.name,"missed.")
def critHit(attacker,target):
critChance = int(round(((attacker.CRITRATE/target.CRITRES) * 2.5),0))
RNGList = []
for x in range(0,critChance):
RNG = random.randint(0,100)
if RNG == critChance:
return True
else:
RNGList.append(RNG)
return False
def physDamage(attacker,target):
return int(round(math.sqrt((attacker.PATK / target.PDEF)\
* random.randrange(8,10) / 10) * 22,0))
def magDamage(attacker,target):
return int(round(math.sqrt((attacker.MATK / target.MDEF)\
* random.randrange(8,10) / 10) * 22,0))
|
"""Busca binária"""
def binary_search(array, item, begin=0, end=None):
"""
Utiliza do algoritmo de busca binária para encontrar um ítem em uma lista. Partindo do pressuposto que o array esteja ordenado.
:param array: lista em que será feita a busca.
:param item: o ítem que está sendo pesquisado.
:param begin: posição inicial da busca.
:param end: posição final da busca.
:return: posição do ítem caso esse seja encontrado. None caso contrário.
"""
if end is None: # Se o end é None, então estamos fazendo a primeira chamada à função
end = len(array) - 1 # Logo a posição final deve ser o tamanho da lista - 1
if begin <= end: # Se a sublista é válida
m = (begin + end) // 2 # Meio da lista
if array[m] == item: # Se o meio da lista é o elemento que estamos pesquisando
return m
if item < array[m]: # Se o ítem pesquisado for menor que o ítem que está no meio da lista
return binary_search(array, item, begin, m - 1) # Faça a pesquisa pela esquerda
return binary_search(array, item, m + 1, end) # Senão, quer dizer que ele está a direita da lista
return None # Caso o elemento não esteja na lista retorne None
if __name__ == '__main__':
lista = [i/5 for i in range(10000000)]
busca = [1, 87, 93812, 90000, 12, 15, -3, 0, -1, 90, 12222]
for b in busca:
indice = binary_search(lista, b)
if indice is not None:
print(f'O elemento {b} está na posição {indice}')
else:
print(f'O elemento {b} não está na lista.')
|
class Solution:
# 迭代
def inorderTraversal(self, root: TreeNode) -> List[int]:
stack = []
cur = root
res = []
while stack or cur:
while cur:
stack.append(cur)
cur = cur.left
cur = stack.pop()
res.append(cur.val)
cur = cur.right
return res
# 递归
def inorder(self, root: TreeNode) -> List[int]:
if not root:
return []
return self.inorder(self.left) + [root.val] + self.inorder(self.right) |
import informedSearch
import random
import time
# Module Classes
class sixteenPuzzleState:
def __init__(self, numbers):
"""
Constructs a new 16 puzzle from an ordering of numbers.
numbers: a list of integers from 0 to 15 representing an
instance of the eight puzzle. 0 represents the blank
space. Thus, the list
[1, 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
represents the 16 puzzle:
---------------------
| 1 | | 2 | 3 |
---------------------
| 4 | 5 | 6 | 7 |
---------------------
| 8 | 9 | 10 | 11 |
---------------------
| 12 | 13 | 14 | 15 |
---------------------
The configuration of the puzzle is stored in a 2-dimensional
list (a list of lists) 'cells'.
"""
self.cells = []
numbers = numbers[:] # Make a copy so as not to cause side-effects.
numbers.reverse()
for row in range(4):
self.cells.append([])
for col in range(4):
self.cells[row].append(numbers.pop())
if self.cells[row][col] == 0:
self.blankLocation = row, col
def isGoal(self):
"""
Checks to see if the puzzle is in its goal state.
---------------------
| 1 | 2 | 3 | 4 |
---------------------
| 5 | 6 | 7 | 8 |
---------------------
| 9 | 10 | 11 | 12 |
---------------------
| 13 | 14 | 15 | |
---------------------
"""
current = 1
for row in range(4):
for col in range(4):
if current != self.cells[row][col]:
return False
current += 1
if current == 16:
return True
return True
def legalMoves(self):
"""
Returns a list of legal moves from the current state.
Moves consist of moving the blank space up, down, left or right.
These are encoded as 'up', 'down', 'left' and 'right' respectively.
"""
moves = []
row, col = self.blankLocation
if row != 0:
moves.append('up')
if col != 0:
moves.append('left')
if row != 3:
moves.append('down')
if col != 3:
moves.append('right')
return moves
def result(self, move):
"""
Returns a new sixteenPuzzle with the current state and blankLocation
updated based on the provided move.
The move should be a string drawn from a list returned by legalMoves.
Illegal moves will raise an exception, which may be an array bounds
exception.
NOTE: This function *does not* change the current object. Instead,
it returns a new object.
"""
row, col = self.blankLocation
if move == 'up':
newrow = row - 1
newcol = col
elif move == 'down':
newrow = row + 1
newcol = col
elif move == 'left':
newrow = row
newcol = col - 1
elif move == 'right':
newrow = row
newcol = col + 1
else:
raise "Illegal Move"
# Create a copy of the current sixteenPuzzle
newPuzzle = sixteenPuzzleState([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
newPuzzle.cells = [values[:] for values in self.cells]
# And update it to reflect the move
newPuzzle.cells[row][col] = self.cells[newrow][newcol]
newPuzzle.cells[newrow][newcol] = self.cells[row][col]
newPuzzle.blankLocation = newrow, newcol
return newPuzzle
# Utilities for comparison and display
def __eq__(self, other):
for row in range(4):
if self.cells[row] != other.cells[row]:
return False
return True
def __hash__(self):
return hash(str(self.cells))
def __getAsciiString(self):
"""
Returns a display string for the maze
"""
lines = []
horizontalLine = ('-' * (21))
lines.append(horizontalLine)
for row in self.cells:
rowLine = '|'
for col in row:
if col <= 9:
if col == 0:
col = ' '
rowLine = rowLine + ' ' + col.__str__() + ' |'
else:
rowLine = rowLine + ' ' + col.__str__() + ' |'
lines.append(rowLine)
lines.append(horizontalLine)
return '\n'.join(lines)
def __str__(self):
return self.__getAsciiString()
# TODO: Implement The methods in this class
class SixteenPuzzleSearchProblem(informedSearch.SearchProblem):
"""
Implementation of a SearchProblem for the sixteen Puzzle domain
Each state is represented by an instance of an sixteenPuzzle.
"""
def __init__(self, puzzle):
"Creates a new sixteen PuzzleSearchProblem which stores search information."
self.puzzle = puzzle
def getStartState(self):
return puzzle
def isGoalState(self, state):
return state.isGoal()
def getSuccessors(self, state):
"""
Returns list of (successor, action, stepCost) pairs where
each succesor is either left, right, up, or down
from the original state and the cost is 1.0 for each
"""
succ = []
for a in state.legalMoves():
succ.append((state.result(a), a, 1))
return succ
def getInverseAction(self,action):
if action == 'up':
return 'down'
elif action == 'left':
return 'right'
elif action == 'right':
return 'left'
elif action == 'down':
return 'up'
def getCostOfActions(self, actions):
"""
actions: A list of actions to take
This method returns the total cost of a particular sequence of actions. The sequence must
be composed of legal moves
"""
return len(actions)
def HeuristicOne(state, problem):
'''heuristic 1: number of misplaced tiles'''
goalState = sixteenPuzzleState([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0]).cells
state = state.cells
heuristic = 0
for row in range(4):
for col in range(4):
if state[row][col] != goalState[row][col]:
heuristic = heuristic + 1
return heuristic
def HeuristicTwo(state, problem):
'''heuristic 2: manhattan distance'''
goalState = sixteenPuzzleState([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0]).cells
state = state.cells
heuristic = 0
for goalRow in range(4):
for goalCol in range(4):
for row in range(4):
for col in range(4):
if goalState[goalRow][goalCol] != 0:
if state[row][col] == goalState[goalRow][goalCol]:
heuristic = heuristic + manhattanDistance([row, col], [goalRow, goalCol])
return heuristic
def manhattanDistance(xy1, xy2):
"Returns the Manhattan distance between points xy1 and xy2"
return abs(xy1[0] - xy2[0]) + abs(xy1[1] - xy2[1])
def createRandomSixteenPuzzle(moves=100):
"""
moves: number of random moves to apply
Creates a random eight puzzle by applying
a series of 'moves' random moves to a solved
puzzle.
"""
puzzle = sixteenPuzzleState([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0])
for i in range(moves):
# Execute a random legal move
puzzle = puzzle.result(random.sample(puzzle.legalMoves(), 1)[0])
return puzzle
if __name__ == '__main__':
#puzzle_random2 = createRandomSixteenPuzzle(100)
puzzle_first_configuration = sixteenPuzzleState([9, 5, 7, 4, 1, 0, 3, 8, 13, 10, 2, 12, 14, 6, 11, 15])
puzzle_second_configuration = sixteenPuzzleState([3, 6, 9, 4, 5, 2, 8, 11, 10, 0, 15, 7, 13, 1, 14, 12])
puzzle_piazza = sixteenPuzzleState([5,3,0,4,7,2,6,8,1,9,10,11,13,14,15,12])
puzzle_random1 = sixteenPuzzleState([0,2,1,3,5,11,7,4,6,9,10,8,13,14,15,12])
puzzle_random2 = sixteenPuzzleState([5,1,3,2,10,0,4,7,6,9,11,8,13,14,15,12])
NonePuzzle = sixteenPuzzleState([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
puzzle_num = int(raw_input(
'Choose the configuration:\n'
'1 - the first given configuration on blackboard\n'
'2 - the second given configuration on blackboard\n'
'3 - the given configuration on Piazza\n'
'4 - No.1 random generated configuration\n'
'5 - No.2 random generated configuration\n'
'Then press enter: '))
print '---------------------'
if puzzle_num == 1:
puzzle = puzzle_first_configuration
elif puzzle_num == 2:
puzzle = puzzle_second_configuration
elif puzzle_num == 3:
puzzle = puzzle_piazza
elif puzzle_num == 4:
puzzle = puzzle_random1
elif puzzle_num == 5:
puzzle = puzzle_random2
else:
print 'You have entered an wrong number, please run again!'
problem = SixteenPuzzleSearchProblem(puzzle)
heuristic_num = int(raw_input(
'Choose the heuristic function\n1 - number of misplaced tiles\n2 - manhattan distance\nThen press enter: '))
print '---------------------'
if heuristic_num == 1:
heuristic = HeuristicOne
elif heuristic_num == 2:
heuristic = HeuristicTwo
else:
print 'You have entered an wrong number, please run again!'
algorithm_num = int(raw_input(
'Choose the algorithm you want to implement\n1 - A*\n2 - IDA*\n3 - AWA*\n4 - ARA*\nThen press enter: '))
print('Your chosen puzzle:')
print(puzzle)
print 'Running...'
print '---------------------'
time_start = time.time()
if algorithm_num == 1:
path = informedSearch.aStarSearch(problem,heuristic)
elif algorithm_num == 2:
path = informedSearch.IDAStarSearch(problem,heuristic)
elif algorithm_num == 3:
path = informedSearch.AnytimeWAstarSearch(problem, NonePuzzle,heuristic)
elif algorithm_num == 4:
path = informedSearch.AnytimeReparingAstarSearch(problem, NonePuzzle,heuristic)
else:
print 'You have entered an wrong number, please run again!'
time_end = time.time()
print '\a'
print('Algorithm found the optimal solution of %d moves: %s' % (len(path), str(path)))
print '---------------------'
print 'Total running rime:', time_end - time_start, 's'
print '---------------------'
curr = puzzle
i = 1
for a in path:
curr = curr.result(a)
print('After %d move%s: %s' % (i, ("", "s")[i > 1], a))
print(curr)
raw_input("Press return for the next state...") # wait for key stroke
i += 1
|
"""
⒈ 从第一个元素开始,该元素可以认为已经被排序
⒉ 取出下一个元素,在已经排序的元素序列中从后向前扫描
⒊ 如果该元素(已排序)大于新元素,将该元素移到下一位置
⒋ 重复步骤3,直到找到已排序的元素小于或者等于新元素的位置
⒌ 将新元素插入到下一位置中
⒍ 重复步骤2~5
"""
# debug rang(i, 0, -1) 改成 range(i, -1, -1)
# 不然只有第一遍历会让第一个和第二值比较
import random
list1 = [1, 3, 5, 6, 2, 4]
Range = 100
Length = 6
list = random.sample(range(Range),Length)
def insert(list):
for i in range(0, len(list) -1):
for j in range(i, -1, -1):
if list[j + 1] < list[j]:
list[j + 1], list[j] = list[j], list[j + 1]
return list
|
#!/usr/bin/env python
PEOPLE_COLUMNS = (
("Name", str), ("Age", int), ("Gender", str), ("Height", int))
PEOPLE = (
("John", 52, "male", 175),
("Alice", 34, "female", 184),
("Bob", 31, "male", 156),
("Jane", 38, "female", 164)
)
def compute():
for row in PEOPLE:
yield row
# dataset description
NAME = 'People'
COLUMNS = PEOPLE_COLUMNS
LENGTH = len(PEOPLE)
COMPUTE_CALLBACK = compute
|
'''
As long as you have a URL, the webbrowser module lets users cut out the step of
opening the browser and directing themselves to a website. Other programs could
use this functionality to do the following:
AIM: Open the browser to the URL for your local weather.
'''
####### LIBRARIES WE'RE GOING TO NEED #######
# WEBBROWSER: to open links in a browser #
# GEOCODER: to fetch the user's geolocation #
#############################################
import webbrowser, geocoder
# 1. We need to get the user's location first. We'll use the user's IP:
g = geocoder.ip('me')
lat = str(g.latlng[0])
long = str(g.latlng[1])
# 2. We are going to use Yandex Pogoda, since the building of the URL
# is pretty easy once we have the latitude and longitude.
link = 'https://www.yandex.ru/pogoda/moscow?'
query_link = link + 'lat=' + lat + '&lon=' + long + '&via=srp'
webbrowser.open_new_tab(query_link)
# Tadaa!
|
from abc import ABCMeta
from abc import abstractmethod
# simple Abastract Base Class demo (Not exactly what I wnat....
# anyway......
class Foo(object):
def oop_trash(self):
return "agreement from Foo"
class LayerMeta(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
raise NotImplementedError
@abstractmethod
def __getitem__(self):
raise NotImplementedError
def getitem(self, index):
return self.__getitem__(index)
@classmethod
def __subclasshook__(cls, C):
if cls is LayerMeta:
if any("oop_trash" in base.__dict__ for base in C.__mro__):
return True
return NotImplementedError
LayerMeta.register(Foo) # Now the LayerMeta has attribute
class LayerFoo(LayerMeta):
def __init__(self):
print "OOP sucks"
def __getitem__(self, index):
return "Foo is Here {0}".format(index)
def oop_trash(self):
return False
if __name__ == "__main__":
layer, n_vis, n_hidden = [None] * 3
print dir(LayerMeta)
assert issubclass(Foo, LayerMeta)
m = LayerFoo()
print m.oop_trash()
# m = LayerMeta([19, 12])
# print LayerMeta()(10, 10)
# print dir(LayerMeta())
# print tuple.__mro__
# print dir(iter(range(10)))
# print dir(tuple)
|
def recurrent(*args, **kwargs):
"""Wraps an apply method to allow its iterative application.
This decorator allows you to implement only one step of a recurrent
network and enjoy applying it to sequences for free. The idea behind is
that its most general form information flow of an RNN can be described
as follows: depending on the context and driven by input sequences the
RNN updates its states and produces output sequences.
Given a method describing one step of an RNN and a specification
which of its inputs are the elements of the input sequence,
which are the states and which are the contexts, this decorator
returns an application method which implements the whole RNN loop.
The returned application method also has additional parameters,
see documentation of the `recurrent_apply` inner function below.
Parameters
----------
sequences : list of strs
Specifies which of the arguments are elements of input sequences.
states : list of strs
Specifies which of the arguments are the states.
contexts : list of strs
Specifies which of the arguments are the contexts.
outputs : list of strs
Names of the outputs. The outputs whose names match with those
in the `state` parameter are interpreted as next step states.
Returns
-------
recurrent_apply : :class:`~blocks.bricks.base.Application`
The new application method that applies the RNN to sequences.
See Also
--------
:doc:`The tutorial on RNNs </rnn>`
"""
def recurrent_wrapper(application_function):
arg_spec = inspect.getargspec(application_function)
arg_names = arg_spec.args[1:]
@wraps(application_function)
def recurrent_apply(brick, application, application_call,
*args, **kwargs):
"""Iterates a transition function.
Parameters
----------
iterate : bool
If ``True`` iteration is made. By default ``True``.
reverse : bool
If ``True``, the sequences are processed in backward
direction. ``False`` by default.
return_initial_states : bool
If ``True``, initial states are included in the returned
state tensors. ``False`` by default.
"""
# Extract arguments related to iteration and immediately relay the
# call to the wrapped function if `iterate=False`
iterate = kwargs.pop('iterate', True)
if not iterate:
return application_function(brick, *args, **kwargs)
reverse = kwargs.pop('reverse', False)
return_initial_states = kwargs.pop('return_initial_states', False)
# Push everything to kwargs
for arg, arg_name in zip(args, arg_names):
kwargs[arg_name] = arg
# Make sure that all arguments for scan are tensor variables
scan_arguments = (application.sequences + application.states +
application.contexts)
for arg in scan_arguments:
if arg in kwargs:
if kwargs[arg] is None:
del kwargs[arg]
else:
kwargs[arg] = tensor.as_tensor_variable(kwargs[arg])
# Check which sequence and contexts were provided
sequences_given = dict_subset(kwargs, application.sequences,
must_have=False)
contexts_given = dict_subset(kwargs, application.contexts,
must_have=False)
# Determine number of steps and batch size.
if len(sequences_given):
# TODO Assumes 1 time dim!
shape = list(sequences_given.values())[0].shape
n_steps = shape[0]
batch_size = shape[1]
else:
# TODO Raise error if n_steps and batch_size not found?
n_steps = kwargs.pop('n_steps')
batch_size = kwargs.pop('batch_size')
# Handle the rest kwargs
rest_kwargs = {key: value for key, value in kwargs.items()
if key not in scan_arguments}
for value in rest_kwargs.values():
if (isinstance(value, Variable) and not
is_shared_variable(value)):
logger.warning("unknown input {}".format(value) +
unknown_scan_input)
# Ensure that all initial states are available.
initial_states = brick.initial_states(batch_size, as_dict=True,
*args, **kwargs)
for state_name in application.states:
dim = brick.get_dim(state_name)
if state_name in kwargs:
if isinstance(kwargs[state_name], NdarrayInitialization):
kwargs[state_name] = tensor.alloc(
kwargs[state_name].generate(brick.rng, (1, dim)),
batch_size, dim)
elif isinstance(kwargs[state_name], Application):
kwargs[state_name] = (
kwargs[state_name](state_name, batch_size,
*args, **kwargs))
else:
try:
kwargs[state_name] = initial_states[state_name]
except KeyError:
raise KeyError(
"no initial state for '{}' of the brick {}".format(
state_name, brick.name))
states_given = dict_subset(kwargs, application.states)
# Theano issue 1772
for name, state in states_given.items():
states_given[name] = tensor.unbroadcast(state,
*range(state.ndim))
def scan_function(*args):
args = list(args)
arg_names = (list(sequences_given) +
[output for output in application.outputs
if output in application.states] +
list(contexts_given))
kwargs = dict(equizip(arg_names, args))
kwargs.update(rest_kwargs)
outputs = application(iterate=False, **kwargs)
# We want to save the computation graph returned by the
# `application_function` when it is called inside the
# `theano.scan`.
application_call.inner_inputs = args
application_call.inner_outputs = pack(outputs)
return outputs
outputs_info = [
states_given[name] if name in application.states
else None
for name in application.outputs]
result, updates = theano.scan(
scan_function, sequences=list(sequences_given.values()),
outputs_info=outputs_info,
non_sequences=list(contexts_given.values()),
n_steps=n_steps,
go_backwards=reverse,
name='{}_{}_scan'.format(
brick.name, application.application_name))
result = pack(result)
if return_initial_states:
# Undo Subtensor
for i in range(len(states_given)):
assert isinstance(result[i].owner.op,
tensor.subtensor.Subtensor)
result[i] = result[i].owner.inputs[0]
if updates:
application_call.updates = dict_union(application_call.updates,
updates)
return result
return recurrent_apply
|
memo = {}
def divide(total_len, block_size) :
if total_len < 0 :
yield 0
elif total_len == 0 :
yield 1
else :
if total_len in memo :
yield memo[total_len]
else :
for block in block_size :
if block <= total_len :
#print (total_len, block)
newsize = total_len - block
if block != 1 and newsize > 0 :
newsize -= 1
s = sum(d for d in divide(newsize, block_size))
memo[newsize] = s
yield s
return
def euler114(total_len) :
global memo
block_sizes = tuple([1]) + tuple(range(3, total_len + 1))
memo = {}
result = sum(divide(total_len, block_sizes))
print (total_len)
print (result)
#print (memo)
print ("-----")
if __name__ == "__main__" :
import time
s = time.clock()
euler114(50)
e = time.clock()
print ("Elapsed: {0}".format(e - s))
|
from math import sqrt
from copy import deepcopy
import sys
def getPrimeList(n):
primeList = range(2,n)
if n < 11:
return [2,3,5,7]
k = int(sqrt(n))
sqrtPrimeList = getPrimeList(k)
length = len(primeList)
primeAssist = [True]*length
for i in sqrtPrimeList:
indexList = 2*i-2
while indexList <length:
primeAssist[indexList] = False
indexList += i
primeList2 = []
for i in xrange(length):
if primeAssist[i]:
primeList2.append(primeList[i])
primeList = deepcopy(primeList2)
return primeList
primeList=getPrimeList(1000000)
subPrimeList=[]
length =1
tmplist=[]
for i in primeList:
if len(str(i))==length:
tmplist.append(i)
else:
length += 1
subPrimeList.append(tmplist)
tmplist=[]
tmplist.append(i)
subPrimeList.append(tmplist)
for isub in range(len(subPrimeList)):
primeList=deepcopy(subPrimeList[isub])
while len(primeList)>0:
i = primeList[0]
if i<10:
break
primeList.remove(i)
strNum = str(i)
print i
for j in range(3):
stro = str(j)
tmpList = strNum.split(stro)
length = len(tmpList)
if length==1:
continue
for ii in range(2**(length-1)-1):
count = 1
count2 = 0
for k in range(j+1,10):
strr=str(k)
rstr=''
for jj in range(length-1):
if (ii>>(length-2-jj))&1==1:
rstr += (tmpList[jj]+stro)
else:
rstr += (tmpList[jj]+strr)
rnum = int(rstr+tmpList[-1])
ff =lambda x,y:int(x)+int(y)
if rnum&1==0 or reduce(ff,str(rnum))%3==1 or (rnum not in primeList):
if j==2:
break
count2 += 1
else:
count += 1
if count >= 8:
print i
sys.exit()
if count2 >=2:
break
|
def binarySearch(a, v) :
lo, hi = 0, len(a)-1
if v > a[-1] : return len(a)
elif v < a[0] : return -1
while lo <= hi :
mid = lo + ((hi - lo) >> 1)
if a[mid] > v : hi = mid - 1
elif a[mid] < v : lo = mid + 1
else: return mid
return hi +1
if __name__ == "__main__" :
import string
def testBinarySearch(a, v) :
i = binarySearch(a,v)
print v, i, (a[i] if (0 <= i < len(a)) else "")
s = string.uppercase
for a in string.uppercase :
testBinarySearch(s, a)
testBinarySearch(string.uppercase, 'a')
testBinarySearch(string.uppercase, '0')
s = [string.uppercase[i] for i in range(0, len(string.uppercase), 2) ]
#s = string.uppercase
for a in (string.uppercase[i] for i in range(0, len(string.uppercase), 2)) :
testBinarySearch(s, a)
for a in (string.uppercase[i] for i in range(1, len(string.uppercase), 2)) :
testBinarySearch(s, a)
|
import psyco
psyco.full()
def reverseString(s) :
return "".join(s[-i-1] for i in range(len(s)))
def isPalindrome(s) :
return all(s[i] == s[len(s) - i - 1] for i in range(len(s) >> 1))
def palindromicNumber(n) :
if n & 1 :
x = (n - 1) >> 1
lower = int(10 ** (x-1))
upper = int(10 ** x)
for j in range(lower, upper) :
s = str(j)
x = int(s + "0" + reverseString(s))
for i in range(0, 10*upper, upper) :
yield x + i
else :
x = n >> 1
lower = int(10 ** (x-1))
upper = int(10 ** x)
for j in range(lower, upper) :
s = str(j)
yield int(s + reverseString(s))
return
def cumulativeSeries(s) :
a = [0]
sum = 0
for ss in s :
sum += ss
a.append(sum)
return a
def euler125(upper) :
print "Getting palindromes..."
p = {}
for i in range(1,upper+1) :
for x in palindromicNumber(i) :
p[x] = 1
print "Getting squares..."
upper_ten = int(int(10 ** upper) ** 0.5)
#print upper_ten
squares = [i * i for i in range(1,upper_ten + 1)]
#print len(squares)
print "Generating cumulative series..."
cum_squares = cumulativeSeries(squares)
#print len(cum_squares)
results = set()
for i in range(len(cum_squares)) :
#print i, "\r",
for j in range(i+2, len(cum_squares)) :
v = cum_squares[j] - cum_squares[i]
if v > 10**upper : break
elif v in p :
results.add(v)
#print len(results), v, "[%d,%d]" %(i+1,j+1) #, squares[i:j]
print
print len(results), sum(results)
#print results
def testPalindromes() :
p = {}
for i in range(1,upper+1) :
for x in palindromicNumber(i) :
p[x] = 1
count = 0
for i in range(10**7, 10**8) :
if (i % 10000 == 0) : print i, "\r",
b1, b2 = isPalindrome(str(i)), (i in p)
if (b1 and not b2) :
print
print "Missed a palindrome: %d" % i
elif (not b1 and b2) :
print
print "Added a non-palindrome: %d" % i
elif b1 == b2 :
count += 1
print "Equal %d times" % count
if __name__ == "__main__" :
#upper = 4
upper = 8
euler125(upper)
#testPalindromes()
|
def palindrome_helper(s, n) :
if n == 0 :
yield s
else :
lower = (0 if n > 2 else 1)
for i in range(lower, 10) :
seed = str(i) + s + str(i)
for x in palindrome_helper(seed, n - 2) :
yield x
return
def palindrome_10(n) :
if n & 1 :
lower = (0 if n > 1 else 1)
for i in range(lower,10) :
for x in palindrome_helper(str(i), n-1):
yield x
else :
for x in palindrome_helper("", n):
yield x
return
def palindrome(s) :
i,j = 0, len(s)-1
while i < j :
if s[i] != s[j] : return False
i += 1; j -= 1
else:
return True
def is_palindrome_2(s) :
x = int(s)
tmp = ""
while x :
tmp = ("1" if x & 1 else "0") + tmp
x >>= 1
return palindrome(tmp)
s = []
for i in range(1,7) :
for x in palindrome_10(i) :
if is_palindrome_2(x) :
s.append(x)
print sum(int(ss) for ss in s)
print s |
user_input = input()
ma = -1
for ch in user_input:
if(user_input.count(ch) > ma):
ma = user_input.count(ch)
char = ch
print(char)
|
#P4T1 Turtle Lab
#P4Lab1: Shapes
#CTI 110
#Jessica Washington
#create turtles
import turtle
wn = turtle.Screen()
jess = turtle.Turtle()
wn.title("Square and Triangle")
jess.shape("turtle")
jess.color("hotpink")
jess.pensize(5)
ed = turtle.Turtle()
ed.color("blue")
ed.pensize(5)
#create square
for x in range(4):
jess.forward(50)
jess.left(90)
#create triangle
for i in range(3):
ed.forward(60)
ed.left(120)
wn.mainloop()
|
#P4T2
#CTI 110
#Jessica Washington
#July 2nd, 2018
#Initialize the accumulator.
runningTotal = 0
#Collect info from user.
while runningTotal >= 0:
print('Enter a number?')
#Input numbers.
n = int(input())
#Add numbers together.
runningTotal = runningTotal + n
#Create a stopping point.
if n < 0:
#Add numbers together.
runningTotal = runningTotal + -n
print('Total:', runningTotal)
|
#!/usr/bin/env python
# -*- coding:utf-8-*-
#リスト作り方①
a_list = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
#リスト作り方②
b_list = []
c_list = []
for i in range(3):
b_list.append(0)
for j in range(3):
c_list.append(b_list)
#リスト作り方③
d_list = [[0]*3]*3
a_list[1][1] = 1
c_list[1][1] = 1
d_list[1][1] = 1
print(a_list)
print(c_list)
print(d_list)
e_list = [[0]*3 for _ in range(3)]
e_list[1][1] = 1
print(e_list) |
import numpy as np
from sklearn.datasets import load_boston
boston = load_boston()
from matplotlib import pyplot as plt
plt.scatter(boston.data[:,5], boston.target, color='r')
from sklearn.linear_model import LinearRegression
lr = LinearRegression()
x = boston.data[:,5]
y = boston.target
x = np.transpose(np.atleast_2d(x))
lr.fit(x, y)
y_predicted = lr.predict(x)
from sklearn.metrics import mean_squared_error
mse = mean_squared_error(y, lr.predict(x))
print("Mean squared error (of training data): {:.3}".format(mse))
x = boston.data
y = boston.target
lr.fit(x, y)
p = lr.predict(x)
plt.scatter(p, y)
plt.xlabel('Predicted price')
plt.ylabel('Actual price')
plt.plot([y.min(), y.max()], [[y.min()], [y.max()]])
plt.show()
|
#PF-Exer-26
def factorial(number):
fact=1
for i in range(1,number+1):
fact*=i
return fact
def find_strong_numbers(num_list):
strong_num_list=[]
for i in num_list:
temp=i
sum=0
if(temp==0):
continue
else:
while i!=0:
num=i%10
sum+=factorial(num)
i=i//10
if(sum==temp):
strong_num_list.append(temp)
return strong_num_list
num_list=[145,375,100,2,10]
strong_num_list=find_strong_numbers(num_list)
print(strong_num_list)
#PF-Exer-28
#This method accepts the name of winner of each match of the day
def find_winner_of_the_day(*match_tuple):
c1=0
c2=0
for i in match_tuple:
if(i=="Team1"):
c1+=1
else:
c2+=1
if(c1>c2):
return "Team1"
elif(c1<c2):
return "Team2"
else:
return "Tie"
#Invoke the function with each of the print statements given below
print(find_winner_of_the_day("Team1","Team2","Team2","Team1","Team2"))
#print(find_winner_of_the_day("Team1","Team2","Team1","Team2"))
#PF-Exer-29
def merge_lists(list1,list2):
#Write your logic here
new_merge_list=[]
for i in range(0,len(list1)):
new_merge_list.append(list1[i])
for i in range(0,len(list2)):
new_merge_list.append(list2[i])
return new_merge_list
def sort_list(merged_list):
#Write your logic here
merged_list.sort()
return merged_list
#Provide different values for list1 and list2 and test your program
merged_list=merge_lists(list1=[1,2,3,4,1] ,list2=[2,3,4,5,4,6])
print(merged_list)
sorted_merged_list=sort_list(merged_list)
print(sorted_merged_list)
#PF-Assgn-34
def find_pairs_of_numbers(num_list,n):
c=0
for i in range(0,len(num_list)):
for j in range(i+1,len(num_list)):
if(num_list[i]+num_list[j]==n):
c+=1
return c
num_list=[1, 2, 4, 5, 6]
n=6
print(find_pairs_of_numbers(num_list,n))
#PF-Assgn-35
#Global variable
list_of_marks=(12,18,25,24,2,5,18,20,20,21)
def find_more_than_average():
avg=0
sum=0
c=0
for i in range(0,len(list_of_marks)):
sum+=list_of_marks[i]
avg=sum/len(list_of_marks)
for i in range(0,len(list_of_marks)):
if(avg<list_of_marks[i]):
c+=1
avg=c/len(list_of_marks)*100
return avg
def sort_marks():
return sorted(list_of_marks)
def generate_frequency():
listt=[]
for i in range(0,26):
c=0
for j in range(0,len(list_of_marks)):
if (list_of_marks[j]==i):
c+=1
listt.append(c)
return listt
print(find_more_than_average())
print(generate_frequency())
print(sort_marks())
#PF-Assgn-36
def create_largest_number(number_list):
ans=""
number_list.sort()
for i in range(len(number_list)-1,-1,-1):
ans+=str(number_list[i])
an=int(ans)
return an
number_list=[23,34,55]
largest_number=create_largest_number(number_list)
print(largest_number)
#PF-Assgn-37
#Global variables
child_id=(10,20,30,40,50)
chocolates_received=[12,5,3,4,6]
def calculate_total_chocolates():
sum=0
for i in range(0,len(chocolates_received)):
sum+=chocolates_received[i]
return sum
def reward_child(child_id_rewarded,extra_chocolates):
c=0
if(extra_chocolates<1):
print("Extra chocolates is less than 1")
else:
for i in range(0,len(child_id)):
if(child_id[i]==child_id_rewarded):
chocolates_received[i]+=extra_chocolates
c=1
if(c==1):
print(chocolates_received)
else:
print("Child id is invalid")
# Use the below given print statements to display the output
# Also, do not modify them for verification to work
#print("Extra chocolates is less than 1")
#print("Child id is invalid")
#print(chocolates_received)
print(calculate_total_chocolates())
#Test your code by passing different values for child_id_rewarded,extra_chocolates
reward_child(20,2)
#PF-Assgn-38
def check_double(number):
ss=[]
kk=[]
s=number
k=number*2
c=0
if(len(str(s))==len(str(k))):
while s!=0:
t1=s%10
s=s//10
t2=k%10
k=k//10
ss.append(t1)
kk.append(t2)
ss.sort()
kk.sort()
for i in range(0,len(kk)):
if(kk[i]==ss[i]):
c+=1
else:
return False
if(c==len(ss)):
return True
else:
return False
#Provide different values for number and test your program
print(check_double(125874))
#PF-Assgn-39
#This verification is based on string match.
#Global variables
menu=('Veg Roll','Noodles','Fried Rice','Soup')
quantity_available=[2,200,3,0]
'''This method accepts the item followed by the quantity required by a customer in the format item1, quantity_required, item2, quantity_required etc.'''
def place_order(*item_tuple):
c=0
m=0
k=0
item=list(item_tuple)
for i in range(0,len(item),2):
c=0
for j in range(0,len(menu)):
if(item[i]==menu[j]):
c=1
break
if(c==0):
print(item[i] +" is not available" )
break
else:
k=check_quantity_available(j,item[i+1])
if(k==0):
print(item[i] +" stock is over")
else:
print(item[i]+ " is available")
#Populate the item name in the below given print statements
#Use it to display the output wherever applicable
#Also, do not modify the text in it for verification to work
'''This method accepts the index position of the item requested by the customer in the quantity_available list, and the requested quantity of the item.'''
def check_quantity_available(index,quantity_requested):
if(quantity_available[index]>=int(quantity_requested)):
return 1
else:
return 0
#Provide different values for items ordered and test your program
place_order("Fried Rice",2,
"Soup",1)
|
#Write your function here
def reversed_list(lst1, lst2):
count = 0
for i in range(0, len(lst1)):
if lst1[i] == lst2[-i - 1]:
count += 1
if count == len(lst1):
return True
return False
#Uncomment the lines below when your function is done
#print(reversed_list([1, 2, 3], [3, 2, 1]))
#print(reversed_list([1, 5, 3], [3, 2, 1]))
|
#!/usr/bin/env python
"""nims.py
A simple competitive game where players take stones from stone piles.
"""
total = int(40)
player = False
while total > 0:
while not player:
print total,"stones left.",
p1 = int(raw_input("Player 1 [1-5]: "))
if p1 > 5 or p1 < 1:
print "Invalid number of stones."
elif p1 > total:
print "Not enough stones."
else:
total = total - p1
if total == 0:
print "Player 2 wins!"
break
else:
player = True
while player:
print total,"stones left.",
p2 = int(raw_input("Player 2 [1-5]: "))
if p2 > 5 or p2 < 1:
print "Invalid number of stones."
elif p1 > total:
print "Not enough stones."
else:
total = total - p2
if total == 0:
print "Player 1 wins!"
break
else:
player = False
|
#!/usr/bin/env python
import math
try:
import unittest2 as unittest
except:
import unittest
import shapes
from shapes import *
@unittest.skipIf(not hasattr(shapes, "Shape"), "No Shape class defined")
class ShapeTest(unittest.TestCase):
def test_shape_does_nothing(self):
shape = Shape()
self.assertTrue(hasattr(Shape, "area"), "Shape should have an abstract area function")
self.assertTrue(hasattr(Shape, "perimeter"), "Shape should have an abstract perimeter function")
self.assertIsNone(shape.area(), "Abstract Shape should have no area")
self.assertIsNone(shape.perimeter(), "Abstract Shape should have no perimeter")
@unittest.skipIf(not hasattr(shapes, "Rect"), "No Rect class defined")
class RectTest(unittest.TestCase):
def setUp(self):
self.rect = Rect(2,4)
def test_is_shape(self):
self.assertTrue(isinstance(self.rect, Shape), "Rectangles should be Shapes")
def test_area(self):
self.assertEqual(self.rect.area(), 8, "Area for Rect 2x4 should be 8")
def test_perimeter(self):
self.assertEqual(self.rect.perimeter(), 12, "Perimeter for Rect 2x4 should be 12")
@unittest.skipIf(not hasattr(shapes, "Square"), "No Square class defined")
class SquareTest(unittest.TestCase):
def setUp(self):
self.sq = Square(2)
def test_is_shape(self):
self.assertTrue(isinstance(self.sq, Shape), "Squares should be Shapes")
def test_is_rect(self):
self.assertTrue(isinstance(self.sq, Rect), "Squares should be Rectangles")
def test_rect_methods(self):
self.assertEqual(Rect.area, Square.area, "Squares should have the same area method as Rectangles")
self.assertEqual(Rect.perimeter, Square.perimeter, "Squares should have the same perimeter method as Rectangles")
def test_area(self):
self.assertEqual(self.sq.area(), 4, "Area for Square 2x2 should be 4")
def test_perimeter(self):
self.assertEqual(self.sq.perimeter(), 8, "Perimeter for Square 2x2 should be 8")
@unittest.skipIf(not hasattr(shapes, "Circle"), "No Circle class defined")
class CircleTest(unittest.TestCase):
def setUp(self):
self.circ = Circle(4)
self.area = 16 * math.pi
self.perim = 8 * math.pi
def test_is_shape(self):
self.assertTrue(isinstance(self.circ, Shape), "Circles should be Shapes")
def test_area(self):
self.assertEqual(self.circ.area(), self.area, "Wrong area for Circle with radius 4")
def test_perimeter(self):
self.assertEqual(self.circ.perimeter(), self.perim, "Wrong perimeter for Circle with radius 4")
if __name__ == "__main__":
unittest.main(verbosity=2)
|
#!/usr/bin/env python
# coding: utf-8
# In[4]:
#MUST BE FIRST LINE OF CODE
from tkinter import *
# create a new tk object named "root"
root = Tk()
# set up the window
## geometry is width x height in pixels of the total amount of space the total amount of created tk vars can take up
root.geometry("350x250")
## create a new frame object named "frame". think of it as a program window. all our interface display will be inside this frame
### NOTE: frame auto-fills the entire above-mentioned geometry (350 x 250 here).
frame = Frame(root)
## .pack() takes whatever object is calling that function and puts it inside a tk object (instance named "root" here)
frame.pack()
## the code below creates a "left side" and "right side" of the frame and orients them to the left and right of the display
''' NOTE:
creating 2 additional frames splits the window into 3 for positioning:
a left side("leftframe"), a middle ("frame"), and a right side ("rightside")
Since both leftframe and rightframe are also created with Frame(root),
"frame", "leftside", and "rightside" are all identical Frame objects that are "aware" of one another existing inside main;"root"
'''
leftframe = Frame(root)
leftframe.pack(side=LEFT)
rightframe = Frame(root)
rightframe.pack(side=RIGHT)
label = Label (frame, text = "Welcome to the budget calculator!")
label.pack()
###################### weekly ######################
weekly_amnt_list=[]
weekly_sub_names=[]
m_weeks = 0
label1 = Label(frame, text = "How many weeks are in the month?")
weeks_in_month = Entry (frame)
m_weeks = int(weeks_in_month)
label2 = Label (leftframe, text = "Enter subscription/company name")
weekly_name = Entry (leftframe)
#add subscription names to file
weekly_sub_names.append(weekly_name)
label3 = Label (leftframe, text = "Enter amount")
weekly_take_amt = Entry (leftframe)
#add subscription cost to file
weekly_amnt_list.append (weekly_take_amnt)
#############################################################################
''' Getting around global vars with writing to files! '''
def write_to_weekly_file(date, names, fees, weeks):
# open file as read-only
file_reader = open("weekly.txt", "r")
#validate appended entries. validatating just the new appends still ensures that all previous entries are valid.
# 1. Validate weeks in month
if weeks < 0 or weeks > 5 or weeks == 1 or weeks == 2:
failed0 = Label (frame, text = "The submitted weeks for month is invalid. Please enter a valid number of weeks for a month and try again.")
file_reader.close()
# 2. Validate most recent date append
while True:
# @catch & @display
try:
catcher = str(date(len(date)))
except ValueError:
failed1 = Label (frame, text = "The submitted date is invalid. Please enter a valid date and try again.")
break
else:
break
# 3. Validate most recent name append
while True:
# @catch & @display
try:
catcher = str(names(len(names))
except ValueError:
failed2 = Label (frame, text = "The submitted subscription name is invalid. Please enter a valid title and try again.")
break
else:
break
# 4. validate most recent cost append
while True:
# @catch & @display
try:
catcher = float(fees(len(fees)))
except ValueError:
failed3 = Label (frame, text = "The submitted cost is invalid. Please enter a valid number and try again.")
else:
break
# determine if file has been previously been written to:
if str(file_reader.readline()).startswith("\n"):
# if @this, file has data in it. close file & @append data to it
file_reader.close()
else:
# file has not been previously written to. designate new:
file_reader.close()
f_designate = open("weekly.txt", "w")
f_designate.write("\n")
f_designate.close()
# append the valid data to the end of the file
f_apply = open("weekly.txt", "a")
#1. find number of entries
entry_count = data_dump.count("\n")
# ... subtract 1 from it becuase we do the designation with a \n
entry_count -= 1
f_apply.append("Week expense #", entry_count, "is name:", names(len(names)), "fees:", fees(len(fees)))
#2. write to @master file. @master is for debugging purposes!
f_apply.close()
f_master = open("internal_data.txt", "w")
#locate start of line
find_string = ""
find_string = "number of entries in weekly.txt = "
find_string.strip()
find_length = 28
# locate counter lines
master_dump = str(f_master.read())
dump_array = master_dump.splitlines()
for y in dump_array:
# if the line starts with the string we want to find,
if dump_aray(y).startswith(find_str) == True:
# separate it out! (casting as a precaution)
grab_str = str(dump_aray(y))
# We start at the end of the identifier (=),
val = grab_str.find("=") + 1
# and our number/s should begin right after that
if val == find_length + 1:
#so we "snip" that value out of the file's string!
#leave end of range for file to automatically go to end
snip = str(grab_str[val:])
# replace the outdated information with updated information
grab_str.replace(snip, entry_count,"\n")
# and then replace the entire string
master_dump(y).replace(grab_str,"\n")
# ... and then replace the whole file.
'''I wasted 3 weeks struggling to understand what I was reading about os library...
and then I realized that I no longer had time to try to understand it'''
f_master.write("\n")
for z in f_master:
f_master.append(master_dump(z))
###########################################################################################
# call write on button click
b_add_weekly_payment = Button (leftframe, text = "Add weekly payment", command = write_to_weekly_file(weekly_date_list, weekly_amnt_list, weekly_sub_names, m_weeks))
#################### monthly #########################
payment_due_date = []
monthly_sub_names=[]
monthly_amnt_list=[]
label4 = Label(leftframe, text = "Enter subscription/company name")
month_sub_name = Entry (leftframe)
monthly_sub_names.append(monthly_sub_names)
label5 = Label(leftframe, text = "Enter amount")
month_sub_amt = Entry (leftframe)
monthly_amnt_list.append(monthly_amnt_list)
label6 = Label(leftframe, text = "Enter date")
sub_payment_date = Entry (leftframe)
payment_due_date.append(sub_payment_date)
##############################################################
''' Getting around global vars with writing to files! '''
def write_to_weekly_file(date, names, fees):
# open file as read-only
file_reader = open("monthly.txt", "r")
#validate appended entries. validatating just the new appends still ensures that all previous entries are valid.
# 1. Validate most recent date append
while True:
# @catch & @display
try:
catcher = str(date(len(date))
except ValueError:
failed0 = Label (frame, text = "The submitted due date is invalid. Please enter a valid date and try again.")
else:
break
# 2. Validate most recent name append
while True:
# @catch & @display
try:
catcher = str(names(len(names))
except ValueError:
failed1 = Label (frame, text = "The submitted subscription name is invalid. Please enter a valid title and try again.")
else:
break
# 3. validate most recent string append
while True:
# @catch & @display
try:
catcher = float(fees(len(fees))
except ValueError:
failed2 = Label (frame, text = "The submitted cost is invalid. Please enter a valid number and try again.")
else:
break
# determine if file has been previously been written to:
if str(file_reader.readline()).startswith("\n"):
# if @this, file has data in it. close file & @append data to it
file_reader.close()
else:
# file has not been previously written to. designate new:
file_reader.close()
f_designate = open("monthly.txt", "w")
f_designate.write("\n")
f_designate.close()
# append the valid data to the end of the file
f_apply = open("monthly.txt", "a")
#1. find number of entries
entry_count = data_dump.count("\n")
# ... subtract 1 from it becuase we do the designation with a \n
entry_count -= 1
if entry_count <= 0:
entry_count = 1
f_apply.append("Monthly expense #", entry_count, "is date:", date(len(date)), "name:", date(len(date)), "fees:", len(fees))
#2. write to @master file. @master is for debugging purposes!
f_apply.close()
f_master = open("internal_data.txt", "w")
#locate start of line
find_str = "number of entries in monthly.txt = "
find_str.strip()
find_length = 29
# locate counter lines
master_dump = str(f_master.read())
master_dump_array = master_dump.splitlines()
for y in master_dump:
# if the line starts with the string we want to find,
if master_dump(y).startswith(find_str) == True:
# separate it out! (casting as a precaution)
grab_str = str(master_dump(y))
# We start at the end of the identifier (=),
val = grab_str.find("=") + 1
# and our number/s should begin right after that
if val == find_length + 1:
#so we "snip" that value out of the file's string!
#leave end of range for file to automatically go to end
snip = str(grab_str[val:])
# replace the outdated information with updated information
grab_str.replace(snip, entry_count,"\n")
# and then replace the entire string
master_dump(y).replace(grab_str,"\n")
# ... and then replace the whole file.
'''I wasted 3 weeks struggling to understand what I was reading about os library...
and then I realized that I no longer had time to try to understand it'''
f_master.write("\n")
for z in f_master:
f_master.append(master_dump(z))
###########################################################################################
payment_due_date = []
monthly_sub_names=[]
monthly_amnt_list=[]
b_add_monthly_payments = Button (leftframe, text = "Add monthly payment", command = write_to_monthly_file(payment_due_date, monthly_sub_names, monthly_amnt_list))
#################### paycheck ###################
paycheck_hours = []
paycheck_pay_rate = []
label7 = Label(leftframe, text = "Enter hours worked for one week")
paycheck_add_hours = Entry (leftframe)
paycheck_hours.append(paycheck_add_hours)
label8 = Label(leftframe, text = "Enter hourly pay rate")
paycheck_hourly_pay = Entry (leftframe)
paycheck_pay_rate.append(paycheck_hourly_pay)
###########################################################################################
def get_paycheck(hours, payrate):
# open file as read-only
file_reader = open("paycheck.txt", "r")
while True:
try:
hours=float(hours(len(hours)))
except ValueError:
print("The submitted work hours is invalid. Please enter a valid number of hours and try again.")
else:
break
while True:
try:
payrate=float(payrate(len(payrate)))
except ValueError:
print("The submitted pay rate is invalid. Please enter a valid rate and try again.")
else:
break
# determine if file has been previously been written to:
if str(file_reader.readline()).startswith("\n"):
# if @this, file has data in it. close file & @append data to it
file_reader.close()
else:
# file has not been previously written to. designate new:
file_reader.close()
f_designate = open("paycheck.txt", "w")
f_designate.write("\n")
f_designate.close()
# append the valid data to the end of the file
f_apply = open("paycheck.txt", "a")
#1. find number of entries
data_dump = str(f_apply.read())
entry_count = data_dump.count("\n")
# ... subtract 1 from it becuase we do the designation with a \n
entry_count -= 1
# *** and divide by 2 because every paycheck has two appends! ***
entry_count = entry_count / 2
if entry_count <= 0:
entry_count = 1
f_apply.append("Paycheck #", entry_count, "is hours:", hours(len(hours)), "and payrate:", payrate(len(payrate)))
####################### calculate paycheck #############################
#1. net pay
net_pay = hours * payrate
# 2. taxes
tax = 0
tax = net_pay * 0.800
# 3. check
total = net_pay - tax
# 4. append
f_apply.append("Net pay for check #", entry_count, "is $",net_pay, "and remaining check is: $",total)
#########################################################################
# 4. write to @master file. @master is for debugging purposes!
f_master = open("internal_data.txt", "w")
#locate start of line
find_str = "number of entries in paycheck.txt = "
find_str.strip()
find_length = 30
# locate counter lines
master_dump = str(f_master.read())
read_array = master_dump.splitlines()
for y in read_array:
# if the line starts with the string we want to find,
if read_array(y).startswith(find_str) == True:
# separate it out! (casting as a precaution)
grab_str = str(master_dump(y))
# We start at the end of the identifier (=),
val = grab_str.find("=") + 1
# and our number/s should begin right after that
if val == find_length + 1:
#so we "snip" that value out of the file's string!
#leave end of range for file to automatically go to end
snip = grab_str[val:]
# replace the outdated information with updated information
grab_str.replace(snip, entry_count"\n")
# and then replace the entire string
master_dump(y).replace(grab_str"\n")
# ... and then replace the whole file.
'''I wasted 3 weeks struggling to understand what I was reading about os library...
and then I realized that I no longer had time to try to understand it'''
f_master.write("\n")
for z in f_master:
f_master.append(master_dump(z))
###########################################################################################
b_add_new_paycheck = Button (rightframe, text = "Add paycheck", command = get_paycheck(paycheck_hours, paycheck_pay_rate))
########################## calculate budget ########################
def calc_total(weeks):
expenses = 0
# 1. read paychecks
r_checks = open("paycheck.txt", "r")
check_identifier_key = "Net pay for check #"
# count number of paychecks
check_dump = str(r_checks.read())
num_checks = check_dump.count(check_identifier_key)
start_pos = "and remaining check is: $"
check_dump_array = check_dump.splitlines()
# catch if no paychecks entered
if num_checks <= 0:
check_error = Label(leftframe, text = "The program cannot find any paychecks. Please create one and try again.")
break
money_to_spend = 0.0
running_total = 0.0
# total money
for x in check_dump_array:
if check_dump_array(x).startswith(check_identifier_key) == True:
snip = str(check_dump_array(x))
pos = snip.index(start_pos) + 1
val = float(snip[pos:].strip())
money_to_spend += val
r_checks.close()
# open monthly
monthly_dates = []
monthly_names = []
monthly_fees = []
entry_id_key = "Monthly expense #"
start_pos1 = "date:"
start_pos2 = "name:"
start_pos3 = "fees:"
r_month = open("monthly.txt", "r")
m_dump = str(r_month.read())
num_entries = m_dump.count(entry_id_key)
# catch if no monthly expenses entered
if num_entries <= 0:
check_error = Label(leftframe, text = "The program cannot find any monthly expenses. Please create one and try again.")
break
m_entry_array = m_dump.splitlines()
for y in m_entry_array:
if m_entry_array(y).startswith(entry_id_key) == True:
snip1 = str(entry_array(y))
pos = snip1.index(start_pos1) + 1
entry = str(snip1[pos:])
monthly_dates.append[entry]
# clear
entry = ""
pos = 0
snip2 = str(entry_array(y))
pos = snip2.index(start_pos2) + 1
entry = str(snip2[pos:])
monthly_names.append[entry]
# clear
val = 0.0
pos = 0
snip3 = str(entry_array(y))
pos = snip3.index(start_pos3) + 1
val = float(snip3[pos:].strip())
monthly_fees.append(val)
expenses += val
r_month.close()
num_entries = 0
# open weekly
weekly_names = []
weekly_fees = []
entry_id_key = "Weekly expense #"
start_pos1 = "name:"
start_pos2 = "fees:"
r_weekly = open("weekly.txt", "r")
w_dump = str(r_weekly.read())
num_entries = w_dump.count(entry_id_key)
# catch if no monthly expenses entered
if num_entries <= 0:
check_error = Label(leftframe, text = "The program cannot find any weekly expenses. Please create one and try again.")
break
w_entry_array = w_dump.splitlines()
for y in entry_array:
if w_entry_array(y).startswith(entry_id_key) == True:
w_snip1 = str(entry_array(y))
pos = w_snip1.index(start_pos1) + 1
entry = str(w_snip1[pos:])
weekly_names.append(entry)
# clear
val = 0
pos = 0
w_snip2 = str(entry_array(y))
pos = w_snip2.index(start_pos2) + 1
val = float(snip2[pos:].strip())
weekly_fees.append[val]
expenses += val * weekly_date_list
r_week.close()
#calculate over/under budget
running_total = money_to_spend - expenses
if running_total >= 0:
remaining_money = Label (frame, "You have $", running_total, "left over.")
else:
remaining_money = Label (frame, "You are $", running_total * -1, "over your budget.")
# display due date/s for monthly payments
due_dates = ""
for z in monthly_dates:
due_dates += str(monthly_dates(z)), ","
m_date_label = Label (rightframe, "Your monthly payments are due on: ", due_dates)
for a in weekly_names:
w_date += str(weekly_names(a)), ","
w_date_label = Label (rightframe, "Your weekly payments are for: ", w_date)
###############################################################################################
b_calc_budget = Button(frame, text = "Calculate Budget", command = calc_total())
############################ new budget; clear all files #######################
#####################################################################################
def new_budget():
w_paycheck = open ("paycheck.txt", "w")
w_paycheck.write()
w_paycheck.close()
w_monthly = open ("monthly.txt", "w")
w_monthly.write()
w_paycheck.close()
w_weekly = open ("weekly.txt", "w")
w_weekly.write()
w_paycheck.close()
w_internal_data = open ("internal_data.txt", "w")
w_internal_data.write("numberofentriesinmonthly.txt=0 \n numberofentriesinweekly.txt=0 \n numberofentriesinpaycheck.txt=0")
##############################################################################
b_start_over = Button(rightframe, text = "Create a new Budget", command = new_budget())
#####################################################################################
# MUST BE LAST LINE OF CODE; tells the program to create a window and keep it open until the program is (manually) terminated
root.mainloop()
# In[ ]:
|
def rearrange_digits(input_list):
"""
Rearrange Array Elements so as to form two number such that their sum is maximum.
Args:
input_list(list): Input List
Returns:
(int),(int): Two maximum sums
"""
if len(input_list) == 0:
return []
if len(input_list) == 1:
return input_list
# use max_heap to sort input_list
max_heap = MaxHeap()
for element in input_list:
max_heap.insert(element)
# take numbers one by one to form two numbers
num_1 = ''
num_2 = ''
for i in range(max_heap.size()):
if i % 2 == 0:
num_1 += str(max_heap.remove())
else:
num_2 += str(max_heap.remove())
return [int(num_1), int(num_2)]
class MaxHeap:
def __init__(self, initial_size=10):
self.cbt = [None for _ in range(initial_size)]
self.next_index = 0
def insert(self, data):
self.cbt[self.next_index] = data
self.up_heapify()
self.next_index += 1
# double the array size if capacity is full
if self.next_index >= len(self.cbt):
old_array = self.cbt
self.cbt = [None for _ in range(2 * len(self.cbt))]
for i in range(len(old_array)):
self.cbt[i] = old_array[i]
def up_heapify(self):
child_index = self.next_index
while child_index >= 1:
parent_index = (child_index - 1) // 2
parent_element = self.cbt[parent_index]
child_element = self.cbt[child_index]
if parent_element < child_element:
self.cbt[parent_index] = child_element
self.cbt[child_index] = parent_element
child_index = parent_index
else:
break
def size(self):
return self.next_index
def remove(self):
if self.size() == 0:
return None
self.next_index -= 1
to_remove = self.cbt[0]
last_element = self.cbt[self.next_index]
self.cbt[0] = last_element
self.cbt[self.next_index] = to_remove
self.down_heapify()
return to_remove
def down_heapify(self):
parent_index = 0
while parent_index < self.next_index:
left_child_index = 2 * parent_index + 1
right_child_index = 2 * parent_index + 2
parent = self.cbt[parent_index]
left_child = None
right_child = None
max_element = parent
# check if left child and right child exist
if left_child_index < self.next_index:
left_child = self.cbt[left_child_index]
if right_child_index < self.next_index:
right_child = self.cbt[right_child_index]
# compare with left child and right child
if left_child is not None:
max_element = max(parent, left_child)
if right_child is not None:
max_element = max(max_element, right_child)
# check if parent is in the right position
if max_element == parent:
return
if max_element == left_child:
self.cbt[parent_index] = max_element
self.cbt[left_child_index] = parent
parent_index = left_child_index
if max_element == right_child:
self.cbt[parent_index] = max_element
self.cbt[right_child_index] = parent
parent_index = right_child_index
print('Rearrange array elements to form two number such that their sum is maximum.')
# test case 1
print('\nTest case 1: input_list = []. Answer is []')
print(rearrange_digits([]))
# test case 2
print('\nTest case 2: input_list = [2]. Answer is [2]')
print(rearrange_digits([2]))
# test case 3
print('\nTest case 3: input_list = [1, 2]. Answer is [2, 1]')
print(rearrange_digits([1, 2]))
# test case 4
print('\nTest case 4: input_list = [1, 2, 3]. Answer is [31, 2]')
print(rearrange_digits([1, 2, 3]))
# test case 5
print('\nTest case 5: input_list = [1, 2, 3, 2, 1]. Answer is [321, 21]')
print(rearrange_digits([1, 2, 3, 2, 1]))
# test case 6
print('\nTest case 6: input_list = [4, 6, 2, 5, 9, 8]. Answer is [964, 852]')
print(rearrange_digits([4, 6, 2, 5, 9, 8]))
# test case 7
print('\nTest case 7: input_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2]. \nAnswer is [9753210, 864210]')
print(rearrange_digits([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2]))
|
"""
ProcessInput.py
Description
-----------
This file reads an input file containing words and their associated vectors. The input format is 'Word [Vector]'. The words
and their vectors are stored in an empty dictionary with words being keys and vectors value.
"""
import re
import numpy as np
def ProcessInput(filename):
# Create an empty dictionary
W_V = {}
# Read file
F = open(filename, "r")
Input = F.readlines()
# print Input
F.close
for x in Input:
y = x.split()
y[1] = re.sub('\[', '', y[1])
y[-1] = re.sub('\]', '', y[-1])
# print y
z = map(float, y[1:])
W_V[y[0]] = np.array(z)
# len(W_V)
# print W_V["'s"]
return W_V |
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 18 10:59:58 2020
@author: alexa
"""
import itertools
import time
rows = "123456789"
cols = "ABCDEFGHI"
def AC3(csp, queue=None):
if queue is None:
queue = list(csp.binary_constraints)
while queue:
(xi, xj) = queue.pop(0)
if remove_inconsistent_values(csp, xi, xj):
# se uma das células tiver 0 possibilidades o sudoku não tem solução
if len(csp.possibilities[xi]) == 0:
return False
for Xk in csp.related_cells[xi]:
if Xk != xi:
queue.append((Xk, xi))
return True
def remove_inconsistent_values(csp, cell_i, cell_j):
removed = False # se o dominio nunca for reduzido é sempre devolvido false
# percorre cada valor possível restante para a cell_i
for value in csp.possibilities[cell_i]:
# se cell_i=value estiver em conflito com cell_j=poss
if not any([is_different(value, poss) for poss in csp.possibilities[cell_j]]):
# então remove cell_i=value do dominio
csp.possibilities[cell_i].remove(value)
removed = True
return removed # devolve true se algum valor tiver sido eliminado
# is_different: verifica se 2 células são diferentes
def is_different(cell_i, cell_j):
result = cell_i != cell_j
return result
class Sudoku:
"""
INICIALIZAÇÃO
"""
def __init__(self, grid):
game = list(grid)
# criação de todas as células das grelhas
self.cells = list()
self.cells = self.generate_coords()
# criação de todas as possibilidades para cada uma dessas células
self.possibilities = dict()
self.possibilities = self.generate_possibilities(grid)
# criação das restrições linha/coluna /quadrado
rule_constraints = self.generate_rules_constraints()
# conversão dessas restrições para restrições binárias
self.binary_constraints = list()
self.binary_constraints = self.generate_binary_constraints(rule_constraints)
# cria todas as restrições relacionadas com cada uma das células
self.related_cells = dict()
self.related_cells = self.generate_related_cells()
#prune(poda)
self.pruned = dict()
self.pruned = {v: list() if grid[i] == '0' else [int(grid[i])] for i, v in enumerate(self.cells)}
"""
gera todas as coordenadas das células
"""
def generate_coords(self):
all_cells_coords = []
# A,B,C, ... ,H,I
for col in cols:
#1,2,3 ,... ,8,9
for row in rows:
# A1, A2, A3, ... , H8, H9
new_coords = col + row
all_cells_coords.append(new_coords)
return all_cells_coords
"""
gera todos os valores possíveis restantes para cada célula
"""
def generate_possibilities(self, grid):
grid_as_list = list(grid)
possibilities = dict()
for index, coords in enumerate(self.cells):
# se o valor for 0, então a célula pode ter qualquer valor entre [1, 9].
if grid_as_list[index] == "0":
possibilities[coords] = list(range(1,10))
# caso contrário, o valor já está definido, as possibilidades são esse valor.
else:
possibilities[coords] = [int(grid_as_list[index])]
return possibilities
"""
gera as restrições baseadas nas regras deste jogo:
valor diferente de qualquer outro na mesma linha, coluna ou grelha
"""
def generate_rules_constraints(self):
row_constraints = []
column_constraints = []
square_constraints = []
# obtem se as restrições das filas
for row in rows:
row_constraints.append([col + row for col in cols])
# obtem se as restrições das colunas
for col in cols:
column_constraints.append([col + row for row in rows])
# obtem se as restrições das grelhas
# https://stackoverflow.com/questions/9475241/split-string-every-nth-character
rows_square_coords = (cols[i:i+3] for i in range(0, len(rows), 3))
rows_square_coords = list(rows_square_coords)
cols_square_coords = (rows[i:i+3] for i in range(0, len(cols), 3))
cols_square_coords = list(cols_square_coords)
# percorre cada grelha
for row in rows_square_coords:
for col in cols_square_coords:
current_square_constraints = []
# e para cada valor nesta grelha
for x in row:
for y in col:
current_square_constraints.append(x + y)
square_constraints.append(current_square_constraints)
# todas as restriçõs são a soma destas 3 regras
return row_constraints + column_constraints + square_constraints
"""
gera as restrições binárias com base nas regras de restrição
"""
def generate_binary_constraints(self, rule_constraints):
generated_binary_constraints = list()
# percorre cada conjunto de restrições
for constraint_set in rule_constraints:
binary_constraints = list()
# 2 porque queremos restrições binárias
# solução retirada em :
# https://stackoverflow.com/questions/464864/how-to-get-all-possible-combinations-of-a-list-s-elements
for tuple_of_constraint in itertools.permutations(constraint_set, 2):
binary_constraints.append(tuple_of_constraint)
# percorre cada uma destas restriçoes binárias
for constraint in binary_constraints:
# verifica se já temos esta restrição guardada
# solution from https://stackoverflow.com/questions/7571635/fastest-way-to-check-if-a-value-exist-in-a-list
constraint_as_list = list(constraint)
if(constraint_as_list not in generated_binary_constraints):
generated_binary_constraints.append([constraint[0], constraint[1]])
return generated_binary_constraints
"""
gera a célula relacionada com cada uma das restições
"""
def generate_related_cells(self):
related_cells = dict()
#percorre cada uma das 81 celulas
for cell in self.cells:
related_cells[cell] = list() # related_cells são aquelas com quem a célula atual tem restrições
for constraint in self.binary_constraints:
if cell == constraint[0]:
related_cells[cell].append(constraint[1])
return related_cells
"""
verifica se a solução do Sudoku está pronta
fazemos um loop através das possibilidades de cada célula
se todos eles tiverem apenas um, então o Sudoku está resolvido
"""
def isFinished(self):
for coords, possibilities in self.possibilities.items():
if len(possibilities) > 1:
return False
return True
"""
devolve uma string legível por humanos
"""
def __str__(self):
output = ""
count = 1
# percorre cada célula e imprime o seu valor
for cell in self.cells:
value = str(self.possibilities[cell])
if type(self.possibilities[cell]) == list:
value = str(self.possibilities[cell][0])
output += "[" + value + "]"
# se chegarmos ao fim da linha passa para uma nova linha
if count >= 9:
count = 0
output += "\n"
count += 1
return output
exemplo = '003020600900305001001806400008102900700000008006708200002609500800203009005010300'
def solve(grid, index, total):
print("\nSudoku {}/{} : \n{}".format(index, total, print_grid(grid)))
print("{}/{} : AC3 iniciou".format(index, total))
tic = time.perf_counter()
# instancia Sudoku
sudoku = Sudoku(grid)
# arranca o algoritmo AC-3
AC3_result = AC3(sudoku)
print(AC3_result)
toc = time.perf_counter()
timeFinal = toc - tic
print("{}/{} : Resultado: \n{}".format(index, total, sudoku))
print(f"\nTempo de cálculo: {toc - tic:0.4f}s\n")
return timeFinal
def print_grid(grid):
output = ""
count = 1
# percorre cada célula e imprime o seu valor
for cell in grid:
value = cell
output += "[" + value + "]"
# se chegarmos ao fim da linha,
# cria uma nova linha no display
if count >= 9:
count = 0
output += "\n"
count += 1
return output
#Função para executar o algoritmo x vezes
#Permite fazer uma averiguação de custo de tempo
def cicloTeste(iter):
total = 0
for i in range(iter):
print("Iteração: " + str(i))
total += solve(exemplo, 0, 1)
tempoFinal = total/iter
print("Média do tempo de cálculo após " + str(iter) + " iterações: " + str(tempoFinal))
#Função simples para user input
def inputUser():
val = input("Introduza o número de vezes que pretende executar este algoritmo? \n")
cicloTeste(int(val))
#Duas opções para executar
#Executa apenas uma vez:
solve(exemplo, 0, 1)
#executa X vezes (ou 10 em debugging)
#cicloTeste(10)
#inputUser() |
def merge_sorted_lists(li1,li2):
ans = []
len1 = len(li1)
len2 = len(li2)
i = j = 0
while i<len1 or j<len2:
if i<len1 and j<len2:
if(li1[i]<=li2[j]):
ans.append(li1[i])
i += 1
else:
ans.append(li2[j])
j += 1
elif i<len1:
ans.append(li1[i])
i += 1
elif j<len2:
ans.append(li2[j])
j += 1
return ans
# print merge_sorted_lists([1,3,4,53],[2,5,33,56])
def merge_sort(li):
if len(li) <= 1:
return li
else:
mid = int(len(li)/2)
left = li[:mid]
right = li[mid:]
sorted_left = merge_sort(left)
sorted_right = merge_sort(right)
return merge_sorted_lists(sorted_left,sorted_right)
print(merge_sort([38,27,43,3,9,82,42,10,-1])) |
'''
Write a function which will take a list of integers as input and returns the max integer from that list
as the output
'''
def max_integer(li):
final = li[0]
for num in li[1:]:
if num > final:
final = num
return final
print(max_integer([22,11,3,45,6,17])) |
class ProgramRunner:
def run_program(self, prog, steps, problem_input):
""" Runs the given program on an input for a given number of steps and returns the output.
Args:
prog (boolean array): binary encoding of the program.
steps (int): Upper bound on the number of instructions to execute in the program.
input (list of ints): Input to be given to the program.
Return:
output (list of ints): A list of ints returned by the program, or an empty list if
nothing is returned. If the program fails due to a syntax or runtime error, None
is returned.
"""
return []
def convert_program(self, prog_encoding):
""" Attempts to convert the given program encoding into a format that run_program can run.
This method may also attempt to remove simple errors to make the program more likely
to run successfully. However there is no guarantee that the program will be valid upon
return from this method
Args:
prog_encoding (boolean array): The binary encoding of a program.
"""
return prog
|
import sys
class Reader:
def __init__(self,path):
self.data = []
self.path = path
def read(self):
with open(self.path, 'rb') as txtfile:
for line in txtfile:
newline = line.rstrip().split(' ')
self.data.append(newline)
return self.data
class Writer:
def __init__(self, path):
self.path = path
def write(self, data):
file = open(self.path, 'w')
for line in data:
file.write(' '.join(line)+'\n')
file.close()
# lines = Reader('./input.txt').read()
# print(lines)
# output = Writer('output.txt').write(lines)
# print(sys.argv) |
import datetime
# Any time 5 PM or later is interpreted as today. Any time "earlier" than 5 PM is interpreted as tomorrow.
class BabysitterTime:
earliest_start_allowed = 17
latest_end_allowed = 4
today = datetime.date(1970, 1, 1)
tomorrow = today + datetime.timedelta(days=1)
def __init__(self, hour, minute=None):
if minute is None:
if hour < self.earliest_start_allowed:
self.time = datetime.datetime.combine(self.tomorrow, datetime.time(hour))
else:
self.time = datetime.datetime.combine(self.today, datetime.time(hour))
else:
if hour < self.earliest_start_allowed:
self.time = datetime.datetime.combine(self.tomorrow, datetime.time(hour, minute))
else:
self.time = datetime.datetime.combine(self.today, datetime.time(hour, minute))
def __lt__(self, other):
return self.time < other.time
def __le__(self, other):
return self.time <= other.time
def __gt__(self, other):
return self.time > other.time
def __ge__(self, other):
return self.time >= other.time
def __eq__(self, other):
return self.time == other.time
def __ne__(self, other):
return self.time != other.time
def __sub__(self, other):
return self.time - other.time
def full_hours_since(self, other):
return (self.time - other.time).total_seconds()//3600
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.