text
stringlengths 37
1.41M
|
---|
def leftRotate(arr, n, k):
# To get the starting point of rotated array
mod = k % n
s = ""
# Prints the rotated array from start position
for i in range(n):
print(str(arr[(mod + i) % n]),end=" ");
return
# Driver program
a, k = input().split()
arr = list(map(int, input().rstrip().split()))
n = len(arr)
leftRotate(arr, n, int(k))
|
"""
Robb Doering
[email protected]
This program fetches the records of individual congress members that are currently
in office. It can be asked about who a certain member is, how their voting history compares
to those of any individual colleague, or their committee memberships.
For publishing on the Amazon Alexa store.
"""
from __future__ import print_function
from urllib2 import Request, urlopen, URLError
import json
# --------------- Helpers that build all of the responses ----------------------
def build_speechlet_response(title, output, reprompt_text, should_end_session):
return {
'outputSpeech': {
'type': 'PlainText',
'text': output
},
'card': {
'type': 'Simple',
'title': title,
'content': output
},
'reprompt': {
'outputSpeech': {
'type': 'PlainText',
'text': reprompt_text
}
},
'shouldEndSession': should_end_session
}
def build_response(session_attributes, speechlet_response):
return {
'version': '1.0',
'sessionAttributes': session_attributes,
'response': speechlet_response
}
# --------------- Functions that control the skill's behavior ------------------
def get_welcome_response():
session_attributes = {}
card_title = "Welcome"
speech_output = "Welcome to the Congress Record. " \
"Please ask me about a congressman currently in office " \
"by saying something like " \
"'Who is Paul Ryan?' " \
"or, " \
"'How is Paul Ryan compared to Nancy Polosi?'" \
# If the user either does not reply to the welcome message or says something
# that is not understood, they will be prompted again with this text.
reprompt_text = "Do you have question for me?" \
"I can tell you about congressman, compare them to others, or give you committee membership details."
should_end_session = False
return build_response(session_attributes, build_speechlet_response(
card_title, speech_output, reprompt_text, should_end_session))
def get_help_response():
session_attributes = {}
card_title = "Help"
speech_output = "I am here to help you keep congresss accountable. " \
"Congressional Records knows all about people currently serving in congress, " \
"as well as all of their memberships in committees, one of the " \
"most important responsiblities of any congress person. " \
"Try asking about individuals, how they're compared to others, " \
"or their committee memberships. " \
# If the user either does not reply to the welcome message or says something
# that is not understood, they will be prompted again with this text.
reprompt_text = None
should_end_session = True
return build_response(session_attributes, build_speechlet_response(
card_title, speech_output, reprompt_text, should_end_session))
def handle_session_end_request():
card_title = "Session Ended"
speech_output = "Thank you for checking up on your government. " \
"Stay informed! "
# Setting this to true ends the session and exits the skill.
should_end_session = True
return build_response({}, build_speechlet_response(
card_title, speech_output, None, should_end_session))
def getCongressId(intent, name, currentMembers):
'''
This function only works for currently serving members.
If only one valid response is found, it returns just the ID.
If more than are found, it returns a tuple of tuples, each containing an id:name pair.
Also always returns reprompt text, which is simply None if no issues were found.
'''
validResponses = ()
reprompt_text = None
name = name.lower()
#This checks current members for the name, checking both full names and just first + last.
#Should be decently fast, on personal clock double checking didn't effect speed over 50ms
for element in currentMembers:
first = element['name']['first'].lower()
last = element['name']['last'].lower()
full = element['name']['official_full'].lower()
if 'nickname' in element['name']:
nickname = element['name']['nickname'].lower()
booleanMatch = (full == name or first + ' ' + last == name or nickname + ' ' + last == name)
else:
booleanMatch = (full == name or first + ' ' + last == name)
if booleanMatch:
validResponses += ((element['id']['bioguide'], element['name']['official_full']),)
#This searches all congressman with a vaguely similar name, if no real matches were found.
if (len(validResponses) == 0):
usersFirst = name.split(' ')[0]
usersLast = name.split(' ')[-1]
for element in currentMembers:
first = element['name']['first'].lower()
last = element['name']['last'].lower()
if 'nickname' in element['name']:
nickname = element['name']['nickname'].lower()
else:
nickname = ''
booleanMatch = (first == name or last == name or nickname == name
or first == usersFirst or last == usersLast)
if booleanMatch:
validResponses += ((element['id']['bioguide'], element['name']['official_full']),)
#if only one response was found, it returns that result.
if (len(validResponses) == 1):
return (validResponses[0][0], reprompt_text)
#if none were found, it passes a simple error (what else could be done?)
if (len(validResponses) == 0):
reprompt_text = "Sorry, I couldn't recognize the name " + name + ". " \
"I work best with both the first and last names of someone serving in the current congress. " \
"Please try stating your request again."
return (validResponses, reprompt_text)
#and if many were found, it continues to the next block
#This block is built to activate if the initital search turned up more than one, OR if the second less formal search did
if (len(validResponses) > 1):
concatenatedNames = ""
for element in validResponses:
(state, party) = getBasicDetails(('state', 'party'), element[0], currentMembers)
#This simple if block with check if the user has already specified what state and party the legislator belongs to
if 'state' in intent['slots']:
if 'state' == intent['slots']['state']:
return (cantidate[0], None)
#Else, this statement when looped creates a meaningful response to clarify.
concatenatedNames += "{0}, the {1} from {2}, or ".format(element[1], party, state)
reprompt_text = "It looks like there's multiple legistlators with the same name. " \
"Please ask again, specifying either " + concatenatedNames[0:-5] + "."
else:
validResponses = validResponses[0][0]
return (validResponses, reprompt_text)
def getBasicDetails(desiredResults, ID, currentMembers):
'''
OPTIONS: name, elected, state, party, house
can change order of input, but output is ALWAYS in that order
(congressmanName, electedDate, state, party, house) =
getBasicDetails(('name', 'elected', 'state', 'party', 'house'), ID, currentMembers)
'''
results = ()
profile = ""
for element in currentMembers:
if element['id']['bioguide'] == ID:
profile = element
break
if 'name' in desiredResults:
results += (profile['name']['first'] + ' ' + profile['name']['last'],)
#finds the year when they were first elected to the house
if 'elected' in desiredResults:
results += (profile['terms'][0]['start'][0:4],)
#gives the two digit state code.
if 'state' in desiredResults:
results += (profile['terms'][-1]['state'],)
#finds the party the legislator was most recently part of
if 'party' in desiredResults:
results += (profile['terms'][-1]['party'],)
#finds the house of congress they have served in. Either 'house', 'senate', or 'both houses of congress'
if 'house' in desiredResults:
houseCount = [0, 0]
for term in profile['terms']:
if term['type'] == 'rep':
houseCount[0] += 1
elif term['type'] == 'sen':
houseCount[1] += 1
houseCount = (str(houseCount[0]), str(houseCount[1]))
results += (houseCount,)
return results
def general_record_check(intent, session, currentMembers):
'''
This function handles the intent asking about the basic details of some specific congressman.
Returns a response properly formatted to work with Alexa.
'''
card_title = "General Record Info"
session_attributes = {}
should_end_session = True
speech_output = ""
congressmanName = (intent['slots']['congressman']['value'])
(ID, reprompt_text) = getCongressId(intent, congressmanName, currentMembers)
#This checks whether an individual congressman was found before continuing
if reprompt_text != None:
return build_response(session_attributes, build_speechlet_response(
card_title, reprompt_text, reprompt_text, False))
#And upon continuing, it gets all the basic details of the congressman and creates a sentence
(congressmanName, electedDate, state, party, house) = getBasicDetails(('name', 'elected',
'state', 'party', 'house'), ID, currentMembers)
speech_output = "{0} is a {1} hailing from {2}, first elected to congress in {3}. " \
"They have served {4} terms in the house, and {5} terms in the senate.".format(
congressmanName, party, state, electedDate, house[0], house[1])
return build_response(session_attributes, build_speechlet_response(
card_title, speech_output, reprompt_text, should_end_session))
def individual_committee_check(intent, session, currentMembers):
'''
This function handles the intent asking about the committee memberships of a congressman.
Returns a response properly formatted to work with Alexa.
'''
card_title = "Individual Committee Info"
session_attributes = {}
should_end_session = True
speech_output = ""
congressmanName = (intent['slots']['congressman']['value'])
(ID, reprompt_text) = getCongressId(intent, congressmanName, currentMembers)
if reprompt_text != None:
return build_response(session_attributes, build_speechlet_response(
card_title, reprompt_text, reprompt_text, False))
committeeAssignments = {}
with open('committee_members.json') as data:
jsonData = json.load(data)
for committee in jsonData:
for member in jsonData[committee]:
if member['bioguide'] == ID:
committeeAssignments[committee] = member['rank']
speech_output = congressmanName + ' holds the chair of rank '
count = 0
for assignment in committeeAssignments:
if count == (len(committeeAssignments) - 1) and len(committeeAssignments) != 1:
speech_output += 'and {0} in the {1}.'.format(committeeAssignments[assignment], assignment)
else:
speech_output += '{0} in the {1}, '.format(committeeAssignments[assignment], assignment)
count = count + 1
return build_response(session_attributes, build_speechlet_response(
card_title, speech_output, reprompt_text, should_end_session))
def record_compare(intent, session, currentMembers):
'''
This function handles the intent asking about how two congresspeople compare.
Returns a response properly formatted to work with Alexa.
'''
card_title = "Comparison"
session_attributes = {}
should_end_session = True
speech_output = 'I\'m sorry, I couldn\'t find one of those congressman in my records'
congressmanName1 = (intent['slots']['congressmanOne']['value'])
congressmanName2 = (intent['slots']['congressmanTwo']['value'])
(ID1, reprompt_text1) = getCongressId(intent, congressmanName1, currentMembers)
(ID2, reprompt_text2) = getCongressId(intent, congressmanName2, currentMembers)
#First checks that both congressman were found
if reprompt_text1 != None:
return build_response(session_attributes, build_speechlet_response(
card_title, reprompt_text1, reprompt_text1, False))
if reprompt_text2 != None:
return build_response(session_attributes, build_speechlet_response(
card_title, reprompt_text2, reprompt_text2, False))
#Then looks for each, so we know if they ever served at the same time
for element in currentMembers:
if element['id']['bioguide'] == ID1:
houseHistory1 = ''
for term in element['terms']:
if term['type'] == 'sen': houseHistory1 += 'S'
else: houseHistory1 += 'H'
continue
if element['id']['bioguide'] == ID2:
houseHistory2 = ''
for term in element['terms']:
if term['type'] == 'sen': houseHistory2 += 'S'
else: houseHistory2 += 'H'
#This would mess up for senators who had a break in their service, but according to wikipedia that is such a rare
#occurence that this will work for now. To fix, also check the dates on each membership.
MAX_SEARCH_LENGTH = 3
minLength = min(len(houseHistory1), len(houseHistory2), MAX_SEARCH_LENGTH)
#this truncates each to only be as long as neccesary.
houseHistory1 = houseHistory1[-minLength:]
houseHistory2 = houseHistory2[-minLength:]
totalVotesShared = 0
votesDisagree = 0
#loops through all congresses that they were both in. Will just skip to the return if one wasn't found.
for num in range(0, minLength):
#skips this iteration if they weren't in the same house during these years
if houseHistory1[-(num + 1)] != houseHistory2[-(num + 1)]:
continue
if houseHistory1[-(num + 1)] == 'H':
house = 'house'
else:
house = 'senate'
#This does the actual work of counting the shared votes
response = Request("https://api.propublica.org/congress/v1/members/{0}/votes/{1}/{2}/{3}.json".format(
ID1, ID2, 115 - num, house), headers={"X-API-Key" : "DIl7ejWZz5ajxyzYyOjDN89YLp1xekEb1mjWkjq1"})
response = urlopen(response)
votes = json.load(response)
totalVotesShared = totalVotesShared + votes['results'][0]['common_votes']
votesDisagree = votesDisagree + votes['results'][0]['disagree_votes']
if totalVotesShared == 0:
speech_output = '{0} and {1} have never voted on the same issue, most likely because they weren\'t' \
' in the same house of congress at the same time'.format(congressmanName1, congressmanName2)
else:
percentage = 100 * (totalVotesShared - votesDisagree) / float(totalVotesShared)
percentage = '%.0f' % percentage
speech_output = '{0} and {1} have voted on the same issue {2} times, ' \
'and agreed about {3} percent of the time.'.format(
congressmanName1, congressmanName2, totalVotesShared, percentage)
return build_response(session_attributes, build_speechlet_response(
card_title, speech_output, reprompt_text1, should_end_session))
# --------------- Events ------------------
def on_session_started(session_started_request, session):
""" Called when the session starts """
print("on_session_started requestId=" + session_started_request['requestId']
+ ", sessionId=" + session['sessionId'])
def on_launch(launch_request, session):
""" Called when the user launches the skill without specifying what they
want
"""
print("on_launch requestId=" + launch_request['requestId'] +
", sessionId=" + session['sessionId'])
# Dispatch to your skill's launch
return get_welcome_response()
def on_intent(intent_request, session):
""" Called when the user specifies an intent for this skill """
print("on_intent requestId=" + intent_request['requestId'] +
", sessionId=" + session['sessionId'])
intent = intent_request['intent']
intent_name = intent_request['intent']['name']
with open('current_members.json') as data:
currentMembers = json.load(data)
# Dispatch to your skill's intent handlers
# Each block here first checks for valid input, and ensures no empty values
if intent_name == "generalRecordCheck":
if 'value' not in intent['slots']['congressman']:
speech_output = 'I\'m sorry, I didn\'t catch a name in that question. Please try again.'
return build_response({}, build_speechlet_response(
'Error', speech_output, None, False))
return general_record_check(intent, session, currentMembers)
elif intent_name == "indivCommitteeCheck":
if 'value' not in intent['slots']['congressman']:
speech_output = 'I\'m sorry, I didn\'t catch a name in that question. Please try again.'
return build_response({}, build_speechlet_response(
'Error', speech_output, None, False))
return individual_committee_check(intent, session, currentMembers)
elif intent_name == "recordCompare":
if 'value' not in intent['slots']['congressmanOne'] or 'value' not in intent['slots']['congressmanTwo']:
speech_output = 'I\'m sorry, I only heard the name of one congressman. Please try again.'
return build_response({}, build_speechlet_response(
'Error', speech_output, None, False))
return record_compare(intent, session, currentMembers)
elif intent_name == "AMAZON.HelpIntent":
return get_help_response()
elif intent_name == "AMAZON.CancelIntent" or intent_name == "AMAZON.StopIntent":
return handle_session_end_request()
else:
raise ValueError("Invalid intent")
def on_session_ended(session_ended_request, session):
""" Called when the user ends the session.
Is not called when the skill returns should_end_session=true
"""
print("on_session_ended requestId=" + session_ended_request['requestId'] +
", sessionId=" + session['sessionId'])
# add cleanup logic here
# --------------- Main handler ------------------
def lambda_handler(event, context):
""" Route the incoming request based on type (LaunchRequest, IntentRequest,
etc.) The JSON body of the request is provided in the event parameter.
"""
print("event.session.application.applicationId=" +
event['session']['application']['applicationId'])
"""
Uncomment this if statement and populate with your skill's application ID to
prevent someone else from configuring a skill that sends requests to this
function.
"""
#if (event['session']['application']['applicationId'] !=
# "amzn1.ask.skill.ef0a117c-a47d-4ca5-97d3-570f9383c01a"):
# raise ValueError("Invalid Application ID")
if event['session']['new']:
on_session_started({'requestId': event['request']['requestId']},
event['session'])
if event['request']['type'] == "LaunchRequest":
return on_launch(event['request'], event['session'])
elif event['request']['type'] == "IntentRequest":
return on_intent(event['request'], event['session'])
elif event['request']['type'] == "SessionEndedRequest":
return on_session_ended(event['request'], event['session'])
|
'''
Generate edges on a graph using preferential
attachment. The first node is selected randomly and
the second is selected using preferential attachment.
'''
import networkx as nx
import random as rand
import sys
import matplotlib.pyplot as plt
NODES = 100
STEP = 5
list_to_randomize = []
def add_preferential_edge(node_list, graph):
global list_to_randomize
rand_val1 = rand.choice(node_list)
rand_val2 = rand_val1
while rand_val2 == rand_val1:
rand_val2 = rand.choice(list_to_randomize)
if graph.has_edge(rand_val1, rand_val2) is False:
list_to_randomize.append(rand_val1)
list_to_randomize.append(rand_val2)
graph.add_edge(rand_val1, rand_val2)
def generate_connected_graph(node_count):
global list_to_randomize
node_list = range(0, node_count)
list_to_randomize = list(node_list)
graph = nx.Graph()
graph.add_nodes_from(node_list)
for i in range(1, node_count):
add_preferential_edge(node_list, graph)
while nx.is_connected(graph) == False:
add_preferential_edge(node_list, graph)
return graph
#########################################
if len(sys.argv) > 1:
try:
NODES = int(sys.argv[1])
except:
print("invalid int, using " + str(NODES))
print("Number of nodes: "+str(NODES))
print("default is 100, configurable by argument")
### Configure plot
fig = plt.figure()
fig.canvas.set_window_title('Preferential attachment')
plt.title('Generation of edges on a graph')
plt.xlabel('# of nodes')
plt.ylabel('degree')
stats = {}
graph = generate_connected_graph(NODES)
for (i, j) in graph.degree():
try:
stats[j] += 1
except:
stats[j] = 1
coords = []
for i in stats:
coords.append((i, stats[i]))
coords.sort(key = lambda x : x[0], reverse = False)
keys, values = zip(*coords)
plt.plot(values, keys, 'ro-')
plt.show()
|
import multiprocessing
import time
def worker(d, key, value):
d[key] = value
def reader(d):
while True:
for k ,v in dict(d).items():
print(k)
time.sleep(1)
if __name__ == '__main__':
mgr = multiprocessing.Manager()
d = mgr.dict()
jobs = [ multiprocessing.Process(target=worker, args=(d, i, i*2))
for i in range(10)
]
p = multiprocessing.Process(target=reader, args=(d,))
p.start()
for j in jobs:
j.start()
for j in jobs:
j.join()
p.join()
print ('Results:' )
|
import math
def sieveOfErat(n):
import math
primes = [True] * (n+1)
primes[0] = False
primes[1] = False
for i in range(2, int(math.sqrt(len(primes)))):
if primes[i]:
for j in range(i*i, len(primes), i):
primes[j] = False
return [i for i in range(len(primes)) if primes[i]]
def DimensionDistance(a, b, primes,case):
factors = []
apowers = []
bpowers = []
i = 0
while (i < len(primes)) and (primes[i] <= a or primes[i] <= b):
t = primes[i]
# print "t:",t
if a%t == 0 and not t in factors:
# print t, "|", a
factors.append(t)
# print [element for element in afactors]
apowers.append(0)
bpowers.append(0)
if b%t == 0 and not t in factors:
# print t, "|", b
factors.append(t)
# print [item for item in bfactors]
bpowers.append(0)
apowers.append(0)
i+= 1
# print "Factors:", [el for el in factors]
countera = a
counterb = b
# print "apowers, bpowers"
# print [h for h in apowers]
# print [h for h in bpowers]
while(countera > 1 or counterb > 1):
for j in range(0, len(factors)):
if(countera%factors[j] == 0):
countera /= factors[j]
apowers[j] += 1
if(counterb%factors[j] == 0):
counterb /= factors[j]
bpowers[j] += 1
# print "apowers, bpowers"
# print [h for h in apowers]
# print [h for h in bpowers]
# print "Powers of factors of a", [kaliph for kaliph in apowers]
# print "Powers of factors of b", [pop for pop in bpowers]
n = len(factors)
# print "Number of axes: ", n
# print "Powers of factors of a", [kaliph for kaliph in apowers]
# print "Powers of factors of b", [pop for pop in bpowers]
distance = 0
for m in range(len(bpowers)):
distance += abs(bpowers[m] - apowers[m])
outp = str(case) +". " + str(n) + ":" + str(distance)
# print "miffles"
print outp
# END DIMENSION DISTANCE
primes = sieveOfErat(1000000)
a = 1
b = 1
case = 0
while(a != 0 and b != 0):
case += 1
inp = raw_input().split()
a = int(inp[0])
b = int(inp[1])
if (a == b == 0):
break
DimensionDistance(a, b, primes, case)
|
def substring(A, B):
A = str(A)
B = str(B)
for b in B.split():
if not b in A.split():
return 0
return 1
elements of computing
|
__author__ = 'sunary'
class SortedWords():
def __init__(self):
self.words = []
def set(self, sorted_list):
self.words = sorted_list
def add(self, word=None, list_word=None):
'''
add word or list of words to sorted list
Args:
word: the word need to add
list_word: the list of words need to add
'''
if not self.words:
if word:
self.words.append(word)
return
else:
self.words.append(list_word[0])
del list_word[0]
if word:
position = self.find(word)
if word != self.words[position]:
self.words[position + 1:position + 1] = [word]
else:
for w in list_word[0:]:
position = self.find(w)
if w != self.words[position]:
self.words[position + 1:position + 1] = [w]
def find(self, word):
'''
position of word in sorted list
Args:
word: input word
Returns:
position of input word
'''
if not word:
return 0
left_position = 0
right_position = len(self.words) - 1
mid_position= (left_position + right_position)/2
mid_value = self.words[mid_position]
while left_position <= right_position:
if word < mid_value:
right_position = mid_position - 1
else:
left_position = mid_position + 1
mid_position = (left_position + right_position)/2
mid_value = self.words[mid_position]
return left_position - 1
def exist(self, word='', position_word=0):
if word:
position = self.find(word)
else:
position = position_word
return word == self.words[position]
if __name__ == '__main__':
sorted_words = SortedWords()
sorted_words.add(list_word = ['w', 'c', 'd', 'ff', 'b', 'c', 'ff'])
print sorted_words.find('c')
print sorted_words.words |
"""
The Western Suburbs Croquet Club has two categories of membership, Senior and Open.
They would like your help with an application form that will tell prospective members which category they will be placed.
To be a senior, a member must be at least 55 years old and have a handicap greater than 7.
In this croquet club, handicaps range from -2 to +26; the better the player the lower the handicap.
"""
#Solution-1
def openOrSenior(data):
output = []
for i in data:
if i[0] > 54 and i[1] > 7:
output.append('Senior')
else:
output.append('Open')
return output
print (openOrSenior([[18, 20],[45, 2],[61, 12],[37, 6],[21, 21],[78, 9]]))
#Solution-2
def openOrSenior(data):
return ["Senior" if m[0]>54 and m[1]>7 else "Open" for m in data]
print (openOrSenior([[18, 20],[45, 2],[61, 12],[37, 6],[21, 21],[78, 9]]))
|
def counVowels(str):
vowels = 0
for i in str.lower():
if (i == 'a' or i == 'e' or i == 'i' or i == 'o' or i == 'u'):
vowels = vowels + 1
print("The Vowels in the String <",str,"> are : ",vowels)
str = input("Enter an String : ")
counVowels(str) |
from copy import deepcopy
from os import system
from queue import Queue
from random import randint, seed
MAX_COL = 4
MAX_ROW = 4
SHUFFLE_MAGNITUDE = 20
class board:
""" game board """
def __init__(self):
""" construct a board """
self.goal = [[" 1", " 2", " 3", " 4"],
[" 5", " 6", " 7", " 8"],
[" 9", "10", "11", "12"],
["13", "14", "15", "__"]]
self.board1 = deepcopy(self.goal)
self.empty_loc = [MAX_ROW - 1, MAX_COL - 1]
#print(self.empty_loc)
self.moves = {0:self.move_up, 1:self.move_right, 2:self.move_down, 3:self.move_left}
def __repr__(self):
""" represent the board """
for i in range(MAX_ROW):
for j in range(MAX_COL):
print(self.board1[i][j], end=" ")
print()
# __repr__ must return something
return ""
def refresh(self):
""" clear screen and print board """
system("clear")
print("Puzzle Fifteen\n")
print(self)
if self.board1 == self.goal:
print("\nCongrats! You Won!")
return False
return True
def shuffle(self):
""" randommizes board """
seed()
for i in range(SHUFFLE_MAGNITUDE):
m = randint(0, 3)
self.moves[m](self.board1,self.empty_loc)
#move the empty space to the right corner
for i in range(MAX_ROW):
self.moves[2](self.board1, self.empty_loc)
for i in range(MAX_COL):
self.moves[1](self.board1, self.empty_loc)
def move(self, board1, empty_loc, x, y):
""" makes legal move """
#check legality of move
if empty_loc[0] + x < 0 or empty_loc[0] + x > 3 or empty_loc[1] + y < 0 or empty_loc[1] + y > 3:
return board1, empty_loc
#swap
board1[empty_loc[0]][empty_loc[1]], board1[empty_loc[0] + x][empty_loc[1] + y] = board1[empty_loc[0] + x][empty_loc[1] + y], board1[empty_loc[0]][empty_loc[1]]
#update empty location
empty_loc[0] += x # empty_loc[0] -> empty_row -> x
empty_loc[1] += y # empty_loc[1] -> empty_col -> y
return board1, empty_loc
def move_up(self, board1, empty_loc):
return self.move(board1, empty_loc, -1, 0) #x -> row | y -> col
def move_right(self, board1, empty_loc):
return self.move(board1, empty_loc, 0, 1)
def move_down(self, board1, empty_loc):
return self.move(board1, empty_loc, 1, 0)
def move_left(self, board1, empty_loc):
return self.move(board1, empty_loc, 0, -1)
def solve(self):
""" solves the game using Breath First Search algorithm """
#self.board1 = deepcopy(self.goal)
def successors(board1, empty_loc):
board1_lst = [deepcopy(board1),deepcopy(board1),deepcopy(board1),deepcopy(board1)]
empty_loc_lst = [list(empty_loc),list(empty_loc),list(empty_loc),list(empty_loc)]
board1_lst[0], empty_loc_lst[0] = self.move_up(board1_lst[0], empty_loc_lst[0])
board1_lst[1], empty_loc_lst[1] = self.move_right(board1_lst[1], empty_loc_lst[1])
board1_lst[2], empty_loc_lst[2] = self.move_down(board1_lst[2], empty_loc_lst[2])
board1_lst[3], empty_loc_lst[3] = self.move_left(board1_lst[3], empty_loc_lst[3])
return [[board1_lst[0], empty_loc_lst[0], 0], [board1_lst[1], empty_loc_lst[1], 1], [board1_lst[2],
empty_loc_lst[2], 2], [board1_lst[3], empty_loc_lst[3], 3]]
searched = set()
fringe = Queue()
fringe.put({"board1": self.board1, "empty_loc": self.empty_loc, "path": []})
while True:
#quit if no solution is found
if fringe.empty():
return []
#inspect cuurent node
node = fringe.get()
#quit if node contains goal
if node["board1"] == self.goal:
return node["path"]
#add current node to searched set: put children in fringe
if str(node["board1"]) not in searched:
searched.add(str(node["board1"]))
for child in successors(node["board1"], node["empty_loc"]):
if str(child[0]) not in searched:
fringe.put({"board1": child[0], "empty_loc": child[1], "path": node["path"] +
[child[2]]})
|
# dict 활용
# dict 과 map, zip을 이용해봅시당
# A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
#
#
# input
# 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 221 222 223 224 225 226
# XYZ
# output
# 456
# 일의 자리수만 뽑아서 매칭
my_dict = dict()
before = [chr(ord('A')+i) for i in range(26)]
# A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
after = list(map(lambda x: int(x)%10 , input().split()))
# 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6
# after = [after[i]%10 for i in range(len(after))]
for k, v in zip(before, after):
my_dict.setdefault(k, v)
test = input()
for i in test:
print(my_dict[i], end='') |
#!usr/bin/python
#This is an attempt at making a shut the box game!
import sys
import pygame
import random
pygame.init()
size = width, height = 1200, 800
black = (0,0,0)
white = (255,255,255)
red = (255, 0, 0)
green = (0,255,0)
blue = (0, 0, 255)
turquoise = (0, 100, 155)
screen = pygame.display.set_mode(size)
pygame.display.set_caption('Shut the Box')
clock = pygame.time.Clock()
dice1 = pygame.image.load("dice1.png")
dice2 = pygame.image.load("dice2.png")
dice3 = pygame.image.load("dice3.png")
dice4 = pygame.image.load("dice4.png")
dice5 = pygame.image.load("dice5.png")
dice6 = pygame.image.load("dice6.png")
list = pygame.image.load("list.jpg")
red_x = pygame.image.load("red_x.png")
complete = False
print("This is a Dice Rolling Program")
print("Try and shut the box!")
roll_total = 0
dice_total = 0
def dice_roller():
global number1, number2, total, number, roll_total, dice_total
screen.blit(list, (400,100))
pygame.display.flip()
print("Press Enter to Roll when you are ready...")
roll = input()
number1 = random.randint(1,6)
number2 = random.randint(1,6)
number = number1 + number2
print("Your first dice roll is...", number1)
print("Your second dice roll is...", number2)
if number1 == 1:
screen.blit(dice1, (350,500))
pygame.display.flip()
if number1 == 2:
screen.blit(dice2, (350,500))
pygame.display.flip()
if number1 == 3:
screen.blit(dice3, (350,500))
pygame.display.flip()
if number1 == 4:
screen.blit(dice4, (350, 500))
pygame.display.flip()
if number1 == 5:
screen.blit(dice5, (350,500))
pygame.display.flip()
if number1 == 6:
screen.blit(dice6, (350,500))
pygame.display.flip()
if number2 == 1:
screen.blit(dice1, (650,500))
pygame.display.flip()
if number2 == 2:
screen.blit(dice2, (650,500))
pygame.display.flip()
if number2 == 3:
screen.blit(dice3, (650,500))
pygame.display.flip()
if number2 == 4:
screen.blit(dice4, (650,500))
pygame.display.flip()
if number2 == 5:
screen.blit(dice5, (650,500))
pygame.display.flip()
if number2 == 6:
screen.blit(dice6, (650,500))
pygame.display.flip()
roll_total += 1
dice_total += number
def dice_score():
global number, dice_total
# number = number1 + number2
# dice_total = [total]
if number == 2:
#total += number
screen.blit(red_x, (530, 120))
pygame.display.flip()
if number == 3:
# total += number
screen.blit(red_x, (640, 120))
pygame.display.flip()
if number == 4:
screen.blit(red_x, (750, 120))
pygame.display.flip()
if number == 5:
# total += number
screen.blit(red_x, (420, 220))
pygame.display.flip()
if number == 6:
# total += number
screen.blit(red_x, (530, 220))
pygame.display.flip()
if number == 7:
# total += number
screen.blit(red_x, (640, 220))
pygame.display.flip()
if number == 8:
# total += number
screen.blit(red_x, (750, 220))
pygame.display.flip()
if number == 9:
# total += number
screen.blit(red_x, (420, 330))
pygame.display.flip()
if number == 10:
# total += number
screen.blit(red_x, (530, 330))
pygame.display.flip()
if number == 11:
# total += number
screen.blit(red_x, (640, 330))
pygame.display.flip()
if number == 12:
# total += number
screen.blit(red_x, (750, 330))
pygame.display.flip()
print("Your Total is...", dice_total)
#def shut_the_box():
# box = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
# for number in box:
# box.remove(number)
# print(dice_total)
def game():
while not complete:
for event in pygame.event.get():
if event.type == pygame.QUIT:
complete = True
screen.fill(white)
dice_roller()
dice_score()
# shut_the_box()
print ("You have rolled", roll_total, "times!")
print ("Roll again!")
pygame.display.update()
clock.tick(60)
pygame.quit()
quit()
|
import numpy as np
a = np.arange(10)**2
print(a)
#perkalian matrix
a = np.array (([1,2],
[3,4]))
b = np.ones([2,2])
print ("matrix a:")
print (a)
print(b)
c1 = np.dot(a,b)
c2 = a.dot (b)
print("matrix c:")
print(c1)
print("matrix c2:")
print(c2)
a1 = np.array(([1,2,3],
[4,5,6]))
print('matrix a1 dengan ukuran:', a1.shape)
print(a1)
|
import numpy as np
a = np.arange(10)**2
print(a)
#slicing
print ('elemen dari 1-6 adalah',a[0:6])
print ('elemen dari 4 sampai akhir', a[3:1])
print ('elemen dari awal sampai 5', a[:5]) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Time complexity: Sum all integers of an interval [a,b]."""
import time
def iterative_sum(num_list):
"""Calculate the sum using a for loop and acumulator variable."""
start_time = time.time()
total = 0
for num in num_list:
total += num
lapsed_time = time.time() - start_time
return total, lapsed_time
def standart_sum(num_list):
"""Calculate the sum using standart 'sum' function of python."""
start_time = time.time()
total = sum(num_list)
lapsed_time = time.time() - start_time
return total, lapsed_time
def gauss_sum(num_list):
"""Calculate the sum using the Gauss formula: Sn = n * (f + l) / 2."""
start_time = time.time()
size_list = len(num_list)
first_num = num_list[0]
last_num = num_list[-1]
total = size_list * (first_num + last_num) / 2
lapsed_time = time.time() - start_time
return int(total), lapsed_time
def main():
"""Compare three different algorithms that sum all integers of an interval."""
print('Time complexity: Sum all integers of an interval [a,b]')
print('------------------------------------------------------')
f_num = 100
l_num = int(1e6)
big_list = list(range(f_num, l_num + 1))
print(f'List: [{f_num}, {f_num + 1}, ..., {l_num - 1}, {l_num}]')
print(f'Size of list: {len(big_list)}')
print('------------------------------------------------------')
total1, lapsed_time1 = iterative_sum(big_list)
total2, lapsed_time2 = standart_sum(big_list)
total3, lapsed_time3 = gauss_sum(big_list)
lap_time_format1 = "{:.10f}".format(lapsed_time1)
lap_time_format2 = "{:.10f}".format(lapsed_time2)
lap_time_format3 = "{:.10f}".format(lapsed_time3)
print('Algorithm\tSum\t\tLapsed time')
print(f'Iterative\t{total1}\t{lap_time_format1}s')
print(f'Standart\t{total2}\t{lap_time_format2}s')
print(f'Gauss\t\t{total3}\t{lap_time_format3}s')
if __name__ == '__main__':
main()
|
#注册
from User import User
from UserList import UserList
class ShoopingSystem:
@staticmethod
def register():
userName = input("请输入用户名:")
password = input("请输入密码:")
C_password = input("请在此输入密码:")
userList = UserList()
if len(userName) == 0 or len(password) == 0 or password != C_password:
print("注册失败")
else:
newUser = User(userName, password)
searchUser = userList.getUserByUserName(newUser.userName)
if searchUser:
print("用户名存在")
else:
userList.append(newUser)
print("注册成功,去登录吧")
print(newUser)
ShoopingSystem.register() |
#!/usr/bin/env python3
# nrooks.py : Solve the N-Rooks, N-Queens and N-Knights problem!
# Based on the Prof. David Crandall's starter code
# Created by Varun Miranda, 2018
# a0.py : Solve the N-Rooks, N-Queens and N-Knights problem!
#Citations :
#https://docs.python.org/3/library/functions.html - implementing the zip function
import sys
# Count # of pieces in given row
def count_on_row(board, row):
return sum(board[row])
# Count # of pieces in given column
def count_on_col(board, col):
return sum([row[col] for row in board])
# Count total # of pieces on board
def count_pieces(board):
return sum([ sum(row) for row in board ] )
# Add a piece to the board at the given position, and return a new board (doesn't change original)
def add_piece(board, row, col):
return board[0:row] + [board[row][0:col] + [1,] + board[row][col+1:]] + board[row+1:]
####################### N-ROOKS PROBLEM ##############################################
# Get list of successors of given board state
def successors_nrooks(board):
board_array = []
if count_pieces(board) < N:
for c in range(0,N):
if count_on_col(board, c) == 0:
for r in range(0,N):
if count_on_row(board, r) == 0:
if (r,c) not in zip(k_array,l_array):
if board not in [add_piece(board, r, c)]:
board_array = board_array + [add_piece(board, r, c)]
return board_array
# check if board is a goal state
def is_goal_nrooks(board):
return count_pieces(board) == N and \
all( [ count_on_row(board, r) <= 1 for r in range(0, N) ] ) and \
all( [ count_on_col(board, c) <= 1 for c in range(0, N) ] )
########################### N-QUEENS PROBLEM ###########################################
# Create a function that checks diagonals
def diagonal(board):
final_val = 0
for col in range(0,N):
for row in range(0,N):
for count in range(1,N):
if row+count < N and col+count < N:
if board[row][col] + board[row+count][col+count] > 1:
final_val = 1
if row+count < N and col-count >= 0:
if board[row][col] + board[row+count][col-count] > 1:
final_val = 1
if row-count >= 0 and col+count < N:
if board[row][col] + board[row-count][col+count] > 1:
final_val = 1
if row-count >= 0 and col-count >= 0:
if board[row][col] + board[row-count][col-count] > 1:
final_val = 1
return final_val
# Get list of successors of given board state
def successors_nqueens(board):
board_array = []
final_val = 0
if count_pieces(board) < N:
for c in range(0,N):
if count_on_col(board, c) == 0:
for r in range(0,N):
if count_on_row(board, r) == 0:
if (r,c) not in zip(k_array,l_array):
if board not in [add_piece(board, r, c)]:
final_val = diagonal(board)
if final_val == 0:
board_array = board_array + [add_piece(board, r, c)]
return board_array
# check if board is a goal state
def is_goal_nqueens(board):
return count_pieces(board) == N and \
all( [ count_on_row(board, r) <= 1 for r in range(0, N) ] ) and \
all( [ count_on_col(board, c) <= 1 for c in range(0, N) ] ) and \
diagonal(board) == 0
####################### N-KNIGHTS PROBLEM ##############################################
# Check the places where a knight can attack another knight
def knight_moves(board):
final_val = 0
for col in range(0,N):
for row in range(0,N):
if row+1 < N and col+2 < N:
if board[row][col] + board[row+1][col+2] > 1:
final_val = 1
if row+1 < N and col-2 >= 0:
if board[row][col] + board[row+1][col-2] > 1:
final_val = 1
if row-1 >= 0 and col+2 < N:
if board[row][col] + board[row-1][col+2] > 1:
final_val = 1
if row-1 >= 0 and col-2 >= 0:
if board[row][col] + board[row-1][col-2] > 1:
final_val = 1
if row+2 < N and col+1 < N:
if board[row][col] + board[row+2][col+1] > 1:
final_val = 1
if row+2 < N and col-1 >= 0:
if board[row][col] + board[row+2][col-1] > 1:
final_val = 1
if row-2 >= 0 and col+1 < N:
if board[row][col] + board[row-2][col+1] > 1:
final_val = 1
if row-2 >= 0 and col-1 >= 0:
if board[row][col] + board[row-2][col-1] > 1:
final_val = 1
return final_val
# Get list of successors of given board state
def successors_nknights(board):
board_array = []
final_val = 0
if count_pieces(board) < N:
for c in range(0,N):
for r in range(0,N):
if (r,c) not in zip(k_array,l_array):
if board not in [add_piece(board, r, c)]:
final_val = knight_moves(board)
if final_val == 0:
board_array = board_array + [add_piece(board, r, c)]
return board_array
# check if board is a goal state
def is_goal_nknights(board):
return count_pieces(board) == N and \
knight_moves(board) == 0
###########################################################################################
# This is N, the size of the board. It is passed through command line arguments.
N = int(sys.argv[2])
initial_board = [[0 for i in range(N)] for j in range(N)]
blocked_spaces = int(sys.argv[3])
k_array = []
l_array = []
for i in range(4,4+(blocked_spaces*2),2):
j = i+1
k = int(sys.argv[i])-1
k_array = k_array + [k]
l = int(sys.argv[j])-1
l_array = l_array + [l]
# Return a string with the board rendered in a human-friendly format
def printable_board(board):
str = ""
for row in range(0,N):
for col in range(0,N):
if (row,col) in zip(k_array,l_array):
str = str + "X "
elif board[row][col] == 0:
str = str + "_ "
else:
if(sys.argv[1] == 'nrook'):
str = str + "R "
elif(sys.argv[1] == 'nqueen'):
str = str + "Q "
elif(sys.argv[1] == 'nknight'):
str = str + "K "
str = str + "\n"
return str
# Solve N-rooks, N-queens or N-knights
def solve(initial_board):
fringe = [initial_board]
while len(fringe) > 0:
if sys.argv[1] == 'nrook':
for s in successors_nrooks(fringe.pop()):
if is_goal_nrooks(s):
return(s)
fringe.append(s)
elif sys.argv[1] == 'nqueen':
for s in successors_nqueens(fringe.pop()):
if is_goal_nqueens(s):
return(s)
fringe.append(s)
elif sys.argv[1] == 'nknight':
for s in successors_nknights(fringe.pop()):
if is_goal_nknights(s):
return(s)
fringe.append(s)
return False
print ("Starting from initial board:\n" + printable_board(initial_board) + "\n\nLooking for solution...\n")
solution = solve(initial_board)
print (printable_board(solution) if solution else "Sorry, no solution found. :(")
|
#!/usr/bin/python
# Quick Sort class that allows for O(lg 2 n) to O(n^2) sorting of items,
# depending on where pivot picked happens to be within context of all sorted items
# Low memory overhead as it simply swaps items during comparisons
class QuickSort:
def __init__(self, items):
self.items = items
def sort(self, low = None, high = None):
if(low == None):
low = 0
if (high == None):
high = len(self.items) - 1
if(high - low > 0):
pivot = self.partition(low, high)
self.sort(low, pivot - 1)
self.sort(pivot + 1, high)
def partition(self, low, high):
pivot = high
first_high = low
for i in range(low, high):
if(self.items[i] < self.items[pivot]):
# Swap items
self.items[i], self.items[first_high] = self.items[first_high], self.items[i]
first_high += 1
self.items[pivot], self.items[first_high] = self.items[first_high], self.items[pivot]
return first_high
import random
print "Initialize QuickSort with list"
items = [3, 45, 89, 1, 7, 34940, 222222, 18, 2342, 344, 34, 233]
# Shuffle items randomly
random.shuffle(items)
print "Unsorted items: " + ", ".join(str(i) for i in items)
ms = QuickSort(items)
ms.sort()
print "Sorted items: " + ", ".join(str(i) for i in ms.items)
|
# A library containing methods to generate random names.
from random import choice
def _to_list(filename):
names = []
with open(filename, 'r') as f:
for line in f:
names.append(line.rstrip())
return names
male_names = _to_list('malenames')
female_names = _to_list('femalenames')
surnames = _to_list('surnames')
def random_female_name():
return '%s %s' % (choice(female_names), choice(surnames))
def random_male_name():
return '%s %s' % (choice(male_names), choice(surnames))
with open('peeps', 'r') as f:
female = True
for line in f:
print('%s\t%s' % (line.rstrip(), random_female_name() if female else random_male_name()))
female = not female
|
##Leira Salene 1785752
import math
paintColor = {
'red' : 35,
'blue' : 25,
'green' : 23
}
height = float(input('Enter wall height (feet):\n'))
width = float(input('Enter wall width (feet):\n'))
wallArea = height * width
print ('Wall area: {:.0f} square feet'.format(wallArea))
paint = wallArea/350
print ('Paint needed: {:.2f} gallons'.format(paint))
print ('Cans needed: {} can(s)'.format(math.ceil(paint)))
wallColor = input('\nChoose a color to paint the wall:\n')
print ('Cost of purchasing {} paint: $'.format(wallColor),end="")
print (paintColor[wallColor]) |
#6
r=int(input('Enter radius:'))
pi=3.14
a=pi*r*r
print('The area of circle:',a)
|
num = 10
stars = 0
blanks = 10
while num >= 0:
print(" "*blanks+"*"*stars)
blanks -= 1
stars += 1
num -= 1
print("You're welcome!")
|
class Product:
def __init__(self, nm, nb):
self.name = nm # unikalna
self.number = nb # ile mamy na stanie
def __str__(self):
return f'{self.name}: {self.number}'
class Warehouse:
def __init__(self, local_account):
self.products = {} # warehouse status - key - name, value - Product
self.account = local_account
self.read_warehouse() # tworząc obiekt wywołujemy metodę czytającą z pliku,
# zapisującą dane do słownika produktów
def read_warehouse(self):
with open("warehouse.txt", "r") as file:
for line in file.readlines():
current_line = line.split(",")
self.products[current_line[0]] = Product(current_line[0], int(current_line[1].split("\n")[0]))
def read_history(self):
with open("history.txt", "r") as file:
for line in file.readlines():
self.account.account_history.append(line)
def add_product(self, local_product, price):
if not self.account.update_balance(-price * local_product.number): # jeśli nie mamy tyle pieniędzy
return False
if local_product.name in self.products:
self.products[local_product.name].number += local_product.number
else:
self.products[local_product.name] = local_product
self.account.account_history.append(f'Purchase: {local_product.name}, {price}, {local_product.number}')
return True
def remove_product(self, local_product, price):
if local_product.name not in self.products:
return False
if self.products[local_product.name].number < local_product.number:
return False
self.products[local_product.name].number -= local_product.number
self.account.update_balance(price * local_product.number)
self.account.account_history.append(f'Sale: {local_product.name}, {price}, {local_product.number}')
return True
def show_products(self, local_input):
for product_name in local_input:
if product_name not in self.products:
print(f'Product: {product_name} not in offer.')
else:
print(f'Product: {product_name} - in stock: {self.products[product_name].number}')
self.account.account_history.append(f'Stock status for: {local_input}')
def save_stock(self):
last_product = list(self.products.keys())[-1]
with open("warehouse.txt", "w") as file:
for name, product in self.products.items():
file.write(name + "," + str(product.number))
if name != last_product:
file.write("\n")
def save_history(self):
with open("history.txt", "a") as file: # tutaj nadpisujemy, nie zapisujemy od nowa
for action in self.account.account_history:
file.write(action + "\n")
class Account:
def __init__(self):
self.balance = 0
self.account_history = []
self.read_account()
def read_account(self):
with open("account.txt", "r") as file:
self.balance = int(file.readline())
def show_account_balance(self):
print(f'Current account balance is {self.balance}.')
self.account_history.append(f'Show balance: {self.balance}')
def add_payment(self, local_input_list):
payment_amount = int(local_input_list[0])
comment = local_input_list[1:]
self.update_balance(payment_amount)
self.account_history.append(f'Payment: {payment_amount}, {comment}')
def update_balance(self, amount): # amount can be negative
if self.balance + amount < 0:
return False
self.balance += amount
return True
def save_account(self):
with open("account.txt", "w") as file: # otwieramy plik do zapisu
file.write(str(self.balance))
my_account = Account()
my_warehouse = Warehouse(my_account)
# dekorator, który zajmuje się wykonaniem tych czynności, które powtarzają się przy rejestrowaniu płatności, sprzedaży
# i zakupu, czyli pobiera informacje ze standardowego wejścia i pakuje je do zmiennych, a następnie po wykonaniu
# funkcji zapisuje do plików historię, stan konta i stan magazynu
def get_input_and_save(label, int_before, str_count, int_after): # label - message to user, int_before - number of
# integer values needed as input arguments for the function before the string value, then str_count - number of
# strings needed for the function, and int_after - number of integers after string value. eg. if for my
# function I need product name (str), price (int) and number (int), the values here will be 0, 1, 2.
def decorate(callback):
while True:
input_string = input(label)
input_list = input_string.split() # lista stringów
if input_list[0] == 'stop':
my_warehouse.save_stock()
my_warehouse.save_history()
my_account.save_account()
break
if len(input_list) < (int_before + str_count + int_after): # if not enough parameters given
print("Please give appropriate number of arguments.")
continue
arg_before = [int(arg) for arg in input_list[0:int_before]] # skrótowy zapis pętli. arg_before to lista
# (bo jest w []) parametrów przekształconych w integery - z całej listy parametrów iput_list wzięliśmy
# slice z int_before parametrów z początku
input_list_int_after = input_list[-int_after:] if int_after else [] # dodałam tę linijkę, ponieważ
# input_list[-int_after:] nie działa, gdy int_after = 0, zwraca wtedy pełną listę
arg_after = [int(arg) for arg in input_list_int_after] # i od końca
glue = " "
arg_str = [glue.join(input_list[int_before:-int_after])] # a wszystko, co było pomiędzy, łączymy razem
# w stringa poprzedzielanego spacjami
args = arg_before + arg_str + arg_after # następnie łączę otrzymane, przekształcone odpowiednio
# argumenty w listę, którą wciągnę do funkcji działającej (callback)
# w takiej formie, w jakiej ich potrzebuję
if not callback(*args): # dzięki gwiazdce nie muszę w definicji ani w wywołaniu funkcji callback podawać
# listy (bo lista jest jednym obiektem) składającej się z argumentów, których potrzebuję, ale mogę podać
# po kolei już argumenty, które mnie interesują i zostaną one wszystkie zinterpretowane
continue
return decorate
|
age = 18
if age >= 18:
print("You can vote")
print("Mature")
elif age < 18:
print("Not mature")
else:
print("Ok bye")
print("Ok i am done")
|
# Author : Nihar Kanungo
import math
'''
A regular strictly convex polygon is a polygon that has the following characteristics:
all interior angles are less than 180
all sides have equal length
This class facilitates creation of objects which can get the properties
edges
vertices
interior angle
edge length
apothem
area
perimeter
'''
class Polygon:
def __init__(self ,edge , circumradius):
'''
where initializer takes in:
number of vertices for largest polygon in the sequence
common circumradius for all polygons
'''
self.edge, self.circumradius = edge,circumradius
@property
def edge(self):
'''
Returns the number of edges of the polygon
'''
return self._edge
@edge.setter
def edge(self, edge):
'''
Sets the edge of the Polygon
'''
if edge <3:
raise ValueError("Edge in a regular polygon must be positive and be minimum 3 to form a closed figure")
else:
#print("I was called")
self._edge = edge
@property
def circumradius(self):
'''
Returns the circumradius of the polygon
'''
return self._circumradius
@circumradius.setter
def circumradius(self, circumradius):
'''
Sets the circum radius of the Polygon
'''
if circumradius <=0:
raise ValueError("Circum radius must be positive")
else:
self._circumradius = circumradius
@property
def interior_angle(self): #method
'''
Returns the interior angle of the polygon
'''
return (self.edge - 2) * (180/self.edge)
@property
def edge_length(self):
'''
Returns the edge length of the polygon
'''
return 2 * self.circumradius * math.sin((math.pi/self.edge))
@property
def apothem(self):
'''
Returns the apothem of the polygon
'''
return self.circumradius * math.cos(math.pi/self.edge)
@property
def area(self):
'''
Returns the Area of the polygon
'''
return (1/2) * self.edge * self.edge_length * self.apothem
@property
def perimeter(self):
'''
Returns the perimeter of the polygon
'''
return (1/2) * self.edge * self.edge_length
def __str__(self):
return 'Polygon: edge={0}, circumradius={1}'.format(self.edge, self.circumradius)
def __repr__(self):
return 'Polygon({0}, {1})'.format(self.edge, self.circumradius)
def __eq__(self, other):
if isinstance(other, Polygon):
return self.edge == other.edge and self.circumradius == other.circumradius
def __gt__(self, other):
if isinstance(other, Polygon):
return self.edge > other.edge
else:
return NotImplemented
|
# General Functions for String Operations.
# Liu Dezi
from astropy.io import fits
import os, sys
def read_param(filename):
"""
Read a parameter configuration file, and save the parameters into
a python directory structure.
Parameter:
filename: the input configuration file name.
NOTE: The format of the configuration should be:
-----------------------------------------------
########### Configuration file ################
# blank or some comments
param1 value # comment
param2 value
...
# blank or some comments
paramn value
...
------------------------------------------------
For each parameter, only one value (string, float, integer ...) can
be assigned. You have to avoid double '#' (i.e. '##'), but it will
work for many more '#' or a single '#'.
"""
pfile = open(filename).readlines()
nn = len(pfile)
param = {} # define dictionary structure
for i in range(nn):
rowlist = pfile[i].split()
if len(rowlist)<=1: continue # blank row
if not "#" in rowlist:
if len(rowlist)==2:
key, value = rowlist[0:2]
param.update({key:value})
else:
print "!! Something is wrong with parameter '%s'."%rowlist[0]
return
elif rowlist.index("#")==2:
key, value = rowlist[0:2]
param.update({key:value})
elif rowlist.index("#")==0:
continue # annotation
else:
print "!! Something is wrong with parameter '%s'."%rowlist[0]
return
return param
def write_FitsTable(table_contents, table_array, outcat="table.ldac"):
"""
Write FITS table
"""
conts = open(table_contents).read().splitlines()
rid = [i for i in range(len(conts)) if not "#" in conts[i]]
ncont = len(rid)
x, y = table_array.shape
if y!=ncont: raise ValueError("!!! Dimensition error")
# first construct an empty fits table
prihdr = fits.Header()
prihdr["AUTHOR"]="Dezi LIU, Peking University"
prihdu = fits.PrimaryHDU(header=prihdr)
# Table Extension
cols = []
for i in range(ncont):
cont = conts[rid[i]]
cont = cont.split()
name, fmt, disp = cont[0], cont[1], " ".join(cont[2:])
col = fits.Column(name=name, format=fmt, disp=disp, array=table_array[:,i])
cols += [col]
cols = fits.ColDefs(cols)
tbhdu = fits.BinTableHDU.from_columns(cols)
tbhdu.header["EXTNAME"] = "OBJECTS"
thdulist = fits.HDUList([prihdu,tbhdu])
if os.path.exists(outcat): os.popen("rm %s"%outcat)
thdulist.writeto(outcat)
return
|
#!/bin/bash/python
def listOfEvenNums():
l1 = [i for i in range(100,2000,2)]
print l1
def mergeTwoLists():
l1 = [i for i in range(1,10)]
l2 = [i for i in range(1,20,2)]
l3 = l1 + l2
l4 = list(set(l1 + l2)) #removing of duplicate elements
print l3
def multiplyLists():
l1 = []
l2 = [[1]*3] #here the elements of the list are getting multiplied.
l3 = [[1]]*3 #here the list inside the list is getting multiplied.
print l2 # op: [[1, 1, 1]]
print l3 # op: [[1], [1], [1]]
def accessListInList():
l1 = [[i for i in range(1,10)],[i for i in range(10,50)]]
print l1[0]
print l1[0][1:4]
print l1[1][10:20]
l1[1][10] = 56
print l1[1][10:20]
def addingTupleInList():
l1 = [(i,i) for i in range(10)]
print l1[0]
l1[0] = 1 #the tuple is replaced by integer
print l1[1][0]
l1[1][0] = 2 #throws error as tuple is an immutable datastructure.The immutable property of tuple holds good even is its in a list.
def accessListInTuple():
t1 = tuple([[i for i in range(1,10)],[i for i in range(10,20)]])
print t1
print t1[0]
#t1[0] = 10 #throws error as tuple is immutable
t1[0][2] = 45
print t1[0] #No matter the list is inside a tuple the mutable property of list holds good.
def createDictInList():
d1 = [{x:y} for x in range(1,10) for y in range(1,20)]#This will create x*y number of dictionaries inside the list with x as key and y as value.
d2 = [{x:x*x} for x in range(1,10)]#This creates x number of dictionaries with x as key and x*x as value.
print d1[0].keys() #To get the list of keys in the dict
print d1[0].values() #To get the list of values in the dict
def createFibonacci(n):
l1 = [fib(x) for x in range(n)]
print l1
def fib(n):
return n if n<=1 else (fib(n-1) + fib(n-2))
#createFibonacci(20)#op:[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]
def convertLargeStringToList():
s1 = "Python is a powerful high-level, object-oriented programming language created by Guido van Rossum."
l1 = s1.strip(',').split(' ') #split breaks the string by converting the above string to smaller strings and inserting them to the list. Strip removes the character mentined in the method.
l2 = [len(w) for w in l1]#get the length of each word.
d1 = {w:len(w) for w in l1}#dictionary which contains the word as key and length as its value.
print l1 #op: ['Python', 'is', 'a', 'powerful', 'high-level,', 'object-oriented', 'programming', 'language', 'created', 'by', 'Guido', 'van', 'Rossum.']
print l2 #op: [6, 2, 1, 8, 11, 15, 11, 8, 7, 2, 5, 3, 7]
print d1 #op: {'a': 1, 'van': 3, 'language': 8, 'created': 7, 'Python': 6, 'programming': 11, 'is': 2, 'powerful': 8, 'object-oriented': 15, 'high-level,': 11, 'Guido': 5, 'by': 2, 'Rossum.': 7}
def checkPalindrome():
s1 = "Python is a powerful high-level, object-oriented programming language created by Guido van Rossum."
p1 = [w for w in s1.replace(',','').strip('.').split(' ') if pal(w.lower()) and len(w)>1]
print pal('hello') #op: False
print pal('rotor') #op: True
print p1 #op: ['abcba']
def pal(str):
for i in range(0,(len(str)/2)):
if str[i] != str[len(str)-i-1]:return False
return True
#checkPalindrome()
'''
def pal(text):
rev = ""
final = ""
for a in range(0, len(text)):
rev = text[len(text) - a - 1]
final = final + rev
return 'true' if final.lower() == text.lower() else 'false'
'''
import copy
def copyList():
l1 = [1,10,[x for x in range(10)],[y for y in range(10,20,2)]]
l2 = copy.copy(l1)
l3 = copy.deepcopy(l1)
print l1 #op [1, 10, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 12, 14, 16, 18]]
l1[1] = 20
l1[3][4] = 25
#Changed the element in list l1 in 2 places.
print l1 #op [1, 20, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 12, 14, 16, 25]]
'''Since list l2 is a shallow copy the change in l1[1] didnt affect but the change in the list inside
the list relected in l2 as it was just a reference object.'''
print l2 #op [1, 10, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 12, 14, 16, 25]]
'''Since list l3 was a deep copy the changes in l1 wont affect as its created a cmplete copy of the
list object including the compound objects inside the list'''
print l3 #op [1, 10, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 12, 14, 16, 18]]
def isPrime(x):
if x >1:
for i in range(2,x):
if (x % i) == 0:
break
else:
return x
def getPrimeNumber():
l1 = [x for x in range(1,100) if isPrime(x)]
print l1
#getPrimeNumber()
def square(i):
return i *i
def cube(i):
return i*i*i
func = [cube,square]
def testMapAndLambda():
l = [i for i in xrange(1,8)]
l2 = [map(cube,l)]
l1 = [map(lambda x:x(i),func) for i in range(1,8)]
l3 = [[cube(i),square(i)] for i in range(1,8)]
print l1 #op [[1, 1], [8, 4], [27, 9], [64, 16], [125, 25], [216, 36], [343, 49]]
print l2 #op [[1, 8, 27, 64, 125, 216, 343]]
print l3 #op [[1, 1], [8, 4], [27, 9], [64, 16], [125, 25], [216, 36], [343, 49]]
from functools import reduce
def testReduceAndFilter():
l = [1,5,8,9]
cl = list(filter(lambda x: x in l, range(1, 20)))
cproduct = reduce((lambda x,y: x * y ), cl)
sl = list(filter(lambda x: x > 10, range(1, 20)))
sproduct = reduce((lambda x,y: x * y ), sl)
print cl #op [1, 5, 8, 9]
print cproduct #op 360
print sl #op [11, 12, 13, 14, 15, 16, 17, 18, 19]
print sproduct #op 33522128640
#testReduceAndFilter()
alist = [1,2,3]
def check():
print id(alist)
print alist
alist = {1:3}
b = {1:4}
print id(alist)
print alist
#check()
def sortingList():
l1 = [20,73,10,21,87,5]
print l1
for i in range(0,len(l1)-1):
for j in range(i+1,len(l1)):
print l1[i],"+++",l1[j]
if l1[i]>l1[j]:
l1[j],l1[i]=l1[i],l1[j]
print l1
sortingList()
|
""" A program that stores and updates a counter using a Python pickle file
@author: Colvin Chapman
"""
from os.path import exists
import sys
import pickle
def update_counter(file_name, reset=False):
""" Updates a counter stored in the file 'file_name'
A new counter will be created and initialized to 1 if none exists or if
the reset flag is True.
If the counter already exists and reset is False, the counter's value will
be incremented.
file_name: the file that stores the counter to be incremented. If the file
doesn't exist, a counter is created and initialized to 1.
reset: True if the counter in the file should be rest.
returns: the new counter value
>>> update_counter('blah.txt',True)
1
>>> update_counter('blah.txt')
2
>>> update_counter('blah2.txt',True)
1
>>> update_counter('blah.txt')
3
>>> update_counter('blah2.txt')
2
"""
# Test if the file needs to be read
if exists(file_name) is False or reset is True:
fout = open(file_name, 'wb') # opening a writing file
counter = 1
pickle.dump(counter, fout) # storing counter as bits in file_name
return counter
# Read and write to the file
else:
fin = open(file_name, 'rb') # opening a reading file
counter = pickle.load(fin)
counter += 1 # Increasing counter by 1
finw = open(file_name, 'wb') # opening a writing file
pickle.dump(counter, finw)
fin.close() # clean up
finw.close()
return(counter)
if __name__ == '__main__':
if len(sys.argv) < 2:
import doctest
doctest.testmod(verbose=True)
else:
print("new value is " + str(update_counter(sys.argv[1])))
|
# 工厂方法 模式,比 简单工厂 模式 更符合“开-闭”原则。
#1. 抽象工厂类
class Factory(object):
def getProduct(self): #必须要有某个方法
return Product()
#2. 抽象产品类
class Product(object):
pass
#3. 具体产品
class ProductA(Product):
def say(self):
print("Product A")
class ProductB(Product):
def say(self):
print("Product B")
#4. 具体工厂
class FactoryA(Factory):
def getProduct(self):
return ProductA()
class FactoryB(Factory):
def getProduct(self):
return ProductB()
def getProduct(factoryName):
return factoryName().getProduct()
getProduct(FactoryA).say()
getProduct(FactoryB).say()
###########
#facA=FactoryA() #A工厂
#facA.getProduct().say() #A工厂生产产品A Product A
#FactoryB().getProduct().say() #Product A
##########
print("="*20)
# 新增产品3,需要2个类,产品3 和工厂3
class Product3(Product):
def say(self):
print("Product 3")
class Factory3(Factory):
def getProduct(self):
return Product3()
#Factory3().getProduct().say() #Product 3
getProduct(Factory3).say()
|
#一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。
#一个最简单的高阶函数:
def add(x, y, f):
return f(x) + f(y)
def f(i):
return i*i;
def f2(i):
return i/2;
a1=add(1,4,f)
a2=add(1,4,f2)
print(a1);
print(a2); |
# 返回函数,可以实现预定义
def getSpliter(pattern):
#内函数能对外函数(不是在全局作用域)的变量进行引用,内部函数就被认为是闭包
def split_str(str):
import re;
return re.split(pattern,str);
return split_str;#返回的是内函数
# 定制化spliter
spliter_tab=getSpliter(r'\t')
spliter_e=getSpliter(r'e')
# 使用spliter
print(spliter_tab)
s2="name\tage\tgrade\tgender";
print(spliter_tab(s2))
print(spliter_e(s2))
|
#一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。
#一个最简单的高阶函数:
def add(x, y, f):
return f(x) + f(y)
def f(i):
return i*i;
print( add(1,4,f) )
#http://research.google.com/scholar/mapreduce-osdi04.pdf |
# 广度优先算法:
# 维护一个队列,先加入一度节点;
# 遍历,如果找到了就停止;没找到,就弹出,并把其好友添加到队列末尾。
# 直到返回,或者找不到。
#
# 这个粗糙的实现有个问题,就是有人(peggy) 被查询了2次。
# 首先同一个元素检查2次是在浪费时间,其次这有可能陷入死循环,如果两个人互为好友。
# 应该使用一个表格,记录检查过的元素。
# 创建图
graph = {}
graph["you"] = ["alice", "bob", "claire"]
graph["bob"] = ["anuj", "peggy"]
graph["alice"] = ["peggy"]
graph["claire"] = ["thom", "jonny"]
graph["anuj"] = []
graph["peggy"] = []
graph["thom"] = []
graph["jonny"] = []
# 在Python中,可使用函数deque来创建一个双端队列。
from collections import deque
search_queue = deque()
search_queue += graph["you"]
# 判断这个人是不是芒果经销商,最后一个字母是m 的停止
def person_is_seller(name):
return name[-1] == 'm'
# 开始搜索
def bfs(search_queue, debug=True):
i=0
while search_queue:
person = search_queue.popleft() #左侧弹出一个元素
i+=1
if debug:
print(f"[{i}] Cur:", person);
print("\t>>>queue:", search_queue);
if person_is_seller(person):
print(person + " is a mango seller!")
return True
else:
search_queue += graph[person]
return False
bfs(search_queue);
print("==End==")
|
class Fib(object):
def __init__(self):
self.a, self.b = 0, 1 # 初始化两个计数器a,b
def __iter__(self):
return self # 实例本身就是迭代对象,故返回自己
def __next__(self):
self.a, self.b = self.b, self.a + self.b # 计算下一个值
if self.a > 100000: # 退出循环的条件
raise StopIteration();
return self.a # 返回下一个值
#完全打印
# f=Fib()
# #print('打印第一个元素:',f[1]) ###################{不支持索引}
# for n in f: #for循环中实现迭代对象__iter__,不断调用自身的__next__方法。
# print(n)
#通过上面的方法,我们自己定义的类表现得和Python自带的list、tuple、dict没什么区别,这完全归功于动态语言的“鸭子类型”,不需要强制继承某个接口。
#http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014319098638265527beb24f7840aa97de564ccc7f20f6000
#但和list不同,还不支持索引。
class Fib2(object):
def __getitem__(self, n):
a, b = 1, 1
for x in range(n):
a, b = b, a + b
return a
# f2=Fib2();
# n=0
# while n<10:
# print('a(',n,')=',f2[n])
# n=n+1
# print( f2[10] )
# #print( f2[2:5] ) ###################{不支持切片}
# #原因是__getitem__()传入的参数可能是一个int,也可能是一个切片对象slice,所以要做判断:
#怎么支持切片呢?
class Fib3(object):
def __getitem__(self, n):
#判断类型1
if isinstance(n, int): # n是索引
a, b = 1, 1
for x in range(n):
a, b = b, a + b
return a
#判断类型2
if isinstance(n, slice): # n是切片
start = n.start
stop = n.stop
step=n.step
if step==None:
step=1;
if start is None:
start = 0
a, b = 1, 1
L = []
for x in range(stop):
if x >= start:
if (x-start)%step==0:
L.append(a)
a, b = b, a + b
return L
#assert 0,'pause.'
f3=Fib3();
n=0
while n<10:
print('f3[%d]='% n,f3[n])
n=n+1
print( f3[10] )
print('切片:', f3[1:20] )#可以切片
#对step参数作处理:
print('步长2:', f3[1:20:2] )
#没有对负数作处理
print('步长3:', f3[2:20:3] )
# 此外,如果把对象看成dict,__getitem__()的参数也可能是一个可以作key的object,例如str。
# 与之对应的是__setitem__()方法,把对象视作list或dict来对集合赋值。
# 最后,还有一个__delitem__()方法,用于删除某个元素。 |
# 分而治之: 数组求和,递归法;
def sumArr(arr):
sum=0;
for i in arr:
sum+=i
return sum
print(sumArr([2,4,6]))
# 方法二,使用递归,数组长度为1或0时返回,否则拿出一个值加上其余 求和数组
def sumArr2(arr):
if len(arr)==0:
return 0
else:
return arr[0] + sumArr2(arr[1:])
print(sumArr2([2,4,6]))
|
import re
# 用正则表达式切分字符串比用固定的字符更灵活
r='a b c'.split(' ')
print('1: ',r)
#['a', 'b', '', '', 'c']
#无法识别连续的空格,用正则表达式试试:
r=re.split(r'\s+', 'a b c')
print('2: ',r)
# ['a', 'b', 'c']
#无论多少个空格都可以正常分割。
#加入,试试:
r=re.split(r'[\s\,]+', 'a,b, c d ,e fg')
print('3: ',r)
#再加入;试试:
r=re.split(r'[\s\,\;]+', 'a,b;; c d')
print('4: ',r)
#用一切非字母元素分割
r=re.split(r'[^a-zA-Z]+', 'a,b;; -c d+e|f__g')
print('5: ',r)
r=re.split(r'[^\w]+', 'a,b;; -c d2+e|f__(g)h')
print('6: ','为什么去不掉下划线f__g',r) #因为\w是字母、数字和下划线
r= re.split(r'[\W_]+', 'a,b;; -c d2+e|f__(g)h')
print('7: ',r) #去掉了下划线
|
# 选择排序
arr=[20,1,6,100,5]
# 返回最小元素的下标
def findSmallest(arr):
small=arr[0]
index=0
for i in range( len(arr)):
if small> arr[i]:
small=arr[i]
index=i;
return index
# use this function in sorting
def searchSort(arr):
arr2=[]
for i in range( len(arr) ):
print(i, arr2)
smallest=findSmallest(arr)
arr2.append(arr.pop(smallest))
return arr2;
print(arr)
arr2=searchSort(arr)
print(arr2) |
#支持函数嵌套
def add3(a,b,c):
#内部函数
def add2(x,y):
return x+y
return add2(add2(a,b),c)
print(add3(1,2,3))
|
# 广度优先算法:
# 维护一个队列,先加入一度节点;
# 遍历,如果找到了就停止;没找到,就弹出,并把其好友添加到队列末尾。
# 直到返回,或者找不到。
from re import search
#
# v2: 为了避免死循环,要记录搜寻过的元素,并跳过它。
# 另一个更新,是把函数封装的更好:传入图和要查找的起始点。
# 创建图
graph = {}
graph["you"] = ["alice", "bob", "claire"]
graph["bob"] = ["anuj", "peggy"]
graph["alice"] = ["peggy"]
graph["claire"] = ["thom", "jonny"]
graph["anuj"] = []
graph["peggy"] = []
graph["thom"] = []
graph["jonny"] = []
# 在Python中,可使用函数deque来创建一个双端队列。
from collections import deque
# 判断这个人是不是芒果经销商,最后一个字母是m 的停止
def person_is_seller(name):
return name[-1] == 'm'
# 开始搜索
def bfs2(graph, name="you", debug=True):
search_queue = deque()
search_queue += graph[name]
searched=[]
i=0
while search_queue:
i+=1
person = search_queue.popleft() #左侧弹出一个元素
if person in searched:
print(f"[{i}]==>Jump:", person)
continue;
else:
searched.append(person);
if debug:
print(f"[{i}] Cur:", person);
print("\t>>>queue:", search_queue);
if person_is_seller(person):
print(person + " is a mango seller!")
return True
else:
search_queue += graph[person]
return False
bfs2(graph, "you");
print("==End==")
|
#if语句
a=110;
if a>0:
if a>100:
print(">100")
elif a>10:
print('>10')
else:
print('>1')
elif a<0:
print('<0')
else:
print('=0')
# 数据类型
mytype=type("this is a book")
mytype2=type(50.3)
print(mytype,' ',mytype2)
#使用if判断数据类型
if type("string") is str:
print("Yes,a string")
else:
print("No, not a string")
#但是type()不靠谱,比如
class A():
pass
class B(A):
pass
a=A()
b=B()
b2=B()
print('type(a): ',type(a))
print(type(a) is type(b)) #False 不识别子类。
print(type(b2) is type(b)) #True
#也可以使用isinstance
print("isinstance: ",isinstance(a,A)) #True
print("isinstance: ",isinstance(b,A)) #True 子类对象当做父类对象
# type的话出来的则是一串字符串,精确到子类,所以可以用来做精确判断,例如判断是不是这个类,而不是这个类的子类,isinstance只能判断是不是这个类或者这个类的子类。
# 判断两个对象是否来自同一个类,可以用type(a)==type(b)来判断。
|
# 汉诺塔思想笔记
# 认识汉诺塔的目标:把A柱子上的N个盘子移动到C柱子,可以使用中间柱子B,小盘必须在大盘上面。
# 递归的思想就是把这个目标分解成三个子目标
# 子目标1:将前n-1个盘子从a移动到b上
# 子目标2:将最底下的最后一个盘子从a移动到c上
# 子目标3:将b上的n-1个盘子移动到c上
# 然后每个子目标又是一次独立的汉诺塔游戏,也就可以继续分解目标直到N为1
def move(n, a, b, c):
if n == 1:
print(a, '-->', c)
else:
move(n-1, a, c, b)# 子目标1
move(1, a, b, c)# 子目标2
move(n-1, b, a, c)# 子目标3
n = input('enter the number:')
move( int(n), 'A', 'B', 'C' ) |
def addEnd(L=None):
if L is None:
L=[]
L.append('END')
return L
a1=addEnd([1,2,3])
print(a1);
b1=addEnd();
b2=addEnd();
b3=addEnd();
print(b1);
print(b2);
print(b3);
print(a1); |
def now():
print('2015-3-25')
f = now
f()
print('now: ', now )
print('now.__name__: ', now.__name__ )
print('f: ', f )
print('f.__name__: ', f.__name__ )
#现在,假设我们要增强now()函数的功能,
#比如,在函数调用前后自动打印日志,但又不希望修改now()函数的定义,
#这种在代码运行期间动态增加功能的方式,称之为“装饰器”(Decorator)。
# OOP的装饰模式需要通过继承和组合来实现,而Python除了能支持OOP的decorator外,直接从语法层次支持decorator。
# Python的decorator可以用函数实现,也可以用类实现。
import functools
print('=========装饰器=========')
def log(text):
def decorator(func):
@functools.wraps(func) #修改函数的__name__属性
def wrapper(*args, **kw):
print('%s %s():' % (text, func.__name__))
return func(*args, **kw)
#wrapper.__name__ = func.__name__; #怎么纠正函数名字?
return wrapper
return decorator
# 我们要借助Python的@语法,把decorator置于函数的定义处:
@log('execute')
def now():
print('2015-3-25')
now()
print('now.__name__: ', now.__name__ ) #now.__name__: wrapper |
def fact(x):
if x<=1:
return 1;
else:
if debug:
print(x)
return x*fact(x-1)
debug=True
x=fact(5)
print(x)
|
#嵌套来模仿二维数组
L=[
['Apple', 'Google', 'Microsoft'],
['Java', 'Python', 'Ruby', 'PHP'],
]
#调用元素
print(L[0][1]); #Google
#元素长度
print('Before append:', len(L));
#在末尾添加元素
L.append(['Adam', 'Bart', 'Lisa'])
print('After append:', len(L));
#删除元素
print(L)
del L[2][-1] #删除序号是2的list中的最后一个元素
print(L)
print("about 分片赋值=======================")
#分片赋值
txt=list('good day')
print(txt)
#部分元素重新赋值
txt[-3:]=list("time")
print(txt)
#替换
txt[0:4]=list('bad') #4个替换成3个
print(txt)
#直接插入
txt[0:0]="realy"
print(txt)
#看来不能分片插入单词。想插入单词需要使用单个位点
del txt[0:4]
txt[0]='realy'
print(txt)
#count方法
mlist=list('this is an apple')
print(mlist)
print('the number of o is:',mlist.count('a')) #2
mylist=list("some")
print(mylist)
#copy方法
mlist=list('this is an apple')
my2=mylist
my3=mylist.copy()
mylist[1:]=' '
print(my2) #受影响。按地址传递
print(my3) #不受影响。直接复制一份出来。
|
# Queue和Pipe只是实现了数据交互,并没实现数据共享。
# 即一个进程去更改另一个进程的数据。那么就要用到Managers
from multiprocessing import Process, Manager
def fun1(dic, lis, index):
dic[index] = 'a'+str(index)
dic['2'] = dic.get("2","")+ '_'+str(index)
lis.append(index) #[0,1,2,3,4,0,1,2,3,4,5,6,7,8,9]
print(index)
if __name__ == '__main__':
with Manager() as manager:
dic1 = manager.dict() #注意字典的声明方式,不能直接通过{}来定义
lis2 = manager.list(range(5)) #[0,1,2,3,4]
process_list = []
for i in range(5):
p = Process(target=fun1, args=(dic1,lis2,i))
p.start()
process_list.append(p)
for pr in process_list:
pr.join()
print(dic1)
print(lis2)
|
u"""
Write a program that outputs the file_names of duplicate files.
"""
__author__ = "Diana Rusu"
__email__ = "[email protected]"
import os
import sys
from collections import defaultdict
import hashlib
def find_files_with_same_size(folder_to_check):
"""Find files that have the same size."""
file_size_to_names = defaultdict(list)
files = [f for f in os.listdir(
folder_to_check) if os.path.isfile(folder_to_check+f)]
for file_name in files:
file_size = os.path.getsize(os.path.join(folder_to_check, file_name))
file_size_to_names[file_size].append(file_name)
duplicate_size_to_name = {file_size: file_size_to_names[file_size]
for file_size in file_size_to_names.keys() if
len(file_size_to_names[file_size]) > 1}
return list(duplicate_size_to_name.values())
def find_duplicates(folder_to_check_duplicates):
"""Calculate hash for files with same size."""
file_hash_to_names = defaultdict(list)
files_with_same_size_list = find_files_with_same_size(
folder_to_check_duplicates)
if len(files_with_same_size_list) == 0:
print('''___________________________________
\n No duplicates found. Will exit now. \n ''')
sys.exit()
else:
for files_with_same_size in files_with_same_size_list:
for file_name in files_with_same_size:
file_hash = compute_hash_sha256(
folder_to_check_duplicates+file_name)
file_hash_to_names[file_hash].append(file_name)
duplicate_hash_to_names = {file_hash: file_hash_to_names[file_hash]
for file_hash in file_hash_to_names.keys() if
len(file_hash_to_names[file_hash]) > 1}
return duplicate_hash_to_names
def compute_hash_sha256(filename, block_size=65536):
"""Since MD5 is known to have weaknesses, will use SHA1 256."""
hash_sha256 = hashlib.sha256()
with open(filename, 'rb') as f:
for block in iter(lambda: f.read(block_size), b''):
hash_sha256.update(block)
return hash_sha256.hexdigest()
def find_original_file(duplicate_hash_to_names, folder_to_check):
"""Find the original file from which the others duplicates are copied."""
original_files = {}
for file_names in duplicate_hash_to_names.values():
min_mtime = sys.maxsize
file_name_min = None
for file_name in file_names:
file_mtime = os.stat(folder_to_check+file_name).st_mtime
if(file_mtime < min_mtime):
min_mtime = file_mtime
file_name_min = file_name
original_files[file_name_min] = [
file_name for file_name in file_names
if file_name != file_name_min]
return original_files
def check_directory_exist(directory):
"""Verify validity of the user input."""
if (os.path.exists(directory) &
os.path.isdir(directory)):
return True
else:
print("That is an invalid path. Try again")
return False
if __name__ == '__main__':
while(True):
folder_to_check_duplicates = input(
"Enter the folder path you want to check for duplicates: "
)
if(check_directory_exist(folder_to_check_duplicates)):
break
duplicate_hash_to_names = find_duplicates(folder_to_check_duplicates)
print("=========================================================\n")
print("Hash of the duplicate files with corresponding file names")
print("_________________________________________________________\n")
for file_hash, file_names in duplicate_hash_to_names.items():
print(file_hash, file_names)
print("=========================================================\n")
print("Original File", " |\t", "Duplicates")
print("_________________________________________________________\n")
originals = find_original_file(
duplicate_hash_to_names, folder_to_check_duplicates)
for original_file, duplicate_files in originals.items():
print(original_file, "\t\t|\t", duplicate_files)
print("=========================================================\n")
|
def isPalindrome(s, ignorecase=False):
"""
>>> type(isPalindrome("bob"))
<type 'bool'>
>>> isPalindrome("abc")
False
>>> isPalindrome("bob")
True
>>> isPalindrome("a man a plan a canal, panama")
True
>>> isPalindrome("A man a plan a canal, Panama")
False
>>> isPalindrome("A man a plan a canal, Panama", ignorecase=True)
True
"""
onlyletters = []
x = 0
if ignorecase == True:
s = str.lower(s)
while x < len(s):
if str.isalpha(s[x]):
onlyletters.append (s[x])
x = x + 1
reverse = onlyletters[::-1]
if onlyletters == reverse:
return True
else:
return False
# Create an empty string "onlyLetters"
# Loop over all characters in the string argument, and add each
# character which is a letter to "onlyletters"
# Reverse "onlyletters" and test if this is equal to "onlyletters"
|
def find_it(seq):
numbers = {}
scanNumbers = (x for x in seq)
for x in scanNumbers:
if x in numbers:
numbers[x] = numbers[x] + 1
else:
numbers[x] = 1
it = next((k, v) for k, v in numbers.items() if v & 1)
return it[0]
print(find_it([20,1,1])) |
def comp_v1(array1, array2):
if (array1 is None and array2 is not None) or (array1 is not None and array2 is None):
return False
if len(array1) != len(array2):
return False
for num in array1:
try:
array2.remove(num**2)
except:
return False
return True if len(array2) == 0 else False
a1 = [121, 144, 19, 161, 19, 144, 19, 11]
a2 = [11*11, 121*121, 144*144, 19*19, 161*161, 19*19, 144*144, 19*19]
def comp_v2(array1, array2):
return False if None in (array1,array2) else sorted([x**2 for x in array1]) == sorted(array2)
print(comp_v2(a1,a2)) |
from linked_list import LinkedList
"""
Given a linked list which might contain a loop, implement an
algorithm that returns the node at the begining of the loop (if exists)
"""
# time complexity: O(n), space complexity: O(1)
def get_loop_head(list):
if list.head == None:
return None
fast_node = list.head
slow_node = list.head
while True:
fast_node = fast_node.next.next
slow_node = slow_node.next
if fast_node == None or fast_node.next == None:
return None
if fast_node is slow_node:
break
slow_node = list.head
while fast_node is not slow_node:
fast_node = fast_node.next
slow_node = slow_node.next
return fast_node
list = LinkedList(1)
loop_end = list.head
list.add(2)
list.add(3)
list.add(4)
list.add(5)
list.add(6)
list.add(7)
list.add(8)
loop_end.next = list.head
list.add(9)
list.add(10)
list.add(11)
print(get_loop_head(list).data)
|
#Given a string, write a function to check if it is a permutation of a palindrome.
def get_char_to_count_map(str):
charToCount = {}
for char in str:
if char == ' ':
continue
elif char in charToCount:
charToCount[char] = charToCount[char] + 1
else:
charToCount[char] = 1
return charToCount
# time complexity: O(n), space complexity: O(n)
def is_palindrome_permutation(str):
charToCount = get_char_to_count_map(str)
hasFoundOddCount = False
for char, count in charToCount.items():
if count % 2 != 0:
if hasFoundOddCount:
return False
hasFoundOddCount = True
return True
print(is_palindrome_permutation("tenet"))
print(is_palindrome_permutation("teent"))
print(is_palindrome_permutation("tteen"))
print(is_palindrome_permutation("teneta"))
print(is_palindrome_permutation("te net "))
|
# This program converts integers and fractions into binary numbers.
x = float(input("Think of a number for binary conversion : "))
numint = int(str(x).split(".")[0])
numffloat = float("."+str(x).split(".")[1])
p = 0
while (numffloat*(2**p))%1 != 0:
#print("remainder : " + str(numf*(2**p)- int(numf*(2**p))))
p +=1
afterd = ""
num = int(numffloat*(2**p))
while num>0:
afterd = str(num%2) + afterd
num= num//2
befored = ""
while numint > 0:
befored = str(numint%2) + befored
numint = numint//2
for i in range(p-len(afterd)):
afterd= "0" + afterd
final = befored + "." + afterd
print("Binary representation is : " +final) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from matplotlib import pyplot as plt
def plot_data(x, y):
plt.xlabel('Population of City in 10,000s')
plt.ylabel('Profit in $10,000s')
plt.plot(x, y, 'rx', markersize=6)
plt.show()
|
from itertools import cycle
from random import choice
from tic_tac_toe import tic_tac_toe_winner
board = " " * 9
symbol = cycle("XO")
while " " in board:
field = choice([n for n, s in enumerate(board) if s == " "])
board = board[:field] + next(symbol) + board[field + 1 :]
print(board)
winner = tic_tac_toe_winner(board)
if winner is not None:
print(f"{winner} won!")
break
else:
print("Tie!")
|
# -*- coding: utf-8 -*-
from sys import argv
from time import time
"""variation of dijkstras shortest path algorithm that searches route between cities that caries heaviest loads
comments in finnish for the finnish teacher"""
# lukee kartta tiedoston
def read_roads(name):
# phase määrää lukeeko ohjelma ensinmäisä riviä vai tie rivejä. roads kertoo monta tietä on lukematta ja kun tiet loppuvat, ohjelma tietää olevansä viimeisellä rivillä josta saadaan määränpää
phase = 0
tiedosto = open(name)
tulos = tiedosto.readlines()
for line in tulos:
line = line.rstrip()
if phase == 0:# ottaa talteen tie lukumäärän ja kaupunkien lukumäärän
cities, roads = line.split(" ")
phase += 1
cities = int(cities)
roads = int(roads)
lroads = []
for i in range(roads):
lroads.append([])
elif phase == 1 and roads > 0:
temp = line.split(" ")
temp = [int(i) for i in temp]
lroads[roads-1] = temp# luo listan mistä löytyy jokainen tie alku- ja loppupisteineen sekä tien paino
roads -= 1
else:
finish = int(line)
lcities = []
cities = range(cities)
for i in cities:
lcities.append(i+1)
return lcities, lroads, finish# funktio palauttaa tie- ja kaupunki-listat sekä määränpään
#luo kaupunki-objectin johon sisällytetään kaikki kyseiseen kaupunkiin liittyvät tiedot
class city:
def __init__(self, name):# alustaa kaupungin
self.name = name
self.nexto = {}# Kaupungin naapurit
self.weight = 0# painoraja jonka kaupunkiin voi tuoda. 0 tarkoittaa että kaupungille ei ole vielä reittiä eli ei tiedetä painorajaa
self.next = 0# kertoo mihin naapuriin täytyy mennä seuraavana. Määritellään myöhemmin
self.path = 0# kertoo mistä kaupungista tähän kaupunkiin on tultu
self.used = False# kertoo onko kaupungissa käyty
#seuraavat funktiot palauttavat tietoja kaupungista tai määrittelevät niitä
def set_weight(self, weight):
self.weight = weight
def get_name(self):
return self.name
def get_weight(self):
return self.weight
def set_nexto(self, next, limit):
self.nexto[next] = limit
def set_used(self):
self.used = True
#Kartta-objekti johon tallennetaan kaikki kaupungit kirjastoon
class map:
def __init__(self):
self.city_dir = {}
def __iter__(self):
return iter(self.city_dir.values())
def add_city(self, name):
town = city(name)
self.city_dir[name] = town
def add_road(self, start, end, weight):
self.city_dir[start].set_nexto(self.city_dir[end], weight)
self.city_dir[end].set_nexto(self.city_dir[start], weight)
def get_city(self, name):
return self.city_dir[name]
#dijkstran algoritmi jota on muunettu niin että se etsii reitin jonka kantovara on suurin lyhimmän reitin sijaan
def path_find(start, end, map):
not_visited = [(place.get_weight(), place)for place in map]# luo listan jossa on jokainen tutkimaton kaupunki painoineen
Pass = 0# jos = 0, reitti määränpäähän löytyy, jos 1 niin ei löydy
while True:
largest = 0
examine = None
for i in not_visited:# Etsii kaupungin jota tutkitaan seuraavaksi sillä perusteella että mihin kaupunkiin voi viedä suurimman kuorman
if i[0] > largest:
largest = i[0]
examine = i[1]
if examine == None:# mikäli ei ole tutkimatonta kaupunkia jonka paino olisi suurempi kuin 0, niin se tarkoittaa että kaikki kaupungit on tutkittu, joihin on reitti aloituskaupungista ja reittiä määränpäähän ei ole
Pass = 1
break
examine.set_used()# merkkaa tutkittavan kaupungin vierailluksi
for next in examine.nexto:# antaa kaupungin naapureille painoarvot teiden mukaan mikäli naapurissa ei ole käyty jo
if next.used == True:
pass
else:
if examine.nexto[next] < examine.weight and examine.weight != float("inf") or examine.weight == float("inf"):# jos tien paino on pienempi kun kaupungin paino, naapuri saa painokseen tien painon
examine.next = examine.nexto[next]
else:# jos tien painoraja on kaupungin painoa suurempi, naapuri saa painokseen tutkittavan kaupungin painon
examine.next = examine.weight
if next.weight < examine.next:# Mikäli naapurilla on jo paino ja se on pienempi kuin tutkittavan kaupungin sille tarjoama paino, naapurin painoksi tulee tutkittavan kaupungin paino
next.set_weight(examine.next)
next.path = examine
else:# Mikäli naapurin paino on tarjolla olevaa suurempi, on naapuriin olemassa jo reitti joka on tutkittavaa reittiä parempi joten ei tehdä mitään
pass
not_visited = []
for town in map:
if town.used == False:
not_visited.append((town.weight, town))# luo listan jossa on jokainen kaupunki jota algoritmi ei ole vielä käsitellyt sekä kaupungin paino
else:
pass
if map.get_city(end).used == True:# lopettaa reittihaun mikäli määränpää kaupunki on tutkittu
break
else:
pass
return Pass# funktio palauttaa tiedon siitä löytyikö reitti
#funktio joka antaa reitin, mikäli sellainen on syötteenä annettuun kaupunkiin
def path (route, city):
past = city.path
if past == 0:
pass
else:
name = past.get_name()
route.append(name)
path(route, past)
if __name__ == "__main__":
alku = time()
komento = argv[1]# lukee karttatiedoston nimen
nodes, edges, goal = read_roads(komento)# lukee karttatiedoston
map = map()# alustaa kartan
for node in nodes:# Alustaa kaikki kaupungit karttaan
map.add_city(node)
for road in edges:# Antaa jokaiselle kaupungille tiedot sen naapureista sekä teiden painot
map.add_road(road[0], road[1], road[2])
first = map.get_city(1)
first.set_weight(float("inf"))# määrittää aloituskaupungin painon äärettömäksi jotta algoritmi löytäisi aloituskaupungin
Pass = path_find(1, goal, map)# tekee reittihaun
weight = map.get_city(goal)
weight = weight.get_weight()
weight = weight-8# laskee kuinka suuren painon voi viedä määränpäähän
if Pass == 0 and weight > 0:# mikäli reitti on olemassa ja painoraja on nollaa suurempi, printtaa painon jonka reittiä pitkin voi kuljettaa
print(weight)
elif weight < 0 or Pass == 1:# mikäli painoraja on nollaa pienempi, ei ole reittiä mitä rekka voi kulkea joten printataan ettei reittiä ole
print("no route")
elif weight == 0:# mikäli painoraja on nolla, reitti on olemassa mutta sillä ei voi kuljettaa kuormaa
print("Maximum load = 0 / No route")
else:# mikäli pass on yksi, ei ole olemassa reittiä jolla voisi kuljettaa minkäänlaista kuormaa määränpäähän. Ei tehdä mitään koska tässä tilanteessa on jo printattu aiemmin ettei ole tietä
pass
loppu = time()
aika = loppu - alku
print (aika) |
print(float(4.6))
print(int(4.6))
print(int(3.7))
print(int(4.5))
print(int(4))
print(int(5))
print(float("three"))
#a.float(4.6) comes out as 4.6 but int(4.6) comes out as 4
#b.int(3.7) turns into 3
#c.int(4.5) turns into 4 so no, but int(4 and 5) works
#d.it dosen't work because three point six is a str() |
prime = [1]
GivenNumber = 600851475143
IterNumber = GivenNumber
idx = 2
while idx <= IterNumber:
if IterNumber % idx == 0:
IterNumber = IterNumber / idx
prime.append(idx)
#print(prime)
#print("New prime is: " + str(idx))
idx = idx + 1
Prime_Max = 1
for idx in prime:
if idx > Prime_Max:
Prime_Max = idx
# The The maximum prime for the given number is: 6857
print("The maximum prime for number " + str(GivenNumber) + " is: " + str(Prime_Max))
|
store = ["Name", "color", "x"]
y = input("What's your name? ")
store[0] = y
z = input("What is your favorite color? ")
store[1] = z
a = input("How many pets do you have? ")
store[2] = a
print(store[0] + "'s favorite color is " + store[1] + ". They have " + store[2] + " pets. ") |
# HOMEWORK: LESSON 1 : PRINTING AND SIMPLE ARITHMETIC
#
print("What is your name?")
print("My name is Li Zhang")
s = input("What is your age?")
print("I am " + s + " years old")
print("Or say I am " + str(int(s) * 12) + " months old")
|
age = int(input("What is your age? "))
age = age + 1
print("You will be " + str(age) + " next year") |
def dividing_func(x , y):
return x % y
x = int(input("Please input a dividend (number): "))
y = int(input("Please input a divisor (number): "))
if dividing_func(x , y) == 0:
print("The number " + str(x) + " is divisible by " + str(y) + ".")
else:
print("The number " + str(x) + " is not divisible by " + str(y) + ".")
print("Their remainder is " + str(x % y) + ".")
|
# Uses python3
import sys
def get_optimal_value(capacity, weights, values):
value = 0
W = capacity
# write your code here
# print(capacity, weights, values)
while W > 0:
max_value = -1
index = len(weights)
for i in range(0, len(weights)):
if weights[i] != 0 and values[i]/weights[i] > max_value:
max_value = values[i]/weights[i]
index = i
if index == len(weights):
break
w = min(W, weights[index])
value = value + (w * values[index] / weights[index])
weights[index] = weights[index] - w
W = W - w
return value
if __name__ == "__main__":
n, capacity = map(int, input().split())
values = []
weights = []
for i in range(0, n):
x, y = map(int, input().split())
values.append(x)
weights.append(y)
# values = data[2:(2 * n + 2):2]
# weights = data[3:(2 * n + 2):2]
opt_value = get_optimal_value(capacity, weights, values)
print("{:.10f}".format(opt_value))
|
# Uses python3
import sys
import random
import math
def binary_search(a, x):
left, right = 0, len(a)-1
# if right == 0:
# return -1
# # write your code here
# mid = (right + left) // 2
# if a[mid] == x:
# return mid
# elif a[mid] > x:
# return mid - binary_search(a[left:mid], x)
# else:
# # if mid+1
# return mid + binary_search(a[mid+1:], x)
while left <= right:
mid = (left+right) // 2
if a[mid] == x:
return mid
elif a[mid] > x:
right = mid - 1
else:
left = mid + 1
return -1
def linear_search(a, x):
for i in range(len(a)):
if a[i] == x:
return i
return -1
def stress_test():
n = math.floor(random.random()*1000000 + 2)
arr = [math.floor(random.random()*100000 - 50000)]*n
arr.sort()
linear = []
binary = []
test = n//2
testcase = [math.floor(random.random()*100 - 50)]*test
for i in testcase:
if linear_search(arr, i) == binary_search(arr, i):
print("Success")
else:
print("Error")
print(arr)
print(testcase)
print(i)
break
if __name__ == '__main__':
# input = sys.stdin.read()
# data = list(map(int, input.split()))
# n = (input())
# m = data[n + 1]
# a = data[1 : n + 1]
# stress_test()
a = list(map(int, input().split()))
n1 = a[0]
a = a[1:]
search = list(map(int, input().split()))
# for x in search[1:]:
# # replace with the call to binary_search when implemented
# print(linear_search(a, x), end=' ')
# print('')
for x in search[1:]:
print(binary_search(a, x), end=' ')
|
# Write a program to create a table of word frequencies by genre, like the one given in Section 2.1 for modals. Choose your own words and try to find words whose presence (or absence) is typical of a genre. Discuss your findings
import nltk
from nltk.corpus import brown
cfd = nltk.ConditionalFreqDist(
(genre,word.lower())
for genre in brown.categories()
for word in brown.words(categories=genre))
genres = ["news","religion","hobbies","science_fiction","romance","humor"]
words = ["who","what","when","where","why","which", "how"]
cfd.tabulate(conditions=genres,samples=words)
|
class Grade:
def __init__(self, kor, math, eng):
self.kor = kor
self.math = math
self.eng = eng
def sum(self):
return self.kor + self.math + self.eng
def avg(self):
return self.sum()/3
def get_grade(self):
score = int(self.avg())
# grade = ''
# --> 없어도 됨. 자바는 정적언어이기 때문에 미리 변수 선언을 해줘야하지만, 파이썬은 동적언어이기 때문에 하지 않아도 된다.
if score >= 90:
grade = 'A학점'
elif score >= 80:
grade = 'B학점'
elif score >= 70:
grade = 'C학점'
elif score >= 60:
grade = 'D학점'
elif score >= 50:
grade = 'E학점'
else:
grade = 'F학점'
return grade
@staticmethod
def main():
g = Grade(int(input('국어점수 입력')), int(input('수학점수 입력')), int(input('영어점수 입력')))
print(f'총점:{g.sum()}')
print(f'평균:{g.avg()}')
print(f'총점:{g.get_grade()}')
# print(f'{g.kor}+{g.math}+{g.eng}={g.sum()}')
# print(f'({g.kor}+{g.math}+{g.eng})/3={g.avg()}')
# hi
Grade.main()
|
class CalculatorConstructor:
# 생성자
def __init__(self, first, second): # init 메소드라 불린다.
self.first = first
self.second = second
def add(self):
return c.first + c.second
def sub(self):
return c.first - c.second
def mul(self):
return c.first * c.second
def div(self):
return c.first / c.second
if __name__ == '__main__': # 메인함수-> 실행포인트
c = CalculatorConstructor(1, 2) # c는 인스턴스라는 객체.
print(c.add())
print(c.sub())
print(c.mul())
print(c.div())
|
inp = input('Enter file name to open: ')
mylist = list()
try:
fh = open(inp)
except:
print('Sorry! Can\'t open file ')
quit()
for line in fh:
words=line.split()
for word in words:
if word not in mylist:
mylist.append(word)
else:
continue
mylist=sorted(mylist)
print(mylist) |
hours = input('Enter Hours:')
rate = input('Enter Rate:')
fhours=float(hours)
frate=float(rate)
if fhours>40:
pay = fhours*frate
epay = (fhours-40)*0.5*frate
tpay = pay+epay
else:
tpay=fhours*frate
print('Pay:',tpay)
|
time = float(input("Input time in minutes: "))
if (time<60):
hour=0
minutes=time
else:
hour=time/60
minutes=time%60
print("h:m-> %d %d" % (hour, minutes))
|
x = raw_input('Enter the string: ')
y = int(input('no of times: '))
def mul(a,b):
z = a*b
print z
mul(x,y)
|
a=int(input("Enter a 5 digit number"))
s=0
while(a!=0):
r=a%10
s=s*10+r
a//=10
print(s)
|
def countPairs(N1,N2,s):
c=0
for i in N1:
if s-i in N2:
c+=N2.count(s-i)
return c
N1=list(map(int,input("Enter elements of list1").split()))
N2=list(map(int,input("Enter elements of list2").split()))
s=int(input("Enter sum"))
print(countPairs(N1,N2,s))
|
n=int(input("Enter the no of batsmen"))
batsmen={}
print()
for i in range(1,n+1):
print("Enter the details of player:"+str(i))
batsmen[i]={'type':input("type"),'name':input("name"),'matches':input("no.of matches played"),'runs':input("runs scored"),'average':input("average score"),'highest score':input('highest score')}
print()
print(batsmen)
|
matrix=[[j for j in range(5)]for i in range(5)]
print(matrix)
flatten_matrix=[val for sublist in matrix for val in sublist]
print(flatten_matrix)
print()
matrix=[[j for j in range(10)]for i in range(5)]
print(matrix)
print()
flatten_even=[val for sublist in matrix for val in sublist if val%2==0]
print(flatten_even)
|
from abc import ABC, abstractmethod
# class Animal(ABC):
# def correr(self):
# print('Correr')
#
# @abstractmethod
# def respirar(self):
# pass
#
#
# class Cao(Animal):
# def respirar(self):
# print('Respirar como um cão')
#
#
# class Passaro(Animal):
# def respirar(self):
# print('Respirar como um passaro')
#
#
# # animal = Animal()
# # animal.correr()
# cao = Cao()
"""
Conta bancária
Conta, Conta corretne e conta poupança
"""
class Conta(ABC):
def __init__(self, numero_conta, saldo):
self._numero_conta = numero_conta
self._saldo = saldo
@property
def saldo(self):
return self._saldo
@saldo.setter
def saldo(self, valor):
self._saldo = valor
def depositar(self, valor):
if valor > 0:
self._saldo += valor
@abstractmethod
def sacar(self, valor):
pass
class ContaPoupanca(Conta):
def __init__(self,numero_conta, saldo):
super().__init__(numero_conta, saldo)
def sacar(self, valor):
limite = 300
if valor <= limite:
self._saldo -= valor
else:
print(f'Limite excedido (R${limite})')
class ContaCorrente(Conta):
def __init__(self,numero_conta, saldo):
super().__init__(numero_conta, saldo)
def sacar(self, valor):
limite = 600
if valor <= limite:
self._saldo -= valor
else:
print(f'Limite excedido (R${limite}) ')
conta = ContaCorrente(15256, 1000)
conta.depositar(200)
conta.sacar(850)
print(conta.saldo)
|
"""
Original Sourcecode pulled from:
https://thadeusb.com/weblog/2010/10/10/python_scale_hex_color/
"""
def clamp(val, minimum=0, maximum=255):
if val < minimum:
return minimum
if val > maximum:
return maximum
return val
def color_scale(hex_str, scale_factor):
"""
Scales a hex string by ``scale_factor``. Returns scaled hex string.
To darken the color, use a float value between 0 and 1.
To brighten the color, use a float value greater than 1.
>>> color_scale("#DF3C3C", .5)
#6F1E1E
>>> color_scale("#52D24F", 1.6)
#83FF7E
>>> color_scale("#4F75D2", 1)
#4F75D2
"""
hex_str = hex_str.strip("#")
if scale_factor < 0 or len(hex_str) != 6:
return hex_str
r, g, b = int(hex_str[:2], 16), int(hex_str[2:4], 16), int(hex_str[4:], 16)
r = int(clamp(r * scale_factor))
g = int(clamp(g * scale_factor))
b = int(clamp(b * scale_factor))
#return "#%02x%02x%02x" % (r, g, b)
return "#%02x%02x%02x" % (r, g, b)
|
import turtle
import math
import time
import random
import ball
from ball import Ball
turtle.bgcolor("black")
turtle.tracer(00)
turtle.hideturtle()
RUNNING = True
SLEEP = 0.0077
SCREEN_WIDTH = turtle.getcanvas().winfo_width()/2
SCREEN_HEIGHT = turtle.getcanvas().winfo_height()/2
#determines balls defenitions
NUMBER_OF_BALLS = 7
MINIMUM_BALL_RADIUS = 10
MAXIMUM_BALL_RADIUS = 73
MINIMUM_BALL_DX = -5
MAXIMUM_BALL_DX = 5
MINIMUM_BALL_DY = -5
MAXIMUM_BALL_DY = 5
BALLS = []
MY_BALL = Ball(0, 0, 2, 2, 60, "green")
for m in range(NUMBER_OF_BALLS):
x = random.randint(-SCREEN_WIDTH + MAXIMUM_BALL_RADIUS, SCREEN_WIDTH - MAXIMUM_BALL_RADIUS)
y = random.randint(-SCREEN_HEIGHT + MAXIMUM_BALL_RADIUS, SCREEN_HEIGHT - MAXIMUM_BALL_RADIUS)
dx = random.randint(MINIMUM_BALL_DX, MAXIMUM_BALL_DX)
dy = random.randint(MINIMUM_BALL_DY, MAXIMUM_BALL_DY)
radius = random.randint(MINIMUM_BALL_RADIUS, MAXIMUM_BALL_RADIUS)
color = (random.random(), random.random(), random.random())
new_ball = Ball(x, y, dx, dy, radius, color)
BALLS.append(new_ball)
def move_all_balls():
for ball in BALLS:
ball.move(SCREEN_WIDTH-20, SCREEN_HEIGHT-20)
#checks when balls collides
def collide(ball1, ball2):
if ball1 == ball2:
return False
x1 = ball1.xcor()
x2 = ball2.xcor()
y1 = ball1.ycor()
y2 = ball2.ycor()
d = ((x1-x2)**2+(y1-y2)**2)**0.5
if d+10 <= ball1.r+ball2.r:
return True
else:
return False
#borders
def draw_borders(corner_x, corner_y):
turtle.penup()
turtle.goto(-corner_x, -corner_y)
turtle.pendown()
turtle.color("red")
turtle.goto(-corner_x, corner_y)
turtle.goto(corner_x, corner_y)
turtle.goto(corner_x, -corner_y)
turtle.goto(-corner_x, -corner_y)
turtle.penup()
def check_all_balls_collision():
for ball1 in BALLS:
for ball2 in BALLS:
if collide(ball1, ball2):
rad1 = ball1.r
rad2 = ball2.r
x = random.randint(-SCREEN_WIDTH + MAXIMUM_BALL_RADIUS, SCREEN_WIDTH - MAXIMUM_BALL_RADIUS)
y = random.randint(-SCREEN_HEIGHT + MAXIMUM_BALL_RADIUS, SCREEN_HEIGHT - MAXIMUM_BALL_RADIUS)
dx = random.randint(MINIMUM_BALL_DX, MAXIMUM_BALL_DX)
dy = random.randint(MINIMUM_BALL_DY, MAXIMUM_BALL_DY)
r = random.randint(MINIMUM_BALL_RADIUS, MAXIMUM_BALL_RADIUS)
color = (random.random(), random.random(), random.random())
if ball1.r > ball2.r:
ball2.goto(x, y)
ball2.dx = dx
ball2.dy = dy
ball2.r = r
ball2.shape("circle")
ball2.shapesize(r/10)
ball2.fillcolor(color)
ball1.r += 1
ball1.shapesize(ball1.r/10)
else:
ball1.goto(x, y)
ball1.dx = dx
ball1.dy = dy
ball1.r = r
ball1.shape("circle")
ball1.shapesize(r/10)
ball1.fillcolor(color)
ball2.r += 1
ball2.shapesize(ball2.r/10)
#checks what touches my ball
def check_myball_collision():
for BALL in BALLS:
if collide(MY_BALL, BALL):
myballr = MY_BALL.r
ballr = BALL.r
if MY_BALL.r < BALL.r:
return False
else:
MY_BALL.r += 1
MY_BALL.shapesize(MY_BALL.r/10)
x = random.randint(-SCREEN_WIDTH + MAXIMUM_BALL_RADIUS, SCREEN_WIDTH - MAXIMUM_BALL_RADIUS)
y = random.randint(-SCREEN_HEIGHT + MAXIMUM_BALL_RADIUS, SCREEN_HEIGHT - MAXIMUM_BALL_RADIUS)
dx = random.randint(MINIMUM_BALL_DX, MAXIMUM_BALL_DX)
dy = random.randint(MINIMUM_BALL_DY, MAXIMUM_BALL_DY)
r = random.randint(MINIMUM_BALL_RADIUS, MAXIMUM_BALL_RADIUS)
color = (random.random(), random.random(), random.random())
BALL.goto(x,y)
BALL.dx = dx
BALL.dy = dy
BALL.r = r
return True
#moves my ball
def movearound(event):
x = event.x - SCREEN_WIDTH
y = SCREEN_HEIGHT - event.y
MY_BALL.goto (x,y)
turtle.getcanvas().bind("<Motion>", movearound)
turtle.listen()
while RUNNING:
SCREEN_WIDTH = turtle.getcanvas().winfo_width()/2
SCREEN_HEIGHT = turtle.getcanvas().winfo_height()/2
move_all_balls()
check_all_balls_collision()
RUNNING = check_myball_collision()
draw_borders(SCREEN_WIDTH - 20, SCREEN_HEIGHT-20)
turtle.update()
time.sleep(SLEEP)
#writes game over
turtle.color("red")
turtle.goto(0,0)
turtle.write("Game over", align = "center", font = ("david" ,90, "normal"))
time.sleep(3)
|
import sys
sys.stdout = open('output.txt', 'w')
sys.stdin = open('input.txt', 'r')
#please remove above 3 lines if you are using teminal for input and output
def merge(li1,li2):
total = len(li1) + len(li2)
n = len(li1)
m = len(li2)
outLi = [0]*total
i = 0
j = 0
k = 0
while i < total :
if(k == m or (j < n and li1[j] < li2[k])):
outLi[i] = li1[j]
j += 1
else :
outLi[i] = li2[k]
k +=1
i += 1
return outLi
def mergeSort(arr,left,right):
if(left == right):
li = []
li.append(arr[left])
return li
mid = left + right // 2
leftSortedHalf = mergeSort(arr, left, mid)
rightSortedHalf = mergeSort(arr, mid + 1, right)
output = merge(leftSortedHalf, rightSortedHalf)
return output
li = input().split(' ')
size = len(li)
for i in range(0,size):
li[i] = int(li[i])
sortedLi = mergeSort(li, 0, size-1)
print(li)
print(sortedLi) |
n = input().split(" ")
len = len(n)
lis = []
ans = 0
i = 0
while i < len :
ele = int(n[i])
ans = ans ^ ele
i = i + 1
lis.append(ele)
print("In the list ", lis, "unique element is", ans)
## LOGIC :
''' If you remember if you XOR any element with itself
answer will be zero
and if you will XOR any element with zero
answer will be element itself only
'''
|
## given a sorted list and an integer x
## find the first value in the list which is grater or equal to x
import sys
sys.stdout = open('output.txt', 'w')
sys.stdin = open('input.txt', 'r')
def findElement(li, tar):
n = len(li)
start = 0
end = n-1
while(start <= end):
mid = start + (end-start)//2
if tar >= li[mid] :
start = mid + 1
else :
end = mid - 1
return start
li = [int(x) for x in input().split(' ')]
target = int(input())
index = findElement(li, target)
print(index) |
numbers=int(input())
for i in range(numbers):
for k in range(i,-1, -1):
print('Осталось секунд:', k)
print('Пуск', i+1) |
nums = input().split()
from_to = input().split()
squares_of_nums = [int(i)**2 for i in nums]
from_to = [int(i) for i in from_to]
print(sum(squares_of_nums[from_to[0]:from_to[1]+1]))
|
from yandex_testing_lesson import is_correct_mobile_phone_number_ru
ans = ''
numbers = ['+7(900)1234567', '8(900)1234567', '+7 999 123-45-67',
'+7-999-123-45-67', '8 (900) 123 45 67']
for i in numbers:
if is_correct_mobile_phone_number_ru(i):
ans = 'YES'
else:
ans = 'NO'
notnumber = ['9(900)1234567', '+7(9lo)1234567', '+7(900)12(345)67',
'+7)900(12((3456))7']
for i in notnumber:
if is_correct_mobile_phone_number_ru(i):
ans = 'NO'
else:
ans = 'YES'
print(ans)
|
word= input()
while True:
if word[0] == 'А' or word[0] == 'а':
print('ДА')
break
if word[0] != 'А' or word[0] != 'а':
print('НЕТ')
break
|
from yandex_testing_lesson import is_prime
ans = ''
prime_nums = ['2', '3', '5', '7', '11', '13', '17', '19', '23', '29', '31',
'83', '89', '97', '101', '103', '107', '109']
for i in prime_nums:
if is_prime(i) in prime_nums:
ans = 'YES'
else:
ans = 'NO'
complicated = ['6', '9', '144', '1075', '6111']
for i in complicated:
if is_prime(i) in complicated:
ans = 'NO'
else:
ans = 'YES'
if is_prime('0') != 'ValueError' or is_prime('1') != 'ValueError':
ans = 'NO'
print('ans') |
city=input()
city1=input()
while True:
if city[-1] == 'ь':
city=city[:-1]
if city[-1] == city1[0]:
print('ВЕРНО')
break
else:
print('НЕВЕРНО')
break |
num=int(input())
search=[]
for i in range(num):
search.append(input())
n=int(input())
search_words=[]
final=[]
for i in range(n):
search_words.append(input())
for i in range(len(search)):
there_is_search_word=True
for j in range(len(search_words)):
if search_words[j] not in search[i]:
there_is_search_word=False
if there_is_search_word:
final.append(search[i])
for i in range(len(final)):
print(final[i]) |
import string
skip_window=2
f=open('./aesop10.txt','r')
l=list(f)
original_text=[]
for x in l:
original_text=original_text+x.split(' ')
n_wordLine=len(original_text)
new_text=[]
# print original_text
pos=string.punctuation.find('.') # position of the period
punc_Period=string.punctuation[0:pos]+string.punctuation[pos+1:] # removes period from string.punctuation
for x in original_text:
# apparently the best way to remove punctuations
# https://stackoverflow.com/questions/265960/best-way-to-strip-punctuation-from-a-string-in-python
# unpunctuated_str=string.translate(x,None,string.punctuation)
perioded_str=string.translate(x,None,punc_Period) # removes all punctuations except period
# noNewLine_str=string.replace(unpunctuated_str,'\n','')
noNewLine_perioded_str=string.replace(perioded_str,'\n','') # replace newline with empty string
noNewLine_perioded_str=string.replace(noNewLine_perioded_str,'\r','')
# new_text=new_text+[noNewLine_str]
# new_text is a list of words where newline is replaced by '' and punctuations except '.' have been removed
new_text=new_text+[noNewLine_perioded_str]
word_to_context=dict()
assert n_wordLine==len(new_text)
print new_text
x=0
while x < n_wordLine :
if x-skip_window>-1 and x+skip_window<n_wordLine and new_text[x]!='' and new_text[x][-1:]!='.':
buffer=new_text[x-skip_window:x]+new_text[x+1:x+skip_window+1] #[m words][x][m words]
flag=True
i=0
while i<len(buffer) and flag==True:
if i!=len(buffer)-1 and buffer[i][-1:]!='.' and buffer[i]!='':
i=i+1
elif i==len(buffer)-1 and buffer[i]!='':
if buffer[i][-1:]=='.':
buffer[i]=buffer[i][:-1]
i=i+1
else:
flag=False
if flag==True:
word_to_context[x]=buffer
print "Buffer "+str(x)
print buffer
x=x+skip_window
else:
flag=True
x=x+1
locations=word_to_context.keys() # locations to encrypt
# print word_to_context
# print "Length of word_to_context="+ str(len(word_to_context))
# print "Locations to encrypt: " + str(locations)
|
# https://www.lintcode.com/problem/edit-distance/description
# 区间型DP要从最大状态开始想,类似分治。从小到大的DP用循环,从大到小的DP用记忆化搜索
class Solution:
"""
@param word1: A string
@param word2: A string
@return: The minimum number of steps.
"""
def minDistance(self, word1, word2):
# write your code here
if len(word1) == 0 and len(word2) == 0:
return 0
if len(word1) == 0:
return len(word2)
if len(word2) == 0:
return len(word1)
# DP[i][j]: the minimim steps to covert word1[0:i+1] to word2[0:j+1]
DP = [[0] * len(word1) for i in word2]
# row
tmp = 0
flag = True
for i in range(len(word2)):
if word2[i] != word1[0]:
tmp += 1
DP[i][0] = tmp
else:
if flag:
flag = False
else:
tmp += 1
DP[i][0] = tmp
# col
tmp = 0
flag = True
for j in range(len(word1)):
if word1[j] != word2[0]:
tmp += 1
DP[0][j] = tmp
else:
if flag:
flag = False
else:
tmp += 1
DP[0][j] = tmp
for i in range(1, len(DP)):
for j in range(1, len(DP[0])):
if word1[j] != word2[i]:
# delete: DP[i-1][j]
# insert: DP[i][j-1]
# replace: DP[i-1][j-1]
DP[i][j] = min(DP[i-1][j], DP[i][j-1], DP[i-1][j-1])+1
else:
DP[i][j] = min(DP[i-1][j]+1, DP[i][j-1]+1, DP[i-1][j-1])
return DP[-1][-1]
|
# 총점, 평균, 학점
name='name'
kor=90
mat=70
eng=90
def getTotal():
#pass - 함수 작성전 쓰는 더미코드!
total = kor+mat+eng
return total
def getAverge():
total=getTotal()
average=total/3
return average
def getGrade():
average=getAverge()
grd='가'
if average > 100 or average >= 90:
grd='수'
elif average >= 80:
grd='우'
elif average >= 70:
grd = '미'
elif average >= 60:
grd = '양'
return grd
fmt = '%s %d %d %d %d %.2f %s'
print(fmt % (name, kor, eng, mat, getTotal(), getAverge(), getGrade()))
|
class Card():
"""
Base card class
"""
type: str
value: int
def __init__(self, type, value):
self.type = type
self.value = value
def __str__(self):
display = f"{self.type}\t\t"
if 1 <= self.value <= 10:
display += str(self.value)
elif self.value == 11:
display += "Jack"
elif self.value == 12:
display += "Queen"
elif self.value == 13:
display += "King"
if display == f"{self.type} ":
raise ValueError('Unidentfied card value/type')
return display
|
from Oving8.ship import Ship
class Position:
shot: bool
__ship: Ship
def __init__(self, x_position, y_position):
self.x_position = x_position
self.y_position = y_position
self.shot = False
self.__ship = None
@property
def is_taken(self):
return self.__ship is not None
def shoot(self):
if self.shot:
return False # Trying to shoot the place twice
self.shot = True
if self.is_taken:
self.__ship.hit()
return True
def set_ship(self, ship: Ship):
self.__ship = ship
def enemy_status(self):
if self.shot and self.is_taken and self.__ship.is_sunk():
return "Ø"
if self.shot and self.is_taken:
return "S"
if self.shot:
return "o"
return "~"
def __str__(self):
if self.shot and self.is_taken and self.__ship.is_sunk():
return "Ø"
if self.shot and self.is_taken:
return "S"
if self.shot:
return "o"
if self.is_taken:
return "M"
return "~"
|
from circle import Circle
if(__name__ == "__main__"):
first_circle = Circle(4, 4, 5)
second_circle = Circle(14, 5, 5.1)
third_circle = Circle(7, 15, 6)
fourth_circle = Circle(9.35, -0.58, 2.04)
print(first_circle)
print(second_circle)
print(third_circle)
print(fourth_circle)
print("First circle area (78.539...): {0}".format(first_circle.area()))
print("Second circle area (81.712...): {0}".format(second_circle.area()))
print("Third circle area (113.097...): {0}".format(third_circle.area()))
print("Fourth circle area (13.074...): {0}".format(fourth_circle.area()))
print("First circle distance to second circle (10.05): {0}".format(first_circle.distance(second_circle)))
print("First circle distance to fourth circle (7.04): {0}".format(first_circle.distance(fourth_circle)))
print("First & second circle overlap (true): {0}".format(first_circle.overlap(second_circle)))
print("First & third circle overlap (false): {0}".format(first_circle.overlap(third_circle)))
print("Second & third circle overlap (false): {0}".format(second_circle.overlap(third_circle)))
print("First & fourth circle overlap (true): {0}".format(first_circle.overlap(fourth_circle)))
print("Second & fourth circle overlap (false): {0}".format(second_circle.overlap(fourth_circle)))
print("First circle equals second circle (false): {0}".format(first_circle == second_circle))
print("First circle equals new same info circle (true): {0}".format(first_circle == Circle(4,4,5))) |
# -*- coding:utf8 -*-
import os
def rename(dirpath):
path = dirpath
filelist = os.listdir(path) # 该文件夹下所有的文件(包括文件夹)
try: # (第二次改名的话,一定要排序,因为os.listdir生成的元素是随机的,第二次改名(os.rename函数)会将第一生成的同名文件覆盖,导致总文件数目变少)
filelist.sort(key=lambda x: int(x[:-4]))
print "文件有序"
return True
except:
print "第一次排序"
for count, files in enumerate(filelist, 1): # 遍历所有文件
Olddir = os.path.join(path, files) # 原来的文件路径
if os.path.isdir(Olddir): # 如果是文件夹则跳过
continue
filename = os.path.splitext(files)[0] # 文件名
filetype = os.path.splitext(files)[1] # 文件扩展名
Newdir = os.path.join(path, ("%09d" % count) + filetype) # 新的文件路径
os.rename(Olddir, Newdir) # 重命名
return True
if __name__ == "__main__":
for i in os.listdir('./image/car'):
# print i
tmpdir = os.path.join("./image/car/", i)
if not os.path.isdir(tmpdir): # 如果是文件则跳过
continue
rename(tmpdir)
|
import sys # print("Debug messages...", file=sys.stderr)
import math
root = {}
count = 0
n = int(input())
for _ in range(n):
print("root", root, file=sys.stderr)
current = root
phone_number = input()
for number in phone_number:
if number not in current:
current[number] = {}
count += 1
print("current", current, file=sys.stderr)
print("root", root, file=sys.stderr)
current = current[number]
print(count)
|
from typing import List
# Name: Split Array Largest Sum
# Link: https://leetcode.com/problems/split-array-largest-sum
# Method: Dynamic programming, keep track of dp[partitions][to index] (alternatively, greedy binary search)
# Time: O(n^2 \* m)
# Space: O(n \* m)
# Difficulty: Hard
class Solution:
def splitArray(self, nums: List[int], m: int) -> int:
memo = {}
return self.get_smaller_part_dp(nums, m)
@staticmethod
def get_smaller_part_dp(arr: List[int], m: int):
n = len(arr)
# Memo matrix, w/ padding
dp = [[float("inf") for _ in range(n + 1)] for _ in range(m + 1)]
dp[0][0] = 0
# Prefix sums
sum_to = [0]
for i in range(n):
sum_to.append(sum_to[-1] + arr[i])
for parts in range(1, m + 1):
for poz in range(1, len(arr) + 1):
for prev_poz in range(poz - 1, -1, -1):
current_sum = sum_to[poz] - sum_to[prev_poz]
dp[parts][poz] = min(
dp[parts][poz],
max(dp[parts - 1][prev_poz], current_sum),
)
if current_sum > dp[parts - 1][prev_poz]:
break
for line in dp:
print([f"{x:4}" for x in line])
return dp[-1][-1]
@staticmethod
def get_smaller_part_brute_force(arr: List[int], start: int, parts: int, memo):
if (start, parts) in memo:
return memo[(start, parts)]
n = len(arr)
if parts == n - start:
# print(f"Best rez for {start=} {parts=} is {max(arr[start:])}")
return max(arr[start:])
elif parts == 1:
# print(f"Best rez for {start=} {parts=} is {sum(arr[start:])}")
return sum(arr[start:])
current_part_sum = 0
best_min = float("inf")
for start_point in range(start, n - parts + 1):
current_part_sum += arr[start_point]
min_of_rest_part = Solution.get_smaller_part(
arr, start_point + 1, parts - 1, memo
)
best_min = min(best_min, max(current_part_sum, min_of_rest_part))
memo[(start, parts)] = best_min
# print(f"Best rez for {start=} {parts=} is {best_min=}")
return best_min
|
from typing import List
class Solution:
def maxLength(self, arr: List[str]) -> int:
combo_list = [set()]
for x in arr:
if len(set(x)) != len(x):
continue # duplicates smh
x_l = set(x)
for combo in combo_list:
# If no letters in common
if len(set(combo & x_l)) == 0:
combo_list.append(combo | x_l)
return len(max(combo_list, key=len))
if __name__ == "__main__":
sol = Solution()
print(sol.maxLength(["cha", "r", "act", "ers"]))
|
from typing import List
import unittest
from collections import defaultdict
# Name: Subarray Sum Equals K
# Link: https://leetcode.com/problems/subarray-sum-equals-k/
# Method: Prefix sum, store number of ways to get to a sum, check against target
# Time: O(n)
# Space: O(n)
# Difficulty: Medium
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
sumseen = defaultdict(int)
sum_now = 0
nr_arrs = 0
for x in nums:
sum_now += x
if sum_now == k:
nr_arrs += 1
if sum_now - k in sumseen:
nr_arrs += sumseen[sum_now - k]
sumseen[sum_now] += 1
return nr_arrs
class TestSolution(unittest.TestCase):
def setUp(self):
self.sol = Solution()
def test_negative(self):
nums = [0, 1, -1]
k = 0
rez = self.sol.subarraySum(nums, k)
self.assertEqual(rez, 3)
def test_small(self):
nums = [1, 2, 3]
k = 3
rez = self.sol.subarraySum(nums, k)
self.assertEqual(rez, 2)
def test_ones(self):
nums = [1, 1, 1]
k = 1
rez = self.sol.subarraySum(nums, k)
self.assertEqual(rez, 3)
unittest.main()
|
#!/bin/python3
import sys
n = int(input().strip())
height = [int(height_temp) for height_temp in input().strip().split(' ')]
height.sort()
height.reverse()
maxCand =1
while(True):
if(maxCand >= len(height) or height[maxCand-1]!=height[maxCand]):
break
maxCand+=1
print(maxCand)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.