Sly32

Рейтинг
367
Регистрация
29.03.2012

ArbNet, Come to the topic for programmers - poreshat tasks, waiting for your decision)

Вот полностью рабочий код с посимвольным вычитыванием на Питон


import json
import time


def truncate_row(data):
start = time.time()
with open('res-task-1.json', 'w') as res:
res.write('[') with open(data) as f:
pos = 1
flag = False
js = ''
while pos:
char = f.read(pos)
if char == ']':
break
if char == '{':
flag = True
if flag:
js += char
if char == '}':
flag = False
data = json.loads(js)
if data.get('scores') >= 0.7:
res.write(json.dumps(data)+',')
js = ''
size = res.tell()
res.truncate(size - 1)

with open('res-task-1.json', 'a') as res:
res.write(']')
print(f'Executing time: {time.time() - start}')


truncate_row('task-1.json')

Executing time: 0.2150096893310547

Выходной файл валидный)

Это конечно очень грубо, можно еще оптимизировать

И просьба ко всем - приводить полностью листинг программы, чтобы можно было запустить и почекать время)

---------- Добавлено 15.06.2020 в 10:47 ----------

Gerga:
На php он может быть еще короче, если не читать посимвольно.

Это уже будет нарушением условий задачи)

Here is a fully working code character by character subtraction on Python


import json
import time


def truncate_row (data):
start = time.time ()
with open ( 'res-task-1.json', 'w') as res:
res.write ( '[') with open (data) as f:
pos = 1
flag = False
js = ''
while pos:
char = f.read (pos)
if char == ']':
break
if char == '{':
flag = True
if flag:
js + = char
if char == '}':
flag = False
data = json.loads (js)
if data.get ( 'scores')> = 0.7:
res.write (json.dumps (data) + ',')
js = ''
size = res.tell ()
res.truncate (size - 1)

with open ( 'res-task-1.json', 'a') as res:
res.write ( ']')
print (f'Executing time: {time.time () - start} ')


truncate_row ( 'task-1.json')

Executing time: 0.2150096893310547

The output file is valid)

This course is very tough, can be further optimized

And the request to all - is the full listing of the program to be able to run and pochekat time)

---------- Posted 06.15.2020 at 10:47 ----------

Gerga:
On php it can be even shorter if you do not read character by character.

It will be a violation of the conditions of the problem)

danforth:
Sly32, на выходе не валидный json Да и вычитано у тебя все в память.

Да, вижу, но пока не нашел красивого решения. не нравиться мне идея читать посимвольно файл руками) С валидацией вроде знаю как решить. Пока роюсь, что там есть в питоне для таких случаев. В приницпе код что на го, что на пхп примерно одинаков будет по длине

Danforth:
Sly32, the output is not valid json Yes and subtract you all to memory.

Yes, I see, but have not yet found a beautiful solution. I do not like the idea of reading character by character file hands) with the validation like I know how to solve. While rummaging, that there is in python for such cases. The code that prinitspe of that php is approximately the same length will be

timo-71:
В задаче запрещено грузить весь файл

да, неправильно в таком случае мое решение

timo-71:
The problem is forbidden to ship the entire file

Yes, wrong in this case, my decision


import json
import time

start = time.time()
with open('task-1.json') as data:
f = json.load(data)
print(len(f))
with open('task-1.json') as data:
content = data.read()
row = json.loads(content)
with open('res-task-1.json', 'w') as f:
f.write('[') for item in row:
if item.get('scores') >= 0.7:
f.write(json.dumps(item))
f.write(',')
f.write(']')
print(time.time()-start)

две строки тут лишние - толкь для подсчета времени

в среднем выполняется за 0.03 сек на core i5 quad

было 10000 строк стало 2995


import json
import time

start = time.time ()
with open ( 'task-1.json') as data:
f = json.load (data)
print (len (f))
with open ( 'task-1.json') as data:
content = data.read ()
row = json.loads (content)
with open ( 'res-task-1.json', 'w') as f:
f.write ( '[') for item in row:
if item.get ( 'scores')> = 0.7:
f.write (json.dumps (item))
f.write ( ',')
f.write ( ']')
print (time.time () - start)

two lines then the extra - Only for counting time

an average of 0.03 seconds is performed on the core i5 quad

It was 10,000 lines in 2995 was

danforth:
Че-то быстро ты, а я хотел задачки по сложнее закинуть, не хочешь?

Создавай тему, почему бы и нет

Всего: 7101