Answer the question
In order to leave comments, you need to log in
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
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()
The function is calculated long enough...And in the code, the function is called twice:
To speed up the calculation, it is necessary to save the already calculated values of the function with known arguments.
print(f(a))
d[a]=f(a)
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?
1) https://jsfiddle.net/webirus/tkp9dr6L/1/
#main {
display: flex;
align-items: flex-end;
}
#main {
display: table-cell;
vertical-align: bottom;
}
#block1, #block2 {
display: flex;
align-items: flex-end;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question