splitting an array of string into individual elements - arrays

['2,3', '1,2,3', '4,5,6', '2,3', '10,11', '13,14,15', 'END']
Instead of how this array looks now, I need it to look like this:
[2,3,1,2,3,4,5,6,2,3,etc...]
I also cannot figure out, or even if there is a way to, separate the array of strings so that they are not strings and instead integers.
This is my read method and how it separated my txt file
def read_file():
with open('extra.txt') as fp:#read file
lines = fp.read().split();
fp.close(); #close file
return lines; #return lines to main function

You can do it in one go with a list comprehension, using str.split() to split the strings by comma and int() to convert to integers:
In [1]: l = ['2,3', '1,2,3', '4,5,6', '2,3', '10,11', '13,14,15', 'END']
In [2]: [int(number) for item in l[:-1] for number in item.split(",")]
Out[2]: [2, 3, 1, 2, 3, 4, 5, 6, 2, 3, 10, 11, 13, 14, 15]
l[:-1] to skip the last END element.
Also, here is a way to read and wrap the head around nested list comprehensions:
How to read aloud Python List Comprehensions?

If your old_list is your list containing the above strings,
old_list.remove('END')
new_list = []
for i in old_list:
sp = i.split(',')
for j in sp:
new_list.append(j)

Related

Add Array in single line to new file and load Array in single line

Hey I'm writing a simple game, where I want to save progress and load it at another point.
One one the elements to save is an array. I want to save this array in one single line as an array and also load it again as an array, but it only takes the first element and the following elements overwrite further content
Example (wrong) - Save Data
player_1 = "name"
array = [1, 2, 3]
count = 1000
File.open("game.txt", "w+") do |file|
file.puts player_1
file.puts array
file.puts count
end
Example (wrong) - Load Data
file_data = File.open("game.txt").readlines.map(&:chomp)
player_1 = file_data[0]
array = file_data[1]
count = file_data[2]
OUTPUT: TEXTFILE
name
1
2
3
1000
So I converted the array to a string and write it in text-file (it works but seems inconvenient)
to save the array
file.puts double_checker.to_s
# Output: String
"[1, 2, 3]"
to load the array (load string from text file, delete special chars, convert it back to array, convert elements to integers)
# Converts String back to Array, digits convert to Integers
double_checker = double_checker.delete(" []").split(",").map { |s| s.to_i }
# Output: Array
[1, 2, 3]
Now my question: Is there a way to store the array directly into to text file (in one line) and read it the same way, so I can store the array straight into a variable?
Or is it only possible to store Strings into a text file?
I'm trying to figure out how I can use write/read to save and load files for example a game progress.
One option would is to use Marshal::dump and Marshal::load.
player_1 = "name"
array = [1, 2, 3]
count = 1000
File.open("game.txt", 'wb') do |f|
f.write(Marshal.dump([player_1, array, count]))
end
#=> 28
player_1, array, count = Marshal.load(File.binread("game.txt"))
#=> ["name", [1, 2, 3], 1000]
Note that it is not guaranteed that an object serialized using dump with one version of Ruby will be readable with load with a later version of Ruby. On the other hand, Marshal can be used to serialize a wide range of Ruby objects.
"The marshaling library converts collections of Ruby objects into a byte stream", which is why Marshal's serialized objects should be written to and read from binary files.
Another option is to use JSON#generate and JSON#parse.
require 'json'
File.write("game.txt", JSON.generate([player_1, array, count]))
#=> 21
player_1, array, count = JSON.parse(File.read("game.txt"))
#=> ["name", [1, 2, 3], 1000]
One can alternatively use JSON::Ext::Generator::GeneratorMethods::Array#to_json to serialize the array:
player_1, array, count].to_json
#=> "[\"name\",[1,2,3],1000]"

Is it possible to save and access and search an array or list containing elements with different length in python?

Is it possible to save and access array or list containing elements with different length? For instance, I want to save data=[s,r,a,se] r,a are scalar but s and se are an arrays with 4 elements.(in python language)
For instance in one time:(s,r,a,se) are different in different times
s=[1,3,4,6] r=5 a=7 se=[11,12,13,14]
data=[s,r,a,se]=[[1,3,4,6],5,7,[11,12,13,14]]
How I can define the array containing them to be able to call them similar to the following code:
s=[data[0] for data in minibatch]
r=[data[1] for data in minibatch]
a=[data[2] for data in minibatch]
se=[data[3] for data in minibatch]
Also, how I can extract (Find) that is there a special[stest,rtest,atest,setest] in data (stest,setest are with 4 elements)
For instance: I want to see can I find [[1,2,3,4],5,6,[7,8,9,10]] in data which is something similar to: [ [[1,2,3,4],5,6,[7,8,9,10]] ,[[...,...,...,...],...,..., [...,...,...,...]], [[18,20,31,42],53,666,[27,48,91,120]]]
If I did not find I append to it otherwise nothing is happened!
You can add them in a new list:
new_list = [s, r, a, se]
But you'll have to be careful managing this list
# This is a great opportunity to explore dictionaries
# lets take the examples you have given in variales
s=[1,3,4,6]
r=5
a=7
se=[11,12,13,14]
# make a dictionary out of them, with keys which are
# the same as the variable name
my_dict = {'s':s,
'r':r,
'a':a,
'se':se}
# lets see what that looks like
print(my_dict)
print()
# to retrieve 2nd (=ix=1) element of s
# the format to do this is simple
# ditionary_variable_name['the string which is the key'][index_of_the_list]
s2 = my_dict['s'][1]
print(s2)
print()
# to retrieve all of se
se_retrieved = my_dict['se']
print(se_retrieved)
# you can further experiment with this
output of sample:
{'s': [1, 3, 4, 6], 'r': 5, 'a': 7, 'se': [11, 12, 13, 14]}
3
[11, 12, 13, 14]
In order to write to this, you need to do something like this:
my_dict['se'] = [15, 16, 17, 18]
or
my_dict['se'][2] = 19

Save integers into array given by first integer

I need to know, how to save integers from stdin into array, given by first integer in line... Ehm... hope you understand. I will give you an example.
On stdin I have:
0 : [ 1, 2, 3 ]
5 : [ 10, 11, 12, 13]
6 : [ 2, 4, 9 ]
0 : [ 4, 9, 8 ]
5 : [ 9, 6, 7 ]
5 : [ 1 ]
And I need save these integers to the arrays like this:
0={1, 2, 3, 4, 9, 8}
5={10, 11, 12, 13, 9, 6, 7, 1}
6={2, 4, 9}
I absolutely don't how to do it. There is a problem, that the number of arrays(in this case - 0, 5, 6 - so 3 arrays ) can be very high and I need to work effectively with memory...So I guess i will need something like malloc and free to solve this problem, or am I wrong? The names of arrays (0, 5, 6) can be changed. Number of integers in brackets has no maximum limit.
Thank you for any help.
I go with the assumption, this is homework, and I go with the assumption, this isn't your first homework to do, so I won't present you a solution but instead some tips that would help you to solve it yourself.
Given the input line
5 : [ 10, 11, 12, 13]
I will call "5" the "array name" and 10, 11, 12 and 13 the values to add.
You should implement some system to map array names to indices. A trivial approach would be like this:
.
size_t num_arrays;
size_t * array_names;
Here, in your example input, num_arrays will end up being 3 with array_names[3] = { 0, 5, 6}. If you find a new array name, realloc and add the new array name. Also you need the actual arrays for the values:
int * * array;
you need to realloc array for each new array name (like you realloc array_names). array[0] will represent array array_names[0] here array 0, array[1] will represent array array_names[1] here array 5 and array[2] will represent array array_names[2] here array 6.
To access an array, find it's index like so:
size_t index;
for (size_t index = 0; index < num_arrays && array_names[index] != search; ++index) ;
The second step is easy. Once you figured out, you need to use array[index] to add elemens, realloc that one (array[index] = realloc(array[index], new size)) and add elements there array[index][i+old_size] = new_value[i].
Obviously, you need to keep track of the number of elements in your separate arrays as well ;)
Hint: If searching for the array names take too long, you will have to replace that trivial mapping part by some more sophisticated data structure, like a hash map or a binary search tree. The rest of the concept may stay more or less the same.
Should you have problems to parse the input lines, I suggest, you open a new question specific on this parsing part.
In algorithmic terms, you need map (associative array) from ints to arrays. This is solved long ago in most higher level languages.
If you have to implement it manually, you have a few options:
simple "master" array where you store your 0, 5, 6, 1000000 and then map them to indices 0, 1, 2, 3 by doing search in for each time you have to access it (it's too time consuming when ;
hash table: write simple hash function to map 0, 5, 6, 1000000 (they're called keys) to values less than 1000, allocate array of 1000 elements and then make "master" array structures for each hash function result;
some kind of tree (e.g. red-black tree), may be a bit complex to implement manually.
Last two structures are part of programming classic and are well described in various articles and books.

How to delete an element from an array based off the user input in Ruby?

I'm not sure where I'm going wrong with this. I have an array and the user is prompted with a question about what number should be deleted from the array. The number is stored and the result is a new array that gets outputted with the deleted value.
def delete(number)
a = [1, 2, 1, 3, 1, 4, 2, 5]
puts "Please type number to be deleted?"
number = gets
result= a.delete(number)
puts result
end
a.delete(number)
maybe do something like this ?
def delete(num,array)
array.reject { |el| el == num }
puts array
end
a = [1, 2, 1, 3, 1, 4, 2, 5]
puts "Please type number to be deleted? from array #{a}"
number = gets
delete(number.to_i,a)
Why Your Code Doesn't Work
In general, Kernel#gets returns a String with a trailing newline. Therefore, Array#delete has no matching elements.
A Working Alternative
You need to convert your input to an Integer for the #gets method. It's also useful to return a value from your method. The following works, and also serves to validate the user's input:
require 'pp'
def delete_from_array array
print 'Number to be deleted: '
array.delete Integer(gets)
pp array
end
array = [1, 2, 1, 3, 1, 4, 2, 5]
delete_from_array array.dup
Note that #delete will modify the original array, rather than returning a copy. In most cases, you will probably want to use #dup to ensure that you aren't modifying your original array. On the other hand, if you want the side-effects, then just elide the call to #dup when passing the array as an argument.

How to pick elements in fixed interval in an array (python)

Given array=[1, 2, 3, 4, 5, 6]
I want to choose the 0-th 2-nd, 4-th index value to build a new array
array1=[1, 3, 5]
Could someone show me how to do using python? Thanks~
If it is just 0, 2, and 4, you can use operator.itemgetter():
from operator import itemgetter
array1 = itemgetter(0, 2, 4)(array)
That will be a tuple. If it must be a list, convert it:
array1 = list(itemgetter(0, 2, 4)(array))
If the point is to get the even numbered indices, use slicing:
array1 = array[::2]
Whichever you are looking for, you could use a list comprehension:
array1 = [array[i] for i in (0, 2, 4)]
or
array1 = [array[i] for i in xrange(0, len(array), 2)]
You can try something like this. In python the nth term of a list has index (n-1). Suppose the first element you want is 2, which happens to be the element 1 of array. Just save the first element index in a variable. Append it to the new list array1 and increase the index by 2. Continue doing this until the list array is exhausted.
from numpy import*
array=[1,2,3,4,5,6]
array1=[]
term=1
while term<len(array): # if the array length is 6 then it will have upto element 5.
array1.append(array[term])
term=term+2 # 2 is the gap between elements. You can replace it with your required step size.

Resources