How to do something equivalent to this:
In: A = [ 1 2 3 ]
In: B = 2 * A
In: B
Out: [ 2 4 6 ]
This method gets part of the way:
In: do for [i in "1 2 3"] { print 2*i }
Out:
2
4
6
But I want to return another list/array that can be used in further operations.
As you already found out, using space-delimited words is the only way to simulate arrays. So you must format the output again as a string in which the single entries are separated by spaces:
out = ''
do for [i in "1 2 3"] {
out = out . sprintf('%d ', 2*i)
}
print sprintf('%d entries: %s', words(out), out)
This prints
3 entries: 2 4 6
If using floats, you must use e.g. '%f' to format the output:
out = ''
do for [i in "1.1 2.2 3.3"] {
out = out . sprintf('%f ', 2*i)
}
print sprintf('%d entries: %s', words(out), out)
words counts the words in a string, and you can use word to extract a certain word from the string (starting from 1):
print word(out, 2)
4
Related
The first line contains an integer N, (the size of our array).
The second line contains N space-separated integers describing array's(A's) elements.
I have tried the following, however I looked at the solution page. However I do not understand how this code works. Can someone please explain it to me. I am pretty new in this coding world.
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input())
arr = [int(arr_one) for arr_one in input().strip().split(' ')]
for i in range(len(arr)):
print(str(arr[-i-1]), end = " ")
input 1234
output 4 3 2 1
In Python3:
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().rstrip().split()))
print(" ".join(str(x) for x in arr[::-1]))
Input:
1 4 3 2
Output:
2 3 4 1
You are creating a list of integer values, by removing spaces and splitting the values at ' '. After obtaining the list of integers, you are iterating over the list and converting the ith element from the back (a negative value of index denotes element with ith index from right and it is 1 based) of arr back to string and printing the number.
Example:
arr = [1,2,3,4]
print(arr[1]) #prints 2 on the console, i.e 2nd element from the left.
print(arr[-1]) #prints 4 on the console, i.e 1st element from the right.
Let's take this code snippet
n = int(input())
arr = [int(arr_one) for arr_one in input().strip().split(' ')]
for i in range(len(arr)):
print(str(arr[-i-1]), end = " ")
The method input() will take the user input from key board. int(input()) will convert the input into int, if the input is in string format. like "4" instead of 4. The input value stored into variable n.
The Array input will be like this "1 2 3 4". So, we need to separate the string with space delimiter.
The strip() method returns a copy of the string with both leading and trailing characters removed.
The split() method returns a list of strings after breaking the given string by the specified separator.Here the separator is space. So, split(' ')
input().strip().split(' ') will take "1 2 3 4" as input and the output is "1" "2" "3" "4".
Now we need to take each element after separated. And then covert into int and store into array.
arr = [int(arr_one) for arr_one in input().strip().split(' ')]
arr_one is a variable, this variable stores each element after split. For each element, we converted it into int and then storing into a array arr.
In python, array index start from 0. If we want to access from last index in the array, the index will start from -1, -2, -3, and so on.
for i in range(len(arr)): The for loop will iterate from index 0 to length of the array. in this example, size is 4.
printing array elements from index -1. and the end argument is used to end the print statement with given character, here the end character is " ". So the output will be 4 3 2 1.
The above code can be rewritten as below with more readability.
if __name__ == '__main__':
n = int(input())
inp = input("Enter the numbers seperated by spaces:::")
inp = inp.strip() # To remove the leading and trailing spaces
array = []
for item in inp.split(' '): # Splitting the input with space and iterating over each element
array.append(int(item)) # converting the element into integer and appending it to the list
print(array[::-1]) # here -1 says to display the items in the reverse order. Look into list comprehension for more details
For more details on list slicing, look in the python documentation.
Try this!
if __name__ == '__main__':
n = int(input()) # input as int from stream
arr = [int(arr_one) for arr_one in input().strip().split(' ')]
"""
1. asking for input from user
2. strip() function removes leading and trailing characters.
3. split(' ') function split your input on space into list of characters
4. arr_one variable contains yours splited character and your iterating over it using for loop
5. int(arr_one) converts it into integer and [] is nothing just storing everything into another list.
6. In last you are assigning new list to arr variable
"""
for i in reversed(arr): # loop over list in reverse order with built in fucntion
print(i, end = " ") # printing whatever comes in i
It should work like this:
3 # your n
1 2 3 # your input
3 2 1 # output
This question already has an answer here:
Create multiple arrays in one line
(1 answer)
Closed 4 years ago.
I'm trying to get the method input to be stored and outputted like this:
Want [ ["email addresses"], ["phone numbers"], ["names"] ] - > [["bobsmith#example.com","sallyfield#example.com"],["555-555-5555","111-111-1111"],["Bob Smith","Sally Field"]]
This is my code:
def hash_2_array contacts
2 # Extract like info from each hash into arrays
3 stringArr = Array.new(3,Array.new(2)) #=> [ [ nil,nil] , [nil,nil] , [nil,nil] ]
4
5 if contacts.empty?
6 return nonsense = Array.new(3, Array.new)
7 else
8 n=0 #name counter
9 e=0 #email counter
10 p=0 #phone counter
11 contacts.each do |key, value|
12 stringArr[2][n] = key.to_s #adds name to array
13 n+=1
14 value.each do |key2, value2|
15 if key2.to_s.eql?("email")
16 stringArr[0][e] = value2.to_s #adds email address to array
17 e+=1
18 else
19 stringArr[1][p] = value2.to_s #adds phone number to array
20 p+=1
21 end
22 end
23 end
24 end
25 return stringArr
26 end
27
28
29 hash_2_array({:"Bob Smith"=>{:email=>"bobsmith#example.com", :phone=>"555-555-5555"}, :"Sally Field"=>{:email=>"sallyfield#example.com", :phone=>"111-111-1111"}})
It returns:
got: [["555-555-5555", "111-111-1111"], ["555-555-5555", "111-111-1111"], ["555-555-5555", "111-111-1111"]]
It's really confusing why it's not just assigning only the the index in the array that I'm specifying. I think this code worked before, but now it's broken somehow. Any help would be great
From the fine manual:
new(size=0, default=nil)
new(array)
new(size) {|index| block }
[...]
Common gotchas
When sending the second parameter, the same object will be used as the value for all the array elements:
a = Array.new(2, Hash.new)
# => [{}, {}]
a[0]['cat'] = 'feline'
a # => [{"cat"=>"feline"}, {"cat"=>"feline"}]
a[1]['cat'] = 'Felix'
a # => [{"cat"=>"Felix"}, {"cat"=>"Felix"}]
If multiple copies are what you want, you should use the block version which uses the result of that block each time an element of the array needs to be initialized:
a = Array.new(2) { Hash.new }
a[0]['cat'] = 'feline'
a # => [{"cat"=>"feline"}, {}]
When you say this:
stringArr = Array.new(3,Array.new(2))
You're creating an array with three elements but all those elements are exactly the same array. You want an array that contains three different arrays as elements:
stringArr = Array.new(3) { Array.new(2) }
Ok lets say I have a list which generates values randomly and sometimes it generates the same value twice.
For example generated int value:
1, 1, 2, 3, 4
Then I have a method called duplicateTracker() and its job is to find duplicates within the list.
I have an idea that it should be done using if else statements. So if it detects duplicate numbers its then true, else false.
How do I do this?
This makes use of Foundation methods but given your use case, you might want to consider making us of an NSCountedSet to keep track of your generated numbers. E.g.
let numbersGenerator = AnyIterator { return 1 + arc4random_uniform(10) }
var numbersBag = NSCountedSet()
for num in (0...15).flatMap({ _ in numbersGenerator.next()}) {
print(num, terminator: " ")
numbersBag.add(num)
} /* 1 3 2 2 10 1 10 7 10 6 8 3 8 10 7 4 */
print()
numbersBag.forEach { print($0, numbersBag.count(for: $0)) }
/* 1 2
2 2
3 2
4 1
6 1
7 2
8 2
10 4 */
Since NSCountedSet conforms to Sequence, you can easily extract any "duplicate diagnostics" that you wish using e.g. filter:
print("Numbers with duplicates: ", numbersBag.filter { numbersBag.count(for: $0) > 1 })
// Numbers with duplicates: [1, 2, 3, 7, 8, 10]
Given this function:
func checkForDups(_ arr1:[Int], _ arr2:[Int]) -> Bool {
let arrChecked = Set(arr1).subtracting(Set(arr2))
if Set(arr1).count != arrChecked.count {
return true
}
return false
}
Here's code that works:
let arr1:[Int] = [1,1,2,3,4,5]
let arr2:[Int] = [1,10,20]
let arr3:[Int] = [10,20,30]
print(checkForDups(arr1, arr2)) // prints true
print(checkForDups(arr1, arr3)) // prints false
I have an array:
animals = [
["cats", "dogs"],
["verrylongcat", "dog"],
["shortcat", "verrylongdog"],
["cat", "dog"]
]
And I would like to display it nicely. Is there an easy way to make the colums a fixed width so I get something like this:
cats dogs
verrylongcat dog
shortcat verrylongdog
cat dog
animals is just an example, my array could also have 3, or 4 columns or even more.
You are looking for String#ljust:
max_cat_size = animals.map(&:first).max_by(&:size).size
animals.each do |cat, dog|
puts "#{cat.ljust(max_cat_size)} #{dog}"
end
If you want more than one space just add the corresponding amount in the interpolation.
Assuming your array is n × m and not 2 × m:
animal_max_sizes = animals.first.size.times.map do |index|
animals.transpose[index].map(&:to_s).max_by(&:size).size
end
animals.map do |animal_line|
animal_line.each.with_index.reduce('') do |animal_line, (animal, index)|
animal_line + animal.to_s.ljust(animal_max_sizes[index].next)
end
end.each { |animal_line_stringified| puts animal_line_stringified }
Note: The to_ses are used in case your arrays contain nils, numbers, etc.
Another way to do this is with printf-style formatting. If you know you will always have exactly 2 words in each line then you can do this:
#!/usr/bin/env ruby
lines = [
' cats dogs',
' verrylongcat dog',
'shortcat verrylongdog ',
' cat dog ',
]
lines.map(&:strip).each do |line|
puts "%-14s%s" % line.split
end
Outputs:
cats dogs
verrylongcat dog
shortcat verrylongdog
cat dog
If you need to calculate the column width based on the data, then you'd have to do a little more work:
# as #ndn showed:
first_col_width = lines.map(&:split).map(&:first).max_by(&:size).size + 2
lines.map(&:strip).each do |line|
puts "%-#{first_col_width}s%s" % line.split
end
Here's another attempt for a variable numbers of columns. Given this array:
animals = [
['Cats', 'Dogs', 'Fish'],
['Mr. Tinkles', 'Buddy', 'Nemo'],
['Calico', 'Butch', 'Marlin'],
['Ginger', 'Ivy', 'Dory']
]
We can calculate the width of each column via transpose, map, length and max:
widths = animals.transpose.map { |x| x.map(&:length).max }
#=> [11, 5, 6]
Based on this, we can generate a format string that can be passed to sprintf (or its shortcut %):
row_format = widths.map { |w| "%-#{w}s" }.join(' ')
#=> "%-11s %-5s %-6s"
%s denotes a string argument, 11, 5 and 6 are our widths and - left-justifies the result.
Let's try it:
row_format % animals[0] #=> "Cats Dogs Fish "
row_format % animals[1] #=> "Mr. Tinkles Buddy Nemo "
row_format % animals[2] #=> "Calico Butch Marlin"
That looks good, we should use a loop and wrap everything it in a method:
def print_table(array)
widths = array.transpose.map { |x| x.map(&:length).max }
row_format = widths.map { |w| "%-#{w}s" }.join(' ')
array.each do |row_values|
puts row_format % row_values
end
end
print_table(animals)
Output:
Cats Dogs Fish
Mr. Tinkles Buddy Nemo
Calico Butch Marlin
Ginger Ivy Dory
More complex formatting
With a little tweaking, you can also output a MySQL style table:
def print_mysql_table(array)
widths = array.transpose.map { |x| x.map(&:length).max }
row_format = '|%s|' % widths.map { |w| " %-#{w}s " }.join('|')
separator = '+%s+' % widths.map { |w| '-' * (w+2) }.join('+')
header, *rows = array
puts separator
puts row_format % header
puts separator
rows.each do |row_values|
puts row_format % row_values
end
puts separator
end
print_mysql_table(animals)
Output:
+-------------+-------+--------+
| Cats | Dogs | Fish |
+-------------+-------+--------+
| Mr. Tinkles | Buddy | Nemo |
| Calico | Butch | Marlin |
| Ginger | Ivy | Dory |
+-------------+-------+--------+
I wrote a method that takes an array of numbers, adds the number 2 to it, and then returns an array of strings.
def add_two(array)
new_array = array.map{|x| "#{x} + 2 = #{x + 2}"}
new_array.to_s
end
The following is a test result:
I have an unwanted \ in my return. I am trying to figure out where the \ is coming from. Can someone point me in the right direction?
It is coming from to_s that you have at the end. You are converting an array of strings (which is presumably already what you want) into a single string that contains double quotations (which must be escaped by \). To fix it, just remove your line with to_s.
Its not adding extra \s. \ is escape character to escape " which is part of the result String. Here:
a = add_two(array)
# => "[\"1 + 2 = 3\", \"2 + 2 = 4\", \"3 + 2 = 5\"]"
puts a
# ["1 + 2 = 3", "2 + 2 = 4", "3 + 2 = 5"]
or directly:
puts add_two(array)
# ["1 + 2 = 3", "2 + 2 = 4", "3 + 2 = 5"]