i have a problem with this question:
You have a string containing !, # and small alphabets a-z. You have to escape each character that follows an ! and lies between 2 # symbols. [Treat odd # as ( and even # as ) ] You have to print out how many alphabets will be escaped.
Input Format
Input will be one line containing the string sequence
Constraints
n = len(string_seq)
1 < n < 1000
Output Format
Output will be a single integer
Sample Input 0
#!a!b#c!d
Sample Output 0
2
Sample Input 1
##bc!a#
Sample Output 1
0
Now this code clears 6 out of 9 test cases but i am not able to understand how to make it clear all the test cases i have tried many ways. My suspision is the test caeses might be wrong. Can someome help me tell me if the question is wrong or the test cases is wrong or my code is wrong and if my code is wrong please help me rectify it. Thank You.
def escape(str1):
counter=0
if(str1.count('!')%2==1):
return '0'
for a,b in enumerate(str1):
if(b=='#'):
if(97<=ord(str1[a+1])<=122):
if(str1.index('#')<a+1<len(str1)-str1[::-1].index('#')):
counter+=1
return counter
str1=input()
print(escape(str1))
Tell me if this code works for all your cases so i make my solution better..
case='#h!a!h#gh#!d##ghj#'
cnt=0
temp=''
flag=False
for c in case:
if c=='#':
if flag:
#print(temp)
tl=temp.split('!')
if len(tl)>1:
#print(tl)
#tl=list(filter(('').__ne__, tl))
#print(tl)
cnt+=len(tl)-1
temp=''
flag=False
else:
flag=True
else:
temp+=c
print(cnt)
def escape(str1):
i=0
counter=0
final_counter=0
condition1=False
while(i!=len(str1)):
if(str1[i]=='#' and condition1==False):
condition1=True
i+=1
elif(str1[i]=='#' and condition1==True):
condition1=False
final_counter+=counter
counter=0
i+=1
elif(condition1==True):
if(str1[i]=='!'):
i+=1
if(97<=ord(str1[i])<=122):
counter+=1
i+=1
else:
i+=1
else:
i+=1
return final_counter
I hope this helps.
I think that the problem asks you for the following conditions to increase your counter:
First you can start counting when a '#' appears, otherwise you can't start counting.
Then when you find a letter after a '!' (e.g !a) you increase your counter.
Finally, if another "#" you accumulate everything in your final counter which you are going to print.
Confirm me if this is correct with all your test cases.
Related
I'm currently working on this problem that ask me to generate an arrow pattern using loops function that looks something like this:
"How many columns? 3"
*
*
*
*
*
I know I can do this with for loop(probably more efficient too), but that is not what I aimed for. I wanted to achieve this only using while loop.
I have some ideas:
1. I set up a control variable and an accumulator to control the loop
2. I then write 2 separate loops to generate the upper and lower part of the pattern. I was thinking about inserting the space before the asterisks using method like this:
(accumulator - (accumulator - integer)) * spaces.
#Ask the user how many column and direction of column
#they want to generate
Keep_going = True
Go = 0
while keep_going:
Column_num = int(input("How many columns? "))
if Column_num <= 0:
print("Invalid entry, try again!")
else:
print()
Go = 1
#Upper part
while Keep_going == True and Go == 1:
print("*")
print(""*(Column_num - (Column_num - 1) + "*")
...but I soon realized it wouldn't work because I don't know the user input and thus cannot manually calculate how many spaces to insert before asterisks. Now everything on the internet tells me to use for loop and range function, I could do that, but I think that is not helpful for me to learn python since I couldn't utilize loops very well yet and brute force it with some other method just not going to improve my skills.
I assume this is achievable only using while loop.
#Take your input in MyNumber
MyNumber = 5
i = 1
MyText = '\t*'
while i <=MyNumber:
print(MyText.expandtabs(i-1))
i = i+1
i = i-1
while i >=1:
print(MyText.expandtabs(i-1))
i = i-1
Python - While Loop
Well first you have to understand that a while loop loops until a requirement is met.
And looking at your situation, to determine the number of spaces before the * you should have an ongoing counter, a variable that counts how many spaces are needed before you continue. For example:
###Getting the number of columns###
while True:
number=int(input('Enter number of rows: '))
if number<=0:
print('Invalid')
else:
###Ending the loop###
break
#This will determine the number of spaces before a '*'
counter=0
#Loops until counter equals number
while counter!=number:
print(" "*counter + "*")
#Each time it loops the counter variable increases by 1
counter=counter+1
counter=counter-1
#Getting the second half of the arrow done
while counter!=0:
counter=counter-1
print(" "*counter + "*")
Please reply if this did not help you so that i can give a more detailed response
Apologies if similar questions have been asked but I wasn't able to find anything to fix my issue. I've written a simple piece of code for the Collatz Sequence in Python which seems to work fine for even numbers but gets stuck in an infinite loop when an odd number is enter.
I've not been able to figure out why this is or a way of breaking out of this loop so any help would be greatly appreciate.
print ('Enter a positive integer')
number = (int(input()))
def collatz(number):
while number !=1:
if number % 2 == 0:
number = number/2
print (number)
collatz(number)
elif number % 2 == 1:
number = 3*number+1
print (number)
collatz(number)
collatz(number)
Your function lacks any return statements, so by default it returns None. You might possibly wish to define the function so it returns how many steps away from 1 the input number is. You might even choose to cache such results.
You seem to want to make a recursive call, yet you also use a while loop. Pick one or the other.
When recursing, you don't have to reassign a variable, you could choose to put the expression into the call, like this:
if number % 2 == 0:
collatz(number / 2)
elif ...
This brings us the crux of the matter. In the course of recursing, you have created many stack frames, each having its own private variable named number and containing distinct values. You are confusing yourself by changing number in the current stack frame, and copying it to the next level frame when you make a recursive call. In the even case this works out for your termination clause, but not in the odd case. You would have been better off with just a while loop and no recursion at all.
You may find that http://pythontutor.com/ helps you understand what is happening.
A power-of-two input will terminate, but you'll see it takes pretty long to pop those extra frames from the stack.
I have simplified the code required to find how many steps it takes for a number to get to zero following the Collatz Conjecture Theory.
def collatz():
steps = 0
sample = int(input('Enter number: '))
y = sample
while sample != 1:
if sample % 2 == 0:
sample = sample // 2
steps += 1
else:
sample = (sample*3)+1
steps += 1
print('\n')
print('Took '+ str(steps)+' steps to get '+ str(y)+' down to 1.')
collatz()
Hope this helps!
Hereafter is my code snippet and it worked perfectly
#!/usr/bin/python
def collatz(i):
if i % 2 == 0:
n = i // 2
print n
if n != 1:
collatz(n)
elif i % 2 == 1:
n = 3 * i + 1
print n
if n != 1:
collatz(n)
try:
i = int(raw_input("Enter number:\n"))
collatz(i)
except ValueError:
print "Error: You Must enter integer"
Here is my interpretation of the assignment, this handles negative numbers and repeated non-integer inputs use cases as well. Without nesting your code in a while True loop, the code will fail on repeated non-integer use-cases.
def collatz(number):
if number % 2 == 0:
print(number // 2)
return(number // 2)
elif number % 2 == 1:
result = 3 * number + 1
print(result)
return(result)
# Program starts here.
while True:
try:
# Ask for input
n = input('Please enter a number: ')
# If number is negative or 0, asks for positive and starts over.
if int(n) < 1:
print('Please enter a positive INTEGER!')
continue
#If number is applicable, goes through collatz function.
while n != 1:
n = collatz(int(n))
# If input is a non-integer, asks for a valid integer and starts over.
except ValueError:
print('Please enter a valid INTEGER!')
# General catch all for any other error.
else:
continue
I am doing a string compress feature with while and for loop. The idea is:
1. Use the 1st character to loop through the string, and then stop when the next char is not the same
2. slide the old string by remove the first same characters
3. redo the loop until the string len = 0.
Somehow my initial code didnt work -> I use a helper ( adding 2 "$$" characters to end of initial string, and loop until last 2 $$.
Can anyone help me to solve this problem without using the helper!
thank you very much.
here is my code:
text = 'aaxxxxxxxbccccaaxxxaa'
text =text+"$$" # this is the helper, I would like the do the task without
using helper
count=0
result=''
while len(text)>2:
for x in range(0,len(text)):
if text[x]==text[0]:
#print( text[x])
count+=1
else:
print(text[0]+str(count))
result = result+text[0]+str(count)
print(result)
text =text[count:]
count=0
break
P.s If I don't use helper, I get Out of string range.
this code below will print: a2x7b1c4a2x3a2
text = 'aaxxxxxxxbccccaaxxxaa'
text =text+"$$" # this is the helper, I would like the do the task withou using
helper
count=0
result=''
while len(text)>2:
for x in range(0,len(text)):
if text[x]==text[0]:
#print( text[x])
count+=1
else:
#print(text[0]+str(count))
result = result+text[0]+str(count)
#print(result)
text =text[count:]
count=0
break
print(result)
I want to remove helper, and get the same a2x7b1c4a2x3a2 with the 2nd code below, but Jupiter notebook will die (I guess infinite loop happen)
text = 'aaxxxxxxxbccccaaxxxaa'
count=0
result=''
while len(text)>0:
for x in range(0,len(text)):
if text[x]==text[0]:
#print( text[x])
count+=1
else:
#print(text[0]+str(count))
result = result+text[0]+str(count)
#print(result)
text =text[count:]
count=0
break
print(result)
I have a problem where two strings of same length are given, and I have to tell how many letters I have to change in the first string to make it an anagram of the second.
Here is what I did:
count = 0
Mutable_str = ''.join(sorted("hhpddlnnsjfoyxpci"))
Ref_str = ''.join(sorted("ioigvjqzfbpllssuj"))
i = 0
while i < len(Mutable_str):
if Mutable_str[i] != Ref_str[i]:
count += 1
i += 1
print(count)
My algorithm in this case returned 16 as result. But the correct answer is 10. Can someone tell me what is wrong in my code?
Thank you very much!
You need to use str.count
So you need to add up the differences between the number of occurrences of each character in the different strings. This can be done with str.count(c) where c is each distinct character in the second string (got with set()). We then need to use max() on the difference with 0 so that if the difference is negative this doesn't effect the total differences.
So as you can see, it boils down to one neat little one-liner:
def changes(s1, s2):
return sum(max(0, s2.count(c) - s1.count(c)) for c in set(s2))
and some tests:
>>> changes("hhpddlnnsjfoyxpci", "ioigvjqzfbpllssuj")
10
>>> changes("abc", "bcd")
1
>>> changes("jimmy", "bobby")
4
Simple question but it is driving me nuts. why when I run this code does it just keep repeating itself? And my indentations are correct just had to space 4 times to post this for whatever reason.
High Scores
0 - Exit
1 - Show Scores
Source code:
scores = []
choice = None
while choice != "0":
print(
"""
High Scores
0 - Exit
1 - Show Scores
"""
)
choice = input("choice: ")
print()
if choice == "0":
print ("exiting")
elif choice == "1":
score = int(input("what score did you get?: "))
scores.append(score)
else:
print ("no")
input ("\n\nPress enter to exit")
This is because you are not using proper indentation. Please indent the code under the while loop that you want to execute while choice != 0
Further there is no mistake with comparison as #wookie919 wrongly indicated because you're taking a String as input and not an Int. You can however typecast your input as a string by wrapping it around an int() like int(input("Choice .. "))
Hope it helped.
It's because you are comparing an Integer to a String. Try entering "0" instead of just 0. Or modify your program to compare with 0 instead of "0".