content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
f = open('rucsac.txt', 'r')
n = int(f.readline())
v = []
for i in range(n):
linie = f.readline().split()
v.append((i+1, int(linie[0]), int(linie[1])))
G = int(f.readline())
cmax = [[0 for i in range(G+1)] for j in range(n+1)]
for i in range(1, n+1):
for j in range(1, G+1):
if v[i-1][1] > j:
cmax[i][j] = cmax[i-1][j]
else:
cmax[i][j] = max(cmax[i-1][j], v[i-1][2] + cmax[i-1][j-v[i-1][1]])
print("Profitul maxim care poate fi obtinut este %s, introducand obiectele: " % cmax[n][G], end = '')
i, j = n, G
solutie = []
while i > 0:
if cmax[i][G] != cmax[i-1][G]:
solutie.append(v[i][0])
j -= v[i][1]
i -= 1
else:
i -= 1
for elem in reversed(solutie):
print(elem, end = ' ')
f.close() | f = open('rucsac.txt', 'r')
n = int(f.readline())
v = []
for i in range(n):
linie = f.readline().split()
v.append((i + 1, int(linie[0]), int(linie[1])))
g = int(f.readline())
cmax = [[0 for i in range(G + 1)] for j in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, G + 1):
if v[i - 1][1] > j:
cmax[i][j] = cmax[i - 1][j]
else:
cmax[i][j] = max(cmax[i - 1][j], v[i - 1][2] + cmax[i - 1][j - v[i - 1][1]])
print('Profitul maxim care poate fi obtinut este %s, introducand obiectele: ' % cmax[n][G], end='')
(i, j) = (n, G)
solutie = []
while i > 0:
if cmax[i][G] != cmax[i - 1][G]:
solutie.append(v[i][0])
j -= v[i][1]
i -= 1
else:
i -= 1
for elem in reversed(solutie):
print(elem, end=' ')
f.close() |
for _ in range(int(input())):
a,b = map(str,input().split())
l1 = len(a)
l2 = len(b)
flag = True
k = ""
while l1>0 and l2>0:
if a[-1]<=b[-1]:
l1-=1
l2-=1
a1 = a[-1]
b1 = b[-1]
a = a[:-1]
b = b[:-1]
a1 = int(a1)
b1 = int(b1)
if not (b1-a1 <10):
flag = False
break
else:
k = f"{b1-a1}" + k
else:
l1-=1
l2-=2
if l2>=0:
pass
if l2<0:
flag = False
break
a1 = a[-1]
b1 = b[-2:]
a = a[:-1]
b = b[:-2]
a1 = int(a1)
b1 = int(b1)
if not (b1-a1 <10 and b1-a1>=0):
flag = False
break
else:
k = f"{b1-a1}" + k
if not (l1 or not flag):
print(int(b+k))
else:
print(-1)
| for _ in range(int(input())):
(a, b) = map(str, input().split())
l1 = len(a)
l2 = len(b)
flag = True
k = ''
while l1 > 0 and l2 > 0:
if a[-1] <= b[-1]:
l1 -= 1
l2 -= 1
a1 = a[-1]
b1 = b[-1]
a = a[:-1]
b = b[:-1]
a1 = int(a1)
b1 = int(b1)
if not b1 - a1 < 10:
flag = False
break
else:
k = f'{b1 - a1}' + k
else:
l1 -= 1
l2 -= 2
if l2 >= 0:
pass
if l2 < 0:
flag = False
break
a1 = a[-1]
b1 = b[-2:]
a = a[:-1]
b = b[:-2]
a1 = int(a1)
b1 = int(b1)
if not (b1 - a1 < 10 and b1 - a1 >= 0):
flag = False
break
else:
k = f'{b1 - a1}' + k
if not (l1 or not flag):
print(int(b + k))
else:
print(-1) |
BILL_TYPES = {
'hconres': 'House Concurrent Resolution',
'hjres': 'House Joint Resolution',
'hr': 'House Bill',
'hres': 'House Resolution',
'sconres': 'Senate Concurrent Resolution',
'sjres': 'Senate Joint Resolution',
's': 'Senate Bill',
'sres': 'Senate Resolution',
}
| bill_types = {'hconres': 'House Concurrent Resolution', 'hjres': 'House Joint Resolution', 'hr': 'House Bill', 'hres': 'House Resolution', 'sconres': 'Senate Concurrent Resolution', 'sjres': 'Senate Joint Resolution', 's': 'Senate Bill', 'sres': 'Senate Resolution'} |
def is_file_h5(item):
output = False
if type(item)==str:
if item.endswith('.h5') or item.endswith('.hdf5'):
output = True
return output
| def is_file_h5(item):
output = False
if type(item) == str:
if item.endswith('.h5') or item.endswith('.hdf5'):
output = True
return output |
class World:
def __init__(self):
self.children = []
def addChild(self, child):
child.world = self
self.children.append(child)
def getChildByName(self, name):
for child in self.children:
if child.name == name:
return name
return None
def getAllChildren(self):
return self.children
| class World:
def __init__(self):
self.children = []
def add_child(self, child):
child.world = self
self.children.append(child)
def get_child_by_name(self, name):
for child in self.children:
if child.name == name:
return name
return None
def get_all_children(self):
return self.children |
class Solution(object):
def findContentChildren(self, g, s):
"""
:type g: List[int]
:type s: List[int]
:rtype: int
"""
g = sorted(g)
s = sorted(s)
ans = 0
start = 0
for x in range(0, len(s)):
for y in range(start, len(g)):
if s[x] >= g[y]:
ans += 1
start = y + 1
break
return ans
| class Solution(object):
def find_content_children(self, g, s):
"""
:type g: List[int]
:type s: List[int]
:rtype: int
"""
g = sorted(g)
s = sorted(s)
ans = 0
start = 0
for x in range(0, len(s)):
for y in range(start, len(g)):
if s[x] >= g[y]:
ans += 1
start = y + 1
break
return ans |
""" Enumerates results and states used by Go CD. """
ASSIGNED = 'Assigned'
BUILDING = 'Building'
CANCELLED = 'Cancelled'
COMPLETED = 'Completed'
COMPLETING = 'Completing'
DISCONTINUED = 'Discontinued'
FAILED = 'Failed'
FAILING = 'Failing'
PASSED = 'Passed'
PAUSED = 'Paused'
PREPARING = 'Preparing'
RESCHEDULED = 'Rescheduled'
SCHEDULED = 'Scheduled'
UNKNOWN = 'Unknown'
WAITING = 'Waiting'
JOB_RESULTS = [
CANCELLED,
FAILED,
PASSED,
UNKNOWN,
]
JOB_STATES = [
ASSIGNED,
BUILDING,
COMPLETED,
COMPLETING,
DISCONTINUED,
PAUSED,
PREPARING,
RESCHEDULED,
SCHEDULED,
UNKNOWN,
WAITING,
]
STAGE_RESULTS = [
CANCELLED,
FAILED,
PASSED,
UNKNOWN,
]
STAGE_STATES = [
BUILDING,
CANCELLED,
FAILED,
FAILING,
PASSED,
UNKNOWN,
]
| """ Enumerates results and states used by Go CD. """
assigned = 'Assigned'
building = 'Building'
cancelled = 'Cancelled'
completed = 'Completed'
completing = 'Completing'
discontinued = 'Discontinued'
failed = 'Failed'
failing = 'Failing'
passed = 'Passed'
paused = 'Paused'
preparing = 'Preparing'
rescheduled = 'Rescheduled'
scheduled = 'Scheduled'
unknown = 'Unknown'
waiting = 'Waiting'
job_results = [CANCELLED, FAILED, PASSED, UNKNOWN]
job_states = [ASSIGNED, BUILDING, COMPLETED, COMPLETING, DISCONTINUED, PAUSED, PREPARING, RESCHEDULED, SCHEDULED, UNKNOWN, WAITING]
stage_results = [CANCELLED, FAILED, PASSED, UNKNOWN]
stage_states = [BUILDING, CANCELLED, FAILED, FAILING, PASSED, UNKNOWN] |
# Taken from https://engineering.semantics3.com/a-simplified-guide-to-grpc-in-python-6c4e25f0c506
def message_to_send(x):
if x=="hi":
return 'hello, how can i help you'
elif x=="good afternoon":
return "good afternoon, how you doing"
elif x== 'Do you think you can really help me?':
return 'Yes, Of Course I can!'
elif x == 'How can I contact You?':
return 'You can call me on 8906803353, 24*7!'
elif x == 'What is the purpose of this chat?':
return 'Not everything has a Purpose, LOL!'
elif x == 'How do I know you?':
return 'It is very simple... I am the server, You are My client!'
elif x == 'Was this a joke?':
return 'I do not know.. Do I seem like a Joker to you??'
elif x == ' I am so tired of talking to you!':
return ' That is because you are RUNNING in your thoughts while talking to me!!'
elif x == ' That is it. I no longer want to talk to you! This chat is over...':
return 'Well, In that case you can talk to my creators Shankar and Ankit.'
elif x == 'Not that drama again.. I know you are good at it! Okay, I forgive you..':
return 'I knew it.. Love you too!'
else:
return "type something please"
'''
elif x == 'Do you think you can really help me?':
return 'Yes, Of Course I can!'
elif x == 'How can I contact You?':
return 'You can call me on 8906803353, 24*7!'
elif x == 'What is the purpose of this chat?':
return 'Not everything has a Purpose, LOL!'
elif x == 'How do I know you?':
return 'It is very simple... I am the server, You are My client!'
elif x == 'Was this a joke?':
return 'I do not know.. Do I seem like a Joker to you??'
elif x == ' I am so tired of talking to you!':
return ' That is because you are RUNNING in your thoughts while talking to me!!'
elif x == ' That is it. I no longer want to talk to you! This chat is over...':
return 'Well, you all are the same. Leave me alone all the time. It seems my heart will break again!'
elif x == 'Not that drama again.. I know you are good at it! Okay, I forgive you..':
return 'I knew it.. Love you too!'
elif x=="exit" or "bye":
pass
else:
return 'Do not be mad at me please. Say something!'
'''
| def message_to_send(x):
if x == 'hi':
return 'hello, how can i help you'
elif x == 'good afternoon':
return 'good afternoon, how you doing'
elif x == 'Do you think you can really help me?':
return 'Yes, Of Course I can!'
elif x == 'How can I contact You?':
return 'You can call me on 8906803353, 24*7!'
elif x == 'What is the purpose of this chat?':
return 'Not everything has a Purpose, LOL!'
elif x == 'How do I know you?':
return 'It is very simple... I am the server, You are My client!'
elif x == 'Was this a joke?':
return 'I do not know.. Do I seem like a Joker to you??'
elif x == ' I am so tired of talking to you!':
return ' That is because you are RUNNING in your thoughts while talking to me!!'
elif x == ' That is it. I no longer want to talk to you! This chat is over...':
return 'Well, In that case you can talk to my creators Shankar and Ankit.'
elif x == 'Not that drama again.. I know you are good at it! Okay, I forgive you..':
return 'I knew it.. Love you too!'
else:
return 'type something please'
' \n\n\n elif x == \'Do you think you can really help me?\':\n return \'Yes, Of Course I can!\'\n elif x == \'How can I contact You?\':\n return \'You can call me on 8906803353, 24*7!\'\n elif x == \'What is the purpose of this chat?\':\n return \'Not everything has a Purpose, LOL!\'\n elif x == \'How do I know you?\':\n return \'It is very simple... I am the server, You are My client!\'\n elif x == \'Was this a joke?\':\n return \'I do not know.. Do I seem like a Joker to you??\'\n elif x == \' I am so tired of talking to you!\':\n return \' That is because you are RUNNING in your thoughts while talking to me!!\'\n elif x == \' That is it. I no longer want to talk to you! This chat is over...\':\n return \'Well, you all are the same. Leave me alone all the time. It seems my heart will break again!\'\n elif x == \'Not that drama again.. I know you are good at it! Okay, I forgive you..\':\n return \'I knew it.. Love you too!\'\n\n elif x=="exit" or "bye":\n pass\n else:\n return \'Do not be mad at me please. Say something!\'\n\n' |
'''
URL: https://leetcode.com/problems/shortest-unsorted-continuous-subarray/description/
Time complexity: O(n)
Space complexity: O(1)
'''
class Solution(object):
def findUnsortedSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
return 0
start = 0
for i in range(1, len(nums)):
if nums[i] < nums[start]:
while start >= 0 and nums[i] < nums[start]:
start -= 1
start += 1
break
start += 1
if start == len(nums) - 1:
return 0
end = len(nums) - 1
for i in range(len(nums)-2, -1, -1):
if nums[i] > nums[end]:
while end < len(nums) and nums[i] > nums[end]:
end += 1
end -= 1
break
end -= 1
min_val, max_val = nums[start], nums[end]
for i in range(start, end+1):
min_val = min(min_val, nums[i])
max_val = max(max_val, nums[i])
u_start, u_end = -1, -1
for i in range(start):
if min_val < nums[i]:
u_start = i
break
for j in range(len(nums)-1, end, -1):
if max_val > nums[j]:
u_end = j
break
if u_start == -1:
u_start = start
if u_end == -1:
u_end = end
return u_end - u_start + 1
| """
URL: https://leetcode.com/problems/shortest-unsorted-continuous-subarray/description/
Time complexity: O(n)
Space complexity: O(1)
"""
class Solution(object):
def find_unsorted_subarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
return 0
start = 0
for i in range(1, len(nums)):
if nums[i] < nums[start]:
while start >= 0 and nums[i] < nums[start]:
start -= 1
start += 1
break
start += 1
if start == len(nums) - 1:
return 0
end = len(nums) - 1
for i in range(len(nums) - 2, -1, -1):
if nums[i] > nums[end]:
while end < len(nums) and nums[i] > nums[end]:
end += 1
end -= 1
break
end -= 1
(min_val, max_val) = (nums[start], nums[end])
for i in range(start, end + 1):
min_val = min(min_val, nums[i])
max_val = max(max_val, nums[i])
(u_start, u_end) = (-1, -1)
for i in range(start):
if min_val < nums[i]:
u_start = i
break
for j in range(len(nums) - 1, end, -1):
if max_val > nums[j]:
u_end = j
break
if u_start == -1:
u_start = start
if u_end == -1:
u_end = end
return u_end - u_start + 1 |
# Python program to implement graph deletion operation | delete node | using dictionary
nodes = []
graph = {}
# delete a node undirected and unweighted
def delete_node(val):
if val not in graph:
print(val, "is not present in the graph")
else:
graph.pop(val) # pop the key with all values
for i in graph: # traverse the dictionary
list1 = graph[i] # assign values to list
if val in list1:
return list1.remove(val) # remove the value
# delete a node directed and wighted graph
def delete_node(val):
if val not in graph:
print(val, "is not present in the graph")
else:
graph.pop(val) # pop the key with all values
for i in graph: # traverse the dictionary
list1 = graph[i] # assign values to list
for j in list1: # search for the value in list1 nested list
if val == j[0]: # check first index of the value
list1.remove(j)
break
delete_node("A")
delete_node("B") | nodes = []
graph = {}
def delete_node(val):
if val not in graph:
print(val, 'is not present in the graph')
else:
graph.pop(val)
for i in graph:
list1 = graph[i]
if val in list1:
return list1.remove(val)
def delete_node(val):
if val not in graph:
print(val, 'is not present in the graph')
else:
graph.pop(val)
for i in graph:
list1 = graph[i]
for j in list1:
if val == j[0]:
list1.remove(j)
break
delete_node('A')
delete_node('B') |
with open('day14/input.txt') as f:
lines = f.readlines()
dic = {}
for line in lines:
a, b = line.strip().split(" -> ")
dic[a] = b
def grow(poly: str) -> str:
result = ""
for i in range(len(poly) - 1):
q = poly[i:i+2]
result += poly[i] +dic[q]
result += poly[-1]
return result
# poly = "NNCB" # sample
poly = "CKFFSCFSCBCKBPBCSPKP"
for i in range(40):
print(i+1)
# print(f"{i+1}: {poly}")
poly = grow(poly)
counts = {}
for p in poly:
if p in counts:
counts[p] += 1
else:
counts[p] = 1
counts = sorted(counts.values())
print(counts[-1] - counts[0])
| with open('day14/input.txt') as f:
lines = f.readlines()
dic = {}
for line in lines:
(a, b) = line.strip().split(' -> ')
dic[a] = b
def grow(poly: str) -> str:
result = ''
for i in range(len(poly) - 1):
q = poly[i:i + 2]
result += poly[i] + dic[q]
result += poly[-1]
return result
poly = 'CKFFSCFSCBCKBPBCSPKP'
for i in range(40):
print(i + 1)
poly = grow(poly)
counts = {}
for p in poly:
if p in counts:
counts[p] += 1
else:
counts[p] = 1
counts = sorted(counts.values())
print(counts[-1] - counts[0]) |
n, m = map(int, input().split())
notes = [list(map(int, input().split())) for _ in range(m)]
if m == 1:
d, h = notes[0]
print(max(h+(d-1), h+(n-d)))
exit(0)
d0, h0 = notes[0]
ans = h0+(d0-1)
for i in range(m-1):
d1, h1 = notes[i]
d2, h2 = notes[i+1]
if d2-d1 < abs(h1-h2):
ans = -1
break
else:
ans = max((h1+h2+(d2-d1))//2, ans)
else:
dm, hm = notes[m-1]
ans = max(ans, hm+(n-dm))
print(ans if ans != -1 else 'IMPOSSIBLE')
| (n, m) = map(int, input().split())
notes = [list(map(int, input().split())) for _ in range(m)]
if m == 1:
(d, h) = notes[0]
print(max(h + (d - 1), h + (n - d)))
exit(0)
(d0, h0) = notes[0]
ans = h0 + (d0 - 1)
for i in range(m - 1):
(d1, h1) = notes[i]
(d2, h2) = notes[i + 1]
if d2 - d1 < abs(h1 - h2):
ans = -1
break
else:
ans = max((h1 + h2 + (d2 - d1)) // 2, ans)
else:
(dm, hm) = notes[m - 1]
ans = max(ans, hm + (n - dm))
print(ans if ans != -1 else 'IMPOSSIBLE') |
t = int(input())
outs = []
for _ in range(t):
n = input()
a = list(map(int, input().split()))
if a[0] != a[1]:
correct = a[2]
else:
correct = a[0]
for i in range(len(a)):
if a[i] != correct:
outs.append(i+1)
break
for out in outs:
print(out) | t = int(input())
outs = []
for _ in range(t):
n = input()
a = list(map(int, input().split()))
if a[0] != a[1]:
correct = a[2]
else:
correct = a[0]
for i in range(len(a)):
if a[i] != correct:
outs.append(i + 1)
break
for out in outs:
print(out) |
d={
"Aligarh":"It is the city in UP ",
"bharatpur":"it is the city in Rajasthan",
"delhi ":"it is the capital of India",
"Mumbai":"it is the city in Maharashtra"
}
print("enter the name which you want to search ")
n1=input()
print(d[n1])
| d = {'Aligarh': 'It is the city in UP ', 'bharatpur': 'it is the city in Rajasthan', 'delhi ': 'it is the capital of India', 'Mumbai': 'it is the city in Maharashtra'}
print('enter the name which you want to search ')
n1 = input()
print(d[n1]) |
class Persona:
def __init__(self,nombre,apellidoPaterno,apellidoMaterno,sexo,edad,domicilio,telefono):
self.nombre = nombre
self.apellidoPaterno = apellidoPaterno
self.apellidoMaterno = apellidoMaterno
self.sexo = sexo
self.edad = edad
self.domicilio = domicilio
self.telefono = telefono
def getNombre(self):
return self.nombre
def getApellidoPaterno(self):
return self.apellidoPaterno
def getApellidoMaterno(self):
return self.apellidoMaterno
def getSexo(self):
return self.sexo
def getEdad(self):
return self.edad
def getDomicilio(self):
return self.domicilio
def getTelefono(self):
return self.telefono
def setNombre(self,nombre):
self.nombre = nombre
def setApellidoPaterno(self,apellidoPaterno):
self.apellidoPaterno = apellidoPaterno
def setApellidoMaterno(self,apellidoMaterno):
self.apellidoMaterno = apellidoMaterno
def setSexo(self,sexo):
self.sexo = sexo
def setEdad(self,edad):
self.edad = edad
def setDomicilio(self,domicilio):
self.domicilio = domicilio
def setTelefono(self,telefono):
self.telefono = telefono
| class Persona:
def __init__(self, nombre, apellidoPaterno, apellidoMaterno, sexo, edad, domicilio, telefono):
self.nombre = nombre
self.apellidoPaterno = apellidoPaterno
self.apellidoMaterno = apellidoMaterno
self.sexo = sexo
self.edad = edad
self.domicilio = domicilio
self.telefono = telefono
def get_nombre(self):
return self.nombre
def get_apellido_paterno(self):
return self.apellidoPaterno
def get_apellido_materno(self):
return self.apellidoMaterno
def get_sexo(self):
return self.sexo
def get_edad(self):
return self.edad
def get_domicilio(self):
return self.domicilio
def get_telefono(self):
return self.telefono
def set_nombre(self, nombre):
self.nombre = nombre
def set_apellido_paterno(self, apellidoPaterno):
self.apellidoPaterno = apellidoPaterno
def set_apellido_materno(self, apellidoMaterno):
self.apellidoMaterno = apellidoMaterno
def set_sexo(self, sexo):
self.sexo = sexo
def set_edad(self, edad):
self.edad = edad
def set_domicilio(self, domicilio):
self.domicilio = domicilio
def set_telefono(self, telefono):
self.telefono = telefono |
# 1. Write a Python class named Rectangle constructed by a length and width and a method which will
# compute the area of a rectangle.
class rectangle():
def __init__(self, width, length):
self.width = width
self.length = length
def area(self):
return self.width * self.length
a = int(input("Enter length of rectangle: "))
b = int(input("Enter width of rectangle: "))
obj = rectangle(a, b)
print("Area of rectangle:", obj.area())
print() | class Rectangle:
def __init__(self, width, length):
self.width = width
self.length = length
def area(self):
return self.width * self.length
a = int(input('Enter length of rectangle: '))
b = int(input('Enter width of rectangle: '))
obj = rectangle(a, b)
print('Area of rectangle:', obj.area())
print() |
CONNECTION_TAB_DEFAULT_TITLE = "Untitled"
CONNECTION_STRING_SUPPORTED_DB_NAMES = ["SQLite"]
CONNECTION_STRING_PLACEHOLDER = "Enter..."
CONNECTION_STRING_DEFAULT = "demo.db"
QUERY_EDITOR_DEFAULT_TEXT = "SELECT name FROM sqlite_master WHERE type='table'"
QUERY_CONTROL_CONNECT_BUTTON_TEXT = "Connect"
QUERY_CONTROL_EXECUTE_BUTTON_TEXT = "Execute"
QUERY_CONTROL_FETCH_BUTTON_TEXT = "Fetch"
QUERY_CONTROL_COMMIT_BUTTON_TEXT = "Commit"
QUERY_CONTROL_ROLLBACK_BUTTON_TEXT = "Rollback"
QUERY_RESULTS_DATA_TAB_TEXT = "Data"
QUERY_RESULTS_EVENTS_TAB_TEXT = "Events"
| connection_tab_default_title = 'Untitled'
connection_string_supported_db_names = ['SQLite']
connection_string_placeholder = 'Enter...'
connection_string_default = 'demo.db'
query_editor_default_text = "SELECT name FROM sqlite_master WHERE type='table'"
query_control_connect_button_text = 'Connect'
query_control_execute_button_text = 'Execute'
query_control_fetch_button_text = 'Fetch'
query_control_commit_button_text = 'Commit'
query_control_rollback_button_text = 'Rollback'
query_results_data_tab_text = 'Data'
query_results_events_tab_text = 'Events' |
# -*- coding: utf-8 -*-
# Copyright 2015 Pietro Brunetti <pietro.brunetti@itb.cnr.it>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__authors__ = "Pietro Brunetti"
__all__ = ["peptidome",
"raw",
"by_targets",
"ChangeTargetPeptides",
'DialogCommons',
'EPPI_data'
"EPPI",
'flatnotebook',
'html_generator',
'Join',
'ManageVars',
'pages',
'project',
'ReportProtein,'
'ReportSequence',
'Resume',
'Search',
'SelPepts',
'Targets']
| __authors__ = 'Pietro Brunetti'
__all__ = ['peptidome', 'raw', 'by_targets', 'ChangeTargetPeptides', 'DialogCommons', 'EPPI_dataEPPI', 'flatnotebook', 'html_generator', 'Join', 'ManageVars', 'pages', 'project', 'ReportProtein,ReportSequence', 'Resume', 'Search', 'SelPepts', 'Targets'] |
#!/usr/bin/python
# This script simply generates a table of the voltage to expect
# if I combine my photoresistors with some of my resitors from stock..
# As there is no strong sunlight at the moment here, I will have to
# postpone the real life testing..
voltage=5.
resistor=[59,180,220,453,750,1000,10000,20000]
measurement=[2000000, 1000000, 600000, 200000, 100000, 80000, 40000, 20000, 10000, 8000, 6000, 4000, 2000, 1000, 800, 600, 400, 200, 100, 80, 60, 40, 20, 8, 2]
def measure(r,p):
return round(voltage-(voltage/(r+p)*r),4)
print("")
print("Photoresistor Simulation")
print("------------------------")
print("")
print("Setup:")
print(" -----[R]---+--(~)---- 5V")
print(" | |")
print(" = 0V {?}")
print(" |")
print(" = 0V")
print("")
print("Table of expected voltage for a given resistor and the resistance")
print("at a certain light exposure (in Ohm):")
print("")
s="~ \\ R\t\t"
for r in resistor:
s+=str(r)+"\t"
print(s)
print("")
for m in measurement:
s=str(m) + "\t\t"
for r in resistor:
s+=str(measure(m,r)) + "\t"
print(s)
| voltage = 5.0
resistor = [59, 180, 220, 453, 750, 1000, 10000, 20000]
measurement = [2000000, 1000000, 600000, 200000, 100000, 80000, 40000, 20000, 10000, 8000, 6000, 4000, 2000, 1000, 800, 600, 400, 200, 100, 80, 60, 40, 20, 8, 2]
def measure(r, p):
return round(voltage - voltage / (r + p) * r, 4)
print('')
print('Photoresistor Simulation')
print('------------------------')
print('')
print('Setup:')
print(' -----[R]---+--(~)---- 5V')
print(' | |')
print(' = 0V {?}')
print(' |')
print(' = 0V')
print('')
print('Table of expected voltage for a given resistor and the resistance')
print('at a certain light exposure (in Ohm):')
print('')
s = '~ \\ R\t\t'
for r in resistor:
s += str(r) + '\t'
print(s)
print('')
for m in measurement:
s = str(m) + '\t\t'
for r in resistor:
s += str(measure(m, r)) + '\t'
print(s) |
# Calculates total acres based on square feet input
# Declare variables
sqftInOneAcre = 43560
# Prompt user for total square feet of parcel of land
totalSqft = float(input('\nEnter total square feet of parcel of land: '))
# Calculate and display total acres
totalAcres = totalSqft / sqftInOneAcre
print('Total acres: ', format(totalAcres, ',.1f'), '\n')
| sqft_in_one_acre = 43560
total_sqft = float(input('\nEnter total square feet of parcel of land: '))
total_acres = totalSqft / sqftInOneAcre
print('Total acres: ', format(totalAcres, ',.1f'), '\n') |
class ReportEntry:
def __init__(self):
self.medium = 'Book'
self.title = None
self.url = None
self.classification = None
self.length = None
self.start_date = None
self.stop_date = None
self.distribution_percent = None
| class Reportentry:
def __init__(self):
self.medium = 'Book'
self.title = None
self.url = None
self.classification = None
self.length = None
self.start_date = None
self.stop_date = None
self.distribution_percent = None |
def rank_cal(rank_list, target_index):
rank = 0.
target_score = rank_list[target_index]
for score in rank_list:
if score >= target_score:
rank += 1.
return rank
def reciprocal_rank(rank):
return 1./rank
def accuracy_at_k(rank, k):
if rank <= k:
return 1.
else:
return 0.
def rank_eval_example(pred, labels):
mrr = []
macc1 = []
macc5 = []
macc10 = []
macc50 = []
cur_pos = []
for i in range(len(pred)):
rank = rank_cal(cas_pred[i], cas_labels[i])
mrr.append(reciprocal_rank(rank))
macc1.append(accuracy_at_k(rank,1))
macc5.append(accuracy_at_k(rank,5))
macc10.append(accuracy_at_k(rank,10))
macc50.append(accuracy_at_k(rank,50))
return mrr, macc1, macc5, macc10, macc50
def rank_eval(pred, labels, sl):
mrr = 0
macc1 = 0
macc5 = 0
macc10 = 0
macc50 = 0
macc100 = 0
cur_pos = 0
for i in range(len(sl)):
length = sl[i]
cas_pred = pred[cur_pos : cur_pos+length]
cas_labels = labels[cur_pos : cur_pos+length]
cur_pos += length
rr = 0
acc1 = 0
acc5 = 0
acc10 = 0
acc50 = 0
acc100 = 0
for j in range(len(cas_pred)):
rank = rank_cal(cas_pred[j], cas_labels[j])
rr += reciprocal_rank(rank)
acc1 += accuracy_at_k(rank,1)
acc5 += accuracy_at_k(rank,5)
acc10 += accuracy_at_k(rank,10)
acc50 += accuracy_at_k(rank,50)
acc100 += accuracy_at_k(rank,100)
mrr += rr/float(length)
macc1 += acc1/float(length)
macc5 += acc5/float(length)
macc10 += acc10/float(length)
macc50 += acc50/float(length)
macc100 += acc100/float(length)
return mrr, macc1, macc5, macc10, macc50, macc100 | def rank_cal(rank_list, target_index):
rank = 0.0
target_score = rank_list[target_index]
for score in rank_list:
if score >= target_score:
rank += 1.0
return rank
def reciprocal_rank(rank):
return 1.0 / rank
def accuracy_at_k(rank, k):
if rank <= k:
return 1.0
else:
return 0.0
def rank_eval_example(pred, labels):
mrr = []
macc1 = []
macc5 = []
macc10 = []
macc50 = []
cur_pos = []
for i in range(len(pred)):
rank = rank_cal(cas_pred[i], cas_labels[i])
mrr.append(reciprocal_rank(rank))
macc1.append(accuracy_at_k(rank, 1))
macc5.append(accuracy_at_k(rank, 5))
macc10.append(accuracy_at_k(rank, 10))
macc50.append(accuracy_at_k(rank, 50))
return (mrr, macc1, macc5, macc10, macc50)
def rank_eval(pred, labels, sl):
mrr = 0
macc1 = 0
macc5 = 0
macc10 = 0
macc50 = 0
macc100 = 0
cur_pos = 0
for i in range(len(sl)):
length = sl[i]
cas_pred = pred[cur_pos:cur_pos + length]
cas_labels = labels[cur_pos:cur_pos + length]
cur_pos += length
rr = 0
acc1 = 0
acc5 = 0
acc10 = 0
acc50 = 0
acc100 = 0
for j in range(len(cas_pred)):
rank = rank_cal(cas_pred[j], cas_labels[j])
rr += reciprocal_rank(rank)
acc1 += accuracy_at_k(rank, 1)
acc5 += accuracy_at_k(rank, 5)
acc10 += accuracy_at_k(rank, 10)
acc50 += accuracy_at_k(rank, 50)
acc100 += accuracy_at_k(rank, 100)
mrr += rr / float(length)
macc1 += acc1 / float(length)
macc5 += acc5 / float(length)
macc10 += acc10 / float(length)
macc50 += acc50 / float(length)
macc100 += acc100 / float(length)
return (mrr, macc1, macc5, macc10, macc50, macc100) |
pos = 0
for k in range(6):
if float(input()) > 2: pos += 1
print(pos, "valores positivos")
| pos = 0
for k in range(6):
if float(input()) > 2:
pos += 1
print(pos, 'valores positivos') |
class NumMatrix:
def __init__(self, matrix: List[List[int]]):
if not any(matrix):
return
m, n = len(matrix), len(matrix[0])
self.tree = [[0] * (n + 1) for _ in range(m + 1)]
self.R = m + 1
self.C = n + 1
for i in range(m):
for j in range(n):
self.add(i + 1, j + 1, matrix[i][j])
self.matrix = matrix
def add(self, row, col, val):
i = row
while i < self.R:
j = col
while j < self.C:
self.tree[i][j] += val
j += (j & (-j))
i += (i & (-i))
def sumRange(self, row, col):
ans = 0
i = row
while i > 0:
j = col
while j > 0:
ans += self.tree[i][j]
j -= (j & (-j))
i -= (i & (-i))
return ans
def update(self, row: int, col: int, val: int) -> None:
self.add(row + 1, col + 1, val - self.matrix[row][col])
self.matrix[row][col] = val
def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:
return self.sumRange(row2 + 1, col2 + 1) - self.sumRange(row2 + 1, col1) - self.sumRange(row1, col2 + 1) + self.sumRange(row1, col1)
# Your NumMatrix object will be instantiated and called as such:
# obj = NumMatrix(matrix)
# obj.update(row,col,val)
# param_2 = obj.sumRegion(row1,col1,row2,col2)
| class Nummatrix:
def __init__(self, matrix: List[List[int]]):
if not any(matrix):
return
(m, n) = (len(matrix), len(matrix[0]))
self.tree = [[0] * (n + 1) for _ in range(m + 1)]
self.R = m + 1
self.C = n + 1
for i in range(m):
for j in range(n):
self.add(i + 1, j + 1, matrix[i][j])
self.matrix = matrix
def add(self, row, col, val):
i = row
while i < self.R:
j = col
while j < self.C:
self.tree[i][j] += val
j += j & -j
i += i & -i
def sum_range(self, row, col):
ans = 0
i = row
while i > 0:
j = col
while j > 0:
ans += self.tree[i][j]
j -= j & -j
i -= i & -i
return ans
def update(self, row: int, col: int, val: int) -> None:
self.add(row + 1, col + 1, val - self.matrix[row][col])
self.matrix[row][col] = val
def sum_region(self, row1: int, col1: int, row2: int, col2: int) -> int:
return self.sumRange(row2 + 1, col2 + 1) - self.sumRange(row2 + 1, col1) - self.sumRange(row1, col2 + 1) + self.sumRange(row1, col1) |
width = 800
height = 700
fps = 60
font_n = 'arial'
sheetload = "spritesheet_jumper.png"
mob_fq = 5000
player_acc = 0.5
player_friction = -0.12
player_gra = 0.8
player_jump = 21
platform_list = [(0,height-50),(width/2-50,height*3/4),
(235,height-350),(350,200),(175,100)]
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
sky = (0,142,205)
| width = 800
height = 700
fps = 60
font_n = 'arial'
sheetload = 'spritesheet_jumper.png'
mob_fq = 5000
player_acc = 0.5
player_friction = -0.12
player_gra = 0.8
player_jump = 21
platform_list = [(0, height - 50), (width / 2 - 50, height * 3 / 4), (235, height - 350), (350, 200), (175, 100)]
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
sky = (0, 142, 205) |
n = int(input())
ans = 0
number = 0
for i in range(n):
a, b = map(int, input().split())
A = int(str(a)[::-1]) # reverse
B = int(str(b)[::-1]) # reverse
ans = A + B
number = int(str(ans)[::-1]) # reverse
print(number)
| n = int(input())
ans = 0
number = 0
for i in range(n):
(a, b) = map(int, input().split())
a = int(str(a)[::-1])
b = int(str(b)[::-1])
ans = A + B
number = int(str(ans)[::-1])
print(number) |
#***Library implementing the sorting algorithms***
def quick_sort(seq,less_than):
if len(seq) < 1:
return seq
else:
pivot=seq[0]
left = quick_sort([x for x in seq[1:] if less_than(x,pivot)],less_than)
right = quick_sort([x for x in seq[1:] if not less_than(x,pivot)],less_than)
return left + [pivot] + right
| def quick_sort(seq, less_than):
if len(seq) < 1:
return seq
else:
pivot = seq[0]
left = quick_sort([x for x in seq[1:] if less_than(x, pivot)], less_than)
right = quick_sort([x for x in seq[1:] if not less_than(x, pivot)], less_than)
return left + [pivot] + right |
# -*- coding: utf-8 -*-
"""
Copyright (C) 2014 Netflix, Inc.
Copyright (C) 2021 Stefano Gottardo (python porting)
SSDP Server helper
SPDX-License-Identifier: BSD-2-Clause
See LICENSES/BSD-2-Clause-Netflix.md for more information.
"""
# IMPORTANT: Make sure to maintain the header structure with exact spaces between header name and value,
# or some mobile apps may not recognise the values correctly.
# CACHE-CONTROL: max-age Amount of time in seconds that the NOTIFY packet should be cached by clients receiving it
# DATE: the format type is "Sat, 09 Jan 2021 09:27:22 GMT"
# M-SEARCH response let know where is the device descriptor XML
SEARCH_RESPONSE = '''\
HTTP/1.1 200 OK
LOCATION: http://{ip_addr}:{port}/ssdp/device-desc.xml
CACHE-CONTROL: max-age=1800
DATE: {date_timestamp}
EXT:
BOOTID.UPNP.ORG: {boot_id}
SERVER: Linux/2.6 UPnP/1.1 appcast_ssdp/1.0
ST: urn:dial-multiscreen-org:service:dial:1
USN: uuid:{device_uuid}::urn:dial-multiscreen-org:service:dial:1
'''
# Notify that the service is changed
ADV_UPDATE = '''\
NOTIFY * HTTP/1.1
HOST: {udp_ip_addr}:{udp_port}
CACHE-CONTROL: max-age=1800
NT: urn:dial-multiscreen-org:service:dial:1
NTS: ssdp:alive
LOCATION: http://{ip_addr}:{port}/dd.xml
USN: uuid:{device_uuid}::urn:dial-multiscreen-org:service:dial:1
'''
# Notify that the service is not available
ADV_BYEBYE = '''\
NOTIFY * HTTP/1.1
HOST: {udp_ip_addr}:{udp_port}
NT: urn:dial-multiscreen-org:service:dial:1
NTS: ssdp:byebye
USN: uuid:{device_uuid}::urn:dial-multiscreen-org:service:dial:1
'''
# Device descriptor XML
DD_XML = '''\
HTTP/1.1 200 OK
Content-Type: text/xml
Application-URL: http://{ip_addr}:{dial_port}/apps/
<?xml version="1.0"?>
<root xmlns="urn:schemas-upnp-org:device-1-0" xmlns:r="urn:restful-tv-org:schemas:upnp-dd">
<specVersion>
<major>1</major>
<minor>0</minor>
</specVersion>
<device>
<deviceType>urn:schemas-upnp-org:device:tvdevice:1</deviceType>
<friendlyName>{friendly_name}</friendlyName>
<manufacturer>{manufacturer_name}</manufacturer>
<modelName>{model_name}</modelName>
<UDN>uuid:{device_uuid}</UDN>
</device>
</root>
'''
| """
Copyright (C) 2014 Netflix, Inc.
Copyright (C) 2021 Stefano Gottardo (python porting)
SSDP Server helper
SPDX-License-Identifier: BSD-2-Clause
See LICENSES/BSD-2-Clause-Netflix.md for more information.
"""
search_response = 'HTTP/1.1 200 OK\nLOCATION: http://{ip_addr}:{port}/ssdp/device-desc.xml\nCACHE-CONTROL: max-age=1800\nDATE: {date_timestamp}\nEXT: \nBOOTID.UPNP.ORG: {boot_id}\nSERVER: Linux/2.6 UPnP/1.1 appcast_ssdp/1.0\nST: urn:dial-multiscreen-org:service:dial:1\nUSN: uuid:{device_uuid}::urn:dial-multiscreen-org:service:dial:1\n\n'
adv_update = 'NOTIFY * HTTP/1.1\nHOST: {udp_ip_addr}:{udp_port}\nCACHE-CONTROL: max-age=1800\nNT: urn:dial-multiscreen-org:service:dial:1\nNTS: ssdp:alive\nLOCATION: http://{ip_addr}:{port}/dd.xml\nUSN: uuid:{device_uuid}::urn:dial-multiscreen-org:service:dial:1\n\n'
adv_byebye = 'NOTIFY * HTTP/1.1\nHOST: {udp_ip_addr}:{udp_port}\nNT: urn:dial-multiscreen-org:service:dial:1\nNTS: ssdp:byebye\nUSN: uuid:{device_uuid}::urn:dial-multiscreen-org:service:dial:1\n\n'
dd_xml = 'HTTP/1.1 200 OK\nContent-Type: text/xml\nApplication-URL: http://{ip_addr}:{dial_port}/apps/\n\n<?xml version="1.0"?>\n<root xmlns="urn:schemas-upnp-org:device-1-0" xmlns:r="urn:restful-tv-org:schemas:upnp-dd">\n <specVersion>\n <major>1</major>\n <minor>0</minor>\n </specVersion>\n <device>\n <deviceType>urn:schemas-upnp-org:device:tvdevice:1</deviceType>\n <friendlyName>{friendly_name}</friendlyName>\n <manufacturer>{manufacturer_name}</manufacturer>\n <modelName>{model_name}</modelName>\n <UDN>uuid:{device_uuid}</UDN>\n </device>\n</root>\n\n' |
class LigneTexte:
"""Une ligne de texte dans un document. """
def __init__(self, texte):
self.texte = texte
| class Lignetexte:
"""Une ligne de texte dans un document. """
def __init__(self, texte):
self.texte = texte |
'''
This module defines the RentalException class, which handles all exception of the type RentalException.
it does not depend on any other module.
'''
class RentalException(Exception):
'''
RentalException class handles all thrown exceptions of the type RentalException. It inherits the Exception
class.
'''
def __init__(self, message):
self._message = message
def __repr__(self, *args, **kwargs):
return "Error! " + self._message
| """
This module defines the RentalException class, which handles all exception of the type RentalException.
it does not depend on any other module.
"""
class Rentalexception(Exception):
"""
RentalException class handles all thrown exceptions of the type RentalException. It inherits the Exception
class.
"""
def __init__(self, message):
self._message = message
def __repr__(self, *args, **kwargs):
return 'Error! ' + self._message |
"""
handler.py
A two operands handler.
"""
class Handler():
def handle(self, expression):
operator = None
operand_1 = None
operand_2 = None
error = None
try:
tokens = expression.split(" ")
operator = tokens[1]
operand_1 = int(tokens[0])
operand_2 = int(tokens[2])
except Exception as exception:
error = "Invalid expression"
return operator, operand_1, operand_2, error
| """
handler.py
A two operands handler.
"""
class Handler:
def handle(self, expression):
operator = None
operand_1 = None
operand_2 = None
error = None
try:
tokens = expression.split(' ')
operator = tokens[1]
operand_1 = int(tokens[0])
operand_2 = int(tokens[2])
except Exception as exception:
error = 'Invalid expression'
return (operator, operand_1, operand_2, error) |
def spd_pgs_limit_range(data, phi=None, theta=None, energy=None):
"""
Applies phi, theta, and energy limits to data structure(s) by
turning off the corresponding bin flags.
Input:
data: dict
Particle data structure
Parameters:
phi: np.ndarray
Minimum and maximum values for phi
theta: np.ndarray
Minimum and maximum values for theta
energy: np.ndarray
Minimum and maximum values for energy
Returns:
Data structure with limits applied (to the bins array)
"""
# if no limits are set, return the input data
if energy is None and theta is None and phi is None:
return data
# apply the phi limits
if phi is not None:
# get min/max phi values for all bins
phi_min = data['phi'] - 0.5*data['dphi']
phi_max = data['phi'] + 0.5*data['dphi'] % 360
# wrap negative values
phi_min[phi_min < 0.0] += 360
# the code below and the phi spectrogram code
# assume maximums at 360 are not wrapped to 0
phi_max[phi_max == 0.0] = 360.0
# find which bins were wrapped back into [0, 360]
wrapped = phi_min > phi_max
# determine which bins intersect the specified range
if phi[0] > phi[1]:
in_range = phi_min < phi[1] or phi_max > phi[0] or wrapped
else:
in_range = ((phi_min < phi[1]) & (phi_max > phi[0])) | (wrapped & ((phi_min < phi[1]) | (phi_max > phi[0])))
data['bins'][in_range == False] = 0
# apply the theta limits
if theta is not None:
lower_theta = min(theta)
upper_theta = max(theta)
# get min/max angle theta values for all bins
theta_min = data['theta'] - 0.5*data['dtheta']
theta_max = data['theta'] + 0.5*data['dtheta']
in_range = (theta_min < upper_theta) & (theta_max > lower_theta)
data['bins'][in_range == False] = 0
# apply the energy limits
if energy is not None:
data['bins'][data['energy'] < energy[0]] = 0
data['bins'][data['energy'] > energy[1]] = 0
return data | def spd_pgs_limit_range(data, phi=None, theta=None, energy=None):
"""
Applies phi, theta, and energy limits to data structure(s) by
turning off the corresponding bin flags.
Input:
data: dict
Particle data structure
Parameters:
phi: np.ndarray
Minimum and maximum values for phi
theta: np.ndarray
Minimum and maximum values for theta
energy: np.ndarray
Minimum and maximum values for energy
Returns:
Data structure with limits applied (to the bins array)
"""
if energy is None and theta is None and (phi is None):
return data
if phi is not None:
phi_min = data['phi'] - 0.5 * data['dphi']
phi_max = data['phi'] + 0.5 * data['dphi'] % 360
phi_min[phi_min < 0.0] += 360
phi_max[phi_max == 0.0] = 360.0
wrapped = phi_min > phi_max
if phi[0] > phi[1]:
in_range = phi_min < phi[1] or phi_max > phi[0] or wrapped
else:
in_range = (phi_min < phi[1]) & (phi_max > phi[0]) | wrapped & ((phi_min < phi[1]) | (phi_max > phi[0]))
data['bins'][in_range == False] = 0
if theta is not None:
lower_theta = min(theta)
upper_theta = max(theta)
theta_min = data['theta'] - 0.5 * data['dtheta']
theta_max = data['theta'] + 0.5 * data['dtheta']
in_range = (theta_min < upper_theta) & (theta_max > lower_theta)
data['bins'][in_range == False] = 0
if energy is not None:
data['bins'][data['energy'] < energy[0]] = 0
data['bins'][data['energy'] > energy[1]] = 0
return data |
class Loss(object):
def __init__(self):
self.output = 0
self.input = 0
def get_output(self, inp, target):
pass
def get_input_gradient(self, target):
pass
| class Loss(object):
def __init__(self):
self.output = 0
self.input = 0
def get_output(self, inp, target):
pass
def get_input_gradient(self, target):
pass |
#Given two arrays, write a function to compute their intersection.
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
l=[]
for i in nums1:
if i in nums2:
l.append(i)
return list(set(l)) | class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
l = []
for i in nums1:
if i in nums2:
l.append(i)
return list(set(l)) |
"""
Module for YamlTemplateFieldBuilder
"""
__author__ = 'DWI'
class TemplateReader(object):
"""
Class for reading complete Templates from files.
"""
def __init__(self, template_field_builder):
self.field_builder = template_field_builder
def read(self, file_name):
"""
Reads the given file and returns a template object
:param file_name: name of the template file
:return: the template that was created
"""
with open(file_name, 'r') as file:
data = self._load_data(file)
return self._build_template(data)
def _load_data(self, file):
pass
def _build_template(self, template_data):
pass
def _load_background_image(self,file_name):
"""
Reads the background image from the given file
:param file_name: name of the file to read the data from
:return: the content of the file as string
"""
try:
with open(file_name, "r") as file:
return file.read()
except FileNotFoundError:
return None | """
Module for YamlTemplateFieldBuilder
"""
__author__ = 'DWI'
class Templatereader(object):
"""
Class for reading complete Templates from files.
"""
def __init__(self, template_field_builder):
self.field_builder = template_field_builder
def read(self, file_name):
"""
Reads the given file and returns a template object
:param file_name: name of the template file
:return: the template that was created
"""
with open(file_name, 'r') as file:
data = self._load_data(file)
return self._build_template(data)
def _load_data(self, file):
pass
def _build_template(self, template_data):
pass
def _load_background_image(self, file_name):
"""
Reads the background image from the given file
:param file_name: name of the file to read the data from
:return: the content of the file as string
"""
try:
with open(file_name, 'r') as file:
return file.read()
except FileNotFoundError:
return None |
#!/user/bin/python
'''Compute the Edit Distance Between Two Strings
The edit-distance between two strings is the minimum number of operations
(insertions, deletions, and substitutions of symbols) to transform one string
into another
'''
# Uses python3
def edit_distance(s, t):
#D[i,0] = i
#D[0,j] = j
m = len(s)
n = len(t)
d = []
for i in range(len(s) + 1):
d.append([i])
del d[0][0]
for j in range(len(t) + 1):
d[0].append(j)
for j in range(1, len(t)+1):
for i in range(1, len(s)+1):
insertion = d[i][j-1] + 1
deletion = d[i-1][j] + 1
match = d[i-1][j-1]
mismatch = d[i-1][j-1] + 1
if s[i-1] == t[j-1]:
d[i].insert(j, match)
else:
minimum = min(insertion, deletion, mismatch)
d[i].insert(j, minimum)
editDist = d[-1][-1]
return editDist
if __name__ == "__main__":
print(edit_distance(input(), input()))
| """Compute the Edit Distance Between Two Strings
The edit-distance between two strings is the minimum number of operations
(insertions, deletions, and substitutions of symbols) to transform one string
into another
"""
def edit_distance(s, t):
m = len(s)
n = len(t)
d = []
for i in range(len(s) + 1):
d.append([i])
del d[0][0]
for j in range(len(t) + 1):
d[0].append(j)
for j in range(1, len(t) + 1):
for i in range(1, len(s) + 1):
insertion = d[i][j - 1] + 1
deletion = d[i - 1][j] + 1
match = d[i - 1][j - 1]
mismatch = d[i - 1][j - 1] + 1
if s[i - 1] == t[j - 1]:
d[i].insert(j, match)
else:
minimum = min(insertion, deletion, mismatch)
d[i].insert(j, minimum)
edit_dist = d[-1][-1]
return editDist
if __name__ == '__main__':
print(edit_distance(input(), input())) |
class iron():
def __init__(self,name,kg):
self.kg = kg
self.name = name
def changeKg(self,newValue):
self.kg = newValue
def changeName(self,newName):
self.newName
| class Iron:
def __init__(self, name, kg):
self.kg = kg
self.name = name
def change_kg(self, newValue):
self.kg = newValue
def change_name(self, newName):
self.newName |
def calculate_power(base, power):
if not power:
return 1
if not power % 2:
return calculate_power(base, power // 2) * calculate_power(base, power // 2)
else:
return calculate_power(base, power // 2) * calculate_power(base, power // 2) * base
if __name__ == "__main__":
a = int(input("Enter base: "))
n = int(input("Enter exponent: "))
print("{}^{} = {}".format(a, n, calculate_power(a, n))) | def calculate_power(base, power):
if not power:
return 1
if not power % 2:
return calculate_power(base, power // 2) * calculate_power(base, power // 2)
else:
return calculate_power(base, power // 2) * calculate_power(base, power // 2) * base
if __name__ == '__main__':
a = int(input('Enter base: '))
n = int(input('Enter exponent: '))
print('{}^{} = {}'.format(a, n, calculate_power(a, n))) |
class Node:
def __init__(self, data, nextNode=None):
self.data = data
self.next = nextNode
# find middle uses a slow pointer and fast pointer (1 ahead) to find the middle
# element of a singly linked list
def find_middle(self):
slow_pointer = self
fast_pointer = self
while fast_pointer.next and fast_pointer.next.next:
slow_pointer = slow_pointer.next
fast_pointer = fast_pointer.next.next
return slow_pointer.data
# test find_middle function
n6 = Node(7)
n5 = Node(6, n6)
n4 = Node(5, n5)
n3 = Node(4, n4)
n2 = Node(3, n3)
n1 = Node(2, n2)
head = Node(1, n1)
middle = head.find_middle()
print("Linked List: ", "1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7")
print("Middle Node: ", middle)
| class Node:
def __init__(self, data, nextNode=None):
self.data = data
self.next = nextNode
def find_middle(self):
slow_pointer = self
fast_pointer = self
while fast_pointer.next and fast_pointer.next.next:
slow_pointer = slow_pointer.next
fast_pointer = fast_pointer.next.next
return slow_pointer.data
n6 = node(7)
n5 = node(6, n6)
n4 = node(5, n5)
n3 = node(4, n4)
n2 = node(3, n3)
n1 = node(2, n2)
head = node(1, n1)
middle = head.find_middle()
print('Linked List: ', '1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7')
print('Middle Node: ', middle) |
def extract_cfg(cfg, prefix, sep='.'):
out = {}
for key,val in cfg.items():
if not key.startswith(prefix): continue
key = key[len(prefix)+len(sep):]
if sep in key or not key: continue
out[key] = val
return out
if __name__=="__main__":
cfg = {
'a.1':'aaa',
'a.2':'bbb',
'a.x.1':'ccc',
'a.x.2':'ddd',
'b.x':'eee',
}
print(extract_cfg(cfg,'a.x'))
| def extract_cfg(cfg, prefix, sep='.'):
out = {}
for (key, val) in cfg.items():
if not key.startswith(prefix):
continue
key = key[len(prefix) + len(sep):]
if sep in key or not key:
continue
out[key] = val
return out
if __name__ == '__main__':
cfg = {'a.1': 'aaa', 'a.2': 'bbb', 'a.x.1': 'ccc', 'a.x.2': 'ddd', 'b.x': 'eee'}
print(extract_cfg(cfg, 'a.x')) |
'''
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
# if not inorder or not postorder:
# return None
if inorder:
ind = inorder.index(postorder.pop())
root = TreeNode(inorder[ind])
root.right = self.buildTree(inorder[ind+1:], postorder)
root.left = self.buildTree(inorder[0:ind], postorder)
return root | """
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
Return the following binary tree:
3
/ 9 20
/ 15 7
"""
class Solution:
def build_tree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
if inorder:
ind = inorder.index(postorder.pop())
root = tree_node(inorder[ind])
root.right = self.buildTree(inorder[ind + 1:], postorder)
root.left = self.buildTree(inorder[0:ind], postorder)
return root |
# -*- coding: utf-8 -*-
def get_tokens(line):
"""tokenize an Epanet line (i.e. split words; stopping when ; encountered)"""
tokens=list()
words=line.split()
for word in words:
if word[:1] == ';':
break
else:
tokens.append(word)
return tokens
def read_epanet_file(filename):
"""read ressources from a epanet input file"""
pipes = None;
tanks = None;
valves = None;
junctions = None;
reservoirs = None;
# EPANET file format is documented here :
# https://github.com/OpenWaterAnalytics/EPANET/wiki/Input-File-Format
#
# EPANET parser
# https://github.com/OpenWaterAnalytics/EPANET/blob/master/src/input3.c
line_number = 0
section = None
with open(filename, "r") as input_file:
for line in input_file:
line_number += 1
tokens = get_tokens(line)
if len(tokens) > 0:
if tokens[0][:1] == '[':
# section keyword, check that it ends with a ']'
if tokens[0][-1:] == ']':
section = tokens[0]
if tokens[0] == '[JUNCTIONS]':
if junctions is None:
junctions = dict()
else:
print("WARNING duplicated section at line {} : {}".format(line_number, line))
elif tokens[0] == '[PIPES]':
if pipes is None:
pipes = dict()
else:
print("WARNING duplicated section at line {} : {}".format(line_number, line))
elif tokens[0] == '[TANKS]':
if tanks is None:
tanks = dict()
else:
print("WARNING duplicated section at line {} : {}".format(line_number, line))
elif tokens[0] == '[RESERVOIRS]':
if reservoirs is None:
reservoirs = dict()
else:
print("WARNING duplicated section at line {} : {}".format(line_number, line))
elif tokens[0] == '[VALVES]':
if valves is None:
valves = dict()
else:
print("WARNING duplicated section at line {} : {}".format(line_number, line))
else:
print("ERROR invalid section name at line {} : {}".format(line_number, line))
else:
# in section line
if section is None:
print("WARNING lines before any section at line {} : {}".format(line_number, line))
elif section == '[JUNCTIONS]':
pass
elif section == '[PIPES]':
if tokens[0] not in pipes:
# from EPANET file format and parser implementation
# extract pipe status or use default value otherwise
status = None
if len(tokens) == 6:
# no optional status, status is Open per default
status = 'Open'
elif len(tokens) == 7:
# optional status
status = tokens[-1]
elif len(tokens) == 8:
# optional minor loss and optional status
status = tokens[-1]
# sanity check on pipe status
if status == 'Open':
pass
elif status == 'Closed':
pass
elif status == 'CV':
pass
else:
status = None
if status is None:
print("ERROR invalid pipe format line {} : {}".format(line_number, line))
else:
# ignore status for now, to be checked with Professor
status = 'Open'
pipes[tokens[0]] = (tokens[1], tokens[2], status)
else:
# sanity check
print("duplicated pipes {}".format(tokens[0]))
elif section == '[VALVES]':
if tokens[0] not in valves:
valves[tokens[0]] = (tokens[1], tokens[2])
else:
# sanity check
print("duplicated valves {}".format(tokens[0]))
elif section == '[TANKS]':
if tokens[0] not in tanks:
tanks[tokens[0]] = None
else:
# sanity check
print("duplicated tanks {}".format(tokens[0]))
elif section == '[RESERVOIRS]':
if tokens[0] not in reservoirs:
reservoirs[tokens[0]] = None
else:
# sanity check
print("duplicated reservoirs {}".format(tokens[0]))
else:
# kind of section not handled
pass
resources = dict()
resources["pipes"] = pipes
resources["valves"] = valves
resources["reservoirs"] = reservoirs
resources["tanks"] = tanks
resources["junctions"] = junctions
return resources
| def get_tokens(line):
"""tokenize an Epanet line (i.e. split words; stopping when ; encountered)"""
tokens = list()
words = line.split()
for word in words:
if word[:1] == ';':
break
else:
tokens.append(word)
return tokens
def read_epanet_file(filename):
"""read ressources from a epanet input file"""
pipes = None
tanks = None
valves = None
junctions = None
reservoirs = None
line_number = 0
section = None
with open(filename, 'r') as input_file:
for line in input_file:
line_number += 1
tokens = get_tokens(line)
if len(tokens) > 0:
if tokens[0][:1] == '[':
if tokens[0][-1:] == ']':
section = tokens[0]
if tokens[0] == '[JUNCTIONS]':
if junctions is None:
junctions = dict()
else:
print('WARNING duplicated section at line {} : {}'.format(line_number, line))
elif tokens[0] == '[PIPES]':
if pipes is None:
pipes = dict()
else:
print('WARNING duplicated section at line {} : {}'.format(line_number, line))
elif tokens[0] == '[TANKS]':
if tanks is None:
tanks = dict()
else:
print('WARNING duplicated section at line {} : {}'.format(line_number, line))
elif tokens[0] == '[RESERVOIRS]':
if reservoirs is None:
reservoirs = dict()
else:
print('WARNING duplicated section at line {} : {}'.format(line_number, line))
elif tokens[0] == '[VALVES]':
if valves is None:
valves = dict()
else:
print('WARNING duplicated section at line {} : {}'.format(line_number, line))
else:
print('ERROR invalid section name at line {} : {}'.format(line_number, line))
elif section is None:
print('WARNING lines before any section at line {} : {}'.format(line_number, line))
elif section == '[JUNCTIONS]':
pass
elif section == '[PIPES]':
if tokens[0] not in pipes:
status = None
if len(tokens) == 6:
status = 'Open'
elif len(tokens) == 7:
status = tokens[-1]
elif len(tokens) == 8:
status = tokens[-1]
if status == 'Open':
pass
elif status == 'Closed':
pass
elif status == 'CV':
pass
else:
status = None
if status is None:
print('ERROR invalid pipe format line {} : {}'.format(line_number, line))
else:
status = 'Open'
pipes[tokens[0]] = (tokens[1], tokens[2], status)
else:
print('duplicated pipes {}'.format(tokens[0]))
elif section == '[VALVES]':
if tokens[0] not in valves:
valves[tokens[0]] = (tokens[1], tokens[2])
else:
print('duplicated valves {}'.format(tokens[0]))
elif section == '[TANKS]':
if tokens[0] not in tanks:
tanks[tokens[0]] = None
else:
print('duplicated tanks {}'.format(tokens[0]))
elif section == '[RESERVOIRS]':
if tokens[0] not in reservoirs:
reservoirs[tokens[0]] = None
else:
print('duplicated reservoirs {}'.format(tokens[0]))
else:
pass
resources = dict()
resources['pipes'] = pipes
resources['valves'] = valves
resources['reservoirs'] = reservoirs
resources['tanks'] = tanks
resources['junctions'] = junctions
return resources |
class SmMarket:
def __init__(self):
self.name = ""
self.product_dic = {}
def add_category(self, product):
self.product_dic[product.code] = product | class Smmarket:
def __init__(self):
self.name = ''
self.product_dic = {}
def add_category(self, product):
self.product_dic[product.code] = product |
#project
print("welcome to the Band name generator")
city_name = input("Enter the city you were born: ")
pet_name = input("Enter your pet name: ")
print(f"your band name could be {city_name} {pet_name}")
#coding exercise(Print)
print("Day 1 - Python Print Function")
print("The function is declared like this:")
print("print(\"what to print\")")
#coding exercise(Print with new line)
print('Day 1 - String Manipulation\nString Concatenation is done with the "+" sign.\ne.g. print("Hello " + "world")\nNew lines can be created with a backslash and n.')
#coding exercise with len,input and print function
print(len(input("What is your name?\n")))
#coding exercise for swapping numbers(variables)
a = input("a: ")
b = input("b: ")
a,b = b,a
print("a: ",a)
print("b: ",b)
| print('welcome to the Band name generator')
city_name = input('Enter the city you were born: ')
pet_name = input('Enter your pet name: ')
print(f'your band name could be {city_name} {pet_name}')
print('Day 1 - Python Print Function')
print('The function is declared like this:')
print('print("what to print")')
print('Day 1 - String Manipulation\nString Concatenation is done with the "+" sign.\ne.g. print("Hello " + "world")\nNew lines can be created with a backslash and n.')
print(len(input('What is your name?\n')))
a = input('a: ')
b = input('b: ')
(a, b) = (b, a)
print('a: ', a)
print('b: ', b) |
"""
signals we use to trigger regular batch jobs
"""
run_hourly_jobs = object()
run_daily_jobs = object()
run_weekly_jobs = object()
run_monthly_jobs = object()
| """
signals we use to trigger regular batch jobs
"""
run_hourly_jobs = object()
run_daily_jobs = object()
run_weekly_jobs = object()
run_monthly_jobs = object() |
num1=int(input("Enter first number :- "))
num2=int(input("Enter second number :- "))
print("Which opertation you want apply 1.add, 2.sub, 3.div")
op=input()
def add():
c=num1+num2
print("After Add",c)
def sub():
c=num1-num2
print("After sub",c)
def div():
c=num1/num2
print("After div",c)
def again():
print("If you want to perform any other operation")
print("say Yes or y else NO or n")
ans=input()
if ans=="yes" or ans=="y":
cal()
else:
print(" Good Bye")
def cal():
if op=='1' or op=="add" or op=="1.add":
add()
elif op=='2' or op=="sub" or op=="2.sub":
sub()
elif op=='3' or op=="div" or op=="3.div":
div()
else:
print("Invalid Operation")
again()
cal()
again()
| num1 = int(input('Enter first number :- '))
num2 = int(input('Enter second number :- '))
print('Which opertation you want apply 1.add, 2.sub, 3.div')
op = input()
def add():
c = num1 + num2
print('After Add', c)
def sub():
c = num1 - num2
print('After sub', c)
def div():
c = num1 / num2
print('After div', c)
def again():
print('If you want to perform any other operation')
print('say Yes or y else NO or n')
ans = input()
if ans == 'yes' or ans == 'y':
cal()
else:
print(' Good Bye')
def cal():
if op == '1' or op == 'add' or op == '1.add':
add()
elif op == '2' or op == 'sub' or op == '2.sub':
sub()
elif op == '3' or op == 'div' or op == '3.div':
div()
else:
print('Invalid Operation')
again()
cal()
again() |
def get_odd_and_even_sets(n):
odd_nums = set()
even_nums = set()
for line in range(1, n + 1):
name = input()
name_ascii_sum = sum([ord(char) for char in name])
devised_num = name_ascii_sum // line
if devised_num % 2 == 0:
even_nums.add(devised_num)
else:
odd_nums.add(devised_num)
return odd_nums, even_nums
def print_result(odd_nums_sum, even_nums_sum, odd_nums, even_nums):
if odd_nums_sum == even_nums_sum:
union_values = odd_nums.union(even_nums)
print(', '.join(map(str, union_values)))
elif odd_nums_sum > even_nums_sum:
different_values = odd_nums.difference(even_nums)
print(', '.join(map(str, different_values)))
else:
symmetric_different_values = even_nums.symmetric_difference(odd_nums)
print(', '.join(map(str, symmetric_different_values)))
odd_nums, even_nums = get_odd_and_even_sets(int(input()))
odd_nums_sum = sum(odd_nums)
even_nums_sum = sum(even_nums)
print_result(odd_nums_sum, even_nums_sum, odd_nums, even_nums)
| def get_odd_and_even_sets(n):
odd_nums = set()
even_nums = set()
for line in range(1, n + 1):
name = input()
name_ascii_sum = sum([ord(char) for char in name])
devised_num = name_ascii_sum // line
if devised_num % 2 == 0:
even_nums.add(devised_num)
else:
odd_nums.add(devised_num)
return (odd_nums, even_nums)
def print_result(odd_nums_sum, even_nums_sum, odd_nums, even_nums):
if odd_nums_sum == even_nums_sum:
union_values = odd_nums.union(even_nums)
print(', '.join(map(str, union_values)))
elif odd_nums_sum > even_nums_sum:
different_values = odd_nums.difference(even_nums)
print(', '.join(map(str, different_values)))
else:
symmetric_different_values = even_nums.symmetric_difference(odd_nums)
print(', '.join(map(str, symmetric_different_values)))
(odd_nums, even_nums) = get_odd_and_even_sets(int(input()))
odd_nums_sum = sum(odd_nums)
even_nums_sum = sum(even_nums)
print_result(odd_nums_sum, even_nums_sum, odd_nums, even_nums) |
class Debugger:
def __init__(self):
self.collectors = {}
def add_collector(self, collector):
self.collectors.update({collector.name: collector})
return self
def get_collector(self, name):
return self.collectors[name]
| class Debugger:
def __init__(self):
self.collectors = {}
def add_collector(self, collector):
self.collectors.update({collector.name: collector})
return self
def get_collector(self, name):
return self.collectors[name] |
frutas = open('frutas.txt', 'r')
numeros = open('numeros.txt', 'r')
def copia_lista(lista:list)->list:
return lista.copy()
"""
if __name__ == "__main__":
lista_fruta_nueva=eliminar_un_caracter_de_toda_la_lista(lista_frutas,"\n")
print(lista_fruta_nueva)
""" | frutas = open('frutas.txt', 'r')
numeros = open('numeros.txt', 'r')
def copia_lista(lista: list) -> list:
return lista.copy()
'\nif __name__ == "__main__":\n lista_fruta_nueva=eliminar_un_caracter_de_toda_la_lista(lista_frutas,"\n")\n print(lista_fruta_nueva)\n' |
# Only these modalities are available for query
ALLOWED_MODALITIES = ['bold', 'T1w', 'T2w']
STRUCTURAL_MODALITIES = ['T1w', 'T2w']
# Name of a subdirectory to hold fetched query results
FETCHED_DIR = 'fetched'
# Name of a subdirectory containing MRIQC group results used as inputs.
INPUTS_DIR = 'inputs'
# Name of the subdirectory which holds output reports.
REPORTS_DIR = 'reports'
# File extensions for report files and BIDS-compliant data files.
BIDS_DATA_EXT = '.tsv'
PLOT_EXT = '.png'
REPORTS_EXT = '.html'
# Symbolic exit codes for various error exit scenarios
INPUT_FILE_EXIT_CODE = 10
OUTPUT_FILE_EXIT_CODE = 11
QUERY_FILE_EXIT_CODE = 12
FETCHED_DIR_EXIT_CODE = 20
INPUTS_DIR_EXIT_CODE = 21
REPORTS_DIR_EXIT_CODE = 22
NUM_RECS_EXIT_CODE = 30
| allowed_modalities = ['bold', 'T1w', 'T2w']
structural_modalities = ['T1w', 'T2w']
fetched_dir = 'fetched'
inputs_dir = 'inputs'
reports_dir = 'reports'
bids_data_ext = '.tsv'
plot_ext = '.png'
reports_ext = '.html'
input_file_exit_code = 10
output_file_exit_code = 11
query_file_exit_code = 12
fetched_dir_exit_code = 20
inputs_dir_exit_code = 21
reports_dir_exit_code = 22
num_recs_exit_code = 30 |
"""
File IO
1.Create
-------------------
f = open('file_name.txt','w')
f.close()
-------------------
2.Write
-------------------
f = open('file_name.txt','w')
data = 'hi'
f.write(data)
f.close()
-------------------
3.Read
1) Readline
-------------------
f = open('file_name.txt','r')
line = f.readline()
print(line)
f.close()
-------------------
-------------------
f = open('file_name.txt','r')
while True:
line = f.readline()
if not line: break
print(line)
f.close
-------------------
---> if readline() has nothing to read, it returns ''(False).
2) Readlines
3) Read
4. Add new data
1) with mode 'a'
-------------------
f = open('file_name.txt','a')
data = 'hi'
f.write(data)
f.close()
-------------------
5. With : autoclose
-------------------
f = open('file_name.txt','w')
f.write('SNP what you want to SNP')
f.close
-------------------
equals to
-------------------
with open('file_name.txt','w') as f:
f.write('SNP what you want to SNP')
-------------------
""" | """
File IO
1.Create
-------------------
f = open('file_name.txt','w')
f.close()
-------------------
2.Write
-------------------
f = open('file_name.txt','w')
data = 'hi'
f.write(data)
f.close()
-------------------
3.Read
1) Readline
-------------------
f = open('file_name.txt','r')
line = f.readline()
print(line)
f.close()
-------------------
-------------------
f = open('file_name.txt','r')
while True:
line = f.readline()
if not line: break
print(line)
f.close
-------------------
---> if readline() has nothing to read, it returns ''(False).
2) Readlines
3) Read
4. Add new data
1) with mode 'a'
-------------------
f = open('file_name.txt','a')
data = 'hi'
f.write(data)
f.close()
-------------------
5. With : autoclose
-------------------
f = open('file_name.txt','w')
f.write('SNP what you want to SNP')
f.close
-------------------
equals to
-------------------
with open('file_name.txt','w') as f:
f.write('SNP what you want to SNP')
-------------------
""" |
# Problem Statement: https://www.hackerrank.com/challenges/symmetric-difference/problem
_, M = int(input()), set(map(int, input().split()))
_, N = int(input()), set(map(int, input().split()))
print(*sorted(M ^ N), sep='\n') | (_, m) = (int(input()), set(map(int, input().split())))
(_, n) = (int(input()), set(map(int, input().split())))
print(*sorted(M ^ N), sep='\n') |
# The manage.py of the {{ project_name }} test project
# template context:
project_name = '{{ project_name }}'
project_directory = '{{ project_directory }}'
secret_key = '{{ secret_key }}'
| project_name = '{{ project_name }}'
project_directory = '{{ project_directory }}'
secret_key = '{{ secret_key }}' |
class PaymentStrategy(object):
def get_payment_metadata(self,service_client):
pass
def get_price(self,service_client):
pass
| class Paymentstrategy(object):
def get_payment_metadata(self, service_client):
pass
def get_price(self, service_client):
pass |
#this program demonstrates several functions of the list class
x = [0.0, 3.0, 5.0, 2.5, 3.7]
print(type(x)) #prints datatype of x (list)
x.pop(2) #remove the 3rd element of x (5.0)
print(x)
x.remove(2.5) #remove the element 2.5 (index 2)
print(x)
x.append(1.2) #add a new element to the end (1.2)
print(x)
y = x.copy() #make a copy of x's current state (y)
print(y)
print(y.count(0.0)) #print the number of elements equal to 0.0 (1)
print(y.index(3.7)) #print the index of the element 3.7 (2)
y.sort() #sort the list y by value
print(y)
y.reverse() #reverse the order of elements in list y
print(y)
y.clear() #remove all elements from y
print(y) | x = [0.0, 3.0, 5.0, 2.5, 3.7]
print(type(x))
x.pop(2)
print(x)
x.remove(2.5)
print(x)
x.append(1.2)
print(x)
y = x.copy()
print(y)
print(y.count(0.0))
print(y.index(3.7))
y.sort()
print(y)
y.reverse()
print(y)
y.clear()
print(y) |
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 28 22:08:00 2017
@author: Roberto Piga
"""
s = 'azcbobobegghakl'
s = 'abcbcd'
subString = ""
maxString = ""
charval = ""
for char in s:
if char >= charval:
subString += char
elif char < charval:
subString = char
charval = char
if len(subString) > len(maxString):
maxString = subString
print("Longest substring in alphabetical order is:", maxString)
| """
Created on Sat Jan 28 22:08:00 2017
@author: Roberto Piga
"""
s = 'azcbobobegghakl'
s = 'abcbcd'
sub_string = ''
max_string = ''
charval = ''
for char in s:
if char >= charval:
sub_string += char
elif char < charval:
sub_string = char
charval = char
if len(subString) > len(maxString):
max_string = subString
print('Longest substring in alphabetical order is:', maxString) |
# Enter your code here. Read input from STDIN. Print output to STDOUT
size = int(input())
nums = list(map(int, input().split()))
weights = list(map(int, input().split()))
weighted_sum = 0
for i in range(size):
weighted_sum += nums[i] * weights[i]
print(round(weighted_sum / sum(weights), 1))
| size = int(input())
nums = list(map(int, input().split()))
weights = list(map(int, input().split()))
weighted_sum = 0
for i in range(size):
weighted_sum += nums[i] * weights[i]
print(round(weighted_sum / sum(weights), 1)) |
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
m = len(matrix)
n = len(matrix[0]) if m else 0
if m * n == 0:
return False
if target < matrix[0][0] or target > matrix[-1][-1]:
return False
i = 0
j = len(matrix) - 1
if target>=matrix[-1][0]:
return self.searchList(matrix[-1], target)
while i < j - 1:
mid = (i + j) // 2
if matrix[mid][0] == target:
return True
if matrix[mid][0] < target:
i = mid
else:
j = mid
return self.searchList(matrix[i], target)
def searchList(self, l, t):
i = 0
j = len(l) - 1
while i <= j:
m = (i + j) // 2
if l[m] == t:
return True
if l[m] > t:
j = m - 1
else:
i = m + 1
return False
| class Solution(object):
def search_matrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
m = len(matrix)
n = len(matrix[0]) if m else 0
if m * n == 0:
return False
if target < matrix[0][0] or target > matrix[-1][-1]:
return False
i = 0
j = len(matrix) - 1
if target >= matrix[-1][0]:
return self.searchList(matrix[-1], target)
while i < j - 1:
mid = (i + j) // 2
if matrix[mid][0] == target:
return True
if matrix[mid][0] < target:
i = mid
else:
j = mid
return self.searchList(matrix[i], target)
def search_list(self, l, t):
i = 0
j = len(l) - 1
while i <= j:
m = (i + j) // 2
if l[m] == t:
return True
if l[m] > t:
j = m - 1
else:
i = m + 1
return False |
# Lower-level functionality for build config.
# The functions in this file might be referred by tensorflow.bzl. They have to
# be separate to avoid cyclic references.
WITH_XLA_SUPPORT = True
def tf_cuda_tests_tags():
return ["local"]
def tf_sycl_tests_tags():
return ["local"]
def tf_additional_plugin_deps():
deps = []
if WITH_XLA_SUPPORT:
deps.append("//tensorflow/compiler/jit")
return deps
def tf_additional_xla_deps_py():
return []
def tf_additional_license_deps():
licenses = []
if WITH_XLA_SUPPORT:
licenses.append("@llvm//:LICENSE.TXT")
return licenses
| with_xla_support = True
def tf_cuda_tests_tags():
return ['local']
def tf_sycl_tests_tags():
return ['local']
def tf_additional_plugin_deps():
deps = []
if WITH_XLA_SUPPORT:
deps.append('//tensorflow/compiler/jit')
return deps
def tf_additional_xla_deps_py():
return []
def tf_additional_license_deps():
licenses = []
if WITH_XLA_SUPPORT:
licenses.append('@llvm//:LICENSE.TXT')
return licenses |
# Write a function that takes a string as input and reverse only the vowels of a string.
# Example 1:
# Input: "hello"
# Output: "holle"
# Example 2:
# Input: "leetcode"
# Output: "leotcede"
class Solution(object):
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
dic = {"a", "e", "i", "o", "u", "A", "E","I","O","U"}
string = list(s)
i,j = 0, len(string) - 1
while i < j:
while i < j and string[i] not in dic:
i += 1
while i < j and string[j] not in dic:
j -= 1
string[i], string[j] = string[j], string[i]
i += 1
j -= 1
return "".join(string)
# Time: O(n)
# Space: O(n)
# Difficulty: easy | class Solution(object):
def reverse_vowels(self, s):
"""
:type s: str
:rtype: str
"""
dic = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
string = list(s)
(i, j) = (0, len(string) - 1)
while i < j:
while i < j and string[i] not in dic:
i += 1
while i < j and string[j] not in dic:
j -= 1
(string[i], string[j]) = (string[j], string[i])
i += 1
j -= 1
return ''.join(string) |
def estimation(text,img_num):
len_text = len(text)
read_time = (len_text/1000) + img_num*0.2
if read_time < 1:
return 1
return round(read_time) | def estimation(text, img_num):
len_text = len(text)
read_time = len_text / 1000 + img_num * 0.2
if read_time < 1:
return 1
return round(read_time) |
numbers = [10, 20, 300, 40, 50]
# random indexing --> O(1) get items if we know the index !!!
print(numbers[4])
# it can store different data types
# numbers[1] = "Adam"
# iteration methods
# for i in range(len(numbers)):
# print(numbers[i])
# for num in numbers:
# print(num)
# remove last two items
print(numbers[:-2])
# show only first 2 items
print(numbers[0:2])
# show 3rd item onwards
print(numbers[2:])
# get the highest number in the array
# O(n) linear time complexity
# this type of search is slow on large array
maximum = numbers[0]
for num in numbers:
if num > maximum:
maximum = num
print(maximum)
| numbers = [10, 20, 300, 40, 50]
print(numbers[4])
print(numbers[:-2])
print(numbers[0:2])
print(numbers[2:])
maximum = numbers[0]
for num in numbers:
if num > maximum:
maximum = num
print(maximum) |
''' Example of python control structures '''
a = 5
b = int(input("Enter an integer: "))
# If-then-else statment
if a < b:
print('{} is less than {}'.format(a,b))
elif a > b:
print('{} is greater than {}'.format(a,b))
else:
print('{} is equal to {}'.format(a,b))
# While loop
ii = 0
print("While loop:")
while ii <= b:
print( "Your number = {}, loop variable = {}".format(b,ii))
ii+=1
# For loop
print("For loop:")
for ii in range(b):
print(" for: loop variable = {}".format(ii))
print("Iterate over a list:")
for ss in ['This is', 'a list', 'of strings']:
print(ss)
# break & continue
for ii in range(100000):
if ii > b:
print("Breaking at {}".format(ii))
break
print("Continue if not divisible by 3:")
for ii in range(b+1):
if not (ii % 3) == 0:
continue
print(" {}".format(ii))
| """ Example of python control structures """
a = 5
b = int(input('Enter an integer: '))
if a < b:
print('{} is less than {}'.format(a, b))
elif a > b:
print('{} is greater than {}'.format(a, b))
else:
print('{} is equal to {}'.format(a, b))
ii = 0
print('While loop:')
while ii <= b:
print('Your number = {}, loop variable = {}'.format(b, ii))
ii += 1
print('For loop:')
for ii in range(b):
print(' for: loop variable = {}'.format(ii))
print('Iterate over a list:')
for ss in ['This is', 'a list', 'of strings']:
print(ss)
for ii in range(100000):
if ii > b:
print('Breaking at {}'.format(ii))
break
print('Continue if not divisible by 3:')
for ii in range(b + 1):
if not ii % 3 == 0:
continue
print(' {}'.format(ii)) |
"""
Calculating the mean
"""
def calculate_mean(numbers):
s=sum(numbers)
N=len(numbers)
mean=s/N
return mean
def main():
donations=[100,60,70,900,100,200,500,500,503,600,1000,1200]
mean=calculate_mean(donations)
N=len(donations)
print("Mean donation over the last {0} days is {1}".format(N,mean))
| """
Calculating the mean
"""
def calculate_mean(numbers):
s = sum(numbers)
n = len(numbers)
mean = s / N
return mean
def main():
donations = [100, 60, 70, 900, 100, 200, 500, 500, 503, 600, 1000, 1200]
mean = calculate_mean(donations)
n = len(donations)
print('Mean donation over the last {0} days is {1}'.format(N, mean)) |
'''
Created on Apr 2, 2021
@author: mballance
'''
class InitializeReq(object):
def __init__(self):
self.module = None
self.entry = None
def dump(self):
pass
@staticmethod
def load(msg) -> 'InitializeReq':
ret = InitializeReq()
if "module" in msg.keys():
ret.module = msg["module"]
if "entry" in msg.keys():
ret.entry = msg["entry"]
return ret
| """
Created on Apr 2, 2021
@author: mballance
"""
class Initializereq(object):
def __init__(self):
self.module = None
self.entry = None
def dump(self):
pass
@staticmethod
def load(msg) -> 'InitializeReq':
ret = initialize_req()
if 'module' in msg.keys():
ret.module = msg['module']
if 'entry' in msg.keys():
ret.entry = msg['entry']
return ret |
# 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 Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
ans = True
def traversal(node_p, node_q):
nonlocal ans
if node_p is None and node_q is None:
return
if node_p is None or node_q is None:
ans = False
return
if node_p.val != node_q.val:
ans = False
return
traversal(node_p.left, node_q.left)
traversal(node_p.right, node_q.right)
traversal(p, q)
return ans
| class Solution:
def is_same_tree(self, p: TreeNode, q: TreeNode) -> bool:
ans = True
def traversal(node_p, node_q):
nonlocal ans
if node_p is None and node_q is None:
return
if node_p is None or node_q is None:
ans = False
return
if node_p.val != node_q.val:
ans = False
return
traversal(node_p.left, node_q.left)
traversal(node_p.right, node_q.right)
traversal(p, q)
return ans |
'''Many Values to Multiple Variables
Python allows you to assign values to multiple variables in one line:'''
x = y = z = "Orange"
print(x)
print(y)
print(z) | """Many Values to Multiple Variables
Python allows you to assign values to multiple variables in one line:"""
x = y = z = 'Orange'
print(x)
print(y)
print(z) |
#
# @lc app=leetcode id=795 lang=python3
#
# [795] Number of Subarrays with Bounded Maximum
#
# https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/description/
#
# algorithms
# Medium (48.43%)
# Likes: 1143
# Dislikes: 78
# Total Accepted: 40.2K
# Total Submissions: 77.7K
# Testcase Example: '[2,1,4,3]\n2\n3'
#
# We are given an array nums of positive integers, and two positive integers
# left and right (left <= right).
#
# Return the number of (contiguous, non-empty) subarrays such that the value of
# the maximum array element in that subarray is at least left and at most
# right.
#
#
# Example:
# Input:
# nums = [2, 1, 4, 3]
# left = 2
# right = 3
# Output: 3
# Explanation: There are three subarrays that meet the requirements: [2], [2,
# 1], [3].
#
#
# Note:
#
#
# left, right, and nums[i] will be an integer in the range [0, 10^9].
# The length of nums will be in the range of [1, 50000].
#
#
#
# @lc code=start
class Solution:
def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int:
i = 0
curr = 0
res = 0
for j in range(len(nums)):
if left <= nums[j] <= right:
curr = j - i + 1
res += j - i + 1
elif nums[j] < left:
res += curr
else:
i = j + 1
curr = 0
return res
# @lc code=end
| class Solution:
def num_subarray_bounded_max(self, nums: List[int], left: int, right: int) -> int:
i = 0
curr = 0
res = 0
for j in range(len(nums)):
if left <= nums[j] <= right:
curr = j - i + 1
res += j - i + 1
elif nums[j] < left:
res += curr
else:
i = j + 1
curr = 0
return res |
class Human:
def __init__(self, xref_id):
self.xref_id = xref_id
self.name = None
self.father = None
self.mother = None
self.pos = None
def __repr__(self):
return "[ {} : {} - {} {} - {} ]".format(
self.xref_id,
self.name,
self.father,
self.mother,
self.pos
)
| class Human:
def __init__(self, xref_id):
self.xref_id = xref_id
self.name = None
self.father = None
self.mother = None
self.pos = None
def __repr__(self):
return '[ {} : {} - {} {} - {} ]'.format(self.xref_id, self.name, self.father, self.mother, self.pos) |
class Cell:
def __init__(self, row, col):
self.row = row
self.col = col
self.links = []
self.north = None
self.south = None
self.east = None
self.west = None
def neighbors(self):
n = []
self.north and n.append(self.north)
self.south and n.append(self.south)
self.east and n.append(self.east)
self.west and n.append(self.west)
return n
def link(self, cell, bidirectional=True):
self.links.append(cell)
if bidirectional:
cell.link(self, False)
def unlink(self, cell, bidirectional=True):
self.links.remove(cell)
if bidirectional:
cell.unlink(self, False)
def isLinked(self, cell):
isLinked = True if cell in self.links else False
return isLinked
| class Cell:
def __init__(self, row, col):
self.row = row
self.col = col
self.links = []
self.north = None
self.south = None
self.east = None
self.west = None
def neighbors(self):
n = []
self.north and n.append(self.north)
self.south and n.append(self.south)
self.east and n.append(self.east)
self.west and n.append(self.west)
return n
def link(self, cell, bidirectional=True):
self.links.append(cell)
if bidirectional:
cell.link(self, False)
def unlink(self, cell, bidirectional=True):
self.links.remove(cell)
if bidirectional:
cell.unlink(self, False)
def is_linked(self, cell):
is_linked = True if cell in self.links else False
return isLinked |
class Notifier(object):
def notify(self, title, message, retry_forever=False):
raise NotImplementedError()
def _resolve_params(self, title, message):
if callable(title):
title = title()
if callable(message):
message = message()
return title, message
| class Notifier(object):
def notify(self, title, message, retry_forever=False):
raise not_implemented_error()
def _resolve_params(self, title, message):
if callable(title):
title = title()
if callable(message):
message = message()
return (title, message) |
n = int(input())
c=0
for _ in range(n):
p, q = list(map(int, input().split()))
if q-p >=2:
c= c+1
print(c)
| n = int(input())
c = 0
for _ in range(n):
(p, q) = list(map(int, input().split()))
if q - p >= 2:
c = c + 1
print(c) |
class Solution:
def smallestRangeI(self, nums: List[int], k: int) -> int:
minNum,maxNum = min(nums),max(nums)
if maxNum-minNum>=2*k:
return maxNum-minNum-2*k
else:
return 0 | class Solution:
def smallest_range_i(self, nums: List[int], k: int) -> int:
(min_num, max_num) = (min(nums), max(nums))
if maxNum - minNum >= 2 * k:
return maxNum - minNum - 2 * k
else:
return 0 |
class Base:
""" This is a class template. All the other classes will be made according to this templae """
def __init__(self) -> None:
""" constructor function """
pass
def enter(self, **param) -> None:
""" This function is called first when we change a group """
pass
def render(self) -> None:
""" This function will render all the current objects on the screen """
pass
def update(self, param) -> None:
""" This function will be called once per frame"""
pass
def leave(self) -> None:
""" This function will be called during changing state. It helps in leaving the current state """
pass | class Base:
""" This is a class template. All the other classes will be made according to this templae """
def __init__(self) -> None:
""" constructor function """
pass
def enter(self, **param) -> None:
""" This function is called first when we change a group """
pass
def render(self) -> None:
""" This function will render all the current objects on the screen """
pass
def update(self, param) -> None:
""" This function will be called once per frame"""
pass
def leave(self) -> None:
""" This function will be called during changing state. It helps in leaving the current state """
pass |
# Q7: What is the time complexity of
# i = 1, 2, 4, 8, 16, ..., 2^k
# El bucle termina para: i >= n
# 2^k = n
# k = log_2(n)
# O(log_2(n))
# Algoritmo
# for (i = 1; i < n; i = i*2) {
# statement;
# }
i = 1
n = 10
while i < n:
print(i)
i = i*2 | i = 1
n = 10
while i < n:
print(i)
i = i * 2 |
# https://www.programiz.com/python-programming/function-argument
# Python allows functions to be called using keyword arguments. When we call
# functions in this way, the order (position) of the arguments can be changed.
# As we can see, we can mix positional arguments with keyword arguments during
# a function call. But we must keep in mind that keyword arguments must follow
# positional arguments.
def greet(name, msg = "Good morning!"):
"""
This function greets to the person with the provided message.
If message is not provided, it defaults to "Good morning!"
"""
print("Hello", name + ', ' + msg)
greet(name = "Bruce", msg = "How do you do?")
greet(msg = "How do you do?", name = "Bruce")
greet("Bruce", msg = "How do you do?")
| def greet(name, msg='Good morning!'):
"""
This function greets to the person with the provided message.
If message is not provided, it defaults to "Good morning!"
"""
print('Hello', name + ', ' + msg)
greet(name='Bruce', msg='How do you do?')
greet(msg='How do you do?', name='Bruce')
greet('Bruce', msg='How do you do?') |
"""
Topological Sort
"""
class Solution(object):
def alienOrder(self, words):
#return true if cycles are detected.
def dfs(c):
if c in path: return True
if c in visited: return False
path.add(c)
for nei in adj[c]:
if dfs(nei): return True
res.append(c)
path.remove(c)
visited.add(c)
return False
#build adjacency list
adj = {c: set() for word in words for c in word}
for i in xrange(len(words)-1):
w1, w2 = words[i], words[i+1]
minLen = min(len(w1), len(w2))
if w1[:minLen]==w2[:minLen] and len(w1)>len(w2): return ""
for j in xrange(minLen):
if w1[j]!=w2[j]:
adj[w1[j]].add(w2[j])
break
#topological sort
path = set() #path currently being reversed
visited = set() #done processing
res = []
for c in adj:
if dfs(c): return ""
return "".join(reversed(res)) | """
Topological Sort
"""
class Solution(object):
def alien_order(self, words):
def dfs(c):
if c in path:
return True
if c in visited:
return False
path.add(c)
for nei in adj[c]:
if dfs(nei):
return True
res.append(c)
path.remove(c)
visited.add(c)
return False
adj = {c: set() for word in words for c in word}
for i in xrange(len(words) - 1):
(w1, w2) = (words[i], words[i + 1])
min_len = min(len(w1), len(w2))
if w1[:minLen] == w2[:minLen] and len(w1) > len(w2):
return ''
for j in xrange(minLen):
if w1[j] != w2[j]:
adj[w1[j]].add(w2[j])
break
path = set()
visited = set()
res = []
for c in adj:
if dfs(c):
return ''
return ''.join(reversed(res)) |
code_map = {
"YEAR": "year",
"MALE": "male population",
"FEMALE": "female population",
"M_MALE": "matable male population",
"M_FEMALE": "matable female population",
"C_PROB": "concieving probability",
"M_AGE_START": "starting age of mating",
"M_AGE_END": "ending age of mating",
"MX_AGE": "maximum age",
"MT_PROB": "mutation probability",
"OF_FACTOR": "offspring factor",
"AGE_DTH": "dependency of age on death",
"FIT_DTH": "dependency of fitness on death",
"AFR_DTH": "dependency ratio of age and fitness on death",
"HT_SP": "dependency of height on speed",
"HT_ST": "dependency of height on stamina",
"HT_VT": "dependency of height on vitality",
"WT_SP": "dependency of weight on speed",
"WT_ST": "dependency of weight on stamina",
"WT_VT": "dependency of weight on vitality",
"VT_AP": "dependency of vitality on appetite",
"VT_SP": "dependency of vitality on speed",
"ST_AP": "dependency of stamina on appetite",
"ST_SP": "dependency of stamina on speed",
"TMB_AP": "theoretical maximum base appetite",
"TMB_HT": "theoretical maximum base height",
"TMB_SP": "theoretical maximum base speed",
"TMB_ST": "theoretical maximum base stamina",
"TMB_VT": "theoretical maximum base vitality",
"TMB_WT": "theoretical maximum base appetite",
"TM_HT": "theoretical maximum height",
"TM_SP": "theoretical maximum speed",
"TM_WT": "theoretical maximum weight",
"TMM_HT": "theoretical maximum height multiplier",
"TMM_SP": "theoretical maximum speed multiplier",
"TMM_ST": "theoretical maximum stamina multiplier",
"TMM_VT": "theoretical maximum vitality multiplier",
"TMM_WT": "theoretical maximum weight multiplier",
"SL_FACTOR": "sleep restore factor",
"AVG_GEN": "average generation",
"AVG_IMM": "average immunity",
"AVG_AGE": "average age",
"AVG_HT": "average height",
"AVG_WT": "average weight",
"AVGMA_AP": "average maximum appetite",
"AVGMA_SP": "average maximum speed",
"AVGMA_ST": "average maximum stamina",
"AVGMA_VT": "average maximum vitality",
"AVG_SFIT": "average static fitness",
"AVG_DTHF": "average death factor",
"AVG_VIS": "average vision radius",
}
def title_case(s):
res = ''
for word in s.split(' '):
if word:
res += word[0].upper()
if len(word) > 1:
res += word[1:]
res += ' '
return res.strip()
def sentence_case(s):
res = ''
if s:
res += s[0].upper()
if len(s) > 1:
res += s[1:]
return res.strip() | code_map = {'YEAR': 'year', 'MALE': 'male population', 'FEMALE': 'female population', 'M_MALE': 'matable male population', 'M_FEMALE': 'matable female population', 'C_PROB': 'concieving probability', 'M_AGE_START': 'starting age of mating', 'M_AGE_END': 'ending age of mating', 'MX_AGE': 'maximum age', 'MT_PROB': 'mutation probability', 'OF_FACTOR': 'offspring factor', 'AGE_DTH': 'dependency of age on death', 'FIT_DTH': 'dependency of fitness on death', 'AFR_DTH': 'dependency ratio of age and fitness on death', 'HT_SP': 'dependency of height on speed', 'HT_ST': 'dependency of height on stamina', 'HT_VT': 'dependency of height on vitality', 'WT_SP': 'dependency of weight on speed', 'WT_ST': 'dependency of weight on stamina', 'WT_VT': 'dependency of weight on vitality', 'VT_AP': 'dependency of vitality on appetite', 'VT_SP': 'dependency of vitality on speed', 'ST_AP': 'dependency of stamina on appetite', 'ST_SP': 'dependency of stamina on speed', 'TMB_AP': 'theoretical maximum base appetite', 'TMB_HT': 'theoretical maximum base height', 'TMB_SP': 'theoretical maximum base speed', 'TMB_ST': 'theoretical maximum base stamina', 'TMB_VT': 'theoretical maximum base vitality', 'TMB_WT': 'theoretical maximum base appetite', 'TM_HT': 'theoretical maximum height', 'TM_SP': 'theoretical maximum speed', 'TM_WT': 'theoretical maximum weight', 'TMM_HT': 'theoretical maximum height multiplier', 'TMM_SP': 'theoretical maximum speed multiplier', 'TMM_ST': 'theoretical maximum stamina multiplier', 'TMM_VT': 'theoretical maximum vitality multiplier', 'TMM_WT': 'theoretical maximum weight multiplier', 'SL_FACTOR': 'sleep restore factor', 'AVG_GEN': 'average generation', 'AVG_IMM': 'average immunity', 'AVG_AGE': 'average age', 'AVG_HT': 'average height', 'AVG_WT': 'average weight', 'AVGMA_AP': 'average maximum appetite', 'AVGMA_SP': 'average maximum speed', 'AVGMA_ST': 'average maximum stamina', 'AVGMA_VT': 'average maximum vitality', 'AVG_SFIT': 'average static fitness', 'AVG_DTHF': 'average death factor', 'AVG_VIS': 'average vision radius'}
def title_case(s):
res = ''
for word in s.split(' '):
if word:
res += word[0].upper()
if len(word) > 1:
res += word[1:]
res += ' '
return res.strip()
def sentence_case(s):
res = ''
if s:
res += s[0].upper()
if len(s) > 1:
res += s[1:]
return res.strip() |
txt = "I like bananas"
x = txt.replace("bananas", "mangoes")
print(x)
txt = "one one was a race horse and two two was one too."
x = txt.replace("one", "three")
print(x)
txt = "one one was a race horse, two two was one too."
x = txt.replace("one", "three", 1)
print(x)
txt = "For only {price:.2f} dollars!"
print(txt.format(price = 49))
txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age = 36)
txt2 = "My name is {0}, I'm {1}".format("John",36)
txt3 = "My name is {}, I'm {}".format("John",36)
txt = "banana"
x = txt.center(15)
print(x)
txt = "banana"
x = txt.center(20, "/")
print(x)
txt = "Hello, And Welcome To My World!"
x = txt.casefold()
print(x)
txt = "Hello, And Welcome To My World!"
x = txt.upper()
print(x)
txt = "Company12"
x = txt.isalnum()
print(x)
txt = "Company!@#$"
x = txt.isalnum()
print(x)
txt = "welcome to the jungle"
x = txt.split()
print(x)
txt = "hello? my name is Peter? I am 26 years old"
x = txt.split("?")
print(x)
txt = "apple#banana#cherry#orange"
x = txt.split("#")
print(x)
| txt = 'I like bananas'
x = txt.replace('bananas', 'mangoes')
print(x)
txt = 'one one was a race horse and two two was one too.'
x = txt.replace('one', 'three')
print(x)
txt = 'one one was a race horse, two two was one too.'
x = txt.replace('one', 'three', 1)
print(x)
txt = 'For only {price:.2f} dollars!'
print(txt.format(price=49))
txt1 = "My name is {fname}, I'm {age}".format(fname='John', age=36)
txt2 = "My name is {0}, I'm {1}".format('John', 36)
txt3 = "My name is {}, I'm {}".format('John', 36)
txt = 'banana'
x = txt.center(15)
print(x)
txt = 'banana'
x = txt.center(20, '/')
print(x)
txt = 'Hello, And Welcome To My World!'
x = txt.casefold()
print(x)
txt = 'Hello, And Welcome To My World!'
x = txt.upper()
print(x)
txt = 'Company12'
x = txt.isalnum()
print(x)
txt = 'Company!@#$'
x = txt.isalnum()
print(x)
txt = 'welcome to the jungle'
x = txt.split()
print(x)
txt = 'hello? my name is Peter? I am 26 years old'
x = txt.split('?')
print(x)
txt = 'apple#banana#cherry#orange'
x = txt.split('#')
print(x) |
def partition_labels(string):
#
"""
"""
indices = {}
for i, char in enumerate(string):
indices[char] = i
result = []
left, right = -1, -1
for i, char in enumerate(string):
right = max(right, indices[char])
if i == right:
result.append(right - left)
left = i
return result
if __name__ == "__main__":
print(partition_labels("ababcbacadefegdehijhklij"))
| def partition_labels(string):
"""
"""
indices = {}
for (i, char) in enumerate(string):
indices[char] = i
result = []
(left, right) = (-1, -1)
for (i, char) in enumerate(string):
right = max(right, indices[char])
if i == right:
result.append(right - left)
left = i
return result
if __name__ == '__main__':
print(partition_labels('ababcbacadefegdehijhklij')) |
class Solution(object):
def dominantIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_index = -1
second_max_value = -1
for i in range(len(nums)):
if i == 0:
max_index = i
continue
value = nums[i]
if value > nums[max_index]:
value = nums[max_index]
max_index = i
if value > second_max_value:
second_max_value = value
if nums[max_index] >= (second_max_value * 2):
return max_index
else:
return -1
if __name__ == '__main__':
test_data1 = [3, 6, 1, 0]
test_data2 = [1, 2, 3, 4]
test_data3 = [2, 1]
test_data4 = [1, 2]
s = Solution()
print(s.dominantIndex(test_data1))
print(s.dominantIndex(test_data2))
print(s.dominantIndex(test_data3))
print(s.dominantIndex(test_data4))
| class Solution(object):
def dominant_index(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_index = -1
second_max_value = -1
for i in range(len(nums)):
if i == 0:
max_index = i
continue
value = nums[i]
if value > nums[max_index]:
value = nums[max_index]
max_index = i
if value > second_max_value:
second_max_value = value
if nums[max_index] >= second_max_value * 2:
return max_index
else:
return -1
if __name__ == '__main__':
test_data1 = [3, 6, 1, 0]
test_data2 = [1, 2, 3, 4]
test_data3 = [2, 1]
test_data4 = [1, 2]
s = solution()
print(s.dominantIndex(test_data1))
print(s.dominantIndex(test_data2))
print(s.dominantIndex(test_data3))
print(s.dominantIndex(test_data4)) |
class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
# 0 -> 0 status = 0
# 1 -> 1 status = 1
# 1 -> 0 status = 2
# 0 -> 1 status = 3
m, n = len(board), len(board[0])
directions = [(-1,-1),(0,-1),(1,-1),(-1,0),(1,0),(-1,1),(0,1),(1,1)]
for x in range(m):
for y in range(n):
lives = 0
for dx, dy in directions:
nx = x + dx
ny = y + dy
if 0<=nx<m and 0<=ny<n and (board[nx][ny] == 1 or board[nx][ny] == 2) :
lives+=1
if board[x][y] == 0 and lives==3: # rule 4
board[x][y] = 3
elif board[x][y] == 1 and (lives<2 or lives>3):
board[x][y] = 2
for x in range(m):
for y in range(n):
board[x][y] = board[x][y]%2
return board | class Solution:
def game_of_life(self, board: List[List[int]]) -> None:
(m, n) = (len(board), len(board[0]))
directions = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]
for x in range(m):
for y in range(n):
lives = 0
for (dx, dy) in directions:
nx = x + dx
ny = y + dy
if 0 <= nx < m and 0 <= ny < n and (board[nx][ny] == 1 or board[nx][ny] == 2):
lives += 1
if board[x][y] == 0 and lives == 3:
board[x][y] = 3
elif board[x][y] == 1 and (lives < 2 or lives > 3):
board[x][y] = 2
for x in range(m):
for y in range(n):
board[x][y] = board[x][y] % 2
return board |
def calc(x,y,ops):
if ops not in "+-*/":
return "only +-*/!!!!!"
if ops=="+":
return (str(x) +""+ ops +str(y)+"="+str(x+y))
elif ops=="-":
return (str(x) +""+ ops +str(y)+"="+str(x-y))
elif ops == "*":
return (str(x) + "" + ops + str(y) + "=" + str(x * y))
elif ops == "/":
return (str(x) + "" + ops + str(y) + "=" + str(x / y))
while True:
x=int(input("please enter first number"))
y=int(input("please enter second number"))
ops=input("choose between +,-,*,/")
print(calc(x,y,ops))
| def calc(x, y, ops):
if ops not in '+-*/':
return 'only +-*/!!!!!'
if ops == '+':
return str(x) + '' + ops + str(y) + '=' + str(x + y)
elif ops == '-':
return str(x) + '' + ops + str(y) + '=' + str(x - y)
elif ops == '*':
return str(x) + '' + ops + str(y) + '=' + str(x * y)
elif ops == '/':
return str(x) + '' + ops + str(y) + '=' + str(x / y)
while True:
x = int(input('please enter first number'))
y = int(input('please enter second number'))
ops = input('choose between +,-,*,/')
print(calc(x, y, ops)) |
n = int(input())
length = 0
while True:
length += 1
n //= 10
if n == 0:
break
print('Length is', length)
| n = int(input())
length = 0
while True:
length += 1
n //= 10
if n == 0:
break
print('Length is', length) |
''' '+' Plus Operator shows polymorphism. It is overloaded to perform multiple things, so we can call it polymorphic. '''
x = 10
y = 20
print(x+y)
s1 = 'Hello'
s2 = " How are you?"
print(s1+s2)
l1 = [1,2,3]
l2 = [4,5,6]
print(l1+l2)
| """ '+' Plus Operator shows polymorphism. It is overloaded to perform multiple things, so we can call it polymorphic. """
x = 10
y = 20
print(x + y)
s1 = 'Hello'
s2 = ' How are you?'
print(s1 + s2)
l1 = [1, 2, 3]
l2 = [4, 5, 6]
print(l1 + l2) |
people = 50 #defines the people variable
cars = 10 #defines the cars variable
trucks = 35 #defines the trucks variable
if cars > people or trucks < cars: #sets up the first branch
print("We should take the cars.") #print that runs if the if above is true
elif cars < people: #sets up second branch that runs if the first one is not true
print("We should not take the cars.") #print that runs if the elif above is true
else: #sets up third and last branch that will run if the above ifs are not true
print("We can't decide.") #print that runs if the else above is true
if trucks > cars:#sets up the first branch
print("That's too many trucks.")#print that runs if the if above is true
elif trucks < cars:#sets up second branch that runs if the first one is not true
print("Maybe we could take the trucks.")#print that runs if the elif above is true
else:#sets up third and last branch that will run if the above ifs are not true
print("We still can't decide.")#print that runs if the else above is true
if people > trucks:#sets up the first branch
print("Alright, let's just take the trucks.")#print that runs if the if above is true
else: #sets up second and last branch
print("Fine, let's stay home then.")#print that runs if the else above is true
| people = 50
cars = 10
trucks = 35
if cars > people or trucks < cars:
print('We should take the cars.')
elif cars < people:
print('We should not take the cars.')
else:
print("We can't decide.")
if trucks > cars:
print("That's too many trucks.")
elif trucks < cars:
print('Maybe we could take the trucks.')
else:
print("We still can't decide.")
if people > trucks:
print("Alright, let's just take the trucks.")
else:
print("Fine, let's stay home then.") |
DESEncryptParam = "key(16 Hex Chars), Number of rounds"
INITIAL_PERMUTATION = [58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6,
64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17, 9, 1,
59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5,
63, 55, 47, 39, 31, 23, 15, 7]
PERMUTED_CHOICE_1 = [57, 49, 41, 33, 25, 17, 9,
1, 58, 50, 42, 34, 26, 18,
10, 2, 59, 51, 43, 35, 27,
19, 11, 3, 60, 52, 44, 36,
63, 55, 47, 39, 31, 23, 15,
7, 62, 54, 46, 38, 30, 22,
14, 6, 61, 53, 45, 37, 29,
21, 13, 5, 28, 20, 12, 4]
PERMUTED_CHOICE_2 = [14, 17, 11, 24, 1, 5, 3, 28,
15, 6, 21, 10, 23, 19, 12, 4,
26, 8, 16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55, 30, 40,
51, 45, 33, 48, 44, 49, 39, 56,
34, 53, 46, 42, 50, 36, 29, 32]
EXPANSION_PERMUTATION = [32, 1, 2, 3, 4, 5,
4, 5, 6, 7, 8, 9,
8, 9, 10, 11, 12, 13,
12, 13, 14, 15, 16, 17,
16, 17, 18, 19, 20, 21,
20, 21, 22, 23, 24, 25,
24, 25, 26, 27, 28, 29,
28, 29, 30, 31, 32, 1]
S_BOX = [
[[14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7],
[0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8],
[4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0],
[15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13],
],
[[15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10],
[3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5],
[0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15],
[13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9],
],
[[10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8],
[13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1],
[13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7],
[1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12],
],
[[7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15],
[13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9],
[10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4],
[3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14],
],
[[2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9],
[14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6],
[4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14],
[11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3],
],
[[12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11],
[10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8],
[9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6],
[4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13],
],
[[4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1],
[13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6],
[1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2],
[6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12],
],
[[13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7],
[1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2],
[7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8],
[2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11],
]
]
PERMUTATION_TABLE = [16, 7, 20, 21, 29, 12, 28, 17,
1, 15, 23, 26, 5, 18, 31, 10,
2, 8, 24, 14, 32, 27, 3, 9,
19, 13, 30, 6, 22, 11, 4, 25]
FINAL_PERMUTATION = [40, 8, 48, 16, 56, 24, 64, 32,
39, 7, 47, 15, 55, 23, 63, 31,
38, 6, 46, 14, 54, 22, 62, 30,
37, 5, 45, 13, 53, 21, 61, 29,
36, 4, 44, 12, 52, 20, 60, 28,
35, 3, 43, 11, 51, 19, 59, 27,
34, 2, 42, 10, 50, 18, 58, 26,
33, 1, 41, 9, 49, 17, 57, 25]
SHIFT = [1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1]
def toBin(input):
binval = bin(input)[2:]
while len(binval) < 4:
binval = "0" + binval
return binval
def hexToBin(input):
return bin(int(input, 16))[2:].zfill(64)
def substitute(input):
subblocks = splitToArrOfN(input, 6)
result = []
for i in range(len(subblocks)):
block = subblocks[i]
row = int(str(block[0])+str(block[5]), 2)
column = int(''.join([str(x) for x in block[1:][:-1]]), 2)
result += [int(x) for x in toBin(S_BOX[i][row][column])]
return result
def splitToArrOfN(listToSplit, newSize):
return [listToSplit[k:k+newSize] for k in range(0, len(listToSplit), newSize)]
def xor(operand1, operand2):
return [int(operand1[i]) ^ int(operand2[i]) for i in range(len(operand1))]
def shift(operand1, operand2, shiftAmount):
return operand1[shiftAmount:] + operand1[:shiftAmount], operand2[shiftAmount:] + operand2[:shiftAmount]
def permut(block, table):
return [block[x-1] for x in table]
def getKeys(initialKey):
keys = []
left, right = splitToArrOfN(
permut(hexToBin(initialKey), PERMUTED_CHOICE_1), 28)
for i in range(16):
left, right = shift(left, right, SHIFT[i])
keys.append(permut(left + right, PERMUTED_CHOICE_2))
return keys
def DESEncrypt(input, param):
key, numberOfRounds = param
numberOfRounds = int(numberOfRounds)
keys = getKeys(key)
currentPhase = input[0].strip()
for _ in range(numberOfRounds):
result = []
for block in splitToArrOfN(currentPhase, 16):
block = permut(hexToBin(block), INITIAL_PERMUTATION)
left, right = splitToArrOfN(block, 32)
intermediateValue = None
for i in range(16):
rightPermuted = permut(right, EXPANSION_PERMUTATION)
intermediateValue = xor(keys[i], rightPermuted)
intermediateValue = substitute(intermediateValue)
intermediateValue = permut(
intermediateValue, PERMUTATION_TABLE)
intermediateValue = xor(left, intermediateValue)
left, right = right, intermediateValue
result += permut(right+left, FINAL_PERMUTATION)
currentPhase = ''.join([hex(int(''.join(map(str, i)), 2))[
2] for i in splitToArrOfN(result, 4)])
return [currentPhase.upper()]
def DESDecrypt(input, param):
key, numberOfRounds = param
numberOfRounds = int(numberOfRounds)
keys = getKeys(key)
currentPhase = input[0].strip()
for _ in range(numberOfRounds):
result = []
for block in splitToArrOfN(currentPhase, 16):
block = permut(hexToBin(block), INITIAL_PERMUTATION)
left, right = splitToArrOfN(block, 32)
intermediateValue = None
for i in range(16):
rightPermuted = permut(right, EXPANSION_PERMUTATION)
intermediateValue = xor(keys[15-i], rightPermuted)
intermediateValue = substitute(intermediateValue)
intermediateValue = permut(
intermediateValue, PERMUTATION_TABLE)
intermediateValue = xor(left, intermediateValue)
left, right = right, intermediateValue
result += permut(right+left, FINAL_PERMUTATION)
currentPhase = ''.join([hex(int(''.join(map(str, i)), 2))[
2] for i in splitToArrOfN(result, 4)])
return [currentPhase.upper()]
| des_encrypt_param = 'key(16 Hex Chars), Number of rounds'
initial_permutation = [58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7]
permuted_choice_1 = [57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4]
permuted_choice_2 = [14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32]
expansion_permutation = [32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1]
s_box = [[[14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7], [0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8], [4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0], [15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13]], [[15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10], [3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5], [0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15], [13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9]], [[10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8], [13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1], [13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7], [1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12]], [[7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15], [13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9], [10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4], [3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14]], [[2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9], [14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6], [4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14], [11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3]], [[12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11], [10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8], [9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6], [4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13]], [[4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1], [13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6], [1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2], [6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12]], [[13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7], [1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2], [7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8], [2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11]]]
permutation_table = [16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25]
final_permutation = [40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25]
shift = [1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1]
def to_bin(input):
binval = bin(input)[2:]
while len(binval) < 4:
binval = '0' + binval
return binval
def hex_to_bin(input):
return bin(int(input, 16))[2:].zfill(64)
def substitute(input):
subblocks = split_to_arr_of_n(input, 6)
result = []
for i in range(len(subblocks)):
block = subblocks[i]
row = int(str(block[0]) + str(block[5]), 2)
column = int(''.join([str(x) for x in block[1:][:-1]]), 2)
result += [int(x) for x in to_bin(S_BOX[i][row][column])]
return result
def split_to_arr_of_n(listToSplit, newSize):
return [listToSplit[k:k + newSize] for k in range(0, len(listToSplit), newSize)]
def xor(operand1, operand2):
return [int(operand1[i]) ^ int(operand2[i]) for i in range(len(operand1))]
def shift(operand1, operand2, shiftAmount):
return (operand1[shiftAmount:] + operand1[:shiftAmount], operand2[shiftAmount:] + operand2[:shiftAmount])
def permut(block, table):
return [block[x - 1] for x in table]
def get_keys(initialKey):
keys = []
(left, right) = split_to_arr_of_n(permut(hex_to_bin(initialKey), PERMUTED_CHOICE_1), 28)
for i in range(16):
(left, right) = shift(left, right, SHIFT[i])
keys.append(permut(left + right, PERMUTED_CHOICE_2))
return keys
def des_encrypt(input, param):
(key, number_of_rounds) = param
number_of_rounds = int(numberOfRounds)
keys = get_keys(key)
current_phase = input[0].strip()
for _ in range(numberOfRounds):
result = []
for block in split_to_arr_of_n(currentPhase, 16):
block = permut(hex_to_bin(block), INITIAL_PERMUTATION)
(left, right) = split_to_arr_of_n(block, 32)
intermediate_value = None
for i in range(16):
right_permuted = permut(right, EXPANSION_PERMUTATION)
intermediate_value = xor(keys[i], rightPermuted)
intermediate_value = substitute(intermediateValue)
intermediate_value = permut(intermediateValue, PERMUTATION_TABLE)
intermediate_value = xor(left, intermediateValue)
(left, right) = (right, intermediateValue)
result += permut(right + left, FINAL_PERMUTATION)
current_phase = ''.join([hex(int(''.join(map(str, i)), 2))[2] for i in split_to_arr_of_n(result, 4)])
return [currentPhase.upper()]
def des_decrypt(input, param):
(key, number_of_rounds) = param
number_of_rounds = int(numberOfRounds)
keys = get_keys(key)
current_phase = input[0].strip()
for _ in range(numberOfRounds):
result = []
for block in split_to_arr_of_n(currentPhase, 16):
block = permut(hex_to_bin(block), INITIAL_PERMUTATION)
(left, right) = split_to_arr_of_n(block, 32)
intermediate_value = None
for i in range(16):
right_permuted = permut(right, EXPANSION_PERMUTATION)
intermediate_value = xor(keys[15 - i], rightPermuted)
intermediate_value = substitute(intermediateValue)
intermediate_value = permut(intermediateValue, PERMUTATION_TABLE)
intermediate_value = xor(left, intermediateValue)
(left, right) = (right, intermediateValue)
result += permut(right + left, FINAL_PERMUTATION)
current_phase = ''.join([hex(int(''.join(map(str, i)), 2))[2] for i in split_to_arr_of_n(result, 4)])
return [currentPhase.upper()] |
# pylint: disable-all
"""Test inputs for day 2"""
test_position: str = """forward 5
down 5
forward 8
up 3
down 8
forward 2"""
test_position_answer: int = 150
test_position_answer_day_two: int = 900
| """Test inputs for day 2"""
test_position: str = 'forward 5\ndown 5\nforward 8\nup 3\ndown 8\nforward 2'
test_position_answer: int = 150
test_position_answer_day_two: int = 900 |
input = """
a :- b.
b | c.
d.
:- d, a.
"""
output = """
a :- b.
b | c.
d.
:- d, a.
"""
| input = '\na :- b.\nb | c.\n\nd.\n:- d, a.\n'
output = '\na :- b.\nb | c.\n\nd.\n:- d, a.\n' |
class WikipediaKnowledge:
@staticmethod
def all_wikipedia_language_codes_order_by_importance():
# list from https://meta.wikimedia.org/wiki/List_of_Wikipedias as of 2017-10-07
# ordered by article count except some for extreme bot spam
# should use https://stackoverflow.com/questions/33608751/retrieve-a-list-of-all-wikipedia-languages-programmatically
# probably via wikipedia connection library
return ['en', 'de', 'fr', 'nl', 'ru', 'it', 'es', 'pl',
'vi', 'ja', 'pt', 'zh', 'uk', 'fa', 'ca', 'ar', 'no', 'sh', 'fi',
'hu', 'id', 'ko', 'cs', 'ro', 'sr', 'ms', 'tr', 'eu', 'eo', 'bg',
'hy', 'da', 'zh-min-nan', 'sk', 'min', 'kk', 'he', 'lt', 'hr',
'ce', 'et', 'sl', 'be', 'gl', 'el', 'nn', 'uz', 'simple', 'la',
'az', 'ur', 'hi', 'vo', 'th', 'ka', 'ta', 'cy', 'mk', 'mg', 'oc',
'tl', 'ky', 'lv', 'bs', 'tt', 'new', 'sq', 'tg', 'te', 'pms',
'br', 'be-tarask', 'zh-yue', 'bn', 'ml', 'ht', 'ast', 'lb', 'jv',
'mr', 'azb', 'af', 'sco', 'pnb', 'ga', 'is', 'cv', 'ba', 'fy',
'su', 'sw', 'my', 'lmo', 'an', 'yo', 'ne', 'gu', 'io', 'pa',
'nds', 'scn', 'bpy', 'als', 'bar', 'ku', 'kn', 'ia', 'qu', 'ckb',
'mn', 'arz', 'bat-smg', 'wa', 'gd', 'nap', 'bug', 'yi', 'am',
'si', 'cdo', 'map-bms', 'or', 'fo', 'mzn', 'hsb', 'xmf', 'li',
'mai', 'sah', 'sa', 'vec', 'ilo', 'os', 'mrj', 'hif', 'mhr', 'bh',
'roa-tara', 'eml', 'diq', 'pam', 'ps', 'sd', 'hak', 'nso', 'se',
'ace', 'bcl', 'mi', 'nah', 'zh-classical', 'nds-nl', 'szl', 'gan',
'vls', 'rue', 'wuu', 'bo', 'glk', 'vep', 'sc', 'fiu-vro', 'frr',
'co', 'crh', 'km', 'lrc', 'tk', 'kv', 'csb', 'so', 'gv', 'as',
'lad', 'zea', 'ay', 'udm', 'myv', 'lez', 'kw', 'stq', 'ie',
'nrm', 'nv', 'pcd', 'mwl', 'rm', 'koi', 'gom', 'ug', 'lij', 'ab',
'gn', 'mt', 'fur', 'dsb', 'cbk-zam', 'dv', 'ang', 'ln', 'ext',
'kab', 'sn', 'ksh', 'lo', 'gag', 'frp', 'pag', 'pi', 'olo', 'av',
'dty', 'xal', 'pfl', 'krc', 'haw', 'bxr', 'kaa', 'pap', 'rw',
'pdc', 'bjn', 'to', 'nov', 'kl', 'arc', 'jam', 'kbd', 'ha', 'tpi',
'tyv', 'tet', 'ig', 'ki', 'na', 'lbe', 'roa-rup', 'jbo', 'ty',
'mdf', 'kg', 'za', 'wo', 'lg', 'bi', 'srn', 'zu', 'chr', 'tcy',
'ltg', 'sm', 'om', 'xh', 'tn', 'pih', 'chy', 'rmy', 'tw', 'cu',
'kbp', 'tum', 'ts', 'st', 'got', 'rn', 'pnt', 'ss', 'fj', 'bm',
'ch', 'ady', 'iu', 'mo', 'ny', 'ee', 'ks', 'ak', 'ik', 've', 'sg',
'dz', 'ff', 'ti', 'cr', 'atj', 'din', 'ng', 'cho', 'kj', 'mh',
'ho', 'ii', 'aa', 'mus', 'hz', 'kr',
# degraded due to major low-quality bot spam
'ceb', 'sv', 'war'
]
| class Wikipediaknowledge:
@staticmethod
def all_wikipedia_language_codes_order_by_importance():
return ['en', 'de', 'fr', 'nl', 'ru', 'it', 'es', 'pl', 'vi', 'ja', 'pt', 'zh', 'uk', 'fa', 'ca', 'ar', 'no', 'sh', 'fi', 'hu', 'id', 'ko', 'cs', 'ro', 'sr', 'ms', 'tr', 'eu', 'eo', 'bg', 'hy', 'da', 'zh-min-nan', 'sk', 'min', 'kk', 'he', 'lt', 'hr', 'ce', 'et', 'sl', 'be', 'gl', 'el', 'nn', 'uz', 'simple', 'la', 'az', 'ur', 'hi', 'vo', 'th', 'ka', 'ta', 'cy', 'mk', 'mg', 'oc', 'tl', 'ky', 'lv', 'bs', 'tt', 'new', 'sq', 'tg', 'te', 'pms', 'br', 'be-tarask', 'zh-yue', 'bn', 'ml', 'ht', 'ast', 'lb', 'jv', 'mr', 'azb', 'af', 'sco', 'pnb', 'ga', 'is', 'cv', 'ba', 'fy', 'su', 'sw', 'my', 'lmo', 'an', 'yo', 'ne', 'gu', 'io', 'pa', 'nds', 'scn', 'bpy', 'als', 'bar', 'ku', 'kn', 'ia', 'qu', 'ckb', 'mn', 'arz', 'bat-smg', 'wa', 'gd', 'nap', 'bug', 'yi', 'am', 'si', 'cdo', 'map-bms', 'or', 'fo', 'mzn', 'hsb', 'xmf', 'li', 'mai', 'sah', 'sa', 'vec', 'ilo', 'os', 'mrj', 'hif', 'mhr', 'bh', 'roa-tara', 'eml', 'diq', 'pam', 'ps', 'sd', 'hak', 'nso', 'se', 'ace', 'bcl', 'mi', 'nah', 'zh-classical', 'nds-nl', 'szl', 'gan', 'vls', 'rue', 'wuu', 'bo', 'glk', 'vep', 'sc', 'fiu-vro', 'frr', 'co', 'crh', 'km', 'lrc', 'tk', 'kv', 'csb', 'so', 'gv', 'as', 'lad', 'zea', 'ay', 'udm', 'myv', 'lez', 'kw', 'stq', 'ie', 'nrm', 'nv', 'pcd', 'mwl', 'rm', 'koi', 'gom', 'ug', 'lij', 'ab', 'gn', 'mt', 'fur', 'dsb', 'cbk-zam', 'dv', 'ang', 'ln', 'ext', 'kab', 'sn', 'ksh', 'lo', 'gag', 'frp', 'pag', 'pi', 'olo', 'av', 'dty', 'xal', 'pfl', 'krc', 'haw', 'bxr', 'kaa', 'pap', 'rw', 'pdc', 'bjn', 'to', 'nov', 'kl', 'arc', 'jam', 'kbd', 'ha', 'tpi', 'tyv', 'tet', 'ig', 'ki', 'na', 'lbe', 'roa-rup', 'jbo', 'ty', 'mdf', 'kg', 'za', 'wo', 'lg', 'bi', 'srn', 'zu', 'chr', 'tcy', 'ltg', 'sm', 'om', 'xh', 'tn', 'pih', 'chy', 'rmy', 'tw', 'cu', 'kbp', 'tum', 'ts', 'st', 'got', 'rn', 'pnt', 'ss', 'fj', 'bm', 'ch', 'ady', 'iu', 'mo', 'ny', 'ee', 'ks', 'ak', 'ik', 've', 'sg', 'dz', 'ff', 'ti', 'cr', 'atj', 'din', 'ng', 'cho', 'kj', 'mh', 'ho', 'ii', 'aa', 'mus', 'hz', 'kr', 'ceb', 'sv', 'war'] |
# -*- coding:utf-8 -*-
# @Script: rotate_array.py
# @Author: Pradip Patil
# @Contact: @pradip__patil
# @Created: 2019-04-01 21:36:57
# @Last Modified By: Pradip Patil
# @Last Modified: 2019-04-01 22:44:02
# @Description: https://leetcode.com/problems/rotate-array/
'''
Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2:
Input: [-1,-100,3,99] and k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
Could you do it in-place with O(1) extra space?
'''
class Solution:
def reverse(self, nums, start, end):
while start < end:
temp = nums[start]
nums[start] = nums[end]
nums[end] = temp
start += 1
end -= 1
def rotate(self, nums, k):
k %= len(nums)
self.reverse(nums, 0, len(nums)-1)
self.reverse(nums, 0, k-1)
self.reverse(nums, k, len(nums)-1)
return nums
# Using builtins
class Solution_1:
def rotate(self, nums, k):
l = len(nums)
k %= l
nums[0:l] = nums[-k:] + nums[:-k]
return nums
if __name__ == "__main__":
print(Solution().rotate([-1, -100, 3, 99], 2))
print(Solution_1().rotate([-1, -100, 3, 99], 2))
print(Solution().rotate([1, 2, 3, 4, 5, 6, 7], 3))
print(Solution_1().rotate([1, 2, 3, 4, 5, 6, 7], 3))
| """
Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2:
Input: [-1,-100,3,99] and k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
Could you do it in-place with O(1) extra space?
"""
class Solution:
def reverse(self, nums, start, end):
while start < end:
temp = nums[start]
nums[start] = nums[end]
nums[end] = temp
start += 1
end -= 1
def rotate(self, nums, k):
k %= len(nums)
self.reverse(nums, 0, len(nums) - 1)
self.reverse(nums, 0, k - 1)
self.reverse(nums, k, len(nums) - 1)
return nums
class Solution_1:
def rotate(self, nums, k):
l = len(nums)
k %= l
nums[0:l] = nums[-k:] + nums[:-k]
return nums
if __name__ == '__main__':
print(solution().rotate([-1, -100, 3, 99], 2))
print(solution_1().rotate([-1, -100, 3, 99], 2))
print(solution().rotate([1, 2, 3, 4, 5, 6, 7], 3))
print(solution_1().rotate([1, 2, 3, 4, 5, 6, 7], 3)) |
class TrainingConfig():
batch_size=64
lr=0.001
epoches=20
print_step=15
class BertMRCTrainingConfig(TrainingConfig):
batch_size=64
lr=1e-5
epoches=5
class TransformerConfig(TrainingConfig):
pass
class HBTTrainingConfig(TrainingConfig):
batch_size=32
lr=1e-5
epoch=20
| class Trainingconfig:
batch_size = 64
lr = 0.001
epoches = 20
print_step = 15
class Bertmrctrainingconfig(TrainingConfig):
batch_size = 64
lr = 1e-05
epoches = 5
class Transformerconfig(TrainingConfig):
pass
class Hbttrainingconfig(TrainingConfig):
batch_size = 32
lr = 1e-05
epoch = 20 |
# mouse
MOUSE_BEFORE_DELAY = 0.1
MOUSE_AFTER_DELAY = 0.1
MOUSE_PRESS_TIME = 0.2
MOUSE_INTERVAL = 0.2
# keyboard
KEYBOARD_BEFORE_DELAY = 0.05
KEYBOARD_AFTER_DELAY = 0.05
KEYBOARD_PRESS_TIME = 0.15
KEYBOARD_INTERVAL = 0.1
# clipbaord
CLIPBOARD_CHARSET = 'gbk'
# window
WINDOW_TITLE = 'Program Manager'
WINDOW_MANAGE_TIMEOUT = 5
WINDOW_NEW_BUILD_TIMEOUT = 5
# image
IMAGE_SCREENSHOT_POSITION_DEFAULT = (0,0)
IMAGE_SCREENSHOT_SIZE_DEFAULT = (1920,1080)
| mouse_before_delay = 0.1
mouse_after_delay = 0.1
mouse_press_time = 0.2
mouse_interval = 0.2
keyboard_before_delay = 0.05
keyboard_after_delay = 0.05
keyboard_press_time = 0.15
keyboard_interval = 0.1
clipboard_charset = 'gbk'
window_title = 'Program Manager'
window_manage_timeout = 5
window_new_build_timeout = 5
image_screenshot_position_default = (0, 0)
image_screenshot_size_default = (1920, 1080) |
class Student(object):
def __init__(self, name):
self.name = name
def __str__(self):
return 'Student object (name: %s)' % self.name
def __call__(self):
print('My name 111111111is %s.' % self.name)
print("-----------------------")
ffl = Student('ffl')
print("ffl-->", ffl)
print("ffl-11->", ffl())
# f = lambda:34
# print(f)
# print(f())
| class Student(object):
def __init__(self, name):
self.name = name
def __str__(self):
return 'Student object (name: %s)' % self.name
def __call__(self):
print('My name 111111111is %s.' % self.name)
print('-----------------------')
ffl = student('ffl')
print('ffl-->', ffl)
print('ffl-11->', ffl()) |
LIMIT = 2000000;
def solve(limit):
a = 0
dam = limit
for i in range(2, 101):
for j in range(i, 101):
d = abs(i*(i + 1) * j*(j + 1)/4 - limit)
if d < dam:
a, dam = i * j, d
return a
if __name__ == "__main__":
print(solve(LIMIT))
| limit = 2000000
def solve(limit):
a = 0
dam = limit
for i in range(2, 101):
for j in range(i, 101):
d = abs(i * (i + 1) * j * (j + 1) / 4 - limit)
if d < dam:
(a, dam) = (i * j, d)
return a
if __name__ == '__main__':
print(solve(LIMIT)) |
for _ in range(int(input())):
l,r=map(int,input().split())
b=r
a=r//2+1
if a<l:
a=l
if a>r:
a=r
print(b%a) | for _ in range(int(input())):
(l, r) = map(int, input().split())
b = r
a = r // 2 + 1
if a < l:
a = l
if a > r:
a = r
print(b % a) |
########################################################
# Copyright (c) 2015-2017 by European Commission. #
# All Rights Reserved. #
########################################################
extends("BaseKPI.py")
"""
Investment Analysis (euro)
---------------------------
Indexed by
* scope
* energy
* test case
* production asset
The Investment Analysis calculates the economic profitability of a given production asset in a given delivery point, defined as the difference between the producer surplus and the investment costs for this specific asset.
The producer surplus is calculated as the benefit the producer receives for selling its product on the market.
The investment costs is the sum of the Capital Expenditure (CAPEX) and Fixed Operating Cost (FOC):
.. math::
\\small investmentAnalysis_{asset} = \\small \\sum_t producerSurplus_{t, asset} - investmentCosts_{asset}
with:
.. math::
\\small investmentCosts_{asset} = \small \\sum_t installedCapacity^{asset}*(CAPEX^{asset} + FOC^{asset})
and:
.. math::
\\small producerSurplus_{asset} = \small \\sum_t (production_{t, asset}.marginalCost_{t, dp, energy}) - productionCost_{asset}
"""
def computeIndicator(context, indexFilter, paramsIndicator, kpiDict):
timeStepDuration = getTimeStepDurationInHours(context)
selectedScopes = indexFilter.filterIndexList(0, getScopes())
selectedTestCases = indexFilter.filterIndexList(1, context.getResultsIndexSet())
selectedAssets = indexFilter.filterIndexList(2, getAssets(context, includedTechnologies = PRODUCTION_TYPES))
selectedAssetsByScope = getAssetsByScope(context, selectedScopes, includedAssetsName = selectedAssets)
producerSurplusDict = getProducerSurplusByAssetDict(context, selectedScopes, selectedTestCases, selectedAssetsByScope)
capexDict = getCapexByAssetDict(context, selectedScopes, selectedTestCases, selectedAssetsByScope)
focDict = getFocByAssetDict(context, selectedScopes, selectedTestCases, selectedAssetsByScope)
for index in producerSurplusDict:
kpiDict[index] = (producerSurplusDict[index]).getSumValue() - (capexDict[index] + focDict[index]).getMeanValue()
return kpiDict
def get_indexing(context) :
baseIndexList = [getScopesIndexing(), getTestCasesIndexing(context), getAssetsIndexing(context, includedTechnologies = PRODUCTION_TYPES)]
return baseIndexList
IndicatorLabel = "Investment Analysis"
IndicatorUnit = u"\u20ac"
IndicatorDeltaUnit = u"\u20ac"
IndicatorDescription = "Difference between the Surplus and the investment costs for a given production asset"
IndicatorParameters = []
IndicatorIcon = ""
IndicatorCategory = "Results>Welfare"
IndicatorTags = "Power System, Power Markets"
| extends('BaseKPI.py')
'\nInvestment Analysis (euro)\n---------------------------\n\nIndexed by\n\t* scope\n\t* energy\n\t* test case\n\t* production asset\n\nThe Investment Analysis calculates the economic profitability of a given production asset in a given delivery point, defined as the difference between the producer surplus and the investment costs for this specific asset.\n\nThe producer surplus is calculated as the benefit the producer receives for selling its product on the market.\nThe investment costs is the sum of the Capital Expenditure (CAPEX) and Fixed Operating Cost (FOC):\n\n.. math::\n\n\t\\small investmentAnalysis_{asset} = \\small \\sum_t producerSurplus_{t, asset} - investmentCosts_{asset}\n\nwith:\n\n.. math::\n\n\t\\small investmentCosts_{asset} = \\small \\sum_t installedCapacity^{asset}*(CAPEX^{asset} + FOC^{asset})\n\nand:\n\n.. math::\n\n\t\\small producerSurplus_{asset} = \\small \\sum_t (production_{t, asset}.marginalCost_{t, dp, energy}) - productionCost_{asset}\n\n'
def compute_indicator(context, indexFilter, paramsIndicator, kpiDict):
time_step_duration = get_time_step_duration_in_hours(context)
selected_scopes = indexFilter.filterIndexList(0, get_scopes())
selected_test_cases = indexFilter.filterIndexList(1, context.getResultsIndexSet())
selected_assets = indexFilter.filterIndexList(2, get_assets(context, includedTechnologies=PRODUCTION_TYPES))
selected_assets_by_scope = get_assets_by_scope(context, selectedScopes, includedAssetsName=selectedAssets)
producer_surplus_dict = get_producer_surplus_by_asset_dict(context, selectedScopes, selectedTestCases, selectedAssetsByScope)
capex_dict = get_capex_by_asset_dict(context, selectedScopes, selectedTestCases, selectedAssetsByScope)
foc_dict = get_foc_by_asset_dict(context, selectedScopes, selectedTestCases, selectedAssetsByScope)
for index in producerSurplusDict:
kpiDict[index] = producerSurplusDict[index].getSumValue() - (capexDict[index] + focDict[index]).getMeanValue()
return kpiDict
def get_indexing(context):
base_index_list = [get_scopes_indexing(), get_test_cases_indexing(context), get_assets_indexing(context, includedTechnologies=PRODUCTION_TYPES)]
return baseIndexList
indicator_label = 'Investment Analysis'
indicator_unit = u'€'
indicator_delta_unit = u'€'
indicator_description = 'Difference between the Surplus and the investment costs for a given production asset'
indicator_parameters = []
indicator_icon = ''
indicator_category = 'Results>Welfare'
indicator_tags = 'Power System, Power Markets' |
print('Please think of a number between 0 and 100!')
x = 54
low = 0
high = 100
guessed = False
while not guessed:
guess = (low + high)/2
print('Is your secret number ' + str(guess)+'?')
s = raw_input("Enter 'h' to indicate the guess is too high.\
Enter 'l' to indicate the guess is too low. Enter \
'c' to indicate I guessed correctly.")
if s == 'c':
guessed = True
elif s == 'l':
low = guess
elif s == 'h':
high = guess
else :
print('Sorry, I did not understand your input.')
print('Game over. Your secret number was: '+str(guess))
| print('Please think of a number between 0 and 100!')
x = 54
low = 0
high = 100
guessed = False
while not guessed:
guess = (low + high) / 2
print('Is your secret number ' + str(guess) + '?')
s = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.")
if s == 'c':
guessed = True
elif s == 'l':
low = guess
elif s == 'h':
high = guess
else:
print('Sorry, I did not understand your input.')
print('Game over. Your secret number was: ' + str(guess)) |
# abcabc
# g_left = a, g_right = b
#
class Solution(object):
def __convert(self, x):
return ord(x) - ord('a') + 1
def distinctEchoSubstrings(self, text):
if len(text) == 1:
return 0
m = int(1e9 + 9)
p = 31
p_pow = 1
g_left = self.__convert(text[0])
g_right = self.__convert(text[1])
hashes = set()
for ws in range(1, len(text)):
left = g_left
right = g_right
for mid in range(len(text) - ws):
if left == right:
hashes.add(left)
first_left = self.__convert(text[ws + mid - 1]) * p_pow
last_left = self.__convert(text[ws + mid])
left = (p * (left - first_left) + last_left) % m
first_right = self.__convert(text[ws * 2 + mid -1]) * p_pow
last_right = self.__convert(text[ws * 2 + mid])
right = (p * (right - first_right) + last_right) % m
for i in range(ws, ws * 2):
first_right = self.__convert()
g_right = (p * (g_right - self.__convert(text[ws]) * p_pow))
p_pow = p_pow * p
g_left = (p * g_left + self.__convert(text[ws])) % m
if __name__ == '__main__':
s = Solution()
n = s.distinctEchoSubstrings("abab")
print(n)
| class Solution(object):
def __convert(self, x):
return ord(x) - ord('a') + 1
def distinct_echo_substrings(self, text):
if len(text) == 1:
return 0
m = int(1000000000.0 + 9)
p = 31
p_pow = 1
g_left = self.__convert(text[0])
g_right = self.__convert(text[1])
hashes = set()
for ws in range(1, len(text)):
left = g_left
right = g_right
for mid in range(len(text) - ws):
if left == right:
hashes.add(left)
first_left = self.__convert(text[ws + mid - 1]) * p_pow
last_left = self.__convert(text[ws + mid])
left = (p * (left - first_left) + last_left) % m
first_right = self.__convert(text[ws * 2 + mid - 1]) * p_pow
last_right = self.__convert(text[ws * 2 + mid])
right = (p * (right - first_right) + last_right) % m
for i in range(ws, ws * 2):
first_right = self.__convert()
g_right = p * (g_right - self.__convert(text[ws]) * p_pow)
p_pow = p_pow * p
g_left = (p * g_left + self.__convert(text[ws])) % m
if __name__ == '__main__':
s = solution()
n = s.distinctEchoSubstrings('abab')
print(n) |
description = 'nGI backpack setup at ICON.'
display_order = 35
pvprefix = 'SQ:ICON:ngiB:'
includes = ['ngi_g0']
excludes = ['ngi_xingi_gratings']
devices = dict(
g1_rz = device('nicos_ess.devices.epics.motor.EpicsMotor',
epicstimeout = 3.0,
description = 'nGI Interferometer Grating Rotation G1 (Backpack)',
motorpv = pvprefix + 'g1rz',
errormsgpv = pvprefix + 'g1rz-MsgTxt',
precision = 0.01,
),
g1_tz = device('nicos_ess.devices.epics.motor.EpicsMotor',
epicstimeout = 3.0,
description = 'nGI Interferometer Grating Talbot G1 (Backpack)',
motorpv = pvprefix + 'g1tz',
errormsgpv = pvprefix + 'g1tz-MsgTxt',
precision = 0.01,
),
g2_rz = device('nicos_ess.devices.epics.motor.EpicsMotor',
epicstimeout = 3.0,
description = 'nGI Interferometer Grating Rotation G2 (Backpack)',
motorpv = pvprefix + 'g2rz',
errormsgpv = pvprefix + 'g2rz-MsgTxt',
precision = 0.01,
)
)
| description = 'nGI backpack setup at ICON.'
display_order = 35
pvprefix = 'SQ:ICON:ngiB:'
includes = ['ngi_g0']
excludes = ['ngi_xingi_gratings']
devices = dict(g1_rz=device('nicos_ess.devices.epics.motor.EpicsMotor', epicstimeout=3.0, description='nGI Interferometer Grating Rotation G1 (Backpack)', motorpv=pvprefix + 'g1rz', errormsgpv=pvprefix + 'g1rz-MsgTxt', precision=0.01), g1_tz=device('nicos_ess.devices.epics.motor.EpicsMotor', epicstimeout=3.0, description='nGI Interferometer Grating Talbot G1 (Backpack)', motorpv=pvprefix + 'g1tz', errormsgpv=pvprefix + 'g1tz-MsgTxt', precision=0.01), g2_rz=device('nicos_ess.devices.epics.motor.EpicsMotor', epicstimeout=3.0, description='nGI Interferometer Grating Rotation G2 (Backpack)', motorpv=pvprefix + 'g2rz', errormsgpv=pvprefix + 'g2rz-MsgTxt', precision=0.01)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.