0

I was trying to get a python function which judges whether a number is written in ascending or descending order (eg 12345 --> ascending, 54321 --> descending, 12321 --> neither).

For this, I first tried making a number into a string type and then converted to a list:

n=12321
for i in list(str(n)):

But then how can I finish comparing each digits of number to show that n belongs to neither?

Are there some ways I could do this without using specific libraries?

ddejohn
  • 8,775
  • 3
  • 17
  • 30
Lee
  • 1
  • Just so you know, you can iterate over a string directly: `for i in str(n)` – ddejohn Apr 26 '22 at 15:55
  • As far as your question goes, try looking at two elements at a time either using indexing over the length of the `n` string (how many digits), or using `zip` with slicing: `n_string = str(n); for a, b in zip(n_string, n_string[1:])`. You'll still need to add your comparison logic. There are other ways too. Like building a `range` object from the largest and smallest digit and comparing your digits, which you'd need to cast to `int`. – ddejohn Apr 26 '22 at 15:56
  • See https://stackoverflow.com/questions/53611711/compare-two-adjacent-elements-in-same-list – ddejohn Apr 26 '22 at 16:01

0 Answers0