text stringlengths 37 1.41M |
|---|
print "Hello World!"
print "Hello Again"
print "I like typing this."
print "This is fun."
print 'Yay! Printing.'
print "I'd much rather you 'not'."
print 'I "said" do not touch this.'
print "Arithemetics"
print 2+4
print 8/2
print 8%2
print 6>8
rate = 12
tax = 24
total = rate + tax /100
print tax
rate = 12
tax = 24
total = rate + tax /100
print "tax is", tax
print "tax is %.2f"%tax
print "tax is %d"%tax
print "tax is %s"%tax
print "double tax is %.2f"%(tax +tax)
x = "'%d' students." % 10
y = "hello %s and bye %s." % ("you", "me")
print x
print y
print "I said: %r." % x
print "I also said: '%s'." % y
hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r"
print joke_evaluation % hilarious
w = "This is the left side of..."
e = "a string with a right side."
print w + e
print "." * 10
x = "h"
y = "mn"
print x +y,
print x +y
formatter = "%r %r %r %r"
print formatter % (1, 2, 3, 4)
print formatter % ("one", "two", "three", "four")
print formatter % (True, False, False, True)
print formatter % (formatter, formatter, formatter, formatter)
print formatter % (
"I had this thing.",
"That you could type up right.",
"But it didn't sing.",
"So I said goodnight."
)
print """hello, I am in a bus
jello bello vello"""
print 'Lol"'
tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split\non a line."
backslash_cat = "I'm \\ a \\ cat."
fat_cat = """
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
"""
print tabby_cat
print persian_cat
print backslash_cat
print fat_cat
print "Enter Your Name:"
name = raw_input()
print "so your name is %s" %name
print "Enter Your Age:"
age = raw_input("We won't tell don't worry")
print "so your age is %s" %age
|
def solution(s):
answer = []
for i in range(len(s)):
for j in range(1, len(s) + 1):
if s[i:j] and str(s[i:j]) == str(s[i:j])[::-1]:
answer.append(s[i:j])
elif s[j:i] and str(s[j:i]) == str(s[j:i])[::-1]:
answer.append(s[j:i])
return max(answer)
print(solution("abcdbda")) |
answer = 0
def dfs(begin, target, words, visited):
global answer
stacks = [begin]
while stacks:
stacks.pop()
stack = stacks.pop()
if begin == target:
return answer
for w in range(len(words)):
if [] == 1:
answer += 1
def solution(begin, target, words):
if target not in words:
return 0
visited = [0 for i in words]
global answer
return answer |
A = list(input())
B = list(input())
count = 0
intersection = set(A) & set(B)
symmetric_difference = set(A) ^ set(B)
for x in symmetric_difference:
count += A.count(x) + B.count(x)
for x in intersection:
count += abs(A.count(x) - B.count(x))
print(count) |
num1 = input("Enter number sequences seperated by comma :").split(',')
# Given tuple
num_tuple = tuple((num1))
print("Given list is ", num_tuple)
# Print elements that are divisible by 5
print("Elements that are divisible by 5:")
for num in num_tuple:
if (int(num) % 5 == 0):
print(num) |
class DictList(dict):
"""A dictionnary of lists of same size. Dictionnary items can be
accessed using `.` notation and list items using `[]` notation.
Example:
>>> d = DictList({"a": [[1, 2], [3, 4]], "b": [[5], [6]]})
>>> d.a
[[1, 2], [3, 4]]
>>> d[0]
DictList({"a": [1, 2], "b": [5]})
"""
__getattr__ = dict.__getitem__
__setattr__ = dict.__setitem__
def __len__(self):
return len(next(iter(dict.values(self))))
def __getitem__(self, index):
return DictList({key: value[index] for key, value in dict.items(self)})
def __setitem__(self, index, d):
for key, value in d.items():
dict.__getitem__(self, key)[index] = value |
def quartiles(arr):
# Write your code here
arr = sorted(arr)
n = len(arr)
if n % 2 == 0:
median = (arr[n//2] + arr[n//2 - 1]) / 2
arr1 = arr[:n//2]
arr2 = arr[n//2:]
else:
median = arr[n//2]
arr1 = arr[:n//2]
arr2 = arr[n//2 + 1:]
l = len(arr1)
if l % 2 == 0:
q1 = (arr1[l//2] + arr1[l//2 - 1]) / 2
q3 = (arr2[l//2] + arr2[l//2 - 1]) / 2
else:
q1 = arr1[l//2]
q3 = arr2[l//2]
res = list(map(int, [q1, median, q3]))
return res
|
def getNumber(string):
for i in range (0,len(string)):
if string[i].isdigit()==True or string[i]=='.':
for j in range (i,len(string)+1):
if j>len(string)-1:
val=string[i:j+1]
return float(val)
if string[j].isdigit()==True or string[j]=='.':
j+=1
else:
val=sphere[i:j]
return float(val)
break
import math
print('A sphere has a cylinder inscribed within it. For a given radius or height of the cylinder, find the greatest possible volume.')
restart=True
while restart:
restart=False
print('What is the radius of the sphere (in cm)?')
sphere=input()
if len(sphere)!=0:
if sphere[0].isdigit==False:
print("Put the value of the sphere radius at the beginning of your input.")
restart=True
if restart==False:
sphere=getNumber(sphere)
if sphere==None:
print("Specify the radius with digits")
restart=True
else: restart=True
restart=True
while restart:
while restart:
restart=False
print('For a sphere with a radius of '+str(sphere)+'cm, input either a radius or height value in cm:')
first=input()
if len(first)==0:
restart=True
if restart==False:
if first[0]=='r' or first[0]=='R':
typ='radius'
elif first[0]=='h' or first[0]=='H':
typ='height'
else:
restart=True
print("Sorry about this, I can't tell if that was a radius or a height. Try again specifying the type at the beginning of your input.")
value=getNumber(first)
if value==None:
print("Specify the radius/height with digits")
restart=True
else:
restart=False
if typ=='radius':
print('I don\'t actually know what the volume is, as I left the sheet of paper with the formula on it at home. You inputted a radius: '+str(value))
#print the volume
if typ=='height':
print('I don\'t actually know what the volume is, as I left the sheet of paper with the formula on it at home. You inputted a height: '+str(value))
#print the volume
|
from .peekable import Peekable
def sequence(*iterables, by=None, compare=None):
if compare is not None:
compare = compare
elif by is not None:
compare = lambda i1, i2: by(i1) <= by(i2)
else:
compare = lambda i1, i2: i1 <= i2
iterables = [Peekable(it) for it in iterables]
done = False
while not done:
next_i = None
for i, it in enumerate(iterables):
if not it.empty():
if next_i is None or compare(it.peek(), iterables[next_i].peek()):
next_i = i
if next_i is None:
done = True
else:
yield next(iterables[next_i])
|
#!usr/bin/env python3
def timeConversion(s):
if s.endswith("AM"):
s=s.strip("AM")
x=s.split(':')
if x[0]=='12':
x[0]='00'
result=':'.join(x)
return result
else:
result=':'.join(x)
return result
elif s.endswith("PM"):
s=s.strip("PM")
x=s.split(':')
if x[0]=='12':
result=':'.join(x)
return result
else:
x[0]=str(int(x[0])+12)
result=':'.join(x)
return result
s="12:45:54PM"
result = timeConversion(s)
print(result)
|
#program to understand the multi-line comments in python
'''
Since python will ignore string literals which are not assigned to a variable,you can add a multi-;ine string (Triple quotes) in your code,
and place your comments inside it.
'''
'''
As long as the string is not assigned to a variable, python read the code, but later ignore it,
and you have made a multiline comment.
'''
'''
This is a comment
written in
more than one just one line
'''
"""
This is comment
written in
more than just one line
"""
print("Hey!!, you have made a multi-line comment in above line of code")
|
"""
Author: Kristofer Stensland
Last Updated: October, 2012
Description: Sends search queries to Ask.com and harvests the top ten most relevant
documents, storing all of their URLS in a sqlite database.
Then Removes all of the HTML tags leaving only the tokens.
Then cleans up the documents by formating and stemming each occurence
of a token in all the documents.
"""
import pickle
import sqlite3
import os, glob
import urllib, urllib2, re, urlparse, cookielib
import poster
from portStemmer import *
from nltk.tokenize import *
from stripper import *
# Formats an ask.com search query.
def makeQuery(phrase):
query = phrase.lower().replace(' ', '+')
return query
# Sends a query to ask.com and collects the top ten documents from the query results.
def harvestAsk(phrase):
query = makeQuery(phrase)
# Send the query to ask.com and collect the first two pages of results in order to obtain
# the top ten documents.
html = urllib2.urlopen("http://www.ask.com/web?qsrc=1&o=0&l=dir&q=" + query).read()
# Using a regular expression, collect all the HTML tags that contain URLS to documents.
pageDataList = re.findall(r'<a id="(r[0-9]*_t)" href="([^"]*)" (.*)</a>', html)
# Get the link to the second page of results.
page2Link = re.findall(r'<div class="pgc"><a href="([^"]*)" class="pg title">2</a>', html)
# We go to the second page because some results consist of media
# files, such as links to youtube videos or music streaming services. So since each page
# only shows ten results, we go to the next page in order to get enough pages that mainly
# consist of text.
if page2Link is not None and len(page2Link) > 0:
html2 = urllib2.urlopen(page2Link[0], html)
moreData = re.findall(r'<a id="(r[0-9]*_t)" href="([^"]*)" (.*)</a>', html)
pageDataList = pageDataList + moreData
# Store all the URLS in a list.
links = []
for i in range(len(pageDataList)):
links.append(pageDataList[i][1])
return links
# Scan the directory containing all the files containing all the search queries.
# In this lab we have different files for movies, books and music.
def scanDir():
#Get the text files from the item directory
os.chdir(os.getcwd"/data/item")
fileList = glob.glob("*.txt")
"""
Dictionary of all the items we are going to search for and their URLS with the following structure:
{(item type):
{(item name aka. search query):
[(list of all the URLS pertaining to that item.)]
}
}
"""
itemsDict = {}
print "Scanning directories for items."
# Read each file.
for fileName in fileList:
itemType = fileName.replace('.txt', '')
print "Scanning items relating to",itemType
itemsDict[itemType] = {}
f = open(fileName, 'r')
items = f.readlines()
# Harvest the top 10 links for each search query
for item in items:
# Make the ask.com query
print "scanning links for: ", item
query = "\""+item.replace("\n", '')+"\" "+itemType
# Get the list of links
itemLinks = harvestAsk(query)
itemsDict[itemType][item] = itemLinks
print
print "\nFound all the links"
return itemsDict
# Harvests the website for each URL and stores the HTML, headers, and text data in text files
def cacheData(itemDict):
for keyword in itemDict.keys(): # =keyword: item
for item in itemDict[keyword].keys(): # item: (movie title, book titles, artist, artist)
print "Checking out", item
conn = sqlite3.connect(os.getcwd'/data/cache.db')
c = conn.cursor()
c.execute("Select * from item WHERE itemName=?", (item,))
rows = c.fetchall()
# Check if item exists in the DB already, if not insert it.
if (len(rows) < 1):
c.execute("INSERT INTO item VALUES (NULL, ?)", (item,))
conn.commit()
c.execute("Select * from item WHERE itemName=?", (item,))
rows = c.fetchall()
print "ROWS:\t", rows
itemId = rows[len(rows)-1][0]
# Harvest all the pages for each URL.
for link in itemDict[keyword][item]:#link to page
print
print "Got that link! ", link
headers = {
'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.0; en-GB; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12',
'Accept': 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5',
'Accept-Language': 'en-gb,en;q=0.5',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
'Connection': 'keep-alive'
}
# Try downloading the page.
try:
req = urllib2.Request(link, None, headers)
response = urllib2.urlopen(req)
page = response.read()
except:
print "Could not retrieve page: ", link
HTTPheader = response.info()# Get the header
# After storing the page in the database we will get its unique ID.
# That ID will be the files name in the cache.
webPageId = storePageInfoInDatabase(link, item)
if webPageId is not None:
writeDataToFiles(webPageId, page, HTTPheader)
# Store a URL and it's document in a sql database.
def storePageInfoInDatabase(link, item):
conn = sqlite3.connect(os.getcwd() + '/data/cache.db')
c = conn.cursor()
c.execute("SELECT * from webPage WHERE linkText=?", (link,))
row = c.fetchone()
# Check if the webpage already exists in the DB
if row is None:
# If not, insert into the webPage table
print link, "not yet in the database"
c.execute("INSERT INTO webPage VALUES (NULL, ?)", (link,))
c.execute("SELECT * from webPage WHERE linkText=?", (link,))
row = c.fetchone() #Get the row with the link
print "The link: ", link," is now in the database"
pageId = str(row[0]) #Get the id number of that row
"""
#insert into item
#Check if item exists already
c.execute("Select * from item WHERE itemName=?", (item,))
rows = c.fetchall()
if (len(rows) < 1):
c.execute("INSERT INTO item VALUES (NULL, ?)", (item,))
conn.commit()
c.execute("Select * from item WHERE itemName=?", (item,))
rows = c.fetchall()
print "ROWS:\t", rows
itemId = rows[len(rows)-1][0]
"""
else:
print "That page already in the database"
pageId = None
# Insert into itemToWebPage, and get the item ID
c.execute("Select itemId from item WHERE itemName=?", (item,))
try:
row = c.fetchone()
itemId = row[0]
c.execute("INSERT INTO itemToWebPage VALUES (NULL, ?, ?)", (itemId, pageId,))
except:
print
print "Could not find that ",item,"'s id"
print
conn.commit()
return pageId
# Write the HTTP header and the web-page document to a local text file.
def writeDataToFiles(ID, page, HTTPheader):
# Make the file name for all the files
# This will be the web pages unique ID in the data base
fileName = convertIdToFileName(ID)
# Write the raw HTML File
rawFilePath = os.getcwd() + "/data/raw/"+(fileName.replace('txt', 'html'))
rawFile = open(rawFilePath, 'w')
rawFile.write(page)
print "Wrote the raw HTML file"
# Write the HTTP header File
headFilePath = os.getcwd() + "/data/header/"+fileName
headFile = open(headFilePath, 'w')
headFile.write(str(HTTPheader))
# Tokenize the raw HTML file and write it
tokenizeRawHTML(ID, rawFilePath)
# Removes all the HTML tags, thus leaving all the tokens in the document.
# Then makes each line
def tokenizeRawHTML(webPageId, rawFilePath):
# Read in the body of the web-document and write it to a local file.
print "Tokenizing the HTML file ", rawFilePath
pageBodyFileName = writeBodyToFile(rawFilePath)
pageBodyFile = open(pageBodyFileName, 'r')
# Store the body in a string.
pageBody = pageBodyFile.read()
# Strip the HTML tags in the body
strippedPage = strip_tags(pageBody)
if strippedPage is None:
print "Page: ", rawFilePath," not read"
return
print "Stripped the body"
# Tokenize the words and write them to a file
p = PorterStemmer()
tokensFileName = convertIdToFileName(webPageId)
# The text file of tokens.
tokensFile = open(os.getcwd() + "/data/clean/"+tokensFileName, 'w')
# Get each line in the leftover body.
sentences = sent_tokenize(strippedPage)
print "About to tokenize the stripped body"
counter = 0
for sentence in sentences:
tokens = word_tokenize(sentence)
for token in tokens:
stem = p.stem(token, 0,len(token)-1)
stem = stem.lower()
try:
stem = stem.encode('utf-8')
except:
print "Could not encode the token, trying a decode"
print "Type: ", type(stem)
stem = stem.decode('utf-8', 'replace')
if (stem.isalpha() or stem.isdigit()) and not(stem in ['-', '_']):
# Write token to the file
tokensFile.write(stem + "\n")
# Store token in database
conn = sqlite3.connect(os.getcwd() + '/data/cache.db')
c = conn.cursor()
c.execute("SELECT * FROM token where word = ?", (stem,))
row = c.fetchone()
tokenId = 0
if row is None:
try:
c.execute("INSERT INTO token VALUES (NULL, ?)",(stem,))
conn.commit()
except:
print "Could not store token: ", stem, " into database."
continue
c.execute("SELECT tokenId FROM token WHERE word=?", (stem,))
row = c.fetchone()
try:
tokenId = row[0]
except:
print "could not find ", stem," in token table."
continue
c.execute("INSERT INTO tokenToWebPage VALUES"+
"(NULL, ?, ?, ?)", (tokenId, webPageId, counter,))
conn.commit()
counter = counter + 1
# Delete the body fileName
os.remove(pageBodyFileName)
print "Tokens in ",tokensFileName
# Converts a db ID number to a string in order to create a file with that name.
def convertIdToFileName(ID):
fileName = str(ID)
# If the id has less than 6 digits, we want to add zeroes until it is 6 digits long.
while len(fileName) < 6:
fileName = "0" + fileName
fileName += ".txt"
return fileName
def main():
try:
f = open("saveItems.p", 'r')
itemDict = pickle.load(f)
except:
print "Couldn't find the pickle file."
f = open("saveItems.p", "r")
#Collect the raw HTML files and store them in a dictionary.
itemDict = scanDir()
pickle.dump(itemDict, f)
# Store all the token files
cacheData(itemDict)
"""
STRUCTURE FOR itemDict
for key in itemDict.keys(): #keyword
print key
for key2 in itemDict[key].keys(): #item (movie title, book titles, artist name)
print "\t",key2
for link in itemDict[key][key2]:#link to page
print "\t\t", link
#Harvest Ask.com for links with query
queryLinks = harvestAsk('poop')
#Get requests for each link and store data in files
VAR = getData(queryLinks)
"""
main()
|
"""Provides helper utilities for formatting"""
import ast
def safe_determine_type(string):
"""
Determine the python type of the given literal, for use in docstrings
Args:
string (str): The string to evaluate
Returns:
``str``: The type, or "TYPE" if the type could not be determined
"""
try:
return ast.literal_eval(string).__class__.__name__
except ValueError:
try:
if string.startswith("set(") or isinstance(
ast.literal_eval(string.replace("{", "[").replace("}", "]")), list
):
return "set"
except ValueError:
return "TYPE"
def get_param_info(param):
"""
Extract info from a parso parameter
Args:
param: the parameter
Returns:
tuple: name, type, default
"""
param_type = param.annotation.value if param.annotation else "TYPE"
param_default = (
" default: ``{0}``".format(param.default.get_code()) if param.default else ""
)
if param_default and not param.annotation:
param_type = safe_determine_type(param.default.get_code())
return param.name.value, param_type, param_default
def get_return_info(ret, annotation):
"""
Extract info from a node containing a return statement
Args:
ret: the return node
annotation: the funcation annotation (may be None)
Returns:
tuple: type, expression after 'return' keyword
"""
ret_type = annotation.value if annotation else "TYPE"
expression = "".join(x.get_code().strip() for x in ret.children[1:])
expression = " ".join(expression.split())
return ret_type, expression
def get_exception_name(node):
"""
Find the name of an exception
Args:
node: Parso node containing the raises statement
Returns:
str: The exception name
"""
name = node.children[1]
while not name.type == "name":
name = name.children[0]
return name.value
|
import collections
class Solution(object):
def numSquares(self, n):
"""
:type n: int
:rtype: int
"""
squares = [1]
i = 2
while squares[len(squares)-1] < n:
squares.append(i*i)
i += 1
print squares
result = 0
results = collections.defaultdict(int)
n_val = n
for square in squares[::-1]:
if n_val / square > 0:
results[square] += n_val / square
result += n_val / square
n_val %= square
print square, results, n_val
return result
print Solution().numSquares(13)
|
# a/b
def add(x, y):
a = True
while a:
a = x & y
b = x ^ y
x = a << 1
y = b
return b
def mult(a, b):
r = 0
for i in xrange(b):
r = add(r, a)
return r
def division(a, b, precission=0.001):
prev_guess = 0
guess = a
while abs(a - mult(guess, b)) > precission:
aux = guess
if mult(guess, b) > a:
guess -= abs(guess - prev_guess) / 2
else:
guess += abs(guess - prev_guess) / 2
prev_guess = aux
return guess
print division(10, 2)
print division(12, 3)
|
"""
You are the main character in a game where you have to defeat a number of
enemies in order. The player has a strength value and an initial amount of
money. Each enemy also has a strength value, plus a price.
When facing each enemy you can either:
1) Fight him (if your strength is enough). You keep your money.
2) Bribe him (if you have the necessary money). You subtract the enemy's
price from your money, and it joins you and adds its strength to yours.
Given a starting strength and amount of money, calculate the optimal
strategy and the amount of money you end with (-1 if impossible).
This can be easily solved recursively in O(2^n) basically trying out each
option at every enemy. But is there a polynomial solution, maybe involving
DP?
"""
class Game(object):
def __init__(self, streingth, money):
self._streingth = streingth
self._money = money
def play(self, enemies, streingth=None, money=None, max_money=None):
if streingth is None:
streingth = self._streingth
money = self._money
max_money = [-1]
if streingth < 0 or money < 0:
return max_money[0]
if len(enemies) == 0:
if money > max_money[0]:
max_money[0] = money
return max_money[0]
self.play(enemies[1:], streingth-enemies[0][0], money, max_money)
self.play(enemies[1:], streingth, money-enemies[0][1], max_money)
return max_money[0]
import unittest
class TestGame(unittest.TestCase):
def test_play(self):
gm = Game(4, 3)
self.assertEqual(gm.play((
(2, 3),
(1, 2),
(2, 3),
)), 1)
self.assertEqual(gm.play(()), 3)
self.assertEqual(gm.play((
(2, 3),
(2, 3),
)), 3)
self.assertEqual(gm.play((
(9, 9),
(9, 9),
)), -1)
if __name__ == '__main__':
unittest.main()
|
"""
You are given a text file that has list of dependencies between (any) two
projects in the source code repository. Write an algorithm to determine the
build order ie. which project needs to be build first, followed by which
project..based on the dependencies.
Bonus point: If you can detect any circular dependencies and throw an exception
if found.
EX: ProjectDependencies.txt
a -> b (means 'a' depends on 'b'..so 'b' needs to be built first and then 'a')
b -> c
b -> d
c -> d
Then the build order can be
d , c, b, a in that order
"""
from collections import defaultdict
class Builder(object):
def __init__(self, deps):
self._deps = defaultdict(list)
self._elems = set()
pointed_elems = set()
for d in deps:
self._deps[d[1]].append(d[0])
self._elems.add(d[1])
self._elems.add(d[0])
pointed_elems.add(d[0])
self._start_nodes = self._elems-pointed_elems
def _dfs(self, node, visited_nodes, path):
print visited_nodes, node, path
if len(visited_nodes) == len(self._elems):
print "Found:", path
return True
for elem in self._deps[node]:
if elem not in visited_nodes:
visited_nodes.add(elem)
path.append(elem)
if self._dfs(elem, visited_nodes, path):
return True
path.pop()
visited_nodes.remove(elem)
return False
def dependencies_order(self):
if len(self._start_nodes) == 0:
return False
(elem, ) = self._start_nodes
path = [elem]
if self._dfs(elem, set(elem), path):
return tuple(path)
return False
import unittest
class TestBuilder(unittest.TestCase):
def test_dependencies_order(self):
bl = Builder((
('a', 'b'),
('b', 'c'),
('b', 'd'),
('c', 'd'),
))
self.assertEquals(bl.dependencies_order(), ('d' , 'c', 'b', 'a',))
bl = Builder((
('a', 'b'),
('b', 'a'),
('b', 'd'),
('c', 'd'),
))
self.assertFalse(bl.dependencies_order())
if __name__ == '__main__':
unittest.main()
|
def is_pal(str_to_check):
for i in xrange(len(str_to_check) / 2):
if str_to_check[i] != str_to_check[-(i+1)]:
return False
return True
print is_pal("hello")
print is_pal("romaamor")
print is_pal("romamor")
# Could be: Manacher's algorithm, but not... this is almost the same
def get_all_palindromes_string(string):
result = set()
for i in xrange(len(string)-1):
pp = 1
while i-pp >= 0 and i+pp < len(string) and string[i-pp] == string[i+pp]:
pp += 1
if pp > 1:
aux = string[i-pp+1:i+pp].strip()
if len(aux) > 1:
result.add(aux)
pp = 0
while i-pp >= 0 and i+pp+1 <= len(string) and string[i-pp] == string[i+pp+1]:
pp += 1
if pp > 0:
aux = string[i-pp+1:i+pp+1].strip()
if len(aux) > 1:
result.add(aux)
return result
print get_all_palindromes_string("thissi is a testtse casa perro or me sa")
print get_all_palindromes_string("t")
print get_all_palindromes_string("")
print get_all_palindromes_string("tt")
print get_all_palindromes_string("atat")
print get_all_palindromes_string("tata")
print get_all_palindromes_string("tatr")
print get_all_palindromes_string("rtat")
|
"""
Given a start position and an target position on the grid. You can move up,down,left,right from one node to another adjacent one on the grid. However there are some walls on the grid that you cannot pass. Now find the shortest path from the start to the target.
"""
from collections import defaultdict
class Game(object):
def __init__(self, grid):
self._grid = grid
def _is_possible_and_better(self, distances, f, t):
return (
t[0] >= 0 and t[0] < len(self._grid) and
t[1] >=0 and t[1] < len(self._grid[0]) and
self._grid[t[0]][t[1]] != 1 and
distances.get(t, float('inf')) > distances[f]+1)
def get_sortest_path(self, f, t):
stack = [f]
distances = defaultdict(int)
distances[f] = 0
while len(stack) > 0:
curr = stack.pop()
possible = (curr[0]-1, curr[1])
if self._is_possible_and_better(distances, curr, possible):
distances[possible] = distances[curr]+1
stack.append(possible)
possible = (curr[0]+1, curr[1])
if self._is_possible_and_better(distances, curr, possible):
distances[possible] = distances[curr]+1
stack.append(possible)
possible = (curr[0], curr[1]+1)
if self._is_possible_and_better(distances, curr, possible):
distances[possible] = distances[curr]+1
stack.append(possible)
possible = (curr[0], curr[1]-1)
if self._is_possible_and_better(distances, curr, possible):
distances[possible] = distances[curr]+1
stack.append(possible)
return distances.get(t, -1)
import unittest
class TestGame(unittest.TestCase):
def test_get_sortest_path(self):
gm = Game((
(0, 1, 0, 1, 0, 0),
(0, 1, 0, 1, 1, 0),
(0, 1, 0, 0, 0, 1),
(1, 0, 1, 1, 0, 0),
(0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0),
))
self.assertEqual(gm.get_sortest_path((0, 0), (2, 2)), -1)
self.assertEqual(gm.get_sortest_path((0, 0), (2, 0)), 2)
self.assertEqual(gm.get_sortest_path((0, 2), (5, 4)), 7)
if __name__ == '__main__':
unittest.main()
|
def intersec_sorted(arr1, arr2):
p1 = 0
p2 = 0
result = []
while p1 < len(arr1) and p2 < len(arr2):
if arr1[p1] == arr2[p2]:
result.append(arr1[p1])
p1 += 1
p2 += 1
elif arr1[p1] < arr2[p2]:
p1 += 1
else:
p2 += 1
return result
print intersec_sorted(
[1, 2, 4, 6],
[1, 2, 3, 4, 7, 9])
print intersec_sorted(
[1, 2, 3, 4, 5, 6],
[1, 2, 3, 4, 5, 6])
print intersec_sorted(
[],
[])
print intersec_sorted(
[],
[1, 2, 3, 4, 5, 6])
print intersec_sorted(
[1, 2, 4, 6],
[1, 3, 4, 7, 9])
|
"""
Given an arraylist of N integers,
(1) find a non-empty subset whose sum is a multiple of N.
(2) find a non-empty subset whose sum is a multiple of 2N.
Compare the solutions of the two questions.
"""
class IntArray(object):
def __init__(self, int_arr):
self._int_arr = int_arr
def sum_mult_n(self, n, subset=None):
if subset is None:
subset = self._int_arr
if sum(subset) == n:
return subset
for i in xrange(len(subset)):
aux_subset = subset[:i] + subset[i+1:]
sum_subset = self.sum_mult_n(n, aux_subset)
if sum_subset is not None:
return sum_subset
return None
import unittest
class TestIntArray(unittest.TestCase):
def test_sum_mult_n(self):
ia = IntArray([2, 3, 4, 6])
self.assertEqual(sum(ia.sum_mult_n(5)), 5)
ia = IntArray([])
self.assertEqual(ia.sum_mult_n(5), None)
ia = IntArray([1, 9])
self.assertEqual(ia.sum_mult_n(1), [1])
if __name__ == '__main__':
unittest.main()
|
fib = lambda x: x if x <= 1 else fib(x-1) + fib(x-2)
print fib(6)
class Fibonacci(object):
def __init__(self):
self.__cache = [1, 1]
def fib(self, pos):
pos -= 1
if pos >= len(self.__cache):
last_pos = len(self.__cache) - 1
while last_pos != pos:
last_pos += 1
self.__cache.append(self.__cache[last_pos-1] + self.__cache[last_pos-2])
return self.__cache[pos]
def fast_fib(self, n):
""" Solves the problem on O(log n) """
if n == 0:
return (0, 1)
a, b = self.fast_fib(n // 2)
c = a * (b * 2 - a)
d = a * a + b * b
if n % 2 == 0:
return (c, d)
return (d, c + d)
fib = Fibonacci()
print fib.fib(6)
print fib.fast_fib(6)[0]
|
import pandas as pd
import numpy as np
def create_data():
"""
This function loads price data from an Excel document.
WARNING : Pay attention to the Excel document's directory path and name.
:return: a DataFrame of the prices of the assets.
:rtype: DataFrame
"""
data = pd.read_excel(
"data/StatApp_Data.xlsx", sheet_name='Data', parse_dates=['Dates'], engine='openpyxl'
)
data = data[data.Dates != 'None']
data["Dates"] = pd.to_datetime(data.Dates, format="%Y-%m-%d %H:%M:%S")
return data.set_index("Dates")
def annualized_return(return_data, freq="daily"):
"""annualized return: inputs are frequency of data and return data"""
window = {"daily": 252, "monthly": 12, "weekly": 52}.get(freq, 252)
px_data = return_to_price_base100(return_data)
return (px_data.iloc[-1] / px_data.iloc[0]) ** (window / len(px_data - 1)) - 1
def volatility(return_data, freq="daily"):
vol = return_data.std()
if freq == "monthly":
return vol * np.sqrt(12)
elif freq == "weekly":
return vol * np.sqrt(52)
elif freq == "daily":
return vol * np.sqrt(252)
return vol
def downside_vol(return_data, freq="daily"):
vol_ = return_data.loc[return_data < 0].std()
if freq == "monthly":
return vol_ * np.sqrt(12)
elif freq == "weekly":
return vol_ * np.sqrt(52)
elif freq == "daily":
return vol_ * np.sqrt(252)
return vol_
def sharpe(return_data, freq="daily"):
return annualized_return(return_data, freq) / volatility(return_data, freq)
def sharpe_corrected(return_data, freq="daily"):
"""
The correction for the sharpe and calmar ratio gives the same if return is
positive than sharpe and calmar uncorrected; when return is negative it
corrects the ratio.
"""
ann_ret = annualized_return(return_data, freq)
sigma = volatility(return_data, freq)
sharpe = ann_ret / (sigma ** np.sign(ann_ret))
return sharpe
def sortino(return_data, freq="daily"):
return annualized_return(return_data, freq=freq) / downside_vol(return_data, freq=freq)
def calmar(return_data, freq="daily", freq_calmar="global"):
return annualized_return(return_data, freq=freq) / max_drawdown(return_data, freq=freq_calmar)
def max_drawdown(portfolio_value, freq="daily"):
window = {"daily": 252, "monthly": 12, "weekly": 52, "global": None}.get(freq, None)
if window is None:
roll_max = portfolio_value.cummax()
drawdown = portfolio_value / roll_max - 1.0
return drawdown.cummin().min()
else:
roll_max = portfolio_value.rolling(window, min_periods=1).max()
drawdown = portfolio_value / roll_max - 1.0
return drawdown.rolling(window, min_periods=1).min()
def return_to_price_base100(return_data):
"""
Works only if here is a pandas.nan in the first row, to fill it with with
0 and start with 100. Otherwise starts with 100*first
"""
return_data = return_data.copy()
return_data = return_data.fillna(0) + 1.0
return_data.iloc[0] *= 100
return return_data.cumprod()
def concentration_function(correlations):
"""
Function CF from ARB article where correlations is a numpy matrix of pairwise correlations
"""
n = len(correlations)
average_rho = ((correlations.sum() - 1) / (n - 1)).mean() # Exclude auto-correlation
return np.sqrt((1 + (n - 1) * average_rho) / n)
def implied_returns(weights, cov_matrix, risk_aversion=1):
"""
:param weights: weights of the portfolio for which
we want to compute implied returns
:type weights: numpy k*1 vector
:param cov_matrix: covariance of returns of the assets considered
:type cov_matrix: numpy k*k matrix
:param risk_aversion: risk aversion to use in MVO, defaults to 1
:return: k*1 numpy vector of implied returns
"""
return risk_aversion * cov_matrix @ weights
def implied_returns_df(weights_df, cov_matrices, risk_aversion=1):
"""
:param weights_df: weights of the portfolio over different dates
:type weights_df: data frame with dates as index,
and assets names as column names
:param cov_matrices: covariance of returns of the assets considered
over different dates
:type cov_matrices: data frame with dates as index, with a cov matrix at each date
:param risk_aversion: same as above
:return: a data frame consisting of the implied returns of the argument portfolio
for each date in the initial weights_df data frame
"""
returns = weights_df.copy(deep=True)
indices = weights_df.index.to_list()
for index in indices:
weights = weights_df.loc[index].to_numpy()
cov_matrix = cov_matrices.loc[index].to_numpy()
implied_return = implied_returns(weights, cov_matrix, risk_aversion)
returns.loc[index] = implied_return
return returns
def describe_stats(returns, freq="daily", verbose=False):
"""
:param Dataframe returns: returns
:param str freq: frequency
:param bool verbose: display parameter
:return: descriptive statistics on the portfolio performance
"""
portfolio_vol = volatility(returns, freq=freq)
portfolio_ann_returns = annualized_return(returns, freq=freq)
portfolio_sharpe = sharpe(returns, freq=freq)
portfolio_sortino = sortino(returns, freq=freq)
nav = (returns.fillna(0) + 1.0).cumprod()
max_dd = max_drawdown(nav, freq="global")
portfolio_calmar = calmar(returns, freq=freq, freq_calmar="global")
if verbose:
print(
f"----- Statistics -----\n"
f"Annualized Volatility : {portfolio_vol:.5f} \n"
f"Annualized Returns : {portfolio_ann_returns:.5f} \n"
f"Sharpe Ratio : {portfolio_sharpe:.5f} \n"
f"Maximum Drawdown : {max_dd:.5f} \n"
f"Sortino Ratio : {portfolio_sortino:.5f} \n"
f"Calmar Ratio : {portfolio_calmar:.5f} \n")
return {
"volatility": portfolio_vol,
"ann_returns": portfolio_ann_returns,
"sharpe_ratio": portfolio_sharpe,
"max_drawdown": max_dd,
"sortino": portfolio_sortino,
"calmar": portfolio_calmar,
}
if __name__ == '__main__':
data = create_data()
MSCI_word_return = data.loc[:, data.columns[0]].pct_change()
describe_stats(MSCI_word_return, verbose=True)
|
a={'Name':'Fatima'}
try:
with open('data.csv','w'):
pass
print('I am after open file')
print(a['Name'])
except KeyError:
print('This key does not exist in this ADT')
except FileNotFoundError as e:
print(e)
print('File does not exist')
except Exception:
print('This is unknown exception')
finally:
print('I am finally block!!')
print('Ennding') |
def add_something(x):
return x + 8
a = add_something(6)
#인자가 2개인 함수
def plus_two_times(a, b):
return a + b + b
c = plus_two_times(3, 4)
print(c)
#문자열을 인자로 받는 함수
def hello_someone(someone):
return 'Hello ~ ' + someone
print(hello_someone('조재성')) |
# To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %%
#Universidad Autónoma de Chihuahua
# Facultad de Ingeniería
# Sistemas de Búsqueda y Razonamiento
# Equipo:
# Carlos García
# Alejandro Aguirre
# Ericka Bermúdez
# referencias: https://www.educative.io/edpresso/how-to-implement-depth-first-search-in-python
# %%
graph = {
'A':['E','D','C', 'B'],
'B':['H','C','A'],
'C':['H','G','D','B','A'],
'D':['G','F','E', 'C', 'A'],
'E':['F','D','A'],
'F':['G','E', 'D', 'C'],
'G':['F', 'C'],
'H':['C', 'B']
}
# %%
import numpy as np
# %%
visited = []
queue = []
parents = {}
# %%
def subt(queue, visited):
for item in queue:
for item2 in visited:
if item == item2:
queue.remove(item)
return queue
# %%
def dfs(visited, graph, node, parent, goal):
print("-----------------------")
print("ACTUAL: ", node)
if node not in visited and node != goal:
visited.append(node)
for child in graph[node]:
if child not in visited and child not in queue:
queue.append(child)
parents[child] = node
nextItem = subt(queue, visited)
nextId = len(nextItem)-1
nextNode = nextItem[nextId]
print("ABIERTOS: ", queue)
print("CERRADOS: ", visited)
dfs(visited, graph, nextNode, node, goal)
# %%
#[parent, child]
parents['G']='G'
dfs(visited, graph, 'G', 'G', 'B')
visited.append('B')
# %%
visited
# %%
queue = queue[0:len(queue)-1]
queue
# %%
parents
# %%
def getPath(visited,parents):
path=[]
aux = visited[len(visited)-1]
while(aux != parents.get(aux)):
path.append(aux)
aux = parents.get(aux)
path.append(aux)
path.reverse()
print('El camino es:')
print(path)
getPath(visited,parents)
|
a, b = input().split()
print('Yes') if (int(a+b)**0.5).is_integer() == True else print('No')
|
A = int(input())
print((A // 2) ** 2 if A % 2 == 0 else A // 2 * (A // 2 + 1)) |
"""un/comment to de/activate ###########################
a = 10
b = 10
print( a == b )
print( a != b )
print( a > b )
print( a < b )
print( a >= b )
print( a <= b )
#######################################################"""
# """un/comment to de/activate ###########################
# evaluation / execution
# data types
# int, float
# bool
# str
# abstractions
# variables
# controll flow
# if, elif, else
# iteration
#######################################################"""
"""un/comment to de/activate ###########################
greeting = "Hello, "
name = "Clark"
cat_string = greeting + name
print( cat_string )
#######################################################"""
"""un/comment to de/activate ###########################
my_string = ""
my_string += "h"
my_string += "e"
my_string += "l"
my_string += "l"
my_string += "o"
print(my_string)
#######################################################"""
"""un/comment to de/activate ###########################
some_var = None
print( print("this is what I'm printing") )
# type()
# int()
# float()
# bool()
# str()
#######################################################"""
"""un/comment to de/activate ###########################
n = 12
m = 42
var = ((2 * n)**m)
print(var) # 9308338151941866618592771645958951941937449991757235224576
#######################################################"""
"""un/comment to de/activate ###########################
# x, y, z = 30, 40
# ValueError: not enough values to unpack (expected 3, got 2)
# x, y = 30, 40, 50
# ValueError: too many values to unpack (expected 2)
x, y, z = 30, 40, 20
print(x, y, z)
x = 30
y = 40
z = 20
#######################################################"""
"""un/comment to de/activate ###########################
print(True and True) # True
print(False and True) # False
print(True and False) # False
print(False and False) # False
print(True or True) # True
print(False or True) # True
print(True or False) # True
print(False or False) # False
print(not True) # False
print(not False) # True
print( not (True and True) ) # False
print( not (False and True) ) # True
print( not (True and False) ) # True
print( not (False and False) ) # True
print( not (True or True) ) # False
print( not (False or True) ) # False
print( not (True or False) ) # False
print( not (False or False) ) # True
print( not True and True ) # False
print( not False and True ) # True
print( not True and False ) # False
print( not False and False ) # False
#######################################################"""
"""un/comment to de/activate ###########################
(not (not (True or False) and (True and True))) and True or True
#######################################################"""
"""un/comment to de/activate ###########################
# ==
# !=
# >
# <
# >=
# <=
a = 3
b = 5
if a == b:
print("a is equal to b")
elif a != b:
print("a is not equal to b")
elif a > b:
print("a is greater than b")
else:
print("a is less than b")
# a is not equal to b
# a is less than b
print("fin")
#######################################################"""
"""un/comment to de/activate ###########################
'''
* Write a code snippet that checks two numbers, `x` and `y`:
* Check if the sum of two numbers is greater than both numbers
* If it is, print `"Both numbers are positive"`
* Check if the sum is equal to either number
* If it is, print `"At least one number is zero"`
* Otherwise, print `"At least one number is negative"`
'''
def code_snippet(x, y):
xy_sum = x + y
if xy_sum > x and xy_sum > y:
return "Both numbers are positive"
elif xy_sum == x or xy_sum == y:
return "At least one number is zero"
else:
return "At least one number is negative"
print(code_snippet(2, 3))
print(code_snippet(-2, 3))
print(code_snippet(2, -3))
print(code_snippet(-2, -3))
print(code_snippet(0, 3))
print(code_snippet(2, 0))
print(code_snippet(0, 0))
print(code_snippet(-2, 0))
print(code_snippet(0, -3))
#######################################################"""
"""un/comment to de/activate ###########################
x = int(input("input a value for x: "))
y = int(input("input a value for y: "))
if ((x + y) > x) and ((x + y) > y):
print("Both numbers are positive")
elif ((x + y) == x) or ((x + y) == y):
print("At least one number is zero")
else:
print("At least one number is negative")
#######################################################"""
|
"""un/comment to de/activate ###########################
# types
# int, float
# bool
# None
# str
# *tuples
# list
# dictionaries
# *sets
# abstraction
# variables
# functions
# control flow
# if elif else
# iteration
# for
# while
# map
text = '''
Whose woods these are I think I know
His house is in the village though
He will not see me stopping here
To watch his woods fill up with snow
'''
word_list = text.split()
word_list.append(57)
# print(word_list)
back_to_string = " ".join( map(str, word_list) )
print(back_to_string)
#######################################################"""
"""un/comment to de/activate ###########################
# mutable
# key/value pairs in a
# unordered
d = {
"make" : "toyota",
"modle": "highlander",
"color": "black",
"year" : 2011 }
# print( d["make"] ) # KeyError: 1
# print( d )
# for k, v in d.items():
# print(k, v)
# car2 = {
# "make" : "honda",
# "modle": "accord",
# "color": "red",
# "year" : 1994 }
#
# print( car2 )
# print( car1 )
#######################################################"""
"""un/comment to de/activate ###########################
# CRUD
# create
d = {}
d = {"make": "toyota"}
d["modle"] = "highlander" # equal to an append
# read / access
# d["make"]
# d["modle"]
print(d)
some_var = "make"
# if some_var in d.keys():
# print(d[some_var])
# else:
# print(some_var, "is not in the dictionary")
res = d.get(some_var, f"{some_var} is not in the dictionary")
print(res)
# update
d["modle"] = "huntsman"
# delete
# del d
# print(d) # NameError: name 'd' is not defined
# del d["modle"]
# print(d.pop("make"))
# print(d)
d = {
"make" : "toyota",
"modle": "highlander",
"color": "black",
"year" : 2011 }
#######################################################"""
"""un/comment to de/activate ###########################
d = {
"make" : "toyota",
"modle": "highlander",
"color": "black",
"year" : 2011 }
# print(d)
# membership
# .keys()
# .values()
# .items() # both keys and values
# .copy()
def remove_short_keys(d, key_lim):
d_copy = d.copy()
for k, v in d.items():
if len(k) <= key_lim:
del d_copy[k] # RuntimeError: dictionary changed size during iteration
return d_copy
some_d = {
"make" : "toyota" ,
"modle": "highlander" ,
"color": "black" ,
"year" : 2011 }
print( remove_short_keys(some_d, 4) )
print( some_d )
#######################################################"""
"""un/comment to de/activate ###########################
# tuples
# Tuples are ordered collections
# Tuples are very similar to list with two key differences:
# Tuples are immutable
# Tuples are declared using parenthesis
# We can index and slice tuples because they are ordered
# Tuples have two methods associated with them: count and index
tup = (55,)
print( tup )
#######################################################"""
"""un/comment to de/activate ###########################
# CSI
'append',
'extend',
tup = ()
# print( tup )
tup += ("hello",)
tup += ("world", "my", "name", "is", "foo")
# print( tup )
'clear',
tup = ()
'copy',
#
'count',
'index',
'insert',
tup = ('hello', 'world', 'my', 'name', 'is', 'foo')
idx = 1
tup = tup[:idx:] + ("there",) + tup[idx::]
'pop',
idx = 1
res = tup[idx]
tup = tup[:idx:] + tup[idx+1::]
print(tup)
'remove',
# idx = 1
ele = "world"
tup = tup[:tup.index("world"):] + tup[tup.index("world")+1::]
print(tup)
'reverse',
print(tup[::-1])
'sort'
# sorted()
#######################################################"""
"""un/comment to de/activate ###########################
# set([])
# .union()
# .intersection()
# .difference()
#######################################################"""
"""un/comment to de/activate ###########################
4 cell
64 gb ram
#######################################################"""
# """un/comment to de/activate ###########################
#######################################################"""
|
"""un/comment to de/activate ###########################
# len
# Input
# some collection ie a list or string or tuple
# Process
# Output
# int representing the lenght of the input
lst = [ 44, 33, 55, 44]
# list
# append
# pop
# len
# len(lst)
# sum
# sorted
# max
# min
# count
# lst.count(44)
# index
# enumerate
# zip
for idx, ele in enumerate(lst): pass
for a, b in zip(lst_a, lst_b): pass
#######################################################"""
"""un/comment to de/activate ###########################
def is_prime(n):
if n <= 1: return False
for i in range(2, int( n**(1/2) ) + 1):
if n % i == 0:
return False
return True
def next_prime(n):
while not is_prime(n + 1):
n += 1
return n + 1
for i in range(20):
print( i, next_prime(i) )
for _ in range(10_000_000):
print(_)
#######################################################"""
"""un/comment to de/activate ###########################
'''
Write a function that computes and returns a list of all of the divisors of some positive number.
Use a while loop. Things to think about:
How do you determine if a single number is a divisor of another?
What is your stopping condition?
BONUS: rewrite this with a for loop
'''
def factors_lst(n):
lst = []
i = 0
while True:
i += 1
if n % i == 0: lst.append(i)
if i >= n: break
return lst
print( factors_lst(24) )
#######################################################"""
"""un/comment to de/activate ###########################
selections = []
make_order = True
while make_order:
print('''Select from this list:
1 : bread
2 : butter
3 : potatoes
4 : broccoli''')
inp = int(input('please make a selection, 1-4: '))
if inp in [1,2,3,4]:
selections.append(inp)
else:
print('-- your selection was not understood --')
continue
inp2 = input('would you like to place another order? (y/n)')
if inp2 == 'y':
continue
else:
make_order = False
print(f'Your order list: {selections}')
#######################################################"""
"""un/comment to de/activate ###########################
''
""
'''
'''
# 235
# CSI
my_string = "hello"
# print( my_string )
my_string += " world"
# my_string = my_string + " world"
# print( my_string )
# print( my_string[4:9:] )
# print( my_string * 3 )
# membership
# print( "z" in my_string )
# case transforms
# res = my_string.upper() # "HELLO WORLD"
# print( my_string.upper() ) # hello world
# print( my_string ) # hello world
# my_string = "hello. world"
# print( my_string.capitalize() )
my_string = "HELlO WoRlD"
# print( my_string.lower() )
# my_string = "something"
# count
# print(my_string.lower().count("l"))
# replace
# my_string = "hello world"
# res = my_string.replace("lo w", "<HEY>")
# print( res )
# casting
# print( [str([8, 7,2 ,3])] )
# methods # dir
# list / split / join
# my_string = "hello. world"
# print( list(my_string) )
# splt_string = my_string.split()
text = '''
Whose woods these are? I think I know.
His house is in the village though;
He will not see me stopping here
To watch his woods fill up with snow.
'''
# for sentance in text.replace("?", ".").replace(";", ".").split("."):
# print(sentance)
words_lst = text.split()
words_lst.append(57)
words_str = " ".join( map(str, words_lst) )
# TypeError: sequence item 30: expected str instance, int found
print(words_str)
# enumerate
#######################################################"""
# """un/comment to de/activate ###########################
#######################################################"""
# """un/comment to de/activate ###########################
#######################################################"""
|
import numpy as np
xa_high = np.loadtxt('data/xa_high_food.csv', comments='#')
xa_low = np.loadtxt('data/xa_low_food.csv', comments='#')
def xa_to_diameter(xa):
"""
Convert an array of cross_sectional areas to diameters with commuensurate units
"""
# Compute diameter from area
# A = pi * d^2 / 4
diameter = np.sqrt(xa * 4 / np.pi)
return diameter
A = np.array([[6.7, 1.3, 0.6, 0.7],
[0.1, 5.5, 0.4, 2.4],
[1.1, 0.8, 4.5, 1.7],
[0.0, 1.5, 3.4, 7.3]])
b = np.array([1.3, 2.3, 3.3, 3.9])
# Print row 1 of A
# Print columns 1 and 3 of A
# Print the values of every entry in A that is Great Than 2
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fileencoding=utf-8
from array import array
alph = list('абвгдежзийклмнопрстуфхцчшщъыьэюя')
new_alph = list()
keyword = list(str(input('Введите ключевое слово:\n')))
text = list(str(input('Введите текст:\n')))
b=-1
new_text=list()
my_keyword=list()
for i in keyword:
if i not in my_keyword:
my_keyword.append(i)
for i in alph:
if i not in keyword:
new_alph.append(i)
new_alph = my_keyword + new_alph
new_alph2= new_alph + new_alph
print(new_alph2)
print(new_alph)
for i in text:
b+=1
if i in new_alph:
a=-1
for r in new_alph:
a+=1
if r==i:
text[b]=new_alph2[a+8]
print(text)
|
# FILL TABLES THAT ALREADY CREATED IN SQL
# setup
from __future__ import unicode_literals
import sqlite3
import csv
connection = None
cursor = None
cursor2 = None
tab_delimited_file = None
tweet_reader = None
tweet_counter = -1
field_count = -1
current_tweet_row = None
# variables to hold fields
tweet_timestamp = ""
twitter_tweet_id = ""
tweet_text = ""
tweet_language = ""
twitter_user_twitter_id = ""
twitter_user_screenname = ""
user_followers_count = ""
user_favorites_count = ""
user_created = ""
user_location = ""
tweet_retweet_count = ""
tweet_place = ""
tweet_user_mention_count = ""
tweet_users_mentioned_screennames = ""
tweet_users_mentioned_ids = ""
tweet_hashtag_mention_count = ""
tweet_hashtags_mentioned = ""
tweet_url_count = ""
tweet_shortened_urls_mentioned = ""
tweet_full_urls_mentioned = ""
user_description = ""
user_friends_count = ""
user_statuses_count = ""
tweet_display_urls_mentioned = ""
# build INSERT statement
sql_insert_string = ""
#start try-except-finally
try:
#connect to database
connection = sqlite3.connect( "tweet_sample.sqlite" )
# set row_factory that returns values mapped to column names as well as list
connection.row_factory = sqlite3.Row
#make cursors
cursor = connection.cursor()
cursor2 = connection.cursor()
##############################READ IN BIG FILE############################################
# open the data file for reading.
with open( 'tweet_sample.txt', 'rb' ) as tab_delimited_file:
# feed the file to csv.reader to parse.
tweet_reader = csv.reader( tab_delimited_file, dialect = "excel-tab" )
delimiter = '\t', quotechar = '\"', strict = True, lineterminator = "\n" )
# loop over logical rows in the file.
tweet_counter = 0
for current_tweet_row in tweet_reader:
tweet_counter = tweet_counter + 1
field_count = len( current_tweet_row )
# print some info
print( "====> line " + str( tweet_counter ) + " - " + str( field_count ) + " fields - text: " + '|||'.join( current_tweet_row ) )
# only do stuff after first row
if ( tweet_counter > 1 ):
# get fields
tweet_timestamp = unicode( current_tweet_row[ 0 ], "UTF-8" )
twitter_tweet_id = unicode( current_tweet_row[ 1 ], "UTF-8" )
tweet_text = unicode( current_tweet_row[ 2 ], "UTF-8" )
tweet_language = unicode( current_tweet_row[ 3 ], "UTF-8" )
twitter_user_twitter_id = int( current_tweet_row[ 4 ] )
twitter_user_screenname = unicode( current_tweet_row[ 5 ], "UTF-8" )
user_followers_count = int( current_tweet_row[ 6 ] )
user_favorites_count = int ( current_tweet_row[ 7 ] )
user_created = unicode( current_tweet_row[ 8 ], "UTF-8" )
user_location = unicode( current_tweet_row[ 9 ], "UTF-8" )
tweet_retweet_count = int( current_tweet_row[ 10 ] )
tweet_place = unicode( current_tweet_row[ 11 ], "UTF-8" )
tweet_user_mention_count = unicode( current_tweet_row[ 12 ], "UTF-8" )
tweet_users_mentioned_screennames = unicode( current_tweet_row[ 13 ], "UTF-8" )
tweet_users_mentioned_ids = unicode( current_tweet_row[ 14 ], "UTF-8" )
tweet_hashtag_mention_count = unicode( current_tweet_row[ 15 ], "UTF-8" )
tweet_hashtags_mentioned = unicode( current_tweet_row[ 16 ], "UTF-8" )
tweet_url_count = unicode( current_tweet_row[ 17 ], "UTF-8" )
tweet_shortened_urls_mentioned = unicode( current_tweet_row[ 18 ], "UTF-8" )
tweet_full_urls_mentioned = unicode( current_tweet_row[ 19 ], "UTF-8" )
user_description = unicode( current_tweet_row[ 20 ], "UTF-8" )
user_friends_count = int( current_tweet_row[ 21 ] )
user_statuses_count = int( current_tweet_row[ 22 ] )
tweet_display_urls_mentioned = unicode( current_tweet_row[ 23 ], "UTF-8" )
# print tweet ID
print ( "====> line " + str( tweet_counter ) + " - " + str( field_count ) +# " Twitter Tweet ID = " + twitter_tweet_id )
# build INSERT statement
sql_insert_string = '''
INSERT INTO tweet_sample_raw
(
tweet_timestamp,
twitter_tweet_id,
tweet_text,
tweet_language,
twitter_user_twitter_id,
twitter_user_screenname,
user_followers_count,
user_favorites_count,
user_created,
user_location,
tweet_retweet_count,
tweet_place,
tweet_user_mention_count,
tweet_users_mentioned_screennames,
tweet_users_mentioned_ids,
tweet_hashtag_mention_count,
tweet_hashtags_mentioned,
tweet_url_count,
tweet_shortened_urls_mentioned,
tweet_full_urls_mentioned,
user_description,
user_friends_count,
user_statuses_count,
tweet_display_urls_mentioned
)
VALUES
(
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?
)
'''
# execute the command.
cursor.execute( sql_insert_string, ( tweet_timestamp, twitter_tweet_id, tweet_text, tweet_language, twitter_user_twitter_id, twitter_user_screenname, user_followers_count, user_favorites_count, user_created, user_location, tweet_retweet_count, tweet_place, tweet_user_mention_count, tweet_users_mentioned_screennames, tweet_users_mentioned_ids, tweet_hashtag_mention_count, tweet_hashtags_mentioned, tweet_url_count, tweet_shortened_urls_mentioned, tweet_full_urls_mentioned, user_description, user_friends_count, user_statuses_count, tweet_display_urls_mentioned ) )
# commit.
connection.commit()
#-- END check to make sure we aren't the first row. --#
#-- END loop over rows in file --#
#-- END use of tab_delimited_file --#
#############################FILL USER TABLE############################
#declare variables
user_set = None
current_row = None
sql_insert_user = ""
user_set = cursor.execute(
'''
SELECT
twitter_user_twitter_id,
twitter_user_screenname,
user_followers_count,
user_favorites_count,
user_created,
user_location,
user_description,
user_friends_count,
user_statuses_count
FROM tweet_sample_raw
''')
unique_users = []
#loop through rows
for current_row in user_set:
if current_row[0] not in unique_users:
unique_users.append(current_row[0])
sql_insert_user = '''
INSERT INTO User (
twitter_user_twitter_id,
twitter_user_screenname,
user_followers_count,
user_favorites_count,
user_created,
user_location,
user_description,
user_friends_count,
user_statuses_count
)
VALUES (?,?,?,?,?,?,?,?,?);
'''
#execute insert function
cursor2.execute(sql_insert_user,(current_row[0], current_row[1], current_row[2],
current_row[3], current_row[4],current_row[5], current_row[6], current_row[7],
current_row[8]))
# get ID of each record.
new_user_id = cursor2.lastrowid
# output result
print("New record inserted with ID = " + str(new_user_id))
#commit
connection.commit()
else:
pass
#end loop
############################FILL TWEET TABLE##########################
#declare variables
tweet_set = None
current_row = None
sql_insert_tweet = ""
#SELECT statement
tweet_set = cursor.execute(
'''
SELECT
twitter_user_twitter_id,
tweet_timestamp,
twitter_tweet_id,
tweet_text,
tweet_language,
tweet_retweet_count,
tweet_place,
tweet_user_mention_count,
tweet_hashtag_mention_count,
tweet_url_count
FROM tweet_sample_raw
''')
#loop through columns
for current_row in tweet_set:
#INSERT statement
sql_insert_tweet = '''
INSERT INTO Tweet (twitter_user_twitter_id,
tweet_timestamp,
twitter_tweet_id,
tweet_text,
tweet_language,
tweet_retweet_count,
tweet_place,
tweet_user_mention_count,
tweet_hashtag_mention_count,
tweet_url_count
)
VALUES (?,?,?,?,?,?,?,?,?,?);
'''
#execute insert function
cursor2.execute(sql_insert_tweet,(current_row[0], current_row[1], current_row[2],
current_row[3], current_row[4], current_row[5], current_row[6], current_row[7],
current_row[8], current_row[9]))
# get ID of each record.
new_tweet_id = cursor2.lastrowid
# output result
print("New record inserted with ID = " + str(new_tweet_id))
print current_row[0]
#commit
connection.commit()
#END LOOP
#######################################FILL IN HASHTAG TABLE###########################
#declare variables
hashtag_set = None
current_row = None
sql_insert_hashtag = ""
hashtag_list = []
unique_hashtags = []
#SELECT statement
hashtag_set = cursor.execute(
'''
SELECT tweet_hashtags_mentioned
FROM tweet_sample_raw
WHERE tweet_hashtags_mentioned !='';
''')
#INSERT function
sql_insert_hashtag = '''
INSERT INTO Hashtag
(hashtag_text)
VALUES (?);
'''
#loop over rows of hashags
for current_row in hashtag_set:
#split list
hashtag_list = current_row[0].split(",")
#loop through split hashtags
for hashtag in hashtag_list:
#check if we already have this hashtag
if hashtag not in unique_hashtags:
#add to list
unique_hashtags.append(hashtag)
#execute insert function
cursor2.execute(sql_insert_hashtag,(hashtag,))
#check whether it worked
new_hashtag_id = cursor2.lastrowid
# output result
print("New record inserted with ID = " + str(new_hashtag_id))
#commit
connection.commit()
#if already in list tell me it's there
else:
print("got this one already")
#end check
#end loop
#end loop
#######################################FILL IN URL TABLE###########################
#declare variables
full_url_set = None
current_row = None
sql_insert_full_url = ""
full_url_list = []
unique_full_urls = []
#SELECT statement
full_url_set = cursor.execute(
'''
SELECT tweet_full_urls_mentioned
FROM tweet_sample_raw
WHERE tweet_full_urls_mentioned !='';
''')
#INSERT function
sql_insert_full_url = '''
INSERT INTO URL
(full_url)
VALUES (?);
'''
#loop over rows of urls
for current_row in full_url_set:
#split list
full_url_list = current_row[0].split(",")
#loop through split urls
for url in full_url_list:
#check if we already have this url
if url not in unique_full_urls:
#add to list
unique_full_urls.append(url)
#execute insert function
cursor2.execute(sql_insert_full_url,(url,))
#check whether it worked
new_url_id = cursor2.lastrowid
# output result
print("New record inserted with ID = " + str(new_url_id))
#commit
connection.commit()
#if already in list print message
else:
print ("got this one already")
#end check
#end loop
#end loop
except Exception as e:
print( "exception: " + str( e ) )
finally:
#check it finished
print( "Done" )
# close cursor
cursor.close()
cursor2.close()
# close connection
connection.close()
#-- END try-->except-->finally around database access. --# |
import math
def is_prime(x):
if x <= 1:
return False
if x <= 3:
return True
i = 2
while (i <= math.sqrt(x)):
if (x % i == 0):
return False
i+= 1
return True
def main():
count = 0
index = 0
primes = list()
while (index < 10001):
if is_prime(count):
primes.append(count)
index += 1
print(index)
count += 1
print(primes[10000])
main()
|
#program to resize the image
import cv2
img = cv2.imread("image.png")
#resize the image using row and column values
newImage = cv2.resize(img, (550, 350))
#display the image
cv2.imshow('Resized Image', newImage)
cv2.waitKey(0)
|
# Word Genetic Algorithm [init, points, selection, crossover, mutation]
# Point Granting
# correct letter 1 points
# correct letter in posistion 2 points
# correct length 4 points
# word properties
# - length
# - letters
import string
import random
# Properties
target_word = "to be or not to be"
showEvery = 5
PopulationSize = 50
minLength = len(target_word)
maxLength = len(target_word)
mutationRate = 10 # / 100 %
usable_chars = 'abcdefghijklmnopqrstuvwxyz '
last_generation = []
current_generation = []
nGeneration = 0
def initPop():
global last_generation
pop = PopulationSize
while pop > 0:
last_generation.append( generateWord(random.randint(minLength, maxLength)) )
pop -= 1
def generateWord(length):
global usable_chars
l = usable_chars
cLength = 0
rWord = ""
while cLength < length:
rWord += random.choice(l)
cLength += 1
return rWord
def pointGranting(word):
points = 0
#if len(word) == len(target_word):
# points += 3
for tl in target_word:
for wl in word:
if tl == wl:
points += 1
for l in target_word:
points = points - ( word.count(l) - target_word.count(l) )
cl = 0
for tl in target_word:
if cl < len(word):
if tl == word[cl]:
points += 2
cl += 1
return points
def selection(): #selection of the best (half the population)
global last_generation
halfbest = []
bestscore = pointGranting(target_word)+1
while len(halfbest) < PopulationSize/2:
ch = False
for i in last_generation:
if bestscore < pointGranting(i):
halfbest.append(i)
last_generation.remove(i)
bestscore = pointGranting(i)
ch = True
#print("choose " + i + " with p " + str(pointGranting(i)))
if(ch == False):
bestscore -= 1
#print(last_)
last_generation = halfbest #purge
#print(halfbest)
def crossover(p1, p2):
if len(p1) > len(p2): # finding out the shorter word
pl = p2
else:
pl = p1
if len(p1) > 2:
crossover_point = random.randint(1, len(pl)-1)
else:
crossover_point = 1
crossover = p1[:crossover_point]+p2[crossover_point:]
#print("("+str(crossover_point)+"): "+p1+"+"+p2+" = "+crossover)
return crossover
def repopulation(): # doubling popualtion
global last_generation
for i in last_generation:
nK = 0
while nK < 2:
partner = last_generation[ random.randint(0, len(last_generation)-1) ]
current_generation.append( crossover(i, partner) )
nK += 1
def mutation():
global current_generation
global usable_chars
ci = 0
for i in current_generation:
#rnd = random.randint(0, 100)
#if rnd < mutationRate:
# if random.choice([True, False]):
# current_generation[ci] = i + random.choice( string.ascii_letters.lower() )
# else:
# if (len(i)-1 > minLength):
# current_generation[ci] = i[:-1]
rnd = random.randint(0, 100)
if rnd < mutationRate:
ri = list(i)
ri[ random.randint(0, len(i)-1 ) ] = random.choice( usable_chars )
current_generation[ci] = ''.join(ri)
#print("mutated")
ci += 1
print("\n - Word Genetic Algorithm -\n by Vox"+"\n"*2)
initPop()
target_word = target_word.lower()
while 1:
bestWord = ""
for w in last_generation:
if pointGranting(bestWord) < pointGranting(w):
bestWord = w
#for l in last_generation:
# print(l)
# print(pointGranting(l))
# print("\n")
if (nGeneration % showEvery) == 0:
print("Generation: "+str(nGeneration))
print("Current Generations best: '" + bestWord + "' with a score of "+str(pointGranting(bestWord))+" / "+str(pointGranting(target_word)) )
inc = input(": next generations ?\n")
if inc == "show":
print(last_generation)
input("-\n")
selection()
repopulation()
mutation()
last_generation = current_generation
current_generation = []
nGeneration += 1
|
#An apparel shop wants to manage the items which it sells
#OOPR-Assgn-24
#Start writing your code here
class Apparel:
counter = 100
def __init__(self,price,item_type):
Apparel.counter+=1
self.__item_id=item_type[0].upper()+str(Apparel.counter)
self.__price = price
self.__item_type = item_type
def calculate_price(self):
self.__price= self.__price + 5/100*self.__price
def get_item_id(self):
return self.__item_id
def get_price(self):
return self.__price
def get_item_type(self):
return self.__item_type
def set_price(self,price):
self.__price = price
class Cotton(Apparel):
def __init__(self,price,discount):
Apparel.__init__(self,price,'cotton')
self.__discount = discount
def calculate_price(self):
super().calculate_price()
price = Apparel.get_price(self)
price = price - (self.__discount/100)*price
price = price + (5/100)*price
Apparel.set_price(self, price)
def get_discount(self):
return self.__discount
class Silk(Apparel):
def __init__(self,price):
Apparel.__init__(self,price,'silk')
self.__points = 0
def calculate_price(self):
super().calculate_price()
price = Apparel.get_price(self)
if(price>10000):
self.__points += 10
else:
self.__points += 3
price = price + (10/100)*price
Apparel.set_price(self,price)
def get_points(self):
return self.__points
c1 = Cotton(2000,4)
c1.calculate_price()
|
# This application renames files based on a user input directory, word that needs to be changed, and word that it will be changed to.
# It also has optional capabilities to add a date stamp to a .txt file that has been renamed
import os
import datetime as dt
def file_renamer(path, original, new, datestamp = False):
'''This accepts a filepath, a string that the user wants changed, and the new string that will be changed to.'''
'''It also has an optional datestamp functionality that will add an edited on Timestamp for any .txt file that needs renaming'''
# changes the path that python is looking at
os.chdir(path)
# creating flags that will tell us whether or not there were any files or any files that needed renaming
flag1, flag2 = 0, 0
# walk through each file in the folder
for file in os.listdir(path):
# check if the file is actually a file and not a directory
if os.path.isfile(file):
#setting flag1 means there are actual files in directory
flag1 = 1
#checking to see if file needs renaming
if original in file:
os.rename(file, file.replace(original, new))
flag2 = 1
#checking if the datestamp functionality was passed and will only pass to txt files
if datestamp and (file[-4:] == '.txt'):
# opening that ALREADY RENAMED text file and stamping it and then closing it
text_file = open(file.replace(original, new), "a") #using 'a' file access mode means it will append to that text file - and not overwrite the old stuff
text_file.write("\n\n\n\n\nEdited on " + str(dt.date.today()) + "\n")
text_file.close()
#using the flags to tell the user if there were any errors or not in the process
if not flag1:
return 'There are no files in this directory.'
elif not flag2:
return 'There were no files that required renaiming based on your parameters.'
else:
return 'All files renamed!'
# ----------------------- #
# main
# ----------------------- #
while True:
#ask user for directory input or if user wants to exit
path = str(input('What directory would you like your files renamed? (or type EXIT): '))
if path.upper() == 'EXIT':
print('Goodbye.')
break
#checks if directory is valid, then asks user for text to be changed and text to be changed to
elif os.path.isdir(path):
original = input('What text string would you like changed? ')
new = input('What would you like the text string to be changed to? ')
#checks if user wants to add a datestamp or not to .txt files
refer = {'Y':True, 'N':False}
datestamp = refer.get(input('Would you like a datestamp to be placed on all .txt files? (Y or N): ').upper(), 'N')
#running the function
print(file_renamer(path, original, new, datestamp))
break
else:
print('Invalid Path.')
# ----------------------------- #
# Test Code:
# ----------------------------- #
# home = os.getcwd()
# path = os.path.join(home, 'Test Rename')
# original = '(draft)'
# new = '(final)'
# datestamp = True
# print(file_renamer(path, original, new, datestamp))
|
a = input()
b = input()
def similar(a, b):
if len(a)-1 != len(b):
return False
offset = 0
for bindex in range(len(b)):
if a[bindex + offset] != b[bindex]:
if offset == 0:
offset += 1
else:
return False
return True
print('TAK' if similar(a, b) else 'NIE')
|
height = int(input())
n = int(input())
for segment in range(0, n):
for i in range(1, height+1):
print(' '.join(['*'] * i))
height += 1 |
n = int(input())
word = ''
for i in range(n):
word += input()[i]
print(word) |
from typing import Optional
from githubmarkdownui.constants import HEADING_MAX_LEVEL, HEADING_MIN_LEVEL
def thematic_break() -> str:
"""Returns a <hr> tag, used to create a thematic break. Equivalent to --- in Markdown."""
return '<hr>'
def code_block(text: str, language: Optional[str] = None) -> str:
"""Creates a code block using HTML syntax. If language is given, then the code block will be
created using Markdown syntax, but it cannot be used inside a table.
:param text: The text inside the code block
:param language: The language to use for syntax highlighting
"""
if language:
return f'```{language}\n{text}\n```'
return f'<pre><code>{text}</code></pre>'
def heading(text: str, level: int) -> str:
"""Returns a heading with the given text, by wrapping the text with a corresponding <h1> to <h6> tag. 1 is the biggest
heading while 6 is the smallest heading. The level must be between 1 and 6 inclusive.
:param text: The text for the heading
:param level: The level of the heading between 1 and 6 inclusive
:raises: Exception if the level is not between 1 and 6 inclusive
"""
if not HEADING_MIN_LEVEL <= level <= HEADING_MAX_LEVEL:
raise Exception(f'Level must be between {HEADING_MIN_LEVEL} and {HEADING_MAX_LEVEL} inclusive')
return f'<h{level}>{text}</h{level}>'
|
def bold(text: str) -> str:
"""Alternative name for strong_emphasis.
:param text: The text to be bolded
"""
return strong_emphasis(text)
def code_span(text: str) -> str:
"""Returns the text surrounded by <code> tags.
:param text: The text that should appear as a code span
"""
return f'<code>{text}</code>'
def emphasis(text: str) -> str:
"""Emphasizes (italicizes) the given text by placing <em> tags around it.
:param text: The text to be emphasized
"""
return f'<em>{text}</em>'
def italics(text: str) -> str:
"""Alternative name for emphasis.
:param text: The text to be italicized
"""
return emphasis(text)
def link(text: str, url: str) -> str:
"""Turns the given text into a link using <a> tags.
:param text: The text for the link
:param url: The url for the link
"""
return f'<a href="{url}">{text}</a>'
def strikethrough(text: str) -> str:
"""Formats the text with a strikethrough by placing <del> tags around it.
:param text: The text to appear with a strikethrough
"""
return f'<del>{text}</del>'
def strong_emphasis(text: str) -> str:
"""Strongly emphasizes (bolds) the given text by placing <strong> tags around it.
:param text: The text to be strongly emphasized
"""
return f'<strong>{text}</strong>'
|
'''
Problem
Either strand of a DNA double helix can serve as the coding strand for RNA transcription. Hence, a given DNA string implies six total reading frames, or ways in which the same region of DNA can be translated into amino acids: three reading frames result from reading the string itself, whereas three more result from reading its reverse complement.
An open reading frame (ORF) is one which starts from the start codon and ends by stop codon, without any other stop codons in between. Thus, a candidate protein string is derived by translating an open reading frame into amino acids until a stop codon is reached.
Given: A DNA string s of length at most 1 kbp in FASTA format.
Return: Every distinct candidate protein string that can be translated from ORFs of s. Strings can be returned in any order.
Sample Dataset
>Rosalind_99
AGCCATGTAGCTAACTCAGGTTACATGGGGATGACCCCGCGACTTGGATTAGAGTCTCTTTTGGAATAAGCCTGAATGATCCGAGTAGCATCTCAG
Sample Output
MLLGSFRLIPKETLIQVAGSSPCNLS
M
MGMTPRLGLESLLE
MTPRLGLESLLE
'''
#function to take DNA sequence string and return the reverse complement
def DNAreverse_complement(dna_seq):
return dna_seq.translate(str.maketrans('ATGCN','TACGN'))[::-1]
#compact codon table and translate function by Gaik Tamazian from Rosalind
def translate(dna_seq):
codon_table = 'KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSS*CWCLFLF'
nucleo = {'A': 0, 'C': 1, 'G': 2, 'T': 3}
protein = ''
for i in range(0, len(dna_seq), 3):
protein+=codon_table[nucleo[dna_seq[i]]*16 + nucleo[dna_seq[i+1]]*4 + nucleo[dna_seq[i+2]]]
return protein
#trim translated protein sequence from Start(Met) to Stop(*) codon; first find all 'M' position and trim sequence to first '*' found in each case
def trim_orf(prot_seq):
orfs_in_seq=[]
start_pos=[index for index,aa in enumerate(prot_seq) if aa=='M']
for start in start_pos:
end=prot_seq[start:].find('*')
if end!=-1:
orfs_in_seq.append(prot_seq[start:end+start])
return orfs_in_seq
#interate through all 3 open reading frames of forward and reverse sequence; be sure to choose endpoint as mod 3 to avoid error, and extend the list of translated open reading frame
def list_all_orfs(dna_seq):
orfs=[]
for seq in [dna_seq,DNAreverse_complement(dna_seq)]:
for i in range(0,3):
endpoint=len(seq)-len(seq[i:])%3
cur_orf=trim_orf(translate(seq[i:endpoint]))
orfs.extend(cur_orf)
return list(dict.fromkeys(orfs)) #remove duplicate sequences and maintain order
#write results to txt file
def write_result(result_list, filename):
with open(filename,'w+') as file:
for seq in result_list:
file.write(seq+'\n')
#read rosalind download txt input and output results in txt
def read_then_write(inputfile):
with open(inputfile,'r') as file:
DNA_seq=''.join(file.read().split('\n')[1:])
results=list_all_orfs(DNA_seq)
write_result(results,inputfile.replace('.txt','')+'_results.txt')
#read_then_write('open_reading_frame/rosalind_orf.txt')
#==============USER_SOLUTIONS==============
def revcomp(s):
r = s.translate(str.maketrans('ACTG','TGAC'))
return r[::-1]
dna = "AGCCATGTAGCTAACTCAGGTTACATGGGGATGACCCCGCGACTTGGATTAGAGTCTCTTTTGGAATAAGCCTGAATGATCCGAGTAGCATCTCAG"
table = """
TTT F CTT L ATT I GTT V
TTC F CTC L ATC I GTC V
TTA L CTA L ATA I GTA V
TTG L CTG L ATG M GTG V
TCT S CCT P ACT T GCT A
TCC S CCC P ACC T GCC A
TCA S CCA P ACA T GCA A
TCG S CCG P ACG T GCG A
TAT Y CAT H AAT N GAT D
TAC Y CAC H AAC N GAC D
TAA Stop CAA Q AAA K GAA E
TAG Stop CAG Q AAG K GAG E
TGT C CGT R AGT S GGT G
TGC C CGC R AGC S GGC G
TGA Stop CGA R AGA R GGA G
TGG W CGG R AGG R GGG G"""
table = dict(zip(table.split()[::2],table.split()[1::2]))
stop = ["TAA","TAG","TGA"]
proteins = []
for s in [dna,revcomp(dna)]:
for i in range(len(s)):
if s[i:i+3] == "ATG":
for j in range(i,len(s),3):
if s[j:j+3] in stop:
c = [s[k:k+3] for k in range(i,j,3)]
proteins.append( ''.join(map(lambda x:table[x],c)) )
break
for seq in set(proteins):
print(seq)
|
def reversecomplement(s):
nucl_replace={'A':'T','T':'A','C':'G','G':'C'}
revcom=''
for nucl in s.strip('\n')[::-1]:
revcom = revcom + nucl_replace[nucl]
return revcom
with open('rosalind_revc.txt') as file:
DNAsequence = file.read()
fh=open('rosalind_revc_output.txt', 'w+')
fh.write(reversecomplement(DNAsequence))
fh.close()
#Look faster
#from string import maketrans
#s = 'AAAACCCGGT'
#print(s[::-1].translate(maketrans('ACGT', 'TGCA')))
#s = 'AAAACCCGGT'
#print(s[::-1].translate(str.maketrans('ACGT', 'TGCA')))
#loop for mulitple characters replacement, in successive order
#def replace_all(str, dict):
#for i, j in dict.iteritems():
#str = str.replace(i,j)
#return str
#$ cat rosalind2.txt | tr 'ACGT' 'TGCA' | rev |
def Fibonacci(n,k):
F1=0
F2=1
if n==0:
return F1
elif n==1:
return F2
else:
for i in range(1,n):
Fib=F2 + k*F1
F1=F2
F2=Fib
return Fib
print(Fibonacci(50,3))
with open('Fibonacci/rosalind_fib.txt', 'r') as file:
value=list(map(int,file.read().split()))
fh=open('Fiboancci/rosalind_fib_output.txt','w+')
fh.write(str(Fibonacci(value[0],value[1])))
fh.close()
|
class MOD(object):
""" A Class for any MOD Statements in the Assembly Code """
def __init__(self, code, memory, cpu):
self.code = code
self.opcode = code[0: 3]
self.operand = code[3: len(self.code)].replace(" ", "").split(",")
self.value = self.getValue(memory)
self.targetReg = self.getRegister()
self.updateReg(cpu)
cpu.programCounter += 1
def getValue(self, memory):
if self.operand[1][0] == "#":
value = self.operand[1][1: len(self.operand)+1]
return value
else:
value = memory.getData(self.operand[1][0])
def getRegister(self):
register = int(self.operand[0][1])
return register
def updateReg(self, cpu):
cpu.registers[self.targetReg-1] = str(self.value) |
#!/usr/bin/env python
# coding: utf-8
# # Algoritmos Computacionais em Grafos - Trabalho Final
#
# **PUC Minas**
#
# **Engenharia de Software**
#
# **Prof Joyce Christina de Paiva Carvalho**
#
# * Bruno Armanelli
# * Douglas Domingues
# * Henrique Freire
# * Luiz Antunes
# ## 0) Imports
#
# A grande parte do código é python nativo.
#
# Para apenas um detalhe foi usado numpy, ao ler a matriz de dissimilaridade.
#
# A biblioteca igraph foi usada ao final para visualizar os grafos.
# In[381]:
from igraph import *
import numpy as np
# ## 1) Classes
#
# #### Aluno
# Os alunos são os vértices dos grafos. Possuem código de aluno e área de pesquisa. São lidos a partir do arquivo 'Aluno_Area_Pesquisa.txt'
#
# #### Arestas
# As arestas possuem aluno1 e aluno2, correspondendo aos alunos que conectam, e o peso. As arestas são colocadas entre os alunos mais próximos em um grupo automaticamente na inserção.
#
# #### Grafo
# O grafo contem uma lista de Aluno e uma lista de Aresta. Nele estão as operações de adição de vértice (aluno), o número de alunos e o cálculo do grau de diferença.
# In[382]:
class Aluno(object):
def __init__(self, codigo, area):
self.codigo_aluno = codigo
self.area_pesquisa = area
def __repr__(self):
to_string = "\nCódigo Aluno: " + str(self.codigo_aluno)
to_string += ", Área de Pesquisa: " + str(self.area_pesquisa)
return to_string
# In[383]:
class Aresta(object):
def __init__(self, aluno1, aluno2, peso):
self.aluno1 = aluno1
self.aluno2 = aluno2
self.peso = peso
def __repr__(self):
to_string = '\n('+str(self.aluno1.codigo_aluno)+', '
to_string += str(self.aluno2.codigo_aluno)+', '
to_string += str(self.peso)+')'
return to_string
# In[384]:
class Grafo(object):
vertices = []
arestas = []
def __init__(self, vertices, arestas):
self.vertices = vertices
self.arestas = arestas
def add(self, aluno):
mais_prox = self.vertices[0]
dist_min = dist_aluno(aluno, mais_prox)
for v in self.vertices:
dist = dist_aluno(aluno, v)
if dist < dist_min:
dist_min = dist
mais_prox = v
self.vertices.append(aluno)
aresta = Aresta(aluno, mais_prox, dist_min)
self.arestas.append(aresta)
def diferenca(self):
diferenca = 0
for v in self.arestas:
diferenca += v.peso
return diferenca
def grau(self):
return len(self.vertices)
def __repr__(self):
return str(self.vertices) + '\n'+ str(self.arestas)
# ## 2) Leitura dos arquivos
#
# Na leitura do arquivo 'Aluno_Area_Pesquisa.txt', as linhas são usadas para instanciar os alunos, e a lista alunos é criada.
#
# Na leitura do arquivo 'Matriz_Dissimilaridade.txt', a matriz triangular é transformada numa matriz simétrica para facilitar o cálculo de distâncias entre as áreas de pesquisa.
# In[390]:
file = open('Aluno_Area_Pesquisa.txt', 'r').read()
lines = file.split('\n')
alunos = []
for line in lines:
line = line.split(' ')
codigo_aluno = int(line[0])
area_pesquisa = int(line[1])
a = Aluno(codigo_aluno, area_pesquisa)
alunos.append(a)
#alunos
# In[387]:
def completa_matriz(matriz_triangulo):
matriz_triangulo.sort(key=len, reverse=True)
lado = len(matriz_triangulo)
matriz = np.zeros((lado, lado))
for i in range(lado):
for j in range(len(matriz_triangulo[i])):
matriz[i][i+j] = matriz_triangulo[i][j]
matriz[i+j][i] = matriz_triangulo[i][j]
return matriz
# In[388]:
file = open('Matriz_Dissimilaridade.txt', 'r').read()
lines = file.split('\n')
matriz_triangulo = []
for l in lines:
l = l.split(' ')
l = list(filter(None, l))
matriz_triangulo.append(l)
matriz = completa_matriz(matriz_triangulo)
matriz
# ## 3) Distâncias
#
# Primeiro se define a distância entre dois alunos, baseado em suas areas de pesquisa e na matriz de dissimilaridade.
#
# Então, é definida a distância entre dois grafos, que é a média das distâncias entre alunos de cada grafo.
# In[391]:
def dist_aluno(aluno1, aluno2):
area1 = aluno1.area_pesquisa
area2 = aluno2.area_pesquisa
return matriz[area1-1][area2-1]
# In[392]:
def dist_grafo(grafo1, grafo2):
sum_dist = 0
for aluno1 in grafo1.vertices:
for aluno2 in grafo2.vertices:
sum_dist += dist_aluno(aluno1, aluno2)
n = len(grafo1.vertices)
m = len(grafo2.vertices)
media_dist = sum_dist/(n*m)
return media_dist
# ## 4) Função Principal e Aplicação
# In[396]:
def particao(k, alunos):
subgrafos = []
for aluno in alunos:
subgrafo = Grafo([aluno],[])
subgrafos.append(subgrafo)
while len(subgrafos) > k:
subgrafos = sorted(subgrafos, key = lambda g: (g.grau(), -g.diferenca())) #grau crescente, diferença decrescente
s = subgrafos.pop(0)
for aluno in s.vertices:
subgrafos = sorted(subgrafos, key = lambda g: (g.grau(), dist_grafo(Grafo([aluno],[]), g)))
subgrafos[0].add(aluno)
return subgrafos
# In[402]:
solucao = particao(11, alunos)
print(solucao)
len(solucao)
# ## 5) Visualização
# In[401]:
#visualização
g = Graph()
n_vertices = len(alunos)
g.add_vertices(n_vertices)
edges = []
for grupo in solucao:
for aresta in grupo.arestas:
edges.append((aresta.aluno1.codigo_aluno-1, aresta.aluno2.codigo_aluno-1))
g.add_edges(edges)
plot(g)
# In[ ]:
|
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
self.level = None
class BST:
def __init__(self):
self.root = None
def create(self, val):
if self.root == None:
self.root = Node(val)
else:
current = self.root
while True:
if val < current.val:
if current.left is not None:
current = current.left
else:
current.left = Node(val)
break
elif val > current.val:
if current.right is not None:
current = current.right
else:
current.right = Node(val)
break
else:
break
def in_order(self, root):
if root:
self.in_order(root.left)
print(root.val, end=" ")
self.in_order(root.right)
def find_height(self, root):
if root is None:
return 0
else:
lh = self.find_height(root.left)
rh = self.find_height(root.right)
if lh > rh:
return lh + 1
else:
return rh + 1
tree = BST()
arr = list(map(int, input().split()))
for element in arr:
tree.create(element)
tree.in_order(tree.root)
print("\n",tree.find_height(tree.root))
|
# Uses error to determine significant digits to display data in
# Usage: r'$(%.0f \pm %.0f)x10^{%i}$' % sigfigs(value, error)
def sigfigs(value, error):
sigfigs = 0
if error >= 1.:
e = str(int(error))
for i in range(len(e),0,-1):
if int(e[i-1]) != 0:
sigfigs = len(e) - i
break
value = value / 10.**sigfigs
error = error / 10.**sigfigs
return(value, error, sigfigs)
elif error == 0.:
return(value, 0, 0)
else:
e = str(float(error))
for i in range(2,len(e),1):
if int(e[i]) != 0:
sigfigs = 1 - i
break
value = value / 10.**sigfigs
error = error / 10.**sigfigs
return(value, error, sigfigs)
|
#Heap Sort
#Function to create max heap
def max_heapify(arr, n, i):
largest = i
left = 2*i+1
right = 2*i+2
if left < n and arr[i] < arr[left]:
largest = left
if right < n and arr[largest] < arr[right]:
largest = right
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
max_heapify(arr, n, largest)
#Function to create min heap
def min_heapify(arr, n, i):
smallest = i
left = 2*i+1
right = 2*i+2
if left < n and arr[i] > arr[left]:
smallest = left
if right < n and arr[smallest] > arr[right]:
smallest = right
if smallest != i:
arr[i], arr[smallest] = arr[smallest], arr[i]
min_heapify(arr, n, smallest)
#This will sort array A in ascending order
arr = [12, 12, 13, 8, 6, 7]
def Aheapsort(arr):
print(arr)
n = len(arr)
for i in range(n, -1, -1):
max_heapify(arr, n, i)
for i in range(n-1, 0, -1):
arr[i], arr[0] = arr[0], arr[i]
max_heapify(arr, i, 0)
print(arr)
Aheapsort(arr)
#This will sort array A in descending order
arr = [12, 12, 13, 8, 6, 7]
def Dheapsort(arr):
print(arr)
n = len(arr)
for i in range(n, -1, -1):
min_heapify(arr, n, i)
for i in range(n-1, 0, -1):
arr[i], arr[0] = arr[0], arr[i]
min_heapify(arr, i, 0)
print(arr)
Dheapsort(arr)
#Function to extract maximum element from the heap
def heap_extract_max(arr):
print(arr)
n = len(arr)
for i in range(n, -1, -1):
max_heapify(arr, n, i)
print(arr)
max = arr[0]
arr[0] = arr[n-1]
n = n-1
arr = arr[:n]
print(max)
print(arr)
arr = [1, 26, 13, 5, 6, 7]
heap_extract_max(arr)
#Function to increase key of heap and still maintain max_heap property
import numpy as np
def heap_increase_key(arr, index, key):
n = len(arr)
print(arr)
for i in range(n, -1, -1):
max_heapify(arr, n, i)
print(arr)
arr[index] = key
print(arr)
while index>1 and arr[int(np.ceil(index/2)-1)] < arr[index]:
arr[index], arr[int(np.ceil(index/2)-1)] = arr[int(np.ceil(index/2)-1)], arr[index]
index = int(np.ceil(n/2)-1)
print(arr)
arr = [1, 26, 13, 5, 6, 7]
heap_increase_key(arr, 4, 10)
#Function to insert a new element in the heap and still maintain max_heap property
def max_heap_insert(arr, key):
n = len(arr)
print(arr)
arr.append(float("-inf"))
heap_increase_key(arr, n, key)
arr = [1, 26, 13, 5, 6, 7]
max_heap_insert(arr, 14) |
#Shell Sort
import numpy as np
#Function to sort input array to ascending order
def Ashellsort(A):
print(A)
n = len(A)
gap = int(np.floor(n/2))
while gap > 0:
for i in range(n-gap):
if A[i] >= A[i+gap]:
A[i], A[i+gap] = A[i+gap], A[i]
j = i
while j-gap >= 0:
if A[j-gap] >= A[j]:
A[j], A[j-gap] = A[j-gap], A[j]
j = j-gap
else:
j = 0
gap = int(np.floor(gap/2))
print(A)
A = [100, 2, 101, 1, 3, 4, 54, 0, -3]
Ashellsort(A)
#Function to sort input array to descending order
def Dshellsort(A):
print(A)
n = len(A)
gap = int(np.floor(n/2))
while gap > 0:
for i in range(n-gap):
if A[i] <= A[i+gap]:
A[i], A[i+gap] = A[i+gap], A[i]
j = i
while j-gap >= 0:
if A[j-gap] <= A[j]:
A[j], A[j-gap] = A[j-gap], A[j]
j = j-gap
else:
j = 0
gap = int(np.floor(gap/2))
print(A)
A = [100, 2, 101, 1, 3, 4, 54, 0, -3]
Dshellsort(A) |
"""
Wave Array
Given a sorted array arr[] of distinct integers. Sort the array into a wave-like array and return it. In other words, arrange the elements into a sequence such that a1 >= a2 <= a3 >= a4 <= a5..... (considering the increasing lexicographical order).
Input Format:
The first line contains an integer T, depicting total number of test cases. T testcases follow. The first line of each testcase contains an integer N depicting the size of the array. The second line contains N space separated elements of the array.
Output Format:
For each testcase, in a new line, print the array into wave-like array.
User Task:
The task is to complete the function convertToWave() which converts the given array to wave array. The newline is automatically added by the driver code.
Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 106
0 ≤ A[i] ≤107
Example:
Input:
2
5
1 2 3 4 5
6
2 4 7 8 9 10
Output:
2 1 4 3 5
4 2 8 7 10 9
Explanation:
Testcase 1: Array elements after sorting it in wave form are 2 1 4 3 5.
Testcase 2: Array elements after sorting it in wave form are 4 2 8 7 10 9.
** For More Input/Output Examples Use 'Expected Output' option **
"""
def convertToWave(A,N):
for x in range(0,N-1,2):
temp = A[x+1]
A[x+1] = A[x]
A[x] = temp |
def func(ch,st,n):
if(n == len(st)):
print(ch)
return
func(ch+st[n],st,n+1)
func(ch,st,n+1)
st = input()
print(func("",st,0))
|
def reverseWords(s):
ans=""
l=[]
for x in s:
ans+=x
if(x=='.'):
l.append(ans)
ans=""
continue
l.append(ans)
answer=""
for x in range(len(l)-1,-1,-1):
answer+=l[x]
if(x==len(l)-1):
answer+='.'
print(answer[0:-1],end="") |
"""
Digital Root
You are given a number n. You need to find the digital root of n.
DigitalRoot of a number is the recursive sum of its digits until we get a single digit number.
Eg.DigitalRoot(191)=1+9+1=>11=>1+1=>2
Input:
The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase contains one line of input containing n.
Output:
For each testcase, in a newline, print the digital root of n.
Your Task:
This is a function problem. You only need to complete the function digitalRoot that takes n as parameter and returns the digital root of n.
Constraints:
1 <= T <= 105
1 <= n <= 107
Examples:
Input:
2
1
99999
Output:
1
9
Explanation:
Testcase 1: Digital root for 1 is 1.
Testcase 2: Digital root for 99999 is 9 + 9 + 9 + 9 + 9 => 45 => 4 + 5 => 9.
** For More Input/Output Examples Use 'Expected Output' option **
"""
def digitalRoot(num):
num = str(num)
if (num == "0"):
return 0
ans = 0
for i in range (0, len(num)):
ans = (ans + int(num[i])) % 9
if(ans == 0):
return 9
else:
return ans % 9
assert digitalRoot(10514) == 2
assert digitalRoot(99999) == 9
assert digitalRoot(1) == 1
print('The code ran Correctly') |
"""
Multiply the matrices
When dealing with matrices, you may, sooner or later, run into the elusive task of matrix multiplication. Here, we will try to multiply two matrices and hope to understand the process.
Two matrices A[][] and B[][] can only be multiplied if A's column size is equal to B's row size. The resultant matrix will have dimensions equal to A's row size and B's column size.
You are given two matrices A and B. A is of dimension n1 x m1; and B is of dimension n2 x m2. You have to multiply A with B and print the resultant matrix. If multiplication is not possible then print -1.
Input:
The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase contains four lines of input. The first line contains dimensions of the first array n1 and m1. The second line contains n1 * m1 elements separated by spaces. The third line contains dimensions of the second array n2 and m2. The fourth line contains n2 * m2 elements separated by spaces.
Output:
For each testcase, in a new line, print the resultant matrix if possible; else print -1.
Your Task:
This is a function problem. You only need to complete the function multiplyMatrix that takes n1,m2,n2,m2,matrix1,matrix2 as parameters and prints the multiplied matrix. The newline is automatically appended by the driver code.
Constraints:
1 <= T <= 100
1 <= n1, m1, n2, m2 <= 30
0 <= arri <= 100
Examples:
Input:
2
3 2
4 8 0 2 1 6
2 2
5 2 9 4
1 1
2
1 1
3
Output:
92 40 18 8 59 26
6
Explanation:
Testcase 1: Matrices are of size 3 x 2 and 2 x 2 which results in 3 x 2 matrix with elements as 92, 40, 18, 8, 59, 26.
Testcase 2: Matrices are of size 1 x 1 and 1 x 1 which results in 1 x 1 matrix having element 6.
"""
import numpy as np
#Complete this function
def multiplyMatrix(n1, m1, n2, m2, arr1, arr2):
if(m1!=n2):
print(-1)
return
result = np.dot(arr1,arr2)
for x in result:
for y in x:
print(y,end=" ") |
"""
Digits In Factorial
Given an integer N. The task is to find the number of digits that appear in its factorial, where factorial is defined as, factorial(n) = 1*2*3*4……..*N and factorial(0) = 1.
Input:
The first line of input contains a single integer T denoting the number of test cases. Then T test cases follow. Each test case consist of one line. The first line of each test case consists of an integer N.
Output:
Corresponding to each test case, in a new line, print the number of digits that appear in its factorial.
Your Task:
This is a function problem. You only need to complete the function digitsInFactorial() that takes N as parameter and returns number of digits in factorial of N.
Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 104
Example:
Input:
2
5
120
Output:
3
199
Explanation:
Testcase 1: Factorial of 5 is 120. Number of digits in 120 is 3 (1, 2, and 0).
Testcase 2: Number of digits in 120! is 199.
** For More Input/Output Examples Use 'Expected Output' option **
"""
import math
def digitsInFactorial(n):
if (n < 0):
return 0
if (n <= 1):
return 1
digits = 0;
for i in range(2, n + 1):
digits += math.log10(i)
return math.floor(digits) + 1
assert digitsInFactorial(2) == 1
assert digitsInFactorial(5) == 3
assert digitsInFactorial(120) == 199
print('The code ran Correctly') |
"""
Minimum Number in a sorted rotated array
Given an array A which is sorted and contains N distinct elements. Also, this array is rotated at some unknown point. The task is to find the minimum element in it.
Note: Expected time complexity is O(logN).
Input:
The first line of input contains an integer T denoting the number of test cases. Each test case contains the number of elements in the array arr[] as N and next line contains space separated n elements in the array arr[].
Output:
Print an integer which denotes the minimum element in the array.
User Task:
The task is to complete the function minNumber() which finds the minimum in sorted and rotated array.
Constraints:
1 <= T <= 100
1 <= N <= 107
1 <= arr[i] <= 107
Example:
Input:
3
10
2 3 4 5 6 7 8 9 10 1
5
3 4 5 1 2
8
10 20 30 45 50 60 4 6
Output:
1
1
4
Explanation:
Testcase 1: The array is rotated once anti-clockwise. So minium element is at last index (n-1) which is 1.
Testcase 2: The array is rotated and the minimum element present is at index (n-2) which is 1.
Testcase 3: The array is rotated and the minimum element present is 4.
** For More Input/Output Examples Use 'Expected Output' option **
"""
def minNumber(arr,low,high):
#return(min(arr)) : Time: 0.03 sec
while(high>low):
if(arr[low+1]>=arr[low] and arr[high]>=arr[low]):
return arr[low]
if(arr[high]<arr[low]):
if(arr[high]>arr[high-1]):
high-=1
else:
return arr[high] #Time = 0.03 sec |
"""
Minimum Platforms
Given arrival and departure times of all trains that reach a railway station. Your task is to find the minimum number of platforms required for the railway station so that no train waits.
Note: Consider that all the trains arrive on the same day and leave on the same day. Also, arrival and departure times will not be same for a train, but we can have arrival time of one train equal to departure of the other.
In such cases, we need different platforms, i.e at any given instance of time, same platform can not be used for both departure of a train and arrival of another.
Input:
The first line of input contains T, the number of test cases. For each test case, first line will contain an integer N, the number of trains. Next two lines will consist of N space separated time intervals denoting arrival and departure times respectively.
Note: Time intervals are in the 24-hour format(hhmm), of the for HHMM , where the first two charcters represent hour (between 00 to 23 ) and last two characters represent minutes (between 00 to 59).
Output:
For each test case, print the minimum number of platforms required for the trains to arrive and depart safely.
Constraints:
1 <= T <= 100
1 <= N <= 1000
1 <= A[i] < D[i] <= 2359
Example:
Input:
2
6
0900 0940 0950 1100 1500 1800
0910 1200 1120 1130 1900 2000
3
0900 1100 1235
1000 1200 1240
Output:
3
1
Explanation:
Testcase 1: Minimum 3 platforms are required to safely arrive and depart all trains.
Testcase 2: Only 1 platform is required to safely manage the arrival and departure of all trains.
** For More Input/Output Examples Use 'Expected Output' option **
"""
def minimumPlatform(n,arr,dep):
'''
:param n: number of activities
:param arr: arrival time of trains
:param dep: corresponding departure time of trains
:return: Integer, minimum number of platforms needed
'''
arr.sort()
dep.sort()
i = 1
j = 0
ans = 1
max1 = 1
while i<n and j<n:
if(arr[i]<=dep[j]):
max1+=1
i+=1
else:
max1-=1
j+=1
ans = max(ans,max1)
return(ans) |
"""
Rotate Array
Given an unsorted array arr[] of size N, rotate it by D elements (counter-clockwise).
Input:
The first line of the input contains T denoting the number of testcases. First line of eacg test case contains two space separated elements, N denoting the size of the array and an integer D denoting the number size of the rotation. Subsequent line will be the N space separated array elements.
Output:
For each testcase, in a new line, output the rotated array.
User Task:
The task is to complete the function rotate() which rotates the array by given D elements. The newline is automatically added by the driver code.
Constraints:
1 <= T <= 200
1 <= N <= 107
1 <= D <= N
0 <= arr[i] <= 105
Example:
Input:
2
5 2
1 2 3 4 5
10 3
2 4 6 8 10 12 14 16 18 20
Output:
3 4 5 1 2
8 10 12 14 16 18 20 2 4 6
Explanation :
Testcase 1: 1 2 3 4 5 when rotated by 2 elements, it becomes 3 4 5 1 2.
Testcase 2: 2 4 6 8 10 12 14 16 18 20 when rotated by 3 elements, it becomes 8 10 12 14 16 18 20 2 4 6.
** For More Input/Output Examples Use 'Expected Output' option **
"""
def rotateArr(A,D,N):
return(A[D:]+A[:D])
|
"""
Modular Multiplicative Inverse
Given two integers ‘a’ and ‘m’. The task is to find modular multiplicative inverse of ‘a’ under modulo ‘m’.
Note: Print the smallest modular multiplicative inverse.
Input:
First line consists of T test cases. Only line of every test case consists of 2 integers 'a' and 'm'.
Output:
For each testcase, in a new line, print the modular multiplicative inverse if exists else print -1.
Your Task:
This is a function problem. You just need to complete the function modInverse() that takes a and m as parameters and returns modular multiplicative inverse of ‘a’ under modulo ‘m’.
Constraints:
1 <= T <= 100
1 <= m <= 100
Example:
Input:
2
3 11
10 17
Output:
4
12
Explanation:
Testcase 1:
Input: a = 3, m = 11
Output: 4
Since (4*3) mod 11 = 1, 4 is modulo inverse of 3
One might think, 15 also as a valid output as "(15*3) mod 11"
is also 1, but 15 is not in ring {0, 1, 2, ... 10}, so not valid.
Testcase 2:
Input: a = 10, m = 17
Output: 12
Since (12*10) mod 17 = 1, 12 is the modulo inverse of 10.
** For More Input/Output Examples Use 'Expected Output' option **
"""
def modInverse(a,m):
for x in range(1,m):
if( (x*a)%m == 1 ):
return(x)
return(-1)
assert modInverse(3,11) == 4
assert modInverse(10,17) == 12
print('The code ran Correctly') |
"""
Interchanging the rows of a Matrix
You are given a matrix A of dimensions n1 x m1. You have to interchange the rows(first row becomes last row and so on).
Input:
The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase two lines of input. The first line contains dimensions of the array A, n1 and m1. The second line contains n1 * m1 elements separated by spaces.
Output:
For each testcase, in a new line, print the resultant matrix.
Your Task:
This is a function problem. You only need to complete the function interchangeRows() that takes n1,m1, and matrix as parameter and modifies the array. The driver code automatically appends a new line.
Constraints:
1 <= T <= 100
1 <= n1, m1 <= 30
1 <= arri <= 100
Examples:
Input:
2
4 4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
5 3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Output:
13 14 15 16 9 10 11 12 5 6 7 8 1 2 3 4
13 14 15 10 11 12 7 8 9 4 5 6 1 2 3
Explanation:
Testcase 1: Original matrix is as follows:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Matrix after exchanging rows:
13 14 15 16
9 10 11 12
5 6 7 8
1 2 3 4
Testcase 2: Original matrix is as follows:
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
After interchanging rows:
13 14 15
10 11 12
7 8 9
4 5 6
1 2 3
** For More Input/Output Examples Use 'Expected Output' option **
Constraints:
1 <= T <= 100
1 <= n1, m1 <= 30
1 <= arri <= 100
Examples:
Input:
2
4 4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
5 3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Output:
13 14 15 16 9 10 11 12 5 6 7 8 1 2 3 4
13 14 15 10 11 12 7 8 9 4 5 6 1 2 3
Explanation:
Testcase 1: Original matrix is as follows:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Matrix after exchanging rows:
13 14 15 16
9 10 11 12
5 6 7 8
1 2 3 4
Testcase 2: Original matrix is as follows:
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
After interchanging rows:
13 14 15
10 11 12
7 8 9
4 5 6
1 2 3
Constraints:
1 <= T <= 100
1 <= n1, m1 <= 30
1 <= arri <= 100
Examples:
Input:
2
4 4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
5 3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Output:
13 14 15 16 9 10 11 12 5 6 7 8 1 2 3 4
13 14 15 10 11 12 7 8 9 4 5 6 1 2 3
Explanation:
Testcase 1: Original matrix is as follows:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Matrix after exchanging rows:
13 14 15 16
9 10 11 12
5 6 7 8
1 2 3 4
Testcase 2: Original matrix is as follows:
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
After interchanging rows:
13 14 15
10 11 12
7 8 9
4 5 6
1 2 3
"""
def interchangeRows(n1, m1, arr):
for x in range(n1//2):
temp = arr[x]
arr[x]=arr[n1-x-1]
arr[n1-x-1]=temp
|
"""
Binary Array Sorting
Given a binary array A[] of size N. The task is to arrange array in increasing order.
Note: The binary array contains only 0 and 1.
Input:
The first line of input contains an integer T, denoting the testcases. Every test case contains two lines, first line is N(size of array) and second line is space separated elements of array.
Output:
Space separated elements of sorted arrays. There should be a new line between output of every test case.
Your Task:
This is a function problem. You only need to complete the function binSort() that takes A and N as parameters and sorts the array. The printing is done automatically by the driver code.
Constraints:
1 < = T <= 100
1 <= N <= 106
0 <= A[i] <= 1
Example:
Input:
2
5
1 0 1 1 0
10
1 0 1 1 1 1 1 0 0 0
Output:
0 0 1 1 1
0 0 0 0 1 1 1 1 1 1
Explanation:
Testcase 1: After arranging the elements in increasing order, elements will be as 0 0 1 1 1.
Testcase 2: After arranging the elements in increasing orde, elements will be 0 0 0 0 1 1 1 1 1 1.
** For More Input/Output Examples Use 'Expected Output' option **
"""
def binSort(arr, n):
i = 0
j = n
p = [0]*n
for x in range(n):
if(arr[x]==0):
i+=1
if(arr[x]==1):
p[j-1] = 1
j-=1
for x in range(n):
arr[x] = p[x] |
temp = head
fast = head
while(temp!=None and fast.next!=None and fast.next.next!=None):
temp = temp.next
fast = fast.next.next
if temp==fast:
return('True')
return('False') |
"""
Possible Words From Phone Digits
Given a keypad as shown in diagram, and an N digit number. List all words which are possible by pressing these numbers.
Input:
The first line of input contains an integer T denoting the number of test cases. T testcases follow. Each testcase contains two lines of input. The first line of each test case is N, N is the number of digits. The second line of each test case contains D[i], N number of digits.
Output:
Print all possible words from phone digits with single space.
Your Task:
This is a function problem. You just need to complete the function possibleWords that takes an array as parameter and prints all the possible words. The newline is automatically added by the driver code.
Constraints:
1 <= T <= 100
1 <= N <= 10
2 <= D[i] <= 9
Example:
Input:
2
3
2 3 4
3
3 4 5
Output:
adg adh adi aeg aeh aei afg afh afi bdg bdh bdi beg beh bei bfg bfh bfi cdg cdh cdi ceg ceh cei cfg cfh cfi
dgj dgk dgl dhj dhk dhl dij dik dil egj egk egl ehj ehk ehl eij eik eil fgj fgk fgl fhj fhk fhl fij fik fil
Explanation:
Testcase 1: When we press 2,3,4 then adg,adh,adi , ......,cfi are the list of possible words.
Testcase 2: When we press 3,4,5 then dgj,dgk,dgl,.......,fil are the list of possible words.
** For More Input/Output Examples Use 'Expected Output' option **
"""
hashTable = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
def printWordsUtil(number, curr, output, n):
if(curr == n):
print(''.join(output), end=" ")
return
for i in range(len(hashTable[number[curr]])):
output.append(hashTable[number[curr]][i])
printWordsUtil(number, curr + 1, output, n)
output.pop()
if(number[curr] == 0 or number[curr] == 1):
return
def possibleWords(number, n):
printWordsUtil(number, 0, [], n)
|
"""
Merge Without Extra Space
Given two sorted arrays arr1[] and arr2[] in non-decreasing order with size n and m. The task is to merge the two sorted arrays in place, i. e., we need to consider all n + m elements in sorted order, then we need to put first n elements of these sorted in first array and remaining m elements in second array.
Note: Expected time complexity is O((n+m) log(n+m)). DO NOT use extra space. We need to modify existing arrays as following.
Input: arr1[] = {10};
arr2[] = {2, 3};
Output: arr1[] = {2}
arr2[] = {3, 10}
Input: arr1[] = {1, 5, 9, 10, 15, 20};
arr2[] = {2, 3, 8, 13};
Output: arr1[] = {1, 2, 3, 5, 8, 9}
arr2[] = {10, 13, 15, 20}
Input:
First line contains an integer T, denoting the number of test cases. First line of each test case contains two space separated integers X and Y, denoting the size of the two sorted arrays. Second line of each test case contains X space separated integers, denoting the first sorted array P. Third line of each test case contains Y space separated integers, denoting the second array Q.
Output:
For each test case, print (X + Y) space separated integer representing the merged array.
Your Task:
This is a function problem. You only need to complete the function merge() that takes n and m as parameters.
Constraints:
1 <= T <= 100
1 <= X, Y <= 5*104
0 <= arr1i, arr2i <= 109
Example:
Input:
2
4 5
1 3 5 7
0 2 6 8 9
2 3
10 12
5 18 20
Output:
0 1 2 3 5 6 7 8 9
5 10 12 18 20
"""
def merge(a,n,b,m):
arr = a+b
arr.sort()
for x in range(n+m):
if(x<n):
a[x] = arr[x]
else:
b[x-n] = arr[x]
|
"""
Find first set bit
Given an integer an N. The task is to print the position of first set bit found from right side in the binary representation of the number.
Input:
The first line of the input contains an integer T, denoting the number of test cases. Then T test cases follow. The only line of the each test case contains an integer N.
Output:
For each test case print in a single line an integer denoting the position of the first set bit found form right side of the binary representation of the number. If there is no set bit print "0".
User Task:
The task is to complete the function getFirstSetBit() that takes n as parameter and returns the the position of first set bit.
Constraints:
1 <= T <= 200
0 <= N <= 106
Example:
Input:
3
18
12
0
Output:
2
3
0
Explanation:
Testcase 1: Binary representation of 18 is 010010, the first set bit from the right side is at position 2.
Testcase 2: Binary representation of 12 is 1100, the first set bit from the right side is at position 3.
Testcase 3: In 0 there is no set bit so we print 0 as mentioned.
** For More Input/Output Examples Use 'Expected Output' option **
"""
import math
def getFirstSetBit(n):
if(n==0):
return(0)
return(int(math.log(n & -n , 2))+1)
assert getFirstSetBit(18) == 2
assert getFirstSetBit(4) == 3
assert getFirstSetBit(0) == 0
print('The code ran Correctly') |
N = int(input())
result = []
for i in range(N):
result.append(2**i)
print(result,end=' ') |
inch = float(input())
cm = inch * 2.54
print('{:.2f} inch => {:.2f} cm '.format(inch, cm))
|
# 런타임에러
N = int(input())
nums = list(map(int, input().split()))
compare_in = nums[0]
compare_de = nums[0]
length_in = 1
length_de = 1
result = []
for i in range(1, len(nums)):
if nums[i] >= compare_in:
compare_in = nums[i]
length_in += 1
result.append(length_in)
else:
compare_in = nums[i]
length_in = 1
for i in range(1, len(nums)):
if nums[i] <= compare_de:
compare_de = nums[i]
length_de += 1
result.append(length_de)
else:
compare_de = nums[i]
length_de = 1
# result2 = max(result)
if len(nums) == 1:
print(1)
elif max(result) < 3:
print(2)
else:
print(max(result))
# if length_in >= length_de:
# print(length_in)
# else:
# print(length_de)
# print(max(result)) |
T = int(input())
for t in range(1, T+1):
str1 = str(input())
str2 = str(input())
if str1 in str2:
result = 1
else:
result = 0
print('#{} {}'.format(t, result)) |
T = int(input())
for tc in range(1, T+1):
words = [0]*5
maxlen = 0
for i in range(5):
words[i] = list(input())
if len(words[i]) > maxlen:
maxlen = len(words[i])
print('#{}'.format(tc), end=' ')
for i in range(maxlen):
for j in range(5):
if len(words[j]) > i:
print(words[j][i], end= ' ')
print() |
n = int(input())
for i in range(1,n+1):
print(f"{'*' * i}")
for i in range(n-1,0,-1):
print(f"{'*' * i}") |
# arr = [0] * 5
# for i in range(5):
# arr[i] = list(map(int,input().split()))
# print(arr[0])
# print(arr)
# print(arr[0][1])
# arr = [[0] * 5] * 5 # 이렇게 초기화하지 않는다!!
# arr[1][0]
# print(arr)
# arr = [[0] * 5 for _ in range(5)] # 이렇게 초기화 해준다!
# arr[1][0] = -1
# print(arr)
10101 => [1, 2, 3, 1,] |
#!/bin/env python
import numpy as np
import integ_Romberg
def NaivTrap(f,a,b,eps):
"""变步长梯形积分
:f: TODO
:a: TODO
:b: TODO
:eps: TODO
:returns: TODO
"""
n = 1
h = (b-a)/n
I1 = 0.5*h*(f(a)+f(b))
tol=1;
while tol>eps:
I0 = I1
n = 2*n
h = (b-a)/n
x = np.linspace(a,b,n+1)
y = f(x)
I1 = h*(0.5*y[0] + np.sum(y[1:n]) + 0.5*y[n])
tol=abs(I1-I0)
print("n is ",n)
return I1
def aTrapInt(f,a,b,eps):
"""变步长梯形积分
:f: TODO
:a: TODO
:b: TODO
:eps: TODO
:returns: TODO
"""
tol=1;nsub=1
inall = 0
T = 0.5*(b-a)*(f(a)-f(b))
while tol>eps:
T0=T
nsub = 2*nsub
n = nsub+1
h = (b-a) / nsub
x = np.linspace(a,b,n)
inall = inall + np.sum(f(x[1:n-1:2]))
T = 0.5*h*(f(a) + 2*inall + f(b))
tol = abs(T-T0)
print("n is ",nsub)
return T
def NaivSimp(f,a,b,eps):
"""变步长辛普森积分
:f: TODO
:a: TODO
:b: TODO
:eps: TODO
:returns: TODO
"""
n=2
h = (b-a)/n
I1 = h*(f(a) + 4*f(a+h) + f(b)) / 3
tol = 1
while tol > eps:
I0 = I1
n = 2*n
h = (b-a)/n
x = np.linspace(a,b,n+1)
y = f(x)
I1 = h * (y[0] + 4*np.sum(y[1:n+1:2]) + 2*np.sum(y[2:n:2]) + y[n])
tol = abs(I1 - I0)
return I1
def aSimpInt(f,a,b,eps):
"""变步长辛普森积分
:f: TODO
:a: TODO
:b: TODO
:eps: TODO
:returns: TODO
"""
nsub = 2
odd = f((a+b)/2)
even = 0
S = (b-a) * (f(a) + 4*odd + 2*even + f(b)) / 6
inall = even + odd
tol = 1
while tol > eps:
S0 = S
nsub = 2 * nsub
n = nsub + 1
h = (b - a) / nsub
x = np.linspace(a,b,n)
odd = np.sum(f(x[1:n:2]))
even = inall
S = (h/3) * (f(a) + 4*odd + 2*even + f(b))
inall = even + odd
tol = abs(S-S0)
print("n is ",nsub)
return S
def main():
print("==========例题4.2.6==========")
def f(x):
return np.exp(-x**2)
print("变步长梯形公式的结果为:",aTrapInt(f,0,1,10**(-6)))
print("变步长辛普森公式的结果为:",aSimpInt(f,0,1,10**(-6)))
print("==========作乐4.2.6==========")
def f(x):
return 4/(1+x**2)
print("变步长梯形公式的结果为:",aTrapInt(f,0,1,10**(-5)))
print("变步长辛普森公式的结果为:",aSimpInt(f,0,1,10**(-5)))
T,k=integ_Romberg.Roberg(f,0,1,10**(-5))
print("Table:")
print(T[:k+1,:k+1])
if __name__ == "__main__":
main()
|
import numpy as np
from scipy import optimize
def newton(f,df,p0,epsilon=10**-6,maxi=1000):
"""solve nonlinear eqution by newton iterative method
:f: func
:df: First derivative of f
:p0: initial value
:returns: solve
"""
x=p0
res=f(x)
i=0
while abs(res)>= epsilon:
x1 = x - (f(x)/df(x))
res = f(x1)
i=i+1
x=x1
print("iteration %i, x=%f"%(i,x))
if i>= maxi:
print("maximum iteration!")
return x
return x
def main():
def f(x):
return x**3 - 3*x**2 + 4*x - 2
def df(x):
return 3*x**2 -6*x + 4
x = newton(f,df,1.5)
print("solution is ",x)
x = optimize.root(f,1.5,jac=df)
print("scipy root:\n",x)
if __name__ == "__main__":
main()
|
from random import random
def GetGuess():
tmp = int(input("Please input your guess\n"))
return tmp
key = int(random()*100)
print("guess the number in (0,100])")
guess = GetGuess()
while guess != key:
if guess > key:
print("Too large!")
if guess < key:
print("Too small!")
guess = GetGuess()
print("Good job!")
|
import numpy as np
# from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
from linalg_gauss_jordan import gauss_jordan
def multifit(x,y,m):
"""TODO: Docstring for multifit.
:arg1: TODO
:returns: TODO
"""
n = len(x)
if m > n :
print("warning: m >n")
S = np.zeros((m+1,m+1))
T = np.zeros(m+1)
tmp = np.zeros(2*m+1)
for i in range(2*m+1):
tmp[i] = np.sum(x**i,0)
for i in range(m+1):
S[i,:] = tmp[i:m+1+i]
for i in range(m+1):
T[i] = np.sum(x**i*y,0)
a = gauss_jordan(S,T)
return a
def main():
x = np.linspace(-1,1,11)
y = np.exp(x)
m=5
a = multifit(x,y,m)
a = a[::-1]
print("a is ",a)
plt.plot(x,y,'o',label='data')
plt.plot(x,np.polyval(a,x),'-',label="fit")
plt.xlabel("x")
plt.ylabel("y")
plt.legend()
plt.show()
#==============================================
x = np.linspace(-50,50,50)
y = np.exp(x)
m=5
a = multifit(x,y,m)
a = a[::-1]
print("a is ",a)
plt.plot(x,y,'o',label='data')
plt.plot(x,np.polyval(a,x),'-',label="fit")
plt.xlabel("x")
plt.ylabel("y")
plt.legend()
plt.show()
#==============================================
x = np.linspace(1,2,2)
def linear(x,a):
y = np.zeros(len(x))
for i in range(len(a)):
y = y + x**i*a[i]
return y
y = linear(x,[4,3,2])
a = multifit(x,y,2)
a = a[::-1]
print("a is :",a)
b = multifit(x,y,1)
b = b[::-1]
print("b is :",b)
xplot=np.arange(-1,3,0.1)
plt.plot(x,y,'o',label='data')
plt.plot(xplot,np.polyval(a,xplot),'-',label="fit 3")
plt.plot(xplot,np.polyval(b,xplot),'-',label="fit 2")
plt.plot(xplot,linear(xplot,[4,3,2]),'-',label="real")
plt.xlabel("x")
plt.ylabel("y")
plt.legend()
plt.show()
if __name__ == "__main__":
main()
|
caps = list(range(65, 91))
lower = list(range(97, 123))
everything = list(range(33, 127))
def hey(str):
str = str.strip()
if says_nothing(str):
return "Fine. Be that way!"
elif question(str):
return "Sure."
elif yell(str):
return "Whoa, chill out!"
else:
return "Whatever."
def question(str):
ord_list = [ord(s) for s in str]
symb_list = [n for n in ord_list if n in everything and n != 63] # ord("?") == 63
return str[-1] == "?" and len(symb_list) > 0 and not all(n in caps for n in symb_list)
def yell(str):
return not any(ord(s) in lower for s in str) and any(ord(s) in caps for s in str)
def says_nothing(str):
return len(str) == 0 or not any(ord(s) in everything for s in str)
|
def distance(str1, str2):
str1, str2 = str1.upper().strip(), str2.upper().strip()
if len(str1) != len(str2):
raise ValueError("Input strings are of unequal length")
for item in str1+str2:
if item not in 'GCTAU':
raise ValueError("At least one input strings was invalid")
diffs, i = 0, 0
while i < len(str1):
if str1[i] != str2[i]:
diffs += 1
i += 1
return diffs
|
# Storing elements in a list / tuple in variables for easy accessibility
numbers = (2, 3, 4, 5)
a = numbers[0]
b = numbers[1]
c = numbers[2]
d = numbers[3]
print(a)
print(b)
print(c)
print(d)
print()
# Unpacking makes the above easier
j, k, l, m = numbers
print(j)
print(k)
print(l)
print(m)
print()
# In lists,
milestones = [200, 400, 800, 1200, 1600]
i, ii, iii, iv, v = milestones
print(i)
print(ii)
print(iii)
print(iv)
print(v) |
# Dictionaries - used for storing unique key-value pairs
# user = {
# "first_name": "Ian",
# "second_name": "Roberts",
# "email": "ianroberts@mail.co.uk",
# "country": "UK",
# "is_registered": True,
# "user_code": 23409
# }
#
# # available methods...
# user["title"] = "Mr."
# print(user.items())
# print(user.keys())
# print(user.values())
# print(user["is_registered"])
# # the get method does not throw an error if the stated value does not exist
# # unlike the square bracket method, it simply returns "None"
# print(user.get("tax_id"))
# print(user.get("first_name"))
###------- PHONE GAME
user_input = input("Phone number: ")
digit_store = {
"0": "Zero",
"1": "One",
"2": "Two",
"3": "Three",
"4": "Four",
"5": "Five",
"6": "Six",
"7": "Seven",
"8": "Eight",
"9": "Nine"
}
feedback = ""
for char in user_input:
word = digit_store.get(char, "*")
feedback += f"{word} "
print(feedback)
###-----------------------------
# {
# {
# "first_name": "Ian",
# "second_name:": "Roberts",
# "email": "ianroberts@mail.co.uk",
# "country": "UK"
# },
# {
# "first_name": "Joanne",
# "second_name:": "Andrews",
# "email": "jandrw20@gooode.org",
# "country": "ES"
# },
# {
# "first_name": "Meghan",
# "second_name:": "Markle",
# "email": "duchessmeghan@royal.co.uk",
# "country": "CA"
# }
# }
|
first_name = "Dean"
mid_name = "van"
last_name = "Thompson"
multiply_string = "good "
print(first_name, last_name)
print(first_name.isprintable())
print(first_name.upper())
print(mid_name.capitalize())
print(first_name.lower())
print(len(last_name))
print(last_name.find("s"))
print(mid_name.isdigit())
print(mid_name.isalpha())
print(last_name.count("o"))
print(last_name.replace("o", "i"))
# repeat or multiply string
print(multiply_string * 5)
print()
# no need for the plus symbol when it comes to string concatenation
# 1.
print("Your other name should be", last_name, "or", first_name)
print("His name in full is", first_name, last_name)
# 2.
print("Hello " "world")
# 3.
print("It doesn't matter what tomorrow brings along. "
"We'll surely win and dominate there too", end="!!!")
# use the 'end=(string)' to end a given string with a string
# instead of a new line
# print multiple line statements with exact formats
# - works like the HTML <pre> tag
print("""
Because He lives...
I can face tomorrow
""") |
import random
import time
name=input("enter your name : ")
tar=50
play=0
comp=0
def player(play,val):
input("press enter to roll the dice")
dice=random.randint(1,6)
if val==1:
print("entry value : ",dice)
return dice
print(dice)
if play+dice<=tar:
if play==tar-6 and dice==6:
return play
play=play+dice
if dice==6:
play=player(play,0)
return play
def computer(comp,val):
print("my turn")
time.sleep(1)
dice=random.randint(1,6)
if val==1:
print("entry value : ",dice)
return dice
print(dice)
if comp+dice<=tar:
if comp==tar-6 and dice==6:
return comp
comp=comp+dice
if dice==6:
comp=computer(comp,0)
return comp
entry=player(play,1)
entry1=computer(comp,1)
print("="*5,"turn","="*5)
while True:
if entry==6:
play=player(play,0)
if play==comp:
print("beatdown")
comp=0
play=player(play,0)
if play==tar:
break
else:
entry=player(play,1)
if entry1==6:
comp=computer(comp,0)
if comp==play:
print("beatdown")
play=0
comp=computer(comp,0)
if comp==tar:
break
else:
entry1=computer(comp,1)
print(name," = ",play)
print("computer = ",comp)
print("="*5,"turn","="*5)
if play==tar:
print("you win\n","your score = ",play,"\nmy score = ",comp)
else:
print("i win\n","your score = ",play,"\nmy score = ",comp)
|
################################################################################
# 'SNAKEY' GAME
## Adapted by George Deeks from https://gist.github.com/sanchitgangwar/2158089
## Use ARROW KEYS to play and Esc Key to exit
################################################################################
# Import helper libraries
import curses
from curses import KEY_RIGHT, KEY_LEFT, KEY_UP, KEY_DOWN
from random import randint
import time
# Constants to adjust the game difficulty
INIT_WIN_SIZE = (1,1) #Set the window size (width,height)
INIT_LENGTH = 3 #Change the initial length of the snake
INIT_SPEED = INIT_LENGTH #This also sets the initial speed of the snake
INIT_P2 = True #Enable second snake controlled with WASD
# Make sure constants are actually valid
INIT_WIN_SIZE = (max(10,INIT_WIN_SIZE[0]),max(12,INIT_WIN_SIZE[1]))
INIT_LENGTH = max(3, min(int(INIT_WIN_SIZE[0] / 6), INIT_LENGTH))
# Initialise cursor and window properties
curses.initscr()
# game window will be 20 units top to bottom, and 60 units left to right
win = curses.newwin(INIT_WIN_SIZE[0], INIT_WIN_SIZE[1], 0, 0)
win.keypad(1)
curses.noecho()
curses.curs_set(0)
# draw a border for our window
win.border(0)
win.nodelay(1)
# Key constants
KEY_ESC = 27 #Escape key reference number for the computer system
KEY_W = 119
KEY_A = 97
KEY_S = 115
KEY_D = 100
VALID_KEYS = [KEY_LEFT, KEY_RIGHT, KEY_UP, KEY_DOWN, KEY_ESC, KEY_W, KEY_A, KEY_S, KEY_D] #The keys that are used to control the game
OPP_KEY = {KEY_RIGHT:KEY_LEFT, KEY_LEFT:KEY_RIGHT, KEY_UP:KEY_DOWN, KEY_DOWN:KEY_UP, KEY_W:KEY_S, KEY_S:KEY_W, KEY_A:KEY_D, KEY_D:KEY_A} #A dict of opposite keys to prevent backtracking
if not INIT_P2:
VALID_KEYS = [KEY_LEFT, KEY_RIGHT, KEY_UP, KEY_DOWN, KEY_ESC] #The keys that are used to control the game with only 1 player
################################################################################
# INITIALISING VALUES BEFORE THE GAME STARTS
################################################################################
# Initial snake co-ordinates
# Co-ordinates are y-coordinate, then x-coordinate.
# Snake is being placed here approximately in the middle left of our window
snake = []
for y in range(0, INIT_LENGTH):
snake.append([int(INIT_WIN_SIZE[0] / 5), int(INIT_WIN_SIZE[0] / 6)+INIT_LENGTH-y])
if INIT_P2:
snake2 = []
for y in range(0, INIT_LENGTH):
snake2.append([int(INIT_WIN_SIZE[0] / 5) * 2, int(INIT_WIN_SIZE[0] / 6)+INIT_LENGTH-y])
# Initial snake direction
# Snake will move in direction of last arrow key pressed, but initially we will
# set this to right arrow key (so snake starts moving left to right)
key = KEY_RIGHT
key2 = KEY_D
# Print the game title on the top border
if INIT_WIN_SIZE[1] > 21:
win.addstr(0, int(INIT_WIN_SIZE[1] / 2) - 5, " SNAKEY+ ")
# Initial score (Lesson 7)
score = 0
def new_food():
food = []
while food == []:
food = [randint(1, INIT_WIN_SIZE[0] - 2), randint(1, INIT_WIN_SIZE[1] - 2)]
# reset food if it's been randomly assigned a co-ordinate that a
# snake is currently occupying
if food in snake:
food = []
if INIT_P2:
if food in snake2:
food = []
return food
# First food co-ordinates (Lesson 4)
food = new_food()
# Display the food
# 'win' represents where we are playing our game.
# 'addch' will add a single character based on co-ordinates it receives
win.addch(food[0], food[1], '*')
################################################################################
# THE MAIN GAME LOOP (Lesson 1)
################################################################################
# A 'while' loop will repeatedly execute until its stated condition is met, OR
# a 'break' statement is executed inside of it. Each loop iteration will execute
# one movement of the snake and update the game display accordingly.
while True:
# Print current 'Score' string
win.addstr(0, 2, ' Score : ' + str(score) + ' ')
###
# SET THE SPEED 'LEVEL' OF THE GAME (Lesson 8)
###
# We will determine the speed of the snake based on the score:
# 0 will be our slowest speed level
# 120 will be our fastest speed level
# Each time the score increases by 1, we will increase the speed level by 2
# Therefore, speedSetting is double the score value:
speedSetting = 2 * INIT_SPEED + 2 * score
# We want to limit the speed level to our max, which is 120
if speedSetting > 120:
speedSetting = 120
# The higher the speed level, the less time it will take for our program
# to update the latest snake movement, and therefore the game will play
# faster
win.timeout(150 - speedSetting)
###
# HANDLE USER KEY INPUT
###
# Store the previous key selection for future reference
prevKey = key
# Determine if a valid new key has been pressed.
event = win.getch()
# If the new key press is invalid, the program will return -1, otherwise
# we will update our active key pressed selection:
if event != -1:
key = event
# Pause/Resume game (Lesson 6)
# If SPACE BAR is pressed, then wait for another SPACE BAR to be pressed to
# resume game.
if key == ord(' '):
# update display to show game is paused
win.addstr(0, int(INIT_WIN_SIZE[1] / 2) - 5, " *PAUSED* ")
# reset key to invalid value, then keep reading new key presses until
# SPACE BAR has been pressed
key = -1
while key != ord(' '):
key = win.getch()
# Game is now resumed, so let's update display:
if INIT_WIN_SIZE[1] > 21:
win.addstr(0, int(INIT_WIN_SIZE[1] / 2) - 5, " SNAKEY+ ")
# replace SPACE BAR with previous key selection, as if no SPACE BARs had
# ever been pressed!
key = prevKey
if key == KEY_ESC:
lose_string = " YOU QUIT "
lose_string_e = " RIP SNEK "
break
# Ignore useless key selections
# Ignore the latest key press if it is not an arrow key (or Esc key)
if key not in VALID_KEYS or key == OPP_KEY[prevKey] or key == OPP_KEY[key2]:
key = prevKey
elif key in [KEY_W, KEY_A, KEY_S, KEY_D]:
key2 = key
key = prevKey
###
# CALCULATE NEW SNAKEHEAD POSITION (Lesson 2)
###
# Current key selection should now be an arrow key. This arrow key, plus
# the snakehead's current position, can be used to calculate the new
# co-ordinates for the snakehead as it moves one 'square'.
# The snake is an array of 2-length arrays, e.g. = [[4,10], [4,9], [4,8]] -
# this is also known as a 3D array.
# snake[0][0] accesses the snakehead's y-coordinate (e.g., '4')
# snake[0][1] accesses the snakehead's x-coordinate (e.g., '10')
newY = snake[0][0]
if key == KEY_DOWN:
newY += 1
elif key == KEY_UP:
newY -= 1
newX = snake[0][1]
if key == KEY_RIGHT:
newX += 1
elif key == KEY_LEFT:
newX -= 1
# Put new snakehead co-ordinates into start of snake array (position 0)
snake.insert(0, [newY, newX])
# ...Snake is now longer than it should be - unless we're about to eat a
# piece of fruit (Lesson 5). If we decide later on that we're not eating a
# piece of fruit, we must remember to reduce the snake length by cutting off
# its tail. See [1].
#Do the same thing for the second snake if we have one.
if INIT_P2:
newY = snake2[0][0]
if key2 == KEY_S:
newY += 1
elif key2 == KEY_W:
newY -= 1
newX = snake2[0][1]
if key2 == KEY_D:
newX += 1
elif key2 == KEY_A:
newX -= 1
# Put new snakehead co-ordinates into start of snake array (position 0)
snake2.insert(0, [newY, newX])
###
# IF SNAKE REACHES BORDER, MAKE IT ENTER FROM OTHER SIDE (Lesson 3)
###
# For our window, the Y-axis runs from 0 to 19, the X-axis from 0 to 59. (We
# defined this earlier at the top of this file.) However, we have also drawn
# a border (again, see earlier), so actually the snake can move 1 to 18 in
# the Y-axis, and from 1 to 58 in the X-axis. If the snake breaches these
# limits, reposition snakehead so it continues from the other side:
if snake[0][0] == 0:
snake[0][0] = INIT_WIN_SIZE[0] - 2
if snake[0][1] == 0:
snake[0][1] = INIT_WIN_SIZE[1] - 2
if snake[0][0] == INIT_WIN_SIZE[0] - 1:
snake[0][0] = 1
if snake[0][1] == INIT_WIN_SIZE[1] - 1:
snake[0][1] = 1
if INIT_P2:
if snake2[0][0] == 0:
snake2[0][0] = INIT_WIN_SIZE[0] - 2
if snake2[0][1] == 0:
snake2[0][1] = INIT_WIN_SIZE[1] - 2
if snake2[0][0] == INIT_WIN_SIZE[0] - 1:
snake2[0][0] = 1
if snake2[0][1] == INIT_WIN_SIZE[1] - 1:
snake2[0][1] = 1
###
# IF SNAKE CROSSES ITSELF OR ANOTHER SNAKE
###
# [1:] refers to position 1 (i.e., the 2nd element in the array, as we
# count from 0) and onwards.
if INIT_P2:
if snake[0] in snake[1:]:
lose_string = " P1 FAIL "
lose_string_e = " HIT SELF "
break
elif snake2[0] in snake2[1:]:
lose_string = " P2 FAIL "
lose_string_e = " HIT SELF "
break
elif snake[0] in snake2 and snake2[0] in snake:
lose_string = " YOU LOSE "
lose_string_e = " BOTH HIT "
break
elif snake[0] in snake2:
lose_string = " P1 FAIL "
lose_string_e = " HIT P2 "
break
elif snake2[0] in snake:
lose_string = " P2 FAIL "
lose_string_e = " HIT P1 "
break
else:
if snake[0] in snake[1:]:
lose_string = " YOU LOSE "
lose_string_e = " INS COIN "
break
###
# CHECK IF SNAKE HAS EATEN FOOD (Lessons 2 + 3)
###
# If the snakehead co-ordinates match the current food's co-ordinates, then
# the snake will have eaten the food!
if snake[0] == food:
# remove the previous food coordinates
food = []
# add 1 to the score
score += 1
# calculate new food position
food = new_food()
# update display with new food
win.addch(food[0], food[1], '*')
else:
# [1] If snake does not eat food, remember to decrease its length
# remove last snake co-ordinate (its 'tail') from snake array
last = snake.pop()
# update display where snaketail has just been removed
win.addch(last[0], last[1], ' ')
if INIT_P2: #Do the same thing for the other snake, if we have one
if snake2[0] == food:
# remove the previous food coordinates
food = []
# add 1 to the score
score += 1
# calculate new food position
food = new_food()
# update display with new food
win.addch(food[0], food[1], '*')
else:
# [1] If snake does not eat food, remember to decrease its length
# remove last snake co-ordinate (its 'tail') from snake array
last = snake2.pop()
# update display where snaketail has just been removed
win.addch(last[0], last[1], ' ')
###
# DRAW THE SNAKE (Lesson 1)
###
# We can write the head with a '@' character, and ensure those parts that
# are (no longer) the head are drawn as body ('#')
win.addch(snake[1][0], snake[1][1], '#')
win.addch(snake[0][0], snake[0][1], '1')
if INIT_P2:
win.addch(snake2[1][0], snake2[1][1], '#')
win.addch(snake2[0][0], snake2[0][1], '2')
#### End of main game loop ###
################################################################################
# END OF GAME
################################################################################
# Show how the player lost for 3 seconds
start_time = time.time()
for tim in range(1,6):
while start_time + tim > time.time():
if tim % 2 == 0:
win.addstr(0, int(INIT_WIN_SIZE[1] / 2) - 5, lose_string_e)
else:
win.addstr(0, int(INIT_WIN_SIZE[1] / 2) - 5, lose_string, curses.A_STANDOUT)
win.refresh()
# Close window
curses.endwin()
with open("highscore.txt", "r+") as score_file:
score_high = int(score_file.read())
if score_high < score:
print("New high score! Previous high score: " + str(score_high))
score_file.seek(0)
score_file.write(str(score))
score_file.truncate()
else:
print("High score: " + str(score_high))
# Print out score and thank you message
# Each print command will print its message to a new line
print("Your score: " + str(score))
print("Thank you for playing!")
################################################################################
### THANKS FOR PLAYING #########################################################
################################################################################
|
from code.algoritmes.dumbsolver import dumbsolver
from code.algoritmes.dannystra import dannystra
from code.algoritmes.breadth import breadth
from code.helper.play import play
from code.helper.play_2 import play_2
from code.helper.draw_2 import begin
from code.helper.compare import compare
def main():
'''
Main wordt aangeroepen om het programma te starten.
Het heeft geen argumenten en het roept andere functies aan,
aan de hand van de gegeven gebruikers input.'''
bordlist = ['data/game_1.txt', 'data/game_2.txt', 'data/game_3.txt',
'data/game_4.txt', 'data/game_5.txt', 'data/game_6.txt',
'data/game_7.txt']
choice = input('type play, dumbsolve or breadth, compare or test' + " ")
choice = choice.lower()
if choice == 'compare':
gridsize = 6
bord = 'data/game_2.txt'
compare(gridsize, bord)
elif choice != 'test':
nummer = int(input('bord 1, 2, 3, 4, 5, 6 of 7?'))
if nummer <= 3:
gridsize = 6
elif 4 <= nummer <= 6:
gridsize = 9
else:
gridsize = 12
bord = bordlist[int(nummer) - 1]
if choice == 'play':
play(int(gridsize), bord)
elif choice == 'dumbsolve':
dumbsolver(int(gridsize), bord)
elif choice == 'hillclimber':
dannystra(int(gridsize), bord)
elif choice == 'bord':
play_2(int(gridsize), bord)
elif choice == 'compare':
compare(int(gridsize), bord)
elif choice == 'breadth':
breadth(int(gridsize), bord)
else:
print('Dat is geen goede input, probeer het opnieuw')
main()
elif choice == 'test':
gridsize = 6
bord = 'data/game_2.txt'
breadth(int(gridsize), bord)
main()
|
import logging
import operator
import copy
from logs.setup_logs import init_logs
from readers.file_reader import FileReader
logger = init_logs(__name__)
HALT = 99
ADD = 1
MULT = 2
def operate(operand, code_position, register):
"""
This method will modify the register with the requested operation
:param operand: This is an operator function: https://docs.python.org/3/library/operator.html
:param code_position: The position of the opt code we are processing in the register
:param register: The array representing the register
"""
result = operand(register[register[code_position+1]], register[register[code_position+2]])
register[register[code_position+3]] = result
def handle_opt_code(position, register):
code = register[position]
if code == HALT:
logging.info("Final value for position 0 is: %s", register[0])
return -1
elif code == ADD:
operate(operator.add, position, register)
return position + 4
elif code == MULT:
operate(operator.mul, position, register)
return position + 4
def run_program(noun, verb, register):
working_position = 0
register[1] = noun
register[2] = verb
while True:
working_position = handle_opt_code(working_position, register)
if working_position < 0:
return register[0]
int_register = list(map(int, FileReader.read_input_as_string().rstrip().split(',')))
compute_number = 19690720
# logging.info(run_program(12, 2, int_register))
#
# exit(0)
for noun_value in range(0, 99):
for verb_value in range(0, 99):
value = run_program(noun_value, verb_value, copy.deepcopy(int_register))
logging.info("Ran program and got value: %s", value)
if compute_number == value:
logging.info("Successfully did math, noun: %s ; verb: %s ; answer: %s",
noun_value, verb_value, 100 * noun_value + verb_value)
exit(0)
|
from operator import methodcaller
from readers import FileReader
COM = "COM"
def main():
raw_orbits = list(map(methodcaller("split", ")"), map(str.strip, FileReader.read_input_as_list())))
orbits = {o[1]: o[0] for o in raw_orbits}
total_orbits = 0
for planet in orbits.keys():
print(f"Getting count of orbits for planet {planet}")
total_orbits += count_total_path_home(planet, orbits)
print(f"Total number of orbits: {total_orbits}")
def count_total_path_home(planet, orbits, count=0):
if planet in orbits:
count += 1
if orbits[planet] == COM:
print(f"{count} orbits for this planet")
return count
return count_total_path_home(orbits[planet], orbits, count)
print(f"This is odd, did not expect to get here! Processing: {planet}")
return count
if __name__ == "__main__":
main()
|
import random
n = random.randrange(1, 20, 2)
print("I am thinking of a number between 1 and 20. Take a guess.")
def inputnum():
a = int(input())
return a
def GuessGame():
b = inputnum()
for i in range(1, 6):
if n == b:
print("Good job! You guessed my number in " + str(i) + " guesses!")
break
elif ((n-3) <= b and b < n) or (b > n and b <= (n+3)):
print("Your guess is too high. Take a guess.")
c = inputnum()
elif(n != b):
print("Your guess is too low.")
c = inputnum()
b = c
i+=1
return
GuessGame()
|
str1='abcsadfadsfgfegegegea'
j = 0
dict1={}
for i in str1:
j+=1
dict1.update({i:j})
print (dict1) |
# -*- coding: utf-8 -*-
# @Time : 2019/1/7 20:36
# @Author : for
# @File : 01_copy_test.py
# @Software: PyCharm
import copy
a = [1,2,3,4,[5,6,7]]
b = a
print('a 的 id : %s ,b 的 Id %s '%(id(a),id(b)))
#深copy
d = copy.deepcopy(a)
print('d 的 id',id(d))
#浅copy
c = copy.copy(a)
print(id(c))
a.append(8)
a[4].append(9)
print(a)
print(b)
print(c)#浅
print(d)#深的
|
n=int(input('请输入递归数'))
result=1
i=1
while i<=n:
result = result*i
i+=1
print(result) |
"""
@File : 2_简单的绘图实例.py
@Time : 2020/4/15 3:31 下午
@Author : FeiLong
@Software: PyCharm
"""
import numpy
from matplotlib import pyplot
# 定义x轴的坐标
x=numpy.arange(1,11)
# 定义y轴的坐标
y=2*x+5
# 坐标图的标题
pyplot.title('Matplotlib Demo')
# x轴的名称
pyplot.xlabel('x axes')
# y轴的名称
pyplot.ylabel('y axes')
# 设置坐标参数
xp=[1,2,3,4]
yp=[7,6,5,4]
# 根据坐标参数绘制
pyplot.plot(xp,yp)
# 展示
pyplot.show()
|
a=[1,2,3,5,7,2,9,6,3,5,4]
for i in a:
if i==max(a):
print('最大值是%d'%i)
elif i==min(a):
print('最小值是%d'%i)
|
'''
对象:万物皆对象,就是事实存在的事物
类: 是对事物的划分,当我们在描述的时候用到类,就是在描述一系列的事物的共性特征,比如:鸟类,我们想要说的是所有鸟的共性比如:卵生,羽毛
实例: 从类当中具体映射出来的个体,比如鸟类当中的鸵鸟
类和实例都有自己独立的内存空间,相互独立互不影响,实例来源于类但是比类更具有个性
'''
'''
域: 属于类或者实例的变量,一些名词,例如name,age……
方法:属于类或者实例的功能(函数),一般来说是函数。一些动词,吃,喝……
属性: 域和方法的统称
类方法:属于类的功能
类属性:属于类的属性
实例方法:属于实例的功能
实例属性:属于实例的属性
'''
#####面向对象:在编程过程当中,把数据及对数据的操作方法放在一起,作为一个相互依存的整体,用这样的思路编程就是面向对象。
# 在编程过程当中,把数据及对数据的操作方法放在一起,作为一个相互依存的整体,用这样的思路编程就是面向对象。
class Registration():
def __init__(self):
self.school={
'linux':[],
'Python':[]
}
def regster(self,major,student):
if major in self.school:
self.school[major].append(student)
print('报名成功')
else:
print('学校没有你想要学习的%s专'%major)
if __name__ == '__main__':
student={'name':'for','age':18,'gender':'男','major':'Python'}
# 将类实例化为对象
reg=Registration()
reg.regster(student.get('major'),student)
print(reg.school)
|
# 导入套接字
import socket
# 创建一个套接字
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# 绑定端口,参数为元组,''代表本地所有的IP
sock.bind(('',8080))
# 监听最大的端口为5
sock.listen(5)
#接收连接请求
#conntent 用来接收请求用户的消息和发送对该用户的的消息功能
#address 是请求用户的身份(ip,port)
conntent,address=sock.accept()
print('%s:%s id connectent...'%address)
# 发送数据,encode()编码
conntent.send('hello'.encode())
# 接受数据参数是字节的形式,decode()解码
print(conntent.recv(521).decode())
# 关闭套接字
sock.close |
#####常规继承
# class Admin():
# def eat(self):
# print('吃。。。')
# def drink(self):
# print('喝。。。')
# class Dog(Admin):
# def eat(self):
# print('狗在吃')
# def call(self):
# print('狗在喝')
# class Cat(Admin):
# def catch(self):
# print('猫抓老鼠')
#
# # 将类实例为对象
# d=Dog()
# # 使用类对象调用父类的方法
# d.eat()
# tom=Cat()
# tom.eat()
# tom.catch()
#####继承中的私有属性和方法
# class Admin():
# # 私有实例方法属性
# def __init__(self,name='汪汪',color='yellow'):
# self.__name=name
# self.color=color
# def eat(self):
# print('吃。。。')
# def drink(self):
# print('喝。。。')
# # 私有类方法
# def __test(self):
# print(self.color)
# # 方法调用私有实例方法属性
# def print_info(self):
# print(self.__name)
# class Dog(Admin):
# def eat(self):
# print('狗吃。。。')
# def call(self):
# print('汪汪。。。')
# # 把类实例化为对象
# d=Dog()
# # 访问父类的方法
# d.drink()
# print(d.color)
'''
私有的属性、方法,不会被子类继承,也不能被访问
'''
#####多继承:多个子类有同一个父类,并且具有他们的特征
# class Base():
# def func(self):
# print('属于Base类')
# class A_class(Base):
# def func_A(self):
# print('这个是func_A函数')
# class B_class(Base):
# def func_B(self):
# print('这个是func_B函数')
# class C_class(B_class,A_class):
# pass
# # 将类实例化为对象
# c=C_class()
# # 通过类对象调用父类的方法
# c.func()
# c.func_A()
# c.func_B()
# 查看访问顺序
# print(c.__class__.mro())
#####更改c类中的继承顺序
# class Base():
# def func(self):
# print('属于Base类')
# class A_class(Base):
# def func_A(self):
# print('这个是func_A函数')
# class B_class(Base):
# def func_B(self):
# print('这个是func_B函数')
# class C_class(A_class,B_class):
# pass
# # 将类实例为对象
# c=C_class()
# print(c.__class__.mro())
'''
说明:
1、python中是可以多继承的并且父类中的方法、属性,子类也会继承
2、python3中多继承遵循mro算法顺序当中的,先广度后深度的原理
3、只会执行一次__init__()文件
'''
'''
总结:
子类在继承的时候,在定义类时,小括号中为父类的类名
子类继承后,父类的属性、方法,都会被继承给子类
私有属性,不能通过对象去直接访问,但是可以通过创建新方法去访问
私有方法,不能通过对象直接访问
私有的属性、方法,不会被子类继承,也不能被访问
'''
|
#####获取异常的信息
# def func():
# try:
# print(a)
# except Exception as e:
# print(e)
# func()
#####没有捕捉到异常就会执行else中的代码
# def func():
# a='我是你爸爸'
# try:
# print(a)
# except Exception as e:
# print(e)
# else:
# print('没有捕捉到异常就执行else中的代码')
# func()
#####finally是不管有没有异常都会执行的代码
# def func():
# a='我是你爸爸'
# try:
# print(a)
# except Exception as e:
# print(e)
# else:
# print('没有异常时执行else下的代码')
# finally:
# print('不管有没有异常都会执行finally中的代码')
# func()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.