content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# Bubble sort
def sort_bubble(my_list):
for i in range(len(my_list) - 1, 0, -1):
for j in range(i):
if my_list[j] > my_list[j + 1]:
my_list[j], my_list[j + 1] = my_list[j + 1], my_list[j]
return my_list
print(sort_bubble([1,4,2,6,5,3,1])) | def sort_bubble(my_list):
for i in range(len(my_list) - 1, 0, -1):
for j in range(i):
if my_list[j] > my_list[j + 1]:
(my_list[j], my_list[j + 1]) = (my_list[j + 1], my_list[j])
return my_list
print(sort_bubble([1, 4, 2, 6, 5, 3, 1])) |
#program to enter number followed by commas and the storing those numbers in a list
arr=[];r=0;
a=input("ENter numbers followed by commas :")
l=a.split(",")
m=''
for c in a:
if(c!=','):
m=m+c;
else:
arr.append(int(m));
m='';
arr.append(int(m));
print(arr);
| arr = []
r = 0
a = input('ENter numbers followed by commas :')
l = a.split(',')
m = ''
for c in a:
if c != ',':
m = m + c
else:
arr.append(int(m))
m = ''
arr.append(int(m))
print(arr) |
file = open ("employees.txt" , "r")
if(file.readable()):
print("Success")
else:
print("Error")
print()
#read the whole file
print(file.read())
#rewind file pointer
file.seek(0)
print()
#read individual line
print(file.readline())
#rewind file pointer
file.seek(0)
print()
#read the whole file and set as l... | file = open('employees.txt', 'r')
if file.readable():
print('Success')
else:
print('Error')
print()
print(file.read())
file.seek(0)
print()
print(file.readline())
file.seek(0)
print()
print(file.readlines())
file.seek(0)
print()
print(file.readlines()[1])
file.seek(0)
print()
for employee in file.readlines():
... |
class UserOutputVariables:
"""The UserOutputVariables object specifies the number of user-defined output variables.
Notes
-----
This object can be accessed by:
.. code-block:: python
import material
mdb.models[name].materials[name].userOutputVariables
import odbMaterial
... | class Useroutputvariables:
"""The UserOutputVariables object specifies the number of user-defined output variables.
Notes
-----
This object can be accessed by:
.. code-block:: python
import material
mdb.models[name].materials[name].userOutputVariables
import odbMaterial
... |
'''
Script converts data from newline seperated values to comma seperated values
'''
fName = input('Enter File Name:')
with open(fName,'r') as f:
lines = f.read()
f.close()
values = lines.splitlines()
s = 'time\n'
for val in values:
s = s + val.strip() + '\n'
print(s)
with open(fName,'w') as f:
f.w... | """
Script converts data from newline seperated values to comma seperated values
"""
f_name = input('Enter File Name:')
with open(fName, 'r') as f:
lines = f.read()
f.close()
values = lines.splitlines()
s = 'time\n'
for val in values:
s = s + val.strip() + '\n'
print(s)
with open(fName, 'w') as f:
f.wri... |
# Spiritual Release (57462)
sakuno = 9130021
sm.setSpeakerID(sakuno)
sm.sendNext("Kanna, please come to Momijigaoka. We have news.")
sm.setPlayerAsSpeaker()
sm.sendSay("I wonder what's going on? I hope Oda's Army isn't on the move.")
sm.startQuest(parentID)
| sakuno = 9130021
sm.setSpeakerID(sakuno)
sm.sendNext('Kanna, please come to Momijigaoka. We have news.')
sm.setPlayerAsSpeaker()
sm.sendSay("I wonder what's going on? I hope Oda's Army isn't on the move.")
sm.startQuest(parentID) |
Theatre_1 = {"Name":'Lviv',
"Seats_Number":120,
"Actors_1":["Andrew Kigan","Jhon Speelberg","Alan Mask","Neil Bambino"],
"Play_1":["25/03/2018","Aida",80,"Andrew Kigan","Jhon Speelberg",60,"OK"],
"Play_2":["26/03/2018","War",220,"Jhon Speelberg","Jhon Speelberg","Alan... | theatre_1 = {'Name': 'Lviv', 'Seats_Number': 120, 'Actors_1': ['Andrew Kigan', 'Jhon Speelberg', 'Alan Mask', 'Neil Bambino'], 'Play_1': ['25/03/2018', 'Aida', 80, 'Andrew Kigan', 'Jhon Speelberg', 60, 'OK'], 'Play_2': ['26/03/2018', 'War', 220, 'Jhon Speelberg', 'Jhon Speelberg', 'Alan Mask', 'Neil Bambino', 100, 'OK'... |
'''
Subgraphs II
In the previous exercise, we gave you a list of nodes whose neighbors we asked you to extract.
Let's try one more exercise in which you extract nodes that have a particular metadata property and their neighbors. This should hark back to what you've learned about using list comprehensions to find node... | """
Subgraphs II
In the previous exercise, we gave you a list of nodes whose neighbors we asked you to extract.
Let's try one more exercise in which you extract nodes that have a particular metadata property and their neighbors. This should hark back to what you've learned about using list comprehensions to find node... |
"""
This module contain functions which are cheking whether the given board
fits the rules.
Git repository: https://github.com/msharsh/puzzle.git
"""
def check_rows(board: list) -> bool:
"""
Checks if there are identical numbers in every row in the board.
Returns True if not, else False.
>>> check_rows(["**... | """
This module contain functions which are cheking whether the given board
fits the rules.
Git repository: https://github.com/msharsh/puzzle.git
"""
def check_rows(board: list) -> bool:
"""
Checks if there are identical numbers in every row in the board.
Returns True if not, else False.
>>> check_rows(["*... |
# program description
# :: python
# :: allows user to enter initial height of ball before dropped
# :: outputs total distance traveled by ball based on number of bounces
# constants
bounceIndex = float(0.6)
# input variables
height = int(input("Enter Ball Height: "))
numberOfBounces = float(input("Enter Number Of Bal... | bounce_index = float(0.6)
height = int(input('Enter Ball Height: '))
number_of_bounces = float(input('Enter Number Of Ball Bounces: '))
distance = 0
while numberOfBounces > 0:
distance += height
height *= bounceIndex
distance += height
number_of_bounces -= 1
print('Total Distance Traveled: ' + str(dista... |
"""Top-level package for EnviroBot."""
__author__ = """Chris Last"""
__email__ = 'chris.last@gmail.com'
__version__ = '0.1.0'
| """Top-level package for EnviroBot."""
__author__ = 'Chris Last'
__email__ = 'chris.last@gmail.com'
__version__ = '0.1.0' |
class Stack:
def __init__(self):
self.items = []
def push(self, e):
self.items = [e] + self.items
def pop(self):
return self.items.pop()
s = Stack()
s.push(5) # [5]
s.push(7) # [7, 5]
s.push(11) # [11, 7, 5]
print(s.pop()) # returns 11, left is [7, 5]
print(s.pop()) ... | class Stack:
def __init__(self):
self.items = []
def push(self, e):
self.items = [e] + self.items
def pop(self):
return self.items.pop()
s = stack()
s.push(5)
s.push(7)
s.push(11)
print(s.pop())
print(s.pop()) |
i=map(int, raw_input())
c=0
for m in i:
c = c+1 if m==4 or m==7 else c
print("YES" if c==4 or c==7 else "NO") | i = map(int, raw_input())
c = 0
for m in i:
c = c + 1 if m == 4 or m == 7 else c
print('YES' if c == 4 or c == 7 else 'NO') |
class Solution:
def tribonacci(self, n: int) -> int:
if n <= 1:
return n
arr = [0 for i in range(n+1)]
arr[1], arr[2] = 1, 1
for i in range(3, len(arr)):
arr[i] = arr[i-1] + arr[i-2] + arr[i-3]
return arr[n]
s = Solution()
print(s.tribonacc... | class Solution:
def tribonacci(self, n: int) -> int:
if n <= 1:
return n
arr = [0 for i in range(n + 1)]
(arr[1], arr[2]) = (1, 1)
for i in range(3, len(arr)):
arr[i] = arr[i - 1] + arr[i - 2] + arr[i - 3]
return arr[n]
s = solution()
print(s.tribonac... |
class Yo():
def __init__(self, name):
self.name = name
def say_name(self):
print('Yo {}!'.format(self.name))
| class Yo:
def __init__(self, name):
self.name = name
def say_name(self):
print('Yo {}!'.format(self.name)) |
"""
1. Clarification
2. Possible solutions
- dfs, bottom-up
- dfs, top-down
- bfs
3. Coding
4. Tests
"""
# 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
# T=O(n)... | """
1. Clarification
2. Possible solutions
- dfs, bottom-up
- dfs, top-down
- bfs
3. Coding
4. Tests
"""
class Solution:
def max_depth(self, root: TreeNode) -> int:
if not root:
return 0
if not root.left and (not root.right):
return 1
return 1 + max(self... |
# coding: utf8
""""""
VOICES = {
"mei-jia": "com.apple.speech.synthesis.voice.mei-jia",
"ting-ting": "com.apple.speech.synthesis.voice.ting-ting",
}
| """"""
voices = {'mei-jia': 'com.apple.speech.synthesis.voice.mei-jia', 'ting-ting': 'com.apple.speech.synthesis.voice.ting-ting'} |
class AlreadyFiredError(RuntimeError):
pass
class InvalidBoardError(RuntimeError):
pass
class InvalidMoveError(RuntimeError):
pass
| class Alreadyfirederror(RuntimeError):
pass
class Invalidboarderror(RuntimeError):
pass
class Invalidmoveerror(RuntimeError):
pass |
class Solution:
def canPermutePalindrome(self, s: str) -> bool:
x={}
k=0
for i in set(s):
x[i]=s.count(i)
for i,j in x.items():
if j%2!=0:
k=k+1
if k>1:
return False
return True
| class Solution:
def can_permute_palindrome(self, s: str) -> bool:
x = {}
k = 0
for i in set(s):
x[i] = s.count(i)
for (i, j) in x.items():
if j % 2 != 0:
k = k + 1
if k > 1:
return False
return True |
def test_user_creation(faunadb_client):
username = "burgerbob"
created_user = faunadb_client.create_user(
username=username, password="password1234"
)
assert created_user["username"] == username
all_users = faunadb_client.all_users()
assert len(all_users) == 1
| def test_user_creation(faunadb_client):
username = 'burgerbob'
created_user = faunadb_client.create_user(username=username, password='password1234')
assert created_user['username'] == username
all_users = faunadb_client.all_users()
assert len(all_users) == 1 |
'''
## Questions
### 154. [Find Minimum in Rotated Sorted Array II](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/)
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.... | """
## Questions
### 154. [Find Minimum in Rotated Sorted Array II](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/)
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.... |
"""
Demonstrates prompting a user to enter input using the keyboard.
This demonstrates two different ways to get the user's input
as a string and converts the input to an int-type.
The same thing can be done for floats by using the float function
instead of the int function.
"""
number1 = input("Enter the first numbe... | """
Demonstrates prompting a user to enter input using the keyboard.
This demonstrates two different ways to get the user's input
as a string and converts the input to an int-type.
The same thing can be done for floats by using the float function
instead of the int function.
"""
number1 = input('Enter the first number... |
class Base(object):
"""
Basic Session Entity is the base entity representing the data in thte session.
"""
def __init__(self, session_id, key, content):
self._session_id = session_id
self.key = key
self.content = content
@property
def session_id(self):
... | class Base(object):
"""
Basic Session Entity is the base entity representing the data in thte session.
"""
def __init__(self, session_id, key, content):
self._session_id = session_id
self.key = key
self.content = content
@property
def session_id(self):
return se... |
# "Unit GCD"
# Alec Dewulf
# April Long 2020
# Difficulty: Simple
# Concepts: Pigeonhole principle
"""
EXPLANATION
This problem becomes very simple if you notice that there are n//2 even numbers
and by pigeonhole principle each must be on a different day (they all share a
factor of two). Therefore there must be n//2... | """
EXPLANATION
This problem becomes very simple if you notice that there are n//2 even numbers
and by pigeonhole principle each must be on a different day (they all share a
factor of two). Therefore there must be n//2 days.
- If n is even each day will have two numbers a at i and a at i + 1.
- If n is odd each day w... |
#
# PySNMP MIB module CISCO-ATM-SERVICE-REGISTRY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ATM-SERVICE-REGISTRY-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:33:26 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python ... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, single_value_constraint, constraints_intersection, constraints_union) ... |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
class StopCondition:
def __init__(self, agent):
self.agent = agent
def check(self) -> bool:
raise NotImplementedError("Implemented by subclass")
class NeverStopCondition(StopCondition):
def __init__(self, agent):
super()._... | """
Copyright (c) Facebook, Inc. and its affiliates.
"""
class Stopcondition:
def __init__(self, agent):
self.agent = agent
def check(self) -> bool:
raise not_implemented_error('Implemented by subclass')
class Neverstopcondition(StopCondition):
def __init__(self, agent):
super()... |
# ------------------------------
# 144. Binary Tree Preorder Traversal
#
# Description:
# Given a binary tree, return the preorder traversal of its nodes' values.
# Example:
# Input: [1,null,2,3]
# 1
# \
# 2
# /
# 3
# Output: [1,2,3]
#
# Follow up: Recursive solution is trivial, could you do it ite... | class Solution(object):
def preorder_traversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
res = []
traverse = [root]
while traverse:
node = traverse.pop()
res.append(node.val)... |
def set_partitions(iterable, k=None):
"""
Yield the set partitions of *iterable* into *k* parts. Set partitions are
not order-preserving.
>>> iterable = 'abc'
>>> for part in set_partitions(iterable, 2):
... print([''.join(p) for p in part])
['a', 'bc']
['ab', 'c']
['b', 'ac']
... | def set_partitions(iterable, k=None):
"""
Yield the set partitions of *iterable* into *k* parts. Set partitions are
not order-preserving.
>>> iterable = 'abc'
>>> for part in set_partitions(iterable, 2):
... print([''.join(p) for p in part])
['a', 'bc']
['ab', 'c']
['b', 'ac']
... |
def is_anagram(first, second):
return sorted(list(first)) == sorted(list(second))
def main():
valid = 0
with open('day_4.in', 'r') as f:
for l in f.readlines():
split = l.strip().split(' ')
valid_passphrase = True
for start in range(0, len(split) - 1):
... | def is_anagram(first, second):
return sorted(list(first)) == sorted(list(second))
def main():
valid = 0
with open('day_4.in', 'r') as f:
for l in f.readlines():
split = l.strip().split(' ')
valid_passphrase = True
for start in range(0, len(split) - 1):
... |
# joint class definitions
class TripleJoint(object):
"""
Describing the relations and dowel placement between 3 beams.
"""
def ___init___(self, beam_set, type_def, loc_para = 0):
"""
Initialization of a triple-joint isinstance
:param beam_set: Which beams to conside... | class Triplejoint(object):
"""
Describing the relations and dowel placement between 3 beams.
"""
def ___init___(self, beam_set, type_def, loc_para=0):
"""
Initialization of a triple-joint isinstance
:param beam_set: Which beams to consider
:param type_def: ... |
APP_KEY = 'u5lo5mX6IzAyv9TQJZG5tErDP'
APP_SECRET = 'pJ294qcsbwcEty3ePPbGYVbD9sTL2J7dgC7BDdQ4KyoupmAxHS'
OAUTH_TOKEN = '1285969065996095488-WqwqIQPP69TovfaCISoY6DkWWgwajY'
OAUTH_TOKEN_SECRET = 'PIC1rTAs9Q9HD8zpGV7dMC5FMXpWmM5yn5WFhpJHt3li5'
## Your Telegram Channel Name ##
channel_name = 'uchihacommunity'
## Telegram A... | app_key = 'u5lo5mX6IzAyv9TQJZG5tErDP'
app_secret = 'pJ294qcsbwcEty3ePPbGYVbD9sTL2J7dgC7BDdQ4KyoupmAxHS'
oauth_token = '1285969065996095488-WqwqIQPP69TovfaCISoY6DkWWgwajY'
oauth_token_secret = 'PIC1rTAs9Q9HD8zpGV7dMC5FMXpWmM5yn5WFhpJHt3li5'
channel_name = 'uchihacommunity'
telegram_token = '1395164117:AAGmUsXuvPng9mwyWt... |
"""
cmd.do('stereo walleye; ')
cmd.do('set ray_shadow, off; ')
cmd.do('#draw 3200,2000;')
cmd.do('draw ${1:1600,1000}; ')
cmd.do('png ${2:aaa}.png')
cmd.do('${0}')
"""
cmd.do('stereo walleye; ')
cmd.do('set ray_shadow, off; ')
cmd.do('#draw 3200,2000;')
cmd.do('draw 1600,1000; ')
cmd.do('png aaa.png')
# Description: ... | """
cmd.do('stereo walleye; ')
cmd.do('set ray_shadow, off; ')
cmd.do('#draw 3200,2000;')
cmd.do('draw ${1:1600,1000}; ')
cmd.do('png ${2:aaa}.png')
cmd.do('${0}')
"""
cmd.do('stereo walleye; ')
cmd.do('set ray_shadow, off; ')
cmd.do('#draw 3200,2000;')
cmd.do('draw 1600,1000; ')
cmd.do('png aaa.png') |
"""
Lecture 10: Dynamic Programming
Alternating Coin Game
---------------------
Consider a game where you have a list
with an even number of coins with
positive integer values
v_0, v_1, ..., v_i, ..., v_(n - 1)
Each player alternates picking either the
leftmost or rightmost coin until there are
no coins left. Whichev... | """
Lecture 10: Dynamic Programming
Alternating Coin Game
---------------------
Consider a game where you have a list
with an even number of coins with
positive integer values
v_0, v_1, ..., v_i, ..., v_(n - 1)
Each player alternates picking either the
leftmost or rightmost coin until there are
no coins left. Whichev... |
"""
author : @akash kumar
github : https://github/Akash671
string fun:
string.replace(sub_old_string,new_sub_string,count)
string.count(your_string)
"""
def solve():
#n,m=map(int,input().split())
#n=int(input())
#a=list(map(int,input().split()[:n]))
#s=str(input())
#a,b=input().split()
s=str(input(... | """
author : @akash kumar
github : https://github/Akash671
string fun:
string.replace(sub_old_string,new_sub_string,count)
string.count(your_string)
"""
def solve():
s = str(input())
a = ''
n = len(s)
for i in range(2):
a += s[i]
if a == '</' and s[n - 1] == '>' and (s[2] != '/'):
... |
"""Timedelta formatter.
This script allows to format a given timedelta to a specific look.
This file can also be imported as a module and contains the following functions:
* format_timedelta - formats timedelta to hours:minutes:seconds
"""
def format_timedelta(td):
"""Format timedelta to hours:minutes:secon... | """Timedelta formatter.
This script allows to format a given timedelta to a specific look.
This file can also be imported as a module and contains the following functions:
* format_timedelta - formats timedelta to hours:minutes:seconds
"""
def format_timedelta(td):
"""Format timedelta to hours:minutes:second... |
def euler():
d = True
x = 1
while d == True:
x += 1
x_1 = str(x)
x_2 = f"{2 * x}"
x_3 = f"{3 * x}"
x_4 = f"{4 * x}"
x_5 = f"{5 * x}"
x_6 = f"{6 * x}"
if len(x_1) != len(x_6):
continue
sez1 = []
sez2 =... | def euler():
d = True
x = 1
while d == True:
x += 1
x_1 = str(x)
x_2 = f'{2 * x}'
x_3 = f'{3 * x}'
x_4 = f'{4 * x}'
x_5 = f'{5 * x}'
x_6 = f'{6 * x}'
if len(x_1) != len(x_6):
continue
sez1 = []
sez2 = []
sez3... |
# Given a string s, return the longest palindromic substring in s.
#
# Example 1:
# Input: s = "babad"
# Output: "bab"
# Note: "aba" is also a valid answer.
# lets first check if s a palindrome
def palindrome(s):
mid = len(s) // 2
if len(s) % 2 != 0:
if s[:mid] == s[:mid:-1]:
return s
... | def palindrome(s):
mid = len(s) // 2
if len(s) % 2 != 0:
if s[:mid] == s[:mid:-1]:
return s
elif s[:mid] == s[:mid - 1:-1]:
return s
return ''
def longest_palindrome(s):
if palindrome(s) == s:
return s
longest = s[0]
for i in range(0, len(s)):
for... |
def algo(load, plants):
row = 0
produced = 0
names = []
p = []
for i in range(len(plants)):
if row < len(plants):
battery = plants.iloc[row, :]
names.append(battery["name"])
if load > produced:
temp = load - produced
... | def algo(load, plants):
row = 0
produced = 0
names = []
p = []
for i in range(len(plants)):
if row < len(plants):
battery = plants.iloc[row, :]
names.append(battery['name'])
if load > produced:
temp = load - produced
if batt... |
# note the looping - we set the initial value for x =10 and when the first for loop is
# executed, it is evaluated at that time, so changing the variable x in the loop
# does not effect that loop. Now the next time that for loop is executed at that
# time the new value of x is used!
x = 10
for i in range(0,x):
pr... | x = 10
for i in range(0, x):
print(i)
x = 5
for i in range(0, x):
print(i)
x = 5
for i in range(0, x):
for j in range(0, x):
print(i, j)
x = 3 |
# -*- coding: utf-8 -*-
"""
Created on Thu May 23 10:05:43 2019
@author: Parikshith.H
"""
L = [10,20,30,40,50]
n = len(L)
print("number of elements =",n)
for i in range(n):
print(L[i])
# =============================================================================
# #output:
# number of elements = 5
# 10
# 20
#... | """
Created on Thu May 23 10:05:43 2019
@author: Parikshith.H
"""
l = [10, 20, 30, 40, 50]
n = len(L)
print('number of elements =', n)
for i in range(n):
print(L[i])
for elem in L:
print(elem)
a = [10, 20, 30]
b = [1, 2, 3]
for i in range(len(A)):
print(A[i] + B[i])
list = [1, 3, 5, 7, 9]
for (i, val) in e... |
# This is a variable concept
'''
a = 10
print(a)
print(type(a))
a = 10.33
print(a)
print(type(a))
a = "New Jersey"
print(a)
print(type(a))
'''
#a = input()
#print(a)
name = input("Please enter your name : ")
print("Your name is ",name)
print(type(name))
number = int(input("Enter your number : ")) #Explicit type ... | """
a = 10
print(a)
print(type(a))
a = 10.33
print(a)
print(type(a))
a = "New Jersey"
print(a)
print(type(a))
"""
name = input('Please enter your name : ')
print('Your name is ', name)
print(type(name))
number = int(input('Enter your number : '))
print('Your number is ', number)
print(type(number)) |
def vowels(word):
if (word[0] in 'AEIOU' or word[0] in 'aeiou'):
if (word[len(word) - 1] in 'AEIOU' or word[len(word) - 1] in 'aeiou'):
return 'First and last letter of ' + word + ' is vowel'
else:
return 'First letter of ' + word + ' is vowel'
else:
return 'Not a... | def vowels(word):
if word[0] in 'AEIOU' or word[0] in 'aeiou':
if word[len(word) - 1] in 'AEIOU' or word[len(word) - 1] in 'aeiou':
return 'First and last letter of ' + word + ' is vowel'
else:
return 'First letter of ' + word + ' is vowel'
else:
return 'Not a vow... |
"""
Author: Andreas Finkler
Created: 23.12.2020
"""
| """
Author: Andreas Finkler
Created: 23.12.2020
""" |
dist = []
for num in range(1, 1000):
if (num % 3 == 0) or (num % 5 == 0):
dist.append(num)
print(sum(dist))
| dist = []
for num in range(1, 1000):
if num % 3 == 0 or num % 5 == 0:
dist.append(num)
print(sum(dist)) |
add_init_container = [
{
'op': 'add',
'path': '/some/new/path',
'value': 'some-value',
},
]
| add_init_container = [{'op': 'add', 'path': '/some/new/path', 'value': 'some-value'}] |
def get_persistent_id(node_unicode_proxy, *args, **kwargs):
return node_unicode_proxy
def get_type(node, *args, **kwargs):
return type(node)
def is_exact_type(node, typename, *args, **kwargs):
return isinstance(node, typename)
def is_type(node, typename, *args, **kwargs):
return typename in ['Tran... | def get_persistent_id(node_unicode_proxy, *args, **kwargs):
return node_unicode_proxy
def get_type(node, *args, **kwargs):
return type(node)
def is_exact_type(node, typename, *args, **kwargs):
return isinstance(node, typename)
def is_type(node, typename, *args, **kwargs):
return typename in ['Transfo... |
age = 20
if age >= 20 and age == 30:
print('age == 30')
elif age >= 20 or age == 30:
print(' age >= 20 or age == 30')
else:
print('...') | age = 20
if age >= 20 and age == 30:
print('age == 30')
elif age >= 20 or age == 30:
print(' age >= 20 or age == 30')
else:
print('...') |
"""Default configuration settings"""
DEBUG = True
TESTING = False
# Logging
LOGGER_NAME = 'api-server'
LOG_FILENAME = 'api-server.log'
# PostgreSQL
USE_POSTGRESQL = True
POSTGRESQL_DATABASE = 'my_resume'
POSTGRESQL_USER = 'learn'
POSTGRESQL_PASSWORD = 'pass.word'
POSTGRESQL_HOST = 'localhost'
POSTGRESQL_PORT = '54... | """Default configuration settings"""
debug = True
testing = False
logger_name = 'api-server'
log_filename = 'api-server.log'
use_postgresql = True
postgresql_database = 'my_resume'
postgresql_user = 'learn'
postgresql_password = 'pass.word'
postgresql_host = 'localhost'
postgresql_port = '5432' |
class Solution(object):
def lastStoneWeight(self, stones):
"""
:type stones: List[int]
:rtype: int
"""
#helper function
def remove_largest():
#locate the index of the element with max value
heaviest_1_idx = stones.index(max(stones))
... | class Solution(object):
def last_stone_weight(self, stones):
"""
:type stones: List[int]
:rtype: int
"""
def remove_largest():
heaviest_1_idx = stones.index(max(stones))
(stones[heaviest_1_idx], stones[-1]) = (stones[-1], stones[heaviest_1_idx])
... |
def namta(p=1):
for i in range(1, 11):
print(p, "x", i, "=", p*i)
namta(5)
namta()
| def namta(p=1):
for i in range(1, 11):
print(p, 'x', i, '=', p * i)
namta(5)
namta() |
num_waves = 2
num_eqn = 2
# Conserved quantities
pressure = 0
velocity = 1
| num_waves = 2
num_eqn = 2
pressure = 0
velocity = 1 |
# Defining our main object of interation
game = [[0,0,0],
[0,0,0],
[0,0,0]]
#printing a column index, printing a row index, now #we have a coordinate to make a move, like c2
def game_board(player=0, row=1, column=1, just_display=False):
print(' 1 2 3')
if not just_display:
game[row... | game = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
def game_board(player=0, row=1, column=1, just_display=False):
print(' 1 2 3')
if not just_display:
game[row][column] = player
for (count, row) in enumerate(game, 1):
print(count, row)
game_board(just_display=True)
game_board(player=1, row=2, col... |
def function_2(x):
return x[0]**2 + x[1]**2
def numerical_diff(f, x):
h = 1e-4
return (f(x+h) - f(x-h)) / (2*h)
def function_tmp1(x0):
return x0*x0 + 4.0**2
def function_tmp2(x1):
return 3.0**2.0 + x1*x1
print(numerical_diff(function_tmp1, 3.0))
print(numerical_diff(function_tmp2, 4.0)) | def function_2(x):
return x[0] ** 2 + x[1] ** 2
def numerical_diff(f, x):
h = 0.0001
return (f(x + h) - f(x - h)) / (2 * h)
def function_tmp1(x0):
return x0 * x0 + 4.0 ** 2
def function_tmp2(x1):
return 3.0 ** 2.0 + x1 * x1
print(numerical_diff(function_tmp1, 3.0))
print(numerical_diff(function_t... |
"""
>>> motor = Motor()
>>> motor.acelerar()
>>> motor.velocidade
1
"""
# TODO: ajustar o doctest
class Carro:
def __init__(self, motor, direcao):
self.motor = motor
self.direcao = direcao
def calcular_velocidade(self):
return self.motor.velocidade
def acelerar... | """
>>> motor = Motor()
>>> motor.acelerar()
>>> motor.velocidade
1
"""
class Carro:
def __init__(self, motor, direcao):
self.motor = motor
self.direcao = direcao
def calcular_velocidade(self):
return self.motor.velocidade
def acelerar(self):
self.motor.a... |
JOBS_RAW = {
0: {
"Name": "Farmer"
},
1: {
"Name": "Baker"
},
2: {
"Name": "Lumberjack"
},
3: {
"Name": "Carpenter"
}
} | jobs_raw = {0: {'Name': 'Farmer'}, 1: {'Name': 'Baker'}, 2: {'Name': 'Lumberjack'}, 3: {'Name': 'Carpenter'}} |
class ApiException(Exception):
"""
Generic Catch-all for API Exceptions.
"""
status_code = None
def __init__(self, status_code=None, msg=None, *args, **kwargs):
self.status_code = status_code
super(ApiException, self).__init__(msg, *args, **kwargs)
| class Apiexception(Exception):
"""
Generic Catch-all for API Exceptions.
"""
status_code = None
def __init__(self, status_code=None, msg=None, *args, **kwargs):
self.status_code = status_code
super(ApiException, self).__init__(msg, *args, **kwargs) |
class AutowiringError(Exception):
"""
Error indicating autowiring of a function failed.
"""
...
| class Autowiringerror(Exception):
"""
Error indicating autowiring of a function failed.
"""
... |
def work(x):
x = x.split("cat ") #"cat " is a delimiter for the whole command dividing the line on two parts
f = open(x[1], "r") #the second part is a filename or path (in the future)
print(f.read()) #outputs the content of the specified file
| def work(x):
x = x.split('cat ')
f = open(x[1], 'r')
print(f.read()) |
def un_avg_pool(name, l_input, k, images_placeholder, test_images):
"""
the input is an 5-D array: batch_size length width height channels
"""
input_shape = l_input.get_shape().as_list()
batch_size = input_shape[0]
length = input_shape[1]
width = input_shape[2]
height = input_shape[3]
channels = inp... | def un_avg_pool(name, l_input, k, images_placeholder, test_images):
"""
the input is an 5-D array: batch_size length width height channels
"""
input_shape = l_input.get_shape().as_list()
batch_size = input_shape[0]
length = input_shape[1]
width = input_shape[2]
height = input_shape[3]
... |
num = int(input('Enter a number:'))
count = 0
while num != 0:
num //= 10
count += 1
print("Total digits are: ", count)
| num = int(input('Enter a number:'))
count = 0
while num != 0:
num //= 10
count += 1
print('Total digits are: ', count) |
#!/usr/bin/python
# -*- coding: utf-8 -*-
class Answer(object):
def __init__(self, p_id, username, datetime_from, content):
self.p_id = p_id
self.username = username
self.datetime_from = datetime_from
self.content = content
"""docstring for Answer"""
# def __init__(self, arg):
# super(Answer,... | class Answer(object):
def __init__(self, p_id, username, datetime_from, content):
self.p_id = p_id
self.username = username
self.datetime_from = datetime_from
self.content = content
'docstring for Answer' |
class MetodoDeNewton(object):
def __init__(self, f, f_derivada, x0, precisao=0.001, max_interacoes=15):
self.__X = [x0]
self.__interacoes = 0
while self.interacoes < max_interacoes:
self.__X.append(self.X[-1] - f(self.X[-1]) / f_derivada(self.X[-1]))
... | class Metododenewton(object):
def __init__(self, f, f_derivada, x0, precisao=0.001, max_interacoes=15):
self.__X = [x0]
self.__interacoes = 0
while self.interacoes < max_interacoes:
self.__X.append(self.X[-1] - f(self.X[-1]) / f_derivada(self.X[-1]))
self.__interacoe... |
S = input()
t = ''.join(c if c in 'ACGT' else ' ' for c in S)
print(max(map(len, t.split(' '))))
| s = input()
t = ''.join((c if c in 'ACGT' else ' ' for c in S))
print(max(map(len, t.split(' ')))) |
"""
Helper functions for both simulator and solver.
"""
__author__ = "Z Feng"
def pattern_to_similarity(pattern: str) -> int:
"""
Convert a pattern of string consisting of '0', '1' and '2' to a similarity rating.
'2': right letter in right place
'1': right letter in wrong place
'0': wrong letter
... | """
Helper functions for both simulator and solver.
"""
__author__ = 'Z Feng'
def pattern_to_similarity(pattern: str) -> int:
"""
Convert a pattern of string consisting of '0', '1' and '2' to a similarity rating.
'2': right letter in right place
'1': right letter in wrong place
'0': wrong letter
... |
# coding=utf-8
def point_inside(p, bounds):
return bounds[3] <= p[0] <= bounds[1] and bounds[0] <= p[1] <= bounds[2]
| def point_inside(p, bounds):
return bounds[3] <= p[0] <= bounds[1] and bounds[0] <= p[1] <= bounds[2] |
#Python Operators
x = 9
y = 3
#Arithmetic operators
print(x+y) #Addition
print(x-y) #Subtraction
print(x*y) #Multiplication
print(x/y) #Division
print(x%y) #Modulus
print(x**y) #Exponentiation
x = 9.191823
print(x//y) #Floor division
#Assignment operators
x = 9
x += 3
print(x)
x = 9
x -= 3
print(x)
x *= 3
print(x)
x... | x = 9
y = 3
print(x + y)
print(x - y)
print(x * y)
print(x / y)
print(x % y)
print(x ** y)
x = 9.191823
print(x // y)
x = 9
x += 3
print(x)
x = 9
x -= 3
print(x)
x *= 3
print(x)
x /= 3
print(x)
x **= 3
print(x)
x = 9
y = 3
print(x == y)
print(x != y)
print(x > y)
print(x < y)
print(x >= y)
print(x <= y) |
test = {
'name': 'lab1_p1a',
'suites': [
{
'cases': [
{
'code': r"""
>>> # It looks like your variable is not named correctly.
>>> # Remember, we want to save the value of pi as a variable.
>>> # What type should the variable be?
>>> # Start the v... | test = {'name': 'lab1_p1a', 'suites': [{'cases': [{'code': "\n >>> # It looks like your variable is not named correctly.\n >>> # Remember, we want to save the value of pi as a variable.\n >>> # What type should the variable be?\n >>> # Start the variable name with pi_\n >>>... |
"""This problem was asked by Google.
You're given a string consisting solely of (, ), and *. * can represent either a (, ), or an empty string.
Determine whether the parentheses are balanced.
For example, (()* and (*) are balanced. )*( is not balanced.
""" | """This problem was asked by Google.
You're given a string consisting solely of (, ), and *. * can represent either a (, ), or an empty string.
Determine whether the parentheses are balanced.
For example, (()* and (*) are balanced. )*( is not balanced.
""" |
# 2020.04.27
# https://leetcode.com/problems/add-two-numbers/submissions/
# works
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
def addTwoNumbers(... | class Listnode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def add_two_numbers(self, l1: ListNode, l2: ListNode) -> ListNode:
list1 = []
list1.append(l1.val)
mask = l1
while mask.next:
if mask.next:
list1.ap... |
KNOWN_PATHS = [
"/etc/systemd/*",
"/etc/systemd/**/*",
"/lib/systemd/*",
"/lib/systemd/**/*",
"/run/systemd/*",
"/run/systemd/**/*",
"/usr/lib/systemd/*",
"/usr/lib/systemd/**/*",
]
KNOWN_DROPIN_PATHS = {
"user.conf": [
"/etc/systemd/%unit%.d/*.conf", "/run/systemd/%unit%.d/... | known_paths = ['/etc/systemd/*', '/etc/systemd/**/*', '/lib/systemd/*', '/lib/systemd/**/*', '/run/systemd/*', '/run/systemd/**/*', '/usr/lib/systemd/*', '/usr/lib/systemd/**/*']
known_dropin_paths = {'user.conf': ['/etc/systemd/%unit%.d/*.conf', '/run/systemd/%unit%.d/*.conf', '/usr/lib/systemd/%unit%.d/*.conf', '/lib... |
"""Top-level package for NewlineCharacterConv."""
__author__ = """NewlineCharacterConv"""
__email__ = 'qin__xuan@yeah.net'
__version__ = '0.1.0'
| """Top-level package for NewlineCharacterConv."""
__author__ = 'NewlineCharacterConv'
__email__ = 'qin__xuan@yeah.net'
__version__ = '0.1.0' |
# Created by MechAviv
# ID :: [101000010]
# Ellinia : Magic Library
sm.warp(101000000, 4) | sm.warp(101000000, 4) |
class SubrectangleQueries:
def __init__(self, rectangle: List[List[int]]):
self.rectangle = rectangle
def updateSubrectangle(self, row1: int, col1: int, row2: int, col2: int, newValue: int) -> None:
self.row1, self.col1, self.row2, self.col2, self.newValue = row1, col1, row2, col2, newValue
... | class Subrectanglequeries:
def __init__(self, rectangle: List[List[int]]):
self.rectangle = rectangle
def update_subrectangle(self, row1: int, col1: int, row2: int, col2: int, newValue: int) -> None:
(self.row1, self.col1, self.row2, self.col2, self.newValue) = (row1, col1, row2, col2, newValu... |
# 2nd Solution
i = 4
d = 4.0
s = 'HackerRank '
a = int(input())
b = float(input())
c = input()
print(i+a)
print(d+b)
print(s+c) | i = 4
d = 4.0
s = 'HackerRank '
a = int(input())
b = float(input())
c = input()
print(i + a)
print(d + b)
print(s + c) |
{
'includes': [
'common.gyp',
'amo.gypi',
],
'targets': [
{
'target_name': 'amo',
'product_name': 'amo',
'type': 'none',
'sources': [
'<@(source_code_amo)',
],
'dependencies': [
]
... | {'includes': ['common.gyp', 'amo.gypi'], 'targets': [{'target_name': 'amo', 'product_name': 'amo', 'type': 'none', 'sources': ['<@(source_code_amo)'], 'dependencies': []}]} |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
MATH6005 Lecture 6. Functions Revision.
# =============================================================================
# Example: Scope of a variable
#
# The code below attempts to double the value of the 'my_salary' variable
# but FAILS. This is because within doub... | """
MATH6005 Lecture 6. Functions Revision.
# =============================================================================
# Example: Scope of a variable
#
# The code below attempts to double the value of the 'my_salary' variable
# but FAILS. This is because within double_value() the argument 'to_double'
# is called... |
def imprime_quadro(numeros):
print('.' * (len(numeros) + 2))
maior_numero = max(numeros)
numeros_traduzidos = []
for numero in numeros:
numeros_traduzidos.append(['|' if n < numero else ' ' for n in range(maior_numero)][::-1])
for linha in zip(*numeros_traduzidos):
print('.' + ''.join(linha) + '.')
print('.' ... | def imprime_quadro(numeros):
print('.' * (len(numeros) + 2))
maior_numero = max(numeros)
numeros_traduzidos = []
for numero in numeros:
numeros_traduzidos.append(['|' if n < numero else ' ' for n in range(maior_numero)][::-1])
for linha in zip(*numeros_traduzidos):
print('.' + ''.joi... |
"""
This function converts given hexadecimal number to decimal number
"""
def hexa_decimal_to_decimal(number: str) -> int:
# check if the number is a hexa decimal number
if not is_hexa_decimal(number):
raise ValueError("Invalid Hexa Decimal Number")
# convert hexa decimal number to decimal
... | """
This function converts given hexadecimal number to decimal number
"""
def hexa_decimal_to_decimal(number: str) -> int:
if not is_hexa_decimal(number):
raise value_error('Invalid Hexa Decimal Number')
decimal = 0
for i in range(len(number)):
decimal += int(number[i], 16) * 16 ** (len(num... |
#
a, b = 10, 10
print(a == b)
print(a is b)
print(id(a), id(b))
a1 = [1, 2, 3, 4]
b1 = [1, 2, 3, 4]
print(a1 == b1)
print(a1 is b1)
print(id(a1), id(b1))
| (a, b) = (10, 10)
print(a == b)
print(a is b)
print(id(a), id(b))
a1 = [1, 2, 3, 4]
b1 = [1, 2, 3, 4]
print(a1 == b1)
print(a1 is b1)
print(id(a1), id(b1)) |
total = 0
media = 0.0
for i in range(6):
num = float(input())
if num > 0.0:
total += 1
media += num
print('{} valores positivos'.format(total))
print('{:.1f}'.format(media/total))
| total = 0
media = 0.0
for i in range(6):
num = float(input())
if num > 0.0:
total += 1
media += num
print('{} valores positivos'.format(total))
print('{:.1f}'.format(media / total)) |
"""This file contains a function that returns the int that apears an odd number of times in a list of integers, the best practice solution was:
def find_it(seq):
for i in seq:
if seq.count(i)%2!=0:
return i
"""
def find_it(seq):
"""This func... | """This file contains a function that returns the int that apears an odd number of times in a list of integers, the best practice solution was:
def find_it(seq):
for i in seq:
if seq.count(i)%2!=0:
return i
"""
def find_it(seq):
"""This funct... |
# http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/JIS/JIS0201.TXT
JIS0201_map = {
'20' : 0x0020, # SPACE
'21' : 0x0021, # EXCLAMATION MARK
'22' : 0x0022, # QUOTATION MARK
'23' : 0x0023, # NUMBER SIGN
'24' : 0x0024, # DOLLAR SIGN
'25' : 0x0025, # PERCENT SIGN
'26' : 0x0... | jis0201_map = {'20': 32, '21': 33, '22': 34, '23': 35, '24': 36, '25': 37, '26': 38, '27': 39, '28': 40, '29': 41, '2A': 42, '2B': 43, '2C': 44, '2D': 45, '2E': 46, '2F': 47, '30': 48, '31': 49, '32': 50, '33': 51, '34': 52, '35': 53, '36': 54, '37': 55, '38': 56, '39': 57, '3A': 58, '3B': 59, '3C': 60, '3D': 61, '3E':... |
#it is collection of data and methods.
class gohul:
a=100
b=200
def func(self):
print("Inside function")
print(gohul.func(1))
object=gohul()
print(object.a)
print(object.b)
print(object.func())
object1=gohul()
print(object1.a)
| class Gohul:
a = 100
b = 200
def func(self):
print('Inside function')
print(gohul.func(1))
object = gohul()
print(object.a)
print(object.b)
print(object.func())
object1 = gohul()
print(object1.a) |
# Array
# An array is monotonic if it is either monotone increasing or monotone decreasing.
#
# An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j].
#
# Return true if and only if the given array A is monotonic.
#
#
#
# Example 1:
#
# In... | class Solution:
def is_monotonic(self, A):
"""
:type A: List[int]
:rtype: bool
"""
if A[0] < A[-1]:
is_increase = True
else:
is_increase = False
if isIncrease:
for i in range(1, len(A)):
if A[i] < A[i - 1]:
... |
class Solution:
"""
@param matrix: an integer matrix
@return: the length of the longest increasing path
"""
def longestIncreasingPath(self, matrix):
if not matrix or len(matrix) == 0 or len(matrix[0]) == 0:
return 0
n = len(matrix)
m = len(matrix[0])
long... | class Solution:
"""
@param matrix: an integer matrix
@return: the length of the longest increasing path
"""
def longest_increasing_path(self, matrix):
if not matrix or len(matrix) == 0 or len(matrix[0]) == 0:
return 0
n = len(matrix)
m = len(matrix[0])
lo... |
# -*- coding: utf-8 -*-
"""Top-level package for NeuroVault Collection Downloader."""
__author__ = """Chris Gorgolewski"""
__email__ = 'krzysztof.gorgolewski@gmail.com'
__version__ = '0.1.0'
| """Top-level package for NeuroVault Collection Downloader."""
__author__ = 'Chris Gorgolewski'
__email__ = 'krzysztof.gorgolewski@gmail.com'
__version__ = '0.1.0' |
class LandingPage:
@staticmethod
def get():
return 'Beautiful UI'
| class Landingpage:
@staticmethod
def get():
return 'Beautiful UI' |
class Peptide:
def __init__(self, sequence, proteinID, modification, mass, isNterm):
self.sequence = sequence
self.length = len(self.sequence)
self.proteinID = [proteinID]
self.modification = modification
self.massArray = self.getMassArray(mass)
self.totalResidueMass = self.getTotalResidueMass()
self.pm ... | class Peptide:
def __init__(self, sequence, proteinID, modification, mass, isNterm):
self.sequence = sequence
self.length = len(self.sequence)
self.proteinID = [proteinID]
self.modification = modification
self.massArray = self.getMassArray(mass)
self.totalResidueMass... |
def fatorial(n):
if n==1:
return n
return fatorial(n-1) * n
print(fatorial(5))
"""n = 5 --> ret = 1*2*3*4*5
n = 4 --> fatorial(4) = 1*2*3*4
n = 3 --> fatorial(3) = 1*2*3
n = 2 --> fatorial(2) = 1*2
n = 1 --> fatorial(1) = 1"""
print(fatorial(4))
| def fatorial(n):
if n == 1:
return n
return fatorial(n - 1) * n
print(fatorial(5))
'n = 5 --> ret = 1*2*3*4*5\nn = 4 --> fatorial(4) = 1*2*3*4\nn = 3 --> fatorial(3) = 1*2*3\nn = 2 --> fatorial(2) = 1*2\nn = 1 --> fatorial(1) = 1'
print(fatorial(4)) |
#CMPUT 410 Lab1 by Chongyang Ye
#This program allows add courses and
#corresponding marks for a student
#and count the average score
class Student:
courseMarks={}
name= ""
def __init__(self,name,family):
self.name = name
self.family = family
def addCourseMark(self, course, m... | class Student:
course_marks = {}
name = ''
def __init__(self, name, family):
self.name = name
self.family = family
def add_course_mark(self, course, mark):
self.courseMarks[course] = mark
def average(self):
grade = []
grade = self.courseMarks.values()
... |
{
"targets": [{
"target_name": "defaults",
"sources": [ ],
"conditions": [
['OS=="mac"', {
"sources": [
"src/defaults.mm",
"src/json_formatter.h",
"src/json_formatter.cc"
],
}]
],
'include_dirs': [
"<!@(node -p \"require('node-addon-a... | {'targets': [{'target_name': 'defaults', 'sources': [], 'conditions': [['OS=="mac"', {'sources': ['src/defaults.mm', 'src/json_formatter.h', 'src/json_formatter.cc']}]], 'include_dirs': ['<!@(node -p "require(\'node-addon-api\').include")'], 'libraries': [], 'dependencies': ['<!(node -p "require(\'node-addon-api\').gyp... |
#!/usr/bin/env python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
register_rule("agents/" + _("Agent Plugins"),
"agent_config:nvidia_gpu",
DropdownChoice(
title = _("Nvidia GPU (Linux)"),
help = _("This will deploy the agent plugin <tt>nvidia_gpu</tt> to collect GPU utilization values."),
... | register_rule('agents/' + _('Agent Plugins'), 'agent_config:nvidia_gpu', dropdown_choice(title=_('Nvidia GPU (Linux)'), help=_('This will deploy the agent plugin <tt>nvidia_gpu</tt> to collect GPU utilization values.'), choices=[(True, _('Deploy plugin for GPU Monitoring')), (None, _('Do not deploy plugin for GPU Monit... |
# -*- coding: utf-8 -*-
"""
Taken from Data Structures and Algorithms using Python
"""
def matrix_chain(d):
n = len(d) - 1
N =[[0]*n for i in range(n)]
for b in range(1,n):
for i in range(n-b):
j = i+b
N[i][j] = min(N[i][j]+N[k+1][j]+d[i]*d[k+1]*d[j+1] for k in range(i,j))
... | """
Taken from Data Structures and Algorithms using Python
"""
def matrix_chain(d):
n = len(d) - 1
n = [[0] * n for i in range(n)]
for b in range(1, n):
for i in range(n - b):
j = i + b
N[i][j] = min((N[i][j] + N[k + 1][j] + d[i] * d[k + 1] * d[j + 1] for k in range(i, j)))
... |
#!/usr/bin/env python
types = [
("bool", "Bool", "strconv.FormatBool(bool(*%s))", "*%s == false"),
("uint8", "Uint8", "strconv.FormatUint(uint64(*%s), 10)", "*%s == 0"),
("uint16", "Uint16", "strconv.FormatUint(uint64(*%s), 10)", "*%s == 0"),
("uint32", "Uint32", "strconv.FormatUint(uint64(*%s), 10)", ... | types = [('bool', 'Bool', 'strconv.FormatBool(bool(*%s))', '*%s == false'), ('uint8', 'Uint8', 'strconv.FormatUint(uint64(*%s), 10)', '*%s == 0'), ('uint16', 'Uint16', 'strconv.FormatUint(uint64(*%s), 10)', '*%s == 0'), ('uint32', 'Uint32', 'strconv.FormatUint(uint64(*%s), 10)', '*%s == 0'), ('uint64', 'Uint64', 'strco... |
"""# `//ll:driver.bzl`
Convenience function to select the C or C++ driver for compilation.
"""
def compiler_driver(ctx, toolchain_type):
driver = ctx.toolchains[toolchain_type].c_driver
for src in ctx.files.srcs:
if src.extension in ["cpp", "hpp", "ipp", "cl", "cc"]:
driver = ctx.toolchain... | """# `//ll:driver.bzl`
Convenience function to select the C or C++ driver for compilation.
"""
def compiler_driver(ctx, toolchain_type):
driver = ctx.toolchains[toolchain_type].c_driver
for src in ctx.files.srcs:
if src.extension in ['cpp', 'hpp', 'ipp', 'cl', 'cc']:
driver = ctx.toolchain... |
#!/usr/bin/env python
counts = dict()
mails = list()
fname = input("Enter file name:")
fh = open(fname)
for line in fh:
if not line.startswith("From "):
continue
# if line.startswith('From:'):
# continue
id = line.split()
mail = id[1]
mails.append(mail)
freq_mail = max(mails, k... | counts = dict()
mails = list()
fname = input('Enter file name:')
fh = open(fname)
for line in fh:
if not line.startswith('From '):
continue
id = line.split()
mail = id[1]
mails.append(mail)
freq_mail = max(mails, key=mails.count)
print(freq_mail, mails.count(freq_mail))
'\nfor x in mails:\n c... |
class OriginEPG():
def __init__(self, fhdhr):
self.fhdhr = fhdhr
def update_epg(self, fhdhr_channels):
programguide = {}
for fhdhr_id in list(fhdhr_channels.list.keys()):
chan_obj = fhdhr_channels.list[fhdhr_id]
if str(chan_obj.number) not in list(programgui... | class Originepg:
def __init__(self, fhdhr):
self.fhdhr = fhdhr
def update_epg(self, fhdhr_channels):
programguide = {}
for fhdhr_id in list(fhdhr_channels.list.keys()):
chan_obj = fhdhr_channels.list[fhdhr_id]
if str(chan_obj.number) not in list(programguide.key... |
class TrieNode:
def __init__(self):
self.children = {}
self.endOfString = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
currNode = self.root
for char in word:
if char not in currNode.children:
currN... | class Trienode:
def __init__(self):
self.children = {}
self.endOfString = False
class Trie:
def __init__(self):
self.root = trie_node()
def insert(self, word):
curr_node = self.root
for char in word:
if char not in currNode.children:
cu... |
def get_capabilities():
return [
"bogus_capability"
]
def should_ignore_response():
return True
| def get_capabilities():
return ['bogus_capability']
def should_ignore_response():
return True |
class ExportModuleToFile(object):
def __init__(self, **kargs):
self.moduleId = kargs["moduleId"] if "moduleId" in kargs else None
self.exportType = kargs["exportType"] if "exportType" in kargs else None
| class Exportmoduletofile(object):
def __init__(self, **kargs):
self.moduleId = kargs['moduleId'] if 'moduleId' in kargs else None
self.exportType = kargs['exportType'] if 'exportType' in kargs else None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.