No response on stdout - python

I'm doing a coding challenge and every time I submit I get a the wrong answer with a "No response on stdout" Do you know what I can do? Here is the link to the problem: https://www.hackerrank.com/challenges/counting-valleys/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup
def countingValleys(n, s):
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
s = input()
result = countingValleys(n, s)
fptr.write(str(result) + '\n')
fptr.close()
N=int(input())
S = input()
L = 0
V = 0
for el in S:
if s == 'U':
L+= 1
if L == 0:
V += 1
else:
L -= 1
print(V)

You are probably returning the value instead of using the print() function. The problem specification says that you have to print it.

Related

Using Python, how to print output string as -> aaa3bb2c1ddddd5 when Input string is aaabbcddddd

Using Python, how to print output string as -> aaa3bb2c1ddddd5 when Input string is aaabbcddddd
I want to concatenate actual character value and number of times a character is repeated in a string
def mycode(myString):
lenstr = len(myString)
print('length of string is '+str(lenstr));
for ele in myString:
count=0
for character in myString:
if character == ele:
count = count+1
totalstr = ele+str(count)
return totalstr
If the string is always sorted and grouped together like that, then you can use a collections.Counter to do it.
from collections import Counter
inp = "aaabbcddddd"
counter = Counter(inp)
out = "".join(k * v + str(v) for k,v in counter.items())
Or in one line:
print(''.join(k * v + str(v) for k,v in Counter(inp).items()))
Output:
aaa3bb2c1ddddd5
Or you can do it manually:
inp = "aaabbcddddd"
last = inp[0]
out = inp[0]
count = 1
for i in inp[1:]:
if i == last:
count += 1
else:
out += str(count)
count = 1
last = i
out += i
out += str(count)
print(out)
Here is a one line solution using a regex replacement with callback:
inp = "aaabbcddddd"
output = re.sub(r'((\w)\2*)', lambda m: m.group(1) + str(len(m.group(1))), inp)
print(output) # aaa3bb2c1ddddd5
Another one-liner:
import itertools
test = 'aaabbcddddd'
out = ''.join(f"{(g := ''.join(ig))}{len(g)}" for _, ig in itertools.groupby(test))
assert out == 'aaa3bb2c1ddddd5'
def char_counter_string(string):
prev_char = None
char_counter = 0
output = ''
for char_index in range(len(string)+1):
if char_index == len(string):
output += str(char_counter)
break
if string[char_index] != prev_char and prev_char is not None:
output += str(char_counter)
char_counter = 0
output += string[char_index]
char_counter += 1
prev_char = string[char_index]
return output
if __name__ == '__main__':
print(char_counter_string('aaabbcddddd'))
you can do like..
Code:
Time Complexity: O(n)
input_string="aaabbcddddd"
res=""
count=1
for i in range(1, len(input_string)):
if input_string[i] == input_string[i-1]:
count += 1
else:
res+=input_string[i-1]*count + str(count)
count = 1
res+=input_string[-1]*count + str(count)
print(res) #aaa3bb2c1ddddd5
Here's another way, ...
Full disclosure: ... as long as the run of characters is 10 or less, it will work. I.e., if there are 11 of anything in row, this won't work (the count will be wrong).
It's just a function wrapping a reduce.
from functools import reduce
def char_rep_count(in_string):
return reduce(
lambda acc, inp:
(acc[:-1]+inp+str(int(acc[-1])+1))
if (inp==acc[-2])
else (acc+inp+"1"),
in_string[1:],
in_string[0]+"1"
)
And here's some sample output:
print(char_rep_count("aaabbcdddd"))
aaa3bb2c1dddd4
I think this fulfils the brief and is also very fast:
s = 'aaabbcddddd'
def mycode(myString):
if myString:
count = 1
rs = [prev := myString[0]]
for c in myString[1:]:
if c != prev:
rs.append(f'{count}')
count = 1
else:
count += 1
rs.append(prev := c)
rs.append(f'{count}')
return ''.join(rs)
return myString

Why is the "f" string not changing

My Problem is on line 25 when it says
if conformation == 1:
for i in range(l, len(lines[k]), 1):
if lines[k][i].isdigit() or lines[k][i].istitle():
f += lines[k][i]
if f in var:
print(var[f])
What my issue is is that the "f" string isn't being added to and its value stays as "". For context, I'm trying to make my own sort of mini programming language, and I'm trying to make prints read for variables. Every time it loops to set f to the variable name, nothing happens. The only way I get remotely close to finding the variable name is by doing "print(lines[k][i])" before the "if lines[k][i]" condition.
Note: I was using a debugger, and I'm not sure if the "if f in var" condition is even being checked.
Python code that reads my custom programming language:
⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄
code = open("HelloWorld.sabo", 'r')
lines = code.readlines()
var = {}
for k in range(0, len(lines), 1):
conformation = 0
temp = ""
temp2 = ""
if lines[k][0:5] == "print":
r = 0
l = 0
p = False
f = ""
for i in lines[k]:
r += 1
if not p:
l += 1
if i == "(":
p = True
conformation += 1
if i == "\"" and conformation == 1:
conformation += 1
if conformation == 2:
break
if conformation == 1:
for i in range(l, len(lines[k]), 1):
if lines[k][i].isdigit() or lines[k][i].istitle():
f += lines[k][i]
if f in var:
print(var[f])
if conformation == 2:
for i in range(r, len(lines[k]), 1):
if not lines[k][i] == "\"":
f += lines[k][i]
else:
break
print(f)
elif lines[k][0:4] == "var ":
for i in range(4, len(lines[k]), 1):
if not lines[k][i] == " ":
temp += lines[k][i]
else: break
for i in range(4, len(lines[k])):
if lines[k][i] == "=":
conformation = 1
elif conformation == 1:
if not lines[k][i] == " ":
temp2 += lines[k][i]
elif not temp2 == "":
break
var[temp] = temp2.strip()
Code that is being read by the above script:
⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄
var val = hello
print(val)
So, I was being a bit dumb with this, but I found out that if I just account for Uppercase and Lowercase characters, then it will work.
if lines[k][i].islower() or lines[k][i].isdigit() or lines[k][i].isnumeric() or lines[k][i].istitle():
f += lines[k][i]
I might have gone overboard with the security though I'm just not sure about the difference isdigit and isnumeric.

How can i make this work. I am basically making my own wordle game but i ran into an issue

import random
import linecache
import colorama
from colorama import Fore, Back, Style
def pickword():
global wrd
fp = open("dictionary.txt", "r")
x = random.randint(0,0)
wrd = fp.readlines()[x]
def split(word):
return list(word.lower())
def checkword():
var1 = 0
ans = input("\n\nEnter a Word: ")
lst = split(wrd)
wrdlst = []
for x in lst:
if x != "\n":
wrdlst.append(x)
anslst = split(ans)
k = anslst[var1]
l = wrdlst[var1]
for i in range(len(wrdlst)):
print(Style.RESET_ALL + l)
for m in range(1):
k = anslst[var1]
l = wrdlst[var1]
if k not in wrdlst:
print(Fore.RED + k)
elif k in wrdlst and k != l:
print(Fore.YELLOW + k)
elif k in wrdlst and k == l:
print(Fore.GREEN + k)
var1 = var1 + 1
print(var1)
# def playerInputCheck(anslist, wrdlist):
#x=1
#for i in wrdlst:
# for m in anslst:
# if m == i:
# print("3")
def main():
start = input(Fore.GREEN + "Hello, welcome to wordle! To get started press enter:\n\n*Hit enter to start* ")
pickword()
checkword()
main()
When I try to run this, it ends up outputting this:
Hello, welcome to wordle! To get started press enter:
*Hit enter to start*
Enter a Word: about
a
a
1
a
b
2
b
o
3
u
u
4
s
t
5
the word i am getting from the file is abuse, but for some reason it is outputting the first a twice and not getting to the e (the top letters are from abuse and the bottom ones are from about) I tried to make a work around but i just couldn't get it to work.
Let's break this down at the problem area (irrelevant parts removed):
l = wrdlst[var1]
for i in range(len(wrdlst)):
print(Style.RESET_ALL + l)
k = anslst[var1]
l = wrdlst[var1]
var1 = var1 + 1
print(var1)
The first time through, we have var1 = 0, l = wrdlst[var1] = 0th letter to start. Print out l.
We enter the loop, k = wrdlst[var1] = 0th letter, l = wrdlst[var1] = 0th letter. var1 goes up by 1. k gets printed.
Going into the loop the second time, we print out l (the 0th letter, again). k = wrdlst[var1] = 1st letter, l = wrdlst[var1] = 1st letter. var1 goes up by 1. k gets printed.
As you see, l gets set once outside the loop, and then printed inside the loop, and then gets accidentally reset back to the beginning inside the loop, so it's always one behind.
Simplest solution, move l = wrdlst[var1] to inside the loop, like so:
for i in range(len(wrdlst)):
l = wrdlst[var1]
print(Style.RESET_ALL + l)
for m in range(1):
k = anslst[var1]
if k not in wrdlst:
print(Fore.RED + k)
elif k in wrdlst and k != l:
print(Fore.YELLOW + k)
elif k in wrdlst and k == l:
print(Fore.GREEN + k)
var1 = var1 + 1
print(var1)
output of suggested code

why does this get an error and this doesn't?

i'm working through a hackerrank problem: https://www.hackerrank.com/challenges/kaprekar-numbers/problem
and kept having to deal with this error:
ValueError: invalid literal for int() with base 10: ''
the line 12 of code in mine that churned out error, is in the working code too. So i don't understand why mine didn't work :( please help
this is my code:
a = input()
b = input()
l = []
for i in range(a, b + 1):
s = i*i
s = str(s)
if i == 1:
l.append(i)
length = len(s)
if length <= 1:
pass
temp = int(s[0:length/2]) + int(s[length/2:]) #error came from this line
if temp == i:
l.append(i)
else:
pass
if not l:
print "INVALID RANGE"
else:
print " ".join(map(str, l))
and this is the one that works:
def kaprekar(i):
if i == 1:
return True
s = i ** 2
s = str(s)
length = len(s)
if len(s) <= 1:
return False
temp = int(s[0:length/2]) + int(s[length/2:])
if temp == i:
return True
else:
return False
a = input()
b = input()
l = []
for i in range(a, b + 1):
if kaprekar(i):
l.append(i)
if not l:
print "INVALID RANGE"
else:
print " ".join(map(str, l))
if length <= 1:
pass
pass literally doesn't do anything, so this check doesn't do anything. Whether the length is or isn't <= 1, you're proceeding to int(s[length/2:]), which will produce said error in case the string is too short.
However, return False exits the function and the following code will not execute, so that check protects you from trying to process short strings.

Parsing Data from live website in Python Enumerate problem!

The following script is supposed to fetch a specific line number and parse it from a live website. It works for like 30 loops but then it seems like enumerate(f) stops working correctly... the "i" in the for loop seems to stop at line 130 instead of like 200 something. Could this be due to the website I'm trying to fetch data from or something else? Thanks!!
import sgmllib
class MyParser(sgmllib.SGMLParser):
"A simple parser class."
def parse(self, s):
"Parse the given string 's'."
self.feed(s)
self.close()
def __init__(self, verbose=0):
"Initialise an object, passing 'verbose' to the superclass."
sgmllib.SGMLParser.__init__(self, verbose)
self.divs = []
self.descriptions = []
self.inside_div_element = 0
def start_div(self, attributes):
"Process a hyperlink and its 'attributes'."
for name, value in attributes:
if name == "id":
self.divs.append(value)
self.inside_div_element = 1
def end_div(self):
"Record the end of a hyperlink."
self.inside_div_element = 0
def handle_data(self, data):
"Handle the textual 'data'."
if self.inside_div_element:
self.descriptions.append(data)
def get_div(self):
"Return the list of hyperlinks."
return self.divs
def get_descriptions(self, check):
"Return a list of descriptions."
if check == 1:
self.descriptions.pop(0)
return self.descriptions
def rm_descriptions(self):
"Remove all descriptions."
self.descriptions.pop()
import urllib
import linecache
import sgmllib
tempLine = ""
tempStr = " "
tempStr2 = ""
myparser = MyParser()
count = 0
user = ['']
oldUser = ['none']
oldoldUser = [' ']
array = [" ", 0]
index = 0
found = 0
k = 0
j = 0
posIndex = 0
a = 0
firstCheck = 0
fCheck = 0
while a < 1000:
print a
f = urllib.urlopen("SITE")
a = a+1
for i, line in enumerate(f):
if i == 187:
print i
tempLine = line
print line
myparser.parse(line)
if fCheck == 1:
result = oldUser[0] is oldUser[1]
u1 = oldUser[0]
u2 = oldUser[1]
tempStr = oldUser[1]
if u1 == u2:
result = 1
else:
result = user is oldUser
fCheck = 1
user = myparser.get_descriptions(firstCheck)
tempStr = user[0]
firstCheck = 1
if result:
array[index+1] = array[index+1] +0
else:
j = 0
for z in array:
k = j+2
tempStr2 = user[0]
if k < len(array) and tempStr2 == array[k]:
array[j+3] = array[j+3] + 1
index = j+2
found = 1
break
j = j+1
if found == 0:
array.append(tempStr)
array.append(0)
oldUser = user
found = 0
print array
elif i > 200:
print "HERE"
break
print array
f.close()
Perhaps the number of lines on that web page are fewer than you think? What does this give you?:
print max(i for i, _ in enumerate(urllib.urlopen("SITE")))
Aside: Your indentation is stuffed after the while a < 1000: line. Excessive empty lines and one-letter names don't assist the understanding of your code.
enumerate is not broken. Instead of such speculation, inspect your data. Suggestion: replace
for i, line in enumerate(f):
by
lines = list(f)
print "=== a=%d linecount=%d === % (a, len(lines))
for i, line in enumerate(lines):
print " a=%d i=%d line=%r" % (a, i, line)
Examine the output carefully.

Categories