string in index out of range grok learning - python

I am trying to make s programme that takes text and gives back to the user every 3rd letter including the first letter.This is what i wrote.
msg = input('Message? ')
for i in range(len(msg)):
(i) = (i*3)
print(msg[i], end=' ')
This gives back every thurd letter including the 1st letter but then also gives the error:
File "program.py", line 4, in
print(msg[i], end=' ')
IndexError: string index out of range
Also the software I am using says: Testing the first example but ignoring whitespace. Your submission raised an exception of type IndexError. This occurred on line 4 of your submission.
Whats the simplest way to fix this?

Let's say you have the string "Here we are". It has length 11. You are letting i go all the way to the end of the string, but once i reaches 4, that string at index i * 3 (12) is not defined. Instead, you shouldn't go farther than i divided by 3 (rounding down). This is how you would do that:
msg = input('Message? ')
for i in range((len(msg) // 3) + 1):
(i) = (i*3)
print(msg[i], end=' ')

what you want to do can easily be achieved by slicing the string
msg = input('Message? ')
print(msg[::3])

This should work:
msg = input("Message?: ")
count = 1
for i in msg:
if count % 3 == 0:
print("First char in string is " + msg[0] + ", the third is " + i)
count += 1

You can increment the range in steps of 3:
msg = input('Message? ')
for i in range(0, len(msg), 3):
print(msg[i], end=' ')

Related

Why is my python code giving wrong answers for only some inputs?

I am new to python and I was trying to write a program that gives the frequency of each letters in a string from a specific point. Now my code is giving correct output for some inputs like if I give the input "hheelloo", I get the correct output, but if the input is "hheelllloooo", the frequency of h,e and l is printed correct, but the frequency of 'o' comes out as 7 if the starting point is index 0. Can somebody tell me what am i doing wrong.
Write a Python program that counts the occurrence of Character in a String (Do
not use built in count function.
Modify the above program so that it starts counting
from Specified Location.
str = list(map(str, input("Enter the string : ")))
count = 1
c = int(input("Enter the location from which the count needs to start : "))
for i in range(c, len(str)):
for j in range(i+1,len(str)):
if str[i] == str[j]:
count += 1
str[j] = 0
if str[i] != 0:
print(str[i], " appears ", count, " times")
count = 1
str = list(map(str, input("Enter the string : ")))
count = 1
c = int(input("Enter the location from which the count needs to start : "))
for i in range(c, len(str)):
for j in range(i+1,len(str)):
if str[i] == str[j]:
count += 1
str[j] = 0
if str[i] != 0:
print(str[i], " appears ", count, " times")
count = 1 // <----- This line should be outside the if block.
The error was because of indentation.
I have just properly indented the last line.
Thanks, if it works, kindly upvote.
string module can be useful and easy to calculate the frequency of letters, numbers and special characters in a string.
import string
a='aahdhdhhhh2236665111...//// '
for i in string.printable:
z=0
for j in a:
if i==j:
z+=1
if z!=0:
print(f'{i} occurs in the string a {z} times')
If you want to calculate the frequency of characters from a particular index value, you just have to modify the above code a little as follows:
import string
a='aahdhdhhhh2236665111...//// '
c = int(input("Enter the location from which the count needs to start : "))
for i in string.printable:
z=0
for j in a[c:]:
if i==j:
z+=1
if z!=0:
print(f'{i} occurs in the string a {z} times')
I don't think you need to map the input to list of str as input() always returns a string and string itself is a list of characters. Also make sure you don't use the built-ins as your variable names (As str used in your code). One of the simpler approach can be:
input_word = input("Enter the string : ")
c = int(input("Enter the location from which the count needs to start : "))
# Dict to maintain the count of letters
counts = {}
for i in range(c, len(input_word)):
# Increment 1 to the letter count
counts[input_word[i]] = counts.get(input_word[i], 0)+1
for letter, freq in counts.items():
print (f'{letter} appears {freq} times')
Output:
Enter the string : hheelllloooo
Enter the location from which the count needs to start : 2
e appears 2 times
l appears 4 times
o appears 4 times

Split lines into words task - linear search method

I've been given a task to split lines into words and then split the lines up based on spaces and newlines. I've came up with an incomplete solution as it will not print the last word. I can only use linear search hence the basic approach.
line = raw_input()
while line != "end":
i = 0
while i < len(line):
i = 0
while i < len(line) and line[i] == " ":
i = i + 1
j = i
while line[j] != " ":
j = j + 1
print line[i:j]
line = line[j:]
line = raw_input()
I understand your problem this is somewhat similar to the Hackerearth problem
See this example to clarify your concept
y=list()
1). y=map(int,raw_input().split()) # for storing integer in list
2). y=map(str,raw_input().split()) # for storing characters of string in list
#then use this to print the value
for i in y:
print i #this loop will print one by one value
#working example of this code is #for Second part
>>baby is cute #input
>>['baby','is','cute'] #output
>> #now according to your problem line is breaks into words
If you find it useful Thumbs up

How to compare sentence character by character in python?

I want to write a code to count number of words in a given sentence by using character comparison and below is the code I have written as I am not allowed to use some fancy utilities like split(), etc. So, could you please guide me where am I making mistakes' I am a novice in python and currently trying to fiigure out how to do charactery by character comparison so as to find out simple counts of words, lines, strings withous using built in utitilites. So, kindly guide me about it.
Input Sentence : I am XYZ
Input_Sentence = raw_input("Enter your sentence: ")
print Input_Sentence
count = 0
i=0
while(Input_Sentence[i] != "\n"):
if(Input_Sentence[i] == ' '):
count=count+1
i+=1
else:
i+=1
print ('Number of Words in a given sentence is :' +str(count))
At first I wouldn't use a while loop in this context. Why not using a for loop?
for char in Input_sentence:
With this you iterate over every letter.
Then you can use the rest of you code and check:
if char == ' ':
# initialize the counter
word_count = 0
last_space_index = 0
# loop through each character in the sentence (assuming Input_Sentence is a string)
for i, x in enumerate(Input_Sentence): # enumerate to get the index of the character
# if a space is found (or newline character for end of sentence)
if x in (' ', '\n'):
word_count += 1 # increment the counter
last_space_index = i # set the index of the last space found
if len(Input_Sentence) > (last_space_index + 1): # check if we are at the end of the sentence (this is in case the word does not end with a newline character or a space)
word_count += 1
# print the total number of words
print 'Number of words:', word_count
The following will avoid errors if there's an space at the beginning or the end of the sentence.
Input_Sentence = raw_input("Enter your sentence: ")
print Input_Sentence
count = 0
sentence_length = len(Input_Sentence)
for i in range(sentence_length):
if Input_Sentence[i] == " ":
if i not in (0, sentence_length - 1):
count += 1
count += 1
print "There are %s words in the sentence \"%s\"." % (count, Input_Sentence)
You may use try-except syntax.
In your code you used while(Input_Sentence[i] != "\n") to find when the sentence comes to an end. If you just print the output at every step before i+ = 1 like this:
...
while(Input_Sentence[i] != "\n"):
...
print i,Input_Sentence[i]
i+=1
else:
print i,Input_Sentence[i],'*'
i+=1
...
you can see for yourself that the output is something like this:
Enter your sentence: Python is good
Python is good
0 P *
1 y *
2 t *
3 h *
4 o *
5 n *
6
7 i *
8 s *
9
10 g *
11 o *
12 o *
13 d *
Traceback (most recent call last):
File "prog8.py", line 19, in <module>
while(Input_Sentence[i] != "\n"):
IndexError: string index out of range
which means that the code that you have written works fine upto the length of the input sentence. After that when i is increased by 1 and it is demanded of the code to check if Input_Sentence[i] == "\n" it gives IndexError. This problem can be overcome by using exception handling tools of Python. Which leaves the option to neglect the block inside try if it is an exception and execute the block within except instead.
Input_Sentence = raw_input("Enter your sentence: ")
print Input_Sentence
count = 0
i=0
try:
while (Input_Sentence[i] != "\n"):
if (Input_Sentence[i] == ' '):
count=count+1
i+=1
else:
i+=1
except:
count = count+1
print ('Number of Words in a given sentence is :' +str(count))

Printing odd numbered characters in a string without string slicing?

I'm currently doing a project for my university, and one of the assignments was to get python to only print the odd characters in a string, when I looked this up all I could find were string slicing solutions which I was told not to use to complete this task. I was also told to use a loop for this as well. Please help, thank you in advance.
Here is my code so far, it prints the string in each individual character using a for loop, and I need to modify it so that it prints the odd characters.
i = input("Please insert characters: ")
for character in i:
print(character)
Please follow this code to print odd numbered characters
#Read Input String
i = input("Please insert characters: ")
#Index through the entire string
for index in range(len(i)):
#Check if odd
if(index % 2 != 0):
#print odd characters
print(i[index])
Another option:
a= 'this is my code'
count = 1
for each in list(a):
if count % 2 != 0:
print(each)
count+=1
else:
count+=1
I think more information would be helpful to answer this question. It is not clear to me whether the string only contains numbers. Anyway, maybe this answers your question.
string = '38566593'
for num in string:
if int(num) % 2 == 1:
print(num)
To extend on Kyrubas's answer, you could use-
string = '38566593'
for i, char in enumerate(string):
if i % 2 == 1:
print(char)
person = raw_input("Enter your name: ")
a = 1
print"hello " , person
print "total : " , len(person)
for each in list (person):
if a % 2 ==0:
print "even chars : " , (each)
a+=1
else:
a+=1
s = raw_input()
even_string=''
odd_string=''
for index in range(len(s)):
if index % 2 != 0:
odd_string = odd_string+s[index]
else:
even_string = even_string+ (s[index])
print even_string,odd_string
Try this code. For even index start you can use range(0, len(s), 2).
s = input()
res = ''
for i in range(1,len(s),2):
res +=s[i]
print(res)
When we want to split a string, we can use the syntax:
str[beg:end:jump]
When we put just one number, this number indicates the index.
When we put just two numbers, the first indicates the first character (included) and the second, the last character (excluded) of the substring
You can just read the string and print it like this:
i = input("Please insert characters: ")
print(i[::2])
When you put str[::] the return is all the string (from 0 to len(str)), the last number means the jump you want to take, that meaning that you will print the characters 0, 2, 4, etc
You can use gapped index calling. s[start:end:gap]
s = 'abcdefgh'
print(s[::2])
# 'aceg'
returning the characters with indexes 0, 2, 4, and 6. It starts from position 0 to the end and continues with a gap of 2.
print(s[1::2])
# 'bdfh'
Returning the characters with indexes 1, 3, 5, and 7. It starts from position 1 and goes with a gap of 2.

Python String Comparisons Using A Word List

Eventually I will be able to post simple questions like this in a chat room, but for now I must post it. I am still struggling with comparison issues in Python. I have a list containing strings that I obtained from a file. I have a function which takes in the word list (previously created from a file) and some 'ciphertext'. I am trying to Brute Force crack the ciphertext using a Shift Cipher. My issue is the same as with comparing integers. Although I can see when trying to debug using print statements, that my ciphertext will be shifted to a word in the word list, it never evaluates to True. I am probably comparing two different variable types or a /n is probably throwing the comparison off. Sorry for all of the posts today, I am doing lots of practice problems today in preparation for an upcoming assignment.
def shift_encrypt(s, m):
shiftAmt = s % 26
msgAsNumList = string2nlist(m)
shiftedNumList = add_val_mod26(msgAsNumList, shiftAmt)
print 'Here is the shifted number list: ', shiftedNumList
# Take the shifted number list and convert it back to a string
numListtoMsg = nlist2string(shiftedNumList)
msgString = ''.join(numListtoMsg)
return msgString
def add_val_mod26(nlist, value):
newValue = value % 26
print 'Value to Add after mod 26: ', newValue
listLen = len(nlist)
index = 0
while index < listLen:
nlist[index] = (nlist[index] + newValue) % 26
index = index + 1
return nlist
def string2nlist(m):
characters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
numbers = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]
newList = []
msgLen = len(m) # var msgLen will be an integer of the length
index = 0 # iterate through message length in while loop
while index < msgLen:
letter = m[index] # iterate through message m
i = 0
while i < 26:
if letter == characters[i]:
newList.append(numbers[i])
i = i + 1
index = index + 1
return newList
def nlist2string(nlist):
characters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
numbers = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]
newList = []
nListLen = len(nlist)
index = 0
while index < nListLen:
num = nlist[index]
newNum = num % 26
i = 0
while i < 26:
num1 = newNum
num2 = numbers[i]
if (num1 == num2):
newList.append(characters[i])
i = i + 1
index = index + 1
return newList
def wordList(filename):
fileObject = open(filename, "r+")
wordsList = fileObject.readlines()
return wordsList
def shift_computePlaintext(wlist, c):
index = 0
while index < 26:
newCipher = shift_encrypt(index, c)
print 'The new cipher text is: ', newCipher
wordlistLen = len(wlist)
i = 0
while i < wordlistLen:
print wlist[i]
if newCipher == wlist[i]:
return newCipher
else:
print 'Word not found.'
i = i + 1
index = index + 1
print 'Take Ciphertext and Find Plaintext from Wordlist Function: \n'
list = wordList('test.txt')
print list
plainText = shift_computePlaintext(list, 'vium')
print 'The plaintext was found in the wordlist: ', plainText
When the shift amount = 18, the ciphertext = name which is a word in my wordlist, but it never evaluates to True. Thanks for any help in advance!!
It's hard to be sure with the information we have so far, but here's a guess:
wordsList = fileObject.readlines()
This is going to return you a list of strings with the newlines preserved, like:
['hello\n', 'my\n', 'name\n', 'is\n', 'jesi\n']
So, inside shift_computePlaintext, when you iterate over wlist looking for something that matches the decrypted 'vium', you're looking for a string that matches 'name', and none of them match, including 'name\n'.
In other words, exactly what you suspected.
There are a few ways to fix this, but the most obvious are to use wlist[i].strip() instead of wlist[i], or to strip everything in the first place by using something like wordsList = [line.strip() for line in fileObject] instead of wordsList = fileObject.readlines().
A few side notes:
There is almost never a good reason to call readlines(). That returns a list of lines that you can iterate over… but the file object itself was already an iterable of lines that you can iterate over. If you really need to make sure it's a list instead of some other kind of iterable, or make a separate copy for later, or whatever, just call list on it, as you would with any other iterable.
You should almost never write a loop like this:
index = 0
while index < 26:
# ...
index = index + 1
Instead, just do this:
for index in range(26):
It's easier to read, harder to get wrong (subtle off-by-one errors are responsible for half the frustrating debugging you will do in your lifetime), etc.
And if you're looping over the length of a collection, don't even do that. Instead of this:
wordlistLen = len(wlist)
i = 0
while i < wordlistLen:
# ...
word = wlist[i]
# ...
i = i + 1
… just do this:
for word in wlist:
… or, if you need both i and word (which you occasionally do):
for i, word in enumerate(wlist):
Meanwhile, if the only reason you're looping over a collection is to check each of its values, you don't even need that. Instead of this:
wordlistLen = len(wlist)
while i < wordlistLen:
print wlist[i]
if newCipher == wlist[i]:
return newCipher
else:
print 'Word not found.'
i = i + 1
… just do this:
if newCipher in wlist:
return newCipher
else:
print 'Word not found.'
Here, you've actually got one of those subtle bugs: you print 'Word not found' over and over, instead of only printing it once at the end if it wasn't found.

Categories

Resources