text stringlengths 37 1.41M |
|---|
"""This module defines a preprocess function to call to preprocess tweets before loading into a database."""
import re
import string
import pytest
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from nltk.tokenize import word_tokenize, sent_tokenize
from xml.etree import ElementTree
import numpy as np
import nltk
nltk.download('punkt')
nltk.download('stopwords')
def preprocess_text(text):
"""Extracts lower-cased and stemmed tokens from input string and
removes punctuation and stop words.
1. Use `nltk.tokenize.sent_tokenize` and `.word_tokenize` for tokenizing
2. Strip punctuations at both ends of words
3. Stem words with the `stemmer`
4. Filter stop words and empty words
Use the given stemmer to stem each word. Use stop_words to filter out stop words.
Args:
text: str, one single str of text to be processed
Returns:
list of str, tokenized & stemmed words.
"""
english_stop_words = set(stopwords.words("english"))
stemmer = PorterStemmer()
text = nltk.tokenize.sent_tokenize(text)
new_text = []
for sentence in text:
temp = nltk.tokenize.word_tokenize(sentence)
temp = [stemmer.stem(word.lower()) for word in temp if word.isalnum() and word.lower() not in english_stop_words]
new_text.append(temp)
new_text = [item for sublist in new_text for item in sublist]
return np.unique(new_text).tolist()
def test_processing_basic():
assert preprocess_text("These are some sample sentences. Watch out!") == ['sampl', 'sentenc',
'watch']
assert preprocess_text("I could have any ? sentence here") == ['could', 'sentenc']
assert preprocess_text("Look at this? Please! Cats in pajamas -.-. Short a Shorting Shorting.") == ['cat', 'look',
'pajama',
'pleas',
'short']
|
import sys
from enum import Enum
class TICPCommand(Enum):
"""Enumeration for Command Opcodes of the TICP Protocol.
This Class is a specialization of the Enum class.
Use this Enumeration für decoding 8 bit Message Blocks to the corresponding Opcode
Example:
The easiest way to initialize an TICPCommand Enum for a given byte is by passing
it to the constuctor of the Enum as follow::
$ opcode = (np.uint8) uart.pull(8)
$ command = TICPCommand(opcode)
or by passing an value::
$ command = TICPCommand(1)
_Git Repository:
https://github.com/eddex/pren2
"""
# Request Messages (REQ)
REQ_ALL_SENSOR_DATA = bytes.fromhex("01")
REQ_TOF1_DATA = bytes.fromhex("02")
REQ_TOF2_DATA = bytes.fromhex("03")
REQ_ACCEL_DATA = bytes.fromhex("04")
REQ_SPEED_DATA = bytes.fromhex("05")
REQ_SERVO_DATA = bytes.fromhex("06")
REQ_FSM_STATE = bytes.fromhex("07")
# Response Messages (RES)
RES_ALL_SENSOR_DATA = bytes.fromhex("21")
RES_TOF1_SENSOR_DATA = bytes.fromhex("22")
RES_TOF2_SENSOR_DATA = bytes.fromhex("23")
RES_ACCEL_DATA = bytes.fromhex("24")
RES_SPEED_DATA = bytes.fromhex("25")
RES_SERVO_DATA = bytes.fromhex("26")
RES_FSM_STATE = bytes.fromhex("27")
RES_ALL_COMMAND_DATA = bytes.fromhex("28")
# Special Commands (SPC)
SPC_LOOPBACK = bytes.fromhex("70")
SPC_LOOPBACK_RESPONSE = bytes.fromhex("71")
SPC_ACKNOWLEDGE = bytes.fromhex("79")
SPC_START_OF_FRAME = bytes.fromhex("7A")
SPC_ESCAPE = bytes.fromhex("7D")
SPC_END_OF_FRAME = bytes.fromhex("7E")
# Synchronization
SYN_MC = bytes.fromhex("00")
SYN_BC = bytes.fromhex("7F")
def __init__(self, opcode: bytes):
self._opcode = opcode
@property
def opcode(self) -> bytes:
""" Returns a 8bit unsigned number containing the Opcoode of the Command
Returns:
8bit unsigned number representing the Opcoode
"""
return self._opcode[0:1]
class TICPMessageType(Enum):
"""Enumeration for Message Types of the TICP Protocol. This Class is a specialization of
the Enum class. Use this Enumeration for the creation of TICP Messages.
Example:
For the creation of TICPMessageType Enum from existing TICPCommands use
the TICPCMessageTypeFactory
$ factory = TICPMessageTypeFactory()
$ msg = factory.get_TICPMessageType_from_TICPCommand(TICPCommand.SYN_MC)
_Git Repository:
https://github.com/eddex/pren2
"""
# Request Messages REQ
REQ_ALL_SENSOR_DATA_MSG = (TICPCommand.REQ_ALL_SENSOR_DATA, 0)
REQ_TOF1_DATA_MSG = (TICPCommand.REQ_TOF1_DATA, 0)
REQ_TOF2_DATA_MSG = (TICPCommand.REQ_TOF2_DATA, 0)
REQ_ACCEL_DATA_MSG = (TICPCommand.REQ_ACCEL_DATA, 0)
REQ_SPEED_DATA_MSG = (TICPCommand.REQ_SPEED_DATA, 0)
REQ_SERVO_DATA_MSG = (TICPCommand.REQ_SERVO_DATA, 0)
REQ_FSM_STATE_MSG = (TICPCommand.REQ_FSM_STATE, 0)
# Response Message RES
RES_ALL_SENSOR_DATA_MSG = (TICPCommand.RES_ALL_SENSOR_DATA, 10)
RES_TOF1_SENSOR_DATA_MSG = (TICPCommand.RES_TOF1_SENSOR_DATA, 1)
RES_TOF2_SENSOR_DATA_MSG = (TICPCommand.RES_TOF2_SENSOR_DATA, 1)
RES_ACCEL_DATA_MSG = (TICPCommand.RES_ACCEL_DATA, 4)
RES_SPEED_DATA_MSG = (TICPCommand.RES_SPEED_DATA, 2)
RES_SERVO_DATA_MSG = (TICPCommand.RES_SERVO_DATA, 1)
RES_FSM_STATE_MSG = (TICPCommand.RES_FSM_STATE, 1)
RES_ALL_COMMAND_DATA_MSG = (TICPCommand.RES_ALL_COMMAND_DATA, 1)
# Special Commands SPC
SPC_LOOPBACK_MSG = (TICPCommand.SPC_LOOPBACK, 1)
SPC_LOOPBACK_RESPONSE_MSG = (TICPCommand.SPC_LOOPBACK_RESPONSE, 1)
SPC_ACKNOWLEDGE_MSG = (TICPCommand.SPC_ACKNOWLEDGE, 0)
SPC_START_OF_FRAME_MSG = (TICPCommand.SPC_START_OF_FRAME, 0)
SPC_ESCAPE_MSG = (TICPCommand.SPC_ESCAPE, 0)
SPC_END_OF_FRAM_MSG = (TICPCommand.SPC_END_OF_FRAME, 0)
# Synchronization
SYN_MC_MSG = (TICPCommand.SYN_MC, 0)
SYN_BC_MSG = (TICPCommand.SYN_BC, 0)
def __init__(self, command: TICPCommand, payload_size: int):
self._command = command
self._payload_size = payload_size
@property
def command(self) -> TICPCommand:
""" Return the TICPCommand Enum of the TICPMessageType
:return: TICPCommand
"""
return self._command
@property
def payload_size(self) -> int:
""" Returns the length of the message payload as number of byte (8bit) blocks.
:return: int
"""
return self._payload_size
class TICPMessageTypeFactory:
"""
Factory for creation of TICPMessageType Enumerations
_Git Repository:
https://github.com/eddex/pren2
"""
def __init__(self):
self.__command_to_msg_type_dict = {}
self.__init_command_to_msg_type_dict()
def __init_command_to_msg_type_dict(self) -> None:
"""
Initializes a Python Dictionary for a translation of TICPCommand to TICPMessageType
Returns:
"""
for msg in TICPMessageType:
self.__command_to_msg_type_dict[msg.command] = msg
def get_ticp_message_type_from_command(self, command: TICPCommand) -> TICPMessageType:
""" Factory methode for creating an TICPMessageType from a TICPCommand
Args:
command: The TICPCommand for which a TICPMessageType should be created
Returns:
The return value in form of an TICPMessageType Enum
"""
return self.__command_to_msg_type_dict[command]
def get_ticp_message_type_from_int(self, opcode: int) -> TICPMessageType:
""" Factory methode for creating an TICPMessageType from a 'uint8' opcode
Args:
opcode: The opcode for which a TICPMessageType should be created
Returns:
The return value in form of an TICPMessageType Enum
"""
opcode_bytes = opcode.to_bytes(1, byteorder=sys.byteorder, signed=False)
cmd = TICPCommand(opcode_bytes)
return self.__command_to_msg_type_dict[cmd]
def get_ticp_message_type_from_byte(self, opcode: bytes) -> TICPMessageType:
cmd = TICPCommand(opcode)
return self.__command_to_msg_type_dict[cmd]
|
# rstrip, lstrip, strip: will not change the string itself.
str1 = " Test Test Test "
# rstrip
print(str1.rstrip())
# lstrip
print(str1.lstrip())
# strip
print(str1.strip())
|
# RUN = 32
#mengurutkan indeks dari kiri ke kanan dengan ukuran yang paling besar pada RUN
def insertionSort(arr, left, right):
for i in range(left + 1, right+1):
temp = arr[i]
j = i - 1
while arr[j] > temp and j >= left:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = temp
# menggabungkan nilai yang sudah di urutkan run
def merge(arr, l, m, r):
#memisah array dalam 2 bagian
len1, len2 = m - l + 1, r - m
left, right = [], []
for i in range(0, len1):
left.append(arr[l + i])
for i in range(0, len2):
right.append(arr[m + 1 + i])
i, j, k = 0, 0, l
# setelah membandingkan , kemudian di gabungkan dalam sub array
while i < len1 and j < len2:
if left[i] <= right[j]:
arr[k] = left[i]
i += 1
else:
arr[k] = right[j]
j += 1
k += 1
# menyalin elemen yang ada di kiri jika masih tersisa
while i < len1:
arr[k] = left[i]
k += 1
i += 1
# menyalin elemen yang ada di kanan jika masih tersisa
while j < len2:
arr[k] = right[j]
k += 1
j += 1
# mengurutkan array[0...n-1] mirip merge sort
# RUN = 32
def timSort(arr, n, RUN):
# RUN = 32
# sorting sub array dengan run
for i in range(0, n, RUN):
insertionSort(arr, i, min((i+31), (n-1)))
# mulai menggabungkan dari ukuran run (32).
# akan digabungkan ke ukuran 64, kemudian 128, 256, dst
size = RUN
while size < n:
# mengambil nilai awal dari array kiri.
# menggabungkan arr[left..left+size-1] dan arr[left+size, left+2*size-1]
# setelah semua di gabungkan, ukuran left di jadikan 2*size
for left in range(0, n, 2*size):
# find ending point of left sub array
# mid+1 is starting point of right sub array
mid = left + size - 1
right = min((left + 2*size - 1), (n-1))
# merge sub array arr[left.....mid] &
# arr[mid+1....right]
merge(arr, left, mid, right)
size = 2*size
# utility function to print the Array
def printArray(arr, n):
for i in range(0, n):
print(arr[i], end = " ")
print()
arr = [14, 23, 12, 42, 37, 3, 34, 22, 1, 19]
n = len(arr)
print("Data awal:")
r = 32
printArray(arr, n)
timSort(arr, n, r)
print("Data setelah diurutkan:")
printArray(arr, n)
|
def functionselection(llist):
for i in range(len(llist)):
#mencari elemen terkecil
min_idx = i
for j in range(i+1, len(llist)):
if llist[min_idx] > llist[j]:
min_idx = j
#menukar elemen terkecil dengan elemen pertama
llist[i], llist[min_idx] = llist[min_idx], llist[i]
m = [11, 21, 12, 42, 37, 3, 34, 22, 1, 19]
functionselection(m)
print ("Sorted array")
print (m)
# for i in range(len(m)):
# print("%d "%m[i]) |
"""CSC148 Assignment 2
=== CSC148 Winter 2020 ===
Department of Computer Science,
University of Toronto
This code is provided solely for the personal and private use of
students taking the CSC148 course at the University of Toronto.
Copying for purposes other than this use is expressly prohibited.
All forms of distribution of this code, whether as given or with
any changes, are expressly prohibited.
Authors: Diane Horton, David Liu, Mario Badr, Sophia Huynh, Misha Schwartz,
and Jaisie Sin
All of the files in this directory and all subdirectories are:
Copyright (c) Diane Horton, David Liu, Mario Badr, Sophia Huynh,
Misha Schwartz, and Jaisie Sin
=== Module Description ===
This file contains the hierarchy of Goal classes.
"""
from __future__ import annotations
import math
import random
from typing import List, Tuple
from block import Block
from settings import colour_name, COLOUR_LIST
def generate_goals(num_goals: int) -> List[Goal]:
"""Return a randomly generated list of goals with length num_goals.
All elements of the list must be the same type of goal, but each goal
must have a different randomly generated colour from COLOUR_LIST. No two
goals can have the same colour.
Precondition:
- num_goals <= len(COLOUR_LIST)
"""
# determines if Perimeter Goal or Blob Goal
num = random.randint(0, 1)
# lst keeps track goals, track_colour keeps track colour
lst, track_colour = [], []
if num == 0:
# Adds to lst of BlobGoal until it reaches num_goals number of goals
while num_goals > 0:
num = random.randint(0, 3)
if num not in track_colour:
track_colour.append(num)
lst.append(BlobGoal(COLOUR_LIST[num]))
num_goals -= 1
else:
# Adds to lst of PerimeterGoal until it reaches num_goals number of
# goals
while num_goals > 0:
num = random.randint(0, 3)
if num not in track_colour:
track_colour.append(num)
lst.append(PerimeterGoal(COLOUR_LIST[num]))
num_goals -= 1
return lst
def _flatten(block: Block) -> List[List[Tuple[int, int, int]]]:
"""Return a two-dimensional list representing <block> as rows and columns of
unit cells.
Return a list of lists L, where,
for 0 <= i, j < 2^{max_depth - self.level}
- L[i] represents column i and
- L[i][j] represents the unit cell at column i and row j.
Each unit cell is represented by a tuple of 3 ints, which is the colour
of the block at the cell location[i][j]
L[0][0] represents the unit cell in the upper left corner of the Block.
"""
if block.level == block.max_depth:
return [[block.colour]]
elif len(block.children) == 0:
temp = []
unit = int(math.pow(2, (block.max_depth - block.level)))
for i in range(unit):
temp.append([block.colour] * unit)
return temp
else:
temp = []
top_left = _flatten(block.children[1])
bottom_left = _flatten(block.children[2])
top_right = _flatten(block.children[0])
bottom_right = _flatten(block.children[3])
for i in range(len(top_left)):
tup = top_left[i] + bottom_left[i]
temp.append(tup)
for i in range(len(top_right)):
tup = top_right[i] + bottom_right[i]
temp.append(tup)
return temp
class Goal:
"""A player goal in the game of Blocky.
This is an abstract class. Only child classes should be instantiated.
=== Attributes ===
colour:
The target colour for this goal, that is the colour to which
this goal applies.
"""
colour: Tuple[int, int, int]
def __init__(self, target_colour: Tuple[int, int, int]) -> None:
"""Initialize this goal to have the given target colour."""
self.colour = target_colour
def score(self, board: Block) -> int:
"""Return the current score for this goal on the given board.
The score is always greater than or equal to 0.
"""
raise NotImplementedError
def description(self) -> str:
"""Return a description of this goal."""
raise NotImplementedError
class PerimeterGoal(Goal):
"""Stores the score for players. This goal is for storing scores of
player colours around the perimeter of the box"""
def score(self, board: Block) -> int:
"""Calculates the score for perimeter goal"""
flattened = _flatten(board)
score = 0
length = len(flattened)
for i in range(length):
if flattened[i][0] == self.colour:
score += 1
if flattened[i][-1] == self.colour:
score += 1
if flattened[0][i] == self.colour:
score += 1
if flattened[-1][i] == self.colour:
score += 1
return score
def description(self) -> str:
"""Returns a description for perimeter goal"""
return 'Player gains a point for each ' + colour_name(self.colour) + \
' connected along the perimeter'
class BlobGoal(Goal):
"""Stores the goal for players. Blob goal accounts for the max score for
player's colours connected top/left/right/bottom together. Player gains
a point for each block connected together."""
def score(self, board: Block) -> int:
"""Calculates the score for blob goal"""
score = []
flatten_board = _flatten(board)
board_size = len(flatten_board)
# fill the board with -1's
visit = [[-1] * board_size for _ in range(board_size)]
for i in range(board_size):
for w in range(board_size):
if visit[i][w] == -1:
score.append \
(self._undiscovered_blob_size
((i, w), flatten_board, visit))
return max(score)
def _undiscovered_blob_size(self, pos: Tuple[int, int],
board: List[List[Tuple[int, int, int]]],
visited: List[List[int]]) -> int:
"""Return the size of the largest connected blob that (a) is of this
Goal's target colour, (b) includes the cell at <pos>, and (c) involves
only cells that have never been visited.
If <pos> is out of bounds for <board>, return 0.
<board> is the flattened board on which to search for the blob.
<visited> is a parallel structure that, in each cell, contains:
-1 if this cell has never been visited
0 if this cell has been visited and discovered
not to be of the target colour
1 if this cell has been visited and discovered
to be of the target colour
Update <visited> so that all cells that are visited are marked with
either 0 or 1.
"""
if len(board) > pos[0] >= 0 and len(board) > pos[1] >= 0 and \
visited[pos[0]][pos[1]] == -1:
# if it is that colour
if board[pos[0]][pos[1]] == self.colour:
visited[pos[0]][pos[1]] = 1
size = 1
# 2 for loops checks left, top, right, bottom
for i in range(-1, 2):
size += self._undiscovered_blob_size \
((i + pos[0], pos[1]), board, visited)
for w in range(-1, 2):
size += self._undiscovered_blob_size \
((pos[0], w + pos[1]), board, visited)
return size
else:
visited[pos[0]][pos[1]] = 0
return 0
def description(self) -> str:
"""Returns a description for blob goal"""
return 'Player gains a point for each ' + colour_name(self.colour) + \
' connected together'
if __name__ == '__main__':
import python_ta
python_ta.check_all(config={
'allowed-import-modules': [
'doctest', 'python_ta', 'random', 'typing', 'block', 'settings',
'math', '__future__'
],
'max-attributes': 15
})
|
s1=input("Enter comma-separated alphabets:")
lis=s1.split(",")
tup=tuple(lis)
print(tup)
print("SECOND METHOD")
lis1=[]
s2=input("Enter a string:")
for i in s2:
lis1.append(i)
tup1=tuple(lis1)
print(tup1)
print("THIRD METHOD")
l1=[]
while(True):
s2=input("Enter an alphabet:")
if(s2.isalpha()):
l1.append(s2)
t1=tuple(l1)
else:
break
print(t1)
|
import random
import string
def generate_password(password_length):
random_source = string.ascii_letters + string.digits + string.punctuation
password = random.choice(string.ascii_lowercase)
password += random.choice(string.ascii_uppercase)
password += random.choice(string.digits)
password += random.choice(string.punctuation)
for i in range(password_length - 4):
password += random.choice(random_source)
password_list = list(password)
random.SystemRandom().shuffle(password_list)
password = ''.join(password_list)
return password
print("Please choose a password length")
password_length = int(input())
if password_length < 4:
try:
password_length = int(input("Please choose a password of 4 characters or more "))
except ValueError:
print("Oops! That was no valid number. Try again...")
print(f"Your {password_length} character password is {generate_password(password_length)}")
|
import sys
import timeit
# Tuples are orderd, immutable, allows duplicate elements
intelcpu = ("3.2Gz", 2019, "genuine")
print(intelcpu)
# mytuple = ("max",) <= string, end with , to make it tuple
# Create tuple from list with 'tuple' keyword
user = tuple(["Max", 28, "Boston", "BS Computer Science", "WSU"])
print(user[-1], user[0], user[-2])
for tuple_itmes in user:
print(tuple_itmes)
# Return number of occurance of a value in tuple
print(user.count('Max'))
# search index place of a string within tuple
print(user.index('Boston',0,len(user)))
# Tuple does not support item assignment
# user[0] = "Bobby" <= will fail
# If item is in the tuple
if "Bobby" in user:
print("Yes")
else:
print("Bobby is not in tuple")
# We can make list out of tuple
user_list = list(user)
print(type(user_list))
print(user_list)
user_list.append('USA')
user = tuple(user_list)
print(user)
# Variable
(power, year, model) = intelcpu
print(power)
# Tuple & List Comparison
a_list = ["Apple", "Banana", "Mango", True, 0]
a_tuple = ("Apple", "Banana", "Mango", True, 0)
print(sys.getsizeof(a_list),"bytes")
print(sys.getsizeof(a_tuple),"bytes")
# Tuples are more efficient then list
# comparison based on timing
print(timeit.timeit(stmt="[0,1,2,3,4,5]", number=10000000))
print(timeit.timeit(stmt="(0,1,2,3,4,5)", number=10000000))
|
NAMES = ['arnold schwarzenegger', 'alec baldwin', 'bob belderbos',
'julian sequeira', 'sandra bullock', 'keanu reeves',
'julbob pybites', 'bob belderbos', 'julian sequeira',
'al pacino', 'brad pitt', 'matt damon', 'brad pitt']
NAMES = [name.title() for name in NAMES]
print(NAMES)
def reverse_name(name):
first,last = name.split()
return f'{last} {first}'
n = [reverse_name(name) for name in NAMES]
print(n)
|
# Booleans in Python
# Booleans only take two values True or False
Today_is_Friday = True
print(Today_is_Friday)
a = 3
b = 5
print( a == b)
print( a != b)
print( a < b)
print( a > b)
# All non-empty strings are default to True
# All empty strings are default to False
# bool(int) will be True if int is non-zero
#bool(int) will be False if 0
print(bool("abid")) #True
print(bool("")) #False
print(bool(0))
print(bool(10))
#None is another boolean type that means nothing
# None is similar to null and will print nothing
|
def sort(arr):
for x in range (0,len(arr)):
lowest = arr[x]
lowestIndex = x
for y in range (x+1,len(arr)):
if(arr[y]<arr[lowestIndex]):
lowest = arr[y]
lowestIndex = y
arr[lowestIndex] = arr[x]
arr[x] = lowest
return arr
def median(arr):
answer = -1
if(len(arr)%2==1):
answer = arr[round(((len(arr))/(2)-.5))]
else:
a1 = (float)(arr[round(((len(arr)-1)/(2)-.5))])
a2 = (float)(arr[round(((len(arr)-1)/(2)+.5))])
answer = (a1+a2)/2
print("Median: %s" %answer)
def mean(arr):
num = 0
for x in range (0,len(arr)):
num = num + (float)(arr[x])
answer = (float)(num/len(arr))
print("Mean: %s" %answer)
return answer
def Range(arr):
answer = arr[len(arr)-1]-arr[0]
print("Range: %s"%answer)
def standardDev(arr,avg):
average = avg
degreesOfFreedom = len(arr)-1
num = 0
for x in range (0,len(arr)):
num = num + (arr[x]-avg)**2
s = (num/degreesOfFreedom)**(1/2)
print("Standard Deviation: %s"%s)
#''''''''''''''''''''''''''''''''''''''''''''''''#
print("Welcome to the data organizer!")
arr = []
done = 1
arrayLength = int(input("How many elements do you have? "))
x = 0
while(x<arrayLength):
element = (float)(input("What is your next value? "))
arr.append(element)
x = x+1
arr = sort(arr)
print("Sorted array: %s" %arr)
avg = mean(arr)
median(arr)
Range(arr)
standardDev(arr,avg)
|
from typing import List
import re
def separate_with_dash(tokens: List[str], sep: chr = ' ') -> str:
tokens = [re.sub(r'་([^ །])', r'-\1', t) for t in tokens]
return sep.join(tokens)
|
"""
Simple rules
"""
def nil_rule(facts):
return None
def un_rule(facts):
return facts
def raise_rule(ex, mes):
def raise_warn(facts):
m = "%s -> %s" % (mes, str(facts))
raise ex(m)
return raise_warn
def is_instance_rule(t):
def is_instance(facts):
if isinstance(facts, t):
return True
return False
return is_instance
def is_null_rule(facts):
if facts is None:
return True
return False
def and_rule(*bs):
def _and(facts):
for b in bs:
if b(facts) is False:
return False
return True
return _and
def not_rule(b):
def _not(facts):
if b(facts) is True:
return False
return True
return _not
def decision_tree_rule(*args):
"""
The *args must be a list[{bool, function}, {bool, function}, {bool, function}...]
The bool can be a simple var, or you can give it an function, but the function must be return a bool
"""
def decision(facts):
for each in args:
dec, action = each.items()[0]
if isinstance(dec, bool):
if dec is True:
return action(facts)
else:
if dec(facts) is True:
return action(facts)
return False
return decision
def sequence_rule(*rules):
flow = rules
def sequence(facts):
for each in flow:
facts = each(facts)
return facts
return sequence
def if_else_rule(IF, TRUE, FALSE=un_rule):
def if_else(facts):
if IF(facts):
return TRUE(facts)
else:
return FALSE(facts)
return if_else
def for_dict_rule(KEY_RULE=nil_rule, VAL_RULE=nil_rule):
"""
use some rule, make dict to list
like --> [(1, "tom"), (2, "jack"), ("at", 6)]
:param KEY_RULE: rule for key
:param VAL_RULE: rule for value
:return: list
"""
def for_dict(facts):
result = dict()
for k, v in facts.iteritems():
nk = KEY_RULE(k)
nv = VAL_RULE(v)
if nk and nv:
result[nk] = nv
elif nk and not nv:
result[nk] = None
else:
continue
return result
return for_dict
def for_list_rule(ITEM_RULE=un_rule):
def for_list(facts):
result = list()
for each in facts:
result.append(ITEM_RULE(each))
return result
return for_list
def func_rule(f_source, *args):
app = eval(f_source % args)
return app
"""
Extend for simple rule
"""
def lower_rule(facts):
return facts.lower()
def upper_rule(facts):
return facts.upper()
# def replace_rule(r_aim, r_t):
# def replace(facts):
# return facts.replace(r_aim, r_t)
# return replace
def join_rule(j_str):
def join(facts):
f = [str(a) for a in facts]
return j_str.join(f)
return join
def to_type_rule(t):
def to(facts):
return t(facts)
return to
"rules"
NIL = nil_rule
UN_DO = un_rule
ERR = raise_rule
# bool
NOT = not_rule
AND = and_rule
IS_NULL = is_null_rule
IS = is_instance_rule
# stream
IE = if_else_rule
SEQ = sequence_rule
DECT = decision_tree_rule
FOR_DICT = for_dict_rule
FOR_LIST = for_list_rule
FUNC = func_rule
# arg transform
LOWER = lower_rule
UPPER = upper_rule
# REP = replace_rule
JOIN = join_rule
TO = to_type_rule
"""
Assemble tool package
"""
IS_STR = IS((str, unicode))
IS_LIST = IS((list, tuple))
IS_DICT = IS(dict)
TO_STR = TO(str)
NOT_NULL = NOT(IS_NULL)
__all__ = ["NIL", "UN_DO", "ERR", "NOT", "AND", "IS_NULL",
"IS", "IE", "SEQ", "DECT", "FOR_DICT", "FOR_LIST",
"FUNC", "LOWER", "UPPER", "JOIN", "TO",
"IS_STR", "IS_LIST", "IS_DICT", "TO_STR", "NOT_NULL"
]
|
# 1.4
# Palindrome Permutation
# Given a string, write a function to check if it is a permutation of a palindrome. A palindrome is
# a word or phrase that is the same forwards and backwards. A permutation is a rearrangement of
# letters. The palindrome does not need to be limited to just dictionary words.
# EXAMPLE
# Input: Tact Coa
# Output: True (permutations: "taco cat", "atco, cta", etc.)
|
import unittest
from student import Student
class StudentTest(unittest.TestCase):
def testDefaults(self):
student = Student()
self.assertEqual(student.name, Student.DEFAULT_NAME)
self.assertEqual(student.grade, Student.DEFAULT_GRADE)
self.assertEqual(student.fail, False)
def testSpecific(self):
testName : str = "John Smith"
testGrade : int = Student.FAILING_GRADE - 10
student = Student(name = testName, grade = testGrade)
self.assertEqual(student.name, testName)
self.assertEqual(student.grade, testGrade)
#self.assertEqual(student.fail, True)
if __name__ == '__main__':
unittest.main() |
# coding=utf-8
def fibonacci():
a, b = 0, 1
while True:
yield b
a, b = b, a+b
fib = fibonacci()
elems = [next(fib) for _ in range(10)]
print(elems)
|
# 우리가 제공되는 API(Advanced Programming Interface)를 사용해야 하는 이유
class Person:
def __init__(self, age=0, name=''):
self._age = age
self._name = name
@property
def age(self):
return self._age
@age.setter
def age(self, age):
# 0을 포함한 양의 정수값만 입력이 가능하도록
try:
age = str(age)
if not (age[0] == '-' and age[1:].isdecimal()):
self._age = int(age)
else:
print('음수는 입력할 수 없습니다.')
except Exception as e:
print('입력값이 부정확 합니다')
장동건 = Person()
장동건.age = 0
print('age: {}'.format(장동건.age))
|
from threading import Thread
import time
def countdown(n):
while n > 0:
n -= 1
c = 50000000
t1 = Thread(target=countdown, args=(c//2, ))
t2 = Thread(target=countdown, args=(c//2, ))
start = time.clock()
t1.start(); t2.start()
t1.join(); t2.join()
stop = time.clock()
print("elapsed time: {}".format(stop - start)) |
from pandas import DataFrame, read_csv
import pandas as pd
import matplotlib.pyplot as plt
# The initial set of baby names and birth rates
names = ['Bob', 'Jessica', 'Mary', 'John', 'Mel']
births = [968, 155, 77, 578, 973]
# To merge these two lists together, use the zip function
BabyDataSet = zip(names, births)
df = pd.DataFrame(data=BabyDataSet, columns=['Names', 'Births'])
df.to_csv('../data/births_ex.csv', index=False, header=False)
|
class Node():
def __init__(self,data):
self.data = data
self.prev=None
self.next=None
def get_prev(self):
return self.prev
def set_prev(self,prev):
self.prev = prev
def get_next(self):
return self.next
def set_next(self,next):
self.next = next
def get_data(self):
return self.data
def set_data(self,data):
self.data = data
class DLinkedList():
def __init__(self):
self.head=None
def add(self,item):
temp = Node(item)
temp.set_next(self.head)
if self.head is not None:
self.head.set_prev(temp)
self.head = temp
def insert_after(self, prev_node, data):
if prev_node is None:
print('previous note cannot be None')
return
new_node = Node(data)
new_node.set_next(prev_node.next)
prev_node.set_next(new_node)
new_node.set_prev(prev_node)
if new_node.get_next()!=None:
new_node.get_next().set_prev(new_node)
def append(self,item):
new_node = Node(item)
new_node.set_next(None)
if self.head is None:
new_node.set_prev(None)
self.head=new_node
last_node = self.head
while last_node.get_next()!=None:
last_node=last_node.get_next()
last_node.set_next(new_node)
new_node.set_prev(last_node)
def print(self):
current = self.head
while current!=None:
print(current.get_data())
current=current.get_next()
mylist = DLinkedList()
mylist.add(2)
mylist.add(3)
mylist.add(4)
mylist.insert_after(mylist.head, 8)
mylist.append(7)
mylist.print() |
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 13 15:45:07 2020
@author: sis
"""
import socket
hostname = socket.gethostname()
IPAddr = socket.gethostbyname(hostname)
print("Your Computer Name is:" + hostname)
print("Your Computer IP Address is:" + IPAddr) |
1
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 1 17:01:20 2020
@author: sis
"""
while True:
balance=10000
print("ATM")
print("""
1)balance
2)withdraw
3)deposit
4)Quit """)
try:
option=int(input("enter option:"))
except Exception as e:
print("Error:",e)
print("enter 1,2,3 or 4 only")
continue
if option==1:
print("Balance $ ",balance)
if option==2:
print("Balance $ ",balance)
withdraw=float(input("Enter withdraw amount $"))
if Withdraw>0:
forewardbalance=(balance-Withdraw)
print("foreward balance $ ",forewardbalance)
elif Withdraw>balance:
print("no fuds in account")
if option==3:
print("Balance $ ",balance)
Deposit=float(input("enter deposit amount $ "))
if Deposit>0:
forwardbalance=(balance+deposit)
else:
print("none deposit made")
if option==4:
exit()
|
import math
import time
# Using decorators to see the time each function takes to complete the execution.
def timing(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"It took {(end - start) * 1000} mil seconds.")
return result
return wrapper
@timing # Decoration through Pie Syntax
def square(bases):
result = []
for i in bases:
result.append(int((math.pow(i, 2))))
print(result)
@timing # Decoration
def cube(bases):
result = []
for i in bases:
result.append(int(math.pow(i, 3)))
print(result)
mantissa_array = range(1, 100000)
square(mantissa_array)
cube(mantissa_array)
|
"""
DEFINITION
One partition:
One partition (ascending):
Choose the first element to be the sorted portion, and 2nd element for making comparison,
compare the next element to the sorted portion and insert it in the appropriate index of the sorted portion.
Sorted portion has increment by 1, unsorted has decremented by 1
Repeat the partition by comparing the next element from the unsorted portion to the elements in the newly
sorted portion of the array. Each partition is one pass
COMPARISON
Number of comparisons = (N-1)+(N-2)+(N-3)...+1 = (N * (N-1))/2
To insert the first element in the first partition it takes N-1 comparisons, and N decrements by
1 in each subsequent partition, since after each partition one element become into sorted portion
TIME COMPLEXITY
Time Complexity = O(N^2). N is the size of the array
Minimum number of insertion sort comparisons = N - 1
Maximum number of insertion sort comparisons = 1/2(N2 - N)
Average number of insertion sort comparisons = 1/4(N2 - N)
"""
def insertionSort(arr):
# arr[0[ is the assumed portion of array that is sorted
for i in range(1, len(arr)):
# element to be compared
current = arr[i]
# Compare the current element with the sorted portion and swap.
while i>0 and arr[i-1] > arr[i]:
arr[i] = arr[i-1]
i-=1
arr[i] = current
return arr
array = [4, 6, 7, 3, 8, 24, 67]
print(insertionSort(array)) |
# dict(key, value)
# Value can be repeated, but key cannot be repeated.
# This is the concept of HashTable and HashMap
student = dict([(101, 'Robert'), (102, 'William'), (103, 'Anderson')])
print(student)
print(student.keys())
print(student.values())
print(student[101])
# The default iterable is the keys, not values. Only key is printed, not the pair.
for s in(student):
print(s)
for s in (student.values()):
print(s)
teacher = {101:"Anderson", 102:"DeLone", 103:"McCormick", 104:"Suleimann"} # simpler way to create a dict
body = {"student": student, "teacher": teacher} # dictionary of dictionaries.
print(body["teacher"])
student_copied = student.copy() # make a copy |
from decimal import Decimal
"""This program implements the RSA algorithm"""
# from math import gcd can be used as well
def gcd(a, b):
if a==a:
return a, 0, 1
else:
return gcd(b, a%b)
def RSA(p, q, no):
n = p*q
t = (p-1)*(q-1)
for e in range(2, t):
if gcd(e, t) == 1:
break
for i in range(1, 10):
x = 1 + i*t
if x%e == 0:
d = int(x/e)
break
ctt = Decimal(0)
ctt = pow(no, e)
ct = ctt % n
dtt = Decimal(0)
dtt = pow(ct, d)
dt = dtt % n
return ('n = '+str(n)+' e = '+str(e)+' t = '+str(t)+' d = '+str(d)+' cipher text = '
+str(ct)+' decrypted text = '+str(dt))
print(RSA(37, 47, 69))
|
arr1 = [1, 232, 345, 345, 2346]
# This is because a list is iterable
for num in iter(arr1):
print(num)
# A tuple is also iterable
arr2 = {1, 2, 45, 56}
for num in iter(arr2):
print(num)
student = {101: "William", 102: "Henry", 103: "Joshua", 104: "George"}
# A dictionary is also iterable (specifically its keys or values)
# By default, a dictionary is iterated through the keys.
for s in iter(student):
print(s)
|
import nltk
from nltk.stem import PorterStemmer
porter = PorterStemmer()
words = ['fish', 'fishing']
for word in words:
print(f"{word}: {porter.stem(word)}")
print("\n")
words = ['game', 'gaming', 'gamed', 'games']
for word in words:
print(f"{word}: {porter.stem(word)}")
|
import math
# Default Argument
def greeting(name='User'):
print(f"Welcome, {name}!")
greeting() # <= default case
greeting('Allie')
# Keyword Argument
def expon(a, b):
return math.pow(a, b)
print(expon(a=24, b=3)) # Both gives the same answers because a and b are now keywords
print(expon(b=3, a=24))
# Arbitrary args
def sayhello(*names):
for name in names:
print(f"Hello, {name}")
sayhello('Zakir', 'Allie', 'Julia', 'Amber')
|
"""
This program implements the Havel-Hakimi Algorithm, which finds if a degree sequence can form a a valid graph
"""
def graphExist(a):
# Keep performing the operations until one of the stopping condition is met
while True:
#Sort the list in a non-increasing order
a = sorted(a, reverse=True)
# Check if all the elements are equal to 0
if a[0]==0 and a[len(a)-1]==0:
return True
#Store the firsr elements in a variable and delete it from the list
v = a[0]
a = a[1:]
# Check if enough element are present in the list
if v>len(a): return False
# Subtract first element from the next v elements
for i in range(v):
a[i] -= 1
# Check if negative element is encountered after subtraction
if a[i]<0: return False
a = [6, 5, 4, 3, 2, 2]
print(graphExist(a))
a = [3, 3, 3, 3]
b = [3, 3, 3]
c = [4, 3, 2, 0]
print(graphExist(a))
print(graphExist(b))
print(graphExist(c))
|
from collections import namedtuple
colors = namedtuple('colors', 'r g b')
red = colors(r=250, g=0, b=0)
print(red.r)
print(red[0])
print(getattr(red, 'r'))
# All 3 gives the same output
# namedtuple is immutable
# Convertible into dict
print(red._asdict())
# Iterables into namedtuple
color1 = colors._make([24, 234, 232])
print(color1)
# Dictionary to namedtuple
color2 = colors(**{'r': 200, 'g': 0, 'b': 67})
print(color2)
# What attributes belong to the tuple
print(color2._fields)
# It is immutable but it's replaceable, but does not change the original
print(color2._replace(**{'g': 34})) |
# reduce(function, sequence)
# Recursive implementation of a function to a sequence.
# First obtains a and b (the first 2 elems) and function is applied to them. result is stored
# To apply the function again, a = result and b = 3rd elem. result is stored.
# The process continues until it hits the last elem
from functools import reduce
A = [12, 34, 45, 67, 43, 2, 3]
# The sum of all elems
s = reduce(lambda a, b: a+b, A)
print(s)
# The max elem
m = reduce(lambda a, b: a if a>b else b, A)
print(m) |
import re
def main():
# 'match' matches the entire string. 'search' look for specific words or character in the string
line = "I think I know it"
matchResult = re.match('think ', line, re.M | re.I)
if matchResult:
print("Match found" + matchResult.group())
else:
print("No match was found") # => output because the entire string is not just 'think'
search_result = re.search('think', line, re.M | re.I)
if search_result:
print("Match found " + search_result.group())
else:
print("Nothing found")
main()
|
class Plateau:
"""
The plateau class keeps track of the bounds of the plateau and can check
whether a given coordinate is within those bounds.
"""
def __init__(self, x_limit, y_limit):
"""
Store the edges as a tuple. They don't need to be mutable.
Does that make sense? Or should these be their own properties?
"""
self.edges = (x_limit, y_limit)
def x_edge(self):
return self.edges[0]
def y_edge(self):
return self.edges[1]
def in_bounds(self, x, y):
"""
We're going to assume x_edge and y_edge are always positive. This could
be built out a little more to allow for multiple plateau quadrants.
"""
return x <= self.x_edge() and y <= self.y_edge()
def __repr__(self):
return '<plateau edges:(%s, %s)>' % (self.x_edge(), self.y_edge())
class Cardinal:
"""
There's enough data associated with the four cardinal directions that I
think they deserve their own class.
"""
def __init__(self, direction, axis, positive):
self.direction = direction
self.axis = axis
self.positive = positive
def __eq__(self, other):
"""
Allows simple strings to be evaluated against this object's direction,
e.g. cardinal_obj == 'N'
"""
return self.direction == other
def __str__(self):
return self.direction
class Rover:
cardinals = (
Cardinal('N', 'y', True),
Cardinal('E', 'x', True),
Cardinal('S', 'y', False),
Cardinal('W', 'x', False)
)
def __init__(self, x, y, cardinal, steps, plateau):
self.x = int(x)
self.y = int(y)
self.cardinal_index = self.get_cardinal_index_by_direction(cardinal)
self.steps = steps
self.step_index = 0
self.plateau = plateau
def move(self):
"""
Moves the rover until the list of steps/instructions are complete.
"""
while self.get_next_step() is not None:
self.take_next_step()
def get_next_step(self):
try:
return self.steps[self.step_index]
except:
return None
def take_next_step(self):
next_step = self.get_next_step()
if next_step == 'L':
status = self.turn_left()
elif next_step == 'R':
self.turn_right()
elif next_step == 'M':
self.move_forward()
if next_step is not None:
self.step_index += 1
#print repr(self)
def turn_left(self):
if self.cardinal_index == 0:
self.cardinal_index = len(self.cardinals) - 1
else:
self.cardinal_index -= 1
#print 'left'
def turn_right(self):
if self.cardinal_index >= len(self.cardinals)-1:
self.cardinal_index = 0
else:
self.cardinal_index += 1
#print 'right'
def move_forward(self):
next_x = self.x
next_y = self.y
current_cardinal = self.get_current_cardinal()
if current_cardinal.axis == 'x':
if current_cardinal.positive:
next_x += 1
else:
next_x -= 1
elif current_cardinal.axis == 'y':
if current_cardinal.positive:
next_y += 1
else:
next_y -= 1
if self.plateau.in_bounds(next_x, next_y):
self.x = next_x
self.y = next_y
#print 'forward'
#else:
#print 'forward failed'
def get_cardinal_index_by_direction(self, cardinal):
"""
Set direction the rover is facing by storing a reference to the index of
the cardinal object inside of the cardinals tuple.
"""
try:
return self.cardinals.index(cardinal)
except:
return None
def get_current_cardinal(self):
"""
Get the cardinal object that corresponds to the direction the rover is
currently facing.
"""
try:
return self.cardinals[self.cardinal_index]
except:
return None
def get_current_position(self):
"""
Get a tuple of the rover's current coordinates and the cardinal
direction it's facing.
"""
return (self.x, self.y, str(self.get_current_cardinal()))
def __str__(self):
return str(self.get_current_position())
def __repr__(self):
return '<rover coordinates:(%i, %i) direction:%s steps:%s next_step:%s>' % (self.x, self.y, str(self.get_current_cardinal()), "".join(self.steps), self.get_next_step())
def parse_file(filename):
"""
Extract plateau edges, and rover coordinates & steps from data file
"""
# Get file contents
file = open(filename, "r")
input_list = file.read().splitlines()
file.close()
# Get plateau edge coordinates
try:
plateau_coordinates = input_list[0].split()
plateau_data = {
'x_edge': plateau_coordinates[0],
'y_edge': plateau_coordinates[1]
}
except:
sys.exit('Invalid input')
# Get rover data
# Use batch_gen() to get two lines of the input_list at a time
rovers_data = []
for rover_data in batch_gen(input_list[1:], 2):
try:
rover_start_params = rover_data[0].split()
rovers_data.append({
'start_x': rover_start_params[0],
'start_y': rover_start_params[1],
'start_cardinal': rover_start_params[2],
'steps': list(rover_data[1])
})
except:
sys.exit('Invalid input')
return {
'plateau_data': plateau_data,
'rovers_data': rovers_data
}
def batch_gen(data, batch_size):
"""
This awesomeness courtesy of http://stackoverflow.com/a/760857
"""
for i in range(0, len(data), batch_size):
yield data[i:i+batch_size]
def main():
data = parse_file('input.dat')
the_plateau = Plateau(data['plateau_data']['x_edge'], data['plateau_data']['x_edge'])
rovers = []
for rover_data in data['rovers_data']:
rovers.append(
Rover(rover_data['start_x'], rover_data['start_y'], rover_data['start_cardinal'], rover_data['steps'], the_plateau)
)
for the_rover in rovers:
the_rover.move()
print str(the_rover.get_current_position())
if __name__ == '__main__':
import sys
main()
|
#!/usr/bin/python3
import random
import simpy
import numpy
###########################################
#Author: Alan Fleming
#Email: alanfleming1998@gmail.com
#Description: This is a script to simulate a McDonalds Drivethru
#Asummuptions: The inter-arrival time is representable by a exponential distribution
# The ordering line has an infinite queue
# The ordering time is representable by a lognormal distribution
# The Payment time is representable by a lognormal distribution
# The Pickup time is representable by a exponential distribution
# No cars will leave the line due to excessive wait times or length
###########################################
#process to make customers
def customergen(env, winOrder, linePay, winPay, linePick, winPick,
arrivalTime, orderTime, payTime, PickupTime):
print("starting gen")
number = 0
while(True):
#select pump, line, and wait for a new customer
t = random.expovariate(1.0/0.722)
#handle negative arrival time
if(t < 0):
t = 0
arrivalTime.put(t)
yield env.timeout(t)
#make and run a new customer
c = customer(env, number, winOrder, linePay, winPay, linePick, winPick,
orderTime, payTime, PickupTime)
env.process(c)
number = number+1
#process to run customers through customerwash
def customer(env, number, winOrder, linePay, winPay, linePick, winPick,
orderTime, payTime, PickupTime):
print("%d arrives at drive-thru at %d" % (number, env.now))
#order time
window = winOrder.request()
yield window
t = random.lognormvariate(-1.367,0.684)
#handle negative required time
if(t < 0):
t = 0
orderTime.put(t)
yield env.timeout(t)
#get a spot in line before you release the window
line = linePay.request()
yield line
winOrder.release(window)
#take a spot at the window and leave the line
window = winPay.request()
yield window
linePay.release(line)
#pay time
t = random.lognormvariate(0.830,1.010)
if(t < 0):
t = 0
payTime.put(t)
yield env.timeout(t)
#get a spot in line before you release the window
line = linePick.request()
yield line
winPay.release(window)
#take a spot at the window and leave the line
window = winPick.request()
yield window
linePick.release(line)
#pickup time
t = random.expovariate(1.0/-0.827)
if(t < 0):
t = 0
PickupTime.put(t)
yield env.timeout(t)
winPick.release(window)
#seed the random number
random.seed(2019)
##reminders for random numbers
#arival random number => random.expovariate(1.0/mean)
#pump random number => random.lognormvariate(scale,shape)
##settup and run the simpulation
#make the enviroment
env = simpy.Environment()
#setup the resources
orderWindow = simpy.Resource(env,capacity=1)
payLine = simpy.Resource(env,capacity=3)
payWindow = simpy.Resource(env,capacity=1)
pickupLine = simpy.Resource(env,capacity=1)
pickupWindow = simpy.Resource(env,capacity=1)
#setup stores for record keeping
arrivalTime = simpy.Store(env)
orderTime = simpy.Store(env)
payTime = simpy.Store(env)
PickupTime = simpy.Store(env)
#setup the process
env.process(customergen(env, orderWindow, payLine, payWindow, pickupLine, pickupWindow, arrivalTime, orderTime, payTime, PickupTime))
#run the sim for 1020 time units
env.run(until = 120)
print("averages: \narrival time: %3.5f , order time: %3.5f , pay time: %3.5f , pickup time: %3.5f" %
(numpy.mean(arrivalTime.items) ,numpy.mean(orderTime.items) ,numpy.mean(payTime.items) ,numpy.mean(PickupTime.items)))
|
# course: DSC510
# assignment: 2.1
# date: 3/17/20
# name: Blaine Blasdell
# description: Customer Fiber Optic cable calculator
# Get Today's date for receipt
import datetime
today_date = datetime.datetime.today()
# welcome message
print('Welcome to Blasdell\'s IT Services')
print('\r')
print('Fiber Optic Cable Cost Calculator')
print('\r')
# input customer's company name
company_name = input('Please enter your company name: ')
print('\r')
# input customer's cable need
cable_feet: float = float(input('Please enter the amount of fiber you need (in feet): '))
print('\r')
# set default cable price
default_price = 0.87
cable_price = default_price
# calculate bulk discount
# > 100 feet = 0.80
# > 250 feet = 0.70
# > 500 feel = 0.50
if cable_feet > 500.0:
cable_price = 0.50
elif cable_feet > 250.0:
cable_price = 0.70
elif cable_feet > 100.0:
cable_price = 0.80
# calculate customer price feet * default price
installation_cost = cable_feet * cable_price
# calculate VA State (Prince William County) sales tax and total cost
sales_tax = 0.053
sales_tax_cost = installation_cost * sales_tax
total_cost = sales_tax_cost + installation_cost
# receipt display
print('\r')
print('\r')
print('------------------------------------------------------')
print(' Blasdell\'s IT Services\r')
print(' Receipt\r')
print(' ', today_date.strftime("%m/%d/%y"))
print('\r')
print('\r')
print('Company: ', company_name)
print('Fiber optic cable amount (in feet)', cable_feet)
print('Fiber Cable installation price: $ ', format(cable_price, '.2f'))
print('\r')
print('Installation total: $', format(installation_cost, '.2f'))
print('Sales Tax: $', format(sales_tax, '.3f'))
print('Total Cost (including Tax): ', format(total_cost, '.2f'))
print('\r')
print('------------------------------------------------------')
# end program
|
# Author: Justin Cappos
#
# This program takes files of the form: lat long count
# and produces a drawing of the resulting information. It is assumed that
# the lat goes from -90 to 90 and the long from -179 to 180.
import sys
import Image, ImageDraw
def georgbarep(origvalue):
r,b,g = georgbrep(origvalue)
return (r,g,b,255)
def georgbrep(origvalue):
value = origvalue
if value <= 0:
raise InternalError('value '+str(value)+' is not allowed for count')
if value == 1:
return (192,192,192)
if value <= 10:
return (0,0,135+(12*value))
value = value / 10
if value <= 10:
return (0,135+(12*value),0)
value = value / 10
if value <= 10:
return (135+(12*value),0,0)
value = value / 10
if value <= 10:
return (200+(5*value),200+(5*value), 0)
print 'color overflow!', origvalue
return (255,255,255)
# if value <= 300:
# return (0,250-(value-50),value-50)
# if value <= 1000:
# return ((value) / 4, 0, (1000-(value-300))/ 4)
# if value > 1300:
# print 'color overflow!', value
# return (255,255,255)
def geoasciirep(value):
if value <= 0:
raise InternalError('value '+str(value)+' is not allowed for count')
if value <= 10:
return '.'
if value <= 50:
return 'o'
if value <= 250:
return 'O'
if value <= 1250:
return '@'
return '*'
asciioutfd = open('map.ascii','w')
geolocfn = sys.argv[1]
imageoutname = 'map.png'
imageobj = Image.new('RGBA',(360,180))
#imageobj = Image.new('RGBA',(360,200))
drawobj = ImageDraw.Draw(imageobj)
geodict = {}
for line in file(geolocfn):
thislat, thislong, thiscount = line.split()
thislat = int(thislat)
thislong = int(thislong)
thiscount = int(thiscount)
geodict[(thislat,thislong)] = thiscount
for y in xrange(90,-90,-1):
for x in xrange(180, -180,-1):
if (y,x) not in geodict:
asciioutfd.write(' ')
drawobj.point((x+180,90-y),(0,0,0,0))
else:
asciioutfd.write(geoasciirep(geodict[(y,x)]))
drawobj.point((x+180,90-y),georgbarep(geodict[(y,x)]))
asciioutfd.write('\n')
val = 1
# draw the legend...
for x in range(5,355):
val = val *1.025
drawobj.point((x,175),georgbarep(int(val)))
drawobj.point((x,176),georgbarep(int(val)))
drawobj.point((x,177),georgbarep(int(val)))
drawobj.line((4,174,355,174),(0,0,0,255))
drawobj.line((4,174,4,178),(0,0,0,255))
drawobj.line((4,178,355,178),(0,0,0,255))
drawobj.line((355,174,355,178),(0,0,0,255))
del drawobj
imageobj.save('map.png','PNG')
|
print("begin")
i = 1
while(i<=5):
print("Welcome",i)
i = i+1
else:
print("In while-else")
print("End")
|
import sys
import os
def clear_screen():
os.system('cls' if os.name=='nt' else 'clear')
def get_input(prompt, accept_blank=True):
try:
while True:
response = raw_input(prompt)
if response == "" and accept_blank==False:
print("A response is required here.\n")
else:
return response
except KeyboardInterrupt:
print("\n\nExiting without saving changes.")
sys.exit(1)
def get_yes_no(prompt, yn_ok=True, default=None):
"""Ask the user a Yes or No question.
yn_ok set to True will allow 'y' or 'n' response too.
A default may be specified when the user just presses enter."""
if not prompt.endswith(" "):
prompt += " "
while True:
response = get_input(prompt).lower()
if response == "yes":
return True
elif response == "y" and yn_ok:
return True
elif response == "no":
return False
elif response == "n" and yn_ok:
return False
elif response == "" and default != None:
return default
else:
print("A Yes or No response is required.\n")
|
#! /usr/bin/env python
########
#
# Even Fibonacci numbers
#
########
def fib(n):
if n == 0:
return 0
if n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
def main():
final_sum = 0
max_sequence_value = 4000000
i = 1
while final_sum <= max_sequence_value:
x = fib(i)
if x%2 == 0:
final_sum += x
i += 1
print "Fibanacci Sequence not exceeding ", max_sequence_value, " sum of even-valued terms is: ", final_sum
if __name__ == '__main__':
main()
|
import random
f = open('word_rus.txt', 'r', encoding='utf-8')
words = f.readlines()
w = words[random.randint(1, 34010)]
answer = list('_' * (len(w) - 1))
flag = True
lives = 6
used = list()
print('Your word:')
print(''.join(answer))
while flag:
fl = False
print('Select a letter:')
letter = input()
used.append(letter)
for a in range(len(w)):
if letter == w[a]:
answer[a] = letter
fl = True
if not fl:
lives -= 1
if lives == 0:
print('Your word:')
print(''.join(answer))
print('')
print('Lives:', lives)
print('')
print('You lose(')
print('Correct answer:', w)
flag = False
elif '_' not in answer:
print('Your word:')
print(''.join(answer))
print('')
print('Lives:', lives)
print('')
print('CONGRATULATIONS!')
flag = False
else:
print('Your word:')
print(''.join(answer))
print('')
print('Lives:', lives)
print('Used letters:', ' '.join(used))
|
file system:
windows:NTFS
Ubuntu: ext4
windows, MAC, linux:fat32: support all 3 system
Partition: the piece of a disk that you can manage
two main partition table schemes: MBR(Master boot record) #main on windows, only allow 2TB or less
GPT(GUID partition Table)# 2TB or more, new, no partition limit
windows:
Diskpart # format, after this command, we will enter a speical termianl window
list disk # list all the dist
select disk 1 # select the disk
clean# earse all the data in the disk
create oartition promary # create a partition for the disk
select partition 1 #select the partition just created
active # active the partition
format FS=NTFS label=<name of the disk> quick #format the disk with the factor you typed
linux:
sudo parted -l #show all the disk info
sudo parted /dev/sdb #enter the manage situation, there will be a new terminal , sdb means the second disk, sda is the frist one
print # after entering the special terminal, we can use print to check the state of the disk
mklabel gpt #set the disk label with gpt partition
mkpart primary ext4 1Mib 5Gib # the command used to slice the disk with factor
quit # quit
mount # 这个命令是干啥的?
sudo mount /dev/sdb1/my_usb/ #create a accessable directory so we use new file system
umount #uninstall the file system
/etc/fstab #the direc we used to mount a disk permanently
sudo blkid #to get the block id , which is the uuid for the disk
swap space
enter the parted terminal, then use mkpart primary linux-swap 5GiB 100% #100% means use all the avaiable space
quit the parted, then
sudo mkswap /dev/sdb2
sudo swap on /dev/sdb2
#if we want auto boot a disk every time, then add a swap item in the /etc fstab
windows:
MFT(master file table) #each file has at least one record in MFT, usually it's one on one. but if a file may has more.
MFT:
file name
timestamp
Permission
compression
location
etc.....
file record number: the index of MFT
symbolic link # similar to short cut, but what is the differece????
mklink #we can use this command to make a symbolic link , follwed by -H, will make a hrad link,
#hard link means even change the name, the short cut still point to the orgin file
linxu:
inode#similar to the MFT of windows, contain all the
softlink # point to a file
hardlink # point to a inode in inode table
ln <filename> <filename_hardlink >
ls -l <filename># the last digit, which is a number, indicate the amount of hard link of the file
du -h # to check the usage of the disk, -h make it readable
df-h # disk free, how much free disk on your disk |
# put your python code here
length = int(input())
width = int(input())
height = int(input())
edges = 4 * (length + width + height)
surface = 2 * (length * width + width * height + length * height)
volume = length * width * height
print(edges)
print(surface)
print(volume)
|
""" Card deck program.
"""
import collections
import itertools
deck = collections.namedtuple('deck', 'rank suit')
suit_values = dict(spades=3, hearts=2, diamonds=1, clubs=0)
class FrenchDeck(object):
""" Deck of cards.
"""
ranks = [str(rank) for rank in range(2, 11)] + list('JQKA')
suit = ['spades', 'diamonds', 'hearts', 'clubs']
def __init__(self):
self.cards = [
deck(rank, suit)
for rank, suit in itertools.product(self.ranks, self.suit)
]
def __getitem__(self, position):
""" Make the object iterable and search by index.
"""
return self.cards[position]
def __len__(self):
""" Get the length of the deck.
"""
return len(self.cards)
def __repr__(self):
""" Represent the object.
"""
return "{classname}()".format(classname=self.__class__.__name__)
def spadesHigh(card):
""" Filter spades.
"""
rank_value = FrenchDeck.ranks.index(card.rank)
return rank_value * len(suit_values) + suit_values[card.suit]
if __name__ == "__main__":
deckOfCards = FrenchDeck()
print(sorted(deckOfCards, key=spadesHigh)) |
# 给定n个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为1 。
# 求在该柱状图中,能够勾勒出来的矩形的最大面积。
# 给定的高度为[2, 1, 5, 6, 2, 3]。
# 最大矩形面积为10个单位。
#
# 示例:
# 输入: [2, 1, 5, 6, 2, 3]
# 输出: 10
from typing import List
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
heights.append(0)
n = len(heights)
max_area = 0
stack = list()
for i in range(n):
while stack and heights[i] < heights[stack[-1]]:
top = stack.pop()
this_area = heights[top] * (i - stack[-1] - 1 if stack else i)
if this_area > max_area:
max_area = this_area
stack.append(i)
return max_area
s = Solution()
print(s.largestRectangleArea([2, 1, 5, 6, 2, 3]))
|
# 编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:
# 每行中的整数从左到右按升序排列。
# 每行的第一个整数大于前一行的最后一个整数。
#
# 示例 1:
# 输入:
# matrix = [
# [1, 3, 5, 7],
# [10, 11, 16, 20],
# [23, 30, 34, 50]
# ]
# target = 3
# 输出: true
#
# 示例 2:
# 输入:
# matrix = [
# [1, 3, 5, 7],
# [10, 11, 16, 20],
# [23, 30, 34, 50]
# ]
# target = 13
# 输出: false
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
m = len(matrix)
if m == 0:
return False
n = len(matrix[0])
if n == 0:
return False
total = m * n
lo, hi = 0, total - 1
while lo <= hi:
mid = (lo + hi) // 2
r, c = mid // n, mid % n
if matrix[r][c] == target:
return True
elif matrix[r][c] < target:
lo = mid + 1
else:
hi = mid - 1
return False
s = Solution()
print(s.searchMatrix([[1, 1]], 2))
|
# 给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
#
# 示例:
# 给定一个链表: 1->2->3->4->5, 和 n = 2.
# 当删除了倒数第二个节点后,链表变为 1->2->3->5.
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeNthFromEnd(self, head, n):
dummy_node = ListNode(-1)
dummy_node.next = head
pre_node = dummy_node
cur_node = dummy_node
while n > 0:
cur_node = cur_node.next
n -= 1
while cur_node.next:
cur_node = cur_node.next
pre_node = pre_node.next
pre_node.next = pre_node.next.next
return dummy_node.next
|
# 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
# 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
# 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
#
# 示例:
# 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
# 输出:7 -> 0 -> 8
# 原因:342 + 465 = 807
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
dummy_head = ListNode(-1)
current = dummy_head
carry = 0
while l1 is not None or l2 is not None:
if l1 is not None:
l1_num = l1.val
l1 = l1.next
else:
l1_num = 0
if l2 is not None:
l2_num = l2.val
l2 = l2.next
else:
l2_num = 0
num = l1_num + l2_num + carry
if num > 9:
carry = 1
num -= 10
else:
carry = 0
node = ListNode(num)
current.next = node
current = node
if carry != 0:
current.next = ListNode(carry)
return dummy_head.next
|
# 给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
from typing import List
class Solution:
def singleNumber(self, nums: List[int]) -> int:
res = 0
for i in nums:
res = res ^ i
return res
input = [4, 2, 1, 4, 1]
s = Solution()
print(s.singleNumber(input)) |
# 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
#
# 示例 1:
# 输入: 123
# 输出: 321
#
# 示例 2:
# 输入: -123
# 输出: -321
#
# 示例 3:
# 输入: 120
# 输出: 21
#
# 注意:
# 假设我们的环境只能存储得下 32 位的有符号整数,请根据这个假设,如果反转后整数溢出那么就返回 0。
class Solution:
def reverse(self, x):
is_positive = True
if x < 0:
is_positive = False
x = -x
res = 0
while x != 0:
remainder = x % 10
res = res * 10 + remainder
x = x // 10
if not is_positive:
res = -res
min_int = -pow(2, 31)
max_int = 0x7fffffff
if res <= min_int or res > max_int:
return 0
return res
s = Solution()
print(s.reverse(321))
|
# Description
#
# Given a square grid of size n, each cell of which contains integer cost which represents a cost to traverse through
# that cell, we need to find a path from top left cell to bottom right cell by which total cost incurred is minimum.
#
# Note : It is assumed that negative cost cycles do not exist in input matrix.
#
# Input
# The first line of input will contain number of test cases T. Then T test cases follow . Each test case contains 2
# lines.The first line of each test case contains an integer n denoting the size of the grid. Next line of each test
# contains a single line containing N*N space separated integers depecting cost of respective cell from (0,0) to (n,n).
#
# Constraints:1<=T<=50,1<= n<= 50
#
# Output
# For each test case output a single integer depecting the minimum cost to reach the destination.
#
# Sample Input 1
# 2
# 5
# 31 100 65 12 18 10 13 47 157 6 100 113 174 11 33 88 124 41 20 140 99 32 111 41 20
# 2
# 42 93 7 14
#
# Sample Output 1
# 327
# 63
import sys
def solve(matrix, n):
x_inc = [-1, 1, 0, 0]
y_inc = [0, 0, -1, 1]
cost = [[sys.maxsize // 2 for _ in range(n)] for _ in range(n)]
cost[0][0] = matrix[0][0]
point_set = set()
point_set.add((cost[0][0], 0, 0))
while point_set:
point_min = min(point_set)
c, i, j = point_min
point_set.remove(point_min)
for k in range(4):
x_new = i + x_inc[k]
y_new = j + y_inc[k]
if 0 <= x_new < n and 0 <= y_new < n:
if cost[x_new][y_new] > c + matrix[x_new][y_new]:
cost[x_new][y_new] = c + matrix[x_new][y_new]
point_set.add((cost[x_new][y_new], x_new, y_new))
return cost[n-1][n-1]
t = int(input())
while t > 0:
n = int(input())
num = [[-1 for _ in range(n)] for _ in range(n)]
m = 0
num_str = input().split()
for m in range(n * n):
num[m // n][m % n] = int(num_str[m])
print(solve(num, n))
t -= 1
|
# 给定一个包含非负整数的 m x n 网格,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。
# 说明:每次只能向下或者向右移动一步。
#
# 示例:
# 输入:
# [
# [1,3,1],
# [1,5,1],
# [4,2,1]
# ]
# 输出: 7
# 解释: 因为路径 1→3→1→1→1 的总和最小
class Solution(object):
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
m = len(grid)
n = len(grid[0])
cost = [[0 for _ in range(n)] for _ in range(m)]
cost[0][0] = grid[0][0]
for i in range(1, m):
cost[i][0] = cost[i-1][0] + grid[i][0]
for j in range(1, n):
cost[0][j] = cost[0][j-1] + grid[0][j]
for i in range(1, m):
for j in range(1, n):
cost[i][j] = min(cost[i-1][j], cost[i][j-1]) + grid[i][j]
return cost[m-1][n-1]
s = Solution()
print(s.minPathSum([[1, 2, 5], [3, 2, 1]]))
|
# 给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。
#
# 示例:
#
# 输入: "25525511135"
# 输出: ["255.255.11.135", "255.255.111.35"]
from typing import List
class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
def traceback(idx: int, segment: int, cur: str):
if segment == 4 and idx == n:
res.append(cur)
return
for i in range(3):
if idx + i < n and 0 <= int(s[idx:idx + i + 1]) <= 255:
if n - (idx + i + 1) <= (3 - segment) * 3:
if (i > 0 and s[idx] != '0') or i == 0:
traceback(idx + i + 1, segment + 1, cur + s[idx:idx + i + 1] + '.' if segment < 3 else cur + s[idx:idx + i + 1])
res, n = list(), len(s)
traceback(0, 0, '')
return res
s = Solution()
print(s.restoreIpAddresses('25525511135'))
|
# 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
# 你可以假设数组中无重复元素。
#
# 示例 1:
# 输入: [1,3,5,6], 5
# 输出: 2
#
# 示例 2:
# 输入: [1,3,5,6], 2
# 输出: 1
#
# 示例 3:
# 输入: [1,3,5,6], 7
# 输出: 4
#
# 示例 4:
# 输入: [1,3,5,6], 0
# 输出: 0
class Solution:
def searchInsert(self, nums, target):
if not nums:
return 0
lo = 0
hi = len(nums) - 1
while lo <= hi:
if target < nums[lo]:
return lo
if target > nums[hi]:
return hi + 1
mid = (lo + hi) // 2
number = nums[mid]
if number == target:
return mid
elif number < target:
lo = mid + 1
else:
hi = mid - 1
s = Solution()
print(s.searchInsert([1,3,5,6], 2)) |
# 给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。
#
# 在杨辉三角中,每个数是它左上方和右上方的数的和。
#
# 示例:
#
# 输入: 3
# 输出: [1,3,3,1]
from typing import List
class Solution:
def getRow(self, rowIndex: int) -> List[int]:
if rowIndex == 0:
return [1]
if rowIndex == 1:
return [1, 1]
pre, cur = [1, 1], []
curIdx = 2
while curIdx < rowIndex + 2:
for i in range(0, curIdx):
cur.append(1 if i == 0 or i == (curIdx - 1) else (pre[i-1] + pre[i]))
pre, cur = cur, []
curIdx += 1
return pre
s = Solution()
print(s.getRow(3))
|
def insert_sort(arr):
n = len(arr)
for i in range(1, n):
cur = arr[i]
j = i - 1
while j >= 0 and cur < arr[j]:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = cur
num = [5, 3, 2, 4, 1]
insert_sort(num)
print(num)
|
#!/bin/env python
# This script will validate and convert a custom formatted tab-delimited text file
# into an OBO file based on input parameters.
import sys, string
import argparse
import time
import collections
generatingTool = "BioGRID Tab2OBO 0.0.1a"
formatVersion = "1.2"
colCount = 8
# Process Command Line Input
argParser = argparse.ArgumentParser( description = 'Convert tab delimited text into an OBO file' )
argParser.add_argument( '--input', '-i', action='store', nargs=1, help='The input tab-delimited file', required=True )
argParser.add_argument( '--output', '-o', action='store', nargs=1, help='The output obo file', required=True )
argParser.add_argument( '--version', '-v', action='store', nargs=1, help='The data version you wish to assign to the new obo file. Example: 2.3.3', required=True )
argParser.add_argument( '--namespace', '-n', action='store', nargs=1, help='A default namespace for the overall file. Example: biogrid_ontologies', required=True )
argParser.add_argument( '--author', '-a', action='store', nargs=1, help='The author of the file. Example: BioGRID-Team', required=True )
inputArgs = argParser.parse_args( )
runDate = time.strftime( '%d:%m:%Y %H:%M' )
ontologyTerms = collections.OrderedDict( )
hasErrors = False
with open( inputArgs.input[0], 'r' ) as fp :
isFirst = True
lineCount = 0
for line in fp :
lineCount += 1
# Skip Header Line
if isFirst:
isFirst = False
continue
line = line.strip( )
# Skip blank Lines
if "" == line :
continue
splitLine = line.split( "\t" )
if len(splitLine) != colCount :
print "ERROR ON LINE " + str(lineCount) + ": Needs to be " + str(colCount) + " columns long! Found " + str(len(splitLine)) + " instead. Place 'none' in empty columns!"
hasErrors = True
continue
termID = splitLine[0].strip( )
termName = splitLine[1].strip( )
termDef = splitLine[2].strip( )
termDefSource = splitLine[3].strip( )
termRelationship = splitLine[4].strip( ).split( "|" )
termObsolete = splitLine[5].strip( )
termSynonym = splitLine[6].strip( ).split( "|" )
termSynonymType = splitLine[7].strip( ).split( "|" )
if len(termSynonym) != len(termSynonymType) :
print "ERROR ON LINE " + str(lineCount) + ": You must have the same number of synonym types as you do synonyms, both separated by '|'"
hasErrors = True
continue
if termObsolete.lower( ) == "true" :
termObsolete = True
else :
termObsolete = False
if termID.lower( ) in ontologyTerms :
print "ERROR ON LINE " + str(lineCount) + ": Duplicate term id used in already!"
hasErrors = True
continue
ontologyTerms[termID.lower( )] = { "ID" : termID, "NAME" : termName, "DEF" : termDef, "DEF_SOURCE" : termDefSource, "RELATIONSHIP" : termRelationship, "OBSOLETE" : termObsolete, "SYNONYMS" : termSynonym, "SYNONYM_TYPES" : termSynonymType }
if hasErrors :
print "Output File Not Generated Due to Errors Above"
else :
with open( inputArgs.output[0], 'w' ) as fp :
fp.write( "format-version: " + str(formatVersion) + "\n" )
fp.write( "data-version: " + str(inputArgs.version[0]) + "\n" )
fp.write( "date: " + runDate + "\n" )
fp.write( "saved-by: " + inputArgs.author[0] + "\n" )
fp.write( "auto-generated-by: " + generatingTool + "\n" )
fp.write( "default-namespace: " + inputArgs.namespace[0] + "\n" )
fp.write( "synonymtypedef: abbreviation \"Abbreviated Representation of the Term\" EXACT\n" )
for (termID, ontologyTerm) in ontologyTerms.items( ) :
fp.write( "\n" )
fp.write( "[Term]\n" )
fp.write( "id: " + ontologyTerm['ID'] + "\n" )
fp.write( "name: " + ontologyTerm['NAME'] + "\n" )
# Don't output the DEF term at all if no definition
# is found to display
if ontologyTerm["DEF"].lower( ) != "none" :
fp.write( "def: \"" + ontologyTerm['DEF'].replace( "\"", "" ) + "\"" )
if ontologyTerm["DEF_SOURCE"] != "none" :
fp.write( " [" + ontologyTerm['DEF_SOURCE'] + "]" )
else :
fp.write( " []" )
fp.write( "\n" )
# Print all the Synonyms if the term has any assigned to it
for synonym, synonymType in zip(ontologyTerm['SYNONYMS'], ontologyTerm['SYNONYM_TYPES']) :
if synonym.lower( ) != "none" :
fp.write( "synonym: \"" + synonym.replace( "\"", "" ) + "\" EXACT " + synonymType + " []\n" )
# Print all Relationships if the term it's related to
# can also be found in the ontology
for relationship in ontologyTerm['RELATIONSHIP'] :
if relationship.lower( ) != "root" and relationship.lower( ) != "none" :
if relationship.lower( ) not in ontologyTerms :
print "ERROR: " + termID + " has a relationship with " + relationship + " but this term is not in the ontology! This relationship was skipped!"
else :
relatedTerm = ontologyTerms[relationship.lower( )]
fp.write( "is_a: " + relationship + " ! " + relatedTerm['NAME'] + "\n" )
# Only output Obsolete if it's obsolete
# no is_obsolete implcitly implies it is not obsolete
if ontologyTerm['OBSOLETE'] :
fp.write( "is_obsolete: true\n" )
sys.exit(0) |
def gcd(a,b):
if a<b:
return gcd(b,a)
if b == 0:
return a
return gcd(a%b,b)
def gcd2(a,b):
if a<b:
a,b=b,a
while b!=1:
if b == 0:
return a
else:
a,b=b,a%b
return 1
x=1
y=2
j=0
for i in range(1000):
j+=len(str(x+y))-len(str(y))
x,y = y,(y*2+x)
print j |
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_excel("preprocessed.xlsx")
# Drugi nacin
corr = df.corr()
print(corr)
def plot_corr(df,size=15):
'''Function plots a graphical correlation matrix for each pair of columns in the dataframe.
Input:
df: pandas DataFrame
size: vertical and horizontal size of the plot'''
corr = df.corr()
fig, ax = plt.subplots(figsize=(size, size))
ax.matshow(corr)
plt.xticks(range(len(corr.columns)), corr.columns);
plt.yticks(range(len(corr.columns)), corr.columns);
plot_corr(df)
|
from socket import *
# TCP port we will listen for connections on
serverPort = 12000
# Create a listening socket
serverSocket = socket(AF_INET, SOCK_STREAM)
# Bind the socket to the local IP address ('') and port number
serverSocket.bind(('', serverPort))
# Start listening on the socket
serverSocket.listen(1)
print 'The server is ready to receive'
while 1:
# Accept a new connection.
# This creates a new socket that is 'connected' to the client
connectionSocket, addr = serverSocket.accept()
# Read data from client
sentence = connectionSocket.recv(1024)
# Convert to uppercase and send back to client
capitalizedSentence = sentence.upper()
connectionSocket.send(capitalizedSentence)
# Close socket
connectionSocket.close()
|
import mnist_reader
import numpy as np
import matplotlib.pyplot as plt
# train_images, train_labels ==> 60000, 60000
X_train, y_train = mnist_reader.load_mnist('train')
# test_images, test_labels ==> 10000, 10000
X_test, y_test = mnist_reader.load_mnist('t10k')
accuracy_test = [] # calculate the accuracy for text examples
##############################################
def predict(w_vector, j, str):
W = [] # record every vector(0 ~ 9) => F(x, y)
max = float("-inf") # record the max value of w * every vector
max_index = 0
for i in range(0, 10): # 10 classes
ww = [0] * len(X_train[0]) * 10 # 7840
if str == "train":
ww[i * 784: (i * 784 + 784)] = X_train[j]
else: # test
ww[i * 784: (i * 784 + 784)] = X_test[j]
W.append(np.array(ww)) # vector
d = np.dot(w_vector, np.array(ww))
if d > max:
max = d
max_index = i
return W, max_index
def a():
w_vector = np.array([0] * len(X_train[0]) * 10) # 7840
mistake = [0] * 50
for i in range(0, 50): # train 50 iteration
m_time = 0
for j in range(0, len(X_train)): # 60000
W, Yt = predict(w_vector, j, "train") # predict
# mistake
if Yt != y_train[j]:
m_time += 1
w_vector = np.add(w_vector, np.subtract(W[y_train[j]], W[Yt]))
mistake[i] = m_time
print(i + 1, "/", 50)
plt.plot([n for n in range(1, 51)], mistake) # learning curve
plt.title("Multi_Perceptron")
plt.xlabel("50 iteration")
plt.ylabel("mistake")
plt.show()
##############################################
def test(wt_vector): # testing examples
mistake = 0
for k in range(0, len(X_test)): # 10000
W, Yt = predict(wt_vector, k, "test") # predict
# mistake
if Yt != y_test[k]:
mistake += 1
accuracy_test.append((len(X_test) - mistake) / len(X_test))
def b():
w_vector = np.array([0] * len(X_train[0]) * 10) # 7840
accuracy = [0] * 20 # train 20 iteration
for i in range(0, 20):
m_time = 0
for j in range(0, len(X_train)): # 60000
W, Yt = predict(w_vector, j, "train") # predict
# mistake
if Yt != y_train[j]:
m_time += 1
w_vector = np.add(w_vector, np.subtract(W[y_train[j]], W[Yt]))
wt_vector = np.copy(w_vector)
test(wt_vector) # call text function
accuracy[i] = (len(X_train) - m_time) / len(X_train)
print(i + 1, "/", 20)
plt.plot([n for n in range(1, 21)], accuracy) # accuracy curve
plt.title("accuracy curve for train (Perceptron)")
plt.xlabel("20 iteration")
plt.ylabel("accuracy")
plt.show()
plt.plot([n for n in range(1, 21)], accuracy_test) # accuracy curve
plt.title("accuracy curve for test (Perceptron)")
plt.xlabel("20 iteration")
plt.ylabel("accuracy")
plt.show()
##############################################
if __name__ == "__main__":
a()
b()
# print("plain perceptron test accuracies :", accuracy_test.pop()) |
from random import *
class Cell(object):
""" Cell object with x,y position
"""
def __init__(self, x, y):
self.x = x
self.y = y
class Circuit:
def __init__(self, f):
[self.numCells, self.numNets, self.ny, self.nx] = [int(s) for s in f.readline().split()]
self.nets = []
self.costs = []
for _ in range(self.numNets):
line = f.readline().split()
if len([s for s in line]) is 0:
# empty line, read next
line = f.readline().split()
# source of net
net = [int(line[1])]
# sinks of net
net.append([int(s) for s in line[2:]])
self.nets.append(net)
self.costs.append(0)
f.close()
self.grid = []
for _ in range(self.ny):
row = []
for _ in range(self.nx):
row.append(' ')
self.grid.append(row)
self.cost = 0
self.cells = []
self.init_place()
def is_empty(self, x, y):
""" Checks the status of the cell position x,y
returns:
False if the cell is not empty or x,y is not in the grid range
True otherwise
"""
if x in range(self.nx) and y in range(self.ny):
if self.grid[y][x] == ' ':
return True
return False
def put_cell(self, x, y, num):
""" Places cell #num on the array at empty position x,y
sets:
- self.grid at x,y, and updates image with initial placement
returns:
False if the cell fails not_empty
True otherwise
:param x: x value of cell
:param y: y value of cell
"""
if self.is_empty(x,y):
self.grid[y][x] = num
return True
return False
def init_place(self):
""" Places cells on the array initially
assumes:
- nothing has been placed before
sets:
- self.grid, and updates image with initial placement
- self.cost
asserts:
- if failure to place cell in grid (put_cell returns False)
- if failure to calculate cost (calc_cost returns False)
"""
for i in range(self.numCells):
x = randint(0,self.nx)
y = randint(0,self.ny)
while not self.is_empty(x,y):
x = randint(0, self.nx)
y = randint(0, self.ny)
assert self.put_cell(x, y, i) is True
self.cells.append(Cell(x,y))
assert self.calc_cost() is True
def switch(self, x1, y1, x2, y2):
""" Switches cells specified by x1,y1 and x2,y2
:param x1: x coordinate of cell1
:param y1: y coordinate of cell1
:param x2: x coordinate of cell2
:param y2: y coordinate of cell2
assumes:
- at least one cell is not empty
sets:
- self.grid, and updates image with new placement
- self.cells, and updates new position for moved cell
- self.cost
asserts:
- if failure to switch cells (both cells are empty)
"""
# both positions should not be empty
assert (self.is_empty(x1, y1) is not True) or (self.is_empty(x2, y2) is not True)
# x1,y1 is empty
if self.is_empty(x1, y1):
self.grid[y1][x1] = self.grid[y2][x2]
self.cells[self.grid[y2][x2]].x = x1
self.cells[self.grid[y2][x2]].y = y1
self.grid[y2][x2] = ' '
self.update_cost(self.grid[y1][x1])
# x2,y2 is empty
elif self.is_empty(x2, y2):
self.grid[y2][x2] = self.grid[y1][x1]
self.cells[self.grid[y1][x1]].x = x2
self.cells[self.grid[y1][x1]].y = y2
self.grid[y1][x1] = ' '
self.update_cost(self.grid[y2][x2])
else:
n = self.grid[y2][x2]
self.grid[y2][x2] = self.grid[y1][x1]
self.cells[self.grid[y1][x1]].x = x2
self.cells[self.grid[y1][x1]].y = y2
self.grid[y1][x1] = n
self.cells[n].x = x1
self.cells[n].y = y1
self.update_cost(self.grid[y1][x1])
self.update_cost(self.grid[y2][x2])
def compare_switch_cost(self, x1, y1, x2, y2):
""" Compares the cost functions of the switching of cells at x1,y1 and x2,y2
:param x1: x coordinate of cell1
:param y1: y coordinate of cell1
:param x2: x coordinate of cell2
:param y2: y coordinate of cell2
:return: the difference in cost function
"""
cost = self.cost
self.switch(x1,y1,x2,y2)
deltaC = self.cost - cost
return deltaC
def update_cost(self, id):
""" Calculates the updated cost given a moved net with index id, to prevent recalculating full cost
:param: id: the if of the source/sink cell that was moved
assumes:
- valid net list in self.nets
sets:
- self.cost
:return: True once complete
"""
cost = 0
for i, [source, sinks] in enumerate(self.nets):
if id == source:
self.costs[i] = self.calc_half_perimeter(source, sinks)
cost += self.costs[i]
elif id in sinks:
self.costs[i] = self.calc_half_perimeter(source, sinks)
cost += self.costs[i]
else:
cost += self.costs[i]
self.cost = cost
return True
def calc_cost(self):
""" Calculates the initial cost for all nets
assumes:
- valid net list in self.nets
sets:
- self.cost
:return: True once complete
"""
cost = 0
for i,[source, sinks] in enumerate(self.nets):
self.costs[i] = self.calc_half_perimeter(source, sinks)
cost += self.costs[i]
self.cost = cost
return True
def calc_half_perimeter(self, source, sinks):
""" Calculates the half perimeter smallest bounding box cost of a net
assumes:
- valid cell positions in source, sinks
asserts:
- if failure to calculate cost (any cell x,y not in grid range)
:param source: index of the source cell
:param sinks: indices of the sink cells
:return: half-perimeter cost of the net
"""
deltax = 0
deltay = 0
assert self.cells[source].x in range(self.nx) and self.cells[source].y in range(self.ny)
for sink in sinks:
assert self.cells[sink].x in range(self.nx) and self.cells[sink].y in range(self.ny)
dx = abs(self.cells[source].x - self.cells[sink].x)
if dx > deltax:
deltax = dx
dy = abs(self.cells[source].y - self.cells[sink].y)
if dy > deltay:
deltay = dy
return deltax + deltay
|
# num=13
# print(type(num))
# n = int(input())
# sum = 2
# for i in range(n+1):
# sum+=i
# print(sum)
# sum = 0
# i =0
# while(i<=5):
# sum+=i
# i+=1
# print(sum)
# sum = 0
# for i in range(1,6):
# cube = i**3
# sum+= cube
# print(sum)
# sum = 0
# i = 0
# while i<=5:
# sum +=i
# i+= 1
# print(sum)
# for i in range(2,56):
# if (i==43):
# break
# print(i)
# i = 0
# while i<=26:
# if(i==17):
# break
# i+= 1
# print(i)
# ls = ["ashu",25,True,20.9]
# print(ls)
# print(type(ls))
# ls = [1,3,5,37,85,847,0,73,9]
# for i in ls:
# print(ls) |
# coding: utf-8
from inheritance import Person
obj2 = Person("Joana", 0)
obj1 = Person("João", 1)
print()
print("{name}:{sex}".format(name=obj1.name, sex=obj1.sex))
print("{name}:{sex}".format(name=obj2.name, sex=obj2.sex))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright © 2017 Manoel Vilela
#
# @project: Prática 9 - Python
# @author: Manoel Vilela
# @email: manoel_vilela@engineer.com
#
class Empregados(object):
def __init__(self, nome, sobrenome, salario):
self.nome = nome
self.sobrenome = sobrenome
self.salario = salario
@property
def nome(self):
return self._nome
@nome.setter
def nome(self, nome):
self._nome = nome
@property
def sobrenome(self):
return self._sobrenome
@sobrenome.setter
def sobrenome(self, sobrenome):
self._sobrenome = sobrenome
@property
def salario(self):
return self._salario
@salario.setter
def salario(self, salario):
self._salario = salario if salario >= 0 else 100
def aumentar_salario(self, porcentagem):
self.salario += self.salario*porcentagem
def descreva(self):
print('== Empregado')
print('nome: {}'.format(self.nome))
print('sobrenome: {}'.format(self.sobrenome))
print('salario: R$ {:,.2f}'.format(self.salario))
|
#EX-5-lumbbharam
#Write a Python program to access dictionary key’s element by index.
num = {'stats': 80, 'math': 90, 'algorithm': 86}
print(list(num)[0])
|
#Cifrado Caesar, sistema de cifrado creado por Caesar para enviar sus
# mensajes mas importantes a sus generales sin que espias descubrieran
# la informacion que contenian sus cartas.
def cifrado_caesar(texto):
abc="abcdefghijklmnñopqrstuvwxyz"
cif = ""
for c in texto:
if c in abc:
if (abc.index(c) + 3 > len(abc)):
cif += abc[((abc.index(c) + 3) - len(abc))]
else: cif += abc[(abc.index(c) + 3)]
else:
cif += c
return cif
# print(cifrado_caesar("la soledad ha sido una verdadera amiga, nunca me ha dejado, aun cuando yo trato de alejarme de ella, siempre esta conmigo"))
# print(cifrado_caesar("stay with me, no, you don't need to run"))
# print(cifrado_caesar("somebody that i used to know"))
# print(cifrado_caesar("do they know I was grown with you?"))
def descifrar(texto1):
cof = "abcdefghijklmnñopqrstuvwxyz"
txt = ""
for c in texto1:
if c in cof:
if (cof.index(c) - 3 < 0):
txt += cof[((cof.index(c) - 3) + len(cof))]
else: txt += cof[(cof.index(c) - 3)]
else:
txt += c
return txt
hola = cifrado_caesar("do they know I was grown with you?")
print(hola)
print(descifrar(hola))
# print(descifrar("\n\nñd vrñhgdg kd vlgr xpd yhugdghud doljd, pxpfd oh kd ghmdgr, dxp fxdpgr br wudwr gh dñhmduoh gh hññd, vlhosuh hvwd frpoljr"))
# print(descifrar("vrohergb wkdw l xvhg wr nprz"))
# print(descifrar("gr wkhb nprz I zdv jurzp zlwk brx?")) |
# rpy2 library used to call r function
# more detailed documentation can be found at https://rpy2.github.io/doc/latest/html/robjects_robjects.html
import rpy2.robjects as ro
# used to exit program when user enters exit
import sys
def load_r_module(path_to_module):
"""[summary]
Args:
path_to_module (str): path to desired R module
Returns:
r: r process for specified module
"""
# entrypoint to R process
r=ro.r
# load file
r.source(path_to_module)
return r
def call_r_increment(r, num_1, num_2):
"""call the function in the r module to increment the two specified variables
Args:
r (r): r process to call function
num_1 (float): first number to increment
num_2 (float): second number to increment
Returns:
tuple: incremented numbers with form (num_1 + 1, num_2 + 1)
"""
# call r function
incremented_vector = r.increment_numbers(num_1,num_2)
return tuple(incremented_vector)
def validate_data(num):
"""if the string is a number, cast it, if not, reprompt the user
Args:
num (str): user inputted unber
Returns:
float: float representation of the number
"""
# quit if the user passes in "Exit"
if num == "exit":
sys.exit()
try:
# return the float representation of the string
return float(num)
# float cast throws a ValueError if unsuccessful
except ValueError:
# reprompt the user to enter a number
print('Malformed Input. Please enter a number')
num = input('Please Enter the first number. (Enter "exit" to quit): ')
# recursively call validate_data until the user either exits or provides valid input
return validate_data(num)
if __name__ == "__main__":
# load the r module
r = load_r_module('module.R')
# repeat until the user exits
while(True):
# get first number
num_1 = input('Enter the first number. (Enter "exit" to quit): ')
num_1 = validate_data(num_1)
# get second number
num_2 = input('Enter the second number. (Enter "exit" to quit): ')
num_2 = validate_data(num_2)
# call r function to increment numbers
incremented_numbers = call_r_increment(r,num_1, num_2)
print('Incremented numbers are %f, %f' % incremented_numbers)
|
from display import *
from matrix import *
def draw_lines( matrix, screen, color ):
q = 0
while q < len(matrix) -1:
draw_line(matrix[q][0], matrix[q][1], matrix[q+1][0], matrix[q+1][1], screen, color)
q+=1
def add_edge( matrix, x0, y0, z0, x1, y1, z1 ):
matrix.append([x0, y0, z0])
matrix.append([x1, y1, z1])
def add_point( matrix, x, y, z=0 ):
matrix.append([x, y, z])
def draw_line( x0, y0, x1, y1, screen, color ):
if x0 == x1 :
y = y0
if y < y1:
while y<y1:
plot(screen, color, x0, y)
y +=1
else:
while y > y1:
plot(screen, color, x0, y)
y -=1
elif y0==y1:
x=x0
if x < x1:
while x<x1:
plot(screen, color, x,y0)
x+=1
else:
while x>x1:
plot(screen, color, x,y0)
x-=1
else:
if (y0<y1 and x0<x1 and abs(x1-x0) >= abs(y1 - y0) ):
drawOct1(x0, y0, x1, y1, screen, color)
elif (y0<y1 and x0<x1 and abs(x1-x0) < abs(y1 - y0) ):
drawOct2(x0, y0, x1, y1, screen, color)
elif (y0>y1 and x0<x1 and abs(x1-x0) >= abs(y1 - y0) ):
drawOct8(x0, y0, x1, y1, screen, color)
elif (y0>y1 and x0<x1 and abs(x1-x0) < abs(y1 - y0) ):
drawOct7(x0, y0, x1, y1, screen, color)
elif (y0>y1 and x0>x1 and abs(x1-x0) < abs(y1 - y0) ): #
drawOct2(x1, y1, x0, y0, screen, color)
elif (y0>y1 and x0>x1 and abs(x1-x0) >= abs(y1 - y0) ): #
drawOct1(x1, y1, x0, y0, screen, color)
elif (y0<y1 and x0>x1 and abs(x1-x0) >= abs(y1 - y0) ): #
drawOct8(x1, y1, x0, y0, screen, color)
else: #
drawOct7(x1, y1, x0, y0, screen, color)
def drawOct1(x0, y0, x1, y1, screen, color):
x = x0
y = y0
A = 2 * (y1 - y0)
B = -2 * (x1 - x0)
d = 2*A + B
while x<x1:
plot(screen, color, x, y)
if d>0:
y+=1
d += 2 * B
x +=1
d += 2 * A
def drawOct2(x0, y0, x1, y1, screen, color):
x = x0
y = y0
A = 2 * (y1 - y0)
B = -2 * (x1 - x0)
d = A + 2*B
while y<y1:
plot(screen, color, x,y)
if d<0:
x+=1
d += 2*A
y+=1
d += 2*B
def drawOct7(x0, y0, x1, y1, screen, color):
x = x0
y = y0
A = 2 * (y1 - y0)
B = -2 * (x1 - x0)
d = A-2*B
while y>=y1:
plot(screen, color, x, y)
if d>0:
x +=1
d += 2*A
y -=1
d -= 2*B
def drawOct8(x0, y0, x1, y1, screen, color):
x = x0
y = y0
A = 2 * (y1 - y0)
B = -2 * (x1 - x0)
d = 2*A-B
while y>=y1:
plot(screen, color, x, y)
if d<0:
y -=1
d -= 2*B
x +=1
d += 2*A
|
import sys
#迭代器操作
def fun1():
list1=['1','a','b','c']
it1=iter(list1)
# print(next(it1))
# print(next(it1))
# 正常循环
# for i in it1:
# print(i,end="|")
# while循环方式
# while True:
# try:
# print(next(it1))
# except StopIteration:
# sys.exit()
if __name__ == '__main__':
# print("aaa")
fun1() |
# 继承的方式,实现多线程
import threading
import time
exitFlag = 0
class myThread(threading.Thread):
def __init__(self, threadIdParam, nameParam, counterParam):
threading.Thread.__init__(self)
self.name = nameParam
self.threadID = threadIdParam
self.counter = counterParam
def print_test(self, delay, counter):
while counter:
if exitFlag:
self.exit()
time.sleep(int(delay))
print("%s: %s" % (self, time.ctime(time.time())))
counter -= 1
def run(self):
print('开始线程:' + self.name)
self.print_test(self.counter, 5)
print('结束线程' + self.name)
if __name__ == '__main__':
# 创建新线程
thread1 = myThread(1, "Thread-1", 2)
# print(thread1.name)
# print(thread1.counter)
# print(thread1.threadID)
thread2 = myThread(2, "Thread-2", 2)
# 开启新线程
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print("退出主线程")
|
from collections import deque
# 列表的操作
list1=[1,2,3,4]
list1.append(7)
list1.append(9)
print(list1)
# 列表当做堆栈使用
# print(list1)
# list1.pop()
# print(list1)
# list1.pop()
# print(list1)
# 列表当做队列使用
queue=deque(list1)
queue.popleft()
print(queue)
queue.popleft()
print(queue)
|
''' 7. Write program to convert prefix/net mask to IP
eg: input:16 output: 255.255.0.0 '''
def convert(n):
a = n//8
b = n%8
l =[]
for i in range(a):
l.append(str(255))
d,s=7,0
for i in range(b):
s+= 2**d
d-=1
l.append(str(s))
while len(l) < 4:
l.append(str(0))
return '.'.join(l)
inp = int(input("enter the number"))
if inp > 32 or inp < 0:
print("invalid input")
print(convert(inp))
|
import math
# Set of Joint Angles
# User Input
print("---Creating Player Profile---")
player_name = input('Name: ')
dominant_hand = input("Are you left (L) or right (R) handed? ")
if dominant_hand in ('R', 'r', 'right', 'Right'):
shooting_arm = 'right'
else:
shooting_arm = 'left'
print('What is your height?')
height_feet = int(float(input("Feet: ")))
total_height = int(12 * height_feet)
height_inches = int(float(input("Inches: ")))
total_height = int(total_height + height_inches)
print(f"{player_name} is {height_feet} feet {height_inches} inches tall")
print(f"Height in Inches: {total_height}")
print("\nPlease enter the following measurements in inches.")
upper_arm = float(input(f"Length of {shooting_arm} upper arm: "))
forearm = float(input(f"Length of {shooting_arm} forearm: "))
hand = float(input(f"Length of {shooting_arm} hand: "))
print(f"\n{player_name} has a {shooting_arm} upper shooting arm of {upper_arm} inches, forearm of {forearm} inches, "
f"and hand length of {hand} inches.\n")
# Recommended Shooting Angle
if total_height < 60:
recommended_angle = "56 (and up)"
elif 60 <= total_height <= 64:
recommended_angle = "53 - 56"
elif 64 < total_height <= 68:
recommended_angle = "52 - 55"
elif 68 < total_height <= 72:
recommended_angle = "51 - 54"
elif 72 < total_height <= 76:
recommended_angle = "50 - 53"
elif 76 < total_height <= 80:
recommended_angle = "49 - 52"
elif 80 < total_height <= 84:
recommended_angle = "48 - 51"
else:
recommended_angle = "47 (and lower)"
print(f"For {player_name}, who is {int(height_feet)}'{int(height_inches)}\", a recommended range of 3PT line release "
f"angles is {recommended_angle} degrees\n")
# Customize Settings
shooting_angle = float(input("Desired Shooting Angle: "))
print("Plotting your optimal shooting form release...")
# record the user data
with open('user_data.txt', 'w') as filehandle:
filehandle.write('%s\n' % shooting_angle)
filehandle.write('%s\n' % player_name)
filehandle.write('%s' % dominant_hand)
# upper_arm = 9
# forearm = 8
# hand = 7
# Examples:
# 11, 9.5, 7.25
# Joint Angles Optimization
# Lists for X Coordinates
x_elbow = []
x_wrist = []
x_fingertip = []
# Lists for Y Coordinates
y_elbow = []
y_wrist = []
y_fingertip = []
# Release & Joint Angles
# shooting_angle = 48
# shoulder_angle = 20
# elbow_angle = 20
# wrist_angle = 20
# Angle Ranges
# Literature Range for Shoulder:
shoulder_min = 15
shoulder_max = 50
# Literature Range for Elbow:
elbow_min = shoulder_min + 1
elbow_max = 60
# Literature Range for Wrist:
wrist_min = 40
wrist_max = 89
shoulder_angle = shoulder_min
# Margin Sensitivity
margin_error = 0.01
# Change in angles
wrist_increment = 1
elbow_increment = 1
shoulder_increment = 1
while shoulder_angle <= shoulder_max:
x_elbow_coord = upper_arm * math.cos(math.radians(shoulder_angle))
y_elbow_coord = upper_arm * math.sin(math.radians(shoulder_angle))
elbow_angle = elbow_min
# print("changing angle")
# loop for elbow_angle (0 - 85)
while elbow_angle <= elbow_max:
x_wrist_coord = x_elbow_coord + forearm * math.cos(math.radians(elbow_angle))
y_wrist_coord = y_elbow_coord + forearm * math.sin(math.radians(elbow_angle))
wrist_angle = wrist_min
# loop for wrist_angle (0 - 130)
while wrist_angle <= wrist_max:
x_fingertip_coord = x_wrist_coord + hand * math.cos(math.radians(wrist_angle))
y_fingertip_coord = y_wrist_coord + hand * math.sin(math.radians(wrist_angle))
margin = math.degrees(math.atan(y_fingertip_coord/x_fingertip_coord))
if (margin - margin_error <= shooting_angle) and (shooting_angle <= margin + margin_error):
# Append X Coordinates
x_elbow.append(x_elbow_coord)
x_wrist.append(x_wrist_coord)
x_fingertip.append(x_fingertip_coord)
# Append Y Coordinates
y_elbow.append(y_elbow_coord)
y_wrist.append(y_wrist_coord)
y_fingertip.append(y_fingertip_coord)
# print("let's get this bread")
# print(x_wrist_coord)
# print(math.cos(math.radians(wrist_angle)))
# print(x_fingertip_coord)
# print(margin)
# Figure out how to correctly iterate each angle joint by 0.5 degrees
# Check if the shooting angle works for this set of joint angles
wrist_angle += wrist_increment
elbow_angle += elbow_increment
shoulder_angle += shoulder_increment
# compute average of x and y coordinates of fingertip
x_sum = 0
for i in x_fingertip:
x_sum += i
x_release = x_sum / len(x_fingertip)
y_sum = 0
for i in y_fingertip:
y_sum += i
y_release = y_sum / len(y_fingertip)
print(f'The x release coord is: {x_release} and the y release coord is {y_release}')
with open('basketball_data.txt', 'w') as filehandle0:
index = 0
while index < len(x_elbow):
filehandle0.write('%s ' % x_elbow[index])
filehandle0.write('%s ' % y_elbow[index])
filehandle0.write('%s ' % x_wrist[index])
filehandle0.write('%s ' % y_wrist[index])
filehandle0.write('%s ' % x_fingertip[index])
filehandle0.write('%s' % y_fingertip[index])
filehandle0.write('\n')
index = index + 1
with open('y_elbow.txt', 'w') as filehandle1:
for listitem in y_elbow:
filehandle1.write('%s\n' % listitem)
with open('x_wrist.txt', 'w') as filehandle2:
for listitem in x_wrist:
filehandle2.write('%s\n' % listitem)
with open('y_wrist.txt', 'w') as filehandle3:
for listitem in y_wrist:
filehandle3.write('%s\n' % listitem)
with open('x_fingertip.txt', 'w') as filehandle4:
for listitem in x_fingertip:
filehandle4.write('%s\n' % listitem)
with open('y_fingertip.txt', 'w') as filehandle5:
for listitem in y_fingertip:
filehandle5.write('%s\n' % listitem)
# //Ball Release Properties
# Optimal Backspin is said to be 3Hz or about 3 full rotations during ball trajectory
# User Input
print("---Calculating Ball Radius and Distance of 3-Point Shot---")
print('Basketball Sizes: Size 7 (29.5"), Size 6 (28.5"), Size 5 (27.5"), Size 4 (26.5")')
ball_type = input("Please input basketball size---Size 7 (1), Size 6 (2), Size 5 (3), Size (4): ")
if ball_type == 1:
ball_radius = 0.119 # roughly 4.695 inches
elif ball_type == 2:
ball_radius = 0.1152 # roughly 4.536 inches
elif ball_type == 3:
ball_radius = 0.1111 # roughly 4.377 inches
else:
ball_radius = 0.1071 # roughly 4.218 inches
three_type = input('Corner 3? (Y/N): ')
if three_type in ('Y', 'y'):
location = 'corner'
else:
location = 'above-the-break'
competition_level = input("Please enter competition level---Professional (P), Collegiate (C), High School "
"or Lower (H): ")
if competition_level in ('P', 'p', 'Professional', 'professional'):
classify = input("Please input the association---NBA (N), FIBA (F), or WNBA (W): ")
if classify in ('N', 'n', 'NBA', 'nba'):
classify = 'NBA'
if three_type in ('Y', 'y', 'Yes', 'yes'):
shot_distance = 6.7056
else:
shot_distance = 7.239
else:
if three_type in ('Y', 'y', 'Yes', 'yes'):
shot_distance = 6.60
else:
shot_distance = 6.75
if classify in ('F', 'f', 'FIBA', 'fiba'):
classify = 'FIBA'
else:
classify = 'WNBA'
elif competition_level in ('C', 'c', 'Collegiate', 'collegiate'):
division = input("Please input the division---I (1), II (2), III (3): ")
classify = input("Please input the program---Men's (M), Women's (W): ")
if classify in ('M', 'm'):
classify = "NCAA Men's"
if division in ('1', 'I', 'i'):
if three_type in ('Y', 'y', 'Yes', 'yes'):
shot_distance = 6.60
else:
shot_distance = 6.75
division = ' Division I'
classify = classify + division
else:
shot_distance = 6.3246
if division in ('2', 'II', 'ii'):
division = ' Division II'
classify = classify + division
else:
division = ' Division III'
classify = classify + division
else:
classify = "NCAA Women's"
shot_distance = 6.3246
if division in ('1', 'I', 'i'):
division = ' Division I'
classify = classify + division
elif division in ('2', 'II', 'ii'):
division = ' Division II'
classify = classify + division
else:
division = ' Division III'
classify = classify + division
else:
shot_distance = 6.0198
classify = 'High School or lower'
#
# # //Ball Properties
#
# # Backspin
backspin_rad = 2 * math.pi * (shot_distance + 2)/3
backspin_hz = backspin_rad * (1/(math.pi * 2))
shot_info = ("\n{a}'s {b} 3-point shot is {c:2.2f} feet from the hoop. An ideal backspin for this shot is {d:1.2} "
"Hz.".format(a=classify, b=location, c=3.28084 * shot_distance, d=backspin_hz))
print(shot_info)
# Calculate the d_hypotenuse
d_hypotenuse = math.sqrt(x_release**2 + y_release**2)
d_hypotenuse = (d_hypotenuse/12)/3.2808
print(f'The hypotenuse is: {d_hypotenuse}')
# Calculating ltb and htb
jump_height = 0.1524 # roughly 6 inches
# Convert Height to Height in m
total_height = (total_height / 12) / 3.2808
shoulder_height = (21/25) * total_height
print(f'Shoulder height: {shoulder_height}')
htb = 3.048 - (shoulder_height + jump_height + d_hypotenuse*math.sin(math.radians(shooting_angle)) +
ball_radius*math.sin(math.radians(shooting_angle)))
ltb = shot_distance - (d_hypotenuse*math.cos(math.radians(shooting_angle)) +
ball_radius*math.cos(math.radians(shooting_angle)))
print(f"The length to basket is l: {ltb} and the height to basket is h: {htb}")
gravity = 9.81
holder0 = math.tan(math.radians(shooting_angle)) - htb/ltb
holder1 = ((math.cos(math.radians(shooting_angle)))**2)*holder0
ball_velocity = math.sqrt((gravity*ltb)/(2*holder1))
print('\nThe ball velocity is: {a:2.2f} m/s'.format(a=ball_velocity))
# //Fingertip Components
# Acceleration
fingertip_acc_hor = ball_radius*(backspin_hz**2)*math.cos(math.radians(shooting_angle))
fingertip_acc_ver = ball_radius*(backspin_hz**2)
fingertip_acc = math.sqrt((fingertip_acc_hor**2) + (fingertip_acc_ver**2))
print('The x-direction fingertip acceleration is {a:2.2f} m/s^2\nThe y-direction fingertip acceleration is'
' {b:2.2f} m/s^2\nThe overall fingertip acceleration is {c:2.2f} m/s^2.\n'.format(a=fingertip_acc_hor,
b=fingertip_acc_ver,
c=fingertip_acc))
# Velocity
fingertip_vel_hor = ball_velocity*math.cos(math.radians(shooting_angle)) + \
ball_radius*backspin_hz*math.sin(math.radians(shooting_angle))
fingertip_vel_ver = ball_velocity*math.sin(math.radians(shooting_angle)) - \
ball_radius*math.cos(math.radians(shooting_angle))
fingertip_vel = math.sqrt((fingertip_vel_hor**2) + (fingertip_vel_ver**2))
angle = math.degrees(math.atan(fingertip_vel_ver/fingertip_vel_hor))
print('\nThe x-direction fingertip velocity is {a:2.2f} m/s\nThe y-direction fingertip velocity is '
'{b:2.2f} m/s\nThe overall fingertip velocity is {c:2.2f} m/s.\n'.format(a=fingertip_vel_hor, b=fingertip_vel_ver,
c=fingertip_vel)) |
# -*- coding: utf-8 -*-
import sys
import itertools
import collections
def list2dict(l):
"""
Convert list to ordered dictionary, where adjacent elements become key and value
Example: [1, 2, 3, 4] --> {1: 2, 2: 4}
"""
return collections.OrderedDict(itertools.izip_longest(*[iter(l)] * 2))
def list2tuplelist(l):
"""
Convert list to list of tuples, where adjacent elements become a pair
Example: [1, 2, 3, 4] --> [(1, 2), (3, 4)]
"""
return list(itertools.izip_longest(*[iter(l)] * 2))
def tuplelist2list(l):
"""
Reverse list2tuplelist()
"""
r = []
for t in l:
r.append(t[0])
r.append(t[1])
return r
def getduplicate(l):
"""
Locate the duplicate element(s) of a list, and return them as a list
"""
counter = collections.Counter(l)
t = filter(lambda x: x[1] > 1, counter.most_common())
return [x[0] for x in t]
class output(object):
"""
ANSI console colored output:
* error (red)
* warning (yellow)
* debug (green)
"""
RED = 1
GREEN = 2
YELLOW = 3
ERROR = 4
DEBUG = 5
WARNING = 6
@staticmethod
def __out(type, msg):
if type == output.ERROR:
sys.stderr.write("\033[%dm [%s] %s\033[m\n" % (30 + output.RED, "Error", msg))
if type == output.DEBUG:
sys.stdout.write("\033[%dm [%s] %s\033[m\n" % (30 + output.GREEN, "Debug", msg))
if type == output.WARNING:
sys.stdout.write("\033[%dm [%s] %s\033[m\n" % (30 + output.YELLOW, "Warning", msg))
@staticmethod
def error(msg):
output.__out(output.ERROR, msg)
@staticmethod
def debug(msg):
output.__out(output.DEBUG, msg)
@staticmethod
def warning(msg):
output.__out(output.WARNING, msg)
def check_version():
version = sys.version_info
if version[0] == 2:
if version[1] < 7:
output.error("Python 2.%d installed. This app requires Python 2.7."%(version[1]))
sys.exit(1)
if version[0] == 3:
output.error("Python 3.%d installed. This app requires Python 2.7."%(version[1]))
sys.exit(1)
if __name__ == '__main__':
utilities.output.warning("Please run main.py script from project's directory.") |
"""
4. Написать функцию которая принимает на вход число от 1 до 100. Если число
равно 13, функция поднимает исключительную ситуации ValueError иначе
возвращает введенное число, возведенное в квадрат. Далее написать основной
код программы. Пользователь вводит число. Введенное число передаем параметром
в написанную функцию и печатаем результат, который вернула функция.
Обработать возможность возникновения исключительной ситуации, которая
поднимается внутри функции.
"""
def check_unlucky_number(user_number: int):
try:
if user_number == 13:
raise ValueError('UnluckyNumber')
elif user_number in range(0, 101):
result_number = user_number ** 2
else:
print(
'Your number is incorrect, enter something in range [0, 100]')
result_number = None
except ValueError:
print('Your number is unlucky, try again')
result_number = None
return result_number
modified_number = check_unlucky_number(100)
print(modified_number)
|
import os
import shutil
import datetime
import random
def create_file(name, text=None):
with open(name, 'w', encoding='utf-8') as f:
if text:
f.write(text)
def create_folder(name):
try:
os.mkdir(name)
except FileExistsError:
print('already exist')
def get_list(folders_only=False):
result = os.listdir()
if folders_only:
result = [f for f in result if os.path.isdir(f)]
print(result)
def delete_file(name):
if os.path.isdir(name):
os.rmdir(name)
else:
os.remove(name)
def copy_file(name, new_name):
if os.path.isdir(name):
try:
shutil.copytree(name, new_name)
except FileExistsError:
print('Такая папка уже есть')
else:
shutil.copy(name, new_name)
def save_info(message):
current_time = datetime.datetime.now()
result = f'{current_time} - {message}'
with open('log.txt', 'a', encoding='utf-8') as f:
f.write(result + '\n')
def chDir(name):
os.chdir(name)
print(os.getcwd())
def game():
number = int(input('Please make a number (1-100): '))
clue = None
x = 1
y = 100
is_winner = False
while not is_winner:
computer_number = random.randint(x, y)
print(f'Computer have chosen the number {computer_number} ')
if computer_number == number:
is_winner = True
break
else:
clue = input(
'Please give me a clue is my number more or less than yours?: ')
if clue == "less":
x = computer_number
elif clue == "more":
y = computer_number
print('Computer wins!')
|
"""
3. Напишите функцию которая принимает на вход список. Функция создает из этого
списка новый список из квадратных корней чисел (если число положительное) и
самих чисел (если число отрицательное) и возвращает результат (желательно
применить генератор и тернарный оператор при необходимости). В результате
работы функции исходный список не должен измениться. Например:
old_list = [1, -3, 4] result = [1, -3, 2]
Примечание: Список с целыми числами создайте вручную в начале файла.
Не забудьте включить туда отрицательные числа.
10-20 чисел в списке вполне достаточно.
"""
from copy import deepcopy
def list_handling(user_list: list):
func_list = deepcopy(user_list)
result_list = [i**2 if i > 0 else i for i in func_list]
return result_list
custom_list = [i for i in range(-10, 10)]
print('source list:', custom_list)
modified_list = list_handling(custom_list)
print('modified list:', modified_list)
|
import unittest
from models.player import *
from models.game import Game
class TestPlayer(unittest.TestCase):
def setUp(self):
self.player1 = Player("Erin", "rock")
self.player2 = Player("Helen", "paper")
def test_player_has_name(self):
self.assertEqual("Erin", self.player1.name)
def test_player_has_choice(self):
self.assertEqual("rock", self.player1.choice)
# def test_no_random_choice(self):
|
"""Shaped bubble field implementation -- allows for creating a field
and placing (rectangular) bubbles in it and expanding them.
currently used for creating clusters of rooms
"""
import random
from rl.util import geometry
class BubbleField:
target_areas = [4, 6, 6, 10, 10, 12, 20, 20, 30, 30, 40]
target_ratios = [1/2, 2/3, 2/3, 3/4, 3/4, 1]
def __init__(self, region, blocked, num_bubbles):
self.num_bubbles = num_bubbles
self.region = region
self.blocked = blocked
self.bubbles = []
self.create_bubbles()
def expand_bubbles(self):
continue_expanding = True
while continue_expanding:
continue_expanding = False
for bubble in self.bubbles:
something_expanded = bubble.expand()
continue_expanding = continue_expanding or something_expanded
def create_bubbles(self):
ul_x, ul_y = self.region.ul_pos
center = (int(ul_x + self.region.shape.width/2), int(ul_y + self.region.shape.height/2))
cx, cy = center
points = set()
for x in range(cx-2, cx+3):
for y in range(cy-2, cy+3):
points.add((x, y))
valid = False
bubbles = []
while not valid:
seeds = random.sample(points, self.num_bubbles)
borders = set()
for seed in seeds:
borders = borders.union(set(geometry.neighbors(seed)))
ok = True
for seed in seeds:
if seed in borders:
ok = False
if ok:
valid = True
for seed in seeds:
bubbles.append(
Bubble(seed, self, random.choice(self.target_areas),
random.choice(self.target_ratios))
)
self.bubbles = bubbles
def can_push(self, origin_bubble, direction):
bubbles_affected = set()
for point in origin_bubble.rect.edge(direction):
# blocked points cannot be pushed
if point in self.blocked:
return False
for bubble in self.bubbles:
if bubble is origin_bubble:
continue
if point in bubble.rect.outline:
bubbles_affected.add(bubble)
push_ok = True
for bubble in bubbles_affected:
push_ok = push_ok and bubble.can_be_pushed(direction)
return push_ok
def resolve_push(self, origin_bubble, direction):
bubbles_affected = set()
for point in origin_bubble.rect.edge(direction):
# blocked points cannot be pushed
if point in self.blocked:
return False
for bubble in self.bubbles:
if bubble is origin_bubble:
continue
if point in bubble.rect.outline:
bubbles_affected.add(bubble)
push_ok = True
for bubble in bubbles_affected:
push_ok = push_ok and bubble.move(direction)
return push_ok
def bubble_has_free_side(self, bubble, direction):
all_boundaries = set()
all_boundaries = all_boundaries.union(self.blocked)
for bubble_ in self.bubbles:
if bubble_ is bubble:
continue
all_boundaries = all_boundaries.union(set(bubble_.rect.outline))
edge = bubble.rect.edge(direction)
for point in edge:
if point in all_boundaries:
return False
return True
def find_adjacent(self, room):
pass
class Bubble:
def __init__(self, pos, field, target_area, target_aspect_ratio):
self.target_area = target_area
self.target_aspect_ratio = target_aspect_ratio
self.rect = geometry.Rectangle(pos, 1, 1)
self.field = field
self.can_expand = {
geometry.Direction.north: True,
geometry.Direction.south: True,
geometry.Direction.east: True,
geometry.Direction.west: True
}
def determine_axis_to_expand(self):
north_south = [geometry.Direction.north, geometry.Direction.south]
east_west = [geometry.Direction.east, geometry.Direction.west]
def other_axis(axis_):
if axis_ == north_south:
return east_west
else:
return north_south
if self.rect.width < self.rect.height:
if self.rect.width/self.rect.height < self.target_aspect_ratio:
axis = east_west
else:
axis = north_south
else:
if self.rect.height/self.rect.width < self.target_aspect_ratio:
axis = north_south
else:
axis = east_west
axis_ok = False
for direction in axis:
if self.can_expand[direction]:
axis_ok = True
if not axis_ok and self.rect.area() < self.target_area:
return other_axis(axis)
return axis
def expand(self):
if self.rect.area() > self.target_area:
return False
if not any(self.can_expand.values()):
return False
axis = self.determine_axis_to_expand()
random.shuffle(axis)
for direction in axis:
if not self.can_expand[direction]:
continue
if self.field.bubble_has_free_side(self, direction):
self.rect.grow(direction)
return True
elif self.field.can_push(self, direction):
self.field.resolve_push(self, direction)
self.rect.grow(direction)
return True
else:
self.can_expand[direction] = False
return False
def move(self, direction):
if self.field.bubble_has_free_side(self, direction):
self.rect.move(direction)
return True
elif self.field.resolve_push(self, direction):
self.rect.move(direction)
return True
else:
return False
def can_be_pushed(self, direction):
if self.field.bubble_has_free_side(self, direction):
return True
elif self.field.can_push(self, direction):
return True
else:
return False
|
# Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление.
def dev(number_1, number_2):
try:
result = number_1 / number_2
return result
except ZeroDivisionError:
return "We can't divide by zero!"
print(dev(int(input(f"Введите целое число: ")), int(input(f"Введите еще одно целое число: "))))
|
from itertools import combinations
main_tup = []
even = []
odd = []
rm_tuple = []
def rSubset(arr, r):
return list(combinations(arr, r))
def getData(num):
input_num = num[0]
check_num = num[1:]
arr = range(1,input_num + 1)
r = 2
main_tup.append(rSubset(arr, r))
for i in range(1,9):
if(i%2 == 0):
even.append(i)
else:
odd.append(i)
for i in range(len(odd)):
if i<=len(odd) - r:
rm_tuple.append((odd[i],even[i+1]))
for i in range(len(even)):
if i<=len(even) - r:
rm_tuple.append((even[i],odd[i+1]))
for i in main_tup[0]:
for j in check_num:
if(i[0] == j or i[1] == j):
rm_tuple.append(i)
if(i[1] > i[0] + r):
rm_tuple.append(i)
return set(main_tup[0]) - set(rm_tuple)
getData([8, 1, 4, 8])
|
from functools import wraps
import numpy as np
class _InvalidatingSetter(object):
"""Setter descriptor that sets target object's _parametrized_circuit to None.
The descriptor uses __get__ and __set__ methods. Both of them accept ansatz as the
first argument (in this case). We just forward the __get__, but in __set__ we set
obj._parametrized_circuit to None.
"""
def __init__(self, target):
self.target = target
def __get__(self, ansatz, obj_type):
return self.target.__get__(ansatz, obj_type)
def __set__(self, ansatz, new_obj):
self.target.__set__(ansatz, new_obj)
ansatz._parametrized_circuit = None
def invalidates_parametrized_circuit(target):
"""Make given target (either property or method) invalidate ansatz's circuit.
It can be used as a decorator, when for some reason `ansatz_property` shouldn't be
used.
"""
if isinstance(target, property):
# If we are dealing with a property, return our modified descriptor.
return _InvalidatingSetter(target)
else:
# Methods are functions that take instance as a first argument
# They only change to "bound" methods once the object is instantiated
# Therefore, we are decorating a function of signature _function(ansatz, ...)
@wraps(target)
def _wrapper(ansatz, *args, **kwargs):
# Pass through the arguments, store the returned value for later use
return_value = target(ansatz, *args, **kwargs)
# Invalidate circuit
ansatz._parametrized_circuit = None
# Return original result
return return_value
return _wrapper
class DynamicProperty:
"""A shortcut to create a getter-setter descriptor with one liners."""
def __init__(self, name: str, default_value=None):
self.default_value = default_value
self.name = name
@property
def attrname(self):
return f"_{self.name}"
def __get__(self, obj, obj_type):
if not hasattr(obj, self.attrname):
setattr(obj, self.attrname, self.default_value)
return getattr(obj, self.attrname)
def __set__(self, obj, new_obj):
setattr(obj, self.attrname, new_obj)
def ansatz_property(name: str, default_value=None):
return _InvalidatingSetter(DynamicProperty(name, default_value))
def combine_ansatz_params(params1: np.ndarray, params2: np.ndarray) -> np.ndarray:
"""Combine two sets of ansatz parameters.
Args:
params1 (numpy.ndarray): the first set of parameters
params2 (numpy.ndarray): the second set of parameters
Returns:
numpy.ndarray: the combined parameters
"""
return np.concatenate((params1, params2))
|
from math import sqrt, ceil
def get_primes(n):
"""Calculates a list of primes up to n (included. """
primelist = []
for candidate in range(2, n + 1):
is_prime = True
root = int(ceil(sqrt(candidate))) # division limit
for prime in primelist: # we try only primes
if prime > root: #noo need to check any further
break
if candidate % prime == 0:
is_prime == False
break
if is_prime:
primelist.append(candidate)
return primelist
|
"""
usage:using list demo
"""
shoplist = ['apple','mango','carrot','banana']
print("I hava",len(shoplist),'itmes to purchase')
print("thes itmes are:")
for item in shoplist :
print(item)
print("I also hava to buy rice.")
shoplist.append("rice")
print("My shopping list is now ",shoplist)
print("I will sort my List now")
shoplist.sort()
print("Sorted shopping list is ",shoplist)
print ("the first item i will buy is",shoplist[0])
olditem = shoplist[0]
del shoplist[0]
print("I bought the ",olditem)
print("my shoplist is now",shoplist) |
"""
usage: docString
"""
def printMax (x,y):
"""Prints the Maximum of two numbers
the two value must be integer."""
x = int(x) #强制转换成int型
y = int(y)
if x > y:
print (x,"is maximum")
else:
print(y,"is maximum")
printMax(3,5)
print (printMax.__doc__)#类似文档注释 |
"""
usage:while 循环demo
"""
number = 23
running = True #true大写
while running:
guess = int(input("please input a int number:"))
if guess == number:
print('Congradulations, you guessed it')
running = False #stop the loop
elif guess < number:
print('No, it is a little higher than you guess')
else:
print("No, it is a little lower than you guess")
else:
print("the while loop is over")
print("Down")
|
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import math
def main_screen():
root=Tk()
rango_a_sexagesimal=StringVar()
rango_b_sexagesimal=StringVar()
numerador_rango_a=StringVar()
denominador_rango_a=StringVar()
numerador_rango_b=StringVar()
denominador_rango_b=StringVar()
rango_a_decimal=StringVar()
rango_b_decimal=StringVar()
root.title("Metodo de la regla falsa (trigonométricas)")
root.resizable(False,False)
frame_ecuacion=Frame(root,height="100", width="548")
frame_ecuacion.pack()
frame_ecuacion.config(bd="1", relief="sunken")
#ecuacion
Label(frame_ecuacion,text="Ecuación", font=("quicksand",13)).place(x=0,y=0)
x6=StringVar()
Entry(frame_ecuacion,width="3",font=("quicksand",12),textvariable=x6).place(x=10,y=30)
x6.set('0')
Label(frame_ecuacion,text="x⁶ +",font=("quicksand",12)).place(x=45,y=29)
x5=StringVar()
Entry(frame_ecuacion,width="3",font=("quicksand",12),textvariable=x5).place(x=90,y=30)
x5.set('0')
Label(frame_ecuacion,text="x⁵ +",font=("quicksand",12)).place(x=125,y=29)
x4=StringVar()
Entry(frame_ecuacion,width="3",font=("quicksand",12),textvariable=x4).place(x=170,y=30)
x4.set('0')
Label(frame_ecuacion,text="x⁴ +",font=("quicksand",12)).place(x=205,y=29)
x3=StringVar()
Entry(frame_ecuacion,width="3",font=("quicksand",12),textvariable=x3).place(x=250,y=30)
x3.set('0')
Label(frame_ecuacion,text="x³ +",font=("quicksand",12)).place(x=285,y=29)
x2=StringVar()
Entry(frame_ecuacion,width="3",font=("quicksand",12),textvariable=x2).place(x=330,y=30)
x2.set('0')
Label(frame_ecuacion,text="x² +",font=("quicksand",12)).place(x=365,y=29)
x1=StringVar()
Entry(frame_ecuacion,width="3",font=("quicksand",12),textvariable=x1).place(x=410,y=30)
x1.set('0')
Label(frame_ecuacion,text="x +",font=("quicksand",12)).place(x=445,y=29)
c=StringVar()
Entry(frame_ecuacion,width="3",font=("quicksand",12),textvariable=c).place(x=490,y=30)
c.set('0')
Label(frame_ecuacion,text="C",font=("quicksand",12)).place(x=525,y=29)
#funciones trigonométricas
funcion=StringVar()
Radiobutton(frame_ecuacion,text="sen",variable=funcion, value='sin').place(x=0,y=70)
Radiobutton(frame_ecuacion,text="cos",variable=funcion, value='cos').place(x=60,y=70)
Radiobutton(frame_ecuacion,text="tan",variable=funcion, value='tan').place(x=120,y=70)
funcion.set('sin')
#intervalo
frame_argumento=Frame(root,height="60", width="548")
frame_argumento.pack()
frame_datos_argumento=Frame(root,height="60", width="500")
frame_datos_argumento.pack()
#definimos el combobox
Label(frame_argumento,text="Medida del argumento",font=("quicksand",12)).place(x=0,y=0)
comboexample=ttk.Combobox(frame_argumento, font=("arial",12),
values=["grados", "fracciones de pi","radianes"])
#creamos la funcion que retorna el valor del combobox
def argumento():
medida_del_argumento=comboexample.get()
if(medida_del_argumento==''):
messagebox.showinfo("ERROR", "Seleccione una medida de argumento")
return 0
if(medida_del_argumento=="grados"):
for widget in frame_datos_argumento.winfo_children():
widget.destroy()
Label(frame_datos_argumento,text="[",font=("quicksand",12)).place(x=0,y=12)
Entry(frame_datos_argumento,width="3",font=("quicksand",12),textvariable=rango_a_sexagesimal).place(x=20,y=10)
rango_a_sexagesimal.set(0)
Label(frame_datos_argumento,text=",",font=("quicksand",12)).place(x=56,y=10)
Entry(frame_datos_argumento,width="3",font=("quicksand",12),textvariable=rango_b_sexagesimal).place(x=70,y=10)
rango_b_sexagesimal.set(0)
Label(frame_datos_argumento,text="]",font=("quicksand",12)).place(x=110,y=12)
elif(medida_del_argumento=="fracciones de pi"):
for widget in frame_datos_argumento.winfo_children():
widget.destroy()
Label(frame_datos_argumento,text="[",font=("quicksand",22)).place(x=0,y=12)
Label(frame_datos_argumento,text="-",font=("quicksand",30)).place(x=26,y=8)
Label(frame_datos_argumento,text="π",font=("arial",18)).place(x=50,y=8)
Label(frame_datos_argumento,text="π",font=("arial",18)).place(x=124,y=8)
Label(frame_datos_argumento,text="-",font=("quicksand",30)).place(x=96,y=8)
Label(frame_datos_argumento,text=",",font=("Quicksand",22)).place(x=72,y=14)
Entry(frame_datos_argumento,width="3",font=("quicksand",12),textvariable=numerador_rango_a).place(x=20,y=0)
numerador_rango_a.set(0)
Entry(frame_datos_argumento,width="3",font=("quicksand",12),textvariable=denominador_rango_a).place(x=20,y=32)
denominador_rango_a.set(0)
Entry(frame_datos_argumento,width="3",font=("quicksand",12),textvariable=numerador_rango_b).place(x=90,y=0)
numerador_rango_b.set(0)
Entry(frame_datos_argumento,width="3",font=("quicksand",12),textvariable=denominador_rango_b).place(x=90,y=32)
denominador_rango_b.set(0)
Label(frame_datos_argumento,text="]",font=("quicksand",22)).place(x=144,y=12)
elif(medida_del_argumento=="radianes"):
for widget in frame_datos_argumento.winfo_children():
widget.destroy()
Label(frame_datos_argumento,text="[",font=("quicksand",12)).place(x=0,y=12)
Entry(frame_datos_argumento,width="3",font=("quicksand",12),textvariable=rango_a_decimal).place(x=20,y=10)
rango_a_decimal.set(0)
Label(frame_datos_argumento,text=",",font=("quicksand",12)).place(x=56,y=10)
Entry(frame_datos_argumento,width="3",font=("quicksand",12),textvariable=rango_b_decimal).place(x=70,y=10)
rango_b_decimal.set(0)
Label(frame_datos_argumento,text="π",font=("arial",18)).place(x=120,y=4)
Label(frame_datos_argumento,text="]",font=("quicksand",12)).place(x=110,y=12)
print(medida_del_argumento)
#posicionamos el combobox
comboexample.place(x=12,y=28)
#boton que llama a la funcion que nos regresa la
button=Button(frame_argumento, text="Desplegar", command=argumento).place(x=230,y=14)
#error y numero de decimales
frame_error_decimales=Frame(root,height="130", width="548")
frame_error_decimales.pack()
frame_error_decimales.config(bd="1", relief="sunken")
Label(frame_error_decimales,text="Porcentaje de error",font=("quicksand",12)).place(x=0,y=20)
error=StringVar()
Entry(frame_error_decimales,width="9",font=("quicksand",12), textvariable=error).place(x=200,y=20)
error.set(0)
Label(frame_error_decimales,text="numero de decimales",font=("quicksand",12)).place(x=0,y=52)
decimales=StringVar()
Entry(frame_error_decimales,width="2",font=("quicksand",12), textvariable=decimales).place(x=200,y=52)
decimales.set(0)
def run():
validaciones()
obtener_resultados()
#es_grado_seis()
def validaciones():
#ecuacion
variables=[c.get(),x1.get(),x2.get(),x3.get(),x4.get(),x5.get(),x6.get()]
print('ecuacion: '+str(variables[0:]))
for x in range(7):
try:
float(variables[x])
print('todo bien, valor:'+ variables[x])
except :
print('error')
if(x>0):
messagebox.showinfo("ERROR", "Se ingresó un tipo de dato no valido en la variable x"+'^'+str(x))
else:
messagebox.showinfo("ERROR", "Se ingresó un tipo de dato no valido en la constante")
break
#funcion trigonometrica
print('funcion trigonométrica: '+str(funcion.get()))
if(funcion.get() == 0):
messagebox.showinfo("ERROR", "no se ha seleccionado una función trigonométrica")
return 0
elif(funcion.get() == 1):
print('funcion sen')
elif(funcion.get() == 2):
print('funcion cos')
elif(funcion.get() == 3):
print('funcion tan')
#intervalo
def validar_y_obtener_rango():
medida_del_argumento=comboexample.get()
print(medida_del_argumento)
if(medida_del_argumento==''):
messagebox.showinfo("ERROR", "no se ha seleccionado un metodo de medida del argumento")
return 0
if(medida_del_argumento=='grados'):
variables=[rango_a_sexagesimal.get(),rango_b_sexagesimal.get()]
print('rango sexagesimal: '+str(variables[0:]))
for x in range(2):
try:
float(variables[x])
print('todo bien, valor:'+ variables[x])
except :
print('error')
if(x<1):
messagebox.showinfo("ERROR", "Se ingresó un tipo de dato no valido en el intervalo 'a'")
else:
messagebox.showinfo("ERROR", "Se ingresó un tipo de dato no valido en el intervalo 'b'")
return 0
if(variables[0]>=variables[1]):
messagebox.showinfo("ERROR", "el intervalo 'a' debe ser menor que 'b'")
return 0
rango_a=float(str(variables[0]))
rango_b=float(str(variables[1]))
elif(medida_del_argumento=='fracciones de pi'):
variables=[numerador_rango_a.get(), denominador_rango_a.get(), numerador_rango_b.get(), denominador_rango_b.get()]
print('rango en fracciones: '+str(variables[0:]))
for x in range(4):
try:
float(variables[x])
print('todo bien, valor:'+ variables[x])
except :
print('error')
if(x==0):
messagebox.showinfo("ERROR", "Se ingresó un tipo de dato no valido en el numerador del intervalo 'a'")
elif(x==1):
messagebox.showinfo("ERROR", "Se ingresó un tipo de dato no valido en el denominador del intervalo 'a'")
elif(x==2):
messagebox.showinfo("ERROR", "Se ingresó un tipo de dato no valido en el numerador del intervalo 'b'")
elif(x==3):
messagebox.showinfo("ERROR", "Se ingresó un tipo de dato no valido en el denominador del intervalo 'b'")
return 0
try:
rango_a=float(variables[0])/float(variables[1])*math.pi
except:
messagebox.showinfo("ERROR", "no se puede resolver el valor del rango en 'a'")
return 0
try:
rango_b=float(variables[2])/float(variables[3])*math.pi
except:
messagebox.showinfo("ERROR", "no se puede resolver el valor del rango en 'b'")
return 0
if(rango_a>=rango_b):
messagebox.showinfo("ERROR", "el intervalo 'a' debe ser menor que 'b'")
return 0
elif(medida_del_argumento=='radianes'):
variables=[rango_a_decimal.get(),rango_b_decimal.get()]
print('rango decimal: '+str(variables[0:]))
for x in range(2):
try:
float(variables[x])
print('todo bien, valor:'+ variables[x])
except :
print('error')
if(x<1):
messagebox.showinfo("ERROR", "Se ingresó un tipo de dato no valido en el intervalo 'a'")
else:
messagebox.showinfo("ERROR", "Se ingresó un tipo de dato no valido en el intervalo 'b'")
return 0
if(variables[0]>=variables[1]):
messagebox.showinfo("ERROR", "el intervalo 'a' debe ser menor que 'b'")
return 0
rango_a=float(variables[0])*math.pi
rango_b=float(variables[1])*math.pi
return rango_a,rango_b
#print('rango: '+str(variables[0:]))
#porcentaje error
variables=[error.get(),decimales.get()]
print('porcentaje error y decimales: '+str(variables[0:]))
for x in range(2):
try:
float(variables[x])
except:
if(x==0):
messagebox.showinfo("ERROR", "se ingresó un dato no válido en el porcentaje de error")
else:
messagebox.showinfo("ERROR", "se ingresó un dato no válido en la cantidad de decimales")
button=Button(frame_error_decimales, text="Calcular",command=run).place(x=460,y=90)
#resultados
frame_resultados=Frame(root,height="200", width="548")
frame_resultados.pack()
frame_resultados.config(bd="1", relief="sunken")
Label(frame_resultados,text="porcentaje de error",font=("quicksand",12)).place(x=0,y=0)
mostrar_error=Listbox(frame_resultados)
Label(frame_resultados,text="resultado",font=("quicksand",12)).place(x=280,y=0)
mostrar_resultado=Listbox(frame_resultados)
def obtener_resultados():
mostrar_error.delete ( 0, 'end' )
mostrar_resultado.delete ( 0, 'end')
rango_a=validar_y_obtener_rango()[0]
rango_b=validar_y_obtener_rango()[1]
#tengo que arreglar el puto rango en los decimales
print(rango_a)
print(rango_b)
rango_a_menos_1=0
x=0
error_obtenido=1000000
variables=[c.get(),x1.get(),x2.get(),x3.get(),x4.get(),x5.get(),x6.get()]
variables=[float(i) for i in variables]
while(error_obtenido>float(str(error.get()))):
f_x0=0
f_x1=0
for j in range(len(variables)):
if(j<1):
f_x0 += variables[j]
f_x1 += variables[j]
else:
f_x0 += (variables[j])*(rango_a**j)
f_x1 += (variables[j])*(rango_b**j)
print("valores" + str(variables[0:]))
if(funcion.get()=='sin'):
f_x0=math.sin(f_x0)
f_x1=math.sin(f_x1)
elif(funcion.get()=='cos'):
f_x0=math.cos(f_x0)
f_x1=math.cos(f_x1)
elif(funcion.get()=='tan'):
f_x0=math.tan(f_x0)
f_x1=math.tan(f_x1)
print('f(x0): '+str(f_x0))
print('f(x1): '+str(f_x1))
medida_del_argumento=comboexample.get()
if(x==0):
rango_a=((f_x0*rango_b)-(f_x1*rango_a))/(f_x0-f_x1)
else:
rango_a_menos_1=rango_a
rango_a=rango_b-((f_x1*rango_a)-(f_x1*rango_b))/(f_x0-f_x1)
error_obtenido=abs(((rango_a-rango_a_menos_1)/rango_a)*100)
if(x>50):
messagebox.showinfo("ERROR", "se excedieron las 50 iteraciones")
return 0
if(error_obtenido<float(str(error.get()))):
return 0
mostrar_error.insert(x, "X"+str(x)+"= "+str(round(error_obtenido, int(str(decimales.get())))))
mostrar_resultado.insert(x, "X"+str(x)+"= "+str(round(rango_a, int(str(decimales.get())))))
x+=1
mostrar_error.place(x=0,y=40)
mostrar_resultado.place(x=280,y=40)
root.mainloop()
main_screen() |
from sklearn import tree
'''
features - used to describe data (i.e. weight, color)
label - identify the kind data (i.e. name)
'''
#in example: 0 = apple, 1 = orange
features = [[140,1],[130,1],[150,0],[170,0]] #input to classifier
labels = [0,0,1,1] #output from classifier
#decision tree - box of rules
clf = tree.DecisionTreeClassifier()
#think of fit as find patterns in data i.e. heavy weight = certain obj
clf = clf.fit(features,labels)
#input = features for new example
# will print what classifier thinks the object is
#I predict it will print 1 for orange
prediction = clf.predict([[160,0]])
if(prediction == 0):
print("0 - apple")
elif (prediction == 1):
print("1 - orange") |
ch=input("Enter a character:")
if((ch>='a'and ch<='z')or(ch>='a'and ch<='z')):
print(ch,"Alphabet")
else:
print("Not alphabet")
|
class Meeting:
def __init__(self, start, end):
self.start = start
self.end = end
def __repr__(self):
return f"Meeting({self.start}, {self.end})"
def merge_meetings(meetings):
ordered = sorted(meetings, key=lambda x: x.start)
tmp = ordered[0]
condensed_meetings = [tmp]
for i in ordered[1:]:
#(1) If it overlaps a condensed element, replace with latest end
if i.start < tmp.end:
condensed_meetings[-1].end = i.end
tmp = Meeting(tmp.start, i.end)
#If it doesn't, append to output array and then (1) check overlaps for it.
else:
condensed_meetings.append(i)
tmp = Meeting(tmp.start, i.end)
print(f"Condensed Meetings: {condensed_meetings}")
if __name__ == '__main__':
meetings = [Meeting(13, 18), Meeting(0, 1), Meeting(2, 5), Meeting(3, 5), Meeting(8, 10), Meeting(9, 14)]
print(meetings)
merge_meetings(meetings) |
import random
score = 0
def main():
print("Rolling Dice !")
print(" ")
doMoreRolls = True
while doMoreRolls == True:
playerChoice = input("Do you want to roll again ? Y/N : ")
if (playerChoice == "Y" or playerChoice == "y" or
playerChoice == "Yes" or playerChoice == "yes" or
playerChoice == "YES"):
rollDice()
else:
doMoreRolls = False
endRollingDiceProgram()
def rollDice():
if score < 55:
diceRollValue = random.randrange(1, 7)
displayDicePicture(diceRollValue)
print('You rolled a ' + str(diceRollValue))
print(' ')
print('Your score is ' + str(score))
else:
print('You Have Won!')
def endRollingDiceProgram():
print(" ")
input("Press Any Key to Exit ")
quit()
def displayDicePicture(diceRollValue):
global score
if diceRollValue == 1:
print(' ')
print(' ----- ')
print('| |')
print('| O |')
print('| |')
print(' ----- ')
print(' ')
score = score + 1
elif diceRollValue == 2:
print(' ')
print(' ----- ')
print('| O|')
print('| |')
print('|O |')
print(' ----- ')
print(' ')
score = score + 2
elif diceRollValue == 3:
print(' ')
print(' ----- ')
print('|O |')
print('| O |')
print('| O|')
print(' ----- ')
print(' ')
score = score + 3
elif diceRollValue == 4:
print(' ')
print(' ----- ')
print('|O O|')
print('| |')
print('|O O|')
print(' ----- ')
print(' ')
score = score + 4
elif diceRollValue == 5:
print(' ')
print(' ----- ')
print('|O O|')
print('| O |')
print('|O O|')
print(' ----- ')
print(' ')
score = score + 5
else:
print(' ')
print(' ----- ')
print('|O O|')
print('|O O|')
print('|O O|')
print(' ----- ')
print(' ')
score = score + 6
main()
endRollingDiceProgram()
|
string=raw_input("Enter a string:")
word=string.split()
str=""
for i in word[::-1]:
str+=" "+i
print(str)
|
n1=input("Enter no1:")
n2=input("Enter no2:")
n3=input("Enter no3:")
if(n1>n2):
if(n1>n3):
max=n1
else:
max=n3
elif(n2>n3):
max=n2
else:
max=n3
print (max)
|
def circle(r):
return 3.14*(r**2)
def rectangle(l,b):
return l*b
def triangle(b,h):
return 1.5*b*h
print ("1.Circle\n2.Rectangle\n3.Square")
ch=input("Enter your choice:")
if (ch==1):
r=input("Enter the radius:")
print("Area of circle:"+str(circle(r)))
if (ch==2):
l=input("Enter the breadth:")
b=input("Enter the height:")
print("Area of rectangle:"+str(rectangle(l,b)))
if (ch==3):
b=input("Enter the base:")
h=input("Enter the height:")
print("Area of triangle:"+str(triangle(b,h)))
|
#funcao responsavel por ler o arquivo e gerar as matrizes a serem utilizadas pelo sistema
#ao achar a matriz de cada sistema, ele resolve o problema com outra função e mostra o resultado
#repetindo para todos os sistemas.
#Antes da repeticao, o resultado eh salvo no arquivo RESUL
def criaMatriz():
#esvazia o arquivo de saida
saidaluI = open("RESUL",'w')
saidaluI.close()
entradalu = open("SISTEMA",'r')
(m,n)= entradalu.readline().split(",")
m = int(m)
n = int(n)
for i in range(0,m):
matrizSistema = []
for j in range(0,n):
linhaAtual = entradalu.readline().split(",")
for k in range(0, len(linhaAtual)):
linhaAtual[k] = int(linhaAtual[k])
matrizSistema.append(linhaAtual)
linhaAtual = []
for j in range(0,n):
linhaAtual.append(entradalu.readline().split("/"))
for k in range(0, len(linhaAtual[j])):
linhaAtual[j][k] = int(linhaAtual[j][k].strip("\n"))
matrizVars = linhaAtual
#chama fatoraLU que realmente faz a fatoracao e retorna os resultados que serao salvos no arquivo de resultado
determinante = achaDeterminante(matrizSistema,n)
solucao = fatoraLU(matrizSistema, matrizVars,n)
saidaluF = open("RESUL", 'a')
saidaluF.write("\n\nDeterminante:" + str(determinante))
saidaluF.close()
#salva L no arquivo
salvaMatriz("RESUL","L:",solucao[0],n)
#salva U no arquivo
salvaMatriz("RESUL","U:",solucao[1],n)
#salva y no arquivo
salvaMatriz("RESUL","Y:",solucao[2],n)
#salva x no arquivo
salvaMatriz("RESUL","X:",solucao[3],n)
#salva o vetor passado no arquivo passado
def salvaVetor(nomeArq,letra,vetor,n):
saida = open(nomeArq,'a')
saida.write("\n\n"+letra+"\n")
linhaAtual = ""
for l in range(0, n):
linhaAtual += " | " +str(vetor[l])+" | "
saida.write(linhaAtual)
#salva a matriz passada no arquivo passado
def salvaMatriz(nomeArq,letra,matriz,n):
saida = open(nomeArq,'a')
saida.write("\n\n"+letra+"\n")
for k in range(0, n):
linhaAtual = "\n"
for l in range(0, n):
linhaAtual += " | " +str(matriz[k][l])+" | "
saida.write(linhaAtual)
#realmente realiza a fatoracao LU
def fatoraLU(coef, vars,n):
solucao = []
print("Sistema atual:" + str(coef))
print("Coeficientes atuais:" + str(vars))
#primeira etapa, achar L e U
l = [[0 for x in range(n)] for y in range(n)]
for i in range(0,n):
l[i][i]=1
u = coef
for i in range(0,n-1):
u = ajustaColuna(u,i)
(l,u) = ajustaLinhas(l,u,i,n)
print("L:" + str(l))
print("U:" + str(u))
solucao.append(l)
solucao.append(u)
yf=[]
xf=[]
for i in range(0,n):
y = achaVarsL(l,vars[i])
yf.append(y)
x = achaVarsU(u,y)
xf.append(x)
solucao.append(yf)
solucao.append(xf)
x=xf
y=yf
print("Y:" + str(y))
print("X:" + str(x))
print("==========================")
return solucao
#essa funcao acha as variveis de incognita dado uma matriz de vals e uma de coeficiente, funciona apenas para L
def achaVarsL(vals,coefs):
tamMax = len(vals)
results = [0]*tamMax
results[0] = coefs[0]/vals[0][0]
for i in range(1,tamMax):
results[i] = coefs[i]
for j in range(0,i):
results[i]-= vals[i][j]*results[j]
results[i]=results[i]/vals[i][i]
return results
#essa funcao acha as variveis de incognita dado uma matriz de vals e uma de coeficiente, funciona apenas para U
def achaVarsU(vals,coefs):
tamMax = len(vals)
results = [0]*tamMax
results[tamMax-1] = coefs[tamMax-1]/vals[tamMax-1][tamMax-1]
for i in range(tamMax-2,-1,-1):
results[i] = coefs[i]
for j in range(i+1,tamMax):
results[i]-= vals[i][j]*results[j]
results[i]=results[i]/vals[i][i]
return results
#essa funcao zera os valores da coluna abaixo da linha atual e atualiza as outras colunas com o valor de multiplicacao
def ajustaLinhas(l,u,atual,max):
valoresDivisao = [0]*(max)
#encontra os valores de divisao e aploca na linha
for i in range(max-1,atual,-1):
valoresDivisao[i]=((u[i][atual])/u[atual][atual])
#ajusta a linha de l
for j in range(atual,max):
u[i][j]= u[i][j] - (u[atual][j])*valoresDivisao[i]
#ajusta u
l[i][atual] = valoresDivisao[i]
return (l,u)
#essa funcao faz o pivoteamente parcial colocando o maior valor da coluna n na linha n
def ajustaColuna(l,n):
maiorLinha = 0
valMaiorLinha = l[0][n]
for i in range(1,len(l)):
if(l[i][n]>valMaiorLinha):
valMaiorLinha=l[i][n]
maiorLinha=i
linhaTemp = l[n]
l[n]=l[maiorLinha]
l[maiorLinha]=linhaTemp
return l
#acha a determinante do sistema
def achaDeterminante(sist,n):
det=0
for i in range(0,n):
det+=sist[i][i]
return det
#funcao principal
criaMatriz() |
'''
@Descripttion: 寻找最大数
@Author: daxiong
@Date: 2019-09-06 20:31:58
@LastEditors: daxiong
@LastEditTime: 2019-09-06 20:41:30
'''
s = input().strip().split()
strL = [int(x) for x in s[0]]
m = int(s[1])
newLength = len(strL) - m
newNum = ''
while newLength != 0: # 一个一个的找到最大的数字
maxNum = max(strL[: len(strL) - newLength + 1])
newNum += str(maxNum)
strL = strL[strL.index(maxNum) + 1: ]
newLength -= 1
print(newNum) |
def QuickSort(list,low,high):
if high > low:
k = Partitions(list,low,high)
QuickSort(list,low,k-1)
QuickSort(list,k+1,high)
def Partitions(list,low,high):
left = low
right = high
k = list[low]
while left < right :
while list[left] <= k:
left += 1
while list[right] > k:
right = right - 1
if left < right:
list[left],list[right] = list[right],list[left]
list[low] = list[right]
list[right] = k
return right
list_demo = [6,1,2,7,9,3,4,5,10,8]
print(list_demo)
QuickSort(list_demo,0,9)
print(list_demo) |
'''
@Descripttion:
@Author: daxiong
@Date: 2019-08-29 19:53:13
@LastEditors: daxiong
@LastEditTime: 2019-08-29 20:26:40
'''
size = int(input().strip())
nums = input().split()
nums = [int(x) for x in nums]
tail = [nums[0]]
for i in range(1, size):
left = 0
right = len(tail)
while left < right:
mid = (left + right) >> 1
if tail[mid] < nums[i]:
left = mid + 1
else:
right = mid
if left == len(tail):
tail.append(nums[i])
else:
tail[left] = nums[i]
print(len(tail))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.