Populating a list/array by index in Python?

后端 未结 7 1824
一整个雨季
一整个雨季 2021-01-31 17:02

Is this possible:

myList = []

myList[12] = \'a\'
myList[22] = \'b\'
myList[32] = \'c\'
myList[42] = \'d\'

When I try, I get:

#         


        
相关标签:
7条回答
  • 2021-01-31 17:39

    Just in case someone needs, I figured out a soluction for my problem, I needed to calc a lot of factorials, some of them could be repeated, so here is my solution:

    factorials = {}
    
    def calcFact(v):
        try:
            return factorials[v]
        except KeyError:
            factorials[v] = math.factorial(v)
            return factorials[v]
    

    Testcase:

    calcFact(99000)
    calcFact(90900)
    calcFact(90090)
    calcFact(90009)
    calcFact(90009) #repeated
    calcFact(90009) #repeated
    

    Results:

    Repeating mathematical calc: 1.576 s

    Using the above code (a list to store repeated values): 1.011 s

    0 讨论(0)
提交回复
热议问题