List value assignment within for loop - list

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'

Related

matching string using regular expression

text = "hellovision hey creator yoyo b creator great publisher"
I want to extract creator's name and publisher's name from text.
The result will be,
creator = hellovision hey, yoyo
publisher = great
How can I get text using regular expression?
Do I need to use span()..?
This is my code.
def preprocess2(text):
text_list = test.split(' ')
lyricist = []
composer = []
music_arranger = []
temp = []
lyricist.clear()
composer.clear()
music_arranger.clear()
for i in range(0, len(text_list)):
if text_list[i] == 'creator':
print(len(text_list))
for a in range(0, i-1):
temp.append(text_list[a])
lyricist.append(''.join(temp))
temp.clear()
for b in range(0, i+1):
print(b)
text_list.pop(b)
print(len(text_list))
break
elif text_list[i] == 'pulisher':
for a in range(0, i-1):
temp.append(text_list[a])
composer.append(''.join(temp))
temp.clear()
for b in range(0, i+1):
text_list.pop(b)
break
i = i +1
return text_list
If you split your array using regex with a capture group, the value that you split on will also be passed into the output array.
You can then loop through looking for 'creator' or 'publisher' and in each case, pass the previous entry into the proper collection.
const text = "hellovision hey creator yoyo b creator great publisher"
const splitArr = text.split(/(creator|publisher)/)
const creators = [], publishers = []
let i = -1, len = splitArr.length
while(++i < len){
if(splitArr[i] == "creator") creators.push(splitArr[i-1].trim())
else if(splitArr[i] == "publisher") publishers.push(splitArr[i-1].trim())
}
console.log("creators: ", creators)
console.log("publishers: ", publishers)

Q: Python3 - If Statements for changing list lengths

I am attempting to analyze data sets as lists of differing lengths. I am calling lines (rows) of my data set one by one to be analyzed by my function. I want the function to still be run properly regardless of the length of the list.
My Code:
f = open('DataSet.txt')
for line in iter(f):
remove_blanks = ['']
entries = line.split()
''.join([i for i in entries if i not in remove_blanks])
trash = (entries[0], entries[1])
time = int(entries[2])
column = [int(v) for v in entries[3:]]
def myFun():
print(entries)
print_string = ''
if column[0] == 100:
if column[1] >= 250 and column[2] == 300:
if len(column) >= 9:
digit = [chr(x) for x in column[4:9]]
print_string = ('code: ' + ''.join(str(digit[l]) for l in range(5)) + ' ')
if len(column) >= 13:
optional_digit = [chr(d) for d in column[9:13]]
for m in range(0, 4):
print_string += 'Optional Field: ' + optional_digit[m] + ''
else:
print_string += 'No Optional Field '
pass
pass
print(print_string)
print('')
myFun()
f.close()
What is happening is if the length of a line of my data is not long enough (i.e. the list ends at column[6]), I get the error:
line 17, in function
print('Code: ' + digit[l])
IndexError: list index out of range
I want it to still print Code: #number #number #number #number and leave any non-existent columns as blanks when it is printed so that one line may print as Code: ABC9 and the next print as Code: AB if there are differing list lengths.
Please help! :)
Well, just make sure you're not looping over a list longer than available:
print_string = 'code: ' + ''.join(str(digit[l]) for l in range(min(5, len(digit)))) + ' '
or better:
print_string = "code {} ".format("".join(str(dig) for dig in digit[:5]))
Although I have a feeling you're over-complicating this.

Extracting elements from list using Python

How can I extract '1' '11' and '111' from this list ?
T0 = ['4\t1\t\n', '0.25\t11\t\n', '0.2\t111\t\n']
to extract '4', '0.25' and '0.2' I used this :
def extract(T0):
T1 = []
for i in range(0, len(T0)):
pos = T0[i].index('\t')
T1.append(resultat[i][0: pos])
return T1
then I got :
T1 = ['4','0.25','0.2']
but for the rest I don't know how to extract it
can you help me please?
Using your code as base, it can be done as below. Will return as string if its alphabet, otherwise return as decimal integer.
def extract(T0):
T1=[]
for i in range len(T0):
tmp = T0[i].split('\t')[1]
if tmp.isalpha():
T1.append(tmp)
else:
T1.append(int(tmp))
return T1
Alternatively, try below for a more compact code using list comprehension
def extract(T0):
# return as string if its alphabet else return as decimal integer
# change int function to float if wanna return as float
tmp = [i.split('\t')[1] for i in T0]
return [i if i.isalpha() else int(i) for i in tmp]
Example
T0= ['X\tY\tf(x.y)\n', '0\t0\t\n', '0.1\t10\t\n', '0.2\t20\t\n', '0.3\t30\t\n']
extract(T0) # return ['Y', 0, 10, 20, 30]
You can accomplish this with the re module and a list comprehension.
import re
# create a regular expression object
regex = re.compile(r'[0-9]{1,}\.{0,1}[0-9]{0,}')
# assign the input list
T0 = ['4\t1\t\n', '0.25\t11\t\n', '0.2\t111\t\n']
# get a list of extractions using the regex
extractions = [x for x in [re.findall(regex, e) for e in T0]]
print extractions
# => [['4', '1'], ['0.25', '11'], ['0.2', '111']]

How to sort numbers in ascending order in a file in python (by insertion sort)

I'm trying to figure out a simple way to sort numbers in ascending order from a file using python.
This is what I have got so far - but it doesnt seem to work!
input_file = open('C:\\Users|\Desktop\\data.txt')
for line in input_file:
print line
print('Before: ', input_file)
insertion_sort(input_file)
print('After : ', input_file)
def insertion_sort(items):
""" Implementation of insertion sort """
for i in range(1, len(items)):
j = i
while j > 0 and items[j] < items[j-1]:
items[j], items[j-1] = items[j-1], items[j]
j -= 1
Any help would be greatly appreciated!!
You just have some grammatical errors:
you should declare the insertion_sort function before use it
you can't print a File type, you should make a List to read the file content, then sort the List, return the List and print the List
your file name maybe wrong, use / is better in Windows
Try this:
input_file = open('C:/Users/Desktop/data.txt')
lst = []
for line in input_file:
lst.append(int(line.strip()))
def insertion_sort(items):
""" Implementation of insertion sort """
for i in range(1, len(items)):
j = i
while j > 0 and items[j] < items[j - 1]:
items[j], items[j - 1] = items[j - 1], items[j]
j -= 1
return items
print('Before: ', lst)
print('After : ', insertion_sort(lst))

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.