content stringlengths 7 1.05M |
|---|
device = '/dev/sandschreiber'
gcode_directory = u'gcodes'
listen = '0.0.0.0'
port = 8080
|
# Lesson 1
def iterative_factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
print(iterative_factorial(5))
# "Recursion" is the act of calling a function from within itself. Some functions naturally work better recursively.
# Recursion is easier to work out if you write... |
'''
Counting inversions. An inversion in an array a[] is a pair of entries
a[i] and a[j] such that i < j but a[i] > a[j]. Given an array,
design a linearithmic algorithm to count the number of inversions.
'''
def count_inversions(arr):
N = len(arr)
aux = arr.copy()
def count_and_sort(arr):
count ... |
a = int(input())
for _ in range(a):
greater = []
smaller = []
temp = input().strip()
while not temp:
temp = input().strip()
x, y = [int(x) for x in temp.split()]
for __ in range(x-1):
t = int(input())
if t > y:
greater.append(t)
else:
small... |
#Calculator using python
#Nader Mahbub Lhan Nabil
#naderkhan2507@gmail.com
welmassage = "[PyCalculator by Nader Mahbub Khan}"
print(welmassage)
print("=====================================================================")
print("INPUT SECTION")
print("============================================================... |
data = []
with open("./test_sampled.txt") as f:
for line in f:
data.append(line.strip())
index = 0
while index < 4000:
with open("test_sampled_" + str(index) + "_" + str(index+500) + ".txt", "w") as wf:
for d in range(index, index+500):
wf.write(data[d]+'\n')
index += 500
|
class Validator():
n = None
k = None
h = None
def are_valid_parameters(self, args):
return self.validate_arguments(args) and \
self.validate_file_name(args[1]) and \
self.validate_instance_no(args[2]) and \
self.validate_param_h(args[3])
def par... |
EGL_PBUFFER_BIT = 0x0001
EGL_PIXMAP_BIT = 0x0002
EGL_WINDOW_BIT = 0x0004
EGL_VG_COLORSPACE_LINEAR_BIT = 0x0020
EGL_VG_ALPHA_FORMAT_PRE_BIT = 0x0040
EGL_MULTISAMPLE_RESOLVE_BOX_BIT = 0x0200
EGL_SWAP_BEHAVIOR_PRESERVED_BIT = 0x0400
EGL_OPENGL_ES_BIT = 0x0001
EGL_OPENVG_BIT = 0x0002
EGL_OPENGL_ES2_BIT = 0x0004
EGL_OPENGL_... |
# name:afunc
def afunc():
print("afunc called")
return 1
|
"""
7.1 Write a program that prompts for a file name, then opens that file and reads through the file, and print the contents of the file in upper case.
Use the file words.txt to produce the output below.
You can download the sample data at http://www.py4e.com/code3/words.txt
"""
fname = input("Enter file name: ")
... |
"""The quick sort algorithm."""
def quicksort(unsorted, low=0, high=False):
"""Quick sort a list."""
if len(unsorted) < 2:
return unsorted
if high is False:
high = len(unsorted) - 1
if low < high:
swapper = swap(unsorted, low, high)
quicksort(unsorted, low, swapper - ... |
class EllysSubstringSorter:
def getMin(self, S, L):
m = "Z" * len(S)
for i in xrange(len(S) - L + 1):
s = S[:i] + "".join(sorted(S[i : i + L])) + S[i + L :]
m = min(m, s)
return m
|
def find_superbubble(G, G_rev, s):
queue = set([s])
labels = {}
while True:
v = queue.pop()
labels[v] = "visited"
v_children = list(G.neighbors(v))
if len(v_children) == 0:
return False, "tip"
for u in v_children:
if u == s:
... |
# -*- coding: utf-8 -*-
def main():
n, m = list(map(int, input().split()))
a = [int(input()) for _ in range(m)]
threads = dict()
used_thread = [False for _ in range(n)]
for index, ai in enumerate(a, 1):
threads[ai] = index
for thread_number, order in sorted(threads.items(... |
"""
@no 22
@name Generate Parenthesis
"""
class Solution:
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
ans = []
self.test('', 0, 0, ans, n)
return ans
def test(self, string, left_num, right_num, ans, n):
if len(string) ... |
'''
Find the Access Codes
=====================
In order to destroy Commander Lambda's LAMBCHOP doomsday device, you'll need access to it.
But the only door leading to the LAMBCHOP chamber is secured with a unique lock system whose
number of passcodes changes daily. Commander Lambda gets a report every day that incl... |
rainfall = [68, 58, 0, 99, 200, 39, 73, 43, 68, 0, 19]
min_rainfall = min(rainfall)
max_rainfall = max(rainfall)
average_rainfall = sum(rainfall) / len(rainfall)
print('minimum rainfal:', min_rainfall)
print('maximum rainfal:', max_rainfall)
print('average rainfall:', average_rainfall)
print(sorted(rainfall,reverse=T... |
def soma_listas(l1, l2):
saida = []
for i, j in zip(l1, l2):
saida.append(i+j)
return saida
def soma_listas2(l1, l2):
return [i+j for i, j in zip(l1, l2)]
|
#Los barcos se sitúan en una línea y solo pueden estar en horizontal.
#Se situarán: 1 portaaviones (3 cuadros); 2 cruceros (2 cuadros); 3 destructores (1 cuadro).
#Longitud del mapa: 25 cuadrados.
#Jugador GANA si hunde todos los barcos antes de 15 tiradas.
#Jugador PIERDE si llega a 15 tiradas y no ha undido todos los... |
#! /usr/bin/python
ctr=1
while ctr<1000:
pass
ctr |
__author__ = 'Chetan'
class Model(object):
def logic(self):
data = 'Got it!'
print("Model: Crunching data as per business logic")
return data
class View(object):
def update(self, data):
print("View: Updating the view with results: ", data)
class Controller(object):
def __i... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 7 15:14:06 2020
@author: NOTEBOOK
"""
#This program calculats a salesperson's pay
def main():
try:
#Get salesperson's monthly sales
sales = get_sales()
#Get amount of advanced pay
advance = advanced_pay()
#Determine comissi... |
print('{:=^40}'.format('CLEYTON SUPERMERCADOS'))
valor = float(input('Digite o valor a ser pago: '))
tipo = str(input('Cartão ou dinhero/cheque: ')).lower().strip()
if tipo == 'cartão' or tipo == 'cartao':
parcelas = int(input('Quantas vezes no cartão: '))
if parcelas == 1:
apagar = valor - ((valor * 5... |
"""
Providers for PureScript.
"""
PureScriptModuleInfo = provider(
doc = "Contains information about a PureScript module",
fields = {
"deps": "A depset of other PureScript modules for this module's dependencies.",
"info": """
A struct containing information about this module.
Has the following... |
print("Введите 3 числа")
a1 = int(input())
a2 = int(input())
a3 = int(input())
b1 = a1 + a2
b2 = b1 / a3
print("%.2f" % b2) |
n = int(input())
m = int(input())
if (n+m)%2 == 1:
print(0)
else:
print(1)
|
# Crear una funcion que permita ingresar al usuario
#Numero enteros...y strings...
# 1- print -> imprime la lista que se fue cargando hasta el momento...
# 2- append a -> siendo a numero entero
# 3- remove b -> siendo b numero entero
# 4- sort
# 5- reverse
# 6- insert c d -> siendo ambos numeros enteros, c el indice y ... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
##############################################
# File Name: tools.py
# Author: Xuhao Du
# Email: duxuhao88@gmail.com
##############################################
def readlog(fn,score):
"""read the log and export the selected features combination as lost
Args:
... |
def s(a, b):
res = 0
for i in xrange(1,a):
res += i**b
return res
def t(a, b):
return a**(b+1) |
class QcValidationResult:
def __init__(self, value: str, passed_qc: bool):
self.value = value
self.passed_qc = passed_qc
|
def B():
n , k = map(int,input().split())
s = [int(x) for x in input().split()]
ans = [-1]*n
color = dict()
for i in range(k):
ans[i]=i+1
color[i+1] = [s[i]]
for i in range(n):
if(ans[i]==-1):
for c in color:
if(s[i] not in color[c]):
ans[i] = c
color[c].append(s[i])
break
if(-1... |
# coding: utf-8
# Contains 15 of IMDB's 250 most popular films of all time, as of 2016,
# from here: http://www.imdb.com/chart/top
IMDBData = {
"Zootopia": {
"Stars": ["Ginnifer Goodwin", "Jason Bateman", "Idris Elba"],
"Rating": 8.1,
"Genre": "Animation",
"Year": 2016,
"URL ... |
UNDERSCORE_NOT_SUPORRTED_ERROR = 'Column names cannot contain `_` symbol'
SPACE_NOT_SUPORRTED_ERROR = 'Column names should not have a space'
def SETUP_PARAMETER_MISSING(paremeter):
return f"The '{paremeter}' is required!"
def DATA_TYPE_ERROR(method):
return f"Parameter passed into method `{method}` must be of type ... |
class DashboardChart:
def __init__(self, name, chart=None, datafn=None):
self.name = name
self.chart = chart
self.datafn = datafn
self.state = {}
def get_chart(self, force):
if self.datafn is not None:
chart, new_state = self.datafn(self.state, True)
... |
# Event: LCCS Python Fundamental Skills Workshop
# Date: Dec 2018
# Author: Joe English, PDST
# eMail: computerscience@pdst.ie
# Purpose: A program to demonstrate how to build a dictionary
# Version 2b. A dictionary to store multiple results for a student
results = {}
name = input("Enter student name: ")
re... |
# uninhm
# https://codeforces.com/contest/279/problem/B
# two pointers
n, t = map(int, input().split())
a = list(map(int, input().split()))
answer = 0
count = 0
suma = 0
i = 0
last = 0
while i < n:
if suma + a[i] <= t:
suma += a[i]
count += 1
i += 1
else:
answer = max(answer,... |
# T https://leetcode-cn.com/contest/weekly-contest-112/problems/minimum-increment-to-make-array-unique/
class Solution(object):
"""
A -> res
A[0] == res[0]
A[2] > res[2]
A[6] < res[6]
"""
# @hetang
def minIncrementForUnique(self, A): # A: 1 3 5 7 7 3 9
... |
# SPDX-License-Identifier: MIT
"""
Files related to ROS for the autonomy_toolkit package
"""
|
def get_longest_common_subsequence(s1, s2):
# Source: https://rosettacode.org/wiki/Longest_common_subsequence#Dynamic_Programming_8
lengths = [[0 for j in range(len(s2) + 1)] for i in range(len(s1) + 1)]
# row 0 and column 0 are initialized to 0 already
for i, x in enumerate(s1):
for j, y in en... |
# بسم الله الرحمن الرحيم
class Human:
def __init__(self, name):
self.name = name
def my_fn():
print(f'الحمد لله') |
# coding=utf-8
class Extractor(object):
"""
Извлечение из текста ключевых слов (в виде списка токенов) в соответствии с поданной IOB-последовательностью.
Если аргумент nested установлен в True, то извлекаются еще и вложенные тёрмы.
Например, вместе с "функциональный язык программирования" извлекаются "... |
teste = []
teste.append('Gustavo')
teste.append(40)
galera = []
galera.append(teste[:])
teste[0] = 'Maria'
teste[1] = 22
galera.append(teste[:])
print(galera)
# print(teste)
|
'''
# NEW app:
0. Move app inside project dir
1. Add the app in settings.py (INSTALLED_APPS)
2. Create urls.py with empty `urlpatterns` inside the app
3. Include app's urls.py into project urls.py
'''
|
nome = input('Qual seu nome ? ')
print(f'Nome do usuario {nome} \n'
f'Tipo do dado {type(nome)}')
idade = int(input('Qual sua idade? '))
print(f'Idade do usuario {idade} \n'
f'Tipo de dado {type(idade)}')
altura = float(input('Qual sua altura? '))
print(f'A altura do usuario e {altura}\n'
f'O tip... |
i = 0 ; sum =0
list = [1,2,3,4,5,6,7,8,9]
for num in list :
sum = sum + i
i = i + 1
print("the sum of list is : ", sum )
|
def getcount(R,L):
if len(R) == 0 or len(L) == 0:
temp = 0
elif len(R) - len(L) == 0:
temp = min(len(R),len(L)) * 2
else:
temp = min(len(R),len(L)) * 2
return temp
def getMaxDeletions(s):
# Write your code here
U = []
D = []
L = []
R = []
for element in ... |
load("//scala:scala_cross_version.bzl", "extract_major_version")
def _default_scala_version():
"""return the scala version for use in maven coordinates"""
return "2.12.11"
def _store_config(repository_ctx):
scala_version = repository_ctx.os.environ.get(
"SCALA_VERSION",
repository_ctx.attr... |
class DNSSeed(object):
def __init__(self):
""" @TODO:
Implement DNS SEED
"""
pass
|
#find the highest and the second highest number in a array
l = [5,5,5,5,5,5,6,5,5,5]
mx = 0
mxt = 0
for i in l:
if i > mx :
mxt = mx
mx = i
else:
if i> mxt and i!=mx :
mxt = i
print(mx,mxt) |
# Although it can't AC leetcode test, it's definitely right. However, its pattern may be not as obvious as the one that can AC
def grayCode(n):
res = [0]
seed = 1
for i in range(n - 1):
res += [seed, 3 * seed]
seed = seed << 1
for j in range((seed << 1) - len(res)):
res.append(r... |
def remove_consecutive_duplicates(s):
words = s.split()
return " ".join(set(words))
print(remove_consecutive_duplicates('alpha beta beta gamma gamma gamma delta alpha beta beta gamma gamma gamma delta'))
|
#!/usr/lib/python2.7
#Group member: Haonan Li
def reverse(read):
reverse_read = ""
read = read[::-1] #reverse the read
# get comlimentary read
for i in range(len(read)):
if read[i] == 'A':
reverse_read += 'T'
elif read[i] == 'T':
reverse_read += 'A'
eli... |
"""
给你一个整数数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。
返回滑动窗口中的最大值。
示例 1:
输入:nums = [1,3,-1,-3,5,3,6,7], k = 3
输出:[3,3,5,5,6,7]
解释:
滑动窗口的位置 最大值
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 ... |
n, q = map(int, input().split())
road = [list(map(int, input().split())) for i in range(n - 1)]
queries = [list(map(int, input().split())) for i in range(q)]
edges = [[] for i in range(n + 1)]
for i in road:
edges[i[0]].append(i[1])
edges[i[1]].append(i[0])
stack = [1]
inf = 10**5
d = [-1 for i in range(n + 1)]... |
"""
File rangetest.py: function decorator that performs range-test
validation for arguments passed to any function or method.
Arguments are specified by keyword to the decorator. In the actual
call, arguments may be passed by position or keyword, and defaults
may be omitted. See rangetest_test.py for example use cases.... |
"""
C200B40A82 finds the sum of 1 and 2, resulting in the value 3.
04005AC33890 finds the product of 6 and 9, resulting in the value 54.
880086C3E88112 finds the minimum of 7, 8, and 9, resulting in the value 7.
CE00C43D881120 finds the maximum of 7, 8, and 9, resulting in the value 9.
D8005AC2A8F0 produces 1, because ... |
def migratoryBirds(arr):
birds = [0,0,0,0,0]
for obj in arr:
birds[obj-1] += 1
return birds.index(max(birds)) + 1 |
##########################################################################################################
## File created on 31-03-2016 to be used in creating waypoint mission file for Pixhawk FC ##
## By Naitik Shukla fir ISS-Drone ##
## Sample file taken from http://qgroundcontrol.org/mavlink/waypoint_proto... |
# python3
"""
Given a non-empty array containing only positive integers,
find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
https://leetcode.com/problems/partition-equal-subset-sum/
"""
"""
строим несколько матриц
рассматриваем все рюкзаки для всех чисел
для... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution(object):
def traversal(self, lst, root):
if root is None:
return
self.traversal(... |
# Kількість паліндромів
#
# Назвемо число паліндромом, якщо воно не змінюється при перестановці його цифр у зворотному порядку. Напишіть програму, яка за заданою кількістю K виводить кількість натуральних палиндромiв, що не перевищують K.
#
# ## Формат введення
#
# Визнач однина K (1≤K≤100000).
#
# ## Формат виведення
... |
def _git_info(ctx):
repo = "@tensorflow"
root = str(ctx.path(Label("{}//:BUILD".format(repo))))[:-len("BUILD")]
script = Label("{}//tensorflow/tools/git:gen_git_source.py".format(repo))
r = ctx.execute([
"test",
"-f",
"{}/.git/logs/HEAD".format(root),
])
if r.return_code ... |
# -*- encoding: utf-8
class StorageServiceException(Exception):
"""Base class for all storage service exceptions."""
pass
class IngestNotFound(StorageServiceException):
"""Raised if you try to get an ingest that doesn't exist."""
pass
class BagNotFound(StorageServiceException):
"""Raised if ... |
"""
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 not count spaces or hyphens. For example,
342 (th... |
""":mod:`seoul.subway.constants` --- Subway constants
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
SUBWAY_ID_NAMES = {
'1001': '1호선',
'1002': '2호선',
'1003': '3호선',
'1004': '4호선',
'1005': '5호선',
'1006': '6호선',
'1007': '7호선',
'1008': '8호선',
'1009': '9호선',
'1063': '경의... |
response = {
"gitan": "le sang de tes morts tu vas manger",
"bière": ":beers: ?",
"🍻": "oui oui oui",
"🍺": ":beers: plutôt non ?",
} |
# Time: O(n)
# Space: O(1)
class Solution:
def rob(self, nums: List[int]) -> int:
"""
"""
if not nums:
return 0
if len(nums)==1:
return nums[0]
return max(self.util(nums[:-1]), self.util(nums[1:]))
def util(self, nums):
# Linear Space
... |
'''
import json
import numpy as np
import torch
import torch.nn as nn
import torch.utils.data as data
import torchvision
import torchvision.transforms as transforms
from tqdm import tqdm
import time
BATCH_SIZE = 128
NUM_EPOCHS = 10
with open("./board_cases.json") as f:
board_json = json.load(f)
print(board_json)... |
def mode(list_in):
"""
Calculate the mode
:param list_in: A list
:return: float
"""
value = []
count = []
for val in list_in:
if val in value:
ind = value.index(val)
count[ind] += 1
else:
value.append(val)
count.append(1)... |
#!/bin/python
# coding: utf-8
##########################################################################################################################################
# A Class to simulate dynamic inheritance of Modules and Classes
class GenericWrapper:
def __init__(self, wrapped):
self.wrapped = wrapped... |
class TC:
"""usage: print(f"{TC('sfsf').fg_green.bg_orange} xxxx {TC('sfsfsfds').bold.fg_black.strikethrough.underline.bg_red}")
print(f"{TC('sfsf').fg_green.bg_orange.bold}{TC('sfsfsfds').fg_orange}")"""
def __init__(self, text):
self.text = str(text)
self.c_reset = "\033[0m"
s... |
h = 0
v = 0
a = 0
for t, x in list(map(lambda x: (x.split(" ")[0], int(x.split(" ")[1])), open("input.txt", "r").readlines())):
if t == "forward":
h += x
v += a * x
elif t == "down":
a += x
elif t == "up":
a -= x
print(t, x, ": ", h, v, a)
print(h * v) |
def solution(phone_book):
phone_book.sort()
for i in range(len(phone_book) - 1):
if phone_book[i] == phone_book[i + 1][: len(phone_book[i])]:
return False
return True |
TYPES = {
"Q15720608" : "Wikidata qualifier",
"Q18608359" : "to indicate a source",
"Q18608871" : "for items about people",
"Q18608993" : "for items about organizations",
"Q18609040" : "for a taxon",
"Q18610173" : "for Commons",
"Q18615010" : "for use as qualifier",
"Q18615777" : "to ind... |
# -*- encoding: utf-8 -*-
{
'name': 'project_ulb',
'version': '13.0',
'description': """Manage Project, extend project""",
'depends': [
'base',
'contacts',
'place',
],
'data': [
# assets
# models
# fields
# actions
# reports
... |
print("你真是个小机灵鬼")
print("好像写错了")
print("en ")
print("ddddd")
|
numero = int(input("Digite um número: "))
while numero < 100:
print(numero)
numero = numero + 1
print("Número encerrado!") |
# democratic_bias = '''The Democratic Party's philosophy of modern liberalism advocates social and economic equality, along with the welfare state. It seeks to provide government regulation in the economy to promote the public interest. Environmental protection, support for organized labor, maintenance and expansion of... |
nome = ''
while len(nome) <= 3:
nome = input("Informe o nome: ")
if len(nome) <= 3:
print("O nome precisa ter mais que 3 caracteres.")
|
class Solution(object):
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
sizes = []
visited = [[False for value in row] for row in grid]
for i in range(len(grid)):
for j in range(len(grid[i])):
if visited[... |
#! usr/bin/env python3
class Group(object):
def __init__(self, _name):
self.name = _name
self.groups = []
self.users = []
def add_group(self, group):
self.groups.append(group)
def add_user(self, user):
self.users.append(user)
def get_groups(self):
ret... |
x = [None] * 3
y = [None] * 3
for i in range(3):
x[i], y[i] = [a for a in input().split()]
xa = "".join([i for i in x if x.count(i) == 1])
ya = "".join([i for i in y if y.count(i) == 1])
print("%s %s" % (xa, ya)) |
MODEL_NAME = "cassava_efficient_net.ckpt"
TRAIN_IMAGES_DIR = '../input/cassava-leaf-disease-classification/train_images'
TEST_IMAGES_DIR = '../input/cassava-leaf-disease-classification/test_images'
TRAIN_CSV = '../input/cassava-leaf-disease-classification/train.csv'
PRETRAINED_PATH = 'ml/trained_model/efficientnet-b5.p... |
# -*- coding: utf-8 -*-
class Account:
def __init__(self, email, balance, credit, total_records):
self.email = email
self.balance = balance,
self.credit = credit,
self.total_records = total_records
def __repr__(self):
return str(vars(self))
|
# -*- coding: utf-8 -*-
"""
Django application to demonstrate 'crispy-forms-foundation'
"""
__version__ = '0.5.0'
|
n1 = int(input('Digite um numero:'))
n2 = int(input('Digite outro:'))
a = n1 + n2
m = n1 * n2
d = n1 / n2
p = n1 // n2
di = n1 ** n2
print ('A soma é {}, o produto é {}'.format(a, m), end='>>>')
print ('A divisão é {:.3f} a divisão inteira é {} \n e a potência é{}'.format(d, p, di))
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
ret = []
self.dfs(root, sum, [], ret)
return... |
# Задача 1
'''
for i in range(1,6):
print(i, "000000000000000000000000000000000000")
'''
# Задача 2
'''
a = input('enter 10 figures')
five = 0
for i in a:
if (int(i)) == 5:
five += 1
print(five)
'''
#Задача 4
'''
mult = 1
for i in range(1,11):
mult *= i
print(mult)
'''
#Задача 5
'''
number = int... |
# -*- coding: utf-8 -*-
name = 'ilmbase'
version = '2.2.0'
build_requires = [
'cmake'
]
variants = [['platform-linux', 'arch-x86_64']]
def commands():
appendenv('LD_LIBRARY_PATH', '{root}/lib/')
appendenv('ILMBASE_ROOT', '{root}')
appendenv('PKG_CONFIG_PATH', '{root}/lib/pkgconfi... |
a=float(input('Enter Kilometer:'))
b=0.621371*a
print('Miles=%0.2f'%b)
|
def init_cfg(hostname, vm_auth_key, device_group_name, template_name, panorama_ip, dns_ip):
r = f"""
ip-address=
default-gateway=
netmask=
ipv6-address=
ipv6-default-gateway=
hostname={hostname}
vm-auth-key={vm_auth_key}
panorama-server={panorama_ip}
tplname={template_name}
dgname={device_group_name}
dns-primary={... |
__all__ = [
'closure',
'networks',
'primal_map'
] |
# Constants to convert between python timestamps and NTP 8B binary format [RFC1305]
TIMEOFFSET = 2208988800 # Time Difference from 1-JAN-1900 to 1-JAN-1970 in seconds
ALLBITS = int(0xFFFFFFFF) # To calculate 32bit fraction of the second
DSCP_TABLE = """
============================================================... |
#retorna primeiro e ultimo nome
nomecompleto = input("Digite seu nome completo: ")
nomefatiado = nomecompleto.split()
primeironome = nomefatiado[0]
ultimonome = nomefatiado[-1]
print("Primeiro nome: {}\n Ultimo nome: {}". format(primeironome, ultimonome))
|
# -*- coding: utf-8 -*-
mensagem = "Hello World"
print(mensagem)
print ('Escolha a operação do banco de dados')
print ('1 - inserir')
print ('2 - ler')
print ('3 - atualizar')
print ('4 - deletar aqui')
operacao = int(input('A operação é: '))
if operacao == 1:
print ('inserir')
elif operacao == 2:
print (... |
def get_file_lines(file_path):
with open(file_path) as file:
lines = file.readlines()
return lines
def write_file(file_path, file_lines):
with open(file_path, "w") as f:
f.writelines(file_lines)
|
"""
Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.
Example 1:
Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]
Example 2:
Input: n = 1
Output: [[1]]
Constraints:
1 <= n <= 20
"""
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
... |
distancia = float(input('Digite a distancia da sua viagem: '))
if distancia > 200:
print('Você pagará R$ 0,45 por cada Km. Total: {}'.format(distancia * 0.45))
else:
print('Você irá pagar R$ 0,50 por cada Km. Total: {}'.format(distancia * 0.50)) |
class Node:
def __init__(self, data):
self.data = data
self.next_node = None
class LinkedList:
def __init__(self):
self.head = None
self.num_of_nodes = 0
# O(1)
def insert_start(self, data):
self.num_of_nodes = self.num_of_nodes + 1
new_node = Node(d... |
"""
Tipe data dictionary sekedar menghubungkan antara Key dan VALU
KVP = Key Value Pair
Dictionary = Kamus
"""
# kamus_ind_en = {}
# kamus_ind_en['anak'] = 'child'
# kamus_ind_en['istri'] = 'wife'
# kamus_ind_en['ayah'] = 'father'
# kamus_ind_en['ibu'] = 'mother'
#
# print(kamus_ind_en)
# print(kamus_ind_en['ayah'])
#... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.