Working with list of string is pretty straightforward in Genie. I was wondering if one could locate the last added item with something similar to [-1] in python.
Taking the example from Genie's tutorial:
[indent=4]
init
/* test lists */
var l = new list of string
l.add ("Genie")
l.add ("Rocks")
l.add ("The")
l.add ("World")
for s in l
print s
print " "
print l[-1]
Aim
My expectative was that the l[-1] bit would point to "World" item. However it gives me the error at execution time:
ERROR:arraylist.c:954:gee_array_list_real_get: assertion failed: (index >= 0)
/tmp/geany_run_script_X6D4JY.sh: line 7: 13815 Abortado (imagem do nĂșcleo gravada)/tmp/./test
Question
The gee array clearly only works with positive indexes, is there any other way to get the last added item on an array?
Gee list has a last method:
print( l.last() )
A Gee list's length is found with the size property:
print( l[ l.size -1 ] )
A Gee list can also be sliced with only the last element:
for s in l[l.size-1:l.size]
print( s )
In python
last_index = len(a) - 1
print a[last_index]
In vala or genie,
last_index = a.length - 1
print a[last_index]
Related
phrase = input("enter the equation you want diferentiated:")#3x^2+2x^1+-4x^4
new_phrase = phrase.split("+")#splits phrase at the + operator
print(len(new_phrase))
for item in new_phrase:
c = (new_phrase>new_phrase.index("^"))#actul differentiation part c is the power of whatever (this is where python has a problem) line 6
y = (new_phrase<(new_phrase.index("^")-1))# y is the number before x
print(float(c)*float(y)+"^"+float(c)-1)# this is the final differentiated answer
#however it keeps saying ^ is not in the list how can I fix this?
Using Python 3.8.1
The actual main code is starting at for item. This is where the problem occurs, as the input is supposed to be 3x^2+2x^1+-4x^4, or something like, that but Python cannot seem to find where the power to sign "^" in the list thus the rest of the code from the " c =" does not work.
I have created a working version from your code. Mainly the problem was the type inconsistency. Furthermore I have added several comments to the code for the better understanding and it contains several prints for the debugging.
Code:
phrase = input("Enter the equation you want differentiated: ").lower() # 3x^2+2x^1+-4x^4
new_phrase = phrase.split("+") # splits phrase at the + operator
print("Elements: {}".format(new_phrase)) # Print elements of differential
for item in new_phrase:
print("Tested element: {}".format(item))
c = float(item.split("^")[-1]) # Get after part of "^" character
y = float(item.split("^")[0].replace("x", "")) # Get before part of "^" character (withour "x")
print("c={} ; y={}".format(c, y))
print(
"Result: {}^{}".format(float(c) * float(y), float(c) - 1)
) # this is the final differentiated answer
Output:
>>> python3 test.py
Enter the equation you want differentiated: 3x^2+2x^1+-4x^4
Elements: ['3x^2', '2x^1', '-4x^4']
Tested element: 3x^2
c=2.0 ; y=3.0
Result: 6.0^1.0
Tested element: 2x^1
c=1.0 ; y=2.0
Result: 2.0^0.0
Tested element: -4x^4
c=4.0 ; y=-4.0
Result: -16.0^3.0
Here is some Python script that can differentiate algebraic expressions based on your code.
phrase = input("enter the equation you want diferentiated:")#3x^2+2x^1+-4x^4
# Splits phrase at the + operator
split_phrase = phrase.split("+")
# Placeholder for the differentiated phrase
new_phrase = ""
for item in split_phrase:
# Exponent - index of ^ - 1
c = int(item[item.index("^") + 1:])
#Coefficient - from 0 to index of x - 1
y = int(item[0:item.index("x")])
#Reconstructs the algebraic expression
new_phrase += str(c*y) + "x^" + str(c-1)
# Adds a plus sign if it is not the last item
if split_phrase.index(item) != len(split_phrase) - 1:
new_phrase += "+"
I'm trying to figure out how to print a one line string while using a for loop. If there are other ways that you know of, I would appreciate the help. Thank you. Also, try edit off my code!
times = int(input("Enter a number: "))
print(times)
a = 0
for i in range(times+1):
print("*"*i)
a += i
print("Total stars: ")
print(a)
print("Equation: ")
for e in range(1,times+1):
print(e)
if e != times:
print("+")
else:
pass
Out:
Enter a number: 5
*
**
***
****
*****
Equation:
1
+
2
+
3
+
4
+
5
How do I make the equation in just one single line like this:
1+2+3+4+5
I don't think you can do a "backspace" after you've printed. At least erasing from the terminal isn't going to be done very easily. But you can build the string before you print it:
times = int(input("Enter a number: "))
print(times)
a = 0
for i in range(times+1):
print("*"*i)
a += i
print("Total stars: ")
print(a)
print("Equation: ")
equation_string = ""
for e in range(1,times+1):
equation_string += str(e)
if e != times:
equation_string += "+"
else:
pass
print(equation_string)
Basically, what happens is you store the temporary equation in equation_str so it's built like this:
1
1+
1+2
1+2+
...
And then you print equation_str once it's completely built. The output of the modified program is this
Enter a number: 5
5
*
**
***
****
*****
Total stars:
15
Equation:
1+2+3+4+5
Feel free to post a comment if anything is unclear.
Instead of your original for loop to print each number, try this:
output = '+'.join([str(i) for i in range(1, times + 1)])
print(output)
Explanation:
[str(i) for i in range(1, times + 1)] is a list comprehension that returns a list of all your numbers, converted to strings so that we can print them.
'+'.join(...) joins each element of your list, with a + in between each element.
Alternatively:
If you want a simple modification to your original code, you can simply suppress the newline from each print statement with the keyword paramater end, and set this to an empty string:
print(e, end='')
(Note that I am addressed the implied question, not the 'how do I do a backspace' question)
Too long for a comment, so I will post here.
The formatting options of python can come into good use, if you have a sequence you wish to format and print.
Consider the following...
>>> num = 5 # number of numbers to generate
>>> n = num-1 # one less used in generating format string
>>> times = [i for i in range(1,num+1)] # generate your numbers
>>> ("{}+"*n + "{}=").format(*times) # format your outputs
'1+2+3+4+5='
So although this doesn't answer your question, you can see that list comprehensions can be brought into play to generate your list of values, which can then be used in the format generation. The format string can also be produced with a l.c. but it gets pretty messy when you want to incorporate string elements like the + and = as shown in the above example.
I think you are looking for the end parameter for the print function - i.e. print(e, end='') which prints each value of e as it arrives followed by no space or newline.
I have a list of variable length and am trying to find a way to test if the list item currently being evaluated is the longest string contained in the list. And I am using Python 2.6.1
For example:
mylist = ['abc','abcdef','abcd']
for each in mylist:
if condition1:
do_something()
elif ___________________: #else if each is the longest string contained in mylist:
do_something_else()
Surely there's a simple list comprehension that's short and elegant that I'm overlooking?
From the Python documentation itself, you can use max:
>>> mylist = ['123','123456','1234']
>>> print max(mylist, key=len)
123456
def longestWord(some_list):
count = 0 #You set the count to 0
for i in some_list: # Go through the whole list
if len(i) > count: #Checking for the longest word(string)
count = len(i)
word = i
return ("the longest string is " + word)
or much easier:
max(some_list , key = len)
What should happen if there are more than 1 longest string (think '12', and '01')?
Try that to get the longest element
max_length,longest_element = max([(len(x),x) for x in ('a','b','aa')])
And then regular foreach
for st in mylist:
if len(st)==max_length:...
To get the smallest or largest item in a list, use the built-in min and max functions:
lo = min(L)
hi = max(L)
As with sort, you can pass in a "key" argument that is used to map the list items before they are compared:
lo = min(L, key=int)
hi = max(L, key=int)
http://effbot.org/zone/python-list.htm
Looks like you could use the max function if you map it correctly for strings and use that as the comparison. I would recommend just finding the max once though of course, not for each element in the list.
len(each) == max(len(x) for x in myList) or just each == max(myList, key=len)
def LongestEntry(lstName):
totalEntries = len(lstName)
currentEntry = 0
longestLength = 0
while currentEntry < totalEntries:
thisEntry = len(str(lstName[currentEntry]))
if int(thisEntry) > int(longestLength):
longestLength = thisEntry
longestEntry = currentEntry
currentEntry += 1
return longestLength
Good afternoon everyone,
I'm trying to sort out names which are already sorted in alphabetical order. I can't figure out why my program isn't working. Any tips or pointers would be nice. Thanks.
def main():
names = ['Ava Fiscer', 'Bob White', 'Chris Rich', 'Danielle Porter', 'Gordon Pike', 'Hannah Beauregard', 'Matt Hoyle', 'Ross Harrison', 'Sasha Ricci', 'Xavier Adams']
input('Please enter the name to be searched: ', )
binarySearch
main()
def binarySearch(names):
first = 0
last = len(names) - 1
position = -1
found = False
while not found and first <= last:
middle = (first + last) / 2
if names[middle] == value:
found = True
position = middle
elif arr[middle] > value:
last = middle -1
else:
first = middle + 1
return position
What does it mean that the program isn't working? Is it a syntax error or is the problem in the wrong results?
With the code you pasted, there are several indentation problems, but besides that, lines:
input('Please enter the name to be searched: ', )
binarySearch
are also syntactically incorrect, the comma is redundant and only the function name appearing just like that is plain wrong. If you are interested in the correctness of your algorithm, it seems alright, but the boundaries can always be tricky. My code below is working and syntactically correct, if you find it helpful. (names are numbers, but that is irrelevant in this case)
names = [1,2,4,5,6,8,9]
def bs(n):
start = 0
end = len(names)
while end - start > 0:
m = (start+end)/2
if names[m] == n:
return m
elif n < names[m]:
end = m
else:
start = m + 1
return -1
print (bs(1))
print (bs(6))
print (bs(9))
print (bs(3))
print (bs(10))
print (bs(-8))
Another thing I would like to point out is that this kind of binary search is already in the python standard library, the bisect module. However, if you are writing your own for practice or for any other reason that is just fine.
if you are using python 3.* then you are going to want to change
m = (start+end)/2
to
m = (start+end)//2
When you do /2 it outputs a float in 3.*
I've found many related questions, and a couple that have at least helped me get this far. My goal is to have a function that receives a string and an arbitrary number of integers. I want the function to return that string with spaces inserted at the points given in the arguments. I will use this function with many different strings that will have varying numbers of inserts and insert locations.
This is an example of what I'd like to produce:
Input a string like 'ATGCATGCATGCATGC' and indexes (e.g. 4, 7). The output should be 'ATGCA TGC ATGCATGC'.
This is the function that has given me the closest results so far:
def breakRNA(seqRNA, *breakPoint):
n = 0
for i in seqRNA:
n += 1
for i in breakPoint:
if i == n:
seqRNA = seqRNA[n:] + ' ' + seqRNA[:n]
return seqRNA
The return string, however, is transposed out of order. Example:
>>> test = breakRNA('AAAAAAAAAAAAAAAAAAAAAAAAAAATTTTTGGGGGGGGCCCCCCCCCC', 5, 8, 14)
>>> test
>>> 'TTTTTGGGGGGGGCCCCCCCCCC AAAAA AAAAAAAA AAAAAAAAAAAAAA'
I am a day-1 beginner so any advice is appreciated. Thank you.
String are indexed like list in Python.
For example consider the following:
test_string = "azertyuiop"
print test_string[0] #will return 'a'
print test_string[0:2] #will return 'az'
So getting back to your problem:
def insert_space(string, integer):
return string[0:integer] + ' ' + string[integer:]
Hope this is what you are looking for
def breakRNA(seqRNA, *breakPoint):
seqRNAList = []
noOfBreakPoints = len(breakPoint)
for breakPt in range(noOfBreakPoints):
for index in breakPoint:
seqRNAList.append(seqRNA[:index])
seqRNA = seqRNA[index:]
break
return seqRNAList
test = breakRNA('AAAAAAAAAAAAAAAAAAAAAAAAAAATTTTTGGGGGGGGCCCCCCCCCC', 5, 8, 14)
print test
This will return you alist then you can create a string out of it using join function.
simbol = input('Enter a character:\n')
triangle_n = int(input('Enter triangle height:\n'))
print('')
for i in range (triangle_n ):
for j in range(i+1):
print(simbol [0],end=' ')
print()
string_name = string_name[starting index:ending index] + ' ' + string_name[starting index:ending index]
example:
product_rating = '4.56888 rating 256156 reviews'
product_rating = product_rating[0:3] + ' ' + product_rating[3:]
output
'4.5 6888 rating 256156 reviews'
If ending index is not mentioned its default value will be till the end of string.
Note indexing will start from 0 and 0:3 means it will take 0 to 2.