0

I want to know something like,

weeks = '2 Weeks'
months = '1 Months'
if weeks < months:
 print(f'{weeks} is less than {months}')
else:
 print(f'{weeks} is greater than {months}')

so in the string, it only compares the numbers in the string. So it is printing "2 Weeks is greater than 1 Month". If I increase the value from '1 Month' to '3 Months' it then printing "2 Weeks is less than 3 Months". How can it detect itself to make the correct comparison?

asked Mar 6, 2022 at 4:52
1
  • 3
    The problem with that is that "1 month" is not well-defined. Sometimes "1 month" == "4 weeks", sometimes "1 month" > "4 weeks". The datetime.timedelta class can handle hours, days, and weeks. Commented Mar 6, 2022 at 4:55

2 Answers 2

2

You need to first get the number of weeks, or months, from the string, and then compare the numbers. By just comparing strings, you are comparing them lexicographically, which will not give you what you want. One way to get the number of weeks or months:

weeks = '2 Weeks'
months = '1 Months'
num_weeks = int(weeks.split()[0])
num_months = int(months.split()[0])
if num_weeks < (num_months * 4):
 print(f'{num_weeks} is less than {num_months}')
else:
 print(f'{num_weeks} is greater than {num_months}')
answered Mar 6, 2022 at 4:58

Comments

1

Here is my example, a little bit longer than Vasias :):

week = input('Week: ') # Get the weeks
month = input('Month: ') # Get the months
# Get the numbers in weeks and months
numberWeek = []
numberMonth = []
numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
for letter in week:
 for num in numbers:
 if num in letter:
 numberWeek.append(letter)
for letter in month:
 for num in numbers:
 if num in letter:
 numberMonth.append(letter)
numberWeek = ''.join(numberWeek)
numberWeek = int(numberWeek)
numberMonth = ''.join(numberMonth)
numberMonth = int(numberMonth)
# Convert the number of weeks to month
numberWeek = numberWeek / 4
# Output
if numberWeek < numberMonth:
 print(f'{week} is less than {month}')
elif numberWeek > numberMonth:
 print(f'{week} is greater than {month}')
elif numberWeek == numberMonth:
 print(f'{week} is the same as {month}')
answered Mar 6, 2022 at 10:09

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.