Hackerrank Code not working [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
The problem is given here
I am coding in python and my code is given below:
num =raw_input()
li=list()
count=150*[0]
ans=0
while num>0:
li.append(raw_input())
num=int(num)-1
for i in range (0, len(li)):
for j in range(0, len(li[i])):
count.insert (ord(li[i][j]), count[ord(li[i][j])]+1)
for i in range(0, len(count)):
if count[i]==len(li):
ans=ans+1
print ans
On running the sample test case the output is 3 instead of 2.
Where am I going wrong?

There are several things wrong with your program.
First the insert method doesn't do what you seem to think it does.
list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).
Second, you're attempting to count every time a letter appears at all, not just the first instance in a line.
This also looks like a low effort question, which is why you're getting downvoted. What have you tried?
Here's a solution that uses your method correctly, but it's still not a very pythonic approach. Have you considered using a dict to keep track of this information instead?
num = raw_input()
li = list()
count = 150*[0]
seen = 150*[False]
ans = 0
while num > 0:
li.append(raw_input())
num = int(num)-1
for i in range(0, len(li)):
for j in range(0, len(li[i])):
if (not seen[ord(li[i][j])]):
count[ord(li[i][j])] += 1
seen[ord(li[i][j])] = True
seen = 150*[False]
print count
for i in range(0, len(count)):
if count[i] == len(li):
ans = ans+1
print chr(i)
print ans
Here's the same approach using more pythonic language, isn't this much easier to understand?
num = raw_input()
lines = []
seen = set()
count = {}
while num > 0:
lines.append(raw_input())
num = int(num)-1
for line in lines:
for char in line:
if (char not in seen):
count[char] = count.get(char, 0) + 1
seen.add(char)
seen = set()
print count
print list(count.values()).count(len(lines))
There are, of course even better ways to do this.

The website states: Required Knowledge: Implementation, Sets: Time Complexity: O(n)
So using set.intersection would be a better way to go:
num = raw_input()
sets = [set(raw_input()) for x in range(int(num))] ]# make set from each line
print len(set.intersection(*sets)) # find letters that are common in all sets and print the length

You are counting c as a gem-element. It occurs 3 times, but not in 3 different lines. Thus count[i]==len(li) is not a sufficient criterion for a gem-element.

Related

how can I plan this sequence-1,2,2,3,4,4,5 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 months ago.
Improve this question
I am fairly new to programming and I try to create the above mentioned sequence.
this problem is about having a strict length of elements which always progresses, this progression is inside the list by moving on the indexes. this strict length shifts from a set of indexes to the next one once all the indexes inside the strict length (not passing it's limits) are finished being scanned, and they are scanned in a format of "one after the other".
after all of that we come to the root of the problem:
once the strict length moves to another set, it starts from the last index that was previously, inside of the strict length but in the previous strict length.
the output of the root problem is the title of this post. I don't know how to solve the root problem.
this problem, involves "k" as an exponent of the strict length.
this is the script:
strarr = ["1","2","3","4","5","6","7","8","9","10"]
k = 2
n = 0
while True:
for i in range(k):
print(strarr[n])
n = n+1
print(strarr[n])
the output I got is:
1,2,3,3,4,5,5,6,7,7,8,9,9,10
and I don't know why I got such output, it doesn't seem logical.
As I can understand what you are looking for is to print the even numbers twice.
You can do the following without using a for loop by this way.
strarr = ["1","2","3","4","5","6","7","8","9","10"]
k = 2
n = 0
while (n<10):
if(int(strarr[n])%2 == 0):
print(strarr[n])
print(strarr[n])
elif(int(strarr[n])%2 != 0):
print(strarr[n])
n = n+1
The reason why your code gives that output is because,
for the 1st iteration it would print 1, 2, 3
2nd iteration it would print out 3 again as there is another print(stararr[n]) outside the for loop. That's the reason why you are getting the output you are getting.
strarr = ["1","2","3","4","5","6","7","8","9","10"]
k = 2
n = 0
while True:
for i in range(k):
print(strarr[n])
n = n+1
print(strarr[n])
The error that I think you're seeing has to do with the order that you print your output and update the index n. In the current, buggy code, you're printing first, then updating the value. This means that the second print outside of the inner loop prints using the next value of n, not the one you just used in the inner loop. The same index gets used a second time in the first pass of the inner loop the next time, but that's not the value you wanted to see repeated.
The solution to this issue is pretty simple. Rather than updating after you print, update before. You'll need to adjust the starting value of n, but that's no problem:
strarr = ["1","2","3","4","5","6","7","8","9","10"]
k = 2
n = -1 # change starting index
while True:
for i in range(k):
n = n+1 # and reorder the lines in the inner loop
print(strarr[n])
print(strarr[n])
That said, the two loop thing is a lot more awkward than anything I'd really recommend. If you just want to repeat the odd-indexed values in the loop, you can do that much more simply:
for index in range(len(strarr)):
print(strarr[index])
if index % 2 == 1:
print(strarr[index])
Or you can avoid directly needing to index at all, using enumerate to get the index and value of each element in the for statement itself. This is probably a more "Pythonic" way to solve the problem.
for index, value in enumerate(strarr):
print(value)
if index % 2 == 1:
print(value)

Why is this code not valid for all the cases? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I am trying to solve this problem on hacker rank:
Here is my code:
L = []
check = True
num_cases = int(input())
for i in range(num_cases):
num_cubes = int(input())
inp = input()
L = inp.split(" ")
for m in range(0, len(L)):
L[m] = int(L[m])
while len(L) != 1:
x = max(L)
if L.count(x) <= 2:
if x == L[0] or x == L[-1]:
while x in L:
L.remove(x)
else:
check = False
break
else:
check = False
break
if check == False:
print("No")
else:
print("Yes")
L = []
check = True
Here I check if the maximum values of the list lie on either end of the list.
This code is working for all the cases that I have given it but works for none of the cases that the website gives it.
Test case 1: Here
Expected solution to test case 1: Here
PS. please inform me if I need to edit my question in any way.
the L.count(x) <= 2 is not correct, as long as it's at either end repeated number are fine e.g. 1 1 1 1 1 1 should be Yes
the while x in L bit is also incorrect, on two fronts
given 2 1 2 1 2 you're going to remove the 2 from the middle of the sequence, which should not be the case
not that this matters because you're also misunderstanding the behaviour of while... else, so this is never going to work either
finally the way you're going at it is extremely inefficient as you're traversing the entire sequence (looking for the max) on every iteration, with a double-ended queue (collections.deque) this can be solved in O(n):
define a "tip of stack" larger than anything possible (e.g. 231 or 232)
check which is the largest of the first or last of the row
if that is larger than your tip of stack, the row is not stackable
otherwise pop it (popleft/pop) and set it as the new tip of stack
then loop around to (2)
alternatively you can first pop the larger end of the row, then check against the current tip, then set as the new tip, same difference:
def solve(cubes):
"""
:param list(int) cubes: cube edge length
:rtype: bool
:returns: whether the input cubes can be stacked
"""
current = 2**32
cubes = collections.deque(cubes)
while cubes:
# pick largest value from either end
if cubes[0] > cubes[-1]:
val = cubes.popleft()
else:
val = cubes.pop()
# found a cube that's larger than the current top of the
# stack, can't solve
if val > current:
return False
current = val
return True
Also note that for this sort of things you might be well-served by:
separating the "parsing" step from the "resolution" step, this lets you more easily feed values and check results
learn about property-testing tools like hypothesis which can automatically generate and reduce test cases as long as you can define a property which should always hold (that's the hardest part)
You should remove if L.count(x) <= 2: , that is one error in your code's logic.

How to change for loops into while loops in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am still sort of new to python, I can do anything with a while loop and I am still having trouble comprehending that.
for i in range(len(s)):
for x in a: <- where a is an empty set
To get items out of a set without a for loop, you can use an iterator. This is probably what your prof. is referring to. Example:
i = iter(s)
while True:
try:
next(i)
except StopIteration:
break
You can do everything in a while loop but sometimes it can be awkward. The thing about a for loop is that it consumes a sequence.
For your first example, the loop is pretty straight forward because all we really wanted was in index in s
for i in range(len(s)):
print(i)
i = 0
while i < len(s):
print(i)
i += 1
Your second example is more problematic because you can't index sets. Likely, the best way to handle it is to convert the set to a list and index that. Or you could mimic for by creating your own iterator for the set and handling the end-of-iteration exception yourself.
a = set()
for x in a:
print(x)
# this would be illegal because you can't index the set
i = 0
while i < len(a):
print(a[i]) # ERROR
i += 1
# so we make a list
i = 0
_a = list(a)
while i < len(_a):
print(_a[i])
i += 1
# or use an iterator for the set
a_iter = iter(a)
while True:
try:
print(next(a_iter))
except StopIteration:
break
In some languages like C, while is just an abreviated form of for...
while(x < 5)) {...}
for(;x < 5;) {...}
but as you can see, such is not the case with python.

Counting numbers in a range [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have to write a Python script that will allow the user to enter a set of positive numbers and then count how many are
equal to 50
greater than 50
less than 50
Use appropriate output to prove that your program is working.
Just for example's sake, let's write a function that counts how many numbers are above 50, then one for equal to 50, then one for less than 50. Disclaimer: this is not the only, or even the BEST way to accomplish what you want to do, this is just the best teaching aid :). Also, some of the nomenclature may change if you're not using Python 3.x.
#this function returns how many values in the list that's passed to it
#are greater than 50
def greaterThanFifty(list_to_compare):
how_many_above_fifty = 0
for value in list_to_compare:
if value > 50:
how_many_above_fifty += 1
return how_many_above_fifty
#this function returns how many values in the list that's passed to it
#are less than 50
def lessThanFifty(list_to_compare):
how_many_under_fifty = 0
for value in list_to_compare:
if value < 50:
how_many_under_fifty += 1
return how_many_under_fifty
#this function returns how many values in the list that's passed to it
#are equal to 50
def equalToFifty(list_to_compare):
how_many_are_fifty = 0
for value in list_to_compare:
if value == 50:
how_many_are_fifty += 1
return how_many_are_fifty
Now we have our functions that will return the values we need. Again, this is not the only or even the best way to do this, but it's the way I'm using because it teaches a lot of basic strategies like writing modular programs (each function is performed by its own bit of code) and using functions rather than straight code to perform your task. Unfortunately, on their own, this code doesn't do anything. It just defines functions that we'll leverage to solve the problem at hand. In essence -- we've made our hammer, nails, and saw, but now we have to cut the lumber to size and nail it up. Let's do that.
def main(): #this is always the name of our function that does the heavy lifting
list_of_numbers = []
user_input = input("List some numbers, comma separated please: ")
for num in user_input.split(","):
#loop through user_input, split by commas
list_of_numbers.append(num.strip())
#add to list_of_numbers each item that we find in user_input,
#stripped of leading and trailing whitespace
#at this point we've looped through all of user_input and added each number
#to list_of_numbers, so we can use our functions, defined earlier, to return
#the requested values. Luckily we set up our functions to accept
#lists!
greater_than_fifty = greaterThanFifty(list_of_numbers)
less_than_fifty = lessThanFifty(list_of_numbers)
equal_to_fifty = equalToFifty(list_of_numbers)
#now just to display the results to the user, and we're done.
print("There are "+str(greater_than_fifty)+" numbers over fifty")
print("There are "+str(less_than_fifty)"+ numbers under fifty")
print("There are "+str(equal_to_fifty)"+ numbers that are fifty")
We still haven't actually DONE anything, though, since all we've done is define functions that do what we want from start to finish. our greaterThanFifty function is our hammer, our lessThanFifty function is our saw, and our equalToFifty function is our nails. Now we've added a main function, which is our handyman. Now we need to tell him to work. Luckily that's easy :)
main()
That's it! We're done!
For comparison purposes, this is how I'd write all that:
input_list = [int(each.strip()) for each in input("Enter a list of numbers, comma-separated: ").split(",")]
print("{} are less than 50, {} are more than 50, {} are 50".format(len([each for each in input_list if each<50]),len([each for each in input_list if each>50]),len([each for each in input_list if each==50])))
You'll get there, young padawan :)
def main():
inp = input('enter number of positive numbers to enter ')
print 'enter the list of positive numbers'
num = []
count_eq = 0
count_gr = 0
count_ls = 0
for elem in range(inp):
num.append(input(''))
for item in num:
if item == 50:
count_eq += 1
if item > 50:
count_gr += 1
if item < 50:
count_ls += 1
print '%d are equal %d are less than and %d are greater than 50' % (count_eq, count_ls, count_gr)
main()
This is a very basic program ! You should start python's beginner tutorial here

Change part of string into * [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Let's say I have an IBAN: NL20INGB0001234567
How can I change all digits except the last 4 into *:
Input: NL20INGB0001234567
Output: NL20INGB******4567
all digits but NL*20*
Using regex:
>>> import re
>>> strs = 'NL20INGB0001234567'
>>> re.sub(r'(\d+)(?=\d{4}$)', lambda m:'*'*len(m.group(1)), strs)
'NL20INGB******4567'
Simplest?
import re
s='NL20INGB0001234567'
re.sub(r'\d+(\d{4})$',r'****\1',s)
Result:
'NL20INGB****4567'
tmp = ''
iban = 'NL20INGB0001234567'
for i in iban[4:-4]:
if i.isdigit():
tmp += '*'
else:
tmp += i
iban = iban[:4] + tmp + iban[-4:]
>>> iban = "NL20INGB0001234567"
>>> iban[:4] + ''.join(i if i.isalpha() else "*" for i in iban[4:-4]) + iban[-4:]
'NL20INGB******4567'
s = "IBAN: NL20INGB0001234567"
s = [ele for ele in s.split(':')[-1] if ele.strip()]
mask = [1 for ele in range(len(s) - 10)] + [0] * 6 + [1] * 4
print ''.join(["*" if mask[i] == 0 else ele for i, ele in enumerate(s)])
Output:
NL20INGB******4567
Based on the way you worded the question, I'm assuming you want to format an IBAN string from
##################
to
########******####
Based on this, a simple solution is to write this function:
def ConverterFunction(IBAN):
return IBAN[:8]+"******"+IBAN[14:]
and call it with this line:
ConverterFunction(<your IBAN here>)
Of course, attaching assignments or prints where necessary.
EDIT: A bit of an explanation might be necessary, too.
Whatever you are using as IBAN is a string, and strings can be sliced. By slicing, a person can pick up parts of a string and leave others behind. It uses the index of each letter's position, like so:
This is OK
0123456789
Note, the index always starts at 0, not 1.
Example of taking string slices:
examplestring = "EXAMPLE!"
print examplestring[:3] # "[:3]" means "from beginning to position 3"
print examplestring[5:] # "[5:]" means "from position 5 to end of string"
print examplestring[3:5] # "[3:5]" means "from position 3 to position 5"
Output:
>> EXAM
>> LE!
>> MPL
So in my solution, what the function ConverterFunction(IBAN) does is:
#Takes string "IBAN"
#Chops off the beginning and end parts you want to save
#Puts them back together with "******" in the middle
Understand?
Happy coding!

Categories

Resources