blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
62527a4a9a630027054825f3d25a4dc9ed90fb4f | xiaoluome/algorithm | /Week_01/id_34/leetcode-189.py | 1,620 | 3.859375 | 4 | from typing import List
class Solution:
# 重伤, 提交代码说是执行时间过长 43333333
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
n = len(nums)
if n == 0 or n == 1:
return
if k > n:
k = k % n
for i in range(k):
temp = nums[n - 1]
for j in range(n - 1, 0, -1):
nums[j] = nums[j - 1]
nums[0] = temp
# 和上面一样, 180 ms, 13.5 MB
def rotate2(self, nums: List, k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
n = len(nums)
if n == 0 or n == 1:
return
if k > n:
k = k % n
for _ in range(k):
nums.insert(0, nums.pop())
# 反转法, 72 ms, 13.2 MB
def rotate3(self, nums: List, k: int) -> None:
n = len(nums)
if n == 0 or n == 1:
return
if k > n:
k = k % n
self.reverse(nums=nums, s=0, end=n-1)
self.reverse(nums=nums, s=0, end=k-1)
self.reverse(nums=nums, s=k, end=n-1)
def reverse(self, nums: List, s: int, end: int):
while end > s:
nums[end], nums[s] = nums[s], nums[end]
end -= 1
s += 1
# 根据索引, 64 ms, 13.2 MB
def rotate4(self, nums: List, k: int) -> None:
n = len(nums)
if n == 0 or n == 1:
return
if k > n:
k = k % n
nums[:] = nums[-k:] + nums[:-k] |
4b11ba24810fbcf5f61b3b635630e384f3189475 | tarunlalchandani/DjangoPython | /pythonLoops.py | 213 | 4.03125 | 4 | KrsnaNames = {"Mukunda","Govinda","Tirupati"}
print(KrsnaNames)
print(KrsnaNames)
for name in KrsnaNames:
print(name)
age = 20
while(age<30):
print("Hare Krsna")
age += 1
for i in range(3,9):
print(i)
|
9e3b4c6752b313508a6ec04c073502b57ab5fe62 | Raman5837/Talking-Dictionary | /main.py | 10,454 | 3.671875 | 4 | from os import close
from tkinter import *
from tkinter import messagebox # to use it in iexit() function.
import json
from difflib import get_close_matches
import pyttsx3
# to initiate python text-to-speech class, we'll create a object of this class.
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
# we can set volume of the voice and volume ranges from 0.0 to 1.0
# we can set rate of speech(word speak in 1 minute) by default it is 200 wpm.
rate = engine.getProperty('rate')
engine.setProperty('rate', 150)
def speakWord():
engine.say(entry_field.get())
engine.runAndWait()
def speakMeaning():
engine.say(textField.get(1.0, END))
engine.runAndWait()
def iexit(): # this iexit() function is used as a command inside exitButton. to exit the window.
result = messagebox.askyesno('Confirm', 'Do you want to exit?') # yes button will return True and No button will return False. and these value will be stored in result variable.
if result == True:
root.destroy() # to close the window.
else:
pass # it will do nothing.
def clearText(): # this function is used in clearButton as a command to clear all the text.
# whatever text present in entry_field and textField will be deleted.
# again making the state normal(enabled) because we are clearing the text inside textField
textField.config(state = NORMAL)
entry_field.delete(0, END) # form 0th position to end position.
textField.delete(1.0, END) # why 1.0 ? => may be this is second text field that's why 1.0.
textField.config(state = DISABLED)
def searchMeaning(): # this function is used in searchButton as a command to search the meaning of the given word.
# we'll use data.json file searching the meaning. data.json contains data in form of dictionary, in which word are in form of key and their meaning are in form of value of that key.
data = json.load(open('data.json'))
inputWord = entry_field.get()
inputWord = inputWord.lower()
if inputWord in data: # if the given word is present in data(data variable contain data.json file), do the below
# textField.insert(END, data[inputWord]) # insert the meaning of given word. we are accessing value for the given key from dict.
# to print the result in seperate line and without curly braces (of dict.)
meaning = data[inputWord]
# again making the state normal(enabled) because we are inserting the text inside textField
textField.config(state = NORMAL)
# just before adding the meaning, we'll delete if any text is present in textField.
textField.delete(1.0, END)
# Now we'll add meaning on the textField.
for item in meaning: # meaning is a list here containing multiple item and we have to access each item in a new line.
textField.insert(END, u'\u2022 ' + item + '\n\n') # 2022 is code to create a bullet symbol. u is for string. \n\n is for new line after each complete sentence.
# we'll disable the state of textField so that no one can edit the textField, else user can change the text present inside textField
textField.config(state = DISABLED)
# what if user enterd a word which is not correct, we'll provide a close match for that word. by using close match module which is present in difflib package.
# ''' How get_close_matches() works.?
# it takes 4 arguments , 2 compulsary and 2 optional
# get_close_matches(
# 1st argument -> 'the wrong word for which we want close matches',
# 2nd argument ->'a list from which it'll search for close matches',
# 3rd argument -> we will give n value. eg- n = 3 , then it'll give max 3 answers.,
# 4th argument -> cutoff = 0.6 # by default cutoff value is 0.6. cutoff value lies between 0.0 to 1.0 , value closer to 1.0 will give more accurate result.)
# '''
elif len(get_close_matches(inputWord, data.keys(), n = 1, cutoff = 0.8)) > 0: # if the close matches list contains atleast 1 word then lenth will be greater than 0
close_match = get_close_matches(inputWord, data.keys(), cutoff = 0.8)[0] # accessing the first word from close_match, because 1st word is more accurate than the rest.
# we'll display the close match word in a message box
correct = messagebox.askyesno('Confirm', 'Did you mean ' + close_match + ' instead.?')
if correct == True:
correct_meaning = data[close_match]
entry_field.delete(0, END) # deleting the entry_field to replace the wwrong word.
entry_field.insert(END, close_match) # inserting the correct word i.e close_match
textField.delete(1.0, END) # deleting the text in textField to update it with correct meaning for given word.
# again making the state normal(enabled) because we are inserting the text inside textField
textField.config(state = NORMAL)
for item in correct_meaning: # inserting multiple meaning line by line.
textField.insert(END, u'\u2022 ' + item + '\n\n')
textField.config(state = DISABLED) # disable the textField.
else:
textField.delete(1.0, END)
messagebox.showinfo('Information', 'Please type a correct word.')
entry_field.delete(0, END) # deleting the entry_field so that user can type again .
else:
textField.delete(1.0, END)
messagebox.showerror('Error', 'This word does not exist in our database.')
entry_field.delete(0, END) # deleting the entry_field so that user can type again .
''' GUI Part Starts Here '''
# we'll init. object of TK() class
root = Tk()
# now we'll set the size of window using geometry('width * height') class.
root.geometry('1000x650+450+180')
# to fix the size of windows (to switch off the maximize button)
# we are passing false value for width and height so that there will be no change in width and height
root.resizable(0, 0)
# setting title to the titlebar
root.title('Talking Dictionary ~ Created With ❤ By Aman')
# this mainloop will keep our window on infinite loop, and we can see window till we closed it.
# to set the background image, we'll use PhotoImage() class.
background_image = PhotoImage(file = 'bg.png')
# to use this image, we have to place it on a label so now we'll create a Label() class
background_label = Label(root, image = background_image) # label will be on root window
# now we have to place this label
background_label.place(x = 0, y = 0)
# placing a Enter Word Text
EnterWordLabel = Label(root, text = "Enter Word", font = ('Kristen ITC', 25, 'bold'), fg = 'red3', bg = 'whitesmoke')
EnterWordLabel.place(x = 600, y = 50)
# now we'll create entry_field for taking user input Word.
entry_field = Entry(root, font = ('FangSong', 15), bd = 5, relief = GROOVE, justify = CENTER) # border = bd, relief is a design for border
# by default cursor in the entry_field will blink in the left hand side.
# that's why we use justify = CENTER , so that it'll blink at the center.
# by default cursor is not pointed on the entry_field.we have to click on the field for pointing the cursor. to change this thing, we'll do the below
entry_field.focus_set()
# Now we'll upload pictures for icons.
searchImage = PhotoImage(file = 'search.png')
# now we'll use Button() class by creating an object of this class.
searchButton = Button(root, image = searchImage, bd = 0, bg = 'whitesmoke', activebackground = 'whitesmoke', cursor = 'hand2', command = searchMeaning)
searchButton.place(x = 620, y = 150)
enterWord_micImage = PhotoImage(file = 'mic.png')
enterWord_micButton = Button(root, image = enterWord_micImage, bd = 0, bg = 'whitesmoke', activebackground = 'whitesmoke', cursor = 'hand2', command = speakWord)
enterWord_micButton.place(x = 720, y = 154)
entry_field.place(x = 591, y = 110)
# placing a Meaning Text
MeaningLabel = Label(root, text = "Meaning", font = ('Kristen ITC', 25, 'bold'), fg = 'red3', bg = 'whitesmoke')
MeaningLabel.place(x = 629, y = 250)
# Now we'll create the TextField.
textField = Text(root, font = ('FangSong',16,'bold'), height = 10, width = 38, bd = 3, relief = GROOVE, wrap = 'word')
# by default at the end of the line, each letter will start going in the next line instead of each word. to fix this, we'll do this. wrap = 'word'
textField.place(x = 463, y = 300)
# Now setting up the buttons.
audio_micImage = PhotoImage(file = 'audio.png')
audio_micButton = Button(root, image = audio_micImage, bd = 0, bg = 'whitesmoke', activebackground = 'whitesmoke', cursor = 'hand2', command = speakMeaning)
audio_micButton.place(x = 530, y = 563)
clearImage = PhotoImage(file = 'clear.png')
clearButton = Button(root, image = clearImage, bd = 0, bg = 'whitesmoke', activebackground = 'whitesmoke', cursor = 'hand2', height = 50, width = 50, command = clearText)
clearButton.place(x = 660, y = 562)
exitImage = PhotoImage(file = 'exit_2.png')
exitButton = Button(root, image = exitImage, bd = 0, bg = 'whitesmoke', activebackground = 'whitesmoke', cursor = 'hand2', height = 50, width = 50, command = iexit)
# iexit is a function defined above.
exitButton.place(x = 800, y = 562)
''' Binding Keyboard Key With Button.'''
# attaching enetr key with searchButton.
def enter_function(event):
searchButton.invoke()
# whenever we'll press enterkey this enter_function will be called. and this function will invoke the askButton.
# To bind the ask button with Enter key. so that on pressing Enter key the button will work.
root.bind('<Return>', enter_function) # Enter is represented like Return.
# attaching backspace key with clearButton.
def backspace_function(event):
clearButton.invoke()
root.bind('<BackSpace>', backspace_function)
# attaching esc key with exitButton.
def exit_function(event):
exitButton.invoke()
root.bind('<Alt-F4>', exit_function)
# attaching Alt-F4 key with exitButton.
def exit_function(event):
exitButton.invoke()
root.bind('<Escape>', exit_function)
''' Binding Keyboard Key With Button End Here...'''
''' GUI Part Ends Here '''
root.mainloop()
|
8f754555f25a4e1d09d0390e22bbe6e042ecc8e7 | ForestPride/python-practice | /move-shape.py | 683 | 3.921875 | 4 | from graphics import *
def moveShape(shape, newCenter):
# get the old center.
oldCenter = shape.getCenter()
# move the shape to the new center.
shape.move(newCenter.getX() - oldCenter.getX(),
newCenter.getY() - oldCenter.getY())
def main():
# draw a window
win = GraphWin("move the circle", 800, 600)
# get a point from the mouse click.
point = win.getMouse()
# draw a circle at Point.
shape = Circle(point, 10)
shape.draw(win)
# get a new point each time the mouse clicks.
for i in range(10):
newCenter = win.getMouse()
# move the shape to the new center position.
moveShape(shape, newCenter)
main()
|
407d21fe4a7c0531fd3f9f2ace3e19008639cf06 | miroslavgasparek/python_intro | /regressions.py | 3,307 | 3.921875 | 4 | # 28 May 2018 Miroslav Gasparek
# Python bootcamp, lesson 37: Performing regressions
# Import modules
import numpy as np
import pandas as pd
# We'll use scipy.optimize.curve_fit to do the nonlinear regression
import scipy.optimize
import matplotlib.pyplot as plt
import seaborn as sns
rc={'lines.linewidth': 2, 'axes.labelsize': 18, 'axes.titlesize': 18}
sns.set(rc=rc)
# Import the dataset
df = pd.read_csv('data/bcd_gradient.csv', comment = '#')
# Rename the columns for the ease of the access
df = df.rename(columns={'fractional distance from anterior': 'x',
'[bcd] (a.u.)' : 'I_bcd'})
# Optimizing function prototype is
# scipy.optimize.curve_fit(f, xdata, ydata, p0=None)
# Step 1. Define the fit function
# (Make sure that all arguments are positive)
def bcd_gradient_model(x, I_0, a, lam):
""" Model for Bcf gradient: exponential decay plus background"""
assert np.all(np.array(x) >= 0), 'All values of x must be >= 0.'
assert np.all(np.array([I_0, a, lam]) >= 0), 'All parameters must be >= 0'
return a + I_0 * np.exp(-x/lam)
# **Never** name a Python variable the same as a keyword!
# To see what the keywords are, do this: `import keyword; print(keyword.kwlist)`
# Step 2. Supply initial guess
# Otherwise, curve_fit() will guess value of 1 for all parameters,
#which is generally not good
# We can see nonzero background signal around a = 0.2, I_0 around 0.9 and
# lambda somewhere around 0.3 (here I drops to approx. 66%), but lets try 1
# Specify initial guess
I_0_guess = 0.9
a_guess = 0.2
lam_guess = 1.0
# Construct initial guess array
p0 = np.array([I_0_guess, a_guess, lam_guess])
# Do curve fit, but dump covariance into dummy variable
# p, _ = scipy.optimize.curve_fit(bcd_gradient_model, df['x'], df['I_bcd'], p0=p0)
# This does not work due to the possiblity of getting negative values of parameters
# when _.curve_fit() searches the parameter space.
# Possible solutions:
# 1. Take out error checking
# 2. Use something other than scipy.optimize.curve_fit()
# 3. Adjust the theoretical function by using the log of parameter values instead
# of parameter values themselves - lets do that
def bcd_gradient_model_log_params(x, log_I_0, log_a, log_lam):
""" Model for Bcf gradueint: exponential decay plus background
with log parameters.
"""
# Exponentiate parameters
I_0, a, lam = np.exp(np.array([log_I_0, log_a, log_lam]))
return bcd_gradient_model(x, I_0, a, lam)
# Construct initial guess array
log_p0 = np.log(p0)
# Do curve fit but dump covariance into dummy variable
log_p, _ = scipy.optimize.curve_fit(bcd_gradient_model_log_params,
df['x'], df['I_bcd'], p0=log_p0)
# Get the optimal parameter values
p = np.exp(log_p)
# Print the results
print("""
I_0 = {0:.2f}
a = {1:.2f}
λ = {2:.2f}
""".format(*tuple(p)))
# Plotting
# Smooth x vales (100 values between zero and one)
x_smooth = np.linspace(0, 1, 100)
# Compute smooth curve
I_smooth = bcd_gradient_model(x_smooth, *tuple(p))
# Plot everything together
plt.plot(x_smooth, I_smooth, marker='None', linestyle='-', color='gray')
plt.plot(df['x'], df['I_bcd'], marker='.', linestyle='None')
# Label axes
plt.xlabel('$x$')
plt.ylabel('$I$ (a.u.)')
# The length scale of the Bcd gradient is about 20% of the embryo length.
|
2c9da507053689dee6cc34724324521983ea0c8c | miroslavgasparek/python_intro | /numpy_practice.py | 1,834 | 4.125 | 4 | # 21 February 2018 Miroslav Gasparek
# Practice with NumPy
import numpy as np
# Practice 1
# Generate array of 0 to 10
my_ar1 = np.arange(0,11,dtype='float')
print(my_ar1)
my_ar2 = np.linspace(0,10,11,dtype='float')
print(my_ar2)
# Practice 2
# Load in data
xa_high = np.loadtxt('data/xa_high_food.csv',comments='#')
xa_low = np.loadtxt('data/xa_low_food.csv',comments='#')
def xa_to_diameter(xa):
""" Convert an array of cross-sectional areas to diameters with
commensurate units."""
# Compute diameter from area
diameter = np.sqrt((4*xa)/np.pi)
return diameter
# Practice 3
# Create matrix A
A = np.array([[6.7, 1.3, 0.6, 0.7],
[0.1, 5.5, 0.4, 2.4],
[1.1, 0.8, 4.5, 1.7],
[0.0, 1.5, 3.4, 7.5]])
# Create vector b
b = np.array([1.1, 2.3, 3.3, 3.9])
# 1. Print row 1 (remember, indexing starts at zero) of A.
print(A[0,:])
# 2. Print columns 1 and 3 of A.
print(A[:,(0,2)])
# 3. Print the values of every entry in A that is greater than 2.
print(A[A > 2])
# 4. Print the diagonal of A. using the np.diag() function.
print(np.diag(A))
# 1. First, we'll solve the linear system A⋅x=bA⋅x=b .
# Try it out: use np.linalg.solve().
# Store your answer in the Numpy array x.
x = np.linalg.solve(A,b)
print('Solution of A*x = b is x = ',x)
# 2. Now do np.dot(A, x) to verify that A⋅x=bA⋅x=b .
b1 = np.dot(A,x)
print(np.isclose(b1,b))
# 3. Use np.transpose() to compute the transpose of A.
AT = np.transpose(A)
print('Transpose of A is AT = \n',AT)
# 4. Use np.linalg.inv() to compute the inverse of A.
AInv = np.linalg.inv(A)
print('Inverse of A is AInv = \n',AInv)
# 1. See what happens when you do B = np.ravel(A).
B = np.ravel(A)
print(B)
# 2. Look of the documentation for np.reshape(). Then, reshape B to make it look like A again.
C = B.reshape((4,4))
print(C)
|
e91d8fc8efc690ce20f022f92382d668e372986c | miroslavgasparek/python_intro | /image_proc_practice2.py | 7,292 | 3.71875 | 4 | # 14 July 2018 Miroslav Gasparek
# Python bootcamp, lesson 40: Image processing practice with Python
# Import modules
import numpy as np
import matplotlib.pyplot as plt
import scipy.ndimage
import skimage.io
import skimage.segmentation
import skimage.morphology
# Import some pretty Seaborn settings
import seaborn as sns
rc={'lines.linewidth': 2, 'axes.labelsize': 18, 'axes.titlesize': 18}
sns.set(rc=rc)
def cell_segmenter(im, thresh='otsu', radius=20.0, image_mode='phase',
area_bounds=(0,1e7), ecc_bounds=(0, 1)):
"""
This function segments a given image via thresholding and returns
a labeled segmentation mask.
Parameters
----------
im : 2d-array
Image to be segmented. This may be of either float or integer
data type.
thresh : int, float, or 'otsu'
Value used during thresholding operation. This can either be a value
(`int` or `float`) or 'otsu'. If 'otsu', the threshold value will be
determined automatically using Otsu's thresholding method.
radius : float
Radius for gaussian blur for background subtraction. Default value
is 20.
image_mode : 'phase' or 'fluorescence'
Mode of microscopy used to capture the image. If 'phase', objects with
intensity values *lower* than the provided threshold will be selected.
If `fluorescence`, values *greater* than the provided threshold will be
selected. Default value is 'phase'.
area_bounds : tuple of ints.
Range of areas of acceptable objects. This should be provided in units
of square pixels.
ecc_bounds : tuple of floats
Range of eccentricity values of acceptable objects. These values should
range between 0.0 and 1.0.
Returns
-------
im_labeled : 2d-array, int
Labeled segmentation mask.
"""
# Apply a median filter to remove hot pixels.
med_selem = skimage.morphology.square(3)
im_filt = skimage.filters.median(im, selem=med_selem)
# Perform gaussian subtraction
im_sub = bg_subtract(im_filt, radius)
# Determine the thresholding method.
if thresh is 'otsu':
thresh = skimage.filters.threshold_otsu(im_sub)
# Determine the image mode and apply threshold.
if image_mode is 'phase':
im_thresh = im_sub < thresh
elif image_mode is 'fluorescence':
im_thresh = im_sub > thresh
else:
raise ValueError("image mode not recognized. Must be 'phase'"
+ " or 'fluorescence'")
# Label the objects.
im_label = skimage.measure.label(im_thresh)
# Apply the area and eccentricity bounds.
im_filt = area_ecc_filter(im_label, area_bounds, ecc_bounds)
# Remove objects touching the border.
im_border = skimage.segmentation.clear_border(im_filt, buffer_size=5)
# Relabel the image.
im_border = im_border > 0
im_label = skimage.measure.label(im_border)
return im_label
def bg_subtract(im, radius):
"""
Subtracts a gaussian blurred image from itself smoothing uneven
illumination.
Parameters
----------
im : 2d-array
Image to be subtracted
radius : int or float
Radius of gaussian blur
Returns
-------
im_sub : 2d-array, float
Background subtracted image.
"""
# Apply the gaussian filter.
im_filt = skimage.filters.gaussian(im, radius)
# Ensure the original image is a float
if np.max(im) > 1.0:
im = skimage.img_as_float(im)
im_sub = im - im_filt
return im_sub
def area_ecc_filter(im, area_bounds, ecc_bounds):
"""
Filters objects in an image based on their areas.
Parameters
----------
im : 2d-array, int
Labeled segmentation mask to be filtered.
area_bounds : tuple of ints
Range of areas in which acceptable objects exist. This should be
provided in units of square pixels.
ecc_bounds : tuple of floats
Range of eccentricities in which acceptable objects exist. This should be
provided on the range of 0 to 1.0.
Returns
-------
im_relab : 2d-array, int
The relabeled, filtered image.
"""
# Extract the region props of the objects.
props = skimage.measure.regionprops(im)
# Extract the areas and labels.
areas = np.array([prop.area for prop in props])
eccs = np.array([prop.eccentricity for prop in props])
labels = np.array([prop.label for prop in props])
# Make an empty image to add the approved cells.
im_approved = np.zeros_like(im)
# Threshold the objects based on area and eccentricity
for i, _ in enumerate(areas):
if areas[i] > area_bounds[0] and areas[i] < area_bounds[1]\
and eccs[i] > ecc_bounds[0] and eccs[i] < ecc_bounds[1]:
im_approved += im==labels[i]
# Relabel the image.
print(np.sum(im_approved))
im_filt = skimage.measure.label(im_approved > 0)
return im_filt
# Load an E. coli test image.
ecoli = skimage.io.imread('data/HG105_images/noLac_phase_0004.tif')
# Using my knowledge of biology, we can draw some bounds.
# Using the information in the problem statement, we know
# the interpixel distance.
ip_dist = 0.0636 # in units of µm per pixel.
area_bounds = (1/ip_dist**2, 10.0/ip_dist**2)
ecc_bounds = (0.8, 1.0) # they are certainly not spheres.
# Pass all images through our function.
ecoli_seg = cell_segmenter(ecoli, area_bounds=area_bounds, ecc_bounds=ecc_bounds)
# Extract and store the mean and total fluorescence intensities for each cell
# in a single image in an array of pandas DataFrame
# Load the fluorescence image.
ecoli_yfp = skimage.io.imread('data/HG105_images/noLac_FITC_0004.tif')
# Compute the regionproperties of our fluorescence image.
props = skimage.measure.regionprops(ecoli_seg, intensity_image = ecoli_yfp)
# Extract the mean intensities
mean_int = np.array([prop.mean_intensity for prop in props])
# We will start with a simple histogram
f1 = plt.figure(1)
plt.hist(mean_int)
plt.xlabel('mean pixel intensity')
plt.ylabel('count')
# To eliminate the bias, check ethe ECDF.
def ecdf(data):
""" Compute x, y values for an empirical distribution function."""
x = np.sort(data)
y = np.arange(1,len(data)+1) / len(data)
return x, y
# Compute the ECDF for the glow-y cells.
intensities, ECDF = ecdf(mean_int)
# Plotting
f2 = plt.figure(2)
plt.plot(intensities, ECDF, marker ='.', linestyle='none')
plt.xlabel('intensities')
plt.ylabel('ECDF')
# Define the number of repetitions.
n_reps = 100000
# Initialize the replicates
bootstrap_means = np.empty(n_reps)
# Compute the replicates. Each bootstrap is plotted
for i in range(n_reps):
resample = np.random.choice(mean_int, replace=True, size=len(mean_int))
bootstrap_means[i] = np.mean(resample)
# Compute the ECDF
bs_means, bs_ECDF = ecdf(bootstrap_means)
# Plot the ECDF
f3 = plt.figure(3)
plt.plot(bs_means, bs_ECDF, marker='.', linestyle='none')
plt.xlabel('mean of bootstrapped intensities')
plt.ylabel('ECDF')
plt.margins(0.02)
# Compute the 95% confidence interval
percs = np.percentile(bootstrap_means, [97.5, 2.5])
print("""
The 97.5% and the 2.5% of the bootstrapped data are {0:.3f}
and {1:.3f}, respectively.
""".format(percs[0], percs[1]))
|
c229d1876e2806036441777368353cb25da31647 | chenmengsheng/- | /python资料/F_AKindSorting.py | 1,001 | 3.65625 | 4 | class Rectangle:
def __init__(self, _number, _length, _width):
self.number, self.length, self.width = _number, _length, _width
def __repr__(self): # __repr__
return '%d %d %d' % (self.number, self.length, self.width)
def __lt__(self, other):
if self.number != other.number:
return self.number < other.number
if self.length < other.length:
return self.length < other.length
return self.width < other.width
T = int(input())
for t in range(T):
n = int(input())
rectangles = []
for i in range(n):
number, length, width = map(int, input().strip().split())
if length < width:
length, width = width, length
rectangles.append(Rectangle(number, length, width))
rectangles.sort()
# print(rectangles)
print(rectangles[0])
for j in range(1, len(rectangles)):
if rectangles[j - 1] < rectangles[j]:
print(rectangles[j])
|
23e2a0d9f7d8ca80413df8a5a36800ae70cd046e | chenmengsheng/- | /python资料/五子棋.py | 2,586 | 3.90625 | 4 |
# coding: utf-8
import random
import sys
# 定义棋盘的大小
BOARD_SIZE = int(input('请输入棋盘大小:'))
#BOARD_SIZE = int(BOARD_SIZE)
high = []
wide = []
num = []
num1 = []
num2 = []
# 定义一个二维列表来充当棋盘
board = []
def initBoard() :
# 把每个元素赋为"╋",用于在控制台画出棋盘
for i in range(BOARD_SIZE) :
row = ["╋"] * BOARD_SIZE
board.append(row)
# 在控制台输出棋盘的方法
def printBoard() :
# 打印每个列表元素
for i in range(BOARD_SIZE) :
for j in range(BOARD_SIZE) :
# 打印列表元素后不换行
print(board[i][j], end="")
# 每打印完一行列表元素后输出一个换行符
print()
initBoard()
printBoard()
# 随机生成2位数字,并判断是否和手动输入相同(相同的话重新获取)
def randoms():
a,b = [random.randint(1, BOARD_SIZE) for j in range(1, 3)]
for i in range(len(wide)) :
if wide[i] == a and high[i] == b :
randoms()
else:
board[a - 1][b - 1]= "○"
# 判断五位数字是否相连
def sorts(num) :
num.sort()
n = 0
j = 0
n = num[0]
for i in num :
if i == n :
n = i + 1
j=j+1
if j >= 5:
printBoard()
print('成功')
sys.exit()
else:
n = i
n = n + 1
j = 1
while 1 > 0 :
inputStr = input("请输入您下棋的坐标,应以x,y的格式:\n")
if inputStr != None :
# 将用户输入的字符串以逗号(,)作为分隔符,分隔成2个字符串
x_str, y_str = inputStr.split(sep = ",")
# 把对应的列表元素赋为"●"。
board[int(y_str) - 1][int(x_str) - 1] = "●"
# 记录输入的x_str和y_str
wide.append(int(x_str))
high.append(int(y_str))
# 进行是否成功判断
if len(wide) >= 5 :
for i in range(len(wide)) :
if (wide[i]+int(y_str))/(high[i]+int(x_str)) == 1 :
num.append(wide[i])
sorts(num)
if wide[i] == int(x_str):
num1.append(high[i])
sorts(num1)
if high[i] == int(y_str):
num2.append(wide[i])
sorts(num2)
num.clear()
num1.clear()
num2.clear()
randoms()
printBoard()
else :
print('输入格式不对')
break
|
9e0de83bf0cbc251455b0028170753e2660bf9ae | chenmengsheng/- | /python资料/Fraction2.py | 598 | 3.734375 | 4 | import math
class Fraction:
def __init__(self, _up, _down): # 构造方法 Constructor
g = math.gcd(_up, _down)
self.up = _up // g
self.down = _down // g
def __str__(self):
return "%d/%d" % (self.up, self.down)
def add(self, other):#bad smell
c = Fraction(0, 1)
c.down = self.down * other.down
c.up = self.up * other.down + self.down * other.up
return c
a = Fraction(3, 9) # 创建一个对象 实例化 instantiate
print(a) # neat
b = Fraction(4, 24);
c = a.add(b)
# c = a + b
print(c)
|
6cb3659d15e480f08ad3fca096cff7a98e226350 | chenmengsheng/- | /python资料/P20/P19.py | 415 | 3.671875 | 4 | '''
19. 从键盘上输入两个不超过32767的整数,试编程序用竖式加法形式显示计算结果。
例如: 输入 123, 85
显示: 123
+ 85
-------------
208
'''
a, b = 123, 85
wid = 10 # 宽度
print(('%' + '%d' % wid + 'd') % a)
print(('+%' + '%d' % (wid - 1) + 'd') % b)
print('-' * wid)
print(('%' + '%d' % wid + 'd') % (a + b))
|
f05a74a96c8113808f01e0d6a341eccb3262f111 | pshashank64/tathastu_week_of_code | /day1/program4.py | 224 | 3.84375 | 4 | cp = float(input("Enter the cost price: "))
sp = float(input("Enter the selling: "))
profit = sp - cp
newsp = 1.05 * profit + cp
print("The profit is", profit)
print("new selling price to increase profit by 5% is: ", newsp)
|
8d3a4af611f5dde4daa4a0f7ecc1bcced8c6d29d | pshashank64/tathastu_week_of_code | /day1/progam3.py | 196 | 4.03125 | 4 | x = float(input("ENter first number: "))
y = float(input("Enter the second number: "))
x = x + y
y = x - y
x = x - y
print("Swapping result: ")
print("Number 1 is: ", x)
print("Number 2 is: ", y)
|
877150ed0d4fb9185a633ee923daee0ba3d745e4 | nmessa/Raspberry-Pi | /Programming/SimplePython/name4.py | 550 | 4.125 | 4 | # iteration (looping) with selection (conditions)
again = True
while again:
name = raw_input("What is your name? ")
print "Hello", name
age = int(raw_input("How old are you? "))
newage = age + 1
print "Next year you will be ", newage
if age>=5 and age<19:
print "You are still in school"
elif age < 5:
print "You have not started school yet?"
elif age > 20:
print "You are probably out of high school now?"
answer = raw_input("Again (y/n)?")
if answer != 'y':
again = False
|
048d3a41084ad1f33b86e558c98ec2a0c582fb95 | GuochangYuan/MyPython | /hello.py | 161 | 3.59375 | 4 | if __name__=='__main__':
fp=open('test1.txt','w')
string=input('please input a string:\n')
string=string.upper()
fp.write(string)
fp.close()
print(string)
|
38c5662d6b91010f45f5628c79e5ef886bdf0133 | LuisGomez11/Python | /Corte 1/TALLER #3 - GESTION DE CADENAS Y LISTAS/SextoEjercicio.py | 1,451 | 3.96875 | 4 | def pedirNumero(mensaje):
correcto = False
num = 0
while(not correcto):
try:
num = int(input(mensaje))
correcto = True
except ValueError:
print('Error, digite un numero entero')
return num
tam = pedirNumero('Digite el numero de datos que ingresara: ')
print('---------------------------------------------------------------')
con = 0
listaNumeros = []
while con<tam:
num = pedirNumero('Ingrese un numero a la lista: ')
listaNumeros.append(num)
con+=1
suma = 0
pruducto = 1
mayor = listaNumeros[0]
menor = listaNumeros[0]
for i in listaNumeros:
suma+=i
pruducto*=i
tam = len(listaNumeros)
for i in range(tam):
if(menor>listaNumeros[i]):
menor=listaNumeros[i]
if(mayor<listaNumeros[i]):
mayor=listaNumeros[i]
print('---------------------------------------------------------------')
print('La lista es:',listaNumeros)
print('---------------------------------------------------------------')
print('La suma de todos los numeros de la lista es:',suma)
print('---------------------------------------------------------------')
print('El producto de todos los numeros de la lista es:',pruducto)
print('---------------------------------------------------------------')
print('El numero mayor de la lista es:',mayor)
print('---------------------------------------------------------------')
print('El numero menor de la lista es:',menor) |
7597d5bf1d1218165c986537b815a01ad9cdbdb6 | LuisGomez11/Python | /Corte 1/TALLER #3 - GESTION DE CADENAS Y LISTAS/SegundoEjercicio.py | 426 | 3.84375 | 4 | cadena = input('Digite una cadena de texto: ')
def numVeces(cadena):
contador = 0
for vocal in cadena:
if (vocal.upper()=='A' or vocal.upper()=='E' or vocal.upper()=='I' or vocal.upper()=='O' or vocal.upper()=='U'):
contador+=1
if contador==0:
print("No se encuentra volcales en la cadena")
print("Las veces que se encuentra una vocal en la cadena son:",contador)
numVeces(cadena) |
753122c74d0c5783b87c29158f5bea1407139e6a | LuisGomez11/Python | /Corte 1/TALLER #3 - GESTION DE CADENAS Y LISTAS/OctavoEjercicio.py | 856 | 3.921875 | 4 | def pedirNumero(mensaje):
correcto = False
num = 0
while(not correcto):
try:
num = int(input(mensaje))
correcto = True
except ValueError:
print('Error, digite un numero entero')
return num
listaFibonacci = []
listaPrimos = []
tam = pedirNumero('Digite el numero de datos que desea mostrar: ')
def fib(tam):
a, b = 0,1
while len(listaFibonacci) < tam:
listaFibonacci.append(a)
a, b = b, a+b
def validarPrimo(num):
if num<2:
return False
for i in range(2,num):
if num % i == 0:
return False
return True
def primos(tam):
i = 0
while len(listaPrimos) < tam:
if validarPrimo(i) == True:
listaPrimos.append(i)
i += 1
fib(tam)
primos(tam)
print('Lista primos:',listaPrimos)
print('Lista Fibonacci:',listaFibonacci)
|
65514aad9b6130592e8674b4f47a0ec914abbdc1 | LuisGomez11/Python | /Corte 1/TALLER #3 - GESTION DE CADENAS Y LISTAS/TercerEjercicio.py | 444 | 3.625 | 4 | cadena = input('Digite una cadena de texto: ')
def impDosPrimerosCar(cadena):
print('Primeros dos caracteres:',cadena[0:2])
def impTresPrimerosCar(cadena):
print('Primeros tres caracteres:',cadena[0:3])
def impCadaDosCar(cadena):
print('Cada dos caracteres',cadena[::2])
def impCadenaInv(cadena):
print('Invertida:',cadena[::-1])
impDosPrimerosCar(cadena)
impTresPrimerosCar(cadena)
impCadaDosCar(cadena)
impCadenaInv(cadena)
|
80a517636f48d65292a13af089509a2c3cca4089 | VDCasper/GameLife | /proba.py | 885 | 3.546875 | 4 | import numpy as np
array_copy = np.array([(0,0,0,1,1,1),
(1,1,0,1,0,1),
(0,0,0,1,1,1),
(1,0,0,1,0,1),
(1,0,1,1,0,1),
(1,1,0,0,0,0)])
while np.sum(array_copy) > 0:
j = 0
while j < 9:
i = 0
while i < 9:
b = mas[j:j+3, i:i+3] # делаем срез матрицы 3х3
if b[1][1] == 0 and np.sum(b) == 3: # проверяем состояние центарльноuj элемента b[1][1]
array_copy[j+1, i+1] = 1
elif b[1][1] == 1 and np.sum(b) > 4 or np.sum(b) < 3:
array_copy[j+1, i+1] = 0
#print(mas)
#print(b)
#print(array_copy)
i += 1
j += 1
print(array_copy) |
20fb4ee755500d04ad055a843c10daa35cdab8b3 | vchernoy/coding | /leetcode/medium/clone_graph/clone_graph.py | 714 | 3.609375 | 4 |
# Definition for a undirected graph node
# class UndirectedGraphNode:
# def __init__(self, x):
# self.label = x
# self.neighbors = []
class Solution:
# @param node, a undirected graph node
# @return a undirected graph node
def cloneGraph(self, node):
graph = {}
copy = self.clone(node, graph)
return copy
def clone(self, node, graph):
if node is None:
return None
if node in graph:
return graph[node]
copy = UndirectedGraphNode(node.label)
graph[node] = copy
for n in node.neighbors:
copy.neighbors.append(self.clone(n, graph))
return copy
|
c099d8ea19bd0459fa0a1c0ce9419c6237d7c647 | bbeuro132/My_python | /실습자료/oper.py | 1,153 | 4.09375 | 4 | num1 = 3
num2 = 4
print(type(num1))
print('덧셈 :', num1+num2)
print('곱셈 :', num1*num2)
print('나머지 :', num1%num2)
res = num1 + num2
print('res : ', res)
res += num1
print('res : ', res)
# 비교 연산자
print(num1 > num2)
print(num1 < num2)
# 논리 연산자
print(num1 > num2 and num1 < num2)
print(num1 > num2 or num1 < num2)
print(not(num1 > num2))
# 3항 연산자
result = (num1 > num2) and \
'num1이 num2보다 크다' or \
'num1이 num2보다 작다'
print(result)
# 문자열
str1 = '홍길동'
str2 = '입니다.'
fullstr = str1 + str2
print(str1+str2)
print('문자열 연결 : ', fullstr)
fullstr = fullstr + '\n' + '안녕하세요.'
print('개행문자 :', fullstr)
# 문자열 인덱싱(indexing)
# 배열과 비슷함
print(str1[0], str1[1], str1[2])
# 문자열 자르기(slicing)
print(fullstr[0:2]) # 0 ~ 1까지 자르기
print(fullstr[1:]) # 1 ~ 끝까지
print(fullstr[:3]) # 처음부터 ~ 2까지
print('\n\n' + fullstr[1::2]) # 1부터 끝까지 2번째 위치만
#in 연산자
search = '홍길동' in fullstr
print('\n', search)
length = len(fullstr)
print('변수값 크기 : ', length) |
3c0491e1e79bdbc716907f9713175dce32afada7 | bbeuro132/My_python | /실습자료/반복문.py | 1,915 | 3.921875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
count = 1
while count <= 5:
print(count)
count+=1
# In[ ]:
while True :
stuff = input("String to capitalize [type q to quit] : ")
if stuff == "q":
break
print(stuff.capitalize())
# In[ ]:
while True:
value = input("Integer, please [q to quit] : ")
if value == 'q' :
break
number = int(value)
if number % 2 == 0 :
continue
print(number, "squared is", number*number)
# In[ ]:
word = 'thud'
for letter in word:
if letter == 'x':
print("Eek! An 'x'!")
break
print(letter)
else:
print("No 'x' in there.")
# In[ ]:
numbers = [1,3,5]
position = 0
while position < len(numbers):
number = numbers[position]
if number % 2 == 0 :
print('Found even number', number)
break
position += 1
else :
print('No even number found')
# In[ ]:
word = 'thud'
for letter in word:
if letter == 'x':
print("Eek! An 'x'!")
break
print(letter)
else:
print("No 'x' in there.")
# In[ ]:
bucket = ['딸기', '수박', '사과', '참외']
for fruit in bucket :
print(fruit)
# In[ ]:
List = [3,2,1,0]
for lst in List :
print(lst)
# In[5]:
guess_me = 7
number = 5
while True :
if number < guess_me :
print('too low')
if number == guess_me :
print('found it!')
break
number+=1
if number > guess_me :
print('opps')
break
# In[13]:
dan = int(input('몇 단을 출력하나요 : '))
for i in range(1,dan+1) :
for j in range(1, 10) :
print('%d x %d = %d'% (i, j, i*j))
print('\n')
# In[17]:
guess_me = 5
for number in range(1, 10):
if number < guess_me :
print('too low')
if number == guess_me :
print('found it!')
break
if number > guess_me :
print('opps')
break
|
f8b7b115d46331ca315b36ef795b5d0a81f0a659 | shubhamkkr/SpyChat | /main.py | 6,659 | 3.859375 | 4 | from steganography.steganography import Steganography
from datetime import datetime
def entry():
name = raw_input("What's your spy name??")
if len(name) > 0:
print("Yay, the name is good.")
salutation = raw_input("What would be your spy salutation, Mr. ,Mrs or Ms.")
full_name = salutation + " " + name
print("Alright " + full_name + ", I would like to know little more about you....")
age = int(raw_input("what's your age?"))
if 20 < age < 50:
print("Alright,")
rating = float(raw_input("whats ur Spy rating??"))
if 2.5 <= rating < 3.5:
print(" U can always do better")
elif 3.5 <= rating < 4.5:
print("Yup, you are one of good ones")
elif rating >= 4.5:
print("Ooo, thts an ace")
else:
print("We can always use somebody to help in the office.")
ol = bool(raw_input("Are u online???"))
if ol == False:
print("Authentication complete, welcome " + full_name + " with age " + repr(age) + " and rating of " + repr(rating) + " Proud to have u you on board")
else:
print(" ")
else:
print("Sorry you are not of the correct age to be a spy")
exit()
else:
print("This name is not valid please try with a better name")
def spy_chat():
show_menu = True
current_status_message = None
while show_menu:
print("What do you want to do?")
menu_choices = "1. Add a status update \n2. Add a friend \n3. Send message \n4. Read a message \n5. Exit the Application " \
"\nInput :- "
menuchoice = raw_input(menu_choices)
if menuchoice == "1":
current_status_message = add_status(current_status_message)
elif menuchoice == "2":
no = add_friend() # no of friends returned
print("No of friends : %d" % no)
elif menuchoice == "3":
send_massage()
elif menuchoice == "4":
read_message()
elif menuchoice== '5':
print("QUITTING....")
show_menu = False
else:
print("invalid input")
pass
def add_status(current_status_message):
if current_status_message is not None:
print("Your current status is : %s" % current_status_message)
else:
print("You don't have any status right now")
default =raw_input( "Do you want to select from the previous status??(Y/N)")
if default.upper() == 'N':
new_status_message = raw_input("Which status you want to set ??")
if len(new_status_message) > 0:
updated_status_message = new_status_message # updates status
STATUS_MESSAGES.append(updated_status_message) # Entered in the list
print(updated_status_message + " : is now set as your as status")
else:
print("Please enter a valid status...") # invalid status
updated_status_message = current_status_message # assign previous status
print(updated_status_message + " : Remains as your as status")
elif default.upper() == 'Y':
item_position = 1
for message in STATUS_MESSAGES:
print("%d . %s" % (item_position, message))
item_position = item_position + 1
menu_selection = int(raw_input("What is your desired status?"))
if len(STATUS_MESSAGES) >= menu_selection:
updated_status_message = STATUS_MESSAGES[menu_selection - 1] # set desired status
print(updated_status_message + " : is now set as your as status") # print desired status
else:
print("invalid raw_input...")
updated_status_message = current_status_message # assign previous status
else:
print("invalid raw_input")
pass
return updated_status_message
def add_friend():
new_friend = {"Name": "", "Salutation": "", "age": 0, "Rating": 0.0, "Chats": []}
new_friend["Name"] = raw_input("Whats your friend spy name?")
new_friend["Salutation"] =raw_input("what would be the salutation, Mr. or Mrs??")
new_friend["Name"] = new_friend["Salutation"] + " " + new_friend["Name"]
new_friend["age"] = int(raw_input("what is friends age?"))
new_friend["Rating"] = float(raw_input("what's your friend spy rating??"))
if len(new_friend["Name"])>0 and 12 < new_friend["age"] < 50: # add friend
Friends.append(new_friend)
else: # invalid details
print("Sorry we can't add your friend's details please try again")
return len(Friends)
def select_a_friend():
item_no = 0
if len(Friends) != 0:
for friend in Friends:
print("%d . %s" % (item_no+1, friend["Name"]))
item_no = item_no + 1
friend_no = int(raw_input("Select your Friend : "))
if friend_no <= len(Friends) and friend_no != 0:
print("You selected %d no Friend" % friend_no)
return friend_no-1
else:
print("Wrong raw_input, plz try again......")
else:
print("Sorry no Friend added till now, plz add a friend first.... ")
friend_no = add_friend()
print("No. of Friends : %d" % friend_no)
select_a_friend()
def send_massage():
selection = select_a_friend();
image = raw_input(" Name of image to be encoded :")
out_path = "ac3.jpg"
text = raw_input("what text do you want to encode :")
Steganography.encode(image,out_path,text)
print("Message sent... ")
text = "You : " + text
new_chat = {
"message": text,
"time": datetime.now(),
"send_by_me": True
}
Friends[selection]["Chats"].append(new_chat)
def read_message():
selection = select_a_friend()
image = raw_input("Name of image to be decoded : ")
text = Steganography.decode(image)
text = Friends[selection]["Name"] + " : "+ text
new_chat = {
"message": text,
"time": datetime.now(),
"send_by_me": False
}
Friends[selection]["Chats"].append(new_chat)
print(text)
user = raw_input("Do you want to continue with the default user ?(Y/N)")
new_user = 0
if user.upper() == 'Y':
from spy_details import spy
print('Welcome,%s %s with %d years of age and %.1f rating. Welcome to SpyChat.... ' %
(spy["Salutation"], spy["name"], spy["age"], spy["Rating"]))
else:
new_user = 1
entry()
STATUS_MESSAGES =['Crazy me...', ' Mandir wahin banaenge...', 'lol']
Friends = []
spy_chat() |
b35e7b8bf2cdd9c34f0867aab741496aca95478e | anikas1/AnatoLearn | /pMLevel1Comp.py | 1,057 | 3.5625 | 4 | """
Authors: Anika Suman & Ayush Khanna
Date: 9/7/21
Class: Math 241 Scientific Computing
Professor: Ben Marlin
"""
import pygame
#initializes the pygame workspace
pygame.init()
#sets the screen size to 960 x 540 pixels
screen = pygame.display.set_mode((960, 540))
pygame.display.set_caption('Practice Mode')
successSound = pygame.mixer.Sound('audio/success.mp3')
#loads the main homescreen page
background = pygame.image.load("images\plevel1comp.png")
screen.blit(background, (0,0))
pygame.display.flip() #updates background
#running the program until something makes it stop
running = True
sC = 0
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if sC == 0:
pygame.mixer.Sound.play(successSound)
sC += 1
pygame.mixer.music.stop()
#if mouse button is down, run the second level
if event.type == pygame.MOUSEBUTTONDOWN:
exec(open("pMLevel2Intro.py").read())
pygame.quit() #allows to exit game |
b6b766c81598c8dab4b2c9b3dcb9979cc87409b6 | famasoon/kyopro | /atcoder/Children and Candies /solve.py | 205 | 3.890625 | 4 | def sigma(n: int) -> int:
sum = 0
if n != 1:
sum += n
sum += sigma(n-1)
else:
sum += n
return sum
return sum
n = int(input())
total = sigma(n)
print(total) |
d8482da6b9983d990da980c3a5edab0c49a28229 | arubikira/Python | /function.py | 185 | 3.890625 | 4 | x = int(input('masukkan'))
y = int(input('masukkan'))
def jumlah(x,y):
hasil = x+y
return hasil
print('hasil dari',x,'+',y,'=', jumlah(x,y))
k = jumlah(2,4)+1
print(k)
|
1ab66596a2a05802cc2d0461d9098dfb8432dd9c | arubikira/Python | /harmonic number.py | 236 | 3.75 | 4 | angka = int(input('masukkin angka: '))
Total = 0
pembagi=0
#for i in range(1, n):
while angka > 0:
pembagi+=1
bil = 1/pembagi
print(bil)
simpan = Total+bil
Total = simpan
angka-=1
print('hasilnya = ', Total)
|
bea0c4098b659deba7dd177a49ca8a478f89fc72 | kamilam1987/EmergingTechnologies | /python-fundamentals/gcdFunction.py | 431 | 3.78125 | 4 | # Function with two arguments
def gcd(a, b):
""" Returns the greatest common divisor of a and b """
if a < b:
a, b = b, a
while b > 0:
a, b = b, a % b
return a
print(gcd(50, 20))
print(gcd(22, 143))
#LCM with two numbers
def lcm(a, b):
if a > b:
a, b = b, a
for x in range(b, a * b + 1, b):
if x % a == 0:
return x
print(lcm(2, 4))
|
40ba01f5f891bfbfc7dd3b1658cb1915d2d42073 | Navyasharma96/tkinter | /tik1.py | 293 | 3.5 | 4 | import tkinter
v=tk.Tk()
v.title('counting second')
Button1=Button(guitext='stop',width='25',command=v.destroy)
Button2=Button(guitext='cancle',width='25',command=v.destroy)
Button3=Button(guitext='submit',width='25',command=v.destroy)
Button1.pack()
Button2.pack()
Button3.pack()
v.mainloop() |
9583f9a916001bd02034aa6974e6d0969e6ec3ff | dessHub/binary_search | /test_binary.py | 608 | 3.5 | 4 |
class BinarySearch(list):
def __init__(self, a, b):
super(BinarySearch, self).__init__(range(b, a * b + b, b))
self.length = a
def search(self,value):
index = 0
dict_obj = {"count":0,"index": 0}
first = 0
last = self.length - 1
while last >= first :
dict_obj["count"] = dict_obj.get("count") + 1
mid_value = (last + first) / 2
if value == self[mid_value]:
dict_obj[index] = mid_value
break
elif value < self[mid_value]:
last = mid_value - 1
break
else:
first = mid_value + 1
return dict_obj
|
c6c26b0f16f103b34be9c40c83a61d6de3ed5642 | Kabi4/AutoMatedStuffWithPython | /rock_paper_sccisors.py | 1,808 | 3.9375 | 4 | import random
def play_twice():
play=str(input("Do you want to play again??Y/N: ")).lower()
if play=='y':
game()
elif play=='n':
print("Thankyou!! you for playing")
else:
print("Your output didn't match Y or N please try again!!!")
play_twice()
def computer_guess():
l=['Rock','Paper','Scissors']
x=random.shuffle(l)
return l[0]
def game():
n=int(input("Enter the wining score: "))
w,l,t=0,0,0
print("Starting game......")
while w<n and l<n:
print("Win {} Loss {} Tie {}".format(w,l,t))
com=computer_guess()
x=int(input('Enter your choice (1)Rock (2)Paper (3)Scissors : '))
ln=['Rock','Paper','Scissors']
if x==1 or x==2 or x==3:
player=ln[x-1]
print(player+" Verses.....")
print(com)
if com==player:
t+=1
else:
if player=='Rock' and com=='Scissors':
w+=1
elif com=='Rock' and player=='Scissors':
l+=1
elif player=='Paper' and com=='Scissors':
l+=1
elif com=='Paper' and player=='Scissors':
w+=1
elif com=='Rock' and player=='Paper':
w+=1
elif player=='Rock' and com=='Paper':
l+=1
else:
print("Your enterted a unwanted value!!! Restarting The game......")
game()
if w==n:
print("Hurray you win!!")
else:
print("You lose Better luck next time!! :-) ")
play_twice()
def main():
print("Welcome to the Rock,Paper,Scissors")
game()
main()
|
5e939364601856aa71a1c5e624218b8867629a7e | Teslothorcha/holbertonschool-higher_level_programming | /0x0B-python-input_output/2-read_lines.py | 590 | 3.5 | 4 | #!/usr/bin/python3
def read_lines(filename="", nb_lines=0):
c = 0
c_ = 0
with open(filename, encoding="utf-8") as file:
for line in file:
line = file.readline()
if line[-1:] == '\n':
c += 1
c += 1
if nb_lines <= 0 or nb_lines >= c:
with open(filename, encoding="utf-8") as file:
print(file.read(), end="")
return
else:
with open(filename, encoding="utf-8") as file:
while nb_lines > c_:
print(file.readline(), end="")
c_ += 1
|
91dc6c6f946fa458ee16d6d806ce6c76386bc9c9 | Teslothorcha/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/2-matrix_divided.py | 883 | 3.8125 | 4 | #!/usr/bin/python3
"""
This divide a matrix
into a given number
and return a new matrix
"""
def matrix_divided(matrix, div):
"""
checks data accuracy to perfom division
"""
msg_1 = "matrix must be a matrix (list of lists) of integers/floats"
msg_2 = "Each row of the matrix must have the same size"
msg_3 = "division by zero"
msg_4 = "div must be a number"
if not isinstance(div, int):
raise TypeError(msg_4)
if not matrix or matrix is None:
raise TypeError(msg_1)
if div == 0:
raise ZeroDivisionError(msg_3)
for row in matrix:
if len(row) != len(matrix[0]):
raise TypeError(msg_2)
for y in row:
if not isinstance(y, (int, float)):
raise TypeError(msg_1)
matrix_reloaded = [[round(x / div, 2) for x in ind] for ind in matrix]
return matrix_reloaded
|
cd0c13a1013724e1ec7920a706ee52e2aa0e9a96 | Teslothorcha/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 411 | 4.15625 | 4 | #!/usr/bin/python3
"""
This function will add two values
casted values if necessary (int/float)
and return the addition
"""
def add_integer(a, b=98):
"""
check if args are ints to add'em'
"""
if not isinstance(a, (int, float)):
raise TypeError("a must be an integer")
if not isinstance(b, (int, float)):
raise TypeError("b must be an integer")
return (int(a) + int(b))
|
729e9edc4bbf1616c53c94eac35675b1a4a37edd | vsmvignesh/pyprograms | /cadbury_problem.py | 909 | 4 | 4 | #!/usr/bin/python
import sys
def create_combination(l1,l2,b1,b2):
tot_count=0
for l in range(l1,l2+1):
for b in range(b1,b2+1):
ret=count_bars(l,b)
print("Chocolate Bar size ({0} x {1}), can be distributed to \"{2}\" children...".format(l,b,ret))
tot_count=tot_count+ret
print("\nSo, total number of \"" + str(tot_count) + "\" children will have chocolates distributed to them...\n")
return 0
def count_bars(l,b):
count=0
while(l!=b):
if b>l :
b=b-l
else:
l=l-b
count+=1
else:
count+=1
return count
def main():
inp=input("Enter the lengths and breadths(len1, len2, brd1, brd2): ")
l1,l2,b1,b2=inp[0], inp[1], inp[2], inp[3]
ret=create_combination(l1,l2,b1,b2)
if ret:
sys.exit(1)
else:
return 0
if __name__=="__main__":
main()
|
cc67778fcffa07c24fa7ab126f63a0d597398859 | valoto/python_trainning | /aula1/script.py | 660 | 3.875 | 4 | #!/usr/bin/python3
print("Hello, world!")
var = False
if var:
print("Var é verdadeiro")
else:
print("Var é falso")
print("Pode apostar nisso!")
#Comentario em Linha
"""Bloco
de
Comentarios
"""
print(type(1))
print(type("Igor"))
print(type(var))
print(type(1.5))
print(type([]))
print(type({}))
print(type(()))
print(type("Igor"));print(type("Igor"))
print ("Igor \
Valoto" )
print(
"Testando"
)
lista = [
'a', 'b', 'c'
]
print (lista)
def imprimir(nome, email, idade):
pass
def imprimir2(
nome,
email,
idade):
pass
imprimir(
"igor",
"valoto@valoto.com",
50
)
|
353bb70b7acbbedf2381635d1d554d117edc6b7f | valoto/python_trainning | /aula2/strings.py | 780 | 4.125 | 4 | var = "PYT''\"HON"
var = 'PYTH"ON'
# TODAS MAIUSCULAS
print(var.upper())
# TODAS MINUSCULAS
print(var.upper())
# SUBSTITUI T POR X
print(var.replace('T', 'X'))
# PRIMEIRA LETRA MAIUSCULA0
print(var.title())
# CONTA QUANTIDADE DE LETRAS T
print(var.count('T'))
# PROCURAR POSIÇÃO DA LETRA T
print(var.find('T'))
# QUANTIDADE DE CARACTERES DA STRING
print(len(var))
# JUNTA UMA LISTA EM UMA STRING
print(', '.join(['a', 'b', 'c']))
# EXPLODE UMA STRING EM UMA LISTA
print(var.split(','))
nome = "Igor"
sobrenome = "Valoto"
idade = 24
print(nome + " " + sobrenome)
print("Meu nome é: %s e tenho %s anos" % (nome, idade))
print("Meu nome é: {0} e tenho {1} anos".format(nome, idade))
var10 = "Meu nome é: {0} e tenho {1} anos".format(nome[:2], idade)
print(var10)
|
77865bbaf68b29ecbc5e9c5ece9c2e6f6ce2a9db | elocamp/Fundamentos-de-Problemas-Computacionais | /VA3/pilha.py | 867 | 3.859375 | 4 | class Pilha:
def __init__(self):
self.lista = []
self.topo = None
def __pilha_vazia(self):
if self.topo == None:
return True
else:
return False
def empilhar(self, valor):
self.lista.append(valor)
self.topo = self.lista[0]
def desempilhar(self):
if self.__pilha_vazia():
print("A pilha está vazia.")
else:
self.lista.pop(0)
if len(self.lista) > 1:
self.topo = self.lista[0]
else:
self.topo = None
def ver_pilha(self):
if len(self.lista) != 0:
print(self.lista)
else:
print("A pilha está vazia.")
def ver_topo(self):
print(self.topo)
pilha = Pilha() |
3e6bd4c07e4ebf9aae3044e62e76532954e58e74 | elocamp/Fundamentos-de-Problemas-Computacionais | /lista_linear.py | 2,071 | 3.75 | 4 | class Nodo:
def __init__(self, valor):
self.valor = valor
self.proximo = None
def mostrar_nodo(self):
print(self.valor)
class Lista:
def __init__(self):
self.primeiro = None
def inserir_lista(self, valor):
novo = Nodo(valor)
novo.proximo = self.primeiro
self.primeiro = novo
def mostrar_lista(self):
if self.primeiro == None:
print('A lista está vazia')
return None
atual = self.primeiro
while atual != None:
atual.mostrar_nodo()
atual = atual.proximo
def pesquisa_lista(self, valor):
if self.primeiro == None:
print("A lista está vazia.")
return None
atual = self.primeiro
while atual.valor != valor:
if atual.proximo == None:
return None
else:
atual = atual.proximo
return atual
def remover_lista(self, valor):
if self.primeiro == None:
print("A lista está vazia.")
return None
atual = self.primeiro
anterior = self.primeiro
while atual.valor != valor:
if atual.proximo == None:
return None
else:
anterior = atual
atual = atual.proximo
if atual == self.primeiro:
self.primeiro = self.primeiro.proximo
else:
anterior.proximo = atual.proximo
return atual
def remover_inicio(self):
if self.primeiro == None:
print('A lista está vazia')
return None
self.primeiro = self.primeiro.proximo
lista = Lista()
lista.inserir_lista('teste')
lista.inserir_lista('cachorro')
lista.inserir_lista('cachorro')
lista.mostrar_lista()
pesquisa = lista.pesquisa_lista('cachorro')
if pesquisa != None:
print('Encontrado:', pesquisa.valor)
else:
print('Não encontrado') |
9ea0061578d975f5b3480ec73db416db19a5619f | mpernow/eratosthenes | /db_entry.py | 3,832 | 4 | 4 | # Implementation of class for database entry
# Author: Marcus Pernow
# Date: January 2020
import uuid # For random filenames
class DB_Entry():
"""
Definition of a database entry.
Contains the required fields and methods
"""
def set_id(self):
"""
Sets the unique id of the entry, with an increasing counter
"""
# Open file and extract last id
f = open('id_num', 'r')
nums = f.readlines()
num = int(nums[-1][:-1]) + 1
f.close()
# set the id
self.id_num = num
# Append to the fil
f = open('id_num', 'a')
f.write(str(num)+'\n')
f.close()
def set_id_manual(self, id_num):
"""
Manually sets the id
"""
self.id_num = id_num
def set_title(self, title):
"""
Set the title of the entry
"""
self.title = title
def set_authors(self, authors):
"""
Set the authors of the entry
TODO: Put into correct format: "surname, firstname(s)"
separated by semicolon
"""
self.authors = authors
def set_year(self, year):
"""
Set the publication year
"""
if not type(year) == int:
raise ValueError('Year must be an integer')
self.year = year
def set_keywords(self, kw_list):
"""
Sets keywords of entry
"""
# Check that it is a list of strings:
if not all([type(i) == str for i in kw_list]):
raise ValueError('Must be list of strings')
for i in range(len(kw_list)):
kw_list[i] = kw_list[i].lower()
self.kw_list = kw_list
def set_type(self, publication_type):
"""
Set the publication type to book/article/review/other
"""
publication_type = publication_type.lower()
if not (publication_type == 'book' or publication_type == 'article' or publication_type == 'review' or publication_type == 'other'):
raise ValueError('Type must be book/article/review/other')
else:
self.publication_type = publication_type
def set_new_path(self, path = '/mnt/mystorage/pdfs/'):
"""
Sets the path of the entry with random file name
'path' is the directory with default './pdfs/'
TODO: Allow for non-pdf files
"""
f_name = uuid.uuid1().hex
self.path = path + f_name + '.pdf'
def set_path_manual(self, path):
"""
Manually set the path
"""
self.path = path
def get_title(self):
"""
Return the title of self
"""
return self.title
def get_authors(self):
"""
Return the authors of self
"""
return self.authors
def get_year(self):
"""
Returns the year of self
"""
return self.year
def get_keywords(self):
"""
Returns keyowrds of self as list of strings
"""
return self.kw_list
def get_pub_type(self):
"""
Returns the publication type of self
"""
return self.publication_type
def get_path(self):
"""
Returns the path of self
"""
return self.path
def get_id(self):
"""
Return the id of the entry
"""
return self.id_num
def __str__(self):
"""
Prints the entry nicely
"""
return str(self.id_num) + '\t|\t' + self.title + '\t|\t' + self.authors + '\t|\t' + str(self.year)
def make_entry(row):
"""
Takes a row from querying database and creates an entry object
"""
entry = DB_Entry()
entry.set_id_manual(row[0])
entry.set_title(row[1])
entry.set_authors(row[2])
entry.set_year(row[3])
entry.set_type(row[4])
entry.set_keywords(row[5].split(';'))
entry.set_path_manual(row[6])
return entry
if __name__ == "__main__":
print("Testing the code:")
test_entry = DB_Entry()
title = 'Best article ever'
print('Setting title to '+title)
test_entry.set_title(title)
author = 'Marcus Pernow'
print('Setting author to '+author)
test_entry.set_authors('Marcus Pernow')
year = 2020
print('Setting year to '+str(year))
test_entry.set_year(year)
keywords = ['physics','mathematics','truth','philosophy']
print('Setting keywords list to \n\t'+',\n\t'.join(keywords))
pub_type = 'article'
print('Setting type to '+pub_type)
test_entry.set_type(pub_type)
|
499570e9e7d06c0f5f19abd984d63c5fd6763123 | wbsth/mooc-da | /part05-e12_coefficient_of_determination/src/coefficient_of_determination.py | 910 | 3.671875 | 4 | #!/usr/bin/env python3
import pandas as pd
from sklearn import linear_model
def coefficient_of_determination():
# loading the data, tab as separator
df = pd.read_csv('src/mystery_data.tsv', sep='\t')
# different dataframes for X's and Y's columns
x = df.loc[:, 'X1':'X5']
y = df.loc[:, 'Y']
# creating linear regression model
model = linear_model.LinearRegression(fit_intercept=True)
# training model using data
model.fit(x, y)
score = model.score(x, y)
rtr = [score]
for i in range(len(x.columns)):
a = x.iloc[:, i].values.reshape(-1, 1)
model.fit(a, y)
rtr.append(model.score(a, y))
return rtr
def main():
x = coefficient_of_determination()
print(f"R2-score with feature(s) X: {x[0]}")
for i in range(1, len(x)):
print(f"R2-score with feature(s) X{i}: {x[i]}")
if __name__ == "__main__":
main()
|
09b02405344102c647fd9fe5745b540957d7bd72 | wbsth/mooc-da | /part02-e09_rational/src/rational.py | 2,219 | 3.890625 | 4 | #!/usr/bin/env python3
class Rational(object):
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
def __str__(self):
return f'{self.numerator}/{self.denominator}'
def __add__(self, numb):
new_denom = int(self.denominator) * int(numb.denominator)
mult1 = new_denom / self.denominator
mult2 = new_denom / numb.denominator
new_nume = int(mult1 * int(self.numerator) + mult2 * int(numb.numerator))
return Rational(new_nume, new_denom)
def __sub__(self, numb):
new_denom = int(self.denominator) * int(numb.denominator)
mult1 = new_denom / self.denominator
mult2 = new_denom / numb.denominator
new_nume = int(mult1 * int(self.numerator) - mult2 * int(numb.numerator))
return Rational(new_nume, new_denom)
def __mul__(self, numb):
#multiplication
new_denom = int(self.denominator * numb.denominator)
new_nume = int(self.numerator * numb.numerator)
return Rational(new_nume, new_denom)
def __truediv__(self, numb):
new_nume = int(self.numerator * numb.denominator)
new_denom = int(self.denominator * numb.numerator)
return Rational(new_nume, new_denom)
def __eq__(self, numb):
return self.numerator == numb.numerator and self.denominator == numb.denominator
def __gt__(self, numb):
new_denom = int(self.denominator) * int(numb.denominator)
mult1 = new_denom / self.denominator
mult2 = new_denom / numb.denominator
return mult1 * self.numerator > mult2 * self.denominator
def __lt__(self, numb):
new_denom = int(self.denominator) * int(numb.denominator)
mult1 = new_denom / self.denominator
mult2 = new_denom / numb.denominator
return mult1 * self.numerator < mult2 * self.denominator
def main():
r1=Rational(1,4)
r2=Rational(2,3)
print(r1)
print(r2)
print(r1*r2)
print(r1/r2)
print(r1+r2)
print(r1-r2)
print(Rational(1,2) == Rational(2,4))
print(Rational(1,2) > Rational(2,4))
print(Rational(1,2) < Rational(2,4))
if __name__ == "__main__":
main()
|
5e6e2e5e3d29dc46c9e5a9e7bc49a5172fbbb3cb | wbsth/mooc-da | /part01-e07_areas_of_shapes/src/areas_of_shapes.py | 935 | 4.1875 | 4 | #!/usr/bin/env python3
import math
def main():
while True:
shape = input('Choose a shape (triangle, rectangle, circle): ')
if shape == '':
break
else:
if shape == 'rectangle':
r_width = int(input("Give width of the rectangle: "))
r_height = int(input("Give height of the rectangle: "))
print(f"The area is {r_height * r_width}")
elif shape == 'triangle':
t_base = int(input("Give base of the triangle: "))
t_height = int(input("Give height of the triangle: "))
print(f"The area is {0.5*t_base*t_height}")
elif shape == 'circle':
c_radius = int(input("Give radius of the circle: "))
print(f"The area is {math.pi * c_radius ** 2}")
else:
print('Unknown shape!')
if __name__ == "__main__":
main()
|
1bc9afe41a145b0feba124487c65ccb717803f58 | SanjoSolutions/tic-tac-toe-solver | /solve_tic_tac_toe.py | 3,143 | 3.5 | 4 | from generate_tic_tac_toe_tree import generate_tic_tac_toe_tree
from main import history_to_state, determine_result, Result
def create_tic_tac_toe_solving_tree():
tree = generate_tic_tac_toe_tree()
calculate_percentages_of_loose_outcomes_recursion(tree.root)
return tree
def calculate_percentages_of_loose_outcomes_recursion(node):
history = node.value
state = history_to_state(history)
result = determine_result(state)
if result is not None:
percentage_of_loose_outcomes_for_player_one = 1.0 if result == Result.PlayerTwoWon else 0.0
percentage_of_loose_outcomes_for_player_two = 1.0 if result == Result.PlayerOneWon else 0.0
node.percentage_of_loose_outcomes_for_player_one = percentage_of_loose_outcomes_for_player_one
node.percentage_of_loose_outcomes_for_player_two = percentage_of_loose_outcomes_for_player_two
return percentage_of_loose_outcomes_for_player_one, percentage_of_loose_outcomes_for_player_two
else:
percentages_of_loose_outcomes_for_player_one = []
percentages_of_loose_outcomes_for_player_two = []
for child in node.children:
percentage_of_loose_outcomes_for_player_one, percentage_of_loose_outcomes_for_player_two = \
calculate_percentages_of_loose_outcomes_recursion(child)
percentages_of_loose_outcomes_for_player_one.append(percentage_of_loose_outcomes_for_player_one)
percentages_of_loose_outcomes_for_player_two.append(percentage_of_loose_outcomes_for_player_two)
percentage_of_loose_outcomes_for_player_one = sum(percentages_of_loose_outcomes_for_player_one) / \
float(len(percentages_of_loose_outcomes_for_player_one))
percentage_of_loose_outcomes_for_player_two = sum(percentages_of_loose_outcomes_for_player_two) / \
float(len(percentages_of_loose_outcomes_for_player_two))
node.percentage_of_loose_outcomes_for_player_one = percentage_of_loose_outcomes_for_player_one
node.percentage_of_loose_outcomes_for_player_two = percentage_of_loose_outcomes_for_player_two
return percentage_of_loose_outcomes_for_player_one, percentage_of_loose_outcomes_for_player_two
def determine_optimal_move_for_player_one(node):
return find_child_node_with_lowest_percentage_of_loose_outcomes(node, determine_percentage_of_loose_outcomes_for_player_one)
def determine_optimal_move_for_player_two(node):
return find_child_node_with_lowest_percentage_of_loose_outcomes(node, determine_percentage_of_loose_outcomes_for_player_two)
def find_child_node_with_lowest_percentage_of_loose_outcomes(node, get_chance_to_loose):
return find_node_with_lowest_percentage_of_loose_outcomes(node.children, get_chance_to_loose)
def find_node_with_lowest_percentage_of_loose_outcomes(nodes, get_chance_to_loose):
return min(nodes, key=get_chance_to_loose)
def determine_percentage_of_loose_outcomes_for_player_one(node):
return node.percentage_of_loose_outcomes_for_player_one
def determine_percentage_of_loose_outcomes_for_player_two(node):
return node.percentage_of_loose_outcomes_for_player_two
|
3d1b52f962c935e2426483a007fd9cd37839ac31 | AravindSK1/Code-Everyday | /01. Python/Day 0018.py | 4,120 | 4.3125 | 4 | """
Singly Linked list
1. class nodes : data, next
2. class linked list: impor
3. add nodes to linked list
4. print linked list
"""
class Nodes:
def __init__(self, data):
self.data = data
self.next = None # stores the node object
class LinkedList:
# initialize head as None for emplty linked list
def __init__(self):
self.head = None
# length of the linked list
def list_length(self):
currentNode = self.head
length = 1
while currentNode.next is not None:
currentNode = currentNode.next
length+=1
return length
# insert node at head
def insertNode_head(self, newNode):
"""
1. Create a temp node and store the current head node
2. Make the new node as the head node
3. Make the next of your new node point to the temp node
4. Del the temp node
"""
tempNode = self.head
self.head = newNode
self.head.next = tempNode
del tempNode
# insert a new node at the end of the list
def insertNode_last(self, newNode):
if self.head is None:
self.head = newNode
else:
# find the last node
"""
1. To find the last node, traverse through the linked list
2. Start with the head
3. if head.next is not None, then go to the next node
"""
lastNode = self.head
while True:
if lastNode.next is None:
break
lastNode = lastNode.next
lastNode.next = newNode
# insert node at desired position
def insertNode_at(self, newNode, position):
# insert at head
if position == 0:
self.insertNode_head(newNode)
return
# to handle negative positions
if position < 0:
print("Incorrect position.. Inserting the element at the head")
self.insertNode_head(newNode)
return
# to handle position greater than the list lenght
len_list = self.list_length()
if position > len_list:
print(f"Incorrect position.. Current list length is {len_list}. Inserting the element at the end of the list..")
self.insertNode_last(newNode)
return
# For position between head and tail
current_position = 0
currentNode = self.head
while True:
if position == current_position:
"""
1. Store the details of the previous node
2. Make a connection from the next of the previous node to the new node
3. Make a connection from the next of the newNode to the node at position
4. The position gets changed. The new node becomes the node at position
5. The node at position becomes position + 1
"""
previousNode.next = newNode
newNode.next = currentNode
break
previousNode = currentNode
currentNode = currentNode.next
current_position += 1
# delete a node at the end of the list
def deleteNode_last(self):
"""
1. Traverse till the end of the list
2.
"""
# print linked list
def printList(self):
if self.head is None:
print("List is empty")
currentNode = self.head
while True:
if currentNode is None:
break
print(currentNode.data)
currentNode = currentNode.next
if __name__ == '__main__':
# data
firstnode = Nodes("Aravind")
secondnode = Nodes("Rishi")
thirdnode = Nodes("Amma and Appa")
# create a linked list object
ll = LinkedList()
# nodes to be inserted sequentially
nodes = [firstnode, secondnode]
# start adding nodes at the last
for n in nodes:
ll.insertNode_last(n)
# insert node at a specific position
ll.insertNode_at(thirdnode,10)
# print the linked list
ll.printList()
|
56ea90dad7f9aac37497e783af60b901bf31da4a | adityaronanki/pytest | /assignment_06.py | 1,946 | 3.734375 | 4 | __author__ = 'Khali'
from placeholders import *
# instead of returning a list of tuples like zip, generate it incrementally (refer to the generators and iterators lessons)
# a tuple at a time. Use exception control flow to write elegant code.
def generator_zip(seq1, seq2, *more_seqs):
items=[]
if len(more_seqs) !=0 :
items.append(iter(seq1))
items.append(iter(seq2))
for x in more_seqs:
items.append(iter(x))
while 1:
try:
tup = [i.next() for i in items]
yield tuple(tup)
except StopIteration:
return
else :
items.append(iter(seq1))
items.append(iter(seq2))
while 1:
try:
tup = [i.next() for i in items]
yield tuple(tup)
except StopIteration:
return
def check_generator(gen, max_count, tuple_length):
for x in range(max_count):
result = next(gen)
assert len(result) == tuple_length, "invalid length"
for element in result:
assert x == element, "unexpected value"
try:
next(gen)
assert False, "generator did not finish as expected"
except StopIteration as se:
pass
def test_generator_zip():
gen = generator_zip(range(5), range(3), range(4), range(5))
assert type(gen).__name__ == 'generator'
check_generator(gen, 3, 4)
gen = generator_zip(range(5), range(3), range(2))
assert type(gen).__name__ == 'generator'
check_generator(gen, 2, 3)
gen = generator_zip(range(1,5), "abc", [1,2])
assert [(1,'a', 1), (2, 'b', 2)] == list(gen)
gen = generator_zip((1,2), "abcd")
assert [(1,'a'), (2, 'b')] == list(gen)
three_things_i_learnt = """
-
-
-
"""
time_taken_minutes = ___
|
a2ba2d26676a7f57245278da36b71572aed3c134 | KrastinsE/EDIBO | /Python/dev/history20200813c.py | 2,242 | 3.578125 | 4 | 1: def f(): pass
2: f()
3: type(f)
4: def f(): print("Hello")
5: def f(): print("Hello")
6: def f(): print("Hello")
7: f()
8:
def g():
a = 22
print(a+3)
9: g()
10:
def g(a):
print(a+3)
11: g()
12:
def g(a):
print(a+3)
13: g()
14: g(a)
15: g(20)
16: g()
17: g(20)
18:
def g(a):
c = a+3
print(c)
19: g(20)
20:
def h():
a = 11
b = 22
c = a + b
print(c)
21: h(10)
22:
def h():
a = 11
b = 22
c = a + b
print(c)
23: h(100)
24:
def h(a, b):
c = a + b
print(c)
25: h(10)
26: h(1, 2)
27:
def h():
a = 11
b = 22
c = a + b
print(c)
28: h(10+10)
29: h(10, 10)
30:
def h2 (a=22, b=33):
c = a + b
print(c)
31: h2()
32: h2(3, 4)
33:
def f2(a, b):
return(a+b)
34: f2(3, 4)
35: history
36: pwd
37: mkdir dev
38: cd dev
39: pwd
40: mkdir python_files
41: ls -l
42: pwd
43: echo Helo
2/1: ls -l
2/2: f = open("a.dat")
2/3: f.close()
2/4: type(f)
2/5: cat a.dat
2/6: f = open("a.dat")
2/7: f.
2/8: f.readlines()
2/9: f.readlines()
2/10: f.readlines()
2/11: f.close()
2/12: f = open("a.dat")
2/13: f.readlines()
2/14: f.close()
2/15: f.readlines()
2/16: f = open("a.dat")
2/17: f.close()
2/18: f = open("a.dat")
2/19: s = f.readlines()
2/20: f.close()
2/21: s
2/22: print(s)
2/23: print(s+s)
2/24: print(s+s+s+s+s)
2/25: type(s)
2/26: s[0]
2/27: f = open("a.dat")
2/28: f.tell()
2/29: s = f.readlines()
2/30: f.tell()
2/31: f.seek(3)
2/32: f.readlines()
2/33: f.close()
2/34: f = open("a.dat", "w")
2/35: ls -l
2/36: cat. a.dat
2/37: f.readlines ()
2/38: f = open("a.dat", "R")
2/39: f = open("a.dat", "r")
2/40: f.readlines ()
2/41: ls -l
2/42: f.seek
2/43: f.seek()
2/44: f.readlines ()
2/45: f.write("DEIBO")
2/46: f = open("a.dat")
2/47: f.write("DEIBO")
2/48: f.write("EDIBO")
2/49: f.closed
2/50: f.close()
2/51: f.closed
2/52: f = open("a.dat", "a")
2/53:
f.write("\n 2020 \n)
"
2/54: f.write( "\n 2020 \n ")
2/55: pwd
2/56: ls -lt
2/57: %history -g -f = history20200813b.py
2/58: ls -l
2/59: ls -lt
2/60: cd dev
2/61: cd .
2/62: cd . .
2/63: cd ..
2/64: ls -lt
2/65: cd ..
2/66: ls -lt
2/67: history
44: history
45: %history > -g -f history20200813c.py
|
6e8f6b42a872c1aacf7daf1fc4042213f5c7d008 | djmattyg007/IdiotScript | /idiotscript/InstructionList.py | 2,581 | 3.859375 | 4 | class InstructionList(object):
'''
An instruction list is the result of parsing an
idiotscript script. It may have nested instruction
lists, which is the result of branching in the
idiotscript. This implementation uses a linked list.
'''
def __init__(self):
self._head = None
self._tail = None
self._current = None
def isempty(self):
return self._head == None
def add(self, instruction, branch = None):
new_node = self.Node(instruction, branch)
if self.isempty() == True:
self._head = new_node
else:
self._tail.successor = new_node
self._tail = new_node
def __str__(self):
return InstructionList.str_ilist(self)
@staticmethod
def str_ilist(ilist, depth = 0):
'''
Pretty-prints an instruction list, representing branches
with indented lines.
'''
temp = ""
for instruction, branch in ilist:
temp += " " * depth
temp += str(instruction) + "\n"
if branch is not None:
temp += InstructionList.str_ilist(branch, depth + 1)
return temp
def __iter__(self):
self.reset()
return self
def __next__(self):
'''
Returns a tuple containing the current instruction,
and a nested instruction list (the branch) if it is
a branching instruction.
'''
if self._current is None:
raise StopIteration
instruction = self._current.instruction
branch = self._current.branch
self._current = self._current.successor
return (instruction, branch)
def reset(self):
'''
In order to support the "repeat" instruction, it
is necessary to be able to manually reset the iterator
back to the start of the instruction list.
'''
self._current = self._head
class Node(object):
def __init__(self, instruction, branch = None):
self._instruction = instruction
self._branch = branch
self._successor = None
@property
def instruction(self):
return self._instruction
@property
def successor(self):
return self._successor
@successor.setter
def successor(self, successor):
self._successor = successor
@property
def branch(self):
return self._branch
@branch.setter
def branch(self, ilist):
self._branch = ilist
|
f613fa6f9dbf7713a764a6e45f29ef8d67a5f39c | abhishek0chauhan/rock-paper-scissors-game | /main.py | 1,431 | 4.25 | 4 | import random
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
#print(scissors)
your_choice = int(input("What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors."))
random_computer_choice = random.randint(0,2)
#for computer
if random_computer_choice == 0:
print(f"{rock}\nComputer chose:")
elif random_computer_choice == 1:
print(f"{paper}\nComputer chose:")
elif random_computer_choice == 2:
print(f"{scissors}\nComputer chose:")
#for player
if your_choice == 0:
print(rock)
elif your_choice == 1:
print(paper)
elif your_choice == 2:
print(scissors)
# logic of game
if your_choice == random_computer_choice:
print('game tied')
elif your_choice == 0 and random_computer_choice == 1:
print("You lose")
elif your_choice == 0 and random_computer_choice == 2:
print('You win')
elif your_choice == 1 and random_computer_choice == 0:
print('You win')
elif your_choice == 1 and random_computer_choice == 2:
print('You lose')
elif your_choice == 2 and random_computer_choice == 0:
print("You lose")
elif your_choice == 2 and random_computer_choice == 1:
print("You win")
else:
print('You typed a invalid number!\nYou lose') |
28b93baa03b5cde60026d8db53eef1be2078100a | srikanthpragada/09_MAR_2018_PYTHON_DEMO | /assignments/find_positions.py | 139 | 3.625 | 4 | st = "Python Programming is fun"
sub = "n"
pos = st.find(sub)
while pos >= 0:
print("Found at ", pos)
pos = st.find(sub, pos + 1)
|
011de1ba4282c802896eb1dcab9dfed9d40e4b1a | srikanthpragada/09_MAR_2018_PYTHON_DEMO | /libdemo/get_country_info.py | 253 | 3.8125 | 4 | import requests
code = input("Enter country code :")
resp = requests.get("https://restcountries.eu/rest/v2/alpha/" + code)
info = resp.json()
if 'name' in info:
print(info["name"])
print(info["capital"])
else:
print("Country Not Found!")
|
131dadb4a22587791dc04c17e7749d3fefc8b0e6 | srikanthpragada/09_MAR_2018_PYTHON_DEMO | /oop/even_iterator.py | 466 | 3.90625 | 4 |
class EvenIterator:
def __init__(self,start, end):
self.start = start if start % 2 == 0 else start + 1
self.end = end
def __iter__(self):
self.value = self.start
return self
def __next__(self):
if self.value <= self.end:
v = self.value
self.value += 2
return v
else:
raise StopIteration
# use Iterator
en = EvenIterator(15,25)
for n in en:
print(n)
|
afc502fd894e0319fb56f6217f21a3b934829d0c | srikanthpragada/09_MAR_2018_PYTHON_DEMO | /db/add_emp.py | 539 | 3.984375 | 4 | import sqlite3
try:
con = sqlite3.connect(r"e:\classroom\python\hr.db")
cur = con.cursor()
# take input from user
ename = input("Enter name :")
salary = input("Enter salary : ")
dept = input("Enter dept id :")
# get next emp id
cur.execute("select max(empid) + 1 from emp")
empid = cur.fetchone()[0]
cur.execute("insert into emp values(?,?,?,?)", (empid, ename, salary, dept))
con.commit()
print("Added Employee")
except Exception as ex:
print("Error : ", ex)
finally:
con.close()
|
7bcab8db6bbb8aac0814cf48b5b97583c14e1d67 | srikanthpragada/09_MAR_2018_PYTHON_DEMO | /oop/Product.py | 803 | 3.59375 | 4 | from Account import *
class Product:
def __init__(self, name, price=None):
# instance variables
self.__name = name
self.__price = price
@property
def netprice(self):
return self.__price * 1.12
def print(self):
print('Name ', self.__name)
print("Price ", self.__price)
def __str__(self):
# return "%s %d" % (self.__name, self.__price)
return "{0} {1}".format(self.__name, self.__price)
def __eq__(self, other):
return self.__name == other.__name
# def __gt__(self, o):
# return self.__price > o.__price
p1 = Product("iPhone X", 70000)
print(str(p1))
p2 = Product("iPhone 8", 60000)
print(p1 != p2) # calls __eq__ and negates
print(p1.netprice)
p1 = Account(1,"Abc",20000);
p1.print()
|
49def8344863803a18df98709fa803d5076cc6e7 | Roma-coder/Python_Labs | /Lab_4/main.py | 914 | 3.546875 | 4 | from datetime import datetime
from patient import Patient
patients = []
with open('data.txt', 'r', encoding='utf-8') as dataFile:
for line in dataFile:
words = line.split(';')
p = Patient(
words[0],
words[1],
words[2],
datetime(year=int(words[3]), month=int(words[4]), day=int(words[5])),
words[6],
int(words[7]),
int(words[8]),
words[9],
)
patients.append(p)
smallest_patient = 999
all_male_height = 0
male_count = 0
for patient in patients:
if patient.weight <= smallest_patient:
smallest_patient = patient.weight
if patient.sex == 'Чоловік':
all_male_height += patient.height
male_count += 1
middle_height = all_male_height / male_count
print('Smallest patient: ', smallest_patient)
print('Middle height: ', middle_height) |
a0516d0ca0791c8584b51cee2e354113f03a74f1 | LFBianchi/pythonWs | /Learning Python/Chap 4/p4e6.py | 839 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Exercise 5 of the Part IV of the book "Learning Python"
Function "addDict" - Returns a union of dictionaries
Created on Mon Nov 9 11:06:47 2020
@author: lfbia
"""
def addList(list1, list2):
return list1 + list2
def addDict(aurelio, michaellis):
D = {}
for i in aurelio.keys():
D[i] = aurelio[i]
for i in michaellis.keys():
D[i] = michaellis[i]
return D
def addListDict(A, B):
if type(A) == list: return addList(A, B)
else: return addDict(A, B)
print(addListDict({'edi': 1,
'noelia': 2,
'anselmo': 4},
{'nilcilene': 54,
'arlete': 55,
'sandra': 8}))
print(addListDict([1, 2, 3, 4, 5],
[5, 3, 4, 5]))
print(addListDict([5, 3, 4, 5],
[1, 2, 3, 4, 5])) |
fd089aac91671c8504e125d4e8db6e058c5afda7 | LFBianchi/pythonWs | /HackerRank/hashTablesRansomNote.py | 1,168 | 3.765625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the checkMagazine function below.
"""
def checkMagazine(magazine, note): #using dictcomp
hashWords = {x: magazine.count(x) for x in set(note)}
if list(hashWords.values()).count(0):
print('No')
else:
hashNoteWords = {x: (hashWords[x] - note.count(x)) for x in set(note)}
if [x for x in hashNoteWords.values() if x < 0]:
print('No')
else:
print('Yes')
"""
def checkMagazine(magazine, note):
hashWords = {}
for word in magazine:
if word not in hashWords:
hashWords[word] = 0
hashWords[word] += 1
for word in note:
if word not in hashWords:
return 'No'
else:
hashWords[word] -= 1
if hashWords[word] < 0:
return 'No'
else: return 'Yes'
if __name__ == '__main__':
mn = input().split()
m = int(mn[0])
n = int(mn[1])
magazine = input().rstrip().split()
note = input().rstrip().split()
print(checkMagazine(magazine, note))
|
474b8dfed6ba1bab4d2f026b025c04407c45d776 | LFBianchi/pythonWs | /Learning Python/Chap 3/p3e4d.py | 127 | 3.640625 | 4 | L = [2 ** i for i in range(7)]
X = 5
pot = 2 ** X
if pot in L:
print('at index', L.index(pot))
else:
print(X, 'not found') |
4957835e457481b3dc71f11f9f6d54d6ba08a01a | LFBianchi/pythonWs | /HackerRank/treeLevelOrderTraversal(while).py | 534 | 3.828125 | 4 |
"""
Node is defined as
self.left (the left child of the node)
self.right (the right child of the node)
self.info (the value of the node)
"""
def levelOrder(root):
nodeQueue = [root]
levelList = []
while nodeQueue:
if nodeQueue[0].left:
nodeQueue.append(nodeQueue[0].left)
if nodeQueue[0].right:
nodeQueue.append(nodeQueue[0].right)
levelList.append(nodeQueue[0].info)
nodeQueue.pop(0)
else:
print(' '.join(map(str, levelList)))
|
89761057d2885d4285e7031cee4c0a230a95ead8 | LFBianchi/pythonWs | /HackerRank/nestedLists.py | 430 | 3.75 | 4 | def secondWorst(arr):
grades = {}
for i in arr:
grades[i[0]] = i[1]
arr = sorted(list(set(grades.values())))
ans = [i for i in grades if grades[i] == arr[1]]
return sorted(ans)
if __name__ == '__main__':
arr = []
for _ in range(int(input())):
name = input()
score = float(input())
arr.append([name, score])
for i in secondWorst(arr):
print(i)
|
312967267570056e85591c7224e488a616acc877 | LFBianchi/pythonWs | /Learning Python/Chap 4/p4e10.py | 833 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Exercise 10 of the Part IV of the book "Learning Python"
Timing three ways to get the square root of a number
Created on Mon Nov 9 16:12:52 2020
@author: lfbia
"""
#Modified from file timeseqs.py
#Test the relative speed of iteration tool alternatives.
import sys, math, timer1 as timer # Import timer functions
reps = 10000
repslist = list(range(reps)) # Hoist out, list in both 2.X/3.X
def usingmath():
return [math.sqrt(x) for x in repslist]
def usingasterisk():
return [x**.5 for x in repslist]
def usingpow():
return [pow(x, .5) for x in repslist]
print(sys.version)
for test in (usingmath, usingasterisk, usingpow):
(bestof, (total, result)) = timer.bestoftotal(5, 1000, test)
print ('%-9s: %.5f => [%s...%s]' %
(test.__name__, bestof, result[0], result[-1]))
|
26ab425409f7f7944820a460b4676c1cbd54a16d | nasrinsultana014/HackerRank-Python-Problems | /Solutions/Problem08.py | 774 | 3.515625 | 4 | if __name__ == '__main__':
x = int(input())
y = int(input())
z = int(input())
n = int(input())
permutationCollection = []
for i in range(x+1):
for j in range(y+1):
for k in range(z+1):
sum = i+j+k
if sum != n:
oneCombo = "[" + str(i) + ", " + str(j) + ", " + str(k) + "]"
permutationCollection.append(oneCombo)
length = len(permutationCollection)
print("[", end="")
for i in range(length):
if i == (length-1):
print(permutationCollection[i], end="")
elif i == 0:
print(permutationCollection[i], end=", ")
else:
print(permutationCollection[i], end=", ")
print("]", end="") |
d3e64c5bfe6b5508c458a2bc76e40fa6ef0f4019 | nasrinsultana014/HackerRank-Python-Problems | /Solutions/Problem14.py | 536 | 4.21875 | 4 | def swap_case(s):
characters = list(s)
convertedCharacters = []
convertedStr = ""
for i in range(len(characters)):
if characters[i].isupper():
convertedCharacters.append(characters[i].lower())
elif characters[i].islower():
convertedCharacters.append(characters[i].upper())
else:
convertedCharacters.append(characters[i])
return convertedStr.join(convertedCharacters)
if __name__ == '__main__':
s = input()
result = swap_case(s)
print(result) |
e25145805f35e7124c290af6ea774296b6a83a67 | DiegoCefalo/GetVidya | /tools/sql_tools.py | 5,271 | 3.53125 | 4 | from config.configuration import engine
import pandas as pd
def collection():
"""
Queries all the games in the database
Args:
Returns:
json with all the games in the database
"""
query = f"""
SELECT * FROM videogame
"""
datos = pd.read_sql_query(query,engine)
return datos.to_json(orient="records")
def score(game):
"""
Queries games scores in the database
Args:
game (str): name of the game we want to know the score of.
Returns:
json with score of the game
"""
query = f"""
SELECT score FROM videogame WHERE name = '{game}'
"""
datos = pd.read_sql_query(query,engine)
return datos.to_json(orient="records")
def gamecomments(game,limit = 1000):
"""
Queries all the comments from a game in the database.
Args:
game (str): name of the game
limit (int): number of comments to return (max 1000)
Returns:
json with all the comments from a game or the maximum specified.
"""
query = f"""
SELECT videogame.name, comments.comment FROM videogame
JOIN comments
WHERE videogame.name = '{game}'
LIMIT {limit}
"""
datos = pd.read_sql_query(query,engine)
return datos.to_json(orient="records")
def gameplatforms(game,limit = 1000):
"""
Queries all the platforms from a game in the database.
Args:
game (str): name of the game
limit (int): number of platforms to return (max 1000)
Returns:
json with all the platforms from a game or the maximum specified.
"""
query = f"""
SELECT videogame.name, platform.name AS platform FROM videogame
JOIN platform
WHERE videogame.name = '{game}'
LIMIT {limit}
"""
datos = pd.read_sql_query(query,engine)
return datos.to_json(orient="records")
def getid(table,string):
"""
Gets the id of the thing you are looking for in the database
Args:
table (str): name of the table
string (str): name of the thing you are looking for
Returns:
theid (int): id of the thing you are looking for
"""
theid = engine.execute(f"SELECT id FROM {table} WHERE name = '{string}'").first()[0]
return theid
def check(selector,string):
"""
check if an entry already exists.
Args:
selector (str): category to check in tables.
string (str): string to check in category.
Returns:
Boolean: true if exists, false if it doesnt.
"""
if selector == "videogame":
query = list(engine.execute(f"SELECT name FROM videogame WHERE name = '{string}';"))
if len(query) > 0:
return True
else:
return False
elif selector == "platform":
query = list(engine.execute(f"SELECT name FROM platform WHERE name = '{string}'"))
if len(query) > 0:
return True
else:
return False
elif selector == "comment":
query = list(engine.execute(f"SELECT comment FROM comments WHERE comment = '{string}'"))
if len(query) > 0:
return True
else:
return False
def insertgame(game):
"""
Inserts a game into the videogame table.
Args:
game (str): name of the game to insert
Returns:
confirmation message: "Inserted correctly: (name of the game)"
"""
engine.execute(f"""
INSERT INTO videogame (name)
VALUES ('{game}');
""")
return f"Inserted correctly: {game}"
def insertplatform(platform):
"""
Inserts a platform into the platform table.
Args:
platform (str): name of the platform to insert
Returns:
confirmation message: "Inserted correctly: (name of the platform)"
"""
engine.execute(f"""
INSERT INTO platform (name)
VALUES ('{platform}');
""")
return f"Se ha introducido correctamente: {platform}"
def new_comment(videogame, platform, username, comment):
"""
Inserts a comment into the database.
Args:
game (str): name of the game to insert
platform (str): name of the platform to insert
username (str): name of the poster
comment (str): comment to be loaded
Returns:
confirmation message: "Comment successfully loaded" when successful
rejection message: "This comment has already been posted" when the comment is already in the database
"""
if check("videogame", videogame):
game_id = getid("videogame", videogame)
else:
insertgame(videogame)
game_id = getid("videogame", videogame)
if check("platform", platform):
plat_id = getid("platform", platform)
else:
insertplatform(platform)
plat_id = getid("platform", platform)
if check("videogame", videogame) and check("platform", platform) and check("comment", comment):
return "This comment has already been posted"
else:
engine.execute(f"""
INSERT INTO comments (comment, videogame_idname, username) VALUES
("{comment}", "{game_id}", "{username}");
""")
return f"Comment successfully loaded" |
394988fc43347898e589148f21777263d78b6bc5 | Israel0806/python | /Ejercicios-Python/Tarea2/asd.py | 468 | 3.84375 | 4 | ##matriz multi
def multiplicacion(A,B):
C=[]
##m=filas de A, p=filas de B n=co
m=3
n=2
p=2
q=3
for k in range(m):
C.append([0]*q)
for i in range(q):
C[k][i]=0
for i in range(m):
for j in range(n):
for k in range(q):
C[i][k]+=A[i][j]*B[j][k]
for k in range(m):
print C[k]
A=[[2, 6],[1, 5],[1, 3]]
B=[[9, 7, 8],[4, 6, 8]]
print multiplicacion(A,B)
|
1ac8195b75d4ea99794791ab5bc6e7a502b1fe06 | Israel0806/python | /Ejercicios-Python/Tarea recursiva Segovia/Ejer5.py | 120 | 3.875 | 4 | def serie(n):
if n==0:
return 3
return 3*serie(n-1)+4
n=int(input("Ingrese numero: "))
print (serie(n))
|
26a225ba03cb7283c98b6a587879f7a0324e895b | Tralo/python_study | /demo/exercise.py | 315 | 3.828125 | 4 | #!/usr/bin/env python
# coding=utf-8
weight = 60
height = 1.65
result = weight / (height * height)
print('BMI的值为: ',result)
if result < 18.5:
print('过轻')
elif result < 25:
print('正常')
elif result < 28:
print('过重')
elif result < 32:
print('肥胖')
else:
print('严重肥胖')
|
4f28a7b82294ded693713370383e2dfce38063ab | CristyTarantino/toolkitten | /summer-of-code/week-01/wk1-homework-submissions/soc-wk01-cert-cristina-tarantino.py | 18,339 | 4.21875 | 4 | """
Description - Week 1 homework for 1mwtt program
Author - Cristina Tarantino
Date - July 2018
"""
from datetime import datetime
from random import randint
days_in_year = 365
# year leap. Source https://en.wikipedia.org/wiki/Year#Variation_in_the_length_of_the_year_and_the_day
days_in_year_leap = 365.2422
# 60 minutes/hour * 24 hours/day
minutes_in_a_day = 60 * 24
# 60 seconds/minute * 60 minutes/hour * 24 hours/day
seconds_in_a_day = 60 * 60 * 24
seconds_in_a_year = seconds_in_a_day * days_in_year
seconds_in_a_year_leap = seconds_in_a_day * days_in_year_leap
seconds_in_milliseconds = 1000
# 1. Hours in a year. How many hours are in a year?
# a day has 24h and a year has 365 days
# therefore
# 1 common year = 365 days = (365 days) times (24 hours/day) = 8760 hours
print("\nHours in a year: " + str(24 * days_in_year))
# 2. Minutes in a decade. How many minutes are in a decade?
# 60 (minutes in 1 hour) times 24 (hours in a day) times 365 times 10 = 5256000 (Integer)
print("\nMinutes in a decade: " + str(minutes_in_a_day * days_in_year * 10))
# If we want to be more accurate though we should know that
# a year is actually 365.2422 making the calculation = to 5259487.68 (Float)
# source https://en.wikipedia.org/wiki/Year#Variation_in_the_length_of_the_year_and_the_day
print("\nMinutes in a decade considering leaps: " + str(minutes_in_a_day * days_in_year_leap * 10))
# 3. Your age in seconds. How many seconds old are you?
# 60 seconds/minutes * 60 minutes/hours * 24 hours/days * 365.2422 days/year * 32 year
my_age = 32
print("\nMy age in seconds: " + str(seconds_in_a_year_leap * my_age))
# 4. Andreea is 48618000 seconds old. Calculate her age
# example showing use of escape characters
andreea_seconds_old = 48618000
print('\nAndreea\'s age: ' + str(andreea_seconds_old / seconds_in_a_year_leap))
# https://github.com/1millionwomentotech/toolkitten/issues/35
print("\nAndreea's corrected age: " + str(andreea_seconds_old / seconds_in_a_year_leap * 24))
# 5. How many days does it take for a 32-bit system to timeout, if it has a bug with integer overflow?
# The Binary Register Width of a processor determines the range of values that can be represented.
# The maximum representable value for a 32-bit system will be 2^32-1
# When an arithmetic operation (in this case the increment of a millisecond in the time)
# produces a result larger than the above we will have an `integer overflow`
# To calculate the days it will take to reach that situation for a 32-bit system
# we need to convert 2^32 milliseconds in days by dividing by 1000s then 60s then 60m 24h
# source https://en.wikipedia.org/wiki/Integer_overflow
max_value_32 = pow(2, 32)
print("\nDays it will take for a 32-bit system to timeout: " + str(
max_value_32 / seconds_in_milliseconds / seconds_in_a_day))
# 6. How many days does it take for a 64-bit system to timeout, if it has a bug with integer overflow?
# The Binary Register Width of a processor determines the range of values that can be represented.
# The maximum representable value for a 32-bit system will be 2^64-1
# When an arithmetic operation (in this case the increment of a millisecond in the time)
# produces a result larger than the above we will have an `integer overflow`
# To calculate the days it will take to reach that situation for a 64-bit system
# we need to convert 2^64 milliseconds in days by dividing by 1000s then 60s then 60m 24h
# source https://en.wikipedia.org/wiki/Integer_overflow
max_value_64 = pow(2, 64)
print("\nDays it will take for a 64-bit system to timeout: " + str(
max_value_64 / seconds_in_milliseconds / seconds_in_a_day))
# 7. Calculate your age accurately based on your birthday
# https://docs.python.org/3/library/datetime.html#datetime.timedelta.total_seconds
# https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting
# example showing %s string variable
delta = datetime.now() - datetime(1986, 12, 8, 18, 45)
print("\nMy age is %d seconds" % delta.total_seconds())
# or
# print("\nMy age is {} seconds".format(delta.total_seconds()))
# 8. Full name greeting. Write a program that asks for a person's first name, then middle, and then last.
# Finally, it should greet the person using their full name.
name = input("\nCould you please type your first name: ")
middle_name = input("Could you please type your middle name: ")
last_name = input("Could you please type your last name: ")
print("\nHello %s %s %s! A really warm welcome to you!" % (name, middle_name, last_name))
# 9. Bigger, better favorite number. Write a program that asks for a person's favorite number.
# Have your program add 1 to the number, and then suggest the result as a bigger and better favorite number.
print("\nEXERCISE Bigger, better favorite number")
# infinite loop
while True:
# try to convert the input in an integer
try:
favorite_number = int(input("\n" + name + " could you please type your favourite number? "))
# if it is not possible acknowledge the user and continue to prompt him to insert a number
except ValueError:
print("That wasn't a number!")
continue
# else execute the input manipulation and break the infinite loop
else:
big_favorite_number = str(favorite_number + 1)
print("I have for you a bigger and better favourite number. What about a nice %s." % big_favorite_number)
break
# 10. Angry boss. Write an angry boss program that rudely asks what you want.
# Whatever you answer, the angry boss should yell it back to you and then fire you.
print("\nEXERCISE Angry boss")
answer = input("\n" + name + " what the hell do you want? ")
print(("whaddaya mean \"" + answer + "\"?!? you're fired!!").upper())
# 11. Table of contents. Here's something for you to do in order to play around more with center, ljust, and rjust:
# write a program that will display a table of contents so that it looks like this:
# Table of Contents
#
# Chapter 1: Getting Started page 1
# Chapter 2: Numbers page 9
# Chapter 3: Letters page 13
print("\nEXERCISE Table of contents")
rows = [
["\nTable of Contents", "\n"],
["Chapter 1: Getting Started", "page 1"],
["Chapter 2: Numbers", "page 9"],
["Chapter 3: Letters", "page 13"]
]
# get the length of the longest world from each row in rows and for each word in row + some padding
col_width = max(len(r[0]) for r in rows) + 10 # padding
# for every row in rows
for r in rows:
# print the first word of the row leaving empty spaces to fill up the column width and then print the second element
print(r[0].ljust(col_width) + r[1])
# 12. Write a program that prints out the lyrics to that beloved classic, "99 Bottles of Beer on the Wall."
# source http://www.99-bottles-of-beer.net/lyrics.html
print("\nEXERCISE \"99 Bottles of Beer on the Wall.\"")
BEER_TOTAL = 99
# print the lyrics title
print("\n", (" Lyrics of the song %s Bottles of Beer " % BEER_TOTAL).center(50, "🍺"), "\n")
for i in range(BEER_TOTAL, 0, -1):
# print the lyrics in the loop from 99 to 0
print("\n", i, "bottles of beer on the wall,", i, "bottles of beer."
"\nTake one down and pass it around,", i - 1, "bottles of beer on the wall.\n")
# print the end of the lyrics
print("No more bottles of beer on the wall, no more bottles of beer."
"\nGo to the store and buy some more,", BEER_TOTAL, "bottles of beer on the wall.")
# 13. Deaf grandma.
# Whatever you say to Grandma (whatever you type in), she should respond with this: HUH?! SPEAK UP, GIRL!
# unless you shout it (type in all capitals). If you shout, she can hear you (or at least she thinks so) and yells back:
# NO, NOT SINCE 1938!
# To make your program really believable, have Grandma shout a different year each time,
# maybe any year at random between 1930 and 1950.
# You can't stop talking to Grandma until you shout BYE.
print("\nEXERCISE Deaf grandma")
tell_grandma = ""
while tell_grandma != "BYE":
tell_grandma = input("Tell something to Grandma: ")
# if tell_grandma.isupper() and not tell_grandma.islower(): => this would be semantically more correct however
# I think that the above method will scan the string tell_grandma twice whilst the one below only once
if tell_grandma == tell_grandma.upper():
random_year = randint(1930, 1950)
print("NO, NOT SINCE %s" % random_year)
else:
print("HUH?! SPEAK UP, GIRL!")
# 14. Deaf grandma extended. What if Grandma doesn't want you to leave?
# When you shout BYE, she could pretend not to hear you.
# Change your previous program so that you have to shout BYE three times in a row.
# Make sure to test your program: if you shout BYE three times but not in a row, you should still be talking to Grandma.
print("\nEXERCISE Deaf grandma extended")
tell_grandma_extended = ""
num_bye = 0
while num_bye < 3:
tell_grandma_extended = input("Tell something to Grandma: ")
# if tell_grandma.isupper() and not tell_grandma.islower(): => this would be semantically more correct however
# I think that the above method will scan the string tell_grandma twice whilst the one below only once
if tell_grandma_extended == tell_grandma_extended.upper():
if tell_grandma_extended == "BYE":
num_bye = num_bye + 1
else:
num_bye = 0
random_year = randint(1930, 1950)
print("NO, NOT SINCE %s" % random_year)
else:
num_bye = 0
print("HUH?! SPEAK UP, GIRL!")
if num_bye == 3:
print("GOODBYE HONEY!!! SEE YOU SOON! I LOVE YOU!")
# 15. Leap years.
# Write a program that asks for a starting year and an ending year and
# then puts all the leap years between them (and including them,
# if they are also leap years). Leap years are years divisible by 4 (like 1984 and 2004).
# However, years divisible by 100 are not leap years (such as 1800 and 1900)
# unless they are also divisible by 400 (such as 1600 and 2000, which were in fact leap years). What a mess!
print("\nEXERCISE Leap years ")
print("\nLet's find leap years. Type a range of two years to find all the leap years in the range.")
loop_years = []
# infinite loop
while True:
# try to convert the input in an integer
try:
year_one = int(input("\nPlease type the starting year: "))
year_two = int(input("\nPlease type the ending year: "))
# check that year one is minor of year two
if year_one >= year_two:
raise ValueError("\nThe starting year must be greater than the ending year!")
# if it is not possible acknowledge the user and continue to prompt her to insert a number
except ValueError as error:
if error:
print(error)
else:
print("\nThat wasn't a valid year!")
continue
# else execute the input manipulation and break the infinite loop
else:
current_year = year_one
while current_year <= year_two:
if current_year % 400 == 0 or (current_year % 4 == 0 and current_year % 100 != 0):
loop_years.append(current_year)
current_year += 1
for y in loop_years:
print(y)
break
# 16. Find something today in your life, that is a calculation.
# I had a JavaScript interview today and the question was to perform a left rotation operation on an array.
# For example, if left rotations are performed on array, then the array would become .
# For example, if 2 left rotations are performed on an array [1, 2, 3, 4, 5],
# then the array would become [3, 4, 5, 1, 2].
# Here is my algorithm:
print("\nEXERCISE FROM YOUR LIFE")
def rotate_left(array, rotations_num):
return array[rotations_num:] + array[:rotations_num]
# O(n) complexity alternative
# def rotate_left(array, rotations_num):
# a_length = len(array)
# new_array = [None]*a_length
# pos_to_left = rotations_num
#
# i = 0
# while i < a_length:
# pos_to_left = pos_to_left if pos_to_left != 0 else a_length
# to_index = a_length - pos_to_left
# new_array[to_index] = array[i]f
# pos_to_left -= 1
# i += 1
#
# return new_array
# O(n) complexity alternative suggested by mentor
# The method above is the mere translation from JS to Python.
# In Python array[-2] is a valid operation as lists are circular linked list (I presume)
# In JS array[-2] is not possible so you have to reset the index
# In Python therefore the function would be the below
# def rotate_left(array, rotations_num):
# a_length = len(array)
# new_array = [None] * a_length
# for i in range(a_length):
# print(i - rotations_num)
# new_array[i-rotations_num] = array[i]
# return new_array
print("\nRotate the following array [1, 2, 3, 4, 5] of 2 position to the left")
print(rotate_left([1, 2, 3, 4, 5], 2))
print("\nRotate the following array [1, 2, 3, 4, 5] of 4 position to the left")
print(rotate_left([1, 2, 3, 4, 5], 4))
print("\nRotate the following array [1, 2, 3, 4, 5] of 5 position to the left")
print(rotate_left([1, 2, 3, 4, 5], 5))
print("\nRotate the following array [1, 2, 3, 4, 5] of 6 position to the left")
print(rotate_left([1, 2, 3, 4, 5], 6))
# 17. Building and sorting an array. Write the program that asks us to type as many words as we want
# (one word per line, continuing until we just press Enter on an empty line)
# and then repeats the words back to us in alphabetical order. Make sure to test your program thoroughly; for example,
# does hitting Enter on an empty line always exit your program? Even on the first line? And the second?
# Hint: There’s a lovely array method that will give you a sorted version of an array: sorted(). Use it!
print("\nEXERCISE Building and sorting an array")
word_list = []
user_word = input("\nPlease type as many words as you want one word per line, "
"continuing until you press Enter on an empty line "
"and I will repeat them to you in alphabetical order: ")
while user_word != '':
word_list.append(user_word)
user_word = input()
print(sorted(word_list))
# 18. Table of contents. Write a table of contents program here.
# Start the program with a list holding all of the information for your table of contents
# (chapter names, page numbers, and so on).
# Then print out the information from the list in a beautifully formatted table of contents.
# Use string formatting such as left align, right align, center.
print("\nEXERCISE Table of contents with function and info array")
def print_contents(contents_list):
# get the length of the longest world from each row in rows and for each word in row + some padding
col_width = max(len(r[1]) for r in contents_list) + 10 # padding
print("\nTable of Contents\n")
for c in contents_list:
print("Chapter " + c[0] + ": " + c[1].ljust(col_width) + "page " + c[2])
contents_table = [
["1", "Getting Started", "1"],
["2", "Numbers", "9"],
["3", "Letters", "13"],
]
print_contents(contents_table)
# 19. Write a function that prints out "moo" n times.
def get_input_number(callback, msg):
# try to convert the input in an integer
try:
user_number = int(input(msg))
# if it is not possible acknowledge the user and continue to prompt him to insert a number
except ValueError:
print("\nThat wasn't a valid number!")
return get_input_number(callback, msg)
# else execute the input manipulation and break the infinite loop
else:
return callback(user_number)
print("\nEXERCISE moo")
def moo(number):
print("\nmoo" * number)
get_input_number(moo, "\nPlease type how many times you want to 'moo': ")
# 20. Old-school Roman numerals. In the early days of Roman numerals,
# the Romans didn't bother with any of this new-fangled subtraction “IX” nonsense.
# No Mylady, it was straight addition, biggest to littlest—so 9 was written “VIIII,” and so on.
# Write a method that when passed an integer between 1 and 3000 (or so) returns a string containing
# the proper old-school Roman numeral. In other words, old_roman_numeral 4 should return 'IIII'.
# Make sure to test your method on a bunch of different numbers.
#
# Hint: Use the integer division and modulus methods.
#
# For reference, these are the values of the letters used:
# I = 1
# V = 5
# X = 10
# L = 50
# C = 100
# D = 500
# M = 1000
print("\nEXERCISE Old-school Roman numerals")
def old_romans(number):
result = ''
decimal = [1000, 500, 100, 50, 10, 5, 1]
roman = ["M", "D", "C", "L", "X", "V", "I"]
# looping over every element of our arrays
for i in range(len(decimal)):
# keep trying the same number until we need to move to a smaller one
while number%decimal[i] < number:
# add the matching roman number to our result string
result += roman[i]
# subtract the decimal value of the roman number from our number
number -= decimal[i]
return result
print(get_input_number(old_romans, "\nPlease type a number between 1 and 3000: "))
# 21. “Modern” Roman numerals.
# Eventually, someone thought it would be terribly clever if putting a smaller number before a larger one meant you
# had to subtract the smaller one. As a result of this development, you must now suffer.
# Rewrite your previous method to return the new-style Roman numerals so when someone calls roman_numeral 4,
# it should return 'IV', 90 should be 'XC' etc.
print("\nEXERCISE “Modern” Roman numerals.")
def modern_romans(number):
result = ''
decimal = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
roman = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
# looping over every element of our arrays
for i in range(len(decimal)):
# keep trying the same number until we need to move to a smaller one
while number%decimal[i] < number:
# add the matching roman number to our result string
result += roman[i]
# subtract the decimal value of the roman number from our number
number -= decimal[i]
return result
print(get_input_number(modern_romans, "\nPlease type a number between 1 and 3000: "))
|
ae0fe95a834ff25df45e0723c01267dbfb50d638 | thonyeh/Linear-Programming | /simplex.py | 7,559 | 3.890625 | 4 | from math import *
from time import sleep
from numpy import *
from Tkinter import *
print 'A CONTINUACION INGRESE LOS DATOS DEL PROBLEMA A MINIMIZAR.'
print ''
def vuelva():
print 'INGRESE LOS DATOS DE OTRO PROBLEMA:'
print ''
main()
def main():
A=[]
b=[]
cont=0
m=input('Ingrese el numero de filas de la matriz A:')
n=input('Ingrese el numero de columnas de la matriz A:')
for i in range(m):
A.append([0]*(n))
for i in range(m):
b.append(0)
for i in range(m):
print'Ingrese los %d elementos de la fila %d:'%(n,i+1)
for j in range(n):
A[i][j]=input('')
simb=raw_input('Escriba " <= " o " = " segun le corresponda a esta fila:')
if '<='==simb:
cont+=1
for j in range (m):
A[j].append(0)
A[i][n-1+cont]=1
print'Ingrese el vector b:'
for i in range(m):
b[i]=input('')
print 'Ingrese el vector Costo'
c=[]
c1=[]
for i in range(n+m):
c.append(0)
c1.append(0)
for i in range(n):
c[i]=input('')
print 'El metodo simplex trabaja ahora de la siguiente forma:'
print ''
print 'Matriz A:'
for i in range(m):
print A[i]
print ''
print 'Vector b:'
print b
print ''
print 'Vector Costo:'
print c
print ''
simplex(A,b,m,n,c,c1)
def combi(A,m,n):
B=[]
for i in range(m):
B.append([0]*(m))
piv=[]
for i in range(m):
piv.append(0)
todcom = []
aux = [i for i in range(m)]
cond = [k for k in range(n-m,n)]
todcom = todcom + [guar(aux)]
while todcom[-1]!=cond:
if aux[-1]!=n-1:
aux[-1] = aux[-1] + 1
todcom = todcom +[guar(aux)]
bolean,index = verif(todcom[-1],cond)
if index == 0:
break
elif bolean == False and index!=0:
aux = decen(todcom[-1],index)
todcom = todcom + [guar(aux)]
for i in range(len(todcom)):
for j in range (m):
piv[j]=todcom[i][j]
for l in range (m):
B[l][j]=A[l][todcom[i][j]]
if linalg.det(B)!=0:
break
return B,piv
def guar(aux1):
temp = []
for t in range(len(aux1)):
temp.append(aux1[t])
return temp
def verif(arra,cond):
m = len(arra)
bolean = True
k = -1
for i in range(m):
if arra[i]==cond[i]:
k = i
bolean = False
break
return bolean,k
def decen(arra,k):
m = len(arra)
temp = []
for i in range(m):
if i == k-1:
temp = temp+[arra[i] + 1]
elif i > k-1:
temp = temp+[temp[i-1] + 1]
else:
temp = temp + [arra[i]]
return temp
def simplex(A,b,m,n,c,c1):
piv=[]
for i in range(m):
piv.append(0)
B,piv=combi(A,m,n)
print 'matriz B (inicial) tomada:'
for i in range (m):
print B[i]
print ''
no_acotado=1
optimo=1
u=[]
cB=[]
piv2=[]
b1=[]
a1_h=[]
for i in range(m):
u.append(0)
cB.append(0)
piv2.append(0)
b1.append(0)
a1_h.append(0)
for i in range(m):
cB[i]=c[piv[i]]
while (optimo ==1) and (no_acotado==1):
Bi=[]
Bi=linalg.inv(B)
B2=[]
C=[]
for i in range(n+m):
C.append(0)
for i in range(m):
B2.append([0]*(m))
for i in range(m):
for j in range(m):
B2[i][j]= '%.2f'%Bi[i][j]
print 'B^(-1), inversa de B:'
for i in range(m):
print B2[i]
print ''
print 'cB:',cB
print ''
for i in range(m):
suma=0
for j in range(m):
suma=suma+cB[j]*Bi[j][i]
u[i]=suma
for i in range(n+m):
suma=0
for j in range(m):
suma=suma+u[j]*A[j][i]
c1[i]=suma
for i in range(m+n):
c1[i]= c[i]-c1[i]
if c1[i] < 10**(-14) and c1[i] > -10**(-14):
c1[i]=0
p=0
for i in range(n+m):
C[i]='%.2f'%c1[i]
print 'vector de "Costos Reducidos":'
print C
print ''
for j in range(n+m):
if c1[j]<0:
break
else: p=j
if p==(n+m-1):
optimo = 0
print 'Todos los elementos del Costo Reducido no son negativos, entonces:'
print 'LA SOLUCION ES OPTIMA'
print ''
else:
print 'Existe al menos un elemento del Costo Reducido menor que cero, entonces:'
print 'LA SOLUCION AUN NO ES OPTIMA'
print ''
for h in range(n+m):
if c1[h]<0:
break
print 'Columna entrante "h" de la matriz A a la matriz B:',h+1
print ''
for i in range(m):
suma=0
for j in range(m):
suma=suma+Bi[i][j]*b[j]
b1[i]=suma
b2=[]
for i in range (m):
b2.append(0)
b2[i]='%.2f'%b1[i]
print 'Calculando b1=(B^(-1))*b:'
print b2
print ''
for i in range(m):
suma=0
for j in range(m):
suma=suma+Bi[i][j]*A[j][h]
a1_h[i]=suma
b2=[]
for i in range (m):
b2.append(0)
b2[i]='%.2f'%a1_h[i]
print 'Calculando(B^(-1))*a_(%d), siendo a_(%d) la columna %d de a'%(h+1,h+1,h+1)
print b2
print ''
p=0
for i in range(m):
if a1_h[i]>0:
break
else: p=i
if p==(m-1):
print 'Todos los elementos del resultado anterior no son positivos, entonces:'
print 'LA SOLUCION NO ESTA ACOTADA'
print ''
no_acotado=0
else:
for i in range(m):
if a1_h[i]>0:
minimo= b1[i]*(a1_h[i]**(-1))
r=i
break
for j in range(i+1,m):
if a1_h[j]>0:
if (b1[j]*(a1_h[j]**(-1))) < minimo:
minimo = b1[j]*(a1_h[j]**(-1))
r=j
print 'Columna saliente "r" de la matriz B:',r+1
print ''
for i in range(m):
B[i][r]=A[i][h]
print 'Haciendo el cambio de la columna %d de B con la columna %d de A'%(r+1,h+1)
print 'Matriz B mejorada:'
for i in range(m):
print B[i]
print ''
cB[r]=c[h]
piv[r]=h
for i in range(m):
piv2[i]=piv[i]+1
if optimo ==0:
for i in range(m):
suma=0
for j in range(m):
suma=suma+Bi[i][j]*b[j]
b1[i]=suma
x=[]
for i in range(m+n):
x.append(0)
for i in range(m):
x[piv[i]]='%.3f'%b1[i]
print 'Solucion:'
print x[0:n]
print ''
conf=raw_input ('Diga SI o NO si desea continuar con mas problemas:')
if 'SI' == conf:
vuelva()
else:
print 'LA TAREA HA FINALIZADO'
main()
|
05babe231f74b03b73717dfebeb7b4146f7b42ce | 5hogun-Ormerod/Network-rewiring-methods | /Final_versions.py | 3,436 | 3.90625 | 4 | import networkx as nx
import random
def Random_Path(G, length, path = []):
"""
Given a graph, G, this function returns a random path of a given number
of edges (length =n). This path is represented by a list of nodes of G
[v0,v1,..., vn] such that (vi,vi+1) is an edge.
This is done recursively by appending a random neighbor of the last
node in the path then appending a path of length n-1.
"""
if path == []:
rand_node = random.choice(nx.nodes(G))
path.append(rand_node)
print(rand_node)
if length == 1:
prev_node = list(path)[-1]
connected = list(set(nx.all_neighbors(G,prev_node)).difference(set(path)))
if len(connected) > 0:
random_new_node = random.choice(connected)
path.append(random_new_node)
return path
else:
return path
else:
prev_node = list(path)[-1]
connected = list(set(nx.all_neighbors(G,prev_node)).difference(set(path)))
if len(connected) > 0:
random_new_node = random.choice(connected)
path.append(random_new_node)
return Random_Path(G, length-1, path)
else:
return path
def rewire_scale_free(G,rewire_iter,max_iter = 10000000):
"""
We create a scale free graph by choosing a random node, x, and a
random path [xij] and rewiring [xi] to [xj] sufficiently many times.
"""
G_new = nx.Graph(G)
count_iter = 0
count_rewire = 0
while (count_iter < max_iter) & (count_rewire < rewire_iter):
count_iter = count_iter + 1
rand_node = random.choice(G_new.nodes())
path = Random_Path(G_new, 2 ,[rand_node])
if len(path) == 3:
if path[2] in nx.non_neighbors(G_new,path[0]):
G_new.remove_edge(path[0],path[1])
G_new.add_edge(path[0],path[2])
count_rewire = count_rewire +1
return G_new
def rewire_cluster_binomial(G,rewire_iter,max_iter = 10000000):
G_new = nx.Graph(G)
count_iter = 0
count_rewire = 0
while (count_iter < max_iter) & (count_rewire < rewire_iter):
count_iter = count_iter + 1
rand_node = random.choice(G_new.nodes())
if len(list(nx.all_neighbors(G_new,rand_node))) >= 2:
path = Random_Path(G_new, 3,[rand_node])
if len(path)== 4:
if path[0] in nx.non_neighbors(G_new,path[2]):
G_new.remove_edge(path[2],path[3])
G_new.add_edge(path[0],path[2])
count_rewire = count_rewire +1
return G_new
def rewire_cluster_scale_free(G,rewire_iter,max_iter = 10000000):
G_new = nx.Graph(G)
count_iter = 0
count_rewire = 0
while (count_iter < max_iter) & (count_rewire < rewire_iter):
count_iter = count_iter + 1
rand_node = random.choice(G_new.nodes())
if len(list(nx.all_neighbors(G_new,rand_node))) >= 2:
path = Random_Path(G_new, 2,Random_Path(G_new,2,[rand_node])[::-1])
if len(path)== 5:
if path[2] in nx.non_neighbors(G_new,path[4]):
G_new.remove_edge(path[1],path[2])
G_new.add_edge(path[2],path[4])
count_rewire = count_rewire +1
return G_new
|
56ef840dad7baebf3ef0f8de973dd968a43215b4 | jhilmilrsingh/Read-Tweet-Data | /Lab10_Singh_Jhilmil.py | 1,126 | 3.703125 | 4 | import json
filename = "tweet_data.txt"
file_handle = open(filename)
outer_dictionary = json.load(file_handle)
tweet_list = outer_dictionary.get("tweet_list")
for tweet in tweet_list:
print("Tweet:", tweet.get("text"))
print("Tweeted at:", tweet.get("created_at"))
print("Tweet ID:", tweet.get("id"))
print("Language:", tweet.get("lang"))
user_dictionary = tweet.get("user")
print("Tweeted by:", user_dictionary.get("name"), end=" ")
if user_dictionary["verified"] == False:
print("(Not Verified)")
else:
print("(Verified)")
print("Location:", user_dictionary.get("location"))
print("Who has", user_dictionary.get("followers_count"), "followers")
retweet = tweet.get("retweeted_status")
if retweet == None:
print("This was an original tweet")
else:
print("This was retweeted", retweet.get("retweet_count"), "times.")
retweet_user_dictionary = retweet.get("user")
print ("The original tweet was", retweet.get("id"), "from", retweet_user_dictionary.get("name"))
print ("")
file_handle.close()
|
f9c8aecfc58fdde84467bb10a3d6147ff012caa8 | ranjanrajiv00/python-algo | /string/longest-sub-sequence.py | 355 | 3.890625 | 4 | def longestSubseqWithK(str, k):
n = len(str)
freq = {}
for i in range(n):
if str[i] not in freq:
freq[str[i]] = 1
else:
freq[str[i]] += 1
for i in range(n):
if (freq[str[i]] >= k):
print(str[i], end="")
print("")
str = "geekswaforgeekswas"
k = 2
longestSubseqWithK(str, k)
|
77a544ec2f00a909d606d7059b7ce0be816c2e7f | ranjanrajiv00/python-algo | /basic/reverse-numbers.py | 172 | 4 | 4 | def reverse(num):
result = 0
while num > 0:
rem = num % 10
result = result * 10 + rem
num = num // 10
return result
print(reverse(123)) |
2798bba307a78bdeb063d36ab752e3ee6b60d791 | NuApt/HandGestRecog_CNN | /Training.py | 2,512 | 3.828125 | 4 | # Importing the Keras libraries and packages
from keras.models import Sequential
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
# Step 1 - Building the CNN
# Initializing the CNN
classifier = Sequential()
# First convolution layer and pooling
classifier.add(Convolution2D(32, (3, 3), input_shape=(64, 64, 1), activation='relu'))
classifier.add(MaxPooling2D(pool_size=(2, 2)))
# Second convolution layer and pooling
classifier.add(Convolution2D(32, (3, 3), activation='relu'))
# input_shape is going to be the pooled feature maps from the previous convolution layer
classifier.add(MaxPooling2D(pool_size=(2, 2)))
# Flattening the layers
classifier.add(Flatten())
# Adding a fully connected layer
classifier.add(Dense(units=128, activation='relu'))
classifier.add(Dense(units=8, activation='softmax')) # softmax for more than 2
# Compiling the CNN
classifier.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) # categorical_crossentropy for more than 2
# Step 2 - Preparing the train/test data and training the model
# Code copied from - https://keras.io/preprocessing/image/
from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1./255)
training_set = train_datagen.flow_from_directory('data/Train',
target_size=(64, 64),
batch_size=5,
color_mode='grayscale',
class_mode='categorical')
test_set = test_datagen.flow_from_directory('data/Test',
target_size=(64, 64),
batch_size=5,
color_mode='grayscale',
class_mode='categorical')
classifier.fit_generator(
training_set,
steps_per_epoch=560, # No of images in training set
epochs=10,
validation_data=test_set,
validation_steps=240)# No of images in test set
# Saving the model
model_json = classifier.to_json()
with open("model-bw.json", "w") as json_file:
json_file.write(model_json)
classifier.save_weights('model-bw.h5')
|
1280c62c354e095dea386fd7f76a37bca5ca4f9b | A-G-U-P-T-A/Penetration-Testing-Tutorial-Series | /python/server.py | 614 | 3.859375 | 4 | #import socket library
import socket
#creating a socket object using socket() function.
s = socket.socket()
#creating a port on which the server will listen at.
p = 4444
#calling bind() function to bind ip address with port number (important step)
s.bind(('', p))
#starting the socket listener mode...
s.listen(5)
#the 5 mentioned here means the server can accept max 5 connections.
while True:
c, addr = s.accept() #accepting incoming connection
c.send('Connected to server !!!') #sending data to a connected client.
c.close() #closes the connection with the client.
#lets check whether its working or not....
|
51b2b221c87ad60208a0193f8efa2a15015096a7 | saurav2401/30-Day-LeetCoding-Challenge | /week4/day_27.py | 1,032 | 3.546875 | 4 | '''
Problem Statement:
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.
Example:
Input:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Output: 4
'''
# Solution:
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
if matrix == []:
return 0
len_r, len_c = len(matrix), len(matrix[0])
if len_r == 0 or len_c == 0:
return 0
dp = [[0 for i in range(len_c + 1)] for j in range(len_r + 1)]
max_dim = 0
# Filling up the dp table
for i in range(len_r):
for j in range(len_c):
if matrix[i][j] == '1':
dp[i+1][j+1] = min(dp[i+1][j], dp[i][j],dp[i][j+1]) + 1
# Finding the max dimension of the square so far
max_dim = max(max_dim, dp[i+1][j+1])
else:
dp[i+1][j+1] = 0
return max_dim*max_dim
|
cedafe0094c583651e50ea830a601dee344b77c2 | masterdorron/Bones | /Bones_new.py | 968 | 3.5625 | 4 | from tkinter import *
class Application(Frame):
def say_hi(self):
self.label["text"] = "hi there, everyone!"
def createWidgets(self):
self.f1 = Frame(self)
self.f1.pack()
self.QUIT = Button(self.f1)
self.QUIT["text"] = "QUIT"
self.QUIT["fg"] = "red"
self.QUIT["command"] = self.quit
self.QUIT.pack({"side": "left"})
self.hi_there = Button(self.f1)
self.hi_there["text"] = "Hello",
self.hi_there["command"] = self.say_hi
self.hi_there.pack({"side": "left"})
self.label = Label(self, text='Place for hello')
self.label.pack()
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
self.createWidgets()
root = Tk()
app = Application(master=root)
app.mainloop()
root.destroy()
tex = Text(root,width=40,
font="Verdana 12",
wrap=WORD) |
039775384439590ad1dc80790deb36d5a4558b6a | oxavelar/NumVis | /numvis.py | 6,685 | 3.765625 | 4 | #!/usr/bin/env python
"""
Author: Omar Avelar
DESCRIPTION
===========
Simple class extension of number to add hex and binary chunk representations
that allow for faster debugging and data analysis, tested in Python 2.6.
EXAMPLE
=======
>>> from numvis import NumVis
>>> # Can be regular integer, long, hex number or binary number
>>> number = NumVis(0xf5fa)
>>> number
0xf5faL
>>> number.hex()
(9B per line):
00 00000000 00000000 [0575:0504]
00 00000000 00000000 [0503:0432]
00 00000000 00000000 [0431:0360]
00 00000000 00000000 [0359:0288]
00 00000000 00000000 [0287:0216]
00 00000000 00000000 [0215:0144]
00 00000000 00000000 [0143:0072]
00 00000000 0000F5FA [0071:0000]
>>> number.bin()
(16b per line)
0000 0000 0000 0000 [0127:0112]
0000 0000 0000 0000 [0111:0096]
0000 0000 0000 0000 [0095:0080]
0000 0000 0000 0000 [0079:0064]
0000 0000 0000 0000 [0063:0048]
0000 0000 0000 0000 [0047:0032]
0000 0000 0000 0000 [0031:0016]
1111 0101 1111 1010 [0015:0000]
Both "bin()" and "hex()" methods provide more flexible ways of organizing the
data to print, for example:
>>> number.hex(line_width=128, full_size = 256, hgroup=2, vgroup=2)
(16B per line):
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 [0255:0128]
00 00 00 00 00 00 00 00 00 00 00 00 00 00 F5 FA [0127:0000]
>>> number.hex(line_width=128, full_size = 1024, hgroup=2, vgroup=4)
(16B per line):
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 [1023:0896]
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 [0895:0768]
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 [0767:0640]
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 [0639:0512]
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 [0511:0384]
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 [0383:0256]
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 [0255:0128]
00 00 00 00 00 00 00 00 00 00 00 00 00 00 F5 FA [0127:0000]
"""
import __builtin__
class NumVis(long):
def hex(self, line_width=72, full_size=576, hgroup=8, vgroup=8):
"""
Organizes numeric data hex chunks for data visualization.
Notes: "line_width" and "full_size" are in bit sizes.
hgroup and vgroup are symbol sizes.
"""
# If data is bigger than size, override manually to fit.
while (self.numerator >> full_size): full_size = full_size + line_width
if line_width % full_size != line_width:
raise(ValueError, 'The choosen "line_width" parameter is not evenly divisible by the specified size')
print(' (%dB per line):' % (line_width / 8))
str_cl_hex = eval("'%%0%dX' %% self.numerator" % (full_size / 4))
# Separates size in chunks of width bits.
tmp = self._reversesplit(str_cl_hex, line_width / 4)
c = full_size / line_width
for chunk in tmp:
# Splits according to horizontal group, left to right.
chunk = ' '.join(self._reversesplit(chunk, hgroup))
print(' %-65s [%04d:%04d]' % (chunk, c * line_width - 1, c * line_width - line_width))
if ((c-1) % vgroup == 0): print('')
c -= 1
def bin(self, line_width=16, full_size=128, hgroup=4, vgroup=8):
"""
Organizes numeric data in chunks of binary for data visualization.
Notes: "line_width" and "full_size" are in bit sizes.
"hgroup" and "vgroup" are symbol sizes.
Default "hgroup" is 4 to see them as nibbles.
"""
# If data is bigger than size, override manually to fit.
while (self.numerator >> full_size): full_size = full_size + line_width
if line_width % full_size != line_width:
raise(ValueError, 'The choosen "line_width" parameter is not evenly divisible by the specified size')
str_cl_bin = self._rawbin(self.numerator, padding=full_size)
# Separates size in chunks of width bits.
print(' (%db per line)' % line_width)
tmp = self._reversesplit(str_cl_bin, line_width)
c = full_size / line_width
for chunk in tmp:
# Splits according to horizontal group, left to right.
chunk = ' '.join(self._reversesplit(chunk, hgroup))
print(' %-65s [%04d:%04d]' % (chunk, c * line_width - 1, c * line_width - line_width))
if ((c-1) % vgroup == 0): print('')
c -= 1
def _reversesplit(self, binstring, size):
"""
Will split the binary string in chunks of desire size. Starts
from the LSB as desired.
"""
results = list()
l = list(binstring)
l.reverse()
for i in xrange(0, len(l), size):
tmp = l[i:i+size]
tmp.reverse()
results.append(tmp)
results.reverse()
# Concatenates and places a separator.
tmp = list()
for e in results:
tmp.append(''.join( [str(x) for x in e]))
return tmp
def _rawbin(self, number, padding=0):
"""
Returns the string representation in binary of the number with left padding.
"""
tmp = bin(number)[2:]
# Padding happens here...
if padding < len(tmp):
return tmp
else:
num_zeros = padding - len(tmp)
return (num_zeros * '0') + tmp
|
7e77dda0e8c28818dbc42abd6ac958a3268df12e | davide-chiuchiu/Analysis_of_job_opening_rejections | /python_code/text_utilities.py | 4,769 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 1 13:16:18 2020
@author: dabol99
This files contains functions that are useful to preprocess strings for nltk
and to build document embeddings.
"""
# import modules
import nltk
import re
import sklearn
import sklearn.cluster
import pandas
"""
this function uses nltk features to returns the word frequencies from the corpus
stored as a series of documents in corpus_as_series
"""
def compute_word_frequencies(corpus_as_series):
corpus_condensed_as_string = corpus_as_series.str.cat(sep = ' ')
tokenized_corpus = nltk.tokenize.word_tokenize(corpus_condensed_as_string)
word_frequencies = nltk.probability.FreqDist(tokenized_corpus)
return word_frequencies
"""
This function tokenizes and stems the input string text while it removes all
stopwords and punctuation symbols.
"""
def preprocess_corpus(text, extra_tokens_to_remove = None, remove_numbers = True):
# remove numbers from text
if remove_numbers == True:
text = re.sub('[0-9]', '', text)
# remove all special symbols from text
text = re.sub(r"[^A-Za-z0-9]+", " ", text)
# create stopwords to remove based on english stopwords, and extra_tokens_to_remove
if extra_tokens_to_remove == None:
stopset = nltk.corpus.stopwords.words('english')
else:
stopset = nltk.corpus.stopwords.words('english') + extra_tokens_to_remove
# tokenize text (replacement of . into )
tokenized_text = nltk.tokenize.word_tokenize(text.lower())
# remove stopwords from tokenized text
stemmer = nltk.stem.lancaster.LancasterStemmer()
tokenized_text_without_stopwords = " ".join([stemmer.stem(word) for word in tokenized_text if not word in stopset])
return tokenized_text_without_stopwords
"""
This wrapper builds the tfidf_embedded_corpus matrix with the corresponding
embedding_labels and embedder object from the collection of strings stored
at column_label in dataframe. The function preprocess the collection of
strings by removing stopwords, punctuation and extra_tokens_to_remove
"""
def build_tfidf_embedding_from_dataframe(dataframe, column_label, extra_tokens_to_remove = None, ngram_range = (1,1), remove_numbers = True):
# create corpus by removing removing stopwords, punctuation symbols and extra_tokens_to_remove
corpus = dataframe.apply(lambda x: preprocess_corpus(x[column_label], extra_tokens_to_remove, remove_numbers = remove_numbers) , axis = 1).tolist()
# build tfidf vectorizer object from function
tfidf_vectorizer = build_tfidf_embedding_from_corpus(corpus, ngram_range = ngram_range)
# extract tfidf embedding as sparse matrix, and extract embedding labels
tfidf_embedded_corpus = tfidf_vectorizer.transform(corpus)
embedding_labels = tfidf_vectorizer.get_feature_names()
return tfidf_embedded_corpus, embedding_labels, tfidf_vectorizer
"""
This function performs the tfidf embedding of a corpus using ngrams in ngram_range
and then it returns the tfidf embedder object.
"""
def build_tfidf_embedding_from_corpus(corpus, ngram_range = (1,1)):
# embed corpus as tfidf matrix
tfidf_vectorizer = sklearn.feature_extraction.text.TfidfVectorizer(ngram_range = ngram_range)
tfidf_vectorizer.fit(corpus)
return tfidf_vectorizer
"""
This function uses the tfidf embedding of corpus to compute an automated
list of buzzwords in the corpus. By definition, a word classify as buzzword if
its ifd is in the buzzword_quantile_treshold quantile.
"""
def identify_custom_buzzwords(corpus, buzzword_quantile_treshold):
# build tfidf embedding of corpus
tfidf_corpus_embedding = build_tfidf_embedding_from_corpus(corpus, ngram_range = (1,1))
# store tfidf vocabulary as dataframe with the corresponding idf
tfidf_corpus_embedding_dataframe = pandas.DataFrame.from_dict(tfidf_corpus_embedding.vocabulary_, orient = 'index', columns = ['word index']).sort_values('word index')
tfidf_corpus_embedding_dataframe['idf'] = tfidf_corpus_embedding.idf_
# identify buzzwords as the ones in the buzzword_quantile_treshold quantile
buzzword_idf_cutoff = tfidf_corpus_embedding_dataframe['idf'].quantile(buzzword_quantile_treshold)
custom_buzzwords = sorted(tfidf_corpus_embedding_dataframe[tfidf_corpus_embedding_dataframe['idf'].between(0, buzzword_idf_cutoff)].index)
# list of next possible buzzwords
other_buzzword_idf_cutoff = tfidf_corpus_embedding_dataframe['idf'].quantile(2 * buzzword_quantile_treshold)
other_custom_buzzwords = sorted(tfidf_corpus_embedding_dataframe[tfidf_corpus_embedding_dataframe['idf'].between(0, other_buzzword_idf_cutoff)].index)
return custom_buzzwords, other_custom_buzzwords |
36ba5f3b29402750e9d5845e97993959b1dcdde2 | vpalex999/lutc_prog_1 | /Gui/Tour/Grid/grid4.py | 304 | 3.78125 | 4 | """ простая двухмерная таблица, в корневом окне Tk по умолчанию """
from tkinter import *
for i in range(5):
for j in range(4):
lab = Label(text='{}.{}'.format(i, j), relief=RIDGE)
lab.grid(row=i, column=j, sticky=NSEW)
mainloop()
|
b8709b8a2416c8ee6a7ccc04635f9cf04e06bca4 | vpalex999/lutc_prog_1 | /system/Filetools/scanfile.py | 670 | 3.875 | 4 |
def scanner(name, function):
file = open(name, 'r') # создать объект файла
while True:
line = file.readline() # вызов метода файла
if not line: break # до конца файла
function(line) # вызвать объект функции
file.close()
def scanner2(name, function):
for line in open(name, 'r'):
function(line)
def scanner3(name, function):
list(map(function, open(name, 'r')))
def scanner4(name, function):
[function(line) for line in open(name, 'r')]
def scanner5(name, function):
list(function(line) for line in open(name, 'r'))
|
b705cbbec15b78f1774990fd0d3d2fabb6c67ef2 | vpalex999/lutc_prog_1 | /system/streams/teststreams.py | 706 | 3.640625 | 4 | """ читает числа до символа конца файла и выводит их квадраты """
def interact():
print('Hello stream world') # print выводит в sys.stdout
while True:
try:
reply = input('Enter a number>') # input читает из sys.stdin
except EOFError:
break # исключение при всрече символа eof
else: # входные данные в виде строки
num = int(reply)
print(f"{num} squared is {num ** 2}")
print('Bye')
if __name__ == '__main__':
interact() # если выполняется, а не импортируется |
12e1c4cc9e6af3035e4501b2cc7cea6477848d25 | kirar2004/LearnPython | /ML_Learning/SelectSort.py | 413 | 3.5625 | 4 | lis = [100, 48, 96, 63, 23, 73, 23, 37, 22, 98, 22, 37, 51, 40, 74, 14, 65, 15, 77, 5]
print('The raw list is:\n', lis)
l = len(lis)
for i in range(0, l - 1):
#print('i=', i)
for j in range(i + 1, l):
#print('j=', j)
if lis[j] < lis[i]:
temp = lis[j]
lis[j] = lis[i]
lis[i] = temp
else:
continue
print('The sorted list is:\n', lis)
|
c659518d0f15b41da1ab0354b6bd2d0f1cf24446 | che-lor/powerpoint-generator | /create_powerpoint.py | 1,254 | 3.625 | 4 | #!/usr/bin/env python3
from pptx import Presentation
import itertools
###################-FILL-OUT-####################
file1 = "name_of_file"
file2 = "name_of_file"
file3 = "name_of_file"
powerpoint_name = "name_of_powerpoint"
#################################################
_file1 = file1 + ".txt"
_file2 = file2 + ".txt"
_file3 = file3 + ".txt"
_powerpoint_name = powerpoint_name + ".pptx"
slide_master_template = "slide_master.pptx"
save_message = _powerpoint_name + "was created!"
with open(_file1) as f1, open(_file2) as f2, open(_file3) as f3:
file1_lines = f1.read().splitlines()
file2_lines = f2.read().splitlines()
file3_lines = f3.read().splitlines()
lines = list(file1_lines + file2_lines + file3_lines)
f1.close()
f2.close()
f3.close()
#Open presentation using the "slide_master.pptx" file
prs = Presentation(slide_master_template)
#Create a slide for each line
cycle = itertools.cycle(lines)
for eachline in lines:
next_line = next(cycle)
bullet_slide_layout = prs.slide_layouts[1]
slide = prs.slides.add_slide(bullet_slide_layout)
shapes = slide.shapes
body_shape = shapes.placeholders[1]
tf = body_shape.text_frame
tf.text = next_line
#Save file
save = prs.save(_powerpoint_name)
if [ save ]:
print(save_message)
|
9bdde279c0bda1dacb365d6c8a641cd0ece69e1c | SerhiiDior/soft_100_task | /100_tasks/unit_test/problems/44.py | 121 | 4.03125 | 4 | string=str(input("Str->"))
string=string.upper()
if string=="YES":
print ("Yes")
elif string=="NO":
print ("No")
|
1128eb72f0905b4f13fcf973bfe42357b5f48241 | SerhiiDior/soft_100_task | /100_tasks/unit_test/problems/63.py | 173 | 3.703125 | 4 | while True:
n=int(input("n="))
if n>0:
break
else:
n=int(input("n="))
sum=0
for i in range(1,n+1):
sum+=(i/(i+1))
print("Sum=",round(sum,2))
|
d9a1212261fda49af86933b9c8425d130a5bddd7 | SerhiiDior/soft_100_task | /100_tasks/unit_test/problems/54.py | 369 | 3.921875 | 4 | class Shape:
def __init__(self):
pass
def area(self):
return 0
class Square(Shape):
def __init__(self,length=0):
Shape.__init__(self)
self.length=length
def area(self):
return round((self.length*self.length),2)
length=float(input("Length->"))
square=Square(length)
print(square.area())
print(Square().area())
|
49c3d50abdec7e61801914d266f93efedc293fd9 | SerhiiDior/soft_100_task | /100_tasks/unit_test/problems/49.py | 92 | 3.53125 | 4 | def pow(a):
return a**2
lst=[i for i in range(1,21)]
res=list(map(pow,lst))
print(res)
|
8414a894eeba8e9b3969c2df65813cc53a16a097 | SerhiiDior/soft_100_task | /100_tasks/unit_test/test_11_20.py | 1,313 | 3.5 | 4 | import unittest
from probElevenTwenty import *
class SecondClassTest(unittest.TestCase):
def test_four_digit_binary(self):
expected = str(1010)
input_data = four_digit_binary('0100,0011,1010,1001')
self.assertEqual(input_data, expected)
def test_even_1000_3000(self):
self.assertIn(even_1000_3000()[0], [1000])
self.assertIn(even_1000_3000()[-1], [3000])
self.assertIn(even_1000_3000()[10], [1020])
def test_letters_numbers(self):
input_data = letters_numbers('hello world! 123')
self.assertEqual(letters_numbers("hello world! 123"), "LETTERS " + '10' + '\n' + "DIGITS " + '3')
def test_upper_lower(self):
self.assertEqual(upper_lower( "Hello world!" ), "UPPER CASE " + '1' + '\n' + "LOWER CASE " + '9' )
def test_upper_lower_empty(self):
self.assertEqual(upper_lower( "" ), "UPPER CASE " + '0' + '\n' + "LOWER CASE " + '0', 'have not any args' )
def test_compute_value(self):
self.assertEqual(compute_value('9'),11106)
def test_square_odd(self):
self.assertEqual(square_odd([1,2,3,4,5,6,7,8,9]),[1, 3, 5, 7, 9])
def test_sorted_name_age(self):
self.assertEqual(sort_name_age('John,23,90'),[('John', '23', '90')])
if __name__ == '__main__':
unittest.main() |
0727c45ce80e9ae2759c86ae802bacacc05b34d5 | SerhiiDior/soft_100_task | /100_tasks/unit_test/problems/41.py | 92 | 3.703125 | 4 | def tu(n):
tup=tuple(i*i for i in range(1,n+1))
print(tup)
n=int(input("n="))
tu(n)
|
36f184fcc05ec26d049a3372f657f650c0ea788b | SerhiiDior/soft_100_task | /100_tasks/unit_test/problems/91-100.py | 1,314 | 3.5 | 4 | #91
def task_91():
lst=[12,24,35,70,88,120,155]
lst.remove(lst[0])
lst.remove(lst[4])
lst.remove(lst[5])
return lst
#92
def task_92():
lst=[12,24,35,70,88,120,155]
lst.remove(24)
return lst
#93
def task_93():
lst1=[1,3,6,78,35,55]
lst2=[12,24,35,24,88,120,155]
res=[]
for i in lst2:
for j in lst1:
if i==j:
res.append(i)
#94
def task_94():
lst=[12, 24, 35, 24, 88, 120, 155, 88, 120, 155]
res=[]
for x in lst:
if x not in res:
res.append(x)
return res
#95
class Person:
def getGender(self):
print("Person")
class Male(Person):
def getGender(self):
print("Male")
class Female(Person):
def getGender(self):
print("Female")
male = Male()
female = Female()
#96
def task_96(string):
st = set(string)
dict = {i: string.count(i) for i in st}
dict = {key: dict[key] for key in sorted(dict.keys())}
for i in dict.keys():
print(str(i) + "," + str(dict[i]))
#97
def task_97(x):
return x[::-1]
#98
def task_98(x):
return x[::2]
#99
def task_99():
return list(itertools.permutations([1, 2, 3]))
#100
def task_100(head, leg):
return("rabbits " + str(leg // 2 - head) + " chikens " + str(head - (leg // 2 - head)))
|
8d52b36de74353d0950346893a1a8ce3ad0c8ea1 | Kazuoryu/Python | /codigo Inicial/While.py | 100 | 3.859375 | 4 | numero = 1
while (numero < 100):
print ("El valor de numero es:",numero)
numero = numero+1
|
51d3f75a11dc6b4e49a683157171ed0eaf22ea98 | Kazuoryu/Python | /Curso Intermedio/Variable de instancia.py | 514 | 3.875 | 4 | class persona(): #nombre clase
edad=18 #variable de clase
def __init__(self,nombre,nacionalidad): #variables de instancia
self.nombre = nombre #y definicion de la funcion
self.nacionalidad = nacionalidad
def nadar(self):
print("Estoy nadando")
persona1 = persona("Diego","Español") #persona1
print(persona.edad)
print(persona1.nombre)
print(persona1.nacionalidad)
persona1.nadar() #Siempre que se llama a un metodo hay que llamarlo con el objeto y la funcion
|
a4626bd141c432c72b937fb754aa0ac2c3b4bae4 | Kazuoryu/Python | /codigo Inicial/tuplas.py | 262 | 3.921875 | 4 | #Diferencia Array vs Tuplas
#Mientras que los arrays estan limitados por tipo str, int, var, etc
#las tuplas no tienen esa limitacion
tupla=(25,1.81,"Diego")
print (tupla[2])
indice = 0
while indice< len(tupla):
print (tupla[indice])
indice = indice + 1
|
3d8289043074e4a197b417ce77f32d2f9d2967a9 | sobanjawaid26/Python_Playground | /PrimeNumberInRange.py | 528 | 4 | 4 | # Write a program to display PRIME NUMBERS from 1 to n?
def isPrime(number):
for divisor in range(2, number):
if number % divisor == 0:
return False
return True
def primeInRange(number):
list = []
isPrime = True
for number in range(1,number):
for n in range(2,number):
if number % n == 0:
isPrime = False
break
if isPrime == True:
list.append(number)
return list
# print(isPrime(8))
print(primeInRange(54)) |
0f28ba6d84069ffabf1a733ca4f4980c28674290 | ngoc123321/nguyentuanngoc-c4e-gen30 | /session2/baiq.py | 480 | 4.15625 | 4 | weight = float(input('Your weight in kilos: ')) # <=== 79
height = float(input('Your height in meters: ')) # <=== 1.75
BMI = weight / height ** 2
BMI = round(BMI, 1)
if BMI < 16: result = 'Severely underweight.'
elif 16 < BMI <= 18.5: result = 'Underweight.'
elif 18.5 < BMI <= 25: result = 'Normal.'
elif 25 < BMI <= 30: result = 'Overweight.'
else: result = 'obese.'
print('Your BMI is', BMI, end = ', ')
print('that is', result) # ===> Your BMI is 25.8, that is overweight.
|
964f47be5d63f75d8302445f6715a4e9c6832d0b | IrinIv/LearnQA_PythonAPI | /tests/ex10.py | 198 | 3.609375 | 4 | def test_phrase():
phrase = input("Set a phrase: ")
actual_result = (int(len(phrase)))
print(int(len(phrase)))
assert actual_result < 15, "The phrase is greater than 15 characters"
|
6323db65f5ad4d4103801871adbf44f70e9b50c4 | Zakaria-Alsahfi/python-tutorial | /python_tutorial/Tuples.py | 408 | 4.09375 | 4 | # tuples are similar to list but we can not modified it
# Mutable
list_1 = ['History', 'Math', 'Physics', 'CompSci']
list_2 = list_1
print(list_1)
print(list_2)
list_1[0] = 'Art'
print(list_1)
print(list_2)
# Immutable: it can't be change
tuple_1 = ('History', 'Math', 'Physics', 'CompSci')
tuple_2 = tuple_1
print(tuple_1)
print(tuple_2)
# Create an Empty Tuples
empty_tuple = ()
empty_tuple = tuple()
|
3a64a81655e34290ec26910a9a56ba8019771ffa | rayaherrera/1CodesAndOtherStuffs | /crypto.py | 2,309 | 3.859375 | 4 | # Transposition Cipher
# original: this_is_a_secret_message_that_i_want_to_transmit
# encrypted:hsi__ertmsaeta__att_rnmtti_sasce_esg_htiwn_otasi
def scramble2Encrypt(plainText):
evenChars = ""
oddChars = ""
charCount = 0
for ch in plainText:
if charCount % 2 == 0:
evenChars = evenChars + ch
else:
oddChars = oddChars + ch
charCount = charCount + 1
cipherText = oddChars + evenChars
return cipherText
def scramble2Decrypt(cipherText):
halfLength = len(cipherText) // 2
evenChars = cipherText[halfLength:]
oddChars = cipherText[:halfLength]
plainText = ""
for i in range(halfLength):
plainText = plainText + evenChars[i]
plainText = plainText + oddChars[i]
if len(oddChars) < len(evenChars):
plainText = plainText + evenChars[-1]
return plainText
def encryptMessage():
msg = input("Enter the message to encrypt: ")
cipherText = scramble2Encrypt(msg)
# write a stripSpaces (text) function here
def stripSpace(text):
print(text.replace(" ", ""))
# write a caesarEncrypt(plainText, shift)
def caesar2Encrypt(plainText, shift):
plainText = ""
upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lower = "abcdefghijklmnopqrstuvwxyz"
def caesarEncrypt(plainText, shift):
cipherText = ""
for ch in plainText:
if ch in upper:
index = upper.find(ch)
nextIndex = (index + shift) % 26
cipherText += upper[nextIndex]
else:
index = lower.find(ch)
nextIndex = (index + shift) % 26
cipherText += lower[nextIndex]
return cipherText
print(caesarEncrypt("I committed to playing soccer at Penn State", 2))
# write a caesarDecrypt(cipherText, shift)
def caesarDecrypt(plainText, shift):
cipherText = ""
for ch in plainText:
if ch in upper:
index = upper.find(ch)
nextIndex = (index + shift) % 27
if nextIndex < 0:
nextIndex = 27 + nextIndex
cipherText += upper[nextIndex]
else:
index = lower.find(ch)
nextIndex = (index + shift) % 27
if nextIndex < 0:
nextIndex = 27 + nextIndex
cipherText += lower[nextIndex]
return cipherText
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.