text stringlengths 37 1.41M |
|---|
"area = base * altura / 2"
"base = b, altura = h"
#area = 0
#b = int
#h = int
#b = int(input("Introduce la base "))
#h = int(input("Introduce la base "))
#area = b * h/2
#print("el area del triangulo es ",area)
def triangulo(num1, num2):
result = 0
result = num1 * num2/2
return result
... |
# This program uses a dictionary as a deck of cards.
def main():
# Create a deck of cards.
deck = create_deck()
# Get the number of cards to deal.
num_cards = int(input('How many cards should I deal? '))
# Deal the cards.
deal_cards(deck, num_cards)
# The create_deck function r... |
#CAHPTER 08 PYTHON PROJECT 06
def sortStringByChar(data) :
data.sort(reverse=True)
return data
data = ['apel', 'rambutan', 'jeruk']
dataTersort = sortStringByChar(data)
print("Data baru terurut dengan karakter terbanyak ke terkecil : ", dataTersort)
|
#CHAP. 05 PRAK. 01 LATIHAN 03
bahasaIndo = int(input("Nilai Bahasa Indonesia : "))
mat = int(input ("Nilai Matematika : "))
ipa = int(input("Nilai IPA : "))
print ("---------------------------")
if (bahasaIndo < 0) or (bahasaIndo > 100):
print("Maaf input anda tidak valid")
elif(mat < 0) or (mat > 100):
print... |
#CHAP.05 PRAK.02 LATIHAN 05
from random import randint
bil = randint(0,100)
print("Hi.. Nama saya Mr.Lappie, saya telah memilih sebuah bilangan bulat secara acak antara 1 sampai dengan 100. Silahkan tebak ya..!!")
tebakan = int(input("Tebakan Kamu :"))
while True:
if (tebakan > bil):
print ("Yahhh teba... |
#CAHPTER 08 PYTHON PROJECT 09
listBuah = {'apel':5000,
'jeruk':8500,
'mangga':7800,
'duku':6500}
def jumlahBuah():
jumlah =int(input('Massukkan jumlah Kg yang diinginkan : '))
print("--------------------------------------------")
print("Total Harga : ", listBuah.get(namaBuah, 0)*jum... |
import re
import re
f1 = open('../../../datas/a.txt','r')
strf1 = f1.read()
print("原文件内容为:")
print(strf1)
strf1_list = strf1.split(' ')
f1.close()
# 由于原文件需要被替换的单词都是大写的英文单词
# 使用正则表达式找出原文件中所有将被替换的单词
replist = re.findall(r'[A-Z]{2,}',strf1)
print("原文件中将被替换的单词为:")
print(replist)
print()
for rep in replist:
inputstr = ... |
def gcd(x,y):
if y == 0:
return x
else:
return gcd(y,x%y)
def lcm(x,y):
return x*y/gcd(x,y)
x,y = map(int, input().split())
n = int(gcd(x,y)+lcm(x,y))
print(n)
|
import re
select = re.compile(r"^[a-zA-Z]+@[a-zA-Z]+.[a-zA-Z]")
while True:
mail = input()
if select.findall(mail):
print("Yes")
else:
print("No")
|
def is_nice(line):
vowels = 0
doubels = False
baddies = False
for i in range(len(line) - 1):
if line[i] in 'aeiou':
vowels += 1
if line[i] == line[i + 1]:
doubels = True
if line[i] + line[i + 1] in ('ab', 'cd', 'pq', 'xy'):
baddies = True
... |
import csv
open_file = open('alunos.csv','r')
file_csv = csv.reader(open_file,delimiter=';')
for [data,nome,status] in file_csv:
print('{} - {} - {}'.format(data,nome,status)) |
import cadquery as cq
# These can be modified rather than hardcoding values for each dimension.
circle_radius = 50.0 # Radius of the plate
thickness = 13.0 # Thickness of the plate
rectangle_width = 13.0 # Width of rectangular hole in cylindrical plate
rectangle_length = 19.0 # Length of rectangular hole in cylind... |
#Exercise 6: Rewrite the program that prompts the user for a list of numbers and prints out the maximum and minimum of the numbers at
#the end when the user enters “done”. Write the program to store the numbers the user enters in a list and use the max() and min() functions to compute the maximum and minimum numbers af... |
#::::::::::::: Built-in practice: enumerate() :::::::::::::::::::::::::::::::::::::::::::
# Rewrite the for loop to use enumerate
indexed_names = []
for i, name in enumerate(names):
index_name = (i,name)
indexed_names.append(index_name)
print(indexed_names)
# Rewrite the above for loop using list comprehens... |
import random #for randint function
import time #for sleep function
print("\n\n\t\t\tWelcome to ROCK , PAPER and SCISSORS")
time.sleep(2) #two sec delay
def print_value(choice): #function to print value
val={1:"ROCK",2:"PAPER",3:"SCISSORS"} # values stored in dictionary
time.sleep... |
#!Python3
import tables, buildings
class Unit:
# all the units will have following attributes, but it is thought that the workers will be the most numerous, so
# -> the default values are set for workers.
def __init__(self, owner, text_name):
self.owner = owner
self.alive = True
s... |
#!/usr/bin/python3
# Problem 6
# ---------
# Sum square difference
# =====================
# The sum of the squares of the first ten natural numbers is,
# 1^2 + 2^2 + ... + 10^2 = 385
#
# The square of the sum of the first ten natural numbers is,
# (1 +2 + ... + 10)^2 = 55^2 = 3025
#
# Hence the difference betw... |
class Stack:
def __int__(self):
self.arr = []
def push(self, val):
self.arr = [val] + self.arr
if len(self.mins) == 0:
self.mins = [val]
else:
if self.mins[0] >= val:
self.mins = [val]
def pop(self):
v = self.arr[0]
se... |
class Solution:
def isValid(self, s: str) -> bool:
brakets = {"(": ")", "[": "]", "{": "}"}
stack = []
def check(s):
n = len(s)
if n == 0:
if len(stack) == 0:
return True
else:
return False
... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class NodeLib:
def createList(self, arr) -> ListNode:
if len(arr) == 0:
return None
node = ListNode(arr[0])
node.next = self.createList(arr[1:])
... |
def translate(board, row_or_col):
return [ board[x] for x in row_or_col if board[x] ]
def how_many_missing(board, row_or_col):
return len([ board[x] for x in row_or_col if not(board[x]) ])
def possibilities(board, sum_contraints, pos):
left = set(range(1,10))
for (row_or_col, sum_) in sum_constraints:... |
import pandas as pd
#read csv into file under variable cali
cali = pd.read_csv("COVID-19_Case_Geography_CA.csv", dtype = str)
#print columns
print("Columns" , list(cali.columns))
#drop any columns with missing variables using .dropna() on cali
cali.dropna()
#drop all columns except 'case_month', 'res_state', 'sta... |
def double(T):
return([i*2 for i in T])
tup=(1,2,3,4,5)
print(double(tup))
|
# Python code to demonstrate the working of
# degrees() and radians()
# importing "math" for mathematical operations
import math
a = math.pi/6
b = 30
# returning the converted value from radians to degrees
print ("The converted value from radians to degrees is : ", end="")
print (math.degrees(a))
# returning... |
n = int(input("enter the age of the person:"))
if(n >= 18):
print("the person is eligible to vote !!!")
else:
print("the person is not eligble to vote ")
years = 18 - n
print("you should wait for atleast " + str(years) + " years") |
class ABC:
cvar=0
def __init__(self,var):
ABC.cvar+=1
self.var=var
print("Object value is : ",var)
print("Class value is : ",ABC.cvar)
obj1=ABC(10)
obj2=ABC(20)
obj3=ABC(30)
obj4=ABC(40)
obj5=ABC(50)
|
d={1:'ravi',2:'raju',3:'sudheer',4:'sekhar'}
print("1st name is"+d[1])
print("2nd name is"+d[2])
print(d)
print(d.keys())
print(d.values())
|
num=[1,2,3,4,10]
for index, i in enumerate (num):
print(num)
|
n = int(input("enter the annual income : "))
if(n<=150000):
print("the person is eligible for scholarship")
else:
print("the person is not eligible for scholarship") |
import pickle
# This program asks the user for some animals, and stores them.
# Make an empty list to store new animals in.
animals = []
# Create a loop that lets users store new animals.
new_animal = ''
while new_animal != 'quit':
print("\nPlease tell me a new animal to remember.")
new_animal = input("Enter... |
from random import randint
def randArray():
array = []
for i in range(0, 10):
randnum = randint(1, 100)
array.append(randnum)
return array
def bubleSort(array):
for i in range(0, len(array)):
for j in range(i+1, len(array)):
if array[j] < array[i]:
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 2 11:14:15 2017
@author: Brandon Mitchell blm150430
Assignment 1, Q1
"""
"""
Body mass index (BMI) is a measure of health based on weight. It can be
calculated by taking your weight in kilograms and dividing it by the square of
your height in meters. Write a program t... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 27 19:39:26 2017
@author: bmitchell
"""
## Display the number from 1 to 5
num = 0
while num <= 5:
print(num)
num += 1 # Increment by 1. |
# def is define - how to start function
#def greeting():
# print("Hello, Chris!")
#greeting()
# def greeting(n):
# print('Hello {}!'.format(n))
# name = input('What is your name?: ')
#
# greeting(name)
# from math import sqrt as square_root
#
# def sqrt():
# return 'I live to drink soda!'
#
# print(sqrt(... |
class Human ():
count = 0
countwoman = 0
countman = 0
def __init__(self, name, lastname, age, uni, gender ):
self.name = name
self.lastname = lastname
self.age = age
self.university = uni
self.gender = gender
Human.count += 1
self.gen()
def gen... |
# -*- coding: utf-8 -*-
amount = float(input('Enter a amount:'))
inrate = float(input('Enter a inrate:'))
period = int(input('Enter a period:'))
value = 0
year = 1
while year <=period:
value = amount + (amount * inrate)
print('every year {} rate {:.2f}'.format(year,value))
amount = value
year += 1 |
# 类
class People(object):
def __init__(self,name,age):
self.name = name
self.age = age
self.jump()
def walk(self):
print("{} 在走路".format(self.name))
def eat(self):
print("{}在吃饭".format(self.name))
def jump(self):
print("{}跳了一下".format(self.name))
xiaoer = People("小儿",12)
wangwu = ... |
print("." * 10)
print("a" + "d" + "s" + "e" + "p", end=" ")
formatter = "{}{}{}{}"
print(formatter.format("hs","as","ds","dd"))
print(formatter.format(1,2,3,9))
print(formatter.format(formatter,formatter,formatter,formatter)) |
# 字典
states = {
'asd' : ' ASD',
'S' : 's',
'qwewe' : 'QWEWE',
'wewewe' : 'WEWEWE'
}
cities = {
"s" : "city",
"P" : "provice",
"CO" : "Contry",
"asd" : "s"
}
cities["C"] = "ccccc"
cities["AA"] = "AAAAA"
print("cities",cities)
print("asdada",cities[states["S"]])
# 利用key来获取value
print(cities["s"])
prin... |
# Number Guess v1.0.0
print("")
print("-------------------------Welcome To Number Guess!---------------------------------------")
print("In this game, you think of a number from 1 through n and I will try to guess what it is.")
print("After each guess, enter h if my guess is too high, l if too low, or c if correct.")
... |
# Importing required packages
import re
from nltk.stem.snowball import SnowballStemmer
# nltk library stemmer algorithm for English language
stem_eng = SnowballStemmer('english')
list_of_specialCharacters = [' ',',','$','-','//','..',' / ',' \\ ','.']
def string_stemmer(s):
stem_resultList = []
for word in s.... |
class Fraction:
""" This class represents one single fraction that consists of
numerator and denominator """
def __init__(self, numerator, denominator):
"""
Constructor. Checks that the numerator and denominator are of
correct type and initializes them.
:param numerator... |
def main():
i = 1
performance_time_list = []
while i <= 5:
performance_time = float(input("Enter the time for performance %d: " % i))
performance_time_list.append(performance_time)
i += 1
performance_time_list.remove(max(performance_time_list))
performance_time_list.remove(m... |
def get_input_lines():
lines = ""
que = " "
while que != '':
que = input()
lines = lines + que + " "
return lines
def get_single_line(words, line_length):
line = ""
words_rest = []
words_rest += words
for item in words:
if len(line)+len(item) <= line_lengt... |
def main():
print("Give 5 numbers:")
element_list = []
for i in range(0, 5, 1):
number = int(input("Next number: "))
element_list.append(number)
print("The numbers you entered, in reverse order:")
for element in element_list[::-1]:
print(element)
main()
|
def main():
print("Give 5 numbers:")
element_list = []
for i in range(0, 5, 2):
number = int(input("Next number: "))
if number > 0:
element_list.append(number)
print("The numbers you entered that were greater than zero were:")
for element in element_list:
print(e... |
# Introduction to Programming
# Geometry
from math import pi
# square function will take the required dimension from user,
# and check if it is greater than zero or not,
# and which then prints the circumference
# and area of the shape to two decimal places.
def square():
dimension = 0
while dimension < 1:
... |
import math
import numpy as np
def is_multiple(x, k):
"""
Tests if x is a multiple of k.
Parameters
----------
x : int or float
k : int or float
Returns
-------
boolean
True if n is a multiple of k.
Raises
------
ZeroDivisionError if k is 0 or 0.0
TypeErro... |
def is_leap_year( year ):
if year%4 == 0 and year%100 != 0:
return True
elif year%100 == 0 and year%400 == 0:
return True
else:
return False
def find_leap_years(start_year,end_year):
years=[]
for i in range( start_year, end_year+1 ):
if is_leap_year(i):
years.append((i,1))
else:
years.append((i,... |
def collatz(start,print_numbers):
if print_numbers:
print(start)
total=start
chain_length=1
while total != 1:
if total%2 == 0:
total/=2
else:
total=total*3+1
if print_numbers:
print(total)
chain_length+=1
if print_numbers... |
import math as math
def nCr( n , r ):
if n < r:
return 0
# nCr: n!/((n-r)!r!)
divisor = math.factorial(n)
print "Divisor: "+str(divisor)
denominator = math.factorial(n-r)*math.factorial(r)
print "Denominator: "+str(denominator)
return divisor/denominator
def nPr( n , r ):
# n... |
"""
Name: Vu Le Nguyen Phuong
Date:18/01/2020
Brief Project Description: My small project to store the list of movies. I have add extra functionality
including sort by ascending and descending order and search movie from the list :)
GitHub URL:https://github.com/phuong16122000/Movie-To-WatchA2
"""
# TODO: Create yo... |
#!/usr/bin/env python
"""
DESCRIPTION
This script is for reorganizing and sorting given addresses and postal codes and sorting the strings into a more visual appealing format.
AUTHOR
Travis Vanos <Travis.vanos@gmail.com>
LICENSE
This script is in the public domain, free from copyrights or restrictio... |
# tic-tac-toe
game = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0],]
def game_board(player: int=0, row: int=0, column: int=0, just_display: bool=False):
print(" a b c")
if not just_display:
game[row][column] = player
for count, row in enumerate(game):
print(count, row)
game_bo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: abekthink
from python3 import ListNode
class Solution:
# 1st version:
# def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
# p1, p2 = l1, l2
# head, tail = None, None
# carry = 0
# while p1 or p2:
# ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: abekthink
from python3 import List
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
length = len(nums)
for i in range(length - 1, 0, -1)... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: abekthink
class Solution:
# def strStr(self, haystack: str, needle: str) -> int:
# i, m, n = 0, len(haystack), len(needle)
# while i < m - n + 1:
# j = 0
# while j < n and haystack[i + j] == needle[j]:
# ... |
import time
import sys
from random import randint
# Delay printing
def delay_print(s):
for c in s:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.1)
class Pokemon:
def __init__(self, name: str, poke_type: str, moves: list, health=100, level=1):
self.name = name
s... |
from flask import Flask, render_template, request#, redirect, url_for
import sqlite3
app = Flask(__name__)
#x=0
#conn = sqlite3.connect("blog.db")
#p ="create table posts(post_id integer, post_title text, post_author text, post_content text);"
#comm = "create table comments(comment_id integer, comment_content text, c... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 30 19:49:49 2021
@author: Kinga Kalinowska
"""
import random
class Card:
def __init__(self,CardSuit,CardValue):
self.Card_suit=CardSuit
self.Card_value=CardValue
def show(self):
print("{} of {}".format(self.Card_value,self.Card_su... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 27 20:22:18 2021
@author: Komputer
"""
class FractionCheck(Exception):
def __init__(self,message="Nominator and denominator should be integers"):
self.message=message
super().__init__(self.message)
class Fraction:
def __init__(self,top,bott... |
class Hund: # Name in großge. CamelCase
species = 'Canis lupus familiaris' # Klassenattri.
zaehler = 0 # soll mitzählen wieviele Objekte gerade leben
@classmethod
def get_anzahl_hunde(cls):
return cls.zaehler
def __init__(self, name: str, age: str): # Zum Initialisieren
self.n... |
class Duck:
def quack(self):
print("quack quack")
def fly(self):
print("Flies through the sky")
class WoodDuck:
def quack(self):
print("*silence*")
def fly(self):
print("Gets thrown")
class Human:
def quack(self):
print("*awkward silence* *quack quack*")
... |
class Pila():
def __init__ (self):
self.cima = None
self.contador = 0
def push(self, comida):
snack = comida
if (self.cima == None):
self.cima = snack
self.contador += 1
else:
snack.abajo = self.cima
self.cima = snack
... |
def bitError(str1, str2):
"""
Compute the bit error rate between two strings.
parameters:
str1 (string): First string to be compared
str2 (string): Second string to be compared
return value:
(int) the bit error rate of two strings in percent
"""
lenStr1 = len(str1)
lenStr2 = le... |
x = 5
y = 7
z = 10
if x%2 != 0:
largest = x
if y%2 != 0:
if y > largest:
largest = y
if z%2 != 0:
if z%2 != 0:
largest = z
print (largest)
|
class Exitgate:
"""CLASS FOR THE EXIT GATE. WHEN LEMMINGS HIT THE EXITGATE, THEY WILL
DISSAPEAR FROM THE GAME AND ADD ONE SCORE UP ON THE "SAVED" SCOREBOARD """
def __init__ (self, myx, myy):
#position attributes
self.exitgate_x = myx
self.exitgate_y = myy
@property
def ... |
class Cell:
""" THIS CLASS IS MADE TO CREATE A CELL OBJECT, IN ORDER TO CREATE THE BOARD
WHERE THE GAME WILL RUN. IT HAS A X AND Y COORDINATE AND IT IS NOT VISIBLE
IN THE GAME, ITS JUST A POSITIONAL REPRESENTATION OF ALL THE THINGS CONTAINED
ON THE BOARD"""
def __init__(self, x, y):
# I... |
import getpass
import psycopg2
import time
def newuser():
conn = psycopg2.connect("dbname=abc user=postgres password=postgres")
cursor = conn.cursor()
username = input("Enter Your Name : ")
cursor.execute("SELECT username from test WHERE username=%s",(username,))
row = cursor.fetchall()
if len(... |
# Given a string, your task is to count how many palindromic substrings in this
# string.
#
# The substrings with different start indexes or end indexes are counted as
# different substrings even they consist of same characters.
#
# Example 1:
#
# Input: "abc"
# Output: 3
# Explanation: Three palindromic strings: "a"... |
# Given a string S and a string T, find the minimum window in S which will
# contain all the characters in T in complexity O(n).
#
# Example:
#
# Input: S = "ADOBECODEBANC", T = "ABC"
# Output: "BANC"
# Note:
#
# If there is no such window in S that covers all characters in T, return the
# empty string "".
# If there... |
# Given a string s that consists of only uppercase English letters,
# you can perform at most k operations on that string.
#
# In one operation, you can choose any character of the string and
# change it to any other uppercase English character.
#
# Find the length of the longest sub-string containing all repeating
... |
# Reverse a linked list.
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def create_node(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def display_n... |
# 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.
#
# Example 1:
#
# Input:
# 11110
# 11010
# 11000
# ... |
import cv2
import numpy as np
def main():
cap = cv2.VideoCapture(0)
if cap.isOpened():
ret,fram = cap.read()
print(ret)
else:
ret = False
while ret:
ret,fram = cap.read()
hsv = cv2.cvtColor(fram,cv2.COLOR_BGR2HSV)
#####################################... |
def solution(number):
sum = 0
for x in range(number):
# Multiplos de 3 y 5
if x % 3 == 0 and x % 5 == 0:
sum += x
elif x % 3 == 0:
sum += x
elif x % 5 == 0:
sum += x
x -= 1
return(sum)
|
import xml.etree.ElementTree as ET
#allows extraction of data from XML without worrying about
#the rules of XML
input = '''
<stuff>
<users>
<user x="2">
<id>001</id>
<name>Chuck</name>
</user>
<user x="7">
<id>009</id>
<name>Brent</name>
</user>
</users>
</stuff>
'''
stuff = ET.fro... |
import sqlite3
conn = sqlite3.connect('music.sqlite3')
cur = conn.cursor()
''' Insert rows into the table'''
cur.execute('INSERT INTO Tracks (title, plays) VALUES (?, ? )',
('Thunderstruck', 20 ))
cur.execute('INSERT INTO Tracks (title, plays) VALUES (?, ? )',
('My Way', 15))
conn.commit() #commit() writes data to ... |
import matplotlib.pyplot as plt
import numpy as np
# creating a data
col_count = 3
bar_width = .2
korea_scores = (554, 536, 538)
canada = (518, 523, 525)
china_scores = (613, 570, 580)
france_scores = (495, 505, 499)
# putting a data into visualization
index = np.arange(col_count)
k1 = plt.bar(index, korea_scores, ... |
from Pessoas import Pessoas
try:
nome: str = str(input('Qual seu nome? '))
sobrenome: str = str(input('Qual seu sobrenome? '))
idade: int = int(input('Qual sua idade? '))
p = Pessoas(nome,sobrenome,idade)
print("Seu nome é " + p.retornoNomeCompleto() + " e sua idade é "+str(p.idade))
except Excepti... |
Frase = input("Ingrese una frase: ")
for i in Frase:
print(i) |
#Datos de entrada
dinero = int(input("Ingrese el dinero: "))
b10 = dinero//10000
dinero = dinero%10000
print("Billetes de 10.000:",b10)
b5 = dinero//5000
dinero = dinero%5000
print("Billetes de 5.000:",b5)
b1 = dinero//1000
dinero = dinero%1000
print("Billetes de 1.000:",b1)
m500 = dinero//500
dinero = dinero%500
p... |
largo = 10
res = range(largo)
################
inicio = 2
fin = 10
res = range(inicio,fin)
#################
inicio = 5
fin = 20
incremento = 5
res = range(inicio,fin,incremento)
for i in res:
print(i) |
def validar_nombre(nombre):
if len(nombre)<6:
return "El nombre de usuario debe contener al menos 6 caracteres"
if len(nombre)>12:
return "El nombre de usuario no debe contener más de 12 caracteres"
if " " in nombre:
return "El nombre no puede contener espacios"
if nombre.isalpha... |
preferencias = ['Tv','Cine','Paseo','Música','Teatro']
# recorrer forma 1
#for i in range(len(preferencias)):
# print(preferencias[i])
# recorrer forma 2
#for x in preferencias:
# print(x)
## Recorrer todos items de la lista e imprimir letra a letra cada items.
###Permite saber el largo de un elemento
#print(... |
print("Bienvenido al medidor de tornillos")
tamano_tornillo = float(input("Ingrese el tamaño del tornillo a medir: "))
if tamano_tornillo >= 1 and tamano_tornillo<3:
print("Pequeño")
elif tamano_tornillo >= 3 and tamano_tornillo<5:
print("Mediano")
elif tamano_tornillo >= 5 and tamano_tornillo<6.5:
print(... |
horas = int(input("Ingrese las horas de trabajo: "))
pagoxhora = int(input("Ingrese el valor de la hora: "))
if horas > 45:
sueldo = horas*pagoxhora*1.5
else:
sueldo = horas*pagoxhora
print("El sueldo es",sueldo) |
#función para calcular el area de un triangulo
# Def <- Indica que es una función
def AreaTriangulo(base, altura):
area = (base*altura)/2
return area
##########################################
baseEntrada = int(input("Ingresa la base: "))
alturaEntrada = int(input("Ingresa la altura: "))
area = AreaTriangul... |
lista1 = []
for i in lista1:
print(i)
lista2 = [1,2,3,4,5,6,7,8,9]
print("Antes:",lista2)
lista3 = ["Uno",1,"Dos",2,"Tres",3]
#lista2[0] = 99
#print("Despues 1:",lista2)
#lista2[4] = lista2[7]
#print("Despues 2:",lista2)
print(lista1)
lista1.append(100)
print(lista1) |
numero = int(input("Ingresa un número "))
print(range(numero))
for i in range(numero,100,5):
print (i) |
cont = 1
while cont:
print(cont)
cont+=1
if cont==25:
break
cont = 0
while cont < 10:
cont+=1
if cont%2==0:
continue
print(cont, end=" ")
print("Es impar")
|
"""LibSPN image visualization functions."""
from libspn.data.image import ImageShape
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
def show_image(image, shape, normalize=False):
"""Show an image from flattened data.
Args:
image (array): Flattened image data
shap... |
"""
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。
注意你不能在买入股票前卖出股票。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
'''Solution
for max min in list:
[..min..max..] -> max - min
[..max...min..] :
... |
"""
给定一个带有头结点 head 的非空单链表,返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。
示例 1:
输入:[1,2,3,4,5]
输出:此列表中的结点 3 (序列化形式:[3,4,5])
返回的结点值为 3 。 (测评系统对该结点序列化表述是 [3,4,5])。
注意,我们返回了一个 ListNode 类型的对象 ans,这样:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, 以及 ans.next.next.next = NULL.
示例 2:
输入:[1,2,3,4,5,6]
输出:此列表中的结点 4 (序列化形式:[4,5,... |
"""
给你一个整数数组 nums,将该数组升序排列。
示例 1:
输入:nums = [5,2,3,1]
输出:[1,2,3,5]
示例 2:
输入:nums = [5,1,1,2,0,0]
输出:[0,0,1,1,2,5]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-an-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
# Quick sort
import random
class Solution:
def sortArray(self, nums: list) -> list:
... |
class Solution:
"""
@param str: An array of char
@param offset: An integer
@return: nothing
"""
def rotateString(self, str, offset):
# write your code here
if str == []:
return str
l = len(str) #5
#print(l)
if offset < 0 :
return "I... |
"""
在给定的网格中,每个单元格可以有以下三个值之一:
值 0 代表空单元格;
值 1 代表新鲜橘子;
值 2 代表腐烂的橘子。
每分钟,任何与腐烂的橘子(在 4 个正方向上)相邻的新鲜橘子都会腐烂。
返回直到单元格中没有新鲜橘子为止所必须经过的最小分钟数。如果不可能,返回 -1。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/rotting-oranges
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
from queue import Queue
class Solution:
def orangesRotting(se... |
"""
输入一个正整数 target ,输出所有和为 target 的连续正整数序列(至少含有两个数)。
序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
# math question
from math import floor, sqrt
class Solution:
def findContinuousSequence(self, t... |
"""
给定一个字符串,逐个翻转字符串中的每个单词。
示例 1:
输入: "the sky is blue"
输出: "blue is sky the"
示例 2:
输入: " hello world! "
输出: "world! hello"
解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
示例 3:
输入: "a good example"
输出: "example good a"
解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-... |
"""
给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。
注意:两结点之间的路径长度是以它们之间边的数目表示。
"""
# Wrong
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def diameterOfBinaryTree(self, root):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.