I wrote the function that converts the string in argument to number. If the string does not contain number the cycle breaks and the new variable with numbers is printed.
If the argument is "123" the function returns 6. I don't want to return the sum, just placing every number in a row. How do I accomplish the result 123? I don!t know what to use instead of string2 += float(c).
def try_parse(string):
string2=0
for c in string:
if c.isdigit() == True:
string2 += float(c)
else:
break
return string2
I modified your code:
def try_parse(string):
string2 = ""
for c in string:
if not c.isdigit() and c != '.':
break
string2 += c
return string2
You can see that now I use string2 as a string and not an int (When the + sign is used on an int you sum, and with a string + is used for concatenation).
Also, I used a more readable if condition.
Update:
Now the condition is ignoring the '.'.
Tests:
>>> try_parse('123')
'123'
>>> try_parse('12n3')
'12'
>>> try_parse('')
''
>>> try_parse('4.13n3')
'4.13'
Note
The return type is string you can use the float() function wherever you like :)
You need to use a string for string2, and str instead of float.
You want string2 = "", and string2 += c. (You don't need to call str on c because it is already a string.)
You could leave the conversion to a number to Python (using int(), rather than float(); you only filter on digits), and only worry about filtering:
def try_parse(string):
digits = []
for c in string:
if c.isdigit():
digits.append(c)
return int(''.join(digits))
but if you really want to build a number yourself, you need to take into account that digits are not just their face value. 1 in 123 does not have the value of one. It has a value of 100.
The easiest way then to build your number would be to multiply the number you have so far by 10 before adding the next digit. That way 1 stays 1, and 12 starts as 1 then becomes 10 as you add the 2, etc:
def try_parse(string):
result = 0
for c in string:
if c.isdigit():
result = result * 10 + int(c)
return result
Related
I mean like it is gonna ask me to type some string and ask me to type one letter and gives me position of it.
like "Hello"
i wanna letter e
it gives me position 2.
Thank you for answer
There are two ways I know of that you could use, one makes the string into a list, making it easier to iterate through, and the other just iterates through the string.
Option #1 (String):
string = 'Hello'
for char in string:
if char == 'e':
break <or whatever code you want here>
Option #2 (List):
def split(string):
return [char for char in string]
string = 'Hello'
for char in split(string):
if char == 'e':
break <or your code>
You can use the .find method.
string = input() # Gets the input from the user
character = input() # Gets another input from the user (the character)
index = string.find(character) # This function is going to return the index of character in string
print(index + 1)
It prints index + 1 because the index in python (actually most languages) starts at 0
Input:
Hello
e
Output:
2
I'm looking to take in two strings via user input and to call a function to match each character from the first string to that of the second string, and count them. So String 1 = bad and String 2 = bed would return a count of 2 characters matched
def occurrences(text1, text2):
count = 0
for c in firstword :
if c == secondword :
count += 1
return True
return False
firstword = input("Enter first word")
secondword = input("Enter second word")
occurrences(firstword, secondword)
Passing the two strings into the function returns false, even if they're exactly the same word. Just wondering where I'm going wrong with the for loop here, why is the if statement not matching the strings and counting.
Thanks
for c in firstword :
if c == secondword :
You're iterating over the first string character by character (for c in firstword), and you match that one character to the entire second string secondword. Not to mention that:
you're using the outer variables firstword and secondword instead of the function parameters text1 and text2
your function only returns True or False, at no point does it even attempt to return a count
you return True right on the first match, if there ever was one, so it could never progress beyond 1
To compare two strings character by character, you need to iterate both string in parallel. The best way to do that is zip:
count = 0
for c1, c2 in zip(text1, text2):
if c1 == c2:
count += 1
Which can be made into a one-liner with sum:
def occurrences(text1, text2):
return sum(c1 == c2 for c1, c2 in zip(text1, text2))
Silly bonus round, if you want to be really fancy and functional about it:
from operator import eq
from itertools import starmap
def occurrences(text1, text2):
return sum(starmap(eq, zip(text1, text2)))
In function when you arrive on return, the function is ending so when you want counting and end of for-loop return your counter don't set return in for-loop.
try this:
def occurrences(text1, text2):
count = 0
for c in firstword :
if c in secondword :
count += 1
return count
firstword = input("Enter first word : ")
secondword = input("Enter second word : ")
occurrences(firstword, secondword)
output:
Enter first word : bad
Enter second word : bed
2
Let's say I have a string a = 31 4 5 + + and a string b = 31 4 5 ++. I need to check that all numbers and operators in the string are delimited by at least one white space. Therefore, string a is correct, string b incorrect. c = 31 4 5+ + is also incorrect. Is there a way how to check for this? I could not come up with anything reasonable.
You can check it through following steps -
Break string into list using .split()
Check whether items in list whose length is more than 1 is numeric or not.
Code snippet:
def is_valid_string(st, delimiter = ' '):
lst = st.split(delimiter) # create list of chars separated by space
for item in lst:
if len(item) > 1 and not item.isdigit():
return False
return True
In case if you are considering float numbers you can use item.replace('.','',1).isdigit()
First thing to do would be splitting the strings by the whitespaces into "words", so something like words = a.split() (split's delimitor is a whitespace by default so no need for arguments)
I'm guessing you're only gonna use integers or floats and a set of operators like adding, substraction, multiplication and division, so one thing that you could do is check if you can cast the words into numbers with int or float and if you can't, check if the word is in your operators set, so something like:
a = "31 4 5 + +"
operators = ["+", "-", "*", "/"]
# Every string is valid by default
valid = True
words = a.split() # ["31", "4", "5", "+", "+"]
for word in words:
# try to cast word into a number
try:
float(word)
except:
# if you can't, check if it's an operator
if word not in operators:
valid = False #if it's not, the string isn't valid
if valid:
print("String is valid")
else:
print("String is not valid")
More complex stuff like equations and variables is obviously more difficult to code.
EDIT: python's isdigit() checks if a string is a number and it is more simple than a try block for casting the string, but it doesn't check for floats, which won't be valid. (you could still replace decimal points by numbers)
Try use regex ^((\d+|[+*/-])(\s+|$))+$. It matches more or more items, each of which is either a number (\d+) or an operator ([+*/-]), followed by either one or more spaces (\s+) or the end of string ($). The ^ at the beginning and ($) at the end force the regex match the whole string. Example:
>>> import re
>>> a = '31 4 5 + +'
>>> b = '31 4 5 ++'
>>> c = '31 4 5+ +'
>>> print(re.match(r'^((\d+|[+*/-])(\s+|$))+$', a))
<re.Match object; span=(0, 10), match='31 4 5 + +'>
>>> print(re.match(r'^((\d+|[+*/-])(\s+|$))+$', b))
None
>>> print(re.match(r'^((\d+|[+*/-])(\s+|$))+$', c))
None
Write a recursive function, len, that accepts a parameter that holds a string value, and returns the number of characters in the string.
The length of the string is:
0 if the string is empty ("")
1 more than the length of the string beyond the first character
This is what I got so far:
def len(string):
if len(string) == ""
return 0
else:
return string[len(string)+1]
What am I doing wrong? Thx
len() is supposed to return an integer. I think they're looking for something like this:
def len(string):
if string == "":
# 0 if the string is empty
return 0
else:
# one more than the length of the string beyond the first character
return 1 + len(string[1:])
You forgot to reduce the problem on your recursive call. You programmed an infinite recursion. The critical statement is to recur on a shorter string:
return len(string[1:]) + 1
beginner here. Trying to figure out how I can define a function that counts the total number of occurrences of certain characters in a string. Say, we want to count the number of occurrences of the letters a and b. I need to do it within a for loop. What I have so far is this. Please let me know what I can do to make this work!
#define functions
def ch_count(word):
total=0
for letter in word:
if letter==L1:
total=total+1
return total
#main program
L1=["a","e","y"]
print(ch_count("Merry Christmas")
You can try using a default dictionary. Unlike a normal dictionary, it provides a default value is a key does not exist in a dictionary.
from collections import defaultdict
string = 'quick brown fox'
letter_count = defaultdict(int)
for letter in string:
letter_count[letter] += 1
print(letter_count)
you could write a function which takes 2 arguments. The string to check, and the letter that we want to use to count occurrencies in the string.
# I will use a as a default letter
def count_occurrencies(s, letter='a'):
return sum([i == letter for i in s])
You can use sum:
string = 'Some test string'
c = 'a'
sum(x == c for x in string)
Checking for multiple characters instead:
c = 'abc'
sum(x in c for x in string)
Or you can use collections.Counter to find the count of each character:
from collections import Counter
counts = Counter(string)
counts[letter]