content stringlengths 7 1.05M |
|---|
"""
785. Is Graph Bipartite?
https://leetcode.com/problems/is-graph-bipartite/
dfs
"""
class Solution:
def isBipartite(self, graph: List[List[int]]) -> bool:
n = len(graph)
colors = [-1] * n
for i in range(n):
if colors[i] == -1:
if not self.dfs(graph, co... |
def extractWwwVerdantloreCom(item):
'''
Parser for 'www.verdantlore.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('monarch of the dark nights', 'Monarch of the Dark Night... |
class KeyValue(object):
def __init__(self, keyvalue):
self._pb_kv = keyvalue
@property
def key(self):
"key in bytes. An empty key is not allowed."
return self._pb_kv.key
@property
def create_revision(self):
"revision of the last creation on the key."
retu... |
HTMLBreak = '<br>'
# Viewport is used on mobile and from what I can tell right now is static
viewport = '<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">'
cb_name=0
cb_value=1
cb_text=2
def textHeader():
header = ''
header = header + 'Content-Type: text/html\n\n'
... |
"""
App for front page news and news articles
"""
default_app_config = 'nablapps.news.apps.NewsConfig'
|
command = '/home/lucas/www/socialrank.lucasou.com/socialrank-env/bin/gunicorn'
pythonpath = '/home/lucas/www/socialrank.lucasou.com/socialrank-env/socialrank'
bind = '127.0.0.1:8080'
workers = 1
user = 'lucas'
accesslog = '/home/lucas/logs/socialrank.lucasou.com/gunicorn-access.log'
errorlog = '/home/lucas/logs/socialr... |
"""
Protein-Ligand Interaction Profiler - Analyze and visualize protein-ligand interactions in PDB files.
__init__.py - Needed for python modules.
"""
|
#!/usr/bin/python3
ORIG = ['docid', 'text', 'tags', 'events', 'event_ranks' 'diagnosis', 'dct']
SEQ = ['docid', 'seqid', 'text', 'text_orig', 'seq', 'seq_labels', 'diagnosis']
ORDER = ['docid', 'text', 'text_orig', 'tags', 'seq', 'seq_labels', 'events', 'event_ranks', 'diagnosis', 'dct']
RELATION = ['docid', 'relid' '... |
class Persons(object):
def __init__(self, client):
self._client = client
def get_person(self, person_id, **kwargs):
url = 'persons/{}'.format(person_id)
return self._client._get(self._client.BASE_URL + url, **kwargs)
def get_all_persons(self, params=None, **kwargs):
url = '... |
"""
https://www.codewars.com/kata/53368a47e38700bd8300030d/train/python
Given: an array of "hashes of names" -- such as {'name': 'Hildegard'}
Return a string with names separated by ',' except last 2 are separated by '&'
Examples:
namelist([ {'name': 'Bart'}, {'name': 'Lisa'}, {'name': 'Maggie'} ])
# returns 'Bart, L... |
n = raw_input()
n=int(n)
ask=[]
for i in range(n):
num=int(raw_input())
num=ask.append(num)
for j in ask:
print(j)
|
class ConditionsAttributes:
def __init__(self, lighting: int, capture_device: int):
self.lighting = lighting
self.capture_device = capture_device
@staticmethod
def from_item(item):
return ConditionsAttributes(
lighting=int(item.info.get("common_lighting", -1)),
... |
# Create a 5 x 5 matrix using a list of lists: matrix
matrix = [[col for col in range(0,5)] for col in range(0,4)]
# Print the matrix
for row in matrix:
print(row)
print ([num **2 for num in range(10) if num % 2 == 0])
#conditional on the ouput expression
print ([num **2 if num % 2 == 0 else 0 for num in range(... |
class Currency(object):
"""this is the currency class"""
# Currency class constructor
def __init__(self, base, symbols, time):
self.base = base
self.symbols = symbols
self.time = time |
'''
https://www.hackerrank.com/challenges/30-hello-world/
To complete this challenge, you must save a line of input from stdin to a variable,
print "Hello, World." on a single line, and finally print the value of your variable
on a second line.
'''
inputString = input() # get a line of input from stdin and save it t... |
# Programa que leia dois números inteiros e compara mostrando na tela qual é menor, maior e se são iguais.
n1 = int(input('Primeiro número: '))
n2 = int(input('Segundo número: '))
if n1 > n2:
print('O {}PRIMEIRO{} valor é maior'.format('\033[32m','\033[m'))
elif n2 > n1:
print('O SEGUNDO valor é maior')
elif n... |
time = input().strip().split(":")
if time[-1][-2:] == "PM" and time[0] != "12":
time[0] = str(int(time[0]) + 12)
elif time[-1][-2:] == "AM" and time[0] == "12":
time[0] = "00"
print("%s:%s:%s" % (time[0], time[1], time[2][:2]))
|
def main():
# input
N = int(input())
S = input()
Q = int(input())
TABss = [list(map(int, input().split())) for _ in range(Q)]
# compute
for i in range(Q):
if TABss[i][0] == 1:
A, B = TABss[i][1]-1, TABss[i][2]-1
tmp = S[:A]+S[B]+S[A+1:B]+S[A]+S[B+1:]
... |
f = open('text.txt',encoding = 'utf-8')
# 1.методами строк очистить текст от знаков препинания
a = f.read()
# print(a)
c = "".join(c for c in a if c not in ('!','.',':',',','?',';','»','—','«',')','('))
# print(len(c))
# 2.сформировать list со словами (split)
d = c.lower() # 3. привести все слова к нижнему реги... |
#
# @lc app=leetcode id=448 lang=python3
#
# [448] Find All Numbers Disappeared in an Array
#
# https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/description/
#
# algorithms
# Easy (52.77%)
# Total Accepted: 144.5K
# Total Submissions: 272.6K
# Testcase Example: '[4,3,2,7,8,2,3,1]'
... |
# [기초-출력] 출력하기04(설명)
# minso.jeong@daum.net
'''
문제링크 : https://www.codeup.kr/problem.php?id=1004
'''
print("'Hello'") |
"""
Profile ../profile-datasets-py/div52_zen50deg/047.py
file automaticaly created by prof_gen.py script
"""
self["ID"] = "../profile-datasets-py/div52_zen50deg/047.py"
self["Q"] = numpy.array([ 1.60776800e+00, 7.95355900e+00, 6.74945900e+00,
7.45557100e+00, 6.46067300e+00, 6.20967000e+0... |
# domain-layer test:
def test_prefers_current_stock_batches_to_shipments():
in_stock_batch = Batch("in-stock-batch", "RETRO-CLOCK", 100, eta=None)
shipment_batch = Batch("shipment-batch", "RETRO-CLOCK", 100, eta=tomorrow)
line = OrderLine("oref", "RETRO-CLOCK", 10)
allocate(line, [in_stock_batch, shipm... |
def pow_mod(n, k, mod):
"""
Exponentiation by squaring
https://atcoder.jp/contests/atc002/tasks/atc002_b
:return: n ** k
"""
if k == 0:
return 1
elif k & 1 == 1:
return pow_mod(n, k - 1, mod) * n % mod
else:
tmp = pow_mod(n, k // 2, mod)
return tmp * tmp... |
def failure_message(message=None, user=None, user_group=None):
return '''
Message failed to send, please try again later or contact administrator
from: TextHomelessHelp Admin
- Only you can see this message
'''
|
# Created by MechAviv
# Map ID :: 940002030
# Hidden Street : Play Magnus Video
sm.curNodeEventEnd(True)
sm.setTemporarySkillSet(0)
sm.setInGameDirectionMode(True, True, False, False)
sm.playURLVideoByScript("http://nxcache.nexon.net/maplestory/video/yt/kaiser.html")
sm.setTemporarySkillSet(0)
sm.setInGameDirectionM... |
#!/usr/bin/env python
class SemGraphNode(object):
def __init__(self, sem_graph, id_minting_d):
self.canonical_id = sem_graph.register_obj(id_minting_d, self)
self.graph = sem_graph
def as_dict(self):
d = {}
for att in self.predicates:
val = getattr(self, att, [])
... |
PAGE_TITLE = 'Car part Classifier'
PAGE_ICON = "🤖"
LAYOUT = "wide"
LANDINGPAGE_TITLE = 'Car part Classification'
SIDEBAR_TITLE = '✨ Navigation ✨'
CONTENT_IMAGES_FILE = [
'tail_light.jpg', 'wheel.jpg', 'steering_wheel.jpg',
'head_light.jpg', 'rear_view_mirror.jpg', 'side_mirror.jpg',
]
CONTENT_IMAGES_NAME = ... |
#!/usr/bin/python
r"""
Contains PEL related constants.
"""
PEL_DETAILS = {
'CreatorID': 'BMC',
'CompID': '0x1000',
'Subsystem': 'BMC Firmware',
'Message': 'An application had an internal failure',
'SRC': 'BD8D1002',
'Sev': 'Unrecoverable Error'}
|
#
# PySNMP MIB module Nortel-Magellan-Passport-CasTestMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-Magellan-Passport-CasTestMIB
# Produced by pysmi-0.3.4 at Wed May 1 14:26:44 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Usi... |
steam_username = ''
steam_password = ''
mail_user = ''
mail_password = ''
mail_server = ''
def steam():
return (steam_username, steam_password)
def mail():
return (mail_server, mail_user, mail_password)
|
# [START app settings]
appSettings = {
"sender_address":"noreply@birthday-168214.appspotmail.com",
}
# [END app settings] |
n = int(input())
t = 0
h_list = []
g_list = []
for i in range(n):
h, g = map(int, input().split())
h_list.append(h)
g_list.append(g)
for x in h_list:
t += g_list.count(x)
print(t)
|
#
# PySNMP MIB module FOUNDRY-MAC-VLAN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/FOUNDRY-MAC-VLAN-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:15:00 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
read_int = lambda: int(input())
read_ints = lambda: list(map(int, input().split()))
read_tuple = lambda: tuple(map(int, input().split()))
def solve():
pass
def main():
T = read_int()
for i in range(T):
result = solve()
print(result, end='\n' if i != T - 1 else '')
if __name__ == '__mai... |
"""Test BLUETOOTH hardware
Send .wav file over bluetooth
"""
# TODO
|
"""
Copyright 2014 Sotera Defense Solutions, Inc.
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 writ... |
# 11. (Função sem retorno com parâmetro) Faça uma função/método para verificar e contar quantas letras a tem numa frase. Não use NENHUMA função pronta da linguagem Python. Aqui deverá ocorrer, PASSAGEM DE PARÂMETRO POR VALOR.
def contar(frase):
cont = 0
for i in range(len(frase)):
if frase[i] == 'a':
... |
def test():
assert (
"docs = list(nlp.pipe(TEXTS))" in __solution__
), "Você está usando nlp.pipe envolvido em uma lista (list)?"
__msg__.good("Bom trabalho!")
|
"""
Examples illustrating the asyncio engine feature of SQLAlchemy.
.. autosource::
"""
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 24 23:00:21 2020
@author: mm
"""
idade =12
if idade<4:
print("Sua entrada custa R$ 0.")
elif idade<=18:
print("Sua entrada custa R$ 5.")
else:
print("Sua entrada custa R$ 10.")
curso = "pos-graduaçao"
if curso =="graduaçao":
da... |
#
# PySNMP MIB module DHCPCLIENT-PRIVATE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DHCPCLIENT-PRIVATE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:46:54 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... |
FILENAME = "input.txt"
def get_input() -> list[tuple[int, int]]:
vector_list = list()
with open(FILENAME) as file:
for line in file.readlines():
direction, unit = line.split()
unit = int(unit)
if direction == "forward":
vector = (unit, 0)
... |
#use classes to define new types
#constructor is called at the time of creating an oject
class Point:
def __init__(self, x, y): #this is the "constructor" that gets called when a new object is created
self.x = x # "self" is a reference to the current object. And x and y are attribute... |
#encoding:utf-8
subreddit = 'PoliticalHumor+PoliticalCompassMemes'
t_channel = '@r_PoliticalMemes'
def send_post(submission, r2t):
return r2t.send_simple(submission)
|
"""
Copyright 2020 The Magma Authors.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES O... |
class Tokenizer():
def __init__(self, go):
# add GO terms in the tokenizer
self.go = go
self.terms = sorted(list(set(go.ont.keys())))
self.vocab_sz = len(self.terms)
# zero is padding
self.term2index = dict(
[(term, i) for i, term in enumerate(self.terms)])
... |
# Copyright 2018 Google Inc. 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 applicable law or a... |
# Memo used to store computed Fibonacci values
memo = {0: 0, 1: 1}
def fibonacci_memoized(n):
"""
Returns the Fibonacci number at the nth index in the Fibonacci sequence
Time complexity: O(n)
Space complexity: O(n)
More efficient, uses a memo to store calculated values, avoiding redundant operatio... |
def production():
"Primes the deployment procedure to execute against production."
config.fab_hosts = ['localhost']
def staging():
"Primes the deployment procedure to execute against staging."
config.fab_hosts = ['127.0.0.1']
def build():
"Compiles, builds and packages our project locally."
l... |
BASE_PATH = 'assets/file_extension_imgs/'
FILE_EXTENSIONS = {
'c': {
'path': BASE_PATH + 'c.png',
'classification': 'backend'
},
'css': {
'path': BASE_PATH + 'css.png',
'classification': 'frontend'
},
'csv': {
'path': BASE_PATH + 'csv.png',
'classific... |
__all__ = ['Node']
class Node:
def __init__(self, operator, attributes, inputs, outputs, scope):
self.operator = operator
self.attributes = attributes
self.inputs = inputs
self.outputs = outputs
self.scope = scope
@property
def operator(self):
return self._... |
#
# @lc app=leetcode id=21 lang=python3
#
# [21] Merge Two Sorted Lists
#
# https://leetcode.com/problems/merge-two-sorted-lists/description/
#
# algorithms
# Easy (49.92%)
# Likes: 2925
# Dislikes: 423
# Total Accepted: 751.7K
# Total Submissions: 1.5M
# Testcase Example: '[1,2,4]\n[1,3,4]'
#
# Merge two sorted... |
# Returns a valid response when request's |referrer| matches
# |expected_referrer|.
def main(request, response):
referrer = request.headers.get("referer", "")
expected_referrer = request.GET.first("expected_referrer", "")
response_headers = [("Content-Type", "text/javascript"),
("Ac... |
C4R_HOST = 'cloud4rpi.io'
C4R_TOKEN = '__YOUR_DEVICE_TOKEN__'
NOTIFICATION_HOOK_URL = '__YOUR_HOOK_URL__'
# GPIO Pins (BCM)
GPIO_PUMP = 4
GPIO_TRIGGER = 17
GPIO_ECHO = 27
# Distance from the sensor to the water level
# based on the coffee-machine's water tank
MIN_DISTANCE = 2 # cm
MAX_DISTANCE = 8 # cm
# Conside... |
# List of regions
region={
"No.":"Region",
1:"US East (N. Virginia)",
2:"US East (Ohio)",
3:"US West (Oregon)",
4:"US West (N. California)",
5:"EU (Ireland)",
6:"EU (Frankfurt)",
7:"EU (London)",
8:"EU (Paris)",
9:"EU (Stockholm)",
10:"Asia Pacific (Singapore)",
11:"Asia Pacific (Tokyo)",
12:"Asia Pacific (Sydney)",... |
# (C) Datadog, Inc. 2019
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
HISTOGRAM_METRICS = {'mapr.db.table.latency'}
COUNT_METRICS = {
'mapr.cache.lookups_data',
'mapr.cache.lookups_dir',
'mapr.cache.lookups_inode',
'mapr.cache.lookups_largefile',
'mapr.cache.lo... |
#!/usr/bin/env python
class Solution(object):
def _count(self, string):
"""
Returns a dictionary of characters counts in the string.
"""
count = dict()
for c in string:
if c not in count:
count[c] = 0
count[c] += 1
return coun... |
def find_and_sum_multiples(maximum, number1, number2=None):
if type(maximum) is not int or type(number1) is not int:
raise TypeError("All parameters should be integers.")
if number1 < 1:
raise ValueError("The second parameter should be an integer with value 1 or higher.")
if maximum < num... |
'''
Source : https://leetcode.com/problems/largest-number-at-least-twice-of-others/
Author : Yuan Wang
Date : 2018-06-13
/**********************************************************************************
In a given integer array nums, there is always exactly one largest element.
Find whether the largest element in... |
def line_x(x: int, width: int) -> int:
if x + 1 < width:
return 0
elif width == 1:
return x
else:
margin = min(width - 3, 6)
return (
width - margin - 2 +
(x + 1 - width) //
(width - margin - 2) *
(width - margin - 2)
)
... |
temp = []
princ = []
mai = men = 0
while True:
temp.append(str(input('Nome: ')).strip().title())
temp.append(float(input('Peso: ')))
if len(princ) == 0:
mai = men = temp[1]
else:
if temp[1] > mai:
mai = temp[1]
if temp[1] < men:
men = temp[1]
princ.app... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 29 11:11:54 2022
@author: leoda
"""
class Polynomial():
def __init__(self, coeffs=[]):
self.__coefficients = coeffs
self.check_zeros()
# properties and setters
@property
def coefficients(self):
return self.__coefficients
@co... |
class ClasseSimples:
contador = 0
def __init__(self):
self.contar()
@classmethod
def contar(cls):
cls.contador += 1
if __name__ == '__main__':
lista = [ClasseSimples(), ClasseSimples()]
print(ClasseSimples.contador) |
# -*- coding: utf-8 -*-
'''
File name: code\square_subsets\sol_619.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #619 :: Square subsets
#
# For more information see:
# https://projecteuler.net/problem=619
# Problem Statement
'''
For a... |
# -*- coding: utf-8 -*-
{
'name': "Bugs Management System",
'summary': """
The Purpose of this module is management of Bugs in Project""",
'description': """
Organize and schedule your Bugs
""",
'author': "Whiz IT Services",
'website': "http://www.whizit.co.in",
# Categor... |
#!/usr/bin/env python
# encoding: utf-8
'''
@author: Jason Lee
@license: (C) Copyright @ Jason Lee
@contact: jiansenll@163.com
@file: jianzhi_offer_56.py
@time: 2019/5/14 15:18
@desc:
'''
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def EntryN... |
# -----------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# -----------------------------------------------------------------------------
""... |
# -*- coding: utf-8 -*-
# noinspection PyUnusedLocal
def test(empty_database, create_and_delete_user, create_login_session, create_user_contact):
pass
|
# -*- coding: utf-8 -*-
"""
@date: 2020/10/30 下午3:22
@file: __init__.py.py
@author: zj
@description:
"""
|
n = int(input())
my_list = [[1, 2] for _ in range(n)]
print(my_list)
|
class Claim:
def __init__(self, claim_type: str, value):
self.type = claim_type
self.value = value
class ClaimsIdentity:
def __init__(self, claims: dict, is_authenticated: bool):
self.claims = claims
self.is_authenticated = is_authenticated
def get_claim_value(self, claim_... |
def calculate_result(string, number): # Ab, AB, aB, ab
number = int(number)
if string[0].isupper() and string[1].islower():
aa = string[0].lower()
bb = string[1].lower()
res = number / int((alphabet.index(aa))) + int((alphabet.index(bb))) # Ab (number / a position) + b position)
... |
#Gives the average of 3 scores in a file
def main():
infile=open("scoresfeb19.dat","r")
print("Reading from file...")
score1=int(infile.readline())
score2=int(infile.readline())
score3=int(infile.readline())
print(score1,score2,score3)
average=(score1+score2+score3)/3.0
print("The avera... |
def repeat(character: str) -> str:
"""Repeat returns character repeated 5 times."""
word = ""
for _ in range(5):
word = word + character
return word
|
# O(n) time | O(1) space
def getNthFib(n):
defaultArray = [0,1]
if n == 1:
return defaultArray[0]
count = 3
while count <= n:
sum = defaultArray[0] + defaultArray[1]
defaultArray[0] = defaultArray[1]
defaultArray[1] = sum
count = count + 1
return defaultArray[1] |
class Apply_Function(object):
def __init__(self):
pass
def apply_function(self,number_change,list_selected_value,method,dataset):
print("---------Change according to {} method ---------------\n".format(method.name))
for i in range(number_change):
#run(row,col,va... |
'''7. По длинам трех отрезков, введенных пользователем, определить возможность
существования треугольника, составленного из этих отрезков. Если такой
треугольник существует, то определить, является ли он разносторонним,
равнобедренным или равносторонним.'''
a, b, c = [
float(x) for x in input('Введите длины отре... |
#!/usr/bin/python
"""Submodules for generating project summary.
"""
|
if __name__ == "__main__":
example_closure = lambda x: x
s = example_closure("hello")
n = example_closure(5)
print(s, n)
x = [1, 2, 3]
equal_to_x = lambda z: z == x
print("this is x", x)
y = [1, 2, 3]
assert equal_to_x(y)
items = [1, 2, 3, 4, 5]
plus_one = list(map(lambd... |
class Singleton:
def __init__(self, cls):
self._cls = cls
def Instance(self):
try:
return self._instance
except AttributeError:
self._instance = self._cls()
return self._instance
def __call__(self):
raise TypeError('Singletons must be ac... |
class NUnitTestFixture(object):
"""Representation of a NUnitTest test fixture.
Attributes:
name: A string representation of the fixture name.
order: An integer indicating the fixture order inside the test suite.
duration: An integer indicating the fixture execution duration in milliseco... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 27 20:39:40 2020
@author: kant
# Daily Challenge #2 - String Diamond
Your task is to return a string that displays a diamond shape on the screen
using asterisk (“*”) characters.
The shape that the print method will return should resemble a diam... |
#Question: Given the root of a tree, find the minimum dept the tree goes
#Solution: Use a BFS traversal to find the first leaf node of the tree
#Difficulty: Easy
def minDepth(root):
#Define queue, current queue and a mindepth variable
queue = [root]; current = []; mindepth = 0
#If our current n... |
# Copyright (c) 2014, Andrea Esposito <info@andreaesposito.org>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice,... |
# You're going to create a list of the actors who appeared in the television programme Monty
# Python's Flying Circus.
# Write a function called create_cast_list that takes a filename as input and returns a list of
# actors' names. It will be run on the file flying_circus_cast.txt (this information was collected
# ... |
with open ("Replace.txt") as f:
content =f.read()
content=content.replace("replace","Sample")
with open("Replace.txt", "w") as f:
f.write(content ) |
class VoiceError(Exception):
pass
class YTDLError(Exception):
pass
class MissingBotToken(Exception):
pass
|
# function / module
def first(input):
if(input==1):
print("On")
else:
print("Off")
def second():
print("test")
#first(1)
#second()
|
def leiaInt(imput):
n = input(imput)
while not n.isnumeric():
print(f'\033[1;31mErro! O valor digitado não é um número.\033[m ')
n = input(imput)
return n
num = leiaInt('Digite um número: ')
print(f'O número digitado foi {num}.')
|
x = {
'a': 12,
'a': 0b1010,
'a': 0o123,
'a': 0xa123,
'a': 1234567,
'a': 0xffff_ffff,
'a': 1234567,
'a': 0b1_1_0_1_0_1,
'a': 0o777,
'a': 0xeeee,
'a': 1.1,
};
|
lines = read_test(12)
lines = read(12)
lines = [(x[0], int(x[1:])) for x in lines]
def turn(facing, deg):
new = facing + deg
while new >= 360:
new = new - 360
while new < 0:
new = new + 360
return new
def execute(cmd,n):
global x, y, facing
if cmd == 'N':
y += n
... |
#Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized.
lines=str(input("Enter sequence of lines: "))
lines.upper()
for line in lines:
upper_lines= line.upper()
print(upper_lines,end='') |
for t in range(int(input())):
n, a, b = map(int, input().split())
for i in range(n):
print(chr(ord('a') + i % b), end="")
print()
|
# GENERATED VERSION FILE
# TIME: Fri Dec 11 13:54:02 2020
__version__ = '1.0.rc0'
short_version = '1.0.rc0'
|
#Desenvolva um programa que pergunte a distancia de uma viagem em KM.
#Calcule o preço da passagem, cobrando R$0,50 por km para viagens de ate 200 Km
# e R$0,45 para viagens mais longas.
dist = float(input('Qual a distancia em Kilometros até o seu destino? '))
if dist <= 200.00:
d1 = dist * 0.50
print(f'O valo... |
# vim: ai ts=4 sts=4 et sw=4 encoding=utf-8
##Variables
ACTIVITY_LOG_PAGE_TITLE = "Activity Log"
TESTER_NAME = "Tester Pune"
CREATED_PROJECT_ACTION = "Created Questionnaire"
PROJECT_NAME = "project_name"
PAGE_TITLE = "page_title"
QUESTIONNAIRE_CODE = "questionnaire_code"
GEN_RANDOM = "gen_random"
DEFAULT_QUESTION = ... |
# SOLUTION 1 OF LEETCODE PROBLEM 2
# Santiago Garcia Arango, July 2020
"""
DESCRIPTION:
You are given two non-empty linked lists representing two non-negative
integers.
The digits are stored in reverse order and each of their nodes contain a
single digit. Add the two numbers and return it as a linked list.
You may ass... |
""" 25 - Crie um programa que leia o nome de uma pessoa e diga se ele tem 'SILVA'. """
nome = str(input('Qual é o seu nome completo? ')).strip().upper()
print('Seu nome tem Silva?', end=' ')
print('SILVA' in nome)
'''
# Esta outra resposta foi criada pelo Marcos do futuro:
nome = str(input('Qual é o seu nome complet... |
# -*- coding:utf-8 -*-
"""
@author: leonardo
@created time: 2020-09-19
@last modified time:2020-09-19
""" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.