text stringlengths 5 121k |
|---|
""". Write a Python program to convert temperatures to and from celsius,
fahrenheit.
C = (5/9) * (F - 32)"""
print("Choose the conversion: ")
print(" [c] for celsius to fahrenheit")
print(" [f] for fahrenheit to celsius")
ans = input()
conversion = 0
cs = ""
if ans == "c":
ans = "Celsius"
elif an... |
"""For given integer x,
print ‘True’ if it is positive,
print ‘False’ if it is negative and
print ‘zero’ if it is 0"""
x = int(input("Enter a number: "))
if x > 0:
print('positive')
elif x<0:
print('negative')
else:
print('zero') |
o = 790
h = 6
names_rating = {"Lucy": 18, "Mary": 12, "Henry": 10, "Stacey": 11, "Loulou": 5}
print("")
print("Hours to comlete %s orders" % o)
for i in names_rating.values():
x = o / i
print(round(x,1))
print("")
print("Hours taken for everyone working together to complete %s order" % o)
print(o / sum(names_... |
def name(value):
first = value.capitalize()
message = "Hi %s" % (first)
return message
name1 = input("Enter your name: ")
print(name(name1)) |
"""
This module contains python implementation of linear regression algorithm,
that I will be then implement in CUDA. I will be using data generated from
`generate_data.py`, which generates data of function `y = 3x + 2`.
The model will is of form `y = X * W` where `X` is a vector of features and
`W` is a vector of wei... |
animal = input('Enter an animal ')
madlib = animal
madlib += ' can be found running wild in '
madlib += input(' Enter a city... ')
madlib += ' causing distruction at every turn, when he turned '
madlib += input('Enter a color ')
madlib += ' he gained strength and speed, {} tried to run from the people. '.format(animal)... |
"""Start a spark session to generate the required document."""
from pyspark.sql import SparkSession
import config
def generate_json_report(input_files, report_file_name=config.OUTPUT_FILE):
"""Generate a json report by starting a spark session.
Args:
- input_files: input files names.
... |
class MyClass(object):
var = 10
this_obj = MyClass()
that_obj = MyClass()
print(this_obj)
print(that_obj)
print(this_obj.var)
print(that_obj.var)
class Joe(object):
def callme(self):
print('Calling "Call me" method instance: ')
thisjoe = Joe()
thisjoe.callme()
|
import os
class DictConfig(dict):
def __init__(self, filename):
self._file_name = filename
if os.path.isfile(self._file_name):
with open(self._file_name, 'a') as fh:
fh.writelines("{key}={value}\n".format(key=key, value=value))
def __setitem__(self, key, value):
print("Set Item")
dict.__setitem__... |
class MyClass(object):
pass
x = MyClass()
print(x)
x.one = 1
x.two = 2
x.word = "String'o text!"
print(x.one)
class GetSet(object):
def __init__(self, value):
self.attrval = value
@property
def var(self):
print("Getting a value")
return self.attrval
@var.setter
def var(self, value):
print("Setti... |
x = 0
while ( x <= 9 ) :
print ( 2*x + 1 ) ;
x += 1 ;
x = 0
while ( x <= 9 ) :
print ( 2*x ) ;
x += 1 ;
|
x = 5 ;
print ( type ( x ) ) ;
x = 5.456 ;
print ( type ( x ) ) ;
x = " hello " ;
print ( type ( x ) ) ;
x = 234 ;
print ( x ) ;
x= 3 ;
print ( id ( x ) ) ;
y = x ;
print ( id ( y ) ) ;
y = 2 ;
print ( id ( y ) ) ;
print ( id ( x ) ) ; |
x =5 & 6 ;
print ( x ) ;
x = 5 | 6 ;
print ( x ) ;
x = ~ 5 ;
print ( x ) ;
x = 5 ^ 6 ;
print ( x ) ;
x = 99 >> 2 ;
print ( x ) ;
x = 5 << 3 ;
print ( x ) ; |
import numpy as np
def softmax(x: np.ndarray) -> np.array:
"""
:param x: Takes in the training data wich is a vector of 1XL
:return: Returns normalized probability distribution consisting of probabilities proportional to the exponentials
of the input numbers. Vector of size
"""
e_x = n... |
def main():
codigo = int(input("Ingrese codigo de moneda: "))
monto = int(input("Ingrese monto: "))
res = None
if(codigo == 1):
res = 3.64 * monto
elif(codigo == 2):
res = 4.42 * monto
elif(codigo == 3):
res = 0.57 * monto
if(res != None):
print("Monto eq... |
n = 10
lista = []
for i in range(n):
valor = int(input("Ingrese numero: "))
lista.append(valor)
print(lista)
lista.reverse()
print(lista) |
def main():
A = int(input("Ingrese el valor de A: "))
B = int(input("Ingrese el valor de B: "))
C = int(input("Ingrese el valor de C: "))
S = 0
if(A / B > 30):
S = (A / C) * B ** 3
else:
for i in range(2, 31, 2):
S = S + i ** 2
print("Valor de S:", S)
if __name__... |
def mayor(a, b):
if(a > b):
return a
else:
return b
def mayor3(a, b, c):
mayor_ab = mayor(a, b)
res = mayor(mayor_ab, c)
n = 30
if n % 2 != 0 and n % 3 != 0 and n % 5 != 0:
print("z")
return res
def main():
n1 = 127
n2 = 156
n3 = 77
res = mayor3(n... |
'''
Implemente un programa que lea la calificacion de un alumno y su cantidad de
participaciones. Si la cantidad de participaciones es mayor que 10, entonces
recibe un punto de bonificacion. Su programa debe mostrar en pantalla la
nota final
'''
def main():
nota = int(input("Ingrese nota: "))
participaci... |
def main():
monto = float(input("Ingrese monto gastado: "))
if(monto < 0):
print("Valor del monto es incorrecto")
elif(monto <= 100):
print("Pago con dinero en efectivo")
elif(monto < 300):
print("Pago con tarjeta de debito")
else:
print("Pago con tarjeta de credito")... |
def burbuja(lista):
for i in range(len(lista) - 1):
for j in range(len(lista) - 1 - i):
if(lista[j] > lista[j + 1]):
aux = lista[j + 1]
lista[j + 1] = lista[j]
lista[j] = aux
def quicksort(lista):
if(len(lista) <= 1):
... |
tiempo_h = int(input("Ingrese cantidad de horas de estacionamiento: "))
tiempo_min = int(input("Ingrese cantidad de minutos de estacionamiento: "))
if(tiempo_h == 0):
print("No tiene que pagar estacionamiento")
else:
if(tiempo_min > 0):
tiempo_h = tiempo_h + 1
monto = 2.5 * tiempo_h
... |
import ordenamiento as ord
def leer_pesos():
continuar = True
lista = []
suma = 0
while(continuar == True):
peso = int(input("Ingrese peso: "))
if(peso <= 0):
continuar = False
else:
lista.append(peso)
suma = suma + peso
lista.append(suma /... |
'''
Estrategia:
1) Leemos el valor como cadena (con el punto decimal)
2) LLamamos a una funcion para quitar el punto decimal
3) aplicamos la funcion que maneja enteros para hallar la suma de digitos
'''
import p06
def convertir(numero):
res = ""
numero = str(numero)
for caracter in numero:
if(c... |
'''
Implemente un programa que reciba un numero "n" y calcule la cantidad de sus divisores.
Ejemplo:
4 --> 1, 2, 4
Podemos decir que 4 tiene 3 divisores
'''
def main():
n = int(input("Ingrese numero: "))
cantidad = 0
for i in range(1, n + 1):
if(n % i == 0):
cantidad = cantidad... |
'''
Formato de los datos (ambos son cadenas):
- clave: termino
- valor: definicion del termino
Ejemplo:
glosario = {"termino1": "El termino1 es <definicion>"}
'''
def leer_glosario():
res = {}
n = int(input("Ingrese la cantidad de terminos: "))
for i in range(n):
ter... |
"""Elliot Blair"""
name = input("What is your name?")
while name == "" or name == " ":
print("Name must not be blank")
name = input("What is your name?")
print(name)
|
s=input()
st=[]
for i in s:
if not st:
st.append(i)
else:
if st[-1]==i:
st.pop()
else:
st.append(i)
if not st:
print("Empty String")
else:
print(''.join(st))
|
d = int(input('Diameter: '))
r = d/2
area = 3.14 * (r * r)
circumference = 2 * 3.14 * r
print(f'Area: {area}, Circumference: {circumference}')
|
class array:
def __init__(self, array=None):
if array is None:
array = [5, 4, 6, 8, 10, 11,34]
self.array = array
def length(self):
print(len(self.array))
def get_value(self):
for n, i in enumerate(self.array):
if i == 1:
print(self.array[n])
... |
fname = "demo.docx"
num_lines = 0
num_words = 0
num_chars = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
num_lines += 1
num_words += len(words)
num_chars += len(line)
print("number of lines :", num_lines)
print("Number of Words :", num_words)
print("Number of... |
def main():
a = "ABC"
b = "123"
for p in range(len(a)):
print(a[p])
print(b[p])
if __name__ == '__main__':
main() |
def squares_needed(grains):
if grains == 0:
return 0
square = 0
while grains > 0:
grains -= 2**square
square += 1
return square
|
from unittest import TestCase
from algos.binary_sum import sum_bin
class BinarySum(TestCase):
def test_should_sum_simple_numbers(self):
a = "100"
b = "101"
self.assertEquals("1001", sum_bin(a, b))
def test_should_more_complex_numbers(self):
a = "1111"
b = "0011"
self.assertEquals("10010", sum_bin(a, ... |
def sort(a):
if (len(a) == 1):
return a
else:
a1 = sort(a[0:len(a)/2])
a2 = sort(a[len(a)/2:len(a)])
return merge(a1, a2)
def merge(a, b):
size = len(a) + len(b)
result = []
i = 0
j = 0
for k in range(0, size):
if (i < len(a) and j < len(b)):
... |
def is_shifted(a, b):
if len(a) != len(b):
return False
return b in a+a
def extra_credit(a, b):
if len(a) != len(b):
return False
if a == b:
return "Match"
count = 0
shift_right = a
shift_left = a
while(count < len(a)):
print(len(a)-count)
print(... |
num = int(input("Hour:"))
num1 = int(input("Min:"))
num2 = int(input("Sec:"))
num3 = int(input("Hour2:"))
num4 = int(input("Min2:"))
num5 = int(input("Sec2:"))
result = (((num - num3) * 3600) + ((num1 - num4) * 60) + (num2 - num5))
print(abs(result))
|
import operator
import functools
def largest_product(series: str, size: int) -> int:
if size < 0 or len(series) < size:
raise ValueError('Length is less than one or larger than series length')
if size < 1:
return 1
string_length = len(series) - size + 1
result = [series[i:size+i] for... |
def compute_set_cover(universe, subsets):
elements = set(el for setOfEls in subsets for el in setOfEls)
print('ELEMENTS:')
print(elements)
covered = set()
cover = []
while covered != elements:
compute_cost = lambda candidate_subset: len(candidate... |
import sys
import math
digit = {
"0" : [True, True, True, False, True, True, True],
"1" : [False, False, True, False, False, True, False],
"2" : [True, False, True, True, True, False, True],
"3" : [True, False, True, True, False, True, True],
"4" : [False, True, True, True, Fals... |
import sys
import math
def prime_factors(n):
i = 2
factors = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return factors
a, b = [int(i) for i in input().split()]
f = prime_factors(a)
... |
import sys
import math
def div_count(x, d):
n = 0
while True:
if x % d == 0:
x //= d
n += 1
else:
break
return n
def fizzbuzz(x):
r =""
if "3" in str(x):
r+= "Fizz" * str(x).count("3")
if x % 3 == 0:
r+= "Fizz" * div_count(x, ... |
"""
Created on Wed Oct 23 15:46:25 2019
@author: RagCoder
Source: https://www.dataquest.io/blog/web-scraping-tutorial-python/
"""
'''Navigating a web page'''
import requests
from bs4 import BeautifulSoup
import pandas as pd
page = requests.get("http://forecast.weather.gov/MapClick.php?lat=37.7772&lon=-122.4168")
... |
from variables import *
def get_list_all_pmids(files):
"""
Read _pmids.txt file(s) to get all the pmids from the publications
Requires: files: a list with the name(s) of the file(s).
Ensures: all_pmids a list with all pmids.
"""
all_pmids = []
for file in files:
... |
from contracts import contract, new_contract, ContractNotRespected
import unittest
class ClassContractsTests(unittest.TestCase):
def test_class_contract1(self):
class Game(object):
def __init__(self, legal):
self.legal = legal
@new_contract
def legal_... |
'''The program asks for a string input, and welcomes the person, or welcomes the world if nothing was given.'''
def inputname():
'''Keeps asking until a string is inputted'''
while True:
try:
name=input("Please enter your name!")
int(name)
print("This is not a string... |
def iterative_levenshtein(s, t):
rows = len(s)+1
cols = len(t)+1
dist = [[0 for x in range(cols)] for x in range(rows)]
for i in range(1, rows):
dist[i][0] = i
for i in range(1, cols):
dist[0][i] = i
for col in range(1, cols):
for... |
def reverse(strng):
word=strng.split()
word.reverse()
new_word=' '.join(word)
print(new_word)
reverse('help') |
import pandas as pd
df = pd.read_csv('sales.csv')
df['date'] = df['date_order'].apply(lambda x : x[:10])
df['revenue'] = df['qty'] * df['price'] - df['promotion']
print(df.head())
print('\nTotal revenue : ', df['revenue'].sum())
df_date = df.groupby('date')['revenue'].sum()
print('\nRev... |
import random
class RPSAgent:
def __init__(self, preferred_selection=1):
self.preferred_selection = preferred_selection
def getMove(self):
"""
This will get a move with some bias built in.
"""
randNumber = random.random()
if self.preferred_selection == 1:
... |
import sys
def palindrome(p):
for i in range(len(p) // 2):
if p[i] == p[-1 - i]:
continue
else:
return 0
return 1
p = list(sys.stdin.readline().rstrip())
x=palindrome(p)
print(x)
|
import turtle
window = turtle.Screen()
milvia = turtle.Turtle()
milvia.forward(100)
milvia.left(90)
milvia.forward(100)
milvia.left(90)
milvia.forward(100)
milvia.left(90)
milvia.forward(100)
milvia.left(90)
turtle.mainloop() |
import os
import sys
def read_data():
if len(sys.argv) != 3:
print('Wrong number of arguments')
exit()
_, pattern, given_file = sys.argv
if not os.path.isfile(given_file):
print('Last argument should be a patternh to file')
exit()
with open(given_file, 'r') as f:
... |
import RPi.GPIO as GPIO
from time import sleep
flag=1
en = 25
enb = 17
in1 = 24
in2 = 23
inB1 = 22
inB2 = 27
GPIO.setmode(GPIO.BCM)
GPIO.setup(in1,GPIO.OUT)
GPIO.setup(in2,GPIO.OUT)
GPIO.setup(inB1,GPIO.OUT)
GPIO.setup(inB2,GPIO.OUT)
GPIO.setup(en,GPIO.OUT)
G... |
number_of_dogs=int(input())
number_of_animals=int(input())
cost_dogs=number_of_dogs*2.5
cost_animals=number_of_animals*4
cost=cost_animals+cost_dogs
print(f'{cost:.2f} lv.') |
input_text=input()
vowels_sum=0
for char in input_text:
if char=='a':
vowels_sum+=1
elif char=='e':
vowels_sum+=2
elif char=='i':
vowels_sum+=3
elif char=='o':
vowels_sum+=4
elif char=='u':
vowels_sum+=5
print(vowels_sum) |
length_in_cm=int(input())
width_in_cm=int(input())
height_in_cm=int(input())
percentage_occupied_volume=float(input())
volume_aquarium=length_in_cm*width_in_cm*height_in_cm
total_liters=volume_aquarium*0.001
percentage=percentage_occupied_volume*0.01
liters=total_liters*(1-percentage)
print(f'{liters:.3f}') |
import sys
'''
Input: fasta file with each sequence on one line.
Input: sequence number to start with and number to print.
Output: subset fasta file
Example to extract just the first sequence.
$ python extractor.py bigfile.fasta 1 1 > reduced.fasta
'''
if len(sys.argv) != 4+1:
print("Number of arguments was %d" %... |
while True:
if option == "x":
print("============================")
print("Selamat Datang di ATM saya")
print("============================")
print('')
option1 = print("1. Chek Uang saya")
option2 = print("2. Ambil Uang saya")
option3 = print("3. Tabung Uang s... |
my_str = "Hello World"
print(dir(my_str))
print("Saludar: " + my_str)
print(f"Saludar: {my_str}")
print(my_str)
print(my_str.upper())
print(my_str.lower())
print(my_str.swapcase())
print(my_str.capitalize())
print(my_str.title())
print(my_str.replace("Hello", "Yuli"))
print(my_str.startswith("H"))
print(my_str.en... |
print(1 - 2)
print(1 + 2)
print(2 * 2)
print(3 / 2)
print(3 // 2)
print(3 % 2)
print(1 + 1.0)
print(2 ** 2)
age = input("Insert your age: ")
new_age = int(age) + 5
print(new_age)
|
'''Jadoo hates numbers, but he requires to print a special number "420" to recharge the equation of life.He asks your help to print the number but Since he hates numbers,
he asks you to write the program such that there would not be any number in the code.
SOLUTION'''
print(ord('Ƥ'))
|
class Customer():
"""Create a Customer for our online game.
They have an account_balance, which they can use to purchase
level-ups within the game, via the purchase_level method.
This increases their level and decreases their account_balance
according to the current cost of a level."""... |
import unittest
from customer_data import Customer
class TestCustomerData(unittest.TestCase):
def setUp(self):
print("setUp")
self.customer1 = Customer("beeble", "bsmith@itsme.com", 350, 7)
self.customer2 = Customer("KarenRulz", "kaz@yolo.com", 5, 2)
def test_account_po... |
import datetime, sys, dynamic, bruteforce, backtracking, firstBranchBound
def run():
path = input("Which method do you want to use? \nBrute force (1), Dynamic (2), Best First Branch Bound (3), or Backtracking (4)?\nOr press q to quit : ")
if path == '1':
time1 = datetime.datetime.now()
print( bruteforce.brute... |
class Stack():
def __init__(self):
self.items = []
def push(self,item):
self.items.append(item)
def pop(self):
return self.items.pop()
def isEmpty(self):
return self.items == []
def peek(self):
if not self.isEmpty():
return self.items[-1]
... |
import sqlite3
from sqlite3 import Error
def create_connection(db_file):
""" create a database connection to the SQLite database
specified by the db_file
:param db_file: database file
:return: Connection object or None
"""
conn = None
try:
conn = sqlite3.connect(db_file)
ex... |
class Solution:
def isValidBST(self, root):
"""
bst定义
左子树都比节点小
右子树都比节点大
并且所有子树都一样
写起来代码更好看,更优雅
"""
return self.valid(root, None, None)
def valid(self, node, left, right):
if not node:
return True
if ... |
class Solution(object):
def minDiffInBST(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.ans = 31 << 1
self.last = -31 << 1
def dfs(root):
if not root:
return
... |
import heapq
class KthLargest(object):
def __init__(self, k, nums):
"""
:type k: int
:type nums: List[int]
"""
self.heap = []
self.k = k
map(self.add, nums)
def add(self, val):
"""
:type val: int
... |
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
n = len(nums)
if n == 0:
return []
res = []
def backtrack(i, tmp):
res.append(tmp)
for j in range(i, n):
backtrack(j... |
import heapq
class KthLargest:
def __init__(self, k: int, nums):
self.heap = []
self.k = k
for v in nums:
self.add(v)
def add(self, val: int):
if len(self.heap) < self.k:
heapq.heappush(self.heap, val)
elif val > self.heap[0]:
heapq... |
class Solution:
def majorityElement(self, nums: List[int]) -> int:
count = 0
candidate = None
for num in nums:... |
"""
参考答案 两颗子树的对称比较,除了比较根节点外,还要比较t1.left是否与t2.right对称, t1.right 是否与t2.left对称
在进行深度优先遍历的时候,每次针对要进行判断是否是镜像的子树进行迭代
1
/ \
2 2
/ \ / \
3 4 4 3
"""
def is_symmetric(root):
return is_mirror(root.left, root.right)
def is_mirror(t1, t2):
if not t1 and not t2:
return T... |
"""
矩阵中的最长递增路径
思路:DFS + 缓存
DFS过程由于需求是数值递增,所以在下钻到过程中不会出现回路,不需要缓存去重。
由于需要找到全局最优解,所以也不需要依赖贪心。
"""
class Solution:
def longestIncreasingPath(self, matrix):
if not matrix:
return 0
col_length = len(matrix)
row_length = len(matrix[0])
cache = [
[0] * row_length fo... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def build(nums):
if not nums:
return None
return build_node(nums, 1)
def build_node(nums, i):
if len(nums) < i or nums[i-1] is None:
return None
node = TreeNode(nums[i-... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
queue = []
queue.append(root)
queue.append(root)... |
from typing import List
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
n = len(nums)
if n == 0 or n == 1:
return
if k > n:
k = k % n
for i in ra... |
KrsnaNames = {"Mukunda","Govinda","Tirupati"}
print(KrsnaNames)
print(KrsnaNames)
for name in KrsnaNames:
print(name)
age = 20
while(age<30):
print("Hare Krsna")
age += 1
for i in range(3,9):
print(i)
|
from graphics import *
def moveShape(shape, newCenter):
oldCenter = shape.getCenter()
shape.move(newCenter.getX() - oldCenter.getX(),
newCenter.getY() - oldCenter.getY())
def main():
win = GraphWin("move the circle", 800, 600)
point = win.getMouse()
shape = Circle(poin... |
import numpy as np
import pandas as pd
import scipy.optimize
import matplotlib.pyplot as plt
import seaborn as sns
rc={'lines.linewidth': 2, 'axes.labelsize': 18, 'axes.titlesize': 18}
sns.set(rc=rc)
df = pd.read_csv('data/bcd_gradient.csv', comment = '#')
df = df.rename(columns={'fractional distance from an... |
import numpy as np
my_ar1 = np.arange(0,11,dtype='float')
print(my_ar1)
my_ar2 = np.linspace(0,10,11,dtype='float')
print(my_ar2)
xa_high = np.loadtxt('data/xa_high_food.csv',comments='#')
xa_low = np.loadtxt('data/xa_low_food.csv',comments='#')
def xa_to_diameter(xa):
""" Convert an array of cross-secti... |
class Rectangle:
def __init__(self, _number, _length, _width):
self.number, self.length, self.width = _number, _length, _width
def __repr__(self):
return '%d %d %d' % (self.number, self.length, self.width)
def __lt__(self, other):
if self.number != other.number:
... |
import random
import sys
BOARD_SIZE = int(input('请输入棋盘大小:'))
high = []
wide = []
num = []
num1 = []
num2 = []
board = []
def initBoard() :
for i in range(BOARD_SIZE) :
row = ["╋"] * BOARD_SIZE
board.append(row)
def printBoard() :
for i in range(BOARD_SIZE) :
... |
import math
class Fraction:
def __init__(self, _up, _down):
g = math.gcd(_up, _down)
self.up = _up // g
self.down = _down // g
def __str__(self):
return "%d/%d" % (self.up, self.down)
def add(self, other):
c = Fraction(0, 1)
c.down = self.dow... |
cp = float(input("Enter the cost price: "))
sp = float(input("Enter the selling: "))
profit = sp - cp
newsp = 1.05 * profit + cp
print("The profit is", profit)
print("new selling price to increase profit by 5% is: ", newsp)
|
x = float(input("ENter first number: "))
y = float(input("Enter the second number: "))
x = x + y
y = x - y
x = x - y
print("Swapping result: ")
print("Number 1 is: ", x)
print("Number 2 is: ", y)
|
if __name__=='__main__':
fp=open('test1.txt','w')
string=input('please input a string:\n')
string=string.upper()
fp.write(string)
fp.close()
print(string)
|
def pedirNumero(mensaje):
correcto = False
num = 0
while(not correcto):
try:
num = int(input(mensaje))
correcto = True
except ValueError:
print('Error, digite un numero entero')
return num
tam = pedirNumero('Digite el numero de datos que ingresara: ')... |
cadena = input('Digite una cadena de texto: ')
def numVeces(cadena):
contador = 0
for vocal in cadena:
if (vocal.upper()=='A' or vocal.upper()=='E' or vocal.upper()=='I' or vocal.upper()=='O' or vocal.upper()=='U'):
contador+=1
if contador==0:
print("No se encuentra volcales en ... |
def pedirNumero(mensaje):
correcto = False
num = 0
while(not correcto):
try:
num = int(input(mensaje))
correcto = True
except ValueError:
print('Error, digite un numero entero')
return num
listaFibonacci = []
listaPrimos = []
tam = pedirNumero('Digit... |
cadena = input('Digite una cadena de texto: ')
def impDosPrimerosCar(cadena):
print('Primeros dos caracteres:',cadena[0:2])
def impTresPrimerosCar(cadena):
print('Primeros tres caracteres:',cadena[0:3])
def impCadaDosCar(cadena):
print('Cada dos caracteres',cadena[::2])
def impCadenaInv(cadena):
print(... |
import numpy as np
array_copy = np.array([(0,0,0,1,1,1),
(1,1,0,1,0,1),
(0,0,0,1,1,1),
(1,0,0,1,0,1),
(1,0,1,1,0,1),
(1,1,0,0,0,0)])
while np.sum(array_copy) > 0:
j = 0
while j < 9:
i = 0
whi... |
class Solution:
def cloneGraph(self, node):
graph = {}
copy = self.clone(node, graph)
return copy
def clone(self, node, graph):
if node is None:
return None
if node in graph:
return graph[node]
copy = Undirect... |
count = 1
while count <= 5:
print(count)
count+=1
while True :
stuff = input("String to capitalize [type q to quit] : ")
if stuff == "q":
break
print(stuff.capitalize())
while True:
value = input("Integer, please [q to quit] : ")
if value == 'q' :
break
nu... |
"""
Authors: Anika Suman & Ayush Khanna
Date: 9/7/21
Class: Math 241 Scientific Computing
Professor: Ben Marlin
"""
import pygame
pygame.init()
screen = pygame.display.set_mode((960, 540))
pygame.display.set_caption('Practice Mode')
successSound = pygame.mixer.Sound('audio/success.mp3')
background... |
def sigma(n: int) -> int:
sum = 0
if n != 1:
sum += n
sum += sigma(n-1)
else:
sum += n
return sum
return sum
n = int(input())
total = sigma(n)
print(total) |
x = int(input('masukkan'))
y = int(input('masukkan'))
def jumlah(x,y):
hasil = x+y
return hasil
print('hasil dari',x,'+',y,'=', jumlah(x,y))
k = jumlah(2,4)+1
print(k)
|
angka = int(input('masukkin angka: '))
Total = 0
pembagi=0
while angka > 0:
pembagi+=1
bil = 1/pembagi
print(bil)
simpan = Total+bil
Total = simpan
angka-=1
print('hasilnya = ', Total)
|
def gcd(a, b):
""" Returns the greatest common divisor of a and b """
if a < b:
a, b = b, a
while b > 0:
a, b = b, a % b
return a
print(gcd(50, 20))
print(gcd(22, 143))
def lcm(a, b):
if a > b:
a, b = b, a
for x in range(b, a * b + 1, b):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.