Iterate over string within list - python

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)

Related

Find every possibility to insert random number into a string? (python)

I'm new to programming and for an exercise I need to create a list of every possibility to insert a random number (from 0 to 9) in to a string. The number can be inserted et every position in this string.
For example I have the string "Aht50rj2" and I need to find every possibility to insert one number at any position in this string (including the beginning and the end).
So far I wasn't able to find a way to solve this. What is the best way to do this?
Edit:
The Input is a String (like for example "Aht50rj2")
And the expected output is a list with all possible ways.
For example ["0Aht50rj2", "Ah1t50rj2", "Aht50rj29", "Aht501rj2", etc.]
def possibility(word):
possibilities = []
for i in range(0,10):
for j in range(len(word)+1):
H = [k for k in word]
H.insert(j,str(i))
possibilities.append(''.join(H))
return possibilities
I'm not sure what you mean but try my code and see if it worked:
import random # import module "random"
example_string = input('Input a string: ') # Asks user to input a string
length_of_string= len(example_string) # Counts how many characters there are in the string, it'll make sense trust me
example_list=[] # Create a temporary list
example_list[:0]=example_string # Get string, turns it into list
example_list.insert(random.randrange(0, length_of_string), str(random.randrange(0, 9))) # Insert a random number into a random position of the list
list_into_string= ''.join(example_list) # Get string, turns it into string
print(list_into_string) # Print result
Result number 1:
Input a string: stackoverflow
sta1ckoverflow
Result number 2:
Input a string: stackoverflow
stacko8verflow
Result number 3:
Input a string: stackoverflow
stackoverfl5ow

find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string ""

find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string ""
I have tried to code this problem
here is code:
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
a=list(list(zip(*strs))[0])
b=list(list(zip(*strs))[1])
c=list(list(zip(*strs))[2])
a1=""
i=0
while(len(strs)):
if(a[i]==b[i]==c[i]):
a1+=a[i]
return a1
I have tried to solve via extracting element from the list and then comparing with other elements.
Don't know where it got struck no output is showing,
please help!
because len(strs) is always True,Your program is stuck in an infinite loop.
Another problem is that you only extracted the first three elements of each string in the string list, but the length of the largest common string may be greater than three elements
The simplest way possible would be to start building a diet.
Iterate over all the strings and capture the first character of all the strings
Add them to the dict with count 1 and key as first character
If duplicates are found increment the count on the dict key
Now find the largest number in values of dict and store in a variable
Now repeat the procedure for 2 characters build dict with 2 character keys with starting value as 1 and increment the number if duplicate 2 characters are found in list of strings and replace the previous variable value with the highest value from recent dict
Repeat the procedure by incrementing the number of characters to be checked until you get 1 as the highest value in dict, and that value's key is the longest common prefix

Counting the characters in strings within a list, Python

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.

I need help in understanding the function of the number "1" and the word 'sum' in the code below

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)

Replacing Odd and Even-indexed characters in a string

How can I replace even and odd-indexed letters in my strings? I'd like to replace odd-indexed characters with uppercased letters and even-indexed characters with lowercased ones.
x=input("Enter String: ")
How can I modify the inputted string?
This sounds a little like a "do my homework for me" post, but I'll help you out, as I need the training myself.
You can do this by breaking down the problem. (As I am quite new with python syntax, I'm gonna assume that the user has already given an input to string x)
Make a loop, or otherwise iterate through the characters of your string
Make sure you have an index number for each character, which increments for each one
Check if the number is even, by using modulus of 2 (%2). This returns the remainder of a number when divided by 2. In the case of even numbers, that will be 0.
If %2 == 0 set letter to lower case, else set letter to upper case.
append letter to new String, which you defined before the loop. You cannot directly alter a single character in a String, because they are immutable. This means that you cannot change the String itself, but you can assign a new String to the variable.
Done. Print and see if it worked.
Code:
x = "seMi Long StRing WiTH COMPLetely RaNDOM CasINg"
result_string = ""
index = 0;
for c in x:
if(index%2 == 0):
result_string += c.lower()
else:
result_string += c.upper()
index+=1
print(result_string)
s=input()
l=[]
s=s.lower()
l=[i.upper() if s.index(i)%2==0 else i for i in s ]
print("".join(l))
x = 'myname'
for item in range(len(x)):
if item%2==0:
print(x[item].upper())
else:
print(x[item].lower())
this is the for loop i was referring to. but the thing with this line of code is that it is specific to the value you have assigned to the variable x where as the function i provided above can take any string value without us having to repeat the code each time.
def myfunc(string):
result=''
for x in range(len(string)):
if x%2==0:
result=result+string[x].upper()
else:
result=result+string[x].lower()
return result
The above is a function for the question you asked.
A non-function for loop might be easier to grasp right now (like you I am very new to Python as well. So for me it was easier to understand the for loop before I got into functions. Look at my next post for the same.

Categories