content stringlengths 7 1.05M |
|---|
"""
Codemonk link: https://www.hackerearth.com/practice/algorithms/dynamic-programming/introduction-to-dynamic-programming-1/practice-problems/algorithm/once-upon-a-time-in-time-land/
In a mystical TimeLand, a person's health and wealth is measured in terms of time(seconds) left. Suppose a person there
has 24x60x60 = ... |
class TreeNode:
def __init__(self, data):
self.data = data
self.parent = None
self.children = []
self.__length = 0
def add_child(self, children):
self.__length += len(children)
for child in children:
child.parent = self
self.children.a... |
# Copyright (C) 2020-Present the hyssop authors and contributors.
#
# This module is part of hyssop and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
'''
File created: September 4th 2020
Modified By: hsky77
Last Updated: April 6th 2021 22:26:59 pm
'''
Version = '0.0.7'
|
class Extractor(object):
def __init__(self, transcript):
self.transcript = transcript
def get_location(self):
return "TBD"
def get_date(self):
return "TBD"
|
"""fglib -- Factor Graph Library.
The factor graph library (fglib) is a Python package
to simulate message passing on factor graphs.
Modules:
inference: Module for inference algorithms.
graphs: Module for factor graphs.
nodes: Module for nodes of factor graphs.
edges: Module for edges of factor graphs... |
class Car:
def __init__(self, speed_input, angle_input, direction, radius, target,brake):
self.speed = speed_input #float, speed input
self.angle = angle_input #integer, servomotor input
self.direction = direction #1 if right, -1 if left
self.radius = radius ... |
# 🚨 Don't change the code below 👇
age = input("What is your current age?")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
#Casts variable age as an integer
age = int(age)
#Computes years left to live to ease next calculations
years_remaining = (90 - age)
#Computes years, months, weeks and... |
def test_all_function(numeric_state):
state = numeric_state
state["subtracted"] = state["amount"] - state["amount"]
space = state.space[1]
all_events = space.all()
assert len(all_events) == 3 |
#input: data from communties_data.txt
#output: data useful for predictive analysis (ie: excluding first 5 attributes) in 2D Array
def clean_raw_data(data):
rows = (row.strip().split() for row in data)
leaveLoop = 0
cleaned_data = []
for row in rows:
tmp = [stat.strip() for stat in row[0].split(',')]
cleaned_dat... |
with open("testFile/read.txt") as file:
# print(len(file.read().strip().split()))
for line in file:
print(line.strip().split(","))
# r :只读 ,w:只写,文件若存在则清空内容,不存在则创建,a:追加,不会清空内容,r+ :读写模式
""""
r 以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。
rb 以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。
r+ 打开一个文件用于读写。文件指针将会放在文件的开头。
rb+ 以二进制格式打开一个文... |
marcador = 30 * '\033[1;34m=\033[m'
print(marcador)
l = float(input('Informe o primeiro lado'))
l2 = float(input('Informe o segundo lado'))
l3 = float(input('Informe o terceiro lado'))
if l + l2 > l3 and l + l3 > l2 and l2 + l3 > l:
print('As medidas \033[1;32mFORMAM\033[m um triângulo')
if l == l2 == l3:
... |
"""
entrada
distancia=>int=>km
salida
deuda por pagar
"""
km=int(input("distancia recorrida "))
if (km<300):
print("se cancela 50.000 ")
elif(km>=300) and (km<=1000):
total=(km-300)*30000+70000
print(" su deuda es de: "+str(total))
elif(km>1000):
total=(km-300)*9000+150000... |
"""
Starts a game against the computer
"""
# TODO |
#
# PySNMP MIB module Juniper-DS3-CONF (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-DS3-CONF
# Produced by pysmi-0.3.4 at Mon Apr 29 19:51:33 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... |
"""pessoa.py em 2021-03-01. Projeto pythonbirds.
"""
class Pessoa:
olhos = 2 # atributo default ou atributo de classe
def __init__(self, *filhos, nome=None, idade=35):
self.nome = nome
self.idade = idade
self.filhos = list(filhos)
def cumprimentar(self):
return f'Olá,... |
def newman_conway(num):
""" Returns a list of the Newman Conway numbers for the given value.
Time Complexity: O(n)
Space Complexity: O(n)
"""
if num == 0:
raise ValueError
if num == 1:
return '1'
if num == 2:
return '1 1'
sequence = [0, 1, 1]
for i ... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2019 Edward Lau <elau1004@netscape.net>
# Licensed under the MIT License.
#
__version__ = '0.1.0'
|
"""
1.Faça um Programa que mostre a mensagem "Alo mundo" na tela.
"""
print("Faça um Programa que mostre a mensagem 'Alo mundo' na tela.")
print("Olá mundo!")
|
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if len(matrix) == 0:
return False
n, m = len(matrix), len(matrix[0])
start, end = 0, n * m - 1... |
# -*- coding: utf-8 -*-
"""Custom exceptions."""
# Part of StackMUD (https://github.com/whutch/stackmud)
# :copyright: (c) 2020 Will Hutcheson
# :license: MIT (https://github.com/whutch/stackmud/blob/master/LICENSE.txt)
class AlreadyExists(Exception):
"""Exception for adding an item to a collection it is already ... |
expected_output = {
"controller_config": {
"group_name": "default",
"ipv4": "10.9.3.4",
"mac_address": "AAAA.BBFF.8888",
"multicast_ipv4": "0.0.0.0",
"multicast_ipv6": "::",
"pmtu": "N/A",
"public_ip": "N/A",
"status": "N/A",
},
"mobility_summa... |
'''
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
'''
# Write your code here
def right(a,b):
r=a
for... |
ESCAPE_CODE = "\033["
COLORS = {'black': 30, 'red': 31, 'green':32, 'yellow': 33, 'blue': 34, 'purple': 35, 'cyan': 36, 'white': 37}
BRIGHTS = {"bright "+color: value + 60 for color, value, in COLORS.items()}
TEXT_COLOR = {'reset': 0, **COLORS, **BRIGHTS}
TEXT_STYLE = {'reset': 0, 'no effect': 0, 'bold': 1, 'underline'... |
# Write a function to check if the array is sorted or not
arr = [1,2,3,5,9]
n = len(arr)
i = 0
def isSortedArray(arr,i, n):
if (i==n-1):
return True
if arr[i] < arr[i+1] and isSortedArray(arr,i+1,n):
return True
else:
return False
print(isSortedArray(arr,i,n))
|
dict = {
"__open_crash__": 'Crash save {} exists, do you want to recover it?',
"__about__": "Simple route designer using BSicon",
"__export_fail__": 'Failed to export {}',
"__open_fail__": 'Failed to open {}',
"__paste_no_valid_blocks__": "No valid blocks to paste",
"__paste_filter_invalid_block... |
def fact(n):
ans = 1
for i in range(1,n+1):
ans = ans*i
return ans
T = int(input())
while T:
n = input()
n = int(n)
print(fact(n))
T = T-1
|
"""
Definition of Interval.
class Interval(object):
def __init__(self, start, end):
self.start = start
self.end = end
"""
class Solution:
"""
@param A: An integer list
@param queries: An query list
@return: The result list
"""
def intervalSum(self, A, queries):
self.... |
BOARDS = {
'arduino' : {
'digital' : tuple(x for x in range(14)),
'analog' : tuple(x for x in range(6)),
'pwm' : (3, 5, 6, 9, 10, 11),
'use_ports' : True,
'disabled' : (0, 1) # Rx, Tx, Crystal
},
'arduino_mega' : {
'digital' : tuple(x for x in range(54)),
... |
# This code should store "codewa.rs" as a variable called name but it's not working.
# Can you figure out why?
a = "code"
b = "wa.rs"
name = a + b
def test():
assert name == "codewa.rs"
|
# @Title: 搜索二维矩阵 (Search a 2D Matrix)
# @Author: KivenC
# @Date: 2018-07-30 21:19:34
# @Runtime: 60 ms
# @Memory: N/A
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix:
... |
#brute force
T= int(input())
while T!=0:
T-=1
n = int(input())
if n>3:
k1=0
k2=0
value1 , value2 , value3 , value4 =0,0,0,0
'''
#---------------------------------------
value1 = 14*(n-1) + 20
#----------------------------------------
k1=n//2
k2 = n % 2
if k2 ==0:
#value2 = 28*(... |
class ZebrokNotImplementedError(NotImplementedError):
"""
Custom exception to be thrown when a derived class
fails to implement an abstract method of a base class
"""
pass
|
'''
pyatmos jb2008 subpackage
This subpackage defines the following functions:
JB2008_subfunc.py - subfunctions that implement the atmospheric model JB2008
jb2008.py - Input interface of JB2008
spaceweather.py
download_sw_jb2008 - Download or update the space weather file for JB2008 from https://sol.spacenvi... |
"""
백준 1016번 : 제곱 ㄴㄴ 수
에라토스테네스의 체 심화 응용
"""
min, max = map(int, input().split())
seive = [1 for _ in range(max-min+1)]
i = 2
while i**2 <= max:
mul = min // (i**2)
while mul * (i**2) <= max:
if 0 <= mul * (i**2) - min <= max-min:
seive[mul * (i**2) - min] = 0
mul += 1
i += 1
... |
class GameContainer:
def __init__(self, lowest_level, high_score, stat_diffs, points_available):
self.lowest_level = lowest_level
self.high_score = high_score
self.stat_diffs = stat_diffs
self.points_available = points_available
|
class Foo:
class Bar:
def baz(self):
pass
|
def main():
return "foo"
def failure():
raise RuntimeError("This is an error")
|
"""
Model Synoptic Module
"""
simple_tree_model_sklearn = (
"<class 'sklearn.ensemble._forest.ExtraTreesClassifier'>",
"<class 'sklearn.ensemble._forest.ExtraTreesRegressor'>",
"<class 'sklearn.ensemble._forest.RandomForestClassifier'>",
"<class 'sklearn.ensemble._forest.RandomForestReg... |
def lily_format(seq):
return " ".join(point["lilypond"] for point in seq)
def output(seq):
return "{ %s }" % lily_format(seq)
def write(filename, seq):
with open(filename, "w") as f:
f.write(output(seq))
|
print("Iterando sobre o arquivo")
with open("dados.txt", "r") as arquivo:
for linha in arquivo:
print(linha)
print("Fim do arquivo", arquivo.name)
|
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
sum = 0
def DFS(self,node: TreeNode, path: str):
if node is N... |
N=int(input())
count=0
for i in range(1,N+1):
if len(str(i))%2==1:count+=1
print(count) |
#
# PySNMP MIB module CXCFG-IPX-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CXCFG-IPX-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:32:22 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... |
#
# PySNMP MIB module RBN-ENVMON-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RBN-ENVMON-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:44:20 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... |
# -*- coding: utf-8 -*-
"""
Strukture za grafe in funkcije na njih.
V ocenah časovne zahtevnosti je n število vozlišč v grafu,
m število povezav v grafu,
d(u) = d+(u) število (izhodnih) sosedov vozlišča u,
d-(u) pa število vhodnih sosedov vozlišča u.
Pri tem predpostavljamo, da velja n = O(m)
(graf ima O(1) povezanih ... |
# https://www.codechef.com/problems/MNMX
for T in range(int(input())):
n,a=int(input()),list(map(int,input().split()))
print((n-1)*min(a))
# If order matters
# s=0
# for z in range(n-1):
# if(a[0]>=a[1]):
# s+=a[1]
# a.pop(0)
# else:
# s+=a[0]... |
class NoLastBookException (Exception):
pass
class OpenLastBookFileFailed (Exception):
pass
|
"""
Contains custom core exceptions
"""
class UnsupportedNews(Exception):
"""
Custom exception for raising when a news type is unsupported
"""
pass
|
fruta = []
fruta.append('Banana')
fruta.append('Tangerina')
fruta.append('uva')
fruta.append('Laranja')
fruta.append('Melancia')
for f,p in enumerate(fruta):
print(f'Na prateleira {f} temos {p}')
|
rows_count = int(input())
def get_snake_pos(matrix):
for i, row in enumerate(matrix):
if "S" in row:
j = row.index("S")
snake_pos = [i, j]
return snake_pos
def get_food_pos(matrix):
food_positions = []
for i, row in enumerate(matrix):
for j, _ in enume... |
#!python3
class Map:
"""
Map
A Map class.
"""
def __init__(self, map_list):
"""
Map(map_list ::= 2D list of MapObjects)
Example:
a = MapObject("Path", " ", True)
b = MapObject("Rock", "X", False)
map_list = [[a, a, a, a, a]
... |
#!/usr/bin/env python
# TODO: import the random module
# This function parses both the player
# and monster files
def parse_file(filename):
members = {}
file = open(filename,"r")
lines = file.readlines()
for line in lines:
name, diff = line.split(";")
members[name] = {"str": int(diff)... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/2/12 16:25
# @Author : Baimohan/PH
# @Site : https://github.com/BaiMoHan
# @File : setdefault.py
# @Software: PyCharm
cars = {'BMW': 8.5, 'BENS': 8.3, 'AUDI': 7.9}
print(cars.setdefault('PORSCHE', 9.2))
print(cars)
print(cars.setdefault('BMW', 4.5))... |
NUMBER_OF_ROWS = 8
NUMBER_OF_COLUMNS = 8
DIMENSION_OF_EACH_SQUARE = 64
BOARD_COLOR_1 = "#DDB88C"
BOARD_COLOR_2 = "#A66D4F"
X_AXIS_LABELS = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H')
Y_AXIS_LABELS = (1, 2, 3, 4, 5, 6, 7, 8)
SHORT_NAME = {
'R':'Rook', 'N':'Knight', 'B':'Bishop',
'Q':'Queen', 'K':'King', 'P':'Paw... |
def power(x, y, p) :
res = 1 # Initialize result
# Update x if it is more
# than or equal to p
x = x % p
if (x == 0) :
return 0
while (y > 0) :
# If y is odd, multiply
# x with result
if ((y & 1) == 1) :
res = (re... |
"""
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
"""
# back tracking
# Runtime: 40 ms, faster than 26.72% of Python3 online submissions for Generate P... |
nota1 = float(input('Digite a nota da 1ª avaliação= '))
nota2 = float(input('Digite a nota da 2ª avaliaçao= '))
media = (nota1+nota2)/2
print('A sua média é {:.2f}'.format(media)) |
class Solution:
def isPalindrome(self, s: str) -> bool:
l, r = 0, len(s) - 1
while(l < r):
while(l < r and s[l].isalnum() == False):
l+=1
while(l < r and s[r].isalnum() == False):
r-=1
if(s[l].lower() != s[r].lower()):
... |
class Solution:
def solve(self, nums):
if len(nums) <= 2: return 0
l_maxes = []
l_max = -inf
for num in nums:
l_max = max(l_max,num)
l_maxes.append(l_max)
r_maxes = []
r_max = -inf
for num in nums[::-1]:
r_max = max(r_ma... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
return self.swap(head)
def swap(self, head: ListNode) -> ListNode:
if head == None:
return ... |
#!/usr/bin/env python
# Created by Bruce yuan on 18-2-7.
class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
tmp = {}
max_ = 0
start = 0
for i in range(len(s)):
# ... |
def FermatPrimalityTest(number):
''' if number != 1 '''
if (number > 1):
''' repeat the test few times '''
for time in range(3):
''' Draw a RANDOM number in range of number ( Z_number ) '''
randomNumber = random.randint(2, number)-1
''' Test if a... |
# Using Array slicing in python to reverse arrays
# defining reverse function
def reversedArray(array):
print(array[::-1])
# Creating a Template Array
array = [1, 2, 3, 4, 5]
print("Current Array Order:")
print(array)
print("Reversed Array Order:")
reversedArray(array)
|
# -*- coding: utf-8 -*-
# author: ysoftman
# python version : 2.x 3.x
# desc : set 테스트
data = ['aaa', 'bbb', 'aaa', 'ccc']
print(list(data))
# set 은 중복 데이터를 제거한다.
set_data = set(data)
print(set_data)
# element 추가
set_data.add("lemon")
set_data.add("banana")
set_data.add("lemon") # 중복 추가 안된다.
print(set_data)
# elem... |
#Get a left position and a right
# iterative uses a loop
def is_palindrome(string):
left_index = 0
right_index = len(string) - 1
#repeat, or loop
while left_index < right_index:
#check if dismatch
if string[left_index] != string[right_index]:
return False
#move to th... |
#!/usr/bin/env python3
def char_frequency(filename):
"""
Counts the frequency of each character in the given file.
"""
# First try to open the file
try:
f = open(filename)
# code in the except block is only executed if one of the instructions in the try block raise an error of the match... |
def distributeCandies(self, candies: int, num_people: int) -> List[int]:
r = [0 for _ in range(num_people)]
i = 0
c = 1
while candies != 0:
if i > num_people - 1:
i = 0
if c > candies:
r[i] += candies
break
r[i] += c
candies -= c
... |
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
FIRST_LETTER = LETTERS[0]
def get_sequence(column, count, step=1):
column = validate(column)
count = max(abs(count), 1)
sequence = []
if column:
sequence.append(column)
count = count - 1
for i in range(count):
previous ... |
def evalRec(env, rec):
"""hearing_loss_genes"""
return (len(set(rec.Symbol) &
{
'ABCD1',
'ABHD12',
'ABHD5',
'ACOT13',
'ACTB',
'ACTG1',
'ADCY1',
'ADGRV1',
'ADK',
'AIFM1',
'A... |
# Copyright 2017 The Forseti Security Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ap... |
# ToDo: Make it configurable
DEFAULT_PARAMS = {
"os_api": "23",
"device_type": "Pixel",
"ssmix": "a",
"manifest_version_code": "2018111632",
"dpi": 420,
"app_name": "musical_ly",
"version_name": "9.1.0",
"is_my_cn": 0,
"ac": "wifi",
"update_version_code": "2018111632",
"chann... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
定制类
__getattr__
"""
class Student(object):
def __init__(self):
self._name = 'Walker'
def __getattr__(self, item):
if item == 'score':
return 99
raise AttributeError('Student object has no attribute %s' % item)
s = Stude... |
def Ispalindrome(usrname):
return usrname==usrname[::-1]
def main():
usrname=input("Enter the String :")
#temp=usrname[::-1]
if Ispalindrome(usrname):
print("String %s is palindrome"%(usrname))
else:
print("String %s is not palindrome"%(usrname))
if __name__ == '__main__':
main()
|
# Advent of Code 2015
#
# From https://adventofcode.com/2015/day/3
#
inputs = [data.strip() for data in open('../inputs/Advent2015_03.txt', 'r')][0]
move = {'^': 0 + 1j, ">": 1, "v": 0 - 1j, "<": -1}
def visit(inputs):
position = 0 + 0j
visited = {position}
for x in inputs:
position = position +... |
def bisect(f, a, b, tol=10e-5):
"""
Implements the bisection root finding algorithm, assuming that f is a
real-valued function on [a, b] satisfying f(a) < 0 < f(b).
"""
lower, upper = a, b
while upper - lower > tol:
middle = 0.5 * (upper + lower)
# === if root is between lower a... |
# -*- coding: utf-8 -*-
"""Products are standard objects that Loaders add to the data store."""
# For now Products are simple dictionaries.
class Product(dict):
"""Standardised product data."""
pass |
age1 = 12
age2 = 18
print("age1 + age2")
print(age1 + age2)
print("age1 - age2")
print(age1 - age2)
print("age1 * age2")
print(age1 * age2)
print("age1 / age2")
print(age1 / age2)
print("age1 % age2")
print(age1 % age2)
sent1 = "Today is a beautiful day"
firstName = "Marlon"
lastName = "Monzon"
print(firstName + " "... |
a = input()
s = [int(x) for x in input().split()]
ans = [str(x) for x in sorted(s)]
print(' '.join(ans))
|
"""
백준 21591번 : Laptop Sticker
"""
a, b, c, d = map(int, input().split())
if a-2 >= c and b-2 >= d:
print(1)
else:
print(0) |
# Equations (c) Baltasar 2019 MIT License <baltasarq@gmail.com>
class TDS:
def __init__(self):
self._vbles = {}
def __iadd__(self, other):
self._vbles[other[0]] = other[1]
return self
def __getitem__(self, item):
return self._vbles[item]
def __setitem__(self, item, v... |
x = int(input("enter percentage\n"))
if(x>=65):
print("Excellent")
elif(x>=55 and x<65):
print("Good")
elif(x>=40 and x<55):
print("Fair")
else:
print("Failed")
|
WORK_PATH = "/tmp/posts"
PORT = 8000
AUTHOR = "@asadiyan"
TITLE = "fsBlog"
DESCRIPTION = "<h3></h3>"
|
"""
written and developed by Daniel Temkin
please refer to LICENSE for ownership and reference information
"""
|
def TwosComplementOf(n):
if isinstance(n,str) == True:
binintnum = int(n)
binmun = int("{0:08b}".format(binintnum))
strnum = str(binmun)
size = len(strnum)
idx = size -1
while idx >= 0:
... |
# pylint: skip-file
# pylint: disable=too-many-instance-attributes
class GcloudComputeZones(GcloudCLI):
''' Class to wrap the gcloud compute zones command'''
# pylint allows 5
# pylint: disable=too-many-arguments
def __init__(self, region=None, verbose=False):
''' Constructor for gcloud resour... |
class Stack:
def __init__(self, *objects):
self.stack = []
if len(objects) > 0:
for obj in objects:
self.stack.append(obj)
def push(self, *objects):
for obj in objects:
self.stack.append(obj)
def pop(self, obj):
... |
class CalcError(Exception):
def __init__(self, error):
self.message = error
super().__init__(self.message)
|
#Binary to Decimal conversion
def binDec(n):
num = int(n);
value = 0;
base = 1;
flag = num;
while(flag):
l = flag%10;
flag = int(flag/10);
print(flag);
value = value+l*base;
base = base*2;
return value
num = input();
a = binDec(num);
print(a)
|
{
'targets': [
{
'target_name': 'lb_shell_package',
'type': 'none',
'default_project': 1,
'dependencies': [
'lb_shell_contents',
],
'conditions': [
['target_arch=="android"', {
'dependencies': [
'lb_shell_android.gyp:lb_shell_apk',
... |
# PRINT OUT A WELCOME MESSAGE.
print('Welcome to Food Funhouse!')
# LOOP UNTIL THE USER CHOOSES TO EXIT.
order_total_in_dollars_and_cents = 0.0
while True:
# PRINT OUT THE MENU OPTIONS.
print('1. Cheeseburger - $5.50')
print('2. Pizza - $5.00')
print('3. Taco - $3.00')
print('4. Cookie - $1.99')
... |
# Simple Calculator
def calculate(x,y,operator):
if operator == "*":
result = float(x * y)
print(f"The answer is {result} ")
elif operator == "/":
result = float(x / y)
print(f"The answer is {result} ")
elif operator == "+":
result = float(x + y)
print(f"The ... |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... |
# Outputs string representation of a unicode hex representation
def uc(hex):
return chr(int(hex))
'''CONSONANTS. Format: Place_Manner_Voicing;
Place:
L=labial, LD=labiodental, D=dental, A=alveolar, R=retroflex,
PA=postalveolar, P=palatal, V=velar, U=uvular, PH=pharyngeal, G=glottal;
Mann... |
#Faça um programa que mostre a tabuada de vários números, um de cada vez, para cada valor digitado pelo usuário. O programa será
#interrompido quando o número solicitado for negativo.
tabuada = 1
c = 1
while True:
tabuada = int(input('Quer ver a tabuada de que valor: '))
while c < 11 and tabuada > 0:
... |
# 8.2) find path to robot in a c*r grid, robot can only move right and down.
def find_path(c, r, off_limits):
path = []
move_robot(0, 0, c, r, off_limits, path)
return path
def move_robot(x, y, c, r, off_limits, path):
if x == (c - 1) and y == (r - 1):
return
elif [x + 1, y] not in off_li... |
test_cases = int(input().strip())
for t in range(1, test_cases + 1):
s = input().strip()
stack = []
bracket = {'}': '{', ')': '('}
result = 1
for letter in s:
if letter == '{' or letter == '(':
stack.append(letter)
elif letter == '}' or letter == ')':
if not ... |
# Tristan Protzman
# Created 2019-02-07
# Holds the note patters
class Pattern:
def __init__(self, beats, subdivisions, notes):
self.beats = beats # How many beats per measure
self.subdivisions = subdivisions # How many divisions per beat
self.divisions = self.beats * self.subdivisions ... |
class Chat:
START_TEXT = """This is a Telegram Bot to Mux subtitle into a video
<b>Send me a Telegram file to begin</b>
/help for more details..
Credits :- @mohdsabahat
"""
HELP_USER = "??"
HELP_TEXT ="""<b>Welcome to the Help Menu</b>
1.) Send a Video file or url.
2.) Send a subtitle file (ass ... |
# To Find an algorithm for giving selected attributes in a formal concept analysis acc to given conditions
a,arr= [],[]
start,end = 3,5
with open('Naive Algo/Input/test2.txt') as file:
for line in file:
line = line.strip()
for c in line:
if c != ' ':
# print(int(c))
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.