content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Hover():
"""
Generate hover information
"""
def hover(self, ws, doc, position):
# return {'contents': '.hover.'}
return None
| class Hover:
"""
Generate hover information
"""
def hover(self, ws, doc, position):
return None |
# -*- coding: utf-8 -*-
dict1 = {'Name':'Zara','Age': 18, 'Gender': ['Female','Les']}
print(len(dict1))
print(dict1['Name'])
del dict1['Name']
dict1['Name'] = "none" #change the factor
print(dict1['Name'])
print(dict1)
print(str(dict1)) #same
list1 = list(range(20)) # a list 0-19
print(list1)
print(dict.keys... | dict1 = {'Name': 'Zara', 'Age': 18, 'Gender': ['Female', 'Les']}
print(len(dict1))
print(dict1['Name'])
del dict1['Name']
dict1['Name'] = 'none'
print(dict1['Name'])
print(dict1)
print(str(dict1))
list1 = list(range(20))
print(list1)
print(dict.keys(dict1))
dict2 = {}
dict2.update(dict1)
print(dict2) |
def largest(test):
largest = []
for i in range(test):
size = int(input())
elements = input().split(" ", size)
lst = []
for j in elements:
lst.append(int(j))
largest.append(max(lst))
for i in largest:
print(i)
Test_cases = int(input())
larg... | def largest(test):
largest = []
for i in range(test):
size = int(input())
elements = input().split(' ', size)
lst = []
for j in elements:
lst.append(int(j))
largest.append(max(lst))
for i in largest:
print(i)
test_cases = int(input())
largest(Test_... |
class Node(object):
def __init__(self, key, value, left=None, right=None, parent=None):
self.key = key
self.value = value
self.parent = parent
self.right_child = right
self.left_child = left
self.balance_factor = 0
def has_right_child(self):
return self.r... | class Node(object):
def __init__(self, key, value, left=None, right=None, parent=None):
self.key = key
self.value = value
self.parent = parent
self.right_child = right
self.left_child = left
self.balance_factor = 0
def has_right_child(self):
return self.... |
if __name__ == '__main__':
N = int(input())
arr = []
for _ in range(N):
s = input()
l = s.split(" ")
if l[0] == "print":
print(arr)
elif l[0] == "sort":
arr.sort()
elif l[0] == "append":
arr.append(int(l[1]))
... | if __name__ == '__main__':
n = int(input())
arr = []
for _ in range(N):
s = input()
l = s.split(' ')
if l[0] == 'print':
print(arr)
elif l[0] == 'sort':
arr.sort()
elif l[0] == 'append':
arr.append(int(l[1]))
elif l[0] == 'r... |
gdbsettings=[
"set follow-fork-mode child",
"catch fork"
]
pipe_write_retries=5 | gdbsettings = ['set follow-fork-mode child', 'catch fork']
pipe_write_retries = 5 |
"""
This module contains the main class to be used in custom bridges.
Methods from :class:`Bridge` class should be used in other bridges
"""
__all__ = ['Bridge', ]
class Bridge:
"""Main bridge class containing basic functions."""
@staticmethod
def noop(_model, _gui):
"""Do nothing."""
@st... | """
This module contains the main class to be used in custom bridges.
Methods from :class:`Bridge` class should be used in other bridges
"""
__all__ = ['Bridge']
class Bridge:
"""Main bridge class containing basic functions."""
@staticmethod
def noop(_model, _gui):
"""Do nothing."""
@static... |
#from const import cw
#from const import ccw
cw,ccw = 1,-1
class Point:
x = 0
y = 0
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
def __add__(self, p):
return Point(self.x + p.x, self.y + p.y)
def __sub__(self, p):
return Point(self.x - p.x,... | (cw, ccw) = (1, -1)
class Point:
x = 0
y = 0
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __add__(self, p):
return point(self.x + p.x, self.y + p.y)
def __sub__(self, p):
return point(self.x - p.x, self.y - p.y)
def translate(self, x, y):
s... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 4 06:26:45 2021
@author: Oluchukwu Okoh
"""
class Solution(object):
def runningSum(nums):
return [sum(nums[:i+1]) for i in range(len(nums))]
| """
Created on Tue May 4 06:26:45 2021
@author: Oluchukwu Okoh
"""
class Solution(object):
def running_sum(nums):
return [sum(nums[:i + 1]) for i in range(len(nums))] |
_SDP_SOURCE_PORT = 7
_SDP_SOURCE_CPU = 31
_SDP_TAG = 0xFF
def update_sdp_header_for_udp_send(sdp_header, source_x, source_y):
""" Apply defaults to the sdp header for sending over UDP
:param sdp_header: The SDP header values
:type sdp_header:\
:py:class:`spinnman.messages.... | _sdp_source_port = 7
_sdp_source_cpu = 31
_sdp_tag = 255
def update_sdp_header_for_udp_send(sdp_header, source_x, source_y):
""" Apply defaults to the sdp header for sending over UDP
:param sdp_header: The SDP header values
:type sdp_header: :py:class:`spinnman.messages.sdp.sdp_... |
# coding: utf-8
class Context:
"""
Context which used by all request builders
:ivar http_client: Default HTTP client
:ivar apikey: API key for access to the Twelvedata API
:ivar base_url: Base URL for Twelvedata API
:ivar defaults: Default parameters that will be used by request builders.
... | class Context:
"""
Context which used by all request builders
:ivar http_client: Default HTTP client
:ivar apikey: API key for access to the Twelvedata API
:ivar base_url: Base URL for Twelvedata API
:ivar defaults: Default parameters that will be used by request builders.
"""
http_clie... |
x = input("Type a number: ")
y = input("Type another number: ")
sum = int(x) + int(y)
print("The sum is: ", sum)
| x = input('Type a number: ')
y = input('Type another number: ')
sum = int(x) + int(y)
print('The sum is: ', sum) |
brd = {
'name': ('StickIt! V1', 'StickIt! V2', 'StickIt! V3'),
'port': {
'pmod' : {
'pm1' : {
'd0': 'ch15',
'd1': 'ch11',
'd2': 'chclk',
'd3': 'ch28',
'd4': 'ch16',
'd5': 'ch13',
... | brd = {'name': ('StickIt! V1', 'StickIt! V2', 'StickIt! V3'), 'port': {'pmod': {'pm1': {'d0': 'ch15', 'd1': 'ch11', 'd2': 'chclk', 'd3': 'ch28', 'd4': 'ch16', 'd5': 'ch13', 'd6': 'ch0', 'd7': 'ch14'}, 'pm2': {'d0': 'ch17', 'd1': 'ch15', 'd2': 'ch1', 'd3': 'chclk', 'd4': 'ch18', 'd5': 'ch16', 'd6': 'ch3', 'd7': 'ch0'}, ... |
def move(x=0, dx=10, y=0, dy=10):
x = x + dx
y = y + dy
return x, y
x = 50
y = 50
new_x, new_y = move(x, 50, y, -25)
print("The new coords are: ", new_x, ",", new_y)
print("Call with missing x and y...")
missing_x, missing_y = move(dx=50, dy=50)
print("The new coords are: ", missing_x, ",", missing_y)
| def move(x=0, dx=10, y=0, dy=10):
x = x + dx
y = y + dy
return (x, y)
x = 50
y = 50
(new_x, new_y) = move(x, 50, y, -25)
print('The new coords are: ', new_x, ',', new_y)
print('Call with missing x and y...')
(missing_x, missing_y) = move(dx=50, dy=50)
print('The new coords are: ', missing_x, ',', missing_y) |
def to_bytes(bytes_or_str):
"""
Converts supplied data into bytes if the data is of type str.
:param bytes_or_str: Data to be converted.
:return: UTF-8 encoded bytes if the data was of type str. Otherwise it returns the supplied data as is.
"""
if isinstance(bytes_or_str, str):
return by... | def to_bytes(bytes_or_str):
"""
Converts supplied data into bytes if the data is of type str.
:param bytes_or_str: Data to be converted.
:return: UTF-8 encoded bytes if the data was of type str. Otherwise it returns the supplied data as is.
"""
if isinstance(bytes_or_str, str):
return by... |
class Name_list:
def __init__(self):
self.PREMIER_URL = 'https://www.footballwebpages.co.uk/premier-league'
self.PREMIER_URL_H = 'https://www.footballwebpages.co.uk/premier-league/league-table/home'
self.PREMIER_URL_A = 'https://www.footballwebpages.co.uk/premier-league/league-table/away'
... | class Name_List:
def __init__(self):
self.PREMIER_URL = 'https://www.footballwebpages.co.uk/premier-league'
self.PREMIER_URL_H = 'https://www.footballwebpages.co.uk/premier-league/league-table/home'
self.PREMIER_URL_A = 'https://www.footballwebpages.co.uk/premier-league/league-table/away'
... |
expected_output = {
"services-accounting-information": {
"flow-aggregate-template-detail": {
"flow-aggregate-template-detail-ipv4": {
"detail-entry": {
"source-address": "27.93.202.64",
"destination-address": "106.187.14.158",
... | expected_output = {'services-accounting-information': {'flow-aggregate-template-detail': {'flow-aggregate-template-detail-ipv4': {'detail-entry': {'source-address': '27.93.202.64', 'destination-address': '106.187.14.158', 'source-port': '8', 'destination-port': '0', 'protocol': {'#text': '1'}, 'tos': '0', 'tcp-flags': ... |
_HAS_COLORS = False
COLOR_LOGO = 1
COLOR_LOGO_ALT = 2
COLOR_FOCUSED = 3
COLOR_SCROLLBAR_TRACK = 4
COLOR_SCROLLBAR_THUMB = 5
COLOR_PROGRESSBAR = 6
COLOR_HIGHLIGHT = 7
def has_colors() -> bool:
return _HAS_COLORS
def set_colors(has_colors: bool) -> None:
global _HAS_COLORS
_HAS_COLORS = has_colors
| _has_colors = False
color_logo = 1
color_logo_alt = 2
color_focused = 3
color_scrollbar_track = 4
color_scrollbar_thumb = 5
color_progressbar = 6
color_highlight = 7
def has_colors() -> bool:
return _HAS_COLORS
def set_colors(has_colors: bool) -> None:
global _HAS_COLORS
_has_colors = has_colors |
"""
Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string
containing only letters a-z or .. A . means it can represent any one letter.
Example:
addWord("bad... | """
Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string
containing only letters a-z or .. A . means it can represent any one letter.
Example:
addWord("bad... |
"""Core workflow configuration/constants"""
REQUEST_IDENTIFIER = 'Initial'
REQUEST_STATUS = (
('Initiated', 'Initiated'),
('Withdrawn', 'Withdrawn'),
('Completed', 'Completed')
)
TASK_STATUS = (
('Not Started', 'Not Started'),
('In Progress', 'In Progress'),
('Rolled Back', 'Rolled Back'),
... | """Core workflow configuration/constants"""
request_identifier = 'Initial'
request_status = (('Initiated', 'Initiated'), ('Withdrawn', 'Withdrawn'), ('Completed', 'Completed'))
task_status = (('Not Started', 'Not Started'), ('In Progress', 'In Progress'), ('Rolled Back', 'Rolled Back'), ('Completed', 'Completed'))
work... |
'''10. Write a Python program to print without newline or space.'''
print("This is a sentence", end='')
print("This is a new line that will not show")
| """10. Write a Python program to print without newline or space."""
print('This is a sentence', end='')
print('This is a new line that will not show') |
def pair(relation, human_readable = None):
'''
Creates a dictionary pair of a relation uri in string form and a human readable equivalent.
Args:
relation (str): This should be preformated so generate_uri works on it
human_readable (str): a plain-text description of the uri
Return:
... | def pair(relation, human_readable=None):
"""
Creates a dictionary pair of a relation uri in string form and a human readable equivalent.
Args:
relation (str): This should be preformated so generate_uri works on it
human_readable (str): a plain-text description of the uri
Return:
... |
# coding: utf-8
# Copyright 2020. ThingsBoard
# #
# 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
# #
# Unl... | class File:
def __init__(self, path: str, filename: str, version: str):
self._path = path
self._filename = filename
self._version = version
self._class_name = None
@property
def full_file_path(self):
return self._path + self._filename
@property
def filename... |
class InvalidTimeRangeError(Exception):
"""Error for invalid time ranges."""
def __init__(self, start, stop):
msg = 'Start time {} exceeds stop time {}'.format(
start.isoformat(),
stop.isoformat()
)
super(InvalidTimeRangeError, self).__init__(msg)
class UnknownC... | class Invalidtimerangeerror(Exception):
"""Error for invalid time ranges."""
def __init__(self, start, stop):
msg = 'Start time {} exceeds stop time {}'.format(start.isoformat(), stop.isoformat())
super(InvalidTimeRangeError, self).__init__(msg)
class Unknowncountertypeerror(Exception):
""... |
# Number letter counts
# Problem 17
# If the numbers 1 to 5 are written out in words: one, two, three,
# four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in
# total.
#
# If all the numbers from 1 to 1000 (one thousand) inclusive were
# written out in words, how many letters would be used?
#
#
# NOTE: Do n... | dictionary = {1: len('one'), 2: len('two'), 3: len('three'), 4: len('four'), 5: len('five'), 6: len('six'), 7: len('seven'), 8: len('eight'), 9: len('nine'), 10: len('ten'), 11: len('eleven'), 12: len('twelve'), 13: len('thirteen'), 14: len('fourteen'), 15: len('fifteen'), 16: len('sixteen'), 17: len('seventeen'), 18: ... |
num = 10
num = 22
a= 2
def main():
pass
if __name__ == '__main__':
main()
b = 3
aa = 33
ss = 334
| num = 10
num = 22
a = 2
def main():
pass
if __name__ == '__main__':
main()
b = 3
aa = 33
ss = 334 |
def has_attachment(ctx):
return bool(len(ctx.message.attachments))
def has_embed(ctx):
return bool(len(ctx.message.embeds))
def file_type(ctx, filetype, attnum = 0):
if not has_attachment(ctx): return False
return ctx.message.attachments[attnum].endswith(filetype) | def has_attachment(ctx):
return bool(len(ctx.message.attachments))
def has_embed(ctx):
return bool(len(ctx.message.embeds))
def file_type(ctx, filetype, attnum=0):
if not has_attachment(ctx):
return False
return ctx.message.attachments[attnum].endswith(filetype) |
class ARANGODB:
"""
Arango DB configuration
"""
URL = 'http://arangodb:8529'
USER = 'root'
PASSWORD = ''
DB_NAME = 'thesis' | class Arangodb:
"""
Arango DB configuration
"""
url = 'http://arangodb:8529'
user = 'root'
password = ''
db_name = 'thesis' |
#!/usr/bin/python3.6
# created by cicek on 26.07.2018 22:25
def myFunc():
print("hello")
myFunc()
# You must define functions before they are called, in the same way that you must assign variables before using them
def function(variable):
variable += 1
print(variable)
function(7)
# print(variable) # Name... | def my_func():
print('hello')
my_func()
def function(variable):
variable += 1
print(variable)
function(7)
def add_numbers(x, y):
total = x + y
return total
print("This won't be printed")
print(add_numbers(834, 567))
def fun():
"""
print("hello")
:return:
"""
'\n print("... |
# Every two consecutive numbers add up to 1
n = int(input())
if n % 2 == 0:
print(n // 2)
else:
print(n // 2 + -n)
| n = int(input())
if n % 2 == 0:
print(n // 2)
else:
print(n // 2 + -n) |
def xor_2_bytes(input1,input2):
xor_bytes = b''
for b1, b2 in zip(input1, input2):
xor_bytes += (bytes([b1 ^ b2]))
print(xor_bytes)
return xor_bytes.hex()
if __name__ == "__main__":
byte_string1 = bytes.fromhex('1c0111001f010100061a024b53535009181c')
byte_string2 = bytes.fromhex('686974207468652062756c6c27732... | def xor_2_bytes(input1, input2):
xor_bytes = b''
for (b1, b2) in zip(input1, input2):
xor_bytes += bytes([b1 ^ b2])
print(xor_bytes)
return xor_bytes.hex()
if __name__ == '__main__':
byte_string1 = bytes.fromhex('1c0111001f010100061a024b53535009181c')
byte_string2 = bytes.fromhex('686974... |
# converting vehicle age to inter
def process_vehicule_age(df):
ds = df.copy()
ds["Vehicle_Age"] = ds["Vehicle_Age"].map(
lambda x: 0 if x == "< 1 Year" else 1 if x == "1-2 Year" else 2
)
ds["Vehicle_Age"] = ds["Vehicle_Age"].astype("int")
return ds
# changing the column type for differe... | def process_vehicule_age(df):
ds = df.copy()
ds['Vehicle_Age'] = ds['Vehicle_Age'].map(lambda x: 0 if x == '< 1 Year' else 1 if x == '1-2 Year' else 2)
ds['Vehicle_Age'] = ds['Vehicle_Age'].astype('int')
return ds
def change_type(df):
cols_types = {'str': ['Gender', 'Driving_License', 'Region_Code'... |
"""
Python client for Mantis connect SOAP API
"""
__version__ = '0.4.0'
__author__ = 'Ji Haijun'
__module_name__ = 'mantisconnect2'
__license__ = 'MIT'
| """
Python client for Mantis connect SOAP API
"""
__version__ = '0.4.0'
__author__ = 'Ji Haijun'
__module_name__ = 'mantisconnect2'
__license__ = 'MIT' |
class Solution:
def lengthOfLastWord(self, s: str) -> int:
p, length = len(s) - 1, 0
while p >= 0:
if s[p] != ' ':
length += 1
else:
if length > 0:
return length
p -= 1
return length | class Solution:
def length_of_last_word(self, s: str) -> int:
(p, length) = (len(s) - 1, 0)
while p >= 0:
if s[p] != ' ':
length += 1
elif length > 0:
return length
p -= 1
return length |
"""
Created on 18 Feb 2019
@author: Frank Ypma
"""
class FlowFile(object):
""""
Mock object for a nifi message, containing flowfile content and a dict of attributes
For now, only string content is accepted, but that could be expanded
"""
def __init__(self, content="", attributes=None):
a... | """
Created on 18 Feb 2019
@author: Frank Ypma
"""
class Flowfile(object):
""""
Mock object for a nifi message, containing flowfile content and a dict of attributes
For now, only string content is accepted, but that could be expanded
"""
def __init__(self, content='', attributes=None):
as... |
#!/usr/bin/python3
# author: Karel Fiala
# email: fiala.karel@gmail.com
# config
SERVER_IP = "0.0.0.0"
SERVER_PORT = 5556
CLIENT_LISTEN_IP = "dev.haut.local"
CLIENT_LISTEN_PORT = 5555
BUFFER_SIZE = 1024
WEBSERVER_IP_BIND = "0.0.0.0"
WEBSERVER_PORT_BIND = 5557 | server_ip = '0.0.0.0'
server_port = 5556
client_listen_ip = 'dev.haut.local'
client_listen_port = 5555
buffer_size = 1024
webserver_ip_bind = '0.0.0.0'
webserver_port_bind = 5557 |
while True:
try:
entrada = int(input())
print('Y' if entrada % 6 == 0 else 'N')
except:
break | while True:
try:
entrada = int(input())
print('Y' if entrada % 6 == 0 else 'N')
except:
break |
class Params(object):
"""
Unified Parameter Object for passing arguments among APIs
from the algorithm frame (e.g., client_trainer.py and server aggregator.py).
Usage::
>> my_params = Params()
>> # add parameter
>> my_params.add(name="w", param=model_weights)
>> ... | class Params(object):
"""
Unified Parameter Object for passing arguments among APIs
from the algorithm frame (e.g., client_trainer.py and server aggregator.py).
Usage::
>> my_params = Params()
>> # add parameter
>> my_params.add(name="w", param=model_weights)
>> ... |
# Created by Hansi at 2/14/2020
def calculate_recall(tp, n):
"""
:param tp: int
Number of True Positives
:param n: int
Number of total instances
:return: float
Recall
"""
if n == 0:
return 0
return tp / n
def calculate_precision(tp, fp):
"""
:param ... | def calculate_recall(tp, n):
"""
:param tp: int
Number of True Positives
:param n: int
Number of total instances
:return: float
Recall
"""
if n == 0:
return 0
return tp / n
def calculate_precision(tp, fp):
"""
:param tp: int
Number of True Pos... |
def once(function):
function_has_been_called = False
def wrapper(*args, **kwargs):
if not function_has_been_called:
function_has_been_called = True
return wrapper(*args, **kwargs)
return wrapper
| def once(function):
function_has_been_called = False
def wrapper(*args, **kwargs):
if not function_has_been_called:
function_has_been_called = True
return wrapper(*args, **kwargs)
return wrapper |
"""This is my module docstring"""
'This is another string that has no runtime effect'
b'Bytes literal'
0
1000
def test():
'Function docstring'
| """This is my module docstring"""
'This is another string that has no runtime effect'
b'Bytes literal'
0
1000
def test():
"""Function docstring""" |
'''2. Write a Python program to create a sequence where the first four members
of the sequence are equal to one, and each successive term of the sequence is equal to the
sum of the four previous ones. Find the Nth member of the sequence.'''
num = int(input("Enter the number of terms: "))
| """2. Write a Python program to create a sequence where the first four members
of the sequence are equal to one, and each successive term of the sequence is equal to the
sum of the four previous ones. Find the Nth member of the sequence."""
num = int(input('Enter the number of terms: ')) |
## AUTHOR: Vamsi Krishna Reddy Satti
##################################################################################
# Optimizers
##################################################################################
class SGD:
def __init__(self, model, lr):
self.model = model
self.lr = lr
de... | class Sgd:
def __init__(self, model, lr):
self.model = model
self.lr = lr
def step(self):
for layer in self.model.layers:
for name in layer.params:
layer.params[name] -= self.lr * layer.grad[name] |
if sm.hasQuest(2566):
if sm.hasItem(4032985):
sm.chatScript("You already have the Ignition Device.")
else:
sm.giveItem(4032985)
sm.chatScript("Ignition Device. Bring ") | if sm.hasQuest(2566):
if sm.hasItem(4032985):
sm.chatScript('You already have the Ignition Device.')
else:
sm.giveItem(4032985)
sm.chatScript('Ignition Device. Bring ') |
'''
Created on June 13, 2018
@author: David Stocker
'''
#classes
class EmptyFileError(ValueError):
'''File contains no data '''
pass
class UndefinedPersistenceError(ValueError):
''' No persistence has been defined '''
pass
class PersistenceQueryError(ValueError):
''' Invalid... | """
Created on June 13, 2018
@author: David Stocker
"""
class Emptyfileerror(ValueError):
"""File contains no data """
pass
class Undefinedpersistenceerror(ValueError):
""" No persistence has been defined """
pass
class Persistencequeryerror(ValueError):
""" Invalid Relational Query to persiste... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 23 17:11:21 2020
@author: ahmad
"""
for i in range(0, 10):
storage = ""
for x in range(0, i + 1):
storage += "*"
print(storage)
# storage += "*" => storage = storage + "*"
print("/////////////////////////")
for i in r... | """
Created on Sat May 23 17:11:21 2020
@author: ahmad
"""
for i in range(0, 10):
storage = ''
for x in range(0, i + 1):
storage += '*'
print(storage)
print('/////////////////////////')
for i in range(0, 10):
storage = ''
for x in range(0, 10):
if x < 9 - i:
storage += '... |
# http://www.codewars.com/kata/554b4ac871d6813a03000035/
def high_and_low(numbers):
lst = [int(num) for num in numbers.split()]
return "{0} {1}".format(max(lst), min(lst))
| def high_and_low(numbers):
lst = [int(num) for num in numbers.split()]
return '{0} {1}'.format(max(lst), min(lst)) |
"""
For details of problem statement visit:
https://www.hackerrank.com/rest/contests/master/challenges/the-minion-game/download_pdf?language=English
"""
def minion_game(s):
# your code goes here
i = len(s)
t = 0
k = 0
for x in range(i):
if s[x] == "A" or s[x] == "E" or s[x] == "I" or s[x... | """
For details of problem statement visit:
https://www.hackerrank.com/rest/contests/master/challenges/the-minion-game/download_pdf?language=English
"""
def minion_game(s):
i = len(s)
t = 0
k = 0
for x in range(i):
if s[x] == 'A' or s[x] == 'E' or s[x] == 'I' or (s[x] == 'O') or (s[x] == 'U'... |
# Coding Challenge 2
### Chelsea Lizardo
### NRS 528
#
#
string = 'hi dee hi how are you mr dee'
#Count the occurrence of each word, and print the word plus the count.
def word_count(str):
counts = dict()
words = str.split()
for w in words:
if w in counts:
counts[w] += 1
... | string = 'hi dee hi how are you mr dee'
def word_count(str):
counts = dict()
words = str.split()
for w in words:
if w in counts:
counts[w] += 1
else:
counts[w] = 1
return counts
print(word_count('hi dee hi how are you mr dee')) |
def xo(s):
xcount = 0
ocount = 0
for i in s.lower():
if (i == 'x'):
xcount += 1
elif (i == 'o'):
ocount += 1
return xcount == ocount
print(xo('ooxx'))
# Using count()
def xo2(s):
s = s.lower()
return s.count('x') == s.count('o') | def xo(s):
xcount = 0
ocount = 0
for i in s.lower():
if i == 'x':
xcount += 1
elif i == 'o':
ocount += 1
return xcount == ocount
print(xo('ooxx'))
def xo2(s):
s = s.lower()
return s.count('x') == s.count('o') |
def print_formatted(number):
width = len(str(bin(number)))-2
for num in range(1, number+1):
decimal = int(num)
octal = oct(num)
hexadecimal = hex(num)
binary = bin(num)
print(str(decimal).rjust(width), octal[2:].rjust(
width), hexadecimal[2:].title().rjust(wid... | def print_formatted(number):
width = len(str(bin(number))) - 2
for num in range(1, number + 1):
decimal = int(num)
octal = oct(num)
hexadecimal = hex(num)
binary = bin(num)
print(str(decimal).rjust(width), octal[2:].rjust(width), hexadecimal[2:].title().rjust(width), bina... |
#
# PySNMP MIB module Nortel-Magellan-Passport-CallRedirectionMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-Magellan-Passport-CallRedirectionMIB
# Produced by pysmi-0.3.4 at Wed May 1 14:26:41 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by use... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, constraints_union, constraints_intersection, single_value_constraint) ... |
def make_adder(x):
def adder(y):
return x + y
return adder
inc = make_adder(1)
plus10 = make_adder(10)
___assertEqual(inc(1), 2)
___assertEqual(plus10(-2), 8)
| def make_adder(x):
def adder(y):
return x + y
return adder
inc = make_adder(1)
plus10 = make_adder(10)
___assert_equal(inc(1), 2)
___assert_equal(plus10(-2), 8) |
class Solution:
def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]:
if x == 1:
i_max = 0
else:
i_max = int(math.log(bound,x))
if y == 1:
j_max = 0
else:
j_max = int(math.log(bound,y))
res =... | class Solution:
def powerful_integers(self, x: int, y: int, bound: int) -> List[int]:
if x == 1:
i_max = 0
else:
i_max = int(math.log(bound, x))
if y == 1:
j_max = 0
else:
j_max = int(math.log(bound, y))
res = []
for i ... |
# Programacion orientada a objetos 1
# https://www.youtube.com/watch?v=lg9p0yWgXYk&list=PLh7JzoyIyU4JVOeKkiNYPkAWBq0Aszxc-&index=2
class Persona:
def __init__(self, nombre_persona, calle=1):
self.nombre = nombre_persona
self.calle = calle
def moverse(self, velocidad):
self.calle += ... | class Persona:
def __init__(self, nombre_persona, calle=1):
self.nombre = nombre_persona
self.calle = calle
def moverse(self, velocidad):
self.calle += velocidad
jose = persona('Jose')
juan = persona('Juan', 2)
print(jose.nombre)
print(juan.nombre)
print(jose.calle)
print(juan.calle)
j... |
""" Given an integer array, find three numbers whose product is maximum and
output the maximum product.
Example 1: Input: [1,2,3] Output: 6
IDEA:
track
3 maximum numbers in desc order (max1 is the biggest)
and
2 smallest
"""
class Solution628:
pass
| """ Given an integer array, find three numbers whose product is maximum and
output the maximum product.
Example 1: Input: [1,2,3] Output: 6
IDEA:
track
3 maximum numbers in desc order (max1 is the biggest)
and
2 smallest
"""
class Solution628:
pass |
# simplified linked list
class Node:
def __init__ (self, value, next=None):
self.value = value
self.next = next
L = Node('a', Node('b', Node('c', Node('d'))))
# print('L', L.value)
# print(L.next.next.value)
| class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
l = node('a', node('b', node('c', node('d')))) |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def bstToGst(self, root: TreeNode) -> TreeNode:
def f(root, val = 0):
if root is None:
... | class Solution:
def bst_to_gst(self, root: TreeNode) -> TreeNode:
def f(root, val=0):
if root is None:
return 0
right_value = f(root.right, val)
left_value = f(root.left, root.val + rightValue + val)
t = root.val
root.val += right... |
tokens = {
"WETH": "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
"DAI": "0x6B175474E89094C44Da98b954EedeAC495271d0F",
"BAT": "0x0D8775F648430679A709E98d2b0Cb6250d2887EF",
"WBTC": "0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599",
"UNI": "0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984",
}
| tokens = {'WETH': '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', 'DAI': '0x6B175474E89094C44Da98b954EedeAC495271d0F', 'BAT': '0x0D8775F648430679A709E98d2b0Cb6250d2887EF', 'WBTC': '0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599', 'UNI': '0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984'} |
# -*- coding: utf-8 -*-
casos = int(input())
result = []
for i in range(casos):
num1, num2, indice1, indice2 = input().split(" ")
num1 = int(num1)
num2 = int(num2)
indice1 = float(indice1)
indice2 = float(indice2)
anos = 0
while num1 <= num2:
num1 += int(num1*indice1/100)
nu... | casos = int(input())
result = []
for i in range(casos):
(num1, num2, indice1, indice2) = input().split(' ')
num1 = int(num1)
num2 = int(num2)
indice1 = float(indice1)
indice2 = float(indice2)
anos = 0
while num1 <= num2:
num1 += int(num1 * indice1 / 100)
num2 += int(num2 * in... |
"""
1. Clarification
2. Possible solutions
- Trie
- Queue
3. Coding
4. Tests
"""
# T=O(n), S=O(n)
class WordDictionary:
def __init__(self):
self.root = {}
self.end_of_word = '#'
def addWord(self, word: str) -> None:
node = self.root
for char in word:
node ... | """
1. Clarification
2. Possible solutions
- Trie
- Queue
3. Coding
4. Tests
"""
class Worddictionary:
def __init__(self):
self.root = {}
self.end_of_word = '#'
def add_word(self, word: str) -> None:
node = self.root
for char in word:
node = node.setdefault... |
"""Constants."""
CACHE_NAME = 'infographics'
CACHE_TIMEOUT = 3600
| """Constants."""
cache_name = 'infographics'
cache_timeout = 3600 |
if __name__ == '__main__':
arr = []
for _ in range(int(input())):
name = input()
score = float(input())
arr.append([name,score])
arr.sort()
first = 100000
second = 100000
for i in range(len(arr)):
if (arr[i][1] < first):
second = first
... | if __name__ == '__main__':
arr = []
for _ in range(int(input())):
name = input()
score = float(input())
arr.append([name, score])
arr.sort()
first = 100000
second = 100000
for i in range(len(arr)):
if arr[i][1] < first:
second = first
first... |
# Find First and Last Position of Element in Sorted Array
class Solution:
def binSearch(self, nums, target):
length = len(nums)
left, right = 0, length - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
while mid >= 0 and nums[... | class Solution:
def bin_search(self, nums, target):
length = len(nums)
(left, right) = (0, length - 1)
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
while mid >= 0 and nums[mid] == target:
mid -= 1
... |
# def find_all_index(text, pattern):
# pattern_index = 0
# match = []
# # if pattern is empty, then return all indices
# if pattern == '':
# for index in range(len(text)):
# match.append(index)
# return match
# for index, charc in enumerate(text):
# # check if let... | def find_all_index(text, pattern):
match = []
if pattern == '':
for index in range(len(text)):
match.append(index)
return match
for (t_index, t_char) in enumerate(text):
print('t_index: ', t_index)
for (p_index, p_char) in enumerate(pattern):
print(' ... |
def mergeSort(list):
if len(list) <= 1:
return list
# Find the middle point and devide it
middle = len(list) // 2
left_list = list[:middle]
right_list = list[middle:]
left_list = mergeSort(left_list)
right_list = mergeSort(right_list)
return merge(left_list, right_list)
... | def merge_sort(list):
if len(list) <= 1:
return list
middle = len(list) // 2
left_list = list[:middle]
right_list = list[middle:]
left_list = merge_sort(left_list)
right_list = merge_sort(right_list)
return merge(left_list, right_list)
def merge(left_half, right_half):
res = []
... |
class HTTPException(Exception):
def __init__(self, request, data):
msg = f"HTTP request returned {request.status} status code."
self.request = request
for k, v in data.items():
setattr(self, k, v)
msg += f"\nIn {k}: {v}"
return super().__init__(msg)
... | class Httpexception(Exception):
def __init__(self, request, data):
msg = f'HTTP request returned {request.status} status code.'
self.request = request
for (k, v) in data.items():
setattr(self, k, v)
msg += f'\nIn {k}: {v}'
return super().__init__(msg)
class ... |
"""
Supplai Version: Generated by python setup.py
"""
__version__ = "0.4.0"
| """
Supplai Version: Generated by python setup.py
"""
__version__ = '0.4.0' |
CARD_VALUES = {
'2': 1,
'3': 1,
'4': 1,
'5': 1,
'6': 1,
'7': 0,
'8': 0,
'9': 0,
'0': -1,
'1': -1,
'J': -1,
'Q': -1,
'K': -1,
'A': -1,
'*': -1
}
DECKS = 8
def main():
count = 0
cards = 0
user_input = True
decks_play... | card_values = {'2': 1, '3': 1, '4': 1, '5': 1, '6': 1, '7': 0, '8': 0, '9': 0, '0': -1, '1': -1, 'J': -1, 'Q': -1, 'K': -1, 'A': -1, '*': -1}
decks = 8
def main():
count = 0
cards = 0
user_input = True
decks_played = 0
while user_input:
user_input = input('CARDS >> ')
user_input = u... |
# -*- coding: utf-8 -*-
# Author: Arthur Imbert <arthur.imbert.pro@gmail.com>
# License: BSD 3 clause
"""
Unitary tests for bigfish.detection.spot_detection module.
"""
# TODO test bigfish.detection.detect_spots
# TODO test bigfish.detection.local_maximum_detection
# TODO test bigfish.detection.spots_thresholding
# T... | """
Unitary tests for bigfish.detection.spot_detection module.
""" |
################### EXERCISE 1 ###############################################
# Constants
METER_PER_INCH = 0.0254
INCHES_PER_FEET = 12
feet = int(input('Enter the number of feet:'))
inches = int(input('Enter the number of inches:'))
number_meters = (feet * INCHES_PER_FEET + inches) * METER_PER_INCH
print(feet,'feet',... | meter_per_inch = 0.0254
inches_per_feet = 12
feet = int(input('Enter the number of feet:'))
inches = int(input('Enter the number of inches:'))
number_meters = (feet * INCHES_PER_FEET + inches) * METER_PER_INCH
print(feet, 'feet', inches, 'inches is equivalent to', number_meters, 'meters')
metres = float(input('Enter th... |
expected_output = {
'ikev2_session': {
'IPv4':{
1:{
'session_id': 3,
'status': 'UP-ACTIVE',
'ike_count': 1,
'child_count': 1,
'tunnel_id': 1,
'local_ip': '1.1.1.1',... | expected_output = {'ikev2_session': {'IPv4': {1: {'session_id': 3, 'status': 'UP-ACTIVE', 'ike_count': 1, 'child_count': 1, 'tunnel_id': 1, 'local_ip': '1.1.1.1', 'local_port': 500, 'remote_ip': '1.1.1.2', 'remote_port': 500, 'fvrf': 'none', 'ivrf': 'none', 'session_status': 'READY', 'encryption': 'AES-CBC', 'key_lengt... |
class Solution:
def addNegabinary(self, arr1: List[int], arr2: List[int]) -> List[int]:
p1, p2 = len(arr1)-1, len(arr2)-1
carry = 0
result = []
while p1 >= 0 or p2 >= 0 or carry:
bit_sum = 0
if p1 >= 0:
bit_sum += arr1[p1]
p... | class Solution:
def add_negabinary(self, arr1: List[int], arr2: List[int]) -> List[int]:
(p1, p2) = (len(arr1) - 1, len(arr2) - 1)
carry = 0
result = []
while p1 >= 0 or p2 >= 0 or carry:
bit_sum = 0
if p1 >= 0:
bit_sum += arr1[p1]
... |
"""
File: anagram.py
Name: Dennis Hsu
----------------------------------
This program recursively finds all the anagram(s)
for the word input by user and terminates when the
input string matches the EXIT constant defined
at line 19
If you correctly implement this program, you should see the
number of anagrams for each... | """
File: anagram.py
Name: Dennis Hsu
----------------------------------
This program recursively finds all the anagram(s)
for the word input by user and terminates when the
input string matches the EXIT constant defined
at line 19
If you correctly implement this program, you should see the
number of anagrams for each... |
class FourCal:
def setdata(self,first,second):
self.first=first
self.second=second
def add(self):
result=self.first+self.second
return result
def mul(self):
result=self.first*self.second
return result
def sub(self):
result=self.first-self.se... | class Fourcal:
def setdata(self, first, second):
self.first = first
self.second = second
def add(self):
result = self.first + self.second
return result
def mul(self):
result = self.first * self.second
return result
def sub(self):
result = self.... |
# pyre-ignore-all-errors
# TODO: Change `pyre-ignore-all-errors` to `pyre-strict` on line 1, so we get
# to see all type errors in this file.
# TypeVars can also take a "bound" argument. Suppose we have a class hierachy like this:
class Pet:
name: str
def __init__(self, name: str) -> None:
self.nam... | class Pet:
name: str
def __init__(self, name: str) -> None:
self.name = name
class Dog(Pet):
pass
class Cat(Pet):
pass
def make_cute(pet):
original_name = pet.name
new_name = f'Cute {original_name}'
pet.name = new_name
return pet
def verify_dog(dog: Dog) -> None:
...
de... |
def part_1():
file = open('input.txt', 'r')
highest_id = 0
for lineWithOptionNewLine in file:
line = lineWithOptionNewLine.strip('\n')
left = 0
right = 127
for letter in line[:-3]:
mid = (left + right) // 2
if letter == "F":
right = mi... | def part_1():
file = open('input.txt', 'r')
highest_id = 0
for line_with_option_new_line in file:
line = lineWithOptionNewLine.strip('\n')
left = 0
right = 127
for letter in line[:-3]:
mid = (left + right) // 2
if letter == 'F':
right =... |
"""Add custom options to py.test."""
def pytest_addoption(parser):
"""Add option to recreate tox environments."""
parser.addoption(
"--tox-recreate",
action="store_true",
default=False,
help="Recreate the tox environments for click and toil modes.",
)
parser.addopt... | """Add custom options to py.test."""
def pytest_addoption(parser):
"""Add option to recreate tox environments."""
parser.addoption('--tox-recreate', action='store_true', default=False, help='Recreate the tox environments for click and toil modes.')
parser.addoption('--tox-develop', action='store_true', def... |
"""
Given two strings X and Y, print the shortest string that has both X and Y as subsequences.
If multiple shortest supersequence exists, print any one of them.
Examples:
Input: X = "AGGTAB", Y = "GXTXAYB"
Output: "AGXGTXAYB" OR "AGGXTXAYB"
OR Any string that represents shortest
supersequence of X and Y
Input: X ... | """
Given two strings X and Y, print the shortest string that has both X and Y as subsequences.
If multiple shortest supersequence exists, print any one of them.
Examples:
Input: X = "AGGTAB", Y = "GXTXAYB"
Output: "AGXGTXAYB" OR "AGGXTXAYB"
OR Any string that represents shortest
supersequence of X and Y
Input: X ... |
fac_no_faction = 0
fac_commoners = 1
fac_outlaws = 2
fac_neutral = 3
fac_player_faction = 4
fac_player_supporters_faction = 5
fac_britain = 6
fac_france = 7
fac_prussia = 8
fac_russia = 9
fac_austria = 10
fac_kingdoms_end = 11
fac_kingdom_6 = 12
fac_kingdom_7 = 13
fac_kingdom_8 = 14
fac_kingdom_9 = 15
fac_kingdom_10 = ... | fac_no_faction = 0
fac_commoners = 1
fac_outlaws = 2
fac_neutral = 3
fac_player_faction = 4
fac_player_supporters_faction = 5
fac_britain = 6
fac_france = 7
fac_prussia = 8
fac_russia = 9
fac_austria = 10
fac_kingdoms_end = 11
fac_kingdom_6 = 12
fac_kingdom_7 = 13
fac_kingdom_8 = 14
fac_kingdom_9 = 15
fac_kingdom_10 = ... |
# -*- coding: utf-8 -*-
def main():
one = plus(2,3)
print("Hello Python!:"&str(one))
def plus(x,y):
return x+y
if __name__ == "__main__":
main()
| def main():
one = plus(2, 3)
print('Hello Python!:' & str(one))
def plus(x, y):
return x + y
if __name__ == '__main__':
main() |
pkgname = "evince"
pkgver = "42.1"
pkgrel = 0
build_style = "meson"
# dvi needs kpathsea, which is in texlive
# does anyone actually need dvi?
configure_args = [
"-Dintrospection=true", "-Dgtk_doc=false",
"-Dcomics=enabled", "-Dps=enabled", "-Ddvi=disabled",
]
hostmakedepends = [
"meson", "pkgconf", "gobjec... | pkgname = 'evince'
pkgver = '42.1'
pkgrel = 0
build_style = 'meson'
configure_args = ['-Dintrospection=true', '-Dgtk_doc=false', '-Dcomics=enabled', '-Dps=enabled', '-Ddvi=disabled']
hostmakedepends = ['meson', 'pkgconf', 'gobject-introspection', 'glib-devel', 'itstool', 'gettext-tiny', 'perl-xml-parser', 'adwaita-icon... |
def gcd(a, b):
if (b == 0):
return a
else:
return gcd(b, a%b)
T = input('')
for _ in xrange(T):
b,a = map(int, raw_input('').split())
print(gcd(a, b))
| def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
t = input('')
for _ in xrange(T):
(b, a) = map(int, raw_input('').split())
print(gcd(a, b)) |
# -*- coding: utf-8 -*-
#
# Copyright 2019 SoloKeys Developers
#
# Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
# http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
# http://opensource.org/licenses/MIT>, at your option. This file may not be
# copied, modified, or distribute... | def to_websafe(data):
data = data.replace('+', '-')
data = data.replace('/', '_')
data = data.replace('=', '')
return data
def from_websafe(data):
data = data.replace('-', '+')
data = data.replace('_', '/')
return data + '=='[:3 * len(data) % 4] |
def numberOfSubarrays(nums, k: int):
odd_indices = []
for idx, x in enumerate(nums):
if x % 2 == 1:
odd_indices.append(idx)
count_over_odds = 0
for start in range(len(odd_indices) - k + 1):
valid_slice = odd_indices[start: start + k]
count = 1
head = ... | def number_of_subarrays(nums, k: int):
odd_indices = []
for (idx, x) in enumerate(nums):
if x % 2 == 1:
odd_indices.append(idx)
count_over_odds = 0
for start in range(len(odd_indices) - k + 1):
valid_slice = odd_indices[start:start + k]
count = 1
head = 1
... |
# Created by Egor Kostan.
# GitHub: https://github.com/ikostan
# LinkedIn: https://www.linkedin.com/in/egor-kostan/
def share_price(invested: int, changes: list) -> str:
"""
Calculates, and returns the current price of your share,
given the following two arguments:
1. invested(number), the amount ... | def share_price(invested: int, changes: list) -> str:
"""
Calculates, and returns the current price of your share,
given the following two arguments:
1. invested(number), the amount of money you initially
invested in the given share
2. changes(array of numbers), contains your shares daily
... |
SAMPLE_INPUT_FILE = "sample_input_day_20_aoc21.txt"
PUZZLE_INPUT_FILE = "puzzle_input_day_20_aoc21.txt"
NUM_ENHANCEMENTS = 50
def parse_input(dir_file: str) -> tuple[str, list]:
"""
Args:
dir_file (str): location of .txt file to pull data from
Returns:
"""
alg, im = '', []
with open(d... | sample_input_file = 'sample_input_day_20_aoc21.txt'
puzzle_input_file = 'puzzle_input_day_20_aoc21.txt'
num_enhancements = 50
def parse_input(dir_file: str) -> tuple[str, list]:
"""
Args:
dir_file (str): location of .txt file to pull data from
Returns:
"""
(alg, im) = ('', [])
with ope... |
#Question Link <https://leetcode.com/problems/trapping-rain-water/>
class Solution:
def trap(self, height):
left, right = 0, len(height) - 1
ans = left_max = right_max = 0
while left < right:
if height[left] < height[right]:
left_max = max(left_max, height[left])
... | class Solution:
def trap(self, height):
(left, right) = (0, len(height) - 1)
ans = left_max = right_max = 0
while left < right:
if height[left] < height[right]:
left_max = max(left_max, height[left])
ans += left_max - height[left]
... |
"""
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
a=[*open(0)][1].split()
print(max(a.count(x)for x in{*a})) | """
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
a = [*open(0)][1].split()
print(max((a.count(x) for x in {*a}))) |
# Project Euler #21: Amicable numbers
def sum_of_divisors(n):
sd = 1 # 1 is a divisors1
i = 2
i2 = i * i
while i2 <= n:
if n % i == 0:
sd += i + n // i
if i2 == n:
sd -= i
i += 1
i2 = i * i
return sd
print(sum_of_divisors(220))
print(s... | def sum_of_divisors(n):
sd = 1
i = 2
i2 = i * i
while i2 <= n:
if n % i == 0:
sd += i + n // i
if i2 == n:
sd -= i
i += 1
i2 = i * i
return sd
print(sum_of_divisors(220))
print(sum_of_divisors(284))
def main():
n = 10000
n = 300
i ... |
#!/usr/bin/env python3
#This program will write Hello World !
print("Hello World!")
| print('Hello World!') |
#!/usr/bin/python3
# -*- coding: utf8 -*-
class Round:
def __init__(self, x1: int, y1: int, x2: int, y2: int, context, **kwargs):
"""
This widget allows you to create circles or ovals
:param x1: int
:param y1: int
:param x2: int
:param y2: int
:param context... | class Round:
def __init__(self, x1: int, y1: int, x2: int, y2: int, context, **kwargs):
"""
This widget allows you to create circles or ovals
:param x1: int
:param y1: int
:param x2: int
:param y2: int
:param context: => context tkinter (here canvas)
... |
archivo = open("DDSIVClases/archivo.txt", "r")
# imprime cada linea del archivo txt
for linea in archivo:
print(linea)
#linea2 = archivo.readline(2)
#print(linea2)
lineas = archivo.readline()
| archivo = open('DDSIVClases/archivo.txt', 'r')
for linea in archivo:
print(linea)
lineas = archivo.readline() |
query = """
SELECT L_SHIPMODE,
sum(CASE WHEN O_ORDERPRIORITY='1-URGENT'
OR O_ORDERPRIORITY='2-HIGH'
THEN 1 ELSE 0 END) AS HIGH_LINE_COUNT,
sum(CASE WHEN O_ORDERPRIORITY <> '1-URGENT'
AND O_ORDERPRIORITY <> '2-HIGH'
THEN 1 ELSE 0 END) AS LOW_LINE_COUNT
FROM orders,
lineitem
WHERE O_ORDERKEY = L_ORDE... | query = "\nSELECT\tL_SHIPMODE,\n\tsum(CASE WHEN O_ORDERPRIORITY='1-URGENT'\n\tOR O_ORDERPRIORITY='2-HIGH'\n\tTHEN 1 ELSE 0 END) AS HIGH_LINE_COUNT,\n\tsum(CASE WHEN O_ORDERPRIORITY <> '1-URGENT' \n\t\tAND O_ORDERPRIORITY <> '2-HIGH' \n\t\tTHEN 1 ELSE 0 END) AS LOW_LINE_COUNT\nFROM\torders,\n\tlineitem\nWHERE\tO_ORDERKE... |
tree_count = 0
with open("input.txt") as file_handler:
for n, line in enumerate(file_handler):
if n == 0:
continue
if len(line.strip()) == 0:
continue
charPos = n*3
if charPos > len(line.strip()):
multiples = int(charPos / len(line.strip()))
... | tree_count = 0
with open('input.txt') as file_handler:
for (n, line) in enumerate(file_handler):
if n == 0:
continue
if len(line.strip()) == 0:
continue
char_pos = n * 3
if charPos > len(line.strip()):
multiples = int(charPos / len(line.strip()))
... |
class Solution(object):
def minSwapsCouples(self, row):
"""
:type row: List[int]
:rtype: int
"""
couple_num = (len(row) + 1) / 2
error_index = []
error_num = 0
for i in range(couple_num):
i = i * 2
if row[i] < row[i + 1]:
... | class Solution(object):
def min_swaps_couples(self, row):
"""
:type row: List[int]
:rtype: int
"""
couple_num = (len(row) + 1) / 2
error_index = []
error_num = 0
for i in range(couple_num):
i = i * 2
if row[i] < row[i + 1]:
... |
class Solution(object):
def findMissingRanges(self, nums, lower, upper):
"""
Find missing ranges by iterating through all nums
To account for inclusivity, we add lower -1 and upper +1 to the nums array
"""
all = [lower -1] + nums + [upper + 1]
res = []
for i... | class Solution(object):
def find_missing_ranges(self, nums, lower, upper):
"""
Find missing ranges by iterating through all nums
To account for inclusivity, we add lower -1 and upper +1 to the nums array
"""
all = [lower - 1] + nums + [upper + 1]
res = []
for... |
"""
FIT1008 Prac 5 Task 1
@purpose reverse.py
@author Loh Hao Bin 25461257, Derwinn Ee 25216384
@modified 20140823
@created 20140821
"""
def reverse():
"""
@purpose: To read in a size n, then input a list of size n, then prints out
in reverse order
@param: none
@complexity: O(N) where N is ... | """
FIT1008 Prac 5 Task 1
@purpose reverse.py
@author Loh Hao Bin 25461257, Derwinn Ee 25216384
@modified 20140823
@created 20140821
"""
def reverse():
"""
@purpose: To read in a size n, then input a list of size n, then prints out
in reverse order
@param: none
@complexity: O(N) where N is ... |
"""
Exception definitions for kastore.
"""
class KastoreException(Exception):
"""
Parent class of all Kastore specific exceptions.
"""
class FileFormatError(KastoreException):
"""
The provided file was not in the expected format.
"""
class StoreClosedError(KastoreException):
"""
Th... | """
Exception definitions for kastore.
"""
class Kastoreexception(Exception):
"""
Parent class of all Kastore specific exceptions.
"""
class Fileformaterror(KastoreException):
"""
The provided file was not in the expected format.
"""
class Storeclosederror(KastoreException):
"""
The s... |
class subtitle:
"""
Digests a YouTube subtitle file.
"""
def __init__(self, file):
try:
f = open(file, "r")
self._file = f
except IOError:
raise Exception("Cannot open subtitle file.")
def get_all_text(self):
"""
Parses the f... | class Subtitle:
"""
Digests a YouTube subtitle file.
"""
def __init__(self, file):
try:
f = open(file, 'r')
self._file = f
except IOError:
raise exception('Cannot open subtitle file.')
def get_all_text(self):
"""
Parses the file i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.