(Add purpose!) Is there a way to code the question code more "like Python"?

Asked 2 years ago, Updated 2 years ago, 14 views

Is there a way to code like Python more like the code below?

At first, I made find_levelid() but I think I made something simple too long... I made it with find_levelid2(). This time, it's hard to see what chord it is It doesn't look as short as the first one.

Python, I think there's a simpler way to do the same thing Is there anyone who knows?

** For specific purposes, enter a number from 1 to 1000 The output from 1 to 200 is 0, the output from 201 to 400 is 1, and the output from 401 to 1000 is 2.

** This output will be used as an index to select another tuple item. e.g. if 1 is output from above when tuplea = (23.2, 187.3, 500.2) and tupleb = (333, 555, 999), then tuplea wants to select 187.3 and tupleb 555 from tupleb.

# usekw is assumed to be 1 to 1000

import math

limit = (200, 400)
tuplea = (23.2, 187.3, 500.2)
tupleb = (333, 555, 999)

def find_levelid(usekw):
    if usekw <= limit[0]:
        level_id = 0
    elif usekw <= limit[1]:
        level_id = 1
    else:
        level_id = 2
    return level_id


def find_levelid2(usekw):
    if usekw <= limit[1]:
        level_id = math.floor((usekw-1)/200)
    else:
        level_id = 2
    return level_id

def test_print(usekw):
    print(usekw,find_levelid(usekw),find_levelid2(usekw), tuplea[find_levelid(usekw)],tupleb[find_levelid(usekw)])

test_print(1)
test_print(199)
test_print(200)
test_print(201)
test_print(399)
test_print(400)
test_print(401)
test_print(599)
test_print(600)
test_print(601)
test_print(999)
test_print(1000)

python

2022-09-21 18:58

2 Answers

Like Python, it's not fixed

It's good to have a simple readability.

numberRange = (range(1, 201), range(201, 401), range(401, 1001))
tuplea = (23.2, 187.3, 500.2)
tupleb = (333, 555, 999)

userInput = 500

for numbers, ntuplea, ntupleb in zip(numberRange, tuplea, tupleb):
    if userInput in numbers:
        print(ntuplea, ntupleb)
        break


=> 500.2 999


2022-09-21 18:58

Thinking about it, I think it would be easy to do it as below. (Tuplea, tupleb) is increased to fit the input range and find_levelidx() is lost.)

I think it's a solution that's not very "like Python."

It was okay because the number range was from 1 to 1000, but if the input range increases, it will not look good.

I would appreciate it if you could let me know if there is any other way.


import math

tuplea = (23.2, 187.3, 500.2, 500.2, 500.2)
tupleb = (333, 555, 999, 999, 999)

def test_print(usekw):
     level_id = int(math.floor((usekw-1)/200))
     print(usekw, tuplea[level_id], tupleb[level_id])


test_print(1)
test_print(199)
test_print(200)
test_print(201)
test_print(399)
test_print(400)
test_print(401)
test_print(599)
test_print(600)
test_print(601)
test_print(999)
test_print(1000)


2022-09-21 18:58

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.