content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""
A pacman package builder.
.. moduleauthor:: James Reed <jcrd@tuta.io>
"""
| """
A pacman package builder.
.. moduleauthor:: James Reed <jcrd@tuta.io>
""" |
# Project Description located @ https://www.dumas.io/teaching/2021/fall/mcs260/nbview/projects/project3.html
# MCS 260 Fall 2021 Project 3
# Umar Chaudhry
# I completed this project completely with my own work and followed the project description to the best of my ability.
" Create functions that help analyze orbits/cycles "
def orbit(f,x0,n):
"""
Compute the first `n` terms of the orbit of `x0` under
the function `f`.
Arguments:
`f` - a function (should take one integer argument and return an integer)
`x0` - a value of the type that `f` accepts as its argument
`n` - the number of points to compute (a positive integer)
Returns:
A list of length `n` containing the values [ x0, f(x0), f(f(x0)), f(f(f(x0))), ... ]
"""
values = [x0]
for i in range(n-1):
values.append(f(x0))
# update 'x0' so the function can be applied repeatedly 'n' amount of times
x0 = f(x0)
return values
def orbit_data(f,x0):
"""
Repeatedly apply function `f` to initial value `x0` until some
value is seen twice. Return dictionary of data about the observed
behavior.
Arguments:
`f` - a function (should take one integer argument and return an integer)
`x0` - a value of the type that `f` accepts as its argument
Returns:
Dictionary with the following keys (after each key is a description of
the associated value):
"initial": The part of the orbit up to, but not including, the first
value that is ever repeated.
"cycle": The part of the orbit between the first and second instances of
the first value that appears twice, including the first but not the
second. In other words, the entire orbit consits of the "initial"
part followed by the "cycle" repeating over and over again.
Example: Suppose that applying f repeatedly to start value 11 gives this sequence:
11, 31, 12, 5, 6, 2, 8, 19, 17, 8, 19, 17, 8, 19, 17, 8, ...
Then the return value would be:
{
"initial":[11, 31, 12, 5, 6, 2],
"cycle": [8,19,17]
}
(If the orbit of `x0` doesn't end up in a cycle, it's ok for this function to run forever
trying to find one.)
"""
results = {}
# 'sequence' will be used to track output of 'f(x0)' called repeatedly on itself and
# determine the data under the "initial" and "cycle" keys of 'results'
sequence = [x0]
# 'seen' will be a boolean to test if a value in the output has been repeated
seen = False
# indice counter will be used to determine the indice in 'sequence' where
# a value has been repeated and use that information to find the 'initial' and 'cycle' keys
indice_counter = 0
while True:
# increment the indice at the start as 'sequence' already has one element
indice_counter += 1
# if a value has been repeated, the 'initial' and 'cycle' keys can be assigned to 'results'
if seen == True:
# assign all the values from the beginning of 'sequence' up until the indice where a cycle occurs
results["initial"] = sequence[:-(len(sequence[sequence.index(seen_value):(indice_counter+1)]))]
# assign all the values from where the first instance of the repeated value was mentioned up until when it was repeated
results["cycle"] = sequence[sequence.index(seen_value):indice_counter]
break
if f(x0) not in sequence:
sequence.append(f(x0))
else:
# still add repeated element to the list but make note of its indice by decreasing 'indice_counter'
# in order to have the correct indice of the repeated value in the next iteration of the while loop
sequence.append(f(x0))
# assign the repeated value of 'f(x0)' to 'seen_value' to use sequence.index() method in the next iteration
seen_value = f(x0)
# boolean triggers the condition of a repeated value
seen = True
indice_counter -= 1
# update 'x0' so the function can be applied repeatedly 'n' amount of times
x0 = f(x0)
return results
def eventual_period(f,x0):
"""
Determine the length of the periodic cycle that `x0` ends up in.
Arguments:
`f` - a function (should take one integer argument and return an integer)
`x0` - a value of the type that `f` accepts as its argument
Returns:
The length of the periodic cycle that the orbit of `x0` ends up in.
Example: Suppose that applying f repeatedly to start value 11 gives this sequence:
11, 31, 12, 5, 6, 2, 8, 19, 17, 8, 19, 17, 8, 19, 17, 8, ...
Then the return value of eventual_period(f,11) would be 3, since the periodic
cycle contains the 3 values 8,19,17.
(If the orbit of `x0` doesn't end up in a cycle, it's ok for this function to run forever
trying to find one.)
"""
data = orbit_data(f,x0)
return len(data["cycle"])
def steps_to_enter_cycle(f,x0):
"""
Determine the length of the intial part of the orbit of `x0` under `f` before
it enters a periodic cycle.
Arguments:
`f` - a function (should take one integer argument and return an integer)
`x0` - a value of the type that `f` accepts as its argument
Returns:
The number of elements of the orbit of `f` before the first value that
repeats.
Example: Suppose that applying f repeatedly to start value 11 gives this sequence:
11, 31, 12, 5, 6, 2, 8, 19, 17, 8, 19, 17, 8, 19, 17, 8, ...
Then the return value of steps_to_enter_cycle(f,11) would be 6, because there are 6
values in the intial segment of the orbit (i.e. 11, 31, 12, 5, 6, 2) which are followed by
a periodic cycle.
(If the orbit of `x0` doesn't end up in a cycle, it's ok for this function to run forever
trying to find one.)
"""
data = orbit_data(f,x0)
return len(data["initial"])
def eventual_cycle(f,x0):
"""
Return the periodic cycle that the orbit of x0 ends up in as a list.
Arguments:
`f` - a function (should take one integer argument and return an integer)
`x0` - a value of the type that `f` accepts as its argument
Returns:
The earliest segment from the orbit of `x0` under `f` that repeats
indefinitely thereafter, as a list.
Example: Suppose that applying f repeatedly to start value 11 gives this sequence:
11, 31, 12, 5, 6, 2, 8, 19, 17, 8, 19, 17, 8, 19, 17, 8, ...
Then eventual_cycle(f,x0) would return [8, 19, 17].
(If the orbit of `x0` doesn't end up in a cycle, it's ok for this function to run forever
trying to find one.)
"""
data = orbit_data(f,x0)
return data["cycle"]
def smallest_first(L):
"""
Rotates a list so that its smallest element appears first.
Arguments:
`L`: A list of integers, no two of them equal
Returns:
A list that is the result of moving the first element of `L` to the end,
repeatedly, until the first element of `L` is the smallest element of the list.
Example: smallest_first([46,41,28]) returns [28,46,41]
Example: smallest_first([4,2,1]) returns [1,4,2]
Example: smallest_first([9,8,7,6,5,4,3,2,1]) returns [1,9,8,7,6,5,4,3,2]
"""
while True:
if L[0] != min(L):
L.append(L[0])
L.remove(L[0])
elif L[0] == min(L):
break
return L
def find_cycles(f,start_vals):
"""
Find all the periodic cycles of the function `f` that appear when you consider
orbits of the elements of `start_vals`.
Arguments:
`f` - a function (should take one integer argument and return an integer)
`start_vals` - a list of integers to use as starting values
Returns:
A list of lists, consisting of all the periodic cycles that are seen
in the orbits of the start values from `start_vals`. Each cycle is
given with its smallest entry appearing first, and any given cycle
appears only once in the list.
e.g. If `mwdp` is the mean with digit power function, then find_cycles(mwdp,[65,66,67])
would return [ [28,46,41], [38,51] ] because both 65 and 67 end up in the [28,46,41]
cycle and 66 ends up in the [38,51] cycle.
"""
periodic_cycles = []
for value in start_vals:
data = orbit_data(f,value)
# use smallest_first() so a repeated cycle is not confused to be new and added to 'periodic cycles'
data = smallest_first(data["cycle"])
if data not in periodic_cycles:
periodic_cycles.append(data)
return periodic_cycles
| """ Create functions that help analyze orbits/cycles """
def orbit(f, x0, n):
"""
Compute the first `n` terms of the orbit of `x0` under
the function `f`.
Arguments:
`f` - a function (should take one integer argument and return an integer)
`x0` - a value of the type that `f` accepts as its argument
`n` - the number of points to compute (a positive integer)
Returns:
A list of length `n` containing the values [ x0, f(x0), f(f(x0)), f(f(f(x0))), ... ]
"""
values = [x0]
for i in range(n - 1):
values.append(f(x0))
x0 = f(x0)
return values
def orbit_data(f, x0):
"""
Repeatedly apply function `f` to initial value `x0` until some
value is seen twice. Return dictionary of data about the observed
behavior.
Arguments:
`f` - a function (should take one integer argument and return an integer)
`x0` - a value of the type that `f` accepts as its argument
Returns:
Dictionary with the following keys (after each key is a description of
the associated value):
"initial": The part of the orbit up to, but not including, the first
value that is ever repeated.
"cycle": The part of the orbit between the first and second instances of
the first value that appears twice, including the first but not the
second. In other words, the entire orbit consits of the "initial"
part followed by the "cycle" repeating over and over again.
Example: Suppose that applying f repeatedly to start value 11 gives this sequence:
11, 31, 12, 5, 6, 2, 8, 19, 17, 8, 19, 17, 8, 19, 17, 8, ...
Then the return value would be:
{
"initial":[11, 31, 12, 5, 6, 2],
"cycle": [8,19,17]
}
(If the orbit of `x0` doesn't end up in a cycle, it's ok for this function to run forever
trying to find one.)
"""
results = {}
sequence = [x0]
seen = False
indice_counter = 0
while True:
indice_counter += 1
if seen == True:
results['initial'] = sequence[:-len(sequence[sequence.index(seen_value):indice_counter + 1])]
results['cycle'] = sequence[sequence.index(seen_value):indice_counter]
break
if f(x0) not in sequence:
sequence.append(f(x0))
else:
sequence.append(f(x0))
seen_value = f(x0)
seen = True
indice_counter -= 1
x0 = f(x0)
return results
def eventual_period(f, x0):
"""
Determine the length of the periodic cycle that `x0` ends up in.
Arguments:
`f` - a function (should take one integer argument and return an integer)
`x0` - a value of the type that `f` accepts as its argument
Returns:
The length of the periodic cycle that the orbit of `x0` ends up in.
Example: Suppose that applying f repeatedly to start value 11 gives this sequence:
11, 31, 12, 5, 6, 2, 8, 19, 17, 8, 19, 17, 8, 19, 17, 8, ...
Then the return value of eventual_period(f,11) would be 3, since the periodic
cycle contains the 3 values 8,19,17.
(If the orbit of `x0` doesn't end up in a cycle, it's ok for this function to run forever
trying to find one.)
"""
data = orbit_data(f, x0)
return len(data['cycle'])
def steps_to_enter_cycle(f, x0):
"""
Determine the length of the intial part of the orbit of `x0` under `f` before
it enters a periodic cycle.
Arguments:
`f` - a function (should take one integer argument and return an integer)
`x0` - a value of the type that `f` accepts as its argument
Returns:
The number of elements of the orbit of `f` before the first value that
repeats.
Example: Suppose that applying f repeatedly to start value 11 gives this sequence:
11, 31, 12, 5, 6, 2, 8, 19, 17, 8, 19, 17, 8, 19, 17, 8, ...
Then the return value of steps_to_enter_cycle(f,11) would be 6, because there are 6
values in the intial segment of the orbit (i.e. 11, 31, 12, 5, 6, 2) which are followed by
a periodic cycle.
(If the orbit of `x0` doesn't end up in a cycle, it's ok for this function to run forever
trying to find one.)
"""
data = orbit_data(f, x0)
return len(data['initial'])
def eventual_cycle(f, x0):
"""
Return the periodic cycle that the orbit of x0 ends up in as a list.
Arguments:
`f` - a function (should take one integer argument and return an integer)
`x0` - a value of the type that `f` accepts as its argument
Returns:
The earliest segment from the orbit of `x0` under `f` that repeats
indefinitely thereafter, as a list.
Example: Suppose that applying f repeatedly to start value 11 gives this sequence:
11, 31, 12, 5, 6, 2, 8, 19, 17, 8, 19, 17, 8, 19, 17, 8, ...
Then eventual_cycle(f,x0) would return [8, 19, 17].
(If the orbit of `x0` doesn't end up in a cycle, it's ok for this function to run forever
trying to find one.)
"""
data = orbit_data(f, x0)
return data['cycle']
def smallest_first(L):
"""
Rotates a list so that its smallest element appears first.
Arguments:
`L`: A list of integers, no two of them equal
Returns:
A list that is the result of moving the first element of `L` to the end,
repeatedly, until the first element of `L` is the smallest element of the list.
Example: smallest_first([46,41,28]) returns [28,46,41]
Example: smallest_first([4,2,1]) returns [1,4,2]
Example: smallest_first([9,8,7,6,5,4,3,2,1]) returns [1,9,8,7,6,5,4,3,2]
"""
while True:
if L[0] != min(L):
L.append(L[0])
L.remove(L[0])
elif L[0] == min(L):
break
return L
def find_cycles(f, start_vals):
"""
Find all the periodic cycles of the function `f` that appear when you consider
orbits of the elements of `start_vals`.
Arguments:
`f` - a function (should take one integer argument and return an integer)
`start_vals` - a list of integers to use as starting values
Returns:
A list of lists, consisting of all the periodic cycles that are seen
in the orbits of the start values from `start_vals`. Each cycle is
given with its smallest entry appearing first, and any given cycle
appears only once in the list.
e.g. If `mwdp` is the mean with digit power function, then find_cycles(mwdp,[65,66,67])
would return [ [28,46,41], [38,51] ] because both 65 and 67 end up in the [28,46,41]
cycle and 66 ends up in the [38,51] cycle.
"""
periodic_cycles = []
for value in start_vals:
data = orbit_data(f, value)
data = smallest_first(data['cycle'])
if data not in periodic_cycles:
periodic_cycles.append(data)
return periodic_cycles |
'''
SHORT URLS BOT CONFIGURATION FILE
Edit me before start Bot.py!
'''
# Token of the bot. Get it one from https://telegram.me/BotFather
TOKEN = "992522370:AAGK3lfg3SFjtWgWHoo6pz9BCy8Liiwvmms"
# Telegram IDs list of admins of the bot (that can issue /users command)
ADMINS = []
# Insert absolute path to database file (.db)
DATABASE_PATH = ""
# Goo.gl API key. Get it one from https://console.developers.google.com/
GOOGLE_API_KEY = ""
# AdfLy UserID and API key. Get it one from https://adf.ly/publisher/tools#tools-api
ADFLY_UID = ""
ADFLY_API_KEY = ""
# BitLy access token. Get it one from https://bitly.com/a/oauth_apps
BITLY_ACCESS_TOKEN = ""
| """
SHORT URLS BOT CONFIGURATION FILE
Edit me before start Bot.py!
"""
token = '992522370:AAGK3lfg3SFjtWgWHoo6pz9BCy8Liiwvmms'
admins = []
database_path = ''
google_api_key = ''
adfly_uid = ''
adfly_api_key = ''
bitly_access_token = '' |
my_room = {
'plaats': "Vlijmen",
'straat naam': "Molenstraat" ,
'postcode': "5251 EN",
'huisnummer': 9,
'surface': 20,
'hoogte': 3,
'lengte': 5,
'breedte': 4,
'banken': 1,
'bureaus': 1,
'kasten': 1,
'deur': 1,
'ramen': 4,
'bed': 1,
} | my_room = {'plaats': 'Vlijmen', 'straat naam': 'Molenstraat', 'postcode': '5251 EN', 'huisnummer': 9, 'surface': 20, 'hoogte': 3, 'lengte': 5, 'breedte': 4, 'banken': 1, 'bureaus': 1, 'kasten': 1, 'deur': 1, 'ramen': 4, 'bed': 1} |
#pattern printing
#pattern triangle pattern
# print("hi pradeep")
#Qn-1 ************************************************************
"""I=1 #OUTPUT
while i<=5: #*
j=1 #**
while j<=i: #***
print("*",end=" ") #****
j=j+1 #*****
print()
i=i+1
"""
"""for i in range (1,6):
for j in range(0,i):
print("*",end="")
print()
"""
#Qn-2 ******************************************************
"""i=1 #OUTPUT
while i<=5: #1
j=1 #22
while j<=i: #333
print(i,end=" ") #4444
j=j+1 #55555
print()
i=i+1
"""
"""for i in range (1,6):
for j in range(0,i):
print(i,end="")
print()
"""
#Qn-3
"""i=1 #OUTPUT
while i<=5: #1
j=1 #12
while j<=i: #123
print(j,end=" ") #1234
j=j+1 #12345
print()
i=i+1
"""
'''for i in range (0,7):
for j in range(1,i):
print(j,end="")
print()
'''
# i=1
# while i<=5:
# b=1
# while b<=5-i:
# print(" ",end="")
# b=b+1
# j=1
# while j<=i:
# print("*",end="")
# j=j+1
# print()
# i=i+1
# print('pradeep')
#Qn-4 *******************************************
# k=1
# i=1
# while i<=5:
# b=1
# while b<=5-i:
# print(" ",end="") #not working
# b=b+1
# j=1
# while j<=k:
# print("*",end="")
# j=j+1
# print()
# k=k+1
# #print()
# i=i+1
# #print()
#Qn-5 *****************************************
# strl = input("enter string :")
# length=len(strl)
# for i in range (length):
# for j in range (length-i-1):
# print(" ",end=" ")
# for j in range (i+1):
# print(strl[j],end=" ")
# print()
#output
# p
# p y
# p y t
# p y t h
# p y t h o
# p y t h o n
# strl = input("enter string :")
# length=len(strl)
# for i in range (length):
# for j in range (length-i-1):
# print(" ",end=" ")
# for j in range (i+1):
# print(strl[i],end=" ") #we take i in
# print() #place of j
#output
# p
# y y
# t t t
# h h h h
# o o o o o
# n n n n n n
# strl = input("enter string :")
# length=len(strl)
# for i in range (length):
# for j in range (length-i-1):
# print(" ",end="") #we remove space
# for j in range (i+1): #from(" ") to ("")
# print(strl[i],end=" ")
# print()
# p
# y y
# t t t
# h h h h
# o o o o o
# n n n n n n
# for row in range(7):
# for col in range(6):
# if col==0 or (col==4 and (row!=1 and row!=2)) or (row==0 or row==6) and (col>0 and col<4)) or(row==3 and (col==3 or col==5)):
# print("*",end="")
# else:
# print(end=" ")
# print()
#Qn- **************************************
# for row in range(7):
# for col in range(5):
# if (row in {0,6}) and (col in {1,2,3}):
# print("*",end=" ")
# elif (row in {1,4,5}) and (col in {0,4}):
# print("*",end=" ")
# elif (row==2) and (col==0):
# print("*",end=" ")
# elif (row==3) and (col!=1):
# print("*",end=" ")
# else:
# print(" ",end=" ")
# print()
#OUTPUT
# * * *
# * *
# *
# * * * *
# * *
# * *
# * * *
# 2nd method *******************************
#n=5
#for i in range(n):
#Qn- ***************************************
# s=7
# for r in range(s):
# for c in range(s):
# if (r==c) or (r+c==s-1):
# print("*",end=" ")
# else:
# print(" ",end=" ")
# print()
# #output
# * *
# * *
# * *
# *
# * *
# * *
# * *
#Qn-print z pattern*******************************
# i=1
# j=4
# for row in range(0,6):
# for col in range(0,6):
# if row==0 or row==5:
# print("*",end="")
# elif row==i and col==j:
# print("*",end="")
# i=i+1
# j=j-1
# else:
# print(end=" ")
# print()
# output
# ******
# *
# *
# *
# *
# ******
#2nd method *************************************
# for row in range(0,6):
# for col in range(0,6):
# if (row==0 or row==5) or (row+col==5):
# print("*",end=" ")
# else:
# print(end=" ")
# print()
# 3rd metod **************************************
# s=6
# for row in range(s):
# for col in range(s):
# if (row==0 or row==s-1) or (row+col==s-1):
# print("*",end=" ")
# else:
# print(end=" ")
# print()
# k=1
# i=1
# while i<=5:
# b=1
# while b<=5-i: #remaind
# print(" ",end="")
# b=b+1
# j=1
# while j<=k:
# print("*",end=" ")
# j=j+1
# k=k+1
# print()
# i=i+1
# #output
# *
# * *
# * * *
# * * * *
# * * * * *
# k=1
# i=1
# while i<=5:
# b=1
# while b<=5-i: #remaind
# print(" ",end="")
# b=b+1
# j=1
# while j<=k:
# print("A",end=" ")
# j=j+1
# k=k+1
# print()
# i=i+1
# A
# A A
# A A A
# A A A A
# A A A A A
#UNIVERSAL CODE FOR PYRAMID
# n=int(input("enter your number"))
# k=1
# i=1
# while i<=n:
# b=1
# while b<=n-i: #remaind
# print(" ",end="")
# b=b+1
# j=1
# while j<=k:
# print("A",end=" ")
# j=j+1
# k=k+1
# print()
# i=i+1
#***********************************************
#ALPHABET BY USING ROW COLUMN METHOD
# for r in range(4):
# for c in range(4):
# if (r==0 and (c==0 or c==1 or c==2 or c==3)) or(r==1 and c==2) or (r==2 and c==1) or (r==3 and (c==0 or c==1 or c==2 or c==3)):
# print("*",end=" ")
# else:
# print(" ",end=" ")
# print()
# * * * *
# *
# *
# * * * *
# for r in range(3):
# for c in range(4):
# if (r==0 and (c==0 or c==2)) or (r==c) or (r==2 and (c==0 or c==2)):
# print("*",end=" ")
# else:
# print(" ", end=" ")
# print( )
#print(ord("A"))
# PRINT ALPHABET PATTERN BY USING ASCCI VALUE
# n=int(input("enter your number :"))
# for i in range(n):
# for z in range(1,n-i):
# print(' ',end='')
# for j in range(i+1):
# print(chr(65+i),end=" ")
# print(" ")
# n=int(input("enter your number"))
# k=1
# i=0
# while i<=n:
# b=1
# while b<=n-i: #remaind
# print(" ",end="")
# b=b+1
# j=1
# while j<=k:
# print(chr(65+i),end=" ")
# j=j+1
# k=k+1
# print()
# i=i+1
#SNACK PATTERN *****************************
#n=int(input("enter your number"))
for i in range(0,15,-1):
for j in range(i+1):
print(i,end=" ")
print()
# PALINDROME NUMBER(153=1^2+5^2+3^2=153 THAT IS PALI)
# i=int(input("enter number"))
# orgi=i
# sum=0
# while i>0:
# sum=sum+(i%10)*(i%10)*(i%10)
# i=i//10
# if sum==orgi:
# print(orgi,"it is armstrong no")
# else:
# print(orgi,"it is not a armstrong no")
| """I=1 #OUTPUT
while i<=5: #*
j=1 #**
while j<=i: #***
print("*",end=" ") #****
j=j+1 #*****
print()
i=i+1
"""
'for i in range (1,6):\n\tfor j in range(0,i):\n\t\tprint("*",end="")\n\tprint()\t\n'
'i=1 #OUTPUT\nwhile i<=5: #1\n\tj=1 #22\n\twhile j<=i: #333\n\t\tprint(i,end=" ") #4444\n\t\tj=j+1 #55555\n\tprint()\n\ti=i+1\n\t'
'for i in range (1,6):\n\tfor j in range(0,i):\n\t\tprint(i,end="")\n\tprint()\n\t'
'i=1 #OUTPUT\nwhile i<=5: #1\n\tj=1 #12\n\twhile j<=i: #123\n\t\tprint(j,end=" ") #1234\n\t\tj=j+1 #12345\n\tprint()\n\ti=i+1\n\t'
'for i in range (0,7):\n\tfor j in range(1,i):\n\t\tprint(j,end="")\n\tprint()\n\t'
for i in range(0, 15, -1):
for j in range(i + 1):
print(i, end=' ')
print() |
class AsyncnotiException(Exception):
def __init__(self, message, code):
super(Exception, self).__init__(message)
self.message = message
self.code = code
| class Asyncnotiexception(Exception):
def __init__(self, message, code):
super(Exception, self).__init__(message)
self.message = message
self.code = code |
# class Tree:
# def __init__(self, val, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
# class LLNode:
# def __init__(self, val, next=None):
# self.val = val
# self.next = next
class Solution:
prev = None
head = None
def solve(self, root):
def solve1(root):
if root:
solve1(root.left)
cur = LLNode(root.val)
if self.prev:
self.prev.next = cur
if not self.head:
self.head = cur
self.prev = cur
solve1(root.right)
return root
solve1(root)
return self.head
| class Solution:
prev = None
head = None
def solve(self, root):
def solve1(root):
if root:
solve1(root.left)
cur = ll_node(root.val)
if self.prev:
self.prev.next = cur
if not self.head:
self.head = cur
self.prev = cur
solve1(root.right)
return root
solve1(root)
return self.head |
class Solution:
def getNoZeroIntegers(self, n: int) -> List[int]:
for A in range(n):
B = n - A
if '0' not in str(A) and '0' not in str(B):
return A, B
| class Solution:
def get_no_zero_integers(self, n: int) -> List[int]:
for a in range(n):
b = n - A
if '0' not in str(A) and '0' not in str(B):
return (A, B) |
# output: ok
a = {}
assert(len(a) == 0)
for i in range(0, 100):
a[i] = i * 2
assert(len(a) == 100)
for i in range(0, 100):
assert i in a
assert(a[i] == i * 2)
assert 101 not in a
for i in range(0, 100, 2):
del a[i]
assert(len(a) == 50)
for i in range(0, 100):
assert (i in a) == ((i % 2) != 0)
a = {}
for i in range(0, 100):
a[str(i)] = i
assert(len(a) == 100)
for i in range(0, 100):
k = str(i)
assert k in a
assert(a[k] == i)
assert '101' not in a
for i in range(0, 100, 2):
del a[str(i)]
assert(len(a) == 50)
for i in range(0, 100):
assert (str(i) in a) == ((i % 2) != 0)
print('ok')
| a = {}
assert len(a) == 0
for i in range(0, 100):
a[i] = i * 2
assert len(a) == 100
for i in range(0, 100):
assert i in a
assert a[i] == i * 2
assert 101 not in a
for i in range(0, 100, 2):
del a[i]
assert len(a) == 50
for i in range(0, 100):
assert (i in a) == (i % 2 != 0)
a = {}
for i in range(0, 100):
a[str(i)] = i
assert len(a) == 100
for i in range(0, 100):
k = str(i)
assert k in a
assert a[k] == i
assert '101' not in a
for i in range(0, 100, 2):
del a[str(i)]
assert len(a) == 50
for i in range(0, 100):
assert (str(i) in a) == (i % 2 != 0)
print('ok') |
#CONFIG FILE
#Made by Luka Dragar
#@thelukadragar
operatingmode="xyz"
#"xy"---move only in xy
#"xyz"--move in xy and z
#----------------------------------------------
sendinginterval=0.15
#interval to send points[seconds]
#try changing if there are problems
myIP= "127.0.0.1" # localhost or your ip "192.168.64.101"
myPort=55555
#limit coordinates for moving
#change if robot out of reach
xmax=600
xmin=0
ymin=0
ymax=600
zmax=300
zmin=-500
zrange=1000 #difference betwen max and min
zoffsetcamera=-500#offset according to where you want Z0 to be
areatocompare=120000#compares area of your hand to this value
#scale in percent
livefeedwindowscalex=100
livefeedwindowscaley=100
#camera you can use ip camera like this.
#cameratouse="http://192.168.64.102:8080/video" #for ip camera
cameratouse=0 #default camera
#coordinatemultiplier
cormultiplyx=1
cormultiplyy=1
cormultiplyz=1
#sensitivity send move if object moves by px +-1 default
sensitivity=1
| operatingmode = 'xyz'
sendinginterval = 0.15
my_ip = '127.0.0.1'
my_port = 55555
xmax = 600
xmin = 0
ymin = 0
ymax = 600
zmax = 300
zmin = -500
zrange = 1000
zoffsetcamera = -500
areatocompare = 120000
livefeedwindowscalex = 100
livefeedwindowscaley = 100
cameratouse = 0
cormultiplyx = 1
cormultiplyy = 1
cormultiplyz = 1
sensitivity = 1 |
# the most common user agents by https://techblog.willshouse.com/2012/01/03/most-common-user-agents/
DEFAULT_USER_AGENTS = [
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/601.6.17 (KHTML, like Gecko) Version/9.1.1 Safari/601.6.17",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/601.5.17 (KHTML, like Gecko) Version/9.1 Safari/601.5.17",
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko",
"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:46.0) Gecko/20100101 Firefox/46.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:46.0) Gecko/20100101 Firefox/46.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586",
"Mozilla/5.0 (Windows NT 6.3; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:46.0) Gecko/20100101 Firefox/46.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; rv:46.0) Gecko/20100101 Firefox/46.0",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/601.6.17 (KHTML, like Gecko) Version/9.1.1 Safari/601.6.17",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64; rv:46.0) Gecko/20100101 Firefox/46.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/601.4.4 (KHTML, like Gecko) Version/9.0.3 Safari/601.4.4",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko",
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/50.0.2661.102 Chrome/50.0.2661.102 Safari/537.36",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; Trident/5.0)",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/5.0; Trident/5.0)",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:46.0) Gecko/20100101 Firefox/46.0",
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/601.5.17 (KHTML, like Gecko) Version/9.1 Safari/601.5.17",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko",
"Mozilla/5.0 (iPad; CPU OS 9_3_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13E238 Safari/601.1",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/49.0.2623.108 Chrome/49.0.2623.108 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36",
"Mozilla/5.0 (iPad; CPU OS 9_3_2 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13F69 Safari/601.1",
"Mozilla/5.0 (Windows NT 5.1; rv:46.0) Gecko/20100101 Firefox/46.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:46.0) Gecko/20100101 Firefox/46.0",
"Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0",
"Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:46.0) Gecko/20100101 Firefox/46.0",
"Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0",
"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.86 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:45.0) Gecko/20100101 Firefox/45.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/600.5.17 (KHTML, like Gecko) Version/8.0.5 Safari/600.5.17",
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/600.8.9 (KHTML, like Gecko) Version/8.0.8 Safari/600.8.9",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9",
"Mozilla/5.0 (Windows NT 6.1; rv:38.0) Gecko/20100101 Firefox/38.0",
"Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:46.0) Gecko/20100101 Firefox/46.0",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36",
] | default_user_agents = ['Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/601.6.17 (KHTML, like Gecko) Version/9.1.1 Safari/601.6.17', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/601.5.17 (KHTML, like Gecko) Version/9.1 Safari/601.5.17', 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko', 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:46.0) Gecko/20100101 Firefox/46.0', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:46.0) Gecko/20100101 Firefox/46.0', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586', 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:46.0) Gecko/20100101 Firefox/46.0', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; rv:46.0) Gecko/20100101 Firefox/46.0', 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/601.6.17 (KHTML, like Gecko) Version/9.1.1 Safari/601.6.17', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36', 'Mozilla/5.0 (X11; Linux x86_64; rv:46.0) Gecko/20100101 Firefox/46.0', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/601.4.4 (KHTML, like Gecko) Version/9.0.3 Safari/601.4.4', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0', 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/50.0.2661.102 Chrome/50.0.2661.102 Safari/537.36', 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; Trident/5.0)', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36', 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/5.0; Trident/5.0)', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:46.0) Gecko/20100101 Firefox/46.0', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/601.5.17 (KHTML, like Gecko) Version/9.1 Safari/601.5.17', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko', 'Mozilla/5.0 (iPad; CPU OS 9_3_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13E238 Safari/601.1', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/49.0.2623.108 Chrome/49.0.2623.108 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36', 'Mozilla/5.0 (iPad; CPU OS 9_3_2 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13F69 Safari/601.1', 'Mozilla/5.0 (Windows NT 5.1; rv:46.0) Gecko/20100101 Firefox/46.0', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:46.0) Gecko/20100101 Firefox/46.0', 'Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0', 'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:46.0) Gecko/20100101 Firefox/46.0', 'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0', 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.86 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:45.0) Gecko/20100101 Firefox/45.0', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/600.5.17 (KHTML, like Gecko) Version/8.0.5 Safari/600.5.17', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0', 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/600.8.9 (KHTML, like Gecko) Version/8.0.8 Safari/600.8.9', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9', 'Mozilla/5.0 (Windows NT 6.1; rv:38.0) Gecko/20100101 Firefox/38.0', 'Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:46.0) Gecko/20100101 Firefox/46.0', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36'] |
class PlayerCharacter:
membership = True
def __init__(self, name, age):
self.name = name
self.age = age
def shout(self):
print(f"My name is {self.name}")
@classmethod
def adding_things(cls, num1, num2):
return cls('Teddy', num1 + num2)
@staticmethod
def adding_things(cls, num1, num2):
return cls('Teddy', num1 + num2)
#player1 = PlayerCharacter("Tom", 20)
player3 = PlayerCharacter.adding_things(2,3)
print(player3.age)
| class Playercharacter:
membership = True
def __init__(self, name, age):
self.name = name
self.age = age
def shout(self):
print(f'My name is {self.name}')
@classmethod
def adding_things(cls, num1, num2):
return cls('Teddy', num1 + num2)
@staticmethod
def adding_things(cls, num1, num2):
return cls('Teddy', num1 + num2)
player3 = PlayerCharacter.adding_things(2, 3)
print(player3.age) |
# 42. Trapping Rain Water
# Runtime: 131 ms, faster than 12.45% of Python3 online submissions for Trapping Rain Water.
# Memory Usage: 15.7 MB, less than 35.74% of Python3 online submissions for Trapping Rain Water.
class Solution:
# Using Stacks
def trap(self, height: list[int]) -> int:
ans = 0
stack = []
for i in range(len(height)):
while stack and height[i] > height[stack[-1]]:
top = stack.pop(-1)
if not stack:
break
# The bar at the top of the stack is bounded by the current bar and a previous bar in the stack.
dist = i - stack[-1] - 1
bounded_height = min(height[i], height[stack[-1]]) - height[top]
ans += dist * bounded_height
stack.append(i)
return ans | class Solution:
def trap(self, height: list[int]) -> int:
ans = 0
stack = []
for i in range(len(height)):
while stack and height[i] > height[stack[-1]]:
top = stack.pop(-1)
if not stack:
break
dist = i - stack[-1] - 1
bounded_height = min(height[i], height[stack[-1]]) - height[top]
ans += dist * bounded_height
stack.append(i)
return ans |
n=int(input())
for i in range(n):
brackets = input()
stack=[]
dictt={'(':')', '[':']', '{':'}'}
flag=0
for b in brackets:
#print(stack)
if (len(stack)==0) and b in dictt.values():
flag=1
break
elif (len(stack)==0) or b in dictt.keys():
stack.append(b)
else:
if (b in dictt.values()) and (b == dictt[stack[-1]]):
del stack[-1]
if len(stack)==0 and flag!=1:
print("YES")
else:
print("NO")
| n = int(input())
for i in range(n):
brackets = input()
stack = []
dictt = {'(': ')', '[': ']', '{': '}'}
flag = 0
for b in brackets:
if len(stack) == 0 and b in dictt.values():
flag = 1
break
elif len(stack) == 0 or b in dictt.keys():
stack.append(b)
elif b in dictt.values() and b == dictt[stack[-1]]:
del stack[-1]
if len(stack) == 0 and flag != 1:
print('YES')
else:
print('NO') |
def export_docs(documents, output_path):
""" Exports a list of dictionaries to a single csv file
:param documents: list of dictionaries
:param output_path: file path to csv file
"""
for doc in documents:
export_dict(doc, output_path)
def export_dict(dictionary, output_path):
""" Exports an ordered dictionary to a csv file
:param dictionary: dictionary with words as keys and the number of appearances as values
:param output_path: file path to csv file
"""
with open(output_path, 'a', encoding='utf-8') as f:
for key in dictionary.keys():
try:
f.write('{}:{},'.format(key, dictionary[key]))
except UnicodeEncodeError:
print("Couldn't encode {}. Skip".format(key))
f.write('\n')
f.close()
def import_docs(file_path):
""" Imports a csv file and returns a list of dictionaries
:param file_path: Path of csv file
"""
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read().splitlines()
f.close()
docs = []
for line in content:
docs.append(import_dict(line))
return docs
def import_dict(line):
""" Converts line of a csv file to a dict
:param line: line of csv file
:return: dictionary
"""
dictionary = {}
elements = line.split(',')
for element in elements:
try:
key, value = element.split(':')
dictionary[key] = int(value)
except ValueError:
pass
return dictionary
| def export_docs(documents, output_path):
""" Exports a list of dictionaries to a single csv file
:param documents: list of dictionaries
:param output_path: file path to csv file
"""
for doc in documents:
export_dict(doc, output_path)
def export_dict(dictionary, output_path):
""" Exports an ordered dictionary to a csv file
:param dictionary: dictionary with words as keys and the number of appearances as values
:param output_path: file path to csv file
"""
with open(output_path, 'a', encoding='utf-8') as f:
for key in dictionary.keys():
try:
f.write('{}:{},'.format(key, dictionary[key]))
except UnicodeEncodeError:
print("Couldn't encode {}. Skip".format(key))
f.write('\n')
f.close()
def import_docs(file_path):
""" Imports a csv file and returns a list of dictionaries
:param file_path: Path of csv file
"""
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read().splitlines()
f.close()
docs = []
for line in content:
docs.append(import_dict(line))
return docs
def import_dict(line):
""" Converts line of a csv file to a dict
:param line: line of csv file
:return: dictionary
"""
dictionary = {}
elements = line.split(',')
for element in elements:
try:
(key, value) = element.split(':')
dictionary[key] = int(value)
except ValueError:
pass
return dictionary |
{
"targets": [
{
"target_name": "index",
"sources": ["src/index.cc"],
"defines": [
'ENC_PUBLIC_KEY="<!(echo $ENC_PUBLIC_KEY)"'
]
},
],
} | {'targets': [{'target_name': 'index', 'sources': ['src/index.cc'], 'defines': ['ENC_PUBLIC_KEY="<!(echo $ENC_PUBLIC_KEY)"']}]} |
OCTICON_THUMBSDOWN = """
<svg class="octicon octicon-thumbsdown" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M7.083 15.986c1.34.153 2.334-.982 2.334-2.183v-.5c0-1.329.646-2.123 1.317-2.614.329-.24.66-.403.919-.508a1.75 1.75 0 001.514.872h1a1.75 1.75 0 001.75-1.75v-7.5a1.75 1.75 0 00-1.75-1.75h-1a1.75 1.75 0 00-1.662 1.2c-.525-.074-1.068-.228-1.726-.415L9.305.705C8.151.385 6.765.053 4.917.053c-1.706 0-2.97.152-3.722 1.139-.353.463-.537 1.042-.669 1.672C.41 3.424.32 4.108.214 4.897l-.04.306c-.25 1.869-.266 3.318.188 4.316.244.537.622.943 1.136 1.2.495.248 1.066.334 1.669.334h1.422l-.015.112c-.07.518-.157 1.17-.157 1.638 0 .921.151 1.718.655 2.299.512.589 1.248.797 2.011.884zm4.334-13.232c-.706-.089-1.39-.284-2.072-.479a63.914 63.914 0 00-.441-.125c-1.096-.304-2.335-.597-3.987-.597-1.794 0-2.28.222-2.529.548-.147.193-.275.505-.393 1.07-.105.502-.188 1.124-.295 1.93l-.04.3c-.25 1.882-.19 2.933.067 3.497a.921.921 0 00.443.48c.208.104.52.175.997.175h1.75c.685 0 1.295.577 1.205 1.335-.022.192-.049.39-.075.586-.066.488-.13.97-.13 1.329 0 .808.144 1.15.288 1.316.137.157.401.303 1.048.377.307.035.664-.237.664-.693v-.5c0-1.922.978-3.127 1.932-3.825a5.862 5.862 0 011.568-.809V2.754zm1.75 6.798a.25.25 0 01-.25-.25v-7.5a.25.25 0 01.25-.25h1a.25.25 0 01.25.25v7.5a.25.25 0 01-.25.25h-1z"></path></svg>
"""
| octicon_thumbsdown = '\n<svg class="octicon octicon-thumbsdown" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M7.083 15.986c1.34.153 2.334-.982 2.334-2.183v-.5c0-1.329.646-2.123 1.317-2.614.329-.24.66-.403.919-.508a1.75 1.75 0 001.514.872h1a1.75 1.75 0 001.75-1.75v-7.5a1.75 1.75 0 00-1.75-1.75h-1a1.75 1.75 0 00-1.662 1.2c-.525-.074-1.068-.228-1.726-.415L9.305.705C8.151.385 6.765.053 4.917.053c-1.706 0-2.97.152-3.722 1.139-.353.463-.537 1.042-.669 1.672C.41 3.424.32 4.108.214 4.897l-.04.306c-.25 1.869-.266 3.318.188 4.316.244.537.622.943 1.136 1.2.495.248 1.066.334 1.669.334h1.422l-.015.112c-.07.518-.157 1.17-.157 1.638 0 .921.151 1.718.655 2.299.512.589 1.248.797 2.011.884zm4.334-13.232c-.706-.089-1.39-.284-2.072-.479a63.914 63.914 0 00-.441-.125c-1.096-.304-2.335-.597-3.987-.597-1.794 0-2.28.222-2.529.548-.147.193-.275.505-.393 1.07-.105.502-.188 1.124-.295 1.93l-.04.3c-.25 1.882-.19 2.933.067 3.497a.921.921 0 00.443.48c.208.104.52.175.997.175h1.75c.685 0 1.295.577 1.205 1.335-.022.192-.049.39-.075.586-.066.488-.13.97-.13 1.329 0 .808.144 1.15.288 1.316.137.157.401.303 1.048.377.307.035.664-.237.664-.693v-.5c0-1.922.978-3.127 1.932-3.825a5.862 5.862 0 011.568-.809V2.754zm1.75 6.798a.25.25 0 01-.25-.25v-7.5a.25.25 0 01.25-.25h1a.25.25 0 01.25.25v7.5a.25.25 0 01-.25.25h-1z"></path></svg>\n' |
'''
Version Checker module entry point
'''
__version__ = '0.2.2-alpha.2'
| """
Version Checker module entry point
"""
__version__ = '0.2.2-alpha.2' |
"""
Classes and functions used to create and download LBRY Files.
LBRY Files are Crypt Streams created from any regular file. The whole file is read
at the time that the LBRY File is created, so all constituent blobs are known and
included in the stream descriptor file.
""" | """
Classes and functions used to create and download LBRY Files.
LBRY Files are Crypt Streams created from any regular file. The whole file is read
at the time that the LBRY File is created, so all constituent blobs are known and
included in the stream descriptor file.
""" |
def main():
while True:
try:
print(''.join(list(chr(ord(word) - 7) for word in input())))
except EOFError:
break
pass
if __name__ == '__main__':
main()
| def main():
while True:
try:
print(''.join(list((chr(ord(word) - 7) for word in input()))))
except EOFError:
break
pass
if __name__ == '__main__':
main() |
print("""
Witaj, w prostym kalkulatorze ;)""")
print("""wybierz porzadana operacje :
+ - dodawanie
- - odejmowanie
/ - dzielenie
* - mnozenie
** - potegowanie
""")
operacja = input("wybrana operacja : ")
a = int(input("Podaj pierwsza liczbe : "))
b = int(input("Podaj druga liczbe : "))
if (operacja == '+'):
print("Wynik dodawania", a, "do", b, "wynosi :", a + b)
elif (operacja == '-'):
print("Wynik odejmowania", a, "od", b, "wynosi :", a - b)
elif (operacja == '/'):
if (b == 0):
print("Nie dziel przez zero !")
else:
print("Wynik dzielenia", a, "przez", b, "wynosi :", a / b)
elif (operacja == '*'):
print("Wynik mnozenia", a, "przez", b, "wynosi :", a * b)
elif (operacja == '**'):
print("Wynik potegowania", a, "do potegi", b, "wynosi :", a ** b)
else:
print("Wybrano niepoprawna operacje!")
| print('\nWitaj, w prostym kalkulatorze ;)')
print('wybierz porzadana operacje : \n\n+ - dodawanie\n- - odejmowanie\n/ - dzielenie\n* - mnozenie\n** - potegowanie\n')
operacja = input('wybrana operacja : ')
a = int(input('Podaj pierwsza liczbe : '))
b = int(input('Podaj druga liczbe : '))
if operacja == '+':
print('Wynik dodawania', a, 'do', b, 'wynosi :', a + b)
elif operacja == '-':
print('Wynik odejmowania', a, 'od', b, 'wynosi :', a - b)
elif operacja == '/':
if b == 0:
print('Nie dziel przez zero !')
else:
print('Wynik dzielenia', a, 'przez', b, 'wynosi :', a / b)
elif operacja == '*':
print('Wynik mnozenia', a, 'przez', b, 'wynosi :', a * b)
elif operacja == '**':
print('Wynik potegowania', a, 'do potegi', b, 'wynosi :', a ** b)
else:
print('Wybrano niepoprawna operacje!') |
class Request:
def __init__(self):
self.app = None
self.base_url = None
self.body = None
self.cookies = {}
self.fresh = None
self.hostname = None
self.ip = None
self.ips = None
self.method = None
self.original_url = None
self.params = {} # named router parameters
self.path = None
self.protocol = None
self.query = {}
self.route = None # contains the currently-matched route, a string
self.secure = None
self.signed_cookies = None
self.stale = None
self.subdomains = None
self.xhr = None
self._headers = {}
self._body = None
self.locals = {}
self.environ = {}
def accetpts(self, types):
pass
def accepts_charsets(self, *charsets):
pass
def accepts_encodings(self, *encodings):
pass
def accepts_languages(self, *langs):
pass
def get(self, field):
'''Aliased as request.header(field)'''
pass
def header(self, field):
pass
def is_type(self, content_type):
pass
def range(self, size, *options):
pass | class Request:
def __init__(self):
self.app = None
self.base_url = None
self.body = None
self.cookies = {}
self.fresh = None
self.hostname = None
self.ip = None
self.ips = None
self.method = None
self.original_url = None
self.params = {}
self.path = None
self.protocol = None
self.query = {}
self.route = None
self.secure = None
self.signed_cookies = None
self.stale = None
self.subdomains = None
self.xhr = None
self._headers = {}
self._body = None
self.locals = {}
self.environ = {}
def accetpts(self, types):
pass
def accepts_charsets(self, *charsets):
pass
def accepts_encodings(self, *encodings):
pass
def accepts_languages(self, *langs):
pass
def get(self, field):
"""Aliased as request.header(field)"""
pass
def header(self, field):
pass
def is_type(self, content_type):
pass
def range(self, size, *options):
pass |
#! /usr/bin/env python3
def are_same(serial):
if (serial[0] != serial[1] and
serial[1] != serial[2] and
serial[0] != serial[2]):
return False
return True
def check_serial(serial):
try:
serials = serial.split('-')
except:
return False
if len(serials) != 3:
return False
try:
X = [ord(a) for a in list(serials[0])]
Y = [ord(a) for a in list(serials[1])]
Z = int(serials[2])
except ValueError:
return False
except:
return False
if not len(X) == 3 or not len(Y) == 3:
return False
for a in X+Y:
if a < 65 or a > 90:
return False
if are_same(X) or are_same(Y):
return False
if X[1] + 10 > X[2]:
return False
if Y[1] - 10 < Y[2]:
return False
sum1 = X[0] + X[1] + X[2]
sum2 = Y[0] + Y[1] + Y[2]
if sum1 == sum2:
return False
if sum1+sum2 != Z:
return False
if Z % 3 != 0:
return False
return True
| def are_same(serial):
if serial[0] != serial[1] and serial[1] != serial[2] and (serial[0] != serial[2]):
return False
return True
def check_serial(serial):
try:
serials = serial.split('-')
except:
return False
if len(serials) != 3:
return False
try:
x = [ord(a) for a in list(serials[0])]
y = [ord(a) for a in list(serials[1])]
z = int(serials[2])
except ValueError:
return False
except:
return False
if not len(X) == 3 or not len(Y) == 3:
return False
for a in X + Y:
if a < 65 or a > 90:
return False
if are_same(X) or are_same(Y):
return False
if X[1] + 10 > X[2]:
return False
if Y[1] - 10 < Y[2]:
return False
sum1 = X[0] + X[1] + X[2]
sum2 = Y[0] + Y[1] + Y[2]
if sum1 == sum2:
return False
if sum1 + sum2 != Z:
return False
if Z % 3 != 0:
return False
return True |
"""
Functionality which could be shared among various serializes.
"""
class InjectUserMixin(object):
"""
Inject a user to object being created from the logged in user such that the
Front-end does not need to supply the value
"""
def __init__(self, *args, **kwargs):
super(InjectUserMixin, self).__init__(*args, **kwargs)
self.fields.pop('user')
def create(self, validated_data):
user = self.context.get('request').user
validated_data['user'] = user
return super(InjectUserMixin, self).create(validated_data)
| """
Functionality which could be shared among various serializes.
"""
class Injectusermixin(object):
"""
Inject a user to object being created from the logged in user such that the
Front-end does not need to supply the value
"""
def __init__(self, *args, **kwargs):
super(InjectUserMixin, self).__init__(*args, **kwargs)
self.fields.pop('user')
def create(self, validated_data):
user = self.context.get('request').user
validated_data['user'] = user
return super(InjectUserMixin, self).create(validated_data) |
class wordsServant:
"""class to look at words
can remove repeadted words"""
def __init__(self, text):
self.text = text
self.deleteWords = ["like", "maybe", "just"]
# TODO lowercase for delete words
self.list_text = self.text.split(" ")
def repeatedWords(self):
"""
Deletes repeadted words in text
"""
# so whenever i delete a word
# the length of the list goes down by 1
# so that changes everything, so i need to keep track of them LMAO
deletionCounter = 0
for counter in range(1, len(self.list_text)):
# for every word in the string
# if that word is repeated, delete it
try:
if self.list_text[counter - 1].strip().lower() == self.list_text[counter].strip().lower():
self.list_text.remove(self.list_text[counter - deletionCounter])
deletionCounter += 1
except IndexError as e:
# basically if the counter == len of list, it errors out so we just skip it lol
pass
print(self.list_text)
def checkForBadWords(self):
"""removes bad words from the text"""
for word in self.deleteWords:
if word in self.list_text:
self.list_text.remove(word)
if __name__ == "__main__":
print("and this runs oops")
ws = wordsServant("hello hello and I I yours")
ws.repeatedWords()
ws.checkForBadWords()
| class Wordsservant:
"""class to look at words
can remove repeadted words"""
def __init__(self, text):
self.text = text
self.deleteWords = ['like', 'maybe', 'just']
self.list_text = self.text.split(' ')
def repeated_words(self):
"""
Deletes repeadted words in text
"""
deletion_counter = 0
for counter in range(1, len(self.list_text)):
try:
if self.list_text[counter - 1].strip().lower() == self.list_text[counter].strip().lower():
self.list_text.remove(self.list_text[counter - deletionCounter])
deletion_counter += 1
except IndexError as e:
pass
print(self.list_text)
def check_for_bad_words(self):
"""removes bad words from the text"""
for word in self.deleteWords:
if word in self.list_text:
self.list_text.remove(word)
if __name__ == '__main__':
print('and this runs oops')
ws = words_servant('hello hello and I I yours')
ws.repeatedWords()
ws.checkForBadWords() |
#Exclude variants not in hearing loss panel
if Panels not in {ACMG59}:
return False
| if Panels not in {ACMG59}:
return False |
def check_palindrome_rearrangement(string):
chars = set()
for char in string:
if char not in chars:
chars.add(char)
else:
chars.remove(char)
return len(chars) < 2
# Tests
assert check_palindrome_rearrangement("carrace")
assert not check_palindrome_rearrangement("daily")
assert not check_palindrome_rearrangement("abac")
assert check_palindrome_rearrangement("abacc")
assert check_palindrome_rearrangement("aabb")
assert not check_palindrome_rearrangement("aabbcccd")
| def check_palindrome_rearrangement(string):
chars = set()
for char in string:
if char not in chars:
chars.add(char)
else:
chars.remove(char)
return len(chars) < 2
assert check_palindrome_rearrangement('carrace')
assert not check_palindrome_rearrangement('daily')
assert not check_palindrome_rearrangement('abac')
assert check_palindrome_rearrangement('abacc')
assert check_palindrome_rearrangement('aabb')
assert not check_palindrome_rearrangement('aabbcccd') |
WEEKLY_STRADDLE_COLUMNS = ['TIMESTAMP', 'OPEN', 'HIGH', 'LOW', 'CLOSE', 'STRIKE', 'OPEN_C', 'HIGH_C', 'LOW_C',
'CLOSE_C', 'H-O_C',
'L-O_C', 'C-O_C', 'OPEN_P', 'HIGH_P', 'LOW_P', 'CLOSE_P', 'H-O_P', 'L-O_P', 'C-O_P']
OPTIONS_COLUMNS = ['TIMESTAMP', 'EXPIRY_DT', 'SYMBOL', 'STRIKE_PR', 'OPTION_TYP', 'OPEN', 'HIGH', 'LOW', 'CLOSE', 'OPEN_INT', 'CHG_IN_OI']
CANDLE_COLUMNS = ['OPEN', 'HIGH', 'LOW', 'CLOSE']
CALL_CANDLE_COLUMNS = [f'{x}_C' for x in CANDLE_COLUMNS]
PUT_CANDLE_COLUMNS = [f'{x}_P' for x in CANDLE_COLUMNS]
PL_CANDLE_COLUMNS = [f'PL_{x}' for x in CANDLE_COLUMNS]
CONSTANT_COLUMNS = ['LOT_SIZE', 'NUM_LOTS', 'TOTAL_LOTS', 'MARGIN_PER_LOT', 'MARGIN_REQUIRED', 'STOP_LOSS', 'STOP_LOSS_TRIGGER']
PL_NET_COLUMNS = ['NET_PL_LO', 'NET_PL_HI', 'NET_PL_CL']
STOP_LOSS_TRUTH_COLUMNS = ['STOP_LOSS_HIT', 'SL_HI_GT_CL']
NET_COLUMNS = ['NET', '%', 'LOSE_COUNT', 'CUM_LOSE_COUNT', 'CUM_NET']
CONVERSION = {'SYMBOL':'first', 'OPEN':'first', 'HIGH':'max', 'LOW':'min', 'CLOSE':'last'}
CHAIN_CONVERSION = {'OPEN_C':'first', 'HIGH_C':'max', 'LOW_C':'min', 'CLOSE_C':'last', 'OPEN_P':'first', 'HIGH_P':'max', 'LOW_P':'min', 'CLOSE_P':'last'}
STRADDLE_CONVERSION = {'OPEN_C':'first', 'HIGH_C': 'max', 'LOW_C':'min', 'CLOSE_C':'last', 'OPEN_P':'first', 'HIGH_P':'max', 'LOW_P':'min', 'CLOSE_P':'last','PL_OPEN':'first', 'PL_HIGH':'max', 'PL_LOW':'min', 'PL_CLOSE':'last'}
STRANGLE_CONVERSION = {'STRIKE_C':'first', 'OPEN_C':'first', 'HIGH_C':'max', 'LOW_C':'min', 'CLOSE_C':'last', 'STRIKE_P':'first', 'OPEN_P':'first', 'HIGH_P':'max', 'LOW_P':'min', 'CLOSE_P':'last', 'PL_OPEN':'first', 'PL_HIGH':'max', 'PL_LOW':'min', 'PL_CLOSE':'last'}
IRON_BUTTERFLY_CONVERSION = {'OPEN_C':'first', 'HIGH_C':'max', 'LOW_C':'min', 'CLOSE_C':'last', 'OPEN_P':'first', 'HIGH_P':'max', 'LOW_P':'min', 'CLOSE_P':'last', 'STRIKE_CL':'first', 'OPEN_CL':'first', 'HIGH_CL':'max', 'LOW_CL':'min', 'CLOSE_CL':'last', 'STRIKE_PR':'first', 'OPEN_PR':'first', 'HIGH_PR':'max', 'LOW_PR':'min', 'CLOSE_PR':'last', 'PL_OPEN':'first', 'PL_HIGH':'max', 'PL_LOW':'min', 'PL_CLOSE':'last'}
CALENDAR_SPREAD_CONVERSION = {'OPEN_C':'first', 'HIGH_C':'max', 'LOW_C':'min', 'CLOSE_C':'last', 'OPEN_P':'first', 'HIGH_P':'max', 'LOW_P':'min', 'CLOSE_P':'last', 'OPEN_CN':'first', 'HIGH_CN':'max', 'LOW_CN':'min', 'CLOSE_CN':'last', 'OPEN_PN':'first', 'HIGH_PN':'max', 'LOW_PN':'min', 'CLOSE_PN':'last', 'PL_OPEN':'first', 'PL_HIGH':'max', 'PL_LOW':'min', 'PL_CLOSE':'last'}
DOUBLE_RATIO_COLUMNS = ['STRIKE_ATM', 'OPEN_CA','HIGH_CA', 'LOW_CA', 'CLOSE_CA', 'OPEN_PA', 'HIGH_PA', 'LOW_PA', 'CLOSE_PA', 'STRIKE_CS', 'OPEN_CS', 'HIGH_CS','LOW_CS', 'CLOSE_CS', 'STRIKE_PS', 'OPEN_PS', 'HIGH_PS', 'LOW_PS', 'CLOSE_PS', 'STRIKE_CL', 'OPEN_CL', 'HIGH_CL','LOW_CL', 'CLOSE_CL', 'STRIKE_PL', 'OPEN_PL', 'HIGH_PL', 'LOW_PL', 'CLOSE_PL']
DOUBLE_RATIO_CONVERSION = {'STRIKE_ATM':'first', 'OPEN_CA':'first', 'HIGH_CA':'max', 'LOW_CA':'min', 'CLOSE_CA':'last', 'OPEN_PA':'first', 'HIGH_PA':'max', 'LOW_PA':'min', 'CLOSE_PA':'last', 'STRIKE_CS':'first', 'OPEN_CS':'first', 'HIGH_CS':'max','LOW_CS':'min', 'CLOSE_CS':'last', 'STRIKE_PS':'first', 'OPEN_PS':'first', 'HIGH_PS':'max', 'LOW_PS':'min', 'CLOSE_PS':'last', 'STRIKE_CL':'first', 'OPEN_CL':'first', 'HIGH_CL':'max','LOW_CL':'min', 'CLOSE_CL':'last', 'STRIKE_PL':'first', 'OPEN_PL':'first', 'HIGH_PL':'max', 'LOW_PL':'min', 'CLOSE_PL':'last', 'PL_OPEN':'first', 'PL_HIGH':'max', 'PL_LOW':'min', 'PL_CLOSE':'last'}
RATIO_WRITE_AT_MAX_OI_COLUMNS = ['STRIKE_C', 'OPEN_C', 'HIGH_C', 'LOW_C', 'CLOSE_C', 'STRIKE_P', 'OPEN_P', 'HIGH_P', 'LOW_P', 'CLOSE_P', 'STRIKE_CS', 'OPEN_CS', 'HIGH_CS','LOW_CS', 'CLOSE_CS', 'STRIKE_PS', 'OPEN_PS', 'HIGH_PS', 'LOW_PS', 'CLOSE_PS']
RATIO_WRITE_AT_MAX_OI_CONVERSION = {'STRIKE_C':'first', 'OPEN_C':'first', 'HIGH_C':'max', 'LOW_C':'min', 'CLOSE_C':'last', 'STRIKE_P':'first', 'OPEN_P':'first', 'HIGH_P':'max', 'LOW_P':'min', 'CLOSE_P':'last', 'STRIKE_CS':'first', 'OPEN_CS':'first', 'HIGH_CS':'max','LOW_CS':'min', 'CLOSE_CS':'last', 'STRIKE_PS':'first', 'OPEN_PS':'first', 'HIGH_PS':'max', 'LOW_PS':'min', 'CLOSE_PS':'last', 'PL_OPEN':'first', 'PL_HIGH':'max', 'PL_LOW':'min', 'PL_CLOSE':'last'} | weekly_straddle_columns = ['TIMESTAMP', 'OPEN', 'HIGH', 'LOW', 'CLOSE', 'STRIKE', 'OPEN_C', 'HIGH_C', 'LOW_C', 'CLOSE_C', 'H-O_C', 'L-O_C', 'C-O_C', 'OPEN_P', 'HIGH_P', 'LOW_P', 'CLOSE_P', 'H-O_P', 'L-O_P', 'C-O_P']
options_columns = ['TIMESTAMP', 'EXPIRY_DT', 'SYMBOL', 'STRIKE_PR', 'OPTION_TYP', 'OPEN', 'HIGH', 'LOW', 'CLOSE', 'OPEN_INT', 'CHG_IN_OI']
candle_columns = ['OPEN', 'HIGH', 'LOW', 'CLOSE']
call_candle_columns = [f'{x}_C' for x in CANDLE_COLUMNS]
put_candle_columns = [f'{x}_P' for x in CANDLE_COLUMNS]
pl_candle_columns = [f'PL_{x}' for x in CANDLE_COLUMNS]
constant_columns = ['LOT_SIZE', 'NUM_LOTS', 'TOTAL_LOTS', 'MARGIN_PER_LOT', 'MARGIN_REQUIRED', 'STOP_LOSS', 'STOP_LOSS_TRIGGER']
pl_net_columns = ['NET_PL_LO', 'NET_PL_HI', 'NET_PL_CL']
stop_loss_truth_columns = ['STOP_LOSS_HIT', 'SL_HI_GT_CL']
net_columns = ['NET', '%', 'LOSE_COUNT', 'CUM_LOSE_COUNT', 'CUM_NET']
conversion = {'SYMBOL': 'first', 'OPEN': 'first', 'HIGH': 'max', 'LOW': 'min', 'CLOSE': 'last'}
chain_conversion = {'OPEN_C': 'first', 'HIGH_C': 'max', 'LOW_C': 'min', 'CLOSE_C': 'last', 'OPEN_P': 'first', 'HIGH_P': 'max', 'LOW_P': 'min', 'CLOSE_P': 'last'}
straddle_conversion = {'OPEN_C': 'first', 'HIGH_C': 'max', 'LOW_C': 'min', 'CLOSE_C': 'last', 'OPEN_P': 'first', 'HIGH_P': 'max', 'LOW_P': 'min', 'CLOSE_P': 'last', 'PL_OPEN': 'first', 'PL_HIGH': 'max', 'PL_LOW': 'min', 'PL_CLOSE': 'last'}
strangle_conversion = {'STRIKE_C': 'first', 'OPEN_C': 'first', 'HIGH_C': 'max', 'LOW_C': 'min', 'CLOSE_C': 'last', 'STRIKE_P': 'first', 'OPEN_P': 'first', 'HIGH_P': 'max', 'LOW_P': 'min', 'CLOSE_P': 'last', 'PL_OPEN': 'first', 'PL_HIGH': 'max', 'PL_LOW': 'min', 'PL_CLOSE': 'last'}
iron_butterfly_conversion = {'OPEN_C': 'first', 'HIGH_C': 'max', 'LOW_C': 'min', 'CLOSE_C': 'last', 'OPEN_P': 'first', 'HIGH_P': 'max', 'LOW_P': 'min', 'CLOSE_P': 'last', 'STRIKE_CL': 'first', 'OPEN_CL': 'first', 'HIGH_CL': 'max', 'LOW_CL': 'min', 'CLOSE_CL': 'last', 'STRIKE_PR': 'first', 'OPEN_PR': 'first', 'HIGH_PR': 'max', 'LOW_PR': 'min', 'CLOSE_PR': 'last', 'PL_OPEN': 'first', 'PL_HIGH': 'max', 'PL_LOW': 'min', 'PL_CLOSE': 'last'}
calendar_spread_conversion = {'OPEN_C': 'first', 'HIGH_C': 'max', 'LOW_C': 'min', 'CLOSE_C': 'last', 'OPEN_P': 'first', 'HIGH_P': 'max', 'LOW_P': 'min', 'CLOSE_P': 'last', 'OPEN_CN': 'first', 'HIGH_CN': 'max', 'LOW_CN': 'min', 'CLOSE_CN': 'last', 'OPEN_PN': 'first', 'HIGH_PN': 'max', 'LOW_PN': 'min', 'CLOSE_PN': 'last', 'PL_OPEN': 'first', 'PL_HIGH': 'max', 'PL_LOW': 'min', 'PL_CLOSE': 'last'}
double_ratio_columns = ['STRIKE_ATM', 'OPEN_CA', 'HIGH_CA', 'LOW_CA', 'CLOSE_CA', 'OPEN_PA', 'HIGH_PA', 'LOW_PA', 'CLOSE_PA', 'STRIKE_CS', 'OPEN_CS', 'HIGH_CS', 'LOW_CS', 'CLOSE_CS', 'STRIKE_PS', 'OPEN_PS', 'HIGH_PS', 'LOW_PS', 'CLOSE_PS', 'STRIKE_CL', 'OPEN_CL', 'HIGH_CL', 'LOW_CL', 'CLOSE_CL', 'STRIKE_PL', 'OPEN_PL', 'HIGH_PL', 'LOW_PL', 'CLOSE_PL']
double_ratio_conversion = {'STRIKE_ATM': 'first', 'OPEN_CA': 'first', 'HIGH_CA': 'max', 'LOW_CA': 'min', 'CLOSE_CA': 'last', 'OPEN_PA': 'first', 'HIGH_PA': 'max', 'LOW_PA': 'min', 'CLOSE_PA': 'last', 'STRIKE_CS': 'first', 'OPEN_CS': 'first', 'HIGH_CS': 'max', 'LOW_CS': 'min', 'CLOSE_CS': 'last', 'STRIKE_PS': 'first', 'OPEN_PS': 'first', 'HIGH_PS': 'max', 'LOW_PS': 'min', 'CLOSE_PS': 'last', 'STRIKE_CL': 'first', 'OPEN_CL': 'first', 'HIGH_CL': 'max', 'LOW_CL': 'min', 'CLOSE_CL': 'last', 'STRIKE_PL': 'first', 'OPEN_PL': 'first', 'HIGH_PL': 'max', 'LOW_PL': 'min', 'CLOSE_PL': 'last', 'PL_OPEN': 'first', 'PL_HIGH': 'max', 'PL_LOW': 'min', 'PL_CLOSE': 'last'}
ratio_write_at_max_oi_columns = ['STRIKE_C', 'OPEN_C', 'HIGH_C', 'LOW_C', 'CLOSE_C', 'STRIKE_P', 'OPEN_P', 'HIGH_P', 'LOW_P', 'CLOSE_P', 'STRIKE_CS', 'OPEN_CS', 'HIGH_CS', 'LOW_CS', 'CLOSE_CS', 'STRIKE_PS', 'OPEN_PS', 'HIGH_PS', 'LOW_PS', 'CLOSE_PS']
ratio_write_at_max_oi_conversion = {'STRIKE_C': 'first', 'OPEN_C': 'first', 'HIGH_C': 'max', 'LOW_C': 'min', 'CLOSE_C': 'last', 'STRIKE_P': 'first', 'OPEN_P': 'first', 'HIGH_P': 'max', 'LOW_P': 'min', 'CLOSE_P': 'last', 'STRIKE_CS': 'first', 'OPEN_CS': 'first', 'HIGH_CS': 'max', 'LOW_CS': 'min', 'CLOSE_CS': 'last', 'STRIKE_PS': 'first', 'OPEN_PS': 'first', 'HIGH_PS': 'max', 'LOW_PS': 'min', 'CLOSE_PS': 'last', 'PL_OPEN': 'first', 'PL_HIGH': 'max', 'PL_LOW': 'min', 'PL_CLOSE': 'last'} |
# HAUL strings
def startsWith(s, prefix):
return s.startswith(prefix)
def sub(s, startIndex, endIndex):
return s[startIndex:endIndex]
def rest(s, startIndex):
return s[startIndex:]
def length(s):
return len(s)
class _strings:
def __init__(self, data):
self.data = data
def length(self):
return len(self.data)
def sub(self, startIndex, endIndex):
return self.data[startIndex:endIndex]
def new(s):
return _strings(s)
#print(str(startsWith('lala', 'lo')))
#print(sub('012345', 0, 0)) | def starts_with(s, prefix):
return s.startswith(prefix)
def sub(s, startIndex, endIndex):
return s[startIndex:endIndex]
def rest(s, startIndex):
return s[startIndex:]
def length(s):
return len(s)
class _Strings:
def __init__(self, data):
self.data = data
def length(self):
return len(self.data)
def sub(self, startIndex, endIndex):
return self.data[startIndex:endIndex]
def new(s):
return _strings(s) |
#!python
def linear_search(array, item):
"""return the first index of item in array or None if item is not found"""
# implement linear_search_iterative and linear_search_recursive below, then
# change this to call your implementation to verify it passes all tests
return linear_search_iterative(array, item)
# return linear_search_recursive(array, item)
def linear_search_iterative(array, item):
# loop over all array values until item is found
for index, value in enumerate(array):
if item == value:
return index # found
return None # not found
def linear_search_recursive(array, item, index=0):
if list[index] == item:
return index
if index == len(list):
return None
else:
return linear_search_recursive(array, item, index + 1)
# once implemented, change linear_search to call linear_search_recursive
# to verify that your recursive implementation passes all tests
def binary_search(array, item):
"""return the index of item in sorted array or None if item is not found"""
# implement binary_search_iterative and binary_search_recursive below, then
# change this to call your implementation to verify it passes all tests
# return binary_search_iterative(array, item)
return binary_search_recursive(array, item, left=0, right=len(array)-1)
def binary_search_iterative(array, item):
# once implemented, change binary_search to call binary_search_iterative
# to verify that your iterative implementation passes all tests
#find the middle position/item
#have a start or end (left or right)
#check if the middle item is the target, if so return
#else compare the target to the item in the middle
#if target is less than ite, at the middle we ignore right half
#if target is greater, we ignore the left half
#repeat until target found ot we looked through everything
# [5, 6, 7, 10, 12] item 6 - middle item is 7
# go to middle, is the item to the right greater or less than the target
left_index = 0
right_index = len(array) - 1
while left_index <= right_index:
mid_index = (right_index + left_index) // 2
if array[mid_index] == item:
return mid_index
#if item < array[mid_index] ignore right
elif item < array[mid_index]:
# change right index to
right_index = mid_index -1
#if item < array[mid_index] ignore right
elif item > array[mid_index]:
#change left index to
left_index = mid_index + 1
def binary_search_recursive(array, item, left=None, right=None):
mid_index = (left + right) // 2
if array[mid_index] == item:
return mid_index
elif left > right:
return None
if array[mid_index] < item:
return binary_search_recursive(array, item, left + 1, right)
if array[mid_index] > item:
return binary_search_recursive(array, item, left, right - 1)
# once implemented, change binary_search to call binary_search_recursive
# to verify that your recursive implementation passes all tests
| def linear_search(array, item):
"""return the first index of item in array or None if item is not found"""
return linear_search_iterative(array, item)
def linear_search_iterative(array, item):
for (index, value) in enumerate(array):
if item == value:
return index
return None
def linear_search_recursive(array, item, index=0):
if list[index] == item:
return index
if index == len(list):
return None
else:
return linear_search_recursive(array, item, index + 1)
def binary_search(array, item):
"""return the index of item in sorted array or None if item is not found"""
return binary_search_recursive(array, item, left=0, right=len(array) - 1)
def binary_search_iterative(array, item):
left_index = 0
right_index = len(array) - 1
while left_index <= right_index:
mid_index = (right_index + left_index) // 2
if array[mid_index] == item:
return mid_index
elif item < array[mid_index]:
right_index = mid_index - 1
elif item > array[mid_index]:
left_index = mid_index + 1
def binary_search_recursive(array, item, left=None, right=None):
mid_index = (left + right) // 2
if array[mid_index] == item:
return mid_index
elif left > right:
return None
if array[mid_index] < item:
return binary_search_recursive(array, item, left + 1, right)
if array[mid_index] > item:
return binary_search_recursive(array, item, left, right - 1) |
def printGraph(graph):
for node in graph:
print(node.toString())
def drawAsMatrix(graph, size = 3):
ret = list()
line = list()
lastLine = 0
for i in range(0, len(graph)):
ii = int(i/size)
if not lastLine == ii:
ret.append(line)
lastLine = ii
line = list()
if(graph[i].notEmpty):
line.append(' ')
else:
line.append('O')
ret.append(line)
finished = ""
for i in range(0,size):
line = ""
for j in range(0,size):
if(j == 0):
line = f"{ret[size-i-1][j]}"
else:
line = f"{line} ][ {ret[size-i-1][j]}"
finished = f"{finished}\n[ {line} ]"
return finished;
| def print_graph(graph):
for node in graph:
print(node.toString())
def draw_as_matrix(graph, size=3):
ret = list()
line = list()
last_line = 0
for i in range(0, len(graph)):
ii = int(i / size)
if not lastLine == ii:
ret.append(line)
last_line = ii
line = list()
if graph[i].notEmpty:
line.append(' ')
else:
line.append('O')
ret.append(line)
finished = ''
for i in range(0, size):
line = ''
for j in range(0, size):
if j == 0:
line = f'{ret[size - i - 1][j]}'
else:
line = f'{line} ][ {ret[size - i - 1][j]}'
finished = f'{finished}\n[ {line} ]'
return finished |
#
# PySNMP MIB module ATM-FORUM-TC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ATM-FORUM-TC-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:15:02 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, ConstraintsUnion, ConstraintsIntersection, ValueRangeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "ValueRangeConstraint", "SingleValueConstraint")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
Integer32, Counter64, ModuleIdentity, MibIdentifier, iso, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32, Unsigned32, IpAddress, Bits, Counter32, enterprises, NotificationType, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "Counter64", "ModuleIdentity", "MibIdentifier", "iso", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Gauge32", "Unsigned32", "IpAddress", "Bits", "Counter32", "enterprises", "NotificationType", "TimeTicks")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
class TruthValue(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))
namedValues = NamedValues(("true", 1), ("false", 2))
class ClnpAddress(TextualConvention, OctetString):
status = 'current'
subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(1, 21)
class AtmServiceCategory(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))
namedValues = NamedValues(("other", 1), ("cbr", 2), ("rtVbr", 3), ("nrtVbr", 4), ("abr", 5), ("ubr", 6))
class AtmAddress(TextualConvention, OctetString):
status = 'current'
subtypeSpec = OctetString.subtypeSpec + ConstraintsUnion(ValueSizeConstraint(8, 8), ValueSizeConstraint(20, 20), )
class NetPrefix(TextualConvention, OctetString):
status = 'current'
subtypeSpec = OctetString.subtypeSpec + ConstraintsUnion(ValueSizeConstraint(8, 8), ValueSizeConstraint(13, 13), )
atmForum = MibIdentifier((1, 3, 6, 1, 4, 1, 353))
atmForumAdmin = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1))
atmfTransmissionTypes = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 2))
atmfMediaTypes = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 3))
atmfTrafficDescrTypes = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 4))
atmfSrvcRegTypes = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 5))
atmForumUni = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 2))
atmfPhysicalGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 2, 1))
atmfAtmLayerGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 2, 2))
atmfAtmStatsGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 2, 3))
atmfVpcGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 2, 4))
atmfVccGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 2, 5))
atmfAddressGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 2, 6))
atmfNetPrefixGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 2, 7))
atmfSrvcRegistryGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 2, 8))
atmfVpcAbrGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 2, 9))
atmfVccAbrGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 2, 10))
atmfAddressRegistrationAdminGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 2, 11))
atmfUnknownType = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 2, 1))
atmfSonetSTS3c = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 2, 2))
atmfDs3 = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 2, 3))
atmf4B5B = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 2, 4))
atmf8B10B = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 2, 5))
atmfSonetSTS12c = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 2, 6))
atmfE3 = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 2, 7))
atmfT1 = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 2, 8))
atmfE1 = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 2, 9))
atmfMediaUnknownType = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 3, 1))
atmfMediaCoaxCable = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 3, 2))
atmfMediaSingleMode = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 3, 3))
atmfMediaMultiMode = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 3, 4))
atmfMediaStp = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 3, 5))
atmfMediaUtp = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 3, 6))
atmfNoDescriptor = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 4, 1))
atmfPeakRate = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 4, 2))
atmfNoClpNoScr = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 4, 3))
atmfClpNoTaggingNoScr = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 4, 4))
atmfClpTaggingNoScr = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 4, 5))
atmfNoClpScr = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 4, 6))
atmfClpNoTaggingScr = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 4, 7))
atmfClpTaggingScr = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 4, 8))
atmfClpNoTaggingMcr = MibIdentifier((1, 3, 6, 1, 4, 1, 353, 1, 4, 9))
mibBuilder.exportSymbols("ATM-FORUM-TC-MIB", atmfMediaUtp=atmfMediaUtp, atmfVccAbrGroup=atmfVccAbrGroup, atmfAddressRegistrationAdminGroup=atmfAddressRegistrationAdminGroup, atmfAtmLayerGroup=atmfAtmLayerGroup, NetPrefix=NetPrefix, atmfSonetSTS12c=atmfSonetSTS12c, atmfSrvcRegistryGroup=atmfSrvcRegistryGroup, atmfDs3=atmfDs3, atmfE3=atmfE3, atmfUnknownType=atmfUnknownType, atmf8B10B=atmf8B10B, atmfPeakRate=atmfPeakRate, TruthValue=TruthValue, atmfClpTaggingScr=atmfClpTaggingScr, atmForum=atmForum, atmfMediaMultiMode=atmfMediaMultiMode, atmfMediaCoaxCable=atmfMediaCoaxCable, atmfNoDescriptor=atmfNoDescriptor, atmf4B5B=atmf4B5B, atmfAddressGroup=atmfAddressGroup, atmfMediaStp=atmfMediaStp, atmForumUni=atmForumUni, atmfTrafficDescrTypes=atmfTrafficDescrTypes, atmfSrvcRegTypes=atmfSrvcRegTypes, atmfE1=atmfE1, atmfNoClpNoScr=atmfNoClpNoScr, AtmAddress=AtmAddress, atmfPhysicalGroup=atmfPhysicalGroup, atmfNetPrefixGroup=atmfNetPrefixGroup, atmfMediaSingleMode=atmfMediaSingleMode, atmfClpNoTaggingMcr=atmfClpNoTaggingMcr, AtmServiceCategory=AtmServiceCategory, atmfClpTaggingNoScr=atmfClpTaggingNoScr, atmfClpNoTaggingScr=atmfClpNoTaggingScr, atmfClpNoTaggingNoScr=atmfClpNoTaggingNoScr, atmfAtmStatsGroup=atmfAtmStatsGroup, atmfMediaUnknownType=atmfMediaUnknownType, atmfNoClpScr=atmfNoClpScr, atmForumAdmin=atmForumAdmin, atmfTransmissionTypes=atmfTransmissionTypes, atmfVccGroup=atmfVccGroup, ClnpAddress=ClnpAddress, atmfSonetSTS3c=atmfSonetSTS3c, atmfVpcAbrGroup=atmfVpcAbrGroup, atmfT1=atmfT1, atmfMediaTypes=atmfMediaTypes, atmfVpcGroup=atmfVpcGroup)
| (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_union, constraints_intersection, value_range_constraint, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueSizeConstraint', 'ConstraintsUnion', 'ConstraintsIntersection', 'ValueRangeConstraint', 'SingleValueConstraint')
(module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup')
(integer32, counter64, module_identity, mib_identifier, iso, object_identity, mib_scalar, mib_table, mib_table_row, mib_table_column, gauge32, unsigned32, ip_address, bits, counter32, enterprises, notification_type, time_ticks) = mibBuilder.importSymbols('SNMPv2-SMI', 'Integer32', 'Counter64', 'ModuleIdentity', 'MibIdentifier', 'iso', 'ObjectIdentity', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Gauge32', 'Unsigned32', 'IpAddress', 'Bits', 'Counter32', 'enterprises', 'NotificationType', 'TimeTicks')
(display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention')
class Truthvalue(TextualConvention, Integer32):
status = 'current'
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2))
named_values = named_values(('true', 1), ('false', 2))
class Clnpaddress(TextualConvention, OctetString):
status = 'current'
subtype_spec = OctetString.subtypeSpec + value_size_constraint(1, 21)
class Atmservicecategory(TextualConvention, Integer32):
status = 'current'
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6))
named_values = named_values(('other', 1), ('cbr', 2), ('rtVbr', 3), ('nrtVbr', 4), ('abr', 5), ('ubr', 6))
class Atmaddress(TextualConvention, OctetString):
status = 'current'
subtype_spec = OctetString.subtypeSpec + constraints_union(value_size_constraint(8, 8), value_size_constraint(20, 20))
class Netprefix(TextualConvention, OctetString):
status = 'current'
subtype_spec = OctetString.subtypeSpec + constraints_union(value_size_constraint(8, 8), value_size_constraint(13, 13))
atm_forum = mib_identifier((1, 3, 6, 1, 4, 1, 353))
atm_forum_admin = mib_identifier((1, 3, 6, 1, 4, 1, 353, 1))
atmf_transmission_types = mib_identifier((1, 3, 6, 1, 4, 1, 353, 1, 2))
atmf_media_types = mib_identifier((1, 3, 6, 1, 4, 1, 353, 1, 3))
atmf_traffic_descr_types = mib_identifier((1, 3, 6, 1, 4, 1, 353, 1, 4))
atmf_srvc_reg_types = mib_identifier((1, 3, 6, 1, 4, 1, 353, 1, 5))
atm_forum_uni = mib_identifier((1, 3, 6, 1, 4, 1, 353, 2))
atmf_physical_group = mib_identifier((1, 3, 6, 1, 4, 1, 353, 2, 1))
atmf_atm_layer_group = mib_identifier((1, 3, 6, 1, 4, 1, 353, 2, 2))
atmf_atm_stats_group = mib_identifier((1, 3, 6, 1, 4, 1, 353, 2, 3))
atmf_vpc_group = mib_identifier((1, 3, 6, 1, 4, 1, 353, 2, 4))
atmf_vcc_group = mib_identifier((1, 3, 6, 1, 4, 1, 353, 2, 5))
atmf_address_group = mib_identifier((1, 3, 6, 1, 4, 1, 353, 2, 6))
atmf_net_prefix_group = mib_identifier((1, 3, 6, 1, 4, 1, 353, 2, 7))
atmf_srvc_registry_group = mib_identifier((1, 3, 6, 1, 4, 1, 353, 2, 8))
atmf_vpc_abr_group = mib_identifier((1, 3, 6, 1, 4, 1, 353, 2, 9))
atmf_vcc_abr_group = mib_identifier((1, 3, 6, 1, 4, 1, 353, 2, 10))
atmf_address_registration_admin_group = mib_identifier((1, 3, 6, 1, 4, 1, 353, 2, 11))
atmf_unknown_type = mib_identifier((1, 3, 6, 1, 4, 1, 353, 1, 2, 1))
atmf_sonet_sts3c = mib_identifier((1, 3, 6, 1, 4, 1, 353, 1, 2, 2))
atmf_ds3 = mib_identifier((1, 3, 6, 1, 4, 1, 353, 1, 2, 3))
atmf4_b5_b = mib_identifier((1, 3, 6, 1, 4, 1, 353, 1, 2, 4))
atmf8_b10_b = mib_identifier((1, 3, 6, 1, 4, 1, 353, 1, 2, 5))
atmf_sonet_sts12c = mib_identifier((1, 3, 6, 1, 4, 1, 353, 1, 2, 6))
atmf_e3 = mib_identifier((1, 3, 6, 1, 4, 1, 353, 1, 2, 7))
atmf_t1 = mib_identifier((1, 3, 6, 1, 4, 1, 353, 1, 2, 8))
atmf_e1 = mib_identifier((1, 3, 6, 1, 4, 1, 353, 1, 2, 9))
atmf_media_unknown_type = mib_identifier((1, 3, 6, 1, 4, 1, 353, 1, 3, 1))
atmf_media_coax_cable = mib_identifier((1, 3, 6, 1, 4, 1, 353, 1, 3, 2))
atmf_media_single_mode = mib_identifier((1, 3, 6, 1, 4, 1, 353, 1, 3, 3))
atmf_media_multi_mode = mib_identifier((1, 3, 6, 1, 4, 1, 353, 1, 3, 4))
atmf_media_stp = mib_identifier((1, 3, 6, 1, 4, 1, 353, 1, 3, 5))
atmf_media_utp = mib_identifier((1, 3, 6, 1, 4, 1, 353, 1, 3, 6))
atmf_no_descriptor = mib_identifier((1, 3, 6, 1, 4, 1, 353, 1, 4, 1))
atmf_peak_rate = mib_identifier((1, 3, 6, 1, 4, 1, 353, 1, 4, 2))
atmf_no_clp_no_scr = mib_identifier((1, 3, 6, 1, 4, 1, 353, 1, 4, 3))
atmf_clp_no_tagging_no_scr = mib_identifier((1, 3, 6, 1, 4, 1, 353, 1, 4, 4))
atmf_clp_tagging_no_scr = mib_identifier((1, 3, 6, 1, 4, 1, 353, 1, 4, 5))
atmf_no_clp_scr = mib_identifier((1, 3, 6, 1, 4, 1, 353, 1, 4, 6))
atmf_clp_no_tagging_scr = mib_identifier((1, 3, 6, 1, 4, 1, 353, 1, 4, 7))
atmf_clp_tagging_scr = mib_identifier((1, 3, 6, 1, 4, 1, 353, 1, 4, 8))
atmf_clp_no_tagging_mcr = mib_identifier((1, 3, 6, 1, 4, 1, 353, 1, 4, 9))
mibBuilder.exportSymbols('ATM-FORUM-TC-MIB', atmfMediaUtp=atmfMediaUtp, atmfVccAbrGroup=atmfVccAbrGroup, atmfAddressRegistrationAdminGroup=atmfAddressRegistrationAdminGroup, atmfAtmLayerGroup=atmfAtmLayerGroup, NetPrefix=NetPrefix, atmfSonetSTS12c=atmfSonetSTS12c, atmfSrvcRegistryGroup=atmfSrvcRegistryGroup, atmfDs3=atmfDs3, atmfE3=atmfE3, atmfUnknownType=atmfUnknownType, atmf8B10B=atmf8B10B, atmfPeakRate=atmfPeakRate, TruthValue=TruthValue, atmfClpTaggingScr=atmfClpTaggingScr, atmForum=atmForum, atmfMediaMultiMode=atmfMediaMultiMode, atmfMediaCoaxCable=atmfMediaCoaxCable, atmfNoDescriptor=atmfNoDescriptor, atmf4B5B=atmf4B5B, atmfAddressGroup=atmfAddressGroup, atmfMediaStp=atmfMediaStp, atmForumUni=atmForumUni, atmfTrafficDescrTypes=atmfTrafficDescrTypes, atmfSrvcRegTypes=atmfSrvcRegTypes, atmfE1=atmfE1, atmfNoClpNoScr=atmfNoClpNoScr, AtmAddress=AtmAddress, atmfPhysicalGroup=atmfPhysicalGroup, atmfNetPrefixGroup=atmfNetPrefixGroup, atmfMediaSingleMode=atmfMediaSingleMode, atmfClpNoTaggingMcr=atmfClpNoTaggingMcr, AtmServiceCategory=AtmServiceCategory, atmfClpTaggingNoScr=atmfClpTaggingNoScr, atmfClpNoTaggingScr=atmfClpNoTaggingScr, atmfClpNoTaggingNoScr=atmfClpNoTaggingNoScr, atmfAtmStatsGroup=atmfAtmStatsGroup, atmfMediaUnknownType=atmfMediaUnknownType, atmfNoClpScr=atmfNoClpScr, atmForumAdmin=atmForumAdmin, atmfTransmissionTypes=atmfTransmissionTypes, atmfVccGroup=atmfVccGroup, ClnpAddress=ClnpAddress, atmfSonetSTS3c=atmfSonetSTS3c, atmfVpcAbrGroup=atmfVpcAbrGroup, atmfT1=atmfT1, atmfMediaTypes=atmfMediaTypes, atmfVpcGroup=atmfVpcGroup) |
weight = input('Please input your weight(kg)...>')
height = input('Please input your height(cm)...>')
weight = float(weight)
height = float(height) / 100
bmi = weight / (height ** 2)
print('{:>7s}\t{:> 3.2f}\tkg'.format('Weight', weight))
print('{:>7s}\t{:> 3.2f}\tcm'.format('Height', height*100))
print('{:>7s}\t{:> 3.2f}'.format('BMI', bmi))
if 18.5 <= bmi < 24:
print("It's good!") | weight = input('Please input your weight(kg)...>')
height = input('Please input your height(cm)...>')
weight = float(weight)
height = float(height) / 100
bmi = weight / height ** 2
print('{:>7s}\t{:> 3.2f}\tkg'.format('Weight', weight))
print('{:>7s}\t{:> 3.2f}\tcm'.format('Height', height * 100))
print('{:>7s}\t{:> 3.2f}'.format('BMI', bmi))
if 18.5 <= bmi < 24:
print("It's good!") |
class BuildLog:
FILE = 0
LINE_NUMBER = 1
WARNING_CODE = 2
MESSAGE = 3
def __init__(self, filePath):
self._file = open(filePath, 'r')
self._parseLog()
def _parseLog(self):
self._lines = self._file.readlines()
self._lines[:] = [line for line in self._lines if ": warning" in line]
self.warnings = [[0 for i in range(4)] for y in range(len(self._lines))]
for index, line in enumerate(self._lines):
self._lines[index] = line.split(":")
self._lines[index][0] = self._lines[index][0][:-1].split("(")
self.warnings[index][self.FILE] = self._lines[index][0][0]
self.warnings[index][self.LINE_NUMBER] = int(self._lines[index][0][1].split(",")[0])
self.warnings[index][self.WARNING_CODE] = self._lines[index][1]
self.warnings[index][self.MESSAGE] = self._lines[index][2].split("[/")[0]
def __del__(self):
self._file.close()
if __name__ == "__main__":
logPath = "../../build.log"
logs = BuildLog(logPath)
print(logs.warnings)
| class Buildlog:
file = 0
line_number = 1
warning_code = 2
message = 3
def __init__(self, filePath):
self._file = open(filePath, 'r')
self._parseLog()
def _parse_log(self):
self._lines = self._file.readlines()
self._lines[:] = [line for line in self._lines if ': warning' in line]
self.warnings = [[0 for i in range(4)] for y in range(len(self._lines))]
for (index, line) in enumerate(self._lines):
self._lines[index] = line.split(':')
self._lines[index][0] = self._lines[index][0][:-1].split('(')
self.warnings[index][self.FILE] = self._lines[index][0][0]
self.warnings[index][self.LINE_NUMBER] = int(self._lines[index][0][1].split(',')[0])
self.warnings[index][self.WARNING_CODE] = self._lines[index][1]
self.warnings[index][self.MESSAGE] = self._lines[index][2].split('[/')[0]
def __del__(self):
self._file.close()
if __name__ == '__main__':
log_path = '../../build.log'
logs = build_log(logPath)
print(logs.warnings) |
DEBUG = True
SECRET_KEY = "Some secret key"
HOST = "127.0.0.1"
PORT = 5000
| debug = True
secret_key = 'Some secret key'
host = '127.0.0.1'
port = 5000 |
# !/usr/bin/env python3
# -*- cosing: utf-8 -*-
fileprt = open("file2.txt", "r")
content1 = fileptr.readline()
content2 = fileptr.readline()
print(content1)
print(content2)
fileprt.close()
| fileprt = open('file2.txt', 'r')
content1 = fileptr.readline()
content2 = fileptr.readline()
print(content1)
print(content2)
fileprt.close() |
human = {
"PSSM_folder": '../data/Malonylation/Human/PSSM/',
"SPD3_folder": '../data/Malonylation/Human/SPD3/',
"encoded_file": '../data/Malonylation/Human/HM_encoded.csv',
"data_folder": '../data/Malonylation/Human/HSA+SPD3/',
"output": '../data/lemp/human/lemp_features.npz',
"output_lemp_compare": '../data/lemp/human/semal_features.npz',
"model": "../data/rotation_forest_human.pkl",
}
mice = {
"PSSM_folder": '../data/Malonylation/Mice/PSSM/',
"SPD3_folder": '../data/Malonylation/Mice/SPD3/',
"encoded_file": '../data/Malonylation/Mice/MM_encoded.csv',
"data_folder": '../data/Malonylation/Mice/HSA+SPD3/',
"output": '../data/lemp/mice/lemp_features.npz',
"output_lemp_compare": '../data/lemp/mice/semal_features.npz',
"model": "../data/rotation_forest_mice.pkl",
}
| human = {'PSSM_folder': '../data/Malonylation/Human/PSSM/', 'SPD3_folder': '../data/Malonylation/Human/SPD3/', 'encoded_file': '../data/Malonylation/Human/HM_encoded.csv', 'data_folder': '../data/Malonylation/Human/HSA+SPD3/', 'output': '../data/lemp/human/lemp_features.npz', 'output_lemp_compare': '../data/lemp/human/semal_features.npz', 'model': '../data/rotation_forest_human.pkl'}
mice = {'PSSM_folder': '../data/Malonylation/Mice/PSSM/', 'SPD3_folder': '../data/Malonylation/Mice/SPD3/', 'encoded_file': '../data/Malonylation/Mice/MM_encoded.csv', 'data_folder': '../data/Malonylation/Mice/HSA+SPD3/', 'output': '../data/lemp/mice/lemp_features.npz', 'output_lemp_compare': '../data/lemp/mice/semal_features.npz', 'model': '../data/rotation_forest_mice.pkl'} |
#It will print the index of e
vowels = ['a', 'e', 'i', 'o', 'i']
index = vowels.index("e")
print(index)
#It will print the index of o
vowels = ['a', 'e', 'i', 'o', 'i']
index=vowels.index("o")
print(index)
| vowels = ['a', 'e', 'i', 'o', 'i']
index = vowels.index('e')
print(index)
vowels = ['a', 'e', 'i', 'o', 'i']
index = vowels.index('o')
print(index) |
print('Welcome to the tip calculator!')
bill = float(input('What was the total bill? $'))
tip = float(input('What percentage tip would you like to give? 10%, 12% or 15% ')) / 100
n_people = int(input('How many people to split the bill? '))
bill_person = (bill + bill * tip) / n_people
print(f'Each person should pay ${bill_person:.2f}')
| print('Welcome to the tip calculator!')
bill = float(input('What was the total bill? $'))
tip = float(input('What percentage tip would you like to give? 10%, 12% or 15% ')) / 100
n_people = int(input('How many people to split the bill? '))
bill_person = (bill + bill * tip) / n_people
print(f'Each person should pay ${bill_person:.2f}') |
"""This is for opening and closing files with a few other features tucked in
for fun"""
def addToFile(filename, information, overwrite=False):
'''(str, str [, bool]) -> True
add content to the end of a file, or create a new file'''
if overwrite:
file = open(filename, "w")
file.write(information)
file.close()
else:
try:
file = open(filename, "r")
filetowrite =file.read()+information
file.close()
file = open(filename, "w")
file.write(filetowrite)
file.close()
except:
file = open(filename, "w")
file.write(information)
file.close()
return True
def retrieveFile(filename, binary=False):
'''(str [, bool]) -> str
retrieve file at location filename, return file contents'''
if binary:
file = open(filename, "rb")
else:
file = open(filename, "r")
fileInfo = file.read()
file.close() #always close your files, kids!
return fileInfo
def retrieveFileLines(filename, binary=False):
'''(str [, bool]) -> list of str
retrieve file a location filename, return file line by line'''
if binary:
file = open(filename, "rb")
else:
file = open(filename, "r")
fileInfo = file.readlines()
file.close() #always close your files, kids!
return fileInfo
def writeFile(filename, information, binary=False, returnFile=False):
'''(str, str [, bool, bool]) -> str (if returnFile == True) or True
write information to file a location filename'''
if binary:
file = open(filename, "wb")
else:
file = open(filename, "w")
file.write(information)
file.close()
if returnFile:
if binary:
file = open(filename, "rb")
fileInfo=file.read()
else:
file = open(filename, "r")
fileInfo=file.read()
file.close()
return fileInfo
else:
return True
| """This is for opening and closing files with a few other features tucked in
for fun"""
def add_to_file(filename, information, overwrite=False):
"""(str, str [, bool]) -> True
add content to the end of a file, or create a new file"""
if overwrite:
file = open(filename, 'w')
file.write(information)
file.close()
else:
try:
file = open(filename, 'r')
filetowrite = file.read() + information
file.close()
file = open(filename, 'w')
file.write(filetowrite)
file.close()
except:
file = open(filename, 'w')
file.write(information)
file.close()
return True
def retrieve_file(filename, binary=False):
"""(str [, bool]) -> str
retrieve file at location filename, return file contents"""
if binary:
file = open(filename, 'rb')
else:
file = open(filename, 'r')
file_info = file.read()
file.close()
return fileInfo
def retrieve_file_lines(filename, binary=False):
"""(str [, bool]) -> list of str
retrieve file a location filename, return file line by line"""
if binary:
file = open(filename, 'rb')
else:
file = open(filename, 'r')
file_info = file.readlines()
file.close()
return fileInfo
def write_file(filename, information, binary=False, returnFile=False):
"""(str, str [, bool, bool]) -> str (if returnFile == True) or True
write information to file a location filename"""
if binary:
file = open(filename, 'wb')
else:
file = open(filename, 'w')
file.write(information)
file.close()
if returnFile:
if binary:
file = open(filename, 'rb')
file_info = file.read()
else:
file = open(filename, 'r')
file_info = file.read()
file.close()
return fileInfo
else:
return True |
arr = list(map(int, input().split()))
n = int(input())
for i in range(n, len(arr)):
print(arr[i], end = ' ')
for i in range(n):
print(arr[i], end = ' ') | arr = list(map(int, input().split()))
n = int(input())
for i in range(n, len(arr)):
print(arr[i], end=' ')
for i in range(n):
print(arr[i], end=' ') |
class BreakingTheCode:
def decodingEncoding(self, code, message):
if 'a' <= message[0] <= 'z':
return ''.join('{0:02}'.format(code.index(e)+1) for e in message)
d = dict(('{0:02}'.format(i), e) for i, e in enumerate(code, 1))
return ''.join(d[message[i:i+2]] for i in xrange(0, len(message), 2))
| class Breakingthecode:
def decoding_encoding(self, code, message):
if 'a' <= message[0] <= 'z':
return ''.join(('{0:02}'.format(code.index(e) + 1) for e in message))
d = dict((('{0:02}'.format(i), e) for (i, e) in enumerate(code, 1)))
return ''.join((d[message[i:i + 2]] for i in xrange(0, len(message), 2))) |
def leia_float ():
while True:
try:
num = float(input('Digite um numero real: ').replace(',', '.'))
except (ValueError, TypeError):
print('Por favor, digite um numero real valido! ')
else:
return num
def leia_int ():
while True:
try:
num = int(input('Digite um numero inteiro valido: '))
except (ValueError, TypeError):
print('Por favor digite um numero inteiro valido! ')
else:
return num
n1 = leia_int()
n2 = leia_float()
print(f'O numero inteiro digitado foi {n1} e o real {n2} ')
| def leia_float():
while True:
try:
num = float(input('Digite um numero real: ').replace(',', '.'))
except (ValueError, TypeError):
print('Por favor, digite um numero real valido! ')
else:
return num
def leia_int():
while True:
try:
num = int(input('Digite um numero inteiro valido: '))
except (ValueError, TypeError):
print('Por favor digite um numero inteiro valido! ')
else:
return num
n1 = leia_int()
n2 = leia_float()
print(f'O numero inteiro digitado foi {n1} e o real {n2} ') |
with open('foo.txt', 'r') as file_read:
for line in file_read: # NOTA: mejor que file_read.readlines():
print(line, end='') | with open('foo.txt', 'r') as file_read:
for line in file_read:
print(line, end='') |
# basic generator function
# def myGen(n):
# yield n
# yield n+1
# g = myGen(1)
# print(next(g))
# print(next(g))
# print(next(g))
def myGen():
yield "These"
yield "words"
yield "come"
yield "one"
yield "at"
yield "a"
yield "time"
gen = myGen()
for i in range(1, 9):
print(next(gen))
| def my_gen():
yield 'These'
yield 'words'
yield 'come'
yield 'one'
yield 'at'
yield 'a'
yield 'time'
gen = my_gen()
for i in range(1, 9):
print(next(gen)) |
class Solution:
def arrayNesting(self, nums: List[int]) -> int:
result = 0
for i in range(len(nums)):
if nums[i] != -1:
start, count = nums[i], 0
while nums[start] != -1:
temp = start
start = nums[start]
count += 1
nums[temp] = -1
result = max(result, count)
return result | class Solution:
def array_nesting(self, nums: List[int]) -> int:
result = 0
for i in range(len(nums)):
if nums[i] != -1:
(start, count) = (nums[i], 0)
while nums[start] != -1:
temp = start
start = nums[start]
count += 1
nums[temp] = -1
result = max(result, count)
return result |
# Practice_#1
# Quick Brown Fox
# Use a for loop to take a list and print each element of the list in its own line.
sentence = ["the", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"]
# Method_#1
for word in sentence:
print(word)
# Method_#2
'''
for index in range(0, len(sentence) ):
print( sentence[index] )
'''
# Practice_#2
# Multiples of 5
# Write a for loop below
# that will print out every whole number that is a multiple of 5 and less than or equal to 30.
for number in range( 5, 31, 5):
print(number) | sentence = ['the', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog']
for word in sentence:
print(word)
'\nfor index in range(0, len(sentence) ):\n print( sentence[index] )\n'
for number in range(5, 31, 5):
print(number) |
## Based off of example at http://pro.arcgis.com/en/pro-app/tool-reference/data-management/calculate-field-examples.htm#ESRI_SECTION1_F3F8CD77A9F647ABBA678A76ADB86E15
## Goal: calculate the percent increase of a numeric field
## Example use case: identify the rate of temperate increase as weather stations move inland
## Steps:
# 1. save the current value as "lastValue"
# 2. define the value in the next row as "newValue"
# 3. calculate the percent change between the two values
## Example list of field value (replace to try out various numbers):
fieldValue = [50.5, 50.6, 55.7, 60, 70.1]
## Code Block:
lastValue = 0
def percentIncrease(newValue):
global lastValue
if lastValue:
percentage = ((newValue - lastValue) / lastValue) * 100
else:
percentage = 0
lastValue = newValue
return percentage
## Expression:
# In ArcGIS, the expression will be:
# percentIncrease(float(!fieldname!))
# In a standard Python editor, exclaimation points are uncessary
# and we have to iterate over each value in the list (ArcGIS does this automatically
# for the selected field, !fieldname!)
for value in fieldValue :
percentage = percentIncrease(value)
print(percentage) | field_value = [50.5, 50.6, 55.7, 60, 70.1]
last_value = 0
def percent_increase(newValue):
global lastValue
if lastValue:
percentage = (newValue - lastValue) / lastValue * 100
else:
percentage = 0
last_value = newValue
return percentage
for value in fieldValue:
percentage = percent_increase(value)
print(percentage) |
word = input('')
word_count = 0
start = 0
croatia_word = [['c=', 'c-', 'dz=', 'd-', 'lj', 'nj', 's=', 'z=']]
for i in range(len(croatia_word[0])):
for j in range(len(croatia_word[0])):
croatia = str(croatia_word[0][j])
if word.find(croatia, start) != -1:
word_count += 1
start += len(croatia)
word_count += len(word) - start
print(word_count) | word = input('')
word_count = 0
start = 0
croatia_word = [['c=', 'c-', 'dz=', 'd-', 'lj', 'nj', 's=', 'z=']]
for i in range(len(croatia_word[0])):
for j in range(len(croatia_word[0])):
croatia = str(croatia_word[0][j])
if word.find(croatia, start) != -1:
word_count += 1
start += len(croatia)
word_count += len(word) - start
print(word_count) |
class SimpleWeightedEnsemble(object):
def __init__(self):
super(SimpleWeightedEnsemble, self).__init__()
class XGBoostEnsemble(object):
def __init__(self):
super(XGBoostEnsemble, self).__init__()
class MLPEnsemble(object):
def __init__(self):
super(MLPEnsemble, self).__init__()
| class Simpleweightedensemble(object):
def __init__(self):
super(SimpleWeightedEnsemble, self).__init__()
class Xgboostensemble(object):
def __init__(self):
super(XGBoostEnsemble, self).__init__()
class Mlpensemble(object):
def __init__(self):
super(MLPEnsemble, self).__init__() |
"""
LEETCODE 278 - FIRST BAD VERSION
coded by Fatih Cinar
on January 13th, 2020
"""
# The isBadVersion API is already defined for you.
# @param version, an integer
# @return a bool
# def isBadVersion(version):
class Solution:
def recFindFirstBadVersion(self, low, high):
"""
This method will figure out
the first bad version using Binary Search Algorimthm
RECURSIVE IMPLEMENTATION
"""
middle = int((low + high) / 2)
if(high == low + 1):
# EXIT CASE
# if high is only one greater than low
# this means that high has been diagnosed as BAD Before
# so HIGH IS THE FIRST BAD VERSION
return high
elif(isBadVersion(middle)):
# if the middle element is BAD
# do not further search successor version of the middle
return self.recFindFirstBadVersion(low, middle)
else:
# if the middle elemeent is CLEAN
# do not search for the previous versions
# because they are also clean
return self.recFindFirstBadVersion(middle, high)
def firstBadVersion(self, numberOfVersions):
"""
:type numberOfVersions: int
:rtype: int
"""
# for low we pass 0
return self.recFindFirstBadVersion(0, numberOfVersions)
| """
LEETCODE 278 - FIRST BAD VERSION
coded by Fatih Cinar
on January 13th, 2020
"""
class Solution:
def rec_find_first_bad_version(self, low, high):
"""
This method will figure out
the first bad version using Binary Search Algorimthm
RECURSIVE IMPLEMENTATION
"""
middle = int((low + high) / 2)
if high == low + 1:
return high
elif is_bad_version(middle):
return self.recFindFirstBadVersion(low, middle)
else:
return self.recFindFirstBadVersion(middle, high)
def first_bad_version(self, numberOfVersions):
"""
:type numberOfVersions: int
:rtype: int
"""
return self.recFindFirstBadVersion(0, numberOfVersions) |
class MyMath:
def add(self, a, b):
if type(a) == list:
if type(b) == list:
return [i + j for i,j in zip(a,b)]
else:
return [i + b for i in a]
else:
return a + b
def pow(self, base, power):
if type(base) == list:
# ALL YOUR BASE ARE BELONG TO US!
return [i ** power for i in base]
else:
return base ** power
def scale(self, val, src, dst):
# Thanks, Stackoverflow http://stackoverflow.com/a/4155197/1778122
return ((val - src[0]) / (src[1]-src[0])) * (dst[1] - dst[0]) + dst[0] | class Mymath:
def add(self, a, b):
if type(a) == list:
if type(b) == list:
return [i + j for (i, j) in zip(a, b)]
else:
return [i + b for i in a]
else:
return a + b
def pow(self, base, power):
if type(base) == list:
return [i ** power for i in base]
else:
return base ** power
def scale(self, val, src, dst):
return (val - src[0]) / (src[1] - src[0]) * (dst[1] - dst[0]) + dst[0] |
# Configuration file of staticmapservice
HEADERS = {'User-Agent':'staticmapservice/0.0.1'}
TILE_SERVER = 'http://a.tile.osm.org/{z}/{x}/{y}.png'
IS_TMS = False # True if you use a TMS instead of OSM XYZ tiles
# Default values can be overwritten in each request
DEFAULT_WIDTH = '300'
DEFAULT_HEIGHT = '200'
DEFAULT_ZOOM = '10'
# Maximum values can't be overwritten
MAX_WIDTH = '800'
MAX_HEIGHT = '800'
MAX_ZOOM = 19
MAX_PNV = '30' # Map won't contain more points, nodes and vertices than this value | headers = {'User-Agent': 'staticmapservice/0.0.1'}
tile_server = 'http://a.tile.osm.org/{z}/{x}/{y}.png'
is_tms = False
default_width = '300'
default_height = '200'
default_zoom = '10'
max_width = '800'
max_height = '800'
max_zoom = 19
max_pnv = '30' |
#!/usr/bin/python2.7
##############################################################################
# Global settings
##############################################################################
# Describes all the garage doors being monitored
GARAGE_DOORS = [
# {
# 'pin': 16,
# 'name': "Garage Door 1",
# 'alerts': [
# {
# 'state': 'open',
# 'time': 120,
# 'recipients': [ 'sms:+11112223333', 'sms:+14445556666' ]
# },
# {
# 'state': 'open',
# 'time': 600,
# 'recipients': [ 'sms:+11112223333', 'sms:+14445556666' ]
# }
# ]
# },
{
'pin': 7,
'name': "Example Garage Door",
'alerts': [
# {
# 'state': 'open',
# 'time': 120,
# 'recipients': [ 'sms:+11112223333', 'email:someone@example.com', 'twitter_dm:twitter_user', 'pushbullet:access_token', 'gcm', 'tweet', 'ifttt:garage_door' ]
# },
# {
# 'state': 'open',
# 'time': 600,
# 'recipients': [ 'sms:+11112223333', 'email:someone@example.com', 'twitter_dm:twitter_user', 'pushbullet:access_token', 'gcm', 'tweet', 'ifttt:garage_door' ]
# }
]
}
]
# All messages will be logged to stdout and this file
LOG_FILENAME = "/var/log/pi_garage_alert.log"
##############################################################################
# Email settings
##############################################################################
SMTP_SERVER = 'localhost'
SMTP_PORT = 25
SMTP_USER = ''
SMTP_PASS = ''
EMAIL_FROM = 'Garage Door <user@example.com>'
EMAIL_PRIORITY = '1'
# 1 High, 3 Normal, 5 Low
##############################################################################
# Cisco Spark settings
##############################################################################
# Obtain your access token from https://developer.ciscospark.com, click
# on your avatar at the top right corner.
SPARK_ACCESSTOKEN = "" #put your access token here between the quotes.
##############################################################################
# Twitter settings
##############################################################################
# Follow the instructions on http://talkfast.org/2010/05/31/twitter-from-the-command-line-in-python-using-oauth/
# to obtain the necessary keys
TWITTER_CONSUMER_KEY = ''
TWITTER_CONSUMER_SECRET = ''
TWITTER_ACCESS_KEY = ''
TWITTER_ACCESS_SECRET = ''
##############################################################################
# Twilio settings
##############################################################################
# Sign up for a Twilio account at https://www.twilio.com/
# then these will be listed at the top of your Twilio dashboard
TWILIO_ACCOUNT = ''
TWILIO_TOKEN = ''
# SMS will be sent from this phone number
TWILIO_PHONE_NUMBER = '+11234567890'
##############################################################################
# Jabber settings
##############################################################################
# Jabber ID and password that status updates will be sent from
# Leave this blank to disable Jabber support
JABBER_ID = ''
JABBER_PASSWORD = ''
# Uncomment to override the default server specified in DNS SRV records
#JABBER_SERVER = 'talk.google.com'
#JABBER_PORT = 5222
# List of Jabber IDs allowed to perform queries
JABBER_AUTHORIZED_IDS = []
##############################################################################
# Google Cloud Messaging settings
##############################################################################
GCM_KEY = ''
GCM_TOPIC = ''
##############################################################################
# IFTTT Maker Channel settings
# Create an applet using the "Maker" channel, pick a event name,
# and use the event name as a recipient of one of the alerts,
# e.g. 'recipients': [ 'ifft:garage_event' ]
#
# Get the key by going to https://ifttt.com/services/maker/settings.
# The key is the part of the URL after https://maker.ifttt.com/use/.
# Do not include https://maker.ifttt.com/use/ in IFTTT_KEY.
##############################################################################
IFTTT_KEY = ''
##############################################################################
# Slack settings
# Send messages to a team slack channel
# e.g. 'recipients': [ 'slack:<your channel ID>']
# where <your channel ID> is the name or ID of the slack channel you want to
# send to
#
# To use this functionality you will need to create a bot user to do the posting
# For information on how to create the bot user and get your API token go to:
# https://api.slack.com/bot-users
#
# Note that the bot user must be added to the channel you want to post
# notifications in
##############################################################################
SLACK_BOT_TOKEN = ''
| garage_doors = [{'pin': 7, 'name': 'Example Garage Door', 'alerts': []}]
log_filename = '/var/log/pi_garage_alert.log'
smtp_server = 'localhost'
smtp_port = 25
smtp_user = ''
smtp_pass = ''
email_from = 'Garage Door <user@example.com>'
email_priority = '1'
spark_accesstoken = ''
twitter_consumer_key = ''
twitter_consumer_secret = ''
twitter_access_key = ''
twitter_access_secret = ''
twilio_account = ''
twilio_token = ''
twilio_phone_number = '+11234567890'
jabber_id = ''
jabber_password = ''
jabber_authorized_ids = []
gcm_key = ''
gcm_topic = ''
ifttt_key = ''
slack_bot_token = '' |
class Baggage_classify_mod:
def __init__(self,modelname,save_modelname):
self.modelname = modelname
self.save_modelname = save_modelname
def fit_func(modelname,x_train,y_train):
modelname.fit(x_train,y_train)
return modelname
def predict_func(model,x_test):
pred = model.predict(x_test)
return pred
| class Baggage_Classify_Mod:
def __init__(self, modelname, save_modelname):
self.modelname = modelname
self.save_modelname = save_modelname
def fit_func(modelname, x_train, y_train):
modelname.fit(x_train, y_train)
return modelname
def predict_func(model, x_test):
pred = model.predict(x_test)
return pred |
class Solution:
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
digits.reverse()
ld = len(digits)
index = 0
c = 1
while index < ld and c == 1:
digits[index] += c
c, digits[index] = digits[index] // 10, digits[index] % 10
index += 1
if c == 1:
digits.append(c)
digits.reverse()
return digits
if __name__ == "__main__":
print(Solution().plusOne([1, 2, 3]))
print(Solution().plusOne([4, 3, 2, 1]))
print(Solution().plusOne([9, 9, 9]))
| class Solution:
def plus_one(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
digits.reverse()
ld = len(digits)
index = 0
c = 1
while index < ld and c == 1:
digits[index] += c
(c, digits[index]) = (digits[index] // 10, digits[index] % 10)
index += 1
if c == 1:
digits.append(c)
digits.reverse()
return digits
if __name__ == '__main__':
print(solution().plusOne([1, 2, 3]))
print(solution().plusOne([4, 3, 2, 1]))
print(solution().plusOne([9, 9, 9])) |
class Sorting:
def swap(self, arr, pos1, pos2):
arr[pos1], arr[pos2] = arr[pos2], arr[pos1]
return
def selection_sort(self, arr):
for i in range(len(arr)):
min_ind = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[min_ind]:
min_ind = j
if arr[i] != arr[min_ind]:
arr[i], arr[min_ind] = arr[min_ind], arr[i]
return arr
if __name__ == "__main__":
obj = Sorting()
print(obj.selection_sort([2, 7, 5, 4, 3]))
| class Sorting:
def swap(self, arr, pos1, pos2):
(arr[pos1], arr[pos2]) = (arr[pos2], arr[pos1])
return
def selection_sort(self, arr):
for i in range(len(arr)):
min_ind = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[min_ind]:
min_ind = j
if arr[i] != arr[min_ind]:
(arr[i], arr[min_ind]) = (arr[min_ind], arr[i])
return arr
if __name__ == '__main__':
obj = sorting()
print(obj.selection_sort([2, 7, 5, 4, 3])) |
class Atributo:
def __init__(self,nombre,tipo):
self.columnNumber = None
self.nombre = nombre
self.tipo = tipo
self.isPrimary = False
self.ForeignTable = None
self.default = None
self.isNull = True
self.isUnique = False
#Punteros
self.siguiente = None
self.anterior = None
@classmethod
def iniciar_esPrimary(cls,nombre,tipo):
nuevo = cls.__new__(cls)
nuevo.nombre = nombre
nuevo.tipo = tipo
nuevo.isPrimary = True
nuevo.ForeignTable = None
nuevo.default = None
nuevo.isNull = False
nuevo.isUnique = True
#Punteros
nuevo.siguiente = None
nuevo.anterior = None
return nuevo
@classmethod
def iniciar_esForeign(cls,nombre,tipo, tabla):
nuevo = cls.__new__(cls)
nuevo.nombre = nombre
nuevo.tipo = tipo
nuevo.isPrimary = False
nuevo.ForeignTable = tabla
nuevo.default = None
nuevo.isNull = False
nuevo.isUnique = False
#Punteros
nuevo.siguiente = None
nuevo.anterior = None
return nuevo
@classmethod
def iniciar_Default(cls,nombre,tipo,default):
nuevo = cls.__new__(cls)
nuevo.nombre = nombre
nuevo.tipo = tipo
nuevo.isPrimary = False
nuevo.foreignTable = None
nuevo.default = default
nuevo.isNull = False
nuevo.isUnique = False
#Punteros
nuevo.siguiente = None
nuevo.anterior = None
return nuevo
@classmethod
def iniciar_NotNull(cls,nombre,tipo):
nuevo = cls.__new__(cls)
nuevo.nombre = nombre
nuevo.tipo = tipo
nuevo.isPrimary = False
nuevo.ForeignTable = None
nuevo.default = None
nuevo.isNull = True
nuevo.isUnique = False
#Punteros
nuevo.siguiente = None
nuevo.anterior = None
return nuevo
@classmethod
def iniciar_esUnique(cls,nombre,tipo):
nuevo = cls.__new__(cls)
nuevo.nombre = nombre
nuevo.tipo = tipo
nuevo.isPrimary = False
nuevo.ForeignTable = None
nuevo.default = None
nuevo.isNull = True
nuevo.isUnique = True
#Punteros
nuevo.siguiente = None
nuevo.anterior = None
return nuevo
@classmethod
def iniciar_Primary_Default(cls,nombre,tipo,default):
nuevo = cls.__new__(cls)
nuevo.nombre = nombre
nuevo.tipo = tipo
nuevo.isPrimary = True
nuevo.ForeignTable = None
nuevo.default = default
nuevo.isNull = False
nuevo.isUnique = True
#Punteros
nuevo.siguiente = None
nuevo.anterior = None
return nuevo
@classmethod
def iniciar_Default_NotNull_Unique(cls,nombre,tipo,default):
nuevo = cls.__new__(cls)
nuevo.nombre = nombre
nuevo.tipo = tipo
nuevo.isPrimary = False
nuevo.ForeignTable = None
nuevo.default = default
nuevo.isNull = False
nuevo.isUnique = True
#Punteros
nuevo.siguiente = None
nuevo.anterior = None
return nuevo
@classmethod
def iniciar_Default_Null(cls,nombre,tipo,default):
nuevo = cls.__new__(cls)
nuevo.nombre = nombre
nuevo.tipo = tipo
nuevo.isPrimary = False
nuevo.ForeignTable = None
nuevo.default = default
nuevo.isNull = True
nuevo.isUnique = False
#Punteros
nuevo.siguiente = None
nuevo.anterior = None
return nuevo
@classmethod
def iniciar_Solo_Default(cls,default:any):
nuevo = cls.__new__(cls)
nuevo.columnNumber = None
nuevo.nombre = None
nuevo.tipo = None
nuevo.isPrimary = False
nuevo.ForeignTable = None
nuevo.default = default
nuevo.isNull = True
nuevo.isUnique = False
# Punteros
nuevo.siguiente = None
nuevo.anterior = None
return nuevo | class Atributo:
def __init__(self, nombre, tipo):
self.columnNumber = None
self.nombre = nombre
self.tipo = tipo
self.isPrimary = False
self.ForeignTable = None
self.default = None
self.isNull = True
self.isUnique = False
self.siguiente = None
self.anterior = None
@classmethod
def iniciar_es_primary(cls, nombre, tipo):
nuevo = cls.__new__(cls)
nuevo.nombre = nombre
nuevo.tipo = tipo
nuevo.isPrimary = True
nuevo.ForeignTable = None
nuevo.default = None
nuevo.isNull = False
nuevo.isUnique = True
nuevo.siguiente = None
nuevo.anterior = None
return nuevo
@classmethod
def iniciar_es_foreign(cls, nombre, tipo, tabla):
nuevo = cls.__new__(cls)
nuevo.nombre = nombre
nuevo.tipo = tipo
nuevo.isPrimary = False
nuevo.ForeignTable = tabla
nuevo.default = None
nuevo.isNull = False
nuevo.isUnique = False
nuevo.siguiente = None
nuevo.anterior = None
return nuevo
@classmethod
def iniciar__default(cls, nombre, tipo, default):
nuevo = cls.__new__(cls)
nuevo.nombre = nombre
nuevo.tipo = tipo
nuevo.isPrimary = False
nuevo.foreignTable = None
nuevo.default = default
nuevo.isNull = False
nuevo.isUnique = False
nuevo.siguiente = None
nuevo.anterior = None
return nuevo
@classmethod
def iniciar__not_null(cls, nombre, tipo):
nuevo = cls.__new__(cls)
nuevo.nombre = nombre
nuevo.tipo = tipo
nuevo.isPrimary = False
nuevo.ForeignTable = None
nuevo.default = None
nuevo.isNull = True
nuevo.isUnique = False
nuevo.siguiente = None
nuevo.anterior = None
return nuevo
@classmethod
def iniciar_es_unique(cls, nombre, tipo):
nuevo = cls.__new__(cls)
nuevo.nombre = nombre
nuevo.tipo = tipo
nuevo.isPrimary = False
nuevo.ForeignTable = None
nuevo.default = None
nuevo.isNull = True
nuevo.isUnique = True
nuevo.siguiente = None
nuevo.anterior = None
return nuevo
@classmethod
def iniciar__primary__default(cls, nombre, tipo, default):
nuevo = cls.__new__(cls)
nuevo.nombre = nombre
nuevo.tipo = tipo
nuevo.isPrimary = True
nuevo.ForeignTable = None
nuevo.default = default
nuevo.isNull = False
nuevo.isUnique = True
nuevo.siguiente = None
nuevo.anterior = None
return nuevo
@classmethod
def iniciar__default__not_null__unique(cls, nombre, tipo, default):
nuevo = cls.__new__(cls)
nuevo.nombre = nombre
nuevo.tipo = tipo
nuevo.isPrimary = False
nuevo.ForeignTable = None
nuevo.default = default
nuevo.isNull = False
nuevo.isUnique = True
nuevo.siguiente = None
nuevo.anterior = None
return nuevo
@classmethod
def iniciar__default__null(cls, nombre, tipo, default):
nuevo = cls.__new__(cls)
nuevo.nombre = nombre
nuevo.tipo = tipo
nuevo.isPrimary = False
nuevo.ForeignTable = None
nuevo.default = default
nuevo.isNull = True
nuevo.isUnique = False
nuevo.siguiente = None
nuevo.anterior = None
return nuevo
@classmethod
def iniciar__solo__default(cls, default: any):
nuevo = cls.__new__(cls)
nuevo.columnNumber = None
nuevo.nombre = None
nuevo.tipo = None
nuevo.isPrimary = False
nuevo.ForeignTable = None
nuevo.default = default
nuevo.isNull = True
nuevo.isUnique = False
nuevo.siguiente = None
nuevo.anterior = None
return nuevo |
# Python program to learn about control flow
number = 23
guess = int(input('Enter an integer : '))
if guess == number:
# New block starts here
print('Congratulations, you guessed it.')
print('(but you do not win any prizes!)')
# New block ends here
elif guess < number:
# Another block
print('No, it is a little higher than that')
# You can do whatever you want in a block ...
else:
print('No, it is a little lower than that')
# you must have guessed > number to reach here
print('Done')
number = 23
running = True
#You can have an else cause for a while loop
while running:
guess = int(input('Enter an integer : '))
if guess == number:
# New block starts here
print('Congratulations, you guessed it.')
print('(but you do not win any prizes!)')
running = False
# New block ends here
elif guess < number:
# Another block
print('No, it is a little higher than that')
# You can do whatever you want in a block ...
else:
print('No, it is a little lower than that')
# you must have guessed > number to reach here
else:
print('the while loop is over')
print('Done')
#for loop
for i in range (1,5):
print(i)
else:
print('the for loop is over')
print(list(range(5)))
while True:
s = input('Ente somting: ')
if s == 'quit':
break
print('Length of the string is', len(s))
print('Done')
print()
while True:
s = input('Enter something : ')
if s == 'quit':
break
if len(s) < 3:
print('too small')
continue
print('Input is of sufficent length')
| number = 23
guess = int(input('Enter an integer : '))
if guess == number:
print('Congratulations, you guessed it.')
print('(but you do not win any prizes!)')
elif guess < number:
print('No, it is a little higher than that')
else:
print('No, it is a little lower than that')
print('Done')
number = 23
running = True
while running:
guess = int(input('Enter an integer : '))
if guess == number:
print('Congratulations, you guessed it.')
print('(but you do not win any prizes!)')
running = False
elif guess < number:
print('No, it is a little higher than that')
else:
print('No, it is a little lower than that')
else:
print('the while loop is over')
print('Done')
for i in range(1, 5):
print(i)
else:
print('the for loop is over')
print(list(range(5)))
while True:
s = input('Ente somting: ')
if s == 'quit':
break
print('Length of the string is', len(s))
print('Done')
print()
while True:
s = input('Enter something : ')
if s == 'quit':
break
if len(s) < 3:
print('too small')
continue
print('Input is of sufficent length') |
#takes data from the Game() class and...
#1. populates the score board with the runs scored and balls used by batsman
#2. changes the player position if the run hit is 1,3 or 5
#3. removes the player from the activePlayers list and the playing list if he gets out
class Runs():
def __init__(self,run,playing,remaining,scoreBoard,total,currentScore,target):
self.run = run
self.playing = playing
self.remaining = remaining
self.scoreBoard = scoreBoard
self.total = total
self.currentScore = currentScore
self.target = target
self.scoreBoard[self.playing[0]][1] += 1
if self.run in [1,2,3,4,5,6]:
self.scoreBoard[self.playing[0]][0] += self.run
self.total += self.run
self.currentScore -= self.run
if self.run in [1,3,5]:
self.playing = self.playing[::-1]
if self.run == "Out":
if len(self.remaining) != 0:
self.scoreBoard[self.playing[0]][1] -= 1
self.playing.pop(0)
self.playing.insert(0, self.remaining[0])
self.remaining.pop(0)
else:
self.playing.pop(0)
| class Runs:
def __init__(self, run, playing, remaining, scoreBoard, total, currentScore, target):
self.run = run
self.playing = playing
self.remaining = remaining
self.scoreBoard = scoreBoard
self.total = total
self.currentScore = currentScore
self.target = target
self.scoreBoard[self.playing[0]][1] += 1
if self.run in [1, 2, 3, 4, 5, 6]:
self.scoreBoard[self.playing[0]][0] += self.run
self.total += self.run
self.currentScore -= self.run
if self.run in [1, 3, 5]:
self.playing = self.playing[::-1]
if self.run == 'Out':
if len(self.remaining) != 0:
self.scoreBoard[self.playing[0]][1] -= 1
self.playing.pop(0)
self.playing.insert(0, self.remaining[0])
self.remaining.pop(0)
else:
self.playing.pop(0) |
class Arrayerrortype(basestring):
"""
ARRAY_INCONSISTENT_ADDRESSING_METHOD|ARRAY_DEVTYPE_ERROR
Possible values:
<ul>
<li> "array_inconsistent_addressing_method" - Array is using
inconsistent LUN addressing schemes.,
<li> "array_devtype_error" - Array has
encountered a device class error.
</ul>
"""
@staticmethod
def get_api_name():
return "arrayerrortype"
| class Arrayerrortype(basestring):
"""
ARRAY_INCONSISTENT_ADDRESSING_METHOD|ARRAY_DEVTYPE_ERROR
Possible values:
<ul>
<li> "array_inconsistent_addressing_method" - Array is using
inconsistent LUN addressing schemes.,
<li> "array_devtype_error" - Array has
encountered a device class error.
</ul>
"""
@staticmethod
def get_api_name():
return 'arrayerrortype' |
#!/usr/bin/env python3
# Author:: Justin Flannery (mailto:juftin@juftin.com)
"""
Project Configuration for Yellowstone Variables
"""
class SearchConfig:
"""
File Path Storage Class
"""
POLLING_INTERVAL_MINIMUM: int = 5 # 5 MINUTES
RECOMMENDED_POLLING_INTERVAL: int = 10 # 10 MINUTES
ERROR_MESSAGE: str = "No search days configured. Exiting"
MINIMUM_CAMPSITES_FIRST_NOTIFY: int = 5
| """
Project Configuration for Yellowstone Variables
"""
class Searchconfig:
"""
File Path Storage Class
"""
polling_interval_minimum: int = 5
recommended_polling_interval: int = 10
error_message: str = 'No search days configured. Exiting'
minimum_campsites_first_notify: int = 5 |
__author__ = 'cosmin'
class CommandError(Exception):
def __init__(self, arg):
self.msg = arg
class InvalidParameters(Exception):
def __init__(self, arg):
self.msg = arg | __author__ = 'cosmin'
class Commanderror(Exception):
def __init__(self, arg):
self.msg = arg
class Invalidparameters(Exception):
def __init__(self, arg):
self.msg = arg |
if __name__ == '__main__':
N = int(input())
nested_list = []
for _ in range(N):
name = input()
score = float(input())
nested_list.append([name,score])
score_list = []
for i in nested_list:
score_list.append(i[1])
mini = min(score_list)
score_list = sorted(score_list)
nun_mini = score_list.count(mini)
score_list = score_list[nun_mini:]
second_lowest = min(score_list)
second_lowest_list = []
for i in range(len(nested_list)):
if nested_list[i][1] == second_lowest:
second_lowest_list.append(nested_list[i][0])
sorted_list = sorted(second_lowest_list)
for name in sorted_list:
print(name)
| if __name__ == '__main__':
n = int(input())
nested_list = []
for _ in range(N):
name = input()
score = float(input())
nested_list.append([name, score])
score_list = []
for i in nested_list:
score_list.append(i[1])
mini = min(score_list)
score_list = sorted(score_list)
nun_mini = score_list.count(mini)
score_list = score_list[nun_mini:]
second_lowest = min(score_list)
second_lowest_list = []
for i in range(len(nested_list)):
if nested_list[i][1] == second_lowest:
second_lowest_list.append(nested_list[i][0])
sorted_list = sorted(second_lowest_list)
for name in sorted_list:
print(name) |
colors = {"Red", "Green", "Blue"}
# add(): adds item to the set.
colors.add("Magenta")
print(colors)
# discard(): removes item from set without error if not present.
colors.discard("Blue")
colors.discard("Blue")
print(colors)
# remove(): removes item from set with KeyError if not present.
colors.remove("Red")
# colors.remove("Red") # KeyError: 'Red'
numbers = {1, 2, 3, 4}
# update(): adds items from a sequence into a set.
colors.update(numbers)
print(colors)
# Below is a string, which will be stored as A, n, d, y
colors.update("Andy")
print(colors)
| colors = {'Red', 'Green', 'Blue'}
colors.add('Magenta')
print(colors)
colors.discard('Blue')
colors.discard('Blue')
print(colors)
colors.remove('Red')
numbers = {1, 2, 3, 4}
colors.update(numbers)
print(colors)
colors.update('Andy')
print(colors) |
"""Presets for end-to-end model training for special tasks."""
__all__ = [
'tabular_gpu_presets'
]
| """Presets for end-to-end model training for special tasks."""
__all__ = ['tabular_gpu_presets'] |
# -*- coding: utf-8 -*-
def main():
n, m, x, y = map(int, input().split())
xs = list(map(int, input().split())) + [x]
ys = list(map(int, input().split())) + [y]
x_max = max(xs)
y_min = min(ys)
if x_max < y_min:
print('No War')
else:
print('War')
if __name__ == '__main__':
main()
| def main():
(n, m, x, y) = map(int, input().split())
xs = list(map(int, input().split())) + [x]
ys = list(map(int, input().split())) + [y]
x_max = max(xs)
y_min = min(ys)
if x_max < y_min:
print('No War')
else:
print('War')
if __name__ == '__main__':
main() |
description_short = "linux signal file descriptor for python"
keywords = [
"signalfd",
"python3",
"linux",
]
| description_short = 'linux signal file descriptor for python'
keywords = ['signalfd', 'python3', 'linux'] |
a, n = map(int, input().split())
ans = 0
for i in range(n):
ans = ans + (n - i) * a * (10 ** i)
print(ans)
| (a, n) = map(int, input().split())
ans = 0
for i in range(n):
ans = ans + (n - i) * a * 10 ** i
print(ans) |
def parse_comment(comment, data):
comment.etag = data["etag"]
comment.id = data["string"]
# snippet
snippet_data = data.get("snippet", False)
if snippet_data:
comment.author_display_name = author_display_name_data["snippet"][
"authorDisplayName"
]
comment.author_profile_image_url = author_profile_image_url_data[
"snippet"
]["authorProfileImageUrl"]
comment.author_channel_url = author_channel_url_data["snippet"][
"authorChannelUrl"
]
comment.channel_id = channel_id_data["snippet"]["channelId"]
comment.video_id = video_id_data["snippet"]["videoId"]
comment.text_display = text_display_data["snippet"]["textDisplay"]
comment.text_original = text_original_data["snippet"]["textOriginal"]
comment.parent_id = parent_id_data["snippet"]["parentId"]
comment.can_rate = can_rate_data["snippet"]["canRate"]
comment.viewer_rating = viewer_rating_data["snippet"]["viewerRating"]
comment.like_count = like_count_data["snippet"]["likeCount"]
comment.moderation_status = moderation_status_data["snippet"][
"moderationStatus"
]
comment.published_at = published_at_data["snippet"]["publishedAt"]
comment.updated_at = updated_at_data["snippet"]["updatedAt"]
return comment
| def parse_comment(comment, data):
comment.etag = data['etag']
comment.id = data['string']
snippet_data = data.get('snippet', False)
if snippet_data:
comment.author_display_name = author_display_name_data['snippet']['authorDisplayName']
comment.author_profile_image_url = author_profile_image_url_data['snippet']['authorProfileImageUrl']
comment.author_channel_url = author_channel_url_data['snippet']['authorChannelUrl']
comment.channel_id = channel_id_data['snippet']['channelId']
comment.video_id = video_id_data['snippet']['videoId']
comment.text_display = text_display_data['snippet']['textDisplay']
comment.text_original = text_original_data['snippet']['textOriginal']
comment.parent_id = parent_id_data['snippet']['parentId']
comment.can_rate = can_rate_data['snippet']['canRate']
comment.viewer_rating = viewer_rating_data['snippet']['viewerRating']
comment.like_count = like_count_data['snippet']['likeCount']
comment.moderation_status = moderation_status_data['snippet']['moderationStatus']
comment.published_at = published_at_data['snippet']['publishedAt']
comment.updated_at = updated_at_data['snippet']['updatedAt']
return comment |
def isPalindrome(strn):
for i in range(0, len(strn)//2):
if strn[i] != strn[len(strn)-i-1]:
return False
return True
x=input()
if isPalindrome(x)==1:
print("Yes, '{}' is a palindrome".format(x))
else:
print("No, '{}' is NOT a palindrome".format(x))
| def is_palindrome(strn):
for i in range(0, len(strn) // 2):
if strn[i] != strn[len(strn) - i - 1]:
return False
return True
x = input()
if is_palindrome(x) == 1:
print("Yes, '{}' is a palindrome".format(x))
else:
print("No, '{}' is NOT a palindrome".format(x)) |
"""
You can't call grok.context multiple times on module level:
>>> import grokcore.component.tests.adapter.modulecontextmultiple_fixture
Traceback (most recent call last):
...
GrokImportError: The 'context' directive can only be called once per
class or module.
"""
| """
You can't call grok.context multiple times on module level:
>>> import grokcore.component.tests.adapter.modulecontextmultiple_fixture
Traceback (most recent call last):
...
GrokImportError: The 'context' directive can only be called once per
class or module.
""" |
if __name__ == "__main__":
# Read integer input from stdin
t = int(input())
for t_itr in range(t):
# Read string input from stdin
n, k = list(map(int, input().split()))
# Compute bitwise and max value
print(k-1 if ((k-1) | k) <= n else k-2)
| if __name__ == '__main__':
t = int(input())
for t_itr in range(t):
(n, k) = list(map(int, input().split()))
print(k - 1 if k - 1 | k <= n else k - 2) |
# -*- coding: utf-8 -*-
"""
This file is covered by the LICENSING file in the root of this project.
"""
__author__ = 'ZGQ'
| """
This file is covered by the LICENSING file in the root of this project.
"""
__author__ = 'ZGQ' |
# https://app.terra.bio/#workspaces/broad-dsp-hca-processing-prod4/Bone-Marrow-Myeloma-copy/workflows/broad-dsp-hca-processing-prod4/CreateSS2AdapterMetadata
BAM_INPUT = {
"file_path": "/cromwell_root/localized-path/call-HISAT2PairedEnd/cacheCopy/0244354d-cf37-4483-8db3-425b7e504ca6_qc.bam",
"sha256": "1d7038c19c5961ee8f956330af0dd24ecd0407eb14aa21e4c1c9bbad47468500",
"input_uuid": "0244354d-cf37-4483-8db3-425b7e504ca6",
"workspace_version": "2021-10-19T17:43:52.000000Z",
"creation_time": "2021-10-14T18:47:57Z",
"pipeline_type": "SS2",
"crc32c": "2a3433fb",
"size": 791383592,
}
BAI_INPUT = {
"file_path": "/cromwell_root/localized-path/call-HISAT2PairedEnd/cacheCopy/0244354d-cf37-4483-8db3-425b7e504ca6_qc.bam.bai",
"sha256": "9474e18a0e86baac1f3b6bd017c781738f7cadafe21862beb1841abc070f32fe",
"input_uuid": "0244354d-cf37-4483-8db3-425b7e504ca6",
"workspace_version": "2021-10-19T17:43:52.000000Z",
"creation_time": "2021-10-14T18:47:57Z",
"pipeline_type": "SS2",
"crc32c": "dbd6cf34",
"size": 2295024,
}
| bam_input = {'file_path': '/cromwell_root/localized-path/call-HISAT2PairedEnd/cacheCopy/0244354d-cf37-4483-8db3-425b7e504ca6_qc.bam', 'sha256': '1d7038c19c5961ee8f956330af0dd24ecd0407eb14aa21e4c1c9bbad47468500', 'input_uuid': '0244354d-cf37-4483-8db3-425b7e504ca6', 'workspace_version': '2021-10-19T17:43:52.000000Z', 'creation_time': '2021-10-14T18:47:57Z', 'pipeline_type': 'SS2', 'crc32c': '2a3433fb', 'size': 791383592}
bai_input = {'file_path': '/cromwell_root/localized-path/call-HISAT2PairedEnd/cacheCopy/0244354d-cf37-4483-8db3-425b7e504ca6_qc.bam.bai', 'sha256': '9474e18a0e86baac1f3b6bd017c781738f7cadafe21862beb1841abc070f32fe', 'input_uuid': '0244354d-cf37-4483-8db3-425b7e504ca6', 'workspace_version': '2021-10-19T17:43:52.000000Z', 'creation_time': '2021-10-14T18:47:57Z', 'pipeline_type': 'SS2', 'crc32c': 'dbd6cf34', 'size': 2295024} |
#! /usr/bin/env python3
a = 1
b = 0
x = 1
limit = 1000
while len("%d"%a) < limit:
print("F(%d) %d: %d " % (x,len("%d"%a),a))
c = a
a = a+b
b = c
x+=1
| a = 1
b = 0
x = 1
limit = 1000
while len('%d' % a) < limit:
print('F(%d) %d: %d ' % (x, len('%d' % a), a))
c = a
a = a + b
b = c
x += 1 |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class FindElements:
def __init__(self, root: TreeNode):
self.root = root
self.recover(self.root, 0)
def recover(self, root: TreeNode, val: int) -> None:
root.val = val
if root.left: self.recover(root.left, 2 * val + 1)
if root.right: self.recover(root.right, 2 * val + 2)
def find(self, target: int) -> bool:
return self.lookup(self.root, target)
def lookup(self, root: TreeNode, target: int) -> bool:
if not root: return False
if root.val > target: return self.lookup(root.left, target)
if root.val == target: return True
return self.lookup(root.right, target) or self.lookup(root.left, target)
# Your FindElements object will be instantiated and called as such:
# obj = FindElements(root)
# param_1 = obj.find(target)
| class Findelements:
def __init__(self, root: TreeNode):
self.root = root
self.recover(self.root, 0)
def recover(self, root: TreeNode, val: int) -> None:
root.val = val
if root.left:
self.recover(root.left, 2 * val + 1)
if root.right:
self.recover(root.right, 2 * val + 2)
def find(self, target: int) -> bool:
return self.lookup(self.root, target)
def lookup(self, root: TreeNode, target: int) -> bool:
if not root:
return False
if root.val > target:
return self.lookup(root.left, target)
if root.val == target:
return True
return self.lookup(root.right, target) or self.lookup(root.left, target) |
a = 10
if 0 <= a < 5:
print('[0, 5)')
elif 5 <= a < 8:
print('[5, 8)')
else:
print('[8, +Infinity)')
| a = 10
if 0 <= a < 5:
print('[0, 5)')
elif 5 <= a < 8:
print('[5, 8)')
else:
print('[8, +Infinity)') |
for T in range(1,int(input())+1):
t,c=input().split()
t=list(t)
c=int(c)
ans=0
for i in range(len(t)-c+1):
if t[i]=='-':
ans+=1
for j in range(i,i+c): t[j]='+' if t[j]=='-' else '-'
if not '-' in t: print('Case #%d:'%T,ans)
else: print('Case #%d: IMPOSSIBLE'%T) | for t in range(1, int(input()) + 1):
(t, c) = input().split()
t = list(t)
c = int(c)
ans = 0
for i in range(len(t) - c + 1):
if t[i] == '-':
ans += 1
for j in range(i, i + c):
t[j] = '+' if t[j] == '-' else '-'
if not '-' in t:
print('Case #%d:' % T, ans)
else:
print('Case #%d: IMPOSSIBLE' % T) |
# Time: O(n)
# Space: O(1)
class Solution:
def missingNumber(self, nums):
n = len(nums)
sum = n * (n + 1) / 2
sum2 = 0
for i in nums:
sum2 += i
return int(sum - sum2)
if __name__ == "__main__":
nums = [9, 6, 4, 2, 3, 5, 7, 0, 1]
s = Solution()
print(s.missingNumber(nums)) | class Solution:
def missing_number(self, nums):
n = len(nums)
sum = n * (n + 1) / 2
sum2 = 0
for i in nums:
sum2 += i
return int(sum - sum2)
if __name__ == '__main__':
nums = [9, 6, 4, 2, 3, 5, 7, 0, 1]
s = solution()
print(s.missingNumber(nums)) |
class Solution:
def uniquePaths(self, m, n):
dp = [[0] * n for i in xrange(m)]
dp[m - 1][n - 1] = 1
process = collections.deque([(m - 1, n - 1)])
while process:
i, j = process.popleft()
if j < n - 1:
a = dp[i][j + 1]
else:
a = 0
if i < m - 1:
b = dp[i + 1][j]
else:
b = 0
dp[i][j] = max(a + b, 1)
if i > 0 and dp[i - 1][j] != -1:
dp[i - 1][j] = -1
process.append((i - 1, j))
if j > 0 and dp[i][j - 1] != -1:
dp[i][j - 1] = -1
process.append((i, j - 1))
return dp[0][0]
| class Solution:
def unique_paths(self, m, n):
dp = [[0] * n for i in xrange(m)]
dp[m - 1][n - 1] = 1
process = collections.deque([(m - 1, n - 1)])
while process:
(i, j) = process.popleft()
if j < n - 1:
a = dp[i][j + 1]
else:
a = 0
if i < m - 1:
b = dp[i + 1][j]
else:
b = 0
dp[i][j] = max(a + b, 1)
if i > 0 and dp[i - 1][j] != -1:
dp[i - 1][j] = -1
process.append((i - 1, j))
if j > 0 and dp[i][j - 1] != -1:
dp[i][j - 1] = -1
process.append((i, j - 1))
return dp[0][0] |
# Adapted from a Java code in the "Refactoring" book by Martin Fowler.
# Replace temp with query
# Code snippet. Not runnable.
def get_price():
base_price = quantity * item_price
discount_factor = 0
if base_price > 1000:
discount_factor = 0.95
else:
discount_factor = 0.98
return base_price * discount_factor
| def get_price():
base_price = quantity * item_price
discount_factor = 0
if base_price > 1000:
discount_factor = 0.95
else:
discount_factor = 0.98
return base_price * discount_factor |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/7/30 10:38
# @Author : Leishichi
# @File : 12.py
# @Software: PyCharm
# @Tag:
class Solution:
def intToRoman(self, num):
"""
:type num: int
:rtype: str
"""
symbols = {1: "I", 5: "V", 10: "X", 50: "L", 100: "C", 500: "D", 1000: "M"}
position = 1
romans = []
while num > 0:
digit = num % 10
if digit < 4:
for _ in range(digit): romans.append(symbols[position])
elif digit == 4 or digit == 9:
romans.append(symbols[(digit + 1) * position]);
romans.append(symbols[position])
elif digit == 5:
romans.append(symbols[digit * position])
else:
for _ in range(digit - 5):
romans.append(symbols[position])
romans.append(symbols[5 * position])
position *= 10
num = num // 10
return "".join(romans[::-1])
| class Solution:
def int_to_roman(self, num):
"""
:type num: int
:rtype: str
"""
symbols = {1: 'I', 5: 'V', 10: 'X', 50: 'L', 100: 'C', 500: 'D', 1000: 'M'}
position = 1
romans = []
while num > 0:
digit = num % 10
if digit < 4:
for _ in range(digit):
romans.append(symbols[position])
elif digit == 4 or digit == 9:
romans.append(symbols[(digit + 1) * position])
romans.append(symbols[position])
elif digit == 5:
romans.append(symbols[digit * position])
else:
for _ in range(digit - 5):
romans.append(symbols[position])
romans.append(symbols[5 * position])
position *= 10
num = num // 10
return ''.join(romans[::-1]) |
# Esto es un comentario
# Input siempre regresa una string(palabra)
# Nombre
nombre = "Cristian"
print("Mi nombre es " + nombre)
# Apellidos
apellidoPaterno = "Flores"
apellidoMaterno = "Bernal"
apellidos = apellidoPaterno + ' ' + apellidoMaterno
print("Mis Apellidos son: " + apellidos)
# Edad
edad = 0
print("Edad:", edad)
edad = int(input("Cual es tu edad? ")) # "21" -> 21
print("Edad:", edad)
print("Edad + 5:", edad + 5) | nombre = 'Cristian'
print('Mi nombre es ' + nombre)
apellido_paterno = 'Flores'
apellido_materno = 'Bernal'
apellidos = apellidoPaterno + ' ' + apellidoMaterno
print('Mis Apellidos son: ' + apellidos)
edad = 0
print('Edad:', edad)
edad = int(input('Cual es tu edad? '))
print('Edad:', edad)
print('Edad + 5:', edad + 5) |
"""
encoders.py
-----------
Convert GraphData to texts.
"""
def encode_edgelist(graph, delimiter=' ', attr=False, header=False):
text = ''
if header:
text += delimiter.join([str(a) for a in graph.edge_attr[:2]])
if attr:
text += delimiter
text += delimiter.join([str(a) for a in graph.edge_attr[2:]])
text += '\n'
for ((node1, node2), *attrs) in graph.edges:
text += '{}{}{}'.format(
graph.nodes[node1][0], delimiter, graph.nodes[node2][0])
if attr:
text += delimiter + delimiter.join([str(d) for d in attrs])
text += '\n'
return text
def write(text, out, close=True):
file = open(out) if isinstance(out, str) else out
file.write(text)
if close:
file.close()
| """
encoders.py
-----------
Convert GraphData to texts.
"""
def encode_edgelist(graph, delimiter=' ', attr=False, header=False):
text = ''
if header:
text += delimiter.join([str(a) for a in graph.edge_attr[:2]])
if attr:
text += delimiter
text += delimiter.join([str(a) for a in graph.edge_attr[2:]])
text += '\n'
for ((node1, node2), *attrs) in graph.edges:
text += '{}{}{}'.format(graph.nodes[node1][0], delimiter, graph.nodes[node2][0])
if attr:
text += delimiter + delimiter.join([str(d) for d in attrs])
text += '\n'
return text
def write(text, out, close=True):
file = open(out) if isinstance(out, str) else out
file.write(text)
if close:
file.close() |
# Largest palindrome product
def checkPalindrome(x):
if str(x) == str(x)[::-1]:
return True
return False
maxPalindrome = 0
for x in range(999,99,-1):
for y in range(999,99,-1):
if checkPalindrome(x*y):
print(x,y)
print(x*y)
if x*y > maxPalindrome:
maxPalindrome = x*y
print(maxPalindrome)
| def check_palindrome(x):
if str(x) == str(x)[::-1]:
return True
return False
max_palindrome = 0
for x in range(999, 99, -1):
for y in range(999, 99, -1):
if check_palindrome(x * y):
print(x, y)
print(x * y)
if x * y > maxPalindrome:
max_palindrome = x * y
print(maxPalindrome) |
class Animal:
name = "Lion"
noise = "Rrrrr"
color = "Gray"
def make_noise(self):
print(f"{self.noise}")
def get_noise(self):
return self.noise
def set_noise(self, new_noise):
self.noise = new_noise
def show_name(self):
print(f"{self.name}")
def get_name(self):
return self.name
def set_name(self, new_name):
self.name = new_name
def show_color(self):
print(f"{self.color}")
def get_name(self):
return self.color
def set_noise(self, new_color):
self.color = new_color
class Wolf(Animal):
noise = "GRrrrrrr" | class Animal:
name = 'Lion'
noise = 'Rrrrr'
color = 'Gray'
def make_noise(self):
print(f'{self.noise}')
def get_noise(self):
return self.noise
def set_noise(self, new_noise):
self.noise = new_noise
def show_name(self):
print(f'{self.name}')
def get_name(self):
return self.name
def set_name(self, new_name):
self.name = new_name
def show_color(self):
print(f'{self.color}')
def get_name(self):
return self.color
def set_noise(self, new_color):
self.color = new_color
class Wolf(Animal):
noise = 'GRrrrrrr' |
# Time complexity: O(n*2^n)
# Approach: For each subset, iterate from 0 to n-1 and for each number in binary, take elements corresponding to 1s.
class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
nums = sorted(nums)
n = len(nums)
ans = []
for i in range(2**n):
tmp = []
for j in range(n):
if i & (1<<j):
tmp.append(nums[j])
if tmp not in ans:
ans.append(tmp)
return ans | class Solution:
def subsets_with_dup(self, nums: List[int]) -> List[List[int]]:
nums = sorted(nums)
n = len(nums)
ans = []
for i in range(2 ** n):
tmp = []
for j in range(n):
if i & 1 << j:
tmp.append(nums[j])
if tmp not in ans:
ans.append(tmp)
return ans |
class rawDataError(Exception):
def __init__(self):
self.message = 'Please choose a valid raw data file!'
super().__init__(self.message)
class ratioError(Exception):
def __init__(self):
self.message = 'Could not read Active:Carbon:Binder ratio input.'
super().__init__(self.message)
class tablePermissionError(Exception):
def __init__(self):
self.message = 'Cannot save data table because the file is currently in use by another program.'
super().__init__(self.message)
class figurePermissionError(Exception):
def __init__(self):
self.message = 'Cannot save figure because the file is currently in use by another program.'
super().__init__(self.message) | class Rawdataerror(Exception):
def __init__(self):
self.message = 'Please choose a valid raw data file!'
super().__init__(self.message)
class Ratioerror(Exception):
def __init__(self):
self.message = 'Could not read Active:Carbon:Binder ratio input.'
super().__init__(self.message)
class Tablepermissionerror(Exception):
def __init__(self):
self.message = 'Cannot save data table because the file is currently in use by another program.'
super().__init__(self.message)
class Figurepermissionerror(Exception):
def __init__(self):
self.message = 'Cannot save figure because the file is currently in use by another program.'
super().__init__(self.message) |
class Reservations:
def __init__(self, client):
self.client = client
def list(self, params={}):
return self.client.request('GET', self._url(params), params)
def create(self, params={}):
return self.client.request('POST', self._url(params), params)
def show(self, id):
url = '/reservations/{0}'.format(id)
return self.client.request('GET', url, {})
def update(self, id, params={}):
url = '/reservations/{0}'.format(id)
update_params = {'reservation': params}
return self.client.request('PUT', url, update_params)
def destroy(self, id):
url = '/reservations/{0}'.format(id)
return self.client.request('DELETE', url, {})
def bulk_create(self, reservations=[], webhook=None):
url = '/reservations/bulk_create'
params = {'reservations': reservations}
if webhook:
params['webhook'] = webhook
return self.client.request('POST', url, params)
def _url(self, params={}):
if 'property_id' in params:
property_id = params['property_id']
return '/properties/{id}/reservations'.format(id=property_id)
else:
return '/reservations'
| class Reservations:
def __init__(self, client):
self.client = client
def list(self, params={}):
return self.client.request('GET', self._url(params), params)
def create(self, params={}):
return self.client.request('POST', self._url(params), params)
def show(self, id):
url = '/reservations/{0}'.format(id)
return self.client.request('GET', url, {})
def update(self, id, params={}):
url = '/reservations/{0}'.format(id)
update_params = {'reservation': params}
return self.client.request('PUT', url, update_params)
def destroy(self, id):
url = '/reservations/{0}'.format(id)
return self.client.request('DELETE', url, {})
def bulk_create(self, reservations=[], webhook=None):
url = '/reservations/bulk_create'
params = {'reservations': reservations}
if webhook:
params['webhook'] = webhook
return self.client.request('POST', url, params)
def _url(self, params={}):
if 'property_id' in params:
property_id = params['property_id']
return '/properties/{id}/reservations'.format(id=property_id)
else:
return '/reservations' |
"""
time complexity = O(n) space complexity = O(1)
set MAX and MIN value to be 32 bits maximun and minimun integar
strip to delete whitespace
remain sign as 1 or -1
check each char should be in '0'~ '9'
plus the ret as each bit check MAX//10 and ret to make sure result will not out of range
return ret*sign
"""
class Solution:
def myAtoi(self, s: str) -> int:
ls = s.strip()
if len(ls) == 0 :
return 0
i=0
ret = 0
sign = 1
MAX = 2147483647
MIN = -2147483648
if ls[i] =='+' or ls[i] == '-':
sign = 1-2*(ls[i] == '-')
i+=1
while i<len(ls) and ls[i]>='0'and ls[i]<='9':
if ret > MAX//10 or (ret == MAX//10 and ord(ls[i])-ord('0') > MAX%10):
return MAX if sign ==1 else MIN
ret = ret*10+ (ord(ls[i])-ord('0'))
i+=1
return ret*sign
A = Solution()
s = "2147483648"
print(A.myAtoi(s)) | """
time complexity = O(n) space complexity = O(1)
set MAX and MIN value to be 32 bits maximun and minimun integar
strip to delete whitespace
remain sign as 1 or -1
check each char should be in '0'~ '9'
plus the ret as each bit check MAX//10 and ret to make sure result will not out of range
return ret*sign
"""
class Solution:
def my_atoi(self, s: str) -> int:
ls = s.strip()
if len(ls) == 0:
return 0
i = 0
ret = 0
sign = 1
max = 2147483647
min = -2147483648
if ls[i] == '+' or ls[i] == '-':
sign = 1 - 2 * (ls[i] == '-')
i += 1
while i < len(ls) and ls[i] >= '0' and (ls[i] <= '9'):
if ret > MAX // 10 or (ret == MAX // 10 and ord(ls[i]) - ord('0') > MAX % 10):
return MAX if sign == 1 else MIN
ret = ret * 10 + (ord(ls[i]) - ord('0'))
i += 1
return ret * sign
a = solution()
s = '2147483648'
print(A.myAtoi(s)) |
def english_full_name(first=None, last=None, middle=None,
prefix=None, suffix=None):
fullname = None
if first is None or last is None:
raise ValueError("first and last must be specified")
if middle:
fullname = first + " " + middle + " " + last
else:
fullname = "{} {}".format(first, last)
if prefix:
fullname = prefix + " " + fullname
if suffix:
fullname = fullname + " " + suffix
return fullname
| def english_full_name(first=None, last=None, middle=None, prefix=None, suffix=None):
fullname = None
if first is None or last is None:
raise value_error('first and last must be specified')
if middle:
fullname = first + ' ' + middle + ' ' + last
else:
fullname = '{} {}'.format(first, last)
if prefix:
fullname = prefix + ' ' + fullname
if suffix:
fullname = fullname + ' ' + suffix
return fullname |
del_items(0x80122C20)
SetType(0x80122C20, "struct THEME_LOC themeLoc[50]")
del_items(0x80123368)
SetType(0x80123368, "int OldBlock[4]")
del_items(0x80123378)
SetType(0x80123378, "unsigned char L5dungeon[80][80]")
del_items(0x80123008)
SetType(0x80123008, "struct ShadowStruct SPATS[37]")
del_items(0x8012310C)
SetType(0x8012310C, "unsigned char BSTYPES[206]")
del_items(0x801231DC)
SetType(0x801231DC, "unsigned char L5BTYPES[206]")
del_items(0x801232AC)
SetType(0x801232AC, "unsigned char STAIRSUP[34]")
del_items(0x801232D0)
SetType(0x801232D0, "unsigned char L5STAIRSUP[34]")
del_items(0x801232F4)
SetType(0x801232F4, "unsigned char STAIRSDOWN[26]")
del_items(0x80123310)
SetType(0x80123310, "unsigned char LAMPS[10]")
del_items(0x8012331C)
SetType(0x8012331C, "unsigned char PWATERIN[74]")
del_items(0x80122C10)
SetType(0x80122C10, "unsigned char L5ConvTbl[16]")
del_items(0x8012B5A8)
SetType(0x8012B5A8, "struct ROOMNODE RoomList[81]")
del_items(0x8012BBFC)
SetType(0x8012BBFC, "unsigned char predungeon[40][40]")
del_items(0x80129D38)
SetType(0x80129D38, "int Dir_Xadd[5]")
del_items(0x80129D4C)
SetType(0x80129D4C, "int Dir_Yadd[5]")
del_items(0x80129D60)
SetType(0x80129D60, "struct ShadowStruct SPATSL2[2]")
del_items(0x80129D70)
SetType(0x80129D70, "unsigned char BTYPESL2[161]")
del_items(0x80129E14)
SetType(0x80129E14, "unsigned char BSTYPESL2[161]")
del_items(0x80129EB8)
SetType(0x80129EB8, "unsigned char VARCH1[18]")
del_items(0x80129ECC)
SetType(0x80129ECC, "unsigned char VARCH2[18]")
del_items(0x80129EE0)
SetType(0x80129EE0, "unsigned char VARCH3[18]")
del_items(0x80129EF4)
SetType(0x80129EF4, "unsigned char VARCH4[18]")
del_items(0x80129F08)
SetType(0x80129F08, "unsigned char VARCH5[18]")
del_items(0x80129F1C)
SetType(0x80129F1C, "unsigned char VARCH6[18]")
del_items(0x80129F30)
SetType(0x80129F30, "unsigned char VARCH7[18]")
del_items(0x80129F44)
SetType(0x80129F44, "unsigned char VARCH8[18]")
del_items(0x80129F58)
SetType(0x80129F58, "unsigned char VARCH9[18]")
del_items(0x80129F6C)
SetType(0x80129F6C, "unsigned char VARCH10[18]")
del_items(0x80129F80)
SetType(0x80129F80, "unsigned char VARCH11[18]")
del_items(0x80129F94)
SetType(0x80129F94, "unsigned char VARCH12[18]")
del_items(0x80129FA8)
SetType(0x80129FA8, "unsigned char VARCH13[18]")
del_items(0x80129FBC)
SetType(0x80129FBC, "unsigned char VARCH14[18]")
del_items(0x80129FD0)
SetType(0x80129FD0, "unsigned char VARCH15[18]")
del_items(0x80129FE4)
SetType(0x80129FE4, "unsigned char VARCH16[18]")
del_items(0x80129FF8)
SetType(0x80129FF8, "unsigned char VARCH17[14]")
del_items(0x8012A008)
SetType(0x8012A008, "unsigned char VARCH18[14]")
del_items(0x8012A018)
SetType(0x8012A018, "unsigned char VARCH19[14]")
del_items(0x8012A028)
SetType(0x8012A028, "unsigned char VARCH20[14]")
del_items(0x8012A038)
SetType(0x8012A038, "unsigned char VARCH21[14]")
del_items(0x8012A048)
SetType(0x8012A048, "unsigned char VARCH22[14]")
del_items(0x8012A058)
SetType(0x8012A058, "unsigned char VARCH23[14]")
del_items(0x8012A068)
SetType(0x8012A068, "unsigned char VARCH24[14]")
del_items(0x8012A078)
SetType(0x8012A078, "unsigned char VARCH25[18]")
del_items(0x8012A08C)
SetType(0x8012A08C, "unsigned char VARCH26[18]")
del_items(0x8012A0A0)
SetType(0x8012A0A0, "unsigned char VARCH27[18]")
del_items(0x8012A0B4)
SetType(0x8012A0B4, "unsigned char VARCH28[18]")
del_items(0x8012A0C8)
SetType(0x8012A0C8, "unsigned char VARCH29[18]")
del_items(0x8012A0DC)
SetType(0x8012A0DC, "unsigned char VARCH30[18]")
del_items(0x8012A0F0)
SetType(0x8012A0F0, "unsigned char VARCH31[18]")
del_items(0x8012A104)
SetType(0x8012A104, "unsigned char VARCH32[18]")
del_items(0x8012A118)
SetType(0x8012A118, "unsigned char VARCH33[18]")
del_items(0x8012A12C)
SetType(0x8012A12C, "unsigned char VARCH34[18]")
del_items(0x8012A140)
SetType(0x8012A140, "unsigned char VARCH35[18]")
del_items(0x8012A154)
SetType(0x8012A154, "unsigned char VARCH36[18]")
del_items(0x8012A168)
SetType(0x8012A168, "unsigned char VARCH37[18]")
del_items(0x8012A17C)
SetType(0x8012A17C, "unsigned char VARCH38[18]")
del_items(0x8012A190)
SetType(0x8012A190, "unsigned char VARCH39[18]")
del_items(0x8012A1A4)
SetType(0x8012A1A4, "unsigned char VARCH40[18]")
del_items(0x8012A1B8)
SetType(0x8012A1B8, "unsigned char HARCH1[14]")
del_items(0x8012A1C8)
SetType(0x8012A1C8, "unsigned char HARCH2[14]")
del_items(0x8012A1D8)
SetType(0x8012A1D8, "unsigned char HARCH3[14]")
del_items(0x8012A1E8)
SetType(0x8012A1E8, "unsigned char HARCH4[14]")
del_items(0x8012A1F8)
SetType(0x8012A1F8, "unsigned char HARCH5[14]")
del_items(0x8012A208)
SetType(0x8012A208, "unsigned char HARCH6[14]")
del_items(0x8012A218)
SetType(0x8012A218, "unsigned char HARCH7[14]")
del_items(0x8012A228)
SetType(0x8012A228, "unsigned char HARCH8[14]")
del_items(0x8012A238)
SetType(0x8012A238, "unsigned char HARCH9[14]")
del_items(0x8012A248)
SetType(0x8012A248, "unsigned char HARCH10[14]")
del_items(0x8012A258)
SetType(0x8012A258, "unsigned char HARCH11[14]")
del_items(0x8012A268)
SetType(0x8012A268, "unsigned char HARCH12[14]")
del_items(0x8012A278)
SetType(0x8012A278, "unsigned char HARCH13[14]")
del_items(0x8012A288)
SetType(0x8012A288, "unsigned char HARCH14[14]")
del_items(0x8012A298)
SetType(0x8012A298, "unsigned char HARCH15[14]")
del_items(0x8012A2A8)
SetType(0x8012A2A8, "unsigned char HARCH16[14]")
del_items(0x8012A2B8)
SetType(0x8012A2B8, "unsigned char HARCH17[14]")
del_items(0x8012A2C8)
SetType(0x8012A2C8, "unsigned char HARCH18[14]")
del_items(0x8012A2D8)
SetType(0x8012A2D8, "unsigned char HARCH19[14]")
del_items(0x8012A2E8)
SetType(0x8012A2E8, "unsigned char HARCH20[14]")
del_items(0x8012A2F8)
SetType(0x8012A2F8, "unsigned char HARCH21[14]")
del_items(0x8012A308)
SetType(0x8012A308, "unsigned char HARCH22[14]")
del_items(0x8012A318)
SetType(0x8012A318, "unsigned char HARCH23[14]")
del_items(0x8012A328)
SetType(0x8012A328, "unsigned char HARCH24[14]")
del_items(0x8012A338)
SetType(0x8012A338, "unsigned char HARCH25[14]")
del_items(0x8012A348)
SetType(0x8012A348, "unsigned char HARCH26[14]")
del_items(0x8012A358)
SetType(0x8012A358, "unsigned char HARCH27[14]")
del_items(0x8012A368)
SetType(0x8012A368, "unsigned char HARCH28[14]")
del_items(0x8012A378)
SetType(0x8012A378, "unsigned char HARCH29[14]")
del_items(0x8012A388)
SetType(0x8012A388, "unsigned char HARCH30[14]")
del_items(0x8012A398)
SetType(0x8012A398, "unsigned char HARCH31[14]")
del_items(0x8012A3A8)
SetType(0x8012A3A8, "unsigned char HARCH32[14]")
del_items(0x8012A3B8)
SetType(0x8012A3B8, "unsigned char HARCH33[14]")
del_items(0x8012A3C8)
SetType(0x8012A3C8, "unsigned char HARCH34[14]")
del_items(0x8012A3D8)
SetType(0x8012A3D8, "unsigned char HARCH35[14]")
del_items(0x8012A3E8)
SetType(0x8012A3E8, "unsigned char HARCH36[14]")
del_items(0x8012A3F8)
SetType(0x8012A3F8, "unsigned char HARCH37[14]")
del_items(0x8012A408)
SetType(0x8012A408, "unsigned char HARCH38[14]")
del_items(0x8012A418)
SetType(0x8012A418, "unsigned char HARCH39[14]")
del_items(0x8012A428)
SetType(0x8012A428, "unsigned char HARCH40[14]")
del_items(0x8012A438)
SetType(0x8012A438, "unsigned char USTAIRS[34]")
del_items(0x8012A45C)
SetType(0x8012A45C, "unsigned char DSTAIRS[34]")
del_items(0x8012A480)
SetType(0x8012A480, "unsigned char WARPSTAIRS[34]")
del_items(0x8012A4A4)
SetType(0x8012A4A4, "unsigned char CRUSHCOL[20]")
del_items(0x8012A4B8)
SetType(0x8012A4B8, "unsigned char BIG1[10]")
del_items(0x8012A4C4)
SetType(0x8012A4C4, "unsigned char BIG2[10]")
del_items(0x8012A4D0)
SetType(0x8012A4D0, "unsigned char BIG5[10]")
del_items(0x8012A4DC)
SetType(0x8012A4DC, "unsigned char BIG8[10]")
del_items(0x8012A4E8)
SetType(0x8012A4E8, "unsigned char BIG9[10]")
del_items(0x8012A4F4)
SetType(0x8012A4F4, "unsigned char BIG10[10]")
del_items(0x8012A500)
SetType(0x8012A500, "unsigned char PANCREAS1[32]")
del_items(0x8012A520)
SetType(0x8012A520, "unsigned char PANCREAS2[32]")
del_items(0x8012A540)
SetType(0x8012A540, "unsigned char CTRDOOR1[20]")
del_items(0x8012A554)
SetType(0x8012A554, "unsigned char CTRDOOR2[20]")
del_items(0x8012A568)
SetType(0x8012A568, "unsigned char CTRDOOR3[20]")
del_items(0x8012A57C)
SetType(0x8012A57C, "unsigned char CTRDOOR4[20]")
del_items(0x8012A590)
SetType(0x8012A590, "unsigned char CTRDOOR5[20]")
del_items(0x8012A5A4)
SetType(0x8012A5A4, "unsigned char CTRDOOR6[20]")
del_items(0x8012A5B8)
SetType(0x8012A5B8, "unsigned char CTRDOOR7[20]")
del_items(0x8012A5CC)
SetType(0x8012A5CC, "unsigned char CTRDOOR8[20]")
del_items(0x8012A5E0)
SetType(0x8012A5E0, "int Patterns[10][100]")
del_items(0x801315F0)
SetType(0x801315F0, "unsigned char lockout[40][40]")
del_items(0x80131350)
SetType(0x80131350, "unsigned char L3ConvTbl[16]")
del_items(0x80131360)
SetType(0x80131360, "unsigned char L3UP[20]")
del_items(0x80131374)
SetType(0x80131374, "unsigned char L3DOWN[20]")
del_items(0x80131388)
SetType(0x80131388, "unsigned char L3HOLDWARP[20]")
del_items(0x8013139C)
SetType(0x8013139C, "unsigned char L3TITE1[34]")
del_items(0x801313C0)
SetType(0x801313C0, "unsigned char L3TITE2[34]")
del_items(0x801313E4)
SetType(0x801313E4, "unsigned char L3TITE3[34]")
del_items(0x80131408)
SetType(0x80131408, "unsigned char L3TITE6[42]")
del_items(0x80131434)
SetType(0x80131434, "unsigned char L3TITE7[42]")
del_items(0x80131460)
SetType(0x80131460, "unsigned char L3TITE8[20]")
del_items(0x80131474)
SetType(0x80131474, "unsigned char L3TITE9[20]")
del_items(0x80131488)
SetType(0x80131488, "unsigned char L3TITE10[20]")
del_items(0x8013149C)
SetType(0x8013149C, "unsigned char L3TITE11[20]")
del_items(0x801314B0)
SetType(0x801314B0, "unsigned char L3ISLE1[14]")
del_items(0x801314C0)
SetType(0x801314C0, "unsigned char L3ISLE2[14]")
del_items(0x801314D0)
SetType(0x801314D0, "unsigned char L3ISLE3[14]")
del_items(0x801314E0)
SetType(0x801314E0, "unsigned char L3ISLE4[14]")
del_items(0x801314F0)
SetType(0x801314F0, "unsigned char L3ISLE5[10]")
del_items(0x801314FC)
SetType(0x801314FC, "unsigned char L3ANVIL[244]")
del_items(0x8013640C)
SetType(0x8013640C, "unsigned char dung[20][20]")
del_items(0x8013659C)
SetType(0x8013659C, "unsigned char hallok[20]")
del_items(0x801365B0)
SetType(0x801365B0, "unsigned char L4dungeon[80][80]")
del_items(0x80137EB0)
SetType(0x80137EB0, "unsigned char L4ConvTbl[16]")
del_items(0x80137EC0)
SetType(0x80137EC0, "unsigned char L4USTAIRS[42]")
del_items(0x80137EEC)
SetType(0x80137EEC, "unsigned char L4TWARP[42]")
del_items(0x80137F18)
SetType(0x80137F18, "unsigned char L4DSTAIRS[52]")
del_items(0x80137F4C)
SetType(0x80137F4C, "unsigned char L4PENTA[52]")
del_items(0x80137F80)
SetType(0x80137F80, "unsigned char L4PENTA2[52]")
del_items(0x80137FB4)
SetType(0x80137FB4, "unsigned char L4BTYPES[140]")
| del_items(2148674592)
set_type(2148674592, 'struct THEME_LOC themeLoc[50]')
del_items(2148676456)
set_type(2148676456, 'int OldBlock[4]')
del_items(2148676472)
set_type(2148676472, 'unsigned char L5dungeon[80][80]')
del_items(2148675592)
set_type(2148675592, 'struct ShadowStruct SPATS[37]')
del_items(2148675852)
set_type(2148675852, 'unsigned char BSTYPES[206]')
del_items(2148676060)
set_type(2148676060, 'unsigned char L5BTYPES[206]')
del_items(2148676268)
set_type(2148676268, 'unsigned char STAIRSUP[34]')
del_items(2148676304)
set_type(2148676304, 'unsigned char L5STAIRSUP[34]')
del_items(2148676340)
set_type(2148676340, 'unsigned char STAIRSDOWN[26]')
del_items(2148676368)
set_type(2148676368, 'unsigned char LAMPS[10]')
del_items(2148676380)
set_type(2148676380, 'unsigned char PWATERIN[74]')
del_items(2148674576)
set_type(2148674576, 'unsigned char L5ConvTbl[16]')
del_items(2148709800)
set_type(2148709800, 'struct ROOMNODE RoomList[81]')
del_items(2148711420)
set_type(2148711420, 'unsigned char predungeon[40][40]')
del_items(2148703544)
set_type(2148703544, 'int Dir_Xadd[5]')
del_items(2148703564)
set_type(2148703564, 'int Dir_Yadd[5]')
del_items(2148703584)
set_type(2148703584, 'struct ShadowStruct SPATSL2[2]')
del_items(2148703600)
set_type(2148703600, 'unsigned char BTYPESL2[161]')
del_items(2148703764)
set_type(2148703764, 'unsigned char BSTYPESL2[161]')
del_items(2148703928)
set_type(2148703928, 'unsigned char VARCH1[18]')
del_items(2148703948)
set_type(2148703948, 'unsigned char VARCH2[18]')
del_items(2148703968)
set_type(2148703968, 'unsigned char VARCH3[18]')
del_items(2148703988)
set_type(2148703988, 'unsigned char VARCH4[18]')
del_items(2148704008)
set_type(2148704008, 'unsigned char VARCH5[18]')
del_items(2148704028)
set_type(2148704028, 'unsigned char VARCH6[18]')
del_items(2148704048)
set_type(2148704048, 'unsigned char VARCH7[18]')
del_items(2148704068)
set_type(2148704068, 'unsigned char VARCH8[18]')
del_items(2148704088)
set_type(2148704088, 'unsigned char VARCH9[18]')
del_items(2148704108)
set_type(2148704108, 'unsigned char VARCH10[18]')
del_items(2148704128)
set_type(2148704128, 'unsigned char VARCH11[18]')
del_items(2148704148)
set_type(2148704148, 'unsigned char VARCH12[18]')
del_items(2148704168)
set_type(2148704168, 'unsigned char VARCH13[18]')
del_items(2148704188)
set_type(2148704188, 'unsigned char VARCH14[18]')
del_items(2148704208)
set_type(2148704208, 'unsigned char VARCH15[18]')
del_items(2148704228)
set_type(2148704228, 'unsigned char VARCH16[18]')
del_items(2148704248)
set_type(2148704248, 'unsigned char VARCH17[14]')
del_items(2148704264)
set_type(2148704264, 'unsigned char VARCH18[14]')
del_items(2148704280)
set_type(2148704280, 'unsigned char VARCH19[14]')
del_items(2148704296)
set_type(2148704296, 'unsigned char VARCH20[14]')
del_items(2148704312)
set_type(2148704312, 'unsigned char VARCH21[14]')
del_items(2148704328)
set_type(2148704328, 'unsigned char VARCH22[14]')
del_items(2148704344)
set_type(2148704344, 'unsigned char VARCH23[14]')
del_items(2148704360)
set_type(2148704360, 'unsigned char VARCH24[14]')
del_items(2148704376)
set_type(2148704376, 'unsigned char VARCH25[18]')
del_items(2148704396)
set_type(2148704396, 'unsigned char VARCH26[18]')
del_items(2148704416)
set_type(2148704416, 'unsigned char VARCH27[18]')
del_items(2148704436)
set_type(2148704436, 'unsigned char VARCH28[18]')
del_items(2148704456)
set_type(2148704456, 'unsigned char VARCH29[18]')
del_items(2148704476)
set_type(2148704476, 'unsigned char VARCH30[18]')
del_items(2148704496)
set_type(2148704496, 'unsigned char VARCH31[18]')
del_items(2148704516)
set_type(2148704516, 'unsigned char VARCH32[18]')
del_items(2148704536)
set_type(2148704536, 'unsigned char VARCH33[18]')
del_items(2148704556)
set_type(2148704556, 'unsigned char VARCH34[18]')
del_items(2148704576)
set_type(2148704576, 'unsigned char VARCH35[18]')
del_items(2148704596)
set_type(2148704596, 'unsigned char VARCH36[18]')
del_items(2148704616)
set_type(2148704616, 'unsigned char VARCH37[18]')
del_items(2148704636)
set_type(2148704636, 'unsigned char VARCH38[18]')
del_items(2148704656)
set_type(2148704656, 'unsigned char VARCH39[18]')
del_items(2148704676)
set_type(2148704676, 'unsigned char VARCH40[18]')
del_items(2148704696)
set_type(2148704696, 'unsigned char HARCH1[14]')
del_items(2148704712)
set_type(2148704712, 'unsigned char HARCH2[14]')
del_items(2148704728)
set_type(2148704728, 'unsigned char HARCH3[14]')
del_items(2148704744)
set_type(2148704744, 'unsigned char HARCH4[14]')
del_items(2148704760)
set_type(2148704760, 'unsigned char HARCH5[14]')
del_items(2148704776)
set_type(2148704776, 'unsigned char HARCH6[14]')
del_items(2148704792)
set_type(2148704792, 'unsigned char HARCH7[14]')
del_items(2148704808)
set_type(2148704808, 'unsigned char HARCH8[14]')
del_items(2148704824)
set_type(2148704824, 'unsigned char HARCH9[14]')
del_items(2148704840)
set_type(2148704840, 'unsigned char HARCH10[14]')
del_items(2148704856)
set_type(2148704856, 'unsigned char HARCH11[14]')
del_items(2148704872)
set_type(2148704872, 'unsigned char HARCH12[14]')
del_items(2148704888)
set_type(2148704888, 'unsigned char HARCH13[14]')
del_items(2148704904)
set_type(2148704904, 'unsigned char HARCH14[14]')
del_items(2148704920)
set_type(2148704920, 'unsigned char HARCH15[14]')
del_items(2148704936)
set_type(2148704936, 'unsigned char HARCH16[14]')
del_items(2148704952)
set_type(2148704952, 'unsigned char HARCH17[14]')
del_items(2148704968)
set_type(2148704968, 'unsigned char HARCH18[14]')
del_items(2148704984)
set_type(2148704984, 'unsigned char HARCH19[14]')
del_items(2148705000)
set_type(2148705000, 'unsigned char HARCH20[14]')
del_items(2148705016)
set_type(2148705016, 'unsigned char HARCH21[14]')
del_items(2148705032)
set_type(2148705032, 'unsigned char HARCH22[14]')
del_items(2148705048)
set_type(2148705048, 'unsigned char HARCH23[14]')
del_items(2148705064)
set_type(2148705064, 'unsigned char HARCH24[14]')
del_items(2148705080)
set_type(2148705080, 'unsigned char HARCH25[14]')
del_items(2148705096)
set_type(2148705096, 'unsigned char HARCH26[14]')
del_items(2148705112)
set_type(2148705112, 'unsigned char HARCH27[14]')
del_items(2148705128)
set_type(2148705128, 'unsigned char HARCH28[14]')
del_items(2148705144)
set_type(2148705144, 'unsigned char HARCH29[14]')
del_items(2148705160)
set_type(2148705160, 'unsigned char HARCH30[14]')
del_items(2148705176)
set_type(2148705176, 'unsigned char HARCH31[14]')
del_items(2148705192)
set_type(2148705192, 'unsigned char HARCH32[14]')
del_items(2148705208)
set_type(2148705208, 'unsigned char HARCH33[14]')
del_items(2148705224)
set_type(2148705224, 'unsigned char HARCH34[14]')
del_items(2148705240)
set_type(2148705240, 'unsigned char HARCH35[14]')
del_items(2148705256)
set_type(2148705256, 'unsigned char HARCH36[14]')
del_items(2148705272)
set_type(2148705272, 'unsigned char HARCH37[14]')
del_items(2148705288)
set_type(2148705288, 'unsigned char HARCH38[14]')
del_items(2148705304)
set_type(2148705304, 'unsigned char HARCH39[14]')
del_items(2148705320)
set_type(2148705320, 'unsigned char HARCH40[14]')
del_items(2148705336)
set_type(2148705336, 'unsigned char USTAIRS[34]')
del_items(2148705372)
set_type(2148705372, 'unsigned char DSTAIRS[34]')
del_items(2148705408)
set_type(2148705408, 'unsigned char WARPSTAIRS[34]')
del_items(2148705444)
set_type(2148705444, 'unsigned char CRUSHCOL[20]')
del_items(2148705464)
set_type(2148705464, 'unsigned char BIG1[10]')
del_items(2148705476)
set_type(2148705476, 'unsigned char BIG2[10]')
del_items(2148705488)
set_type(2148705488, 'unsigned char BIG5[10]')
del_items(2148705500)
set_type(2148705500, 'unsigned char BIG8[10]')
del_items(2148705512)
set_type(2148705512, 'unsigned char BIG9[10]')
del_items(2148705524)
set_type(2148705524, 'unsigned char BIG10[10]')
del_items(2148705536)
set_type(2148705536, 'unsigned char PANCREAS1[32]')
del_items(2148705568)
set_type(2148705568, 'unsigned char PANCREAS2[32]')
del_items(2148705600)
set_type(2148705600, 'unsigned char CTRDOOR1[20]')
del_items(2148705620)
set_type(2148705620, 'unsigned char CTRDOOR2[20]')
del_items(2148705640)
set_type(2148705640, 'unsigned char CTRDOOR3[20]')
del_items(2148705660)
set_type(2148705660, 'unsigned char CTRDOOR4[20]')
del_items(2148705680)
set_type(2148705680, 'unsigned char CTRDOOR5[20]')
del_items(2148705700)
set_type(2148705700, 'unsigned char CTRDOOR6[20]')
del_items(2148705720)
set_type(2148705720, 'unsigned char CTRDOOR7[20]')
del_items(2148705740)
set_type(2148705740, 'unsigned char CTRDOOR8[20]')
del_items(2148705760)
set_type(2148705760, 'int Patterns[10][100]')
del_items(2148734448)
set_type(2148734448, 'unsigned char lockout[40][40]')
del_items(2148733776)
set_type(2148733776, 'unsigned char L3ConvTbl[16]')
del_items(2148733792)
set_type(2148733792, 'unsigned char L3UP[20]')
del_items(2148733812)
set_type(2148733812, 'unsigned char L3DOWN[20]')
del_items(2148733832)
set_type(2148733832, 'unsigned char L3HOLDWARP[20]')
del_items(2148733852)
set_type(2148733852, 'unsigned char L3TITE1[34]')
del_items(2148733888)
set_type(2148733888, 'unsigned char L3TITE2[34]')
del_items(2148733924)
set_type(2148733924, 'unsigned char L3TITE3[34]')
del_items(2148733960)
set_type(2148733960, 'unsigned char L3TITE6[42]')
del_items(2148734004)
set_type(2148734004, 'unsigned char L3TITE7[42]')
del_items(2148734048)
set_type(2148734048, 'unsigned char L3TITE8[20]')
del_items(2148734068)
set_type(2148734068, 'unsigned char L3TITE9[20]')
del_items(2148734088)
set_type(2148734088, 'unsigned char L3TITE10[20]')
del_items(2148734108)
set_type(2148734108, 'unsigned char L3TITE11[20]')
del_items(2148734128)
set_type(2148734128, 'unsigned char L3ISLE1[14]')
del_items(2148734144)
set_type(2148734144, 'unsigned char L3ISLE2[14]')
del_items(2148734160)
set_type(2148734160, 'unsigned char L3ISLE3[14]')
del_items(2148734176)
set_type(2148734176, 'unsigned char L3ISLE4[14]')
del_items(2148734192)
set_type(2148734192, 'unsigned char L3ISLE5[10]')
del_items(2148734204)
set_type(2148734204, 'unsigned char L3ANVIL[244]')
del_items(2148754444)
set_type(2148754444, 'unsigned char dung[20][20]')
del_items(2148754844)
set_type(2148754844, 'unsigned char hallok[20]')
del_items(2148754864)
set_type(2148754864, 'unsigned char L4dungeon[80][80]')
del_items(2148761264)
set_type(2148761264, 'unsigned char L4ConvTbl[16]')
del_items(2148761280)
set_type(2148761280, 'unsigned char L4USTAIRS[42]')
del_items(2148761324)
set_type(2148761324, 'unsigned char L4TWARP[42]')
del_items(2148761368)
set_type(2148761368, 'unsigned char L4DSTAIRS[52]')
del_items(2148761420)
set_type(2148761420, 'unsigned char L4PENTA[52]')
del_items(2148761472)
set_type(2148761472, 'unsigned char L4PENTA2[52]')
del_items(2148761524)
set_type(2148761524, 'unsigned char L4BTYPES[140]') |
# -*- coding: utf-8 -*-
def pytest_addoption(parser):
group = parser.getgroup("portion")
group.addoption(
"--portion", action="store", help='Select a part of all the collected tests in the form "i/n" or "start:end"'
)
def slice_fraction(sequence, i, n):
"""
Split a sequence in `n` slices and then return the i-th (1-indexed).
The last slice will be longer if the sequence can't be splitted even-sized or
n is greater than the sequence's size.
"""
total = len(sequence)
per_slice = total // n
if not per_slice:
return sequence if i == n else type(sequence)()
ranges = [[n, n + per_slice] for n in range(0, total, per_slice)]
# fix last
if total % n != 0:
ranges = ranges[:-1]
ranges[-1][1] = None
portion = dict(enumerate(ranges, 1))[i]
return sequence[slice(*portion)]
def slice_percentage_range(sequence, start, end):
"""
return the slice range between coefficient `start` and `end`
where start and end represents fractions between 0 and 1.
Corner elements may be repeated in consecutive slices.
"""
total = len(sequence)
return slice(int(round(total * start)), int(total * end) + 1)
def pytest_collection_modifyitems(config, items):
try:
portion = config.getoption("portion") or config.getini("portion")
except ValueError:
portion = None
deselected = []
if not portion:
return
elif "/" in portion:
i, n = [int(n) for n in portion.split("/")]
selected = slice_fraction(items, i, n)
for range_number in range(1, n + 1):
if range_number == i:
continue
deselected.extend(slice_fraction(items, range_number, n))
elif ":" in portion:
start, end = [float(n) for n in portion.split(":")]
slice_selected = slice_percentage_range(items, start, end)
selected = items[slice_selected]
deselected.extend(items[:slice_selected.start])
deselected.extend(items[slice_selected.stop:])
items[:] = selected
config.hook.pytest_deselected(items=deselected)
| def pytest_addoption(parser):
group = parser.getgroup('portion')
group.addoption('--portion', action='store', help='Select a part of all the collected tests in the form "i/n" or "start:end"')
def slice_fraction(sequence, i, n):
"""
Split a sequence in `n` slices and then return the i-th (1-indexed).
The last slice will be longer if the sequence can't be splitted even-sized or
n is greater than the sequence's size.
"""
total = len(sequence)
per_slice = total // n
if not per_slice:
return sequence if i == n else type(sequence)()
ranges = [[n, n + per_slice] for n in range(0, total, per_slice)]
if total % n != 0:
ranges = ranges[:-1]
ranges[-1][1] = None
portion = dict(enumerate(ranges, 1))[i]
return sequence[slice(*portion)]
def slice_percentage_range(sequence, start, end):
"""
return the slice range between coefficient `start` and `end`
where start and end represents fractions between 0 and 1.
Corner elements may be repeated in consecutive slices.
"""
total = len(sequence)
return slice(int(round(total * start)), int(total * end) + 1)
def pytest_collection_modifyitems(config, items):
try:
portion = config.getoption('portion') or config.getini('portion')
except ValueError:
portion = None
deselected = []
if not portion:
return
elif '/' in portion:
(i, n) = [int(n) for n in portion.split('/')]
selected = slice_fraction(items, i, n)
for range_number in range(1, n + 1):
if range_number == i:
continue
deselected.extend(slice_fraction(items, range_number, n))
elif ':' in portion:
(start, end) = [float(n) for n in portion.split(':')]
slice_selected = slice_percentage_range(items, start, end)
selected = items[slice_selected]
deselected.extend(items[:slice_selected.start])
deselected.extend(items[slice_selected.stop:])
items[:] = selected
config.hook.pytest_deselected(items=deselected) |
def normalize_bbox(bbox, size):
return [
int(1000 * bbox[0] / size[0]),
int(1000 * bbox[1] / size[1]),
int(1000 * bbox[2] / size[0]),
int(1000 * bbox[3] / size[1]),
]
| def normalize_bbox(bbox, size):
return [int(1000 * bbox[0] / size[0]), int(1000 * bbox[1] / size[1]), int(1000 * bbox[2] / size[0]), int(1000 * bbox[3] / size[1])] |
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
result = set()
l = len(nums)
for a in range(l - 3):
if a > 0 and nums[a] == nums[a - 1]: continue
if nums[a] + nums[a + 1] + nums[a + 2] + nums[a + 3] > target: break
if nums[a] + nums[l - 3] + nums[l - 2] + nums[l - 1] < target: continue
for b in range(a + 1, l - 2):
if b > a + 1 and nums[b] == nums[b - 1]: continue
if nums[a] + nums[b] + nums[b + 1] + nums[b + 2] > target: break
if nums[a] + nums[b] + nums[l - 2] + nums[l - 1] < target: continue
c, d = b + 1, l - 1
rem_target = target - (nums[a] + nums[b])
while c < d:
if nums[c] + nums[d] > rem_target:
d -= 1
elif nums[c] + nums[d] < rem_target:
c += 1
else:
result.add((nums[a], nums[b], nums[c], nums[d]))
c += 1
d -= 1
return result
| class Solution:
def four_sum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
result = set()
l = len(nums)
for a in range(l - 3):
if a > 0 and nums[a] == nums[a - 1]:
continue
if nums[a] + nums[a + 1] + nums[a + 2] + nums[a + 3] > target:
break
if nums[a] + nums[l - 3] + nums[l - 2] + nums[l - 1] < target:
continue
for b in range(a + 1, l - 2):
if b > a + 1 and nums[b] == nums[b - 1]:
continue
if nums[a] + nums[b] + nums[b + 1] + nums[b + 2] > target:
break
if nums[a] + nums[b] + nums[l - 2] + nums[l - 1] < target:
continue
(c, d) = (b + 1, l - 1)
rem_target = target - (nums[a] + nums[b])
while c < d:
if nums[c] + nums[d] > rem_target:
d -= 1
elif nums[c] + nums[d] < rem_target:
c += 1
else:
result.add((nums[a], nums[b], nums[c], nums[d]))
c += 1
d -= 1
return result |
a = int(input())
b = int(input())
for i in range(a,b+1):
if i%2==0:
print(i) | a = int(input())
b = int(input())
for i in range(a, b + 1):
if i % 2 == 0:
print(i) |
'''
BFS is a tree traversal method. We search the graph level by level.
- The concept is a layered traversal.
- This means we start at the root of the node and we begin a "levelled" traversal.
Let's define the **level or depth of a given node the amount of edges between that node and the root**.
Let's look at the following tree as an example:
```
1
/ \
2 3
/ \
4 5
```
**Level 0**
All nodes at distance 0 from root. `{1}`
**Level 1**
All nodes at distance 1 from root. `{2, 3}`
**Level 2**
All nodes at distance 2 from root. `{4, 5}`
**Traversal Example**
Like mentioned above a valid BFS traversal could visit the nodes in the graph in the following order:
`1->2->3->4->5`
Another valid BFS traversal could be:
`1->3->2->5->4`
Let's look at an iterative and recursive BFS implmentation.
'''
class TreeNode:
def __init__(self, val, left, right):
self.val = val
self.left = left
self.right = right
def visitNode(node):
if node:
print(node.val)
def bfsIterative(root):
if not root:
return
q = [root]
while q:
current = q.pop(0)
if not current:
return
visitNode(current)
if current.left:
q.append(current.left)
if current.right:
q.append(current.right)
def recursiveBfs(root):
if not root:
return
def helper(q):
if not q:
return
current = q.pop(0)
if not current:
return
visitNode(current)
if current.left:
q.append(current.left)
if current.right:
q.append(current.right)
helper(q)
q = [root]
helper(q)
| """
BFS is a tree traversal method. We search the graph level by level.
- The concept is a layered traversal.
- This means we start at the root of the node and we begin a "levelled" traversal.
Let's define the **level or depth of a given node the amount of edges between that node and the root**.
Let's look at the following tree as an example:
```
1
/ 2 3
/ 4 5
```
**Level 0**
All nodes at distance 0 from root. `{1}`
**Level 1**
All nodes at distance 1 from root. `{2, 3}`
**Level 2**
All nodes at distance 2 from root. `{4, 5}`
**Traversal Example**
Like mentioned above a valid BFS traversal could visit the nodes in the graph in the following order:
`1->2->3->4->5`
Another valid BFS traversal could be:
`1->3->2->5->4`
Let's look at an iterative and recursive BFS implmentation.
"""
class Treenode:
def __init__(self, val, left, right):
self.val = val
self.left = left
self.right = right
def visit_node(node):
if node:
print(node.val)
def bfs_iterative(root):
if not root:
return
q = [root]
while q:
current = q.pop(0)
if not current:
return
visit_node(current)
if current.left:
q.append(current.left)
if current.right:
q.append(current.right)
def recursive_bfs(root):
if not root:
return
def helper(q):
if not q:
return
current = q.pop(0)
if not current:
return
visit_node(current)
if current.left:
q.append(current.left)
if current.right:
q.append(current.right)
helper(q)
q = [root]
helper(q) |
defs = {
'season': {
'type': 'numeric',
'options': {
'min_length': 1,
'max_length': 2
}
},
'episode': {
'type': 'numeric',
'options': {
'min_length': 1,
'max_length': 2
}
},
'shot': {
'type': 'numeric',
'options': {
'min_length': 1,
'max_length': 4
}
},
'version': {
'type': 'numeric',
'options': {
'min_length': 1,
'max_length': 4
}
}
}
motion_template = {
'name': 'motion',
'template': 'S${season}_EP${episode}_MOTION_SH${shot}_V${version}',
'definitions': defs
}
| defs = {'season': {'type': 'numeric', 'options': {'min_length': 1, 'max_length': 2}}, 'episode': {'type': 'numeric', 'options': {'min_length': 1, 'max_length': 2}}, 'shot': {'type': 'numeric', 'options': {'min_length': 1, 'max_length': 4}}, 'version': {'type': 'numeric', 'options': {'min_length': 1, 'max_length': 4}}}
motion_template = {'name': 'motion', 'template': 'S${season}_EP${episode}_MOTION_SH${shot}_V${version}', 'definitions': defs} |
def main():
h,w = map(int,input().split())
maze = []
for _ in range(h):
maze.append(list(input()))
dx = [1,0,-1,0]
dy = [0,1,0,-1]
que = []
que.append([0,0])
d = [[-1 for _ in range(w)] for _ in range(h)]
d[0][0] = 0
while len(que)!=0:
qx,qy = que.pop()
for i in range(4):
nx = qx + dx[i]
ny = qy + dy[i]
if 0 <= nx < h and 0 <= ny < w and maze[nx][ny] == "." and d[nx][ny] == -1:
d[nx][ny] = d[qx][qy] + 1
que.append([nx,ny])
if d[h-1][w-1] == -1:
print(-1)
return
cnt = 0
for i in range(h):
for j in range(w):
if maze[i][j] == ".":
cnt += 1
print(cnt-d[h-1][w-1]-1)
if __name__ == "__main__":
main() | def main():
(h, w) = map(int, input().split())
maze = []
for _ in range(h):
maze.append(list(input()))
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]
que = []
que.append([0, 0])
d = [[-1 for _ in range(w)] for _ in range(h)]
d[0][0] = 0
while len(que) != 0:
(qx, qy) = que.pop()
for i in range(4):
nx = qx + dx[i]
ny = qy + dy[i]
if 0 <= nx < h and 0 <= ny < w and (maze[nx][ny] == '.') and (d[nx][ny] == -1):
d[nx][ny] = d[qx][qy] + 1
que.append([nx, ny])
if d[h - 1][w - 1] == -1:
print(-1)
return
cnt = 0
for i in range(h):
for j in range(w):
if maze[i][j] == '.':
cnt += 1
print(cnt - d[h - 1][w - 1] - 1)
if __name__ == '__main__':
main() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.