I have to write an application that asks the user to enter a list of numbers separated by a space and then prints the sum of the numbers. The user can enter any number of numbers. I am not allowed to use the split function in python. I was wondering how I can do it that. Any help would be appreciated it as I'm kind of stuck on where to start.
Possible solution is to use regular expressions:
# import regular expression library
import re
# let user enter numbers and store user data into 'data' variable
data = input("Enter numbers separated by space: ")
"""
regular expression pattern '\d+' means the following:
'\d' - any number character,
'+' - one or more occurence of the character
're.findall' will find all occurrences of regular expression pattern
and store to list like '['1', '258', '475', '2', '6']'
please note that list items stored as str type
"""
numbers = re.findall(r'\d+', data)
"""
list comprehension '[int(_) for _ in numbers]' converts
list items to int type
'sum()' - summarizes list items
"""
summary = sum([int(_) for _ in numbers])
print(f'Sum: {summary}')
Another solution is following:
string = input("Enter numbers separated by space: ")
splits = []
pos = -1
last_pos = -1
while ' ' in string[pos + 1:]:
pos = string.index(' ', pos + 1)
splits.append(string[last_pos + 1:pos])
last_pos = pos
splits.append(string[last_pos + 1:])
summary = sum([int(_) for _ in filter(None, splits)])
print(f'Sum: {summary}')
From my point of view, the first option is more concise and better protected from user errors.
Related
'''def tokenize(s):
string = s.lower().split()
getVals = list([val for val in s if val.isalnum()])
result = "".join(getVals)
print (result)'''
tokenize('AKKK#eastern B!##est!')
Im trying for the output of ('akkkeastern', 'best')
but my output for the above code is - AKKKeasternBest
what are the changes I should be making
Using a list comprehension is a good way to filter elements out of a sequence like a string. In the example below, the list comprehension is used to build a list of characters (characters are also strings in Python) that are either alphanumeric or a space - we are keeping the space around to use later to split the list. After the filtered list is created, what's left to do is make a string out of it using join and last but not least use split to break it in two at the space.
Example:
string = 'AKKK#eastern B!##est!'
# Removes non-alpha chars, but preserves space
filtered = [
char.lower()
for char in string
if char.isalnum() or char == " "
]
# String-ifies filtered list, and splits on space
result = "".join(filtered).split()
print(result)
Output:
['akkkeastern', 'best']
so, i have assingment from my course, it requires me to find a word (or more) from a list that contain a specific character from input.
lets say i have this list
word = ["eat", "drink", "yoga", "swim"]
and when i given input A, it should return me
["eat", "yoga"]
You can use list comprehension.
ch = input("enter character")
output = [w for w in word if ch.lower() in w]
You may want to add some checks on the input (e.g. input is a single character or not)
try this
list = ["eat", "drink", "yoga", "swim"]
reslst = []
alpa = input("enter character") #convert into lowercase
ch = alpa.lower()
for i in list:
#check if character is in string
if ch in i:
reslst.append(i)
print(reslst)
My question is more or less similar to:
Is there a way to substring a string in Python?
but it's more specifically oriented.
How can I get a par of a string which is located between two known words in the initial string.
Example:
mySrting = "this is the initial string"
Substring = "initial"
knowing that "the" and "string" are the two known words in the string that can be used to get the substring.
Thank you!
You can start with simple string manipulation here. str.index is your best friend there, as it will tell you the position of a substring within a string; and you can also start searching somewhere later in the string:
>>> myString = "this is the initial string"
>>> myString.index('the')
8
>>> myString.index('string', 8)
20
Looking at the slice [8:20], we already get close to what we want:
>>> myString[8:20]
'the initial '
Of course, since we found the beginning position of 'the', we need to account for its length. And finally, we might want to strip whitespace:
>>> myString[8 + 3:20]
' initial '
>>> myString[8 + 3:20].strip()
'initial'
Combined, you would do this:
startIndex = myString.index('the')
substring = myString[startIndex + 3 : myString.index('string', startIndex)].strip()
If you want to look for matches multiple times, then you just need to repeat doing this while looking only at the rest of the string. Since str.index will only ever find the first match, you can use this to scan the string very efficiently:
searchString = 'this is the initial string but I added the relevant string pair a few more times into the search string.'
startWord = 'the'
endWord = 'string'
results = []
index = 0
while True:
try:
startIndex = searchString.index(startWord, index)
endIndex = searchString.index(endWord, startIndex)
results.append(searchString[startIndex + len(startWord):endIndex].strip())
# move the index to the end
index = endIndex + len(endWord)
except ValueError:
# str.index raises a ValueError if there is no match; in that
# case we know that we’re done looking at the string, so we can
# break out of the loop
break
print(results)
# ['initial', 'relevant', 'search']
You can also try something like this:
mystring = "this is the initial string"
mystring = mystring.strip().split(" ")
for i in range(1,len(mystring)-1):
if(mystring[i-1] == "the" and mystring[i+1] == "string"):
print(mystring[i])
I suggest using a combination of list, split and join methods.
This should help if you are looking for more than 1 word in the substring.
Turn the string into array:
words = list(string.split())
Get the index of your opening and closing markers then return the substring:
open = words.index('the')
close = words.index('string')
substring = ''.join(words[open+1:close])
You may want to improve a bit with the checking for the validity before proceeding.
If your problem gets more complex, i.e multiple occurrences of the pair values, I suggest using regular expression.
import re
substring = ''.join(re.findall(r'the (.+?) string', string))
The re should store substrings separately if you view them in list.
I am using the spaces between the description to rule out the spaces between words, you can modify to your needs as well.
Input:
to-camel-case
to_camel_case
Desired output:
toCamelCase
My code:
def to_camel_case(text):
lst =['_', '-']
if text is None:
return ''
else:
for char in text:
if text in lst:
text = text.replace(char, '').title()
return text
Issues:
1) The input could be an empty string - the above code does not return '' but None;
2) I am not sure that the title()method could help me obtaining the desired output(only the first letter of each word before the '-' or the '_' in caps except for the first.
I prefer not to use regex if possible.
A better way to do this would be using a list comprehension. The problem with a for loop is that when you remove characters from text, the loop changes (since you're supposed to iterate over every item originally in the loop). It's also hard to capitalize the next letter after replacing a _ or - because you don't have any context about what came before or after.
def to_camel_case(text):
# Split also removes the characters
# Start by converting - to _, then splitting on _
l = text.replace('-','_').split('_')
# No text left after splitting
if not len(l):
return ""
# Break the list into two parts
first = l[0]
rest = l[1:]
return first + ''.join(word.capitalize() for word in rest)
And our result:
print to_camel_case("hello-world")
Gives helloWorld
This method is quite flexible, and can even handle cases like "hello_world-how_are--you--", which could be difficult using regex if you're new to it.
Print all the ways of arranging the letters in a word.
Given a word, print every possible rearrangement of the letters in the word.
word = input("Write your word:")
My attempt is below:
The factorial of len(word) provides the number of permutations.
count = 1
i = len(word)
while i > 0:
count *= i
i-=1
factorial = count # i!
f_minus = int(count/len(word)) # (i - 1)!
print("There are " + str(count) + " ways to arrange " + str(len(word)) \
+ " letters.")
Create a list to append rearranged words.
inside_list = []
for i in range(len(word)):
inside_list.append('')
Create a List to contain each inside_list.
container_list = []
for i in range(factorial):
container_list.append(inside_list)
The variable f_minus provides details about how many times each letter appears at the start of the word . Sticking with 'farm', f_minus = (4-1)! = 6. This tells us that each letter appears in the first position six times. The following for loop prints 'f' six times, followed by six 'a's and so on.
for index in range(factorial):
print(index + 1, word[index//f_minus])
So the following for loop assigns letters to the first element of each nested list.
for index in range(factorial):
container_list[index][0] = word[index//f_minus]
print(container_list)
How can I save the iterations to the list of lists so that the 'f's, 'a's, 'r's and 'm's go into the first element of the nested lists rather than all 'm's? i.e. the first 6 lists have an 'f' as their first element, the next 6 lists have an 'a' as the first element and so on.
There is already a function called permutations in itertools library for this purpose. You can use that instead of re-inventing the wheel.
from itertools import permutations
word = input("Write your word:")
print (["".join(wd) for wd in permutations(word, len(word))])
>>> Write your word:asd
>>> ['asd', 'ads', 'sad', 'sda', 'das', 'dsa']