I am having difficulty with one of my homework questions.
Basically, I am to create a function using a for loop to count the characters used in strings which are inside of a list. I am able to get the length of the strings with len(), but I can only get one of the strings and I can't seem to get it in list form.
My Code:
def method1(input1):
total = 0
a = []
for word in input1:
total = len(word)
a = [total]
return a
This returns [3] with the input ['seven', 'one']
Any help would be appreciated. I am very new to Python.
Well here is one way of doing it. You have list "a" with different strings inside of them. You can simply iterate through the list counting the length of each string.
def method1(input1):
l = list(input1)
total = sum(len(i) for i in l)
return int(total)
print(method1(["hello", "bye"]))
What you are doing here is receiving an input and converting it to a list. Then for each value inside of the list, you are calculating it's length. The sum adds up those lengths and finally, you return total.
Related
lst = ["abc", "sassafrass", "bingo", "bass"]
My problem that I need help with is that I want to iterate through each character and count characters within each string. So I used the nested for loop......ex:
def multi_letter(s)
for c in s:
for l in c:
so basically I want to count each letter (l) in each word (c) in the list but organized as the word.....lets say that the letters have numerical value and I want to add them up...
I DON'T WANT THE ANSWER!!! Please help me find an answer......I'm lost and a beginner looking for understanding......Thanks in advance!!
You are off to a good start. The nested loop will give you each letter from each word. One way to get the numeric value is using:
ord(l)
From the documentation:
Given a string representing one Unicode character, return an integer
representing the Unicode code point of that character. For example,
ord('a') returns the integer 97.
97 is the ASCII value of the a.
You can add these values up and you will get the numerical value of the word.
But that won't be very helpful. Consider a string zz - your sum will be 244; and QQR will also give you 244. This is just one of infinite possibilities.
May be this code help you:
lst = ["abc", "sassafrass", "bingo", "bass"]
#make a empty list to store count
count=[]
for i in range(len(lst)):
count.append(len(lst[i]))
print(count)
I am trying to create a golf calculator in which I enter two strings (par_string,score_string). For each item in par_string and score_string, I subtract the score_string item from the par_string item.
I have tried turning the strings into integers but it still doesn't work.
#score_string-par_string
def golf_score_calculator(par_string, score_string):
new_str = ""
par = int(par_string,10)
score = int(score_string,10)
for i in str(par):
for i in str(score):
new_str += score_string[i]-par_string[i]
return new_str
print(golf_score_calculator("12","13"))
What should happen is that each time a value is subtracted, it adds on to new_str.
I think that the problem is bacause you are using the same index for two nested loops.
Well it is odd you are using strings instead of lists of ints but if you have two strings and you want the difference, simply doing
def golf_score_calculator(par_string, score_string):
return str(int(par_string) - int(score_string))
should be what you want.
How will I be able to count the number of time a list of items are repeated in a string. For example how can I search through string and check the number of times this list has been repeated in string?
list = ('+','-','*','/')
string = "33+33-33*33/33"
Firstly, don't use a name like list, it masks the built-in name list [See: Built-in Methods] and that can lead to some subtle bugs.
After that, there's ways to do this. The crucial thing to have in mind is that objects like strings come along with a plethora of methods [See: String Methods] that act on them. One of these methods is str.count(sub) which counts the number of times sub occurs in your string.
So, creating a count for every element in lst could be done by using a for loop:
lst = ('+','-','*','/')
string = "33+33-33*33/33"
for i in lst:
print("Item ", i, " occured", str(string.count(i)), "times")
str(string.count(i)) transforms the integer result of string.count to an str object so it can be printed by print.
This prints out:
Item + occured 1 times
Item - occured 1 times
Item * occured 1 times
Item / occured 1 times
After getting more accustomed to Python you could use a comprehension to create a list of the results and supply them to print:
print(*["Item {} occured {} times".format(x, string.count(x)) for x in lst], sep='\n')
which prints a similar result.
Finally, make sure you read the Tutorial available on the Python documentation website, it'll help you get acquainted with the language.
This is the solution to counting upper and lower case letters in a sentence that my friend gave to me without explaining the use of 1 in the statements.
x = raw_input('Enter the word')
print ("Capital Letters: ", sum(1 for d in x if d.isupper()))
print ("Small letters:" , sum(1 for d in x if d.islower()))
Could anyone help me explain why 1 is used ? also why is sum used instead of len?
Thanks
The sum function takes in a container as its arguments and returns the sum of its elements.
This line, sum(1 for d in x if d.isupper()), feeds a generator expression to the sum function, consisting of ones, which in effect counts the number of upper case words in the string.
For example if your string was HeLLo, it would essentially look like sum((1,1,1)), which is equal to 3.
He's filtering all the capital letters in a string and building a list of 1's for each item in the remaining list. Then he's summing that list. Since the list comprehension is building a generator and not a list, len cannot be used.
(Edited. Previous version said len could be used equivalently)
I'm currently learning python so I apologize in advance for the messiness of my code. My function is meant to take in a single string and add the string numbers together. i.e. A string argument of 123 will become 1 + 2 + 3 and return 6.
My issue is when I iterate through my list - python keeps indicating that the variable has been referenced before any value has been assigned. However when I print out the values being calculated they are correct. Even more confusing is that when I return them - they are incorrect. I can't seem to work out where I'm going wrong. Could anyone tell me what the issue may be?
Thank you!
listy = []
global total
#Convert number to a list then cycle through the list manually via elements and add them all up
def digit_sum(x):
number= []
number.append(x)
print number
for i in range(len(number)):
result = str(number[i])
print result
#Now it has been converted to a string so we should be able to
#read each number separately now and re-convert them to integers
for i in result:
listy.append(i)
print listy
#listy is printing [5,3,4]
for i in listy:
total += int(i)
return total
print digit_sum(x)
I'm not really sure what's going on in your code there, especially with the messed up indentation, but your problem is easily sovled:
sum(map(int, str(534)))
It makes the number a string, then converts each digit to an int with map, then just sums it all.
If your concern is only about summing a string of numbers, then list comprehension itself would do or as #Maltysen suggested you could use map
sum([int(x) for x in "534"])
pretty simple:
You can use a map or a list comprehension. They are pretty much equivalent. Other people gave an answer using map but I decided to use a list comprehension.
s = "1234567"
sum([int(character) for character in s])
I believe I have worked out what was wrong with my code. As I am still new to Python, I made some very novice mistakes such as not realizing declaring a variable outside the local function would result in the solution not being what I had expected.
Due to my returns being placed incorrectly as well as my listy [] variable being instantiated outside my function, instead of reading each number once, it would read it three times.
This has now been corrected in the code below.
#Convert number to a list then cycle through the list manually via elements and add them all up
def digit_sum(x):
total = 0
number= []
number.append(x)
print number
for i in range(len(number)):
result = str(number[i])
print result
#Now it has been converted to a string so we should be able to
#read each number separately now and re-convert them to integers
for i in result:
listy = []
listy.append(i)
# print listy
#listy is printing [5,3,4]
for i in listy:
print i
total+= int(i)
print total
break
return total
print digit_sum(111)