Im coding in Groovy and I have a string parameter "X" which looks like this:
899-921-876-123
For now i succesfully removed the "-" from it by
replaceAll("-", "")
And now I want to divide this String into separete numbers - to an array, like (8,9,9...) to make some calculations using those numbers. But somehow I cannot split() this String and make it an Integer at the same time like that:
assert X.split("")
def XInt = Integer.parseInt(X)
So then when Im trying something like:
def sum = (6* X[0]+ 5 * X[1] + 7 * X[2])
I get an error that "Cannot find matching method int#getAt(int). Please check if the declared type is right and if the method exists." or "Cannot find matching method int#multiply(java.lang.String). Please check if the declared type is right and if the method " if im not converting it to Integer...
Any idea how can I just do calculations on separate numbers of this string?
def X = '899-921-876-123'
def XInt = X.replaceAll(/\D++/, '').collect { it as int }
assert XInt == [8, 9, 9, 9, 2, 1, 8, 7, 6, 1, 2, 3]
assert 6* XInt[0]+ 5 * XInt[1] + 7 * XInt[2] == 6* 8+ 5 * 9 + 7 * 9
the replaceAll removes all non-digits
the collect iterates over the iterable and converts all elements to ints
a String is an iterable of its characters
Given you already just have a string of numbers:
"123"*.toLong() // or toShort(), toInteger(), ...
// ===> [1, 2, 3]
If found #cfrick approach the most grooviest solution.
This makes it complete:
def n = "899-921-876-123".replaceAll("-", "")
print n*.toInteger()
Related
I am trying to remove a digit from an integer.
My code seems to work except when I input an integer such as 8880888.
For some reason, with an integer above, when removing the index passing the middle number, but it doesn't remove the correct index.
n = 8880888
def question(n):
newlist = [int(x) for x in str(n)] #coverting integer to list
result = newlist[:]
y = newlist[5]
result.remove(y)
return result
When removing the 5th element, it should return 888088.
But instead, I am being returned 880888.
You are using remove() instead of a del method. If you are looking to remove an element based on an index, your code should look something like:
n = [8, 8, 8, 0, 8, 8, 8]
#If you want to remove the 5th element:
del n[5]
Please refer to https://www.csestack.org/difference-between-remove-del-pop-python-list/
Note the two consecutive spaces in this string:
string = "Hello there everyone!"
for i, c in enumerate(string):
print(i, c)
0 H
1 e
2 l
3 l
4 o
5
6 t
7 h
8 e
9 r
10 e
11
12
13 e
14 v
15 e
16 r
17 y
18 o
19 n
20 e
21 !
How can I make a list len(string) long, with each value containing the word count up to that point in the string?
Expected output: 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2
The only way I could do it was by looping through each character, setting a space=True flag and increasing a counter each time I hit a non-space character when space == True. This is probably because I'm most proficient with C, but I would like to learn a more Pythonic way to solve this.
I feel like your solution is not that far from being pythonic. Maybe you can use the zip operator to iterate your string two by two and then just detect local changes (from a space to a letter -> this is a new word):
string = "Hello there everyone!"
def word_index(phrase):
nb_words = 0
for a, b in zip(phrase, phrase[1:]):
if a == " " and b != " ":
nb_words += 1
yield nb_words
print(list(word_index(string)))
This also make use of generators which is quite common in python (see the documentation for the yield keyword). You can probably do the same by using itertools.accumulate instead of the for loop, but I'm not sure it wouldn't obfuscate the code (see the third item from The Zen of Python). Here is what it would look like, note that I used a lambda function here, not because I think it's the best choice, but simply because I couldn't find any meaningful function name:
import itertools
def word_index(phrase):
char_pairs = zip(phrase, phrase[1:])
new_words = map(lambda p: int(p[0] == " " and p[1] != " "), char_pairs)
return itertools.accumulate(new_words)
This second version similarly to the first one returns an iterator. Note that using a iterators is usually a good idea as it doesn't make any assumption on whether your user want to instantiate anything. If the user want to transform an iterator it to a list he can always call list(it) as I did in the first piece of code. Iterators simply gives you the values one by one: at any point in time, there only is a single value in memory:
for word_index in word_index(string):
print(word_index)
Remark that phrase[1:] makes a copy of the phrase, which means it doubles the memory used. This can be improved by using itertools.islice which returns an iterator (and therefore only use constant memory). The second version would for example look like this:
def word_index(phrase):
char_pairs = zip(phrase, itertools.islice(phrase, 1, None))
new_words = map(lambda p: int(p[0] == " " and p[1] != " "), char_pairs)
return itertools.accumulate(new_words)
Hi I'm new to programming and have a project to create a program to convert binary to decimal in Python. I have to make use of the values stored in the list and multiply based on user input. I keep getting errors regarding int/str. Any help would be appreciated.Please see code below of what I have so far.
denaryNumber = 0
binaryNumber = input("Please enter binary number: ")
placeValues = [128, 64, 32, 16, 8, 4, 2, 1]
for i in range(0, len(binaryNumber) -1):
denaryNumber = denaryNumber + (binaryNumber(i) * placeValues[i])
print (denaryNumber)
There are a few issues in your code.
Every input by default in python is taken in as 'str' , so your binaryNumber is str
To access an element from a list, you use[] not () as you have used here: binaryNumber(i)
Since your binary number is str you cant apply mathematical operations on str , so binaryNumber(i) * placeValues[i] is invalid. You need to type-cast str to int like this : int(binaryNumber[i])
So change your 2nd last line to this:
denaryNumber = denaryNumber + (int(binaryNumber[i]) * placeValues[i])
It would work then.
jbtw, your code would return correct results only if your input is 8bits.
I want to change the first element of a string with the last element.
def change(string):
for i in range(16):
helper = string[i]
string[i]=string[15-i]
string[15-i]=helper
return string
print (change("abcdefghijklmnop"))
Error Output:
string[i]=helper2[0]
TypeError: 'str' object does not support item assignment
You can't alter a string; they're immutable. You can create a new string that is altered as you want:
def change(string):
return string[-1]+string[1:-1]+string[0]
You can use "*" operator.
my_list = [1,2,3,4,5,6,7,8,9]
a, *middle, b = my_list
my_new_list = [b, *middle, a]
my_list
[1, 2, 3, 4, 5, 6, 7, 8, 9]
my_new_list
[9, 2, 3, 4, 5, 6, 7, 8, 1]
Read here for more information.
As you discovered, strings are immutable so you can index a string (eg string[x]), but you can't assign to an index (eg string[x] = 'z').
If you want to swap the first and last element, you will need to create a new string. For example:
def change(input_str):
return input_str[-1] + input_str[1:-1] + input_str[0]
However, based on your example code, it looks like you trying to swap all the "elements" of the string. If you want to do that, see this previous discussion on different methods of reversing a string: Reverse a string in Python
Additionally, even if you could "index" a string, your code would not work as written. With a minor change to "explode" it into a list:
def change(string):
string = [c for c in string]
for i in range(16):
helper = string[i]
string[i]=string[15-i]
string[15-i]=helper
return string
print (change("abcdefghijklmnop"))
DEMO
As you can see, the output is the "same" as the input (except exploded into a list) because you step through every index in the string, reverse all of them twice (which puts them back in their original position).
Im aware that this may come up as a duplicate but so far I haven't found (or should that be understood) an answer to what Im looking for.
I have a list of strings and want to convert each one into a variable name which I then assign something to. I understand that I may need a dict for this but I am unfamiliar with them as I am relatively new to python and all the examples I have seen so far deal with values whilst I'm trying something different.
Im after something like:
list = ['spam', 'eggs', 'ham']
for i in range(len(list)):
list[i] = rat.readColumn(ratDataset, list[i])
where the first list[i] is a variable name and not a string. The second list[i] is a string (and for context is the name of a column Im reading from a raster attribute table (rat))
Essentially I want each string within the list to be set as a variable name.
The idea behind this is that I can create a loop without having to write out the line for each variable I want, with matching rat column name (the string). Maybe there is a beer way of doing this than I am suggesting?
Try the following:
lst = ['spam', 'eggs', 'ham']
d = {} # empty dictionary
for name in lst:
d[name] = rat.readColumn(ratDataset, name)
Do not use list for your identifiers as it is a type identifier and you would mask its existence. The for loop can iterate directly for the elements inside -- no need to construct index and use it aganist the list. The d['spam'] will be one of your variables.
Although, it is also possible to create the real variable names like spam, eggs, ham, you would not probably do that as the effect would be useless.
Here comes a simple dictionary use :
variables = ['spam', 'eggs', 'ham']
data = {}
datum = 0
for variable in variables:
data[variable] = datum
datum+=1
print(data)
print("value : ",data[variables[2]])
It gives as result :
{'eggs': 1, 'ham': 2, 'spam': 0}
value : 2
NB : don't use list as a variable name, list is a type identifier that you can use to transform an object into a list if possible (list("abc")==['a', 'b', 'c']) and you are overriding it with your value list right now.
one way is setting the variable name as a string and changing a part or all of it via format() method and then using the string as a varibale via vars()[STRING]
import numpy as np
X1= np.arange(1,10)
y1=[i**2 for i in X1]
X2= np.arange(-5,5)
y2=[i**2 for i in X2]
for i in range(1,3):
X = 'X{}'.format(i)
y = 'y{}'.format(i)
print('X_{}'.format(i) , vars()[X])
print('y_{}'.format(i) , vars()[y])
Output:
X_1 [1 2 3 4 5 6 7 8 9]
y_1 [1, 4, 9, 16, 25, 36, 49, 64, 81]
X_2 [-5 -4 -3 -2 -1 0 1 2 3 4]
y_2 [25, 16, 9, 4, 1, 0, 1, 4, 9, 16]