Easiest Way to Convert "A/B/C" to ["A/B/C", "A/B", "A"]

Convert [a b c] to [a,b,c] with python

First, this does not work...

a = [john jr 0, Akbar AK 1001, doctor rd 9999, Mohammedans med 1000, pat mat 200, cajole Jul 21]

because it is not python valid syntax.
So I assume you mean

a = "[john jr 0, Akbar AK 1001, doctor rd 9999, Mohammedans med 1000, pat mat 200, cajole Jul 21]"

We can split it into parts on a separator...
The default seperator is space " "
now our code is

s = "[john jr 0, Akbar AK 1001, doctor rd 9999, Mohammedans med 1000, pat mat 200, cajole Jul 21]"
s = s.replace("[", "").replace("]", "")
s = s.replace(",", " ")
a = s.split()
print(s)
print(a)

and we get printed

[john jr 0, Akbar AK 1001, doctor rd 9999, Mohammedans med 1000, pat mat 200, cajole Jul 21]
['[john', 'jr', '0,', 'Akbar', 'AK', '1001,', 'doctor', 'rd', '9999,', 'Mohammedans', 'med', '1000,', 'pat', 'mat', '200,', 'cajole', 'Jul', '21]']

A bit hard to read and you probably don't want the leading and trailing brackets so we strip those. the commas are going to cause number parsing errors so we replace those with spaces. Since spaces are the separator and we want any parts like 12,hi with no space to become 12 hi

Next lets find all the numbers and add those up. We have to simply try to parse each string as a number see if it succeeds.

s = "[john jr 0, Akbar AK 1001, doctor rd 9999, Mohammedans med 1000, pat mat 200, cajole Jul 21]"
s = s.replace("[", "").replace("]", "")
s = s.replace(",", " ")
a = s.split()
print(s)
print(a)
mysum = 0.0
for w in a:
print("Word is %s" % (w,))
try:
n = float(w)
print("Found number %f" % (n,))
mysum += n
except:
# Ignore any exceptions
pass
print("Sum is %f" %(mysum,))
pass

And we get

john jr 0  Akbar AK 1001  doctor rd 9999  Mohammedans med 1000  pat mat 200  cajole Jul 21
['john', 'jr', '0', 'Akbar', 'AK', '1001', 'doctor', 'rd', '9999', 'Mohammedans', 'med', '1000', 'pat', 'mat', '200', 'cajole', 'Jul', '21']
Word is john
Word is jr
Word is 0
Found number 0.000000
Word is Akbar
Word is AK
Word is 1001
Found number 1001.000000
Word is doctor
Word is rd
Word is 9999
Found number 9999.000000
Word is Mohammedans
Word is med
Word is 1000
Found number 1000.000000
Word is pat
Word is mat
Word is 200
Found number 200.000000
Word is cajole
Word is Jul
Word is 21
Found number 21.000000
Sum is 12221.000000

So now we have working code that meets what you stated, it finds the numbers and adds them.
But is this maintainable and efficient and functional etc.
When I have the above problem I use some methods I made that make it easier.
Here they are.

def tryParseInt(value=None, default_value=0):
"""
Try to parse a string value to an int. Returns the value and True
e.g. tryParseInt("42", 7) returns (42, True)
tryParseInt("abcdef", 7) returns (7, False)
See twit_test.py
"""
try:
return int(value), True
except (ValueError, TypeError):
return default_value, False

def tryParseFloat(value=None, default_value=0.0):
"""
Try to parse a string value to an float. Returns the value and True
e.g. tryParseInt("42.42", 7.3) returns (42.42, True)
tryParseInt("abcdef", 7.3) returns (7.3, False)
See twit_test.py
"""
try:
return float(value), True
except (ValueError, TypeError):
return default_value, False

def split_strip(s: str, sep=' '):
"""
Split s into parts on delimiter, then strip the sub strings and remove any blanks.
Never returns None.
Returns an array of the sub strings. The returned array my be empty.
See twit_test.py for examples.
"""
if s is None:
return []
parts = s.split(sep=sep)
ret = []
if parts is not None:
for ss in parts:
sss = ss.strip()
if len(sss) > 0:
ret.append(sss)
return ret

The above helpers are available on GitHib project https://github.com/RMKeene/twit

Easiest way to convert a/b/c to [a/b/c, a/b, a]

The highest voted answer works, but here is a slightly shorter way to do it that I think will be more readable for those not familiar with all the features used there:

a=[]; s.scan(/\/|$/){a << $`}

The result is stored in a:

> s = 'abc/def/ghi'
> a=[]; s.scan(/\/|$/){a << $`}
> a
["abc", "abc/def", "abc/def/ghi"]

If the order is important, you can reverse the array or use unshift instead of <<.

Thanks to dkubb, and to the OP for the improvements to this answer.

How can I split a String like [A,B,C] into A B C (Java)

Just omit the brackets, it's faster than using .replaceAll:

a = a.substring(1, a.length() - 1); // Substringing removes first and last character
String[] str = a.split(",");

JavaScript: Convert [a,b,c] into [a][b][c]

You could map it with Array#map.That returns an array with the processed values.

ES6

console.log([1, 2, 3, 4].map(a => [a]));

How to convert [a,b,c] to [a+b+c, b+c, c] in numpy?

You can use np.cumsum:

import numpy as np

a = np.array([1, 2, 3])
print(np.cumsum(a[::-1])[::-1])
# Outputs [6 5 3]

Convert JavaScript Array [a, b, c, d, e] into [a+b, b+c, c+d, d+e] dynamically

There are some issues in your code:

  • The randomIntegerArray function can only deal with lengths up to about 17, ... for greater values, it will keep producing zeroes beyond index 17. This is because of the precision limit that floating point has.

  • The randomIntegerArray function does not do what its name says: it produces an array of strings, not of integers

  • The randomIntegerArray function never produces a zero at index 0.

  • The randomIntegerArray function cannot produce numbers greater than 9.

  • Your code only generates one such random array, and then assigns that single array to several slots in your question array using fill. Although not clear from your question, it seems more likely you want to generate as many random arrays as you have "questions".

Here is how you could do the job, also addressing the above mentioned issues:

const randomIntegerArray = (length, max=9) =>
Array.from({length}, () => Math.floor(Math.random() * (max+1)));

const makeQuestions = (del, length) =>
Array.from({length}, () => randomIntegerArray(del))
.map((question, index) => ({
question,
anser: question.slice(0, -1)
.map((item, index) => item + question[index+1])
}));

console.log(makeQuestions(5, 2));


Related Topics



Leave a reply



Submit