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)
Hello Community Members,
I am getting the error NameError: name 'f' is not defined. The code is as follows. Please help. Any sort of help is appreciated. I have been strucked onto this since 3 days. The code is all about to extract all the subcategories name of wikipedia category in Python 3.
I have tried both the relative and absolute paths.
The code is as follows:
import httplib2
from bs4 import BeautifulSoup
import subprocess
import time, wget
import os, os.path
#declarations
catRoot = "http://en.wikipedia.org/wiki/Category:"
MAX_DEPTH = 100
done = []
ignore = []
path = 'trivial'
#Removes all newline characters and replaces with spaces
def removeNewLines(in_text):
return in_text.replace('\n', ' ')
# Downloads a link into the destination
def download(link, dest):
# print link
if not os.path.exists(dest) or os.path.getsize(dest) == 0:
subprocess.getoutput('wget "' + link + '" -O "' + dest+ '"')
print ("Downloading")
def ensureDir(f):
if not os.path.exists(f):
os.mkdir(f)
# Cleans a text by removing tags
def clean(in_text):
s_list = list(in_text)
i,j = 0,0
while i < len(s_list):
#iterate until a left-angle bracket is found
if s_list[i] == '<':
if s_list[i+1] == 'b' and s_list[i+2] == 'r' and s_list[i+3] == '>':
i=i+1
print ("hello")
continue
while s_list[i] != '>':
#pop everything from the the left-angle bracket until the right-angle bracket
s_list.pop(i)
#pops the right-angle bracket, too
s_list.pop(i)
elif s_list[i] == '\n':
s_list.pop(i)
else:
i=i+1
#convert the list back into text
join_char=''
return (join_char.join(s_list))#.replace("<br>","\n")
def getBullets(content):
mainSoup = BeautifulSoup(contents, "html.parser")
# Gets empty bullets
def getAllBullets(content):
mainSoup = BeautifulSoup(str(content), "html.parser")
subcategories = mainSoup.findAll('div',attrs={"class" : "CategoryTreeItem"})
empty = []
full = []
for x in subcategories:
subSoup = BeautifulSoup(str(x))
link = str(subSoup.findAll('a')[0])
if (str(x)).count("CategoryTreeEmptyBullet") > 0:
empty.append(clean(link).replace(" ","_"))
elif (str(x)).count("CategoryTreeBullet") > 0:
full.append(clean(link).replace(" ","_"))
return((empty,full))
def printTree(catName, count):
catName = catName.replace("\\'","'")
if count == MAX_DEPTH : return
download(catRoot+catName, path)
filepath = "categories/Category:"+catName+".html"
print(filepath)
content = open('filepath', 'w+')
content.readlines()
(emptyBullets,fullBullets) = getAllBullets(content)
f.close()
for x in emptyBullets:
for i in range(count):
print (" "),
download(catRoot+x, "categories/Category:"+x+".html")
print (x)
for x in fullBullets:
for i in range(count):
print (" "),
print (x)
if x in done:
print ("Done... "+x)
continue
done.append(x)
try: printTree(x, count + 1)
except:
print ("ERROR: " + x)
name = "Cricket"
printTree(name, 0)
The error encountered is as follows.
I think f.close() should be content.close().
It's common to use a context manager for such cases, though, like this:
with open(filepath, 'w+') as content:
(emptyBullets,fullBullets) = getAllBullets(content)
Then Python will close the file for you, even in case of an exception.
(I also changed 'filepath' to filepath, which I assume is the intent here.)
I'm running Python 3 and I'm getting the following error:
AttributeError: 'AssemblyParser' object has no attribute 'hasMoreCommands'
Here is the code that is raising the error:
import sys
from Parser import AssemblyParser
from Code import Code
parser = AssemblyParser(sys.argv[1])
translator = Code()
out_file = str(sys.argv[1]).split(".")
out_file = str(out_file[:1]) + ".hack"
with open(out_file, 'w', encoding='utf-8') as f:
while parser.hasMoreCommands():
parser.advance()
if parser.commandType() == "A_COMMAND":
dec_num = parser.symbol()
binary = "{0:b}".format(dec_num)
elif parser.commandType() == "C_COMMAND":
default_bits = "111"
comp_bits += translator.comp(parser.comp())
dest_bits += translator.dest(parser.dest())
jump_bits += translator.jump(parser.jump())
binary = default_bits + comp_bits + dest_bits + jump_bits
assert len(binary) == 16
f.write(binary)
Here is my Parser.py file:
class AssemblyParser:
"""
Encapsulates access to the input code. Reads an assembly language command,
parses it, and provides convenient access to the command's components (fields and symbols).
In addition, removes all whitespace and comments.
"""
def __init__(self, input_file):
self.current_command = ""
self.next_command = ""
with open(input_file,"r+", encoding='utf-8') as f:
for l in f:
line = "".join(l.split()) # Remove whitespace from the line
line = line.split('//') # Removes any comments from the line
clean_line = line[0]
if clean_line.strip(): # Removes any blank lines
f.write(clean_line)
next_command = f.readline()
def __hasMoreCommands__(self):
if self.next_command:
return true
return false
def __advance__(self):
with open(input_file, encoding='utf-8') as f:
self.current_command = self.next_command
self.next_command = f.readline()
def __commandType__(self):
char_1 = self.current_command[:1]
if char_1 == "#":
return "A_COMMAND"
elif char_1 == "(":
return "L_COMMAND"
else:
return "C_COMMAND"
def __symbol__(self):
assert self.commandType() == ("A_COMMAND" or "L_COMMAND")
if self.commandType() == "A_COMMAND":
symbol = str(symbol[1:])
else:
symbol = str(symbol[1:len(symbol)-1])
return str(symbol)
def __dest__(self):
assert self.commandType() == "C_COMMAND"
if "=" in self.current_command:
temp = self.current_command.split("=")
return str(temp[:1])
else:
return ""
def __comp__(self):
assert self.commandType() == "C_COMMAND"
temp = self.current_command
if "=" in temp:
temp = temp.split("=")
temp = str(temp[1:])
if ";" in temp:
temp = temp.split(";")
temp = str(temp[:1])
return temp
def __jump__(self):
assert self.commandType() == "C_COMMAND"
if ";" in self.current_command:
temp = self.current_command.split(";")
return str(temp[1:])
else:
return ""
I really don't know why I'm getting this error, I've looked at the import documentation, but I'm getting more and more confused. I'm fairly new to Python. Can anyone explain this error?
Thanks.
Well. There seems to be no function in Parser module with name hasMoreCommand. The function in there starts with underscore and end eith underscore.
Two leading and trailing underscores are used to identify "magic" attributes. You can't use that to create your own, as they only reference pre-existing methods.
The following is what you probably want:
hasMoreCommands():
If you have multiple classes with this function, use name mangling instead:
_hasMoreCommands():
See: https://stackoverflow.com/a/8689983/2030480
And: http://www.rafekettler.com/magicmethods.html
input.txt
A(0,1,2)
...
B(A,3)
...
C(B,4,5)
If the first parameter of a function is not equal 0 but corresponding to a function name, I want to replace it with all of the corresponding function's parameters (e.g. to replace the first parameter 'A' in function B above with all parameters of function A). That is to expect
output.txt
A(0,1,2)
...
B(0,1,2,3)
...
C(0,1,2,3,4,5)
How can we do this with awk/sed or python?
EDIT:
One idea I have is to store the function name as variables and its parameters as values in bash. In python, we may use dict, and consider function names as keys, and its parameters as values. The implementation is not that easy.
Awk
awk -F'[()]' '
$2 !~ /^0,/ {
split($2, a, /,/)
sub(/^[^,]+/, val[a[1]], $2)
}
{
val[$1] = $2
print $1 "(" $2 ")"
}
' input.txt > output.txt
Where sub(/^[^,]+/, val[a[1]], $2) is used to match the first parameter in $2 and replace it with the value of val[a[1]] which is defined by the execution of val[$1] = $2 on previous lines.
Here's a solution in Python:
import re
with open('input.txt') as f:
data = f.read()
data = [line.strip() for line in data.split('\n') if line]
sets, output = {}, open('output.txt', 'w')
for line in data:
if line == '...':
output.write(line + '\n')
continue
sets[line[0]] = line[2:-1]
output.write(line[0] + '(')
for char in line[2:-1]:
if re.match(r'[\d,]', char):
output.write(char)
else:
output.write(sets[char])
output.write(')\n')
output.close()
Relevant documentation: open(), re.
Let lines be the lines of the input file. The following code will work if all parameters are integers or a functionname
funcs = {}
for line in lines:
match = re.search( '(.*)\((.*)\)', line)
if not match:
raise RuntimeError('Line does not match expectation')
function_name = match.group(1)
parameters = map(str.strip, match.group(2).split(','))
parameter_list = []
for parameter in parameters:
try:
parameter_list.append(int(parameter))
except ValueError:
parameter_list.extend( funcs.get(parameter, []) )
funcs[function_name] = parameter_list
for func_name, paras in sorted(funcs.items()):
print '{function}({parameters})'.format(
function=func_name,
parameters=', '.join(map(str, paras))
)
There are probably a ton of ways to do this but I think this is a simple way to do what you want.
import re
import sys
def convertLine(line):
if re.match("^\\w{1}\(.*\)$", line) is None:
return line
retVal = re.sub( "A", "0,1,2",line[1:])
retVal = re.sub( "B", "0,1,2,3",retVal)
retVal = re.sub( "C", "0,1,2,3,4,5",retVal)
return line[0:1]+retVal
def main():
for line in sys.stdin.read().splitlines():
print convertLine(line)
if __name__ == "__main__":
main()
usage:
python ReplaceProg.py < input.txt
if your file is like this
A(0,1,2)
B(A,3)
C(B,4,5)
using python:
f = open('inpu_file.txt').readlines()
f[0] = f[0].strip()
for i,x in enumerate(f):
if i > 0:
f[i]=re.sub(f[i-1][0],",".join(re.findall('\d+',f[i-1])),x).strip()
print f
output:
['A(0,1,2)', 'B(0,1,2,3)', 'C(0,1,2,3,4,5)']
i don't understand that ... in every alternate line, if its there tell me i can edit the code for that.
Kinda long but more modular:
import re
def build_dict(fobj):
d = dict()
for line in fobj:
match = re.match('^(\w)\((.*)\)', line)
fname = match.group(1)
fargs = match.group(2)
d[fname] = replace(fargs, d)
fobj.seek(0) # Reset cursor to start of file
return d
def replace(s, d):
for each in d:
if each in s:
s = s.replace(each, d[each])
return s
def split_paren(s):
index = s.index('(')
return s[:index], s[index:]
def write_replace(fobj, d):
outname = fobj.name[:-4] + '.out'
outfile = open(outname, 'w')
for line in fobj:
first, second = split_paren(line)
second = replace(second, d)
outfile.write(first + second)
outfile.close()
if __name__ == '__main__':
with open('test.txt', 'r') as f:
d = build_dict(f)
write_replace(f, d)
I have to create a function that reads a random line from a text file in python.
I have the following code but am not able to get it to work
import random
def randomLine(filename):
#Retrieve a random line from a file, reading through the file irrespective of the length
fh = open(filename.txt, "r")
lineNum = 0
it = ''
while 1:
aLine = fh.readline()
lineNum = lineNum + 1
if aLine != "":
# How likely is it that this is the last line of the file ?
if random.uniform(0,lineNum)<1:
it = aLine
else:
break
fh.close()
return it
print(randomLine(testfile.txt))
I got so far but,need help to go further, Please help
once the program is running i'm getting an error saying
print(randomLine(testfile.txt))
NameError: name 'testfile' is not defined
Here's a version that's been tested to work, and avoids empty lines.
Variable names are verbose for clarity.
import random
import sys
def random_line(file_handle):
lines = file_handle.readlines()
num_lines = len(lines)
random_line = None
while not random_line:
random_line_num = random.randint(0, num_lines - 1)
random_line = lines[random_line_num]
random_line = random_line.strip()
return random_line
file_handle = None
if len(sys.argv) < 2:
sys.stderr.write("Reading stdin\n")
file_handle = sys.stdin
else:
file_handle = open(sys.argv[1])
print(random_line(file_handle))
file_handle.close()