text stringlengths 37 1.41M |
|---|
import numpy as np
A = np.arange(3,15).reshape(3,4)
print(A)
print(A[2])
print(A[2][1])
print(A[:,1])
print(A[1,1:2])
print(A.T)
for row in A:
print(row)
for column in A.T:
print(column)
print(A.flatten())
for item in A.flat:
print(item)
A = np.array([1,1,1])
B = np.array([2,2,2])
C = np.vstack((A,B)) # vertical stack
D = np.hstack((A,B)) # horizontal stack
print(C)
print(A.shape,D.shape)
A = np.array([1,1,1])[:,np.newaxis]
B = np.array([2,2,2])[:,np.newaxis]
C = np.concatenate((A,B,B,A),axis=1)
print(C)
|
from collections import OrderedDict
class Dog():
""" Description of the class"""
def __init__(self, name, age):
self.name = name #any variable with the predix self is available to every method in the class
self.age = age
self.gender = "male"
def sit(self):
"""simulate a puppy sitting"""
print(self.name.title() + " is now sitting.")
def get_gender(self):
print(self.name.title() + "'s gender is " + self.gender)
my_dog = Dog("Buddy", 13)
my_dog.sit()
my_dog.get_gender()
class SamoyedDog(Dog): #as you create a child class, the parent class must be part of the current file and must appear before the child class in the file
def __init__(self, name, age):
super().__init__(name, age)
self.fuzziness = "high"
def get_fuziness(self):
print(self.name + " has a " + self.fuzziness + " fuziness level.")
my_samoyed_dog = SamoyedDog("Buddy the Bear", 13)
my_samoyed_dog.sit()
my_samoyed_dog.get_fuziness()
fav_lang = OrderedDict()
fav_lang['Mike'] = "English"
fav_lang['Katie'] = "Chinese"
for name, language in fav_lang.items():
print(name.title() + "'s fav language is " + language.title()) |
print ("How old are you?"),
age = int(input())
print ("How tall are you?"),
height = input()
print ("How much do you weight?"),
weight = input()
print ("so you are {} old, {} tall, and {} heavy".format(age, height, weight))
exit() |
from NodoMatriz2 import matriz2
class listaenlazada2:
def __init__ (self):
self.cabeza=None
def insertar(self,m,n,nombre,p,Filas2):
nuevo=matriz2(m,n,nombre,p,Filas2)
if self.cabeza is None:
self.cabeza=nuevo
else:
tmp=self.cabeza
while tmp.siguiente is not None:
tmp = tmp.siguiente
tmp.siguiente=nuevo
def Mostrar2(self):
tmp=self.cabeza
while tmp is not None:
print("M: "+tmp.m+"N: "+tmp.n+"Nombre: "+tmp.nombre+"p: "+tmp.p)
tmp=tmp.siguiente |
import random
def rng(a,b):
ran = random.randint(a,b)
return ran
def montyalways():
if selection == prize:
return False
else:
return True
def montynever():
if selection == prize:
return True
else:
return False
games = input("Number of games to play: ")
try:
int(games)
except:
print("Please enter a positive integer")
quit()
gamesplayed = int(games)
g= gamesplayed - 1
countalways = 0
countnever = 0
for i in range(0,g,1):
prize=rng(1,3)
selection=rng(1,3)
win = montyalways()
if win==True:
countalways = countalways + 1
for i in range(0,g,1):
prize=rng(1,3)
selection=rng(1,3)
win = montynever()
if win==True:
countnever = countnever + 1
percentagealways= countalways / gamesplayed
percentagenever = countnever / gamesplayed
print("Out of %d games: " % (gamesplayed))
print("Always switching wins: %9.7f (%d games) " % (percentagealways, gamesplayed))
print("Never switching wins: %9.7f (%d games) " % (percentagenever, gamesplayed))
|
#import statistics module to use function to solve for standard deviation
import statistics
#define functions for all equations in program: standard deviation, average, max difference, and min difference
def stddev(s):
return statistics.stdev(s)
def average(s):
return sum(s) / len(s)
def maxdif(a,b):
if max(a) > max(b):
return max(a) - max(b)
else:
return max(b) - max(a)
def mindif(a,b):
if min(a) > min(b):
return min(a) - min(b)
else:
return min(b) - min(a)
#identify the file and open it
name = "data_hw_3.txt"
handle = open(name)
#create two lists that will be populated later with values from the file
inspired=list()
expired=list()
#for loop to read from each line in file and organize it
for line in handle:
#rstrip function gets rid of the spaces
line = line.rstrip()
#split up into 3 strings on each line and add them to lst
lst = line.split()
#for loop for the 3 strings on each line
for word in lst:
#if it's the second string on each line, add that string to the list inspired
if word == lst[1]:
inspired.append(int(lst[1]))
#if it's the last string on each line, add that string to the list expired
if word == lst[2]:
expired.append(int(lst[2]))
#print statements that calls the 4 define functions to solve for everything
print("Average volume of air inspired is %6.2f ml with a standard deviation of%6.2f" % (average(inspired),stddev(inspired)))
print("Average volume of air expired is %6.2f ml with a standard deviation of%6.2f" % (average(expired),stddev(expired)))
print("The maximum difference between air inspired and expired is %d" % (maxdif(inspired,expired)))
print("The minimum difference between air inspired and expired is %d" % (mindif(inspired,expired)))
|
name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
names=dict()
for line in handle:
if not line.startswith("From:"): continue
line = line.rstrip()
word= line.split()
addy=word[1]
names[addy] = names.get(addy,0)+1
largest=-1
theword=None
for a,b in names.items():
if b>largest:
largest = b
theword = a
print(theword,largest)
|
import tkinter as tk
import tk_tools
import random
import string
def random_letters():
sal = string.ascii_letters
return (random.choice(sal)
+ random.choice(sal)
+ random.choice(sal))
def add_row_random():
r1 = random_letters()
r2 = random_letters()
r3 = random_letters()
button_grid.add_row(
[
(r1, lambda: print(r1)),
(r2, lambda: print(r2)),
(r3, lambda: print(r3))
]
)
def remove_row():
button_grid.remove_row()
if __name__ == '__main__':
root = tk.Tk()
button_grid = tk_tools.ButtonGrid(root, 3, ['Column0', 'Column1', 'Column2'])
button_grid.grid(row=0, column=0)
add_row_btn2 = tk.Button(text='Add button row (random text)',
command=add_row_random)
add_row_btn2.grid(row=1, column=0, sticky='EW')
rm_row_btn = tk.Button(text='Remove button row', command=remove_row)
rm_row_btn.grid(row=2, column=0, sticky='EW')
root.mainloop()
|
import tkinter as tk
class ToolTip(object):
"""
Add a tooltip to any widget.::
entry = tk.Entry(root)
entry.grid()
# createst a tooltip
tk_tools.ToolTip(entry, 'enter a value between 1 and 10')
:param widget: the widget on which to hover
:param text: the text to display
:param time: the time to display the text, in milliseconds
"""
def __init__(self, widget, text: str = "widget info", time: int = 4000):
self._widget = widget
self._text = text
self._time = time
self._widget.bind("<Enter>", lambda _: self._widget.after(500, self._enter()))
self._widget.bind("<Leave>", self._close)
self._tw = None
def _enter(self, event=None):
x, y, cx, cy = self._widget.bbox("insert")
x += self._widget.winfo_rootx() + 25
y += self._widget.winfo_rooty() + 20
# creates a toplevel window
self._tw = tk.Toplevel(self._widget)
# Leaves only the label and removes the app window
self._tw.wm_overrideredirect(True)
self._tw.wm_geometry("+%d+%d" % (x, y))
label = tk.Label(
self._tw,
text=self._text,
justify="left",
background="#FFFFDD",
relief="solid",
borderwidth=1,
font=("times", "8", "normal"),
)
label.pack(ipadx=1)
if self._time:
self._tw.after(self._time, self._tw.destroy)
def _close(self, event=None):
if self._tw:
self._tw.destroy()
|
from . import Solver
from . import Digits_extractor
import sys
def main():
try:
file = sys.argv[1]
except Exception:
raise Exception("A file name is needed !")
if file == "--help":
print("""Usage: Solve.py filename outputname(optionnal)
filename is required
outputname is just a name without file extension, if blank the files will be named 'sudokusolution'""")
return
else:
sudoku = Digits_extractor.get_board(file)
try:
output = sys.argv[2]
Solver.solve_sudoku(sudoku, output)
except Exception :
Solver.solve_sudoku(sudoku)
#def solve(file, output="sudokusolution"):
# sudoku = get_board(file)
# solve_sudoku(sudoku, output)
main() |
print "que numero es mayor que el otro"
print "introduce el primer numero"
primero = int(raw_input())
print "introduce el segundo numero"
segundo = int(raw_input())
if primero>segundo:
primero ,"es mayor que", segundo
else:
segundo ,"es mayor que", primero
|
import numpy as np
import cv2 as cv
import sys
# Returns the coordinates of the points where the meniscus intersects with the tongue.
# The user selects the points from the inputted video (array of images)
# The inputted video must be a numpy array and can be black and white or color
def get_meniscus(selected_frames, selected_color):
# selected_frames = np.load('./data_output/selected_frames.npy')
meniscus_coords = []
frame_num = 0
magnification = 1
is_color = False
total_frames = np.shape(selected_frames)[0]
print()
print('===================')
print('You will now select the point at which the tongue intersects with the meniscus')
print(f'There are {total_frames} images to select')
print()
while frame_num < total_frames:
print(f'{frame_num + 1}/{total_frames}')
print("Click the point at which the tongue intersects with the meniscus, then")
print("Press 'SPACE' to continue, 'R' to redo, 'Q' to quit ")
print("Press '+' to zoom in. Press '-' to zoom out")
if not is_color:
frame = selected_frames[frame_num, :, :]
else:
frame = selected_color[frame_num, :, :]
coords, magnification, is_color = select_intersection(frame, magnification, is_color)
print(coords)
if coords != -1:
meniscus_coords.append(coords)
frame_num += 1
meniscus_coords = np.asarray(meniscus_coords)
return meniscus_coords
# Returns the coordinates of a user's first click. Also draws a circle under the clicked point
# so the user can assess whether they want to redo or continue.
# Takes an image as input, along with user mouse and keyboard input
# If the user doesn't click, or wants to redo ('R'), the function returns -1
# If the user presses Q or ESC, the program closes.
# If the user clicks and presses SPACE, the coordinates are returned as tuples (x, y)
def select_intersection(frame, magnification, is_color):
class CoordinateStore:
def __init__(self, magnification):
self.points = -1
self.clicked = False
self.magnification = magnification
def select_point(self, event, x, y, flags, param):
if event == cv.EVENT_LBUTTONDOWN and not self.clicked:
cv.circle(img, (x, y), 3, (0, 120, 0), -1)
self.points = (int(x / self.magnification), int(y / self.magnification))
self.clicked = True
def zoom_in(self):
self.magnification += 1
def zoom_out(self):
if self.magnification > 1:
self.magnification -= 1
# instantiate class
coordinateStore1 = CoordinateStore(magnification)
# Creates a copy of the image so the array isn't changed
img = frame.copy()
if not is_color:
img = cv.cvtColor(img, cv.COLOR_GRAY2BGR)
cv.namedWindow('image')
cv.setMouseCallback('image', coordinateStore1.select_point)
y_dim, x_dim, px_value = np.asarray(np.shape(img))
while True:
magnification = coordinateStore1.magnification
dim = (x_dim * magnification, y_dim * magnification)
img = cv.resize(img, dim, interpolation=cv.INTER_NEAREST)
cv.imshow('image', img)
k = cv.waitKey(20) & 0xFF
if k == 27 or k == ord("q"): # ESC or Q
cv.destroyAllWindows()
sys.exit(-1)
elif k == 32: # SPACE
cv.destroyAllWindows()
return coordinateStore1.points, magnification, is_color
elif k == ord('r'): # R
cv.destroyAllWindows()
return -1, magnification, is_color
elif k == ord('s'):
cv.destroyAllWindows()
return -1, magnification, not is_color
elif k == ord('='):
coordinateStore1.zoom_in()
elif (k == ord("-")) and coordinateStore1.magnification > 1:
coordinateStore1.zoom_out()
if __name__ == '__main__':
main()
|
def countPos(l):
pos = 0
for e in l:
if e>0:
pos+=1
return pos
'''
Returns the number of elements of the list l that are positive.
>>> countPos([1, -4, 0, 4, 8, 0])
3
'''
def dotProduct(v1, v2):
summand = 0
while v1 != [] and v2!= []:
summand += v1[0]*v2[0]
v1 = v1[1:]
v2 = v2[1:]
return summand
'''
Computes the dot product of the vectors v1 and v2, each of which is a list
of numbers. The dot product of [x1,...,xn] and [y1,...,yn] is
x1*y1 + ... + xn*yn. You may assume that v1 and v2 have the same length.
>>> dotProduct([1,2,3],[4,5,6])
32
'''
def partition(v, l):
accumV= []
remainder = []
for e in l:
if e == v:
accumV+=[v]
else:
remainder+=[e]
l=l[1:]
return [accumV]+[remainder]
'''
Partitions the list l into a list of elements that are equal to the value v
and a list of all other elements. Note that the result of partition should
always be a list that contains exactly two lists.
>>> partition(2, [1,5,3,2,2,1,3,2])
[[2, 2, 2], [1, 5, 3, 1, 3]].
'''
return
def toDigitList(n):
if n==0:
return [0]
baseList = []
while n > 0:
answer = n%10
n= n//10
baseList= [answer] + baseList
return baseList
'''
Converts a given nonnegative integer n to a list of digits.
>>> toDigitList(403)
[4, 0, 3]
'''
def digitalRootAndPersistence(n):
count=0
while n>=10:
numList = toDigitList(n)
n = sum(numList)
count+=1
return (n,count)
'''
Consider the process of taking a nonnegative integer n, summing its digits, then
summing the digits of the number derived from it, etc., until the remaining
number has only one digit. The digit obtained is called the *digital root* of
n, and the number of sums required to obtain a single digit from a number n is
called the *additive persistence* of n.
For example, 9879 has a digital root of 6 since 9+8+7+9 = 33 and 3+3 = 6. Since
two numbers were summed in this process, the additive persistence of 9879 is 2.
This function takes a nonnegative integer n and returns a pair of its digital
root and its additive persistence, represented as a list of two numbers.
>>> digitalRootAndPersistence(9879)
[6, 2]
NOTE: You may use Python's built-in sum function, which sums the elements of
a list of numbers, and the toDigitList function you defined above will also be
useful.
'''
def merge(l1, l2):
base_list = []
while l1 != [] or l2!= []:
if l1 != [] and l2 !=[]:
if l1[0] < l2[0]:
base_list = base_list + [l1[0]]
l1 = l1[1:]
else:
base_list = base_list + [l2[0]]
l2 = l2[1:]
elif l1 == [] and l2 != []:
base_list = base_list + [l2[0]]
l2 = l2[1:]
else :
base_list = base_list + [l1[0]]
l1 = l1[1:]
return base_list
"""
Accepts two integer lists l1 and l2, which are each assumed to be sorted from
least to greatest, and produces a new list that contains the elements of both
lists, also sorted from least to greatest. Note that duplicates are allowed,
both within and across lists.
>>> merge([1,2,4], [2,3,3,5])
[1, 2, 2, 3, 3, 4, 5]
NOTE: This function is trickier to implement using loops than you might expect.
Take care to ensure that all accesses to the lists l1 and l2 are in bounds!
"""
|
fib = open("2600-0.txt")
line = fib.read()
def rotate_pair():
for i in line:
word = line.strip()
b = word.sort()
c = 0
if b[i] == b[i+1]:
print(b)
c = c + 1
my_set = set(b)
print("Unique words are:", my_set)
|
#!/usr/local/bin/python
#
import RPi.GPIO as GPIO
import time
from time import sleep
GPIO.setmode(GPIO.BCM)
# Defines the number of times that the LED should flash when the calorie intake exceeds 100% of the daily recommended dosage.
cycles_for_cal100 = 3
# This function sets up the LED which serves to nudge the user towards a healthier diet, by telling him/her that
# he has eaten beyond a certain level of his daily recommended calorie intake
def flash_led(led_pin, threshold_num):
GPIO.setup(led_pin, GPIO.OUT)
# threshold 1 is when calorie intake is >75%; light up LED for 3 seconds
if threshold_num == 1:
GPIO.output(led_pin, GPIO.LOW)
time.sleep(3)
# threshold 2 is when calorie intake is >100%; flash LED 3 times
elif threshold_num == 2:
#print("100")
for i in range(cycles_for_cal100):
GPIO.output(led_pin, GPIO.LOW)
time.sleep(0.5)
GPIO.output(led_pin, GPIO.HIGH)
time.sleep(0.5)
|
class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
arr1=nums[0:len(nums)//2]
arr2=nums[len(nums)//2:len(nums)]
print(arr1)
print(arr2)
result=[]
for i in range(len(arr1)):
result.append(arr1[i])
result.append(arr2[i])
return result |
class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
result = []
def helper(number):
string = str(number)
for i in string:
if int(i) == 0:
return -1
if number % int(i) != 0:
return -1
return number
for i in range(left, right + 1):
if helper(i) == -1:
pass
else:
result.append(helper(i))
return result |
class Solution:
def reverse(self, x: int) -> int:
def reverse(num):
if num < 0:
num = str(num)[1::]
num = int(str(num)[::-1])
return -num
else:
num = int(str(num)[::-1])
return num
if (-2) ** 31 <= x <= (2 ** 31) - 1 and (-2) ** 31 <= reverse(x) <= (2 ** 31):
return reverse(x)
else:
return 0 |
import keras
from keras.models import Sequential
from keras.layers import Dense, Activation
# model = Sequential([
# Dense(32, input_dim=784),
# Activation('relu'),
# Dense(10),
# Activation('softmax'),
# ])
# For a single-input model with 10 classes (categorical classification):
model = Sequential()
model.add(Dense(32, activation='relu', input_dim=100))
model.add(Dense(10, activation='softmax'))
model.compile(optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['accuracy'])
# Generate dummy data
import numpy as np
data = np.random.random((1000, 100))
labels = np.random.randint(10, size=(1000, 1))
# Convert labels to categorical one-hot encoding
binary_labels = keras.utils.np_utils.to_categorical(labels, 10)
# Train the model, iterating on the data in batches of 32 samples
# model.fit(data, binary_labels, batch_size=32, epochs=10)
model.fit(data, binary_labels, batch_size=32, nb_epoch=1000) |
# My Name
# Prints my name to the screen
print ("Trent")
input("\n\nPress enter to continue")
|
import unittest
from models.location import Location
class TestLocation(unittest.TestCase):
def setUp(self):
self.spin_room = Location("spin room", 10)
self.tiny_room = Location("wee room", 3)
def test_room_id_is_none(self):
self.assertTrue(self.spin_room.id == None)
def test_room_has_name(self):
self.assertEqual("spin room", self.spin_room.room_name)
def test_room_has_capacity(self):
self.assertEqual(10, self.spin_room.capacity) |
import pandas as pd
pd.plotting.register_matplotlib_converters()
import matplotlib.pyplot as plt
import seaborn as sea
iris_data = pd.read_csv('../iris.csv', index_col="Id")
print(iris_data.head())
# Histogram
# sea.distplot(a=iris_data['Petal Length (cm)'], kde=False)
"""
a= chooses the column we'd like to plot
kde= if not set to False will create a different plot ( will fit a curve on top of it)
"""
# Density Plots
"""
Kernel Density Estimate
- smoothed histogram
- non parametric way to estimate the probability density function of a random variable
parameter: any measured quantity of a statistical population that summarises or describes the population
- ex) mean, standard deviation
probability density function (pdf): of a continuous random variable, is a function whose value at any given sample
or point in the sample space can be interpreted as providing a relative likelihood that the value of the random
variable would equal that sample
- since the absolute likelhood for continuous random variables to take on any particular value is 0, since
there are infinite set of possible values, the value of the PDF at two different samples can be used to infer
in any particular draw of the random variable how much more likely i is that the random variable would equal
one sample compared to the other sample.
- in a more precise sense, the PDF is used to specify the probability of the random variable falling within a particular range of values, as opposed to taking on any one value.
sample space: the set of possible values taken by the random variable
"""
# KDE Plot
# sea.kdeplot(data=iris_data['Petal Length (cm)'], shade=True)
# 2D KDE Plots
# sea.jointplot(x=iris_data['Petal Length (cm)'], y=iris_data['Sepal Width (cm)'], kind="kde")
iris_set_data = pd.read_csv('../iris_setosa.csv', index_col="Id")
iris_ver_data = pd.read_csv('../iris_versicolor.csv', index_col='Id')
iris_vir_data = pd.read_csv('../iris_virginica.csv', index_col='Id')
"""# Histograms for each species
sea.distplot(a=iris_set_data['Petal Length (cm)'], label="Iris-setosa", kde=False)
sea.distplot(a=iris_ver_data['Petal Length (cm)'], label="Iris-versicolor", kde=False)
sea.distplot(a=iris_vir_data['Petal Length (cm)'], label="Iris-virginica", kde=False)
# Add title
plt.title("Histogram of Petal Lengths, by Species")
# Force legend to appear
plt.legend()"""
# KDE plots for each species
sea.kdeplot(data=iris_set_data['Petal Length (cm)'], label="Iris-setosa", shade=True)
sea.kdeplot(data=iris_ver_data['Petal Length (cm)'], label="Iris-versicolor", shade=True)
sea.kdeplot(data=iris_vir_data['Petal Length (cm)'], label="Iris-virginica", shade=True)
# Add title
plt.title("Distribution of Petal Lengths, by Species")
plt.legend()
plt.show()
# Exercises
"""
1.
Load the data file corresponding to benign tumors into a DataFrame called cancer_b_data. The corresponding filepath is cancer_b_filepath. Use the "Id" column to label the rows.
Load the data file corresponding to malignant tumors into a DataFrame called cancer_m_data. The corresponding filepath is cancer_m_filepath. Use the "Id" column to label the rows.
# Paths of the files to read
cancer_b_filepath = "../input/cancer_b.csv"
cancer_m_filepath = "../input/cancer_m.csv"
# Fill in the line below to read the (benign) file into a variable cancer_b_data
cancer_b_data = pd.read_csv(filepath_or_buffer=cancer_b_filepath, index_col='Id')
# Fill in the line below to read the (malignant) file into a variable cancer_m_data
cancer_m_data = pd.read_csv(filepath_or_buffer=cancer_m_filepath, index_col='Id')
"""
"""
2.
Use a Python command to print the first 5 rows of the data for benign tumors.
cancer_b_data.head()
Use a Python command to print the first 5 rows of the data for malignant tumors.
cancer_m_data.head()
# Fill in the line below: In the first five rows of the data for benign tumors, what is the
# largest value for 'Perimeter (mean)'?
max_perim = 87.46
# Fill in the line below: What is the value for 'Radius (mean)' for the tumor with Id 842517?
mean_radius = 20.57
"""
"""
3.
Part A
Use the code cell below to create two histograms that show the distribution in values for 'Area (mean)' for both benign and malignant tumors. (To permit easy comparison, create a single figure containing both histograms in the code cell below.)
sns.distplot(a=cancer_b_data['Area (mean)'], label="Benign", kde=False)
sns.distplot(a=cancer_m_data['Area (mean)'], label="Malignant", kde=False)
plt.legend()
Part B
A researcher approaches you for help with identifying how the 'Area (mean)' column can be used to understand the difference between benign and malignant tumors. Based on the histograms above,
Do malignant tumors have higher or lower values for 'Area (mean)' (relative to benign tumors), on average?
Which tumor type seems to have a larger range of potential values?
Malignant tumors have higher values for Area on average and a larger range of potential values
"""
"""
4.
Part A
Use the code cell below to create two KDE plots that show the distribution in values for 'Radius (worst)' for both benign and malignant tumors. (To permit easy comparison, create a single figure containing both KDE plots in the code cell below.)
sns.kdeplot(data=cancer_b_data['Radius (worst)'], shade=True, label="Benign")
sns.kdeplot(data=cancer_m_data['Radius (worst)'], shade=True, label="Malignant")
Part B
A hospital has recently started using an algorithm that can diagnose tumors with high accuracy. Given a tumor with a value for 'Radius (worst)' of 25, do you think the algorithm is more likely to classify the tumor as benign or malignant?
Malignant becuase the curve is higher than benign around the values of 25
""" |
import pandas as pd
"""
- dtype shorthand for data type
- dtype(object) returns the data type
- can use dtype to grab the specific type of column
"""
reviews = pd.read_csv('../winemag-data-130k-v2.csv', index_col=0)
print(reviews.price.dtype)
print("------------")
print()
# can also get the data types for every column
print(reviews.dtypes)
print("------------")
print()
# you can convert the data type of one column into another type
reviews.points.astype('float64')
"""
- pandas also supports more data types such as categorical, timeseries, etc
"""
# Missing Data
"""
- Entries missing values are given Nan
- remember pd.isnull() or pd.notnull()
"""
print(reviews[pd.isnull(reviews.country)])
print("------------")
print()
"""
- replacing missing values is a common operation
- fillna()
"""
print(reviews.region_2.fillna("Unknown"))
print("-----------------")
print()
"""
- alternatively, you may have a non-null value that we would like to replace.
- example
- changing twitter handles
- replace()
"""
print(reviews.taster_twitter_handle.replace("@kerinokeefe", "@kerino"))
print("-----------------")
print()
# Exercise
"""
1.
What is the data type of the points column in the dataset?
"""
dtype = reviews.points.dtype
"""
2.
Create a Series from entries in the points column, but convert the entries to strings. Hint: strings are str in native Python.
"""
point_strings = reviews.points.astype('str')
"""
3.
Sometimes the price column is null. How many reviews in the dataset are missing a price?
"""
n_missing_prices = reviews.price.isnull().sum()
"""
4.
What are the most common wine-producing regions? Create a Series counting the number of times each value occurs in the region_1 field. This field is often missing data, so replace missing values with Unknown. Sort in descending order. Your output should look something like this:
"""
reviews_per_region = reviews.region_1.fillna("Unkown").value_counts().sort_values(ascending=False) |
# -*- coding: utf-8 -*-
a=input();
b = a.split(" ")
m = int(b[0])
n = int (b[1])
if(m>n):
print(m)
elif(n>m):
print(n)
elif(n==m):
print(n) |
import heapq
class PriorityQueue(object):
def __init__(self):
self.qlist = []
def __len__(self):
return len(self.qlist)
def isEmpty(self):
return len(self) == 0
def enqueue(self,data,priority):
heapq.heappush(self.qlist, (priority,data))
self.qlist.sort()
def dequeue(self):
return self.qlist.pop(-1)
def getFrontMost(self):
return self.qlist[0]
def getRearMost(self):
return self.qlist[-1]
Q = PriorityQueue()
Q.enqueue(28, 7)
Q.enqueue(19, 4)
Q.enqueue(45, 1)
Q.enqueue(13, 8)
Q.enqueue(7, 3)
Q.enqueue(98, 6)
Q.enqueue(54, 9)
print(Q.getFrontMost())
print(Q.getRearMost())
print(Q.qlist)
|
#!/usr/bin/env/ python
# ECBM E4040 Fall 2018 Assignment 2
# This Python script contains various functions for layer construction.
import numpy as np
def affine_forward(x, w, b):
"""
Computes the forward pass for an affine (fully-connected) layer.
The input x has shape (N, d_1, ..., d_k) and contains a minibatch of N
examples, where each example x[i] has shape (d_1, ..., d_k). We will
reshape each input into a vector of dimension D = d_1 * ... * d_k, and
then transform it to an output vector of dimension M.
Inputs:
:param x: A numpy array containing input data, of shape (N, d_1, ..., d_k)
:param w: A numpy array of weights, of shape (D, M)
:param b: A numpy array of biases, of shape (M,)
:return:
- out: output, of shape (N, M)
- cache: x, w, b for back-propagation
"""
num_train = x.shape[0]
x_flatten = x.reshape((num_train, -1))
out = np.dot(x_flatten, w) + b
cache = (x, w, b)
return out, cache
def affine_backward(dout, cache):
"""
Computes the backward pass for an affine layer.
:param dout: Upstream derivative, of shape (N, M)
:param cache: Tuple of:
x: Input data, of shape (N, d_1, ... d_k)
w: Weights, of shape (D, M)
:return: a tuple of:
- dx: Gradient with respect to x, of shape (N, d1, ..., d_k)
- dw: Gradient with respect to w, of shape (D, M)
- db: Gradient with respect to b, of shape (M,)
"""
x, w, b = cache
N = x.shape[0]
x_flatten = x.reshape((N, -1))
dx = np.reshape(np.dot(dout, w.T), x.shape)
dw = np.dot(x_flatten.T, dout)
db = np.dot(np.ones((N,)), dout)
return dx, dw, db
def relu_forward(x):
"""
Computes the forward pass for a layer of rectified linear units (ReLUs).
:param x: Inputs, of any shape
:return: A tuple of:
- out: Output, of the same shape as x
- cache: x for back-propagation
"""
out = np.zeros_like(x)
out[np.where(x > 0)] = x[np.where(x > 0)]
cache = x
return out, cache
def relu_backward(dout, cache):
"""
Computes the backward pass for a layer of rectified linear units (ReLUs).
:param dout: Upstream derivatives, of any shape
:param cache: Input x, of same shape as dout
:return: dx - Gradient with respect to x
"""
x = cache
dx = np.zeros_like(x)
dx[np.where(x > 0)] = dout[np.where(x > 0)]
return dx
def softmax(x):
"""
Softmax loss function, vectorized version.
:param x: (float) a tensor of shape (N, #classes)
"""
delta = np.max(x, axis=1)
x -= delta
exp_x = np.exp(x)
sumup = np.sum(exp_x, axis=1)
result = exp_x / sumup
return result
def softmax_loss(x, y):
"""
Softmax loss function, vectorized version.
y_prediction = argmax(softmax(x))
:param x: (float) a tensor of shape (N, #classes)
:param y: (int) ground truth label, a array of length N
:return: loss - the loss function
dx - the gradient wrt x
"""
loss = 0.0
num_train = x.shape[0]
x = x - np.max(x, axis=1, keepdims=True)
x_exp = np.exp(x)
loss -= np.sum(x[range(num_train), y])
loss += np.sum(np.log(np.sum(x_exp, axis=1)))
loss /= num_train
neg = np.zeros_like(x)
neg[range(num_train), y] = -1
pos = (x_exp.T / np.sum(x_exp, axis=1)).T
dx = (neg + pos) / num_train
return loss, dx
def conv_forward(x, w, b, pad, stride):
"""
A Numpy implementation of 2-D image convolution.
By 'convolution', simple element-wise multiplication and summation will suffice.
The border mode is 'valid' - Your convolution only happens when your input and your filter fully overlap.
Another thing to remember is that in TensorFlow, 'padding' means border mode (VALID or SAME). For this practice,
'pad' means the number rows/columns of zeroes to to concatenate before/after the edge of input.
Inputs:
:param x: Input data. Should have size (batch, height, width, channels).
:param w: Filter. Should have size (num_of_filters, filter_height, filter_width, channels).
:param b: Bias term. Should have size (num_of_filters, ).
:param pad: Integer. The number of zeroes to pad along the height and width axis.
:param stride: Integer. The number of pixels to move between 2 neighboring receptive fields.
:return: A 4-D array. Should have size (batch, new_height, new_width, num_of_filters).
Note:
To calculate the output shape of your convolution, you need the following equations:
new_height = ((height - filter_height + 2 * pad) // stride) + 1
new_width = ((width - filter_width + 2 * pad) // stride) + 1
For reference, visit this website:
https://adeshpande3.github.io/A-Beginner%27s-Guide-To-Understanding-Convolutional-Neural-Networks-Part-2/
"""
batch, height, width, channels = x.shape
num_of_filters, filter_height, filter_width, channels_f = w.shape
assert channels == channels_f
new_height = int(np.floor((height - filter_height + 2 * pad) / stride) + 1)
new_width = int(np.floor((width - filter_width + 2 * pad) / stride) + 1)
A = np.zeros((batch, new_height, new_width, num_of_filters))
x_pad = np.zeros((batch, height + 2*pad, width+2*pad, channels))
for bt in range(batch):
for i in range(height):
for j in range(width):
for cn in range(channels):
x_pad[bt,i+pad,j+pad,cn] = x[bt,i,j,cn]
for bt in range(batch):
for ft in range(num_of_filters):
for i in range(new_height):
for j in range(new_width):
A[bt,i,j,ft] = b[ft] + np.sum(w[ft,:,:,:] *
x_pad[bt, i*stride: i*stride + filter_height,j * stride: j*stride + filter_width,:])
return A
def conv_backward(d_top, x, w, b, pad, stride):
"""
(Optional, but if you solve it correctly, we give you +10 points for this assignment.)
A lite Numpy implementation of 2-D image convolution back-propagation.
Inputs:
:param d_top: The derivatives of pre-activation values from the previous layer
with shape (batch, height_new, width_new, num_of_filters).
:param x: Input data. Should have size (batch, height, width, channels).
:param w: Filter. Should have size (num_of_filters, filter_height, filter_width, channels).
:param b: Bias term. Should have size (num_of_filters, ).
:param pad: Integer. The number of zeroes to pad along the height and width axis.
:param stride: Integer. The number of pixels to move between 2 neighboring receptive fields.
:return: (d_w, d_b), i.e. the derivative with respect to w and b. For example, d_w means how a change of each value
of weight w would affect the final loss function.
Note:
Normally we also need to compute d_x in order to pass the gradients down to lower layers, so this is merely a
simplified version where we don't need to back-propagate.
For reference, visit this website:
http://www.jefkine.com/general/2016/09/05/backpropagation-in-convolutional-neural-networks/
"""
batch, height, width, channels = x.shape
num_of_filters, filter_height, filter_width, channels_f = w.shape
batch_dtop, new_height, new_width, num_f_top = d_top.shape
assert channels == channels_f and batch_dtop == batch and num_f_top == num_of_filters
dw = np.zeros_like(w)
db = np.zeros_like(b)
x_pad = np.zeros((batch, height + 2*pad, width+2*pad, channels))
for bt in range(batch):
for i in range(height):
for j in range(width):
for cn in range(channels):
x_pad[bt,i+pad,j+pad,cn] = x[bt,i,j,cn]
for bt in range(batch):
for ft in range(num_of_filters):
for i in range(new_height):
for j in range(new_width):
#A[bt,i,j,ft] = np.sum(w[ft,:,:,:] * x_pad[bt,i*stride :i*stride + filter_height,j * stride: j*stride + filter_width,:])+ b[ft]
dw[ft,:,:,:] += d_top[bt,i,j,ft] * x_pad[bt,i*stride :i*stride + filter_height,j * stride: j*stride + filter_width,:]
db[ft] += d_top[bt,i,j,ft]
#dw /= batch
#db /= batch
return dw, db
def max_pool_forward(x, pool_size, stride):
"""
A Numpy implementation of 2-D image max pooling.
Inputs:
:params x: Input data. Should have size (batch, height, width, channels).
:params pool_size: Integer. The size of a window in which you will perform max operations.
:params stride: Integer. The number of pixels to move between 2 neighboring receptive fields.
:return :A 4-D array. Should have size (batch, new_height, new_width, num_of_filters).
"""
batch, height, width, channels = x.shape
new_height = int(np.floor((height - pool_size) / stride) + 1)
new_width = int(np.floor((width - pool_size) / stride) + 1)
A = np.min(x) * np.ones((batch, new_height, new_width, channels))
for bt in range(batch):
for row in range(new_height):
for col in range(new_width):
for cn in range(channels):
for i in range(pool_size):
for j in range(pool_size):
if (x[bt][row*stride+i][col*stride+j][cn] > A[bt][row][col][cn]):
A[bt][row][col][cn] = x[bt][row*stride+i][col*stride+j][cn]
return A
def max_pool_backward(dout, x, pool_size, stride):
"""
(Optional, but if you solve it correctly, we give you +10 points for this assignment.)
A Numpy implementation of 2-D image max pooling back-propagation.
Inputs:
:params dout: The derivatives of values from the previous layer
with shape (batch, height_new, width_new, num_of_filters).
:params x: Input data. Should have size (batch, height, width, channels).
:params pool_size: Integer. The size of a window in which you will perform max operations.
:params stride: Integer. The number of pixels to move between 2 neighboring receptive fields.
:return dx: The derivative with respect to x
You may find this website helpful:
https://medium.com/the-bioinformatics-press/only-numpy-understanding-back-propagation-for-max-pooling-layer-in-multi-layer-cnn-with-example-f7be891ee4b4
"""
batch, height, width, channels = x.shape
batch_dout, new_height, new_width, num_of_filters = dout.shape
assert batch == batch_dout and num_of_filters == num_of_filters
dx = np.zeros_like(x)
# forward pooling
A = np.min(x) * np.ones((batch, new_height, new_width, channels))
for bt in range(batch):
for row in range(new_height):
for col in range(new_width):
for cn in range(channels):
for i in range(pool_size):
for j in range(pool_size):
if (x[bt][row*stride+i][col*stride+j][cn] > A[bt][row][col][cn]):
A[bt][row][col][cn] = x[bt][row*stride+i][col*stride+j][cn]
# backprop
for bt in range(batch):
for row in range(new_height):
for col in range(new_width):
for cn in range(channels):
for i in range(pool_size):
for j in range(pool_size):
if (x[bt][row*stride+i][col*stride+j][cn] == A[bt][row][col][cn]):
dx[bt, row*stride+i, col*stride+j, cn] += dout[bt,row,col,cn]
#A[bt][row][col][cn] = x[bt][row*stride+i][col*stride+j][cn]
return dx
|
from tkinter import *
root = Tk()
root.title("Simple calculator")
root.iconbitmap('C:/Users/simao/OneDrive/Ambiente de Trabalho/Projects/Python/dinal_deal.ico')
e = Entry(root, width=35, borderwidth=5)
e.grid(row=0, column=0, columnspan=3, padx=10, pady=10)
def button_click(number):
current=e.get()
e.delete(0, END)
e.insert(0, str(current) + str(number))
def gui_clear():
e.delete(0, END)
def function_add():
global op
op = "add"
x=e.get()
global f_x
f_x=0
f_x = int(x)
e.delete(0, END)
def function_multi():
global op
op = "multi"
x=e.get()
global f_x
f_x=0
f_x = int(x)
e.delete(0, END)
def function_div():
global op
op = "div"
x=e.get()
global f_x
f_x=0
f_x = int(x)
e.delete(0, END)
def function_sub():
global op
op = "sub"
x=e.get()
global f_x
f_x=0
f_x = int(x)
e.delete(0, END)
def final_result():
if op=="add":
y=e.get()
e.delete(0, END)
z=int(y)+f_x
e.insert(0, z)
if op=="sub":
y=e.get()
e.delete(0, END)
z=f_x-int(y)
e.insert(0, z)
if op=="multi":
y=e.get()
e.delete(0, END)
z=f_x*int(y)
e.insert(0, z)
if op=="div":
y=e.get()
e.delete(0, END)
z=f_x/int(y)
e.insert(0, z)
button_0 = Button(root, text="0", padx=40, pady=20, command=lambda: button_click(0))
button_1 = Button(root, text="1", padx=40, pady=20, command=lambda: button_click(1))
button_2 = Button(root, text="2", padx=40, pady=20, command=lambda: button_click(2))
button_3 = Button(root, text="3", padx=40, pady=20, command=lambda: button_click(3))
button_4 = Button(root, text="4", padx=40, pady=20, command=lambda: button_click(4))
button_5 = Button(root, text="5", padx=40, pady=20, command=lambda: button_click(5))
button_6 = Button(root, text="6", padx=40, pady=20, command=lambda: button_click(6))
button_7 = Button(root, text="7", padx=40, pady=20, command=lambda: button_click(7))
button_8 = Button(root, text="8", padx=40, pady=20, command=lambda: button_click(8))
button_9 = Button(root, text="9", padx=40, pady=20, command=lambda: button_click(9))
button_clear = Button(root, text="Clear", padx=79, pady=20, command=gui_clear)
button_plus = Button(root, text="+", padx=39, pady=20, command=function_add)
button_equal = Button(root, text="=", padx=91, pady=20, command=final_result)
button_multiplication = Button(root, text="x", padx=40, pady=20, command=function_multi)
button_division = Button(root, text="/", padx=40, pady=20, command=function_div)
button_subtraction = Button(root, text="-", padx=40, pady=20, command=function_sub)
button_0.grid(row=4, column=0)
button_1.grid(row=3, column=0)
button_2.grid(row=3, column=1)
button_3.grid(row=3, column=2)
button_4.grid(row=2, column=0)
button_5.grid(row=2, column=1)
button_6.grid(row=2, column=2)
button_7.grid(row=1, column=0)
button_8.grid(row=1, column=1)
button_9.grid(row=1, column=2)
button_clear.grid(row=5, column=1, columnspan=2)
button_plus.grid(row=5, column=0)
button_equal.grid(row=6, column=1, columnspan=2)
button_multiplication.grid(row=4, column=2)
button_division.grid(row=4, column=1)
button_subtraction.grid(row=6, column=0)
root.mainloop() |
#!usr/bin/python
#defines vector object
import math
class vector:
v = []
#constructor
def __init__(self, a):
self.v = a
#instance methods
def magnitude(self):
sum = 0
for i in range(len(self.v)):
sum += self.v[i]^2
return math.sqrt(sum)
def multiply(self, factor):
for i in self.v:
i *= factor
def unit(self):
temp_vector = vector(self.v)
mag = temp_vector.magnitude()
temp_vector.multiply(1/mag)
self.v = temp_vector.v
#static methods
#add two vectors
@staticmethod
def add(v1, v2):
temp = vector(v1.v)
for i in range(len(v1.v)):
temp.v[i] = v1.v[i] + v2.v[i]
return temp
#difference
@staticmethod
def difference(v1, v2):
difference = vector(v1.v)
for i in range(len(v1.v)):
difference.v[i] = v1.v[i] - v2.v[i]
return difference
#dot product
@staticmethod
def dot(v1, v2):
dot = 0
for i in range(len(v1.v)):
dot += v1.v[i]*v2.v[i]
return dot
#cross product
@staticmethod
def cross(v1, v2):
if len(v1)==3 and len(v2)==3:
cross = vector([v1.v[1]*v2.v[2]-v1.v[2]*v2.v[1],
v1.v[2]*v2.v[0]-v1.v[0]*v2.v[2],
v1.v[0]*v2.v[1]-v1.v[1]*v2.v[0]])
return cross
else:
print "both vectors must be of length 3 to be crossed."
return vector([0,0,0])
#distance
@staticmethod
def distance(v1, v2):
return vector.difference(v1, v2).magnitude()
#print
@staticmethod
def printv(vec):
print '{',
for i in range(len(vec.v)):
if i == len(vec.v)-1:
print str(vec.v[i]),
else:
print str(vec.v[i]) + ',',
print '}\n'
#v1 = vector([0,1,2])
#v2 = vector([-3,1,2])
#vector.printv(v1)
#vector.printv(v2)
#v1.multiply(3)
#print '2 magnitude: ' + str(v2.magnitude()) + '\n'
#v1.unit()
#vector.printv(v1)
#v3 = vector.add(v1, v2)
#vector.printv(v3)
#v4 = vector.difference(v1, v2)
#vector.printv(v4)
#print 'distance: ' + str(vector.distance(v3, v4)) + '\n' |
#------------------------------------
# Name: Dylan Markovic
# Class: CS372
# Assignment: Project 1
# Due Date: 2.11.2018
#------------------------------------
import sys
from socket import *
MESSAGE_LENGTH = 500
HANDLE_LENGTH = 10
#--------------------------
# checkArgs makes sure the client inputs the correct number of arguments
# to run the server program
# checkArgs also makes sure that the input is an integer that falls in the
# range of valid, non-reserved port numbers
#--------------------------
def checkArgs():
if len(sys.argv) != 2:
print("invalid argument count for chatserve.py")
print("Correct Input: python3 " + sys.argv[0] + " <port number>");
sys.exit()
if int(sys.argv[1]) < 1024 or int(sys.argv[1]) > 65535:
print("Port Number does not fall into valid range")
print("Acceptable Port Number Range is [1024, 65535]")
sys.exit()
#-----------------------------
# getServerHandle is a simple function
# that prompts the user to input their nameExchange
# It will continue to ask user for a name until it is
# between 1 and 10 characters long
#-----------------------------------
def getServerHandle():
serverHandle = ""
while len(serverHandle) < 1 or len(serverHandle) > 10:
serverHandle = input("Enter the handle for the server (must be 1 to 10 characters long):")
return serverHandle
#--------------------------------------------
# startSocket creates a socket with the port number
# included in the command line used to begin the program
# after it is created, the socket listens and informs user
# what port it is listening on
#-------------------------------------------------
def startSocket():
serverPort = int(sys.argv[1])
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(('',serverPort))
serverSocket.listen(1)
print("Server is listening on port: " + sys.argv[1])
return serverSocket
#-----------------------------------------------------
# nameExchange is the first phase of the chatroom
# the server first receives the client's handle
# and it then sends the server's handle
# It requires the connectionSocket and the server's handle
# be passed as arguments.
#--------------------------------------------------
def nameExchange(connectionSocket, serverHandle):
clientHandle = connectionSocket.recv(HANDLE_LENGTH).decode('UTF-8')
print("Began chat with {}".format(clientHandle))
connectionSocket.send(serverHandle.encode())
return clientHandle
#-------------------------------------------------
# getClientMessage is responsible for receiving messages
# from the client during the chat. It receives, decodes the
# message into a string, and then removes any trailing '\n'
# It requires the connection socket and client's handle to
# be passed as arguments. It returns the formatted message
#-----------------------------------------------------
def getClientMessage(client, clientHandle):
message = client.recv(MESSAGE_LENGTH).decode('UTF-8').rstrip()
return message
#--------------------------------------------------
# sendServerMessage is responsible for sending messages written on
# this side of the chat. It appends the server's handle and '> '
# to the message to format it correctly. It then checks if '\quit'
# was the message, and sends it when this is not the case.
# It needs the connection socket and server's handle as arguments,
# and returns the formatted message
#-------------------------------------------------------
def sendServerMessage(client, serverHandle):
prefix = serverHandle + "> "
message2 = input(prefix)
deliverThis = prefix + message2
if(message2 != "\quit"):
client.send(deliverThis.encode())
return deliverThis
#--------------------------------------------------------
# chat uses the sendServerMessage and getClientMessage functions
# to create the entire chat experience. It closes the connection
# when the received message is blank or if the server side message is
# '\quit'. It also prints the messages to the console and informs the
# user when the connection is closed.
# It requires the connection socket, the client's handle, and the
# server's handle be passed in as arguments
#-----------------------------------------------------------
def chat(client, clientHandle, serverHandle):
while True:
clientMessage = getClientMessage(client, clientHandle)
if (clientMessage == ""):
print("Client has closed connection")
print("Server is still listening on port " + sys.argv[1])
break
print("{}> {}".format(clientHandle, clientMessage));
serverMessage = sendServerMessage(client, serverHandle)
if (serverMessage == serverHandle + "> \quit"):
print("Connection terminated");
print("Server is still listening on port " + sys.argv[1])
break
client.close()
#-------------------------------------------------
# main drives the whole program. It calls all necessary
# functions to create the server side chatroom
#-----------------------------------------------
def main():
checkArgs() # check command line arguments
serverHandle = getServerHandle() # get server's handle
serverSocket = startSocket() #start the socket
while True:
connectionSocket, addr = serverSocket.accept() #accept requested connections
clientHandle = nameExchange(connectionSocket, serverHandle) #swap handles
chat(connectionSocket, clientHandle, serverHandle) #start the chat
main()
#---------------------------------------
# Using Computer Networking, a Top Down Approach section 2.7 for reference
# https://wiki.python.org/moin/tcpcommunication
# Used to remove trailing newlines:
#https://stackoverflow.com/questions/275018/how-can-i-remove-chomp-a-trailing-newline-in-python |
def recurse(n):
# check for base case
if (n <= 0):
return 0
else:
# recursive case
# print(n)
return 1 + recurse(n-1)
recurse(10)
# Computes the sum of numbers from 0 to n
def sum(n):
if (n <= 0):
return 0
else:
# print(n)
return n + sum(n-1)
# print(sum(5))
# Example functions to demonstrate the recursive sum for n = 3
def sumBase():
return 0
def sum1():
return 1 + sumBase()
def sum2():
return 2 + sum1()
def sum3():
return 3 + sum2()
# print the sum of 3 + 2 + 1
# print(sum3())
def is_palindrome(s):
if (len(s) < 2):
return True
else:
first = s[0]
last = s[-1]
if (first != last):
return False
else:
middle = s[1:-1]
return is_palindrome(middle)
# print(is_palindrome('amanaplanacanalpanama'))
def factorial(n):
if n < 1:
return 1
else:
return n * factorial(n - 1)
# print(factorial(7))
def string_reverse(s):
if (len(s) < 1):
return s
else:
return string_reverse(s[1:]) + s[0]
# print(string_reverse('semordnilap'))
def divisor(a, b):
if (a < 1 and b < 1):
return 0
else:
if a > b:
quotient = a / b
remainder = a % b
# b / remainder
return divisor(a - b, b)
elif b > a:
return divisor(a, b - a)
# else:
# print(12 % 8)
# print(divisor(12, 8))
# Tower of Hanoi Problem
source = [[3, 2, 1], "source"]
helper = [[], "helper"]
target = [[], "target"]
def hanoi(n, source, helper, target):
print("hanoi called with values:", n, source, helper, target)
if n > 0:
# move everything but the bottom disc
hanoi(n-1, source, target, helper)
if source:
disk = source[0].pop()
print("moving " + str(disk) + " from " + source[1] + " to " + target[1])
target[0].append(disk)
# now move the remaining stack to the target
hanoi(n-1, helper, source, target)
hanoi(len(source[0]), source, helper, target)
|
import numpy as np
from sklearn.model_selection import ShuffleSplit
X = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]])
y = np.array([1, 2, 3, 4, 5, 6])
rs = ShuffleSplit(n_splits=3, test_size=0.25, random_state=0)
rs.get_n_splits(X)
print(rs)
for train_index, test_index in rs.split(X, y):
print("Train Index:", train_index, ",Test Index:", test_index)
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
# print(X_train,X_test,y_train,y_test)
print("==============================")
rs = ShuffleSplit(n_splits=3, train_size=0.5, test_size=0.25, random_state=0)
rs.get_n_splits(X)
print(rs)
for train_index, test_index in rs.split(X, y):
print("Train Index:", train_index, ",Test Index:", test_index) |
class Solution(object):
def solveSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: None Do not return anything, modify board in-place instead.
"""
row = [set() for i in range(0, 9)]
col = [set() for i in range(0, 9)]
grid = [set() for i in range(0, 9)]
positions = {}
for i in range(0, 9):
for j in range(0, 9):
if board[i][j] != '.':
row[i].add(board[i][j])
col[j].add(board[i][j])
grid[(i // 3) * 3 + (j // 3)].add(board[i][j])
else:
positions[i * 9 + j] = (i, j)
print positions
def dfs(position):
if position == 81:
return True
if not positions.get(position, None):
return dfs(position + 1)
i = position // 9
j = position % 9
for num in range(1, 10):
strNum = str(num)
if (strNum in row[i]) or (strNum in col[j]) or (strNum in grid[(i // 3) * 3 + (j // 3)]):
continue
else:
row[i].add(strNum)
col[j].add(strNum)
grid[(i // 3) * 3 + (j // 3)].add(strNum)
board[i][j] = strNum
if (dfs(position + 1)):
return True
row[i].remove(strNum)
col[j].remove(strNum)
grid[(i // 3) * 3 + (j // 3)].remove(strNum)
dfs(0)
|
class Solution(object):
def countCharacters(self, words, chars):
"""
:type words: List[str]
:type chars: str
:rtype: int
"""
result = 0
charsArr = [0 for i in range(26)]
for char in chars:
charsArr[ord(char) - ord('a')] += 1
for word in words:
flag = True
for character in word:
if word.count(character) > charsArr[ord(character) - ord('a')]:
flag = False
break
if flag:
result += len(word)
return result
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if not root and sum == 0:
return False
self.result = False
self.total = sum
self.dfs(root, 0)
return self.result
def dfs(self, root, tempSum):
if self.result or not root:
return
if not root.left and not root.right:
if self.total == tempSum + root.val:
self.result = True
return
self.dfs(root.left, tempSum + root.val)
self.dfs(root.right, tempSum + root.val)
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isCousins(self, root, x, y):
"""
:type root: TreeNode
:type x: int
:type y: int
:rtype: bool
"""
self.depthDict = collections.defaultdict(tuple)
self.dfs(root, None, 0)
xParent, xDepth = self.depthDict[x]
yParent, yDepth = self.depthDict[y]
return xDepth == yDepth and xParent != yParent
def dfs(self, root, parent, level):
if not root:
return
self.depthDict[root.val] = (parent, level)
self.dfs(root.left, root, level+1)
self.dfs(root.right, root, level+1)
|
class Solution(object):
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: None Do not return anything, modify board in-place instead.
"""
row = len(board) - 1
if row <= 0:
return
col = len(board[0]) - 1
quene = []
for i in range(0, row):
if (board[i][0]) == "O":
quene.append((i, 0))
if (board[i][col]) == "O":
quene.append((i, col))
for j in range(0, col+1):
if (board[0][j]) == "O":
quene.append((0, j))
if (board[row][j]) == "O":
quene.append((row, j))
# 广度优先搜索
while quene:
x, y = quene.pop(0)
board[x][y] = "A"
if x > 0 and board[x-1][y] == "O":
quene.append((x-1, y))
if x < row and board[x+1][y] == "O":
quene.append((x+1, y))
if y > 0 and board[x][y-1] == "O":
quene.append((x, y-1))
if y < col and board[x][y+1] == "O":
quene.append((x, y+1))
for i in range(0, row+1):
for j in range(0, col+1):
if board[i][j] == "O":
board[i][j] = "X"
elif board[i][j] == "A":
board[i][j] = "O"
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
self.result = []
if not root:
return []
self.dfs(root, [str(root.val)])
return self.result
def dfs(self, root, tempResult):
if not root:
return
if not root.left and not root.right:
self.result.append("->".join(tempResult))
return
if root.left:
self.dfs(root.left, tempResult + [str(root.left.val)])
if root.right:
self.dfs(root.right, tempResult + [str(root.right.val)])
|
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
result = ListNode(0)
result.next = head
temp = result
while temp.next and temp.next.next:
node1 = temp.next
node2 = temp.next.next
temp.next = node2
node1.next = node2.next
node2.next = node1
temp = node1
return result.next
|
class Solution(object):
def longestMountain(self, A):
"""
:type A: List[int]
:rtype: int
"""
result = 0
lengthA = len(A)
start = 0
end = lengthA
# filter down
while start + 1 < lengthA:
if A[start] >= A[start + 1]:
start += 1
else:
break
if lengthA - start < 3:
return 0
temp = 1
flag = False
while start + 2 < lengthA:
# up
end = start
while end + 1 < lengthA and A[end] < A[end + 1]:
temp += 1
end += 1
# down
if (end > start):
while end + 1 < lengthA and A[end] > A[end + 1]:
temp += 1
end += 1
flag = True
if start == end:
start += 1
else:
result = max(result, temp)
temp = 1
start = end
print result
return 0 if not flag or result < 3 else result
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
self.result = []
self.bfs(root, 0)
return self.result[::-1]
def bfs(self, root, level):
if not root:
return None
if (len(self.result) - 1) < level:
self.result.append([root.val])
else:
self.result[level].append(root.val)
if root.left:
self.bfs(root.left, level+1)
if root.right:
self.bfs(root.right, level+1)
return None
|
# prints the prime factorization of the user's number
#gets number from user
print ("Insert a number:")
num = int(input())
ori = num
#breaks down the number into its prime factorization in order
a = []
while(num > 1):
for count in range(2, num+1):
print(num, count)
if(num % count == 0):
a.append(count)
num = int(num / count)
if(count == ori):
a.insert(0, 1)
a.sort()
print(a)
|
print("the number of a's in banana are :::"+str('banana'.count('a')))
|
def do_n(func,n):
if(n==0):
return 1
else:
return n+do_n(func,n-1)
n=int(input("Enter the value"))
print("The Sum of values from 0 to %d is %d"%(n,do_n(do_n,n)))
|
val=input("Please enter a string::")
if(len(val)<3):
pass
elif val[len(val)-3:] =='ing':
val=val+'ly'
else:
val=val+'ing'
print("The string is :::"+val)
|
def first(word):
return word[0]
def last(word):
return word[-1]
def middle(word):
return word[1:-1]
print('The middle with 2 char::'+middle("AK"))
print('The middle with 1 char::'+middle("A"))
print('The middle with 0 char::'+middle(""))
print('The first with 2 char::'+first("AK"))
print('The first with 1 char::'+first("A"))
#below one thrpws error string index out of range
#print('The first with 0 char::'+first(""))
print('The last with 2 char::'+last("AK"))
print('The last with 1 char::'+last("A"))
#below one thrpws error string index out of range
#print('The last with 0 char::'+last(""))
def is_palindrome(word):
temp=list(word)
temp1=list(word[len(word)-1::-1])
if temp == temp1:
return "True"
else:
return "False"
word=input("please Enter a String to check it is Palindrom or not::")
print("The Entered String %s is Palindrom ? %s"%(word,is_palindrome(word)))
|
def histogram(word):
dic={}
for char in word:
if char in dic:
dic[char]+=1
else:
dic[char]=1
return dic
def is_anagram(s1,s2):
if len(s1)!=len(s2):
return False
else:
dic_s1=histogram(s1)
dic_s2=histogram(s2)
for key in dic_s1:
if(key not in dic_s2 or dic_s1[key]!=dic_s2[key]):
return False
return True
def file_anagram_list(fout):
l1=[]
l2={}
temp=[]
temp2=[]
for item in fout:
l1.append(item.strip())
for i in range(len(l1)):
temp2.append(l1[i])
if l1[i] in l2.keys():
continue
else:
for j in range(len(l1)):
if l1[j] in temp2:
continue
else:
if is_anagram(l1[i],l1[j]):
if l1[i] not in temp:
temp.append(l1[i])
temp.append(l1[j])
temp2.append(l1[j])
if len(temp)>0:
#print(temp)
l2[l1[i]]=temp
temp=[]
return l2
#print('The Entered string is anagram::',is_anagram('abcdefgasas','gcfedbaasas'))
fout=open('words.txt','r')
ll={}
ll=file_anagram_list(fout)
print('The Maximum anagram list is ::',ll[max(ll)])
|
'''
As long as you have a URL, the webbrowser module lets users cut out the step of
opening the browser and directing themselves to a website. Other programs could
use this functionality to do the following:
AIM: Open all links on a page in separate browser tabs.
'''
### LIBRARIES WE'RE GOING TO NEED ###
# WEBBROWSER: to open links in a browser
# RE: to use and parse regular expressions
# ULRLIB: to fetch URLs
# BEAUTIFULSOUP: to web scrape
import webbrowser
import re
import urllib.request as URL
from bs4 import BeautifulSoup
# urlopen() returns the source code of the URL passed
start_page = URL.urlopen('https://teamtreehouse.com')
#print(start_page.read())
# now we need to find the links
# 1. let's create a soup with the source code
soup = BeautifulSoup(start_page, features='lxml')
# 2. we need to find the links (<a>) with a URL (href=...). Mind that if you
# don't include the RE, you may also catch internal links.
for tag in soup('a', attrs = {'href':re.compile('^http(s)?://')}):
# We have 2 options now: Open links in new tabs as we find them
# Or store them in a list and open them later
# To save time, here we'll do the former.
webbrowser.open_new_tab(tag.get('href'))
# Tadaa!
|
Sample_list=[8,2,3,-1,7]
def multi(Sample_list):
result=1
for i in Sample_list:
result=i*result
return result
a=multi(Sample_list)
print (a)
|
# Implement a class to hold item information
class Item: #base class
"""
This is a item class with attributes
name & description
"""
def __init__(self, name, description):
self.name = name
self.description = description
def __repr__(self):
return f"{self.name}, {self.description}"
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
class Student(object):
def __init__(self,name,age,score):
self.name = name
self.age = age
self.score = score
def Student2dict(std):
return{
'name':std.name,
'age':std.age,
'score':std.score
}
def dict2student(d):
return Student(d['name'],d['age'],d['score'])
s = Student('Bob', 20, 88)
print(json.dumps(s,default=Student2dict))
json_str = '{"age": 20, "score": 88, "name": "Bob"}'
print(json.loads(json_str, object_hook=dict2student))
#print(json.dumps(s))
|
print "Simple Fizz-Buzz Game."
print "Type 'quit' to exit."
while True:
userInput = raw_input("Please enter a number: ")
try:
intVal = int(userInput)
print "Fizz-Buzz" if intVal%3 == 0 and intVal%5 == 0 else "Fizz" if intVal%3 == 0 else "Buzz" if intVal%5 == 0 else intVal
except ValueError:
if userInput == "quit":
break
else:
print "Error - not an integer, please try again!"
|
def main():
#Escribe tu código debajo de esta línea
import math
edad= int(input("Ingresa tu edad: "))
if edad>=18:
identificacion= str(input("¿Tienes identificación oficial? (s/n): "))
if (identificacion== "s"):
print ("Trámite de licencia concedido")
elif (identificacion== "n"):
print ("No cumples requisitos")
elif (identificacion != "s" != "n"):
print ("Respuesta incorrecta")
else:
print("No cumples con los requisitos")
pass
if __name__ == '__main__':
main()
|
import random
cards = {'Hearts':
{'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10, 'Queen':10, 'King':10, 'Ace':11},
'Diamonds':
{'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10, 'Queen':10, 'King':10, 'Ace':11},
'Spades':
{'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10, 'Queen':10, 'King':10, 'Ace':11},
'Clubs':
{'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10, 'Queen':10, 'King':10, 'Ace':11}}
def make_deck():
deck = []
for outer_key in cards:
for inner_key in cards[outer_key]:
deck.append(('{} of {}'.format(inner_key,outer_key)))
random.shuffle(deck)
return deck
def deal(hand,deck):
card = random.choice(deck)
hand.append(card)
deck.remove(card)
def return_total(hand, total):
for i in range(len(hand)):
if "Ace" in hand[i]:
total += 11
elif "Two" in hand[i]:
total +=2
elif "Three" in hand[i]:
total +=3
elif "Four" in hand[i]:
total +=4
elif "Five" in hand[i]:
total +=5
elif "Six" in hand[i]:
total +=6
elif "Seven" in hand[i]:
total +=7
elif "Eight" in hand[i]:
total +=8
elif "Nine" in hand[i]:
total +=9
elif "Ten" in hand[i]:
total +=10
elif "Jack" in hand[i]:
total +=10
elif "Queen" in hand[i]:
total +=10
elif "King" in hand[i]:
total +=10
return total
|
import requests
import hashlib
import sys
def request_data(query):
"""
Given the first 5 characters of a sha1 hash (query), request_data returns the request response after
trying to access the Pwnedpasswords API.
Keyword arguments:
query: a 5 charachter string corresponding to the first 5 characters of our sha1 encrypted password.
Return:
res: a Response object. Its status_code indicates whether the request was successful (code: 200) or not.
"""
url = 'https://api.pwnedpasswords.com/range/' + query
res = requests.get(url)
if res.status_code != 200:
raise RuntimeError('Something went wrong. Please check your password again and read the API documentation.')
return res
def check_num_leaks(hashes, our_hash):
"""
Checks the number of times a (hashed) password has been leaked and returns its count.
Keyword arguments:
hashes: a string text containing a number of hashed passwords tails, each followed by
a colon and an integer (the number of times this password has been leaked). The format
is similar to this: A5B800C301FEE5A:56
our_hash: the tail of our password (all the characters except the first 5)
Returns: an integer with the number of times our password has been leaked.
"""
print(type(hashes))
for line in hashes.splitlines():
hashcount = line.split(':') # tail on hashcount[0]; count on hashcount[1]
if hashcount[0] == our_hash:
hashcount[1] = int(hashcount[1])
return hashcount[1]
return 0
def pwned_api_check(password):
"""
Hashes the password into SHA1, splits it into a head and a tail and calls the other two functions. It requests information
from the API using the head, and checks the number of leaks using the tail.
Keyword argument:
password: a string with the password to check.
Returns: an integer with the number of times our password has been leaked.
"""
sha1pass = hashlib.sha1(password.encode('utf-8')).hexdigest().upper()
first_char, tail = sha1pass[:5], sha1pass[5:]
response = request_data(first_char)
return check_num_leaks(response.text, tail)
def main(args):
for password in args:
count = pwned_api_check(password)
if count:
print(f'\'{password}\' has been leaked {count} times. Try another one.')
else:
print(f'\'{password}\' has never been leaked before. Well chosen!')
return '\n---Leak checking finished.---\n'
if __name__ == '__main__':
sys.exit(main(sys.argv[1:])) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 7 23:30:46 2019
@author: danilo
"""
def main():
x=eval(input("Give me x: "))
while(x!=1):
print ("{0:.0f}".format(x))
if(x%2==0):
x=x/2
else:
x=x*3+1
print ("{0:.0f}".format(x))
main() |
import mysql.connector
import connect
db = connect.koneksi()
#Menambahkan data baru ke dalam tabel pendaftaran
def add(data):
cursor = db.cursor()
sql = """INSERT INTO pendaftaran_pemeriksaan(tanggal,nomor_urut,nama,jenis_kelamin,umur,alamat) VALUES (%s,%s,%s,%s,%s,%s)"""
cursor.execute(sql,data)
db.commit()
print(' Data Pendaftar berhasil ditambahkan!'.format(cursor.rowcount))
#Menampilkan seluruh data dari tabel pendaftaran
def show():
cursor = db.cursor()
sql = """SELECT * FROM pendaftaran_pemeriksaan"""
cursor.execute(sql)
results = cursor.fetchall()
print("-----------------------------------------------------------------------------------------------------------------")
print("|TANGGAL\t|NOMOR URUT\t|NAMA\t\t\t|JENIS KELAMIN\t\t|UMUR\t|ALAMAT\t\t\t|")
print("-----------------------------------------------------------------------------------------------------------------")
for data in results:
print("|",data[0],"\t|",data[1],"\t\t|",data[2],"\t\t|",data[3],"\t\t|",data[4],"\t|",data[5],"\t\t|")
print("-----------------------------------------------------------------------------------------------------------------")
#Mengubah data per record berdasarkan id pada tabel pendaftaran
def edit(data):
cursor=db.cursor()
sql="""UPDATE pendaftaran_pemeriksaan SET nama=%s,alamat=%s,jenis_kelamin=%s,umur=%s WHERE nomor_urut=%s and tanggal=%s"""
cursor.execute(sql,data)
db.commit()
print(' Data Pendaftar berhasil diubah!'.format(cursor.rowcount))
#Menghapus data dari tabel pendaftaran
def delete(data):
cursor = db.cursor()
sql = """DELETE FROM pendaftaran_pemeriksaan WHERE nama=%s"""
cursor.execute(sql,data)
db.commit()
print(' Data Pendaftar berhasil dihapus!'.format(cursor.rowcount))
#Mencari data dari tabel pendaftaran
def search(data):
cursor = db.cursor()
sql = """SELECT * FROM pendaftaran_pemeriksaan WHERE nama=%s"""
cursor.execute(sql,data)
results = cursor.fetchall()
print("------------------------------------------------------------------------------------------------------------------")
print("|TANGGAL\t|NOMOR URUT\t|NAMA\t\t\t|JENIS KELAMIN\t\t|UMUR\t|ALAMAT\t\t\t|")
print("------------------------------------------------------------------------------------------------------------------")
for data in results:
print("|",data[0],"\t|",data[1],"\t\t|",data[2],"\t\t|",data[3],"\t\t|",data[4],"\t|",data[5],"\t\t|")
print("------------------------------------------------------------------------------------------------------------------")
|
# 2.
# DIM = 4 # dimension of the board DIMxDIM
# EMPTYSLOT = 0
# QUIT = 0
# def initialize_board():
# ''' Creates the initial board according to the user input.
# The board is a list of lists.
# The list contains DIM elements (rows), each of which contains DIM elements (columns)'''
# numbers = input().split()
# numbers = [int(number) for number in numbers]
# puzzle_board = []
# index = 0
# for _ in range(DIM):
# row = numbers[index:index + DIM]
# index += DIM
# puzzle_board.append(row)
# return puzzle_board
# def display(puzzle_board):
# ''' Display the board, printing it one row in each line '''
# print()
# for i in range(DIM):
# for j in range(DIM):
# if puzzle_board[i][j] == EMPTYSLOT:
# print("\t", end="")
# else:
# print(str(puzzle_board[i][j]) + "\t", end="")
# print()
# print()
# def order(nested_list):
# order = int(input())
# #Dictates when to stop
# if order == 0:
# return False
# else:
# return order
# def find_index(order,grid):
# for y_axis in range(DIM):
# for x_axis in range(DIM):
# if grid[y_axis][x_axis] == order:
# return (y_axis,x_axis)
# return None
# def move(empty_index,number_index,grid,order):
# grid[empty_index[0]][empty_index[1]] = order
# grid[number_index[0]][number_index[1]] = 0
# return grid
# def main():
# command = True
# board = initialize_board()
# while command != False:
# display(board)
# command = order(board)
# empty_index = find_index(EMPTYSLOT,board)
# number_index = find_index(command,board)
# if number_index != None:
# board = move(empty_index,number_index,board,command)
# main()
#------------------------------------------------------- question 3 -------------------------------
#3.
class StringSet:
def __init__(self,other):
temp = other.split()
self.__words = []
for each in temp:
if each not in self.__words:
self.__words.append(each)
def size(self):
self.__words
return len(self.__words)
def __str__(self):
answer = ""
for words in self.__words:
answer += words + " "
answer = answer.strip()
return answer
def __add__(self,other):
temp = str(other)
temp = temp.split()
for words in temp:
if words not in self.__words:
self.__words.append(words)
return self
def at(self,other):
return self.__words[other]
def find(self,other):
if other in self.__words:
return True
else:
return False
#Testcode:
def main():
str1 = 'chocolate ice cream and chocolate candy ice bars are my favorite'
set1 = StringSet(str1)
str2 = 'I like to eat broccoli and fish and ice cream and brussel fish sprouts'
set2 = StringSet(str2)
print("Set1:", set1)
print("Set2:", set2)
print("Set1 size:", set1.size())
print("Set2 size:", set2.size())
the_union = set1 + set2
print("Union:", the_union)
print("Union size:", the_union.size())
query = StringSet('chocolate cream fish good rubbish')
print("Query:", query)
count = 0
for i in range(query.size()):
if the_union.find(query.at(i)):
count += 1
print("Query size:", query.size())
print("Found in union:", count)
main() |
import string
def open_file():
"""A function that takes the name of a file as an input and opens it"""
name = input("Enter name of file: ")
try:
my_file = open(name,"r")
return my_file
except FileNotFoundError:
print(("File {} not found!").format(name))
def scramble_middle(texti):
"""A function that "scrambles" words by swapping adjacent characters from left to right,
but leaves the first and last character untouched"""
shuffled_str = ""
punct = ""
final_char = ""
place = 0
if texti[-1] in string.punctuation:
punct = texti[-1]
str_cleaned = texti[0:-1]
else:
str_cleaned = texti
first_char = str_cleaned[0]
middle = str_cleaned[1:-1]
reps = len(middle)//2
if len(str_cleaned)>1:
if len(str_cleaned) % 2 == 0:
final_char = str_cleaned[-1]
else:
final_char=str_cleaned[-2::]
#A loop in which the scrambling it self occurs:
while reps>0:
letter_1 = middle[(0 + place)]
letter_2 = middle[(1 + place)]
shuffled_str += (letter_2 + letter_1)
reps -= 1
place += 2
return (first_char + shuffled_str + final_char + punct)
#The main program starts here ---------------------------------------
outcome = ""
text_file = open_file()
#Each line is scrambled and a single line text is created:
for lines in text_file:
lines = lines.rstrip()
outcome += (scramble_middle(lines)+" ")
print(outcome) |
def read_file():
"""Askes the user for a file name and tries to open it"""
file_name = input("Enter filename: ")
try:
the_file = open(file_name,"r")
return the_file
except FileNotFoundError:
print("Filename {} not found!".format(file_name))
def file_to_list(file_to_read): #comment more
"""Recives a file and creates a nested list"""
nested_list = []
first_line = file_to_read.readline()
first_line = first_line.split()
rows = len(first_line)
for lines in file_to_read:
lines = lines.split()
if len(lines) > rows:
lines[0] = lines[0] + " " + lines[1]
del lines[1]
for ind in range (1,len(lines)):
lines[ind] = int(lines[ind])
nested_list.append(lines)
nested_list.insert(0,first_line)
return nested_list
def what_year(the_list):
"""Askes the user for a year and if the year is valid, return its index"""
to_continue=True
while to_continue:
input_year = input("Enter year: ")
if input_year in the_list[0]:
to_continue = False
year_index = the_list[0].index(input_year)
else:
print("Invalid year!")
return year_index
def min_max_of_year(the_list,position):
"""Creates a list of tuples containing the states and their population,
then finds the min/max values and corresponding state name"""
final_list = []
for states in range(1,len(the_list)):
population = the_list[states][position]
name = the_list[states][0]
pop_and_name_tuple = (population,name)
final_list.append(pop_and_name_tuple)
max_tuple = max(final_list)
min_tuple = min(final_list)
return min_tuple,max_tuple
#The main code
target_file = read_file()
nested_list = file_to_list(target_file)
year_index = what_year(nested_list)
lowest, highest = min_max_of_year(nested_list, year_index)
print("Minimum: " , lowest)
print("Maximum: " , highest) |
def get_input():
"""gets the input from the user"""
user_input = input("Enter an ISBN: ")
return user_input
def input_to_list(the_input):
word_as_list = [item for item in the_input]
return word_as_list
def is_valid(input_as_list,LENGTH_OF_ISBN,PLACEHOLDER_POSITION):
if len(input_as_list) == LENGTH_OF_ISBN:#checks desired length
for index in PLACEHOLDER_POSITION:
if input_as_list[index] != "-":#checks if the placeholde ("-") is at the right place
return False
for number in range(LENGTH_OF_ISBN-1):
#Checks if the numbers are at the right places
if number not in PLACEHOLDER_POSITION:
try:
int(input_as_list[number])
except ValueError:
return False
return True
return False
def main():
LENGTH_OF_ISBN = 13 #A constant to change the desired length of ISBN with ease
PLACEHOLDER_POSITION = [1,5,11] #List to change the positions of placeholders with ease.
QUIT = "q"
valid = False
user_input = ""
"""the main function"""
while user_input != QUIT:
user_input = get_input()
word_as_list = input_to_list(user_input)
valid = is_valid(word_as_list,LENGTH_OF_ISBN,PLACEHOLDER_POSITION)
if valid:
print("Valid format!")
elif user_input != QUIT:
print("Invalid format!")
#The main function is executed.
main()
def open_file(filename):
''' Returns a file stream if filename found, otherwise None '''
try:
file_stream = open(filename, "r")
return file_stream
except FileNotFoundError:
return None
def get_winning_numbers(NUMBERS_IN_LOTTO_ROW, HIGHEST_VALID_NUMBER):
"""askes for the winning numbers and makes sure they are valid."""
winning_numbers = input("Enter winning numbers: ")
test_list = winning_numbers.split()
if len(test_list) != NUMBERS_IN_LOTTO_ROW:
return False
for numbs in test_list:
try:
numbs = int(numbs)
except ValueError:
return False
if numbs > HIGHEST_VALID_NUMBER or numbs < 1:
return False
return test_list
def check_if_won(the_file_list,the_winning_numbers_list):
"""Checks if each line has winning numbers and adds a star next to winning numbers"""
answer = []
for lines in the_file_list:
current_line_answer = ""
lotto_numbers = lines.split()#splits the lines into a list of values
for value in lotto_numbers:
if value in the_winning_numbers_list: # if the value is a winning number, put a star next to it
current_line_answer += str(value)+ "* "
else:
current_line_answer += str(value) + " "
answer.append(current_line_answer)
return answer #one list containing the answers to each line.
def print_answer(answer):
for lines in answer:
print(lines)
def main():
"""the main function"""
#You can change the max numbers in a lotto row and the highest valid number with these constants:
NUMBERS_IN_LOTTO_ROW = 5
HIGHEST_VALID_NUMBER = 40
file_name = input("Enter file name: ")
a_file = open_file(file_name)
#if file is found proceed, else return an error message.
if a_file:
winning_numbers = get_winning_numbers(NUMBERS_IN_LOTTO_ROW, HIGHEST_VALID_NUMBER)
if winning_numbers:
to_print = check_if_won(a_file,winning_numbers) #compares the numbers in the file to the winning numbers and puts a star where they match
print_answer(to_print)#prints the results of each line
else:
print("Winning numbers are invalid!")
a_file.close #Always close a file when done using it.
#prints the error message if the file is not found.
else:
print("File {} not found!".format(file_name))
#Main program executed.
main()
class Distribution:
def __init__(self,other = None):
#if fed a data stream, creates a dictionary out of the information
if other:
the_file = other.read()
file_stream_list = the_file.split()
keys = set(file_stream_list)
key_list = list(keys)
key_list.sort()
for keys in range(len(key_list)):
key_list[keys] = int(key_list[keys])
the_dict = {}
for key_number in range(len(key_list)):
key_amount = 0
for a_number in file_stream_list:
if int(a_number) == key_list[key_number]:
key_amount +=1
the_dict.update({key_list[key_number]:key_amount})
self.__distribution = the_dict
else: # if not fed anything, self.__distribution becomes None
self.__distribution = other
def set_distribution(self, distribution):
#allows user to change the value of self.__distribution
self.__distribution = distribution
def average(self):
#finds the average by multiplying every number by its counter and then devided by the sum of all the counters
average = 0
total_numbers = 0
current_value = 0
if self.__distribution != None:
for each in self.__distribution:
current_value += (self.__distribution[each])*each
total_numbers += self.__distribution[each]
average = current_value/total_numbers
return average
def __ge__(self, other):
#allows you to compare two instances of this class by comparing their average.
return self.average() >= other.average()
def __add__(self,other):
#allows you to add to gether two instances of the class by creating merging the dicts in self.__distribution and other.__distribution into a new dict
#then returns a new instance of itself with the new dict as self.__distribution.
temp_list = []
temp_dict = {}
#merging the dicts:
for each in other.__distribution:
if each in self.__distribution:
self.__distribution[each] += other.__distribution[each]
else:
self.__distribution.update({each:other.__distribution[each]})
for each in self.__distribution:
temp_list.append([each,self.__distribution[each]])
temp_list.sort()
for each in temp_list:
temp_dict.update({each[0]:each[1]})
self.__distribution = temp_dict
#returns a new instance of itself:
return self
def __str__(self):
#delivers the data in self.__distribution as a neat string.
string = ""
if self.__distribution != None:
for each in self.__distribution:
string += ("{}: {}\n".format(each,self.__distribution[each]))
return string |
def open_file(filename):
''' Returns a file stream if filename found, otherwise None '''
try:
file_stream = open(filename, "r")
return file_stream
except FileNotFoundError:
return None
def get_winning_numbers(NUMBERS_IN_LOTTO_ROW, HIGHEST_VALID_NUMBER):
"""askes for the winning numbers and makes sure they are valid."""
winning_numbers = input("Enter winning numbers: ")
test_list = winning_numbers.split()
if len(test_list) != NUMBERS_IN_LOTTO_ROW:
return False
for numbs in test_list:
try:
numbs = int(numbs)
except ValueError:
return False
if numbs > HIGHEST_VALID_NUMBER or numbs < 1:
return False
return test_list
def check_if_won(the_file_list,the_winning_numbers_list):
"""Checks if each line has winning numbers and adds a star next to winning numbers"""
answer = []
for lines in the_file_list:
current_line_answer = ""
lotto_numbers = lines.split()#splits the lines into a list of values
for value in lotto_numbers:
if value in the_winning_numbers_list: # if the value is a winning number, put a star next to it
current_line_answer += str(value)+ "* "
else:
current_line_answer += str(value) + " "
answer.append(current_line_answer)
return answer #one list containing the answers to each line.
def print_answer(answer):
for lines in answer:
print(lines)
def main():
"""the main function"""
#You can change the max numbers in a lotto row and the highest valid number with these constants:
NUMBERS_IN_LOTTO_ROW = 5
HIGHEST_VALID_NUMBER = 40
file_name = input("Enter file name: ")
a_file = open_file(file_name)
#if file is found proceed, else return an error message.
if a_file:
winning_numbers = get_winning_numbers(NUMBERS_IN_LOTTO_ROW, HIGHEST_VALID_NUMBER)
if winning_numbers:
to_print = check_if_won(a_file,winning_numbers) #compares the numbers in the file to the winning numbers and puts a star where they match
print_answer(to_print)#prints the results of each line
else:
print("Winning numbers are invalid!")
a_file.close #Always close a file when done using it.
#prints the error message if the file is not found.
else:
print("File {} not found!".format(file_name))
#Main program executed.
main() |
#!/usr/bin/env python
# coding: utf-8
import copy
def minor(A, i, j):
M = copy.deepcopy(A)
del M[i]
for i in range(len(A[0]) - 1):
del M[i][j]
return M
def det(A):
m = len(A)
n = len(A[0])
if m != n:
return None
if n == 1:
return A[0][0]
signum = 1
determinant = 0
for j in range(n):
determinant += A[0][j]*signum*det(minor(A, 0, j))
signum *= -1
return determinant
def calculate_determinant(list_of_lists):
'''
Метод, считающий детерминант входной матрицы,
если это возможно, если невозможно, то возвращается
None
Гарантируется, что в матрице float
:param list_of_lists: список списков - исходная матрица
:return: значение определителя или None
'''
# raise NotImplementedError
return det(list_of_lists)
|
from dna import *
import random
class Population(object):
def __init__(self, target, mutation_rate, max_pop):
self.target = target
self.mutation_rate = mutation_rate
self.max_pop = max_pop
self.population = []
self.buildPopulation()
def buildPopulation(self):
for i in range(self.max_pop):
chromosome = DNA(len(self.target))
self.population.append(chromosome)
def calculate_fitness(self):
self.score_total = 0
# calculate score total
for i in range(len(self.population)):
self.score_total += self.population[i].rate(self.target)
self.normalize() # normalize each score
return self.score_total
def normalize(self):
# normalization
for i in range(len(self.population)):
self.population[i].score /= self.score_total
def get_best(self):
best = self.population[0]
for i in range(1, len(self.population)):
if (best.score < self.population[i].score):
best = self.population[i]
return best
def create_offspring(self):
mating_pool = []
for i in range(len(self.population)):
parentA = self.select_random()
parentB = self.select_random()
child = self.perform_crossover(parentA, parentB)
mating_pool.append(child)
self.population = mating_pool
def perform_crossover(self, parentA, parentB):
split_idx = random.randint(1, len(parentA.data) - 1)
child = DNA(len(self.target))
child.data[:split_idx] = parentA.data[:split_idx]
child.data[split_idx:] = parentB.data[split_idx:]
# introduce variance
for i in range(len(self.target)):
if (random.random() < self.mutation_rate):
random_char = random.choice(string.ascii_letters)
child.data[i] = random_char
return child
""" select_random()
Returns a random element based on its
cooresponding score (or probability)
Args:
N/A
Returns:
DNA: The randomly selected by weight, element
"""
def select_random(self):
r = random.random()
upto = 0
for i in range(len(self.population)):
if upto + self.population[i].score >= r:
return self.population[i]
upto += self.population[i].score
|
""""Estructura de una aplicación MVC
Definición de Modelos
Modelo: Incluye todos los datos y su lógica relacionada.
Definicion de Vistas
Vista: presentar datos al usuario o manejar la interacción del usuario (entrega las entradas del usuario)
Definición de controladores
Controlador: una interfaz entre los componentes Modelo y Vista"""
class Course():
"""bluePrint of a course"""
def __init__(self, name, hours):
self.name = name
self.hours = hours
self.students = []
def addStudent(self, student):
self.students.append(student)
class Student():
"""bluePrint of a student"""
def __init__(self,studentId,name,age,gender):
self.studentId=studentId
self.name=name
self.age=age
self.gender=gender
print("Cod: {} \nNombre: {}\nEdad: {}\nGenero: {}".format(self.studentId,self.name,self.age,self.gender))
|
# !/usr/bin/env python
# -*-coding:utf-8 -*-
# Author: kr.r
"""
文件的序列化与反序列化
"""
import json
import requests
r = requests.get(url='http://www.weather.com.cn/data/sk/101190408.html')
print(r.content.decode('utf-8'))
print(type(r.content.decode('utf-8')))
# 对文件进行序列化--》就是把服务端数据写到文件中
# json.dump(r.content.decode('utf-8'),open('weather.json','w'))
# 对文件的反序列化:读取文件的内容
dict1 = json.load(open('weather.json')) # 读取json信息-->> str
print(type(dict1)) # <class 'str'>
dict2 = json.loads(dict1) # 反序列化
print(type(dict2)) # class 'dict'>
print(dict2)
|
tinta = float(input("Digite a área do local que desejar pintar(m^): "))
litros = tinta / 6
latas = litros / 18
galoes = litros / 3.6
preco_latas = latas * 80
preco_galoes = galoes * 25
print('Quantidade de latas eh: '+str(latas))
print('O preco total eh de: '+str(preco_latas))
print('O preco total eh de: '+str(preco_galoes)) |
country_a = 80000
country_b = 200000
while country_b > country_a:
print()
print('cA -> ' + str(country_a))
print('cB -> ' + str(country_b))
country_a = country_a + (country_a * 3/100)
country_b = country_b + (country_b * 1.5/100)
print()
print('cA -> ' + str(country_a))
print('cB -> ' + str(country_b)) |
n = int(input('Digite o numero: '))
str_number = str(n)
str_len = len(str_number)
str_len = str_len - 1
while str_len >= 0:
print(str_number[str_len], end='')
str_len = str_len - 1
print()
|
print("Digite dois 2 numeros inteiros: ")
n1 = int(input())
n2 = int(input())
print("Digite o numero real: ")
n3 = float(input())
result_a = (n1*2*2)+(n2/2)
result_b = (3*n1 + n3)
print("Questao a: "+str(result_a))
print("Questao b: "+str(result_b))
|
name = input('Digite o seu nome, caro padawan: ')
aux = ''
counter = len(name)
lista = []
while counter >= 0:
print(name[:counter], end='')
print()
counter = counter - 1
|
import sqlite3
conn = sqlite3.connect("dati.db")
cursor = conn.cursor()
fine_inserimento = False
while not fine_inserimento:
cid = input("id: ")
nome = input("nome: ")
peso = input("peso: ")
sql = f"insert into coffee "\
f"(id, nome, peso) values "\
f"({cid},'{nome}',{peso})"
print(sql)
cursor.execute(sql)
conn.commit()
ans = input("ancora? (s/n) :")
if not (ans == 's'):
fine_inserimento = True
conn.close()
|
class Node:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def __str__(self):
return str(self.data)
def isLeaf(self):
if self.left == None and self.right == None:
return True
else:
return False
def setLeft(self, lnode):
self.left = lnode
def setRight(self, rnode):
self.right = rnode
def visit(node):
print(node)
if node.isLeaf():
return
else:
if node.left is not None:
visit(node.left)
if node.right is not None:
visit(node.right)
n1 = Node(10)
n2 = Node(12)
n3 = Node(23)
n4 = Node(34)
n5 = Node(56)
n0 = Node(1, n1, n2)
n1.setLeft(n3)
n1.setRight(n4)
n2.setLeft(n5)
visit(n0)
|
#cerco un numero indicato dall'utente
src = input("che numero vuoi? ")
for n in range(0,100):
print "n = ", n
if n == src:
print "trovato"
break
print "fine loop"
|
# -*- coding: utf-8 -*-
import pandas as pd
# 读取txt文件
def read_txt_file(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
content = [_.strip() for _ in f.readlines()]
labels, texts = [], []
for line in content:
parts = line.split()
label, text = parts[0], ''.join(parts[1:])
labels.append(label)
texts.append(text)
return labels, texts
# 获取训练数据和测试数据,格式为pandas的DataFrame
def get_train_test_pd():
file_path = 'data/train.txt'
labels, texts = read_txt_file(file_path)
train_df = pd.DataFrame({'label': labels, 'text': texts})
file_path = 'data/test.txt'
labels, texts = read_txt_file(file_path)
test_df = pd.DataFrame({'label': labels, 'text': texts})
return train_df, test_df
if __name__ == '__main__':
train_df, test_df = get_train_test_pd()
print(train_df.head())
print(test_df.head())
train_df['text_len'] = train_df['text'].apply(lambda x: len(x))
print(train_df.describe())
|
"""
Class for Room
"""
class Room:
def __init__(self, room_id):
"""
Constructor for a room
Args:
room_id (string): the room's ID which is also its invite code
"""
self.room_id = room_id
self.controlled = []
self.controller = []
self.users = []
def add_controlled(self, user):
"""
Adds someone who will be getting their keyboard controlled
Args:
user (client.Client): the client to add
"""
self.controlled.append(user)
self.users.append(user)
def add_controller(self, user):
"""
Adds someone who will be controlling another's keyboard
Args:
user (client.Client): the client to add
"""
self.controller.append(user)
self.users.append(user)
def check_room_code(self, code):
"""
This isn't secure but that's ok
Args:
code (string): The code
Returns:
boolean: True if this is the same as the invite code, False otherwise
"""
return self.room_id == code
|
# -*- coding:utf-8 -*-
"""
Author :Yxxxb & Xubing Ye
Number :1953348
Date :2021/10/09
File :象限法实现.py
"""
import matplotlib.pyplot as plt
def drawline(x, y):
for i in range(len(x)):
plt.plot(x[i], y[i], color='r')
plt.scatter(x[i], y[i], color='b')
def tellLocation(x, y):
assert (x != 0 and y != 0)
if x > 0 and y > 0:
return 1
elif x < 0 and y > 0:
return 2
elif x < 0 and y < 0:
return 3
else:
return 4
def calChange(x, y):
if y[1] * x[0] - x[1] * y[0] > 0:
return 1
elif y[1] * x[0] - x[1] * y[0] > 0:
return -1
else:
return 0
def cal(x, y):
ans = 0
for i in range(len(x)):
Loc1 = tellLocation(x[i][0], y[i][0])
Loc2 = tellLocation(x[i][1], y[i][1])
if abs(Loc1 - Loc2) == 0:
pass
elif abs(Loc1 - Loc2) == 2:
ans = ans + calChange(x[i], y[i])
elif Loc1 - Loc2 == 1 or Loc1 - Loc2 == -3:
ans = ans - 0.5
else:
ans = ans + 0.5
assert (ans == 0 or ans == 1 or ans == 2)
explain = {
0: "在外部",
1: "在边界上",
2: "在内部"
}
return ans, explain.get(ans)
xList = [[2, -4], [-4, -4], [-4, 4], [4, 4], [4, -2], [-2, 2]]
yList = [[4, 4], [4, -4], [-4, -4], [-4, 2], [2, -2], [-2, 4]]
xList1 = [[4, -4], [-4, 1], [1, -2], [-2, 4], [4, 4]]
yList1 = [[4, 4], [4, 3], [3, -4], [-4, -4], [-4, 4]]
plt.scatter(0, 0, color='black')
drawline(xList, yList)
# plt.plot([-2, 0], [-2, 0], color='black', linestyle=':')
# plt.plot([0, 2], [0, 4], color='black', linestyle=':')
plt.plot([-5, 5], [0, 0], color='black', linestyle=':')
plt.plot([0, 0], [-5, 5], color='black', linestyle=':')
plt.show()
print(cal(xList, yList))
|
from block import Block
# This file defines the class for a Blockchain.
class Blockchain:
# Initiate a list that will contain all the blocks, initiate a list for any unconfirmed transactions,
# and create and add the genesis block to to list.
def __init__(self):
self.chain = []
self.unconfirmed_transactions = []
self.genesis_block()
# The .genesis_block() method creates the first block in the chain, with a previous hash of 0,
# and adds it as the first element of the list of blocks.
def genesis_block(self):
transactions = []
genesis_block = Block(transactions, "0")
genesis_block.generate_hash()
self.chain.append(genesis_block)
return self.chain
# The .add_block() method takes a dictionary containing transactions and appends the list of blocks
# in the blockchain.
def add_block(self, transactions):
previous_hash = (self.chain[len(self.chain)-1]).hash
new_block = Block(transactions, previous_hash)
new_block.generate_hash()
# proof = proof_of_work(block)
self.chain.append(new_block)
return new_block
# The .print_blocks() method displays all the blocks currently in the chain.
def print_blocks(self):
for i in range(len(self.chain)):
current_block = self.chain[i]
print("Block {} {}".format(i, current_block))
current_block.print_contents()
# The .validate_chain() method checks to see if every block in the chain was added in a valid way.
def validate_chain(self):
for i in range(1, len(self.chain)):
current = self.chain[i]
previous = self.chain[i-1]
if(current.hash != current.generate_hash()):
print("Current hash does not equal generated hash")
return False
if(current.previous_hash != previous.generate_hash()):
print("Previous block's hash got changed")
return False
return True
# The .proof_of_work() method can be used to determine the difficulty of the hash function.
def proof_of_work(self, block, difficulty=2):
proof = block.generate_hash()
while proof[:2] != "0"*difficulty:
block.nonce += 1
proof = block.generate_hash()
block.nonce = 0
return proof
|
def say_hi(name,age):
print("Hello "+name+", you are "+age +" years old.")
name = input("Enter your name: ")
age = input("Enter your age: ")
say_hi(name,age)
#say_hi("Professor",10) --> because in say_hi fucntion age is taken as string but for int it is not typecasted to string
say_hi("Professor","10")
|
name = "Janit Lodha"
print(name)
print("Janit\Lodha")
print("Janit\nLodha")
#Concatenation
print(name + " is a student of IIITA")
#Functions
print(name.lower())
print(name.upper())
print((name.upper()).isupper())
print(len(name))
print(name.index('ni'))
print(name.replace("Janit","Ashok"))
#Accessing elements using indices
print(name[0])
print(name[0].lower())
print(name[3])
print(name[9]) |
#Append Mode
company_designations = open("Employees.txt","a")
#Checking the writability
print(company_designations.writable())
#Appending text in document
company_designations.write("\nPrateek - Human Resources")
company_designations.close()
#Overriding By Write Mode
company_designations = open("Employees.txt","w")
company_designations.write("This is the first line of Employees.txt file")
company_designations.close()
#Finally reading out the file
company_designations = open("Employees.txt","r")
print(company_designations.read())
company_designations.close()
|
import sqlite3
import sys
conn = sqlite3.connect('./mydb.db')
cursor = conn.cursor()
#cursor.execute("DROP TABLE matrix")
#create a table
cursor.execute("""
CREATE TABLE IF NOT EXISTS matrix
(/*id int AUTO_INCREMENT NOT NULL PRIMARY KEY UNIQUE, */
row_num int,
col_num int,
value int)
""")
#insert multiple records using the more secure "?" method
"""values = [(0, 1, 2),
(0, 2, -1),
(1, 0, 1),
(1, 1, 1),
(1, 2, 2),
(2, 0, 1),
(2, 2, 3)]
"""
values = [(0, 1, 2),
(0, 2, -1),
(1, 0, 1),
(2, 2, -3)]
cursor.executemany("INSERT INTO matrix VALUES(?, ?, ?)", values)
conn.commit()
|
def IsDigit(a):
x = int(a) #input("Enter your number")
if (x / 1 == x):
return ("Yes")
def IsPossitive(a):
x = a
if (int(x) >= 0):
return ("Yes")
def checkBin(a):
p = set(a)
s = {'0', '1'}
if s == p or p == {'0'} or p == {'1'}:
return ("Yes")
else:
return ("No")
a = input("inter a unsigned number:")
def all(a):
if (IsDigit(a == True)):
if (IsPossitive(a == True)):
if (checkBin(a) == 'Yes'):
return " This is an unsigned (integer or real) number"
else:
return (" this is not an unsigned (integer or real) number")
else:
return (" this is not an unsigned (integer or real) number")
else:
return (" this is not an unsigned (integer or real) number")
print(all(a))
|
# coding:utf-8
"""
经典排序算法 - 地精排序Gnome Sort
号称最简单的排序算法,只有一层循环,默认情况下前进冒泡,
一旦遇到冒泡的情况发生就往回冒,直到把这个数字放好为止
java代码:
static void gnome_sort(int[] unsorted)
{
int i = 0;
while (i < unsorted.Length)
{
if (i == 0 || unsorted[i - 1] <= unsorted[i])
{
i++;
}
else
{
int tmp = unsorted[i];
unsorted[i] = unsorted[i - 1];
unsorted[i - 1] = tmp;
i--;
}
}
}
"""
def gnome_sort(input_list):
i = 0
while i < len(input_list):
if i == 0 or input_list[i-1] <= input_list[i]:
i += 1
else:
input_list[i-1], input_list[i] = input_list[i], input_list[i-1]
i -= 1
return input_list
print(gnome_sort([6, 2, 4, 1, 5, 9]))
|
# Edgar Castillo / Github: https://github.com/hellocastillo
# Copyright (c) 2021 Edgar Castillo
# The Blueprint for recursion
"""
def recursionMethod(parameters):
if exit from condition satisfied:
return some Value
else:
recursionMethod(modified parameters)
"""
# How the Recursion works
def firstMethod(): # First then second
secondMethod()
print("I am the first Method") # Print 1st method
def secondMethod(): # Second then third
thirdMethod()
print("I am the second Method") # Print 2nd method
def thirdMethod(): # Third then fourth
fourthMethod()
print("I am the third Method") # Print 3rd method
def fourthMethod(): # Finally last
print("I am the fourth Method") # end of the algorithm
# Example
def recursiveMethod(n):
if n<1:
print("n is less than 1")
else:
recursiveMethod(n-1)
print(n)
# Visual of Example^
# recursiveMethod(4) > recursiveMethod(3) then,
# recursiveMethod(3) > recursiveMethod(2) then,
# recursiveMethod(2) > recursiveMethod(1) then,
# recurisveMethod(1) > recursiveMethod(0)
# then, go in reverse till recursiveMethod(4).
|
# Komment
class Base(object):
"""A Base is the underlying construct of the other classes defined here"""
# A Base can be created
def __init__(self):
# A Base has a Name
self.name = None
# A Base contains something
self.contains = None
# What else is Common Amongst ALL?
# A Base can create something to contain
def create(self):
"""This function is supposed to create something this will then
contain."""
print "Not yet defined, go and do so!"
pass
# A Base can list whatever it contains
def list(self):
"""This function is supposed to list whatever this contains."""
print "Not yet defined, go and do so!"
pass
# A Base can be delete something it contains
def delete(self):
"""This function is supposed to delete something this contains."""
print "Not yet defined, go and do so!"
# A base can show what it contains
def show(self):
"""This function will show everything it contains."""
print "Not yet defined, go and do so!"
#May be defined here!!
class Node(Base):
"""A Node is a bit of Information, that may be a Theorem an Equation or
just an Idea; transferable to other fields, too """
# A Node is contained in a Network
# A Node is linked to other Nodes
# A Node may be contained in Clusters.
# A if a Node is connected to a Node within a Cluster it is connected to
# that, too.
pass
class Connection(Base):
"""A Connection signifies a Link between to Nodes, that may be an
argumentation, or simply a relationship between the two."""
# A Connection can exist:
# between a Node and a Node
# between a Node and a Cluster
pass
class Network(Base):
"""A Network is a collection of Nodes,
Connections and Clusters, it's the overarching structure of my project"""
# A Network contains:
# Nodes
# Clusters
# A Network can:
# create : Nodes and Clusters
# create : Connections between:
# Nodes and Nodes
# Nodes and Clusters
# Clusters and Clusters
# list : Nodes and Clusters it contains
# see : Connections between:
# all its Nodes and Clusters
# only its Nodes and Nodes
# only its Clusters and Clusters
# only its Nodes and Clusters
# delete : Nodes and Clusters it contains
# remove : Connections between any of its Contingents
pass
class Cluster(Network, Node):
"""A Cluster is a Node that also is a Network,
representing an entity within the Network.
All Nodes with Connections to Nodes within a Cluster have a Connection to
the Cluster as well."""
# A Cluster is a Network and a Node
# What else?
passs
|
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
begin = 0
end = len(nums) - 1
while begin <= end:
mid = int((begin + end) / 2)
if nums[mid] == target:
return mid
if nums[begin] <= nums[mid]:
if target < nums[mid] and target >= nums[begin]:
end = mid - 1
else:
begin = mid + 1
continue
if nums[mid] <= nums[end]:
if target > nums[mid] and target <= nums[end]:
begin = mid + 1
else:
end = mid - 1
continue
return -1
if __name__ == '__main__':
S = Solution()
print(S.search([4,5, 6, 7, 0, 1, 2], 2)) |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def flatten(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
self.flattern2(root)
def flattern2(self, node):
if not node:
return None
if not node.left and not node.right:
return node
left = self.flattern2(node.left)
right = self.flattern2(node.right)
node.right = left
while left and left.right:
left = left.right
if left:
left.right = right
else:
node.right = right
node.left = None
return node
if __name__ == '__main__':
S = Solution()
a1 = TreeNode(1)
a2 = TreeNode(4)
a3 = TreeNode(2)
a4 = TreeNode(11)
a5 = TreeNode(13)
a6 = TreeNode(4)
a7 = TreeNode(7)
a8 = TreeNode(2)
a9 = TreeNode(5)
a10 = TreeNode(1)
# a1.left = a2
a1.left = a3
# a2.left = a4
# a3.left = a5
# a3.right = a6
# a4.left = a7
# a4.right = a8
# a6.left = a9
# a6.right = a10
S.flatten(a1)
print(a1) |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
path1 = []
path2 = []
self.find_path(root, p, path1)
self.find_path(root, q, path2)
i = 0
j = 0
ancestor = None
while 1:
if i >= len(path1) or j >= len(path2):
break
if path1[i] == path2[j]:
ancestor = path1[i]
i += 1
j += 1
return ancestor
def find_path(self, node, p, path):
if not node:
return False
path.append(node)
if node == p:
return True
if not node.left and not node.right:
del path[-1]
return False
a = self.find_path(node.left, p, path)
if a:
return True
b = self.find_path(node.right, p, path)
if b:
return True
del path[-1]
return False
if __name__ == '__main__':
S = Solution()
a1 = TreeNode(5)
a2 = TreeNode(4)
a3 = TreeNode(8)
a4 = TreeNode(11)
a5 = TreeNode(13)
a6 = TreeNode(4)
a7 = TreeNode(7)
a8 = TreeNode(2)
a9 = TreeNode(5)
a10 = TreeNode(1)
a1.left = a2
a1.right = a3
a2.left = a4
a3.left = a5
a3.right = a6
a4.left = a7
a4.right = a8
a6.left = a9
a6.right = a10
print(S.lowestCommonAncestor(a1, a5, a9).val) |
import random
from options import options
from utils import dictobj
class Gene(object):
"""
A gene represents a single allele.
Once created, it's value never changes
"""
def __init__(self, value=None):
if self.__class__ == Gene:
if random.random() < options.multi_chance:
self.__class__ = Multiplier
else:
self.__class__ = Constant
if value:
self.value = value
else:
self.value = self.random_value()
def reproduce(self):
if random.random() < options.mutation_rate:
return self.__class__(self._mutate())
return self
def random_value(self):
raise NotImplementedError
def _mutate(self):
raise NotImplementedError
def __str__(self):
return "%s(%1.1f)" % (self.str_symb, self.value)
def __repr__(self):
return "%s(%f)" % (self.str_symb, self.value)
class Constant(Gene):
str_symb = "C"
def random_value(self):
return random.random() * options.constant_max_init
def _mutate(self):
mutate_val = self.value + options.constant_mutation_depth * (2 * random.random() - 1)
return max(0, mutate_val)
class Multiplier(Gene):
str_symb = "M"
def random_value(self):
return random.random() * options.multi_max_init
def _mutate(self):
mutate_val = self.value + options.multi_mutation_depth * (2 * random.random() - 1)
return max(0, mutate_val)
gene_types = [Constant, Multiplier]
class Genome(object):
"""
A genome is a group of genes - two of each type.
It is all the genetic information that a creature would have
"""
def __init__(self, ploid_a, ploid_b):
if ploid_a.keys() != ploid_b.keys():
raise Exception("chromosome mismatch. You'd have a mule")
self.chromosome = {trait: (ploid_a[trait], ploid_b[trait])
for trait in ploid_a.keys()}
@classmethod
def random(cls, traits):
ploid_a = {trait:Gene() for trait in traits}
ploid_b = {trait:Gene() for trait in traits}
return cls(ploid_a, ploid_b)
def make_phenotype(self):
phenotype_values = {trait: self.combine(*genes)
for trait, genes in self.chromosome.iteritems()}
return Phenotype(**phenotype_values)
def make_gamete(self):
return {trait: random.choice(genes).reproduce()
for trait, genes in self.chromosome.iteritems()}
@staticmethod
def combine(genea, geneb):
"""
Use Randall Monroe's gene mutlplier/constant system.
He inspired this program
"""
if type(genea) == Constant and type(geneb) == Constant:
return max(genea.value, geneb.value)
elif type(genea) == Multiplier and type(geneb) == Multiplier:
return 1
elif type(genea) == Constant and type(geneb) == Multiplier or \
type(genea) == Multiplier and type(geneb) == Constant:
return genea.value * geneb.value
raise Exception("Should never reach this point - unknown gene type")
def mutate(self):
ploid_a = {}
ploid_b = {}
for trait, genes in self.chromosome.iteritems():
ploid_a[trait] = genes[0].reproduce()
ploid_b[trait] = genes[1].reproduce()
return Genome(ploid_a, ploid_b)
def __str__(self):
chromosome_str = ", ".join(["%s : %s/%s" % (trait, genes[0], genes[1])
for trait, genes in self.chromosome.iteritems()])
return "Genome: {%s}" % chromosome_str
class Phenotype(dictobj):
pass
|
"""
Queues Python Introduction
As previously mentioned, a queue is a data structure that contains an ordered set of data that follows a
FIFO (first in, first out) protocol. You can visualize it as a line at a deli:
The customer at the front of the line (equivalent to the head in a queue) is the first customer to get served
Any new customer must go to the back of the line (the tail of the queue) and wait until everyone in front of them
has been served (no line cutters allowed in this deli!)
The deli server only needs to know about the current order
Now, we can use Python to build out a Queue class with those three essential queue methods:
enqueue() which will allow us to add a new node to the tail of the queue
dequeue() which will allow us to remove a node from the head of the queue and return its value
peek() which will allow us to view the value of head of the queue without returning it
We’ll also set up a few helper methods that will help us keep track of the queue size in order to prevent
queue “overflow” and “underflow.”
Ready, set, queue up!
"""
class Queue:
def __init__(self):
self.head = None
self.tail = None
def peek(self):
return self.head.get_value()
|
"""
Queues Python Size
Bounded queues require limits on the number of nodes that can be contained, while other queues don’t. To account for
this, we will need to make some modifications to our Queue class so we can keep track of and limit size where needed.
We’ll be adding two new properties to help us out here:
A size property to keep track of the queue’s current size
A max_size property that bounded queues can utilize to limit the total node count
In addition, we will add three new methods:
get_size() will return the value of the size property
has_space() will return True if the queue has space for another node
is_empty() will return true if the size is 0
"""
class Queue:
def __init__(self, max_size=None):
self.head = None
self.tail = None
self.max_size = max_size
self.size = 0
def peek(self):
if not self.is_empty():
return self.head.get_value()
print('Error: queue empty')
def get_size(self):
return self.size
def has_space(self):
if self.max_size is None:
return True
return self.size < self.max_size
def is_empty(self):
return self.size == 0
|
#Write a python function stats() that takes name of text file as an argument. The function
#should print the number of lines, words, and characters in the file. For example,
#>>>stats('example.txt')
#Line count: 3
#Word count: 20
#Character count: 98
def stat(txt):
num_lines = 0
num_words = 0
num_chars = 0
with open(txt, 'r') as f:
for x in f.readlines():
words = x.split()
num_lines += 1
num_words += len(words)
num_chars += len(x)-1
print("Line count:",num_lines)
print("Word count:",num_words)
print("Character count:",num_chars)
stat("2.1a.py")
|
#(b) Write a python program to implement a class called Adder that exports a method
#add(self, x, y) that prints a “Not Implemented” message. Then define two subclasses of Adder that implement the add method:
#1. ListAdder, with an add method that returns the concatenation of its two list argu¬ments
#2. DictAdder, with an add method that returns a new dictionary with the items in both its two dictionary arguments.
#3. Overload the + operator
class Adder:
def add(self,x,y):
print("Not Implemented")
def __init__(self,start=[]):
self.data=start
def __add__(self,other):
self.data=self.data+other
print(self.data)
def __radd__(self,other):
return self.add(self.data,other)
class listadder(Adder):
def add(self,x,y):
return x+y
class dictadder(Adder):
def add(self,x,y):
new={}
for k in x.keys():
new[k]=x[k]
for k in y.keys():
new[k]=y[k]
return new
x=Adder()
print(x.add(1,2))
x=listadder()
print(x.add([1],[2]))
x=dictadder()
print(x.add({"a":"1"},{"b":"2"}))
x=Adder([1])
print(x+[3])
x=listadder([1])
print(x+[8])
print([2]+x)
|
import sqlite3
class Database:
def __init__(self,db):
self.conn = sqlite3.connect(db)
self.cur = self.conn.cursor()
self.cur.execute("CREATE TABLE IF NOT EXISTS std (id INTEGER PRIMARY KEY, usn TEXT, name TEXT, mobile INTEGER, branch TEXT)")
self.conn.commit()
def insert(self,usn, name, mobile, branch):
#the NULL parameter is for the auto-incremented id
self.cur.execute("INSERT INTO std VALUES(NULL,?,?,?,?)", (usn,name,mobile,branch))
self.conn.commit()
def view(self):
self.cur.execute("SELECT * FROM std")
rows = self.cur.fetchall()
return rows
def search(self,usn="", name="", mobile="", branch=""):
self.cur.execute("SELECT * FROM std WHERE usn = ? OR name = ? OR mobile = ? OR branch = ?", (usn, name, mobile, branch))
rows = self.cur.fetchall()
#conn.close()
return rows
def delete(self,id):
self.cur.execute("DELETE FROM std WHERE id = ?", (id,))
self.conn.commit()
#conn.close()
def update(self,id, usn, name, mobile, branch):
self.cur.execute("UPDATE std SET usn = ?, name = ?, mobile = ?, branch = ? WHERE id = ?", (usn, name, mobile, branch, id))
self.conn.commit()
#destructor-->now we close the connection to our database here
def __del__(self):
self.conn.close()
|
import sys
wyrazenie_lista = []
nawias_l = []
OPERATORY = ('+', '-', '*', '%')
POZ_OPER = (('*', '%'), ('-'), ('+'))
def main():
print("\t\t\t\t\t PROSTY KALKULATOR")
print("""
Ten prosty kalkulator wykonuje podstawowe operacje:
- mnożenie;
- dzielenie modulo;
- dodawanie;
- odejmowanie
Posiada 'zabezpieczenia':
- wstawisz dwa operatory obok siebie - wywali błąd i obliczy głupoty
- zapomnisz nawiasu - wywali błąd
Jeśli chcesz użyc liczby ujemnej daj ją w nawias.\n""")
print("\tPrzykład:")
print("\t 2+2*2 =", end=" ")
print(zadanie("2+2*2"))
print("\t(2+2)*2 =", end=" ")
print(zadanie("(2*2)*2"))
print("\t(2+2)*2+9%2*8+2-3+(-3) =", end=" ")
print(zadanie("(2+2)*2+9%2*8+2-3+(-3)"), "\n")
zadanie_uzytkownika()
def parser(wyrazenie):
error = 0
for c in wyrazenie:
if c == '(':
error += 1
elif c == ')':
error -= 1
if error != 0:
sys.exit("Błąd składniowy - brak nawiasu")
else:
f_nawias = False
f_operatora = False
f_cyfry = False
for c in wyrazenie:
try:
znak = int(c) # sprawdz czy znak jest cyfrą
f_operatora = False
if f_cyfry: # jeśli jest to kolejna cyfra liczby
dodaj_cyfre(znak, f_cyfry, f_nawias)
else:
dodaj_cyfre(znak, f_cyfry, f_nawias)
f_cyfry = True
except ValueError:
f_cyfry = False # to jest operator
if c in OPERATORY:
if c == '-' and f_nawias == True:
f_operatora = False
if f_operatora:
sys.exit("NIELEGALNE WYRAŻENIE")
else:
dodaj_znak(c, f_nawias)
f_operatora = True
if c == '(':
f_nawias = True
if c == ')':
f_nawias = False
w_nawias()
def oblicz(lista):
while len(lista) > 1:
for op in range(len(POZ_OPER)):
for el in range(len(lista)):
try:
if str(lista[el]) in POZ_OPER[op]:
rezultat = operacje(lista, el, lista[el])
del lista[el - 1]
del lista[el - 1]
del lista[el - 1]
lista.insert(el - 1, rezultat)
except IndexError:
break
return lista[0]
def dodaj_cyfre(cyfra, flaga, nawias):
if nawias == 0:
if flaga == 0: # jesli jest to pierwsza cyfra wyrażenia
wyrazenie_lista.append(cyfra)
else:
index = len(wyrazenie_lista)
liczba = wyrazenie_lista[index - 1] * 10 + cyfra
wyrazenie_lista.insert(index - 1, liczba)
del wyrazenie_lista[index]
else:
if flaga == 0:
nawias_l.append(cyfra)
else:
index = len(nawias_l)
liczba = nawias_l[index - 1] * 10 + cyfra
nawias_l.insert(index - 1, liczba)
del nawias_l[index]
def dodaj_znak(znak, nawias):
if nawias == 0:
if wyrazenie_lista == []: wyrazenie_lista.append(0)
wyrazenie_lista.append(znak)
else:
if nawias_l == []: nawias_l.append(0)
nawias_l.append(znak)
def operacje(lista, index, op):
x = lista[index - 1]
y = lista[index + 1]
if op == '+':
x += y
elif op == '-':
x -= y
elif op == '*':
x *= y
elif op == '%':
x %= y
return x
def w_nawias():
oblicz(nawias_l)
wyrazenie_lista.append(nawias_l[0])
del nawias_l[0]
def zadanie(tekst):
parser(''.join(tekst.split()))
wynik = oblicz(wyrazenie_lista)
wyrazenie_lista.pop()
return wynik
def zadanie_uzytkownika():
print("Aby zakończyć wciśnij ENTER")
uzytkownik = input("wpisz wyrazenie(zatwierdz ENTEREM):")
while uzytkownik != '':
print("wynik =", zadanie(uzytkownik))
uzytkownik = input("wpisz wyrazenie(zatwierdz ENTEREM):")
if uzytkownik == '':
print("\nTo już koniec \nDziękuję za zabawe :)")
main()
|
# conda_python3_code
from tkinter import *
def callback():
print (u"你好~")
def popup(event):
menubar.post(event.x_root,event.y_root)
root = Tk()
menubar=Menu(root)
menubar.add_command(label="撤销",command=callback)
menubar.add_command(label="重做",command=root.quit)
frame=Frame(root,width=300,height=300)
frame.pack()
# MAC is button-2 to define the right-click
frame.bind("<Button-2>",popup)
mainloop() |
# conda_python3_code
from tkinter import *
from PIL import Image,ImageTk
# PIL is used for decode the JPG PNG format
# Clear text display
# def show():
# print('Your name is %s'% e1.get())
# print('Your id is %s'% e2.get())
# root = Tk()
#
# Label(root,text='name:').grid(row=0,column=0)
# Label(root,text='ID:').grid(row=1,column=0)
#
# e1 = Entry(root)
# e2 = Entry(root)
# e1.grid(row=0,column=1,padx=5,pady=5)
# e2.grid(row=1,column=1,padx=5,pady=5)
#
# Button(root,text='Confirm',width=10,command=show).grid(row=3,column=0,sticky=W,padx=10,pady=5)
# Button(root, text='Exit', width=10, command=root.quit).grid(row=3,column=1,sticky=E,padx=10,pady=5)
#
# mainloop()
# Secret text display
def show():
print('Your ID is %s'% e1.get())
print('Your password is %s'% e2.get())
root = Tk()
Label(root,text='ID:').grid(row=0,column=0)
Label(root,text='password:').grid(row=1,column=0)
v1 = StringVar()
v2 = StringVar()
e1 = Entry(root,textvariable=v1)
e2 = Entry(root,textvariable=v2,show='*')
e1.grid(row=0,column=1,padx=5,pady=5)
e2.grid(row=1,column=1,padx=5,pady=5)
Button(root,text='Confirm',width=10,command=show).grid(row=3,column=0,sticky=W,padx=10,pady=5)
Button(root, text='Exit', width=10, command=root.quit).grid(row=3,column=1,sticky=E,padx=10,pady=5)
mainloop() |
# conda_python3_code
from tkinter import *
# panedwindow is the advanced func of pack.
# showhandle means the control line of panedwindow
m1 = PanedWindow(showhandle=True,sashrelief=SUNKEN)
m1.pack(fill=BOTH,expand=1)
left = Label(m1,text="left pane")
m1.add(left)
m2 = PanedWindow(orient=VERTICAL,showhandle=False,sashrelief=SUNKEN)
m1.add(m2)
top = Label(m2,text="top pane")
m2.add(top)
bottom = Label(m2,text="bottom pane")
m2.add(bottom)
mainloop() |
from array import array
array_num = array('i', [4,3,6,3,1,2,2,3,3])
print("Original array: "+str(array_num))
print("Number of occurrences of the number 3 in the said array: "+str(array_num.count(3))) |
#numberlist = ['1','5','8','3']
#value1 = True
numberlist = list(input("Please Enter numbers "))
numbers = input("Please Enter number ")
if numbers in numberlist:
print("True")
else:
print("False")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.