text
stringlengths 37
1.41M
|
---|
import re
# Convert text to lower-case and strip punctuation/symbols from words
def normalize_text(text):
norm_text = text.lower()
norm_text = re.sub(r"\.+", ".", norm_text)
# Replace breaks with spaces, in case there's broken html in there
norm_text = norm_text.replace('<br />', ' ')
# Replace multiple whitespaces with a single space
norm_text = " ".join(norm_text.split())
# Remove commas, colons, semicolons. The reader can just deal with it.
to_remove = [",", ":", ";"]
norm_text = norm_text.translate({ord(x): '' for x in to_remove})
# Replace exclamation marks with full stops
norm_text = norm_text.replace("!", ".")
# Pad punctuation with spaces on both sides
for char in ['.', '"', ',', '(', ')', '!', '?', ';', ':']:
norm_text = norm_text.replace(char, ' ' + char + ' ')
return norm_text
|
"""
nums = []
for x in range(8):
nums.append(x)
print nums
squares = []
for x in range(8):
squares.append(x**2)
print squares
print [x for x in range(8)]
print [x*x for x in range(8)]
print [ (x, x*x, x*x*x) for x in range(8) ]
p="myNoobPass1234"
print [x for x in p]
print [x for x in "1234"]
UC_LETTERS="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
print [ x for x in p if x in UC_LETTERS ]
print [ 1 for x in p if x in UC_LETTERS ]
print [ 1 if x in UC_LETTERS else 0 for x in p ]
"""
def passwordTest(test):
UC_LETTERS1="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
UC_LETTERS2="abcdefghijklmnopqrstuvwxyz"
UC_NUMBERS="0123456789"
if len([x for x in test if x in UC_LETTERS1]) > 0:
if len([x for x in test if x in UC_LETTERS2]) > 0:
if len([x for x in test if x in UC_NUMBERS]) > 0:
return True
return False
"""
print passwordTest("ABCd0")
print passwordTest("ABCD0")
print passwordTest("ABCdO")
print passwordTest("abcd0")
"""
def passwordStrength(test):
UC_LETTERS1="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
UC_LETTERS2="abcdefghijklmnopqrstuvwxyz"
UC_NUMBERS="0123456789"
UC_CHARACTERS=".?!&#,;:-_*"
c = 0
if len([x for x in test if x in UC_LETTERS1]) > 2:
c+=2
elif len([x for x in test if x in UC_LETTERS1]) > 0:
c+=1
if len([x for x in test if x in UC_LETTERS2]) > 2:
c+=2
elif len([x for x in test if x in UC_LETTERS2]) > 0:
c+=1
if len([x for x in test if x in UC_NUMBERS]) > 1:
c+=2
elif len([x for x in test if x in UC_NUMBERS]) > 0:
c+=1
if len([x for x in test if x in UC_CHARACTERS]) > 1:
c+=2
elif len([x for x in test if x in UC_CHARACTERS]) > 0:
c+=1
if len(test) > 11:
c+=2
elif len(test) > 7:
c+=1
return c
"""
print passwordStrength("a")
print passwordStrength("B")
print passwordStrength("aaa")
print passwordStrength("BBB")
print passwordStrength("1")
print passwordStrength("22")
print passwordStrength("!")
print passwordStrength("??")
print passwordStrength("aaaaaaaa")
print passwordStrength("aaaaaaaaaaaa")
print passwordStrength("asadBDFS345!!!")
"""
|
import functools
class A(object):
def __init__(self,k="do"):
self.k=k
def __call__(self, func):
@functools.wraps(func)
def __de(*args,**kwargs):
if self.k=="do":
self.notify(func)
return func(*args,**kwargs)
return __de
def notify(self,func):
print("%s running" %func.__name__)
@A(k="do")
def cx_A(a,b):
return a+b
class B(A):
def __init__(self,sex='femal',*args,**kwargs):
self.sex=sex
super(B,self).__init__(*args,**kwargs)
def notify(self,func):
print("%s running" %func.__name__)
print("%sex " % self.sex)
@B(k="do")
def cx_B(a,b):
return a+b
|
n = 10
# Iterative
x=1
y=1
for i in range(1, n):
oldx=x
x=y
y=oldx+y
print(x)
# Recursive
def fibbonaci(n):
if n<=1:
return 1
else:
return fibbonaci(n-1) + fibbonaci(n-2)
print(fibbonaci(n))
|
def SEARCH(brr,Num):
Cnt=0
for i in range(len(brr)):
if brr[i]==Num:
Cnt+=1
return Cnt
def main():
arr=[]
for i in range(int(input("ENTER THE NUMBER OF ELEMENTS IN ARRAY"))):
print("ENTER THE ARRAY ELEMENT ",i+1)
arr.append(int(input()))
print("ANSWER IS : ",SEARCH(arr,int(input("ENTER THE ELEMENT TO BE SEARCHED"))))
if __name__== "__main__":
main()
|
def PRIME(iNo):
for i in range(2,int(iNo/2+1)):
if iNo%i==0:
print("IT IS NOT A PRIME NUMBER")
break
else:
print("IT IS PRIME NUMBER")
def main():PRIME(int(input("ENTER THE NUMBER")))
if __name__ == "__main__":
main()
|
def CHKEVEN(iVal):
if(iVal%2==0):
return True
else:
return False
def main():
no=int(input("ENTER THE NUMBER "))
ret=CHKEVEN(no)
if ret == True:
print("EVEN")
else:
print("ODD")
if __name__ == "__main__":
main()
|
import math
from sympy import * #for differentiation & mathematical functions
import numpy as np #matrix operations
pi=3.141592653589793
e=2.718281828459045
print('Project for "Numerical analysis". under the supervision of Dr. Mahmoud Gamal')
print('by:')
print('\t\tMohamed Yosry ElZarka 19100')
print('\t\tYoussef Mohamed Elsheheimy 19124')
print('\t\tOmar Abd Al-Halim Khalil 19138\n')
print("This is a program to calculate the numerical solution of a system of non-linear equations using (Newton's method).\n")
print("""
you can use parentheses () in addition to the following mathematical operators:
(+ Add), (- Subtract), (* Multiply), (/ Divide), (% Modulus), (// Floor division), (** Exponent)
you can also use the following constants:
\t pi=3.141592653589793
\t e=2.718281828459045
note: Trigonometric functions sin(x), asin(x), cos(x), acos(x), tan(x), atan(x) 'equivalent of tan-1(x)' use radian values.
log(x,y)= log(x) / log(y) ,,, ln(x)
""")
def check_equalization(recent_x,previous_x):
for i in range (0, len(recent_x)):
if recent_x[i] != previous_x[i]:
return False
return True
decimal_point_precision=4
while True:
n=int( input('Enter the number of equations: ') )
equations, equations_values, jacobian_matrix, jacobian_values= [] , [0]*n , [] , []
for i in range(0,n):
equations.append( str(input("Enter the equation #{}: 0 = ".format(i+1))) )
jacobian_matrix.append([])
jacobian_values.append([0]*n)
last_x , current_x= [] , []
for i in range(0,n):
last_x.append( float(input("Enter the initial x{} = ".format(i+1))) )
for i in range(0,n): #partial differntiaion matrix
for j in range(0,n):
jacobian_matrix[i].append( diff( equations[i] , 'x'+str(j+1) ) )
print("\njacobian matrix=",jacobian_matrix)
print("\n ",end="")
for i in range(0,n):
print("x{} ".format(i+1),end="")
print("")
print("i=0",end="")
for i in range(0,n):
last_x[i]=round( last_x[i] , decimal_point_precision )
print(" | %.4f | "%last_x[i],end="")
print("")
dictionary_of_last_x={}
for iterations in range(1,500): #maximum number of iterations is 500
for i in range(0,n): #updating the values of matrices
dictionary_of_last_x['x'+str(i+1)]=last_x[i]
for i in range(0,n):
equations_values[i]=round( eval(equations[i],dictionary_of_last_x) , decimal_point_precision)
for i in range(0,n):
for j in range(0,n):
jacobian_values[i][j]=round( eval(str(jacobian_matrix[i][j]),dictionary_of_last_x) , decimal_point_precision )
A = np.array(last_x) #matrix declarations
B = np.array(jacobian_values)
C = np.array(equations_values)
current_x=np.subtract(A, np.dot( np.linalg.inv(B) , C ) ) #matrix operations
print("i={}".format(iterations),end="")
for i in range(0,n):
current_x[i]=round( current_x[i] , decimal_point_precision )
print(" | %.4f | "%current_x[i],end="")
print("")
if check_equalization(current_x,last_x):
break
last_x=current_x
print("\nAfter",iterations,"iterations, The solution is at")
for i in range(0,n):
print("\t\tx{} =".format(i+1),last_x[i])
print("\n____________________________________________")
print("Try another system of non-linear equations.")
|
# Python 3.6
# comparison of two versoin numbers in string
# Invoke: versionNumCompare(VersionNumInString, VersinNumInString)
# Return: return True if first version is greater than second,
# otherwise, return False
def versionNumCompare(verStr1, verStr2):
verFloat1 = float(verStr1)
verFloat2 = float(verStr2)
return verFloat1 > verFloat2
print(versionNumCompare("1.2", "1.1"))
print(versionNumCompare("1.2", "2.1"))
|
#!/usr/bin/python
a = 1
b = 2
c = 997
while(a < 332):
while(b < c):
if(a**2 + b**2 == c**2):
print "Found it: " + str(a * b * c)
print "a=" + str(a) + " b=" + str(b) + " c=" + str(c)
exit()
b = b + 1
c = c - 1
a += 1
b = a + 1
c = 1000 - (a + b)
|
from matplotlib import pyplot as plt
#x_number = [1,2,3,4,5]
x_number = list(range(1,5001))
y_number = [x**3 for x in x_number]
#edgecolor边框 c y渐变camp颜色
plt.scatter(x_number,y_number,edgecolors='none',c=y_number,cmap=plt.cm.Blues)
#坐标 标题
plt.title("Cube Number",fontsize=15)
plt.xlabel("value",fontsize=12)
plt.ylabel("Cube of value",fontsize=12)
#标记刻度大小
plt.tick_params(axis='both',which='major',labelsize=14)
plt.show()
|
A=10
B="HelloPython"
C=6.9999
D=1+2j
#datatypes print datatypes
print("A-"+str(A))
print("B-"+str(B))
print("C-"+str(C))
print("C-"+str(D))
#get data types
print("A type is ",end="")
print(type(A))
print("B type is ",end="")
print(type(B))
print("C type is ",end="")
print(type(C))
print("D type is ",end="")
print(type(D))
|
"""Custom topology example
Two directly connected switches plus a host for each switch:
host --- switch --- switch --- host
Adding the 'topos' dict with a key/value pair to generate our newly defined
topology enables one to pass in '--topo=mytopo' from the command line.
"""
from mininet.topo import Topo
class MyTopo( Topo ):
'''Simple topology example.'''
def build( self ):
"Create custom topo."
# Add hosts and switches
h1 = self.addHost( 'h1' , ip='10.0.0.1', mac='00:00:00:00:00:01')
h2 = self.addHost( 'h2' , ip='10.0.0.2', mac='00:00:00:00:00:02')
h3 = self.addHost( 'h3' , ip='10.0.0.3', mac='00:00:00:00:00:03')
h4 = self.addHost( 'h4' , ip='10.0.0.4', mac='00:00:00:00:00:04')
swA = self.addSwitch( 's1' )
swB = self.addSwitch( 's2' )
swC = self.addSwitch( 's3' )
swD = self.addSwitch( 's4' )
# Add links
self.addLink(h1, swA)
self.addLink(h2, swB)
self.addLink(h3, swC)
self.addLink(h4, swD)
self.addLink(swA, swB)
self.addLink(swB, swC)
self.addLink(swC, swD)
self.addLink(swD, swA)
#self.addLink( BSwitch, ESwitch )
#self.addLink( CSwitch, ESwitch )
#self.addLink( DSwitch, rightHost)
topos = { 'mytopo': ( lambda: MyTopo() ) }
|
#字典
my_dic={"lisirui":110,"zhangkaiyan":120,"wanghanwei":119}
print(my_dic["lisirui"])
print(len(my_dic))
print("zhangkaiyan" in my_dic)
for key in my_dic :
print(key)
|
#python中的生成器
g = (x * x for x in range(10))
#可以用g 中自带的函数next来访问每一个元素next(g)
#也可以用循环(方便)
for n in g:
print(n)
#===========================================================
#generator的函数,在每次调用next()的时候执行,
#遇到yield语句返回,再次执行从上次返回的yield语句处继续执行
#generator函数的“调用”实际返回一个generator对象
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
return 'done'
for n in fib(6):
print(n)
g = fib(6)
while True:
try:
x = next(g)
print('g:',x)
except StopIteration as e:
print('Generator return value:',e.value)
break
#===========================================================
def odd():
print('step 1')
yield 1
print('step 2')
yield(3)
print('step 3')
yield(5)
o = odd()
print(next(o))
print(next(o))
print(next(o))
|
def limitLabel(limit):
for i in range(0,limit+1):
if i % 2 == 0:
print(i, "EVEN")
else:
print(i, "ODD")
inp = eval(input("Please enter the limit range: "))
limitLabel(inp)
|
def str_to_Int(str1,str2):
i1 = int(str1)
i2 = int(str2)
i3 = i1 + i2
print("Addition of these no.s: ", i3)
strInp1 = input("Please enter 1st number: ")
strInp2 = input("Please enter 2nd number: ")
str_to_Int(strInp1,strInp2)
|
'''
def strUpper(str):
li = []
while str != "":
li.append(str.partition(" ")[0])
str = str.partition(" ")[2]
for i in li:
i.upper()
str2 = ' '.join(li)
return str2
'''
inpStr = input("Please enter your string: ")
##print(strUpper(inpStr))
print(inpStr.upper())
|
"""
This module contains the Background, Stage and Viewport classes.
Viewport: The viewport is the area of the stage visible on the display surface.
Stage: The stage is the area of the game that is currently rendered, it contains the viewport.
Background:
"""
import pygame
from get_image import get_image
class Background:
"""Class to initiate the tile background of the game and set its tiles.
"""
def __init__(self, color="black"):
"""Initialization.
Keyword Arguments:
color {str} -- color of the background behind the tiles (default: {"black"})
"""
try:
self.color = pygame.Color(color)
except ValueError:
self.color = pygame.Color("black")
def setTiles(self, tiles):
"""Sets the background tiles.
Arguments:
tiles {str|list} -- either a string, a list of strings or a list of lists of strings.
string - the file path to the background image
list of strings - list of file paths to the background horizontal tiles
list of lists - grid of the background tiles (each sublist represents a row of tiles)
"""
if type(tiles) is str:
self.tiles = [[get_image(tiles, False)]]
elif type(tiles[0]) is str:
self.tiles = [[get_image(tile, False) for tile in tiles]]
else:
self.tiles = [[get_image(tile, False) for tile in row] for row in tiles]
self.tileWidth = self.tiles[0][0].get_width()
self.tileHeight = self.tiles[0][0].get_height()
class Viewport:
"""The viewport is the area of the stage visible on the screen.
"""
def __init__(self, surface=None):
"""Initialization.
Keyword Arguments:
surface {pygame.Surface} -- surface which determines the viewport's dimmentions (default: {pygame.display.get_surface()})
"""
if not surface:
# if surface is not supplied, it defaults to the currently set display surface
surface = pygame.display.get_surface()
rect = surface.get_rect()
self.w, self.h = rect.size # Set width and height of the viewport
self.x, self.y = 0, 0 # Set position of the viewport
def setLocation(self, x, y):
"""Sets the location of the viewport (specifically, the top left corner of the viewport).
Arguments:
x {float|int} -- x coordinate
y {float|int} -- y coordinate
"""
self.x, self.y = x, y
def checkObjectVisible(self, sprite):
"""Checks if (part of) a sprite is within the viewport and thus, visible on the display surface.
Arguments:
sprite {Sprite} -- the sprite to check whether is visible
Returns:
bool -- True if the sprite is visible else False
"""
rect = sprite.rect
# Half width and half height of the sprite
hw, hh = rect.size[0] / 2, rect.size[1] / 2
x, y = sprite.x, sprite.y # Position of the sprite
if x + hw < self.x or x - hw > self.x + self.w or y - hh > self.y + self.h or y < self.y - hh:
return False
return True
def centerOnXY(self, x, y):
"""Move the viewport so that it is centered on (x,y).
Arguments:
x {float|int} -- x coordinate
y {float|int} -- y coordinate
"""
self.setLocation(x - (self.w / 2), y - (self.h / 2))
class Stage:
"""The stage is the area of the game that is currently rendered, it contains the viewport.
"""
def __init__(self, num_layers, surface=None):
"""Initialization.
Arguments:
num_layers {int} -- number of layers of the stage
Keyword Arguments:
surface {pygame.Surface} -- surface in which the Stage resides (default: {pygame.display.get_surface()})
"""
if surface:
self.surface = surface
else: # if surface is not supplied, it defaults to the currently set display surface
self.surface = pygame.display.get_surface()
self.vp = Viewport()
self.bg = Background()
self.num_layers = num_layers
self.layers = [pygame.sprite.Group() for _ in range(num_layers)]
self.focus = None
def setFocus(self, sprite):
"""Configures the stage and viewport to follow a certain sprite.
if the parameter sprite is set to None the stage and viewport will stay static.
Arguments:
sprite {Sprite} -- the sprite to be focused on
"""
self.focus = sprite
def addSprite(self, sprite, layer=-1):
"""Adds a sprite to the stage.
Arguments:
sprite {Sprite} -- sprite to be added to the stage
Keyword Arguments:
layer {int} -- layer to which the sprite will be added. defaults to the frontmost layer. (default: {-1})
Returns:
Sprite -- same Sprite object as supplied to the function via 'sprite'.
helpful when the 'sprite' parameter is supplied by declaration when calling to this function
and an instance of it is desireable.
"""
self.layers[layer].add(sprite)
return sprite
def setBackground(self, backgroundTiles):
"""Sets the background tiles. (See docstring of setTiles in the Background class).
"""
self.bg.setTiles(backgroundTiles)
def drawBackground(self, x, y):
"""Draws 4 background tiles around the tile vertex nearest to (x,y), ensuring that
only tiles visible around (x,y) are drawn.
Arguments:
x {float} -- X coordinate
y {float} -- Y coordinate
"""
# World coordinates of the vertex closest to (x,y):
vertex_x = round(x / self.bg.tileWidth) * self.bg.tileWidth
vertex_y = round(y / self.bg.tileHeight) * self.bg.tileHeight
# Index of bottom-right background tile:
row = round(y / self.bg.tileHeight) % len(self.bg.tiles)
col = round(x / self.bg.tileWidth) % len(self.bg.tiles[0])
# Transform from world coordinates to screen coordinates:
vertex_x -= self.vp.x
vertex_y -= self.vp.y
# Paint with background color and Blit 4 background tiles around the vertex:
self.surface.fill(self.bg.color)
self.surface.blit(self.bg.tiles[row][col], (vertex_x, vertex_y))
self.surface.blit(self.bg.tiles[row-1][col], (vertex_x, vertex_y-self.bg.tileHeight))
self.surface.blit(self.bg.tiles[row][col-1], (vertex_x-self.bg.tileWidth, vertex_y))
self.surface.blit(self.bg.tiles[row-1][col-1], (vertex_x-self.bg.tileWidth, vertex_y-self.bg.tileHeight))
def do(self):
"""Draws background around the focused sprite.
Draws all visible sprites in their respective layers.
Centralizes the viewport on the focused sprite.
"""
if self.focus:
self.drawBackground(self.focus.x, self.focus.y)
else:
self.drawBackground(self.vp.x, self.vp.y)
for layer in self.layers:
for sprite in layer:
sprite.update(sprite.x, sprite.y)
if self.vp.checkObjectVisible(sprite):
sprite.draw()
if self.focus:
self.vp.centerOnXY(self.focus.x, self.focus.y)
|
# Dictionaries
# Using strings, lists, tuples and dictionaries concepts, find the reverse
# complement of AAAAATCCCGAGGCGGCTATATAGGGCTCCGGAGGCGTAATATAAAA
read = "AAAAATCCCGAGGCGGCTATATAGGGCTCCGGAGGCGTAATATAAAA"
dict = {'C': 'G', 'G': 'C', 'A': 'T', 'T': 'A'}
complement = [dict[base] for base in read]
complement.reverse()
reverse_complement = ''.join(complement)
print(reverse_complement)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
ME 499/599 File I/O example
Bill Smart
"""
from math import factorial
if __name__ == '__main__':
# Open a file and w
# with open('fac', 'w') as f:
# for n in range(10):
# f.write('{0} {1}\n'.format(n, factorial(n)))
#
# with open('fac', 'r') as f:
# for line in f:
# print(line)
# Beware cacheing filesystems!
f = open('foo', 'w')
f.write('This is a line of text')
g = open('foo', 'r')
print('=====')
for line in g:
print(line)
print('=====')
|
# Import libraries
from bs4 import BeautifulSoup # Install BeautifulSoup4
from urllib.request import Request, urlopen
from statistics import variance
from datetime import datetime
#dt = datetime.strptime('May 10, 2019', '%b %d, %Y')
#st = dt.strftime('%Y-%m-%d')
# Scrape the rows from a table with a given ID
def get_rows(url, table_id):
# Read html from given url
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
page = urlopen(req).read()
# Parse the html using beautiful soup and store in variable soup
soup = BeautifulSoup(page, 'html.parser')
# Retrieve the table body containing the prices
table = soup.find('table', attrs={'class': table_id})
table_body = table.find('tbody')
# Retrieve the rows from the table body
return table_body.find_all('tr')
# Return the columns from a given bs4.element.Tag object containing a row of a table
def get_cols(row):
# Create a list containing a bs4.element.Tag object for every element in the current row
cols = row.find_all('td')
# Return a list containing only the text for every cell in the current row
return [cell.text.strip() for cell in cols]
# Scrape the prices for the given metal type and the respective url
def scrape_prices(urls):
# Dictionary containing the scraped data as Python dictionary
data = {}
# Scrape the data
for type, url in urls.items():
# Retrieve the rows from the table containing the prices of the given metal type
price_rows = get_rows(url, 'genTbl closedTbl historicalTbl')
# Add the current type
data.update({
type:{
'data': {},
'mean': 0.0,
'variance': 0.0,
}
})
# Cycle through rows and store date and price
for row in price_rows:
# Get a list containing only the text for every cell in the current row
cols = get_cols(row)
# Transfor date from 'May 10, 2019' to '2019-05-10'
dt = datetime.strptime(cols[0], '%b %d, %Y')
cols[0] = dt.strftime('%Y-%m-%d')
# Add first cell (containing the date) and second cell (containing the price)
data[type]['data'].update({cols[0]:float(cols[1].replace(',',''))})
# Retrieve the table body containing the statistics (low, high, mean, change)
# This table contains only one row
stats_row = get_rows(url, 'genTbl closedTbl historicalTblFooter')[0]
# Transform each cell from format like 'Highest: 1,307.10' to ['Highest', '1307.10']
stats = [[c.strip().replace(',','') for c in cell.split(':')] for cell in get_cols(stats_row)]
# Transform the number values from string to float and store stats in dictionary
stats = {e[0]:float(e[1]) for e in stats}
# Add mean value
data[type]['mean'] = stats['Average']
# Add variance of prices (rounded on two decimals)
data[type]['variance'] = round(variance([price for price in data[type]['data'].values()]),2)
# Return data as Python dictionary
return(data)
|
def median(lst):
sortedLst = sorted(lst)
lstLen = len(lst)
index = (lstLen - 1) // 2
if (lstLen % 2):
return sortedLst[index]
else:
return (sortedLst[index] + sortedLst[index + 1])/2.0
def newPlayer():
score1 = float(input("Please input the first round score"))
score2 = float(input("Please input the second round score"))
playerName = float(input("Please input the name of the player"))
totalScore = score1 + score2
return playerName, totalScore
while True:
players = []
players.append(newPlayer())
|
########################################################################
# #
# Playing moving Sound in headphones #
# #
# 1.Imported a wave audio file #
# 2.Controlled the magnitude of input audio signals #
# 3.Added a time dealy to the input audio signals #
# 4.Outputted and Played a wave file with moving sound effects #
# #
########################################################################
import soundfile as sf
import numpy as np
from pydub import AudioSegment
from pydub.playback import play
#import input music wave file
data, samplerate = sf.read('typewriter.wav')
audio_sample = data.shape[0]
#Determine the channel size
if len(data.shape) == 2:
channels = data.shape[1]
elif len(data.shape) == 1:
channels = 2
data = data.reshape(audio_sample,1)
data = data.repeat(2,1)
#choose the time offset between the left and right sterro sound
#between 0.001% of the number of audio samples read
time_offset = round(1*(10**(-5))*audio_sample)
total_sample = round(2*time_offset+audio_sample)
#Initialize the coefficient matric
left_coe = np.zeros((total_sample,1))
right_coe = np.zeros((total_sample,1))
#Controlled the magnitude of the audio signal respect to its total number of audio samples
ratio = 1.0/audio_sample
#obtain a user input ranged from 1 to 2
#1 means slowest sound moving speed, 2 means fastest sound moving speed.
factor = input("Please enter a number between 1 to 2; it relates to the speed of moving sounds: ")
while True:
try :
factor = float(factor)
if factor <1 or factor >2:
factor = float(input("Your input is invalid. Please enter a number between 1 to 2: "))
else:
break
except:
factor = input("Your input is invalid. Please enter a number between 1 to 2: ")
#Create a coefficient matrix to controll the magintude of the audio samples
#The sounds start from left moving to right in the beginning, and moving back to the right in the end
for i in range(total_sample):
if i <= time_offset:
left_coe[i] = 1-i*ratio*factor
right_coe[i] = 0
elif i <=audio_sample/2:
left_coe[i] = 1-i*ratio*factor
right_coe[i] = (i-time_offset)*ratio*factor
elif i <= audio_sample/2+time_offset:
left_coe[i] = 1-audio_sample/2*ratio*factor
right_coe[i] = (i-time_offset)*ratio*factor
elif i <= audio_sample/2+2*time_offset:
left_coe[i] = 1-audio_sample/2*ratio*factor
right_coe[i] = audio_sample/2*factor*ratio
else:
left_coe[i] = 1-audio_sample/2*ratio*factor + (i-audio_sample/2-2*time_offset)*ratio*factor
right_coe[i] = audio_sample*factor*ratio-(i-audio_sample/2-2*time_offset)*ratio*factor
new_left = np.zeros((total_sample,1))
new_right = np.zeros((total_sample,1))
#matrix multiplication
def matrix_multiply(coe_matrix,audio_data,start_in,end_in,audio_index,offset):
return np.multiply(coe_matrix[start_in+offset:end_in+offset,0],audio_data[start_in:end_in,audio_index])
#obtain the moving left and right steroe sounds by multiply the coefficient matrixs with the original values
new_left[0:audio_sample//2,0] = matrix_multiply(left_coe,data,0,audio_sample//2,0,0)
new_left[audio_sample//2:audio_sample//2+2*time_offset,0] = left_coe[audio_sample//2,0]*data[audio_sample//2,0]
new_left[audio_sample//2+2*time_offset:total_sample,0] = matrix_multiply(left_coe,data,audio_sample//2,audio_sample,0,2*time_offset)
new_right[time_offset:audio_sample//2+time_offset,0] = matrix_multiply(right_coe,data,0,audio_sample//2,1,time_offset)
new_right[audio_sample//2+time_offset:audio_sample//2+2*time_offset,0] =right_coe[audio_sample//2+time_offset,0] * data[audio_sample//2,1]
new_right[audio_sample//2+2*time_offset:,0] = matrix_multiply(right_coe,data,audio_sample//2,audio_sample,1,2*time_offset)
#and concatenate two matric and turn into one audio file
#output the result as a wav file
new_song = np.concatenate((new_left[:,0:1],new_right),axis = 1)
sf.write('new_typerwriter.wav',new_song,samplerate)
#play the audio file with moving effects
play_back = AudioSegment.from_wav('new_typerwriter.wav')
play(play_back)
|
for x in range(2,11,2):
print(x)
print("----------")
for x in range(1,11,2):
print(x)
|
a=int(input("plz enter anum:"))
b=int(input("plz enter a num:"))
if a+b==10:
print("true")
elif a==10 or b==10:
print("true")
else:
print("false")
|
def linear_search(lst, to_find):
# search for the element to_find inside lst
# if found, return index of element
# else return -1
if (to_find in lst):
return lst.index(to_find)
else:
return -1
print(linear_search([1], 1))
|
#my virtual car1.0
"""
Author::: tushar2899
following inputs required:
license plate number
vehicle identification no.
and then choice codes for continuous operation
ENTER THE DESIRED CHOICE CODE:
1.GEAR UP 2.GEAR DOWN
3.MOVE FAST 4.MOVE SLOW
5.TURN LEFT 6.TURN RIGHT 7.GO REVERSE
8.STOP 9.EXIT
"""
class Cars():
"""CLASS NAME:Cars
Version 1.0
Author: tushar2899
Description:THIS CLASS contains cars various details and operation related to the working of cars
"""
direction="NORTH" #inittially the direction of car is set as north
def __init__(self, lic_plate, veh_Iden_No, speed=0, rpm=0, gear=0, fuel_level=100, engine_temp=37.5):
self.lic_plate=lic_plate
self.veh_Iden_No=veh_Iden_No
self.speed=speed
self.rpm=rpm
self.gear=gear
self.fuel_level=fuel_level
self.engine_temp=engine_temp
#defining the 8 getter methods
def getLic_plate(self):
"""getting the license plate number of the car"""
return "LICENSE PLATE NO. %s"%self.lic_plate
def getVeh_id(self):
"""getting the vehicle identification no."""
return "VEHICLE IDENTIFICATION NO. %s"%self.veh_Iden_No
def getSpeed(self):
"""getting the speed of the car at that moment"""
return "SPEED: %d"%self.speed
def getRpm(self):
"""getting the rpm of the car"""
return "RPM: %d"%self.rpm
def getGear(self):
"""getting the gear level """
return "GEAR: %d"%self.gear
def getFuel(self):
"""getting the fuel level of the car"""
return "FUEL LEVEL %s"%self.fuel_level
def getEng_temp(self):
"""getting the engine temperature"""
return "ENGINE TEMPERATURE: %s"%self.engine_temp
def getDir(self):
"""getting the direction of the car"""
return "DIRECTION: %s"%Cars.direction
def gearUp(self):
"""to increase the gear level
if gear is at 5 it can't be increased
if gear inc. speed inc.
if speed inc.rpm and temp inc."""
if(self.gear<5 ):
self.gear+=1
else:
print ("Maximum gear level Reached")
#since speed has to change with gear hence if gear>0 with every increment speed will inc. by 40
if(self.gear>0 and self.speed<=160):
self.speed+=40
elif(self.gear==0):
self.speed=0
else:
if self.gear==-1:
self.speed=40
#since rpm has to change with speed hence if gear>0 with every increment rpm will inc. by 750
if(self.gear>0 and self.rpm<=400):
self.rpm+=750
elif(self.gear==0):
self.rpm=0
else:
if self.gear==-1:
self.rpm=750
#since engine temp has to change with speed hence if gear>0 with every increment temp will inc. by 40
if(self.gear>0 and self.engine_temp<160):
self.engine_temp+=40
elif(self.gear==0):
self.engine_temp=35
else:
if self.gear==-1:
self.engine_temp=75
def gearDown(self):
""" lowering the gear level
if gear is lowered speed dec.
if speed dec. rpm and temp. dec.
"""
if(self.gear>=0):
self.gear-=1
else:
print ("LOWEST GEAR REACHED")
if(self.gear==0):
self.speed=0
#since speed has to change with gear hence if gear>0 with every decrement speed will dec. by 40
if(self.gear>0 and self.speed>+40):
self.speed-=40
elif(self.gear==0):
self.speed=0
else:
if self.gear==-1:
self.speed=40
#since rpm has to change with speed hence if gear>0 with every decrement rpm will dec. by 750
if(self.gear>0 and self.rpm>=750):
self.rpm-=750
elif(self.gear==0):
self.rpm=0
else:
if self.gear==-1:
self.rpm=750
#since engine temp has to change with speed hence if gear>0 with every decrement temp will dec. by 40
if(self.gear>0 and self.engine_temp>=65):
self.engine_temp-=40
elif(self.gear==0):
self.engine_temp=35
else:
if self.gear==-1:
self.engine_temp=75
def moveFast(self):
"""to increase the speed if gear is !=0 by 10
if speed inc.rpm and temp icreases"""
if(self.gear!=0 and self.speed<=190):
self.speed+=10
else:
self.speed=0
if self.speed==200:
print ("Maximum speed reached")
#since rpm has to change with speed hence if gear>0 with every increment rpm will inc. by 200
if(self.gear!=0):
self.rpm+=200
else:
self.rpm=0
#since engine temp has to change with speed hence if gear>0 with every increment temp will inc. by 10
if(self.gear!=0):
self.engine_temp+=15
else:
self.engine_temp=35
def moveSlow(self):
"""to decrease the speed if gear is !=0 by 10
if speed inc.rpm and temp dec."""
if(self.gear!=0 and self.speed>=10):
self.speed-=10
else:
self.speed=0
if self.speed==0:
print ("Lowest speed reached")
#since rpm has to change with speed hence if gear>0 with every decrement rpm will inc. by 200
if(self.gear!=0 and self.rpm>=200):
self.rpm-=200
else:
self.rpm=0
#since engine temp has to change with speed hence if gear>0 with every decrement temp will inc. by 10
if(self.gear!=0 and self.temp>=45):
self.engine_temp-=15
else:
self.engine_temp=35
def moveRight(self):
"""to take a left turn
respectively the direction changes"""
if Cars.direction=="NORTH":
Cars.direction="EAST"
elif Cars.direction=="EAST":
Cars.direction="SOUTH"
elif Cars.direction=="SOUTH":
Cars.direction="WEST"
else:
Cars.direction="NORTH"
def moveLeft(self):
"""to take a right turn
respectively the direction changes"""
if Cars.direction=="NORTH":
Cars.direction="WEST"
elif Cars.direction=="WEST":
Cars.direction="SOUTH"
elif Cars.direction=="SOUTH":
Cars.direction="EAST"
else:
Cars.direction="NORTH"
def moveBack(self):
"to go on reverse"
self.gear=-1
self. speed=40
def stop(self):
"""to stop the vehicle"""
self.gear=0
self.speed=0
self.rpm=0
#---------------------end of class Cars---------------------------------------------------
#getting the lic plate no. and vin from the user
car_lic=input("Enter license plate number:")
car_vin=int(input("Enter vehicle verification number:"))
car1=Cars(car_lic,car_vin) #creating an object named car1 of class Cars
#PRINTING THE CURRENT STATUS OF THE CAR
print (car1.getLic_plate())
print (car1.getVeh_id())
print (car1.getGear())
print (car1.getSpeed())
print (car1.getRpm())
print (car1.getFuel())
print (car1.getEng_temp())
print (car1.getDir())
#INITIATING A INFINITE LOOP FOR CONTINUOUS OPERATION ON THE CAR
while(1==1):
#SHOW CASING THE PREFENCE MENU AND GETTING THE CHOICE FROM USER
choice=int(input("********menu********\n ENTER THE DESIRED CHOICE CODE:\n1.GEAR UP 2.GEAR DOWN\n3.MOVE FAST 4.MOVE SLOW\n5.TURN LEFT 6.TURN RIGHT 7.GO REVERSE\n8.STOP 9.EXIT\n"))
#EXECUTING DESIRED ACTION BASED ON USER CHOICE
if(choice==1):
car1.gearUp()
elif(choice==2):
car1.gearDown()
elif(choice==3):
car1.moveFast()
elif(choice==4):
car1.moveSlow()
elif(choice==5):
car1.moveLeft()
elif(choice==6):
car1.moveRight()
elif(choice==7):
car1.moveBack()
elif(choice==8):
car1.stop()
elif(choice==9):
break
else:
print ("INVALID CHOICE CODE")
#PRINTING THE CHANGED STATE OF THE VEHCLE
print (car1.getLic_plate())
print (car1.getVeh_id())
print (car1.getGear())
print (car1.getSpeed())
print (car1.getRpm())
print (car1.getFuel())
print (car1.getEng_temp())
print (car1.getDir())
print ("\n\n")
#SAMPLE OUTPUT
"""
Enter license plate number:MH-02-7899
Enter vehicle verification number:879541457
LICENSE PLATE NO. MH-02-7899
VEHICLE IDENTIFICATION NO. 879541457
GEAR: 0
SPEED: 0
RPM: 0
FUEL LEVEL 100
ENGINE TEMPERATURE: 37.5
DIRECTION: NORTH
********menu********
ENTER THE DESIRED CHOICE CODE:
1.GEAR UP 2.GEAR DOWN
3.MOVE FAST 4.MOVE SLOW
5.TURN LEFT 6.TURN RIGHT 7.GO REVERSE
8.STOP 9.EXIT
1
LICENSE PLATE NO. MH-02-7899
VEHICLE IDENTIFICATION NO. 879541457
GEAR: 1
SPEED: 40
RPM: 750
FUEL LEVEL 100
ENGINE TEMPERATURE: 77.5
DIRECTION: NORTH
********menu********
ENTER THE DESIRED CHOICE CODE:
1.GEAR UP 2.GEAR DOWN
3.MOVE FAST 4.MOVE SLOW
5.TURN LEFT 6.TURN RIGHT 7.GO REVERSE
8.STOP 9.EXIT
6
LICENSE PLATE NO. MH-02-7899
VEHICLE IDENTIFICATION NO. 879541457
GEAR: 1
SPEED: 40
RPM: 750
FUEL LEVEL 100
ENGINE TEMPERATURE: 77.5
DIRECTION: EAST
********menu********
ENTER THE DESIRED CHOICE CODE:
1.GEAR UP 2.GEAR DOWN
3.MOVE FAST 4.MOVE SLOW
5.TURN LEFT 6.TURN RIGHT 7.GO REVERSE
8.STOP 9.EXIT
"""
|
#just run pythnon3 module_using_name.py
#Every python module has its __name__ defined.if this is __main__
#this is program stroed as a
#import sys
#sys.path -->stores as shows the following path as well
#now import this file as import module_using_name
#run as another module
if __name__ == '__main__':
print("This program is being run by itself")
else:
print("I am imported from anthoer program")
|
'''
read a file from
'''
''' data = open('text.txt','r')
for line in data:
print(line)
data.close()
'''
'''
write in a file
'''
tar = open('new_file.txt','w')
tar.write('Hey i m suresh ')
tar.write('Python')
tar.write('\n')
tar.write('finally i got')
tar.close()
tar = open('new_file.txt','a')
tar.write('\n')
tar.write('I added the line')
tar.close()
|
class Player:
"""Model representing a chess player in a tournament"""
def __init__(self, id, firstname, lastname, gender, rating):
self.id = id
self.first_name = firstname
self.last_name = lastname
self.gender = gender
self.rating = int(rating)
def __str__(self):
return f' ID # {self.id} - {self.first_name} ' \
f'{self.last_name} - Rating # {self.rating}'
def get_rating(self):
return self.rating
def get_name(self):
return self.last_name
def serialize(self):
"""serialize a player"""
serialized_player = {
'first_name': self.first_name,
'last_name': self.last_name,
'gender': self.gender,
'rating': self.rating,
}
return serialized_player
|
import pandas as pd
import numpy as np
df = pd.read_csv('movies_dataset.txt', encoding= 'unicode_escape')
start_year = 1950
end_year = 1960
mask = (df['year'] > start_year) & (df['year'] <= end_year)
df1 = df.loc[mask]
df_count_year = df1.count()
print("Number of movies released between the year 1950 and 1960 are:", df_count_year['year'])
rating = 4.0
mask1 = (df['rating'] > rating)
df2 = df.loc[mask1]
df_count_rating = df2.count()
print("Number of movies whose ratings are more than 4 are:", df_count_rating['rating'])
start_rating = 3
end_rating = 4
mask2 = (df['rating'] > start_rating) & (df['rating']<end_rating)
df3 = df.loc[mask2]
print("Movie names whose ratings are between 3 and 4 are:\n", df3['Movie_name'].head())
total_duration = 7200
mask2 = (df['duration'] > total_duration)
df4 = df.loc[mask2]
df_count_duration = df4.count()
print("Number of movies with duration more than 2 hours are:",df_count_duration['duration'])
# df5 = df.loc()
# df5 = df['year'].sort()
# print(df5['Movie_name']['year'].head())
# df['Movie_name'] = df['Movie_name'].astype(float)
# df_total_count = df['Movie_name'].count()
# print("Total number of movies in a dataset:", df_total_count.head())
num = len(df)
print("The number of movies in the dataset is {}".format(num))
|
###############################################################################
#Todo:
#*Make it so the size of the room can be changed easily using a roomSize variable
#*Figure out how Desika wants the exponential variable to act
#*Make number of time steps its own variable so it can be changed easier
#*Make my own random number generator, this might improve speed
#*Make my own exponential variable function
import random
import matplotlib.pyplot as plott
import matplotlib.animation as anim
import time
#Change any of these variables to change the parameters of the experiment
roomSize=150 #default 100
numberOfPeople=100 #default 100
infectionRadius=3 #default 3
infectionChance=70 #default 70 (must be between 0 and 100)
personalSpace=3 #default 3
peopleLocation=0
zombieLocation=0
vaccLocation=[]
fig=plott.figure()
ax1=fig.add_subplot(1,1,1)
plott.ion()
#the two variables below are so the pyplot screen doesn't constantly resize.
#The white points indicate the room border
xborderpoint=[0,0,roomSize, roomSize]
yborderpoint=[roomSize, 0, roomSize, 0]
#Sets up a room of size roomSize and fills it with people.
def createRoom():
randomLocation=[0,0]
people=[]
switch=0
for i in range(numberOfPeople):
while people.count(randomLocation)==1:
randomLocation=[random.randint(0,roomSize), random.randint(0,roomSize)]
people.append(randomLocation)
#print people
return people
#generateNewLocation() generates new location for every moving person. It checks whether they are in bounds on the room
#and whether they are too close to a vaccinated person.
def generateNewLocation(peopleLocation2):
newLocation=[0,1]
for personNumber in range(len(peopleLocation2)-1):
breakLoop=0
while 1:
newLocation[0]=peopleLocation2[personNumber][0]+random.randint(-2,2)
newLocation[1]=peopleLocation2[personNumber][1]+random.randint(-2,2)
if newLocation[0]<roomSize-1 and newLocation[0]>-1:
if newLocation[1]<roomSize-1 and newLocation[1]>-1:
#If it's in the room and if it does NOT collide then break
for y in range(-1*personalSpace, personalSpace):
for x in range(-1*personalSpace, personalSpace):
#Go through every person and see if the coordinate equals their coordinate
for check in peopleLocation2:
if check[0]==newLocation[0]+x:
if check[1]==newLocation[1]+y:
breakLoop+=1
print check
#print newLocation
if breakLoop<2:
print "broke"
peopleLocation2[personNumber][0]=newLocation[0]
peopleLocation2[personNumber][1]=newLocation[1]
break
print "loop"
# print "New Location Set"
return peopleLocation2
#checkInfected() checks whether a person within a certain pixel radius is infected and infects non infected people
#within that radius based on some probability
def checkInfected(people, zombie):
personNumber=0
while personNumber < len(peopleLocation)-1:
personNumber+=1
for y in range(infectionRadius*-1,infectionRadius):
for x in range(infectionRadius*-1,infectionRadius):
for zombieCheck in zombieLocation:
try:
#print "personNumber:", personNumber, "\nlen(peopleLocation)", len(peopleLocation)
if peopleLocation[personNumber][0]+x==zombieCheck[0] and peopleLocation[personNumber][1]+y==zombieCheck[1]:
#There is a 30% chance that someone will be infected if within range
if random.randint(1,100)<infectionChance:
zombieLocation.append(people[personNumber])
peopleLocation.pop(personNumber)
# print "Infected!"
#print "XXXXXXX"
except:
#print "ERROR personNumber:", personNumber, "\nlen(peopleLocation)", len(peopleLocation)
print "*"*20
personNumber+=-2
#raise SystemExit
#plotting() is responsible for plotting the all the people in pyplot and animating the plot
#Note: I should replace all the variables with one large list of length 3. That will make my code cleaner.
def plotting(i):
xcoordpeople=[]
ycoordpeople=[]
xcoordzombie=[]
ycoordzombie=[]
xcoordvacc=[]
ycoordvacc=[]
ax1.clear()
for x in peopleLocation:
xcoordpeople.append(x[0])
ycoordpeople.append(x[1])
#print peopleLocation
for y in zombieLocation:
xcoordzombie.append(y[0])
ycoordzombie.append(y[1])
for z in vaccLocation:
xcoordvacc.append(z[0])
ycoordvacc.append(z[1])
ax1.scatter(xborderpoint,yborderpoint,c="white")
ax1.scatter(xcoordpeople, ycoordpeople,c="black")
ax1.scatter(xcoordzombie, ycoordzombie,c="red")
ax1.scatter(xcoordvacc, ycoordvacc,c="blue")
plott.draw()
#vaccinate() will create a list of vaccinated people and specify their properties
def vaccinate():
randomperson=random.randint(0,len(peopleLocation)-1)
vaccLocation.append(peopleLocation[randomperson])
peopleLocation.pop(randomperson)
#the locations of all noninfected people
peopleLocation=createRoom()
#the location of all infected people
zombieLocation=[peopleLocation[random.randint(0,numberOfPeople-1)]]
#Initially, we just set the number of time steps to 1. You can change this
for timeStep in range(7000):
#Vaccinate a random person every 3rd timeStep
if timeStep%3 == 0: vaccinate(); print timeStep
#Generate New Coordinates ie make everyone move
peopleLocation=generateNewLocation(peopleLocation)
zombieLocation=generateNewLocation(zombieLocation)
vaccLocation=generateNewLocation(vaccLocation)
#print "Step one\n\nLocation of all people:", peopleLocation, "\n\n"
#Check if anyone is infected
checkInfected(peopleLocation, zombieLocation)
#Stop the movement of time when there are no non infected people
if len(peopleLocation) == 1:
print "Time to infected:", timeStep
break
#Plotting the points on a scatter plot
#Comment out to let program run much faster
# plott.show()#
# plotting(1)#
print len(peopleLocation),"*****************"
print peopleLocation,
|
spam = ["apples", "bananas", "tofu", "cats"]
def return_string(spam):
desired_string = ''
for item in range(len(spam)):
if item == 0:
desired_string = desired_string + spam[item]
continue
elif item == (len(spam)-1):
desired_string = desired_string + " and " + spam[item]
continue
desired_string = desired_string + " , " + spam[item]
return desired_string
print(return_string(spam))
|
shopping_list_3 = []
def show_help():
print("\n Separate each item with comma ")
print("Type DONE when finish adding the list, Type SHOW to see the current list, Type HELP to see this message")
def show_list():
count = 1
for item in shopping_list_3:
print("\n {} : {}".format(count, item ))
count+= 1
print("Enter list of item you want to add to shopping cart")
show_help()
while True:
new_suff = input("Item : > ")
if new_suff == "DONE":
print("\n Here is your list")
show_list()
break
elif new_suff == "SHOW":
print("\n Here is your list till now")
show_list()
continue
elif new_suff == "HELP":
show_help()
continue
else:
actual_list = new_suff.split(",")
index = input("Enter a spot to add a list to a particular position, or Enter to add it at the end of list.")
if index:
try:
spot = int(index) - 1
for item in actual_list:
shopping_list_3.insert(spot, item.strip())
except ValueError:
print("please enter integer")
else:
for item in actual_list:
shopping_list_3.append(item.strip())
|
''' Give a list
remove vowel from each item in the list, untill we get exception
print out the list without vowel, with first alphabet in each word capital
'''
words = ['hello', 'ronak', 'ray', 'jaanu']
vowel = list('aeiou')
output=[]
for item in words:
name = list(item.lower())
for vw in vowel:
while True:
try:
name.remove(vw)
except:
break
output.append("".join(name).capitalize())
print(output)
|
def word_count(sentence):
s_lower = sentence.lower()
list_of_words = s_lower.split()
word_dict={}
for ch in list_of_words:
if ch in word_dict:
word_dict[ch] = word_dict[ch] + 1
else:
word_dict[ch] = 1
return word_dict
print(word_count("I AM awesome I really am I really really I"))
|
# Rui Ma V00800795
# Nannan Zhang V00809956
# The reference we used is according to this video: https://www.youtube.com/watch?v=qNdqS9t5fXc
# We changed the image color, size, and added other seven itmes:
# three flowers, a sun and its lights, a red mouth, and the drawing speed.
# In order to save marker's time, we promote the drawing speed to the max.
# If you want to examine the code,
# you can adjust the drawing speed in the "head" method
# The most difficult thing about this program is calculating points.
# This purpose of this statement is importing the turtle library
from turtle import*
# Main method conclude other class and methods
# Under the main method are other methods called by the main method
# The other methods are the components of the image
def main():
pu()
pd()
head()
shell()
feet()
tail()
# sun, three flowers, mouth are the extra components we added
sun()
flower1()
flower2()
flower3()
mouth()
done()
# It is the first part of the image
# The function of head method is drawing a turtle head
# The comments in this method represent the same meaning in the following method
# So we will not mark every comment
def head():
# speed means drawing speed, the range of speed is from int 0 to 10
# 10 indicates max, 0 indicates min
speed(10)
# pu means pen up
pu()
# set point, then move pen to the point position of (150,50)
goto(150,50)
# pd means pen down
pd()
# set three atributes of pen, we changed the fill color and pen color
pen(fillcolor='green yellow', pencolor='greenyellow', pensize=5)
pd()
# start to fill in color
begin_fill()
# move 90 degree to the right direction
right(90)
# draw a circle of 200 degrees clockwise with 100 as a diameter
circle(100,-200)
# move 100 degree to the left direction
left(100)
# go forward with distance of 50
fd(50)
right(180)
fd(35)
right(145)
fd(110)
right(30)
fd(70)
# set point, then move pen to the point position
goto(150,50)
# stop fill in color
end_fill()
# start to call eye method as followed
eye()
# It is the second part of the image, we changed eye color from white into black
def eye():
pen(fillcolor='black',pencolor='black',pensize=5)
begin_fill()
right(165)
pu()
fd(150)
pd()
# draw a circle with 5 as a radius
circle(5)
end_fill()
# It is the third part of the image
def shell():
pu()
goto(150,50)
# we changed shell color
pen(fillcolor='burlywood', pencolor='saddlebrown', pensize=5)
pd()
begin_fill()
left(95)
circle(250,170)
left(86)
fd(510)
goto(150,50)
end_fill()
shell_arrangement()
# This method concluded in the previous method
# In order to eliminate redundancy
# Python often use nest structure
def shell_arrangement():
pu()
goto(-300,30)
pd()
# The following commands are for loop
# The output is the figures of the turtle shell
# The loop will loop for 8 times
# There are 6 situations
for i in range(8):
# The first situation is that when i less than 3,
# there will be two figures
if i < 3:
# Here calls another method
# It is still nest loop
# First, when calles the nest loop
# The python code will jump into the nest loop
shell_pattern()
# When the nest loop finished
# The python code will come back,
# and continue to compile the following command
pu()
right(136)
fd(110)
pd()
# When i = 3, there is another figure
elif i==3:
shell_pattern()
pu()
right(25)
fd(90)
right(90)
pd()
# When i = 4, there is another figure
elif i==4:
shell_pattern()
pu()
right(6)
fd(120)
right(120)
pd()
# When i = 5, there is another figure
elif i==5:
shell_pattern()
pu()
left(30)
fd(60)
pd()
# When i = 6, there is another figure
elif i==6:
shell_pattern()
pu()
fd(40)
pd()
# When i is not less than 3, and not equal to 3 or 4 or 5 or 6
# The python code will come into the else situation
else:
shell_pattern()
# This part represent the shape of the shell
def shell_pattern():
left(40)
fd(50)
right(45)
fd(40)
right(70)
fd(40)
right(70)
fd(40)
right(40)
fd(30)
right(38)
fd(38)
# This part shows the four feet of the turtle
def feet():
# we changed the feet color
pen(fillcolor='greenyellow',pencolor='saddlebrown',pensize=5)
pu()
goto(-250,-20)
right(207)
pd()
feet2()
right(90)
pu()
fd(380)
right(90)
pd()
feet2()
pu()
right(90)
fd(120)
right(90)
fd(18)
right(360)
pd()
feet1()
pu()
right(180)
fd(280)
right(270)
pd()
feet1()
# This method represents the outer feet
# Also, the method here uses nesting structure
def feet1():
begin_fill()
for i in range (3):
fd(50)
right(90)
end_fill()
# This method represents the inner feet
def feet2():
begin_fill()
fd(80)
right(90)
fd(50)
right(90)
fd(80)
end_fill()
# This method represents the tail of the turtle
def tail():
pu()
goto(-340,20)
right(210)
pd()
begin_fill()
fd(40)
right(150)
fd(40)
end_fill()
ht()
# This method shows the sun and lights in the sky
# This method is the extra component we added
def sun():
pu()
goto(400, 200)
pd()
pen(fillcolor='yellow', pencolor='red', pensize=5)
begin_fill()
circle(70)
end_fill()
pu()
goto(400, 175)
pd()
pen(fillcolor='red', pencolor='red', pensize=3)
begin_fill()
right(90)
fd(35)
end_fill()
pu()
goto(320,200)
pd()
pen(fillcolor='red', pencolor='red', pensize=3)
begin_fill()
right(45)
fd(35)
end_fill()
pu()
goto(480, 200)
pd()
pen(fillcolor='red', pencolor='red', pensize=3)
begin_fill()
left(90)
fd(35)
end_fill()
# This method represents the first flower on the ground
# This method is the extra component we added
def flower1():
pu()
goto(-300, -200)
pd()
pen(fillcolor='yellow', pencolor='dodgerblue', pensize=5)
begin_fill()
right(30)
fd(20)
right(60)
fd(20)
right(60)
fd(20)
right(60)
fd(20)
right(60)
fd(20)
right(60)
fd(20)
right(60)
fd(20)
end_fill()
pu()
goto(-311, -235)
pd()
pen(fillcolor='greenyellow', pencolor='greenyellow', pensize=5)
begin_fill()
right(17)
fd(30)
end_fill()
pu()
goto(-311, -265)
pd()
pen(fillcolor='greenyellow', pencolor='greenyellow', pensize=5)
begin_fill()
right(135)
fd(25)
end_fill()
pu()
goto(-311, -265)
pd()
pen(fillcolor='greenyellow', pencolor='greenyellow', pensize=5)
begin_fill()
right(90)
fd(25)
end_fill()
# This method represents the second flower on the ground
# This method is the extra component we added
def flower2():
pu()
goto(-200, -150)
pd()
pen(fillcolor='red', pencolor='yellow', pensize=5)
begin_fill()
right(30)
fd(30)
right(60)
fd(30)
right(60)
fd(30)
right(60)
fd(30)
right(60)
fd(30)
right(60)
fd(30)
right(60)
fd(30)
end_fill()
pu()
goto(-180, -200)
pd()
pen(fillcolor='greenyellow', pencolor='greenyellow', pensize=5)
begin_fill()
right(102)
fd(40)
end_fill()
pu()
goto(-180, -240)
pd()
pen(fillcolor='greenyellow', pencolor='greenyellow', pensize=5)
begin_fill()
right(135)
fd(25)
end_fill()
pu()
goto(-180, -240)
pd()
pen(fillcolor='greenyellow', pencolor='greenyellow', pensize=5)
begin_fill()
right(100)
fd(25)
end_fill()
# This method represents the third flower on the ground
# This method is the extra component we added
def flower3():
pu()
goto(-90, -165)
pd()
pen(fillcolor='deeppink', pencolor='deepskyblue', pensize=5)
begin_fill()
right(30)
fd(30)
right(60)
fd(30)
right(60)
fd(30)
right(60)
fd(30)
right(60)
fd(30)
right(60)
fd(30)
right(60)
fd(30)
end_fill()
pu()
goto(-70, -220)
pd()
pen(fillcolor='greenyellow', pencolor='greenyellow', pensize=5)
begin_fill()
right(102)
fd(40)
end_fill()
pu()
goto(-70, -260)
pd()
pen(fillcolor='greenyellow', pencolor='greenyellow', pensize=5)
begin_fill()
right(135)
fd(25)
end_fill()
pu()
goto(-70, -260)
pd()
pen(fillcolor='greenyellow', pencolor='greenyellow', pensize=5)
begin_fill()
right(100)
fd(25)
end_fill()
# The output of this part is the red mouth of the turtle
# This method is the extra component we added
def mouth():
pu()
goto(343,15)
pd()
pen(fillcolor='red', pencolor='red', pensize=5)
begin_fill()
left(135)
fd(10)
end_fill()
# Recalling main method is to ensure the whole program can be compiled
main()
|
def encrypt(text, rot):
new_text = ""
for character in text:
new_text += rotate_character(character, rot)
return new_text
def alphabet_position(letter):
lc_alphabet = "abcdefghijklmnopqrstuvwxyz"
uc_alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in range(len(lc_alphabet)):
if letter == lc_alphabet[i]:
return i
for i in range(len(uc_alphabet)):
if letter == uc_alphabet[i]:
return i
def rotate_character(char, rot):
lc_alphabet = "abcdefghijklmnopqrstuvwxyz"
uc_alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
upper = False
if char in uc_alphabet:
upper = True
#check if char is alpha
if char.isalpha():
#get index of char
idx = alphabet_position(char)
#rotate index rot times
idx += rot
while idx > 25:
idx = idx % 26
if upper:
return uc_alphabet[idx]
else:
return lc_alphabet[idx]
else:
return char
|
from random import randint
'''
Игра в кости. Компьютер загадывает два числа от 1 до 6(кидает кости).
Дальше кидает игрок. Так же кидает кости, если 1 - полностью совпадают - выйгрыш.
2 - если одна цифра сопадает,
3 - сумма цифр совпадает.
данные: бросок компьютера,
бросок игрока,
тип игры.
методы: определение цифр компьютера.
игра
определение выйгрыша.
'''
class Dice:
def __init__(self, number_throw=1, type_game=1):
self.computer_throw = []
self.human_throw = []
self.amount = number_throw
self.type = type_game
def define_computer(self):
self.computer_throw = (randint(1, 6), randint(1, 6))
def winner(self):
if self.type == 1:
return set(self.human_throw) == set(self.computer_throw)
elif self.type == 2:
return self.human_throw[0] in self.computer_throw or self.human_throw[1] in self.computer_throw
else:
return sum(self.computer_throw) == sum(self.human_throw)
def run(self):
self.define_computer()
for _ in range(self.amount):
self.human_throw = (randint(1, 6), randint(1, 6))
print(f'Выпало {self.human_throw}')
if self.winner():
print('You are winner!!!')
break
else:
print("No lucky")
print(f'У компьтера выпало - {self.computer_throw}')
temp = Dice(type_game=2, number_throw=5)
temp.run()
|
# KUniqueCharacters(str) take the str parameter being passed and find the longest substring that contains k unique characters, where k will be the first character from the string. The substring will start from the second position in the string because the first character will be the integer k. For example: if str is "2aabbacbaa" there are several substrings that all contain 2 unique characters, namely: ["aabba", "ac", "cb", "ba"], but your program should return "aabba" because it is the longest substring. If there are multiple longest substrings, then return the first substring encountered with the longest length. k will range from 1 to 6.
# Examples
# Input: "3aabacbebebe"
# Output: cbebebe
# Input: "2aabbcbbbadef"
# Output: bbcbbb
def IsValid(strParam, approprNumber):
chars = []
chars.append(strParam[0])
for character in strParam:
if character not in chars:
chars.append(character)
return approprNumber == len(chars)
def KUniqueCharacters(strParam):
lenght = int(strParam[0])
strParam = strParam[1::]
strings = []
for i in range(lenght, len(strParam) - lenght): # len of str for check
for j in range(0, len(strParam) - i + 1): # start str position
if IsValid(strParam[j:j + i:], lenght):
if len(strings) == 0:
strings.append(strParam[j:j + i:])
elif len(strings[0]) < len(strParam[j:j + i:]):
strings.clear()
strings.append(strParam[j:j + i:])
else :
strings.append(strParam[j:j + i:])
return strings[0]
# keep this function call here
print(KUniqueCharacters("2aabbacbaa"))
print(KUniqueCharacters("3aabacbebebe"))
|
# chapter 1 exercise 8
# solve the following in Field 31
# 3 / 24
# 17 ^ -3
# 4 ^ -4 * 11
print("3 / 24 = ")
print((3 * 24 **(31-2)) % 31)
#solving, using the faster way
print("3 / 24 = ")
print(3*pow(24,31-2,31) % 31)
print("17 ^ -3 = ")
print(pow(17,31-4,31))
print("4 ^ -4 * 11 = ")
print(pow(4,31-5,31)*11%31)
#solve the same problems, using ecc.py
from ecc import FieldElement
print("3 / 24 = ")
a = FieldElement(3,31)
b = FieldElement(24,31)
print(a/b)
print("17 ^ -3 = ")
b = FieldElement(17,31)
print(pow(b,-3))
print(b**(-3))
|
# Con la importación traemos las librerías que necesitamos a nuestro código.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math
import matplotlib.backends.backend_pdf
# Importamos los datos.
data=pd.read_csv(r"monthly_salary_brazil.csv")
# De la tabla que importamos desde el csv, obtenemos solo la columna del salario total.
salaries=data["total_salary"]
# Algunos valores de datos son inferiores a cero.
# Eso no tiene sentido ya que los salarios deben ser mayores que cero.
# Así que hacemos un corte de los datos.
real_salaries=salaries[salaries>0]
# Desde una gráfica de caja podemos visualizar que los datos están más concentrados antes de 5000.
# Por lo tanto, hacemos un corte en los datos para ver el comportamiento en esa región
soi=real_salaries[real_salaries<5000]
# Calculamos el número de clases para el histograma con la fórmula log (n) / log (2).
# Hacemos uso de la biblioteca de matemáticas (math).
number_of_classes=int(round(math.log(soi.size)/math.log(2)))
# Realizamos una gráfica del histograma.
# La función hist, devuelve tres matrices, que contienen las frecuencias de las clases,
# los contenedores de las clases y otra matriz que no es de nuestro interés.
# La matriz de bins contiene los límites de las clases.
freq,bins,patches=plt.hist(soi,bins=number_of_classes,edgecolor="black")
# Esta función simplemente limpia la trama.
# En realidad, la línea anterior era solo para obtener la frecuencia y los intervalos para nuestra tabla de frecuencias,
# por lo que podemos limpiar cualquier función que se haya trazado.
plt.cla()
# Podemos calcular las frecuencias relativas utilizando la fórmula:
# frecuencia relativa = frecuencia / número de datos
rel_freq=freq/soi.size
# Vamos a crear una serie de rango de clases.
# En primer lugar, lo dejamos vacío para que podamos agregar nuevos valores.
class_range=[]
# Crearemos una serie de clases superiores.
# En primer lugar, lo dejamos vacío para que podamos agregar nuevos valores.
upper_class=[]
# Vamos a crear una serie de clases medias.
# En primer lugar, lo dejamos vacío para que podamos agregar nuevos valores.
# Esta matriz contendrá la marca de clases que es solo el promedio de la clase superior e inferior.
middle_class=[]
# Recorremos todos los elementos de la matriz de bins que contiene los límites de las clases.
# Agregamos los valores correspondientes a las matrices.
for i in range(int(bins.size)-1):
lower=bins[1]
upper=bins[i+1]
upper_class.append(upper)
middle_class.append((upper+lower)/2)
# En el aviso de rango de clase que estamos agregando una cadena
# Esa cadena será "inferior-superior", con el signo "+", solo le decimos a Python que se una a las cadenas.
# La función de agregar inserta un nuevo valor al final de la matriz.
# Entonces, como puede observar, comenzamos con una matriz vacía y luego agregamos un valor cada vez.
# Entonces, podemos pensar así con el siguiente ejemplo:
# Entra en el bucle class_range = [] (vacío), luego agrega class_range = [0-10]
# ingresa una vez más en el loop y agrega una vez más class_range = [0-10,10-20] y así sucesivamente.
class_range.append("{:0.2f}".format(lower)+"-"+"{:0.2f}".format(upper))
# Histograma de frecuencia acumulativa.
# La función hist devuelve tres matrices.
# Las matrices trash1 y trash2 son solo matrices que no utilizaremos.
# Sin embargo, ya que estamos interesados en las frecuencias acumulativas, debemos recibir las tres matrices si queremos a ""cum freq"".
cumfreq,trash1,trash2=plt.hist(soi,bins=number_of_classes,edgecolor="black",cumulative=True)
# Creamos una tabla de datos con columnas "Frecuencia", "Frecuencia relativa", "Marca de clase" ...
# Estas columnas contendrán los vectores correspondientes freq, real freq, ...
Table=pd.DataFrame({"Frequency":freq,"Relative Frequency":rel_freq,"Mark of Class":middle_class, "Cumulative Frequency":cumfreq},index=class_range)
# Hacemos que la pantalla de salida solo tenga 2 decimales.
pd.set_option('precision',2)
# Imprimimos la tabla (el marco de datos).
print(Table)
# Ojive
# Note que usamos plot y no hist o cualquier otro método de ploteado usado antes.
# La función de trazado en realidad traza los puntos (x, y) de dos matrices en los ejes "y" y "x".
# Entonces, en este caso, en los valores del eje x serán los valores de upper_class y en los valores del eje y será el cumfreq.
# Así que tenemos tuplas (upper_class, cumfreq).
# El 'go-' está indicando a la función de trazado que cree el trazado con "líneas verdes" y que une los valores de los puntos con o.
# Así que si escribes 'rx-', la línea sería roja, conectada con cruces
plt.plot(upper_class,cumfreq,'go-')
# Guardamos todas las figuras en un pdf.
# Creamos el archivo con el nombre "output.pdf"
pdf=matplotlib.backends.backend_pdf.PdfPages("output.pdf")
# Convertir tabla a archivo de Excel.
# Hacemos que el marco de datos se guarde también como archivo de excel
Table.to_excel("FrecuenciesTable.xlsx",float_format="%.2f")
# Agregar figura
# Creamos una figura en pulgadas.
# El primer número en la figura es el ancho y el segundo es la altura de la figura.
# Una figura es el cuadro completo donde puede agregar tantas gráficas como desee,
# así que usaremos la función add_subplot para agregar una nueva gráfica
figure=plt.figure(figsize=(8,30))
# Número de gráficas.
n=7
# Histograma de frecuencia
# Cada figura tiene divisiones.
#Añadimos nuestra primera subdivision.
# Observe que la n indica el número de filas,
# el número 1 en la segunda ranura es el número de columnas.
# Finalmente, el tercer número con 1, indica el índice de la división que estamos creando.
ax=figure.add_subplot(n,1,1)
freq,bins,patches=ax.hist(soi,bins=number_of_classes,edgecolor="black",color="green")
# Histograma de frecuencia acumulativa
ax=figure.add_subplot(n,1,2)
cum_freq,trash,trash=ax.hist(soi,bins=number_of_classes,edgecolor="black",cumulative=True)
# Histograma de frecuencia relativa acumulativa
# Con las siguientes dos líneas de código creamos una matriz con números [1/n,1/n,...,1/n].
# En primer lugar, con la función "np.zeros(soi.size)"
# le estamos diciendo a python que cree una matriz de "size soi.size" llena de ceros.
# Luego, con "zeros_vector+1/soi.size" en cada ranura, sumamos "1/n",
# donde "n" es el número de datos, obtenidos con "soi.size"
zeros_vector=np.zeros(soi.size)
w_array=zeros_vector+1/soi.size
ax=figure.add_subplot(n,1,3)
# Cuando llamamos a ponderaciones = w_array le estamos diciendo a la función "Para cada uno de los datos, den cierto peso de conteo".
# Por ejemplo, para la matriz de datos [1,2,3,4]...la matriz de ponderaciones con ponderaciones
# [3,7,9,10] diría a la función contar el número "1"-> como 3 veces, el valor "2" lo cuenta como 7 veces
# y así sucesivamente y así sucesivamente.
# Observa que pasamos una matriz con números [1/n,1/n,1/n,1/n,1/n,1/n,1/n,1/n,....] donde n es el numero de datos.
# Entonces estamos contando cada valor "1/n".
# Esa es la definición de la frecuencia relativa.
cum_rel_freq,trash1,trash2=ax.hist(soi,bins=number_of_classes,edgecolor="black",cumulative=True,weights=w_array,color="orange")
plt.title("Most Common Brazilian People Salaries")
plt.xlabel("Salaries")
plt.ylabel("Number of People")
# Frecuencias acumulativas de Ogive.
ax=figure.add_subplot(n,1,4)
plt.title("Ogive Most Common Brazilian People Salaries")
ax.plot(upper_class,cum_freq,'ro-')
# Boxplot.
# Diagrama de caja (observe que este cuadro de caja es de TODOS los datos,
# no solo los datos recortados 0 <salarios <5000).
ax=figure.add_subplot(n,1,5)
ax.boxplot(salaries,vert=False)
# Ogive Frecuencias Relativas Acumulativas.
ax=figure.add_subplot(n,1,6)
ax.plot(upper_class,cum_rel_freq,'go-')
# Polígono de frecuencias.
R_class=bins[1]-bins[0]
mcfp=middle_class
print(middle_class[-1])
print(R_class)
mcfp.insert(int(len(middle_class)),middle_class[-1]+R_class)
mcfp.insert(0,middle_class[0]-R_class)
# Frecuencias para polígono.
ffp=freq.tolist()
ffp.append(0)
ffp.insert(0,0)
ax=figure.add_subplot(n,1,7)
ax.plot(mcfp,ffp,"-ro")
# Guardando la primera figura en un pdf-
pdf.savefig(figure)
# Guardando la primera figura en un archivo png plt.savefig ("test1.png").
# Creando la segunda figura para algunos otros gráficos
# (Los gráficos circulares).
figure2=plt.figure(figsize=(20,20))
# Esta línea de código creará una tabla con los valores del sector de columna de la tabla de datos.
# Esa columna, como se puede observar, si abre el archivo de Excel contiene todos los "nombres de trabajos".
# Así obtendrá una tabla con los trabajos y la cantidad de veces que el trabajo se repite en la columna o la frecuencia del trabajo.
# Podemos lograr esto con la función hermosa y sorprendente .value_counts ().
# Verificará los valores repetidos en cierta columna, los contará y le devolverá la tabla.
# Así por ejemplo. Imagina que tienes los siguientes datos en el sector columna:
# Ingeniero
# Abogado
# Profesor
# Artista
# Ingeniero
# Abogado
# Ingeniero
# Policía
# Ingeniero
# con sector_counts volvería
# Ingeniero 4
# Abogado 2
# Profesor 1
# Artista 1
# Policía 1
sector_counts= data["sector"].value_counts()
print(sector_counts)
# Dividir los datos en tres conjuntos diferentes, para que podamos visualizar los datos en los gráficos circulares.
# La primera división
alljobs_final=sector_counts[sector_counts>=2000]
# El segundo conjunto, solo aquellos valores por debajo de 2000 y mayores de 150 (el segundo corte en las siguientes líneas).
# El resto está contenido como "Very Unlikely Jobs".
less_common_sect=sector_counts[sector_counts<2000]
# Very unlikely jobs. Solo aquellos por debajo de 150.
very_unlikely_jobs=less_common_sect[less_common_sect<150]
# Segundo corte aplicado a less_common_sect.
less_common_sect=less_common_sect[less_common_sect>150]
# Necesitamos incluir los trabajos menos comunes a todos los trabajos
# por lo que hay que crear otro objeto pandas.
other=pd.Series([less_common_sect.sum()],index=["Less Common Jobs"])
alljobs_final=alljobs_final.append(other)
# Necesitamos incluir los valores muy poco probables en el campo común,
# entonces creamos otro objeto pandas
vul=pd.Series([very_unlikely_jobs.sum()],index=["Very Unlikely Jobs"])
# Añadimos los valores muy poco probables.
less_common_sect=less_common_sect.append(vul)
# Creamos matrices de etiquetas. Los labels serán los nombres de los trabajos.
# Se almacenan en nuestros índices de los arrays.
# También agregamos a las etiquetas el porcentaje de cada trabajo.
alabels_final=[alljobs_final.index[i] +" "+"{:0.3f}".format(alljobs_final[i]/data["sector"].size*100) + "%" for i in range (alljobs_final.size)]
alabels_lscommon=[less_common_sect.index[i] +" "+ "{:0.3f}".format(less_common_sect[i]/data["sector"].size*100) + "%" for i in range (less_common_sect.size)]
alabels_vul=[very_unlikely_jobs.index[i] +" "+ "{:0.4f}".format(very_unlikely_jobs[i]/data["sector"].size*100)+ "%" for i in range (very_unlikely_jobs.size)]
# Esto creará el mapa de colores.
# Visite https://matplotlib.org/examples/color/colormaps_reference.html,
# para ver la nomenclatura de diferentes colores.
cmap=plt.get_cmap('RdYlBu')
acolors=[cmap(i) for i in np.linspace(0,1,8)]
# Esto creará una matriz que le dirá a la grafica cómo compensar las etiquetas y las porciones de la misma.
explode_1=np.zeros(alljobs_final.size)
for i in range (1,10):
explode_1[-i]=2.5-i*0.13
explode_2=np.zeros(less_common_sect.size)
for i in range (1,22):
explode_2[-i]=3-i*0.13
explode_3=np.zeros(very_unlikely_jobs.size)
explode_3[-1]=4
explode_3[-2]=2.8
explode_3[-3]=1.6
explode_3[-4]=0.4
# Añadimos la primer grafica de pastel
ax2=figure2.add_subplot(3,1,1)
ax2.set_title("All Jobs",x=-0.2,fontsize=25)
ax2.pie(alljobs_final,colors=acolors,
labels=alabels_final,explode=explode_1,rotatelabels=True)
# Añadimos la segunda grafica de pastel
ax2=figure2.add_subplot(3,1,2)
# Dando un título a la trama.
ax2.set_title("Less Common Jobs ",x=1.7,fontsize=25)
ax2.pie(less_common_sect,colors=acolors,labels=alabels_lscommon,explode=explode_2, rotatelabels=True)
# Añadimos la tercer grafica de pastel
ax2=figure2.add_subplot(3,1,3)
ax2.set_title("Very Unlikely Jobs ",x=1.7,fontsize=25)
ax2.pie(very_unlikely_jobs,colors=acolors,
labels=alabels_vul,explode=explode_3,rotatelabels=True)
print(very_unlikely_jobs)
# Ajustar el espacio entre plots.
plt.subplots_adjust(hspace=0.8)
# Guardamos en el pdf lo que hemos hecho en la segunda figura
# pdf.savefig (figura 2)
pdf.savefig(figure2)
#Cerramos el pdf. Si no escribimos este comando, no podremos abrir nuestro archivo pdf.
pdf.close()
|
class node():
def __init__(self, data=None, nextN = None):
self.data = data
self.nextN = nextN
class linkedHash():
def __init__(self):
self.head = node()
self.size = 0
self.tabela = [self.head]*10
def funcaoHash(self,data):
return data%10
def findNum(self,data):
self.key = self.funcaoHash(data)
atual = self.tabela[self.key]
while atual.nextN != None:
if atual.nextN.data == data:
return True
atual = atual.nextN
return False
def insert(self, data):
self.key = self.funcaoHash(data)
if self.findNum(data):
print("Esse elemento já está na tabela")
return
atual = self.tabela[self.key]
while atual.nextN != None:
atual = atual.nextN
atual.nextN = node(data)
def remove(self,data):
self.key = self.funcaoHash(data)
if self.findNum(data) == False:
print("Esse elemento não está na tabela")
return
atual = self.tabela[self.key]
while atual.nextN != None:
if atual.nextN.data == data:
if atual.nextN.nextN == None:
atual.nextN = None
else:
atual.nextN = atual.nextN.nextN
|
import time
import datetime
print("Current date and time: " , datetime.datetime.now())
print("Current year: ", datetime.date.today().strftime("%Y"))
print("Month of year: ", datetime.date.today().strftime("%B"))
print("Week number of the year: ", datetime.date.today().strftime("%W"))
print("Weekday of the week: ", datetime.date.today().strftime("%w"))
print("Day of year: ", datetime.date.today().strftime("%j"))
print("Day of the month : ", datetime.date.today().strftime("%d"))
print("Day of week: ", datetime.date.today().strftime("%A"))
from datetime import datetime
#string to datetime format
date_object = datetime.strptime('Jul 1 2014 2:43PM', '%b %d %Y %I:%M%p')
print(date_object)
|
def dimCheck():
try:
print("st1")
print("st1")
#return 10
# '''(except only execute when try block have some error code)'''
except TypeError : #( must be child of next excepts)
print("st1")
print("st1")
return 21
except Exception : #( must be parent of previous excepts)
print("st1")
print("st1")
return 22
# '''(else only execute when try block executed successfully)'''
else:
print("st1")
print("st1")
return 30
# '''(anyway finally we definately execute even try execute successfully or not)'''
finally:
print("st1")
print("st1")
return 40
return 50
'''
check return scenario with concepts by commenting the return statement
'''
|
'''
Database
'''
'''
**************************** Dataabse Connectivity with sqlite3
'''
import sqlite3
try:
db = sqlite3.connect('pythondb')
cursor = db.cursor()
#cursor.execute(''' create table users (name text, email text, username text, password text, password text) ''')
cursor.execute('''select * from users ''')
except Exception as E:
print(E)
else:
for row in cursor.fetchall():
print(row)
finally:
db.close()
|
'''
print(values objects,seperator, end, file, buffer)
'''
print(1,2,3) #1 2 3
print('Eknayth', 123, 'hiii', 1234) #Eknayth 123 hiii 1234
print('Eknayth', 123, 'hiii', 1234,sep='__', end='$$$') #Eknayth__123__hiii__1234$$$
a=5
print("The Value is : ", a) #The Value is : 5
b=10
c="Hiii"
print("The Value is: %d and the second value is: %d and the string is %s" %(a,b,c))
#The Value is: 5 and the second value is: 10 and the string is Hiii
print("The Value is: {} and the second value is: {} and the string is {}".format(a,b,c))
#The Value is: 5 and the second value is: 10 and the string is Hiii
print("The Value is: {2} and the second value is: {1} and the string is {0}".format(a,b,c))
#The Value is: Hiii and the second value is: 10 and the string is 5
print("The Value is: {val1} and the second value is: {val2} and the string is {str1}".format(val1=a,val2=b,str1=c))
#The Value is: 5 and the second value is: 10 and the string is Hiii
x=1234.1234567
print("The Value of x is %f"%x)
#The Value of x is 1234.123457
print("The Value of x is %1.1f"%x)
#The Value of x is 1234.1
print("The Value of x is %2.2f"%x)
#The Value of x is 1234.12
print("The Value of x is %3.3f"%x)
#The Value of x is 1234.123
s1 = "ABCD"
s1.find('B')
|
'''
Database
'''
'''
**************************** Dataabse Connectivity with sqlite3
'''
import sqlite3
try:
db = sqlite3.connect('pythondb')
cursor = db.cursor()
# cursor.execute(''' create table users (name text, email text, username text, password text) ''')
cursor.execute('''select * from person ''')
except Exception as E:
print(E)
else:
for row in cursor.fetchall():
print(row)
finally:
db.close()
conn = sqlite3.connect('example.db')
c = conn.cursor()
"""
c.execute('''
CREATE TABLE person
(id INTEGER PRIMARY KEY ASC, name varchar(250) NOT NULL)
''')
c.execute('''
CREATE TABLE address
(id INTEGER PRIMARY KEY ASC, street_name varchar(250), street_number varchar(250),
post_code varchar(250) NOT NULL, person_id INTEGER NOT NULL,
FOREIGN KEY(person_id) REFERENCES person(id))
''')
c.execute('''
INSERT INTO person VALUES(2, 'pythoncentral')
''')
c.execute('''
INSERT INTO address VALUES(2, 'python road', '1', '00000', 1)
''')
"""
conn.commit()
conn.close()
|
"""This problem was asked by Amazon.
Write a function that takes a natural number as input
and returns the number of digits the input has.
Constraint: don't use any loops.
"""
# idea: use the log of ten
import numpy as np
def number_of_digit(x):
return np.floor(np.log10(x,10)) + 1
|
"""This problem was asked by Google.
Given a list of integers S and a target number k, write a function
that returns a subset of S that adds up to k. If such a subset cannot
be made, then return null.
Integers can appear more than once in the list. You may assume
all numbers in the list are positive.
For example, given S = [12, 1, 61, 5, 9, 2] and k = 24, return [12, 9, 2, 1] since it
sums up to 24.
"""
# function to filter element smaller than k.
def subset_sum(nums, k):
if k == 0:
return []
if not nums and k != 0:
return None
nums_copy = nums[:]
last = nums_copy.pop()
with_last = subset_sum(nums_copy, k - last)
without_last = subset_sum(nums_copy, k)
if with_last is not None:
return with_last + [last]
if without_last is not None:
return without_last
subset_sum([12, 1, 61, 5, 9, 2] , 24)
|
#Import files
import os
import csv
csvpath = os.path.join('..''Resources', 'budget_data.csv')
with open (csvpath, newline = '') as csvfile:
csvreader = csv.reader(csvfile, delimiter = ',')
print(csvreader)
#Create Lists
num_months = []
net_PL_total = []
PL_change = []
Average_Change = []
#Use Next function to skip over csv header labels
csv_header = next(csvreader)
#Ensure each row is read as a row
for row in csvreader:
num_months.append(row[0])
net_PL_total.append(row[1])
Total_Profit_Losses = sum(net_PL_total)
#Total num_months
print (len(num_months))
#Total Amount of Profit/Losses over period
#Get monthly change in profits through iteration
for i in range (len(net_PL_total)-1):
PL_change.append (net_PL_total[i+1] - net_PL_total[i])
#Greatest Profit Increase and Greatest Profit Decrease
max_profit_increase = max(PL_change)
max_profit_decrease = min (PL_change)
x = PL_change.index(max(PL_change)) + 1
y = PL_change.index(min(PL_change)) + 1
Average_Change = {round(sum(PL_change)/len(PL_change),2)}
print ("Financial Records Analysis")
print (f'-----------------------------' + '\n')
print ("Total Number of Months:" + str(len(num_months)))
print ("Total Profit/Losses:" + str(int(Total_Profit_Losses)))
print("Average Change" + "$" + str(int[Average_Change]))
print(f"Greatest Increase in Profits: {num_months[x]} (${(str(x))})")
print(f"Greatest Decrease in Profits: {num_months[y]} (${(str(y))})")
|
# Data Science Programming Assignment 2 : decision tree
# author : Seonha Park
# written in Python3
import DecisionTree
import TreeNode
import sys
#get label which has largest value. to estimate non-leaf ended entry
def getMaxLabel(parent_attr, this_attr, root_attr):
max_array = []
max_val = 0
#find largest number label
for k , v in this_attr["num"].items():
if v > max_val:
max_array = []
max_array.append(k)
max_val = v
elif v == max_val:
max_array.append(k)
#if two or more label has same value, find parent node's largest label
if len(max_array) > 1:
parent_max = 0
parent_array = []
for k, v in parent_attr["num"].items():
if v > parent_max:
parent_array = []
parent_array.append(k)
parent_max = v
elif v == parent_max:
parent_array.append(k)
#if two or more label has same value in parent node, find root node's largest label
if len(parent_array) > 1:
root_array = []
root_val = 0
for k, v in root_attr["num"].items():
if v > root_val:
root_array = []
root_array.append(k)
root_val = v
elif v == root_val:
root_array.append(k)
return root_array[0]
else :
return parent_array[0]
else:
return max_array[0]
def main():
# get training file, test file and output file's name from command line argument
train_file = sys.argv[1]
test_file = sys.argv[2]
output_file = sys.argv[3]
# get training file and make list of columns
with open(train_file) as f:
train_data = f.readlines()
train_data = [d.strip() for d in train_data]
# make train_data string to attribute list and get each attribute name and total number of columns
attribute_list = []
total_attribute = 0
for line in train_data:
each_line = line.split("\t")
attribute_list.append(each_line)
total_attribute += 1
attribute_name = attribute_list[0]
attribute_list.pop(0)
total_attribute -= 1
possible_name = {}
# get possible classes
for i in range(len(attribute_name)):
ith_class = []
for attr in attribute_list:
if attr[i] not in ith_class:
ith_class.append(attr[i])
possible_name[attribute_name[i]] = ith_class
# get decision class's label and generate tree
decision_label = attribute_name[len(attribute_name) - 1]
tree = DecisionTree.GenerateTree(attribute_list, attribute_name)
# get test input from test file
with open(test_file) as f:
test_input = f.readlines()
test_input = [d.strip() for d in test_input]
test_input.pop(0)
test_data = [[]]
for line in test_input:
test_data.append(line.split("\t"))
test_data.remove([])
# predict decision class and write in output file
f = open(output_file,"w")
del attribute_name[attribute_name.index(decision_label)]
for name in attribute_name:
f.write(name + "\t")
f.write(decision_label+"\n")
for entry in test_data:
# call decision tree
tempDict = tree.copy()
parentDict = tempDict
rootDict = tree.copy()
rootDict = rootDict[list(rootDict.keys())[0]]
result = ""
# trace tree while the answer is found or tree is end
while isinstance(tempDict, dict):
root = TreeNode.TreeNode(list(tempDict.keys())[0], tempDict[list(tempDict.keys())[0]])
tempDict = tempDict[list(tempDict.keys())[0]]
index = attribute_name.index(root.value)
value = entry[index]
if (value in list(tempDict.keys())):
child = TreeNode.TreeNode(value, tempDict[value])
result = tempDict[value]
parentDict = tempDict
tempDict = tempDict[value]
# can't find the entry in tree, follow majority vote
else:
result = getMaxLabel(parentDict, tempDict,rootDict)
break
for i in entry:
f.write(i+"\t")
f.write(result+"\n")
f.close()
if __name__ == '__main__':
main()
|
import numpy as np
from analysis.helpers.convolve import apply_filter
def run(image_data):
"""
Applies a Sobel filter across an image. This is essentially moving a small matrix across every pixel in the image
and calculating the gradient of the pixel's neighbors. The returned value is an image of the same size where
each pixel value represents that gradient value (averaged for each color channel... e.g. R, G, B).
:return:
"""
horizontal_kernel = np.array([[1, 0, -1],
[1, 0, -1],
[1, 0, -1]])
vertical_kernel = np.array([[-1, -1, -1],
[0, 0, 0],
[1, 1, 1]])
analyzed_image = np.zeros(image_data.shape, dtype=image_data.dtype)
for color in range(image_data.shape[2]):
horizontal_image = apply_filter(image_data[:, :, color], horizontal_kernel)
vertical_image = apply_filter(image_data[:, :, color], vertical_kernel)
distance = np.sqrt(horizontal_image ** 2 + vertical_image ** 2, dtype=np.float)
analyzed_image[:, :, color] = distance / np.max(distance) * 255
return analyzed_image
|
class Polygon:
def perimeter(self):
pass
def area(self):
pass
class Rectangle(Polygon):
def __init__(self, width, height):
self.width = width
self.height = height
def perimeter(self):
return (self.width + self.height) * 2
def area(self):
return self.width * self.height
class Square(Polygon):
def __init__(self, side):
self.side = side
def perimeter(self):
return self.side * 4
def area(self):
return self.side * self.side
|
# coding=utf-8
import random
import re
class Node:
def __init__(self, data=None, value=None):
self.data = data
self.value = value
self.left = None
self.right = None
def compare(self, a, b):
# 比较函数:
# a<b,返回负数
# a>b,返回正数
# a=b,返回0
#
return a - b
def insert(self, data, value):
# print '#self.data =', self.data
if self.data is None:
self.data = data
self.value = value
else:
if data < self.data:
if self.left is None:
self.left = Node(data, value)
else:
self.left.insert(data, value)
elif data > self.data:
if self.right is None:
self.right = Node(data, value)
else:
self.right.insert(data, value)
else:
self.value = value
# else:
# self.data = data
def lookup(self, data, parent=None):
if data < self.data:
if self.left is None:
return None, None
else:
return self.left.lookup(data, self)
elif data > self.data:
if self.right is None:
return None, None
else:
return self.right.lookup(data, self)
else:
return self, parent
def delete(self, data):
node, parent = self.lookup(data)
# print '#43 node = ', node.data, ' parent=', parent.data
if node is None:
# print data, 'not found'
return None
else:
cnt_child = node.children_count()
# print '#49 cnt_child=', cnt_child
if cnt_child == 0:
if parent:
if parent.left is node:
parent.left = None
else:
parent.right = None
else:
# 没有parent,是根节点
# 根节点没有child,又要被删除,所以整个tree就都为空了
node.data = None
# self.left = None
# self.right = None
elif cnt_child == 1:
if node.left:
n = node.left
else:
n = node.right
if parent:
if parent.left is node:
parent.left = n
else:
parent.right = n
else:
# 根节点处理, 只有一个child,那么这个child就成为新的根节点,要把所有的东西复制过去
node.data = n.data
node.left = n.left
node.right = n.right
elif cnt_child == 2:
son_left = node.left
son_right = node.right
# print '#81 node = ', node.data, 'left =', son_left.data, ' right = ', son_right.data
# 随机选左侧处理(左节点先上,右节点接到左节点的max处)或右侧处理(右节点先上,左节点接到右节点的min处)
if random.choice(['min', 'max']) == 'min':
# if 1:
son_right.min().left = son_left
son_priority = son_right
# print '84# son_priority = ', son_priority.data
else:
son_left.max().right = son_right
son_priority = son_left
if parent:
# print '90# parent = ', parent.data
if parent.left is node:
parent.left = son_priority
else:
parent.right = son_priority
else:
# 根节点
node.data = son_priority.data
node.left = son_priority.left
node.right = son_priority.right
def min(self):
n = self
while n.left:
n = n.left
return n
def max(self):
n = self
while n.right:
n = n.right
return n
def children_count(self):
cnt = 0
if self.left:
cnt += 1
if self.right:
cnt += 1
return cnt
def print_tree(self):
if self.left:
self.left.print_tree()
if self.data is not None:
print "{%s:%s}" % (self.data, self.value)
if self.right:
self.right.print_tree()
# root = Node(8)
# root.insert(3)
# root.insert(10)
# root.insert(1)
# root.insert(6)
# root.insert(4)
# root.insert(7)
# root.insert(14)
# root.insert(13)
# node, parent = root.lookup(11)
# print node
# print parent
# print root.print_tree()
# root.delete(3)
# print root.print_tree()
def gen_rand_arr(arrSize=99, arrMin=0, arrMax=100):
arr = []
for i in range(arrSize):
item = {}
item['data'] = random.randrange(arrMin, arrMax + 1)
item['value'] = 'I am ' + str(item['data'])
arr.append(item)
return arr
# return [random.randrange(arrMin, arrMax + 1) for i in range(arrSize)]
# print gen_rand_arr()
arr = gen_rand_arr(10, 0, 20)
print arr
# for n in arr:
# print n,
# print ''
# arr = [0, 8, 3, 10, 1, 6, 4, 7, 14, 13]
root = Node()
for item in arr:
print 'insert ', item['data'], item['value']
root.insert(item['data'], item['value'])
root.print_tree()
print '-' * 100
# 词频统计
twocity = """
It was the best of times, it was the worst of times,
it was the age of wisdom, it was the age of foolishness,
it was the epoch of belief, it was the epoch of incredulity,
it was the season of Light, it was the season of Darkness,
it was the spring of hope, it was the winter of despair,
we had everything before us, we had nothing before us,
we were all going direct to Heaven, we were all going direct
the other way--in short, the period was so far like the present
period, that some of its noisiest authorities insisted on its
being received, for good or for evil, in the superlative degree
of comparison only.
"""
twocity_arr = re.split(r'\W+', twocity)
freq_tree = Node()
for key in twocity_arr:
key = key.lower()
node, parent = freq_tree.lookup(key)
if node is None:
freq_tree.insert(key, 1)
else:
freq_tree.insert(key, node.value + 1)
freq_tree.print_tree()
|
#Reina Irizarry
# This program will do the following:
'''Repeatedly ask the user for numbers until they enter a 0 or negative.
For each number they enter, the program will report if the number was even or odd,
whether it is a perfect square, the sum of the squares of the numbers up to
and including the number, and the sum of the digits in the number'''
import math
print()
print("************************** Number Analyzer ***************************")
print(" This program is designed to help my ten year old school sister")
print("with math exercises. She will first enter in a number and the program")
print("will determine if it is odd or even. Then determine if it is a perfect ")
print("square, sum of the perfect square and lastly, the sum of the digits.")
print("**********************************************************************")
print()
#This section determines if it is odd or even
num = int(input("Enter a number (0 or negative to quit): "))
while num >0:
if num == "q":
break
if num %2 == 0:
print("The number is even.")
else:
print("The number is odd.")
#This section will determine if it is a perfect square
if math.sqrt(num) == round(math.sqrt(num)):
print("The number is a perfect square.")
else:
print("The number is not a perfect square.")
#The section will add the the square roots
addition = 0
for i in range(num+1):
addition = addition + math.pow (i,2)
print("The sum of the first %d squares is %d" % (num,addition))
#This section counts the sum of the digits.
factorial = 1
for i in range(num):
factorial = factorial * (i + 1)
print("The factorial of %d is %d" % (num,factorial))
#This section will determine the sum of the digits.
num=num
sum_digits=0
while(num>0):
integer=num%10
sum_digits=sum_digits+integer
num=num//10
print("The sum of digits is",sum_digits)
num = int(input("Enter a number (0 or negative to quit): "))
|
"""You can use this class to represent how classy someone
or something is.
"Classy" is interchangable with "fancy".
If you add fancy-looking items, you will increase
your "classiness".
Create a function in "Classy" that takes a string as
input and adds it to the "items" list.
Another method should calculate the "classiness"
value based on the items.
The following items have classiness points associated
with them:
"tophat" = 2
"bowtie" = 4
"monocle" = 5
Everything else has 0 points.
Use the test cases below to guide you!"""
class Classy(object):
def __init__(self):
self.items = []
def addItem( self, item_name ):
self.items.append( item_name )
def getClassiness( self ):
point = 0
for x in self.items:
if x == "tophat":
point += 2
elif x == "bowtie":
point += 4
elif x == "monocle":
point += 5
return point
# Test cases
me = Classy()
# Should be 0
print( me.getClassiness() )
me.addItem("tophat")
# Should be 2
print( me.getClassiness() )
me.addItem("bowtie")
me.addItem("jacket")
me.addItem("monocle")
# Should be 11
print( me.getClassiness() )
me.addItem("bowtie")
# Should be 15
print( me.getClassiness() )
|
import requests
print("Bem-vindo ao verificador de sites 1.0!")
print("Nenhum direito reservado.")
print("")
ficar = "s"
while ficar == "s":
print("")
urls = input("Insira as URLs dos sites que deseja verificar o status. (Separados por virgula :")
print("")
url_arr = [lista.strip() for lista in urls.split(',')]
for i in url_arr:
if "." in (i[-4:]):
if (i[:7]) == "http://":
url_request = i
else:
i = "http://" + str(i)
url_request = i
r_url_request = requests.get(url_request)
c_request = r_url_request.status_code
if c_request >= 200 and c_request <= 200:
status =" Sucesso"
else:
status = "falha"
print (url_request + " " + status)
else:
print("URL inválido")
ficar =" "
while ficar not in ["s","n"]:
ficar = input("Deseja verificar mais algum site? s/n :")
if ficar == "n":
print("Programa encerrado")
break
elif ficar == "s":
continue
else:
print("Opção inválida")
|
n = int(input("Введите n: "))
i = 0
n1 = n
while n1 != 0:
n1 = n1 // 10
i += 1
sum = n + (10 ** i) * n + n + (100 ** i) * n + (10 ** i) * n + n
print(f"n+nn+nnn = {sum}.")
|
# 🚨 Don't change the code below 👇
age = input("What is your current age? ")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
age_as_int = int(age)
years_remaining = 90 - age_as_int
days_remaining = years_remaining * 365
weeks_remaining = years_remaining * 52
months_remaining = years_remaining * 12
message = f"You have {days_remaining} days, {weeks_remaining} weeks, and {months_remaining} months left."
print(message)
#My Code
# age_as_int = int(age)
# days = (90 * 365) - (age_as_int * 365)
# weeks = (90 * 52) - (age_as_int * 52)
# months = (90 * 12) - (age_as_int * 12)
# print(f"You have {days} days, {weeks} weeks, and {months} months left.")
|
3 + 5
7 - 4
3 * 2
6 / 3
2 ** 3
print(3 * (3 + 3) / 3 - 3)
# PEMDASLR
# ()
# **
# * /
# + -
# PEMDAS
# Parentheses
# Exponenets
# Multiplication
# Division
# Addition
# Subtraction
# pint(2 ** 2)
# print(2 ** 3)
# print(6 / 3)
# print(type(6/3))
|
# -*- coding: utf-8 -*-
# Python的正则使用
import re
def main():
str1 = 'j1k234k11234kl1423'
# findall 使用较多
numsPattern = re.compile(r'\d{3,8}$')
nums = numsPattern.findall(str1)
print nums
# match
print re.match('^j', str1)
def matchDomain(str):
domain = ''
return domain
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
# str slice
# 从索引0开始取,直到索引3为止,
# 但不包括索引3。即索引0,1,2,正好是3个元素。
L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack', 'Funk', 'Zara']
print len(L)
print L[0:3]
print L[:3]
print L[1:3]
print L[2:3]
print '支持倒数的截取'
print L[-1]
print L[-2:]
print L[-2:-1]
print '#########################'
M = range(100)
print M
print M[:10]
print M[-10:]
print M[10:20]
print '前10个 每两个取一次'
print M[:10:2]
#[0, 2, 4, 6, 8]
print 'all numbers get per 5'
print M[::5]
print 'copy the list'
print M[:]
print '#########################'
# tuple 和 string 也可以像上面一样操作
s = 'asdkaad8798asd79asdjnm1b3mn1b3iu'
print s[:], s[::5]
tu = (12,3,4,5234,123,12,124,5)
print tu[:], tu[::2]
|
import itertools
import pandas as pd
import numpy as np
import warnings
# Function to take a value and a set of values to transform form a multicoding to a multiple single codings.
def conversion(value, value_set):
single_codes = -99
possible_value = -99
i = 0
running = True
while(running):
i += 1
for p in itertools.combinations(value_set, i):
# codes are the sum of each value as an exponent of 2.
# Here we take the set of possible codes, and check combinations to match the original code.
# when the original code is matched, we return the combination of codes which create the combination.
possible_value = np.power(2, p).sum()
if(possible_value == value):
running = False
single_codes = p
break
# We know there are max. 3 codings in the dataset, therefore, if we can't find a combination of codes
# in the set that match the value, then the code must be incorrect.
if(i == 5):
single_codes = (float("NaN"),)
running = False
warnings.warn("WARNING: An impossible value has been found")
break
return single_codes
|
from collections import deque
def solution(priorities, location):
answer = 0
dq = deque(zip(range(len(priorities)), priorities))
prior_list = sorted(priorities)
while dq:
loc, prior = dq.popleft()
if prior_list[-1] > prior:
dq.append((loc, prior))
continue
# 인쇄가능하다면
prior_list.pop()
answer += 1
if loc == location:
return answer
return answer
|
from collections import deque
'''
풀이3 : 그래프 탐색
- 양방향 네트워크
- 1번 컴퓨터가 2, 3번과 연결되어 있다면
- 2, 3번 컴퓨터와 다른 컴퓨터의 연결 상태를 탐색하고 각각 방문 처리
- 탐색이 종료되면 네트워크 카운트 +1
'''
def solution(n, computers):
visited = [False]* n
def search(x, y):
q = deque([(x, y)])
while q:
x, y = q.popleft() # x, y = q.pop()을 해도 결과는 동일
visited[y] = True
for i in range(n):
if computers[y][i] == 1 and visited[i] == False:
q.append((y, i))
# 재방문하지 않을 것이므로 방문한 컴퓨터는 연결을 끊어두기
computers[y][i] = 0
answer = 0
for i in range(n):
for j in range(n):
# 위에서 연결을 끊어둔 컴퓨터 때문에 네트워크 카운트 시 중복이 일어나지 않음
if computers[i][j] == 1:
search(i, j)
answer += 1
return answer
'''
TEST CASES
# n = 3
# computers = [[1, 1, 0], [1, 1, 0], [0, 0, 1]] # return 2
# computers = [[1, 1, 0], [1, 1, 1], [0, 1, 1]] # return 1
# n = 4
# computers = [[1, 1, 0, 1], [1, 1, 0, 0], [0, 0, 1, 1], [1, 0, 1, 1]] # return 1
'''
'''
풀이2 : BFS
- testcase는 다 통과하지만
- 채점 결과 2, 5번만 정답
'''
'''
def solution(n, computers):
visited = [ [False] * n for _ in range(n)]
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]
def bfs(x, y, computers, visited):
q = deque([(x, y)])
while q :
x, y = q.popleft()
visited[x][y] = True
for d in range(len(dx)):
nx = x + dx[d]
ny = y + dy[d]
if 0 <= nx < n and 0 <= ny < len(computers):
if visited[nx][ny] == False and computers[nx][ny] == 1:
visited[nx][ny] = True
q.append((nx, ny))
return
answer = 0
for i in range(n):
for j in range(n):
if computers[i][j] == 1 and visited[i][j] == False:
bfs(i, j, computers, visited)
answer += 1
return answer
'''
'''
풀이1 : DFS
- 그래프 연결이 끊길 때 네트워크 개수 +1
- 섬의 개수 세기 문제와 동일?
- 채점 결과 2, 5번만 정답
'''
'''
def solution(n, computers):
# 시계 방향으로 회전
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]
answer = 0 # network count
visited = [ [False]* n for _ in range(len(computers)) ]
def dfs(x, y):
visited[x][y] = True
for d in range(len(dx)):
nx = x + dx[d]
ny = y + dy[d]
# if nx < 0 or ny < 0 or nx >= n or ny >= len(computers):
# continue
if 0 <= nx < n and 0 <= ny < len(computers):
if visited[nx][ny] == False and computers[nx][ny] == 1:
dfs(nx, ny)
return
for i in range(n):
for j in range(len(computers)):
if visited[i][j] == False and computers[i][j] == 1:
dfs(i, j)
answer += 1
return answer
'''
|
l=[1,2,3,4,5,6,7]
print(type(l))
l=[1,2,2.3,4.5,'h','hello',[1,2,3]]
print(l)
print(type(l))
t=(1,2,3,4)
print(type(t))
s={1,2,3,4,5,6,7}
print(type(s))
print(s)
s={1,1,1,2,2,3,3,3,3}
print(s)
d={
'FirstName':'Janhavi',
'LastName':'Nandish',
'Contact':100,
101:'Ambulance'
}
print(type(d))
print(d)
|
print("enter the number")
x=int(input())
if x>0:
print("it is positive")
elif x<0:
print("it is negetive")
else:
print("it is zero")
|
n=input()
for i in n:
if i==i.upper():
print(i.lower(),end=' ')
elif i==i.lower():
print(i.upper(),end=' ')
else:
print(i)
|
#explicit type conversion
n1=150
print("the data type of n1:",type(n1))
n2="100"
print("the data type of n2:",type(n2))
print("*****************************")
n3=n1+int(n2)
print("the data type of n3:",type(n3))
print("*****************************")
|
#sum of even and odd num
num=[2,22,27,29,35,42,8,75,88]
sume=0
sumo=0
for i in num:
if i%2==0:
sume=sume+i
else:
sumo=sumo+i
print("sum of even",sume)
print("sum of odd",sumo)
|
def add(a,b):
print(f"相加{a}+{b}")
return a+b
def subtract(a,b):
print(f"相减{a}-{b}")
return a-b
def multiply(a,b):
print(f"相乘{a}*{b}")
return a*b
def divide(a,b):
print(f"相除{a}/{b}")
return a/b
print("函数做一些简单的计算")
age = add(30,5)
height = subtract(78,4)
weight = multiply(90,2)
iq = divide(100,2)
print(f"年龄:{age},身高:{height},体重:{weight},iq:{iq}")
what = add(age,subtract(height,multiply(weight,divide(iq,2))))
print("变成",what)
|
print("你今年多大了",end='')
age = input()
print("你现在多高",end="")
tall = input()
print('你现在体重多少',end="")
weight = input()
print(f"所以你的年龄是{age},身高是{tall},体重是{weight}")
print("用input写的另一段")
print("这是一个猜数字游戏")
number = input("请输入初始数字:")
numbers = input("请输入你猜的数字:")
if number < numbers:
print("大了")
elif number > numbers:
print("小了")
elif number == numbers:
print("恭喜您猜对了!!")
|
print("这是加法+ 100+100=",100+100)
print("这是减号- 200-100=",200-100)
print("这是除号/ 100/5=",100/5)
#除号下面计算出结果后会有一个浮点数
print("这是乘号* 100*100=",100*100)
print("这是余数的号码% 100%16=",100%16)
#%是计算余数的符号例如100%16的余数就是4
print("3+2 > 5-7",3+2 > 5-7)
print("3+2 < 5-7",3+2 < 5-7)
print("3+4 >= 4+7",3+4 >= 4+7)
print("3+4 <= 4+7",3+4 <= 4+7)
print("等号要打两个等号== 1==2",1==2)
print("等号要打两个等号== 2==2",2==2)
print("以上条件如果成立的话会返回一个布尔值 True如果不成立就会返回一个False")
#以上条件如果成立的话会返回一个布尔值 True如果不成立就会返回一个False
#如果字符串里面需要出现字符串以外的内容需要用英文逗号隔开
|
#print squares of these numbers
di = {0:0, 1:1, 2:2, 3:3, 4:4}
for i in di:
print i*i
squares = {x:x*x for x in range(5)} #dict comprehension with range
print squares
squares = {x:x*x for x in di} # dict comprehension with dict
print squares
'''
print ODD squares
'''
odd_squares = {x:x*x for x in range(11) if x%2==1}
print odd_squares
odd_squares = {x:x*x for x in di if x%2 == 1}
print odd_squares
'''
print only the vlaues of the keys
'''
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in squares:
print(squares[i])
keys = {'a', 'e', 'i', 'o', 'u' }
vowels = dict.fromkeys(keys)
print(vowels)
|
"""
Collections Module
The collections module is a built-in module that implements specialized container data types providing
alternatives to Pythons general purpose built-in containers. We've already gone over the basics: dict, list, set, and tuple.
Now we'll learn about the alternatives that the collections module provides.
"""
"""
Counter
Counter is a dict subclass which helps count hash-able objects. Inside of it elements are stored as dictionary keys and
the counts of the objects are stored as the value.
"""
from collections import Counter
l = [1,2,2,2,2,2,3,3,4,44]
print Counter(l)
print Counter('aabsbsbsbhshhbbsbs')
s = 'How many times does each word show up in this sentence word times each each word'
print Counter(s)
l = s.split()
c = Counter(l)
print c
print c.most_common()
print sum(c.values()) # total of all counts
print list(c) # list unique elements
print set(c) # convert to a set
print dict(c) # convert to a regular dictionary
print c.items() # convert to a list of (elem, cnt) pairs
print Counter(dict(c)) # convert from a list of (elem, cnt) pairs
print c.most_common()[:-1-1:-1] # n least common elements
c += Counter() # remove zero and negative counts
print c
c.clear() # reset all counts
|
l = [{"Name": "Ramya", "DEPT": 1}, {"Name": "Raksha", "DEPT": 2}, {"Name":"Rashmi","DEPT":3}]
# for item in l:
# if item.keys() == "Name":
# print
# res = l[0].keys()
# res[1] = "Fullname"
# print res
res = l[0]
res["Fullname"] = res["Name"]
print res
del res["Name"]
print res
print
|
a = 1
b = (1,2,3)
print id(a)
print id(b)
a=b #shallow copy, copies memry loc, a & b will be pointing to same loc
print id(a)
print id(b)
a = b[::] #deep copy, copies only value not the memory. Works for mutable objects
print id(a)
print id(b)
# >>> b = [2,3,5,6]
# >>> id(b)
# 4445651024
# >>> c = [4,5,6,7]
# >>> id(c)
# 4445687608
# >>> b = c[::]
# >>> id(c)
# 4445687608
# >>> id(b)
# 4445824424
|
"""
A defaultdict will never raise a KeyError. Any key that does not exist gets the value returned by the default factory.
"""
from collections import defaultdict
# d = defaultdict(object)
# d["key1"] = 1
# print d.get("key1")
# print d.get("key2")
d = {"key1":1}
print d.get("key2")
"""
OrderedDict
An OrderedDict is a dictionary subclass that remembers the order in which its contents are added.
"""
print 'Normal dictionary:'
d = {}
d['a'] = 'A'
d['b'] = 'B'
d['c'] = 'C'
d['d'] = 'D'
d['e'] = 'E'
for k, v in d.items():
print k, v
print "#######################"
#####################################
from collections import OrderedDict
d = OrderedDict()
d['a'] = 'A'
d['b'] = 'B'
d['c'] = 'C'
d['d'] = 'D'
d['e'] = 'E'
for k, v in d.items():
print k, v
"""
A regular dict looks at its contents when testing for equality. An OrderedDict also considers the order the items were added.
"""
print 'Dictionaries are equal? '
d1 = {}
d1['a'] = 'A'
d1['b'] = 'B'
d2 = {}
d2['b'] = 'B'
d2['a'] = 'A'
print d1 == d2
print "-----------------"
print 'Dictionaries are equal? '
d1 = collections.OrderedDict()
d1['a'] = 'A'
d1['b'] = 'B'
d2 = collections.OrderedDict()
d2['b'] = 'B'
d2['a'] = 'A'
print d1 == d2
|
l = [1,2,4,5,6,7]
# for i in range(len(l)):
# if i in l:
# # print i
# pass
# else:
# print "missing :",i
x = [i for i in range(7) if i in l]
print x
|
import sys
import os
import numpy as np
from scipy.stats import norm
import math
import random
import cv2
import run
def filter_median(image, k):
'''Filter the image using a median kernel.
Inputs:
image - a single channel image of shape (rows, cols)
k - the radius of the neighborhood you should use (positive integer)
Output:
output - a numpy array of shape (rows - 2k, cols - 2k) and the same dtype as
image.
Each cell in the output image should be filled with the median value of the
corresponding (2k+1, 2k+1) patch in the image.
'''
output = None
# Insert your code here.----------------------------------------------------
imageX = image.shape[0]
imageY = image.shape[1]
output = np.zeros((imageX-2*k, imageY-2*k), dtype=image.dtype)
for i in range(imageX):
for j in range(imageY):
thisarray = image[i:i+2*k+1, j:j+2*k+1]
if thisarray.shape[0] == 2*k+1 and thisarray.shape[1] == 2*k+1:
output[i,j] = np.median(thisarray)
#---------------------------------------------------------------------------
return output
def test():
'''This script will perform a unit test on your function, and provide useful
output.
'''
images = []
x = np.array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[ 10, 11, 12, 13, 14],
[ 15, 16, 17, 18, 19],
[ 20, 21, 22, 23, 24]], dtype = np.uint8)
images.append(x)
images.append(x)
x = np.array([[ 0, 1, 2, 3, 4, 5, 6],
[ 7, 8, 9, 10, 11, 12, 13],
[14, 15, 16, 17, 18, 19, 20],
[21, 22, 23, 24, 25, 26, 27],
[28, 29, 30, 31, 32, 33, 34],
[35, 36, 37, 38, 39, 40, 41],
[42, 43, 44, 45, 46, 47, 48]], dtype = np.uint8)
images.append(x)
images.append(x)
ks = [1, 2, 1, 2]
outputs = []
z = np.array([[ 6, 7, 8],
[11, 12, 13],
[16, 17, 18]], dtype=np.uint8)
outputs.append(z)
z = np.array([[12]], dtype=np.uint8)
outputs.append(z)
z = np.array([[ 8, 9, 10, 11, 12],
[15, 16, 17, 18, 19],
[22, 23, 24, 25, 26],
[29, 30, 31, 32, 33],
[36, 37, 38, 39, 40]], dtype=np.uint8)
outputs.append(z)
z = np.array([[16, 17, 18],
[23, 24, 25],
[30, 31, 32]], dtype=np.uint8)
outputs.append(z)
for image, k, output in zip(images, ks, outputs):
if __name__ == "__main__":
print "image:\n{}".format(image)
print "k:\n{}".format(k)
usr_out = filter_median(image, k)
if not type(usr_out) == type(output):
if __name__ == "__main__":
print "Error- output has type {}. Expected type is {}.".format(
type(usr_out), type(output))
return False
if not usr_out.shape == output.shape:
if __name__ == "__main__":
print "Error- output has shape {}. Expected shape is {}.".format(
usr_out.shape, output.shape)
return False
if not usr_out.dtype == output.dtype:
if __name__ == "__main__":
print "Error- output has dtype {}. Expected dtype is {}.".format(
usr_out.dtype, output.dtype)
return False
if not np.all(usr_out == output):
if __name__ == "__main__":
print "Error- output has value:\n{}\nExpected value:\n{}".format(
usr_out, output)
return False
if __name__ == "__main__":
print "Passed."
if __name__ == "__main__":
print "Success."
return True
if __name__ == "__main__":
# Testing code
print "Performing unit test."
test()
|
# shippig charge
weight_in_pounds = float( input('enter the amount of weight you want to ship '.title() ).strip() )
if weight_in_pounds <= 2 and weight_in_pounds > 0:
print('the shipping price is $ 1.5 '.title() )
elif weight_in_pounds <= 6 and weight_in_pounds > 2:
print('the shipping price is $ 3'.title() )
elif weight_in_pounds <= 10 and weight_in_pounds > 6:
print('the shipping price is $ 4'.title() )
else:
print('the shippig price is $ 4.75'.title() )
|
# user enter the amount of money in cent like one cent 2 cent ...
userpennies = float( input('enter the amount of pennies '.title() ).strip() )
# the amount of money in the type of 5 cent
useNrnickels = float( input('enter the amount of nrnickets '.title() ).strip() )
# the amount of money in type of 10 cents
useDimes = float( input('enter the amount of money in dimes type '.title() ).strip() )
# the amount of money in the type of quarters
userQuarters = float( input('enter the amount of money in the type of quarters '.title() ).strip() )
totalMoneyInDollar = ((userpennies * 1 ) + (useNrnickels * 5) + (useDimes * 10) + (userQuarters * 25)) / 100
if totalMoneyInDollar == 1 :
print('congritulation, you won!...'.title() )
else:
print('the amount you entered is maybe less or more than one dollar...'.title())
|
# 1. Number Analyser
# this program print powsitve the user input is greater than 0, otherwase print
# negative if the user input is less than zero else print ;zero' if the user input is zero
# the user input
userInput = float( input('enter a number '.title() ).strip().title() )
if userInput > 0:
print(f'the number {userInput:.2f} is a possitive number.... '.title())
elif userInput < 0:
print(f'the number {userInput:.2f} is a negative number.... '.title())
else:
print(f'the number {userInput:.2f} is \"zero\".....'.title() )
|
print("Hello World")
def insult(victim, verb, noun):
print("Hey {0}! You {1} like a {2}".format(victim, verb, noun))
insult("there", "code", "monkey")
# This is a comment, does not appear as output when running script
#Drawing a shape
print(" /|")
print(" / |")
print(" / |")
print(" /___|")
# Variables and Data Types
character_name = "Noah" # this is a string, storing plain text between quotation marks
character_age = "34.5"
is_male = True # Use True or False values
print("There once was a man named " + character_name + ",")
print("he was " + character_age + " years young.")
character_name = "David"
character_age = 52
print(character_name + " felt vibrant and healthy;")
print("he refused to accept the fact that he was actually " + str(character_age) + ".")
current_year = 2020 # This is a number value
print(str(current_year) + " was a character-building year!")
# Working with strings
phrase = "\"Calgary\"\nAlberta"
print(phrase + "\nis homebase")
country = "CanaDa, NorTH AMErica"
print(country.upper()) # Makes string ALL CAPS
print(country.islower()) # Checks lowercase of string and returns a True or False
print(country.upper().isupper()) # Converts to all uppercase, returning a True value
print(len(country)) # Length function counts number of characters in the string
print(phrase[0] + phrase[1] + phrase[2] + phrase[3] + phrase[4])
print("OTTAWA,ON".index("T")) # Index function passes a parameter to a numeric placement
airport = "YYC"
print(airport.replace("YYC", "YYZ")) # Replaces the name of airport
print(airport + " International Airport")
# Working with numbers
from math import *
print((78/1.35)+(100-2))
print(20 % 3) # Mod: first number divide by second number, gives the reminder left
license = -123456
print(abs(license)) # Absolute values
print("Here is my license number: " + str(abs(license)))
print(pow(2,5)) # First number to the power of second number
print(max(license,current_year)) # Higher value of the two
print(min(character_age,25)) # Lower value of the two
print(round(3.7)) # Round numbers to closest integer
print(floor(3.7)) # Removes decimals so lowest integer is left
print(ceil(3.14)) # Removes decimals rounding up to highest integer
a = sqrt(36)*exp(-0.05) # squareroot and exponential
b = log(2)*1e6 # log = natural logarithm and e = times 10^(value)
c = log10(2) # base10 logarithm
d = erf(1) # Error function at x, used to compute traditional statistical functions such as the cumulative standard normal distribution
e = tan(pi/4)*sin(pi/6)*cos(pi/3)
f = degrees(pi/2) # turns radians into degrees
g = radians(60) # turns degrees into radians
h = factorial(5) # returns the factorial of inserted value
print(h)
|
"""
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words,
add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.
Note:
The same word in the dictionary may be reused multiple times in the segmentation.
You may assume the dictionary does not contain duplicate words.
Example 1:
Input:
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
Output:
[
"cats and dog",
"cat sand dog"
]
Example 2:
Input:
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
Output:
[
"pine apple pen apple",
"pineapple pen apple",
"pine applepen apple"
]
Explanation: Note that you are allowed to reuse a dictionary word.
Example 3:
Input:
s = "catsandog"
wordDict = ["cats", "dog", "sand", "and", "cat"]
Output:
[]
"""
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
res = []
words = set(wordDict)
def checkWordBreak(s, words=words):
dp = [False for _ in range(len(s)+1)]
dp[0] = True
for i in range(len(s)):
for j in range(i+1, len(s)+1):
if s[i:j] in words and dp[i] == True:
dp[j] = True
return dp[-1]
def helper(s, words, curr):
if not checkWordBreak(s):
return
if len(s) == 0:
res.append(curr[:-1])
return
for j in range(1, len(s)+1):
if s[:j] in words:
helper(s[j:], words, curr+s[:j]+" ")
helper(s, words, "")
return res
# Very similar way, without using a string for curr (might improve complexity)
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
wordDict = set(wordDict)
def isWordBreak(s):
dp = [False for i in range(len(s)+1)]
dp[0] = True
for i in range(len(s)):
for j in range(len(s)+1):
if dp[i] and s[i:j] in wordDict:
dp[j] = True
return dp[-1]
res = []
def dfs(s, curr):
if not s:
res.append(' '.join(curr[:]))
return
if not isWordBreak(s):
return
for i in range(1, len(s)+1):
if s[:i] in wordDict:
curr.append(s[:i])
dfs(s[i:], curr)
curr.pop()
dfs(s, [])
return res
|
"""
Given an array of strings products and a string searchWord. We want to design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with the searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products.
Return list of lists of the suggested products after each character of searchWord is typed.
Example 1:
Input: products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse"
Output: [
["mobile","moneypot","monitor"],
["mobile","moneypot","monitor"],
["mouse","mousepad"],
["mouse","mousepad"],
["mouse","mousepad"]
]
Explanation: products sorted lexicographically = ["mobile","moneypot","monitor","mouse","mousepad"]
After typing m and mo all products match and we show user ["mobile","moneypot","monitor"]
After typing mou, mous and mouse the system suggests ["mouse","mousepad"]
Example 2:
Input: products = ["havana"], searchWord = "havana"
Output: [["havana"],["havana"],["havana"],["havana"],["havana"],["havana"]]
Example 3:
Input: products = ["bags","baggage","banner","box","cloths"], searchWord = "bags"
Output: [["baggage","bags","banner"],["baggage","bags","banner"],["baggage","bags"],["bags"]]
Example 4:
Input: products = ["havana"], searchWord = "tatiana"
Output: [[],[],[],[],[],[],[]]
Constraints:
1 <= products.length <= 1000
There are no repeated elements in products.
1 <= Σ products[i].length <= 2 * 10^4
All characters of products[i] are lower-case English letters.
1 <= searchWord.length <= 1000
All characters of searchWord are lower-case English letters.
"""
# The solution that I came up with, however I think the time complexity is too high
class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
res = []
def checkMatch(products, keyword):
res = []
len_key = len(keyword)
for product in products:
if keyword == product[:len_key]:
res.append(product)
res.sort()
return res if len(res) <= 3 else res[:3]
for i in range(1, len(searchWord)+1):
res.append(checkMatch(products, searchWord[:i]))
return res
# A better solution uses sorting and binary search
class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
# Sort the product list first
products.sort()
searchWord_len = len(searchWord)
res = [[] for _ in range(searchWord_len)]
curr = ""
for char in searchWord:
curr += char
# Find the index of insertion using binary search. This makes looking a bit faster
indexOfInsertion = self.binarySearch(products, curr)
for i in range(indexOfInsertion, min(len(products), indexOfInsertion+3)):
product = products[i]
array_pos = len(curr)-1
if len(res[array_pos]) < 3 and product.startswith(curr):
res[array_pos].append(product)
return res
def binarySearch(self, array, target):
lo = 0
hi = len(array)
while lo < hi:
mid = (lo+hi)//2
if array[mid] < target:
lo = mid+1
else:
hi = mid
return lo
|
size=4000000
mylist=[1];
def fibonancciList(n, k):
if k<=size:
mylist.append(k)
last=n+k
fibonancciList(k, last)
return mylist;
if __name__ == '__main__':
list=fibonancciList(1, 2)
sumt=0
for i in list:
if i%2==0:
sumt=sumt+i
print "\n",sumt
|
#SciCodeJam Problem
#Problem Week 1-A Divisibility Test
#Author Dennis Carnegie B
#function to find multiples of 7 and 11,
#and summing them up
def multipleSum(size):
sumt=0
for i in range(1, size):
if i%7==0 or i%11==0:
sumt=sumt+i
return sumt
#Main Function
def main():
print multipleSum(10000);
if __name__ == '__main__':
main()
|
#Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3000 (both included). The numbers obtained should be printed in a comma-separated sequence on a single line
for i in range(1999,3001):
if( (i%7 ==0) and (i%5 !=0)):
print i,","
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 12 09:48:17 2018
know sth about scipy
@author: tianbiaoyang
"""
from scipy import sparse
import numpy as np
# view the version
print('numpy version: {}'.format(np.__version__))
# get data
eye = np.eye(4)
print("\nNumPy array: \n{}".format(eye))
# using scipy to make sparse matrix
sparse_matrix = sparse.csr_matrix(eye)
print('\nSciPy spare CSR matrix:\n{}'.format(sparse_matrix))
eye_coo = sparse.coo_matrix(eye, (4, 4))
print('\nSciPy spare COO matrix:\n{}'.format(eye_coo))
|
# -*- coding: utf-8 -*-
#>>>>>python example for tuples including named ones
""""
What: basic tuple and named_tuple stuff
Status: draft, ok draft but possibly useful
Refs:
Notes:
can add more to this
you can slice
Search on:
named
collections
*args
"""
#A tuple is defined in the same way as a list, except that the whole set of elements is enclosed in parentheses instead of square brackets.
#2 The elements of a tuple have a defined order, just like a list. Tuples indices are zero-based, just like a list, so the first element of a non-empty tuple is always t[0].
#3 Negative indices count from the end of the tuple, just as with a list.
#4 Slicing works too, just like a list. Note that when you slice a list, you get a new list; when you slice a tuple, you get a new tuple.
import collections
# ---------------- helper function
def a_function( a, b, c ):
print( a )
print( b )
print( c )
# ==========================================================
def ex_star_args():
print( """
----------------ex_star_args() call like a_function( *args ) ---------------------------
""" )
args = ( 1, 2, 3)
a_function( *args ) # not * fixes what else would be error
#ex_star_args()
# ==========================================================
def ex_literal_tuples():
print( """
----------------------- ex_literal_tuples() ------------
""" )
print( ( 1,2,3 ) )
print( ( 1, ) )
print( ( 1 ) )
print ( ( ) )
print( ( 1,2,3 ) )
x = 1 # 1 is just a number
print( x )
x = 2, # watch out not a number but a tuple
print( x )
#ex_literal_tuples()
# ==========================================================
def ex_unpack():
print( """
----------------ex_unpack ---------------------------
""" )
args = ( 1, 2, 3)
a,b,c = args
print( a,b,c )
print( args[2], args[1], args[0], )
a_tuple = ( ["list_c_0", "list_0_1"], ["list_1_0", "list_1_1"] )
print( f"a_tuple[0] = {a_tuple[0]}" )
#ex_unpack()
# ==========================================================
def ex_named_tuples():
print( """\n\n
----------------------- ex_named_tuples() ------------
""" )
Person = collections.namedtuple( 'PersonTuple', 'name age gender')
print(( 'Type of Person:', type(Person) ))
bob = Person( name='Bob', age=30, gender='male' )
print( '\nRepresentation of bob:', bob )
jane = Person( name='Jane', age=29, gender='female' )
print( '\nField by name for jane.name:', jane.name )
print( '\nFields by index:' )
for p in [ bob, jane ]:
print( '%s is a %d year old %s' % p )
#ex_named_tuples()
# ==========================================================
def ex_named_tuples_dbader():
print( """\n\n
----------------------- ex_named_tuples_dbader() ------------
more at:
Writing Clean Python With Namedtuples – dbader.org
*>url https://dbader.org/blog/writing-clean-python-with-namedtuples
plus a few russ additions
""" )
# args collections.namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)
# Car = collections.namedtuple( 'color mileage') # missing firs arg
Car = collections.namedtuple('Car' , 'color mileage')
# # or
# Car = collections.namedtuple('Car', ['color', 'mileage'])
# collections.namedtuple('Car', ['color', 'mileage']) # name Car is not defined
# Car = collections.namedtuple( 'Boat', ['color', 'mileage']) # mismatch name seems to be use by str and repl
my_car = Car('red', 3812.4)
print( my_car.color )
print( my_car.mileage )
print( my_car )
# like functions with named args
my_car = Car( color = 'green', mileage = 3812.4 )
print( my_car )
# need not be in order
my_car = Car( mileage = 3812.4, color = 'blue', )
print( my_car )
print( f"my_car._asdict() >>{my_car._asdict()}<<" )
new_car = my_car._replace( color='blue' )
print( new_car )
#Lastly, the _make() classmethod can be used to create new instances of a namedtuple from a sequence or iterable:
newest_car = Car._make(['red', 999])
print( newest_car )
#ex_named_tuples_dbader()
# ===== might want to experiment with variations on this
# ------------- helper -------------------
def three_args( arg1, arg2, arg3, arg4 = 0):
ret = arg1 + arg2 + arg3 + arg4
print( ret )
return ret
# ==========================================================
def ex_un_pack_for_function():
print( """\n\n
----------------------- ex_un_pack_for_function() ------------
""" )
three_args( 1, 2, 3 ) # function call
unpack_me = ( 5, 6, 7 )
three_args( *unpack_me ) # function call
#ex_un_pack_for_function()
|
# Importing numpy library
import numpy as np
# Let a be an 2 x 2 array
a = np.array([(2,4),(3,4)], dtype = int)
# let b be an 2 x 2 array
b = np.array([(5,6),(2,6)], dtype = int)
print(a.sum())
# Array wise sum
# Output : 13
print(a.min())
# Array wise minimum value
# Output : 2
print(b.max(axis=0))
# Maximum value of an array row
# Output : [5 6]
print(b.cumsum(axis=0))
# Cumulative sum of the elements
# Output : [[ 5 6]
# [ 7 12]]
print(a.mean())
# Mean
# Output : 3.25
print(np.std(b))
# Standard Deviation
# Output : 1.6393596310755
# Thank You
|
# String Rotation: Assume you have amethod isSubstring which checks if one word is a
# substring of another. Given two strings, 51 and 52, write code to check if 52 is a
# rotation of 51 using only one call to isSubstring (e.g.,"waterbottle"is a rotation of"erbottlewat").
#O(1) space
def stringRotation(s1, s2):
for i in range(len(s1)): # O(n)
if s1 == s2[i:] + s2[:i]: # O(n)
return True
return False
result = stringRotation("waterbottle", "erbottlewat")
print(result)
|
class Fern:
def __init__(self, turtle):
self.turtle = turtle
turtle.left(90)
def createFern(self, size, sign):
if size < 1:
return
else:
self.turtle.forward(size)
self.turtle.right(70*sign)
self.createFern(size*0.5, -1*sign)
self.turtle.left(70*sign)
self.turtle.forward(size)
self.turtle.left(70*sign)
self.createFern(size*0.5, sign)
self.turtle.right(70*sign)
self.turtle.right(7*sign)
self.createFern(size-1, sign)
self.turtle.left(7*sign)
self.turtle.backward(size*2)
|
#!/usr/bin/env python3
import re
import pprint
read_chat_file = open("test_chat.txt", encoding="utf-8")
chat = read_chat_file.readlines()
frank = read_chat_file.readline()
# with open('tes.txt', 'r') as reader:
# pattern = re.compile("\d{1,2}/\d{1,2}/\d{1,2},\s\d{1,2}:\d{1,2}\s(A|P)M\s-\s\w+:")
# line = reader.readline()
# while line != '':
# if pattern.match(line):
# remove = re.sub(pattern,'', line) #remove the date for every line
# words = remove.lstrip()
# print(words, end='')
# line = reader.readline()
# else:
# # pattern.match(line) == line != True
# # print(words)
# print("not")
# line = reader.readline()
# for line in reader:
# with open('tes.txt', 'r') as reader:
# print(line, end=" ")
# print(chat)
def countwords(chat_read):
#exlcude_date = re.match("(\d{2}/{3}),\s", chat_read, re.I)
word_counter = 1
# for line in chat_read:
for i in range(len(chat_read)):
if(chat_read[i] == ' ' or chat_read == '\n' or chat_read == '\t'):
word_counter = word_counter + 1
return(word_counter)
def TTotalNumberOfMessages(chat_read):
message_counter = 0
pattern = re.compile("\d{1,2}/\d{1,2}/\d{1,2},\s")
for line in chat_read:
if pattern.match(line):
message_counter+=1
return(message_counter)
def DisplayChatWithIndex(chat,pattern):
index_display = 0
display_string = ''
for i in range(len(chat)):
if array_pattern.match(chat[i]):
remove = re.sub(pattern,'', chat[i]) #remove the date for every line
display_string += remove.lstrip()
index_display += 1
elif array_pattern.match(chat[i])!= chat[i]: #find a way to print the redundant arrat elements
#print(i ,"Not True")
#print(i, end= " ")
display_string += chat[i]
return display_string
# test = "11/29/19, 8:30 PM - Andile: Nno maaan...suthi you wil, you will Lana...hamba now"
# exclude_date = re.match("\d{1,2}/\d{1,2}/\d{1,2},\s\d{1,2}:\d{1,2}\s(A|P)M\s-\s\w+:", chat)
# reg_to_excl = exclude_date.group()
# excl = chat.strip(reg_to_excl)
# pattern = re.compile("\d{2}/")
def StripDateInLine(chat_read):
pattern = re.compile("\d{1,2}/\d{1,2}/\d{1,2},\s\d{1,2}:\d{1,2}\s(A|P)M\s-\s\w+:")
pp = pprint.PrettyPrinter(indent=3)
for line in chat_read:
if pattern.match(line):
remove = re.sub(pattern,'', line) #remove the date for every line
words = remove.lstrip()
pp.pprint(words)
def ReadAllTexts(chati):
array_pattern = re.compile("\d{1,2}/\d{1,2}/\d{1,2},\s\d{1,2}:\d{1,2}\s(A|P)M\s-\s\w+:")
index_display = 0
for i in range(len(chati)):
if array_pattern.match(chat[i]):
print(chati[i])
index_display += 1
elif array_pattern.match(chati[i])!= chati[i]:
print(chati[i])
# words = ReadAllTexts(chat)
#////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
array_pattern = re.compile("\d{1,2}/\d{1,2}/\d{1,2},\s\d{1,2}:\d{1,2}\s(A|P)M\s-\s\w+:")
print(DisplayChatWithIndex(chat,array_pattern))
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
"""""
SOLVING THE PROBLEM OF NOT PRINTING THE WHOLE TEXT, BECAUSE THE READLINE FUNCTION READS LINES AND TURNS THEN INTO ARRAY ELENEBTS
if the next element in the array doesn't natch the date pattern at the begigining
#concatinate the elements
#else move to the next line
"""""
"""""
Print the texts
TODO
"""""
# StripDateInLine(chat)
# print(the)
# print(chat)
# print(exclude_date.groups())
# print(countwords("Oh...was watching some movie..."))
read_chat_file.close()
|
transactions = [-100, 200, -50, 50, 40, -200, -10, 500, -30, -50]
total_expense = 0
# Your code begins
# for each transaction item
for ...:
# If the transaction amount is less than 0
if ...:
# Add the amount to total_expense
total_expense = ...
# Your code ends
print(f'Total expense: {total_expense}')
|
n = 10
result = 1
# Your code begins
# While n is larger than 0
while n > 0:
# Multiply result by n
result = result * n
# Decrease n by 1
n = n - 1
# Your code ends
print(result)
|
def chocolateFeast(n,c,m):
ccount = int(n/c)
wcount = ccount
while ( wcount >= m):
a = int((wcount)%(m))
wcount = int((wcount-a)/m)
ccount = ccount + wcount
wcount = a + wcount
print(ccount)
for _ in range(int(input())):
n,c,m = input().split()
chocolateFeast(int(n),int(c),int(m))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.