Obtener una función que reciba número positivo y muestre en pantalla su factorial
def factorial(n):
total = 1
for i in range(1, n + 1):
total *= i
return total
factorial(5)
Generate code just by typing a text description. AI will create the code for you. Test it now
Generate
More than just a code generator. A tool that helps you with a wide range of tasks. All in one place.
Function from Description
Text Description to SQL Command
Translate Languages
Generate HTML from Description
Code to Explanation
Fix invalid Code
Get Test for Code
Class from Description
Regex from Description
Regex to Explanation
Git Command from Description
Linux Command
Function from Docstring
Add typing to code
Get Language from Code
Time complexity
CSS from Description
Meta Tags from Description
− sponsored −
Generated by the communtiy
def factorial(n):
total = 1
for i in range(1, n + 1):
total *= i
return total
factorial(5)
++
bool S1 = 0;
bool S2 = 0;
bool S3 = 0;
bool S4 = 0;
bool S5 = 0;
bool S6 = 0;
bool S7 = 0;
bool S8 = 0;
bool S9 = 0;
bool S10 = 0;
bool S11 = 0;
bool S12 = 0;
bool S13 = 0;
bool S14 = 0;
bool S15 = 0;
bool S16 = 0;
void setup() {
pinMode(S1, OUTPUT);
pinMode(S2, OUTPUT);
pinMode(S3, OUTPUT);
pinMode(S4, OUTPUT);
pinMode(S5, OUTPUT);
pinMode(S6, OUTPUT);
pinMode(S7, OUTPUT);
pinMode(S8, OUTPUT);
pinMode(S9, OUTPUT);
pinMode(S10, OUTPUT);
pinMode(S11, OUTPUT);
pinMode(S12
using System;
using Classes;
namespace SevenWonders
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
def menu():
print("1. datos personales")
print("2. Notas de cursos")
print("3. Ausencias y Tardías")
print("4. Salir")
opcion = int(input("Ingrese una opción >> "))
if opcion == 1:
datos_personales()
elif opcion == 2:
notas()
elif opcion == 3:
ausencias()
elif opcion == 4:
exit()
else:
print("Opción incorrecta")
def datos_personales():
print("Ingrese sus datos")
nombre = input("Nombre >> ")
apellido = input("Apellido >> ")
edad = input("Edad >> ")
sexo = input("Sexo >> ")
print("")
print("Datos Ingresados")
print("Nombre: "
def factorial(n):
total = 1
for i in range(1, n + 1):
total *= i
return total
factorial(5)
// no es una funcion real
add(Mensaje)
{
// almacenar mensajes en una lista
var mensajes = [];
// si el mensaje es de esa persona contestar
if mensaje.persona == "alguna":
mensaje.respond("hola");
}
}
function hablarEspañol(persona) {
if (persona === "español" || persona === "colombiano") {
console.log("¡Hola!");
} else {
console.log("¡Hablas inglés!");
}
}
import numpy as np
def add_matrix_and_vector(x, y):
return x + y
matrix = np.array([[1, 2], [3, 4]])
vector = np.array([6, 7])
add_matrix_and_vector(matrix, vector)
import numpy as np
def add_matrix_and_vector(x, y):
return x + y
matrix = np.array([[1, 2], [3, 4]])
vector = np.array([6, 7])
add_matrix_and_vector(matrix, vector)
def sum_of_integers(n):
sumatoria = 0
for i in range(1, 101):
if i % n == 0:
sumatoria += i
return sumatoria
sum_of_integers(3)
Script
def push_notice(message):
for user in users:
user.receive_message(message)
push_notice('hello!')
def serie(resistencias):
total = 0
for resistencia in resistencias:
total += resistencia
return total
def paralelo(resistencias):
total = 0
for resistencia in resistencias:
if resistencia == 0:
return 0
total += 1 / resistencia
return 1 / total
def total(resistencias, tipo):
if tipo == "serie":
return serie(resistencias)
elif tipo == "paralelo":
return paralelo(resistencias)
else:
print("Tipo de resistencia no reconocida")
return None
resistencias = []
while True:
cantidad = int(input("Ingrese la cantidad de resistencias: "))
if cantidad > 0:
break
print("Ingrese una cantidad positiva")
for i in range(cantidad):
while True:
function (key, wait, loop, ...) {
for(var i=0; i<loop; i++) {
key(arguments[3], arguments[4], ...);
wait(500);
}
}
def add_one(number):
return number + 1
add_one(2)
## 六、过程与思考(必填)
1. 你理解的实验标题和主题是什么?
def file_to_dict(file_name):
file_dict = {}
# open the file
with open(file_name) as f:
# loop through each line in the file
for line in f:
# remove new line character
key = line.rstrip()
# get the number of files in the directory
file_dict[key] = len(os.listdir(key))
return file_dict
def file_to_sorted_list(file_name):
file_dict = file_to_dict(file_name)
# return a list of directory name and number of files
return sorted(file_dict.items(), key=lambda kv: kv[1])
# test
for dir_name, number_of_files in file_to_sorted_list('directorios.txt'):
print(f'{dir_name} has {number_of_files} files')
#include <iostream>
int main() {
std::cout << "Hello World!" << std::endl;
return 0;
}
function generar_qr(texto) {
if (texto.length >= 100) {
return "El texto es demasiado largo"
}
return "https://api.qrserver.com/v1/create-qr-code/?data=" + texto + "&size=250x250"
}
void programar(a, z) {
if (a == z)
return a;
}
#LMM
library(lme4)
m2 <- clm(categorical_FOD_FODs ~ 0 + Condition_FODs:Language_used_FODs - 1, random = ~1|subject, data = indvar_FODs)
summary(m2)
#LM
m2 <- clm(categorical_FOD_FODs ~ Condition_FODs:Language_used_FODs - 1, data = indvar_FODs)
summary(m2)
#post-hoc analysis
library(lsmeans)
contrast(m2, "pairwise", list(Condition_FODs = c("A", "B", "C", "D")))
library(emmeans)
emmeans(m2, pairwise~Condition_FODs, adjust = "bonferroni")
#include <stdio.h>
int main(int argc, char const *argv[])
{
int n;
scanf("%d", &n);
int numbers[n];
for (int i = 0; i < n; i++)
{
int number;
scanf("%d", &number);
numbers[i] = number;
}
int sumOfEvens = 0;
int sumOfOdds = 0;
for (int i = 0; i < n; i++)
{
int number = numbers[i];
if (number % 2 == 0)
{
sumOfEvens += number;
}
else
{
sumOfOdds += number;
}
}
printf("%d\n", sumOfEvens);
if (sumOfOdds == 0)
{
printf("No hay números impares");
}
else
{
printf("%.2
fn swap(left: &mut usize, right: &mut usize) {
let temp = *left;
*left = *right;
*right = temp;
}
fn main() {
let mut left = 1;
let mut right = 2;
swap(&mut left, &mut right);
println!("left: {}, right: {}", left, right);
}
def file_to_dict(file_name):
file_dict = {}
# open the file
with open(file_name) as f:
# loop through each line in the file
for line in f:
# remove new line character
key = line.rstrip()
# get the number of files in the directory
file_dict[key] = len(os.listdir(key))
return file_dict
def file_to_sorted_list(file_name):
file_dict = file_to_dict(file_name)
# return a list of directory name and number of files
return sorted(file_dict.items(), key=lambda kv: kv[1])
# test
for dir_name, number_of_files in file_to_sorted_list('directorios.txt'):
print(f'{dir_name} has {number_of_files} files')
int salary;
if salaries > 50000:
salary = 50000
else:
salary = salaries
print("You are hired")
return salary
def num_asign(data, col, row):
data.loc[row,col] = data.loc[row,col].replace(data.loc[row,col],num)
for row in range(len(data)):
for col in range(2,len(data.columns)):
for num in range(1,4):
if data.loc[row,col] == num:
num_asign(data, col, row)
Script
function add(a, b) {
return a + b;
}
def factorial(x):
if x == 0:
return 1
return x * factorial(x - 1)
factorial(5)
SELECT * FROM `order` where ctime between '2017-03-01' and '2017-05-22' and id in (select order_id from order_detail where status = 1 )
int salary;
if salaries > 50000:
salary = 50000
else:
salary = salaries
print("You are hired")
return salary
int main()
{
int a, b, c;
cin>>a>>b>>c;
if(a>b && a>c)
{
cout<<a<<" ";
if(b>c)
cout<<b<<" "<<c;
else
cout<<c<<" "<<b;
}
else if(b>a && b>c)
{
cout<<b<<" ";
if(a>c)
cout<<a<<" "<<c;
else
cout<<c<<" "<<a;
}
else if(c>a && c>b)
{
cout<<c<<" ";
if(a>b)
cout<<a<<" "<<b;
else
cout<<b<<" "<<a;
}
return 0;
}
Script
function processes(arr) {
var obj = {};
var p1_count = 0;
var p2_count = 0;
var a = 0;
var b = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i] === "PROC1") {
p1_count += 1;
a = p1_count;
} else {
p2_count += 1;
b = p2_count;
}
if (a === b) {
obj[arr[i]] = b;
a = 0;
b = 0;
}
}
return obj;
}
processes(["PROC1", "PROC1", "PROC1", "PROC2", "PROC2", "PROC2"]);
function (key, wait, loop, ...) {
for(var i=0; i<loop; i++) {
key(arguments[3], arguments[4], ...);
wait(500);
}
}
def num_asign(data, col, row):
data.loc[row,col] = data.loc[row,col].replace(data.loc[row,col],num)
for row in range(len(data)):
for col in range(2,len(data.columns)):
for num in range(1,4):
if data.loc[row,col] == num:
num_asign(data, col, row)
SELECT * FROM `order` where ctime between '2017-03-01' and '2017-05-22' and id in (select order_id from order_detail where status = 1 )
SELECT string_agg(case data_type
when 'character varying' then 'text'
when 'integer' then 'integer'
when 'double precision' then 'real'
when 'jsonb' then 'jsonb'
end,',') FROM information_schema.columns where table_schema='public' and table_name='customers';
public class Ejercicio02 {
public static void main(String[] args) {
int[] numeros = new int[20];
int suma = 0;
int media;
System.out.println("Array original:");
for (int i = 0; i < 20; i++) {
numeros[i] = (int)(Math.random() * 401);
System.out.print(numeros[i] + " ");
suma += numeros[i];
}
System.out.println("\n\nArray modificado:");
media = suma / 20;
for (int i = 0; i < 20; i++) {
if (numeros[i] < media) {
numeros[i] = numeros[i] * -1;
}
System.out.print(numeros[i] + " ");
}
}
}
fun hola(name: String) {
println("Hola $name")
}
hola("Miguel")
function generar_qr(texto) {
if (texto.length >= 100) {
return "El texto es demasiado largo"
}
return "https://api.qrserver.com/v1/create-qr-code/?data=" + texto + "&size=250x250"
}
def add(a,b):
return (a+b)
def sum_complex(*args):
sum_ = 0
for i in args:
sum_ = add(sum_, i)
return sum_
sum_complex(1,2,3,4,5,6)
printf("\n1. Cálculo de perímetro de circunferencia\n");
printf("2. Área de circunferencia\n");
printf("3. Volumen de la esfera\n");
printf("4. Salir\n");
printf("\nIngrese una opción: ");
scanf("%d",&opcion);
# -*- coding: utf-8 -*-
# Copyright (c) 2019, DigiThinkIT and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class ProductDetector(Document):
pass
#
public double IVA(double subtotal)
{
return subtotal * 0.16;
}
@Entity
@Table(name = "orders")
public class Order implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "total_amount")
private Double totalAmount;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "order")
private List<OrderItem> orderItems;
// getters and setters
}
A = {1,2,3,4,5}
B = {4,5,6,7,8}
A | B
onsole
mango
$1.00
pera
$1.50
tomate
$0.75
var products = [
{ name: 'Galletas', description: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' },
{ name: 'Bebidas', description: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' },
{ name: 'Comida', description: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' },
{ name: 'Papas', description: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' },
{ name: 'Tortas', description: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' },
]
var carousel = document.getElementById('carousel');
var html = '';
html += '<div class="products">'
for (var i = 0; i < products.length; i++) {
html += '<div class="product">';
html += '<
Script
function doubleArray(arr){
let newArray = arr.map(num => num * 2)
return newArray
}
doubleArray([2,4,6,8]) // [4,8,12,16]
def age(name, age, address, phone, sex):
if age > 18:
print("Es mayor de edad")
else:
print("Es menor de edad")
if sex == "M":
print("Es hombre")
else:
print("Es mujer")
age("Maria", 26, "Calle 6", "123-4567", "F")
# Add a rectangle
color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255) )
pygame.draw.rect(screen, color, [random.randint(0, 200), random.randint(0, 200), 50, 50])
def main()
principal = 200000
monthly_interest_rate = 0.02
number_of_payments = 24
payment = principal * ((monthly_interest_rate * (1 + monthly_interest_rate)**number_of_payments) / ((1 + monthly_interest_rate)**number_of_payments - 1))
return payment
def agregar_verdura(lista, verdura):
if verdura not in lista:
lista.append(verdura)
return "{} agregada exitosamente".format(verdura)
else:
return "La verdura ya está en la lista"
verduras = ['lechuga', 'cebolla']
agregar_verdura(verduras, 'tomate')
Script
function add(a, b) {
return a + b;
}
def big_vowels(sentence, word):
def serie(resistencias):
total = 0
for resistencia in resistencias:
total += resistencia
return total
def paralelo(resistencias):
total = 0
for resistencia in resistencias:
if resistencia == 0:
return 0
total += 1 / resistencia
return 1 / total
def total(resistencias, tipo):
if tipo == "serie":
return serie(resistencias)
elif tipo == "paralelo":
return paralelo(resistencias)
else:
print("Tipo de resistencia no reconocida")
return None
resistencias = []
while True:
cantidad = int(input("Ingrese la cantidad de resistencias: "))
if cantidad > 0:
break
print("Ingrese una cantidad positiva")
for i in range(cantidad):
while True:
Script
def push_notice(message):
for user in users:
user.receive_message(message)
push_notice('hello!')
// This is a "stub" file. It's a little start on your solution.
// It's not a complete solution though; you have to write some code.
// Package greeting should have a package comment that summarizes what it's about.
// https://golang.org/doc/effective_go.html#commentary
package greeting
// HelloWorld needs a comment documenting it as package does.
func HelloWorld() string {
return "Hello, World!"
}
Script
function doubleArray(arr){
let newArray = arr.map(num => num * 2)
return newArray
}
doubleArray([2,4,6,8]) // [4,8,12,16]
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int numero;
cin >> numero;
for(int x = 1; x <= numero; x++)
{
double fx = pow(2.71828, 2 * x) - x;
cout << x << ' ' << fx << endl;
}
return 0;
}
for(int i = 1; i <= 10; i++){
std::cout << i << std::endl;
}
int main(){
char letra, mes[13];
printf("Ingrese una letra de la A a la L: ");
scanf("%c", &letra);
switch(letra){
case 'A':
case 'a':
printf("Enero");
break;
case 'B':
case 'b':
printf("Febrero");
break;
case 'C':
case 'c':
printf("Marzo");
break;
case 'D':
case 'd':
printf("Abril");
break;
case 'E':
case 'e':
printf("Mayo");
break;
case 'F':
case 'f':
printf("Junio");
break;
case 'G':
case 'g':
printf("Julio");
break;
case 'H':
case 'h':
printf("Agosto");
break;
case 'I':
case
#include <stdio.h>
float avg(int nums[ ], int n) {
int i, sum = 0;
for(i = 0; i < n; i++) {
sum += nums[i];
}
return ((float)sum)/n;
}
int main() {
int nums[] = {1, 2, 3, 4, 5};
printf("%f", avg(nums, 5));
}
Future<void> signUp(String email, String password) async {
var result = await _cognitoUserPool.signUp(email, password, [
AttributeArg(name: 'email', value: email),
AttributeArg(name: 'name', value: 'minh'),
AttributeArg(name: 'phone_number', value: '0932919800'),
AttributeArg(name: 'gender', value: 'male'),
]);
print('signUp result: $result');
}
a?.b?.c?.d()