text stringlengths 37 1.41M |
|---|
# USAGE
# python drawing.py
# Import the necessary packages
import numpy as np
import cv2
def draw_line():
# Draw a green line from the top-left corner of our canvas
# to the bottom-right
green = (0, 255, 0)
cv2.line(canvas, (0, 0), (300, 300), green)
cv2.imshow("Canvas", canvas)
cv2.waitKey(0)
def draw_rectangle():
# Draw a green 50x50 pixel square, starting at 10x10 and
# ending at 60x60
green = (0, 255, 0)
cv2.rectangle(canvas, (10, 10), (60, 60), green)
cv2.imshow("Canvas", canvas)
cv2.waitKey(0)
def draw_ellipse():
red = (255, 0, 0)
cx,cy = 201,113
ax1,ax2 = 37,27
angle = -108
center = (cx,cy)
axes = (ax1,ax2)
cv2.ellipse(canvas, center, axes, angle, 0, 360, red, 2)
def draw_circle():
# Reset our canvas and draw a white circle at the center
# of the canvas with increasing radii - from 25 pixels to
# 150 pixels
(centerX, centerY) = (canvas.shape[1] / 2, canvas.shape[0] / 2)
white = (255, 255, 255)
for r in xrange(0, 175, 25):
cv2.circle(canvas, (centerX, centerY), r, white)
cv2.imshow("Canvas", canvas)
cv2.waitKey(0)
def draw_fillpoly():
pts = np.array([[10,5],[20,30],[70,20],[50,10]], np.int32)
pts = pts.reshape((-1,1,2))
cv2.polylines(canvas,[pts],True,(0,255,255),3)
cv2.imshow("Canvas", canvas)
cv2.waitKey(0)
def draw_color():
# Let's go crazy and draw 25 random circles
for i in xrange(0, 25):
# randomly generate a radius size between 5 and 200,
# generate a random color, and then pick a random
# point on our canvas where the circle will be drawn
radius = np.random.randint(5, high = 200)
color = np.random.randint(0, high = 256, size = (3,)).tolist()
pt = np.random.randint(0, high = 300, size = (2,))
# draw our random circle
cv2.circle(canvas, tuple(pt), radius, color, -1)
# Show our masterpiece
cv2.imshow("Canvas", canvas)
cv2.waitKey(0)
def put_text():
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(canvas, 'Hello zhangyushan', (10,50), font, 1, (255,255,255) , 2, cv2.LINE_AA)
#cv2.putText(canvas, "Hello Zhangyushan", (50,50), cv2.FONT_HERSHEY_SIMPLEX, .6, (0, 255, 0), 1, 2)
cv2.imshow("Canvas", canvas)
cv2.waitKey(0)
if __name__=="__main__":
#ap = argparse.ArgumentParser()
#ap.add_argument("-i", "--image", required = True,
# help = "Path to the image")
#args = vars(ap.parse_args())
# Initialize our canvas as a 300x300 with 3 channels,
# Red, Green, and Blue, with a black background
canvas = np.zeros((400, 400, 3), dtype = "uint8")
draw_line();
draw_rectangle()
draw_ellipse()
draw_circle()
draw_fillpoly()
draw_color()
put_text()
|
from Aluno import Aluno
nome = input("Nome do aluno: ")
curso = input("Nome do Curso: ")
horasSemDormir = int(input("Quantidades de horas sem dormir: "))
horasDeEstudos = int(input("Quantidades de horas de estudo: "))
dormir = int(input("Quantidades de horas sono: "))
aluno = Aluno(nome, curso, horasSemDormir)
aluno.estudar(horasDeEstudos)
aluno.dormir(dormir)
print("%s esta %d horas sem dormir" % (aluno.nome, aluno.tempoSemDormir)) |
miles = float(input("Please enter the miles you drove: "))
gallons = float(input("Please enter the amount of gallons you put in the tank: "))
mpg = int(miles/gallons)
print("You got", mpg, "mpg on that tank of gas.")
|
#!/usr/bin/env python
#coding:UTF-8
def isMatch(s, p):
if len(p) == 0:
return len(s) == 0
if len(p) == 1:
return len(s) == 1 and p[0] == s[0]
if p[1] == '*':
while len(s) != 0 and (p[0] == '.' or p[0] == s[0]):
if isMatch(s, p[2:]):
return True
s = s[1:]
return isMatch(s, p[2:])
else:
if len(s) != 0 and (p[0] == '.' or p[0] == s[0]):
return isMatch(s[1:], p[1:])
return False
if __name__ == '__main__':
print isMatch('aa', 'a')
print isMatch('aa', 'aa')
print isMatch('aaa', 'a')
print isMatch('aa', '.*')
print isMatch('ab', '.*')
print isMatch('aab', 'c*a*b')
print isMatch('aaaab', '.*ab')
print isMatch('aaaaaaaaccc', 'a*ccc')
|
# A List is a collection which is ordered and changeable. Allows duplicate members.
arr = ['apple', 'pear', 'strawberry', 'mango']
arr.sort()
print(len(arr))
|
#!/usr/bin/env python
import sys
import csv
data=csv.reader(sys.stdin, delimiter=',')
for info in data:
if info[12]:
value=float(info[12])
else:
value=float(0.00)
print(info[2] + '\t'+str(value)+',' + '1.00')
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
# Question1:
person_dict={"first_name":"Muhammad Asad","last_name":"Ahmed","age":"22","city":"Sukkur"}
for key, value in person_dict.items():
print(key+" : "+value)
print("\n Add qualification \n")
person_dict["qualification"]="Intermediate"
for key, value in person_dict.items():
print(key+" : "+value)
print("\n New qualification \n")
person_dict["qualification"]="BCom"
for key, value in person_dict.items():
print(key+" : "+value)
# In[8]:
#Q2
cities={
"Lahore":{
"country":"pakistan",
"population":11188000,
"fact":"Lahore is the province of Punjab. It is the second largest and most beautiful city in Pakistan"
},
"Karachi":{
"country":"pakistan",
"population":14741000,
"fact":"Karachi is contribute 70 per cent of income tax."
},
"Islamabad":{
"country":"pakistan",
"population":195049,
"fact":"Islamabad is the capital of pakistan."
},
}
for citykey,cityinfo in cities.items():
print("\n"+citykey+"\n")
for city in cityinfo:
print(city+" : "+str(cityinfo[city]))
# In[11]:
#Q3
for i in range(1,4):
age = int(input("Enter your age: "))
if age>0 and age<3:
print("The ticket for you is free.")
elif age>3 and age<13:
print("The tick for you us $10.")
else:
print("The ticket for you is $15.")
# In[13]:
#Q4
def favorite_book(title):
print("One of my favorite books is", title)
favorite_book("Smart way to learn phyton")
# In[14]:
#Q5
import random
c=0
rNumber=0
while c<3:
rNumber=int(random.randrange(1,30))
userNumber=int(input("Enter number between 1 and 30: "))
c=c+1
if rNumber>userNumber:
print("Hidden number is greater\n")
elif rNumber<userNumber:
print("Hidden number is Smaller\n")
else:
print("Hidden number is equal\n")
# In[ ]:
|
naam = str(input("Naam: "))
percent = int(input("Behaalde percentage: "))
while naam != "xx" or "XX":
if (percent < 0 or percent > 100):
print("ongelevdig percent")
elif(percent >= 0 or percent <= 100):
if(percent < 60):
print("onvoldoende")
elif(percent < 70):
print("voldoende")
elif(percent < 80):
print("onderscheiding")
elif(percent < 85):
print("grote onderscheiding")
else:
print("grootste onderscheiding")
naam = str(input("Naam: "))
percent = int(input("Behaalde percentage: "))
print("klaar!") |
def main():
aantal_karakters = int(input("Hoeveel karakters wil je ingegeven? "))
teller = 0
som = 0
while teller != aantal_karakters:
karakter = input("Geef een karakter in: ")
if karakter >= 'a' and karakter <= 'z':
print(karakter, "is een kleine letter")
elif karakter >= 'A' and karakter <= 'Z':
print(karakter, "is een hoofdletter")
elif karakter >= '0' and karakter <= '9':
som += int(karakter)
else:
print("Karakter onbekend")
teller += 1
print("som van alle opgegeven getallen:", som)
if __name__ == '__main__':
main() |
totaal = 0
for x in range(5):
getal = int(input("Geef een getal "))
totaal += getal
print(totaal) |
def main():
fruitlist = ["appel", "banaan", "kers", "mandarijn", "mango"]
for element in fruitlist:
print(element)
element = element.upper()
print(element)
if __name__ == '__main__':
main() |
def main():
def delete_double(list):
for element in list:
if list.count(element) > 1:
list.remove(element)
else:
print(element)
numberlist = ["1", "1", "1", "1", "2", "5", "6", "8", "5", "5", "6", "8", "8", "7", "5"]
delete_double(numberlist)
if __name__ == '__main__':
main() |
# -*- coding: utf-8 -*-
class Branch:
# poszczególne gałęzie - ściany piramid - mają postać:
# f(x, y) = (aX*x + bX) * (aY*y + bY)
def __init__(self, aX, bX, aY, bY):
self.aX = aX
self.bX = bX
self.aY = aY
self.bY = bY
def f(self, x, y):
return (self.aX*x + self.bX)*(self.aY*y + self.bY)
def dXf(self, x, y):
return self.aX*(self.aY*y + self.bY)
def dYf(self, x, y):
return self.aY*(self.aX*x + self.bX)
|
for i in range(int(input())):
n = int(input())
gest = list(input())
if "Y" in gest:
print("NOT INDIAN")
elif "N" in gest and "I" not in gest:
print("NOT SURE")
elif "I" in gest:
print("INDIAN")
|
for i in range(int(input())):
j = list(map(int, input().split()))
s = j[0]
if(j[1] + j[2] + j[3] <= s):
print(1)
elif((j[1] + j[2]) <= s or (j[2] + j[3]) <= s):
print(2)
else:
print(3)
|
t = int(input())
for i in range(t):
a, b, c = input().split()
t = 0
a = int(a)
b = int(b)
c = int(c)
t = a + b + c
if t == 180:
print("YES")
else:
print("NO")
|
for i in range(int(input())):
j = input()
s = ["2010","2015","2016","2017","2019"]
if j in s:
print("HOSTED")
else:
print("NOT HOSTED")
|
for i in range(int(input())):
j = input()
if(len(set(j)) == len(j)):
print("no")
else:
print("yes")
|
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
header=ListNode(0)
header.next=head #记录头
p1=p2=header
for i in range(n):p1=p1.next
while p1.next:
p1=p1.next
p2=p2.next
p2.next=p2.next.next
return header.next |
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n=len(nums)
if n<3:return n
index=2
for i in range(2,n):
if nums[i]!=nums[index-2]:
nums[index]=nums[i]
index+=1
return index
|
"# Use of Directories It is like Map"
students = {"nakul": 20, "dhrumil": 20, "bhautik": 22}
print(students["nakul"])
"# Update the value in dictionaries #"
students["nakul"] = 21
print(students["nakul"])
"# Delete the value in dictionaries #"
del students["dhrumil"]
print(students)
"# Length of dictionaries In this it is 2#"
print(len(students))
"# clear everything in dictionaries #"
students.clear()
del students
students = {"nakul": 20, "dhrumil": 20, "bhautik": 22}
"# To get all the keys of dictionaries #"
print(students.keys())
"# To get all the values of dictionaries #"
print(students.values())
"# Add values of two dictionaries #"
students1 = {"elon": 50, "jeff": 40, "mark": 60}
students.update(students1)
print(students)
|
def main():
#print("Inserir tamanho da matrix (m x n)")
linhas, colunas = input().split(" ")
#print(f"Inserir matriz ({linhas} x {colunas})")
matrix = [input().split("\n") for i in range(int(linhas))]
for i in range(len(matrix)):
matrix[i] = matrix[i][0].split(" ")
print(90)
rotated = rotate(matrix)
print_matrix(rotated)
for i in range(2,4,1):
print(f"{90*i}")
rotated = rotate(rotated)
print_matrix(rotated)
def rotate(matrix):
inverted = [ [0 for i in range(len(matrix))] for i in range(len(matrix[0]))]
matrix.reverse()
for i in range(len(matrix)):
for j in range(len(matrix[i])):
inverted[j][i] = matrix[i][j]
return inverted
def print_matrix(matrix):
# matrix = ['1','2','3']
# ['4','5','6']
for i in range(len(matrix)):
aux = ""
for j in range(len(matrix[i])): # matrix[i] = ['1','2','3']
if j == len(matrix[i])-1:
aux = aux + matrix[i][j]
else:
aux = aux + matrix[i][j] + " "
print(aux)
main()
|
f = open("ppp.txt", "r")
text = f.read().strip().split(" ")
f.close()
word = raw_input("what word are you looking for: ").strip()
def find_word_freq(w):
correct_words = [x for x in text if x == w]
return(len(correct_words))
print(find_word_freq(word))
phrase = raw_input("what word phrase are you looking for: ").strip()
def find_word_phrase_freq(wp):
phrase_combos = [text[i] + " " + text[i+1] + " " + text[i+2] for i in range(len(text)-2)]
correct_phrases = [x for x in phrase_combos if x == wp]
return len(correct_phrases)
print(find_word_phrase_freq(phrase))
most_freq_word = reduce(lambda x,y: x if find_word_freq(x) > find_word_freq(y) else y, text)
print(most_freq_word)
|
'''
Created on 27/10/2015
@author: Maxim Scheremetjew
amended 07/11/2016 by Maxim Scheremetjew
version: 1.1
'''
import argparse
import csv
import os
import urllib
import urllib2
from urllib2 import URLError
def _download_resource_by_url(url, output_file_name):
"""Kicks off a download and stores the file at the given path.
Arguments:
'url' -- Resource location.
'output_file_name' -- Path of the output file.
"""
print "Starting the download of the following file..."
print url
print "Saving file in:\n" + output_file_name
try:
urllib.urlretrieve(url, output_file_name)
except URLError as url_error:
print(url_error)
raise
except IOError as io_error:
print(io_error)
raise
print "Download finished."
def _get_number_of_chunks(url_template, study_id, sample_id, run_id, version, domain, file_type):
"""
Returns the number of chunks for the given set of parameters (study, sample and run identifier).
"""
print "Getting the number of chunks from the following URL..."
url_get_number_of_chunks = url_template % (
study_id, sample_id, run_id, version, domain, file_type)
print url_get_number_of_chunks
try:
file_stream_handler = urllib2.urlopen(url_get_number_of_chunks)
result = int(file_stream_handler.read())
print "Retrieved " + str(result) + " chunks."
return result
except URLError as url_error:
print(url_error)
raise
except IOError as io_error:
print(io_error)
raise
except ValueError as e:
print(e)
print "Skipping this run! Could not retrieve the number of chunks for this URL. " \
"Check the version number in the URL and check if the run is available online."
return 0
def _get_file_stream_handler(url_template, study_id):
"""
Returns a file stream handler for the given URL.
"""
print "Getting the list of project runs..."
url_get_project_runs = url_template % (study_id)
try:
req = urllib2.Request(url=url_get_project_runs, headers={'Content-Type': 'text/plain'})
return urllib2.urlopen(req)
except URLError as url_error:
print(url_error)
raise
except IOError as io_error:
print(io_error)
raise
except ValueError as e:
print(e)
print "Could not retrieve any runs. Open the retrieval URL further down in your browser and see if you get any results back. Program will exit now."
print url_get_project_runs
raise
def _print_program_settings(project_id, version, selected_file_types_list, output_path, root_url):
print "Running the program with the following setting..."
print "Project: " + project_id
print "Pipeline version: " + version
print "Selected file types: " + ",".join(selected_file_types_list)
print "Root URL: " + root_url
print "Writing result to: " + output_path
if __name__ == "__main__":
function_file_type_list = ["InterProScan", "GOAnnotations", "GOSlimAnnotations"]
sequences_file_type_list = ["ProcessedReads", "ReadsWithPredictedCDS", "ReadsWithMatches", "ReadsWithoutMatches",
"PredictedCDS", "PredictedCDSWithoutAnnotation", "PredictedCDSWithAnnotation",
"PredictedORFWithoutAnnotation", "ncRNA-tRNA-FASTA"]
taxonomy_file_type_list = ["5S-rRNA-FASTA", "16S-rRNA-FASTA", "23S-rRNA-FASTA", "OTU-TSV", "OTU-BIOM",
"OTU-table-HDF5-BIOM", "OTU-table-JSON-BIOM", "NewickTree", "NewickPrunedTree"]
# Default list of available file types
default_file_type_list = sequences_file_type_list + function_file_type_list + taxonomy_file_type_list
# Parse script parameters
parser = argparse.ArgumentParser(description="MGPortal bulk download tool.")
parser.add_argument("-p", "--project_id",
help="Project accession (e.g. ERP001736, SRP000319) from a project which is publicly available on the EBI Metagenomics website (https://www.ebi.ac.uk/metagenomics/projects).**MANDATORY**",
required=True)
parser.add_argument("-o", "--output_path",
help="Location of the output directory, where the downloadable files get stored.**MANDATORY**",
required=True)
parser.add_argument("-v", "--version", help="Version of the pipeline used to generate the results.**MANDATORY**",
required=True)
parser.add_argument("-t", "--file_type",
help="Supported file types are: AllFunction, AllTaxonomy, AllSequences OR a comma-separated list of supported file types: " + ', '.join(
default_file_type_list) + " OR a single file type.**OPTIONAL**\nDownloads all file types if not provided.",
required=False)
parser.add_argument("-vb", "--verbose", help="Switches on the verbose mode.**OPTIONAL**",
required=False)
args = vars(parser.parse_args())
# Turn on verbose mode if option is set
verbose = False
if 'verbose' in args.keys():
verbose = True
# Parse the project accession
study_id = args['project_id']
# Parse the values for the file type parameter
selected_file_types_list = []
if not args['file_type']:
# If not specified use the default set of file types
selected_file_types_list = default_file_type_list
else:
# Remove whitespaces
selected_file_types_str = args['file_type'].replace(" ", "")
# Set all functional result file types
if selected_file_types_str == "AllFunction":
selected_file_types_list = function_file_type_list
elif selected_file_types_str == "AllTaxonomy":
selected_file_types_list = taxonomy_file_type_list
elif selected_file_types_str == "AllSequences":
selected_file_types_list = sequences_file_type_list
# Set defined file types
elif len(selected_file_types_str.split(",")) > 1:
selected_file_types_list = selected_file_types_str.split(",")
# Set single file type
else:
selected_file_types_list.append(selected_file_types_str)
# Parse the analysis version
version = args['version']
root_url = "https://www.ebi.ac.uk"
study_url_template = root_url + "/metagenomics/projects/%s/runs"
number_of_chunks_url_template = root_url + "/metagenomics/projects/%s/samples/%s/runs/%s/results/versions/%s/%s/%s/chunks"
chunk_url_template = root_url + "/metagenomics/projects/%s/samples/%s/runs/%s/results/versions/%s/%s/%s/chunks/%s"
download_url_template = root_url + "/metagenomics/projects/%s/samples/%s/runs/%s/results/versions/%s/%s/%s"
# Print out the program settings
_print_program_settings(study_id, version, selected_file_types_list, args['output_path'], root_url)
# Iterating over all file types
for file_type in selected_file_types_list:
domain = None
fileExtension = None
# Boolean flag to indicate if a file type is chunked or not
is_chunked = True
# Set the result file domain (sequences, function or taxonomy) dependent on the file type
# Set output file extension (tsv, faa or fasta) dependent on the file type
if file_type == 'InterProScan':
domain = "function"
fileExtension = ".tsv.gz"
elif file_type == 'GOSlimAnnotations' or file_type == 'GOAnnotations':
domain = "function"
fileExtension = ".csv"
is_chunked = False
# PredictedCDS is version 1.0 and 2.0 only, from version 3.0 on this file type was replaced by
# PredictedCDSWithAnnotation (PredictedCDS can be gained by concatenation of the 2 sequence file types now)
elif file_type == 'PredictedCDS' or file_type == 'PredicatedCDSWithoutAnnotation' or file_type == \
'PredictedCDSWithAnnotation':
if file_type == 'PredictedCDSWithAnnotation' and (version == '1.0' or version == '2.0'):
print "File type '" + file_type + "' is not available for version " + version + "!"
continue
elif file_type == 'PredictedCDS' and version == '3.0':
print "File type '" + file_type + "' is not available for version " + version + "!"
continue
domain = "sequences"
fileExtension = ".faa.gz"
elif file_type == 'ncRNA-tRNA-FASTA':
domain = "sequences"
fileExtension = ".fasta"
is_chunked = False
elif file_type == '5S-rRNA-FASTA' or file_type == '16S-rRNA-FASTA' or file_type == '23S-rRNA-FASTA':
is_chunked = False
domain = "taxonomy"
fileExtension = ".fasta"
# NewickPrunedTree is version 2 only
# NewickTree is version 1 only
elif file_type == 'NewickPrunedTree' or file_type == 'NewickTree':
if file_type == 'NewickPrunedTree' and version == '1.0':
print "File type '" + file_type + "' is not available for version " + version + "!"
continue
if file_type == 'NewickTree' and version == '2.0':
print "File type '" + file_type + "' is not available for version " + version + "!"
continue
is_chunked = False
domain = "taxonomy"
fileExtension = ".tree"
elif file_type == 'OTU-TSV':
is_chunked = False
domain = "taxonomy"
fileExtension = ".tsv"
# OTU-BIOM is version 1 only
# OTU-table-HDF5-BIOM and OTU-table-JSON-BIOM are version 2 only
elif file_type == 'OTU-BIOM' or file_type == 'OTU-table-HDF5-BIOM' or file_type == 'OTU-table-JSON-BIOM':
if file_type == 'OTU-BIOM' and version == '2.0':
print "File type '" + file_type + "' is not available for version " + version + "!"
continue
if (file_type == 'OTU-table-HDF5-BIOM' or file_type == 'OTU-table-JSON-BIOM') and version == '1.0':
print "File type '" + file_type + "' is not available for version " + version + "!"
continue
is_chunked = False
domain = "taxonomy"
fileExtension = ".biom"
else:
domain = "sequences"
fileExtension = ".fasta.gz"
# Retrieve a file stream handler from the given URL and iterate over each line (each run) and build the download link using the variables from above
file_stream_handler = _get_file_stream_handler(study_url_template, study_id)
reader = csv.reader(file_stream_handler, delimiter=',')
for study_id, sample_id, run_id in reader:
print study_id + ", " + sample_id + ", " + run_id
output_path = args['output_path'] + "/" + study_id + "/" + file_type
if not os.path.exists(output_path):
os.makedirs(output_path)
if is_chunked:
number_of_chunks = _get_number_of_chunks(number_of_chunks_url_template, study_id, sample_id, run_id,
version, domain, file_type)
for chunk in range(1, number_of_chunks + 1):
output_file_name = output_path + "/" + run_id.replace(" ", "").replace(",",
"-") + "_" + file_type + "_" + str(
chunk) + fileExtension
rootUrl = chunk_url_template % (study_id, sample_id, run_id, version, domain, file_type, chunk)
_download_resource_by_url(rootUrl, output_file_name)
else:
output_file_name = output_path + "/" + run_id.replace(" ", "").replace(",",
"-") + "_" + file_type + fileExtension
rootUrl = download_url_template % (study_id, sample_id, run_id, version, domain, file_type)
_download_resource_by_url(rootUrl, output_file_name)
print "Program finished."
|
def square_digits(num):
num = str(num)
squarednum = ""
for i in range(len(num)):
squarednum += str((int(num[i]) ** 2))
squarednum = int(squarednum)
return squarednum
|
# ROT13 is a simple letter substitution cipher that replaces a letter with the letter 13 letters after it in the alphabet.
# ROT13 is an example of the Caesar cipher.
# Create a function that takes a string and returns the string ciphered with Rot13.
# If there are numbers or special characters included in the string, they should be returned as they are.
# Only letters from the latin/english alphabet should be shifted, like in the original Rot13 "implementation".
# Please note that using encode is considered cheating.
def rot13(message):
encoded = ""
for letter in message:
if letter.isupper():
encoded += chr((((ord(letter)-65)+13)%26)+65)
elif letter.islower():
encoded += chr((((ord(letter)-97)+13)%26)+97)
else:
encoded += letter
return encoded
|
class Point():
def __init__(self, x, y):
self.x = x
self.y = y
def getTuple(self):
return (self.x, self.y)
class Line():
def __init__(self, point1, point2):
self.point1 = point1
self.point2 = point2
if self.point1.x == self.point2.x:
self.m = 100000
else:
self.m = float((float(self.point1.y-self.point2.y))/(float(self.point1.x-self.point2.x)))
def intersect(self, line):
x1 = self.point1.x
x2 = self.point2.x
x3 = line.point1.x
x4 = line.point2.x
y1 = self.point1.y
y2 = self.point2.y
y3 = line.point1.y
y4 = line.point2.y
den = ((x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4))
out_x = int(round(((x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4))/den))
out_y = int(round(((x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4))/den))
out = Point(out_x, out_y)
return out
def getPoints(self):
return ((self.point1.x, self.point1.y), (self.point2.x, self.point2.y))
|
x=1
y=2
print (x+y)
print (x-y)
print (x*y)
print (x/y)
print (x**y)
print ("page 13")
print (x+2*y)
print (x-y/2)
print (2*x**3)
print ((x/2)*y)
print (x, y, sep="...")
print (x,"\n",y)
x=input ("entre el valor para x:")
x=input("")
x=float(x)
print (3*x)
t=input ("ingrese el valor del tiempo t:")
h=input ("ingrese la altura h:")
g=9.8
y=(0.5*g*t**2)+h
print ("el valor obtenido es",y)
|
chars = {chr(a + ord('А')): a for a in range(64)}
chars.update({' ': 64, ',': 65, '.': 66, '?': 67, '!': 68, '-': 69, '(': 70, ')': 71, '\'': 72, '"': 73, '&': 74,
':': 75, ';': 76, '*': 77, '\\': 78, '/': 79, '<': 80, '>': 81, '\n': 82})
chars.update({chr(a - 83 + ord('0')): a for a in range(83, 93)})
inverted_chars = {value: key for key, value in chars.items()}
chars_num = len(chars)
def encode(c, key, i):
return inverted_chars[(chars[c] + chars[key[i % len(key)]]) % chars_num]
def decode(c, key, i):
return inverted_chars[(chars[c] + chars_num - chars[key[i % len(key)]]) % chars_num]
def decode_from_file(filename, key):
f_input = open(filename).read()
f_output_name = filename[:-4] + "_decoded_output.txt"
f_output = open(f_output_name, "w+", encoding="utf-8")
for i, char in enumerate(f_input):
f_output.write(decode(char, key, i))
return f_output_name
def encode_from_file(filename, key):
f_input = open(filename, encoding="utf-8").read()
f_output_name = filename[:-4] + "_encoded_output.txt"
f_output = open(f_output_name, "w+")
for i, char in enumerate(f_input):
f_output.write(encode(char, key, i))
return f_output_name
path = "data/task_7/"
def test_all():
key = "сложныйключ"
file_1 = path + "test_input_1.txt"
file_2 = path + "test_input_2.txt"
result1 = encode_from_file(file_1, key)
decode_from_file(result1, key)
result2 = encode_from_file(file_2, key)
decode_from_file(result2, key)
test_all()
|
# File: Grid.py
# Description: This program takes in an input file of an any dimension square grid,
# and finds the largest product of 4 adjacent numbers in any direction.
# Student Name: Brionna Huynh
# Student UT EID: bph637
# Partner Name: Patricia Garcia
# Partner UT EID: pgg378
# Course Name: CS 303E
# Unique Number: 51345
# Date Created: November 2, 2015
# Date Last Modified: November 3, 2015
def main():
#Open relevant files
in_file = open('Grid.txt', 'r')
#Read dimensions
dim = in_file.readline()
dim = dim.strip()
dim = int(dim)
#Create an empty grid
grid = []
#Populate the grid
for i in range(dim):
line = in_file.readline()
line = line.strip()
row = line.split()
for j in range(dim):
row[j] = int(row[j])
grid.append(row)
#Create a product list
prod_list = []
#Read and multiply blocks of four along rows
for row in grid:
for i in range(dim - 3):
prod = 1
for j in range(i, i + 4):
prod = prod * row[j]
prod_list.append(prod)
#Read and multiply blocks of four along columns
for j in range(dim):
for i in range(dim - 3):
prod = 1
for k in range(i, i + 4):
prod = prod * grid[k][j]
prod_list.append(prod)
#Read and multiply blocks of four along L-R diagonals
for i in range(dim - 3):
for j in range(dim - 3):
prod = 1
for k in range(4):
prod = prod * grid[i + k][j + k]
prod_list.append(prod)
#Read and multiply blocks of four along R-L diagonals
for i in range(dim - 3):
for j in range(dim - 3):
prod = 1
for k in range(4):
prod = prod * grid[i - k][j + k]
prod_list.append(prod)
#Display output with max product
print('The greatest product is ' + str(max(prod_list)) + '.')
#Close file
in_file.close()
main()
|
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 14 17:32:39 2021
@author: User
"""
def multiple(*numbers):
"""Istalgancha sonlarni qabul qilib, ularning ko'paytmasini
qaytaruvchi funksiya"""
multiples = 1
for number in numbers:
multiples *= number
return multiples
print(multiple(1,2,3,9, 10))
print(multiple())
def student_info(ism, familiya, **info):
"""Talabalar haqidagi ma'lumotlarini lug'at ko'rinishida qaytaruvchi
funkisya yozing. Talabaning ismi va familiyasi majburiy argument,
qolgan ma'lumotlar esa ixtiyoriy ko'rinishda istalgancha berilishi
mumkin bo'lsin."""
info['ism'] = ism
info['familiya'] = familiya
return info
talaba1 = student_info('Hilola', 'xushmanova', t_yil=2000, baho=5, t_joy='kasan')
talaba2 = student_info('Guli', 'sohibova', t_yil = 1997, fan = 'math')
talabalar = [talaba1, talaba2]
for talaba in talabalar:
print(talaba)
|
'''
Created on Apr 4, 2021
@author: Q
'''
class FirstUnique(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.l_nums = list()
self.d_nums = dict()
self.start_idx = 0
for num in nums:
self.add(num)
def showFirstUnique(self):
"""
:rtype: int
"""
if len(self.l_nums):
for i in range(self.start_idx, len(self.l_nums)):
if self.d_nums[self.l_nums[i]]:
self.start_idx = i
return self.l_nums[i]
return -1
else:
return -1
def add(self, value):
"""
:type value: int
:rtype: None
"""
if not value in self.d_nums:
self.l_nums.append(value)
self.d_nums[value] = True
else:
self.d_nums[value] = False
# Your FirstUnique object will be instantiated and called as such:
# obj = FirstUnique(nums)
# param_1 = obj.showFirstUnique()
# obj.add(value) |
'''
Created on Nov 1, 2020
@author: Q
starting from 2 I know the steps you choose to the last ending tested floor is:
m, m-1, m-2 .... 1
this makes the total tests in worst scenario same in each range by decreasing the steps for next egg test by 1 with current egg increase test by 1
then within each step range, just move down each turn,
1,1,1,1,1
now from 2 to 3, the next step to end
S be the maximum steps to reach with E eggs and N throws
It includes the maximum steps to reach with E-1 eggs in N-1 throws (if the egg after this throw breaks so we are left with one less eggs and one less throws)
S[e-1, n-1] -- # floors downstairs as egg breaks
plus the maximum steps to reach with E eggs in N-1 throws (if the egg after this throw dosn't break and we are left with one less throws)
S[e, n-1] -- # floors to achieve upstairs as egg contact
plus 1 (for current floor)
1 -- current floor
S[e, n] = S[e-1, n-1] + 1 + S[e, n-1]
'''
class Solution(object):
def superEggDrop(self, K, N):
"""
:type K: int
:type N: int
:rtype: int
"""
if (K==1): return N
if (N==1): return 1
S = [[0 for _ in range(N)] for _ in range(K+1)]
for i in range(K+1):
S[i][0] = 1
for j in range(N):
S[0][j] = 0
for i in range(1, K+1, 1):
for j in range(1, N, 1):
S[i][j] = S[i-1][j-1] + 1 + S[i][j-1]
if S[K][j] >= N:
print (S)
return j+1
sol = Solution()
K=2
N=7
print(sol.superEggDrop(K, N)) |
'''
Created on Jan 3, 2021
@author: Q
1 loop for 3rd element and
2 points in a loop for 2 sum
'''
import sys
class Solution(object):
def threeSumClosest(self, nums0, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums = sorted(nums0)
low_diff = sys.maxsize
res = 0
for i in range(len(nums)-2):
lp, rp = i+1, len(nums)-1
while (lp<rp):
cur = nums[i] + nums[lp] + nums[rp]
if abs(target-cur)<low_diff:
res = cur
low_diff = abs(target-cur)
if cur>target:
rp -= 1
elif cur<target:
lp += 1
else:
return res
return res
msol = Solution()
nums = [0,2,1,-3]
target = 1
ares = msol.threeSumClosest(nums, target)
print(ares)
|
'''
Created on Dec 26, 2020
@author: Q
'''
import random
class Solution(object):
def __init__(self, w):
"""
:type w: List[int]
"""
self.nums = [0] * len(w)
self.nums[0] = w[0]
for i in range(1, len(w)):
self.nums[i] = self.nums[i-1] + w[i]
print(self.nums)
def pickIndex1(self):
"""
:rtype: int
"""
x = random.randrange(0, self.nums[-1])
#print('x='+str(x))
# use use binary search
# right the lower bound index
l, r = 0, len(self.nums)-1
mid = int((l+r) / 2)
while l<r:
mid = int((l+r) / 2)
#print('mid='+str(mid))
if self.nums[mid]>x:
r = mid-1
elif self.nums[mid]<x:
l = mid+1
else:
return mid+1
if x>=self.nums[l]:
return l+1
else:
return l
def pickIndex(self):
"""
:rtype: int
"""
# both generating x work
x = self.nums[-1] * random.random()
#x = random.randint(1, self.nums[-1])
# use use binary search
# right the lower bound index
l, r = 0, len(self.nums)
while l<r:
mid = (l+r) // 2
#print('mid='+str(mid))
if self.nums[mid]<x:
l = mid+1
elif self.nums[mid]==x:
return mid+1
else:
r = mid
return l
# Your Solution object will be instantiated and called as such:
w = [3,14,1,7]
obj = Solution(w)
print(obj.pickIndex())
print(obj.pickIndex())
print(obj.pickIndex())
print(obj.pickIndex()) |
'''
Created on Dec 20, 2020
@author: Q
double stack
one for one by one add
one for calculate the equation within the paired parenthesis
'''
class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
st = list()
number = ''
for x in s:
if x.isdigit():
number = number + x
else:
if number != '':
st.append(int(number))
number = ''
if x in '+-':
st.append(x)
elif x in '(':
st.append(x)
elif x in ')':
equation = list()
while (st[-1] != '('):
equation.append(st.pop())
st.pop()
# solve equation
if len(equation)>0:
x = equation.pop()
while len(equation)>0:
operator = equation.pop()
y = equation.pop()
if operator=='+':
x = x+y
elif operator=='-':
x = x-y
else:
print ('error 2')
st.append(x)
else:
pass
if number != '':
st.append(int(number))
res = 0
#print(st)
if len(st)>0:
res = st.pop(0)
while len(st)>0:
operator = st.pop(0)
y = st.pop(0)
if operator == '+':
res = res+y
elif operator == '-':
res = res-y
else:
print ('error 3')
return res
msol = Solution()
s = "(1+(4+5+2)-3)+(6+8)"
ares = msol.calculate(s)
print(ares)
|
'''
Created on Sep 13, 2020
@author: Q
similar to 005
and mask the cell a[i,j] to 1 if [i,j] forms a palindromic string
'''
class Solution(object):
def countSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
# add #
if len(s)==0: return 0
s = "#".join(s[i:i+1] for i in range(len(s)))
dim = len(s)
a = [[0]*dim for i in range(dim)]
total = 0
# initialization and count
for i in range(dim):
a[i][i] = 1
if s[i] != '#':
total += 1
# DP and count
for i in range(dim-1,0,-1):
for j in range(i,dim,1):
#print (i,j, s[i-1], s[j+1])
if (i-1)>=0 and (j+1)<dim and s[i-1]==s[j+1] and a[i][j]==1:
a[i-1][j+1]=1
if s[i-1]!='#':
total += 1
#print(a)
return total
a = "a"
msol = Solution()
print(msol.countSubstrings(a))
|
'''
Created on Jan 9, 2021
@author: Q
backtracking
to speed up, it introduce a globe check to see if the node's dependency edges have all be visited,
if it has all been visited and there is no cycle (otherwise the func would have returned), there is no need to check this node in the following backtracking
'''
class Solution(object):
def canFinish(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: bool
"""
visited = [0] * numCourses
checked = [0] * numCourses
courses = dict()
for c1, c2 in prerequisites:
if c2 in courses:
courses[c2].append(c1)
else:
courses[c2] = [c1]
if not c1 in courses:
courses[c1] = []
def dfs_circle(cur_course):
if visited[cur_course] == 1:
return True
if checked[cur_course] == 1:
return False
visited[cur_course] = 1
for next_course in courses[cur_course]:
if dfs_circle(next_course):
return True
visited[cur_course] = 0
checked[cur_course] = 1
for c in courses:
if dfs_circle(c):
return False
return True
msol = Solution()
numCourses = 2
prerequisites = [[1,0], [0,1]]
ares = msol.canFinish(numCourses,prerequisites)
print(ares)
|
'''
Created on Sep 7, 2020
@author: Q
in the main loop, the current array always includes pivot point: ascending pivot ascending
so whether mid is (l+r)//2 or sometimes to be (l+r)//2+1 is not important, because the structure keeps.
yet at the very end when there are 2 elements e.g. [5,1], we need to terminate
because if we no longer can maintain the structure in the loop anymore if we do one more step
either we will exclude pivot or keep infinite loop due to not be able to move head/tail forward/backward
For those types of questions, check out the cases towards the end and decide different if/else and loop end condition
'''
class Solution(object):
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
cnt = len(nums)
if cnt==0: return None
if nums[0]<nums[cnt-1]: return nums[0]
l, r = 0, cnt-1
while (l<r):
if l+1==r:
break
mid = (l+r)//2
#print(l,r,mid)
if nums[l] > nums[mid]:
r = mid
elif nums[l] < nums[mid]:
l = mid
return nums[r]
a = [3,4,5,1,2]
msol = Solution()
print(msol.findMin(a)) |
CODE = 'EBG KVVV vf n fvzcyr yrggre fhofgvghgvba pvcure gung ercynprf n yrggre jvgu gur yrggre KVVV yrggref nsgre vg va gur nycunorg. EBG KVVV vf na rknzcyr bs gur Pnrfne pvcure, qrirybcrq va napvrag Ebzr. Synt vf SYNTFjmtkOWFNZdjkkNH. Vafreg na haqrefpber vzzrqvngryl nsgre SYNT.'
ALPHABET_NUM = 26
def rotate(rot, c):
A = ord('A')
Z = A + ALPHABET_NUM - 1
a = ord('a')
z = a + ALPHABET_NUM - 1
o = ord(c)
if A <= o <= Z:
o = (o - A + rot) % ALPHABET_NUM + A
elif a <= o <= z:
o = (o - a + rot) % ALPHABET_NUM + a
return chr(o)
def main():
for rot in range(1, ALPHABET_NUM):
print("rot: ", rot)
for c in [rotate(rot, c) for c in CODE]:
print(c, end="")
print("\n")
if __name__ == '__main__':
main()
|
class SpellChecker:
def __init__(self):
self.words = []
def load_words(self,file_name):
self.words = open(file_name).readlines()
self.words = map(lambda x: x.strip(), self.words)
return self.words
def check_word(self,word):
return word.strip('.').lower() in self.words
def check_words(self, sentence):
words_to_check = sentence.split(' ')
for word in words_to_check:
if not self.check_word(word):
print('Word is misspelt : ' + word)
return False
return True
if __name__ =='main':
spell_check = SpellChecker()
spell_check.load_words("spell.words")
print spell_check.check_word('zygotic')
print spell_check.check_word('mistasdas')
print spell_check.check_words('zygotic mistasdas elementary') |
# -*- coding: utf-8 -*-
# @Time : 18-10-16 上午10:47
# @Author : Mingan Luan
# @File : Pomodoro_Timer.py
"""
A Pomodoro Technique.
How it works:
1. Set a pomodoro timer (default is 25 min).
2. When the timer ends, a short break timer (default is 5 min) kicks in.
3. Go to step 1.
4. After four pomodoro cycles (step 1 to 3), take a longer break (default
is 30 min).
"""
import datetime
import time
def convert_string_to_time(times):
# times = datetime.datetime.strptime(time, '%M:%S')
# times.time()
times = int(times)
times = datetime.timedelta(seconds=times)
return times
def main():
pomodoro_timer = input("Please input your pomodoro timer(for example: 25(min)):")
break_timer = input("Please input your pomodoro timer(for example: 5(min)):")
big_break_timer = input("Please input your pomodoro timer(for example: 30(min)):")
the_number_of_pt = int(input("Please input your the number of pomodoro timer(for example: 4):"))
the_number_of_pt_round = int(input("How many numbers do you want to learning(for example: 4):"))
#convert_string_to_time()
#pomodoro_timer = convert_string_to_time(pomodoro_timer)
#break_timer = convert_string_to_time(break_timer)
#big_break_timer = convert_string_to_time(big_break_timer)
seconds = datetime.timedelta(seconds=1)
judge = datetime.timedelta(0)
Number = 0
number = 0
print(datetime.datetime.now())
while Number != the_number_of_pt_round:
while number != the_number_of_pt:
pomodoro_timers = convert_string_to_time(pomodoro_timer)
while pomodoro_timers != judge:
pomodoro_timers -= seconds
print(pomodoro_timers)
time.sleep(1)
print("It's time to rest")
break_timers = convert_string_to_time(break_timer)
while break_timers != judge:
print(break_timers)
break_timers -= seconds
time.sleep(1)
print("!!!!!It's time to work")
number += 1
print("You should have a big rest!")
big_break_timers = convert_string_to_time(big_break_timer)
while big_break_timers != judge:
big_break_timers -= seconds
time.sleep(1)
print("!!!!!It's time to work")
Number += 1
print(datetime.datetime.now())
#if __name__ == '__main__':
main() |
"""
Description
Given an array of integers,
find how many unique pairs in the array such that their sum is equal to a specific target number.
Please return the number of pairs.
Example
Given nums = [1,1,2,45,46,46], target = 47
return 2
1 + 46 = 47
2 + 45 = 47
"""
class Solution:
"""
* @param nums an array of integer
* @param target an integer
* @return an integer
"""
def two_sum_unique_pairs(self, nums, target):
unique_pairs = 0
if nums is None or len(nums) == 0:
return unique_pairs
nums.sort()
index1 = 0
index2 = len(nums)-1
while index1 < index2:
cur_sum = nums[index1] + nums[index2]
if cur_sum == target:
print nums[index1], nums[index2]
unique_pairs = unique_pairs + 1
index1 = index1 + 1
index2 = index2 - 1
# Skip same pairs
while index1 < index2 and nums[index1] == nums[index1-1]:
index1 = index1 + 1
while index1 < index2 and nums[index2] == nums[index2+1]:
index2 = index2 - 1
elif cur_sum < target:
index1 = index1 + 1
else:
index2 = index2 - 1
return unique_pairs
if __name__ == '__main__':
sol = Solution()
print 'target: 47'
print sol.two_sum_unique_pairs([1,1,2,45,46,46], 47)
print 'target: 12'
print sol.two_sum_unique_pairs([2,3,3,5,7,9,9,10], 12)
print 'target: 2'
print sol.two_sum_unique_pairs([1,1,1,1,1], 2)
print 'target: 4'
print sol.two_sum_unique_pairs([1,2,2,3], 4)
print 'target: 4'
print sol.two_sum_unique_pairs([3,2,1,2], 4)
|
"""
Description
Implement double sqrt(double x) and x >= 0.
Compute and return the square root of x.
Notice
You do not care about the accuracy of the result, we will help you to output results.
Example
Given n = 2 return 1.41421356
"""
from __future__ import division
def sqrt(x):
if x == 0.:
return 0.
elif x == 1.:
return 1.
threshold = 1e-12
# check if x > 1 (ex. 2) or < 1 (ex. 0.25)
start = 1.
end = x
if x < 1:
start = x
end = 1
while end - start > threshold:
mid = start + (end - start) / 2.
mid_2 = mid * mid
if mid_2 == x:
return mid_2
elif mid_2 < x:
start = mid
else:
end = mid
return (start + end) / 2
print sqrt(4.)
print sqrt(2.)
print sqrt(0.25)
print sqrt(0.5)
|
"""
Description
Your are given a binary tree in which each node contains a value.
Design an algorithm to get all paths which sum to a given value.
he path does not need to start or end at the root or a leaf,
but it must go in a straight line down.
Example
Given a binary tree:
1
/ \
2 3
/ /
4 2
for target = 6, return
[
[2, 4],
[1, 3, 2]
]
"""
from binary_tree import TreeNode, inorder_print
# create tree 1
root1 = TreeNode(1)
root1.left = TreeNode(2)
root1.left.left = TreeNode(4)
root1.right = TreeNode(3)
root1.right.left = TreeNode(2)
def find_sum_paths(root, target):
paths = []
def traverse(root, target, paths, prev_seqs):
if root is None:
return
curr_seqs = [s + [root.val] for s in prev_seqs + [[]]]
for s in curr_seqs:
if sum(s) == target:
paths.append(s[:])
if root.left is not None:
traverse(root.left, target, paths, curr_seqs)
if root.right is not None:
traverse(root.right, target, paths, curr_seqs)
traverse(root, target, paths, [])
return paths
print 6, find_sum_paths(root1, 6)
print 3, find_sum_paths(root1, 3)
print 4, find_sum_paths(root1, 4)
|
class SymbolNode:
def __init__(self, start_symbol=None, symbolic_str=''):
self.start_symbol = start_symbol
self.raw_str = raw_str
self.children = []
class SymbolTree:
def __init__(self, startSymbol):
self.root = SymbolNode(startSymbol)
def parse_node(self, raw_str):
start_symbol = None
for i, c in enumerate(raw_str):
if c.isupper():
start_symbol = c
else:
symbolic_str += c
return SymbolNode(start_symbol, symbolic_str)
def search(self, root, start_symbol):
if root.start == start_symbol:
return root
for child in root.children:
node = self.search(child, start_symbol)
if node:
return node
return None
def add_node(self, start_symbol, raw_str):
child = self.parse_node(raw_str)
parent = self.search(self.root, start_symbol)
if not parent:
return
parent.children.append(child)
class Solution:
"""
@param generator: Generating set of rules.
@param startSymbol: Start symbol.
@param symbolString: Symbol string.
@return: Return true if the symbol string can be generated, otherwise return false.
"""
def canBeGenerated(self, generator, startSymbol, symbolString):
# Write your code here.
if not generator or not startSymbol or not symbolString:
return False
tree = SymbolTree(startSymbol)
for rule in generator:
start_sumbol, raw_str = rule.split(' -> ')
tree.add_node(start_sumbol, raw_str)
return self.find_symbol(tree.root, '', symbolString)
def find_symbol(self, root, prevString, symbolString):
curString = prevString + root.symbol_str
print root.start, curString
if not root.start and curString == symbolString:
return True
for child in root.children:
if self.find_symbol(child, curString, symbolString):
return True
return False
if __name__ == '__main__':
sol = Solution()
generator = ["S -> abc", "S -> aA", "A -> b", "A -> c"]
startSymbol = 'S'
symbolString = 'ac'
#print sol.canBeGenerated(generator, startSymbol, symbolString)
generator = ["S -> abcd", "S -> A", "A -> abc"]
symbolString = 'abc'
#print sol.canBeGenerated(generator, startSymbol, symbolString)
generator = ["S -> abc", "S -> aA", "A -> b", "A -> c"]
symbolString = 'a'
#print sol.canBeGenerated(generator, startSymbol, symbolString)
generator = ["S -> abcd", "S -> A", "A -> abc"]
symbolString = 'ab'
print sol.canBeGenerated(generator, startSymbol, symbolString)
|
"""
Description
Given an array nums of n integers,
find two integers in nums such that the sum is
closest to a given number, target.
Return the difference between the sum of the two integers and the target.
Example
Given array nums = [-1, 2, 1, -4], and target = 4.
The minimum difference is 1. (4 - (2 + 1) = 1).
Challenge
Do it in O(nlogn) time complexity.
"""
class Solution:
"""
* @param nums an array of integer
* @param target an integer
* @return the difference between the sum and the target
"""
def two_sum(self, nums, target):
if nums is None or len(nums) < 2:
return None
min_diff = float('inf')
nums.sort()
i1 = 0
i2 = len(nums)-1
while i1 < i2:
cur_sum = nums[i1] + nums[i2]
min_diff = min(min_diff, abs(cur_sum-target))
if cur_sum == target:
break
elif cur_sum < target:
i1 = i1 + 1
else:
i2 = i2 - 1
return min_diff
if __name__ == '__main__':
sol = Solution()
print sol.two_sum([-1, 2, 1, -4], 4), 1
print sol.two_sum([-1, 2, 1, -4], 0), 0
print sol.two_sum([1, -1, 2, 2], -1), 1
|
'''
https://monkeysayhi.github.io/2017/08/04/%E3%80%90%E5%88%B7%E9%A2%98%E3%80%91Search-in-a-Big-Sorted-Array/
Given a big sorted array with positive integers sorted by ascending order.
The array is so big so that you can not get the length of the whole array directly,
and you can only access the kth number by ArrayReader.get(k)
(or ArrayReader->get(k) for C++).
Find the first index of a target number.
Your algorithm should be in O(log k),
where k is the first index of the target number.
'''
import numpy
def search_big_array(nums, target):
# write your code
EOF = 2147483647
if nums is None:
return -1
def query(nums, index):
try:
return nums[index]
except:
return EOF
def get_range(nums, target):
end = 1
while query(nums, end) < target:
end = end << 1
start = end >> 1
while end > start and query(nums, end) == EOF:
end = end - 1
if end < start or query(nums, end) == EOF:
return None, None
return start, end
start, end = get_range(nums, target)
if start is None or end is None:
return -1
def helper(nums, start, end, target):
if start + 1 < end:
mid = start + (end - start) / 2
if query(nums, mid) == target:
return helper(nums, start, mid, target)
if query(nums, mid) < target:
return helper(nums, mid+1, end, target)
if query(nums, mid) > target:
return helper(nums, start, mid-1, target)
if query(nums, start) == target:
return start
elif query(nums, end) == target:
return end
return -1
return helper(nums, start, end, target)
big_arr = [1, 2, 3, 4, 6, 7] + ([10] * 100)
ans = search_big_array(big_arr, 6)
print ans, ans==4
big_arr = [1, 2, 3, 4] + [7]*100 + [10]*100
ans = search_big_array(big_arr, 7)
print ans, ans==4
big_arr = ([2]*1000) + ([10]*100) + ([20]*400)
ans = search_big_array(big_arr, 20)
print ans, ans==1100
|
"""
Description
Partition an unsorted integer array into three parts:
The front part < low
The middle part >= low & <= high
The tail part > high
Return any of the possible solutions.
Notice
low <= high in all testcases.
Example
Given [4,3,4,1,2,3,1,2], and low = 2 and high = 3.
Change to [1,1,2,3,2,3,4,4].
xw
([1,1,2,2,3,3,4,4] is also a correct answer, but [1,2,1,2,3,3,4,4] is not)
Challenge
Do it in place.
Do it in one pass (one loop).
"""
class Solution:
"""
* @param nums an integer array
* @param low an integer
* @param high an integer
* @return nothing
"""
def partition(self, nums, low, high):
if nums == None or len(nums) == 0:
return
start = 0
end = len(nums) - 1
i = 0
while i < end:
if nums[i] < low:
nums[start], nums[i] = nums[i], nums[start]
start = start + 1
i = i + 1
elif nums[i] > high:
nums[end], nums[i] = nums[i], nums[end]
end = end - 1
else:
i = i + 1 # skip when low <= i <= high
if __name__ == '__main__':
sol = Solution()
nums = [4,3,4,1,2,3,1,2]
sol.partition(nums, 2, 3)
print nums
nums = [5, 5, 3, 2, 1, 0, 0, 2, 4, 4, 3, 3]
sol.partition(nums, 2, 4)
print nums
|
"""
Description
Given an array of integers,
find how many pairs in the array such that their sum is bigger than a specific target number.
Please return the number of pairs.
Example
Given numbers = [2, 7, 11, 15], target = 24.
Return 1. (11 + 15 is the only pair)
Challenge
Do it in O(1) extra space and O(nlogn) time.
"""
class Solution:
"""
* @param nums an array of integer
* @param target an integer
* @return an integer
"""
def two_sum(self, nums, target):
count = 0
if nums is None or len(nums) == 0:
return count
nums.sort()
i1 = 0
i2 = len(nums)-1
while i1 < i2:
cur_sum = nums[i1] + nums[i2]
if cur_sum > target:
count = count + (i2 - i1)
i2 = i2 - 1
else:
i1 = i1 + 1
return count
if __name__ == '__main__':
sol = Solution()
print sol.two_sum([2, 7, 11, 15], 24), 1
print sol.two_sum([1, 2, 3], 3), 2
print sol.two_sum([3, 2, 1], 3), 2
print sol.two_sum([1, 1, 2, 2], 2), 5 |
def adicao(operando_1, operando_2):
return operando_1 + operando_2
def subtracao(operando_1, operando_2):
return operando_1 - operando_2
def multiplicacao(operando_1, operando_2):
return operando_1 * operando_2
def divisao(dividendo, divisor):
return dividendo / divisor
def faz_nada():
pass
def contador_caracteres(lista_palavras):
if len(lista_palavras) == 1:
return len(lista_palavras[0])
else:
quantidade_caracteres = []
for palavra in lista_palavras:
quantidade_caracteres.append(len(palavra))
return quantidade_caracteres
|
class A:
def __init__(self, name, salary):
self.name = name
self.__salary = salary
def _assign_values_method(self):
# self.name=name
return self.name
class B(A):
def __init__(self, id, name, age, salary):
super().__init__(name, salary)
self._id = id
self.age = age
class C(B):
def __init__(self, id, name, age, salary, level):
super().__init__(id, name, age, salary)
self.level = level
try:
def display(self):
print(self._id, self.age, self.name, self.__salary, self.level)
except AttributeError as e:
print(e)
print('Caught Exception' )
obj = C(1, 'vamsi', 22, 2000, 'ASE')
obj.display()
# print(obj._assign_values_method())
# class Employee:
# # constructor
# def __init__(self, name, sal):
# self._name = name # protected attribute
# self.__sal = sal
#
#
# class HR(Employee):
#
# # member function task
# def task(self):
# print("We manage Employees")
#
#
# hr_emp = HR('vamsi', 2200)
# print(hr_emp._sal)
|
# even numbers
inputList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 342, 4, 24, 2]
outputList = [var for var in inputList if var % 2 == 0]
print outputList
# squares of 1-10 numbers
squareNumberList = [var ** 2 for var in range(1, 10)]
print squareNumberList |
"""1.Write a program that examines three variables—x, y, and z— and prints
the largest odd number among them. If none of them are odd, it should print a message to that effect."""
a, b, c = 2, 4, 6
odd_list = []
if a % 2 != 0:
odd_list.append(a)
elif b % 2 != 0:
odd_list.append(b)
elif c % 2 != 0:
odd_list.append(c)
if len(odd_list)!=0:
maxi = odd_list[0]
for i in odd_list:
if i > maxi:
maxi = i
print('Max ODD value:', maxi)
else:
print('None of the are odd values')
|
# number = 34
# binary = ''
# while number != 0:
# binary = str(int(number % 2))+binary
# number = int(number) / 2
# print(binary)
# convert to single list
a = [1, [2, 3], [4, 5, [6, 7, [8, [9]]]]]
def convert_to_list(list_elem):
if type(list_elem) is not type([]):
return_list.append(list_elem)
else:
for elem in list_elem:
if type(list_elem) is not type([]):
return_list.append(elem)
else:
convert_to_list(elem)
return_list = []
for i in a:
convert_to_list(i)
print(return_list)
|
li = [1, 2, 3, 12, 11]
a = iter(li)
while True:
try:
print(a.__next__())
except StopIteration:
break
|
def isPrime(num):
count = 2
k = 0
for i in range(count, num + 1):
if num % count == 0:
k += 1
factors(num)
break
else:
continue
if k == 0:
print 'number is prime'
def factors(n):
for i in range(1, n):
if n % i == 0:
print i
print n
isPrime(20)
|
# def sayHello(a):
# print('Hello')
# return a
#
#
# print(sayHello(1))
"""sum fo integers """
# def sumOfIntegers(a,b):
# return a+b
# a=0
# b=3
# c=sumOfIntegers(a,b)
# if c>0:
# print(c)
# else:
# print('negative value')
# def sum(a, b=0):
# c = a + b
# return a, b, c
#
#
# temp1, temp2, temp3 = sum(1)
# print(temp1, temp2, temp3)
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist) |
"""3.Write a program that asks the user to input 10 integers, and then prints the largest odd number that was entered.
If no odd number was entered, it should print a message to that effect."""
li1 = input('Enter 10 numbers with space').split()
odd_list = []
if len(li1)==0:
print('Enter some values')
else:
for i in li1:
if int(i) % 2 != 0:
odd_list.append(int(i))
maxi = odd_list[0]
if len(odd_list) != 0:
for i in odd_list:
if i > maxi:
maxi = i
print('Max ODD value:', maxi)
else:
print('None of the are odd values')
|
"""1.The greatest common divisor (GCD) of a and b is the largest number that divides both of them with no remainder.
One way to find the GCD of two numbers is based on the observation that if r is the remainder when a is divided by b,
then gcd(a, b) = gcd(b, r). As a base case, we can use gcd(a, 0) = a.
Write a function called gcd that takes parameters a and b and returns their greatest common divisor."""
def greatestCommon(a, b):
if a == 0:
return b
elif b == 0:
return a
else:
return greatestCommon(b, a % b)
num1 = int(input('Enter 1st value'))
num2 = int(input('Enter 2nd value'))
print(greatestCommon(num1, num2))
|
"""7.A palindrome is a word that is spelled the same backward and forward, l
ike "Malayalam" and "Noon" . Recursively, a word is a palindrome if the first and last letters are
the same and the middle is a palindrome. Write a function called is_palindrome that takes a string
argument and returns True if it is a palindrome and False otherwise. Remember that you can use the
built-in function len to check the length of a string.
Use the function definition"""
def is_palindrome(m_str):
reverse_string = ''
# reverse_string = "".join(reversed(m_str))
for i in m_str:
reverse_string = i +reverse_string
return reverse_string == m_str
string = (input('Enter a String to check Palindrome')).lower()
if is_palindrome(string):
print("Palindrome")
else:
print("Not a palindrome")
|
import csv
import pandas as pd
import numpy as np
import parameters as P
def csv_dict_list(variables_file):
mydict = {}
reader = csv.reader(open(variables_file, "rb"))
for i, rows in enumerate(reader):
if i == 0: continue
k = rows[0]
v = rows[1]
try:
value = float(v)
except ValueError:
value = str(v)
mydict[k] = value
return mydict
def FuelConvertMJ(num, fuel_name, unit):
# Computes the equivalent MJ (HHV) for kg or liters of a
# fuel-type material
#
# Args:
# num: Physical quantity of material in whatever input unit is chosen
# (numeric)
# fuel_name: String name of the fuel material in all lower-case letters.
# unit: String abbreviated name of unit in which the input is measured in
# (num) and must be either volume or mass. Must enter units that the
# udunits2 package can handle. See documentation here:
# http://cran.r-project.org/web/packages/udunits2/udunits2.pdf
#
# Returns:
# The equivalent MJ (HHV) of num quantity of the fuel material denoted by
# fuel_name
#
# Read in two files:
# 1) list of fuels with corresponding MJ HHV by liter and kg;
# 2) file with all possible aliases for each fuel that can be entered by user
energy_content = pd.read_csv(P.energy_content_path) # Import conversion table
aliases = csv_dict_list(P.fuel_aliases_path) # Import table of aliases for fuels and units
#
# Check to make sure units entered are valid and detect whether it's a unit of
# mass or volume
# Check if units are valid and, if so, convert num to kg or liter.
if unit != "kg" and unit != "liter":
print("Invalid unit entered. Please use only kg or liters")
return
#
# Pull official fuel name from list of aliases and lookup energy content to
# calculate final HHV in MJ
# Takes any number of potential fuel aliases from user input and returns
# official fuel name for calculations
unit = unit+"_hhv"
if fuel_name in aliases.keys():
fuel = aliases[fuel_name]
elif fuel_name in aliases.values():
fuel = fuel_name
else:
print ("fuel not found")
return
content_MJ = energy_content[energy_content['Fuel'] == fuel][unit].iloc[0]
if content_MJ == "N/A":
print ("Invalid unit entered. You may not enter a unit of volume for solid fuels")
else:
# liter column of data frame requires that the output be converted to a
# character, then to numeric. Converting directly to numeric doesn't work
# because the column is a combination of numbers and strings.
energy_MJ = num * content_MJ
return energy_MJ
def FuelCO2kg(MJ_fuel_in, fuel_type):
# Provides the fossil CO2 emissions (kg) for combustion of a given MJ equivalent
# of fuel combusted
#
# Args:
# MJ_fuel_in: total MJ of fuel (HHV) to be combusted
# fuel_type: string indicating the fuel type (ethanol, gasoline, diesel)
adj = (12+16*2)/12 # Calculates CO2 based on carbon fraction
#Assume alcohols are completely biomass-derived
# Numeric coefficients carbon emissions per MJ of fuel
fuels = {
'ethanol': 0*adj,
'n_butanol': 0*adj,
'iso_butanol': 0*adj,
'methanol': 0*adj,
'gasoline': 0.01844452*adj,
'diesel': 0.01895634*adj,
'lignite': 0.03901754*adj,
'anthracite': 0.0456817*adj,
'coal': 0.02447264*adj,
'bituminous': 0.03493306*adj,
'subbituminous': 0.02149727*adj,
'wood': 0*adj,
'herbaceousbiomass': 0*adj,
'cornstover': 0*adj,
'forestresidue': 0*adj,
'bagasse': 0*adj,
'hydrogen': 0*adj,
'rfo': 0.01885208*adj,
'naturalgas': 0.01370544*adj,
'naphtha': 0.01758201*adj,
'refgas': 0.01725027*adj,
'crude': 0.01925017*adj,
'biochar': 0*adj,
'lignin': 0*adj,
'ethylene': 0.01683809*adj,
'propene': 0.01755613*adj,
'butane': 0.01827829*adj,
'petrobutanol': 0.01961145*adj,
'petrohexanol': 0.01812604*adj}
if fuel_type in fuels.keys():
fuel_CO2 = MJ_fuel_in * fuels[fuel_type]
else:
print ("fuel not found")
return
return fuel_CO2
def CooledWaterCO2kg(cooled_type):
# Provides the fossil CO2 emissions (kg) for cooling water or heating steam
# of a given volume equivalent
#
# Args:
# cooled_type: string indicating the water type (cooling_water, chilled_water,
# steam_low, steam_high)
# Numeric coefficients carbon emissions per L of water
waters = {
'cooling_water': 0,
'chilled_water': 0,
'steam_low': 0,
'steam_high': 0}
if cooled_type in waters.keys():
water_CO2 = waters[cooled_type]
else:
print ("water not found")
return
return water_CO2
def GHGImpactVectorSum(time_horizon):
# Computes an impact vector equal to the total kg co2 equivalents per physical
# output unit for each sector
#
# Args:
# co2.filepath: csv file path for co2 impact vector (kg/physical output unit)
# ch4.filepath: csv file path for ch4 impact vector (kg/physical output unit)
# n2o.filepath: csv file path for n2o impact vector (kg/physical output unit)
# time.horizon: number of years used for time horizon of IPCC factors -
# default is 100 years, can also to 20
# Returns:
# The total kg co2e for each sector in a vector form
filepaths = [P.co2_filepath, P.ch4_filepath, P.n2o_filepath]
# IPCC 100-year multipliers for different GHGs to normalize to CO2e
ipcc_values = {'ipcc_ch4_100': 28,
'ipcc_ch4_20': 72,
'ipcc_n2o_100': 298,
'ipcc_n2o_20': 289}
ipcc_multipliers = [1, ipcc_values["ipcc_ch4_{}".format(time_horizon)], ipcc_values["ipcc_n2o_{}".format(time_horizon)]]
ghg_total_kg = 0
for x in range(3):
impact = pd.read_csv(filepaths[x]).loc[:,'r']
impact *= ipcc_multipliers[x]
ghg_total_kg = ghg_total_kg + impact
return ghg_total_kg
def IOSolutionPhysicalUnits(A, y):
# Solves for total requirements from each sector in in physical units
#
# Args:
# A: input-output vector in physical units
# y: direct requirements vector
#
# Returns:
# The total (direct + indirect) requirements by sector
num_sectors = A.shape[1]
I = np.eye(A.shape[1])
solution = np.linalg.solve((I - A), y)
return solution
def TotalGHGEmissions(io_data, y, biorefinery_direct_ghg, cooled_water_ghg, time_horizon):
# Returns a vector of of all GHG emissions in the form of kg CO2e
#
# Args:
# A: input-output vector in physical units ratios
# y: direct requirements vector in physical units
# co2.filepath: filepath to csv file containing kg CO2/kg output for
# each sector
# ch4.filepath: filepath to csv file containing kg CH4/kg output for
# each sector
# n2o.filepath: filepath to csv file containing kg N2O/kg output for
# each sector
# time.horizon: number of years used for time horizon of normalized GHG
# forcing
# biorefinery.direct.ghg: kg fossil CO2e emitted directly at the biorefinery
# combustion.direct.ghg: kg fossil CO2e emitted during product combustion/
# end-of-life. Only applicable where some fossil carbon is in product
# or there is net biogenic carbon sequestration
# Returns:
# The net GHG emissions (kg CO2e) for the product life cycle by sector
A = io_data.drop(['products'],1).values.T
y_array = []
for item in io_data['products']:
y_array.append(y[item])
io_ghg_results_kg = IOSolutionPhysicalUnits(A, y_array) * GHGImpactVectorSum(time_horizon)
io_ghg_results_kg = np.append(io_ghg_results_kg,[biorefinery_direct_ghg, cooled_water_ghg])
rownames = np.append(io_data.products.values, ['direct', 'cooled_water_and_steam'])
io_ghg_results_kg_df = pd.DataFrame(io_ghg_results_kg, columns = ['ghg_results_kg'])
io_ghg_results_kg_df['products'] = rownames
return io_ghg_results_kg_df
def TotalWaterImpacts(io_data, y, water_consumption, biorefinery_direct_consumption):
# Returns a vector of of all water consumption in the form of liters of water
#
# Args:
# A: input-output vector in in physical units ratios
# y: direct requirements vector in in physical units
# water.consumption.filepath: filepath to csv file containing liters
# water consumed/kg output for each sector
# biorefinery.direct.water.consumption: liters water consumed directy at the
# biorefinery
# Returns:
# The net water consumption (liters water) for the product life cycle by sector
A = io_data.drop(['products'],1).values.T
y_array = []
water_consumption_array = []
for item in io_data['products']:
y_array.append(y[item])
water_consumption_array.append(water_consumption[item])
io_water_consumption_results_kg = IOSolutionPhysicalUnits(A, y_array) * water_consumption_array
results_liter_water_consumption = np.append(io_water_consumption_results_kg, biorefinery_direct_consumption)
rownames = np.append(io_data.products.values, 'direct')
io_water_results_kg_df = pd.DataFrame(results_liter_water_consumption, columns = ['liter_results_kg'])
io_water_results_kg_df['products'] = rownames
return io_water_results_kg_df
def AggregateResults(m, results_kg_co2e, selectivity, scenario, fuel):
if fuel == 'ethanol':
# Category 1 : "Farming"
m[scenario][selectivity].loc['Farming'] = results_kg_co2e["farmedstover.kg"]
# Category 2 : "Transportation"
m[scenario][selectivity].loc['Transportation'] = sum([results_kg_co2e["flatbedtruck.mt_km"],
results_kg_co2e["tankertruck.mt_km"],
results_kg_co2e["rail.mt_km"],
results_kg_co2e["gaspipeline.mt_km"],
results_kg_co2e["liquidpipeline.mt_km"],
results_kg_co2e["barge.mt_km"],
results_kg_co2e["marinetanker.mt_km"]])
# Category 3 : "Petroleum Products"
m[scenario][selectivity].loc['Petroleum'] = sum([results_kg_co2e["diesel.MJ"],
results_kg_co2e["rfo.MJ"],
results_kg_co2e["refgas.MJ"],
results_kg_co2e["gasoline.MJ"],
results_kg_co2e["crudeoil.MJ"],
results_kg_co2e["coal.MJ"],
results_kg_co2e["naturalgas.MJ"]])
# Category 4: "Electricity"
m[scenario][selectivity].loc['Electricity'] = sum([results_kg_co2e["electricity.NG.kWh"],
results_kg_co2e["electricity.NGCC.kWh"],
results_kg_co2e["electricity.Coal.kWh"],
results_kg_co2e["electricity.Lignin.kWh"],
results_kg_co2e["electricity.Renewables.kWh"],
results_kg_co2e["electricity.WECC.kWh"],
results_kg_co2e["electricity.MRO.kWh"],
results_kg_co2e["electricity.SPP.kWh"],
results_kg_co2e["electricity.TRE.kWh"],
results_kg_co2e["electricity.SERC.kWh"],
results_kg_co2e["electricity.RFC.kWh"],
results_kg_co2e["electricity.NPCC.kWh"],
results_kg_co2e["electricity.US.kWh"],
results_kg_co2e["electricity.FRCC.kWh"],
results_kg_co2e["electricity.china.kWh"]])
# Category 5: "Chemicals and Fertilizers"
m[scenario][selectivity].loc['Chemicals_And_Fertilizers'] = sum([results_kg_co2e["n.kg"],
results_kg_co2e["hcl.kg"],
results_kg_co2e["dap.kg"],
results_kg_co2e["k2o.kg"],
results_kg_co2e["p2o5.kg"],
results_kg_co2e["cellulase.kg"],
results_kg_co2e["atrazine.kg"],
results_kg_co2e["nacl.kg"],
results_kg_co2e["urea.kg"],
results_kg_co2e["insecticide.kg"],
results_kg_co2e["h2so4.kg"],
results_kg_co2e["naoh.kg"],
results_kg_co2e["ammonia.kg"],
results_kg_co2e["ethylene.MJ"],
results_kg_co2e["caco3.kg"],
results_kg_co2e["lysine.us.kg"],
results_kg_co2e["methanol.kg"],
results_kg_co2e["glucose.kg"],
results_kg_co2e["corn.bushel"],
results_kg_co2e["corn_starch.kg"]])
#Direct emissions at the biorefinery facility
m[scenario][selectivity].loc['Direct'] = results_kg_co2e["direct"]
#Others
m[scenario][selectivity].loc['Other'] = (round(sum(results_kg_co2e.values()),3) -
round(sum([m[scenario][selectivity].loc['Farming'],
m[scenario][selectivity].loc['Transportation'],
m[scenario][selectivity].loc['Petroleum'],
m[scenario][selectivity].loc['Electricity'],
m[scenario][selectivity].loc['Chemicals_And_Fertilizers'],
m[scenario][selectivity].loc['Direct']]),3))
else:
m[scenario]['All'][selectivity] = sum(results_kg_co2e.values())
|
masa=float(input("Ingresa tu masa en kilogramos"))
peso=float(input("Ingresa tu altra en metros"))
imc=masa/altura**2
print("Tu imc es: ")+str(imc))
if imc >= 25 :
print("Tienes sobrepeso")
if imc <= 19 :
print("Tienes bajo peso")
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#功能要求:
# 要求用户输入总资产,例如:2000
# 显示商品列表,让用户输入商品名称,加入购物车
# 购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。
# 附加:可充值、某商品移除购物车
#用字典构造以购买产品,购物车
#用户输入总资产
zong_zi_chan = input("请输入你的总资产")
#将用户输入总资产转换成数字类型
zong_zi_chan1 = int(zong_zi_chan)
#打印出总资产
print("您的总资产为",zong_zi_chan1,"元")
print("\n")
#产品字典
shang_pin = [
{"名称":"手机", "价格":200},
{"名称":"电脑", "价格":300},
{"名称":"水笔", "价格":10},
{"名称":"纸张", "价格":20},
]
print("可购买产品有:")
for i in shang_pin:
#循环出产品字典里的名称和价格
print(i["名称"],i["价格"],"元")
print("\n")
#以购买的产品
gou_mai2 = {}
#循环购买模块
while True:
#用户输入要购买的产品名称
gou_mai = input("请输入要购买的商品名称,输入y结算")
#将用户输入的信息进行判断,如果用户输入的是y退出循环购买模块
if gou_mai.lower() == "y":
break
else:#如果用户输入不是y执行下面
for i in shang_pin:
#判断循环到的产品名称如果等于用户输入的购买名称
if i["名称"] == gou_mai:
#将循环到的赋值给一个变量
chan_pin = i["名称"]
#判断循环到的名称在已购买产品字典里是否存在这个键
if chan_pin in gou_mai2.keys():
#如果存在将已购买产品字典里本条数据的数量加1
gou_mai2[chan_pin]["数量"] = gou_mai2[chan_pin]["数量"] + 1
else:
#如果不在将已购买产品字典里,将本条数据更新到已购买产品字典里,默认数量1
gou_mai2[chan_pin] = {"价格":i["价格"], "数量":1}
#打印已购买产品
print(gou_mai2)
print("\n")
print("您以购买的商品有:")
#购买产品的所有共计费用
gong_ji = 0
#循环出以购买产品字典里的键和值
for k,v in gou_mai2.items():
#将字典里的价格赋值给一个变量
jia_ge = v["价格"]
#将字典里的数量赋值给一个变量
shu_liang = v["数量"]
#将数量乘以价格等于每样产品的总价
zong_jia = shu_liang * jia_ge
#打印出以购买的每样产品的价格,数量,总价
print(k,"价格", v["价格"], "数量", v["数量"], "总价=",zong_jia)
#每次循环累计共计加总价等于共计消费
gong_ji += zong_jia
#打印出共计费用
print("共计:",gong_ji)
#判断总资产如果大于或者等于共计费用,购买成功,如果总资产小于共计费用说明资金不够
if zong_zi_chan1 >= gong_ji:
print("恭喜你购买成功")
else:
print("对不起你的资金不够,请充值") |
dictionary = []
def displayDictionary():
if dictionary==[]:
print("*** The dictionary is empty ***")
else:
print("*** Known words ****")
for i in dictionary:
print("%-8s %-8s"%(i[0],i[1]))
def lookup(word):
if dictionary==[]:
words=input("How do i translate %s:"%word)
dictionary.append([word,words])
return words
else:
for i in dictionary:
if word in i:
words=i[1]
return words
words=input("How do i translate %s:"%word)
dictionary.append([word,words])
return word
def file_dic(file1):
# global file1
for l in file1.readlines():
l=l.strip("\n")
l=l.split("/")
dictionary.append([l[0],l[1]])
return file1
def Copydictionary(filename):
file=open(filename,"w")
for i in dictionary:
file.write("%s/%s\n"%(i[0],i[1]))
def main():
while True:
reply = input("Eng:>")
reply.lower()
reply=reply.replace(","," ")
reply=reply.replace("."," ")
reply=reply.replace(":"," ")
reply=reply.replace("!"," ")
if reply=="?":
displayDictionary()
elif reply=="save":
Copydictionary(filename)
elif reply=="quit":
choice=input("yes or no:")
if choice=="yes":
Copydictionary(filename)
break
else:
main()
else:
translatedReply=[]
r=reply.split()
for word in r:
if (word==".")or(word=="?")or(word=="!"):
continue
else:
translation = lookup(word)
translatedReply.append(translation)
for i in range(len(translatedReply)):
print(translatedReply[i],end=" ")
print()
print("quit: quit the program save: save in file")
filename=input("what file do you open:")
file1=open(filename,"r")
file_dic(file1)
main()
|
def selection_sort(list):
for i in range( len(list) ): # Loop through the entire array
# Find the position that has the smallest number
# Start with the current position
minPos = i
for j in range(i+1, len(list) ): # Scan what's left
if len(list[j]) < len(list[minPos]): # Is this position smallest?
minPos = j # yes, save position
# Swap the two values
temp = list[minPos]
list[minPos] = list[i]
list[i] = temp
# Binary Search, recursive version
# def binary_search(the_list, lower, upper, item):
# if lower > upper:
# print( "%s is not in the list." % item )
# return -1
#
# middle_pos = (lower + upper) // 2
# if the_list[middle_pos] < item:
# lower = middle_pos+1
# return binary_search(the_list, lower, upper, item)
# elif the_list[middle_pos] > item:
# upper = middle_pos-1
# return binary_search(the_list, lower, upper, item)
# else:
# print( "%s is at position %d" %(item,middle_pos))
# return middle_pos
# Binary Search, iterative versionoip
def binary_search_iterative(the_list, item): #
selection_sort(the_list)
lower_bound = 0
upper_bound = len(the_list)-1
found = False
while lower_bound <= upper_bound and not found :
middle_pos =( (lower_bound + upper_bound) // 2)
if the_list[middle_pos][0] < item:
lower_bound = middle_pos+1
elif the_list[middle_pos][0] > item:
upper_bound = middle_pos-1
else:
print(the_list[middle_pos])
the_list.remove(the_list[middle_pos])
binary_search_iterative(the_list, item)
found = True
# if found:
# print( "%s is at position %d" % (item,middle_pos))
# return middle_pos
# else:
# print( "%s is not in the list." % item )
# return -1
filename = "example_sorted_names.txt"
with open(filename, 'r') as f:
lines = f.read()
name_list = lines.split('\n')
print(name_list)
binary_search_iterative(name_list, 'S')
# K = [ x for x in range(50)]
# print (K[:6])
# print("Test recursive binary search")
# index = binary_search (K, 0, len(K)-1, 5) # should return 5
# index = binary_search (K, 0, len(K)-1, 1005) # should return -1 (not found)
#
# print("Test Iterative Binary Search")
# index = binary_search_iterative (K, 5) # should return 5
# index = binary_search_iterative (K, 1005) # should return -1 (not found)
|
def total(R1,R2,R3):
R=1/(1/R1+1/R2+1/R3)
return R
R1=float(input("R1 is:"))
R2=float(input("R2 is:"))
R3=float(input("R3 is:"))
print(total(R1,R2,R3))
|
import random
def randomised_st_connectivity(G, n, s, t):
stepcount = 0
current_vertex = s
while (current_vertex != t) and (stepcount < 2*n**3):
a=random.randint(0,n-1)
# print(a)
if int(G[current_vertex-1][a]) != 0:
current_vertex = a+1
else:
continue
stepcount = stepcount + 1
if current_vertex == t:
return (True, stepcount)
else:
return (False, stepcount)
content = []
f = open("testgraph7.txt","r")
list = f.read()
list = list.split("\n")
for i in range(len(list)):
list[i] = list[i].split()
for l in list:
if len(l)>3:
content.append(l)
print(content)
print(randomised_st_connectivity(content, int(list[0][0]), int(list[1][0]), int(list[2][0])))
|
A = int(input("The start value:"))
B = int(input("The end value:"))
L=1
count=0
for i in range(A,B+1):
print(i,end=" ")
count+=1
if (L==count):
print()
L+=1
count=0
else:
continue
A = int(input("Line:"))
for i in range(A):
for j in range(i):
print(A,end="\t")
A+=1
print()
|
import turtle
wn = turtle.Screen()
my_turtle = turtle.Turtle()
for i in range(0,101,10):
my_turtle.forward(i)
my_turtle.left(90)
my_turtle.forward(i)
my_turtle.left(90)
wn.exitonclick()
|
# import random
#
# def main():
# smaller=int(input("Enter the smaller numbers:"))
# larger=int(input("Enter the larger number:"))
# myNumber=random.randint(smaller,larger)
# count=0
# while True:
# count +=1
# usernumber=int(input("Enter your guess:"))
# if usernumber < myNumber:
# print("Too small")
# elif usernumber > myNumber:
# print("Too large")
# else:
# print("You`re got it in",count,"tries")
# break
#
# if __name__ =="__main__" :
# main()
# import random
# # traveled=0
# # travellist=[5,6,7,8,9,10,11,12]
# traveled=random.randint(5,12)
# print("miles traveled=",traveled)
import pygame
import mycritters
# Define some colors
white = ( 255, 255, 255)
green = ( 0, 255, 0)
lightblue = ( 0, 100, 255)
brown = ( 125, 100, 100)
# Initialize pygame
pygame.init()
# Set the height and width of the screen
size=[1000,1000]
screen=pygame.display.set_mode(size)
# Set title of screen
pygame.display.set_caption("Critters")
# Function to draw background scene
def draw_background():
pygame.draw.rect(screen,brown,[0, 700, 1000, 300])
pygame.draw.rect(screen,green,[0, 600, 1000, 100])
pygame.draw.rect(screen,lightblue,[0, 0, 1000, 600])
pygame.draw.ellipse(screen,white,[50, 80, 100, 60])
pygame.draw.ellipse(screen,white,[120, 60, 180, 80])
pygame.draw.ellipse(screen,white,[700, 80, 150, 60])
# Loop until the user clicks the close button.
done=False
# Used to manage how fast the screen updates
clock=pygame.time.Clock()
critterlist = []
######################################
# -------- Main Program Loop -----------
while done==False:
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done=True # Flag that we are done so we exit this loop
if event.type == pygame.KEYDOWN: # If user wants to perform an action
if event.key == pygame.K_c:
newcaterpillar = mycritters.Caterpillar()
critterlist.append(newcaterpillar)
# Draw the background scene
draw_background()
# Draw the critters
for critter in critterlist:
critter.draw_critter(screen)
# Limit to 20 frames per second
clock.tick(50)
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# If you forget this line, the program will 'hang' on exit.
pygame.quit ()
|
def translate(animal,language):
if animal=="cat" :
if language=="Chinese":
ww="The translate of a cat into Chinese is Māo"
elif language=="German":
ww="The translate of a cat into German is katze"
elif language=="French":
ww="The translate of a cat into French is chat"
elif language=="Spanish":
ww="The translate of a cat into Spanish is gate"
elif language:
ww=""
elif animal=="dog":
if language=="Chinese":
ww="The translate of a dog into Chinese is Gǒu"
elif language=="German":
ww="The translate of a dog into German is hund"
elif language=="French":
ww="The translate of a dog into French is chien"
elif language=="Spanish":
ww="The translate of a dog into Spanish is perro"
elif language:
ww=""
elif animal:
ww=""
return ww
animal =input("What is your pet? : ")
language =input("What is the language? :")
language=language.capitalize()
print(translate(animal,language))
|
a = 0
for i in range(10):
a = a + 1
print(a,"\n")
for j in range(10):
a = a + 1
print(a)
mylist = [1,2,3,4,5,6,7,8,9,10]
mylist[0:10:2] = ['a', 'b', 'c', 'd', 'e']
print(mylist)
mylist[9::-3] = [22, 22, 22, 22]
print(mylist)
lst=['my ', 'big ', 'fat ']
lst.append('wedding ')
lst.extend(['next','week'])
print(lst)
newlst=['my','big','wedding','next','week']
newlst.insert(0, 'fat ')
print(newlst,",,,,")
newlst1=['my ', 'big ', 'fat ', 'wedding', 'next', 'week ']
newlst1.pop()
print(newlst1)
newlst1.pop(0)
print(newlst1)
x=[1,2,3,4]
x.reverse()
print(x)
newlst2=['my ', 'big ', 'fat ', 'wedding ', 'next', 'week ']
print(newlst2.index('next'),)
lst1=['my ', 'big ', 'fat ', 'bottom ']
print(''.join(lst1))
print([x*x for x in range(10) if x % 2 == 0])
print([x+2*y for x in range(4) for y in range(3)])
result = []
for x in range(4):
for y in range(3):
result.append(x+2*y)
print(result)
def even(x):
return x % 2==0
list(map(even,[1,2,3,4,5]))
print(list(map(even,[1,2,3,4,5])))
print([even(x) for x in [0,1,2,3,4]])
def negative(x):
return x<0
print(list(filter(negative,[-1, 2, -3, 5, 7, -9])))
print([x for x in [-1, 2, -3, 5, 7, -9] if negative(x)])
ll=[1,2,3,4,5]
print(zip(ll,ll))
def removedups(mylist):
newlist = [ ]
for x in mylist:
if x not in newlist:
newlist.append(x)
return newlist
def removedups1(mylist):
for x in mylist:
if mylist.count(x) > 1:
indx = mylist.index(x)
del mylist[indx]
return mylist
a=[1,1,2,5,8,9,3,6,6,6,7,9]
print(removedups(a))
print(removedups1(a))
def pascal(n):
if n == 1:
return [[1]]
else:
result = [[1]]
x = 1
while x < n:
lastRow = result[-1]
nextRow = [(a+b) for a,b in zip([0]+lastRow,lastRow+[0])]
result.append(nextRow)
x += 1
return result
n=10
print(pascal(n))
import random
p=[[(x,y) for x in range(0,600,15)] for y in range(0,600,15)]
for i in p:
print(i)
print(p)
q=[ i for i in range(240,480,15)]
print(q)
|
import math
def Volume(R):
V = (4*math.pi*R*R*R)/3
return V
R = float(input("sphere radius:"))
print("volume is:",Volume(R))
|
import random
def coin_toss(number):
A = random.randint(0,1)
if A==0:
X="heads"
else:
X="tails"
return X
H=0
T=0
number=int(input("number of coin tosses:"))
for i in range(number):
print(coin_toss(number))
if coin_toss(number)=="heads":
H+=1
else:
T+=1
print(H,"× heats",T,"× tails")
|
a=int(input("ENTER YOUR ROLL NUMBER"))
if a==1:
print ("JONES")
a=int(input("ENTER YOUR ROLL NUMBER"))
if a==1:
print ("JONES")
elif a==4:
print ("KODIDETY SOLOMON JONES")
break
elif a==4:
print ("KODIDETY SOLOMON JONES")
else:
print ("invalid entry")
|
a=input("value of A")
b=input("value of B")
if a>b:
print ("A is greater")
if a<b:
print ("B is greater")
if a==b:
print ("Both are equal")
|
'''
Michael Galarnyk
1. Define a function named to_number(str) that takes a string as a parameter, converts it to an int value, and returns that int value.
2. Define a function named add_two(n1, n2) that takes two ints as parameters, sums them, and then returns that int sum value.
3. Define a function named cube(n) that takes numeric value as a parameter, cubes that value, and then returns that resulting numeric value.
4. Use the above functions in one statement to take two string literals, convert them to ints, add them together, cube the result, and print the cubed value.
'''
def to_number(string):
new_int = int(string)
return new_int
def add_two(n1,n2):
summation = n1 + n2
return summation
def cube(n):
cubed = n**3
return cubed
print cube(add_two(to_number('6'),to_number('5')))
|
import turtle
import math
def square(t,length):
"""Draws a square with the given length.
:param t: Turtle
:param length: Side length
"""
for i in range(4):
t.fd(length)
t.lt(90)
def polygon(t,length,n):
"""Draws a polygon with the given number and length.
:param t: Turtle
:param length: Side length
:param n: The number of edges
"""
for i in range(n):
t.fd(length)
t.lt(360/n)
def polyline(t,length,n,angle):
"""Draws a polyline with the given number,length and angle.
:param t: Turtle
:param length: Side length
:param n: The number of lines
:param angle: Angle of rotation
"""
for i in range(n):
t.fd(length)
t.lt(angle)
def arc(t, r, angle):
"""Draws a arc with the given radius and angle.
:param t: Turtle
:param r: radius
:param angle: Angle of rotation
"""
arc_length = 2 * math.pi * r * abs(angle) / 360
n = int(arc_length / 4) + 1
step_length = arc_length / n
step_angle = float(angle) / n
# making a slight left turn before starting reduces
# the error caused by the linear approximation of the arc
t.lt(step_angle/2)
polyline(t, step_length,n,step_angle)
t.rt(step_angle/2)
def circle(t, r):
"""Draws a circle with the given radius.
t: Turtle
r: radius
"""
arc(t, r, 360)
bob = turtle.Turtle()
#circle(bob,100)
#square(bob,200)
#polygon(bob,40,9)
#polyline(bob,40,6,30)
def petal(t,r,angel):
for i in range(2):
t.lt(angel)
t.fd(10)
arc(t,r,angel)
t.rt(180-angel)
petal(bob,30,60)
# wait for the user to close the window
turtle.mainloop() |
import turtle
bob = turtle.Turtle()
def square(t,length):
"""Draws a square with the given length.
:param t: Turtle
:param length: Side length
"""
for i in range(4):
t.fd(length)
t.lt(90)
square(bob,100) |
import re
class Lexer(object):
"""dosource_codering for Lexer"""
def __init__(self, source_code):
self.source_code = source_code
def token(self):
#print('test')
# Where all the tokens dibuat oleh lexer akan di stored
tokens = []
# Menampung wordlist di test lang
source_code =self.source_code.split()
# Will keep track f the word index
source_index = 0
#Mengulangi isi pada test lang
while source_index < len(source_code):
kata = source_code[source_index]
#mengandung token tyoe dan value ke tokens
if kata == "var": tokens.append(["VAR_DECLERATION", kata])
# harus menambahkan import re berguna jika kita tidak menemmukan sesuatu yang tidak spesifikasi
elif re.match('[a-z]', kata) or re.match('[A-Z]', kata):
if kata[len(kata)-1] == ";":
tokens.append(['id', kata[0:len(kata)-1]])
else:
tokens.append(['id', kata])
# sekarang untuk angka
elif re.match('[0-9]', kata):
if kata[len(kata)-1] == ";":
tokens.append(['int', kata[0:len(kata)-1]])
else:
tokens.append(['Int', kata])
elif kata in "=/*=+":
tokens.append(['OP', kata])
if kata[len(kata)-1] == ";":
tokens.append(['symbol', ';'])
#print(source_code[source_index])
#Menambah increment agar tidak melakukan re-check token
source_index += 1
print(tokens)
return tokens |
#Alex Shelton
#Project Euler Problem 3:
# The prime factors of 13195 are 5, 7, 13 and 29.
# What is the largest prime factor of the number 600851475143 ?
#Answer = 6857
#Get the factors in a list using % Done
# Checking if the number is prime or not: Done
# finding largest prime
import math
import time
def getFactors(n):
factors = []
for num in range(1, int(math.sqrt(n))+1):
if n % num == 0: #divides evenly
factors.append(num)
factors.append(n // num)
return factors
def isPrime(n):
return len(getFactors(n)) == 2
start = time.time()
largestPrime = 0
listOfFactors = getFactors(600851475143)
for factor in listOfFactors:
if(isPrime(factor) and factor > largestPrime):
largestPrime = factor
print(largestPrime)
end = time.time()
print(end - start)
|
from argparse import ArgumentParser
from pathlib import Path
import shutil
import random
def main(input_dir: Path, output_dir: Path, num_move, filetype=None):
if filetype is None:
paths = list(Path(input_dir).iterdir())
else:
paths = list(Path(input_dir).glob("*" + filetype))
random.shuffle(paths)
for path in paths[:num_move]:
shutil.move(path, output_dir / path.name)
if __name__ == "__main__":
parser = ArgumentParser(
description="Move a number of files from one directory to another."
" Useful when making a test set.")
parser.add_argument("--input_dir", required=True,
help="Path to move files from")
parser.add_argument("--output_dir", required=True,
help="Path to move files to")
parser.add_argument("-n", "--num_move", required=True, type=int,
help="Percent in 0 to 100, float")
parser.add_argument("-f", "--filetype", default=None,
help="Move only files of this file type")
args = parser.parse_args()
main(
input_dir=Path(args.input_dir),
output_dir=Path(args.output_dir),
num_move=args.num_move,
filetype=args.filetype)
|
from time import time
class ContextTimer:
""" Usage:
with ContextTimer() as timer:
#do stuff
print("Current time: ", timer.time)
# do more stuff
print("Current time: ", timer.time
print("Total process took : ", timer.time, " seconds")
"""
def __init__(self, name="GenericTimer", post_print=True):
self.name = name
self.post_print = post_print
def __enter__(self):
self.start_time = time()
return self
def __exit__(self, type, value, traceback):
self.end_time = time()
if self.post_print:
final_elapsed = self.end_time - self.start_time
fps = None if final_elapsed == 0 else 1 / final_elapsed
p = self.name + ": " + str(final_elapsed)
if fps is not None:
p += " FPS: " + str(fps)
print(p)
@property
def elapsed(self):
return time() - self.start_time
|
"""Utility functions"""
import os
import pandas as pd
import matplotlib.pyplot as plt
def plot_selected(df, columns, start_index, end_index):
"""Plot the desired columns over index values in the given range."""
df_temp = df.ix[start_index : end_index, columns]
plot_data(df_temp, "Selected data")
def symbol_to_path(symbol, base_dir = "data"):
"""Return CSV file path given ticker symbol."""
return os.path.join(base_dir, "{}.csv".format(str(symbol)))
def get_data(symbols, dates):
"""Read stock data (adjusted close) for given symbols from CSV files."""
df = pd.DataFrame(index = dates)
if 'SPY' not in symbols: # add SPY for reference, if absent
symbols.insert(0, 'SPY')
for symbol in symbols:
df_temp = pd.read_csv(symbol_to_path(symbol), index_col = "Date",
parse_dates = True, usecols = ['Date', 'Adj Close'],
na_values = ['nan'])
# Rename to prevent clash
df_temp = df_temp.rename(columns = {'Adj Close' : symbol})
df = df.join(df_temp)
if symbol == 'SPY': # drop dates SPY did not trade
df = df.dropna(subset = ["SPY"])
return df
def plot_data(df, title = 'Stock Prices', xlabel = 'Date', ylabel = 'Price'):
'''Plot stock prices'''
axis = df.plot(title = title, fontsize = 12)
axis.set_xlabel(xlabel)
axis.set_ylabel(ylabel)
plt.show()
def how_long(func, *args):
"""Execute function with given arguments, measurng exec time."""
t0 = time()
result = func(*args)
t1 = time()
return result, t1 - t0
def get_rolling_mean(values, window):
"""Return rolling mean of given values, using specified window size."""
return pd.rolling_mean(values, window=window)
def get_rolling_std(values, window):
"""Return rolling standard deviation of given values, using specified window size."""
return pd.rolling_std(values, window = window)
def get_bollinger_bands(rm, rstd):
"""Return upper and lower Bollinger Bands."""
upper_band = rm + 2 * rstd
lower_band = rm - 2 * rstd
return upper_band, lower_band
def compute_daily_returns(df):
"""Compute and return the daily return values."""
daily_returns = (df / df.shift(1)) - 1 # with Pandas
daily_returns.ix[0, :] = 0 # set daily returns for row 0 to 0
return daily_returns
def fill_missing_values(df_data):
"""Fill missing values in data frame, in place."""
df_data.fillna(method="ffill", inplace=True)
df_data.fillna(method="bfill", inplace=True)
|
"""Locate maximum value."""
import numpy as np
def get_max_index(a):
"""Return the index of the maximum value in given 1D array."""
return a.argmax()
def test_run():
a = np.array([9, 6, 2, 3, 12, 14, 7, 10], dtype=np.int32) # 32-bit integer array
print "Array:", a
# Find the maximum and its index in array
print "Maximum value:", a.max()
print "Index of max.:", get_max_index(a)
if __name__ == "__main__":
test_run()
|
"""Fit a polynomial to a given set of data points using optimization."""
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize as spo
def error_poly(C, data): # error function
"""Compute error between given polynomial and observed data.
Parameters
----------
C: numpy.poly1d object or equivalent array representing polynomial coefficients
data: 2D array where each row is a point (x, y)
Returns error as a single real value.
"""
# Metric: Sum of squared Y-axis differences
err = np.sum((data[:, 1] - np.polyval(C, data[:, 0])) ** 2)
return err
def fit_poly(data, error_func, degree = 3):
""" Fit a polynomial to given data, using supplied error function.
Parameters
----------
data: 2D array where each row is a point (X0, Y)
error_func: function that computes the error between a polynomial and observed data
degree: polynomial degree
Returns line that optimizes the error function.
"""
# Generate initial guess for polynomial model (all coeffs = 1)
Cguess = np.poly1d(np.ones(degree + 1, dtype = np.float32))
# Plot initial guess (optional)
x = np.linspace(-5, 5, 21)
plt.plot(x, np.polyval(Cguess, x), 'm--', linewidth = 2.0, label = 'Initial guess')
# Call optimizer to minimize error function
result = spo.minimize(error_func, Cguess, args = (data, ), method = 'SLSQP', options = {'disp': True})
return np.poly1d(result.x) # convert optimal result into a poly1d object
def test_run():
# Define original polynomial
Corig = np.poly1d(np.float32([1.5, -10, -5, 60, 50]))
print "Original polynomial:\n{}".format(Corig)
Xorig = np.linspace(-5, 5, 21)
Yorig = np.polyval(Corig, Xorig)
plt.plot(Xorig, Yorig, 'b--', linewidth = 2.0, label = "Original line")
# Generate noisy data point
noise_sigma = 30.0
noise = np.random.normal(0, noise_sigma, Yorig.shape)
data = np.asarray([Xorig, Yorig + noise]).T
plt.plot(data[:, 0], data[:, 1], 'go', label = "Data points")
# Try to fit a line to this data
p_fit = fit_poly(data, error_poly, 4)
print "Fitted poly:\n{}".format(p_fit)
plt.plot(data[:, 0], np.polyval(p_fit, data[:, 0]), 'r--', linewidth = 2.0, label = "Fitted line")
# Add a legend and show plot
plt.legend(loc = 'upper left')
plt.show()
if __name__ == "__main__":
test_run()
|
string = raw_input()
Q = int(raw_input())
for i in xrange(Q):
sub = raw_input()
if sub in string:
print "Yes"
else:
print "No"
|
T = int(raw_input())
def printArray(arr):
for item in arr:
print item,
print
def merge(arr1,arr2,N,M):
i = j = k = 0
merged = [0] * (N+M)
while( i < N and j < M):
if arr1[i] >= arr2[j]:
merged[k] = arr1[i]
i += 1
k +=1
else:
merged[k] = arr2[j]
j +=1
k +=1
if i!=N:
while(i < N):
merged[k] = arr1[i]
k += 1
i +=1
if j!=M:
while(j < M):
merged[k] = arr2[j]
k += 1
j +=1
return merged
for i in xrange(T):
N,M = map(int,raw_input().strip().split())
arr1 = map(int,raw_input().strip().split())
arr2 = map(int,raw_input().strip().split())
merged = merge(arr1,arr2,N,M)
printArray(merged)
|
import time
import pickle
import random
from random import seed,randint
class OTGame(object):
'''Oregon Trail text game. Developed by Python Foundations Class, Hack Oregon Summer 2016'''
def __init__(self):
# self.intro()
# self.start_month = self.going()
# self.role, self.bank = self.characters()
# self.bank = 1600
# self.supplies, self.bank = self.shop()
self.river_cross()
#TODO make your function a method within the OTGame class, and anything returned as an attribute
def intro(self):
"""gives player options to start, learn about the game, or change settings."""
valid_choices = ['1','2','3','4','5','6']
options = \
'''You may:
1. Travel the trail
2. Learn about the trail
3. See the Oregon Top Ten
4. Turn sound off
5. Choose Management Options
6. End
What is your Choice?:
'''
story = \
'''
Try taking a journey by covered
wagon across 2000 miles of plains,
rivers, and mountains. Try! On the
plains, will you slosh your oxen
through ud and watter-filled ruts
or will you plod through dust six
inches deep?
How will you cross the rivers? If
you have money, you might take a
ferry (if there is a ferry). Or,
you can ford the river and hope
you and your wagon aren't swalled
alive!
What about supplies? Well, if you're
low on food you can hunt. You might
get a buffalo ... you might. And
there are bear in the Mountains.
At the Dalles, you can try navigating
the Columbia River, but if running
the rapids with a makeshift raft
makes you queasy, better take the
Barlow Road.
If for some reason you don't
survive -- your wagon burns, or
thieves steal your oxen, or you
run out of provisions, or you die
of cholera -- don't give up! Try
again... and again... until your
name is up owith the others on
The Oregon Top Ten.
The software team responsible for
Creation of this product is the
Hack University Python Foundations
class.
'''
print('Welcome to the Oregon Trail!')
choice = input(options)
while choice not in valid_choices:
print('"{}" is not a valid response, try again'.format(choice))
time.sleep(2)
choice = input(options)
if choice == '1':
#1. Travel the trail
self.player_name()
elif choice == '2':
#2. Learn about the trail
print(story)
time.sleep(10)
self.intro()
elif choice == '3':
top_ten = pickle.load(open('topten.txt','rb'))
for position, name in top_ten:
print(position, name)
time.sleep(3)
self.intro()
elif choice == '4':
print('This functionality has not been made yet')
time.sleep(3)
self.intro()
elif choice == '5':
management_options()
elif choice == '6':
exit()
def management_options(self):
valid_inputs = ['1','2','3','4']
options = \
'''
You may:
1. See the current Top Ten List
2. Erase the current Tob Ten List
3. Erase saved games
4. Return to the main menu
What is your choice?: '''
choice = input(options)
while choice not in valid_inputs:
print('"{}" is not a valid response, try again'.format(choice))
time.sleep(2)
choice = input(options)
if choice == '1':
top_ten = pickle.load(open('topten.txt','rb'))
for position, name in top_ten:
print(position, name)
time.sleep(3)
management_options()
elif choice == '2':
top_ten = [('Top Ten:','')]
for i in range(1,11):
top_ten.append((i,''))
pickle.dump(top_ten,open('topten.txt','wb'))
for position, name in top_ten:
print(position, name)
time.sleep(3)
management_options()
elif choice == '3':
print('Feature has not been built yet')
time.sleep(2)
management_options()
elif choice == '4':
self.intro()
def player_name(self):
print('Five players are required to play The Oregon Trail.')
self.trail_dict = {}
for item in range(1, 6):
player = input("What is the name of player #{}?: ".format(item))
self.trail_dict['player{}'.format(item)] = ({'name': player, 'health': 10, 'status': "Healthy"})
def going(self):
choice = 0
while choice not in ['1', '2', '3', '4', '5', '6']:
choice = input('''When ya going? Pick a month:
1. March
2. April
3. May
4. June
5. July
6. Ask for advice
''')
if choice == '1':
return 'March'
elif choice == '2':
return 'April'
elif choice == '3':
return 'May'
elif choice == '4':
return 'June'
elif choice == '5':
return 'July'
elif choice == '6':
print('''If you leave too early there will not be any grass for your oxen to eat. \n
If you leave to late you may not get to Oregon before winter comes. \n
If you leave at just the right time, there will be green grass and the weather will still be cool.''')
self.going()
def characters(self):
choice = input('''Many kinds of people made the trip to Oregon.
You may:
1. Be a banker from Boston
2. Be a carpenter from Ohio
3. Be a farmer from Illinois
What is your choice? ''')
if choice == '1':
print ('You are a banker; you have $1600.')
return 'Banker',1600
elif choice == '2':
print ('You are a carpenter; you have $800.')
return 'Carpenter',800
elif choice == '3':
print ('You are a farmer; you have $400.')
return 'Farmer',400
else:
print ('Please choose 1, 2 or 3.')
return self.characters()
def shop(self):
store = {
'oxen': (40, 'yoke'),
'food': (.20, 'lb'),
'clothing': (10, 'set'),
'ammunition': (20, '20 round box'),
'spare parts': (10, 'part')
}
supplies = {
'oxen': [0, 'yokes'],
'food': [0, 'lbs'],
'clothing': [0, 'sets'],
'ammunition': [0, 'boxes'],
'spare parts': [0, 'parts']
}
end_money = self.bank
print('Welcome to the GENERAL STORE!\n\nInventory:\n----------')
for i in store: # prints the store's inventory
print('+ {}'.format(i.capitalize()))
print("Press 'e' to exit the store\n")
while end_money >= 0:
print('You have ${} to spend.'.format(end_money))
buy = input('What supplies would you like to buy? ').lower()
if buy in store:
purchase = int(input(
'\n{} costs {} dollars per {}.\nYou currently have {}.\nEnter the amount you wish to buy: '.format(
buy,store[buy][0],store[buy][1],supplies[buy][0])))
if (purchase * store[buy][0]) <= end_money:
print('\nSuccess!')
supplies[buy][0] = purchase # adds purchase to user's supplies dict
total = 0
for each in supplies: # for loop recalculates how much money is left
total += supplies[each][0] * store[each][0]
end_money = self.bank - total
else:
print("\nSorry, you don't have enough money.\n")
elif buy.lower() == 'e':
print('\nThanks for shopping at the GENERAL STORE!\nRemaining cash: ${}\nSupplies:'.format(
end_money)) # prints how much money is left
for i in supplies: # iterates over and prints each item in the user's inventory
print('{} - {} {}'.format(i.capitalize(), supplies[i][0], supplies[i][1]))
return supplies, end_money
def river_cross(self):
''' This function determines whether crossing a river is a success or not.'''
seed(42)
choices = ['1','2','3']
depth=(random.randint(2,10))
width=(random.randint(100,300))
chance=(width*depth/3000*100)
success=(random.randint(1,100))
print('''The river is {} feet deep at its
deepest point, and {} feet accross.
You have a {}% chance of crossing successfully.'''.format(depth,width,success))
choice = input('''You must choose how to cross:
1. Attempt to ford the river.
2. Caulk the wagon and float it accross.
3. Wait to see if conditions improve.
What is your choice?\n''')
while choice not in choices:
print('\nPlease choose 1, 2, or 3.\n')
choice = input()
if choice == '1':
print('\nYou attempt to ford the river...\n')
if (success) <= (chance):
print('\nYou have successfully navigated the river without incident!\n')
return True
else:
print('\nYour river crossing was not a success.\n')
return False
elif choice == '2':
# day = day +1
print('\nYou spend a day caulking the wagon and attempt to float accross...\n')
(success)=((success)*2)
if (success) <= (chance):
print('\nYou are able to float accross the river safely.\n')
return True
else:
print('\nYour river crossing was not a success\n')
return False
elif choice == '3':
# day = day +1
print('\nYou wait a day to see if conditions improve.\n')
return self.river_cross()
def animal_generator():
check_out = input("Something is rustling in the bushes. Would you like to go check it out? (y/n) ")
if check_out == "y":
animal = randint(1,4)
if animal == 1:
return shoot_decision("squirrel")
elif animal == 2:
return shoot_decision("rabbit")
elif animal == 3:
return shoot_decision("deer")
else:
return shoot_decision("bear")
else:
print("You've decided to continue down the road.")
#Animal is killed, attacks, or is missed
def shoot_decision(animal):
decision = input(("A {} jumps out! Would you like to shoot the {}? (y/n) ").format(animal, animal))
if decision == "y":
result = randint(1,3)
if result == 1:
food(animal)
elif result == 2:
print(("The {} ran away.").format(animal))
bullets_wasted = randint(1,3)
inventory['bullets'] -= bullets_wasted
if bullets_wasted == 1:
print("You've wasted 1 bullet.")
else:
print(("You've wasted {} bullets.").format(bullets_wasted))
else:
attack(animal)
else:
print(("You've decided to spare the {}'s life.").format(animal))
#Animal is killed
def food(animal):
statement = ("You have killed the {}.").format(animal)
print(statement)
if animal == "squirrel":
print("You've received 1 pound of food!")
inventory['food'] += 1
elif animal == "rabbit":
print("You've received 5 pounds of food!")
inventory['food'] += 5
elif animal == "deer":
print("You've received 80 pounds of food!")
inventory['food'] += 80
else:
print("You've received 800 pounds of food!")
inventory['food'] += 800
bullets_wasted = randint(1,3)
inventory['bullets'] -= bullets_wasted
if bullets_wasted == 1:
print("You used 1 bullet.")
else:
print(("You used {} bullets.").format(bullets_wasted))
#Animal Attacks
def attack(animal):
statement = ("You have been attacked by the {}!").format(animal)
print(statement)
if animal == "squirrel":
print("You've lost 1 point of health!")
player['health'] += 1
elif animal == "rabbit":
print("You've lost 5 points of health!")
player['health'] += 5
elif animal == "deer":
print("You've lost 80 points of health!")
player['health'] += 80
else:
print("You've lost 800 points of health!")
player['health'] += 800
if __name__ == "__main__":
x = OTGame()
# intro()
# player_name()
# going()
# role, bank = characters()
# shop()
# river_cross()
# animal_generator() |
"""Create a program that will play the “cows and bulls” game with the user. The game works like this:
Randomly generate a 4-digit number. Ask the user to guess a 4-digit number.
For every digit that the user guessed correctly in the correct place, they have a “cow”.
For every digit the user guessed correctly in the wrong place is a “bull.”
Every time the user makes a guess, tell them how many “cows” and “bulls” they have.
Once the user guesses the correct number, the game is over.
source - http://www.practicepython.org/exercise/2014/07/05/18-cows-and-bulls.html"""
import random
def cows_bulls():
guesses = 0
number_list = (str(random.randint(0,9999)).zfill(4))
print number_list
while True:
user_input = str(raw_input("Enter a 4 digit number: "))
bulls = []
cows = []
guesses += 1
if user_input[0] == number_list[0]:
bulls.append(number_list[0])
elif number_list[0] in user_input:
cows.append(number_list[0])
if user_input[1] == number_list[1]:
bulls.append(number_list[1])
elif number_list[1] in user_input:
cows.append(number_list[1])
if user_input[2] == number_list[2]:
bulls.append(number_list[2])
elif number_list[2] in user_input:
cows.append(number_list[2])
if user_input[3] == number_list[3]:
bulls.append(number_list[3])
elif number_list[3] in user_input:
cows.append(number_list[3])
if number_list == user_input:
print 'you have %d bulls and %d cows using %d guesses' % (len(bulls), len(cows), guesses)
break
print 'you have %d bulls and %d cows' % (len(bulls), len(cows))
if __name__ == "__main__":
print(cows_bulls())
|
"""This program gets the bitcoin value from worldcoinindex.com using beautfiulsoup library
and performs profit/loss calculations with it based on user's 2 personal investments at different btc rates
using smtplib it sends different content email notificationsto user that vary depending on the high/low profit levels
using twilio client it sends similar text messages to user that vary based on the same levels """
# SMTP is simple mail transfer protocol, used for sending email
import smtplib
import requests
from bs4 import BeautifulSoup
from twilio.rest import Client
import schedule
import time
def BitcoinPrice():
base_url = 'https://www.worldcoinindex.com/coin/bitcoin'
r = requests.get(base_url)
soup = BeautifulSoup(r.text, 'lxml')
# extracts all info from selected div, gets just the text and splits it into a list of items
# in this case it's [u'$', u'16,855.84']
current_price = soup.find('div',{'class': 'col-md-6 col-xs-6 coinprice'}).get_text().split()
# isolates just the number part and replace comma to a dot so it fits the float form
btc_price = current_price[1].replace(',','.')
# gets rid of the last 3 charachters, which are cents and a dot
# converts number to float
btc_price = float(btc_price[:-3])
profit_loss(btc_price)
def profit_loss(btc_price):
buyin1 = 0.22853543
btc_rate1 = 10.778
money_spent1 = (buyin1 * btc_rate1) * 1000
revenue1 = (btc_price * buyin1) * 1000
profit_loss1 = revenue1 - money_spent1
buyin2 = 0.17042113
btc_rate2 = 14.454
money_spent2 = (buyin2 * btc_rate2) * 1000
revenue2 = (btc_price * buyin2) * 1000
profit_loss2 = revenue2 - money_spent2
overall_profit_loss = (profit_loss1 + profit_loss2)
print "The current bitcoin price is $%.3f\n" % btc_price
print "Net profit/loss from buyin 1 is $%.2f - bought at %r\n" % (profit_loss1, btc_rate1)
print "Net profit/loss from buyin 2 is $%.2f - bought at %r\n" % (profit_loss2, btc_rate2)
print "Your overall profit/loss is $%.3f" % overall_profit_loss
if overall_profit_loss < 100:
email_notification(2, btc_price)
sms_notification(2, btc_price)
elif overall_profit_loss < 500:
email_notification(1, btc_price)
sms_notification(1, btc_price)
elif overall_profit_loss < 1000:
email_notification(0, btc_price)
sms_notification(0, btc_price)
def email_notification (value, btc_price):
# the SMTP object represents a connection to an SMTP mail server and has
# methods for sending email. This creates an SMTP object for connecting to gmail
# Domain name will be different for each provider
# port number will most always be 587
smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
# important step (method) to establish 'say hello' a connection to the email server
# example returns '250, b'mx.google.com at your service, etc.'
smtpObj.ehlo()
# this required step enables encryption for your connection, it returns
# (220, '2.0.0 Ready to start TLS') 220 in the return value means that the server is ready
smtpObj.starttls()
# login with your username and password by using the login() method
# returns (235, '2.7.0 Accepted') 235 means successful authentication
smtpObj.login('p.vengrinovich@gmail.com', 'Ecology9')
# after logging in to the SMTP server we can use sendmail() method to actually send the email
# first agument is my email address (from), second is the recepeints, third is the email subject and body body
# sends out different emails depending on the value of profit/loss
if value == 1:
smtpObj.sendmail('p.vengrinovich@gmail.com', 'p.vengrinovich@gmail.com', 'Subject: Bitcoin profit Less then $500 \nThe price is at $'+ str(btc_price))
if value == 2:
smtpObj.sendmail('p.vengrinovich@gmail.com', 'p.vengrinovich@gmail.com', 'Subject: Bitcoin profit Less then $100 \nThe price is at $'+ str(btc_price))
if value == 0:
smtpObj.sendmail('p.vengrinovich@gmail.com', 'p.vengrinovich@gmail.com', 'Subject: Bitcoin profit Less then $1000 \nThe price is at $'+ str(btc_price))
# always disconnect your program from the SMTP server when done sending emails
smtpObj.quit()
def sms_notification (value, btc_price):
# these are taken directly from twilio account
accountSID = 'take this from twilio, cant disclose here - sensitive information'
authToken = 'take this from twilio, cant disclose here - sensitive information'
myTwilioNumber = 'dont disclose number on the web'
myCellPhone = 'dont disclose number on the web'
# the call to the Client returns a Twilio Client object
twilio_client_object = Client(accountSID, authToken)
# This object has a messages attribute which in turn has a create method
# you can use to send text messages;
# sends different text messages with 'body' as the message depending on the value of profit
if value == 0:
message = twilio_client_object.messages.create(body = 'Bitcoin profit is less then a $1000 at $'+ str(btc_price),
from_ = myTwilioNumber, to = myCellPhone)
if value == 1:
message = twilio_client_object.messages.create(body = 'Its happening: bitcoin profit is less then a $500 at $'+ str(btc_price),
from_ = myTwilioNumber, to = myCellPhone)
if value == 2:
message = twilio_client_object.messages.create(body = 'Danger!!! Bitcoin profit is less then a $100 at $'+ str(btc_price),
from_ = myTwilioNumber, to = myCellPhone)
# main function is to make importing the code later easier into other programs
# schedule uses the schedule module to run this script every hour
if __name__ == "__main__":
schedule.every(60).minutes.do(BitcoinPrice)
BitcoinPrice()
while True:
schedule.run_pending()
|
import json
import datetime
# gets the json data from dict and loads into variable birthday, then passes this on to function birthday_date
def dictionary():
birthday = {}
with open('dict.json', 'r') as openfile_object:
birthday = json.load(openfile_object)
months(birthday)
def months(birthday):
dates = str(birthday.values()) #extracts the dates from dictionary
date_module = datetime.datetime.strptime(dates,'%m-%d-%Y')
dictionary()
|
"""Make a two-player Rock-Paper-Scissors game."""
import random
words = ['rock', 'paper', 'scissors']
def function():
while True:
word = random.choice(words)
input = raw_input("Pick rock, paper, or scissors:")
print "the computer picked %s" % word
if input == 'rock' and word == 'scissors':
print "You won, would you like to play again?"
new_input = raw_input("Yes or No:")
if new_input == 'yes':
return function()
else:
break
elif input == 'scissors' and word == 'paper':
print "You won, would you like to play again?"
new_input = raw_input("Yes or No:")
if new_input == 'yes':
return function()
else:
break
elif input == 'paper' and word == 'rock':
print "You won, would you like to play again?"
new_input = raw_input("Yes or No:")
if new_input == 'yes':
return function()
else:
break
elif input == word:
print "It's a draw, would you like to play again?"
new_input = raw_input("Yes or No:")
if new_input == 'yes':
return function()
else:
break
elif input != 'rock' and input != 'paper' and input != 'scissors':
print "This is not an appropriate value, pick again"
return function()
else:
print "You lost, would you like to play again?"
new_input = raw_input("Yes or No:")
if new_input == 'yes':
return function()
else:
break
function()
|
'''
In order to win the senate, the Republicans will have to win 21 of the 36 races
this November.
What is the probability they will win 21 of these races?
Created on Sep 28, 2014
@author: adrian
'''
# QSTK Imports
# Third Party Imports
import pandas as pd
import numpy as np
import random as rn
from scipy.stats import norm
import matplotlib.pyplot as plt
print "Pandas Version", pd.__version__
print "NumPy Version", np.__version__
def plot_results(results):
plt.hist(results, bins = (np.amax(results) - np.amin(results)), normed = True)
plt.title('Election Results')
plt.xlabel('Margin')
plt.ylabel('Probability')
plt.show()
def main():
''' Main Function'''
# Reading the poll results
na_senate = np.loadtxt('senate.csv', dtype='S20,f4, f4',
delimiter=',', comments="#", skiprows=1)
print na_senate
# Sorting the poll results by state
na_senate = sorted(na_senate, key=lambda x: x[0])
print na_senate
# Create lists for each race:
# race name, republican advantage, margin of error
ls_race_name = []
lf_rep_margin = []
lf_err = []
for race_poll in na_senate:
ls_race_name.append(race_poll[0])
lf_rep_margin.append(race_poll[1])
lf_err.append(race_poll[2])
# simulate the election a large number of times
# and count how many times the total of republican victories in the
# simulated races has reached or surpassed the required number of victories
# to win majority in the senate
n = 10000
i_rep_sen = 0
i_req_number = 21
li_sim_result = []
for rep in range(n):
# init a counter to tally total republican victories in the simulated election
i_rep_vic = 0
for s_race_name in ls_race_name:
i_index = ls_race_name.index(s_race_name)
f_rep_adv = lf_rep_margin[i_index]
f_err = lf_err[i_index]
if rn.gauss(f_rep_adv, f_err/1.96) > 0.0:
i_rep_vic += 1
# debug
print "repetition = ", rep, " -- victories = ", i_rep_vic
print ""
# store result for each repetition of the simulation
li_sim_result.append(i_rep_vic)
# count if republican achieved majority in senate
if i_rep_vic >= i_req_number:
i_rep_sen += 1
# estimate the parameters of distribution of the simulation results
x = np.array(li_sim_result)
f_mu = x.mean()
f_sigma = x.std()
print "mu=", f_mu, " -- sigma=", f_sigma
# print the result
f_prob = 1 - norm(f_mu, f_sigma).pdf(i_req_number)
print "Probability of republicans winning the senate = ", f_prob
plot_results(li_sim_result)
if __name__ == '__main__':
main()
|
def primeCheck(sentPrime):
for i in range(3,int(sentPrime**0.5)+1,2):
if sentPrime%i == 0:
return False
return True
def main():
count = 4 # Start count one step back due to location of +=
prime = 11 # Start 5th prime due to lower primes' problems with above
while count < 10002:
if primeCheck(prime) is True:
count += 1
if count == 10001:
print(prime)
return
else:
prime += 2
else:
prime += 2
main()
|
""" def prime-factorization(n):
for i < 2 to sqrt(n)
if n%i == 0
ct < 0
while(n%i == 0)
n = n/i
ct++
Print(i, ct)
if(n! = 1)
Print(n, 1)
"""
def generate_prime_factors(argnumber):
""" Returns prime factors that compose argnumber """
if type(argnumber) != int:
raise ValueError
else:
if argnumber == 0:
return []
if argnumber == 1:
return []
n = argnumber
b = []
while n % 2 == 0:
b.append(2)
n /= 2
while n % 3 == 0:
b.append(3)
n /= 3
i = 5
inc = 2
while i*i <= n:
while n % i == 0:
b.append(i)
n /= i
i += inc
inc = 6-inc
if n != 1:
b.append(n)
return b
|
import matplotlib.pyplot as plt
input_values = [1,2,3,4,5]
squares = [1,4,9,16,25]
plt.plot(input_values,squares,linewidth=5)
# 设置图标标题, 并给坐标轴加上标签
plt.title("Square Number",fontsize = 14)
plt.xlabel("value",fontsize = 13)
plt.ylabel("Square of value",fontsize =14)
# 设置刻度标记大小
plt.tick_params(axis = 'both',labelsize = 14)
plt.show() |
my_list = [232,32,1,4,55,4,3,32,3,24,5,5,5,34,2,35,5365743,52,34,3,55]
#Your code go here:
for each_item in my_list:
print(each_item) |
#!/usr/bin/python3
# coding: utf-8
# 上面两句注释必须要,防止无法打印中文的
import time
import datetime
import os
word=['hot']
dic=['doh', 'got' , 'dot' , 'god' , 'tod' , 'dog' , 'lot' , 'log']
w = ['hot']
dic = ['doh', 'got', 'dot', 'god', 'tod', 'dog', 'lot', 'log']
def result(n,m,li):
length=len(li)
i=n-2
j=n-1
while j>0:
sum1=li[j]
while i>=0:
if (li[i]+sum1)>m :
i-=1
elif (li[i]+sum1)==m:
return 'prefect'
else:
sum1+=li[i]
i-=1
j-=1
print(sum1)
return 'good'
def main():
n = 5 #int(input())
m=140
# li=[100 ,30, 20 ,110 ,120]
li=[10 ,70, 20 ,90 ,50]
# li=[10 ,30, 20 ,40 ,50]
li.sort()
print(li )
res=result(n,m,li)
print(res)
if __name__ == '__main__':
main() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.