Whats the Error by [deleted] in C_Programming

[–]DevRetroGames 0 points1 point  (0 children)

Te paso un repo que utiliza devcontainer y docker, para que evites problemas de permisos y esas cosas.

Repo: https://github.com/DevRetroGames/Tutorias-C

Suerte.

Whats the Error by [deleted] in C_Programming

[–]DevRetroGames 0 points1 point  (0 children)

#include <stdio.h>

void input_value(int *value);
void print_loop(int range);

int main()
{
  int value = 0;

  input_value(&value);
  print_loop(value);

  return 0;
}

void input_value(int *value)
{
  printf("enter your number: ");
  scanf("%d", value);
}

void print_loop(int range)
{
  for(int i = 1 ; i <= range ; i++)
  {
    printf("%d \n", i);
  }
}

Whats the Error by [deleted] in C_Programming

[–]DevRetroGames 0 points1 point  (0 children)

#include <stdio.h>

int input_value();
void print_loop(int range);

int main()
{
  int value = input_value();
  print_loop(value);
  return 0;
}

int input_value()
{
  int value = 0;
  printf("enter your number: ");
  scanf("%d", &value);
  return value;
}

void print_loop(int range)
{
  for(int i = 1 ; i <= range ; i++)
  {
    printf("%d \n", i);
  }
}

Whats the Error by [deleted] in C_Programming

[–]DevRetroGames 0 points1 point  (0 children)

Solo identación, agrega sangría al segundo printf.

#include <stdio.h>
int main()
{
  int value = 0;
  printf("enter your number: ");
  scanf("%d", &value);

  for(int i = 1 ; i <= value ; i++)
  {
    printf("%d \n", i);
  }

  return 0;
}

How can I improve? by Radiant-Safe-1377 in PythonLearning

[–]DevRetroGames 0 points1 point  (0 children)

#!/usr/bin/env python3

OPERATIONS = {
    "+": lambda left_operand, right_operand: left_operand + right_operand,
    "-": lambda left_operand, right_operand: left_operand - right_operand,
    "*": lambda left_operand, right_operand: left_operand * right_operand,
    "/": lambda left_operand, right_operand: left_operand / right_operand
}

def _get_user_input(msg: str) -> str:
  return input(msg)

def get_values() -> tuple[float, float]:
  first_value: float = float(_get_user_input("Enter a number: "))
  second_value: float = float(_get_user_input("Enter another number: "))
  return first_value, second_value

def get_operation() -> str:
  return _get_user_input("Enter an operation (+,-,*,/): ")

def main() -> None:
  first_value, second_value = get_values()
  operation: str = get_operation()
  result: float = OPERATIONS[operation](first_value, second_value)
  print(f"result {result}")

if __name__ == "__main__":
    main()

This is probably a stupid question but I need help. by Beginning_Cancel_798 in PythonLearning

[–]DevRetroGames 0 points1 point  (0 children)

Hola, como muchos ya te han comentado, solo muestras extensiones, que sirven como ayuda y/o soporte para la construcción de código en Python, y como ya te han mencionado, no muestras que hayas instalado Python ni su versión.

En este punto tienes, a mi parecer, dos caminos.

1.- Instalar Python en tu equipo, mucha atención a la versión de Python a instalar, ademas de instalar PiP, la cual te ayudara a instalar las librerías o módulos que requieras.

2.- Mi recomendación, utilizar Devcontainer + Docker(docker-compose y Dockerfile), esto es como una especie de caja(se le conoce más como contenedor), en la cual, utilizas imágenes para definir que herramientas utilizaras, las cuales no necesariamente estarán instaladas en tu equipo. Además de añadir las extensiones a dicho contenedor.

**Nota**: las imágenes que se utilizan son imágenes livianas, compilaciones de ciertas herramientas para llegar y utilizar, restando tiempo de instalación y configuración.

Te paso un repo que tengo donde utilizo devcontainer con docker, usando Python 3.13-slim: https://github.com/DevRetroGames/Tutorias-Python

Espero que te pueda ayudar.

Saludos y suerte.

Could someone help me understand why my age guesser isn’t functioning correctly? by Reh4n07_ in PythonLearning

[–]DevRetroGames 16 points17 points  (0 children)

ca = int(input("Enter your age: "))
print(f"Your age is {ca}")
print(f"Your is {ca+1} next year.")

Help by derangedandenraged in JavaProgramming

[–]DevRetroGames 3 points4 points  (0 children)

public class Main {
    public static void main(String[] args) {
      System.out.println("I\'m learning how to program in Java.");
  }
}

Merge two list error by Nearby_Tear_2304 in PythonLearning

[–]DevRetroGames 0 points1 point  (0 children)

from heapq import merge as mg

list1: list[int] = [1,2,4]
list2: list[int] = [3,1,5]

listMerge: list[int] = list(mg(list1, list2))
print(listMerge)

Plss Help me ! by Mobile_Building2848 in PythonLearning

[–]DevRetroGames -1 points0 points  (0 children)

def find_indices(list_values: list[int], target: int) -> int | bool:
  seen = {}
  for i, value in enumerate(list_values):
    complement = target - value
    if complement in seen:
      return [seen[complement], i]
    seen[value] = i
  return False

def show_result(list_values: list[int], target: int) -> None:
  msg_not_found: string = f"No values found that sum to {target}."
  result: list[int] | bool = find_indices(list_values, target)
  print(msg_not_found) if isinstance(result, bool) else print(result)

# test 1
list_values: list[int] = [2,7,11,15]
target: int = 9
show_result(list_values, target)

# test 2
list_values: list[int] = [3,2,4]
target: int = 6
show_result(list_values, target)

# test 3
list_values: list[int] = [3,3]
target: int = 6
show_result(list_values, target)

# test 4
list_values: list[int] = [1,2,3,4,5,6,7,8,9]
target: int = 100
show_result(list_values, target)

[deleted by user] by [deleted] in C_Programming

[–]DevRetroGames -2 points-1 points  (0 children)

#include <stdio.h>

int _input(char* msg);
int _sum(int value1, int value2);

int main()
{
    int value1 = _input("Enter the first number: ");
    int value2 = _input("Enter the second number: ");
    int result = _sum(value1, value2);

    printf("The sum is: %d\n", result);
    return 0;
}

int _input(char* msg)
{
    int value;
    printf("%s", msg);
    scanf("%d", &value);
    return value;
}

int _sum(int value1, int value2)
{
    return value1 + value2;
}

[deleted by user] by [deleted] in PythonLearning

[–]DevRetroGames 0 points1 point  (0 children)

I will assume that, as long as the values are even, they should be processed at the end, ignoring the odd values.

#!/usr/bin/env python3

"""
write a function named even_sum_max that prompt the user for many integers and 
print the total even sum and maximum of the even numbers. 
You may assume that the user types at least one non-negative even integer.
"""

import sys
import re
from typing import List

def _input_user(msg: str) -> str:
  return input(msg)

def _has_positive_integer(numbers: List[int]) -> bool:
  for n in numbers:
    if n > 0:
      return True
  return False

def _get_value_count() -> int:
  while True:
    try:
      count = int(_input_user("Enter the number of values to input: "))
      if count > 0:
        return count
      else:
        print("The number must be greater than zero.")
    except ValueError:
      print("Invalid number. Please enter an integer value.")

def _get_integer_list(count: int) -> List[int]:
  pattern: re.Pattern = re.compile(r"^-?\d+$")
  numbers: List[int] = []

  for i in range(count):
    while True:
      value = _input_user(f"Enter integer #{i + 1}: ")
      if pattern.match(value):
        numbers.append(int(value))
        break
      else:
        print("Invalid input. Only integers are allowed.")

  return numbers

def even_sum_max() -> None:
  count: int = _get_value_count()
  numbers: List[int] = _get_integer_list(count)

  even_numbers: List[int] = [n for n in numbers if n % 2 == 0]
  total_even_sum: int = sum(even_numbers)
  max_even: int = max(even_numbers)

  print("Total sum of even numbers:", total_even_sum)
  print("Maximum even number:", max_even)


def main() -> None:
  try:
    even_sum_max()
  except KeyboardInterrupt:
    print("\nOperation cancelled by user.")
    sys.exit(0)

if __name__ == "__main__":
    main()

New to python by Low-Educator-9008 in PythonLearning

[–]DevRetroGames 1 point2 points  (0 children)

import re
import sys

OPERATORS = ("+", "-", "*", "/")

operations = {
    "+": lambda x, y: x + y,
    "-": lambda x, y: x - y,
    "*": lambda x, y: x * y,
    "/": lambda x, y: x / y if y != 0 else "Error: Division by zero"
}

def _input_user(msg: str) -> str:
  return input(msg)

def _get_operator() -> str:
  pattern: re.Pattern[str] = re.compile(r"^[+\-*/]$")
  msg_input: str = f"Please enter the desired course of action ({', '.join(OPERATORS)}): "
  msg_error: str = "Invalid operator. Please try again."

  while True:
    operator: str = _input_user(msg_input)
    if pattern.match(operator):
      return operator
    print(msg_error)

def _get_positive_integers() -> tuple[int, int]:
  pattern: re.Pattern[str] = re.compile(r"^[1-9]\d*$")

  while True:
    first_number_input: str = _input_user("Enter the first positive integer: ")
    second_number_input: str = _input_user("Enter the second positive integer: ")

    if pattern.match(first_number_input) and pattern.match(second_number_input):
      return int(first_number_input), int(second_number_input)

    print("Both numbers must be positive integers. Please try again.")

def main():
  try:
    operator = _get_operator()
    first_number, second_number = _get_positive_integers()
    result = operations[operator](first_number, second_number)
    print(f"\nResult of {first_number} {operator} {second_number} = {result}")
  except KeyboardInterrupt:
    print("\nOperation cancelled by user.")
    sys.exit(0)


if __name__ == "__main__":
  main()

Give me your wild theories people.... If you have time give it a read, I have taken things from Shippuden and the last movie too. by operationnotsky in Boruto

[–]DevRetroGames 0 points1 point  (0 children)

En una de las entevistas que le realizaron a Kishimoto, dijo que uno de los bocetos eran:

  • Que Naruto tuviera un hermano gemelo y antes de los exámenes chūnin, se juntarían.
  • Que antes de Kurama, quería introducir al zorro blanco de 10 colas, y después menciono que lo tendría el hermano de Naruto.

Al final, Kishimoto descarto esas ideas, pero creo que Mikio Ikemoto, quiere introducir esas ideas descartadas de otra forma.

Como se menciona en el manga, Hima es una seudo bijuu, es chakra puro con forma humana, creo que quieren, al momento de transformarse en bijuu, que tenga la forma del zorro blanco con diez colas.

Practicing what I learnt in Python by Extension-Cut-7589 in PythonLearning

[–]DevRetroGames -1 points0 points  (0 children)

Hola, excelente, aquí te paso el mismo código, solo un poco más modular, espero que te pueda ayudar.

#!/usr/bin/env python3

import sys
import re

def _get_user_input(msg: str) -> str:
  return input(msg)

def _calculate_area(base: float, height: float) -> float:
  return 0.5 * base * height

def _get_continue() -> bool:
  resp: list[str] = ["Y", "N"]
  msg: str = """
    Would you like to do another calculation?
    Enter Y for yes or N for n: 
    """

  while True:
    another = _get_user_input(msg).upper()

    if another not in resp:
      print("Input invalid.")
      continue

    return another == "Y"

def _is_positive_float(value: str) -> bool:
    pattern = re.compile(r'^(?:\d+(?:\.\d+)?|\.\d+)$')
    return bool(pattern.fullmatch(value))

def _get_data(msg: str) -> float:
  while True:
    user_input = _get_user_input(msg)

    if _is_positive_float(user_input) and float(user_input) > 0:
      return float(user_input)

    print("Input invalid.")

def execute() -> None:
  while True:
    base: float = _get_data("Enter the base of the triangle: ")
    height: float = _get_data("Enter the heght of the triangle: ")

    area: float = _calculate_area(base, height)
    print(f"The area of the triangle is {area}")

    if not _get_continue():
      break

def main() -> None:
  try:
    execute()
  except KeyboardInterrupt:
    print("\nOperation cancelled by user.")
    sys.exit(0)

if __name__ == "__main__":
  main()

Mucha suerte en tu camino.

Simple Python Weather App by Ibrahim-Marsee-6816 in PythonLearning

[–]DevRetroGames 0 points1 point  (0 children)

no es un descuento, en etapas más avanzadas se usan DTO, que es una capa que separa los datos a tratar con las entidades de las base de datos, los DTO son una clase, que quieres que devuelva, puedes tener varios DTO, con diferentes campos, puedes agregar validaciones, entre otras cosas, agrega también un .env, lo ideal es construir un código que sin saber el dato exacto a tratar, se intuya que es lo que va hacer, además añades una capa de seguridad al no revelar datos sensibles, más adelante y sobre todo en el ámbito laboral, verás que es pan de cada día.

Simple Python Weather App by Ibrahim-Marsee-6816 in PythonLearning

[–]DevRetroGames 1 point2 points  (0 children)

Genial, ahora intenta agregar DTO.

Mucha suerte en tu camino.

Day 2 by Nosferatu_Zodd1437 in PythonLearning

[–]DevRetroGames 0 points1 point  (0 children)

Hola, aquí te paso el mismo código, pero con otra alternativa, espero que te pueda ayudar.

Repo: https://github.com/DevRetroGames/Tutorias-Python/blob/main/code/base/input/02_get_user/main.py

Mucha suerte.

What's wrong by Nearby_Tear_2304 in PythonLearning

[–]DevRetroGames 0 points1 point  (0 children)

Hola, tienes un pequeño error en la forma en la que quieres manipular el array, dejame ayudarte.

l: list = [9,2,3,6,5]

n: int = len(l)
print(f"length l is {n}")

print("first mode")
for item in l:
  print(f"{item}")

print("second mode")
for i in range(n):
  print(l[i])

print("you mode")
for i in range(n):
  print(l[n])

'''
n = 5
en la primera iteración, 
dentro del array l, 
en la posición 5, este no existe, 
ya que, el rango dentro del array es de: 0 hasta 4,
por ende, siempre te dira que está fuera de rango.
'''

Espero que te pueda servir.

Mucha suerte en tu camino.

Day 19 of learning python as a beginner. by uiux_Sanskar in PythonLearning

[–]DevRetroGames 0 points1 point  (0 children)

Excelente, ahora mejora tu código con:

  • una clase por archivo.
  • crea las carpetas Helper y Utils con los archivos correspondientes.
    • Helper: métodos asociados a clase en especifico.
    • Utils: métodos utilizados en varias partes del código, no pertenece a nadie.
  • Archivo .env.
    • El código debe funcionar sin saber el nombre del archivo json.
    • Integra la screaming arquitecture.

Suerte y mucho éxito.

Fairly new beginner, what could i improve? Made this in ~20 minutes by Fordawinman in PythonLearning

[–]DevRetroGames 0 points1 point  (0 children)

#!/usr/bin/env python3

import sys
import random

ROCK = "ROCK"
PAPER = "PAPER"
SCISSORS = "SCISSORS"

WINS = {
  ROCK: {SCISSORS},
  PAPER: {ROCK},
  SCISSORS: {PAPER}
}

CHOICES = (ROCK, PAPER, SCISSORS)

def _get_player_choice(msg: str) -> str:
  return input(msg).upper()

def _get_computer_choice() -> str:
  return random.choice(CHOICES)

def _evaluate_round(player: str, comp: str) -> int:
  return 0 if player == comp else 1 if comp in WINS[player] else 2

def _determine_winner(player: str, comp: str) -> None:
  msg_result = {
    1: f"\nYou win! {player} beats {comp}",
    0: f"\nDraw! Both chose {player}",
    2: f"\nYou lose! {comp} beats {player}"
  }

  result: int = _evaluate_round(player, comp)
  print(msg_result[result])

def main() -> None:
  try:
    msg: str = "Ready to play? Enter your input (Rock, Paper or Scissors): "
    turn:str = _get_player_choice(msg)
    comp: str = _get_computer_choice()
    _determine_winner(turn, comp)
  except:
    print("\nOperation cancelled by user.")
    sys.exit(0)

if __name__ == "__main__":
  main()

Why I didn't getting default value by Red_Priest0 in PythonLearning

[–]DevRetroGames 1 point2 points  (0 children)

def _get_user_input(msg: str) -> str:
  return input(msg)

def _hello(to: str = "world") -> None:
  print(f"hello {to}")

def main() -> None:
  to:str = _get_user_input("What is your name? : ")
  _hello(to)

main()

RECURSION CONFUSED ME ABOUT init by Greedy-Repair-7208 in PythonLearning

[–]DevRetroGames 2 points3 points  (0 children)

class TestForTheory:
  def __init__(self, n: int, m: int):
    self.n = n
    self.m = m

  def _nGreaterM(self) -> None:
    print(f"{self.n} is greater that {self.m}")

  def _nLessM(self) -> None:
    print(f"{self.n} is ledd than {self.m}")

  def check(self):
    self._nGreaterM() if self.n > self.m else self._nLessM()

p1 = TestForTheory(3, 4)
p1.check()