在我的狗年到人类年计划中发现错误

2024-04-23 19:24:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python的初学者

  1. 如果输入为5,如何使输出33仅打印一次

  2. 最重要的问题是:是否有一种算法可以取代写21的需要

原来的问题是:

It is commonly said that one human year is equivalent to 7 dog years.Some people believe that it is better to count each of the first two human years as 10.5 dog years, and then count each additional human year as 4 dog years

dog_years=int(input("Enter the age of the dog to get it's equivalent for it's owner:" ))
dog_age_to_human_age_1=10.5*dog_years
dog_age_to_human_age_2=4*(dog_years-2)
dog_1=[]

if dog_years <= 0:
    print("Please Enter an positive integer whole number")
    exit()
elif dog_years > 0 and  dog_years <= 2:
    print(dog_age_to_human_age_1)
    dog_1.append(dog_age_to_human_age_1)


for dog_years in range(3,dog_years+1):
    dog_1.append(dog_age_to_human_age_2)
    print(dog_1[-1]+21)               #is there an algorithm to replace the 21?

Tags: ofthetoagethatiscountit
2条回答

不同转换技术的性能

检查了以下方法

  1. 算术O(1)复杂度
  2. 对于循环O(n)复杂性,其中n是年
  3. Numpy O(n)复杂性,其中n是年份
  4. 生成器O(n)复杂性,其中n是年份

结果

测试1:不同长度的年龄列表,随机年龄在0到25岁之间

  • 使用算术的最佳性能
  • 对于回路和发电机类似
  • 最糟糕的表现

测试2:年龄从0岁到2**10岁不等(尽管年龄超过25岁对狗来说是不现实的)

  • 算术是所有年龄段中表现最好的
  • 对于小于20岁的年龄,回路优于发电机
  • 对于高于20的回路,其性能优于发电机
  • Numpy优于100岁以上的回路和发电机,但在其他方面最差

代码

import numpy as np
from random import randint
import perfplot

def test_arithmetic(test_years):
  " Arithmetic method test "
  def calc_arithmetic(dog_years):
    " arithmetic conversion O(1) complexity "
    return young_year*dog_years if dog_years <= 2 else 2*young_year + (dog_years-2)*old_year

  for years in test_years:
    " Perform over the designated years "
    calc_arithmetic(years)

def test_for_loop(test_years):
  " For loop test runs "
  def calc_for_loop(dog_years):
    human_age = 0
    for i in range(dog_years):
      if i < 2:
        human_age += young_year
      else:
        human_age += old_year
    return human_age

  for years in test_years:
    " Perform over the designated years "
    calc_for_loop(years)

def test_np(test_years):
 " Numpy method test runs "
  def calc_np(years):
    " convert using numpy "
    arr = np.ones(years)
    arr[:2] *= young_year
    arr[2:] *= old_year
    return np.sum(arr)

  for years in test_years:
    " Perform over the designated years "
    calc_np(years)

def test_generator(test_years):
  def calc_list(years):
    " convert using generator "
    return sum(young_year if i < 2 else old_year for i in range(years))

  for years in test_years:
    " Perform over the designated years "
    calc_list(years)

young_year = 10.5
old_year = 4

测试1:从0到25岁的随机年龄,改变年龄数量

# Time using perfplot (https://pypi.org/project/perfplot/)
perfplot.show(
   setup=lambda n: [randint(0, 25) for _ in range(n)],  # or simply setup=numpy.random.rand
    kernels=[test_arithmetic, test_np, test_for_loop, test_generator],
    labels=['arithmetic', 'numpy', 'for_loop', 'generator'],
    n_range=[2 ** k for k in range(17)],
    xlabel="List Length",
    equality_check= None,
    target_time_per_measurement=1.0
    )

输出

Performance Comparision

测试2:年龄从0岁到1024岁不等

perfplot.show(
   setup=lambda n: [n],  # or simply setup=numpy.random.rand
    kernels=[test_arithmetic, test_np, test_for_loop, test_generator],
    labels=['arithmetic', 'numpy', 'for_loop', 'generator'],
    n_range=[2 ** k for k in range(10)],
    xlabel="Years",
    equality_check= None,
    target_time_per_measurement=1.0
    )

输出enter image description here

我重新编写了您的代码,以获得所需的功能:

# Algorithmic solution

dog_years = int(input("Enter the age of the dog to get it's equivalent for it's owner:" ))

young_year = 10.5
old_year = 4

human_age = 0

if dog_years < 0:
    print("Please Enter a positive integer whole number")
else:
    for i in range(dog_years):
        if i < 2:
            human_age += young_year
        else:
            human_age += old_year
    print(f"Your dog is {human_age} human years old.")  

可以使用NumPy替换for循环,如下所示:

arr = np.ones(dog_years)
arr[:2] *= young_year
arr[2:] *= old_year
human_age = np.sum(arr)

这个问题可以更优雅地用算术来解决:

# Arithmetic solution
if dog_years < 0:
    print("Please Enter a positive integer whole number")
elif dog_years <= 2:
    human_age = dog_years * young_year
else:
    human_age = 2 * young_year + (dog_years - 2) * old_year

相关问题 更多 >