text
stringlengths
37
1.41M
#FileName: While.py num=23 running=True while running: guess=int(input("Enter any Number: ")) if guess==num: print("Congo you WIN") running=False elif guess<num: print("Little Higher") else: print("little Lower") print("Finish")
def edad2070(edad,año): diferencia = 2070 - año return(diferencia+edad) def main(): Años = int(input("Introduzca su edad: ")) AñoActual = int(input("Introduzca el año actual: ")) print(edad2070(Años,AñoActual)) if __name__ == '__main__': main()
''' Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. Input: 11000 11000 00100 00011 Output: 3 ''' def numIsla...
def strStr(haystack,needle): if not len(needle): return 0 for i in range(0,len(haystack)-len(needle)+1): if haystack[i:i+len(needle)] == needle: print(i) return i print(-1) return -1 strStr("hello","ll")
def funkcija_map(y): #kvadrira elemente return y**2 def funkcija_filter(y): #vraca prirodne brojeve if y>=0: return True else: return False def funkcija_reduce(x,y): #sumira return x+y def MAPP(funk, iterab): #realizovana MAP funkcija for x in range (0, len(iterab)): itera...
import sys,os #Write a function named countEndWrd that takes 2 arguments filename and word. #Count how many times the given word appears at the end of a line, #Then append the following string to the passed file : #'The word => '+"'"+word+"'"+' appears => '+count+' times' . ''' Write your function Here ''' def count...
# -*- coding: utf-8 -*- print("HelloWorld") print """<html lnag="ja"> <body> </body> </html>""" a = 100 b = c = 200 d,e = 300,400 print("a=",a) print("b=",b) print("c=",c) print("d=",d) print("e=",e) for char in 'Hello': print(char...
import pygame def question(): #dit zoekt waar de speler zich bevind player_position = int(input("What catagorie are you in?: 0=Red, 1=Yellow, 2=Blue, 3=Green \n Select the number of catagorie? ")) catagorie = 0 #score per catagorie zodat je geen zelfde vragen krijgt red_score = 0 yell...
basket={'apple','orange','apple','pear','orange','bana'} print(basket) print ('orange' in basket) print ('otrnshr' in basket) a=set('abc') b=set('alac') print a print b print a-b # in a not in b print a | b print a & b print a ^ b {x for x in 'abcdefghijkld' if x not in 'abc'}
for i in range(5): print i print range(5,10) print range(0,10,3) print range(-10,-100,-30) a=["MARY",'hAD','A','LITTLE'] for i in range(len(a)): print i,a[i] print (range(10)) for n in range(0,10): for x in range(0,n): print x,n
""" Splitting the bill program J. Knerr Spring 2020 """ def main(): amt = float(input(" bill amount: ")) pct = float(input(" percent tip: ")) num = int(input("num of people: ")) tip = amt*(pct/100) total = amt + tip cpp = total/num # cost per person print("-=-"*10) print(" ...
class Program: def __init__(self): self.nodes = [] self.values = {} def add_node(self, node): self.nodes.append(node) def get_or_add_value(self, val): if val not in self.values: self.values[val] = Value(val) return self.values[val] def dump(self): ...
# Ninous, Saoumi, 20132936 # Montassar, Elkolli , 20137575 import math import random import copy class LinkedList: class _Node: def __init__(self, v, n): self.value = v self.next = n def __init__(self): self._head = None self._size = 0 def __str__(self): ...
#!/usr/bin/env python """Module for testing network conections.""" import re import sys import argparse import socket import logging import ConfigParser import collections Address = collections.namedtuple('address', ('host', 'port', 'servicename')) Family = {getattr(socket, i): i for i in dir(socket) if i.startswith('...
# -*- coding: utf-8 -*- """ Created on Wed Sep 15 19:10:19 2020 @author: ashah """ # # Import Libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd print("Generating Random DataSet for the Neural Network") X = np.vstack([(np.random.rand(10,2)*5), (np.random.rand(10,2)*10)]) # Vertical St...
empty_color = 9 def copy_board(board): n = len(board) res = [[board[j][i] for i in range(n)] for j in range(n)] return res def hash_board(board): res = 0 for i in range(len(board)): for j in range(len(board)): res = res * 10 + board[i][j] return res def clear_color(board, ...
# Copyright (C) 2018 by Kevin L. Mitchell <klmitch@mit.edu> # # 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 applicabl...
from random import randint print("Are you ready to Roll a Dice?? ") is_ready = input("Type r to play... ") if is_ready == 'r': while True: dice_value = randint(1, 6) print(f"You rolled {dice_value}") wanna_continue = input("Wanna play again? (If yes type 'y').. ") if wanna_continu...
import picking, time while True: s = int(input("please enter a value between 0-5 (6 for exit)")) if s == 6: break else: picking.pick(s)
# Name: Navraj (Navie) Narula # CS320: Grammars, Lexing, and Parsing # HW1 # September 16, 2015 # I collaborated with Shahrez Jan, John Gonsalves, and Phong Pham. import re def regexp(tokens): res = "(" for i in range(len(tokens)): if tokens[i] == '$' or tokens[i] =="?" or tokens[i] == '*' or tokens...
""" Author : Robin Singh Implementation Of LCS(Dynamic Approch) Time Complexity : O(MN) """ def lcs(s1, s2): len_s1 = len(s1) #M len_s2 = len(s2) #N arr = [['' for i in range(len_s2)]for x in range(len_s1)] for i in range(len_s1): for j in range(len_s2): if s1[i] == s2[j]: ...
""" Author : Robin Singh Implementation of Queue using linked list """ class Node: def __init__(self,data): self.data = data self.next = None class Linked_list: def __init__(self): self.start = None def enqueu_linkedlist(self,ele): new_node = Node(ele) if self.start...
""" AUTHOR :Robin Singh IMPLEMENTAION OF BINARY SEARCH It Uses Divide And Conquer Approch,Binary search works on sorted arrays Binary search begins by comparing an element in the middle of the array with the target value, If the target value matches the element, its position in the array is returned, If the target valu...
""" Author : Robin Singh Implementation of Min Max Algorithm Using Divide And Conquer Approch In this approach, the array is divided into two halves. Then using recursive approach maximum and minimum numbers in each halves are found. Later, return the maximum of two maxima of each half and the minimum of two minima of ...
list1=["robin","singh",7890,80.98,'y'] list2=['a','b','c','d',2020,"feb"] #Length of the list length_of_list=len(list1) Length_2nd_list=len(list2) print("length of 1st list=",length_of_list) print("length of 2nd list=",Length_2nd_list) #Concatenating my_list = ["zero", "one", "two", "three", "four"] my_new_list = ["f...
#Author : Robin Singh #Shell sort is an algorithm that first sorts the elements far apart from each other and successively reduces #the interval between the elements to be sorted. It is a generalized version of insertion sort #In shell sort, elements at a specific interval are sorted. The interval between the elements ...
""" Author : Robin Singh Currency Converter """ with open('CurrencyData.txt') as r: data = r.readlines() currency_dict = {} for line in data: parsed = line.split("\t") currency_dict[parsed[0]] = parsed[1] r.close() amt = int(input("Entre Amount\n")) print("Entre Currency Name : ") print("Availabl...
def fibbonacchiseries(n): if n ==1: return 0 elif n==2: return 1 else: return fibbonacchiseries(n-1)+fibbonacchiseries(n-2) n= int(input("entre ur number")) print("fibbonacchi series : ",fibbonacchiseries(n))
""" Author : Robin Singh Implementaion of Number Of Coins Change(Number Of ways to get reqd Sum) Time Complexity : O(Coins*Sum) """ def number_of_coins(coins, sum): size = len(coins) arr = [[0 for x in range(sum+1)]for x in range(size+1)] for i in range(size + 1): arr[i][0] = 1 for i in range(1,...
""" Author : Robin Singh Implementation of Jump Search Algorithm """ import math def jump_search(arr,search): low = 0 jump = int(math.sqrt(len(arr))) for i in range(0,len(arr),jump): if arr[i] < search: low = i elif arr[i] == search: return i else: ...
class HighScores(object): def __init__(self, scores): self.scores = scores def latest(self): return self.scores[-1] def highest(self): return max(self.scores) def top(self): return sorted(self.scores, reverse=True)[:3] def report(self): difference = self.h...
n=int(input("enter num")) i=0 sum=0 while n>0: sum=sum+(n%10) n=n//10 i=i+1 print(sum)
n=int(input("enter num")) n1=int(input("enter num")) n2=int(input("enter num")) if n>n1 and n2<n: print("n is max") elif n1>n2 and n<n1: print("n1 is max") elif n2>n and n1<n2: print("n2 is max") else: pass
n=int(input("enter num")) if n%2==0 and n>200: print("nav") elif n%2!=0 and n<200: print("gurukul") else: pass
class UniversityAdmission: applicants = [] accepted = {'Biotech': [], 'Chemistry': [], 'Engineering': [], 'Mathematics': [], 'Physics': []} used = [] score_id = 1 sec_score_id = 0 def __init__(self, number, departments): self.number = number self.departments = departments d...
list_color = ['green', 'orange', 'violet'] print(list_color) index_violet = list_color.index('violet') print(list_color) list_color.insert(index_violet, 'red') print(list_color) list_color.append('yellow') print(list_color) list_color.remove('orange') print(list_color)
""" 给你一个字符串 s,找到 s 中最长的回文子串。 示例 1: 输入:s = "babad" 输出:"bab" 解释:"aba" 同样是符合题意的答案。 示例 2: 输入:s = "cbbd" 输出:"bb" 示例 3: 输入:s = "a" 输出:"a" 示例 4: 输入:s = "ac" 输出:"a"   提示: 1 <= s.length <= 1000 s 仅由数字和英文字母(大写和/或小写)...
#== Python Libraries ==# from abc import ABC, abstractmethod # So we can count the alphabet #==== Food Class (ABSTRACT) ============================================= # CONSTRUCTOR << amount=0, item_type=DEFAULT_TYPE, size=DEFAULT_SIZE >> # self.amount - amount of the item currently in stock # self.sizes - returns the ...
class Menu(): #print list of food def view_menu(self, inventory, menu_choice): available_foods = inventory #This function prints out the menu! print('\n***MAINS:{}***'.format(str.upper(menu_choice))) for key in available_foods.get_list(): if menu_choice == 'wrap': #print the wraps menu if available_...
#Euan McElhoney #16/09/2014 #Math unit Exercises - pytonschool.github.io import math print ("This program will take three numbers multiply the first two and divide that by the third") int1 = float(input("What is your first number? ")) int2 = float(input("What is your second number? ")) int3 = float(input("...
#Euan McElhoney #12/09/2014 #Assignment Exercises - Development + Challenge Exercises import math #Challenge task 1 number1 = float(input("What is your first number? ")) number2 = float(input("What is your second number? ")) division = number1 // number2 remainder = number1 % number2 print("{1} goes in...
import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation fig, ax = plt.subplots() lne, = plt.plot([], []) numPixel = 108 def init(): #initializing the graph/canvas to draw color on ax.set_xlim(-1, 1) ax.set_ylim(-1, 1) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visi...
'''num = int(input("enter the number: ")) rev = int(str(num)[::-1]) print("the reversed number is: ",rev) if num == rev: if num>1: for i in range(2,num): if(num%i)==0: print(num,"it is not a prime number and it is palindrom") break else: ...
'''string = "the quick brown fox jumps over the lazy dog" string=string.casefold() string=set(string) if(len(string) == 27 and " " in string): print("this is a pangram!!") else: print("this is not a pangram")''' my_string = "the quick brown fox jumps over the lazy dog" def pangram(string): alphab...
student_list = {'S 001': ['Math', 'Science'], 'S 002': ['Math', 'English']} print("Original dictionary: ",student_list) d = {} for key,value in student_list.items(): key = key.split() d["".join(key)] = value print("new dictionary is: ",d)
class hello: a = 10 b = 20 def add(self,z): print(self.a+self.b+z) obj = hello() obj.add(50) print(hello.a+hello.b) hello.add(obj,100)
string = "venkateshbabuprattipati" d = {} for i in string: key = d.keys() if i in key: d[i]+=1 else: d[i] = 1 print(d)
n = int(input("enter the number: ")) d = {} for i in range(1,n+1): d[i] = i*i print(d)
from string import punctuation string = "hello there... iam learning python !" new_string = " " for i in string: if i not in punctuation: new_string = new_string+i print(new_string)
my_str = "welcome to python" my_split = my_str.split(' ') my_split.reverse() my_join = ' '.join(my_split) print(my_join)
d = {'Alex': ['subj1', 'subj2', 'subj3'], 'David': ['subj1', 'subj2']} l = [] for i in d.values(): l.append(i) a = len(l[0]+l[1]) print("count of the dictionary values are: ",a)
a = ['ashok', 'hari', 'bhanu', 'anil', 'bharath', 'anvesh', 'uday', 'raja'] d = {} for i in a: s = i.split() if s[0] not in d: d[s[0][0]] = [] d[s[0][0]].append(s[0]) print(d)
d = {'a':500, 'b':5874, 'c': 560,'d':400, 'e':5874, 'f': 20} l = [] for k,v in d.items(): l.append((v,k)) l.sort(reverse=True) a = [] for i in l: a.append(i[1]) print(a[:3])
'''a = ["apple","orange","mango","bananaa"] b = "" for i in a: if len(i)>len(b): b = i print("longest word is: ",b)''' a = ["apple","orange","mango","bananaa"] b = [] for i in a: b.append((len(i),i)) print(b) b.sort(reverse=True) print("longest word is: ",b[0][1])
""" Escribir un programa que solicite una cantidad (n) y que calcule el factorial de un número. Por ejemplo: n: 8 El Factorial es: 40320 """ n = int(input()) if n == 0: factorial = 1 else: contador = 1 factorial = 1 while contador <= n: factorial = 0 # reemplazar esta linea por una expresi...
# Clase array de enteros class ArrayInt: #Constructor def __init__(self, n): self._elementos = [0] * n def elementos(self): return self._elementos # valida que se ingresen enteros def set_elemento(self, indice, valor): if type(valor) == int: self._elementos[indic...
# Escribir una funcion recursiva que encuentre el mayor elemento de una lista def mayor(l): if len(l) == 0: return 0 if len(l) == 1: return l[0] if len(l) == 2: return l[0] if l[0] > l[1] else l[1] if len(l)> 2: m = l[0] if l[0] > l[1] else l[1] if m > l[2]: ...
# aceptar un entero n con la funcion input # imprimir el valor del n-avo numero armónico # https://es.wikipedia.org/wiki/N%C3%BAmero_arm%C3%B3nico n = int(input('ingrese numero: ')) total = 0.0 for i in range(1, n+1): # adiciona el i-esimo termino a la suma total = total + 1.0 / i print(total)
# This is a global variable a = 0 if a == 0: # This is still a global variable b = 1 def my_function(c): # this is a local variable d = 3 print(c) print(d) # Now we call the function, passing the value 7 as the first and only parameter my_function(7) # a and b still exist print(a) print(b) # c a...
# hallar los numeros primos del 1 al 100 def primo(numero): no_es_primo = False for x in range(2, numero): if ((numero % x) == 0): no_es_primo = True return no_es_primo print('primos: ', end='') for x in range(1, 101): if n...
""" 2. Que genere el producto de numeros impares de 1 hasta N """ N = int(input()) def prod(N): inicio = 1 producto = 0 while inicio <= N: producto = producto * inicio inicio = inicio + 2 return producto producto = prod(N) print(producto)
# Escribir una función recursiva que genere el resultado de la división entera del número a y b por restas sucesivas. def division_entera(a, b): if b > a: return 0 return division_entera(a - b, b) + 1
# escriba un programa que permita hallar las raices de una ecuacion # cuadratica. si se conoce la formula cuadratica import math A = float(input('Ingrese A: ')) B = float(input('Ingrese B: ')) C = float(input('Ingrese C: ')) discriminante = B**2 - 4*A*C if discriminante > 0: raiz1 = (B + math.sqrt(discriminante)...
# array de dos dimensiones a = [[1, 2, 3], [3, 4, 4]] # creando un array vacio b = [] for i in range(3): row = [0.0] * 3 b += [row] print(b)
nombre=input("diga el nombre del archivo") archivo=open(nombre,"r") texto=input("ingrese el texto a buscar") for linea in archivo: if linea.find(texto)>-1: print(linea,end="")
import time #----------------------------------------------------------------------- class Stopwatch: # Construct self and start it running. def __init__(self): self._creationTime = time.time() # Creation time # Return the elapsed time since creation of self, in seconds. def elapsedTime(sel...
key = '' frutas = {} while key != '*': key = input('ingrese nombre de fruta:') valor = int(input('ingrese precio:')) if key != '*': frutas[key] = valor for k in frutas.keys(): frutas[k] = frutas[k] * 1.18 print('tabla de precios') for k, v in frutas.items(): print(' {:>10} {:>10}'.format(k...
# Escribir un programa en Python que se ingrese como dato la coordenada de un punto y el programa indique el cuadrante # al que pertenece el punto o si se encuentra en el centro del plano cartesiano x = float(input('ingrese X: ')) y = 0 if x > 0 and y > 0: print('cuadrante I') elif x > 0 and y < 0: print(' cua...
import string #Generar todas las letras en una lista s = string.ascii_uppercase l = [] for x in s: l.append(x) print(l)
#programa que simula un hospital pacientes = [] separador = "" contador = 1 while separador != "#": separador = input("Ingrese el apellido del paciente {}: ".format(contador)) if separador != "#": pacientes.append(separador) contador = contador+1 #atencion firstIn-firstOut (FIFO) copia_pacientes =...
# Calcular el promedio de numeros ingresados en una lista # ingresar los valores a la lista s = [2, 3, 4, 4, 4, 6, 6, 7, 8] total = 0.0 promedio = 0.0 # usar for i in range(): print(promedio)
""" Escribir un programa que permita leer 7 valores que representan a las notas de un examen. El programa debe calcular el promedio e imprimirlo. """ TOTAL_NOTAS = 7 contador = 1 total = 0 while contador <= 7: nota = float(input('ingrese la nota ' + str(contador) + ': ')) total += nota contador += 1 pro...
from random import randint as random # given a hash target # generate a word with a number of letters such that the average # of the hash target divided by that number will be between 65 and 122 # fill each letter in order # if the last letter to be filled must have a prohibited ascii value below 65 # remove the firs...
class storeLocation: """ The location of a given stored Parsed_SFVExpr in the Store Always a Natural Number """ def __init__(self): self.loc = 0 self.gen = 0 def __init__(self, location, gen =0): self.loc = location self.gen = gen def __eq__(self, other): ...
# Program 02d : Power series solution of a second order ODE. # See Example 8. from sympy import dsolve, Function, pprint from sympy.abc import t x = Function('x') ODE2 = x(t).diff(t,2) + 2*t**2*x(t).diff(t) + x(t) pprint(dsolve(ODE2, hint='2nd_power_series_ordinary', n=6))
# Program 01g: A program that animates a simple curve. #http://louistiao.me/posts/notebooks/embedding-matplotlib-animations-in-jupyter-notebooks/ # Remember to run the Module (or type F5). import numpy as np from matplotlib import pyplot as plt from matplotlib import animation from IPython.display import HTML fi...
#!/usr/bin/env python def mean(list1): sum = 0 for i in list1: sum += 1 b = sum / len(list1) return b print(mean([1,2,3,4]))
def dict_of_square(n): d = {} for i in range(1, n+1): d[i] = i*i return d print(dict_of_square(8))
"""This function is to check if string is a palindrome or not. If string is not a palindrome, then it will return the palindrome version. Also will return count how many letters added to make palindrome""" def make_palindrome(str1): s = str1.lower() r = s[::-1] if s == r: return "This is already ...
Table_Number=17 #Iterate 10 times from i(if you want to print table for 10 times) for i in range(1,11): print (Table_Number, "X", i, "=", i*Table_Number)
''' Faça um programa que leia o ano de nascimento de um jovem e informe, de acordo com a sua idade, se ele ainda vai se alistar ao serviço militar, se é a hora exata de se alistar ou se já passou do tempo do alistamento. Seu programa também deverá mostrar o tempo que falta ou que passou do prazo. ''' from datetime im...
''' Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa. Pergunte o valor da casa, o salário do comprador e em quantos anos ele vai pagar. A prestação mensal não pode exceder 30% do salário ou então o empréstimo será negado. ''' valorCasa = float(input('Digite o valor da casa:\nR$ ')) sal...
''' Faça um programa que leia um nome de usuário e a sua senha e não aceite a senha igual ao nome do usuário, mostrando uma mensagem de erro e voltando a pedir as informações. ''' while 1: nome = str(input('Nome de usuário: ')).strip() senha = str(input('Senha: ')).strip() if nome != senha: break ...
''' Um professor quer sortear um dos seus quatro alunos para apagar o quadro. Faça um programa que ajude ele, lendo o nome dos alunos e escrevendo na tela o nome do escolhido. ''' from random import choice aluno1 = str(input('Primeiro aluno:\n')) aluno2 = str(input('Segundo aluno:\n')) aluno3 = str(input('Terceiro al...
''' Desenvolva um programa que leia seis números inteiros e mostre a soma apenas daqueles que forem pares. Se o valor digitado for ímpar, desconsidere-o. ''' soma = 0 cont = 0 for c in range(1,7): num = int(input('Digite um valor: ')) if num % 2 == 0: soma += num print('A soma dos números é {}'.format(...
''' Crie um programa que tenha uma dupla totalmente preenchida com uma contagem por extenso, de zero até vinte. Seu programa deverá ler um número pelo teclado (entre 0 e 10) e mostrá-lo por extenso. ''' cont = ('zero', 'um', 'dois', 'três', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove', 'dez') while True: núme...
''' Mostre a tabuada de um número que o usuário escolher, utilizando um laço for. ''' numero = int(input('Digite um número para ver a sua tabuada: ')) for c in range(1, 11): print('{} x {:2} = {}'.format(numero, c, numero*c))
''' Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, crie duas listas extras que vão conter apenas os valores pares e os valores ímpares digitados, respectivamente. Ao final, mostre o conteúdo das três listas geradas. ''' lista = [] pares = [] impares = [] while True: lista.append(...
''' Faça um programa que calcule a área de um quadrado, em seguida mostre o dobro desta área para o usuário. ''' medidaLado = float(input('Digite a medida de um dos lados do quadrado (cm): ')) área = pow(medidaLado, 2) print('Área do quadrado: {:.2f}cm²'.format(área)) print('Dobro da área: {:.2f}cm²'.format(área*2))
''' Crie um programa que leia o nome e o preço de vários produtos. O programa deverá perguntar se o usuário vai continuar ou não. No final, mostre: A) qual é o total gasto na compra. B) quantos produtos custam mais de R$1000. C) qual é o nome do produto mais barato. ''' totalCompra = maiorQueMil = menorPreço = contado...
num1 = float(input("Digite o primeiro número: ")) operator = input("Digite o operador: ") num2 = float(input("Digite o segundo número: ")) #sum if operator == "+": result = num1 + num2 elif operator == "-": result = num1 - num2 elif operator == "/": result = num1 / num2 elif operator == "*": result = n...
class QuizBrain: def __init__(self, bank): self.question_bank = bank self.question_number = 0 self.score = 0 def next_question(self): ans = input(f"Q.{self.question_number+1}: {self.question_bank[self.question_number].question} (True / False): ") self.check_answe...
def poly_hash(a, m, s): if len(s) > 0: p_hash = ord(s[0]) for c in s[1:]: p_hash = (p_hash * a + ord(c)) % m return p_hash % m return 0 def main(): with open("../input.txt", "r") as reader: a = int(reader.readline()) m = int(reader.readline()) s ...
''' Created on 5 dic. 2019 @author: Ruby ''' print("Las temperaturas deben ser con el formato 34.12C o 78.4F") cantidad = int(input("Cuantas temperaturas desea ingresar?")) far=[] cen=[] temperaturas=[] for i in range(cantidad): temperaturas.append(input(f"Ingresa temperatura {i+1}:").upper()) for i ...
''' Created on 6 dic. 2019 @author: Ruby ''' candidatos = [["Dist", "Cand", "Cand", "Cand", "Cand"], [" ", " A ", " B ", " C ", " D "], [" 1 ", " 194", " 48", " 206", " 45"], [" 2 ", " 180", " 20", " 320", " 16"], [" 3 ", " 221", " 90", " 140", " ...
''' Created on 27 nov. 2019 @author: Ruby ''' print("===Programa que muestra el promedio de 5 calificaciones ===\n") cal1 = int (input("Ingresa la calificacion 1: ")) cal2 = int (input("Ingresa la calificacion 2: ")) cal3 = int (input("Ingresa la calificacion 3: ")) cal4 = int (input("Ingresa la calificacion 4: ")) c...
''' Created on 4 dic. 2019 @author: Ruby ''' print("Programa que obtiene el RFC de una persona\n") nombre = input("Ingresa tu nombre: ") apellidoPaterno = input("Ingresa tu apellido paterno: ").lower() apellidoMaterno = input("Ingresa tu apellido materno: ") fecha = input("Ingresa tu fecha de nacimiento en formato dd...
''' Created on 4 dic. 2019 @author: Ruby ''' print("Programa que lee una nombre completo e indique cuantas letras son vocales y\n" "cuantas consonantes, ademas si la cantidad de vocales y consonantes es par o impar\n") nombreC = input("Ingresa tu nombre completo:").lower() vocales=0 espacios=0 for i in nombreC: ...
#! /usr/bin/python import sys import re def fetch_text_list(filename_list): text_list = [] for filename in filename_list: with open(filename, 'r') as data_file: file_text = data_file.read() tmp_text_list = re.findall('[A-Z]+', file_text) text_list += tmp_text_list return text_list def calculate_tex...
def simple_interest(p,r,t): return (p*r*t)/100 p=float(input("enter the principle")) r=float(input("enter the rate")) t=int(input("enter the time")) Si=simple_interest(p,r,t) print("Simple interest of p={},r={},t={} is ={}".format(p,r,t,Si))