Python while loop index error - while-loop

I've made a reverse function, it reverses the sentence, however it generates index error.
what the program does is append the last word from s and puts it into rev[],
it then deletes the word s[-1].
s = "This is awesome"
def Reverse1(s):
s = s.split(" ") #reverses the word instead of letters
rev = []
while True:
rev.append (s[-1])
del s[-1]
print (rev)
return
reverse1(s)
its returning index error as it tries to continue when s is empty
so I think its the while loop statement.
any ideas?

You need to stop the while loop, you can use something like this
while n in range(len(s)):

Related

Keyword 'BuiltIn.Exit For Loop If' expected 1 argument, got 2

I am new learner of RobotFramework, I tried to run this code, but this error shows: Keyword 'BuiltIn.Exit For Loop If' expected 1 argument, got 2. Thank you in advance!
Select the Card
[arguments] ${cardName}
${elements} = Get WebElements css:.card-title
${index}= Set Variable 1
FOR ${element} IN #{elements}
Exit For Loop If '${cardName}' == '${element.text}'
${index}= Evaluate ${index} + 1
END
You have two spaces after ==. Robot uses two or more spaces as argument separators so it sees '${cardName}' == as one argument and '${element.text}' as a second argument.
The solution is to make sure the entire expression doesn't have any sequences of two or more spaces.
Exit For Loop If '${cardName}' == '${element.text}'

How to validate update or select query in shell scripting?

I am trying to validate the update or select query in shell scripting.
For example, my query is:
update table_name set col_name = 1 where emp_id = '1234'
If the code will validate the first word must be update and second word must be table_name and third word will be set. I tried to validate, but I am not able to get the things.
I created a very simple python script which works in v2 and v3.
Copy the content to filename.py and perform sudo chmod +x filename.py
#!/usr/bin/env python
string = "update table_name set col_name = 1 where emp_id = '1234'"
x = string.split(' ')
if "update" != x[0]:
print("the first word does not contain update, exiting")
exit
else:
print("the first word contains update")
if "update" != x[1]:
print("the second word does not contain table_name, exiting")
exit
else:
print("the second word contains table_name")
if "update" != x[2]:
print("the third word does not contain set, exiting")
exit
else:
print("the third word contains set")
print("we're good to go")

Iterate on OrientRecord object

I am trying to increment twice in a loop and print the OrientRecord Objects using Python.
Following is my code -
for items in iteritems:
x = items.oRecordData
print (x['attribute1'])
y=(next(items)).oRecordData #Here is the error
print (y['attribute2'])
Here, iteritems is a list of OrientRecord objects. I have to print attributes of two consecutive objects in one loop.
I am getting the following error -
TypeError: 'OrientRecord' object is not an iterator
Try using a different approach to it:
for i in range(0,len(iteritems),2):
x = iteritems[i].oRecordData
print (x['attribute1'])
y = iteritems[i+1].oRecordData
print (y['attribute2'])
The range() function will start from 0 and iterate by 2 steps.
However, this will work properly only if the total amount (range) of records is an even number, otherwise it'll return:
IndexError: list index out of range
I hope this helps.

Checking errors in my program

I'm trying to make some changes to my dictionary counter in python. I want make some changes to my current counter, but not making any progress so far. I want my code to show the number of different words.
This is what I have so far:
# import sys module in order to access command line arguments later
import sys
# create an empty dictionary
dicWordCount = {}
# read all words from the file and put them into
#'dicWordCount' one by one,
# then count the occurance of each word
you can use the Count function from collections lib:
from collections import Counter
q = Counter(fileSource.read().split())
total = sum(q.values())
First, your first problem, add a variable for the word count and one for the different words. So wordCount = 0 and differentWords = 0. In the loop for your file reading put wordCount += 1 at the top, and in your first if statement put differentWords += 1. You can print these variables out at the end of the program as well.
The second problem, in your printing, add the if statement, if len(strKey)>4:.
If you want a full example code here it is.
import sys
fileSource = open(sys.argv[1], "rt")
dicWordCount = {}
wordCount = 0
differentWords = 0
for strWord in fileSource.read().split():
wordCount += 1
if strWord not in dicWordCount:
dicWordCount[strWord] = 1
differentWords += 1
else:
dicWordCount[strWord] += 1
for strKey in sorted(dicWordCount, key=dicWordCount.get, reverse=True):
if len(strKey) > 4: # if the words length is greater than four.
print(strKey, dicWordCount[strKey])
print("Total words: %s\nDifferent Words: %s" % (wordCount, differentWords))
For your first qs, you can use set to help you count the number of different words. (Assume there is a space between every two words)
str = 'apple boy cat dog elephant fox'
different_word_count = len(set(str.split(' ')))
For your second qs, using a dictionary to help you record the word_count is ok.
How about this?
#gives unique words count
unique_words = len(dicWordCount)
total_words = 0
for k, v in dicWordCount.items():
total_words += v
#gives total word count
print(total_words)
You don't need a separate variable for counting word counts since you're using dictionary, and to count the total words, you just need to add the values of the keys(which are just counts)

How to load 2D array from a text(csv) file into Octave?

Consider the following text(csv) file:
1, Some text
2, More text
3, Text with comma, more text
How to load the data into a 2D array in Octave? The number can go into the first column, and all text to the right of the first comma (including other commas) goes into the second text column.
If necessary, I can replace the first comma with a different delimiter character.
AFAIK you cannot put stings of different size into an array. You need to create a so called cell array.
A possible way to read the data from your question stored in a file Test.txt into a cell array is
t1 = textread("Test.txt", "%s", "delimiter", "\n");
for i = 1:length(t1)
j = findstr(t1{i}, ",")(1);
T{i,1} = t1{i}(1:j - 1);
T{i,2} = strtrim(t1{i}(j + 1:end));
end
Now
T{3,1} gives you 3 and
T{3,2} gives you Text with comma, more text.
After many long hours of searching and debugging, here's how I got it to work on Octave 3.2.4. Using | as the delimiter (instead of comma).
The data file now looks like:
1|Some text
2|More text
3|Text with comma, more text
Here's how to call it: data = load_data('data/data_file.csv', NUMBER_OF_LINES);
Limitation: You need to know how many lines you want to get. If you want to get all, then you will need to write a function to count the number of lines in the file in order to initialize the cell_array. It's all very clunky and primitive. So much for "high level languages like Octave".
Note: After the unpleasant exercise of getting this to work, it seems that Octave is not very useful unless you enjoy wasting your time writing code to do the simplest things. Better choices seems to be R, Python, or C#/Java with a Machine Learning or Matrix library.
function all_messages = load_data(filename, NUMBER_OF_LINES)
fid = fopen(filename, "r");
all_messages = cell (NUMBER_OF_LINES, 2 );
counter = 1;
line = fgetl(fid);
while line != -1
separator_index = index(line, '|');
all_messages {counter, 1} = substr(line, 1, separator_index - 1); % Up to the separator
all_messages {counter, 2} = substr(line, separator_index + 1, length(line) - separator_index); % After the separator
counter++;
line = fgetl(fid);
endwhile
fprintf("Processed %i lines.\n", counter -1);
fclose(fid);
end