How do I take multi-line input from Codeforces? - python

Codefores requires a lot of multi-line input. For example:
https://codeforces.com/contest/71/problem/A
TLDR: read this and reduce length of all words
:
4
word
localization
internationalization
pneumonoultramicroscopicsilicovolcanoconiosis
I used this solution, which I believe is correct and works for me:
lines = []
while True:
line = input()
if line:
lines.append(line)
else:
break
input = '\n'.join(lines)
tab=input.splitlines()
numb=tab[0]
tab.pop(0)
for i in tab:
wordTab=[]
if len(i)>10:
wordTab.append(i[:1])
wordTab.append(i[-1:])
print(f"{i[:1]}{len(i)-2}{i[-1:]}")
else:
print(i)
Yet i got an error (on their side). How can I make Codeforces accept multi-line input in Python?

I have a setup where I have two files called "input.txt" and "output.txt". That is where I write the code locally and then I have a FILE params which I make it True and False when I have to submit to Codeforces. Here is an example of the same problem you had mentioned. It worked fine with 77 ms as running time.
import sys
from os import path
FILE = False # if needed change it while submitting
if FILE:
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
def get_int():
return int(sys.stdin.readline())
def get_string():
return sys.stdin.readline().strip()
n = get_int()
final_result = []
for i in range(n):
word = get_string()
if len(word) > 10:
word = word[0] + str(len(word) - 2) + word[-1]
final_result.append(word)
for item in final_result:
sys.stdout.write(item)
sys.stdout.write('\n')

Here is my answer
n = int(input())
arr = []
for i in range(n) :
word = input()
if len(word) > 10 :
arr.append(word[0] + str(len(word) - 2) + word[len(word)-1])
else :
arr.append(word)
print("\n".join(arr))

lines = '''4
word
localization
internationalization
pneumonoultramicroscopicsilicovolcanoconiosis'''
input = '\n'.join(lines)
tab=lines.splitlines()
for i in tab:
wordTab=[]
if len(i)>10:
start= i[:1]
middle = len(i)-2
end= i[-1:]
print(f"{start}{len(i)-2}{end}")
else:
print(i)

Related

Why is csv "not implemented in Skulpt"?

I am trying to make a program that uses the functions get_neg and get_posto gather information about the file called project_twitter_data.csv and create a a csv that contains the information about how many negative and positive words that there are. As you can see (I will copy/paste all my current code) on lines 4-7, I am just testing out trying to make a csv without any of the fancy stuff, but for some reason a get an error:
**
NotImplementedError: csv is not yet implemented in Skulpt on line 1
**
I then Googled "What is Skulpt" and got a fat percentage measurer website. Could somebody please explain to a Python noob what the error means and how to fix it?
(PS here is the code):
#
import csv
with open('resulting_data.csv', 'wb') as f:
writer = csv.writer(f)
writer.writerow(['first line', '2nd line'])
punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '#']
# lists of words to use
positive_words = []
with open("positive_words.txt") as pos_f:
for lin in pos_f:
if lin[0] != ';' and lin[0] != '\n':
positive_words.append(lin.strip())
negative_words = []
with open("negative_words.txt") as pos_f:
for lin in pos_f:
if lin[0] != ';' and lin[0] != '\n':
negative_words.append(lin.strip())
twitter = []
with open("project_twitter_data.csv") as pos_f:
for lin in pos_f:
if lin[0] != ';' and lin[0] != '\n':
twitter.append(lin.strip())
print(twitter)
#######################
def strip_punctuation(x):
lst = []
for letter in x:
if not letter in punctuation_chars:
lst.append(letter)
return ("".join(lst))
######################
def get_neg(x):
lst = []
original_lst_name = []
var = 0
string = x.lower()
original_lst_name = string.split(" ")
print(original_lst_name)
for letter in original_lst_name:
if strip_punctuation(letter) in negative_words:
var += 1
print(var)
print(letter)
return (var)
#######################
def get_pos(x):
lst = []
original_lst_name = []
var = 0
string = x.lower()
original_lst_name = string.split(" ")
print(original_lst_name)
for letter in original_lst_name:
if strip_punctuation(letter) in positive_words:
var += 1
print(var)
print(letter)
return (var)
#########################
try opening CSV file as text file instead and process it from there as a list.

How to join values of map in python?

This is a .py file for pattern matching problem:
import sys
def pattern_matching(pattern,genome):
loc = []
for i in range(len(genome) - len(pattern) + 1):
if pattern == genome[i:i+len(pattern)]:
loc.append(i)
return loc
if __name__ == '__main__':
if len(sys.argv) == 2:
filename = sys.argv[1]
with open(filename) as f:
lines = f.read().splitlines()
pattern = lines[0]
genome = lines[1]
else:
pattern = 'ATAT'
genome = 'GATATATGCATATACTT'
loc = pattern_matching(pattern,genome)
print ",".join(map(str,loc))
But it's showing an error called "SyntaxError: invalid syntax" for line 22. How to print the result?
To convert to a list will be ok.
print(",".join(list(map(str,loc))))
In python2.x, map function return a list which return a map object in python3.x, so you neect to convert the return of map function to a list.
Fix the Unexpected Unindenting and encapsulate the print() statement if your on a version > python3
import sys
def pattern_matching(pattern,genome):
loc = []
for i in range(len(genome) - len(pattern) + 1):
if pattern == genome[i:i+len(pattern)]:
loc.append(i)
return loc
if __name__ == '__main__':
if len(sys.argv) == 2:
filename = sys.argv[1]
with open(filename) as f:
lines = f.read().splitlines()
pattern = lines[0]
genome = lines[1]
else:
pattern = 'ATAT'
genome = 'GATATATGCATATACTT'
loc = pattern_matching(pattern,genome)
print(",".join(map(str,loc))) # Corrected unindent and encapsulated print

Hashing wordlist with big input output files in Python 3.8

I'm a beginner in coding and am trying to build a script that takes a txt file as an input, hash it and output to another txt file containing "string:hashedstring" in each line of it. The code is working properly. The problem I am facing now is that if the input file is big, it will consume all RAM and kill it. I tried to use chunks, but couldn't figure out how to use it with multiline input and output.
Any suggestions regarding other parts of the code other than the main subject here is very welcome, since I am just starting on this. Thanks.
import argparse
import hashlib
import os
import sys
def sofia_hash(msg):
h = ""
m = hashlib.md5()
m.update(msg.encode('utf-8'))
msg_md5 = m.digest()
for i in range(8):
n = (msg_md5[2*i] + msg_md5[2*i+1]) % 0x3e
if n > 9:
if n > 35:
n += 61
else:
n += 55
else:
n += 0x30
h += chr(n)
return h
top_parser = argparse.ArgumentParser(description='Sofiamass')
top_parser.add_argument('input', action="store", type=argparse.FileType('r', encoding='utf8'), help="Set input file")
top_parser.add_argument('output', action="store", help="Set output file")
args = top_parser.parse_args()
sofiainput = args.input.read().splitlines()
a = 0
try:
while a < len(sofiainput):
target_sofiainput = sofiainput[a]
etarget_sofiainput = (target_sofiainput).encode('utf-8')
try:
sofia_pass = sofia_hash(target_sofiainput)
x = True
except KeyboardInterrupt:
print ("\n[---]exiting now[---]")
if x == True:
with open(args.output, 'a') as sofiaoutput:
sofiaoutput.write(str(target_sofiainput) + ":" + str(sofia_pass) + "\n")
elif x == False:
print('error')
a += 1
except KeyboardInterrupt:
print ("\n[---]exiting now[---]")
except AttributeError:
pass
When you open the file with the open command, it creates a object called file handler. So, when you do:
with open('filepath.txt', 'r') as f:
for line in f:
print(line)
it only keeps the current line you are using in the RAM, thus achieving your objective to use as little as RAM as possible.

How to convert multi line INI file to single line INI file in Python?

I have INI file formatted like this:
But i need it to look like this:
What would be the easiest solution to write such converter?
I tried to do it in Python, but it don't work as expected. My code is below.
def fix_INI_file(in_INI_filepath, out_INI_filepath):
count_lines = len(open( in_INI_filepath).readlines() )
print("Line count: " + str(count_lines))
in_INI_file = open(in_INI_filepath, 'rt')
out_arr = []
temp_arr = []
line_flag = 0
for i in range(count_lines):
line = in_INI_file.readline()
print (i)
if line == '':
break
if (line.startswith("[") and "]" in line) or ("REF:" in line) or (line == "\n"):
out_arr.append(line)
else:
temp_str = ""
line2 = ""
temp_str = line.strip("\n")
wh_counter = 0
while 1:
wh_counter += 1
line = in_INI_file.readline()
if (line.startswith("[") and "]" in line) or ("REF:" in line) or (line == "\n"):
line2 += line
break
count_lines -= 1
temp_str += line.strip("\n") + " ; "
temp_str += "\n"
out_arr.append(temp_str)
out_arr.append(line2 )
out_INI_file = open(out_INI_filepath, 'wt+')
strr_blob = ""
for strr in out_arr:
strr_blob += strr
out_INI_file.write(strr_blob)
out_INI_file.close()
in_INI_file.close()
Fortunately, there's a much easier way to handle this than by parsing the text by hand. The built-in configparser module supports keys without values via the allow_no_values constructor argument.
import configparser
read_config = configparser.ConfigParser(allow_no_value=True)
read_config.read_string('''
[First section]
s1value1
s1value2
[Second section]
s2value1
s2value2
''')
write_config = configparser.ConfigParser(allow_no_value=True)
for section_name in read_config.sections():
write_config[section_name] = {';'.join(read_config[section_name]): None}
with open('/tmp/test.ini', 'w') as outfile:
write_config.write(outfile)
While I don't immediately see a way to use the same ConfigParser object for reading and writing (it maintains default values for the original keys), using the second object as a writer should yield what you're looking for.
Output from the above example:
[First section]
s1value1;s1value2
[Second section]
s2value1;s2value2

How can I change for loop while in it?

for x in file.readlines():
something()
I think this code caching all the lines when loop is started. I deleting some of the lines from the file but it still repeating deleted lines. How can I change loop while in it?
def wanted(s,d):
print("deneme = " + str(s))
count = 0
total = 0
TG_count = TC_count = TA_count = GC_count = CC_count = CG_count = GG_count = AA_count = AT_count = TT_count = CT_count = AG_count = AC_count = GT_count = 0
for x in range(d,fileCount):
print(str(x+1) + 'st file processing...')
searchFile = open(str(x) + '.txt',encoding = 'utf-8',mode = "r+")
l = searchFile.readlines()
searchFile.seek(0)
for line in l:
if s in line[:12]:
blabla()
else:
searchFile.write(line)
searchFile.truncate()
searchFile.close()
for p in range(fileCount):
searchFile = open(str(p) + '.txt',encoding = 'utf-8',mode = "r+")
for z in searchFile.readlines():
wanted(z[:12],p)
print("Progressing file " + str(p) + " complete")
I guess it's Python. Yes, readlines() reads the whole file at once. In order to avoid this you can use:
for x in file:
something()
Maybe you can find the appropriate information in the Python tutorial. It says
If you want to read all the lines of a file in a list you can also use list(f) or f.readlines().
So yes, all lines are read and stored in memory.
Also the manual says:
f.readline() reads a single line from the file;
More details can be found in the manual.

Categories

Resources