F
F
fakename2014-11-29 17:10:55
Python
fakename, 2014-11-29 17:10:55

And again: How to find a bug in Python code?

I solved the problem, but the code does not pass the test (stepic.org). What can be improved?
problem:
There is an implemented function f(x) that takes an integer x as input.
The function takes a long time to evaluate, does not display anything on the screen, does not write to files, and depends only on the passed x argument.
Write a program that takes the number n as input in the first line — the number of x values ​​for which you want to know the value of the function f (x), after which these n values ​​themselves, each on a separate line. The program must, after each entered value of the argument, print the corresponding values ​​of the function f on a separate line.
To speed up the calculation, it is necessary to save the already calculated values ​​of the function with known arguments.
Please note that this task has a rather strong one-second limit on the code execution time on the test.
Sample Input:
5
5
12
9
20
12
Sample Output:
11
41
47
61
41
Memory Limit: 256 MB
Time Limit: 1 seconds
solution:

def fn():
    d={}
    n=int(input())
    x=0
    while x<n:
        a=int(input())
        if a in d:
            print(d[a])
        else:
            print(f(a))
            d[a]=f(a)
        x+=1

Answer the question

In order to leave comments, you need to log in

5 answer(s)
T
tsarevfs, 2014-11-29
@tsarevfs

Why do you cast `n` to int, but not `a`?
And to the question "how to find?" - write some function f() for example:

def f(a):
    return a + 1

def main():
    d = {}
    n = int(input())
    x = 0
    while x < n:
        a = input()
        if a in d:
            print(d[a])
        else:
            print(f(a))
            d[a] = f(a)
        x += 1

if __name__ == '__main__':
    main()

And run.

L
lega, 2014-11-29
@lega

The function is calculated long enough...
To speed up the calculation, it is necessary to save the already calculated values ​​of the function with known arguments.
And in the code, the function is called twice:
print(f(a))
d[a]=f(a)

V
Vladimir Abramov, 2014-11-29
@kivsiak

It's not the first time I've seen this kind of question. Do you understand that you are harming yourself by looking for questions to answer educational tasks?

S
Sergey Goryachev, 2017-03-15
@webirus

1) https://jsfiddle.net/webirus/tkp9dr6L/1/

#main {
    display: flex;
    align-items: flex-end;
}

2) https://jsfiddle.net/webirus/tkp9dr6L/2/
#main {
    display: table-cell;
    vertical-align: bottom;
}

3) https://jsfiddle.net/webirus/tkp9dr6L/3/
#block1, #block2 {
    display: flex;
    align-items: flex-end;
}

A
Andrew, 2017-03-15
@AndrewHaze

well then

#block2 {
   display: flex;  
   align-items: flex-end;
   background-color:#CC9933;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question