String manipulaiton runtime error python - python-2.7

Input: 3
gandhi
mahatma gandhI
Mohndas KaramChand gandhi
Output:
Gandhi
M. Gandhi
M. K. Gandhi
And I wrote the following code:
n = int(input())
while n > 0 :
k = raw_input()
if k.find(" ") != -1:
final = str(k[0].upper() + '.')
for i in range(len(k)) :
if (k[i] == ' ') & (k[i:].find(" ")):
final += k[i+1].upper() + ". "
else:
if(k[i] == ' '):
final += k[i+1].upper() + k[i+2:].lower()
n -= 1
print final[0:len(final)]
else :
print k[0].upper() + k[1:].lower()
I'm getting a runtime error for this. Can someone explain why?
­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

try this code.
str = "gandhi mahatma gandhi Mohndas KaramChand gandhi"
temp = ''
for st in str.split():
if st == 'gandhi':
temp = temp + ' ' + st.title()
else:
temp = temp + ' ' + st[0].upper() + '.'
print temp
Output as per your expectation - Gandhi M. Gandhi M. K. Gandhi

Related

Python: How can I sort in outputting .csv files?

Linked is my project that I am working on.
Link to what this project is about:https://i.stack.imgur.com/dnuHD.png, https://i.stack.imgur.com/HuFBe.png, https://i.stack.imgur.com/12CcT.png
I have already completed some of the program. However, I am having trouble on doing part b, which is asking me to create an output file for each major and add the students that are in that major.
Here is my current code:
student_major_file = 'StudentsMajorsList.csv'
gpa_file = 'GPAList.csv'
graduation_file = 'GraduationDatesList.csv'
with open(student_major_file) as file1:
list1 = file1.read().splitlines()
with open(gpa_file) as file2:
list2 = file2.read().splitlines()
with open(graduation_file) as file3:
list3 = file3.read().splitlines()
output1 = open('FullRoster.csv', 'w')
output3 = open('ScholarshipCandidates.csv', 'w')
output4 = open('DisciplinedStudents.csv', 'w')
#part a
for a, b, c in zip(list1, list2, list3):
x = a.split(',')
y = b.split(',')
z = c.split(',')
output1.write(x[0] + ', ' + x[2] + ', ' + y[-1] + ', ' +
x[1] + ', ' + z[-1] + ', ' + x[4])
output1.write('\n')
#part b
#part c
for a, b, c in zip(list1, list2, list3):
x = a.split(',')
y = b.split(',')
z = c.split(',')
if float(b[-1]) > 3.8:
output3.write(x[0] + ', ' + x[1] + ', ' + x[2] + ', ' +
z[-1])
output3.write('\n')
#part d
for a, b, c in zip(list1, list2, list3):
x = a.split(',')
y = b.split(',')
z = c.split(',')
if a[-1] == 'Y':
output4.write(x[0] + ', ' + x[1] + ', ' + x[2] + ', ' +
z[-1])
output4.write('\n')
output1.close()
output3.close()
output4.close()
Thanks in advance!

List value assignment within for loop

What can I do when I get the following error in this code?
def reverse_word(word):
index = len(word)
new_word = []
for i in range(index - 1, -1, -1):
new_word.append(word[i])
return ''.join(new_word)
def reverse_sentence(sentence):
l = sentence.split()
for i in l:
l[i] = reverse_word(i)
l = ' '.join(l)
print(l)
a = "Hello !Nhoj Want to have lunch?"
reverse_sentence(a)
TypeError: list indices must be integers or slices, not str.
What can I write instead of this line:
l[i] = reverse_word(i)
... this line: l[i] = reverse_word(i) throws an error because i is a string (word), but in l[i], i must be an index.
You probably wanted to do something like this:
words = sentence.plit()
new_sentence = []
for i,word in enumerate(words): #or just for word in words, you don't need the index
new_sentence.append(reverse_word(word))
and then join at return time return ' '.join(new_sentence)
This implementation follows your logic but uses strings instead of lists.
def reverse_word(word):
new_word = ''
for i in range(len(word) - 1, -1, -1):
new_word += word[i]
return new_word
def reverse_sentence(sentence):
r = ''
for word in sentence.split():
r += reverse_word(word) + ' '
return r[:-1]
>>> a = "Hello !Nhoj Want to have lunch?"
>>> reverse_sentence(a)
>>> 'olleH johN! tnaW ot evah ?hcnul'

IndexError: Python list index out of range

I have an empty list, (r) and declared first element as r[0] = a
import time, urllib.request,random
def getDictionary():
word_site = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"
response = urllib.request.urlopen(word_site)
txt = response.read()
return txt.splitlines()
def getWordsList(listOfWords, sample):
word = ""
randWords = []
for i in range(0,sample):
while(len(word) <=2):
word = random.choice(listOfWords).decode('utf-8')
randWords.append(word)
word = ""
return randWords
start = True
noOfWords = 25
words = getDictionary()
wordsList = getWordsList(words, noOfWords)
start = True
print ("\nINSTRUCTIONS\nWhen the coundown gets to zero, type the word in lowercase letters!\n That's the only rule!")
name = input("What is your name? ")
name = name.split(" ")
input("Press enter when ready...")
while start == True:
print("Game will start in: ")
print ("3 seconds")
time.sleep(1)
print ("2 seconds")
time.sleep(1)
print ("1 seconds")
time.sleep(1)
times = []
k = list()
r = list()
for i in range(25):
startTime = time.time()
userWord = input(str(i+1) + ". " + wordsList[i].capitalize() + " " )
k.append(wordsList[i].capitalize())
if (userWord.lower() == wordsList[i].lower()):
endTime = time.time()
times.append(endTime - startTime)
r[i] = str(endTime - startTime)
else:
times.append("Wrong Word")
r[i] = ("Wrong Word")
Above is where I am having a problem.
for i in range(25):
startTime = time.time()
print (str(i+1) + ". " + str(k[i]) + ": " + str(times[i]) )
a = 0
for i in range(25):
a = a+i
for i in range(25):
if r[i] == "Wrong Word":
r = r.pop(i)
b = (a/len(r))
c = round(b, 2)
print (c)
start = False
here is my error:
r[i] = "Wrong Word"
IndexError: list assignment index out of range
The pop() method removes an element from the list and returnes it (see an example). What I think is happening is that at some point the condition of the if statment resolves to true. Next, after calling r.pop(i) r is replaced by its i-th element. It's probpably a string so calling its (i+1)-th element later can result in Index out of range error.
In other words, something like this is happening:
r = ["a", "foo", "bar", "baz"]
for i in range(4):
if r[i] == "a": # for i=0 this gives "a" == "a"
r = r.pop(i) # later,this results in r = "a"
next loop iteration with i = 1 will result in "a"[1] which will result in Index out of range.
All in all instead of:
for i in range(25):
if r[i] == "Wrong Word":
r = r.pop(i)
you could just write:
r = [item for item in r if item != "Wrong word"]
which would be also more pythonic solution.

Python- handling warning and critical parameters with getopt

I'm trying to write a script to alert on certain warning and critical levels. So far it only shows ok no matter the output. It ignores warning and critical. What do I need to change?
./check_sqs -p prefix -q queue -s xxx -a xxx -w 5 -c 10
OK: depth = 33;| Prefix_Queue=33
for o, a in opts:
if o in ('-q', '--queue'):
queue_name = a
if o in ('-a', '--access_key'):
access_key = a
if o in ('-s', '--secret_key'):
secret_key = a
if o in ('-p', '--prefix'):
prefix = a
if o in ('-w', '--warning'):
warning = a
if o in ('-c', '--critical'):
critical = a
if access_key == "_none_":
c = SQSConnection()
else:
c = SQSConnection(access_key, secret_key)
cnt = 0
if queue_name != '':
q = c.get_queue(queue_name)
if q == None:
print "ERROR: Invalid queue name " + queue_name
sys.exit(3)
cnt = q.count()
if cnt >= critical:
print 'Critical: depth =', str(cnt) + ';|', q.id.split('/')[2] + "=" + str(cnt)
sys.exit(2)
if cnt >= warning:
print 'Warning: depth =', str(cnt) + ';|', q.id.split('/')[2] + "=" + str(cnt)
sys.exit(1)
if isinstance(cnt, int) and cnt >= 0:
print 'OK: depth =', str(cnt) + ';|', q.id.split('/')[2] + "=" + str(cnt)
sys.exit(0)
else:
print 'Unknown: depth =', str(cnt) + ';|', q.id.split('/')[2] + "=" + str(cnt)
sys.exit(3)
rs = c.get_all_queues()
resp = ''
for q in rs:
name = q.id.split('/')[2]
if name.startswith(prefix):
cnt = cnt + q.count()
resp = resp + name + "=" + str(q.count()) + " "
print 'OK: depth =', str(cnt) + ';|', resp
sys.exit(0)
Thanks, that was very helpful. Critical and Warning are strings, and that's why the comparison was not working. Changing them into int made the trick.
critical = int(critical)
warning = int(warning)

raw_input() invalid syntax

I want to input a string of five numbers with spaces between them and use raw_input() for it. However the second item(the portion that's between the first and second spaces) is claimed to be a syntax error. Code below:
#class for final output - used as an ad hoc static string
class StatString:
outstring = ""
#function to check if Boom or Trach or both
def BoomTrach(num,B,T):
Boom = False
Trach = False
temp = num
while temp != 0:
if num % B == 0:
Boom == True
break
if (temp % 10) % B == 0:
Boom = True
break
temp = (temp - temp % 10) / 10
temp = num
while temp != 0:
if num % T == 0:
Trach = True
break
if (temp % 10) % T == 0:
Trach = True
break
temp = (temp - temp % 10) / 10
if Boom and Trach:
herestring.outstring = herestring.outstring + "Boom-Trach"
elif Boom:
herestring.outstring = herestring.outstring + "Boom"
elif Trach:
herestring.outstring = herestring.outstring + "Trach"
else:
herestring.outstring = herestring.outstring + str(num)
#start of "main" portion
def main():
inS = raw_input() <<<--- Input here
arr = inS.split(' ')
X = int(arr[0])
Y = int(arr[1])
CountFrom = int(arr[2])
jump = int(arr[3])
CountUntil = int(arr[4])
#variable for error check
error = False
#checking for errors
if X < 1 or X > 9 or Y < 1 or Y > 9:
print "X and Y must be between 1 and 9"
error = True
if jump == 0:
print "jump cannot be 0"
error = True
elif (CountUntil - CountFrom) % jump != 0:
print "cannot jump from %d to %d",CountFrom,CountUntil
error = True
if error:
exit()
if CountFrom < 0 and CountUntil < 0 and jump > 0:
jump = jump * (-1)
herestring = StatString()
while CountFrom != CountUntil:
BoomTrach(CountFrom,X,Y)
CountFrom = CountFrom + jump
if(CountFrom != CountUntil):
herestring.outstring = herestring.outstring + ","
print herestring.outstring
error message: (the second 1 was marked as the source of the error)
>>> 1 1 1 1 1
SyntaxError: invalid syntax
>>>
I know what happened. You just run this module, and you thought that you start running it from the main function (like in C for example).
There is no problem with the raw_input line (the first line of the input). The problem is that your module does not try to read anything! You just typed "1 1 1 1 1" which is of course syntax error...
Append to your code this line to run the main function:
main()
You can also write the code of the main function not in some function, to get the same effect.