text stringlengths 37 1.41M |
|---|
import string
upper = ""
if __name__ == '__main__':
print("This program will encrypt your input using ROT13.")
print("Please enter the text to be encrypted")
encrypt = input()
for k in encrypt:
if k.isalpha() == False:
print(k, end='')
else:
if k.isupper():
... |
#return a sequence reversed (just with slicing)
#original seuqence
seq1 = [1,2,3,4,5,6,7,8,9,10,'a','b','c','d']
#print the original sequence
print("original sequence",seq1)
seq2 = seq1[::-1]
print("sequence reversed is:.......",seq2)
|
val=[]
continuar=True
# x=x3[:] é o mesmo que x=x1[o:len(x1)]
while continuar==True:
numero=input("digite um número:")
if "0"<=numero<="9":
int(numero)
val.append(numero)
elif numero=="":
continuar=False
else:
print("por favor, digite um número valido... |
def max_recursivo(lista):
i = len(lista) -1
if len(lista) == 1:
return lista[0]
else:
if lista [i] > lista[i-1]:
lista.pop(i-1)
return max_recursivo(lista)
else:
lista.pop(i)
return max_recursivo(lista)
lista1 = [76,34,5,6,20... |
# Your code here
# Read from the file.
with open("robin.txt") as f:
words = f.read()
word_list = words.split(' ')
# create a hash table
histogram = {}
# iterate through the word list and make each word the key, and the value a list
# if the word is in the hash table already, add a hash symbol to the value list.
... |
## Challenge 1: PyBank
#* In this challenge, you are tasked with creating a Python script for analyzing the financial records of your company.
# [budget_data.csv](PyBank/Resources/budget_data.csv).
# The dataset is composed of two columns: `Date` and `Profit/Losses`.
#* Your task is to create a Python script that ... |
#!/usr/bin/python
# Pseudo code: controller loop for house heating
from datetime import datetime
class Schedule:
pass
class EnvironmentSensor:
pass
class HeatingSystem:
pass
class House:
pass
schedule = Schedule()
sensor = EnvironmentSensor() # the Particle
heating_system = Lyric() # the H... |
print "Biology Testing on Ecology"
print "By Joshua Bingham"
print "This test will test your knowledge about Ecology and show you what areas you need to improve in."
print "When answering a question, type the number of the answer you think is true."
#name = str(input("What is your name?"))
score = 0
score = int(score)
... |
'''
dictionary.py
Leif Anderson 7/8/17
'''
dojo = {
'Ninjas': [
{'fname' : 'Blaze', 'lname' : 'Hayes'},
{'fname' : 'Master', 'lname' : 'Chief'},
{'fname' : 'Steve', 'lname' : 'Jobs'},
{'fname' : 'Bill', 'lname' : 'Gates'}
],
'Sensei': ... |
def longest_oscillation(L):
"""
this is the bottom-up DP solution for the task 1
@param L: a list
@return: a tuple with the length if longest oscillation and the list of longest oscillation
@time complexity: O(N^2) where n is the size of the list
@space complexity: O(N) where n is the size... |
import math
def get_digit(num, digit):
"""
this function simplyt get the right most digit for the input number
@param num: a integer
@param digit: the which digit should it get
@return the specific digit of the integer
@time complexity: O(1)
@space complexity: O(1)
"""
return num[-d... |
a=int(input("enter a number"))
temp=a
rev=0
while(a>0):
remainder=a%10
rev=(rev*10)+remainder
a=a//10
if(rev==temp):
print("is palindrome")
else:
print("not a palindrome") |
def reverse(arr):
n = len(arr) - 1
for i in range(len(arr)/2):
arr[i], arr[n - i] = arr[n - i], arr[i]
return arr
def palindrome(s):
n = len(s) - 1
for i in range(len(s)/2):
if s[i] != s[n - i]:
return False
return True
if __name__ == "__main__":
#in_arr = [int... |
def subset_sum(subsets):
output = []
for subset in subsets:
if not reduce(lambda x,y: x + y, subset):
output.append(subset)
return output
def subset(arr):
if not len(arr):
return [""]
sub = subset(arr[1:])
return [arr[0] + el for el in sub] + sub
if __name__ == "__... |
def subset(arr):
if not len(arr):
return [[]]
sub = subset(arr[1:])
return [[arr[0]] + s for s in sub] + sub
if __name__ == "__main__":
in_arr = [int(i) for i in raw_input("Enter the array: ").split(",")]
print subset(in_arr)
|
def find_all_nums(n):
out = []
if n == 0:
return [[]]
for i in range(1, n + 1):
nums = find_all_nums(n-i)
for v in nums:
out.append(v + [i])
return out
if __name__ == "__main__":
print find_all_nums(int(raw_input("Enter the number: ")))
|
def intersect_all(arr):
return reduce(intersection, arr)
def intersection(a, b):
return [el for el in a if el in b]
if __name__ == "__main__":
in_str = raw_input("Enter the array: ").split(',')
print intersect_all(in_str)
|
#!/usr/bin/python
import sys
#Create list of alphabetic chars to check against
CHAR = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
CHAR = dict.fromkeys(list(CHAR))
def main():
#Input validation
argc = len(sys.argv) - 1
if argc != 1:
print("Improper number of arguments")
quit()
elif (not sys.argv[1] == "-e") and (not sys.a... |
all_frutes=["mango","orange","bnana"]
for frutes in all_frutes:
print(frutes)
# _in a for loops
n=1
for _ in range(100):
print(n)
n+=1
|
import time
class meas:
def __init__(self, message="Time measured", average_on=1):
self.time_a = 0
self.time_b = 0
self.times = []
self.message = message
self.average_on = average_on
def start(self):
self.time_a = time.time()
def end(self):
self.tim... |
class Solution:
def maxValue(self, n, x):
# We want to separate between two cases where the integer n is
# negative and where it is positive.
if n[0] == '-':
# We start at i =1 to bypass the negative sign
i = 1
length = len(n)
... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def list_repr(self):
# Here we will list the numbers in the ListNode in a list
# representation
list_integer = []
# We store our curr... |
#Name:Andrew Hunter, Greg Francis, Preston Fry
#Date:September 18, 2014
#Assignment:Ch. 3 Programming Excercises
#Problem: 11
#Purpose of the program:display the points earned for the number of books
#purchased by the customer
#Assumptions:if the customer doesn't purchase any books, they don't get any points
#if... |
#Name:Andrew Hunter, Greg Francis, Preston Fry
#Date:October 7, 2014
#Assignment:Ch. 5 Programming Excercise
#Problem: 21
import random
def main():
computernumber=random.randint(1,3)
humanword=input('rock, paper, or scissors')
humannumber=from_word(humanword)
computerword=from_number(computernumber)
... |
#Name:Andrew Hunter
#Date:October 7, 2014
#Assignment:Ch. 4 Programming Excercises
#Problem: 14
#Purpose of the program:
steps=6
for r in range(steps):
print('#', end='')
for c in range(r):
print(' ', end='')
print('#')
|
#Name:Andrew Hunter, Greg Francis, Preston Fry
#Team Name:Funky Town Monkey Pimps
#Date:September 2, 2014
#Assignment:Ch. 2 Programming Excercises
#Problem: 2
#Purpose of the program:Display profit from total sales.
#Assumptions:Profit is 23% of total sales
#Other Comments:
total_sales=float(input('What are the total s... |
#Name:Andrew Hunter, Greg Francis, Preston Fry
#Date:September 18, 2014
#Assignment:Ch. 3 Programming Excercises
#Problem: 14
#Purpose of the program:to calculate a persons body mass index(BMI)
#Assumptions:BMI = weight * 703//height**2
#Other Comments:optimal bmi is between 18.5 and 25
#if bmi is under 18.5 the... |
#Name:Andrew Hunter, Greg Francis, Preston Fry
#Team Name: The Funky Town Monkey Pimps
#Date:September 2, 2014
#Assignment:Ch. 2 Programming Excercises
#Problem:10
#Purpose of the program:To find amount of ingredients needed
#Assumptions:The recipe is correct
#Other Comments:
cookies=int(input('How many cookies... |
# 328 Odd Even Linked List
class Solution(object):
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None:
return
pointer1 = head
pointer2 = head.next
conn = head.next
... |
def shift(li):
temp = li[0]
for i in range(1, len(li)):
li[i-1] = li[i]
li[-1] = temp
return li
class Solution(object):
def productExceptSelf(self, nums):
output = []
for i in range(len(nums)):
shift... |
"""
Задание 4.
Приведены два алгоритма. В них определяется число,
которое встречается в массиве чаще всего.
Сделайте профилировку каждого алгоритма через timeit
Попытайтесь написать третью версию, которая будет самой быстрой.
Сделайте замеры и опишите, получилось ли у вас ускорить задачу.
"""
from timeit import time... |
"""
Задание 3.
Определить количество различных подстрок с использованием хеш-функции.
Дана строка S длиной N, состоящая только из строчных латинских букв.
Подсказка: примените хеши и множества
рара:
рар
ра
ар
ара
р
а
"""
count = 0
my_str = "papa"
uniq = []
for i in range(len(my_str)):
for j in range(len(my_str),... |
from datastructures.linked_list.linked_list import LinkedList
def test_instance():
ll = LinkedList()
assert isinstance(ll, LinkedList)
#Add_First To Empty LinkedList
def test_LinkedList_insert():
test_LinkedList = LinkedList()
test_LinkedList.insert(0)
assert test_LinkedList.head.value == 0
#... |
x = str(input("Введіть слово:"))
y = ""
for i in x[::-1]:
y = y + i
print(y) |
def longest(s):
"""
:type s: str
:rtype: int
"""
max_before = max_now = start = 0
dict = {}
for index, i in enumerate(s):
if i in dict and dict[i] >= start:
max_before = max(max_before, max_now)
max_now = index - start - 1
start = dict[i] + 1
... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data_main=pd.read_csv("Medals.csv")
print data_main.head()
a=data_main["Athlete"].unique().tolist()
print "Valor de a::",len(a)
data_country=pd.read_csv("Athelete_Country_Map.csv")
print data_country.head()
print len(data_country)
duplicado=data_... |
# https://adventofcode.com/2020/day/5
file = open("day5_data", "r")
ticket_list = file.read().splitlines()
def parse(ticket, row_min, row_max, col_min, col_max):
row = None
column = None
for letter in ticket[0:8]: # parse the first 7 characters
if letter == "F":
row_max = row_min + (... |
# https://adventofcode.com/2020/day/7
import re
file = open("day7_data", "r")
data = file.read().splitlines()
graph = {}
for line in data:
if re.search('contain\sno\sother\sbags', line):
continue
# building the graph backwards, with the keys being the bags contained by their values
# this simplifi... |
a = input()
b = [1,0,0]
for move in a:
if move == 'A':
b[0],b[1] = b[1],b[0]
elif move == 'B':
b[1],b[2] = b[2],b[1]
else:
b[0],b[2] = b[2],b[0]
for i in range(len(b)):
if b[i] == 1: print(i+1)
|
a = int(input())
for i in range(a):
print("{} Abracadabra".format(i+1)) |
class Animal (object):
def __init__(self,sound,name,age,favorite_color):
self.sound=sound
self.name=name
self.age=age
self.favorite_color-favorite_color
def eat(self,food):
print("yummy!!"+self.name+"is eating"+ food)
def description(self):
print(self.name + "is" + self.age+ "years old and loves the colo... |
from turtle import *
#import random
# colormode(255)
class Rectangle(Turtle):
def __init__(self,width,height):
Turtle.__init__(self)
register_shape("rectangle",((0,0),(0,height),(width,height),(width,0),(0,0)))
self.shape("rectangle")
self.setheading(90)
class Square(Turtle):
def __init__(self,size):
Recta... |
a, b = (int(s) for s in input().strip().split(' '))
if a <= 0 and 0 <= b:
print('Zero')
elif 0 < a or (b-a)%2 == 1:
print('Positive')
else:
print('Negative')
|
from math import sqrt
from sympy import factorint
def isSquare(n):
return n == (int(sqrt(n)))**2
n = 10**12
ans = 0
for r in range(1, int(sqrt(n))):
fac = factorint(r)
_r = 1
for f in fac:
_r *= f ** ((fac[f]+1) // 2)
d = r + _r
a = d**3 // r + r
while a < n:
if isSquare(a)... |
#!/usr/bin/python3
"""
Contains the definition of the read_file function
"""
def read_file(filename=""):
"""Reads a text file and prints it to stdout
Args:
filename (str): name of the file to be read
"""
with open(filename, encoding="UTF-8") as f:
for line in f:
print(line... |
#!/usr/bin/python3
'''
check if a especific object is a kind of instance of a class
'''
def is_kind_of_class(obj, a_class):
'''
check if object belongs a class or heritance
args:
obj: object
a_class: class to check
Return:
True or false
'''
r... |
#!/usr/bin/python3
def uniq_add(my_list=[]):
adds = 0
for i in set(my_list):
adds += i
return(adds)
|
#!/usr/bin/python3
def multiply_by_2(a_dictionary):
a_dictionary2 = {}
for key, val in a_dictionary.items():
a_dictionary2[key] = 2 * val
return(a_dictionary2)
|
#!/usr/bin/python3
"""
Contains the definition of the class Square.
"""
from models.rectangle import Rectangle
class Square(Rectangle):
"""Definition of class Square that inherits from class Rectangle"""
def __init__(self, size, x=0, y=0, id=None):
"""Initialize an instance of class Square"""
... |
#!/usr/bin/python3
"""
Contains the definition of the append_write function
"""
def append_write(filename="", text=""):
"""Appends a string at the end of the text file and returns the
number of chars written
Args:
filename (str): name of the file to be written to
text (str): text to be... |
#!/usr/bin/python3
'''
Class BaseGeometry
'''
BaseGeometry = __import__("7-base_geometry").BaseGeometry
class Rectangle(BaseGeometry):
'''
Represent a class Rectangle heritance from BaseGeometry
'''
def __init__(self, width, height):
'''
define width and height of Rectangle... |
class Solution:
def simplifyPath(self, path):
"""
:type path: str
:rtype: str
"""
path_list = path.split("/")
path_stack = []
for path in path_list:
if path != "/" and path != "." and path != ".." and path != "":
path_stac... |
# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
class NestedInteger:
def __init__(self, value=None):
"""
If value is not specified, initializes an empty list.
Otherwise initializes a single integer eq... |
class Solution:
def search(self, nums: list, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
def search_index(nums: list, low: int, high: int):
if len(nums) == 0:
return -1
mid = (int)((low + high) / 2)
... |
class TrieNode:
def __init__(self, ch):
self.subs = [None] * 26
self.isEnd = False
self.ch = ch
def addWord(self, word):
nodePoint = self
for i, ch in enumerate(word):
if nodePoint.subs[ord(ch) - ord('a')] == None:
nodePoint.subs[ord(ch) - ord... |
class Solution:
def groupAnagrams(self, strs: list):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
def generate_tuple_key(_str):
a = [0] * 26
for char in _str:
a[ord(char) - ord('a')] += 1
return tuple(a)
s... |
import sys
import matplotlib
matplotlib.use('TkAgg')
import numpy as np
import scipy.io
import scipy.spatial
import matplotlib.pyplot as plt
import math
from pca import PCA
# TODO: Implement euclidean distance between two vectors
def euclideanDistance(a, b):
'''
:param a: vector
:param b: vector
:ret... |
"""
4. Median of Two Sorted Arrays
Hard
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
"""
class Solution:
def findMedianSortedArrays(... |
def checkParity(byte):
parity = True
for bit in byte:
if bit == '1':
parity = not parity
return parity
for line in open('temp.txt'):
for byte in line.split():
if(checkParity(byte)):
print(byte[:-1])
|
## Victor Fabio and Dan Wolf
##
## 11/17/13
##
## This program runs a game in which hamburgers fly across the screen and the player has to catch
## them and eat them before they leave the screen. If they miss too many, the game is over.
##
## For this game we used the python and pygame documentation.
#import... |
#!/usr/bin/python
#coding:utf-8
#内置函数open()
#打开一个文件
#打开一个参数,标识我要打开的文件名为python.txt
#第二个参数,表示打开文件的模式是w,
# 表示打开文件的模式是ww打开一个文件只用于写入,如果该文件已存在则打开文件
# 并从头开始编辑,即原有内容被删除,
# 如果该文件不存在,穿件新文件
#open()后会返回一个对象,file = open()把这个对象保存在file
# file =open('F:/pythonlanguage2/cxy/test.txt','w')
# file.close()
# print('文件名称',file.name)
# prin... |
from player import Player
from human import Human
from computer import Computer
class Game:
# 1. A “friendly” welcome, and display the rules
# 2. Choose single player (Human vs. AI) or multiplayer (Human vs. Human)
# 3. Players enter names
# 4. How many rounds? (Remember that only three are required for the user story... |
'''
Python Homework Assignment #6
Advanced Loops
By: Hieu Nguyen
'''
# Details:
# Create a function that takes in two parameters: rows, and columns, both of which are integers. The function should then proceed to draw a playing board (as in the examples from the lectures) the same number of rows and columns as spec... |
'''
calculate chi squared distance between two histograms
'''
def chisquared(a,b):
chi = 0.0
for x,y in zip(a,b):
#print x,y
if(x+y>0):
chi += (float(x-y)**2 / float(x+y))
return chi
if __name__=='__main__':
print chisquared([1,2],[3,4])
|
# Factorial digit sum
# Problem 20
# n! means n (n 1) ... 3 2 1
# For example, 10! = 10 9 ... 3 2 1 = 3628800,
# and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
# Find the sum of the digits in the number 100!
from math import factorial
digits = list(str(factorial(100)))
pr... |
# Smallest multiple
# Problem 5
# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
# What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
def divisible_by(n, divisor):
return n % divisor == 0
i, n = 20, 20
while... |
from tkinter import *
import random
from tkinter import messagebox
answers = [
"python",
"java",
"swift",
"canada",
"india",
"america",
"london",
]
words = [
"nptoyh",
"avja",
"wfsit",
"cdanaa",
"aidin",
"aiearcm",
"odnlon",
]
num = rand... |
import random
from random import shuffle
Playerchar = [{"name": "Ronaldo", "Shoot" : 9.5, "Passing": 6.0, "Speed": 9.0},
{"name": "Messi", "Shoot" : 9.0, "Passing": 9.5, "Speed": 7.0},
{"name": "Ramos", "Shoot" : 7.0, "Passing": 7.0, "Speed": 5.0},
{"name": "Buffon", "Shoot" : 6.0, "Passing": ... |
class Padlock(object):
def __init_(self, combination):
self.combination = combination
self.isOpen = False
def open(self, combination_entered):
if self.isOpen:
print("The lock is alread open")
else:
if self.combination != combination_entered:
... |
import datetime
class LecturerDirectory:
def __init__(self, name, tele_Num, office_Num, subject, start_Year):
self.name = name
self.tele = tele_Num
self.office = office_Num
self.subject = subject
self.start_Y = start_Year
def change_Name(self, newName):
if newNa... |
import graphics as g
import math
def areaOfCircle(radius):
return math.pi * (radius ** 2)
def circumferenceOfCircle(radius):
return 2 * math.pi * radius
def areaOfCircle(radius):
return math.pi * radius ** 2
def circleInfo():
radius = float(input("Enter for radis: "))
print("Area: ", areaOfCircl... |
from Polygon import Polygon
import math
class Rectangle(Polygon):
def __init__(self, height, width):
Polygon.__init__(self, [height, width, height, width])
def calculateRectangleArea(self):
a = self.sides[0]
b = self.sides[1]
return a * b
def calculat... |
def sayName():
print("Will")
def sayHelloWorld():
print("Hello...")
print("... World!")
def euros2pounds():
euro = float(input("Please enter value: "))
print("Converted = £", euro * 1.09)
def addNum():
num1 = int(input("Enter Num1: "))
num2 = int(input("Enter Num2: "))
sum = num1 + n... |
kilos = eval(input("Enter a weight in kilograms: "))
pounds = 2.2 * kilos
print("The weight in pounds is", pounds)
|
from Polygon import Polygon
import math
class Hexagon(Polygon):
def __init__(self, side):
Polygon.__init__(self, [side] * 6)
def calculateHexagonArea(self):
a = self.sides[0]
area = ((3 * math.sqrt(3))/2)* (a**2)
return area
def calculate... |
from nltk.tokenize import sent_tokenize
def lines(a, b):
"""Return lines in both a and b"""
#take in string inputs a, b, split each string into lines, compute a list of all lines that appear in both a and b
lines_a = set(a.split('\n'))
lines_b = set(b.split('\n'))
#return the list
return lines_... |
# Import libraries necessary for this project
import numpy as np
import pandas as pd
from IPython.display import display # Allows the use of display() for DataFrames
# Set a random seed
import random
random.seed(42)
# Load the dataset
in_file = 'titanic_data.csv'
# Store the 'Survived' feature in a new variable and ... |
import tkinter as tk
from tkinter import ttk
class Aplicacion:
def __init__(self):
self.ventana1=tk.Tk()
self.label1=ttk.Label(text="Ingrese nombre")
self.label1.grid(column=0, row=0)
self.nombre=tk.StringVar()
self.entry1=ttk.Entry(self.ventana1, width=40, textvariable=self... |
import sys
if sys.version_info.major == 2:
nombre1=raw_input("Ingrese el primer nombre:")
nombre2=raw_input("Ingrese el segundo nombre:")
else:
if sys.version_info.major == 3:
nombre1=input("Ingrese el primer nombre:")
nombre2=input("Ingrese el segundo nombre:")
print("Listado alfabetico:")
... |
while True:
try:
valor1=int(input("Ingrese primer valor:"))
valor2=int(input("Ingrese segundo valor:"))
suma=valor1+valor2
print("La suma es",suma)
except ValueError:
print("debe ingresar números.")
respuesta=input("Desea ingresar otro par de valores?[s/n]")
i... |
numero=int(input("Ingrese un numero positivo de 1 o 2 digitos:"))
if numero > 9:
print('el numero tiene dos digitos')
else:
print('el numero tiene un digito')
|
def cargar():
empleados={}
continua="s"
while continua=="s":
legajo=int(input("Ingrese el numero de legajo:"))
nombre=input("Ingrese el nombre del empleado:")
profesion=input("Ingrese el nombre de la profesion:")
sueldo=float(input("Ingrese el sueldo:"))
empleados[leg... |
lista=[]
for x in range(5):
valor=int(input("Ingrese valor:"))
lista.append(valor)
menor=lista[0]
posicion=0
for x in range(1,5):
if lista[x]<menor:
menor=lista[x]
posicion=x
print("Lista completa")
print(lista)
print("Menor de la lista")
print(menor)
print("Posicion del menor en la lista"... |
class Lista:
def __init__(self, lista):
self.lista=lista
def imprimir(self):
print(self.lista)
def __add__(self,entero):
nueva=[]
for x in range(len(self.lista)):
nueva.append(self.lista[x]+entero)
return nueva
def __sub__(self,entero):
nue... |
numero1 = int(input('Ingresar primer numero:'))
numero2 = int(input('Ingresar segundo numero:'))
numero3 = int(input('Ingresar tercer numero:'))
numero4 = int(input('Ingresar cuarto numero:'))
suma = numero1+numero2
producto = numero3*numero4
print('la suma del primero con el segundo es:')
print(suma)
print('el product... |
from urllib import request
import json
codigo=input("Ingrese el código de artículo a consultar:")
pagina=request.urlopen(f"http://localhost/pythonya/retornarunarticulo.php?codigo={codigo}")
datos=pagina.read().decode("utf-8")
lista=json.loads(datos)
if len(lista)>0:
print(f"Descripción:{lista[0]['descripcion']}")
... |
def cargar():
alumnos={}
for x in range(3):
dni=int(input("Ingrese el numero de dni:"))
listamaterias=[]
continua="s"
while continua=="s":
materia=input("Ingrese el nombre de materia que cursa:")
nota=int(input("Ingrese la nota:"))
listamateria... |
lado=input("Ingrese la medida del lado del cuadrado:")
lado=int(lado)
superficie=lado*lado
print("La superficie del cuadrado es")
print(superficie) |
sueldo=int(input("Ingrese sueldo:"))
antiguedad=int(input("Ingrese antiguedad:"))
print("Sueldo a pagar")
if sueldo<500 and antiguedad>=10:
sueldoapagar = sueldo * 1.20
else:
if sueldo<500:
sueldoapagar = sueldo * 1.05
else:
sueldoapagar=sueldo
print(sueldoapagar) |
class Socio:
def __init__(self):
self.nombre=input("Ingrese el nombre del socio:")
self.antiguedad=int(input("Ingrese la antiguedad:"))
def imprimir(self):
print(self.nombre,"tiene una antiguedad de",self.antiguedad)
def retornar_antiguedad(self):
return self.antiguedad
... |
lista1=[0,1,2,3,4,5,6]
print(lista1)
print(lista1[-1]) # 6
print(lista1[-2]) # 5
|
def menor_valor():
valor1=int(input("Ingrese primer valor:"))
valor2=int(input("Ingrese segundo valor:"))
valor3=int(input("Ingrese tercer valor:"))
print("Menor de los tres")
if valor1<valor2 and valor1<valor3:
print(valor1)
else:
if valor2<valor3:
print(valor2)
... |
num1=int(input("Ingrese primer valor:"))
num2=int(input("ingrese segundo valor:"))
print("El valor mayor es")
if num1>num2:
print(num1)
else:
print(num2) |
def cargar_empleados():
empleados=[]
for x in range(5):
nom=raw_input("Ingresar el nombre del Empleado: ")
sue1=int(input("Ingrese Sueldo 1: "))
sue2=int(input("Ingrese Sueldo 2: "))
sue3=int(input("Ingrese Sueldo 3: "))
empleados.append([nom,(sue1,sue2,sue3)])
return... |
meses=("enero","febrero","marzo","abril","mayo","junio",
"julio","agosto","septiembre","octubre","noviembre","diciembre")
try:
nromes=int(input("Ingrese un número de mes [1-12]:"))
print(meses[nromes-1])
except IndexError:
print("En número de mes debe ir entre 1 y 12") |
largo = 0
clave = raw_input('Ingrese la clave: ')
largo = len(clave)
if largo < 10 and largo > 20:
print('Error: numero de caracteres no valido.')
else:
print('Correcto.') |
"""
Mostrar la tabla de 5 con las estructuras repetitivas:
while
y
for
"""
#utilizando el while
print("Tabla del 5 empleando el while")
x=5
while x<=50:
print(x)
x=x+5
#utilizando el for
print("Tabla del 5 empleando el for")
for x in range(5,51,5):
print(x) |
def cargar():
lista=[]
for x in range(5):
num=int(input("Ingrese un valor:"))
lista.append(num)
return lista
def imprimir(lista):
print("Lista completa")
for elemento in lista:
print(elemento)
def mayor(lista):
may=lista[0]
for elemento in lista:
if elemen... |
import tkinter as tk
class Aplicacion:
def __init__(self):
self.valor=1
self.ventana1=tk.Tk()
self.ventana1.title("Controles Button y Label")
self.label1=tk.Label(self.ventana1, text=self.valor)
self.label1.grid(column=0, row=0)
self.label1.configure(foreground="red"... |
paises=[]
for x in range(5):
valor=raw_input("Ingrese pais:")
paises.append(valor)
print("Lista sin ordenar")
print(paises)
for k in range(4):
for x in range(4-k):
if paises[x]>paises[x+1]:
aux=paises[x]
paises[x]=paises[x+1]
paises[x+1]=aux
print("Lista ordena... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.