Politics.be

Politics.be (https://forum.politics.be/index.php)
-   Over koetjes en kalfjes... (https://forum.politics.be/forumdisplay.php?f=9)
-   -   Challenge! Python of wiskunde! Kan jij het? (https://forum.politics.be/showthread.php?t=272824)

CUFI 17 september 2024 08:05

Challenge! Python of wiskunde! Kan jij het?
 
Citaat:

Life in Weeks

I was reading this article by Tim Urban - Your Life in Weeks and realised just how little time we actually have.


Create a function called life_in_weeks() using maths and f-Strings that tells us how many weeks we have left, if we live until 90 years old.


It will take your current age as the input and output a message with our time left in this format:


You have x weeks left.


Where x is replaced with the actual calculated number of weeks the input age has left until age 90.


**Warning** The function must be called life_in_weeks for the tests to pass. Also the output must have the same punctuation and spelling as the example. Including the full stop!


Example Input

56


Example Output

You have 1768 weeks left.


How to test your code and see your output?


Udemy coding exercises do not have a console, so you cannot use input() . You will need to call your function with hard-coded values like so:


def life_in_weeks(age):
# your code here


# Call your function with hard coded values
life_in_weeks(12)
Mijn code is:
Citaat:

def life_in_weeks(age):
age = 90 - age
days_in_age = age * 365.25
toweeks = days_in_age / 7
return int(toweeks)

result = life_in_weeks(20)
print(f"You have {result} weeks left. ")
Zelfs als ik het schrikkeljaar (365,25) uit de berekening haal, dan klopt die code nog niet. Ik heb al Gemini ingeschakeld en die rekent mijn code goed?

Maar ik krijg de error:
+ You have 3650 weeks left.
? ^
: For age 20, there should be 3640 weeks remaining


(De fout is dat hij het resterend aantal weken foutief uitrekent, maar hoezo dan?)

CUFI 17 september 2024 08:55

De fout is niet het schrikkeljaar, maar Python die ingelepeld moest krijgen dat een jaar 52 weken per jaar heeft.
Je moet dus niet delen door 7 maar de overige jaren vermenigvuldigen met 52.

Het onderwerp is dus onnodig, maar ik was gisterenavond UUUUREN aan het zoeken en berekeningen aan het doorspitten om het dan nu pas te vinden.

Mijn excuses.

Het staat ook veel netter:

def life_in_weeks(age):
age = 90 - age
weeks = age * 52
print(f"You have {weeks} weeks left.")

life_in_weeks(12)


Alle tijden zijn GMT +1. Het is nu 14:16.

Forumsoftware: vBulletin®
Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
Content copyright ©2002 - 2020, Politics.be