Finding a longest string in for loop - python

I have the task to write a program in which the user inputs 8 words, after which the program prints the longest word inputed and counts the length of the word. I'm having problems with finding the longest inputed string. Here's my code:
counter = 0
for i in range(8):
x = str(input('Enter a word: '))
counter = len(x)
if counter == max(counter):
print('The longest word is: ', counter)
which of course doesn't work.

max can take an argument key which is applied to each element:
words = [raw_input('Enter a word: ') for _ in xrange(8)]
max_word = max(words, key=len)

This ought to do it - this sorts the list using the 'len' operator to obtain the length of each string, and [-1] just picks the last (the longest) one.
words = []
for i in range(8):
words.append(raw_input('Enter a word: '))
longestWord = sorted(words, key=len)[-1]
print 'The longest word is %s (%s character%s)' % (longestWord, len(longestWord), len(longestWord) != 1 and 's' or '')
Mind you it is somewhat inefficient in that it stores all inputs in the array until the loop is over. Maybe better would be this:
longestWord = ''
for i in range(8):
word = raw_input('Enter a word: ')
if len(word) > len(longestWord):
longestWord = word
print 'The longest word is %s (%s character%s)' % (longestWord, len(longestWord), len(longestWord) != 1 and 's' or '')

Consider keeping the lengths in a list and finding the max value in that list.

counter=""
for i in range(8):
x=str(input('Enter a word: '))
if len(counter) < len(x):
counter = x
print('The longest word is: ',x)

Related

Python list index not in order

I'm trying to make it so that my text alternates between upper and lower case like the question ask. It seems to skip 3 in the indexing and I can't figure out why.
sentence = input("Write a sentence")
newList = []
for i in range(len(sentence)):
if sentence[i] != " ":
newList.append(sentence[i])
listJoint = "".join(newList)
newList2 = []
for i in range(len(listJoint)):
if (listJoint.index(listJoint[i]) % 2) == 0:
print(listJoint.index(listJoint[i]))
newList2.append(listJoint[i].upper())
elif (listJoint.index(listJoint[i]) % 2) != 0:
print(listJoint.index(listJoint[i]))
newList2.append(listJoint[i].lower())
print(newList2)
#newListJoint = "".join(newList2)
#print(newListJoint[::-1])
Thanks in advance
List index doesn't go 0 1 2 3 4
The function .index() finds the first occurrence of that letter. 'L' occurs at index 2 and 3 so it would return 2 for both L's.
Iterate through each character of the string and alternate upper/lower methods.
sentence = "Hello"
alternated_sentence = ''
for i, char in enumerate(sentence):
if i % 2:
alternated_sentence += char.upper()
else:
alternated_sentence += char.lower()
print(alternated_sentence)
#hElLo
sentence = input("Write a sentence:")
# Remove spaces (as per your question)
sentence = sentence.replace(' ', '')
# Reverse the string order (as per your question)
sentence = sentence[::-1]
result = []
for i in range(len(sentence)):
if(i%2==1):
result.append(sentence[i].lower())
else:
result.append(sentence[i].upper())
print(''.join(result))
Here's the solution. The above code would give output as follows:
Write a sentence: Hello world
DlRoWoLlEh
I never realised index method referenced the first instance of the character. This works:
sentence = input("Write a sentence")
newList = []
for i in range(len(sentence)):
if sentence[i] != " ":
newList.append(sentence[i])
listJoint = "".join(newList)
newList2 = []
for i, value in enumerate(newList):
if i % 2 == 0:
newList2.append(listJoint[i].upper())
elif i % 2 !=0:
newList2.append(listJoint[i].lower())
newListJoint = "".join(newList2)
print(newListJoint[::-1])

I created an empty list. Take words from the user. Give the total number of words greater then 5

Any mistake is there?
list1 = []
len = int(input('Enter the lenght you want : '))
for k in range(len):
alp = input('Enter your word : ')
list1.append(alp)
print()
print('The original List : ' , list1)
temp1 = 0
temp2 = 0
words = alp.split(" ")
for word in words:
if len(word) >= 5:
temp1 += 1
else :
temp2 += 1
print(temp1)
print(temp2)
Here is the corrected version:
words = [] # try to use more descriptive variable names ('list1' is not clear, 'words' is better)
num_words = int(input('Enter the length you want : '))
for k in range(num_words):
words.append(input('Enter your word : ')) # directly append the inputted word, no need for an intermediate variable
print()
print('The original List : ' , words)
result = 0
for word in words: # no need to split words, as it is already a list of words
if len(word) >= 5:
result += 1 # only count if it is longer than 5 characters
print(result)
As other commenters have mentioned, avoid renamed reserved names such as len, because this leads to mistakes.

How to find the longest word in a string without using split method

I need an algorithm that can find the longest word in a string, I can't use split(), the only predefined function I can use is find() and I don't think it's useful for this solution.
This is what I managed to do so far:
ch=input("donner: ")
def plus_long(ch):
p=ch.find(" ")
if p==-1:
return ch
maximum=""
mot=""
while p!=-1:
mot=ch[:p]
print(mot)
ch=ch[p+1:]
print(ch)
if len(mot)>len(maximum):
maximum=mot
p=ch.find(" ")
return maximum
print("maximum est: ",plus_long(ch))
But this one doesn't check the last word because there are no more spaces.
EDIT: Thank you all for the answers, i realised how to solve it this morning by putting ch in a new variable and comparing it to maximum and it worked
ch=input("donner: ")
def plus_long(ch):
p=ch.find(" ")
if p==-1:
return ch
maximum=""
mot=""
while p!=-1:
mot=ch[:p]
print(mot)
ch=ch[p+1:len(ch)]
print(ch)
if len(mot)>len(maximum):
maximum=mot
p=ch.find(" ")
f=ch
if len(f)>len(maximum):
maximum=f
return maximum
print("maximum est: ",plus_long(ch))
I've split this problem into two parts:
Use find to create the list of words.
Find the longest word in the list.
def plus_long(ch):
letters = "abcdefghijklmnopqrstuvwxyz"
words = ['']
for v in ch:
if letters.find(v.lower()) != -1: # Use find to check if the character is part of the alphabet
words[-1] += v # If so, add that character to the last string in the list
else:
words.append('') # Else, start a new string
result = "" # Check which string is the longest
for word in words:
if len(word) > len(result):
result = word
return result
Test:
>>> plus_long("Hello!!!!!!!!!!! How are you? I am exhausted.")
Output:
'exhausted'
I see that the other answers don't put punctuation into account, so that using their functions, the result would be 'Hello!!!!!!!!!!!'.
You can find using split and len:
# Longest word
# Reading sentence from user
sentence = input("Enter sentence: ")
# Finding longest word
longest = max(sentence.split(), key=len)
# Displaying longest word
print("Longest word is: ", longest)
print("And its length is: ", len(longest))
The output is:
Enter sentence: Tongue tied and twisted just an earth bound misfit I
Longest word is: twisted
And its length is: 7
Here is your code with an addition that checks the last word (len) when p == -1 just as the loop is going to exit. This addition reported the correct max length if the last word is greater than maximum.
ch=input("donner: ")
def plus_long(ch):
p=ch.find(" ")
if p==-1:
return ch
maximum=""
mot=""
while p!=-1:
mot=ch[:p]
print(mot)
ch=ch[p+1:]
print(ch)
if len(mot)>len(maximum):
maximum=mot
p=ch.find(" ")
# 'ch' now has the last word in a sentence
# it needs to be checked against 'maximum'
if p == -1:
if len(ch) > len(maximum):
maximum = ch
return maximum
print("maximum est: ",plus_long(ch))
You can set p to None if the find method returns -1 so that ch[:p] would slice the rest of the string to get the last word:
def plus_long(ch):
maximum = ""
while True:
p = ch.find(" ")
if p == -1:
p = None
mot = ch[:p]
if len(mot) > len(maximum):
maximum = mot
if p is None:
break
ch = ch[p + 1:]
return maximum
Using find
def plus_long(ch):
longest = ""
i = 0
while i < len(ch):
n = ch.find(" ", i)
if n == -1:
n = len(ch)
if len(longest) < len(ch[i:n]):
longest = ch[i:n]
i = n+1
Test:
print (plus_long("there is a cat on a very big banana tree"))
print (plus_long("there is a cat on a mountain"))
print (plus_long("there"))
Output:
banana
mountain
there
ch=input("donner: ")
def plus_long(ch):
word = ''
maximum = ''
for letter in ch:
if letter == ' ':
if len(maximum) < len(word):
maximum = word
word = ''
else:
word += letter
return maximum
print("maximum est: ",plus_long(ch))
this is a very long and probably the worst method as far as Big 'O' Notation is concerned but it is a simple approach for beginners.
def longWord (sentence):
singleWord = ""
words = []
for letter in sentence:
if letter != " ":
singleWord += letter
else:
words += [singleWord]
singleWord = ""
words += [singleWord]
for i in range(len(words)-1):
biggestWord = ""
if len(words[i]) >= len(words[i+1]):
biggestWord += words[i]
else:
biggestWord += words[i+1]
print(words)
print(biggestWord)
longWord("This is a callback")
OUTPUT -
['This', 'is', 'a', 'callback']
callback
I know you already have a few answers. Here's a code with O(1)
ch=input("donner: ")
prev_pos = 0
max_word = ''
for i, sp in enumerate(ch):
if sp == ' ':
if len(ch[prev_pos:i]) > len(max_word): max_word = ch[prev_pos:i]
prev_pos = i+1
if len(ch[prev_pos:]) > len(max_word): max_word = ch[prev_pos:]
print ('longest word :', max_word, 'length :', len(max_word))
The output for this are:
donner: sentence
longest word : sentence length : 8
donner: this sentence
longest word : sentence length : 8
donner: this is a sentence
longest word : sentence length : 8
donner: this sentence is expectedly very lengthy
longest word : expectedly length : 10
donner: word is lengthy
longest word : lengthy length : 7
I wanted to give you an alternate approach as well. I have added comments for you to understand the code
ch=input("donner: ") #input the sentence
word = '' #capture each word in this variable
wd = [] #store all the words into this list
for sp in ch: #iterate thru the string
if sp != ' ': word += sp #concat to create the word
else:
wd.append(word) #add the word to list
word = '' #reset word
wd.append(word) #add the last word to the list
long_word = max(wd,key=len) #find the longest word
print ('longest word :',long_word, 'length :', len(long_word))

I'm trying to perform some manual encoding of strings using python

Probelm Description:
sms_encoding() which accepts a sentence and converts it into an abbreviated sentence to be sent as SMS and returns the abbreviated sentence.
Rules are as follows:
a. Spaces are to be retained as is
b. Each word should be encoded separately
If a word has only vowels then retain the word as is
If a word has a consonant (at least 1) then retain only those consonants
My Code:
#PF-Assgn-50
def sms_encoding(data):
#start writing your code here
vowels=set("aeiouAEIOU")
v_list=[]
c_list=[]
final_list=[]
new_string=''
word=data.split()
word2=[]
for i in range(0,len(word)):
ch=word[i]
#print(ch)
if ch in vowels:
v_list.append(ch)
for letter in word[i]:
if letter not in vowels:
c_list.append(letter)
c_list.append(" ")
new_string=''.join(v_list)+''.join(c_list)
final_list.append(new_string)
#print(v_list)
return ' '.join(final_list)
data="Have a Nice Day"
print(sms_encoding(data))
My Output:
aHv **<2spaces>** Nc **<1space>** Dy
Expected Output:
Hv a Nc Dy (contains only 1 space)
You could iterate over words in the sentence taking only consonants only if the word contains atleast one consonant:
data = "Have a Nice Day"
splitted = data.split()
for i, x in enumerate(splitted):
if not all(y in 'aeiou' for y in x.lower()):
splitted[i] = ''.join([y for y in x if y.lower() not in 'aeiou'])
print(' '.join(splitted))
# Hv a Nc Dy
This will work for all cases... retains all except vowels when even 1 character in a string is not vowel.
def sms_encoding(data):
vowels = set("aeiouAEIOU")
words = data.split()
encoded_words = []
for i in range(0,len(words)):
vow_count = 0
cons_word = []
for x in words[i]:
if x in vowels:
vow_count =vow_count+1
elif x not in vowels:
cons_word.append(x)
if vow_count == len(words[i]):
encoded_words.append(words[i])
elif vow_count != len(words[i]):
encoded_words.append("".join(cons_word))
encoded_msg = " ".join(encoded_words)
return encoded_msg
data=input("Kindly enter your message for sms encoding : ")
print(sms_encoding(data))
Try and let me know!
def sms_encoding(data):
vowel = "aeiouAEIOU"
list1 = data.split()
list2 = []
for i in list1:
length=len(i)
if length == 1:
list2.append(i)
list2.append(" ")#to add spaces between the words
else:
count=0
for a in i:
if a in vowel:
count+=1
if count==length: #to check if all the letters are vowels
list2.append(i)
list2.append(" ")
for a in i:
if a not in vowel:
list2.append(a)
list2.append(" ")
list2.pop() #to remove the extra space at the end of the whole sentence
q="".join(list2)
return q
data = "I love Python aeio"
print(sms_encoding(data))
try this code it will work the question is from infytq
def sms_encoding(data):
data=data.lower()
a=data.split()
v1=""
for i in range(0,len(a)):
z=a[i]
v=""
c1=0
for j in z:
if j not in ('a','e','i','o','u'):
v=v+j
elif j in ('a','e','i','o','u'):
c1=c1+1
if(c1!=len(z)):
v1=v1+v+" "
elif(c1==len(z)):
v1=v1+z+" "
word=v1[0:len(v1)-1]
return word
data="I love Python"
print(sms_encoding(data))
def sms_encoding(new_s):
encrypt_string = []
consonant_list = []
vowel_set = set("aeiouAEIOU")
for word in range(0, len(new_s)):
v_letter = new_s[word]
if v_letter in vowel_set:
encrypt_string.append(v_letter)
for letter in v_letter:
if letter not in vowel_set:
consonant = " ".join(letter)
encrypt_string.append(consonant)
encrypt_string.append(" ")
encrypt_string = "".join(encrypt_string)
print(encrypt_string)
s = input("Enter a string ")
new_s = s.split()
sms_encoding(new_s)

How can I capitalize a character with an odd-numbered index in a string?

So I was doing our exercise when I came across capitalizing characters in odd indices. I tried this:
for i in word:
if i % 2 != 0:
word[i] = word[i].capitalize()
else:
word[i] = word[i]
However, it ends up showing an error saying that not all strings can be converted. Can you help me debug this code snippet?
The problem is strings in python are immutable and you cannot change individual characters. Apart fro that when you iterate through a string you iterate over the characters and not the indices. So you need to use a different approach
A work around is
(using enumerate)
for i,v in enumerate(word):
if i % 2 != 0:
word2+= v.upper()
# Can be word2+=v.capitalize() in your case
# only as your text is only one character long.
else:
word2+= v
Using lists
wordlist = list(word)
for i,v in enumerate(wordlist):
if i % 2 != 0:
wordlist[i]= v.upper()
# Can be wordlist[i]=v.capitalize() in your case
# only as your text is only one character long.
word2 = "".join(wordlist)
A short note on capitalize and upper.
From the docs capitalize
Return a copy of the string with its first character capitalized and the rest lowercased.
So you need to use upper instead.
Return a copy of the string with all the cased characters converted to uppercase.
But in your case both work accurately. Or as Padraic puts it across "there is pretty much no difference in this example efficiency or output wise"
You need enumerate and capitalise any character at any odd i where i is the index of each char in the word:
word = "foobar"
print("".join( ch.upper() if i % 2 else ch for i, ch in enumerate(word)))
fOoBaR
ch.upper() if i % 2 else ch is a conditional expression where we change the char if the condition is True or else leave as is.
You cannot i % 2 when i is the actual character from the string, you would need to use range in your code or use enumerate and concatenate the changed characters to an output string or make words a list.
Using a list you can use assignment:
word = "foobar"
word = list(word)
for i, ele in enumerate(word):
if i % 2:
word[i] = ele.upper()
print("".join(word))
Using an output string:
word = "foobar"
out = ""
for i, ele in enumerate(word):
if i % 2:
out += ele.upper()
else:
out += ele
if i % 2: is the same as writing if i % 2 != 0.
This is how I would change word letters in a word or a sentence to uppercase
word = "tester"
letter_count = 1
new_word = []
for ch in word:
if not letter_count % 2 == 0:
new_word.append(ch.upper())
else:
new_word.append(ch)
letter_count += 1
print "".join(new_word)
if I wanted to change odd words in a sentence to uppercase I would do this
sentence = "this is a how we change odd words to uppercase"
sentence_count = 1
new_sentence = []
for word in sentence.split():
if not sentence_count % 2 == 0:
new_sentence.append(word.title() + " ")
else:
new_sentence.append(word + " ")
sentence_count += 1
print "".join(new_sentence)
I think it will help...
s = input("enter a string : ")
for i in range(0,len(s)):
if(i%2!=0):
s = s.replace(s[i],s[i].upper())
print(s)

Categories