I'm using Python (3.x) to create a simple program for an assignment. It takes a multiline input, and if there is more than one consecutive whitespace it strips them out and replaces it with one whitespace. [That's the easy part.] It must also print the value of the most consecutive whitespaces in the entire input.
Example:
input = ("This is the input.")
Should print:
This is the input.
3
My code is below:
def blanks():
#this function works wonderfully!
all_line_max= []
while True:
try:
strline= input()
if len(strline)>0:
z= (maxspaces(strline))
all_line_max.append(z)
y= ' '.join(strline.split())
print(y)
print(z)
if strline =='END':
break
except:
break
print(all_line_max)
def maxspaces(x):
y= list(x)
count = 0
#this is the number of consecutive spaces we've found so far
counts=[]
for character in y:
count_max= 0
if character == ' ':
count= count + 1
if count > count_max:
count_max = count
counts.append(count_max)
else:
count = 0
return(max(counts))
blanks()
I understand that this is probably horribly inefficient, but it seems to almost work. My issue is this: I would like to, once the loop is finished appending to all_lines_max, print the largest value of that list. However, there doesn't seem to be a way to print the max of that list without doing it on every line, if that makes sense. Any ideas on my convoluted code?
Just print the max of all_line_max, right where you currently print the whole list:
print(max(all_line_max))
but leave it at the top level (so dedent once):
def blanks():
all_line_max = []
while True:
try:
strline = input()
if strline:
z = maxspaces(strline)
all_line_max.append(z)
y = ' '.join(strline.split())
print(y)
if strline == 'END':
break
except Exception:
break
print(max(all_line_max))
and remove the print(z) call, which prints the maximum whitespace count per line.
Your maxspaces() function adds count_max to your counts list each time a space is found; not the most efficient method. You don't even need to keep a list there; count_max needs to be moved out of the loop and will then correctly reflect the maximum space count. You also don't have to turn the sentence into a list, you can directly loop over a string:
def maxspaces(x):
max_count = count = 0
for character in x:
if character == ' ':
count += 1
if count > max_count:
max_count = count
else:
count = 0
return max_count
Related
There is some issue with my python code. I am making a program that finds the occurrences of the letter A in a word and if that letter is found and the next letter is not the letter A the A is swapped with the next letter.
As an example TAN being TNA but WHOA staying as WHOA
AARDVARK being ARADVRAK
The issue is when I input ABRACADABRA I get a string index out of range exception. Before I had that exception I had the word that prints it as BRACADABRIi'm not sure why if I have to add another loop in my program.
If you guys also have anymore efficient way to run the code then the way I have please let me know!
def scrambleWord(userInput):
count = 0
scramble = ''
while count < len(userInput):
if userInput[count] =='A' and userInput[count+1] != 'A':
scramble+= userInput[count+1] + userInput[count]
count+=2
elif userInput[count] != 'A':
scramble += userInput[count]
count+=1
if count < len(userInput):
scramble += userInput(len(userInput)-1)
return scramble
#if a is found switch the next letter index with a's index
def main():
userInput = input("Enter a word: ")
finish = scrambleWord(userInput.upper())
print(finish)
main()
When you get to the end of the string and it is an 'A' your program is then asking for the next character which is off the end of the string.
Change the loop so it doesn't include the last character:
while count < len(userInput)-1:
if ...
You can modify your code as below:
def scrambleWord(userInput):
count = 0
scramble = ''
while count < len(userInput):
if count < len(userInput)-1 and userInput[count] =='A' and userInput[count+1] != 'A':
scramble+= userInput[count+1] + userInput[count]
count+=2
else:
scramble += userInput[count]
count+=1
return scramble
You are not checking the condition (count < len(userInput)-1) when logic tries to check for A's occurrence and swap with next letter. It throws string index out of range exception.
The issue arises in your code when last character in input is 'A'.
This is because your first if in the loop tries to access 'count + 1' character during last iteration.
And since there's no character at that position, you get index error.
The simplest solution would be to make a separate if condition for the same.
Updated snippet for while loop might look like this -
# while start
while count < len_: # len_ is length of input
if count + 1 >= len_:
break # break outta loop, copy last character
current = inp[count]
next_ = inp[count + 1]
if current == 'A':
op += ( next_ + current) # op is result
count += 1
else:
op += current
# increment counter by 1
count += 1
# rest of the code after while is same
Another small issue in your code is while copying last character ( after loop ends ), you should use [ ] instead of ( ) to refer last character in input string.
Just for fun :
from functools import reduce
def main():
word = input("Enter a word: ").lower()
scramble = reduce((lambda x,y : x[:-1]+y+'A' \
if (x[-1]=='a' and y!=x[-1]) \
else x+y),word)
print(scramble.upper())
main()
I need to write a code that does a linear search on a character within a string. I have to do it without using any inbuilt functions.
The program should output the index of the found character.
If the character isn't in the sentence it should output -1.
I have tried writing the code but it inputs the sentence and character but then doesn't work.
def linear_search(intList,target):
found = False
count = 0
while count < len(intList):
if intList[count] == target:
count = count + 1
found = True
break
return found
sentence = input('Enter a sentence: ')
character = input('Enter a character: ')
character_found = linear_search(sentence,character)
if character_found:
print("The character is", count, "on the index")
else:
print("The character is -1")
You probably want this:
def linear_search(intList, target):
count = 0
while count < len(intList):
if intList[count] == target:
return count
else:
count += 1
return -1
Problems with your code:
If the value at the current index is equal to target, then you've found it! You can just return count. If not, then you want to increase count. Currently, your code does the opposite.
Your code returns found, which means that it will only ever return True or False. There is actually no need for a found variable, since you can break out of the function by returning, but in any case you should be returning count.
Outside the function, you attempt to refer to count. That won't work, because count is a local variable: a new instance of count is created for every time you run the function, and destroyed after the function returns. Incidentally, this is another reason you should be returning count, not found: you can just check if count == -1.
You are getting stuck in an infinite loop, because you only update the count variable after the solution is found.
Proper implementation of the while loop:
def linear_search(intList, target):
found = False
count = 0
while count < len(intList):
if intList[count] == target:
found = True
break
count = count + 1
I also suggest using a for-loop instead of a while-loop to prevent this mistake:
def linear_search(intList, target):
found = False
count = 0
for i in range(len(intList)):
if intList[i] == target:
found = True
count = i
break
return found
I also noticed some other mistakes, but since they aren't a part of your question I will let you try and solve those yourself first.
New to coding, sorry if the question is too simple.
I am trying to keep a tally of how many times a character in a certain string range appears. I want to use that tally, count, later and add it to different values, and other tallies. If I return it I can't seem to be able to reuse it. How would I be able to reuse the tally, but outside of the loop?
def function(word):
letters = 'abcdefgh'
while count < len(word):
for i in word:
if i in letters:
count += 1
return count
a = count + 5
print(a)
print(function('AaB5a'))
count should be 2, but how do I take it, and add it to other values, like a = count + 5? print(a) does not print 7, or anything.
Like most of the comments already covered, you should remove the return to the end, and also the while loop doesn't seem to be required (and in fact, appears to provide a wrong result).
Please let me know if this is not what you wanted, and I will correct it based on your input, but it does output 2 and prints 7 as you requested in OP
def function(word):
count = 0
letters = 'abcdefgh'
for i in word:
if i in letters:
count += 1
a = count + 5
print(a)
return count
First, you should probably not use the word function to name your function. I changed your sample to check_letters
You also want to create the variable count outside of the while loop so you can save the incremented count. At the end, return the count.
def check_letters(word):
letters = 'abcdefgh'
count = 0
while count < len(word):
for i in word:
if i in letters:
count += 1
return count
Once that is done, you can call the function and pass in your paramenter, it will return an int which in this case, you want to add 5. We're then saving the results to the variable
a = check_letters('AaB5a') + 5
print (a)
11
if you print the check letters, you'll get the return count to the output.
print (check_letters('AaB5a'))
6
I set the count variable to zero because it throws UnboundLocalError: local variable 'count' referenced before assignment. The function will return the count of the string passed in. The count is now returned by the function. You can then assign it to a variable and then add, subtract, etc., to that variable.
def function(word):
letters = 'abcdefgh'
count=0
while count < len(word):
for i in word:
if i in letters:
count += 1
return count
c=function('AaB5a')
a=c + 5
print(a)
I want to calculate the number of integers in the string "abajaao1grg100rgegege".
I tried using isnumeric() but it considers '100' as three different integers and shows the output 4. I want my program to consider 100 as a single integer.
Here is my attempt:
T = int(input())
for x in range(T):
S = input()
m = 0
for k in S:
if (k.isnumeric()):
m += 1
print(m)
I'd use a very basic regex (\d+) then count the number of matches:
import re
string = 'abajaao1grg100rgegege'
print(len(re.findall(r'(\d+)', string)))
# 2
Regex is the go-to tool for this sort of problem, as the other answers have noted. However, here is a solution that uses looping constructs and no regex:
result = sum(y.isdigit() and not x.isdigit() for x,y in zip(myString[1:], myString))
In addition, here is an easy to understand, iterative solution, that also doesn't use regex and is much more clear than the other one, but also more verbose:
def getNumbers(string):
result = 0
for i in range(len(string)):
if string[i].isdigit() and (i==0 or not string[i-1].isdigit()):
result += 1
return result
You can use the regex library to solve this issue.
import re
st = "abajaao1grg100rgegege"
res = re.findall(r'\d+', st)
>>> ['1', '100']
You can check how many numbers you have on that list that the findall returned.
print (len(res))
>>> 2
In order to read more on python regex and the patterns, enter here
Not very Pythonic but for beginners more understandable:
Loop over characters in string and in every iteration remember in the was_digit (logical variable) if the current character is digit - for the next iteration.
Increase the counter only if the previous character was not a digit:
string = 'abajaao1grg100rgegege'
counter = 0 # Reset the counter
was_digit = False # Was previous character a digit?
for ch in string:
if ch.isdigit():
if not was_digit: # previous character was not a digit ...
counter += 1 # ... so it is start of the new number - count it!
was_digit = True # for the next iteration
else:
was_digit = False # for the next iteration
print(counter) # Will print 2
random="1qq11q1qq121a21ws1ssq1";
counter=0
i=0
length=len(random)
while(i<length):
if (random[i].isnumeric()):
z=i+1
counter+=1
while(z<length):
if (random[z].isnumeric()):
z=z+1
continue
else:
break
i=z
else:
i+=1
print ("No of integers",counter)
I'm designing a system that allows users to input a string, and the strength of the string to be determined by the amount of non alphanumeric characters. Points should be awarded like so: +1 for every non-alnum character to a maximum of 3 non-alnum characters.
def non_alnum_2(total,pwd):
count = 0
lid = 3
number = 0
if pwd[count].isalnum():
if True:
print "Nope"
if False:
print "Good job"
count = count + 1
number += 1
if number > lid:
number = lid
return number
total = 0
number = 0
pwd = raw_input("What is your password? ")
non_alnum_2(total, pwd)
print total
total += number
I've only just started coding, so I'm sorry if this seems like a very junior question.
You can simply try:
bonus = min(sum(not c.isalnum() for c in pwd), 3)
If you want to count the number of non-alpha strings you could say
def strength(string):
'''Computes and returns the strength of the string'''
count = 0
# check each character in the string
for char in string:
# increment by 1 if it's non-alphanumeric
if not char.isalpha():
count += 1
# Take whichever is smaller
return min(3, count)
print (strength("test123"))
There are multiple problems with this code.
First, if True: is always true, so the "Nope" will always happen, and if False: is never true, so none of that stuff will ever happen. I think you wanted this:
if pwd[count].isalnum():
print "Nope"
else:
print "Good job"
count = count + 1
number += 1
Also, I think you want to increment count always, not just if it's a symbol, so:
if pwd[count].isalnum():
print "Nope"
else:
print "Good job"
number += 1
count = count + 1
Meanwhile, you need some kind of loop if you want this to happen over and over. For example:
while count < len(pwd):
if pwd[count].isalnum():
# etc.
However, you really don't need to maintain count yourself and keep doing pwd[count]; you can use a for loop for this:
for ch in pwd:
if ch.isalnum():
# etc.
Meanwhile, while you do return a value from the end of the function, you don't do anything with that returned value when you call the function. What you need is:
number = non_alnum_2(total, pwd)
Also, there's no reason to pass total to non_alnum_2 here. In fact, it doesn't do anything useful at all.
So, putting it all together:
def non_alnum_2(pwd):
lid = 3
number = 0
for ch in pwd:
if ch.isalnum():
print "Nope"
else:
print "Good job"
number += 1
if number > lid:
number = lid
return number
pwd = raw_input("What is your password? ")
number = non_alnum_2(pwd)
print number
def non_alnum(s):
temp=[]
for i in s:
if i.isalnum():
continue
else:
temp.append(i)
if temp==[]:
print("The string doesn't contain any non_alphanumeric chars")
else:
print("The string contains non_alphanumeric chars: ",temp)
str1="ABCDEFabcdef123450"
str2="ABCDEF;abcdef'1234!50"
str3="*&%#!}{"
non_alnum(str1)
non_alnum(str2)
non_alnum(str3)